@sleep2agi/commhub-server 0.9.0-preview.26 → 0.9.0-preview.260

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 (429) hide show
  1. package/README.md +120 -3
  2. package/bin/commhub.ts +93 -9
  3. package/build-info.json +7 -0
  4. package/package.json +10 -8
  5. package/src/ack-create-request-transport.test.ts +182 -0
  6. package/src/ack-create-request.test.ts +52 -8
  7. package/src/admin-delete-network-http.test.ts +228 -0
  8. package/src/admin-networks-http.test.ts +88 -0
  9. package/src/adoption-candidates-http.test.ts +140 -0
  10. package/src/adoption-candidates.ts +158 -0
  11. package/src/agent-access-batch.test.ts +210 -0
  12. package/src/agent-access.ts +487 -0
  13. package/src/agent-acl-groups-http.test.ts +247 -0
  14. package/src/agent-acl-http.test.ts +680 -0
  15. package/src/agent-acl-slice3-http.test.ts +885 -0
  16. package/src/agent-department-http.test.ts +215 -0
  17. package/src/agent-groups-perf.test.ts +223 -0
  18. package/src/agent-notice.ts +48 -0
  19. package/src/agent-team-whoami-http.test.ts +98 -0
  20. package/src/agent-teams-http.test.ts +330 -0
  21. package/src/agent-teams.ts +244 -0
  22. package/src/alias-baseline-2571.test.ts +162 -0
  23. package/src/alias-baseline.ts +113 -0
  24. package/src/alias-filter.test.ts +72 -0
  25. package/src/alias-filter.ts +42 -0
  26. package/src/api-host-supervisors-can-create-nodes.test.ts +350 -0
  27. package/src/api-host-supervisors-fallback.test.ts +6 -7
  28. package/src/api-host-supervisors-runtime-readiness.test.ts +195 -0
  29. package/src/api-nodes-shape.test.ts +131 -4
  30. package/src/auth-abuse-counters.test.ts +125 -0
  31. package/src/auth-abuse-counters.ts +122 -0
  32. package/src/auth-password-change-cli-tokens-http.test.ts +423 -0
  33. package/src/auth-sessions-http.test.ts +260 -0
  34. package/src/auth-validate.test.ts +5 -1
  35. package/src/auth-weak-password-login.test.ts +176 -0
  36. package/src/auth.ts +609 -56
  37. package/src/backfill-node-ids-2664.test.ts +128 -0
  38. package/src/binding-generation-http.test.ts +141 -0
  39. package/src/blocked-exit-on-reply.test.ts +122 -0
  40. package/src/broadcast-fanout-2721.test.ts +149 -0
  41. package/src/broadcast-fanout.ts +117 -0
  42. package/src/build-commit-report-http.test.ts +128 -0
  43. package/src/build-info.test.ts +60 -0
  44. package/src/build-info.ts +85 -0
  45. package/src/chain-attempt-dedup.test.ts +447 -0
  46. package/src/clip.test.ts +36 -0
  47. package/src/clip.ts +48 -0
  48. package/src/clone-node.test.ts +269 -0
  49. package/src/clone-node.ts +289 -0
  50. package/src/codex-config-flags.ts +77 -0
  51. package/src/codex-fork-contract.ts +23 -0
  52. package/src/codex-fork-migration.test.ts +38 -0
  53. package/src/commhub-bin-args.test.ts +85 -0
  54. package/src/config-apply-validate.test.ts +188 -1
  55. package/src/config-apply-validate.ts +222 -3
  56. package/src/cors-origins.test.ts +73 -0
  57. package/src/create-node-blocked-gate.test.ts +365 -0
  58. package/src/create-node-error-domain.test.ts +124 -0
  59. package/src/create-node-network-id.test.ts +91 -0
  60. package/src/create-node-tool-schema.test.ts +49 -0
  61. package/src/create-node-unicode-name.test.ts +126 -0
  62. package/src/create-node-validate.test.ts +199 -7
  63. package/src/create-node-validate.ts +232 -15
  64. package/src/create-node-workdir.test.ts +298 -0
  65. package/src/create-node.ts +88 -23
  66. package/src/daemon-provider-snapshots.test.ts +453 -0
  67. package/src/daemon-provider-snapshots.ts +327 -0
  68. package/src/daemon-token-owner-http.test.ts +346 -0
  69. package/src/dashboard-slash-routing-http.test.ts +109 -0
  70. package/src/db-adapter-guard.test.ts +148 -0
  71. package/src/db-adapter-translate.test.ts +128 -0
  72. package/src/db-adapter.ts +377 -91
  73. package/src/db-timestamp.test.ts +38 -0
  74. package/src/db-timestamp.ts +15 -0
  75. package/src/db.ts +1269 -153
  76. package/src/delivered-without-push.test.ts +140 -0
  77. package/src/department-groups-http.test.ts +209 -0
  78. package/src/department-groups-sync-http.test.ts +328 -0
  79. package/src/department-groups.ts +434 -0
  80. package/src/department-heads-http.test.ts +350 -0
  81. package/src/department-heads.ts +226 -0
  82. package/src/departments-agent-count.test.ts +139 -0
  83. package/src/departments-http.test.ts +185 -0
  84. package/src/departments-mcp-error-domain.test.ts +135 -0
  85. package/src/departments-mcp.test.ts +128 -0
  86. package/src/departments.ts +318 -0
  87. package/src/desktop-message-seam.test.ts +150 -0
  88. package/src/desktop-message.test.ts +368 -0
  89. package/src/dm-file-scope-http.test.ts +178 -0
  90. package/src/empty-node-sweeper.test.ts +104 -0
  91. package/src/empty-node-sweeper.ts +88 -0
  92. package/src/env-transport-gate-http.test.ts +240 -0
  93. package/src/env-transport-gate.ts +80 -0
  94. package/src/env-transport-policy.ts +56 -0
  95. package/src/etag-of.test.ts +57 -0
  96. package/src/event-loop-lag.test.ts +180 -0
  97. package/src/event-loop-lag.ts +201 -0
  98. package/src/expiry-counters.test.ts +187 -0
  99. package/src/expiry-counters.ts +227 -0
  100. package/src/expiry-evidence-db.test.ts +103 -0
  101. package/src/ext-token-shared.test.ts +60 -0
  102. package/src/ext-validation-regression.test.ts +10 -17
  103. package/src/external-schedule-edits-http.test.ts +321 -0
  104. package/src/external-schedule-edits-timestamps.test.ts +64 -0
  105. package/src/external-schedule-edits.ts +327 -0
  106. package/src/file-download-authz-dev-open.test.ts +1 -1
  107. package/src/file-download-authz.test.ts +25 -4
  108. package/src/file-download-date-bucket.test.ts +1 -1
  109. package/src/file-network-scope-dev-open.test.ts +1 -1
  110. package/src/file-network-scope.test.ts +7 -6
  111. package/src/group-membership-events-http.test.ts +264 -0
  112. package/src/group-messages-http.test.ts +483 -0
  113. package/src/group-messages.ts +297 -0
  114. package/src/health-anon-readers.ts +67 -0
  115. package/src/health-host-disk-2756.test.ts +71 -0
  116. package/src/health-redaction.test.ts +1576 -7
  117. package/src/host-supervisor-identity-http.test.ts +152 -0
  118. package/src/host-supervisor-identity.ts +92 -0
  119. package/src/host-supervisors-daemon-version.test.ts +137 -0
  120. package/src/http-gzip.test.ts +94 -0
  121. package/src/http-gzip.ts +112 -0
  122. package/src/hub-catalog-read-http.test.ts +641 -0
  123. package/src/hub-provider-config.test.ts +166 -0
  124. package/src/hub-provider-config.ts +202 -0
  125. package/src/hub-timestamp.test.ts +38 -0
  126. package/src/hub-timestamp.ts +27 -0
  127. package/src/human-dm.ts +215 -0
  128. package/src/human-inbox.ts +42 -0
  129. package/src/inbox-caller.ts +49 -0
  130. package/src/inbox-count-sse.test.ts +318 -0
  131. package/src/inbox-count.ts +29 -0
  132. package/src/index.ts +6 -2
  133. package/src/license-state.test.ts +56 -0
  134. package/src/license-state.ts +48 -0
  135. package/src/lifecycle-error-domain.test.ts +109 -0
  136. package/src/list-ack-error-domain.test.ts +108 -0
  137. package/src/list-host-supervisors.test.ts +15 -4
  138. package/src/mcp-context-cost-http.test.ts +127 -0
  139. package/src/mcp-inflight.test.ts +92 -0
  140. package/src/mcp-inflight.ts +38 -0
  141. package/src/mcp-projects-events-http.test.ts +168 -0
  142. package/src/mcp-route-label-http.test.ts +120 -0
  143. package/src/mcp-write-network-resolution.test.ts +21 -0
  144. package/src/member-audit-network-id-http.test.ts +93 -0
  145. package/src/member-presence-http.test.ts +210 -0
  146. package/src/messages-ack-by-agent-http.test.ts +142 -0
  147. package/src/migrate-sqlite-to-pg.test.ts +47 -0
  148. package/src/migrate-sqlite-to-pg.ts +263 -0
  149. package/src/model-auth-notify-http.test.ts +181 -0
  150. package/src/model-auth-notify.ts +116 -0
  151. package/src/network-name-http.test.ts +75 -0
  152. package/src/network-rules-http.test.ts +169 -0
  153. package/src/network-rules.ts +129 -0
  154. package/src/network-scope.ts +222 -3
  155. package/src/network-token-membership-http.test.ts +186 -0
  156. package/src/node-alias-control.ts +12 -0
  157. package/src/node-attrs.test.ts +47 -2
  158. package/src/node-caller-identity-http.test.ts +1108 -0
  159. package/src/node-create-request-status-http.test.ts +105 -0
  160. package/src/node-daemon-bindings.test.ts +142 -0
  161. package/src/node-daemon-bindings.ts +135 -0
  162. package/src/node-failure-alert.test.ts +150 -0
  163. package/src/node-failure-alert.ts +177 -0
  164. package/src/node-files-transport.test.ts +350 -0
  165. package/src/node-health-codex-login.test.ts +120 -0
  166. package/src/node-health-dispatch-http.test.ts +373 -0
  167. package/src/node-health-guard.ts +121 -0
  168. package/src/node-health-passthrough.test.ts +115 -0
  169. package/src/node-health-store.ts +101 -0
  170. package/src/node-id-alias.test.ts +190 -0
  171. package/src/node-identity-conflict-http.test.ts +269 -0
  172. package/src/node-identity-conflict.ts +142 -0
  173. package/src/node-identity-mismatch.test.ts +74 -0
  174. package/src/node-in-flight-tasks.ts +31 -0
  175. package/src/node-lifecycle-controllable.test.ts +64 -0
  176. package/src/node-lifecycle-controllable.ts +53 -0
  177. package/src/node-lifecycle-read-http.test.ts +257 -0
  178. package/src/node-lifecycle-read.ts +124 -0
  179. package/src/node-logs-transport.test.ts +266 -0
  180. package/src/node-peer-allowlist.test.ts +114 -0
  181. package/src/node-permissions-http.test.ts +728 -0
  182. package/src/node-permissions.ts +494 -0
  183. package/src/node-request-retention.test.ts +281 -0
  184. package/src/node-request-retention.ts +120 -0
  185. package/src/node-secret-rest-http.test.ts +190 -0
  186. package/src/node-security-write-gate.test.ts +72 -0
  187. package/src/node-serviceability.test.ts +86 -0
  188. package/src/node-serviceability.ts +124 -0
  189. package/src/node-session-control-http.test.ts +310 -0
  190. package/src/node-session-control.ts +258 -0
  191. package/src/node-skills-transport.test.ts +212 -0
  192. package/src/node-token-identity.ts +35 -0
  193. package/src/node-token-ownership.ts +51 -0
  194. package/src/node-token-privilege-http.test.ts +158 -0
  195. package/src/not-found-api-http.test.ts +67 -0
  196. package/src/observer-avatar-http.test.ts +103 -10
  197. package/src/observer-push.test.ts +76 -0
  198. package/src/opencode-catalog-report-http.test.ts +139 -0
  199. package/src/opencode-v2-catalog.test.ts +268 -0
  200. package/src/opencode-v2-catalog.ts +356 -0
  201. package/src/package-version-consistency.test.ts +25 -0
  202. package/src/parent-source-marker.test.ts +50 -0
  203. package/src/password-network-tokens.ts +25 -0
  204. package/src/peer-reply-atomic.test.ts +462 -0
  205. package/src/peer-reply-capability.test.ts +70 -0
  206. package/src/pg-worker.ts +87 -0
  207. package/src/poll-pacing.test.ts +74 -0
  208. package/src/poll-pacing.ts +123 -0
  209. package/src/probe-provider-error-domain.test.ts +141 -0
  210. package/src/project-dir-warn-clear-http.test.ts +132 -0
  211. package/src/project-viewer-can-http.test.ts +116 -0
  212. package/src/provider-skill-error-domain.test.ts +130 -0
  213. package/src/provider-tools-shape.test.ts +165 -0
  214. package/src/push.test.ts +20 -10
  215. package/src/push.ts +373 -9
  216. package/src/redact-tokens.test.ts +86 -0
  217. package/src/redact-tokens.ts +43 -0
  218. package/src/rejection-counters.test.ts +72 -0
  219. package/src/rejection-counters.ts +173 -0
  220. package/src/rename.ts +38 -10
  221. package/src/reply-target-derivation.test.ts +96 -0
  222. package/src/report-status-handover-capabilities-http.test.ts +124 -0
  223. package/src/report-status-host-schema.test.ts +235 -0
  224. package/src/report-status-resume-id-handover.test.ts +184 -0
  225. package/src/report-status-secret-keys.test.ts +140 -0
  226. package/src/require-explicit-test-db.ts +9 -0
  227. package/src/requirement-due-reminders-http.test.ts +620 -0
  228. package/src/requirement-due-reminders.ts +416 -0
  229. package/src/requirement-events-http.test.ts +318 -0
  230. package/src/requirement-events.test.ts +45 -0
  231. package/src/requirement-events.ts +144 -0
  232. package/src/requirement-notify.ts +165 -0
  233. package/src/requirement-participant-notify-http.test.ts +313 -0
  234. package/src/requirement-tag-ops-http.test.ts +454 -0
  235. package/src/requirement-tag-tree-http.test.ts +275 -0
  236. package/src/requirement-tag-tree.ts +127 -0
  237. package/src/requirement-tags.ts +102 -0
  238. package/src/requirements-abandoned-http.test.ts +236 -0
  239. package/src/requirements-assignee-drift.test.ts +154 -0
  240. package/src/requirements-comment-http.test.ts +174 -0
  241. package/src/requirements-completed-at-migration.test.ts +70 -0
  242. package/src/requirements-errors-mcp-http.test.ts +164 -0
  243. package/src/requirements-errors.ts +158 -0
  244. package/src/requirements-etag-http.test.ts +91 -0
  245. package/src/requirements-http.test.ts +709 -0
  246. package/src/requirements-last-event-http.test.ts +349 -0
  247. package/src/requirements-list-mcp-slim-http.test.ts +155 -0
  248. package/src/requirements-list-slim-http.test.ts +324 -0
  249. package/src/requirements-mcp.test.ts +180 -0
  250. package/src/requirements-migrate.ts +283 -0
  251. package/src/requirements-owner-strict-mcp-http.test.ts +145 -0
  252. package/src/requirements-people-http.test.ts +114 -0
  253. package/src/requirements-people-mcp-http.test.ts +231 -0
  254. package/src/requirements-people.ts +196 -0
  255. package/src/requirements-priority-lowest.test.ts +114 -0
  256. package/src/requirements-projects-network-echo.test.ts +57 -0
  257. package/src/requirements-projects-parent-http.test.ts +123 -0
  258. package/src/requirements-search-http.test.ts +182 -0
  259. package/src/requirements-search.test.ts +32 -0
  260. package/src/requirements-search.ts +145 -0
  261. package/src/requirements-seq-http.test.ts +193 -0
  262. package/src/requirements-seq-migration.test.ts +63 -0
  263. package/src/requirements-start-date.test.ts +125 -0
  264. package/src/requirements-stats-http.test.ts +357 -0
  265. package/src/requirements-stats.ts +195 -0
  266. package/src/requirements-status-participants-http.test.ts +222 -0
  267. package/src/requirements-upgrade-e2e.test.ts +126 -0
  268. package/src/requirements-upgrade-migration.test.ts +98 -0
  269. package/src/requirements.ts +2205 -0
  270. package/src/resolve-port.test.ts +57 -0
  271. package/src/resolve-port.ts +44 -0
  272. package/src/rest-alias-network-fallback-http.test.ts +123 -0
  273. package/src/rest-alias-network-fallback.test.ts +60 -0
  274. package/src/rest-alias-network-fallback.ts +65 -0
  275. package/src/rest-explicit-columns-http.test.ts +266 -0
  276. package/src/rest-identity.test.ts +130 -0
  277. package/src/rest-identity.ts +141 -0
  278. package/src/rest-projections.ts +72 -0
  279. package/src/rest-read-network-real-chain.test.ts +97 -0
  280. package/src/rest-write-network-resolution.test.ts +133 -0
  281. package/src/restart-readiness-http.test.ts +121 -0
  282. package/src/restricted-files.ts +76 -0
  283. package/src/retention-first-sweep-quiet.test.ts +31 -0
  284. package/src/retention.test.ts +100 -40
  285. package/src/retention.ts +423 -104
  286. package/src/route-callers-http.test.ts +120 -0
  287. package/src/route-timing.test.ts +218 -0
  288. package/src/route-timing.ts +262 -0
  289. package/src/rules-file-duplicate-alias.test.ts +234 -0
  290. package/src/rules-file-session-target.test.ts +207 -0
  291. package/src/rules-file-transport.test.ts +271 -0
  292. package/src/runtime-label.test.ts +22 -0
  293. package/src/runtime-label.ts +21 -0
  294. package/src/runtime-readiness.ts +90 -0
  295. package/src/schedule-agent-mcp-http.test.ts +486 -0
  296. package/src/schedule-agent.ts +252 -0
  297. package/src/schedule-starved.test.ts +92 -0
  298. package/src/schedule-starved.ts +114 -0
  299. package/src/scheduled-backoff-http.test.ts +203 -0
  300. package/src/scheduled-backoff.ts +64 -0
  301. package/src/scheduled-doorbell-nodeless-session.test.ts +134 -0
  302. package/src/scheduled-failure-backoff-2622.test.ts +145 -0
  303. package/src/scheduled-failure-code.test.ts +73 -0
  304. package/src/scheduled-failure-code.ts +105 -0
  305. package/src/scheduled-failures-http.test.ts +279 -0
  306. package/src/scheduled-failures.ts +425 -0
  307. package/src/scheduled-noprogress-backoff-2622.test.ts +163 -0
  308. package/src/scheduled-offline-backoff-probe.test.ts +56 -0
  309. package/src/scheduled-offline.test.ts +131 -0
  310. package/src/scheduled-offline.ts +66 -0
  311. package/src/scheduled-outcome-guidance-http.test.ts +139 -0
  312. package/src/scheduled-outcome-guidance.ts +9 -0
  313. package/src/scheduled-reply-unread-http.test.ts +212 -0
  314. package/src/scheduled-requirement-wake-http.test.ts +289 -0
  315. package/src/scheduled-requirement-wake.ts +125 -0
  316. package/src/scheduled-run-terminal.test.ts +290 -0
  317. package/src/scheduled-skip-blocking-task.test.ts +120 -0
  318. package/src/scheduled-skip-path-backoff-2622.test.ts +98 -0
  319. package/src/scheduled-stuck-http.test.ts +316 -0
  320. package/src/scheduled-stuck-notice-cap.test.ts +80 -0
  321. package/src/scheduled-stuck.ts +219 -0
  322. package/src/scheduled-tasks-http.test.ts +679 -0
  323. package/src/scheduled-tasks.ts +959 -0
  324. package/src/scheduled-work-outcome-http.test.ts +154 -0
  325. package/src/scheduled-work-outcome.ts +50 -0
  326. package/src/scoped-secrets.ts +141 -0
  327. package/src/secret-echo-negative-control.test.ts +118 -0
  328. package/src/send-dedup-request-id.test.ts +229 -0
  329. package/src/send-reply-agent-warning.test.ts +38 -38
  330. package/src/send-reply-alias-optional.test.ts +131 -0
  331. package/src/send-reply-attachments.test.ts +28 -7
  332. package/src/send_dedup.test.ts +54 -0
  333. package/src/send_dedup.ts +52 -6
  334. package/src/serve-error.test.ts +73 -0
  335. package/src/serve-error.ts +56 -0
  336. package/src/server.ts +4842 -325
  337. package/src/session-task-on-dispatch.ts +14 -0
  338. package/src/session-token-ownership-http.test.ts +122 -0
  339. package/src/shared/codex-inventory.ts +41 -0
  340. package/src/shared/daemon-provider-login.ts +31 -0
  341. package/src/shared/daemon-provider-snapshot.ts +52 -0
  342. package/src/shared/external-schedule-contract.ts +60 -0
  343. package/src/shared/node-name.test.ts +62 -0
  344. package/src/shared/node-name.ts +161 -0
  345. package/src/shared/probe-host-allowlist-drift.test.ts +45 -0
  346. package/src/shared/provider-application.ts +29 -0
  347. package/src/shared/provider-collection.ts +14 -0
  348. package/src/shared/provider-initialization.ts +8 -0
  349. package/src/shared/reserved-env-drift.test.ts +10 -0
  350. package/src/shared/scoped-secret-contract.ts +5 -0
  351. package/src/shared/task-content-limit-drift.test.ts +28 -0
  352. package/src/shared/task-content-limit.ts +25 -0
  353. package/src/side-thread-command-transport.test.ts +312 -0
  354. package/src/side-thread-command-transport.ts +318 -0
  355. package/src/side-thread-http-integration.test.ts +233 -0
  356. package/src/side-thread-http.ts +504 -0
  357. package/src/side-thread-production.test.ts +72 -0
  358. package/src/side-thread-production.ts +118 -0
  359. package/src/side-thread.test.ts +1067 -0
  360. package/src/side-thread.ts +2499 -0
  361. package/src/skillhub-http.test.ts +144 -0
  362. package/src/sqlite-close-checkpoint.test.ts +78 -0
  363. package/src/start-node.test.ts +265 -0
  364. package/src/start-request-error-domain.test.ts +182 -0
  365. package/src/start-skill-error-domain.test.ts +122 -0
  366. package/src/stats-versions-http.test.ts +65 -0
  367. package/src/status-alias-filter-http.test.ts +106 -0
  368. package/src/status-alias-resolver-http.test.ts +163 -0
  369. package/src/status-alias-resolver.ts +19 -0
  370. package/src/status-node-id-filter-http.test.ts +161 -0
  371. package/src/status-read-cache-http.test.ts +229 -0
  372. package/src/status-read-cache.ts +129 -0
  373. package/src/stop-delete-node.test.ts +567 -1
  374. package/src/task-access-http.test.ts +402 -0
  375. package/src/task-access.ts +420 -0
  376. package/src/task-activity.ts +60 -0
  377. package/src/task-auth-origin-http.test.ts +93 -0
  378. package/src/task-auth-origin.test.ts +24 -0
  379. package/src/task-auth-origin.ts +7 -0
  380. package/src/task-consumption.test.ts +508 -0
  381. package/src/task-diagnostic-http.test.ts +149 -0
  382. package/src/task-diagnostic.test.ts +115 -0
  383. package/src/task-diagnostic.ts +118 -0
  384. package/src/task-expiry-notice-http.test.ts +298 -0
  385. package/src/task-expiry-notice.ts +318 -0
  386. package/src/task-idempotency-mcp.test.ts +148 -0
  387. package/src/task-idempotency.test.ts +76 -0
  388. package/src/task-idempotency.ts +81 -0
  389. package/src/task-late-replies.ts +54 -0
  390. package/src/task-late-reply-http.test.ts +227 -0
  391. package/src/task-lifecycle-watcher-busy.test.ts +114 -0
  392. package/src/task-lifecycle-watcher.test.ts +209 -0
  393. package/src/task-lifecycle-watcher.ts +109 -0
  394. package/src/task-network-resolution-http.test.ts +140 -0
  395. package/src/task-not-found-error-domain.test.ts +76 -0
  396. package/src/task-offline-delivery-2668.test.ts +119 -0
  397. package/src/task-offline-delivery.ts +81 -0
  398. package/src/task-orphan-http.test.ts +287 -0
  399. package/src/task-orphan.ts +119 -0
  400. package/src/task-queue-ahead-http.test.ts +309 -0
  401. package/src/task-queue-ahead-scale.test.ts +236 -0
  402. package/src/task-queue-ahead.ts +186 -0
  403. package/src/task-rejection-log-http.test.ts +160 -0
  404. package/src/task-rejection-log.ts +61 -0
  405. package/src/task-sender-http.test.ts +143 -0
  406. package/src/task-stale-open-http.test.ts +292 -0
  407. package/src/task-stale-open.ts +103 -0
  408. package/src/tasks-pagination-http.test.ts +141 -0
  409. package/src/team-rules-status-http.test.ts +90 -0
  410. package/src/team-rules-status.test.ts +59 -0
  411. package/src/team-rules-status.ts +72 -0
  412. package/src/tmux-allowlist.test.ts +48 -0
  413. package/src/tool-audience-http.test.ts +248 -0
  414. package/src/tool-audience.ts +127 -0
  415. package/src/tools-list-json-schema.test.ts +94 -0
  416. package/src/tools.ts +4215 -397
  417. package/src/update-node-config-error-domain.test.ts +107 -0
  418. package/src/uploads-http.test.ts +6 -4
  419. package/src/uploads.ts +23 -4
  420. package/src/user-avatar-http.test.ts +74 -0
  421. package/src/user-avatar-image.ts +160 -0
  422. package/src/user-avatar-migration.test.ts +25 -0
  423. package/src/user-avatar-upload-http.test.ts +348 -0
  424. package/src/user-inbox-by-agent-http.test.ts +165 -0
  425. package/src/user-inbox-netid-notnull.test.ts +122 -0
  426. package/src/user-inbox-read-http.test.ts +223 -0
  427. package/src/user-inbox-schema.test.ts +54 -0
  428. package/src/version-stats.test.ts +66 -0
  429. package/src/version-stats.ts +109 -0
