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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (407) hide show
  1. package/README.md +129 -9
  2. package/bin/commhub.ts +93 -9
  3. package/package.json +7 -7
  4. package/src/ack-create-request-transport.test.ts +182 -0
  5. package/src/ack-create-request.test.ts +50 -7
  6. package/src/admin-delete-network-http.test.ts +228 -0
  7. package/src/admin-networks-http.test.ts +88 -0
  8. package/src/adoption-candidates-http.test.ts +137 -0
  9. package/src/adoption-candidates.ts +158 -0
  10. package/src/agent-access-batch.test.ts +210 -0
  11. package/src/agent-access.ts +487 -0
  12. package/src/agent-acl-groups-http.test.ts +247 -0
  13. package/src/agent-acl-http.test.ts +659 -0
  14. package/src/agent-acl-slice3-http.test.ts +654 -0
  15. package/src/agent-department-http.test.ts +215 -0
  16. package/src/agent-groups-perf.test.ts +223 -0
  17. package/src/agent-notice.ts +48 -0
  18. package/src/agent-team-whoami-http.test.ts +98 -0
  19. package/src/agent-teams-http.test.ts +330 -0
  20. package/src/agent-teams.ts +244 -0
  21. package/src/alias-baseline-2571.test.ts +162 -0
  22. package/src/alias-baseline.ts +113 -0
  23. package/src/alias-filter.test.ts +72 -0
  24. package/src/alias-filter.ts +42 -0
  25. package/src/api-host-supervisors-can-create-nodes.test.ts +350 -0
  26. package/src/api-host-supervisors-fallback.test.ts +6 -7
  27. package/src/api-host-supervisors-runtime-readiness.test.ts +195 -0
  28. package/src/api-nodes-shape.test.ts +120 -13
  29. package/src/auth-password-change-cli-tokens-http.test.ts +423 -0
  30. package/src/auth-sessions-http.test.ts +250 -0
  31. package/src/auth-validate.test.ts +5 -1
  32. package/src/auth-weak-password-login.test.ts +176 -0
  33. package/src/auth.ts +609 -51
  34. package/src/avatar-validate.test.ts +52 -2
  35. package/src/avatar-validate.ts +35 -1
  36. package/src/backfill-node-ids-2664.test.ts +128 -0
  37. package/src/binding-generation-http.test.ts +121 -0
  38. package/src/blocked-exit-on-reply.test.ts +122 -0
  39. package/src/broadcast-fanout-2721.test.ts +149 -0
  40. package/src/broadcast-fanout.ts +117 -0
  41. package/src/chain-attempt-dedup.test.ts +447 -0
  42. package/src/clone-node.test.ts +248 -0
  43. package/src/clone-node.ts +289 -0
  44. package/src/codex-config-flags.ts +77 -0
  45. package/src/codex-fork-contract.ts +23 -0
  46. package/src/codex-fork-migration.test.ts +38 -0
  47. package/src/commhub-bin-args.test.ts +85 -0
  48. package/src/config-apply-validate.test.ts +188 -1
  49. package/src/config-apply-validate.ts +222 -3
  50. package/src/cors-origins.test.ts +40 -0
  51. package/src/create-node-blocked-gate.test.ts +356 -0
  52. package/src/create-node-network-id.test.ts +91 -0
  53. package/src/create-node-tool-schema.test.ts +49 -0
  54. package/src/create-node-unicode-name.test.ts +120 -0
  55. package/src/create-node-validate.test.ts +199 -7
  56. package/src/create-node-validate.ts +232 -15
  57. package/src/create-node-workdir.test.ts +289 -0
  58. package/src/create-node.ts +88 -23
  59. package/src/daemon-provider-snapshots.test.ts +421 -0
  60. package/src/daemon-provider-snapshots.ts +327 -0
  61. package/src/daemon-token-owner-http.test.ts +236 -0
  62. package/src/dashboard-slash-routing-http.test.ts +109 -0
  63. package/src/db-adapter-guard.test.ts +148 -0
  64. package/src/db-adapter-translate.test.ts +128 -0
  65. package/src/db-adapter.ts +377 -91
  66. package/src/db-timestamp.test.ts +38 -0
  67. package/src/db-timestamp.ts +15 -0
  68. package/src/db.ts +1296 -153
  69. package/src/delivered-without-push.test.ts +140 -0
  70. package/src/department-groups-http.test.ts +209 -0
  71. package/src/department-groups-sync-http.test.ts +328 -0
  72. package/src/department-groups.ts +434 -0
  73. package/src/department-heads-http.test.ts +350 -0
  74. package/src/department-heads.ts +226 -0
  75. package/src/departments-agent-count.test.ts +132 -0
  76. package/src/departments-http.test.ts +185 -0
  77. package/src/departments-mcp.test.ts +128 -0
  78. package/src/departments.ts +318 -0
  79. package/src/desktop-message-seam.test.ts +150 -0
  80. package/src/desktop-message.test.ts +368 -0
  81. package/src/dm-file-scope-http.test.ts +178 -0
  82. package/src/empty-node-sweeper.test.ts +104 -0
  83. package/src/empty-node-sweeper.ts +88 -0
  84. package/src/env-transport-gate-http.test.ts +240 -0
  85. package/src/env-transport-gate.ts +80 -0
  86. package/src/env-transport-policy.ts +56 -0
  87. package/src/etag-of.test.ts +57 -0
  88. package/src/event-loop-lag.test.ts +180 -0
  89. package/src/event-loop-lag.ts +201 -0
  90. package/src/ext-token-shared.test.ts +60 -0
  91. package/src/ext-validation-regression.test.ts +131 -0
  92. package/src/external-schedule-edits-http.test.ts +321 -0
  93. package/src/external-schedule-edits-timestamps.test.ts +64 -0
  94. package/src/external-schedule-edits.ts +327 -0
  95. package/src/file-download-authz-dev-open.test.ts +135 -0
  96. package/src/file-download-authz.test.ts +404 -0
  97. package/src/file-download-date-bucket.test.ts +436 -0
  98. package/src/file-network-scope-dev-open.test.ts +97 -0
  99. package/src/file-network-scope.test.ts +732 -0
  100. package/src/group-membership-events-http.test.ts +264 -0
  101. package/src/group-messages-http.test.ts +482 -0
  102. package/src/group-messages.ts +297 -0
  103. package/src/health-anon-readers.ts +59 -0
  104. package/src/health-host-disk-2756.test.ts +71 -0
  105. package/src/health-redaction.test.ts +1574 -2
  106. package/src/host-supervisor-identity-http.test.ts +152 -0
  107. package/src/host-supervisor-identity.ts +92 -0
  108. package/src/host-supervisors-daemon-version.test.ts +137 -0
  109. package/src/http-gzip.test.ts +94 -0
  110. package/src/http-gzip.ts +112 -0
  111. package/src/hub-catalog-read-http.test.ts +266 -0
  112. package/src/hub-provider-config.test.ts +156 -0
  113. package/src/hub-provider-config.ts +124 -0
  114. package/src/hub-timestamp.test.ts +38 -0
  115. package/src/hub-timestamp.ts +27 -0
  116. package/src/human-dm.ts +215 -0
  117. package/src/human-inbox.ts +42 -0
  118. package/src/inbox-caller.ts +49 -0
  119. package/src/inbox-count-sse.test.ts +310 -0
  120. package/src/inbox-count.ts +29 -0
  121. package/src/index.ts +6 -2
  122. package/src/license-state.test.ts +56 -0
  123. package/src/license-state.ts +48 -0
  124. package/src/list-host-supervisors.test.ts +15 -4
  125. package/src/mcp-context-cost-http.test.ts +127 -0
  126. package/src/mcp-inflight.test.ts +92 -0
  127. package/src/mcp-inflight.ts +38 -0
  128. package/src/mcp-projects-events-http.test.ts +165 -0
  129. package/src/mcp-route-label-http.test.ts +120 -0
  130. package/src/mcp-write-network-resolution.test.ts +435 -0
  131. package/src/member-audit-network-id-http.test.ts +93 -0
  132. package/src/member-presence-http.test.ts +210 -0
  133. package/src/messages-ack-by-agent-http.test.ts +142 -0
  134. package/src/migrate-sqlite-to-pg.test.ts +47 -0
  135. package/src/migrate-sqlite-to-pg.ts +263 -0
  136. package/src/model-auth-notify-http.test.ts +181 -0
  137. package/src/model-auth-notify.ts +116 -0
  138. package/src/network-name-http.test.ts +75 -0
  139. package/src/network-rules-http.test.ts +169 -0
  140. package/src/network-rules.ts +129 -0
  141. package/src/network-scope.ts +276 -0
  142. package/src/network-token-membership-http.test.ts +139 -0
  143. package/src/node-alias-control.ts +12 -0
  144. package/src/node-attrs-validate.ts +88 -0
  145. package/src/node-attrs.test.ts +258 -0
  146. package/src/node-caller-identity-http.test.ts +1091 -0
  147. package/src/node-create-request-status-http.test.ts +105 -0
  148. package/src/node-daemon-bindings.test.ts +132 -0
  149. package/src/node-daemon-bindings.ts +135 -0
  150. package/src/node-failure-alert.test.ts +150 -0
  151. package/src/node-failure-alert.ts +177 -0
  152. package/src/node-files-transport.test.ts +344 -0
  153. package/src/node-health-codex-login.test.ts +120 -0
  154. package/src/node-health-dispatch-http.test.ts +335 -0
  155. package/src/node-health-guard.ts +121 -0
  156. package/src/node-health-passthrough.test.ts +115 -0
  157. package/src/node-health-store.ts +101 -0
  158. package/src/node-id-alias.test.ts +190 -0
  159. package/src/node-identity-conflict-http.test.ts +269 -0
  160. package/src/node-identity-conflict.ts +142 -0
  161. package/src/node-identity-mismatch.test.ts +74 -0
  162. package/src/node-in-flight-tasks.ts +31 -0
  163. package/src/node-lifecycle-controllable.test.ts +64 -0
  164. package/src/node-lifecycle-controllable.ts +53 -0
  165. package/src/node-lifecycle-read-http.test.ts +250 -0
  166. package/src/node-lifecycle-read.ts +124 -0
  167. package/src/node-logs-transport.test.ts +263 -0
  168. package/src/node-peer-allowlist.test.ts +114 -0
  169. package/src/node-permissions-http.test.ts +728 -0
  170. package/src/node-permissions.ts +494 -0
  171. package/src/node-request-retention.test.ts +281 -0
  172. package/src/node-request-retention.ts +120 -0
  173. package/src/node-secret-rest-http.test.ts +190 -0
  174. package/src/node-serviceability.test.ts +86 -0
  175. package/src/node-serviceability.ts +124 -0
  176. package/src/node-session-control-http.test.ts +310 -0
  177. package/src/node-session-control.ts +258 -0
  178. package/src/node-skills-transport.test.ts +212 -0
  179. package/src/node-token-identity.ts +35 -0
  180. package/src/node-token-ownership.ts +51 -0
  181. package/src/node-token-privilege-http.test.ts +158 -0
  182. package/src/not-found-api-http.test.ts +67 -0
  183. package/src/observer-avatar-http.test.ts +102 -9
  184. package/src/observer-push.test.ts +76 -0
  185. package/src/opencode-catalog-report-http.test.ts +139 -0
  186. package/src/opencode-v2-catalog.test.ts +268 -0
  187. package/src/opencode-v2-catalog.ts +356 -0
  188. package/src/package-version-consistency.test.ts +25 -0
  189. package/src/parent-source-marker.test.ts +50 -0
  190. package/src/password-network-tokens.ts +25 -0
  191. package/src/peer-reply-atomic.test.ts +457 -0
  192. package/src/peer-reply-capability.test.ts +70 -0
  193. package/src/pg-worker.ts +87 -0
  194. package/src/poll-pacing.test.ts +74 -0
  195. package/src/poll-pacing.ts +123 -0
  196. package/src/project-dir-warn-clear-http.test.ts +132 -0
  197. package/src/project-viewer-can-http.test.ts +116 -0
  198. package/src/push.test.ts +20 -10
  199. package/src/push.ts +382 -9
  200. package/src/redact-tokens.test.ts +86 -0
  201. package/src/redact-tokens.ts +43 -0
  202. package/src/rejection-counters.test.ts +72 -0
  203. package/src/rejection-counters.ts +173 -0
  204. package/src/rename.ts +38 -10
  205. package/src/reply-target-derivation.test.ts +96 -0
  206. package/src/report-status-handover-capabilities-http.test.ts +124 -0
  207. package/src/report-status-host-schema.test.ts +235 -0
  208. package/src/report-status-resume-id-handover.test.ts +184 -0
  209. package/src/report-status-secret-keys.test.ts +140 -0
  210. package/src/require-explicit-test-db.ts +9 -0
  211. package/src/requirement-due-reminders-http.test.ts +620 -0
  212. package/src/requirement-due-reminders.ts +416 -0
  213. package/src/requirement-events-http.test.ts +295 -0
  214. package/src/requirement-events.test.ts +45 -0
  215. package/src/requirement-events.ts +144 -0
  216. package/src/requirement-notify.ts +165 -0
  217. package/src/requirement-participant-notify-http.test.ts +309 -0
  218. package/src/requirement-tag-ops-http.test.ts +425 -0
  219. package/src/requirement-tag-tree-http.test.ts +275 -0
  220. package/src/requirement-tag-tree.ts +127 -0
  221. package/src/requirement-tags.ts +102 -0
  222. package/src/requirements-abandoned-http.test.ts +236 -0
  223. package/src/requirements-comment-http.test.ts +167 -0
  224. package/src/requirements-completed-at-migration.test.ts +70 -0
  225. package/src/requirements-errors-mcp-http.test.ts +164 -0
  226. package/src/requirements-errors.ts +158 -0
  227. package/src/requirements-etag-http.test.ts +91 -0
  228. package/src/requirements-http.test.ts +709 -0
  229. package/src/requirements-last-event-http.test.ts +349 -0
  230. package/src/requirements-list-mcp-slim-http.test.ts +155 -0
  231. package/src/requirements-list-slim-http.test.ts +324 -0
  232. package/src/requirements-mcp.test.ts +163 -0
  233. package/src/requirements-migrate.ts +283 -0
  234. package/src/requirements-owner-strict-mcp-http.test.ts +145 -0
  235. package/src/requirements-people-http.test.ts +114 -0
  236. package/src/requirements-people-mcp-http.test.ts +231 -0
  237. package/src/requirements-people.ts +196 -0
  238. package/src/requirements-priority-lowest.test.ts +114 -0
  239. package/src/requirements-projects-network-echo.test.ts +57 -0
  240. package/src/requirements-projects-parent-http.test.ts +123 -0
  241. package/src/requirements-search-http.test.ts +182 -0
  242. package/src/requirements-search.test.ts +32 -0
  243. package/src/requirements-search.ts +145 -0
  244. package/src/requirements-seq-http.test.ts +193 -0
  245. package/src/requirements-seq-migration.test.ts +63 -0
  246. package/src/requirements-start-date.test.ts +125 -0
  247. package/src/requirements-stats-http.test.ts +357 -0
  248. package/src/requirements-stats.ts +195 -0
  249. package/src/requirements-status-participants-http.test.ts +222 -0
  250. package/src/requirements-upgrade-e2e.test.ts +126 -0
  251. package/src/requirements-upgrade-migration.test.ts +98 -0
  252. package/src/requirements.ts +2042 -0
  253. package/src/resolve-port.test.ts +57 -0
  254. package/src/resolve-port.ts +44 -0
  255. package/src/rest-alias-network-fallback-http.test.ts +123 -0
  256. package/src/rest-alias-network-fallback.test.ts +60 -0
  257. package/src/rest-alias-network-fallback.ts +65 -0
  258. package/src/rest-explicit-columns-http.test.ts +266 -0
  259. package/src/rest-identity.test.ts +130 -0
  260. package/src/rest-identity.ts +141 -0
  261. package/src/rest-projections.ts +72 -0
  262. package/src/rest-read-network-real-chain.test.ts +97 -0
  263. package/src/rest-write-network-resolution.test.ts +133 -0
  264. package/src/restart-readiness-http.test.ts +121 -0
  265. package/src/restricted-files.ts +76 -0
  266. package/src/retention-first-sweep-quiet.test.ts +31 -0
  267. package/src/retention.test.ts +100 -40
  268. package/src/retention.ts +423 -104
  269. package/src/route-callers-http.test.ts +120 -0
  270. package/src/route-timing.test.ts +218 -0
  271. package/src/route-timing.ts +262 -0
  272. package/src/rules-file-duplicate-alias.test.ts +234 -0
  273. package/src/rules-file-session-target.test.ts +207 -0
  274. package/src/rules-file-transport.test.ts +237 -0
  275. package/src/runtime-label.test.ts +22 -0
  276. package/src/runtime-label.ts +21 -0
  277. package/src/runtime-readiness.ts +90 -0
  278. package/src/schedule-agent-mcp-http.test.ts +432 -0
  279. package/src/schedule-agent.ts +252 -0
  280. package/src/schedule-starved.test.ts +92 -0
  281. package/src/schedule-starved.ts +114 -0
  282. package/src/scheduled-backoff-http.test.ts +193 -0
  283. package/src/scheduled-backoff.ts +64 -0
  284. package/src/scheduled-doorbell-nodeless-session.test.ts +134 -0
  285. package/src/scheduled-failure-backoff-2622.test.ts +145 -0
  286. package/src/scheduled-failure-code.test.ts +73 -0
  287. package/src/scheduled-failure-code.ts +105 -0
  288. package/src/scheduled-failures-http.test.ts +279 -0
  289. package/src/scheduled-failures.ts +425 -0
  290. package/src/scheduled-noprogress-backoff-2622.test.ts +163 -0
  291. package/src/scheduled-offline-backoff-probe.test.ts +56 -0
  292. package/src/scheduled-offline.test.ts +131 -0
  293. package/src/scheduled-offline.ts +66 -0
  294. package/src/scheduled-outcome-guidance-http.test.ts +139 -0
  295. package/src/scheduled-outcome-guidance.ts +9 -0
  296. package/src/scheduled-reply-unread-http.test.ts +212 -0
  297. package/src/scheduled-requirement-wake-http.test.ts +279 -0
  298. package/src/scheduled-requirement-wake.ts +125 -0
  299. package/src/scheduled-run-terminal.test.ts +268 -0
  300. package/src/scheduled-skip-blocking-task.test.ts +120 -0
  301. package/src/scheduled-skip-path-backoff-2622.test.ts +98 -0
  302. package/src/scheduled-stuck-http.test.ts +316 -0
  303. package/src/scheduled-stuck-notice-cap.test.ts +80 -0
  304. package/src/scheduled-stuck.ts +219 -0
  305. package/src/scheduled-tasks-http.test.ts +679 -0
  306. package/src/scheduled-tasks.ts +959 -0
  307. package/src/scheduled-work-outcome-http.test.ts +154 -0
  308. package/src/scheduled-work-outcome.ts +50 -0
  309. package/src/scoped-secrets.ts +141 -0
  310. package/src/send-dedup-request-id.test.ts +229 -0
  311. package/src/send-reply-agent-warning.test.ts +202 -0
  312. package/src/send-reply-alias-optional.test.ts +131 -0
  313. package/src/send-reply-attachments.test.ts +458 -0
  314. package/src/send_dedup.test.ts +54 -0
  315. package/src/send_dedup.ts +52 -6
  316. package/src/serve-error.test.ts +73 -0
  317. package/src/serve-error.ts +56 -0
  318. package/src/server.ts +4921 -344
  319. package/src/session-task-on-dispatch.ts +14 -0
  320. package/src/session-token-ownership-http.test.ts +122 -0
  321. package/src/shared/codex-inventory.ts +41 -0
  322. package/src/shared/daemon-provider-login.ts +31 -0
  323. package/src/shared/daemon-provider-snapshot.ts +52 -0
  324. package/src/shared/external-schedule-contract.ts +60 -0
  325. package/src/shared/node-name.test.ts +62 -0
  326. package/src/shared/node-name.ts +161 -0
  327. package/src/shared/probe-host-allowlist-drift.test.ts +45 -0
  328. package/src/shared/provider-application.ts +29 -0
  329. package/src/shared/provider-collection.ts +14 -0
  330. package/src/shared/provider-initialization.ts +8 -0
  331. package/src/shared/reserved-env-drift.test.ts +10 -0
  332. package/src/shared/scoped-secret-contract.ts +5 -0
  333. package/src/shared/task-content-limit-drift.test.ts +28 -0
  334. package/src/shared/task-content-limit.ts +25 -0
  335. package/src/side-thread-command-transport.test.ts +312 -0
  336. package/src/side-thread-command-transport.ts +318 -0
  337. package/src/side-thread-http-integration.test.ts +233 -0
  338. package/src/side-thread-http.ts +504 -0
  339. package/src/side-thread-production.test.ts +72 -0
  340. package/src/side-thread-production.ts +118 -0
  341. package/src/side-thread.test.ts +1067 -0
  342. package/src/side-thread.ts +2499 -0
  343. package/src/skillhub-http.test.ts +142 -0
  344. package/src/sqlite-close-checkpoint.test.ts +78 -0
  345. package/src/start-node.test.ts +264 -0
  346. package/src/status-alias-filter-http.test.ts +106 -0
  347. package/src/status-alias-resolver-http.test.ts +163 -0
  348. package/src/status-alias-resolver.ts +19 -0
  349. package/src/status-node-id-filter-http.test.ts +161 -0
  350. package/src/status-read-cache-http.test.ts +229 -0
  351. package/src/status-read-cache.ts +129 -0
  352. package/src/stop-delete-node.test.ts +567 -1
  353. package/src/task-access-http.test.ts +402 -0
  354. package/src/task-access.ts +420 -0
  355. package/src/task-activity.ts +60 -0
  356. package/src/task-auth-origin-http.test.ts +93 -0
  357. package/src/task-auth-origin.test.ts +24 -0
  358. package/src/task-auth-origin.ts +7 -0
  359. package/src/task-consumption.test.ts +490 -0
  360. package/src/task-diagnostic-http.test.ts +149 -0
  361. package/src/task-diagnostic.test.ts +115 -0
  362. package/src/task-diagnostic.ts +118 -0
  363. package/src/task-expiry-notice-http.test.ts +287 -0
  364. package/src/task-expiry-notice.ts +315 -0
  365. package/src/task-idempotency-mcp.test.ts +142 -0
  366. package/src/task-idempotency.test.ts +76 -0
  367. package/src/task-idempotency.ts +81 -0
  368. package/src/task-late-replies.ts +54 -0
  369. package/src/task-late-reply-http.test.ts +227 -0
  370. package/src/task-lifecycle-watcher-busy.test.ts +114 -0
  371. package/src/task-lifecycle-watcher.test.ts +204 -0
  372. package/src/task-lifecycle-watcher.ts +109 -0
  373. package/src/task-network-resolution-http.test.ts +140 -0
  374. package/src/task-offline-delivery-2668.test.ts +119 -0
  375. package/src/task-offline-delivery.ts +81 -0
  376. package/src/task-orphan-http.test.ts +287 -0
  377. package/src/task-orphan.ts +119 -0
  378. package/src/task-queue-ahead-http.test.ts +309 -0
  379. package/src/task-queue-ahead-scale.test.ts +236 -0
  380. package/src/task-queue-ahead.ts +186 -0
  381. package/src/task-rejection-log-http.test.ts +160 -0
  382. package/src/task-rejection-log.ts +58 -0
  383. package/src/task-sender-http.test.ts +143 -0
  384. package/src/task-stale-open-http.test.ts +292 -0
  385. package/src/task-stale-open.ts +103 -0
  386. package/src/tasks-pagination-http.test.ts +141 -0
  387. package/src/team-rules-status-http.test.ts +90 -0
  388. package/src/team-rules-status.test.ts +59 -0
  389. package/src/team-rules-status.ts +72 -0
  390. package/src/tmux-allowlist.test.ts +48 -0
  391. package/src/tool-audience-http.test.ts +230 -0
  392. package/src/tool-audience.ts +127 -0
  393. package/src/tools-list-json-schema.test.ts +94 -0
  394. package/src/tools.ts +4320 -413
  395. package/src/upload-early-reject-guard.test.ts +155 -0
  396. package/src/uploads-http.test.ts +86 -7
  397. package/src/uploads.ts +103 -6
  398. package/src/user-avatar-http.test.ts +74 -0
  399. package/src/user-avatar-image.ts +160 -0
  400. package/src/user-avatar-migration.test.ts +25 -0
  401. package/src/user-avatar-upload-http.test.ts +348 -0
  402. package/src/user-inbox-by-agent-http.test.ts +161 -0
  403. package/src/user-inbox-netid-notnull.test.ts +122 -0
  404. package/src/user-inbox-read-http.test.ts +223 -0
  405. package/src/user-inbox-schema.test.ts +54 -0
  406. package/src/version-stats.test.ts +66 -0
  407. package/src/version-stats.ts +109 -0
