@sleep2agi/commhub-server 0.9.0-preview.7 → 0.9.0-preview.70

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.
Files changed (162) hide show
  1. package/README.md +125 -7
  2. package/bin/commhub.ts +10 -2
  3. package/package.json +5 -5
  4. package/src/ack-create-request-transport.test.ts +159 -0
  5. package/src/ack-create-request.test.ts +331 -0
  6. package/src/admin-networks-http.test.ts +88 -0
  7. package/src/agent-access.ts +267 -0
  8. package/src/agent-acl-http.test.ts +510 -0
  9. package/src/agent-acl-slice3-http.test.ts +267 -0
  10. package/src/alias-filter.test.ts +72 -0
  11. package/src/alias-filter.ts +32 -0
  12. package/src/api-host-supervisors-can-create-nodes.test.ts +350 -0
  13. package/src/api-host-supervisors-fallback.test.ts +271 -0
  14. package/src/api-nodes-shape.test.ts +26 -10
  15. package/src/auth-sessions-http.test.ts +250 -0
  16. package/src/auth-validate.test.ts +5 -1
  17. package/src/auth.ts +348 -29
  18. package/src/avatar-validate.test.ts +163 -0
  19. package/src/avatar-validate.ts +103 -0
  20. package/src/blocked-exit-on-reply.test.ts +122 -0
  21. package/src/boot-side-effect.test.ts +124 -0
  22. package/src/config-apply-sec1.test.ts +107 -0
  23. package/src/config-apply-validate.test.ts +92 -0
  24. package/src/config-apply-validate.ts +81 -3
  25. package/src/create-node-blocked-gate.test.ts +356 -0
  26. package/src/create-node-tool-schema.test.ts +39 -0
  27. package/src/create-node-validate.test.ts +89 -1
  28. package/src/create-node-validate.ts +89 -7
  29. package/src/create-node-workdir.test.ts +255 -0
  30. package/src/create-node.ts +51 -1
  31. package/src/dashboard-slash-routing-http.test.ts +107 -0
  32. package/src/db-adapter-guard.test.ts +85 -0
  33. package/src/db-adapter.ts +64 -23
  34. package/src/db-timestamp.test.ts +38 -0
  35. package/src/db-timestamp.ts +15 -0
  36. package/src/db.ts +762 -33
  37. package/src/delivered-without-push.test.ts +140 -0
  38. package/src/desktop-message-seam.test.ts +150 -0
  39. package/src/desktop-message.test.ts +368 -0
  40. package/src/ext-token-shared.test.ts +60 -0
  41. package/src/ext-validation-regression.test.ts +131 -0
  42. package/src/external-schedule-edits-http.test.ts +321 -0
  43. package/src/external-schedule-edits-timestamps.test.ts +64 -0
  44. package/src/external-schedule-edits.ts +327 -0
  45. package/src/file-download-authz-dev-open.test.ts +135 -0
  46. package/src/file-download-authz.test.ts +404 -0
  47. package/src/file-download-date-bucket.test.ts +436 -0
  48. package/src/file-network-scope-dev-open.test.ts +97 -0
  49. package/src/file-network-scope.test.ts +732 -0
  50. package/src/health-redaction.test.ts +642 -0
  51. package/src/http-gzip.test.ts +73 -0
  52. package/src/http-gzip.ts +60 -0
  53. package/src/hub-timestamp.test.ts +38 -0
  54. package/src/hub-timestamp.ts +27 -0
  55. package/src/human-dm.ts +149 -0
  56. package/src/inbox-count-sse.test.ts +310 -0
  57. package/src/inbox-count.ts +29 -0
  58. package/src/index.ts +15 -2331
  59. package/src/lifecycle-guard.ts +50 -0
  60. package/src/mcp-write-network-resolution.test.ts +429 -0
  61. package/src/messages-ack-by-agent-http.test.ts +142 -0
  62. package/src/network-name-http.test.ts +75 -0
  63. package/src/network-scope.ts +224 -0
  64. package/src/node-attrs-validate.ts +88 -0
  65. package/src/node-attrs.test.ts +217 -0
  66. package/src/node-create-request-status-http.test.ts +92 -0
  67. package/src/node-files-transport.test.ts +344 -0
  68. package/src/node-id-alias.test.ts +188 -0
  69. package/src/node-lifecycle-controllable.test.ts +64 -0
  70. package/src/node-lifecycle-controllable.ts +51 -0
  71. package/src/node-logs-transport.test.ts +263 -0
  72. package/src/node-request-retention.test.ts +281 -0
  73. package/src/node-request-retention.ts +120 -0
  74. package/src/node-skills-transport.test.ts +209 -0
  75. package/src/node-token-privilege-http.test.ts +149 -0
  76. package/src/observer-avatar-http.test.ts +429 -0
  77. package/src/observer-push.test.ts +252 -0
  78. package/src/package-version-consistency.test.ts +25 -0
  79. package/src/peer-reply-atomic.test.ts +455 -0
  80. package/src/peer-reply-capability.test.ts +70 -0
  81. package/src/push.ts +204 -7
  82. package/src/redact-tokens.test.ts +65 -0
  83. package/src/redact-tokens.ts +40 -0
  84. package/src/rename.ts +7 -2
  85. package/src/reply-target-derivation.test.ts +96 -0
  86. package/src/report-status-host-schema.test.ts +211 -0
  87. package/src/report-status-resume-id-handover.test.ts +150 -0
  88. package/src/require-explicit-test-db.ts +9 -0
  89. package/src/requirement-tags.ts +16 -0
  90. package/src/requirements-http.test.ts +708 -0
  91. package/src/requirements-mcp.test.ts +142 -0
  92. package/src/requirements-migrate.ts +83 -0
  93. package/src/requirements-priority-lowest.test.ts +114 -0
  94. package/src/requirements-upgrade-e2e.test.ts +126 -0
  95. package/src/requirements-upgrade-migration.test.ts +85 -0
  96. package/src/requirements.ts +865 -0
  97. package/src/resolve-port.test.ts +57 -0
  98. package/src/resolve-port.ts +44 -0
  99. package/src/response-charset.test.ts +130 -0
  100. package/src/rest-explicit-columns-http.test.ts +216 -0
  101. package/src/rest-identity.test.ts +129 -0
  102. package/src/rest-identity.ts +100 -0
  103. package/src/rest-projections.ts +68 -0
  104. package/src/rest-write-network-resolution.test.ts +133 -0
  105. package/src/restricted-files.ts +73 -0
  106. package/src/retention.ts +10 -1
  107. package/src/rules-file-duplicate-alias.test.ts +234 -0
  108. package/src/rules-file-session-target.test.ts +207 -0
  109. package/src/rules-file-transport.test.ts +237 -0
  110. package/src/runtime-label.test.ts +22 -0
  111. package/src/runtime-label.ts +21 -0
  112. package/src/scheduled-doorbell-nodeless-session.test.ts +130 -0
  113. package/src/scheduled-run-terminal.test.ts +268 -0
  114. package/src/scheduled-skip-blocking-task.test.ts +120 -0
  115. package/src/scheduled-tasks-http.test.ts +574 -0
  116. package/src/scheduled-tasks.ts +596 -0
  117. package/src/send-dedup-request-id.test.ts +229 -0
  118. package/src/send-reply-agent-warning.test.ts +202 -0
  119. package/src/send-reply-alias-optional.test.ts +131 -0
  120. package/src/send-reply-attachments.test.ts +458 -0
  121. package/src/send_dedup.test.ts +54 -0
  122. package/src/send_dedup.ts +52 -6
  123. package/src/serve-error.test.ts +38 -0
  124. package/src/serve-error.ts +27 -0
  125. package/src/server.ts +4279 -0
  126. package/src/shared/external-schedule-contract.ts +60 -0
  127. package/src/side-thread-command-transport.test.ts +302 -0
  128. package/src/side-thread-command-transport.ts +318 -0
  129. package/src/side-thread-http-integration.test.ts +233 -0
  130. package/src/side-thread-http.ts +504 -0
  131. package/src/side-thread-production.test.ts +72 -0
  132. package/src/side-thread-production.ts +118 -0
  133. package/src/side-thread.test.ts +1067 -0
  134. package/src/side-thread.ts +2495 -0
  135. package/src/skillhub-http.test.ts +92 -0
  136. package/src/start-node.test.ts +109 -0
  137. package/src/stop-delete-node.test.ts +1164 -0
  138. package/src/task-auth-origin-http.test.ts +91 -0
  139. package/src/task-auth-origin.test.ts +24 -0
  140. package/src/task-auth-origin.ts +7 -0
  141. package/src/task-consumption.test.ts +482 -0
  142. package/src/task-diagnostic-http.test.ts +149 -0
  143. package/src/task-diagnostic.test.ts +115 -0
  144. package/src/task-diagnostic.ts +118 -0
  145. package/src/task-idempotency-mcp.test.ts +142 -0
  146. package/src/task-idempotency.test.ts +60 -0
  147. package/src/task-idempotency.ts +75 -0
  148. package/src/task-lifecycle-watcher.test.ts +204 -0
  149. package/src/task-lifecycle-watcher.ts +49 -0
  150. package/src/task-network-resolution-http.test.ts +141 -0
  151. package/src/tasks-pagination-http.test.ts +141 -0
  152. package/src/tools-list-json-schema.test.ts +66 -0
  153. package/src/tools.ts +3445 -257
  154. package/src/update-provider.test.ts +65 -0
  155. package/src/upload-early-reject-guard.test.ts +155 -0
  156. package/src/uploads-http.test.ts +97 -15
  157. package/src/uploads.test.ts +66 -0
  158. package/src/uploads.ts +130 -5
  159. package/src/user-inbox-by-agent-http.test.ts +161 -0
  160. package/src/user-inbox-netid-notnull.test.ts +122 -0
  161. package/src/user-inbox-read-http.test.ts +223 -0
  162. package/src/user-inbox-schema.test.ts +54 -0
