@sleep2agi/commhub-server 0.9.0-preview.25 → 0.9.0-preview.250
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 +129 -9
- package/bin/commhub.ts +93 -9
- package/build-info.json +7 -0
- package/package.json +10 -8
- package/src/ack-create-request-transport.test.ts +182 -0
- package/src/ack-create-request.test.ts +52 -8
- 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 +140 -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 +675 -0
- package/src/agent-acl-slice3-http.test.ts +717 -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 +6 -7
- package/src/api-host-supervisors-runtime-readiness.test.ts +195 -0
- package/src/api-nodes-shape.test.ts +95 -4
- package/src/auth-password-change-cli-tokens-http.test.ts +423 -0
- package/src/auth-sessions-http.test.ts +260 -0
- package/src/auth-validate.test.ts +5 -1
- package/src/auth-weak-password-login.test.ts +176 -0
- package/src/auth.ts +609 -51
- package/src/avatar-validate.test.ts +52 -2
- package/src/avatar-validate.ts +35 -1
- package/src/backfill-node-ids-2664.test.ts +128 -0
- package/src/binding-generation-http.test.ts +132 -0
- package/src/blocked-exit-on-reply.test.ts +122 -0
- package/src/broadcast-fanout-2721.test.ts +149 -0
- package/src/broadcast-fanout.ts +117 -0
- package/src/build-info.test.ts +60 -0
- package/src/build-info.ts +85 -0
- package/src/chain-attempt-dedup.test.ts +447 -0
- package/src/clip.test.ts +36 -0
- package/src/clip.ts +48 -0
- package/src/clone-node.test.ts +262 -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-validate.test.ts +188 -1
- package/src/config-apply-validate.ts +222 -3
- package/src/cors-origins.test.ts +73 -0
- package/src/create-node-blocked-gate.test.ts +356 -0
- package/src/create-node-network-id.test.ts +91 -0
- package/src/create-node-tool-schema.test.ts +49 -0
- package/src/create-node-unicode-name.test.ts +126 -0
- package/src/create-node-validate.test.ts +199 -7
- package/src/create-node-validate.ts +232 -15
- package/src/create-node-workdir.test.ts +298 -0
- package/src/create-node.ts +88 -23
- package/src/daemon-provider-snapshots.test.ts +445 -0
- package/src/daemon-provider-snapshots.ts +327 -0
- package/src/daemon-token-owner-http.test.ts +292 -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 +1264 -153
- 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 +350 -0
- package/src/department-heads.ts +226 -0
- package/src/departments-agent-count.test.ts +132 -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 +240 -0
- package/src/env-transport-gate.ts +80 -0
- package/src/env-transport-policy.ts +56 -0
- package/src/etag-of.test.ts +57 -0
- package/src/event-loop-lag.test.ts +180 -0
- package/src/event-loop-lag.ts +201 -0
- package/src/expiry-counters.test.ts +111 -0
- package/src/expiry-counters.ts +93 -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 +1 -1
- package/src/file-download-authz.test.ts +73 -18
- package/src/file-download-date-bucket.test.ts +8 -26
- 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 +483 -0
- package/src/group-messages.ts +297 -0
- package/src/health-anon-readers.ts +60 -0
- package/src/health-host-disk-2756.test.ts +71 -0
- package/src/health-redaction.test.ts +1541 -7
- 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 +641 -0
- package/src/hub-provider-config.test.ts +166 -0
- package/src/hub-provider-config.ts +202 -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 +6 -2
- package/src/license-state.test.ts +56 -0
- package/src/license-state.ts +48 -0
- package/src/list-host-supervisors.test.ts +15 -4
- 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 +165 -0
- package/src/mcp-route-label-http.test.ts +120 -0
- package/src/mcp-write-network-resolution.test.ts +435 -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 +186 -0
- package/src/node-alias-control.ts +12 -0
- package/src/node-attrs.test.ts +47 -2
- package/src/node-caller-identity-http.test.ts +1108 -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 +347 -0
- package/src/node-health-codex-login.test.ts +120 -0
- package/src/node-health-dispatch-http.test.ts +373 -0
- package/src/node-health-guard.ts +121 -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 +257 -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 +114 -0
- package/src/node-permissions-http.test.ts +728 -0
- package/src/node-permissions.ts +494 -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 +212 -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 +102 -9
- package/src/observer-push.test.ts +76 -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 +356 -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 +462 -0
- package/src/peer-reply-capability.test.ts +70 -0
- package/src/pg-worker.ts +87 -0
- package/src/poll-pacing.test.ts +74 -0
- package/src/poll-pacing.ts +123 -0
- package/src/project-dir-warn-clear-http.test.ts +132 -0
- package/src/project-viewer-can-http.test.ts +116 -0
- package/src/provider-tools-shape.test.ts +150 -0
- package/src/push.test.ts +20 -10
- package/src/push.ts +373 -9
- package/src/redact-tokens.test.ts +86 -0
- package/src/redact-tokens.ts +43 -0
- package/src/rejection-counters.test.ts +72 -0
- package/src/rejection-counters.ts +173 -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 +318 -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 +454 -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-assignee-drift.test.ts +154 -0
- package/src/requirements-comment-http.test.ts +174 -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 +164 -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-network-echo.test.ts +57 -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 +2205 -0
- package/src/resolve-port.test.ts +57 -0
- package/src/resolve-port.ts +44 -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 +218 -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 +475 -0
- package/src/schedule-agent.ts +252 -0
- package/src/schedule-starved.test.ts +92 -0
- package/src/schedule-starved.ts +114 -0
- package/src/scheduled-backoff-http.test.ts +203 -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 +425 -0
- package/src/scheduled-noprogress-backoff-2622.test.ts +163 -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 +285 -0
- package/src/scheduled-requirement-wake.ts +125 -0
- package/src/scheduled-run-terminal.test.ts +290 -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 +316 -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 +141 -0
- package/src/secret-echo-negative-control.test.ts +118 -0
- package/src/send-dedup-request-id.test.ts +229 -0
- package/src/send-reply-agent-warning.test.ts +38 -38
- 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 +73 -0
- package/src/serve-error.ts +56 -0
- package/src/server.ts +5134 -503
- 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 +45 -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 +10 -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 +142 -0
- package/src/sqlite-close-checkpoint.test.ts +78 -0
- package/src/start-node.test.ts +265 -0
- package/src/stats-versions-http.test.ts +65 -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 +129 -0
- package/src/stop-delete-node.test.ts +567 -1
- 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 +498 -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 +318 -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 +227 -0
- package/src/task-lifecycle-watcher-busy.test.ts +114 -0
- package/src/task-lifecycle-watcher.test.ts +209 -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 +61 -0
- package/src/task-sender-http.test.ts +143 -0
- package/src/task-stale-open-http.test.ts +292 -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/tmux-allowlist.test.ts +48 -0
- package/src/tool-audience-http.test.ts +230 -0
- package/src/tool-audience.ts +127 -0
- package/src/tools-list-json-schema.test.ts +94 -0
- package/src/tools.ts +4326 -420
- package/src/upload-early-reject-guard.test.ts +155 -0
- package/src/uploads-http.test.ts +86 -7
- package/src/uploads.ts +38 -4
- 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 +165 -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/version-stats.test.ts +66 -0
- package/src/version-stats.ts +109 -0
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
// Agent(节点)显式归属部门 —— `PUT /api/networks/:net/nodes/:nodeId/department`。
|
|
2
|
+
//
|
|
3
|
+
// 2026-10-19 现网:组织架构页 4 个部门各「0 个 Agent」、328 个 Agent 全在「未归属」。
|
|
4
|
+
// 原因不是没人管,而是后端**没有**「Agent 属于哪个部门」这个字段:那时的口径只有
|
|
5
|
+
// 「负责人(人)在哪个部门」,于是没有负责人 / 负责人不在部门树里的 Agent 只能算未归属。
|
|
6
|
+
//
|
|
7
|
+
// 这组用例钉住:
|
|
8
|
+
// 1. owner 能把 Agent 放进部门、能改、能清空;
|
|
9
|
+
// 2. 清空后回到「按负责人的部门推断」的旧口径(directory 里 department_id 为 null);
|
|
10
|
+
// 3. 别的网络的部门 / 不存在的部门 / 不存在的节点都被拒;
|
|
11
|
+
// 4. 普通成员不能改;本部门负责人只能在子树内调动;
|
|
12
|
+
// 5. 通讯录(/api/requirements/people/directory)会把显式部门带给客户端。
|
|
13
|
+
import { describe, expect, test, beforeAll, afterAll } from "bun:test";
|
|
14
|
+
import { mkdtempSync, rmSync } from "fs";
|
|
15
|
+
import { join } from "path";
|
|
16
|
+
import { tmpdir } from "os";
|
|
17
|
+
import { register } from "./auth.js";
|
|
18
|
+
import { db } from "./db.js";
|
|
19
|
+
|
|
20
|
+
const DIR = mkdtempSync(join(tmpdir(), "anet-agent-dept-"));
|
|
21
|
+
let BASE = "";
|
|
22
|
+
let hub: any = null;
|
|
23
|
+
const PW = "AgentDeptPassw0rd!xyz";
|
|
24
|
+
let NET = "";
|
|
25
|
+
let OTHER_NET = "";
|
|
26
|
+
const U: Record<string, { token: string; id: string }> = {};
|
|
27
|
+
const D: Record<string, string> = {};
|
|
28
|
+
let NODE_A = "";
|
|
29
|
+
let NODE_OUTSIDE = "";
|
|
30
|
+
|
|
31
|
+
async function send(token: string, method: string, path: string, body?: unknown) {
|
|
32
|
+
const res = await fetch(`${BASE}${path}`, {
|
|
33
|
+
method,
|
|
34
|
+
headers: token ? { Authorization: `Bearer ${token}`, "Content-Type": "application/json" } : { "Content-Type": "application/json" },
|
|
35
|
+
body: body === undefined ? undefined : JSON.stringify(body),
|
|
36
|
+
});
|
|
37
|
+
const text = await res.text();
|
|
38
|
+
let json: any = null;
|
|
39
|
+
try { json = JSON.parse(text); } catch {}
|
|
40
|
+
return { status: res.status, body: json };
|
|
41
|
+
}
|
|
42
|
+
const setDept = (token: string, nodeId: string, department_id: string | null) =>
|
|
43
|
+
send(token, "PUT", `/api/networks/${NET}/nodes/${nodeId}/department`, { department_id });
|
|
44
|
+
const dept = (token: string, method: string, path = "", body?: unknown) =>
|
|
45
|
+
send(token, method, `/api/networks/${NET}/departments${path}`, body);
|
|
46
|
+
|
|
47
|
+
function agentRow(nodeId: string) {
|
|
48
|
+
return db.get<{ department_id: string | null }>("SELECT department_id FROM nodes WHERE node_id = ?1", nodeId);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
beforeAll(async () => {
|
|
52
|
+
process.env.COMMHUB_DB ||= join(DIR, "hub.db");
|
|
53
|
+
process.env.COMMHUB_UPLOADS_DIR = join(DIR, "uploads");
|
|
54
|
+
process.env.HOST = "127.0.0.1";
|
|
55
|
+
const a = register(`ad_owner_${Date.now()}`, PW, undefined, "Owner");
|
|
56
|
+
U.owner = { token: a.token!, id: a.user!.user_id };
|
|
57
|
+
NET = a.network_id!;
|
|
58
|
+
db.run("UPDATE users SET role = 'admin' WHERE user_id = ?1", [U.owner.id]);
|
|
59
|
+
const mod: any = await import("./server.js");
|
|
60
|
+
hub = mod.bootServer({ port: 0, hostname: "127.0.0.1" });
|
|
61
|
+
BASE = `http://127.0.0.1:${hub.port}`;
|
|
62
|
+
|
|
63
|
+
// 第二个网络:用来钉「别的网络的部门不能被借来用」。
|
|
64
|
+
OTHER_NET = `net_other_${Date.now()}`;
|
|
65
|
+
db.run("INSERT INTO networks (network_id, network_name, owner_id) VALUES (?1, ?1, ?2)", [OTHER_NET, U.owner.id]);
|
|
66
|
+
db.run("INSERT INTO network_members (network_id, user_id, role) VALUES (?1, ?2, 'owner')", [OTHER_NET, U.owner.id]);
|
|
67
|
+
db.run("INSERT INTO network_departments (network_id, department_id, name, sort, created_by) VALUES (?1, 'dept_other', '别的网', 0, ?2)", [OTHER_NET, U.owner.id]);
|
|
68
|
+
|
|
69
|
+
// 两个部门 + 一个普通成员
|
|
70
|
+
const made = await dept(U.owner.token, "POST", "", { name: "TMAI" });
|
|
71
|
+
expect([200, 201]).toContain(made.status);
|
|
72
|
+
D.tmai = made.body.department.id;
|
|
73
|
+
const made2 = await dept(U.owner.token, "POST", "", { name: "A 站" });
|
|
74
|
+
expect([200, 201]).toContain(made2.status);
|
|
75
|
+
D.a = made2.body.department.id;
|
|
76
|
+
|
|
77
|
+
const stamp = Date.now();
|
|
78
|
+
expect((await send(U.owner.token, "POST", "/api/admin/users", { username: `ad_member_${stamp}`, password: PW, network_id: NET, role: "member" })).status).toBe(200);
|
|
79
|
+
const login = await send("", "POST", "/api/auth/login", { username: `ad_member_${stamp}`, password: PW });
|
|
80
|
+
U.member = { token: login.body.token, id: login.body.user.user_id };
|
|
81
|
+
|
|
82
|
+
// 两个节点:一个在本网络(无负责人),一个属于别的网络。
|
|
83
|
+
NODE_A = `n_ad_${stamp}`;
|
|
84
|
+
NODE_OUTSIDE = `n_ad_out_${stamp}`;
|
|
85
|
+
db.run(
|
|
86
|
+
"INSERT INTO nodes (node_id, node_name, alias, network_id, created_at, updated_at) VALUES (?1, '测试员 3 号', '测试员 3 号', ?2, datetime('now'), datetime('now'))",
|
|
87
|
+
[NODE_A, NET],
|
|
88
|
+
);
|
|
89
|
+
db.run(
|
|
90
|
+
"INSERT INTO nodes (node_id, node_name, alias, network_id, created_at, updated_at) VALUES (?1, '别的网的节点', '别的网的节点', ?2, datetime('now'), datetime('now'))",
|
|
91
|
+
[NODE_OUTSIDE, OTHER_NET],
|
|
92
|
+
);
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
afterAll(() => {
|
|
96
|
+
try { hub?.stop?.(true); } catch {}
|
|
97
|
+
rmSync(DIR, { recursive: true, force: true });
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
describe("Agent 显式归属部门", () => {
|
|
101
|
+
test("owner 把 Agent 放进部门 → 落库;再改到另一个部门 → 跟随", async () => {
|
|
102
|
+
const first = await setDept(U.owner.token, NODE_A, D.tmai);
|
|
103
|
+
expect(first.status).toBe(200);
|
|
104
|
+
expect(first.body).toMatchObject({ ok: true, node_id: NODE_A, department_id: D.tmai });
|
|
105
|
+
expect(agentRow(NODE_A)!.department_id).toBe(D.tmai);
|
|
106
|
+
|
|
107
|
+
const moved = await setDept(U.owner.token, NODE_A, D.a);
|
|
108
|
+
expect(moved.status).toBe(200);
|
|
109
|
+
expect(agentRow(NODE_A)!.department_id).toBe(D.a);
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
test("清空(null / 空串)→ 回到「按负责人推断」的口径", async () => {
|
|
113
|
+
expect((await setDept(U.owner.token, NODE_A, D.tmai)).status).toBe(200);
|
|
114
|
+
const cleared = await setDept(U.owner.token, NODE_A, null);
|
|
115
|
+
expect(cleared.status).toBe(200);
|
|
116
|
+
expect(cleared.body.department_id).toBeNull();
|
|
117
|
+
expect(agentRow(NODE_A)!.department_id).toBeNull();
|
|
118
|
+
|
|
119
|
+
expect((await setDept(U.owner.token, NODE_A, D.tmai)).status).toBe(200);
|
|
120
|
+
expect((await setDept(U.owner.token, NODE_A, "")).body.department_id).toBeNull();
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
test("拒绝:别的网络的部门 / 不存在的部门 / 不存在的节点 / 别的网络的节点", async () => {
|
|
124
|
+
expect((await setDept(U.owner.token, NODE_A, "dept_other")).status).toBe(400);
|
|
125
|
+
expect((await setDept(U.owner.token, NODE_A, "dept_nope")).status).toBe(400);
|
|
126
|
+
expect((await setDept(U.owner.token, "n_nope", D.tmai)).status).toBe(404);
|
|
127
|
+
expect((await setDept(U.owner.token, NODE_OUTSIDE, D.tmai)).status).toBe(404);
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
// #2965 —— 同 alias 多 node 行必须在通讯录里折叠成一行,并给出「历史注册」计数。
|
|
131
|
+
// 现场:一组同名里只有一个挂过会话,其余是重复注册留下的空行;页面看起来就是「重复的 Agent」。
|
|
132
|
+
// 折叠不能只看 updated_at —— 实测那 3 个 node 的 updated_at 完全相同,必须优先保留有会话的那条。
|
|
133
|
+
test("同 alias 多 node:不删行,但其余行带 duplicate_of 指向首选(有会话者优先)", async () => {
|
|
134
|
+
const now = Date.now();
|
|
135
|
+
const dupAlias = `重复-Agent-${now}`;
|
|
136
|
+
const live = `n_live_${now}`;
|
|
137
|
+
const dead1 = `n_dead1_${now}`;
|
|
138
|
+
const dead2 = `n_dead2_${now}`;
|
|
139
|
+
// 三条 updated_at 完全一样(现场就是这样),只有 live 有会话行
|
|
140
|
+
for (const id of [dead2, live, dead1]) {
|
|
141
|
+
db.run(
|
|
142
|
+
"INSERT INTO nodes (node_id, node_name, alias, network_id, created_at, updated_at) VALUES (?1, ?2, ?2, ?3, datetime('now'), '2026-10-26 12:26:22')",
|
|
143
|
+
[id, dupAlias, NET],
|
|
144
|
+
);
|
|
145
|
+
}
|
|
146
|
+
db.run(
|
|
147
|
+
"INSERT INTO sessions (resume_id, alias, status, network_id, node_id, updated_at) VALUES (?1, ?2, 'offline', ?3, ?4, datetime('now'))",
|
|
148
|
+
[`s_${live}`, dupAlias, NET, live],
|
|
149
|
+
);
|
|
150
|
+
|
|
151
|
+
const dir = await send(U.owner.token, "GET", `/api/requirements/people/directory?network_id=${NET}`);
|
|
152
|
+
expect(dir.status).toBe(200);
|
|
153
|
+
const agents = [...(dir.body.people ?? []).flatMap((p: any) => p.agents ?? []), ...(dir.body.agents_without_owner ?? [])];
|
|
154
|
+
const rows = agents.filter((a: any) => a.alias === dupAlias);
|
|
155
|
+
// 契约不变:三条都还在(客户端照旧可按 updated_at 去重)
|
|
156
|
+
expect(rows).toHaveLength(3);
|
|
157
|
+
// 新增:其余两条都指向首选,而首选必须是**有会话**的那条(三条 updated_at 完全相同)
|
|
158
|
+
const liveRow = rows.find((a: any) => a.node_id === live);
|
|
159
|
+
expect(liveRow.duplicate_of).toBeUndefined();
|
|
160
|
+
for (const dead of [dead1, dead2]) {
|
|
161
|
+
expect(rows.find((a: any) => a.node_id === dead)?.duplicate_of).toBe(live);
|
|
162
|
+
}
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
test("普通成员改不了(403)", async () => {
|
|
166
|
+
const r = await setDept(U.member.token, NODE_A, D.tmai);
|
|
167
|
+
expect(r.status).toBe(403);
|
|
168
|
+
});
|
|
169
|
+
|
|
170
|
+
test("通讯录把显式部门带给客户端;清空后回到 null", async () => {
|
|
171
|
+
expect((await setDept(U.owner.token, NODE_A, D.a)).status).toBe(200);
|
|
172
|
+
const dir = await send(U.owner.token, "GET", `/api/requirements/people/directory?network_id=${NET}`);
|
|
173
|
+
expect(dir.status).toBe(200);
|
|
174
|
+
const agents = [...(dir.body.people ?? []).flatMap((p: any) => p.agents ?? []), ...(dir.body.agents_without_owner ?? [])];
|
|
175
|
+
const mine = agents.find((a: any) => a.node_id === NODE_A);
|
|
176
|
+
expect(mine?.department_id).toBe(D.a);
|
|
177
|
+
|
|
178
|
+
expect((await setDept(U.owner.token, NODE_A, null)).status).toBe(200);
|
|
179
|
+
const dir2 = await send(U.owner.token, "GET", `/api/requirements/people/directory?network_id=${NET}`);
|
|
180
|
+
const agents2 = [...(dir2.body.people ?? []).flatMap((p: any) => p.agents ?? []), ...(dir2.body.agents_without_owner ?? [])];
|
|
181
|
+
expect(agents2.find((a: any) => a.node_id === NODE_A)?.department_id ?? null).toBeNull();
|
|
182
|
+
});
|
|
183
|
+
|
|
184
|
+
// #1976 —— Agent 归属与人类部门是两个独立的结构。通讯录顶层要说明「这个 Hub 支持显式
|
|
185
|
+
// Agent 部门」,客户端据此把「行里没有 department_id」读成「没有显式归属」,
|
|
186
|
+
// 而不是从「负责人在哪个部门」推断出来。
|
|
187
|
+
// #2888(通信客户端欧 2026-10-28 提)—— 军团按部门分区时,N 个部门要发 N 次
|
|
188
|
+
// `…/departments/:dept/nodes` 才能拼出「每个 Agent 属于哪个部门」,人数一多就慢。
|
|
189
|
+
// 事实上 /api/nodes 早就返回全部节点,只是没 select `department_id` 这一列。
|
|
190
|
+
// 补上之后一次往返就能完成分区初始化。
|
|
191
|
+
test("/api/nodes 一次返回全部节点且带 department_id(免 N 次部门往返)", async () => {
|
|
192
|
+
expect((await send(U.owner.token, "PUT", `/api/networks/${NET}/nodes/${NODE_A}/department`, { department_id: D.tmai })).status).toBe(200);
|
|
193
|
+
const all = await send(U.owner.token, "GET", `/api/nodes?network_id=${NET}`);
|
|
194
|
+
expect(all.status).toBe(200);
|
|
195
|
+
const row = (all.body.nodes ?? []).find((n: any) => n.node_id === NODE_A);
|
|
196
|
+
expect(row).toBeDefined();
|
|
197
|
+
expect(row.department_id).toBe(D.tmai);
|
|
198
|
+
// 未归属的节点这一格是 null(不是缺键)——分区逻辑可以统一按 null 判「未分组」。
|
|
199
|
+
const other = (all.body.nodes ?? []).find((n: any) => n.node_id === NODE_OUTSIDE);
|
|
200
|
+
if (other) expect(other.department_id ?? null).toBeNull();
|
|
201
|
+
});
|
|
202
|
+
|
|
203
|
+
test("通讯录声明支持显式 Agent 部门(与人类部门相互独立)", async () => {
|
|
204
|
+
const dir = await send(U.owner.token, "GET", `/api/requirements/people/directory?network_id=${NET}`);
|
|
205
|
+
expect(dir.status).toBe(200);
|
|
206
|
+
expect(dir.body.agent_department_supported).toBe(true);
|
|
207
|
+
// 行形状不变:没有显式归属的行**不带** department_id 这一格(旧客户端形状不变)。
|
|
208
|
+
const agents = [...(dir.body.people ?? []).flatMap((p: any) => p.agents ?? []), ...(dir.body.agents_without_owner ?? [])];
|
|
209
|
+
for (const a of agents) {
|
|
210
|
+
// 显式归属 ⇒ 带这一格且非空;没有显式归属 ⇒ **不带这一格**(旧客户端形状不变)。
|
|
211
|
+
if (a.department_id) expect(typeof a.department_id).toBe("string");
|
|
212
|
+
else expect(Object.prototype.hasOwnProperty.call(a, "department_id")).toBe(false);
|
|
213
|
+
}
|
|
214
|
+
});
|
|
215
|
+
});
|
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
// Agent 分组的性能守卫(RFC-038 §8):visibleAgents() 每个请求多做一次「组授权 → 组成员」展开,
|
|
2
|
+
// 这里量它的额外开销,并用 EXPLAIN QUERY PLAN 钉住展开查询走索引(不是全表扫)。
|
|
3
|
+
//
|
|
4
|
+
// 场景:NET 里 300 个节点;50 个组,每组 6 个节点(合起来覆盖全部 300 个)。
|
|
5
|
+
// baseline —— bob 直接授权这 300 个节点(没有组);
|
|
6
|
+
// groups —— alice 授权这 50 个组(没有直接授权),可见集合与 bob 完全相同。
|
|
7
|
+
// 两人看到的 Agent 一样多,差值就是「按组展开」本身的代价。团队要求 ≈2 ms 以内(本机实测 −0.5~+1.9 ms);
|
|
8
|
+
// 断言放宽到 max(5 ms, 基线的 15%)—— CI 容器比本机慢时两边一起变慢,绝对差也跟着放大。数字打印出来。
|
|
9
|
+
// #517:差值怎么量见 lowDelta*() —— 交替且每轮翻转先后、样本 40 对、比两边的 p20(不是每轮差值的中位数)、
|
|
10
|
+
// 一轮超标再重量最多 2 轮。界限本身(max(5 ms, 15%))没动。
|
|
11
|
+
|
|
12
|
+
import { describe, expect, test, beforeAll, afterAll } from "bun:test";
|
|
13
|
+
import { mkdtempSync, rmSync } from "fs";
|
|
14
|
+
import { join } from "path";
|
|
15
|
+
import { tmpdir } from "os";
|
|
16
|
+
import { register } from "./auth.js";
|
|
17
|
+
import { db } from "./db.js";
|
|
18
|
+
import { visibleAgents } from "./agent-access.js";
|
|
19
|
+
|
|
20
|
+
const DIR = mkdtempSync(join(tmpdir(), "anet-agent-groups-perf-"));
|
|
21
|
+
let BASE = "";
|
|
22
|
+
let hub: any = null;
|
|
23
|
+
const PW = "GroupPerfPassw0rd!x";
|
|
24
|
+
let NET = "";
|
|
25
|
+
let adminToken = "";
|
|
26
|
+
let adminId = "";
|
|
27
|
+
let alice = { token: "", id: "" };
|
|
28
|
+
let bob = { token: "", id: "" };
|
|
29
|
+
const NODES = 300;
|
|
30
|
+
const GROUPS = 50;
|
|
31
|
+
const PER_GROUP = NODES / GROUPS;
|
|
32
|
+
const BOUND_MS = 5;
|
|
33
|
+
const bound = (base: number) => Math.max(BOUND_MS, base * 0.15);
|
|
34
|
+
// CI 容器里一次 visibleAgents() 约 65 ms(本机约 28 ms):原来 40 次 × 两边再加预热,顶破了 bun 默认的 5 s 单测超时(#2131 CI 实测)。
|
|
35
|
+
// 性能用例另给显式超时(差值守卫最坏 3 轮 × 40 对,见 lowDelta)。
|
|
36
|
+
const WARMUP = 3;
|
|
37
|
+
const PERF_TIMEOUT_MS = 60_000;
|
|
38
|
+
// #517 差值守卫:每轮 DELTA_PAIRS 对、比两边的 LOW_P 分位、超标再量最多 RETRIES 轮。
|
|
39
|
+
const DELTA_PAIRS = 40, LOW_P = 0.2, RETRIES = 2;
|
|
40
|
+
|
|
41
|
+
const json = (token: string) => ({ Authorization: `Bearer ${token}`, "Content-Type": "application/json" });
|
|
42
|
+
async function send(token: string, method: string, path: string, payload?: unknown) {
|
|
43
|
+
const res = await fetch(`${BASE}${path}`, { method, headers: json(token), body: payload === undefined ? undefined : JSON.stringify(payload) });
|
|
44
|
+
return { status: res.status, body: await res.json().catch(() => null) as any };
|
|
45
|
+
}
|
|
46
|
+
const median = (xs: number[]) => { const s = [...xs].sort((a, b) => a - b); return s[Math.floor(s.length / 2)]; };
|
|
47
|
+
/**
|
|
48
|
+
* 交替计时:每一轮先量 A 再量 B,取「B − A」的中位数(再附上两边各自的中位数给人看)。
|
|
49
|
+
* 不能 A 连量 N 次再 B 连量 N 次:test638 在同一台机器上并发跑两份 aggregate,负载随时间变,
|
|
50
|
+
* 两段分开量时差值被负载漂移主导(--cpus=1 实测差出 26–33 ms,真实差值 < 1 ms)。
|
|
51
|
+
*/
|
|
52
|
+
function pairedDelta(a: () => void, b: () => void, n: number): { a: number; b: number; delta: number } {
|
|
53
|
+
for (let i = 0; i < WARMUP; i++) { a(); b(); }
|
|
54
|
+
const as: number[] = [], bs: number[] = [], ds: number[] = [];
|
|
55
|
+
for (let i = 0; i < n; i++) {
|
|
56
|
+
let t = performance.now(); a(); const ta = performance.now() - t;
|
|
57
|
+
t = performance.now(); b(); const tb = performance.now() - t;
|
|
58
|
+
as.push(ta); bs.push(tb); ds.push(tb - ta);
|
|
59
|
+
}
|
|
60
|
+
return { a: median(as), b: median(bs), delta: median(ds) };
|
|
61
|
+
}
|
|
62
|
+
const pct = (xs: number[], p: number) => { const s = [...xs].sort((a, b) => a - b); return s[Math.min(s.length - 1, Math.floor(p * s.length))]; };
|
|
63
|
+
type LowDelta = { a: number; b: number; delta: number; aP50: number; bP50: number; ok: boolean };
|
|
64
|
+
/**
|
|
65
|
+
* #517 —— 「组授权比直接授权多出多少」的稳健量法。旧做法(15 对、每轮固定先 A 后 B、取每轮差值中位数)在 test638
|
|
66
|
+
* 两份 aggregate 并发时红过(本地 2 核 + 忙循环邻居实测 paired-delta 7.34 ms > 5 ms,同一轮两边中位数差出 10 ms)——
|
|
67
|
+
* 量的是负载,不是组展开。现在:
|
|
68
|
+
* - 每轮翻转先后(偶数轮 A→B,奇数轮 B→A),「第二个总吃前一个的 GC / 调度」这类顺序偏差两边对半分;
|
|
69
|
+
* - 每边 DELTA_PAIRS 个样本,比两边各自的 LOW_P 分位:调度噪声只会加时间,低尾最接近真实成本;
|
|
70
|
+
* - 一轮超标就整轮重量,最多 RETRIES 次;真回归(组路径每节点多查一次,#2133 那种 N+1)每一轮都超。
|
|
71
|
+
*/
|
|
72
|
+
function lowDelta(a: () => void, b: () => void, bound: (base: number) => number): LowDelta {
|
|
73
|
+
let r: LowDelta | null = null;
|
|
74
|
+
for (let attempt = 0; attempt <= RETRIES; attempt++) {
|
|
75
|
+
for (let i = 0; i < WARMUP; i++) { a(); b(); }
|
|
76
|
+
const as: number[] = [], bs: number[] = [];
|
|
77
|
+
for (let i = 0; i < DELTA_PAIRS; i++) {
|
|
78
|
+
const time = (f: () => void) => { const t = performance.now(); f(); return performance.now() - t; };
|
|
79
|
+
if (i % 2 === 0) { as.push(time(a)); bs.push(time(b)); } else { bs.push(time(b)); as.push(time(a)); }
|
|
80
|
+
}
|
|
81
|
+
const lowA = pct(as, LOW_P), lowB = pct(bs, LOW_P);
|
|
82
|
+
r = { a: lowA, b: lowB, delta: lowB - lowA, aP50: pct(as, 0.5), bP50: pct(bs, 0.5), ok: lowB - lowA <= bound(lowA) };
|
|
83
|
+
if (r.ok) return r;
|
|
84
|
+
}
|
|
85
|
+
return r!;
|
|
86
|
+
}
|
|
87
|
+
async function lowDeltaAsync(a: () => Promise<void>, b: () => Promise<void>, bound: (base: number) => number, label: string): Promise<LowDelta> {
|
|
88
|
+
let r: LowDelta | null = null;
|
|
89
|
+
for (let attempt = 0; attempt <= RETRIES; attempt++) {
|
|
90
|
+
for (let i = 0; i < WARMUP; i++) { await a(); await b(); }
|
|
91
|
+
const as: number[] = [], bs: number[] = [];
|
|
92
|
+
const time = async (f: () => Promise<void>) => { const t = performance.now(); await f(); return performance.now() - t; };
|
|
93
|
+
for (let i = 0; i < DELTA_PAIRS; i++) {
|
|
94
|
+
if (i % 2 === 0) { as.push(await time(a)); bs.push(await time(b)); } else { bs.push(await time(b)); as.push(await time(a)); }
|
|
95
|
+
}
|
|
96
|
+
const lowA = pct(as, LOW_P), lowB = pct(bs, LOW_P);
|
|
97
|
+
r = { a: lowA, b: lowB, delta: lowB - lowA, aP50: pct(as, 0.5), bP50: pct(bs, 0.5), ok: lowB - lowA <= bound(lowA) };
|
|
98
|
+
console.log(`[perf] ${label} pass ${attempt + 1}: p${LOW_P * 100} direct-300=${lowA.toFixed(2)}ms groups-50x6=${lowB.toFixed(2)}ms delta=${r.delta.toFixed(2)}ms bound=${bound(lowA).toFixed(2)}ms (p50 ${r.aP50.toFixed(2)} / ${r.bP50.toFixed(2)}) ${r.ok ? "ok" : "OVER"}`);
|
|
99
|
+
if (r.ok) return r;
|
|
100
|
+
}
|
|
101
|
+
return r!;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
beforeAll(async () => {
|
|
105
|
+
process.env.COMMHUB_DB ||= join(DIR, "hub.db");
|
|
106
|
+
process.env.COMMHUB_UPLOADS_DIR = join(DIR, "uploads");
|
|
107
|
+
process.env.HOST = "127.0.0.1";
|
|
108
|
+
const admin = register(`perf_admin_${Date.now()}`, PW, undefined, "Admin");
|
|
109
|
+
expect(admin.ok).toBe(true);
|
|
110
|
+
adminToken = admin.token!;
|
|
111
|
+
adminId = admin.user!.user_id;
|
|
112
|
+
NET = admin.network_id!;
|
|
113
|
+
db.run("UPDATE users SET role = 'admin' WHERE user_id = ?1", [adminId]);
|
|
114
|
+
db.transaction(() => {
|
|
115
|
+
for (let i = 0; i < NODES; i++) {
|
|
116
|
+
const node = `node_perf_${i}`;
|
|
117
|
+
const alias = `perf-agent-${i}`;
|
|
118
|
+
db.run(`INSERT INTO nodes (node_id, node_name, alias, network_id, owner_user_id, updated_at) VALUES (?1, ?2, ?2, ?3, ?4, datetime('now'))`, [node, alias, NET, adminId]);
|
|
119
|
+
db.run(`INSERT INTO sessions (resume_id, alias, node_id, status, network_id, updated_at, last_seen_at) VALUES (?1, ?2, ?3, 'idle', ?4, datetime('now'), datetime('now'))`, [`resume_${node}`, alias, node, NET]);
|
|
120
|
+
}
|
|
121
|
+
});
|
|
122
|
+
const mod: any = await import("./server.js");
|
|
123
|
+
hub = mod.bootServer({ port: 0, hostname: "127.0.0.1" });
|
|
124
|
+
BASE = `http://127.0.0.1:${hub.port}`;
|
|
125
|
+
|
|
126
|
+
const mk = async (username: string) => {
|
|
127
|
+
const r = await send(adminToken, "POST", "/api/admin/users", { username, password: PW, network_id: NET, role: "member" });
|
|
128
|
+
expect(r.status).toBe(200);
|
|
129
|
+
const login = await send("", "POST", "/api/auth/login", { username, password: PW });
|
|
130
|
+
return { token: login.body.token as string, id: login.body.user.user_id as string };
|
|
131
|
+
};
|
|
132
|
+
alice = await mk(`perf_alice_${Date.now()}`);
|
|
133
|
+
bob = await mk(`perf_bob_${Date.now()}`);
|
|
134
|
+
|
|
135
|
+
const groupIds: string[] = [];
|
|
136
|
+
for (let g = 0; g < GROUPS; g++) {
|
|
137
|
+
const nodeIds = Array.from({ length: PER_GROUP }, (_, k) => `node_perf_${g * PER_GROUP + k}`);
|
|
138
|
+
const r = await send(adminToken, "POST", `/api/networks/${NET}/agent-groups`, { name: `perf-group-${g}`, node_ids: nodeIds });
|
|
139
|
+
expect(r.status).toBe(200);
|
|
140
|
+
groupIds.push(r.body.group.group_id);
|
|
141
|
+
}
|
|
142
|
+
expect((await send(adminToken, "PUT", `/api/networks/${NET}/members/${alice.id}/agent-grants`, { group_grants: groupIds })).status).toBe(200);
|
|
143
|
+
expect((await send(adminToken, "PUT", `/api/networks/${NET}/members/${bob.id}/agent-grants`, { grants: Array.from({ length: NODES }, (_, i) => `node_perf_${i}`) })).status).toBe(200);
|
|
144
|
+
}, 60_000);
|
|
145
|
+
|
|
146
|
+
afterAll(() => {
|
|
147
|
+
try { hub?.stop?.(true); } catch {}
|
|
148
|
+
try { rmSync(DIR, { recursive: true, force: true }); } catch {}
|
|
149
|
+
});
|
|
150
|
+
|
|
151
|
+
describe("Agent 分组:性能守卫(50 组 × 300 节点)", () => {
|
|
152
|
+
test("两人可见集合相同(比较才公平)", () => {
|
|
153
|
+
const a = visibleAgents(alice.id, NET);
|
|
154
|
+
const b = visibleAgents(bob.id, NET);
|
|
155
|
+
expect(a.nodeIds.length).toBe(NODES);
|
|
156
|
+
expect([...a.nodeIds].sort()).toEqual([...b.nodeIds].sort());
|
|
157
|
+
});
|
|
158
|
+
|
|
159
|
+
test(`visibleAgents():组展开的额外开销 ≤ max(${BOUND_MS} ms, 基线 15%)(目标 ≈2 ms)`, () => {
|
|
160
|
+
const r = lowDelta(() => { visibleAgents(bob.id, NET); }, () => { visibleAgents(alice.id, NET); }, bound);
|
|
161
|
+
console.log(`[perf] visibleAgents p${LOW_P * 100}: direct-300=${r.a.toFixed(2)}ms groups-50x6=${r.b.toFixed(2)}ms delta=${r.delta.toFixed(2)}ms bound=${bound(r.a).toFixed(2)}ms (p50 ${r.aP50.toFixed(2)} / ${r.bP50.toFixed(2)})`);
|
|
162
|
+
expect(r.delta).toBeLessThanOrEqual(bound(r.a));
|
|
163
|
+
}, PERF_TIMEOUT_MS);
|
|
164
|
+
|
|
165
|
+
// #2133:visibleAgents() 以前每个授权节点查一次 alias(300 条 ≈ 28–43 ms)。这两条钉住它不再回到 N+1:
|
|
166
|
+
// 查询条数(直接授权 1 + 组授权 1 + alias 1)是主判据,不受机器负载影响;绝对上限只兜底 ——
|
|
167
|
+
// 本机实测 ≈2.6–3.7 ms(负载 ~5),15 ms 给 test638 那种 --cpus=1 双份并发留足余量,仍远低于 N+1 的 28 ms。
|
|
168
|
+
const ABS_MS = 15;
|
|
169
|
+
test(`visibleAgents() at 300 grants stays under ${ABS_MS} ms (direct and via groups)`, () => {
|
|
170
|
+
const t = pairedDelta(() => { visibleAgents(bob.id, NET); }, () => { visibleAgents(alice.id, NET); }, 40);
|
|
171
|
+
console.log(`[perf] visibleAgents absolute: direct-300=${t.a.toFixed(2)}ms groups-50x6=${t.b.toFixed(2)}ms bound=${ABS_MS}ms`);
|
|
172
|
+
expect(t.a).toBeLessThan(ABS_MS);
|
|
173
|
+
expect(t.b).toBeLessThan(ABS_MS);
|
|
174
|
+
});
|
|
175
|
+
|
|
176
|
+
test("visibleAgents() makes a fixed number of queries, not one per granted node (#2133)", () => {
|
|
177
|
+
for (const who of [bob, alice]) {
|
|
178
|
+
let queries = 0;
|
|
179
|
+
const all = db.all.bind(db), get = db.get.bind(db);
|
|
180
|
+
(db as any).all = (...a: any[]) => { queries++; return (all as any)(...a); };
|
|
181
|
+
(db as any).get = (...a: any[]) => { queries++; return (get as any)(...a); };
|
|
182
|
+
try { visibleAgents(who.id, NET); } finally { (db as any).all = all; (db as any).get = get; }
|
|
183
|
+
console.log(`[perf] visibleAgents queries (${who === bob ? "direct-300" : "groups-50x6"}): ${queries}`);
|
|
184
|
+
expect(queries).toBeLessThanOrEqual(3);
|
|
185
|
+
}
|
|
186
|
+
});
|
|
187
|
+
|
|
188
|
+
test(`受限成员 GET /api/status:组授权比等量直接授权多出 ≤ max(${BOUND_MS} ms, 基线 15%)`, async () => {
|
|
189
|
+
const hit = async (token: string) => {
|
|
190
|
+
const r = await fetch(`${BASE}/api/status?network_id=${NET}`, { headers: json(token) });
|
|
191
|
+
const body = await r.json() as any;
|
|
192
|
+
if ((body.sessions ?? []).length !== NODES) throw new Error(`expected ${NODES} sessions, got ${(body.sessions ?? []).length}`);
|
|
193
|
+
};
|
|
194
|
+
const r = await lowDeltaAsync(() => hit(bob.token), () => hit(alice.token), bound, "GET /api/status");
|
|
195
|
+
expect(r.delta).toBeLessThanOrEqual(bound(r.a));
|
|
196
|
+
}, PERF_TIMEOUT_MS);
|
|
197
|
+
|
|
198
|
+
test("EXPLAIN QUERY PLAN:组展开走索引,不全表扫描", () => {
|
|
199
|
+
const plan = db.all<{ detail: string }>(
|
|
200
|
+
`EXPLAIN QUERY PLAN
|
|
201
|
+
SELECT m.node_id, g.can_message
|
|
202
|
+
FROM network_member_group_grants g
|
|
203
|
+
JOIN agent_groups ag ON ag.group_id = g.group_id AND ag.network_id = g.network_id
|
|
204
|
+
JOIN agent_group_members m ON m.group_id = g.group_id
|
|
205
|
+
JOIN nodes n ON n.node_id = m.node_id AND n.network_id = g.network_id
|
|
206
|
+
WHERE g.network_id = ?1 AND g.user_id = ?2`,
|
|
207
|
+
NET, alice.id,
|
|
208
|
+
).map((r) => r.detail);
|
|
209
|
+
console.log(`[perf] plan:\n ${plan.join("\n ")}`);
|
|
210
|
+
// 四张表都是 SEARCH(按主键 / 索引定位),没有一张是 SCAN。
|
|
211
|
+
expect(plan.length).toBeGreaterThanOrEqual(4);
|
|
212
|
+
expect(plan.filter((d) => /^SCAN\b/.test(d))).toEqual([]);
|
|
213
|
+
expect(plan.every((d) => /^SEARCH\b/.test(d) && /(PRIMARY KEY|INDEX)/.test(d))).toBe(true);
|
|
214
|
+
});
|
|
215
|
+
|
|
216
|
+
test("EXPLAIN QUERY PLAN:按组找被授权成员(改组成员时断流用)走 group_id 索引", () => {
|
|
217
|
+
const plan = db.all<{ detail: string }>(
|
|
218
|
+
"EXPLAIN QUERY PLAN SELECT user_id FROM network_member_group_grants WHERE group_id = ?1", "x",
|
|
219
|
+
).map((r) => r.detail);
|
|
220
|
+
console.log(`[perf] plan (usersGrantedGroup): ${plan.join(" | ")}`);
|
|
221
|
+
expect(plan.some((d) => /SEARCH .*idx_group_grants_group/.test(d))).toBe(true);
|
|
222
|
+
});
|
|
223
|
+
});
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
// Hub 以某个节点的名义发给一个用户的一条通知(#462 登录失效、#464 定时任务卡住)。
|
|
2
|
+
//
|
|
3
|
+
// 走 user_inbox + /events/users/me 的 desktop_message —— 与 send_desktop_message 同一张表、同一条推送,
|
|
4
|
+
// from_session = 节点别名,所以 App 把它显示在**与该节点的会话**里(主动消息)+ 未读角标 + 通知。不新增渠道。
|
|
5
|
+
// 只发给一个人;他不在本网络了就不发。推送在写库之后:收到推送的 App 立刻回读得到这一行。
|
|
6
|
+
|
|
7
|
+
import { db, uuidv4 } from "./db.js";
|
|
8
|
+
import { getUserNetworkRole } from "./auth.js";
|
|
9
|
+
import { pushUserEvent } from "./push.js";
|
|
10
|
+
|
|
11
|
+
export type AgentNotice = {
|
|
12
|
+
networkId: string;
|
|
13
|
+
userId: string;
|
|
14
|
+
/** 节点别名:通知出现在与它的会话里。 */
|
|
15
|
+
fromAlias: string;
|
|
16
|
+
kind: string;
|
|
17
|
+
title: string;
|
|
18
|
+
text: string;
|
|
19
|
+
severity?: "info" | "warning" | "error";
|
|
20
|
+
meta: Record<string, unknown>;
|
|
21
|
+
/** 消息 id 前缀(`dm_` 开头,与 App 的去重键同一套)。 */
|
|
22
|
+
idPrefix: string;
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
/** 返回 message_id;没发(收件人不在本网络)→ null。 */
|
|
26
|
+
export function sendAgentNotice(n: AgentNotice): string | null {
|
|
27
|
+
if (!getUserNetworkRole(n.userId, n.networkId)) return null;
|
|
28
|
+
const messageId = `${n.idPrefix}${uuidv4()}`;
|
|
29
|
+
const severity = n.severity ?? "warning";
|
|
30
|
+
db.run(
|
|
31
|
+
`INSERT INTO user_inbox (message_id, network_id, user_id, from_session, kind, title, content, severity, meta_json)
|
|
32
|
+
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)
|
|
33
|
+
ON CONFLICT(message_id) DO NOTHING`,
|
|
34
|
+
[messageId, n.networkId, n.userId, n.fromAlias, n.kind, n.title, n.text, severity, JSON.stringify(n.meta)],
|
|
35
|
+
);
|
|
36
|
+
pushUserEvent(n.networkId, n.userId, {
|
|
37
|
+
type: "desktop_message",
|
|
38
|
+
message_id: messageId,
|
|
39
|
+
kind: n.kind,
|
|
40
|
+
from: n.fromAlias,
|
|
41
|
+
title: n.title,
|
|
42
|
+
message: n.text,
|
|
43
|
+
severity,
|
|
44
|
+
created_at: new Date().toISOString(),
|
|
45
|
+
meta: n.meta,
|
|
46
|
+
});
|
|
47
|
+
return messageId;
|
|
48
|
+
}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import { beforeAll, afterAll, expect, test } from "bun:test";
|
|
2
|
+
import { mkdtempSync } from "node:fs";
|
|
3
|
+
|
|
4
|
+
process.env.COMMHUB_DB ||= `${mkdtempSync('/tmp/team-whoami-')}/hub.db`;
|
|
5
|
+
let db: any, hub: any, base: string, owner: any, outside: any;
|
|
6
|
+
let selfToken: string, otherToken: string, outsideToken: string, unboundToken: string;
|
|
7
|
+
const SELF = 'node_team_whoami_self', OTHER = 'node_team_whoami_other', FOREIGN = 'node_team_whoami_foreign';
|
|
8
|
+
const TEAM = 'team_whoami_child', ROOT = 'team_whoami_root';
|
|
9
|
+
|
|
10
|
+
async function rpc(token: string, method = 'tools/call', params: unknown = { name: 'org_whoami', arguments: {} }) {
|
|
11
|
+
const response = await fetch(`${base}/mcp`, { method: 'POST', headers: {
|
|
12
|
+
Authorization: `Bearer ${token}`, 'Content-Type': 'application/json',
|
|
13
|
+
Accept: 'application/json, text/event-stream', 'MCP-Protocol-Version': '2025-03-26',
|
|
14
|
+
}, body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }) });
|
|
15
|
+
expect(response.status).toBe(200);
|
|
16
|
+
const text = await response.text();
|
|
17
|
+
const line = text.split('\n').filter(x => x.startsWith('data:')).at(-1);
|
|
18
|
+
const body = JSON.parse(line ? line.slice(5) : text);
|
|
19
|
+
expect(body.error).toBeUndefined();
|
|
20
|
+
return body.result;
|
|
21
|
+
}
|
|
22
|
+
async function who(token = selfToken, args: Record<string, unknown> = {}) {
|
|
23
|
+
const result = await rpc(token, 'tools/call', { name: 'org_whoami', arguments: args });
|
|
24
|
+
return JSON.parse(result.content[0].text);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
beforeAll(async () => {
|
|
28
|
+
({ db } = await import('./db.js'));
|
|
29
|
+
const { register, createNetworkTokenForNode } = await import('./auth.js');
|
|
30
|
+
owner = register('team_whoami_owner', 'Fixture-Passw0rd!xyz');
|
|
31
|
+
outside = register('team_whoami_outside', 'Fixture-Passw0rd!xyz');
|
|
32
|
+
db.run("UPDATE users SET display_name = 'Team owner' WHERE user_id = ?1", [owner.user.user_id]);
|
|
33
|
+
const mint = (u: any, alias: string, node?: string) => {
|
|
34
|
+
const r = createNetworkTokenForNode(u.user.user_id, u.network_id, alias, node);
|
|
35
|
+
expect(r.error ?? null).toBe(null); return r.token!;
|
|
36
|
+
};
|
|
37
|
+
selfToken = mint(owner, 'team-self', SELF);
|
|
38
|
+
otherToken = mint(owner, 'team-other', OTHER);
|
|
39
|
+
outsideToken = mint(outside, 'team-self', FOREIGN); // Same alias in a different network.
|
|
40
|
+
unboundToken = mint(owner, 'team-unregistered');
|
|
41
|
+
const { bootServer } = await import('./server.js');
|
|
42
|
+
hub = bootServer({ port: 0, hostname: '127.0.0.1' });
|
|
43
|
+
base = `http://127.0.0.1:${hub.port}`;
|
|
44
|
+
for (const [net, id, name, parent] of [
|
|
45
|
+
[owner.network_id, ROOT, 'Parent', null], [owner.network_id, TEAM, 'My team', ROOT],
|
|
46
|
+
[outside.network_id, TEAM, 'Foreign team', null],
|
|
47
|
+
]) db.run('INSERT INTO network_agent_teams(network_id,team_id,name,parent_id) VALUES(?1,?2,?3,?4)', [net,id,name,parent]);
|
|
48
|
+
db.run('UPDATE network_agent_teams SET lead_node_id=?1,owner_user_id=?2 WHERE network_id=?3 AND team_id=?4', [SELF,owner.user.user_id,owner.network_id,TEAM]);
|
|
49
|
+
for (const [net, node] of [[owner.network_id, SELF], [outside.network_id, FOREIGN]]) {
|
|
50
|
+
db.run('INSERT INTO network_agent_team_members(network_id,node_id,team_id) VALUES(?1,?2,?3)', [net,node,TEAM]);
|
|
51
|
+
}
|
|
52
|
+
// Even a stale/corrupt membership must not project a node from another network.
|
|
53
|
+
db.run('INSERT INTO network_agent_team_members(network_id,node_id,team_id) VALUES(?1,?2,?3)', [owner.network_id,FOREIGN,TEAM]);
|
|
54
|
+
}, 60_000);
|
|
55
|
+
afterAll(() => hub?.stop(true));
|
|
56
|
+
|
|
57
|
+
test('exact node team, nearest-first ancestors, Agent lead and private human display name', async () => {
|
|
58
|
+
const r = await who();
|
|
59
|
+
expect(r.ok).toBe(true); expect(r.source).toBe('node'); expect(r.node_id).toBe(SELF);
|
|
60
|
+
expect(r.team).toEqual({ id: TEAM, name: 'My team' });
|
|
61
|
+
expect(r.ancestors).toEqual([{ id: ROOT, name: 'Parent' }]);
|
|
62
|
+
expect(r.lead.node_id).toBe(SELF);
|
|
63
|
+
expect(r.owner).toEqual({ user_id: owner.user.user_id, display_name: 'Team owner' });
|
|
64
|
+
expect(r.agents.map((n: any) => n.node_id)).toEqual([SELF]);
|
|
65
|
+
expect(r.truncated).toBe(false);
|
|
66
|
+
expect(JSON.stringify(r)).not.toContain('team_whoami_owner');
|
|
67
|
+
});
|
|
68
|
+
test('same-id foreign team and foreign node cannot cross network; supplied identity is ignored', async () => {
|
|
69
|
+
const r = await who(selfToken, { network_id: outside.network_id, node_id: FOREIGN, alias: 'team-other' });
|
|
70
|
+
expect(r.node_id).toBe(SELF); expect(r.team.name).toBe('My team');
|
|
71
|
+
expect(JSON.stringify(r)).not.toContain(FOREIGN);
|
|
72
|
+
const b = await who(outsideToken);
|
|
73
|
+
expect(b.team.name).toBe('Foreign team'); expect(b.node_id).toBe(FOREIGN);
|
|
74
|
+
expect(b.ancestors).toEqual([]); expect(JSON.stringify(b)).not.toContain(SELF);
|
|
75
|
+
});
|
|
76
|
+
test('unassigned node does not inherit its owner or another node team', async () => {
|
|
77
|
+
expect(await who(otherToken)).toEqual({ ok: true, source: 'none', node_id: OTHER, team: null,
|
|
78
|
+
ancestors: [], lead: null, owner: null, agents: [], truncated: false });
|
|
79
|
+
expect((await who(unboundToken)).error).toBe('node_identity_unbound');
|
|
80
|
+
});
|
|
81
|
+
test('user credentials cannot list or call; node credentials can list', async () => {
|
|
82
|
+
expect((await rpc(owner.token, 'tools/list', {})).tools.some((t: any) => t.name === 'org_whoami')).toBe(false);
|
|
83
|
+
expect((await who(owner.token)).error).toBe('network_token_required');
|
|
84
|
+
expect((await rpc(selfToken, 'tools/list', {})).tools.some((t: any) => t.name === 'org_whoami')).toBe(true);
|
|
85
|
+
});
|
|
86
|
+
test('foreign lead and human owner references are not returned', async () => {
|
|
87
|
+
db.run('UPDATE network_agent_teams SET lead_node_id=?1,owner_user_id=?2 WHERE network_id=?3 AND team_id=?4', [FOREIGN,outside.user.user_id,owner.network_id,TEAM]);
|
|
88
|
+
try { const r = await who(); expect(r.lead).toBe(null); expect(r.owner).toBe(null); }
|
|
89
|
+
finally { db.run('UPDATE network_agent_teams SET lead_node_id=?1,owner_user_id=?2 WHERE network_id=?3 AND team_id=?4', [SELF,owner.user.user_id,owner.network_id,TEAM]); }
|
|
90
|
+
});
|
|
91
|
+
test('large teams are bounded to 50 and explicitly truncated', async () => {
|
|
92
|
+
for (let i = 0; i < 51; i++) {
|
|
93
|
+
const id = `node_team_whoami_cap_${i}`;
|
|
94
|
+
db.run('INSERT INTO nodes(node_id,node_name,alias,network_id) VALUES(?1,?1,?1,?2)', [id,owner.network_id]);
|
|
95
|
+
db.run('INSERT INTO network_agent_team_members(network_id,node_id,team_id) VALUES(?1,?2,?3)', [owner.network_id,id,TEAM]);
|
|
96
|
+
}
|
|
97
|
+
const r = await who(); expect(r.agents.length).toBe(50); expect(r.truncated).toBe(true);
|
|
98
|
+
});
|