-
-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathsessionMemoryDefinitions.ts
More file actions
2052 lines (1929 loc) · 79.8 KB
/
Copy pathsessionMemoryDefinitions.ts
File metadata and controls
2052 lines (1929 loc) · 79.8 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
import { type Tool } from "@modelcontextprotocol/sdk/types.js";
// ─── Session Save Ledger ─────────────────────────────────────
export const SESSION_SAVE_LEDGER_TOOL: Tool = {
name: "session_save_ledger",
description:
"Save an immutable session log entry to the session ledger. " +
"Use this at the END of each work session to record what was accomplished. " +
"The ledger is append-only — entries cannot be updated or deleted. " +
"This creates a permanent audit trail of all agent work sessions.",
inputSchema: {
type: "object",
properties: {
project: {
type: "string",
description: "Project identifier (e.g. 'bcba-private', 'my-app'). Used to group and filter sessions.",
},
conversation_id: {
type: "string",
description: "Unique conversation/session identifier.",
},
summary: {
type: "string",
description: "Brief summary of what was accomplished in this session.",
},
todos: {
type: "array",
items: { type: "string" },
description: "Optional list of open TODO items remaining after this session.",
},
files_changed: {
type: "array",
items: { type: "string" },
description: "Optional list of files created or modified during this session.",
},
decisions: {
type: "array",
items: { type: "string" },
description: "Optional list of key decisions made during this session.",
},
role: {
type: "string",
description: "Optional. Agent role for Hivemind scoping (e.g., 'dev', 'qa', 'pm'). Omit to let the server auto-resolve from dashboard settings.",
},
},
required: ["project", "conversation_id", "summary"],
},
};
// ─── Session Save Handoff ─────────────────────────────────────
// REVIEWER NOTE: v0.4.0 adds expected_version for Optimistic Concurrency
// Control (OCC). See Enhancement #5 in the implementation plan.
//
// UPGRADE PATH: The expected_version field is optional so v0.3.0
// clients still work without changes. When omitted, the version
// check is skipped entirely (backward compatible).
export const SESSION_SAVE_HANDOFF_TOOL: Tool = {
name: "session_save_handoff",
description:
"Upsert the latest project handoff state for the next session to consume on boot. " +
"This is the 'live context' that gets loaded when a new session starts. " +
"Calling this replaces the previous handoff for the same project (upsert on project).\n\n" +
"**v5.4 CRDT Merge**: On version conflict, a CRDT OR-Map engine automatically merges " +
"your changes with concurrent work (Add-Wins OR-Set for arrays, Last-Writer-Wins for scalars). " +
"Pass expected_version to enable concurrency control.\n\n" +
"**v0.4.0 OCC**: If you received a version number from session_load_context, " +
"/resume_session prompt, or memory resource attachment, you MUST pass it as " +
"expected_version to prevent overwriting another session's changes.",
inputSchema: {
type: "object",
properties: {
project: {
type: "string",
description: "Project identifier — must match the project used in session_save_ledger.",
},
expected_version: {
type: "integer",
description:
"v0.4.0: The version number you received when loading context. " +
"Pass this to enable optimistic concurrency control. " +
"If omitted, version check is skipped (backward compatible).",
},
open_todos: {
type: "array",
items: { type: "string" },
description: "Current open TODO items that need attention in the next session.",
},
active_branch: {
type: "string",
description: "Git branch or context the next session should resume on.",
},
last_summary: {
type: "string",
description: "Summary of the most recent session — used for quick context recovery.",
},
key_context: {
type: "string",
description: "Free-form critical context the next session needs to know.",
},
role: {
type: "string",
description: "Optional. Agent role for Hivemind scoping (e.g., 'dev', 'qa', 'pm'). Omit to let the server auto-resolve from dashboard settings.",
},
disable_merge: {
type: "boolean",
description: "Set to true to disable automatic CRDT merging and fail strictly on version conflict (original OCC behavior). Default: false.",
},
},
required: ["project"],
},
};
// ─── Session Load Context ─────────────────────────────────────
export const SESSION_LOAD_CONTEXT_TOOL: Tool = {
name: "session_load_context",
description:
"Load session context for a project using progressive context loading. " +
"Use this at the START of a new session to recover previous work state. " +
"Three levels available:\n" +
"- **quick**: Just the latest project state — keywords and open TODOs (~50 tokens)\n" +
"- **standard**: Project state plus recent session summaries and decisions (~200 tokens, recommended)\n" +
"- **deep**: Everything — full session history with all files changed, TODOs, and decisions (~1000+ tokens)",
inputSchema: {
type: "object",
properties: {
project: {
type: "string",
description: "Project identifier to load context for.",
},
level: {
type: "string",
enum: ["quick", "standard", "deep"],
description: "How much context to load: 'quick' (just TODOs), 'standard' (recommended — includes recent summaries), or 'deep' (full history). Default: standard.",
},
role: {
type: "string",
description: "Optional. Agent role for Hivemind scoping (e.g., 'dev', 'qa', 'pm'). Omit to let the server auto-resolve from dashboard settings. When set, also injects active_team roster.",
},
// v4.0: Token Budget
max_tokens: {
type: "integer",
description: "Maximum token budget for context response. Uses 1 token ≈ 4 chars heuristic. When set, the response is truncated to fit within the budget. Default: unlimited.",
},
toolAction: {
type: "string",
description: "Brief 2-5 word summary of what this tool is doing. Capitalize like a sentence.",
},
toolSummary: {
type: "string",
description: "Brief 2-5 word noun phrase describing what this tool call is about.",
},
},
required: ["project", "toolAction", "toolSummary"],
},
};
// ─── Knowledge Search ─────────────────────────────────────────
// Phase 1 Change: Added `enable_trace` optional boolean.
// When true, the handler returns a separate content[1] block with a
// MemoryTrace object (strategy="keyword", latency, result metadata).
// Default: false — output is identical to pre-Phase 1 behavior.
export const KNOWLEDGE_SEARCH_TOOL: Tool = {
name: "knowledge_search",
description:
"Search accumulated knowledge across all sessions by keywords, category, or free text. " +
"The knowledge base grows automatically as sessions are saved — keywords are extracted " +
"from every ledger and handoff entry. Use this to find related past work, decisions, " +
"and context from previous sessions.\n\n" +
"Categories available: debugging, architecture, deployment, testing, configuration, " +
"api-integration, data-migration, security, performance, documentation, ai-ml, " +
"ui-frontend, resume",
inputSchema: {
type: "object",
properties: {
project: {
type: "string",
description: "Optional project filter. If omitted, searches across all projects.",
},
query: {
type: "string",
description: "Free-text search query. Searched against session summaries using full-text search.",
},
category: {
type: "string",
description: "Optional category filter (e.g. 'debugging', 'architecture', 'ai-ml'). " +
"Filters results to sessions in this category.",
},
limit: {
type: "integer",
description: "Maximum results to return (default: 10, max: 50).",
default: 10,
},
// Phase 1: Explainability — when true, appends a MemoryTrace JSON
// object as content[1] in the response array.
// MCP clients can parse content[1] programmatically for debugging.
enable_trace: {
type: "boolean",
description: "If true, returns a separate MEMORY TRACE content block with search strategy, " +
"latency breakdown, and scoring metadata for explainability. Default: false.",
},
activation: {
type: "object",
description: "Configuration for ACT-R inspired Spreading Activation. Use this to find structurally related memories beyond direct semantic/keyword hits.",
properties: {
enabled: { type: "boolean", description: "Enable spreading activation (default: false)." },
iterations: { type: "integer", description: "Number of propagation loops (default: 3)." },
spreadFactor: { type: "number", description: "Decay multiplier per step (default: 0.8)." },
lateralInhibition: { type: "integer", description: "Maximum nodes returned (default: 7)." },
}
},
},
required: ["query"],
},
};
// ─── Knowledge Forget ─────────────────────────────────────────
export const KNOWLEDGE_FORGET_TOOL: Tool = {
name: "knowledge_forget",
description:
"Selectively forget (delete) accumulated knowledge entries. " +
"Like a brain pruning bad memories — remove outdated, incorrect, or irrelevant " +
"session entries to keep the knowledge base clean and relevant.\n\n" +
"Forget modes:\n" +
"- **By project**: Clear all knowledge for a specific project\n" +
"- **By category**: Remove entries matching a category (e.g. 'debugging')\n" +
"- **By age**: Forget entries older than N days\n" +
"- **Full reset**: Wipe everything (requires confirm_all=true)\n\n" +
"⚠️ This permanently deletes ledger entries. Handoff state is preserved unless explicitly cleared.",
inputSchema: {
type: "object",
properties: {
project: {
type: "string",
description: "Project to forget entries for. Required unless using confirm_all.",
},
category: {
type: "string",
description: "Optional: only forget entries in this category (e.g. 'debugging', 'resume').",
},
older_than_days: {
type: "integer",
description: "Optional: only forget entries older than this many days.",
},
clear_handoff: {
type: "boolean",
description: "Also clear the handoff (live state) for this project. Default: false.",
},
confirm_all: {
type: "boolean",
description: "Set to true to confirm wiping ALL entries for the project (safety flag).",
},
dry_run: {
type: "boolean",
description: "If true, only count what would be deleted without actually deleting. Default: false.",
},
},
},
};
// ─── v0.4.0: Session Compact Ledger (Enhancement #2) ─────────
// REVIEWER NOTE: This tool triggers Gemini-powered summarization
// of old ledger entries into rollup records. See compactionHandler.ts
// for the implementation and migration 017 for the DB schema.
export const SESSION_COMPACT_LEDGER_TOOL: Tool = {
name: "session_compact_ledger",
description:
"Auto-compact old session ledger entries by rolling them up into AI-generated summaries. " +
"This prevents the ledger from growing indefinitely and keeps deep context loading fast.\n\n" +
"How it works:\n" +
"1. Finds projects with more entries than the threshold\n" +
"2. Summarizes old entries using Gemini (keeps recent entries intact)\n" +
"3. Inserts a rollup entry and archives the originals (soft-delete)\n\n" +
"Use dry_run=true to preview what would be compacted without executing.",
inputSchema: {
type: "object",
properties: {
project: {
type: "string",
description: "Optional: compact a specific project. If omitted, auto-detects all candidates.",
},
threshold: {
type: "integer",
description: "Minimum entries before compaction triggers (default: 50).",
default: 50,
},
keep_recent: {
type: "integer",
description: "Number of recent entries to keep intact (default: 10).",
default: 10,
},
dry_run: {
type: "boolean",
description: "If true, only preview what would be compacted without executing. Default: false.",
},
},
},
};
// REVIEWER NOTE: Guard intentionally placed directly after the tool definition
// it covers. All four optional fields (project, threshold, keep_recent, dry_run)
// are validated — an LLM passing {threshold: "many"} now fails the guard instead
// of reaching the handler as a string.
export function isSessionCompactLedgerArgs(
args: unknown
): args is {
project?: string;
threshold?: number;
keep_recent?: number;
dry_run?: boolean;
} {
if (typeof args !== "object" || args === null) return false;
const a = args as Record<string, unknown>;
if (a.project !== undefined && typeof a.project !== "string") return false;
if (a.threshold !== undefined && typeof a.threshold !== "number") return false;
if (a.keep_recent !== undefined && typeof a.keep_recent !== "number") return false;
if (a.dry_run !== undefined && typeof a.dry_run !== "boolean") return false;
return true;
}
// ─── v0.4.0: Session Search Memory (Enhancement #4) ──────────
// REVIEWER NOTE: This tool uses pgvector embeddings for semantic
// (meaning-based) search. Unlike knowledge_search which uses keyword
// overlap, this finds results by meaning similarity.
//
// Example where this beats keyword search:
// Query: "that weird API key error we fixed"
// Match: "Resolved authentication failure by rotating credentials"
// → Keyword search: MISS (no shared words)
// → Semantic search: HIT (meaning overlap is high)
export const SESSION_SEARCH_MEMORY_TOOL: Tool = {
name: "session_search_memory",
description:
"Search session history semantically (by meaning, not just keywords). " +
"Uses vector embeddings to find sessions with similar context, even when " +
"the exact wording differs. Requires pgvector extension in Supabase.\n\n" +
"Complements knowledge_search (keyword-based) — use this when keyword " +
"search returns no results or when the query is phrased differently " +
"from stored summaries.",
inputSchema: {
type: "object",
properties: {
query: {
type: "string",
description: "Natural language search query describing what you're looking for.",
},
project: {
type: "string",
description: "Optional: limit search to a specific project.",
},
limit: {
type: "integer",
description: "Maximum results to return (default: 5, max: 20).",
default: 5,
},
similarity_threshold: {
type: "number",
description: "Minimum similarity score 0-1 (default: 0.7). Higher = more relevant, fewer results.",
default: 0.7,
},
// Phase 1: Explainability — when true, appends a MemoryTrace JSON
// object as content[1] in the response array. For semantic search,
// the trace includes embedding_ms (Gemini API time) vs storage_ms
// (pgvector query time) to pinpoint performance bottlenecks.
enable_trace: {
type: "boolean",
description: "If true, returns a separate MEMORY TRACE content block with search strategy, " +
"latency breakdown (embedding vs storage), and scoring metadata. Default: false.",
},
// v5.2: Context-Weighted Retrieval — biases search toward active work context
context_boost: {
type: "boolean",
description: "If true, appends current project and working context to the search query " +
"before embedding generation, naturally biasing results toward contextually relevant memories. " +
"Useful when searching within a specific project context. Default: false.",
},
activation: {
type: "object",
description: "Configuration for ACT-R inspired Spreading Activation. Use this to find structurally related memories beyond direct semantic/keyword hits.",
properties: {
enabled: { type: "boolean", description: "Enable spreading activation (default: false)." },
iterations: { type: "integer", description: "Number of propagation loops (default: 3)." },
spreadFactor: { type: "number", description: "Decay multiplier per step (default: 0.8)." },
lateralInhibition: { type: "integer", description: "Maximum nodes returned (default: 7)." },
}
},
},
required: ["query"],
},
};
// ─── v1.5.0: Session Backfill Embeddings (Edge Case B Fix) ────
// REVIEWER NOTE: If the Gemini API was temporarily down when a ledger
// entry was saved, the fire-and-forget embedding catch() fires and
// the row is saved without an embedding. This tool scans for those
// orphaned rows and batch-generates the missing embeddings.
export const SESSION_BACKFILL_EMBEDDINGS_TOOL: Tool = {
name: "session_backfill_embeddings",
description:
"Repair ledger entries that are missing vector embeddings. " +
"This can happen if the Gemini API was temporarily unavailable when the entry was saved.\n\n" +
"How it works:\n" +
"1. Scans for active ledger entries where embedding IS NULL\n" +
"2. Generates embeddings via Gemini text-embedding-004\n" +
"3. Patches each row with the generated embedding\n\n" +
"Run this periodically or after known API outages to ensure full semantic search coverage.",
inputSchema: {
type: "object",
properties: {
project: {
type: "string",
description: "Optional: repair only a specific project. If omitted, repairs all projects.",
},
limit: {
type: "integer",
description: "Maximum entries to repair in one call (default: 20, max: 50). Keeps API costs predictable.",
default: 20,
},
dry_run: {
type: "boolean",
description: "If true, only count missing embeddings without generating them. Default: false.",
},
},
},
};
// ─── v6.0 Phase 3: Backfill Links Tool ───────────────────────
export const SESSION_BACKFILL_LINKS_TOOL: Tool = {
name: "session_backfill_links",
description:
"Retroactively create graph edges (memory links) for all existing entries in a project. " +
"This builds the associative memory graph from your existing session history.\n\n" +
"Three strategies are run:\n" +
"1. **Temporal Chaining**: Links consecutive entries within the same conversation\n" +
"2. **Keyword Overlap**: Links entries sharing ≥3 keywords (bidirectional)\n" +
"3. **Provenance**: Links rollup summaries to their archived originals\n\n" +
"All strategies use INSERT OR IGNORE — safe to re-run multiple times.\n\n" +
"**When to use:** Run once after upgrading to v6.0 to populate the graph for existing memories. " +
"New entries are auto-linked on save (no manual action needed).",
inputSchema: {
type: "object",
properties: {
project: {
type: "string",
description: "Project to backfill links for. Required.",
},
},
required: ["project"],
},
};
// ─── Type Guards ──────────────────────────────────────────────
export function isKnowledgeForgetArgs(
args: unknown
): args is {
project?: string;
category?: string;
older_than_days?: number;
clear_handoff?: boolean;
confirm_all?: boolean;
dry_run?: boolean;
} {
if (typeof args !== "object" || args === null) return false;
const a = args as Record<string, unknown>;
if (a.project !== undefined && typeof a.project !== "string") return false;
if (a.category !== undefined && typeof a.category !== "string") return false;
if (a.older_than_days !== undefined && typeof a.older_than_days !== "number") return false;
if (a.clear_handoff !== undefined && typeof a.clear_handoff !== "boolean") return false;
if (a.confirm_all !== undefined && typeof a.confirm_all !== "boolean") return false;
if (a.dry_run !== undefined && typeof a.dry_run !== "boolean") return false;
return true;
}
// Phase 1: Added enable_trace to the type guard.
// Optional boolean — when true, the handler returns a MemoryTrace content block.
// Default: false, so existing callers see no change in behavior.
export function isKnowledgeSearchArgs(
args: unknown
): args is {
project?: string;
query: string;
category?: string;
limit?: number;
enable_trace?: boolean; // Phase 1: Explainability flag
} {
if (typeof args !== "object" || args === null) return false;
const a = args as Record<string, unknown>;
if (typeof a.query !== "string") return false;
if (a.project !== undefined && typeof a.project !== "string") return false;
if (a.category !== undefined && typeof a.category !== "string") return false;
if (a.limit !== undefined && typeof a.limit !== "number") return false;
if (a.enable_trace !== undefined && typeof a.enable_trace !== "boolean") return false;
if (a.activation !== undefined && typeof a.activation !== "object") return false;
return true;
}
export function isSessionSaveLedgerArgs(
args: unknown
): args is {
project: string;
conversation_id: string;
summary: string;
todos?: string[];
files_changed?: string[];
decisions?: string[];
role?: string; // v3.0: Hivemind
} {
if (typeof args !== "object" || args === null) return false;
const a = args as Record<string, unknown>;
// Required fields
if (typeof a.project !== "string") return false;
if (typeof a.conversation_id !== "string") return false;
if (typeof a.summary !== "string") return false;
// Optional array fields — guard against LLM passing a string instead of string[] and check elements
if (a.todos !== undefined && (!Array.isArray(a.todos) || !a.todos.every(t => typeof t === "string"))) return false;
if (a.files_changed !== undefined && (!Array.isArray(a.files_changed) || !a.files_changed.every(t => typeof t === "string"))) return false;
if (a.decisions !== undefined && (!Array.isArray(a.decisions) || !a.decisions.every(t => typeof t === "string"))) return false;
if (a.role !== undefined && typeof a.role !== "string") return false;
return true;
}
// REVIEWER NOTE: v0.4.0 adds expected_version to the type guard
// for optimistic concurrency control. It's optional for backward compat.
// v5.4: Added disable_merge for CRDT bypass.
export function isSessionSaveHandoffArgs(
args: unknown
): args is {
project: string;
expected_version?: number;
open_todos?: string[];
active_branch?: string;
last_summary?: string;
key_context?: string;
role?: string; // v3.0: Hivemind
disable_merge?: boolean; // v5.4: CRDT bypass
} {
if (typeof args !== "object" || args === null) return false;
const a = args as Record<string, unknown>;
if (typeof a.project !== "string") return false;
if (a.expected_version !== undefined && typeof a.expected_version !== "number") return false;
if (a.open_todos !== undefined && (!Array.isArray(a.open_todos) || !a.open_todos.every(t => typeof t === "string"))) return false;
if (a.active_branch !== undefined && typeof a.active_branch !== "string") return false;
if (a.last_summary !== undefined && typeof a.last_summary !== "string") return false;
if (a.key_context !== undefined && typeof a.key_context !== "string") return false;
if (a.role !== undefined && typeof a.role !== "string") return false;
if (a.disable_merge !== undefined && typeof a.disable_merge !== "boolean") return false;
return true;
}
// ─── v0.4.0: Type guard for semantic search ──────────────────
// Phase 1: Added enable_trace to the type guard.
// Optional boolean — when true, a MemoryTrace block (with embedding_ms,
// storage_ms, top_score, etc.) is appended as content[1] in the response.
export function isSessionSearchMemoryArgs(
args: unknown
): args is {
query: string;
project?: string;
limit?: number;
similarity_threshold?: number;
enable_trace?: boolean; // Phase 1: Explainability flag
context_boost?: boolean; // v5.2: Context-Weighted Retrieval
} {
if (typeof args !== "object" || args === null) return false;
const a = args as Record<string, unknown>;
if (typeof a.query !== "string") return false;
if (a.project !== undefined && typeof a.project !== "string") return false;
if (a.limit !== undefined && typeof a.limit !== "number") return false;
if (a.similarity_threshold !== undefined && typeof a.similarity_threshold !== "number") return false;
if (a.enable_trace !== undefined && typeof a.enable_trace !== "boolean") return false;
if (a.context_boost !== undefined && typeof a.context_boost !== "boolean") return false;
if (a.activation !== undefined && typeof a.activation !== "object") return false;
return true;
}
// ─── v1.5.0: Type guard for backfill embeddings ──────────────
export function isBackfillEmbeddingsArgs(
args: unknown
): args is {
project?: string;
limit?: number;
dry_run?: boolean;
} {
if (typeof args !== "object" || args === null) return false;
const a = args as Record<string, unknown>;
if (a.project !== undefined && typeof a.project !== "string") return false;
if (a.limit !== undefined && typeof a.limit !== "number") return false;
if (a.dry_run !== undefined && typeof a.dry_run !== "boolean") return false;
return true;
}
export function isBackfillLinksArgs(
args: unknown
): args is { project: string } {
if (typeof args !== "object" || args === null) return false;
const a = args as Record<string, unknown>;
if (typeof a.project !== "string") return false;
return true;
}
export function isSessionLoadContextArgs(
args: unknown
): args is { project: string; level?: "quick" | "standard" | "deep"; role?: string; max_tokens?: number; toolAction?: string; toolSummary?: string } {
if (typeof args !== "object" || args === null) return false;
const a = args as Record<string, unknown>;
if (typeof a.project !== "string") return false;
if (a.level !== undefined && a.level !== "quick" && a.level !== "standard" && a.level !== "deep") return false;
if (a.role !== undefined && typeof a.role !== "string") return false;
if (a.max_tokens !== undefined && typeof a.max_tokens !== "number") return false;
if (a.toolAction !== undefined && typeof a.toolAction !== "string") return false;
if (a.toolSummary !== undefined && typeof a.toolSummary !== "string") return false;
return true;
}
// ─── v2.0: Time Travel Tool Definitions ──────────────────────
export const MEMORY_HISTORY_TOOL: Tool = {
name: "memory_history",
description:
"View the timeline of past memory states for this project. " +
"Use this BEFORE memory_checkout to find the correct version to revert to. " +
"Shows version numbers, timestamps, and summaries of each saved state.",
inputSchema: {
type: "object",
properties: {
project: {
type: "string",
description: "Project identifier to view history for.",
},
limit: {
type: "number",
description: "Maximum number of history entries to return (default: 10, max: 50).",
default: 10,
},
},
required: ["project"],
},
};
export const MEMORY_CHECKOUT_TOOL: Tool = {
name: "memory_checkout",
description:
"Time travel! Restores the project's memory to a specific past version. " +
"This overwrites the current handoff state with the historical snapshot, " +
"like a Git revert — the version number moves forward (no data is lost). " +
"Call memory_history first to find the correct target_version.",
inputSchema: {
type: "object",
properties: {
project: {
type: "string",
description: "Project identifier to revert.",
},
target_version: {
type: "number",
description: "The version number to restore from history (get this from memory_history).",
},
},
required: ["project", "target_version"],
},
};
// ─── v2.0: Time Travel Type Guards ───────────────────────────
export function isMemoryHistoryArgs(
args: unknown
): args is { project: string; limit?: number } {
if (typeof args !== "object" || args === null) return false;
const a = args as Record<string, unknown>;
if (typeof a.project !== "string") return false;
if (a.limit !== undefined && typeof a.limit !== "number") return false;
return true;
}
export function isMemoryCheckoutArgs(
args: unknown
): args is { project: string; target_version: number } {
if (typeof args !== "object" || args === null) return false;
const a = args as Record<string, unknown>;
if (typeof a.project !== "string") return false;
if (typeof a.target_version !== "number") return false;
return true;
}
// ─── v2.0: Visual Memory Tool Definitions ────────────────────
export const SESSION_SAVE_IMAGE_TOOL: Tool = {
name: "session_save_image",
description:
"Save a local image file into the project's permanent visual memory. " +
"Use this to remember UI states, diagrams, architecture graphs, or bug screenshots. " +
"The image is copied into Prism's media vault and indexed in the handoff metadata. " +
"On the next session_load_context, the agent will see a lightweight index of available images.",
inputSchema: {
type: "object",
properties: {
project: {
type: "string",
description: "Project identifier — must match an existing project.",
},
file_path: {
type: "string",
description: "Absolute or relative path to the image file (png, jpg, jpeg, webp, gif, svg).",
},
description: {
type: "string",
description: "What does this image show? Used for indexing and context display.",
},
},
required: ["project", "file_path", "description"],
},
};
export const SESSION_VIEW_IMAGE_TOOL: Tool = {
name: "session_view_image",
description:
"Retrieve an image from visual memory using its ID. " +
"Returns the image as Base64 inline content for the LLM to analyze. " +
"Use session_load_context first to see available image IDs.",
inputSchema: {
type: "object",
properties: {
project: {
type: "string",
description: "Project identifier.",
},
image_id: {
type: "string",
description: "The short image ID (e.g., '8f2a1b3c') from the visual memory index.",
},
},
required: ["project", "image_id"],
},
};
// ─── v2.0: Visual Memory Type Guards ─────────────────────────
export function isSessionSaveImageArgs(
args: unknown
): args is { project: string; file_path: string; description: string } {
if (typeof args !== "object" || args === null) return false;
const a = args as Record<string, unknown>;
if (typeof a.project !== "string") return false;
if (typeof a.file_path !== "string") return false;
if (typeof a.description !== "string") return false;
return true;
}
export function isSessionViewImageArgs(
args: unknown
): args is { project: string; image_id: string } {
if (typeof args !== "object" || args === null) return false;
const a = args as Record<string, unknown>;
if (typeof a.project !== "string") return false;
if (typeof a.image_id !== "string") return false;
return true;
}
// ─── v2.2.0: Health Check (fsck) Tool Definition ─────────────
/**
* MCP tool definition for the brain integrity checker.
* Inspired by Mnemory's health check + Unix fsck.
* Absorbs session_backfill_embeddings when auto_fix is true.
*/
export const SESSION_HEALTH_CHECK_TOOL: Tool = {
name: "session_health_check",
description:
"Run integrity checks on the agent's memory (like fsck for filesystems). " +
"Scans for missing embeddings, duplicate entries, orphaned handoffs, and stale rollups.\n\n" +
"Checks performed:\n" +
"1. **Missing embeddings** — entries that can't be found via semantic search\n" +
"2. **Duplicate entries** — near-identical summaries wasting context tokens\n" +
"3. **Orphaned handoffs** — handoff state with no backing ledger entries\n" +
"4. **Stale rollups** — compaction artifacts with no archived originals\n\n" +
"Use auto_fix=true to automatically repair missing embeddings and clean up orphans.",
inputSchema: {
type: "object",
properties: {
auto_fix: {
type: "boolean",
description:
"If true, automatically repair issues (backfill embeddings, remove orphaned handoffs). Default: false.",
},
},
},
};
/**
* Type guard for session_health_check arguments.
* Only optional auto_fix boolean — no required fields.
*/
export function isSessionHealthCheckArgs(
args: unknown
): args is { auto_fix?: boolean } {
if (typeof args !== "object" || args === null) return false;
const a = args as Record<string, unknown>;
if (a.auto_fix !== undefined && typeof a.auto_fix !== "boolean") return false;
return true;
}
// ─── Phase 2: GDPR-Compliant Memory Deletion Tool ────────────
//
// This tool enables SURGICAL deletion of individual memory entries by ID.
// It supports two modes:
// 1. Soft Delete (default): Sets deleted_at = NOW(). The entry remains
// in the database for audit trails but is excluded from ALL search
// queries (both FTS5 and vector). This prevents the Top-K Hole
// problem where LIMIT N queries return fewer results than expected.
// 2. Hard Delete: Physical removal from the database. Irreversible.
// Use only when GDPR Article 17 requires complete erasure.
//
// DESIGN DECISION: This is intentionally separate from knowledge_forget,
// which operates on bulk filter criteria (project, category, age).
// session_forget_memory is surgical — one entry at a time — for
// precise GDPR compliance.
export const SESSION_FORGET_MEMORY_TOOL: Tool = {
name: "session_forget_memory",
description:
"Forget (delete) a specific memory entry by its ID. " +
"Supports two modes:\n\n" +
"- **Soft delete** (default): Tombstones the entry — it stays in the database " +
"for audit trails but is excluded from all search results. Reversible.\n" +
"- **Hard delete**: Permanently removes the entry from the database. Irreversible. " +
"Use only when GDPR Article 17 requires complete erasure.\n\n" +
"⚠️ Soft delete is recommended for most use cases. The entry can be " +
"restored in the future if needed.",
inputSchema: {
type: "object",
properties: {
memory_id: {
type: "string",
description:
"The UUID of the memory (ledger) entry to forget. " +
"You can find this ID in search results returned by " +
"session_search_memory or knowledge_search.",
},
hard_delete: {
type: "boolean",
description:
"If true, permanently removes the entry (irreversible). " +
"If false (default), soft-deletes by setting deleted_at timestamp. " +
"Soft-deleted entries are excluded from searches but remain in the database.",
},
reason: {
type: "string",
description:
"Optional GDPR Article 17 justification for the deletion. " +
"Examples: 'User requested', 'Data retention policy', 'Outdated information'. " +
"Stored alongside the tombstone for audit trail purposes.",
},
},
required: ["memory_id"],
},
};
/**
* Type guard for session_forget_memory arguments.
* Validates that memory_id (required) is present and is a string.
* hard_delete and reason are optional.
*/
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
export function isSessionForgetMemoryArgs(
args: unknown
): args is { memory_id: string; hard_delete?: boolean; reason?: string } {
if (typeof args !== "object" || args === null) return false;
const a = args as Record<string, unknown>;
if (typeof a.memory_id !== "string" || !UUID_RE.test(a.memory_id)) return false;
if (a.hard_delete !== undefined && typeof a.hard_delete !== "boolean") return false;
if (a.reason !== undefined && typeof a.reason !== "string") return false;
return true;
}
// ─── Phase 2: GDPR Export Tool ─────────────────────────────────────────
//
// Complements session_forget_memory (surgical deletion) with a full data
// portability export. Fulfills GDPR Article 20 (Right to Data Portability).
// API keys are always redacted from the exported settings object.
export const SESSION_EXPORT_MEMORY_TOOL: Tool = {
name: "session_export_memory",
description:
"Export all of a project's memory to a local file. " +
"Fulfills GDPR Article 20 (Right to Data Portability) and the " +
"'local-first' portability promise.\n\n" +
"**What is exported:**\n" +
"- All session ledger entries (summaries, decisions, TODOs, file changes)\n" +
"- Current handoff state (live project context)\n" +
"- System settings (API keys are \"**REDACTED**\" for security)\n" +
"- Visual memory index (descriptions, captions, timestamps; not the raw files)\n\n" +
"**Formats:**\n" +
"- `json` — machine-readable, suitable for import into another Prism instance\n" +
"- `markdown` — human-readable, ideal for static archiving\n" +
"- `vault` — Prism-Port: exports a compressed `.zip` of interrelated Markdown files with proper Obsidian/Logseq YAML frontmatter and `[[Wikilinks]]`\n\n" +
"⚠️ Output directory must exist and be writable. " +
"Filenames are auto-generated: `prism-export-<project>-<date>.(json|md|zip)`",
inputSchema: {
type: "object",
properties: {
project: {
type: "string",
description:
"Project to export. If omitted, exports ALL projects into separate files.",
},
format: {
type: "string",
enum: ["json", "markdown", "vault", "obsidian", "logseq"],
description:
"Export format: 'json' (single file), 'markdown' (single human doc), " +
"'vault' / 'obsidian' / 'logseq' (zip with wikilinked .md files + " +
"YAML frontmatter — drop into your PKM vault). Default: json.",
default: "json",
},
output_dir: {
type: "string",
description:
"Absolute path to the directory where the export file(s) will be written. " +
"Must exist and be writable. Example: '/Users/admin/Desktop'.",
},
},
required: ["output_dir"],
},
};
/**
* Type guard for session_export_memory arguments.
* output_dir is required (must be an absolute path).
* project and format are optional.
*/
/** Formats accepted by session_export_memory. obsidian + logseq are
* aliases for vault — the wikilinked-zip output is already compatible
* with both PKMs verbatim. */
export type ExportFormat = "json" | "markdown" | "vault" | "obsidian" | "logseq";
export function isSessionExportMemoryArgs(
args: unknown
): args is { project?: string; format?: ExportFormat; output_dir: string } {
if (typeof args !== "object" || args === null) return false;
const a = args as Record<string, unknown>;
// Required
if (typeof a.output_dir !== "string") return false;
// Optional — validate types and enum membership
if (a.project !== undefined && typeof a.project !== "string") return false;
if (
a.format !== undefined &&
a.format !== "json" &&
a.format !== "markdown" &&
a.format !== "vault" &&
a.format !== "obsidian" &&
a.format !== "logseq"
) return false;
return true;
}
/** obsidian + logseq are user-facing aliases for vault. */
export function normalizeExportFormat(f: ExportFormat): "json" | "markdown" | "vault" {
if (f === "obsidian" || f === "logseq") return "vault";
return f;
}
// ─── v3.1: Knowledge Set Retention (TTL) ─────────────────────
export const KNOWLEDGE_SET_RETENTION_TOOL: Tool = {
name: "knowledge_set_retention",
description:
"Set an automatic data retention policy (TTL) for a project's memory. " +
"Entries older than ttl_days will be soft-deleted (archived) automatically " +
"on every server startup and every 12 hours while running.\n\n" +
"**Use cases:**\n" +
"- Set `ttl_days: 90` to auto-expire sessions older than 3 months\n" +
"- Set `ttl_days: 0` to disable auto-expiry (default)\n\n" +
"**Note:** Rollup/compaction entries are never expired — only raw sessions.",
inputSchema: {
type: "object",
properties: {
project: {
type: "string",
description: "Project to set retention policy for.",
},
ttl_days: {
type: "integer",
description:
"Entries older than this many days are auto-expired. " +
"Set to 0 to disable. Minimum: 7 days when enabled.",
minimum: 0,
},
},
required: ["project", "ttl_days"],