package/src/db.ts CHANGED
@@ -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'))
@@ -301,6 +359,16 @@ try {
301
359
  if (!/duplicate column|already exists/i.test(e?.message || "")) throw e;
302
360
  }
303
361
 
362
+ // RFC-036 / B4 — immutable per-node owner. New nodes receive this value in
363
+ // the same transaction that mints their node token. Heartbeats may verify the
364
+ // binding but must never first-claim or replace it. Legacy NULL rows remain
365
+ // read-only for external-schedule writes.
366
+ try {
367
+ db.exec(`ALTER TABLE nodes ADD COLUMN owner_user_id TEXT`);
368
+ } catch (e: any) {
369
+ if (!/duplicate column|already exists/i.test(e?.message || "")) throw e;
370
+ }
371
+
304
372
  // RFC-026 §9 / #338 PR2 — daemon self-declare fields promoted from
305
373
  // config_snapshot to first-class indexable columns. The hub
306
374
  // `list_host_supervisors` MCP tool reads these directly without parsing
@@ -324,6 +392,126 @@ try {
324
392
  if (!/duplicate column|already exists/i.test(e?.message || "")) throw e;
325
393
  }
326
394
 
395
+ // RFC-027 §2.3 — state machine for stop/delete (D5). 'active' default
396
+ // matches pre-RFC behavior for every existing row. Transitions:
397
+ // active → stopping → stopped → (back to active via restart_node)
398
+ // active → deleting → (row gone)
399
+ // stopped → deleting → (row gone)
400
+ // Used as the inbox-enqueue gate per §2.3 race-free invariant:
401
+ // pushEvent / INSERT INTO inbox must refuse a non-active target so the
402
+ // SIGTERM-in-flight window never gets a new task.
403
+ try {
404
+ db.exec(`ALTER TABLE nodes ADD COLUMN lifecycle_state TEXT DEFAULT 'active'`);
405
+ } catch (e: any) {
406
+ if (!/duplicate column|already exists/i.test(e?.message || "")) throw e;
407
+ }
408
+
409
+ // #462 — user-set custom avatar (nullable http/https image URL). Pure
410
+ // display attribute: deliberately NOT part of the RFC-024 config-apply
411
+ // pipeline (nothing for agent-node to consume, no revision/ack). Written
412
+ // only via PUT /api/nodes/:ref/avatar which validates the URL shape.
413
+ try {
414
+ db.exec(`ALTER TABLE nodes ADD COLUMN avatar_url TEXT`);
415
+ } catch (e: any) {
416
+ if (!/duplicate column|already exists/i.test(e?.message || "")) throw e;
417
+ }
418
+
419
+ // Node DISPLAY attributes (Vincent 目标第 3 条 — dashboard/app 多维度编辑).
420
+ // Same posture as avatar_url above: hub-side presentation only, NOT part of
421
+ // the RFC-024 config-apply pipeline (agent-node consumes none of them, so a
422
+ // doorbell/ack round-trip would be meaningless and could wedge the config
423
+ // revision). Written only via PUT /api/nodes/:ref/attrs.
424
+ //
425
+ // display_name — human label shown in the UI. Distinct from `alias`,
426
+ // which is the ROUTING key (messages address the alias)
427
+ // and from `node_name`, which is an addressing key
428
+ // (`WHERE node_id OR node_name OR alias`). Renaming
429
+ // either of those must go through the rename 2PC
430
+ // (/api/node-rename/*), never through an attrs write.
431
+ // team, tags — organisation metadata; tags stored as JSON array text.
432
+ // attrs_revision — optimistic-lock counter for these display fields ONLY.
433
+ // Deliberately separate from config_revision so that
434
+ // editing a tag never bumps the node's *config* revision
435
+ // (which would perturb the config ack protocol).
436
+ //
437
+ // All nullable / defaulted so the ~100 rows already in flight keep reading.
438
+ for (const ddl of [
439
+ `ALTER TABLE nodes ADD COLUMN display_name TEXT`,
440
+ `ALTER TABLE nodes ADD COLUMN team TEXT`,
441
+ `ALTER TABLE nodes ADD COLUMN tags TEXT`,
442
+ `ALTER TABLE nodes ADD COLUMN attrs_revision INTEGER NOT NULL DEFAULT 0`,
443
+ ]) {
444
+ try {
445
+ db.exec(ddl);
446
+ } catch (e: any) {
447
+ if (!/duplicate column|already exists/i.test(e?.message || "")) throw e;
448
+ }
449
+ }
450
+
451
+ // RFC-027 §2 — stop/delete request envelope. Mirrors
452
+ // node_create_requests structure so the daemon-side pull/ack pattern
453
+ // is symmetric with create_node. action='stop'|'delete' picks which
454
+ // branch (delete adds backup_path + revokes ntok on ack).
455
+ db.exec(`
456
+ CREATE TABLE IF NOT EXISTS node_stop_requests (
457
+ request_id TEXT PRIMARY KEY,
458
+ network_id TEXT NOT NULL,
459
+ daemon_node_id TEXT NOT NULL,
460
+ child_node_id TEXT NOT NULL,
461
+ child_alias TEXT NOT NULL,
462
+ child_token_id TEXT,
463
+ action TEXT NOT NULL CHECK (action IN ('stop', 'delete')),
464
+ delete_config INTEGER NOT NULL DEFAULT 1,
465
+ grace_seconds INTEGER NOT NULL DEFAULT 10,
466
+ force INTEGER NOT NULL DEFAULT 0,
467
+ in_flight_at_dispatch INTEGER NOT NULL DEFAULT 0,
468
+ created_by_token TEXT NOT NULL,
469
+ status TEXT NOT NULL DEFAULT 'pending',
470
+ error TEXT,
471
+ backup_path TEXT,
472
+ exit_signal TEXT,
473
+ created_at INTEGER NOT NULL,
474
+ delivered_at INTEGER,
475
+ acked_at INTEGER
476
+ )
477
+ `);
478
+ db.exec(`CREATE INDEX IF NOT EXISTS idx_stop_req_daemon ON node_stop_requests(daemon_node_id, status)`);
479
+ db.exec(`CREATE INDEX IF NOT EXISTS idx_stop_req_child ON node_stop_requests(child_node_id)`);
480
+ // #1448 finding-5 — 存 delete 目标 child 的 token_id,让 ack 精确按 token_id 撤 ntok
481
+ // (而非按 name='node:<alias>' 广撤 → 同 alias 在 delete 窗口内重建会误杀新 token)。
482
+ // 幂等迁移:已有库补列,旧行 child_token_id 为 NULL、ack 时 fallback 回按 name 撤。
483
+ try { db.exec(`ALTER TABLE node_stop_requests ADD COLUMN child_token_id TEXT`); } catch { /* 已存在 */ }
484
+
485
+ // Daemon-mediated start request. Kept separate from node_stop_requests:
486
+ // the deployed stop table has a CHECK(action IN ('stop','delete')) and
487
+ // rebuilding that table in-place would be a risky migration for an additive
488
+ // lifecycle operation.
489
+ db.exec(`
490
+ CREATE TABLE IF NOT EXISTS node_start_requests (
491
+ request_id TEXT PRIMARY KEY,
492
+ network_id TEXT NOT NULL,
493
+ daemon_node_id TEXT NOT NULL,
494
+ child_node_id TEXT NOT NULL,
495
+ child_alias TEXT NOT NULL,
496
+ created_by_token TEXT NOT NULL,
497
+ status TEXT NOT NULL DEFAULT 'pending',
498
+ error TEXT,
499
+ child_pid INTEGER,
500
+ created_at INTEGER NOT NULL,
501
+ delivered_at INTEGER,
502
+ acked_at INTEGER
503
+ )
504
+ `);
505
+ db.exec(`CREATE INDEX IF NOT EXISTS idx_start_req_daemon ON node_start_requests(daemon_node_id, status)`);
506
+ db.exec(`CREATE INDEX IF NOT EXISTS idx_start_req_child ON node_start_requests(child_node_id)`);
507
+ try {
508
+ db.exec(`CREATE UNIQUE INDEX IF NOT EXISTS uniq_start_req_child_inflight
509
+ ON node_start_requests(child_node_id)
510
+ WHERE status IN ('pending', 'delivered')`);
511
+ } catch (e: any) {
512
+ if (!/unique constraint/i.test(e?.message || "")) throw e;
513
+ }
514
+
327
515
  // `node_config_updates` — pending + history. One row per dashboard write.
