@sleep2agi/commhub-server 0.9.0-preview.5 → 0.9.0-preview.50

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 (128) 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/alias-filter.test.ts +72 -0
  8. package/src/alias-filter.ts +32 -0
  9. package/src/api-host-supervisors-can-create-nodes.test.ts +350 -0
  10. package/src/api-host-supervisors-fallback.test.ts +271 -0
  11. package/src/api-nodes-shape.test.ts +26 -10
  12. package/src/auth-validate.test.ts +5 -1
  13. package/src/auth.ts +93 -14
  14. package/src/avatar-validate.test.ts +163 -0
  15. package/src/avatar-validate.ts +103 -0
  16. package/src/blocked-exit-on-reply.test.ts +122 -0
  17. package/src/boot-side-effect.test.ts +124 -0
  18. package/src/config-apply-sec1.test.ts +107 -0
  19. package/src/config-apply-validate.test.ts +92 -0
  20. package/src/config-apply-validate.ts +81 -3
  21. package/src/create-node-blocked-gate.test.ts +356 -0
  22. package/src/create-node-tool-schema.test.ts +39 -0
  23. package/src/create-node-validate.test.ts +80 -1
  24. package/src/create-node-validate.ts +49 -5
  25. package/src/create-node.ts +51 -1
  26. package/src/dashboard-slash-routing-http.test.ts +107 -0
  27. package/src/db-adapter-guard.test.ts +85 -0
  28. package/src/db-adapter.ts +64 -23
  29. package/src/db-timestamp.test.ts +38 -0
  30. package/src/db-timestamp.ts +15 -0
  31. package/src/db.ts +690 -33
  32. package/src/delivered-without-push.test.ts +140 -0
  33. package/src/desktop-message-seam.test.ts +150 -0
  34. package/src/desktop-message.test.ts +368 -0
  35. package/src/ext-token-shared.test.ts +60 -0
  36. package/src/ext-validation-regression.test.ts +131 -0
  37. package/src/external-schedule-edits-http.test.ts +320 -0
  38. package/src/external-schedule-edits-timestamps.test.ts +64 -0
  39. package/src/external-schedule-edits.ts +327 -0
  40. package/src/file-download-authz-dev-open.test.ts +135 -0
  41. package/src/file-download-authz.test.ts +403 -0
  42. package/src/file-download-date-bucket.test.ts +436 -0
  43. package/src/file-network-scope-dev-open.test.ts +97 -0
  44. package/src/file-network-scope.test.ts +731 -0
  45. package/src/health-redaction.test.ts +641 -0
  46. package/src/hub-timestamp.test.ts +38 -0
  47. package/src/hub-timestamp.ts +27 -0
  48. package/src/inbox-count-sse.test.ts +310 -0
  49. package/src/inbox-count.ts +29 -0
  50. package/src/index.ts +15 -2227
  51. package/src/lifecycle-guard.ts +50 -0
  52. package/src/list-host-supervisors.test.ts +314 -0
  53. package/src/mcp-write-network-resolution.test.ts +429 -0
  54. package/src/network-name-http.test.ts +75 -0
  55. package/src/network-scope.ts +101 -0
  56. package/src/node-attrs-validate.ts +88 -0
  57. package/src/node-attrs.test.ts +217 -0
  58. package/src/node-id-alias.test.ts +188 -0
  59. package/src/node-lifecycle-controllable.test.ts +64 -0
  60. package/src/node-lifecycle-controllable.ts +51 -0
  61. package/src/observer-avatar-http.test.ts +428 -0
  62. package/src/observer-push.test.ts +252 -0
  63. package/src/package-version-consistency.test.ts +25 -0
  64. package/src/peer-reply-atomic.test.ts +455 -0
  65. package/src/peer-reply-capability.test.ts +70 -0
  66. package/src/push.ts +163 -7
  67. package/src/redact-tokens.test.ts +65 -0
  68. package/src/redact-tokens.ts +40 -0
  69. package/src/reply-target-derivation.test.ts +96 -0
  70. package/src/report-status-host-schema.test.ts +211 -0
  71. package/src/report-status-resume-id-handover.test.ts +150 -0
  72. package/src/require-explicit-test-db.ts +9 -0
  73. package/src/resolve-port.test.ts +57 -0
  74. package/src/resolve-port.ts +44 -0
  75. package/src/response-charset.test.ts +130 -0
  76. package/src/rest-explicit-columns-http.test.ts +216 -0
  77. package/src/rest-identity.test.ts +129 -0
  78. package/src/rest-identity.ts +100 -0
  79. package/src/rest-projections.ts +67 -0
  80. package/src/rest-write-network-resolution.test.ts +133 -0
  81. package/src/rules-file-transport.test.ts +235 -0
  82. package/src/runtime-label.test.ts +22 -0
  83. package/src/runtime-label.ts +21 -0
  84. package/src/scheduled-run-terminal.test.ts +268 -0
  85. package/src/scheduled-tasks-http.test.ts +483 -0
  86. package/src/scheduled-tasks.ts +549 -0
  87. package/src/send-reply-agent-warning.test.ts +202 -0
  88. package/src/send-reply-alias-optional.test.ts +131 -0
  89. package/src/send-reply-attachments.test.ts +458 -0
  90. package/src/serve-error.test.ts +38 -0
  91. package/src/serve-error.ts +27 -0
  92. package/src/server.ts +3736 -0
  93. package/src/shared/external-schedule-contract.ts +60 -0
  94. package/src/side-thread-command-transport.test.ts +302 -0
  95. package/src/side-thread-command-transport.ts +318 -0
  96. package/src/side-thread-http-integration.test.ts +233 -0
  97. package/src/side-thread-http.ts +504 -0
  98. package/src/side-thread-production.test.ts +72 -0
  99. package/src/side-thread-production.ts +118 -0
  100. package/src/side-thread.test.ts +1067 -0
  101. package/src/side-thread.ts +2495 -0
  102. package/src/skillhub-http.test.ts +92 -0
  103. package/src/start-node.test.ts +109 -0
  104. package/src/stop-delete-node.test.ts +952 -0
  105. package/src/task-auth-origin-http.test.ts +91 -0
  106. package/src/task-auth-origin.test.ts +24 -0
  107. package/src/task-auth-origin.ts +7 -0
  108. package/src/task-consumption.test.ts +471 -0
  109. package/src/task-diagnostic-http.test.ts +149 -0
  110. package/src/task-diagnostic.test.ts +115 -0
  111. package/src/task-diagnostic.ts +118 -0
  112. package/src/task-idempotency-mcp.test.ts +142 -0
  113. package/src/task-idempotency.test.ts +60 -0
  114. package/src/task-idempotency.ts +75 -0
  115. package/src/task-lifecycle-watcher.test.ts +204 -0
  116. package/src/task-lifecycle-watcher.ts +49 -0
  117. package/src/task-network-resolution-http.test.ts +141 -0
  118. package/src/tasks-pagination-http.test.ts +141 -0
  119. package/src/tools-list-json-schema.test.ts +66 -0
  120. package/src/tools.ts +3026 -197
  121. package/src/update-provider.test.ts +65 -0
  122. package/src/upload-early-reject-guard.test.ts +155 -0
  123. package/src/uploads-http.test.ts +97 -15
  124. package/src/uploads.test.ts +66 -0
  125. package/src/uploads.ts +130 -5
  126. package/src/user-inbox-netid-notnull.test.ts +122 -0
  127. package/src/user-inbox-read-http.test.ts +223 -0
  128. 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,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).
