File size: 28,604 Bytes
be59b3a
 
 
8eaad14
 
 
be59b3a
 
 
 
 
 
 
 
 
 
8eaad14
be59b3a
 
 
 
a57411f
be59b3a
 
 
8eaad14
 
be59b3a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d13ebb9
 
 
 
 
 
 
 
 
 
 
 
 
 
be59b3a
0039ed6
8eaad14
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0039ed6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
be59b3a
 
 
8eaad14
be59b3a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8eaad14
d13ebb9
 
 
 
 
 
 
 
 
 
 
 
 
be59b3a
0039ed6
 
 
 
 
 
 
be59b3a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a57411f
 
 
 
be59b3a
 
 
 
 
 
 
 
 
 
 
 
8eaad14
be59b3a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d13ebb9
 
 
 
 
 
be59b3a
 
 
 
 
 
 
d13ebb9
 
 
 
 
 
be59b3a
 
 
 
d13ebb9
 
 
 
 
 
 
 
be59b3a
 
d13ebb9
 
 
 
 
be59b3a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d13ebb9
be59b3a
 
 
 
dff6fcd
 
 
 
0039ed6
 
8eaad14
dff6fcd
 
8eaad14
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0039ed6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dff6fcd
8eaad14
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
190fb26
 
 
 
 
 
 
 
8eaad14
 
 
 
 
 
190fb26
8eaad14
 
190fb26
 
8eaad14
 
 
 
 
190fb26
 
 
8eaad14
 
 
 
 
 
190fb26
 
 
 
 
 
 
8eaad14
 
 
190fb26
 
8eaad14
 
be59b3a
8eaad14
 
190fb26
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
"""
persistent_db.py
────────────────
Unified persistence layer supporting both PostgreSQL and SQLite.
If `DATABASE_URL` or `POSTGRES_URL` is set, PostgreSQL is used for durability across
restarts/deployments. Otherwise, it gracefully falls back to local SQLite.
"""

import os
import json
import sqlite3
import threading
import time
import uuid
from contextlib import contextmanager
from typing import Any, Dict, List, Optional
from utils.logger import app_logger

# ── paths ──────────────────────────────────────────────────────────────────
_THIS_DIR = os.path.dirname(os.path.abspath(__file__))
_APP_DIR = os.path.dirname(_THIS_DIR)
DATA_DIR = "/data" if (os.path.exists("/data") and os.access("/data", os.W_OK)) else os.path.join(_APP_DIR, "data")
DB_PATH = os.path.join(DATA_DIR, "memory.db")
os.makedirs(DATA_DIR, exist_ok=True)

