-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.py
More file actions
2908 lines (2529 loc) · 117 KB
/
Copy pathmain.py
File metadata and controls
2908 lines (2529 loc) · 117 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
import asyncio
import fnmatch
import hashlib
import logging
import os
import re
import sqlite3
import tempfile
import threading
import time
from dataclasses import dataclass, field
from datetime import datetime, timedelta, timezone
from logging.handlers import RotatingFileHandler
from pathlib import Path
from uuid import uuid4
import tiktoken
from chromadb import PersistentClient
try:
from mcp.server.fastmcp import FastMCP
except ImportError:
import importlib.metadata
import sys
version = importlib.metadata.version("mcp")
print(
f"ImportError: FastMCP not found in mcp.server.fastmcp. "
f"SDK version {version} detected. Expected <2.0.0.",
file=sys.stderr,
)
sys.exit(1)
from ollama import Client
from openai import OpenAI
from code_indexer import extract_entities, get_supported_extensions
from config import (
CLOUD_ESCALATION_KEYWORDS,
CLOUD_ESCALATION_WORD_COUNT,
DB_PATH,
DEEPSEEK_API_KEY,
DEEPSEEK_BASE_URL,
DEEPSEEK_MODEL_FAST,
DEEPSEEK_MODEL_PRO,
DEFAULT_MEMORY_MODE,
ENABLE_DEEPSEEK_PRO,
ENABLE_LEXICAL_RERANK,
ENABLE_TOKEN_TRACKING,
FETCH_CAP,
LEXICAL_RERANK_WEIGHT,
OLLAMA_HOST,
OLLAMA_MAX_CONCURRENCY,
OLLAMA_MODEL,
QUERY_DISTANCE_THRESHOLD,
SKIP_BARE_FILES,
SYNTHESIZE_WITH_CLOUD,
ZERIKAI_DB,
get_deepseek_pricing,
is_deepseek_peak_hour,
)
# Format string for every log line via the logging module. Layout:
# asctime, levelname (8-char padded), logger name, em-dash, message.
# Applied in logging.basicConfig to both StreamHandler and the
# RotatingFileHandler writing to .brain/server.log. Free-form printf
# style — no valid range; edit the string to reshape log output.
_LOG_FORMAT = "%(asctime)s %(levelname)-8s %(name)s — %(message)s"
_log_dir = DB_PATH # .brain/ — already in .memignore via *.log
# Ensure .brain/ exists before we try to write the log file
_log_dir.mkdir(parents=True, exist_ok=True)
logging.basicConfig(
level=logging.INFO,
format=_LOG_FORMAT,
handlers=[
# Live output captured by the IDE / terminal
logging.StreamHandler(),
# Persistent file — 5 MB cap, 2 rolling backups
RotatingFileHandler(
filename=_log_dir / "server.log",
maxBytes=5 * 1024 * 1024,
backupCount=2,
encoding="utf-8",
),
],
)
log = logging.getLogger("universal-brain")
log.info("=" * 60)
log.info("Universal Brain MCP Server starting")
log.info("DB_PATH : %s", DB_PATH.resolve())
log.info("Ollama host: %s", OLLAMA_HOST)
log.info("Ollama model: %s", OLLAMA_MODEL)
log.info("Default mode: %s", DEFAULT_MEMORY_MODE)
log.info("=" * 60)
# ---------------------------------------------------------------------------
# Atomic file write helper
# ---------------------------------------------------------------------------
def _atomic_write_text(path: Path, content: str, retries: int = 3) -> None:
"""Write text to a file atomically: temp file in same dir, then os.replace().
Guarantees the target is always old-or-new, never truncated — a crash
mid-write leaves the previous content intact. Atomic on Windows, macOS,
and Linux because the temp file lives in path.parent (same filesystem).
Retries on Windows sharing violations (destination open by another
process, e.g. an editor tab) with a brief backoff before giving up.
Side effect: writes to filesystem; cleans up the temp file on failure.
"""
for attempt in range(retries):
fd, tmp = tempfile.mkstemp(dir=path.parent, suffix=".tmp")
try:
with os.fdopen(fd, "w", encoding="utf-8") as f:
f.write(content)
f.flush()
os.fsync(f.fileno()) # durability before rename
os.replace(tmp, path) # atomic swap
return
except PermissionError:
os.unlink(tmp)
if attempt == retries - 1:
raise
time.sleep(0.1) # brief backoff, then retry
except BaseException:
os.unlink(tmp)
raise
# ---------------------------------------------------------------------------
# MCP Server
# ---------------------------------------------------------------------------
mcp = FastMCP("UniversalBrain")
# ---------------------------------------------------------------------------
# ChromaDB — single client, collections are per-workspace (created on demand)
# ---------------------------------------------------------------------------
_db_lock = threading.Lock()
_vector_db_path = DB_PATH / "vector_db"
_vector_db_path.mkdir(parents=True, exist_ok=True)
db_client = PersistentClient(path=str(_vector_db_path))
# ---------------------------------------------------------------------------
# DeepSeek client
# ---------------------------------------------------------------------------
ds_client = OpenAI(api_key=DEEPSEEK_API_KEY, base_url=DEEPSEEK_BASE_URL)
# ---------------------------------------------------------------------------
# Ollama client
# ---------------------------------------------------------------------------
ol_client = Client(host=OLLAMA_HOST)
# Local concurrency semaphore for local synthesis/briefs
ollama_semaphore = asyncio.Semaphore(OLLAMA_MAX_CONCURRENCY)
# ---------------------------------------------------------------------------
# Token usage tracking database
# ---------------------------------------------------------------------------
def _init_db():
"""Initialise zerikai.db via sqlite3: creates token_usage and
workspace_registry tables (IF NOT EXISTS), auto-migrates missing
columns (e.g. estimated_cost_usd), creates indices, and enables
WAL mode. Skips entirely if ENABLE_TOKEN_TRACKING is disabled.
Idempotent — safe to call on every startup.
"""
if not ENABLE_TOKEN_TRACKING:
return
conn = sqlite3.connect(str(ZERIKAI_DB), timeout=10)
# allows concurrent reads during writes
conn.execute("PRAGMA journal_mode=WAL")
# Create token tracking table
conn.execute("""
CREATE TABLE IF NOT EXISTS token_usage (
id INTEGER PRIMARY KEY AUTOINCREMENT,
timestamp TEXT NOT NULL,
workspace_id TEXT NOT NULL,
operation TEXT NOT NULL,
model TEXT NOT NULL,
prompt_tokens INTEGER NOT NULL,
completion_tokens INTEGER NOT NULL,
cache_hit_tokens INTEGER NOT NULL,
cache_miss_tokens INTEGER NOT NULL,
estimated_cost_usd REAL NOT NULL
)
""")
# Migrate existing table: add estimated_cost_usd column if missing
cursor = conn.cursor()
cursor.execute("PRAGMA table_info(token_usage)")
columns = [row[1] for row in cursor.fetchall()]
if "estimated_cost_usd" not in columns:
log.info("Migrating token_usage table: adding estimated_cost_usd column")
conn.execute(
"ALTER TABLE token_usage ADD COLUMN estimated_cost_usd REAL DEFAULT 0.0"
)
conn.execute("""
CREATE INDEX IF NOT EXISTS idx_workspace_timestamp
ON token_usage(workspace_id, timestamp)
""")
conn.execute("""
CREATE INDEX IF NOT EXISTS idx_timestamp
ON token_usage(timestamp)
""")
# Create workspace registry table
conn.execute("""
CREATE TABLE IF NOT EXISTS workspace_registry (
workspace_uuid TEXT PRIMARY KEY,
workspace_path TEXT NOT NULL UNIQUE,
display_name TEXT NOT NULL,
created_at TEXT NOT NULL,
last_scanned TEXT,
last_brief_update TEXT
)
""")
conn.execute("""
CREATE INDEX IF NOT EXISTS idx_workspace_path
ON workspace_registry(workspace_path)
""")
conn.commit()
conn.close()
def _track_token_usage(
workspace_id: str,
operation: str,
model: str,
usage: object,
):
"""Record DeepSeek API token usage and estimated cost to zerikai.db sqlite3.
Best-effort: returns silently if ENABLE_TOKEN_TRACKING is disabled,
usage is None, or insert fails. Routes pricing via get_deepseek_pricing()
('v4-pro' vs 'v4-flash') at the UTC time of the call. Side effect: inserts
one row per call into token_usage table.
Args:
workspace_id: The workspace identifier
operation: Type of operation (query, brief_synthesis, etc.)
model: Model name (deepseek-v4-flash, deepseek-v4-pro)
usage: OpenAI usage object from API response
"""
if not ENABLE_TOKEN_TRACKING or not usage:
return
try:
# Extract token counts
prompt_tokens = getattr(usage, "prompt_tokens", 0)
completion_tokens = getattr(usage, "completion_tokens", 0)
cache_hit = getattr(usage, "prompt_cache_hit_tokens", 0)
cache_miss = getattr(usage, "prompt_cache_miss_tokens", 0)
# Determine pricing tier (time-aware — resolves peak vs off-peak at call time)
model_key = "v4-pro" if "pro" in model.lower() else "v4-flash"
pricing = get_deepseek_pricing(model_key)
# Calculate cost: cache hits + cache misses + output
cost = (
(cache_hit / 1_000_000) * pricing["cache_hit"]
+ (cache_miss / 1_000_000) * pricing["input"]
+ (completion_tokens / 1_000_000) * pricing["output"]
)
# Store in database
with sqlite3.connect(str(ZERIKAI_DB), timeout=10) as conn:
conn.execute(
"""
INSERT INTO token_usage (
timestamp, workspace_id, operation, model,
prompt_tokens, completion_tokens,
cache_hit_tokens, cache_miss_tokens, estimated_cost_usd
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
(
datetime.now(timezone.utc).isoformat(),
workspace_id,
operation,
model,
prompt_tokens,
completion_tokens,
cache_hit,
cache_miss,
cost,
),
)
log.info(
"Token tracking | workspace=%s | operation=%s | cost=$%.6f",
workspace_id,
operation,
cost,
)
except Exception as exc:
log.error("Token tracking failed: %s", exc)
# Initialize database (token tracking + workspace registry) on startup
_init_db()
# ---------------------------------------------------------------------------
# Workspace helpers
# ---------------------------------------------------------------------------
def _derive_workspace_id(workspace_path: str) -> tuple[str, str]:
"""Derive a stable workspace UUID from a filesystem path via zerikai.db sqlite3.
Normalizes the path (case, separators, trailing slashes), then looks
up or creates a workspace_registry entry. Subsequent calls with the
same path return the same UUID. Deterministic per path. Side effect:
inserts a new row on first call for each unique path.
Args:
workspace_path: Filesystem path to the workspace
Returns:
tuple: (workspace_uuid, display_name)
"""
if not workspace_path:
return ("default", "default")
# Aggressive normalization to prevent duplicate workspace IDs due to:
# - Case differences (d:\ vs D:\)
# - Separator differences (/ vs \)
# - Relative vs absolute paths
# - Trailing slashes
# - Symlinks/junctions (on Windows)
# Step 1: Strip trailing slashes/backslashes
workspace_path = workspace_path.rstrip("/\\")
# Step 2: Convert to absolute path using os.path.abspath
if not os.path.isabs(workspace_path):
workspace_path = os.path.abspath(workspace_path)
# Step 3: Normalize path separators and case
# os.path.normcase handles platform-specific case-sensitivity correctly
normalized_path = os.path.normcase(os.path.normpath(workspace_path))
# Step 4: Use forward slashes as canonical separator
normalized_path = normalized_path.replace("\\", "/")
# Step 5: Extract folder name for display name
folder_name = os.path.basename(normalized_path)
display_name = re.sub(r"[^a-z0-9]+", "_", folder_name.lower()).strip("_")
# Step 6: Look up or create workspace registry entry
try:
conn = sqlite3.connect(str(ZERIKAI_DB), timeout=10)
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
# Try to find existing workspace by normalized path
cursor.execute(
"SELECT workspace_uuid, display_name FROM workspace_registry WHERE workspace_path = ?",
(normalized_path,),
)
row = cursor.fetchone()
if row:
# Existing workspace found
workspace_uuid = row["workspace_uuid"]
stored_display_name = row["display_name"]
conn.close()
log.debug(
f"Workspace ID lookup: '{workspace_path}' → '{normalized_path}' → {workspace_uuid} ({stored_display_name})"
)
return (workspace_uuid, stored_display_name)
# No existing workspace - create new UUID and register it
workspace_uuid = str(uuid4())
created_at = datetime.now(timezone.utc).isoformat()
cursor.execute(
"""
INSERT INTO workspace_registry (workspace_uuid, workspace_path, display_name, created_at)
VALUES (?, ?, ?, ?)
""",
(workspace_uuid, normalized_path, display_name, created_at),
)
conn.commit()
conn.close()
log.info(
f"New workspace registered: '{workspace_path}' → '{normalized_path}' → {workspace_uuid} ({display_name})"
)
return (workspace_uuid, display_name)
except Exception as exc:
log.error(f"Workspace ID derivation failed for '{workspace_path}': {exc}")
# Fallback: generate ephemeral UUID (won't persist, but allows operation to continue)
return (str(uuid4()), display_name)
def _resolve_workspace(identifier: str) -> tuple[str, str, str]:
"""Resolve a workspace identifier via zerikai.db sqlite3 to (uuid, name, path).
Three-tier routing: exact UUID match → short UUID (first 8+ chars)
LIKE match → display_name exact match. Reads from workspace_registry
table. Pure read — no side effects.
Args:
identifier: Full UUID, short UUID (first 8+ chars), or display name
Returns:
tuple: (workspace_uuid, display_name, workspace_path)
Raises:
ValueError: If no workspace matches the identifier
"""
try:
conn = sqlite3.connect(str(ZERIKAI_DB), timeout=10)
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
# Try exact UUID match
cursor.execute(
"SELECT workspace_uuid, display_name, workspace_path FROM workspace_registry WHERE workspace_uuid = ?",
(identifier,),
)
row = cursor.fetchone()
# Try short UUID match (first 8+ chars)
if not row and len(identifier) >= 8:
cursor.execute(
"SELECT workspace_uuid, display_name, workspace_path FROM workspace_registry WHERE workspace_uuid LIKE ?",
(f"{identifier}%",),
)
row = cursor.fetchone()
# Try display name match
if not row:
cursor.execute(
"SELECT workspace_uuid, display_name, workspace_path FROM workspace_registry WHERE display_name = ?",
(identifier,),
)
row = cursor.fetchone()
conn.close()
if not row:
raise ValueError(
f"No workspace found matching '{identifier}'. "
f"Run `list_workspaces` to see available workspaces."
)
return (row["workspace_uuid"], row["display_name"], row["workspace_path"])
except Exception as exc:
if isinstance(exc, ValueError):
raise
log.error(f"Workspace resolution failed for '{identifier}': {exc}")
raise ValueError(f"Could not resolve workspace '{identifier}': {exc}")
# Placeholder string inserted into .brain/contexts/<id>.md after init_workspace.
# Detected by _background_scan to trigger first-time brief synthesis via
# DeepSeek or Ollama after scan completes. Replaced by the generated brief.
UNINITIALIZED_MARKER = "<!-- ZERIKAI_PENDING_SYNTHESIS -->"
def _truncate_for_brief(doc: str) -> str:
"""Truncate a docstring to its first sentence for cheap brief synthesis.
Skips leading blank lines, joins remaining text, then splits at the
first period+space found after position 20. Used by _build_section
to keep DeepSeek/Ollama prompt context compact. Pure, deterministic.
"""
lines = doc.strip().split("\n")
meaningful = []
for line in lines:
stripped = line.strip()
if not stripped:
continue
meaningful.append(stripped)
result = " ".join(meaningful)
dot = result.find(". ")
if dot > 20:
result = result[: dot + 1]
return result
async def _build_section(
section: dict,
collection,
display_name: str,
use_cloud: bool,
workspace_id: str,
) -> tuple[str, str]:
"""Build one brief section: queries ChromaDB, lexically re-ranks,
and synthesizes via DeepSeek or Ollama. Runs in parallel via
asyncio.gather across all 9 sections. Lexical re-ranking boosts
results by keyword overlap in entity name, docstring, and
source_file. Trims to per-section fetch_cap before LLM call.
Side effect: writes token usage to zerikai.db sqlite3.
Args:
section: Dict with query, prompt_template, heading, optional
fetch_cap (default 20) and full_context (bool).
collection: ChromaDB collection for this workspace.
display_name: Project name for prompt formatting.
use_cloud: True → DeepSeek, False → Ollama.
workspace_id: UUID for _track_token_usage logging.
Returns:
(heading, content) on success, (heading, error) on failure.
"""
heading = section["heading"]
log.info("_synthesize_deep_brief | Generating: %s", heading)
try:
with _db_lock:
total_docs = collection.count()
# Fetch a wide pool (up to 75) for re-ranking, then trim to
# the per-section fetch_cap before sending to the LLM.
# This lets the re-rank pull in semantically-distant but
# keyword-relevant files (e.g. todo.md, ROADMAP.md).
pool_size = min(FETCH_CAP, total_docs) if total_docs > 0 else 1
results = collection.query(
query_texts=[section["query"]],
n_results=pool_size,
where={"category": "codebase"},
include=["documents", "metadatas", "distances"],
)
docs = results.get("documents", [[]])[0]
metas = results.get("metadatas", [[]])[0]
distances = results.get("distances", [[]])[0]
if not docs:
with _db_lock:
fallback = collection.get(
where={"category": "codebase"}, limit=pool_size
)
docs = fallback.get("documents", [])
metas = fallback.get("metadatas", [])
distances = [1.0] * len(docs)
# ── Lexical re-rank: boost results whose filename, entity name, or
# content share keywords with the section query. Same scoring
# formula used by query_memory, extended with source_file so that
# files named todo.md, ROADMAP.md, CHANGELOG.md surface naturally.
query_terms = set(section["query"].lower().split())
scored = []
for doc, meta, dist in zip(docs, metas or [{}] * len(docs), distances):
if (meta or {}).get("source_type") == "manual":
continue
name = (meta or {}).get("name", "").lower()
text = doc.lower()
src_file = (meta or {}).get("source_file", "").lower()
hits = sum(
1 for t in query_terms if t in name or t in text or t in src_file
)
score = (1 / dist) + (hits * LEXICAL_RERANK_WEIGHT)
scored.append((score, doc, meta))
scored.sort(key=lambda x: x[0], reverse=True)
# Trim to per-section cap for LLM cost control
llm_cap = section.get("fetch_cap", 20)
scored = scored[:llm_cap]
context_parts = []
for _score, doc, meta in scored:
src = (meta or {}).get("source_file", "")
header = f"### {src}\n" if src else ""
if section.get("full_context"):
context_parts.append(f"{header}{doc}")
else:
context_parts.append(f"{header}{_truncate_for_brief(doc)}")
context = "\n\n".join(context_parts)
prompt = section["prompt_template"].format(context=context)
if use_cloud:
response = await asyncio.to_thread(
ds_client.chat.completions.create,
model=DEEPSEEK_MODEL_FAST,
messages=[
{
"role": "system",
"content": "You are a senior software architect.",
},
{"role": "user", "content": prompt},
],
temperature=0,
max_tokens=2048,
)
content = response.choices[0].message.content.strip()
usage = getattr(response, "usage", None)
if usage:
_track_token_usage(
workspace_id, "brief_synthesis", DEEPSEEK_MODEL_FAST, usage
)
else:
result = await asyncio.to_thread(
ol_client.generate,
model=OLLAMA_MODEL,
prompt=prompt,
options={"temperature": 0},
)
content = result["response"].strip()
log.info("_synthesize_deep_brief | \u2713 %s complete", heading)
return (heading, content)
except Exception as exc:
log.error("_synthesize_deep_brief | Failed on %s: %s", heading, exc)
return (heading, f"(Section generation failed: {exc})")
async def _synthesize_deep_brief(
workspace_id: str, display_name: str, use_cloud: bool = True
) -> str:
"""Build a 9-section project brief via parallel ChromaDB queries.
Fires all section-specific queries via asyncio.gather, delegating
each to _build_section. Routes to DeepSeek or Ollama based on
SYNTHESIZE_WITH_CLOUD. Side effect: saves assembled markdown to
.brain/contexts/<id>.md. Overwrites existing brief.
Args:
workspace_id: The workspace UUID (for collection access)
display_name: Human-readable project name (for brief title and prompts)
use_cloud: If True, uses DeepSeek for higher quality (small cost).
If False, uses Ollama (free, may include noise).
"""
log.info(
"_synthesize_deep_brief | Starting iterative synthesis for %s (%s)",
display_name,
workspace_id,
)
collection = _get_collection(workspace_id)
# Check if we have any codebase data at all
with _db_lock:
check = collection.get(where={"category": "codebase"}, limit=1)
if not check.get("documents"):
return (
f"# Project Brief: {display_name}\n\nNo codebase files found during scan."
)
# Section definitions with semantic queries and format-guided prompts
sections = [
{
"heading": "## Overview",
"query": "What is this project's purpose, main features, external services it integrates with, who it is designed for, and what does the README say about the project overview?",
"prompt_template": (
f"You are a senior software architect analyzing the `{display_name}` project. "
"Based on the following file summaries from the codebase, write the Overview section. "
"Be concise and direct. Do not preface your answer with any introductory sentence.\n\n"
"Use this format:\n"
f"`{display_name}` is a [type] system designed to [purpose]. "
"State the key technologies used (parsing, storage, LLMs, protocols). "
"Name the external services or APIs it integrates with and their role. "
"State who it is designed for and in what context it operates.\n\n"
f"Do not add new sections or headings — this is one continuous paragraph.\n\n"
"=== CODEBASE SUMMARIES ===\n"
"{context}\n\n"
"Write the Overview section:"
),
},
{
"heading": "## Technical Stack",
"query": "What are the primary dependencies, libraries, frameworks, and databases used in this project? List the language, frameworks, data storage, interfaces (API, CLI, web, MCP), and key libraries.",
"prompt_template": (
f"You are a senior software architect analyzing the `{display_name}` project. "
"Based on the following file summaries from the codebase, list the Technical Stack. "
"Be concise and direct. Start directly with 'Listing only primary libraries, max 5:' — no other introductory text.\n\n"
"IMPORTANT: Only list the 5-10 most important PRIMARY dependencies. "
"Omit transitive dependencies, low-level utilities, and standard library modules. "
"Focus on frameworks, databases, APIs, and major integrations that define the project's architecture.\n\n"
"Use this format:\n\n"
"* **Language:** [Python, JavaScript, TypeScript, etc.]\n"
"* **Frameworks:** [Server, web, MCP frameworks — omit if none]\n"
"* **Data Storage:** [Database, vector store, file-based, etc.]\n"
"* **Interfaces:** [API, CLI, web, MCP — omit any that do not apply]\n"
"* **Libraries:**\n"
" * [Category]: [Library names]\n\n"
"=== CODEBASE SUMMARIES ===\n"
"{context}\n\n"
"List the Technical Stack:"
),
},
{
"heading": "## Core Architecture",
"query": "How is this project structured? Describe the architectural layers — entry points, processing pipeline, data storage, code indexing, and LLM integration.",
"full_context": True,
"fetch_cap": 25,
"prompt_template": (
f"You are a senior software architect analyzing the `{display_name}` project. "
"Based on the following file summaries from the codebase, describe the Core Architecture. "
"Be concise and direct. Start directly with 'The application consists of the following layers:' — no other introductory text.\n\n"
"Use this format:\n\n"
"The application consists of the following layers:\n\n"
"1. **[Layer Name]:** [Technology and what it handles]\n"
"2. **[Layer Name]:** [Technology and what it handles]\n\n"
"Name each layer based on what you find in the summaries. "
"Omit any layer that does not exist in the codebase.\n\n"
"=== CODEBASE SUMMARIES ===\n"
"{context}\n\n"
"Describe the Core Architecture:"
),
},
{
"heading": "## Primary Conventions",
"query": "What conventions, patterns, and standards does this project follow? Describe the code organization, naming conventions, error handling, docstring style, file ignore rules, and any other conventions evident in the codebase.",
"prompt_template": (
f"You are a senior software architect analyzing the `{display_name}` project. "
"Based on the following file summaries from the codebase, list the Primary Conventions. "
"Be concise and direct. Start directly with the first bullet point — no introductory text.\n\n"
"Use this format for any sections that apply:\n"
"* **Code Organization:** [How code is structured into directories/modules]\n"
"* **Naming Conventions:** [Prefix patterns like _private, UPPER_CASE constants]\n"
"* **File Ignore Rules:** [How .memignore or similar patterns are handled]\n"
"* **Docstring Style:** [Convention used]\n"
"* **Error Handling & Logging:** [Method and mechanism]\n"
"* **Database Schema:** [Where defined and how updated]\n\n"
"Omit any section that does not apply. Only include categories evident "
"in the codebase. Do not add any other sections.\n\n"
"=== CODEBASE SUMMARIES ===\n"
"{context}\n\n"
"List the Primary Conventions:"
),
},
{
"heading": "## Purpose",
"query": "What problem does this project solve? What is its goal, who is it for, and what technologies does it use to achieve that goal?",
"prompt_template": (
f"You are a senior software architect analyzing the `{display_name}` project. "
"Based on the following file summaries from the codebase, explain the Purpose. "
"Be concise and direct. Do not preface your answer with any introductory sentence.\n\n"
"Use this format:\n"
f"`{display_name}` aims to [goal] using [technologies] to solve [problem]. "
"It is designed for [audience].\n\n"
"=== CODEBASE SUMMARIES ===\n"
"{context}\n\n"
"Explain the Purpose:"
),
},
{
"heading": "## Key Files & Directories",
"query": "What are the key files and directories in this project? List the entry point, configuration, core modules, documentation, and storage directories with their purposes.",
"prompt_template": (
f"You are a senior software architect analyzing the `{display_name}` project. "
"Based on the following file summaries from the codebase, identify Key Files & Directories. "
"Be concise and direct. Start directly with the first bullet point — no introductory text.\n\n"
"Use this format:\n"
"* **`path/to/file.ext`** - [Brief purpose]\n"
"* **`directory/`** - [What this directory contains]\n\n"
"Focus on entry points, configuration, core modules, key directories, "
"and project documentation. Omit test files, CI configs, and generic items.\n\n"
"=== CODEBASE SUMMARIES ===\n"
"{context}\n\n"
"List Key Files & Directories:"
),
},
{
"heading": "## Development & Testing",
"query": "How do you set up, run, test, and deploy this project? What are the installation steps, startup commands, test framework, and build or deployment process?",
"prompt_template": (
f"You are a senior software architect analyzing the `{display_name}` project. "
"Based on the following file summaries from the codebase, describe Development & Testing setup. "
"Be concise and direct. Start directly with the first bullet point — no introductory text.\n\n"
"Use this format:\n"
"* **Setup:** [How to install dependencies and prepare environment]\n"
"* **Running Locally:** [Command or method to start the project]\n"
"* **Testing:** [Test framework and command to run tests — omit if none]\n"
"* **Build/Deploy:** [Build process or containerization — omit if none]\n\n"
"If a category has no information in the summaries, omit it. "
"Do not fabricate details.\n\n"
"=== CODEBASE SUMMARIES ===\n"
"{context}\n\n"
"Describe Development & Testing:"
),
},
{
"full_context": True,
"fetch_cap": 25,
"heading": "## Data Flow & Request Lifecycle",
"query": "How does a request flow through this project? Describe the entry point, processing pipeline, data access, response generation, and authentication if present.",
"prompt_template": (
f"You are a senior software architect analyzing the `{display_name}` project. "
"Based on the following file summaries from the codebase, describe the Data Flow & Request Lifecycle. "
"Be concise and direct. Start directly with 'A typical request flows through:' — no other introductory text.\n\n"
"Use this format:\n"
"A typical request flows through:\n\n"
"1. **[Entry Point]:** [What happens first]\n"
"2. **[Processing Layer]:** [How request is processed]\n"
"3. **[Data Layer]:** [How data is accessed/modified]\n"
"4. **[Response]:** [How response is generated]\n\n"
"Include authentication flow only if present in the summaries. "
"Do not fabricate details.\n\n"
"=== CODEBASE SUMMARIES ===\n"
"{context}\n\n"
"Describe Data Flow & Request Lifecycle:"
),
},
{
"heading": "## Future Roadmap",
"query": "What planned features, TODOs, FIXMEs, roadmap items, or future improvements are documented in this codebase?",
"full_context": True,
"fetch_cap": 30,
"prompt_template": (
f"You are a senior software architect analyzing the `{display_name}` project. "
"Based on the following file summaries from the codebase (look for TODOs, FIXME, comments about future changes, documented roadmaps, or explicit plans), "
"describe the Future Roadmap. "
"Be concise and direct. Start directly with the first planned item or milestone — no introductory text.\n\n"
"Use this format:\n"
"1. **Phase/Feature Title:** [Description of planned improvement]\n"
"2. **[Next Title]:** [Description...]\n\n"
"IMPORTANT: If no clear future plans, TODOs, or roadmap items are found in the code or documentation, "
"respond ONLY with: 'No future roadmap specified in the codebase.'\n\n"
"DO NOT suggest or infer plans. Only report what is explicitly documented.\n\n"
"=== CODEBASE SUMMARIES ===\n"
"{context}\n\n"
"Describe the Future Roadmap:"
),
},
]
async def _build_section_safe(s: dict):
"""Wrapper to gate Ollama calls via semaphore during local synthesis."""
if not use_cloud:
async with ollama_semaphore:
return await _build_section(
s, collection, display_name, use_cloud, workspace_id
)
return await _build_section(
s, collection, display_name, use_cloud, workspace_id
)
tasks = [_build_section_safe(s) for s in sections]
results = await asyncio.gather(*tasks)
brief_parts = [f"# Project Brief: {display_name}\n"]
for heading, content in results:
brief_parts.append(f"\n{heading}\n\n{content}\n")
final_brief = "".join(brief_parts)
log.info("_synthesize_deep_brief | Complete for %s", workspace_id)
return final_brief
# ---------------------------------------------------------------------------
# Background scan progress tracking
# ---------------------------------------------------------------------------
@dataclass
class ScanProgress:
"""Tracks progress of a background workspace scan. Written by
_background_scan during file processing and _background_brief_synthesis
for brief_status transitions (pending → running → Complete/Failed).
Read by scan_status for user-facing progress reports. Plain dataclass
— no methods, no side effects beyond field mutation by callers.
"""
workspace_id: str
display_name: str
total_files: int
scanned: int = 0
entities: int = 0
skipped: int = 0
errors: int = 0
started_at: float = field(
default_factory=lambda: datetime.now(timezone.utc).timestamp()
)
completed: bool = False
brief_status: str = "pending" # pending, running, complete, failed
# Module-level registry of active/recent scans, keyed by workspace_id
_scans: dict[str, ScanProgress] = {}
_scan_tasks: dict[str, asyncio.Task] = {}
async def _background_brief_synthesis(
workspace_id: str,
display_name: str,
context_file: Path,
progress: ScanProgress | None = None,
) -> None:
"""Fire-and-forget brief synthesis after scan to avoid MCP timeouts.
Delegates to _synthesize_deep_brief (cloud/local via
SYNTHESIZE_WITH_CLOUD). Creates/overwrites .brain/contexts/<id>.md.
Updates progress.brief_status to 'Complete' or 'Failed'. Launched
via asyncio.create_task — no await, no return value.
"""
try:
new_brief = await _synthesize_deep_brief(
workspace_id, display_name, use_cloud=SYNTHESIZE_WITH_CLOUD
)
_atomic_write_text(context_file, new_brief)
if progress:
progress.brief_status = "Complete"
log.info("_background_brief_synthesis | brief saved for %s", display_name)
except Exception as exc:
if progress:
progress.brief_status = "Failed"
log.error("_background_brief_synthesis | failed for %s: %s", display_name, exc)
def _get_collection(workspace_id: str):
"""Return the ChromaDB PersistentClient collection for a workspace.
Uses db_client.get_or_create_collection with name `memory_{id}`.
Idempotent — creates on first call, reuses thereafter. Thread-safe
when callers hold _db_lock. No other side effects.
"""
return db_client.get_or_create_collection(f"memory_{workspace_id}")
def _load_project_context(workspace_id: str) -> str:
"""Load the per-workspace project brief from .brain/contexts/<id>.md.
Used as the stable prefix for DeepSeek KV cache optimisation via
_build_system_message. Creates contexts/ directory on first call.
Falls back to a placeholder string if no brief file exists. Pure
read — no writes beyond mkdir.
"""
context_dir = Path(DB_PATH) / "contexts"
context_dir.mkdir(parents=True, exist_ok=True)
context_file = context_dir / f"{workspace_id}.md"
if context_file.exists():
return context_file.read_text(encoding="utf-8").strip()
# Placeholder — functional but won't produce meaningful cache hits
# until you populate the file with real project context.
return (
f"Project workspace: {workspace_id}\n"
"No project brief found. Run the `init_workspace` tool to create one."
)
def _get_score_tuple(evidence_item: dict) -> tuple[float | None, str]:
"""Return score and label from an evidence dict for citation formatting.
Routing: prefers 'rerank_score' (label 'rerank'); falls back to
ChromaDB 'l2_distance' (label 'L2') when rerank is absent. Returns
(None, 'L2') when neither key is present. Pure, deterministic.
"""
score = evidence_item.get("rerank_score")
score_label = "rerank"
if score is None:
score = evidence_item.get("l2_distance")
score_label = "L2"
return score, score_label
def _build_system_message(workspace_id: str) -> str:
"""Assemble the DeepSeek system message with tiktoken for KV cache optimisation.
Concatenates a fixed role instruction with the per-workspace project
brief from _load_project_context. The identical prefix maximises
DeepSeek KV cache hits across calls (best-effort, no guarantees).
Logs token count via tiktoken's cl100k_base encoding. Pure read-only.
"""
role_instruction = (
"You are a project memory assistant. "
"Your role is to synthesize retrieved project context and answer "
"the developer's query accurately and concisely. "
"Prioritise specifics over generalities. "
"Do not repeat the retrieved context verbatim.\n\n"
"=== STRICT ATTRIBUTION RULES ===\n"
"1. GROUNDING: Base your answer EXCLUSIVELY on the provided context. If the information is not present, say 'I don't have this information'.\n"
"2. SIGNATURE TRUTH: When explaining a function or class, use only the signature and logic provided in its specific context block. Do not attribute logic from helper functions (e.g., _extract_*) to the top-level caller unless explicitly stated in that caller's block.\n"
"3. NO HALLUCINATION: Do not invent parameters, return types, or implementation details. Verify every claim against the context.\n"
"4. INLINE CITATIONS: When you state a fact drawn from a specific source, cite it inline immediately "
"after the claim using the format: #file:line | score L2 or rerank\n"
' Example: "The brief is loaded via _load_project_context (#main.py:810 | 0.72 L2)."\n'
" Only cite sources that are present in the provided context. Do not fabricate file paths, line numbers, or scores.\n\n"
"=== PROJECT BRIEF ===\n"
)
project_context = _load_project_context(workspace_id)
full_message = role_instruction + project_context
# Per https://api-docs.deepseek.com/guides/kv_cache:
# - Cache persists at request boundaries and detects common prefixes automatically
# - Prefix matching works from token 0
# - Cache units are created at fixed intervals for long inputs
# - No explicit minimum length requirement; cache works on "best-effort" basis
try:
enc = tiktoken.get_encoding("cl100k_base")
token_count = len(enc.encode(full_message))
log.debug("_build_system_message | System message: %d tokens", token_count)
except Exception as exc:
log.warning("_build_system_message | Token count failed: %s", exc)
return full_message
# ---------------------------------------------------------------------------
# .memignore helpers
# ---------------------------------------------------------------------------
# Text extensions we are willing to read and summarise.
_TEXT_EXTENSIONS = {
".py",
".pyw",
".js",
".ts",
".jsx",
".tsx",
".md",
".txt",
".rst",
".json",
".yaml",
".yml",
".toml",