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

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