# ── SQLite schema ───────────────────────────────────────────────────────────
_SQLITE_DDL = """
PRAGMA journal_mode=WAL;
PRAGMA foreign_keys=ON;

CREATE TABLE IF NOT EXISTS chats (
    chat_id     TEXT PRIMARY KEY,
    title       TEXT,
    doc_id      TEXT,
    doc_name    TEXT,
    created_at  REAL NOT NULL,
    updated_at  REAL NOT NULL
);

CREATE TABLE IF NOT EXISTS messages (
    id          INTEGER PRIMARY KEY AUTOINCREMENT,
    chat_id     TEXT NOT NULL REFERENCES chats(chat_id) ON DELETE CASCADE,
    role        TEXT NOT NULL CHECK(role IN ('user','assistant','system')),
    content     TEXT NOT NULL,
    created_at  REAL NOT NULL
);

CREATE INDEX IF NOT EXISTS idx_messages_chat ON messages(chat_id, created_at);

CREATE TABLE IF NOT EXISTS doc_meta (
    doc_id          TEXT PRIMARY KEY,
    filename        TEXT,
    status          TEXT,
    page_count      INTEGER DEFAULT 0,
    section_count   INTEGER DEFAULT 0,
    progress        INTEGER DEFAULT 0,
    current_stage   TEXT DEFAULT 'uploaded',
    indexing_method TEXT,
    duration        REAL,
    error           TEXT,
    content_hash    TEXT,
    file_path       TEXT,
    created_at      REAL NOT NULL,
    updated_at      REAL NOT NULL
);

CREATE INDEX IF NOT EXISTS idx_doc_meta_hash ON doc_meta(content_hash);

CREATE TABLE IF NOT EXISTS doc_indices (
    doc_id          TEXT PRIMARY KEY REFERENCES doc_meta(doc_id) ON DELETE CASCADE,
    content_hash    TEXT,
    tree            TEXT,
    node_map        TEXT,
    flat_sections   TEXT,
    file_base64     TEXT,
    created_at      REAL NOT NULL,
    updated_at      REAL NOT NULL
);

CREATE INDEX IF NOT EXISTS idx_doc_indices_hash ON doc_indices(content_hash);

CREATE TABLE IF NOT EXISTS chat_documents (
    chat_id     TEXT NOT NULL REFERENCES chats(chat_id) ON DELETE CASCADE,
    doc_id      TEXT NOT NULL REFERENCES doc_meta(doc_id) ON DELETE CASCADE,
    doc_name    TEXT,
    attached_at REAL NOT NULL,
    PRIMARY KEY (chat_id, doc_id)
);
CREATE INDEX IF NOT EXISTS idx_chat_docs ON chat_documents(chat_id);

CREATE TABLE IF NOT EXISTS chat_summaries (
    chat_id     TEXT PRIMARY KEY REFERENCES chats(chat_id) ON DELETE CASCADE,
    summary     TEXT NOT NULL,
    turn_count  INTEGER DEFAULT 0,
    updated_at  REAL NOT NULL
);

CREATE TABLE IF NOT EXISTS knowledge_memory (
    doc_id            TEXT PRIMARY KEY REFERENCES doc_meta(doc_id) ON DELETE CASCADE,
    filename          TEXT NOT NULL,
    executive_summary TEXT,
    key_entities      TEXT,
    key_findings      TEXT,
    topics            TEXT,
    updated_at        REAL NOT NULL
);

CREATE TABLE IF NOT EXISTS global_knowledge_summary (
    id                  TEXT PRIMARY KEY,
    collective_summary  TEXT NOT NULL,
    total_documents     INTEGER DEFAULT 0,
    key_insights        TEXT,
    updated_at          REAL NOT NULL
);
"""


