@sleep2agi/commhub-server 0.9.0-preview.2 → 0.9.0-preview.200

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 (412) hide show
  1. package/README.md +130 -10
  2. package/bin/commhub.ts +99 -11
  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 +374 -0
  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 +267 -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 +271 -0
  27. package/src/api-host-supervisors-runtime-readiness.test.ts +195 -0
  28. package/src/api-nodes-shape.test.ts +279 -0
  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 +611 -51
  34. package/src/avatar-validate.test.ts +163 -0
  35. package/src/avatar-validate.ts +103 -0
  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/boot-side-effect.test.ts +124 -0
  40. package/src/broadcast-fanout-2721.test.ts +118 -0
  41. package/src/broadcast-fanout.ts +98 -0
  42. package/src/chain-attempt-dedup.test.ts +447 -0
  43. package/src/clone-node.test.ts +248 -0
  44. package/src/clone-node.ts +289 -0
  45. package/src/codex-config-flags.ts +77 -0
  46. package/src/codex-fork-contract.ts +23 -0
  47. package/src/codex-fork-migration.test.ts +38 -0
  48. package/src/commhub-bin-args.test.ts +85 -0
  49. package/src/config-apply-sec1.test.ts +107 -0
  50. package/src/config-apply-validate.test.ts +134 -1
  51. package/src/config-apply-validate.ts +111 -5
  52. package/src/create-node-blocked-gate.test.ts +356 -0
  53. package/src/create-node-network-id.test.ts +79 -0
  54. package/src/create-node-tool-schema.test.ts +49 -0
  55. package/src/create-node-unicode-name.test.ts +120 -0
  56. package/src/create-node-validate.test.ts +379 -0
  57. package/src/create-node-validate.ts +423 -0
  58. package/src/create-node-workdir.test.ts +289 -0
  59. package/src/create-node.test.ts +354 -0
  60. package/src/create-node.ts +411 -0
  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 +1501 -152
  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 +330 -0
  76. package/src/department-heads.ts +226 -0
  77. package/src/departments-agent-count.test.ts +129 -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 +177 -0
  87. package/src/env-transport-gate.ts +74 -0
  88. package/src/env-transport-policy.ts +21 -0
  89. package/src/event-loop-lag.test.ts +139 -0
  90. package/src/event-loop-lag.ts +150 -0
  91. package/src/ext-token-shared.test.ts +60 -0
  92. package/src/ext-validation-regression.test.ts +131 -0
  93. package/src/external-schedule-edits-http.test.ts +321 -0
  94. package/src/external-schedule-edits-timestamps.test.ts +64 -0
  95. package/src/external-schedule-edits.ts +327 -0
  96. package/src/file-download-authz-dev-open.test.ts +135 -0
  97. package/src/file-download-authz.test.ts +404 -0
  98. package/src/file-download-date-bucket.test.ts +436 -0
  99. package/src/file-network-scope-dev-open.test.ts +97 -0
  100. package/src/file-network-scope.test.ts +732 -0
  101. package/src/group-membership-events-http.test.ts +264 -0
  102. package/src/group-messages-http.test.ts +482 -0
  103. package/src/group-messages.ts +297 -0
  104. package/src/health-host-disk-2756.test.ts +49 -0
  105. package/src/health-redaction.test.ts +685 -0
  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 +187 -0
  112. package/src/hub-provider-config.test.ts +139 -0
  113. package/src/hub-provider-config.ts +105 -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 +15 -2172
  122. package/src/lifecycle-guard.ts +50 -0
  123. package/src/list-host-supervisors.test.ts +315 -0
  124. package/src/mcp-context-cost-http.test.ts +127 -0
  125. package/src/mcp-inflight.test.ts +92 -0
  126. package/src/mcp-inflight.ts +38 -0
  127. package/src/mcp-projects-events-http.test.ts +162 -0
  128. package/src/mcp-route-label-http.test.ts +120 -0
  129. package/src/mcp-write-network-resolution.test.ts +432 -0
  130. package/src/member-audit-network-id-http.test.ts +93 -0
  131. package/src/member-presence-http.test.ts +210 -0
  132. package/src/messages-ack-by-agent-http.test.ts +142 -0
  133. package/src/migrate-sqlite-to-pg.test.ts +47 -0
  134. package/src/migrate-sqlite-to-pg.ts +263 -0
  135. package/src/model-auth-notify-http.test.ts +181 -0
  136. package/src/model-auth-notify.ts +116 -0
  137. package/src/network-name-http.test.ts +75 -0
  138. package/src/network-rules-http.test.ts +169 -0
  139. package/src/network-rules.ts +129 -0
  140. package/src/network-scope.ts +276 -0
  141. package/src/network-token-membership-http.test.ts +139 -0
  142. package/src/node-alias-control.ts +12 -0
  143. package/src/node-attrs-validate.ts +88 -0
  144. package/src/node-attrs.test.ts +258 -0
  145. package/src/node-caller-identity-http.test.ts +1083 -0
  146. package/src/node-create-request-status-http.test.ts +105 -0
  147. package/src/node-daemon-bindings.test.ts +132 -0
  148. package/src/node-daemon-bindings.ts +135 -0
  149. package/src/node-failure-alert.test.ts +150 -0
  150. package/src/node-failure-alert.ts +177 -0
  151. package/src/node-files-transport.test.ts +344 -0
  152. package/src/node-health-codex-login.test.ts +120 -0
  153. package/src/node-health-dispatch-http.test.ts +279 -0
  154. package/src/node-health-guard.ts +105 -0
  155. package/src/node-health-passthrough.test.ts +115 -0
  156. package/src/node-health-store.ts +101 -0
  157. package/src/node-id-alias.test.ts +190 -0
  158. package/src/node-identity-conflict-http.test.ts +269 -0
  159. package/src/node-identity-conflict.ts +142 -0
  160. package/src/node-identity-mismatch.test.ts +74 -0
  161. package/src/node-in-flight-tasks.ts +31 -0
  162. package/src/node-lifecycle-controllable.test.ts +64 -0
  163. package/src/node-lifecycle-controllable.ts +53 -0
  164. package/src/node-lifecycle-read-http.test.ts +250 -0
  165. package/src/node-lifecycle-read.ts +124 -0
  166. package/src/node-logs-transport.test.ts +263 -0
  167. package/src/node-peer-allowlist.test.ts +79 -0
  168. package/src/node-permissions-http.test.ts +345 -0
  169. package/src/node-permissions.ts +393 -0
  170. package/src/node-request-retention.test.ts +281 -0
  171. package/src/node-request-retention.ts +120 -0
  172. package/src/node-secret-rest-http.test.ts +190 -0
  173. package/src/node-serviceability.test.ts +86 -0
  174. package/src/node-serviceability.ts +124 -0
  175. package/src/node-session-control-http.test.ts +310 -0
  176. package/src/node-session-control.ts +258 -0
  177. package/src/node-skills-transport.test.ts +209 -0
  178. package/src/node-token-identity.ts +35 -0
  179. package/src/node-token-ownership.ts +51 -0
  180. package/src/node-token-privilege-http.test.ts +158 -0
  181. package/src/not-found-api-http.test.ts +67 -0
  182. package/src/observer-avatar-http.test.ts +442 -0
  183. package/src/observer-push.test.ts +252 -0
  184. package/src/opencode-catalog-report-http.test.ts +139 -0
  185. package/src/opencode-v2-catalog.test.ts +268 -0
  186. package/src/opencode-v2-catalog.ts +352 -0
  187. package/src/package-version-consistency.test.ts +25 -0
  188. package/src/parent-source-marker.test.ts +50 -0
  189. package/src/password-network-tokens.ts +25 -0
  190. package/src/peer-reply-atomic.test.ts +455 -0
  191. package/src/peer-reply-capability.test.ts +70 -0
  192. package/src/pg-worker.ts +87 -0
  193. package/src/probe-validate.test.ts +221 -0
  194. package/src/probe-validate.ts +104 -0
  195. package/src/probe.test.ts +80 -0
  196. package/src/probe.ts +200 -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 +466 -13
  201. package/src/redact-tokens.test.ts +65 -0
  202. package/src/redact-tokens.ts +40 -0
  203. package/src/rename.ts +38 -10
  204. package/src/reply-target-derivation.test.ts +96 -0
  205. package/src/report-status-handover-capabilities-http.test.ts +124 -0
  206. package/src/report-status-host-schema.test.ts +235 -0
  207. package/src/report-status-resume-id-handover.test.ts +184 -0
  208. package/src/report-status-secret-keys.test.ts +140 -0
  209. package/src/require-explicit-test-db.ts +9 -0
  210. package/src/requirement-due-reminders-http.test.ts +620 -0
  211. package/src/requirement-due-reminders.ts +416 -0
  212. package/src/requirement-events-http.test.ts +268 -0
  213. package/src/requirement-events.test.ts +45 -0
  214. package/src/requirement-events.ts +144 -0
  215. package/src/requirement-notify.ts +165 -0
  216. package/src/requirement-participant-notify-http.test.ts +309 -0
  217. package/src/requirement-tag-ops-http.test.ts +425 -0
  218. package/src/requirement-tag-tree-http.test.ts +275 -0
  219. package/src/requirement-tag-tree.ts +127 -0
  220. package/src/requirement-tags.ts +102 -0
  221. package/src/requirements-abandoned-http.test.ts +236 -0
  222. package/src/requirements-comment-http.test.ts +167 -0
  223. package/src/requirements-completed-at-migration.test.ts +70 -0
  224. package/src/requirements-errors-mcp-http.test.ts +164 -0
  225. package/src/requirements-errors.ts +158 -0
  226. package/src/requirements-etag-http.test.ts +91 -0
  227. package/src/requirements-http.test.ts +709 -0
  228. package/src/requirements-last-event-http.test.ts +349 -0
  229. package/src/requirements-list-mcp-slim-http.test.ts +155 -0
  230. package/src/requirements-list-slim-http.test.ts +324 -0
  231. package/src/requirements-mcp.test.ts +163 -0
  232. package/src/requirements-migrate.ts +283 -0
  233. package/src/requirements-owner-strict-mcp-http.test.ts +145 -0
  234. package/src/requirements-people-http.test.ts +114 -0
  235. package/src/requirements-people-mcp-http.test.ts +231 -0
  236. package/src/requirements-people.ts +196 -0
  237. package/src/requirements-priority-lowest.test.ts +114 -0
  238. package/src/requirements-projects-parent-http.test.ts +123 -0
  239. package/src/requirements-search-http.test.ts +182 -0
  240. package/src/requirements-search.test.ts +32 -0
  241. package/src/requirements-search.ts +145 -0
  242. package/src/requirements-seq-http.test.ts +193 -0
  243. package/src/requirements-seq-migration.test.ts +63 -0
  244. package/src/requirements-start-date.test.ts +125 -0
  245. package/src/requirements-stats-http.test.ts +357 -0
  246. package/src/requirements-stats.ts +195 -0
  247. package/src/requirements-status-participants-http.test.ts +222 -0
  248. package/src/requirements-upgrade-e2e.test.ts +126 -0
  249. package/src/requirements-upgrade-migration.test.ts +98 -0
  250. package/src/requirements.ts +2027 -0
  251. package/src/resolve-port.test.ts +57 -0
  252. package/src/resolve-port.ts +44 -0
  253. package/src/response-charset.test.ts +130 -0
  254. package/src/rest-alias-network-fallback-http.test.ts +123 -0
  255. package/src/rest-alias-network-fallback.test.ts +60 -0
  256. package/src/rest-alias-network-fallback.ts +65 -0
  257. package/src/rest-explicit-columns-http.test.ts +266 -0
  258. package/src/rest-identity.test.ts +130 -0
  259. package/src/rest-identity.ts +141 -0
  260. package/src/rest-projections.ts +72 -0
  261. package/src/rest-read-network-real-chain.test.ts +97 -0
  262. package/src/rest-write-network-resolution.test.ts +133 -0
  263. package/src/restart-readiness-http.test.ts +121 -0
  264. package/src/restricted-files.ts +76 -0
  265. package/src/retention-first-sweep-quiet.test.ts +31 -0
  266. package/src/retention.test.ts +100 -40
  267. package/src/retention.ts +423 -104
  268. package/src/route-callers-http.test.ts +120 -0
  269. package/src/route-timing.test.ts +211 -0
  270. package/src/route-timing.ts +262 -0
  271. package/src/rules-file-duplicate-alias.test.ts +234 -0
  272. package/src/rules-file-session-target.test.ts +207 -0
  273. package/src/rules-file-transport.test.ts +237 -0
  274. package/src/runtime-label.test.ts +22 -0
  275. package/src/runtime-label.ts +21 -0
  276. package/src/runtime-readiness.ts +90 -0
  277. package/src/schedule-agent-mcp-http.test.ts +391 -0
  278. package/src/schedule-agent.ts +192 -0
  279. package/src/schedule-starved.test.ts +92 -0
  280. package/src/schedule-starved.ts +114 -0
  281. package/src/scheduled-backoff-http.test.ts +193 -0
  282. package/src/scheduled-backoff.ts +64 -0
  283. package/src/scheduled-doorbell-nodeless-session.test.ts +134 -0
  284. package/src/scheduled-failure-backoff-2622.test.ts +145 -0
  285. package/src/scheduled-failure-code.test.ts +73 -0
  286. package/src/scheduled-failure-code.ts +105 -0
  287. package/src/scheduled-failures-http.test.ts +279 -0
  288. package/src/scheduled-failures.ts +377 -0
  289. package/src/scheduled-noprogress-backoff-2622.test.ts +133 -0
  290. package/src/scheduled-offline-backoff-probe.test.ts +56 -0
  291. package/src/scheduled-offline.test.ts +131 -0
  292. package/src/scheduled-offline.ts +66 -0
  293. package/src/scheduled-outcome-guidance-http.test.ts +139 -0
  294. package/src/scheduled-outcome-guidance.ts +9 -0
  295. package/src/scheduled-reply-unread-http.test.ts +212 -0
  296. package/src/scheduled-requirement-wake-http.test.ts +279 -0
  297. package/src/scheduled-requirement-wake.ts +125 -0
  298. package/src/scheduled-run-terminal.test.ts +268 -0
  299. package/src/scheduled-skip-blocking-task.test.ts +120 -0
  300. package/src/scheduled-skip-path-backoff-2622.test.ts +98 -0
  301. package/src/scheduled-stuck-http.test.ts +312 -0
  302. package/src/scheduled-stuck-notice-cap.test.ts +80 -0
  303. package/src/scheduled-stuck.ts +219 -0
  304. package/src/scheduled-tasks-http.test.ts +679 -0
  305. package/src/scheduled-tasks.ts +959 -0
  306. package/src/scheduled-work-outcome-http.test.ts +154 -0
  307. package/src/scheduled-work-outcome.ts +50 -0
  308. package/src/scoped-secrets.ts +139 -0
  309. package/src/send-dedup-request-id.test.ts +229 -0
  310. package/src/send-reply-agent-warning.test.ts +202 -0
  311. package/src/send-reply-alias-optional.test.ts +131 -0
  312. package/src/send-reply-attachments.test.ts +458 -0
  313. package/src/send_dedup.test.ts +54 -0
  314. package/src/send_dedup.ts +52 -6
  315. package/src/serve-error.test.ts +38 -0
  316. package/src/serve-error.ts +27 -0
  317. package/src/server.ts +5997 -0
  318. package/src/session-task-on-dispatch.ts +14 -0
  319. package/src/session-token-ownership-http.test.ts +122 -0
  320. package/src/shared/codex-inventory.ts +41 -0
  321. package/src/shared/daemon-provider-login.ts +31 -0
  322. package/src/shared/daemon-provider-snapshot.ts +52 -0
  323. package/src/shared/external-schedule-contract.ts +60 -0
  324. package/src/shared/node-name.test.ts +62 -0
  325. package/src/shared/node-name.ts +161 -0
  326. package/src/shared/probe-host-allowlist-drift.test.ts +54 -0
  327. package/src/shared/probe-host-allowlist.ts +128 -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 +53 -0
  332. package/src/shared/reserved-env.test.ts +35 -0
  333. package/src/shared/reserved-env.ts +31 -0
  334. package/src/shared/scoped-secret-contract.ts +5 -0
  335. package/src/shared/task-content-limit-drift.test.ts +28 -0
  336. package/src/shared/task-content-limit.ts +25 -0
  337. package/src/side-thread-command-transport.test.ts +312 -0
  338. package/src/side-thread-command-transport.ts +318 -0
  339. package/src/side-thread-http-integration.test.ts +233 -0
  340. package/src/side-thread-http.ts +504 -0
  341. package/src/side-thread-production.test.ts +72 -0
  342. package/src/side-thread-production.ts +118 -0
  343. package/src/side-thread.test.ts +1067 -0
  344. package/src/side-thread.ts +2499 -0
  345. package/src/skillhub-http.test.ts +108 -0
  346. package/src/sqlite-close-checkpoint.test.ts +78 -0
  347. package/src/start-node.test.ts +264 -0
  348. package/src/status-alias-filter-http.test.ts +106 -0
  349. package/src/status-alias-resolver-http.test.ts +163 -0
  350. package/src/status-alias-resolver.ts +19 -0
  351. package/src/status-node-id-filter-http.test.ts +161 -0
  352. package/src/status-read-cache-http.test.ts +229 -0
  353. package/src/status-read-cache.ts +122 -0
  354. package/src/stop-delete-node.test.ts +1286 -0
  355. package/src/task-access-http.test.ts +402 -0
  356. package/src/task-access.ts +420 -0
  357. package/src/task-activity.ts +60 -0
  358. package/src/task-auth-origin-http.test.ts +93 -0
  359. package/src/task-auth-origin.test.ts +24 -0
  360. package/src/task-auth-origin.ts +7 -0
  361. package/src/task-consumption.test.ts +482 -0
  362. package/src/task-diagnostic-http.test.ts +149 -0
  363. package/src/task-diagnostic.test.ts +115 -0
  364. package/src/task-diagnostic.ts +118 -0
  365. package/src/task-expiry-notice-http.test.ts +287 -0
  366. package/src/task-expiry-notice.ts +315 -0
  367. package/src/task-idempotency-mcp.test.ts +142 -0
  368. package/src/task-idempotency.test.ts +76 -0
  369. package/src/task-idempotency.ts +81 -0
  370. package/src/task-late-replies.ts +54 -0
  371. package/src/task-late-reply-http.test.ts +152 -0
  372. package/src/task-lifecycle-watcher-busy.test.ts +114 -0
  373. package/src/task-lifecycle-watcher.test.ts +204 -0
  374. package/src/task-lifecycle-watcher.ts +109 -0
  375. package/src/task-network-resolution-http.test.ts +140 -0
  376. package/src/task-offline-delivery-2668.test.ts +119 -0
  377. package/src/task-offline-delivery.ts +81 -0
  378. package/src/task-orphan-http.test.ts +287 -0
  379. package/src/task-orphan.ts +119 -0
  380. package/src/task-queue-ahead-http.test.ts +309 -0
  381. package/src/task-queue-ahead-scale.test.ts +236 -0
  382. package/src/task-queue-ahead.ts +186 -0
  383. package/src/task-rejection-log-http.test.ts +160 -0
  384. package/src/task-rejection-log.ts +49 -0
  385. package/src/task-sender-http.test.ts +143 -0
  386. package/src/task-stale-open-http.test.ts +290 -0
  387. package/src/task-stale-open.ts +103 -0
  388. package/src/tasks-pagination-http.test.ts +141 -0
  389. package/src/team-rules-status-http.test.ts +90 -0
  390. package/src/team-rules-status.test.ts +59 -0
  391. package/src/team-rules-status.ts +72 -0
  392. package/src/tool-audience-http.test.ts +230 -0
  393. package/src/tool-audience.ts +120 -0
  394. package/src/tools-list-json-schema.test.ts +94 -0
  395. package/src/tools.ts +5815 -348
  396. package/src/update-provider.test.ts +234 -0
  397. package/src/upload-early-reject-guard.test.ts +155 -0
  398. package/src/uploads-http.test.ts +97 -15
  399. package/src/uploads.test.ts +66 -0
  400. package/src/uploads.ts +138 -5
  401. package/src/user-avatar-http.test.ts +74 -0
  402. package/src/user-avatar-image.ts +160 -0
  403. package/src/user-avatar-migration.test.ts +25 -0
  404. package/src/user-avatar-upload-http.test.ts +348 -0
  405. package/src/user-inbox-by-agent-http.test.ts +161 -0
  406. package/src/user-inbox-netid-notnull.test.ts +122 -0
  407. package/src/user-inbox-read-http.test.ts +223 -0
  408. package/src/user-inbox-schema.test.ts +54 -0
  409. package/src/vault.test.ts +200 -0
  410. package/src/vault.ts +156 -0
  411. package/src/version-stats.test.ts +66 -0
  412. package/src/version-stats.ts +109 -0
