@sleep2agi/commhub-server 0.9.0-preview.27 → 0.9.0-preview.270

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 (444) hide show
  1. package/README.md +120 -3
  2. package/bin/commhub.ts +93 -9
  3. package/build-info.json +7 -0
  4. package/package.json +10 -8
  5. package/src/ack-create-request-transport.test.ts +182 -0
  6. package/src/ack-create-request.test.ts +52 -8
  7. package/src/admin-delete-network-http.test.ts +229 -0
  8. package/src/admin-networks-http.test.ts +88 -0
  9. package/src/adoption-candidates-http.test.ts +140 -0
  10. package/src/adoption-candidates.ts +158 -0
  11. package/src/agent-access-batch.test.ts +210 -0
  12. package/src/agent-access.ts +585 -0
  13. package/src/agent-acl-groups-http.test.ts +247 -0
  14. package/src/agent-acl-http.test.ts +691 -0
  15. package/src/agent-acl-slice3-http.test.ts +885 -0
  16. package/src/agent-department-grants.test.ts +129 -0
  17. package/src/agent-department-http.test.ts +215 -0
  18. package/src/agent-groups-perf.test.ts +223 -0
  19. package/src/agent-notice.ts +48 -0
  20. package/src/agent-team-whoami-http.test.ts +98 -0
  21. package/src/agent-teams-http.test.ts +330 -0
  22. package/src/agent-teams.ts +244 -0
  23. package/src/alias-baseline-2571.test.ts +162 -0
  24. package/src/alias-baseline.ts +113 -0
  25. package/src/alias-filter.test.ts +72 -0
  26. package/src/alias-filter.ts +42 -0
  27. package/src/api-host-supervisors-can-create-nodes.test.ts +350 -0
  28. package/src/api-host-supervisors-fallback.test.ts +6 -7
  29. package/src/api-host-supervisors-runtime-readiness.test.ts +195 -0
  30. package/src/api-nodes-shape.test.ts +131 -4
  31. package/src/auth-abuse-counters.test.ts +144 -0
  32. package/src/auth-abuse-counters.ts +122 -0
  33. package/src/auth-layer-shape.test.ts +105 -0
  34. package/src/auth-password-change-cli-tokens-http.test.ts +423 -0
  35. package/src/auth-sessions-http.test.ts +260 -0
  36. package/src/auth-validate.test.ts +5 -1
  37. package/src/auth-weak-password-login.test.ts +176 -0
  38. package/src/auth.ts +641 -68
  39. package/src/backfill-node-ids-2664.test.ts +128 -0
  40. package/src/binding-generation-http.test.ts +141 -0
  41. package/src/blocked-exit-on-reply.test.ts +122 -0
  42. package/src/broadcast-fanout-2721.test.ts +149 -0
  43. package/src/broadcast-fanout.ts +117 -0
  44. package/src/build-commit-report-http.test.ts +128 -0
  45. package/src/build-info.test.ts +60 -0
  46. package/src/build-info.ts +85 -0
  47. package/src/chain-attempt-dedup.test.ts +447 -0
  48. package/src/clip.test.ts +36 -0
  49. package/src/clip.ts +48 -0
  50. package/src/clone-node.test.ts +269 -0
  51. package/src/clone-node.ts +289 -0
  52. package/src/codex-config-flags.ts +77 -0
  53. package/src/codex-fork-contract.ts +23 -0
  54. package/src/codex-fork-migration.test.ts +38 -0
  55. package/src/commhub-bin-args.test.ts +85 -0
  56. package/src/config-apply-validate.test.ts +188 -1
  57. package/src/config-apply-validate.ts +222 -3
  58. package/src/cors-origins.test.ts +73 -0
  59. package/src/create-node-blocked-gate.test.ts +365 -0
  60. package/src/create-node-error-domain.test.ts +127 -0
  61. package/src/create-node-network-id.test.ts +91 -0
  62. package/src/create-node-tool-schema.test.ts +49 -0
  63. package/src/create-node-unicode-name.test.ts +126 -0
  64. package/src/create-node-validate.test.ts +199 -7
  65. package/src/create-node-validate.ts +232 -15
  66. package/src/create-node-workdir.test.ts +298 -0
  67. package/src/create-node.ts +88 -23
  68. package/src/daemon-provider-snapshots.test.ts +453 -0
  69. package/src/daemon-provider-snapshots.ts +327 -0
  70. package/src/daemon-token-owner-http.test.ts +346 -0
  71. package/src/dashboard-slash-routing-http.test.ts +109 -0
  72. package/src/db-adapter-guard.test.ts +148 -0
  73. package/src/db-adapter-translate.test.ts +128 -0
  74. package/src/db-adapter.ts +377 -91
  75. package/src/db-timestamp.test.ts +38 -0
  76. package/src/db-timestamp.ts +15 -0
  77. package/src/db.ts +1298 -153
  78. package/src/delivered-without-push.test.ts +140 -0
  79. package/src/department-groups-http.test.ts +209 -0
  80. package/src/department-groups-sync-http.test.ts +328 -0
  81. package/src/department-groups.ts +434 -0
  82. package/src/department-heads-http.test.ts +350 -0
  83. package/src/department-heads.ts +226 -0
  84. package/src/departments-agent-count.test.ts +139 -0
  85. package/src/departments-http.test.ts +185 -0
  86. package/src/departments-mcp-error-domain.test.ts +135 -0
  87. package/src/departments-mcp.test.ts +128 -0
  88. package/src/departments.ts +318 -0
  89. package/src/desktop-message-seam.test.ts +150 -0
  90. package/src/desktop-message.test.ts +368 -0
  91. package/src/dm-file-scope-http.test.ts +227 -0
  92. package/src/empty-node-sweeper.test.ts +104 -0
  93. package/src/empty-node-sweeper.ts +88 -0
  94. package/src/env-transport-gate-http.test.ts +240 -0
  95. package/src/env-transport-gate.ts +80 -0
  96. package/src/env-transport-policy.ts +56 -0
  97. package/src/etag-of.test.ts +57 -0
  98. package/src/event-loop-lag.test.ts +180 -0
  99. package/src/event-loop-lag.ts +201 -0
  100. package/src/expiry-counters.test.ts +187 -0
  101. package/src/expiry-counters.ts +227 -0
  102. package/src/expiry-evidence-db.test.ts +103 -0
  103. package/src/ext-token-shared.test.ts +60 -0
  104. package/src/ext-validation-regression.test.ts +10 -17
  105. package/src/external-schedule-edits-http.test.ts +321 -0
  106. package/src/external-schedule-edits-timestamps.test.ts +64 -0
  107. package/src/external-schedule-edits.ts +327 -0
  108. package/src/file-download-authz-dev-open.test.ts +1 -1
  109. package/src/file-download-authz.test.ts +25 -4
  110. package/src/file-download-date-bucket.test.ts +1 -1
  111. package/src/file-network-scope-dev-open.test.ts +1 -1
  112. package/src/file-network-scope.test.ts +7 -6
  113. package/src/group-membership-events-http.test.ts +264 -0
  114. package/src/group-messages-http.test.ts +483 -0
  115. package/src/group-messages.ts +297 -0
  116. package/src/health-anon-readers.ts +67 -0
  117. package/src/health-host-disk-2756.test.ts +71 -0
  118. package/src/health-identity-root.test.ts +98 -0
  119. package/src/health-redaction.test.ts +1599 -7
  120. package/src/health-status-reasons.test.ts +84 -0
  121. package/src/host-supervisor-identity-http.test.ts +152 -0
  122. package/src/host-supervisor-identity.ts +92 -0
  123. package/src/host-supervisors-daemon-version.test.ts +137 -0
  124. package/src/http-gzip.test.ts +94 -0
  125. package/src/http-gzip.ts +112 -0
  126. package/src/hub-catalog-read-http.test.ts +664 -0
  127. package/src/hub-provider-config.test.ts +166 -0
  128. package/src/hub-provider-config.ts +202 -0
  129. package/src/hub-timestamp.test.ts +38 -0
  130. package/src/hub-timestamp.ts +27 -0
  131. package/src/human-dm.ts +215 -0
  132. package/src/human-inbox.ts +42 -0
  133. package/src/inbox-caller.ts +49 -0
  134. package/src/inbox-count-sse.test.ts +318 -0
  135. package/src/inbox-count.ts +29 -0
  136. package/src/index.ts +6 -2
  137. package/src/license-state.test.ts +105 -0
  138. package/src/license-state.ts +48 -0
  139. package/src/lifecycle-error-domain.test.ts +149 -0
  140. package/src/list-ack-error-domain.test.ts +108 -0
  141. package/src/list-host-supervisors.test.ts +15 -4
  142. package/src/list-tasks-omit-default.test.ts +84 -0
  143. package/src/list-tasks-since-last.test.ts +100 -0
  144. package/src/list-tasks-since.test.ts +104 -0
  145. package/src/mcp-context-cost-http.test.ts +127 -0
  146. package/src/mcp-inflight.test.ts +92 -0
  147. package/src/mcp-inflight.ts +38 -0
  148. package/src/mcp-projects-events-http.test.ts +168 -0
  149. package/src/mcp-route-label-http.test.ts +120 -0
  150. package/src/mcp-write-network-resolution.test.ts +21 -0
  151. package/src/member-audit-network-id-http.test.ts +93 -0
  152. package/src/member-presence-http.test.ts +210 -0
  153. package/src/messages-ack-by-agent-http.test.ts +142 -0
  154. package/src/migrate-sqlite-to-pg.test.ts +47 -0
  155. package/src/migrate-sqlite-to-pg.ts +263 -0
  156. package/src/model-auth-notify-http.test.ts +181 -0
  157. package/src/model-auth-notify.ts +116 -0
  158. package/src/network-name-http.test.ts +75 -0
  159. package/src/network-quota-config.test.ts +100 -0
  160. package/src/network-rules-http.test.ts +169 -0
  161. package/src/network-rules.ts +129 -0
  162. package/src/network-scope.ts +222 -3
  163. package/src/network-token-membership-http.test.ts +186 -0
  164. package/src/node-alias-control.ts +12 -0
  165. package/src/node-attrs.test.ts +47 -2
  166. package/src/node-caller-identity-http.test.ts +1108 -0
  167. package/src/node-config-last-update.test.ts +126 -0
  168. package/src/node-config-last-update.ts +107 -0
  169. package/src/node-create-request-status-http.test.ts +105 -0
  170. package/src/node-daemon-bindings.test.ts +142 -0
  171. package/src/node-daemon-bindings.ts +135 -0
  172. package/src/node-failure-alert.test.ts +150 -0
  173. package/src/node-failure-alert.ts +177 -0
  174. package/src/node-files-transport.test.ts +350 -0
  175. package/src/node-health-codex-login.test.ts +120 -0
  176. package/src/node-health-dispatch-http.test.ts +373 -0
  177. package/src/node-health-guard-origin.test.ts +98 -0
  178. package/src/node-health-guard.ts +121 -0
  179. package/src/node-health-passthrough.test.ts +115 -0
  180. package/src/node-health-store.ts +101 -0
  181. package/src/node-id-alias.test.ts +190 -0
  182. package/src/node-identity-conflict-http.test.ts +269 -0
  183. package/src/node-identity-conflict.ts +142 -0
  184. package/src/node-identity-mismatch.test.ts +74 -0
  185. package/src/node-in-flight-tasks.ts +31 -0
  186. package/src/node-lifecycle-controllable.test.ts +64 -0
  187. package/src/node-lifecycle-controllable.ts +53 -0
  188. package/src/node-lifecycle-read-http.test.ts +257 -0
  189. package/src/node-lifecycle-read.ts +124 -0
  190. package/src/node-logs-transport.test.ts +266 -0
  191. package/src/node-peer-allowlist.test.ts +114 -0
  192. package/src/node-permissions-http.test.ts +901 -0
  193. package/src/node-permissions.ts +494 -0
  194. package/src/node-request-retention.test.ts +281 -0
  195. package/src/node-request-retention.ts +120 -0
  196. package/src/node-secret-rest-http.test.ts +190 -0
  197. package/src/node-secret-vault-inject.test.ts +132 -0
  198. package/src/node-security-write-gate.test.ts +72 -0
  199. package/src/node-serviceability.test.ts +86 -0
  200. package/src/node-serviceability.ts +124 -0
  201. package/src/node-session-control-http.test.ts +310 -0
  202. package/src/node-session-control.ts +258 -0
  203. package/src/node-skills-transport.test.ts +212 -0
  204. package/src/node-token-identity.ts +35 -0
  205. package/src/node-token-ownership.ts +51 -0
  206. package/src/node-token-privilege-http.test.ts +224 -0
  207. package/src/not-found-api-http.test.ts +67 -0
  208. package/src/observer-avatar-http.test.ts +103 -10
  209. package/src/observer-push.test.ts +76 -0
  210. package/src/opencode-catalog-report-http.test.ts +139 -0
  211. package/src/opencode-v2-catalog.test.ts +268 -0
  212. package/src/opencode-v2-catalog.ts +356 -0
  213. package/src/package-version-consistency.test.ts +25 -0
  214. package/src/parent-infer.test.ts +82 -0
  215. package/src/parent-infer.ts +110 -0
  216. package/src/parent-source-marker.test.ts +70 -0
  217. package/src/parent-source-orphan.test.ts +121 -0
  218. package/src/password-network-tokens.ts +25 -0
  219. package/src/peer-reply-atomic.test.ts +462 -0
  220. package/src/peer-reply-capability.test.ts +70 -0
  221. package/src/pg-worker.ts +87 -0
  222. package/src/poll-pacing.test.ts +74 -0
  223. package/src/poll-pacing.ts +123 -0
  224. package/src/probe-provider-error-domain.test.ts +145 -0
  225. package/src/project-dir-warn-clear-http.test.ts +132 -0
  226. package/src/project-viewer-can-http.test.ts +116 -0
  227. package/src/provider-skill-error-domain.test.ts +130 -0
  228. package/src/provider-tools-shape.test.ts +165 -0
  229. package/src/push.test.ts +20 -10
  230. package/src/push.ts +373 -9
  231. package/src/redact-tokens.test.ts +86 -0
  232. package/src/redact-tokens.ts +43 -0
  233. package/src/rejection-counters.test.ts +72 -0
  234. package/src/rejection-counters.ts +173 -0
  235. package/src/rename.ts +38 -10
  236. package/src/reply-target-derivation.test.ts +96 -0
  237. package/src/report-status-handover-capabilities-http.test.ts +124 -0
  238. package/src/report-status-host-schema.test.ts +235 -0
  239. package/src/report-status-resume-id-handover.test.ts +184 -0
  240. package/src/report-status-secret-keys.test.ts +140 -0
  241. package/src/require-explicit-test-db.ts +9 -0
  242. package/src/requirement-due-reminders-http.test.ts +620 -0
  243. package/src/requirement-due-reminders.ts +416 -0
  244. package/src/requirement-events-http.test.ts +318 -0
  245. package/src/requirement-events.test.ts +45 -0
  246. package/src/requirement-events.ts +144 -0
  247. package/src/requirement-notify.ts +165 -0
  248. package/src/requirement-participant-notify-http.test.ts +313 -0
  249. package/src/requirement-tag-ops-http.test.ts +454 -0
  250. package/src/requirement-tag-tree-http.test.ts +275 -0
  251. package/src/requirement-tag-tree.ts +127 -0
  252. package/src/requirement-tags.ts +102 -0
  253. package/src/requirements-abandoned-http.test.ts +236 -0
  254. package/src/requirements-assignee-drift.test.ts +154 -0
  255. package/src/requirements-comment-http.test.ts +174 -0
  256. package/src/requirements-completed-at-migration.test.ts +70 -0
  257. package/src/requirements-errors-mcp-http.test.ts +164 -0
  258. package/src/requirements-errors.ts +158 -0
  259. package/src/requirements-etag-http.test.ts +91 -0
  260. package/src/requirements-http.test.ts +709 -0
  261. package/src/requirements-last-event-http.test.ts +349 -0
  262. package/src/requirements-list-mcp-slim-http.test.ts +155 -0
  263. package/src/requirements-list-slim-http.test.ts +324 -0
  264. package/src/requirements-mcp.test.ts +180 -0
  265. package/src/requirements-migrate.ts +283 -0
  266. package/src/requirements-owner-strict-mcp-http.test.ts +145 -0
  267. package/src/requirements-people-http.test.ts +114 -0
  268. package/src/requirements-people-mcp-http.test.ts +231 -0
  269. package/src/requirements-people.ts +196 -0
  270. package/src/requirements-priority-lowest.test.ts +114 -0
  271. package/src/requirements-projects-network-echo.test.ts +57 -0
  272. package/src/requirements-projects-parent-http.test.ts +123 -0
  273. package/src/requirements-search-http.test.ts +182 -0
  274. package/src/requirements-search.test.ts +32 -0
  275. package/src/requirements-search.ts +145 -0
  276. package/src/requirements-seq-http.test.ts +193 -0
  277. package/src/requirements-seq-migration.test.ts +63 -0
  278. package/src/requirements-start-date.test.ts +125 -0
  279. package/src/requirements-stats-http.test.ts +357 -0
  280. package/src/requirements-stats.ts +195 -0
  281. package/src/requirements-status-participants-http.test.ts +222 -0
  282. package/src/requirements-upgrade-e2e.test.ts +126 -0
  283. package/src/requirements-upgrade-migration.test.ts +98 -0
  284. package/src/requirements.ts +2205 -0
  285. package/src/resolve-port.test.ts +57 -0
  286. package/src/resolve-port.ts +44 -0
  287. package/src/rest-alias-network-fallback-http.test.ts +123 -0
  288. package/src/rest-alias-network-fallback.test.ts +60 -0
  289. package/src/rest-alias-network-fallback.ts +65 -0
  290. package/src/rest-explicit-columns-http.test.ts +266 -0
  291. package/src/rest-identity.test.ts +130 -0
  292. package/src/rest-identity.ts +141 -0
  293. package/src/rest-projections.ts +72 -0
  294. package/src/rest-read-network-real-chain.test.ts +97 -0
  295. package/src/rest-write-network-resolution.test.ts +133 -0
  296. package/src/restart-readiness-http.test.ts +121 -0
  297. package/src/restricted-files.ts +76 -0
  298. package/src/retention-first-sweep-quiet.test.ts +31 -0
  299. package/src/retention.test.ts +100 -40
  300. package/src/retention.ts +423 -104
  301. package/src/route-callers-http.test.ts +120 -0
  302. package/src/route-timing.test.ts +218 -0
  303. package/src/route-timing.ts +262 -0
  304. package/src/rules-file-duplicate-alias.test.ts +234 -0
  305. package/src/rules-file-session-target.test.ts +207 -0
  306. package/src/rules-file-transport.test.ts +271 -0
  307. package/src/runtime-label.test.ts +22 -0
  308. package/src/runtime-label.ts +21 -0
  309. package/src/runtime-readiness.ts +90 -0
  310. package/src/schedule-agent-mcp-http.test.ts +486 -0
  311. package/src/schedule-agent.ts +252 -0
  312. package/src/schedule-starved.test.ts +92 -0
  313. package/src/schedule-starved.ts +114 -0
  314. package/src/scheduled-backoff-http.test.ts +203 -0
  315. package/src/scheduled-backoff.ts +64 -0
  316. package/src/scheduled-doorbell-nodeless-session.test.ts +134 -0
  317. package/src/scheduled-failure-backoff-2622.test.ts +145 -0
  318. package/src/scheduled-failure-code.test.ts +73 -0
  319. package/src/scheduled-failure-code.ts +105 -0
  320. package/src/scheduled-failures-http.test.ts +279 -0
  321. package/src/scheduled-failures.ts +425 -0
  322. package/src/scheduled-noprogress-backoff-2622.test.ts +163 -0
  323. package/src/scheduled-offline-backoff-probe.test.ts +56 -0
  324. package/src/scheduled-offline.test.ts +131 -0
  325. package/src/scheduled-offline.ts +66 -0
  326. package/src/scheduled-outcome-guidance-http.test.ts +139 -0
  327. package/src/scheduled-outcome-guidance.ts +9 -0
  328. package/src/scheduled-reply-unread-http.test.ts +212 -0
  329. package/src/scheduled-requirement-wake-http.test.ts +289 -0
  330. package/src/scheduled-requirement-wake.ts +125 -0
  331. package/src/scheduled-run-terminal.test.ts +290 -0
  332. package/src/scheduled-skip-blocking-task.test.ts +120 -0
  333. package/src/scheduled-skip-path-backoff-2622.test.ts +98 -0
  334. package/src/scheduled-stuck-http.test.ts +316 -0
  335. package/src/scheduled-stuck-notice-cap.test.ts +80 -0
  336. package/src/scheduled-stuck.ts +219 -0
  337. package/src/scheduled-tasks-http.test.ts +679 -0
  338. package/src/scheduled-tasks.ts +959 -0
  339. package/src/scheduled-work-outcome-http.test.ts +154 -0
  340. package/src/scheduled-work-outcome.ts +50 -0
  341. package/src/scoped-secrets.ts +167 -0
  342. package/src/secret-echo-negative-control.test.ts +118 -0
  343. package/src/send-dedup-request-id.test.ts +229 -0
  344. package/src/send-reply-agent-warning.test.ts +38 -38
  345. package/src/send-reply-alias-optional.test.ts +131 -0
  346. package/src/send-reply-attachments.test.ts +28 -7
  347. package/src/send_dedup.test.ts +54 -0
  348. package/src/send_dedup.ts +52 -6
  349. package/src/serve-error.test.ts +73 -0
  350. package/src/serve-error.ts +56 -0
  351. package/src/server.ts +4930 -377
  352. package/src/session-task-on-dispatch.ts +14 -0
  353. package/src/session-token-ownership-http.test.ts +122 -0
  354. package/src/shared/codex-inventory.ts +41 -0
  355. package/src/shared/daemon-provider-login.ts +31 -0
  356. package/src/shared/daemon-provider-snapshot.ts +52 -0
  357. package/src/shared/external-schedule-contract.ts +60 -0
  358. package/src/shared/node-name.test.ts +62 -0
  359. package/src/shared/node-name.ts +161 -0
  360. package/src/shared/probe-host-allowlist-drift.test.ts +45 -0
  361. package/src/shared/provider-application.ts +29 -0
  362. package/src/shared/provider-collection.ts +14 -0
  363. package/src/shared/provider-initialization.ts +8 -0
  364. package/src/shared/reserved-env-drift.test.ts +10 -0
  365. package/src/shared/scoped-secret-contract.ts +5 -0
  366. package/src/shared/task-content-limit-drift.test.ts +28 -0
  367. package/src/shared/task-content-limit.ts +25 -0
  368. package/src/side-thread-command-transport.test.ts +312 -0
  369. package/src/side-thread-command-transport.ts +318 -0
  370. package/src/side-thread-http-integration.test.ts +233 -0
  371. package/src/side-thread-http.ts +504 -0
  372. package/src/side-thread-production.test.ts +72 -0
  373. package/src/side-thread-production.ts +118 -0
  374. package/src/side-thread.test.ts +1067 -0
  375. package/src/side-thread.ts +2499 -0
  376. package/src/skillhub-http.test.ts +144 -0
  377. package/src/sqlite-close-checkpoint.test.ts +78 -0
  378. package/src/start-node.test.ts +265 -0
  379. package/src/start-request-error-domain.test.ts +182 -0
  380. package/src/start-skill-error-domain.test.ts +122 -0
  381. package/src/stats-versions-http.test.ts +65 -0
  382. package/src/status-alias-filter-http.test.ts +106 -0
  383. package/src/status-alias-resolver-http.test.ts +163 -0
  384. package/src/status-alias-resolver.ts +19 -0
  385. package/src/status-node-id-filter-http.test.ts +161 -0
  386. package/src/status-read-cache-http.test.ts +229 -0
  387. package/src/status-read-cache.ts +129 -0
  388. package/src/stop-delete-node.test.ts +567 -1
  389. package/src/task-access-http.test.ts +407 -0
  390. package/src/task-access.ts +420 -0
  391. package/src/task-activity.ts +60 -0
  392. package/src/task-auth-origin-http.test.ts +93 -0
  393. package/src/task-auth-origin.test.ts +24 -0
  394. package/src/task-auth-origin.ts +7 -0
  395. package/src/task-consumption.test.ts +508 -0
  396. package/src/task-diagnostic-http.test.ts +149 -0
  397. package/src/task-diagnostic.test.ts +115 -0
  398. package/src/task-diagnostic.ts +118 -0
  399. package/src/task-expiry-notice-http.test.ts +298 -0
  400. package/src/task-expiry-notice.ts +318 -0
  401. package/src/task-idempotency-mcp.test.ts +148 -0
  402. package/src/task-idempotency.test.ts +76 -0
  403. package/src/task-idempotency.ts +81 -0
  404. package/src/task-late-replies.ts +54 -0
  405. package/src/task-late-reply-http.test.ts +227 -0
  406. package/src/task-lifecycle-watcher-busy.test.ts +114 -0
  407. package/src/task-lifecycle-watcher.test.ts +209 -0
  408. package/src/task-lifecycle-watcher.ts +109 -0
  409. package/src/task-network-resolution-http.test.ts +140 -0
  410. package/src/task-not-found-error-domain.test.ts +114 -0
  411. package/src/task-offline-delivery-2668.test.ts +119 -0
  412. package/src/task-offline-delivery.ts +81 -0
  413. package/src/task-orphan-http.test.ts +287 -0
  414. package/src/task-orphan.ts +119 -0
  415. package/src/task-queue-ahead-http.test.ts +309 -0
  416. package/src/task-queue-ahead-scale.test.ts +236 -0
  417. package/src/task-queue-ahead.ts +186 -0
  418. package/src/task-rejection-log-http.test.ts +160 -0
  419. package/src/task-rejection-log.ts +61 -0
  420. package/src/task-sender-http.test.ts +143 -0
  421. package/src/task-stale-open-http.test.ts +292 -0
  422. package/src/task-stale-open.ts +103 -0
  423. package/src/tasks-pagination-http.test.ts +141 -0
  424. package/src/team-rules-status-http.test.ts +90 -0
  425. package/src/team-rules-status.test.ts +59 -0
  426. package/src/team-rules-status.ts +72 -0
  427. package/src/tmux-allowlist.test.ts +48 -0
  428. package/src/tool-audience-http.test.ts +248 -0
  429. package/src/tool-audience.ts +127 -0
  430. package/src/tools-list-json-schema.test.ts +94 -0
  431. package/src/tools.ts +4314 -392
  432. package/src/update-node-config-error-domain.test.ts +107 -0
  433. package/src/uploads-http.test.ts +6 -4
  434. package/src/uploads.ts +23 -4
  435. package/src/user-avatar-http.test.ts +74 -0
  436. package/src/user-avatar-image.ts +160 -0
  437. package/src/user-avatar-migration.test.ts +25 -0
  438. package/src/user-avatar-upload-http.test.ts +353 -0
  439. package/src/user-inbox-by-agent-http.test.ts +189 -0
  440. package/src/user-inbox-netid-notnull.test.ts +122 -0
  441. package/src/user-inbox-read-http.test.ts +223 -0
  442. package/src/user-inbox-schema.test.ts +54 -0
  443. package/src/version-stats.test.ts +66 -0
  444. package/src/version-stats.ts +109 -0
