-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmemory.rs
More file actions
3078 lines (2884 loc) · 109 KB
/
Copy pathmemory.rs
File metadata and controls
3078 lines (2884 loc) · 109 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
// persistent memory system. Stores named memories as markdown files with
// YAML-like frontmatter under ~/.config/catalyst-code/memory/<project-hash>/.
// Memories are scoped per workspace (hashed canonical path) and injected into
// the standing system prompt so learnings persist across sessions.
// ponytail: no DB, no extra crate — just markdown files on disk.
//
// Wired end-to-end: the `memory` AI tool (tools.rs) exposes save/append/list/
// forget to the model; the TUI slash commands (/remember /memory /forget) map
// to the SaveMemory/ListMemory/ForgetMemory core commands; memory_injection is
// spliced into the system prompt (main.rs). append_memory also runs at
// compaction to preserve durable facts. `project_hash` is a standalone helper
// kept for potential external use, hence the module-level dead-code allow.
#![allow(dead_code)]
use std::path::{Path, PathBuf};
use std::sync::Mutex as StdMutex;
use std::time::Instant;
/// Serializes all memory write operations (save/append/forget) across the
/// orchestrator and any in-process subagents. `append_memory` is a
/// read-modify-write, so two parallel subagents appending to the same memory
/// name would otherwise race and silently drop facts. Writes are rare and fast,
/// so a single global lock is the ponytail fix (no per-file lock map) and is
/// correct for one core process — the only writer to a memory dir.
static WRITE_LOCK: StdMutex<()> = StdMutex::new(());
/// Optional override for the memory store root (tests only). Avoids mutating
/// process-global `HOME`, which races with parallel tests that also touch
/// the memory store.
static ROOT_OVERRIDE: StdMutex<Option<PathBuf>> = StdMutex::new(None);
/// Process-local scan + relevant-tail cache. `scan_all_memories` reads every
/// `.md` on each call; without this, every model round (including post-tool
/// re-streams) re-reads the whole store. Invalidated on any write.
struct MemoryScanCache {
/// Workspace project hash this cache belongs to (empty = unset).
ws_hash: String,
entries: Vec<MemoryEntry>,
/// `(prompt, rendered tail)` for the current user turn.
relevant: Option<(String, String)>,
/// Wall time of last successful scan (tests / debugging).
scanned_at: Option<Instant>,
}
impl MemoryScanCache {
const fn empty() -> Self {
Self {
ws_hash: String::new(),
entries: Vec::new(),
relevant: None,
scanned_at: None,
}
}
}
static SCAN_CACHE: StdMutex<MemoryScanCache> = StdMutex::new(MemoryScanCache::empty());
/// Drop cached scans / relevant tails. Called after every successful memory
/// mutation so the next request re-reads from disk.
pub fn invalidate_scan_cache() {
if let Ok(mut c) = SCAN_CACHE.lock() {
*c = MemoryScanCache::empty();
}
}
/// Serializes tests that touch the default memory store or install a root
/// override — without this, parallel `tools` memory tests race with hygiene
/// tests that temporarily redirect the store root.
#[cfg(test)]
pub fn memory_test_serial() -> &'static StdMutex<()> {
use std::sync::OnceLock;
static LOCK: OnceLock<StdMutex<()>> = OnceLock::new();
LOCK.get_or_init(|| StdMutex::new(()))
}
/// RAII guard that installs a temporary memory root and restores the previous
/// override on drop. Tests that need an isolated store should hold this guard
/// for the duration of the test body.
pub struct MemoryRootGuard {
prev: Option<PathBuf>,
}
impl Drop for MemoryRootGuard {
fn drop(&mut self) {
let mut g = ROOT_OVERRIDE.lock().unwrap_or_else(|e| e.into_inner());
*g = self.prev.take();
}
}
/// Install `root` as the memory store root until the returned guard is dropped.
#[cfg(test)]
pub fn override_memory_root(root: PathBuf) -> MemoryRootGuard {
let mut g = ROOT_OVERRIDE.lock().unwrap_or_else(|e| e.into_inner());
let prev = g.replace(root);
MemoryRootGuard { prev }
}
fn memory_store_root() -> PathBuf {
if let Ok(g) = ROOT_OVERRIDE.lock() {
if let Some(ref p) = *g {
return p.clone();
}
}
let home = crate::config::home_dir().unwrap_or_else(|| PathBuf::from("."));
home.join(".config/catalyst-code/memory")
}
/// Memory scope: workspace-local (per-codebase) or global (cross-codebase).
/// Global memories carry user-level facts — the user's name, preferred tech
/// stacks, harness conventions — that apply regardless of which project is
/// open. They are stored in a fixed `global/` directory and merged into every
/// workspace's system-prompt injection.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Scope {
Workspace,
Global,
}
impl Scope {
pub fn as_str(&self) -> &'static str {
match self {
Scope::Workspace => "workspace",
Scope::Global => "global",
}
}
/// Parse a scope string; unrecognized values default to Workspace.
pub fn parse(s: &str) -> Scope {
match s.trim().to_lowercase().as_str() {
"global" | "user" => Scope::Global,
// Spec §4 uses "project"; keep "workspace" as the historical alias.
"project" | "workspace" | "local" => Scope::Workspace,
_ => Scope::Workspace,
}
}
}
/// Relative durability hint for catalog preference + write policy.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum Importance {
High,
#[default]
Normal,
Low,
}
impl Importance {
pub fn as_str(self) -> &'static str {
match self {
Importance::High => "high",
Importance::Normal => "normal",
Importance::Low => "low",
}
}
pub fn parse(s: &str) -> Importance {
match s.trim().to_lowercase().as_str() {
"high" | "critical" | "durable" => Importance::High,
"low" | "ephemeral" | "temp" => Importance::Low,
_ => Importance::Normal,
}
}
}
/// Memory verification / lifecycle status (schema v2). Legacy files without
/// `status:` are treated as [`MemoryStatus::Verified`] so they keep ranking.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum MemoryStatus {
Candidate,
#[default]
Verified,
NeedsVerification,
Stale,
Deprecated,
Rejected,
}
impl MemoryStatus {
pub fn as_str(self) -> &'static str {
match self {
Self::Candidate => "candidate",
Self::Verified => "verified",
Self::NeedsVerification => "needs_verification",
Self::Stale => "stale",
Self::Deprecated => "deprecated",
Self::Rejected => "rejected",
}
}
pub fn parse(s: &str) -> MemoryStatus {
match s.trim().to_lowercase().as_str() {
"candidate" => Self::Candidate,
"needs_verification" | "needs-verification" => Self::NeedsVerification,
"stale" => Self::Stale,
"deprecated" => Self::Deprecated,
"rejected" => Self::Rejected,
_ => Self::Verified,
}
}
/// Candidate/stale rank below verified; deprecated/rejected are not positive guidance.
pub fn is_positive_guidance(self) -> bool {
!matches!(self, Self::Deprecated | Self::Rejected)
}
/// Retrieval rank boost relative to verified (1.0).
pub fn rank_multiplier(self) -> f32 {
match self {
Self::Verified => 1.0,
Self::NeedsVerification => 0.7,
Self::Candidate => 0.55,
Self::Stale => 0.4,
Self::Deprecated | Self::Rejected => 0.0,
}
}
}
#[derive(Clone, Debug)]
pub struct MemoryEntry {
pub name: String,
pub description: String,
pub mem_type: String,
pub content: String,
pub path: PathBuf,
pub scope: Scope,
/// When true (frontmatter `pin: true`), this memory is preferred in the
/// standing catalog over unpinned notes when the entry budget is tight.
pub pinned: bool,
/// Frontmatter `importance:` (high|normal|low). High ranks with pins in
/// the catalog; low is discouraged by the write policy unless forced.
pub importance: Importance,
/// When true, this memory is superseded/invalidated and excluded from the
/// standing catalog + per-turn relevant tail (the successor carries the
/// knowledge). Set via `memory save ... replaces=` / `memory deprecate`;
/// still visible via `list`/`get`/`forget` so it can be audited.
pub deprecated: bool,
/// Name/id of the memory that supersedes this one (frontmatter
/// `superseded_by`), set when a new memory `replaces` this one.
pub superseded_by: Option<String>,
/// Optional schema version (frontmatter `schema_version`). Absent on
/// legacy files; treated as 1. Schema 2 adds status/confidence/evidence.
pub schema_version: u32,
/// Originating session/run when known. Legacy and manually authored
/// memories leave these empty; diagnostics must treat them as provenance,
/// never as authority.
pub source_session: Option<String>,
pub source_run: Option<String>,
/// Unix creation timestamp when recorded by the producer.
pub created_at: Option<u64>,
/// Learning status (frontmatter `status:`). Defaults to `verified` for
/// legacy files so existing memories keep ranking.
pub status: MemoryStatus,
/// Confidence in `0.0..=1.0` (frontmatter `confidence:`).
pub confidence: f32,
/// Supporting evidence count (frontmatter `support_count:`).
pub support_count: u32,
/// Contradiction count (frontmatter `contradiction_count:`).
pub contradiction_count: u32,
/// Unix seconds when last verified against code (optional).
pub last_verified_at: Option<u64>,
/// Commit short-SHA when last verified (optional).
pub last_verified_commit: Option<String>,
/// Referenced relative file paths (frontmatter list under `references.files`).
pub ref_files: Vec<String>,
/// Referenced symbol names.
pub ref_symbols: Vec<String>,
/// Linked episode ids (evidence).
pub evidence_episodes: Vec<String>,
}
/// Standing-prompt catalog caps. Bodies are NOT injected — only name/type/scope
/// + one-line description — so a large store stays cheap in the prefix cache.
/// Full text is loaded on demand via `memory` action=get (or list).
pub const CATALOG_MAX_ENTRIES: usize = 48;
/// ~2.5k tokens at the chars/4 heuristic used elsewhere in the harness.
pub const CATALOG_MAX_CHARS: usize = 10_000;
const CATALOG_DESC_MAX_CHARS: usize = 100;
/// Maximum pinned entries shown in the standing catalog, so a large set of
/// pinned convention/decision memories can't crowd out operational
/// architecture/note/gotcha knowledge. Pinned entries beyond this budget are
/// omitted (still visible via `list`/`get`).
pub const CATALOG_PIN_BUDGET: usize = 16;
/// Per-turn relevant-memory tail (transient, not prefix-cached).
pub const RELEVANT_MAX_ENTRIES: usize = 8;
const RELEVANT_PREVIEW_LINES: usize = 5;
/// Soft warning threshold for the `memory` tool after save/append.
pub const SAVE_COUNT_WARN_THRESHOLD: usize = 60;
// ---- hash ----
/// Hash the workspace path for scoped storage. Deterministic, using FNV-1a
/// on the canonicalized absolute path of `cwd`. Returns 16 hex chars.
pub fn project_hash(cwd: &str) -> String {
let p = PathBuf::from(cwd);
let canonical = std::fs::canonicalize(&p).unwrap_or(p);
let h = fnv1a(canonical.to_string_lossy().as_bytes());
format!("{:016x}", h)
}
fn hash_workspace(workspace: &Path) -> String {
// Prefer project_identity's stable workspace_hash so learning + memory share
// keys across path moves (CORE_REVIEW dual-identity fix). Fall back to raw
// path hash when identity resolution is unavailable.
let identity = crate::project_identity::resolve_project_identity(workspace);
if !identity.workspace_hash.is_empty() {
return identity.workspace_hash;
}
let canonical = std::fs::canonicalize(workspace).unwrap_or_else(|_| workspace.to_path_buf());
let h = fnv1a(canonical.to_string_lossy().as_bytes());
format!("{:016x}", h)
}
/// All memory directory hashes that may hold entries for this workspace
/// (current hash + registry legacy hashes).
fn memory_dir_candidates(workspace: &Path) -> Vec<String> {
let mut out = vec![hash_workspace(workspace)];
// Also try raw path hash in case legacy data pre-dates identity.
let canonical = std::fs::canonicalize(workspace).unwrap_or_else(|_| workspace.to_path_buf());
let raw = format!("{:016x}", fnv1a(canonical.to_string_lossy().as_bytes()));
if !out.iter().any(|h| h == &raw) {
out.push(raw);
}
out
}
fn fnv1a(s: &[u8]) -> u64 {
let mut h: u64 = 0xcbf29ce484222325;
for &b in s {
h ^= b as u64;
h = h.wrapping_mul(0x100000001b3);
}
h
}
// ---- store (scoped to a root) ----
struct Store {
root: PathBuf,
}
impl Store {
fn default_root() -> PathBuf {
memory_store_root()
}
fn new(root: PathBuf) -> Self {
Self { root }
}
fn dir(&self, workspace: &Path) -> PathBuf {
self.root.join(hash_workspace(workspace))
}
/// Fixed directory for global (cross-workspace) memories.
fn global_dir(&self) -> PathBuf {
self.root.join("global")
}
/// Resolve the memory directory for a given scope.
fn dir_scoped(&self, workspace: &Path, scope: Scope) -> PathBuf {
match scope {
Scope::Global => self.global_dir(),
Scope::Workspace => self.dir(workspace),
}
}
fn scan(&self, workspace: &Path) -> Vec<MemoryEntry> {
self.scan_scoped(workspace, Scope::Workspace)
}
fn scan_scoped(&self, workspace: &Path, scope: Scope) -> Vec<MemoryEntry> {
match scope {
Scope::Global => scan_dir(&self.global_dir(), Scope::Global),
Scope::Workspace => {
// Merge current + legacy hash dirs so path moves keep memories
// (CORE_REVIEW dual project identity).
let mut out = Vec::new();
let mut seen = std::collections::HashSet::new();
for h in memory_dir_candidates(workspace) {
for e in scan_dir(&self.root.join(&h), Scope::Workspace) {
if seen.insert(e.name.clone()) {
out.push(e);
}
}
}
out
}
}
}
fn save(
&self,
workspace: &Path,
name: &str,
content: &str,
mem_type: &str,
description: &str,
) -> Result<PathBuf, String> {
self.save_scoped(
workspace,
Scope::Workspace,
name,
content,
mem_type,
description,
)
}
fn save_scoped(
&self,
workspace: &Path,
scope: Scope,
name: &str,
content: &str,
mem_type: &str,
description: &str,
) -> Result<PathBuf, String> {
self.save_scoped_with_importance(
workspace,
scope,
name,
content,
mem_type,
description,
Importance::Normal,
)
}
fn save_scoped_with_importance(
&self,
workspace: &Path,
scope: Scope,
name: &str,
content: &str,
mem_type: &str,
description: &str,
importance: Importance,
) -> Result<PathBuf, String> {
self.save_scoped_with_importance_pin(
workspace,
scope,
name,
content,
mem_type,
description,
importance,
false,
)
}
fn save_scoped_with_importance_pin(
&self,
workspace: &Path,
scope: Scope,
name: &str,
content: &str,
mem_type: &str,
description: &str,
importance: Importance,
pin: bool,
) -> Result<PathBuf, String> {
let dir = self.dir_scoped(workspace, scope);
std::fs::create_dir_all(&dir).map_err(|e| format!("failed to create memory dir: {e}"))?;
let slug = slugify(name);
if slug.is_empty() {
return Err("memory name must contain at least one alphanumeric character".to_string());
}
let filename = format!("{}.md", slug);
let path = dir.join(&filename);
let pin_line = if pin || is_pinned_type(mem_type) || importance == Importance::High {
"pin: true\n"
} else {
""
};
let importance_line = if importance != Importance::Normal {
format!("importance: {}\n", importance.as_str())
} else {
String::new()
};
let body = format!(
"---\nname: {}\ndescription: {}\ntype: {}\n{pin_line}{importance_line}---\n{}",
name, description, mem_type, content
);
// Atomic + fsync'd write (temp + fsync + rename) so a crash mid-write
// can't leave a truncated/empty memory file — memories are durable
// learnings, so they get the same crash-safety as session persistence.
atomic_write(&path, &body)
.map_err(|e| format!("failed to write memory file {filename:?}: {e}"))?;
rebuild_index(&dir, scope)?;
Ok(path)
}
}
// ---- public API ----
/// Scan all memory files for a workspace, returning parsed entries.
/// Skips the index file (MEMORY.md) and any unparseable files.
pub fn scan_memories(workspace: &Path) -> Vec<MemoryEntry> {
scan_memories_scoped(workspace, Scope::Workspace)
}
/// Like `scan_memories` but for a specific scope.
pub fn scan_memories_scoped(workspace: &Path, scope: Scope) -> Vec<MemoryEntry> {
Store::new(Store::default_root()).scan_scoped(workspace, scope)
}
/// Scan memories from BOTH scopes: global first (user-level, cross-codebase
/// facts), then workspace (project-specific). Each entry's `scope` field
/// identifies its origin. Used by `memory_injection` so the system prompt
/// carries forward both universal and project-specific learnings.
///
/// Results are process-cached per workspace hash and invalidated on write.
pub fn scan_all_memories(workspace: &Path) -> Vec<MemoryEntry> {
let hash = hash_workspace(workspace);
{
let cache = SCAN_CACHE.lock().unwrap_or_else(|e| e.into_inner());
if cache.ws_hash == hash && cache.scanned_at.is_some() {
return cache.entries.clone();
}
}
let store = Store::new(Store::default_root());
let mut entries = store.scan_scoped(workspace, Scope::Global);
entries.extend(store.scan_scoped(workspace, Scope::Workspace));
{
let mut cache = SCAN_CACHE.lock().unwrap_or_else(|e| e.into_inner());
cache.ws_hash = hash;
cache.entries = entries.clone();
cache.relevant = None;
cache.scanned_at = Some(Instant::now());
}
entries
}
/// Write a memory file (with frontmatter) and rebuild the MEMORY.md index.
/// The filename is derived from `name` (slugified). Existing files are
/// overwritten silently.
pub fn save_memory(
workspace: &Path,
name: &str,
content: &str,
mem_type: &str,
description: &str,
) -> Result<PathBuf, String> {
save_memory_scoped(
workspace,
Scope::Workspace,
name,
content,
mem_type,
description,
)
}
/// Like `save_memory` but for a specific scope. Use `Scope::Global` to store a
/// cross-codebase memory (user identity, tech-stack preferences, harness facts)
/// that is injected into every workspace's system prompt.
pub fn save_memory_scoped(
workspace: &Path,
scope: Scope,
name: &str,
content: &str,
mem_type: &str,
description: &str,
) -> Result<PathBuf, String> {
save_memory_scoped_with_importance(
workspace,
scope,
name,
content,
mem_type,
description,
Importance::Normal,
)
}
/// Like `save_memory_scoped` but records an importance hint in frontmatter.
pub fn save_memory_scoped_with_importance(
workspace: &Path,
scope: Scope,
name: &str,
content: &str,
mem_type: &str,
description: &str,
importance: Importance,
) -> Result<PathBuf, String> {
save_memory_scoped_with_importance_pin(
workspace,
scope,
name,
content,
mem_type,
description,
importance,
false,
)
}
/// Like [`save_memory_scoped_with_importance`] but honors an explicit `pin`.
pub fn save_memory_scoped_with_importance_pin(
workspace: &Path,
scope: Scope,
name: &str,
content: &str,
mem_type: &str,
description: &str,
importance: Importance,
pin: bool,
) -> Result<PathBuf, String> {
let _guard = WRITE_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let path = Store::new(Store::default_root()).save_scoped_with_importance_pin(
workspace,
scope,
name,
content,
mem_type,
description,
importance,
pin,
)?;
// Drop after write succeeds so the next scan/relevance call re-reads disk.
drop(_guard);
invalidate_scan_cache();
// Best-effort embedding index so synonym-miss recovery can prefer
// embeddings when enabled (CORE_REVIEW: index_memory was never called).
let index_text = format!(
"{name}
{description}
{content}"
);
crate::embed::index_memory(workspace, name, &index_text);
Ok(path)
}
/// Mutate an existing memory using the latest on-disk entry while holding both
/// the in-process writer lock and the store's cross-process directory lock.
/// Callers that rewrite lifecycle/evidence metadata must use this instead of a
/// previously scanned snapshot, which can silently undo a concurrent append.
pub(crate) fn update_memory_scoped(
workspace: &Path,
scope: Scope,
id: &str,
update: impl FnOnce(&mut MemoryEntry),
) -> Result<PathBuf, String> {
let _guard = WRITE_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let store = Store::new(Store::default_root());
let dir = store.dir_scoped(workspace, scope);
let slug = slugify(id);
if slug.is_empty() {
return Err("memory id/name must contain at least one alphanumeric character".into());
}
let path = dir.join(format!("{slug}.md"));
let _lock = crate::fsutil::FileLock::acquire(&dir.join(".lock"))
.map_err(|e| format!("failed to acquire memory lock: {e}"))?;
let mut entry = parse_memory_file(&path)
.ok_or_else(|| format!("memory '{id}' is missing or unreadable"))?;
entry.scope = scope;
update(&mut entry);
write_memory_file(&path, &entry, &entry.content, &entry.description)
.map_err(|e| format!("failed to update memory: {e}"))?;
rebuild_index(&dir, scope)?;
drop(_lock);
drop(_guard);
invalidate_scan_cache();
Ok(path)
}
/// Replace content and merge all schema-v2 metadata from an absorbed memory.
/// Scalar provenance is retained from the survivor (or filled when absent),
/// while references/evidence and counters are accumulated without duplicates.
pub(crate) fn merge_memory_scoped(
workspace: &Path,
scope: Scope,
survivor: &str,
absorbed: &MemoryEntry,
content: String,
description: String,
mem_type: String,
) -> Result<PathBuf, String> {
update_memory_scoped(workspace, scope, survivor, |entry| {
entry.content = content;
entry.description = description;
entry.mem_type = mem_type;
entry.schema_version = entry.schema_version.max(absorbed.schema_version);
entry.source_session = entry
.source_session
.clone()
.or_else(|| absorbed.source_session.clone());
entry.source_run = entry
.source_run
.clone()
.or_else(|| absorbed.source_run.clone());
entry.created_at = match (entry.created_at, absorbed.created_at) {
(Some(a), Some(b)) => Some(a.min(b)),
(a, b) => a.or(b),
};
entry.confidence = entry.confidence.max(absorbed.confidence);
entry.support_count = entry.support_count.saturating_add(absorbed.support_count);
entry.contradiction_count = entry
.contradiction_count
.saturating_add(absorbed.contradiction_count);
entry.last_verified_at = match (entry.last_verified_at, absorbed.last_verified_at) {
(Some(a), Some(b)) => Some(a.max(b)),
(a, b) => a.or(b),
};
if entry.last_verified_commit.is_none() {
entry.last_verified_commit = absorbed.last_verified_commit.clone();
}
extend_unique(&mut entry.ref_files, &absorbed.ref_files);
extend_unique(&mut entry.ref_symbols, &absorbed.ref_symbols);
extend_unique(&mut entry.evidence_episodes, &absorbed.evidence_episodes);
})
}
pub(crate) fn extend_unique(target: &mut Vec<String>, additions: &[String]) {
for value in additions {
if !value.trim().is_empty() && !target.iter().any(|v| v == value) {
target.push(value.clone());
}
}
}
/// Append `new_facts` to an existing memory (same name/slug), capped to
/// `max_bytes` by trimming the oldest facts from the front (on a line boundary).
/// Unlike `save_memory` (which overwrites), this accumulates durable facts across
/// compactions so early-session facts aren't lost when later compactions fire —
/// the rolling cap keeps the file bounded instead of growing forever.
pub fn append_memory(
workspace: &Path,
name: &str,
new_facts: &str,
mem_type: &str,
description: &str,
max_bytes: usize,
) -> Result<PathBuf, String> {
append_memory_scoped(
workspace,
Scope::Workspace,
name,
new_facts,
mem_type,
description,
max_bytes,
)
}
/// Like `append_memory` but for a specific scope. Use `Scope::Global` to
/// accumulate cross-codebase facts.
pub fn append_memory_scoped(
workspace: &Path,
scope: Scope,
name: &str,
new_facts: &str,
mem_type: &str,
description: &str,
max_bytes: usize,
) -> Result<PathBuf, String> {
append_memory_locked(
&Store::new(Store::default_root()),
workspace,
scope,
name,
new_facts,
mem_type,
description,
max_bytes,
)
}
/// Like `append_memory` but against a provided store, and the testable seam for
/// the write lock: acquires `WRITE_LOCK` across the whole read-modify-write so
/// concurrent appends to the same memory name (e.g. from parallel subagents)
/// can't interleave and drop facts.
fn append_memory_locked(
store: &Store,
workspace: &Path,
scope: Scope,
name: &str,
new_facts: &str,
mem_type: &str,
description: &str,
max_bytes: usize,
) -> Result<PathBuf, String> {
let _guard = WRITE_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let path = append_memory_into(
store,
workspace,
scope,
name,
new_facts,
mem_type,
description,
max_bytes,
)?;
drop(_guard);
invalidate_scan_cache();
Ok(path)
}
fn append_memory_into(
store: &Store,
workspace: &Path,
scope: Scope,
name: &str,
new_facts: &str,
mem_type: &str,
description: &str,
max_bytes: usize,
) -> Result<PathBuf, String> {
let dir = store.dir_scoped(workspace, scope);
let slug = slugify(name);
let path = dir.join(format!("{slug}.md"));
// Cross-process lock: append is a read-modify-write (read existing content,
// merge new facts, write back). The in-process WRITE_LOCK serializes
// threads/subagents but NOT separate processes — two processes appending
// to the same memory name concurrently would both read the same base and
// the second rename would silently drop the first's facts. This advisory
// flock (auto-released on exit/crash) closes that gap.
let _lock = crate::fsutil::FileLock::acquire(&dir.join(".lock"))
.map_err(|e| format!("failed to acquire memory lock: {e}"))?;
let existing = parse_memory_file(&path);
let mut combined = match &existing {
Some(m) if !m.content.is_empty() => {
let mut s = m.content.clone();
if !s.ends_with('\n') {
s.push('\n');
}
s.push_str("\n--- appended ---\n");
s.push_str(new_facts);
s
}
_ => new_facts.to_string(),
};
if combined.len() > max_bytes {
// Keep the newest facts (the tail, since we append) and trim the oldest
// from the front. We keep the last `max_bytes` verbatim; a mid-line start
// is acceptable for a rolling fact buffer (a giant single-line fact must
// not be dropped entirely just because it has no newline to snap to).
let mut start = combined.len() - max_bytes;
while !combined.is_char_boundary(start) {
start += 1;
}
combined = format!(
"[older auto-extracted facts trimmed to fit]\n{}",
&combined[start..]
);
}
// Preserve every parsed field when appending to an existing memory. The
// generic save builder creates fresh metadata and would resurrect deprecated
// entries while dropping provenance, references, and evidence.
if let Some(mut entry) = existing {
entry.content = combined.clone();
write_memory_file(&path, &entry, &combined, &entry.description)
.map_err(|e| format!("failed to append memory: {e}"))?;
rebuild_index(&dir, scope)?;
return Ok(path);
}
store.save_scoped_with_importance(
workspace,
scope,
name,
&combined,
mem_type,
description,
Importance::Normal,
)
}
/// Delete a memory by its slug/id (the filename stem) and rebuild the index.
/// Accepts either the slug (file stem) or the original memory `name` — slugify()
/// normalizes both to the same filename, so only the slug candidate is needed.
/// slugify() strips '/', '\', and '.' to '-', so the joined path can never
/// escape the memory dir (no path-traversal deletion via a crafted id).
pub fn forget_memory(workspace: &Path, id: &str) -> Result<(), String> {
forget_memory_scoped(workspace, Scope::Workspace, id)
}
/// Like `forget_memory` but for a specific scope.
pub fn forget_memory_scoped(workspace: &Path, scope: Scope, id: &str) -> Result<(), String> {
if id.trim().is_empty() {
return Err("memory id must not be empty".to_string());
}
let _guard = WRITE_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let store = Store::new(Store::default_root());
let dir = store.dir_scoped(workspace, scope);
let slug = slugify(id);
let path = dir.join(format!("{}.md", slug));
if path.exists() {
std::fs::remove_file(&path).map_err(|e| format!("failed to remove memory: {e}"))?;
rebuild_index(&dir, scope)?;
drop(_guard);
invalidate_scan_cache();
Ok(())
} else {
Err(format!("no memory found with id/name '{id}'"))
}
}
/// Forget a memory by searching both scopes (workspace first, then global).
/// Used when the caller doesn't know which scope a memory lives in. Each
/// scoped forget acquires WRITE_LOCK internally, so this is safe to call
/// without an outer lock.
pub fn forget_memory_any(workspace: &Path, id: &str) -> Result<(), String> {
if id.trim().is_empty() {
return Err("memory id must not be empty".to_string());
}
forget_memory_scoped(workspace, Scope::Workspace, id)
.or_else(|_| forget_memory_scoped(workspace, Scope::Global, id))
}
/// Look up a memory by id (slug) or name in both scopes (workspace first).
pub fn get_memory(workspace: &Path, id: &str) -> Result<MemoryEntry, String> {
get_memory_scoped(workspace, Scope::Workspace, id)
.or_else(|_| get_memory_scoped(workspace, Scope::Global, id))
}
/// Look up a memory by id/name in a specific scope.
pub fn get_memory_scoped(workspace: &Path, scope: Scope, id: &str) -> Result<MemoryEntry, String> {
let store = Store::new(Store::default_root());
let dir = store.dir_scoped(workspace, scope);
let slug = slugify(id);
if slug.is_empty() {
return Err("memory id/name must contain at least one alphanumeric character".into());
}
let path = dir.join(format!("{slug}.md"));
if !path.exists() {
// Fall back to scanning by display name (slug may differ from id input).
if let Some(entry) = store
.scan_scoped(workspace, scope)
.into_iter()
.find(|e| e.name.eq_ignore_ascii_case(id.trim()) || slugify(&e.name) == slug)
{
return Ok(entry);
}
return Err(format!(
"no {} memory found with id/name '{id}'",
scope.as_str()
));
}
match parse_memory_file(&path) {
Some(mut entry) => {
entry.scope = scope;
Ok(entry)
}
None => Err(format!("memory file at {} is unreadable", path.display())),
}
}
/// True when a memory with this name/id already exists in the given scope.
pub fn memory_exists_scoped(workspace: &Path, scope: Scope, name: &str) -> bool {
get_memory_scoped(workspace, scope, name).is_ok()
}
/// Count of memories across both scopes (for save-path soft warnings).
pub fn memory_count(workspace: &Path) -> usize {
scan_all_memories(workspace).len()
}
/// Report from a stale-reference migration pass ([`migrate_memories`]).
#[derive(Clone, Debug, Default)]
pub struct MigrateReport {
pub migrated: Vec<String>,
pub message: String,
}
/// Old → new project-name substitution map applied by [`migrate_memories`].
/// Targets dead path/env references left by the umans-harness → catalyst-code
/// rename. The provider name "Umans" is intentionally NOT rewritten (it is a
/// distinct, still-valid name).
fn apply_rename_map(s: &str) -> String {
s.replace("UMANS_CORE", "CATALYST_CODE")
.replace(".umans-harness", ".catalyst-code")
.replace("umans-harness", "catalyst-code")
}
/// Emit a memory markdown file from explicit parsed fields (preserving
/// `pinned`/`importance`/deprecation metadata exactly as parsed — unlike
/// [`Store::save_scoped_with_importance`], which re-derives `pin` from type).
fn write_memory_file(
path: &Path,
e: &MemoryEntry,
content: &str,
description: &str,
) -> std::io::Result<()> {
let pin_line = if e.pinned { "pin: true\n" } else { "" };
let importance_line = if e.importance != Importance::Normal {
format!("importance: {}\n", e.importance.as_str())
} else {
String::new()
};
let dep_line = if e.deprecated {
"deprecated: true\n".to_string()
} else {
String::new()
};