-
Notifications
You must be signed in to change notification settings - Fork 49
Expand file tree
/
Copy pathtools.rs
More file actions
2157 lines (1989 loc) · 72.2 KB
/
Copy pathtools.rs
File metadata and controls
2157 lines (1989 loc) · 72.2 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
use chrono::Utc;
use serde_json::{json, Value};
use icm_core::{
Concept, ConceptLink, Embedder, Feedback, FeedbackStore, Label, Memoir, MemoirStore, Memory,
MemoryStore, Relation,
};
use icm_store::SqliteStore;
use crate::protocol::ToolResult;
// ---------------------------------------------------------------------------
// Tool schemas for tools/list
// ---------------------------------------------------------------------------
pub fn tool_definitions(has_embedder: bool) -> Value {
let mut tools = vec![
// --- Memory tools ---
json!({
"name": "icm_memory_store",
"description": "Store important information in ICM long-term memory. Use to save decisions, preferences, project context, resolved errors — anything that should persist between sessions.",
"inputSchema": {
"type": "object",
"properties": {
"topic": {
"type": "string",
"description": "Category/namespace (e.g. 'projet-kexa', 'preferences', 'decisions-architecture', 'erreurs-resolues')"
},
"content": {
"type": "string",
"description": "Information to memorize — be concise but complete"
},
"importance": {
"type": "string",
"enum": ["critical", "high", "medium", "low"],
"default": "medium",
"description": "critical=never forgotten, high=slow decay, medium=normal, low=fast decay"
},
"keywords": {
"type": "array",
"items": { "type": "string" },
"description": "Keywords to improve search"
},
"raw_excerpt": {
"type": "string",
"description": "Optional verbatim (code, exact error message, etc.)"
}
},
"required": ["topic", "content"]
}
}),
json!({
"name": "icm_memory_recall",
"description": "Search ICM long-term memory. Use to find past decisions, project context, preferences, or solutions to previously encountered problems.",
"inputSchema": {
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "Natural language search query"
},
"topic": {
"type": "string",
"description": "Filter by specific topic (optional)"
},
"limit": {
"type": "integer",
"default": 5,
"minimum": 1,
"maximum": 20,
"description": "Max number of results"
},
"keyword": {
"type": "string",
"description": "Filter results by keyword (exact match on memory keywords)"
}
},
"required": ["query"]
}
}),
json!({
"name": "icm_memory_forget",
"description": "Delete a specific memory by its ID. Use when information is obsolete or incorrect.",
"inputSchema": {
"type": "object",
"properties": {
"id": {
"type": "string",
"description": "Memory ID to delete"
}
},
"required": ["id"]
}
}),
json!({
"name": "icm_memory_consolidate",
"description": "Consolidate all memories of a topic into a single summary. Useful when a topic accumulates too many entries.",
"inputSchema": {
"type": "object",
"properties": {
"topic": {
"type": "string",
"description": "Topic to consolidate"
},
"summary": {
"type": "string",
"description": "Consolidated summary to replace all memories in the topic"
}
},
"required": ["topic", "summary"]
}
}),
json!({
"name": "icm_memory_list_topics",
"description": "List all available topics in memory with their counts.",
"inputSchema": {
"type": "object",
"properties": {}
}
}),
json!({
"name": "icm_memory_stats",
"description": "Get global ICM memory statistics.",
"inputSchema": {
"type": "object",
"properties": {}
}
}),
json!({
"name": "icm_memory_update",
"description": "Update an existing memory in-place. Use to correct, refresh, or extend a memory without creating a duplicate.",
"inputSchema": {
"type": "object",
"properties": {
"id": {
"type": "string",
"description": "Memory ID to update"
},
"content": {
"type": "string",
"description": "New content (replaces existing summary)"
},
"importance": {
"type": "string",
"enum": ["critical", "high", "medium", "low"],
"description": "New importance level (optional, keeps existing if not set)"
},
"keywords": {
"type": "array",
"items": { "type": "string" },
"description": "New keywords (optional, keeps existing if not set)"
}
},
"required": ["id", "content"]
}
}),
json!({
"name": "icm_memory_health",
"description": "Get health stats for all topics: entry count, staleness, consolidation needs. Use to audit memory hygiene.",
"inputSchema": {
"type": "object",
"properties": {
"topic": {
"type": "string",
"description": "Check a specific topic (optional — checks all if omitted)"
}
}
}
}),
// --- Memoir tools ---
json!({
"name": "icm_memoir_create",
"description": "Create a new memoir — a permanent knowledge container. Memoirs hold concepts that never decay.",
"inputSchema": {
"type": "object",
"properties": {
"name": {
"type": "string",
"description": "Unique human-readable name for the memoir"
},
"description": {
"type": "string",
"description": "Description of what this memoir is for"
}
},
"required": ["name"]
}
}),
json!({
"name": "icm_memoir_list",
"description": "List all memoirs with their concept counts.",
"inputSchema": {
"type": "object",
"properties": {}
}
}),
json!({
"name": "icm_memoir_show",
"description": "Show a memoir's stats, labels, and all its concepts.",
"inputSchema": {
"type": "object",
"properties": {
"name": {
"type": "string",
"description": "Memoir name"
}
},
"required": ["name"]
}
}),
json!({
"name": "icm_memoir_add_concept",
"description": "Add a permanent concept to a memoir. Concepts are knowledge nodes that get refined, never decayed.",
"inputSchema": {
"type": "object",
"properties": {
"memoir": {
"type": "string",
"description": "Memoir name"
},
"name": {
"type": "string",
"description": "Concept name (unique within memoir)"
},
"definition": {
"type": "string",
"description": "Dense description of the concept"
},
"labels": {
"type": "string",
"description": "Comma-separated labels (namespace:value or plain tag). E.g. 'domain:arch,type:decision'"
}
},
"required": ["memoir", "name", "definition"]
}
}),
json!({
"name": "icm_memoir_refine",
"description": "Refine an existing concept with a new, improved definition. Bumps revision and boosts confidence.",
"inputSchema": {
"type": "object",
"properties": {
"memoir": {
"type": "string",
"description": "Memoir name"
},
"name": {
"type": "string",
"description": "Concept name"
},
"definition": {
"type": "string",
"description": "New, refined definition"
}
},
"required": ["memoir", "name", "definition"]
}
}),
json!({
"name": "icm_memoir_search",
"description": "Full-text search concepts within a memoir.",
"inputSchema": {
"type": "object",
"properties": {
"memoir": {
"type": "string",
"description": "Memoir name"
},
"query": {
"type": "string",
"description": "Search query"
},
"label": {
"type": "string",
"description": "Filter by label (e.g. 'domain:tech')"
},
"limit": {
"type": "integer",
"default": 10,
"description": "Max results"
}
},
"required": ["memoir", "query"]
}
}),
json!({
"name": "icm_memoir_link",
"description": "Create a directed, typed edge between two concepts in the same memoir.",
"inputSchema": {
"type": "object",
"properties": {
"memoir": {
"type": "string",
"description": "Memoir name"
},
"from": {
"type": "string",
"description": "Source concept name"
},
"to": {
"type": "string",
"description": "Target concept name"
},
"relation": {
"type": "string",
"enum": ["part_of", "depends_on", "related_to", "contradicts", "refines", "alternative_to", "caused_by", "instance_of", "superseded_by"],
"description": "Relation type"
}
},
"required": ["memoir", "from", "to", "relation"]
}
}),
json!({
"name": "icm_memoir_inspect",
"description": "Inspect a concept and its graph neighborhood (BFS).",
"inputSchema": {
"type": "object",
"properties": {
"memoir": {
"type": "string",
"description": "Memoir name"
},
"name": {
"type": "string",
"description": "Concept name"
},
"depth": {
"type": "integer",
"default": 1,
"description": "BFS depth"
}
},
"required": ["memoir", "name"]
}
}),
json!({
"name": "icm_memoir_search_all",
"description": "Full-text search concepts across all memoirs.",
"inputSchema": {
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "Search query"
},
"limit": {
"type": "integer",
"default": 10,
"description": "Max results"
}
},
"required": ["query"]
}
}),
// --- Feedback tools ---
json!({
"name": "icm_feedback_record",
"description": "Record a correction/feedback when an AI prediction was wrong. Helps improve future predictions by learning from mistakes.",
"inputSchema": {
"type": "object",
"properties": {
"topic": {
"type": "string",
"description": "Category/namespace for this feedback (e.g. 'triage-owner/repo', 'pr-analysis')"
},
"context": {
"type": "string",
"description": "What was the situation / input that led to the prediction"
},
"predicted": {
"type": "string",
"description": "What the AI predicted or did"
},
"corrected": {
"type": "string",
"description": "What the correct answer/action should have been"
},
"reason": {
"type": "string",
"description": "Why the correction was made (optional)"
},
"source": {
"type": "string",
"description": "Which tool/pipeline generated the prediction (optional)"
}
},
"required": ["topic", "context", "predicted", "corrected"]
}
}),
json!({
"name": "icm_feedback_search",
"description": "Search past feedback/corrections to inform current predictions. Use before making predictions to learn from past mistakes.",
"inputSchema": {
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "Search query to find relevant past corrections"
},
"topic": {
"type": "string",
"description": "Filter by topic (optional)"
},
"limit": {
"type": "integer",
"default": 5,
"minimum": 1,
"maximum": 20,
"description": "Max number of results"
}
},
"required": ["query"]
}
}),
json!({
"name": "icm_feedback_stats",
"description": "Get feedback statistics: total count, breakdown by topic, most applied corrections.",
"inputSchema": {
"type": "object",
"properties": {}
}
}),
];
if has_embedder {
tools.push(json!({
"name": "icm_memory_embed_all",
"description": "Generate embeddings for all memories that don't have one yet. Use this to backfill vector search capability.",
"inputSchema": {
"type": "object",
"properties": {
"topic": {
"type": "string",
"description": "Only embed memories in this topic (optional)"
}
}
}
}));
}
json!({ "tools": tools })
}
// ---------------------------------------------------------------------------
// Tool dispatch
// ---------------------------------------------------------------------------
pub fn call_tool(
store: &SqliteStore,
embedder: Option<&dyn Embedder>,
name: &str,
args: &Value,
compact: bool,
) -> ToolResult {
match name {
// Memory tools
"icm_memory_store" => tool_store(store, embedder, args, compact),
"icm_memory_recall" => tool_recall(store, embedder, args, compact),
"icm_memory_forget" => tool_forget(store, args),
"icm_memory_update" => tool_update(store, embedder, args),
"icm_memory_consolidate" => tool_consolidate(store, args),
"icm_memory_list_topics" => tool_list_topics(store),
"icm_memory_stats" => tool_stats(store),
"icm_memory_health" => tool_health(store, args),
"icm_memory_embed_all" => tool_embed_all(store, embedder, args),
// Memoir tools
"icm_memoir_create" => tool_memoir_create(store, args),
"icm_memoir_list" => tool_memoir_list(store),
"icm_memoir_show" => tool_memoir_show(store, args),
"icm_memoir_add_concept" => tool_memoir_add_concept(store, args),
"icm_memoir_refine" => tool_memoir_refine(store, args),
"icm_memoir_search" => tool_memoir_search(store, args),
"icm_memoir_search_all" => tool_memoir_search_all(store, args),
"icm_memoir_link" => tool_memoir_link(store, args),
"icm_memoir_inspect" => tool_memoir_inspect(store, args),
// Feedback tools
"icm_feedback_record" => tool_feedback_record(store, args, compact),
"icm_feedback_search" => tool_feedback_search(store, args),
"icm_feedback_stats" => tool_feedback_stats(store),
_ => ToolResult::error(format!("unknown tool: {name}")),
}
}
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
fn get_str<'a>(args: &'a Value, key: &str) -> Option<&'a str> {
args.get(key).and_then(|v| v.as_str())
}
fn get_i64(args: &Value, key: &str, default: i64) -> i64 {
args.get(key).and_then(|v| v.as_i64()).unwrap_or(default)
}
fn resolve_memoir(store: &SqliteStore, name: &str) -> Result<Memoir, ToolResult> {
store
.get_memoir_by_name(name)
.map_err(|e| ToolResult::error(format!("db error: {e}")))?
.ok_or_else(|| ToolResult::error(format!("memoir not found: {name}")))
}
// ---------------------------------------------------------------------------
// Memory tool handlers
// ---------------------------------------------------------------------------
fn tool_store(
store: &SqliteStore,
embedder: Option<&dyn Embedder>,
args: &Value,
compact: bool,
) -> ToolResult {
let topic = match get_str(args, "topic") {
Some(t) => t,
None => return ToolResult::error("missing required field: topic".into()),
};
let content = match get_str(args, "content") {
Some(c) => c,
None => return ToolResult::error("missing required field: content".into()),
};
let importance_str = get_str(args, "importance").unwrap_or("medium");
let importance = importance_str
.parse()
.unwrap_or(icm_core::Importance::Medium);
let mut memory = Memory::new(topic.into(), content.into(), importance);
if let Some(keywords) = args.get("keywords").and_then(|v| v.as_array()) {
memory.keywords = keywords
.iter()
.filter_map(|v| v.as_str().map(String::from))
.collect();
}
if let Some(raw) = get_str(args, "raw_excerpt") {
memory.raw_excerpt = Some(raw.into());
}
// Auto-embed if embedder is available
if let Some(emb) = embedder {
let text = format!("{topic} {content}");
match emb.embed(&text) {
Ok(vec) => memory.embedding = Some(vec),
Err(e) => tracing::warn!("embedding failed: {e}"),
}
}
// Dedup check: if a very similar memory exists in the same topic, update it instead
if let Some(emb) = embedder {
let text = format!("{topic} {content}");
if let Ok(query_emb) = emb.embed(&text) {
if let Ok(similar) = store.search_hybrid(&text, &query_emb, 1) {
if let Some((existing, score)) = similar.first() {
if score > &0.85 && existing.topic == topic {
// Very similar content in same topic — update instead of duplicate
let mut updated = existing.clone();
updated.summary = content.to_string();
updated.updated_at = Utc::now();
updated.weight = 1.0; // Reset weight on update
if let Some(raw) = get_str(args, "raw_excerpt") {
updated.raw_excerpt = Some(raw.into());
}
if let Some(keywords_arr) = args.get("keywords").and_then(|v| v.as_array())
{
updated.keywords = keywords_arr
.iter()
.filter_map(|v| v.as_str().map(String::from))
.collect();
}
updated.importance = importance;
updated.embedding = Some(query_emb);
if let Err(e) = store.update(&updated) {
return ToolResult::error(format!("failed to update: {e}"));
}
return if compact {
ToolResult::text(format!("ok:{}", updated.id))
} else {
ToolResult::text(format!(
"Updated existing memory (similarity {score:.2}): {}",
updated.id
))
};
}
}
}
}
}
match store.store(memory) {
Ok(id) => {
if compact {
ToolResult::text(format!("ok:{id}"))
} else {
// Check if topic needs consolidation
let hint = if let Ok(count) = store.count_by_topic(topic) {
if count > 7 {
format!(
"\n⚠ Topic '{topic}' has {count} entries — consider consolidating with icm_memory_consolidate."
)
} else {
String::new()
}
} else {
String::new()
};
ToolResult::text(format!("Stored memory: {id}{hint}"))
}
}
Err(e) => ToolResult::error(format!("failed to store: {e}")),
}
}
fn tool_recall(
store: &SqliteStore,
embedder: Option<&dyn Embedder>,
args: &Value,
compact: bool,
) -> ToolResult {
// Auto-decay if >24h since last decay
let _ = store.maybe_auto_decay();
let query = match get_str(args, "query") {
Some(q) => q,
None => return ToolResult::error("missing required field: query".into()),
};
let limit = get_i64(args, "limit", 5) as usize;
let topic = get_str(args, "topic");
let keyword = get_str(args, "keyword");
// Try hybrid search if embedder is available
if let Some(emb) = embedder {
if let Ok(query_emb) = emb.embed(query) {
if let Ok(results) = store.search_hybrid(query, &query_emb, limit) {
let mut scored_results = results;
if let Some(t) = topic {
scored_results.retain(|(m, _)| m.topic == t);
}
if let Some(kw) = keyword {
scored_results.retain(|(m, _)| m.keywords.iter().any(|k| k.contains(kw)));
}
// Update access counts
for (mem, _) in &scored_results {
let _ = store.update_access(&mem.id);
}
if scored_results.is_empty() {
return ToolResult::text("No memories found.".into());
}
let mut output = String::new();
if compact {
for (mem, _) in &scored_results {
output.push_str(&format!("[{}] {}\n", mem.topic, mem.summary));
}
} else {
for (mem, score) in &scored_results {
output.push_str(&format!(
"--- {} [score: {:.3}] ---\n topic: {}\n importance: {}\n weight: {:.3}\n summary: {}\n",
mem.id, score, mem.topic, mem.importance, mem.weight, mem.summary
));
if !mem.keywords.is_empty() {
output.push_str(&format!(" keywords: {}\n", mem.keywords.join(", ")));
}
if let Some(ref raw) = mem.raw_excerpt {
output.push_str(&format!(" raw: {raw}\n"));
}
output.push('\n');
}
}
return ToolResult::text(output);
}
}
}
// Fallback: FTS then keywords
let mut results = match store.search_fts(query, limit) {
Ok(r) => r,
Err(e) => return ToolResult::error(format!("search error: {e}")),
};
if results.is_empty() {
let keywords: Vec<&str> = query.split_whitespace().collect();
results = match store.search_by_keywords(&keywords, limit) {
Ok(r) => r,
Err(e) => return ToolResult::error(format!("search error: {e}")),
};
}
if let Some(t) = topic {
results.retain(|m| m.topic == t);
}
if let Some(kw) = keyword {
results.retain(|m| m.keywords.iter().any(|k| k.contains(kw)));
}
// Update access counts
for mem in &results {
let _ = store.update_access(&mem.id);
}
if results.is_empty() {
return ToolResult::text("No memories found.".into());
}
let mut output = String::new();
if compact {
for mem in &results {
output.push_str(&format!("[{}] {}\n", mem.topic, mem.summary));
}
} else {
for mem in &results {
output.push_str(&format!(
"--- {} ---\n topic: {}\n importance: {}\n weight: {:.3}\n summary: {}\n",
mem.id, mem.topic, mem.importance, mem.weight, mem.summary
));
if !mem.keywords.is_empty() {
output.push_str(&format!(" keywords: {}\n", mem.keywords.join(", ")));
}
if let Some(ref raw) = mem.raw_excerpt {
output.push_str(&format!(" raw: {raw}\n"));
}
output.push('\n');
}
}
ToolResult::text(output)
}
fn tool_forget(store: &SqliteStore, args: &Value) -> ToolResult {
let id = match get_str(args, "id") {
Some(id) => id,
None => return ToolResult::error("missing required field: id".into()),
};
match store.delete(id) {
Ok(()) => ToolResult::text(format!("Deleted memory: {id}")),
Err(e) => ToolResult::error(format!("failed to delete: {e}")),
}
}
fn tool_consolidate(store: &SqliteStore, args: &Value) -> ToolResult {
let topic = match get_str(args, "topic") {
Some(t) => t,
None => return ToolResult::error("missing required field: topic".into()),
};
let summary = match get_str(args, "summary") {
Some(s) => s,
None => return ToolResult::error("missing required field: summary".into()),
};
let consolidated = Memory::new(topic.into(), summary.into(), icm_core::Importance::High);
match store.consolidate_topic(topic, consolidated) {
Ok(()) => ToolResult::text(format!("Consolidated topic: {topic}")),
Err(e) => ToolResult::error(format!("failed to consolidate: {e}")),
}
}
fn tool_list_topics(store: &SqliteStore) -> ToolResult {
match store.list_topics() {
Ok(topics) => {
if topics.is_empty() {
return ToolResult::text("No topics yet.".into());
}
let mut output = String::from("Topics:\n");
for (topic, count) in &topics {
output.push_str(&format!(" {topic}: {count} memories\n"));
}
ToolResult::text(output)
}
Err(e) => ToolResult::error(format!("failed to list topics: {e}")),
}
}
fn tool_stats(store: &SqliteStore) -> ToolResult {
match store.stats() {
Ok(stats) => {
let mut output = format!(
"Memories: {}\nTopics: {}\nAvg weight: {:.3}\n",
stats.total_memories, stats.total_topics, stats.avg_weight
);
if let Some(oldest) = stats.oldest_memory {
output.push_str(&format!("Oldest: {}\n", oldest.format("%Y-%m-%d %H:%M")));
}
if let Some(newest) = stats.newest_memory {
output.push_str(&format!("Newest: {}\n", newest.format("%Y-%m-%d %H:%M")));
}
ToolResult::text(output)
}
Err(e) => ToolResult::error(format!("failed to get stats: {e}")),
}
}
fn tool_update(store: &SqliteStore, embedder: Option<&dyn Embedder>, args: &Value) -> ToolResult {
let id = match get_str(args, "id") {
Some(id) => id,
None => return ToolResult::error("missing required field: id".into()),
};
let content = match get_str(args, "content") {
Some(c) => c,
None => return ToolResult::error("missing required field: content".into()),
};
let mut memory = match store.get(id) {
Ok(Some(m)) => m,
Ok(None) => return ToolResult::error(format!("memory not found: {id}")),
Err(e) => return ToolResult::error(format!("db error: {e}")),
};
memory.summary = content.to_string();
memory.updated_at = Utc::now();
memory.weight = 1.0; // Reset weight on update (refreshed content)
if let Some(imp_str) = get_str(args, "importance") {
if let Ok(imp) = imp_str.parse() {
memory.importance = imp;
}
}
if let Some(keywords_arr) = args.get("keywords").and_then(|v| v.as_array()) {
memory.keywords = keywords_arr
.iter()
.filter_map(|v| v.as_str().map(String::from))
.collect();
}
// Re-embed if embedder available
if let Some(emb) = embedder {
let text = format!("{} {}", memory.topic, content);
if let Ok(vec) = emb.embed(&text) {
memory.embedding = Some(vec);
}
}
match store.update(&memory) {
Ok(()) => ToolResult::text(format!("Updated memory: {id}")),
Err(e) => ToolResult::error(format!("failed to update: {e}")),
}
}
fn tool_health(store: &SqliteStore, args: &Value) -> ToolResult {
let specific_topic = get_str(args, "topic");
let topics = if let Some(t) = specific_topic {
vec![(t.to_string(), 0usize)]
} else {
match store.list_topics() {
Ok(t) => t,
Err(e) => return ToolResult::error(format!("failed to list topics: {e}")),
}
};
if topics.is_empty() {
return ToolResult::text("No topics yet.".into());
}
let mut output = String::from("Memory Health Report:\n\n");
let mut total_stale = 0usize;
let mut topics_needing_consolidation = 0usize;
for (topic, _) in &topics {
match store.topic_health(topic) {
Ok(health) => {
let status = if health.needs_consolidation && health.stale_count > 0 {
"⚠ NEEDS ATTENTION"
} else if health.needs_consolidation {
"⚠ consolidate"
} else if health.stale_count > 0 {
"○ has stale entries"
} else {
"✓ healthy"
};
output.push_str(&format!(
" {topic}: {status}\n entries: {} avg_weight: {:.2} stale: {} avg_access: {:.1}\n",
health.entry_count, health.avg_weight, health.stale_count, health.avg_access_count
));
if health.needs_consolidation {
topics_needing_consolidation += 1;
}
total_stale += health.stale_count;
}
Err(_) => {
output.push_str(&format!(" {topic}: (error reading)\n"));
}
}
}
output.push_str(&format!(
"\nSummary: {} topics, {} need consolidation, {} stale entries total\n",
topics.len(),
topics_needing_consolidation,
total_stale
));
ToolResult::text(output)
}
fn tool_embed_all(
store: &SqliteStore,
embedder: Option<&dyn Embedder>,
args: &Value,
) -> ToolResult {
let embedder = match embedder {
Some(e) => e,
None => return ToolResult::error("embeddings not available".into()),
};
let topic_filter = get_str(args, "topic");
// Get all memories, filtered by topic if specified
let memories = if let Some(t) = topic_filter {
match store.get_by_topic(t) {
Ok(m) => m,
Err(e) => return ToolResult::error(format!("failed to list memories: {e}")),
}
} else {
// Get all by listing topics
let topics = match store.list_topics() {
Ok(t) => t,
Err(e) => return ToolResult::error(format!("failed to list topics: {e}")),
};
let mut all = Vec::new();
for (t, _) in &topics {
if let Ok(mems) = store.get_by_topic(t) {
all.extend(mems);
}
}
all
};
// Filter to only those without embeddings
let to_embed: Vec<&Memory> = memories.iter().filter(|m| m.embedding.is_none()).collect();
if to_embed.is_empty() {
return ToolResult::text("All memories already have embeddings.".into());
}
let total = to_embed.len();
let mut embedded = 0;
let mut errors = 0;
for mem in &to_embed {
let text = format!("{} {}", mem.topic, mem.summary);
match embedder.embed(&text) {
Ok(vec) => {
let mut updated = (*mem).clone();
updated.embedding = Some(vec);
if store.update(&updated).is_ok() {
embedded += 1;
} else {
errors += 1;
}
}
Err(_) => errors += 1,
}
}
ToolResult::text(format!(
"Embedded {embedded}/{total} memories ({errors} errors)"
))
}
// ---------------------------------------------------------------------------
// Memoir tool handlers
// ---------------------------------------------------------------------------
fn tool_memoir_create(store: &SqliteStore, args: &Value) -> ToolResult {
let name = match get_str(args, "name") {
Some(n) => n,
None => return ToolResult::error("missing required field: name".into()),
};
let description = get_str(args, "description").unwrap_or("");
let memoir = Memoir::new(name.into(), description.into());
match store.create_memoir(memoir) {
Ok(id) => ToolResult::text(format!("Created memoir '{name}': {id}")),
Err(e) => ToolResult::error(format!("failed to create memoir: {e}")),
}
}
fn tool_memoir_list(store: &SqliteStore) -> ToolResult {
let memoirs = match store.list_memoirs() {
Ok(m) => m,
Err(e) => return ToolResult::error(format!("failed to list memoirs: {e}")),
};
if memoirs.is_empty() {
return ToolResult::text("No memoirs yet.".into());
}
let mut output = String::from("Memoirs:\n");
for m in &memoirs {
let stats = store.memoir_stats(&m.id).ok();
let concept_count = stats.map(|s| s.total_concepts).unwrap_or(0);
output.push_str(&format!(
" {} ({} concepts) — {}\n",