relate-codemem 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.
- relate_codemem/__init__.py +3 -0
- relate_codemem/__main__.py +5 -0
- relate_codemem/cli.py +166 -0
- relate_codemem/config.py +210 -0
- relate_codemem/embeddings.py +222 -0
- relate_codemem/events.py +211 -0
- relate_codemem/extract.py +388 -0
- relate_codemem/indexer.py +299 -0
- relate_codemem/project.py +221 -0
- relate_codemem/recall.py +299 -0
- relate_codemem/store.py +257 -0
- relate_codemem/templates/claude-section.md +78 -0
- relate_codemem/templates/decision-template.md +32 -0
- relate_codemem/templates/meeting-template.md +36 -0
- relate_codemem/templates/skill.md +91 -0
- relate_codemem-0.1.0.dist-info/METADATA +208 -0
- relate_codemem-0.1.0.dist-info/RECORD +20 -0
- relate_codemem-0.1.0.dist-info/WHEEL +4 -0
- relate_codemem-0.1.0.dist-info/entry_points.txt +3 -0
- relate_codemem-0.1.0.dist-info/licenses/LICENSE +21 -0
relate_codemem/cli.py
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
"""Command line: `relate-codemem <command>` (alias `rcm`)."""
|
|
2
|
+
import argparse
|
|
3
|
+
import json
|
|
4
|
+
import subprocess
|
|
5
|
+
import sys
|
|
6
|
+
|
|
7
|
+
from . import __version__, config, embeddings, events, indexer, project, recall, store
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _embedding_options(parser):
|
|
11
|
+
parser.add_argument("--embeddings", choices=config.PROVIDERS, help="embedding provider")
|
|
12
|
+
parser.add_argument("--model", help="embedding model name")
|
|
13
|
+
parser.add_argument("--url", help="base URL (ollama, openai-compatible)")
|
|
14
|
+
parser.add_argument("--api-key-env", help="name of the environment variable holding the API key")
|
|
15
|
+
parser.add_argument("--dimensions", type=int, help="vector size, for models that accept it")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _overrides(args):
|
|
19
|
+
return project.embedding_overrides(args.embeddings, args.model, args.url, args.api_key_env, args.dimensions)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def build_parser():
|
|
23
|
+
ap = argparse.ArgumentParser(prog="relate-codemem", description=__doc__.splitlines()[0] + "\n\n"
|
|
24
|
+
"Project memory graph for Claude Code on the relate embedded database.",
|
|
25
|
+
formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
26
|
+
ap.add_argument("--version", action="version", version=f"relate-codemem {__version__}")
|
|
27
|
+
sub = ap.add_subparsers(dest="cmd", required=True, metavar="command")
|
|
28
|
+
|
|
29
|
+
a = sub.add_parser("setup", help="machine setup: default embedding provider, global Claude Code skill")
|
|
30
|
+
_embedding_options(a)
|
|
31
|
+
a.add_argument("--no-skill", action="store_true")
|
|
32
|
+
sub.add_parser("doctor", help="check the installation")
|
|
33
|
+
a = sub.add_parser("init", help="set up a project (hooks, settings, CLAUDE.md, docs dirs) and index it")
|
|
34
|
+
a.add_argument("path", nargs="?", default=".")
|
|
35
|
+
_embedding_options(a)
|
|
36
|
+
a.add_argument("--no-index", action="store_true", help="skip the initial analysis")
|
|
37
|
+
a = sub.add_parser("index", help="analyse the project: hashes, revisions, symbols, docs, embeddings")
|
|
38
|
+
a.add_argument("paths", nargs="*")
|
|
39
|
+
a.add_argument("--full", action="store_true", help="re-extract every file (no new revision)")
|
|
40
|
+
a.add_argument("--no-embed", action="store_true")
|
|
41
|
+
a = sub.add_parser("embed", help="compute missing embeddings")
|
|
42
|
+
a.add_argument("--reset", action="store_true", help="rebuild all vectors")
|
|
43
|
+
a.add_argument("--quiet", action="store_true")
|
|
44
|
+
a = sub.add_parser("search", help="hybrid search (full-text + semantic)")
|
|
45
|
+
a.add_argument("query", nargs="+")
|
|
46
|
+
a.add_argument("-k", type=int, default=10)
|
|
47
|
+
a.add_argument("--kind", choices=sorted(recall.KINDS))
|
|
48
|
+
a.add_argument("--all", action="store_true", help="include superseded entries and deleted files")
|
|
49
|
+
a.add_argument("--no-semantic", action="store_true")
|
|
50
|
+
sub.add_parser("recall", help="open decisions, notes, meetings, recent sessions")
|
|
51
|
+
a = sub.add_parser("file", help="revisions, symbols, dependencies, decisions and sessions of a file")
|
|
52
|
+
a.add_argument("path")
|
|
53
|
+
a = sub.add_parser("symbol", help="where a symbol is defined")
|
|
54
|
+
a.add_argument("name")
|
|
55
|
+
a = sub.add_parser("query", help="read-only Cypher")
|
|
56
|
+
a.add_argument("cypher")
|
|
57
|
+
sub.add_parser("schema", help="the graph model")
|
|
58
|
+
a = sub.add_parser("decide", help="record a decision")
|
|
59
|
+
a.add_argument("--title", required=True)
|
|
60
|
+
a.add_argument("--text", required=True)
|
|
61
|
+
a.add_argument("--rationale")
|
|
62
|
+
a.add_argument("--slot")
|
|
63
|
+
a.add_argument("--files")
|
|
64
|
+
a.add_argument("--supersedes")
|
|
65
|
+
a = sub.add_parser("note", help="record a note")
|
|
66
|
+
a.add_argument("text", nargs="+")
|
|
67
|
+
a.add_argument("--title")
|
|
68
|
+
a.add_argument("--slot")
|
|
69
|
+
a.add_argument("--files")
|
|
70
|
+
a.add_argument("--supersedes")
|
|
71
|
+
sub.add_parser("status", help="node counts, spool, embedding coverage")
|
|
72
|
+
sub.add_parser("config", help="effective configuration and where each value comes from")
|
|
73
|
+
sub.add_parser("flush", help="write spooled hook events now")
|
|
74
|
+
sub.add_parser("hook", help="Claude Code hook entry point (payload on stdin)")
|
|
75
|
+
sub.add_parser("mcp", help="read-only MCP server on the project store (stdio)")
|
|
76
|
+
return ap
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def show_config():
|
|
80
|
+
ecfg = config.embedding_config()
|
|
81
|
+
print(f"project root: {config.project_root()}")
|
|
82
|
+
print(f"store: {store.home()}")
|
|
83
|
+
print(f"project options: {config.project_config_path()}"
|
|
84
|
+
+ ("" if config.project_config_path().exists() else " (absent, defaults apply)"))
|
|
85
|
+
print(f"user config: {config.global_config_path()}"
|
|
86
|
+
+ ("" if config.global_config_path().exists() else " (absent, defaults apply)"))
|
|
87
|
+
print(f"embeddings: {ecfg['provider']} (from {ecfg['source']})")
|
|
88
|
+
for key in ("model", "url", "api_key_env", "dimensions", "min_similarity"):
|
|
89
|
+
if ecfg.get(key) is not None:
|
|
90
|
+
print(f" {key + ':':<15}{ecfg[key]}")
|
|
91
|
+
marker = embeddings.read_marker()
|
|
92
|
+
if marker:
|
|
93
|
+
print(f"store vectors: {marker['provider']}:{marker['model']} ({marker['dimensions']} dimensions)")
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def main(argv=None):
|
|
97
|
+
for stream in (sys.stdout, sys.stderr):
|
|
98
|
+
try:
|
|
99
|
+
stream.reconfigure(encoding="utf-8", errors="replace")
|
|
100
|
+
except (AttributeError, ValueError):
|
|
101
|
+
pass
|
|
102
|
+
args = build_parser().parse_args(argv)
|
|
103
|
+
|
|
104
|
+
if args.cmd == "hook":
|
|
105
|
+
try:
|
|
106
|
+
events.hook()
|
|
107
|
+
except Exception as exc: # a hook must never break the session
|
|
108
|
+
store.log(f"hook error: {type(exc).__name__}: {exc}")
|
|
109
|
+
return 0
|
|
110
|
+
try:
|
|
111
|
+
if args.cmd == "setup":
|
|
112
|
+
return project.setup(_overrides(args), skill=not args.no_skill)
|
|
113
|
+
if args.cmd == "doctor":
|
|
114
|
+
return project.doctor()
|
|
115
|
+
if args.cmd == "init":
|
|
116
|
+
project.init_project(args.path, _overrides(args))
|
|
117
|
+
if not args.no_index:
|
|
118
|
+
print("\ninitial analysis:")
|
|
119
|
+
indexer.index()
|
|
120
|
+
embeddings.embed_pass()
|
|
121
|
+
print("\nrestart Claude Code in this project to load the hooks and the MCP server.")
|
|
122
|
+
elif args.cmd == "index":
|
|
123
|
+
indexer.index(args.paths or None, full=args.full)
|
|
124
|
+
if not args.no_embed:
|
|
125
|
+
embeddings.embed_pass()
|
|
126
|
+
elif args.cmd == "embed":
|
|
127
|
+
embeddings.embed_pass(quiet=args.quiet, reset=args.reset)
|
|
128
|
+
elif args.cmd == "search":
|
|
129
|
+
recall.search(" ".join(args.query), k=args.k, kind=args.kind, include_closed=args.all,
|
|
130
|
+
semantic=not args.no_semantic)
|
|
131
|
+
elif args.cmd == "recall":
|
|
132
|
+
recall.recall()
|
|
133
|
+
elif args.cmd == "file":
|
|
134
|
+
recall.show_file(args.path)
|
|
135
|
+
elif args.cmd == "symbol":
|
|
136
|
+
recall.show_symbol(args.name)
|
|
137
|
+
elif args.cmd == "query":
|
|
138
|
+
for row in store.read(args.cypher):
|
|
139
|
+
print(json.dumps(row, ensure_ascii=False))
|
|
140
|
+
elif args.cmd == "schema":
|
|
141
|
+
print(recall.MODEL_DOC)
|
|
142
|
+
elif args.cmd == "decide":
|
|
143
|
+
recall.remember("Decision", args.title, args.text, args.rationale, args.slot, args.files,
|
|
144
|
+
args.supersedes)
|
|
145
|
+
elif args.cmd == "note":
|
|
146
|
+
text = " ".join(args.text)
|
|
147
|
+
recall.remember("Note", args.title or recall.one_line(text, 100), text, None, args.slot,
|
|
148
|
+
args.files, args.supersedes)
|
|
149
|
+
elif args.cmd == "status":
|
|
150
|
+
recall.status()
|
|
151
|
+
elif args.cmd == "config":
|
|
152
|
+
show_config()
|
|
153
|
+
elif args.cmd == "flush":
|
|
154
|
+
print(f"flushed {events.flush()} event(s)")
|
|
155
|
+
elif args.cmd == "mcp":
|
|
156
|
+
store.ensure_store()
|
|
157
|
+
return subprocess.call([store.relate_bin(), "serve", "--mcp", "stdio", "--database",
|
|
158
|
+
str(store.db()), "--read-only=live"])
|
|
159
|
+
except (store.RelateError, config.ConfigError, subprocess.SubprocessError) as exc:
|
|
160
|
+
print(f"error: {exc}", file=sys.stderr)
|
|
161
|
+
return 1
|
|
162
|
+
return 0
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
if __name__ == "__main__":
|
|
166
|
+
sys.exit(main())
|
relate_codemem/config.py
ADDED
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
"""Paths and layered configuration.
|
|
2
|
+
|
|
3
|
+
Three layers, most specific first:
|
|
4
|
+
|
|
5
|
+
1. the process environment, then the `env` block of the project's
|
|
6
|
+
`.claude/settings.local.json`, then of `.claude/settings.json`
|
|
7
|
+
(variables named RELATE_CODEMEM_*);
|
|
8
|
+
2. the user configuration written by `relate-codemem setup`
|
|
9
|
+
(~/.config/relate-codemem/config.json, %APPDATA% on Windows);
|
|
10
|
+
3. built-in defaults (local embeddings).
|
|
11
|
+
|
|
12
|
+
Indexing options that describe the repository (directories, exclusions) live in
|
|
13
|
+
the project file `.claude/relate-codemem.json`.
|
|
14
|
+
"""
|
|
15
|
+
import json
|
|
16
|
+
import os
|
|
17
|
+
import subprocess
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
|
|
20
|
+
APP = "relate-codemem"
|
|
21
|
+
ENV = "RELATE_CODEMEM_"
|
|
22
|
+
SCHEMA_VERSION = 1
|
|
23
|
+
|
|
24
|
+
PROJECT_DEFAULTS = {
|
|
25
|
+
"decisions_dirs": ["docs/decisions", "docs/adr", "adr"],
|
|
26
|
+
"meetings_dirs": ["docs/meetings", "meetings"],
|
|
27
|
+
"exclude_dirs": [".git", ".claude", "node_modules", ".venv", "venv", "__pycache__", "dist",
|
|
28
|
+
"build", "target", ".next", ".nuxt", "vendor", ".idea", ".vscode", "coverage",
|
|
29
|
+
".pytest_cache", ".mypy_cache", ".tox", "DerivedData", "Pods", ".gradle"],
|
|
30
|
+
"exclude_files": ["package-lock.json", "yarn.lock", "pnpm-lock.yaml", "poetry.lock",
|
|
31
|
+
"Cargo.lock", "uv.lock", "composer.lock", "Gemfile.lock"],
|
|
32
|
+
"max_file_bytes": 500000,
|
|
33
|
+
"chunk_chars": 1800,
|
|
34
|
+
"max_prompt_chars": 6000,
|
|
35
|
+
"max_reply_chars": 8000,
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
PROVIDERS = ("local", "ollama", "openai", "none")
|
|
39
|
+
EMBEDDING_DEFAULTS = {
|
|
40
|
+
"local": {"model": "sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2",
|
|
41
|
+
"min_similarity": 0.62},
|
|
42
|
+
"ollama": {"model": "bge-m3", "url": "http://localhost:11434", "min_similarity": 0.60},
|
|
43
|
+
"openai": {"model": "text-embedding-3-small", "url": "https://api.openai.com/v1",
|
|
44
|
+
"api_key_env": "OPENAI_API_KEY", "min_similarity": 0.60},
|
|
45
|
+
"fake": {"model": "hash-16", "min_similarity": 0.55}, # deterministic, for tests
|
|
46
|
+
"none": {},
|
|
47
|
+
}
|
|
48
|
+
_ALIASES = {"fastembed": "local", "off": "none", "false": "none", "no": "none", "0": "none",
|
|
49
|
+
"disabled": "none", "openai-compatible": "openai", "api": "openai"}
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class ConfigError(ValueError):
|
|
53
|
+
pass
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
# ---------------------------------------------------------------- user-level locations
|
|
57
|
+
|
|
58
|
+
def user_config_dir():
|
|
59
|
+
if os.name == "nt":
|
|
60
|
+
base = os.environ.get("APPDATA") or str(Path.home() / "AppData" / "Roaming")
|
|
61
|
+
else:
|
|
62
|
+
base = os.environ.get("XDG_CONFIG_HOME") or str(Path.home() / ".config")
|
|
63
|
+
return Path(base) / APP
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def user_cache_dir():
|
|
67
|
+
if os.name == "nt":
|
|
68
|
+
base = os.environ.get("LOCALAPPDATA") or str(Path.home() / "AppData" / "Local")
|
|
69
|
+
return Path(base) / APP / "cache"
|
|
70
|
+
return Path(os.environ.get("XDG_CACHE_HOME") or Path.home() / ".cache") / APP
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def global_config_path():
|
|
74
|
+
return user_config_dir() / "config.json"
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def load_global():
|
|
78
|
+
try:
|
|
79
|
+
return json.loads(global_config_path().read_text("utf-8"))
|
|
80
|
+
except (OSError, ValueError):
|
|
81
|
+
return {}
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def save_global(data):
|
|
85
|
+
path = global_config_path()
|
|
86
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
87
|
+
path.write_text(json.dumps(data, indent=2) + "\n", "utf-8")
|
|
88
|
+
return path
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
# ---------------------------------------------------------------- project root
|
|
92
|
+
|
|
93
|
+
_state = {"root": None, "settings_env": None, "project": None}
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def reset(root=None):
|
|
97
|
+
"""Forget cached lookups; optionally pin the project root (init, tests)."""
|
|
98
|
+
_state.update(root=Path(root).resolve() if root else None, settings_env=None, project=None)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _git_toplevel(cwd):
|
|
102
|
+
try:
|
|
103
|
+
out = subprocess.run(["git", "-C", str(cwd), "rev-parse", "--show-toplevel"],
|
|
104
|
+
capture_output=True, text=True, timeout=10)
|
|
105
|
+
return Path(out.stdout.strip()) if out.returncode == 0 and out.stdout.strip() else None
|
|
106
|
+
except (OSError, subprocess.SubprocessError):
|
|
107
|
+
return None
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def project_root():
|
|
111
|
+
"""Project the command applies to: Claude Code's project directory when a hook or a
|
|
112
|
+
tool call runs us, else the nearest initialised ancestor, else the git root, else cwd."""
|
|
113
|
+
if _state["root"]:
|
|
114
|
+
return _state["root"]
|
|
115
|
+
for var in (ENV + "PROJECT", "CLAUDE_PROJECT_DIR"):
|
|
116
|
+
value = os.environ.get(var)
|
|
117
|
+
if value and Path(value).is_dir():
|
|
118
|
+
_state["root"] = Path(value).resolve()
|
|
119
|
+
return _state["root"]
|
|
120
|
+
cwd = Path.cwd().resolve()
|
|
121
|
+
for candidate in (cwd, *cwd.parents):
|
|
122
|
+
if (candidate / ".claude" / "relate").is_dir() or (candidate / ".claude" / f"{APP}.json").is_file():
|
|
123
|
+
_state["root"] = candidate
|
|
124
|
+
return candidate
|
|
125
|
+
_state["root"] = _git_toplevel(cwd) or cwd
|
|
126
|
+
return _state["root"]
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
# ---------------------------------------------------------------- settings
|
|
130
|
+
|
|
131
|
+
def _settings_env():
|
|
132
|
+
"""RELATE_CODEMEM_* variables declared in the project's Claude Code settings files.
|
|
133
|
+
Read from the files so that a terminal run and a hook run agree."""
|
|
134
|
+
if _state["settings_env"] is None:
|
|
135
|
+
found = {}
|
|
136
|
+
for name in ("settings.json", "settings.local.json"): # local wins
|
|
137
|
+
path = project_root() / ".claude" / name
|
|
138
|
+
try:
|
|
139
|
+
env = json.loads(path.read_text("utf-8")).get("env") or {}
|
|
140
|
+
except (OSError, ValueError, AttributeError):
|
|
141
|
+
continue
|
|
142
|
+
for key, value in env.items():
|
|
143
|
+
if key.startswith(ENV) and value not in (None, ""):
|
|
144
|
+
found[key] = (str(value), f".claude/{name}")
|
|
145
|
+
_state["settings_env"] = found
|
|
146
|
+
return _state["settings_env"]
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def setting(name):
|
|
150
|
+
"""-> (value, source) for RELATE_CODEMEM_<name>, or (None, None)."""
|
|
151
|
+
key = ENV + name
|
|
152
|
+
if os.environ.get(key):
|
|
153
|
+
return os.environ[key], "environment"
|
|
154
|
+
return _settings_env().get(key, (None, None))
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def store_home():
|
|
158
|
+
value, _ = setting("HOME")
|
|
159
|
+
return Path(value) if value else project_root() / ".claude" / "relate"
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def project_config_path():
|
|
163
|
+
return project_root() / ".claude" / f"{APP}.json"
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def project_config():
|
|
167
|
+
if _state["project"] is None:
|
|
168
|
+
cfg = dict(PROJECT_DEFAULTS)
|
|
169
|
+
try:
|
|
170
|
+
data = json.loads(project_config_path().read_text("utf-8"))
|
|
171
|
+
cfg.update({k: v for k, v in data.items() if k in PROJECT_DEFAULTS})
|
|
172
|
+
except (OSError, ValueError):
|
|
173
|
+
pass
|
|
174
|
+
_state["project"] = cfg
|
|
175
|
+
return _state["project"]
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def normalise_provider(name):
|
|
179
|
+
name = (name or "").strip().lower()
|
|
180
|
+
name = _ALIASES.get(name, name)
|
|
181
|
+
if name not in EMBEDDING_DEFAULTS:
|
|
182
|
+
raise ConfigError(f"unknown embedding provider '{name}' (choose: {', '.join(PROVIDERS)})")
|
|
183
|
+
return name
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def embedding_config():
|
|
187
|
+
"""Effective embedding settings: {provider, model, url, api_key_env, dimensions,
|
|
188
|
+
min_similarity, source}. Default when nothing is configured: local."""
|
|
189
|
+
stored = load_global().get("embeddings") or {}
|
|
190
|
+
value, source = setting("EMBEDDINGS")
|
|
191
|
+
if value:
|
|
192
|
+
provider = normalise_provider(value)
|
|
193
|
+
elif stored.get("provider"):
|
|
194
|
+
provider, source = normalise_provider(stored["provider"]), str(global_config_path())
|
|
195
|
+
else:
|
|
196
|
+
provider, source = "local", "default"
|
|
197
|
+
cfg = dict(EMBEDDING_DEFAULTS[provider], provider=provider, source=source)
|
|
198
|
+
if stored.get("provider") and normalise_provider(stored["provider"]) == provider:
|
|
199
|
+
cfg.update({k: v for k, v in stored.items() if k != "provider" and v not in (None, "")})
|
|
200
|
+
for key, var, cast in (("model", "EMBEDDING_MODEL", str), ("url", "EMBEDDING_URL", str),
|
|
201
|
+
("api_key_env", "EMBEDDING_API_KEY_ENV", str),
|
|
202
|
+
("dimensions", "EMBEDDING_DIMENSIONS", int),
|
|
203
|
+
("min_similarity", "EMBEDDING_MIN_SIMILARITY", float)):
|
|
204
|
+
raw, _ = setting(var)
|
|
205
|
+
if raw:
|
|
206
|
+
try:
|
|
207
|
+
cfg[key] = cast(raw)
|
|
208
|
+
except ValueError:
|
|
209
|
+
raise ConfigError(f"{ENV}{var}={raw!r} is not a valid {cast.__name__}")
|
|
210
|
+
return cfg
|
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
"""Embeddings computed upstream of relate, then stored as typed vectors and searched
|
|
2
|
+
through relate's vector index.
|
|
3
|
+
|
|
4
|
+
Providers:
|
|
5
|
+
local fastembed, on this machine (extra `relate-codemem[local]`); nothing leaves it
|
|
6
|
+
ollama an Ollama server (default http://localhost:11434)
|
|
7
|
+
openai any OpenAI-compatible /embeddings endpoint (OpenAI, Mistral, Voyage, vLLM, ...)
|
|
8
|
+
none full-text search only
|
|
9
|
+
"""
|
|
10
|
+
import hashlib
|
|
11
|
+
import json
|
|
12
|
+
import math
|
|
13
|
+
import os
|
|
14
|
+
import re
|
|
15
|
+
import subprocess
|
|
16
|
+
import sys
|
|
17
|
+
import urllib.error
|
|
18
|
+
import urllib.request
|
|
19
|
+
|
|
20
|
+
from . import config, store
|
|
21
|
+
|
|
22
|
+
EMBED_LABELS = ("Decision", "Note", "Chunk", "Symbol", "Prompt", "Reply")
|
|
23
|
+
VECTOR_INDEX = "memory_vec"
|
|
24
|
+
MAX_CHARS = 2000
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class EmbeddingError(store.RelateError):
|
|
28
|
+
pass
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
# ---------------------------------------------------------------- providers
|
|
32
|
+
|
|
33
|
+
def _post(url, body, headers=None, timeout=300):
|
|
34
|
+
req = urllib.request.Request(url, data=json.dumps(body).encode("utf-8"),
|
|
35
|
+
headers={"Content-Type": "application/json", **(headers or {})})
|
|
36
|
+
try:
|
|
37
|
+
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
|
38
|
+
return json.loads(resp.read().decode("utf-8"))
|
|
39
|
+
except urllib.error.HTTPError as exc:
|
|
40
|
+
detail = exc.read().decode("utf-8", errors="replace")[:300]
|
|
41
|
+
raise EmbeddingError(f"{url} answered HTTP {exc.code}: {detail}")
|
|
42
|
+
except (urllib.error.URLError, OSError, ValueError) as exc:
|
|
43
|
+
raise EmbeddingError(f"cannot reach {url}: {exc}")
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _local(texts, cfg):
|
|
47
|
+
try:
|
|
48
|
+
from fastembed import TextEmbedding
|
|
49
|
+
except ImportError:
|
|
50
|
+
raise EmbeddingError("local embeddings need fastembed: reinstall with the `local` extra "
|
|
51
|
+
"(uv tool install 'relate-codemem[local]') or pick another provider")
|
|
52
|
+
cache = config.user_cache_dir() / "fastembed"
|
|
53
|
+
cache.mkdir(parents=True, exist_ok=True)
|
|
54
|
+
model = TextEmbedding(model_name=cfg["model"], cache_dir=str(cache))
|
|
55
|
+
return [[float(x) for x in v] for v in model.embed(texts, batch_size=32)]
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _ollama(texts, cfg):
|
|
59
|
+
out = []
|
|
60
|
+
for start in range(0, len(texts), 64):
|
|
61
|
+
data = _post(cfg["url"].rstrip("/") + "/api/embed",
|
|
62
|
+
{"model": cfg["model"], "input": texts[start:start + 64]})
|
|
63
|
+
if "embeddings" not in data:
|
|
64
|
+
raise EmbeddingError(f"Ollama returned no embeddings: {str(data)[:200]}")
|
|
65
|
+
out += data["embeddings"]
|
|
66
|
+
return out
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _openai(texts, cfg):
|
|
70
|
+
key_env = cfg.get("api_key_env") or ""
|
|
71
|
+
key = os.environ.get(key_env, "") if key_env else ""
|
|
72
|
+
headers = {"Authorization": f"Bearer {key}"} if key else {}
|
|
73
|
+
if key_env and not key and "localhost" not in cfg["url"] and "127.0.0.1" not in cfg["url"]:
|
|
74
|
+
raise EmbeddingError(f"environment variable {key_env} is not set (API key for {cfg['url']})")
|
|
75
|
+
out = []
|
|
76
|
+
for start in range(0, len(texts), 96):
|
|
77
|
+
body = {"model": cfg["model"], "input": texts[start:start + 96]}
|
|
78
|
+
if cfg.get("dimensions"):
|
|
79
|
+
body["dimensions"] = int(cfg["dimensions"])
|
|
80
|
+
data = _post(cfg["url"].rstrip("/") + "/embeddings", body, headers)
|
|
81
|
+
rows = sorted(data.get("data") or [], key=lambda r: r.get("index", 0))
|
|
82
|
+
if len(rows) != len(body["input"]):
|
|
83
|
+
raise EmbeddingError(f"embedding API returned {len(rows)} vectors for {len(body['input'])} texts")
|
|
84
|
+
out += [r["embedding"] for r in rows]
|
|
85
|
+
return out
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _fake(texts, cfg):
|
|
89
|
+
"""Deterministic bag-of-words vectors: no model, for the test suite."""
|
|
90
|
+
out = []
|
|
91
|
+
for text in texts:
|
|
92
|
+
v = [0.0] * 16
|
|
93
|
+
for word in re.findall(r"\w+", text.lower()):
|
|
94
|
+
v[int(hashlib.md5(word.encode()).hexdigest(), 16) % 16] += 1.0
|
|
95
|
+
norm = math.sqrt(sum(x * x for x in v)) or 1.0
|
|
96
|
+
out.append([x / norm for x in v])
|
|
97
|
+
return out
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
_PROVIDERS = {"local": _local, "ollama": _ollama, "openai": _openai, "fake": _fake}
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def embed_texts(texts, cfg=None):
|
|
104
|
+
cfg = cfg or config.embedding_config()
|
|
105
|
+
if cfg["provider"] == "none":
|
|
106
|
+
raise EmbeddingError("embeddings are disabled")
|
|
107
|
+
vectors = _PROVIDERS[cfg["provider"]](texts, cfg)
|
|
108
|
+
if len(vectors) != len(texts):
|
|
109
|
+
raise EmbeddingError(f"provider returned {len(vectors)} vectors for {len(texts)} texts")
|
|
110
|
+
return [[round(float(x), 5) for x in v] for v in vectors]
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
# ---------------------------------------------------------------- store side
|
|
114
|
+
|
|
115
|
+
def marker_path():
|
|
116
|
+
return store.home() / "embeddings.json"
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def read_marker():
|
|
120
|
+
"""What the vectors in this store were built with: {provider, model, dimensions}."""
|
|
121
|
+
try:
|
|
122
|
+
return json.loads(marker_path().read_text("utf-8"))
|
|
123
|
+
except (OSError, ValueError):
|
|
124
|
+
return None
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def marker_matches(cfg, marker=None):
|
|
128
|
+
marker = marker if marker is not None else read_marker()
|
|
129
|
+
return bool(marker) and (marker["provider"], marker["model"]) == (cfg["provider"], cfg["model"])
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _drop_vectors():
|
|
133
|
+
with store.write_lock():
|
|
134
|
+
store.run(f"DROP INDEX {VECTOR_INDEX} IF EXISTS")
|
|
135
|
+
store.run("MATCH (n:Searchable) WHERE n.embedding IS NOT NULL SET n.embedding = null")
|
|
136
|
+
try:
|
|
137
|
+
marker_path().unlink()
|
|
138
|
+
except OSError:
|
|
139
|
+
pass
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _create_index(cfg, dim):
|
|
143
|
+
with store.write_lock():
|
|
144
|
+
store.run(f"CREATE VECTOR INDEX {VECTOR_INDEX} IF NOT EXISTS FOR (n:Searchable) ON (n.embedding) "
|
|
145
|
+
f"OPTIONS {{indexConfig: {{`vector.dimensions`: {int(dim)}, "
|
|
146
|
+
f"`vector.similarity_function`: 'cosine'}}}}")
|
|
147
|
+
marker = {"provider": cfg["provider"], "model": cfg["model"], "dimensions": int(dim),
|
|
148
|
+
"at": store.now_iso()}
|
|
149
|
+
marker_path().write_text(json.dumps(marker), "utf-8")
|
|
150
|
+
return marker
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def embed_pass(quiet=False, reset=False):
|
|
154
|
+
"""Embed every searchable node whose text has no vector yet (new or changed text).
|
|
155
|
+
A store built with another provider or model is re-embedded from scratch."""
|
|
156
|
+
cfg = config.embedding_config()
|
|
157
|
+
say = (lambda *a: None) if quiet else (lambda msg: print(msg, flush=True))
|
|
158
|
+
if cfg["provider"] == "none":
|
|
159
|
+
say("embeddings are off (provider: none); search is full-text only")
|
|
160
|
+
return 0
|
|
161
|
+
store.ensure_store()
|
|
162
|
+
try:
|
|
163
|
+
guard = store.file_lock("embed.lock", timeout=0).__enter__()
|
|
164
|
+
except store.Busy:
|
|
165
|
+
say("an embedding pass is already running")
|
|
166
|
+
return 0
|
|
167
|
+
try:
|
|
168
|
+
marker = read_marker()
|
|
169
|
+
if marker and (reset or not marker_matches(cfg, marker)):
|
|
170
|
+
embed_texts(["probe"], cfg) # fail here, before dropping the vectors we have
|
|
171
|
+
say(f"embedding model changed ({marker['provider']}:{marker['model']} -> "
|
|
172
|
+
f"{cfg['provider']}:{cfg['model']}): rebuilding all vectors")
|
|
173
|
+
_drop_vectors()
|
|
174
|
+
marker = None
|
|
175
|
+
total = 0
|
|
176
|
+
for _ in range(1000):
|
|
177
|
+
pending = []
|
|
178
|
+
for label in EMBED_LABELS:
|
|
179
|
+
rows = store.read(f"MATCH (n:{label}) WHERE n.embedding IS NULL AND n.text IS NOT NULL "
|
|
180
|
+
f"RETURN n.id AS id, n.title AS title, n.text AS text LIMIT 1500")
|
|
181
|
+
pending += [(label, r) for r in rows]
|
|
182
|
+
if len(pending) >= 1500:
|
|
183
|
+
break
|
|
184
|
+
if not pending:
|
|
185
|
+
break
|
|
186
|
+
vectors = embed_texts([f"{r['title'] or ''}\n{r['text']}"[:MAX_CHARS] for _, r in pending], cfg)
|
|
187
|
+
dim = len(vectors[0])
|
|
188
|
+
if marker is None:
|
|
189
|
+
marker = _create_index(cfg, dim)
|
|
190
|
+
elif dim != marker["dimensions"]:
|
|
191
|
+
raise EmbeddingError(f"model returned {dim} dimensions, the store holds "
|
|
192
|
+
f"{marker['dimensions']}: run `relate-codemem embed --reset`")
|
|
193
|
+
for start in range(0, len(pending), 250):
|
|
194
|
+
by_label = {}
|
|
195
|
+
for (label, r), v in zip(pending[start:start + 250], vectors[start:start + 250]):
|
|
196
|
+
by_label.setdefault(label, []).append({"id": r["id"], "v": v})
|
|
197
|
+
with store.write_lock():
|
|
198
|
+
for label, rows in by_label.items():
|
|
199
|
+
store.write(f"UNWIND $p.rows AS r MATCH (n:{label} {{id: r.id}}) "
|
|
200
|
+
f"SET n.embedding = vector(r.v, {dim}, FLOAT32)", {"rows": rows})
|
|
201
|
+
total += len(pending)
|
|
202
|
+
say(f" embedded {total} item(s)")
|
|
203
|
+
if total:
|
|
204
|
+
store.log(f"embedded {total} item(s) with {cfg['provider']}:{cfg['model']}")
|
|
205
|
+
say(f"embeddings up to date ({total} computed, {cfg['provider']}:{cfg['model']})")
|
|
206
|
+
return total
|
|
207
|
+
finally:
|
|
208
|
+
guard.__exit__(None, None, None)
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def embed_in_background():
|
|
212
|
+
"""Hooks must return quickly: the embedding pass runs in a detached process."""
|
|
213
|
+
try:
|
|
214
|
+
if config.embedding_config()["provider"] == "none":
|
|
215
|
+
return
|
|
216
|
+
env = dict(os.environ, **{config.ENV + "PROJECT": str(config.project_root())})
|
|
217
|
+
kwargs = {"creationflags": 0x00000008 | 0x00000200} if os.name == "nt" else {"start_new_session": True}
|
|
218
|
+
with open(store.home() / "memory.log", "a") as out:
|
|
219
|
+
subprocess.Popen([sys.executable, "-m", "relate_codemem", "embed", "--quiet"],
|
|
220
|
+
stdin=subprocess.DEVNULL, stdout=out, stderr=out, env=env, **kwargs)
|
|
221
|
+
except (OSError, ValueError) as exc:
|
|
222
|
+
store.log(f"background embed not started: {exc}")
|