@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.
- package/README.md +130 -10
- package/bin/commhub.ts +99 -11
- package/package.json +7 -7
- package/src/ack-create-request-transport.test.ts +182 -0
- package/src/ack-create-request.test.ts +374 -0
- package/src/admin-delete-network-http.test.ts +228 -0
- package/src/admin-networks-http.test.ts +88 -0
- package/src/adoption-candidates-http.test.ts +137 -0
- package/src/adoption-candidates.ts +158 -0
- package/src/agent-access-batch.test.ts +210 -0
- package/src/agent-access.ts +487 -0
- package/src/agent-acl-groups-http.test.ts +247 -0
- package/src/agent-acl-http.test.ts +659 -0
- package/src/agent-acl-slice3-http.test.ts +267 -0
- package/src/agent-department-http.test.ts +215 -0
- package/src/agent-groups-perf.test.ts +223 -0
- package/src/agent-notice.ts +48 -0
- package/src/agent-team-whoami-http.test.ts +98 -0
- package/src/agent-teams-http.test.ts +330 -0
- package/src/agent-teams.ts +244 -0
- package/src/alias-baseline-2571.test.ts +162 -0
- package/src/alias-baseline.ts +113 -0
- package/src/alias-filter.test.ts +72 -0
- package/src/alias-filter.ts +42 -0
- package/src/api-host-supervisors-can-create-nodes.test.ts +350 -0
- package/src/api-host-supervisors-fallback.test.ts +271 -0
- package/src/api-host-supervisors-runtime-readiness.test.ts +195 -0
- package/src/api-nodes-shape.test.ts +279 -0
- package/src/auth-password-change-cli-tokens-http.test.ts +423 -0
- package/src/auth-sessions-http.test.ts +250 -0
- package/src/auth-validate.test.ts +5 -1
- package/src/auth-weak-password-login.test.ts +176 -0
- package/src/auth.ts +611 -51
- package/src/avatar-validate.test.ts +163 -0
- package/src/avatar-validate.ts +103 -0
- package/src/backfill-node-ids-2664.test.ts +128 -0
- package/src/binding-generation-http.test.ts +121 -0
- package/src/blocked-exit-on-reply.test.ts +122 -0
- package/src/boot-side-effect.test.ts +124 -0
- package/src/broadcast-fanout-2721.test.ts +118 -0
- package/src/broadcast-fanout.ts +98 -0
- package/src/chain-attempt-dedup.test.ts +447 -0
- package/src/clone-node.test.ts +248 -0
- package/src/clone-node.ts +289 -0
- package/src/codex-config-flags.ts +77 -0
- package/src/codex-fork-contract.ts +23 -0
- package/src/codex-fork-migration.test.ts +38 -0
- package/src/commhub-bin-args.test.ts +85 -0
- package/src/config-apply-sec1.test.ts +107 -0
- package/src/config-apply-validate.test.ts +134 -1
- package/src/config-apply-validate.ts +111 -5
- package/src/create-node-blocked-gate.test.ts +356 -0
- package/src/create-node-network-id.test.ts +79 -0
- package/src/create-node-tool-schema.test.ts +49 -0
- package/src/create-node-unicode-name.test.ts +120 -0
- package/src/create-node-validate.test.ts +379 -0
- package/src/create-node-validate.ts +423 -0
- package/src/create-node-workdir.test.ts +289 -0
- package/src/create-node.test.ts +354 -0
- package/src/create-node.ts +411 -0
- package/src/daemon-provider-snapshots.test.ts +421 -0
- package/src/daemon-provider-snapshots.ts +327 -0
- package/src/daemon-token-owner-http.test.ts +236 -0
- package/src/dashboard-slash-routing-http.test.ts +109 -0
- package/src/db-adapter-guard.test.ts +148 -0
- package/src/db-adapter-translate.test.ts +128 -0
- package/src/db-adapter.ts +377 -91
- package/src/db-timestamp.test.ts +38 -0
- package/src/db-timestamp.ts +15 -0
- package/src/db.ts +1501 -152
- package/src/delivered-without-push.test.ts +140 -0
- package/src/department-groups-http.test.ts +209 -0
- package/src/department-groups-sync-http.test.ts +328 -0
- package/src/department-groups.ts +434 -0
- package/src/department-heads-http.test.ts +330 -0
- package/src/department-heads.ts +226 -0
- package/src/departments-agent-count.test.ts +129 -0
- package/src/departments-http.test.ts +185 -0
- package/src/departments-mcp.test.ts +128 -0
- package/src/departments.ts +318 -0
- package/src/desktop-message-seam.test.ts +150 -0
- package/src/desktop-message.test.ts +368 -0
- package/src/dm-file-scope-http.test.ts +178 -0
- package/src/empty-node-sweeper.test.ts +104 -0
- package/src/empty-node-sweeper.ts +88 -0
- package/src/env-transport-gate-http.test.ts +177 -0
- package/src/env-transport-gate.ts +74 -0
- package/src/env-transport-policy.ts +21 -0
- package/src/event-loop-lag.test.ts +139 -0
- package/src/event-loop-lag.ts +150 -0
- package/src/ext-token-shared.test.ts +60 -0
- package/src/ext-validation-regression.test.ts +131 -0
- package/src/external-schedule-edits-http.test.ts +321 -0
- package/src/external-schedule-edits-timestamps.test.ts +64 -0
- package/src/external-schedule-edits.ts +327 -0
- package/src/file-download-authz-dev-open.test.ts +135 -0
- package/src/file-download-authz.test.ts +404 -0
- package/src/file-download-date-bucket.test.ts +436 -0
- package/src/file-network-scope-dev-open.test.ts +97 -0
- package/src/file-network-scope.test.ts +732 -0
- package/src/group-membership-events-http.test.ts +264 -0
- package/src/group-messages-http.test.ts +482 -0
- package/src/group-messages.ts +297 -0
- package/src/health-host-disk-2756.test.ts +49 -0
- package/src/health-redaction.test.ts +685 -0
- package/src/host-supervisor-identity-http.test.ts +152 -0
- package/src/host-supervisor-identity.ts +92 -0
- package/src/host-supervisors-daemon-version.test.ts +137 -0
- package/src/http-gzip.test.ts +94 -0
- package/src/http-gzip.ts +112 -0
- package/src/hub-catalog-read-http.test.ts +187 -0
- package/src/hub-provider-config.test.ts +139 -0
- package/src/hub-provider-config.ts +105 -0
- package/src/hub-timestamp.test.ts +38 -0
- package/src/hub-timestamp.ts +27 -0
- package/src/human-dm.ts +215 -0
- package/src/human-inbox.ts +42 -0
- package/src/inbox-caller.ts +49 -0
- package/src/inbox-count-sse.test.ts +310 -0
- package/src/inbox-count.ts +29 -0
- package/src/index.ts +15 -2172
- package/src/lifecycle-guard.ts +50 -0
- package/src/list-host-supervisors.test.ts +315 -0
- package/src/mcp-context-cost-http.test.ts +127 -0
- package/src/mcp-inflight.test.ts +92 -0
- package/src/mcp-inflight.ts +38 -0
- package/src/mcp-projects-events-http.test.ts +162 -0
- package/src/mcp-route-label-http.test.ts +120 -0
- package/src/mcp-write-network-resolution.test.ts +432 -0
- package/src/member-audit-network-id-http.test.ts +93 -0
- package/src/member-presence-http.test.ts +210 -0
- package/src/messages-ack-by-agent-http.test.ts +142 -0
- package/src/migrate-sqlite-to-pg.test.ts +47 -0
- package/src/migrate-sqlite-to-pg.ts +263 -0
- package/src/model-auth-notify-http.test.ts +181 -0
- package/src/model-auth-notify.ts +116 -0
- package/src/network-name-http.test.ts +75 -0
- package/src/network-rules-http.test.ts +169 -0
- package/src/network-rules.ts +129 -0
- package/src/network-scope.ts +276 -0
- package/src/network-token-membership-http.test.ts +139 -0
- package/src/node-alias-control.ts +12 -0
- package/src/node-attrs-validate.ts +88 -0
- package/src/node-attrs.test.ts +258 -0
- package/src/node-caller-identity-http.test.ts +1083 -0
- package/src/node-create-request-status-http.test.ts +105 -0
- package/src/node-daemon-bindings.test.ts +132 -0
- package/src/node-daemon-bindings.ts +135 -0
- package/src/node-failure-alert.test.ts +150 -0
- package/src/node-failure-alert.ts +177 -0
- package/src/node-files-transport.test.ts +344 -0
- package/src/node-health-codex-login.test.ts +120 -0
- package/src/node-health-dispatch-http.test.ts +279 -0
- package/src/node-health-guard.ts +105 -0
- package/src/node-health-passthrough.test.ts +115 -0
- package/src/node-health-store.ts +101 -0
- package/src/node-id-alias.test.ts +190 -0
- package/src/node-identity-conflict-http.test.ts +269 -0
- package/src/node-identity-conflict.ts +142 -0
- package/src/node-identity-mismatch.test.ts +74 -0
- package/src/node-in-flight-tasks.ts +31 -0
- package/src/node-lifecycle-controllable.test.ts +64 -0
- package/src/node-lifecycle-controllable.ts +53 -0
- package/src/node-lifecycle-read-http.test.ts +250 -0
- package/src/node-lifecycle-read.ts +124 -0
- package/src/node-logs-transport.test.ts +263 -0
- package/src/node-peer-allowlist.test.ts +79 -0
- package/src/node-permissions-http.test.ts +345 -0
- package/src/node-permissions.ts +393 -0
- package/src/node-request-retention.test.ts +281 -0
- package/src/node-request-retention.ts +120 -0
- package/src/node-secret-rest-http.test.ts +190 -0
- package/src/node-serviceability.test.ts +86 -0
- package/src/node-serviceability.ts +124 -0
- package/src/node-session-control-http.test.ts +310 -0
- package/src/node-session-control.ts +258 -0
- package/src/node-skills-transport.test.ts +209 -0
- package/src/node-token-identity.ts +35 -0
- package/src/node-token-ownership.ts +51 -0
- package/src/node-token-privilege-http.test.ts +158 -0
- package/src/not-found-api-http.test.ts +67 -0
- package/src/observer-avatar-http.test.ts +442 -0
- package/src/observer-push.test.ts +252 -0
- package/src/opencode-catalog-report-http.test.ts +139 -0
- package/src/opencode-v2-catalog.test.ts +268 -0
- package/src/opencode-v2-catalog.ts +352 -0
- package/src/package-version-consistency.test.ts +25 -0
- package/src/parent-source-marker.test.ts +50 -0
- package/src/password-network-tokens.ts +25 -0
- package/src/peer-reply-atomic.test.ts +455 -0
- package/src/peer-reply-capability.test.ts +70 -0
- package/src/pg-worker.ts +87 -0
- package/src/probe-validate.test.ts +221 -0
- package/src/probe-validate.ts +104 -0
- package/src/probe.test.ts +80 -0
- package/src/probe.ts +200 -0
- package/src/project-dir-warn-clear-http.test.ts +132 -0
- package/src/project-viewer-can-http.test.ts +116 -0
- package/src/push.test.ts +20 -10
- package/src/push.ts +466 -13
- package/src/redact-tokens.test.ts +65 -0
- package/src/redact-tokens.ts +40 -0
- package/src/rename.ts +38 -10
- package/src/reply-target-derivation.test.ts +96 -0
- package/src/report-status-handover-capabilities-http.test.ts +124 -0
- package/src/report-status-host-schema.test.ts +235 -0
- package/src/report-status-resume-id-handover.test.ts +184 -0
- package/src/report-status-secret-keys.test.ts +140 -0
- package/src/require-explicit-test-db.ts +9 -0
- package/src/requirement-due-reminders-http.test.ts +620 -0
- package/src/requirement-due-reminders.ts +416 -0
- package/src/requirement-events-http.test.ts +268 -0
- package/src/requirement-events.test.ts +45 -0
- package/src/requirement-events.ts +144 -0
- package/src/requirement-notify.ts +165 -0
- package/src/requirement-participant-notify-http.test.ts +309 -0
- package/src/requirement-tag-ops-http.test.ts +425 -0
- package/src/requirement-tag-tree-http.test.ts +275 -0
- package/src/requirement-tag-tree.ts +127 -0
- package/src/requirement-tags.ts +102 -0
- package/src/requirements-abandoned-http.test.ts +236 -0
- package/src/requirements-comment-http.test.ts +167 -0
- package/src/requirements-completed-at-migration.test.ts +70 -0
- package/src/requirements-errors-mcp-http.test.ts +164 -0
- package/src/requirements-errors.ts +158 -0
- package/src/requirements-etag-http.test.ts +91 -0
- package/src/requirements-http.test.ts +709 -0
- package/src/requirements-last-event-http.test.ts +349 -0
- package/src/requirements-list-mcp-slim-http.test.ts +155 -0
- package/src/requirements-list-slim-http.test.ts +324 -0
- package/src/requirements-mcp.test.ts +163 -0
- package/src/requirements-migrate.ts +283 -0
- package/src/requirements-owner-strict-mcp-http.test.ts +145 -0
- package/src/requirements-people-http.test.ts +114 -0
- package/src/requirements-people-mcp-http.test.ts +231 -0
- package/src/requirements-people.ts +196 -0
- package/src/requirements-priority-lowest.test.ts +114 -0
- package/src/requirements-projects-parent-http.test.ts +123 -0
- package/src/requirements-search-http.test.ts +182 -0
- package/src/requirements-search.test.ts +32 -0
- package/src/requirements-search.ts +145 -0
- package/src/requirements-seq-http.test.ts +193 -0
- package/src/requirements-seq-migration.test.ts +63 -0
- package/src/requirements-start-date.test.ts +125 -0
- package/src/requirements-stats-http.test.ts +357 -0
- package/src/requirements-stats.ts +195 -0
- package/src/requirements-status-participants-http.test.ts +222 -0
- package/src/requirements-upgrade-e2e.test.ts +126 -0
- package/src/requirements-upgrade-migration.test.ts +98 -0
- package/src/requirements.ts +2027 -0
- package/src/resolve-port.test.ts +57 -0
- package/src/resolve-port.ts +44 -0
- package/src/response-charset.test.ts +130 -0
- package/src/rest-alias-network-fallback-http.test.ts +123 -0
- package/src/rest-alias-network-fallback.test.ts +60 -0
- package/src/rest-alias-network-fallback.ts +65 -0
- package/src/rest-explicit-columns-http.test.ts +266 -0
- package/src/rest-identity.test.ts +130 -0
- package/src/rest-identity.ts +141 -0
- package/src/rest-projections.ts +72 -0
- package/src/rest-read-network-real-chain.test.ts +97 -0
- package/src/rest-write-network-resolution.test.ts +133 -0
- package/src/restart-readiness-http.test.ts +121 -0
- package/src/restricted-files.ts +76 -0
- package/src/retention-first-sweep-quiet.test.ts +31 -0
- package/src/retention.test.ts +100 -40
- package/src/retention.ts +423 -104
- package/src/route-callers-http.test.ts +120 -0
- package/src/route-timing.test.ts +211 -0
- package/src/route-timing.ts +262 -0
- package/src/rules-file-duplicate-alias.test.ts +234 -0
- package/src/rules-file-session-target.test.ts +207 -0
- package/src/rules-file-transport.test.ts +237 -0
- package/src/runtime-label.test.ts +22 -0
- package/src/runtime-label.ts +21 -0
- package/src/runtime-readiness.ts +90 -0
- package/src/schedule-agent-mcp-http.test.ts +391 -0
- package/src/schedule-agent.ts +192 -0
- package/src/schedule-starved.test.ts +92 -0
- package/src/schedule-starved.ts +114 -0
- package/src/scheduled-backoff-http.test.ts +193 -0
- package/src/scheduled-backoff.ts +64 -0
- package/src/scheduled-doorbell-nodeless-session.test.ts +134 -0
- package/src/scheduled-failure-backoff-2622.test.ts +145 -0
- package/src/scheduled-failure-code.test.ts +73 -0
- package/src/scheduled-failure-code.ts +105 -0
- package/src/scheduled-failures-http.test.ts +279 -0
- package/src/scheduled-failures.ts +377 -0
- package/src/scheduled-noprogress-backoff-2622.test.ts +133 -0
- package/src/scheduled-offline-backoff-probe.test.ts +56 -0
- package/src/scheduled-offline.test.ts +131 -0
- package/src/scheduled-offline.ts +66 -0
- package/src/scheduled-outcome-guidance-http.test.ts +139 -0
- package/src/scheduled-outcome-guidance.ts +9 -0
- package/src/scheduled-reply-unread-http.test.ts +212 -0
- package/src/scheduled-requirement-wake-http.test.ts +279 -0
- package/src/scheduled-requirement-wake.ts +125 -0
- package/src/scheduled-run-terminal.test.ts +268 -0
- package/src/scheduled-skip-blocking-task.test.ts +120 -0
- package/src/scheduled-skip-path-backoff-2622.test.ts +98 -0
- package/src/scheduled-stuck-http.test.ts +312 -0
- package/src/scheduled-stuck-notice-cap.test.ts +80 -0
- package/src/scheduled-stuck.ts +219 -0
- package/src/scheduled-tasks-http.test.ts +679 -0
- package/src/scheduled-tasks.ts +959 -0
- package/src/scheduled-work-outcome-http.test.ts +154 -0
- package/src/scheduled-work-outcome.ts +50 -0
- package/src/scoped-secrets.ts +139 -0
- package/src/send-dedup-request-id.test.ts +229 -0
- package/src/send-reply-agent-warning.test.ts +202 -0
- package/src/send-reply-alias-optional.test.ts +131 -0
- package/src/send-reply-attachments.test.ts +458 -0
- package/src/send_dedup.test.ts +54 -0
- package/src/send_dedup.ts +52 -6
- package/src/serve-error.test.ts +38 -0
- package/src/serve-error.ts +27 -0
- package/src/server.ts +5997 -0
- package/src/session-task-on-dispatch.ts +14 -0
- package/src/session-token-ownership-http.test.ts +122 -0
- package/src/shared/codex-inventory.ts +41 -0
- package/src/shared/daemon-provider-login.ts +31 -0
- package/src/shared/daemon-provider-snapshot.ts +52 -0
- package/src/shared/external-schedule-contract.ts +60 -0
- package/src/shared/node-name.test.ts +62 -0
- package/src/shared/node-name.ts +161 -0
- package/src/shared/probe-host-allowlist-drift.test.ts +54 -0
- package/src/shared/probe-host-allowlist.ts +128 -0
- package/src/shared/provider-application.ts +29 -0
- package/src/shared/provider-collection.ts +14 -0
- package/src/shared/provider-initialization.ts +8 -0
- package/src/shared/reserved-env-drift.test.ts +53 -0
- package/src/shared/reserved-env.test.ts +35 -0
- package/src/shared/reserved-env.ts +31 -0
- package/src/shared/scoped-secret-contract.ts +5 -0
- package/src/shared/task-content-limit-drift.test.ts +28 -0
- package/src/shared/task-content-limit.ts +25 -0
- package/src/side-thread-command-transport.test.ts +312 -0
- package/src/side-thread-command-transport.ts +318 -0
- package/src/side-thread-http-integration.test.ts +233 -0
- package/src/side-thread-http.ts +504 -0
- package/src/side-thread-production.test.ts +72 -0
- package/src/side-thread-production.ts +118 -0
- package/src/side-thread.test.ts +1067 -0
- package/src/side-thread.ts +2499 -0
- package/src/skillhub-http.test.ts +108 -0
- package/src/sqlite-close-checkpoint.test.ts +78 -0
- package/src/start-node.test.ts +264 -0
- package/src/status-alias-filter-http.test.ts +106 -0
- package/src/status-alias-resolver-http.test.ts +163 -0
- package/src/status-alias-resolver.ts +19 -0
- package/src/status-node-id-filter-http.test.ts +161 -0
- package/src/status-read-cache-http.test.ts +229 -0
- package/src/status-read-cache.ts +122 -0
- package/src/stop-delete-node.test.ts +1286 -0
- package/src/task-access-http.test.ts +402 -0
- package/src/task-access.ts +420 -0
- package/src/task-activity.ts +60 -0
- package/src/task-auth-origin-http.test.ts +93 -0
- package/src/task-auth-origin.test.ts +24 -0
- package/src/task-auth-origin.ts +7 -0
- package/src/task-consumption.test.ts +482 -0
- package/src/task-diagnostic-http.test.ts +149 -0
- package/src/task-diagnostic.test.ts +115 -0
- package/src/task-diagnostic.ts +118 -0
- package/src/task-expiry-notice-http.test.ts +287 -0
- package/src/task-expiry-notice.ts +315 -0
- package/src/task-idempotency-mcp.test.ts +142 -0
- package/src/task-idempotency.test.ts +76 -0
- package/src/task-idempotency.ts +81 -0
- package/src/task-late-replies.ts +54 -0
- package/src/task-late-reply-http.test.ts +152 -0
- package/src/task-lifecycle-watcher-busy.test.ts +114 -0
- package/src/task-lifecycle-watcher.test.ts +204 -0
- package/src/task-lifecycle-watcher.ts +109 -0
- package/src/task-network-resolution-http.test.ts +140 -0
- package/src/task-offline-delivery-2668.test.ts +119 -0
- package/src/task-offline-delivery.ts +81 -0
- package/src/task-orphan-http.test.ts +287 -0
- package/src/task-orphan.ts +119 -0
- package/src/task-queue-ahead-http.test.ts +309 -0
- package/src/task-queue-ahead-scale.test.ts +236 -0
- package/src/task-queue-ahead.ts +186 -0
- package/src/task-rejection-log-http.test.ts +160 -0
- package/src/task-rejection-log.ts +49 -0
- package/src/task-sender-http.test.ts +143 -0
- package/src/task-stale-open-http.test.ts +290 -0
- package/src/task-stale-open.ts +103 -0
- package/src/tasks-pagination-http.test.ts +141 -0
- package/src/team-rules-status-http.test.ts +90 -0
- package/src/team-rules-status.test.ts +59 -0
- package/src/team-rules-status.ts +72 -0
- package/src/tool-audience-http.test.ts +230 -0
- package/src/tool-audience.ts +120 -0
- package/src/tools-list-json-schema.test.ts +94 -0
- package/src/tools.ts +5815 -348
- package/src/update-provider.test.ts +234 -0
- package/src/upload-early-reject-guard.test.ts +155 -0
- package/src/uploads-http.test.ts +97 -15
- package/src/uploads.test.ts +66 -0
- package/src/uploads.ts +138 -5
- package/src/user-avatar-http.test.ts +74 -0
- package/src/user-avatar-image.ts +160 -0
- package/src/user-avatar-migration.test.ts +25 -0
- package/src/user-avatar-upload-http.test.ts +348 -0
- package/src/user-inbox-by-agent-http.test.ts +161 -0
- package/src/user-inbox-netid-notnull.test.ts +122 -0
- package/src/user-inbox-read-http.test.ts +223 -0
- package/src/user-inbox-schema.test.ts +54 -0
- package/src/vault.test.ts +200 -0
- package/src/vault.ts +156 -0
- package/src/version-stats.test.ts +66 -0
- package/src/version-stats.ts +109 -0
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
// RFC-027 §2.3 race-free invariant — shared helper for the inbox-
|
|
2
|
+
// enqueue lifecycle guard.
|
|
3
|
+
//
|
|
4
|
+
// PR1.1 (#346) added an `assertNodeActive` helper inside the
|
|
5
|
+
// registerTools() closure and applied it at the 6 INSERT INTO inbox
|
|
6
|
+
// sites in server/src/tools.ts. PR1.1 review (通信龙 #346 ack) caught
|
|
7
|
+
// that the closure scope made the helper unreachable from REST
|
|
8
|
+
// handlers in server/src/index.ts — POST /api/task (:1631) and
|
|
9
|
+
// POST /api/broadcast (:1706) are dashboard's "Dispatch" entry
|
|
10
|
+
// points and bypassed the guard, leaving the §2.3 race open on the
|
|
11
|
+
// REST path.
|
|
12
|
+
//
|
|
13
|
+
// PR1.2a (#346 follow-up) extracts the helper to this module so both
|
|
14
|
+
// the MCP tools and the REST handlers can import the same code path,
|
|
15
|
+
// per team rule (grep every write site before adding a guard): any SQL-level
|
|
16
|
+
// guard's helper lives at module scope so every write site
|
|
17
|
+
// (MCP + REST + internal db.ts helpers) can use it.
|
|
18
|
+
//
|
|
19
|
+
// Behaviour:
|
|
20
|
+
// - no nodes row for the alias → ok:true (brand-new alias allowed;
|
|
21
|
+
// could be the first INSERT for a child about to register)
|
|
22
|
+
// - lifecycle_state = 'active' OR NULL (pre-RFC-027 row) → ok:true
|
|
23
|
+
// - anything else (stopping / stopped / stop_failed / deleting) →
|
|
24
|
+
// ok:false + structured `node_not_active` reply
|
|
25
|
+
//
|
|
26
|
+
// COALESCE on the WHERE keeps NULL-network inbox rows / legacy nodes
|
|
27
|
+
// rows correctly scoped (PR1 SF-5 lineage).
|
|
28
|
+
|
|
29
|
+
import { db } from "./db.js";
|
|
30
|
+
|
|
31
|
+
export type LifecycleGuardResult =
|
|
32
|
+
| { ok: true }
|
|
33
|
+
| { ok: false; error: "node_not_active"; lifecycle_state: string; alias: string };
|
|
34
|
+
|
|
35
|
+
export function assertNodeActive(
|
|
36
|
+
sessionAlias: string,
|
|
37
|
+
networkId: string | null,
|
|
38
|
+
): LifecycleGuardResult {
|
|
39
|
+
if (!sessionAlias) return { ok: true };
|
|
40
|
+
const row = db.get<{ lifecycle_state: string | null }>(
|
|
41
|
+
networkId
|
|
42
|
+
? `SELECT lifecycle_state FROM nodes WHERE alias = ?1 AND COALESCE(network_id, ?2) = ?2 LIMIT 1`
|
|
43
|
+
: `SELECT lifecycle_state FROM nodes WHERE alias = ?1 LIMIT 1`,
|
|
44
|
+
...(networkId ? [sessionAlias, networkId] : [sessionAlias]),
|
|
45
|
+
);
|
|
46
|
+
if (!row) return { ok: true };
|
|
47
|
+
const st = row.lifecycle_state ?? "active";
|
|
48
|
+
if (st === "active") return { ok: true };
|
|
49
|
+
return { ok: false, error: "node_not_active", lifecycle_state: st, alias: sessionAlias };
|
|
50
|
+
}
|
|
@@ -0,0 +1,315 @@
|
|
|
1
|
+
import { afterAll, beforeEach, describe, expect, test } from "bun:test";
|
|
2
|
+
import { db, hashToken, generateId } from "./db.js";
|
|
3
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
4
|
+
import { registerTools } from "./tools.js";
|
|
5
|
+
|
|
6
|
+
// RFC-026 §9.2 / #338 PR2 v2 — list_host_supervisors HANDLER tests.
|
|
7
|
+
//
|
|
8
|
+
// PR2 v1 used a mirror-SQL pattern (re-implemented the query in the test
|
|
9
|
+
// itself) → trivially passed but didn't exercise the handler. 通信龙 audit
|
|
10
|
+
// caught: that style misses the SEC-1 scope-derivation bug
|
|
11
|
+
// (`getNetworkId(clientNetId)` returns the unchecked client-supplied
|
|
12
|
+
// network_id for utok_ callers when enforceNetworkId is null, leaking
|
|
13
|
+
// cross-tenant daemons). This rewrite drives the registered MCP tool
|
|
14
|
+
// through registerTools() so the auth context is real.
|
|
15
|
+
//
|
|
16
|
+
// Covers:
|
|
17
|
+
// SEC-1.1 — cross-tenant utok_ caller with foreign network_id: DENIED
|
|
18
|
+
// SEC-1.2 — admin caller with own network_id: returns own daemons
|
|
19
|
+
// SEC-1.3 — caller with no network_id: returns daemons in all member networks
|
|
20
|
+
// masking — non-admin viewer: host_telemetry IP/cpu/mem stripped, alert_level still surfaces
|
|
21
|
+
// revoked — DELETEd token row (revokeToken path): daemon excluded
|
|
22
|
+
// revoked — revoked_at SET token: daemon excluded
|
|
23
|
+
// self-declare — runtimes_supported/allowed_secret_keys surface from columns
|
|
24
|
+
// pre-PR2 daemon — empty arrays on NULL columns (back-compat)
|
|
25
|
+
|
|
26
|
+
const NET_ALPHA = "net_lhs_alpha";
|
|
27
|
+
const NET_BETA = "net_lhs_beta";
|
|
28
|
+
|
|
29
|
+
interface ToolHandler { (args: any, extra?: any): Promise<{ content: Array<{ type: "text"; text: string }> }>; }
|
|
30
|
+
interface Reply { ok?: boolean; error?: string; daemons?: any[]; count?: number; }
|
|
31
|
+
|
|
32
|
+
function cleanup() {
|
|
33
|
+
for (const n of [NET_ALPHA, NET_BETA]) {
|
|
34
|
+
try { db.run("DELETE FROM nodes WHERE network_id = ?1", [n]); } catch {}
|
|
35
|
+
try { db.run("DELETE FROM sessions WHERE network_id = ?1", [n]); } catch {}
|
|
36
|
+
try { db.run("DELETE FROM api_tokens WHERE network_id = ?1", [n]); } catch {}
|
|
37
|
+
try { db.run("DELETE FROM network_members WHERE network_id = ?1", [n]); } catch {}
|
|
38
|
+
try { db.run("DELETE FROM networks WHERE network_id = ?1", [n]); } catch {}
|
|
39
|
+
}
|
|
40
|
+
try { db.run("DELETE FROM users WHERE user_id LIKE 'u_lhs_%'"); } catch {}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// Each case starts empty; plain INSERT keeps these fixtures portable to PostgreSQL.
|
|
44
|
+
beforeEach(cleanup);
|
|
45
|
+
afterAll(cleanup);
|
|
46
|
+
|
|
47
|
+
function seedUser(user_id: string) {
|
|
48
|
+
db.run(
|
|
49
|
+
`INSERT INTO users (user_id, username, password_hash, role, created_at)
|
|
50
|
+
VALUES (?1, ?2, 'x', 'user', datetime('now'))`,
|
|
51
|
+
[user_id, user_id],
|
|
52
|
+
);
|
|
53
|
+
}
|
|
54
|
+
function seedNetwork(net_id: string, owner_id = "u_lhs_owner") {
|
|
55
|
+
db.run(
|
|
56
|
+
`INSERT INTO networks (network_id, network_name, owner_id, created_at)
|
|
57
|
+
VALUES (?1, ?2, ?3, datetime('now'))`,
|
|
58
|
+
[net_id, net_id, owner_id],
|
|
59
|
+
);
|
|
60
|
+
}
|
|
61
|
+
function seedMembership(user_id: string, net_id: string, role: "owner" | "admin" | "member" | "viewer" = "member") {
|
|
62
|
+
db.run(
|
|
63
|
+
`INSERT INTO network_members (user_id, network_id, role, joined_at)
|
|
64
|
+
VALUES (?1, ?2, ?3, datetime('now'))`,
|
|
65
|
+
[user_id, net_id, role],
|
|
66
|
+
);
|
|
67
|
+
}
|
|
68
|
+
function seedDaemon(opts: {
|
|
69
|
+
network_id: string, alias: string, node_id?: string,
|
|
70
|
+
role?: string,
|
|
71
|
+
runtimes?: string[],
|
|
72
|
+
secrets?: string[],
|
|
73
|
+
sessionAgeMs?: number,
|
|
74
|
+
mintToken?: boolean,
|
|
75
|
+
tokenRevokedAt?: boolean,
|
|
76
|
+
tokenDeleted?: boolean,
|
|
77
|
+
}) {
|
|
78
|
+
const node_id = opts.node_id || `node_${opts.network_id}_${opts.alias}`;
|
|
79
|
+
const snapshot = JSON.stringify({
|
|
80
|
+
model: "claude-opus", flags: {}, role: opts.role ?? "host_supervisor",
|
|
81
|
+
runtimes_supported: opts.runtimes ?? ["claude-agent-sdk"],
|
|
82
|
+
allowed_secret_keys: opts.secrets ?? [],
|
|
83
|
+
});
|
|
84
|
+
db.run(
|
|
85
|
+
`INSERT INTO nodes (
|
|
86
|
+
node_id, node_name, alias, network_id,
|
|
87
|
+
runtimes_supported, allowed_secret_keys,
|
|
88
|
+
config_snapshot, hostname,
|
|
89
|
+
created_at, updated_at
|
|
90
|
+
) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, datetime('now'), datetime('now'))`,
|
|
91
|
+
[node_id, opts.alias, opts.alias, opts.network_id,
|
|
92
|
+
JSON.stringify(opts.runtimes ?? ["claude-agent-sdk"]),
|
|
93
|
+
JSON.stringify(opts.secrets ?? []),
|
|
94
|
+
snapshot, `host-${opts.alias}`],
|
|
95
|
+
);
|
|
96
|
+
if (opts.sessionAgeMs !== undefined) {
|
|
97
|
+
const ts = new Date(Date.now() - opts.sessionAgeMs).toISOString().replace("T", " ").replace(/\..+/, "");
|
|
98
|
+
db.run(
|
|
99
|
+
`INSERT INTO sessions (resume_id, alias, network_id, last_seen_at, status, cpu_cores, mem_total_gb, ip)
|
|
100
|
+
VALUES (?1, ?2, ?3, ?4, 'idle', 8, 16, '10.0.0.5')`,
|
|
101
|
+
[`s_${node_id}`, opts.alias, opts.network_id, ts],
|
|
102
|
+
);
|
|
103
|
+
}
|
|
104
|
+
if (opts.mintToken !== false && !opts.tokenDeleted) {
|
|
105
|
+
db.run(
|
|
106
|
+
`INSERT INTO api_tokens (token_id, user_id, network_id, scope, name, token_hash, expires_at, revoked_at)
|
|
107
|
+
VALUES (?1, ?2, ?3, 'network', ?4, ?5, NULL, ?6)`,
|
|
108
|
+
[`tok_${node_id}`, `u_seed_${node_id}`, opts.network_id, `node:${opts.alias}`,
|
|
109
|
+
`hash_${node_id}`,
|
|
110
|
+
opts.tokenRevokedAt ? new Date().toISOString().replace("T", " ").replace(/\..+/, "") : null],
|
|
111
|
+
);
|
|
112
|
+
}
|
|
113
|
+
return node_id;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** Build a server with registerTools wired to a specific enforceUserId. */
|
|
117
|
+
function buildToolHandler(enforceUserId: string | null): ToolHandler {
|
|
118
|
+
const server = new McpServer({ name: "test", version: "0" }) as any;
|
|
119
|
+
const tools: Record<string, ToolHandler> = {};
|
|
120
|
+
// Capture the registered tool function. The MCP SDK's server.tool stores
|
|
121
|
+
// the handler internally; we intercept by overriding before registerTools.
|
|
122
|
+
const origTool = server.tool.bind(server);
|
|
123
|
+
server.tool = (name: string, _desc: string, _schema: any, handler: ToolHandler) => {
|
|
124
|
+
tools[name] = handler;
|
|
125
|
+
return origTool(name, _desc, _schema, handler);
|
|
126
|
+
};
|
|
127
|
+
// Some tools use registerTool; intercept that too
|
|
128
|
+
const origRegisterTool = server.registerTool?.bind(server);
|
|
129
|
+
if (origRegisterTool) {
|
|
130
|
+
server.registerTool = (name: string, _cfg: any, handler: ToolHandler) => {
|
|
131
|
+
tools[name] = handler;
|
|
132
|
+
return origRegisterTool(name, _cfg, handler);
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
registerTools(
|
|
136
|
+
server,
|
|
137
|
+
/* clientIP */ undefined,
|
|
138
|
+
/* enforceNetworkId */ null,
|
|
139
|
+
/* enforceUserId */ enforceUserId,
|
|
140
|
+
/* callerAlias */ null,
|
|
141
|
+
/* callerTokenIsNetwork */ false,
|
|
142
|
+
/* callerTokenId */ null,
|
|
143
|
+
);
|
|
144
|
+
const h = tools["list_host_supervisors"];
|
|
145
|
+
if (!h) throw new Error("list_host_supervisors tool not registered");
|
|
146
|
+
return h;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
async function callList(handler: ToolHandler, args: any = {}): Promise<Reply> {
|
|
150
|
+
const r = await handler(args);
|
|
151
|
+
return JSON.parse(r.content[0].text) as Reply;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
describe("list_host_supervisors HANDLER tests (RFC-026 §9.2, PR2 v2)", () => {
|
|
155
|
+
test("SEC-1.1: cross-tenant utok_ caller with foreign network_id → DENIED", async () => {
|
|
156
|
+
const userA = "u_lhs_alice"; // belongs to NET_ALPHA only
|
|
157
|
+
seedUser(userA);
|
|
158
|
+
seedNetwork(NET_ALPHA);
|
|
159
|
+
seedNetwork(NET_BETA);
|
|
160
|
+
seedMembership(userA, NET_ALPHA, "admin");
|
|
161
|
+
seedDaemon({ network_id: NET_BETA, alias: "secret-beta-daemon" });
|
|
162
|
+
|
|
163
|
+
const handler = buildToolHandler(userA);
|
|
164
|
+
const reply = await callList(handler, { network_id: NET_BETA });
|
|
165
|
+
// PR2 v1 BUG: this returned ok:true with secret-beta-daemon in the list.
|
|
166
|
+
expect(reply.ok).toBe(false);
|
|
167
|
+
expect(reply.error).toMatch(/access denied|not a member/i);
|
|
168
|
+
// Belt: hostname not in error payload
|
|
169
|
+
expect(JSON.stringify(reply)).not.toContain("secret-beta-daemon");
|
|
170
|
+
expect(JSON.stringify(reply)).not.toContain("host-secret-beta-daemon");
|
|
171
|
+
});
|
|
172
|
+
|
|
173
|
+
test("SEC-1.2: admin caller with own network_id returns own daemons", async () => {
|
|
174
|
+
const userA = "u_lhs_alice";
|
|
175
|
+
seedUser(userA);
|
|
176
|
+
seedNetwork(NET_ALPHA);
|
|
177
|
+
seedMembership(userA, NET_ALPHA, "admin");
|
|
178
|
+
seedDaemon({ network_id: NET_ALPHA, alias: "alpha-daemon-1" });
|
|
179
|
+
seedDaemon({ network_id: NET_ALPHA, alias: "alpha-daemon-2" });
|
|
180
|
+
|
|
181
|
+
const handler = buildToolHandler(userA);
|
|
182
|
+
const reply = await callList(handler, { network_id: NET_ALPHA });
|
|
183
|
+
expect(reply.ok).toBe(true);
|
|
184
|
+
const aliases = (reply.daemons ?? []).map(d => d.alias).sort();
|
|
185
|
+
expect(aliases).toEqual(["alpha-daemon-1", "alpha-daemon-2"]);
|
|
186
|
+
});
|
|
187
|
+
|
|
188
|
+
test("SEC-1.3: caller without network_id arg → returns daemons across member networks only", async () => {
|
|
189
|
+
const userA = "u_lhs_alice"; // member of NET_ALPHA only
|
|
190
|
+
seedUser(userA);
|
|
191
|
+
seedNetwork(NET_ALPHA);
|
|
192
|
+
seedNetwork(NET_BETA);
|
|
193
|
+
seedMembership(userA, NET_ALPHA, "member");
|
|
194
|
+
seedDaemon({ network_id: NET_ALPHA, alias: "ok-daemon" });
|
|
195
|
+
seedDaemon({ network_id: NET_BETA, alias: "forbidden-daemon" });
|
|
196
|
+
|
|
197
|
+
const handler = buildToolHandler(userA);
|
|
198
|
+
const reply = await callList(handler);
|
|
199
|
+
expect(reply.ok).toBe(true);
|
|
200
|
+
const aliases = (reply.daemons ?? []).map(d => d.alias);
|
|
201
|
+
expect(aliases).toContain("ok-daemon");
|
|
202
|
+
expect(aliases).not.toContain("forbidden-daemon");
|
|
203
|
+
});
|
|
204
|
+
|
|
205
|
+
test("masking: member caller gets host_telemetry without IP/cpu/mem; admin gets full", async () => {
|
|
206
|
+
const userMember = "u_lhs_bob_member";
|
|
207
|
+
const userAdmin = "u_lhs_carol_admin";
|
|
208
|
+
seedUser(userMember);
|
|
209
|
+
seedUser(userAdmin);
|
|
210
|
+
seedNetwork(NET_ALPHA);
|
|
211
|
+
seedMembership(userMember, NET_ALPHA, "member");
|
|
212
|
+
seedMembership(userAdmin, NET_ALPHA, "admin");
|
|
213
|
+
seedDaemon({ network_id: NET_ALPHA, alias: "telemetry-daemon", sessionAgeMs: 5_000 });
|
|
214
|
+
|
|
215
|
+
const memberHandler = buildToolHandler(userMember);
|
|
216
|
+
const memberReply = await callList(memberHandler, { network_id: NET_ALPHA });
|
|
217
|
+
expect(memberReply.daemons?.[0].host_telemetry.alert_level).toBeDefined();
|
|
218
|
+
expect(memberReply.daemons?.[0].host_telemetry).not.toHaveProperty("cpu_cores");
|
|
219
|
+
expect(memberReply.daemons?.[0].host_telemetry).not.toHaveProperty("mem_gb");
|
|
220
|
+
expect(memberReply.daemons?.[0].host_telemetry).not.toHaveProperty("ip_internal");
|
|
221
|
+
|
|
222
|
+
const adminHandler = buildToolHandler(userAdmin);
|
|
223
|
+
const adminReply = await callList(adminHandler, { network_id: NET_ALPHA });
|
|
224
|
+
expect(adminReply.daemons?.[0].host_telemetry.cpu_cores).toBe(8);
|
|
225
|
+
expect(adminReply.daemons?.[0].host_telemetry.mem_gb).toBe(16);
|
|
226
|
+
expect(adminReply.daemons?.[0].host_telemetry.ip_internal).toBe("10.0.0.5");
|
|
227
|
+
});
|
|
228
|
+
|
|
229
|
+
test("revoked: DELETEd token row (revokeToken path) excludes daemon", async () => {
|
|
230
|
+
const userA = "u_lhs_alice";
|
|
231
|
+
seedUser(userA);
|
|
232
|
+
seedNetwork(NET_ALPHA);
|
|
233
|
+
seedMembership(userA, NET_ALPHA, "admin");
|
|
234
|
+
seedDaemon({ network_id: NET_ALPHA, alias: "alive-daemon" });
|
|
235
|
+
seedDaemon({ network_id: NET_ALPHA, alias: "deleted-token-daemon", tokenDeleted: true });
|
|
236
|
+
|
|
237
|
+
const handler = buildToolHandler(userA);
|
|
238
|
+
const reply = await callList(handler, { network_id: NET_ALPHA });
|
|
239
|
+
const aliases = (reply.daemons ?? []).map(d => d.alias).sort();
|
|
240
|
+
expect(aliases).toContain("alive-daemon");
|
|
241
|
+
expect(aliases).not.toContain("deleted-token-daemon");
|
|
242
|
+
});
|
|
243
|
+
|
|
244
|
+
test("revoked: token with revoked_at SET also excludes daemon", async () => {
|
|
245
|
+
const userA = "u_lhs_alice";
|
|
246
|
+
seedUser(userA);
|
|
247
|
+
seedNetwork(NET_ALPHA);
|
|
248
|
+
seedMembership(userA, NET_ALPHA, "admin");
|
|
249
|
+
seedDaemon({ network_id: NET_ALPHA, alias: "alive-daemon" });
|
|
250
|
+
seedDaemon({ network_id: NET_ALPHA, alias: "revoked-at-daemon", tokenRevokedAt: true });
|
|
251
|
+
|
|
252
|
+
const handler = buildToolHandler(userA);
|
|
253
|
+
const reply = await callList(handler, { network_id: NET_ALPHA });
|
|
254
|
+
const aliases = (reply.daemons ?? []).map(d => d.alias).sort();
|
|
255
|
+
expect(aliases).toContain("alive-daemon");
|
|
256
|
+
expect(aliases).not.toContain("revoked-at-daemon");
|
|
257
|
+
});
|
|
258
|
+
|
|
259
|
+
test("role filter: regular member nodes (role=member) excluded after extraction", async () => {
|
|
260
|
+
const userA = "u_lhs_alice";
|
|
261
|
+
seedUser(userA);
|
|
262
|
+
seedNetwork(NET_ALPHA);
|
|
263
|
+
seedMembership(userA, NET_ALPHA, "admin");
|
|
264
|
+
seedDaemon({ network_id: NET_ALPHA, alias: "real-daemon", role: "host_supervisor" });
|
|
265
|
+
seedDaemon({ network_id: NET_ALPHA, alias: "regular-node", role: "member" });
|
|
266
|
+
|
|
267
|
+
const handler = buildToolHandler(userA);
|
|
268
|
+
const reply = await callList(handler, { network_id: NET_ALPHA });
|
|
269
|
+
const aliases = (reply.daemons ?? []).map(d => d.alias).sort();
|
|
270
|
+
expect(aliases).toEqual(["real-daemon"]);
|
|
271
|
+
});
|
|
272
|
+
|
|
273
|
+
test("self-declare: runtimes_supported + allowed_secret_keys surface from columns", async () => {
|
|
274
|
+
const userA = "u_lhs_alice";
|
|
275
|
+
seedUser(userA);
|
|
276
|
+
seedNetwork(NET_ALPHA);
|
|
277
|
+
seedMembership(userA, NET_ALPHA, "admin");
|
|
278
|
+
seedDaemon({
|
|
279
|
+
network_id: NET_ALPHA, alias: "rich-daemon",
|
|
280
|
+
runtimes: ["claude-agent-sdk", "codex-sdk", "grok-build-acp"],
|
|
281
|
+
secrets: ["ANTHROPIC_API_KEY", "OPENAI_API_KEY"],
|
|
282
|
+
});
|
|
283
|
+
|
|
284
|
+
const handler = buildToolHandler(userA);
|
|
285
|
+
const reply = await callList(handler, { network_id: NET_ALPHA });
|
|
286
|
+
const d = reply.daemons?.[0];
|
|
287
|
+
expect(d.runtimes_supported).toEqual(["claude-agent-sdk", "codex-sdk", "grok-build-acp"]);
|
|
288
|
+
expect(d.allowed_secret_keys).toEqual(["ANTHROPIC_API_KEY", "OPENAI_API_KEY"]);
|
|
289
|
+
});
|
|
290
|
+
|
|
291
|
+
test("pre-PR2 daemon (NULL columns) extracts to empty arrays back-compat", async () => {
|
|
292
|
+
const userA = "u_lhs_alice";
|
|
293
|
+
seedUser(userA);
|
|
294
|
+
seedNetwork(NET_ALPHA);
|
|
295
|
+
seedMembership(userA, NET_ALPHA, "admin");
|
|
296
|
+
db.run(
|
|
297
|
+
`INSERT INTO nodes (node_id, node_name, alias, network_id, config_snapshot, runtimes_supported, allowed_secret_keys, created_at, updated_at)
|
|
298
|
+
VALUES (?1, 'legacy', 'legacy', ?2, ?3, NULL, NULL, datetime('now'), datetime('now'))`,
|
|
299
|
+
["node_legacy_alpha", NET_ALPHA, JSON.stringify({ role: "host_supervisor" })],
|
|
300
|
+
);
|
|
301
|
+
// Seed active token so the EXISTS guard lets it through
|
|
302
|
+
db.run(
|
|
303
|
+
`INSERT INTO api_tokens (token_id, user_id, network_id, scope, name, token_hash)
|
|
304
|
+
VALUES ('tok_legacy', 'u_seed_legacy', ?1, 'network', 'node:legacy', 'hash_legacy')`,
|
|
305
|
+
[NET_ALPHA],
|
|
306
|
+
);
|
|
307
|
+
|
|
308
|
+
const handler = buildToolHandler(userA);
|
|
309
|
+
const reply = await callList(handler, { network_id: NET_ALPHA });
|
|
310
|
+
const d = reply.daemons?.find(d => d.alias === "legacy");
|
|
311
|
+
expect(d).toBeTruthy();
|
|
312
|
+
expect(d.runtimes_supported).toEqual([]);
|
|
313
|
+
expect(d.allowed_secret_keys).toEqual([]);
|
|
314
|
+
});
|
|
315
|
+
});
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
// #476(#469 MCP 审计的最后一项)—— Hub MCP 面的上下文成本。
|
|
2
|
+
//
|
|
3
|
+
// 钉住:
|
|
4
|
+
// 1. tools/list 的总字节有上限(TOOLS_LIST_MAX_BYTES):描述 / 参数说明不能悄悄长回去。每个工具也有上限,
|
|
5
|
+
// 单条工具描述有上限。要加新工具 / 新说明,改这里的数字 —— 改的时候就会被看见。
|
|
6
|
+
// 2. requirements_events 不带 requirement_id(全网动态)默认 50 条、从新到旧、next_cursor 翻更早的;
|
|
7
|
+
// 带 requirement_id 的单卡调用不变(默认 200);REST /api/requirements/events 不变(默认 200,App 用它)。
|
|
8
|
+
// 3. requirements_events 参数严格:不认识的参数 → -32602,列出能用的参数。
|
|
9
|
+
//
|
|
10
|
+
// 跑法:cd server && COMMHUB_DB=/tmp/x.db bun test src/mcp-context-cost-http.test.ts
|
|
11
|
+
// PG:COMMHUB_TEST_PG_URL=… COMMHUB_PG_EXPERIMENTAL=1(tests/test2123-hub-postgres-ladder 里注册)
|
|
12
|
+
import { afterAll, beforeAll, describe, expect, test } from "bun:test";
|
|
13
|
+
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
|
14
|
+
import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
|
|
15
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
16
|
+
import { register } from "./auth.js";
|
|
17
|
+
import { registerTools } from "./tools.js";
|
|
18
|
+
|
|
19
|
+
const activeDbPath = process.env.COMMHUB_DB ?? (process.env.COMMHUB_TEST_PG_URL ? "postgres" : undefined);
|
|
20
|
+
if (!activeDbPath) throw new Error("mcp-context-cost requires COMMHUB_DB (or COMMHUB_TEST_PG_URL) before module import");
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* tools/list 整份 JSON 的字节上限。#476 之前(main,含 #475)74 个工具 76,824 B;修剪后 71,399 B。
|
|
24
|
+
* #478 起 tools/list 按调用者给:这里的调用者是用户令牌,看到 56 个工具 54,780 B(不含节点 / 协议工具)。
|
|
25
|
+
* 上限跟着收到用户这一档(~1.7 KB 余量);节点 / 全部工具的上限在 tool-audience-http.test.ts。
|
|
26
|
+
* 加工具或加说明超过它,就在这里改数字并在 PR 里说为什么。
|
|
27
|
+
*/
|
|
28
|
+
// Board #625: two human adoption tools; measured 58 tools / 56,615 B.
|
|
29
|
+
// Hub #938 clone_node is audience both (60 tools / 58,169 B). OpenCode V2
|
|
30
|
+
// catalog adds read_opencode_catalog and get_opencode_catalog on that user
|
|
31
|
+
// list. Measured together: 62 tools / 59,409 B. Ceiling keeps ~401 B.
|
|
32
|
+
// #1894(2026-10-23):新增 `departments` 一个工具(组织架构的 list/create/update/
|
|
33
|
+
// delete/assign_agent 合并成一个,避免 5 个工具把上下文顶穿)。实测 63 个工具
|
|
34
|
+
// 60,089 B,比原上限高 279 B —— 这是**有意的功能增长**,不是描述悄悄变长,
|
|
35
|
+
// 所以显式抬到 60_500(留 411 B 余量)并在同一行写清理由。
|
|
36
|
+
const TOOLS_LIST_MAX_BYTES = 60_500;
|
|
37
|
+
/** 单个工具(名字 + 描述 + 输入 schema)的上限;最大的是 report_status(节点心跳,~8.4 KB 的遥测结构)。 */
|
|
38
|
+
const TOOL_MAX_BYTES = 9_000;
|
|
39
|
+
/** 单条工具描述的上限(说明写进参数的 describe,或者拆短)。 */
|
|
40
|
+
const DESCRIPTION_MAX_BYTES = 1_000;
|
|
41
|
+
const NETWORK_EVENTS = 80;
|
|
42
|
+
|
|
43
|
+
let server: any;
|
|
44
|
+
let base = "";
|
|
45
|
+
let token = "", netId = "";
|
|
46
|
+
let close: () => Promise<void>;
|
|
47
|
+
let client: Client;
|
|
48
|
+
const call = async (name: string, args: Record<string, unknown>) => {
|
|
49
|
+
const r: any = await client.callTool({ name, arguments: args });
|
|
50
|
+
const text = String(r.content?.[0]?.text ?? "");
|
|
51
|
+
return r.isError ? { mcpError: true, text } : { ...JSON.parse(text), _bytes: Buffer.byteLength(text, "utf8") };
|
|
52
|
+
};
|
|
53
|
+
let busyId = "";
|
|
54
|
+
|
|
55
|
+
beforeAll(async () => {
|
|
56
|
+
const u = register(`ctx_${Date.now()}`, "CtxCost123!", undefined, "seed");
|
|
57
|
+
token = u.token!; netId = u.network_id!;
|
|
58
|
+
const s = new McpServer({ name: "ctx", version: "1" });
|
|
59
|
+
registerTools(s, undefined, null, u.user!.user_id, u.user!.username, false, "tok_user");
|
|
60
|
+
client = new Client({ name: "ctx-client", version: "1" });
|
|
61
|
+
const [ct, st] = InMemoryTransport.createLinkedPair();
|
|
62
|
+
await s.connect(st);
|
|
63
|
+
await client.connect(ct);
|
|
64
|
+
close = async () => { await client.close(); await s.close(); };
|
|
65
|
+
const mod: any = await import("./server.js");
|
|
66
|
+
server = mod.bootServer({ port: 0, hostname: "127.0.0.1" });
|
|
67
|
+
base = `http://127.0.0.1:${server.port}`;
|
|
68
|
+
// 一张卡上 60 条评论(单卡调用要能拿到 > 50 条),再加 20 张卡各一条
|
|
69
|
+
const busy = await call("requirements_create", { network_id: netId, name: "busy task" });
|
|
70
|
+
busyId = busy.requirement.id;
|
|
71
|
+
for (let i = 0; i < 60; i++) expect((await call("requirements_comment", { network_id: netId, id: busyId, text: `进展 ${i}:这一步完成了` })).ok).toBe(true);
|
|
72
|
+
for (let i = 0; i < NETWORK_EVENTS - 60; i++) {
|
|
73
|
+
const r = await call("requirements_create", { network_id: netId, name: `task ${i}` });
|
|
74
|
+
await call("requirements_comment", { network_id: netId, id: r.requirement.id, text: "已开始" });
|
|
75
|
+
}
|
|
76
|
+
}, 120_000);
|
|
77
|
+
afterAll(async () => { await close?.(); server?.stop?.(true); });
|
|
78
|
+
|
|
79
|
+
describe("#476 tools/list size", () => {
|
|
80
|
+
test("total, per tool and per description stay under their ceilings", async () => {
|
|
81
|
+
const { tools } = await client.listTools();
|
|
82
|
+
const total = Buffer.byteLength(JSON.stringify({ tools }), "utf8");
|
|
83
|
+
const sizes = tools.map((t: any) => ({ name: t.name, all: Buffer.byteLength(JSON.stringify(t)), desc: Buffer.byteLength(t.description ?? "") }));
|
|
84
|
+
sizes.sort((a, b) => b.all - a.all);
|
|
85
|
+
console.log(`tools/list: ${tools.length} tools, ${total} B; largest ${sizes.slice(0, 3).map(x => `${x.name}=${x.all}`).join(", ")}`);
|
|
86
|
+
expect(total).toBeLessThanOrEqual(TOOLS_LIST_MAX_BYTES);
|
|
87
|
+
for (const x of sizes) {
|
|
88
|
+
expect(x.all, x.name).toBeLessThanOrEqual(TOOL_MAX_BYTES);
|
|
89
|
+
expect(x.desc, x.name).toBeLessThanOrEqual(DESCRIPTION_MAX_BYTES);
|
|
90
|
+
}
|
|
91
|
+
});
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
describe("#476 requirements_events defaults", () => {
|
|
95
|
+
test("network-wide: 50 newest by default, next_cursor pages older events", async () => {
|
|
96
|
+
const p1 = await call("requirements_events", { network_id: netId });
|
|
97
|
+
expect(p1.events.length).toBe(50);
|
|
98
|
+
expect(typeof p1.next_cursor).toBe("string");
|
|
99
|
+
const times = p1.events.map((e: any) => e.at ?? e.created_at);
|
|
100
|
+
expect([...times].sort().reverse()).toEqual(times);
|
|
101
|
+
const p2 = await call("requirements_events", { network_id: netId, cursor: p1.next_cursor });
|
|
102
|
+
const ids = new Set([...p1.events, ...p2.events].map((e: any) => e.id));
|
|
103
|
+
expect(ids.size).toBe(p1.events.length + p2.events.length);
|
|
104
|
+
console.log(`network events page of 50: ${p1._bytes} B`);
|
|
105
|
+
expect(p1._bytes).toBeLessThan(25_000);
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
test("an explicit limit still wins; one task's timeline keeps its old default (200)", async () => {
|
|
109
|
+
expect((await call("requirements_events", { network_id: netId, limit: 70 })).events.length).toBe(70);
|
|
110
|
+
const one = await call("requirements_events", { network_id: netId, requirement_id: busyId });
|
|
111
|
+
expect(one.events.filter((e: any) => e.kind === "comment").length).toBe(60);
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
test("REST GET /api/requirements/events is unchanged (default 200)", async () => {
|
|
115
|
+
const res = await fetch(`${base}/api/requirements/events?network_id=${netId}`, { headers: { Authorization: `Bearer ${token}` } });
|
|
116
|
+
const body = await res.json() as any;
|
|
117
|
+
expect(res.status).toBe(200);
|
|
118
|
+
expect(body.events.length).toBeGreaterThan(50);
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
test("unknown parameters → -32602 listing the valid ones", async () => {
|
|
122
|
+
const r = await call("requirements_events", { network_id: netId, task_id: busyId });
|
|
123
|
+
expect(r.mcpError).toBe(true);
|
|
124
|
+
expect(r.text).toContain("-32602");
|
|
125
|
+
expect(r.text).toContain("unknown parameter(s): task_id; valid parameters: network_id, requirement_id, since, limit, cursor");
|
|
126
|
+
});
|
|
127
|
+
});
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
// #2363 —— MCP 在飞计数的单测 + 源码断言。
|
|
2
|
+
//
|
|
3
|
+
// 计数值本身很小,但它是“RSS 尖峰能不能被解释”的唯一在线指标:`sse_connections`
|
|
4
|
+
// 只反映长连接,看不到同秒打进来的一批短请求。这里钉住三件事:
|
|
5
|
+
// 1. enter/leave 必须配平(含重复 leave 不把计数打成负数);
|
|
6
|
+
// 2. 峰值要能记住高水位,并能被显式重置;
|
|
7
|
+
// 3. server.ts 必须在**任何 await 之前**进入计数,并且在“正常关闭 / 抛异常”
|
|
8
|
+
// 两条路径上都退出计数——少一条就会让指标永远偏高,比没有指标更糟。
|
|
9
|
+
|
|
10
|
+
import { describe, expect, test, beforeEach } from "bun:test";
|
|
11
|
+
import { readFileSync } from "node:fs";
|
|
12
|
+
import { join } from "node:path";
|
|
13
|
+
import {
|
|
14
|
+
enterMcpInflight,
|
|
15
|
+
leaveMcpInflight,
|
|
16
|
+
getMcpInflightStats,
|
|
17
|
+
resetMcpInflightPeak,
|
|
18
|
+
} from "./mcp-inflight.js";
|
|
19
|
+
|
|
20
|
+
beforeEach(() => {
|
|
21
|
+
// 模块级单例:每个用例从 0 开始,避免用例顺序影响。
|
|
22
|
+
while (getMcpInflightStats().inflight > 0) leaveMcpInflight();
|
|
23
|
+
resetMcpInflightPeak();
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
describe("#2363 mcp inflight counter", () => {
|
|
27
|
+
test("enter/leave 配平,peak 记住高水位且不自己回落", () => {
|
|
28
|
+
expect(getMcpInflightStats()).toEqual({ inflight: 0, peak: 0 });
|
|
29
|
+
enterMcpInflight();
|
|
30
|
+
enterMcpInflight();
|
|
31
|
+
enterMcpInflight();
|
|
32
|
+
expect(getMcpInflightStats()).toEqual({ inflight: 3, peak: 3 });
|
|
33
|
+
leaveMcpInflight();
|
|
34
|
+
leaveMcpInflight();
|
|
35
|
+
// 当前只有 1 条在飞,但峰值仍是 3 —— 峰值是“撞过悬崖没有”的证据。
|
|
36
|
+
expect(getMcpInflightStats()).toEqual({ inflight: 1, peak: 3 });
|
|
37
|
+
leaveMcpInflight();
|
|
38
|
+
expect(getMcpInflightStats()).toEqual({ inflight: 0, peak: 3 });
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
test("多余的 leave 不会把计数打成负数", () => {
|
|
42
|
+
leaveMcpInflight();
|
|
43
|
+
leaveMcpInflight();
|
|
44
|
+
expect(getMcpInflightStats().inflight).toBe(0);
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
test("reset 把峰值对齐到当前在飞数(不会把峰值压到低于现况)", () => {
|
|
48
|
+
enterMcpInflight();
|
|
49
|
+
enterMcpInflight();
|
|
50
|
+
expect(getMcpInflightStats().peak).toBe(2);
|
|
51
|
+
leaveMcpInflight();
|
|
52
|
+
resetMcpInflightPeak();
|
|
53
|
+
expect(getMcpInflightStats()).toEqual({ inflight: 1, peak: 1 });
|
|
54
|
+
});
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
describe("#2363 server wiring (source assertions)", () => {
|
|
58
|
+
const src = readFileSync(join(import.meta.dir, "server.ts"), "utf8");
|
|
59
|
+
|
|
60
|
+
test("进入计数发生在创建 transport 之前(请求体解析阶段也要计入)", () => {
|
|
61
|
+
const enterAt = src.indexOf("enterMcpInflight();");
|
|
62
|
+
const transportAt = src.indexOf("new WebStandardStreamableHTTPServerTransport({", enterAt);
|
|
63
|
+
expect(enterAt).toBeGreaterThan(0);
|
|
64
|
+
expect(transportAt).toBeGreaterThan(enterAt);
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
test("两条退出路径都在:handleRequest 抛异常时、以及 MCP server 关闭后", () => {
|
|
68
|
+
// 抛异常路径
|
|
69
|
+
expect(src).toContain("settleMcpInflight();\n throw e;");
|
|
70
|
+
// 正常路径(setImmediate 里 close 完成后结算,且重复调用安全)
|
|
71
|
+
expect(src).toContain("mcpServer.close().catch(() => {}).finally(settleMcpInflight)");
|
|
72
|
+
// 幂等闸门:只允许真正减一次
|
|
73
|
+
expect(src).toContain("if (mcpInflightSettled) return;");
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
test("/health 暴露的是聚合值(匿名也安全),且没有 new 的按会话明细", () => {
|
|
77
|
+
expect(src).toContain("mcp_inflight: getMcpInflightStats().inflight,");
|
|
78
|
+
expect(src).toContain("mcp_inflight_peak: getMcpInflightStats().peak,");
|
|
79
|
+
expect(src).not.toContain("mcp_inflight_sessions");
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
test("这一版只观测:/mcp 入口不得出现 429 / 拒绝分支", () => {
|
|
83
|
+
const mcpStart = src.indexOf('if (url.pathname === "/mcp") {');
|
|
84
|
+
const mcpEnd = src.indexOf("// ── #461 SSE network observer stream ──", mcpStart);
|
|
85
|
+
expect(mcpStart).toBeGreaterThan(0);
|
|
86
|
+
expect(mcpEnd).toBeGreaterThan(mcpStart);
|
|
87
|
+
const block = src.slice(mcpStart, mcpEnd);
|
|
88
|
+
expect(block).not.toContain("429");
|
|
89
|
+
expect(block).not.toContain("hub_busy");
|
|
90
|
+
expect(block).not.toContain("Retry-After");
|
|
91
|
+
});
|
|
92
|
+
});
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
// #2363 —— MCP 在飞计数(先只观测,不拦请求)。
|
|
2
|
+
//
|
|
3
|
+
// 为什么需要它:隔离 Hub 上用**生产库副本**实测,RSS 与“同时在飞的 MCP 请求数”
|
|
4
|
+
// 成正比(≈1.2–1.4 MB/条;`send_message` 与 `get_inbox` 同形),而与吞吐无关——
|
|
5
|
+
// 顺序发 3,255 条/60s(≈54 条/秒)时 RSS 稳定在 151–156 MB,而 50/100/200 并发
|
|
6
|
+
// 的峰值是 249/446/689 MB。`/health` 里的 `sse_connections` 只反映长连接,看不到
|
|
7
|
+
// 这个量,所以生产上“为什么 RSS 突然抬到 450 MB”一直只能事后猜。
|
|
8
|
+
//
|
|
9
|
+
// 本模块只做计数与峰值,**不拒绝、不排队、不改任何响应**——限流(有界队列 + 429)
|
|
10
|
+
// 是另一步,需要先有一天的真实分布再定上限。见 docs/runbooks/hub-memory-and-sse.md。
|
|
11
|
+
|
|
12
|
+
let inflight = 0;
|
|
13
|
+
let peak = 0;
|
|
14
|
+
|
|
15
|
+
/** /mcp 进入时调用(在任何 await 之前,保证计入请求体解析阶段)。 */
|
|
16
|
+
export function enterMcpInflight(): void {
|
|
17
|
+
inflight += 1;
|
|
18
|
+
if (inflight > peak) peak = inflight;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** /mcp 结束时调用(响应对象产出且 MCP server 已关闭);重复调用安全。 */
|
|
22
|
+
export function leaveMcpInflight(): void {
|
|
23
|
+
if (inflight > 0) inflight -= 1;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* 当前在飞数与**自上次 reset 以来的峰值**。
|
|
28
|
+
* 峰值是“滚动高水位”,不会自己回落——运维看它判断是否撞到过悬崖,
|
|
29
|
+
* 看 `inflight` 判断现在是否还在里面。
|
|
30
|
+
*/
|
|
31
|
+
export function getMcpInflightStats(): { inflight: number; peak: number } {
|
|
32
|
+
return { inflight, peak };
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** 把峰值重置为当前在飞数(运维定位完一次尖峰后调用,或测试用)。 */
|
|
36
|
+
export function resetMcpInflightPeak(): void {
|
|
37
|
+
peak = inflight;
|
|
38
|
+
}
|