@@ -0,0 +1,72 @@
1
+ // 2026-10-31 —— 拒绝原因计数的契约。
2
+ //
3
+ // 三条断言对应三条设计约束(见 rejection-counters.ts):
4
+ // ① 按 reason 分桶(不是只有一个总数)
5
+ // ② 键有限/可枚举(客户端塞不了长串把键空间撑爆)
6
+ // ③ 快照有序(两次读数可比;无序 Map 会让“同一个计数器”看起来在变)
7
+
8
+ import { describe, expect, test, beforeEach } from "bun:test";
9
+ import {
10
+ recordTaskRejection,
11
+ taskRejectionCounters,
12
+ resetTaskRejectionCounters,
13
+ } from "./rejection-counters.js";
14
+
15
+ beforeEach(() => resetTaskRejectionCounters());
16
+
17
+ describe("taskRejectionCounters", () => {
18
+ test("buckets by status+code — a bare total would count frequency and hide the reason", () => {
19
+ recordTaskRejection(401, "unauthorized");
20
+ recordTaskRejection(401, "unauthorized");
21
+ recordTaskRejection(400, "model_package_request_invalid");
22
+ recordTaskRejection(403, "runtime_sdk_csrf_invalid");
23
+ const c = taskRejectionCounters();
24
+ expect(c.total).toBe(4);
25
+ expect(c.by_reason).toEqual({
26
+ "400:model_package_request_invalid": 1,
27
+ "401:unauthorized": 2,
28
+ "403:runtime_sdk_csrf_invalid": 1,
29
+ });
30
+ });
31
+
32
+ test("missing or non-string code falls into `unknown` — never silently merges into another bucket", () => {
33
+ recordTaskRejection(500, undefined);
34
+ recordTaskRejection(500, null);
35
+ recordTaskRejection(500, 42);
36
+ const c = taskRejectionCounters();
37
+ expect(c.by_reason["500:unknown"]).toBe(3);
38
+ expect(c.total).toBe(3);
39
+ });
40
+
41
+ test("sanitizes the code so a client cannot inflate the key space", () => {
42
+ recordTaskRejection(400, "../../etc/passwd " + "x".repeat(200));
43
+ const c = taskRejectionCounters();
44
+ const keys = Object.keys(c.by_reason);
45
+ expect(keys.length).toBe(1);
46
+ // 只保留 \w . : - 且截断到 48 —— 键里不可能出现路径分隔或空白。
47
+ expect(keys[0]).toMatch(/^400:[A-Za-z0-9_.:-]+$/);
48
+ expect(keys[0].length).toBeLessThanOrEqual(48 + "400:".length);
49
+ });
50
+
51
+ test("snapshot is sorted and capped, with the overflow folded into `other`", () => {
52
+ for (let i = 0; i < 70; i += 1) recordTaskRejection(400, `code_${String(i).padStart(3, "0")}`);
53
+ const c = taskRejectionCounters();
54
+ const keys = Object.keys(c.by_reason);
55
+ expect(c.total).toBe(70);
56
+ expect(keys.length).toBe(65); // 64 个桶 + other
57
+ expect(c.by_reason.other).toBe(6);
58
+ // 有序:每次遍历顺序一致(否则两次快照无法比较)。
59
+ const sorted = [...keys.filter((k) => k !== "other")].sort();
60
+ expect(keys.filter((k) => k !== "other")).toEqual(sorted);
61
+ });
62
+
63
+ test("empty state is a readable zero, not an absent field", () => {
64
+ expect(taskRejectionCounters()).toEqual({ scope: "process_lifetime", total: 0, by_reason: {} });
65
+ });
66
+
67
+ // 2026-10-31 —— null 的第三个成因:记录还在日志里,只是不在这个窗口里。
68
+ // 那个事实必须由**数据**说出来,不能只写在注释里(读者不会去看注释)。
69
+ test("scope names the counter's lifetime, so a zero cannot be read as 'never happened'", () => {
70
+ expect(taskRejectionCounters().scope).toBe("process_lifetime");
71
+ });
72
+ });
@@ -0,0 +1,173 @@
1
+ // 2026-10-31 —— 拒绝原因不止要有日志,还要有**计数**。
2
+ //
3
+ // 背景:同一条路由的失败可以有很多原因(TM 侧那条是 401/400/403 三种「1 键」出口),
4
+ // 而日志只回答「有没有发生过」:要回答「今天拒了多少次、分别为什么」,
5
+ // 得去翻文件、还要考虑轮转与压缩 —— 而轮转后的 .gz 用 grep 读是**静默 0**。
6
+ //
7
+ // ⇒ **日志是事后取证,计数器是随时可读。**
8
+ //
9
+ // 🔴 三条设计约束(每条都对应一个我们已经踩过的坑):
10
+ // ① **按 reason 分桶,不是只有一个总数。**
11
+ // 一个总数会数出频率、看不出原因 —— 而「为什么」才是排查要的东西。
12
+ // ② **窗口必须显式给出。** 计数器随进程重启归零,
13
+ // 而「归零」与「没有发生」在读数上同值 ⇒ 必须与 startedAt 一起读。
14
+ // (历史教训:拿累计值除以 uptime 当速率 ⇒ 分母与分子不独立 ⇒ 刚重启必假阳性。)
15
+ // ③ **键必须有限且可枚举。** reason 由 (status, code) 组成,两者都来自
16
+ // 我们自己的出口 ⇒ 不会随请求内容膨胀(不做「按 URL 分桶」那种事)。
17
+ //
18
+ // 🔴 这一类的第四问(2026-10-31 补):**它在正常运行时会不会动?**
19
+ // 本模块的计数器属于「只有异常路径能让它 +1」那一类 ⇒ 正常运行时恒为 0,
20
+ // 而「0」读起来像「从没出过错」。它与「死计数器」在读数上完全一样,
21
+ // 但处置相反:死计数器该删,这一种**必须配一个 must-fire**(注入一次真实拒绝,看它跳不跳)。
22
+ // ⇒ 光有 by_reason 的形状断言不够:形状对、接线错,读数照样是 0。
23
+ // ⇒ 已有一处 must-fire:health-redaction.test.ts 里真实 POST /api/task 触发非 2xx 后读 /health。
24
+ //
25
+ // 🔴 已知缺口 —— 写成**可数清单**,而不是一句“可能不全”(2026-10-31 实测)。
26
+ //
27
+ // 🔑 行键是 **位置**(谁在那里拒绝),不是「失败种类」。
28
+ // 理由:同一类失败会随实现搬家 —— `express.json()` 把 parser 放在中间件里 ⇒ 不计;
29
+ // 我们把 `await req.json()` 放在 handler 里 ⇒ 计。
30
+ // **失败种类会漂,位置不会。** 分类键要选「不因重构而改变」的那个维度。
31
+ //
32
+ // 位置 是否计数 失败种类(只作说明)
33
+ // ────────────────────────────────────────────────────────────────────────────
34
+ // 鉴权中间件之前 ✗ 401 在到达 /api/task 之前返回
35
+ // 路由表之前 ✗ 全局/路由 404(未匹配)
36
+ // fetch() 之前(运行时层) ✗ Bun maxRequestBodySize(请求体超限)
37
+ // handler 内 · 解析 ✓ await req.json() 失败(本仓如此;Express 恰好相反)
38
+ // handler 内 · 校验/权限 ✓ schema / 网络归属 等非 2xx
39
+ // 错误 hook(500 兜底) ✗ buildServeErrorResponse
40
+ //
41
+ // ⇒ **位置仪器化 2/6;但链路覆盖 = 0/6。**
42
+ //
43
+ // 🔴 「2/6」这个写法本身是错的(2026-10-31 修正):
44
+ // 从上表可知被仪器化的是第 4、5 个位置 —— **不是前缀**。
45
+ // 而「要到达第 k 个位置,必须先经过前 k-1 个」⇒
46
+ // 一条能被判读的「链路覆盖」只能是 prefix(k);
47
+ // 非前缀的覆盖数会**暗示测试绕过链路**,而不是测了链路。
48
+ // ⇒ 所以按「首个未被观测的位置」算:**#1(鉴权中间件之前)就是那个洞 ⇒ 链覆盖 0/6**。
49
+ // ⇒ 2/6 只能念成「有 2 个点装了表」,不能念成「链路有三分之一被覆盖」。
50
+ // ⇒ 判据:**覆盖数必须是前缀**;非前缀时,报告要写「首个空洞在哪」,否则它是个自相矛盾的读数。
51
+ // ⇒ 清单要能被一次坏输入打出来,而不是靠回想中间件有哪些:
52
+ // `curl -X POST /api/task -H 'content-type: application/json' -d '{bad'` ⇒ 400,
53
+ // 看计数器动不动 ⇒ 动 ⇒ 这个位置被覆盖(本仓就是动的,见 health-redaction.test.ts)。
54
+ // ⇒ 为什么必须写分母:一个有分母的缺口是可排期的;一个没有分母的缺口只会被当成注释。
55
+ // ⇒ 补齐路径:把 +1 上移到中间件(401/404)或统一错误兜底(500),本次不做。
56
+ //
57
+ // 🔴 而下面的流程顺序也来自同一个教训:
58
+ // ① 先写「怎么让它 +1」的具体注入(命令或测试)
59
+ // ② 写不出 ⇒ **停下来先补出口** —— 此时暴露的往往是产品缺陷,不是测试缺陷
60
+ // ③ 写得出 ⇒ 再写断言
61
+ // ⇒ 形状断言写得再漂亮,也不要求「它能响」;而「能不能响」才是判据的入场券。
62
+ //
63
+ // 🔴 2026-10-31 补:窗口不能只给时长,要给**两个时刻**。
64
+ // 读者拿 counters.since(起点)与 /health.served_at(终点)相减才是窗口;
65
+ // 「我打算等 60 秒」是意图,不是读数 —— 而意图与读数在字段里同形。
66
+ // ⇒ 判据:速率/窗口类字段,分子分母各要自己的时刻戳;**被声明的那个永远不算**。
67
+ //
68
+ // 字段注释的三行格式(本模块的对外承诺):
69
+ // 由拒绝日志同一位置 +1;不由读它的人 +1;**只有非 2xx 的 /api/task 才会让它 >0**。
70
+ //
71
+ // 为什么不做成 Prometheus 指标:本仓没有指标管道,而 /health 已经是
72
+ // 「随手可读」的那个面。放这里能被 agent-node、dashboard、人都读到。
73
+
74
+ const REJECTION_COUNTS = new Map<string, number>();
75
+
76
+ /** 桶键:`<status>:<code>`。code 缺失时用 `unknown`,绝不省略 —— 省略会让两种原因并桶。 */
77
+ function bucketKey(status: number, code: unknown): string {
78
+ const raw = typeof code === "string" && code ? code : "unknown";
79
+ // 只保留可打印的短标识,防客户端塞长串把键空间撑爆。
80
+ const safe = raw.replace(/[^\w.:-]+/g, "_").slice(0, 48) || "unknown";
81
+ return `${status}:${safe}`;
82
+ }
83
+
84
+ /** 记一次拒绝。调用点:logTaskRejection —— 与那一行日志同一个位置,不会漏记。 */
85
+ export function recordTaskRejection(status: number, code: unknown): void {
86
+ const key = bucketKey(status, code);
87
+ REJECTION_COUNTS.set(key, (REJECTION_COUNTS.get(key) ?? 0) + 1);
88
+ }
89
+
90
+ /**
91
+ * 快照。**只读、已排序、键有限**:
92
+ * - 排序是为了让两次读数可比(无序 Map 会让「同一个计数器」看起来在变)
93
+ * - 上限 64 个桶,超出的合并进 `other` —— 计数器的价值在「为什么」,不在「穷举」
94
+ */
95
+ /**
96
+ * 2026-10-31 —— 加一个 `scope` 字段:让「这个数是进程生命期内的」无法被误读。
97
+ *
98
+ * null 有三个成因,而只有前两个被写进过文档:
99
+ * ① 真的没发生
100
+ * ② 记录随进程没了(进程内计数器)
101
+ * ③ **记录还在日志里,只是不在这个窗口里**
102
+ * ⇒ 第三种最常见,而它与「没发生」在读数上同值。
103
+ * ⇒ 与其在注释里提醒,不如让数据自己说明:`scope: "process_lifetime"`。
104
+ */
105
+ export function taskRejectionCounters(): {
106
+ scope: "process_lifetime";
107
+ total: number;
108
+ by_reason: Record<string, number>;
109
+ } {
110
+ let total = 0;
111
+ const entries = [...REJECTION_COUNTS.entries()].sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));
112
+ const byReason: Record<string, number> = {};
113
+ let other = 0;
114
+ for (const [key, count] of entries) {
115
+ total += count;
116
+ if (Object.keys(byReason).length < 64) byReason[key] = count;
117
+ else other += count;
118
+ }
119
+ if (other > 0) byReason.other = other;
120
+ // ⚠️ `scope` 说的是**这个计数的生命期**,不是证据的生命期:
121
+ // 进程没了 ⇒ 这里归零;但对应日志行仍在磁盘上 ⇒
122
+ // 「计数器为 0 且日志里有拒绝」是正常的,不是矛盾。
123
+ return { scope: "process_lifetime", total, by_reason: byReason };
124
+ }
125
+
126
+ /** 测试用:清空。生产路径不调用。 */
127
+ export function resetTaskRejectionCounters(): void {
128
+ REJECTION_COUNTS.clear();
129
+ }/**
130
+ * 2026-10-31 —— 出口清单**导出成数据**(外部复核 ②:「那张表的分母本身需要一个来源」)。
131
+ *
132
+ * 以前这六行只活在注释里:加一个中间件时,注释不会自己变,而「覆盖 2/6」这个比例
133
+ * 也没人知道分母从哪来。⇒ 现在它是数据,测试会断言:
134
+ * · 行数恰好 6(有变化就必须改测试,而不是让注释漂)
135
+ * · 每个 `counted: true` 的位置都有 must-fire 用例覆盖
136
+ * · 每个 `counted: false` 的位置都有「已知缺口」用例钉住(防止它悄悄被修好而报告仍写 0/6)
137
+ */
138
+ export const TASK_REJECTION_EXITS: ReadonlyArray<{
139
+ /** 位置(谁在那里拒绝)——分类键选位置,不选失败种类(种类会漂,位置不会) */
140
+ position: string;
141
+ /** 这个位置拒绝时,task_rejections 计数器会不会 +1 */
142
+ counted: boolean;
143
+ /** 钉住这一行的测试名(空串 = 还没有测试,属于缺口) */
144
+ pinned_by: string;
145
+ /**
146
+ * 当 `pinned_by` 是空串时,**必须**说明为什么钉不住、以及什么能让它被钉住。
147
+ *
148
+ * 2026-10-31 —— 外部复核 (b) 那条的直接应用:
149
+ * 「兜底值必须说出自己是兜底」(`failure_reason_source: none` / `artifact_errors_source: empty`)。
150
+ * 本表同款:空的 `pinned_by` 与「忘了填」在数据里长得一样 ——
151
+ * 而填一个 gap_reason 之后,「我们知道这是洞」与「我们没看见这个洞」就分开了。
152
+ *
153
+ * 反例守卫:`pinned_by` 与 `gap_reason` **恰好填一个**(两个都填 = 自相矛盾;都不填 = 又回到静默缺口)。
154
+ */
155
+ gap_reason?: string;
156
+ }> = [
157
+ { position: "before_auth_middleware", counted: false, pinned_by: "KNOWN GAP: unauthenticated /api/task rejection is NOT counted" },
158
+ { position: "before_route_table", counted: false, pinned_by: "KNOWN GAP: unmatched /api/* route 404 is NOT counted" },
159
+ { position: "before_fetch_runtime_body_limit", counted: false, pinned_by: "KNOWN GAP: body over runtime maxRequestBodySize is NOT counted" },
160
+ { position: "handler_parse", counted: true, pinned_by: "malformed JSON on /api/task IS counted" },
161
+ { position: "handler_validate_or_permission", counted: true, pinned_by: "a real rejected /api/task actually bumps the counter" },
162
+ {
163
+ position: "error_hook_500",
164
+ counted: false,
165
+ pinned_by: "",
166
+ gap_reason:
167
+ "未捕获异常 → 500 的出口目前没有夹具:要钉它必须能**按需诱发**一次未捕获异常," +
168
+ "而本仓没有测试专用路由(也不打算为测试在路由表里开洞)。" +
169
+ "解锁条件:出现一个可被合法输入诱发、且不依赖测试钩子的异常路径,或在测试里单独起一个只注册 error hook 的最小 server。",
170
+ },
171
+ ];
172
+
173
+
package/src/rename.ts CHANGED
@@ -15,8 +15,11 @@
15
15
  import { randomUUID } from "crypto";