class SQLitePersistentDB:
    """Thread-safe SQLite wrapper for long-term chat & document memory."""

    def __init__(self, db_path: str = DB_PATH) -> None:
        self._path = db_path
        self._local = threading.local()
        self._init_schema()

    # ── connection management ───────────────────────────────────────────────
    def _conn(self) -> sqlite3.Connection:
        if not getattr(self._local, "conn", None):
            conn = sqlite3.connect(self._path, check_same_thread=False)
            conn.row_factory = sqlite3.Row
            self._local.conn = conn
        return self._local.conn

    @contextmanager
    def _tx(self):
        conn = self._conn()
        try:
            yield conn
            conn.commit()
        except Exception:
            conn.rollback()
            raise

    def _init_schema(self) -> None:
        with self._tx() as conn:
            conn.executescript(_SQLITE_DDL)
            # Ensure newly added columns exist in older DB instances
            cursor = conn.execute("PRAGMA table_info(doc_meta)")
            existing_cols = {row["name"] for row in cursor.fetchall()}
            for col, col_type, default_val in [
                ("section_count", "INTEGER", "0"),
                ("progress", "INTEGER", "0"),
                ("current_stage", "TEXT", "'uploaded'"),
                ("indexing_method", "TEXT", "NULL"),
                ("duration", "REAL", "NULL"),
                ("error", "TEXT", "NULL"),
            ]:
                if col not in existing_cols:
                    conn.execute(f"ALTER TABLE doc_meta ADD COLUMN {col} {col_type} DEFAULT {default_val}")

            # Migrate existing chats.doc_id into chat_documents table
            conn.execute("""
                INSERT OR IGNORE INTO chat_documents(chat_id, doc_id, doc_name, attached_at)
                SELECT chat_id, doc_id, doc_name, created_at FROM chats
                WHERE doc_id IS NOT NULL AND doc_id != ''
            """)

    # ── chat CRUD ───────────────────────────────────────────────────────────
    def create_chat(self, chat_id: Optional[str] = None, title: Optional[str] = None) -> str:
        cid = chat_id or str(uuid.uuid4())
        now = time.time()
        with self._tx() as conn:
            conn.execute(
                "INSERT OR IGNORE INTO chats(chat_id, title, created_at, updated_at) VALUES(?,?,?,?)",
                (cid, title, now, now),
            )
        return cid

    def get_chat(self, chat_id: str) -> Optional[Dict[str, Any]]:
        row = self._conn().execute(
            "SELECT * FROM chats WHERE chat_id=?", (chat_id,)
        ).fetchone()
        return dict(row) if row else None

    def list_chats(self) -> List[Dict[str, Any]]:
        rows = self._conn().execute(
            "SELECT * FROM chats ORDER BY updated_at DESC"
        ).fetchall()
        return [dict(r) for r in rows]

    def update_chat_title(self, chat_id: str, title: str) -> None:
        with self._tx() as conn:
            conn.execute(
                "UPDATE chats SET title=?, updated_at=? WHERE chat_id=?",
                (title, time.time(), chat_id),
            )

    def set_chat_doc(self, chat_id: str, doc_id: str, doc_name: Optional[str] = None) -> None:
        with self._tx() as conn:
            conn.execute(
                "UPDATE chats SET doc_id=?, doc_name=?, updated_at=? WHERE chat_id=?",
                (doc_id, doc_name, time.time(), chat_id),
            )

    def remove_chat_doc(self, chat_id: str) -> None:
        with self._tx() as conn:
            conn.execute(
                "UPDATE chats SET doc_id=NULL, doc_name=NULL, updated_at=? WHERE chat_id=?",
                (time.time(), chat_id),
            )

    def delete_chat(self, chat_id: str) -> None:
        with self._tx() as conn:
            conn.execute("DELETE FROM chats WHERE chat_id=?", (chat_id,))

    # ── message CRUD ────────────────────────────────────────────────────────
    def add_message(self, chat_id: str, role: str, content: str) -> None:
        now = time.time()
        with self._tx() as conn:
            conn.execute(
                "INSERT OR IGNORE INTO chats(chat_id, title, created_at, updated_at) VALUES(?, 'New research', ?, ?)",
                (chat_id, now, now),
            )
            conn.execute(
                "INSERT INTO messages(chat_id, role, content, created_at) VALUES(?,?,?,?)",
                (chat_id, role, content, now),
            )
            conn.execute(
                "UPDATE chats SET updated_at=? WHERE chat_id=?", (now, chat_id)
            )

    def get_messages(self, chat_id: str, limit: int = 0) -> List[Dict[str, str]]:
        q = "SELECT role, content FROM messages WHERE chat_id=? ORDER BY created_at ASC"
        if limit > 0:
            rows = self._conn().execute(
                "SELECT role, content FROM messages WHERE chat_id=? ORDER BY created_at DESC LIMIT ?",
                (chat_id, limit),
            ).fetchall()
            return [{"role": r["role"], "content": r["content"]} for r in reversed(rows)]
        rows = self._conn().execute(q, (chat_id,)).fetchall()
        return [{"role": r["role"], "content": r["content"]} for r in rows]

    def clear_messages(self, chat_id: str) -> None:
        with self._tx() as conn:
            conn.execute("DELETE FROM messages WHERE chat_id=?", (chat_id,))

    # ── document metadata ────────────────────────────────────────────────────
    def upsert_doc_meta(
        self,
        doc_id: str,
        filename: str,
        status: str,
        page_count: int = 0,
        section_count: int = 0,
        progress: int = 0,
        current_stage: str = "uploaded",
        indexing_method: Optional[str] = None,
        duration: Optional[float] = None,
        error: Optional[str] = None,
        content_hash: Optional[str] = None,
        file_path: Optional[str] = None,
    ) -> None:
        now = time.time()
        with self._tx() as conn:
            conn.execute(
                """
                INSERT INTO doc_meta(
                    doc_id, filename, status, page_count, section_count,
                    progress, current_stage, indexing_method, duration,
                    error, content_hash, file_path, created_at, updated_at
                )
                VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)
                ON CONFLICT(doc_id) DO UPDATE SET
                    filename=excluded.filename,
                    status=excluded.status,
                    page_count=excluded.page_count,
                    section_count=excluded.section_count,
                    progress=excluded.progress,
                    current_stage=excluded.current_stage,
                    indexing_method=COALESCE(excluded.indexing_method, doc_meta.indexing_method),
                    duration=COALESCE(excluded.duration, doc_meta.duration),
                    error=excluded.error,
                    content_hash=COALESCE(excluded.content_hash, doc_meta.content_hash),
                    file_path=COALESCE(excluded.file_path, doc_meta.file_path),
                    updated_at=excluded.updated_at
                """,
                (
                    doc_id, filename, status, page_count, section_count,
                    progress, current_stage, indexing_method, duration,
                    error, content_hash, file_path, now, now
                ),
            )

    def get_doc_meta(self, doc_id: str) -> Optional[Dict[str, Any]]:
        row = self._conn().execute(
            "SELECT * FROM doc_meta WHERE doc_id=?", (doc_id,)
        ).fetchone()
        return dict(row) if row else None

    def list_docs(self) -> List[Dict[str, Any]]:
        rows = self._conn().execute(
            "SELECT * FROM doc_meta ORDER BY created_at DESC"
        ).fetchall()
        return [dict(r) for r in rows]

    def find_doc_by_hash(self, content_hash: str) -> Optional[Dict[str, Any]]:
        row = self._conn().execute(
            "SELECT * FROM doc_meta WHERE content_hash=? ORDER BY updated_at DESC LIMIT 1",
            (content_hash,),
        ).fetchone()
        return dict(row) if row else None

    def delete_doc(self, doc_id: str) -> bool:
        with self._tx() as conn:
            cur = conn.execute("DELETE FROM doc_meta WHERE doc_id=?", (doc_id,))
            conn.execute("UPDATE chats SET doc_id=NULL, doc_name=NULL WHERE doc_id=?", (doc_id,))
            conn.execute("DELETE FROM chat_documents WHERE doc_id=?", (doc_id,))
            conn.execute("DELETE FROM knowledge_memory WHERE doc_id=?", (doc_id,))
            conn.execute("DELETE FROM doc_indices WHERE doc_id=?", (doc_id,))
            return cur.rowcount > 0

    # ── document heavy indices store ─────────────────────────────────────────
    def save_doc_index(
        self,
        doc_id: str,
        content_hash: Optional[str],
        tree: Any,
        node_map: Optional[Dict[str, Any]] = None,
        flat_sections: Optional[List[Dict[str, Any]]] = None,
        file_base64: Optional[str] = None,
    ) -> None:
        now = time.time()
        with self._tx() as conn:
            conn.execute(
                """
                INSERT INTO doc_indices(
                    doc_id, content_hash, tree, node_map, flat_sections, file_base64, created_at, updated_at
                )
                VALUES(?,?,?,?,?,?,?,?)
                ON CONFLICT(doc_id) DO UPDATE SET
                    content_hash=COALESCE(excluded.content_hash, doc_indices.content_hash),
                    tree=excluded.tree,
                    node_map=excluded.node_map,
                    flat_sections=excluded.flat_sections,
                    file_base64=COALESCE(excluded.file_base64, doc_indices.file_base64),
                    updated_at=excluded.updated_at
                """,
                (
                    doc_id,
                    content_hash,
                    json.dumps(tree) if tree is not None else None,
                    json.dumps(node_map) if node_map is not None else None,
                    json.dumps(flat_sections) if flat_sections is not None else None,
                    file_base64,
                    now,
                    now,
                ),
            )

    def get_doc_index(self, doc_id: str) -> Optional[Dict[str, Any]]:
        row = self._conn().execute(
            "SELECT * FROM doc_indices WHERE doc_id=?", (doc_id,)
        ).fetchone()
        if not row:
            return None
        res = dict(row)
        for k in ("tree", "node_map", "flat_sections"):
            if res.get(k) and isinstance(res[k], str):
                try:
                    res[k] = json.loads(res[k])
                except Exception:
                    pass
        return res

    def get_doc_index_by_hash(self, content_hash: str) -> Optional[Dict[str, Any]]:
        row = self._conn().execute(
            "SELECT * FROM doc_indices WHERE content_hash=? ORDER BY updated_at DESC LIMIT 1",
            (content_hash,),
        ).fetchone()
        if not row:
            return None
        res = dict(row)
        for k in ("tree", "node_map", "flat_sections"):
            if res.get(k) and isinstance(res[k], str):
                try:
                    res[k] = json.loads(res[k])
                except Exception:
                    pass
        return res

    def delete_doc_index(self, doc_id: str) -> None:
        with self._tx() as conn:
            conn.execute("DELETE FROM doc_indices WHERE doc_id=?", (doc_id,))

    # ── multi-doc session associations ──────────────────────────────────────
    def add_chat_document(self, chat_id: str, doc_id: str, doc_name: Optional[str] = None) -> None:
        now = time.time()
        with self._tx() as conn:
            conn.execute(
                """
                INSERT INTO chat_documents(chat_id, doc_id, doc_name, attached_at)
                VALUES(?,?,?,?)
                ON CONFLICT(chat_id, doc_id) DO UPDATE SET
                    doc_name=COALESCE(excluded.doc_name, chat_documents.doc_name),
                    attached_at=excluded.attached_at
                """,
                (chat_id, doc_id, doc_name, now),
            )
            conn.execute(
                "UPDATE chats SET doc_id=?, doc_name=?, updated_at=? WHERE chat_id=?",
                (doc_id, doc_name, now, chat_id),
            )

    def remove_chat_document(self, chat_id: str, doc_id: str) -> None:
        now = time.time()
        with self._tx() as conn:
            conn.execute("DELETE FROM chat_documents WHERE chat_id=? AND doc_id=?", (chat_id, doc_id))
            rem = conn.execute(
                "SELECT doc_id, doc_name FROM chat_documents WHERE chat_id=? ORDER BY attached_at DESC LIMIT 1",
                (chat_id,),
            ).fetchone()
            if rem:
                conn.execute(
                    "UPDATE chats SET doc_id=?, doc_name=?, updated_at=? WHERE chat_id=?",
                    (rem["doc_id"], rem["doc_name"], now, chat_id),
                )
            else:
                conn.execute(
                    "UPDATE chats SET doc_id=NULL, doc_name=NULL, updated_at=? WHERE chat_id=?",
                    (now, chat_id),
                )

    def get_chat_documents(self, chat_id: str) -> List[Dict[str, Any]]:
        rows = self._conn().execute(
            """
            SELECT cd.chat_id, cd.doc_id, cd.doc_name, cd.attached_at,
                   dm.status, dm.page_count, dm.section_count, dm.filename
            FROM chat_documents cd
            LEFT JOIN doc_meta dm ON cd.doc_id = dm.doc_id
            WHERE cd.chat_id=?
            ORDER BY cd.attached_at ASC
            """,
            (chat_id,),
        ).fetchall()
        return [dict(r) for r in rows]

    def clear_chat_documents(self, chat_id: str) -> None:
        now = time.time()
        with self._tx() as conn:
            conn.execute("DELETE FROM chat_documents WHERE chat_id=?", (chat_id,))
            conn.execute("UPDATE chats SET doc_id=NULL, doc_name=NULL, updated_at=? WHERE chat_id=?", (now, chat_id))

    # ── session long memory & rolling summaries ─────────────────────────────
    def set_chat_summary(self, chat_id: str, summary: str, turn_count: int = 0) -> None:
        now = time.time()
        with self._tx() as conn:
            conn.execute(
                """
                INSERT INTO chat_summaries(chat_id, summary, turn_count, updated_at)
                VALUES(?,?,?,?)
                ON CONFLICT(chat_id) DO UPDATE SET
                    summary=excluded.summary,
                    turn_count=excluded.turn_count,
                    updated_at=excluded.updated_at
                """,
                (chat_id, summary, turn_count, now),
            )

    def get_chat_summary(self, chat_id: str) -> Optional[Dict[str, Any]]:
        row = self._conn().execute(
            "SELECT * FROM chat_summaries WHERE chat_id=?", (chat_id,)
        ).fetchone()
        return dict(row) if row else None

    # ── global knowledge memory & document dossiers ────────────────────────
    def save_knowledge_dossier(
        self,
        doc_id: str,
        filename: str,
        executive_summary: str,
        key_entities: Optional[List[str]] = None,
        key_findings: Optional[List[str]] = None,
        topics: Optional[List[str]] = None,
    ) -> None:
        now = time.time()
        with self._tx() as conn:
            conn.execute(
                """
                INSERT INTO knowledge_memory(
                    doc_id, filename, executive_summary, key_entities, key_findings, topics, updated_at
                )
                VALUES(?,?,?,?,?,?,?)
                ON CONFLICT(doc_id) DO UPDATE SET
                    filename=excluded.filename,
                    executive_summary=excluded.executive_summary,
                    key_entities=excluded.key_entities,
                    key_findings=excluded.key_findings,
                    topics=excluded.topics,
                    updated_at=excluded.updated_at
                """,
                (
                    doc_id,
                    filename,
                    executive_summary,
                    json.dumps(key_entities or []),
                    json.dumps(key_findings or []),
                    json.dumps(topics or []),
                    now,
                ),
            )

    def get_knowledge_dossier(self, doc_id: str) -> Optional[Dict[str, Any]]:
        row = self._conn().execute(
            "SELECT * FROM knowledge_memory WHERE doc_id=?", (doc_id,)
        ).fetchone()
        if not row:
            return None
        res = dict(row)
        for k in ("key_entities", "key_findings", "topics"):
            if res.get(k) and isinstance(res[k], str):
                try:
                    res[k] = json.loads(res[k])
                except Exception:
                    res[k] = []
        return res

    def list_knowledge_dossiers(self) -> List[Dict[str, Any]]:
        rows = self._conn().execute(
            "SELECT * FROM knowledge_memory ORDER BY updated_at DESC"
        ).fetchall()
        result = []
        for r in rows:
            item = dict(r)
            for k in ("key_entities", "key_findings", "topics"):
                if item.get(k) and isinstance(item[k], str):
                    try:
                        item[k] = json.loads(item[k])
                    except Exception:
                        item[k] = []
            result.append(item)
        return result

    def delete_knowledge_dossier(self, doc_id: str) -> None:
        with self._tx() as conn:
            conn.execute("DELETE FROM knowledge_memory WHERE doc_id=?", (doc_id,))

    def save_global_knowledge_summary(
        self,
        collective_summary: str,
        total_documents: int,
        key_insights: Optional[List[str]] = None,
    ) -> None:
        now = time.time()
        gid = "global"
        with self._tx() as conn:
            conn.execute(
                """
                INSERT INTO global_knowledge_summary(
                    id, collective_summary, total_documents, key_insights, updated_at
                )
                VALUES(?,?,?,?,?)
                ON CONFLICT(id) DO UPDATE SET
                    collective_summary=excluded.collective_summary,
                    total_documents=excluded.total_documents,
                    key_insights=excluded.key_insights,
                    updated_at=excluded.updated_at
                """,
                (gid, collective_summary, total_documents, json.dumps(key_insights or []), now),
            )

    def get_global_knowledge_summary(self) -> Optional[Dict[str, Any]]:
        row = self._conn().execute(
            "SELECT * FROM global_knowledge_summary WHERE id='global'"
        ).fetchone()
        if not row:
            return None
        res = dict(row)
        if res.get("key_insights") and isinstance(res["key_insights"], str):
            try:
                res["key_insights"] = json.loads(res["key_insights"])
            except Exception:
                res["key_insights"] = []
        return res


