@sleep2agi/commhub-server 0.9.0-preview.23 → 0.9.0-preview.230

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 (408) hide show
  1. package/README.md +129 -9
  2. package/bin/commhub.ts +93 -9
  3. package/package.json +7 -7
  4. package/src/ack-create-request-transport.test.ts +182 -0
  5. package/src/ack-create-request.test.ts +50 -7
  6. package/src/admin-delete-network-http.test.ts +228 -0
  7. package/src/admin-networks-http.test.ts +88 -0
  8. package/src/adoption-candidates-http.test.ts +137 -0
  9. package/src/adoption-candidates.ts +158 -0
  10. package/src/agent-access-batch.test.ts +210 -0
  11. package/src/agent-access.ts +487 -0
  12. package/src/agent-acl-groups-http.test.ts +247 -0
  13. package/src/agent-acl-http.test.ts +659 -0
  14. package/src/agent-acl-slice3-http.test.ts +654 -0
  15. package/src/agent-department-http.test.ts +215 -0
  16. package/src/agent-groups-perf.test.ts +223 -0
  17. package/src/agent-notice.ts +48 -0
  18. package/src/agent-team-whoami-http.test.ts +98 -0
  19. package/src/agent-teams-http.test.ts +330 -0
  20. package/src/agent-teams.ts +244 -0
  21. package/src/alias-baseline-2571.test.ts +162 -0
  22. package/src/alias-baseline.ts +113 -0
  23. package/src/alias-filter.test.ts +72 -0
  24. package/src/alias-filter.ts +42 -0
  25. package/src/api-host-supervisors-can-create-nodes.test.ts +350 -0
  26. package/src/api-host-supervisors-fallback.test.ts +6 -7
  27. package/src/api-host-supervisors-runtime-readiness.test.ts +195 -0
  28. package/src/api-nodes-shape.test.ts +95 -4
  29. package/src/auth-password-change-cli-tokens-http.test.ts +423 -0
  30. package/src/auth-sessions-http.test.ts +250 -0
  31. package/src/auth-validate.test.ts +5 -1
  32. package/src/auth-weak-password-login.test.ts +176 -0
  33. package/src/auth.ts +609 -51
  34. package/src/avatar-validate.test.ts +52 -2
  35. package/src/avatar-validate.ts +35 -1
  36. package/src/backfill-node-ids-2664.test.ts +128 -0
  37. package/src/binding-generation-http.test.ts +121 -0
  38. package/src/blocked-exit-on-reply.test.ts +122 -0
  39. package/src/broadcast-fanout-2721.test.ts +149 -0
  40. package/src/broadcast-fanout.ts +117 -0
  41. package/src/chain-attempt-dedup.test.ts +447 -0
  42. package/src/clip.test.ts +36 -0
  43. package/src/clip.ts +46 -0
  44. package/src/clone-node.test.ts +248 -0
  45. package/src/clone-node.ts +289 -0
  46. package/src/codex-config-flags.ts +77 -0
  47. package/src/codex-fork-contract.ts +23 -0
  48. package/src/codex-fork-migration.test.ts +38 -0
  49. package/src/commhub-bin-args.test.ts +85 -0
  50. package/src/config-apply-validate.test.ts +188 -1
  51. package/src/config-apply-validate.ts +222 -3
  52. package/src/cors-origins.test.ts +73 -0
  53. package/src/create-node-blocked-gate.test.ts +356 -0
  54. package/src/create-node-network-id.test.ts +91 -0
  55. package/src/create-node-tool-schema.test.ts +49 -0
  56. package/src/create-node-unicode-name.test.ts +120 -0
  57. package/src/create-node-validate.test.ts +199 -7
  58. package/src/create-node-validate.ts +232 -15
  59. package/src/create-node-workdir.test.ts +289 -0
  60. package/src/create-node.ts +88 -23
  61. package/src/daemon-provider-snapshots.test.ts +421 -0
  62. package/src/daemon-provider-snapshots.ts +327 -0
  63. package/src/daemon-token-owner-http.test.ts +236 -0
  64. package/src/dashboard-slash-routing-http.test.ts +109 -0
  65. package/src/db-adapter-guard.test.ts +148 -0
  66. package/src/db-adapter-translate.test.ts +128 -0
  67. package/src/db-adapter.ts +377 -91
  68. package/src/db-timestamp.test.ts +38 -0
  69. package/src/db-timestamp.ts +15 -0
  70. package/src/db.ts +1264 -153
  71. package/src/delivered-without-push.test.ts +140 -0
  72. package/src/department-groups-http.test.ts +209 -0
  73. package/src/department-groups-sync-http.test.ts +328 -0
  74. package/src/department-groups.ts +434 -0
  75. package/src/department-heads-http.test.ts +350 -0
  76. package/src/department-heads.ts +226 -0
  77. package/src/departments-agent-count.test.ts +132 -0
  78. package/src/departments-http.test.ts +185 -0
  79. package/src/departments-mcp.test.ts +128 -0
  80. package/src/departments.ts +318 -0
  81. package/src/desktop-message-seam.test.ts +150 -0
  82. package/src/desktop-message.test.ts +368 -0
  83. package/src/dm-file-scope-http.test.ts +178 -0
  84. package/src/empty-node-sweeper.test.ts +104 -0
  85. package/src/empty-node-sweeper.ts +88 -0
  86. package/src/env-transport-gate-http.test.ts +240 -0
  87. package/src/env-transport-gate.ts +80 -0
  88. package/src/env-transport-policy.ts +56 -0
  89. package/src/etag-of.test.ts +57 -0
  90. package/src/event-loop-lag.test.ts +180 -0
  91. package/src/event-loop-lag.ts +201 -0
  92. package/src/ext-token-shared.test.ts +60 -0
  93. package/src/ext-validation-regression.test.ts +131 -0
  94. package/src/external-schedule-edits-http.test.ts +321 -0
  95. package/src/external-schedule-edits-timestamps.test.ts +64 -0
  96. package/src/external-schedule-edits.ts +327 -0
  97. package/src/file-download-authz-dev-open.test.ts +1 -1
  98. package/src/file-download-authz.test.ts +73 -18
  99. package/src/file-download-date-bucket.test.ts +436 -0
  100. package/src/file-network-scope-dev-open.test.ts +97 -0
  101. package/src/file-network-scope.test.ts +732 -0
  102. package/src/group-membership-events-http.test.ts +264 -0
  103. package/src/group-messages-http.test.ts +482 -0
  104. package/src/group-messages.ts +297 -0
  105. package/src/health-anon-readers.ts +60 -0
  106. package/src/health-host-disk-2756.test.ts +71 -0
  107. package/src/health-redaction.test.ts +1721 -2
  108. package/src/host-supervisor-identity-http.test.ts +152 -0
  109. package/src/host-supervisor-identity.ts +92 -0
  110. package/src/host-supervisors-daemon-version.test.ts +137 -0
  111. package/src/http-gzip.test.ts +94 -0
  112. package/src/http-gzip.ts +112 -0
  113. package/src/hub-catalog-read-http.test.ts +409 -0
  114. package/src/hub-provider-config.test.ts +156 -0
  115. package/src/hub-provider-config.ts +170 -0
  116. package/src/hub-timestamp.test.ts +38 -0
  117. package/src/hub-timestamp.ts +27 -0
  118. package/src/human-dm.ts +215 -0
  119. package/src/human-inbox.ts +42 -0
  120. package/src/inbox-caller.ts +49 -0
  121. package/src/inbox-count-sse.test.ts +310 -0
  122. package/src/inbox-count.ts +29 -0
  123. package/src/index.ts +6 -2
  124. package/src/license-state.test.ts +56 -0
  125. package/src/license-state.ts +48 -0
  126. package/src/list-host-supervisors.test.ts +15 -4
  127. package/src/mcp-context-cost-http.test.ts +127 -0
  128. package/src/mcp-inflight.test.ts +92 -0
  129. package/src/mcp-inflight.ts +38 -0
  130. package/src/mcp-projects-events-http.test.ts +165 -0
  131. package/src/mcp-route-label-http.test.ts +120 -0
  132. package/src/mcp-write-network-resolution.test.ts +435 -0
  133. package/src/member-audit-network-id-http.test.ts +93 -0
  134. package/src/member-presence-http.test.ts +210 -0
  135. package/src/messages-ack-by-agent-http.test.ts +142 -0
  136. package/src/migrate-sqlite-to-pg.test.ts +47 -0
  137. package/src/migrate-sqlite-to-pg.ts +263 -0
  138. package/src/model-auth-notify-http.test.ts +181 -0
  139. package/src/model-auth-notify.ts +116 -0
  140. package/src/network-name-http.test.ts +75 -0
  141. package/src/network-rules-http.test.ts +169 -0
  142. package/src/network-rules.ts +129 -0
  143. package/src/network-scope.ts +276 -0
  144. package/src/network-token-membership-http.test.ts +139 -0
  145. package/src/node-alias-control.ts +12 -0
  146. package/src/node-attrs.test.ts +47 -2
  147. package/src/node-caller-identity-http.test.ts +1091 -0
  148. package/src/node-create-request-status-http.test.ts +105 -0
  149. package/src/node-daemon-bindings.test.ts +132 -0
  150. package/src/node-daemon-bindings.ts +135 -0
  151. package/src/node-failure-alert.test.ts +150 -0
  152. package/src/node-failure-alert.ts +177 -0
  153. package/src/node-files-transport.test.ts +344 -0
  154. package/src/node-health-codex-login.test.ts +120 -0
  155. package/src/node-health-dispatch-http.test.ts +335 -0
  156. package/src/node-health-guard.ts +121 -0
  157. package/src/node-health-passthrough.test.ts +115 -0
  158. package/src/node-health-store.ts +101 -0
  159. package/src/node-id-alias.test.ts +190 -0
  160. package/src/node-identity-conflict-http.test.ts +269 -0
  161. package/src/node-identity-conflict.ts +142 -0
  162. package/src/node-identity-mismatch.test.ts +74 -0
  163. package/src/node-in-flight-tasks.ts +31 -0
  164. package/src/node-lifecycle-controllable.test.ts +64 -0
  165. package/src/node-lifecycle-controllable.ts +53 -0
  166. package/src/node-lifecycle-read-http.test.ts +250 -0
  167. package/src/node-lifecycle-read.ts +124 -0
  168. package/src/node-logs-transport.test.ts +263 -0
  169. package/src/node-peer-allowlist.test.ts +114 -0
  170. package/src/node-permissions-http.test.ts +728 -0
  171. package/src/node-permissions.ts +494 -0
  172. package/src/node-request-retention.test.ts +281 -0
  173. package/src/node-request-retention.ts +120 -0
  174. package/src/node-secret-rest-http.test.ts +190 -0
  175. package/src/node-serviceability.test.ts +86 -0
  176. package/src/node-serviceability.ts +124 -0
  177. package/src/node-session-control-http.test.ts +310 -0
  178. package/src/node-session-control.ts +258 -0
  179. package/src/node-skills-transport.test.ts +212 -0
  180. package/src/node-token-identity.ts +35 -0
  181. package/src/node-token-ownership.ts +51 -0
  182. package/src/node-token-privilege-http.test.ts +158 -0
  183. package/src/not-found-api-http.test.ts +67 -0
  184. package/src/observer-avatar-http.test.ts +102 -9
  185. package/src/observer-push.test.ts +76 -0
  186. package/src/opencode-catalog-report-http.test.ts +139 -0
  187. package/src/opencode-v2-catalog.test.ts +268 -0
  188. package/src/opencode-v2-catalog.ts +356 -0
  189. package/src/package-version-consistency.test.ts +25 -0
  190. package/src/parent-source-marker.test.ts +50 -0
  191. package/src/password-network-tokens.ts +25 -0
  192. package/src/peer-reply-atomic.test.ts +457 -0
  193. package/src/peer-reply-capability.test.ts +70 -0
  194. package/src/pg-worker.ts +87 -0
  195. package/src/poll-pacing.test.ts +74 -0
  196. package/src/poll-pacing.ts +123 -0
  197. package/src/project-dir-warn-clear-http.test.ts +132 -0
  198. package/src/project-viewer-can-http.test.ts +116 -0
  199. package/src/push.test.ts +20 -10
  200. package/src/push.ts +382 -9
  201. package/src/redact-tokens.test.ts +86 -0
  202. package/src/redact-tokens.ts +43 -0
  203. package/src/rejection-counters.test.ts +72 -0
  204. package/src/rejection-counters.ts +173 -0
  205. package/src/rename.ts +38 -10
  206. package/src/reply-target-derivation.test.ts +96 -0
  207. package/src/report-status-handover-capabilities-http.test.ts +124 -0
  208. package/src/report-status-host-schema.test.ts +235 -0
  209. package/src/report-status-resume-id-handover.test.ts +184 -0
  210. package/src/report-status-secret-keys.test.ts +140 -0
  211. package/src/require-explicit-test-db.ts +9 -0
  212. package/src/requirement-due-reminders-http.test.ts +620 -0
  213. package/src/requirement-due-reminders.ts +416 -0
  214. package/src/requirement-events-http.test.ts +295 -0
  215. package/src/requirement-events.test.ts +45 -0
  216. package/src/requirement-events.ts +144 -0
  217. package/src/requirement-notify.ts +165 -0
  218. package/src/requirement-participant-notify-http.test.ts +309 -0
  219. package/src/requirement-tag-ops-http.test.ts +443 -0
  220. package/src/requirement-tag-tree-http.test.ts +275 -0
  221. package/src/requirement-tag-tree.ts +127 -0
  222. package/src/requirement-tags.ts +102 -0
  223. package/src/requirements-abandoned-http.test.ts +236 -0
  224. package/src/requirements-comment-http.test.ts +167 -0
  225. package/src/requirements-completed-at-migration.test.ts +70 -0
  226. package/src/requirements-errors-mcp-http.test.ts +164 -0
  227. package/src/requirements-errors.ts +158 -0
  228. package/src/requirements-etag-http.test.ts +91 -0
  229. package/src/requirements-http.test.ts +709 -0
  230. package/src/requirements-last-event-http.test.ts +349 -0
  231. package/src/requirements-list-mcp-slim-http.test.ts +155 -0
  232. package/src/requirements-list-slim-http.test.ts +324 -0
  233. package/src/requirements-mcp.test.ts +163 -0
  234. package/src/requirements-migrate.ts +283 -0
  235. package/src/requirements-owner-strict-mcp-http.test.ts +145 -0
  236. package/src/requirements-people-http.test.ts +114 -0
  237. package/src/requirements-people-mcp-http.test.ts +231 -0
  238. package/src/requirements-people.ts +196 -0
  239. package/src/requirements-priority-lowest.test.ts +114 -0
  240. package/src/requirements-projects-network-echo.test.ts +57 -0
  241. package/src/requirements-projects-parent-http.test.ts +123 -0
  242. package/src/requirements-search-http.test.ts +182 -0
  243. package/src/requirements-search.test.ts +32 -0
  244. package/src/requirements-search.ts +145 -0
  245. package/src/requirements-seq-http.test.ts +193 -0
  246. package/src/requirements-seq-migration.test.ts +63 -0
  247. package/src/requirements-start-date.test.ts +125 -0
  248. package/src/requirements-stats-http.test.ts +357 -0
  249. package/src/requirements-stats.ts +195 -0
  250. package/src/requirements-status-participants-http.test.ts +222 -0
  251. package/src/requirements-upgrade-e2e.test.ts +126 -0
  252. package/src/requirements-upgrade-migration.test.ts +98 -0
  253. package/src/requirements.ts +2064 -0
  254. package/src/resolve-port.test.ts +57 -0
  255. package/src/resolve-port.ts +44 -0
  256. package/src/rest-alias-network-fallback-http.test.ts +123 -0
  257. package/src/rest-alias-network-fallback.test.ts +60 -0
  258. package/src/rest-alias-network-fallback.ts +65 -0
  259. package/src/rest-explicit-columns-http.test.ts +266 -0
  260. package/src/rest-identity.test.ts +130 -0
  261. package/src/rest-identity.ts +141 -0
  262. package/src/rest-projections.ts +72 -0
  263. package/src/rest-read-network-real-chain.test.ts +97 -0
  264. package/src/rest-write-network-resolution.test.ts +133 -0
  265. package/src/restart-readiness-http.test.ts +121 -0
  266. package/src/restricted-files.ts +76 -0
  267. package/src/retention-first-sweep-quiet.test.ts +31 -0
  268. package/src/retention.test.ts +100 -40
  269. package/src/retention.ts +423 -104
  270. package/src/route-callers-http.test.ts +120 -0
  271. package/src/route-timing.test.ts +218 -0
  272. package/src/route-timing.ts +262 -0
  273. package/src/rules-file-duplicate-alias.test.ts +234 -0
  274. package/src/rules-file-session-target.test.ts +207 -0
  275. package/src/rules-file-transport.test.ts +237 -0
  276. package/src/runtime-label.test.ts +22 -0
  277. package/src/runtime-label.ts +21 -0
  278. package/src/runtime-readiness.ts +90 -0
  279. package/src/schedule-agent-mcp-http.test.ts +432 -0
  280. package/src/schedule-agent.ts +252 -0
  281. package/src/schedule-starved.test.ts +92 -0
  282. package/src/schedule-starved.ts +114 -0
  283. package/src/scheduled-backoff-http.test.ts +193 -0
  284. package/src/scheduled-backoff.ts +64 -0
  285. package/src/scheduled-doorbell-nodeless-session.test.ts +134 -0
  286. package/src/scheduled-failure-backoff-2622.test.ts +145 -0
  287. package/src/scheduled-failure-code.test.ts +73 -0
  288. package/src/scheduled-failure-code.ts +105 -0
  289. package/src/scheduled-failures-http.test.ts +279 -0
  290. package/src/scheduled-failures.ts +425 -0
  291. package/src/scheduled-noprogress-backoff-2622.test.ts +163 -0
  292. package/src/scheduled-offline-backoff-probe.test.ts +56 -0
  293. package/src/scheduled-offline.test.ts +131 -0
  294. package/src/scheduled-offline.ts +66 -0
  295. package/src/scheduled-outcome-guidance-http.test.ts +139 -0
  296. package/src/scheduled-outcome-guidance.ts +9 -0
  297. package/src/scheduled-reply-unread-http.test.ts +212 -0
  298. package/src/scheduled-requirement-wake-http.test.ts +279 -0
  299. package/src/scheduled-requirement-wake.ts +125 -0
  300. package/src/scheduled-run-terminal.test.ts +268 -0
  301. package/src/scheduled-skip-blocking-task.test.ts +120 -0
  302. package/src/scheduled-skip-path-backoff-2622.test.ts +98 -0
  303. package/src/scheduled-stuck-http.test.ts +316 -0
  304. package/src/scheduled-stuck-notice-cap.test.ts +80 -0
  305. package/src/scheduled-stuck.ts +219 -0
  306. package/src/scheduled-tasks-http.test.ts +679 -0
  307. package/src/scheduled-tasks.ts +959 -0
  308. package/src/scheduled-work-outcome-http.test.ts +154 -0
  309. package/src/scheduled-work-outcome.ts +50 -0
  310. package/src/scoped-secrets.ts +141 -0
  311. package/src/send-dedup-request-id.test.ts +229 -0
  312. package/src/send-reply-agent-warning.test.ts +38 -38
  313. package/src/send-reply-alias-optional.test.ts +131 -0
  314. package/src/send-reply-attachments.test.ts +458 -0
  315. package/src/send_dedup.test.ts +54 -0
  316. package/src/send_dedup.ts +52 -6
  317. package/src/serve-error.test.ts +73 -0
  318. package/src/serve-error.ts +56 -0
  319. package/src/server.ts +5035 -457
  320. package/src/session-task-on-dispatch.ts +14 -0
  321. package/src/session-token-ownership-http.test.ts +122 -0
  322. package/src/shared/codex-inventory.ts +41 -0
  323. package/src/shared/daemon-provider-login.ts +31 -0
  324. package/src/shared/daemon-provider-snapshot.ts +52 -0
  325. package/src/shared/external-schedule-contract.ts +60 -0
  326. package/src/shared/node-name.test.ts +62 -0
  327. package/src/shared/node-name.ts +161 -0
  328. package/src/shared/probe-host-allowlist-drift.test.ts +45 -0
  329. package/src/shared/provider-application.ts +29 -0
  330. package/src/shared/provider-collection.ts +14 -0
  331. package/src/shared/provider-initialization.ts +8 -0
  332. package/src/shared/reserved-env-drift.test.ts +10 -0
  333. package/src/shared/scoped-secret-contract.ts +5 -0
  334. package/src/shared/task-content-limit-drift.test.ts +28 -0
  335. package/src/shared/task-content-limit.ts +25 -0
  336. package/src/side-thread-command-transport.test.ts +312 -0
  337. package/src/side-thread-command-transport.ts +318 -0
  338. package/src/side-thread-http-integration.test.ts +233 -0
  339. package/src/side-thread-http.ts +504 -0
  340. package/src/side-thread-production.test.ts +72 -0
  341. package/src/side-thread-production.ts +118 -0
  342. package/src/side-thread.test.ts +1067 -0
  343. package/src/side-thread.ts +2499 -0
  344. package/src/skillhub-http.test.ts +142 -0
  345. package/src/sqlite-close-checkpoint.test.ts +78 -0
  346. package/src/start-node.test.ts +264 -0
  347. package/src/status-alias-filter-http.test.ts +106 -0
  348. package/src/status-alias-resolver-http.test.ts +163 -0
  349. package/src/status-alias-resolver.ts +19 -0
  350. package/src/status-node-id-filter-http.test.ts +161 -0
  351. package/src/status-read-cache-http.test.ts +229 -0
  352. package/src/status-read-cache.ts +129 -0
  353. package/src/stop-delete-node.test.ts +567 -1
  354. package/src/task-access-http.test.ts +402 -0
  355. package/src/task-access.ts +420 -0
  356. package/src/task-activity.ts +60 -0
  357. package/src/task-auth-origin-http.test.ts +93 -0
  358. package/src/task-auth-origin.test.ts +24 -0
  359. package/src/task-auth-origin.ts +7 -0
  360. package/src/task-consumption.test.ts +490 -0
  361. package/src/task-diagnostic-http.test.ts +149 -0
  362. package/src/task-diagnostic.test.ts +115 -0
  363. package/src/task-diagnostic.ts +118 -0
  364. package/src/task-expiry-notice-http.test.ts +287 -0
  365. package/src/task-expiry-notice.ts +315 -0
  366. package/src/task-idempotency-mcp.test.ts +142 -0
  367. package/src/task-idempotency.test.ts +76 -0
  368. package/src/task-idempotency.ts +81 -0
  369. package/src/task-late-replies.ts +54 -0
  370. package/src/task-late-reply-http.test.ts +227 -0
  371. package/src/task-lifecycle-watcher-busy.test.ts +114 -0
  372. package/src/task-lifecycle-watcher.test.ts +204 -0
  373. package/src/task-lifecycle-watcher.ts +109 -0
  374. package/src/task-network-resolution-http.test.ts +140 -0
  375. package/src/task-offline-delivery-2668.test.ts +119 -0
  376. package/src/task-offline-delivery.ts +81 -0
  377. package/src/task-orphan-http.test.ts +287 -0
  378. package/src/task-orphan.ts +119 -0
  379. package/src/task-queue-ahead-http.test.ts +309 -0
  380. package/src/task-queue-ahead-scale.test.ts +236 -0
  381. package/src/task-queue-ahead.ts +186 -0
  382. package/src/task-rejection-log-http.test.ts +160 -0
  383. package/src/task-rejection-log.ts +61 -0
  384. package/src/task-sender-http.test.ts +143 -0
  385. package/src/task-stale-open-http.test.ts +292 -0
  386. package/src/task-stale-open.ts +103 -0
  387. package/src/tasks-pagination-http.test.ts +141 -0
  388. package/src/team-rules-status-http.test.ts +90 -0
  389. package/src/team-rules-status.test.ts +59 -0
  390. package/src/team-rules-status.ts +72 -0
  391. package/src/tmux-allowlist.test.ts +48 -0
  392. package/src/tool-audience-http.test.ts +230 -0
  393. package/src/tool-audience.ts +127 -0
  394. package/src/tools-list-json-schema.test.ts +94 -0
  395. package/src/tools.ts +4310 -419
  396. package/src/upload-early-reject-guard.test.ts +155 -0
  397. package/src/uploads-http.test.ts +86 -7
  398. package/src/uploads.ts +103 -6
  399. package/src/user-avatar-http.test.ts +74 -0
  400. package/src/user-avatar-image.ts +160 -0
  401. package/src/user-avatar-migration.test.ts +25 -0
  402. package/src/user-avatar-upload-http.test.ts +348 -0
  403. package/src/user-inbox-by-agent-http.test.ts +161 -0
  404. package/src/user-inbox-netid-notnull.test.ts +122 -0
  405. package/src/user-inbox-read-http.test.ts +223 -0
  406. package/src/user-inbox-schema.test.ts +54 -0
  407. package/src/version-stats.test.ts +66 -0
  408. package/src/version-stats.ts +109 -0