@@ -0,0 +1,346 @@
1
+ import { beforeAll, afterAll, expect, test } from "bun:test";
2
+ import { mkdtempSync, readFileSync, readdirSync } from "node:fs";
3
+ import { nodeTokenReissueError } from "../../agent-network/src/cli-errors";
4
+
5
+ process.env.COMMHUB_DB ||= `${mkdtempSync("/tmp/owner678-")}/hub.db`;
6
+ let db: any, hub: ReturnType<typeof Bun.serve>, base: string;
7
+ let owner: any, member: any, outsider: any, legacy: string, mismatched: string, bound: string;
8
+ let wrongBound: string, ownerless: string, revoked: string, crossNetwork: string, requestId: string;
9
+ const daemon = "n_owner_fixture_daemon", child = "n_owner_fixture_child";
10
+
11
+ async function call(token: string, name: string, args: Record<string, unknown> = {}) {
12
+ const response = await fetch(`${base}/mcp`, {
13
+ method: "POST", headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json",
14
+ Accept: "application/json, text/event-stream", "MCP-Protocol-Version": "2025-03-26" },
15
+ body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name, arguments: args } }),
16
+ });
17
+ expect(response.status).toBe(200);
18
+ const raw = await response.text(), lines = raw.split("\n").filter(line => line.startsWith("data:"));
19
+ const message = JSON.parse(lines.length ? lines.at(-1)!.slice(5) : raw);
20
+ expect(message.error).toBeUndefined();
21
+ return JSON.parse(message.result.content[0].text);
22
+ }
23
+ async function mint(token: string, network: string, name: string, nodeId?: string) {
24
+ const response = await fetch(`${base}/api/auth/node-token`, { method: "POST",
25
+ headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" },
26
+ body: JSON.stringify({ network_id: network, node_name: name, ...(nodeId ? { node_id: nodeId } : {}) }),
27
+ });
28
+ return { status: response.status, body: await response.json() as any };
29
+ }
30
+ beforeAll(async () => {
31
+ ({ db } = await import("./db.js"));
32
+ const { register } = await import("./auth.js");
33
+ const { generateNetworkToken, hashToken } = await import("./db.js");
34
+ owner = register("owner678", "Fixture-Strong1!");
35
+ member = register("member678", "Fixture-Strong1!");
36
+ outsider = register("outside678", "Fixture-Strong1!");
37
+ db.run("UPDATE users SET role='user' WHERE user_id IN (?1,?2)", [member.user.user_id, outsider.user.user_id]);
38
+ db.run("INSERT INTO network_members(network_id,user_id,role) VALUES(?1,?2,'member')", [owner.network_id, member.user.user_id]);
39
+ for (const id of [daemon, child, "n_ownerless_fixture"]) {
40
+ db.run(`INSERT INTO nodes(node_id,node_name,alias,network_id,owner_user_id,hostname,config_snapshot,lifecycle_state)
41
+ VALUES(?1,?1,?1,?2,?3,'fixture-host',?4,'active')`, [id, owner.network_id,
42
+ id === "n_ownerless_fixture" ? null : owner.user.user_id,
43
+ JSON.stringify(id === daemon ? { role: "host_supervisor", daemon_capabilities: { adopt_capable: true } } : {})]);
44
+ }
45
+ db.run("INSERT INTO sessions(resume_id,alias,node_id,network_id,status,last_seen_at) VALUES(?1,?1,?1,?2,'idle',datetime('now'))", [daemon, owner.network_id]);
46
+ function credential(label: string, user: string, node: string | null = null, alias = daemon, network = owner.network_id) {
47
+ const token = generateNetworkToken();
48
+ db.run(`INSERT INTO api_tokens(token_id,user_id,network_id,scope,name,token_hash,bound_node_id)
49
+ VALUES(?1,?2,?3,'network',?4,?5,?6)`, [label, user, network, `node:${alias}`, hashToken(token), node]);
50
+ return token;
51
+ }
52
+ legacy = credential("owner678_legacy", owner.user.user_id);
53
+ mismatched = credential("owner678_mismatch", member.user.user_id);
54
+ bound = credential("owner678_bound", member.user.user_id, daemon);
55
+ wrongBound = credential("owner678_wrong_bound", member.user.user_id, "n_absent_bound");
56
+ ownerless = credential("owner678_ownerless", member.user.user_id, null, "n_ownerless_fixture");
57
+ db.run("UPDATE api_tokens SET node_identity_epoch=1 WHERE token_id='owner678_ownerless'");
58
+ revoked = credential("owner678_revoked", owner.user.user_id);
59
+ db.run("UPDATE api_tokens SET revoked_at=datetime('now') WHERE token_id='owner678_revoked'");
60
+ crossNetwork = credential("owner678_cross", outsider.user.user_id, daemon, daemon, outsider.network_id);
61
+ const { bootServer } = await import("./server.js");
62
+ hub = bootServer({ port: 0, hostname: "127.0.0.1" }); base = `http://127.0.0.1:${hub.port}`;
63
+ const request = await call(owner.token, "request_adopt_node", { node_id: child, daemon_node_id: daemon, workdir: "/fixture/project" });
64
+ // #3275 批次 4 —— request_adopt_node 的外层三键(与 read_node_rules_file 同形:
65
+ // 「下发一个请求」这一族的统一形状)。status 一并回来,调用方不必再查一次。
66
+ expect(Object.keys(request).sort()).toEqual(["ok", "request_id", "status"]);
67
+ expect(request.ok).toBe(true); requestId = request.request_id;
68
+ }, 60000);
69
+ afterAll(() => hub?.stop(true));
70
+
71
+ test("name-only issuance checks existing ownership atomically", async () => {
72
+ const count = () => db.get("SELECT COUNT(*) AS n FROM api_tokens").n;
73
+ const before = count();
74
+ expect(await mint(member.token, owner.network_id, daemon)).toEqual({ status: 400, body: { ok: false, error: "node_owner_mismatch" } });
75
+ expect(await mint(owner.token, owner.network_id, "n_ownerless_fixture")).toEqual({ status: 400, body: { ok: false, error: "node_owner_mismatch" } });
76
+ expect(count()).toBe(before);
77
+ // Legacy owner refresh and a new node name remain supported.
78
+ const refresh = await mint(owner.token, owner.network_id, daemon);
79
+ expect(refresh.status).toBe(200);
80
+ expect((await call(refresh.body.token, "list_my_children")).ok).toBe(true);
81
+ expect((await mint(member.token, owner.network_id, "fresh678")).status).toBe(200);
82
+ expect((await mint(member.token, owner.network_id, daemon, daemon)).body.error).toBe("node_owner_mismatch");
83
+ });
84
+
85
+ // Every daemon-facing handler must fail at the shared identity boundary,
86
+ // not incidentally at request lookup or argument validation. The resolver
87
+ // mutation expects all 15 of these cases to go red together.
88
+ const endpoints: [string, Record<string, unknown>][] = [
89
+ ["list_my_pending_create_requests", {}], ["list_my_pending_lifecycle_requests", {}],
90
+ ["get_create_request", { request_id: "cr_fixture_absent" }],
91
+ ["ack_create_request", { request_id: "cr_fixture_absent", status: "started" }],
92
+ ["get_stop_request", { request_id: "sr_fixture_absent" }],
93
+ ["ack_stop_request", { request_id: "sr_fixture_absent", status: "stopped" }],
94
+ ["get_start_request", { request_id: "start_fixture_absent" }],
95
+ ["ack_start_request", { request_id: "start_fixture_absent", status: "started" }],
96
+ ["list_my_children", {}], ["get_adopt_request", {}], ["ack_adopt_request", { status: "adopted" }],
97
+ ["get_probe_request", { probe_id: "probe_fixture_absent" }],
98
+ ["ack_probe_request", { probe_id: "probe_fixture_absent", status: "ok", latency_ms: 1 }],
99
+ ["get_opencode_catalog_request", { request_id: "cat_fixture_absent" }],
100
+ ["ack_opencode_catalog", { request_id: "cat_fixture_absent", error: "unavailable" }],
101
+ ];
102
+ for (const [name, arguments_] of endpoints) {
103
+ test(`daemon identity boundary: ${name}`, async () => {
104
+ const args = name.includes("adopt_request") ? { ...arguments_, request_id: requestId } : arguments_;
105
+ for (const token of [mismatched, wrongBound, ownerless, owner.token, member.token]) {
106
+ const denied = await call(token, name, args);
107
+ expect(denied).toMatchObject({ ok: false, error: "caller_not_a_daemon" });
108
+ // 2026-10-31 —— #3275:**错误信封也是契约**。
109
+ // 这八个 ack/get 工具此前只被断言过 error 的**值**,没有一条钉住键集:
110
+ // 谁顺手在某个出口多塞一个字段(例如 hint / request_id),客户端的分支就多一个没人知道的键。
111
+ // ⇒ 在同一个循环里把形状钉住,成本几乎为零。
112
+ expect(Object.keys(denied).sort()).toEqual(["error", "ok"]);
113
+ }
114
+ expect(db.get("SELECT status FROM node_daemon_bindings WHERE request_id=?1", requestId).status).toBe("pending");
115
+ });
116
+ }
117
+
118
+ // #3275 批次 1 —— 上面那个表驱动循环里工具名是**变量**,所以「同变量」统计口径按名字归因不到任何一个工具。
119
+ // 这不是测试写得不好,是**统计的粒度**问题:一条循环里的断言无法被归到被循环的那 N 个工具上。
120
+ // ⇒ 给 ack_create_request 补一条带字面量的:错误信封是闭集 {error, ok}。
121
+ //
122
+ // 批次 1·c 的结论(写在这里,因为它是这一批的**真实成本**:夹具不够,不是断言不够):
123
+ // 三个 `ack_*_request` 的失败分支闭集是 request_not_found / not_your_request /
124
+ // cross_network_request / caller_not_a_daemon。今天只有最后一条可达(上面的循环已钉住 {error,ok})。
125
+ // 前三条要么需要**绑定到 daemon 的** MCP 凭证(owner 令牌先撞 caller_not_a_daemon),
126
+ // 要么需要跨网络 daemon 凭证 —— 本夹具里的 `bound` 只用于 REST 侧 mint 测试,
127
+ // 拿它调 /mcp 直接非 200(实测),所以那条路走不通。
128
+ // ⇒ 批次 1·c 要先造一个「daemon 绑定 + MCP 可用」的凭证,再谈断言。
129
+ // 在那之前,任何「4 条失败分支已覆盖」的说法都是假的。
130
+ test("#3275 ack_create_request 的错误信封恰好 {error, ok}", async () => {
131
+ const denied = await call(owner.token, "ack_create_request", { request_id: "cr_fixture_absent", status: "started" });
132
+ expect(denied.ok).toBe(false);
133
+ expect(Object.keys(denied).sort()).toEqual(["error", "ok"]);
134
+ });
135
+
136
+ test("legacy owner and exact bound identity remain supported", async () => {
137
+ expect(db.get("SELECT bound_node_id FROM api_tokens WHERE token_id='owner678_legacy'").bound_node_id).toBeNull();
138
+ for (const token of [legacy, bound]) {
139
+ expect((await call(token, "list_my_children")).ok).toBe(true);
140
+ // 2026-10-31 —— #3275 批次 2:这两条是 **SSE 重连补偿**的入口(漏了门铃节点会卡死),
141
+ // 客户端按字段名读;键集从未被钉住。改为 `const` 赋值,顺便让严格口径能数到它们。
142
+ const pendCreate = await call(token, "list_my_pending_create_requests");
143
+ expect(pendCreate.ok).toBe(true);
144
+ expect(Object.keys(pendCreate).sort()).toEqual(["clone_count", "clone_requests", "count", "ok", "requests"]);
145
+
146
+ const pendLife = await call(token, "list_my_pending_lifecycle_requests");
147
+ expect(pendLife.ok).toBe(true);
148
+ expect(Object.keys(pendLife).sort()).toEqual(["ok", "start_count", "start_requests", "stop_count", "stop_requests"]);
149
+ // 计数与数组同源:两个 count 必须等于各自数组长度(否则「有 N 条」与「列出来」会分叉)
150
+ expect(pendLife.stop_count).toBe(pendLife.stop_requests.length);
151
+ expect(pendLife.start_count).toBe(pendLife.start_requests.length);
152
+ // 2026-10-31 —— #3275:形状由**一次真实调用**给出(不靠读源码猜)
153
+ const gotAdopt = await call(token, "get_adopt_request", { request_id: requestId });
154
+ expect(gotAdopt.ok).toBe(true);
155
+ // ⚠️ 我第一版按源码猜了 7 个键(binding_request_id / child_alias / child_node_id …)——**全错**。
156
+ // 真实形状由这次调用给出,12 个键;其中 error 为空、request_id 是这一行自己的 id。
157
+ // 这是本卡第三次被「读源码猜形状」打回,写进注释免得下一个人再猜:
158
+ // 行对象整行透传时,源码里看到的字段名是**SQL 的列名**,与对外载荷不是一回事。
159
+ expect(Object.keys(gotAdopt).sort()).toEqual([
160
+ "alias", "created_at", "daemon_node_id", "error", "network_id", "node_id",
161
+ "ok", "request_id", "requested_by", "status", "updated_at", "workdir",
162
+ ]);
163
+ }
164
+ // An explicit binding does not bypass the network or revocation boundaries.
165
+ expect(await call(crossNetwork, "list_my_children")).toMatchObject({ ok: false, error: "caller_not_a_daemon" });
166
+ const denied = await fetch(`${base}/mcp`, { method: "POST", headers: { Authorization: `Bearer ${revoked}` } });
167
+ expect(denied.status).toBe(401);
168
+ // 2026-10-31 —— #3275:**成功体也要钉键集**(上面那个循环钉的是错误信封)。
169
+ // 这四条是 daemon 侧最常被按字段名读的回执;多一个键不会让谁报错,但会改变解析分支。
170
+ const adopted = await call(legacy, "ack_adopt_request", { request_id: requestId, status: "adopted" });
171
+ expect(adopted).toMatchObject({ ok: true, status: "active" });
172
+ expect(Object.keys(adopted).sort()).toEqual(["ok", "status"]);
173
+ expect((await call(legacy, "list_my_children")).children).toContainEqual({ child_node_id: child, alias: child, lifecycle_state: "active", managed: "adopted", binding_request_id: requestId });
174
+ // 2026-10-31 —— #3275:get_probe_request 的**不存在**分支键集(成功分支需要真实 probe 夹具,
175
+ // 本文件不造;错误分支同样是契约:客户端按 error 分支,多一个键就会多一个没人知道的分支)
176
+ const gotProbe = await call(legacy, "get_probe_request", { probe_id: "probe_fixture_absent" });
177
+ expect(gotProbe.ok).toBe(false);
178
+ // 实测:错误分支多一个 reason(不是只 {error, ok})——**又一次由真实调用纠正**
179
+ expect(Object.keys(gotProbe).sort()).toEqual(["error", "ok", "reason"]);
180
+ // #3309 分支 —— get_probe_request 的**成功出口**(此前只有不存在分支被钉)。
181
+ // `putPendingProbeSecret` 是导出的 ⇒ 直接把一条 probe 放进 Map 即可,不需要造真 probe 流程。
182
+ {
183
+ const { putPendingProbeSecret } = await import("./probe.js");
184
+ putPendingProbeSecret({
185
+ probe_id: "probe_fixture_live", daemon_node_id: daemon, provider_id: "prov_fixture",
186
+ vendor: "anthropic", base_url: "https://api.anthropic.com", model_name: "m",
187
+ api_key: `PROBE-SENTINEL-${Date.now()}`, network_id: owner.network_id,
188
+ });
189
+ const live = await call(legacy, "get_probe_request", { probe_id: "probe_fixture_live" });
190
+ // 实测六键。**注意 api_key 在里面** —— 这是本仓唯一一个「读面回传明文密钥」的出口,
191
+ // 它靠三条约束成立:① 只有目标 daemon 能取(cross-daemon guard)
192
+ // ② 取一次就删(takePendingProbeSecret)
193
+ // ③ 60s TTL
194
+ // ⇒ 断言里顺带把这三条的可观测面钉住:取走后第二次调用必须回到不存在分支。
195
+ expect(Object.keys(live).sort()).toEqual(["api_key", "base_url", "model_name", "ok", "probe_id", "vendor"]);
196
+ expect(live.ok).toBe(true);
197
+ const again = await call(legacy, "get_probe_request", { probe_id: "probe_fixture_live" });
198
+ expect(again).toEqual({ ok: false, error: "probe_request_unavailable", reason: "not_found_or_wrong_daemon_or_expired" });
199
+ }
200
+
201
+ // 2026-10-31 —— #3275:get_opencode_catalog_request 的**不存在**分支恰好两键
202
+ // (与 get_probe_request 的三键不同族 —— 又一次说明「错误信封不是全仓一个形状」)
203
+ const gotCatalog = await call(legacy, "get_opencode_catalog_request", { request_id: "cat_fixture_absent" });
204
+ expect(gotCatalog.ok).toBe(false);
205
+ expect(Object.keys(gotCatalog).sort()).toEqual(["error", "ok"]);
206
+ const stop = await call(owner.token, "stop_node", { node_id: child, network_id: owner.network_id });
207
+ // #3275 批次 2·f —— stop_node 的外层(实测)。比 start_node 多两个键:
208
+ // `action` 说明触发的是哪条路径(restart_node 走同一条),`in_flight_at_dispatch` 说明
209
+ // **下发那一刻**手上还有几条任务 —— 少了它,客户端无法区分「干净停机」与「截断在跑的任务」。
210
+ expect(Object.keys(stop).sort()).toEqual(["action", "in_flight_at_dispatch", "lifecycle_state", "ok", "request_id"]);
211
+ expect(stop.ok).toBe(true);
212
+ // 2026-10-31 —— #3275 批次 2:get_stop_request 的**成功体**键集(daemon 按字段名读,
213
+ // 尤其 delete_config / grace_seconds / force 三个决定它要不要删配置)
214
+ const gotStop = await call(legacy, "get_stop_request", { request_id: stop.request_id });
215
+ expect(gotStop.ok).toBe(true);
216
+ expect(Object.keys(gotStop).sort()).toEqual([
217
+ "action", "child_alias", "child_node_id", "delete_config", "force", "grace_seconds", "ok", "request_id",
218
+ ]);
219
+ const stoppedAck = await call(legacy, "ack_stop_request", { request_id: stop.request_id, status: "stopped" });
220
+ expect(stoppedAck.ok).toBe(true);
221
+ expect(Object.keys(stoppedAck).sort()).toEqual(["ok", "status"]); // #3275:成功体键集
222
+ const start = await call(owner.token, "start_node", { node_id: child, network_id: owner.network_id });
223
+ // start_node 只有四个键:**它没有 in_flight_at_dispatch** ——
224
+ // 因为「启动时手上还有几条任务」不是一个有意义的问题。两个工具同名不同形,各自量。
225
+ expect(Object.keys(start).sort()).toEqual(["lifecycle_state", "ok", "request_id"]);
226
+ expect(start.ok).toBe(true);
227
+ const gotStart = await call(legacy, "get_start_request", { request_id: start.request_id });
228
+ expect(gotStart.ok).toBe(true);
229
+ // 成功体:四个固定键 + start_completion_capable;fork_recovery 只在「创建即恢复」路径出现(条件键)
230
+ expect(Object.keys(gotStart).sort()).toEqual([
231
+ "child_alias", "child_node_id", "ok", "request_id", "start_completion_capable",
232
+ ]);
233
+ const startedAck = await call(legacy, "ack_start_request", { request_id: start.request_id, status: "started", child_pid: 4321 });
234
+ expect(startedAck).toMatchObject({ ok: true, status: "started" });
235
+ expect(Object.keys(startedAck).sort()).toEqual(["ok", "status"]); // #3275:成功体键集
236
+ });
237
+
238
+ test("ownerless legacy daemon remains supported without rewriting its owner", async () => {
239
+ db.run("UPDATE api_tokens SET node_identity_epoch=0 WHERE token_id='owner678_ownerless'");
240
+ try {
241
+ expect((await call(ownerless, "list_my_children")).ok).toBe(true);
242
+ const refresh = await mint(member.token, owner.network_id, "n_ownerless_fixture");
243
+ expect(refresh.status).toBe(200);
244
+ expect(refresh.body.node_id).toBe("n_ownerless_fixture");
245
+ expect((await call(refresh.body.token, "list_my_children")).ok).toBe(true);
246
+ const withId = await mint(member.token, owner.network_id, "n_ownerless_fixture", "n_ownerless_fixture");
247
+ expect(withId.status).toBe(200);
248
+ expect(db.get("SELECT owner_user_id FROM nodes WHERE node_id='n_ownerless_fixture'").owner_user_id).toBeNull();
249
+ expect((await mint(owner.token, owner.network_id, "n_ownerless_fixture")).status).toBe(400);
250
+ } finally { db.run("UPDATE api_tokens SET node_identity_epoch=1 WHERE token_id='owner678_ownerless'"); }
251
+ });
252
+
253
+ test("new name-only registration binds once and its holder can refresh with either shape", async () => {
254
+ const first = await mint(member.token, owner.network_id, "refresh_fixture");
255
+ expect(first.status).toBe(200);
256
+ expect(db.get("SELECT node_identity_epoch FROM api_tokens WHERE token_id=?1", first.body.token_id).node_identity_epoch).toBe(2);
257
+ const result = await call(first.body.token, "report_status", {
258
+ resume_id: "refresh-fixture-session", alias: "refresh_fixture", status: "idle", node_id: "n_refresh_fixture",
259
+ });
260
+ // #3275 批次 2 —— 同变量口径,形状由一次真实调用给出:
261
+ // ["alias","inbox_count","ok","resume_id"]
262
+ // 少一个 `inbox_count`,客户端就再也不知道「还有几条待办」——而它正是每轮心跳唯一的推送面;
263
+ // 少一个 `alias`,多网络下的会话就认不出自己是谁。只断言 ok 时,这两个都能被悄悄删掉。
264
+ expect(Object.keys(result).sort()).toEqual(["alias", "inbox_count", "ok", "resume_id"]);
265
+ expect(result.ok).toBe(true);
266
+ expect(db.get("SELECT bound_node_id FROM api_tokens WHERE token_id=?1", first.body.token_id).bound_node_id).toBe("n_refresh_fixture");
267
+ expect(db.get("SELECT owner_user_id FROM nodes WHERE node_id='n_refresh_fixture'").owner_user_id).toBeNull();
268
+ for (const id of [undefined, "n_refresh_fixture"]) {
269
+ const refresh = await mint(member.token, owner.network_id, "refresh_fixture", id);
270
+ expect(refresh.status).toBe(200);
271
+ expect(refresh.body.node_id).toBe("n_refresh_fixture");
272
+ expect((await call(refresh.body.token, "list_my_children")).ok).toBe(true);
273
+ }
274
+ expect((await mint(owner.token, owner.network_id, "refresh_fixture")).status).toBe(400);
275
+ });
276
+
277
+ test("fresh ID cannot mint another node alias", async () => {
278
+ const before = db.get("SELECT COUNT(*) AS n FROM api_tokens").n;
279
+ expect((await mint(member.token, owner.network_id, daemon, "n_fresh_impostor")).status).toBe(400);
280
+ expect(db.get("SELECT node_id FROM nodes WHERE node_id='n_fresh_impostor'")).toBeNull();
281
+ expect(db.get("SELECT COUNT(*) AS n FROM api_tokens").n).toBe(before);
282
+ expect((await call(legacy, "list_my_children")).ok).toBe(true);
283
+ });
284
+
285
+ test("duplicate legacy aliases use bound IDs and an unbound token follows its owner", async () => {
286
+ // Historical duplicate rows: the member's row was inserted first. Neither
287
+ // lookup order nor alias can redirect an exact-bound token. An unbound
288
+ // token resolves to the row its issuer owns.
289
+ const { hashToken, generateNetworkToken } = await import("./db.js");
290
+ const tokens: string[] = [];
291
+ for (const [id, user] of [["n_duplicate_first", member.user.user_id], ["n_duplicate_owner", owner.user.user_id]]) {
292
+ db.run("INSERT INTO nodes(node_id,node_name,alias,network_id,owner_user_id) VALUES(?1,'duplicate_fixture','duplicate_fixture',?2,?3)", [id, owner.network_id, user]);
293
+ const token = generateNetworkToken(); tokens.push(token);
294
+ db.run("INSERT INTO api_tokens(token_id,token_hash,user_id,network_id,name,scope,bound_node_id) VALUES(?1,?2,?3,?4,'node:duplicate_fixture','network',?1)", [id, hashToken(token), user, owner.network_id]);
295
+ 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,?1,?1,'/fixture',?3,'pending',1,1)", [id, owner.network_id, user]);
296
+ }
297
+ for (let i = 0; i < tokens.length; i++) {
298
+ const result = await call(tokens[i], "list_my_children");
299
+ expect(result.ok).toBe(true);
300
+ const ownId = i === 0 ? "n_duplicate_first" : "n_duplicate_owner";
301
+ expect((await call(tokens[i], "get_adopt_request", { request_id: ownId })).ok).toBe(true);
302
+ expect((await call(tokens[i], "get_adopt_request", { request_id: i === 0 ? "n_duplicate_owner" : "n_duplicate_first" })).ok).toBe(false);
303
+ }
304
+ db.run("UPDATE api_tokens SET bound_node_id=NULL WHERE token_id='n_duplicate_owner'");
305
+ expect((await call(tokens[1], "list_my_children")).ok).toBe(true);
306
+ expect((await call(tokens[1], "get_adopt_request", { request_id: "n_duplicate_owner" })).ok).toBe(true);
307
+ expect((await call(tokens[1], "get_adopt_request", { request_id: "n_duplicate_first" })).ok).toBe(false);
308
+ db.run("UPDATE api_tokens SET bound_node_id=NULL WHERE token_id='n_duplicate_first'");
309
+ expect((await call(tokens[0], "list_my_children")).ok).toBe(true);
310
+ expect((await call(tokens[0], "get_adopt_request", { request_id: "n_duplicate_first" })).ok).toBe(true);
311
+ expect((await call(tokens[0], "get_adopt_request", { request_id: "n_duplicate_owner" })).ok).toBe(false);
312
+ expect((await mint(owner.token, owner.network_id, "duplicate_fixture", "n_third_duplicate")).status).toBe(400);
313
+ });
314
+
315
+ test("all production token issuers explicitly mark the rollout epoch", () => {
316
+ const root = `${import.meta.dir}/../..`;
317
+ function sources(dir: string): string[] {
318
+ return readdirSync(dir, { withFileTypes: true }).flatMap(entry => {
319
+ const path = `${dir}/${entry.name}`;
320
+ return entry.isDirectory() ? sources(path) : entry.name.endsWith(".ts") && !entry.name.endsWith(".test.ts") ? [path] : [];
321
+ });
322
+ }
323
+ const sourceFiles = ["server/src", "agent-network/src", "agent-network/bin", "agent-node/src"].flatMap(dir => sources(`${root}/${dir}`));
324
+ let count = 0;
325
+ for (const file of sourceFiles) {
326
+ const source = readFileSync(file, "utf8");
327
+ for (const match of source.matchAll(/INSERT\s+INTO\s+api_tokens\s*\(([^)]+)\)/gi)) {
328
+ expect(match[1]).toContain("node_identity_epoch"); count++;
329
+ }
330
+ }
331
+ // Hub #938: clone_node mints a child ntok_ with node_identity_epoch=2,
332
+ // the same column create_node already writes. 9 issuers → 10.
333
+ expect(count).toBe(10);
334
+ expect(readFileSync(`${root}/agent-network/bin/cli.ts`, "utf8")).toContain("'admin-reset', 'user', 1)");
335
+ });
336
+
337
+ test("revoked ownerless credential cannot be reclaimed by doctor and gives actionable guidance", async () => {
338
+ db.run("UPDATE api_tokens SET revoked_at=datetime('now') WHERE name='node:n_ownerless_fixture'");
339
+ const result = await mint(member.token, owner.network_id, "n_ownerless_fixture");
340
+ expect(result.status).toBe(400);
341
+ expect(result.body.error).toBe("node_owner_mismatch");
342
+ expect(nodeTokenReissueError(result.body)).toContain("这个节点没有归属,请联系管理员认领(#682)");
343
+ expect(nodeTokenReissueError({ error: "node_owner_unclaimed" })).toContain("请联系管理员认领(#682)");
344
+ expect(nodeTokenReissueError({ error: "network_not_found" })).toBe("network_not_found");
345
+ expect(readFileSync(`${import.meta.dir}/../../agent-network/bin/cli.ts`, "utf8")).toContain("body ? nodeTokenReissueError(body) : r.status");
346
+ });
@@ -0,0 +1,109 @@
1
+ import { afterAll, beforeAll, describe, expect, test } from "bun:test";
2
+ import { mkdtempSync, rmSync } from "fs";
3
+ import { join } from "path";
4
+ import { tmpdir } from "os";
5
+ import { isInteractiveDashboardTask } from "../../agent-node/src/inbox-dispatch";
6
+ import { shouldCreateScheduledGoal } from "../../agent-node/src/goals/routing";
7
+ import { createNetworkTokenForNode, register } from "./auth.js";
8
+ import { db } from "./db.js";
9
+
10
+ const PRIVATE_DB_DIR = mkdtempSync(join(tmpdir(), "anet-dashboard-slash-http-"));
11
+ const TARGET = `dashboard-slash-target-${process.pid}`;
12
+ const TARGET_NODE_ID = `node_dashboard_slash_target_${process.pid}`;
13
+ const TARGET_RESUME_ID = `resume_dashboard_slash_target_${process.pid}`;
14
+ let server: any;
15
+ let base = "";
16
+ let userToken = "";
17
+ let userName = "";
18
+ let nodeToken = "";
19
+ let networkId = "";
20
+ let requestSequence = 0;
21
+
22
+ // 30s 而不是 bun 默认的 5s:这个 hook 跑 register()(KDF)+bootServer(),
23
+ // 本机空载基线 ~620ms,而 2026-08-17 与 2026-08-31 两次 CI 上它被 5s 上限打死
24
+ // (0 pass / 1 fail / Ran 1 test —— 见 #928、#1627)。5247ms 是**被截断的下界**,
25
+ // 不是测量值,所以余量按基线的 ~48x 取,而不是按那个数取。
26
+ beforeAll(async () => {
27
+ process.env.COMMHUB_DB = process.env.COMMHUB_DB || join(PRIVATE_DB_DIR, "hub.db");
28
+ const username = `dashboard_slash_${Date.now()}`;
29
+ userName = username;
30
+ const registered = register(username, "DashboardSlash123!", undefined, "seed");
31
+ expect(registered.ok).toBe(true);
32
+ userToken = registered.token!;
33
+ networkId = registered.network_id!;
34
+ const userId = db.get<{ user_id: string }>("SELECT user_id FROM users WHERE username = ?1", [username])!.user_id;
35
+ const minted = createNetworkTokenForNode(userId, networkId, "dashboard-slash-node");
36
+ expect(minted.ok).toBe(true);
37
+ nodeToken = minted.token!;
38
+ db.run(
39
+ `INSERT INTO sessions (resume_id, alias, status, node_id, network_id, updated_at, last_seen_at)
40
+ VALUES (?1, ?2, 'idle', ?3, ?4, datetime('now'), datetime('now'))`,
41
+ [TARGET_RESUME_ID, TARGET, TARGET_NODE_ID, networkId],
42
+ );
43
+ db.run(
44
+ `INSERT INTO nodes (node_id, node_name, alias, network_id, created_at, updated_at, lifecycle_state)
45
+ VALUES (?1, ?2, ?2, ?3, datetime('now'), datetime('now'), 'active')`,
46
+ [TARGET_NODE_ID, TARGET, networkId],
47
+ );
48
+ const mod: any = await import("./server.js");
49
+ server = mod.bootServer({ port: 0, hostname: "127.0.0.1" });
50
+ base = `http://127.0.0.1:${server.port}`;
51
+ }, 30_000);
52
+
53
+ afterAll(() => {
54
+ try { server?.stop?.(true); } catch {}
55
+ try { rmSync(PRIVATE_DB_DIR, { recursive: true, force: true }); } catch {}
56
+ });
57
+
58
+ async function postAndRead(token: string, from: string, task: string) {
59
+ requestSequence += 1;
60
+ const clientRequestId = `dreq_${requestSequence.toString(16).padStart(32, "0")}`;
61
+ const response = await fetch(`${base}/api/task`, {
62
+ method: "POST",
63
+ headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" },
64
+ body: JSON.stringify({
65
+ alias: TARGET,
66
+ from,
67
+ network_id: networkId,
68
+ task,
69
+ meta: { source: "dashboard-chat", client_request_id: clientRequestId, auth_origin: "user" },
70
+ }),
71
+ });
72
+ const body = await response.json() as any;
73
+ expect([200, 202]).toContain(response.status);
74
+ const taskId = body.task_id ?? body.message_id;
75
+ const row = db.get<{ content: string; meta_json: string }>(
76
+ "SELECT content, meta_json FROM inbox WHERE id = ?1",
77
+ [taskId],
78
+ );
79
+ expect(row).toBeTruthy();
80
+ return { type: "task", content: row!.content, meta_json: row!.meta_json };
81
+ }
82
+
83
+ describe("real Hub → authenticated Dashboard slash routing", () => {
84
+ test("Dashboard /goal and /loop remain exact native payloads for every runtime", async () => {
85
+ for (const command of ["/goal 更新一下文档", "/loop 5m native loop"] as const) {
86
+ const row = await postAndRead(userToken, userName, command);
87
+ expect(row.content).toBe(command);
88
+ expect(isInteractiveDashboardTask(row)).toBe(true);
89
+ for (const runtime of ["codex-app-server", "codex", "claude", "grok", "opencode"] as const) {
90
+ expect(shouldCreateScheduledGoal(row.content, runtime, true)).toBe(false);
91
+ }
92
+ }
93
+ });
94
+
95
+ test("Dashboard /agoal and /aloop use the Agent Network scheduler", async () => {
96
+ for (const command of ["/agoal 5m update docs", "/aloop 5m update docs"] as const) {
97
+ const row = await postAndRead(userToken, userName, command);
98
+ expect(isInteractiveDashboardTask(row)).toBe(true);
99
+ expect(shouldCreateScheduledGoal(row.content, "codex-app-server", true)).toBe(true);
100
+ }
101
+ });
102
+
103
+ test("node token cannot forge Dashboard pass-through and keeps legacy compatibility", async () => {
104
+ const row = await postAndRead(nodeToken, "dashboard-slash-node", "/loop 5m legacy automation");
105
+ expect(JSON.parse(row.meta_json).auth_origin).toBe("node");
106
+ expect(isInteractiveDashboardTask(row)).toBe(false);
107
+ expect(shouldCreateScheduledGoal(row.content, "codex-app-server", false)).toBe(true);
108
+ });
109
+ });
@@ -0,0 +1,148 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import {
3
+ assertSafeTestDatabaseEnv,
4
+ redactPgUrl,
5
+ resolveDatabaseTarget,
6
+ } from "./db-adapter";
7
+
8
+ const BASE_ENV: NodeJS.ProcessEnv = { HOME: "/nonexistent" };
9
+
10
+ describe("#435 inherited DATABASE_URL guard", () => {
11
+ for (const databaseUrl of [
12
+ "postgres://user:pw@prod.example:5432/commhub",
13
+ "postgresql://user:pw@prod.example:5432/commhub",
14
+ "sqlite:///tmp/not-an-escape",
15
+ ]) {
16
+ test(`NODE_ENV=test rejects ${databaseUrl.split(":", 1)[0]} DATABASE_URL`, () => {
17
+ expect(() => assertSafeTestDatabaseEnv({
18
+ ...BASE_ENV,
19
+ NODE_ENV: "test",
20
+ DATABASE_URL: databaseUrl,
21
+ })).toThrow(/REFUSING to honor inherited DATABASE_URL/);
22
+ });
23
+ }
24
+
25
+ test("test without DATABASE_URL leaves the existing SQLite guard in charge", () => {
26
+ expect(() => assertSafeTestDatabaseEnv({ ...BASE_ENV, NODE_ENV: "test" })).not.toThrow();
27
+ expect(() => resolveDatabaseTarget({ ...BASE_ENV, NODE_ENV: "test" }))
28
+ .toThrow(/REFUSING to open the default SQLite database/);
29
+ });
30
+
31
+ test("DATABASE_URL refusal wins even when COMMHUB_DB is also set", () => {
32
+ expect(() => resolveDatabaseTarget({
33
+ ...BASE_ENV,
34
+ NODE_ENV: "test",
35
+ DATABASE_URL: "postgres://user:pw@prod.example:5432/commhub",
36
+ COMMHUB_DB: "/tmp/isolated.db",
37
+ })).toThrow(/REFUSING to honor inherited DATABASE_URL/);
38
+ });
39
+
40
+ test("production postgres branch remains unchanged without constructing it", () => {
41
+ const url = "postgres://user:pw@prod.example:5432/commhub";
42
+ expect(resolveDatabaseTarget({
43
+ ...BASE_ENV,
44
+ NODE_ENV: "production",
45
+ DATABASE_URL: url,
46
+ })).toEqual({ kind: "postgres", url });
47
+ });
48
+
49
+ test("unset NODE_ENV still selects postgres", () => {
50
+ const url = "postgresql://user:pw@prod.example:5432/commhub";
51
+ expect(resolveDatabaseTarget({ ...BASE_ENV, DATABASE_URL: url }))
52
+ .toEqual({ kind: "postgres", url });
53
+ });
54
+
55
+ test("explicit SQLite targets remain unchanged in test and production", () => {
56
+ for (const NODE_ENV of ["test", "production"]) {
57
+ expect(resolveDatabaseTarget({
58
+ ...BASE_ENV,
59
+ NODE_ENV,
60
+ COMMHUB_DB: "/tmp/isolated.db",
61
+ })).toEqual({ kind: "sqlite", path: "/tmp/isolated.db" });
62
+ }
63
+ });
64
+
65
+ test("non-server callers cannot silently fall through to the production default SQLite path", () => {
66
+ for (const NODE_ENV of [undefined, "development", "production"]) {
67
+ expect(() => resolveDatabaseTarget({ ...BASE_ENV, NODE_ENV }))
68
+ .toThrow(/explicit COMMHUB_DB|COMMHUB_SERVER=1/);
69
+ }
70
+ });
71
+
72
+ test("the explicit server boot capability permits the canonical default SQLite path", () => {
73
+ expect(resolveDatabaseTarget({
74
+ ...BASE_ENV,
75
+ NODE_ENV: "production",
76
+ COMMHUB_SERVER: "1",
77
+ })).toEqual({ kind: "sqlite", path: "/nonexistent/.commhub/commhub.db" });
78
+ });
79
+
80
+ test("lookalike server capability values fail closed", () => {
81
+ for (const COMMHUB_SERVER of ["", "true", "yes", "01", " 1"] ) {
82
+ expect(() => resolveDatabaseTarget({ ...BASE_ENV, COMMHUB_SERVER }))
83
+ .toThrow(/COMMHUB_SERVER=1/);
84
+ }
85
+ });
86
+ });
87
+
88
+ describe("RFC-039 §9 COMMHUB_TEST_PG_URL (test-only PostgreSQL)", () => {
89
+ const TEST = { ...BASE_ENV, NODE_ENV: "test" };
90
+ const ok = (url: string) => expect(resolveDatabaseTarget({ ...TEST, COMMHUB_TEST_PG_URL: url })).toEqual({ kind: "postgres", url });
91
+ const refused = (url: string, why: RegExp) => {
92
+ let message = "";
93
+ try { resolveDatabaseTarget({ ...TEST, COMMHUB_TEST_PG_URL: url }); } catch (e: any) { message = String(e?.message ?? e); }
94
+ expect(message).toMatch(/REFUSING COMMHUB_TEST_PG_URL/);
95
+ expect(message).toMatch(why);
96
+ // Credentials never reach an error message.
97
+ expect(message).not.toContain("s3cret");
98
+ expect(message).not.toContain("tester");
99
+ };
100
+
101
+ test("loopback host + anet_*_test database is accepted under NODE_ENV=test", () => {
102
+ ok("postgres://tester:s3cret@127.0.0.1:5432/anet_sched_test");
103
+ ok("postgresql://tester:s3cret@localhost/anet_side_thread_test");
104
+ ok("postgres://tester:s3cret@[::1]:6543/anet_x_test?connect_timeout=2&sslmode=disable");
105
+ });
106
+
107
+ test("ignored outside NODE_ENV=test", () => {
108
+ expect(resolveDatabaseTarget({ ...BASE_ENV, NODE_ENV: "production", COMMHUB_DB: "/tmp/i.db", COMMHUB_TEST_PG_URL: "postgres://tester:s3cret@127.0.0.1/anet_x_test" }))
109
+ .toEqual({ kind: "sqlite", path: "/tmp/i.db" });
110
+ });
111
+
112
+ test("inherited DATABASE_URL still refuses even when COMMHUB_TEST_PG_URL is set", () => {
113
+ expect(() => resolveDatabaseTarget({
114
+ ...TEST,
115
+ DATABASE_URL: "postgres://user:pw@prod.example:5432/commhub",
116
+ COMMHUB_TEST_PG_URL: "postgres://tester:s3cret@127.0.0.1/anet_x_test",
117
+ })).toThrow(/REFUSING to honor inherited DATABASE_URL/);
118
+ });
119
+
120
+ test("refuses a value that is not a URL or not postgres", () => {
121
+ refused("not a url", /not a URL/);
122
+ refused("mysql://tester:s3cret@127.0.0.1/anet_x_test", /scheme/);
123
+ });
124
+
125
+ test("refuses every host that is not literally loopback", () => {
126
+ for (const host of ["10.0.0.5", "db.internal", "localhost.evil.example", "127.0.0.2", "127.0.0.1,evil.example", "LOCALHOST", "%2Ftmp"]) {
127
+ refused(`postgres://tester:s3cret@${host}/anet_x_test`, /host must be/);
128
+ }
129
+ });
130
+
131
+ test("refuses database names outside /^anet_[a-z0-9_]*_test$/", () => {
132
+ for (const name of ["commhub", "anet_x", "anet_x_test2", "ANET_X_TEST", "anet-x_test", "anet_x_test/extra", ""]) {
133
+ refused(`postgres://tester:s3cret@127.0.0.1/${name}`, /database name/);
134
+ }
135
+ });
136
+
137
+ test("refuses connection-steering query parameters", () => {
138
+ refused("postgres://tester:s3cret@127.0.0.1/anet_x_test?host=db.internal", /"host" is not allowed/);
139
+ refused("postgres://tester:s3cret@127.0.0.1/anet_x_test?options=-csearch_path%3Dprod", /"options" is not allowed/);
140
+ });
141
+
142
+ test("redactPgUrl drops user and password", () => {
143
+ const out = redactPgUrl("postgres://tester:s3cret@127.0.0.1:5432/anet_x_test");
144
+ expect(out).not.toContain("tester");
145
+ expect(out).not.toContain("s3cret");
146
+ expect(out).toContain("127.0.0.1:5432/anet_x_test");
147
+ });
148
+ });