def _migrate_sqlite_to_postgres_if_needed(pg_db: Any) -> None:
    """If local SQLite contains chats/docs and PostgreSQL is newly initialized, migrate data smoothly."""
    if not os.path.exists(DB_PATH):
        return

    # Check if Postgres already has documents or chats
    if pg_db.list_docs() or pg_db.list_chats():
        return

    sqlite_db = SQLitePersistentDB(DB_PATH)
    sqlite_chats = sqlite_db.list_chats()
    sqlite_docs = sqlite_db.list_docs()

    if not sqlite_chats and not sqlite_docs:
        return

    app_logger.info(f"[Migration] Migrating {len(sqlite_docs)} docs and {len(sqlite_chats)} chats from SQLite to PostgreSQL...")

    for d in sqlite_docs:
        try:
            pg_db.upsert_doc_meta(
                doc_id=d["doc_id"],
                filename=d.get("filename", "document.pdf"),
                status=d.get("status", "ready"),
                page_count=d.get("page_count", 0),
                section_count=d.get("section_count", 0),
                progress=d.get("progress", 100),
                current_stage=d.get("current_stage", "Ready"),
                indexing_method=d.get("indexing_method"),
                duration=d.get("duration"),
                error=d.get("error"),
                content_hash=d.get("content_hash"),
                file_path=d.get("file_path"),
            )
            # Check if index exists in SQLite
            s_idx = sqlite_db.get_doc_index(d["doc_id"])
            if s_idx:
                pg_db.save_doc_index(
                    doc_id=d["doc_id"],
                    content_hash=d.get("content_hash"),
                    tree=s_idx.get("tree"),
                    node_map=s_idx.get("node_map"),
                    flat_sections=s_idx.get("flat_sections"),
                    file_base64=s_idx.get("file_base64"),
                )
        except Exception as dex:
            app_logger.warning(f"[Migration] Error migrating doc {d.get('doc_id')}: {dex}")

    for c in sqlite_chats:
        try:
            cid = c["chat_id"]
            pg_db.create_chat(chat_id=cid, title=c.get("title"))
            if c.get("doc_id"):
                pg_db.set_chat_doc(cid, c["doc_id"], c.get("doc_name"))
            # Migrate messages
            msgs = sqlite_db.get_messages(cid)
            for m in msgs:
                pg_db.add_message(cid, m["role"], m["content"])
            # Migrate attached documents
            att = sqlite_db.get_chat_documents(cid)
            for a in att:
                pg_db.add_chat_document(cid, a["doc_id"], a.get("doc_name"))
        except Exception as cex:
            app_logger.warning(f"[Migration] Error migrating chat {c.get('chat_id')}: {cex}")

    app_logger.info("[Migration] SQLite to PostgreSQL migration completed successfully.")