@@ -0,0 +1,1286 @@
1
+ import { afterAll, beforeEach, describe, expect, test } from "bun:test";
2
+ import { db } from "./db.js";
3
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
4
+ import { registerTools } from "./tools.js";
5
+ import { patrolExpiredTasks } from "./server.js";
6
+
7
+ // RFC-027 PR1 — handler-driven tests for stop_node, delete_node,
8
+ // get_stop_request, ack_stop_request. Drives the MCP handlers via
9
+ // registerTools() so the wired auth context is real (not the
10
+ // mirror-SQL pattern that PR2 v1 used and which let SEC-1 leak slip
11
+ // through — per team rule: independent fork-review catches wired-wrong even when unit tests pass).
12
+ //
13
+ // Covers RFC-027 P1 e2e plan §5.2 scenarios A/B/C/D/E/F at the
14
+ // handler layer:
15
+ // A — stop happy path
16
+ // B — stop + in-flight (default refuse)
17
+ // C — stop + in-flight + force=true → audit row written
18
+ // D — delete happy path
19
+ // E — cross-tenant SEC-1 refusal
20
+ // F — delete daemon via delete_node refused (D6 gate)
21
+ // Plus state machine + confirm_alias + ack finalize transitions.
22
+
23
+ const NET_A = "net_sd_alpha";
24
+ const NET_B = "net_sd_beta";
25
+ const USER_A_ID = "u_sd_alice";
26
+ const USER_B_ID = "u_sd_bob";
27
+ const DAEMON_A_ID = "node_sd_daemon_a";
28
+ const DAEMON_A_ALIAS = "sd-daemon-a";
29
+ const DAEMON_A_TOK = "tok_sd_daemon_a";
30
+ const CHILD_A_ID = "node_sd_child_a";
31
+ const CHILD_A_ALIAS = "sd-child-a";
32
+ const CHILD_TOK_A_ID = "tok_sd_child_a";
33
+
34
+ interface ToolHandler { (args: any, extra?: any): Promise<{ content: Array<{ type: "text"; text: string }> }>; }
35
+ interface Reply { ok?: boolean; error?: string; [k: string]: unknown; }
36
+
37
+ function cleanup() {
38
+ for (const n of [NET_A, NET_B]) {
39
+ try { db.run("DELETE FROM node_stop_requests WHERE network_id = ?1", [n]); } catch {}
40
+ try { db.run("DELETE FROM node_create_requests WHERE network_id = ?1", [n]); } catch {}
41
+ try { db.run("DELETE FROM audit_log WHERE network_id = ?1", [n]); } catch {}
42
+ try { db.run("DELETE FROM inbox WHERE network_id = ?1", [n]); } catch {}
43
+ // PR1.2a restart_node tests leave node_config_updates rows; clear
44
+ // so the next test's restart_node doesn't see them as in_flight.
45
+ try { db.run("DELETE FROM node_config_updates WHERE network_id = ?1", [n]); } catch {}
46
+ // #2022 seeds tasks rows whose status drives the in-flight join; clear
47
+ // them by network or a later test inherits a stale terminal row.
48
+ try { db.run("DELETE FROM tasks WHERE network_id = ?1", [n]); } catch {}
49
+ try { db.run("DELETE FROM nodes WHERE network_id = ?1", [n]); } catch {}
50
+ try { db.run("DELETE FROM sessions WHERE network_id = ?1", [n]); } catch {}
51
+ try { db.run("DELETE FROM api_tokens WHERE network_id = ?1", [n]); } catch {}
52
+ try { db.run("DELETE FROM network_members WHERE network_id = ?1", [n]); } catch {}
53
+ try { db.run("DELETE FROM networks WHERE network_id = ?1", [n]); } catch {}
54
+ }
55
+ // SF-5 test plants a NULL-network inbox row keyed by alias — clean
56
+ // by alias too so it doesn't pollute later tests that use the same
57
+ // CHILD_A_ALIAS.
58
+ for (const alias of [CHILD_A_ALIAS, DAEMON_A_ALIAS]) {
59
+ try { db.run("DELETE FROM inbox WHERE session_name = ?1", [alias]); } catch {}
60
+ }
61
+ try { db.run("DELETE FROM users WHERE user_id IN (?1, ?2)", [USER_A_ID, USER_B_ID]); } catch {}
62
+ }
63
+
64
+ beforeEach(cleanup);
65
+ afterAll(cleanup);
66
+
67
+ function seedUser(user_id: string) {
68
+ db.run(
69
+ `INSERT INTO users (user_id, username, password_hash, role, created_at)
70
+ VALUES (?1, ?2, 'x', 'user', datetime('now'))`,
71
+ [user_id, user_id],
72
+ );
73
+ }
74
+ function seedNetwork(net_id: string, owner_id: string) {
75
+ db.run(
76
+ `INSERT OR REPLACE INTO networks (network_id, network_name, owner_id, created_at)
77
+ VALUES (?1, ?2, ?3, datetime('now'))`,
78
+ [net_id, net_id, owner_id],
79
+ );
80
+ }
81
+ function seedMembership(user_id: string, net_id: string, role: "owner" | "admin" | "member" | "viewer" = "admin") {
82
+ db.run(
83
+ `INSERT INTO network_members (user_id, network_id, role, joined_at)
84
+ VALUES (?1, ?2, ?3, datetime('now'))`,
85
+ [user_id, net_id, role],
86
+ );
87
+ }
88
+ function seedDaemon(net: string, node_id: string, alias: string, user_id: string, tokenId: string, role = "host_supervisor") {
89
+ db.run(
90
+ `INSERT INTO nodes (node_id, node_name, alias, network_id, config_snapshot, hostname, created_at, updated_at, lifecycle_state)
91
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, datetime('now'), datetime('now'), 'active')`,
92
+ [node_id, alias, alias, net, JSON.stringify({ role, daemon_capabilities: { runtimes_supported: ["claude-agent-sdk"] } }), `host-${alias}`],
93
+ );
94
+ db.run(
95
+ `INSERT INTO api_tokens (token_id, user_id, network_id, scope, name, token_hash, expires_at, revoked_at)
96
+ VALUES (?1, ?2, ?3, 'network', ?4, ?5, NULL, NULL)`,
97
+ [tokenId, user_id, net, `node:${alias}`, `hash_${tokenId}`],
98
+ );
99
+ }
100
+ function seedChild(net: string, node_id: string, alias: string, user_id: string, tokenId: string, opts: { lifecycle_state?: string; role?: string } = {}) {
101
+ db.run(
102
+ `INSERT INTO nodes (node_id, node_name, alias, network_id, config_snapshot, hostname, created_at, updated_at, lifecycle_state)
103
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, datetime('now'), datetime('now'), ?7)`,
104
+ [node_id, alias, alias, net, JSON.stringify({ role: opts.role ?? "member" }), `host-${alias}`, opts.lifecycle_state ?? "active"],
105
+ );
106
+ db.run(
107
+ `INSERT INTO api_tokens (token_id, user_id, network_id, scope, name, token_hash, expires_at, revoked_at)
108
+ VALUES (?1, ?2, ?3, 'network', ?4, ?5, NULL, NULL)`,
109
+ [tokenId, user_id, net, `node:${alias}`, `hash_${tokenId}`],
110
+ );
111
+ }
112
+ function seedInbox(net: string, alias: string, n: number) {
113
+ for (let i = 0; i < n; i++) {
114
+ db.run(
115
+ `INSERT INTO inbox (id, session_name, type, priority, content, from_session, network_id, acked)
116
+ VALUES (?1, ?2, 'task', 'normal', ?3, 'caller', ?4, 0)`,
117
+ [`inbox_${alias}_${i}_${Date.now()}`, alias, `task ${i}`, net],
118
+ );
119
+ }
120
+ }
121
+
122
+ function buildHandlers(
123
+ enforceUserId: string | null,
124
+ daemonTokenBound = false,
125
+ callerTokenId: string | null = null,
126
+ daemonNetId: string | null = null,
127
+ ): Record<string, ToolHandler> {
128
+ const server = new McpServer({ name: "test", version: "0" }) as any;
129
+ const tools: Record<string, ToolHandler> = {};
130
+ const origTool = server.tool.bind(server);
131
+ server.tool = (name: string, _desc: string, _schema: any, handler: ToolHandler) => {
132
+ tools[name] = handler;
133
+ return origTool(name, _desc, _schema, handler);
134
+ };
135
+ const origRegisterTool = server.registerTool?.bind(server);
136
+ if (origRegisterTool) {
137
+ server.registerTool = (name: string, _cfg: any, handler: ToolHandler) => {
138
+ tools[name] = handler;
139
+ return origRegisterTool(name, _cfg, handler);
140
+ };
141
+ }
142
+ registerTools(
143
+ server, undefined,
144
+ /* enforceNetworkId */ daemonTokenBound ? daemonNetId : null,
145
+ /* enforceUserId */ enforceUserId,
146
+ /* callerAlias */ null,
147
+ /* callerTokenIsNetwork */ daemonTokenBound,
148
+ /* callerTokenId */ callerTokenId,
149
+ );
150
+ return tools;
151
+ }
152
+
153
+ async function call(handler: ToolHandler, args: any): Promise<Reply> {
154
+ const r = await handler(args);
155
+ return JSON.parse(r.content[0].text) as Reply;
156
+ }
157
+
158
+ function readNode(node_id: string) {
159
+ return db.get<{ lifecycle_state: string | null; alias: string }>(
160
+ `SELECT lifecycle_state, alias FROM nodes WHERE node_id = ?1`, node_id,
161
+ );
162
+ }
163
+ function readToken(tokenId: string) {
164
+ return db.get<{ revoked_at: string | null }>(
165
+ `SELECT revoked_at FROM api_tokens WHERE token_id = ?1`, tokenId,
166
+ );
167
+ }
168
+ function readRequest(request_id: string) {
169
+ return db.get<{ status: string; action: string; backup_path: string | null; exit_signal: string | null }>(
170
+ `SELECT status, action, backup_path, exit_signal FROM node_stop_requests WHERE request_id = ?1`,
171
+ request_id,
172
+ );
173
+ }
174
+ function readAudit(action: string, network_id: string) {
175
+ return db.all<{ action: string; target_id: string; detail: string }>(
176
+ `SELECT action, target_id, detail FROM audit_log WHERE action = ?1 AND network_id = ?2 ORDER BY id DESC`,
177
+ [action, network_id],
178
+ );
179
+ }
180
+
181
+ function setupAlphaNetwork() {
182
+ seedUser(USER_A_ID);
183
+ seedNetwork(NET_A, USER_A_ID);
184
+ seedMembership(USER_A_ID, NET_A, "admin");
185
+ seedDaemon(NET_A, DAEMON_A_ID, DAEMON_A_ALIAS, USER_A_ID, DAEMON_A_TOK);
186
+ seedChild(NET_A, CHILD_A_ID, CHILD_A_ALIAS, USER_A_ID, CHILD_TOK_A_ID);
187
+ // Board #625: happy paths must carry actual creation authority, not merely a node_ id.
188
+ db.run(
189
+ `INSERT INTO node_create_requests(request_id,daemon_node_id,child_name,network_id,runtime,model,flags_json,env_keys,status,created_at,created_by_token,child_node_id)
190
+ VALUES(?1,?2,?3,?4,'claude-agent-sdk','x','{}','[]','succeeded',1,'t',?5)`,
191
+ [`cr_${CHILD_A_ID.slice(5)}`, DAEMON_A_ID, CHILD_A_ALIAS, NET_A, CHILD_A_ID],
192
+ );
193
+ }
194
+
195
+ // ── stop_node ──────────────────────────────────────────────────────
196
+
197
+ describe("stop_node — happy path (RFC-027 §5.2 A)", () => {
198
+ test("active child + no in-flight → dispatch + state→stopping", async () => {
199
+ setupAlphaNetwork();
200
+ const tools = buildHandlers(USER_A_ID);
201
+ const r = await call(tools.stop_node, {
202
+ child_node_id: CHILD_A_ID,
203
+ daemon_node_id: DAEMON_A_ID,
204
+ network_id: NET_A,
205
+ });
206
+ expect(r.ok).toBe(true);
207
+ expect(r.action).toBe("stop");
208
+ expect(r.lifecycle_state).toBe("stopping");
209
+ expect(r.in_flight_at_dispatch).toBe(0);
210
+ expect(typeof r.request_id).toBe("string");
211
+ expect((r.request_id as string).startsWith("sr_")).toBe(true);
212
+
213
+ expect(readNode(CHILD_A_ID)?.lifecycle_state).toBe("stopping");
214
+ expect(readAudit("stop_node_dispatched", NET_A).length).toBe(1);
215
+ });
216
+ });
217
+
218
+ describe("stop_node — in-flight default-refuse (RFC-027 §5.2 B)", () => {
219
+ test("inbox has 2 unacked tasks → error=node_busy_in_flight, count surfaced", async () => {
220
+ setupAlphaNetwork();
221
+ seedInbox(NET_A, CHILD_A_ALIAS, 2);
222
+ const tools = buildHandlers(USER_A_ID);
223
+ const r = await call(tools.stop_node, {
224
+ child_node_id: CHILD_A_ID, daemon_node_id: DAEMON_A_ID, network_id: NET_A,
225
+ });
226
+ expect(r.ok).toBe(false);
227
+ expect(r.error).toBe("node_busy_in_flight");
228
+ expect(r.in_flight_count).toBe(2);
229
+ // state untouched
230
+ expect(readNode(CHILD_A_ID)?.lifecycle_state).toBe("active");
231
+ expect(readAudit("stop_node_dispatched", NET_A).length).toBe(0);
232
+ });
233
+ });
234
+
235
+ describe("stop_node — force=true with in-flight (RFC-027 §5.2 C)", () => {
236
+ test("force overrides + forced_stop_with_in_flight audit row written", async () => {
237
+ setupAlphaNetwork();
238
+ seedInbox(NET_A, CHILD_A_ALIAS, 3);
239
+ const tools = buildHandlers(USER_A_ID);
240
+ const r = await call(tools.stop_node, {
241
+ child_node_id: CHILD_A_ID, daemon_node_id: DAEMON_A_ID, network_id: NET_A,
242
+ force: true,
243
+ });
244
+ expect(r.ok).toBe(true);
245
+ expect(r.in_flight_at_dispatch).toBe(3);
246
+ const audits = readAudit("forced_stop_with_in_flight", NET_A);
247
+ expect(audits.length).toBe(1);
248
+ expect(JSON.parse(audits[0].detail).in_flight_count).toBe(3);
249
+ });
250
+ });
251
+
252
+ describe("stop_node — state machine guards", () => {
253
+ test("stop on already-stopped node → node_not_active", async () => {
254
+ setupAlphaNetwork();
255
+ db.run(`UPDATE nodes SET lifecycle_state = 'stopped' WHERE node_id = ?1`, [CHILD_A_ID]);
256
+ const tools = buildHandlers(USER_A_ID);
257
+ const r = await call(tools.stop_node, {
258
+ child_node_id: CHILD_A_ID, daemon_node_id: DAEMON_A_ID, network_id: NET_A,
259
+ });
260
+ expect(r.ok).toBe(false);
261
+ expect(r.error).toBe("node_not_active");
262
+ expect(r.current_state).toBe("stopped");
263
+ });
264
+
265
+ test("stop on already-stopping node → node_already_stopping", async () => {
266
+ setupAlphaNetwork();
267
+ db.run(`UPDATE nodes SET lifecycle_state = 'stopping' WHERE node_id = ?1`, [CHILD_A_ID]);
268
+ const tools = buildHandlers(USER_A_ID);
269
+ const r = await call(tools.stop_node, {
270
+ child_node_id: CHILD_A_ID, daemon_node_id: DAEMON_A_ID, network_id: NET_A,
271
+ });
272
+ expect(r.ok).toBe(false);
273
+ expect(r.error).toBe("node_already_stopping");
274
+ });
275
+ });
276
+
277
+ // ── delete_node ────────────────────────────────────────────────────
278
+
279
+ describe("delete_node — happy path (RFC-027 §5.2 D)", () => {
280
+ test("active child + correct confirm_alias → dispatch + state→deleting", async () => {
281
+ setupAlphaNetwork();
282
+ const tools = buildHandlers(USER_A_ID);
283
+ const r = await call(tools.delete_node, {
284
+ child_node_id: CHILD_A_ID, daemon_node_id: DAEMON_A_ID, network_id: NET_A,
285
+ confirm_alias: CHILD_A_ALIAS,
286
+ });
287
+ expect(r.ok).toBe(true);
288
+ expect(r.action).toBe("delete");
289
+ expect(r.lifecycle_state).toBe("deleting");
290
+ expect(readNode(CHILD_A_ID)?.lifecycle_state).toBe("deleting");
291
+ expect(readAudit("delete_node_dispatched", NET_A).length).toBe(1);
292
+ });
293
+ });
294
+
295
+ describe("delete_node — confirm_alias gate", () => {
296
+ test("wrong alias input → confirm_alias_mismatch", async () => {
297
+ setupAlphaNetwork();
298
+ const tools = buildHandlers(USER_A_ID);
299
+ const r = await call(tools.delete_node, {
300
+ child_node_id: CHILD_A_ID, daemon_node_id: DAEMON_A_ID, network_id: NET_A,
301
+ confirm_alias: "wrong-alias",
302
+ });
303
+ expect(r.ok).toBe(false);
304
+ expect(r.error).toBe("confirm_alias_mismatch");
305
+ expect(readNode(CHILD_A_ID)?.lifecycle_state).toBe("active");
306
+ });
307
+ });
308
+
309
+ describe("delete_node — D6 daemon-role-gate (RFC-027 §5.2 F)", () => {
310
+ test("delete targeting host_supervisor daemon → cannot_delete_daemon_via_delete_node", async () => {
311
+ setupAlphaNetwork();
312
+ const tools = buildHandlers(USER_A_ID);
313
+ const r = await call(tools.delete_node, {
314
+ child_node_id: DAEMON_A_ID, // targeting the daemon itself
315
+ daemon_node_id: DAEMON_A_ID,
316
+ network_id: NET_A,
317
+ confirm_alias: DAEMON_A_ALIAS,
318
+ });
319
+ expect(r.ok).toBe(false);
320
+ expect(r.error).toBe("cannot_delete_daemon_via_delete_node");
321
+ // Daemon row untouched.
322
+ expect(readNode(DAEMON_A_ID)?.lifecycle_state).toBe("active");
323
+ });
324
+ });
325
+
326
+ // ── SEC-1 cross-tenant ─────────────────────────────────────────────
327
+
328
+ describe("stop_node / delete_node — SEC-1 cross-tenant (RFC-027 §5.2 E)", () => {
329
+ test("user-B targeting user-A's child → forbidden_cross_tenant; netA node untouched", async () => {
330
+ setupAlphaNetwork();
331
+ // also seed user B in own network
332
+ seedUser(USER_B_ID);
333
+ seedNetwork(NET_B, USER_B_ID);
334
+ seedMembership(USER_B_ID, NET_B, "admin");
335
+
336
+ const tools = buildHandlers(USER_B_ID);
337
+ const r = await call(tools.stop_node, {
338
+ child_node_id: CHILD_A_ID, daemon_node_id: DAEMON_A_ID,
339
+ network_id: NET_A, // user-B claiming netA scope
340
+ });
341
+ expect(r.ok).toBe(false);
342
+ expect(r.error).toMatch(/forbidden_cross_tenant|access denied/i);
343
+ // netA child unaffected
344
+ expect(readNode(CHILD_A_ID)?.lifecycle_state).toBe("active");
345
+ expect(readAudit("stop_node_dispatched", NET_A).length).toBe(0);
346
+ });
347
+
348
+ test("user-B with no network_id arg still can't see/touch netA child", async () => {
349
+ setupAlphaNetwork();
350
+ seedUser(USER_B_ID);
351
+ seedNetwork(NET_B, USER_B_ID);
352
+ seedMembership(USER_B_ID, NET_B, "admin");
353
+
354
+ const tools = buildHandlers(USER_B_ID);
355
+ const r = await call(tools.delete_node, {
356
+ child_node_id: CHILD_A_ID, daemon_node_id: DAEMON_A_ID,
357
+ confirm_alias: CHILD_A_ALIAS,
358
+ });
359
+ expect(r.ok).toBe(false);
360
+ expect(r.error).toMatch(/forbidden_cross_tenant/i);
361
+ expect(readNode(CHILD_A_ID)?.lifecycle_state).toBe("active");
362
+ });
363
+ });
364
+
365
+ // ── get_stop_request + ack_stop_request (daemon-side flow) ─────────
366
+
367
+ describe("get_stop_request + ack_stop_request — daemon flow", () => {
368
+ test("daemon pulls request → ack 'stopped' → state machine finalizes (stop branch)", async () => {
369
+ setupAlphaNetwork();
370
+ const userTools = buildHandlers(USER_A_ID);
371
+ const dispatch = await call(userTools.stop_node, {
372
+ child_node_id: CHILD_A_ID, daemon_node_id: DAEMON_A_ID, network_id: NET_A,
373
+ });
374
+ expect(dispatch.ok).toBe(true);
375
+ const requestId = dispatch.request_id as string;
376
+
377
+ // daemon perspective: token-bound to its own ntok
378
+ const daemonTools = buildHandlers(USER_A_ID, /*tokenBound*/ true, DAEMON_A_TOK, NET_A);
379
+ const got = await call(daemonTools.get_stop_request, { request_id: requestId });
380
+ expect(got.ok).toBe(true);
381
+ expect(got.action).toBe("stop");
382
+ expect(got.child_node_id).toBe(CHILD_A_ID);
383
+ expect(got.child_alias).toBe(CHILD_A_ALIAS);
384
+ expect(readRequest(requestId)?.status).toBe("delivered");
385
+
386
+ const acked = await call(daemonTools.ack_stop_request, {
387
+ request_id: requestId, status: "stopped", exit_signal: "SIGTERM",
388
+ });
389
+ expect(acked.ok).toBe(true);
390
+ expect(readRequest(requestId)?.status).toBe("stopped");
391
+ expect(readRequest(requestId)?.exit_signal).toBe("SIGTERM");
392
+ expect(readNode(CHILD_A_ID)?.lifecycle_state).toBe("stopped");
393
+ expect(readAudit("stop_node_completed", NET_A).length).toBe(1);
394
+ // ntok must NOT be revoked on stop (reversible).
395
+ expect(readToken(CHILD_TOK_A_ID)?.revoked_at).toBeNull();
396
+ });
397
+
398
+ test("daemon ack 'stopped' on delete branch → ntok revoked + node row DELETEd", async () => {
399
+ setupAlphaNetwork();
400
+ const userTools = buildHandlers(USER_A_ID);
401
+ const dispatch = await call(userTools.delete_node, {
402
+ child_node_id: CHILD_A_ID, daemon_node_id: DAEMON_A_ID, network_id: NET_A,
403
+ confirm_alias: CHILD_A_ALIAS,
404
+ });
405
+ expect(dispatch.ok).toBe(true);
406
+ const requestId = dispatch.request_id as string;
407
+
408
+ const daemonTools = buildHandlers(USER_A_ID, true, DAEMON_A_TOK, NET_A);
409
+ const acked = await call(daemonTools.ack_stop_request, {
410
+ request_id: requestId, status: "stopped", exit_signal: "SIGTERM",
411
+ backup_path: "/home/u/.anet/deleted/1719647200000-sd-child-a",
412
+ });
413
+ expect(acked.ok).toBe(true);
414
+ // Row gone, ntok revoked, audit row written
415
+ expect(readNode(CHILD_A_ID) ?? null).toBeNull();
416
+ expect(readToken(CHILD_TOK_A_ID)?.revoked_at).not.toBeNull();
417
+ const audits = readAudit("delete_node_completed", NET_A);
418
+ expect(audits.length).toBe(1);
419
+ expect(JSON.parse(audits[0].detail).backup_path).toBe("/home/u/.anet/deleted/1719647200000-sd-child-a");
420
+ });
421
+
422
+ // Daemon-mediated delete used to drop only the nodes row. The child's sessions
423
+ // row stayed behind as "offline", so /api/status — and every client list built
424
+ // on it — kept showing the deleted node forever (desktop: the node stays put
425
+ // under 「删除请求已提交」). REST DELETE /api/nodes/:id already drops both.
426
+ test("daemon ack 'stopped' on delete branch → the child's session row is gone too", async () => {
427
+ setupAlphaNetwork();
428
+ db.run(
429
+ "INSERT INTO sessions (resume_id, alias, node_id, network_id, status) VALUES (?1, ?2, ?3, ?4, 'idle')",
430
+ ["resume-sd-child-a", CHILD_A_ALIAS, CHILD_A_ID, NET_A],
431
+ );
432
+ const userTools = buildHandlers(USER_A_ID);
433
+ const dispatch = await call(userTools.delete_node, {
434
+ child_node_id: CHILD_A_ID, daemon_node_id: DAEMON_A_ID, network_id: NET_A, confirm_alias: CHILD_A_ALIAS,
435
+ });
436
+ expect(dispatch.ok).toBe(true);
437
+ const daemonTools = buildHandlers(USER_A_ID, true, DAEMON_A_TOK, NET_A);
438
+ await call(daemonTools.ack_stop_request, { request_id: dispatch.request_id as string, status: "stopped", exit_signal: "SIGTERM" });
439
+ const left = db.get<{ n: number }>("SELECT COUNT(*) AS n FROM sessions WHERE node_id = ?1", CHILD_A_ID);
440
+ expect(Number(left?.n ?? 0)).toBe(0);
441
+ });
442
+
443
+ test("delete finalize drops the session by node_id, sparing a same-alias rebuilt node", async () => {
444
+ setupAlphaNetwork();
445
+ const userTools = buildHandlers(USER_A_ID);
446
+ const dispatch = await call(userTools.delete_node, {
447
+ child_node_id: CHILD_A_ID, daemon_node_id: DAEMON_A_ID, network_id: NET_A, confirm_alias: CHILD_A_ALIAS,
448
+ });
449
+ expect(dispatch.ok).toBe(true);
450
+ // Before the ack lands, a new node takes the same alias and registers.
451
+ const REBUILT_ID = "node_sd_child_a_rebuilt";
452
+ db.run(
453
+ "INSERT INTO sessions (resume_id, alias, node_id, network_id, status) VALUES (?1, ?2, ?3, ?4, 'idle')",
454
+ ["resume-sd-child-a-rebuilt", CHILD_A_ALIAS, REBUILT_ID, NET_A],
455
+ );
456
+ const daemonTools = buildHandlers(USER_A_ID, true, DAEMON_A_TOK, NET_A);
457
+ await call(daemonTools.ack_stop_request, { request_id: dispatch.request_id as string, status: "stopped", exit_signal: "SIGTERM" });
458
+ const rebuilt = db.get<{ status: string }>("SELECT status FROM sessions WHERE node_id = ?1", REBUILT_ID);
459
+ expect(rebuilt?.status).toBe("idle");
460
+ });
461
+
462
+ // #1448 finding-4 — stop/delete 必须校验 daemon 是 child 的权威创建者(镜像 start)。
463
+ // 改前只校验 daemon 存在+同网 → 同网调用方传错 daemon_node_id,门铃路由到错 daemon。
464
+ // f3 合入后错 daemon 会 sweep 空 + ack stopped → hub 假收敛 stopped 而 child 仍在跑。
465
+ test("#1448 finding-4: stop/delete reject a wrong same-network daemon_node_id (daemon_child_mismatch)", async () => {
466
+ setupAlphaNetwork();
467
+ // setupAlphaNetwork carries the creation authority.
468
+ // 一个同网、存在、但没创建 CHILD_A 的 daemon
469
+ const DAEMON_B = "node_sd_daemon_b";
470
+ seedDaemon(NET_A, DAEMON_B, "sd-daemon-b", USER_A_ID, "tok_sd_daemon_b");
471
+ const u = buildHandlers(USER_A_ID);
472
+ // 错 daemon → mismatch(stop + delete 都拦)。改前会放行、路由到错 daemon。
473
+ expect((await call(u.stop_node, { child_node_id: CHILD_A_ID, daemon_node_id: DAEMON_B, network_id: NET_A })).error).toBe("daemon_child_mismatch");
474
+ expect((await call(u.delete_node, { child_node_id: CHILD_A_ID, daemon_node_id: DAEMON_B, confirm_alias: CHILD_A_ALIAS, network_id: NET_A })).error).toBe("daemon_child_mismatch");
475
+ // 正确 daemon → 放行(回归钉)
476
+ expect((await call(u.stop_node, { child_node_id: CHILD_A_ID, daemon_node_id: DAEMON_A_ID, network_id: NET_A })).ok).toBe(true);
477
+ });
478
+
479
+ // #571 — 手工起的节点(id `n_…`)没有任何 daemon 链接。改前:authority==null 时
480
+ // 放行调用方点名的任意同网 daemon → 门铃发过去,那台 daemon 本地无记录,按 alias
481
+ // 全机 pgrep+SIGTERM,误杀同 alias 的别的 agent-node。改后:不论传没传 daemon 一律拒。
482
+ test("#571: stop/delete of a hand-started node refuse even with an explicit same-network daemon", async () => {
483
+ setupAlphaNetwork();
484
+ const HAND_ID = "n_571abcde";
485
+ const HAND_ALIAS = "sd-hand-571";
486
+ seedChild(NET_A, HAND_ID, HAND_ALIAS, USER_A_ID, "tok_sd_hand_571");
487
+ const u = buildHandlers(USER_A_ID);
488
+ const s = await call(u.stop_node, { child_node_id: HAND_ID, daemon_node_id: DAEMON_A_ID, network_id: NET_A });
489
+ expect(s.ok).toBe(false);
490
+ expect(s.error).toBe("not_daemon_managed");
491
+ expect(String(s.message)).toContain("anet node stop");
492
+ const d = await call(u.delete_node, { child_node_id: HAND_ID, daemon_node_id: DAEMON_A_ID, confirm_alias: HAND_ALIAS, network_id: NET_A });
493
+ expect(d.error).toBe("not_daemon_managed");
494
+ // 没有任何副作用:状态没动、没写 stop 请求行
495
+ expect(readNode(HAND_ID)?.lifecycle_state).toBe("active");
496
+ const rows = db.get<{ n: number }>(`SELECT COUNT(*) AS n FROM node_stop_requests WHERE child_node_id = ?1`, HAND_ID);
497
+ expect(Number(rows?.n ?? 0)).toBe(0);
498
+ // 回归钉:setupAlphaNetwork 中有 create 记录的 child 照常可停。
499
+ expect((await call(u.stop_node, { child_node_id: CHILD_A_ID, network_id: NET_A })).ok).toBe(true);
500
+ });
501
+
502
+ // #1448 finding-5 — delete 完成时按派发时定住的 token_id 精确撤 ntok,而非按
503
+ // name='node:<alias>' 广撤。改前:同 alias 在 delete 未收敛窗口内被重建、拿到同名新
504
+ // token,ack 会把新 token 一并误撤(下面 REBUILT_TOK 断言 not revoked 会红)。
505
+ test("#1448 finding-5: delete revokes by token_id, spares a same-alias rebuilt token", async () => {
506
+ setupAlphaNetwork();
507
+ const userTools = buildHandlers(USER_A_ID);
508
+ const dispatch = await call(userTools.delete_node, {
509
+ child_node_id: CHILD_A_ID, daemon_node_id: DAEMON_A_ID, network_id: NET_A, confirm_alias: CHILD_A_ALIAS,
510
+ });
511
+ expect(dispatch.ok).toBe(true);
512
+ // 派发后、ack 前:同 alias 节点被重建,拿到**同名**新 ntok(不同 token_id,仍 active)。
513
+ const REBUILT_TOK = "tok_sd_child_a_rebuilt";
514
+ db.run(
515
+ `INSERT INTO api_tokens (token_id, user_id, network_id, scope, name, token_hash, expires_at, revoked_at)
516
+ VALUES (?1, ?2, ?3, 'network', ?4, ?5, NULL, NULL)`,
517
+ [REBUILT_TOK, USER_A_ID, NET_A, `node:${CHILD_A_ALIAS}`, `hash_${REBUILT_TOK}`],
518
+ );
519
+ const daemonTools = buildHandlers(USER_A_ID, true, DAEMON_A_TOK, NET_A);
520
+ await call(daemonTools.ack_stop_request, { request_id: dispatch.request_id as string, status: "stopped", exit_signal: "SIGTERM" });
521
+ expect(readToken(CHILD_TOK_A_ID)?.revoked_at).not.toBeNull(); // 原 token 撤销(精确命中)
522
+ expect(readToken(REBUILT_TOK)?.revoked_at).toBeNull(); // 重建的同名新 token 未被误撤(改前按 name 广撤会红)
523
+ });
524
+
525
+ test("daemon ack 'stop_failed' → lifecycle_state=stop_failed, request error captured", async () => {
526
+ setupAlphaNetwork();
527
+ const userTools = buildHandlers(USER_A_ID);
528
+ const dispatch = await call(userTools.stop_node, {
529
+ child_node_id: CHILD_A_ID, daemon_node_id: DAEMON_A_ID, network_id: NET_A,
530
+ });
531
+ const requestId = dispatch.request_id as string;
532
+ const daemonTools = buildHandlers(USER_A_ID, true, DAEMON_A_TOK, NET_A);
533
+ await call(daemonTools.ack_stop_request, {
534
+ request_id: requestId, status: "stop_failed", error: "SIGKILL also failed",
535
+ });
536
+ expect(readNode(CHILD_A_ID)?.lifecycle_state).toBe("stop_failed");
537
+ expect(readRequest(requestId)?.status).toBe("stop_failed");
538
+ });
539
+
540
+ test("daemon B can't ack daemon A's request → not_your_request", async () => {
541
+ setupAlphaNetwork();
542
+ const userTools = buildHandlers(USER_A_ID);
543
+ const dispatch = await call(userTools.stop_node, {
544
+ child_node_id: CHILD_A_ID, daemon_node_id: DAEMON_A_ID, network_id: NET_A,
545
+ });
546
+ const requestId = dispatch.request_id as string;
547
+ // Seed an unrelated daemon B in netA with its own token.
548
+ db.run(
549
+ `INSERT INTO nodes (node_id, node_name, alias, network_id, config_snapshot, hostname, created_at, updated_at, lifecycle_state)
550
+ VALUES ('node_other_daemon', 'other-daemon', 'other-daemon', ?1, '{}', 'h', datetime('now'), datetime('now'), 'active')`,
551
+ [NET_A],
552
+ );
553
+ db.run(
554
+ `INSERT INTO api_tokens (token_id, user_id, network_id, scope, name, token_hash, expires_at, revoked_at)
555
+ VALUES ('tok_other_daemon', ?1, ?2, 'network', 'node:other-daemon', 'hash_other', NULL, NULL)`,
556
+ [USER_A_ID, NET_A],
557
+ );
558
+ const otherDaemonTools = buildHandlers(USER_A_ID, true, "tok_other_daemon", NET_A);
559
+ const r = await call(otherDaemonTools.ack_stop_request, {
560
+ request_id: requestId, status: "stopped",
561
+ });
562
+ expect(r.ok).toBe(false);
563
+ expect(r.error).toBe("not_your_request");
564
+ });
565
+ });
566
+
567
+ // ── PR1 v3: 通信龙 #345 deep-review fixes ──────────────────────────
568
+
569
+ describe("SF-2 — audit in tx propagates failure (D8 atomicity真)", () => {
570
+ test("forced audit row written alongside dispatch in same tx (rollback if either fails)", async () => {
571
+ // We can't easily simulate audit_log INSERT failure without
572
+ // schema munging; the atomicity guarantee is structural (BEGIN..
573
+ // COMMIT + auditCreateNodeStrict re-throws). Pin the invariant
574
+ // observable to ops: the dispatch + forced audit both appear OR
575
+ // both are absent. Happy path here; a true failure-injection
576
+ // belongs in PR1.1's docker e2e where we can drop audit_log
577
+ // permissions / corrupt the row.
578
+ setupAlphaNetwork();
579
+ seedInbox(NET_A, CHILD_A_ALIAS, 1);
580
+ const tools = buildHandlers(USER_A_ID);
581
+ const r = await call(tools.stop_node, {
582
+ child_node_id: CHILD_A_ID, daemon_node_id: DAEMON_A_ID, network_id: NET_A,
583
+ force: true,
584
+ });
585
+ expect(r.ok).toBe(true);
586
+ // Both audit rows present.
587
+ expect(readAudit("stop_node_dispatched", NET_A).length).toBe(1);
588
+ expect(readAudit("forced_stop_with_in_flight", NET_A).length).toBe(1);
589
+ // node state moved
590
+ expect(readNode(CHILD_A_ID)?.lifecycle_state).toBe("stopping");
591
+ });
592
+ });
593
+
594
+ describe("SF-4 — D6 fail-CLOSED on ambiguous role", () => {
595
+ test("corrupt config_snapshot + node referenced as daemon → still refused", async () => {
596
+ setupAlphaNetwork();
597
+ // Wreck the daemon's snapshot but leave the row + create-request
598
+ // history. delete_node MUST still refuse — corrupt snapshot was the
599
+ // SF-4 fail-open path.
600
+ db.run(
601
+ `UPDATE nodes SET config_snapshot = ?1 WHERE node_id = ?2`,
602
+ ["not-valid-json{{{", DAEMON_A_ID],
603
+ );
604
+ // Plant a node_create_request that points to DAEMON_A as daemon,
605
+ // simulating that this daemon has handed out children before.
606
+ db.run(
607
+ `INSERT INTO node_create_requests
608
+ (request_id, daemon_node_id, child_name, network_id, runtime, model, flags_json, env_keys, status, child_token_id, created_at, created_by_token)
609
+ VALUES ('cr_sf4_evidence', ?1, 'past-child', ?2, 'claude-agent-sdk', 'x', '{}', '[]', 'succeeded', NULL, ?3, 'tok_test')`,
610
+ [DAEMON_A_ID, NET_A, Date.now()],
611
+ );
612
+ const tools = buildHandlers(USER_A_ID);
613
+ const r = await call(tools.delete_node, {
614
+ child_node_id: DAEMON_A_ID,
615
+ daemon_node_id: DAEMON_A_ID,
616
+ network_id: NET_A,
617
+ confirm_alias: DAEMON_A_ALIAS,
618
+ });
619
+ expect(r.ok).toBe(false);
620
+ expect(r.error).toBe("cannot_delete_daemon_via_delete_node");
621
+ expect(readNode(DAEMON_A_ID)?.lifecycle_state).toBe("active");
622
+ });
623
+
624
+ test("corrupt snapshot + NO daemon evidence → can be deleted (no FP)", async () => {
625
+ // A plain child whose snapshot got mangled mustn't be refused.
626
+ // Simulates corruption on a regular member node.
627
+ setupAlphaNetwork();
628
+ db.run(
629
+ `UPDATE nodes SET config_snapshot = ?1 WHERE node_id = ?2`,
630
+ ["{broken", CHILD_A_ID],
631
+ );
632
+ const tools = buildHandlers(USER_A_ID);
633
+ const r = await call(tools.delete_node, {
634
+ child_node_id: CHILD_A_ID, daemon_node_id: DAEMON_A_ID, network_id: NET_A,
635
+ confirm_alias: CHILD_A_ALIAS,
636
+ });
637
+ expect(r.ok).toBe(true);
638
+ expect(r.action).toBe("delete");
639
+ });
640
+ });
641
+
642
+ describe("SF-5 — in-flight COALESCE for legacy inbox rows", () => {
643
+ test("inbox row with network_id=NULL but session_name matches → counted", async () => {
644
+ setupAlphaNetwork();
645
+ // Legacy-shape inbox row: session_name set, network_id NULL.
646
+ db.run(
647
+ `INSERT INTO inbox (id, session_name, type, priority, content, from_session, network_id, acked)
648
+ VALUES (?1, ?2, 'task', 'normal', 'legacy-task', 'caller', NULL, 0)`,
649
+ [`inbox_legacy_${Date.now()}`, CHILD_A_ALIAS],
650
+ );
651
+ const tools = buildHandlers(USER_A_ID);
652
+ const r = await call(tools.stop_node, {
653
+ child_node_id: CHILD_A_ID, daemon_node_id: DAEMON_A_ID, network_id: NET_A,
654
+ });
655
+ expect(r.ok).toBe(false);
656
+ expect(r.error).toBe("node_busy_in_flight");
657
+ expect(r.in_flight_count).toBeGreaterThanOrEqual(1);
658
+ });
659
+ });
660
+
661
+ // ─── RFC-027 PR1.1 — D8 atomicity failure-injection (real teeth) ──
662
+ //
663
+ // PR1's SF-2 fix introduced auditCreateNodeStrict (re-throws inside tx
664
+ // callback). The PR1 v3 test only verified happy path: both rows
665
+ // present after success. 通信龙's #345 ack flagged that as a shape-pin
666
+ // — could pass even if the strict variant were silently reverted. This
667
+ // PR1.1 test injects a real failure (monkey-patch db.run to throw at
668
+ // the audit_log INSERT moment) and asserts BOTH rollback halves:
669
+ // 1. nodes.lifecycle_state UNCHANGED (didn't transition to 'stopping')
670
+ // 2. node_stop_requests row absent (INSERT rolled back too)
671
+ describe("SF-2 D8 atomicity — REAL failure injection forces ROLLBACK", () => {
672
+ test("audit_log table dropped → audit INSERT throws inside tx → ROLLBACK leaves nodes + request untouched", async () => {
673
+ setupAlphaNetwork();
674
+ const tools = buildHandlers(USER_A_ID);
675
+ // Real failure injection: drop audit_log so the strict audit
676
+ // INSERT inside the tx throws a real SQLite "no such table"
677
+ // error. The whole tx must roll back per §4.5 D8. (Patching
678
+ // adapter.db.run via property overwrite proved unreliable under
679
+ // bun:sqlite's transaction wrapper in earlier draft; dropping
680
+ // the table is the simplest way to make the failure REAL — the
681
+ // error originates inside the SQL engine, not a JS mock.)
682
+ db.exec("DROP TABLE IF EXISTS audit_log_BACKUP");
683
+ db.exec("ALTER TABLE audit_log RENAME TO audit_log_BACKUP");
684
+ let r: Reply;
685
+ try {
686
+ r = await call(tools.stop_node, {
687
+ child_node_id: CHILD_A_ID, daemon_node_id: DAEMON_A_ID, network_id: NET_A,
688
+ });
689
+ } finally {
690
+ // Restore so subsequent tests + cleanup work.
691
+ db.exec("DROP TABLE IF EXISTS audit_log");
692
+ db.exec("ALTER TABLE audit_log_BACKUP RENAME TO audit_log");
693
+ }
694
+ expect(r.ok).toBe(false);
695
+ // dispatch_tx_failed is the expected error. Print the actual reply
696
+ // if we got something else so the failure mode is diagnosable.
697
+ if (r.error !== "dispatch_tx_failed") {
698
+ console.error("[SF-2 unexpected reply]", JSON.stringify(r));
699
+ }
700
+ expect(r.error).toBe("dispatch_tx_failed");
701
+
702
+ // ROLLBACK observable:
703
+ // (a) lifecycle_state did NOT transition out of 'active'
704
+ expect(readNode(CHILD_A_ID)?.lifecycle_state).toBe("active");
705
+ // (b) no node_stop_requests row exists for this child
706
+ const reqs = db.all<{ request_id: string }>(
707
+ `SELECT request_id FROM node_stop_requests WHERE child_node_id = ?1`, [CHILD_A_ID],
708
+ );
709
+ expect(reqs.length).toBe(0);
710
+ // (c) no audit row was written
711
+ expect(readAudit("stop_node_dispatched", NET_A).length).toBe(0);
712
+ });
713
+ });
714
+
715
+ // ─── RFC-027 PR1.1 — inbox-enqueue lifecycle guard at routing layer ──
716
+ //
717
+ // 6 inbox INSERT sites in tools.ts (send_task / send_message / reply /
718
+ // retry_task / reassign_task / broadcast) now pre-check the target
719
+ // alias's nodes.lifecycle_state. Anything other than `active` refuses
720
+ // with `node_not_active`. Sample the highest-traffic path (send_task)
721
+ // for a stopping target — this catches the routing-after-SIGTERM
722
+ // window that RFC §2.3 explicitly closes.
723
+ describe("inbox-enqueue lifecycle_state guard (RFC-027 §2.3 race-free)", () => {
724
+ test("send_task to a stopping node → refused with node_not_active", async () => {
725
+ setupAlphaNetwork();
726
+ // Caller + target sessions rows (send_task's resolveDeliveryTarget
727
+ // looks up the target in sessions, not just nodes).
728
+ db.run(
729
+ `INSERT INTO sessions (resume_id, alias, network_id, last_seen_at, status, cpu_cores, mem_total_gb, ip)
730
+ VALUES (?1, ?2, ?3, datetime('now'), 'idle', 4, 8, '10.0.0.99')`,
731
+ [`s_caller_${Date.now()}`, "sender-x", NET_A],
732
+ );
733
+ db.run(
734
+ `INSERT INTO sessions (resume_id, alias, network_id, last_seen_at, status, cpu_cores, mem_total_gb, ip)
735
+ VALUES (?1, ?2, ?3, datetime('now'), 'idle', 4, 8, '10.0.0.5')`,
736
+ [`s_child_${Date.now()}`, CHILD_A_ALIAS, NET_A],
737
+ );
738
+ // Move target into stopping (mid-flight stop_node race window).
739
+ db.run(`UPDATE nodes SET lifecycle_state = 'stopping' WHERE node_id = ?1`, [CHILD_A_ID]);
740
+
741
+ const tools = buildHandlers(USER_A_ID);
742
+ const r = await call(tools.send_task, {
743
+ alias: CHILD_A_ALIAS,
744
+ task: "racey post-SIGTERM task",
745
+ network_id: NET_A,
746
+ });
747
+ expect(r.ok).toBe(false);
748
+ expect(r.error).toBe("node_not_active");
749
+ expect(r.lifecycle_state).toBe("stopping");
750
+ // Inbox unchanged (no row inserted for this alias post-stopping).
751
+ const inboxRows = db.all<{ id: string }>(
752
+ `SELECT id FROM inbox WHERE session_name = ?1 AND network_id = ?2`,
753
+ [CHILD_A_ALIAS, NET_A],
754
+ );
755
+ expect(inboxRows.length).toBe(0);
756
+ });
757
+ });
758
+
759
+ // ─── list_my_children (PR1.1 hub support for rebuild) ────────────
760
+ describe("list_my_children HANDLER (RFC-027 PR1.1)", () => {
761
+ test("daemon-bound caller gets its children list", async () => {
762
+ setupAlphaNetwork();
763
+ // Plant a create-request row simulating that DAEMON_A has spawned
764
+ // CHILD_A previously (the daemon's child must be in this table).
765
+ db.run(
766
+ `INSERT INTO node_create_requests
767
+ (request_id, daemon_node_id, child_name, network_id, runtime, model, flags_json, env_keys, status, child_token_id, created_at, created_by_token)
768
+ VALUES ('cr_lmc_test', ?1, ?2, ?3, 'claude-agent-sdk', 'x', '{}', '[]', 'succeeded', NULL, ?4, 'tok_test')`,
769
+ [DAEMON_A_ID, CHILD_A_ALIAS, NET_A, Date.now()],
770
+ );
771
+ // The child's nodes row must exist (setupAlphaNetwork seeds it),
772
+ // and the canonical child_node_id needs to match `node_${request_id.slice(3)}`
773
+ // We update the existing child row's id so the LEFT JOIN matches.
774
+ db.run(`UPDATE nodes SET node_id = 'node_lmc_test' WHERE alias = ?1 AND network_id = ?2`, [CHILD_A_ALIAS, NET_A]);
775
+
776
+ const daemonTools = buildHandlers(USER_A_ID, true, DAEMON_A_TOK, NET_A);
777
+ const r = await call(daemonTools.list_my_children, {});
778
+ expect(r.ok).toBe(true);
779
+ expect(Array.isArray(r.children)).toBe(true);
780
+ const aliases = (r.children as Array<{ alias: string }>).map(c => c.alias);
781
+ expect(aliases).toContain(CHILD_A_ALIAS);
782
+ });
783
+
784
+ test("non-daemon caller (utok) refused", async () => {
785
+ setupAlphaNetwork();
786
+ const userTools = buildHandlers(USER_A_ID); // utok, not daemon-bound
787
+ const r = await call(userTools.list_my_children, {});
788
+ expect(r.ok).toBe(false);
789
+ });
790
+ });
791
+
792
+ describe("create_node audit wording (#1362)", () => {
793
+ test("create_node records a dispatch attempt, not guaranteed SSE delivery", async () => {
794
+ setupAlphaNetwork();
795
+ const tools = buildHandlers(USER_A_ID);
796
+ const r = await call(tools.create_node, {
797
+ daemon_node_id: DAEMON_A_ID,
798
+ node_spec: {
799
+ name: "sd-new-child",
800
+ runtime: "claude-agent-sdk",
801
+ model: "x",
802
+ },
803
+ network_id: NET_A,
804
+ });
805
+
806
+ expect(r.ok).toBe(true);
807
+ expect(typeof r.request_id).toBe("string");
808
+ expect(readAudit("create_node_dispatch_attempted", NET_A).length).toBe(1);
809
+ expect(readAudit("create_node_dispatched", NET_A).length).toBe(0);
810
+ });
811
+ });
812
+
813
+ describe("list_my_pending_create_requests HANDLER (#1362 SSE reconnect compensation)", () => {
814
+ test("daemon-bound caller gets only its own pending create requests", async () => {
815
+ setupAlphaNetwork();
816
+ const otherDaemonId = "node_sd_daemon_other";
817
+ seedDaemon(NET_A, otherDaemonId, "sd-daemon-other", USER_A_ID, "tok_sd_daemon_other");
818
+ db.run(
819
+ `INSERT INTO node_create_requests
820
+ (request_id, daemon_node_id, child_name, network_id, runtime, model, flags_json, env_keys, status, child_token_id, created_at, created_by_token)
821
+ VALUES
822
+ ('cr_pending_mine', ?1, 'child-pending-mine', ?2, 'claude-agent-sdk', 'x', '{}', '[]', 'pending', NULL, ?3, 'tok_test'),
823
+ ('cr_delivered_mine', ?1, 'child-delivered-mine', ?2, 'claude-agent-sdk', 'x', '{}', '[]', 'delivered', NULL, ?4, 'tok_test'),
824
+ ('cr_pending_other', ?5, 'child-pending-other', ?2, 'claude-agent-sdk', 'x', '{}', '[]', 'pending', NULL, ?6, 'tok_test')`,
825
+ [DAEMON_A_ID, NET_A, Date.now(), Date.now() + 1, otherDaemonId, Date.now() + 2],
826
+ );
827
+
828
+ const daemonTools = buildHandlers(USER_A_ID, true, DAEMON_A_TOK, NET_A);
829
+ const r = await call(daemonTools.list_my_pending_create_requests, {});
830
+
831
+ expect(r.ok).toBe(true);
832
+ expect(r.count).toBe(1);
833
+ expect(r.requests).toEqual([
834
+ expect.objectContaining({ request_id: "cr_pending_mine", child_name: "child-pending-mine" }),
835
+ ]);
836
+ });
837
+
838
+ test("non-daemon caller (utok) refused", async () => {
839
+ setupAlphaNetwork();
840
+ const userTools = buildHandlers(USER_A_ID);
841
+ const r = await call(userTools.list_my_pending_create_requests, {});
842
+ expect(r.ok).toBe(false);
843
+ });
844
+ });
845
+
846
+ describe("list_my_pending_lifecycle_requests HANDLER (#1448 SSE reconnect compensation)", () => {
847
+ function seedStop(reqId: string, daemonId: string, status: string, action: string, ageMs: number) {
848
+ db.run(
849
+ `INSERT INTO node_stop_requests (request_id, network_id, daemon_node_id, child_node_id,
850
+ child_alias, action, delete_config, created_by_token, status, created_at)
851
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, 1, 'tok_test', ?7, ?8)`,
852
+ [reqId, NET_A, daemonId, CHILD_A_ID, CHILD_A_ALIAS, action, status, Date.now() - ageMs],
853
+ );
854
+ }
855
+ // child_node_id parameterized: node_start_requests has a partial-unique
856
+ // index on child_node_id WHERE status IN ('pending','delivered'), so the
857
+ // "mine" and "other" pending start rows must target different children.
858
+ function seedStart(reqId: string, daemonId: string, childId: string, status: string, ageMs: number) {
859
+ db.run(
860
+ `INSERT INTO node_start_requests (request_id, network_id, daemon_node_id, child_node_id,
861
+ child_alias, created_by_token, status, created_at)
862
+ VALUES (?1, ?2, ?3, ?4, ?5, 'tok_test', ?6, ?7)`,
863
+ [reqId, NET_A, daemonId, childId, CHILD_A_ALIAS, status, Date.now() - ageMs],
864
+ );
865
+ }
866
+
867
+ test("daemon-bound caller gets only its own PENDING stop/delete + start (excludes delivered + other daemon)", async () => {
868
+ setupAlphaNetwork();
869
+ const otherDaemonId = "node_sd_daemon_other";
870
+ seedDaemon(NET_A, otherDaemonId, "sd-daemon-other", USER_A_ID, "tok_sd_daemon_other");
871
+ // mine — should be returned (stop + delete, oldest first)
872
+ seedStop("sr_pending_stop", DAEMON_A_ID, "pending", "stop", 30);
873
+ seedStop("sr_pending_delete", DAEMON_A_ID, "pending", "delete", 20);
874
+ seedStart("str_pending_mine", DAEMON_A_ID, CHILD_A_ID, "pending", 25);
875
+ // excluded — delivered (already pulled) + other daemon's pending
876
+ seedStop("sr_delivered_mine", DAEMON_A_ID, "delivered", "stop", 40);
877
+ seedStop("sr_pending_other", otherDaemonId, "pending", "stop", 10);
878
+ seedStart("str_pending_other", otherDaemonId, "node_sd_child_other", "pending", 10);
879
+
880
+ const daemonTools = buildHandlers(USER_A_ID, true, DAEMON_A_TOK, NET_A);
881
+ const res = await call(daemonTools.list_my_pending_lifecycle_requests, {});
882
+ expect(res.ok).toBe(true);
883
+ expect(res.stop_count).toBe(2);
884
+ expect((res.stop_requests as Array<{ request_id: string }>).map(x => x.request_id))
885
+ .toEqual(["sr_pending_stop", "sr_pending_delete"]); // oldest-first, action preserved
886
+ expect(res.start_count).toBe(1);
887
+ expect((res.start_requests as Array<{ request_id: string }>).map(x => x.request_id))
888
+ .toEqual(["str_pending_mine"]);
889
+ });
890
+
891
+ // Witnessed-red 的核心链:真实 stop_node 派发时 daemon 无 SSE 订阅者 →
892
+ // pushEvent 静默丢门铃 → 行卡 pending / 节点卡 stopping(缺陷态)。修复后这条
893
+ // pending 行会被 list_my_pending_lifecycle_requests 列出 → 重连 reconcile 能重放。
894
+ // 改前(无此工具)该行永远无人发现、节点永久卡 stopping。
895
+ test("stuck-pending after a dropped doorbell IS surfaced for reconnect replay", async () => {
896
+ setupAlphaNetwork();
897
+ const userTools = buildHandlers(USER_A_ID);
898
+ // 无 SSE 订阅者:dispatch 建 pending 行 + pushEvent 丢弃(测试进程里没有 client)
899
+ const disp = await call(userTools.stop_node, { child_node_id: CHILD_A_ID, daemon_node_id: DAEMON_A_ID, network_id: NET_A });
900
+ expect(disp.ok).toBe(true);
901
+ const reqId = disp.request_id as string;
902
+ // 缺陷态:行 pending、节点 stopping(门铃没送达,无人推进)
903
+ const row = db.get<{ status: string }>("SELECT status FROM node_stop_requests WHERE request_id = ?1", reqId);
904
+ expect(row?.status).toBe("pending");
905
+ expect(readNode(CHILD_A_ID)?.lifecycle_state).toBe("stopping");
906
+ // 修复:pending 行经新工具对本 daemon 可见 → 重连补偿能拿到并重放
907
+ const daemonTools = buildHandlers(USER_A_ID, true, DAEMON_A_TOK, NET_A);
908
+ const r = await call(daemonTools.list_my_pending_lifecycle_requests, {});
909
+ expect(r.ok).toBe(true);
910
+ expect((r.stop_requests as Array<{ request_id: string }>).map(x => x.request_id)).toContain(reqId);
911
+ });
912
+
913
+ test("non-daemon caller (utok) refused", async () => {
914
+ setupAlphaNetwork();
915
+ const userTools = buildHandlers(USER_A_ID);
916
+ const r = await call(userTools.list_my_pending_lifecycle_requests, {});
917
+ expect(r.ok).toBe(false);
918
+ });
919
+ });
920
+
921
+ // ─── PR1.2a — restart_node resets lifecycle_state ──────────────────
922
+ //
923
+ // 通信龙 #346 ack latent: without this, a stopped node restart-ed via
924
+ // restart_node would still have lifecycle_state='stopped' in the
925
+ // nodes table → the 6 MCP + 2 REST inbox guards would refuse all
926
+ // routing → node silently unreachable until manual DB fix. Asserts
927
+ // the dispatch + state flip happen atomically (tx).
928
+ describe("RFC-027 PR1.2a — restart_node resets lifecycle_state to 'active'", () => {
929
+ test("restart_node on a stopped node → lifecycle_state flips back to 'active' + dispatch row created", async () => {
930
+ setupAlphaNetwork();
931
+ // Move the child to 'stopped' (simulating prior stop_node completion).
932
+ db.run(`UPDATE nodes SET lifecycle_state = 'stopped' WHERE node_id = ?1`, [CHILD_A_ID]);
933
+ expect(readNode(CHILD_A_ID)?.lifecycle_state).toBe("stopped");
934
+
935
+ const tools = buildHandlers(USER_A_ID);
936
+ const r = await call(tools.restart_node, {
937
+ node_id: CHILD_A_ID,
938
+ network_id: NET_A,
939
+ });
940
+ expect(r.ok).toBe(true);
941
+ expect(r.apply_mode).toBe("restart_only");
942
+
943
+ // State flipped back.
944
+ expect(readNode(CHILD_A_ID)?.lifecycle_state).toBe("active");
945
+ // node_config_updates row exists (the dispatch).
946
+ const rows = db.all<{ update_id: string; status: string }>(
947
+ `SELECT update_id, status FROM node_config_updates WHERE node_id = ?1 ORDER BY created_at DESC LIMIT 1`,
948
+ [CHILD_A_ID],
949
+ );
950
+ expect(rows.length).toBe(1);
951
+ expect(rows[0].status).toBe("pending");
952
+ });
953
+
954
+ test("restart_node on an active node → still resets to active (idempotent, no-op state-wise)", async () => {
955
+ setupAlphaNetwork();
956
+ expect(readNode(CHILD_A_ID)?.lifecycle_state).toBe("active");
957
+ const tools = buildHandlers(USER_A_ID);
958
+ const r = await call(tools.restart_node, { node_id: CHILD_A_ID, network_id: NET_A });
959
+ expect(r.ok).toBe(true);
960
+ expect(readNode(CHILD_A_ID)?.lifecycle_state).toBe("active");
961
+ });
962
+ });
963
+
964
+ // ── #1511 — restart_node 在途任务默认拒绝(只提示,不自动重启) ──────
965
+ //
966
+ // 节点侧 exit-75 的 drain 只等 60 秒,超时会硬打断当前回合;所以「正在跑
967
+ // 任务」时 Hub 端在派发前就拒绝,计数规则与 stop_node 完全同一份
968
+ // (#2022/#2029 修订版,实现在 countInFlightTasks)。客户端语义:保存密钥
969
+ // 后若节点忙,不安排重启,只提示等任务完成或去节点机器上手动重启。
970
+ describe("restart_node — in-flight default-refuse (#1511)", () => {
971
+ test("live task row → node_busy_in_flight, no dispatch row, state untouched", async () => {
972
+ setupAlphaNetwork();
973
+ seedTaskWithInbox(NET_A, CHILD_A_ALIAS, { task_id: "task_1511_live", status: "delivered" });
974
+ const r = await call(buildHandlers(USER_A_ID).restart_node, { node_id: CHILD_A_ID, network_id: NET_A });
975
+ expect(r.ok).toBe(false);
976
+ expect(r.error).toBe("node_busy_in_flight");
977
+ expect(r.in_flight_count).toBe(1);
978
+ expect(typeof r.hint).toBe("string");
979
+ const rows = db.all<{ update_id: string }>(`SELECT update_id FROM node_config_updates WHERE node_id = ?1`, [CHILD_A_ID]);
980
+ expect(rows.length).toBe(0);
981
+ expect(readNode(CHILD_A_ID)?.lifecycle_state).toBe("active");
982
+ });
983
+
984
+ test("unacked legacy inbox rows count too — same rule as stop", async () => {
985
+ setupAlphaNetwork();
986
+ seedInbox(NET_A, CHILD_A_ALIAS, 2);
987
+ const r = await call(buildHandlers(USER_A_ID).restart_node, { node_id: CHILD_A_ID, network_id: NET_A });
988
+ expect(r.ok).toBe(false);
989
+ expect(r.error).toBe("node_busy_in_flight");
990
+ expect(r.in_flight_count).toBe(2);
991
+ });
992
+
993
+ test("terminal-only rows → restart dispatches (parity with #2022 stop rule)", async () => {
994
+ setupAlphaNetwork();
995
+ seedTaskWithInbox(NET_A, CHILD_A_ALIAS, { task_id: "task_1511_replied", status: "replied" });
996
+ const r = await call(buildHandlers(USER_A_ID).restart_node, { node_id: CHILD_A_ID, network_id: NET_A });
997
+ expect(r.ok).toBe(true);
998
+ expect(r.apply_mode).toBe("restart_only");
999
+ });
1000
+
1001
+ test("2h-old live task is never aged out — status wins over age (same as stop)", async () => {
1002
+ setupAlphaNetwork();
1003
+ seedTaskWithInbox(NET_A, CHILD_A_ALIAS, {
1004
+ task_id: "task_1511_running_120m", status: "running",
1005
+ task_age: "-120 minutes", inbox_age: "-120 minutes", expires_in: "-60 minutes",
1006
+ });
1007
+ const r = await call(buildHandlers(USER_A_ID).restart_node, { node_id: CHILD_A_ID, network_id: NET_A });
1008
+ expect(r.ok).toBe(false);
1009
+ expect(r.error).toBe("node_busy_in_flight");
1010
+ });
1011
+
1012
+ test("stopped node + live-row corpse → restart still dispatches (un-stop must not be blocked)", async () => {
1013
+ setupAlphaNetwork();
1014
+ db.run(`UPDATE nodes SET lifecycle_state = 'stopped' WHERE node_id = ?1`, [CHILD_A_ID]);
1015
+ seedTaskWithInbox(NET_A, CHILD_A_ALIAS, { task_id: "task_1511_corpse", status: "delivered" });
1016
+ const r = await call(buildHandlers(USER_A_ID).restart_node, { node_id: CHILD_A_ID, network_id: NET_A });
1017
+ expect(r.ok).toBe(true);
1018
+ expect(r.apply_mode).toBe("restart_only");
1019
+ expect(readNode(CHILD_A_ID)?.lifecycle_state).toBe("active");
1020
+ });
1021
+ });
1022
+
1023
+ // ── #1286 stale-deleting 重派出口 ──────────────────────────────────
1024
+ //
1025
+ // 修复前 daemon 丢 ack 会让行永远停在 deleting:重发被挡、force 也一样。
1026
+ // 2026-08-28 实测两行卡死(acc-…-3373 / probe-tl2),API 层面无解。
1027
+ // 出口三条件缺一不放行:force=true + 最近 delete 请求非终态 + 晾超 5 分钟。
1028
+ describe("delete_node — stale-deleting redispatch exit (#1286)", () => {
1029
+ function seedDeletingChild() {
1030
+ setupAlphaNetwork();
1031
+ db.run(`UPDATE nodes SET lifecycle_state = 'deleting' WHERE node_id = ?1`, [CHILD_A_ID]);
1032
+ }
1033
+ function seedStopRequest(status: string, ageMs: number) {
1034
+ db.run(
1035
+ `INSERT INTO node_stop_requests (request_id, network_id, daemon_node_id, child_node_id,
1036
+ child_alias, action, delete_config, created_by_token, status, created_at)
1037
+ VALUES (?1, ?2, ?3, ?4, ?5, 'delete', 1, 'tok_test', ?6, ?7)`,
1038
+ [`sr_stale_${Date.now()}_${Math.floor(ageMs)}`, NET_A, DAEMON_A_ID, CHILD_A_ID,
1039
+ CHILD_A_ALIAS, status, Date.now() - ageMs],
1040
+ );
1041
+ }
1042
+ const base = { child_node_id: CHILD_A_ID, daemon_node_id: DAEMON_A_ID, network_id: NET_A, confirm_alias: CHILD_A_ALIAS };
1043
+
1044
+ test("无 force:仍拒,且带 hint 指出口(不是让人反复撞墙)", async () => {
1045
+ seedDeletingChild(); seedStopRequest("pending", 10 * 60_000);
1046
+ const r = await call(buildHandlers(USER_A_ID).delete_node, base);
1047
+ expect(r.ok).toBe(false);
1048
+ expect(r.error).toBe("node_already_deleting");
1049
+ expect(typeof r.hint).toBe("string");
1050
+ });
1051
+
1052
+ test("🔴 force 但请求还新鲜(1 分钟):仍拒 —— force 不能变成竞态放大器", async () => {
1053
+ seedDeletingChild(); seedStopRequest("pending", 60_000);
1054
+ const r = await call(buildHandlers(USER_A_ID).delete_node, { ...base, force: true });
1055
+ expect(r.ok).toBe(false);
1056
+ expect(r.error).toBe("node_already_deleting");
1057
+ });
1058
+
1059
+ test("🔴 force 但上一条已终态(stopped):仍拒 —— daemon 刚 ack 过,行马上会转移", async () => {
1060
+ seedDeletingChild(); seedStopRequest("stopped", 10 * 60_000);
1061
+ const r = await call(buildHandlers(USER_A_ID).delete_node, { ...base, force: true });
1062
+ expect(r.ok).toBe(false);
1063
+ expect(r.error).toBe("node_already_deleting");
1064
+ });
1065
+
1066
+ test("force + pending 晾超 5 分钟:放行,生成新 request_id", async () => {
1067
+ seedDeletingChild(); seedStopRequest("pending", 10 * 60_000);
1068
+ const r = await call(buildHandlers(USER_A_ID).delete_node, { ...base, force: true });
1069
+ expect(r.ok).toBe(true);
1070
+ expect((r.request_id as string).startsWith("sr_")).toBe(true);
1071
+ });
1072
+
1073
+ test("force + dispatched 晾超 5 分钟:同样放行", async () => {
1074
+ seedDeletingChild(); seedStopRequest("dispatched", 10 * 60_000);
1075
+ const r = await call(buildHandlers(USER_A_ID).delete_node, { ...base, force: true });
1076
+ expect(r.ok).toBe(true);
1077
+ });
1078
+ });
1079
+
1080
+ // ── #2022 — in-flight gate: terminal / aged rows must not pin busy ──
1081
+ //
1082
+ // The old gate was COUNT(*) FROM inbox WHERE session_name=? AND acked=0:
1083
+ // no join to tasks, no age limit, and nothing acks an inbox row whose
1084
+ // task already died (retention sweeps only acked=1 rows), so a single
1085
+ // dead row pinned the node to node_busy_in_flight forever.
1086
+ //
1087
+ // Rule under test (#2029 review):
1088
+ // 1. type='task' rows that join to a tasks row are judged by status
1089
+ // ALONE — terminal (replied / failed / cancelled / expired) is not
1090
+ // counted, anything else is counted with NO age ceiling. agent-node
1091
+ // acks the inbox row only when the task is done, so a 90-minute
1092
+ // (or ttl_seconds>3600) run stays acked=0 the whole time and must
1093
+ // keep the gate closed; expiry is patrolExpiredTasks' job.
1094
+ // Join key is COALESCE(task_id, id), the logical id cancel_task
1095
+ // uses.
1096
+ // 2. rows with no status of their own — task rows whose tasks row is
1097
+ // gone, and non-task rows (reply / broadcast / message) — get the
1098
+ // 60-minute age ceiling; nothing else will ever retire them.
1099
+ // 3. patrolExpiredTasks acks the matching inbox rows in the same
1100
+ // transaction that expires the task.
1101
+
1102
+ function seedTaskWithInbox(
1103
+ net: string,
1104
+ alias: string,
1105
+ opts: {
1106
+ task_id: string;
1107
+ status: string;
1108
+ /** signed datetime offset for the tasks row, e.g. '-3 days' */
1109
+ task_age?: string;
1110
+ /** signed datetime offset for the inbox row, e.g. '-3 days' */
1111
+ inbox_age?: string;
1112
+ /** signed datetime offset for tasks.expires_at, e.g. '+1 hour' */
1113
+ expires_in?: string;
1114
+ },
1115
+ ) {
1116
+ db.run(
1117
+ `INSERT INTO tasks (task_id, from_name, to_name, priority, status, content, requires_response,
1118
+ created_at, delivered_at, expires_at, network_id)
1119
+ VALUES (?1, 'caller', ?2, 'normal', ?3, 'do the thing', 'reply',
1120
+ datetime('now', ?4), datetime('now', ?4), datetime('now', ?5), ?6)`,
1121
+ [opts.task_id, alias, opts.status, opts.task_age ?? "0 seconds", opts.expires_in ?? "+1 hour", net],
1122
+ );
1123
+ db.run(
1124
+ `INSERT INTO inbox (id, task_id, session_name, type, priority, content, from_session, network_id, acked, created_at)
1125
+ VALUES (?1, ?1, ?2, 'task', 'normal', 'do the thing', 'caller', ?3, 0, datetime('now', ?4))`,
1126
+ [opts.task_id, alias, net, opts.inbox_age ?? "0 seconds"],
1127
+ );
1128
+ }
1129
+
1130
+ function stopArgs() {
1131
+ return { child_node_id: CHILD_A_ID, daemon_node_id: DAEMON_A_ID, network_id: NET_A };
1132
+ }
1133
+
1134
+ describe("#2022 stop gate — terminal task rows are not in flight", () => {
1135
+ test("28-day-old expired + 3-day-old replied rows → stop dispatches, in_flight=0", async () => {
1136
+ setupAlphaNetwork();
1137
+ seedTaskWithInbox(NET_A, CHILD_A_ALIAS, {
1138
+ task_id: "task_2022_expired", status: "expired",
1139
+ task_age: "-28 days", inbox_age: "-28 days", expires_in: "-27 days",
1140
+ });
1141
+ seedTaskWithInbox(NET_A, CHILD_A_ALIAS, {
1142
+ task_id: "task_2022_replied", status: "replied",
1143
+ task_age: "-3 days", inbox_age: "-3 days", expires_in: "-2 days",
1144
+ });
1145
+ const r = await call(buildHandlers(USER_A_ID).stop_node, stopArgs());
1146
+ expect(r.ok).toBe(true);
1147
+ expect(r.in_flight_at_dispatch).toBe(0);
1148
+ expect(readNode(CHILD_A_ID)?.lifecycle_state).toBe("stopping");
1149
+ });
1150
+
1151
+ test("FRESH terminal row (replied, 0s old) also not counted — terminal filter alone is enough", async () => {
1152
+ setupAlphaNetwork();
1153
+ seedTaskWithInbox(NET_A, CHILD_A_ALIAS, { task_id: "task_2022_fresh_replied", status: "replied" });
1154
+ const r = await call(buildHandlers(USER_A_ID).stop_node, stopArgs());
1155
+ expect(r.ok).toBe(true);
1156
+ expect(r.in_flight_at_dispatch).toBe(0);
1157
+ });
1158
+ });
1159
+
1160
+ describe("#2022 stop gate — genuinely in-flight rows still block", () => {
1161
+ test("fresh non-terminal task row → node_busy_in_flight, count surfaced, state untouched", async () => {
1162
+ setupAlphaNetwork();
1163
+ seedTaskWithInbox(NET_A, CHILD_A_ALIAS, { task_id: "task_2022_live", status: "delivered" });
1164
+ const r = await call(buildHandlers(USER_A_ID).stop_node, stopArgs());
1165
+ expect(r.ok).toBe(false);
1166
+ expect(r.error).toBe("node_busy_in_flight");
1167
+ expect(r.in_flight_count).toBe(1);
1168
+ expect(readNode(CHILD_A_ID)?.lifecycle_state).toBe("active");
1169
+ expect(readAudit("stop_node_dispatched", NET_A).length).toBe(0);
1170
+ });
1171
+
1172
+ test("fresh non-task inbox row (type='reply') still counts — judged by age only", async () => {
1173
+ setupAlphaNetwork();
1174
+ db.run(
1175
+ `INSERT INTO inbox (id, session_name, type, content, from_session, network_id, acked, created_at)
1176
+ VALUES (?1, ?2, 'reply', 'fresh reply', 'caller', ?3, 0, datetime('now'))`,
1177
+ [`inbox_2022_fresh_reply`, CHILD_A_ALIAS, NET_A],
1178
+ );
1179
+ const r = await call(buildHandlers(USER_A_ID).stop_node, stopArgs());
1180
+ expect(r.ok).toBe(false);
1181
+ expect(r.error).toBe("node_busy_in_flight");
1182
+ expect(r.in_flight_count).toBe(1);
1183
+ });
1184
+ });
1185
+
1186
+ describe("#2022 stop gate — a live task is never aged out (status wins over age)", () => {
1187
+ test("🔴 created 2 hours ago + task.status='running' → still node_busy_in_flight", async () => {
1188
+ setupAlphaNetwork();
1189
+ seedTaskWithInbox(NET_A, CHILD_A_ALIAS, {
1190
+ task_id: "task_2022_running_90m", status: "running",
1191
+ task_age: "-120 minutes", inbox_age: "-120 minutes", expires_in: "-60 minutes",
1192
+ });
1193
+ const r = await call(buildHandlers(USER_A_ID).stop_node, stopArgs());
1194
+ expect(r.ok).toBe(false);
1195
+ expect(r.error).toBe("node_busy_in_flight");
1196
+ expect(r.in_flight_count).toBe(1);
1197
+ expect(readNode(CHILD_A_ID)?.lifecycle_state).toBe("active");
1198
+ });
1199
+
1200
+ test("task.status='acked' 2 hours old (patrol never expires it) → still blocked", async () => {
1201
+ setupAlphaNetwork();
1202
+ seedTaskWithInbox(NET_A, CHILD_A_ALIAS, {
1203
+ task_id: "task_2022_acked_120m", status: "acked",
1204
+ inbox_age: "-120 minutes", expires_in: "+12 hours",
1205
+ });
1206
+ const r = await call(buildHandlers(USER_A_ID).stop_node, stopArgs());
1207
+ expect(r.error).toBe("node_busy_in_flight");
1208
+ expect(r.in_flight_count).toBe(1);
1209
+ });
1210
+ });
1211
+
1212
+ describe("#2022 stop gate — age ceiling (60 min) for rows with no status", () => {
1213
+ test("orphan task row (tasks row reaped) 8 days old → not counted", async () => {
1214
+ setupAlphaNetwork();
1215
+ db.run(
1216
+ `INSERT INTO inbox (id, task_id, session_name, type, content, from_session, network_id, acked, created_at)
1217
+ VALUES (?1, ?1, ?2, 'task', 'orphan task', 'caller', ?3, 0, datetime('now', '-8 days'))`,
1218
+ [`task_2022_reaped`, CHILD_A_ALIAS, NET_A],
1219
+ );
1220
+ const r = await call(buildHandlers(USER_A_ID).stop_node, stopArgs());
1221
+ expect(r.ok).toBe(true);
1222
+ expect(r.in_flight_at_dispatch).toBe(0);
1223
+ });
1224
+
1225
+ test("non-task row older than the ceiling → not counted (the production backlog shape)", async () => {
1226
+ setupAlphaNetwork();
1227
+ db.run(
1228
+ `INSERT INTO inbox (id, session_name, type, content, from_session, network_id, acked, created_at)
1229
+ VALUES (?1, ?2, 'broadcast', 'week-old broadcast', 'caller', ?3, 0, datetime('now', '-7 days'))`,
1230
+ [`inbox_2022_old_broadcast`, CHILD_A_ALIAS, NET_A],
1231
+ );
1232
+ const r = await call(buildHandlers(USER_A_ID).stop_node, stopArgs());
1233
+ expect(r.ok).toBe(true);
1234
+ expect(r.in_flight_at_dispatch).toBe(0);
1235
+ });
1236
+ });
1237
+
1238
+ describe("#2022 patrolExpiredTasks — expires the task AND acks its inbox rows", () => {
1239
+ test("same transaction: tasks.status='expired' + inbox.acked=1 → gate unblocks", async () => {
1240
+ setupAlphaNetwork();
1241
+ seedTaskWithInbox(NET_A, CHILD_A_ALIAS, {
1242
+ task_id: "task_2022_due", status: "delivered",
1243
+ inbox_age: "-10 minutes", expires_in: "-1 minute",
1244
+ });
1245
+
1246
+ // Before the patrol: fresh, non-terminal → the node is correctly busy.
1247
+ const before = await call(buildHandlers(USER_A_ID).stop_node, stopArgs());
1248
+ expect(before.error).toBe("node_busy_in_flight");
1249
+ expect(before.in_flight_count).toBe(1);
1250
+
1251
+ patrolExpiredTasks();
1252
+
1253
+ expect(db.get<{ status: string }>("SELECT status FROM tasks WHERE task_id = ?1", "task_2022_due")?.status).toBe("expired");
1254
+ const inboxRow = db.get<{ acked: number }>(
1255
+ "SELECT acked FROM inbox WHERE task_id = ?1 AND session_name = ?2", "task_2022_due", CHILD_A_ALIAS,
1256
+ );
1257
+ expect(inboxRow?.acked).toBe(1);
1258
+
1259
+ // And the gate that was blocked a moment ago now dispatches.
1260
+ const after = await call(buildHandlers(USER_A_ID).stop_node, stopArgs());
1261
+ expect(after.ok).toBe(true);
1262
+ expect(after.in_flight_at_dispatch).toBe(0);
1263
+ });
1264
+
1265
+ test("legacy inbox row keyed by id (task_id IS NULL) is acked too", async () => {
1266
+ setupAlphaNetwork();
1267
+ db.run(
1268
+ `INSERT INTO tasks (task_id, from_name, to_name, priority, status, content, requires_response,
1269
+ created_at, expires_at, network_id)
1270
+ VALUES ('task_2022_legacy', 'caller', ?1, 'normal', 'delivered', 'do the thing', 'reply',
1271
+ datetime('now', '-10 minutes'), datetime('now', '-1 minute'), ?2)`,
1272
+ [CHILD_A_ALIAS, NET_A],
1273
+ );
1274
+ // Pre-task_id shape: the transport row IS the logical id.
1275
+ db.run(
1276
+ `INSERT INTO inbox (id, session_name, type, content, from_session, network_id, acked, created_at)
1277
+ VALUES ('task_2022_legacy', ?1, 'task', 'do the thing', 'caller', ?2, 0, datetime('now', '-10 minutes'))`,
1278
+ [CHILD_A_ALIAS, NET_A],
1279
+ );
1280
+
1281
+ patrolExpiredTasks();
1282
+
1283
+ expect(db.get<{ status: string }>("SELECT status FROM tasks WHERE task_id = 'task_2022_legacy'")?.status).toBe("expired");
1284
+ expect(db.get<{ acked: number }>("SELECT acked FROM inbox WHERE id = 'task_2022_legacy'")?.acked).toBe(1);
1285
+ });
1286
+ });