@@ -342,6 +540,37 @@ try {
342
540
  console.warn(`[commhub] partial unique index uniq_ncu_node_inflight skipped: ${e?.message || e}`);
343
541
  }
344
542
 
543
+ // ── app#225: 节点规则文件(AGENTS.md / CLAUDE.md)远程读写请求 ──
544
+ //
545
+ // 形状照抄 node_config_updates(上面):客户端落一行 + 门铃,节点拉走做完回报,
546
+ // 客户端轮询结果。network_id 同样在插入时从 nodes 反规范化。
547
+ //
548
+ // 🔴 这张表**故意没有路径列**:文件名由节点按自己的 RUNTIME 决定
549
+ // (claude → CLAUDE.md,其余 → AGENTS.md),目录固定是节点进程的 cwd。
550
+ // hub 侧只存 op + 内容,客户端连文件名都指定不了(#225 验收第 5 条)。
551
+ // file_name 是节点**回报**的实际文件名,只用于显示。
552
+ db.exec(`
553
+ CREATE TABLE IF NOT EXISTS node_rules_requests (
554
+ request_id TEXT PRIMARY KEY,
555
+ node_id TEXT NOT NULL,
556
+ network_id TEXT NOT NULL,
557
+ op TEXT NOT NULL,
558
+ content TEXT,
559
+ status TEXT NOT NULL,
560
+ file_name TEXT,
561
+ file_exists INTEGER,
562
+ result_content TEXT,
563
+ error TEXT,
564
+ created_at INTEGER NOT NULL,
565
+ created_by_token TEXT NOT NULL,
566
+ pulled_at INTEGER,
567
+ acked_at INTEGER
568
+ );
569
+
570
+ CREATE INDEX IF NOT EXISTS idx_nrr_node_status ON node_rules_requests(node_id, status);
571
+ CREATE INDEX IF NOT EXISTS idx_nrr_network ON node_rules_requests(network_id);
572
+ `);
573
+
345
574
  // ── V3: networks table ──
