@sleep2agi/commhub-server 0.9.0-preview.4 → 0.9.0-preview.41

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 (122) 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 +84 -0
  7. package/src/alias-filter.test.ts +72 -0
  8. package/src/alias-filter.ts +32 -0
  9. package/src/api-host-supervisors-fallback.test.ts +267 -0
  10. package/src/api-nodes-shape.test.ts +107 -13
  11. package/src/auth.ts +93 -14
  12. package/src/avatar-validate.test.ts +163 -0
  13. package/src/avatar-validate.ts +103 -0
  14. package/src/boot-side-effect.test.ts +124 -0
  15. package/src/config-apply-sec1.test.ts +107 -0
  16. package/src/config-apply-validate.test.ts +92 -0
  17. package/src/config-apply-validate.ts +81 -3
  18. package/src/create-node-tool-schema.test.ts +39 -0
  19. package/src/create-node-validate.test.ts +80 -1
  20. package/src/create-node-validate.ts +49 -5
  21. package/src/create-node.ts +51 -1
  22. package/src/dashboard-slash-routing-http.test.ts +103 -0
  23. package/src/db-adapter-guard.test.ts +85 -0
  24. package/src/db-adapter.ts +64 -23
  25. package/src/db-timestamp.test.ts +38 -0
  26. package/src/db-timestamp.ts +15 -0
  27. package/src/db.ts +654 -33
  28. package/src/delivered-without-push.test.ts +140 -0
  29. package/src/desktop-message-seam.test.ts +150 -0
  30. package/src/desktop-message.test.ts +368 -0
  31. package/src/ext-token-shared.test.ts +60 -0
  32. package/src/ext-validation-regression.test.ts +131 -0
  33. package/src/external-schedule-edits-http.test.ts +316 -0
  34. package/src/external-schedule-edits.ts +314 -0
  35. package/src/file-download-authz-dev-open.test.ts +135 -0
  36. package/src/file-download-authz.test.ts +403 -0
  37. package/src/file-download-date-bucket.test.ts +436 -0
  38. package/src/file-network-scope-dev-open.test.ts +97 -0
  39. package/src/file-network-scope.test.ts +731 -0
  40. package/src/health-redaction.test.ts +637 -0
  41. package/src/inbox-count-sse.test.ts +310 -0
  42. package/src/inbox-count.ts +29 -0
  43. package/src/index.ts +15 -2187
  44. package/src/lifecycle-guard.ts +50 -0
  45. package/src/list-host-supervisors.test.ts +314 -0
  46. package/src/mcp-write-network-resolution.test.ts +429 -0
  47. package/src/network-name-http.test.ts +71 -0
  48. package/src/network-scope.ts +101 -0
  49. package/src/node-attrs-validate.ts +88 -0
  50. package/src/node-attrs.test.ts +213 -0
  51. package/src/node-id-alias.test.ts +147 -0
  52. package/src/node-lifecycle-controllable.test.ts +64 -0
  53. package/src/node-lifecycle-controllable.ts +51 -0
  54. package/src/observer-avatar-http.test.ts +424 -0
  55. package/src/observer-push.test.ts +252 -0
  56. package/src/package-version-consistency.test.ts +25 -0
  57. package/src/peer-reply-atomic.test.ts +455 -0
  58. package/src/peer-reply-capability.test.ts +70 -0
  59. package/src/probe-validate.test.ts +221 -0
  60. package/src/probe-validate.ts +104 -0
  61. package/src/probe.test.ts +80 -0
  62. package/src/probe.ts +200 -0
  63. package/src/push.ts +163 -7
  64. package/src/redact-tokens.test.ts +65 -0
  65. package/src/redact-tokens.ts +40 -0
  66. package/src/reply-target-derivation.test.ts +96 -0
  67. package/src/require-explicit-test-db.ts +9 -0
  68. package/src/resolve-port.test.ts +57 -0
  69. package/src/resolve-port.ts +44 -0
  70. package/src/response-charset.test.ts +130 -0
  71. package/src/rest-explicit-columns-http.test.ts +212 -0
  72. package/src/rest-identity.test.ts +129 -0
  73. package/src/rest-identity.ts +100 -0
  74. package/src/rest-projections.ts +67 -0
  75. package/src/rest-write-network-resolution.test.ts +133 -0
  76. package/src/runtime-label.test.ts +22 -0
  77. package/src/runtime-label.ts +21 -0
  78. package/src/scheduled-run-terminal.test.ts +268 -0
  79. package/src/scheduled-tasks-http.test.ts +479 -0
  80. package/src/scheduled-tasks.ts +549 -0
  81. package/src/send-reply-agent-warning.test.ts +202 -0
  82. package/src/send-reply-alias-optional.test.ts +131 -0
  83. package/src/send-reply-attachments.test.ts +437 -0
  84. package/src/server.ts +3664 -0
  85. package/src/shared/external-schedule-contract.ts +60 -0
  86. package/src/shared/probe-host-allowlist-drift.test.ts +54 -0
  87. package/src/shared/probe-host-allowlist.ts +128 -0
  88. package/src/side-thread-command-transport.test.ts +302 -0
  89. package/src/side-thread-command-transport.ts +318 -0
  90. package/src/side-thread-http-integration.test.ts +229 -0
  91. package/src/side-thread-http.ts +504 -0
  92. package/src/side-thread-production.test.ts +72 -0
  93. package/src/side-thread-production.ts +118 -0
  94. package/src/side-thread.test.ts +1067 -0
  95. package/src/side-thread.ts +2495 -0
  96. package/src/skillhub-http.test.ts +88 -0
  97. package/src/start-node.test.ts +109 -0
  98. package/src/stop-delete-node.test.ts +952 -0
  99. package/src/task-auth-origin-http.test.ts +87 -0
  100. package/src/task-auth-origin.test.ts +24 -0
  101. package/src/task-auth-origin.ts +7 -0
  102. package/src/task-consumption.test.ts +471 -0
  103. package/src/task-diagnostic-http.test.ts +145 -0
  104. package/src/task-diagnostic.test.ts +115 -0
  105. package/src/task-diagnostic.ts +118 -0
  106. package/src/task-idempotency-mcp.test.ts +142 -0
  107. package/src/task-idempotency.test.ts +60 -0
  108. package/src/task-idempotency.ts +75 -0
  109. package/src/task-lifecycle-watcher.test.ts +200 -0
  110. package/src/task-lifecycle-watcher.ts +49 -0
  111. package/src/task-network-resolution-http.test.ts +137 -0
  112. package/src/tasks-pagination-http.test.ts +137 -0
  113. package/src/tools.ts +2994 -191
  114. package/src/update-provider.test.ts +234 -0
  115. package/src/upload-early-reject-guard.test.ts +155 -0
  116. package/src/uploads-http.test.ts +92 -14
  117. package/src/uploads.test.ts +66 -0
  118. package/src/uploads.ts +130 -5
  119. package/src/user-inbox-read-http.test.ts +220 -0
  120. package/src/user-inbox-schema.test.ts +53 -0
  121. package/src/vault.test.ts +200 -0
  122. package/src/vault.ts +156 -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,
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,8 @@ 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" },
92
126
  ]) {
93
127
  try { db.exec(`ALTER TABLE sessions ADD COLUMN ${col.name} ${col.def}`); } catch {}
94
128
  }