DB_STATUS = {
    "provider": "SQLite",
    "connected": True,
    "error": None,
    "url_configured": False,
}


def create_persistent_db() -> Any:
    """
    Factory function for persistent database.
    Checks environment for DATABASE_URL / POSTGRES_URL.
    If provided and accessible, uses PostgresDB. Otherwise falls back to SQLite.
    """
    global DB_STATUS
    pg_url = os.getenv("DATABASE_URL") or os.getenv("POSTGRES_URL") or os.getenv("POSTGRESQL_URL")
    if pg_url:
        pg_url = pg_url.strip().strip("'").strip('"')
        DB_STATUS["url_configured"] = True
        try:
            from core.postgres_db import PostgresDB
            pg_db = PostgresDB(pg_url)
            safe_url = pg_url.split("@")[-1] if "@" in pg_url else "local"
            app_logger.info(f"[PersistentDB] Connected to PostgreSQL: {safe_url}")
            DB_STATUS["provider"] = "PostgreSQL"
            DB_STATUS["connected"] = True
            DB_STATUS["error"] = None
            try:
                _migrate_sqlite_to_postgres_if_needed(pg_db)
            except Exception as mex:
                app_logger.warning(f"[PersistentDB] Auto-migration skipped: {mex}")
            return pg_db
        except Exception as e:
            err_msg = str(e)
            # Sanitize password from error if any
            if "@" in err_msg and ":" in err_msg:
                err_msg = err_msg.split("@")[-1]
            DB_STATUS["provider"] = "SQLite (fallback)"
            DB_STATUS["connected"] = False
            DB_STATUS["error"] = err_msg
            app_logger.error(f"[PersistentDB] Failed to connect to PostgreSQL ({e}). Falling back to SQLite.")

    app_logger.info(f"[PersistentDB] Using SQLite persistence at {DB_PATH}")
    DB_STATUS["provider"] = "SQLite"
    DB_STATUS["connected"] = True
    return SQLitePersistentDB(DB_PATH)


# Global singleton instance
persistent_db = create_persistent_db()