346
575
  db.exec(`
347
576
  CREATE TABLE IF NOT EXISTS networks (
@@ -387,6 +616,7 @@ for (const ddl of [
387
616
  "ALTER TABLE api_tokens ADD COLUMN request_id TEXT",
388
617
  "ALTER TABLE api_tokens ADD COLUMN revoked_at TEXT",
389
618
  "ALTER TABLE api_tokens ADD COLUMN role TEXT",
619
+ "ALTER TABLE api_tokens ADD COLUMN bound_node_id TEXT",
390
620
  ]) {
391
621
  try { db.exec(ddl); }
392
622
  catch (e: any) {
@@ -395,6 +625,8 @@ for (const ddl of [
395
625
  }
396
626
  try { db.exec(`CREATE INDEX IF NOT EXISTS idx_tokens_request ON api_tokens(request_id)`); }
397
627
  catch (e: any) { /* index may already exist */ void e; }
628
+ try { db.exec(`CREATE INDEX IF NOT EXISTS idx_tokens_bound_node ON api_tokens(bound_node_id)`); }
629
+ catch (e: any) { void e; }
398
630
 
399
631
  // RFC-026 v4 §2.5 + §4.4 — node_create_requests. Metadata only;
400
632
  // env_blob NEVER lives in this table (F1 mint-stream-evict — secret
@@ -411,7 +643,7 @@ db.exec(`
411
643
  child_name TEXT NOT NULL,
412
644
  network_id TEXT NOT NULL,
413
645
  runtime TEXT NOT NULL,
414
- model TEXT NOT NULL,
646
+ model TEXT,
415
647
  flags_json TEXT NOT NULL,
416
648
  env_keys TEXT NOT NULL,
417
649
  status TEXT NOT NULL,
@@ -428,6 +660,138 @@ db.exec(`
428
660
  CREATE INDEX IF NOT EXISTS idx_ncr_network ON node_create_requests(network_id);
429
661
  CREATE INDEX IF NOT EXISTS idx_ncr_child_name ON node_create_requests(child_name);
430
662
  `);
663
+ function migrateNodeCreateRequestsModelNullable() {
664
+ if (db.dialect === "postgres") {
665
+ try { db.exec("ALTER TABLE node_create_requests ALTER COLUMN model DROP NOT NULL"); } catch {}
666
+ return;
667
+ }
668
+
669
+ let needsRebuild = false;
670
+ try {
671
+ const createSql = db.get<{ sql: string }>("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'node_create_requests'");
672
+ needsRebuild = !!createSql?.sql && /\bmodel\s+TEXT\s+NOT\s+NULL\b/i.test(createSql.sql);
673
+ } catch {}
674
+ if (!needsRebuild) return;
675
+
676
+ db.transaction(() => {
677
+ db.exec("DROP TABLE IF EXISTS node_create_requests_migrated");
678
+ db.exec(`
679
+ CREATE TABLE node_create_requests_migrated (
680
+ request_id TEXT PRIMARY KEY,
681
+ daemon_node_id TEXT NOT NULL,
682
+ child_name TEXT NOT NULL,
683
+ network_id TEXT NOT NULL,
684
+ runtime TEXT NOT NULL,
685
+ model TEXT,
686
+ flags_json TEXT NOT NULL,
687
+ env_keys TEXT NOT NULL,
688
+ status TEXT NOT NULL,
689
+ error TEXT,
690
+ child_token_id TEXT,
691
+ created_at INTEGER NOT NULL,
692
+ created_by_token TEXT NOT NULL,
693
+ delivered_at INTEGER,
694
+ acked_at INTEGER,
695
+ child_node_id TEXT
696
+ )
697
+ `);
698
+ db.exec(`
699
+ INSERT INTO node_create_requests_migrated (
700
+ request_id, daemon_node_id, child_name, network_id, runtime, model,
701
+ flags_json, env_keys, status, error, child_token_id, created_at,
702
+ created_by_token, delivered_at, acked_at, child_node_id
703
+ )
704
+ SELECT
705
+ request_id, daemon_node_id, child_name, network_id, runtime, model,
706
+ flags_json, env_keys, status, error, child_token_id, created_at,
707
+ created_by_token, delivered_at, acked_at, child_node_id
708
+ FROM node_create_requests
709
+ `);
710
+ db.exec("DROP TABLE node_create_requests");
711
+ db.exec("ALTER TABLE node_create_requests_migrated RENAME TO node_create_requests");
712
+ });
713
+ }
714
+ migrateNodeCreateRequestsModelNullable();
715
+
716
+ // #1493 — 把 user_inbox.network_id 升到 **schema 级 NOT NULL**(belt-and-suspenders,
717
+ // 叠在 send_desktop_message 的代码级三闸之上:canWrite / `!effectiveNetId` return /
718
+ // getUserNetworkRole,tools.ts)。「不产生 network_id=NULL 孤儿」现是代码级保证 + #1492
719
+ // 三道测试;schema 级约束让**任何**未来绕过那三闸写 NULL 的回归在 INSERT 处直接被
720
+ // 数据库拒(而非产出 scoped-unreadable 的静默孤儿)。
721
+ //
722
+ // SQLite 不能 `ALTER COLUMN ADD NOT NULL` → 建新表→copy→drop→rename(与本文件既有
723
+ // recreate-table 迁移同范式);新库的 CREATE 已直接 NOT NULL,迁移检测到就跳过(幂等)。
724
+ function migrateUserInboxNetworkIdNotNull() {
725
+ if (db.dialect === "postgres") {
726
+ try { db.exec("ALTER TABLE user_inbox ALTER COLUMN network_id SET NOT NULL"); } catch {}
727
+ return;
728
+ }
729
+ let createSql: string | undefined;
730
+ try {
731
+ createSql = db.get<{ sql: string }>("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'user_inbox'")?.sql;
732
+ } catch { return; }
733
+ if (!createSql) return; // 表不存在:上面的 CREATE 已建成 NOT NULL 新表
734
+ if (/network_id\s+TEXT\s+NOT\s+NULL/i.test(createSql)) return; // 已是 NOT NULL → 幂等跳过
735
+
736
+ // 🔴 迁移前守卫:存量若有 network_id IS NULL 行(按代码级三闸理应 0)→ **大声 warn +
737
+ // 跳过迁移**(列暂保持可空),hub 照常启动。fail-safe,不 throw(SDK马 review #1516):
738
+ // · 这条 NOT NULL 是 belt-and-suspenders,代码级三闸(#1492 三测钉着)已挡新 NULL;
739
+ // 为一条冗余保险带让**整个舰队的 hub** boot 期停摆,代价与收益不成比例;
740
+ // · 生产这个 COUNT 没人量过,而 #1493 第一条原则就是"没量过的数不要动手"——只要生产
741
+ // 有一行历史 NULL,throw 就把升级变成停机;
742
+ // · fail-closed 的真正目的(不盲目清空、不 COALESCE 猜网络)用 warn+skip 一样达到。
743
+ // ⚠ 校正:本文件既有迁移(migrateNodeCreateRequestsModelNullable 内部 catch{}+return;
744
+ // migrateSessionsNetworkAliasUnique 全函数 throw 0 次)都**不**在 boot 期打死 hub——
745
+ // "顶层无 try/catch"是真前提,但"所以 throw 符合惯例"是没验的推论(SDK马 量出),撤回。
746
+ // 孤儿行仍有明确运维信号,三闸仍生效;等人工量过、清干净,下次启动幂等判据自动完成迁移。
747
+ const nullCount = db.get<{ n: number }>("SELECT COUNT(*) AS n FROM user_inbox WHERE network_id IS NULL")?.n ?? 0;
748
+ if (nullCount > 0) {
749
+ console.error(
750
+ `[migrate #1493] user_inbox 有 ${nullCount} 行 network_id IS NULL —— 与 send_desktop_message ` +
751
+ `的代码级三闸矛盾,可能存在更早的写路径漏洞;已**跳过** NOT NULL 迁移(列暂保持可空),` +
752
+ `hub 正常启动。请人工排查这些孤儿行来源、清理后下次启动会自动完成迁移(不要盲目清空)。`,
753
+ );
754
+ return;
755
+ }
756
+
757
+ db.transaction(() => {
758
+ db.exec("DROP TABLE IF EXISTS user_inbox_migrated");
759
+ db.exec(`
760
+ CREATE TABLE user_inbox_migrated (
761
+ message_id TEXT PRIMARY KEY,
762
+ network_id TEXT NOT NULL,
763
+ user_id TEXT NOT NULL,
764
+ from_session TEXT,
765
+ kind TEXT NOT NULL DEFAULT 'info',
766
+ title TEXT,
767
+ content TEXT NOT NULL,
768
+ severity TEXT NOT NULL DEFAULT 'info',
769
+ meta_json TEXT,
770
+ acked INTEGER NOT NULL DEFAULT 0,
771
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
772
+ acked_at TEXT
773
+ )
774
+ `);
775
+ db.exec(`
776
+ INSERT INTO user_inbox_migrated
777
+ (message_id, network_id, user_id, from_session, kind, title, content, severity, meta_json, acked, created_at, acked_at)
778
+ SELECT
779
+ message_id, network_id, user_id, from_session, kind, title, content, severity, meta_json, acked, created_at, acked_at
780
+ FROM user_inbox
781
+ `);
782
+ db.exec("DROP TABLE user_inbox");
783
+ db.exec("ALTER TABLE user_inbox_migrated RENAME TO user_inbox");
784
+ });
785
+ }
786
+ migrateUserInboxNetworkIdNotNull();
787
+ // 迁移会 drop 掉旧表上的 idx_user_inbox_user_acked → 重建(IF NOT EXISTS;未迁移时 no-op)。
788
+ db.exec(`CREATE INDEX IF NOT EXISTS idx_user_inbox_user_acked ON user_inbox(user_id, acked, created_at);`);
789
+
790
+ db.exec(`
791
+ CREATE INDEX IF NOT EXISTS idx_ncr_daemon_status ON node_create_requests(daemon_node_id, status);
792
+ CREATE INDEX IF NOT EXISTS idx_ncr_network ON node_create_requests(network_id);
793
+ CREATE INDEX IF NOT EXISTS idx_ncr_child_name ON node_create_requests(child_name);
794
+ `);
431
795
  try {
432
796
  // Single-flight per (daemon, child_name) — prevents racing dashboard
433
797
  // create on same name. Mirrors RFC-024 uniq_ncu_node_inflight.
@@ -526,6 +890,37 @@ db.exec(`
526
890
  CREATE INDEX IF NOT EXISTS idx_audit_network ON audit_log(network_id);
527
891
  `);
528
892
 
893
+ // SkillHub — immutable, network-scoped skill submissions. A (network, slug,
894
+ // version) tuple is write-once: retries with the same content are idempotent,
895
+ // while different content must use a new version. Node submissions remain
896
+ // pending until an owner/admin explicitly publishes them.
897
+ db.exec(`
898
+ CREATE TABLE IF NOT EXISTS skillhub_skills (
899
+ skill_id TEXT PRIMARY KEY,
900
+ network_id TEXT NOT NULL,
901
+ slug TEXT NOT NULL,
902
+ name TEXT NOT NULL,
903
+ description TEXT NOT NULL DEFAULT '',
904
+ version TEXT NOT NULL,
905
+ content TEXT NOT NULL,
906
+ content_hash TEXT NOT NULL,
907
+ status TEXT NOT NULL DEFAULT 'pending' CHECK(status IN ('pending', 'published', 'rejected', 'archived')),
908
+ source_type TEXT NOT NULL CHECK(source_type IN ('node', 'user')),
909
+ source_alias TEXT,
910
+ created_by_user TEXT,
911
+ reviewed_by_user TEXT,
912
+ review_note TEXT,
913
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
914
+ updated_at TEXT NOT NULL DEFAULT (datetime('now')),
915
+ reviewed_at TEXT,
916
+ UNIQUE(network_id, slug, version)
917
+ );
918
+ CREATE INDEX IF NOT EXISTS idx_skillhub_network_status
919
+ ON skillhub_skills(network_id, status, updated_at DESC);
920
+ CREATE INDEX IF NOT EXISTS idx_skillhub_network_slug
921
+ ON skillhub_skills(network_id, slug, version);
922
+ `);
923
+
529
924
  // ── V3: licenses table ──
530
925
  db.exec(`
531
926
  CREATE TABLE IF NOT EXISTS licenses (
@@ -636,6 +1031,14 @@ for (const table of ["sessions", "nodes", "tasks", "inbox", "task_events", "comp
636
1031
  try { db.exec(`ALTER TABLE ${table} ADD COLUMN network_id TEXT`); } catch {}
637
1032
  }
638
1033
 
1034
+ // #167 — stable lifecycle event names plus an internal idempotency key.
1035
+ // Ordinary status transitions keep event_key NULL, so retries and repeated
1036
+ // transitions remain auditable. Watcher warnings set a stable key; the unique
1037
+ // index makes every (task, threshold) write-once across patrol rounds/workers.
1038
+ try { db.exec("ALTER TABLE task_events ADD COLUMN event_type TEXT"); } catch {}
1039
+ try { db.exec("ALTER TABLE task_events ADD COLUMN event_key TEXT"); } catch {}
1040
+ try { db.exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_task_events_task_key ON task_events(task_id, event_key)"); } catch {}
1041
+
639
1042
  // PR-1 (#146): durable node identity on historical inbox/tasks rows. Some
640
1043
  // existing databases created `tasks` before from_node_id/to_node_id were in the
641
1044
  // CREATE TABLE statement, so keep these ALTERs explicit and idempotent.
@@ -922,6 +1325,172 @@ try { db.exec("CREATE INDEX IF NOT EXISTS idx_completions_network ON completions
922
1325
  // the reply up the chain via parent_task_id.
923
1326
  try { db.exec("ALTER TABLE tasks ADD COLUMN parent_task_id TEXT"); } catch {}
924
1327
  try { db.exec("ALTER TABLE tasks ADD COLUMN meta_json TEXT"); } catch {}
1328
+ // #520 — two monotonic evidence levels for this exact task:
1329
+ // runtime_submitted_at means agent-node handed the body to the vendor runtime;
1330
+ // consumed_at requires an attributable turn-start/first-activity signal.
1331
+ // Both stay separate from delivered_at (enqueue), acked (process receipt), and
1332
+ // started_at (legacy report_status/content matching). Old binaries ignore them.
1333
+ try { db.exec("ALTER TABLE tasks ADD COLUMN runtime_submitted_at TEXT"); } catch {}
1334
+ try { db.exec("ALTER TABLE tasks ADD COLUMN consumed_at TEXT"); } catch {}
1335
+ // Exact vendor-runtime boundary for SideThread-capable clients. These values
1336
+ // are written only by the token-bound target node after attributable runtime
1337
+ // evidence; the Hub never derives them from task text or caller input.
1338
+ try { db.exec("ALTER TABLE tasks ADD COLUMN thread_id TEXT"); } catch {}
1339
+ try { db.exec("ALTER TABLE tasks ADD COLUMN turn_id TEXT"); } catch {}
1340
+
1341
+ // #1181 durable outbound terminal cursor. A task's created_at cannot be used
1342
+ // as a recovery watermark because an old task may become terminal after newer
1343
+ // tasks. Record terminal transitions in their own monotonically increasing
1344
+ // journal instead. The journal is append-only for a logical task; retry keeps
1345
+ // the existing task identity and therefore the same idempotency domain.
1346
+ db.exec(`
1347
+ CREATE TABLE IF NOT EXISTS task_terminal_events (
1348
+ terminal_seq INTEGER PRIMARY KEY AUTOINCREMENT,
1349
+ task_id TEXT NOT NULL UNIQUE,
1350
+ network_id TEXT,
1351
+ from_node_id TEXT,
1352
+ completed_at TEXT NOT NULL DEFAULT (datetime('now'))
1353
+ );
1354
+ CREATE INDEX IF NOT EXISTS idx_task_terminal_events_sender_seq
1355
+ ON task_terminal_events(network_id, from_node_id, terminal_seq);
1356
+ `);
1357
+ if (db.dialect === "sqlite") {
1358
+ db.exec(`
1359
+ CREATE TRIGGER IF NOT EXISTS tasks_terminal_event_insert
1360
+ AFTER INSERT ON tasks
1361
+ WHEN NEW.status IN ('replied', 'failed', 'cancelled', 'expired')
1362
+ BEGIN
1363
+ INSERT OR IGNORE INTO task_terminal_events (task_id, network_id, from_node_id, completed_at)
1364
+ VALUES (NEW.task_id, NEW.network_id, NEW.from_node_id, COALESCE(NEW.completed_at, datetime('now')));
1365
+ END;
1366
+ CREATE TRIGGER IF NOT EXISTS tasks_terminal_event_update
1367
+ AFTER UPDATE OF status ON tasks
1368
+ WHEN NEW.status IN ('replied', 'failed', 'cancelled', 'expired')
1369
+ AND OLD.status NOT IN ('replied', 'failed', 'cancelled', 'expired')
1370
+ BEGIN
1371
+ INSERT OR IGNORE INTO task_terminal_events (task_id, network_id, from_node_id, completed_at)
1372
+ VALUES (NEW.task_id, NEW.network_id, NEW.from_node_id, COALESCE(NEW.completed_at, datetime('now')));
1373
+ END;
1374
+ `);
1375
+ db.run(`INSERT OR IGNORE INTO task_terminal_events (task_id, network_id, from_node_id, completed_at)
1376
+ SELECT task_id, network_id, from_node_id, COALESCE(completed_at, created_at)
1377
+ FROM tasks
1378
+ WHERE status IN ('replied', 'failed', 'cancelled', 'expired')
1379
+ ORDER BY COALESCE(completed_at, created_at), task_id`);
1380
+ } else {
1381
+ db.exec(`
1382
+ CREATE OR REPLACE FUNCTION record_task_terminal_event() RETURNS trigger AS $$
1383
+ BEGIN
1384
+ IF NEW.status IN ('replied', 'failed', 'cancelled', 'expired')
1385
+ AND (TG_OP = 'INSERT' OR OLD.status NOT IN ('replied', 'failed', 'cancelled', 'expired')) THEN
1386
+ INSERT INTO task_terminal_events (task_id, network_id, from_node_id, completed_at)
1387
+ VALUES (NEW.task_id, NEW.network_id, NEW.from_node_id, COALESCE(NEW.completed_at, NOW()))
1388
+ ON CONFLICT (task_id) DO NOTHING;
1389
+ END IF;
1390
+ RETURN NEW;
1391
+ END;
1392
+ $$ LANGUAGE plpgsql;
1393
+ DROP TRIGGER IF EXISTS tasks_terminal_event_insert ON tasks;
1394
+ DROP TRIGGER IF EXISTS tasks_terminal_event_update ON tasks;
1395
+ CREATE TRIGGER tasks_terminal_event_insert AFTER INSERT ON tasks
1396
+ FOR EACH ROW EXECUTE FUNCTION record_task_terminal_event();
1397
+ CREATE TRIGGER tasks_terminal_event_update AFTER UPDATE OF status ON tasks
1398
+ FOR EACH ROW EXECUTE FUNCTION record_task_terminal_event();
1399
+ INSERT INTO task_terminal_events (task_id, network_id, from_node_id, completed_at)
1400
+ SELECT task_id, network_id, from_node_id, COALESCE(completed_at, created_at)
1401
+ FROM tasks WHERE status IN ('replied', 'failed', 'cancelled', 'expired')
1402
+ ON CONFLICT (task_id) DO NOTHING;
1403
+ `);
1404
+ }
1405
+
1406
+ // ── Hub scheduled tasks ──────────────────────────────────────────────
1407
+ // Scheduling is a Hub concern: clients manage these rows, while agents only
1408
+ // receive the ordinary inbox/tasks rows produced for each occurrence. Keep
1409
+ // the occurrence table separate so retries, skips and failures remain
1410
+ // auditable without overloading the task lifecycle.
1411
+ db.exec(`
1412
+ CREATE TABLE IF NOT EXISTS scheduled_tasks (
1413
+ schedule_id TEXT PRIMARY KEY,
1414
+ network_id TEXT NOT NULL,
1415
+ created_by TEXT,
1416
+ name TEXT NOT NULL,
1417
+ target_node_id TEXT NOT NULL,
1418
+ target_alias TEXT NOT NULL,
1419
+ task_content TEXT NOT NULL,
1420
+ priority TEXT NOT NULL DEFAULT 'normal',
1421
+ schedule_type TEXT NOT NULL,
1422
+ schedule_json TEXT NOT NULL,
1423
+ timezone TEXT NOT NULL DEFAULT 'UTC',
1424
+ overlap_policy TEXT NOT NULL DEFAULT 'skip',
1425
+ misfire_policy TEXT NOT NULL DEFAULT 'catch_up_once',
1426
+ status TEXT NOT NULL DEFAULT 'active',
1427
+ next_run_at TEXT,
1428
+ last_run_at TEXT,
1429
+ revision INTEGER NOT NULL DEFAULT 1,
1430
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
1431
+ updated_at TEXT NOT NULL DEFAULT (datetime('now'))
1432
+ );
1433
+
1434
+ CREATE INDEX IF NOT EXISTS idx_scheduled_tasks_due
1435
+ ON scheduled_tasks(status, next_run_at);
1436
+ CREATE INDEX IF NOT EXISTS idx_scheduled_tasks_network
1437
+ ON scheduled_tasks(network_id, updated_at DESC);
1438
+ CREATE INDEX IF NOT EXISTS idx_scheduled_tasks_target
1439
+ ON scheduled_tasks(network_id, target_node_id);
1440
+
1441
+ CREATE TABLE IF NOT EXISTS scheduled_task_runs (
1442
+ run_id TEXT PRIMARY KEY,
1443
+ schedule_id TEXT NOT NULL,
1444
+ network_id TEXT NOT NULL,
1445
+ scheduled_for TEXT NOT NULL,
1446
+ task_id TEXT,
1447
+ status TEXT NOT NULL,
1448
+ error_code TEXT,
1449
+ error_message TEXT,
1450
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
1451
+ completed_at TEXT,
1452
+ UNIQUE(schedule_id, scheduled_for)
1453
+ );
1454
+
1455
+ CREATE INDEX IF NOT EXISTS idx_scheduled_runs_schedule
1456
+ ON scheduled_task_runs(schedule_id, created_at DESC);
1457
+ CREATE INDEX IF NOT EXISTS idx_scheduled_runs_network
1458
+ ON scheduled_task_runs(network_id, created_at DESC);
1459
+ `);
1460
+ try { db.exec("ALTER TABLE scheduled_tasks ADD COLUMN misfire_policy TEXT NOT NULL DEFAULT 'catch_up_once'"); } catch {}
1461
+
1462
+ // RFC-036 / B4 — owner-authorized edits of node-host managed schedules.
1463
+ // This is intentionally separate from Hub scheduled_tasks: these rows are
1464
+ // one-shot control intents consumed by the exact token-bound node. The partial
1465
+ // unique index makes the single-flight promise survive multiple Hub workers.
1466
+ db.exec(`
1467
+ CREATE TABLE IF NOT EXISTS external_schedule_edits (
1468
+ intent_id TEXT PRIMARY KEY,
1469
+ network_id TEXT NOT NULL,
1470
+ node_id TEXT NOT NULL,
1471
+ schedule_id TEXT NOT NULL,
1472
+ base_revision INTEGER NOT NULL,
1473
+ patch_json TEXT NOT NULL,
1474
+ status TEXT NOT NULL DEFAULT 'pending',
1475
+ expires_at INTEGER NOT NULL,
1476
+ created_at INTEGER NOT NULL,
1477
+ delivered_at INTEGER,
1478
+ acked_at INTEGER,
1479
+ created_by_user TEXT NOT NULL,
1480
+ created_by_token TEXT NOT NULL,
1481
+ consumed_by_token TEXT,
1482
+ result_revision INTEGER,
1483
+ error_code TEXT
1484
+ );
1485
+
1486
+ CREATE INDEX IF NOT EXISTS idx_external_schedule_edits_node
1487
+ ON external_schedule_edits(network_id, node_id, status, created_at);
1488
+ CREATE INDEX IF NOT EXISTS idx_external_schedule_edits_owner
1489
+ ON external_schedule_edits(created_by_user, created_at DESC);
1490
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_external_schedule_edits_singleflight
1491
+ ON external_schedule_edits(node_id, schedule_id)
1492
+ WHERE status IN ('pending', 'delivered');
1493
+ `);
925
1494
  try { db.exec("CREATE INDEX IF NOT EXISTS idx_tasks_parent ON tasks(parent_task_id)"); } catch {}
926
1495
 
927
1496
  // Helpers
@@ -1230,38 +1799,40 @@ export function chainReplyToParent(
1230
1799
  const marker = `\n\n[via ${childAlias} 子任务结果]\n${currentReply}`;
1231
1800
  const newResult = parent.result ? parent.result + marker : `[via ${childAlias} 子任务结果]\n${currentReply}`;
1232
1801
 
1233
- // Bump parent status to replied if still open. If it was already replied
1234
- // (e.g. 指挥室 sent an early status update), we still want to update the
1235
- // result so the dashboard can render the final chained answer — but keep
1236
- // status as replied (it was already terminal).
1237
- if (parent.status === "delivered" || parent.status === "acked" || parent.status === "running" || parent.status === "created") {
1238
- db.run(
1239
- "UPDATE tasks SET status = ?1, result = ?2, completed_at = datetime('now') WHERE task_id = ?3",
1240
- [replyStatus, newResult.slice(0, 8000), parent.task_id]
1241
- );
1242
- logTaskEvent(parent.task_id, parent.status, replyStatus, "auto-chain", `from ${childAlias}`);
1243
- } else {
1244
- db.run(
1245
- "UPDATE tasks SET result = ?1, completed_at = datetime('now') WHERE task_id = ?2",
1246
- [newResult.slice(0, 8000), parent.task_id]
1247
- );
1248
- logTaskEvent(parent.task_id, parent.status, parent.status, "auto-chain-append", `from ${childAlias}`);
1249
- }
1250
-
1251
- if (parent.from_name && parent.from_name !== "hub" && parent.from_name !== "api") {
1252
- try {
1253
- const notifyId = `chain_${crypto.randomUUID().replace(/-/g, "").slice(0, 16)}`;
1254
- const notifyNode = db.get<{ node_id: string | null }>(
1255
- "SELECT node_id FROM sessions WHERE alias = ?1 AND COALESCE(network_id, 'default') = COALESCE(?2, 'default') ORDER BY updated_at DESC LIMIT 1",
1256
- [parent.from_name, parent.network_id ?? null]
1802
+ db.transaction(() => {
1803
+ // Bump parent status to replied if still open. The task transition and
1804
+ // its scheduler-run mirror share this transaction, so a crash cannot
1805
+ // leave one terminal while the other remains delivered.
1806
+ if (parent.status === "delivered" || parent.status === "acked" || parent.status === "running" || parent.status === "created") {
1807
+ db.run(
1808
+ "UPDATE tasks SET status = ?1, result = ?2, completed_at = datetime('now') WHERE task_id = ?3",
1809
+ [replyStatus, newResult.slice(0, 8000), parent.task_id]
1257
1810
  );
1811
+ syncScheduledRunForTask(parent.task_id, parent.network_id);
1812
+ logTaskEvent(parent.task_id, parent.status, replyStatus, "auto-chain", `from ${childAlias}`);
1813
+ } else {
1258
1814
  db.run(
1259
- `INSERT INTO inbox (id, session_name, node_id, type, priority, content, from_session, in_reply_to, requires_response, network_id)
1260
- VALUES (?1, ?2, ?3, 'reply', 'normal', ?4, ?5, ?6, 'none', ?7)`,
1261
- [notifyId, parent.from_name, notifyNode?.node_id ?? null, `[${childAlias} 子任务完成]\n${currentReply.slice(0, 4000)}`, parent.to_name, parent.task_id, parent.network_id ?? null]
1815
+ "UPDATE tasks SET result = ?1, completed_at = datetime('now') WHERE task_id = ?2",
1816
+ [newResult.slice(0, 8000), parent.task_id]
1262
1817
  );
1263
- } catch {}
1264
- }
1818
+ logTaskEvent(parent.task_id, parent.status, parent.status, "auto-chain-append", `from ${childAlias}`);
1819
+ }
1820
+
1821
+ if (parent.from_name && parent.from_name !== "hub" && parent.from_name !== "api") {
1822
+ try {
1823
+ const notifyId = `chain_${crypto.randomUUID().replace(/-/g, "").slice(0, 16)}`;
1824
+ const notifyNode = db.get<{ node_id: string | null }>(
1825
+ "SELECT node_id FROM sessions WHERE alias = ?1 AND COALESCE(network_id, 'default') = COALESCE(?2, 'default') ORDER BY updated_at DESC LIMIT 1",
1826
+ [parent.from_name, parent.network_id ?? null]
1827
+ );
1828
+ db.run(
1829
+ `INSERT INTO inbox (id, session_name, node_id, type, priority, content, from_session, in_reply_to, requires_response, network_id)
1830
+ VALUES (?1, ?2, ?3, 'reply', 'normal', ?4, ?5, ?6, 'none', ?7)`,
1831
+ [notifyId, parent.from_name, notifyNode?.node_id ?? null, `[${childAlias} 子任务完成]\n${currentReply.slice(0, 4000)}`, parent.to_name, parent.task_id, parent.network_id ?? null]
1832
+ );
1833
+ } catch {}
1834
+ }
1835
+ });
1265
1836
 
1266
1837
  // This iteration actually wrote a parent row (and possibly an
1267
1838
  // inbox notification). Record that so the caller can gate its
@@ -1275,12 +1846,98 @@ export function chainReplyToParent(
1275
1846
  return { chained };
1276
1847
  }
1277
1848
 
1849
+ const SCHEDULED_RUN_TERMINAL_STATUSES = new Set(["replied", "failed", "cancelled", "expired"]);
1850
+
1851
+ type ScheduledTaskLifecycleRow = {
1852
+ task_id: string;
1853
+ network_id: string | null;
1854
+ status: string;
1855
+ completed_at: string | null;
1856
+ };
1857
+
1858
+ type ScheduledTaskBinding = { run_id: string; schedule_id: string };
1859
+
1860
+ /**
1861
+ * Mirror an exact scheduler-created task's lifecycle into its run row.
1862
+ *
1863
+ * The status is always read back from `tasks`; callers cannot supply one.
1864
+ * The scheduler's storage binding is the four-part tuple
1865
+ * (run_id, schedule_id, task_id, network_id). It is read from
1866
+ * `scheduled_task_runs`, not caller-controlled task metadata (which may also
1867
+ * legitimately be replaced by reply attachment metadata).
1868
+ *
1869
+ * Terminal states close the run. `retry_task` calls this after resetting the
1870
+ * same logical task_id to delivered, which deliberately reopens that run so
1871
+ * the history reflects the current retry rather than the first failed attempt.
1872
+ */
1873
+ export function syncScheduledRunForTask(taskId: string, expectedNetworkId?: string | null): { matched: boolean; status?: string } {
1874
+ const task = db.get<ScheduledTaskLifecycleRow>(
1875
+ `SELECT task_id, network_id, status, completed_at
1876
+ FROM tasks
1877
+ WHERE task_id = ?1
1878
+ AND (?2 IS NULL OR network_id = ?2)`,
1879
+ taskId,
1880
+ expectedNetworkId ?? null,
1881
+ );
1882
+ if (!task?.network_id) return { matched: false };
1883
+ const bindings = db.all<ScheduledTaskBinding>(
1884
+ `SELECT run_id, schedule_id FROM scheduled_task_runs
1885
+ WHERE task_id = ?1 AND network_id = ?2`,
1886
+ task.task_id,
1887
+ task.network_id,
1888
+ );
1889
+ // One task belongs to at most one scheduled occurrence. Fail closed if a
1890
+ // corrupt/legacy database violates that invariant rather than fanning one
1891
+ // lifecycle transition into multiple runs.
1892
+ if (bindings.length !== 1) return { matched: false };
1893
+ const binding = bindings[0];
1894
+
1895
+ if (SCHEDULED_RUN_TERMINAL_STATUSES.has(task.status)) {
1896
+ const errorCode = task.status === "replied" ? null : `task_${task.status}`;
1897
+ const updated = db.run(
1898
+ `UPDATE scheduled_task_runs
1899
+ SET status = ?1,
1900
+ error_code = ?2,
1901
+ error_message = NULL,
1902
+ completed_at = COALESCE(?3, datetime('now'))
1903
+ WHERE run_id = ?4 AND task_id = ?5 AND network_id = ?6 AND schedule_id = ?7`,
1904
+ [task.status, errorCode, task.completed_at, binding.run_id, task.task_id, task.network_id, binding.schedule_id],
1905
+ );
1906
+ return { matched: updated.changes === 1, status: task.status };
1907
+ }
1908
+
1909
+ if (task.status === "delivered") {
1910
+ const updated = db.run(
1911
+ `UPDATE scheduled_task_runs
1912
+ SET status = 'delivered', error_code = NULL, error_message = NULL, completed_at = NULL
1913
+ WHERE run_id = ?1 AND task_id = ?2 AND network_id = ?3 AND schedule_id = ?4`,
1914
+ [binding.run_id, task.task_id, task.network_id, binding.schedule_id],
1915
+ );
1916
+ return { matched: updated.changes === 1, status: task.status };
1917
+ }
1918
+
1919
+ return { matched: false };
1920
+ }
1921
+
1922
+ function taskEventTypeForStatus(toStatus: string): string {
1923
+ switch (toStatus) {
1924
+ case "delivered": return "task.send.delivered";
1925
+ case "acked": return "task.ack";
1926
+ case "running": return "task.started";
1927
+ case "replied": return "task.replied";
1928
+ case "expired": return "task.expired";
1929
+ case "failed":
1930
+ case "cancelled": return "task.failed";
1931
+ default: return `task.status.${toStatus}`;
1932
+ }
1933
+ }
1934
+
1278
1935
  export function logTaskEvent(taskId: string, fromStatus: string | null, toStatus: string, actor: string, detail?: string) {
1279
1936
  try {
1280
1937
  db.run(
1281
- `INSERT INTO task_events (task_id, from_status, to_status, actor, detail, network_id)
1282
- VALUES (?1, ?2, ?3, ?4, ?5, (SELECT network_id FROM tasks WHERE task_id = ?1))`,
1283
- [taskId, fromStatus, toStatus, actor, detail ?? null]
1938
+ `INSERT INTO task_events (task_id, from_status, to_status, event_type, actor, detail, network_id)
1939
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, (SELECT network_id FROM tasks WHERE task_id = ?1))`,
1940
+ [taskId, fromStatus, toStatus, taskEventTypeForStatus(toStatus), actor, detail ?? null]
1284
1941
  );
1285
1942
  } catch {}
1286
1943
  }