@sleep2agi/commhub-server 0.9.0-preview.25 → 0.9.0-preview.250

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 (417) hide show
  1. package/README.md +129 -9
  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 +675 -0
  15. package/src/agent-acl-slice3-http.test.ts +717 -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 +95 -4
  30. package/src/auth-password-change-cli-tokens-http.test.ts +423 -0
  31. package/src/auth-sessions-http.test.ts +260 -0
  32. package/src/auth-validate.test.ts +5 -1
  33. package/src/auth-weak-password-login.test.ts +176 -0
  34. package/src/auth.ts +609 -51
  35. package/src/avatar-validate.test.ts +52 -2
  36. package/src/avatar-validate.ts +35 -1
  37. package/src/backfill-node-ids-2664.test.ts +128 -0
  38. package/src/binding-generation-http.test.ts +132 -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-info.test.ts +60 -0
  43. package/src/build-info.ts +85 -0
  44. package/src/chain-attempt-dedup.test.ts +447 -0
  45. package/src/clip.test.ts +36 -0
  46. package/src/clip.ts +48 -0
  47. package/src/clone-node.test.ts +262 -0
  48. package/src/clone-node.ts +289 -0
  49. package/src/codex-config-flags.ts +77 -0
  50. package/src/codex-fork-contract.ts +23 -0
  51. package/src/codex-fork-migration.test.ts +38 -0
  52. package/src/commhub-bin-args.test.ts +85 -0
  53. package/src/config-apply-validate.test.ts +188 -1
  54. package/src/config-apply-validate.ts +222 -3
  55. package/src/cors-origins.test.ts +73 -0
  56. package/src/create-node-blocked-gate.test.ts +356 -0
  57. package/src/create-node-network-id.test.ts +91 -0
  58. package/src/create-node-tool-schema.test.ts +49 -0
  59. package/src/create-node-unicode-name.test.ts +126 -0
  60. package/src/create-node-validate.test.ts +199 -7
  61. package/src/create-node-validate.ts +232 -15
  62. package/src/create-node-workdir.test.ts +298 -0
  63. package/src/create-node.ts +88 -23
  64. package/src/daemon-provider-snapshots.test.ts +445 -0
  65. package/src/daemon-provider-snapshots.ts +327 -0
  66. package/src/daemon-token-owner-http.test.ts +292 -0
  67. package/src/dashboard-slash-routing-http.test.ts +109 -0
  68. package/src/db-adapter-guard.test.ts +148 -0
  69. package/src/db-adapter-translate.test.ts +128 -0
  70. package/src/db-adapter.ts +377 -91
  71. package/src/db-timestamp.test.ts +38 -0
  72. package/src/db-timestamp.ts +15 -0
  73. package/src/db.ts +1264 -153
  74. package/src/delivered-without-push.test.ts +140 -0
  75. package/src/department-groups-http.test.ts +209 -0
  76. package/src/department-groups-sync-http.test.ts +328 -0
  77. package/src/department-groups.ts +434 -0
  78. package/src/department-heads-http.test.ts +350 -0
  79. package/src/department-heads.ts +226 -0
  80. package/src/departments-agent-count.test.ts +132 -0
  81. package/src/departments-http.test.ts +185 -0
  82. package/src/departments-mcp.test.ts +128 -0
  83. package/src/departments.ts +318 -0
  84. package/src/desktop-message-seam.test.ts +150 -0
  85. package/src/desktop-message.test.ts +368 -0
  86. package/src/dm-file-scope-http.test.ts +178 -0
  87. package/src/empty-node-sweeper.test.ts +104 -0
  88. package/src/empty-node-sweeper.ts +88 -0
  89. package/src/env-transport-gate-http.test.ts +240 -0
  90. package/src/env-transport-gate.ts +80 -0
  91. package/src/env-transport-policy.ts +56 -0
  92. package/src/etag-of.test.ts +57 -0
  93. package/src/event-loop-lag.test.ts +180 -0
  94. package/src/event-loop-lag.ts +201 -0
  95. package/src/expiry-counters.test.ts +111 -0
  96. package/src/expiry-counters.ts +93 -0
  97. package/src/ext-token-shared.test.ts +60 -0
  98. package/src/ext-validation-regression.test.ts +131 -0
  99. package/src/external-schedule-edits-http.test.ts +321 -0
  100. package/src/external-schedule-edits-timestamps.test.ts +64 -0
  101. package/src/external-schedule-edits.ts +327 -0
  102. package/src/file-download-authz-dev-open.test.ts +1 -1
  103. package/src/file-download-authz.test.ts +73 -18
  104. package/src/file-download-date-bucket.test.ts +8 -26
  105. package/src/file-network-scope-dev-open.test.ts +97 -0
  106. package/src/file-network-scope.test.ts +732 -0
  107. package/src/group-membership-events-http.test.ts +264 -0
  108. package/src/group-messages-http.test.ts +483 -0
  109. package/src/group-messages.ts +297 -0
  110. package/src/health-anon-readers.ts +60 -0
  111. package/src/health-host-disk-2756.test.ts +71 -0
  112. package/src/health-redaction.test.ts +1541 -7
  113. package/src/host-supervisor-identity-http.test.ts +152 -0
  114. package/src/host-supervisor-identity.ts +92 -0
  115. package/src/host-supervisors-daemon-version.test.ts +137 -0
  116. package/src/http-gzip.test.ts +94 -0
  117. package/src/http-gzip.ts +112 -0
  118. package/src/hub-catalog-read-http.test.ts +641 -0
  119. package/src/hub-provider-config.test.ts +166 -0
  120. package/src/hub-provider-config.ts +202 -0
  121. package/src/hub-timestamp.test.ts +38 -0
  122. package/src/hub-timestamp.ts +27 -0
  123. package/src/human-dm.ts +215 -0
  124. package/src/human-inbox.ts +42 -0
  125. package/src/inbox-caller.ts +49 -0
  126. package/src/inbox-count-sse.test.ts +310 -0
  127. package/src/inbox-count.ts +29 -0
  128. package/src/index.ts +6 -2
  129. package/src/license-state.test.ts +56 -0
  130. package/src/license-state.ts +48 -0
  131. package/src/list-host-supervisors.test.ts +15 -4
  132. package/src/mcp-context-cost-http.test.ts +127 -0
  133. package/src/mcp-inflight.test.ts +92 -0
  134. package/src/mcp-inflight.ts +38 -0
  135. package/src/mcp-projects-events-http.test.ts +165 -0
  136. package/src/mcp-route-label-http.test.ts +120 -0
  137. package/src/mcp-write-network-resolution.test.ts +435 -0
  138. package/src/member-audit-network-id-http.test.ts +93 -0
  139. package/src/member-presence-http.test.ts +210 -0
  140. package/src/messages-ack-by-agent-http.test.ts +142 -0
  141. package/src/migrate-sqlite-to-pg.test.ts +47 -0
  142. package/src/migrate-sqlite-to-pg.ts +263 -0
  143. package/src/model-auth-notify-http.test.ts +181 -0
  144. package/src/model-auth-notify.ts +116 -0
  145. package/src/network-name-http.test.ts +75 -0
  146. package/src/network-rules-http.test.ts +169 -0
  147. package/src/network-rules.ts +129 -0
  148. package/src/network-scope.ts +276 -0
  149. package/src/network-token-membership-http.test.ts +186 -0
  150. package/src/node-alias-control.ts +12 -0
  151. package/src/node-attrs.test.ts +47 -2
  152. package/src/node-caller-identity-http.test.ts +1108 -0
  153. package/src/node-create-request-status-http.test.ts +105 -0
  154. package/src/node-daemon-bindings.test.ts +132 -0
  155. package/src/node-daemon-bindings.ts +135 -0
  156. package/src/node-failure-alert.test.ts +150 -0
  157. package/src/node-failure-alert.ts +177 -0
  158. package/src/node-files-transport.test.ts +347 -0
  159. package/src/node-health-codex-login.test.ts +120 -0
  160. package/src/node-health-dispatch-http.test.ts +373 -0
  161. package/src/node-health-guard.ts +121 -0
  162. package/src/node-health-passthrough.test.ts +115 -0
  163. package/src/node-health-store.ts +101 -0
  164. package/src/node-id-alias.test.ts +190 -0
  165. package/src/node-identity-conflict-http.test.ts +269 -0
  166. package/src/node-identity-conflict.ts +142 -0
  167. package/src/node-identity-mismatch.test.ts +74 -0
  168. package/src/node-in-flight-tasks.ts +31 -0
  169. package/src/node-lifecycle-controllable.test.ts +64 -0
  170. package/src/node-lifecycle-controllable.ts +53 -0
  171. package/src/node-lifecycle-read-http.test.ts +257 -0
  172. package/src/node-lifecycle-read.ts +124 -0
  173. package/src/node-logs-transport.test.ts +263 -0
  174. package/src/node-peer-allowlist.test.ts +114 -0
  175. package/src/node-permissions-http.test.ts +728 -0
  176. package/src/node-permissions.ts +494 -0
  177. package/src/node-request-retention.test.ts +281 -0
  178. package/src/node-request-retention.ts +120 -0
  179. package/src/node-secret-rest-http.test.ts +190 -0
  180. package/src/node-serviceability.test.ts +86 -0
  181. package/src/node-serviceability.ts +124 -0
  182. package/src/node-session-control-http.test.ts +310 -0
  183. package/src/node-session-control.ts +258 -0
  184. package/src/node-skills-transport.test.ts +212 -0
  185. package/src/node-token-identity.ts +35 -0
  186. package/src/node-token-ownership.ts +51 -0
  187. package/src/node-token-privilege-http.test.ts +158 -0
  188. package/src/not-found-api-http.test.ts +67 -0
  189. package/src/observer-avatar-http.test.ts +102 -9
  190. package/src/observer-push.test.ts +76 -0
  191. package/src/opencode-catalog-report-http.test.ts +139 -0
  192. package/src/opencode-v2-catalog.test.ts +268 -0
  193. package/src/opencode-v2-catalog.ts +356 -0
  194. package/src/package-version-consistency.test.ts +25 -0
  195. package/src/parent-source-marker.test.ts +50 -0
  196. package/src/password-network-tokens.ts +25 -0
  197. package/src/peer-reply-atomic.test.ts +462 -0
  198. package/src/peer-reply-capability.test.ts +70 -0
  199. package/src/pg-worker.ts +87 -0
  200. package/src/poll-pacing.test.ts +74 -0
  201. package/src/poll-pacing.ts +123 -0
  202. package/src/project-dir-warn-clear-http.test.ts +132 -0
  203. package/src/project-viewer-can-http.test.ts +116 -0
  204. package/src/provider-tools-shape.test.ts +150 -0
  205. package/src/push.test.ts +20 -10
  206. package/src/push.ts +373 -9
  207. package/src/redact-tokens.test.ts +86 -0
  208. package/src/redact-tokens.ts +43 -0
  209. package/src/rejection-counters.test.ts +72 -0
  210. package/src/rejection-counters.ts +173 -0
  211. package/src/rename.ts +38 -10
  212. package/src/reply-target-derivation.test.ts +96 -0
  213. package/src/report-status-handover-capabilities-http.test.ts +124 -0
  214. package/src/report-status-host-schema.test.ts +235 -0
  215. package/src/report-status-resume-id-handover.test.ts +184 -0
  216. package/src/report-status-secret-keys.test.ts +140 -0
  217. package/src/require-explicit-test-db.ts +9 -0
  218. package/src/requirement-due-reminders-http.test.ts +620 -0
  219. package/src/requirement-due-reminders.ts +416 -0
  220. package/src/requirement-events-http.test.ts +318 -0
  221. package/src/requirement-events.test.ts +45 -0
  222. package/src/requirement-events.ts +144 -0
  223. package/src/requirement-notify.ts +165 -0
  224. package/src/requirement-participant-notify-http.test.ts +309 -0
  225. package/src/requirement-tag-ops-http.test.ts +454 -0
  226. package/src/requirement-tag-tree-http.test.ts +275 -0
  227. package/src/requirement-tag-tree.ts +127 -0
  228. package/src/requirement-tags.ts +102 -0
  229. package/src/requirements-abandoned-http.test.ts +236 -0
  230. package/src/requirements-assignee-drift.test.ts +154 -0
  231. package/src/requirements-comment-http.test.ts +174 -0
  232. package/src/requirements-completed-at-migration.test.ts +70 -0
  233. package/src/requirements-errors-mcp-http.test.ts +164 -0
  234. package/src/requirements-errors.ts +158 -0
  235. package/src/requirements-etag-http.test.ts +91 -0
  236. package/src/requirements-http.test.ts +709 -0
  237. package/src/requirements-last-event-http.test.ts +349 -0
  238. package/src/requirements-list-mcp-slim-http.test.ts +155 -0
  239. package/src/requirements-list-slim-http.test.ts +324 -0
  240. package/src/requirements-mcp.test.ts +164 -0
  241. package/src/requirements-migrate.ts +283 -0
  242. package/src/requirements-owner-strict-mcp-http.test.ts +145 -0
  243. package/src/requirements-people-http.test.ts +114 -0
  244. package/src/requirements-people-mcp-http.test.ts +231 -0
  245. package/src/requirements-people.ts +196 -0
  246. package/src/requirements-priority-lowest.test.ts +114 -0
  247. package/src/requirements-projects-network-echo.test.ts +57 -0
  248. package/src/requirements-projects-parent-http.test.ts +123 -0
  249. package/src/requirements-search-http.test.ts +182 -0
  250. package/src/requirements-search.test.ts +32 -0
  251. package/src/requirements-search.ts +145 -0
  252. package/src/requirements-seq-http.test.ts +193 -0
  253. package/src/requirements-seq-migration.test.ts +63 -0
  254. package/src/requirements-start-date.test.ts +125 -0
  255. package/src/requirements-stats-http.test.ts +357 -0
  256. package/src/requirements-stats.ts +195 -0
  257. package/src/requirements-status-participants-http.test.ts +222 -0
  258. package/src/requirements-upgrade-e2e.test.ts +126 -0
  259. package/src/requirements-upgrade-migration.test.ts +98 -0
  260. package/src/requirements.ts +2205 -0
  261. package/src/resolve-port.test.ts +57 -0
  262. package/src/resolve-port.ts +44 -0
  263. package/src/rest-alias-network-fallback-http.test.ts +123 -0
  264. package/src/rest-alias-network-fallback.test.ts +60 -0
  265. package/src/rest-alias-network-fallback.ts +65 -0
  266. package/src/rest-explicit-columns-http.test.ts +266 -0
  267. package/src/rest-identity.test.ts +130 -0
  268. package/src/rest-identity.ts +141 -0
  269. package/src/rest-projections.ts +72 -0
  270. package/src/rest-read-network-real-chain.test.ts +97 -0
  271. package/src/rest-write-network-resolution.test.ts +133 -0
  272. package/src/restart-readiness-http.test.ts +121 -0
  273. package/src/restricted-files.ts +76 -0
  274. package/src/retention-first-sweep-quiet.test.ts +31 -0
  275. package/src/retention.test.ts +100 -40
  276. package/src/retention.ts +423 -104
  277. package/src/route-callers-http.test.ts +120 -0
  278. package/src/route-timing.test.ts +218 -0
  279. package/src/route-timing.ts +262 -0
  280. package/src/rules-file-duplicate-alias.test.ts +234 -0
  281. package/src/rules-file-session-target.test.ts +207 -0
  282. package/src/rules-file-transport.test.ts +237 -0
  283. package/src/runtime-label.test.ts +22 -0
  284. package/src/runtime-label.ts +21 -0
  285. package/src/runtime-readiness.ts +90 -0
  286. package/src/schedule-agent-mcp-http.test.ts +475 -0
  287. package/src/schedule-agent.ts +252 -0
  288. package/src/schedule-starved.test.ts +92 -0
  289. package/src/schedule-starved.ts +114 -0
  290. package/src/scheduled-backoff-http.test.ts +203 -0
  291. package/src/scheduled-backoff.ts +64 -0
  292. package/src/scheduled-doorbell-nodeless-session.test.ts +134 -0
  293. package/src/scheduled-failure-backoff-2622.test.ts +145 -0
  294. package/src/scheduled-failure-code.test.ts +73 -0
  295. package/src/scheduled-failure-code.ts +105 -0
  296. package/src/scheduled-failures-http.test.ts +279 -0
  297. package/src/scheduled-failures.ts +425 -0
  298. package/src/scheduled-noprogress-backoff-2622.test.ts +163 -0
  299. package/src/scheduled-offline-backoff-probe.test.ts +56 -0
  300. package/src/scheduled-offline.test.ts +131 -0
  301. package/src/scheduled-offline.ts +66 -0
  302. package/src/scheduled-outcome-guidance-http.test.ts +139 -0
  303. package/src/scheduled-outcome-guidance.ts +9 -0
  304. package/src/scheduled-reply-unread-http.test.ts +212 -0
  305. package/src/scheduled-requirement-wake-http.test.ts +285 -0
  306. package/src/scheduled-requirement-wake.ts +125 -0
  307. package/src/scheduled-run-terminal.test.ts +290 -0
  308. package/src/scheduled-skip-blocking-task.test.ts +120 -0
  309. package/src/scheduled-skip-path-backoff-2622.test.ts +98 -0
  310. package/src/scheduled-stuck-http.test.ts +316 -0
  311. package/src/scheduled-stuck-notice-cap.test.ts +80 -0
  312. package/src/scheduled-stuck.ts +219 -0
  313. package/src/scheduled-tasks-http.test.ts +679 -0
  314. package/src/scheduled-tasks.ts +959 -0
  315. package/src/scheduled-work-outcome-http.test.ts +154 -0
  316. package/src/scheduled-work-outcome.ts +50 -0
  317. package/src/scoped-secrets.ts +141 -0
  318. package/src/secret-echo-negative-control.test.ts +118 -0
  319. package/src/send-dedup-request-id.test.ts +229 -0
  320. package/src/send-reply-agent-warning.test.ts +38 -38
  321. package/src/send-reply-alias-optional.test.ts +131 -0
  322. package/src/send-reply-attachments.test.ts +458 -0
  323. package/src/send_dedup.test.ts +54 -0
  324. package/src/send_dedup.ts +52 -6
  325. package/src/serve-error.test.ts +73 -0
  326. package/src/serve-error.ts +56 -0
  327. package/src/server.ts +5134 -503
  328. package/src/session-task-on-dispatch.ts +14 -0
  329. package/src/session-token-ownership-http.test.ts +122 -0
  330. package/src/shared/codex-inventory.ts +41 -0
  331. package/src/shared/daemon-provider-login.ts +31 -0
  332. package/src/shared/daemon-provider-snapshot.ts +52 -0
  333. package/src/shared/external-schedule-contract.ts +60 -0
  334. package/src/shared/node-name.test.ts +62 -0
  335. package/src/shared/node-name.ts +161 -0
  336. package/src/shared/probe-host-allowlist-drift.test.ts +45 -0
  337. package/src/shared/provider-application.ts +29 -0
  338. package/src/shared/provider-collection.ts +14 -0
  339. package/src/shared/provider-initialization.ts +8 -0
  340. package/src/shared/reserved-env-drift.test.ts +10 -0
  341. package/src/shared/scoped-secret-contract.ts +5 -0
  342. package/src/shared/task-content-limit-drift.test.ts +28 -0
  343. package/src/shared/task-content-limit.ts +25 -0
  344. package/src/side-thread-command-transport.test.ts +312 -0
  345. package/src/side-thread-command-transport.ts +318 -0
  346. package/src/side-thread-http-integration.test.ts +233 -0
  347. package/src/side-thread-http.ts +504 -0
  348. package/src/side-thread-production.test.ts +72 -0
  349. package/src/side-thread-production.ts +118 -0
  350. package/src/side-thread.test.ts +1067 -0
  351. package/src/side-thread.ts +2499 -0
  352. package/src/skillhub-http.test.ts +142 -0
  353. package/src/sqlite-close-checkpoint.test.ts +78 -0
  354. package/src/start-node.test.ts +265 -0
  355. package/src/stats-versions-http.test.ts +65 -0
  356. package/src/status-alias-filter-http.test.ts +106 -0
  357. package/src/status-alias-resolver-http.test.ts +163 -0
  358. package/src/status-alias-resolver.ts +19 -0
  359. package/src/status-node-id-filter-http.test.ts +161 -0
  360. package/src/status-read-cache-http.test.ts +229 -0
  361. package/src/status-read-cache.ts +129 -0
  362. package/src/stop-delete-node.test.ts +567 -1
  363. package/src/task-access-http.test.ts +402 -0
  364. package/src/task-access.ts +420 -0
  365. package/src/task-activity.ts +60 -0
  366. package/src/task-auth-origin-http.test.ts +93 -0
  367. package/src/task-auth-origin.test.ts +24 -0
  368. package/src/task-auth-origin.ts +7 -0
  369. package/src/task-consumption.test.ts +498 -0
  370. package/src/task-diagnostic-http.test.ts +149 -0
  371. package/src/task-diagnostic.test.ts +115 -0
  372. package/src/task-diagnostic.ts +118 -0
  373. package/src/task-expiry-notice-http.test.ts +287 -0
  374. package/src/task-expiry-notice.ts +318 -0
  375. package/src/task-idempotency-mcp.test.ts +142 -0
  376. package/src/task-idempotency.test.ts +76 -0
  377. package/src/task-idempotency.ts +81 -0
  378. package/src/task-late-replies.ts +54 -0
  379. package/src/task-late-reply-http.test.ts +227 -0
  380. package/src/task-lifecycle-watcher-busy.test.ts +114 -0
  381. package/src/task-lifecycle-watcher.test.ts +209 -0
  382. package/src/task-lifecycle-watcher.ts +109 -0
  383. package/src/task-network-resolution-http.test.ts +140 -0
  384. package/src/task-offline-delivery-2668.test.ts +119 -0
  385. package/src/task-offline-delivery.ts +81 -0
  386. package/src/task-orphan-http.test.ts +287 -0
  387. package/src/task-orphan.ts +119 -0
  388. package/src/task-queue-ahead-http.test.ts +309 -0
  389. package/src/task-queue-ahead-scale.test.ts +236 -0
  390. package/src/task-queue-ahead.ts +186 -0
  391. package/src/task-rejection-log-http.test.ts +160 -0
  392. package/src/task-rejection-log.ts +61 -0
  393. package/src/task-sender-http.test.ts +143 -0
  394. package/src/task-stale-open-http.test.ts +292 -0
  395. package/src/task-stale-open.ts +103 -0
  396. package/src/tasks-pagination-http.test.ts +141 -0
  397. package/src/team-rules-status-http.test.ts +90 -0
  398. package/src/team-rules-status.test.ts +59 -0
  399. package/src/team-rules-status.ts +72 -0
  400. package/src/tmux-allowlist.test.ts +48 -0
  401. package/src/tool-audience-http.test.ts +230 -0
  402. package/src/tool-audience.ts +127 -0
  403. package/src/tools-list-json-schema.test.ts +94 -0
  404. package/src/tools.ts +4326 -420
  405. package/src/upload-early-reject-guard.test.ts +155 -0
  406. package/src/uploads-http.test.ts +86 -7
  407. package/src/uploads.ts +38 -4
  408. package/src/user-avatar-http.test.ts +74 -0
  409. package/src/user-avatar-image.ts +160 -0
  410. package/src/user-avatar-migration.test.ts +25 -0
  411. package/src/user-avatar-upload-http.test.ts +348 -0
  412. package/src/user-inbox-by-agent-http.test.ts +165 -0
  413. package/src/user-inbox-netid-notnull.test.ts +122 -0
  414. package/src/user-inbox-read-http.test.ts +223 -0
  415. package/src/user-inbox-schema.test.ts +54 -0
  416. package/src/version-stats.test.ts +66 -0
  417. package/src/version-stats.ts +109 -0