@@ -0,0 +1,356 @@
1
+ // Hub authorization for a native OpenCode V2 catalog read.
2
+ //
3
+ // The caller names a daemon and a child node. Identity, generation, and the
4
+ // project directory come from Hub rows. The queued payload has no URL,
5
+ // authorization, settings, headers, or body. The daemon reads its own
6
+ // already-running loopback and acks a whitelist snapshot.
7
+ //
8
+ // `status: "pending"` means the read was authorized and stored. It does not
9
+ // mean a daemon received the doorbell or produced a snapshot. Only
10
+ // `status: "ready"` is a snapshot, and that snapshot stays completeness
11
+ // unknown / invocation unverified.
12
+
13
+ import { posix, win32 } from "node:path";
14
+ import { z } from "zod/v4";
15
+ import { db, uuidv4 } from "./db.js";
16
+ import { getUserNetworkRole } from "./auth.js";
17
+
18
+ const TTL_MS = 60_000;
19
+ const MAX_PENDING = 100;
20
+ const SECRET = /^(sk-|gh[pousr]_|github_pat_|xox[baprs]-|AKIA|AIza|ya29\.|glpat-)/i;
21
+
22
+ export const CATALOG_ERROR_CODES = [
23
+ "invalid_target", "unauthorized", "unavailable", "invalid_response", "scope_mismatch", "too_large",
24
+ // 2026-10-31 —— 两格新增,都要与 agent-node 侧的手工联合类型同步:
25
+ // "unexpected" 兜底不许点名因果(原先把非目录错误一律报 "unavailable")
26
+ // "directory_not_ascii" 传输层结构性限制:OpenCode 只认 header,而 header 运不了非 ASCII
27
+ "unexpected", "directory_not_ascii",
28
+ ] as const;
29
+ export type CatalogErrorCode = (typeof CATALOG_ERROR_CODES)[number];
30
+
31
+ const identifier = z.string().min(1).max(512).refine(value => !/[\s\u0000-\u001f\u007f]/.test(value) && !SECRET.test(value));
32
+ const CONTROL = /[\u0000-\u001f\u007f]/;
33
+ const WINDOWS_DRIVE = /^[A-Za-z]:[\\/]/;
34
+
35
+ /** Absolute in the path's own format. Hub `path.resolve` is not used: on a
36
+ * POSIX Hub it treats `C:\project` as a relative path under the process cwd. */
37
+ function windowsStrictAbsolute(value: string): boolean {
38
+ if (!WINDOWS_DRIVE.test(value)) return false;
39
+ const parts = value.slice(2).split(/[\\/]/);
40
+ if (parts[0] !== "" || parts.length < 2) return false;
41
+ return parts.slice(1).every(part => part !== "" && part !== "." && part !== "..");
42
+ }
43
+
44
+ export function strictNativeAbsoluteDirectory(value: string): boolean {
45
+ if (value.length < 1 || value.length > 1024 || CONTROL.test(value)) return false;
46
+ if (WINDOWS_DRIVE.test(value)) return windowsStrictAbsolute(value);
47
+ if (value.startsWith("/")) return posix.resolve(value) === value;
48
+ return false;
49
+ }
50
+
51
+ function tildeWorkdir(value: string): boolean {
52
+ const trimmed = value.trim();
53
+ return trimmed === "~" || trimmed.startsWith("~/") || trimmed.startsWith("~\\");
54
+ }
55
+
56
+ /** Compare a stored create workdir with the directory the daemon reported.
57
+ * Windows keys ignore slash style and case. POSIX keys are lexical (`..` and
58
+ * a trailing slash collapse) and are not realpath'd — Hub does not see the
59
+ * daemon disk. A `~` / `~/…` workdir has no Hub-side home to expand; a
60
+ * native-absolute report is accepted because the daemon already refused the
61
+ * read unless that path is the endpoint it owns. A compromised daemon can
62
+ * name another absolute path for a tilde row, same as a null workdir. */
63
+ export function catalogDirectoriesMatch(stored: string, reported: string): boolean {
64
+ if (!strictNativeAbsoluteDirectory(reported)) return false;
65
+ const storedTrim = stored.trim();
66
+ if (tildeWorkdir(storedTrim)) return true;
67
+ const storedWindows = WINDOWS_DRIVE.test(storedTrim);
68
+ const reportedWindows = WINDOWS_DRIVE.test(reported);
69
+ if (storedWindows !== reportedWindows) return false;
70
+ if (storedWindows) {
71
+ const left = win32.resolve(storedTrim);
72
+ const right = win32.resolve(reported);
73
+ return /^[A-Za-z]:\\/.test(left) && left.toLowerCase() === right.toLowerCase();
74
+ }
75
+ if (storedTrim.startsWith("/") && reported.startsWith("/")) return posix.resolve(storedTrim) === posix.resolve(reported);
76
+ return false;
77
+ }
78
+
79
+ const directoryText = z.string().min(1).max(1024).refine(strictNativeAbsoluteDirectory);
80
+
81
+ export const opencodeCatalogSnapshotSchema = z.object({
82
+ scope: z.object({
83
+ networkId: z.string().min(1).max(200),
84
+ daemonId: z.string().min(1).max(200),
85
+ directory: directoryText,
86
+ }).strict(),
87
+ source: z.literal("opencode-v2-api"),
88
+ state: z.literal("snapshot"),
89
+ invocationVerified: z.literal(false),
90
+ completeness: z.literal("unknown"),
91
+ observedAt: z.string().regex(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?Z$/),
92
+ providers: z.array(z.object({
93
+ id: identifier,
94
+ activation: z.enum(["auto", "enabled", "disabled"]),
95
+ }).strict()).max(20_000),
96
+ models: z.array(z.object({
97
+ providerId: identifier,
98
+ id: identifier,
99
+ }).strict()).max(20_000),
100
+ defaultModel: z.object({ providerId: identifier, id: identifier }).strict().nullable(),
101
+ }).strict();
102
+
103
+ export type OpenCodeCatalogSnapshotWire = z.infer<typeof opencodeCatalogSnapshotSchema>;
104
+
105
+ export const opencodeCatalogAckSchema = z.object({
106
+ request_id: z.string().min(1).max(200),
107
+ error: z.enum(CATALOG_ERROR_CODES).optional(),
108
+ snapshot: opencodeCatalogSnapshotSchema.optional(),
109
+ }).strict();
110
+
111
+ interface PendingCatalogRead {
112
+ requestId: string;
113
+ daemonNodeId: string;
114
+ daemonAlias: string;
115
+ networkId: string;
116
+ nodeId: string;
117
+ alias: string;
118
+ directory: string | null;
119
+ expiresAt: number;
120
+ taken: boolean;
121
+ }
122
+
123
+ export interface StoredCatalogRead {
124
+ requestId: string;
125
+ networkId: string;
126
+ daemonNodeId: string;
127
+ nodeId: string;
128
+ status: "pending" | "ready" | "failed" | "expired";
129
+ error?: CatalogErrorCode;
130
+ snapshot?: OpenCodeCatalogSnapshotWire;
131
+ expiresAt: number;
132
+ }
133
+
134
+ const pending = new Map<string, PendingCatalogRead>();
135
+ const stored = new Map<string, StoredCatalogRead>();
136
+
137
+ export function resetOpenCodeCatalogForTest(): void {
138
+ pending.clear();
139
+ stored.clear();
140
+ }
141
+
142
+ export function expireOpenCodeCatalogForTest(requestId: string): void {
143
+ // Just past the read deadline, still inside the retention window. Setting
144
+ // the deadline to 0 would also drop the stored row and look like not_found.
145
+ const expiredAt = Date.now() - 1;
146
+ const row = pending.get(requestId);
147
+ if (row) row.expiresAt = expiredAt;
148
+ const result = stored.get(requestId);
149
+ if (result) result.expiresAt = expiredAt;
150
+ }
151
+
152
+ function childNodeId(requestId: string): string | null {
153
+ return requestId.startsWith("cr_") ? `node_${requestId.slice(3)}` : null;
154
+ }
155
+
156
+ function supervisorRole(snapshot: string | null): boolean {
157
+ if (!snapshot) return false;
158
+ try {
159
+ const parsed = JSON.parse(snapshot) as { role?: unknown };
160
+ return parsed.role === "host_supervisor";
161
+ } catch {
162
+ return false;
163
+ }
164
+ }
165
+
166
+ function v2Flags(flagsJson: string): boolean {
167
+ try {
168
+ const flags = JSON.parse(flagsJson) as { opencodeGeneration?: unknown; opencodeUnsafeTools?: unknown };
169
+ return flags.opencodeGeneration === "v2" && flags.opencodeUnsafeTools === true;
170
+ } catch {
171
+ return false;
172
+ }
173
+ }
174
+
175
+ export interface QueueCatalogInput {
176
+ callerUserId: string | null;
177
+ callerIsNode: boolean;
178
+ networkId: string | null;
179
+ daemonNodeId: string;
180
+ nodeId: string;
181
+ }
182
+
183
+ function evictExpired(now = Date.now()): void {
184
+ for (const [id, row] of pending) {
185
+ if (now > row.expiresAt) pending.delete(id);
186
+ }
187
+ for (const [id, row] of stored) {
188
+ if (row.status === "pending" && now > row.expiresAt) row.status = "expired";
189
+ if (now > row.expiresAt + TTL_MS) stored.delete(id);
190
+ }
191
+ }
192
+
193
+ export function queueOpenCodeCatalogRead(input: QueueCatalogInput):
194
+ | { ok: true; request_id: string; status: "pending"; daemon_alias: string; network_id: string }
195
+ | { ok: false; error: string } {
196
+ evictExpired();
197
+ if (input.callerIsNode) return { ok: false, error: "user_token_required" };
198
+ if (!input.callerUserId) return { ok: false, error: "auth_required" };
199
+ if (!input.networkId) return { ok: false, error: "network_id_required" };
200
+ const role = getUserNetworkRole(input.callerUserId, input.networkId);
201
+ if (!role) return { ok: false, error: "access_denied" };
202
+ if (pending.size >= MAX_PENDING) return { ok: false, error: "catalog_busy" };
203
+
204
+ const daemon = db.get<{ node_id: string; alias: string; config_snapshot: string | null }>(
205
+ `SELECT node_id, alias, config_snapshot FROM nodes WHERE node_id = ?1 AND network_id = ?2`,
206
+ input.daemonNodeId, input.networkId,
207
+ );
208
+ if (!daemon) return { ok: false, error: "daemon_not_found" };
209
+ if (!supervisorRole(daemon.config_snapshot)) return { ok: false, error: "daemon_not_supervisor" };
210
+
211
+ const child = db.get<{ node_id: string }>(
212
+ `SELECT node_id FROM nodes WHERE node_id = ?1 AND network_id = ?2`,
213
+ input.nodeId, input.networkId,
214
+ );
215
+ if (!child) return { ok: false, error: "node_not_found" };
216
+
217
+ const creates = db.all<{
218
+ request_id: string; daemon_node_id: string; child_name: string; runtime: string;
219
+ flags_json: string; workdir: string | null; status: string;
220
+ }>(
221
+ `SELECT request_id, daemon_node_id, child_name, runtime, flags_json, workdir, status
222
+ FROM node_create_requests
223
+ WHERE network_id = ?1 AND daemon_node_id = ?2 AND status IN ('succeeded', 'delivered')`,
224
+ input.networkId, input.daemonNodeId,
225
+ );
226
+ const owned = creates.filter(row => childNodeId(row.request_id) === input.nodeId && row.daemon_node_id === input.daemonNodeId);
227
+ if (owned.length !== 1) return { ok: false, error: "node_not_found" };
228
+ const row = owned[0]!;
229
+ if (row.runtime !== "opencode-cli" || !v2Flags(row.flags_json)) return { ok: false, error: "not_opencode_v2" };
230
+
231
+ const requestId = `cat_${uuidv4()}`;
232
+ const directory = typeof row.workdir === "string" && row.workdir.length > 0 ? row.workdir : null;
233
+ const record: PendingCatalogRead = {
234
+ requestId,
235
+ daemonNodeId: daemon.node_id,
236
+ daemonAlias: daemon.alias,
237
+ networkId: input.networkId,
238
+ nodeId: input.nodeId,
239
+ alias: row.child_name,
240
+ directory,
241
+ expiresAt: Date.now() + TTL_MS,
242
+ taken: false,
243
+ };
244
+ pending.set(requestId, record);
245
+ stored.set(requestId, {
246
+ requestId,
247
+ networkId: input.networkId,
248
+ daemonNodeId: daemon.node_id,
249
+ nodeId: input.nodeId,
250
+ status: "pending",
251
+ expiresAt: record.expiresAt,
252
+ });
253
+ return { ok: true, request_id: requestId, status: "pending", daemon_alias: daemon.alias, network_id: input.networkId };
254
+ }
255
+
256
+ export function takeOpenCodeCatalogRequest(requestId: string, daemonNodeId: string):
257
+ | { ok: true; request_id: string; node_id: string; alias: string; directory: string | null; scope: { networkId: string; daemonId: string } }
258
+ | { ok: false; error: "catalog_request_unavailable" } {
259
+ const row = pending.get(requestId);
260
+ if (!row || row.daemonNodeId !== daemonNodeId || row.taken) return { ok: false, error: "catalog_request_unavailable" };
261
+ if (Date.now() > row.expiresAt) {
262
+ row.taken = true;
263
+ const result = stored.get(requestId);
264
+ if (result && result.status === "pending") result.status = "expired";
265
+ return { ok: false, error: "catalog_request_unavailable" };
266
+ }
267
+ row.taken = true;
268
+ return {
269
+ ok: true,
270
+ request_id: row.requestId,
271
+ node_id: row.nodeId,
272
+ alias: row.alias,
273
+ directory: row.directory,
274
+ scope: { networkId: row.networkId, daemonId: row.daemonNodeId },
275
+ };
276
+ }
277
+
278
+ function consistent(snapshot: OpenCodeCatalogSnapshotWire): boolean {
279
+ const providers = new Set<string>();
280
+ for (const row of snapshot.providers) {
281
+ if (providers.has(row.id)) return false;
282
+ providers.add(row.id);
283
+ }
284
+ const models = new Set<string>();
285
+ for (const row of snapshot.models) {
286
+ if (!providers.has(row.providerId)) return false;
287
+ const key = JSON.stringify([row.providerId, row.id]);
288
+ if (models.has(key)) return false;
289
+ models.add(key);
290
+ }
291
+ if (snapshot.defaultModel && !models.has(JSON.stringify([snapshot.defaultModel.providerId, snapshot.defaultModel.id]))) return false;
292
+ return Buffer.byteLength(JSON.stringify(snapshot), "utf8") <= 2 * 1024 * 1024;
293
+ }
294
+
295
+ export function ackOpenCodeCatalog(daemonNodeId: string, body: unknown):
296
+ | { ok: true; status: "ready" | "failed"; error?: CatalogErrorCode }
297
+ | { ok: false; error: "catalog_request_unavailable" | "invalid_ack" } {
298
+ const parsed = opencodeCatalogAckSchema.safeParse(body);
299
+ if (!parsed.success) return { ok: false, error: "invalid_ack" };
300
+ const ack = parsed.data;
301
+ const hasSnapshot = ack.snapshot !== undefined;
302
+ const hasError = ack.error !== undefined;
303
+ if (hasSnapshot === hasError) return { ok: false, error: "invalid_ack" };
304
+ const row = pending.get(ack.request_id);
305
+ const result = stored.get(ack.request_id);
306
+ if (!row || !result || row.daemonNodeId !== daemonNodeId || !row.taken) {
307
+ return { ok: false, error: "catalog_request_unavailable" };
308
+ }
309
+ if (Date.now() > row.expiresAt || result.status !== "pending") {
310
+ if (result.status === "pending") result.status = "expired";
311
+ return { ok: false, error: "catalog_request_unavailable" };
312
+ }
313
+ if (ack.error) {
314
+ result.status = "failed";
315
+ result.error = ack.error;
316
+ return { ok: true, status: "failed", error: ack.error };
317
+ }
318
+ const snapshot = ack.snapshot!;
319
+ // A stored workdir must match. A null workdir (legacy create) has no
320
+ // hub-side path to compare; the daemon binds that read to the project
321
+ // directory it already owns. Hub does not see that filesystem.
322
+ const directoryOk = row.directory ? catalogDirectoriesMatch(row.directory, snapshot.scope.directory) : true;
323
+ if (snapshot.scope.networkId !== row.networkId || snapshot.scope.daemonId !== row.daemonNodeId || !directoryOk || !consistent(snapshot)) {
324
+ result.status = "failed";
325
+ result.error = "invalid_response";
326
+ return { ok: true, status: "failed", error: "invalid_response" };
327
+ }
328
+ result.status = "ready";
329
+ result.snapshot = snapshot;
330
+ return { ok: true, status: "ready" };
331
+ }
332
+
333
+ export function getOpenCodeCatalogResult(input: {
334
+ callerUserId: string | null;
335
+ callerIsNode: boolean;
336
+ networkId: string | null;
337
+ requestId: string;
338
+ }):
339
+ | { ok: true; status: "pending"; request_id: string }
340
+ | { ok: true; status: "ready"; request_id: string; snapshot: OpenCodeCatalogSnapshotWire }
341
+ | { ok: false; status?: "failed" | "expired"; error: string; request_id?: string } {
342
+ if (input.callerIsNode) return { ok: false, error: "user_token_required" };
343
+ if (!input.callerUserId) return { ok: false, error: "auth_required" };
344
+ if (!input.networkId) return { ok: false, error: "network_id_required" };
345
+ if (!getUserNetworkRole(input.callerUserId, input.networkId)) return { ok: false, error: "access_denied" };
346
+ evictExpired();
347
+ const result = stored.get(input.requestId);
348
+ if (!result || result.networkId !== input.networkId) return { ok: false, error: "not_found" };
349
+ if (result.status === "pending" && Date.now() > result.expiresAt) result.status = "expired";
350
+ if (result.status === "pending") return { ok: true, status: "pending", request_id: result.requestId };
351
+ if (result.status === "ready" && result.snapshot) {
352
+ return { ok: true, status: "ready", request_id: result.requestId, snapshot: result.snapshot };
353
+ }
354
+ if (result.status === "expired") return { ok: false, status: "expired", error: "unavailable", request_id: result.requestId };
355
+ return { ok: false, status: "failed", error: result.error || "unavailable", request_id: result.requestId };
356
+ }
@@ -0,0 +1,25 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { readFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+
5
+ type PackageManifest = { version: string };
6
+ type PackageLock = {
7
+ version: string;
8
+ packages: { "": { version: string } };
9
+ };
10
+
11
+ const readJson = <T>(name: string): T =>
12
+ JSON.parse(readFileSync(join(import.meta.dir, "..", name), "utf8")) as T;
13
+
14
+ describe("server package version consistency", () => {
15
+ const manifest = readJson<PackageManifest>("package.json");
16
+ const lock = readJson<PackageLock>("package-lock.json");
17
+
18
+ test("package-lock top-level version matches package.json", () => {
19
+ expect(lock.version).toBe(manifest.version);
20
+ });
21
+
22
+ test("package-lock root package version matches package.json", () => {
23
+ expect(lock.packages[""].version).toBe(manifest.version);
24
+ });
25
+ });
@@ -0,0 +1,82 @@
1
+ // #669 —— 父任务推断收窄的判据:**候选唯一 + 在窗口内**,且每一种拒绝都要能被数出来。
2
+ //
3
+ // 为什么这三件事要一起测:
4
+ // 收窄是「减少推断」,而减少在派发日志里不留痕(任务照常派出,只是没有父)。
5
+ // 没有 rejected 计数时,「收窄生效」与「收窄没写对」同形——两者的 7 天失败率都会降。
6
+ //
7
+ // 为什么「年龄未知」要算拒绝而不是放行:
8
+ // 这条约束的全部价值是「刚派不久」,而 age 未知时无法证明它成立。
9
+ // 放行会让这一条在最需要它的输入上失效。
10
+ import { test, beforeEach } from "node:test";
11
+ import assert from "node:assert/strict";
12
+ import {
13
+ INFER_WINDOW_MS,
14
+ __resetParentInferForTest,
15
+ decideParentInference,
16
+ noteInferAccepted,
17
+ noteInferRejected,
18
+ parentInferCounters,
19
+ } from "./parent-infer.js";
20
+
21
+ const NOW = 1_800_000_000_000;
22
+
23
+ beforeEach(() => __resetParentInferForTest());
24
+
25
+ test("唯一候选且在窗口内 ⇒ 推断到它", () => {
26
+ const r = decideParentInference([{ task_id: "t1", created_at_ms: NOW - 60_000 }], NOW);
27
+ assert.equal(r.ok, true);
28
+ assert.equal(r.ok && r.task_id, "t1");
29
+ });
30
+
31
+ test("多个候选 ⇒ 不推断(挑最近一条正是挂错的来源)", () => {
32
+ const r = decideParentInference([
33
+ { task_id: "new", created_at_ms: NOW - 10_000 },
34
+ { task_id: "old", created_at_ms: NOW - 500_000 },
35
+ ], NOW);
36
+ assert.equal(r.ok, false);
37
+ // 关键:**不是**退化成「取最新那条」
38
+ assert.equal(!r.ok && r.rejection.reason, "ambiguous_candidates");
39
+ assert.equal(!r.ok && r.rejection.candidates, 2);
40
+ });
41
+
42
+ test("唯一候选但太旧 ⇒ 不推断(那是排在后面还没轮到的)", () => {
43
+ const r = decideParentInference(
44
+ [{ task_id: "t1", created_at_ms: NOW - INFER_WINDOW_MS - 1 }], NOW);
45
+ assert.equal(r.ok, false);
46
+ assert.equal(!r.ok && r.rejection.reason, "candidate_too_old");
47
+ });
48
+
49
+ test("窗口边界:正好等于窗口 ⇒ 仍然推断(<= 而非 <)", () => {
50
+ const r = decideParentInference(
51
+ [{ task_id: "t1", created_at_ms: NOW - INFER_WINDOW_MS }], NOW);
52
+ assert.equal(r.ok, true);
53
+ });
54
+
55
+ test("年龄未知 ⇒ 不推断(无法证明「刚派不久」,而那是这条约束的全部价值)", () => {
56
+ const r = decideParentInference([{ task_id: "t1", created_at_ms: null }], NOW);
57
+ assert.equal(r.ok, false);
58
+ assert.equal(!r.ok && r.rejection.reason, "candidate_too_old");
59
+ assert.equal(!r.ok && r.rejection.age_ms, null);
60
+ });
61
+
62
+ test("没有候选 ⇒ 也是 ok:false,但 candidates=0(调用方据此决定不计数)", () => {
63
+ const r = decideParentInference([], NOW);
64
+ assert.equal(r.ok, false);
65
+ assert.equal(!r.ok && r.rejection.candidates, 0);
66
+ // 「没有要接的任务」是常态,不是拒绝;把它记成拒绝会让分母虚高。
67
+ });
68
+
69
+ test("计数:accepted 与两种 rejected 分开,且窗口值随快照给出", () => {
70
+ noteInferAccepted();
71
+ noteInferRejected({ reason: "ambiguous_candidates", candidates: 2, age_ms: 1000 });
72
+ noteInferRejected({ reason: "candidate_too_old", candidates: 1, age_ms: 999999 });
73
+ noteInferRejected({ reason: "candidate_too_old", candidates: 1, age_ms: 999999 });
74
+ const c = parentInferCounters();
75
+ assert.equal(c.accepted, 1);
76
+ assert.equal(c.rejected_ambiguous, 1);
77
+ assert.equal(c.rejected_too_old, 2);
78
+ assert.equal(c.window_ms, INFER_WINDOW_MS);
79
+ assert.deepEqual(Object.keys(c).sort(), [
80
+ "accepted", "rejected_ambiguous", "rejected_too_old", "since", "window_ms",
81
+ ]);
82
+ });
@@ -0,0 +1,110 @@
1
+ // #669 —— 父任务**推断**的收窄:从「取最近一条 delivered」改成「候选唯一且在窗口内」。
2
+ //
3
+ // ## 为什么收窄,而不是取消
4
+ //
5
+ // 生产实测(近 7 天,`meta_json.parent_source`):
6
+ //
7
+ // inferred 795 条(78% 的有父任务派发靠推断)
8
+ // explicit 222 条
9
+ //
10
+ // inferred 非正常收尾 48/795 = **6.0%**(expired 43 + failed 17 + cancelled 5 里与 expired 合并计)
11
+ // explicit 非正常收尾 1/222 = **0.5%**
12
+ //
13
+ // ⇒ 取消会让 795 条/周失去父链(不可接受);但 12 倍的失败率说明它确实在挂错父任务
14
+ // (子任务回复提前关掉那条还没开始的 delivered)。
15
+ //
16
+ // ## 收窄的两条约束
17
+ //
18
+ // ① **候选必须唯一**:该节点名下 `delivered` 的条数 == 1。多于一条时无法判断
19
+ // 「你要接的是哪一条」,而挑最近一条正是挂错的来源。
20
+ // ② **必须在窗口内**:那条 delivered 的 `created_at` 距今 ≤ INFER_WINDOW_MS。
21
+ // 太旧的 delivered 更可能是「排在后面还没轮到」的,而不是「刚派给我、我正在做」的。
22
+ //
23
+ // 两个常量都可改;改完的效果由 `inferred_rejected` 计数与 7 天后的失败率对比来读。
24
+ //
25
+ // ## 为什么每一条拒绝都要计数
26
+ //
27
+ // 收窄是**减少**推断,而「减少」在派发日志里不留痕:任务照常派出,只是没有父。
28
+ // 没有计数时,「收窄了多少」与「收窄没生效」同形——两者的 7 天失败率都会下降。
29
+
30
+ export const INFER_WINDOW_MS = 10 * 60_000;
31
+
32
+ export interface InferRejection {
33
+ /** 被拒绝的原因:候选不唯一 / 候选太旧 */
34
+ reason: "ambiguous_candidates" | "candidate_too_old";
35
+ /** 候选条数(不唯一时 >1;太旧时 ==1) */
36
+ candidates: number;
37
+ /** 最近那条候选的年龄(毫秒,未知时 null) */
38
+ age_ms: number | null;
39
+ }
40
+
41
+ const counters = {
42
+ accepted: 0,
43
+ rejected_ambiguous: 0,
44
+ rejected_too_old: 0,
45
+ since: new Date().toISOString(),
46
+ };
47
+
48
+ export function noteInferAccepted(): void {
49
+ counters.accepted += 1;
50
+ }
51
+
52
+ export function noteInferRejected(r: InferRejection): void {
53
+ if (r.reason === "ambiguous_candidates") counters.rejected_ambiguous += 1;
54
+ else counters.rejected_too_old += 1;
55
+ }
56
+
57
+ export interface InferCounters {
58
+ since: string;
59
+ /** 推断成功挂上父任务的次数 */
60
+ accepted: number;
61
+ /** 因候选不唯一而放弃推断 */
62
+ rejected_ambiguous: number;
63
+ /** 因候选太旧而放弃推断 */
64
+ rejected_too_old: number;
65
+ window_ms: number;
66
+ }
67
+
68
+ export function parentInferCounters(): InferCounters {
69
+ return {
70
+ since: counters.since,
71
+ accepted: counters.accepted,
72
+ rejected_ambiguous: counters.rejected_ambiguous,
73
+ rejected_too_old: counters.rejected_too_old,
74
+ window_ms: INFER_WINDOW_MS,
75
+ };
76
+ }
77
+
78
+ /** 裁定:候选列表(按 created_at DESC 排好)+ 现在的时间 ⇒ 是否推断、以及为什么。 */
79
+ export function decideParentInference(
80
+ candidates: Array<{ task_id: string; created_at_ms: number | null }>,
81
+ now: number,
82
+ windowMs: number = INFER_WINDOW_MS,
83
+ ): { ok: true; task_id: string } | { ok: false; rejection: InferRejection } {
84
+ if (candidates.length === 0) {
85
+ // 没有候选不是「拒绝」,是「本来就不该推断」—— 由调用方决定要不要记。
86
+ return { ok: false, rejection: { reason: "ambiguous_candidates", candidates: 0, age_ms: null } };
87
+ }
88
+ if (candidates.length > 1) {
89
+ const newest = candidates[0]?.created_at_ms ?? null;
90
+ return { ok: false, rejection: {
91
+ reason: "ambiguous_candidates", candidates: candidates.length,
92
+ age_ms: newest === null ? null : Math.max(0, now - newest),
93
+ } };
94
+ }
95
+ const only = candidates[0]!;
96
+ const age = only.created_at_ms === null ? null : Math.max(0, now - only.created_at_ms);
97
+ // 年龄未知时**不推断**:无法证明它「刚派不久」,而正是这个条件在防挂错。
98
+ if (age === null || age > windowMs) {
99
+ return { ok: false, rejection: { reason: "candidate_too_old", candidates: 1, age_ms: age } };
100
+ }
101
+ return { ok: true, task_id: only.task_id };
102
+ }
103
+
104
+ /** 只在测试里用。 */
105
+ export function __resetParentInferForTest(): void {
106
+ counters.accepted = 0;
107
+ counters.rejected_ambiguous = 0;
108
+ counters.rejected_too_old = 0;
109
+ counters.since = new Date().toISOString();
110
+ }
@@ -0,0 +1,70 @@
1
+ // #669 —— parent_task_id 的来源必须可区分(显式 / 推断)。
2
+ //
3
+ // 没有这个标记时,那张卡要求的前置统计做不出来:tasks 表只存 parent_task_id,
4
+ // 不记它是怎么来的(实测近 7 天 949 条里 0 条可区分)。
5
+ //
6
+ // 这里不测完整派发链路,只钉住「来源判定 + 写进 meta」这一段的行为:
7
+ // · 显式带了 parent_task_id → parent_source = "explicit"
8
+ // · 没带但被推断命中最近 delivered → parent_source = "inferred"
9
+ // · 两者都没有 → meta 里没有 parent_source
10
+ import { describe, expect, test } from "bun:test";
11
+ import { readFileSync } from "node:fs";
12
+
13
+ const src = readFileSync(new URL("./tools.ts", import.meta.url), "utf8");
14
+
15
+ describe("#669 parent source marker", () => {
16
+ test("显式 parent 记为 explicit,推断命中时改写为 inferred", () => {
17
+ expect(src).toContain('let parentSource: "explicit" | "inferred" | null = parentIn ? "explicit" : null;');
18
+ // #669 收窄之后,推断不再是「取最近一条」,而是「裁定通过才认」。
19
+ // 断言从「命中最近一条就改写」改成「裁定 ok 才改写」,并且配一条否定断言:
20
+ // 那条 SQL 不能退回 `LIMIT 1` —— 退回之后裁定拿不到候选条数,
21
+ // 「候选唯一」这条约束会静默失效,而它失效时测试仍然全绿(拿到的永远是一条)。
22
+ const block = src.slice(src.indexOf("const verdict = decideParentInference("),
23
+ src.indexOf("// #669 —— 把来源写进 meta"));
24
+ expect(block).toContain("if (verdict.ok)");
25
+ expect(block).toContain('parentSource = "inferred"');
26
+ expect(block).toContain("noteInferAccepted()");
27
+ expect(block).toContain("noteInferRejected(verdict.rejection)");
28
+ });
29
+
30
+ // 分成独立一条,而不是塞进上一条:「候选唯一」这条约束的见证是 LIMIT,
31
+ // 「裁定通过才改写」的见证是 verdict.ok。两者放在同一个 test 里时,
32
+ // 任一被破都只让同一条红 —— 红的集合相同,归因就得靠读行号。
33
+ // 独立成条之后,「只破 LIMIT」只红这一条,「只破 verdict」只红上一条。
34
+ test("取候选必须看得到「不止一条」—— LIMIT 1 会让「候选唯一」静默失效", () => {
35
+ const sqlBlock = src.slice(src.indexOf("SELECT task_id, created_at FROM tasks WHERE to_name"),
36
+ src.indexOf("const cands = db.all"));
37
+ expect(sqlBlock).toContain("LIMIT 5");
38
+ expect(sqlBlock).not.toContain("LIMIT 1");
39
+ });
40
+
41
+ test("来源只在确实有 parent 时写进 meta,且序列化失败不影响派发", () => {
42
+ const block = src.slice(src.indexOf("let metaJsonWithParent = metaJson;"), src.indexOf("// round5 F2 fix"));
43
+ expect(block).toContain("if (parentSource && parentTaskId)");
44
+ expect(block).toContain("try {");
45
+ expect(block).toContain("parent_source: parentSource");
46
+ expect(block).toContain("catch {}");
47
+ });
48
+
49
+ test("两条 INSERT(inbox / tasks)都用合并后的 meta", () => {
50
+ const inserts = src.split("\n").filter((l) => l.includes("targetAlias, priority, task") || l.includes("effectiveNetId ?? null, parentTaskId"));
51
+ expect(inserts.some((l) => l.includes("metaJsonWithParent"))).toBe(true);
52
+ });
53
+
54
+ // 这条原本断言「REST 里根本没有 parent_source」——理由是「REST 不走推断,
55
+ // 不要造第二真相」。方向对,但结论错了一半:REST 确实**不该推断**,
56
+ // 可它建的子任务同样是显式父子关系,不标就会被统计漏掉。
57
+ //
58
+ // 实测(2026-10-29,.195 上线后 90 分钟):3 条带 parent 的任务全部走 REST、
59
+ // 全部没有 parent_source。而 MCP 那条路是标的 ⇒ 分母只含 MCP,
60
+ // explicit 占比会被系统性压低。#669 要统计的正是这个比例。
61
+ test("REST /api/task 标「显式」,但不推断", () => {
62
+ const rest = readFileSync(new URL("./server.ts", import.meta.url), "utf8");
63
+ expect(rest).toContain("body.parent_task_id ?? null");
64
+ expect(rest).toContain('parent_source: "explicit"');
65
+ // 不能出现第二份推断:REST 里没有「找最近 delivered」这种 SQL。
66
+ const restBlock = rest.slice(rest.indexOf("const metaWithParent"), rest.indexOf("const metaWithParent") + 400);
67
+ expect(restBlock.toLowerCase()).not.toContain("delivered");
68
+ expect(rest).not.toContain('parentSource = "inferred"');
69
+ });
70
+ });