Repository navigation
Expand file tree
/
Copy pathdb.js
More file actions
6726 lines (6327 loc) · 277 KB
/
Copy pathdb.js
File metadata and controls
6726 lines (6327 loc) · 277 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ── Project database (SQLite) ────────────────────────────────────────────────
//
// The single persistence layer for the project's important information: chat
// messages, document records & source text, the PageIndex document index, and
// single-user preferences. Opened with WAL + foreign keys; schema migrations
// are tracked in `schema_migrations` and applied transactionally.
//
// Graceful degradation: if the DB cannot be opened or migrated (missing dir,
// permissions, corrupt file), `dbReady` stays false, a warning is logged, and
// the server continues to start - chat runs in-memory without persistence and
// documents are disabled. This mirrors the project's optional-dependency pattern.
//
// `DB_PATH` overrides the default `data/app.db` location.
import Database from "better-sqlite3";
import { promises as fs } from "node:fs";
import path from "node:path";
import { storeDir } from "./paths.js";
const DEFAULT_DB_PATH = process.env.DB_PATH
? path.resolve(process.env.DB_PATH)
: path.join(storeDir("data"), "app.db");
const INDEX_VERSION = 1; // PageIndex result format version (re-index from source_text if bumped)
let db = null;
let dbReady = false;
// ── Schema migrations ───────────────────────────────────────────────────────
//
// Each migration is a list of SQL statements applied in a single transaction.
// `schema_migrations` itself is bootstrapped by the runner (chicken-and-egg),
// so it does not appear as a numbered migration.
// 迁移链的 head 由数组本身决定(2026-11-10)。测试曾把 head 写成字面量 115,
// 于是每加一条迁移就有六条断言假红——那是「测的是历史快照,不是当前契约」。
// 导出这个常量后,断言可以写「跑到 head」而不必跟着数字改。
// Credentials are encrypted at rest (add-user-supplied-credentials). These are
// the SYNC variants: db.js accessors are synchronous (better-sqlite3), and the
// key is primed once at init. Legacy plaintext rows are read through
// `maybeEncrypted` so the migration needs no backfill.
import {
encryptCredentialSync,
readCredentialMaybeEncryptedSync,
} from "./lib/credential-crypto.js";
const MIGRATIONS = [
{
version: 1,
statements: [
`CREATE TABLE IF NOT EXISTS chat_sessions (
id TEXT PRIMARY KEY,
title TEXT NOT NULL DEFAULT 'New chat',
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
path TEXT
)`,
`CREATE TABLE IF NOT EXISTS chat_messages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
session_id TEXT NOT NULL REFERENCES chat_sessions(id) ON DELETE CASCADE,
role TEXT NOT NULL,
content TEXT NOT NULL,
seq INTEGER NOT NULL,
created_at TEXT NOT NULL
)`,
`CREATE INDEX IF NOT EXISTS idx_chat_messages_session
ON chat_messages(session_id, seq)`,
`CREATE TABLE IF NOT EXISTS documents (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
type TEXT NOT NULL,
status TEXT NOT NULL,
added_at TEXT NOT NULL,
error TEXT,
source_text TEXT
)`,
`CREATE TABLE IF NOT EXISTS doc_index (
doc_id TEXT PRIMARY KEY REFERENCES documents(id) ON DELETE CASCADE,
index_data TEXT NOT NULL,
index_version INTEGER NOT NULL,
updated_at TEXT NOT NULL
)`,
`CREATE TABLE IF NOT EXISTS user_preferences (
key TEXT PRIMARY KEY,
value TEXT NOT NULL,
updated_at TEXT NOT NULL
)`,
],
},
{
version: 2,
statements: [
`CREATE TABLE IF NOT EXISTS collections (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
description TEXT,
created_at TEXT NOT NULL
)`,
`CREATE TABLE IF NOT EXISTS collection_documents (
collection_id TEXT NOT NULL REFERENCES collections(id) ON DELETE CASCADE,
document_id TEXT NOT NULL REFERENCES documents(id) ON DELETE CASCADE,
added_at TEXT NOT NULL,
PRIMARY KEY (collection_id, document_id)
)`,
],
},
{
version: 3,
statements: [
`CREATE TABLE IF NOT EXISTS extension_configs (
id TEXT PRIMARY KEY,
name TEXT NOT NULL UNIQUE,
type TEXT NOT NULL,
config_json TEXT NOT NULL,
enabled INTEGER NOT NULL DEFAULT 1,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL
)`,
`CREATE TABLE IF NOT EXISTS custom_skills (
id TEXT PRIMARY KEY,
name TEXT NOT NULL UNIQUE,
description TEXT,
content TEXT NOT NULL,
enabled INTEGER NOT NULL DEFAULT 1,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL
)`,
],
},
{
version: 4,
statements: [
`ALTER TABLE extension_configs ADD COLUMN source TEXT NOT NULL DEFAULT 'user'`,
],
},
{
version: 5,
// origin: who seeded the row ("bundled" = shipped in the installer via the
// bundle manifest / server startup, "startup" = mcp.json, "user" = API).
// locked: bundled entries the packager forbids deleting/disabling/editing.
// permissions: nullable JSON ({ allow?: string[], deny?: string[] }) — the
// packager-declared tool allow/deny lists (consumed by the follow-up
// extension-tool-permissions change; stored now so seeding can persist it).
// PRAGMA-guarded so the migration stays idempotent on DBs that picked the
// columns up out-of-band (e.g. dev experimentation).
apply: (db) => {
const cols = new Set(
db.prepare("PRAGMA table_info(extension_configs)").all().map((c) => c.name)
);
if (!cols.has("origin"))
db.exec(`ALTER TABLE extension_configs ADD COLUMN origin TEXT NOT NULL DEFAULT 'user'`);
if (!cols.has("locked"))
db.exec(`ALTER TABLE extension_configs ADD COLUMN locked INTEGER NOT NULL DEFAULT 0`);
if (!cols.has("permissions"))
db.exec(`ALTER TABLE extension_configs ADD COLUMN permissions TEXT`);
},
},
{
version: 6,
// Transcript block structure (tool calls with results) as nullable JSON on
// assistant messages, so a reloaded session rebuilds the evidence trail
// instead of flattening it to prose. Rows written before this migration
// have NULL blocks and fall back to the plain-content path.
apply: (db) => {
const cols = new Set(
db.prepare("PRAGMA table_info(chat_messages)").all().map((c) => c.name)
);
if (!cols.has("blocks")) db.exec(`ALTER TABLE chat_messages ADD COLUMN blocks TEXT`);
},
},
{
version: 7,
// Full-fidelity dsh notification log for the /trace viewer. The table moved
// OUT of this database (openspec: bound-trace-storage): trace is
// observational data and now lives in its own `trace.db`, so a session
// index can never be inflated — or a rebuild entangled — by trace volume.
// This migration is retained as a version marker only; databases created
// before the move still carry the table, and `server/trace.js` moves its
// rows into `trace.db` and drops it on first boot.
statements: [],
},
{
version: 8,
// Social chat-platform bots (WeCom / Feishu / Telegram / WeChat OA).
// `secret` is the per-bot random path segment of the webhook URL (it
// defeats bot-id guessing; the platform's own signature check is the real
// verification). `credentials` is server-only JSON — never serialized to
// the browser (the REST layer masks it).
statements: [
`CREATE TABLE IF NOT EXISTS bots (
id TEXT PRIMARY KEY,
type TEXT NOT NULL,
name TEXT NOT NULL,
enabled INTEGER NOT NULL DEFAULT 1,
secret TEXT NOT NULL,
credentials TEXT NOT NULL,
created_at TEXT NOT NULL
)`,
],
},
{
version: 9,
// The dsh agent preset (agent mode) a session STARTED under, recorded at
// session-row creation so a resumed session's header label resolves to the
// composition it actually runs. Nullable: rows written before this
// migration (and blank deployments) read as "the deployment default".
apply: (db) => {
const cols = new Set(
db.prepare("PRAGMA table_info(chat_sessions)").all().map((c) => c.name)
);
if (!cols.has("agent_preset"))
db.exec(`ALTER TABLE chat_sessions ADD COLUMN agent_preset TEXT`);
},
},
{
version: 10,
// The runtime workspace a session ran in, recorded at session-row creation
// so the sidebar can group sessions by workspace. Nullable: rows written
// before this migration surface as the sidebar's "Ungrouped" group, and a
// mid-session workspace switch never re-stamps the row.
apply: (db) => {
const cols = new Set(
db.prepare("PRAGMA table_info(chat_sessions)").all().map((c) => c.name)
);
if (!cols.has("workspace"))
db.exec(`ALTER TABLE chat_sessions ADD COLUMN workspace TEXT`);
},
},
{
version: 11,
// Library search index: chunked document text under FTS5 (bm25 ranking).
// Written in the same logical step as source_text at ingest; rows are
// replaced wholesale per document (delete + insert in one transaction).
// A virtual table cannot carry FK cascades, so document deletion purges
// chunks explicitly in deleteDocument(). Existing rows are backfilled at
// startup by documents-search.js, not by this migration (keep DDL only).
statements: [
`CREATE VIRTUAL TABLE IF NOT EXISTS document_chunks USING fts5(
text,
doc_id UNINDEXED,
name UNINDEXED,
loc UNINDEXED
)`,
],
},
{
version: 12,
statements: [
`CREATE TABLE IF NOT EXISTS user_model_bindings (
email TEXT NOT NULL,
provider_id TEXT NOT NULL,
model_id TEXT NOT NULL,
updated_at TEXT NOT NULL,
PRIMARY KEY (email)
)`,
`CREATE TABLE IF NOT EXISTS user_mcp_bindings (
email TEXT NOT NULL,
name TEXT NOT NULL,
enabled INTEGER NOT NULL CHECK (enabled IN (0, 1)),
updated_at TEXT NOT NULL,
PRIMARY KEY (email, name)
)`,
`CREATE INDEX IF NOT EXISTS idx_user_mcp_bindings_email
ON user_mcp_bindings(email)`,
],
},
{
// Role gating for market-installed MCP entries (add-role-gated-extensions):
// null = ungated; a JSON array of group names required to keep the server
// in the effective runtime profile. Stamped at install time only.
version: 13,
statements: [
`ALTER TABLE extension_configs ADD COLUMN required_groups TEXT`,
],
},
{
// Machine-caller relay (add-bot-relay-endpoint). `bot_chats` records which
// chats have actually talked to each bot — the chat key is otherwise never
// persisted (it is hashed one-way into the dsh session id), so this is the
// only way a destination can be shown or bound. `bot_channels` binds a
// stable name to exactly one (bot, chat_key), which is what a relay caller
// addresses. `bot_relay_log` audits every relay attempt.
//
// No message text in any of the three: the log keeps the length only, and
// the chat record keeps identity and timing only (design D4/D5).
version: 14,
statements: [
`CREATE TABLE IF NOT EXISTS bot_chats (
bot_id TEXT NOT NULL,
chat_key TEXT NOT NULL,
sender_name TEXT,
first_seen_at TEXT NOT NULL,
last_seen_at TEXT NOT NULL,
PRIMARY KEY (bot_id, chat_key)
)`,
`CREATE TABLE IF NOT EXISTS bot_channels (
name TEXT PRIMARY KEY,
bot_id TEXT NOT NULL,
chat_key TEXT NOT NULL,
created_at TEXT NOT NULL
)`,
`CREATE TABLE IF NOT EXISTS bot_relay_log (
ts TEXT NOT NULL,
channel TEXT,
bot_id TEXT,
text_chars INTEGER,
outcome TEXT NOT NULL,
error TEXT
)`,
`CREATE INDEX IF NOT EXISTS idx_bot_relay_log_ts ON bot_relay_log(ts)`,
],
},
{
// registry-sso-credentials: one market-proxy credential per user, minted
// through the registry's silent SSO popup (or pasted by hand). Keyed by
// identity email, never returned to the browser, and referenced from an
// installed registry MCP server as `credentialRef: "registry"` — the
// effective-profile writer resolves that ref to an Authorization header, so
// the token itself never lands in extension_configs.
version: 15,
statements: [
`CREATE TABLE IF NOT EXISTS user_registry_credentials (
email TEXT PRIMARY KEY,
token TEXT NOT NULL,
expires_at TEXT,
stale INTEGER NOT NULL DEFAULT 0,
source TEXT NOT NULL DEFAULT 'sso',
updated_at TEXT NOT NULL
)`,
],
},
{
// resource-library: artifacts produced in chat (openspec: add-resource-library).
// Charts are captured automatically from assistant turns; files are saved
// by explicit user action. `type` + `payload` is the extension seam for
// future kinds — a new type adds rows, never a schema change.
//
// Provenance is a SOFT reference on purpose: session_id/message_id carry
// no foreign key, so deleting a session leaves its resources intact, with
// session_title (a snapshot taken at capture time) as the display fallback.
//
// content_hash is UNIQUE because a resource's identity IS its content:
// regeneration re-emits identical chart specs, and this constraint (plus
// the insert-or-return-existing helper) is what makes that idempotent.
// file_path is relative to the resources root that /api/files serves
// (`root=resources`); payload holds the normalized chart option JSON.
version: 16,
statements: [
`CREATE TABLE IF NOT EXISTS resources (
id TEXT PRIMARY KEY,
type TEXT NOT NULL,
title TEXT NOT NULL,
source TEXT NOT NULL,
session_id TEXT,
session_title TEXT,
message_id INTEGER,
payload TEXT,
file_path TEXT,
file_size INTEGER,
file_mime TEXT,
content_hash TEXT NOT NULL,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
last_seen_at TEXT,
seeded INTEGER NOT NULL DEFAULT 0
)`,
`CREATE UNIQUE INDEX IF NOT EXISTS idx_resources_hash ON resources(content_hash)`,
`CREATE INDEX IF NOT EXISTS idx_resources_type ON resources(type, created_at DESC)`,
],
},
{
// Chart data binding: the binding rows + the resource-side references
// (openspec: add-chart-data-binding). A binding is a data SOURCE, not a
// property of one chart: identity is the content-derived lineage key, so
// two charts over the same call share one row and one observation history.
//
// Additive on purpose — an older build ignores these columns entirely
// (SELECTs name their columns, the new columns are nullable), which is the
// rollback story: drop the routes, keep the tables, charts keep rendering
// their static payload.
//
// binding_refs JSON [{seriesIndex, bindingId}] — one per rendered
// series; a chart with no refs renders its own payload.
// binding_candidates JSON [{name, args, result}] — the same-turn MCP
// calls that produced the chart, retained so the user
// can confirm one later. Results are capped at capture
// (200KB) because this column is per-chart, not global.
version: 17,
statements: [
`CREATE TABLE IF NOT EXISTS chart_bindings (
id TEXT PRIMARY KEY,
lineage_key TEXT NOT NULL,
server TEXT NOT NULL,
tool TEXT NOT NULL,
args TEXT NOT NULL,
map TEXT NOT NULL,
concept TEXT,
frequency TEXT NOT NULL,
unit TEXT,
refresh_rule TEXT,
origin TEXT NOT NULL,
stale INTEGER NOT NULL DEFAULT 0,
stale_reason TEXT,
stale_since TEXT,
last_ok_at TEXT,
consecutive_failures INTEGER NOT NULL DEFAULT 0,
backoff_until TEXT,
gate_fingerprint TEXT,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL
)`,
`CREATE UNIQUE INDEX IF NOT EXISTS idx_chart_bindings_lineage ON chart_bindings(lineage_key)`,
`ALTER TABLE resources ADD COLUMN binding_refs TEXT`,
`ALTER TABLE resources ADD COLUMN binding_candidates TEXT`,
],
},
{
// The bitemporal point store + the refresh log (openspec:
// add-chart-data-binding). Two time axes: `period` is the valid time the
// value is about, `observed_at` the record time we learned it.
//
// chart_point_revisions — append-only truth. `kind` records what each
// observation WAS (appended/revised/resourced/unchanged) because the
// retention sweeper keeps changed rows forever and prunes unchanged
// ones to their first+latest observation; without the kind the
// distinction is unrecoverable.
// chart_series_points — the materialized latest view every render reads,
// written in the same transaction as the revision rows.
// chart_refreshes — what we DID (log, not data): one row per refresh
// attempt with per-classification counts, the gate fingerprint it
// skipped on, and the anomaly detail (both conflicting values).
version: 18,
statements: [
`CREATE TABLE IF NOT EXISTS chart_point_revisions (
binding_id TEXT NOT NULL,
series TEXT NOT NULL,
period TEXT NOT NULL,
value REAL,
source TEXT,
kind TEXT NOT NULL,
observed_at TEXT NOT NULL,
PRIMARY KEY (binding_id, series, period, observed_at)
)`,
`CREATE INDEX IF NOT EXISTS idx_chart_point_revisions_seen ON chart_point_revisions(observed_at)`,
`CREATE TABLE IF NOT EXISTS chart_series_points (
binding_id TEXT NOT NULL,
series TEXT NOT NULL,
period TEXT NOT NULL,
value REAL,
source TEXT,
first_seen_at TEXT NOT NULL,
revision_count INTEGER NOT NULL DEFAULT 1,
updated_at TEXT NOT NULL,
PRIMARY KEY (binding_id, series, period)
)`,
`CREATE TABLE IF NOT EXISTS chart_refreshes (
id TEXT PRIMARY KEY,
binding_id TEXT NOT NULL,
fetched_at TEXT NOT NULL,
trigger TEXT NOT NULL,
outcome TEXT NOT NULL,
added INTEGER NOT NULL DEFAULT 0,
revised INTEGER NOT NULL DEFAULT 0,
resourced INTEGER NOT NULL DEFAULT 0,
unchanged INTEGER NOT NULL DEFAULT 0,
missing INTEGER NOT NULL DEFAULT 0,
anomalies INTEGER NOT NULL DEFAULT 0,
anomalies_detail TEXT,
gate TEXT,
error TEXT,
duration_ms INTEGER
)`,
`CREATE INDEX IF NOT EXISTS idx_chart_refreshes_binding ON chart_refreshes(binding_id, fetched_at DESC)`,
`CREATE INDEX IF NOT EXISTS idx_chart_refreshes_fetched ON chart_refreshes(fetched_at)`,
],
},
{
version: 19,
statements: [
// Deployment-wide key/value config (branding now, future knobs without
// migrations). Same shape as user_preferences, resolved stored→env at read.
`CREATE TABLE IF NOT EXISTS deployment_config (
key TEXT PRIMARY KEY,
value TEXT NOT NULL,
updated_at TEXT NOT NULL
)`,
],
},
{
version: 20,
// Pack marketplace (add-pack-marketplace). All additive: pack ownership of
// custom skills (nullable — user-created and pre-migration rows have none),
// creator drafts, and the cell's installed-pack state (the operational
// truth for what a subscription materialized here, including the version
// snapshot that uninstall and upgrade diff against).
statements: [
`ALTER TABLE custom_skills ADD COLUMN origin_pack_id TEXT`,
`ALTER TABLE custom_skills ADD COLUMN origin_pack_version INTEGER`,
`CREATE TABLE IF NOT EXISTS pack_drafts (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
description TEXT NOT NULL DEFAULT '',
tags TEXT NOT NULL DEFAULT '[]',
entries TEXT NOT NULL DEFAULT '{}',
published_pack_id TEXT,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL
)`,
`CREATE TABLE IF NOT EXISTS installed_packs (
pack_id TEXT PRIMARY KEY,
name TEXT NOT NULL,
version INTEGER NOT NULL,
manifest TEXT NOT NULL,
report TEXT NOT NULL DEFAULT '[]',
installed_at TEXT NOT NULL,
updated_at TEXT NOT NULL
)`,
],
},
{
version: 21,
// Custom presets (add-custom-presets, design D1): the cell's user-composed
// persona presets. One row per preset — indexed rows (not a preferences
// blob) because the catalog source and the management page list them; the
// installed_packs table is the working precedent. ids are server-assigned
// under the reserved `user.` prefix; the row IS the owner (no ownership
// bookkeeping columns).
statements: [
`CREATE TABLE IF NOT EXISTS user_presets (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
persona TEXT NOT NULL,
skills TEXT NOT NULL DEFAULT '[]',
mcp_servers TEXT NOT NULL DEFAULT '[]',
tags TEXT NOT NULL DEFAULT '[]',
icon TEXT,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL
)`,
],
},
{
version: 22,
// Session ownership (add-session-ownership): the email of the authenticated
// user whose connection submitted the session's first user message. Nullable
// by design — auth-off deployments never stamp (single-user semantics), and
// pre-existing rows are backfilled only when SESSION_LEGACY_OWNER names the
// account that owns them (unset ⇒ rows stay NULL, which under auth-on means
// admin-only visibility). The backfill itself is an idempotent boot step,
// not just this migration — see backfillSessionOwners.
apply: (db) => {
const cols = new Set(
db.prepare("PRAGMA table_info(chat_sessions)").all().map((c) => c.name)
);
if (!cols.has("owner")) db.exec(`ALTER TABLE chat_sessions ADD COLUMN owner TEXT`);
db.exec(`CREATE INDEX IF NOT EXISTS idx_chat_sessions_owner ON chat_sessions(owner)`);
},
},
{
version: 23,
// connector-credentials (add-connector-credentials, design D2): the 萬星
// connector's per-user PAT (oct_…, no expiry — revocation is user-driven).
// Same shape as user_registry_credentials but a separate table: the two
// credentials have independent lifecycles (connecting one side must never
// disturb the other), and merging them would force a data migration for
// zero behavioral gain. Referenced from mcp.json's connector server row as
// `credentialRef: "connector"` — the token never lands in any server config.
statements: [
`CREATE TABLE IF NOT EXISTS user_connector_credentials (
email TEXT PRIMARY KEY,
token TEXT NOT NULL,
stale INTEGER NOT NULL DEFAULT 0,
updated_at TEXT NOT NULL
)`,
],
},
{
version: 24,
// pack-usage telemetry (add-pack-usage-telemetry, design D1): one row per
// completed chat turn, for the marketplace's supply feedback (weekly-active
// packs). pack_id is NULL for local personas / custom presets — those turns
// aggregate into their own bucket, never inflating a pack. Kept in the main
// app db (NOT trace.db): 180-day aggregate surface, not a 7-day debug tap.
statements: [
`CREATE TABLE IF NOT EXISTS pack_usage_events (
id INTEGER PRIMARY KEY AUTOINCREMENT,
ts INTEGER NOT NULL,
user_email TEXT,
session_id TEXT NOT NULL,
agent_id TEXT NOT NULL,
pack_id TEXT,
outcome TEXT NOT NULL,
duration_ms INTEGER NOT NULL
)`,
`CREATE INDEX IF NOT EXISTS idx_pack_usage_ts ON pack_usage_events(ts)`,
],
},
{
version: 25,
// add-connector-account-picker D1/D6: one email may hold several connector
// accounts. (email, slot) is the key — slot is the user-readable account
// name (zero-paste names it after the connector identity; paste defaults
// to 'default'). pat_id keeps the connector-side PAT id from the mint
// response so disconnect/replace can best-effort revoke (D7); paste rows
// have none. active marks the one account injected into profiles; exactly
// one per email, maintained transactionally by the store. Old single rows
// migrate to slot='default', active=1 so connected users don't drop.
apply: (db) => {
const cols = new Set(
db.prepare("PRAGMA table_info(user_connector_credentials)").all().map((c) => c.name)
);
if (cols.has("slot")) return; // already rebuilt
db.exec(`CREATE TABLE user_connector_credentials_v25 (
email TEXT NOT NULL,
slot TEXT NOT NULL,
token TEXT NOT NULL,
pat_id TEXT,
stale INTEGER NOT NULL DEFAULT 0,
active INTEGER NOT NULL DEFAULT 0,
updated_at TEXT NOT NULL,
PRIMARY KEY (email, slot)
)`);
db.exec(`INSERT INTO user_connector_credentials_v25 (email, slot, token, pat_id, stale, active, updated_at)
SELECT email, 'default', token, NULL, stale, 1, updated_at FROM user_connector_credentials`);
db.exec(`DROP TABLE user_connector_credentials`);
db.exec(`ALTER TABLE user_connector_credentials_v25 RENAME TO user_connector_credentials`);
},
},
{
version: 26,
// add-session-to-preset: sample prompts captured from a session ride the
// preset (≤3×200 chars, validated in routes/custom-presets.js) and flow
// into the pack draft's serving card at publish. NULL = none authored;
// JSON array like the sibling list columns.
apply: (db) => {
const cols = new Set(db.prepare("PRAGMA table_info(user_presets)").all().map((c) => c.name));
if (cols.has("examples")) return;
db.exec(`ALTER TABLE user_presets ADD COLUMN examples TEXT`);
},
},
{
// add-search-byok: the user's own search-provider key (SerpAPI), used by
// the relay in preference to the shared pool. Same shape as the sibling
// per-user credential tables (registry v15, connector v23) — a separate
// table for the same reason: independent lifecycle, no shared migration.
version: 27,
statements: [
`CREATE TABLE IF NOT EXISTS user_search_credentials (
email TEXT PRIMARY KEY,
token TEXT NOT NULL,
updated_at TEXT NOT NULL
)`,
],
},
{
version: 28,
// facet-market-credentials (add-facet-market-credentials, design D1): the
// market's app tokens live 12h, so what's stored is the DEVICE identity
// (Ed25519 keypair + facet-side account), not a terminal token. token /
// token_exp are the silent-relogin cache (challenge→sign→login); stale
// means the binding was revoked (re-pair required). Referenced from
// mcp.json's facet-market server row as `credentialRef: "facet-market"`.
statements: [
`CREATE TABLE IF NOT EXISTS user_facet_market_devices (
email TEXT PRIMARY KEY,
device_id TEXT NOT NULL,
public_key TEXT NOT NULL,
private_key TEXT NOT NULL,
facet_email TEXT,
stale INTEGER NOT NULL DEFAULT 0,
token TEXT,
token_exp INTEGER,
paired_at TEXT NOT NULL,
updated_at TEXT NOT NULL
)`,
],
},
{
version: 29,
// paper-trading-credentials (add-paper-trading-credentials, design D7):
// one pasted `fdt_` long-lived token per identity — the service has no
// multi-account dimension, so a single slot (token IS the identity). No
// expiry and no re-login: stale is the only invalid state, cleared by
// re-pasting. Referenced from mcp.json's paper-trading server row as
// `credentialRef: "paper-trading"`.
statements: [
`CREATE TABLE IF NOT EXISTS user_paper_trading_credentials (
email TEXT PRIMARY KEY,
token TEXT NOT NULL,
stale INTEGER NOT NULL DEFAULT 0,
updated_at TEXT NOT NULL
)`,
],
},
{
version: 30,
// add-external-skill-install (刀二, design D1): a stored skill becomes a
// directory tree, not a lone SKILL.md.
// files — JSON map {"scripts/x.py": "<text>"} of AUXILIARY files
// only (the SKILL.md body stays in `content`). NULL = the
// pre-existing single-file shape; behavior is byte-identical.
// frontmatter — the upstream frontmatter map (JSON) captured at install;
// materialization re-emits it (name/description overridden
// by the row) so dsh-consumed fields (whenToUse /
// user-invocable / disable-model-invocation / metadata)
// survive. NULL = regenerate the legacy name/description
// header exactly as before.
// origin_meta — external provenance JSON {kind:"external", source, slug,
// originUrl, upstreamName, upstreamVersion}. NULL = locally
// authored or pack-owned.
// All nullable and additive: existing rows migrate losslessly.
statements: [
`ALTER TABLE custom_skills ADD COLUMN files TEXT`,
`ALTER TABLE custom_skills ADD COLUMN frontmatter TEXT`,
`ALTER TABLE custom_skills ADD COLUMN origin_meta TEXT`,
],
},
{
version: 31,
// line-credentials (add-line-credential-refs, design D1): per-line creds —
// wire-customer / lex hold short-lived Logto ID tokens (browser PKCE silent
// mint; aud is each line's own Logto app — upstream verifies),
// wanxing-caller holds a pasted long-lived sk- key. Referenced from
// mcp.json rows as credentialRef: wire-customer | lex | wanxing-caller.
statements: [
`CREATE TABLE IF NOT EXISTS user_line_credentials (
email TEXT NOT NULL,
line TEXT NOT NULL,
token TEXT NOT NULL,
token_exp INTEGER,
stale INTEGER NOT NULL DEFAULT 0,
updated_at TEXT NOT NULL,
PRIMARY KEY (email, line)
)`,
],
},
{
version: 32,
// ciyuan-account-lane (design D4): one 词元 account binding per identity —
// the key minted server-side through the user's 词元 login, plus display
// metadata (never the password or the login token, which are discarded).
statements: [
`CREATE TABLE IF NOT EXISTS user_ciyuan_account (
email TEXT NOT NULL PRIMARY KEY,
token TEXT NOT NULL,
key_id INTEGER,
key_name TEXT,
group_id INTEGER,
ciyuan_email_masked TEXT,
minted_at TEXT NOT NULL,
stale INTEGER NOT NULL DEFAULT 0,
updated_at TEXT NOT NULL
)`,
],
},
{
version: 33,
// full-mode-tool-scope (design D4): a custom preset may narrow each of its
// own MCP references to tool leaf names — JSON {server: [leaf...]}.
// '{}' / NULL = no declaration (the preset inherits the full-mode derived
// scope). Additive and nullable: existing rows migrate losslessly.
statements: [`ALTER TABLE user_presets ADD COLUMN mcp_tools TEXT DEFAULT '{}'`],
},
{
version: 34,
// add-line-boards-and-action-gate: action proposals + audit log.
// action_proposals — pending/approved/rejected/expired actions;
// id (proposalId), line, action_id, args_digest (sha256), args_json (encrypted or plain for execution), risk, target,
// impact_text, proposer_session, proposer_email, approver_email,
// approved_at, expired_at, state ("pending"|"executed"|"rejected"|"expired"),
// result_summary, created_at, updated_at.
// action_audit — executed actions (append-only); same columns plus
// executor_info, duration_ms, error_text.
// Both tables use WAL-friendly design; no FK cascades needed (session/user
// rows are soft-deleted by design; we keep history even if session is gone).
statements: [
`CREATE TABLE IF NOT EXISTS action_proposals (
proposal_id TEXT PRIMARY KEY,
line TEXT NOT NULL,
action_id TEXT NOT NULL,
args_digest TEXT NOT NULL,
args_json TEXT,
risk TEXT NOT NULL,
target TEXT NOT NULL,
impact_text TEXT NOT NULL,
proposer_session TEXT,
proposer_email TEXT,
approver_email TEXT,
approved_at TEXT,
expired_at TEXT,
state TEXT NOT NULL DEFAULT 'pending',
result_summary TEXT,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL
)`,
`CREATE INDEX IF NOT EXISTS idx_action_proposals_line ON action_proposals(line)`,
`CREATE INDEX IF NOT EXISTS idx_action_proposals_state ON action_proposals(state)`,
`CREATE INDEX IF NOT EXISTS idx_action_proposals_created ON action_proposals(created_at DESC)`,
`CREATE TABLE IF NOT EXISTS action_audit (
id INTEGER PRIMARY KEY AUTOINCREMENT,
proposal_id TEXT REFERENCES action_proposals(proposal_id) ON DELETE SET NULL,
line TEXT NOT NULL,
action_id TEXT NOT NULL,
args_digest TEXT NOT NULL,
args_json TEXT,
risk TEXT NOT NULL,
target TEXT NOT NULL,
impact_text TEXT NOT NULL,
executor_info TEXT,
duration_ms INTEGER,
error_text TEXT,
result_summary TEXT NOT NULL,
created_at TEXT NOT NULL
)`,
`CREATE INDEX IF NOT EXISTS idx_action_audit_line ON action_audit(line)`,
`CREATE INDEX IF NOT EXISTS idx_action_audit_created ON action_audit(created_at DESC)`,
],
},
{
version: 35,
// add-crm-desk-pack-embed (task 2.1): per-user Chatwoot BYOK credential —
// the API token (tool face + action execution) plus optional login
// email/password (embed server-side sign-in only). One row per user;
// paste semantics (401 flips stale, re-paste to recover) like the
// connector family. Plaintext at rest matches the line/registry
// credential tables' existing posture (same threat domain, owner-keyed).
statements: [
`CREATE TABLE IF NOT EXISTS user_chatwoot_credentials (
email TEXT PRIMARY KEY,
token TEXT NOT NULL,
login_email TEXT,
login_password TEXT,
stale INTEGER NOT NULL DEFAULT 0,
updated_at TEXT NOT NULL
)`,
],
},
{
// version 100 on purpose: cell ledgers carry their own compacted history
// (old cells sat at 60+), so a low number would collide with an
// already-recorded entry and NEVER run on those cells. 100 is beyond any
// ledger seen in the wild; versions need not be contiguous.
version: 100,
// add-crm-desk-pack-embed task 6.x (SSO): the Chatwoot user id behind the
// stored API token — discovered lazily via /api/v1/profile and cached so
// the platform-API SSO login endpoint can be addressed per user.
//
// Guarded, not a bare ALTER: a cell whose ledger already records v35 can
// still be missing the table (compacted/legacy cell DB — cell
// 2b043ce050ca134c is one: 42 tables at v37, no user_chatwoot_credentials).
// A bare ALTER there throws `no such table`, runMigrations aborts, initDb
// catches and disables the WHOLE database — every feature of that cell,
// not just the Chatwoot one. Recreate the v35 shape, then add the column
// only when it is absent; both steps are no-ops on a healthy database.
apply: (db) => {
db.exec(`CREATE TABLE IF NOT EXISTS user_chatwoot_credentials (
email TEXT PRIMARY KEY,
token TEXT NOT NULL,
login_email TEXT,
login_password TEXT,
stale INTEGER NOT NULL DEFAULT 0,
updated_at TEXT NOT NULL
)`);
const cols = new Set(
db.prepare("PRAGMA table_info(user_chatwoot_credentials)").all().map((c) => c.name)
);
if (!cols.has("chatwoot_user_id")) {
db.exec(`ALTER TABLE user_chatwoot_credentials ADD COLUMN chatwoot_user_id INTEGER`);
}
},
},
{
// fix-gateway-bot-owner: the creator email on the bot row — the gateway's
// webhook router prefers it over session-ownership inference (which is
// arbitrary on cells with mixed sign-in history). Nullable: legacy rows
// fall back to the inference path.
version: 101,
statements: [`ALTER TABLE bots ADD COLUMN owner_email TEXT`],
},
{
// add-line-credential-renewal: the rotating refresh token for ID-token
// lines (wire-customer/lex), minted together with the ID token via
// offline_access and consumed server-side for unattended renewal. NULL =
// no renewal capability (legacy rows, manual pastes); readable only
// through the secret-bearing accessor — never the projection SELECT.
version: 102,
statements: [`ALTER TABLE user_line_credentials ADD COLUMN refresh_token TEXT`],
},
{
// add-agent-config-dims: the two configuration dimensions beyond the model
// (thinking depth, per-turn context budget), declarable per bot. Nullable
// by design — unset = inherit the deployment default = byte-identical to
// before; rollback needs no data migration.
version: 103,
statements: [
`ALTER TABLE bots ADD COLUMN effort TEXT`,
`ALTER TABLE bots ADD COLUMN context_budget INTEGER`,
],
},
{
// add-zhiyu-im-bridge: optional room binding for a bot (`zhiRoomId`, null
// = legacy per-chat agent session, byte-identical) plus the output bridge's
// restart-safe last-sent cursor (`zhiBridgeCursor`, room message seq).
version: 104,
statements: [
`ALTER TABLE bots ADD COLUMN zhi_room_id TEXT`,
`ALTER TABLE bots ADD COLUMN zhi_bridge_cursor INTEGER NOT NULL DEFAULT 0`,
],
},
{
// add-unified-memory-and-outputs: resources carry a denormalized mirror of
// the fd-memory reference page's tier/tags for fast list filtering. Truth
// lives in fd-memory; these columns only ever move via the gesture write
// face — never by direct client writes.
version: 105,
statements: [
`ALTER TABLE resources ADD COLUMN tier TEXT NOT NULL DEFAULT 'draft'`,
`ALTER TABLE resources ADD COLUMN tags TEXT NOT NULL DEFAULT '[]'`,
`ALTER TABLE resources ADD COLUMN memory_ref_path TEXT`,
`ALTER TABLE resources ADD COLUMN tags_origin TEXT NOT NULL DEFAULT ''`,
`ALTER TABLE resources ADD COLUMN tier_origin TEXT NOT NULL DEFAULT ''`,
],
},
{
// add-local-fleet-control-plane: the local roster truth. One row per
// deployed serving agent on THIS machine; the local feed
// (server/local-agent-feed.js) synthesizes registry-shaped entries from
// these rows × the installed pack manifest, so agent-runner needs no
// code change — only a feed pointer. `agent_path` is the stable identity
// across stop/start (stop removes the entry from the feed, keeps the row).
version: 106,
statements: [
`CREATE TABLE IF NOT EXISTS local_fleet_deployments (
agent_path TEXT PRIMARY KEY,
pack_id TEXT NOT NULL,
agent_id TEXT NOT NULL,
enabled INTEGER NOT NULL DEFAULT 1,
config_overrides TEXT,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
UNIQUE (pack_id, agent_id)
)`,
`CREATE INDEX IF NOT EXISTS idx_local_fleet_deployments_pack
ON local_fleet_deployments(pack_id)`,
],
},
{
// add-offline-pack-supply: an installed pack remembers where it came from
// (market | bundle). Historical rows default to 'market' — the only source
// that existed before bundles — so no backfill pass is needed and old
// readers that ignore the column are unaffected.
version: 107,
statements: [
`ALTER TABLE installed_packs ADD COLUMN source TEXT NOT NULL DEFAULT 'market'`,
],
},
{
// add-skill-self-evolution: the candidate store (AI-proposed skills) and
// the lineage column on custom_skills. Candidates live OUTSIDE
// custom_skills on purpose (D1): the materializer mirrors custom_skills
// verbatim, so a status column there would be one missed filter away from
// a candidate going live. Promotion is a one-way write with audit.
// lineage records "superseded by X per eval Y" on the OLD row (never
// delete — 永不删页只 lineage).
version: 109,
statements: [
`CREATE TABLE IF NOT EXISTS skill_candidates (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
description TEXT NOT NULL,
body TEXT NOT NULL,
evidence TEXT NOT NULL,
supersedes TEXT,
status TEXT NOT NULL DEFAULT 'candidate',
eval_report TEXT,
proposed_by TEXT,
created_at TEXT NOT NULL,
decided_at TEXT,
decided_by TEXT
)`,
`CREATE INDEX IF NOT EXISTS idx_skill_candidates_status ON skill_candidates(status)`,
`ALTER TABLE custom_skills ADD COLUMN evolution_lineage TEXT`,
],
},
{
// add-unified-fleet-console: a deployment row remembers WHO established it
// — 'manual' (user action on this machine, wins over cloud desired state)
// or 'cloud' (applied by the desired-state merge, keeps following the
// cloud's desired set until a manual action adopts it). Historical rows
// default to 'manual' — the only source that existed before the merge —
// so no backfill pass is needed and old readers that ignore the column
// are unaffected (same convention as installed_packs.source v107).
version: 108,
statements: [
`ALTER TABLE local_fleet_deployments ADD COLUMN source TEXT NOT NULL DEFAULT 'manual'`,
],
},
{
// add-web-project-container: Project as the web-side top-level container —
// a persisted entity with identity (id + display name), NOT just a
// directory. `projects` carries id/name/backing-path (unique)/owner and