@sleep2agi/commhub-server 0.9.0-preview.28 → 0.9.0-preview.281
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 +120 -3
- package/bin/commhub.ts +93 -9
- package/build-info.json +7 -0
- package/package.json +10 -8
- package/src/ack-create-request-transport.test.ts +182 -0
- package/src/ack-create-request.test.ts +52 -8
- package/src/admin-delete-network-http.test.ts +229 -0
- package/src/admin-networks-http.test.ts +88 -0
- package/src/adoption-candidates-http.test.ts +140 -0
- package/src/adoption-candidates.ts +158 -0
- package/src/agent-access-batch.test.ts +215 -0
- package/src/agent-access.ts +585 -0
- package/src/agent-acl-groups-http.test.ts +247 -0
- package/src/agent-acl-http.test.ts +691 -0
- package/src/agent-acl-slice3-http.test.ts +888 -0
- package/src/agent-department-grants.test.ts +129 -0
- package/src/agent-department-http.test.ts +215 -0
- package/src/agent-groups-perf.test.ts +228 -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/all-status-cache.test.ts +31 -0
- package/src/all-status-cache.ts +37 -0
- package/src/anet-variant-real-daemon-http.test.ts +185 -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 +131 -4
- package/src/auth-abuse-counters.test.ts +144 -0
- package/src/auth-abuse-counters.ts +122 -0
- package/src/auth-layer-shape.test.ts +105 -0
- package/src/auth-password-change-cli-tokens-http.test.ts +423 -0
- package/src/auth-sessions-http.test.ts +260 -0
- package/src/auth-validate.test.ts +5 -1
- package/src/auth-weak-password-login.test.ts +176 -0
- package/src/auth.ts +641 -68
- package/src/backfill-node-ids-2664.test.ts +128 -0
- package/src/binding-generation-http.test.ts +141 -0
- package/src/blocked-exit-on-reply.test.ts +122 -0
- package/src/broadcast-fanout-2721.test.ts +149 -0
- package/src/broadcast-fanout.ts +117 -0
- package/src/build-commit-report-http.test.ts +219 -0
- package/src/build-info.test.ts +60 -0
- package/src/build-info.ts +85 -0
- package/src/chain-attempt-dedup.test.ts +447 -0
- package/src/clip.test.ts +36 -0
- package/src/clip.ts +48 -0
- package/src/clone-node.test.ts +269 -0
- package/src/clone-node.ts +289 -0
- package/src/codex-config-flags.ts +77 -0
- package/src/codex-fork-contract.ts +23 -0
- package/src/codex-fork-migration.test.ts +38 -0
- package/src/commhub-bin-args.test.ts +85 -0
- package/src/config-apply-sec1.test.ts +37 -0
- package/src/config-apply-validate.test.ts +188 -1
- package/src/config-apply-validate.ts +226 -3
- package/src/contracts/session-project-create.ts +14 -0
- package/src/contracts/session-source-delivery.ts +16 -0
- package/src/contracts/session-source-directory.ts +54 -0
- package/src/contracts/session-source-evidence.ts +72 -0
- package/src/contracts/session-source-execution.ts +24 -0
- package/src/contracts/session-source-transport.ts +18 -0
- package/src/cors-origins.test.ts +73 -0
- package/src/create-node-blocked-gate.test.ts +365 -0
- package/src/create-node-error-domain.test.ts +127 -0
- package/src/create-node-network-id.test.ts +91 -0
- package/src/create-node-tool-schema.test.ts +59 -0
- package/src/create-node-unicode-name.test.ts +126 -0
- package/src/create-node-validate.test.ts +199 -7
- package/src/create-node-validate.ts +232 -15
- package/src/create-node-workdir.test.ts +298 -0
- package/src/create-node.ts +88 -23
- package/src/daemon-provider-snapshots.test.ts +453 -0
- package/src/daemon-provider-snapshots.ts +327 -0
- package/src/daemon-token-owner-http.test.ts +346 -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 +1334 -154
- 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 +139 -0
- package/src/departments-http.test.ts +185 -0
- package/src/departments-mcp-error-domain.test.ts +135 -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 +227 -0
- package/src/empty-node-sweeper.test.ts +104 -0
- package/src/empty-node-sweeper.ts +88 -0
- package/src/env-transport-gate-http.test.ts +240 -0
- package/src/env-transport-gate.ts +80 -0
- package/src/env-transport-policy.ts +56 -0
- package/src/etag-of.test.ts +57 -0
- package/src/event-loop-lag.test.ts +180 -0
- package/src/event-loop-lag.ts +201 -0
- package/src/expiry-counters.test.ts +187 -0
- package/src/expiry-counters.ts +227 -0
- package/src/expiry-evidence-db.test.ts +103 -0
- package/src/ext-token-shared.test.ts +60 -0
- package/src/ext-validation-regression.test.ts +10 -17
- 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 +25 -4
- package/src/file-download-date-bucket.test.ts +1 -1
- package/src/file-network-scope-dev-open.test.ts +1 -1
- package/src/file-network-scope.test.ts +7 -6
- package/src/group-membership-events-http.test.ts +264 -0
- package/src/group-messages-http.test.ts +483 -0
- package/src/group-messages.ts +297 -0
- package/src/health-anon-readers.ts +67 -0
- package/src/health-host-disk-2756.test.ts +71 -0
- package/src/health-identity-root.test.ts +98 -0
- package/src/health-redaction.test.ts +1603 -7
- package/src/health-status-reasons.test.ts +84 -0
- package/src/host-supervisor-identity-http.test.ts +152 -0
- package/src/host-supervisor-identity.ts +92 -0
- package/src/host-supervisors-daemon-version.test.ts +137 -0
- package/src/http-gzip.test.ts +94 -0
- package/src/http-gzip.ts +112 -0
- package/src/hub-catalog-read-http.test.ts +664 -0
- package/src/hub-provider-config.test.ts +166 -0
- package/src/hub-provider-config.ts +202 -0
- package/src/hub-timestamp.test.ts +38 -0
- package/src/hub-timestamp.ts +27 -0
- package/src/human-dm.ts +215 -0
- package/src/human-inbox.ts +42 -0
- package/src/inbox-caller.ts +49 -0
- package/src/inbox-count-sse.test.ts +318 -0
- package/src/inbox-count.ts +29 -0
- package/src/index.ts +6 -2
- package/src/launched-by-cli-report-http.test.ts +155 -0
- package/src/license-state.test.ts +105 -0
- package/src/license-state.ts +48 -0
- package/src/lifecycle-error-domain.test.ts +149 -0
- package/src/list-ack-error-domain.test.ts +108 -0
- package/src/list-host-supervisors.test.ts +15 -4
- package/src/list-tasks-omit-default.test.ts +84 -0
- package/src/list-tasks-since-last.test.ts +100 -0
- package/src/list-tasks-since.test.ts +104 -0
- package/src/mcp-context-cost-http.test.ts +127 -0
- package/src/mcp-inflight.test.ts +92 -0
- package/src/mcp-inflight.ts +38 -0
- package/src/mcp-projects-events-http.test.ts +168 -0
- package/src/mcp-route-label-http.test.ts +120 -0
- package/src/mcp-write-network-resolution.test.ts +21 -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-quota-config.test.ts +100 -0
- package/src/network-rules-http.test.ts +169 -0
- package/src/network-rules.ts +129 -0
- package/src/network-scope.ts +222 -3
- package/src/network-token-membership-http.test.ts +186 -0
- package/src/node-alias-control.ts +12 -0
- package/src/node-attrs.test.ts +47 -2
- package/src/node-caller-identity-http.test.ts +1108 -0
- package/src/node-config-last-update.test.ts +126 -0
- package/src/node-config-last-update.ts +107 -0
- package/src/node-create-request-status-http.test.ts +105 -0
- package/src/node-daemon-bindings.test.ts +142 -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 +350 -0
- package/src/node-health-codex-login.test.ts +120 -0
- package/src/node-health-dispatch-http.test.ts +373 -0
- package/src/node-health-guard-origin.test.ts +98 -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-inbox-allowlist-http.test.ts +320 -0
- package/src/node-lifecycle-controllable.test.ts +64 -0
- package/src/node-lifecycle-controllable.ts +53 -0
- package/src/node-lifecycle-read-http.test.ts +257 -0
- package/src/node-lifecycle-read.ts +126 -0
- package/src/node-logs-transport.test.ts +266 -0
- package/src/node-peer-allowlist.test.ts +114 -0
- package/src/node-permissions-http.test.ts +901 -0
- package/src/node-permissions.ts +627 -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-secret-vault-inject.test.ts +132 -0
- package/src/node-security-write-gate.test.ts +72 -0
- package/src/node-serviceability.test.ts +86 -0
- package/src/node-serviceability.ts +124 -0
- package/src/node-session-control-http.test.ts +398 -0
- package/src/node-session-control.ts +316 -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 +224 -0
- package/src/node-token-usage.test.ts +128 -0
- package/src/node-token-usage.ts +228 -0
- package/src/not-found-api-http.test.ts +67 -0
- package/src/observer-avatar-http.test.ts +103 -10
- 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 +282 -0
- package/src/opencode-v2-catalog.ts +357 -0
- package/src/package-self-contained.test.ts +32 -0
- package/src/package-version-consistency.test.ts +25 -0
- package/src/parent-infer.test.ts +82 -0
- package/src/parent-infer.ts +110 -0
- package/src/parent-source-marker.test.ts +70 -0
- package/src/parent-source-orphan.test.ts +121 -0
- package/src/password-network-tokens.ts +25 -0
- package/src/peer-reply-atomic.test.ts +462 -0
- package/src/peer-reply-capability.test.ts +70 -0
- package/src/pg-worker.ts +87 -0
- package/src/poll-pacing.test.ts +74 -0
- package/src/poll-pacing.ts +123 -0
- package/src/probe-provider-error-domain.test.ts +145 -0
- package/src/project-dir-warn-clear-http.test.ts +132 -0
- package/src/project-viewer-can-http.test.ts +116 -0
- package/src/provider-skill-error-domain.test.ts +130 -0
- package/src/provider-tools-shape.test.ts +165 -0
- package/src/push.test.ts +20 -10
- package/src/push.ts +373 -9
- package/src/redact-tokens.test.ts +86 -0
- package/src/redact-tokens.ts +43 -0
- package/src/rejection-counters.test.ts +72 -0
- package/src/rejection-counters.ts +173 -0
- package/src/rename.ts +38 -10
- package/src/reply-target-derivation.test.ts +96 -0
- package/src/report-status-handover-capabilities-http.test.ts +124 -0
- package/src/report-status-host-schema.test.ts +272 -0
- package/src/report-status-resume-id-handover.test.ts +184 -0
- package/src/report-status-secret-keys.test.ts +140 -0
- package/src/require-explicit-test-db.ts +9 -0
- package/src/requirement-due-reminders-http.test.ts +620 -0
- package/src/requirement-due-reminders.ts +416 -0
- package/src/requirement-events-http.test.ts +318 -0
- package/src/requirement-events.test.ts +45 -0
- package/src/requirement-events.ts +144 -0
- package/src/requirement-notify.ts +165 -0
- package/src/requirement-participant-notify-http.test.ts +313 -0
- package/src/requirement-tag-ops-http.test.ts +454 -0
- package/src/requirement-tag-tree-http.test.ts +275 -0
- package/src/requirement-tag-tree.ts +127 -0
- package/src/requirement-tags.ts +102 -0
- package/src/requirements-abandoned-http.test.ts +236 -0
- package/src/requirements-assignee-drift.test.ts +154 -0
- package/src/requirements-comment-http.test.ts +174 -0
- package/src/requirements-completed-at-migration.test.ts +70 -0
- package/src/requirements-errors-mcp-http.test.ts +164 -0
- package/src/requirements-errors.ts +158 -0
- package/src/requirements-etag-http.test.ts +91 -0
- package/src/requirements-http.test.ts +709 -0
- package/src/requirements-last-event-http.test.ts +349 -0
- package/src/requirements-list-mcp-slim-http.test.ts +155 -0
- package/src/requirements-list-slim-http.test.ts +324 -0
- package/src/requirements-mcp.test.ts +180 -0
- package/src/requirements-migrate.ts +283 -0
- package/src/requirements-owner-strict-mcp-http.test.ts +145 -0
- package/src/requirements-people-http.test.ts +114 -0
- package/src/requirements-people-mcp-http.test.ts +231 -0
- package/src/requirements-people.ts +196 -0
- package/src/requirements-priority-lowest.test.ts +114 -0
- package/src/requirements-projects-network-echo.test.ts +57 -0
- package/src/requirements-projects-parent-http.test.ts +123 -0
- package/src/requirements-search-http.test.ts +182 -0
- package/src/requirements-search.test.ts +32 -0
- package/src/requirements-search.ts +145 -0
- package/src/requirements-seq-http.test.ts +193 -0
- package/src/requirements-seq-migration.test.ts +63 -0
- package/src/requirements-start-date.test.ts +125 -0
- package/src/requirements-stats-http.test.ts +357 -0
- package/src/requirements-stats.ts +195 -0
- package/src/requirements-status-participants-http.test.ts +222 -0
- package/src/requirements-upgrade-e2e.test.ts +126 -0
- package/src/requirements-upgrade-migration.test.ts +98 -0
- package/src/requirements.ts +2205 -0
- package/src/resolve-port.test.ts +57 -0
- package/src/resolve-port.ts +44 -0
- package/src/rest-alias-network-fallback-http.test.ts +123 -0
- package/src/rest-alias-network-fallback.test.ts +60 -0
- package/src/rest-alias-network-fallback.ts +65 -0
- package/src/rest-explicit-columns-http.test.ts +266 -0
- package/src/rest-identity.test.ts +130 -0
- package/src/rest-identity.ts +141 -0
- package/src/rest-projections.ts +72 -0
- package/src/rest-read-network-real-chain.test.ts +97 -0
- package/src/rest-write-network-resolution.test.ts +133 -0
- package/src/restart-readiness-http.test.ts +121 -0
- package/src/restricted-files.ts +76 -0
- package/src/retention-first-sweep-quiet.test.ts +31 -0
- package/src/retention.test.ts +100 -40
- package/src/retention.ts +423 -104
- package/src/route-callers-http.test.ts +120 -0
- package/src/route-timing.test.ts +218 -0
- package/src/route-timing.ts +262 -0
- package/src/rules-file-duplicate-alias.test.ts +234 -0
- package/src/rules-file-session-target.test.ts +207 -0
- package/src/rules-file-transport.test.ts +280 -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 +486 -0
- package/src/schedule-agent.ts +252 -0
- package/src/schedule-starved.test.ts +92 -0
- package/src/schedule-starved.ts +114 -0
- package/src/scheduled-backoff-http.test.ts +203 -0
- package/src/scheduled-backoff.ts +64 -0
- package/src/scheduled-doorbell-nodeless-session.test.ts +134 -0
- package/src/scheduled-failure-backoff-2622.test.ts +145 -0
- package/src/scheduled-failure-code.test.ts +73 -0
- package/src/scheduled-failure-code.ts +105 -0
- package/src/scheduled-failures-http.test.ts +279 -0
- package/src/scheduled-failures.ts +425 -0
- package/src/scheduled-noprogress-backoff-2622.test.ts +163 -0
- package/src/scheduled-offline-backoff-probe.test.ts +56 -0
- package/src/scheduled-offline.test.ts +131 -0
- package/src/scheduled-offline.ts +66 -0
- package/src/scheduled-outcome-guidance-http.test.ts +139 -0
- package/src/scheduled-outcome-guidance.ts +9 -0
- package/src/scheduled-reply-unread-http.test.ts +212 -0
- package/src/scheduled-requirement-wake-http.test.ts +289 -0
- package/src/scheduled-requirement-wake.ts +125 -0
- package/src/scheduled-run-terminal.test.ts +290 -0
- package/src/scheduled-skip-blocking-task.test.ts +120 -0
- package/src/scheduled-skip-path-backoff-2622.test.ts +98 -0
- package/src/scheduled-stuck-http.test.ts +316 -0
- package/src/scheduled-stuck-notice-cap.test.ts +80 -0
- package/src/scheduled-stuck.ts +219 -0
- package/src/scheduled-tasks-http.test.ts +679 -0
- package/src/scheduled-tasks.ts +980 -0
- package/src/scheduled-work-outcome-http.test.ts +154 -0
- package/src/scheduled-work-outcome.ts +50 -0
- package/src/scoped-secrets.ts +167 -0
- package/src/secret-echo-negative-control.test.ts +118 -0
- package/src/send-dedup-request-id.test.ts +229 -0
- package/src/send-reply-agent-warning.test.ts +38 -38
- package/src/send-reply-alias-optional.test.ts +131 -0
- package/src/send-reply-attachments.test.ts +28 -7
- 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 +5103 -377
- package/src/session-fork-store.test.ts +43 -0
- package/src/session-fork-store.ts +51 -0
- package/src/session-project-attach-migration.test.ts +23 -0
- package/src/session-project-attach-native.test.ts +123 -0
- package/src/session-project-create-http.test.ts +408 -0
- package/src/session-project-create-native.test.ts +292 -0
- package/src/session-project-create.ts +159 -0
- package/src/session-source-admission-store.ts +58 -0
- package/src/session-source-create.test.ts +155 -0
- package/src/session-source-create.ts +97 -0
- package/src/session-source-delivery.ts +114 -0
- package/src/session-source-directory-http.test.ts +196 -0
- package/src/session-source-evidence.test.ts +905 -0
- package/src/session-source-evidence.ts +191 -0
- package/src/session-source-execution.ts +87 -0
- package/src/session-source-grant.test.ts +117 -0
- package/src/session-source-grant.ts +78 -0
- package/src/session-source-issuer.test.ts +250 -0
- package/src/session-source-issuer.ts +164 -0
- package/src/session-source-transport.ts +381 -0
- package/src/session-task-on-dispatch.ts +14 -0
- package/src/session-token-ownership-http.test.ts +122 -0
- package/src/shared/codex-inventory.ts +41 -0
- package/src/shared/daemon-provider-login.ts +31 -0
- package/src/shared/daemon-provider-snapshot.ts +52 -0
- package/src/shared/external-schedule-contract.ts +60 -0
- package/src/shared/node-name.test.ts +62 -0
- package/src/shared/node-name.ts +161 -0
- package/src/shared/probe-host-allowlist-drift.test.ts +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 +144 -0
- package/src/sqlite-close-checkpoint.test.ts +78 -0
- package/src/start-node.test.ts +265 -0
- package/src/start-request-error-domain.test.ts +182 -0
- package/src/start-skill-error-domain.test.ts +122 -0
- package/src/stats-versions-http.test.ts +65 -0
- package/src/status-alias-filter-http.test.ts +106 -0
- package/src/status-alias-resolver-http.test.ts +163 -0
- package/src/status-alias-resolver.ts +19 -0
- package/src/status-node-id-filter-http.test.ts +161 -0
- package/src/status-node-secrets-capable-http.test.ts +44 -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 +407 -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 +512 -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 +298 -0
- package/src/task-expiry-notice.ts +318 -0
- package/src/task-idempotency-mcp.test.ts +148 -0
- package/src/task-idempotency.test.ts +76 -0
- package/src/task-idempotency.ts +81 -0
- package/src/task-late-replies.ts +54 -0
- package/src/task-late-reply-http.test.ts +227 -0
- package/src/task-lifecycle-watcher-busy.test.ts +114 -0
- package/src/task-lifecycle-watcher.test.ts +209 -0
- package/src/task-lifecycle-watcher.ts +109 -0
- package/src/task-network-resolution-http.test.ts +140 -0
- package/src/task-not-found-error-domain.test.ts +117 -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/test-work-root.ts +18 -0
- package/src/tmux-allowlist.test.ts +48 -0
- package/src/token-usage-http.test.ts +156 -0
- package/src/tool-audience-http.test.ts +266 -0
- package/src/tool-audience.ts +130 -0
- package/src/tools-list-json-schema.test.ts +94 -0
- package/src/tools.ts +4557 -472
- package/src/update-node-config-error-domain.test.ts +107 -0
- package/src/uploads-http.test.ts +6 -4
- package/src/uploads.ts +23 -4
- package/src/user-avatar-http.test.ts +74 -0
- package/src/user-avatar-image.ts +160 -0
- package/src/user-avatar-migration.test.ts +25 -0
- package/src/user-avatar-upload-http.test.ts +353 -0
- package/src/user-inbox-by-agent-http.test.ts +189 -0
- package/src/user-inbox-netid-notnull.test.ts +122 -0
- package/src/user-inbox-read-http.test.ts +223 -0
- package/src/user-inbox-schema.test.ts +54 -0
- package/src/version-stats.test.ts +66 -0
- package/src/version-stats.ts +109 -0
|
@@ -0,0 +1,2205 @@
|
|
|
1
|
+
// 需求池。长期卡片,存在 Hub 上,手机和电脑读同一份。
|
|
2
|
+
// 不是 tasks:tasks 是正在派给节点的活,状态由节点收尾。
|
|
3
|
+
import { errorBody, errorFrom, RequirementFieldError, type ErrorContext } from "./requirements-errors.js";
|
|
4
|
+
import { clipSafe } from "./clip.js";
|
|
5
|
+
import { createHash } from "node:crypto";
|
|
6
|
+
import { parsePeopleQuery, peopleDirectory, resolvePersonName } from "./requirements-people.js";
|
|
7
|
+
import { encodeCursor, matchesTaskId, matchesTerms, parseListQuery, type ListQuery, type NameMaps } from "./requirements-search.js";
|
|
8
|
+
import { db, logAudit } from "./db.js";
|
|
9
|
+
import { resolveNodeCaller } from "./create-node.js";
|
|
10
|
+
import { markGzipReusable } from "./http-gzip.js";
|
|
11
|
+
import { applyTagOp, normalizeTags, parseTagOp, storedTags, type TagOp } from "./requirement-tags.js";
|
|
12
|
+
import { buildTagNodes, isDescendant, MAX_TAG_DEPTH, parseCreateTag, TAG_TREE_CAPABILITY, tagDepth, tagSubtreeHeight, type TagNodeRow } from "./requirement-tag-tree.js";
|
|
13
|
+
import { aggregateStats, parseStatsQuery, type StatsRow } from "./requirements-stats.js";
|
|
14
|
+
import { addHumanNetworkScope, canRestWriteNetwork, canRestWriteNetworkAsHuman, resolveRestWriteNetworkId, type RestNetworkScope } from "./network-scope.js";
|
|
15
|
+
import { isAgentRestricted, restrictedNetworkIds, visibleAgents } from "./agent-access.js";
|
|
16
|
+
import { nodeDecide, nodeIdentity, nodePermissionDeniedBody, nodePermissionsFlag, type NodeIdentity, type Verdict } from "./node-permissions.js";
|
|
17
|
+
import {
|
|
18
|
+
addProjectVisibilityScope, addTaskVisibilityScope, canDeleteTask, canEditTask, deletesAsHeadOnly, headOnlyEditScope, canParticipantEditTask, canSeeTask, canUseProject, deleteTaskGrantsForProject, projectUseResolver,
|
|
19
|
+
cardAssignedToNode, isTaskScoped, PARTICIPANT_EDIT_FIELDS, shouldAuditDenied, taskPermissionsResolver, type TaskCaller,
|
|
20
|
+
} from "./task-access.js";
|
|
21
|
+
import { notifyLeaderDeleted, notifyParticipantChange } from "./requirement-notify.js";
|
|
22
|
+
import { departmentCardsFor, departmentSubtree } from "./department-heads.js";
|
|
23
|
+
import { dueReminderTimezone, dueWithinSql, ensureDueReminders, overdueSql } from "./requirement-due-reminders.js";
|
|
24
|
+
import { diffRequirement, ensureRequirementEvents, eventPublic, recordRequirementEvents, type EventRow } from "./requirement-events.js";
|
|
25
|
+
import { ensureNetworkTagNodes, ensureNetworkTags, ensureRequirementCompletedAt, ensureRequirementIndexes, ensureRequirementProjects, ensureRequirementSeq, ensureRequirementTombstones, migrateRequirementAgentOwners, migrateRequirementColumnCheck, migrateRequirementPriorityCheck, nextRequirementSeq } from "./requirements-migrate.js";
|
|
26
|
+
|
|
27
|
+
// 启动迁移:旧库里节点当负责人的卡,节点挪到 agent_owner(列由 db.ts 的加列循环加上)。
|
|
28
|
+
// 放在这里而不是 db.ts:db.ts 每多一行,文档里钉着的行号就漂一次。
|
|
29
|
+
migrateRequirementPriorityCheck(db);
|
|
30
|
+
migrateRequirementColumnCheck(db);
|
|
31
|
+
migrateRequirementAgentOwners(db);
|
|
32
|
+
ensureRequirementProjects(db);
|
|
33
|
+
ensureRequirementIndexes(db);
|
|
34
|
+
ensureRequirementSeq(db);
|
|
35
|
+
ensureRequirementCompletedAt(db);
|
|
36
|
+
ensureNetworkTags(db);
|
|
37
|
+
ensureNetworkTagNodes(db);
|
|
38
|
+
ensureRequirementTombstones(db);
|
|
39
|
+
ensureRequirementEvents(db);
|
|
40
|
+
ensureDueReminders(db);
|
|
41
|
+
|
|
42
|
+
type RequestAuth = { userId: string; networkId: string | null; username: string; tokenId?: string | null; tokenName?: string | null } | null;
|
|
43
|
+
|
|
44
|
+
export type RequirementsRequestContext = {
|
|
45
|
+
req: Request;
|
|
46
|
+
url: URL;
|
|
47
|
+
auth: RequestAuth;
|
|
48
|
+
isAdmin: boolean;
|
|
49
|
+
isNodeToken: boolean;
|
|
50
|
+
scope: RestNetworkScope;
|
|
51
|
+
/**
|
|
52
|
+
* #470 —— 负责人(owner)只收人,传节点一律 400 owner_must_be_human,不走旧 App 的「节点负责人 → 负责 Agent」兼容。
|
|
53
|
+
* MCP 工具(Agent 与人经 MCP 的调用)总是严格:那条兼容只为 App ≤ 0.2.142 的 REST 保存存在,Agent 走它会
|
|
54
|
+
* 静默清空人类负责人(task-lifecycle 测试报告问题 1)。REST 上带 agent_owner 的新客户端也严格(见 assignments)。
|
|
55
|
+
*/
|
|
56
|
+
strictOwner?: boolean;
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
const COLUMNS = new Set(["pool", "doing", "done", "abandoned"]);
|
|
60
|
+
/**
|
|
61
|
+
* 废弃(abandoned):和 done 一样是关闭态 —— 不算开着、不算逾期、不发到期提醒,不记完成时间;能改回 pool / doing。
|
|
62
|
+
* 旧客户端(desktop ≤ 0.2.220)只认 pool / doing / done,不认识的值一律当成 pool(会把废弃的卡摆回需求池、还标逾期)。
|
|
63
|
+
* 所以客户端没声明认识它时,响应里把 abandoned 投影成 done;声明方式二选一:
|
|
64
|
+
* 请求头 `X-Anet-Accept-Columns: abandoned`,或查询参数 `accept_columns=abandoned`。
|
|
65
|
+
* MCP(tools.ts)总是声明。文档:docs-site/docs/api/mcp-tools.md「需求池 / 任务看板」的 column 字段。
|
|
66
|
+
*/
|
|
67
|
+
const ACCEPT_COLUMNS_HEADER = "x-anet-accept-columns";
|
|
68
|
+
function knowsAbandoned(ctx: RequirementsRequestContext): boolean {
|
|
69
|
+
const raw = `${ctx.req.headers.get(ACCEPT_COLUMNS_HEADER) ?? ""},${ctx.url.searchParams.get("accept_columns") ?? ""}`;
|
|
70
|
+
return raw.split(",").some(v => v.trim() === "abandoned");
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* 动态的旧客户端视图:column 改动的 old / new、created 的 new.column 都投影;投影后前后一样(done ↔ abandoned)= null(不回)。
|
|
74
|
+
*/
|
|
75
|
+
function projectEvent<T extends { kind: string; field: string | null; old: unknown; new: unknown }>(ev: T, aware: boolean): T | null {
|
|
76
|
+
if (aware) return ev;
|
|
77
|
+
if (ev.kind === "created" && ev.new && typeof ev.new === "object" && typeof (ev.new as any).column === "string") {
|
|
78
|
+
return { ...ev, new: { ...(ev.new as object), column: projectColumn((ev.new as any).column, false) } };
|
|
79
|
+
}
|
|
80
|
+
if (ev.field !== "column") return ev;
|
|
81
|
+
const old = typeof ev.old === "string" ? projectColumn(ev.old, false) : ev.old;
|
|
82
|
+
const neu = typeof ev.new === "string" ? projectColumn(ev.new, false) : ev.new;
|
|
83
|
+
return old === neu ? null : { ...ev, old, new: neu };
|
|
84
|
+
}
|
|
85
|
+
/** 旧客户端看到的状态:abandoned → done,其余原样。 */
|
|
86
|
+
export function projectColumn(column: string, aware: boolean): string {
|
|
87
|
+
return column === "abandoned" && !aware ? "done" : column;
|
|
88
|
+
}
|
|
89
|
+
// 界面上 P0–P3:high=P0 最高、normal=P1 普通、low=P2 低、lowest=P3 极低。存的值不变,旧客户端照常读写前三个。
|
|
90
|
+
const PRIORITIES = new Set(["high", "normal", "low", "lowest"]);
|
|
91
|
+
const DUE = /^\d{4}-\d{2}-\d{2}$/;
|
|
92
|
+
|
|
93
|
+
type Row = {
|
|
94
|
+
owner_json: string | null;
|
|
95
|
+
agent_owner_json: string | null;
|
|
96
|
+
description: string | null;
|
|
97
|
+
checklist_json: string | null;
|
|
98
|
+
project_id: string | null;
|
|
99
|
+
external_ref: string | null;
|
|
100
|
+
external_url: string | null;
|
|
101
|
+
archived: number | null;
|
|
102
|
+
created_by: string | null;
|
|
103
|
+
created_by_json: string | null;
|
|
104
|
+
updated_by_json: string | null;
|
|
105
|
+
updated_at: string | null;
|
|
106
|
+
parent_id: string | null;
|
|
107
|
+
children_total: number | null;
|
|
108
|
+
children_done: number | null;
|
|
109
|
+
children_abandoned?: number | null;
|
|
110
|
+
participants_json: string;
|
|
111
|
+
requirement_id: string;
|
|
112
|
+
network_id: string;
|
|
113
|
+
title: string;
|
|
114
|
+
column_name: string;
|
|
115
|
+
priority: string;
|
|
116
|
+
due_on: string | null;
|
|
117
|
+
start_on: string | null;
|
|
118
|
+
assignee: string | null;
|
|
119
|
+
issues_json: string | null;
|
|
120
|
+
tags_json: string | null;
|
|
121
|
+
created_at: string;
|
|
122
|
+
seq: number | null;
|
|
123
|
+
completed_at: string | null;
|
|
124
|
+
completed_by_json: string | null;
|
|
125
|
+
completed_at_approx: number | null;
|
|
126
|
+
};
|
|
127
|
+
|
|
128
|
+
// #472:错误码原样,统一补 field / message / hint(requirements-errors.ts,唯一出口)。
|
|
129
|
+
function jsonError(error: string, status: number, ctx?: ErrorContext): Response {
|
|
130
|
+
return Response.json(errorBody(error, ctx), { status });
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// ── 任务的人员权限(RFC-038 §9,判定在 task-access.ts) ──
|
|
134
|
+
// Hub 管理员、没有身份的旧全局令牌:不受任务权限约束(null)。
|
|
135
|
+
// 节点令牌(RFC-041,#487):受限模式 → 按主人的权限且只碰派给它的卡;执行开关为 enforce → 按主人的权限;
|
|
136
|
+
// 其余(默认 log 下的正常 / 只读节点)→ null,与以前一样(只读的写在 nodeTaskGate 里拒)。
|
|
137
|
+
function taskCaller(ctx: RequirementsRequestContext): TaskCaller {
|
|
138
|
+
if (!ctx.auth || ctx.isAdmin) return null;
|
|
139
|
+
if (ctx.isNodeToken) return nodeTaskCaller(ctx);
|
|
140
|
+
return { userId: ctx.auth.userId };
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
const nodeIdentities = new WeakMap<RequirementsRequestContext, NodeIdentity | null>();
|
|
144
|
+
function nodeIdent(ctx: RequirementsRequestContext): NodeIdentity | null {
|
|
145
|
+
if (!ctx.isNodeToken) return null;
|
|
146
|
+
if (!nodeIdentities.has(ctx)) nodeIdentities.set(ctx, nodeIdentity(ctx.auth?.tokenId, ctx.auth?.networkId));
|
|
147
|
+
return nodeIdentities.get(ctx) ?? null;
|
|
148
|
+
}
|
|
149
|
+
function nodeTaskCaller(ctx: RequirementsRequestContext): TaskCaller {
|
|
150
|
+
const id = nodeIdent(ctx);
|
|
151
|
+
if (!id?.ownerUserId) return null;
|
|
152
|
+
if (id.mode === "restricted") return { userId: id.ownerUserId, node: { id: id.logKey, only: true } };
|
|
153
|
+
if (nodePermissionsFlag() === "enforce") return { userId: id.ownerUserId, node: { id: id.logKey, only: false } };
|
|
154
|
+
return null;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* RFC-041 —— 节点的一次任务写(建 / 改 / 勾检查项 / 评论 / upsert)先过这里。row=null 是新建(create 给出目标项目、
|
|
159
|
+
* 负责 Agent、父卡)。只读 → 必拒;受限 → 不是派给它的必拒;正常 → 主人看不见 / 改不了时按开关记录或拒。
|
|
160
|
+
*/
|
|
161
|
+
function nodeTaskGate(ctx: RequirementsRequestContext, route: string, row: Row | null, create?: { networkId: string; projectId: string | null; agentOwnerJson: string | null; parentId: string | null }): Response | null {
|
|
162
|
+
const id = nodeIdent(ctx);
|
|
163
|
+
if (!id) return null;
|
|
164
|
+
const sample = row ? `#${row.seq ?? "?"} ${row.requirement_id}` : create?.projectId ?? undefined;
|
|
165
|
+
let verdict: Verdict = null;
|
|
166
|
+
if (id.mode === "readonly") verdict = { reason: "mode_readonly", sample };
|
|
167
|
+
else if (id.mode === "restricted") {
|
|
168
|
+
const nodeRef = JSON.stringify({ kind: "node", id: id.logKey });
|
|
169
|
+
const parent = create?.parentId ? db.get<Row>(`SELECT ${SELECT} FROM requirements WHERE requirement_id = ?1`, create.parentId) : undefined;
|
|
170
|
+
const assigned = row ? cardAssignedToNode(row, id.logKey) : create?.agentOwnerJson === nodeRef || (!!parent && cardAssignedToNode(parent, id.logKey));
|
|
171
|
+
if (!assigned) verdict = { reason: "mode_restricted_not_assigned", sample };
|
|
172
|
+
} else if (!id.ownerUserId) verdict = { reason: "owner_unknown", sample };
|
|
173
|
+
else {
|
|
174
|
+
const asOwner: TaskCaller = { userId: id.ownerUserId, node: { id: id.logKey, only: false } };
|
|
175
|
+
const ok = row ? canSeeTask(asOwner, row) && canEditTask(asOwner, row) : canUseProject(asOwner, create!.networkId, create!.projectId);
|
|
176
|
+
if (!ok) verdict = { reason: "beyond_owner_visibility", sample };
|
|
177
|
+
}
|
|
178
|
+
return nodeDecide(id, route, verdict) ? Response.json(nodePermissionDeniedBody(verdict!.reason, route), { status: 403 }) : null;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** 正常模式的节点读到了主人看不见的卡:只记录(执行时 taskCaller 已按主人收窄,读不到)。主人不受任务范围限制时什么都不做。 */
|
|
182
|
+
function nodeReadNote(ctx: RequirementsRequestContext, route: string, row: Row | null): void {
|
|
183
|
+
const id = nodeIdent(ctx);
|
|
184
|
+
if (!id?.ownerUserId || id.mode === "restricted" || nodePermissionsFlag() !== "log" || !isTaskScoped(id.ownerUserId, id.networkId)) return;
|
|
185
|
+
const asOwner: TaskCaller = { userId: id.ownerUserId };
|
|
186
|
+
if (row) {
|
|
187
|
+
if (!canSeeTask(asOwner, row)) nodeDecide(id, route, { reason: "beyond_owner_visibility", sample: `#${row.seq ?? "?"} ${row.requirement_id}` });
|
|
188
|
+
return;
|
|
189
|
+
}
|
|
190
|
+
const all = Number(db.get<{ n: number | string }>("SELECT COUNT(*) AS n FROM requirements WHERE network_id = ?1", id.networkId)?.n ?? 0);
|
|
191
|
+
const params: unknown[] = [id.networkId];
|
|
192
|
+
const seen = Number(db.get<{ n: number | string }>(addTaskVisibilityScope("SELECT COUNT(*) AS n FROM requirements WHERE network_id = ?1", params, asOwner), ...params)?.n ?? 0);
|
|
193
|
+
if (all > seen) nodeDecide(id, route, { reason: "beyond_owner_visibility", sample: `list: ${all - seen} card(s) the owner cannot see` });
|
|
194
|
+
}
|
|
195
|
+
/**
|
|
196
|
+
* 看得见但没权限写:403,并按 (用户, 卡) 每小时最多记一条审计。
|
|
197
|
+
* field:参与人改了参与人不能改的字段 —— 错误码不变(旧 App 照旧认 task_read_only),多带 field + 一句中文 message。
|
|
198
|
+
*/
|
|
199
|
+
function taskDenied(ctx: RequirementsRequestContext, row: Row, error: "task_read_only" | "task_delete_denied", field?: string): Response {
|
|
200
|
+
if (ctx.auth && shouldAuditDenied(ctx.auth.userId, row.requirement_id)) {
|
|
201
|
+
logAudit(ctx.auth.userId, ctx.auth.username || null, "task_access_denied", "requirement", row.requirement_id, JSON.stringify(field ? { error, field } : { error }), undefined, row.network_id);
|
|
202
|
+
}
|
|
203
|
+
if (!field) return jsonError(error, 403);
|
|
204
|
+
return Response.json({ ok: false, error, field, message: `参与人只能修改状态和检查项,不能修改「${FIELD_LABEL[field] ?? field}」` }, { status: 403 });
|
|
205
|
+
}
|
|
206
|
+
const FIELD_LABEL: Record<string, string> = {
|
|
207
|
+
name: "标题", description: "描述", owner: "负责人", agent_owner: "负责 Agent", participants: "参与人", project_id: "项目",
|
|
208
|
+
priority: "优先级", due: "预计完成", start: "开始时间", tags: "标签", issues: "关联 issue", assignee: "执行人",
|
|
209
|
+
external_ref: "外部引用", external_url: "外部链接", archived: "归档", parent_id: "父任务",
|
|
210
|
+
};
|
|
211
|
+
/** 参与人改完(事务提交后)发通知;操作者不是参与人 / 状态和检查项没变 → 不发。只对人(用户令牌)。 */
|
|
212
|
+
function notifyIfParticipant(ctx: RequirementsRequestContext, before: Row, after: Row): void {
|
|
213
|
+
if (!ctx.auth || ctx.isNodeToken) return;
|
|
214
|
+
try {
|
|
215
|
+
notifyParticipantChange({ before, after, actorUserId: ctx.auth.userId });
|
|
216
|
+
} catch (e) {
|
|
217
|
+
// 通知失败不影响这次改动(已经提交)。
|
|
218
|
+
console.error(`[requirements] participant notice failed: ${(e as Error).message}`);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
/** 父卡对调用者不可见 = 与不存在同一个错误(不给 scoped 成员留卡片存在性探测)。 */
|
|
222
|
+
function parentHidden(ctx: RequirementsRequestContext, parentId: string): boolean {
|
|
223
|
+
const caller = taskCaller(ctx);
|
|
224
|
+
if (!caller) return false;
|
|
225
|
+
const parent = db.get<Row>(`SELECT ${SELECT} FROM requirements WHERE requirement_id = ?1`, parentId);
|
|
226
|
+
return !!parent && !canSeeTask(caller, parent);
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
function dueOk(due: string): boolean {
|
|
230
|
+
if (!DUE.test(due)) return false;
|
|
231
|
+
const [y, m, d] = due.split("-").map(Number);
|
|
232
|
+
const dt = new Date(Date.UTC(y, m - 1, d));
|
|
233
|
+
return dt.getUTCFullYear() === y && dt.getUTCMonth() === m - 1 && dt.getUTCDate() === d;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
// 预计完成:两种形状都收。
|
|
237
|
+
// YYYY-MM-DD 全天(旧值原样保存、原样返回;客户端按查看者本地时区的那一天理解)
|
|
238
|
+
// YYYY-MM-DDTHH:MM[:SS][.fff](Z|±HH:MM) 精确到秒的时刻 → 统一存成 UTC「YYYY-MM-DDTHH:MM:SSZ」
|
|
239
|
+
// 不带时区的时刻拒收(无法知道是谁的本地时间)。返回 null = 不合法。
|
|
240
|
+
const DUE_DATETIME = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::(\d{2}))?(?:\.\d{1,9})?(Z|[+-](\d{2}):(\d{2}))$/;
|
|
241
|
+
export function normalizeDue(raw: string): string | null {
|
|
242
|
+
const due = raw.trim();
|
|
243
|
+
if (!due) return "";
|
|
244
|
+
if (dueOk(due)) return due;
|
|
245
|
+
const m = DUE_DATETIME.exec(due);
|
|
246
|
+
if (!m) return null;
|
|
247
|
+
if (!dueOk(`${m[1]}-${m[2]}-${m[3]}`)) return null;
|
|
248
|
+
const [hh, mm, ss] = [Number(m[4]), Number(m[5]), Number(m[6] ?? 0)];
|
|
249
|
+
if (hh > 23 || mm > 59 || ss > 59) return null;
|
|
250
|
+
if (m[7] !== "Z" && (Number(m[8]) > 14 || Number(m[9]) > 59)) return null;
|
|
251
|
+
const ms = Date.parse(due);
|
|
252
|
+
if (!Number.isFinite(ms)) return null;
|
|
253
|
+
return new Date(Math.floor(ms / 1000) * 1000).toISOString().replace(/\.\d{3}Z$/, "Z");
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
const REPO = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;
|
|
257
|
+
const ISSUE_URL = /^https:\/\/github\.com\/([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)\/issues\/(\d+)\/?$/;
|
|
258
|
+
|
|
259
|
+
function clipTitle(value: unknown): string {
|
|
260
|
+
// 120 是**渲染上限**;clipSafe 保证截断不产生孤立代理(否则该标题在 JSON 里「合法」、在 UTF-8 里非法)
|
|
261
|
+
return typeof value === "string" ? clipSafe(value.replace(/[\r\n\t]/g, " ").trim(), 120) : "";
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
function issueFromParts(repo: string, number: number, title: string) {
|
|
265
|
+
if (!REPO.test(repo) || !Number.isInteger(number) || number < 1 || number > 10_000_000) return null;
|
|
266
|
+
return { repo, number, title: clipTitle(title) };
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
function oneIssue(item: unknown) {
|
|
270
|
+
if (typeof item === "string") {
|
|
271
|
+
const m = ISSUE_URL.exec(item.trim());
|
|
272
|
+
return m ? issueFromParts(`${m[1]}/${m[2]}`, Number(m[3]), "") : null;
|
|
273
|
+
}
|
|
274
|
+
if (!item || typeof item !== "object") return null;
|
|
275
|
+
const row = item as Record<string, unknown>;
|
|
276
|
+
if (typeof row.url === "string") {
|
|
277
|
+
const m = ISSUE_URL.exec(row.url.trim());
|
|
278
|
+
if (m) return issueFromParts(`${m[1]}/${m[2]}`, Number(m[3]), clipTitle(row.title));
|
|
279
|
+
}
|
|
280
|
+
const repo = typeof row.repo === "string" ? row.repo.trim() : "";
|
|
281
|
+
const number = typeof row.number === "number" ? row.number : Number(row.number);
|
|
282
|
+
return issueFromParts(repo, number, clipTitle(row.title));
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
function normalizeIssues(raw: unknown) {
|
|
286
|
+
if (!Array.isArray(raw) || raw.length > 8) return null;
|
|
287
|
+
const out: { repo: string; number: number; title: string }[] = [];
|
|
288
|
+
const seen = new Set<string>();
|
|
289
|
+
for (const item of raw) {
|
|
290
|
+
const issue = oneIssue(item);
|
|
291
|
+
if (!issue) return null;
|
|
292
|
+
const key = `${issue.repo}#${issue.number}`;
|
|
293
|
+
if (seen.has(key)) continue;
|
|
294
|
+
seen.add(key);
|
|
295
|
+
out.push(issue);
|
|
296
|
+
}
|
|
297
|
+
return out;
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
function storedIssues(raw: string | null) {
|
|
301
|
+
if (!raw) return [];
|
|
302
|
+
try {
|
|
303
|
+
const parsed = normalizeIssues(JSON.parse(raw));
|
|
304
|
+
return parsed ?? [];
|
|
305
|
+
} catch {
|
|
306
|
+
return [];
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
// ── 描述 / 子任务 ──
|
|
311
|
+
// 描述是 markdown 原文,整段替换。子任务是有序数组 [{id,text,done}]:PATCH 整个替换(排序、增删都走这里),
|
|
312
|
+
// 单项勾选走 PATCH /api/requirements/{id}/checklist/{itemId} {done} —— 只改那一项,app 和 Agent 同时操作
|
|
313
|
+
// 不会互相盖掉对方的整张清单。done 是显式值(不是「取反」),重复请求结果一样。
|
|
314
|
+
export const DESCRIPTION_MAX = 20_000;
|
|
315
|
+
export const CHECKLIST_MAX_ITEMS = 100;
|
|
316
|
+
export const CHECKLIST_TEXT_MAX = 500;
|
|
317
|
+
const CHECKLIST_ID = /^[A-Za-z0-9_-]{1,40}$/;
|
|
318
|
+
type ChecklistItem = { id: string; text: string; done: boolean };
|
|
319
|
+
|
|
320
|
+
function normalizeDescription(raw: unknown): string | null {
|
|
321
|
+
if (typeof raw !== "string") return null;
|
|
322
|
+
const text = raw.replace(/\r\n?/g, "\n");
|
|
323
|
+
return text.length > DESCRIPTION_MAX ? null : text;
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/** 输入的 id 保留(客户端要靠它对上勾选);缺 id 的由 Hub 生成。重复 id、空文字、超长 → null(整体拒绝)。 */
|
|
327
|
+
function normalizeChecklist(raw: unknown): ChecklistItem[] | null {
|
|
328
|
+
if (!Array.isArray(raw) || raw.length > CHECKLIST_MAX_ITEMS) return null;
|
|
329
|
+
const seen = new Set<string>();
|
|
330
|
+
const out: ChecklistItem[] = [];
|
|
331
|
+
for (const value of raw) {
|
|
332
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
|
|
333
|
+
const item = value as Record<string, unknown>;
|
|
334
|
+
const id = item.id === undefined ? `ck_${crypto.randomUUID().replace(/-/g, "").slice(0, 16)}` : item.id;
|
|
335
|
+
if (typeof id !== "string" || !CHECKLIST_ID.test(id) || seen.has(id)) return null;
|
|
336
|
+
const text = typeof item.text === "string" ? item.text.replace(/[\r\n]+/g, " ").trim() : "";
|
|
337
|
+
if (!text || text.length > CHECKLIST_TEXT_MAX) return null;
|
|
338
|
+
if (item.done !== undefined && typeof item.done !== "boolean") return null;
|
|
339
|
+
seen.add(id);
|
|
340
|
+
out.push({ id, text, done: item.done === true });
|
|
341
|
+
}
|
|
342
|
+
return out;
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
function storedChecklist(raw: string | null): ChecklistItem[] {
|
|
346
|
+
if (!raw) return [];
|
|
347
|
+
try { return normalizeChecklist(JSON.parse(raw)) ?? []; } catch { return []; }
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
// ── 项目 ──
|
|
351
|
+
// 按网络隔离;名字 1–40 字,同一网络里未归档的项目不重名;颜色 #RRGGBB;sort 越小越靠前。
|
|
352
|
+
// 删除 = 删项目行 + 把引用它的卡片 project_id 置空(卡片本身不动);归档 = 保留引用,只是不能再被选。
|
|
353
|
+
type ProjectRow = { project_id: string; network_id: string; name: string; color: string; sort: number; archived: number; created_at: string; parent_id: string | null };
|
|
354
|
+
const PROJECT_COLOR = /^#[0-9a-fA-F]{6}$/;
|
|
355
|
+
const PROJECT_PALETTE = ["#2563eb", "#16a34a", "#d97706", "#dc2626", "#7c3aed", "#0891b2", "#db2777", "#4b5563"];
|
|
356
|
+
const PROJECT_SELECT = "project_id, network_id, name, color, sort, archived, created_at, parent_id";
|
|
357
|
+
/** 子项目最多 3 层(顶层=1)。再深的话「项目」这个词就没有意义了,也没人能在选择器里点对。 */
|
|
358
|
+
const PROJECT_MAX_DEPTH = 3;
|
|
359
|
+
const projectPublic = (row: ProjectRow) => ({ id: row.project_id, name: row.name, color: row.color, sort: row.sort, archived: !!row.archived, createdAt: row.created_at, parentId: row.parent_id ?? null });
|
|
360
|
+
const projectName = (raw: unknown): string | null => {
|
|
361
|
+
if (typeof raw !== "string") return null;
|
|
362
|
+
const name = raw.replace(/[\r\n\t]+/g, " ").trim();
|
|
363
|
+
return name && name.length <= 40 ? name : null;
|
|
364
|
+
};
|
|
365
|
+
function projectNameTaken(networkId: string, name: string, except?: string): boolean {
|
|
366
|
+
return !!db.get("SELECT 1 FROM requirement_projects WHERE network_id = ?1 AND name = ?2 AND archived = 0 AND project_id != ?3", networkId, name, except ?? "");
|
|
367
|
+
}
|
|
368
|
+
/** 这个项目往上数有几层(自己算第一层)。用于深度上限与环路判断。 */
|
|
369
|
+
function projectDepth(projectId: string): number {
|
|
370
|
+
let depth = 0;
|
|
371
|
+
let cur: string | null = projectId;
|
|
372
|
+
const seen = new Set<string>();
|
|
373
|
+
while (cur && depth < 64) {
|
|
374
|
+
if (seen.has(cur)) return Number.POSITIVE_INFINITY; // 循环:当成超深,调用方会拒绝
|
|
375
|
+
seen.add(cur);
|
|
376
|
+
depth++;
|
|
377
|
+
const row: { parent_id: string | null } | null = db.get("SELECT parent_id FROM requirement_projects WHERE project_id = ?1", cur);
|
|
378
|
+
cur = row?.parent_id ?? null;
|
|
379
|
+
}
|
|
380
|
+
return depth;
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
/**
|
|
384
|
+
* 校验 parent_id(新项目或搬家时)。返回 { parent } 或错误码。
|
|
385
|
+
* 规则:同一网络、存在、未归档、不是自己或自己的后代、加进来后不超过 PROJECT_MAX_DEPTH。
|
|
386
|
+
*/
|
|
387
|
+
function validateProjectParent(
|
|
388
|
+
networkId: string, parentId: string, selfId: string | null,
|
|
389
|
+
): { ok: true; parent: ProjectRow } | { ok: false; error: string } {
|
|
390
|
+
const parent = db.get<ProjectRow>(`SELECT ${PROJECT_SELECT} FROM requirement_projects WHERE project_id = ?1`, parentId);
|
|
391
|
+
if (!parent || parent.network_id !== networkId) return { ok: false, error: "project_parent_not_found" };
|
|
392
|
+
if (parent.archived) return { ok: false, error: "project_parent_archived" };
|
|
393
|
+
if (selfId) {
|
|
394
|
+
if (parent.project_id === selfId) return { ok: false, error: "project_parent_cycle" };
|
|
395
|
+
// 把 A 挂到 A 的后代下面 = 环。沿 parent 链往上走,遇到自己就拒绝。
|
|
396
|
+
let cur: string | null = parent.parent_id ?? null;
|
|
397
|
+
const seen = new Set<string>();
|
|
398
|
+
while (cur && !seen.has(cur)) {
|
|
399
|
+
if (cur === selfId) return { ok: false, error: "project_parent_cycle" };
|
|
400
|
+
seen.add(cur);
|
|
401
|
+
cur = db.get<{ parent_id: string | null }>("SELECT parent_id FROM requirement_projects WHERE project_id = ?1", cur)?.parent_id ?? null;
|
|
402
|
+
}
|
|
403
|
+
if (projectDepth(selfId) + projectDepth(parent.project_id) > PROJECT_MAX_DEPTH) {
|
|
404
|
+
return { ok: false, error: "project_parent_too_deep" };
|
|
405
|
+
}
|
|
406
|
+
} else if (projectDepth(parent.project_id) + 1 > PROJECT_MAX_DEPTH) {
|
|
407
|
+
return { ok: false, error: "project_parent_too_deep" };
|
|
408
|
+
}
|
|
409
|
+
return { ok: true, parent };
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
/** 卡片上的 project_id:null 清空;字符串必须是同一网络、未归档的项目。 */
|
|
413
|
+
function projectRef(value: unknown, networkId: string): string | null {
|
|
414
|
+
if (value === null) return null;
|
|
415
|
+
if (typeof value !== "string" || !value) throw new RequirementFieldError("invalid_project", "project_id", value);
|
|
416
|
+
const row = db.get<ProjectRow>(`SELECT ${PROJECT_SELECT} FROM requirement_projects WHERE project_id = ?1`, value);
|
|
417
|
+
if (!row || row.network_id !== networkId) throw new RequirementFieldError("project_not_in_network", "project_id", value);
|
|
418
|
+
if (row.archived) throw new RequirementFieldError("project_archived", "project_id", value);
|
|
419
|
+
return row.project_id;
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
async function handleProjects(ctx: RequirementsRequestContext): Promise<Response> {
|
|
423
|
+
const { req, url } = ctx;
|
|
424
|
+
const networkId = resolveRestWriteNetworkId(ctx.scope, ctx.auth, ctx.isAdmin);
|
|
425
|
+
if (!networkId) return jsonError("network_id_required", 400);
|
|
426
|
+
const one = url.pathname.match(/^\/api\/requirements\/projects\/([^/]+)$/);
|
|
427
|
+
if (url.pathname === "/api/requirements/projects" && req.method === "GET") {
|
|
428
|
+
// scoped 成员只列授权给自己的项目(RFC-038 §9.3)。
|
|
429
|
+
const projectParams: unknown[] = [networkId];
|
|
430
|
+
const projectSql = addProjectVisibilityScope(`SELECT ${PROJECT_SELECT} FROM requirement_projects WHERE network_id = ?1`, projectParams, taskCaller(ctx), networkId);
|
|
431
|
+
const rows = db.all<ProjectRow>(`${projectSql} ORDER BY sort, created_at`, ...projectParams);
|
|
432
|
+
// viewer_can.edit:调用者能不能把卡建进 / 挪进这个项目 —— 与 POST / PATCH 卡片同一套判据
|
|
433
|
+
// (canWrite + projectRef 拒归档 + canUseProject)。只加字段;客户端据此只列能编辑的项目(app 任务页审计 L13)。
|
|
434
|
+
const writable = canWrite(ctx, networkId);
|
|
435
|
+
const canUse = projectUseResolver(taskCaller(ctx), networkId);
|
|
436
|
+
// #2899 —— 回显**实际使用的** network_id。
|
|
437
|
+
//
|
|
438
|
+
// 现场(2026-10-30,两个独立复核):
|
|
439
|
+
// ① 用户令牌 + 非成员 network_id → 200 + 空数组
|
|
440
|
+
// ② 用户令牌属于多网络、不带 network_id → 400 network_id_required(这才是当时那个 400)
|
|
441
|
+
// ③ 网络作用域节点令牌 + 任意 network_id → 200 + **它自己网络的数据**
|
|
442
|
+
// 三条共同点:响应码不携带「你问的是不是这个网络」。
|
|
443
|
+
// ③ 尤其危险 —— 客户端以为在看 A 的项目,实际拿到的是 B 的(自己的)。
|
|
444
|
+
//
|
|
445
|
+
// 只加一个回显字段:不改鉴权、不改返回内容、不引入新的 4xx。
|
|
446
|
+
// 调用方(dashboard / MCP)可以据此判定「拿到的到底是谁的网络」。
|
|
447
|
+
return Response.json({
|
|
448
|
+
ok: true,
|
|
449
|
+
network_id: networkId,
|
|
450
|
+
projects: rows.map((row) => ({ ...projectPublic(row), viewer_can: { edit: writable && !row.archived && canUse(row.project_id) } })),
|
|
451
|
+
});
|
|
452
|
+
}
|
|
453
|
+
if (!canWrite(ctx, networkId)) return jsonError("permission_denied", 403);
|
|
454
|
+
// 项目管理(建 / 改名 / 归档 / 删)只给不受任务范围限制的人。
|
|
455
|
+
if (taskCaller(ctx) && isTaskScoped(ctx.auth!.userId, networkId)) return jsonError("permission_denied", 403);
|
|
456
|
+
let body: Record<string, unknown> = {};
|
|
457
|
+
if (req.method === "POST" || req.method === "PATCH") {
|
|
458
|
+
try { body = await bodyObject(req); } catch { return jsonError("invalid_json", 400); }
|
|
459
|
+
}
|
|
460
|
+
if (url.pathname === "/api/requirements/projects" && req.method === "POST") {
|
|
461
|
+
const name = projectName(body.name);
|
|
462
|
+
if (!name) return jsonError("invalid_project_name", 400);
|
|
463
|
+
if (projectNameTaken(networkId, name)) return jsonError("project_name_taken", 409);
|
|
464
|
+
const count = db.get<{ n: number }>("SELECT COUNT(*) AS n FROM requirement_projects WHERE network_id = ?1", networkId)?.n ?? 0;
|
|
465
|
+
if (count >= 200) return jsonError("too_many_projects", 400);
|
|
466
|
+
const color = body.color === undefined ? PROJECT_PALETTE[count % PROJECT_PALETTE.length] : body.color;
|
|
467
|
+
if (typeof color !== "string" || !PROJECT_COLOR.test(color)) return jsonError("invalid_project_color", 400);
|
|
468
|
+
const sort = body.sort === undefined ? count : body.sort;
|
|
469
|
+
if (!Number.isInteger(sort)) return jsonError("invalid_project_sort", 400);
|
|
470
|
+
const id = `proj_${crypto.randomUUID()}`;
|
|
471
|
+
// 子项目:parent_id 可选;null/缺省 = 顶层。
|
|
472
|
+
let parentId: string | null = null;
|
|
473
|
+
if (body.parent_id !== undefined && body.parent_id !== null && body.parent_id !== "") {
|
|
474
|
+
if (typeof body.parent_id !== "string") return jsonError("invalid_project_parent", 400);
|
|
475
|
+
const check = validateProjectParent(networkId, body.parent_id, null);
|
|
476
|
+
if (!check.ok) return jsonError(check.error, check.error === "project_parent_not_found" ? 404 : 400);
|
|
477
|
+
parentId = check.parent.project_id;
|
|
478
|
+
}
|
|
479
|
+
db.run(`INSERT INTO requirement_projects (${PROJECT_SELECT}) VALUES (?1, ?2, ?3, ?4, ?5, 0, ?6, ?7)`, [id, networkId, name, color, sort, new Date().toISOString(), parentId]);
|
|
480
|
+
return Response.json({ ok: true, project: projectPublic(db.get<ProjectRow>(`SELECT ${PROJECT_SELECT} FROM requirement_projects WHERE project_id = ?1`, id)!) }, { status: 201 });
|
|
481
|
+
}
|
|
482
|
+
if (!one) return jsonError("not_found", 404);
|
|
483
|
+
const current = db.get<ProjectRow>(`SELECT ${PROJECT_SELECT} FROM requirement_projects WHERE project_id = ?1`, decodeURIComponent(one[1]));
|
|
484
|
+
if (!current || current.network_id !== networkId) return jsonError("project_not_found", 404);
|
|
485
|
+
if (req.method === "DELETE") {
|
|
486
|
+
// 子项目不能凭空变孤儿:先搬走或删掉它们(明确拒绝,不偷偷改层级)。
|
|
487
|
+
const kids = db.get<{ n: number }>("SELECT COUNT(*) AS n FROM requirement_projects WHERE parent_id = ?1", current.project_id)?.n ?? 0;
|
|
488
|
+
if (kids > 0) return jsonError("project_has_children", 409);
|
|
489
|
+
// 先把卡片上的引用置空,再删项目:卡片一张不少。
|
|
490
|
+
// updated_at 跟着动:按 updated_since 增量同步的客户端要看得见「项目被清空」这一改动。
|
|
491
|
+
// 每张被清空项目的卡记一条「项目 X → 无」(与清空同一个事务)。
|
|
492
|
+
const at = new Date().toISOString();
|
|
493
|
+
const actor = JSON.stringify(actorOf(ctx));
|
|
494
|
+
db.transaction(() => {
|
|
495
|
+
const cards = db.all<{ requirement_id: string; network_id: string; seq: number | null; title: string }>("SELECT requirement_id, network_id, seq, title FROM requirements WHERE project_id = ?1", current.project_id);
|
|
496
|
+
db.run("UPDATE requirements SET project_id = NULL, updated_at = ?2 WHERE project_id = ?1", [current.project_id, at]);
|
|
497
|
+
for (const card of cards) recordRequirementEvents(db, card, actor, [{ kind: "changed", field: "project", old: current.project_id, new: null }], at);
|
|
498
|
+
db.run("DELETE FROM requirement_projects WHERE project_id = ?1", [current.project_id]);
|
|
499
|
+
});
|
|
500
|
+
deleteTaskGrantsForProject(current.project_id);
|
|
501
|
+
return Response.json({ ok: true });
|
|
502
|
+
}
|
|
503
|
+
if (req.method !== "PATCH") return jsonError("not_found", 404);
|
|
504
|
+
let { name, color, sort, archived } = current;
|
|
505
|
+
if ("name" in body) {
|
|
506
|
+
const next = projectName(body.name);
|
|
507
|
+
if (!next) return jsonError("invalid_project_name", 400);
|
|
508
|
+
name = next;
|
|
509
|
+
}
|
|
510
|
+
if ("color" in body) {
|
|
511
|
+
if (typeof body.color !== "string" || !PROJECT_COLOR.test(body.color)) return jsonError("invalid_project_color", 400);
|
|
512
|
+
color = body.color;
|
|
513
|
+
}
|
|
514
|
+
if ("sort" in body) {
|
|
515
|
+
if (!Number.isInteger(body.sort)) return jsonError("invalid_project_sort", 400);
|
|
516
|
+
sort = body.sort as number;
|
|
517
|
+
}
|
|
518
|
+
if ("archived" in body) {
|
|
519
|
+
if (typeof body.archived !== "boolean") return jsonError("invalid_project_archived", 400);
|
|
520
|
+
archived = body.archived ? 1 : 0;
|
|
521
|
+
}
|
|
522
|
+
let parentId: string | null = current.parent_id ?? null;
|
|
523
|
+
if ("parent_id" in body) {
|
|
524
|
+
if (body.parent_id === null || body.parent_id === "") {
|
|
525
|
+
parentId = null; // 变成顶层
|
|
526
|
+
} else if (typeof body.parent_id !== "string") {
|
|
527
|
+
return jsonError("invalid_project_parent", 400);
|
|
528
|
+
} else {
|
|
529
|
+
const check = validateProjectParent(networkId, body.parent_id, current.project_id);
|
|
530
|
+
if (!check.ok) return jsonError(check.error, check.error === "project_parent_not_found" ? 404 : 400);
|
|
531
|
+
parentId = check.parent.project_id;
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
if (!archived && projectNameTaken(networkId, name, current.project_id)) return jsonError("project_name_taken", 409);
|
|
535
|
+
db.run("UPDATE requirement_projects SET name = ?1, color = ?2, sort = ?3, archived = ?4, parent_id = ?6 WHERE project_id = ?5", [name, color, sort, archived, current.project_id, parentId]);
|
|
536
|
+
return Response.json({ ok: true, project: projectPublic(db.get<ProjectRow>(`SELECT ${PROJECT_SELECT} FROM requirement_projects WHERE project_id = ?1`, current.project_id)!) });
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
// ── 标签管理(RFC-038 §9 的取舍:同项目管理) ──
|
|
540
|
+
// 改名 / 合并 / 删除要改写网络里**每一张**带这个标签的卡,包括调用者看不见的;所以只给不受任务范围限制的人
|
|
541
|
+
// (网络 owner / 管理员 / task_access='all' 的成员),scoped 成员一律 403 —— 不做「只改我看得见的那几张」:
|
|
542
|
+
// 那样同一个标签会被拆成两半,而且改动条数会泄露看不见的卡有几张。节点令牌在入口已被拒(tags_write)。
|
|
543
|
+
function canManageTags(ctx: RequirementsRequestContext, networkId: string): boolean {
|
|
544
|
+
if (ctx.isNodeToken || !canWrite(ctx, networkId)) return false;
|
|
545
|
+
return !(taskCaller(ctx) && isTaskScoped(ctx.auth!.userId, networkId));
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
async function handleTagOp(ctx: RequirementsRequestContext): Promise<Response> {
|
|
549
|
+
const networkId = resolveRestWriteNetworkId(ctx.scope, ctx.auth, ctx.isAdmin);
|
|
550
|
+
if (!networkId) return jsonError("network_id_required", 400);
|
|
551
|
+
if (!canManageTags(ctx, networkId)) return jsonError("permission_denied", 403);
|
|
552
|
+
let body: Record<string, unknown>;
|
|
553
|
+
try { body = await bodyObject(ctx.req); } catch { return jsonError("invalid_json", 400); }
|
|
554
|
+
const op = parseTagOp(body);
|
|
555
|
+
if ("error" in op) return jsonError(op.error, 400);
|
|
556
|
+
const now = new Date().toISOString();
|
|
557
|
+
const actor = JSON.stringify(actorOf(ctx));
|
|
558
|
+
// 读-改-写整个网络的标签在一个事务里:中途失败一张都不改;颜色表跟着一起挪。
|
|
559
|
+
const result = db.transaction(() => {
|
|
560
|
+
const cards = db.all<{ requirement_id: string; network_id: string; seq: number | null; title: string; tags_json: string | null }>(
|
|
561
|
+
"SELECT requirement_id, network_id, seq, title, tags_json FROM requirements WHERE network_id = ?1 AND tags_json IS NOT NULL AND tags_json <> '[]'", networkId,
|
|
562
|
+
);
|
|
563
|
+
const colorOf = (name: string) => db.get<{ color: string }>("SELECT color FROM network_tags WHERE network_id = ?1 AND name = ?2", networkId, name)?.color ?? null;
|
|
564
|
+
const sources = op.op === "rename" ? [op.from] : op.op === "merge" ? op.from : [op.tag];
|
|
565
|
+
// 「存在」= 有卡片在用 / 有颜色行 / 是登记过的树节点。最后一种让 0 任务的标签也能改名、合并、删除、上色。
|
|
566
|
+
const nodeExists = (name: string) => !!db.get<{ x: number }>("SELECT 1 AS x FROM network_tag_nodes WHERE network_id = ?1 AND name = ?2", networkId, name);
|
|
567
|
+
// 「存在」的三种形态(卡片在用 / 有颜色行 / 登记过的树节点),reparent 判父存在时用的是同一个口径。
|
|
568
|
+
const tagExists = (name: string) => cards.some(card => storedTags(card.tags_json).includes(name)) || colorOf(name) !== null || nodeExists(name);
|
|
569
|
+
const known = sources.some(tagExists);
|
|
570
|
+
if (!known) return null;
|
|
571
|
+
if (op.op === "color") {
|
|
572
|
+
if (op.color === null) db.run("DELETE FROM network_tags WHERE network_id = ?1 AND name = ?2", [networkId, op.tag]);
|
|
573
|
+
else db.run("INSERT INTO network_tags (network_id, name, color, updated_at) VALUES (?1, ?2, ?3, ?4) ON CONFLICT (network_id, name) DO UPDATE SET color = excluded.color, updated_at = excluded.updated_at", [networkId, op.tag, op.color, now]);
|
|
574
|
+
return { affected: 0 };
|
|
575
|
+
}
|
|
576
|
+
// 改父级:只动标签树,不动任何卡片(标签仍然是卡片 tags_json 里的字符串)。
|
|
577
|
+
// 三条规则都明确拒绝而不是静默纠正:父必须存在、不许成环、搬完最深不超过 MAX_TAG_DEPTH。
|
|
578
|
+
if (op.op === "reparent") {
|
|
579
|
+
const nodes = db.all<TagNodeRow>("SELECT name, parent_name FROM network_tag_nodes WHERE network_id = ?1", networkId);
|
|
580
|
+
const parentOf = new Map(nodes.map(row => [row.name, row.parent_name ?? null]));
|
|
581
|
+
// 只在卡片上出现过的老标签没有行可改,要登记成顶层节点(这不是把它降级,它本来就没有父)。
|
|
582
|
+
// ⚠ 先**在虚拟树上**判环与深度,判过了再写:事务返回 {error} 是提交而不是回滚,
|
|
583
|
+
// 如果先 INSERT 登记再返回错误,调用方看到的是"被拒绝了",库里却多了一行 —— 树被静默改过。
|
|
584
|
+
const virtual = new Map(parentOf);
|
|
585
|
+
if (!virtual.has(op.tag)) virtual.set(op.tag, null);
|
|
586
|
+
if (op.parent) {
|
|
587
|
+
if (!tagExists(op.parent)) return { error: "tag_parent_not_found" };
|
|
588
|
+
if (!virtual.has(op.parent)) virtual.set(op.parent, null);
|
|
589
|
+
// 环:父是自己(parse 已挡)或自己的子孙(这里挡)。深度:新父的深度 + 自己这棵子树的高度。
|
|
590
|
+
if (isDescendant(op.parent, op.tag, virtual)) return { error: "tag_parent_cycle" };
|
|
591
|
+
if (tagDepth(op.parent, virtual) + tagSubtreeHeight(op.tag, virtual) > MAX_TAG_DEPTH) return { error: "tag_depth_exceeded" };
|
|
592
|
+
}
|
|
593
|
+
if (!parentOf.has(op.tag)) db.run("INSERT INTO network_tag_nodes (network_id, name, parent_name, created_at, updated_at, created_by_json) VALUES (?1, ?2, NULL, ?3, ?3, ?4)", [networkId, op.tag, now, actor]);
|
|
594
|
+
if (op.parent && !parentOf.has(op.parent)) db.run("INSERT INTO network_tag_nodes (network_id, name, parent_name, created_at, updated_at, created_by_json) VALUES (?1, ?2, NULL, ?3, ?3, ?4)", [networkId, op.parent, now, actor]);
|
|
595
|
+
db.run("UPDATE network_tag_nodes SET parent_name = ?1, updated_at = ?2 WHERE network_id = ?3 AND name = ?4", [op.parent, now, networkId, op.tag]);
|
|
596
|
+
return { affected: 0, reparented: 1 };
|
|
597
|
+
}
|
|
598
|
+
let affected = 0;
|
|
599
|
+
for (const card of cards) {
|
|
600
|
+
const next = applyTagOp(storedTags(card.tags_json), op);
|
|
601
|
+
if (!next) continue;
|
|
602
|
+
db.run("UPDATE requirements SET tags_json = ?1, updated_at = ?2, updated_by_json = ?3 WHERE requirement_id = ?4", [JSON.stringify(next), now, actor, card.requirement_id]);
|
|
603
|
+
recordRequirementEvents(db, card, actor, [{ kind: "changed", field: "tags", old: storedTags(card.tags_json), new: next }], now);
|
|
604
|
+
affected++;
|
|
605
|
+
}
|
|
606
|
+
moveTagColors(networkId, op, colorOf, now);
|
|
607
|
+
const reparented = maintainTagTree(networkId, op, now);
|
|
608
|
+
return { affected, reparented };
|
|
609
|
+
});
|
|
610
|
+
if (!result) return jsonError("tag_not_found", 404);
|
|
611
|
+
if ("error" in result) return jsonError(result.error, result.error === "tag_parent_not_found" ? 404 : 400);
|
|
612
|
+
if (ctx.auth) logAudit(ctx.auth.userId, ctx.auth.username || null, `requirement_tag_${op.op}`, "requirement_tag", op.op === "rename" || op.op === "merge" ? op.to : op.tag, JSON.stringify({ ...op, affected: result.affected }).slice(0, 1000), undefined, networkId);
|
|
613
|
+
return Response.json({ ok: true, op: op.op, affected: result.affected, reparented: result.reparented });
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
/** 改名 / 合并:目标没有颜色就继承第一个有颜色的来源;来源的颜色行删掉。删除:删颜色行。 */
|
|
617
|
+
function moveTagColors(networkId: string, op: TagOp, colorOf: (name: string) => string | null, now: string): void {
|
|
618
|
+
if (op.op === "color" || op.op === "reparent") return;
|
|
619
|
+
const sources = op.op === "rename" ? [op.from] : op.op === "merge" ? op.from : [op.tag];
|
|
620
|
+
if (op.op !== "delete" && colorOf(op.to) === null) {
|
|
621
|
+
const inherited = sources.map(colorOf).find(color => color !== null);
|
|
622
|
+
if (inherited) db.run("INSERT INTO network_tags (network_id, name, color, updated_at) VALUES (?1, ?2, ?3, ?4)", [networkId, op.to, inherited, now]);
|
|
623
|
+
}
|
|
624
|
+
for (const tag of sources) db.run("DELETE FROM network_tags WHERE network_id = ?1 AND name = ?2", [networkId, tag]);
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
/**
|
|
628
|
+
* 标签改名 / 合并 / 删除时让树跟着动(与卡片改写同一个事务):
|
|
629
|
+
* rename —— 节点改名,子节点的 parent_name 一起改;目标已有节点时按合并处理(并把「目标自己是来源的子节点」这种情况挂到来源的父上,避免自环)。
|
|
630
|
+
* merge —— 来源节点的子节点挂到目标,来源节点删掉。
|
|
631
|
+
* delete —— 被删节点的子节点挂到它的父(没有父就成根);不删子节点、不丢层级。
|
|
632
|
+
* 返回被改挂的节点数(客户端能报「N 个子标签已上移」)。
|
|
633
|
+
*/
|
|
634
|
+
function maintainTagTree(networkId: string, op: TagOp, now: string): number {
|
|
635
|
+
if (op.op === "color" || op.op === "reparent") return 0;
|
|
636
|
+
const rows = db.all<TagNodeRow>("SELECT name, parent_name FROM network_tag_nodes WHERE network_id = ?1", networkId);
|
|
637
|
+
if (!rows.length) return 0;
|
|
638
|
+
const parentOf = new Map(rows.map(row => [row.name, row.parent_name ?? null]));
|
|
639
|
+
if (op.op === "rename") {
|
|
640
|
+
if (!parentOf.has(op.from)) return 0;
|
|
641
|
+
const fromParent = parentOf.get(op.from) ?? null;
|
|
642
|
+
if (!parentOf.has(op.to)) {
|
|
643
|
+
db.run("UPDATE network_tag_nodes SET name = ?1, updated_at = ?2 WHERE network_id = ?3 AND name = ?4", [op.to, now, networkId, op.from]);
|
|
644
|
+
const moved = db.run("UPDATE network_tag_nodes SET parent_name = ?1, updated_at = ?2 WHERE network_id = ?3 AND parent_name = ?4", [op.to, now, networkId, op.from]);
|
|
645
|
+
return moved.changes ?? 0;
|
|
646
|
+
}
|
|
647
|
+
// 目标已有节点 —— 合并。目标若正好是来源的子孙,直接挂过去会自环,改挂到来源的父。
|
|
648
|
+
let moved = 0;
|
|
649
|
+
for (const row of rows) {
|
|
650
|
+
if (row.parent_name !== op.from) continue;
|
|
651
|
+
const nextParent = row.name === op.to ? fromParent : op.to;
|
|
652
|
+
db.run("UPDATE network_tag_nodes SET parent_name = ?1, updated_at = ?2 WHERE network_id = ?3 AND name = ?4", [nextParent, now, networkId, row.name]);
|
|
653
|
+
moved++;
|
|
654
|
+
}
|
|
655
|
+
db.run("DELETE FROM network_tag_nodes WHERE network_id = ?1 AND name = ?2", [networkId, op.from]);
|
|
656
|
+
return moved;
|
|
657
|
+
}
|
|
658
|
+
if (op.op === "merge") {
|
|
659
|
+
let moved = 0;
|
|
660
|
+
for (const source of op.from) {
|
|
661
|
+
if (!parentOf.has(source)) continue;
|
|
662
|
+
const children = rows.filter(row => row.parent_name === source);
|
|
663
|
+
const res = db.run("UPDATE network_tag_nodes SET parent_name = ?1, updated_at = ?2 WHERE network_id = ?3 AND parent_name = ?4", [op.to, now, networkId, source]);
|
|
664
|
+
moved += res.changes ?? children.length;
|
|
665
|
+
db.run("DELETE FROM network_tag_nodes WHERE network_id = ?1 AND name = ?2", [networkId, source]);
|
|
666
|
+
}
|
|
667
|
+
return moved;
|
|
668
|
+
}
|
|
669
|
+
// delete
|
|
670
|
+
const row = parentOf.has(op.tag) ? rows.find(item => item.name === op.tag)! : null;
|
|
671
|
+
if (!row) return 0;
|
|
672
|
+
const res = db.run("UPDATE network_tag_nodes SET parent_name = ?1, updated_at = ?2 WHERE network_id = ?3 AND parent_name = ?4", [row.parent_name ?? null, now, networkId, op.tag]);
|
|
673
|
+
db.run("DELETE FROM network_tag_nodes WHERE network_id = ?1 AND name = ?2", [networkId, op.tag]);
|
|
674
|
+
return res.changes ?? 0;
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
/** 网络里所有卡片上出现过的标签(**不分可见范围**)。写操作按整个网络判重,否则同名标签会被拆成两半。 */
|
|
678
|
+
function networkTagNames(networkId: string): Set<string> {
|
|
679
|
+
const names = new Set<string>();
|
|
680
|
+
for (const row of db.all<{ tags_json: string | null }>(
|
|
681
|
+
"SELECT tags_json FROM requirements WHERE network_id = ?1 AND tags_json IS NOT NULL AND tags_json <> '[]'", networkId,
|
|
682
|
+
)) {
|
|
683
|
+
for (const tag of storedTags(row.tags_json)) names.add(tag);
|
|
684
|
+
}
|
|
685
|
+
return names;
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
/**
|
|
689
|
+
* 2026-10-31 —— **状态码是 code 的函数,映射表必须穷尽**(外部复核 (c):
|
|
690
|
+
* 「三元式默认分支 = 未映射与某个真实含义同值 ⇒ 口令字段;应改成
|
|
691
|
+
* `Record<ErrorCode, number>` 由 tsc 报红」)。
|
|
692
|
+
*
|
|
693
|
+
* 原来是 `code === "tag_exists" ? 409 : code === "tag_parent_not_found" ? 404 : 400`:
|
|
694
|
+
* 新增一个错误码时它**默认落到 400**,而有些码 400 是错的(冲突应是 409),且没人会提醒你。
|
|
695
|
+
* 改成穷尽表之后,漏一个码 = tsc 红。
|
|
696
|
+
*/
|
|
697
|
+
// 2026-10-31 —— **本仓 server 没有 tsc 门**(只有 agent-network 在 e2e-docker 里 typecheck),
|
|
698
|
+
// 所以「漏一个码 = tsc 红」在这里是空头支票。⇒ 用运行时钉住:
|
|
699
|
+
// 码集合由这个数组当**唯一来源**,测试断言映射表的键与它逐字相等。
|
|
700
|
+
// 这样新增一个码只改一处(数组),而「忘了加 status」会红在测试里,不依赖编辑器。
|
|
701
|
+
export const TAG_CREATE_ERRORS = ["tag_exists", "tag_parent_not_found", "tag_depth_exceeded"] as const;
|
|
702
|
+
export type TagCreateError = (typeof TAG_CREATE_ERRORS)[number];
|
|
703
|
+
export const TAG_CREATE_STATUS: Record<TagCreateError, number> = {
|
|
704
|
+
tag_exists: 409,
|
|
705
|
+
tag_parent_not_found: 404,
|
|
706
|
+
tag_depth_exceeded: 400,
|
|
707
|
+
};
|
|
708
|
+
|
|
709
|
+
type CreateTagOutcome =
|
|
710
|
+
| { error: TagCreateError }
|
|
711
|
+
| { name: string; parent: string | null; depth: number; parentRegistered: boolean };
|
|
712
|
+
|
|
713
|
+
/** POST /api/requirements/tags/create —— 建标签(可带父)。原子、整网络判重、父不存在就报错。 */
|
|
714
|
+
async function handleTagCreate(ctx: RequirementsRequestContext): Promise<Response> {
|
|
715
|
+
const networkId = resolveRestWriteNetworkId(ctx.scope, ctx.auth, ctx.isAdmin);
|
|
716
|
+
if (!networkId) return jsonError("network_id_required", 400);
|
|
717
|
+
// 与改名 / 合并 / 删除同一把锁:整网写,只给不受任务范围限制的人。
|
|
718
|
+
if (!canManageTags(ctx, networkId)) return jsonError("permission_denied", 403);
|
|
719
|
+
let body: Record<string, unknown>;
|
|
720
|
+
try { body = await bodyObject(ctx.req); } catch { return jsonError("invalid_json", 400); }
|
|
721
|
+
const input = parseCreateTag(body);
|
|
722
|
+
if ("error" in input) return jsonError(input.error, 400);
|
|
723
|
+
const now = new Date().toISOString();
|
|
724
|
+
const actor = JSON.stringify(actorOf(ctx));
|
|
725
|
+
const result = db.transaction<CreateTagOutcome>(() => {
|
|
726
|
+
const nodes = db.all<TagNodeRow>("SELECT name, parent_name FROM network_tag_nodes WHERE network_id = ?1", networkId);
|
|
727
|
+
const parentOf = new Map(nodes.map(row => [row.name, row.parent_name ?? null]));
|
|
728
|
+
const used = networkTagNames(networkId);
|
|
729
|
+
const hasColor = (name: string) => !!db.get<{ x: number }>("SELECT 1 AS x FROM network_tags WHERE network_id = ?1 AND name = ?2", networkId, name);
|
|
730
|
+
const exists = (name: string) => parentOf.has(name) || used.has(name) || hasColor(name);
|
|
731
|
+
// 重名 = 409:不「复用」已有标签(复用会让 UI 以为新建成功,实际改了别的分支的标签)。
|
|
732
|
+
if (exists(input.name)) return { error: "tag_exists" };
|
|
733
|
+
let parentRegistered = false;
|
|
734
|
+
if (input.parent) {
|
|
735
|
+
// 父不存在 = 404。**不**把子标签建到根上:客户端预选了父,存成根会让回读的层级和表单不一致。
|
|
736
|
+
if (!exists(input.parent)) return { error: "tag_parent_not_found" };
|
|
737
|
+
if (!parentOf.has(input.parent)) {
|
|
738
|
+
// 父此前只在卡片上出现过(老数据):登记成顶层节点。父本来就没有父,这不是把子标签降级到根。
|
|
739
|
+
db.run("INSERT INTO network_tag_nodes (network_id, name, parent_name, created_at, updated_at, created_by_json) VALUES (?1, ?2, NULL, ?3, ?3, ?4)", [networkId, input.parent, now, actor]);
|
|
740
|
+
parentOf.set(input.parent, null);
|
|
741
|
+
parentRegistered = true;
|
|
742
|
+
}
|
|
743
|
+
if (tagDepth(input.parent, parentOf) + 1 > MAX_TAG_DEPTH) return { error: "tag_depth_exceeded" };
|
|
744
|
+
}
|
|
745
|
+
db.run("INSERT INTO network_tag_nodes (network_id, name, parent_name, created_at, updated_at, created_by_json) VALUES (?1, ?2, ?3, ?4, ?4, ?5)", [networkId, input.name, input.parent, now, actor]);
|
|
746
|
+
parentOf.set(input.name, input.parent);
|
|
747
|
+
return { name: input.name, parent: input.parent, depth: tagDepth(input.name, parentOf), parentRegistered };
|
|
748
|
+
});
|
|
749
|
+
if ("error" in result) {
|
|
750
|
+
return jsonError(result.error, TAG_CREATE_STATUS[result.error]);
|
|
751
|
+
}
|
|
752
|
+
if (ctx.auth) logAudit(ctx.auth.userId, ctx.auth.username || null, "requirement_tag_create", "requirement_tag", result.name, JSON.stringify({ parent_id: result.parent, depth: result.depth }).slice(0, 1000), undefined, networkId);
|
|
753
|
+
return Response.json({ ok: true, tag: { name: result.name, parent_id: result.parent, depth: result.depth }, parent_registered: result.parentRegistered }, { status: 201 });
|
|
754
|
+
}
|
|
755
|
+
|
|
756
|
+
function toPublic(row: Row) {
|
|
757
|
+
return {
|
|
758
|
+
owner: row.owner_json ? JSON.parse(row.owner_json) : null,
|
|
759
|
+
// 负责 Agent(执行者)。字段总在:客户端靠它判断这个 Hub 分不分「负责人 / 负责 Agent」。
|
|
760
|
+
agent_owner: row.agent_owner_json ? JSON.parse(row.agent_owner_json) : null,
|
|
761
|
+
// 描述(markdown)与子任务。字段总在:客户端靠它判断这个 Hub 支不支持。
|
|
762
|
+
description: row.description || "",
|
|
763
|
+
checklist: storedChecklist(row.checklist_json),
|
|
764
|
+
// 项目(可空)。字段总在:客户端靠它判断这个 Hub 有没有项目。项目被删 → 置空;被归档 → 引用保留。
|
|
765
|
+
project_id: row.project_id || null,
|
|
766
|
+
participants: JSON.parse(row.participants_json || '[]'),
|
|
767
|
+
id: row.requirement_id,
|
|
768
|
+
// 短号:每个网络自己的 #1、#2…(不回收)。界面显示 #N;GET / PATCH / MCP 的 id 也收「#N」。旧 App 忽略它。
|
|
769
|
+
seq: row.seq == null ? null : Number(row.seq),
|
|
770
|
+
name: row.title,
|
|
771
|
+
priority: row.priority,
|
|
772
|
+
// 引用优先:owner/agent_owner 在写入时被校验过;assignee 可能停在旧值(见 displayAssignee)
|
|
773
|
+
assignee: displayAssignee(row as any),
|
|
774
|
+
due: row.due_on || "",
|
|
775
|
+
// 开始(可空,甘特图用)。形状同 due;没设 = ""。旧 App 不认识这个字段,忽略即可。
|
|
776
|
+
start: row.start_on || "",
|
|
777
|
+
column: row.column_name,
|
|
778
|
+
createdAt: row.created_at,
|
|
779
|
+
updatedAt: row.updated_at || row.created_at,
|
|
780
|
+
issues: storedIssues(row.issues_json),
|
|
781
|
+
tags: storedTags(row.tags_json),
|
|
782
|
+
// 同步用的外部引用(如 github:owner/repo#123)和链接;归档的卡默认不在列表里(include_archived=1 才有)。
|
|
783
|
+
external_ref: row.external_ref || null,
|
|
784
|
+
external_url: row.external_url || null,
|
|
785
|
+
archived: !!row.archived,
|
|
786
|
+
// 谁建的 / 谁最后改的:{kind:"user"|"node", id}。旧卡只有 created_by(用户 id)。
|
|
787
|
+
created_by: row.created_by_json ? JSON.parse(row.created_by_json) : row.created_by ? { kind: "user", id: row.created_by } : null,
|
|
788
|
+
updated_by: row.updated_by_json ? JSON.parse(row.updated_by_json) : null,
|
|
789
|
+
// 子需求:parent_id(可空)和父卡上的子需求进度(未归档的子需求数 / 其中完成的)。
|
|
790
|
+
parent_id: row.parent_id || null,
|
|
791
|
+
// 废弃的子需求不算进度(total 里减掉);旧客户端眼里它是 done,见 toPublicFor。
|
|
792
|
+
children: { total: Number(row.children_total ?? 0) - Number(row.children_abandoned ?? 0), done: Number(row.children_done ?? 0) },
|
|
793
|
+
// 完成时间:进「完成」列的时刻,移出清空(不在「完成」列 = null)。completedAtApprox = 升级前就完成的卡,
|
|
794
|
+
// 时刻是按 updated_at 补的近似值。completedBy = 谁移进「完成」的(近似值的卡为 null)。旧 App 忽略这三个字段。
|
|
795
|
+
completedAt: row.completed_at || null,
|
|
796
|
+
completedAtApprox: !!row.completed_at_approx,
|
|
797
|
+
completedBy: row.completed_by_json ? JSON.parse(row.completed_by_json) : null,
|
|
798
|
+
};
|
|
799
|
+
}
|
|
800
|
+
|
|
801
|
+
async function bodyObject(req: Request): Promise<Record<string, unknown>> {
|
|
802
|
+
const value = await req.json();
|
|
803
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("invalid_json");
|
|
804
|
+
return value as Record<string, unknown>;
|
|
805
|
+
}
|
|
806
|
+
|
|
807
|
+
function writeNetwork(body: Record<string, unknown>, ctx: RequirementsRequestContext): string | null {
|
|
808
|
+
if (ctx.auth?.networkId) return ctx.auth.networkId;
|
|
809
|
+
if (typeof body.network_id === "string" && body.network_id.trim()) return body.network_id.trim();
|
|
810
|
+
return resolveRestWriteNetworkId(ctx.scope, ctx.auth, ctx.isAdmin);
|
|
811
|
+
}
|
|
812
|
+
|
|
813
|
+
function canWrite(ctx: RequirementsRequestContext, networkId: string | null): boolean {
|
|
814
|
+
// 节点令牌只能写它绑定的那个网络(scope 已强制;这里再核一次,防止别的入口绕过 scope)。
|
|
815
|
+
if (ctx.isNodeToken && (!ctx.auth?.networkId || ctx.auth.networkId !== networkId)) return false;
|
|
816
|
+
if (ctx.isNodeToken) return canRestWriteNetwork(ctx.auth, networkId, ctx.isAdmin);
|
|
817
|
+
// 需求看板是人类协作面:受限成员(只看授权 Agent 的成员)照样能读写卡片,
|
|
818
|
+
// 只是卡片上没授权给他的 Agent 引用会被隐去、也不能被他指派(见 hiddenNodeFilter)。
|
|
819
|
+
return canRestWriteNetworkAsHuman(ctx.auth, networkId, ctx.isAdmin);
|
|
820
|
+
}
|
|
821
|
+
|
|
822
|
+
// ── 多用户 Agent 权限 ──
|
|
823
|
+
// 受限成员看需求卡时:agent_owner / 参与人 / created_by / updated_by 里没授权给他的节点一律隐去;
|
|
824
|
+
// 他写卡时也不能引用这些节点。返回 null = 这个调用者在这个网络里不受限。
|
|
825
|
+
type HiddenNode = ((nodeId: string) => boolean) | null;
|
|
826
|
+
function hiddenNodeFilter(ctx: RequirementsRequestContext, networkId: string): HiddenNode {
|
|
827
|
+
if (!ctx.auth || ctx.isNodeToken || ctx.isAdmin) return null;
|
|
828
|
+
if (!isAgentRestricted(ctx.auth.userId, networkId)) return null;
|
|
829
|
+
const visible = new Set(visibleAgents(ctx.auth.userId, networkId).nodeIds);
|
|
830
|
+
return (nodeId: string) => !visible.has(nodeId);
|
|
831
|
+
}
|
|
832
|
+
/**
|
|
833
|
+
* 2026-10-31 —— **派生展示字段绕过了引用抹除**(#3285 的另一半)。
|
|
834
|
+
*
|
|
835
|
+
* `owner` / `agent_owner` / `participants` 都是 `{kind:"node", id}` 引用,所以能被
|
|
836
|
+
* `isHiddenRef` 判定并抹掉。而 `assignee` 与事件里的同名字段存的是**别名字符串** ——
|
|
837
|
+
* 没有任何 {kind,id} 可判 ⇒ 受限成员在**卡片列表**上(比事件列表常用得多)直接读到
|
|
838
|
+
* 一个他看不见的 Agent 的名字。
|
|
839
|
+
*
|
|
840
|
+
* 只能在「别名集合」这一层判:把该网络里受限成员看不见的节点的别名收成一个集合。
|
|
841
|
+
* 方向写死:**命中就抹**(宁可少显示一个名字,也不多露一个)。
|
|
842
|
+
*/
|
|
843
|
+
const aliasSetByCtx = new WeakMap<RequirementsRequestContext, Map<string, Set<string>>>();
|
|
844
|
+
export function hiddenNodeAliases(ctx: RequirementsRequestContext, networkId: string): Set<string> {
|
|
845
|
+
const hidden = hiddenNodeFilter(ctx, networkId);
|
|
846
|
+
if (!hidden) return EMPTY_ALIAS_SET;
|
|
847
|
+
let perNet = aliasSetByCtx.get(ctx);
|
|
848
|
+
if (!perNet) aliasSetByCtx.set(ctx, perNet = new Map());
|
|
849
|
+
let set = perNet.get(networkId);
|
|
850
|
+
if (!set) {
|
|
851
|
+
const rows = db.all<{ node_id: string; alias: string | null }>(
|
|
852
|
+
"SELECT node_id, alias FROM nodes WHERE network_id = ?1", networkId);
|
|
853
|
+
set = new Set(rows.filter(r => r.alias && hidden(r.node_id)).map(r => r.alias as string));
|
|
854
|
+
perNet.set(networkId, set);
|
|
855
|
+
}
|
|
856
|
+
return set;
|
|
857
|
+
}
|
|
858
|
+
const EMPTY_ALIAS_SET: Set<string> = new Set();
|
|
859
|
+
|
|
860
|
+
function isHiddenRef(ref: unknown, hidden: HiddenNode): boolean {
|
|
861
|
+
if (!hidden || !ref || typeof ref !== "object") return false;
|
|
862
|
+
const r = ref as { kind?: unknown; id?: unknown };
|
|
863
|
+
return r.kind === "node" && typeof r.id === "string" && hidden(r.id);
|
|
864
|
+
}
|
|
865
|
+
// 每个请求一个权限解析器(按网络缓存成员行与项目授权)。
|
|
866
|
+
const permsByCtx = new WeakMap<RequirementsRequestContext, ReturnType<typeof taskPermissionsResolver>>();
|
|
867
|
+
function toPublicFor(ctx: RequirementsRequestContext, row: Row) {
|
|
868
|
+
let perms = permsByCtx.get(ctx);
|
|
869
|
+
if (!perms) permsByCtx.set(ctx, perms = taskPermissionsResolver(taskCaller(ctx)));
|
|
870
|
+
// viewer_can:只对「只看相关任务」的调用者出现,客户端据此画只读锁、藏删除;不出现 = 与今天一样全能(旧 Hub 也不出现)。
|
|
871
|
+
const can = perms(row);
|
|
872
|
+
const base = toPublic(row);
|
|
873
|
+
if (!knowsAbandoned(ctx)) {
|
|
874
|
+
base.column = projectColumn(base.column, false);
|
|
875
|
+
// 旧客户端把废弃的子需求当 done 列出来:进度也按「算进总数、算作完成」给,和它看到的子需求列表对得上。
|
|
876
|
+
const abandoned = Number(row.children_abandoned ?? 0);
|
|
877
|
+
base.children = { total: base.children.total + abandoned, done: base.children.done + abandoned };
|
|
878
|
+
}
|
|
879
|
+
const pub = can ? { ...base, viewer_can: can } : base;
|
|
880
|
+
const hidden = hiddenNodeFilter(ctx, row.network_id);
|
|
881
|
+
if (!hidden) return pub;
|
|
882
|
+
const hiddenAliases = hiddenNodeAliases(ctx, row.network_id);
|
|
883
|
+
return {
|
|
884
|
+
...pub,
|
|
885
|
+
// 别名不是引用 ⇒ 单列一条(见 hiddenNodeAliases 的长注释)
|
|
886
|
+
assignee: hiddenAliases.has(pub.assignee) ? null : pub.assignee,
|
|
887
|
+
owner: isHiddenRef(pub.owner, hidden) ? null : pub.owner,
|
|
888
|
+
agent_owner: isHiddenRef(pub.agent_owner, hidden) ? null : pub.agent_owner,
|
|
889
|
+
participants: Array.isArray(pub.participants) ? pub.participants.filter((ref: unknown) => !isHiddenRef(ref, hidden)) : pub.participants,
|
|
890
|
+
created_by: isHiddenRef(pub.created_by, hidden) ? null : pub.created_by,
|
|
891
|
+
updated_by: isHiddenRef(pub.updated_by, hidden) ? null : pub.updated_by,
|
|
892
|
+
completedBy: isHiddenRef(pub.completedBy, hidden) ? null : pub.completedBy,
|
|
893
|
+
};
|
|
894
|
+
}
|
|
895
|
+
|
|
896
|
+
const SELECT = "requirement_id, network_id, title, column_name, priority, due_on, assignee, issues_json, tags_json, created_at, owner_json, participants_json, agent_owner_json, description, checklist_json, project_id, external_ref, external_url, archived, created_by, created_by_json, updated_by_json, updated_at, parent_id, start_on, seq, completed_at, completed_by_json, completed_at_approx, " +
|
|
897
|
+
"(SELECT COUNT(*) FROM requirements c WHERE c.parent_id = requirements.requirement_id AND COALESCE(c.archived, 0) = 0) AS children_total, " +
|
|
898
|
+
"(SELECT COUNT(*) FROM requirements c WHERE c.parent_id = requirements.requirement_id AND COALESCE(c.archived, 0) = 0 AND c.column_name = 'abandoned') AS children_abandoned, " +
|
|
899
|
+
"(SELECT COUNT(*) FROM requirements c WHERE c.parent_id = requirements.requirement_id AND COALESCE(c.archived, 0) = 0 AND c.column_name = 'done') AS children_done";
|
|
900
|
+
|
|
901
|
+
type PersonRef = { kind: 'user' | 'node'; id: string };
|
|
902
|
+
function personRef(value: unknown, networkId: string, hidden: HiddenNode = null, field = 'owner'): PersonRef {
|
|
903
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) throw new RequirementFieldError('invalid_person', field);
|
|
904
|
+
const row = value as Record<string, unknown>;
|
|
905
|
+
if (row.kind !== 'user' && row.kind !== 'node') throw new RequirementFieldError('invalid_person', field);
|
|
906
|
+
// #473 —— 没给 id 时可以按名字:人 {kind:'user', username},Agent {kind:'node', alias}。
|
|
907
|
+
// 只在 networkId(任务所在的网络)里找,绝不跨网络;存下来的仍是 {kind, id}。给了 id 就只看 id(与以前逐字相同)。
|
|
908
|
+
if (typeof row.id !== 'string' || !row.id.trim()) {
|
|
909
|
+
const name = row.kind === 'user' ? row.username : row.alias;
|
|
910
|
+
if (row.id !== undefined || typeof name !== 'string' || !name.trim()) throw new RequirementFieldError('invalid_person', field);
|
|
911
|
+
try { return { kind: row.kind, id: resolvePersonName(row.kind, name.trim(), networkId, hidden) }; }
|
|
912
|
+
catch (e) { throw new RequirementFieldError((e as Error).message, field); }
|
|
913
|
+
}
|
|
914
|
+
const exists = row.kind === 'user'
|
|
915
|
+
? db.get("SELECT 1 FROM network_members m JOIN users u ON u.user_id=m.user_id WHERE m.network_id=?1 AND m.user_id=?2", networkId, row.id)
|
|
916
|
+
: db.get("SELECT 1 FROM nodes WHERE network_id=?1 AND node_id=?2", networkId, row.id);
|
|
917
|
+
// 没授权的节点与不存在的节点同一个错误,不给受限成员留 node_id 探测差异。
|
|
918
|
+
if (!exists || (row.kind === 'node' && hidden?.(row.id as string))) throw new RequirementFieldError('person_not_in_network', field);
|
|
919
|
+
return { kind: row.kind, id: row.id };
|
|
920
|
+
}
|
|
921
|
+
|
|
922
|
+
// participants_remove 的一项 → "kind:id"。给了 id 就直接按 id 比(已经离开网络的人也能从列表里减掉,不查在不在网络里);
|
|
923
|
+
// 没给 id 的形状交给 personRef 解析。受限成员看不见的节点与不存在同一个错误(不给他留探测差异)。
|
|
924
|
+
function participantKey(value: unknown, networkId: string, hidden: HiddenNode, field: string): string {
|
|
925
|
+
const row = value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : null;
|
|
926
|
+
if (row && (row.kind === 'user' || row.kind === 'node') && typeof row.id === 'string' && row.id.trim()) {
|
|
927
|
+
if (row.kind === 'node' && hidden?.(row.id)) throw new RequirementFieldError('person_not_in_network', field);
|
|
928
|
+
return `${row.kind}:${row.id}`;
|
|
929
|
+
}
|
|
930
|
+
const ref = personRef(value, networkId, hidden, field);
|
|
931
|
+
return `${ref.kind}:${ref.id}`;
|
|
932
|
+
}
|
|
933
|
+
|
|
934
|
+
// 负责人只能是人类,负责 Agent 只能是节点;参与人两种都行。库里旧的节点负责人照样读出来(启动迁移会挪走),
|
|
935
|
+
// 只有这次请求显式写了 owner / agent_owner 才校验种类。
|
|
936
|
+
// 旧客户端兼容(App ≤ 0.2.142 只有一个「负责人」,可以选节点):请求里 owner 是节点、又**没带** agent_owner
|
|
937
|
+
// → 当成设置负责 Agent,负责人清空,照常 200,并回 owner_coerced_to_agent_owner: true。
|
|
938
|
+
// 带了 agent_owner 的就是新客户端,保持严格:owner 是节点 → 400 owner_must_be_human。
|
|
939
|
+
function assignments(body: Record<string, unknown>, networkId: string, current?: Row, hidden: HiddenNode = null, strictOwner = false) {
|
|
940
|
+
let owner = current?.owner_json ? JSON.parse(current.owner_json) : null;
|
|
941
|
+
let agentOwner = current?.agent_owner_json ? JSON.parse(current.agent_owner_json) : null;
|
|
942
|
+
let coerced: PersonRef | null = null;
|
|
943
|
+
// 受限成员看不见的负责 Agent,他也不能换掉或清空(他读到的是 null,写回 null 不该抹掉别人的指派)。
|
|
944
|
+
const agentOwnerLocked = isHiddenRef(agentOwner, hidden);
|
|
945
|
+
if ('owner' in body) {
|
|
946
|
+
owner = body.owner === null ? null : personRef(body.owner, networkId, hidden, 'owner');
|
|
947
|
+
if (owner && owner.kind !== 'user') {
|
|
948
|
+
if (strictOwner || 'agent_owner' in body) throw new Error('owner_must_be_human');
|
|
949
|
+
coerced = owner;
|
|
950
|
+
agentOwner = owner;
|
|
951
|
+
owner = null;
|
|
952
|
+
}
|
|
953
|
+
}
|
|
954
|
+
if (coerced && agentOwnerLocked) throw new Error('agent_owner_not_granted');
|
|
955
|
+
if ('agent_owner' in body) {
|
|
956
|
+
if (agentOwnerLocked) throw new Error('agent_owner_not_granted');
|
|
957
|
+
agentOwner = body.agent_owner === null ? null : personRef(body.agent_owner, networkId, hidden, 'agent_owner');
|
|
958
|
+
if (agentOwner && agentOwner.kind !== 'node') throw new Error('agent_owner_must_be_agent');
|
|
959
|
+
}
|
|
960
|
+
let participants = current ? JSON.parse(current.participants_json || '[]') : [];
|
|
961
|
+
if ('participants' in body) {
|
|
962
|
+
if (!Array.isArray(body.participants) || body.participants.length > 100) throw new Error('invalid_participants');
|
|
963
|
+
const refs = body.participants.map(value => personRef(value, networkId, hidden, 'participants'));
|
|
964
|
+
// 参与人是整体替换:把受限成员看不见的那些节点原样留下,别让他「保存」时静默删掉。
|
|
965
|
+
const keptHidden = hidden ? participants.filter((ref: unknown) => isHiddenRef(ref, hidden)) : [];
|
|
966
|
+
participants = [...new Map([...keptHidden, ...refs].map((ref: PersonRef) => [`${ref.kind}:${ref.id}`, ref])).values()];
|
|
967
|
+
}
|
|
968
|
+
// #475 —— 增量改参与人:participants_add / participants_remove 在当前列表上加 / 减(同步读改写,中间不让出,
|
|
969
|
+
// 并发的另一个请求插不进来),不碰别的参与人。加已有的人 = 不变;减不在列表里的人 = 不变。
|
|
970
|
+
// 和整体替换的 participants 不能同时用;同一个人既加又减 = 400,不猜先后。
|
|
971
|
+
if ('participants_add' in body || 'participants_remove' in body) {
|
|
972
|
+
if ('participants' in body) throw new RequirementFieldError('participants_conflict', 'participants');
|
|
973
|
+
const list = (key: string): unknown[] => {
|
|
974
|
+
const value = body[key];
|
|
975
|
+
if (value === undefined) return [];
|
|
976
|
+
if (!Array.isArray(value) || value.length > 100) throw new RequirementFieldError('invalid_participants_delta', key);
|
|
977
|
+
return value;
|
|
978
|
+
};
|
|
979
|
+
const add: PersonRef[] = list('participants_add').map(value => personRef(value, networkId, hidden, 'participants_add'));
|
|
980
|
+
const remove = new Set(list('participants_remove').map(value => participantKey(value, networkId, hidden, 'participants_remove')));
|
|
981
|
+
if (add.some(ref => remove.has(`${ref.kind}:${ref.id}`))) throw new RequirementFieldError('participants_add_remove_overlap', 'participants_remove');
|
|
982
|
+
const next = new Map<string, PersonRef>(participants.map((ref: PersonRef) => [`${ref.kind}:${ref.id}`, ref]));
|
|
983
|
+
for (const ref of add) if (!next.has(`${ref.kind}:${ref.id}`)) next.set(`${ref.kind}:${ref.id}`, ref);
|
|
984
|
+
for (const key of remove) next.delete(key);
|
|
985
|
+
if (next.size > 100) throw new RequirementFieldError('too_many_participants', 'participants_add');
|
|
986
|
+
participants = [...next.values()];
|
|
987
|
+
}
|
|
988
|
+
return {
|
|
989
|
+
coerced,
|
|
990
|
+
ownerJson: owner === null ? null : JSON.stringify(owner),
|
|
991
|
+
agentOwnerJson: agentOwner === null ? null : JSON.stringify(agentOwner),
|
|
992
|
+
participantsJson: JSON.stringify(participants),
|
|
993
|
+
};
|
|
994
|
+
}
|
|
995
|
+
|
|
996
|
+
/**
|
|
997
|
+
* 节点令牌(Agent,比如把 GitHub issue 同步进任务的 TM 节点)可用的操作 —— 只在它自己的网络里
|
|
998
|
+
* (令牌绑定的网络,范围由 resolveRestNetworkScope 强制)。删除卡片、管理项目仍然只给人。
|
|
999
|
+
*/
|
|
1000
|
+
/** 一条评论最多这么多字(去掉首尾空白后);进展 / 结论写得下,又不至于让动态列表里一条撑爆。 */
|
|
1001
|
+
export const COMMENT_MAX_CHARS = 4000;
|
|
1002
|
+
|
|
1003
|
+
const NODE_TOKEN_OPERATIONS: ReadonlySet<string> = new Set<string>(["read", "create", "patch", "checklist_item", "comment", "upsert", "projects_read"]);
|
|
1004
|
+
function operationOf(req: Request, url: URL): string {
|
|
1005
|
+
if (/^\/api\/requirements\/projects(\/|$)/.test(url.pathname)) return req.method === "GET" ? "projects_read" : "projects_write";
|
|
1006
|
+
if (url.pathname === "/api/requirements/tags/ops" || url.pathname === "/api/requirements/tags/create") return "tags_write";
|
|
1007
|
+
if (req.method === "GET") return "read";
|
|
1008
|
+
if (/^\/api\/requirements\/[^/]+\/checklist\/[^/]+$/.test(url.pathname)) return "checklist_item";
|
|
1009
|
+
if (/^\/api\/requirements\/[^/]+\/comments$/.test(url.pathname)) return "comment";
|
|
1010
|
+
if (url.pathname === "/api/requirements/upsert") return "upsert";
|
|
1011
|
+
if (req.method === "DELETE") return "delete";
|
|
1012
|
+
if (req.method === "PATCH") return "patch";
|
|
1013
|
+
return "create";
|
|
1014
|
+
}
|
|
1015
|
+
|
|
1016
|
+
/**
|
|
1017
|
+
* GET /api/requirements 的条件请求:ETag = 响应体的哈希,`If-None-Match` 对上就回 304 空体。
|
|
1018
|
+
* app 每 15 s 轮询整张表(生产 500 行 708 KB / gzip 163 KB,中国 → 美国约 0.65 s 纯传输),
|
|
1019
|
+
* 绝大多数轮询里表根本没变。按**响应体**算,所以对这个调用方可见的任何字段变了都会变
|
|
1020
|
+
* (同一张表不同成员看到的不同,ETag 也不同)。不带 If-None-Match 的旧客户端照旧拿 200 全量。
|
|
1021
|
+
*/
|
|
1022
|
+
export function conditionalJson(req: Request, payload: unknown): Response {
|
|
1023
|
+
const body = JSON.stringify(payload);
|
|
1024
|
+
return conditionalBody(req, body, bodyEtag(body));
|
|
1025
|
+
}
|
|
1026
|
+
|
|
1027
|
+
function bodyEtag(body: string): string {
|
|
1028
|
+
return `W/"${createHash("sha256").update(body).digest("base64url").slice(0, 27)}"`;
|
|
1029
|
+
}
|
|
1030
|
+
|
|
1031
|
+
function conditionalBody(req: Request, body: string, etag: string): Response {
|
|
1032
|
+
// private:按用户可见范围生成,不能被共享缓存复用;no-cache:每次都要回来验证,不会拿旧表当新的。
|
|
1033
|
+
const headers = { ETag: etag, "Cache-Control": "private, no-cache" };
|
|
1034
|
+
if (ifNoneMatchHits(req.headers.get("if-none-match"), etag)) return new Response(null, { status: 304, headers });
|
|
1035
|
+
// ETag 就是正文的哈希:同一份正文的 gzip 结果可以复用(http-gzip.ts)。
|
|
1036
|
+
return markGzipReusable(new Response(body, { headers: { ...headers, "Content-Type": "application/json;charset=utf-8" } }), etag);
|
|
1037
|
+
}
|
|
1038
|
+
|
|
1039
|
+
function ifNoneMatchHits(header: string | null, etag: string): boolean {
|
|
1040
|
+
if (!header) return false;
|
|
1041
|
+
const bare = (tag: string) => tag.trim().replace(/^W\//, "");
|
|
1042
|
+
return header.split(",").some(tag => tag.trim() === "*" || bare(tag) === bare(etag));
|
|
1043
|
+
}
|
|
1044
|
+
|
|
1045
|
+
// tag_ops:有 POST /api/requirements/tags/ops(标签改名 / 合并 / 删除 / 颜色),GET /api/requirements/tags 带 counts / colors / can_manage。
|
|
1046
|
+
// search:GET 认 q=(服务端搜索,语义同 App 的任务搜索);paging:认 limit / cursor,响应带 has_more / next_cursor。
|
|
1047
|
+
// list_summary:GET 认 view=summary(不带描述正文与子任务条目,见 toSummary);changes:GET 认 changes=1 + updated_since
|
|
1048
|
+
// (改过的卡含归档的,加上 deleted 墓碑与 server_time,见 listChanges)。
|
|
1049
|
+
// events:GET /api/requirements/events —— 字段级的改动流水(谁、何时、旧值 → 新值,requirement-events.ts)。
|
|
1050
|
+
export const REQUIREMENT_CAPABILITIES = ["agent_owner", "description", "checklist", "projects", "due_datetime", "external_ref", "archived", "agent_api", "sub_requirements", "tags", "priority_lowest", "start_date", "requirement_seq", "search", "paging", "completed_at", "stats", "tag_status_snapshot", "tag_ops", TAG_TREE_CAPABILITY, "list_summary", "changes", "events", "last_event", "column_abandoned"] as const;
|
|
1051
|
+
|
|
1052
|
+
// ── 子需求 ──
|
|
1053
|
+
// parent_id:同一网络里的另一张卡;不能成环;最多 5 层(顶层是第 1 层)。删父卡 = 子卡保留、parent_id 置空。
|
|
1054
|
+
export const MAX_REQUIREMENT_DEPTH = 5;
|
|
1055
|
+
function levelOf(id: string): number {
|
|
1056
|
+
let level = 1;
|
|
1057
|
+
let cur: string | null = id;
|
|
1058
|
+
const seen = new Set<string>();
|
|
1059
|
+
while (cur) {
|
|
1060
|
+
if (seen.has(cur)) return Number.POSITIVE_INFINITY; // 已存在的环(不该有):当作超深,拒绝挂上去
|
|
1061
|
+
seen.add(cur);
|
|
1062
|
+
const up = db.get<{ parent_id: string | null }>("SELECT parent_id FROM requirements WHERE requirement_id = ?1", cur);
|
|
1063
|
+
cur = up?.parent_id ?? null;
|
|
1064
|
+
if (cur) level++;
|
|
1065
|
+
}
|
|
1066
|
+
return level;
|
|
1067
|
+
}
|
|
1068
|
+
/** 以 id 为根的子树还有几层(叶子 = 0)。 */
|
|
1069
|
+
function heightBelow(id: string): number {
|
|
1070
|
+
let height = 0;
|
|
1071
|
+
let frontier = [id];
|
|
1072
|
+
const seen = new Set<string>([id]);
|
|
1073
|
+
while (frontier.length && height <= MAX_REQUIREMENT_DEPTH) {
|
|
1074
|
+
const next: string[] = [];
|
|
1075
|
+
for (const f of frontier) {
|
|
1076
|
+
for (const c of db.all<{ requirement_id: string }>("SELECT requirement_id FROM requirements WHERE parent_id = ?1", f)) {
|
|
1077
|
+
if (!seen.has(c.requirement_id)) { seen.add(c.requirement_id); next.push(c.requirement_id); }
|
|
1078
|
+
}
|
|
1079
|
+
}
|
|
1080
|
+
if (!next.length) break;
|
|
1081
|
+
height++;
|
|
1082
|
+
frontier = next;
|
|
1083
|
+
}
|
|
1084
|
+
return height;
|
|
1085
|
+
}
|
|
1086
|
+
/** 校验要挂的父卡:同网络、存在、不是自己或自己的后代(不成环)、挂上后不超过 5 层。返回错误码或 null。 */
|
|
1087
|
+
function parentError(networkId: string, parentId: string, selfId: string | null): string | null {
|
|
1088
|
+
const parent = db.get<{ network_id: string; requirement_id: string }>("SELECT network_id, requirement_id FROM requirements WHERE requirement_id = ?1", parentId);
|
|
1089
|
+
if (!parent || parent.network_id !== networkId) return "parent_not_found";
|
|
1090
|
+
if (selfId) {
|
|
1091
|
+
// 从父卡往上走,碰到自己 = 成环
|
|
1092
|
+
let cur: string | null = parentId;
|
|
1093
|
+
const seen = new Set<string>();
|
|
1094
|
+
while (cur && !seen.has(cur)) {
|
|
1095
|
+
if (cur === selfId) return "parent_cycle";
|
|
1096
|
+
seen.add(cur);
|
|
1097
|
+
cur = db.get<{ parent_id: string | null }>("SELECT parent_id FROM requirements WHERE requirement_id = ?1", cur)?.parent_id ?? null;
|
|
1098
|
+
}
|
|
1099
|
+
}
|
|
1100
|
+
const depth = levelOf(parentId) + 1 + (selfId ? heightBelow(selfId) : 0);
|
|
1101
|
+
return depth > MAX_REQUIREMENT_DEPTH ? "parent_too_deep" : null;
|
|
1102
|
+
}
|
|
1103
|
+
function parentIdOf(value: unknown): string | null | undefined {
|
|
1104
|
+
if (value === null || value === "") return null;
|
|
1105
|
+
return typeof value === "string" && /^[A-Za-z0-9_-]{1,200}$/.test(value) ? value : undefined;
|
|
1106
|
+
}
|
|
1107
|
+
|
|
1108
|
+
// ── 谁做的 ──
|
|
1109
|
+
// 用户令牌 = {kind:"user", id:user_id};节点令牌 = {kind:"node", id:令牌绑定的 node_id}(老令牌没绑 node_id 时按
|
|
1110
|
+
// 令牌名里的 alias 在本网络找;都找不到记 token 本身,不冒充任何节点)。写进 created_by / updated_by。
|
|
1111
|
+
type Actor = { kind: "user" | "node"; id: string };
|
|
1112
|
+
function actorOf(ctx: RequirementsRequestContext): Actor | null {
|
|
1113
|
+
if (!ctx.auth) return null;
|
|
1114
|
+
if (!ctx.isNodeToken) return { kind: "user", id: ctx.auth.userId };
|
|
1115
|
+
const tokenId = ctx.auth.tokenId ?? null;
|
|
1116
|
+
const resolved = tokenId ? resolveNodeCaller(tokenId) : null;
|
|
1117
|
+
if (resolved?.ok && resolved.kind === "node") return { kind: "node", id: resolved.nodeId };
|
|
1118
|
+
return { kind: "node", id: `token:${tokenId ?? "unknown"}` };
|
|
1119
|
+
}
|
|
1120
|
+
|
|
1121
|
+
// ── 外部引用(同步用) ──
|
|
1122
|
+
// external_ref:如 github:owner/repo#123,同一网络里唯一(部分唯一索引,见 requirements-migrate.ts)。
|
|
1123
|
+
// external_url:http(s) 链接,给界面显示成「在 GitHub 打开」。
|
|
1124
|
+
const EXTERNAL_REF = /^[A-Za-z0-9][A-Za-z0-9_.:\/#@+-]{0,199}$/;
|
|
1125
|
+
function externalRef(value: unknown): string | null | undefined {
|
|
1126
|
+
if (value === null) return null;
|
|
1127
|
+
if (typeof value !== "string") return undefined;
|
|
1128
|
+
const v = value.trim();
|
|
1129
|
+
return EXTERNAL_REF.test(v) ? v : undefined;
|
|
1130
|
+
}
|
|
1131
|
+
function externalUrl(value: unknown): string | null | undefined {
|
|
1132
|
+
if (value === null || value === "") return null;
|
|
1133
|
+
if (typeof value !== "string") return undefined;
|
|
1134
|
+
const v = value.trim();
|
|
1135
|
+
return /^https?:\/\/[^\s]{1,500}$/i.test(v) ? v : undefined;
|
|
1136
|
+
}
|
|
1137
|
+
function rowByExternalRef(networkId: string, ref: string): Row | undefined {
|
|
1138
|
+
return db.get<Row>(`SELECT ${SELECT} FROM requirements WHERE network_id = ?1 AND external_ref = ?2`, networkId, ref) ?? undefined;
|
|
1139
|
+
}
|
|
1140
|
+
|
|
1141
|
+
// ── 新建 ──
|
|
1142
|
+
async function createRequirement(ctx: RequirementsRequestContext, body: Record<string, unknown>): Promise<Response> {
|
|
1143
|
+
const networkId = writeNetwork(body, ctx);
|
|
1144
|
+
if (!networkId) return jsonError("network_id_required", 400);
|
|
1145
|
+
if (!canWrite(ctx, networkId)) return jsonError("permission_denied", 403);
|
|
1146
|
+
const name = typeof body.name === "string" ? body.name.trim() : "";
|
|
1147
|
+
if (!name || name.length > 80) return jsonError("invalid_name", 400);
|
|
1148
|
+
const priority = typeof body.priority === "string" ? body.priority : "normal";
|
|
1149
|
+
if (!PRIORITIES.has(priority)) return jsonError("invalid_priority", 400);
|
|
1150
|
+
const due = typeof body.due === "string" ? normalizeDue(body.due) : "";
|
|
1151
|
+
if (due === null) return jsonError("invalid_due", 400);
|
|
1152
|
+
const start = typeof body.start === "string" ? normalizeDue(body.start) : "";
|
|
1153
|
+
if (start === null) return jsonError("invalid_start", 400);
|
|
1154
|
+
const assignee = typeof body.assignee === "string" ? body.assignee.trim().slice(0, 80) : "";
|
|
1155
|
+
const clientId = typeof body.client_id === "string" ? body.client_id.trim() : "";
|
|
1156
|
+
if (clientId && !/^[A-Za-z0-9._-]{1,80}$/.test(clientId)) return jsonError("invalid_client_id", 400);
|
|
1157
|
+
const column = typeof body.column === "string" && COLUMNS.has(body.column) ? body.column : "pool";
|
|
1158
|
+
const issues = body.issues === undefined ? [] : normalizeIssues(body.issues);
|
|
1159
|
+
if (issues === null) return jsonError("invalid_issues", 400);
|
|
1160
|
+
const tags = body.tags === undefined ? [] : normalizeTags(body.tags);
|
|
1161
|
+
if (tags === null) return jsonError("invalid_tags", 400);
|
|
1162
|
+
const description = body.description === undefined ? "" : normalizeDescription(body.description);
|
|
1163
|
+
if (description === null) return jsonError("invalid_description", 400);
|
|
1164
|
+
const checklist = body.checklist === undefined ? [] : normalizeChecklist(body.checklist);
|
|
1165
|
+
if (checklist === null) return jsonError("invalid_checklist", 400);
|
|
1166
|
+
const caller = taskCaller(ctx);
|
|
1167
|
+
const scoped = !!caller && isTaskScoped(caller.userId, networkId);
|
|
1168
|
+
let projectId: string | null = null;
|
|
1169
|
+
if (body.project_id !== undefined) {
|
|
1170
|
+
try { projectId = projectRef(body.project_id, networkId); } catch (e) { return errorFrom(e); }
|
|
1171
|
+
// scoped 成员只能建进自己 can_edit 的项目;没授权的项目与不存在的项目同一个错误。
|
|
1172
|
+
if (!canUseProject(caller, networkId, projectId)) return jsonError("project_not_in_network", 400);
|
|
1173
|
+
}
|
|
1174
|
+
const ref = body.external_ref === undefined ? null : externalRef(body.external_ref);
|
|
1175
|
+
if (ref === undefined) return jsonError("invalid_external_ref", 400);
|
|
1176
|
+
// scoped 成员不能带 external_ref:「external_ref_exists」会把别人的卡号回给他。
|
|
1177
|
+
if (ref && scoped) return jsonError("external_ref_not_allowed", 403);
|
|
1178
|
+
const extUrl = body.external_url === undefined ? null : externalUrl(body.external_url);
|
|
1179
|
+
if (extUrl === undefined) return jsonError("invalid_external_url", 400);
|
|
1180
|
+
const parentId = body.parent_id === undefined ? null : parentIdOf(body.parent_id);
|
|
1181
|
+
if (parentId === undefined) return jsonError("invalid_parent_id", 400);
|
|
1182
|
+
if (parentId) {
|
|
1183
|
+
const err = parentHidden(ctx, parentId) ? "parent_not_found" : parentError(networkId, parentId, null);
|
|
1184
|
+
if (err) return jsonError(err, 400);
|
|
1185
|
+
}
|
|
1186
|
+
if (ref) {
|
|
1187
|
+
const existing = rowByExternalRef(networkId, ref);
|
|
1188
|
+
// 同一个外部条目再建一次 = 冲突,回已有的 id(同步方改用 upsert,或按这个 id PATCH)。
|
|
1189
|
+
if (existing) return Response.json({ ...errorBody("external_ref_exists"), existing_id: existing.requirement_id }, { status: 409 });
|
|
1190
|
+
}
|
|
1191
|
+
if (clientId) {
|
|
1192
|
+
const existing = db.get<Row>(`SELECT ${SELECT} FROM requirements WHERE network_id = ?1 AND client_id = ?2`, networkId, clientId);
|
|
1193
|
+
// 重放只回调用者看得见的卡;撞上别人的卡(scoped 看不见)= 固定的 409,不把那张卡回给他。
|
|
1194
|
+
if (existing) return canSeeTask(caller, existing) ? Response.json({ ok: true, requirement: toPublicFor(ctx, existing) }) : jsonError("client_id_taken", 409);
|
|
1195
|
+
}
|
|
1196
|
+
const id = `req_${crypto.randomUUID()}`;
|
|
1197
|
+
const createdAt = new Date().toISOString();
|
|
1198
|
+
let people;
|
|
1199
|
+
try { people = assignments(body, networkId, undefined, hiddenNodeFilter(ctx, networkId), ctx.strictOwner === true); } catch (e) { return errorFrom(e); }
|
|
1200
|
+
const nodeDenied = nodeTaskGate(ctx, "POST /api/requirements", null, { networkId, projectId, agentOwnerJson: people.agentOwnerJson, parentId });
|
|
1201
|
+
if (nodeDenied) return nodeDenied;
|
|
1202
|
+
const actor = JSON.stringify(actorOf(ctx));
|
|
1203
|
+
try {
|
|
1204
|
+
// 领号、插入、记「新建」这条动态在同一个事务里:插入被唯一索引挡下时,号和动态一起回滚,不留空洞。
|
|
1205
|
+
db.transaction(() => {
|
|
1206
|
+
const seq = nextRequirementSeq(db, networkId);
|
|
1207
|
+
db.run(
|
|
1208
|
+
`INSERT INTO requirements
|
|
1209
|
+
(requirement_id, network_id, title, column_name, priority, due_on, assignee, client_id, issues_json, created_by, created_at, updated_at, owner_json, participants_json, agent_owner_json, description, checklist_json, project_id, external_ref, external_url, created_by_json, updated_by_json, archived, parent_id, tags_json, start_on, seq, completed_at, completed_by_json, completed_at_approx)
|
|
1210
|
+
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?11, ?12, ?13, ?14, ?15, ?16, ?17, ?18, ?19, ?20, ?20, 0, ?21, ?22, ?23, ?24, ?25, ?26, 0)`,
|
|
1211
|
+
[id, networkId, name, column, priority, due || null, assignee, clientId || null, JSON.stringify(issues), ctx.auth?.userId ?? null, createdAt, people.ownerJson, people.participantsJson, people.agentOwnerJson, description || null, JSON.stringify(checklist), projectId, ref, extUrl, actor, parentId, JSON.stringify(tags), start || null, seq,
|
|
1212
|
+
// 直接建在「完成」列 = 此刻完成、由建卡的人完成。
|
|
1213
|
+
column === "done" ? createdAt : null, column === "done" ? actor : null],
|
|
1214
|
+
);
|
|
1215
|
+
recordRequirementEvents(db, { requirement_id: id, network_id: networkId, seq, title: name }, actor, [{ kind: "created", field: null, old: null, new: { title: name, column } }], createdAt);
|
|
1216
|
+
});
|
|
1217
|
+
} catch {
|
|
1218
|
+
// 并发的同一个 external_ref / client_id:唯一索引挡住了第二个,回已有的那条。
|
|
1219
|
+
if (ref) {
|
|
1220
|
+
const existing = rowByExternalRef(networkId, ref);
|
|
1221
|
+
if (existing) return Response.json({ ...errorBody("external_ref_exists"), existing_id: existing.requirement_id }, { status: 409 });
|
|
1222
|
+
}
|
|
1223
|
+
if (!clientId) return jsonError("insert_failed", 500);
|
|
1224
|
+
const existing = db.get<Row>(`SELECT ${SELECT} FROM requirements WHERE network_id = ?1 AND client_id = ?2`, networkId, clientId);
|
|
1225
|
+
if (!existing) return jsonError("insert_failed", 500);
|
|
1226
|
+
if (!canSeeTask(caller, existing)) return jsonError("client_id_taken", 409);
|
|
1227
|
+
return Response.json({ ok: true, requirement: toPublicFor(ctx, existing) });
|
|
1228
|
+
}
|
|
1229
|
+
const created = db.get<Row>(`SELECT ${SELECT} FROM requirements WHERE requirement_id = ?1`, id)!;
|
|
1230
|
+
return Response.json(withLegacyOwner(toPublicFor(ctx, created), people.coerced), { status: 201 });
|
|
1231
|
+
}
|
|
1232
|
+
|
|
1233
|
+
// ── 修改(省略的字段保留原值) ──
|
|
1234
|
+
const PATCH_FIELDS = ["column", "issues", "tags", "name", "priority", "due", "assignee", "owner", "agent_owner", "participants", "participants_add", "participants_remove", "description", "checklist", "project_id", "external_ref", "external_url", "archived", "parent_id", "start"];
|
|
1235
|
+
function patchRequirement(ctx: RequirementsRequestContext, row: Row, body: Record<string, unknown>): Response {
|
|
1236
|
+
if (!PATCH_FIELDS.some(k => Object.prototype.hasOwnProperty.call(body, k))) return jsonError("empty_patch", 400, { sent: Object.keys(body), writable: PATCH_FIELDS });
|
|
1237
|
+
const has = (k: string) => Object.prototype.hasOwnProperty.call(body, k);
|
|
1238
|
+
if (!canWrite(ctx, row.network_id)) return jsonError("permission_denied", 403);
|
|
1239
|
+
const nodeDenied = nodeTaskGate(ctx, "PATCH /api/requirements/:id", row);
|
|
1240
|
+
if (nodeDenied) return nodeDenied;
|
|
1241
|
+
const caller = taskCaller(ctx);
|
|
1242
|
+
if (!canEditTask(caller, row)) {
|
|
1243
|
+
// 参与人:只放状态和检查项;别的字段点名拒绝。不是参与人 → 与今天一样。
|
|
1244
|
+
if (!canParticipantEditTask(caller, row)) return taskDenied(ctx, row, "task_read_only");
|
|
1245
|
+
const other = PATCH_FIELDS.find(k => has(k) && !PARTICIPANT_EDIT_FIELDS.includes(k));
|
|
1246
|
+
if (other) return taskDenied(ctx, row, "task_read_only", other);
|
|
1247
|
+
}
|
|
1248
|
+
// scoped 成员不能写 external_ref:唯一索引冲突会泄露别的卡用了这个 ref。
|
|
1249
|
+
if (has("external_ref") && caller && isTaskScoped(caller.userId, row.network_id)) return jsonError("external_ref_not_allowed", 403);
|
|
1250
|
+
if (has("column") && !COLUMNS.has(String(body.column))) return jsonError("invalid_column", 400);
|
|
1251
|
+
const issues = has("issues") ? normalizeIssues(body.issues) : null;
|
|
1252
|
+
if (has("issues") && issues === null) return jsonError("invalid_issues", 400);
|
|
1253
|
+
const tags = has("tags") ? normalizeTags(body.tags) : null;
|
|
1254
|
+
if (has("tags") && tags === null) return jsonError("invalid_tags", 400);
|
|
1255
|
+
const description = has("description") ? normalizeDescription(body.description) : null;
|
|
1256
|
+
if (has("description") && description === null) return jsonError("invalid_description", 400);
|
|
1257
|
+
const checklist = has("checklist") ? normalizeChecklist(body.checklist) : null;
|
|
1258
|
+
if (has("checklist") && checklist === null) return jsonError("invalid_checklist", 400);
|
|
1259
|
+
let name = row.title;
|
|
1260
|
+
if (has("name")) {
|
|
1261
|
+
name = typeof body.name === "string" ? body.name.trim() : "";
|
|
1262
|
+
if (!name || name.length > 80) return jsonError("invalid_name", 400);
|
|
1263
|
+
}
|
|
1264
|
+
let priority = row.priority;
|
|
1265
|
+
if (has("priority")) {
|
|
1266
|
+
if (typeof body.priority !== "string" || !PRIORITIES.has(body.priority)) return jsonError("invalid_priority", 400);
|
|
1267
|
+
priority = body.priority;
|
|
1268
|
+
}
|
|
1269
|
+
let due = row.due_on || "";
|
|
1270
|
+
if (has("due")) {
|
|
1271
|
+
if (typeof body.due !== "string") return jsonError("invalid_due", 400);
|
|
1272
|
+
const next = normalizeDue(body.due);
|
|
1273
|
+
if (next === null) return jsonError("invalid_due", 400);
|
|
1274
|
+
due = next;
|
|
1275
|
+
}
|
|
1276
|
+
let start = row.start_on || "";
|
|
1277
|
+
if (has("start")) {
|
|
1278
|
+
if (typeof body.start !== "string") return jsonError("invalid_start", 400);
|
|
1279
|
+
const next = normalizeDue(body.start);
|
|
1280
|
+
if (next === null) return jsonError("invalid_start", 400);
|
|
1281
|
+
start = next;
|
|
1282
|
+
}
|
|
1283
|
+
let assignee = row.assignee || "";
|
|
1284
|
+
if (has("assignee")) {
|
|
1285
|
+
if (typeof body.assignee !== "string") return jsonError("invalid_assignee", 400);
|
|
1286
|
+
assignee = body.assignee.trim().slice(0, 80);
|
|
1287
|
+
}
|
|
1288
|
+
let people;
|
|
1289
|
+
try { people = assignments(body, row.network_id, row, hiddenNodeFilter(ctx, row.network_id), ctx.strictOwner === true); } catch (e) { return errorFrom(e); }
|
|
1290
|
+
|
|
1291
|
+
// 2026-10-31 —— **写侧对账**(#3270 的另一半):
|
|
1292
|
+
// 读侧已经以 owner/agent_owner 为准(displayAssignee),但库里那一列仍会停在旧值。
|
|
1293
|
+
// 一个派生字段只要有第二个写入路径,就迟早会与事实分叉;同一次写入里把它对齐,分叉就不会累积。
|
|
1294
|
+
// 规则:调用方**没有显式给 assignee** 时,用本次写入后的引用回填;显式给了就以调用方为准
|
|
1295
|
+
// (那可能是系统外的人,例如「王工」—— 用引用覆盖它等于丢信息)。
|
|
1296
|
+
if (!has("assignee") && (has("owner") || has("agent_owner"))) {
|
|
1297
|
+
// 用 refDisplayName(把 {kind,id} 换回人名),**不是** displayAssignee
|
|
1298
|
+
// (后者只回显存下来的自由文本 —— 这里正是要从引用推)。
|
|
1299
|
+
const fromRef = refDisplayName(people.agentOwnerJson) || refDisplayName(people.ownerJson);
|
|
1300
|
+
if (fromRef) assignee = fromRef.slice(0, 80);
|
|
1301
|
+
}
|
|
1302
|
+
// RFC-040:只凭负责人身份改这张卡时,负责人 / 负责 Agent 只能交给本部门的人(或自己)/ 本部门成员的 Agent,
|
|
1303
|
+
// 不能把卡推出本部门(推出去等于替别的部门派活)。清空(null)不限制。
|
|
1304
|
+
const headOnly = (has("owner") || has("agent_owner")) ? headOnlyEditScope(caller, row) : null;
|
|
1305
|
+
if (headOnly) {
|
|
1306
|
+
const owner = people.ownerJson ? JSON.parse(people.ownerJson) as PersonRef : null;
|
|
1307
|
+
const agent = people.agentOwnerJson ? JSON.parse(people.agentOwnerJson) as PersonRef : null;
|
|
1308
|
+
if (has("owner") && owner && owner.id !== caller!.userId && !headOnly.users.has(owner.id)) return jsonError("department_scope_denied", 403, { field: "owner" });
|
|
1309
|
+
if (has("agent_owner") && agent && !headOnly.nodes.has(agent.id)) return jsonError("department_scope_denied", 403, { field: "agent_owner" });
|
|
1310
|
+
}
|
|
1311
|
+
let projectId = row.project_id;
|
|
1312
|
+
if (has("project_id")) {
|
|
1313
|
+
try { projectId = projectRef(body.project_id, row.network_id); } catch (e) { return errorFrom(e); }
|
|
1314
|
+
// scoped 成员只能挪进自己 can_edit 的项目;没授权的项目与不存在的项目同一个错误。
|
|
1315
|
+
if (projectId !== row.project_id && !canUseProject(caller, row.network_id, projectId)) return jsonError("project_not_in_network", 400);
|
|
1316
|
+
}
|
|
1317
|
+
let ref = row.external_ref;
|
|
1318
|
+
if (has("external_ref")) {
|
|
1319
|
+
const next = externalRef(body.external_ref);
|
|
1320
|
+
if (next === undefined) return jsonError("invalid_external_ref", 400);
|
|
1321
|
+
if (next && next !== row.external_ref) {
|
|
1322
|
+
const taken = rowByExternalRef(row.network_id, next);
|
|
1323
|
+
if (taken) return Response.json({ ...errorBody("external_ref_exists"), existing_id: taken.requirement_id }, { status: 409 });
|
|
1324
|
+
}
|
|
1325
|
+
ref = next;
|
|
1326
|
+
}
|
|
1327
|
+
let extUrl = row.external_url;
|
|
1328
|
+
if (has("external_url")) {
|
|
1329
|
+
const next = externalUrl(body.external_url);
|
|
1330
|
+
if (next === undefined) return jsonError("invalid_external_url", 400);
|
|
1331
|
+
extUrl = next;
|
|
1332
|
+
}
|
|
1333
|
+
let parentId = row.parent_id;
|
|
1334
|
+
if (has("parent_id")) {
|
|
1335
|
+
const next = parentIdOf(body.parent_id);
|
|
1336
|
+
if (next === undefined) return jsonError("invalid_parent_id", 400);
|
|
1337
|
+
if (next) {
|
|
1338
|
+
const err = parentHidden(ctx, next) ? "parent_not_found" : parentError(row.network_id, next, row.requirement_id);
|
|
1339
|
+
if (err) return jsonError(err, 400);
|
|
1340
|
+
}
|
|
1341
|
+
parentId = next;
|
|
1342
|
+
}
|
|
1343
|
+
let archived = row.archived ? 1 : 0;
|
|
1344
|
+
if (has("archived")) {
|
|
1345
|
+
if (typeof body.archived !== "boolean") return jsonError("invalid_archived", 400);
|
|
1346
|
+
archived = body.archived ? 1 : 0;
|
|
1347
|
+
}
|
|
1348
|
+
const updatedAt = new Date().toISOString();
|
|
1349
|
+
// 旧客户端眼里废弃的卡是 done:它回传 column=done 不是「改成完成」,保持废弃。
|
|
1350
|
+
const column = !has("column") ? row.column_name
|
|
1351
|
+
: row.column_name === "abandoned" && body.column === "done" && !knowsAbandoned(ctx) ? "abandoned"
|
|
1352
|
+
: String(body.column);
|
|
1353
|
+
const actor = JSON.stringify(actorOf(ctx));
|
|
1354
|
+
// 完成时间:移进「完成」= 此刻 + 这次的操作者;移出 = 清空;留在「完成」(done → done、改别的字段)= 原样不动。
|
|
1355
|
+
const completed = column !== "done" ? { at: null, by: null, approx: 0 }
|
|
1356
|
+
: row.column_name !== "done" ? { at: updatedAt, by: actor, approx: 0 }
|
|
1357
|
+
: { at: row.completed_at, by: row.completed_by_json, approx: row.completed_at_approx ? 1 : 0 };
|
|
1358
|
+
// 改卡和记动态(改前 row → 改后 updated 的字段差异)在同一个事务里:要么都在,要么都不在。
|
|
1359
|
+
const updated = db.transaction(() => {
|
|
1360
|
+
db.run(
|
|
1361
|
+
`UPDATE requirements SET column_name = ?1, updated_at = ?2, title = ?7, priority = ?8, due_on = ?9, assignee = ?10, owner_json = ?4, participants_json = ?5, issues_json = ?6,
|
|
1362
|
+
agent_owner_json = ?11, description = ?12, checklist_json = ?13, project_id = ?14, external_ref = ?15, external_url = ?16, archived = ?17, updated_by_json = ?18, parent_id = ?19, tags_json = ?20, start_on = ?21,
|
|
1363
|
+
completed_at = ?22, completed_by_json = ?23, completed_at_approx = ?24
|
|
1364
|
+
WHERE requirement_id = ?3`,
|
|
1365
|
+
[column, updatedAt, row.requirement_id, people.ownerJson, people.participantsJson, has("issues") ? JSON.stringify(issues) : row.issues_json, name, priority, due || null, assignee, people.agentOwnerJson,
|
|
1366
|
+
has("description") ? (description || null) : row.description, has("checklist") ? JSON.stringify(checklist) : row.checklist_json, projectId, ref, extUrl, archived, actor, parentId, has("tags") ? JSON.stringify(tags) : row.tags_json, start || null,
|
|
1367
|
+
completed.at, completed.by, completed.approx],
|
|
1368
|
+
);
|
|
1369
|
+
const after = db.get<Row>(`SELECT ${SELECT} FROM requirements WHERE requirement_id = ?1`, row.requirement_id)!;
|
|
1370
|
+
recordRequirementEvents(db, after, actor, diffRequirement(row, after), updatedAt);
|
|
1371
|
+
return after;
|
|
1372
|
+
});
|
|
1373
|
+
notifyIfParticipant(ctx, row, updated);
|
|
1374
|
+
return Response.json(withLegacyOwner(toPublicFor(ctx, updated), people.coerced));
|
|
1375
|
+
}
|
|
1376
|
+
|
|
1377
|
+
/**
|
|
1378
|
+
* 被兼容改写的请求(旧客户端):响应里的 owner 按旧客户端的理解回显那个节点(它会拿响应核对「保存生效没有」,
|
|
1379
|
+
* 0.2.142 的核对不通过就报「这个 Hub 还不能修改」),真实存储是 owner 空、agent_owner = 节点;agent_owner 也一并返回。
|
|
1380
|
+
* GET 不这么做:新 App 读 owner / agent_owner 两个字段,GET 回显会让新 App 把 Agent 当成负责人。
|
|
1381
|
+
*/
|
|
1382
|
+
function withLegacyOwner(requirement: ReturnType<typeof toPublic>, coerced: PersonRef | null) {
|
|
1383
|
+
if (!coerced) return { ok: true, requirement };
|
|
1384
|
+
return { ok: true, requirement: { ...requirement, owner: coerced }, owner_coerced_to_agent_owner: true };
|
|
1385
|
+
}
|
|
1386
|
+
|
|
1387
|
+
/** 「#123」→ 123;别的形状(包括裸数字)→ null,仍按 requirement_id 查。 */
|
|
1388
|
+
export function seqFromId(id: string): number | null {
|
|
1389
|
+
const m = /^#([1-9]\d{0,14})$/.exec(id.trim());
|
|
1390
|
+
return m ? Number(m[1]) : null;
|
|
1391
|
+
}
|
|
1392
|
+
|
|
1393
|
+
/**
|
|
1394
|
+
* 按 id 或「#N」找调用者作用域里的那张卡。短号只在一个网络里唯一:作用域跨多个网络、又各有一张 #N 时
|
|
1395
|
+
* 不猜,回 409 ambiguous_seq(带 ?network_id= 再查)。
|
|
1396
|
+
*/
|
|
1397
|
+
function scopedRow(ctx: RequirementsRequestContext, id: string): Row | Response {
|
|
1398
|
+
const seq = seqFromId(id);
|
|
1399
|
+
const params: unknown[] = [seq ?? id];
|
|
1400
|
+
let sql = `SELECT ${SELECT} FROM requirements WHERE ${seq === null ? "requirement_id" : "seq"} = ?1`;
|
|
1401
|
+
sql = addHumanNetworkScope(sql, params, ctx.scope);
|
|
1402
|
+
// 看不见的卡与不存在的卡同一个 404(逐字节相同);#N 的 ambiguous_seq 也只在看得见的行里判定。
|
|
1403
|
+
sql = addTaskVisibilityScope(sql, params, taskCaller(ctx));
|
|
1404
|
+
const rows = db.all<Row>(`${sql} LIMIT 2`, ...params);
|
|
1405
|
+
if (rows.length > 1) {
|
|
1406
|
+
const networks = rows.map(r => r.network_id);
|
|
1407
|
+
return Response.json({ ...errorBody("ambiguous_seq"), networks, message: `#${seq} exists in more than one network you can see (${networks.join(", ")}); pass network_id to pick one` }, { status: 409 });
|
|
1408
|
+
}
|
|
1409
|
+
return rows[0] ?? jsonError("requirement_not_found", 404);
|
|
1410
|
+
}
|
|
1411
|
+
|
|
1412
|
+
/** GET 的筛选(同步方 / MCP 用):seq(短号)、status、project_id、owner / agent_owner(kind:id)、updated_since、external_ref、parent_id / top_level、include_archived。 */
|
|
1413
|
+
function listFilters(url: URL, sql: string, params: unknown[], ctx?: RequirementsRequestContext): string | Response {
|
|
1414
|
+
const q = url.searchParams;
|
|
1415
|
+
const status = q.get("status");
|
|
1416
|
+
if (status !== null) {
|
|
1417
|
+
if (!COLUMNS.has(status)) return jsonError("invalid_status", 400);
|
|
1418
|
+
// 旧客户端把废弃的卡看成 done:它按 done 筛时也要带上废弃的,否则同一张卡在列表里有、筛出来没有。
|
|
1419
|
+
if (status === "done" && ctx && !knowsAbandoned(ctx)) sql += " AND column_name IN ('done', 'abandoned')";
|
|
1420
|
+
else sql += ` AND column_name = ?${params.push(status)}`;
|
|
1421
|
+
}
|
|
1422
|
+
const project = q.get("project_id");
|
|
1423
|
+
if (project !== null) sql += project === "none" ? " AND project_id IS NULL" : ` AND project_id = ?${params.push(project)}`;
|
|
1424
|
+
for (const [param, column] of [["owner", "owner_json"], ["agent_owner", "agent_owner_json"]] as const) {
|
|
1425
|
+
const v = q.get(param);
|
|
1426
|
+
if (v === null) continue;
|
|
1427
|
+
if (v === "none") { sql += ` AND ${column} IS NULL`; continue; }
|
|
1428
|
+
const m = /^(user|node):(.+)$/.exec(v);
|
|
1429
|
+
if (!m) return jsonError(`invalid_${param}`, 400);
|
|
1430
|
+
// 受限成员按一个没授权给他的节点筛选:与「没有这样的卡」同一结果(否则是「谁负责这张卡」的探测器)。
|
|
1431
|
+
if (m[1] === "node" && ctx && hiddenFilterForScope(ctx, m[2])) { sql += " AND 1=0"; continue; }
|
|
1432
|
+
sql += ` AND ${column} = ?${params.push(JSON.stringify({ kind: m[1], id: m[2] }))}`;
|
|
1433
|
+
}
|
|
1434
|
+
const since = q.get("updated_since");
|
|
1435
|
+
if (since !== null) {
|
|
1436
|
+
const ms = Date.parse(since);
|
|
1437
|
+
if (!Number.isFinite(ms)) return jsonError("invalid_updated_since", 400);
|
|
1438
|
+
const n = params.push(new Date(ms).toISOString());
|
|
1439
|
+
// #506 —— 增量(changes=1)且带 last_event 时,「之后有新流水」的卡也算改过:评论只追加 requirement_events、
|
|
1440
|
+
// 不动 updated_at(updatedAt 是「卡本身最后一次被改」,评论不算 —— 见 last_event 测试),不这样评论要等下次整读才出现。
|
|
1441
|
+
// 同一个占位符用两次(SQLite / PostgreSQL 都认,没有绑了不用的参数);子查询走 idx_requirement_events_created,
|
|
1442
|
+
// 只扫游标之后的流水。不带 changes 的 updated_since 照旧只按 updated_at 过滤(同步方 / MCP 筛选语义不变);
|
|
1443
|
+
// last_event=0(MCP 默认)行上没有动态可看,也照旧。
|
|
1444
|
+
const eventsToo = q.get("changes") === "1" && q.get("last_event") !== "0";
|
|
1445
|
+
sql += eventsToo
|
|
1446
|
+
? ` AND (updated_at >= ?${n} OR requirement_id IN (SELECT requirement_id FROM requirement_events WHERE created_at >= ?${n}))`
|
|
1447
|
+
: ` AND updated_at >= ?${n}`;
|
|
1448
|
+
}
|
|
1449
|
+
const seq = q.get("seq");
|
|
1450
|
+
if (seq !== null) {
|
|
1451
|
+
if (!/^[1-9]\d{0,14}$/.test(seq)) return jsonError("invalid_seq", 400);
|
|
1452
|
+
sql += ` AND seq = ?${params.push(Number(seq))}`;
|
|
1453
|
+
}
|
|
1454
|
+
const ref = q.get("external_ref");
|
|
1455
|
+
if (ref !== null) sql += ` AND external_ref = ?${params.push(ref)}`;
|
|
1456
|
+
const parent = q.get("parent_id");
|
|
1457
|
+
if (parent !== null) sql += parent === "none" ? " AND parent_id IS NULL" : ` AND parent_id = ?${params.push(parent)}`;
|
|
1458
|
+
// RFC-040:department_id= —— 负责人是这个部门(含下级)的成员、或负责 Agent 归这些成员所有的卡。可见范围照旧由上面的
|
|
1459
|
+
// addTaskVisibilityScope 管,这里只再收窄。部门按调用者看得见的网络找(部门 id 只在网络内唯一)。
|
|
1460
|
+
const dept = q.get("department_id");
|
|
1461
|
+
if (dept !== null) {
|
|
1462
|
+
if (!dept || !/^[A-Za-z0-9_-]{1,64}$/.test(dept)) return jsonError("department_not_found", 400);
|
|
1463
|
+
const networks = ctx ? departmentNetworks(ctx, dept) : [];
|
|
1464
|
+
if (!networks.length) return jsonError("department_not_found", 400);
|
|
1465
|
+
const parts: string[] = [];
|
|
1466
|
+
for (const networkId of networks) {
|
|
1467
|
+
const cards = departmentCardsFor(networkId, departmentSubtree(networkId, dept));
|
|
1468
|
+
const ors: string[] = [];
|
|
1469
|
+
if (cards.users.size) ors.push(`owner_json IN (${[...cards.users].map((id) => `?${params.push(JSON.stringify({ kind: "user", id }))}`).join(", ")})`);
|
|
1470
|
+
if (cards.nodes.size) ors.push(`agent_owner_json IN (${[...cards.nodes].map((id) => `?${params.push(JSON.stringify({ kind: "node", id }))}`).join(", ")})`);
|
|
1471
|
+
if (ors.length) parts.push(`(network_id = ?${params.push(networkId)} AND (${ors.join(" OR ")}))`);
|
|
1472
|
+
}
|
|
1473
|
+
sql += parts.length ? ` AND (${parts.join(" OR ")})` : " AND 1=0";
|
|
1474
|
+
}
|
|
1475
|
+
if (q.get("top_level") === "1") sql += " AND parent_id IS NULL";
|
|
1476
|
+
// #494 —— 到期筛选(只看没完成的卡;「今天」按到期提醒同一个时区,见 requirement-due-reminders.ts)。
|
|
1477
|
+
const overdue = q.get("overdue");
|
|
1478
|
+
if (overdue !== null) {
|
|
1479
|
+
if (!["1", "true", "0", "false"].includes(overdue)) return jsonError("invalid_overdue", 400);
|
|
1480
|
+
const cond = overdueSql(params, Date.now(), dueReminderTimezone());
|
|
1481
|
+
sql += overdue === "1" || overdue === "true" ? ` AND ${cond}` : ` AND NOT ${cond}`;
|
|
1482
|
+
}
|
|
1483
|
+
const within = q.get("due_within_days");
|
|
1484
|
+
if (within !== null) {
|
|
1485
|
+
if (!/^\d{1,3}$/.test(within) || Number(within) > 365) return jsonError("invalid_due_within_days", 400);
|
|
1486
|
+
sql += ` AND ${dueWithinSql(params, Number(within), Date.now(), dueReminderTimezone())}`;
|
|
1487
|
+
}
|
|
1488
|
+
// Explicit archived-only wins over the legacy include-all switch.
|
|
1489
|
+
// changes=1 看得见「被归档」这一改动:默认连归档的一起回(行上 archived: true),客户端据此把它移出看板。
|
|
1490
|
+
if (q.get("archived") === "true") sql += " AND COALESCE(archived, 0) = 1";
|
|
1491
|
+
else if (q.get("include_archived") !== "1" && q.get("changes") !== "1") sql += " AND COALESCE(archived, 0) = 0";
|
|
1492
|
+
return sql;
|
|
1493
|
+
}
|
|
1494
|
+
|
|
1495
|
+
/** department_id 筛选:调用者作用域里有这个部门的网络。 */
|
|
1496
|
+
function departmentNetworks(ctx: RequirementsRequestContext, deptId: string): string[] {
|
|
1497
|
+
const params: unknown[] = [deptId];
|
|
1498
|
+
const sql = addHumanNetworkScope("SELECT DISTINCT network_id FROM network_departments WHERE department_id = ?1", params, ctx.scope);
|
|
1499
|
+
return db.all<{ network_id: string }>(sql, ...params).map((r) => r.network_id);
|
|
1500
|
+
}
|
|
1501
|
+
|
|
1502
|
+
const LIST_ORDER = " ORDER BY created_at DESC, requirement_id DESC";
|
|
1503
|
+
type LightRow = { requirement_id: string; seq?: number | null; network_id: string; created_at: string; title: string; description: string | null; assignee: string | null; tags_json: string | null; project_id: string | null; owner_json: string | null; agent_owner_json: string | null; participants_json: string | null };
|
|
1504
|
+
/**
|
|
1505
|
+
* 2026-10-31 —— `assignee` 是**派生展示字段**,但它有自己的旧写入路径,会停在旧值。
|
|
1506
|
+
*
|
|
1507
|
+
* 实测(ANet 项目 archived=0,1105 张):25 张与 owner/agent_owner 不一致,
|
|
1508
|
+
* 其中 22 张「有 assignee 但既无 owner 也无 agent_owner」。读的人看的是 assignee,
|
|
1509
|
+
* 于是「有人负责」这句话可以比事实晚很久。
|
|
1510
|
+
*
|
|
1511
|
+
* 判据:**owner / agent_owner 是写入时被校验过的引用**(owner 必须是本网络 user,
|
|
1512
|
+
* agent_owner 必须是本网络 node),而 assignee 是自由文本。两者冲突时,读一侧应以引用为准。
|
|
1513
|
+
* 没有引用时保留自由文本 —— 它可能是系统外的人(例如「王工」),删掉就等于丢信息。
|
|
1514
|
+
*/
|
|
1515
|
+
/**
|
|
1516
|
+
* 2026-10-31 —— **删节点时要清掉指向它的卡引用**(#3277,实测 31 条悬空)。
|
|
1517
|
+
*
|
|
1518
|
+
* 实测:三个已删除的 node id 仍被 27 张卡引用,其中两个 id 在 api_tokens 里还有绑定行
|
|
1519
|
+
* ⇒ 悬空不是录入错误,是**删除路径的缺口**;而读侧把它显示成「负责人是 n_xxxx」。
|
|
1520
|
+
*
|
|
1521
|
+
* 处理:
|
|
1522
|
+
* · agent_owner 指向该节点 ⇒ 置空(卡本身不动,它是正确的)
|
|
1523
|
+
* · participants 含该节点 ⇒ 从列表里摘掉
|
|
1524
|
+
* · owner 是**人**,删节点不影响它 ⇒ 不动
|
|
1525
|
+
* 返回 { agentOwnerCleared, participantsTouched },供删除路径写进审计。
|
|
1526
|
+
*/
|
|
1527
|
+
export function clearNodeFromRequirements(nodeId: string): { agentOwnerCleared: number; participantsTouched: number } {
|
|
1528
|
+
const needle = `"id":"${nodeId}"`;
|
|
1529
|
+
let agentOwnerCleared = 0;
|
|
1530
|
+
const owners = db.all<{ requirement_id: string }>(
|
|
1531
|
+
"SELECT requirement_id FROM requirements WHERE agent_owner_json LIKE ?1", `%${needle}%`);
|
|
1532
|
+
for (const row of owners) {
|
|
1533
|
+
db.run("UPDATE requirements SET agent_owner_json = NULL, updated_at = ?2 WHERE requirement_id = ?1",
|
|
1534
|
+
[row.requirement_id, new Date().toISOString()]);
|
|
1535
|
+
agentOwnerCleared += 1;
|
|
1536
|
+
}
|
|
1537
|
+
let participantsTouched = 0;
|
|
1538
|
+
const parts = db.all<{ requirement_id: string; participants_json: string | null }>(
|
|
1539
|
+
"SELECT requirement_id, participants_json FROM requirements WHERE participants_json LIKE ?1", `%${needle}%`);
|
|
1540
|
+
for (const row of parts) {
|
|
1541
|
+
let list: Array<{ kind?: string; id?: string }> = [];
|
|
1542
|
+
try { list = JSON.parse(row.participants_json || "[]") as any[]; } catch { continue; }
|
|
1543
|
+
const next = (list || []).filter((ref) => !(ref?.kind === "node" && ref?.id === nodeId));
|
|
1544
|
+
if (next.length !== (list || []).length) {
|
|
1545
|
+
db.run("UPDATE requirements SET participants_json = ?2, updated_at = ?3 WHERE requirement_id = ?1",
|
|
1546
|
+
[row.requirement_id, JSON.stringify(next), new Date().toISOString()]);
|
|
1547
|
+
participantsTouched += 1;
|
|
1548
|
+
}
|
|
1549
|
+
}
|
|
1550
|
+
return { agentOwnerCleared, participantsTouched };
|
|
1551
|
+
}
|
|
1552
|
+
|
|
1553
|
+
export function refDisplayName(json: string | null | undefined): string {
|
|
1554
|
+
/**
|
|
1555
|
+
* 把写入侧的引用 `{kind,id}` 换回**给人看的名字**(node → nodes.alias,user → users.username)。
|
|
1556
|
+
* 只给**写侧回填**用:读侧不再由它推导 assignee(见 displayAssignee 的注释)。
|
|
1557
|
+
*/
|
|
1558
|
+
let ref: { kind?: string; id?: string; alias?: string; username?: string } | null = null;
|
|
1559
|
+
try { ref = json ? JSON.parse(json) : null; } catch { return ""; }
|
|
1560
|
+
if (!ref) return "";
|
|
1561
|
+
const inline = String(ref.alias || ref.username || "").trim();
|
|
1562
|
+
if (inline) return inline;
|
|
1563
|
+
if (!ref.id) return "";
|
|
1564
|
+
try {
|
|
1565
|
+
if (ref.kind === "node") {
|
|
1566
|
+
const r = db.get<{ alias: string | null }>("SELECT alias FROM nodes WHERE node_id = ?1", ref.id);
|
|
1567
|
+
if (r?.alias) return String(r.alias);
|
|
1568
|
+
} else if (ref.kind === "user") {
|
|
1569
|
+
const r = db.get<{ username: string | null }>("SELECT username FROM users WHERE user_id = ?1", ref.id);
|
|
1570
|
+
if (r?.username) return String(r.username);
|
|
1571
|
+
}
|
|
1572
|
+
} catch { /* 读不到就退回 id */ }
|
|
1573
|
+
return String(ref.id);
|
|
1574
|
+
}
|
|
1575
|
+
|
|
1576
|
+
export function displayAssignee(row: { assignee?: string | null }): string {
|
|
1577
|
+
/**
|
|
1578
|
+
* 2026-10-31 —— **只回显存下来的值,不从引用推导**(两次实测把方向改对了):
|
|
1579
|
+
* · 契约要求「显式 assignee 不被引用覆盖」(requirements-http 老测试)
|
|
1580
|
+
* · 契约也要求「显式清空后就是空」(同文件的 cleared 用例)
|
|
1581
|
+
* 两者合起来意味着:读侧无法区分「从没设过」与「显式清空」⇒ 推导就会猜错其中一边。
|
|
1582
|
+
* ⇒ 漂移的修法放在**写侧回填**(设引用且没显式给 assignee 时),读侧只负责如实显示。
|
|
1583
|
+
*/
|
|
1584
|
+
return String(row.assignee || "").trim();
|
|
1585
|
+
}
|
|
1586
|
+
|
|
1587
|
+
const parseRef = (json: string | null) => { try { return json ? JSON.parse(json) : null; } catch { return null; } };
|
|
1588
|
+
|
|
1589
|
+
/**
|
|
1590
|
+
* 列表的一页(from = listFilters 拼好的「FROM requirements WHERE …」)。没有搜索词:SQL 直接 LIMIT。有搜索词:先按同样的筛选 + 顺序读轻量列(不算子需求计数),
|
|
1591
|
+
* 在这里逐行匹配,凑够 limit + 1 张就停,再按 id 读这一页的完整行。
|
|
1592
|
+
*/
|
|
1593
|
+
function listPage(ctx: RequirementsRequestContext, from: string, baseParams: unknown[], lq: ListQuery): { rows: Row[]; hasMore: boolean; nextCursor: string | null } {
|
|
1594
|
+
const params = [...baseParams];
|
|
1595
|
+
let where = from;
|
|
1596
|
+
if (lq.cursor) {
|
|
1597
|
+
const a = params.push(lq.cursor.createdAt), b = params.push(lq.cursor.id);
|
|
1598
|
+
where += ` AND (created_at < ?${a} OR (created_at = ?${a} AND requirement_id < ?${b}))`;
|
|
1599
|
+
}
|
|
1600
|
+
let rows: Row[];
|
|
1601
|
+
if (!lq.terms.length && lq.tag === null) {
|
|
1602
|
+
rows = db.all<Row>(`SELECT ${SELECT} ${where}${LIST_ORDER} LIMIT ${lq.limit + 1}`, ...params);
|
|
1603
|
+
} else {
|
|
1604
|
+
// seq(任务短号,#2139):启动迁移 ensureRequirementSeq 在 SQLite / PostgreSQL 上都加这一列,SELECT 本来就带它。
|
|
1605
|
+
const light = db.all<LightRow>(`SELECT requirement_id, seq, network_id, created_at, title, description, assignee, tags_json, project_id, owner_json, agent_owner_json, participants_json ${where}${LIST_ORDER}`, ...params);
|
|
1606
|
+
const maps = new Map<string, NameMaps>();
|
|
1607
|
+
const hits: string[] = [];
|
|
1608
|
+
for (const r of light) {
|
|
1609
|
+
let m = maps.get(r.network_id);
|
|
1610
|
+
if (!m) maps.set(r.network_id, m = searchNameMaps(ctx, r.network_id));
|
|
1611
|
+
const row = { name: r.title, description: r.description || "", assignee: displayAssignee(r), tags: storedTags(r.tags_json), project_id: r.project_id, owner: parseRef(r.owner_json), agent_owner: parseRef(r.agent_owner_json), participants: parseRef(r.participants_json) ?? [] };
|
|
1612
|
+
// #471 —— tag= 在这里按存好的标签数组精确比(JSON 列,SQLite / PostgreSQL 写法不同,所以不进 SQL)。
|
|
1613
|
+
if (lq.tag !== null && !row.tags.includes(lq.tag)) continue;
|
|
1614
|
+
if (!lq.terms.length || matchesTaskId(r, lq.idQuery) || matchesTerms(row, lq.terms, m)) hits.push(r.requirement_id);
|
|
1615
|
+
if (hits.length > lq.limit) break;
|
|
1616
|
+
}
|
|
1617
|
+
const byId = new Map(hits.length ? db.all<Row>(`SELECT ${SELECT} FROM requirements WHERE requirement_id IN (${hits.map((_, i) => `?${i + 1}`).join(",")})`, ...hits).map(r => [r.requirement_id, r]) : []);
|
|
1618
|
+
rows = hits.map(id => byId.get(id)).filter((r): r is Row => !!r);
|
|
1619
|
+
}
|
|
1620
|
+
const hasMore = rows.length > lq.limit;
|
|
1621
|
+
if (hasMore) rows = rows.slice(0, lq.limit);
|
|
1622
|
+
const last = rows[rows.length - 1];
|
|
1623
|
+
return { rows, hasMore, nextCursor: hasMore && last ? encodeCursor({ createdAt: last.created_at, id: last.requirement_id }) : null };
|
|
1624
|
+
}
|
|
1625
|
+
|
|
1626
|
+
/** 搜索用的名字表(与 GET /api/requirements/people 同一个显示名规则);调用者看不见的节点不放进来。 */
|
|
1627
|
+
function searchNameMaps(ctx: RequirementsRequestContext, networkId: string): NameMaps {
|
|
1628
|
+
const hidden = hiddenNodeFilter(ctx, networkId);
|
|
1629
|
+
const people = new Map<string, string>();
|
|
1630
|
+
for (const u of db.all<{ id: string; name: string }>("SELECT u.user_id AS id, COALESCE(NULLIF(u.display_name,''), u.username) AS name FROM network_members m JOIN users u ON u.user_id=m.user_id WHERE m.network_id=?1", networkId)) people.set(`user:${u.id}`, u.name);
|
|
1631
|
+
for (const n of db.all<{ id: string; name: string }>("SELECT node_id AS id, COALESCE(NULLIF(display_name,''), NULLIF(alias,''), node_name) AS name FROM nodes WHERE network_id=?1", networkId)) if (!hidden?.(n.id)) people.set(`node:${n.id}`, n.name);
|
|
1632
|
+
const projects = new Map(db.all<{ project_id: string; name: string }>("SELECT project_id, name FROM requirement_projects WHERE network_id=?1", networkId).map(p => [p.project_id, p.name] as const));
|
|
1633
|
+
return { people, projects };
|
|
1634
|
+
}
|
|
1635
|
+
|
|
1636
|
+
/** 这个节点对调用者在他作用域内的某个受限网络里是否隐藏。 */
|
|
1637
|
+
function hiddenFilterForScope(ctx: RequirementsRequestContext, nodeId: string): boolean {
|
|
1638
|
+
const restricted = ctx.scope.agentRestriction?.networkIds ?? [];
|
|
1639
|
+
for (const networkId of restricted) {
|
|
1640
|
+
const hidden = hiddenNodeFilter(ctx, networkId);
|
|
1641
|
+
if (hidden?.(nodeId)) return true;
|
|
1642
|
+
}
|
|
1643
|
+
return false;
|
|
1644
|
+
}
|
|
1645
|
+
|
|
1646
|
+
// ── 列表省流(2026-09-30,App「连接较慢 · 数据可能稍有延迟」)──
|
|
1647
|
+
// 生产:425 张卡、1447 条子任务,整张表 1 MB(gzip 240 KB),任务页每 15 s 读一次;中国经 RELAY 的链路上
|
|
1648
|
+
// 一次要好几秒。三件事,都是加法,旧 App 不带新参数就与原来逐字相同:
|
|
1649
|
+
// 1. view=summary:不带描述正文和子任务条目(打开一张卡再 GET /api/requirements/:id 读全文);
|
|
1650
|
+
// 2. changes=1 + updated_since:只回这之后改过的卡(含归档的),加上删掉的卡的 id 和下次用的 server_time;
|
|
1651
|
+
// 3. 表没变时不重算:按「调用者 + 查询」缓存上一次的正文和 ETag,需求表一有写入就作废(见 requirementsGeneration)。
|
|
1652
|
+
|
|
1653
|
+
/** view=summary 的一行:去掉 description / checklist,换成 has_description 和 checklist_count。 */
|
|
1654
|
+
function toSummary<T extends { description: string; checklist: ChecklistItem[] }>(pub: T): Omit<T, "description" | "checklist"> & { has_description: boolean; checklist_count: { total: number; done: number } } {
|
|
1655
|
+
const { description, checklist, ...rest } = pub;
|
|
1656
|
+
return { ...rest, has_description: !!description, checklist_count: { total: checklist.length, done: checklist.filter(item => item.done).length } };
|
|
1657
|
+
}
|
|
1658
|
+
|
|
1659
|
+
/** 墓碑保留多久。changes 的 updated_since 早于这之前,删除就可能漏报 —— 响应里的 tombstones_since 告诉客户端这个下限。 */
|
|
1660
|
+
export const TOMBSTONE_RETENTION_MS = 30 * 86_400_000;
|
|
1661
|
+
|
|
1662
|
+
/** 删卡时留一条墓碑(连同判断「谁看得见」要用的列,受限成员只收到他本来看得见的卡的删除)。 */
|
|
1663
|
+
function recordTombstone(row: Row, deletedAt: string): void {
|
|
1664
|
+
db.run(
|
|
1665
|
+
`INSERT INTO requirement_tombstones (requirement_id, network_id, deleted_at, project_id, owner_json, participants_json, created_by, created_by_json)
|
|
1666
|
+
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)
|
|
1667
|
+
ON CONFLICT(requirement_id) DO UPDATE SET deleted_at = excluded.deleted_at`,
|
|
1668
|
+
[row.requirement_id, row.network_id, deletedAt, row.project_id || null, row.owner_json || null, row.participants_json || null, row.created_by || null, row.created_by_json || null],
|
|
1669
|
+
);
|
|
1670
|
+
db.run("DELETE FROM requirement_tombstones WHERE deleted_at < ?1", [new Date(Date.parse(deletedAt) - TOMBSTONE_RETENTION_MS).toISOString()]);
|
|
1671
|
+
}
|
|
1672
|
+
|
|
1673
|
+
type TombstoneRow = { requirement_id: string; network_id: string; deleted_at: string; project_id: string | null; owner_json: string | null; participants_json: string | null; created_by: string | null; created_by_json: string | null };
|
|
1674
|
+
|
|
1675
|
+
/** updated_since 之后删掉的、调用者看得见的卡。同 id 又出现在表里的(不该有)不算删除。 */
|
|
1676
|
+
function deletedSince(ctx: RequirementsRequestContext, sinceIso: string): string[] {
|
|
1677
|
+
const params: unknown[] = [sinceIso];
|
|
1678
|
+
let sql = "SELECT requirement_id, network_id, deleted_at, project_id, owner_json, participants_json, created_by, created_by_json FROM requirement_tombstones WHERE deleted_at >= ?1";
|
|
1679
|
+
sql = addHumanNetworkScope(sql, params, ctx.scope);
|
|
1680
|
+
sql += " AND requirement_id NOT IN (SELECT requirement_id FROM requirements) ORDER BY deleted_at, requirement_id";
|
|
1681
|
+
const caller = taskCaller(ctx);
|
|
1682
|
+
return db.all<TombstoneRow>(sql, ...params).filter(row => canSeeTask(caller, row)).map(row => row.requirement_id);
|
|
1683
|
+
}
|
|
1684
|
+
|
|
1685
|
+
// ── 列表每行的「最新动态」(#506)──
|
|
1686
|
+
// 卡片上一行「谁 · 刚刚 · 干了什么」。以前 App 只能拿 updatedAt / updated_by 拼,评论不改卡、所以不算;也说不出改了什么。
|
|
1687
|
+
// 这里从 requirement_events(评论也在里面,kind=comment)取每张卡最新的一条:一页只一次查询
|
|
1688
|
+
// (MAX(id) GROUP BY,走 idx_requirement_events_card;SQLite / PostgreSQL 同一句),再按出现的人一次查名字。
|
|
1689
|
+
// 只算这一页的卡(已经按调用者可见范围筛过);受限成员看不见的节点:actor 隐去,
|
|
1690
|
+
// 人员字段(owner / agent_owner / participants)的改动隐去之后前后一样的,只剩「改过」(field / summary 都不给)——
|
|
1691
|
+
// 与 updatedAt 透露的信息相同,不多泄一个字。180 天保留期外 / 没有流水的卡 = null。
|
|
1692
|
+
export type LastEvent = {
|
|
1693
|
+
type: string;
|
|
1694
|
+
field: string | null;
|
|
1695
|
+
actor: { id: string; kind: "user" | "node"; display_name: string | null } | null;
|
|
1696
|
+
at: string;
|
|
1697
|
+
summary?: string;
|
|
1698
|
+
};
|
|
1699
|
+
const LAST_EVENT_SUMMARY_MAX = 120;
|
|
1700
|
+
const clip = (s: string) => (s.length > LAST_EVENT_SUMMARY_MAX ? `${s.slice(0, LAST_EVENT_SUMMARY_MAX - 1)}…` : s);
|
|
1701
|
+
const isRef = (v: unknown): v is { kind: string; id: string } => !!v && typeof v === "object" && typeof (v as { id?: unknown }).id === "string" && ((v as { kind?: unknown }).kind === "user" || (v as { kind?: unknown }).kind === "node");
|
|
1702
|
+
|
|
1703
|
+
/** 一条流水 → 一句话(人员字段不给:名字另有 actor 显示,引用里的 id 对卡片没用)。 */
|
|
1704
|
+
function lastEventSummary(ev: ReturnType<typeof eventPublic>): string | undefined {
|
|
1705
|
+
const text = (v: unknown) => (v === null || v === undefined || v === "" ? "—" : String(v));
|
|
1706
|
+
if (ev.kind === "comment") {
|
|
1707
|
+
const t = (ev.new as { text?: unknown } | null)?.text;
|
|
1708
|
+
return typeof t === "string" ? clip(t.replace(/\s+/g, " ").trim()) : undefined;
|
|
1709
|
+
}
|
|
1710
|
+
if (ev.kind !== "changed") return undefined;
|
|
1711
|
+
switch (ev.field) {
|
|
1712
|
+
case "column": case "priority": case "due": case "start": case "archived": case "project": case "parent":
|
|
1713
|
+
return clip(`${text(ev.old)} → ${text(ev.new)}`);
|
|
1714
|
+
case "title": return typeof ev.new === "string" ? clip(ev.new) : undefined;
|
|
1715
|
+
case "checklist_item": {
|
|
1716
|
+
const item = ev.new as { text?: unknown; done?: unknown } | null;
|
|
1717
|
+
return item && typeof item.text === "string" ? clip(`${item.done ? "[x]" : "[ ]"} ${item.text}`) : undefined;
|
|
1718
|
+
}
|
|
1719
|
+
case "checklist": {
|
|
1720
|
+
const c = ev.new as { total?: unknown; done?: unknown } | null;
|
|
1721
|
+
return c ? `${Number(c.done ?? 0)}/${Number(c.total ?? 0)}` : undefined;
|
|
1722
|
+
}
|
|
1723
|
+
case "tags": return Array.isArray(ev.new) ? clip(ev.new.join(", ")) : undefined;
|
|
1724
|
+
default: return undefined;
|
|
1725
|
+
}
|
|
1726
|
+
}
|
|
1727
|
+
|
|
1728
|
+
function lastEventsFor(ctx: RequirementsRequestContext, rows: readonly Row[]): Map<string, LastEvent> {
|
|
1729
|
+
const out = new Map<string, LastEvent>();
|
|
1730
|
+
if (!rows.length) return out;
|
|
1731
|
+
const ids = rows.map(r => r.requirement_id);
|
|
1732
|
+
const marks = ids.map((_, i) => `?${i + 1}`).join(",");
|
|
1733
|
+
const events = db.all<EventRow>(
|
|
1734
|
+
`SELECT id, network_id, requirement_id, seq, title, actor_json, kind, field, old_json, new_json, created_at FROM requirement_events
|
|
1735
|
+
WHERE id IN (SELECT MAX(id) FROM requirement_events WHERE requirement_id IN (${marks}) GROUP BY requirement_id)`,
|
|
1736
|
+
...ids,
|
|
1737
|
+
);
|
|
1738
|
+
if (!events.length) return out;
|
|
1739
|
+
const aware = knowsAbandoned(ctx);
|
|
1740
|
+
// 投影后成了 done → done 的那条:当作没有可展示的字段(同下面隐去节点的处理)。
|
|
1741
|
+
const pubs = events.map(e => { const ev = eventPublic(e); return projectEvent(ev, aware) ?? { ...ev, field: null, old: null, new: null }; });
|
|
1742
|
+
const userIds = new Set<string>(), nodeIds = new Set<string>();
|
|
1743
|
+
for (const ev of pubs) if (isRef(ev.actor)) (ev.actor.kind === "user" ? userIds : nodeIds).add(ev.actor.id);
|
|
1744
|
+
// 名字规则同 GET /api/requirements/people 的 name(没设显示名 → 用户名 / alias / node_name)。
|
|
1745
|
+
const names = new Map<string, string>();
|
|
1746
|
+
if (userIds.size) {
|
|
1747
|
+
const u = [...userIds];
|
|
1748
|
+
for (const r of db.all<{ id: string; name: string }>(`SELECT user_id AS id, COALESCE(NULLIF(display_name,''), username) AS name FROM users WHERE user_id IN (${u.map((_, i) => `?${i + 1}`).join(",")})`, ...u)) names.set(`user:${r.id}`, r.name);
|
|
1749
|
+
}
|
|
1750
|
+
if (nodeIds.size) {
|
|
1751
|
+
const n = [...nodeIds];
|
|
1752
|
+
for (const r of db.all<{ id: string; name: string }>(`SELECT node_id AS id, COALESCE(NULLIF(display_name,''), NULLIF(alias,''), node_name) AS name FROM nodes WHERE node_id IN (${n.map((_, i) => `?${i + 1}`).join(",")})`, ...n)) names.set(`node:${r.id}`, r.name);
|
|
1753
|
+
}
|
|
1754
|
+
const networkOf = new Map(rows.map(r => [r.requirement_id, r.network_id] as const));
|
|
1755
|
+
const hiddenBy = new Map<string, HiddenNode>();
|
|
1756
|
+
for (const ev of pubs) {
|
|
1757
|
+
const networkId = networkOf.get(ev.requirement_id)!;
|
|
1758
|
+
if (!hiddenBy.has(networkId)) hiddenBy.set(networkId, hiddenNodeFilter(ctx, networkId));
|
|
1759
|
+
const hidden = hiddenBy.get(networkId)!;
|
|
1760
|
+
const actor = isRef(ev.actor) && !isHiddenRef(ev.actor, hidden)
|
|
1761
|
+
? { id: ev.actor.id, kind: ev.actor.kind as "user" | "node", display_name: names.get(`${ev.actor.kind}:${ev.actor.id}`) ?? null }
|
|
1762
|
+
: null;
|
|
1763
|
+
let field = ev.field;
|
|
1764
|
+
let summary = lastEventSummary(ev);
|
|
1765
|
+
if (hidden && (field === "owner" || field === "agent_owner" || field === "participants")) {
|
|
1766
|
+
const strip = (v: unknown) => (Array.isArray(v) ? v.filter(ref => !isHiddenRef(ref, hidden)) : isHiddenRef(v, hidden) ? null : v);
|
|
1767
|
+
if (JSON.stringify(strip(ev.old)) === JSON.stringify(strip(ev.new))) { field = null; summary = undefined; }
|
|
1768
|
+
}
|
|
1769
|
+
const last: LastEvent = { type: ev.kind, field, actor, at: ev.at };
|
|
1770
|
+
if (summary !== undefined) last.summary = summary;
|
|
1771
|
+
out.set(ev.requirement_id, last);
|
|
1772
|
+
}
|
|
1773
|
+
return out;
|
|
1774
|
+
}
|
|
1775
|
+
|
|
1776
|
+
// ── 任务动态(requirement-events.ts)──
|
|
1777
|
+
// GET /api/requirements/events?network_id&since&limit&cursor&requirement_id:一个网络的改动流水,按 id 从新到旧。
|
|
1778
|
+
// 可见范围与列表相同:卡还在 → 按当前这张卡判断调用者看不看得见;删掉了 → 按墓碑(过了墓碑保留期的删除,
|
|
1779
|
+
// 只有不受任务范围限制的调用者看得到)。受限成员看不见的节点:操作者隐去,负责人 / 负责 Agent / 参与人里的隐去,
|
|
1780
|
+
// 隐去之后前后一样的那条整条不回(否则是「这张卡的 Agent 换过」的探测器)。
|
|
1781
|
+
// 按可见性过滤是在读出来之后做的:一页最多扫 EVENTS_SCAN_MAX 条,扫满还没凑够就带 next_cursor 回去,客户端接着翻。
|
|
1782
|
+
const EVENTS_PAGE_DEFAULT = 200;
|
|
1783
|
+
const EVENTS_PAGE_MAX = 500;
|
|
1784
|
+
const EVENTS_SCAN_MAX = 5000;
|
|
1785
|
+
type VisibilityRow = { network_id: string; owner_json: string | null; participants_json: string | null; created_by: string | null; created_by_json: string | null; project_id: string | null; agent_owner_json?: string | null };
|
|
1786
|
+
|
|
1787
|
+
function listEvents(ctx: RequirementsRequestContext): Response {
|
|
1788
|
+
const networkId = resolveRestWriteNetworkId(ctx.scope, ctx.auth, ctx.isAdmin);
|
|
1789
|
+
if (!networkId) return jsonError("network_id_required", 400);
|
|
1790
|
+
const q = ctx.url.searchParams;
|
|
1791
|
+
const limit = q.get("limit") === null ? EVENTS_PAGE_DEFAULT : Number(q.get("limit"));
|
|
1792
|
+
if (!Number.isInteger(limit) || limit < 1 || limit > EVENTS_PAGE_MAX) return jsonError("invalid_limit", 400);
|
|
1793
|
+
let since: string | null = null;
|
|
1794
|
+
if (q.get("since") !== null) {
|
|
1795
|
+
const ms = Date.parse(q.get("since")!);
|
|
1796
|
+
if (!Number.isFinite(ms)) return jsonError("invalid_since", 400);
|
|
1797
|
+
since = new Date(ms).toISOString();
|
|
1798
|
+
}
|
|
1799
|
+
const cursor = q.get("cursor");
|
|
1800
|
+
if (cursor !== null && !/^[1-9]\d{0,17}$/.test(cursor)) return jsonError("invalid_cursor", 400);
|
|
1801
|
+
const card = q.get("requirement_id");
|
|
1802
|
+
// server_time 取在读表之前:下次拿它当 since,读的期间写进来的不会漏(>= 会重复回,客户端按 id 去重)。
|
|
1803
|
+
const serverTime = new Date().toISOString();
|
|
1804
|
+
const caller = taskCaller(ctx);
|
|
1805
|
+
const hidden = hiddenNodeFilter(ctx, networkId);
|
|
1806
|
+
// 2026-10-31 —— `assignee` 是**派生展示字段**,存的是**别名字符串**,不是 {kind,id} 引用。
|
|
1807
|
+
// 于是它绕过了 isHiddenRef:受限成员会在事件里读到「某个他看不见的 Agent 的名字」。
|
|
1808
|
+
// 实测(本仓):把 agent_owner 设成一个受限成员看不见的节点后,事件列表里多出
|
|
1809
|
+
// { field:"assignee", old:null, new:"<那个节点的别名>" }
|
|
1810
|
+
// 而同一张卡的 agent_owner 事件已被正确抹掉 ⇒ 名字从旁边漏了出去。
|
|
1811
|
+
// 修法:按「隐藏节点的别名集合」判,命中就抹成 null;随后「抹后 old==new」的规则会把整条丢弃。
|
|
1812
|
+
// 方向选择:宁可多抹(隐藏)也不多露 —— 别名与人名冲突时,少显示一个名字的代价小于多露一个。
|
|
1813
|
+
const aliasSet = hiddenNodeAliases(ctx, networkId);
|
|
1814
|
+
const hiddenAlias = (v: unknown): boolean => !!hidden && typeof v === "string" && v !== "" && aliasSet.has(v);
|
|
1815
|
+
const aware = knowsAbandoned(ctx);
|
|
1816
|
+
const seen = new Map<string, boolean>();
|
|
1817
|
+
const canSee = (id: string): boolean => {
|
|
1818
|
+
if (!caller) return true;
|
|
1819
|
+
let ok = seen.get(id);
|
|
1820
|
+
if (ok === undefined) {
|
|
1821
|
+
const cols = "network_id, owner_json, participants_json, created_by, created_by_json, project_id";
|
|
1822
|
+
// agent_owner_json:负责人按「负责 Agent 归本部门成员」也认得这张卡(RFC-040);墓碑表没有这一列。
|
|
1823
|
+
const row = db.get<VisibilityRow>(`SELECT ${cols}, agent_owner_json FROM requirements WHERE requirement_id = ?1`, id)
|
|
1824
|
+
?? db.get<VisibilityRow>(`SELECT ${cols} FROM requirement_tombstones WHERE requirement_id = ?1`, id);
|
|
1825
|
+
seen.set(id, ok = !!row && row.network_id === networkId && canSeeTask(caller, row));
|
|
1826
|
+
}
|
|
1827
|
+
return ok;
|
|
1828
|
+
};
|
|
1829
|
+
const shown = (row: EventRow) => {
|
|
1830
|
+
if (!canSee(row.requirement_id)) return null;
|
|
1831
|
+
const ev = projectEvent(eventPublic(row), aware);
|
|
1832
|
+
if (!ev) return null;
|
|
1833
|
+
if (!hidden) return ev;
|
|
1834
|
+
const mask = (ref: unknown) => (isHiddenRef(ref, hidden) ? null : ref);
|
|
1835
|
+
const masked = { ...ev, actor: mask(ev.actor) };
|
|
1836
|
+
if (ev.field === "owner" || ev.field === "agent_owner") { masked.old = mask(ev.old); masked.new = mask(ev.new); }
|
|
1837
|
+
if (ev.field === "assignee") {
|
|
1838
|
+
// 见上:别名字符串同样要按隐藏节点判定
|
|
1839
|
+
masked.old = hiddenAlias(ev.old) ? null : ev.old;
|
|
1840
|
+
masked.new = hiddenAlias(ev.new) ? null : ev.new;
|
|
1841
|
+
}
|
|
1842
|
+
if (ev.field === "participants") {
|
|
1843
|
+
masked.old = Array.isArray(ev.old) ? ev.old.filter(ref => !isHiddenRef(ref, hidden)) : ev.old;
|
|
1844
|
+
masked.new = Array.isArray(ev.new) ? ev.new.filter(ref => !isHiddenRef(ref, hidden)) : ev.new;
|
|
1845
|
+
}
|
|
1846
|
+
return ev.field && JSON.stringify(masked.old) === JSON.stringify(masked.new) ? null : masked;
|
|
1847
|
+
};
|
|
1848
|
+
const events: ReturnType<typeof eventPublic>[] = [];
|
|
1849
|
+
let before = cursor === null ? null : Number(cursor);
|
|
1850
|
+
let scanned = 0;
|
|
1851
|
+
let nextCursor: string | null = null;
|
|
1852
|
+
scan: for (;;) {
|
|
1853
|
+
const params: unknown[] = [networkId];
|
|
1854
|
+
let sql = "SELECT id, network_id, requirement_id, seq, title, actor_json, kind, field, old_json, new_json, created_at FROM requirement_events WHERE network_id = ?1";
|
|
1855
|
+
if (since) sql += ` AND created_at >= ?${params.push(since)}`;
|
|
1856
|
+
if (card) sql += ` AND requirement_id = ?${params.push(card)}`;
|
|
1857
|
+
if (before !== null) sql += ` AND id < ?${params.push(before)}`;
|
|
1858
|
+
const batch = db.all<EventRow>(`${sql} ORDER BY id DESC LIMIT ${limit + 1}`, ...params);
|
|
1859
|
+
for (const row of batch) {
|
|
1860
|
+
const ev = shown(row);
|
|
1861
|
+
if (ev && events.length === limit) { nextCursor = events[events.length - 1].id; break scan; }
|
|
1862
|
+
scanned++;
|
|
1863
|
+
before = Number(row.id);
|
|
1864
|
+
if (ev) events.push(ev);
|
|
1865
|
+
}
|
|
1866
|
+
if (batch.length < limit + 1) break;
|
|
1867
|
+
// 扫满了(调用者看不见的太多):从扫到的地方接着翻。
|
|
1868
|
+
if (scanned >= EVENTS_SCAN_MAX) { nextCursor = String(before); break; }
|
|
1869
|
+
}
|
|
1870
|
+
return Response.json({ ok: true, network_id: networkId, events, has_more: nextCursor !== null, next_cursor: nextCursor, server_time: serverTime });
|
|
1871
|
+
}
|
|
1872
|
+
|
|
1873
|
+
/**
|
|
1874
|
+
* 需求表的写入代数:每个经过 handleRequirementsRequest 的非 GET 请求处理完就 +1(REST 和 MCP 的写入都走它,
|
|
1875
|
+
* tools.ts 调的是同一个处理函数)。列表缓存只在代数没变时复用。进程重启 = 缓存清空。
|
|
1876
|
+
*/
|
|
1877
|
+
let requirementsGeneration = 0;
|
|
1878
|
+
/** 缓存条目最长信任这么久:兜住不经过处理函数的改动(启动迁移、运维脚本直接改库)。 */
|
|
1879
|
+
export const LIST_CACHE_MAX_AGE_MS = 60_000;
|
|
1880
|
+
/** 只缓存不带搜索词的列表(搜索每打一个字就是一个新键),总共最多这么多字符(条目按最近使用淘汰)。 */
|
|
1881
|
+
const LIST_CACHE_MAX_CHARS = 16 * 1024 * 1024;
|
|
1882
|
+
type ListCacheEntry = { generation: number; acl: string; at: number; body: string; etag: string };
|
|
1883
|
+
const listCache = new Map<string, ListCacheEntry>();
|
|
1884
|
+
let listCacheChars = 0;
|
|
1885
|
+
function rememberList(key: string, entry: ListCacheEntry): void {
|
|
1886
|
+
const old = listCache.get(key);
|
|
1887
|
+
if (old) { listCache.delete(key); listCacheChars -= old.body.length; }
|
|
1888
|
+
if (entry.body.length > LIST_CACHE_MAX_CHARS / 4) return;
|
|
1889
|
+
listCache.set(key, entry);
|
|
1890
|
+
listCacheChars += entry.body.length;
|
|
1891
|
+
for (const [k, v] of listCache) {
|
|
1892
|
+
if (listCacheChars <= LIST_CACHE_MAX_CHARS) break;
|
|
1893
|
+
listCache.delete(k);
|
|
1894
|
+
listCacheChars -= v.body.length;
|
|
1895
|
+
}
|
|
1896
|
+
}
|
|
1897
|
+
|
|
1898
|
+
/**
|
|
1899
|
+
* 缓存能不能用、以及调用者权限的指纹。null = 这个调用者不缓存:受限成员(看得见哪些 Agent 取决于节点表)
|
|
1900
|
+
* 和「只看相关任务」的成员(看得见哪些卡取决于项目授权)每次照旧现算。
|
|
1901
|
+
* 其余调用者的输出只取决于需求表本身 + 他的角色 / 成员行:这些都放进指纹,变了就不命中。
|
|
1902
|
+
*/
|
|
1903
|
+
function listCacheAcl(ctx: RequirementsRequestContext): string | null {
|
|
1904
|
+
const caller = taskCaller(ctx);
|
|
1905
|
+
if (!caller) return `open:${ctx.isAdmin ? 1 : 0}:${ctx.isNodeToken ? 1 : 0}`;
|
|
1906
|
+
if (caller.node) return null; // 按节点收窄的列表不缓存(模式随时可改)
|
|
1907
|
+
if (restrictedNetworkIds(caller.userId).length > 0) return null;
|
|
1908
|
+
const members = db.all<Record<string, unknown>>("SELECT * FROM network_members WHERE user_id = ?1 ORDER BY network_id", caller.userId);
|
|
1909
|
+
const networks = members.map(m => String(m.network_id));
|
|
1910
|
+
if (networks.some(networkId => isTaskScoped(caller.userId, networkId))) return null;
|
|
1911
|
+
const role = db.get<{ role: string | null }>("SELECT role FROM users WHERE user_id = ?1", caller.userId)?.role ?? null;
|
|
1912
|
+
return JSON.stringify({ role, members });
|
|
1913
|
+
}
|
|
1914
|
+
|
|
1915
|
+
function listCacheKey(ctx: RequirementsRequestContext): string {
|
|
1916
|
+
const sorted = [...ctx.url.searchParams.entries()].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
|
|
1917
|
+
return JSON.stringify({ u: ctx.auth?.userId ?? null, n: ctx.auth?.networkId ?? null, a: ctx.isAdmin, t: ctx.isNodeToken, s: ctx.scope, q: sorted, c: knowsAbandoned(ctx) });
|
|
1918
|
+
}
|
|
1919
|
+
|
|
1920
|
+
/** Test-only. */
|
|
1921
|
+
export function __requirementsListCacheForTest() {
|
|
1922
|
+
return { size: () => listCache.size, clear: () => { listCache.clear(); listCacheChars = 0; }, generation: () => requirementsGeneration };
|
|
1923
|
+
}
|
|
1924
|
+
|
|
1925
|
+
export async function handleRequirementsRequest(ctx: RequirementsRequestContext): Promise<Response | null> {
|
|
1926
|
+
const { url } = ctx;
|
|
1927
|
+
if (url.pathname !== "/api/requirements" && !url.pathname.startsWith("/api/requirements/")) return null;
|
|
1928
|
+
if (ctx.req.method === "GET") return handleRequirementsRequestInner(ctx);
|
|
1929
|
+
// 写完(成功与否)才 +1:之后的 GET 一定看得见这次写入。
|
|
1930
|
+
try { return await handleRequirementsRequestInner(ctx); } finally { requirementsGeneration++; }
|
|
1931
|
+
}
|
|
1932
|
+
|
|
1933
|
+
async function handleRequirementsRequestInner(ctx: RequirementsRequestContext): Promise<Response | null> {
|
|
1934
|
+
const { req, url } = ctx;
|
|
1935
|
+
// 节点令牌只能做 NODE_TOKEN_OPERATIONS 里的事(读 / 建 / 改 / 勾子任务 / upsert / 读项目),
|
|
1936
|
+
// 而且只在它绑定的网络里 —— 范围由 scope 强制,写入再由 canWrite 核一次。
|
|
1937
|
+
if (ctx.isNodeToken && !NODE_TOKEN_OPERATIONS.has(operationOf(req, url))) return jsonError("user_token_required", 403);
|
|
1938
|
+
|
|
1939
|
+
if (url.pathname === "/api/requirements/projects" || url.pathname.startsWith("/api/requirements/projects/")) return handleProjects(ctx);
|
|
1940
|
+
|
|
1941
|
+
if (url.pathname === "/api/requirements/tags" && req.method === "GET") {
|
|
1942
|
+
const networkId = resolveRestWriteNetworkId(ctx.scope, ctx.auth, ctx.isAdmin);
|
|
1943
|
+
if (!networkId) return jsonError("network_id_required", 400);
|
|
1944
|
+
const tagParams: unknown[] = [networkId];
|
|
1945
|
+
const tagSql = addTaskVisibilityScope("SELECT tags_json FROM requirements WHERE network_id=?1", tagParams, taskCaller(ctx));
|
|
1946
|
+
const rows = db.all<{ tags_json: string | null }>(tagSql, ...tagParams);
|
|
1947
|
+
// counts:调用者看得见的卡里(含归档)每个标签用了几张;colors:只回这些标签的颜色(看不见的卡上的标签不外泄)。
|
|
1948
|
+
// can_manage:这个调用者能不能用 /tags/ops /tags/create。旧 App 只读 tags,多出的字段忽略。
|
|
1949
|
+
const counts: Record<string, number> = {};
|
|
1950
|
+
for (const row of rows) for (const tag of storedTags(row.tags_json)) counts[tag] = (counts[tag] ?? 0) + 1;
|
|
1951
|
+
const tags = Object.keys(counts).sort();
|
|
1952
|
+
const manageable = canManageTags(ctx, networkId);
|
|
1953
|
+
// nodes:标签树。登记过的节点(create 建的,含 0 任务)∪ 调用者看得见的在用标签。
|
|
1954
|
+
// 受限成员只拿得到「看得见的名字」:登记过但一张可见卡都没有的标签不外泄(与 counts / colors 同一口径)。
|
|
1955
|
+
const registeredRows = db.all<TagNodeRow>("SELECT name, parent_name FROM network_tag_nodes WHERE network_id = ?1", networkId);
|
|
1956
|
+
const visibleRegistered = manageable ? registeredRows : registeredRows.filter(row => counts[row.name] > 0);
|
|
1957
|
+
const nodeNames = new Set([...registeredRows.map(row => row.name), ...tags]);
|
|
1958
|
+
const colors: Record<string, string> = {};
|
|
1959
|
+
for (const row of db.all<{ name: string; color: string }>("SELECT name, color FROM network_tags WHERE network_id = ?1", networkId)) {
|
|
1960
|
+
if (counts[row.name] || (manageable && nodeNames.has(row.name))) colors[row.name] = row.color;
|
|
1961
|
+
}
|
|
1962
|
+
const nodes = buildTagNodes(visibleRegistered, tags).map(node => ({ ...node, count: counts[node.name] ?? 0, color: colors[node.name] ?? null }));
|
|
1963
|
+
return Response.json({ ok: true, networkId, tags, counts, colors, nodes, can_manage: manageable });
|
|
1964
|
+
}
|
|
1965
|
+
|
|
1966
|
+
if (url.pathname === "/api/requirements/tags/ops") {
|
|
1967
|
+
if (req.method !== "POST") return jsonError("not_found", 404);
|
|
1968
|
+
return handleTagOp(ctx);
|
|
1969
|
+
}
|
|
1970
|
+
|
|
1971
|
+
// 建标签(可带 parent_id)。原子:节点 + 审计在一个事务里;父不存在 404,绝不安静建到根上。
|
|
1972
|
+
if (url.pathname === "/api/requirements/tags/create") {
|
|
1973
|
+
if (req.method !== "POST") return jsonError("not_found", 404);
|
|
1974
|
+
return handleTagCreate(ctx);
|
|
1975
|
+
}
|
|
1976
|
+
|
|
1977
|
+
// 仪表盘聚合(requirements-stats.ts):一个网络、调用者看得见的卡(与列表同一个可见范围),含归档的卡 ——
|
|
1978
|
+
// 完成的卡常被归档,不算它们「今天完成了多少」就会偏少。
|
|
1979
|
+
if (url.pathname === "/api/requirements/stats" && req.method === "GET") {
|
|
1980
|
+
const networkId = resolveRestWriteNetworkId(ctx.scope, ctx.auth, ctx.isAdmin);
|
|
1981
|
+
if (!networkId) return jsonError("network_id_required", 400);
|
|
1982
|
+
const sq = parseStatsQuery(url.searchParams, Date.now());
|
|
1983
|
+
if ("error" in sq) return jsonError(sq.error, 400);
|
|
1984
|
+
const statsParams: unknown[] = [networkId];
|
|
1985
|
+
const statsSql = addTaskVisibilityScope(
|
|
1986
|
+
"SELECT requirement_id, seq, title, project_id, column_name, archived, created_at, completed_at, completed_at_approx, completed_by_json, tags_json FROM requirements WHERE network_id = ?1",
|
|
1987
|
+
statsParams, taskCaller(ctx),
|
|
1988
|
+
);
|
|
1989
|
+
const rows = db.all<StatsRow>(statsSql, ...statsParams);
|
|
1990
|
+
return conditionalJson(ctx.req, { ok: true, networkId, ...aggregateStats(rows, sq, hiddenNodeFilter(ctx, networkId)) });
|
|
1991
|
+
}
|
|
1992
|
+
|
|
1993
|
+
if (url.pathname === "/api/requirements/events" && req.method === "GET") return listEvents(ctx);
|
|
1994
|
+
|
|
1995
|
+
// #473 —— MCP requirements_people:紧凑通讯录(用户名、角色、部门、名下 Agent),q / limit / offset。
|
|
1996
|
+
if (url.pathname === '/api/requirements/people/directory' && req.method === 'GET') {
|
|
1997
|
+
const networkId = resolveRestWriteNetworkId(ctx.scope, ctx.auth, ctx.isAdmin);
|
|
1998
|
+
if (!networkId) return jsonError('network_id_required', 400);
|
|
1999
|
+
const pq = parsePeopleQuery(url.searchParams);
|
|
2000
|
+
if ('error' in pq) return jsonError(pq.error, 400);
|
|
2001
|
+
return Response.json(peopleDirectory(networkId, hiddenNodeFilter(ctx, networkId), pq));
|
|
2002
|
+
}
|
|
2003
|
+
|
|
2004
|
+
if (url.pathname === '/api/requirements/people' && req.method === 'GET') {
|
|
2005
|
+
const networkId = resolveRestWriteNetworkId(ctx.scope, ctx.auth, ctx.isAdmin);
|
|
2006
|
+
if (!networkId) return jsonError('network_id_required', 400);
|
|
2007
|
+
// name = 显示用的名字(没设 display_name 时回落到用户名 / alias,旧 app 只读它);display_name 单独给出、没设为 ""
|
|
2008
|
+
// —— 分享图等对外场景据此判断「只有用户名」,不把 admin 之类的账号名印出去。
|
|
2009
|
+
// 成员的 display_name 等于用户名也算「没设」:register() 在没给显示名时存的就是 username(auth.ts),
|
|
2010
|
+
// 否则没设过显示名的账号(比如 admin)照样把账号名当显示名送出去。
|
|
2011
|
+
const users = db.all<{ id: string; name: string; display_name: string }>(
|
|
2012
|
+
"SELECT u.user_id AS id, COALESCE(NULLIF(u.display_name,''), u.username) AS name, CASE WHEN u.display_name IS NULL OR u.display_name = '' OR u.display_name = u.username THEN '' ELSE u.display_name END AS display_name FROM network_members m JOIN users u ON u.user_id=m.user_id WHERE m.network_id=?1 ORDER BY name, id", networkId,
|
|
2013
|
+
);
|
|
2014
|
+
const hidden = hiddenNodeFilter(ctx, networkId);
|
|
2015
|
+
const nodes = db.all<{ id: string; name: string; display_name: string }>(
|
|
2016
|
+
"SELECT node_id AS id, COALESCE(NULLIF(display_name,''), NULLIF(alias,''), node_name) AS name, COALESCE(display_name,'') AS display_name FROM nodes WHERE network_id=?1 ORDER BY name, id", networkId,
|
|
2017
|
+
).filter(row => !hidden?.(row.id));
|
|
2018
|
+
return Response.json({ ok: true, people: [...users.map(row => ({ ...row, kind: 'user', networkId })), ...nodes.map(row => ({ ...row, kind: 'node', networkId }))] });
|
|
2019
|
+
}
|
|
2020
|
+
|
|
2021
|
+
if (url.pathname === "/api/requirements" && req.method === "GET") {
|
|
2022
|
+
const params: unknown[] = [];
|
|
2023
|
+
// 只拼 FROM … WHERE:同一组条件既用来读整行,也用来(搜索时)先读轻量列。
|
|
2024
|
+
let sql = "FROM requirements WHERE 1=1";
|
|
2025
|
+
sql = addHumanNetworkScope(sql, params, ctx.scope);
|
|
2026
|
+
sql = addTaskVisibilityScope(sql, params, taskCaller(ctx));
|
|
2027
|
+
const filtered = listFilters(url, sql, params, ctx);
|
|
2028
|
+
if (typeof filtered !== "string") return filtered;
|
|
2029
|
+
// q= / limit / cursor(requirements-search.ts)。都不带 = 旧行为:最新 500 张、同样的顺序。
|
|
2030
|
+
const lq = parseListQuery(url.searchParams);
|
|
2031
|
+
if ("error" in lq) return jsonError(lq.error, 400);
|
|
2032
|
+
const view = url.searchParams.get("view");
|
|
2033
|
+
if (view !== null && view !== "full" && view !== "summary") return jsonError("invalid_view", 400);
|
|
2034
|
+
const changes = url.searchParams.get("changes") === "1";
|
|
2035
|
+
if (changes && url.searchParams.get("updated_since") === null) return jsonError("updated_since_required", 400);
|
|
2036
|
+
// last_event=0:不带每行的 last_event(MCP requirements_list 默认这么调,保住 #471 的 Agent 上下文预算)。不带 / =1 = 带。
|
|
2037
|
+
const lastEventParam = url.searchParams.get("last_event");
|
|
2038
|
+
if (lastEventParam !== null && lastEventParam !== "0" && lastEventParam !== "1") return jsonError("invalid_last_event", 400);
|
|
2039
|
+
const withLastEvent = lastEventParam !== "0";
|
|
2040
|
+
// changes 模式:server_time 取在读表之前,下次拿它当 updated_since,读表期间的写入不会漏(>= 会重复回一次,客户端按 id 覆盖)。
|
|
2041
|
+
const serverTime = new Date().toISOString();
|
|
2042
|
+
nodeReadNote(ctx, "GET /api/requirements", null);
|
|
2043
|
+
// overdue / due_within_days 随时间变化而不随写入变化:不进按 generation 失效的缓存。
|
|
2044
|
+
const cacheKey = changes || url.searchParams.get("q") || url.searchParams.has("overdue") || url.searchParams.has("due_within_days") ? null : listCacheKey(ctx);
|
|
2045
|
+
const acl = cacheKey ? listCacheAcl(ctx) : null;
|
|
2046
|
+
const generation = requirementsGeneration;
|
|
2047
|
+
const cached = cacheKey && acl !== null ? listCache.get(cacheKey) : undefined;
|
|
2048
|
+
if (cached && cached.generation === generation && cached.acl === acl && Date.now() - cached.at < LIST_CACHE_MAX_AGE_MS) {
|
|
2049
|
+
listCache.delete(cacheKey!);
|
|
2050
|
+
listCache.set(cacheKey!, cached);
|
|
2051
|
+
return conditionalBody(ctx.req, cached.body, cached.etag);
|
|
2052
|
+
}
|
|
2053
|
+
const page = listPage(ctx, filtered, params, lq);
|
|
2054
|
+
// last_event(#506):每行最新一条动态(含评论),没有 = null。旧 App 不认识,忽略即可。
|
|
2055
|
+
const lastEvents = withLastEvent ? lastEventsFor(ctx, page.rows) : null;
|
|
2056
|
+
const rows = lastEvents ? page.rows.map(row => ({ ...toPublicFor(ctx, row), last_event: lastEvents.get(row.requirement_id) ?? null })) : page.rows.map(row => toPublicFor(ctx, row));
|
|
2057
|
+
// capabilities:客户端按这个决定显示哪些功能(预计完成能不能带时刻、有没有项目…),不用靠猜字段。
|
|
2058
|
+
// has_more / next_cursor:后面还有没有(带 cursor=next_cursor 再读一页)。旧客户端不认识,忽略即可。
|
|
2059
|
+
const payload: Record<string, unknown> = { ok: true, requirements: view === "summary" ? rows.map(toSummary) : rows, capabilities: REQUIREMENT_CAPABILITIES, has_more: page.hasMore, next_cursor: page.nextCursor };
|
|
2060
|
+
if (view === "summary") payload.view = "summary";
|
|
2061
|
+
if (changes) {
|
|
2062
|
+
const since = new Date(Date.parse(url.searchParams.get("updated_since")!)).toISOString();
|
|
2063
|
+
payload.deleted = deletedSince(ctx, since);
|
|
2064
|
+
payload.server_time = serverTime;
|
|
2065
|
+
payload.tombstones_since = new Date(Date.parse(serverTime) - TOMBSTONE_RETENTION_MS).toISOString();
|
|
2066
|
+
}
|
|
2067
|
+
const body = JSON.stringify(payload);
|
|
2068
|
+
const etag = bodyEtag(body);
|
|
2069
|
+
if (cacheKey && acl !== null) rememberList(cacheKey, { generation, acl, at: Date.now(), body, etag });
|
|
2070
|
+
return conditionalBody(ctx.req, body, etag);
|
|
2071
|
+
}
|
|
2072
|
+
|
|
2073
|
+
if (url.pathname === "/api/requirements" && req.method === "POST") {
|
|
2074
|
+
let body: Record<string, unknown>;
|
|
2075
|
+
try { body = await bodyObject(req); } catch { return jsonError("invalid_json", 400); }
|
|
2076
|
+
return createRequirement(ctx, body);
|
|
2077
|
+
}
|
|
2078
|
+
|
|
2079
|
+
// 按 external_ref 建或改(同步用,幂等):同一网络里已有这个 external_ref → 按 PATCH 语义改它
|
|
2080
|
+
// (省略的字段保留,包括状态);没有 → 新建。重复同步同一个 issue 只会改,不会重复建。
|
|
2081
|
+
if (url.pathname === "/api/requirements/upsert" && req.method === "POST") {
|
|
2082
|
+
let body: Record<string, unknown>;
|
|
2083
|
+
try { body = await bodyObject(req); } catch { return jsonError("invalid_json", 400); }
|
|
2084
|
+
const ref = externalRef(body.external_ref);
|
|
2085
|
+
if (!ref) return jsonError("external_ref_required", 400);
|
|
2086
|
+
const networkId = writeNetwork(body, ctx);
|
|
2087
|
+
if (!networkId) return jsonError("network_id_required", 400);
|
|
2088
|
+
if (!canWrite(ctx, networkId)) return jsonError("permission_denied", 403);
|
|
2089
|
+
// scoped 成员不能用同步接口:external_ref 的唯一索引会把「这个 ref 已经有卡」泄露出去。固定错误,不看 ref。
|
|
2090
|
+
if (taskCaller(ctx) && isTaskScoped(ctx.auth!.userId, networkId)) return jsonError("upsert_not_allowed", 403);
|
|
2091
|
+
const existing = rowByExternalRef(networkId, ref);
|
|
2092
|
+
if (!existing) {
|
|
2093
|
+
const res = await createRequirement(ctx, body);
|
|
2094
|
+
if (res.status !== 201) return res;
|
|
2095
|
+
const data = await res.json() as Record<string, unknown>;
|
|
2096
|
+
return Response.json({ ...data, created: true }, { status: 201 });
|
|
2097
|
+
}
|
|
2098
|
+
const { external_ref: _ref, network_id: _net, client_id: _client, ...patch } = body;
|
|
2099
|
+
if (!PATCH_FIELDS.some(k => Object.prototype.hasOwnProperty.call(patch, k))) {
|
|
2100
|
+
// 没有要改的字段 = 读回这张卡:受限节点只能读派给它的(与列表同一个可见范围)。
|
|
2101
|
+
if (!canSeeTask(taskCaller(ctx), existing)) return jsonError("upsert_not_allowed", 403);
|
|
2102
|
+
return Response.json({ ok: true, requirement: toPublicFor(ctx, existing), created: false });
|
|
2103
|
+
}
|
|
2104
|
+
const res = patchRequirement(ctx, existing, patch);
|
|
2105
|
+
if (res.status !== 200) return res;
|
|
2106
|
+
const data = await res.json() as Record<string, unknown>;
|
|
2107
|
+
return Response.json({ ...data, created: false });
|
|
2108
|
+
}
|
|
2109
|
+
|
|
2110
|
+
// #474 评论 / 进展(MCP 任务生命周期测试报告问题 5):以前 Agent 只能读全文再整段改写 description,两次调用、
|
|
2111
|
+
// 并发会覆盖别人刚写的。评论是一条只追加的动态(requirement_events kind=comment,正文存在 new.text),
|
|
2112
|
+
// 不碰 requirements 表的任何一列;谁能看见这张卡谁就能读到,能写这个网络(非只读角色)又看得见它的人能发。
|
|
2113
|
+
const commentMatch = url.pathname.match(/^\/api\/requirements\/([^/]+)\/comments$/);
|
|
2114
|
+
if (commentMatch) {
|
|
2115
|
+
if (req.method !== "POST") return jsonError("not_found", 404);
|
|
2116
|
+
let body: Record<string, unknown>;
|
|
2117
|
+
try { body = await bodyObject(req); } catch { return jsonError("invalid_json", 400); }
|
|
2118
|
+
const text = typeof body.text === "string" ? body.text.trim() : "";
|
|
2119
|
+
if (!text) return jsonError("invalid_comment", 400);
|
|
2120
|
+
if (text.length > COMMENT_MAX_CHARS) return jsonError("comment_too_long", 400);
|
|
2121
|
+
const row = scopedRow(ctx, decodeURIComponent(commentMatch[1]));
|
|
2122
|
+
if (row instanceof Response) return row;
|
|
2123
|
+
if (!canWrite(ctx, row.network_id)) return jsonError("permission_denied", 403);
|
|
2124
|
+
const nodeDenied = nodeTaskGate(ctx, "POST /api/requirements/:id/comments", row);
|
|
2125
|
+
if (nodeDenied) return nodeDenied;
|
|
2126
|
+
const at = new Date().toISOString();
|
|
2127
|
+
const event = db.transaction(() => {
|
|
2128
|
+
recordRequirementEvents(db, row, JSON.stringify(actorOf(ctx)), [{ kind: "comment", field: null, old: null, new: { text } }], at);
|
|
2129
|
+
return db.get<EventRow>("SELECT id, network_id, requirement_id, seq, title, actor_json, kind, field, old_json, new_json, created_at FROM requirement_events WHERE requirement_id = ?1 AND kind = 'comment' ORDER BY id DESC LIMIT 1", row.requirement_id)!;
|
|
2130
|
+
});
|
|
2131
|
+
return Response.json({ ok: true, event: eventPublic(event) }, { status: 201 });
|
|
2132
|
+
}
|
|
2133
|
+
|
|
2134
|
+
const itemMatch = url.pathname.match(/^\/api\/requirements\/([^/]+)\/checklist\/([^/]+)$/);
|
|
2135
|
+
if (itemMatch) {
|
|
2136
|
+
if (req.method !== "PATCH") return jsonError("not_found", 404);
|
|
2137
|
+
let body: Record<string, unknown>;
|
|
2138
|
+
try { body = await bodyObject(req); } catch { return jsonError("invalid_json", 400); }
|
|
2139
|
+
if (typeof body.done !== "boolean") return jsonError("invalid_done", 400);
|
|
2140
|
+
const row = scopedRow(ctx, decodeURIComponent(itemMatch[1]));
|
|
2141
|
+
if (row instanceof Response) return row;
|
|
2142
|
+
if (!canWrite(ctx, row.network_id)) return jsonError("permission_denied", 403);
|
|
2143
|
+
const nodeDenied = nodeTaskGate(ctx, "PATCH /api/requirements/:id/checklist/:id", row);
|
|
2144
|
+
if (nodeDenied) return nodeDenied;
|
|
2145
|
+
if (!canEditTask(taskCaller(ctx), row) && !canParticipantEditTask(taskCaller(ctx), row)) return taskDenied(ctx, row, "task_read_only");
|
|
2146
|
+
// 读-改-写在同一个同步段里完成(中间没有 await),同一进程里的两次勾选不会交错。
|
|
2147
|
+
const items = storedChecklist(row.checklist_json);
|
|
2148
|
+
const itemId = decodeURIComponent(itemMatch[2]);
|
|
2149
|
+
const item = items.find(entry => entry.id === itemId);
|
|
2150
|
+
if (!item) return jsonError("checklist_item_not_found", 404);
|
|
2151
|
+
const was = item.done;
|
|
2152
|
+
item.done = body.done;
|
|
2153
|
+
const at = new Date().toISOString();
|
|
2154
|
+
const actor = JSON.stringify(actorOf(ctx));
|
|
2155
|
+
const updated = db.transaction(() => {
|
|
2156
|
+
db.run("UPDATE requirements SET checklist_json = ?1, updated_at = ?2, updated_by_json = ?3 WHERE requirement_id = ?4", [JSON.stringify(items), at, actor, row.requirement_id]);
|
|
2157
|
+
// 重复勾同一个值(done 是显式值,幂等)不算一次改动,不记。
|
|
2158
|
+
if (was !== item.done) recordRequirementEvents(db, row, actor, [{ kind: "changed", field: "checklist_item", old: { ...item, done: was }, new: { ...item } }], at);
|
|
2159
|
+
return db.get<Row>(`SELECT ${SELECT} FROM requirements WHERE requirement_id = ?1`, row.requirement_id)!;
|
|
2160
|
+
});
|
|
2161
|
+
notifyIfParticipant(ctx, row, updated);
|
|
2162
|
+
return Response.json({ ok: true, requirement: toPublicFor(ctx, updated) });
|
|
2163
|
+
}
|
|
2164
|
+
|
|
2165
|
+
const match = url.pathname.match(/^\/api\/requirements\/([^/]+)$/);
|
|
2166
|
+
if (!match) return jsonError("not_found", 404);
|
|
2167
|
+
const id = decodeURIComponent(match[1]);
|
|
2168
|
+
if (req.method === "GET") {
|
|
2169
|
+
const row = scopedRow(ctx, id);
|
|
2170
|
+
if (!(row instanceof Response)) nodeReadNote(ctx, "GET /api/requirements/:id", row);
|
|
2171
|
+
return row instanceof Response ? row : Response.json({ ok: true, requirement: toPublicFor(ctx, row) });
|
|
2172
|
+
}
|
|
2173
|
+
if (req.method === "DELETE") {
|
|
2174
|
+
// 删除只给人(节点令牌在入口已被拒):Agent 用 archived 归档。
|
|
2175
|
+
const row = scopedRow(ctx, id);
|
|
2176
|
+
if (row instanceof Response) return row;
|
|
2177
|
+
if (!canWrite(ctx, row.network_id)) return jsonError("permission_denied", 403);
|
|
2178
|
+
if (!canDeleteTask(taskCaller(ctx), row)) return taskDenied(ctx, row, "task_delete_denied");
|
|
2179
|
+
const byLeader = deletesAsHeadOnly(taskCaller(ctx), row);
|
|
2180
|
+
// 子需求不跟着删:先解挂(变成顶层),再删父卡。
|
|
2181
|
+
const deletedAt = new Date().toISOString();
|
|
2182
|
+
db.transaction(() => {
|
|
2183
|
+
db.run("UPDATE requirements SET parent_id = NULL, updated_at = ?2 WHERE parent_id = ?1", [row.requirement_id, deletedAt]);
|
|
2184
|
+
db.run("DELETE FROM requirements WHERE requirement_id = ?1", [row.requirement_id]);
|
|
2185
|
+
recordTombstone(row, deletedAt);
|
|
2186
|
+
// 卡没了,动态里还要画得出「谁删了 #N 标题」:标题 / 短号随行存(seq、title 列)。
|
|
2187
|
+
recordRequirementEvents(db, row, JSON.stringify(actorOf(ctx)), [{ kind: "deleted", field: null, old: null, new: null }], deletedAt);
|
|
2188
|
+
});
|
|
2189
|
+
// 硬删除以前不留痕(RFC-038 §9.1):记下是谁删了哪张(标题 + 短号),卡本身已经没了。
|
|
2190
|
+
if (ctx.auth) logAudit(ctx.auth.userId, ctx.auth.username || null, "requirement_deleted", "requirement", row.requirement_id, JSON.stringify({ title: row.title, seq: row.seq ?? null }).slice(0, 1000), undefined, row.network_id);
|
|
2191
|
+
// RFC-040 Q4:只凭部门负责人身份删的,另记一条并私信卡的负责人(人;没有就私信负责 Agent 的主人)。
|
|
2192
|
+
if (byLeader && ctx.auth) {
|
|
2193
|
+
const notified = notifyLeaderDeleted({ card: row, actorUserId: ctx.auth.userId });
|
|
2194
|
+
logAudit(ctx.auth.userId, ctx.auth.username || null, "requirement_deleted_by_leader", "requirement", row.requirement_id, JSON.stringify({ title: row.title, seq: row.seq ?? null, owner: row.owner_json ? JSON.parse(row.owner_json) : null, agent_owner: row.agent_owner_json ? JSON.parse(row.agent_owner_json) : null, notified }).slice(0, 1000), undefined, row.network_id);
|
|
2195
|
+
}
|
|
2196
|
+
return Response.json({ ok: true, deleted: row.requirement_id });
|
|
2197
|
+
}
|
|
2198
|
+
if (req.method !== "PATCH") return jsonError("not_found", 404);
|
|
2199
|
+
let body: Record<string, unknown>;
|
|
2200
|
+
try { body = await bodyObject(req); } catch { return jsonError("invalid_json", 400); }
|
|
2201
|
+
if (!PATCH_FIELDS.some(k => Object.prototype.hasOwnProperty.call(body, k))) return jsonError("empty_patch", 400, { sent: Object.keys(body), writable: PATCH_FIELDS });
|
|
2202
|
+
const row = scopedRow(ctx, id);
|
|
2203
|
+
if (row instanceof Response) return row;
|
|
2204
|
+
return patchRequirement(ctx, row, body);
|
|
2205
|
+
}
|