16
16
  import { db } from "./db";
17
17
  import { getUserNetworkRole, getNetworkMembers } from "./auth";
18
+ import { canSeeAgent, isAgentRestricted } from "./agent-access";
18
19
  import { pushEvent } from "./push";
19
20
  import { eventBus } from "./event_bus";
21
+ import { aliasControlCharacter, describeAliasControlCharacter } from "./node-alias-control";
22
+ import { activeNodeTokenIds } from "./node-token-identity.js";
20
23
 
21
24
  export interface RenameResult {
22
25
  ok: boolean;
@@ -24,6 +27,9 @@ export interface RenameResult {
24
27
  error?: string;
25
28
  code?: string;
26
29
  suggested?: string;
30
+ reason?: string;
31
+ char?: string;
32
+ message?: string;
27
33
  }
28
34
 
29
35
  export interface CanonicalAlias {
@@ -35,7 +41,8 @@ export interface CanonicalAlias {
35
41
 
36
42
  function hasWriteAccess(userId: string, networkId: string): boolean {
37
43
  const role = getUserNetworkRole(userId, networkId);
38
- return !!role && role !== "viewer";
44
+ // 改名是对 Agent 的写操作;受限成员(只看授权 Agent 的成员)不能改。
45
+ return !!role && role !== "viewer" && !isAgentRestricted(userId, networkId);
39
46
  }
40
47
 
41
48
  // Resolve committed alias renames (old -> new), following short chains such
@@ -103,13 +110,27 @@ export function cleanupCommittedRenameSessions(networkIds: string[] | null = nul
103
110
 
104
111
  // PHASE 1 P3 — create a prepared rename_txn row reserving new_alias.
105
112
  // CAS guard (RFC §4 risk #3 TOCTOU): new_alias must be free both in the
106
- // sessions registry AND among in-flight prepared rename_txn rows.
113
+ // sessions/nodes registries AND among in-flight prepared rename_txn rows.
107
114
  export function prepareRename(
108
115
  userId: string, networkId: string, oldAlias: string, newAlias: string,
109
116
  ): RenameResult {
110
117
  if (!hasWriteAccess(userId, networkId)) return { ok: false, error: "no write access to this network" };
111
118
  if (!oldAlias || !newAlias) return { ok: false, error: "old and new alias required" };
119
+ const control = aliasControlCharacter(newAlias);
120
+ if (control !== null) {
121
+ return {
122
+ ok: false,
123
+ code: "node_alias_invalid",
124
+ error: "node_alias_invalid",
125
+ reason: "control_character",
126
+ char: control,
127
+ message: `alias cannot contain control character ${describeAliasControlCharacter(control)}`,
128
+ };
129
+ }
112
130
  if (oldAlias === newAlias) return { ok: false, error: "old and new alias are identical" };
131
+ if (db.all("SELECT node_id FROM nodes WHERE network_id=?1 AND alias=?2", networkId, oldAlias).length > 1) {
132
+ return { ok: false, error: "node_alias_ambiguous" };
133
+ }
113
134
 
114
135
  // old-alias must exist as a session in this network
115
136
  const oldSession = db.get<any>(
@@ -123,9 +144,9 @@ export function prepareRename(
123
144
  };
124
145
  }
125
146
 
126
- // new-alias must not be taken — in sessions OR reserved by another prepared txn
147
+ // A node can reserve its alias before it has ever reported a session.
127
148
  const newInSessions = db.get<any>(
128
- "SELECT 1 FROM sessions WHERE network_id = ?1 AND alias = ?2", networkId, newAlias);
149
+ "SELECT 1 FROM sessions WHERE network_id = ?1 AND alias = ?2 UNION ALL SELECT 1 FROM nodes WHERE network_id = ?1 AND alias = ?2", networkId, newAlias);
129
150
  if (newInSessions) return { ok: false, error: `alias "${newAlias}" already in use` };
130
151
  const newPrepared = db.get<any>(
131
152
  "SELECT txn_id FROM rename_txn WHERE network_id = ?1 AND new_alias = ?2 AND status = 'prepared'",
@@ -150,11 +171,15 @@ export function commitRename(userId: string, txnId: string): RenameResult {
150
171
  if (txn.status === "committed") return { ok: true, txn_id: txnId }; // idempotent
151
172
  if (txn.status === "aborted") return { ok: false, error: "rename transaction was aborted" };
152
173
  if (!hasWriteAccess(userId, txn.network_id)) return { ok: false, error: "no write access to this network" };
174
+ const nodes = db.all<{ node_id: string }>("SELECT node_id FROM nodes WHERE network_id=?1 AND alias=?2", txn.network_id, txn.old_alias);
175
+ if (nodes.length > 1) return { ok: false, error: "node_alias_ambiguous" };
176
+ // Resolve labels before changing the node alias, so legacy unbound ownership remains verifiable.
177
+ const tokenIds = nodes[0] ? activeNodeTokenIds(nodes[0].node_id, txn.network_id) : [];
153
178
 
154
- // Defense-in-depth: new-alias still free in sessions (prepare already CAS'd,
179
+ // Defense-in-depth: new-alias still free in both registries (prepare already CAS'd,
155
180
  // but a parallel direct registration could have raced in).
156
181
  const conflict = db.get<any>(
157
- "SELECT 1 FROM sessions WHERE network_id = ?1 AND alias = ?2", txn.network_id, txn.new_alias);
182
+ "SELECT 1 FROM sessions WHERE network_id = ?1 AND alias = ?2 UNION ALL SELECT 1 FROM nodes WHERE network_id = ?1 AND alias = ?2", txn.network_id, txn.new_alias);
158
183
  if (conflict) return { ok: false, error: `alias "${txn.new_alias}" was taken since prepare` };
159
184
 
160
185
  const renamedNode = db.transaction(() => {
@@ -165,9 +190,9 @@ export function commitRename(userId: string, txnId: string): RenameResult {
165
190
  db.run(
166
191
  "UPDATE nodes SET alias = ?1, updated_at = datetime('now') WHERE network_id = ?2 AND alias = ?3",
167
192
  [txn.new_alias, txn.network_id, txn.old_alias]);
168
- db.run(
169
- "UPDATE api_tokens SET name = ?1 WHERE network_id = ?2 AND name = ?3",
170
- [`node:${txn.new_alias}`, txn.network_id, `node:${txn.old_alias}`]);
193
+ for (const tokenId of tokenIds) db.run(
194
+ "UPDATE api_tokens SET name = ?1 WHERE token_id = ?2 AND network_id = ?3",
195
+ [`node:${txn.new_alias}`, tokenId, txn.network_id]);
171
196
  db.run(
172
197
  "UPDATE rename_txn SET status = 'committed', committed_at = datetime('now') WHERE txn_id = ?1",
173
198
  [txnId]);
@@ -214,8 +239,11 @@ export function commitRename(userId: string, txnId: string): RenameResult {
214
239
  // without this it would never receive node.renamed (#84 SSE channel fix:
215
240
  // N站马 confirmed the dashboard listens on the user channel). All members get
216
241
  // it, not just the owner, since any member's dashboard should reflect the rename.
242
+ // 多用户 Agent 权限:受限成员只收到他被授权的那个 Agent 的改名(否则等于把 alias 广播给他)。
217
243
  for (const member of getNetworkMembers(txn.network_id)) {
218
- if (member.username) pushEvent(member.username, renamedEvent, txn.network_id);
244
+ if (!member.username) continue;
245
+ if (!canSeeAgent(member.user_id, txn.network_id, { alias: txn.new_alias, nodeId: renamedNode?.node_id ?? null })) continue;
246
+ pushEvent(member.username, renamedEvent, txn.network_id);
219
247
  }
220
248
 
221
249
  return { ok: true, txn_id: txnId };
@@ -0,0 +1,96 @@
1
+ // f015d9d6 根因隔离:admin(dashboard/人类) 发给「无 node_id 的 MCP 会话」的任务,
2
+ // 其回执被 reply_target_mismatch 拒绝。
3
+ //
4
+ // 上报时给出的假设是「校验依赖投递绑定 ⇒ 任务还没真正 deliver 进会话时回执会被拒」。
5
+ // 本文件把两个变量分开量,一次只动一个:
6
+ // 变量 1 = 任务是否已投递(status created vs delivered,有无 SSE 订阅者)
7
+ // 变量 2 = 调用方是否显式传 alias
8
+ // 如果假设成立,变量 1 应当决定结果;如果 alias 推导才是决定因素,变量 2 才会。
9
+ import { beforeEach, afterAll, describe, expect, test } from "bun:test";
10
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
11
+ import { db } from "./db.js";
12
+ import { registerTools } from "./tools.js";
13
+ import { __resetSSEClientsForTest, createSSEStream } from "./push.js";
14
+
15
+ const NET = "net_admin_reply_f015";
16
+ const USER = "user_admin_reply_f015";
17
+ const ADMIN = "admin-f015"; // 人类/dashboard 发起方,无 node
18
+ const AGENT = "agent-mcp-f015"; // MCP 会话:sessions 行 node_id = NULL
19
+ const AGENT_NODE = "node-agent-f015"; // token 绑定的 node(会话本身仍无 node_id)
20
+
21
+ type ToolHandler = (args: any) => Promise<{ content: Array<{ type: "text"; text: string }> }>;
22
+
23
+ function cleanup() {
24
+ __resetSSEClientsForTest();
25
+ for (const t of ["tasks", "inbox", "task_events", "sessions", "api_tokens", "nodes", "rename_txn"]) {
26
+ try { db.run(`DELETE FROM ${t} WHERE network_id = ?1`, [NET]); } catch {}
27
+ }
28
+ try { db.run("DELETE FROM network_members WHERE network_id = ?1", [NET]); } catch {}
29
+ try { db.run("DELETE FROM networks WHERE network_id = ?1", [NET]); } catch {}
30
+ try { db.run("DELETE FROM users WHERE user_id = ?1", [USER]); } catch {}
31
+ }
32
+
33
+ function seed() {
34
+ db.run("INSERT INTO users (user_id, username, password_hash, role, created_at) VALUES (?1, ?1, 'x', 'admin', datetime('now'))", [USER]);
35
+ db.run("INSERT INTO networks (network_id, network_name, owner_id, created_at) VALUES (?1, ?1, ?2, datetime('now'))", [NET, USER]);
36
+ db.run("INSERT INTO network_members (user_id, network_id, role, joined_at) VALUES (?1, ?2, 'owner', datetime('now'))", [USER, NET]);
37
+ db.run(
38
+ "INSERT INTO nodes (node_id, node_name, alias, network_id, hostname, config_snapshot, created_at, updated_at, lifecycle_state) VALUES (?1, ?2, ?2, ?3, 'host', '{}', datetime('now'), datetime('now'), 'active')",
39
+ [AGENT_NODE, AGENT, NET],
40
+ );
41
+ // 🔴 关键夹具属性:会话行 node_id 为 NULL —— 这正是 MCP 挂载的 claude-code 会话的形状
42
+ db.run(
43
+ "INSERT INTO sessions (resume_id, alias, status, node_id, network_id, updated_at, last_seen_at) VALUES (?1, ?2, 'idle', NULL, ?3, datetime('now'), datetime('now'))",
44
+ [`cc-n_${AGENT}`, AGENT, NET],
45
+ );
46
+ db.run(
47
+ "INSERT INTO api_tokens (token_id, token_hash, user_id, network_id, name, scope, bound_node_id) VALUES (?1, ?2, ?3, ?4, ?5, 'network', ?6)",
48
+ [`token-${AGENT}`, `hash-${AGENT}`, USER, NET, `node:${AGENT}`, AGENT_NODE],
49
+ );
50
+ }
51
+
52
+ function toolsFor(alias: string): Record<string, ToolHandler> {
53
+ const server = new McpServer({ name: "admin-reply-f015", version: "0" }) as any;
54
+ const tools: Record<string, ToolHandler> = {};
55
+ const original = server.tool.bind(server);
56
+ server.tool = (name: string, description: string, schema: any, handler: ToolHandler) => {
57
+ tools[name] = handler; return original(name, description, schema, handler);
58
+ };
59
+ registerTools(server, undefined, NET, USER, alias, true, `token-${alias}`);
60
+ return tools;
61
+ }
62
+
63
+ function parse(res: { content: Array<{ text: string }> }) { return JSON.parse(res.content[0].text); }
64
+
65
+ /** 造一条 admin(人类) → AGENT 的任务;delivered 控制「是否已投递」这一个变量。 */
66
+ function seedAdminTask(taskId: string, delivered: boolean) {
67
+ db.run(
68
+ `INSERT INTO tasks (task_id, from_name, from_node_id, to_name, to_node_id, content, status, priority, network_id, created_at)
69
+ VALUES (?1, ?2, NULL, ?3, NULL, 'ping', ?4, 'normal', ?5, datetime('now'))`,
70
+ [taskId, ADMIN, AGENT, delivered ? "delivered" : "created", NET],
71
+ );
72
+ }
73
+
74
+ describe("f015d9d6 — admin→无 node_id 的 MCP 会话,回执绑定", () => {
75
+ beforeEach(() => { cleanup(); seed(); });
76
+ afterAll(() => cleanup());
77
+
78
+ test("变量1:任务【未投递】+ 省略 alias(走 #1085 推导)⇒ 回执应当成功", async () => {
79
+ seedAdminTask("t-undelivered", false);
80
+ const r = parse(await toolsFor(AGENT).send_reply({ in_reply_to: "t-undelivered", text: "done", status: "completed" }));
81
+ expect(r).toEqual(expect.objectContaining({ ok: true }));
82
+ });
83
+
84
+ test("变量1 对照:任务【已投递且有 SSE 订阅者】+ 省略 alias ⇒ 同样成功", async () => {
85
+ seedAdminTask("t-delivered", true);
86
+ createSSEStream(AGENT, NET);
87
+ const r = parse(await toolsFor(AGENT).send_reply({ in_reply_to: "t-delivered", text: "done", status: "completed" }));
88
+ expect(r).toEqual(expect.objectContaining({ ok: true }));
89
+ });
90
+
91
+ test("变量2:显式传一个不等于任务发起方的 alias ⇒ reply_target_mismatch", async () => {
92
+ seedAdminTask("t-wrong-alias", true);
93
+ const r = parse(await toolsFor(AGENT).send_reply({ alias: "someone-else", in_reply_to: "t-wrong-alias", text: "done", status: "completed" }));
94
+ expect(r).toEqual(expect.objectContaining({ ok: false, error: "reply_target_mismatch" }));
95
+ });
96
+ });
@@ -0,0 +1,124 @@
1
+ // #550 — the sticky session capability flags (rules_file_capable / skills_capable /
2
+ // files_capable / logs_capable) survive a session handover.
3
+ //
4
+ // report_status for an alias that already has a row under ANOTHER resume_id takes
5
+ // the DELETE + INSERT handover path. That path carried registered_at and the
6
+ // descriptive columns, but not the capability flags, so the new row started at
7
+ // the column default 0 — although the flags are meant to be sticky (only ever set
8
+ // to 1). Board #548: a production node's MCP channel reconnected under a new
9
+ // resume_id and the rules-file / skills / files / logs doorbells went dark.
10
+ //
11
+ // Pinned through the real HTTP entrance (POST /mcp with the node's own token):
12
+ // 1. flags set on resume A are still 1 after the same alias reports resume B
13
+ // without them — and after it switches back to A.
14
+ // 2. only flags that were 1 are carried; a 0 is never promoted.
15
+ // 3. a later report omitting the flags on the same resume_id still keeps them.
16
+ // 4. a user token cannot report for the alias, so it cannot hand the flags to a
17
+ // session of its own.
18
+ //
19
+ // 跑法:cd server && COMMHUB_DB=/tmp/x.db bun test src/report-status-handover-capabilities-http.test.ts
20
+ // PG:COMMHUB_TEST_PG_URL=… COMMHUB_PG_EXPERIMENTAL=1(tests/test2123-hub-postgres-ladder 里注册)
21
+ import { afterAll, beforeAll, describe, expect, test } from "bun:test";
22
+ import { mkdtempSync, rmSync } from "node:fs";
23
+ import { join } from "node:path";
24
+ import { tmpdir } from "node:os";
25
+ import { createNetworkTokenForNode, register } from "./auth.js";
26
+ import { db } from "./db.js";
27
+
28
+ const dir = mkdtempSync(join(tmpdir(), "anet-handover-caps-"));
29
+ const activeDbPath = process.env.COMMHUB_DB ?? (process.env.COMMHUB_TEST_PG_URL ? "postgres" : undefined);
30
+ if (!activeDbPath) throw new Error("report-status-handover-capabilities requires COMMHUB_DB (or COMMHUB_TEST_PG_URL) before module import");
31
+
32
+ const stamp = Date.now();
33
+ let server: any;
34
+ let base = "";
35
+ let ownerToken = "", ownerId = "", NET = "";
36
+ type Node = { alias: string; nodeId: string; token: string };
37
+ const nodes: Record<string, Node> = {};
38
+
39
+ async function tool(token: string, name: string, args: Record<string, unknown>) {
40
+ const res = await fetch(`${base}/mcp`, {
41
+ method: "POST",
42
+ headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json", Accept: "application/json, text/event-stream", "MCP-Protocol-Version": "2025-03-26" },
43
+ body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name, arguments: args } }),
44
+ });
45
+ const raw = await res.text();
46
+ const data = raw.split("\n").filter((x) => x.startsWith("data:"));
47
+ const payload = data.length ? JSON.parse(data.at(-1)!.slice(5).trim()) : JSON.parse(raw);
48
+ const text = payload.result.content[0].text;
49
+ if (!text.startsWith("{")) throw new Error(`${name}: ${text}`);
50
+ return JSON.parse(text);
51
+ }
52
+
53
+ // resume_id is the sessions primary key — every alias below uses its own (cc-*-<nodeId>).
54
+ const ALL_FLAGS = { rules_file_capable: true, skills_capable: true, files_capable: true, logs_capable: true };
55
+ const report = (token: string, n: Node, resume: string, extra: Record<string, unknown> = {}) =>
56
+ tool(token, "report_status", { resume_id: resume, alias: n.alias, status: "idle", agent: "claude-code", network_id: NET, ...extra });
57
+
58
+ type CapRow = { resume_id: string; rules_file_capable: number; skills_capable: number; files_capable: number; logs_capable: number };
59
+ const capRows = (alias: string) =>
60
+ db.all<CapRow>(
61
+ "SELECT resume_id, rules_file_capable, skills_capable, files_capable, logs_capable FROM sessions WHERE alias = ?1 AND network_id = ?2",
62
+ alias, NET,
63
+ ).map((r) => ({
64
+ resume_id: r.resume_id,
65
+ rules_file_capable: Number(r.rules_file_capable), skills_capable: Number(r.skills_capable),
66
+ files_capable: Number(r.files_capable), logs_capable: Number(r.logs_capable),
67
+ }));
68
+
69
+ beforeAll(async () => {
70
+ process.env.COMMHUB_UPLOADS_DIR = join(dir, "uploads");
71
+ process.env.HOST = "127.0.0.1";
72
+ const owner = register(`hcap_owner_${stamp}`, "HandoverCaps123!", undefined, "seed");
73
+ ownerToken = owner.token!; ownerId = owner.user!.user_id; NET = owner.network_id!;
74
+ for (const key of ["all", "some", "user"]) {
75
+ const alias = `hcap-${key}-${stamp}`;
76
+ const nodeId = `n_hcap_${key}_${stamp}`;
77
+ const minted = createNetworkTokenForNode(ownerId, NET, alias, nodeId);
78
+ expect(minted.ok).toBe(true);
79
+ nodes[key] = { alias, nodeId, token: minted.token! };
80
+ }
81
+ const mod: any = await import("./server.js");
82
+ server = mod.bootServer({ port: 0, hostname: "127.0.0.1" });
83
+ base = `http://127.0.0.1:${server.port}`;
84
+ }, 30_000);
85
+
86
+ afterAll(() => {
87
+ try { server?.stop?.(true); } catch {}
88
+ try { rmSync(dir, { recursive: true, force: true }); } catch {}
89
+ });
90
+
91
+ describe("#550 sticky capability flags survive a resume_id handover", () => {
92
+ test("all four flags carry to the new resume_id, and back again", async () => {
93
+ const n = nodes.all!;
94
+ expect((await report(n.token, n, `cc-a-${n.nodeId}`, ALL_FLAGS)).ok).toBe(true);
95
+ expect(capRows(n.alias)).toEqual([{ resume_id: `cc-a-${n.nodeId}`, rules_file_capable: 1, skills_capable: 1, files_capable: 1, logs_capable: 1 }]);
96
+
97
+ // The channel reconnects under a new resume_id and reports WITHOUT the flags.
98
+ expect((await report(n.token, n, `cc-b-${n.nodeId}`)).ok).toBe(true);
99
+ expect(capRows(n.alias)).toEqual([{ resume_id: `cc-b-${n.nodeId}`, rules_file_capable: 1, skills_capable: 1, files_capable: 1, logs_capable: 1 }]);
100
+
101
+ // Same resume_id, flags omitted again (status-only report) — still sticky.
102
+ expect((await report(n.token, n, `cc-b-${n.nodeId}`)).ok).toBe(true);
103
+ expect(capRows(n.alias)[0]).toMatchObject({ rules_file_capable: 1, skills_capable: 1, files_capable: 1, logs_capable: 1 });
104
+
105
+ // Two reporters taking turns (agent-node + TUI MCP): switching back keeps them too.
106
+ expect((await report(n.token, n, `cc-a-${n.nodeId}`)).ok).toBe(true);
107
+ expect(capRows(n.alias)).toEqual([{ resume_id: `cc-a-${n.nodeId}`, rules_file_capable: 1, skills_capable: 1, files_capable: 1, logs_capable: 1 }]);
108
+ }, 20_000);
109
+
110
+ test("only flags that were 1 are carried — a 0 is never promoted", async () => {
111
+ const n = nodes.some!;
112
+ expect((await report(n.token, n, `cc-a-${n.nodeId}`, { rules_file_capable: true, logs_capable: true })).ok).toBe(true);
113
+ expect((await report(n.token, n, `cc-b-${n.nodeId}`)).ok).toBe(true);
114
+ expect(capRows(n.alias)).toEqual([{ resume_id: `cc-b-${n.nodeId}`, rules_file_capable: 1, skills_capable: 0, files_capable: 0, logs_capable: 1 }]);
115
+ }, 20_000);
116
+
117
+ test("a user token cannot report for the alias, so it cannot take over the flags", async () => {
118
+ const n = nodes.user!;
119
+ expect((await report(n.token, n, `cc-a-${n.nodeId}`, ALL_FLAGS)).ok).toBe(true);
120
+ const r = await report(ownerToken, n, `cc-hijack-${n.nodeId}`);
121
+ expect(r.ok).toBe(false);
122
+ expect(capRows(n.alias)).toEqual([{ resume_id: `cc-a-${n.nodeId}`, rules_file_capable: 1, skills_capable: 1, files_capable: 1, logs_capable: 1 }]);
123
+ }, 20_000);
124
+ });