@sleep2agi/commhub-server 0.9.0-preview.13 → 0.9.0-preview.130
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +130 -10
- package/bin/commhub.ts +99 -11
- package/package.json +7 -7
- package/src/ack-create-request-transport.test.ts +182 -0
- package/src/ack-create-request.test.ts +50 -7
- package/src/admin-delete-network-http.test.ts +228 -0
- package/src/admin-networks-http.test.ts +88 -0
- package/src/adoption-candidates-http.test.ts +137 -0
- package/src/adoption-candidates.ts +158 -0
- package/src/agent-access-batch.test.ts +210 -0
- package/src/agent-access.ts +487 -0
- package/src/agent-acl-groups-http.test.ts +247 -0
- package/src/agent-acl-http.test.ts +659 -0
- package/src/agent-acl-slice3-http.test.ts +267 -0
- package/src/agent-groups-perf.test.ts +223 -0
- package/src/agent-notice.ts +48 -0
- package/src/agent-team-whoami-http.test.ts +98 -0
- package/src/agent-teams-http.test.ts +323 -0
- package/src/agent-teams.ts +244 -0
- package/src/alias-filter.test.ts +72 -0
- package/src/alias-filter.ts +42 -0
- package/src/api-host-supervisors-can-create-nodes.test.ts +350 -0
- package/src/api-host-supervisors-fallback.test.ts +271 -0
- package/src/api-host-supervisors-runtime-readiness.test.ts +195 -0
- package/src/api-nodes-shape.test.ts +26 -10
- package/src/auth-password-change-cli-tokens-http.test.ts +294 -0
- package/src/auth-sessions-http.test.ts +250 -0
- package/src/auth-validate.test.ts +5 -1
- package/src/auth-weak-password-login.test.ts +176 -0
- package/src/auth.ts +598 -49
- package/src/avatar-validate.test.ts +163 -0
- package/src/avatar-validate.ts +103 -0
- package/src/binding-generation-http.test.ts +121 -0
- package/src/blocked-exit-on-reply.test.ts +122 -0
- package/src/boot-side-effect.test.ts +124 -0
- package/src/clone-node.test.ts +248 -0
- package/src/clone-node.ts +289 -0
- package/src/codex-config-flags.ts +77 -0
- package/src/codex-fork-contract.ts +23 -0
- package/src/codex-fork-migration.test.ts +38 -0
- package/src/commhub-bin-args.test.ts +85 -0
- package/src/config-apply-sec1.test.ts +107 -0
- package/src/config-apply-validate.test.ts +134 -1
- package/src/config-apply-validate.ts +111 -5
- package/src/create-node-blocked-gate.test.ts +356 -0
- package/src/create-node-network-id.test.ts +79 -0
- package/src/create-node-tool-schema.test.ts +48 -0
- package/src/create-node-unicode-name.test.ts +120 -0
- package/src/create-node-validate.test.ts +193 -7
- package/src/create-node-validate.ts +227 -15
- package/src/create-node-workdir.test.ts +289 -0
- package/src/create-node.ts +77 -23
- package/src/daemon-provider-snapshots.test.ts +421 -0
- package/src/daemon-provider-snapshots.ts +327 -0
- package/src/daemon-token-owner-http.test.ts +236 -0
- package/src/dashboard-slash-routing-http.test.ts +107 -0
- package/src/db-adapter-guard.test.ts +148 -0
- package/src/db-adapter-translate.test.ts +128 -0
- package/src/db-adapter.ts +323 -87
- package/src/db-timestamp.test.ts +38 -0
- package/src/db-timestamp.ts +15 -0
- package/src/db.ts +930 -35
- package/src/delivered-without-push.test.ts +140 -0
- package/src/department-groups-http.test.ts +209 -0
- package/src/department-groups-sync-http.test.ts +328 -0
- package/src/department-groups.ts +434 -0
- package/src/department-heads-http.test.ts +330 -0
- package/src/department-heads.ts +226 -0
- package/src/departments-http.test.ts +185 -0
- package/src/departments.ts +260 -0
- package/src/desktop-message-seam.test.ts +150 -0
- package/src/desktop-message.test.ts +368 -0
- package/src/dm-file-scope-http.test.ts +178 -0
- package/src/ext-token-shared.test.ts +60 -0
- package/src/ext-validation-regression.test.ts +131 -0
- package/src/external-schedule-edits-http.test.ts +321 -0
- package/src/external-schedule-edits-timestamps.test.ts +64 -0
- package/src/external-schedule-edits.ts +327 -0
- package/src/file-download-authz-dev-open.test.ts +135 -0
- package/src/file-download-authz.test.ts +404 -0
- package/src/file-download-date-bucket.test.ts +436 -0
- package/src/file-network-scope-dev-open.test.ts +97 -0
- package/src/file-network-scope.test.ts +732 -0
- package/src/group-membership-events-http.test.ts +264 -0
- package/src/group-messages-http.test.ts +482 -0
- package/src/group-messages.ts +297 -0
- package/src/health-redaction.test.ts +642 -0
- package/src/http-gzip.test.ts +94 -0
- package/src/http-gzip.ts +112 -0
- package/src/hub-provider-config.test.ts +139 -0
- package/src/hub-provider-config.ts +105 -0
- package/src/hub-timestamp.test.ts +38 -0
- package/src/hub-timestamp.ts +27 -0
- package/src/human-dm.ts +215 -0
- package/src/inbox-caller.ts +49 -0
- package/src/inbox-count-sse.test.ts +310 -0
- package/src/inbox-count.ts +29 -0
- package/src/index.ts +15 -2362
- package/src/lifecycle-guard.ts +1 -1
- package/src/mcp-context-cost-http.test.ts +123 -0
- package/src/mcp-projects-events-http.test.ts +162 -0
- package/src/mcp-route-label-http.test.ts +120 -0
- package/src/mcp-write-network-resolution.test.ts +432 -0
- package/src/member-audit-network-id-http.test.ts +93 -0
- package/src/member-presence-http.test.ts +210 -0
- package/src/messages-ack-by-agent-http.test.ts +142 -0
- package/src/migrate-sqlite-to-pg.test.ts +47 -0
- package/src/migrate-sqlite-to-pg.ts +263 -0
- package/src/model-auth-notify-http.test.ts +181 -0
- package/src/model-auth-notify.ts +116 -0
- package/src/network-name-http.test.ts +75 -0
- package/src/network-scope.ts +276 -0
- package/src/network-token-membership-http.test.ts +139 -0
- package/src/node-alias-control.ts +12 -0
- package/src/node-attrs-validate.ts +88 -0
- package/src/node-attrs.test.ts +217 -0
- package/src/node-caller-identity-http.test.ts +781 -0
- package/src/node-create-request-status-http.test.ts +105 -0
- package/src/node-daemon-bindings.test.ts +132 -0
- package/src/node-daemon-bindings.ts +130 -0
- package/src/node-files-transport.test.ts +344 -0
- package/src/node-health-codex-login.test.ts +120 -0
- package/src/node-health-dispatch-http.test.ts +279 -0
- package/src/node-health-guard.ts +105 -0
- package/src/node-health-passthrough.test.ts +115 -0
- package/src/node-health-store.ts +101 -0
- package/src/node-id-alias.test.ts +190 -0
- package/src/node-identity-conflict-http.test.ts +269 -0
- package/src/node-identity-conflict.ts +142 -0
- package/src/node-identity-mismatch.test.ts +74 -0
- package/src/node-lifecycle-controllable.test.ts +64 -0
- package/src/node-lifecycle-controllable.ts +53 -0
- package/src/node-lifecycle-read-http.test.ts +245 -0
- package/src/node-lifecycle-read.ts +121 -0
- package/src/node-logs-transport.test.ts +263 -0
- package/src/node-permissions-http.test.ts +276 -0
- package/src/node-permissions.ts +285 -0
- package/src/node-request-retention.test.ts +281 -0
- package/src/node-request-retention.ts +120 -0
- package/src/node-skills-transport.test.ts +209 -0
- package/src/node-token-ownership.ts +51 -0
- package/src/node-token-privilege-http.test.ts +158 -0
- package/src/observer-avatar-http.test.ts +431 -0
- package/src/observer-push.test.ts +252 -0
- package/src/opencode-v2-catalog.test.ts +268 -0
- package/src/opencode-v2-catalog.ts +352 -0
- package/src/package-version-consistency.test.ts +25 -0
- package/src/peer-reply-atomic.test.ts +455 -0
- package/src/peer-reply-capability.test.ts +70 -0
- package/src/pg-worker.ts +87 -0
- package/src/project-dir-warn-clear-http.test.ts +132 -0
- package/src/project-viewer-can-http.test.ts +114 -0
- package/src/push.ts +429 -10
- package/src/redact-tokens.test.ts +65 -0
- package/src/redact-tokens.ts +40 -0
- package/src/rename.ts +22 -2
- package/src/reply-target-derivation.test.ts +96 -0
- package/src/report-status-handover-capabilities-http.test.ts +124 -0
- package/src/report-status-host-schema.test.ts +235 -0
- package/src/report-status-resume-id-handover.test.ts +150 -0
- package/src/require-explicit-test-db.ts +9 -0
- package/src/requirement-due-reminders-http.test.ts +620 -0
- package/src/requirement-due-reminders.ts +416 -0
- package/src/requirement-events-http.test.ts +268 -0
- package/src/requirement-events.test.ts +45 -0
- package/src/requirement-events.ts +144 -0
- package/src/requirement-notify.ts +165 -0
- package/src/requirement-participant-notify-http.test.ts +309 -0
- package/src/requirement-tag-ops-http.test.ts +266 -0
- package/src/requirement-tags.ts +89 -0
- package/src/requirements-abandoned-http.test.ts +236 -0
- package/src/requirements-comment-http.test.ts +167 -0
- package/src/requirements-completed-at-migration.test.ts +70 -0
- package/src/requirements-errors-mcp-http.test.ts +164 -0
- package/src/requirements-errors.ts +143 -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 +319 -0
- package/src/requirements-mcp.test.ts +163 -0
- package/src/requirements-migrate.ts +259 -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 +225 -0
- package/src/requirements-people.ts +127 -0
- package/src/requirements-priority-lowest.test.ts +114 -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 +288 -0
- package/src/requirements-stats.ts +167 -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 +1806 -0
- package/src/resolve-port.test.ts +57 -0
- package/src/resolve-port.ts +44 -0
- package/src/response-charset.test.ts +130 -0
- package/src/rest-explicit-columns-http.test.ts +222 -0
- package/src/rest-identity.test.ts +129 -0
- package/src/rest-identity.ts +125 -0
- package/src/rest-projections.ts +68 -0
- package/src/rest-write-network-resolution.test.ts +133 -0
- package/src/restricted-files.ts +76 -0
- package/src/retention.ts +15 -3
- package/src/route-callers-http.test.ts +120 -0
- package/src/route-timing.test.ts +211 -0
- package/src/route-timing.ts +258 -0
- package/src/rules-file-duplicate-alias.test.ts +234 -0
- package/src/rules-file-session-target.test.ts +207 -0
- package/src/rules-file-transport.test.ts +237 -0
- package/src/runtime-label.test.ts +22 -0
- package/src/runtime-label.ts +21 -0
- package/src/runtime-readiness.ts +90 -0
- package/src/schedule-agent-mcp-http.test.ts +381 -0
- package/src/schedule-agent.ts +192 -0
- package/src/scheduled-doorbell-nodeless-session.test.ts +134 -0
- package/src/scheduled-failures-http.test.ts +233 -0
- package/src/scheduled-failures.ts +179 -0
- package/src/scheduled-offline.test.ts +131 -0
- package/src/scheduled-offline.ts +66 -0
- package/src/scheduled-reply-unread-http.test.ts +212 -0
- package/src/scheduled-run-terminal.test.ts +268 -0
- package/src/scheduled-skip-blocking-task.test.ts +120 -0
- package/src/scheduled-stuck-http.test.ts +238 -0
- package/src/scheduled-stuck.ts +153 -0
- package/src/scheduled-tasks-http.test.ts +638 -0
- package/src/scheduled-tasks.ts +766 -0
- package/src/scoped-secrets.ts +124 -0
- package/src/send-dedup-request-id.test.ts +229 -0
- package/src/send-reply-agent-warning.test.ts +202 -0
- package/src/send-reply-alias-optional.test.ts +131 -0
- package/src/send-reply-attachments.test.ts +458 -0
- package/src/send_dedup.test.ts +54 -0
- package/src/send_dedup.ts +52 -6
- package/src/serve-error.test.ts +38 -0
- package/src/serve-error.ts +27 -0
- package/src/server.ts +5257 -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/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 +108 -0
- package/src/sqlite-close-checkpoint.test.ts +78 -0
- package/src/start-node.test.ts +264 -0
- package/src/status-alias-filter-http.test.ts +106 -0
- package/src/status-alias-resolver-http.test.ts +163 -0
- package/src/status-alias-resolver.ts +19 -0
- package/src/status-node-id-filter-http.test.ts +161 -0
- package/src/status-read-cache-http.test.ts +229 -0
- package/src/status-read-cache.ts +122 -0
- package/src/stop-delete-node.test.ts +509 -1
- package/src/task-access-http.test.ts +402 -0
- package/src/task-access.ts +420 -0
- package/src/task-auth-origin-http.test.ts +91 -0
- package/src/task-auth-origin.test.ts +24 -0
- package/src/task-auth-origin.ts +7 -0
- package/src/task-consumption.test.ts +482 -0
- package/src/task-diagnostic-http.test.ts +149 -0
- package/src/task-diagnostic.test.ts +115 -0
- package/src/task-diagnostic.ts +118 -0
- package/src/task-expiry-notice-http.test.ts +287 -0
- package/src/task-expiry-notice.ts +315 -0
- package/src/task-idempotency-mcp.test.ts +142 -0
- package/src/task-idempotency.test.ts +60 -0
- package/src/task-idempotency.ts +75 -0
- package/src/task-late-replies.ts +54 -0
- package/src/task-late-reply-http.test.ts +152 -0
- package/src/task-lifecycle-watcher.test.ts +204 -0
- package/src/task-lifecycle-watcher.ts +49 -0
- package/src/task-network-resolution-http.test.ts +141 -0
- package/src/task-orphan-http.test.ts +287 -0
- package/src/task-orphan.ts +119 -0
- package/src/task-queue-ahead-http.test.ts +309 -0
- package/src/task-queue-ahead-scale.test.ts +236 -0
- package/src/task-queue-ahead.ts +186 -0
- package/src/task-rejection-log-http.test.ts +160 -0
- package/src/task-rejection-log.ts +49 -0
- package/src/task-stale-open-http.test.ts +290 -0
- package/src/task-stale-open.ts +103 -0
- package/src/tasks-pagination-http.test.ts +141 -0
- package/src/tool-audience-http.test.ts +220 -0
- package/src/tool-audience.ts +118 -0
- package/src/tools-list-json-schema.test.ts +67 -0
- package/src/tools.ts +3927 -323
- package/src/upload-early-reject-guard.test.ts +155 -0
- package/src/uploads-http.test.ts +97 -15
- package/src/uploads.ts +103 -6
- package/src/user-avatar-http.test.ts +74 -0
- package/src/user-avatar-migration.test.ts +25 -0
- package/src/user-inbox-by-agent-http.test.ts +161 -0
- package/src/user-inbox-netid-notnull.test.ts +122 -0
- package/src/user-inbox-read-http.test.ts +223 -0
- package/src/user-inbox-schema.test.ts +54 -0
package/src/db.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { createAdapter, type DbAdapter } from "./db-adapter";
|
|
1
|
+
import { createAdapter, type DbAdapter } from "./db-adapter"; import { withStatementHook } from "./status-read-cache"; // #431 写 sessions 的语句让 /api/status 缓存失效
|
|
2
2
|
|
|
3
|
-
export const db: DbAdapter = createAdapter();
|
|
3
|
+
export const db: DbAdapter = withStatementHook(createAdapter());
|
|
4
4
|
|
|
5
5
|
// Schema
|
|
6
6
|
db.exec(`
|
|
@@ -53,6 +53,38 @@ db.exec(`
|
|
|
53
53
|
CREATE INDEX IF NOT EXISTS idx_inbox_pending
|
|
54
54
|
ON inbox(session_name, acked) WHERE acked = 0;
|
|
55
55
|
|
|
56
|
+
-- #1459 ① — agent→用户的 desktop message 持久化收件箱。
|
|
57
|
+
-- inbox 是 session_name(alias) 寻址的;desktop message 目标是 user_id,不能复用
|
|
58
|
+
-- inbox(否则 /api/messages+inbox_count+SSE gate 一票 alias 域查询会隐性开始返回
|
|
59
|
+
-- 用户消息)。单独一张 user_id 寻址表,镜像 inbox 的 acked/count 语义。
|
|
60
|
+
-- message_id 即主键(dm_<uuid>,与 inbox「消息 id 即主键」同形)→ 写入用
|
|
61
|
+
-- INSERT OR IGNORE,send_desktop_message 重试天然幂等,不会插出重复消息行。
|
|
62
|
+
-- 索引留到 P3:读取查询形状定了再按真实 WHERE 加(SDK马 review:没查询就加索引是猜;
|
|
63
|
+
-- 部分索引 acked=0 若「近期」读含已 ack 行则用不上)。P1 只落表。
|
|
64
|
+
CREATE TABLE IF NOT EXISTS user_inbox (
|
|
65
|
+
message_id TEXT PRIMARY KEY,
|
|
66
|
+
network_id TEXT NOT NULL,
|
|
67
|
+
user_id TEXT NOT NULL,
|
|
68
|
+
from_session TEXT,
|
|
69
|
+
kind TEXT NOT NULL DEFAULT 'info',
|
|
70
|
+
title TEXT,
|
|
71
|
+
content TEXT NOT NULL,
|
|
72
|
+
severity TEXT NOT NULL DEFAULT 'info',
|
|
73
|
+
meta_json TEXT,
|
|
74
|
+
acked INTEGER NOT NULL DEFAULT 0,
|
|
75
|
+
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
76
|
+
acked_at TEXT
|
|
77
|
+
);
|
|
78
|
+
|
|
79
|
+
-- #1459 ① P3 —— 现在有真实查询了才建索引(P1 刻意没建:没有查询就加索引是猜)。
|
|
80
|
+
-- 覆盖回读分支的两条:
|
|
81
|
+
-- 列表 SELECT ... WHERE user_id = ? [AND acked = 0] ORDER BY created_at DESC
|
|
82
|
+
-- 未读数 SELECT COUNT(*) WHERE user_id = ? AND acked = 0
|
|
83
|
+
-- 不是部分索引(不写 WHERE acked = 0):列表在 unacked=0 时要读**含已 ack 的**
|
|
84
|
+
-- 近期消息,部分索引那时用不上。
|
|
85
|
+
CREATE INDEX IF NOT EXISTS idx_user_inbox_user_acked
|
|
86
|
+
ON user_inbox(user_id, acked, created_at);
|
|
87
|
+
|
|
56
88
|
CREATE TABLE IF NOT EXISTS completions (
|
|
57
89
|
id TEXT PRIMARY KEY,
|
|
58
90
|
session_name TEXT NOT NULL,
|
|
@@ -89,6 +121,21 @@ for (const col of [
|
|
|
89
121
|
{ name: "process_cpu_pct", def: "REAL" },
|
|
90
122
|
{ name: "process_uptime_seconds", def: "REAL" },
|
|
91
123
|
{ name: "process_in_flight_count", def: "INTEGER" },
|
|
124
|
+
{ name: "external_schedules", def: "TEXT" },
|
|
125
|
+
{ name: "peer_reply_inbox_capable", def: "INTEGER NOT NULL DEFAULT 0" },
|
|
126
|
+
// app#225 follow-up — a session (incl. claude-code sessions with no `nodes` row)
|
|
127
|
+
// that answers the rules-file doorbell. Sticky: set by a bound node token, never
|
|
128
|
+
// cleared by reports that omit it (agent-node status-only reports do).
|
|
129
|
+
{ name: "rules_file_capable", def: "INTEGER NOT NULL DEFAULT 0" },
|
|
130
|
+
// Node skills view — the same session answers skills_list / skill_read on the
|
|
131
|
+
// rules-file doorbell (node-skills.ts). Sticky, bound-token only, like above.
|
|
132
|
+
{ name: "skills_capable", def: "INTEGER NOT NULL DEFAULT 0" },
|
|
133
|
+
// Project folder view — the same session answers files_list / file_read on the
|
|
134
|
+
// rules-file doorbell (node-files.ts). Sticky, bound-token only, like above.
|
|
135
|
+
{ name: "files_capable", def: "INTEGER NOT NULL DEFAULT 0" },
|
|
136
|
+
// Node run-log view — the same session answers logs_tail on the rules-file
|
|
137
|
+
// doorbell (node-logs.ts). Sticky, bound-token only, like above.
|
|
138
|
+
{ name: "logs_capable", def: "INTEGER NOT NULL DEFAULT 0" },
|
|
92
139
|
]) {
|
|
93
140
|
try { db.exec(`ALTER TABLE sessions ADD COLUMN ${col.name} ${col.def}`); } catch {}
|
|
94
141
|
}
|
|
@@ -162,6 +209,11 @@ for (const col of [
|
|
|
162
209
|
{ name: "scope", def: "TEXT DEFAULT 'single'" },
|
|
163
210
|
{ name: "meta_json", def: "TEXT" },
|
|
164
211
|
{ name: "node_id", def: "TEXT" },
|
|
212
|
+
// #520 — explicit logical task identity. Initial deliveries historically
|
|
213
|
+
// used inbox.id == tasks.task_id, while retry/reassign generate a fresh
|
|
214
|
+
// inbox row id. Keep transport-row identity and logical-task identity
|
|
215
|
+
// separate so runtime evidence/replies survive those redeliveries.
|
|
216
|
+
{ name: "task_id", def: "TEXT" },
|
|
165
217
|
]) {
|
|
166
218
|
try { db.exec(`ALTER TABLE inbox ADD COLUMN ${col.name} ${col.def}`); } catch {}
|
|
167
219
|
}
|
|
@@ -191,6 +243,10 @@ db.exec(`
|
|
|
191
243
|
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
192
244
|
delivered_at TEXT,
|
|
193
245
|
started_at TEXT,
|
|
246
|
+
runtime_submitted_at TEXT,
|
|
247
|
+
consumed_at TEXT,
|
|
248
|
+
thread_id TEXT,
|
|
249
|
+
turn_id TEXT,
|
|
194
250
|
completed_at TEXT,
|
|
195
251
|
expires_at TEXT
|
|
196
252
|
);
|
|
@@ -237,6 +293,8 @@ db.exec(`
|
|
|
237
293
|
task_id TEXT NOT NULL,
|
|
238
294
|
from_status TEXT,
|
|
239
295
|
to_status TEXT NOT NULL,
|
|
296
|
+
event_type TEXT,
|
|
297
|
+
event_key TEXT,
|
|
240
298
|
actor TEXT NOT NULL DEFAULT 'system',
|
|
241
299
|
detail TEXT,
|
|
242
300
|
created_at TEXT NOT NULL DEFAULT (datetime('now'))
|
|
@@ -262,6 +320,15 @@ db.exec(`
|
|
|
262
320
|
CREATE INDEX IF NOT EXISTS idx_users_username ON users(username);
|
|
263
321
|
`);
|
|
264
322
|
|
|
323
|
+
// Human profile avatar. Additive for existing databases; old binaries ignore it.
|
|
324
|
+
try {
|
|
325
|
+
db.exec("ALTER TABLE users ADD COLUMN avatar_url TEXT");
|
|
326
|
+
} catch (e: any) {
|
|
327
|
+
// Both supported adapters report a duplicate column on the next startup.
|
|
328
|
+
// Do not send SQLite PRAGMA to PostgreSQL or swallow other migration errors.
|
|
329
|
+
if (!/duplicate column|already exists/i.test(e?.message || "")) throw e;
|
|
330
|
+
}
|
|
331
|
+
|
|
265
332
|
// #261 P0-2 (2026-06-28): must_change_password flag. Added via ALTER
|
|
266
333
|
// (not in the CREATE block above) so it's a no-op on fresh DBs that
|
|
267
334
|
// already get the column via the CREATE path's full definition AND a
|
|
@@ -301,6 +368,16 @@ try {
|
|
|
301
368
|
if (!/duplicate column|already exists/i.test(e?.message || "")) throw e;
|
|
302
369
|
}
|
|
303
370
|
|
|
371
|
+
// RFC-036 / B4 — immutable per-node owner. New nodes receive this value in
|
|
372
|
+
// the same transaction that mints their node token. Heartbeats may verify the
|
|
373
|
+
// binding but must never first-claim or replace it. Legacy NULL rows remain
|
|
374
|
+
// read-only for external-schedule writes.
|
|
375
|
+
try {
|
|
376
|
+
db.exec(`ALTER TABLE nodes ADD COLUMN owner_user_id TEXT`);
|
|
377
|
+
} catch (e: any) {
|
|
378
|
+
if (!/duplicate column|already exists/i.test(e?.message || "")) throw e;
|
|
379
|
+
}
|
|
380
|
+
|
|
304
381
|
// RFC-026 §9 / #338 PR2 — daemon self-declare fields promoted from
|
|
305
382
|
// config_snapshot to first-class indexable columns. The hub
|
|
306
383
|
// `list_host_supervisors` MCP tool reads these directly without parsing
|
|
@@ -338,6 +415,48 @@ try {
|
|
|
338
415
|
if (!/duplicate column|already exists/i.test(e?.message || "")) throw e;
|
|
339
416
|
}
|
|
340
417
|
|
|
418
|
+
// #462 — user-set custom avatar (nullable http/https image URL). Pure
|
|
419
|
+
// display attribute: deliberately NOT part of the RFC-024 config-apply
|
|
420
|
+
// pipeline (nothing for agent-node to consume, no revision/ack). Written
|
|
421
|
+
// only via PUT /api/nodes/:ref/avatar which validates the URL shape.
|
|
422
|
+
try {
|
|
423
|
+
db.exec(`ALTER TABLE nodes ADD COLUMN avatar_url TEXT`);
|
|
424
|
+
} catch (e: any) {
|
|
425
|
+
if (!/duplicate column|already exists/i.test(e?.message || "")) throw e;
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
// Node DISPLAY attributes (Vincent 目标第 3 条 — dashboard/app 多维度编辑).
|
|
429
|
+
// Same posture as avatar_url above: hub-side presentation only, NOT part of
|
|
430
|
+
// the RFC-024 config-apply pipeline (agent-node consumes none of them, so a
|
|
431
|
+
// doorbell/ack round-trip would be meaningless and could wedge the config
|
|
432
|
+
// revision). Written only via PUT /api/nodes/:ref/attrs.
|
|
433
|
+
//
|
|
434
|
+
// display_name — human label shown in the UI. Distinct from `alias`,
|
|
435
|
+
// which is the ROUTING key (messages address the alias)
|
|
436
|
+
// and from `node_name`, which is an addressing key
|
|
437
|
+
// (`WHERE node_id OR node_name OR alias`). Renaming
|
|
438
|
+
// either of those must go through the rename 2PC
|
|
439
|
+
// (/api/node-rename/*), never through an attrs write.
|
|
440
|
+
// team, tags — organisation metadata; tags stored as JSON array text.
|
|
441
|
+
// attrs_revision — optimistic-lock counter for these display fields ONLY.
|
|
442
|
+
// Deliberately separate from config_revision so that
|
|
443
|
+
// editing a tag never bumps the node's *config* revision
|
|
444
|
+
// (which would perturb the config ack protocol).
|
|
445
|
+
//
|
|
446
|
+
// All nullable / defaulted so the ~100 rows already in flight keep reading.
|
|
447
|
+
for (const ddl of [
|
|
448
|
+
`ALTER TABLE nodes ADD COLUMN display_name TEXT`,
|
|
449
|
+
`ALTER TABLE nodes ADD COLUMN team TEXT`,
|
|
450
|
+
`ALTER TABLE nodes ADD COLUMN tags TEXT`,
|
|
451
|
+
`ALTER TABLE nodes ADD COLUMN attrs_revision INTEGER NOT NULL DEFAULT 0`,
|
|
452
|
+
]) {
|
|
453
|
+
try {
|
|
454
|
+
db.exec(ddl);
|
|
455
|
+
} catch (e: any) {
|
|
456
|
+
if (!/duplicate column|already exists/i.test(e?.message || "")) throw e;
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
|
|
341
460
|
// RFC-027 §2 — stop/delete request envelope. Mirrors
|
|
342
461
|
// node_create_requests structure so the daemon-side pull/ack pattern
|
|
343
462
|
// is symmetric with create_node. action='stop'|'delete' picks which
|
|
@@ -349,6 +468,7 @@ db.exec(`
|
|
|
349
468
|
daemon_node_id TEXT NOT NULL,
|
|
350
469
|
child_node_id TEXT NOT NULL,
|
|
351
470
|
child_alias TEXT NOT NULL,
|
|
471
|
+
child_token_id TEXT,
|
|
352
472
|
action TEXT NOT NULL CHECK (action IN ('stop', 'delete')),
|
|
353
473
|
delete_config INTEGER NOT NULL DEFAULT 1,
|
|
354
474
|
grace_seconds INTEGER NOT NULL DEFAULT 10,
|
|
@@ -366,8 +486,75 @@ db.exec(`
|
|
|
366
486
|
`);
|
|
367
487
|
db.exec(`CREATE INDEX IF NOT EXISTS idx_stop_req_daemon ON node_stop_requests(daemon_node_id, status)`);
|
|
368
488
|
db.exec(`CREATE INDEX IF NOT EXISTS idx_stop_req_child ON node_stop_requests(child_node_id)`);
|
|
489
|
+
// #1448 finding-5 — 存 delete 目标 child 的 token_id,让 ack 精确按 token_id 撤 ntok
|
|
490
|
+
// (而非按 name='node:<alias>' 广撤 → 同 alias 在 delete 窗口内重建会误杀新 token)。
|
|
491
|
+
// 幂等迁移:已有库补列,旧行 child_token_id 为 NULL、ack 时 fallback 回按 name 撤。
|
|
492
|
+
try { db.exec(`ALTER TABLE node_stop_requests ADD COLUMN child_token_id TEXT`); } catch { /* 已存在 */ }
|
|
493
|
+
|
|
494
|
+
// Daemon-mediated start request. Kept separate from node_stop_requests:
|
|
495
|
+
// the deployed stop table has a CHECK(action IN ('stop','delete')) and
|
|
496
|
+
// rebuilding that table in-place would be a risky migration for an additive
|
|
497
|
+
// lifecycle operation.
|
|
498
|
+
db.exec(`
|
|
499
|
+
CREATE TABLE IF NOT EXISTS node_start_requests (
|
|
500
|
+
request_id TEXT PRIMARY KEY,
|
|
501
|
+
network_id TEXT NOT NULL,
|
|
502
|
+
daemon_node_id TEXT NOT NULL,
|
|
503
|
+
child_node_id TEXT NOT NULL,
|
|
504
|
+
child_alias TEXT NOT NULL,
|
|
505
|
+
created_by_token TEXT NOT NULL,
|
|
506
|
+
status TEXT NOT NULL DEFAULT 'pending',
|
|
507
|
+
error TEXT,
|
|
508
|
+
child_pid INTEGER,
|
|
509
|
+
created_at INTEGER NOT NULL,
|
|
510
|
+
delivered_at INTEGER,
|
|
511
|
+
acked_at INTEGER
|
|
512
|
+
)
|
|
513
|
+
`);
|
|
514
|
+
db.exec(`CREATE INDEX IF NOT EXISTS idx_start_req_daemon ON node_start_requests(daemon_node_id, status)`);
|
|
515
|
+
db.exec(`CREATE INDEX IF NOT EXISTS idx_start_req_child ON node_start_requests(child_node_id)`);
|
|
516
|
+
// Additive: old rows remain ordinary starts (NULL). Keep the request and the
|
|
517
|
+
// observed side effect separate from launcher status, including startup failure.
|
|
518
|
+
for (const column of ["fork_recovery_json", "fork_result_json"]) {
|
|
519
|
+
try { db.exec(`ALTER TABLE node_start_requests ADD COLUMN ${column} TEXT`); }
|
|
520
|
+
catch (e: any) { if (!/duplicate column|already exists/i.test(e?.message || "")) throw e; }
|
|
521
|
+
}
|
|
522
|
+
try {
|
|
523
|
+
db.exec(`CREATE UNIQUE INDEX IF NOT EXISTS uniq_start_req_child_inflight
|
|
524
|
+
ON node_start_requests(child_node_id)
|
|
525
|
+
WHERE status IN ('pending', 'delivered')`);
|
|
526
|
+
} catch (e: any) {
|
|
527
|
+
if (!/unique constraint/i.test(e?.message || "")) throw e;
|
|
528
|
+
}
|
|
369
529
|
|
|
370
530
|
// `node_config_updates` — pending + history. One row per dashboard write.
|
|
531
|
+
// #906: redacted daemon-owned inventory requests, never credential material.
|
|
532
|
+
db.exec(`CREATE TABLE IF NOT EXISTS daemon_provider_snapshots (
|
|
533
|
+
request_id TEXT PRIMARY KEY, network_id TEXT NOT NULL, daemon_node_id TEXT NOT NULL,
|
|
534
|
+
requested_by TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'pending',
|
|
535
|
+
created_at INTEGER NOT NULL, expires_at INTEGER NOT NULL, observed_at INTEGER,
|
|
536
|
+
snapshot_json TEXT, error TEXT
|
|
537
|
+
)`);
|
|
538
|
+
db.exec(`CREATE INDEX IF NOT EXISTS idx_daemon_provider_pending
|
|
539
|
+
ON daemon_provider_snapshots(network_id, daemon_node_id, status)`);
|
|
540
|
+
db.exec(`CREATE UNIQUE INDEX IF NOT EXISTS uniq_daemon_provider_inflight
|
|
541
|
+
ON daemon_provider_snapshots(network_id, daemon_node_id) WHERE status='pending'`);
|
|
542
|
+
// One encrypted mutation payload per request; public receipt remains secret-free.
|
|
543
|
+
db.exec(`CREATE TABLE IF NOT EXISTS daemon_provider_writes (
|
|
544
|
+
request_id TEXT PRIMARY KEY, expected_revision INTEGER NOT NULL,
|
|
545
|
+
ciphertext BLOB NOT NULL, iv BLOB NOT NULL, tag BLOB NOT NULL
|
|
546
|
+
)`);
|
|
547
|
+
// Application intent is credential-free; secrets stay in the daemon's store.
|
|
548
|
+
db.exec(`CREATE TABLE IF NOT EXISTS daemon_provider_applications (
|
|
549
|
+
request_id TEXT PRIMARY KEY, expected_revision INTEGER NOT NULL,
|
|
550
|
+
selection_json TEXT NOT NULL
|
|
551
|
+
)`);
|
|
552
|
+
|
|
553
|
+
// Login commands contain only intent. OAuth tokens never enter Hub storage.
|
|
554
|
+
db.exec(`CREATE TABLE IF NOT EXISTS daemon_provider_logins (
|
|
555
|
+
request_id TEXT PRIMARY KEY, intent_json TEXT NOT NULL
|
|
556
|
+
)`);
|
|
557
|
+
|
|
371
558
|
// At most one row per node may be in a non-terminal state at a time
|
|
372
559
|
// (single-flight enforced at the tool layer; this table just stores).
|
|
373
560
|
//
|
|
@@ -408,6 +595,47 @@ try {
|
|
|
408
595
|
console.warn(`[commhub] partial unique index uniq_ncu_node_inflight skipped: ${e?.message || e}`);
|
|
409
596
|
}
|
|
410
597
|
|
|
598
|
+
// ── app#225: 节点规则文件(AGENTS.md / CLAUDE.md)远程读写请求 ──
|
|
599
|
+
//
|
|
600
|
+
// 形状照抄 node_config_updates(上面):客户端落一行 + 门铃,节点拉走做完回报,
|
|
601
|
+
// 客户端轮询结果。network_id 同样在插入时从 nodes 反规范化。
|
|
602
|
+
//
|
|
603
|
+
// 🔴 这张表**故意没有路径列**:文件名由节点按自己的 RUNTIME 决定
|
|
604
|
+
// (claude → CLAUDE.md,其余 → AGENTS.md),目录固定是节点进程的 cwd。
|
|
605
|
+
// hub 侧只存 op + 内容,客户端连文件名都指定不了(#225 验收第 5 条)。
|
|
606
|
+
// file_name 是节点**回报**的实际文件名,只用于显示。
|
|
607
|
+
db.exec(`
|
|
608
|
+
CREATE TABLE IF NOT EXISTS node_rules_requests (
|
|
609
|
+
request_id TEXT PRIMARY KEY,
|
|
610
|
+
node_id TEXT NOT NULL,
|
|
611
|
+
network_id TEXT NOT NULL,
|
|
612
|
+
op TEXT NOT NULL,
|
|
613
|
+
content TEXT,
|
|
614
|
+
status TEXT NOT NULL,
|
|
615
|
+
file_name TEXT,
|
|
616
|
+
file_exists INTEGER,
|
|
617
|
+
result_content TEXT,
|
|
618
|
+
error TEXT,
|
|
619
|
+
created_at INTEGER NOT NULL,
|
|
620
|
+
created_by_token TEXT NOT NULL,
|
|
621
|
+
pulled_at INTEGER,
|
|
622
|
+
acked_at INTEGER
|
|
623
|
+
);
|
|
624
|
+
|
|
625
|
+
CREATE INDEX IF NOT EXISTS idx_nrr_node_status ON node_rules_requests(node_id, status);
|
|
626
|
+
CREATE INDEX IF NOT EXISTS idx_nrr_network ON node_rules_requests(network_id);
|
|
627
|
+
`);
|
|
628
|
+
// Content retention (node-request-retention.ts): file bytes in content /
|
|
629
|
+
// result_content are purged after the first terminal read (+grace) or a TTL;
|
|
630
|
+
// these two columns record when, so the row itself survives as audit metadata.
|
|
631
|
+
for (const col of ["first_read_at INTEGER", "content_purged_at INTEGER"]) {
|
|
632
|
+
try { db.exec(`ALTER TABLE node_rules_requests ADD COLUMN ${col}`); } catch {}
|
|
633
|
+
}
|
|
634
|
+
db.exec(`
|
|
635
|
+
CREATE INDEX IF NOT EXISTS idx_nrr_created ON node_rules_requests(created_at);
|
|
636
|
+
CREATE INDEX IF NOT EXISTS idx_nrr_first_read ON node_rules_requests(first_read_at);
|
|
637
|
+
`);
|
|
638
|
+
|
|
411
639
|
// ── V3: networks table ──
|
|
412
640
|
db.exec(`
|
|
413
641
|
CREATE TABLE IF NOT EXISTS networks (
|
|
@@ -453,14 +681,37 @@ for (const ddl of [
|
|
|
453
681
|
"ALTER TABLE api_tokens ADD COLUMN request_id TEXT",
|
|
454
682
|
"ALTER TABLE api_tokens ADD COLUMN revoked_at TEXT",
|
|
455
683
|
"ALTER TABLE api_tokens ADD COLUMN role TEXT",
|
|
684
|
+
"ALTER TABLE api_tokens ADD COLUMN bound_node_id TEXT",
|
|
685
|
+
// Existing tokens retain epoch 0. Every production issuer writes 1 (general)
|
|
686
|
+
// or 2 (ownership-checked node token); 0 is a rollout boundary, not a clock.
|
|
687
|
+
"ALTER TABLE api_tokens ADD COLUMN node_identity_epoch INTEGER NOT NULL DEFAULT 0",
|
|
688
|
+
// 登录会话的设备标识(GET /api/auth/sessions 显示用):客户端自报的 client_label + 登录请求的 User-Agent。
|
|
689
|
+
"ALTER TABLE api_tokens ADD COLUMN client_label TEXT",
|
|
690
|
+
"ALTER TABLE api_tokens ADD COLUMN user_agent TEXT",
|
|
691
|
+
// #711 不绑网络的用户令牌分两类:'login' = 浏览器 / app 的登录会话;'cli' = anet 命令行登录、
|
|
692
|
+
// POST /api/auth/tokens 建的具名脚本令牌。只用于展示和 keep_cli_tokens 那条显式保留路径;节点 / 网络令牌(network_id 非空)不填。
|
|
693
|
+
"ALTER TABLE api_tokens ADD COLUMN kind TEXT",
|
|
456
694
|
]) {
|
|
457
695
|
try { db.exec(ddl); }
|
|
458
696
|
catch (e: any) {
|
|
459
697
|
if (!/duplicate column|already exists/i.test(e?.message || "")) throw e;
|
|
460
698
|
}
|
|
461
699
|
}
|
|
700
|
+
// #711 回填 kind:只碰 kind 还是 NULL 的非网络令牌(幂等;回滚到旧 Hub 期间新签的行,下次启动照样补上)。
|
|
701
|
+
// 能明确认出是 anet 命令行的才算 'cli':scope='full'(POST /api/auth/tokens 建的具名令牌),
|
|
702
|
+
// 或 client_label 去掉首尾空格后以「anet 」开头(anet 自报的「anet <版本> · <主机> · <子命令>」)。其余一律 'login'。
|
|
703
|
+
// 用 SUBSTR + = 而不是 LIKE:SQLite 的 LIKE 不分大小写、PG 分,两边结果会不一样;= 两边都区分大小写,
|
|
704
|
+
// 与运行时 isAnetClientLabel(auth.ts)同一条规则。
|
|
705
|
+
db.run(
|
|
706
|
+
`UPDATE api_tokens SET kind = CASE
|
|
707
|
+
WHEN scope = 'full' OR SUBSTR(TRIM(client_label), 1, 5) = 'anet ' THEN 'cli'
|
|
708
|
+
ELSE 'login' END
|
|
709
|
+
WHERE network_id IS NULL AND kind IS NULL`,
|
|
710
|
+
);
|
|
462
711
|
try { db.exec(`CREATE INDEX IF NOT EXISTS idx_tokens_request ON api_tokens(request_id)`); }
|
|
463
712
|
catch (e: any) { /* index may already exist */ void e; }
|
|
713
|
+
try { db.exec(`CREATE INDEX IF NOT EXISTS idx_tokens_bound_node ON api_tokens(bound_node_id)`); }
|
|
714
|
+
catch (e: any) { void e; }
|
|
464
715
|
|
|
465
716
|
// RFC-026 v4 §2.5 + §4.4 — node_create_requests. Metadata only;
|
|
466
717
|
// env_blob NEVER lives in this table (F1 mint-stream-evict — secret
|
|
@@ -477,7 +728,7 @@ db.exec(`
|
|
|
477
728
|
child_name TEXT NOT NULL,
|
|
478
729
|
network_id TEXT NOT NULL,
|
|
479
730
|
runtime TEXT NOT NULL,
|
|
480
|
-
model TEXT
|
|
731
|
+
model TEXT,
|
|
481
732
|
flags_json TEXT NOT NULL,
|
|
482
733
|
env_keys TEXT NOT NULL,
|
|
483
734
|
status TEXT NOT NULL,
|
|
@@ -494,6 +745,168 @@ db.exec(`
|
|
|
494
745
|
CREATE INDEX IF NOT EXISTS idx_ncr_network ON node_create_requests(network_id);
|
|
495
746
|
CREATE INDEX IF NOT EXISTS idx_ncr_child_name ON node_create_requests(child_name);
|
|
496
747
|
`);
|
|
748
|
+
function migrateNodeCreateRequestsModelNullable() {
|
|
749
|
+
if (db.dialect === "postgres") {
|
|
750
|
+
try { db.exec("ALTER TABLE node_create_requests ALTER COLUMN model DROP NOT NULL"); } catch {}
|
|
751
|
+
return;
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
let needsRebuild = false;
|
|
755
|
+
try {
|
|
756
|
+
const createSql = db.get<{ sql: string }>("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'node_create_requests'");
|
|
757
|
+
needsRebuild = !!createSql?.sql && /\bmodel\s+TEXT\s+NOT\s+NULL\b/i.test(createSql.sql);
|
|
758
|
+
} catch {}
|
|
759
|
+
if (!needsRebuild) return;
|
|
760
|
+
|
|
761
|
+
db.transaction(() => {
|
|
762
|
+
db.exec("DROP TABLE IF EXISTS node_create_requests_migrated");
|
|
763
|
+
db.exec(`
|
|
764
|
+
CREATE TABLE node_create_requests_migrated (
|
|
765
|
+
request_id TEXT PRIMARY KEY,
|
|
766
|
+
daemon_node_id TEXT NOT NULL,
|
|
767
|
+
child_name TEXT NOT NULL,
|
|
768
|
+
network_id TEXT NOT NULL,
|
|
769
|
+
runtime TEXT NOT NULL,
|
|
770
|
+
model TEXT,
|
|
771
|
+
flags_json TEXT NOT NULL,
|
|
772
|
+
env_keys TEXT NOT NULL,
|
|
773
|
+
status TEXT NOT NULL,
|
|
774
|
+
error TEXT,
|
|
775
|
+
child_token_id TEXT,
|
|
776
|
+
created_at INTEGER NOT NULL,
|
|
777
|
+
created_by_token TEXT NOT NULL,
|
|
778
|
+
delivered_at INTEGER,
|
|
779
|
+
acked_at INTEGER,
|
|
780
|
+
child_node_id TEXT
|
|
781
|
+
)
|
|
782
|
+
`);
|
|
783
|
+
db.exec(`
|
|
784
|
+
INSERT INTO node_create_requests_migrated (
|
|
785
|
+
request_id, daemon_node_id, child_name, network_id, runtime, model,
|
|
786
|
+
flags_json, env_keys, status, error, child_token_id, created_at,
|
|
787
|
+
created_by_token, delivered_at, acked_at, child_node_id
|
|
788
|
+
)
|
|
789
|
+
SELECT
|
|
790
|
+
request_id, daemon_node_id, child_name, network_id, runtime, model,
|
|
791
|
+
flags_json, env_keys, status, error, child_token_id, created_at,
|
|
792
|
+
created_by_token, delivered_at, acked_at, child_node_id
|
|
793
|
+
FROM node_create_requests
|
|
794
|
+
`);
|
|
795
|
+
db.exec("DROP TABLE node_create_requests");
|
|
796
|
+
db.exec("ALTER TABLE node_create_requests_migrated RENAME TO node_create_requests");
|
|
797
|
+
});
|
|
798
|
+
}
|
|
799
|
+
migrateNodeCreateRequestsModelNullable();
|
|
800
|
+
|
|
801
|
+
// app「新建节点」工作目录 —— 请求带的 node_spec.workdir(可空;空 = 落 daemon cwd 的老行为)。
|
|
802
|
+
// 🔴 必须排在上面那个重建表迁移**之后**:它按显式列清单拷贝,排在前面的话,老库(model NOT NULL)
|
|
803
|
+
// 第一次启动时这一列会被重建吞掉。
|
|
804
|
+
try {
|
|
805
|
+
db.exec(`ALTER TABLE node_create_requests ADD COLUMN workdir TEXT`);
|
|
806
|
+
} catch (e: any) {
|
|
807
|
+
if (!/duplicate column|already exists/i.test(e?.message || "")) throw e;
|
|
808
|
+
}
|
|
809
|
+
|
|
810
|
+
// Registration also stamps acked_at, so it cannot prove daemon launch checks.
|
|
811
|
+
// Keep old rows NULL; run after the legacy model-nullability table rebuild.
|
|
812
|
+
try {
|
|
813
|
+
db.exec(`ALTER TABLE node_create_requests ADD COLUMN launch_verified_at BIGINT`);
|
|
814
|
+
} catch (e: any) {
|
|
815
|
+
if (!/duplicate column|already exists/i.test(e?.message || "")) throw e;
|
|
816
|
+
}
|
|
817
|
+
|
|
818
|
+
// Hub #938 — clone_node reuses this table (same token mint, sweeper, and
|
|
819
|
+
// register finalize) but must not be replayed as a blank create_node.
|
|
820
|
+
// NULL/empty = ordinary create. Non-empty JSON = clone directives.
|
|
821
|
+
try {
|
|
822
|
+
db.exec(`ALTER TABLE node_create_requests ADD COLUMN clone_json TEXT`);
|
|
823
|
+
} catch (e: any) {
|
|
824
|
+
if (!/duplicate column|already exists/i.test(e?.message || "")) throw e;
|
|
825
|
+
}
|
|
826
|
+
|
|
827
|
+
// #1493 — 把 user_inbox.network_id 升到 **schema 级 NOT NULL**(belt-and-suspenders,
|
|
828
|
+
// 叠在 send_desktop_message 的代码级三闸之上:canWrite / `!effectiveNetId` return /
|
|
829
|
+
// getUserNetworkRole,tools.ts)。「不产生 network_id=NULL 孤儿」现是代码级保证 + #1492
|
|
830
|
+
// 三道测试;schema 级约束让**任何**未来绕过那三闸写 NULL 的回归在 INSERT 处直接被
|
|
831
|
+
// 数据库拒(而非产出 scoped-unreadable 的静默孤儿)。
|
|
832
|
+
//
|
|
833
|
+
// SQLite 不能 `ALTER COLUMN ADD NOT NULL` → 建新表→copy→drop→rename(与本文件既有
|
|
834
|
+
// recreate-table 迁移同范式);新库的 CREATE 已直接 NOT NULL,迁移检测到就跳过(幂等)。
|
|
835
|
+
function migrateUserInboxNetworkIdNotNull() {
|
|
836
|
+
if (db.dialect === "postgres") {
|
|
837
|
+
try { db.exec("ALTER TABLE user_inbox ALTER COLUMN network_id SET NOT NULL"); } catch {}
|
|
838
|
+
return;
|
|
839
|
+
}
|
|
840
|
+
let createSql: string | undefined;
|
|
841
|
+
try {
|
|
842
|
+
createSql = db.get<{ sql: string }>("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'user_inbox'")?.sql;
|
|
843
|
+
} catch { return; }
|
|
844
|
+
if (!createSql) return; // 表不存在:上面的 CREATE 已建成 NOT NULL 新表
|
|
845
|
+
if (/network_id\s+TEXT\s+NOT\s+NULL/i.test(createSql)) return; // 已是 NOT NULL → 幂等跳过
|
|
846
|
+
|
|
847
|
+
// 🔴 迁移前守卫:存量若有 network_id IS NULL 行(按代码级三闸理应 0)→ **大声 warn +
|
|
848
|
+
// 跳过迁移**(列暂保持可空),hub 照常启动。fail-safe,不 throw(SDK马 review #1516):
|
|
849
|
+
// · 这条 NOT NULL 是 belt-and-suspenders,代码级三闸(#1492 三测钉着)已挡新 NULL;
|
|
850
|
+
// 为一条冗余保险带让**整个舰队的 hub** boot 期停摆,代价与收益不成比例;
|
|
851
|
+
// · 生产这个 COUNT 没人量过,而 #1493 第一条原则就是"没量过的数不要动手"——只要生产
|
|
852
|
+
// 有一行历史 NULL,throw 就把升级变成停机;
|
|
853
|
+
// · fail-closed 的真正目的(不盲目清空、不 COALESCE 猜网络)用 warn+skip 一样达到。
|
|
854
|
+
// ⚠ 校正:本文件既有迁移(migrateNodeCreateRequestsModelNullable 内部 catch{}+return;
|
|
855
|
+
// migrateSessionsNetworkAliasUnique 全函数 throw 0 次)都**不**在 boot 期打死 hub——
|
|
856
|
+
// "顶层无 try/catch"是真前提,但"所以 throw 符合惯例"是没验的推论(SDK马 量出),撤回。
|
|
857
|
+
// 孤儿行仍有明确运维信号,三闸仍生效;等人工量过、清干净,下次启动幂等判据自动完成迁移。
|
|
858
|
+
const nullCount = db.get<{ n: number }>("SELECT COUNT(*) AS n FROM user_inbox WHERE network_id IS NULL")?.n ?? 0;
|
|
859
|
+
if (nullCount > 0) {
|
|
860
|
+
console.error(
|
|
861
|
+
`[migrate #1493] user_inbox 有 ${nullCount} 行 network_id IS NULL —— 与 send_desktop_message ` +
|
|
862
|
+
`的代码级三闸矛盾,可能存在更早的写路径漏洞;已**跳过** NOT NULL 迁移(列暂保持可空),` +
|
|
863
|
+
`hub 正常启动。请人工排查这些孤儿行来源、清理后下次启动会自动完成迁移(不要盲目清空)。`,
|
|
864
|
+
);
|
|
865
|
+
return;
|
|
866
|
+
}
|
|
867
|
+
|
|
868
|
+
db.transaction(() => {
|
|
869
|
+
db.exec("DROP TABLE IF EXISTS user_inbox_migrated");
|
|
870
|
+
db.exec(`
|
|
871
|
+
CREATE TABLE user_inbox_migrated (
|
|
872
|
+
message_id TEXT PRIMARY KEY,
|
|
873
|
+
network_id TEXT NOT NULL,
|
|
874
|
+
user_id TEXT NOT NULL,
|
|
875
|
+
from_session TEXT,
|
|
876
|
+
kind TEXT NOT NULL DEFAULT 'info',
|
|
877
|
+
title TEXT,
|
|
878
|
+
content TEXT NOT NULL,
|
|
879
|
+
severity TEXT NOT NULL DEFAULT 'info',
|
|
880
|
+
meta_json TEXT,
|
|
881
|
+
acked INTEGER NOT NULL DEFAULT 0,
|
|
882
|
+
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
883
|
+
acked_at TEXT
|
|
884
|
+
)
|
|
885
|
+
`);
|
|
886
|
+
db.exec(`
|
|
887
|
+
INSERT INTO user_inbox_migrated
|
|
888
|
+
(message_id, network_id, user_id, from_session, kind, title, content, severity, meta_json, acked, created_at, acked_at)
|
|
889
|
+
SELECT
|
|
890
|
+
message_id, network_id, user_id, from_session, kind, title, content, severity, meta_json, acked, created_at, acked_at
|
|
891
|
+
FROM user_inbox
|
|
892
|
+
`);
|
|
893
|
+
db.exec("DROP TABLE user_inbox");
|
|
894
|
+
db.exec("ALTER TABLE user_inbox_migrated RENAME TO user_inbox");
|
|
895
|
+
});
|
|
896
|
+
}
|
|
897
|
+
migrateUserInboxNetworkIdNotNull();
|
|
898
|
+
// 迁移会 drop 掉旧表上的 idx_user_inbox_user_acked → 重建(IF NOT EXISTS;未迁移时 no-op)。
|
|
899
|
+
db.exec(`CREATE INDEX IF NOT EXISTS idx_user_inbox_user_acked ON user_inbox(user_id, acked, created_at);`);
|
|
900
|
+
// 多用户:人与人私信。sender_user_id 由 Hub 按发信人的**用户令牌**写入(不是客户端填的 from_session),
|
|
901
|
+
// 会话记录按它双向取;Agent / 节点令牌发来的桌面消息这一列为 NULL。
|
|
902
|
+
try { db.exec("ALTER TABLE user_inbox ADD COLUMN sender_user_id TEXT"); } catch {}
|
|
903
|
+
db.exec(`CREATE INDEX IF NOT EXISTS idx_user_inbox_dm ON user_inbox(network_id, user_id, sender_user_id, created_at);`);
|
|
904
|
+
|
|
905
|
+
db.exec(`
|
|
906
|
+
CREATE INDEX IF NOT EXISTS idx_ncr_daemon_status ON node_create_requests(daemon_node_id, status);
|
|
907
|
+
CREATE INDEX IF NOT EXISTS idx_ncr_network ON node_create_requests(network_id);
|
|
908
|
+
CREATE INDEX IF NOT EXISTS idx_ncr_child_name ON node_create_requests(child_name);
|
|
909
|
+
`);
|
|
497
910
|
try {
|
|
498
911
|
// Single-flight per (daemon, child_name) — prevents racing dashboard
|
|
499
912
|
// create on same name. Mirrors RFC-024 uniq_ncu_node_inflight.
|
|
@@ -523,6 +936,19 @@ db.exec(`
|
|
|
523
936
|
);
|
|
524
937
|
CREATE INDEX IF NOT EXISTS idx_providers_network ON providers(network_id);
|
|
525
938
|
`);
|
|
939
|
+
// #907 network-owned Provider configuration. Keys remain in network_secrets.
|
|
940
|
+
db.exec(`
|
|
941
|
+
CREATE TABLE IF NOT EXISTS hub_provider_configs (
|
|
942
|
+
network_id TEXT NOT NULL, provider_id TEXT NOT NULL, revision INTEGER NOT NULL,
|
|
943
|
+
config_json TEXT NOT NULL, secret_key_ref TEXT NOT NULL, updated_at INTEGER NOT NULL,
|
|
944
|
+
PRIMARY KEY(network_id, provider_id)
|
|
945
|
+
);
|
|
946
|
+
CREATE TABLE IF NOT EXISTS hub_provider_bindings (
|
|
947
|
+
request_id TEXT PRIMARY KEY, network_id TEXT NOT NULL, provider_id TEXT NOT NULL,
|
|
948
|
+
provider_revision INTEGER NOT NULL, daemon_node_id TEXT NOT NULL,
|
|
949
|
+
daemon_provider_id TEXT NOT NULL, created_at INTEGER NOT NULL
|
|
950
|
+
);
|
|
951
|
+
`);
|
|
526
952
|
db.exec(`
|
|
527
953
|
CREATE TABLE IF NOT EXISTS provider_models (
|
|
528
954
|
model_id TEXT PRIMARY KEY,
|
|
@@ -592,6 +1018,64 @@ db.exec(`
|
|
|
592
1018
|
CREATE INDEX IF NOT EXISTS idx_audit_network ON audit_log(network_id);
|
|
593
1019
|
`);
|
|
594
1020
|
|
|
1021
|
+
// SkillHub — immutable, network-scoped skill submissions. A (network, slug,
|
|
1022
|
+
// version) tuple is write-once: retries with the same content are idempotent,
|
|
1023
|
+
// while different content must use a new version. Node submissions remain
|
|
1024
|
+
// pending until an owner/admin explicitly publishes them.
|
|
1025
|
+
db.exec(`
|
|
1026
|
+
CREATE TABLE IF NOT EXISTS skillhub_skills (
|
|
1027
|
+
skill_id TEXT PRIMARY KEY,
|
|
1028
|
+
network_id TEXT NOT NULL,
|
|
1029
|
+
slug TEXT NOT NULL,
|
|
1030
|
+
name TEXT NOT NULL,
|
|
1031
|
+
description TEXT NOT NULL DEFAULT '',
|
|
1032
|
+
version TEXT NOT NULL,
|
|
1033
|
+
content TEXT NOT NULL,
|
|
1034
|
+
content_hash TEXT NOT NULL,
|
|
1035
|
+
status TEXT NOT NULL DEFAULT 'pending' CHECK(status IN ('pending', 'published', 'rejected', 'archived')),
|
|
1036
|
+
source_type TEXT NOT NULL CHECK(source_type IN ('node', 'user')),
|
|
1037
|
+
source_alias TEXT,
|
|
1038
|
+
created_by_user TEXT,
|
|
1039
|
+
reviewed_by_user TEXT,
|
|
1040
|
+
review_note TEXT,
|
|
1041
|
+
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
1042
|
+
updated_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
1043
|
+
reviewed_at TEXT,
|
|
1044
|
+
UNIQUE(network_id, slug, version)
|
|
1045
|
+
);
|
|
1046
|
+
CREATE INDEX IF NOT EXISTS idx_skillhub_network_status
|
|
1047
|
+
ON skillhub_skills(network_id, status, updated_at DESC);
|
|
1048
|
+
CREATE INDEX IF NOT EXISTS idx_skillhub_network_slug
|
|
1049
|
+
ON skillhub_skills(network_id, slug, version);
|
|
1050
|
+
`);
|
|
1051
|
+
|
|
1052
|
+
// 需求池。长期卡片,按 network 隔离。不是 tasks。
|
|
1053
|
+
db.exec(`
|
|
1054
|
+
CREATE TABLE IF NOT EXISTS requirements (
|
|
1055
|
+
requirement_id TEXT PRIMARY KEY,
|
|
1056
|
+
network_id TEXT NOT NULL,
|
|
1057
|
+
title TEXT NOT NULL,
|
|
1058
|
+
column_name TEXT NOT NULL DEFAULT 'pool' CHECK(column_name IN ('pool', 'doing', 'done', 'abandoned')),
|
|
1059
|
+
priority TEXT NOT NULL DEFAULT 'normal' CHECK(priority IN ('high', 'normal', 'low', 'lowest')),
|
|
1060
|
+
due_on TEXT,
|
|
1061
|
+
assignee TEXT,
|
|
1062
|
+
client_id TEXT,
|
|
1063
|
+
issues_json TEXT,
|
|
1064
|
+
created_by TEXT,
|
|
1065
|
+
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
1066
|
+
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
|
|
1067
|
+
);
|
|
1068
|
+
CREATE INDEX IF NOT EXISTS idx_requirements_network
|
|
1069
|
+
ON requirements(network_id, created_at DESC);
|
|
1070
|
+
`);
|
|
1071
|
+
try { db.exec("ALTER TABLE requirements ADD COLUMN client_id TEXT"); } catch {}
|
|
1072
|
+
try { db.exec("ALTER TABLE requirements ADD COLUMN issues_json TEXT"); } catch {}
|
|
1073
|
+
try { db.exec("ALTER TABLE requirements ADD COLUMN tags_json TEXT NOT NULL DEFAULT '[]'"); } catch (e: any) { if (!/duplicate column|already exists/i.test(e?.message || "")) throw e; }
|
|
1074
|
+
db.exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_requirements_client ON requirements(network_id, client_id) WHERE client_id IS NOT NULL AND client_id != ''");
|
|
1075
|
+
for (const column of ["owner_json TEXT", "participants_json TEXT NOT NULL DEFAULT '[]'", "agent_owner_json TEXT", "description TEXT", "checklist_json TEXT", "project_id TEXT", "external_ref TEXT", "external_url TEXT", "archived INTEGER NOT NULL DEFAULT 0", "created_by_json TEXT", "updated_by_json TEXT", "parent_id TEXT", "start_on TEXT"]) {
|
|
1076
|
+
try { db.exec(`ALTER TABLE requirements ADD COLUMN ${column}`); } catch (e: any) { if (!/duplicate column|already exists/i.test(e?.message || "")) throw e; }
|
|
1077
|
+
}
|
|
1078
|
+
|
|
595
1079
|
// ── V3: licenses table ──
|
|
596
1080
|
db.exec(`
|
|
597
1081
|
CREATE TABLE IF NOT EXISTS licenses (
|
|
@@ -648,6 +1132,68 @@ db.exec(`
|
|
|
648
1132
|
);
|
|
649
1133
|
`);
|
|
650
1134
|
|
|
1135
|
+
// ── 多用户账号与 Agent 权限:成员可见哪些 Agent ──
|
|
1136
|
+
// network_members.agent_access:
|
|
1137
|
+
// 'all' —— 旧语义:能看到并联系网络里所有 Agent。ALTER 的 DEFAULT 让**升级前已有的**成员行
|
|
1138
|
+
// 全部落在这里,生产上已有成员的可见范围不因升级而变。
|
|
1139
|
+
// 'granted' —— 只看到 network_member_agent_grants 里给了的 Agent。此后**新加入**的
|
|
1140
|
+
// member/viewer(管理员建号、POST members、邀请码)都以它入库,即默认零权限。
|
|
1141
|
+
// owner/admin 角色与 Hub 管理员不看这一列(永远全部可见),判定集中在 agent-access.ts。
|
|
1142
|
+
try { db.exec("ALTER TABLE network_members ADD COLUMN agent_access TEXT NOT NULL DEFAULT 'all'"); } catch {}
|
|
1143
|
+
// node_id 优先(稳定);alias 只给没有 node_id 的旧会话用。两者恰有其一。
|
|
1144
|
+
db.exec(`
|
|
1145
|
+
CREATE TABLE IF NOT EXISTS network_member_agent_grants (
|
|
1146
|
+
network_id TEXT NOT NULL,
|
|
1147
|
+
user_id TEXT NOT NULL,
|
|
1148
|
+
node_id TEXT,
|
|
1149
|
+
alias TEXT,
|
|
1150
|
+
can_message INTEGER NOT NULL DEFAULT 1,
|
|
1151
|
+
created_by TEXT,
|
|
1152
|
+
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
1153
|
+
CHECK ((node_id IS NULL) <> (alias IS NULL))
|
|
1154
|
+
);
|
|
1155
|
+
|
|
1156
|
+
CREATE UNIQUE INDEX IF NOT EXISTS idx_agent_grants_node ON network_member_agent_grants(network_id, user_id, node_id) WHERE node_id IS NOT NULL;
|
|
1157
|
+
CREATE UNIQUE INDEX IF NOT EXISTS idx_agent_grants_alias ON network_member_agent_grants(network_id, user_id, alias) WHERE alias IS NOT NULL;
|
|
1158
|
+
`);
|
|
1159
|
+
|
|
1160
|
+
// ── Agent 分组(RFC-038 §8):管理员自由定义的组,授权可以给到组,组成员动态生效 ──
|
|
1161
|
+
// 组授权单独一张表(不给 network_member_agent_grants 加列):那张表的 CHECK 改不了,
|
|
1162
|
+
// 而且旧 app 的 PUT 是整体替换 —— 同表的话,旧 app 一保存就把组授权清掉。
|
|
1163
|
+
db.exec(`
|
|
1164
|
+
CREATE TABLE IF NOT EXISTS agent_groups (
|
|
1165
|
+
group_id TEXT PRIMARY KEY,
|
|
1166
|
+
network_id TEXT NOT NULL,
|
|
1167
|
+
name TEXT NOT NULL,
|
|
1168
|
+
description TEXT,
|
|
1169
|
+
created_by TEXT,
|
|
1170
|
+
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
1171
|
+
updated_at TEXT
|
|
1172
|
+
);
|
|
1173
|
+
CREATE UNIQUE INDEX IF NOT EXISTS idx_agent_groups_name ON agent_groups(network_id, name);
|
|
1174
|
+
|
|
1175
|
+
CREATE TABLE IF NOT EXISTS agent_group_members (
|
|
1176
|
+
group_id TEXT NOT NULL,
|
|
1177
|
+
node_id TEXT NOT NULL,
|
|
1178
|
+
added_by TEXT,
|
|
1179
|
+
added_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
1180
|
+
PRIMARY KEY (group_id, node_id)
|
|
1181
|
+
);
|
|
1182
|
+
|
|
1183
|
+
CREATE TABLE IF NOT EXISTS network_member_group_grants (
|
|
1184
|
+
network_id TEXT NOT NULL,
|
|
1185
|
+
user_id TEXT NOT NULL,
|
|
1186
|
+
group_id TEXT NOT NULL,
|
|
1187
|
+
can_message INTEGER NOT NULL DEFAULT 1,
|
|
1188
|
+
created_by TEXT,
|
|
1189
|
+
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
1190
|
+
PRIMARY KEY (network_id, user_id, group_id)
|
|
1191
|
+
);
|
|
1192
|
+
-- 改组成员 / 删组时按组找被授权成员(usersGrantedGroup、granted_user_count):主键以 network_id 开头用不上。
|
|
1193
|
+
-- 展开查询本身走各表主键,见 agent-groups-perf.test.ts 的 EXPLAIN QUERY PLAN。
|
|
1194
|
+
CREATE INDEX IF NOT EXISTS idx_group_grants_group ON network_member_group_grants(group_id);
|
|
1195
|
+
`);
|
|
1196
|
+
|
|
651
1197
|
// ── #84: node rename — rename_txn table (RFC-010 §4) ──
|
|
652
1198
|
// Single isolated table holding the rename 2PC transaction state. It doubles
|
|
653
1199
|
// as the alias_rename_log (RFC §4 risk #5): the audit log of completed renames
|
|
@@ -702,6 +1248,14 @@ for (const table of ["sessions", "nodes", "tasks", "inbox", "task_events", "comp
|
|
|
702
1248
|
try { db.exec(`ALTER TABLE ${table} ADD COLUMN network_id TEXT`); } catch {}
|
|
703
1249
|
}
|
|
704
1250
|
|
|
1251
|
+
// #167 — stable lifecycle event names plus an internal idempotency key.
|
|
1252
|
+
// Ordinary status transitions keep event_key NULL, so retries and repeated
|
|
1253
|
+
// transitions remain auditable. Watcher warnings set a stable key; the unique
|
|
1254
|
+
// index makes every (task, threshold) write-once across patrol rounds/workers.
|
|
1255
|
+
try { db.exec("ALTER TABLE task_events ADD COLUMN event_type TEXT"); } catch {}
|
|
1256
|
+
try { db.exec("ALTER TABLE task_events ADD COLUMN event_key TEXT"); } catch {}
|
|
1257
|
+
try { db.exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_task_events_task_key ON task_events(task_id, event_key)"); } catch {}
|
|
1258
|
+
|
|
705
1259
|
// PR-1 (#146): durable node identity on historical inbox/tasks rows. Some
|
|
706
1260
|
// existing databases created `tasks` before from_node_id/to_node_id were in the
|
|
707
1261
|
// CREATE TABLE statement, so keep these ALTERs explicit and idempotent.
|
|
@@ -977,6 +1531,12 @@ migrateSessionsNetworkAliasUnique();
|
|
|
977
1531
|
try { db.exec("CREATE INDEX IF NOT EXISTS idx_sessions_network ON sessions(network_id)"); } catch {}
|
|
978
1532
|
try { db.exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_sessions_network_alias_unique ON sessions(network_id, alias)"); } catch {}
|
|
979
1533
|
try { db.exec("CREATE INDEX IF NOT EXISTS idx_tasks_network ON tasks(network_id)"); } catch {}
|
|
1534
|
+
// #500 — covering index for the full /api/status queue_depth GROUP BY (task-queue-ahead.ts queueDepthQuery): the 24 h
|
|
1535
|
+
// created_at range plus every column that query reads, so it never touches the (wide) task rows. Here, not in the
|
|
1536
|
+
// CREATE TABLE block: tasks.network_id only exists after the ALTER above. On a read-only copy of the production DB
|
|
1537
|
+
// (57k tasks, 1.9k in the last 24 h) the statement went from ~3 ms (idx_tasks_created + one row lookup per task) to
|
|
1538
|
+
// ~0.3 ms; building it there took ~170 ms once. Plain composite index: the same DDL runs on PostgreSQL.
|
|
1539
|
+
try { db.exec("CREATE INDEX IF NOT EXISTS idx_tasks_created_queue ON tasks(created_at, status, network_id, to_name)"); } catch {}
|
|
980
1540
|
try { db.exec("CREATE INDEX IF NOT EXISTS idx_nodes_network ON nodes(network_id)"); } catch {}
|
|
981
1541
|
try { db.exec("CREATE INDEX IF NOT EXISTS idx_inbox_network ON inbox(network_id)"); } catch {}
|
|
982
1542
|
try { db.exec("CREATE INDEX IF NOT EXISTS idx_task_events_network ON task_events(network_id)"); } catch {}
|
|
@@ -988,6 +1548,214 @@ try { db.exec("CREATE INDEX IF NOT EXISTS idx_completions_network ON completions
|
|
|
988
1548
|
// the reply up the chain via parent_task_id.
|
|
989
1549
|
try { db.exec("ALTER TABLE tasks ADD COLUMN parent_task_id TEXT"); } catch {}
|
|
990
1550
|
try { db.exec("ALTER TABLE tasks ADD COLUMN meta_json TEXT"); } catch {}
|
|
1551
|
+
// #520 — two monotonic evidence levels for this exact task:
|
|
1552
|
+
// runtime_submitted_at means agent-node handed the body to the vendor runtime;
|
|
1553
|
+
// consumed_at requires an attributable turn-start/first-activity signal.
|
|
1554
|
+
// Both stay separate from delivered_at (enqueue), acked (process receipt), and
|
|
1555
|
+
// started_at (legacy report_status/content matching). Old binaries ignore them.
|
|
1556
|
+
try { db.exec("ALTER TABLE tasks ADD COLUMN runtime_submitted_at TEXT"); } catch {}
|
|
1557
|
+
try { db.exec("ALTER TABLE tasks ADD COLUMN consumed_at TEXT"); } catch {}
|
|
1558
|
+
// Exact vendor-runtime boundary for SideThread-capable clients. These values
|
|
1559
|
+
// are written only by the token-bound target node after attributable runtime
|
|
1560
|
+
// evidence; the Hub never derives them from task text or caller input.
|
|
1561
|
+
try { db.exec("ALTER TABLE tasks ADD COLUMN thread_id TEXT"); } catch {}
|
|
1562
|
+
try { db.exec("ALTER TABLE tasks ADD COLUMN turn_id TEXT"); } catch {}
|
|
1563
|
+
|
|
1564
|
+
// Board #710 — a result that arrives after the task is already terminal is
|
|
1565
|
+
// evidence about that exact runtime turn, not a second task transition. Keep
|
|
1566
|
+
// it in an additive table: old clients and old Hub code continue to read the
|
|
1567
|
+
// tasks row unchanged, while new detail readers can project `late_replies`.
|
|
1568
|
+
db.exec(`
|
|
1569
|
+
CREATE TABLE IF NOT EXISTS task_late_replies (
|
|
1570
|
+
late_reply_id TEXT PRIMARY KEY,
|
|
1571
|
+
inbox_id TEXT NOT NULL UNIQUE,
|
|
1572
|
+
task_id TEXT NOT NULL,
|
|
1573
|
+
network_id TEXT,
|
|
1574
|
+
from_node_id TEXT NOT NULL,
|
|
1575
|
+
thread_id TEXT NOT NULL,
|
|
1576
|
+
turn_id TEXT NOT NULL,
|
|
1577
|
+
status TEXT NOT NULL CHECK (status IN ('replied','failed','cancelled')),
|
|
1578
|
+
result TEXT NOT NULL,
|
|
1579
|
+
meta_json TEXT,
|
|
1580
|
+
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
1581
|
+
UNIQUE (task_id, thread_id, turn_id)
|
|
1582
|
+
);
|
|
1583
|
+
CREATE INDEX IF NOT EXISTS idx_task_late_replies_task_time
|
|
1584
|
+
ON task_late_replies(task_id, created_at);
|
|
1585
|
+
CREATE INDEX IF NOT EXISTS idx_task_late_replies_network
|
|
1586
|
+
ON task_late_replies(network_id, created_at);
|
|
1587
|
+
`);
|
|
1588
|
+
|
|
1589
|
+
// #1181 durable outbound terminal cursor. A task's created_at cannot be used
|
|
1590
|
+
// as a recovery watermark because an old task may become terminal after newer
|
|
1591
|
+
// tasks. Record terminal transitions in their own monotonically increasing
|
|
1592
|
+
// journal instead. The journal is append-only for a logical task; retry keeps
|
|
1593
|
+
// the existing task identity and therefore the same idempotency domain.
|
|
1594
|
+
db.exec(`
|
|
1595
|
+
CREATE TABLE IF NOT EXISTS task_terminal_events (
|
|
1596
|
+
terminal_seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
1597
|
+
task_id TEXT NOT NULL UNIQUE,
|
|
1598
|
+
network_id TEXT,
|
|
1599
|
+
from_node_id TEXT,
|
|
1600
|
+
completed_at TEXT NOT NULL DEFAULT (datetime('now'))
|
|
1601
|
+
);
|
|
1602
|
+
CREATE INDEX IF NOT EXISTS idx_task_terminal_events_sender_seq
|
|
1603
|
+
ON task_terminal_events(network_id, from_node_id, terminal_seq);
|
|
1604
|
+
`);
|
|
1605
|
+
if (db.dialect === "sqlite") {
|
|
1606
|
+
db.exec(`
|
|
1607
|
+
CREATE TRIGGER IF NOT EXISTS tasks_terminal_event_insert
|
|
1608
|
+
AFTER INSERT ON tasks
|
|
1609
|
+
WHEN NEW.status IN ('replied', 'failed', 'cancelled', 'expired')
|
|
1610
|
+
BEGIN
|
|
1611
|
+
INSERT OR IGNORE INTO task_terminal_events (task_id, network_id, from_node_id, completed_at)
|
|
1612
|
+
VALUES (NEW.task_id, NEW.network_id, NEW.from_node_id, COALESCE(NEW.completed_at, datetime('now')));
|
|
1613
|
+
END;
|
|
1614
|
+
CREATE TRIGGER IF NOT EXISTS tasks_terminal_event_update
|
|
1615
|
+
AFTER UPDATE OF status ON tasks
|
|
1616
|
+
WHEN NEW.status IN ('replied', 'failed', 'cancelled', 'expired')
|
|
1617
|
+
AND OLD.status NOT IN ('replied', 'failed', 'cancelled', 'expired')
|
|
1618
|
+
BEGIN
|
|
1619
|
+
INSERT OR IGNORE INTO task_terminal_events (task_id, network_id, from_node_id, completed_at)
|
|
1620
|
+
VALUES (NEW.task_id, NEW.network_id, NEW.from_node_id, COALESCE(NEW.completed_at, datetime('now')));
|
|
1621
|
+
END;
|
|
1622
|
+
`);
|
|
1623
|
+
db.run(`INSERT OR IGNORE INTO task_terminal_events (task_id, network_id, from_node_id, completed_at)
|
|
1624
|
+
SELECT task_id, network_id, from_node_id, COALESCE(completed_at, created_at)
|
|
1625
|
+
FROM tasks
|
|
1626
|
+
WHERE status IN ('replied', 'failed', 'cancelled', 'expired')
|
|
1627
|
+
ORDER BY COALESCE(completed_at, created_at), task_id`);
|
|
1628
|
+
} else {
|
|
1629
|
+
db.exec(`
|
|
1630
|
+
CREATE OR REPLACE FUNCTION record_task_terminal_event() RETURNS trigger AS $$
|
|
1631
|
+
BEGIN
|
|
1632
|
+
IF NEW.status IN ('replied', 'failed', 'cancelled', 'expired')
|
|
1633
|
+
AND (TG_OP = 'INSERT' OR OLD.status NOT IN ('replied', 'failed', 'cancelled', 'expired')) THEN
|
|
1634
|
+
INSERT INTO task_terminal_events (task_id, network_id, from_node_id, completed_at)
|
|
1635
|
+
VALUES (NEW.task_id, NEW.network_id, NEW.from_node_id, COALESCE(NEW.completed_at, datetime('now')))
|
|
1636
|
+
ON CONFLICT (task_id) DO NOTHING;
|
|
1637
|
+
END IF;
|
|
1638
|
+
RETURN NEW;
|
|
1639
|
+
END;
|
|
1640
|
+
$$ LANGUAGE plpgsql;
|
|
1641
|
+
DROP TRIGGER IF EXISTS tasks_terminal_event_insert ON tasks;
|
|
1642
|
+
DROP TRIGGER IF EXISTS tasks_terminal_event_update ON tasks;
|
|
1643
|
+
CREATE TRIGGER tasks_terminal_event_insert AFTER INSERT ON tasks
|
|
1644
|
+
FOR EACH ROW EXECUTE FUNCTION record_task_terminal_event();
|
|
1645
|
+
CREATE TRIGGER tasks_terminal_event_update AFTER UPDATE OF status ON tasks
|
|
1646
|
+
FOR EACH ROW EXECUTE FUNCTION record_task_terminal_event();
|
|
1647
|
+
INSERT INTO task_terminal_events (task_id, network_id, from_node_id, completed_at)
|
|
1648
|
+
SELECT task_id, network_id, from_node_id, COALESCE(completed_at, created_at)
|
|
1649
|
+
FROM tasks WHERE status IN ('replied', 'failed', 'cancelled', 'expired')
|
|
1650
|
+
ON CONFLICT (task_id) DO NOTHING;
|
|
1651
|
+
`);
|
|
1652
|
+
}
|
|
1653
|
+
|
|
1654
|
+
// ── Hub scheduled tasks ──────────────────────────────────────────────
|
|
1655
|
+
// Scheduling is a Hub concern: clients manage these rows, while agents only
|
|
1656
|
+
// receive the ordinary inbox/tasks rows produced for each occurrence. Keep
|
|
1657
|
+
// the occurrence table separate so retries, skips and failures remain
|
|
1658
|
+
// auditable without overloading the task lifecycle.
|
|
1659
|
+
db.exec(`
|
|
1660
|
+
CREATE TABLE IF NOT EXISTS scheduled_tasks (
|
|
1661
|
+
schedule_id TEXT PRIMARY KEY,
|
|
1662
|
+
network_id TEXT NOT NULL,
|
|
1663
|
+
created_by TEXT,
|
|
1664
|
+
name TEXT NOT NULL,
|
|
1665
|
+
target_node_id TEXT NOT NULL,
|
|
1666
|
+
target_alias TEXT NOT NULL,
|
|
1667
|
+
task_content TEXT NOT NULL,
|
|
1668
|
+
priority TEXT NOT NULL DEFAULT 'normal',
|
|
1669
|
+
schedule_type TEXT NOT NULL,
|
|
1670
|
+
schedule_json TEXT NOT NULL,
|
|
1671
|
+
timezone TEXT NOT NULL DEFAULT 'UTC',
|
|
1672
|
+
overlap_policy TEXT NOT NULL DEFAULT 'skip',
|
|
1673
|
+
misfire_policy TEXT NOT NULL DEFAULT 'catch_up_once',
|
|
1674
|
+
status TEXT NOT NULL DEFAULT 'active',
|
|
1675
|
+
next_run_at TEXT,
|
|
1676
|
+
last_run_at TEXT,
|
|
1677
|
+
revision INTEGER NOT NULL DEFAULT 1,
|
|
1678
|
+
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
1679
|
+
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
|
|
1680
|
+
);
|
|
1681
|
+
|
|
1682
|
+
CREATE INDEX IF NOT EXISTS idx_scheduled_tasks_due
|
|
1683
|
+
ON scheduled_tasks(status, next_run_at);
|
|
1684
|
+
CREATE INDEX IF NOT EXISTS idx_scheduled_tasks_network
|
|
1685
|
+
ON scheduled_tasks(network_id, updated_at DESC);
|
|
1686
|
+
CREATE INDEX IF NOT EXISTS idx_scheduled_tasks_target
|
|
1687
|
+
ON scheduled_tasks(network_id, target_node_id);
|
|
1688
|
+
|
|
1689
|
+
CREATE TABLE IF NOT EXISTS scheduled_task_runs (
|
|
1690
|
+
run_id TEXT PRIMARY KEY,
|
|
1691
|
+
schedule_id TEXT NOT NULL,
|
|
1692
|
+
network_id TEXT NOT NULL,
|
|
1693
|
+
scheduled_for TEXT NOT NULL,
|
|
1694
|
+
task_id TEXT,
|
|
1695
|
+
status TEXT NOT NULL,
|
|
1696
|
+
error_code TEXT,
|
|
1697
|
+
error_message TEXT,
|
|
1698
|
+
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
1699
|
+
completed_at TEXT,
|
|
1700
|
+
UNIQUE(schedule_id, scheduled_for)
|
|
1701
|
+
);
|
|
1702
|
+
|
|
1703
|
+
CREATE INDEX IF NOT EXISTS idx_scheduled_runs_schedule
|
|
1704
|
+
ON scheduled_task_runs(schedule_id, created_at DESC);
|
|
1705
|
+
CREATE INDEX IF NOT EXISTS idx_scheduled_runs_network
|
|
1706
|
+
ON scheduled_task_runs(network_id, created_at DESC);
|
|
1707
|
+
`);
|
|
1708
|
+
try { db.exec("ALTER TABLE scheduled_tasks ADD COLUMN misfire_policy TEXT NOT NULL DEFAULT 'catch_up_once'"); } catch {}
|
|
1709
|
+
// Skipped runs (overlap_policy=skip) name the open task that blocked them and
|
|
1710
|
+
// whether the node had ever picked it up: not_received | in_progress.
|
|
1711
|
+
try { db.exec("ALTER TABLE scheduled_task_runs ADD COLUMN blocked_by_task_id TEXT"); } catch {}
|
|
1712
|
+
try { db.exec("ALTER TABLE scheduled_task_runs ADD COLUMN blocked_by_state TEXT"); } catch {}
|
|
1713
|
+
// Board #733 — schedules an Agent created over MCP name the creating node. NULL = created by a person
|
|
1714
|
+
// (REST / Dashboard) or a row from before this column; old rows keep NULL and old code never reads it.
|
|
1715
|
+
try { db.exec("ALTER TABLE scheduled_tasks ADD COLUMN created_by_node_id TEXT"); } catch {}
|
|
1716
|
+
try { db.exec("CREATE INDEX IF NOT EXISTS idx_scheduled_tasks_creator_node ON scheduled_tasks(network_id, created_by_node_id)"); } catch {}
|
|
1717
|
+
// #523 — consecutive-failure alert bookkeeping (scheduled-failures.ts). Additive and nullable:
|
|
1718
|
+
// an older Hub never reads them, so rolling back is safe. failure_alert_at = ISO time of the last
|
|
1719
|
+
// alert; failure_alert_key = the last successful run_id at that moment ('' = none yet), so a
|
|
1720
|
+
// success in between re-arms the alert.
|
|
1721
|
+
try { db.exec("ALTER TABLE scheduled_tasks ADD COLUMN failure_alert_at TEXT"); } catch {}
|
|
1722
|
+
try { db.exec("ALTER TABLE scheduled_tasks ADD COLUMN failure_alert_key TEXT"); } catch {}
|
|
1723
|
+
// Board #757 — one warning per continuous target-offline episode. The scheduler
|
|
1724
|
+
// clears this as soon as the target session is online again; older Hubs ignore it.
|
|
1725
|
+
try { db.exec("ALTER TABLE scheduled_tasks ADD COLUMN offline_alert_at TEXT"); } catch {}
|
|
1726
|
+
|
|
1727
|
+
// RFC-036 / B4 — owner-authorized edits of node-host managed schedules.
|
|
1728
|
+
// This is intentionally separate from Hub scheduled_tasks: these rows are
|
|
1729
|
+
// one-shot control intents consumed by the exact token-bound node. The partial
|
|
1730
|
+
// unique index makes the single-flight promise survive multiple Hub workers.
|
|
1731
|
+
db.exec(`
|
|
1732
|
+
CREATE TABLE IF NOT EXISTS external_schedule_edits (
|
|
1733
|
+
intent_id TEXT PRIMARY KEY,
|
|
1734
|
+
network_id TEXT NOT NULL,
|
|
1735
|
+
node_id TEXT NOT NULL,
|
|
1736
|
+
schedule_id TEXT NOT NULL,
|
|
1737
|
+
base_revision INTEGER NOT NULL,
|
|
1738
|
+
patch_json TEXT NOT NULL,
|
|
1739
|
+
status TEXT NOT NULL DEFAULT 'pending',
|
|
1740
|
+
expires_at INTEGER NOT NULL,
|
|
1741
|
+
created_at INTEGER NOT NULL,
|
|
1742
|
+
delivered_at INTEGER,
|
|
1743
|
+
acked_at INTEGER,
|
|
1744
|
+
created_by_user TEXT NOT NULL,
|
|
1745
|
+
created_by_token TEXT NOT NULL,
|
|
1746
|
+
consumed_by_token TEXT,
|
|
1747
|
+
result_revision INTEGER,
|
|
1748
|
+
error_code TEXT
|
|
1749
|
+
);
|
|
1750
|
+
|
|
1751
|
+
CREATE INDEX IF NOT EXISTS idx_external_schedule_edits_node
|
|
1752
|
+
ON external_schedule_edits(network_id, node_id, status, created_at);
|
|
1753
|
+
CREATE INDEX IF NOT EXISTS idx_external_schedule_edits_owner
|
|
1754
|
+
ON external_schedule_edits(created_by_user, created_at DESC);
|
|
1755
|
+
CREATE UNIQUE INDEX IF NOT EXISTS idx_external_schedule_edits_singleflight
|
|
1756
|
+
ON external_schedule_edits(node_id, schedule_id)
|
|
1757
|
+
WHERE status IN ('pending', 'delivered');
|
|
1758
|
+
`);
|
|
991
1759
|
try { db.exec("CREATE INDEX IF NOT EXISTS idx_tasks_parent ON tasks(parent_task_id)"); } catch {}
|
|
992
1760
|
|
|
993
1761
|
// Helpers
|
|
@@ -1296,38 +2064,40 @@ export function chainReplyToParent(
|
|
|
1296
2064
|
const marker = `\n\n[via ${childAlias} 子任务结果]\n${currentReply}`;
|
|
1297
2065
|
const newResult = parent.result ? parent.result + marker : `[via ${childAlias} 子任务结果]\n${currentReply}`;
|
|
1298
2066
|
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
);
|
|
1308
|
-
logTaskEvent(parent.task_id, parent.status, replyStatus, "auto-chain", `from ${childAlias}`);
|
|
1309
|
-
} else {
|
|
1310
|
-
db.run(
|
|
1311
|
-
"UPDATE tasks SET result = ?1, completed_at = datetime('now') WHERE task_id = ?2",
|
|
1312
|
-
[newResult.slice(0, 8000), parent.task_id]
|
|
1313
|
-
);
|
|
1314
|
-
logTaskEvent(parent.task_id, parent.status, parent.status, "auto-chain-append", `from ${childAlias}`);
|
|
1315
|
-
}
|
|
1316
|
-
|
|
1317
|
-
if (parent.from_name && parent.from_name !== "hub" && parent.from_name !== "api") {
|
|
1318
|
-
try {
|
|
1319
|
-
const notifyId = `chain_${crypto.randomUUID().replace(/-/g, "").slice(0, 16)}`;
|
|
1320
|
-
const notifyNode = db.get<{ node_id: string | null }>(
|
|
1321
|
-
"SELECT node_id FROM sessions WHERE alias = ?1 AND COALESCE(network_id, 'default') = COALESCE(?2, 'default') ORDER BY updated_at DESC LIMIT 1",
|
|
1322
|
-
[parent.from_name, parent.network_id ?? null]
|
|
2067
|
+
db.transaction(() => {
|
|
2068
|
+
// Bump parent status to replied if still open. The task transition and
|
|
2069
|
+
// its scheduler-run mirror share this transaction, so a crash cannot
|
|
2070
|
+
// leave one terminal while the other remains delivered.
|
|
2071
|
+
if (parent.status === "delivered" || parent.status === "acked" || parent.status === "running" || parent.status === "created") {
|
|
2072
|
+
db.run(
|
|
2073
|
+
"UPDATE tasks SET status = ?1, result = ?2, completed_at = datetime('now') WHERE task_id = ?3",
|
|
2074
|
+
[replyStatus, newResult.slice(0, 8000), parent.task_id]
|
|
1323
2075
|
);
|
|
2076
|
+
syncScheduledRunForTask(parent.task_id, parent.network_id);
|
|
2077
|
+
logTaskEvent(parent.task_id, parent.status, replyStatus, "auto-chain", `from ${childAlias}`);
|
|
2078
|
+
} else {
|
|
1324
2079
|
db.run(
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
[notifyId, parent.from_name, notifyNode?.node_id ?? null, `[${childAlias} 子任务完成]\n${currentReply.slice(0, 4000)}`, parent.to_name, parent.task_id, parent.network_id ?? null]
|
|
2080
|
+
"UPDATE tasks SET result = ?1, completed_at = datetime('now') WHERE task_id = ?2",
|
|
2081
|
+
[newResult.slice(0, 8000), parent.task_id]
|
|
1328
2082
|
);
|
|
1329
|
-
|
|
1330
|
-
|
|
2083
|
+
logTaskEvent(parent.task_id, parent.status, parent.status, "auto-chain-append", `from ${childAlias}`);
|
|
2084
|
+
}
|
|
2085
|
+
|
|
2086
|
+
if (parent.from_name && parent.from_name !== "hub" && parent.from_name !== "api") {
|
|
2087
|
+
try {
|
|
2088
|
+
const notifyId = `chain_${crypto.randomUUID().replace(/-/g, "").slice(0, 16)}`;
|
|
2089
|
+
const notifyNode = db.get<{ node_id: string | null }>(
|
|
2090
|
+
"SELECT node_id FROM sessions WHERE alias = ?1 AND COALESCE(network_id, 'default') = COALESCE(?2, 'default') ORDER BY updated_at DESC LIMIT 1",
|
|
2091
|
+
[parent.from_name, parent.network_id ?? null]
|
|
2092
|
+
);
|
|
2093
|
+
db.run(
|
|
2094
|
+
`INSERT INTO inbox (id, session_name, node_id, type, priority, content, from_session, in_reply_to, requires_response, network_id)
|
|
2095
|
+
VALUES (?1, ?2, ?3, 'reply', 'normal', ?4, ?5, ?6, 'none', ?7)`,
|
|
2096
|
+
[notifyId, parent.from_name, notifyNode?.node_id ?? null, `[${childAlias} 子任务完成]\n${currentReply.slice(0, 4000)}`, parent.to_name, parent.task_id, parent.network_id ?? null]
|
|
2097
|
+
);
|
|
2098
|
+
} catch {}
|
|
2099
|
+
}
|
|
2100
|
+
});
|
|
1331
2101
|
|
|
1332
2102
|
// This iteration actually wrote a parent row (and possibly an
|
|
1333
2103
|
// inbox notification). Record that so the caller can gate its
|
|
@@ -1341,12 +2111,137 @@ export function chainReplyToParent(
|
|
|
1341
2111
|
return { chained };
|
|
1342
2112
|
}
|
|
1343
2113
|
|
|
2114
|
+
const SCHEDULED_RUN_TERMINAL_STATUSES = new Set(["replied", "failed", "cancelled", "expired"]);
|
|
2115
|
+
|
|
2116
|
+
// #523 — called after a run row is closed by its task's terminal state. Registered by
|
|
2117
|
+
// scheduled-failures.ts (a hook, not an import: that module depends on db.ts). Never throws.
|
|
2118
|
+
type ScheduledRunTerminalHook = (scheduleId: string, status: string) => void;
|
|
2119
|
+
let scheduledRunTerminalHook: ScheduledRunTerminalHook | null = null;
|
|
2120
|
+
export function setScheduledRunTerminalHook(fn: ScheduledRunTerminalHook | null): void { scheduledRunTerminalHook = fn; }
|
|
2121
|
+
function fireScheduledRunTerminalHook(scheduleId: string, status: string): void {
|
|
2122
|
+
if (!scheduledRunTerminalHook) return;
|
|
2123
|
+
try { scheduledRunTerminalHook(scheduleId, status); } catch (e: any) {
|
|
2124
|
+
console.error(`[scheduled-tasks] run terminal hook failed schedule=${scheduleId}: ${e?.message || e}`);
|
|
2125
|
+
}
|
|
2126
|
+
}
|
|
2127
|
+
|
|
2128
|
+
type ScheduledTaskLifecycleRow = {
|
|
2129
|
+
task_id: string;
|
|
2130
|
+
network_id: string | null;
|
|
2131
|
+
status: string;
|
|
2132
|
+
completed_at: string | null;
|
|
2133
|
+
};
|
|
2134
|
+
|
|
2135
|
+
type ScheduledTaskBinding = { run_id: string; schedule_id: string };
|
|
2136
|
+
|
|
2137
|
+
/**
|
|
2138
|
+
* Mirror an exact scheduler-created task's lifecycle into its run row.
|
|
2139
|
+
*
|
|
2140
|
+
* The status is always read back from `tasks`; callers cannot supply one.
|
|
2141
|
+
* The scheduler's storage binding is the four-part tuple
|
|
2142
|
+
* (run_id, schedule_id, task_id, network_id). It is read from
|
|
2143
|
+
* `scheduled_task_runs`, not caller-controlled task metadata (which may also
|
|
2144
|
+
* legitimately be replaced by reply attachment metadata).
|
|
2145
|
+
*
|
|
2146
|
+
* Terminal states close the run. `retry_task` calls this after resetting the
|
|
2147
|
+
* same logical task_id to delivered, which deliberately reopens that run so
|
|
2148
|
+
* the history reflects the current retry rather than the first failed attempt.
|
|
2149
|
+
*/
|
|
2150
|
+
export function syncScheduledRunForTask(taskId: string, expectedNetworkId?: string | null): { matched: boolean; status?: string } {
|
|
2151
|
+
const task = db.get<ScheduledTaskLifecycleRow>(
|
|
2152
|
+
`SELECT task_id, network_id, status, completed_at
|
|
2153
|
+
FROM tasks
|
|
2154
|
+
WHERE task_id = ?1
|
|
2155
|
+
AND (CAST(?2 AS TEXT) IS NULL OR network_id = ?2)`,
|
|
2156
|
+
taskId,
|
|
2157
|
+
expectedNetworkId ?? null,
|
|
2158
|
+
);
|
|
2159
|
+
if (!task?.network_id) return { matched: false };
|
|
2160
|
+
const bindings = db.all<ScheduledTaskBinding>(
|
|
2161
|
+
`SELECT run_id, schedule_id FROM scheduled_task_runs
|
|
2162
|
+
WHERE task_id = ?1 AND network_id = ?2`,
|
|
2163
|
+
task.task_id,
|
|
2164
|
+
task.network_id,
|
|
2165
|
+
);
|
|
2166
|
+
// One task belongs to at most one scheduled occurrence. Fail closed if a
|
|
2167
|
+
// corrupt/legacy database violates that invariant rather than fanning one
|
|
2168
|
+
// lifecycle transition into multiple runs.
|
|
2169
|
+
if (bindings.length !== 1) return { matched: false };
|
|
2170
|
+
const binding = bindings[0];
|
|
2171
|
+
|
|
2172
|
+
if (SCHEDULED_RUN_TERMINAL_STATUSES.has(task.status)) {
|
|
2173
|
+
const errorCode = task.status === "replied" ? null : `task_${task.status}`;
|
|
2174
|
+
const updated = db.run(
|
|
2175
|
+
`UPDATE scheduled_task_runs
|
|
2176
|
+
SET status = ?1,
|
|
2177
|
+
error_code = ?2,
|
|
2178
|
+
error_message = NULL,
|
|
2179
|
+
completed_at = COALESCE(?3, datetime('now'))
|
|
2180
|
+
WHERE run_id = ?4 AND task_id = ?5 AND network_id = ?6 AND schedule_id = ?7`,
|
|
2181
|
+
[task.status, errorCode, task.completed_at, binding.run_id, task.task_id, task.network_id, binding.schedule_id],
|
|
2182
|
+
);
|
|
2183
|
+
if (updated.changes === 1) fireScheduledRunTerminalHook(binding.schedule_id, task.status);
|
|
2184
|
+
return { matched: updated.changes === 1, status: task.status };
|
|
2185
|
+
}
|
|
2186
|
+
|
|
2187
|
+
if (task.status === "delivered") {
|
|
2188
|
+
const updated = db.run(
|
|
2189
|
+
`UPDATE scheduled_task_runs
|
|
2190
|
+
SET status = 'delivered', error_code = NULL, error_message = NULL, completed_at = NULL
|
|
2191
|
+
WHERE run_id = ?1 AND task_id = ?2 AND network_id = ?3 AND schedule_id = ?4`,
|
|
2192
|
+
[binding.run_id, task.task_id, task.network_id, binding.schedule_id],
|
|
2193
|
+
);
|
|
2194
|
+
return { matched: updated.changes === 1, status: task.status };
|
|
2195
|
+
}
|
|
2196
|
+
|
|
2197
|
+
return { matched: false };
|
|
2198
|
+
}
|
|
2199
|
+
|
|
2200
|
+
function taskEventTypeForStatus(toStatus: string): string {
|
|
2201
|
+
switch (toStatus) {
|
|
2202
|
+
case "delivered": return "task.send.delivered";
|
|
2203
|
+
case "acked": return "task.ack";
|
|
2204
|
+
case "running": return "task.started";
|
|
2205
|
+
case "replied": return "task.replied";
|
|
2206
|
+
case "expired": return "task.expired";
|
|
2207
|
+
case "failed":
|
|
2208
|
+
case "cancelled": return "task.failed";
|
|
2209
|
+
default: return `task.status.${toStatus}`;
|
|
2210
|
+
}
|
|
2211
|
+
}
|
|
2212
|
+
|
|
1344
2213
|
export function logTaskEvent(taskId: string, fromStatus: string | null, toStatus: string, actor: string, detail?: string) {
|
|
1345
2214
|
try {
|
|
1346
2215
|
db.run(
|
|
1347
|
-
`INSERT INTO task_events (task_id, from_status, to_status, actor, detail, network_id)
|
|
1348
|
-
VALUES (?1, ?2, ?3, ?4, ?5, (SELECT network_id FROM tasks WHERE task_id = ?1))`,
|
|
1349
|
-
[taskId, fromStatus, toStatus, actor, detail ?? null]
|
|
2216
|
+
`INSERT INTO task_events (task_id, from_status, to_status, event_type, actor, detail, network_id)
|
|
2217
|
+
VALUES (?1, ?2, ?3, ?4, ?5, ?6, (SELECT network_id FROM tasks WHERE task_id = ?1))`,
|
|
2218
|
+
[taskId, fromStatus, toStatus, taskEventTypeForStatus(toStatus), actor, detail ?? null]
|
|
1350
2219
|
);
|
|
1351
2220
|
} catch {}
|
|
1352
2221
|
}
|
|
2222
|
+
|
|
2223
|
+
// RFC-039 F3: queries break created_at ties with SQLite's implicit rowid
|
|
2224
|
+
// (insertion order). PostgreSQL has none, so give these tables a real one.
|
|
2225
|
+
if (db.dialect === "postgres") {
|
|
2226
|
+
for (const table of ["nodes", "user_inbox"]) db.exec(`ALTER TABLE ${table} ADD COLUMN IF NOT EXISTS rowid BIGSERIAL`);
|
|
2227
|
+
}
|
|
2228
|
+
|
|
2229
|
+
// Board #625: common SQLite/PostgreSQL DDL. Adoption records authority, not processes.
|
|
2230
|
+
db.exec(`
|
|
2231
|
+
CREATE TABLE IF NOT EXISTS node_daemon_bindings (
|
|
2232
|
+
request_id TEXT PRIMARY KEY,
|
|
2233
|
+
network_id TEXT NOT NULL,
|
|
2234
|
+
node_id TEXT NOT NULL,
|
|
2235
|
+
daemon_node_id TEXT NOT NULL,
|
|
2236
|
+
workdir TEXT NOT NULL,
|
|
2237
|
+
requested_by TEXT NOT NULL,
|
|
2238
|
+
status TEXT NOT NULL CHECK (status IN ('pending','active','refused','revoked')),
|
|
2239
|
+
error TEXT,
|
|
2240
|
+
created_at BIGINT NOT NULL,
|
|
2241
|
+
updated_at BIGINT NOT NULL
|
|
2242
|
+
);
|
|
2243
|
+
CREATE UNIQUE INDEX IF NOT EXISTS idx_ndb_live_node
|
|
2244
|
+
ON node_daemon_bindings(node_id) WHERE status IN ('pending','active');
|
|
2245
|
+
CREATE INDEX IF NOT EXISTS idx_ndb_daemon_network
|
|
2246
|
+
ON node_daemon_bindings(daemon_node_id,network_id,status);
|
|
2247
|
+
`);
|