@@ -0,0 +1,57 @@
1
+ import { expect, test } from "bun:test";
2
+ import { DEFAULT_PORT, resolvePort } from "./resolve-port";
3
+
4
+ // The whole reason this module exists.
5
+ test("PORT=0 means an ephemeral port, not the production default", () => {
6
+ expect(resolvePort("0")).toBe(0);
7
+ expect(resolvePort("0")).not.toBe(DEFAULT_PORT);
8
+ });
9
+
10
+ test("unset or empty falls back to the default", () => {
11
+ expect(resolvePort(undefined)).toBe(DEFAULT_PORT);
12
+ expect(resolvePort("")).toBe(DEFAULT_PORT);
13
+ expect(resolvePort(" ")).toBe(DEFAULT_PORT);
14
+ });
15
+
16
+ test("surrounding whitespace is tolerated — it is trimmed, not treated as malformed", () => {
17
+ expect(resolvePort(" 9201 ")).toBe(9201);
18
+ expect(resolvePort("\t0\n")).toBe(0);
19
+ });
20
+
21
+ test("an explicit port is used verbatim", () => {
22
+ expect(resolvePort("9201")).toBe(9201);
23
+ expect(resolvePort("1")).toBe(1);
24
+ expect(resolvePort("65535")).toBe(65535);
25
+ });
26
+
27
+ // Defaulting on a malformed value means a typo silently starts the server on
28
+ // the production port — on this fleet, on top of the running Hub.
29
+ test("a malformed value is rejected, never quietly defaulted", () => {
30
+ for (const bad of ["abc", "80a", "-1", "65536", "1.5", "0x10", "NaN", "Infinity", "9 200", "+80"]) {
31
+ expect(() => resolvePort(bad)).toThrow();
32
+ }
33
+ });
34
+
35
+ test("the rejection names the value and the accepted range", () => {
36
+ try {
37
+ resolvePort("abc");
38
+ throw new Error("should have thrown");
39
+ } catch (e: any) {
40
+ expect(e.message).toContain("abc");
41
+ expect(e.message).toContain("0 and 65535");
42
+ expect(e.message).toContain("ephemeral");
43
+ }
44
+ });
45
+
46
+ test("a caller can override the fallback without touching the default", () => {
47
+ expect(resolvePort(undefined, 3000)).toBe(3000);
48
+ expect(resolvePort("0", 3000)).toBe(0);
49
+ });
50
+
51
+ test("server.ts resolves PORT through this module, not through `|| DEFAULT`", () => {
52
+ const src = require("fs").readFileSync(require("path").join(import.meta.dir, "server.ts"), "utf8");
53
+ const code = src.split("\n").filter((l: string) => !l.trim().startsWith("//")).join("\n");
54
+ expect(code).toContain("resolvePort(process.env.PORT)");
55
+ // `Number(env) || default` is the exact shape that swallowed the 0.
56
+ expect(code).not.toMatch(/Number\(process\.env\.PORT\)\s*\|\|/);
57
+ });
@@ -0,0 +1,44 @@
1
+ // Resolve the listen port from the environment.
2
+ //
3
+ // `Number(process.env.PORT) || 9200` swallows a legitimate `0`. `Number("0")`
4
+ // is `0`, which is falsy, so `PORT=0` — the conventional way to ask the OS for
5
+ // an ephemeral port — silently became 9200, the production Hub port.
6
+ //
7
+ // Three consequences, and the middle one is the worst:
8
+ //
9
+ // 1. On a host where 9200 is already taken (a running Hub), a test that sets
10
+ // PORT=0 dies with EADDRINUSE and reads as a product bug.
11
+ // task-lifecycle-watcher.test.ts fails on main today for exactly this.
12
+ // 2. On a host where 9200 is FREE, the same test passes — by binding 9200.
13
+ // It is green because it grabbed the production port, not because PORT=0
14
+ // worked. Green for the wrong reason is worse than red.
15
+ // 3. Anyone asking for an ephemeral port gets the production port instead.
16
+ //
17
+ // The file already knew: `bootServer` uses `opts.port ?? PORT` with a comment
18
+ // saying `||` "would swallow a legitimate 0". The rule was one level up from
19
+ // where it was needed.
20
+ //
21
+ // A malformed value is rejected rather than defaulted. Falling back to 9200 on
22
+ // `PORT=abc` means a typo silently starts the server somewhere the operator did
23
+ // not ask for — and on this fleet that somewhere is production.
24
+
25
+ export const DEFAULT_PORT = 9200;
26
+
27
+ export function resolvePort(raw: string | undefined, fallback = DEFAULT_PORT): number {
28
+ // Unset or empty means "not specified". An empty string is what a shell
29
+ // exports for an unset variable it still passes along, so treating it as 0
30
+ // would make `PORT= anet hub start` bind an ephemeral port by accident.
31
+ if (raw === undefined || raw.trim() === "") return fallback;
32
+
33
+ // Decimal digits only, after trimming. `Number()` alone accepts "0x10" (16)
34
+ // and " 9200 ", so a value that does not look like a port would still resolve
35
+ // to one — quietly, and to a different number than the operator typed.
36
+ const text = raw.trim();
37
+ const n = /^\d+$/.test(text) ? Number(text) : NaN;
38
+ if (!Number.isInteger(n) || n < 0 || n > 65535) {
39
+ throw new Error(
40
+ `PORT must be an integer between 0 and 65535 (0 asks the OS for an ephemeral port); got ${JSON.stringify(raw)}`,
41
+ );
42
+ }
43
+ return n;
44
+ }
@@ -0,0 +1,123 @@
1
+ // #1974 —— 多网络账号给「另一个网络里的 Agent」发消息,hub 侧也要能发出去。
2
+ //
3
+ // 起因(admin 2026-10-21 截图 + hub 拒绝日志):
4
+ // [15:55:54] tang → /api/task → tang02: REJECTED 404 alias_not_found (net=net_ac567b4ab74e)
5
+ //
6
+ // 客户端的 Agent 列表是跨网络的(GET /api/status?light=1 不带 network_id ⇒ 返回调用者所属的
7
+ // 全部网络),发送却带着「登录时选的那一个网络」。这里用真实 HTTP + 临时库复现那个形状:
8
+ // * admin 拥有 NET_A,里面有 Agent `cross-agent`;
9
+ // * tang 注册 ⇒ 自己的个人网络 NET_B(owner),同时是 NET_A 的 admin 成员(agent_access 'all');
10
+ // * tang 用 NET_B 发给 `cross-agent` ⇒ 修之前 404 alias_not_found,修之后送达 NET_A。
11
+ //
12
+ // 三条红线各有断言:同名在两个网络都有 ⇒ 不猜(仍 404);没授权的网络 ⇒ 不去;不存在的 alias ⇒ 404。
13
+
14
+ import { describe, expect, test, beforeAll, afterAll } from "bun:test";
15
+ import { mkdtempSync, rmSync } from "node:fs";
16
+ import { join } from "node:path";
17
+ import { tmpdir } from "node:os";
18
+ import { addNetworkMember, register } from "./auth.js";
19
+ import { db } from "./db.js";
20
+
21
+ const DIR = mkdtempSync(join(tmpdir(), "anet-1974-alias-net-"));
22
+ let BASE = "";
23
+ let hub: any = null;
24
+ const PW = "AliasNetPassw0rd!x";
25
+ let NET_A = "";
26
+ let NET_B = "";
27
+ let tangToken = "";
28
+ let tangUserId = "";
29
+
30
+ const stamp = Date.now();
31
+
32
+ let sessionSeq = 0;
33
+ function insertSession(alias: string, networkId: string, nodeId: string | null = null) {
34
+ sessionSeq += 1;
35
+ db.run(
36
+ `INSERT INTO sessions (resume_id, alias, node_id, network_id, status, updated_at, last_seen_at)
37
+ VALUES (?1, ?2, ?3, ?4, 'idle', datetime('now'), datetime('now'))`,
38
+ [`resume_${alias}_${stamp}_${sessionSeq}`, alias, nodeId, networkId],
39
+ );
40
+ }
41
+
42
+ async function postTask(token: string, body: any) {
43
+ const res = await fetch(`${BASE}/api/task`, {
44
+ method: "POST",
45
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}` },
46
+ body: JSON.stringify(body),
47
+ });
48
+ const text = await res.text();
49
+ let json: any = text;
50
+ try { json = JSON.parse(text); } catch { /* keep text */ }
51
+ return { status: res.status, json };
52
+ }
53
+
54
+ beforeAll(async () => {
55
+ process.env.COMMHUB_DB ||= join(DIR, "hub.db");
56
+ process.env.COMMHUB_UPLOADS_DIR = join(DIR, "uploads");
57
+ process.env.HOST = "127.0.0.1";
58
+
59
+ const admin = register(`aliasnet_admin_${stamp}`, PW, undefined, "Admin");
60
+ expect(admin.ok).toBe(true);
61
+ NET_A = admin.network_id!;
62
+ db.run("UPDATE users SET role = 'admin' WHERE user_id = ?1", [admin.user!.user_id]);
63
+
64
+ // admin 名下的 Agent:只在 NET_A 里。
65
+ insertSession("cross-agent", NET_A, `node_cross_${stamp}`);
66
+
67
+ // tang:自己的个人网络 NET_B(owner)+ NET_A 的 admin 成员(两个网络 agent_access 都是 'all',
68
+ // 这正是现网 tang 的形状:owner 个人网络 + admin 团队网络)。
69
+ const tang = register(`aliasnet_tang_${stamp}`, PW, undefined, "Tang");
70
+ expect(tang.ok).toBe(true);
71
+ NET_B = tang.network_id!;
72
+ tangToken = tang.token!;
73
+ tangUserId = tang.user!.user_id;
74
+ expect(addNetworkMember(NET_A, tangUserId, "admin", admin.user!.user_id, { agentAccess: "all" }).ok).toBe(true);
75
+
76
+ // 同名 alias 在**请求的网络之外**的两个网络里都有 ⇒ 不猜。
77
+ // 需要第三个网络:另一个用户建自己的网络,tang 也是它的成员。
78
+ const third = register(`aliasnet_third_${stamp}`, PW, undefined, "Third");
79
+ expect(third.ok).toBe(true);
80
+ const NET_C = third.network_id!;
81
+ expect(addNetworkMember(NET_C, tangUserId, "member", third.user!.user_id, { agentAccess: "all" }).ok).toBe(true);
82
+ insertSession("twin-agent", NET_A, `node_twin_a_${stamp}`);
83
+ insertSession("twin-agent", NET_C, `node_twin_c_${stamp}`);
84
+
85
+ const mod: any = await import("./server.js");
86
+ hub = mod.bootServer({ port: 0, hostname: "127.0.0.1" });
87
+ BASE = `http://127.0.0.1:${hub.port}`;
88
+ });
89
+
90
+ afterAll(() => {
91
+ try { hub?.stop?.(); } catch { /* ignore */ }
92
+ try { rmSync(DIR, { recursive: true, force: true }); } catch { /* ignore */ }
93
+ });
94
+
95
+ describe("POST /api/task across the caller's own networks (#1974)", () => {
96
+ test("an alias in the caller's other network is delivered there, not 404", async () => {
97
+ const res = await postTask(tangToken, { alias: "cross-agent", task: "hi", network_id: NET_B });
98
+ expect(res.status).toBe(200);
99
+ expect(res.json.ok).toBe(true);
100
+ // 落在 NET_A(那个 alias 真正所在的网络),不是请求里带的 NET_B。
101
+ expect(res.json.actual_to?.network_id ?? res.json.actual_to?.networkId).toBe(NET_A);
102
+ const row = db.get<{ network_id: string }>("SELECT network_id FROM tasks WHERE task_id = ?1", [res.json.task_id]);
103
+ expect(row?.network_id).toBe(NET_A);
104
+ });
105
+
106
+ test("the same alias in two of the caller's networks is not guessed", async () => {
107
+ const res = await postTask(tangToken, { alias: "twin-agent", task: "hi", network_id: NET_B });
108
+ expect(res.status).toBe(404);
109
+ expect(res.json.error).toBe("alias_not_found");
110
+ });
111
+
112
+ test("an alias nobody has is still 404", async () => {
113
+ const res = await postTask(tangToken, { alias: "nowhere-agent", task: "hi", network_id: NET_B });
114
+ expect(res.status).toBe(404);
115
+ expect(res.json.error).toBe("alias_not_found");
116
+ });
117
+
118
+ test("the requested network still wins when it has the alias", async () => {
119
+ const res = await postTask(tangToken, { alias: "cross-agent", task: "hi2", network_id: NET_A });
120
+ expect(res.status).toBe(200);
121
+ expect(res.json.actual_to?.network_id ?? res.json.actual_to?.networkId).toBe(NET_A);
122
+ });
123
+ });
@@ -0,0 +1,60 @@
1
+ // #1974 —— alias 不在请求的网络里、但在调用者另一个网络里(且唯一)时,发到那儿去。
2
+ //
3
+ // 三条红线各有���一条断言:只找调用者已加入的网络、同名不猜、没权限不换。
4
+ import { describe, expect, test } from "bun:test";
5
+ import { pickAliasNetwork } from "./rest-alias-network-fallback.js";
6
+
7
+ const base = {
8
+ alias: "tang02",
9
+ requestedNetworkId: "net_own",
10
+ memberNetworkIds: ["net_own", "net_team"],
11
+ networksWithAlias: ["net_team"],
12
+ canWrite: () => true,
13
+ canMessage: () => true,
14
+ };
15
+
16
+ describe("pickAliasNetwork (#1974)", () => {
17
+ test("the alias lives in exactly one other member network ⇒ use it", () => {
18
+ expect(pickAliasNetwork({ ...base })).toBe("net_team");
19
+ });
20
+
21
+ test("the alias is in the requested network too ⇒ do not switch", () => {
22
+ expect(pickAliasNetwork({ ...base, networksWithAlias: ["net_own", "net_team"] })).toBeNull();
23
+ });
24
+
25
+ test("the same alias in two other networks ⇒ do not guess", () => {
26
+ expect(pickAliasNetwork({
27
+ ...base,
28
+ memberNetworkIds: ["net_own", "net_a", "net_b"],
29
+ networksWithAlias: ["net_a", "net_b"],
30
+ })).toBeNull();
31
+ });
32
+
33
+ test("a network the caller does not belong to is never used", () => {
34
+ expect(pickAliasNetwork({
35
+ ...base,
36
+ memberNetworkIds: ["net_own"],
37
+ networksWithAlias: ["net_team"],
38
+ })).toBeNull();
39
+ });
40
+
41
+ test("no write access in that network ⇒ keep the 404", () => {
42
+ expect(pickAliasNetwork({ ...base, canWrite: () => false })).toBeNull();
43
+ });
44
+
45
+ test("no message permission in that network ⇒ keep the 404", () => {
46
+ expect(pickAliasNetwork({ ...base, canMessage: () => false })).toBeNull();
47
+ });
48
+
49
+ test("the alias is nowhere ⇒ keep the 404", () => {
50
+ expect(pickAliasNetwork({ ...base, networksWithAlias: [] })).toBeNull();
51
+ });
52
+
53
+ test("no membership at all ⇒ keep the 404", () => {
54
+ expect(pickAliasNetwork({ ...base, memberNetworkIds: [] })).toBeNull();
55
+ });
56
+
57
+ test("an empty alias is never sent anywhere", () => {
58
+ expect(pickAliasNetwork({ ...base, alias: " " })).toBeNull();
59
+ });
60
+ });
@@ -0,0 +1,65 @@
1
+ // #1974 —— 「alias 不在请求的网络里」时,发到调用者**另一个**网络里那个 alias 所在的网络。
2
+ //
3
+ // 起因(admin 2026-10-21 截图 + hub 拒绝日志):
4
+ // [15:55:54] tang → /api/task → tang02: REJECTED 404 alias_not_found (net=net_ac567b4ab74e)
5
+ //
6
+ // 客户端的 Agent 列表是**跨网络**的:`GET /api/status?light=1` 不带 network_id,
7
+ // hub 就按「调用者属于哪些网络」返回。tang 因此同时看到默认网络(net_399bdf86f528)的
8
+ // tang02/03/04 和自己个人网络(net_ac567b4ab74e)里的 Agent。发送却带着「登录时选定的
9
+ // 那一个网络」—— 多网络账号(自己网络的 owner + 团队网络的 admin)两个网络对它都是
10
+ // agent_access='all',pickDefaultNetworkId 于是选中了自己的个人网络 ⇒ 给团队网络的
11
+ // Agent 发消息一律 404 alias_not_found,客户端只显示「没有找到这个 Agent」+「未送达」。
12
+ //
13
+ // 客户端侧已有修法(用 alias 所在网络发),但那只在**新客户端**里生效;已经在用的旧客户端
14
+ // 仍然发不出去。这里补 Hub 侧:alias 唯一地存在于调用者的另一个网络、且调用者在那个网络
15
+ // 有写权限 ⇒ 就发到那儿去。旧客户端立刻受益,不用等升级。
16
+ //
17
+ // 三条红线:
18
+ // ① 只在调用者**已加入**的网络里找(不跨租户、不做 alias 探测);
19
+ // ② 同一个 alias 在调用者的多个网络里都存在 ⇒ **不猜**,保持 404;
20
+ // ③ 调用者在目标网络没有写权限(受限成员没被授权这个 Agent)⇒ 保持 404/403。
21
+ //
22
+ // 纯函数:不碰 db、不碰 http,好测。
23
+
24
+ export interface AliasNetworkFallbackInput {
25
+ /** 请求里带的 alias(已按请求网络 canonical 化)。 */
26
+ alias: string;
27
+ /** 请求带/推出的那个网络。 */
28
+ requestedNetworkId: string | null;
29
+ /** 调用者所属的全部网络。 */
30
+ memberNetworkIds: readonly string[];
31
+ /** 上面这些网络里,真的存在这个 alias 的网络(去重后)。 */
32
+ networksWithAlias: readonly string[];
33
+ /** 调用者在这个网络能不能写。 */
34
+ canWrite: (networkId: string) => boolean;
35
+ /** 调用者能不能给这个 alias 发消息(受限成员的 Agent 授权)。 */
36
+ canMessage: (networkId: string) => boolean;
37
+ }
38
+
39
+ /**
40
+ * 该发到哪个网络?返回 null = 保持原来的 404。
41
+ *
42
+ * 只在「请求的网络里没有这个 alias」时才会换网络;请求网络里有 ⇒ 传 requestedNetworkId
43
+ * 之外一律不动(调用方只在 not_found 时才问这个函数)。
44
+ */
45
+ export function pickAliasNetwork(input: AliasNetworkFallbackInput): string | null {
46
+ const alias = (input.alias ?? '').trim();
47
+ if (!alias) return null;
48
+ const requested = (input.requestedNetworkId ?? '').trim();
49
+ const members = new Set((input.memberNetworkIds ?? []).map(n => (n ?? '').trim()).filter(Boolean));
50
+ if (members.size === 0) return null;
51
+
52
+ // 请求的网络里本来就有这个 alias ⇒ 不换网络(它就在那儿,不用猜)。
53
+ const withAlias = [...new Set((input.networksWithAlias ?? []).map(n => (n ?? '').trim()).filter(Boolean))];
54
+ if (requested && withAlias.includes(requested)) return null;
55
+ // 候选 = 调用者所属、且真的有这个 alias 的网络;请求网络本身不算。
56
+ const candidates = withAlias.filter(n => n !== requested && members.has(n));
57
+ if (candidates.length === 0) return null;
58
+ // 多个网络都有同名 alias ⇒ 不猜(alias 探测的防线)。
59
+ if (candidates.length > 1) return null;
60
+
61
+ const only = candidates[0];
62
+ if (!input.canWrite(only)) return null;
63
+ if (!input.canMessage(only)) return null;
64
+ return only;
65
+ }
@@ -0,0 +1,266 @@
1
+ import { afterAll, beforeAll, describe, expect, test } from "bun:test";
2
+ import { mkdtempSync, rmSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+
6
+ const PRIVATE_DB_DIR = mkdtempSync(join(tmpdir(), "anet-rest-columns-"));
7
+ process.env.COMMHUB_DB ||= join(PRIVATE_DB_DIR, "hub.db");
8
+
9
+ let db: typeof import("./db.js").db;
10
+ let server: ReturnType<typeof Bun.serve>;
11
+ let base = "";
12
+ let token = "";
13
+ let networkId = "";
14
+
15
+ const INTERNAL_SENTINEL = "future_internal_only";
16
+ const sortedKeys = (value: Record<string, unknown>): string[] => Object.keys(value).sort();
17
+ const sorted = (values: readonly string[]): string[] => [...values].sort();
18
+
19
+ // Independent wire-contract golden. Do not derive these expectations from
20
+ // rest-projections.ts: doing so makes a deleted projection column disappear
21
+ // from both the response and the expected value, producing a false green.
22
+ const GOLDEN_RESPONSE_KEYS = {
23
+ networkList: [
24
+ "network_id", "network_name", "owner_id", "description", "settings",
25
+ "created_at", "updated_at", "visibility", "max_members", "member_role", "name",
26
+ ],
27
+ // 🔴 #1097:GET /api/auth/me 走的是 auth.ts 的 getUserAllNetworks(),
28
+ // 与 GET /api/networks 的 admin 分支**不是同一条查询**。
29
+ // server.ts:985 直接返回原始行,没有 :1166 那个 withNetworkNameAlias,
30
+ // 所以比 networkList 少一个 "name"。这里逐字写死,不从 rest-projections.ts 推导
31
+ // —— 理由见本文件顶部:从投影推导会让被删掉的列同时从响应和期望里消失,产生假绿。
32
+ authMeNetwork: [
33
+ "network_id", "network_name", "owner_id", "description", "settings",
34
+ "created_at", "updated_at", "visibility", "max_members", "member_role", "agent_access", "task_access",
35
+ // RFC-040(#455):不是列,是每次请求现算的「我负责的部门 + 全部下级」(department-heads.ts)。
36
+ "managed_department_ids",
37
+ ],
38
+ networkDetail: [
39
+ "network_id", "network_name", "owner_id", "description", "settings",
40
+ "created_at", "updated_at", "visibility", "max_members",
41
+ ],
42
+ statusSession: [
43
+ "resume_id", "alias", "tmux_name", "server", "ip", "hostname", "agent",
44
+ "project_dir", "version", "status", "task", "output", "progress", "score",
45
+ "cpu_load_1min", "cpu_cores", "mem_total_gb", "mem_used_gb", "mem_avail_gb",
46
+ "disk_total_gb", "disk_used_gb", "disk_avail_gb", "process_rss_bytes",
47
+ "process_rss_mb", "process_cpu_pct", "process_uptime_seconds",
48
+ "process_in_flight_count", "network_id", "registered_at", "updated_at",
49
+ "node_id", "session_id", "config_path", "channels", "last_seen_at", "model",
50
+ "external_schedules", "rules_file_capable", "skills_capable", "files_capable", "logs_capable", "runtime", "host", "process_telemetry",
51
+ // #448 — layered node health (memory-only; null when not reported or stale).
52
+ "health", "health_observed_ms_ago",
53
+ // #500 step 2 — open tasks on that node (task-queue-ahead.ts); full projection only.
54
+ "queue_depth",
55
+ ],
56
+ task: [
57
+ "task_id", "from_node_id", "from_name", "to_node_id", "to_name", "priority",
58
+ "status", "content", "result", "in_reply_to", "requires_response", "scope",
59
+ "created_at", "delivered_at", "started_at", "runtime_submitted_at", "consumed_at",
60
+ "completed_at", "expires_at", "network_id", "parent_task_id", "meta_json",
61
+ "thread_id", "turn_id", "late_replies",
62
+ ],
63
+ audit: [
64
+ "id", "user_id", "username", "action", "target_type", "target_id", "detail",
65
+ "ip", "network_id", "created_at",
66
+ ],
67
+ taskEvent: [
68
+ "id", "task_id", "from_status", "to_status", "event_type", "actor", "detail",
69
+ "created_at", "network_id",
70
+ ],
71
+ completion: [
72
+ "id", "session_name", "task", "result", "artifacts", "score",
73
+ "duration_minutes", "network_id", "completed_at",
74
+ ],
75
+ scheduledTask: [
76
+ "schedule_id", "network_id", "name", "target_node_id", "target_alias",
77
+ "task_content", "priority", "schedule_type", "timezone", "overlap_policy",
78
+ "misfire_policy", "status", "next_run_at", "last_run_at", "revision",
79
+ "created_at", "updated_at", "schedule", "watchers", "is_watcher", "can_edit", "can_manage_watchers",
80
+ ],
81
+ } as const;
82
+
83
+ async function api(path: string): Promise<any> {
84
+ const response = await fetch(`${base}${path}`, {
85
+ headers: { Authorization: `Bearer ${token}` },
86
+ });
87
+ expect(response.status).toBe(200);
88
+ return response.json();
89
+ }
90
+
91
+ // 30s 而不是 bun 默认的 5s:这个 hook 跑 register()(KDF)+bootServer(),
92
+ // 本机空载基线 ~620ms,而 2026-08-17 与 2026-08-31 两次 CI 上它被 5s 上限打死
93
+ // (0 pass / 1 fail / Ran 1 test —— 见 #928、#1627)。5247ms 是**被截断的下界**,
94
+ // 不是测量值,所以余量按基线的 ~48x 取,而不是按那个数取。
95
+ beforeAll(async () => {
96
+ ({ db } = await import("./db.js"));
97
+ const { register } = await import("./auth.js");
98
+ const auth = register(`rest_shape_${Date.now()}`, "RestShape-Strong-1!", undefined, "rest-shape");
99
+ expect(auth.ok).toBe(true);
100
+ token = auth.token!;
101
+ networkId = auth.network_id!;
102
+
103
+ // Simulate future migrations. Any REST SELECT * silently broadcasts these
104
+ // columns; every endpoint below must keep them private without needing a
105
+ // code change when the table grows.
106
+ for (const table of ["networks", "sessions", "audit_log", "task_events", "tasks", "completions", "scheduled_tasks"]) {
107
+ db.exec(`ALTER TABLE ${table} ADD COLUMN ${INTERNAL_SENTINEL} TEXT`);
108
+ }
109
+
110
+ db.run(
111
+ `INSERT INTO sessions (resume_id, alias, status, agent, model, network_id, external_schedules)
112
+ VALUES ('resume-rest-shape', 'rest-shape-node', 'idle', 'agent-node:codex', 'gpt-shape', ?1, ?2)`,
113
+ [networkId, JSON.stringify({ observed_at: "2026-08-10T02:00:00.000Z", schedules: [] })],
114
+ );
115
+ db.run(
116
+ `INSERT INTO tasks (task_id, from_name, to_name, status, content, priority, network_id, parent_task_id, meta_json)
117
+ VALUES ('task-rest-shape', 'sender', 'rest-shape-node', 'delivered', 'shape', 'normal', ?1, 'parent-shape', '{"attachment":true}')`,
118
+ [networkId],
119
+ );
120
+ db.run(
121
+ `INSERT INTO task_events (task_id, from_status, to_status, actor, detail, network_id)
122
+ VALUES ('task-rest-shape', 'created', 'delivered', 'shape-test', 'shape', ?1)`,
123
+ [networkId],
124
+ );
125
+ db.run(
126
+ `INSERT INTO completions (id, session_name, task, result, network_id)
127
+ VALUES ('completion-rest-shape', 'rest-shape-node', 'shape', 'done', ?1)`,
128
+ [networkId],
129
+ );
130
+ db.run(
131
+ `INSERT INTO audit_log (user_id, username, action, target_type, target_id, detail, ip, network_id)
132
+ VALUES ((SELECT owner_id FROM networks WHERE network_id = ?1), 'shape-user', 'shape_action', 'shape', 'shape-id', 'shape', '127.0.0.1', ?1)`,
133
+ [networkId],
134
+ );
135
+ db.run(
136
+ `INSERT INTO scheduled_tasks
137
+ (schedule_id, network_id, created_by, name, target_node_id, target_alias,
138
+ task_content, schedule_type, schedule_json, timezone, next_run_at)
139
+ VALUES ('schedule-rest-shape', ?1, 'private-user-id', 'shape schedule',
140
+ 'node-rest-shape', 'rest-shape-node', 'shape task', 'interval',
141
+ '{"type":"interval","every_seconds":3600}', 'UTC', '2099-01-01T00:00:00.000Z')`,
142
+ [networkId],
143
+ );
144
+
145
+ const mod = await import("./server.js");
146
+ server = mod.bootServer({ port: 0, hostname: "127.0.0.1" });
147
+ base = `http://127.0.0.1:${server.port}`;
148
+ }, 30_000);
149
+
150
+ afterAll(() => {
151
+ try { server?.stop(true); } catch {}
152
+ try { rmSync(PRIVATE_DB_DIR, { recursive: true, force: true }); } catch {}
153
+ });
154
+
155
+ describe("#311 REST response projections are stable across future ALTER TABLE", () => {
156
+ test("network list and detail preserve their existing public keys", async () => {
157
+ const list = await api("/api/networks");
158
+ const row = list.networks.find((item: any) => item.network_id === networkId);
159
+ expect(sortedKeys(row)).toEqual(sorted(GOLDEN_RESPONSE_KEYS.networkList));
160
+ expect(row[INTERNAL_SENTINEL]).toBeUndefined();
161
+
162
+ const detail = await api(`/api/networks/${networkId}`);
163
+ expect(sortedKeys(detail.network)).toEqual(sorted(GOLDEN_RESPONSE_KEYS.networkDetail));
164
+ expect(detail.network[INTERNAL_SENTINEL]).toBeUndefined();
165
+ });
166
+
167
+ // 🔴 #1097:这条补的是 test647 抓到的一个**真覆盖洞**。
168
+ // tests/test647-rest-explicit-columns 的 L3b 变异把 auth.ts 的
169
+ // `SELECT ${sqlColumns(NETWORK_REST_COLUMNS, "n")}, nm.role as member_role`
170
+ // 改成 `SELECT n.*, …`,而**整套测试仍然全绿** —— 因为 getUserAllNetworks()
171
+ // 只在两处可达:server.ts:985(GET /api/auth/me) 与 server.ts:1165
172
+ // (GET /api/networks 的三元 **else** 分支),而上面那条测试打的是 /api/networks
173
+ // 且它的用户走 **if** 分支(:1156-1162 的内联查询)⇒ 两条可达路径一条都没覆盖。
174
+ test("auth/me networks come from an explicit column list, not SELECT *", async () => {
175
+ const me = await api("/api/auth/me");
176
+ const row = me.networks.find((item: any) => item.network_id === networkId);
177
+ expect(row).toBeDefined();
178
+ expect(sortedKeys(row)).toEqual(sorted(GOLDEN_RESPONSE_KEYS.authMeNetwork));
179
+ expect(row[INTERNAL_SENTINEL]).toBeUndefined();
180
+ });
181
+
182
+ test("full status preserves telemetry compatibility without storage drift", async () => {
183
+ const body = await api(`/api/status?network_id=${networkId}`);
184
+ const row = body.sessions.find((item: any) => item.alias === "rest-shape-node");
185
+ expect(sortedKeys(row)).toEqual(sorted(GOLDEN_RESPONSE_KEYS.statusSession));
186
+ expect(row[INTERNAL_SENTINEL]).toBeUndefined();
187
+ expect(row.external_schedules).toEqual({ observed_at: "2026-08-10T02:00:00.000Z", schedules: [] });
188
+ });
189
+
190
+ test("task list and task detail expose the same explicit contract", async () => {
191
+ const list = await api(`/api/tasks?network_id=${networkId}&task_id=task-rest-shape&skip_stats=1`);
192
+ expect(sortedKeys(list.tasks[0])).toEqual(sorted(GOLDEN_RESPONSE_KEYS.task));
193
+ expect(list.tasks[0][INTERNAL_SENTINEL]).toBeUndefined();
194
+
195
+ const detail = await api(`/api/tasks/task-rest-shape?network_id=${networkId}`);
196
+ expect(sortedKeys(detail.task)).toEqual(sorted(GOLDEN_RESPONSE_KEYS.task));
197
+ expect(detail.task[INTERNAL_SENTINEL]).toBeUndefined();
198
+ });
199
+
200
+ // #2884 —— 共享会话忙的失败:任务详情/列表要把「排队」与「会话等待」分开报。
201
+ // 现场那条 412 分钟的任务**不是排程任务**(scheduled_task_runs 里没有它),
202
+ // 所以投影必须落在任务读端点,不能只改排程 run。
203
+ test("#2884 busy failures expose queue vs session-wait split (non-scheduled tasks too)", async () => {
204
+ const BUSY = "[n] opencode 任务未提交:共享会话在 30 分钟 内一直处于忙碌状态,本任务没有发出";
205
+ // 时间用 JS 算再传参:`datetime('now','-N minutes')` 是 SQLite 方言,
206
+ // PG ladder 里会直接报错 (#2884)。completed_at 留空表示「现在」,由断言侧不需要它。
207
+ const minutesAgo = (m: number) => new Date(Date.now() - m * 60_000).toISOString().replace("T", " ").replace(/\..+/, "");
208
+ const nowTs = minutesAgo(0);
209
+ db.run(
210
+ `INSERT INTO tasks (task_id, from_name, to_name, status, content, priority, result,
211
+ created_at, started_at, completed_at, network_id)
212
+ VALUES ('task-busy-shape', 'sender', 'rest-shape-node', 'failed', 'busy', 'normal', ?1, ?2, ?3, ?4, ?5)`,
213
+ [BUSY, minutesAgo(412), minutesAgo(30), nowTs, networkId],
214
+ );
215
+ // 对照组:同一形状但原因不是会话忙 ⇒ 不能被加拆解
216
+ db.run(
217
+ `INSERT INTO tasks (task_id, from_name, to_name, status, content, priority, result,
218
+ created_at, started_at, completed_at, network_id)
219
+ VALUES ('task-plain-fail', 'sender', 'rest-shape-node', 'failed', 'plain', 'normal',
220
+ '执行出错: upstream refused', ?1, ?2, ?3, ?4)`,
221
+ [minutesAgo(400), minutesAgo(370), nowTs, networkId],
222
+ );
223
+
224
+ const detail = await api(`/api/tasks/task-busy-shape?network_id=${networkId}`);
225
+ expect(detail.task.status).toBe("failed");
226
+ expect(detail.task.result).toContain("共享会话");
227
+ expect(detail.task.result).toContain("排队 382 分钟");
228
+ expect(detail.task.result).toContain("会话等待 30 分钟");
229
+ expect(detail.task.result).toContain("不代表总共等了多久");
230
+ // 幂等:再读一次不重复追加
231
+ const again = await api(`/api/tasks/task-busy-shape?network_id=${networkId}`);
232
+ expect(again.task.result.match(/实测总耗时/g)?.length).toBe(1);
233
+
234
+ const plain = await api(`/api/tasks/task-plain-fail?network_id=${networkId}`);
235
+ expect(plain.task.result).not.toContain("排队");
236
+
237
+ // 列表端点走同一条投影
238
+ const list = await api(`/api/tasks?network_id=${networkId}&task_id=task-busy-shape&skip_stats=1`);
239
+ expect(list.tasks[0].result).toContain("排队 382 分钟");
240
+ // 响应键不变(不新增字段)
241
+ expect(sortedKeys(list.tasks[0])).toEqual(sorted(GOLDEN_RESPONSE_KEYS.task));
242
+ });
243
+
244
+ test("audit, task-event, and completion rows are explicit", async () => {
245
+ const audit = await api("/api/audit-log?action=shape_action");
246
+ expect(sortedKeys(audit.logs[0])).toEqual(sorted(GOLDEN_RESPONSE_KEYS.audit));
247
+ expect(audit.logs[0][INTERNAL_SENTINEL]).toBeUndefined();
248
+
249
+ const events = await api(`/api/task_events?network_id=${networkId}&task_id=task-rest-shape`);
250
+ expect(sortedKeys(events.events[0])).toEqual(sorted(GOLDEN_RESPONSE_KEYS.taskEvent));
251
+ expect(events.events[0][INTERNAL_SENTINEL]).toBeUndefined();
252
+
253
+ const completions = await api(`/api/completions?network_id=${networkId}&since=2000-01-01T00:00:00.000Z`);
254
+ expect(sortedKeys(completions.completions[0])).toEqual(sorted(GOLDEN_RESPONSE_KEYS.completion));
255
+ expect(completions.completions[0][INTERNAL_SENTINEL]).toBeUndefined();
256
+ });
257
+
258
+ test("scheduled-task decoding keeps storage-only identity and JSON private", async () => {
259
+ const body = await api(`/api/scheduled-tasks?network_id=${networkId}`);
260
+ const row = body.schedules.find((item: any) => item.schedule_id === "schedule-rest-shape");
261
+ expect(sortedKeys(row)).toEqual(sorted(GOLDEN_RESPONSE_KEYS.scheduledTask));
262
+ expect(row.created_by).toBeUndefined();
263
+ expect(row.schedule_json).toBeUndefined();
264
+ expect(row[INTERNAL_SENTINEL]).toBeUndefined();
265
+ });
266
+ });