328
516
  // At most one row per node may be in a non-terminal state at a time
329
517
  // (single-flight enforced at the tool layer; this table just stores).
@@ -365,6 +553,47 @@ try {
365
553
  console.warn(`[commhub] partial unique index uniq_ncu_node_inflight skipped: ${e?.message || e}`);
366
554
  }
367
555
 
556
+ // ── app#225: 节点规则文件(AGENTS.md / CLAUDE.md)远程读写请求 ──
557
+ //
558
+ // 形状照抄 node_config_updates(上面):客户端落一行 + 门铃,节点拉走做完回报,
559
+ // 客户端轮询结果。network_id 同样在插入时从 nodes 反规范化。
560
+ //
561
+ // 🔴 这张表**故意没有路径列**:文件名由节点按自己的 RUNTIME 决定
562
+ // (claude → CLAUDE.md,其余 → AGENTS.md),目录固定是节点进程的 cwd。
563
+ // hub 侧只存 op + 内容,客户端连文件名都指定不了(#225 验收第 5 条)。
564
+ // file_name 是节点**回报**的实际文件名,只用于显示。
565
+ db.exec(`
566
+ CREATE TABLE IF NOT EXISTS node_rules_requests (
567
+ request_id TEXT PRIMARY KEY,
568
+ node_id TEXT NOT NULL,
569
+ network_id TEXT NOT NULL,
570
+ op TEXT NOT NULL,
571
+ content TEXT,
572
+ status TEXT NOT NULL,
573
+ file_name TEXT,
574
+ file_exists INTEGER,
575
+ result_content TEXT,
576
+ error TEXT,
577
+ created_at INTEGER NOT NULL,
578
+ created_by_token TEXT NOT NULL,
579
+ pulled_at INTEGER,
580
+ acked_at INTEGER
581
+ );
582
+
583
+ CREATE INDEX IF NOT EXISTS idx_nrr_node_status ON node_rules_requests(node_id, status);
584
+ CREATE INDEX IF NOT EXISTS idx_nrr_network ON node_rules_requests(network_id);
585
+ `);
586
+ // Content retention (node-request-retention.ts): file bytes in content /
587
+ // result_content are purged after the first terminal read (+grace) or a TTL;
588
+ // these two columns record when, so the row itself survives as audit metadata.
589
+ for (const col of ["first_read_at INTEGER", "content_purged_at INTEGER"]) {
590
+ try { db.exec(`ALTER TABLE node_rules_requests ADD COLUMN ${col}`); } catch {}
591
+ }
592
+ db.exec(`
593
+ CREATE INDEX IF NOT EXISTS idx_nrr_created ON node_rules_requests(created_at);
594
+ CREATE INDEX IF NOT EXISTS idx_nrr_first_read ON node_rules_requests(first_read_at);
595
+ `);
596
+
368
597
  // ── V3: networks table ──
