@sleep2agi/commhub-server 0.9.0-preview.23 → 0.9.0-preview.230
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/package.json +7 -7
- package/src/ack-create-request-transport.test.ts +182 -0
- package/src/ack-create-request.test.ts +50 -7
- 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 +654 -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 +250 -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 +121 -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/chain-attempt-dedup.test.ts +447 -0
- package/src/clip.test.ts +36 -0
- package/src/clip.ts +46 -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-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 +120 -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 +289 -0
- package/src/create-node.ts +88 -23
- 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 +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/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 +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-anon-readers.ts +60 -0
- package/src/health-host-disk-2756.test.ts +71 -0
- package/src/health-redaction.test.ts +1721 -2
- 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 +409 -0
- package/src/hub-provider-config.test.ts +156 -0
- package/src/hub-provider-config.ts +170 -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 +139 -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 +1091 -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 +335 -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 +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 +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 +457 -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/push.test.ts +20 -10
- package/src/push.ts +382 -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 +295 -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 +443 -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-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 +2064 -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 +432 -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 +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 +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 +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 +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/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 +5035 -457
- 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 +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 +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 +490 -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 +227 -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 +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 +4310 -419
- package/src/upload-early-reject-guard.test.ts +155 -0
- package/src/uploads-http.test.ts +86 -7
- package/src/uploads.ts +103 -6
- 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/version-stats.test.ts +66 -0
- package/src/version-stats.ts +109 -0
|
@@ -0,0 +1,318 @@
|
|
|
1
|
+
// 人类成员的组织架构(board #419):部门(多层)+ 每个成员归一个部门 + 部门负责人。
|
|
2
|
+
//
|
|
3
|
+
// 只增不改:新表 network_departments,network_members 多一列 department_id(默认 NULL = 未分配)。
|
|
4
|
+
// 旧 app 不读这两样,行为不变。网络本身就是根(parent_id = NULL 的部门挂在网络下面)。
|
|
5
|
+
//
|
|
6
|
+
// 权限:网络里任何成员(含 viewer、受限成员)都能读组织架构 —— 和 /humans 通讯录同一可见范围;
|
|
7
|
+
// 写(建 / 改名 / 移动 / 删除部门、设负责人、调人)只给网络 owner / admin 和 Hub 管理员。节点令牌只能读自己网络的。
|
|
8
|
+
//
|
|
9
|
+
// /humans 通讯录保持只有身份字段(它的键集合被测试钉着);谁在哪个部门从 GET …/departments 的 members[] 读。
|
|
10
|
+
// 规则:同一上级下部门不重名;移动不能挂到自己或自己的下级下面;最多 MAX_DEPTH 层;
|
|
11
|
+
// 只有空部门(没有子部门、没有成员)能删;负责人必须是本网络成员;人离开网络后,作为负责人的引用读出来是 null。
|
|
12
|
+
|
|
13
|
+
import { db, logAudit } from "./db.js";
|
|
14
|
+
import { deleteDepartmentGrants, deleteDepartmentGrantsForNetwork } from "./department-heads.js";
|
|
15
|
+
import { deleteChatGroupsForNetwork, groupTx, removeMemberFromChatGroups, syncDepartmentGroups, unlinkDepartmentGroup } from "./department-groups.js";
|
|
16
|
+
|
|
17
|
+
// auth.ts 的 removeNetworkMember 从这里拿(auth.ts 只 import departments.js 一行,文档钉着它的行号)。
|
|
18
|
+
export { groupTx, removeMemberFromChatGroups };
|
|
19
|
+
|
|
20
|
+
try { db.exec("ALTER TABLE network_members ADD COLUMN department_id TEXT"); } catch {}
|
|
21
|
+
db.exec(`
|
|
22
|
+
CREATE TABLE IF NOT EXISTS network_departments (
|
|
23
|
+
network_id TEXT NOT NULL,
|
|
24
|
+
department_id TEXT NOT NULL,
|
|
25
|
+
name TEXT NOT NULL,
|
|
26
|
+
parent_id TEXT,
|
|
27
|
+
leader_user_id TEXT,
|
|
28
|
+
sort INTEGER NOT NULL DEFAULT 0,
|
|
29
|
+
created_by TEXT,
|
|
30
|
+
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
31
|
+
updated_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
32
|
+
PRIMARY KEY (network_id, department_id)
|
|
33
|
+
);
|
|
34
|
+
CREATE INDEX IF NOT EXISTS idx_network_departments_parent ON network_departments(network_id, parent_id);
|
|
35
|
+
`);
|
|
36
|
+
|
|
37
|
+
export const MAX_DEPTH = 10;
|
|
38
|
+
export const MAX_DEPARTMENTS = 500;
|
|
39
|
+
const NAME_MAX = 40;
|
|
40
|
+
const ID_RE = /^[A-Za-z0-9_-]{1,64}$/;
|
|
41
|
+
|
|
42
|
+
type DeptRow = { network_id: string; department_id: string; name: string; parent_id: string | null; leader_user_id: string | null; sort: number; created_at: string; updated_at: string };
|
|
43
|
+
/**
|
|
44
|
+
* 部门(轴1 = 人)。
|
|
45
|
+
*
|
|
46
|
+
* `member_count` 是**直属人数**(不含子树)。
|
|
47
|
+
* `agent_count` 是**轴2**:Agent 显式归属 `nodes.department_id` 指向本部门的数量,
|
|
48
|
+
* 与「成员的 Agent」无关(RFC-040 / #1976:Agent 部门只由显式设置决定,不再按负责人推断)。
|
|
49
|
+
* 没有这一格时,任何客户端想画「部门 → Agent 数」都得自己拉全量
|
|
50
|
+
* `people/directory` 再去重,各端口径必然分叉(#2822:Dashboard 105/TMAI 1
|
|
51
|
+
* vs 客户端 TMWork 15/TM智能体空间 2)。
|
|
52
|
+
*/
|
|
53
|
+
export type Department = { id: string; name: string; parent_id: string | null; leader_user_id: string | null; sort: number; member_count: number; agent_count: number; created_at: string; updated_at: string };
|
|
54
|
+
|
|
55
|
+
type Fail = { ok: false; status: number; error: string };
|
|
56
|
+
type Ok<T> = { ok: true } & T;
|
|
57
|
+
|
|
58
|
+
const fail = (status: number, error: string): Fail => ({ ok: false, status, error });
|
|
59
|
+
|
|
60
|
+
function rows(networkId: string): DeptRow[] {
|
|
61
|
+
return db.all<DeptRow>(
|
|
62
|
+
"SELECT network_id, department_id, name, parent_id, leader_user_id, sort, created_at, updated_at FROM network_departments WHERE network_id = ?1 ORDER BY sort, created_at, department_id",
|
|
63
|
+
networkId,
|
|
64
|
+
);
|
|
65
|
+
}
|
|
66
|
+
function one(networkId: string, id: string): DeptRow | null {
|
|
67
|
+
return db.get<DeptRow>(
|
|
68
|
+
"SELECT network_id, department_id, name, parent_id, leader_user_id, sort, created_at, updated_at FROM network_departments WHERE network_id = ?1 AND department_id = ?2",
|
|
69
|
+
networkId, id,
|
|
70
|
+
) ?? null;
|
|
71
|
+
}
|
|
72
|
+
function isMember(networkId: string, userId: string): boolean {
|
|
73
|
+
return !!db.get<{ user_id: string }>("SELECT user_id FROM network_members WHERE network_id = ?1 AND user_id = ?2", networkId, userId);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** 读:部门(带直属人数)+ 每个成员在哪个部门。负责人不在本网络了 → null。 */
|
|
77
|
+
export function listDepartments(networkId: string): {
|
|
78
|
+
departments: Department[];
|
|
79
|
+
members: Array<{ user_id: string; department_id: string | null }>;
|
|
80
|
+
/// 轴2 里没有显式归属的 Agent 数(Dashboard 的「未分组」不该拿人的未分配去填)。
|
|
81
|
+
agents_unassigned: number;
|
|
82
|
+
} {
|
|
83
|
+
const members = db.all<{ user_id: string; department_id: string | null }>(
|
|
84
|
+
"SELECT user_id, department_id FROM network_members WHERE network_id = ?1 ORDER BY joined_at, user_id",
|
|
85
|
+
networkId,
|
|
86
|
+
);
|
|
87
|
+
const memberIds = new Set(members.map((m) => m.user_id));
|
|
88
|
+
const all = rows(networkId);
|
|
89
|
+
const ids = new Set(all.map((d) => d.department_id));
|
|
90
|
+
// 成员行指着一个已经不存在的部门(理论上删除时已清空;防御)→ 当未分配。
|
|
91
|
+
const placed = members.map((m) => ({ user_id: m.user_id, department_id: m.department_id && ids.has(m.department_id) ? m.department_id : null }));
|
|
92
|
+
const counts = new Map<string, number>();
|
|
93
|
+
for (const m of placed) if (m.department_id) counts.set(m.department_id, (counts.get(m.department_id) ?? 0) + 1);
|
|
94
|
+
// ── 轴2:Agent 的显式部门(nodes.department_id)────────────────────────────
|
|
95
|
+
// 去重口径与 #2596 一致:同一个 alias 只算一个 Agent,保留 updated_at 最新的那一行,
|
|
96
|
+
// 它落在哪个部门就计入哪个部门(没有 alias 的用 node_id 当键)。
|
|
97
|
+
// 不在这里做「近 7 天」过滤:那是展示策略,接口只给事实。
|
|
98
|
+
const agentRows = db.all<{ department_id: string; alias: string | null; node_id: string; updated_at: string | null }>(
|
|
99
|
+
"SELECT department_id, alias, node_id, updated_at FROM nodes WHERE network_id = ?1 AND department_id IS NOT NULL AND department_id != ''",
|
|
100
|
+
networkId,
|
|
101
|
+
);
|
|
102
|
+
const newestByKey = new Map<string, { department_id: string; updated_at: string | null }>();
|
|
103
|
+
for (const n of agentRows) {
|
|
104
|
+
const key = n.alias || n.node_id;
|
|
105
|
+
const prev = newestByKey.get(key);
|
|
106
|
+
if (!prev || (n.updated_at ?? "") > (prev.updated_at ?? "")) {
|
|
107
|
+
newestByKey.set(key, { department_id: n.department_id, updated_at: n.updated_at });
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
const agentCounts = new Map<string, number>();
|
|
111
|
+
for (const v of newestByKey.values()) agentCounts.set(v.department_id, (agentCounts.get(v.department_id) ?? 0) + 1);
|
|
112
|
+
const unassigned = db.get<{ n: number }>(
|
|
113
|
+
"SELECT COUNT(*) AS n FROM nodes WHERE network_id = ?1 AND (department_id IS NULL OR department_id = '')",
|
|
114
|
+
networkId,
|
|
115
|
+
)?.n ?? 0;
|
|
116
|
+
return {
|
|
117
|
+
departments: all.map((d) => ({
|
|
118
|
+
id: d.department_id,
|
|
119
|
+
name: d.name,
|
|
120
|
+
parent_id: d.parent_id,
|
|
121
|
+
leader_user_id: d.leader_user_id && memberIds.has(d.leader_user_id) ? d.leader_user_id : null,
|
|
122
|
+
sort: d.sort,
|
|
123
|
+
member_count: counts.get(d.department_id) ?? 0,
|
|
124
|
+
agent_count: agentCounts.get(d.department_id) ?? 0,
|
|
125
|
+
created_at: d.created_at,
|
|
126
|
+
updated_at: d.updated_at,
|
|
127
|
+
})),
|
|
128
|
+
members: placed,
|
|
129
|
+
agents_unassigned: unassigned,
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const cleanName = (raw: unknown): string | null => {
|
|
134
|
+
if (typeof raw !== "string") return null;
|
|
135
|
+
const name = raw.trim();
|
|
136
|
+
return name && [...name].length <= NAME_MAX ? name : null;
|
|
137
|
+
};
|
|
138
|
+
|
|
139
|
+
function depthOf(networkId: string, id: string | null): number {
|
|
140
|
+
let depth = 0;
|
|
141
|
+
let cur = id;
|
|
142
|
+
const seen = new Set<string>();
|
|
143
|
+
while (cur) {
|
|
144
|
+
if (seen.has(cur)) return Infinity;
|
|
145
|
+
seen.add(cur);
|
|
146
|
+
depth += 1;
|
|
147
|
+
cur = one(networkId, cur)?.parent_id ?? null;
|
|
148
|
+
}
|
|
149
|
+
return depth;
|
|
150
|
+
}
|
|
151
|
+
/** 以 id 为根的子树最深有几层(含自己)。 */
|
|
152
|
+
function subtreeHeight(networkId: string, id: string): number {
|
|
153
|
+
const children = db.all<{ department_id: string }>("SELECT department_id FROM network_departments WHERE network_id = ?1 AND parent_id = ?2", networkId, id);
|
|
154
|
+
return 1 + children.reduce((m, c) => Math.max(m, subtreeHeight(networkId, c.department_id)), 0);
|
|
155
|
+
}
|
|
156
|
+
function isDescendant(networkId: string, ancestor: string, id: string | null): boolean {
|
|
157
|
+
let cur = id;
|
|
158
|
+
const seen = new Set<string>();
|
|
159
|
+
while (cur) {
|
|
160
|
+
if (cur === ancestor) return true;
|
|
161
|
+
if (seen.has(cur)) return true;
|
|
162
|
+
seen.add(cur);
|
|
163
|
+
cur = one(networkId, cur)?.parent_id ?? null;
|
|
164
|
+
}
|
|
165
|
+
return false;
|
|
166
|
+
}
|
|
167
|
+
function siblingNameTaken(networkId: string, parentId: string | null, name: string, exceptId?: string): boolean {
|
|
168
|
+
const sql = parentId === null
|
|
169
|
+
? "SELECT department_id FROM network_departments WHERE network_id = ?1 AND parent_id IS NULL AND name = ?2"
|
|
170
|
+
: "SELECT department_id FROM network_departments WHERE network_id = ?1 AND parent_id = ?3 AND name = ?2";
|
|
171
|
+
const hits = parentId === null ? db.all<{ department_id: string }>(sql, networkId, name) : db.all<{ department_id: string }>(sql, networkId, name, parentId);
|
|
172
|
+
return hits.some((h) => h.department_id !== exceptId);
|
|
173
|
+
}
|
|
174
|
+
function publicOne(networkId: string, id: string): Department {
|
|
175
|
+
return listDepartments(networkId).departments.find((d) => d.id === id)!;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
export function createDepartment(networkId: string, actor: string, body: Record<string, unknown>): Ok<{ department: Department }> | Fail {
|
|
179
|
+
const name = cleanName(body.name);
|
|
180
|
+
if (!name) return fail(400, "invalid_department_name");
|
|
181
|
+
let id: string;
|
|
182
|
+
if (body.id !== undefined && body.id !== null && body.id !== "") {
|
|
183
|
+
if (typeof body.id !== "string" || !ID_RE.test(body.id)) return fail(400, "invalid_department_id");
|
|
184
|
+
if (one(networkId, body.id)) return fail(409, "department_id_taken");
|
|
185
|
+
id = body.id;
|
|
186
|
+
} else {
|
|
187
|
+
id = `dept_${crypto.randomUUID().replace(/-/g, "").slice(0, 16)}`;
|
|
188
|
+
}
|
|
189
|
+
const parentId = body.parent_id === undefined || body.parent_id === null || body.parent_id === "" ? null : body.parent_id;
|
|
190
|
+
if (parentId !== null && (typeof parentId !== "string" || !one(networkId, parentId))) return fail(400, "parent_not_found");
|
|
191
|
+
if (depthOf(networkId, parentId as string | null) + 1 > MAX_DEPTH) return fail(400, "department_too_deep");
|
|
192
|
+
if (siblingNameTaken(networkId, parentId as string | null, name)) return fail(409, "department_name_taken");
|
|
193
|
+
const leader = body.leader_user_id === undefined || body.leader_user_id === null || body.leader_user_id === "" ? null : body.leader_user_id;
|
|
194
|
+
if (leader !== null && (typeof leader !== "string" || !isMember(networkId, leader))) return fail(400, "leader_not_member");
|
|
195
|
+
if (body.sort !== undefined && !Number.isInteger(body.sort)) return fail(400, "invalid_sort");
|
|
196
|
+
const count = db.get<{ n: number }>("SELECT COUNT(*) AS n FROM network_departments WHERE network_id = ?1", networkId)?.n ?? 0;
|
|
197
|
+
if (count >= MAX_DEPARTMENTS) return fail(400, "too_many_departments");
|
|
198
|
+
const sort = body.sort === undefined
|
|
199
|
+
? (db.get<{ n: number }>(
|
|
200
|
+
parentId === null
|
|
201
|
+
? "SELECT COUNT(*) AS n FROM network_departments WHERE network_id = ?1 AND parent_id IS NULL"
|
|
202
|
+
: "SELECT COUNT(*) AS n FROM network_departments WHERE network_id = ?1 AND parent_id = ?2",
|
|
203
|
+
...(parentId === null ? [networkId] : [networkId, parentId]),
|
|
204
|
+
)?.n ?? 0)
|
|
205
|
+
: body.sort as number;
|
|
206
|
+
groupTx(() => {
|
|
207
|
+
db.run(
|
|
208
|
+
"INSERT INTO network_departments (network_id, department_id, name, parent_id, leader_user_id, sort, created_by) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
|
|
209
|
+
[networkId, id, name, parentId, leader, sort, actor],
|
|
210
|
+
);
|
|
211
|
+
// RFC-042 §4:新部门带负责人 → 上级部门群的 roster 多了这个负责人。没有负责人的新部门是空的,roster 不变。
|
|
212
|
+
if (leader !== null) syncDepartmentGroups(networkId);
|
|
213
|
+
});
|
|
214
|
+
return { ok: true, department: publicOne(networkId, id) };
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
export function updateDepartment(networkId: string, id: string, body: Record<string, unknown>): Ok<{ department: Department }> | Fail {
|
|
218
|
+
const cur = one(networkId, id);
|
|
219
|
+
if (!cur) return fail(404, "department_not_found");
|
|
220
|
+
let name = cur.name;
|
|
221
|
+
let parentId = cur.parent_id;
|
|
222
|
+
let leader = cur.leader_user_id;
|
|
223
|
+
let sort = cur.sort;
|
|
224
|
+
let touched = false;
|
|
225
|
+
if (body.name !== undefined) {
|
|
226
|
+
const n = cleanName(body.name);
|
|
227
|
+
if (!n) return fail(400, "invalid_department_name");
|
|
228
|
+
name = n; touched = true;
|
|
229
|
+
}
|
|
230
|
+
if (body.parent_id !== undefined) {
|
|
231
|
+
const p = body.parent_id === null || body.parent_id === "" ? null : body.parent_id;
|
|
232
|
+
if (p !== null && (typeof p !== "string" || !one(networkId, p))) return fail(400, "parent_not_found");
|
|
233
|
+
if (p !== null && isDescendant(networkId, id, p as string)) return fail(400, "department_cycle");
|
|
234
|
+
if (depthOf(networkId, p as string | null) + subtreeHeight(networkId, id) > MAX_DEPTH) return fail(400, "department_too_deep");
|
|
235
|
+
parentId = p as string | null; touched = true;
|
|
236
|
+
}
|
|
237
|
+
if (body.leader_user_id !== undefined) {
|
|
238
|
+
const l = body.leader_user_id === null || body.leader_user_id === "" ? null : body.leader_user_id;
|
|
239
|
+
if (l !== null && (typeof l !== "string" || !isMember(networkId, l))) return fail(400, "leader_not_member");
|
|
240
|
+
leader = l as string | null; touched = true;
|
|
241
|
+
}
|
|
242
|
+
if (body.sort !== undefined) {
|
|
243
|
+
if (!Number.isInteger(body.sort)) return fail(400, "invalid_sort");
|
|
244
|
+
sort = body.sort as number; touched = true;
|
|
245
|
+
}
|
|
246
|
+
if (!touched) return fail(400, "empty_patch");
|
|
247
|
+
if ((name !== cur.name || parentId !== cur.parent_id) && siblingNameTaken(networkId, parentId, name, id)) return fail(409, "department_name_taken");
|
|
248
|
+
groupTx(() => {
|
|
249
|
+
db.run(
|
|
250
|
+
"UPDATE network_departments SET name = ?3, parent_id = ?4, leader_user_id = ?5, sort = ?6, updated_at = datetime('now') WHERE network_id = ?1 AND department_id = ?2",
|
|
251
|
+
[networkId, id, name, parentId, leader, sort],
|
|
252
|
+
);
|
|
253
|
+
// RFC-042 §4:改上级(子树变了)/ 换负责人 → 同一事务对账部门群。只改名 / 排序不影响 roster。
|
|
254
|
+
if (parentId !== cur.parent_id || leader !== cur.leader_user_id) syncDepartmentGroups(networkId);
|
|
255
|
+
});
|
|
256
|
+
return { ok: true, department: publicOne(networkId, id) };
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/** 只删空部门:有子部门 / 有成员 → 409(带数字,界面照着说)。 */
|
|
260
|
+
export function deleteDepartment(networkId: string, id: string): Ok<{ deleted: string }> | (Fail & { children?: number; members?: number; agents?: number }) {
|
|
261
|
+
if (!one(networkId, id)) return fail(404, "department_not_found");
|
|
262
|
+
const children = db.get<{ n: number }>("SELECT COUNT(*) AS n FROM network_departments WHERE network_id = ?1 AND parent_id = ?2", networkId, id)?.n ?? 0;
|
|
263
|
+
const members = db.get<{ n: number }>("SELECT COUNT(*) AS n FROM network_members WHERE network_id = ?1 AND department_id = ?2", networkId, id)?.n ?? 0;
|
|
264
|
+
// #1894 —— Agent 的部门归属是 nodes.department_id(显式归属线)。以前只数人类成员,
|
|
265
|
+
// 于是「部门里还有 300 个 Agent」也能被删掉,留下指向不存在部门的悬空归属。
|
|
266
|
+
const agents = db.get<{ n: number }>("SELECT COUNT(*) AS n FROM nodes WHERE network_id = ?1 AND department_id = ?2", networkId, id)?.n ?? 0;
|
|
267
|
+
if (children || members || agents) return { ...fail(409, "department_not_empty"), children, members, agents };
|
|
268
|
+
// RFC-040:部门的项目授权(network_department_project_grants)和部门同一事务删掉。
|
|
269
|
+
groupTx(() => {
|
|
270
|
+
db.run("DELETE FROM network_departments WHERE network_id = ?1 AND department_id = ?2", [networkId, id]);
|
|
271
|
+
deleteDepartmentGrants(networkId, id);
|
|
272
|
+
// RFC-042:部门群解除关联(群和成员、以后的聊天记录都留着),不删。
|
|
273
|
+
unlinkDepartmentGroup(networkId, id);
|
|
274
|
+
// 删掉的部门的负责人可能还在上级部门群的 roster 里(负责人不必在本部门):对账一次。解除关联的群不再对账。
|
|
275
|
+
syncDepartmentGroups(networkId);
|
|
276
|
+
});
|
|
277
|
+
return { ok: true, deleted: id };
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/** 把成员放进一个部门(null = 未分配)。 */
|
|
281
|
+
export function setMemberDepartment(networkId: string, userId: string, departmentId: unknown): Ok<{ user_id: string; department_id: string | null }> | Fail {
|
|
282
|
+
if (!isMember(networkId, userId)) return fail(404, "member_not_found");
|
|
283
|
+
const dept = departmentId === null || departmentId === "" ? null : departmentId;
|
|
284
|
+
if (dept !== null && (typeof dept !== "string" || !one(networkId, dept))) return fail(400, "department_not_found");
|
|
285
|
+
groupTx(() => {
|
|
286
|
+
db.run("UPDATE network_members SET department_id = ?3 WHERE network_id = ?1 AND user_id = ?2", [networkId, userId, dept]);
|
|
287
|
+
// RFC-042 §4:调进 / 调出 → 同一事务对账部门群(manual 行不动)。
|
|
288
|
+
syncDepartmentGroups(networkId);
|
|
289
|
+
});
|
|
290
|
+
return { ok: true, user_id: userId, department_id: dept as string | null };
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/** Agent(节点)显式归属部门。`null` / "" = 清掉,回到「按负责人的部门推断」。 */
|
|
294
|
+
export function setAgentDepartment(
|
|
295
|
+
networkId: string,
|
|
296
|
+
nodeId: string,
|
|
297
|
+
departmentId: unknown,
|
|
298
|
+
): Ok<{ node_id: string; department_id: string | null }> | Fail {
|
|
299
|
+
const node = db.get<{ node_id: string }>("SELECT node_id FROM nodes WHERE network_id = ?1 AND node_id = ?2", networkId, nodeId);
|
|
300
|
+
if (!node) return fail(404, "node_not_found");
|
|
301
|
+
const dept = departmentId === null || departmentId === "" ? null : departmentId;
|
|
302
|
+
if (dept !== null && (typeof dept !== "string" || !one(networkId, dept))) return fail(400, "department_not_found");
|
|
303
|
+
db.run("UPDATE nodes SET department_id = ?3, updated_at = datetime('now') WHERE network_id = ?1 AND node_id = ?2", [networkId, nodeId, dept]);
|
|
304
|
+
// 部门群(RFC-042)按成员归属同步:Agent 不是群成员,这里只保证不把群带歪。
|
|
305
|
+
syncDepartmentGroups(networkId);
|
|
306
|
+
return { ok: true, node_id: nodeId, department_id: dept as string | null };
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/** 网络删掉时一起清(和项目授权同一时机调用)。 */
|
|
310
|
+
export function deleteDepartmentsForNetwork(networkId: string): void {
|
|
311
|
+
db.run("DELETE FROM network_departments WHERE network_id = ?1", [networkId]);
|
|
312
|
+
deleteDepartmentGrantsForNetwork(networkId);
|
|
313
|
+
deleteChatGroupsForNetwork(networkId); // RFC-042:网络没了,群一起删
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
export function auditDepartment(user: { user_id: string; username: string }, action: string, networkId: string, detail: string): void {
|
|
317
|
+
logAudit(user.user_id, user.username, action, "network", networkId, detail.slice(0, 2000), undefined, networkId);
|
|
318
|
+
}
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
// #1459 —— P2 写路径与 P3 读路径的**接缝**。
|
|
2
|
+
//
|
|
3
|
+
// 通信龙 在 origin/main 上核出的覆盖缝:desktop-message.test.ts 测真实 send 但
|
|
4
|
+
// 不碰 scope=user 读;user-inbox-read-http.test.ts 测 scope=user 读但用 SQL 直接
|
|
5
|
+
// 播种行。两半各自对着自己的夹具绿,而"真实 send 写进的行、真实 scope=user
|
|
6
|
+
// 读得回来"从没验过。本文件就走这一条:真 send → 真 HTTP 读。
|
|
7
|
+
//
|
|
8
|
+
// 附带钉住 network_id 不为 NULL 的**真实机制**:不是 INSERT 时兜底,而是
|
|
9
|
+
// tools.ts 里 `if (!effectiveNetId) return writeDeniedReply(...)` 在写之前就拒。
|
|
10
|
+
// 见下面 "解析不出 network 时拒发" 那条 —— 把那个 if 拿掉,本文件会红。
|
|
11
|
+
import { afterAll, beforeAll, describe, expect, test } from "bun:test";
|
|
12
|
+
import { mkdtempSync, rmSync } from "node:fs";
|
|
13
|
+
import { tmpdir } from "node:os";
|
|
14
|
+
import { join } from "node:path";
|
|
15
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
16
|
+
|
|
17
|
+
const PRIVATE_DB_DIR = mkdtempSync(join(tmpdir(), "anet-dm-seam-"));
|
|
18
|
+
process.env.COMMHUB_DB ||= join(PRIVATE_DB_DIR, "hub.db");
|
|
19
|
+
|
|
20
|
+
let server: ReturnType<typeof Bun.serve>;
|
|
21
|
+
let base = "";
|
|
22
|
+
let targetToken = "";
|
|
23
|
+
let senderId = "", targetId = "", senderNet = "", secondNet = "";
|
|
24
|
+
let send: (args: any) => Promise<Record<string, any>>;
|
|
25
|
+
|
|
26
|
+
function buildSend(opts: { netId: string | null; userId: string | null; alias: string | null }) {
|
|
27
|
+
const mcp = new McpServer({ name: "test", version: "0" }) as any;
|
|
28
|
+
const tools: Record<string, any> = {};
|
|
29
|
+
const origTool = mcp.tool.bind(mcp);
|
|
30
|
+
mcp.tool = (name: string, _d: string, _s: any, handler: any) => { tools[name] = handler; return origTool(name, _d, _s, handler); };
|
|
31
|
+
const { registerTools } = require("./tools.js");
|
|
32
|
+
registerTools(mcp, undefined, opts.netId, opts.userId, opts.alias, false, "tok_seam_test");
|
|
33
|
+
return async (args: any) => JSON.parse((await tools["send_desktop_message"](args)).content[0].text);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
beforeAll(async () => {
|
|
37
|
+
const { db } = await import("./db.js");
|
|
38
|
+
const { register, addNetworkMember } = await import("./auth.js");
|
|
39
|
+
const stamp = Date.now();
|
|
40
|
+
|
|
41
|
+
// 首个注册用户自动成为全局 admin,而 admin 读侧不走 scope 过滤分支。
|
|
42
|
+
// 收件人必须是普通 user,否则"读得回来"可能只是因为它绕过了过滤。
|
|
43
|
+
expect(register(`seam_admin_${stamp}`, "SeamAdmin-Strong-1!").ok).toBe(true);
|
|
44
|
+
const s = register(`seam_sender_${stamp}`, "SeamSender-Strong-1!");
|
|
45
|
+
const t = register(`seam_target_${stamp}`, "SeamTarget-Strong-1!");
|
|
46
|
+
expect(s.ok && t.ok).toBe(true);
|
|
47
|
+
targetToken = t.token!;
|
|
48
|
+
senderNet = s.network_id!;
|
|
49
|
+
secondNet = t.network_id!;
|
|
50
|
+
senderId = db.get<{ user_id: string }>("SELECT user_id FROM users WHERE username = ?1", `seam_sender_${stamp}`)!.user_id;
|
|
51
|
+
targetId = db.get<{ user_id: string }>("SELECT user_id FROM users WHERE username = ?1", `seam_target_${stamp}`)!.user_id;
|
|
52
|
+
expect(db.get<{ role: string }>("SELECT role FROM users WHERE user_id = ?1", targetId)?.role).toBe("user");
|
|
53
|
+
|
|
54
|
+
// 收件人进发件人的网(真实形态:同网两成员)。
|
|
55
|
+
expect(addNetworkMember(senderNet, targetId, "member").ok).toBe(true);
|
|
56
|
+
|
|
57
|
+
send = buildSend({ netId: senderNet, userId: senderId, alias: "seam-sender" });
|
|
58
|
+
|
|
59
|
+
const mod = await import("./server.js");
|
|
60
|
+
server = mod.bootServer({ port: 0, hostname: "127.0.0.1" });
|
|
61
|
+
base = `http://127.0.0.1:${server.port}`;
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
afterAll(() => {
|
|
65
|
+
try { server?.stop(true); } catch {}
|
|
66
|
+
try { rmSync(PRIVATE_DB_DIR, { recursive: true, force: true }); } catch {}
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
const readOwn = async (token: string, qs = "") => {
|
|
70
|
+
const r = await fetch(`${base}/api/messages?scope=user${qs}`, { headers: { Authorization: `Bearer ${token}` } });
|
|
71
|
+
return { status: r.status, body: await r.json() as any };
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
describe("#1459 P2 写 → P3 读 接缝", () => {
|
|
75
|
+
test("🔴 真实 send_desktop_message 写进的行,真实 GET ?scope=user 读得回来", async () => {
|
|
76
|
+
const sent = await send({ to_user_id: targetId, message: "接缝测试正文", title: "接缝", severity: "warning", kind: "agent_message" });
|
|
77
|
+
expect([sent.ok, sent.persisted]).toEqual([true, true]);
|
|
78
|
+
|
|
79
|
+
const { status, body } = await readOwn(targetToken);
|
|
80
|
+
expect(status).toBe(200);
|
|
81
|
+
const row = body.messages.find((m: any) => m.message_id === sent.message_id);
|
|
82
|
+
expect(row).toBeTruthy(); // 承重:两半接得上
|
|
83
|
+
expect(row.content).toBe("接缝测试正文");
|
|
84
|
+
expect(row.title).toBe("接缝");
|
|
85
|
+
expect(row.severity).toBe("warning");
|
|
86
|
+
expect(row.user_id).toBe(targetId);
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
test("🔴 落库的 network_id 就是授权用的那个网,不是 NULL —— 否则 scoped 读回不来", async () => {
|
|
90
|
+
const { db } = require("./db.js");
|
|
91
|
+
const sent = await send({ to_user_id: targetId, message: "网络归属" });
|
|
92
|
+
const row = db.get<any>("SELECT network_id FROM user_inbox WHERE message_id = ?1", sent.message_id);
|
|
93
|
+
expect(row.network_id).toBe(senderNet);
|
|
94
|
+
|
|
95
|
+
const { body } = await readOwn(targetToken);
|
|
96
|
+
expect(body.messages.map((m: any) => m.message_id)).toContain(sent.message_id);
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
test("unread 随真实 send 增长", async () => {
|
|
100
|
+
const before = (await readOwn(targetToken)).body.unread;
|
|
101
|
+
await send({ to_user_id: targetId, message: "计数 +1" });
|
|
102
|
+
expect((await readOwn(targetToken)).body.unread).toBe(before + 1);
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
test("redact-at-read 作用在真实写进去的正文上", async () => {
|
|
106
|
+
const sent = await send({ to_user_id: targetId, message: "凭据 ntok_seamtoken123456 在正文里" });
|
|
107
|
+
const { db } = require("./db.js");
|
|
108
|
+
// 存储侧保留原文,遮蔽发生在**回读**时 —— 这两句一起才说明是 read-time 脱敏。
|
|
109
|
+
expect(db.get<any>("SELECT content FROM user_inbox WHERE message_id = ?1", sent.message_id).content)
|
|
110
|
+
.toContain("ntok_seamtoken123456");
|
|
111
|
+
const row = (await readOwn(targetToken)).body.messages.find((m: any) => m.message_id === sent.message_id);
|
|
112
|
+
expect(row.content).toContain("ntok_***redacted***");
|
|
113
|
+
expect(row.content).not.toContain("ntok_seamtoken123456");
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
// 🔴 这一条是 `if (!effectiveNetId) return` 这道守卫**唯一**能被触发的场景。
|
|
117
|
+
// 有 auth ctx 时前一道 `canWrite` 就拦了;而 canRestWriteNetwork 对
|
|
118
|
+
// legacy 全局 token / --dev-open(authCtx 为 null)是 `return true`
|
|
119
|
+
// (network-scope.ts:96)—— 那条路上只剩这道守卫挡着 NULL 孤儿行。
|
|
120
|
+
// 把 tools.ts:2320 那行删掉,本条会红(写出一行 network_id=NULL)。
|
|
121
|
+
test("🔴 legacy 无 auth ctx 的调用者同样拒发,不写 NULL 孤儿行", async () => {
|
|
122
|
+
const { db } = require("./db.js");
|
|
123
|
+
const legacy = buildSend({ netId: null, userId: null as any, alias: null as any });
|
|
124
|
+
const before = db.get<{ n: number }>("SELECT COUNT(*) AS n FROM user_inbox")!.n;
|
|
125
|
+
const r = await legacy({ to_user_id: targetId, message: "legacy 无网络上下文" });
|
|
126
|
+
expect(r.ok).toBe(false);
|
|
127
|
+
expect(r.error).toBe("network_id_required");
|
|
128
|
+
expect(db.get<{ n: number }>("SELECT COUNT(*) AS n FROM user_inbox")!.n).toBe(before);
|
|
129
|
+
expect(db.get<{ n: number }>("SELECT COUNT(*) AS n FROM user_inbox WHERE network_id IS NULL")!.n).toBe(0);
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
test("🔴 解析不出 network 时**拒发**,而不是写一行 network_id=NULL 的孤儿", async () => {
|
|
133
|
+
const { db } = require("./db.js");
|
|
134
|
+
const { addNetworkMember } = require("./auth.js");
|
|
135
|
+
// 发件人进第二个网 ⇒ 不带 network_id 时 singleNetworkId 解析不出唯一网。
|
|
136
|
+
addNetworkMember(secondNet, senderId, "member");
|
|
137
|
+
const ambiguous = buildSend({ netId: null, userId: senderId, alias: "seam-sender" });
|
|
138
|
+
|
|
139
|
+
const before = db.get<{ n: number }>("SELECT COUNT(*) AS n FROM user_inbox")!.n;
|
|
140
|
+
const r = await ambiguous({ to_user_id: targetId, message: "无法解析网络" });
|
|
141
|
+
|
|
142
|
+
expect(r.ok).toBe(false);
|
|
143
|
+
expect(r.error).toBe("network_id_required");
|
|
144
|
+
// 承重:拒发意味着**一行都不写**。若把 tools.ts 的
|
|
145
|
+
// `if (!effectiveNetId) return writeDeniedReply(...)` 拿掉,这里会多出一行
|
|
146
|
+
// network_id=NULL 的孤儿 —— 写得进去、scoped 读不回来。
|
|
147
|
+
expect(db.get<{ n: number }>("SELECT COUNT(*) AS n FROM user_inbox")!.n).toBe(before);
|
|
148
|
+
expect(db.get<{ n: number }>("SELECT COUNT(*) AS n FROM user_inbox WHERE network_id IS NULL")!.n).toBe(0);
|
|
149
|
+
});
|
|
150
|
+
});
|