-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmemory.py
More file actions
209 lines (171 loc) · 6.61 KB
/
Copy pathmemory.py
File metadata and controls
209 lines (171 loc) · 6.61 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
"""
memory.py — pluggable memory backend for Agent Meeting Room
Supported backends (set MEMORY_BACKEND in .env):
obsidian — saves .md notes to an Obsidian vault folder (default if path set)
local — saves to a local folder (no Obsidian needed)
none — memory disabled, no files written
To add a custom backend: implement save(title, content) -> bool
and read(max_chars) -> str, then register it in BACKENDS below.
"""
import os
import re
import uuid
from datetime import datetime
from dotenv import load_dotenv
from semantic_memory import index_note, semantic_status
load_dotenv()
# ── Config ───────────────────────────────────────────────────
MEMORY_BACKEND = os.getenv("MEMORY_BACKEND", "auto").lower()
# Obsidian vault path — optional
OBSIDIAN_VAULT = os.getenv("OBSIDIAN_VAULT_PATH", "")
# Local fallback folder (used when backend=local or obsidian path not set)
LOCAL_MEMORY_DIR = os.getenv(
"LOCAL_MEMORY_PATH",
os.path.join(os.path.dirname(os.path.abspath(__file__)), "meeting_notes")
)
MEMORY_FILE = "meeting_memory.md"
INVALID_FILENAME_CHARS = re.compile(r'[<>:"/\\|?*\x00-\x1f]')
def _resolve_backend() -> str:
"""Auto-detect which backend to use based on env config."""
if MEMORY_BACKEND == "none":
return "none"
if MEMORY_BACKEND == "obsidian" or (MEMORY_BACKEND == "auto" and OBSIDIAN_VAULT):
if OBSIDIAN_VAULT:
return "obsidian"
print("[Memory] MEMORY_BACKEND=obsidian but OBSIDIAN_VAULT_PATH is not set — falling back to local")
return "local"
return "local"
ACTIVE_BACKEND = _resolve_backend()
def _get_memory_dir() -> str:
"""Return the active storage directory."""
if ACTIVE_BACKEND == "obsidian":
return OBSIDIAN_VAULT
return LOCAL_MEMORY_DIR
def safe_note_title(title: str) -> str:
"""Return a filesystem-safe note title stem."""
cleaned = INVALID_FILENAME_CHARS.sub("-", title.strip())
cleaned = re.sub(r"\s+", "_", cleaned)
cleaned = re.sub(r"[-_]{2,}", "_", cleaned)
cleaned = cleaned.strip("._-")
return (cleaned or "Meeting_note")[:50]
def save_to_obsidian(title: str, content: str) -> bool:
"""
Save a note. Works with any backend.
Name kept as save_to_obsidian for backwards compatibility.
"""
if ACTIVE_BACKEND == "none":
return False
memory_dir = _get_memory_dir()
try:
os.makedirs(memory_dir, exist_ok=True)
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M")
safe_title = safe_note_title(title)
filename = f"{datetime.now().strftime('%Y%m%d_%H%M')}_{uuid.uuid4().hex}_{safe_title}.md"
filepath = os.path.join(memory_dir, filename)
note_content = f"""# {title}
*Saved: {timestamp}*
*Backend: {ACTIVE_BACKEND}*
{content}
---
#agent-meeting #auto-saved
"""
with open(filepath, "x", encoding="utf-8") as f:
f.write(note_content)
# Rolling memory file
memory_path = os.path.join(memory_dir, MEMORY_FILE)
with open(memory_path, "a", encoding="utf-8") as f:
f.write(f"\n## {title} — {timestamp}\n{content}\n\n")
index_note(memory_dir, filename, title, content)
print(f"[Memory] Saved to {filepath} (backend: {ACTIVE_BACKEND})")
return True
except Exception as e:
print(f"[Memory] Error saving: {e}")
return False
def get_recent_memory(max_chars: int = 1500) -> str:
"""Read recent memory context for agents."""
if ACTIVE_BACKEND == "none":
return ""
memory_dir = _get_memory_dir()
try:
memory_path = os.path.join(memory_dir, MEMORY_FILE)
if not os.path.exists(memory_path):
return ""
with open(memory_path, "r", encoding="utf-8") as f:
content = f.read()
if len(content) > max_chars:
content = "..." + content[-max_chars:]
return content
except Exception as e:
print(f"[Memory] Error reading: {e}")
return ""
def _build_snippet(content: str, query: str, radius: int = 90) -> str:
lower_content = content.lower()
lower_query = query.lower()
index = lower_content.find(lower_query)
if index < 0:
return content[: radius * 2].strip()
start = max(0, index - radius)
end = min(len(content), index + len(query) + radius)
prefix = "..." if start else ""
suffix = "..." if end < len(content) else ""
return f"{prefix}{content[start:end].strip()}{suffix}"
def search_memory(query: str, limit: int = 8) -> list:
"""Search saved Markdown notes in the active memory folder."""
if ACTIVE_BACKEND == "none":
return []
query = (query or "").strip()
if not query:
return []
memory_dir = _get_memory_dir()
if not os.path.isdir(memory_dir):
return []
results = []
try:
note_names = sorted(
(name for name in os.listdir(memory_dir) if name.lower().endswith(".md")),
reverse=True,
)
for name in note_names:
path = os.path.join(memory_dir, name)
if not os.path.isfile(path):
continue
try:
with open(path, "r", encoding="utf-8") as f:
content = f.read()
except OSError:
continue
if query.lower() not in content.lower():
continue
first_line = next((line.strip("# ").strip() for line in content.splitlines() if line.strip()), name)
results.append({
"title": first_line or name,
"filename": name,
"snippet": _build_snippet(content, query),
})
if len(results) >= limit:
break
except OSError as e:
print(f"[Memory] Error searching: {e}")
return results
def clear_memory() -> bool:
"""Clear the rolling memory file."""
if ACTIVE_BACKEND == "none":
return True
memory_dir = _get_memory_dir()
try:
memory_path = os.path.join(memory_dir, MEMORY_FILE)
if os.path.exists(memory_path):
os.remove(memory_path)
return True
except Exception:
return False
def get_memory_status() -> dict:
"""Return current memory backend info (used by /status endpoint)."""
backend = ACTIVE_BACKEND
memory_dir = _get_memory_dir() if backend != "none" else None
return {
"backend": backend,
"path": memory_dir,
"configured": backend != "none",
"semantic": semantic_status(memory_dir) if memory_dir else {"enabled": False, "available": False},
}