369
598
  db.exec(`
370
599
  CREATE TABLE IF NOT EXISTS networks (
@@ -410,6 +639,10 @@ for (const ddl of [
410
639
  "ALTER TABLE api_tokens ADD COLUMN request_id TEXT",
411
640
  "ALTER TABLE api_tokens ADD COLUMN revoked_at TEXT",
412
641
  "ALTER TABLE api_tokens ADD COLUMN role TEXT",
642
+ "ALTER TABLE api_tokens ADD COLUMN bound_node_id TEXT",
643
+ // 登录会话的设备标识(GET /api/auth/sessions 显示用):客户端自报的 client_label + 登录请求的 User-Agent。
644
+ "ALTER TABLE api_tokens ADD COLUMN client_label TEXT",
645
+ "ALTER TABLE api_tokens ADD COLUMN user_agent TEXT",
413
646
  ]) {
414
647
  try { db.exec(ddl); }
415
648
  catch (e: any) {
@@ -418,6 +651,8 @@ for (const ddl of [
418
651
  }
419
652
  try { db.exec(`CREATE INDEX IF NOT EXISTS idx_tokens_request ON api_tokens(request_id)`); }
420
653
  catch (e: any) { /* index may already exist */ void e; }
654
+ try { db.exec(`CREATE INDEX IF NOT EXISTS idx_tokens_bound_node ON api_tokens(bound_node_id)`); }
655
+ catch (e: any) { void e; }
421
656
 
422
657
  // RFC-026 v4 §2.5 + §4.4 — node_create_requests. Metadata only;
423
658
  // env_blob NEVER lives in this table (F1 mint-stream-evict — secret
@@ -434,7 +669,7 @@ db.exec(`
434
669
  child_name TEXT NOT NULL,
435
670
  network_id TEXT NOT NULL,
436
671
  runtime TEXT NOT NULL,
437
- model TEXT NOT NULL,
672
+ model TEXT,
438
673
  flags_json TEXT NOT NULL,
439
674
  env_keys TEXT NOT NULL,
440
675
  status TEXT NOT NULL,
@@ -451,6 +686,151 @@ db.exec(`
451
686
  CREATE INDEX IF NOT EXISTS idx_ncr_network ON node_create_requests(network_id);
452
687
  CREATE INDEX IF NOT EXISTS idx_ncr_child_name ON node_create_requests(child_name);
453
688
  `);
689
+ function migrateNodeCreateRequestsModelNullable() {
690
+ if (db.dialect === "postgres") {
691
+ try { db.exec("ALTER TABLE node_create_requests ALTER COLUMN model DROP NOT NULL"); } catch {}
692
+ return;
693
+ }
694
+
695
+ let needsRebuild = false;
696
+ try {
697
+ const createSql = db.get<{ sql: string }>("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'node_create_requests'");
698
+ needsRebuild = !!createSql?.sql && /\bmodel\s+TEXT\s+NOT\s+NULL\b/i.test(createSql.sql);
699
+ } catch {}
700
+ if (!needsRebuild) return;
701
+
702
+ db.transaction(() => {
703
+ db.exec("DROP TABLE IF EXISTS node_create_requests_migrated");
704
+ db.exec(`
705
+ CREATE TABLE node_create_requests_migrated (
706
+ request_id TEXT PRIMARY KEY,
707
+ daemon_node_id TEXT NOT NULL,
708
+ child_name TEXT NOT NULL,
709
+ network_id TEXT NOT NULL,
710
+ runtime TEXT NOT NULL,
711
+ model TEXT,
712
+ flags_json TEXT NOT NULL,
713
+ env_keys TEXT NOT NULL,
714
+ status TEXT NOT NULL,
715
+ error TEXT,
716
+ child_token_id TEXT,
717
+ created_at INTEGER NOT NULL,
718
+ created_by_token TEXT NOT NULL,
719
+ delivered_at INTEGER,
720
+ acked_at INTEGER,
721
+ child_node_id TEXT
722
+ )
723
+ `);
724
+ db.exec(`
725
+ INSERT INTO node_create_requests_migrated (
726
+ request_id, daemon_node_id, child_name, network_id, runtime, model,
727
+ flags_json, env_keys, status, error, child_token_id, created_at,
728
+ created_by_token, delivered_at, acked_at, child_node_id
729
+ )
730
+ SELECT
731
+ request_id, daemon_node_id, child_name, network_id, runtime, model,
732
+ flags_json, env_keys, status, error, child_token_id, created_at,
733
+ created_by_token, delivered_at, acked_at, child_node_id
734
+ FROM node_create_requests
735
+ `);
736
+ db.exec("DROP TABLE node_create_requests");
737
+ db.exec("ALTER TABLE node_create_requests_migrated RENAME TO node_create_requests");
738
+ });
739
+ }
740
+ migrateNodeCreateRequestsModelNullable();
741
+
742
+ // app「新建节点」工作目录 —— 请求带的 node_spec.workdir(可空;空 = 落 daemon cwd 的老行为)。
743
+ // 🔴 必须排在上面那个重建表迁移**之后**:它按显式列清单拷贝,排在前面的话,老库(model NOT NULL)
744
+ // 第一次启动时这一列会被重建吞掉。
745
+ try {
746
+ db.exec(`ALTER TABLE node_create_requests ADD COLUMN workdir TEXT`);
747
+ } catch (e: any) {
748
+ if (!/duplicate column|already exists/i.test(e?.message || "")) throw e;
749
+ }
750
+
751
+ // #1493 — 把 user_inbox.network_id 升到 **schema 级 NOT NULL**(belt-and-suspenders,
752
+ // 叠在 send_desktop_message 的代码级三闸之上:canWrite / `!effectiveNetId` return /
753
+ // getUserNetworkRole,tools.ts)。「不产生 network_id=NULL 孤儿」现是代码级保证 + #1492
754
+ // 三道测试;schema 级约束让**任何**未来绕过那三闸写 NULL 的回归在 INSERT 处直接被
755
+ // 数据库拒(而非产出 scoped-unreadable 的静默孤儿)。
756
+ //
757
+ // SQLite 不能 `ALTER COLUMN ADD NOT NULL` → 建新表→copy→drop→rename(与本文件既有
758
+ // recreate-table 迁移同范式);新库的 CREATE 已直接 NOT NULL,迁移检测到就跳过(幂等)。
759
+ function migrateUserInboxNetworkIdNotNull() {
760
+ if (db.dialect === "postgres") {
761
+ try { db.exec("ALTER TABLE user_inbox ALTER COLUMN network_id SET NOT NULL"); } catch {}
762
+ return;
763
+ }
764
+ let createSql: string | undefined;
765
+ try {
766
+ createSql = db.get<{ sql: string }>("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'user_inbox'")?.sql;
767
+ } catch { return; }
768
+ if (!createSql) return; // 表不存在:上面的 CREATE 已建成 NOT NULL 新表
769
+ if (/network_id\s+TEXT\s+NOT\s+NULL/i.test(createSql)) return; // 已是 NOT NULL → 幂等跳过
770
+
771
+ // 🔴 迁移前守卫:存量若有 network_id IS NULL 行(按代码级三闸理应 0)→ **大声 warn +
772
+ // 跳过迁移**(列暂保持可空),hub 照常启动。fail-safe,不 throw(SDK马 review #1516):
773
+ // · 这条 NOT NULL 是 belt-and-suspenders,代码级三闸(#1492 三测钉着)已挡新 NULL;
774
+ // 为一条冗余保险带让**整个舰队的 hub** boot 期停摆,代价与收益不成比例;
775
+ // · 生产这个 COUNT 没人量过,而 #1493 第一条原则就是"没量过的数不要动手"——只要生产
776
+ // 有一行历史 NULL,throw 就把升级变成停机;
777
+ // · fail-closed 的真正目的(不盲目清空、不 COALESCE 猜网络)用 warn+skip 一样达到。
778
+ // ⚠ 校正:本文件既有迁移(migrateNodeCreateRequestsModelNullable 内部 catch{}+return;
779
+ // migrateSessionsNetworkAliasUnique 全函数 throw 0 次)都**不**在 boot 期打死 hub——
780
+ // "顶层无 try/catch"是真前提,但"所以 throw 符合惯例"是没验的推论(SDK马 量出),撤回。
781
+ // 孤儿行仍有明确运维信号,三闸仍生效;等人工量过、清干净,下次启动幂等判据自动完成迁移。
782
+ const nullCount = db.get<{ n: number }>("SELECT COUNT(*) AS n FROM user_inbox WHERE network_id IS NULL")?.n ?? 0;
783
+ if (nullCount > 0) {
784
+ console.error(
785
+ `[migrate #1493] user_inbox 有 ${nullCount} 行 network_id IS NULL —— 与 send_desktop_message ` +
786
+ `的代码级三闸矛盾,可能存在更早的写路径漏洞;已**跳过** NOT NULL 迁移(列暂保持可空),` +
787
+ `hub 正常启动。请人工排查这些孤儿行来源、清理后下次启动会自动完成迁移(不要盲目清空)。`,
788
+ );
789
+ return;
790
+ }
791
+
792
+ db.transaction(() => {
793
+ db.exec("DROP TABLE IF EXISTS user_inbox_migrated");
794
+ db.exec(`
795
+ CREATE TABLE user_inbox_migrated (
796
+ message_id TEXT PRIMARY KEY,
797
+ network_id TEXT NOT NULL,
798
+ user_id TEXT NOT NULL,
799
+ from_session TEXT,
800
+ kind TEXT NOT NULL DEFAULT 'info',
801
+ title TEXT,
802
+ content TEXT NOT NULL,
803
+ severity TEXT NOT NULL DEFAULT 'info',
804
+ meta_json TEXT,
805
+ acked INTEGER NOT NULL DEFAULT 0,
806
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
807
+ acked_at TEXT
808
+ )
809
+ `);
810
+ db.exec(`
811
+ INSERT INTO user_inbox_migrated
812
+ (message_id, network_id, user_id, from_session, kind, title, content, severity, meta_json, acked, created_at, acked_at)
813
+ SELECT
814
+ message_id, network_id, user_id, from_session, kind, title, content, severity, meta_json, acked, created_at, acked_at
815
+ FROM user_inbox
816
+ `);
817
+ db.exec("DROP TABLE user_inbox");
818
+ db.exec("ALTER TABLE user_inbox_migrated RENAME TO user_inbox");
819
+ });
820
+ }
821
+ migrateUserInboxNetworkIdNotNull();
822
+ // 迁移会 drop 掉旧表上的 idx_user_inbox_user_acked → 重建(IF NOT EXISTS;未迁移时 no-op)。
823
+ db.exec(`CREATE INDEX IF NOT EXISTS idx_user_inbox_user_acked ON user_inbox(user_id, acked, created_at);`);
824
+ // 多用户:人与人私信。sender_user_id 由 Hub 按发信人的**用户令牌**写入(不是客户端填的 from_session),
825
+ // 会话记录按它双向取;Agent / 节点令牌发来的桌面消息这一列为 NULL。
826
+ try { db.exec("ALTER TABLE user_inbox ADD COLUMN sender_user_id TEXT"); } catch {}
827
+ db.exec(`CREATE INDEX IF NOT EXISTS idx_user_inbox_dm ON user_inbox(network_id, user_id, sender_user_id, created_at);`);
828
+
829
+ db.exec(`
830
+ CREATE INDEX IF NOT EXISTS idx_ncr_daemon_status ON node_create_requests(daemon_node_id, status);
831
+ CREATE INDEX IF NOT EXISTS idx_ncr_network ON node_create_requests(network_id);
832
+ CREATE INDEX IF NOT EXISTS idx_ncr_child_name ON node_create_requests(child_name);
833
+ `);
454
834
  try {
455
835
  // Single-flight per (daemon, child_name) — prevents racing dashboard
456
836
  // create on same name. Mirrors RFC-024 uniq_ncu_node_inflight.
@@ -549,6 +929,64 @@ db.exec(`
549
929
  CREATE INDEX IF NOT EXISTS idx_audit_network ON audit_log(network_id);
550
930
  `);
551
931
 
932
+ // SkillHub — immutable, network-scoped skill submissions. A (network, slug,
933
+ // version) tuple is write-once: retries with the same content are idempotent,
934
+ // while different content must use a new version. Node submissions remain
935
+ // pending until an owner/admin explicitly publishes them.
936
+ db.exec(`
937
+ CREATE TABLE IF NOT EXISTS skillhub_skills (
938
+ skill_id TEXT PRIMARY KEY,
939
+ network_id TEXT NOT NULL,
940
+ slug TEXT NOT NULL,
941
+ name TEXT NOT NULL,
942
+ description TEXT NOT NULL DEFAULT '',
943
+ version TEXT NOT NULL,
944
+ content TEXT NOT NULL,
945
+ content_hash TEXT NOT NULL,
946
+ status TEXT NOT NULL DEFAULT 'pending' CHECK(status IN ('pending', 'published', 'rejected', 'archived')),
947
+ source_type TEXT NOT NULL CHECK(source_type IN ('node', 'user')),
948
+ source_alias TEXT,
949
+ created_by_user TEXT,
950
+ reviewed_by_user TEXT,
951
+ review_note TEXT,
952
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
953
+ updated_at TEXT NOT NULL DEFAULT (datetime('now')),
954
+ reviewed_at TEXT,
955
+ UNIQUE(network_id, slug, version)
956
+ );
957
+ CREATE INDEX IF NOT EXISTS idx_skillhub_network_status
958
+ ON skillhub_skills(network_id, status, updated_at DESC);
959
+ CREATE INDEX IF NOT EXISTS idx_skillhub_network_slug
960
+ ON skillhub_skills(network_id, slug, version);
961
+ `);
962
+
963
+ // 需求池。长期卡片,按 network 隔离。不是 tasks。
964
+ db.exec(`
965
+ CREATE TABLE IF NOT EXISTS requirements (
966
+ requirement_id TEXT PRIMARY KEY,
967
+ network_id TEXT NOT NULL,
968
+ title TEXT NOT NULL,
969
+ column_name TEXT NOT NULL DEFAULT 'pool' CHECK(column_name IN ('pool', 'doing', 'done')),
970
+ priority TEXT NOT NULL DEFAULT 'normal' CHECK(priority IN ('high', 'normal', 'low', 'lowest')),
971
+ due_on TEXT,
972
+ assignee TEXT,
973
+ client_id TEXT,
974
+ issues_json TEXT,
975
+ created_by TEXT,
976
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
977
+ updated_at TEXT NOT NULL DEFAULT (datetime('now'))
978
+ );
979
+ CREATE INDEX IF NOT EXISTS idx_requirements_network
980
+ ON requirements(network_id, created_at DESC);
981
+ `);
982
+ try { db.exec("ALTER TABLE requirements ADD COLUMN client_id TEXT"); } catch {}
983
+ try { db.exec("ALTER TABLE requirements ADD COLUMN issues_json TEXT"); } catch {}
984
+ 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; }
985
+ 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 != ''");
986
+ 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"]) {
987
+ try { db.exec(`ALTER TABLE requirements ADD COLUMN ${column}`); } catch (e: any) { if (!/duplicate column|already exists/i.test(e?.message || "")) throw e; }
988
+ }
989
+
552
990
  // ── V3: licenses table ──