@@ -162,6 +196,11 @@ for (const col of [
162
196
  { name: "scope", def: "TEXT DEFAULT 'single'" },
163
197
  { name: "meta_json", def: "TEXT" },
164
198
  { name: "node_id", def: "TEXT" },
199
+ // #520 — explicit logical task identity. Initial deliveries historically
200
+ // used inbox.id == tasks.task_id, while retry/reassign generate a fresh
201
+ // inbox row id. Keep transport-row identity and logical-task identity
202
+ // separate so runtime evidence/replies survive those redeliveries.
203
+ { name: "task_id", def: "TEXT" },
165
204
  ]) {
166
205
  try { db.exec(`ALTER TABLE inbox ADD COLUMN ${col.name} ${col.def}`); } catch {}
167
206
  }
@@ -191,6 +230,10 @@ db.exec(`
191
230
  created_at TEXT NOT NULL DEFAULT (datetime('now')),
192
231
  delivered_at TEXT,
193
232
  started_at TEXT,
233
+ runtime_submitted_at TEXT,
234
+ consumed_at TEXT,
235
+ thread_id TEXT,
236
+ turn_id TEXT,
194
237
  completed_at TEXT,
195
238
  expires_at TEXT
196
239
  );
@@ -237,6 +280,8 @@ db.exec(`
237
280
  task_id TEXT NOT NULL,
238
281
  from_status TEXT,
239
282
  to_status TEXT NOT NULL,
283
+ event_type TEXT,
284
+ event_key TEXT,
240
285
  actor TEXT NOT NULL DEFAULT 'system',
241
286
  detail TEXT,
242
287
  created_at TEXT NOT NULL DEFAULT (datetime('now'))
@@ -301,6 +346,159 @@ try {
301
346
  if (!/duplicate column|already exists/i.test(e?.message || "")) throw e;
302
347
  }
303
348
 
349
+ // RFC-036 / B4 — immutable per-node owner. New nodes receive this value in
350
+ // the same transaction that mints their node token. Heartbeats may verify the
351
+ // binding but must never first-claim or replace it. Legacy NULL rows remain
352
+ // read-only for external-schedule writes.
353
+ try {
354
+ db.exec(`ALTER TABLE nodes ADD COLUMN owner_user_id TEXT`);
355
+ } catch (e: any) {
356
+ if (!/duplicate column|already exists/i.test(e?.message || "")) throw e;
357
+ }
358
+
359
+ // RFC-026 §9 / #338 PR2 — daemon self-declare fields promoted from
360
+ // config_snapshot to first-class indexable columns. The hub
361
+ // `list_host_supervisors` MCP tool reads these directly without parsing
362
+ // the snapshot JSON on every list call.
363
+ //
364
+ // Both fields are JSON arrays of strings:
365
+ // runtimes_supported e.g. ["claude-agent-sdk","codex-sdk","grok-build-acp"]
366
+ // allowed_secret_keys e.g. ["ANTHROPIC_API_KEY","OPENAI_API_KEY"]
367
+ //
368
+ // Stored as TEXT (JSON-encoded) — SQLite has no native array type and
369
+ // the wrapper code is small. Both nullable for pre-PR2 daemons; the
370
+ // list endpoint falls back to [] when null.
371
+ try {
372
+ db.exec(`ALTER TABLE nodes ADD COLUMN runtimes_supported TEXT`);
373
+ } catch (e: any) {
374
+ if (!/duplicate column|already exists/i.test(e?.message || "")) throw e;
375
+ }
376
+ try {
377
+ db.exec(`ALTER TABLE nodes ADD COLUMN allowed_secret_keys TEXT`);
378
+ } catch (e: any) {
379
+ if (!/duplicate column|already exists/i.test(e?.message || "")) throw e;
380
+ }
381
+
382
+ // RFC-027 §2.3 — state machine for stop/delete (D5). 'active' default
383
+ // matches pre-RFC behavior for every existing row. Transitions:
384
+ // active → stopping → stopped → (back to active via restart_node)
385
+ // active → deleting → (row gone)
386
+ // stopped → deleting → (row gone)
387
+ // Used as the inbox-enqueue gate per §2.3 race-free invariant:
388
+ // pushEvent / INSERT INTO inbox must refuse a non-active target so the
389
+ // SIGTERM-in-flight window never gets a new task.
390
+ try {
391
+ db.exec(`ALTER TABLE nodes ADD COLUMN lifecycle_state TEXT DEFAULT 'active'`);
392
+ } catch (e: any) {
393
+ if (!/duplicate column|already exists/i.test(e?.message || "")) throw e;
394
+ }
395
+
396
+ // #462 — user-set custom avatar (nullable http/https image URL). Pure
397
+ // display attribute: deliberately NOT part of the RFC-024 config-apply
398
+ // pipeline (nothing for agent-node to consume, no revision/ack). Written
399
+ // only via PUT /api/nodes/:ref/avatar which validates the URL shape.
400
+ try {
401
+ db.exec(`ALTER TABLE nodes ADD COLUMN avatar_url TEXT`);
402
+ } catch (e: any) {
403
+ if (!/duplicate column|already exists/i.test(e?.message || "")) throw e;
404
+ }
405
+
406
+ // Node DISPLAY attributes (Vincent 目标第 3 条 — dashboard/app 多维度编辑).
407
+ // Same posture as avatar_url above: hub-side presentation only, NOT part of
408
+ // the RFC-024 config-apply pipeline (agent-node consumes none of them, so a
409
+ // doorbell/ack round-trip would be meaningless and could wedge the config
410
+ // revision). Written only via PUT /api/nodes/:ref/attrs.
411
+ //
412
+ // display_name — human label shown in the UI. Distinct from `alias`,
413
+ // which is the ROUTING key (messages address the alias)
414
+ // and from `node_name`, which is an addressing key
415
+ // (`WHERE node_id OR node_name OR alias`). Renaming
416
+ // either of those must go through the rename 2PC
417
+ // (/api/node-rename/*), never through an attrs write.
418
+ // team, tags — organisation metadata; tags stored as JSON array text.
419
+ // attrs_revision — optimistic-lock counter for these display fields ONLY.
420
+ // Deliberately separate from config_revision so that
421
+ // editing a tag never bumps the node's *config* revision
422
+ // (which would perturb the config ack protocol).
423
+ //
424
+ // All nullable / defaulted so the ~100 rows already in flight keep reading.
425
+ for (const ddl of [
426
+ `ALTER TABLE nodes ADD COLUMN display_name TEXT`,
427
+ `ALTER TABLE nodes ADD COLUMN team TEXT`,
428
+ `ALTER TABLE nodes ADD COLUMN tags TEXT`,
429
+ `ALTER TABLE nodes ADD COLUMN attrs_revision INTEGER NOT NULL DEFAULT 0`,
430
+ ]) {
431
+ try {
432
+ db.exec(ddl);
433
+ } catch (e: any) {
434
+ if (!/duplicate column|already exists/i.test(e?.message || "")) throw e;
435
+ }
436
+ }
437
+
438
+ // RFC-027 §2 — stop/delete request envelope. Mirrors
439
+ // node_create_requests structure so the daemon-side pull/ack pattern
440
+ // is symmetric with create_node. action='stop'|'delete' picks which
441
+ // branch (delete adds backup_path + revokes ntok on ack).
442
+ db.exec(`
443
+ CREATE TABLE IF NOT EXISTS node_stop_requests (
444
+ request_id TEXT PRIMARY KEY,
445
+ network_id TEXT NOT NULL,
446
+ daemon_node_id TEXT NOT NULL,
447
+ child_node_id TEXT NOT NULL,
448
+ child_alias TEXT NOT NULL,
449
+ child_token_id TEXT,
450
+ action TEXT NOT NULL CHECK (action IN ('stop', 'delete')),
451
+ delete_config INTEGER NOT NULL DEFAULT 1,
452
+ grace_seconds INTEGER NOT NULL DEFAULT 10,
453
+ force INTEGER NOT NULL DEFAULT 0,
454
+ in_flight_at_dispatch INTEGER NOT NULL DEFAULT 0,
455
+ created_by_token TEXT NOT NULL,
456
+ status TEXT NOT NULL DEFAULT 'pending',
457
+ error TEXT,
458
+ backup_path TEXT,
459
+ exit_signal TEXT,
460
+ created_at INTEGER NOT NULL,
461
+ delivered_at INTEGER,
462
+ acked_at INTEGER
463
+ )
464
+ `);
465
+ db.exec(`CREATE INDEX IF NOT EXISTS idx_stop_req_daemon ON node_stop_requests(daemon_node_id, status)`);
466
+ db.exec(`CREATE INDEX IF NOT EXISTS idx_stop_req_child ON node_stop_requests(child_node_id)`);
467
+ // #1448 finding-5 — 存 delete 目标 child 的 token_id,让 ack 精确按 token_id 撤 ntok
468
+ // (而非按 name='node:<alias>' 广撤 → 同 alias 在 delete 窗口内重建会误杀新 token)。
469
+ // 幂等迁移:已有库补列,旧行 child_token_id 为 NULL、ack 时 fallback 回按 name 撤。
470
+ try { db.exec(`ALTER TABLE node_stop_requests ADD COLUMN child_token_id TEXT`); } catch { /* 已存在 */ }
471
+
472
+ // Daemon-mediated start request. Kept separate from node_stop_requests:
473
+ // the deployed stop table has a CHECK(action IN ('stop','delete')) and
474
+ // rebuilding that table in-place would be a risky migration for an additive
475
+ // lifecycle operation.
476
+ db.exec(`
477
+ CREATE TABLE IF NOT EXISTS node_start_requests (
478
+ request_id TEXT PRIMARY KEY,
479
+ network_id TEXT NOT NULL,
480
+ daemon_node_id TEXT NOT NULL,
481
+ child_node_id TEXT NOT NULL,
482
+ child_alias TEXT NOT NULL,
483
+ created_by_token TEXT NOT NULL,
484
+ status TEXT NOT NULL DEFAULT 'pending',
485
+ error TEXT,
486
+ child_pid INTEGER,
487
+ created_at INTEGER NOT NULL,
488
+ delivered_at INTEGER,
489
+ acked_at INTEGER
490
+ )
491
+ `);
492
+ db.exec(`CREATE INDEX IF NOT EXISTS idx_start_req_daemon ON node_start_requests(daemon_node_id, status)`);
493
+ db.exec(`CREATE INDEX IF NOT EXISTS idx_start_req_child ON node_start_requests(child_node_id)`);
494
+ try {
495
+ db.exec(`CREATE UNIQUE INDEX IF NOT EXISTS uniq_start_req_child_inflight
496
+ ON node_start_requests(child_node_id)
497
+ WHERE status IN ('pending', 'delivered')`);
498
+ } catch (e: any) {
499
+ if (!/unique constraint/i.test(e?.message || "")) throw e;
500
+ }
501
+
304
502
  // `node_config_updates` — pending + history. One row per dashboard write.
305
503
  // At most one row per node may be in a non-terminal state at a time
306
504
  // (single-flight enforced at the tool layer; this table just stores).
@@ -387,6 +585,7 @@ for (const ddl of [
387
585
  "ALTER TABLE api_tokens ADD COLUMN request_id TEXT",
388
586
  "ALTER TABLE api_tokens ADD COLUMN revoked_at TEXT",
389
587
  "ALTER TABLE api_tokens ADD COLUMN role TEXT",
588
+ "ALTER TABLE api_tokens ADD COLUMN bound_node_id TEXT",
390
589
  ]) {
391
590
  try { db.exec(ddl); }
392
591
  catch (e: any) {
@@ -395,6 +594,8 @@ for (const ddl of [
395
594
  }
396
595
  try { db.exec(`CREATE INDEX IF NOT EXISTS idx_tokens_request ON api_tokens(request_id)`); }
397
596
  catch (e: any) { /* index may already exist */ void e; }
597
+ try { db.exec(`CREATE INDEX IF NOT EXISTS idx_tokens_bound_node ON api_tokens(bound_node_id)`); }
598
+ catch (e: any) { void e; }
398
599
 
399
600
  // RFC-026 v4 §2.5 + §4.4 — node_create_requests. Metadata only;
400
601
  // env_blob NEVER lives in this table (F1 mint-stream-evict — secret
@@ -411,7 +612,7 @@ db.exec(`
411
612
  child_name TEXT NOT NULL,
412
613
  network_id TEXT NOT NULL,
413
614
  runtime TEXT NOT NULL,
414
- model TEXT NOT NULL,
615
+ model TEXT,
415
616
  flags_json TEXT NOT NULL,
416
617
  env_keys TEXT NOT NULL,
417
618
  status TEXT NOT NULL,
@@ -428,6 +629,63 @@ db.exec(`
428
629
  CREATE INDEX IF NOT EXISTS idx_ncr_network ON node_create_requests(network_id);
429
630
  CREATE INDEX IF NOT EXISTS idx_ncr_child_name ON node_create_requests(child_name);
430
631
  `);
632
+ function migrateNodeCreateRequestsModelNullable() {
633
+ if (db.dialect === "postgres") {
634
+ try { db.exec("ALTER TABLE node_create_requests ALTER COLUMN model DROP NOT NULL"); } catch {}
635
+ return;
636
+ }
637
+
638
+ let needsRebuild = false;
639
+ try {
640
+ const createSql = db.get<{ sql: string }>("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'node_create_requests'");
641
+ needsRebuild = !!createSql?.sql && /\bmodel\s+TEXT\s+NOT\s+NULL\b/i.test(createSql.sql);
642
+ } catch {}
643
+ if (!needsRebuild) return;
644
+
645
+ db.transaction(() => {
646
+ db.exec("DROP TABLE IF EXISTS node_create_requests_migrated");
647
+ db.exec(`
648
+ CREATE TABLE node_create_requests_migrated (
649
+ request_id TEXT PRIMARY KEY,
650
+ daemon_node_id TEXT NOT NULL,
651
+ child_name TEXT NOT NULL,
652
+ network_id TEXT NOT NULL,
653
+ runtime TEXT NOT NULL,
654
+ model TEXT,
655
+ flags_json TEXT NOT NULL,
656
+ env_keys TEXT NOT NULL,
657
+ status TEXT NOT NULL,
658
+ error TEXT,
659
+ child_token_id TEXT,
660
+ created_at INTEGER NOT NULL,
661
+ created_by_token TEXT NOT NULL,
662
+ delivered_at INTEGER,
663
+ acked_at INTEGER,
664
+ child_node_id TEXT
665
+ )
666
+ `);
667
+ db.exec(`
668
+ INSERT INTO node_create_requests_migrated (
669
+ request_id, daemon_node_id, child_name, network_id, runtime, model,
670
+ flags_json, env_keys, status, error, child_token_id, created_at,
671
+ created_by_token, delivered_at, acked_at, child_node_id
672
+ )
673
+ SELECT
674
+ request_id, daemon_node_id, child_name, network_id, runtime, model,
675
+ flags_json, env_keys, status, error, child_token_id, created_at,
676
+ created_by_token, delivered_at, acked_at, child_node_id
677
+ FROM node_create_requests
678
+ `);
679
+ db.exec("DROP TABLE node_create_requests");
680
+ db.exec("ALTER TABLE node_create_requests_migrated RENAME TO node_create_requests");
681
+ });
682
+ }
683
+ migrateNodeCreateRequestsModelNullable();
684
+ db.exec(`
685
+ CREATE INDEX IF NOT EXISTS idx_ncr_daemon_status ON node_create_requests(daemon_node_id, status);
686
+ CREATE INDEX IF NOT EXISTS idx_ncr_network ON node_create_requests(network_id);
687
+ CREATE INDEX IF NOT EXISTS idx_ncr_child_name ON node_create_requests(child_name);
688
+ `);
431
689
  try {
432
690
  // Single-flight per (daemon, child_name) — prevents racing dashboard
433
691
  // create on same name. Mirrors RFC-024 uniq_ncu_node_inflight.
@@ -436,6 +694,76 @@ try {
436
694
  console.warn(`[commhub] partial unique index uniq_ncr_inflight skipped: ${e?.message || e}`);
437
695
  }
438
696
 
697
+ // RFC-028 P1 v4 §2.2 — providers + provider_models + network_secrets +
698
+ // probe_results. All 4 tables idempotent CREATE TABLE IF NOT EXISTS. F2
699
+ // lazy gate: tables created on hub boot regardless; vault master key
700
+ // (ANET_HUB_SECRET_VAULT_KEY env) only required when these tables get
701
+ // their first non-empty row (lazy in vault.ts). Empty tables = hub
702
+ // boots fine without env (critical for existing prod hub升级 不 brick).
703
+ db.exec(`
704
+ CREATE TABLE IF NOT EXISTS providers (
705
+ provider_id TEXT PRIMARY KEY,
706
+ network_id TEXT NOT NULL,
707
+ name TEXT NOT NULL,
708
+ vendor TEXT NOT NULL,
709
+ base_url TEXT NOT NULL,
710
+ secret_key_ref TEXT NOT NULL,
711
+ created_at INTEGER NOT NULL,
712
+ created_by TEXT NOT NULL,
713
+ enabled INTEGER NOT NULL DEFAULT 1,
714
+ UNIQUE(network_id, name)
715
+ );
716
+ CREATE INDEX IF NOT EXISTS idx_providers_network ON providers(network_id);
717
+ `);
718
+ db.exec(`
719
+ CREATE TABLE IF NOT EXISTS provider_models (
720
+ model_id TEXT PRIMARY KEY,
721
+ provider_id TEXT NOT NULL,
722
+ model_name TEXT NOT NULL,
723
+ display_name TEXT,
724
+ context_window INTEGER,
725
+ supports_vision INTEGER NOT NULL DEFAULT 0,
726
+ enabled INTEGER NOT NULL DEFAULT 1,
727
+ created_at INTEGER NOT NULL,
728
+ UNIQUE(provider_id, model_name)
729
+ );
730
+ CREATE INDEX IF NOT EXISTS idx_models_provider ON provider_models(provider_id);
731
+ `);
732
+ // network_secrets — encrypted-at-rest vault. ciphertext + iv + tag are
733
+ // AES-GCM output; plaintext NEVER touches this table. master key from
734
+ // ANET_HUB_SECRET_VAULT_KEY env (lazy gate in vault.ts).
735
+ db.exec(`
736
+ CREATE TABLE IF NOT EXISTS network_secrets (
737
+ network_id TEXT NOT NULL,
738
+ key TEXT NOT NULL,
739
+ ciphertext BLOB NOT NULL,
740
+ iv BLOB NOT NULL,
741
+ tag BLOB NOT NULL,
742
+ created_at INTEGER NOT NULL,
743
+ updated_at INTEGER NOT NULL,
744
+ PRIMARY KEY (network_id, key)
745
+ );
746
+ `);
747
+ // probe_results — connectivity matrix history. v3 R3 lock: error_label
748
+ // is HUB-DERIVED ONLY from (status, raw_status_code) — daemon CANNOT
749
+ // submit arbitrary error string. status enum mirrors ProbeAckPayload.
750
+ db.exec(`
751
+ CREATE TABLE IF NOT EXISTS probe_results (
752
+ probe_id TEXT PRIMARY KEY,
753
+ provider_id TEXT NOT NULL,
754
+ model_name TEXT NOT NULL,
755
+ daemon_node_id TEXT NOT NULL,
756
+ network_id TEXT NOT NULL,
757
+ status TEXT NOT NULL,
758
+ latency_ms INTEGER,
759
+ error_label TEXT,
760
+ probed_at INTEGER NOT NULL,
761
+ probed_by_user TEXT,
762
+ raw_status_code INTEGER
763
+ );
764
+ CREATE INDEX IF NOT EXISTS idx_probe_matrix ON probe_results(network_id, provider_id, model_name, daemon_node_id, probed_at DESC);
765
+ `);
766
+
439
767
  // ── V3: audit_log table ──
440
768
  db.exec(`
441
769
  CREATE TABLE IF NOT EXISTS audit_log (
@@ -456,6 +784,37 @@ db.exec(`
456
784
  CREATE INDEX IF NOT EXISTS idx_audit_network ON audit_log(network_id);
457
785
  `);
458
786
 
787
+ // SkillHub — immutable, network-scoped skill submissions. A (network, slug,
788
+ // version) tuple is write-once: retries with the same content are idempotent,
789
+ // while different content must use a new version. Node submissions remain
790
+ // pending until an owner/admin explicitly publishes them.
791
+ db.exec(`
792
+ CREATE TABLE IF NOT EXISTS skillhub_skills (
793
+ skill_id TEXT PRIMARY KEY,
794
+ network_id TEXT NOT NULL,
795
+ slug TEXT NOT NULL,
796
+ name TEXT NOT NULL,
797
+ description TEXT NOT NULL DEFAULT '',
798
+ version TEXT NOT NULL,
799
+ content TEXT NOT NULL,
800
+ content_hash TEXT NOT NULL,
801
+ status TEXT NOT NULL DEFAULT 'pending' CHECK(status IN ('pending', 'published', 'rejected', 'archived')),
802
+ source_type TEXT NOT NULL CHECK(source_type IN ('node', 'user')),
803
+ source_alias TEXT,
804
+ created_by_user TEXT,
805
+ reviewed_by_user TEXT,
806
+ review_note TEXT,
807
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
808
+ updated_at TEXT NOT NULL DEFAULT (datetime('now')),
809
+ reviewed_at TEXT,
810
+ UNIQUE(network_id, slug, version)
811
+ );
812
+ CREATE INDEX IF NOT EXISTS idx_skillhub_network_status
813
+ ON skillhub_skills(network_id, status, updated_at DESC);
814
+ CREATE INDEX IF NOT EXISTS idx_skillhub_network_slug
815
+ ON skillhub_skills(network_id, slug, version);
816
+ `);
817
+
459
818
  // ── V3: licenses table ──
460
819
  db.exec(`
461
820
  CREATE TABLE IF NOT EXISTS licenses (
@@ -566,6 +925,14 @@ for (const table of ["sessions", "nodes", "tasks", "inbox", "task_events", "comp
566
925
  try { db.exec(`ALTER TABLE ${table} ADD COLUMN network_id TEXT`); } catch {}
567
926
  }
568
927
 
928
+ // #167 — stable lifecycle event names plus an internal idempotency key.
929
+ // Ordinary status transitions keep event_key NULL, so retries and repeated
930
+ // transitions remain auditable. Watcher warnings set a stable key; the unique
931
+ // index makes every (task, threshold) write-once across patrol rounds/workers.
932
+ try { db.exec("ALTER TABLE task_events ADD COLUMN event_type TEXT"); } catch {}
933
+ try { db.exec("ALTER TABLE task_events ADD COLUMN event_key TEXT"); } catch {}
934
+ try { db.exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_task_events_task_key ON task_events(task_id, event_key)"); } catch {}
935
+
569
936
  // PR-1 (#146): durable node identity on historical inbox/tasks rows. Some
570
937
  // existing databases created `tasks` before from_node_id/to_node_id were in the
571
938
  // CREATE TABLE statement, so keep these ALTERs explicit and idempotent.
@@ -852,6 +1219,172 @@ try { db.exec("CREATE INDEX IF NOT EXISTS idx_completions_network ON completions
852
1219
  // the reply up the chain via parent_task_id.
853
1220
  try { db.exec("ALTER TABLE tasks ADD COLUMN parent_task_id TEXT"); } catch {}
854
1221
  try { db.exec("ALTER TABLE tasks ADD COLUMN meta_json TEXT"); } catch {}
1222
+ // #520 — two monotonic evidence levels for this exact task:
1223
+ // runtime_submitted_at means agent-node handed the body to the vendor runtime;
1224
+ // consumed_at requires an attributable turn-start/first-activity signal.
1225
+ // Both stay separate from delivered_at (enqueue), acked (process receipt), and
1226
+ // started_at (legacy report_status/content matching). Old binaries ignore them.
1227
+ try { db.exec("ALTER TABLE tasks ADD COLUMN runtime_submitted_at TEXT"); } catch {}
1228
+ try { db.exec("ALTER TABLE tasks ADD COLUMN consumed_at TEXT"); } catch {}
1229
+ // Exact vendor-runtime boundary for SideThread-capable clients. These values
1230
+ // are written only by the token-bound target node after attributable runtime
1231
+ // evidence; the Hub never derives them from task text or caller input.
1232
+ try { db.exec("ALTER TABLE tasks ADD COLUMN thread_id TEXT"); } catch {}
1233
+ try { db.exec("ALTER TABLE tasks ADD COLUMN turn_id TEXT"); } catch {}
1234
+
1235
+ // #1181 durable outbound terminal cursor. A task's created_at cannot be used
1236
+ // as a recovery watermark because an old task may become terminal after newer
1237
+ // tasks. Record terminal transitions in their own monotonically increasing
1238
+ // journal instead. The journal is append-only for a logical task; retry keeps
1239
+ // the existing task identity and therefore the same idempotency domain.
1240
+ db.exec(`
1241
+ CREATE TABLE IF NOT EXISTS task_terminal_events (
1242
+ terminal_seq INTEGER PRIMARY KEY AUTOINCREMENT,
1243
+ task_id TEXT NOT NULL UNIQUE,
1244
+ network_id TEXT,
1245
+ from_node_id TEXT,
1246
+ completed_at TEXT NOT NULL DEFAULT (datetime('now'))
1247
+ );
1248
+ CREATE INDEX IF NOT EXISTS idx_task_terminal_events_sender_seq
1249
+ ON task_terminal_events(network_id, from_node_id, terminal_seq);
1250
+ `);
1251
+ if (db.dialect === "sqlite") {
1252
+ db.exec(`
1253
+ CREATE TRIGGER IF NOT EXISTS tasks_terminal_event_insert
1254
+ AFTER INSERT ON tasks
1255
+ WHEN NEW.status IN ('replied', 'failed', 'cancelled', 'expired')
1256
+ BEGIN
1257
+ INSERT OR IGNORE INTO task_terminal_events (task_id, network_id, from_node_id, completed_at)
1258
+ VALUES (NEW.task_id, NEW.network_id, NEW.from_node_id, COALESCE(NEW.completed_at, datetime('now')));
1259
+ END;
1260
+ CREATE TRIGGER IF NOT EXISTS tasks_terminal_event_update
1261
+ AFTER UPDATE OF status ON tasks
1262
+ WHEN NEW.status IN ('replied', 'failed', 'cancelled', 'expired')
1263
+ AND OLD.status NOT IN ('replied', 'failed', 'cancelled', 'expired')
1264
+ BEGIN
1265
+ INSERT OR IGNORE INTO task_terminal_events (task_id, network_id, from_node_id, completed_at)
1266
+ VALUES (NEW.task_id, NEW.network_id, NEW.from_node_id, COALESCE(NEW.completed_at, datetime('now')));
1267
+ END;
1268
+ `);
1269
+ db.run(`INSERT OR IGNORE INTO task_terminal_events (task_id, network_id, from_node_id, completed_at)
1270
+ SELECT task_id, network_id, from_node_id, COALESCE(completed_at, created_at)
1271
+ FROM tasks
1272
+ WHERE status IN ('replied', 'failed', 'cancelled', 'expired')
1273
+ ORDER BY COALESCE(completed_at, created_at), task_id`);
1274
+ } else {
1275
+ db.exec(`
1276
+ CREATE OR REPLACE FUNCTION record_task_terminal_event() RETURNS trigger AS $$
1277
+ BEGIN
1278
+ IF NEW.status IN ('replied', 'failed', 'cancelled', 'expired')
1279
+ AND (TG_OP = 'INSERT' OR OLD.status NOT IN ('replied', 'failed', 'cancelled', 'expired')) THEN
1280
+ INSERT INTO task_terminal_events (task_id, network_id, from_node_id, completed_at)
1281
+ VALUES (NEW.task_id, NEW.network_id, NEW.from_node_id, COALESCE(NEW.completed_at, NOW()))
1282
+ ON CONFLICT (task_id) DO NOTHING;
1283
+ END IF;
1284
+ RETURN NEW;
1285
+ END;
1286
+ $$ LANGUAGE plpgsql;
1287
+ DROP TRIGGER IF EXISTS tasks_terminal_event_insert ON tasks;
1288
+ DROP TRIGGER IF EXISTS tasks_terminal_event_update ON tasks;
1289
+ CREATE TRIGGER tasks_terminal_event_insert AFTER INSERT ON tasks
1290
+ FOR EACH ROW EXECUTE FUNCTION record_task_terminal_event();
1291
+ CREATE TRIGGER tasks_terminal_event_update AFTER UPDATE OF status ON tasks
1292
+ FOR EACH ROW EXECUTE FUNCTION record_task_terminal_event();
1293
+ INSERT INTO task_terminal_events (task_id, network_id, from_node_id, completed_at)
1294
+ SELECT task_id, network_id, from_node_id, COALESCE(completed_at, created_at)
1295
+ FROM tasks WHERE status IN ('replied', 'failed', 'cancelled', 'expired')
1296
+ ON CONFLICT (task_id) DO NOTHING;
1297
+ `);
1298
+ }
1299
+
1300
+ // ── Hub scheduled tasks ──────────────────────────────────────────────
1301
+ // Scheduling is a Hub concern: clients manage these rows, while agents only
1302
+ // receive the ordinary inbox/tasks rows produced for each occurrence. Keep
1303
+ // the occurrence table separate so retries, skips and failures remain
1304
+ // auditable without overloading the task lifecycle.
1305
+ db.exec(`
1306
+ CREATE TABLE IF NOT EXISTS scheduled_tasks (
1307
+ schedule_id TEXT PRIMARY KEY,
1308
+ network_id TEXT NOT NULL,
1309
+ created_by TEXT,
1310
+ name TEXT NOT NULL,
1311
+ target_node_id TEXT NOT NULL,
1312
+ target_alias TEXT NOT NULL,
1313
+ task_content TEXT NOT NULL,
1314
+ priority TEXT NOT NULL DEFAULT 'normal',
1315
+ schedule_type TEXT NOT NULL,
1316
+ schedule_json TEXT NOT NULL,
1317
+ timezone TEXT NOT NULL DEFAULT 'UTC',
1318
+ overlap_policy TEXT NOT NULL DEFAULT 'skip',
1319
+ misfire_policy TEXT NOT NULL DEFAULT 'catch_up_once',
1320
+ status TEXT NOT NULL DEFAULT 'active',
1321
+ next_run_at TEXT,
1322
+ last_run_at TEXT,
1323
+ revision INTEGER NOT NULL DEFAULT 1,
1324
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
1325
+ updated_at TEXT NOT NULL DEFAULT (datetime('now'))
1326
+ );
1327
+
1328
+ CREATE INDEX IF NOT EXISTS idx_scheduled_tasks_due
1329
+ ON scheduled_tasks(status, next_run_at);
1330
+ CREATE INDEX IF NOT EXISTS idx_scheduled_tasks_network
1331
+ ON scheduled_tasks(network_id, updated_at DESC);
1332
+ CREATE INDEX IF NOT EXISTS idx_scheduled_tasks_target
1333
+ ON scheduled_tasks(network_id, target_node_id);
1334
+
1335
+ CREATE TABLE IF NOT EXISTS scheduled_task_runs (
1336
+ run_id TEXT PRIMARY KEY,
1337
+ schedule_id TEXT NOT NULL,
1338
+ network_id TEXT NOT NULL,
1339
+ scheduled_for TEXT NOT NULL,
1340
+ task_id TEXT,
1341
+ status TEXT NOT NULL,
1342
+ error_code TEXT,
1343
+ error_message TEXT,
1344
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
1345
+ completed_at TEXT,
1346
+ UNIQUE(schedule_id, scheduled_for)
1347
+ );
1348
+
1349
+ CREATE INDEX IF NOT EXISTS idx_scheduled_runs_schedule
1350
+ ON scheduled_task_runs(schedule_id, created_at DESC);
1351
+ CREATE INDEX IF NOT EXISTS idx_scheduled_runs_network
1352
+ ON scheduled_task_runs(network_id, created_at DESC);
1353
+ `);
1354
+ try { db.exec("ALTER TABLE scheduled_tasks ADD COLUMN misfire_policy TEXT NOT NULL DEFAULT 'catch_up_once'"); } catch {}
1355
+
1356
+ // RFC-036 / B4 — owner-authorized edits of node-host managed schedules.
1357
+ // This is intentionally separate from Hub scheduled_tasks: these rows are
1358
+ // one-shot control intents consumed by the exact token-bound node. The partial
1359
+ // unique index makes the single-flight promise survive multiple Hub workers.
1360
+ db.exec(`
1361
+ CREATE TABLE IF NOT EXISTS external_schedule_edits (
1362
+ intent_id TEXT PRIMARY KEY,
1363
+ network_id TEXT NOT NULL,
1364
+ node_id TEXT NOT NULL,
1365
+ schedule_id TEXT NOT NULL,
1366
+ base_revision INTEGER NOT NULL,
1367
+ patch_json TEXT NOT NULL,
1368
+ status TEXT NOT NULL DEFAULT 'pending',
1369
+ expires_at INTEGER NOT NULL,
1370
+ created_at INTEGER NOT NULL,
1371
+ delivered_at INTEGER,
1372
+ acked_at INTEGER,
1373
+ created_by_user TEXT NOT NULL,
1374
+ created_by_token TEXT NOT NULL,
1375
+ consumed_by_token TEXT,
1376
+ result_revision INTEGER,
1377
+ error_code TEXT
1378
+ );
1379
+
1380
+ CREATE INDEX IF NOT EXISTS idx_external_schedule_edits_node
1381
+ ON external_schedule_edits(network_id, node_id, status, created_at);
1382
+ CREATE INDEX IF NOT EXISTS idx_external_schedule_edits_owner
1383
+ ON external_schedule_edits(created_by_user, created_at DESC);
1384
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_external_schedule_edits_singleflight
1385
+ ON external_schedule_edits(node_id, schedule_id)
1386
+ WHERE status IN ('pending', 'delivered');
1387
+ `);
855
1388
  try { db.exec("CREATE INDEX IF NOT EXISTS idx_tasks_parent ON tasks(parent_task_id)"); } catch {}
856
1389
 
857
1390
  // Helpers
@@ -1160,38 +1693,40 @@ export function chainReplyToParent(
1160
1693
  const marker = `\n\n[via ${childAlias} 子任务结果]\n${currentReply}`;
1161
1694
  const newResult = parent.result ? parent.result + marker : `[via ${childAlias} 子任务结果]\n${currentReply}`;
1162
1695
 
1163
- // Bump parent status to replied if still open. If it was already replied
1164
- // (e.g. 指挥室 sent an early status update), we still want to update the
1165
- // result so the dashboard can render the final chained answer — but keep
1166
- // status as replied (it was already terminal).
1167
- if (parent.status === "delivered" || parent.status === "acked" || parent.status === "running" || parent.status === "created") {
1168
- db.run(
1169
- "UPDATE tasks SET status = ?1, result = ?2, completed_at = datetime('now') WHERE task_id = ?3",
1170
- [replyStatus, newResult.slice(0, 8000), parent.task_id]
1171
- );
1172
- logTaskEvent(parent.task_id, parent.status, replyStatus, "auto-chain", `from ${childAlias}`);
1173
- } else {
1174
- db.run(
1175
- "UPDATE tasks SET result = ?1, completed_at = datetime('now') WHERE task_id = ?2",
1176
- [newResult.slice(0, 8000), parent.task_id]
1177
- );
1178
- logTaskEvent(parent.task_id, parent.status, parent.status, "auto-chain-append", `from ${childAlias}`);
1179
- }
1180
-
1181
- if (parent.from_name && parent.from_name !== "hub" && parent.from_name !== "api") {
1182
- try {
1183
- const notifyId = `chain_${crypto.randomUUID().replace(/-/g, "").slice(0, 16)}`;
1184
- const notifyNode = db.get<{ node_id: string | null }>(
1185
- "SELECT node_id FROM sessions WHERE alias = ?1 AND COALESCE(network_id, 'default') = COALESCE(?2, 'default') ORDER BY updated_at DESC LIMIT 1",
1186
- [parent.from_name, parent.network_id ?? null]
1696
+ db.transaction(() => {
1697
+ // Bump parent status to replied if still open. The task transition and
1698
+ // its scheduler-run mirror share this transaction, so a crash cannot
1699
+ // leave one terminal while the other remains delivered.
1700
+ if (parent.status === "delivered" || parent.status === "acked" || parent.status === "running" || parent.status === "created") {
1701
+ db.run(
1702
+ "UPDATE tasks SET status = ?1, result = ?2, completed_at = datetime('now') WHERE task_id = ?3",
1703
+ [replyStatus, newResult.slice(0, 8000), parent.task_id]
1187
1704
  );
1705
+ syncScheduledRunForTask(parent.task_id, parent.network_id);
1706
+ logTaskEvent(parent.task_id, parent.status, replyStatus, "auto-chain", `from ${childAlias}`);
1707
+ } else {
1188
1708
  db.run(
1189
- `INSERT INTO inbox (id, session_name, node_id, type, priority, content, from_session, in_reply_to, requires_response, network_id)
1190
- VALUES (?1, ?2, ?3, 'reply', 'normal', ?4, ?5, ?6, 'none', ?7)`,
1191
- [notifyId, parent.from_name, notifyNode?.node_id ?? null, `[${childAlias} 子任务完成]\n${currentReply.slice(0, 4000)}`, parent.to_name, parent.task_id, parent.network_id ?? null]
1709
+ "UPDATE tasks SET result = ?1, completed_at = datetime('now') WHERE task_id = ?2",
1710
+ [newResult.slice(0, 8000), parent.task_id]
1192
1711
  );
1193
- } catch {}
1194
- }
1712
+ logTaskEvent(parent.task_id, parent.status, parent.status, "auto-chain-append", `from ${childAlias}`);
1713
+ }
1714
+
1715
+ if (parent.from_name && parent.from_name !== "hub" && parent.from_name !== "api") {
1716
+ try {
1717
+ const notifyId = `chain_${crypto.randomUUID().replace(/-/g, "").slice(0, 16)}`;
1718
+ const notifyNode = db.get<{ node_id: string | null }>(
1719
+ "SELECT node_id FROM sessions WHERE alias = ?1 AND COALESCE(network_id, 'default') = COALESCE(?2, 'default') ORDER BY updated_at DESC LIMIT 1",
1720
+ [parent.from_name, parent.network_id ?? null]
1721
+ );
1722
+ db.run(
1723
+ `INSERT INTO inbox (id, session_name, node_id, type, priority, content, from_session, in_reply_to, requires_response, network_id)
1724
+ VALUES (?1, ?2, ?3, 'reply', 'normal', ?4, ?5, ?6, 'none', ?7)`,
1725
+ [notifyId, parent.from_name, notifyNode?.node_id ?? null, `[${childAlias} 子任务完成]\n${currentReply.slice(0, 4000)}`, parent.to_name, parent.task_id, parent.network_id ?? null]
1726
+ );
1727
+ } catch {}
1728
+ }
1729
+ });
1195
1730
 
1196
1731
  // This iteration actually wrote a parent row (and possibly an
1197
1732
  // inbox notification). Record that so the caller can gate its
@@ -1205,12 +1740,98 @@ export function chainReplyToParent(
1205
1740
  return { chained };
1206
1741
  }
1207
1742
 
1743
+ const SCHEDULED_RUN_TERMINAL_STATUSES = new Set(["replied", "failed", "cancelled", "expired"]);
1744
+
1745
+ type ScheduledTaskLifecycleRow = {
1746
+ task_id: string;
1747
+ network_id: string | null;
1748
+ status: string;
1749
+ completed_at: string | null;
1750
+ };
1751
+
1752
+ type ScheduledTaskBinding = { run_id: string; schedule_id: string };
1753
+
1754
+ /**
1755
+ * Mirror an exact scheduler-created task's lifecycle into its run row.
1756
+ *
1757
+ * The status is always read back from `tasks`; callers cannot supply one.
1758
+ * The scheduler's storage binding is the four-part tuple
1759
+ * (run_id, schedule_id, task_id, network_id). It is read from
1760
+ * `scheduled_task_runs`, not caller-controlled task metadata (which may also
1761
+ * legitimately be replaced by reply attachment metadata).
1762
+ *
1763
+ * Terminal states close the run. `retry_task` calls this after resetting the
1764
+ * same logical task_id to delivered, which deliberately reopens that run so
1765
+ * the history reflects the current retry rather than the first failed attempt.
1766
+ */
1767
+ export function syncScheduledRunForTask(taskId: string, expectedNetworkId?: string | null): { matched: boolean; status?: string } {
1768
+ const task = db.get<ScheduledTaskLifecycleRow>(
1769
+ `SELECT task_id, network_id, status, completed_at
1770
+ FROM tasks
1771
+ WHERE task_id = ?1
1772
+ AND (?2 IS NULL OR network_id = ?2)`,
1773
+ taskId,
1774
+ expectedNetworkId ?? null,
1775
+ );
1776
+ if (!task?.network_id) return { matched: false };
1777
+ const bindings = db.all<ScheduledTaskBinding>(
1778
+ `SELECT run_id, schedule_id FROM scheduled_task_runs
1779
+ WHERE task_id = ?1 AND network_id = ?2`,
1780
+ task.task_id,
1781
+ task.network_id,
1782
+ );
1783
+ // One task belongs to at most one scheduled occurrence. Fail closed if a
1784
+ // corrupt/legacy database violates that invariant rather than fanning one
1785
+ // lifecycle transition into multiple runs.
1786
+ if (bindings.length !== 1) return { matched: false };
1787
+ const binding = bindings[0];
1788
+
1789
+ if (SCHEDULED_RUN_TERMINAL_STATUSES.has(task.status)) {
1790
+ const errorCode = task.status === "replied" ? null : `task_${task.status}`;
1791
+ const updated = db.run(
1792
+ `UPDATE scheduled_task_runs
1793
+ SET status = ?1,
1794
+ error_code = ?2,
1795
+ error_message = NULL,
1796
+ completed_at = COALESCE(?3, datetime('now'))
1797
+ WHERE run_id = ?4 AND task_id = ?5 AND network_id = ?6 AND schedule_id = ?7`,
1798
+ [task.status, errorCode, task.completed_at, binding.run_id, task.task_id, task.network_id, binding.schedule_id],
1799
+ );
1800
+ return { matched: updated.changes === 1, status: task.status };
1801
+ }
1802
+
1803
+ if (task.status === "delivered") {
1804
+ const updated = db.run(
1805
+ `UPDATE scheduled_task_runs
1806
+ SET status = 'delivered', error_code = NULL, error_message = NULL, completed_at = NULL
1807
+ WHERE run_id = ?1 AND task_id = ?2 AND network_id = ?3 AND schedule_id = ?4`,
1808
+ [binding.run_id, task.task_id, task.network_id, binding.schedule_id],
1809
+ );
1810
+ return { matched: updated.changes === 1, status: task.status };
1811
+ }
1812
+
1813
+ return { matched: false };
1814
+ }
1815
+
1816
+ function taskEventTypeForStatus(toStatus: string): string {
1817
+ switch (toStatus) {
1818
+ case "delivered": return "task.send.delivered";
1819
+ case "acked": return "task.ack";
1820
+ case "running": return "task.started";
1821
+ case "replied": return "task.replied";
1822
+ case "expired": return "task.expired";
1823
+ case "failed":
1824
+ case "cancelled": return "task.failed";
1825
+ default: return `task.status.${toStatus}`;
1826
+ }
1827
+ }
1828
+
1208
1829
  export function logTaskEvent(taskId: string, fromStatus: string | null, toStatus: string, actor: string, detail?: string) {
1209
1830
  try {
1210
1831
  db.run(
1211
- `INSERT INTO task_events (task_id, from_status, to_status, actor, detail, network_id)
1212
- VALUES (?1, ?2, ?3, ?4, ?5, (SELECT network_id FROM tasks WHERE task_id = ?1))`,
1213
- [taskId, fromStatus, toStatus, actor, detail ?? null]
1832
+ `INSERT INTO task_events (task_id, from_status, to_status, event_type, actor, detail, network_id)
1833
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, (SELECT network_id FROM tasks WHERE task_id = ?1))`,
1834
+ [taskId, fromStatus, toStatus, taskEventTypeForStatus(toStatus), actor, detail ?? null]
1214
1835
  );
1215
1836
  } catch {}
1216
1837
  }