@@ -0,0 +1,409 @@
1
+ // #1473 (#909) — the Hub's Skills / secrets / Provider catalogs had MCP tools
2
+ // but no HTTP read surface, so the desktop client shipped a fixture page
3
+ // (agent-network-app/src/hub-scope-demo.ts: "Hub 这些写接口还没接通 ... 不发请求").
4
+ //
5
+ // These three endpoints are read-only and user-token only. The load-bearing
6
+ // properties are:
7
+ // * a NODE token cannot enumerate the network's catalogs;
8
+ // * a plain member of another network cannot read this network's catalogs;
9
+ // * pending SkillHub submissions stay invisible unless the caller reviews;
10
+ // * NO secret value ever appears in a response body (asserted with a
11
+ // sentinel that would be trivially visible if a value were serialized).
12
+ //
13
+ // The sentinel test is deliberately byte-level on the raw response text: a
14
+ // future field like `value_preview` would pass a JSON-shape assertion while
15
+ // still leaking the secret.
16
+ import { afterAll, beforeAll, describe, expect, test } from "bun:test";
17
+ import { mkdtempSync, rmSync } from "node:fs";
18
+ import { tmpdir } from "node:os";
19
+ import { join } from "node:path";
20
+
21
+ const PRIVATE_DB_DIR = mkdtempSync(join(tmpdir(), "anet-hub-catalog-"));
22
+ process.env.COMMHUB_DB ||= join(PRIVATE_DB_DIR, "hub.db");
23
+ // The vault encrypts on write; set the master key before db.ts/vault.ts load.
24
+ process.env.ANET_HUB_SECRET_VAULT_KEY ||= "00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff";
25
+
26
+ let server: ReturnType<typeof Bun.serve>;
27
+ let base = "";
28
+ let ownerToken = "", strangerToken = "", nodeToken = "";
29
+ let ownerNet = "", strangerNet = "", ownerUserId = "";
30
+ const SECRET_NAME = "PROVIDER_SENTINEL_KEY";
31
+ const SECRET_VALUE = "sentinel-value-DO-NOT-LEAK-4f9a2c";
32
+
33
+ const get = async (path: string, token: string) => {
34
+ const r = await fetch(`${base}${path}`, { headers: { Authorization: `Bearer ${token}` } });
35
+ const text = await r.text();
36
+ let body: any = null;
37
+ try { body = JSON.parse(text); } catch { body = null; }
38
+ return { status: r.status, body, text };
39
+ };
40
+
41
+ beforeAll(async () => {
42
+ const { db } = await import("./db.js");
43
+ const { register, createNetworkTokenForNode } = await import("./auth.js");
44
+ const { vaultUpsert } = await import("./vault.js");
45
+ const stamp = Date.now();
46
+
47
+ const owner = register(`hc_owner_${stamp}`, "HcOwner-Strong-1!");
48
+ const stranger = register(`hc_stranger_${stamp}`, "HcStranger-Strong-1!");
49
+ expect(owner.ok && stranger.ok).toBe(true);
50
+ ownerToken = owner.token!;
51
+ strangerToken = stranger.token!;
52
+ ownerNet = owner.network_id!;
53
+ strangerNet = stranger.network_id!;
54
+ ownerUserId = db.get<{ user_id: string }>("SELECT user_id FROM users WHERE username = ?1", `hc_owner_${stamp}`)!.user_id;
55
+
56
+ // A node token in the SAME network: it must still be refused, because a node
57
+ // is not a person and may not enumerate catalogs.
58
+ const nodeTok = createNetworkTokenForNode(ownerUserId, ownerNet, "hc-node", "n_hc_test");
59
+ expect(nodeTok.ok).toBe(true);
60
+ nodeToken = nodeTok.token!;
61
+
62
+ // Published + pending skills in the owner's network.
63
+ const skill = (id: string, status: string, slug: string) => db.run(
64
+ `INSERT INTO skillhub_skills (skill_id, network_id, slug, name, description, content, content_hash, version, status, source_type, source_alias, created_at, updated_at)
65
+ VALUES (?1, ?2, ?3, ?3, 'd', '# SKILL body', 'hash-' || ?1, '1.0.0', ?4, 'node', 'hc-node', datetime('now'), datetime('now'))`,
66
+ [id, ownerNet, slug, status],
67
+ );
68
+ skill("skill_hc_pub", "published", "hc-published");
69
+ skill("skill_hc_pending", "pending", "hc-pending");
70
+
71
+ // The sentinel secret. Names may be shown; values never.
72
+ vaultUpsert(ownerNet, SECRET_NAME, SECRET_VALUE);
73
+
74
+ db.run(
75
+ `INSERT INTO hub_provider_configs (network_id, provider_id, revision, config_json, secret_key_ref, updated_at)
76
+ VALUES (?1, 'hc-provider', 3, ?2, ?3, ?4)`,
77
+ [ownerNet, JSON.stringify({ id: "hc-provider", label: "HC Provider", enabled: true, protocol: "openai-responses", baseUrl: "https://example.test/v1", models: ["m1"] }), "HC_PROVIDER_KEY", Date.now()],
78
+ );
79
+
80
+ const mod = await import("./server.js");
81
+ server = mod.bootServer({ port: 0, hostname: "127.0.0.1" });
82
+ base = `http://127.0.0.1:${server.port}`;
83
+ });
84
+
85
+ afterAll(() => {
86
+ try { server?.stop(true); } catch {}
87
+ try { rmSync(PRIVATE_DB_DIR, { recursive: true, force: true }); } catch {}
88
+ });
89
+
90
+ describe("GET /api/skills", () => {
91
+ test("owner sees published skills and no content body", async () => {
92
+ const r = await get(`/api/skills?network_id=${ownerNet}`, ownerToken);
93
+ expect(r.status).toBe(200);
94
+ expect(r.body.ok).toBe(true);
95
+ expect(r.body.reviewer).toBe(true);
96
+ expect(r.body.network_id).toBe(ownerNet);
97
+ const slugs = r.body.skills.map((s: any) => s.slug);
98
+ expect(slugs).toContain("hc-published");
99
+ // Pending is opt-in even for a reviewer.
100
+ expect(slugs).not.toContain("hc-pending");
101
+ // The list is metadata only — a body field would mean SKILL.md text leaked.
102
+ for (const s of r.body.skills) expect(s.content).toBeUndefined();
103
+ });
104
+
105
+ test("reviewer may ask for pending submissions", async () => {
106
+ const r = await get(`/api/skills?network_id=${ownerNet}&include_pending=1`, ownerToken);
107
+ expect(r.status).toBe(200);
108
+ const slugs = r.body.skills.map((s: any) => s.slug);
109
+ expect(slugs).toContain("hc-pending");
110
+ });
111
+
112
+ // 2026-10-31 —— **两条「providers」读的是不同的表**,而空数组在载荷里长得一样:
113
+ // GET /api/providers → hub_provider_configs | MCP list_providers → providers / provider_models
114
+ // 客户端「没有可选模型」既可能是前者空,也可能是后者空 ⇒ 必须能在载荷里区分。
115
+ test("an empty registry says which table it read, and whether the CLI registry has rows", async () => {
116
+ const { db } = await import("./db.js");
117
+ // strangerNet 里没有 hub_provider_configs 行;先看「两张表都空」这一档
118
+ const before = await get(`/api/providers?network_id=${strangerNet}`, strangerToken);
119
+ expect(before.status).toBe(200);
120
+ expect(before.body.state).toBe("unconfigured");
121
+ expect(before.body.source_table).toBe("hub_provider_configs");
122
+ expect(before.body.counts.providers).toBe(0);
123
+ expect(before.body.hint).toContain("hub_provider_configs");
124
+
125
+ // 再给 CLI 注册表塞一行(另一张表),本端点**仍然为空**,但 hint 必须改口
126
+ db.run(
127
+ `INSERT OR REPLACE INTO providers (provider_id, network_id, name, vendor, base_url, secret_key_ref, created_at, created_by, enabled)
128
+ VALUES ('hc-cli-only', ?1, 'hc-cli-only', 'openai', 'https://api.example.com', 'K', ?2, 'test', 1)`,
129
+ [strangerNet, Date.now()],
130
+ );
131
+ const after = await get(`/api/providers?network_id=${strangerNet}`, strangerToken);
132
+ expect(after.body.providers).toHaveLength(0); // 本端点还是空
133
+ expect(after.body.counts.providers_in_cli_registry).toBeGreaterThan(0);
134
+ expect(after.body.hint).toContain("不会自动出现在本端点");
135
+ // 反向:有行时不该带 hint(载荷不变胖,且「有理由」与「没理由」可区分)
136
+ const owner = await get(`/api/providers?network_id=${ownerNet}`, ownerToken);
137
+ expect(owner.body.state).toBe("configured");
138
+ expect("hint" in owner.body).toBe(false);
139
+ });
140
+
141
+ test("a member of another network is refused", async () => {
142
+ const r = await get(`/api/skills?network_id=${ownerNet}`, strangerToken);
143
+ expect(r.status).toBe(403);
144
+ // Cross-network access is refused by REST scope resolution BEFORE the role
145
+ // check runs, so the error names the scope gate. Either way: 403, no data.
146
+ expect(String(r.body.error)).toMatch(/access denied|permission_denied/);
147
+ });
148
+
149
+ test("a node token is refused even inside its own network", async () => {
150
+ const r = await get(`/api/skills?network_id=${ownerNet}`, nodeToken);
151
+ expect(r.status).toBe(403);
152
+ expect(r.body.error).toBe("user_token_required");
153
+ });
154
+
155
+ test("include_pending is ignored for a non-reviewer of that network", async () => {
156
+ // The stranger's own network has no skills; the point is that asking for
157
+ // pending must not widen what they can see when they ask about their own.
158
+ const r = await get(`/api/skills?network_id=${strangerNet}&include_pending=1`, strangerToken);
159
+ expect(r.status).toBe(200);
160
+ expect(r.body.reviewer).toBe(true); // they own their own network
161
+ expect(r.body.skills).toEqual([]);
162
+ });
163
+ });
164
+
165
+ describe("GET /api/secrets", () => {
166
+ test("returns key names and timestamps, never the value", async () => {
167
+ const r = await get(`/api/secrets?network_id=${ownerNet}`, ownerToken);
168
+ expect(r.status).toBe(200);
169
+ const names = r.body.keys.map((k: any) => k.key);
170
+ expect(names).toContain(SECRET_NAME);
171
+ // <-- The load-bearing assertion: raw body text must not contain the value.
172
+ expect(r.text).not.toContain(SECRET_VALUE);
173
+ expect(r.text).not.toContain("ciphertext");
174
+ expect(r.text).not.toContain("iv");
175
+ expect(r.text).not.toContain("tag");
176
+ });
177
+
178
+ test("a member of another network is refused and learns no key names", async () => {
179
+ const r = await get(`/api/secrets?network_id=${ownerNet}`, strangerToken);
180
+ expect(r.status).toBe(403);
181
+ expect(r.text).not.toContain(SECRET_NAME);
182
+ expect(r.text).not.toContain(SECRET_VALUE);
183
+ });
184
+
185
+ test("a node token is refused", async () => {
186
+ const r = await get(`/api/secrets?network_id=${ownerNet}`, nodeToken);
187
+ expect(r.status).toBe(403);
188
+ expect(r.body.error).toBe("user_token_required");
189
+ });
190
+ });
191
+
192
+ describe("GET /api/providers", () => {
193
+ test("returns the registry without secret references", async () => {
194
+ const r = await get(`/api/providers?network_id=${ownerNet}`, ownerToken);
195
+ expect(r.status).toBe(200);
196
+ expect(r.body.providers).toHaveLength(1);
197
+ expect(r.body.providers[0]).toMatchObject({ id: "hc-provider", label: "HC Provider", source: "hub" });
198
+ // The vault key NAME is a hint an attacker does not need; `exposeRefs` is
199
+ // false here on purpose.
200
+ expect(r.body.providers[0].secret_key_ref).toBeUndefined();
201
+ expect(r.text).not.toContain("HC_PROVIDER_KEY");
202
+ expect(r.text).not.toContain(SECRET_VALUE);
203
+ });
204
+
205
+ test("a member of another network is refused", async () => {
206
+ const r = await get(`/api/providers?network_id=${ownerNet}`, strangerToken);
207
+ expect(r.status).toBe(403);
208
+ expect(r.text).not.toContain("hc-provider");
209
+ });
210
+
211
+ test("a node token is refused", async () => {
212
+ const r = await get(`/api/providers?network_id=${ownerNet}`, nodeToken);
213
+ expect(r.status).toBe(403);
214
+ expect(r.body.error).toBe("user_token_required");
215
+ });
216
+ // 2026-10-31 —— **写侧原来只有 MCP**:客户端能显示「还没有 provider」,却没办法把它变成「有」。
217
+ // 这条把「第一行」确认成一次 HTTP 调用,并核对三件事:落库、读回来一致、revision 冲突是 409。
218
+ test("PUT /api/providers creates the first row, and the read side sees it", async () => {
219
+ const body = {
220
+ revision: 0,
221
+ provider: {
222
+ id: "hc-first", label: "First Provider", enabled: true,
223
+ protocol: "openai-chat-completions", baseUrl: "https://api.example.com/v1",
224
+ models: ["gpt-x"], key: "sk-test-not-a-real-secret",
225
+ },
226
+ };
227
+ const r = await fetch(`${base}/api/providers?network_id=${ownerNet}`, {
228
+ method: "PUT",
229
+ headers: { Authorization: `Bearer ${ownerToken}`, "content-type": "application/json" },
230
+ body: JSON.stringify(body),
231
+ });
232
+ const saved = await r.json() as any;
233
+ expect(r.status).toBe(200);
234
+ expect(saved.ok).toBe(true);
235
+ expect(saved.provider.id).toBe("hc-first");
236
+ expect(saved.provider.revision).toBe(1);
237
+ // 密钥永不回显
238
+ expect(JSON.stringify(saved)).not.toContain("sk-test-not-a-real-secret");
239
+
240
+ const read = await get(`/api/providers?network_id=${ownerNet}`, ownerToken);
241
+ const ids = read.body.providers.map((p: any) => p.id);
242
+ expect(ids).toContain("hc-first");
243
+
244
+ // 用旧 revision 再写一次 ⇒ 409(乐观锁;这正是「两个人同时改」的那一格)
245
+ const stale = await fetch(`${base}/api/providers?network_id=${ownerNet}`, {
246
+ method: "PUT",
247
+ headers: { Authorization: `Bearer ${ownerToken}`, "content-type": "application/json" },
248
+ body: JSON.stringify({ ...body, revision: 0, provider: { ...body.provider, label: "Second Writer" } }),
249
+ });
250
+ expect(stale.status).toBe(409);
251
+ expect((await stale.json() as any).error).toBe("hub_provider_revision_conflict");
252
+
253
+ // 别的网络成员不许写
254
+ const foreign = await fetch(`${base}/api/providers?network_id=${ownerNet}`, {
255
+ method: "PUT",
256
+ headers: { Authorization: `Bearer ${strangerToken}`, "content-type": "application/json" },
257
+ body: JSON.stringify({ ...body, revision: 1 }),
258
+ });
259
+ expect(foreign.status).toBe(403);
260
+
261
+ // 清理:这条测试造了一行,后面的断言按「1 行」计数,不能留痕
262
+ const { db } = await import("./db.js");
263
+ db.run(`DELETE FROM hub_provider_configs WHERE network_id = ?1 AND provider_id = 'hc-first'`, [ownerNet]);
264
+ });
265
+
266
+
267
+ // 2026-10-31 —— **写侧状态码是穷尽表**(外部复核:三元式默认分支 = 未映射与真实含义同值)。
268
+ // 两条断言分开:① 映射键 == 码清单;② 码清单里的每个码都真的在源码里被产出(跨源)。
269
+ test("provider write: every error code has a status, and every status code is really produced", async () => {
270
+ const { PROVIDER_WRITE_ERROR_CODES, PROVIDER_WRITE_STATUS } = await import("./hub-provider-config.js");
271
+ const { readFileSync } = await import("node:fs");
272
+ expect(Object.keys(PROVIDER_WRITE_STATUS).sort()).toEqual([...PROVIDER_WRITE_ERROR_CODES].sort());
273
+ for (const code of PROVIDER_WRITE_ERROR_CODES) {
274
+ expect(Number.isInteger(PROVIDER_WRITE_STATUS[code])).toBe(true);
275
+ expect(PROVIDER_WRITE_STATUS[code]).toBeGreaterThanOrEqual(400);
276
+ }
277
+ // 跨源:这些码必须能在源码里找到(`denied('x')` 或 vault 的 code 字面量),
278
+ // 否则清单会退化成「我们以为会发生的错误」。
279
+ const src = readFileSync(new URL("./hub-provider-config.ts", import.meta.url), "utf8");
280
+ const missing = [...PROVIDER_WRITE_ERROR_CODES].filter((c) => !src.includes(`'${c}'`) && !src.includes(`"${c}"`));
281
+ if (missing.length) throw new Error(`码清单里这些码在源码中找不到产出点:${missing.join(", ")}`);
282
+ });
283
+
284
+ // 2026-10-31 —— 节点当前 provider/模型的三态读口(#3145 的数据面)。
285
+ // 关键:**从未切换过 / 正在切 / 切失败** 必须能分开 —— 界面给的下一步完全不同。
286
+ test("GET /api/nodes/:id/provider-selection distinguishes never_switched / pending / applied / failed", async () => {
287
+ const { db } = await import("./db.js");
288
+ const nodeId = "ps-probe-node";
289
+ db.run(`INSERT OR REPLACE INTO nodes (node_id, node_name, network_id, alias, created_at, updated_at)
290
+ VALUES (?1, 'ps-probe', ?2, 'ps-probe', ?3, ?3)`, [nodeId, ownerNet, Date.now()]);
291
+ const read = async () => {
292
+ const r = await fetch(`${base}/api/nodes/${nodeId}/provider-selection`, { headers: { Authorization: `Bearer ${ownerToken}` } });
293
+ return { status: r.status, body: await r.json() as any };
294
+ };
295
+ try {
296
+ // ① 从未切换过:带 hint,selection 为 null(不假装是 Hub 的读数)
297
+ const a = await read();
298
+ expect(a.status).toBe(200);
299
+ expect(a.body.state).toBe("never_switched");
300
+ expect(a.body.selection).toBeNull();
301
+ expect(String(a.body.hint)).toContain("本地默认配置");
302
+
303
+ // ② 正在切:pending 时不带 hint(hint 只属于「没有读数」那一档)
304
+ const q = (requestId: string, status: string, payload: string | null, error: string | null) => db.run(
305
+ `INSERT OR REPLACE INTO daemon_provider_snapshots (request_id, network_id, daemon_node_id, requested_by, status, created_at, expires_at, observed_at, snapshot_json, error)
306
+ VALUES (?1, ?2, ?3, 'test', ?4, ?5, ?6, ?5, ?7, ?8)`,
307
+ [requestId, ownerNet, nodeId, status, Date.now(), Date.now() + 60_000, payload, error],
308
+ );
309
+ q("dpa_probe_1", "pending", null, null);
310
+ const b = await read();
311
+ expect(b.body.state).toBe("pending");
312
+ expect("hint" in b.body).toBe(false);
313
+
314
+ // ③ 已生效:selection 原样带回,并给出 revision
315
+ q("dpa_probe_2", "completed", JSON.stringify({ expected_revision: 7, provider_id: "main", model: "m1" }), null);
316
+ const c = await read();
317
+ expect(c.body.state).toBe("applied");
318
+ expect(c.body.selection).toMatchObject({ provider_id: "main", model: "m1" });
319
+ expect(c.body.revision).toBe(7);
320
+ expect(typeof c.body.observed_at).toBe("string");
321
+
322
+ // ④ 失败:必须带 error(否则界面只能说「失败了」)
323
+ q("dpa_probe_3", "failed", null, "daemon_rejected_selection");
324
+ const d = await read();
325
+ expect(d.body.state).toBe("failed");
326
+ expect(d.body.error).toBe("daemon_rejected_selection");
327
+ } finally {
328
+ db.run(`DELETE FROM daemon_provider_snapshots WHERE daemon_node_id = ?1`, [nodeId]);
329
+ db.run(`DELETE FROM node_daemon_bindings WHERE request_id = 'bind_ps'`);
330
+ db.run(`DELETE FROM nodes WHERE node_id = 'ps-target-node'`);
331
+ db.run(`DELETE FROM api_tokens WHERE token_id = 'tok_ps_write'`);
332
+ db.run(`DELETE FROM nodes WHERE node_id = ?1`, [nodeId]);
333
+ }
334
+ });
335
+
336
+ // 2026-10-31 —— 写侧:切 provider 的**第一步**(排队 + 带切换前读数)。
337
+ // 关键断言不是「返回 202」,而是「它把 before 带回来了」——没有 before,
338
+ // 「切成功了吗」只能靠客户端自己记住上一次。
339
+ test("POST /api/nodes/:id/provider-selection queues an application and returns the pre-state", async () => {
340
+ const { db } = await import("./db.js");
341
+ const nodeId = "ps-write-node";
342
+ // provider 切换只对 host_supervisor 守护进程有意义 —— 那条前置条件本身也要先被证明:
343
+ // 普通节点 ⇒ 404 daemon_not_found(下面第一条断言)。
344
+ db.run(`INSERT OR REPLACE INTO nodes (node_id, node_name, network_id, alias, created_at, updated_at, config_snapshot)
345
+ VALUES (?1, 'ps-write', ?2, 'ps-write', ?3, ?3, '{}')`, [nodeId, ownerNet, Date.now()]);
346
+ const selection0 = { node_id: nodeId, node_revision: "a".repeat(64), provider_id: "main", auth_id: "auth1", model: "m1", confirm_restart: true };
347
+ const postRaw = async (body: any) => {
348
+ const r = await fetch(`${base}/api/nodes/${nodeId}/provider-selection`, {
349
+ method: "POST",
350
+ headers: { Authorization: `Bearer ${ownerToken}`, "content-type": "application/json" },
351
+ body: JSON.stringify(body),
352
+ });
353
+ return { status: r.status, body: await r.json() as any };
354
+ };
355
+ db.run(`INSERT OR REPLACE INTO daemon_provider_snapshots (request_id, network_id, daemon_node_id, requested_by, status, created_at, expires_at, observed_at, snapshot_json, error)
356
+ VALUES ('dpa_prev', ?1, ?2, 'test', 'completed', ?3, ?4, ?3, ?5, NULL)`,
357
+ [ownerNet, nodeId, Date.now(), Date.now() + 60_000, JSON.stringify({ expected_revision: 3, provider_id: "prev", model: "m0" })]);
358
+ // 真实语义:切的是**被这个守护进程监督的节点**,不是守护进程自己 ⇒ 需要一个 target 节点 + 一条 active 绑定
359
+ const targetId = "ps-target-node";
360
+ db.run(`INSERT OR REPLACE INTO nodes (node_id, node_name, network_id, alias, created_at, updated_at)
361
+ VALUES (?1, 'ps-target', ?2, 'ps-target', ?3, ?3)`, [targetId, ownerNet, Date.now()]);
362
+ db.run(`INSERT OR REPLACE INTO node_daemon_bindings (request_id, network_id, node_id, daemon_node_id, workdir, requested_by, status, created_at, updated_at)
363
+ VALUES ('bind_ps', ?1, ?2, ?3, '/tmp', 'test', 'active', ?4, ?4)`, [ownerNet, targetId, nodeId, Date.now()]);
364
+ const selection = { node_id: targetId, node_revision: "a".repeat(64), provider_id: "main", auth_id: "auth1", model: "m1", confirm_restart: true };
365
+ try {
366
+ const post = async (body: any) => {
367
+ const r = await fetch(`${base}/api/nodes/${nodeId}/provider-selection`, {
368
+ method: "POST",
369
+ headers: { Authorization: `Bearer ${ownerToken}`, "content-type": "application/json" },
370
+ body: JSON.stringify(body),
371
+ });
372
+ return { status: r.status, body: await r.json() as any };
373
+ };
374
+ // ① 普通节点(不是 host_supervisor)⇒ 404:切换只对守护进程有意义
375
+ expect((await postRaw({ revision: 3, selection: selection0 })).status).toBe(404);
376
+
377
+ // 补上前置条件:节点既要有 node-scoped token,也要 config_snapshot.role=host_supervisor
378
+ db.run(`INSERT OR REPLACE INTO api_tokens (token_id, token_hash, user_id, network_id, name, created_at)
379
+ VALUES ('tok_ps_write', 'hash', ?1, ?2, 'node:ps-write', datetime('now'))`, [ownerUserId, ownerNet]);
380
+ db.run(`UPDATE nodes SET config_snapshot = '{"role":"host_supervisor"}' WHERE node_id = ?1`, [nodeId]);
381
+
382
+ // 缺 revision ⇒ 400(且提示「先 GET 同一路由」)
383
+ const noRev = await post({ selection });
384
+ expect(noRev.status).toBe(400);
385
+ expect(noRev.body.error).toBe("invalid_revision");
386
+
387
+ // 正常:202 + state=pending + before 是上一次生效的 selection
388
+ const ok = await post({ revision: 3, selection });
389
+ if (ok.status !== 202) throw new Error(`期望 202,实际 ${ok.status}:${JSON.stringify(ok.body)}`);
390
+ expect(ok.status).toBe(202);
391
+ expect(ok.body.state).toBe("pending");
392
+ expect(ok.body.request_id).toMatch(/^dpa_/);
393
+ expect(ok.body.before).toMatchObject({ provider_id: "prev", model: "m0" });
394
+ expect(String(ok.body.hint)).toContain("pending 不等于生效");
395
+
396
+ // 回读:pending 状态在 GET 上立刻可见(写与读用同一个状态源)
397
+ const get = await fetch(`${base}/api/nodes/${nodeId}/provider-selection`, { headers: { Authorization: `Bearer ${ownerToken}` } });
398
+ const got = await get.json() as any;
399
+ expect(got.state).toBe("pending");
400
+ } finally {
401
+ db.run(`DELETE FROM daemon_provider_applications WHERE request_id IN (SELECT request_id FROM daemon_provider_snapshots WHERE daemon_node_id = ?1)`, [nodeId]);
402
+ db.run(`DELETE FROM daemon_provider_snapshots WHERE daemon_node_id = ?1`, [nodeId]);
403
+ db.run(`DELETE FROM node_daemon_bindings WHERE request_id = 'bind_ps'`);
404
+ db.run(`DELETE FROM nodes WHERE node_id = 'ps-target-node'`);
405
+ db.run(`DELETE FROM api_tokens WHERE token_id = 'tok_ps_write'`);
406
+ db.run(`DELETE FROM nodes WHERE node_id = ?1`, [nodeId]);
407
+ }
408
+ });
409
+ });
@@ -0,0 +1,156 @@
1
+ // 2026-10-31 —— **本地直跑会看到 3 条红,那不是回归**。
2
+ // 这 7 条里有 3 条(HTTP 端点 / names-only 密钥 / daemon 队列)依赖
3
+ // `.github/workflows/hub-provider-core.yml` 里的容器环境(`tests/test907-hub-provider/run.sh`,
4
+ // `--network none` + 特定 host 映射);在仓外 `bun test src/hub-provider-config.test.ts`
5
+ // 会看到 `status: "failed"`(服务端 URL 走不到 secure transport)。
6
+ // ⇒ 按本仓规矩把环境依赖写在文件头:否则下一个人会把 3 条环境红当成自己改坏的。
7
+ // ⇒ 判定这条文件是否健康,看那套 Docker 测试,不看本地 bun test。
8
+
9
+ import './require-explicit-test-db';
10
+ import { afterAll, beforeEach, expect, test } from 'bun:test';
11
+ import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'node:fs';
12
+ import { tmpdir } from 'node:os';
13
+ import { join } from 'node:path';
14
+ import { db } from './db';
15
+ import { registerTools } from './tools';
16
+ import { vaultGet } from './vault';
17
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
18
+ import { reconcileProviderSnapshots, secureProviderTransport } from '../../agent-node/src/runtime/daemon-provider-snapshot';
19
+ import { DaemonProviderStore } from '../../agent-network/src/daemon-provider-store';
20
+ const net = 'net_hub907', user = 'u_hub907', daemonId = 'n_hub907', alias = 'daemon907', token = 'tok_hub907';
21
+ const root = mkdtempSync(join(tmpdir(), 'hub907-')), key = 'TEST-ONLY-shared-provider-key';
22
+ function cleanup() {
23
+ for (const t of ['daemon_provider_writes', 'daemon_provider_applications', 'daemon_provider_logins']) db.run(`DELETE FROM ${t} WHERE request_id IN (SELECT request_id FROM daemon_provider_snapshots WHERE network_id=?1)`, [net]);
24
+ for (const t of ['hub_provider_bindings', 'hub_provider_configs', 'network_secrets', 'daemon_provider_snapshots', 'nodes', 'api_tokens', 'network_members']) db.run(`DELETE FROM ${t} WHERE network_id=?1`, [net]);
25
+ db.run('DELETE FROM networks WHERE network_id=?1', [net]); db.run('DELETE FROM users WHERE user_id=?1', [user]);
26
+ }
27
+ beforeEach(() => {
28
+ cleanup(); rmSync(join(root, '.anet'), { recursive: true, force: true });
29
+ process.env.ANET_HUB_SECRET_VAULT_KEY = '42'.repeat(32);
30
+ db.run("INSERT INTO users(user_id,username,password_hash,role) VALUES(?1,?1,'x','user')", [user]);
31
+ db.run('INSERT INTO networks(network_id,network_name,owner_id) VALUES(?1,?1,?2)', [net, user]);
32
+ db.run("INSERT INTO network_members(user_id,network_id,role) VALUES(?1,?2,'owner')", [user, net]);
33
+ db.run('INSERT INTO nodes(node_id,node_name,alias,network_id,config_snapshot) VALUES(?1,?2,?2,?3,?4)', [daemonId, alias, net, JSON.stringify({ role: 'host_supervisor' })]);
34
+ db.run("INSERT INTO api_tokens(token_id,user_id,network_id,scope,name,token_hash) VALUES(?1,?2,?3,'network',?4,?5)", [token, user, net, `node:${alias}`, `hash_${token}`]);
35
+ const dir = join(root, '.anet/nodes', alias); mkdirSync(dir, { recursive: true, mode: 0o700 });
36
+ writeFileSync(join(dir, 'config.json'), JSON.stringify({ role: 'host_supervisor', node_id: daemonId, network_id: net }), { mode: 0o600 });
37
+ });
38
+ afterAll(() => { cleanup(); rmSync(root, { recursive: true, force: true }); });
39
+ function client(kind = 'human') {
40
+ const handlers: Record<string, any> = {}, server = new McpServer({ name: 'test907', version: '0' }) as any;
41
+ const tool = server.tool.bind(server), register = server.registerTool.bind(server);
42
+ server.tool = (name: string, desc: any, shape: any, handler: any) => { handlers[name] = handler; return tool(name, desc, shape, handler); };
43
+ server.registerTool = (name: string, config: any, handler: any) => { handlers[name] = handler; return register(name, config, handler); };
44
+ registerTools(server, undefined, kind === 'daemon' ? net : null, kind === 'anonymous' ? null : user, alias, kind === 'daemon', kind === 'daemon' ? token : null);
45
+ return async (name: string, args: any = {}) => JSON.parse((await handlers[name](args)).content[0].text);
46
+ }
47
+ const provider = () => ({ id: 'shared', label: 'Shared model', enabled: true, protocol: 'openai-responses', baseUrl: 'https://provider.example/v1', models: ['fixture-model'], key });
48
+ const save = (human: ReturnType<typeof client>, value = provider(), revision = 0) => human('daemon_provider_snapshot', { action: 'hub_put', id: value.id, network_id: net, revision, provider: value });
49
+ const bind = (human: ReturnType<typeof client>, target = daemonId, revision = 1) => human('daemon_provider_snapshot', { action: 'hub_bind', network_id: net, id: 'shared', revision, provider: { daemon_node_id: target, daemon_revision: 0, confirm: true } });
50
+ test('HTTP Hub and API endpoint support save, explicit bind and exact private-store readback', async () => {
51
+ expect(secureProviderTransport('http://hub907.example.test')).toBe(true);
52
+ expect(secureProviderTransport('ftp://hub907.example.test')).toBe(false);
53
+ expect(secureProviderTransport('http://user:password@hub907.example.test')).toBe(false);
54
+ const human = client(), daemon = client('daemon');
55
+ const config = { ...provider(), baseUrl: 'http://provider.example/v1' };
56
+ const saved = await save(human, config); expect(saved.ok).toBe(true);
57
+ expect(saved.provider.baseUrl).toBe(config.baseUrl);
58
+ const queued = await bind(human); expect(queued.ok).toBe(true);
59
+ await reconcileProviderSnapshots({ workDir: root, alias, networkId: net, daemonId,
60
+ serverUrl: 'http://hub907.example.test', callCommHub: daemon, warn: message => console.warn(message) });
61
+ const receipt = await human('daemon_provider_snapshot', { action: 'read', id: queued.request_id, network_id: net });
62
+ expect(receipt.status).toBe('succeeded');
63
+ expect(receipt.snapshot.providers[0].runtimes[0].auth[0].baseUrl).toBe(config.baseUrl);
64
+ expect(JSON.stringify([saved, queued, receipt])).not.toContain(key);
65
+ const store = new DaemonProviderStore(join(root, '.anet/nodes', alias));
66
+ await store.withApiKey({ revision: 1, providerId: queued.provider_reference.daemon_provider_id, authId: 'hub_key', model: 'fixture-model' }, async actual => {
67
+ expect(actual.baseUrl).toBe(config.baseUrl); expect(actual.key).toBe(key);
68
+ }); // Exact synthetic key in local callback, no external model request.
69
+ for (const baseUrl of ['ftp://provider.example/v1', 'http://user:pass@provider.example/v1', 'http://provider.example/v1?key=secret']) {
70
+ expect(await save(human, { ...provider(), id: 'invalid', baseUrl })).toMatchObject({ ok: false, error: 'invalid_hub_provider' });
71
+ }
72
+ });
73
+ test('existing names-only vault key → Provider reference → actual daemon store, without re-entering key', async () => {
74
+ const human = client(), daemon = client('daemon');
75
+ expect(await human('upsert_network_secret', { network_id: net, key: 'SHARED_API_KEY', value: key })).toMatchObject({ ok: true });
76
+ const { key: ignored, ...config } = provider();
77
+ const saved = await save(human, { ...config, secretKeyRef: 'SHARED_API_KEY' } as any);
78
+ expect(saved.provider).toMatchObject({ secret_key_ref: 'SHARED_API_KEY', credential_present: true });
79
+ expect(db.get<any>('SELECT secret_key_ref FROM hub_provider_configs WHERE network_id=?1', net).secret_key_ref).toBe('SHARED_API_KEY');
80
+ const legacy = await human('daemon_provider_snapshot', { action: 'hub_read', id: 'hub', network_id: net });
81
+ expect(legacy.providers[0].secret_key_ref).toBeUndefined(); // older strict client shape unchanged
82
+ const modern = await human('daemon_provider_snapshot', { action: 'hub_read', id: 'hub', network_id: net, provider: { include_secret_refs: true } });
83
+ expect(modern.secret_reference_supported).toBe(true); expect(modern.providers[0].secret_key_ref).toBe('SHARED_API_KEY');
84
+ expect(JSON.stringify([saved, legacy, modern])).not.toContain(key);
85
+ const queued = await bind(human); expect(queued.ok).toBe(true);
86
+ await reconcileProviderSnapshots({ workDir: root, alias, networkId: net, daemonId, serverUrl: 'https://hub907.example.test', callCommHub: daemon, warn: message => console.warn(message) });
87
+ const receipt = await human('daemon_provider_snapshot', { action: 'read', id: queued.request_id, network_id: net });
88
+ expect(receipt.status).toBe('succeeded'); expect(receipt.snapshot.providers[0].runtimes[0].auth[0].credential_present).toBe(true);
89
+ const store = new DaemonProviderStore(join(root, '.anet/nodes', alias));
90
+ await store.withApiKey({ revision: receipt.snapshot.revision, providerId: queued.provider_reference.daemon_provider_id, authId: 'hub_key', model: 'fixture-model' }, async profile => {
91
+ expect(profile.key).toBe(key); expect(profile.baseUrl).toBe(config.baseUrl);
92
+ }); // synthetic local callback only; no model/vendor request
93
+ expect(JSON.stringify(receipt)).not.toContain(key);
94
+ // Switching back to Provider-owned plaintext never changes the reusable named key.
95
+ await save(human, { ...provider(), key: 'TEST-ONLY-provider-specific' }, 1);
96
+ expect(vaultGet(net, 'SHARED_API_KEY')).toBe(key);
97
+ expect(db.get<any>('SELECT secret_key_ref FROM hub_provider_configs WHERE network_id=?1', net).secret_key_ref).not.toBe('SHARED_API_KEY');
98
+ });
99
+ test('missing or ambiguous references do not save; explicit ref replacement updates the stored reference', async () => {
100
+ const human = client(); const { key: ignored, ...config } = provider();
101
+ expect(await save(human, { ...config, secretKeyRef: 'MISSING_KEY' } as any)).toMatchObject({ ok: false, error: 'provider_secret_reference_missing' });
102
+ expect(await save(human, { ...provider(), secretKeyRef: 'SHARED_API_KEY' } as any)).toMatchObject({ ok: false, error: 'invalid_provider_secret_reference' });
103
+ await save(human);
104
+ await human('upsert_network_secret', { network_id: net, key: 'SECOND_API_KEY', value: 'TEST-ONLY-second-key' });
105
+ expect((await save(human, { ...config, secretKeyRef: 'SECOND_API_KEY' } as any, 1)).provider.secret_key_ref).toBe('SECOND_API_KEY');
106
+ expect(db.get<any>('SELECT secret_key_ref FROM hub_provider_configs WHERE network_id=?1', net).secret_key_ref).toBe('SECOND_API_KEY');
107
+ });
108
+ test('actual Hub tool atomically saves encrypted Provider; metadata read and conflict never echo key', async () => {
109
+ const human = client(); const result = await save(human); expect(result.ok).toBe(true);
110
+ expect(result.provider).toMatchObject({ id: 'shared', revision: 1, source: 'hub', credential_present: true, compatible_runtimes: ['codex-tui'] });
111
+ const read = await human('daemon_provider_snapshot', { action: 'hub_read', id: 'hub', network_id: net }); expect(read.providers).toHaveLength(1);
112
+ // 2026-10-31 —— **精确键集**(#3171):客户端「可选模型」这一面直接消费这两个投影,
113
+ // 而多给一个键(尤其 secret_key_ref)在这条线上是最严重的那类改动。
114
+ // 实际四键(我第一版漏了 network_id —— 断言当场纠正)。
115
+ expect(Object.keys(read).sort()).toEqual(["network_id", "ok", "providers", "source"]);
116
+ // provider 视图实际 12 键(我第一版写了 6 个,漏了 baseUrl/enabled/models/protocol/updated_at/verification)
117
+ expect(Object.keys(result.provider).sort()).toEqual([
118
+ "baseUrl", "compatible_runtimes", "credential_present", "enabled", "id", "label",
119
+ "models", "protocol", "revision", "source", "updated_at", "verification",
120
+ ]);
121
+ expect(JSON.stringify([result, read])).not.toContain(key);
122
+ expect(await save(human)).toMatchObject({ ok: false, error: 'hub_provider_revision_conflict' });
123
+ const secret = db.get<any>('SELECT ciphertext FROM network_secrets WHERE network_id=?1', net);
124
+ expect(Buffer.from(secret.ciphertext).toString()).not.toContain(key);
125
+ });
126
+ test('Hub → actual daemon queue → pinned CLI store → redacted receipt, not runtime application', async () => {
127
+ const human = client(), daemon = client('daemon'); await save(human);
128
+ const queued = await bind(human); expect(queued.ok).toBe(true); expect(queued.status).toBe('pending');
129
+ expect(JSON.stringify(queued)).not.toContain(key);
130
+ await reconcileProviderSnapshots({ workDir: root, alias, networkId: net, daemonId, serverUrl: 'https://hub907.example.test', callCommHub: daemon, warn: message => console.warn(message) });
131
+ const read = await human('daemon_provider_snapshot', { action: 'read', id: queued.request_id, network_id: net });
132
+ expect(read.status).toBe('succeeded'); expect(read.snapshot.revision).toBe(1);
133
+ expect(read.snapshot.providers[0]).toMatchObject({ id: queued.provider_reference.daemon_provider_id, label: 'Hub · Shared model' });
134
+ expect(read.snapshot.providers[0].runtimes[0].auth[0]).toMatchObject({ id: 'hub_key', models: ['fixture-model'], application: 'not_applied', verification: 'not_checked' });
135
+ expect(JSON.stringify(read)).not.toContain(key);
136
+ });
137
+ test('scope/role boundaries: no node or anonymous writes, no viewer distribution or foreign daemon', async () => {
138
+ expect(await save(client('daemon'))).toMatchObject({ ok: false, error: 'user_token_required' });
139
+ expect(await save(client('anonymous'))).toMatchObject({ ok: false, error: 'user_token_required' });
140
+ const human = client(); await save(human);
141
+ expect(await human('daemon_provider_snapshot', { action: 'hub_read', id: 'hub', network_id: 'foreign' })).toMatchObject({ ok: false, error: 'provider_access_denied' });
142
+ expect(await bind(human, 'foreign')).toMatchObject({ ok: false, error: 'daemon_not_found' });
143
+ db.run("UPDATE network_members SET role='viewer' WHERE network_id=?1 AND user_id=?2", [net, user]);
144
+ expect(await bind(human)).toMatchObject({ ok: false, error: 'provider_access_denied' });
145
+ expect(await save(human)).toMatchObject({ ok: false, error: 'provider_owner_required' });
146
+ });
147
+ test('protocol mismatch never queues Codex; editing source cancels pending distribution, not installed copies', async () => {
148
+ const human = client(); await save(human, { ...provider(), protocol: 'openai-chat-completions' });
149
+ expect(await bind(human)).toMatchObject({ ok: false, error: 'runtime_protocol_not_supported' });
150
+ await save(human, provider(), 1);
151
+ const queued = await bind(human, daemonId, 2);
152
+ expect(queued.ok).toBe(true); await save(human, { ...provider(), enabled: false }, 2);
153
+ const read = await human('daemon_provider_snapshot', { action: 'read', id: queued.request_id, network_id: net });
154
+ expect(read).toMatchObject({ status: 'failed', error: 'hub_provider_source_changed' });
155
+ expect(db.get('SELECT request_id FROM daemon_provider_writes WHERE request_id=?1', queued.request_id)).toBeNull();
156
+ });