-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathquick_memory.py
More file actions
executable file
Β·360 lines (279 loc) Β· 13 KB
/
Copy pathquick_memory.py
File metadata and controls
executable file
Β·360 lines (279 loc) Β· 13 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
#!/usr/bin/env python3
"""
Quick Memory Query Interface
Fast access to relevant memories during conversations.
Use this to get instant memory suggestions without starting the full assistant.
"""
import sys
import argparse
from memory_integration import MemoryIntegration
from token_tracker import tracker
# Global instance for performance - lazy loaded
_memory_integration = None
def get_memory_integration():
"""Get the shared MemoryIntegration instance (lazy loaded)"""
global _memory_integration
if _memory_integration is None:
try:
_memory_integration = MemoryIntegration()
except ImportError as e:
raise RuntimeError(f"Missing required dependencies: {e}\nπ‘ Try: pip install -r requirements.txt")
except FileNotFoundError as e:
raise RuntimeError(f"Memory system files not found: {e}\nπ‘ Try: python auto_bootstrap.py")
except PermissionError as e:
raise RuntimeError(f"Permission denied accessing memory files: {e}\nπ‘ Check file permissions in the project directory")
except Exception as e:
raise RuntimeError(f"Failed to initialize memory system: {e}\nπ‘ Try: python quick_memory.py tool")
return _memory_integration
def get_memory_suggestion(query: str, max_memories: int = 3) -> str:
"""
Get quick memory suggestions for a query
Args:
query: The topic or question to get memories for
max_memories: Maximum number of memories to return
Returns:
Formatted memory suggestions
"""
if not query or not query.strip():
return "β Query cannot be empty. Please provide a topic or question to search for."
if max_memories < 1 or max_memories > 10:
return "β max_memories must be between 1 and 10."
try:
integration = get_memory_integration()
# Add the query as user context
integration.update_conversation("user", query)
# Get relevant memories
result = integration.get_context_memories(max_memories=max_memories)
if result["memory_count"] == 0:
return f"π No relevant memories found for '{query}'. Consider adding some knowledge about this topic."
response = f"π§ **Relevant Memories** ({result['memory_count']} found, {result['tokens_used']} tokens):\n\n"
response += result["formatted_context"]
return response
except ConnectionError as e:
return f"β Network error accessing memory system: {e}\nπ‘ Check your internet connection"
except TimeoutError as e:
return f"β Timeout error: {e}\nπ‘ Try again in a moment"
except ValueError as e:
return f"β Invalid query format: {e}\nπ‘ Try rephrasing your question"
except Exception as e:
return f"β Unexpected error accessing memory system: {e}\nπ‘ Try: python quick_memory.py tool"
def add_memory_quick(content: str, tags: str = "", importance: float = 0.5):
"""
Quickly add a memory to the system
Args:
content: Memory content
tags: Comma-separated tags
importance: Importance score (0.0-1.0)
"""
if not content or not content.strip():
return "β Memory content cannot be empty. Please provide meaningful content to remember."
if not (0.0 <= importance <= 1.0):
return "β Importance must be between 0.0 and 1.0."
try:
integration = get_memory_integration()
tag_list = [tag.strip() for tag in tags.split(",")] if tags else []
memory_id = integration.add_memory(content, importance=importance, tags=tag_list)
tag_info = f" with tags: {', '.join(tag_list)}" if tag_list else ""
return f"β
Memory added (ID: {memory_id[:8]}){tag_info}"
except ValueError as e:
return f"β Invalid memory format: {e}\nπ‘ Check your content and importance values"
except PermissionError as e:
return f"β Permission denied saving memory: {e}\nπ‘ Check file permissions"
except Exception as e:
return f"β Error adding memory: {e}\nπ‘ Try: python quick_memory.py tool"
def delete_memory_quick(memory_id: str):
"""
Quickly delete a memory from the system
Args:
memory_id: ID of the memory to delete
"""
if not memory_id or not memory_id.strip():
return "β Memory ID cannot be empty. Please provide a valid memory ID."
try:
integration = get_memory_integration()
deleted = integration.delete_memory(memory_id)
if deleted:
return f"ποΈ Memory {memory_id} successfully deleted and forgotten"
else:
return f"β Memory {memory_id} not found\nπ‘ Use 'python quick_memory.py stats' to see available memories"
except ValueError as e:
return f"β Invalid memory ID format: {e}\nπ‘ Memory IDs are typically 8-character strings"
except PermissionError as e:
return f"β Permission denied deleting memory: {e}\nπ‘ Check file permissions"
except Exception as e:
return f"β Error deleting memory: {e}\nπ‘ Try: python quick_memory.py tool"
def wipe_all_memories():
"""
Delete all memories and start fresh
Returns:
Status message
"""
try:
integration = get_memory_integration()
count = integration.wipe_all_memories()
if count > 0:
return f"π§Ή Wiped {count} memories. Memory system is now empty and ready for fresh start."
else:
return "βΉοΈ No memories to wipe. Memory system was already empty."
except PermissionError as e:
return f"β Permission denied wiping memories: {e}\nπ‘ Check file permissions"
except Exception as e:
return f"β Error wiping memories: {e}\nπ‘ Try: python quick_memory.py tool"
def show_memory_stats():
"""Show current memory system statistics"""
try:
integration = get_memory_integration()
stats = integration.get_system_status()
return f"""π **Memory System Stats:**
- Total memories: {stats['memory_system']['total_memories']}
- Integration rate: {stats['integration_layer']['integration_rate']:.1%}
- Context window: {stats['context_manager']['usage_percentage']:.1f}% utilized
- Memory performance: {stats.get('integration_layer', {}).get('performance', 'N/A')}"""
except Exception as e:
return f"β Error getting stats: {e}"
def show_token_stats():
"""Show current token usage statistics for Brain and MemMan"""
return tracker.format_stats()
def check_autonomous_milestone(context: str = "manual_check") -> str:
"""Check if current system state warrants an autonomous milestone commit"""
try:
integration = get_memory_integration()
if hasattr(integration.bootstrap_handler, 'check_and_commit_milestone'):
success = integration.bootstrap_handler.check_and_commit_milestone(context)
if success:
return "π― AUTONOMOUS MILESTONE: Significant improvements detected and committed!"
else:
return "βΉοΈ No milestone-worthy improvements detected at this time."
else:
return "β Autonomous milestone system not available"
except Exception as e:
return f"β Error checking milestone: {e}"
def get_conversation_bootstrap() -> str:
"""Get bootstrap knowledge for Cursor IDE conversations"""
try:
from bootstrap_memory import bootstrap_conversation_awareness
return bootstrap_conversation_awareness()
except Exception as e:
return f"β Error getting bootstrap knowledge: {e}"
def bootstrap_tool() -> str:
"""CRITICAL BOOTSTRAP TOOL - Must be called first in every new conversation"""
try:
from bootstrap_memory import execute_bootstrap_tool
return execute_bootstrap_tool()
except Exception as e:
return f"β CRITICAL ERROR: Bootstrap tool failed: {e}\n\nPlease manually run: python quick_memory.py bootstrap"
def get_memory_reminder() -> str:
"""Get a memory-saving reminder"""
try:
integration = get_memory_integration()
if hasattr(integration.bootstrap_handler, 'get_memory_saving_reminder'):
return integration.bootstrap_handler.get_memory_saving_reminder()
else:
return "π§ **MEMORY REMINDER**: Save important insights!\nUse: python quick_memory.py add \"insight\" \"tags\" 0.8"
except Exception as e:
return f"β Error getting reminder: {e}"
def create_parser():
"""Create argument parser for the CLI interface"""
parser = argparse.ArgumentParser(
description="π§ Quick Memory Query Interface - Fast access to relevant memories",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
π§ **CRITICAL**: Start EVERY new conversation with:
python quick_memory.py tool
Examples:
python quick_memory.py query "How does the memory system work?"
python quick_memory.py add "New insight" "tags,here" 0.8
python quick_memory.py delete "memory_id"
python quick_memory.py wipe
python quick_memory.py stats
python quick_memory.py milestone "manual_check"
python quick_memory.py remind
"""
)
subparsers = parser.add_subparsers(dest='command', help='Available commands')
# Query command
query_parser = subparsers.add_parser('query', help='Query relevant memories')
query_parser.add_argument('query', help='The topic or question to search for')
query_parser.add_argument('--max-memories', type=int, default=3, help='Maximum memories to return (default: 3)')
# Add command
add_parser = subparsers.add_parser('add', help='Add a new memory')
add_parser.add_argument('content', help='Memory content to add')
add_parser.add_argument('tags', nargs='?', default='', help='Comma-separated tags (e.g., "tag1,tag2")')
add_parser.add_argument('importance', nargs='?', type=float, default=0.5, help='Importance score 0.0-1.0 (default: 0.5)')
# Delete command
delete_parser = subparsers.add_parser('delete', help='Delete a memory')
delete_parser.add_argument('memory_id', help='ID of the memory to delete')
# Wipe command
subparsers.add_parser('wipe', help='Delete all memories and start fresh')
# Stats command
subparsers.add_parser('stats', help='Show memory system statistics')
# Tokens command
subparsers.add_parser('tokens', help='Show token usage and cost stats for Brain/MemMan')
# Milestone command
milestone_parser = subparsers.add_parser('milestone', help='Check for autonomous milestone commit')
milestone_parser.add_argument('--context', default='manual_check', help='Context for milestone check')
# Bootstrap command
subparsers.add_parser('bootstrap', help='Get conversation bootstrap knowledge')
# Tool command
subparsers.add_parser('tool', help='CRITICAL BOOTSTRAP TOOL - Run at start of every conversation')
# Remind command
subparsers.add_parser('remind', help='Get memory-saving reminder')
return parser
def main():
"""Main entry point with improved argument parsing and error handling"""
parser = create_parser()
try:
args = parser.parse_args()
except SystemExit:
# argparse handles --help and invalid arguments, but let's add a helpful message
if len(sys.argv) == 1:
print("π§ **CRITICAL**: Start EVERY new conversation with: python quick_memory.py tool")
return
if not args.command:
parser.print_help()
return
try:
if args.command == 'query':
result = get_memory_suggestion(args.query, args.max_memories)
print(result)
elif args.command == 'add':
result = add_memory_quick(args.content, args.tags, args.importance)
print(result)
elif args.command == 'delete':
result = delete_memory_quick(args.memory_id)
print(result)
elif args.command == 'wipe':
result = wipe_all_memories()
print(result)
elif args.command == 'stats':
result = show_memory_stats()
print(result)
elif args.command == 'tokens':
result = show_token_stats()
print(result)
elif args.command == 'milestone':
result = check_autonomous_milestone(args.context)
print(result)
elif args.command == 'bootstrap':
result = get_conversation_bootstrap()
print(result)
elif args.command == 'tool':
result = bootstrap_tool()
print(result)
elif args.command == 'remind':
result = get_memory_reminder()
print(result)
except KeyboardInterrupt:
print("\nπ Operation cancelled by user")
sys.exit(1)
except RuntimeError as e:
# Handle initialization errors specifically
print(f"β Memory system initialization failed: {e}")
sys.exit(1)
except Exception as e:
print(f"β Unexpected error: {e}")
print("π‘ Tip: Run 'python quick_memory.py tool' to bootstrap the memory system")
print("π For more help: python quick_memory.py --help")
sys.exit(1)
if __name__ == "__main__":
main()