553
991
  db.exec(`
554
992
  CREATE TABLE IF NOT EXISTS licenses (
@@ -605,6 +1043,31 @@ db.exec(`
605
1043
  );
606
1044
  `);
607
1045
 
1046
+ // ── 多用户账号与 Agent 权限:成员可见哪些 Agent ──
1047
+ // network_members.agent_access:
1048
+ // 'all' —— 旧语义:能看到并联系网络里所有 Agent。ALTER 的 DEFAULT 让**升级前已有的**成员行
1049
+ // 全部落在这里,生产上已有成员的可见范围不因升级而变。
1050
+ // 'granted' —— 只看到 network_member_agent_grants 里给了的 Agent。此后**新加入**的
1051
+ // member/viewer(管理员建号、POST members、邀请码)都以它入库,即默认零权限。
1052
+ // owner/admin 角色与 Hub 管理员不看这一列(永远全部可见),判定集中在 agent-access.ts。
1053
+ try { db.exec("ALTER TABLE network_members ADD COLUMN agent_access TEXT NOT NULL DEFAULT 'all'"); } catch {}
1054
+ // node_id 优先(稳定);alias 只给没有 node_id 的旧会话用。两者恰有其一。
1055
+ db.exec(`
1056
+ CREATE TABLE IF NOT EXISTS network_member_agent_grants (
1057
+ network_id TEXT NOT NULL,
1058
+ user_id TEXT NOT NULL,
1059
+ node_id TEXT,
1060
+ alias TEXT,
1061
+ can_message INTEGER NOT NULL DEFAULT 1,
1062
+ created_by TEXT,
1063
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
1064
+ CHECK ((node_id IS NULL) <> (alias IS NULL))
1065
+ );
1066
+
1067
+ 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;
1068
+ 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;
1069
+ `);
1070
+
608
1071
  // ── #84: node rename — rename_txn table (RFC-010 §4) ──
609
1072
  // Single isolated table holding the rename 2PC transaction state. It doubles
610
1073
  // as the alias_rename_log (RFC §4 risk #5): the audit log of completed renames
@@ -659,6 +1122,14 @@ for (const table of ["sessions", "nodes", "tasks", "inbox", "task_events", "comp
659
1122
  try { db.exec(`ALTER TABLE ${table} ADD COLUMN network_id TEXT`); } catch {}
660
1123
  }
661
1124
 
1125
+ // #167 — stable lifecycle event names plus an internal idempotency key.
1126
+ // Ordinary status transitions keep event_key NULL, so retries and repeated
1127
+ // transitions remain auditable. Watcher warnings set a stable key; the unique
1128
+ // index makes every (task, threshold) write-once across patrol rounds/workers.
1129
+ try { db.exec("ALTER TABLE task_events ADD COLUMN event_type TEXT"); } catch {}
1130
+ try { db.exec("ALTER TABLE task_events ADD COLUMN event_key TEXT"); } catch {}
1131
+ try { db.exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_task_events_task_key ON task_events(task_id, event_key)"); } catch {}
1132
+
662
1133
  // PR-1 (#146): durable node identity on historical inbox/tasks rows. Some
663
1134
  // existing databases created `tasks` before from_node_id/to_node_id were in the
664
1135
  // CREATE TABLE statement, so keep these ALTERs explicit and idempotent.
@@ -945,6 +1416,176 @@ try { db.exec("CREATE INDEX IF NOT EXISTS idx_completions_network ON completions
945
1416
  // the reply up the chain via parent_task_id.
946
1417
  try { db.exec("ALTER TABLE tasks ADD COLUMN parent_task_id TEXT"); } catch {}
947
1418
  try { db.exec("ALTER TABLE tasks ADD COLUMN meta_json TEXT"); } catch {}
1419
+ // #520 — two monotonic evidence levels for this exact task:
1420
+ // runtime_submitted_at means agent-node handed the body to the vendor runtime;
1421
+ // consumed_at requires an attributable turn-start/first-activity signal.
1422
+ // Both stay separate from delivered_at (enqueue), acked (process receipt), and
1423
+ // started_at (legacy report_status/content matching). Old binaries ignore them.
1424
+ try { db.exec("ALTER TABLE tasks ADD COLUMN runtime_submitted_at TEXT"); } catch {}
1425
+ try { db.exec("ALTER TABLE tasks ADD COLUMN consumed_at TEXT"); } catch {}
1426
+ // Exact vendor-runtime boundary for SideThread-capable clients. These values
1427
+ // are written only by the token-bound target node after attributable runtime
1428
+ // evidence; the Hub never derives them from task text or caller input.
1429
+ try { db.exec("ALTER TABLE tasks ADD COLUMN thread_id TEXT"); } catch {}
1430
+ try { db.exec("ALTER TABLE tasks ADD COLUMN turn_id TEXT"); } catch {}
1431
+
1432
+ // #1181 durable outbound terminal cursor. A task's created_at cannot be used
1433
+ // as a recovery watermark because an old task may become terminal after newer
1434
+ // tasks. Record terminal transitions in their own monotonically increasing
1435
+ // journal instead. The journal is append-only for a logical task; retry keeps
1436
+ // the existing task identity and therefore the same idempotency domain.
1437
+ db.exec(`
1438
+ CREATE TABLE IF NOT EXISTS task_terminal_events (
1439
+ terminal_seq INTEGER PRIMARY KEY AUTOINCREMENT,
1440
+ task_id TEXT NOT NULL UNIQUE,
1441
+ network_id TEXT,
1442
+ from_node_id TEXT,
1443
+ completed_at TEXT NOT NULL DEFAULT (datetime('now'))
1444
+ );
1445
+ CREATE INDEX IF NOT EXISTS idx_task_terminal_events_sender_seq
1446
+ ON task_terminal_events(network_id, from_node_id, terminal_seq);
1447
+ `);
1448
+ if (db.dialect === "sqlite") {
1449
+ db.exec(`
1450
+ CREATE TRIGGER IF NOT EXISTS tasks_terminal_event_insert
1451
+ AFTER INSERT ON tasks
1452
+ WHEN NEW.status IN ('replied', 'failed', 'cancelled', 'expired')
1453
+ BEGIN
1454
+ INSERT OR IGNORE INTO task_terminal_events (task_id, network_id, from_node_id, completed_at)
1455
+ VALUES (NEW.task_id, NEW.network_id, NEW.from_node_id, COALESCE(NEW.completed_at, datetime('now')));
1456
+ END;
1457
+ CREATE TRIGGER IF NOT EXISTS tasks_terminal_event_update
1458
+ AFTER UPDATE OF status ON tasks
1459
+ WHEN NEW.status IN ('replied', 'failed', 'cancelled', 'expired')
1460
+ AND OLD.status NOT IN ('replied', 'failed', 'cancelled', 'expired')
1461
+ BEGIN
1462
+ INSERT OR IGNORE INTO task_terminal_events (task_id, network_id, from_node_id, completed_at)
1463
+ VALUES (NEW.task_id, NEW.network_id, NEW.from_node_id, COALESCE(NEW.completed_at, datetime('now')));
1464
+ END;
1465
+ `);
1466
+ db.run(`INSERT OR IGNORE INTO task_terminal_events (task_id, network_id, from_node_id, completed_at)
1467
+ SELECT task_id, network_id, from_node_id, COALESCE(completed_at, created_at)
1468
+ FROM tasks
1469
+ WHERE status IN ('replied', 'failed', 'cancelled', 'expired')
1470
+ ORDER BY COALESCE(completed_at, created_at), task_id`);
1471
+ } else {
1472
+ db.exec(`
1473
+ CREATE OR REPLACE FUNCTION record_task_terminal_event() RETURNS trigger AS $$
1474
+ BEGIN
1475
+ IF NEW.status IN ('replied', 'failed', 'cancelled', 'expired')
1476
+ AND (TG_OP = 'INSERT' OR OLD.status NOT IN ('replied', 'failed', 'cancelled', 'expired')) THEN
1477
+ INSERT INTO task_terminal_events (task_id, network_id, from_node_id, completed_at)
1478
+ VALUES (NEW.task_id, NEW.network_id, NEW.from_node_id, COALESCE(NEW.completed_at, NOW()))
1479
+ ON CONFLICT (task_id) DO NOTHING;
1480
+ END IF;
1481
+ RETURN NEW;
1482
+ END;
1483
+ $$ LANGUAGE plpgsql;
1484
+ DROP TRIGGER IF EXISTS tasks_terminal_event_insert ON tasks;
1485
+ DROP TRIGGER IF EXISTS tasks_terminal_event_update ON tasks;
1486
+ CREATE TRIGGER tasks_terminal_event_insert AFTER INSERT ON tasks
1487
+ FOR EACH ROW EXECUTE FUNCTION record_task_terminal_event();
1488
+ CREATE TRIGGER tasks_terminal_event_update AFTER UPDATE OF status ON tasks
1489
+ FOR EACH ROW EXECUTE FUNCTION record_task_terminal_event();
1490
+ INSERT INTO task_terminal_events (task_id, network_id, from_node_id, completed_at)
1491
+ SELECT task_id, network_id, from_node_id, COALESCE(completed_at, created_at)
1492
+ FROM tasks WHERE status IN ('replied', 'failed', 'cancelled', 'expired')
1493
+ ON CONFLICT (task_id) DO NOTHING;
1494
+ `);
1495
+ }
1496
+
1497
+ // ── Hub scheduled tasks ──────────────────────────────────────────────
1498
+ // Scheduling is a Hub concern: clients manage these rows, while agents only
1499
+ // receive the ordinary inbox/tasks rows produced for each occurrence. Keep
1500
+ // the occurrence table separate so retries, skips and failures remain
1501
+ // auditable without overloading the task lifecycle.
1502
+ db.exec(`
1503
+ CREATE TABLE IF NOT EXISTS scheduled_tasks (
1504
+ schedule_id TEXT PRIMARY KEY,
1505
+ network_id TEXT NOT NULL,
1506
+ created_by TEXT,
1507
+ name TEXT NOT NULL,
1508
+ target_node_id TEXT NOT NULL,
1509
+ target_alias TEXT NOT NULL,
1510
+ task_content TEXT NOT NULL,
1511
+ priority TEXT NOT NULL DEFAULT 'normal',
1512
+ schedule_type TEXT NOT NULL,
1513
+ schedule_json TEXT NOT NULL,
1514
+ timezone TEXT NOT NULL DEFAULT 'UTC',
1515
+ overlap_policy TEXT NOT NULL DEFAULT 'skip',
1516
+ misfire_policy TEXT NOT NULL DEFAULT 'catch_up_once',
1517
+ status TEXT NOT NULL DEFAULT 'active',
1518
+ next_run_at TEXT,
1519
+ last_run_at TEXT,
1520
+ revision INTEGER NOT NULL DEFAULT 1,
1521
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
1522
+ updated_at TEXT NOT NULL DEFAULT (datetime('now'))
1523
+ );
1524
+
1525
+ CREATE INDEX IF NOT EXISTS idx_scheduled_tasks_due
1526
+ ON scheduled_tasks(status, next_run_at);
1527
+ CREATE INDEX IF NOT EXISTS idx_scheduled_tasks_network
1528
+ ON scheduled_tasks(network_id, updated_at DESC);
1529
+ CREATE INDEX IF NOT EXISTS idx_scheduled_tasks_target
1530
+ ON scheduled_tasks(network_id, target_node_id);
1531
+
1532
+ CREATE TABLE IF NOT EXISTS scheduled_task_runs (
1533
+ run_id TEXT PRIMARY KEY,
1534
+ schedule_id TEXT NOT NULL,
1535
+ network_id TEXT NOT NULL,
1536
+ scheduled_for TEXT NOT NULL,
1537
+ task_id TEXT,
1538
+ status TEXT NOT NULL,
1539
+ error_code TEXT,
1540
+ error_message TEXT,
1541
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
1542
+ completed_at TEXT,
1543
+ UNIQUE(schedule_id, scheduled_for)
1544
+ );
1545
+
1546
+ CREATE INDEX IF NOT EXISTS idx_scheduled_runs_schedule
1547
+ ON scheduled_task_runs(schedule_id, created_at DESC);
1548
+ CREATE INDEX IF NOT EXISTS idx_scheduled_runs_network
1549
+ ON scheduled_task_runs(network_id, created_at DESC);
1550
+ `);
1551
+ try { db.exec("ALTER TABLE scheduled_tasks ADD COLUMN misfire_policy TEXT NOT NULL DEFAULT 'catch_up_once'"); } catch {}
1552
+ // Skipped runs (overlap_policy=skip) name the open task that blocked them and
1553
+ // whether the node had ever picked it up: not_received | in_progress.
1554
+ try { db.exec("ALTER TABLE scheduled_task_runs ADD COLUMN blocked_by_task_id TEXT"); } catch {}
1555
+ try { db.exec("ALTER TABLE scheduled_task_runs ADD COLUMN blocked_by_state TEXT"); } catch {}
1556
+
1557
+ // RFC-036 / B4 — owner-authorized edits of node-host managed schedules.
1558
+ // This is intentionally separate from Hub scheduled_tasks: these rows are
1559
+ // one-shot control intents consumed by the exact token-bound node. The partial
1560
+ // unique index makes the single-flight promise survive multiple Hub workers.
1561
+ db.exec(`
1562
+ CREATE TABLE IF NOT EXISTS external_schedule_edits (
1563
+ intent_id TEXT PRIMARY KEY,
1564
+ network_id TEXT NOT NULL,
1565
+ node_id TEXT NOT NULL,
1566
+ schedule_id TEXT NOT NULL,
1567
+ base_revision INTEGER NOT NULL,
1568
+ patch_json TEXT NOT NULL,
1569
+ status TEXT NOT NULL DEFAULT 'pending',
1570
+ expires_at INTEGER NOT NULL,
1571
+ created_at INTEGER NOT NULL,
1572
+ delivered_at INTEGER,
1573
+ acked_at INTEGER,
1574
+ created_by_user TEXT NOT NULL,
1575
+ created_by_token TEXT NOT NULL,
1576
+ consumed_by_token TEXT,
1577
+ result_revision INTEGER,
1578
+ error_code TEXT
1579
+ );
1580
+
1581
+ CREATE INDEX IF NOT EXISTS idx_external_schedule_edits_node
1582
+ ON external_schedule_edits(network_id, node_id, status, created_at);
1583
+ CREATE INDEX IF NOT EXISTS idx_external_schedule_edits_owner
1584
+ ON external_schedule_edits(created_by_user, created_at DESC);
1585
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_external_schedule_edits_singleflight
1586
+ ON external_schedule_edits(node_id, schedule_id)
1587
+ WHERE status IN ('pending', 'delivered');
1588
+ `);
948
1589
  try { db.exec("CREATE INDEX IF NOT EXISTS idx_tasks_parent ON tasks(parent_task_id)"); } catch {}
949
1590
 
950
1591
  // Helpers
@@ -1253,38 +1894,40 @@ export function chainReplyToParent(
1253
1894
  const marker = `\n\n[via ${childAlias} 子任务结果]\n${currentReply}`;
1254
1895
  const newResult = parent.result ? parent.result + marker : `[via ${childAlias} 子任务结果]\n${currentReply}`;
1255
1896
 
1256
- // Bump parent status to replied if still open. If it was already replied
1257
- // (e.g. 指挥室 sent an early status update), we still want to update the
1258
- // result so the dashboard can render the final chained answer — but keep
1259
- // status as replied (it was already terminal).
1260
- if (parent.status === "delivered" || parent.status === "acked" || parent.status === "running" || parent.status === "created") {
1261
- db.run(
1262
- "UPDATE tasks SET status = ?1, result = ?2, completed_at = datetime('now') WHERE task_id = ?3",
1263
- [replyStatus, newResult.slice(0, 8000), parent.task_id]
1264
- );
1265
- logTaskEvent(parent.task_id, parent.status, replyStatus, "auto-chain", `from ${childAlias}`);
1266
- } else {
1267
- db.run(
1268
- "UPDATE tasks SET result = ?1, completed_at = datetime('now') WHERE task_id = ?2",
1269
- [newResult.slice(0, 8000), parent.task_id]
1270
- );
1271
- logTaskEvent(parent.task_id, parent.status, parent.status, "auto-chain-append", `from ${childAlias}`);
1272
- }
1273
-
1274
- if (parent.from_name && parent.from_name !== "hub" && parent.from_name !== "api") {
1275
- try {
1276
- const notifyId = `chain_${crypto.randomUUID().replace(/-/g, "").slice(0, 16)}`;
1277
- const notifyNode = db.get<{ node_id: string | null }>(
1278
- "SELECT node_id FROM sessions WHERE alias = ?1 AND COALESCE(network_id, 'default') = COALESCE(?2, 'default') ORDER BY updated_at DESC LIMIT 1",
1279
- [parent.from_name, parent.network_id ?? null]
1897
+ db.transaction(() => {
1898
+ // Bump parent status to replied if still open. The task transition and
1899
+ // its scheduler-run mirror share this transaction, so a crash cannot
1900
+ // leave one terminal while the other remains delivered.
1901
+ if (parent.status === "delivered" || parent.status === "acked" || parent.status === "running" || parent.status === "created") {
1902
+ db.run(
1903
+ "UPDATE tasks SET status = ?1, result = ?2, completed_at = datetime('now') WHERE task_id = ?3",
1904
+ [replyStatus, newResult.slice(0, 8000), parent.task_id]
1280
1905
  );
1906
+ syncScheduledRunForTask(parent.task_id, parent.network_id);
1907
+ logTaskEvent(parent.task_id, parent.status, replyStatus, "auto-chain", `from ${childAlias}`);
1908
+ } else {
1281
1909
  db.run(
1282
- `INSERT INTO inbox (id, session_name, node_id, type, priority, content, from_session, in_reply_to, requires_response, network_id)
1283
- VALUES (?1, ?2, ?3, 'reply', 'normal', ?4, ?5, ?6, 'none', ?7)`,
1284
- [notifyId, parent.from_name, notifyNode?.node_id ?? null, `[${childAlias} 子任务完成]\n${currentReply.slice(0, 4000)}`, parent.to_name, parent.task_id, parent.network_id ?? null]
1910
+ "UPDATE tasks SET result = ?1, completed_at = datetime('now') WHERE task_id = ?2",
1911
+ [newResult.slice(0, 8000), parent.task_id]
1285
1912
  );
1286
- } catch {}
1287
- }
1913
+ logTaskEvent(parent.task_id, parent.status, parent.status, "auto-chain-append", `from ${childAlias}`);
1914
+ }
1915
+
1916
+ if (parent.from_name && parent.from_name !== "hub" && parent.from_name !== "api") {
1917
+ try {
1918
+ const notifyId = `chain_${crypto.randomUUID().replace(/-/g, "").slice(0, 16)}`;
1919
+ const notifyNode = db.get<{ node_id: string | null }>(
1920
+ "SELECT node_id FROM sessions WHERE alias = ?1 AND COALESCE(network_id, 'default') = COALESCE(?2, 'default') ORDER BY updated_at DESC LIMIT 1",
1921
+ [parent.from_name, parent.network_id ?? null]
1922
+ );
1923
+ db.run(
1924
+ `INSERT INTO inbox (id, session_name, node_id, type, priority, content, from_session, in_reply_to, requires_response, network_id)
1925
+ VALUES (?1, ?2, ?3, 'reply', 'normal', ?4, ?5, ?6, 'none', ?7)`,
1926
+ [notifyId, parent.from_name, notifyNode?.node_id ?? null, `[${childAlias} 子任务完成]\n${currentReply.slice(0, 4000)}`, parent.to_name, parent.task_id, parent.network_id ?? null]
1927
+ );
1928
+ } catch {}
1929
+ }
1930
+ });
1288
1931
 
1289
1932
  // This iteration actually wrote a parent row (and possibly an
1290
1933
  // inbox notification). Record that so the caller can gate its
@@ -1298,12 +1941,98 @@ export function chainReplyToParent(
1298
1941
  return { chained };
1299
1942
  }
1300
1943
 
1944
+ const SCHEDULED_RUN_TERMINAL_STATUSES = new Set(["replied", "failed", "cancelled", "expired"]);
1945
+
1946
+ type ScheduledTaskLifecycleRow = {
1947
+ task_id: string;
1948
+ network_id: string | null;
1949
+ status: string;
1950
+ completed_at: string | null;
1951
+ };
1952
+
1953
+ type ScheduledTaskBinding = { run_id: string; schedule_id: string };
1954
+
1955
+ /**
1956
+ * Mirror an exact scheduler-created task's lifecycle into its run row.
1957
+ *
1958
+ * The status is always read back from `tasks`; callers cannot supply one.
1959
+ * The scheduler's storage binding is the four-part tuple
1960
+ * (run_id, schedule_id, task_id, network_id). It is read from
1961
+ * `scheduled_task_runs`, not caller-controlled task metadata (which may also
1962
+ * legitimately be replaced by reply attachment metadata).
1963
+ *
1964
+ * Terminal states close the run. `retry_task` calls this after resetting the
1965
+ * same logical task_id to delivered, which deliberately reopens that run so
1966
+ * the history reflects the current retry rather than the first failed attempt.
1967
+ */
1968
+ export function syncScheduledRunForTask(taskId: string, expectedNetworkId?: string | null): { matched: boolean; status?: string } {
1969
+ const task = db.get<ScheduledTaskLifecycleRow>(
1970
+ `SELECT task_id, network_id, status, completed_at
1971
+ FROM tasks
1972
+ WHERE task_id = ?1
1973
+ AND (?2 IS NULL OR network_id = ?2)`,
1974
+ taskId,
1975
+ expectedNetworkId ?? null,
1976
+ );
1977
+ if (!task?.network_id) return { matched: false };
1978
+ const bindings = db.all<ScheduledTaskBinding>(
1979
+ `SELECT run_id, schedule_id FROM scheduled_task_runs
1980
+ WHERE task_id = ?1 AND network_id = ?2`,
1981
+ task.task_id,
1982
+ task.network_id,
1983
+ );
1984
+ // One task belongs to at most one scheduled occurrence. Fail closed if a
1985
+ // corrupt/legacy database violates that invariant rather than fanning one
1986
+ // lifecycle transition into multiple runs.
1987
+ if (bindings.length !== 1) return { matched: false };
1988
+ const binding = bindings[0];
1989
+
1990
+ if (SCHEDULED_RUN_TERMINAL_STATUSES.has(task.status)) {
1991
+ const errorCode = task.status === "replied" ? null : `task_${task.status}`;
1992
+ const updated = db.run(
1993
+ `UPDATE scheduled_task_runs
1994
+ SET status = ?1,
1995
+ error_code = ?2,
1996
+ error_message = NULL,
1997
+ completed_at = COALESCE(?3, datetime('now'))
1998
+ WHERE run_id = ?4 AND task_id = ?5 AND network_id = ?6 AND schedule_id = ?7`,
1999
+ [task.status, errorCode, task.completed_at, binding.run_id, task.task_id, task.network_id, binding.schedule_id],
2000
+ );
2001
+ return { matched: updated.changes === 1, status: task.status };
2002
+ }
2003
+
2004
+ if (task.status === "delivered") {
2005
+ const updated = db.run(
2006
+ `UPDATE scheduled_task_runs
2007
+ SET status = 'delivered', error_code = NULL, error_message = NULL, completed_at = NULL
2008
+ WHERE run_id = ?1 AND task_id = ?2 AND network_id = ?3 AND schedule_id = ?4`,
2009
+ [binding.run_id, task.task_id, task.network_id, binding.schedule_id],
2010
+ );
2011
+ return { matched: updated.changes === 1, status: task.status };
2012
+ }
2013
+
2014
+ return { matched: false };
2015
+ }
2016
+
2017
+ function taskEventTypeForStatus(toStatus: string): string {
2018
+ switch (toStatus) {
2019
+ case "delivered": return "task.send.delivered";
2020
+ case "acked": return "task.ack";
2021
+ case "running": return "task.started";
2022
+ case "replied": return "task.replied";
2023
+ case "expired": return "task.expired";
2024
+ case "failed":
2025
+ case "cancelled": return "task.failed";
2026
+ default: return `task.status.${toStatus}`;
2027
+ }
2028
+ }
2029
+
1301
2030
  export function logTaskEvent(taskId: string, fromStatus: string | null, toStatus: string, actor: string, detail?: string) {
1302
2031
  try {
1303
2032
  db.run(
1304
- `INSERT INTO task_events (task_id, from_status, to_status, actor, detail, network_id)
1305
- VALUES (?1, ?2, ?3, ?4, ?5, (SELECT network_id FROM tasks WHERE task_id = ?1))`,
1306
- [taskId, fromStatus, toStatus, actor, detail ?? null]
2033
+ `INSERT INTO task_events (task_id, from_status, to_status, event_type, actor, detail, network_id)
2034
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, (SELECT network_id FROM tasks WHERE task_id = ?1))`,
2035
+ [taskId, fromStatus, toStatus, taskEventTypeForStatus(toStatus), actor, detail ?? null]
1307
2036
  );
1308
2037
  } catch {}
1309
2038
  }