cortex-claude 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- cortex_claude/__init__.py +1 -0
- cortex_claude/__main__.py +10 -0
- cortex_claude/core/__init__.py +4 -0
- cortex_claude/core/decay.py +31 -0
- cortex_claude/core/engine.py +574 -0
- cortex_claude/core/scope_manager.py +48 -0
- cortex_claude/core/token_budget.py +35 -0
- cortex_claude/embeddings/__init__.py +4 -0
- cortex_claude/embeddings/engine.py +26 -0
- cortex_claude/embeddings/tokenizer.py +9 -0
- cortex_claude/facts/__init__.py +3 -0
- cortex_claude/facts/extractor.py +71 -0
- cortex_claude/facts/normalizer.py +69 -0
- cortex_claude/facts/patterns.py +37 -0
- cortex_claude/facts/spacy_extract.py +122 -0
- cortex_claude/models/__init__.py +14 -0
- cortex_claude/models/fact.py +32 -0
- cortex_claude/models/memory.py +47 -0
- cortex_claude/models/scope.py +18 -0
- cortex_claude/pipeline/__init__.py +0 -0
- cortex_claude/server/__init__.py +0 -0
- cortex_claude/server/app.py +140 -0
- cortex_claude/server/config.py +96 -0
- cortex_claude/server/tools/__init__.py +0 -0
- cortex_claude/server/tools/facts.py +29 -0
- cortex_claude/server/tools/forget.py +33 -0
- cortex_claude/server/tools/recall.py +35 -0
- cortex_claude/server/tools/save.py +23 -0
- cortex_claude/server/tools/scopes.py +49 -0
- cortex_claude/server/tools/status.py +37 -0
- cortex_claude/server/tools/traverse.py +27 -0
- cortex_claude/storage/__init__.py +5 -0
- cortex_claude/storage/database.py +81 -0
- cortex_claude/storage/fact_repo.py +117 -0
- cortex_claude/storage/memory_repo.py +142 -0
- cortex_claude/storage/migrations.py +117 -0
- cortex_claude/summarizer/__init__.py +3 -0
- cortex_claude/summarizer/extractive.py +76 -0
- cortex_claude/summarizer/scoring.py +30 -0
- cortex_claude-0.1.0.dist-info/METADATA +258 -0
- cortex_claude-0.1.0.dist-info/RECORD +44 -0
- cortex_claude-0.1.0.dist-info/WHEEL +4 -0
- cortex_claude-0.1.0.dist-info/entry_points.txt +2 -0
- cortex_claude-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass, field
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
@dataclass
|
|
7
|
+
class TokenBudget:
|
|
8
|
+
max_tokens: int
|
|
9
|
+
used_tokens: int = field(default=0)
|
|
10
|
+
|
|
11
|
+
facts_ratio: float = 0.40
|
|
12
|
+
summaries_ratio: float = 0.35
|
|
13
|
+
chunks_ratio: float = 0.25
|
|
14
|
+
|
|
15
|
+
@property
|
|
16
|
+
def remaining(self) -> int:
|
|
17
|
+
return self.max_tokens - self.used_tokens
|
|
18
|
+
|
|
19
|
+
@property
|
|
20
|
+
def facts_budget(self) -> int:
|
|
21
|
+
return int(self.max_tokens * self.facts_ratio)
|
|
22
|
+
|
|
23
|
+
@property
|
|
24
|
+
def summaries_budget(self) -> int:
|
|
25
|
+
return int(self.max_tokens * self.summaries_ratio)
|
|
26
|
+
|
|
27
|
+
@property
|
|
28
|
+
def chunks_budget(self) -> int:
|
|
29
|
+
return int(self.max_tokens * self.chunks_ratio)
|
|
30
|
+
|
|
31
|
+
def consume(self, tokens: int) -> bool:
|
|
32
|
+
if self.used_tokens + tokens > self.max_tokens:
|
|
33
|
+
return False
|
|
34
|
+
self.used_tokens += tokens
|
|
35
|
+
return True
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
from sentence_transformers import SentenceTransformer
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class EmbeddingEngine:
|
|
8
|
+
def __init__(self, model_name: str = "all-MiniLM-L6-v2"):
|
|
9
|
+
self._model_name = model_name
|
|
10
|
+
self._model: SentenceTransformer | None = None
|
|
11
|
+
|
|
12
|
+
def _load(self) -> SentenceTransformer:
|
|
13
|
+
if self._model is None:
|
|
14
|
+
self._model = SentenceTransformer(self._model_name)
|
|
15
|
+
return self._model
|
|
16
|
+
|
|
17
|
+
def embed(self, text: str) -> np.ndarray:
|
|
18
|
+
model = self._load()
|
|
19
|
+
return model.encode(text, normalize_embeddings=True)
|
|
20
|
+
|
|
21
|
+
def embed_batch(self, texts: list[str]) -> np.ndarray:
|
|
22
|
+
model = self._load()
|
|
23
|
+
return model.encode(texts, normalize_embeddings=True, batch_size=32)
|
|
24
|
+
|
|
25
|
+
def similarity(self, a: np.ndarray, b: np.ndarray) -> float:
|
|
26
|
+
return float(np.dot(a, b))
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from cortex_claude.facts.normalizer import entities_match
|
|
4
|
+
from cortex_claude.facts.patterns import extract_facts_patterns
|
|
5
|
+
from cortex_claude.facts.spacy_extract import extract_facts_spacy
|
|
6
|
+
from cortex_claude.models.fact import Fact
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def _deduplicate_facts(facts: list[Fact]) -> list[Fact]:
|
|
10
|
+
seen: set[tuple[str, str, str]] = set()
|
|
11
|
+
unique: list[Fact] = []
|
|
12
|
+
|
|
13
|
+
for fact in facts:
|
|
14
|
+
key = (fact.subject, fact.relation, fact.object)
|
|
15
|
+
if key not in seen:
|
|
16
|
+
seen.add(key)
|
|
17
|
+
unique.append(fact)
|
|
18
|
+
|
|
19
|
+
return unique
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _canonicalize_entities(facts: list[Fact]) -> list[Fact]:
|
|
23
|
+
entity_groups: dict[str, str] = {}
|
|
24
|
+
|
|
25
|
+
all_entities: list[str] = []
|
|
26
|
+
for f in facts:
|
|
27
|
+
if f.subject not in all_entities:
|
|
28
|
+
all_entities.append(f.subject)
|
|
29
|
+
if f.object not in all_entities:
|
|
30
|
+
all_entities.append(f.object)
|
|
31
|
+
|
|
32
|
+
for entity in all_entities:
|
|
33
|
+
if entity in entity_groups:
|
|
34
|
+
continue
|
|
35
|
+
for other in all_entities:
|
|
36
|
+
if other == entity or other in entity_groups:
|
|
37
|
+
continue
|
|
38
|
+
if entities_match(entity, other):
|
|
39
|
+
canonical = entity if len(entity) >= len(other) else other
|
|
40
|
+
entity_groups[entity] = canonical
|
|
41
|
+
entity_groups[other] = canonical
|
|
42
|
+
break
|
|
43
|
+
|
|
44
|
+
if not entity_groups:
|
|
45
|
+
return facts
|
|
46
|
+
|
|
47
|
+
for fact in facts:
|
|
48
|
+
if fact.subject in entity_groups:
|
|
49
|
+
fact.subject = entity_groups[fact.subject]
|
|
50
|
+
if fact.object in entity_groups:
|
|
51
|
+
fact.object = entity_groups[fact.object]
|
|
52
|
+
|
|
53
|
+
return facts
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def extract_facts(text: str, min_confidence: float = 0.5) -> list[Fact]:
|
|
57
|
+
if not text or not text.strip():
|
|
58
|
+
return []
|
|
59
|
+
|
|
60
|
+
facts: list[Fact] = []
|
|
61
|
+
|
|
62
|
+
facts.extend(extract_facts_spacy(text))
|
|
63
|
+
facts.extend(extract_facts_patterns(text))
|
|
64
|
+
|
|
65
|
+
facts = _deduplicate_facts(facts)
|
|
66
|
+
facts = _canonicalize_entities(facts)
|
|
67
|
+
facts = _deduplicate_facts(facts)
|
|
68
|
+
facts = [f for f in facts if f.confidence >= min_confidence]
|
|
69
|
+
facts.sort(key=lambda f: f.confidence, reverse=True)
|
|
70
|
+
|
|
71
|
+
return facts
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
from difflib import SequenceMatcher
|
|
5
|
+
|
|
6
|
+
STOP_WORDS = {"the", "a", "an", "is", "are", "was", "were", "be", "been", "being",
|
|
7
|
+
"o", "a", "os", "as", "um", "uma", "uns", "umas", "de", "do", "da",
|
|
8
|
+
"dos", "das", "em", "no", "na", "nos", "nas", "por", "pelo", "pela"}
|
|
9
|
+
|
|
10
|
+
CANONICAL_ALIASES: dict[str, str] = {
|
|
11
|
+
"js": "javascript",
|
|
12
|
+
"ts": "typescript",
|
|
13
|
+
"py": "python",
|
|
14
|
+
"pg": "postgresql",
|
|
15
|
+
"postgres": "postgresql",
|
|
16
|
+
"mongo": "mongodb",
|
|
17
|
+
"k8s": "kubernetes",
|
|
18
|
+
"react.js": "react",
|
|
19
|
+
"reactjs": "react",
|
|
20
|
+
"next.js": "nextjs",
|
|
21
|
+
"node.js": "nodejs",
|
|
22
|
+
"vue.js": "vue",
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def normalize_entity(text: str) -> str:
|
|
27
|
+
text = text.strip().lower()
|
|
28
|
+
text = re.sub(r"\s+", " ", text)
|
|
29
|
+
|
|
30
|
+
words = text.split()
|
|
31
|
+
words = [w for w in words if w not in STOP_WORDS]
|
|
32
|
+
text = " ".join(words) if words else text
|
|
33
|
+
|
|
34
|
+
if text in CANONICAL_ALIASES:
|
|
35
|
+
text = CANONICAL_ALIASES[text]
|
|
36
|
+
|
|
37
|
+
text = re.sub(r"[\s_-]+", " ", text).strip()
|
|
38
|
+
return text
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def normalize_relation(text: str) -> str:
|
|
42
|
+
text = text.strip().lower()
|
|
43
|
+
text = re.sub(r"\s+", "_", text)
|
|
44
|
+
return text
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def entities_match(a: str, b: str, threshold: float = 0.75) -> bool:
|
|
48
|
+
if a == b:
|
|
49
|
+
return True
|
|
50
|
+
|
|
51
|
+
na = normalize_entity(a)
|
|
52
|
+
nb = normalize_entity(b)
|
|
53
|
+
|
|
54
|
+
if na == nb:
|
|
55
|
+
return True
|
|
56
|
+
|
|
57
|
+
if na in nb or nb in na:
|
|
58
|
+
return True
|
|
59
|
+
|
|
60
|
+
ratio = SequenceMatcher(None, na, nb).ratio()
|
|
61
|
+
return ratio >= threshold
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def find_canonical(entity: str, existing: list[str], threshold: float = 0.75) -> str | None:
|
|
65
|
+
normalized = normalize_entity(entity)
|
|
66
|
+
for candidate in existing:
|
|
67
|
+
if entities_match(normalized, candidate, threshold):
|
|
68
|
+
return candidate
|
|
69
|
+
return None
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
|
|
5
|
+
from cortex_claude.facts.normalizer import normalize_entity, normalize_relation
|
|
6
|
+
from cortex_claude.models.fact import Fact
|
|
7
|
+
|
|
8
|
+
PATTERNS: list[tuple[re.Pattern, str]] = [
|
|
9
|
+
(re.compile(r"(\w[\w\s-]+?)\s+(?:is set to|defaults? to|equals?)\s+(.+?)(?:\.|,|$)", re.I), "defaults_to"),
|
|
10
|
+
(re.compile(r"([\w\s-]+?):\s+(.+?)(?:\.|,|$)", re.M), "has_value"),
|
|
11
|
+
(re.compile(r"(rate[\s_-]?limit)\w*[:\s]+(\d+\s*\w+)", re.I), "has_value"),
|
|
12
|
+
(re.compile(r"(port)\s*[=:]\s*(\d+)", re.I), "has_value"),
|
|
13
|
+
(re.compile(r"(version)\s*[=:]\s*([\d.]+)", re.I), "has_value"),
|
|
14
|
+
]
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def extract_facts_patterns(text: str) -> list[Fact]:
|
|
18
|
+
facts: list[Fact] = []
|
|
19
|
+
|
|
20
|
+
for pattern, default_relation in PATTERNS:
|
|
21
|
+
for match in pattern.finditer(text):
|
|
22
|
+
subject = match.group(1).strip()
|
|
23
|
+
obj = match.group(2).strip()
|
|
24
|
+
|
|
25
|
+
if len(subject) < 2 or len(obj) < 2:
|
|
26
|
+
continue
|
|
27
|
+
if len(subject) > 50 or len(obj) > 100:
|
|
28
|
+
continue
|
|
29
|
+
|
|
30
|
+
facts.append(Fact(
|
|
31
|
+
subject=normalize_entity(subject),
|
|
32
|
+
relation=normalize_relation(default_relation),
|
|
33
|
+
object=normalize_entity(obj),
|
|
34
|
+
confidence=0.6,
|
|
35
|
+
))
|
|
36
|
+
|
|
37
|
+
return facts
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import spacy
|
|
4
|
+
from spacy.tokens import Token
|
|
5
|
+
|
|
6
|
+
from cortex_claude.facts.normalizer import normalize_entity, normalize_relation
|
|
7
|
+
from cortex_claude.models.fact import Fact
|
|
8
|
+
|
|
9
|
+
_models: dict[str, spacy.Language] = {}
|
|
10
|
+
|
|
11
|
+
LANG_MODELS = {
|
|
12
|
+
"en": "en_core_web_sm",
|
|
13
|
+
"pt": "pt_core_news_sm",
|
|
14
|
+
"es": "es_core_news_sm",
|
|
15
|
+
"de": "de_core_news_sm",
|
|
16
|
+
"fr": "fr_core_news_sm",
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _get_nlp(lang: str = "en") -> spacy.Language:
|
|
21
|
+
if lang not in _models:
|
|
22
|
+
model_name = LANG_MODELS.get(lang, LANG_MODELS["en"])
|
|
23
|
+
try:
|
|
24
|
+
_models[lang] = spacy.load(model_name)
|
|
25
|
+
except OSError:
|
|
26
|
+
if lang != "en":
|
|
27
|
+
_models[lang] = _get_nlp("en")
|
|
28
|
+
else:
|
|
29
|
+
raise
|
|
30
|
+
return _models[lang]
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _detect_lang(text: str) -> str:
|
|
34
|
+
markers = {
|
|
35
|
+
"pt": [" usa ", " com ", " para ", " tem ", " via ", " como ",
|
|
36
|
+
" não ", " pelo ", " pela ", " dos ", " das ", " que "],
|
|
37
|
+
"es": [" con ", " para ", " tiene ", " por ", " del ", " las ",
|
|
38
|
+
" los ", " una ", " está ", " como ", " pero "],
|
|
39
|
+
"de": [" und ", " der ", " die ", " das ", " ist ", " ein ",
|
|
40
|
+
" eine ", " für ", " mit ", " auf ", " nicht "],
|
|
41
|
+
"fr": [" les ", " des ", " une ", " est ", " pour ", " dans ",
|
|
42
|
+
" avec ", " pas ", " sur ", " qui ", " cette "],
|
|
43
|
+
}
|
|
44
|
+
text_lower = f" {text.lower()} "
|
|
45
|
+
scores = {}
|
|
46
|
+
for lang, words in markers.items():
|
|
47
|
+
scores[lang] = sum(1 for m in words if m in text_lower)
|
|
48
|
+
best = max(scores, key=scores.get)
|
|
49
|
+
return best if scores[best] >= 2 else "en"
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _get_compound_span(token: Token) -> str:
|
|
53
|
+
compounds = sorted(
|
|
54
|
+
[child for child in token.children if child.dep_ in ("compound", "amod", "flat", "flat:name")],
|
|
55
|
+
key=lambda t: t.i,
|
|
56
|
+
)
|
|
57
|
+
parts = [c.text for c in compounds] + [token.text]
|
|
58
|
+
return " ".join(parts)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def extract_facts_spacy(text: str) -> list[Fact]:
|
|
62
|
+
lang = _detect_lang(text)
|
|
63
|
+
nlp = _get_nlp(lang)
|
|
64
|
+
doc = nlp(text)
|
|
65
|
+
facts: list[Fact] = []
|
|
66
|
+
|
|
67
|
+
for sent in doc.sents:
|
|
68
|
+
root = sent.root
|
|
69
|
+
|
|
70
|
+
if root.pos_ not in ("VERB", "AUX"):
|
|
71
|
+
continue
|
|
72
|
+
|
|
73
|
+
subjects = [
|
|
74
|
+
child for child in root.children
|
|
75
|
+
if child.dep_ in ("nsubj", "nsubj:pass", "nsubjpass")
|
|
76
|
+
]
|
|
77
|
+
|
|
78
|
+
objects = [
|
|
79
|
+
child for child in root.children
|
|
80
|
+
if child.dep_ in ("dobj", "obj", "attr", "oprd", "obl")
|
|
81
|
+
]
|
|
82
|
+
|
|
83
|
+
for child in root.children:
|
|
84
|
+
if child.dep_ in ("prep", "case", "obl"):
|
|
85
|
+
for grandchild in child.children:
|
|
86
|
+
if grandchild.dep_ in ("pobj", "nmod", "obl"):
|
|
87
|
+
objects.append(grandchild)
|
|
88
|
+
|
|
89
|
+
for subj in subjects:
|
|
90
|
+
subj_text = _get_compound_span(subj)
|
|
91
|
+
for obj in objects:
|
|
92
|
+
obj_text = _get_compound_span(obj)
|
|
93
|
+
|
|
94
|
+
if len(subj_text.strip()) < 2 or len(obj_text.strip()) < 2:
|
|
95
|
+
continue
|
|
96
|
+
|
|
97
|
+
facts.append(Fact(
|
|
98
|
+
subject=normalize_entity(subj_text),
|
|
99
|
+
relation=normalize_relation(root.lemma_),
|
|
100
|
+
object=normalize_entity(obj_text),
|
|
101
|
+
confidence=0.8,
|
|
102
|
+
))
|
|
103
|
+
|
|
104
|
+
facts.extend(_extract_ner_facts(doc))
|
|
105
|
+
return facts
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _extract_ner_facts(doc: spacy.tokens.Doc) -> list[Fact]:
|
|
109
|
+
facts: list[Fact] = []
|
|
110
|
+
|
|
111
|
+
for ent in doc.ents:
|
|
112
|
+
if ent.label_ in ("CARDINAL", "QUANTITY", "TIME", "PERCENT", "MONEY"):
|
|
113
|
+
head = ent.root.head
|
|
114
|
+
if head.pos_ in ("NOUN", "PROPN"):
|
|
115
|
+
facts.append(Fact(
|
|
116
|
+
subject=normalize_entity(head.text),
|
|
117
|
+
relation="has_value",
|
|
118
|
+
object=ent.text,
|
|
119
|
+
confidence=0.7,
|
|
120
|
+
))
|
|
121
|
+
|
|
122
|
+
return facts
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
from cortex_claude.models.fact import Fact, FactQuery
|
|
2
|
+
from cortex_claude.models.memory import Memory, RecallItem, RecallResult, SaveResult
|
|
3
|
+
from cortex_claude.models.scope import ScopeConfig, ScopeInfo
|
|
4
|
+
|
|
5
|
+
__all__ = [
|
|
6
|
+
"Fact",
|
|
7
|
+
"FactQuery",
|
|
8
|
+
"Memory",
|
|
9
|
+
"SaveResult",
|
|
10
|
+
"RecallResult",
|
|
11
|
+
"RecallItem",
|
|
12
|
+
"ScopeInfo",
|
|
13
|
+
"ScopeConfig",
|
|
14
|
+
]
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import time
|
|
4
|
+
import uuid
|
|
5
|
+
|
|
6
|
+
from pydantic import BaseModel, Field
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def _now_ms() -> int:
|
|
10
|
+
return int(time.time() * 1000)
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _new_id() -> str:
|
|
14
|
+
return str(uuid.uuid4())
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class Fact(BaseModel):
|
|
18
|
+
id: str = Field(default_factory=_new_id)
|
|
19
|
+
subject: str
|
|
20
|
+
relation: str
|
|
21
|
+
object: str
|
|
22
|
+
confidence: float = 1.0
|
|
23
|
+
source_memory_id: str = ""
|
|
24
|
+
scope: str = "global"
|
|
25
|
+
created_at: int = Field(default_factory=_now_ms)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class FactQuery(BaseModel):
|
|
29
|
+
topic: str
|
|
30
|
+
relation: str | None = None
|
|
31
|
+
scope: str | None = None
|
|
32
|
+
limit: int = 20
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import time
|
|
4
|
+
import uuid
|
|
5
|
+
from pydantic import BaseModel, Field
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def _now_ms() -> int:
|
|
9
|
+
return int(time.time() * 1000)
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _new_id() -> str:
|
|
13
|
+
return str(uuid.uuid4())
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class Memory(BaseModel):
|
|
17
|
+
id: str = Field(default_factory=_new_id)
|
|
18
|
+
content: str
|
|
19
|
+
summary: str | None = None
|
|
20
|
+
tags: list[str] = Field(default_factory=list)
|
|
21
|
+
scope: str = "global"
|
|
22
|
+
created_at: int = Field(default_factory=_now_ms)
|
|
23
|
+
updated_at: int = Field(default_factory=_now_ms)
|
|
24
|
+
accessed_at: int = Field(default_factory=_now_ms)
|
|
25
|
+
access_count: int = 0
|
|
26
|
+
decay_score: float = 1.0
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class SaveResult(BaseModel):
|
|
30
|
+
memory_id: str
|
|
31
|
+
scope: str
|
|
32
|
+
tokens_stored: int
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class RecallItem(BaseModel):
|
|
36
|
+
memory_id: str
|
|
37
|
+
content: str
|
|
38
|
+
score: float
|
|
39
|
+
scope: str
|
|
40
|
+
tags: list[str] = Field(default_factory=list)
|
|
41
|
+
created_at: int
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class RecallResult(BaseModel):
|
|
45
|
+
memories: list[RecallItem] = Field(default_factory=list)
|
|
46
|
+
total_tokens: int = 0
|
|
47
|
+
query: str
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
|
|
5
|
+
from pydantic import BaseModel
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class ScopeInfo(BaseModel):
|
|
9
|
+
name: str
|
|
10
|
+
path: Path
|
|
11
|
+
memory_count: int = 0
|
|
12
|
+
size_bytes: int = 0
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class ScopeConfig(BaseModel):
|
|
16
|
+
mappings: dict[str, str] = {}
|
|
17
|
+
default: str = "global"
|
|
18
|
+
search_order: str = "project_first"
|
|
File without changes
|
|
File without changes
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import Literal
|
|
6
|
+
|
|
7
|
+
from mcp.server.fastmcp import FastMCP
|
|
8
|
+
|
|
9
|
+
from cortex_claude.core.engine import CortexEngine
|
|
10
|
+
from cortex_claude.server.config import CortexConfig
|
|
11
|
+
from cortex_claude.server.tools.facts import handle_facts
|
|
12
|
+
from cortex_claude.server.tools.forget import handle_forget
|
|
13
|
+
from cortex_claude.server.tools.recall import handle_recall
|
|
14
|
+
from cortex_claude.server.tools.save import handle_save
|
|
15
|
+
from cortex_claude.server.tools.scopes import handle_scopes
|
|
16
|
+
from cortex_claude.server.tools.status import handle_status
|
|
17
|
+
from cortex_claude.server.tools.traverse import handle_traverse
|
|
18
|
+
|
|
19
|
+
mcp = FastMCP("cortex-claude")
|
|
20
|
+
engine: CortexEngine | None = None
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _get_engine() -> CortexEngine:
|
|
24
|
+
if engine is None:
|
|
25
|
+
_init_engine()
|
|
26
|
+
return engine
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _init_engine() -> None:
|
|
30
|
+
global engine
|
|
31
|
+
base_path = Path(
|
|
32
|
+
os.environ.get("CORTEX_HOME", str(Path.home() / ".cortex-claude"))
|
|
33
|
+
).expanduser()
|
|
34
|
+
config = CortexConfig.load(base_path)
|
|
35
|
+
engine = CortexEngine(config=config)
|
|
36
|
+
engine.initialize()
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _cwd() -> str:
|
|
40
|
+
return os.getcwd()
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@mcp.tool()
|
|
44
|
+
async def cortex_save(
|
|
45
|
+
content: str,
|
|
46
|
+
tags: list[str] | None = None,
|
|
47
|
+
scope: str | None = None,
|
|
48
|
+
) -> str:
|
|
49
|
+
"""Save information to persistent memory.
|
|
50
|
+
|
|
51
|
+
Stores content with automatic embedding generation, fact extraction,
|
|
52
|
+
and summarization. Use 'global' scope for cross-project memories.
|
|
53
|
+
"""
|
|
54
|
+
return await handle_save(_get_engine(), content, _cwd(), tags, scope)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
@mcp.tool()
|
|
58
|
+
async def cortex_recall(
|
|
59
|
+
query: str,
|
|
60
|
+
max_tokens: int = 200,
|
|
61
|
+
scope: str | None = None,
|
|
62
|
+
depth: Literal["auto", "facts", "summaries", "full"] = "auto",
|
|
63
|
+
) -> str:
|
|
64
|
+
"""Recall relevant memories using progressive retrieval.
|
|
65
|
+
|
|
66
|
+
Uses 3-layer search: facts (cheapest) -> summaries -> full content.
|
|
67
|
+
- depth='facts': only knowledge graph triplets (~5-15 tokens each)
|
|
68
|
+
- depth='summaries': facts + compressed summaries
|
|
69
|
+
- depth='full': all layers including original content
|
|
70
|
+
- depth='auto': progressive, stops at cheapest sufficient layer (default)
|
|
71
|
+
"""
|
|
72
|
+
return await handle_recall(_get_engine(), query, _cwd(), max_tokens, scope, depth)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
@mcp.tool()
|
|
76
|
+
async def cortex_facts(
|
|
77
|
+
topic: str,
|
|
78
|
+
relation: str | None = None,
|
|
79
|
+
scope: str | None = None,
|
|
80
|
+
limit: int = 20,
|
|
81
|
+
) -> str:
|
|
82
|
+
"""Query the knowledge graph directly.
|
|
83
|
+
|
|
84
|
+
Returns structured subject-relation-object facts.
|
|
85
|
+
Extremely token-efficient (~5-15 tokens per fact).
|
|
86
|
+
"""
|
|
87
|
+
return await handle_facts(_get_engine(), topic, _cwd(), relation, scope, limit)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
@mcp.tool()
|
|
91
|
+
async def cortex_traverse(
|
|
92
|
+
start: str,
|
|
93
|
+
max_hops: int = 2,
|
|
94
|
+
scope: str | None = None,
|
|
95
|
+
) -> str:
|
|
96
|
+
"""Traverse the knowledge graph from an entity.
|
|
97
|
+
|
|
98
|
+
Follows connections through multiple hops to discover related information.
|
|
99
|
+
Example: 'auth' → 'JWT' → 'express-jwt' (2 hops).
|
|
100
|
+
"""
|
|
101
|
+
return await handle_traverse(_get_engine(), start, _cwd(), max_hops, scope)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
@mcp.tool()
|
|
105
|
+
async def cortex_forget(
|
|
106
|
+
query: str | None = None,
|
|
107
|
+
memory_id: str | None = None,
|
|
108
|
+
scope: str | None = None,
|
|
109
|
+
dry_run: bool = True,
|
|
110
|
+
) -> str:
|
|
111
|
+
"""Remove memories from storage.
|
|
112
|
+
|
|
113
|
+
By default runs in dry_run mode (preview only).
|
|
114
|
+
Set dry_run=false to actually delete.
|
|
115
|
+
"""
|
|
116
|
+
return await handle_forget(_get_engine(), _cwd(), query, memory_id, scope, dry_run)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
@mcp.tool()
|
|
120
|
+
async def cortex_scopes(
|
|
121
|
+
action: Literal["list", "create", "delete", "link", "unlink", "info"],
|
|
122
|
+
name: str | None = None,
|
|
123
|
+
path: str | None = None,
|
|
124
|
+
) -> str:
|
|
125
|
+
"""Manage memory scopes.
|
|
126
|
+
|
|
127
|
+
Actions: list, create, delete, link (directory to scope), unlink, info.
|
|
128
|
+
"""
|
|
129
|
+
return await handle_scopes(_get_engine(), action, _cwd(), name, path)
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
@mcp.tool()
|
|
133
|
+
async def cortex_status(
|
|
134
|
+
scope: str | None = None,
|
|
135
|
+
) -> str:
|
|
136
|
+
"""Show Cortex memory statistics.
|
|
137
|
+
|
|
138
|
+
Returns total memories, facts, scopes, storage size.
|
|
139
|
+
"""
|
|
140
|
+
return await handle_status(_get_engine(), _cwd(), scope)
|