@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
package/src/db.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { refreshScheduledBackoff } from "./scheduled-backoff.js"; import { scheduledFailureCode } from "./scheduled-failure-code.js";
|
|
2
|
+
import { createAdapter, type DbAdapter } from "./db-adapter"; import { withStatementHook } from "./status-read-cache"; // #431 写 sessions 的语句让 /api/status 缓存失效
|
|
2
3
|
|
|
3
|
-
export const db: DbAdapter = createAdapter();
|
|
4
|
+
export const db: DbAdapter = withStatementHook(createAdapter());
|
|
4
5
|
|
|
5
6
|
// Schema
|
|
6
7
|
db.exec(`
|
|
@@ -53,6 +54,38 @@ db.exec(`
|
|
|
53
54
|
CREATE INDEX IF NOT EXISTS idx_inbox_pending
|
|
54
55
|
ON inbox(session_name, acked) WHERE acked = 0;
|
|
55
56
|
|
|
57
|
+
-- #1459 ① — agent→用户的 desktop message 持久化收件箱。
|
|
58
|
+
-- inbox 是 session_name(alias) 寻址的;desktop message 目标是 user_id,不能复用
|
|
59
|
+
-- inbox(否则 /api/messages+inbox_count+SSE gate 一票 alias 域查询会隐性开始返回
|
|
60
|
+
-- 用户消息)。单独一张 user_id 寻址表,镜像 inbox 的 acked/count 语义。
|
|
61
|
+
-- message_id 即主键(dm_<uuid>,与 inbox「消息 id 即主键」同形)→ 写入用
|
|
62
|
+
-- INSERT OR IGNORE,send_desktop_message 重试天然幂等,不会插出重复消息行。
|
|
63
|
+
-- 索引留到 P3:读取查询形状定了再按真实 WHERE 加(SDK马 review:没查询就加索引是猜;
|
|
64
|
+
-- 部分索引 acked=0 若「近期」读含已 ack 行则用不上)。P1 只落表。
|
|
65
|
+
CREATE TABLE IF NOT EXISTS user_inbox (
|
|
66
|
+
message_id TEXT PRIMARY KEY,
|
|
67
|
+
network_id TEXT NOT NULL,
|
|
68
|
+
user_id TEXT NOT NULL,
|
|
69
|
+
from_session TEXT,
|
|
70
|
+
kind TEXT NOT NULL DEFAULT 'info',
|
|
71
|
+
title TEXT,
|
|
72
|
+
content TEXT NOT NULL,
|
|
73
|
+
severity TEXT NOT NULL DEFAULT 'info',
|
|
74
|
+
meta_json TEXT,
|
|
75
|
+
acked INTEGER NOT NULL DEFAULT 0,
|
|
76
|
+
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
77
|
+
acked_at TEXT
|
|
78
|
+
);
|
|
79
|
+
|
|
80
|
+
-- #1459 ① P3 —— 现在有真实查询了才建索引(P1 刻意没建:没有查询就加索引是猜)。
|
|
81
|
+
-- 覆盖回读分支的两条:
|
|
82
|
+
-- 列表 SELECT ... WHERE user_id = ? [AND acked = 0] ORDER BY created_at DESC
|
|
83
|
+
-- 未读数 SELECT COUNT(*) WHERE user_id = ? AND acked = 0
|
|
84
|
+
-- 不是部分索引(不写 WHERE acked = 0):列表在 unacked=0 时要读**含已 ack 的**
|
|
85
|
+
-- 近期消息,部分索引那时用不上。
|
|
86
|
+
CREATE INDEX IF NOT EXISTS idx_user_inbox_user_acked
|
|
87
|
+
ON user_inbox(user_id, acked, created_at);
|
|
88
|
+
|
|
56
89
|
CREATE TABLE IF NOT EXISTS completions (
|
|
57
90
|
id TEXT PRIMARY KEY,
|
|
58
91
|
session_name TEXT NOT NULL,
|
|
@@ -89,6 +122,28 @@ for (const col of [
|
|
|
89
122
|
{ name: "process_cpu_pct", def: "REAL" },
|
|
90
123
|
{ name: "process_uptime_seconds", def: "REAL" },
|
|
91
124
|
{ name: "process_in_flight_count", def: "INTEGER" },
|
|
125
|
+
{ name: "external_schedules", def: "TEXT" },
|
|
126
|
+
{ name: "peer_reply_inbox_capable", def: "INTEGER NOT NULL DEFAULT 0" },
|
|
127
|
+
// app#225 follow-up — a session (incl. claude-code sessions with no `nodes` row)
|
|
128
|
+
// that answers the rules-file doorbell. Sticky: set by a bound node token, never
|
|
129
|
+
// cleared by reports that omit it (agent-node status-only reports do).
|
|
130
|
+
{ name: "rules_file_capable", def: "INTEGER NOT NULL DEFAULT 0" },
|
|
131
|
+
// Node skills view — the same session answers skills_list / skill_read on the
|
|
132
|
+
// rules-file doorbell (node-skills.ts). Sticky, bound-token only, like above.
|
|
133
|
+
{ name: "skills_capable", def: "INTEGER NOT NULL DEFAULT 0" },
|
|
134
|
+
// Project folder view — the same session answers files_list / file_read on the
|
|
135
|
+
// rules-file doorbell (node-files.ts). Sticky, bound-token only, like above.
|
|
136
|
+
{ name: "files_capable", def: "INTEGER NOT NULL DEFAULT 0" },
|
|
137
|
+
// Node run-log view — the same session answers logs_tail on the rules-file
|
|
138
|
+
// doorbell (node-logs.ts). Sticky, bound-token only, like above.
|
|
139
|
+
{ name: "logs_capable", def: "INTEGER NOT NULL DEFAULT 0" },
|
|
140
|
+
// #2211 — what the node last did with the network's team rules (agent-node .156+
|
|
141
|
+
// reports it on every status). Not sticky: the newest report wins, and a node that
|
|
142
|
+
// later starts reporting `skipped` must be able to clear an older revision.
|
|
143
|
+
{ name: "team_rules_revision", def: "INTEGER" },
|
|
144
|
+
{ name: "team_rules_status", def: "TEXT" },
|
|
145
|
+
{ name: "team_rules_at", def: "TEXT" },
|
|
146
|
+
{ name: "team_rules_reason", def: "TEXT" },
|
|
92
147
|
]) {
|
|
93
148
|
try { db.exec(`ALTER TABLE sessions ADD COLUMN ${col.name} ${col.def}`); } catch {}
|
|
94
149
|
}
|
|
@@ -119,6 +174,13 @@ db.exec(`
|
|
|
119
174
|
|
|
120
175
|
CREATE INDEX IF NOT EXISTS idx_agent_telemetry_alias_time
|
|
121
176
|
ON agent_telemetry(network_id, alias, created_at);
|
|
177
|
+
|
|
178
|
+
-- #2614 —— retention 每小时跑一次 DELETE FROM agent_telemetry WHERE created_at < ?。
|
|
179
|
+
-- 上面三个复合索引都以 network_id 打头,**这个查询用不上**(没有 network_id 等值条件),
|
|
180
|
+
-- 于是每次扫全表 62 万行 → 生产实测每小时出现 **8–11 秒的事件循环阻塞**
|
|
181
|
+
-- ([commhub retention] swept in 8331ms / 9863ms / 10588ms,同时日志静默 11 秒)。
|
|
182
|
+
-- 单独给 created_at 建索引,让这个扫描变成范围 seek。
|
|
183
|
+
CREATE INDEX IF NOT EXISTS idx_agent_telemetry_created ON agent_telemetry(created_at);
|
|
122
184
|
`);
|
|
123
185
|
|
|
124
186
|
// Round-2/4 review ② — server-health index split.
|
|
@@ -162,6 +224,11 @@ for (const col of [
|
|
|
162
224
|
{ name: "scope", def: "TEXT DEFAULT 'single'" },
|
|
163
225
|
{ name: "meta_json", def: "TEXT" },
|
|
164
226
|
{ name: "node_id", def: "TEXT" },
|
|
227
|
+
// #520 — explicit logical task identity. Initial deliveries historically
|
|
228
|
+
// used inbox.id == tasks.task_id, while retry/reassign generate a fresh
|
|
229
|
+
// inbox row id. Keep transport-row identity and logical-task identity
|
|
230
|
+
// separate so runtime evidence/replies survive those redeliveries.
|
|
231
|
+
{ name: "task_id", def: "TEXT" },
|
|
165
232
|
]) {
|
|
166
233
|
try { db.exec(`ALTER TABLE inbox ADD COLUMN ${col.name} ${col.def}`); } catch {}
|
|
167
234
|
}
|
|
@@ -191,6 +258,11 @@ db.exec(`
|
|
|
191
258
|
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
192
259
|
delivered_at TEXT,
|
|
193
260
|
started_at TEXT,
|
|
261
|
+
runtime_submitted_at TEXT,
|
|
262
|
+
consumed_at TEXT,
|
|
263
|
+
last_activity_at TEXT,
|
|
264
|
+
thread_id TEXT,
|
|
265
|
+
turn_id TEXT,
|
|
194
266
|
completed_at TEXT,
|
|
195
267
|
expires_at TEXT
|
|
196
268
|
);
|
|
@@ -237,6 +309,8 @@ db.exec(`
|
|
|
237
309
|
task_id TEXT NOT NULL,
|
|
238
310
|
from_status TEXT,
|
|
239
311
|
to_status TEXT NOT NULL,
|
|
312
|
+
event_type TEXT,
|
|
313
|
+
event_key TEXT,
|
|
240
314
|
actor TEXT NOT NULL DEFAULT 'system',
|
|
241
315
|
detail TEXT,
|
|
242
316
|
created_at TEXT NOT NULL DEFAULT (datetime('now'))
|
|
@@ -262,6 +336,30 @@ db.exec(`
|
|
|
262
336
|
CREATE INDEX IF NOT EXISTS idx_users_username ON users(username);
|
|
263
337
|
`);
|
|
264
338
|
|
|
339
|
+
// 账号头像上传(二进制 PNG,Hub 自己发 URL)。与 users.avatar_url 并存:
|
|
340
|
+
// avatar_url 仍可指向内建池/外链;这张表只存「上传到 Hub 本人的那张」。
|
|
341
|
+
// 单行/人:新版本覆盖旧版本,旧 URL 立刻 404(version 变了),不做历史留存。
|
|
342
|
+
db.exec(`
|
|
343
|
+
CREATE TABLE IF NOT EXISTS user_avatar_uploads (
|
|
344
|
+
user_id TEXT PRIMARY KEY,
|
|
345
|
+
version TEXT NOT NULL,
|
|
346
|
+
png BLOB NOT NULL,
|
|
347
|
+
bytes INTEGER NOT NULL,
|
|
348
|
+
width INTEGER NOT NULL,
|
|
349
|
+
height INTEGER NOT NULL,
|
|
350
|
+
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
|
|
351
|
+
);
|
|
352
|
+
`);
|
|
353
|
+
|
|
354
|
+
// Human profile avatar. Additive for existing databases; old binaries ignore it.
|
|
355
|
+
try {
|
|
356
|
+
db.exec("ALTER TABLE users ADD COLUMN avatar_url TEXT");
|
|
357
|
+
} catch (e: any) {
|
|
358
|
+
// Both supported adapters report a duplicate column on the next startup.
|
|
359
|
+
// Do not send SQLite PRAGMA to PostgreSQL or swallow other migration errors.
|
|
360
|
+
if (!/duplicate column|already exists/i.test(e?.message || "")) throw e;
|
|
361
|
+
}
|
|
362
|
+
|
|
265
363
|
// #261 P0-2 (2026-06-28): must_change_password flag. Added via ALTER
|
|
266
364
|
// (not in the CREATE block above) so it's a no-op on fresh DBs that
|
|
267
365
|
// already get the column via the CREATE path's full definition AND a
|
|
@@ -301,6 +399,16 @@ try {
|
|
|
301
399
|
if (!/duplicate column|already exists/i.test(e?.message || "")) throw e;
|
|
302
400
|
}
|
|
303
401
|
|
|
402
|
+
// RFC-036 / B4 — immutable per-node owner. New nodes receive this value in
|
|
403
|
+
// the same transaction that mints their node token. Heartbeats may verify the
|
|
404
|
+
// binding but must never first-claim or replace it. Legacy NULL rows remain
|
|
405
|
+
// read-only for external-schedule writes.
|
|
406
|
+
try {
|
|
407
|
+
db.exec(`ALTER TABLE nodes ADD COLUMN owner_user_id TEXT`);
|
|
408
|
+
} catch (e: any) {
|
|
409
|
+
if (!/duplicate column|already exists/i.test(e?.message || "")) throw e;
|
|
410
|
+
}
|
|
411
|
+
|
|
304
412
|
// RFC-026 §9 / #338 PR2 — daemon self-declare fields promoted from
|
|
305
413
|
// config_snapshot to first-class indexable columns. The hub
|
|
306
414
|
// `list_host_supervisors` MCP tool reads these directly without parsing
|
|
@@ -391,6 +499,7 @@ db.exec(`
|
|
|
391
499
|
daemon_node_id TEXT NOT NULL,
|
|
392
500
|
child_node_id TEXT NOT NULL,
|
|
393
501
|
child_alias TEXT NOT NULL,
|
|
502
|
+
child_token_id TEXT,
|
|
394
503
|
action TEXT NOT NULL CHECK (action IN ('stop', 'delete')),
|
|
395
504
|
delete_config INTEGER NOT NULL DEFAULT 1,
|
|
396
505
|
grace_seconds INTEGER NOT NULL DEFAULT 10,
|
|
@@ -408,8 +517,75 @@ db.exec(`
|
|
|
408
517
|
`);
|
|
409
518
|
db.exec(`CREATE INDEX IF NOT EXISTS idx_stop_req_daemon ON node_stop_requests(daemon_node_id, status)`);
|
|
410
519
|
db.exec(`CREATE INDEX IF NOT EXISTS idx_stop_req_child ON node_stop_requests(child_node_id)`);
|
|
520
|
+
// #1448 finding-5 — 存 delete 目标 child 的 token_id,让 ack 精确按 token_id 撤 ntok
|
|
521
|
+
// (而非按 name='node:<alias>' 广撤 → 同 alias 在 delete 窗口内重建会误杀新 token)。
|
|
522
|
+
// 幂等迁移:已有库补列,旧行 child_token_id 为 NULL、ack 时 fallback 回按 name 撤。
|
|
523
|
+
try { db.exec(`ALTER TABLE node_stop_requests ADD COLUMN child_token_id TEXT`); } catch { /* 已存在 */ }
|
|
524
|
+
|
|
525
|
+
// Daemon-mediated start request. Kept separate from node_stop_requests:
|
|
526
|
+
// the deployed stop table has a CHECK(action IN ('stop','delete')) and
|
|
527
|
+
// rebuilding that table in-place would be a risky migration for an additive
|
|
528
|
+
// lifecycle operation.
|
|
529
|
+
db.exec(`
|
|
530
|
+
CREATE TABLE IF NOT EXISTS node_start_requests (
|
|
531
|
+
request_id TEXT PRIMARY KEY,
|
|
532
|
+
network_id TEXT NOT NULL,
|
|
533
|
+
daemon_node_id TEXT NOT NULL,
|
|
534
|
+
child_node_id TEXT NOT NULL,
|
|
535
|
+
child_alias TEXT NOT NULL,
|
|
536
|
+
created_by_token TEXT NOT NULL,
|
|
537
|
+
status TEXT NOT NULL DEFAULT 'pending',
|
|
538
|
+
error TEXT,
|
|
539
|
+
child_pid INTEGER,
|
|
540
|
+
created_at INTEGER NOT NULL,
|
|
541
|
+
delivered_at INTEGER,
|
|
542
|
+
acked_at INTEGER
|
|
543
|
+
)
|
|
544
|
+
`);
|
|
545
|
+
db.exec(`CREATE INDEX IF NOT EXISTS idx_start_req_daemon ON node_start_requests(daemon_node_id, status)`);
|
|
546
|
+
db.exec(`CREATE INDEX IF NOT EXISTS idx_start_req_child ON node_start_requests(child_node_id)`);
|
|
547
|
+
// Additive: old rows remain ordinary starts (NULL). Keep the request and the
|
|
548
|
+
// observed side effect separate from launcher status, including startup failure.
|
|
549
|
+
for (const column of ["fork_recovery_json", "fork_result_json"]) {
|
|
550
|
+
try { db.exec(`ALTER TABLE node_start_requests ADD COLUMN ${column} TEXT`); }
|
|
551
|
+
catch (e: any) { if (!/duplicate column|already exists/i.test(e?.message || "")) throw e; }
|
|
552
|
+
}
|
|
553
|
+
try {
|
|
554
|
+
db.exec(`CREATE UNIQUE INDEX IF NOT EXISTS uniq_start_req_child_inflight
|
|
555
|
+
ON node_start_requests(child_node_id)
|
|
556
|
+
WHERE status IN ('pending', 'delivered')`);
|
|
557
|
+
} catch (e: any) {
|
|
558
|
+
if (!/unique constraint/i.test(e?.message || "")) throw e;
|
|
559
|
+
}
|
|
411
560
|
|
|
412
561
|
// `node_config_updates` — pending + history. One row per dashboard write.
|
|
562
|
+
// #906: redacted daemon-owned inventory requests, never credential material.
|
|
563
|
+
db.exec(`CREATE TABLE IF NOT EXISTS daemon_provider_snapshots (
|
|
564
|
+
request_id TEXT PRIMARY KEY, network_id TEXT NOT NULL, daemon_node_id TEXT NOT NULL,
|
|
565
|
+
requested_by TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'pending',
|
|
566
|
+
created_at INTEGER NOT NULL, expires_at INTEGER NOT NULL, observed_at INTEGER,
|
|
567
|
+
snapshot_json TEXT, error TEXT
|
|
568
|
+
)`);
|
|
569
|
+
db.exec(`CREATE INDEX IF NOT EXISTS idx_daemon_provider_pending
|
|
570
|
+
ON daemon_provider_snapshots(network_id, daemon_node_id, status)`);
|
|
571
|
+
db.exec(`CREATE UNIQUE INDEX IF NOT EXISTS uniq_daemon_provider_inflight
|
|
572
|
+
ON daemon_provider_snapshots(network_id, daemon_node_id) WHERE status='pending'`);
|
|
573
|
+
// One encrypted mutation payload per request; public receipt remains secret-free.
|
|
574
|
+
db.exec(`CREATE TABLE IF NOT EXISTS daemon_provider_writes (
|
|
575
|
+
request_id TEXT PRIMARY KEY, expected_revision INTEGER NOT NULL,
|
|
576
|
+
ciphertext BLOB NOT NULL, iv BLOB NOT NULL, tag BLOB NOT NULL
|
|
577
|
+
)`);
|
|
578
|
+
// Application intent is credential-free; secrets stay in the daemon's store.
|
|
579
|
+
db.exec(`CREATE TABLE IF NOT EXISTS daemon_provider_applications (
|
|
580
|
+
request_id TEXT PRIMARY KEY, expected_revision INTEGER NOT NULL,
|
|
581
|
+
selection_json TEXT NOT NULL
|
|
582
|
+
)`);
|
|
583
|
+
|
|
584
|
+
// Login commands contain only intent. OAuth tokens never enter Hub storage.
|
|
585
|
+
db.exec(`CREATE TABLE IF NOT EXISTS daemon_provider_logins (
|
|
586
|
+
request_id TEXT PRIMARY KEY, intent_json TEXT NOT NULL
|
|
587
|
+
)`);
|
|
588
|
+
|
|
413
589
|
// At most one row per node may be in a non-terminal state at a time
|
|
414
590
|
// (single-flight enforced at the tool layer; this table just stores).
|
|
415
591
|
//
|
|
@@ -450,6 +626,47 @@ try {
|
|
|
450
626
|
console.warn(`[commhub] partial unique index uniq_ncu_node_inflight skipped: ${e?.message || e}`);
|
|
451
627
|
}
|
|
452
628
|
|
|
629
|
+
// ── app#225: 节点规则文件(AGENTS.md / CLAUDE.md)远程读写请求 ──
|
|
630
|
+
//
|
|
631
|
+
// 形状照抄 node_config_updates(上面):客户端落一行 + 门铃,节点拉走做完回报,
|
|
632
|
+
// 客户端轮询结果。network_id 同样在插入时从 nodes 反规范化。
|
|
633
|
+
//
|
|
634
|
+
// 🔴 这张表**故意没有路径列**:文件名由节点按自己的 RUNTIME 决定
|
|
635
|
+
// (claude → CLAUDE.md,其余 → AGENTS.md),目录固定是节点进程的 cwd。
|
|
636
|
+
// hub 侧只存 op + 内容,客户端连文件名都指定不了(#225 验收第 5 条)。
|
|
637
|
+
// file_name 是节点**回报**的实际文件名,只用于显示。
|
|
638
|
+
db.exec(`
|
|
639
|
+
CREATE TABLE IF NOT EXISTS node_rules_requests (
|
|
640
|
+
request_id TEXT PRIMARY KEY,
|
|
641
|
+
node_id TEXT NOT NULL,
|
|
642
|
+
network_id TEXT NOT NULL,
|
|
643
|
+
op TEXT NOT NULL,
|
|
644
|
+
content TEXT,
|
|
645
|
+
status TEXT NOT NULL,
|
|
646
|
+
file_name TEXT,
|
|
647
|
+
file_exists INTEGER,
|
|
648
|
+
result_content TEXT,
|
|
649
|
+
error TEXT,
|
|
650
|
+
created_at INTEGER NOT NULL,
|
|
651
|
+
created_by_token TEXT NOT NULL,
|
|
652
|
+
pulled_at INTEGER,
|
|
653
|
+
acked_at INTEGER
|
|
654
|
+
);
|
|
655
|
+
|
|
656
|
+
CREATE INDEX IF NOT EXISTS idx_nrr_node_status ON node_rules_requests(node_id, status);
|
|
657
|
+
CREATE INDEX IF NOT EXISTS idx_nrr_network ON node_rules_requests(network_id);
|
|
658
|
+
`);
|
|
659
|
+
// Content retention (node-request-retention.ts): file bytes in content /
|
|
660
|
+
// result_content are purged after the first terminal read (+grace) or a TTL;
|
|
661
|
+
// these two columns record when, so the row itself survives as audit metadata.
|
|
662
|
+
for (const col of ["first_read_at INTEGER", "content_purged_at INTEGER"]) {
|
|
663
|
+
try { db.exec(`ALTER TABLE node_rules_requests ADD COLUMN ${col}`); } catch {}
|
|
664
|
+
}
|
|
665
|
+
db.exec(`
|
|
666
|
+
CREATE INDEX IF NOT EXISTS idx_nrr_created ON node_rules_requests(created_at);
|
|
667
|
+
CREATE INDEX IF NOT EXISTS idx_nrr_first_read ON node_rules_requests(first_read_at);
|
|
668
|
+
`);
|
|
669
|
+
|
|
453
670
|
// ── V3: networks table ──
|
|
454
671
|
db.exec(`
|
|
455
672
|
CREATE TABLE IF NOT EXISTS networks (
|
|
@@ -495,14 +712,37 @@ for (const ddl of [
|
|
|
495
712
|
"ALTER TABLE api_tokens ADD COLUMN request_id TEXT",
|
|
496
713
|
"ALTER TABLE api_tokens ADD COLUMN revoked_at TEXT",
|
|
497
714
|
"ALTER TABLE api_tokens ADD COLUMN role TEXT",
|
|
715
|
+
"ALTER TABLE api_tokens ADD COLUMN bound_node_id TEXT",
|
|
716
|
+
// Existing tokens retain epoch 0. Every production issuer writes 1 (general)
|
|
717
|
+
// or 2 (ownership-checked node token); 0 is a rollout boundary, not a clock.
|
|
718
|
+
"ALTER TABLE api_tokens ADD COLUMN node_identity_epoch INTEGER NOT NULL DEFAULT 0",
|
|
719
|
+
// 登录会话的设备标识(GET /api/auth/sessions 显示用):客户端自报的 client_label + 登录请求的 User-Agent。
|
|
720
|
+
"ALTER TABLE api_tokens ADD COLUMN client_label TEXT",
|
|
721
|
+
"ALTER TABLE api_tokens ADD COLUMN user_agent TEXT",
|
|
722
|
+
// #711 不绑网络的用户令牌分两类:'login' = 浏览器 / app 的登录会话;'cli' = anet 命令行登录、
|
|
723
|
+
// POST /api/auth/tokens 建的具名脚本令牌。只用于展示和 keep_cli_tokens 那条显式保留路径;节点 / 网络令牌(network_id 非空)不填。
|
|
724
|
+
"ALTER TABLE api_tokens ADD COLUMN kind TEXT",
|
|
498
725
|
]) {
|
|
499
726
|
try { db.exec(ddl); }
|
|
500
727
|
catch (e: any) {
|
|
501
728
|
if (!/duplicate column|already exists/i.test(e?.message || "")) throw e;
|
|
502
729
|
}
|
|
503
730
|
}
|
|
731
|
+
// #711 回填 kind:只碰 kind 还是 NULL 的非网络令牌(幂等;回滚到旧 Hub 期间新签的行,下次启动照样补上)。
|
|
732
|
+
// 能明确认出是 anet 命令行的才算 'cli':scope='full'(POST /api/auth/tokens 建的具名令牌),
|
|
733
|
+
// 或 client_label 去掉首尾空格后以「anet 」开头(anet 自报的「anet <版本> · <主机> · <子命令>」)。其余一律 'login'。
|
|
734
|
+
// 用 SUBSTR + = 而不是 LIKE:SQLite 的 LIKE 不分大小写、PG 分,两边结果会不一样;= 两边都区分大小写,
|
|
735
|
+
// 与运行时 isAnetClientLabel(auth.ts)同一条规则。
|
|
736
|
+
db.run(
|
|
737
|
+
`UPDATE api_tokens SET kind = CASE
|
|
738
|
+
WHEN scope = 'full' OR SUBSTR(TRIM(client_label), 1, 5) = 'anet ' THEN 'cli'
|
|
739
|
+
ELSE 'login' END
|
|
740
|
+
WHERE network_id IS NULL AND kind IS NULL`,
|
|
741
|
+
);
|
|
504
742
|
try { db.exec(`CREATE INDEX IF NOT EXISTS idx_tokens_request ON api_tokens(request_id)`); }
|
|
505
743
|
catch (e: any) { /* index may already exist */ void e; }
|
|
744
|
+
try { db.exec(`CREATE INDEX IF NOT EXISTS idx_tokens_bound_node ON api_tokens(bound_node_id)`); }
|
|
745
|
+
catch (e: any) { void e; }
|
|
506
746
|
|
|
507
747
|
// RFC-026 v4 §2.5 + §4.4 — node_create_requests. Metadata only;
|
|
508
748
|
// env_blob NEVER lives in this table (F1 mint-stream-evict — secret
|
|
@@ -519,7 +759,7 @@ db.exec(`
|
|
|
519
759
|
child_name TEXT NOT NULL,
|
|
520
760
|
network_id TEXT NOT NULL,
|
|
521
761
|
runtime TEXT NOT NULL,
|
|
522
|
-
model TEXT
|
|
762
|
+
model TEXT,
|
|
523
763
|
flags_json TEXT NOT NULL,
|
|
524
764
|
env_keys TEXT NOT NULL,
|
|
525
765
|
status TEXT NOT NULL,
|
|
@@ -536,6 +776,168 @@ db.exec(`
|
|
|
536
776
|
CREATE INDEX IF NOT EXISTS idx_ncr_network ON node_create_requests(network_id);
|
|
537
777
|
CREATE INDEX IF NOT EXISTS idx_ncr_child_name ON node_create_requests(child_name);
|
|
538
778
|
`);
|
|
779
|
+
function migrateNodeCreateRequestsModelNullable() {
|
|
780
|
+
if (db.dialect === "postgres") {
|
|
781
|
+
try { db.exec("ALTER TABLE node_create_requests ALTER COLUMN model DROP NOT NULL"); } catch {}
|
|
782
|
+
return;
|
|
783
|
+
}
|
|
784
|
+
|
|
785
|
+
let needsRebuild = false;
|
|
786
|
+
try {
|
|
787
|
+
const createSql = db.get<{ sql: string }>("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'node_create_requests'");
|
|
788
|
+
needsRebuild = !!createSql?.sql && /\bmodel\s+TEXT\s+NOT\s+NULL\b/i.test(createSql.sql);
|
|
789
|
+
} catch {}
|
|
790
|
+
if (!needsRebuild) return;
|
|
791
|
+
|
|
792
|
+
db.transaction(() => {
|
|
793
|
+
db.exec("DROP TABLE IF EXISTS node_create_requests_migrated");
|
|
794
|
+
db.exec(`
|
|
795
|
+
CREATE TABLE node_create_requests_migrated (
|
|
796
|
+
request_id TEXT PRIMARY KEY,
|
|
797
|
+
daemon_node_id TEXT NOT NULL,
|
|
798
|
+
child_name TEXT NOT NULL,
|
|
799
|
+
network_id TEXT NOT NULL,
|
|
800
|
+
runtime TEXT NOT NULL,
|
|
801
|
+
model TEXT,
|
|
802
|
+
flags_json TEXT NOT NULL,
|
|
803
|
+
env_keys TEXT NOT NULL,
|
|
804
|
+
status TEXT NOT NULL,
|
|
805
|
+
error TEXT,
|
|
806
|
+
child_token_id TEXT,
|
|
807
|
+
created_at INTEGER NOT NULL,
|
|
808
|
+
created_by_token TEXT NOT NULL,
|
|
809
|
+
delivered_at INTEGER,
|
|
810
|
+
acked_at INTEGER,
|
|
811
|
+
child_node_id TEXT
|
|
812
|
+
)
|
|
813
|
+
`);
|
|
814
|
+
db.exec(`
|
|
815
|
+
INSERT INTO node_create_requests_migrated (
|
|
816
|
+
request_id, daemon_node_id, child_name, network_id, runtime, model,
|
|
817
|
+
flags_json, env_keys, status, error, child_token_id, created_at,
|
|
818
|
+
created_by_token, delivered_at, acked_at, child_node_id
|
|
819
|
+
)
|
|
820
|
+
SELECT
|
|
821
|
+
request_id, daemon_node_id, child_name, network_id, runtime, model,
|
|
822
|
+
flags_json, env_keys, status, error, child_token_id, created_at,
|
|
823
|
+
created_by_token, delivered_at, acked_at, child_node_id
|
|
824
|
+
FROM node_create_requests
|
|
825
|
+
`);
|
|
826
|
+
db.exec("DROP TABLE node_create_requests");
|
|
827
|
+
db.exec("ALTER TABLE node_create_requests_migrated RENAME TO node_create_requests");
|
|
828
|
+
});
|
|
829
|
+
}
|
|
830
|
+
migrateNodeCreateRequestsModelNullable();
|
|
831
|
+
|
|
832
|
+
// app「新建节点」工作目录 —— 请求带的 node_spec.workdir(可空;空 = 落 daemon cwd 的老行为)。
|
|
833
|
+
// 🔴 必须排在上面那个重建表迁移**之后**:它按显式列清单拷贝,排在前面的话,老库(model NOT NULL)
|
|
834
|
+
// 第一次启动时这一列会被重建吞掉。
|
|
835
|
+
try {
|
|
836
|
+
db.exec(`ALTER TABLE node_create_requests ADD COLUMN workdir TEXT`);
|
|
837
|
+
} catch (e: any) {
|
|
838
|
+
if (!/duplicate column|already exists/i.test(e?.message || "")) throw e;
|
|
839
|
+
}
|
|
840
|
+
|
|
841
|
+
// Registration also stamps acked_at, so it cannot prove daemon launch checks.
|
|
842
|
+
// Keep old rows NULL; run after the legacy model-nullability table rebuild.
|
|
843
|
+
try {
|
|
844
|
+
db.exec(`ALTER TABLE node_create_requests ADD COLUMN launch_verified_at BIGINT`);
|
|
845
|
+
} catch (e: any) {
|
|
846
|
+
if (!/duplicate column|already exists/i.test(e?.message || "")) throw e;
|
|
847
|
+
}
|
|
848
|
+
|
|
849
|
+
// Hub #938 — clone_node reuses this table (same token mint, sweeper, and
|
|
850
|
+
// register finalize) but must not be replayed as a blank create_node.
|
|
851
|
+
// NULL/empty = ordinary create. Non-empty JSON = clone directives.
|
|
852
|
+
try {
|
|
853
|
+
db.exec(`ALTER TABLE node_create_requests ADD COLUMN clone_json TEXT`);
|
|
854
|
+
} catch (e: any) {
|
|
855
|
+
if (!/duplicate column|already exists/i.test(e?.message || "")) throw e;
|
|
856
|
+
}
|
|
857
|
+
|
|
858
|
+
// #1493 — 把 user_inbox.network_id 升到 **schema 级 NOT NULL**(belt-and-suspenders,
|
|
859
|
+
// 叠在 send_desktop_message 的代码级三闸之上:canWrite / `!effectiveNetId` return /
|
|
860
|
+
// getUserNetworkRole,tools.ts)。「不产生 network_id=NULL 孤儿」现是代码级保证 + #1492
|
|
861
|
+
// 三道测试;schema 级约束让**任何**未来绕过那三闸写 NULL 的回归在 INSERT 处直接被
|
|
862
|
+
// 数据库拒(而非产出 scoped-unreadable 的静默孤儿)。
|
|
863
|
+
//
|
|
864
|
+
// SQLite 不能 `ALTER COLUMN ADD NOT NULL` → 建新表→copy→drop→rename(与本文件既有
|
|
865
|
+
// recreate-table 迁移同范式);新库的 CREATE 已直接 NOT NULL,迁移检测到就跳过(幂等)。
|
|
866
|
+
function migrateUserInboxNetworkIdNotNull() {
|
|
867
|
+
if (db.dialect === "postgres") {
|
|
868
|
+
try { db.exec("ALTER TABLE user_inbox ALTER COLUMN network_id SET NOT NULL"); } catch {}
|
|
869
|
+
return;
|
|
870
|
+
}
|
|
871
|
+
let createSql: string | undefined;
|
|
872
|
+
try {
|
|
873
|
+
createSql = db.get<{ sql: string }>("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'user_inbox'")?.sql;
|
|
874
|
+
} catch { return; }
|
|
875
|
+
if (!createSql) return; // 表不存在:上面的 CREATE 已建成 NOT NULL 新表
|
|
876
|
+
if (/network_id\s+TEXT\s+NOT\s+NULL/i.test(createSql)) return; // 已是 NOT NULL → 幂等跳过
|
|
877
|
+
|
|
878
|
+
// 🔴 迁移前守卫:存量若有 network_id IS NULL 行(按代码级三闸理应 0)→ **大声 warn +
|
|
879
|
+
// 跳过迁移**(列暂保持可空),hub 照常启动。fail-safe,不 throw(SDK马 review #1516):
|
|
880
|
+
// · 这条 NOT NULL 是 belt-and-suspenders,代码级三闸(#1492 三测钉着)已挡新 NULL;
|
|
881
|
+
// 为一条冗余保险带让**整个舰队的 hub** boot 期停摆,代价与收益不成比例;
|
|
882
|
+
// · 生产这个 COUNT 没人量过,而 #1493 第一条原则就是"没量过的数不要动手"——只要生产
|
|
883
|
+
// 有一行历史 NULL,throw 就把升级变成停机;
|
|
884
|
+
// · fail-closed 的真正目的(不盲目清空、不 COALESCE 猜网络)用 warn+skip 一样达到。
|
|
885
|
+
// ⚠ 校正:本文件既有迁移(migrateNodeCreateRequestsModelNullable 内部 catch{}+return;
|
|
886
|
+
// migrateSessionsNetworkAliasUnique 全函数 throw 0 次)都**不**在 boot 期打死 hub——
|
|
887
|
+
// "顶层无 try/catch"是真前提,但"所以 throw 符合惯例"是没验的推论(SDK马 量出),撤回。
|
|
888
|
+
// 孤儿行仍有明确运维信号,三闸仍生效;等人工量过、清干净,下次启动幂等判据自动完成迁移。
|
|
889
|
+
const nullCount = db.get<{ n: number }>("SELECT COUNT(*) AS n FROM user_inbox WHERE network_id IS NULL")?.n ?? 0;
|
|
890
|
+
if (nullCount > 0) {
|
|
891
|
+
console.error(
|
|
892
|
+
`[migrate #1493] user_inbox 有 ${nullCount} 行 network_id IS NULL —— 与 send_desktop_message ` +
|
|
893
|
+
`的代码级三闸矛盾,可能存在更早的写路径漏洞;已**跳过** NOT NULL 迁移(列暂保持可空),` +
|
|
894
|
+
`hub 正常启动。请人工排查这些孤儿行来源、清理后下次启动会自动完成迁移(不要盲目清空)。`,
|
|
895
|
+
);
|
|
896
|
+
return;
|
|
897
|
+
}
|
|
898
|
+
|
|
899
|
+
db.transaction(() => {
|
|
900
|
+
db.exec("DROP TABLE IF EXISTS user_inbox_migrated");
|
|
901
|
+
db.exec(`
|
|
902
|
+
CREATE TABLE user_inbox_migrated (
|
|
903
|
+
message_id TEXT PRIMARY KEY,
|
|
904
|
+
network_id TEXT NOT NULL,
|
|
905
|
+
user_id TEXT NOT NULL,
|
|
906
|
+
from_session TEXT,
|
|
907
|
+
kind TEXT NOT NULL DEFAULT 'info',
|
|
908
|
+
title TEXT,
|
|
909
|
+
content TEXT NOT NULL,
|
|
910
|
+
severity TEXT NOT NULL DEFAULT 'info',
|
|
911
|
+
meta_json TEXT,
|
|
912
|
+
acked INTEGER NOT NULL DEFAULT 0,
|
|
913
|
+
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
914
|
+
acked_at TEXT
|
|
915
|
+
)
|
|
916
|
+
`);
|
|
917
|
+
db.exec(`
|
|
918
|
+
INSERT INTO user_inbox_migrated
|
|
919
|
+
(message_id, network_id, user_id, from_session, kind, title, content, severity, meta_json, acked, created_at, acked_at)
|
|
920
|
+
SELECT
|
|
921
|
+
message_id, network_id, user_id, from_session, kind, title, content, severity, meta_json, acked, created_at, acked_at
|
|
922
|
+
FROM user_inbox
|
|
923
|
+
`);
|
|
924
|
+
db.exec("DROP TABLE user_inbox");
|
|
925
|
+
db.exec("ALTER TABLE user_inbox_migrated RENAME TO user_inbox");
|
|
926
|
+
});
|
|
927
|
+
}
|
|
928
|
+
migrateUserInboxNetworkIdNotNull();
|
|
929
|
+
// 迁移会 drop 掉旧表上的 idx_user_inbox_user_acked → 重建(IF NOT EXISTS;未迁移时 no-op)。
|
|
930
|
+
db.exec(`CREATE INDEX IF NOT EXISTS idx_user_inbox_user_acked ON user_inbox(user_id, acked, created_at);`);
|
|
931
|
+
// 多用户:人与人私信。sender_user_id 由 Hub 按发信人的**用户令牌**写入(不是客户端填的 from_session),
|
|
932
|
+
// 会话记录按它双向取;Agent / 节点令牌发来的桌面消息这一列为 NULL。
|
|
933
|
+
try { db.exec("ALTER TABLE user_inbox ADD COLUMN sender_user_id TEXT"); } catch {}
|
|
934
|
+
db.exec(`CREATE INDEX IF NOT EXISTS idx_user_inbox_dm ON user_inbox(network_id, user_id, sender_user_id, created_at);`);
|
|
935
|
+
|
|
936
|
+
db.exec(`
|
|
937
|
+
CREATE INDEX IF NOT EXISTS idx_ncr_daemon_status ON node_create_requests(daemon_node_id, status);
|
|
938
|
+
CREATE INDEX IF NOT EXISTS idx_ncr_network ON node_create_requests(network_id);
|
|
939
|
+
CREATE INDEX IF NOT EXISTS idx_ncr_child_name ON node_create_requests(child_name);
|
|
940
|
+
`);
|
|
539
941
|
try {
|
|
540
942
|
// Single-flight per (daemon, child_name) — prevents racing dashboard
|
|
541
943
|
// create on same name. Mirrors RFC-024 uniq_ncu_node_inflight.
|
|
@@ -565,6 +967,19 @@ db.exec(`
|
|
|
565
967
|
);
|
|
566
968
|
CREATE INDEX IF NOT EXISTS idx_providers_network ON providers(network_id);
|
|
567
969
|
`);
|
|
970
|
+
// #907 network-owned Provider configuration. Keys remain in network_secrets.
|
|
971
|
+
db.exec(`
|
|
972
|
+
CREATE TABLE IF NOT EXISTS hub_provider_configs (
|
|
973
|
+
network_id TEXT NOT NULL, provider_id TEXT NOT NULL, revision INTEGER NOT NULL,
|
|
974
|
+
config_json TEXT NOT NULL, secret_key_ref TEXT NOT NULL, updated_at INTEGER NOT NULL,
|
|
975
|
+
PRIMARY KEY(network_id, provider_id)
|
|
976
|
+
);
|
|
977
|
+
CREATE TABLE IF NOT EXISTS hub_provider_bindings (
|
|
978
|
+
request_id TEXT PRIMARY KEY, network_id TEXT NOT NULL, provider_id TEXT NOT NULL,
|
|
979
|
+
provider_revision INTEGER NOT NULL, daemon_node_id TEXT NOT NULL,
|
|
980
|
+
daemon_provider_id TEXT NOT NULL, created_at INTEGER NOT NULL
|
|
981
|
+
);
|
|
982
|
+
`);
|
|
568
983
|
db.exec(`
|
|
569
984
|
CREATE TABLE IF NOT EXISTS provider_models (
|
|
570
985
|
model_id TEXT PRIMARY KEY,
|
|
@@ -634,6 +1049,64 @@ db.exec(`
|
|
|
634
1049
|
CREATE INDEX IF NOT EXISTS idx_audit_network ON audit_log(network_id);
|
|
635
1050
|
`);
|
|
636
1051
|
|
|
1052
|
+
// SkillHub — immutable, network-scoped skill submissions. A (network, slug,
|
|
1053
|
+
// version) tuple is write-once: retries with the same content are idempotent,
|
|
1054
|
+
// while different content must use a new version. Node submissions remain
|
|
1055
|
+
// pending until an owner/admin explicitly publishes them.
|
|
1056
|
+
db.exec(`
|
|
1057
|
+
CREATE TABLE IF NOT EXISTS skillhub_skills (
|
|
1058
|
+
skill_id TEXT PRIMARY KEY,
|
|
1059
|
+
network_id TEXT NOT NULL,
|
|
1060
|
+
slug TEXT NOT NULL,
|
|
1061
|
+
name TEXT NOT NULL,
|
|
1062
|
+
description TEXT NOT NULL DEFAULT '',
|
|
1063
|
+
version TEXT NOT NULL,
|
|
1064
|
+
content TEXT NOT NULL,
|
|
1065
|
+
content_hash TEXT NOT NULL,
|
|
1066
|
+
status TEXT NOT NULL DEFAULT 'pending' CHECK(status IN ('pending', 'published', 'rejected', 'archived')),
|
|
1067
|
+
source_type TEXT NOT NULL CHECK(source_type IN ('node', 'user')),
|
|
1068
|
+
source_alias TEXT,
|
|
1069
|
+
created_by_user TEXT,
|
|
1070
|
+
reviewed_by_user TEXT,
|
|
1071
|
+
review_note TEXT,
|
|
1072
|
+
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
1073
|
+
updated_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
1074
|
+
reviewed_at TEXT,
|
|
1075
|
+
UNIQUE(network_id, slug, version)
|
|
1076
|
+
);
|
|
1077
|
+
CREATE INDEX IF NOT EXISTS idx_skillhub_network_status
|
|
1078
|
+
ON skillhub_skills(network_id, status, updated_at DESC);
|
|
1079
|
+
CREATE INDEX IF NOT EXISTS idx_skillhub_network_slug
|
|
1080
|
+
ON skillhub_skills(network_id, slug, version);
|
|
1081
|
+
`);
|
|
1082
|
+
|
|
1083
|
+
// 需求池。长期卡片,按 network 隔离。不是 tasks。
|
|
1084
|
+
db.exec(`
|
|
1085
|
+
CREATE TABLE IF NOT EXISTS requirements (
|
|
1086
|
+
requirement_id TEXT PRIMARY KEY,
|
|
1087
|
+
network_id TEXT NOT NULL,
|
|
1088
|
+
title TEXT NOT NULL,
|
|
1089
|
+
column_name TEXT NOT NULL DEFAULT 'pool' CHECK(column_name IN ('pool', 'doing', 'done', 'abandoned')),
|
|
1090
|
+
priority TEXT NOT NULL DEFAULT 'normal' CHECK(priority IN ('high', 'normal', 'low', 'lowest')),
|
|
1091
|
+
due_on TEXT,
|
|
1092
|
+
assignee TEXT,
|
|
1093
|
+
client_id TEXT,
|
|
1094
|
+
issues_json TEXT,
|
|
1095
|
+
created_by TEXT,
|
|
1096
|
+
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
1097
|
+
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
|
|
1098
|
+
);
|
|
1099
|
+
CREATE INDEX IF NOT EXISTS idx_requirements_network
|
|
1100
|
+
ON requirements(network_id, created_at DESC);
|
|
1101
|
+
`);
|
|
1102
|
+
try { db.exec("ALTER TABLE requirements ADD COLUMN client_id TEXT"); } catch {}
|
|
1103
|
+
try { db.exec("ALTER TABLE requirements ADD COLUMN issues_json TEXT"); } catch {}
|
|
1104
|
+
try { db.exec("ALTER TABLE requirements ADD COLUMN tags_json TEXT NOT NULL DEFAULT '[]'"); } catch (e: any) { if (!/duplicate column|already exists/i.test(e?.message || "")) throw e; }
|
|
1105
|
+
db.exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_requirements_client ON requirements(network_id, client_id) WHERE client_id IS NOT NULL AND client_id != ''");
|
|
1106
|
+
for (const column of ["owner_json TEXT", "participants_json TEXT NOT NULL DEFAULT '[]'", "agent_owner_json TEXT", "description TEXT", "checklist_json TEXT", "project_id TEXT", "external_ref TEXT", "external_url TEXT", "archived INTEGER NOT NULL DEFAULT 0", "created_by_json TEXT", "updated_by_json TEXT", "parent_id TEXT", "start_on TEXT"]) {
|
|
1107
|
+
try { db.exec(`ALTER TABLE requirements ADD COLUMN ${column}`); } catch (e: any) { if (!/duplicate column|already exists/i.test(e?.message || "")) throw e; }
|
|
1108
|
+
}
|
|
1109
|
+
|
|
637
1110
|
// ── V3: licenses table ──
|
|
638
1111
|
db.exec(`
|
|
639
1112
|
CREATE TABLE IF NOT EXISTS licenses (
|
|
@@ -650,16 +1123,11 @@ db.exec(`
|
|
|
650
1123
|
);
|
|
651
1124
|
`);
|
|
652
1125
|
|
|
653
|
-
//
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
"INSERT INTO licenses (id, license_key, type, expires_at) VALUES (?1, ?2, 'trial', datetime('now', '+14 days'))",
|
|
659
|
-
[`lic_${trialId}`, `trial-${trialId}`]
|
|
660
|
-
);
|
|
661
|
-
console.log("[commhub] 🎉 14-day free trial started!");
|
|
662
|
-
}
|
|
1126
|
+
// license 功能已移除(2026-10-29 admin 决定)。
|
|
1127
|
+
// 这里原来会在首次启动时插一条 14 天 trial —— 现在没有任何代码读它,
|
|
1128
|
+
// 继续插只会让每个新库凭空多一行死数据。
|
|
1129
|
+
// `licenses` 表本身保留(CREATE TABLE 不动):已有实例里可能还有历史行,
|
|
1130
|
+
// 删表的迁移代价大于留着;表从此不再被读写。
|
|
663
1131
|
|
|
664
1132
|
// ── V3.13: network_members table (user ↔ network many-to-many) ──
|
|
665
1133
|
db.exec(`
|
|
@@ -690,6 +1158,68 @@ db.exec(`
|
|
|
690
1158
|
);
|
|
691
1159
|
`);
|
|
692
1160
|
|
|
1161
|
+
// ── 多用户账号与 Agent 权限:成员可见哪些 Agent ──
|
|
1162
|
+
// network_members.agent_access:
|
|
1163
|
+
// 'all' —— 旧语义:能看到并联系网络里所有 Agent。ALTER 的 DEFAULT 让**升级前已有的**成员行
|
|
1164
|
+
// 全部落在这里,生产上已有成员的可见范围不因升级而变。
|
|
1165
|
+
// 'granted' —— 只看到 network_member_agent_grants 里给了的 Agent。此后**新加入**的
|
|
1166
|
+
// member/viewer(管理员建号、POST members、邀请码)都以它入库,即默认零权限。
|
|
1167
|
+
// owner/admin 角色与 Hub 管理员不看这一列(永远全部可见),判定集中在 agent-access.ts。
|
|
1168
|
+
try { db.exec("ALTER TABLE network_members ADD COLUMN agent_access TEXT NOT NULL DEFAULT 'all'"); } catch {}
|
|
1169
|
+
// node_id 优先(稳定);alias 只给没有 node_id 的旧会话用。两者恰有其一。
|
|
1170
|
+
db.exec(`
|
|
1171
|
+
CREATE TABLE IF NOT EXISTS network_member_agent_grants (
|
|
1172
|
+
network_id TEXT NOT NULL,
|
|
1173
|
+
user_id TEXT NOT NULL,
|
|
1174
|
+
node_id TEXT,
|
|
1175
|
+
alias TEXT,
|
|
1176
|
+
can_message INTEGER NOT NULL DEFAULT 1,
|
|
1177
|
+
created_by TEXT,
|
|
1178
|
+
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
1179
|
+
CHECK ((node_id IS NULL) <> (alias IS NULL))
|
|
1180
|
+
);
|
|
1181
|
+
|
|
1182
|
+
CREATE UNIQUE INDEX IF NOT EXISTS idx_agent_grants_node ON network_member_agent_grants(network_id, user_id, node_id) WHERE node_id IS NOT NULL;
|
|
1183
|
+
CREATE UNIQUE INDEX IF NOT EXISTS idx_agent_grants_alias ON network_member_agent_grants(network_id, user_id, alias) WHERE alias IS NOT NULL;
|
|
1184
|
+
`);
|
|
1185
|
+
|
|
1186
|
+
// ── Agent 分组(RFC-038 §8):管理员自由定义的组,授权可以给到组,组成员动态生效 ──
|
|
1187
|
+
// 组授权单独一张表(不给 network_member_agent_grants 加列):那张表的 CHECK 改不了,
|
|
1188
|
+
// 而且旧 app 的 PUT 是整体替换 —— 同表的话,旧 app 一保存就把组授权清掉。
|
|
1189
|
+
db.exec(`
|
|
1190
|
+
CREATE TABLE IF NOT EXISTS agent_groups (
|
|
1191
|
+
group_id TEXT PRIMARY KEY,
|
|
1192
|
+
network_id TEXT NOT NULL,
|
|
1193
|
+
name TEXT NOT NULL,
|
|
1194
|
+
description TEXT,
|
|
1195
|
+
created_by TEXT,
|
|
1196
|
+
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
1197
|
+
updated_at TEXT
|
|
1198
|
+
);
|
|
1199
|
+
CREATE UNIQUE INDEX IF NOT EXISTS idx_agent_groups_name ON agent_groups(network_id, name);
|
|
1200
|
+
|
|
1201
|
+
CREATE TABLE IF NOT EXISTS agent_group_members (
|
|
1202
|
+
group_id TEXT NOT NULL,
|
|
1203
|
+
node_id TEXT NOT NULL,
|
|
1204
|
+
added_by TEXT,
|
|
1205
|
+
added_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
1206
|
+
PRIMARY KEY (group_id, node_id)
|
|
1207
|
+
);
|
|
1208
|
+
|
|
1209
|
+
CREATE TABLE IF NOT EXISTS network_member_group_grants (
|
|
1210
|
+
network_id TEXT NOT NULL,
|
|
1211
|
+
user_id TEXT NOT NULL,
|
|
1212
|
+
group_id TEXT NOT NULL,
|
|
1213
|
+
can_message INTEGER NOT NULL DEFAULT 1,
|
|
1214
|
+
created_by TEXT,
|
|
1215
|
+
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
1216
|
+
PRIMARY KEY (network_id, user_id, group_id)
|
|
1217
|
+
);
|
|
1218
|
+
-- 改组成员 / 删组时按组找被授权成员(usersGrantedGroup、granted_user_count):主键以 network_id 开头用不上。
|
|
1219
|
+
-- 展开查询本身走各表主键,见 agent-groups-perf.test.ts 的 EXPLAIN QUERY PLAN。
|
|
1220
|
+
CREATE INDEX IF NOT EXISTS idx_group_grants_group ON network_member_group_grants(group_id);
|
|
1221
|
+
`);
|
|
1222
|
+
|
|
693
1223
|
// ── #84: node rename — rename_txn table (RFC-010 §4) ──
|
|
694
1224
|
// Single isolated table holding the rename 2PC transaction state. It doubles
|
|
695
1225
|
// as the alias_rename_log (RFC §4 risk #5): the audit log of completed renames
|
|
@@ -744,6 +1274,14 @@ for (const table of ["sessions", "nodes", "tasks", "inbox", "task_events", "comp
|
|
|
744
1274
|
try { db.exec(`ALTER TABLE ${table} ADD COLUMN network_id TEXT`); } catch {}
|
|
745
1275
|
}
|
|
746
1276
|
|
|
1277
|
+
// #167 — stable lifecycle event names plus an internal idempotency key.
|
|
1278
|
+
// Ordinary status transitions keep event_key NULL, so retries and repeated
|
|
1279
|
+
// transitions remain auditable. Watcher warnings set a stable key; the unique
|
|
1280
|
+
// index makes every (task, threshold) write-once across patrol rounds/workers.
|
|
1281
|
+
try { db.exec("ALTER TABLE task_events ADD COLUMN event_type TEXT"); } catch {}
|
|
1282
|
+
try { db.exec("ALTER TABLE task_events ADD COLUMN event_key TEXT"); } catch {}
|
|
1283
|
+
try { db.exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_task_events_task_key ON task_events(task_id, event_key)"); } catch {}
|
|
1284
|
+
|
|
747
1285
|
// PR-1 (#146): durable node identity on historical inbox/tasks rows. Some
|
|
748
1286
|
// existing databases created `tasks` before from_node_id/to_node_id were in the
|
|
749
1287
|
// CREATE TABLE statement, so keep these ALTERs explicit and idempotent.
|
|
@@ -759,7 +1297,19 @@ try { db.exec("CREATE INDEX IF NOT EXISTS idx_tasks_from_node ON tasks(from_node
|
|
|
759
1297
|
try { db.exec("CREATE INDEX IF NOT EXISTS idx_tasks_to_node ON tasks(to_node_id)"); } catch {}
|
|
760
1298
|
try { db.exec("CREATE INDEX IF NOT EXISTS idx_inbox_node ON inbox(node_id)"); } catch {}
|
|
761
1299
|
|
|
762
|
-
function backfillMessageNodeIds() {
|
|
1300
|
+
export function backfillMessageNodeIds() {
|
|
1301
|
+
// #2664 —— 旧写法是 6 条 `UPDATE … SET x = (SELECT … WHERE alias = t.name …)`:
|
|
1302
|
+
// 每条都对 **84k 行 tasks.from_node_id IS NULL / 36k 行 inbox.node_id IS NULL** 逐行
|
|
1303
|
+
// 跑一次相关子查询,而子查询里的 `COALESCE(network_id,'default')` 让
|
|
1304
|
+
// idx_sessions_network_alias_unique 用不上 ⇒ 每行扫一遍 369 行 sessions。
|
|
1305
|
+
// 生产实测(`.162` 慢 SQL 日志,2026-10-27 00:21 重启):5398ms / 2451ms / 1270ms,
|
|
1306
|
+
// 而且当次命中 0 行 —— **结果是 0,代价不是 0**。
|
|
1307
|
+
//
|
|
1308
|
+
// 改成 `UPDATE … FROM (物化后的别名→node_id 表)`:sessions/rename_txn 只扫一遍,
|
|
1309
|
+
// 每行只做一次自动索引探测。同一份生产库副本上 6.56s → 0.29s。
|
|
1310
|
+
// 语义不变:同一 (alias, network) 取 `updated_at` / `committed_at` 最新的那一行;
|
|
1311
|
+
// 仍然是「先按 session 别名直连,再补 rename_txn 的旧别名」;对 tasks 仍排除人是发送方的情况。
|
|
1312
|
+
const t0 = performance.now();
|
|
763
1313
|
let inboxDirect = 0;
|
|
764
1314
|
let inboxRenamed = 0;
|
|
765
1315
|
let tasksToDirect = 0;
|
|
@@ -770,158 +1320,197 @@ function backfillMessageNodeIds() {
|
|
|
770
1320
|
try {
|
|
771
1321
|
inboxDirect = db.run(`
|
|
772
1322
|
UPDATE inbox
|
|
773
|
-
SET node_id =
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
)
|
|
1323
|
+
SET node_id = pick.node_id
|
|
1324
|
+
FROM (
|
|
1325
|
+
SELECT alias, COALESCE(network_id, 'default') AS net, node_id,
|
|
1326
|
+
ROW_NUMBER() OVER (
|
|
1327
|
+
PARTITION BY alias, COALESCE(network_id, 'default')
|
|
1328
|
+
ORDER BY updated_at DESC
|
|
1329
|
+
) AS rn
|
|
1330
|
+
FROM sessions
|
|
1331
|
+
WHERE node_id IS NOT NULL
|
|
1332
|
+
) pick
|
|
1333
|
+
WHERE pick.rn = 1
|
|
1334
|
+
AND pick.alias = inbox.session_name
|
|
1335
|
+
AND pick.net = COALESCE(inbox.network_id, 'default')
|
|
1336
|
+
AND inbox.node_id IS NULL
|
|
788
1337
|
`).changes;
|
|
789
1338
|
} catch {}
|
|
790
1339
|
|
|
791
1340
|
try {
|
|
792
1341
|
inboxRenamed = db.run(`
|
|
793
1342
|
UPDATE inbox
|
|
794
|
-
SET node_id =
|
|
795
|
-
|
|
1343
|
+
SET node_id = pick.node_id
|
|
1344
|
+
FROM (
|
|
1345
|
+
SELECT r.old_alias AS old_alias,
|
|
1346
|
+
COALESCE(r.network_id, 'default') AS net,
|
|
1347
|
+
s.node_id AS node_id,
|
|
1348
|
+
ROW_NUMBER() OVER (
|
|
1349
|
+
PARTITION BY r.old_alias, COALESCE(r.network_id, 'default')
|
|
1350
|
+
ORDER BY r.committed_at DESC
|
|
1351
|
+
) AS rn
|
|
1352
|
+
FROM rename_txn r
|
|
796
1353
|
JOIN sessions s
|
|
797
1354
|
ON s.alias = r.new_alias
|
|
798
1355
|
AND COALESCE(s.network_id, 'default') = COALESCE(r.network_id, 'default')
|
|
799
1356
|
WHERE s.node_id IS NOT NULL
|
|
800
1357
|
AND r.status = 'committed'
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
WHERE node_id IS NULL
|
|
807
|
-
AND EXISTS (
|
|
808
|
-
SELECT 1 FROM rename_txn r
|
|
809
|
-
JOIN sessions s
|
|
810
|
-
ON s.alias = r.new_alias
|
|
811
|
-
AND COALESCE(s.network_id, 'default') = COALESCE(r.network_id, 'default')
|
|
812
|
-
WHERE s.node_id IS NOT NULL
|
|
813
|
-
AND r.status = 'committed'
|
|
814
|
-
AND r.old_alias = inbox.session_name
|
|
815
|
-
AND COALESCE(r.network_id, 'default') = COALESCE(inbox.network_id, 'default')
|
|
816
|
-
)
|
|
1358
|
+
) pick
|
|
1359
|
+
WHERE pick.rn = 1
|
|
1360
|
+
AND pick.old_alias = inbox.session_name
|
|
1361
|
+
AND pick.net = COALESCE(inbox.network_id, 'default')
|
|
1362
|
+
AND inbox.node_id IS NULL
|
|
817
1363
|
`).changes;
|
|
818
1364
|
} catch {}
|
|
819
1365
|
|
|
820
1366
|
try {
|
|
821
1367
|
tasksToDirect = db.run(`
|
|
822
1368
|
UPDATE tasks
|
|
823
|
-
SET to_node_id =
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
)
|
|
1369
|
+
SET to_node_id = pick.node_id
|
|
1370
|
+
FROM (
|
|
1371
|
+
SELECT alias, COALESCE(network_id, 'default') AS net, node_id,
|
|
1372
|
+
ROW_NUMBER() OVER (
|
|
1373
|
+
PARTITION BY alias, COALESCE(network_id, 'default')
|
|
1374
|
+
ORDER BY updated_at DESC
|
|
1375
|
+
) AS rn
|
|
1376
|
+
FROM sessions
|
|
1377
|
+
WHERE node_id IS NOT NULL
|
|
1378
|
+
) pick
|
|
1379
|
+
WHERE pick.rn = 1
|
|
1380
|
+
AND pick.alias = tasks.to_name
|
|
1381
|
+
AND pick.net = COALESCE(tasks.network_id, 'default')
|
|
1382
|
+
AND tasks.to_node_id IS NULL
|
|
838
1383
|
`).changes;
|
|
839
1384
|
} catch {}
|
|
840
1385
|
|
|
841
1386
|
try {
|
|
842
1387
|
tasksToRenamed = db.run(`
|
|
843
1388
|
UPDATE tasks
|
|
844
|
-
SET to_node_id =
|
|
845
|
-
|
|
1389
|
+
SET to_node_id = pick.node_id
|
|
1390
|
+
FROM (
|
|
1391
|
+
SELECT r.old_alias AS old_alias,
|
|
1392
|
+
COALESCE(r.network_id, 'default') AS net,
|
|
1393
|
+
s.node_id AS node_id,
|
|
1394
|
+
ROW_NUMBER() OVER (
|
|
1395
|
+
PARTITION BY r.old_alias, COALESCE(r.network_id, 'default')
|
|
1396
|
+
ORDER BY r.committed_at DESC
|
|
1397
|
+
) AS rn
|
|
1398
|
+
FROM rename_txn r
|
|
846
1399
|
JOIN sessions s
|
|
847
1400
|
ON s.alias = r.new_alias
|
|
848
1401
|
AND COALESCE(s.network_id, 'default') = COALESCE(r.network_id, 'default')
|
|
849
1402
|
WHERE s.node_id IS NOT NULL
|
|
850
1403
|
AND r.status = 'committed'
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
WHERE to_node_id IS NULL
|
|
857
|
-
AND EXISTS (
|
|
858
|
-
SELECT 1 FROM rename_txn r
|
|
859
|
-
JOIN sessions s
|
|
860
|
-
ON s.alias = r.new_alias
|
|
861
|
-
AND COALESCE(s.network_id, 'default') = COALESCE(r.network_id, 'default')
|
|
862
|
-
WHERE s.node_id IS NOT NULL
|
|
863
|
-
AND r.status = 'committed'
|
|
864
|
-
AND r.old_alias = tasks.to_name
|
|
865
|
-
AND COALESCE(r.network_id, 'default') = COALESCE(tasks.network_id, 'default')
|
|
866
|
-
)
|
|
1404
|
+
) pick
|
|
1405
|
+
WHERE pick.rn = 1
|
|
1406
|
+
AND pick.old_alias = tasks.to_name
|
|
1407
|
+
AND pick.net = COALESCE(tasks.network_id, 'default')
|
|
1408
|
+
AND tasks.to_node_id IS NULL
|
|
867
1409
|
`).changes;
|
|
868
1410
|
} catch {}
|
|
869
1411
|
|
|
870
1412
|
try {
|
|
871
1413
|
tasksFromDirect = db.run(`
|
|
872
1414
|
UPDATE tasks
|
|
873
|
-
SET from_node_id =
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
)
|
|
1415
|
+
SET from_node_id = pick.node_id
|
|
1416
|
+
FROM (
|
|
1417
|
+
SELECT alias, COALESCE(network_id, 'default') AS net, node_id,
|
|
1418
|
+
ROW_NUMBER() OVER (
|
|
1419
|
+
PARTITION BY alias, COALESCE(network_id, 'default')
|
|
1420
|
+
ORDER BY updated_at DESC
|
|
1421
|
+
) AS rn
|
|
1422
|
+
FROM sessions
|
|
1423
|
+
WHERE node_id IS NOT NULL
|
|
1424
|
+
) pick
|
|
1425
|
+
WHERE pick.rn = 1
|
|
1426
|
+
AND pick.alias = tasks.from_name
|
|
1427
|
+
AND pick.net = COALESCE(tasks.network_id, 'default')
|
|
1428
|
+
AND tasks.from_node_id IS NULL
|
|
1429
|
+
AND NOT EXISTS (SELECT 1 FROM users u WHERE u.username = tasks.from_name)
|
|
888
1430
|
`).changes;
|
|
889
1431
|
} catch {}
|
|
890
1432
|
|
|
891
1433
|
try {
|
|
892
1434
|
tasksFromRenamed = db.run(`
|
|
893
1435
|
UPDATE tasks
|
|
894
|
-
SET from_node_id =
|
|
895
|
-
|
|
1436
|
+
SET from_node_id = pick.node_id
|
|
1437
|
+
FROM (
|
|
1438
|
+
SELECT r.old_alias AS old_alias,
|
|
1439
|
+
COALESCE(r.network_id, 'default') AS net,
|
|
1440
|
+
s.node_id AS node_id,
|
|
1441
|
+
ROW_NUMBER() OVER (
|
|
1442
|
+
PARTITION BY r.old_alias, COALESCE(r.network_id, 'default')
|
|
1443
|
+
ORDER BY r.committed_at DESC
|
|
1444
|
+
) AS rn
|
|
1445
|
+
FROM rename_txn r
|
|
896
1446
|
JOIN sessions s
|
|
897
1447
|
ON s.alias = r.new_alias
|
|
898
1448
|
AND COALESCE(s.network_id, 'default') = COALESCE(r.network_id, 'default')
|
|
899
1449
|
WHERE s.node_id IS NOT NULL
|
|
900
1450
|
AND r.status = 'committed'
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
AND EXISTS (
|
|
908
|
-
SELECT 1 FROM rename_txn r
|
|
909
|
-
JOIN sessions s
|
|
910
|
-
ON s.alias = r.new_alias
|
|
911
|
-
AND COALESCE(s.network_id, 'default') = COALESCE(r.network_id, 'default')
|
|
912
|
-
WHERE s.node_id IS NOT NULL
|
|
913
|
-
AND r.status = 'committed'
|
|
914
|
-
AND r.old_alias = tasks.from_name
|
|
915
|
-
AND COALESCE(r.network_id, 'default') = COALESCE(tasks.network_id, 'default')
|
|
916
|
-
)
|
|
1451
|
+
) pick
|
|
1452
|
+
WHERE pick.rn = 1
|
|
1453
|
+
AND pick.old_alias = tasks.from_name
|
|
1454
|
+
AND pick.net = COALESCE(tasks.network_id, 'default')
|
|
1455
|
+
AND tasks.from_node_id IS NULL
|
|
1456
|
+
AND NOT EXISTS (SELECT 1 FROM users u WHERE u.username = tasks.from_name)
|
|
917
1457
|
`).changes;
|
|
918
1458
|
} catch {}
|
|
919
1459
|
|
|
920
1460
|
const total = inboxDirect + inboxRenamed + tasksToDirect + tasksToRenamed + tasksFromDirect + tasksFromRenamed;
|
|
921
|
-
|
|
1461
|
+
// #2664 —— 旧日志只有条数,于是「total=0 却花了 10 秒」在生产里完全看不见。
|
|
1462
|
+
console.log(`[commhub] node_id backfill: inbox=${inboxDirect + inboxRenamed}, tasks.to=${tasksToDirect + tasksToRenamed}, tasks.from=${tasksFromDirect + tasksFromRenamed}, total=${total}, took=${Math.round(performance.now() - t0)}ms`);
|
|
922
1463
|
}
|
|
923
1464
|
|
|
924
|
-
|
|
1465
|
+
// #2664 —— 不在 import 时跑(见 runDeferredBootBackfills 的说明)。这里留一行**准确**的日志:
|
|
1466
|
+
// · 有测试/运维会 grep `node_id backfill` 来确认迁移路径被走到过;
|
|
1467
|
+
// · 真正的汇总行(带 took=)在 runDeferredBootBackfills() 里,启动后 15 秒出现。
|
|
1468
|
+
console.log("[commhub] node_id backfill: deferred until after start (#2664)");
|
|
1469
|
+
|
|
1470
|
+
/**
|
|
1471
|
+
* #2664 —— 两个 boot 期的历史回填,挪到「服务已开始监听之后」再跑。
|
|
1472
|
+
*
|
|
1473
|
+
* 为什么:这两条语句在生产上合计约 3.5 秒(慢 SQL 日志实测:`UPDATE tasks … FROM` 1511ms +
|
|
1474
|
+
* `INSERT OR IGNORE INTO task_terminal_events` 2137ms),而它们只修**历史缺口**——
|
|
1475
|
+
* 新行由触发器实时写入。把 3.5 秒挡在启动路径上,等于让 369 个会话的重连风暴多等 3.5 秒,
|
|
1476
|
+
* 而这段时间里 Hub 本来就最脆弱。
|
|
1477
|
+
*
|
|
1478
|
+
* 调用点:startHub() 监听成功后延迟数秒执行(见 server.ts)。
|
|
1479
|
+
*/
|
|
1480
|
+
export async function runDeferredBootBackfills(): Promise<{ nodeIdsMs: number; terminalEventsMs: number; chunks: number }> {
|
|
1481
|
+
// #2664(第二批)—— 前一版把两条回填整体挪到启动后,但**每条仍是一次性长查询**:
|
|
1482
|
+
// 生产实测 `node_id=1194ms terminal_events=1593ms`,对应一次 2.7秒级的 stall
|
|
1483
|
+
// (`.165`/`.166` 启动窗口都观测到 3–3.7 秒)。这里把它们切成小块、块间让出事件循环,
|
|
1484
|
+
// 让「2.7 秒卡一下」变成「若干次 <300ms 的让出」。
|
|
1485
|
+
const t0 = performance.now();
|
|
1486
|
+
try { backfillMessageNodeIds(); } catch (e: any) {
|
|
1487
|
+
console.error(`[commhub] node_id backfill failed: ${e?.message || e}`);
|
|
1488
|
+
}
|
|
1489
|
+
await Bun.sleep(0); // 两条之间先让一次:即使前半段偏慢,也不会和后半段叠成一段长阻塞
|
|
1490
|
+
const t1 = performance.now();
|
|
1491
|
+
let chunks = 0;
|
|
1492
|
+
try {
|
|
1493
|
+
if (db.dialect === "sqlite") {
|
|
1494
|
+
const maxRow = db.get<{ m: number | null }>("SELECT MAX(rowid) AS m FROM tasks")?.m ?? 0;
|
|
1495
|
+
const CHUNK = 20000;
|
|
1496
|
+
for (let lo = 0; lo <= maxRow; lo += CHUNK) {
|
|
1497
|
+
db.run(`INSERT OR IGNORE INTO task_terminal_events (task_id, network_id, from_node_id, completed_at)
|
|
1498
|
+
SELECT task_id, network_id, from_node_id, COALESCE(completed_at, created_at)
|
|
1499
|
+
FROM tasks
|
|
1500
|
+
WHERE rowid BETWEEN ?1 AND ?2
|
|
1501
|
+
AND status IN ('replied', 'failed', 'cancelled', 'expired')
|
|
1502
|
+
ORDER BY COALESCE(completed_at, created_at), task_id`,
|
|
1503
|
+
[lo, lo + CHUNK - 1]);
|
|
1504
|
+
chunks++;
|
|
1505
|
+
await Bun.sleep(0); // 每 2 万行让出一次
|
|
1506
|
+
}
|
|
1507
|
+
}
|
|
1508
|
+
} catch (e: any) {
|
|
1509
|
+
console.error(`[commhub] task_terminal_events backfill failed: ${e?.message || e}`);
|
|
1510
|
+
}
|
|
1511
|
+
const t2 = performance.now();
|
|
1512
|
+
return { nodeIdsMs: Math.round(t1 - t0), terminalEventsMs: Math.round(t2 - t1), chunks };
|
|
1513
|
+
}
|
|
925
1514
|
|
|
926
1515
|
// ── P0: sessions alias uniqueness is network-scoped.
|
|
927
1516
|
// Older SQLite databases created `alias TEXT UNIQUE`, which prevents the same
|
|
@@ -1019,6 +1608,17 @@ migrateSessionsNetworkAliasUnique();
|
|
|
1019
1608
|
try { db.exec("CREATE INDEX IF NOT EXISTS idx_sessions_network ON sessions(network_id)"); } catch {}
|
|
1020
1609
|
try { db.exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_sessions_network_alias_unique ON sessions(network_id, alias)"); } catch {}
|
|
1021
1610
|
try { db.exec("CREATE INDEX IF NOT EXISTS idx_tasks_network ON tasks(network_id)"); } catch {}
|
|
1611
|
+
// #2722 —— 任务统计(`SELECT status, COUNT(*) FROM tasks WHERE network_id=? GROUP BY status`)是
|
|
1612
|
+
// Dashboard/状态接口最常走的聚合:只有上面的单列索引时,它要扫该网络**全部**行再建临时 B 树
|
|
1613
|
+
// (生产 116k 行实测 **5325ms**;同库副本 294ms)。加覆盖索引后副本 **24ms(12×)**。
|
|
1614
|
+
// 只加列、不改任何查询;老库首次启动多花约 0.4 秒建索引。
|
|
1615
|
+
try { db.exec("CREATE INDEX IF NOT EXISTS idx_tasks_network_status ON tasks(network_id, status)"); } catch {}
|
|
1616
|
+
// #500 — covering index for the full /api/status queue_depth GROUP BY (task-queue-ahead.ts queueDepthQuery): the 24 h
|
|
1617
|
+
// created_at range plus every column that query reads, so it never touches the (wide) task rows. Here, not in the
|
|
1618
|
+
// CREATE TABLE block: tasks.network_id only exists after the ALTER above. On a read-only copy of the production DB
|
|
1619
|
+
// (57k tasks, 1.9k in the last 24 h) the statement went from ~3 ms (idx_tasks_created + one row lookup per task) to
|
|
1620
|
+
// ~0.3 ms; building it there took ~170 ms once. Plain composite index: the same DDL runs on PostgreSQL.
|
|
1621
|
+
try { db.exec("CREATE INDEX IF NOT EXISTS idx_tasks_created_queue ON tasks(created_at, status, network_id, to_name)"); } catch {}
|
|
1022
1622
|
try { db.exec("CREATE INDEX IF NOT EXISTS idx_nodes_network ON nodes(network_id)"); } catch {}
|
|
1023
1623
|
try { db.exec("CREATE INDEX IF NOT EXISTS idx_inbox_network ON inbox(network_id)"); } catch {}
|
|
1024
1624
|
try { db.exec("CREATE INDEX IF NOT EXISTS idx_task_events_network ON task_events(network_id)"); } catch {}
|
|
@@ -1030,6 +1630,236 @@ try { db.exec("CREATE INDEX IF NOT EXISTS idx_completions_network ON completions
|
|
|
1030
1630
|
// the reply up the chain via parent_task_id.
|
|
1031
1631
|
try { db.exec("ALTER TABLE tasks ADD COLUMN parent_task_id TEXT"); } catch {}
|
|
1032
1632
|
try { db.exec("ALTER TABLE tasks ADD COLUMN meta_json TEXT"); } catch {}
|
|
1633
|
+
// #520 — two monotonic evidence levels for this exact task:
|
|
1634
|
+
// runtime_submitted_at means agent-node handed the body to the vendor runtime;
|
|
1635
|
+
// consumed_at requires an attributable turn-start/first-activity signal.
|
|
1636
|
+
// Both stay separate from delivered_at (enqueue), acked (process receipt), and
|
|
1637
|
+
// started_at (legacy report_status/content matching). Old binaries ignore them.
|
|
1638
|
+
try { db.exec("ALTER TABLE tasks ADD COLUMN runtime_submitted_at TEXT"); } catch {}
|
|
1639
|
+
try { db.exec("ALTER TABLE tasks ADD COLUMN consumed_at TEXT"); } catch {}
|
|
1640
|
+
// #1113: exact original-turn activity. NULL keeps the old execution-clock fallback.
|
|
1641
|
+
try { db.exec("ALTER TABLE tasks ADD COLUMN last_activity_at TEXT"); } catch {}
|
|
1642
|
+
// Exact vendor-runtime boundary for SideThread-capable clients. These values
|
|
1643
|
+
// are written only by the token-bound target node after attributable runtime
|
|
1644
|
+
// evidence; the Hub never derives them from task text or caller input.
|
|
1645
|
+
try { db.exec("ALTER TABLE tasks ADD COLUMN thread_id TEXT"); } catch {}
|
|
1646
|
+
try { db.exec("ALTER TABLE tasks ADD COLUMN turn_id TEXT"); } catch {}
|
|
1647
|
+
|
|
1648
|
+
// Board #710 — a result that arrives after the task is already terminal is
|
|
1649
|
+
// evidence about that exact runtime turn, not a second task transition. Keep
|
|
1650
|
+
// it in an additive table: old clients and old Hub code continue to read the
|
|
1651
|
+
// tasks row unchanged, while new detail readers can project `late_replies`.
|
|
1652
|
+
db.exec(`
|
|
1653
|
+
CREATE TABLE IF NOT EXISTS task_late_replies (
|
|
1654
|
+
late_reply_id TEXT PRIMARY KEY,
|
|
1655
|
+
inbox_id TEXT NOT NULL UNIQUE,
|
|
1656
|
+
task_id TEXT NOT NULL,
|
|
1657
|
+
network_id TEXT,
|
|
1658
|
+
from_node_id TEXT NOT NULL,
|
|
1659
|
+
thread_id TEXT NOT NULL,
|
|
1660
|
+
turn_id TEXT NOT NULL,
|
|
1661
|
+
status TEXT NOT NULL CHECK (status IN ('replied','failed','cancelled')),
|
|
1662
|
+
result TEXT NOT NULL,
|
|
1663
|
+
meta_json TEXT,
|
|
1664
|
+
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
1665
|
+
UNIQUE (task_id, thread_id, turn_id)
|
|
1666
|
+
);
|
|
1667
|
+
CREATE INDEX IF NOT EXISTS idx_task_late_replies_task_time
|
|
1668
|
+
ON task_late_replies(task_id, created_at);
|
|
1669
|
+
CREATE INDEX IF NOT EXISTS idx_task_late_replies_network
|
|
1670
|
+
ON task_late_replies(network_id, created_at);
|
|
1671
|
+
`);
|
|
1672
|
+
|
|
1673
|
+
// #1181 durable outbound terminal cursor. A task's created_at cannot be used
|
|
1674
|
+
// as a recovery watermark because an old task may become terminal after newer
|
|
1675
|
+
// tasks. Record terminal transitions in their own monotonically increasing
|
|
1676
|
+
// journal instead. The journal is append-only for a logical task; retry keeps
|
|
1677
|
+
// the existing task identity and therefore the same idempotency domain.
|
|
1678
|
+
db.exec(`
|
|
1679
|
+
CREATE TABLE IF NOT EXISTS task_terminal_events (
|
|
1680
|
+
terminal_seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
1681
|
+
task_id TEXT NOT NULL UNIQUE,
|
|
1682
|
+
network_id TEXT,
|
|
1683
|
+
from_node_id TEXT,
|
|
1684
|
+
completed_at TEXT NOT NULL DEFAULT (datetime('now'))
|
|
1685
|
+
);
|
|
1686
|
+
CREATE INDEX IF NOT EXISTS idx_task_terminal_events_sender_seq
|
|
1687
|
+
ON task_terminal_events(network_id, from_node_id, terminal_seq);
|
|
1688
|
+
`);
|
|
1689
|
+
if (db.dialect === "sqlite") {
|
|
1690
|
+
db.exec(`
|
|
1691
|
+
CREATE TRIGGER IF NOT EXISTS tasks_terminal_event_insert
|
|
1692
|
+
AFTER INSERT ON tasks
|
|
1693
|
+
WHEN NEW.status IN ('replied', 'failed', 'cancelled', 'expired')
|
|
1694
|
+
BEGIN
|
|
1695
|
+
INSERT OR IGNORE INTO task_terminal_events (task_id, network_id, from_node_id, completed_at)
|
|
1696
|
+
VALUES (NEW.task_id, NEW.network_id, NEW.from_node_id, COALESCE(NEW.completed_at, datetime('now')));
|
|
1697
|
+
END;
|
|
1698
|
+
CREATE TRIGGER IF NOT EXISTS tasks_terminal_event_update
|
|
1699
|
+
AFTER UPDATE OF status ON tasks
|
|
1700
|
+
WHEN NEW.status IN ('replied', 'failed', 'cancelled', 'expired')
|
|
1701
|
+
AND OLD.status NOT IN ('replied', 'failed', 'cancelled', 'expired')
|
|
1702
|
+
BEGIN
|
|
1703
|
+
INSERT OR IGNORE INTO task_terminal_events (task_id, network_id, from_node_id, completed_at)
|
|
1704
|
+
VALUES (NEW.task_id, NEW.network_id, NEW.from_node_id, COALESCE(NEW.completed_at, datetime('now')));
|
|
1705
|
+
END;
|
|
1706
|
+
`);
|
|
1707
|
+
// #2664 —— 回填本身挪到 runDeferredBootBackfills()(启动后再跑)。这里只留触发器定义:
|
|
1708
|
+
// 触发器负责**新**行的写入,回填只修历史缺口,不该占启动的关键路径。
|
|
1709
|
+
} else {
|
|
1710
|
+
db.exec(`
|
|
1711
|
+
CREATE OR REPLACE FUNCTION record_task_terminal_event() RETURNS trigger AS $$
|
|
1712
|
+
BEGIN
|
|
1713
|
+
IF NEW.status IN ('replied', 'failed', 'cancelled', 'expired')
|
|
1714
|
+
AND (TG_OP = 'INSERT' OR OLD.status NOT IN ('replied', 'failed', 'cancelled', 'expired')) THEN
|
|
1715
|
+
INSERT INTO task_terminal_events (task_id, network_id, from_node_id, completed_at)
|
|
1716
|
+
VALUES (NEW.task_id, NEW.network_id, NEW.from_node_id, COALESCE(NEW.completed_at, datetime('now')))
|
|
1717
|
+
ON CONFLICT (task_id) DO NOTHING;
|
|
1718
|
+
END IF;
|
|
1719
|
+
RETURN NEW;
|
|
1720
|
+
END;
|
|
1721
|
+
$$ LANGUAGE plpgsql;
|
|
1722
|
+
DROP TRIGGER IF EXISTS tasks_terminal_event_insert ON tasks;
|
|
1723
|
+
DROP TRIGGER IF EXISTS tasks_terminal_event_update ON tasks;
|
|
1724
|
+
CREATE TRIGGER tasks_terminal_event_insert AFTER INSERT ON tasks
|
|
1725
|
+
FOR EACH ROW EXECUTE FUNCTION record_task_terminal_event();
|
|
1726
|
+
CREATE TRIGGER tasks_terminal_event_update AFTER UPDATE OF status ON tasks
|
|
1727
|
+
FOR EACH ROW EXECUTE FUNCTION record_task_terminal_event();
|
|
1728
|
+
INSERT INTO task_terminal_events (task_id, network_id, from_node_id, completed_at)
|
|
1729
|
+
SELECT task_id, network_id, from_node_id, COALESCE(completed_at, created_at)
|
|
1730
|
+
FROM tasks WHERE status IN ('replied', 'failed', 'cancelled', 'expired')
|
|
1731
|
+
ON CONFLICT (task_id) DO NOTHING;
|
|
1732
|
+
`);
|
|
1733
|
+
}
|
|
1734
|
+
|
|
1735
|
+
// ── Hub scheduled tasks ──────────────────────────────────────────────
|
|
1736
|
+
// Scheduling is a Hub concern: clients manage these rows, while agents only
|
|
1737
|
+
// receive the ordinary inbox/tasks rows produced for each occurrence. Keep
|
|
1738
|
+
// the occurrence table separate so retries, skips and failures remain
|
|
1739
|
+
// auditable without overloading the task lifecycle.
|
|
1740
|
+
db.exec(`
|
|
1741
|
+
CREATE TABLE IF NOT EXISTS scheduled_tasks (
|
|
1742
|
+
schedule_id TEXT PRIMARY KEY,
|
|
1743
|
+
network_id TEXT NOT NULL,
|
|
1744
|
+
created_by TEXT,
|
|
1745
|
+
name TEXT NOT NULL,
|
|
1746
|
+
target_node_id TEXT NOT NULL,
|
|
1747
|
+
target_alias TEXT NOT NULL,
|
|
1748
|
+
task_content TEXT NOT NULL,
|
|
1749
|
+
priority TEXT NOT NULL DEFAULT 'normal',
|
|
1750
|
+
schedule_type TEXT NOT NULL,
|
|
1751
|
+
schedule_json TEXT NOT NULL,
|
|
1752
|
+
timezone TEXT NOT NULL DEFAULT 'UTC',
|
|
1753
|
+
overlap_policy TEXT NOT NULL DEFAULT 'skip',
|
|
1754
|
+
misfire_policy TEXT NOT NULL DEFAULT 'catch_up_once',
|
|
1755
|
+
status TEXT NOT NULL DEFAULT 'active',
|
|
1756
|
+
next_run_at TEXT,
|
|
1757
|
+
last_run_at TEXT,
|
|
1758
|
+
revision INTEGER NOT NULL DEFAULT 1,
|
|
1759
|
+
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
1760
|
+
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
|
|
1761
|
+
);
|
|
1762
|
+
|
|
1763
|
+
CREATE INDEX IF NOT EXISTS idx_scheduled_tasks_due
|
|
1764
|
+
ON scheduled_tasks(status, next_run_at);
|
|
1765
|
+
CREATE INDEX IF NOT EXISTS idx_scheduled_tasks_network
|
|
1766
|
+
ON scheduled_tasks(network_id, updated_at DESC);
|
|
1767
|
+
CREATE INDEX IF NOT EXISTS idx_scheduled_tasks_target
|
|
1768
|
+
ON scheduled_tasks(network_id, target_node_id);
|
|
1769
|
+
|
|
1770
|
+
CREATE TABLE IF NOT EXISTS scheduled_task_runs (
|
|
1771
|
+
run_id TEXT PRIMARY KEY,
|
|
1772
|
+
schedule_id TEXT NOT NULL,
|
|
1773
|
+
network_id TEXT NOT NULL,
|
|
1774
|
+
scheduled_for TEXT NOT NULL,
|
|
1775
|
+
task_id TEXT,
|
|
1776
|
+
status TEXT NOT NULL,
|
|
1777
|
+
error_code TEXT,
|
|
1778
|
+
error_message TEXT,
|
|
1779
|
+
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
1780
|
+
completed_at TEXT,
|
|
1781
|
+
UNIQUE(schedule_id, scheduled_for)
|
|
1782
|
+
);
|
|
1783
|
+
|
|
1784
|
+
CREATE INDEX IF NOT EXISTS idx_scheduled_runs_schedule
|
|
1785
|
+
ON scheduled_task_runs(schedule_id, created_at DESC);
|
|
1786
|
+
CREATE INDEX IF NOT EXISTS idx_scheduled_runs_network
|
|
1787
|
+
ON scheduled_task_runs(network_id, created_at DESC);
|
|
1788
|
+
`);
|
|
1789
|
+
// #1278 — opt-in state. Existing schedules remain disabled.
|
|
1790
|
+
try { db.exec("ALTER TABLE scheduled_tasks ADD COLUMN no_change_backoff INTEGER NOT NULL DEFAULT 0"); } catch {}
|
|
1791
|
+
try { db.exec("ALTER TABLE scheduled_tasks ADD COLUMN backoff_streak INTEGER NOT NULL DEFAULT 0"); } catch {}
|
|
1792
|
+
try { db.exec("ALTER TABLE scheduled_tasks ADD COLUMN backoff_effective_seconds INTEGER"); } catch {}
|
|
1793
|
+
try { db.exec("ALTER TABLE scheduled_tasks ADD COLUMN backoff_last_run_id TEXT"); } catch {}
|
|
1794
|
+
try { db.exec("ALTER TABLE scheduled_task_runs ADD COLUMN backoff_excluded INTEGER NOT NULL DEFAULT 0"); } catch {}
|
|
1795
|
+
// #1279 — opt-in requirement event policy/cursor; old plans stay disabled.
|
|
1796
|
+
try { db.exec("ALTER TABLE scheduled_tasks ADD COLUMN requirement_wake_json TEXT"); } catch {}
|
|
1797
|
+
try { db.exec("ALTER TABLE scheduled_tasks ADD COLUMN requirement_wake_cursor INTEGER NOT NULL DEFAULT 0"); } catch {}
|
|
1798
|
+
try { db.exec("ALTER TABLE scheduled_tasks ADD COLUMN requirement_wake_last_event_id INTEGER"); } catch {}
|
|
1799
|
+
// #1274 — explicit successful-work signal and dispatch revision, separate
|
|
1800
|
+
// from lifecycle. NULL is unknown for legacy runs; rollback ignores columns.
|
|
1801
|
+
try { db.exec("ALTER TABLE scheduled_task_runs ADD COLUMN work_outcome TEXT"); } catch {}
|
|
1802
|
+
try { db.exec("ALTER TABLE scheduled_task_runs ADD COLUMN schedule_revision INTEGER"); } catch {}
|
|
1803
|
+
try { db.exec("ALTER TABLE scheduled_task_runs ADD COLUMN work_outcome_node_id TEXT"); } catch {}
|
|
1804
|
+
try { db.exec("ALTER TABLE scheduled_tasks ADD COLUMN misfire_policy TEXT NOT NULL DEFAULT 'catch_up_once'"); } catch {}
|
|
1805
|
+
// Skipped runs (overlap_policy=skip) name the open task that blocked them and
|
|
1806
|
+
// whether the node had ever picked it up: not_received | in_progress.
|
|
1807
|
+
try { db.exec("ALTER TABLE scheduled_task_runs ADD COLUMN blocked_by_task_id TEXT"); } catch {}
|
|
1808
|
+
try { db.exec("ALTER TABLE scheduled_task_runs ADD COLUMN blocked_by_state TEXT"); } catch {}
|
|
1809
|
+
// Board #733 — schedules an Agent created over MCP name the creating node. NULL = created by a person
|
|
1810
|
+
// (REST / Dashboard) or a row from before this column; old rows keep NULL and old code never reads it.
|
|
1811
|
+
try { db.exec("ALTER TABLE scheduled_tasks ADD COLUMN created_by_node_id TEXT"); } catch {}
|
|
1812
|
+
|
|
1813
|
+
try { db.exec(`CREATE TABLE IF NOT EXISTS scheduled_task_watchers (
|
|
1814
|
+
schedule_id TEXT NOT NULL,
|
|
1815
|
+
user_id TEXT NOT NULL,
|
|
1816
|
+
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
1817
|
+
PRIMARY KEY (schedule_id, user_id)
|
|
1818
|
+
)`); } catch {}
|
|
1819
|
+
try { db.exec("CREATE INDEX IF NOT EXISTS idx_scheduled_task_watchers_user ON scheduled_task_watchers(user_id)"); } catch {}
|
|
1820
|
+
try { db.exec("CREATE INDEX IF NOT EXISTS idx_scheduled_tasks_creator_node ON scheduled_tasks(network_id, created_by_node_id)"); } catch {}
|
|
1821
|
+
// #523 — consecutive-failure alert bookkeeping (scheduled-failures.ts). Additive and nullable:
|
|
1822
|
+
// an older Hub never reads them, so rolling back is safe. failure_alert_at = ISO time of the last
|
|
1823
|
+
// alert; failure_alert_key = the last successful run_id at that moment ('' = none yet), so a
|
|
1824
|
+
// success in between re-arms the alert.
|
|
1825
|
+
try { db.exec("ALTER TABLE scheduled_tasks ADD COLUMN failure_alert_at TEXT"); } catch {}
|
|
1826
|
+
try { db.exec("ALTER TABLE scheduled_tasks ADD COLUMN failure_alert_key TEXT"); } catch {}
|
|
1827
|
+
// Board #757 — one warning per continuous target-offline episode. The scheduler
|
|
1828
|
+
// clears this as soon as the target session is online again; older Hubs ignore it.
|
|
1829
|
+
try { db.exec("ALTER TABLE scheduled_tasks ADD COLUMN offline_alert_at TEXT"); } catch {}
|
|
1830
|
+
|
|
1831
|
+
// RFC-036 / B4 — owner-authorized edits of node-host managed schedules.
|
|
1832
|
+
// This is intentionally separate from Hub scheduled_tasks: these rows are
|
|
1833
|
+
// one-shot control intents consumed by the exact token-bound node. The partial
|
|
1834
|
+
// unique index makes the single-flight promise survive multiple Hub workers.
|
|
1835
|
+
db.exec(`
|
|
1836
|
+
CREATE TABLE IF NOT EXISTS external_schedule_edits (
|
|
1837
|
+
intent_id TEXT PRIMARY KEY,
|
|
1838
|
+
network_id TEXT NOT NULL,
|
|
1839
|
+
node_id TEXT NOT NULL,
|
|
1840
|
+
schedule_id TEXT NOT NULL,
|
|
1841
|
+
base_revision INTEGER NOT NULL,
|
|
1842
|
+
patch_json TEXT NOT NULL,
|
|
1843
|
+
status TEXT NOT NULL DEFAULT 'pending',
|
|
1844
|
+
expires_at INTEGER NOT NULL,
|
|
1845
|
+
created_at INTEGER NOT NULL,
|
|
1846
|
+
delivered_at INTEGER,
|
|
1847
|
+
acked_at INTEGER,
|
|
1848
|
+
created_by_user TEXT NOT NULL,
|
|
1849
|
+
created_by_token TEXT NOT NULL,
|
|
1850
|
+
consumed_by_token TEXT,
|
|
1851
|
+
result_revision INTEGER,
|
|
1852
|
+
error_code TEXT
|
|
1853
|
+
);
|
|
1854
|
+
|
|
1855
|
+
CREATE INDEX IF NOT EXISTS idx_external_schedule_edits_node
|
|
1856
|
+
ON external_schedule_edits(network_id, node_id, status, created_at);
|
|
1857
|
+
CREATE INDEX IF NOT EXISTS idx_external_schedule_edits_owner
|
|
1858
|
+
ON external_schedule_edits(created_by_user, created_at DESC);
|
|
1859
|
+
CREATE UNIQUE INDEX IF NOT EXISTS idx_external_schedule_edits_singleflight
|
|
1860
|
+
ON external_schedule_edits(node_id, schedule_id)
|
|
1861
|
+
WHERE status IN ('pending', 'delivered');
|
|
1862
|
+
`);
|
|
1033
1863
|
try { db.exec("CREATE INDEX IF NOT EXISTS idx_tasks_parent ON tasks(parent_task_id)"); } catch {}
|
|
1034
1864
|
|
|
1035
1865
|
// Helpers
|
|
@@ -1296,6 +2126,72 @@ export function chainReplyToParent(
|
|
|
1296
2126
|
maxDepth = 5,
|
|
1297
2127
|
callerNetId?: string | null,
|
|
1298
2128
|
): ChainReplyResult {
|
|
2129
|
+
// Node-TMAI#4 (E/F): bind the ORIGIN of the result once, up front.
|
|
2130
|
+
//
|
|
2131
|
+
// The walk below climbs from the child towards the root, so the loop
|
|
2132
|
+
// variable is the CURRENT HOP's child and it changes on every iteration.
|
|
2133
|
+
// That is hop identity, not result identity. Conflating the two was the
|
|
2134
|
+
// defect this key used to carry: keying the de-dup index on the loop
|
|
2135
|
+
// variable let a descendant's upward notice burn an intermediate task's
|
|
2136
|
+
// key, so that task's own later completion looked like a "replay" and was
|
|
2137
|
+
// silently dropped (grandparent <- parent <- leaf, then the parent
|
|
2138
|
+
// finishes for real => 0 notices). Three notions are now kept apart:
|
|
2139
|
+
//
|
|
2140
|
+
// * originChildId / originAlias / originReply — the ONE task whose
|
|
2141
|
+
// result this call carries; fixed for the whole walk.
|
|
2142
|
+
// * originStamp — the DELIVERY of that result (its terminal
|
|
2143
|
+
// transition), kept only as a human-readable audit value.
|
|
2144
|
+
// * attemptKey — the ATTEMPT that produced the result: the inbox
|
|
2145
|
+
// transport row that queued it. See the block below for why the
|
|
2146
|
+
// delivery stamp alone is not usable as the key.
|
|
2147
|
+
// * hopKind — "completion" (the origin's own result reaching its
|
|
2148
|
+
// direct parent) vs "descendant" (a forwarded notice at a higher
|
|
2149
|
+
// ancestor). The two can never share a de-dup slot.
|
|
2150
|
+
const origin = db.get<{
|
|
2151
|
+
to_name: string;
|
|
2152
|
+
completed_at: string | null;
|
|
2153
|
+
delivered_at: string | null;
|
|
2154
|
+
started_at: string | null;
|
|
2155
|
+
}>(
|
|
2156
|
+
"SELECT to_name, completed_at, delivered_at, started_at FROM tasks WHERE task_id = ?1",
|
|
2157
|
+
childTaskId
|
|
2158
|
+
);
|
|
2159
|
+
const originChildId = childTaskId;
|
|
2160
|
+
const originAlias = origin?.to_name ?? childTaskId.slice(0, 8);
|
|
2161
|
+
const originStamp = (origin?.completed_at ?? origin?.delivered_at ?? origin?.started_at ?? "n/a")
|
|
2162
|
+
.replace(/[^0-9A-Za-z]/g, "-");
|
|
2163
|
+
const originReply = replyText;
|
|
2164
|
+
|
|
2165
|
+
// Node-TMAI#4 (F, round 3): the de-dup key must identify the ATTEMPT, and
|
|
2166
|
+
// no delivery timestamp can do that. `completed_at` / `delivered_at` are
|
|
2167
|
+
// written with `datetime('now')` — second granularity — so two legitimate
|
|
2168
|
+
// attempts of one task_id (the second one created by `retry_task`) can
|
|
2169
|
+
// complete inside the same second and carry an identical stamp. The later
|
|
2170
|
+
// result then looked like a replay of the earlier one and was swallowed.
|
|
2171
|
+
//
|
|
2172
|
+
// A retry or a reassign queues a fresh inbox transport row for the same
|
|
2173
|
+
// task_id, inside the same transaction as the task reset: `retry_task`
|
|
2174
|
+
// first runs `UPDATE tasks SET status='delivered', result=NULL,
|
|
2175
|
+
// completed_at=NULL, ...` and only then `INSERT INTO inbox` with a new id;
|
|
2176
|
+
// `reassign_task` acks the old row, updates the task, then inserts the new
|
|
2177
|
+
// one. db.ts #520 keeps transport-row identity separate from logical task
|
|
2178
|
+
// identity for precisely this reason ("runtime evidence/replies survive
|
|
2179
|
+
// those redeliveries"). This candidate therefore takes the newest
|
|
2180
|
+
// transport row of the task as its attempt identity: it changes on every
|
|
2181
|
+
// retry/reassign and survives a re-delivery of the same attempt, and it
|
|
2182
|
+
// needs no schema change.
|
|
2183
|
+
//
|
|
2184
|
+
// That is the identity source THIS CANDIDATE adopts; it is not a verified
|
|
2185
|
+
// account of every asynchronous late-reply or retention path, and those
|
|
2186
|
+
// are out of scope here. A row that was never dispatched (synthetic or
|
|
2187
|
+
// imported) has no transport row and falls back to its delivery stamp,
|
|
2188
|
+
// which preserves the old behaviour for those.
|
|
2189
|
+
const dispatch = db.get<{ transport_id: string | null }>(
|
|
2190
|
+
"SELECT id AS transport_id FROM inbox WHERE task_id = ?1 ORDER BY rowid DESC LIMIT 1",
|
|
2191
|
+
childTaskId
|
|
2192
|
+
);
|
|
2193
|
+
const attemptKey = dispatch?.transport_id ?? `undispatched-${originStamp}`;
|
|
2194
|
+
|
|
1299
2195
|
let currentChildId: string | null = childTaskId;
|
|
1300
2196
|
let currentReply = replyText;
|
|
1301
2197
|
let depth = 0;
|
|
@@ -1309,6 +2205,9 @@ export function chainReplyToParent(
|
|
|
1309
2205
|
|
|
1310
2206
|
while (currentChildId && depth < maxDepth) {
|
|
1311
2207
|
depth++;
|
|
2208
|
+
// Narrow the loop cursor once. It is the walk position for this hop and
|
|
2209
|
+
// nothing else; the result's origin is pinned outside the loop above.
|
|
2210
|
+
const hopChildId: string = currentChildId;
|
|
1312
2211
|
type ChildRow = { parent_task_id: string | null; to_name: string; from_name: string; content: string };
|
|
1313
2212
|
type ParentRow = { task_id: string; from_name: string; to_name: string; status: string; result: string | null; network_id: string | null; parent_task_id: string | null };
|
|
1314
2213
|
const child: ChildRow | null = db.get<ChildRow>(
|
|
@@ -1334,61 +2233,273 @@ export function chainReplyToParent(
|
|
|
1334
2233
|
}
|
|
1335
2234
|
}
|
|
1336
2235
|
|
|
2236
|
+
// The origin's own result reaching its direct parent is the "executor
|
|
2237
|
+
// completion" notice; anything higher up is a "descendant notice"
|
|
2238
|
+
// forwarded on the origin's behalf. They are different events and must
|
|
2239
|
+
// never occupy the same de-dup slot.
|
|
2240
|
+
const hopKind = depth === 1 ? "completion" : "descendant";
|
|
1337
2241
|
const childAlias = child.to_name;
|
|
1338
2242
|
const marker = `\n\n[via ${childAlias} 子任务结果]\n${currentReply}`;
|
|
1339
2243
|
const newResult = parent.result ? parent.result + marker : `[via ${childAlias} 子任务结果]\n${currentReply}`;
|
|
1340
2244
|
|
|
1341
|
-
//
|
|
1342
|
-
//
|
|
1343
|
-
//
|
|
1344
|
-
//
|
|
1345
|
-
|
|
1346
|
-
|
|
1347
|
-
|
|
1348
|
-
|
|
1349
|
-
|
|
1350
|
-
|
|
1351
|
-
|
|
1352
|
-
|
|
1353
|
-
|
|
1354
|
-
[newResult.slice(0, 8000), parent.task_id]
|
|
2245
|
+
// Node-TMAI#4 (E/F): one ATTEMPT of a child result may be recorded
|
|
2246
|
+
// against a parent at most once. The key binds the ORIGIN of the result
|
|
2247
|
+
// (not the loop variable), the attempt (its inbox transport row), the
|
|
2248
|
+
// parent and the hop kind. A replayed reply therefore cannot fan out
|
|
2249
|
+
// into a second audit row and a second notice, while a fresh attempt of
|
|
2250
|
+
// the same task (a legal retry) still gets through.
|
|
2251
|
+
const recordKey = `auto-chain:${hopKind}:${parent.task_id}:${originChildId}:${attemptKey}`;
|
|
2252
|
+
let recorded = false;
|
|
2253
|
+
|
|
2254
|
+
db.transaction(() => {
|
|
2255
|
+
const already = db.get<{ c: number }>(
|
|
2256
|
+
"SELECT COUNT(*) AS c FROM task_events WHERE task_id = ?1 AND event_key = ?2",
|
|
2257
|
+
[parent.task_id, recordKey]
|
|
1355
2258
|
);
|
|
1356
|
-
|
|
1357
|
-
}
|
|
2259
|
+
if ((already?.c ?? 0) > 0) return;
|
|
1358
2260
|
|
|
1359
|
-
|
|
1360
|
-
|
|
1361
|
-
|
|
1362
|
-
|
|
1363
|
-
|
|
1364
|
-
[parent.from_name, parent.network_id ?? null]
|
|
1365
|
-
);
|
|
2261
|
+
// An OPEN parent is completed by the chain: this is the #690 contract —
|
|
2262
|
+
// a scheduled/dispatched parent whose executor answered through a child
|
|
2263
|
+
// must reach a terminal state, and its scheduler-run mirror follows it
|
|
2264
|
+
// in the same transaction.
|
|
2265
|
+
if (parent.status === "delivered" || parent.status === "acked" || parent.status === "running" || parent.status === "created") {
|
|
1366
2266
|
db.run(
|
|
1367
|
-
|
|
1368
|
-
|
|
1369
|
-
[notifyId, parent.from_name, notifyNode?.node_id ?? null, `[${childAlias} 子任务完成]\n${currentReply.slice(0, 4000)}`, parent.to_name, parent.task_id, parent.network_id ?? null]
|
|
2267
|
+
"UPDATE tasks SET status = ?1, result = ?2, completed_at = datetime('now') WHERE task_id = ?3",
|
|
2268
|
+
[replyStatus, newResult.slice(0, 8000), parent.task_id]
|
|
1370
2269
|
);
|
|
1371
|
-
|
|
1372
|
-
|
|
2270
|
+
syncScheduledRunForTask(parent.task_id, parent.network_id);
|
|
2271
|
+
logTaskEvent(
|
|
2272
|
+
parent.task_id, parent.status, replyStatus, "auto-chain",
|
|
2273
|
+
`from ${childAlias}; origin ${originChildId.slice(0, 8)}, attempt=${attemptKey}`,
|
|
2274
|
+
recordKey,
|
|
2275
|
+
);
|
|
2276
|
+
} else {
|
|
2277
|
+
// A TERMINAL parent is never rewritten. It used to have its `result`
|
|
2278
|
+
// appended and its `completed_at` moved forward long after it had
|
|
2279
|
+
// finished (observed: 22 minutes later), so an answer given to the
|
|
2280
|
+
// parent could silently become part of somebody else's result. The
|
|
2281
|
+
// child result is still recorded — as an audit row plus a notice to
|
|
2282
|
+
// the parent's author — but the parent row stays byte-identical.
|
|
2283
|
+
logTaskEvent(
|
|
2284
|
+
parent.task_id, parent.status, parent.status, "auto-chain-append",
|
|
2285
|
+
`from ${childAlias}; origin ${originChildId.slice(0, 8)}, attempt=${attemptKey}; terminal parent left untouched`,
|
|
2286
|
+
recordKey,
|
|
2287
|
+
);
|
|
2288
|
+
}
|
|
2289
|
+
// The audit row for this (parent, child) link now exists. Only a call
|
|
2290
|
+
// that actually recorded one may unlock the caller's SSE push; a
|
|
2291
|
+
// deduped replay returns early above and leaves this false.
|
|
2292
|
+
recorded = true;
|
|
2293
|
+
|
|
2294
|
+
if (parent.from_name && parent.from_name !== "hub" && parent.from_name !== "api") {
|
|
2295
|
+
try {
|
|
2296
|
+
const notifyId = `chain_${crypto.randomUUID().replace(/-/g, "").slice(0, 16)}`;
|
|
2297
|
+
const notifyNode = db.get<{ node_id: string | null }>(
|
|
2298
|
+
"SELECT node_id FROM sessions WHERE alias = ?1 AND COALESCE(network_id, 'default') = COALESCE(?2, 'default') ORDER BY updated_at DESC LIMIT 1",
|
|
2299
|
+
[parent.from_name, parent.network_id ?? null]
|
|
2300
|
+
);
|
|
2301
|
+
db.run(
|
|
2302
|
+
`INSERT INTO inbox (id, session_name, node_id, type, priority, content, from_session, in_reply_to, requires_response, network_id)
|
|
2303
|
+
VALUES (?1, ?2, ?3, 'reply', 'normal', ?4, ?5, ?6, 'none', ?7)`,
|
|
2304
|
+
[notifyId, parent.from_name, notifyNode?.node_id ?? null, `[${childAlias} ${hopKind === "descendant" ? "后代结果转呈" : "子任务完成"}]\n${originReply.slice(0, 4000)}`, parent.to_name, parent.task_id, parent.network_id ?? null]
|
|
2305
|
+
);
|
|
2306
|
+
} catch {}
|
|
2307
|
+
}
|
|
2308
|
+
});
|
|
1373
2309
|
|
|
1374
|
-
//
|
|
1375
|
-
//
|
|
1376
|
-
|
|
1377
|
-
chained = true;
|
|
2310
|
+
// An audit row (and possibly an inbox notification) was recorded for
|
|
2311
|
+
// this parent-child link. The caller gates its SSE push on this.
|
|
2312
|
+
if (recorded) chained = true;
|
|
1378
2313
|
|
|
1379
|
-
// Recurse up the chain.
|
|
1380
|
-
|
|
2314
|
+
// Recurse up the chain. Only the HOP cursor advances: the origin and
|
|
2315
|
+
// its delivery stay pinned, so no hop can absorb another's identity
|
|
2316
|
+
// and each notice carries the origin reply once instead of nesting
|
|
2317
|
+
// every ancestor's copy of it.
|
|
1381
2318
|
currentReply = newResult;
|
|
2319
|
+
currentChildId = parent.task_id;
|
|
1382
2320
|
}
|
|
1383
2321
|
return { chained };
|
|
1384
2322
|
}
|
|
1385
2323
|
|
|
1386
|
-
|
|
2324
|
+
const SCHEDULED_RUN_TERMINAL_STATUSES = new Set(["replied", "failed", "cancelled", "expired"]);
|
|
2325
|
+
|
|
2326
|
+
// #523 — called after a run row is closed by its task's terminal state. Registered by
|
|
2327
|
+
// scheduled-failures.ts (a hook, not an import: that module depends on db.ts). Never throws.
|
|
2328
|
+
type ScheduledRunTerminalHook = (scheduleId: string, status: string) => void;
|
|
2329
|
+
let scheduledRunTerminalHook: ScheduledRunTerminalHook | null = null;
|
|
2330
|
+
export function setScheduledRunTerminalHook(fn: ScheduledRunTerminalHook | null): void { scheduledRunTerminalHook = fn; }
|
|
2331
|
+
function fireScheduledRunTerminalHook(scheduleId: string, status: string): void {
|
|
2332
|
+
if (!scheduledRunTerminalHook) return;
|
|
2333
|
+
try { scheduledRunTerminalHook(scheduleId, status); } catch (e: any) {
|
|
2334
|
+
console.error(`[scheduled-tasks] run terminal hook failed schedule=${scheduleId}: ${e?.message || e}`);
|
|
2335
|
+
}
|
|
2336
|
+
}
|
|
2337
|
+
|
|
2338
|
+
type ScheduledTaskLifecycleRow = {
|
|
2339
|
+
task_id: string;
|
|
2340
|
+
network_id: string | null;
|
|
2341
|
+
status: string;
|
|
2342
|
+
completed_at: string | null;
|
|
2343
|
+
result: string | null;
|
|
2344
|
+
};
|
|
2345
|
+
|
|
2346
|
+
type ScheduledTaskBinding = { run_id: string; schedule_id: string };
|
|
2347
|
+
|
|
2348
|
+
/**
|
|
2349
|
+
* Mirror an exact scheduler-created task's lifecycle into its run row.
|
|
2350
|
+
*
|
|
2351
|
+
* The status is always read back from `tasks`; callers cannot supply one.
|
|
2352
|
+
* The scheduler's storage binding is the four-part tuple
|
|
2353
|
+
* (run_id, schedule_id, task_id, network_id). It is read from
|
|
2354
|
+
* `scheduled_task_runs`, not caller-controlled task metadata (which may also
|
|
2355
|
+
* legitimately be replaced by reply attachment metadata).
|
|
2356
|
+
*
|
|
2357
|
+
* Terminal states close the run. `retry_task` calls this after resetting the
|
|
2358
|
+
* same logical task_id to delivered, which deliberately reopens that run so
|
|
2359
|
+
* the history reflects the current retry rather than the first failed attempt.
|
|
2360
|
+
*/
|
|
2361
|
+
export function syncScheduledRunForTask(taskId: string, expectedNetworkId?: string | null): { matched: boolean; status?: string } {
|
|
2362
|
+
return db.transaction(() => syncScheduledRunForTaskInTransaction(taskId, expectedNetworkId));
|
|
2363
|
+
}
|
|
2364
|
+
|
|
2365
|
+
function syncScheduledRunForTaskInTransaction(taskId: string, expectedNetworkId?: string | null): { matched: boolean; status?: string } {
|
|
2366
|
+
const task = db.get<ScheduledTaskLifecycleRow>(
|
|
2367
|
+
`SELECT task_id, network_id, status, completed_at, result
|
|
2368
|
+
FROM tasks
|
|
2369
|
+
WHERE task_id = ?1
|
|
2370
|
+
AND (CAST(?2 AS TEXT) IS NULL OR network_id = ?2)`,
|
|
2371
|
+
taskId,
|
|
2372
|
+
expectedNetworkId ?? null,
|
|
2373
|
+
);
|
|
2374
|
+
if (!task?.network_id) return { matched: false };
|
|
2375
|
+
const bindings = db.all<ScheduledTaskBinding>(
|
|
2376
|
+
`SELECT run_id, schedule_id FROM scheduled_task_runs
|
|
2377
|
+
WHERE task_id = ?1 AND network_id = ?2`,
|
|
2378
|
+
task.task_id,
|
|
2379
|
+
task.network_id,
|
|
2380
|
+
);
|
|
2381
|
+
// One task belongs to at most one scheduled occurrence. Fail closed if a
|
|
2382
|
+
// corrupt/legacy database violates that invariant rather than fanning one
|
|
2383
|
+
// lifecycle transition into multiple runs.
|
|
2384
|
+
if (bindings.length !== 1) return { matched: false };
|
|
2385
|
+
const binding = bindings[0];
|
|
2386
|
+
|
|
2387
|
+
if (SCHEDULED_RUN_TERMINAL_STATUSES.has(task.status)) {
|
|
2388
|
+
const errorCode = scheduledFailureCode(task.status, task.result);
|
|
2389
|
+
const updated = db.run(
|
|
2390
|
+
`UPDATE scheduled_task_runs
|
|
2391
|
+
SET status = ?1,
|
|
2392
|
+
error_code = ?2,
|
|
2393
|
+
error_message = NULL,
|
|
2394
|
+
work_outcome = CASE WHEN ?1 = 'replied' THEN work_outcome ELSE NULL END,
|
|
2395
|
+
work_outcome_node_id = CASE WHEN ?1 = 'replied' THEN work_outcome_node_id ELSE NULL END,
|
|
2396
|
+
completed_at = COALESCE(?3, datetime('now'))
|
|
2397
|
+
WHERE run_id = ?4 AND task_id = ?5 AND network_id = ?6 AND schedule_id = ?7`,
|
|
2398
|
+
[task.status, errorCode, task.completed_at, binding.run_id, task.task_id, task.network_id, binding.schedule_id],
|
|
2399
|
+
);
|
|
2400
|
+
if (updated.changes === 1) {
|
|
2401
|
+
refreshScheduledBackoff(binding.schedule_id, task.network_id!);
|
|
2402
|
+
fireScheduledRunTerminalHook(binding.schedule_id, task.status);
|
|
2403
|
+
}
|
|
2404
|
+
return { matched: updated.changes === 1, status: task.status };
|
|
2405
|
+
}
|
|
2406
|
+
|
|
2407
|
+
if (task.status === "delivered") {
|
|
2408
|
+
const updated = db.run(
|
|
2409
|
+
`UPDATE scheduled_task_runs
|
|
2410
|
+
SET status = 'delivered', error_code = NULL, error_message = NULL, completed_at = NULL, work_outcome = NULL, work_outcome_node_id = NULL, backoff_excluded = 1
|
|
2411
|
+
WHERE run_id = ?1 AND task_id = ?2 AND network_id = ?3 AND schedule_id = ?4`,
|
|
2412
|
+
[binding.run_id, task.task_id, task.network_id, binding.schedule_id],
|
|
2413
|
+
);
|
|
2414
|
+
return { matched: updated.changes === 1, status: task.status };
|
|
2415
|
+
}
|
|
2416
|
+
|
|
2417
|
+
return { matched: false };
|
|
2418
|
+
}
|
|
2419
|
+
|
|
2420
|
+
function taskEventTypeForStatus(toStatus: string): string {
|
|
2421
|
+
switch (toStatus) {
|
|
2422
|
+
case "delivered": return "task.send.delivered";
|
|
2423
|
+
case "acked": return "task.ack";
|
|
2424
|
+
case "running": return "task.started";
|
|
2425
|
+
case "replied": return "task.replied";
|
|
2426
|
+
case "expired": return "task.expired";
|
|
2427
|
+
case "failed":
|
|
2428
|
+
case "cancelled": return "task.failed";
|
|
2429
|
+
default: return `task.status.${toStatus}`;
|
|
2430
|
+
}
|
|
2431
|
+
}
|
|
2432
|
+
|
|
2433
|
+
export function logTaskEvent(taskId: string, fromStatus: string | null, toStatus: string, actor: string, detail?: string, eventKey?: string) {
|
|
1387
2434
|
try {
|
|
1388
2435
|
db.run(
|
|
1389
|
-
`INSERT INTO task_events (task_id, from_status, to_status, actor, detail, network_id)
|
|
1390
|
-
VALUES (?1, ?2, ?3, ?4, ?5, (SELECT network_id FROM tasks WHERE task_id = ?1))`,
|
|
1391
|
-
[taskId, fromStatus, toStatus, actor, detail ?? null]
|
|
2436
|
+
`INSERT INTO task_events (task_id, from_status, to_status, event_type, event_key, actor, detail, network_id)
|
|
2437
|
+
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, (SELECT network_id FROM tasks WHERE task_id = ?1))`,
|
|
2438
|
+
[taskId, fromStatus, toStatus, taskEventTypeForStatus(toStatus), eventKey ?? null, actor, detail ?? null]
|
|
1392
2439
|
);
|
|
1393
2440
|
} catch {}
|
|
1394
2441
|
}
|
|
2442
|
+
|
|
2443
|
+
// RFC-039 F3: queries break created_at ties with SQLite's implicit rowid
|
|
2444
|
+
// (insertion order). PostgreSQL has none, so give these tables a real one.
|
|
2445
|
+
if (db.dialect === "postgres") {
|
|
2446
|
+
for (const table of ["nodes", "user_inbox", "inbox"]) db.exec(`ALTER TABLE ${table} ADD COLUMN IF NOT EXISTS rowid BIGSERIAL`);
|
|
2447
|
+
}
|
|
2448
|
+
|
|
2449
|
+
// Board #625: common SQLite/PostgreSQL DDL. Adoption records authority, not processes.
|
|
2450
|
+
db.exec(`
|
|
2451
|
+
CREATE TABLE IF NOT EXISTS node_daemon_bindings (
|
|
2452
|
+
request_id TEXT PRIMARY KEY,
|
|
2453
|
+
network_id TEXT NOT NULL,
|
|
2454
|
+
node_id TEXT NOT NULL,
|
|
2455
|
+
daemon_node_id TEXT NOT NULL,
|
|
2456
|
+
workdir TEXT NOT NULL,
|
|
2457
|
+
requested_by TEXT NOT NULL,
|
|
2458
|
+
status TEXT NOT NULL CHECK (status IN ('pending','active','refused','revoked')),
|
|
2459
|
+
error TEXT,
|
|
2460
|
+
created_at BIGINT NOT NULL,
|
|
2461
|
+
updated_at BIGINT NOT NULL
|
|
2462
|
+
);
|
|
2463
|
+
CREATE UNIQUE INDEX IF NOT EXISTS idx_ndb_live_node
|
|
2464
|
+
ON node_daemon_bindings(node_id) WHERE status IN ('pending','active');
|
|
2465
|
+
CREATE INDEX IF NOT EXISTS idx_ndb_daemon_network
|
|
2466
|
+
ON node_daemon_bindings(daemon_node_id,network_id,status);
|
|
2467
|
+
`);
|
|
2468
|
+
|
|
2469
|
+
// #1198 — OS account the node process runs as. Appended at the end of this file
|
|
2470
|
+
// on purpose: docs/test846 pin line anchors in db.ts, and an in-place insertion
|
|
2471
|
+
// would drift every anchor below it.
|
|
2472
|
+
try { db.exec("ALTER TABLE sessions ADD COLUMN os_user TEXT"); } catch {}
|
|
2473
|
+
|
|
2474
|
+
// #1474 — env key NAMES the node reports having (JSON array of strings, never
|
|
2475
|
+
// values). Appended after os_user for the same reason: doc/test anchors pin
|
|
2476
|
+
// line numbers in this file, so new migrations go at EOF, never in the middle.
|
|
2477
|
+
try { db.exec("ALTER TABLE sessions ADD COLUMN secret_keys TEXT"); } catch {}
|
|
2478
|
+
|
|
2479
|
+
// #1510 — how the node reaches the hub (loopback / https / plain), reported by
|
|
2480
|
+
// the node itself. Appended at EOF like the other post-1.0 columns so the doc
|
|
2481
|
+
// and test846 line anchors below it never drift.
|
|
2482
|
+
try { db.exec("ALTER TABLE sessions ADD COLUMN env_transport TEXT"); } catch {}
|
|
2483
|
+
|
|
2484
|
+
// #1510 — hourly count of secret writes that a transport gate WOULD have refused
|
|
2485
|
+
// (nodes reporting a plain-HTTP hub link). Log-only until an operator decides.
|
|
2486
|
+
db.exec(`
|
|
2487
|
+
CREATE TABLE IF NOT EXISTS env_transport_would_refuse (
|
|
2488
|
+
network_id TEXT NOT NULL,
|
|
2489
|
+
node_id TEXT NOT NULL,
|
|
2490
|
+
route TEXT NOT NULL,
|
|
2491
|
+
hour TEXT NOT NULL,
|
|
2492
|
+
hits INTEGER NOT NULL DEFAULT 0,
|
|
2493
|
+
sample TEXT,
|
|
2494
|
+
PRIMARY KEY (network_id, node_id, route, hour)
|
|
2495
|
+
);
|
|
2496
|
+
`);
|
|
2497
|
+
|
|
2498
|
+
// 组织架构:Agent(节点)**显式**归属部门。
|
|
2499
|
+
//
|
|
2500
|
+
// 在这条之前,「某个部门有几个 Agent」只能由「负责人(人)在哪个部门」推出来
|
|
2501
|
+
// (`/api/networks/:net/departments/:dept/nodes`)。所以没有负责人、或者负责人不在部门树里的
|
|
2502
|
+
// Agent 只能落进「未归属」——2026-10-19 现网就是 328 个 Agent 全在未归属里,
|
|
2503
|
+
// 而部门 0 个 Agent。这一列让 Agent 可以被直接放进部门,和人的归属互不覆盖:
|
|
2504
|
+
// 显式值优先,没有显式值时仍按负责人的部门推断。
|
|
2505
|
+
try { db.exec("ALTER TABLE nodes ADD COLUMN department_id TEXT"); } catch {}
|