-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathdb_utils.py
More file actions
5762 lines (5199 loc) · 206 KB
/
db_utils.py
File metadata and controls
5762 lines (5199 loc) · 206 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
"""Shared DB connection, constants, and query helpers for sqlite-memory-mcp.
Single source of truth for task constants, DB connection setup, and common
utilities used by server.py, task_tray.py, and utility scripts.
"""
from __future__ import annotations
import base64
import hashlib
import inspect
import json
import logging
import mimetypes
import os
import re
import shutil
import socket
import sqlite3
import subprocess
import sys
import threading
import tempfile
import uuid
from contextlib import contextmanager
from datetime import date, datetime, timedelta, timezone
from pathlib import Path
from typing import Any
# Suppress console windows on Windows when spawning git/gh from GUI
_NOWIN: dict = (
{"creationflags": subprocess.CREATE_NO_WINDOW} if sys.platform == "win32" else {}
)
try:
import orjson
def json_dumps(obj: Any, **kw) -> str:
"""Fast JSON serialize via orjson (returns str for compatibility)."""
return orjson.dumps(obj).decode("utf-8")
def json_loads(s: str | bytes) -> Any:
return orjson.loads(s)
except ImportError:
import json
def json_dumps(obj: Any, **kw) -> str: # type: ignore[misc]
return json.dumps(obj, ensure_ascii=False, **kw)
def json_loads(s: str | bytes) -> Any: # type: ignore[misc]
return json.loads(s)
# ── Paths ────────────────────────────────────────────────────────────────
DB_PATH = os.environ.get(
"SQLITE_MEMORY_DB",
os.path.expanduser("~/.claude/memory/memory.db"),
)
BRIDGE_REPO = os.environ.get(
"BRIDGE_REPO",
os.path.expanduser("~/.claude/memory/bridge"),
)
TASK_ATTACHMENT_ROOT = os.environ.get(
"TASK_ATTACHMENT_ROOT",
os.path.expanduser("~/.claude/memory/task_attachments"),
)
# ── Task constants (canonical ordering) ──────────────────────────────────
TASK_SECTIONS = ("inbox", "today", "next", "someday", "waiting")
TASK_PRIORITIES = ("low", "medium", "high", "critical") # ascending rank
TASK_STATUSES = ("not_started", "in_progress", "done", "archived", "cancelled")
TASK_TYPES = ("task", "note")
TASK_HIDDEN_STATUSES = ("archived", "cancelled")
TASK_ACTIVE_EXCLUSIONS = ("done", "archived", "cancelled")
# v5: Extended memory keys — written to separate files during bridge export
EXTENDED_MEMORY_KEYS = (
"context_chunks",
"context_annotations",
"context_questions",
"candidate_claims",
"claim_evidence",
"canonical_facts",
"provenance_links",
"knowledge_links",
"memory_events",
"memory_audit_issues",
"memory_artifacts",
"memory_conflicts",
"memory_audit_state",
)
# v0.7.0: Public knowledge visibility
VISIBILITY_LEVELS = ("private", "pending_public", "public")
PUBLISH_STANDBY_MINUTES = 15
BRIDGE_SYNC_DELAY = 60 # seconds; shared between bridge_server and task_tray
# Collaboration constants
TRUST_LEVELS = ("read_only", "read_write")
SHARE_TYPES = ("entity", "relation", "all")
ENTITY_ORIGINS = ("local",) # "shared:{username}" added dynamically
# v0.9.0: Quality rating constants (HARDCODED — not configurable to prevent gaming)
VERIFICATION_OUTCOMES = ("confirmed", "contradicted", "inconclusive")
VERIFICATION_WEIGHTS = {"confirmed": 1.0, "inconclusive": 0.5, "contradicted": 0.0}
# Composite score weights (sealed)
IQ_WEIGHTS = {
"specificity": 0.35,
"falsifiability": 0.25,
"internal_consistency": 0.25,
"novelty": 0.15,
}
TIER_WEIGHTS = {"iq": 0.40, "verification": 0.35, "cross_validation": 0.25}
# Anomaly detection
RATING_BURST_THRESHOLD = 5
RATING_BURST_WINDOW_HOURS = 24
PRIORITY_RANK = {p: i for i, p in enumerate(TASK_PRIORITIES)}
_PROJECT_ALIAS_CANONICAL = {
"mappingstudio": "mapping-studio",
"smartkey": "SmartKey",
}
def _project_alias_key(project: str) -> str:
"""Build a punctuation-insensitive key for project alias matching."""
return re.sub(r"[-_\s]+", "", project.strip().casefold())
def normalize_project_name(project: str | None) -> str | None:
"""Normalize known project aliases while preserving unrelated names."""
if project is None:
return None
cleaned = re.sub(r"\s+", " ", str(project)).strip()
if not cleaned:
return None
return _PROJECT_ALIAS_CANONICAL.get(_project_alias_key(cleaned), cleaned)
def normalize_project_filter_values(values: Any) -> set[str]:
"""Normalize a project filter collection into canonical project names."""
result: set[str] = set()
if not values:
return result
for value in values:
normalized = normalize_project_name(value)
if normalized:
result.add(normalized)
return result
PRIORITY_COLORS = {
"critical": "#e53e3e",
"high": "#dd6b20",
"medium": "#2b6cb0",
"low": "#718096",
}
TASK_ALLOWED_UPDATE_FIELDS = frozenset(
{
"title",
"description",
"status",
"section",
"priority",
"due_date",
"project",
"parent_id",
"notes",
"recurring",
"reminder_at",
"type",
"assignee",
"shared_by",
"updated_at",
"visibility",
"publish_requested_at",
}
)
GITHUB_USER_RE = re.compile(r"^[a-zA-Z0-9](?:[a-zA-Z0-9\-]{0,37}[a-zA-Z0-9])?$")
# ── Recurring task validation ─────────────────────────────────────────
RECURRING_EVERY = ("day", "week", "month", "year")
RECURRING_WEEKDAYS = frozenset(
("monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday")
)
def validate_recurring(raw: str) -> str | None:
"""Validate recurring JSON config. Returns error message or None if valid."""
try:
config = json.loads(raw)
except (json.JSONDecodeError, TypeError):
return f"Invalid JSON: {raw!r}"
if not isinstance(config, dict):
return "Recurring config must be a JSON object"
every = config.get("every", "").lower()
if every not in RECURRING_EVERY:
return f"Invalid 'every': {every}. Use: {RECURRING_EVERY}"
# Optional interval (default 1)
interval = config.get("interval")
if interval is not None:
try:
iv = int(interval)
if iv < 1:
return f"'interval' must be >= 1. Got: {iv}"
except (ValueError, TypeError):
return f"'interval' must be an integer. Got: {interval!r}"
if every == "week":
day = config.get("day", "").lower()
if day not in RECURRING_WEEKDAYS:
return f"Weekly recurrence requires 'day' (weekday name). Got: {day!r}"
if every == "month":
day = config.get("day")
if day is None:
return "Monthly recurrence requires 'day' (1-31)"
try:
d = int(day)
if not 1 <= d <= 31:
return f"Monthly 'day' must be 1-31. Got: {d}"
except (ValueError, TypeError):
return f"Monthly 'day' must be an integer. Got: {day!r}"
if every == "year":
month = config.get("month")
if month is not None:
try:
m = int(month)
if not 1 <= m <= 12:
return f"Yearly 'month' must be 1-12. Got: {m}"
except (ValueError, TypeError):
return f"Yearly 'month' must be an integer. Got: {month!r}"
day = config.get("day")
if day is not None:
try:
d = int(day)
if not 1 <= d <= 31:
return f"Yearly 'day' must be 1-31. Got: {d}"
except (ValueError, TypeError):
return f"Yearly 'day' must be an integer. Got: {day!r}"
return None
def validate_task_fields(**kwargs: str | None) -> str | None:
"""Validate task enum/date/recurring fields. Returns error message or None.
Pass only the fields that need validation. None values are skipped.
Works for both create_task (pass all fields) and update_task (pass only changed fields).
"""
section = kwargs.get("section")
if section is not None and section not in TASK_SECTIONS:
return f"Invalid section: {section}. Use: {TASK_SECTIONS}"
priority = kwargs.get("priority")
if priority is not None and priority not in TASK_PRIORITIES:
return f"Invalid priority: {priority}. Use: {TASK_PRIORITIES}"
status = kwargs.get("status")
if status is not None and status not in TASK_STATUSES:
return f"Invalid status: {status}. Use: {TASK_STATUSES}"
type_ = kwargs.get("type")
if type_ is not None and type_ not in TASK_TYPES:
return f"Invalid type: {type_}. Use: {TASK_TYPES}"
due_date = kwargs.get("due_date")
if due_date:
try:
datetime.strptime(due_date, "%Y-%m-%d")
except ValueError:
return f"Invalid due_date: {due_date}. Use YYYY-MM-DD format"
recurring = kwargs.get("recurring")
if recurring:
err = validate_recurring(recurring)
if err:
return f"Invalid recurring config: {err}"
reminder_at = kwargs.get("reminder_at")
if reminder_at:
try:
datetime.fromisoformat(reminder_at)
except ValueError:
return f"Invalid reminder_at: {reminder_at}. Use ISO datetime format"
return None
# ── Bridge Sync v2: Per-field LWW conflict resolver ─────────────────────
MACHINE_ID = os.environ.get("MACHINE_ID", socket.gethostname())
_HLC_COUNTER_BITS = 16
_HLC_COUNTER_MASK = (1 << _HLC_COUNTER_BITS) - 1
_HLC_PACKED_MIN = 1 << 32
def _iso_to_epoch_ms(value: str | None) -> int:
raw = (value or "").strip()
if raw.endswith("Z"):
raw = raw[:-1] + "+00:00"
try:
dt = datetime.fromisoformat(raw) if raw else datetime.now(timezone.utc)
except ValueError:
dt = datetime.now(timezone.utc)
if dt.tzinfo is None:
dt = dt.replace(tzinfo=timezone.utc)
return int(dt.astimezone(timezone.utc).timestamp() * 1000)
def _decode_logical_clock(clock: int) -> tuple[int, int]:
value = int(clock or 0)
if value <= 0:
return 0, 0
if value < _HLC_PACKED_MIN:
return value, 0
return value >> _HLC_COUNTER_BITS, value & _HLC_COUNTER_MASK
def _pack_logical_clock(physical_ms: int, counter: int) -> int:
return (max(0, int(physical_ms)) << _HLC_COUNTER_BITS) | (
int(counter) & _HLC_COUNTER_MASK
)
METADATA_FIELDS = (
"id",
"title",
"status",
"priority",
"section",
"due_date",
"project",
"parent_id",
"recurring",
"reminder_at",
"type",
"assignee",
"shared_by",
"visibility",
"publish_requested_at",
"created_at",
"updated_at",
)
CONTENT_FIELDS = ("description", "notes")
TASK_FILE_HYDRATION_FIELDS = ("_attachments", "_field_ts", "_links", "_tombstone")
CONTENT_SHRINK_GUARD_MIN_CHARS = 1000
CONTENT_SHRINK_GUARD_RATIO = 0.5
# Fields that enrichment pipelines must NEVER modify — only user/bridge can write these.
# Invariant: enrichment = add new records (facts, claims, chunks), never modify existing content.
ENRICHMENT_PROTECTED_FIELDS = frozenset({"title", "description", "notes"})
def content_length(value: Any) -> int:
"""Return trimmed length for text-like content, else 0."""
if value is None:
return 0
return len(str(value).strip())
def has_meaningful_content(value: Any) -> bool:
"""True when a content field has non-whitespace text."""
return content_length(value) > 0
def is_suspicious_content_shrink(
old_value: Any,
new_value: Any,
*,
min_chars: int = CONTENT_SHRINK_GUARD_MIN_CHARS,
ratio: float = CONTENT_SHRINK_GUARD_RATIO,
) -> bool:
"""Flag likely data loss when substantial content collapses to a much shorter value."""
old_len = content_length(old_value)
if old_len < min_chars:
return False
return content_length(new_value) < (old_len * ratio)
def assert_enrichment_safe(fields: dict[str, Any] | set[str] | list[str]) -> None:
"""Raise ValueError if any enrichment-protected field is in the update set.
Call this from any enrichment code path that touches tasks.
"""
keys = set(fields) if isinstance(fields, dict) else set(fields)
violation = keys & ENRICHMENT_PROTECTED_FIELDS
if violation:
raise ValueError(
f"Enrichment invariant violation: cannot modify protected fields {sorted(violation)}. "
"Enrichment must be additive-only (new facts/claims/chunks)."
)
# Fields eligible for per-field LWW merge (excludes id, created_at, updated_at)
MERGEABLE_FIELDS = (
"title",
"status",
"priority",
"section",
"due_date",
"project",
"parent_id",
"recurring",
"reminder_at",
"type",
"assignee",
"shared_by",
"visibility",
"publish_requested_at",
"description",
"notes",
)
_TOMBSTONE_DAYS = 30
# Path traversal defense for direct filename usage: raw task IDs may only use
# alphanumerics and hyphens. Legacy IDs are still supported via encoded stems.
_SAFE_TASK_ID = re.compile(r"^[a-zA-Z0-9\-]+$")
_SAFE_ENTITY_ID = re.compile(r"^[1-9][0-9]*$")
def _task_storage_stem(task_id: str) -> str:
"""Return a filesystem-safe stem for per-task bridge files."""
if _SAFE_TASK_ID.match(task_id):
return task_id
encoded = base64.urlsafe_b64encode(task_id.encode("utf-8")).decode("ascii")
return f"_id_{encoded.rstrip('=')}"
def _task_storage_path(task_id: str, bridge_dir: str) -> Path:
"""Return the canonical per-task bridge file path for a task id."""
return Path(bridge_dir) / "tasks" / f"{_task_storage_stem(task_id)}.json"
_ATTACHMENT_NAME_SANITIZE_RE = re.compile(r'[<>:"/\\|?*\x00-\x1F]+')
def _safe_attachment_name(file_name: str) -> str:
"""Return a filesystem-safe attachment file name."""
base = os.path.basename((file_name or "").strip()) or "attachment"
cleaned = _ATTACHMENT_NAME_SANITIZE_RE.sub("_", base).strip(" .")
return cleaned or "attachment"
def _task_attachment_relpath(task_id: str, attachment_id: str, file_name: str) -> str:
"""Return attachment relpath shared by local store and bridge export."""
safe_name = _safe_attachment_name(file_name)
return f"{_task_storage_stem(task_id)}/{attachment_id}__{safe_name}"
def _resolve_attachment_path(root_dir: str, stored_relpath: str) -> Path:
"""Resolve a stored attachment path under a root dir with traversal defense."""
root = Path(root_dir).resolve()
target = (root / stored_relpath).resolve()
if target != root and root not in target.parents:
raise ValueError(f"Attachment path escapes root: {stored_relpath!r}")
return target
def _local_attachment_path(stored_relpath: str, root_dir: str | None = None) -> Path:
return _resolve_attachment_path(root_dir or TASK_ATTACHMENT_ROOT, stored_relpath)
def _bridge_attachment_path(stored_relpath: str, bridge_dir: str) -> Path:
return _resolve_attachment_path(
os.path.join(bridge_dir, "attachments"), stored_relpath
)
def _copy_attachment_file(src: Path, dst: Path) -> None:
"""Copy attachment bytes atomically, creating parent dirs as needed."""
dst.parent.mkdir(parents=True, exist_ok=True)
tmp_path = dst.with_suffix(dst.suffix + ".tmp")
shutil.copy2(src, tmp_path)
os.replace(tmp_path, dst)
def setup_logger(name: str, log_file: str = "server.log") -> logging.Logger:
"""Configure file logger. Idempotent — safe to call multiple times."""
logger = logging.getLogger(name)
logger.setLevel(logging.DEBUG)
if not logger.handlers:
candidates = [
Path.home() / ".claude" / "memory" / log_file,
Path(tempfile.gettempdir()) / "sqlite-memory-mcp" / log_file,
]
for log_path in candidates:
try:
log_path.parent.mkdir(parents=True, exist_ok=True)
fh = logging.FileHandler(log_path, encoding="utf-8")
except OSError:
continue
fh.setFormatter(logging.Formatter("%(asctime)s %(levelname)s %(message)s"))
logger.addHandler(fh)
break
if not logger.handlers:
logger.addHandler(logging.NullHandler())
return logger
_log = logging.getLogger("sqlite-kb")
# ── DB connection ────────────────────────────────────────────────────────
_PRAGMAS = (
"PRAGMA journal_mode=WAL;",
"PRAGMA foreign_keys=ON;",
"PRAGMA busy_timeout=10000;",
"PRAGMA wal_autocheckpoint=100;",
)
_BUSY_RETRIES = 3
_BUSY_BASE_DELAY = 0.5 # seconds, doubles each retry
_DB_INIT_DONE: set[str] = set()
_DB_INIT_ACTIVE: set[str] = set()
_DB_INIT_COND = threading.Condition()
_DB_INIT_LOCAL = threading.local()
def ensure_db_initialized(db_path: str | None = None) -> str:
"""Initialize the target DB lazily, once per process and path."""
target = db_path or DB_PATH
local_paths = getattr(_DB_INIT_LOCAL, "paths", set())
if target in local_paths:
return target
with _DB_INIT_COND:
while target in _DB_INIT_ACTIVE:
_DB_INIT_COND.wait()
if target in _DB_INIT_DONE:
return target
_DB_INIT_ACTIVE.add(target)
_DB_INIT_LOCAL.paths = set(local_paths) | {target}
try:
from schema import init_db
init_db(target)
except Exception:
with _DB_INIT_COND:
_DB_INIT_ACTIVE.discard(target)
_DB_INIT_COND.notify_all()
raise
finally:
local_paths = set(getattr(_DB_INIT_LOCAL, "paths", set()))
local_paths.discard(target)
_DB_INIT_LOCAL.paths = local_paths
with _DB_INIT_COND:
_DB_INIT_ACTIVE.discard(target)
_DB_INIT_DONE.add(target)
_DB_INIT_COND.notify_all()
return target
@contextmanager
def get_conn(db_path: str | None = None):
"""Yield a SQLite connection with PRAGMAs set, auto-commit/rollback.
Uses explicit BEGIN/COMMIT to ensure each context-manager block is atomic.
Retries BEGIN up to 3× on SQLITE_BUSY (exponential backoff on top of busy_timeout).
"""
import time as _time
target = db_path or DB_PATH
if db_path is None:
ensure_db_initialized(target)
# Retry connection + BEGIN on SQLITE_BUSY (lock contention with tray/bridge)
conn = None
for attempt in range(_BUSY_RETRIES):
conn = sqlite3.connect(target, isolation_level=None, timeout=10)
conn.row_factory = sqlite3.Row
for pragma in _PRAGMAS:
conn.execute(pragma)
try:
conn.execute("BEGIN;")
break # transaction started successfully
except sqlite3.OperationalError as e:
conn.close()
conn = None
if "locked" in str(e).lower() and attempt < _BUSY_RETRIES - 1:
_time.sleep(_BUSY_BASE_DELAY * (2**attempt))
continue
raise
# Yield exactly once, outside the retry loop
try:
yield conn
conn.execute("COMMIT;")
except Exception:
try:
conn.execute("ROLLBACK;")
except Exception:
pass # ROLLBACK failed — original exception is more important
raise
finally:
if conn is not None:
conn.close()
@contextmanager
def bulk_conn(db_path: str | None = None):
"""Connection optimized for bulk inserts: single transaction, relaxed sync.
Use for batch imports where throughput matters more than per-row durability.
WAL checkpoint runs automatically after the transaction commits.
"""
target = db_path or DB_PATH
if db_path is None:
ensure_db_initialized(target)
conn = sqlite3.connect(target, isolation_level=None, timeout=30)
conn.row_factory = sqlite3.Row
conn.execute("PRAGMA journal_mode=WAL;")
conn.execute("PRAGMA foreign_keys=ON;")
conn.execute("PRAGMA busy_timeout=30000;")
conn.execute("PRAGMA synchronous=NORMAL;") # faster writes, safe with WAL
conn.execute("PRAGMA cache_size=-64000;") # 64MB cache for bulk ops
conn.execute("BEGIN;")
try:
yield conn
conn.execute("COMMIT;")
conn.execute("PRAGMA wal_checkpoint(PASSIVE);")
except Exception:
try:
conn.execute("ROLLBACK;")
except Exception:
pass
raise
finally:
conn.close()
# ── Git helpers ──────────────────────────────────────────────────────────
log = logging.getLogger(__name__)
BRIDGE_GENERATED_FILES = frozenset(
{
"shared.json",
"shared.js",
"index.json",
"entities_index.json",
".bridge_sync.lock", # legacy in-repo lock path; safe to discard
}
)
BRIDGE_GENERATED_TEMP_FILES = frozenset(
{
"shared.tmp", # legacy temp path used by older bridge writers
"shared.json.tmp",
"shared.js.tmp",
"index.json.tmp",
"entities_index.json.tmp",
}
)
BRIDGE_GENERATED_DIRS = frozenset(
{"tasks", "entities", "attachments", "public_knowledge", "extended_memory"}
)
def validate_github_username(username: str) -> None:
"""Raise ValueError when a collaborator/assignee name is not GitHub-safe."""
if not GITHUB_USER_RE.match(username):
raise ValueError(f"Invalid GitHub username: {username!r}")
_BRIDGE_CONFLICT_STATES = frozenset({"AA", "AU", "DD", "DU", "UA", "UD", "UU"})
def git_run(
repo_dir: str, *args: str, timeout: int = 30
) -> subprocess.CompletedProcess:
"""Run git command in specified repo directory."""
return subprocess.run(
["git", *args],
cwd=repo_dir,
capture_output=True,
text=True,
timeout=timeout,
**_NOWIN,
)
def git_retry(
repo_dir: str, *args: str, max_retries: int = 3, timeout: int = 30
) -> subprocess.CompletedProcess:
"""Git command with exponential backoff retry."""
import time
delays = [2, 4, 8]
last_result = None
for attempt in range(max_retries):
try:
last_result = git_run(repo_dir, *args, timeout=timeout)
except subprocess.TimeoutExpired:
last_result = subprocess.CompletedProcess(
["git", *args],
124,
"",
f"git {' '.join(args)} timed out after {timeout}s",
)
if last_result.returncode == 0:
return last_result
if attempt < max_retries - 1:
log.warning(
"git %s attempt %d/%d failed: %s — retrying in %ds",
" ".join(args),
attempt + 1,
max_retries,
last_result.stderr.strip(),
delays[attempt],
)
time.sleep(delays[attempt])
return last_result
def ensure_bridge_git_identity(
repo_dir: str,
*,
source_repo_dir: str | None = None,
) -> dict[str, Any]:
"""Copy the source repo git identity into the bridge repo as local config."""
source_dir = source_repo_dir or str(Path(__file__).resolve().parent)
def _cfg(repo: str, *cfg_args: str) -> str | None:
result = git_run(repo, *cfg_args, timeout=10)
if result.returncode != 0:
return None
value = result.stdout.strip()
return value or None
bridge_name = _cfg(repo_dir, "config", "--get", "user.name")
bridge_email = _cfg(repo_dir, "config", "--get", "user.email")
target_name = (
_cfg(source_dir, "config", "--get", "user.name")
or _cfg(source_dir, "config", "--global", "user.name")
or bridge_name
)
target_email = (
_cfg(source_dir, "config", "--get", "user.email")
or _cfg(source_dir, "config", "--global", "user.email")
or bridge_email
)
changed = False
if target_name and bridge_name != target_name:
result = git_run(repo_dir, "config", "user.name", target_name, timeout=10)
if result.returncode == 0:
bridge_name = target_name
changed = True
if target_email and bridge_email != target_email:
result = git_run(repo_dir, "config", "user.email", target_email, timeout=10)
if result.returncode == 0:
bridge_email = target_email
changed = True
return {
"changed": changed,
"user_name": bridge_name,
"user_email": bridge_email,
}
def _bridge_status_path(line: str) -> str:
"""Extract the repo-relative path from a git status --porcelain line."""
path = line[3:].strip()
if " -> " in path:
path = path.split(" -> ", 1)[1]
return path.replace("\\", "/").strip("/")
def is_generated_bridge_path(path: str) -> bool:
"""Return True for files/directories regenerated by bridge sync."""
rel = path.replace("\\", "/").strip("/")
if rel in BRIDGE_GENERATED_FILES or rel in BRIDGE_GENERATED_TEMP_FILES:
return True
if rel.endswith(".tmp"):
return any(rel.startswith(f"{dirname}/") for dirname in BRIDGE_GENERATED_DIRS)
return any(rel == d or rel.startswith(f"{d}/") for d in BRIDGE_GENERATED_DIRS)
def _bridge_generated_symlink_issues(repo_dir: str, limit: int = 3) -> list[str]:
"""Return generated bridge paths that are symlinks or escape the repo root."""
repo_root = Path(repo_dir).resolve()
flagged: list[str] = []
seen: set[str] = set()
def _record(path: Path) -> None:
rel = path.relative_to(repo_dir).as_posix()
if rel not in seen:
seen.add(rel)
flagged.append(rel)
for rel_name in sorted(BRIDGE_GENERATED_FILES | BRIDGE_GENERATED_DIRS):
path = Path(repo_dir) / rel_name
if not path.exists() and not path.is_symlink():
continue
if path.is_symlink():
_record(path)
if len(flagged) >= limit:
return flagged
continue
try:
resolved = path.resolve(strict=True)
except OSError:
_record(path)
if len(flagged) >= limit:
return flagged
continue
if resolved != repo_root and repo_root not in resolved.parents:
_record(path)
if len(flagged) >= limit:
return flagged
continue
if not path.is_dir():
continue
try:
for child in path.rglob("*"):
if not child.is_symlink():
continue
_record(child)
if len(flagged) >= limit:
return flagged
except OSError:
_record(path)
if len(flagged) >= limit:
return flagged
return flagged
def ensure_bridge_repo_ready(repo_dir: str) -> tuple[bool, str | None]:
"""Prepare the bridge repo for sync without discarding user-managed files.
Safe behavior:
- detached HEAD -> try to return to main
- conflicts in generated artifacts -> auto-reset to origin/main
- edits in generated artifacts -> discard/rebuild
- edits in user-managed files -> block sync and surface the paths
"""
branch = git_run(repo_dir, "rev-parse", "--abbrev-ref", "HEAD")
if branch.returncode != 0:
detail = (branch.stderr or branch.stdout).strip()
return False, f"cannot inspect bridge branch: {detail or 'unknown git error'}"
if branch.stdout.strip() == "HEAD":
checkout = git_run(repo_dir, "checkout", "main")
if checkout.returncode != 0:
git_run(repo_dir, "fetch", "origin")
checkout = git_run(repo_dir, "checkout", "-B", "main", "origin/main")
if checkout.returncode != 0:
detail = (checkout.stderr or checkout.stdout).strip()
return (
False,
f"bridge repo is detached and could not checkout main: {detail}",
)
symlink_issues = _bridge_generated_symlink_issues(repo_dir)
if symlink_issues:
shown = ", ".join(symlink_issues[:3])
return (
False,
f"bridge repo contains unsafe generated symlinks/escaped paths: {shown}",
)
status = git_run(repo_dir, "status", "--porcelain")
if status.returncode != 0:
detail = (status.stderr or status.stdout).strip()
return False, f"cannot inspect bridge status: {detail or 'unknown git error'}"
lines = [ln for ln in status.stdout.splitlines() if ln.strip()]
if not lines:
return True, None
conflict_lines = [ln for ln in lines if ln[:2] in _BRIDGE_CONFLICT_STATES]
if conflict_lines:
conflict_paths = [_bridge_status_path(ln) for ln in conflict_lines]
unsafe = [p for p in conflict_paths if not is_generated_bridge_path(p)]
if unsafe:
shown = ", ".join(unsafe[:3])
return (
False,
f"resolve bridge conflicts in user-managed files first: {shown}",
)
git_run(repo_dir, "rebase", "--abort")
git_run(repo_dir, "merge", "--abort")
git_run(repo_dir, "fetch", "origin")
reset = git_run(repo_dir, "reset", "--hard", "origin/main")
if reset.returncode != 0:
detail = (reset.stderr or reset.stdout).strip()
return False, f"failed to reset generated bridge conflicts: {detail}"
status = git_run(repo_dir, "status", "--porcelain")
if status.returncode != 0:
detail = (status.stderr or status.stdout).strip()
return (
False,
f"cannot re-check bridge status: {detail or 'unknown git error'}",
)
lines = [ln for ln in status.stdout.splitlines() if ln.strip()]
if not lines:
return True, None
dirty_paths = [_bridge_status_path(ln) for ln in lines]
unsafe = [p for p in dirty_paths if not is_generated_bridge_path(p)]
if unsafe:
shown = ", ".join(unsafe[:3])
return False, f"commit or stash bridge repo edits before sync: {shown}"
# Generated artifacts are safe to rebuild from DB state.
generated_paths = [
"shared.json",
"shared.js",
"index.json",
"entities_index.json",
".bridge_sync.lock",
"shared.tmp",
"shared.json.tmp",
"shared.js.tmp",
"index.json.tmp",
"entities_index.json.tmp",
"tasks",
"entities",
"attachments",
"public_knowledge",
"extended_memory",
]
restore = git_run(repo_dir, "checkout", "--", *generated_paths)
clean = git_run(repo_dir, "clean", "-fd", "--", *generated_paths)
if restore.returncode != 0 and clean.returncode != 0:
detail = ((restore.stderr or "") + " " + (clean.stderr or "")).strip()
return False, f"failed to discard generated bridge artifacts: {detail}"
status = git_run(repo_dir, "status", "--porcelain")
if status.returncode != 0:
detail = (status.stderr or status.stdout).strip()
return False, f"cannot verify bridge cleanup: {detail or 'unknown git error'}"
remaining = [
_bridge_status_path(ln) for ln in status.stdout.splitlines() if ln.strip()
]
unsafe = [p for p in remaining if not is_generated_bridge_path(p)]
if unsafe:
shown = ", ".join(unsafe[:3])
return False, f"bridge repo still has user-managed edits after cleanup: {shown}"
return True, None
def source_hash(name: str, entity_type: str, observations: list) -> str:
"""SHA256 hash for entity deduplication."""
raw = json.dumps({"n": name, "t": entity_type, "o": observations}, sort_keys=True)
return hashlib.sha256(raw.encode()).hexdigest()
# ── Timestamp helpers ────────────────────────────────────────────────────
def now_iso() -> str:
"""ISO 8601 UTC timestamp."""
return datetime.now(timezone.utc).isoformat()
def _sqlite_table_exists(conn: sqlite3.Connection, table_name: str) -> bool:
row = conn.execute(
"SELECT 1 FROM sqlite_master WHERE type='table' AND name = ?",
(table_name,),
).fetchone()
return row is not None
def _sqlite_has_column(
conn: sqlite3.Connection, table_name: str, column_name: str
) -> bool:
try:
rows = conn.execute(f"PRAGMA table_info('{table_name}')").fetchall()
except sqlite3.OperationalError:
return False
# PRAGMA table_info columns: (cid, name, type, notnull, dflt_value, pk).
# Use positional access so this works whether the caller's connection has
# row_factory=sqlite3.Row set or returns plain tuples (bin/task opens a
# raw connection without row_factory).
return any(r[1] == column_name for r in rows)
def _new_event_id() -> str:
return uuid.uuid4().hex
def _json_text(value: Any) -> str | None:
if value is None:
return None
if isinstance(value, str):
return value
try: