forked from OpenCoven/coven-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclaudemd.rs
More file actions
911 lines (809 loc) · 32.7 KB
/
Copy pathclaudemd.rs
File metadata and controls
911 lines (809 loc) · 32.7 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
//! AGENTS.md hierarchical memory loading.
//! Mirrors src/utils/claudemd.ts (1,479 lines).
//!
//! Priority order: managed > user > project > local
//! Supports @include directives, YAML frontmatter, and mtime-based caching.
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::time::SystemTime;
use crate::hosted_review::{MemorySourceTrust, RuntimeMode};
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
/// Memory file type / priority scope.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum MemoryScope {
/// `~/.coven-code/rules/*.md` — global managed policy.
Managed,
/// `~/.coven-code/AGENTS.md` — user-level memory.
User,
/// `{project_root}/AGENTS.md` — project-level memory.
Project,
/// `{project_root}/.coven-code/AGENTS.md` — local override.
Local,
}
/// Frontmatter parsed from a AGENTS.md file.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct MemoryFrontmatter {
#[serde(default)]
pub id: Option<String>,
#[serde(default)]
pub memory_type: Option<String>,
#[serde(default)]
pub priority: Option<u32>,
#[serde(default)]
pub scope: Option<String>,
#[serde(default)]
pub trust: Option<MemorySourceTrust>,
#[serde(default)]
pub visibility: Option<MemoryVisibility>,
#[serde(default)]
pub source: Option<String>,
#[serde(default)]
pub source_ref: Option<String>,
#[serde(default)]
pub expires_at: Option<String>,
#[serde(default)]
pub retention_class: Option<String>,
#[serde(default)]
pub redacted_at: Option<String>,
#[serde(default)]
pub deleted_at: Option<String>,
#[serde(default)]
pub created_at: Option<String>,
#[serde(default)]
pub created_by: Option<String>,
#[serde(default)]
pub session_id: Option<String>,
#[serde(default)]
pub transcript_ref: Option<String>,
#[serde(default)]
pub confidence: Option<f32>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum MemoryVisibility {
PublicReview,
PrivateReview,
SecurityPrivate,
}
/// Loaded memory file with metadata.
#[derive(Debug, Clone)]
pub struct MemoryFileInfo {
pub path: PathBuf,
pub scope: MemoryScope,
pub content: String,
pub frontmatter: MemoryFrontmatter,
pub mtime: Option<SystemTime>,
}
/// Controls which memory scopes are loaded for the current runtime mode.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MemoryLoadOptions {
pub mode: RuntimeMode,
pub allow_user_memory: bool,
pub allow_managed_rules: bool,
pub min_trust: MemorySourceTrust,
pub allow_security_private: bool,
}
impl MemoryLoadOptions {
pub fn local() -> Self {
Self {
mode: RuntimeMode::Local,
allow_user_memory: true,
allow_managed_rules: true,
min_trust: MemorySourceTrust::Unknown,
allow_security_private: true,
}
}
pub fn hosted_review() -> Self {
Self {
mode: RuntimeMode::HostedReview,
allow_user_memory: false,
allow_managed_rules: false,
min_trust: MemorySourceTrust::MaintainerApproved,
allow_security_private: false,
}
}
pub fn from_mode(mode: RuntimeMode) -> Self {
match mode {
RuntimeMode::Local => Self::local(),
RuntimeMode::HostedReview => Self::hosted_review(),
}
}
}
fn memory_home_dir() -> Option<PathBuf> {
#[cfg(test)]
if let Ok(path) = std::env::var("COVEN_CODE_TEST_HOME") {
if !path.is_empty() {
return Some(PathBuf::from(path));
}
}
dirs::home_dir()
}
// ---------------------------------------------------------------------------
// Cache
// ---------------------------------------------------------------------------
/// Simple mtime-keyed file cache.
#[derive(Default)]
pub struct MemoryCache {
entries: HashMap<PathBuf, (SystemTime, String)>,
}
impl MemoryCache {
/// Return cached content if the file hasn't changed since last read.
pub fn get(&self, path: &Path) -> Option<&str> {
let mtime = std::fs::metadata(path).ok()?.modified().ok()?;
let (cached_mtime, content) = self.entries.get(path)?;
if *cached_mtime == mtime {
Some(content.as_str())
} else {
None
}
}
/// Store file content with its current mtime.
pub fn insert(&mut self, path: PathBuf, content: String) {
if let Ok(mtime) = std::fs::metadata(&path).and_then(|m| m.modified()) {
self.entries.insert(path, (mtime, content));
}
}
}
// ---------------------------------------------------------------------------
// YAML frontmatter parsing
// ---------------------------------------------------------------------------
/// Strip YAML frontmatter (--- ... ---) from content and parse it.
/// Returns (frontmatter, body_without_frontmatter).
pub fn parse_frontmatter(content: &str) -> (MemoryFrontmatter, &str) {
if !content.starts_with("---") {
return (MemoryFrontmatter::default(), content);
}
let after_first = &content[3..];
if let Some(end) = after_first.find("\n---") {
let yaml = after_first[..end].trim();
let body = &after_first[end + 4..];
// Minimal YAML key-value parse (no external dependency).
let mut fm = MemoryFrontmatter::default();
for line in yaml.lines() {
let line = line.trim();
if let Some((key, val)) = line.split_once(':') {
let val = val.trim().to_string();
match key.trim() {
"id" => fm.id = Some(strip_frontmatter_value(&val).to_string()),
"memory_type" => fm.memory_type = Some(val),
"priority" => fm.priority = val.parse().ok(),
"scope" => fm.scope = Some(strip_frontmatter_value(&val).to_string()),
"trust" => fm.trust = parse_memory_trust(&val),
"visibility" => fm.visibility = parse_memory_visibility(&val),
"source" => fm.source = Some(strip_frontmatter_value(&val).to_string()),
"source_ref" => fm.source_ref = Some(strip_frontmatter_value(&val).to_string()),
"expires_at" => fm.expires_at = Some(strip_frontmatter_value(&val).to_string()),
"retention_class" => {
fm.retention_class = Some(strip_frontmatter_value(&val).to_string())
}
"redacted_at" => {
fm.redacted_at = Some(strip_frontmatter_value(&val).to_string())
}
"deleted_at" => fm.deleted_at = Some(strip_frontmatter_value(&val).to_string()),
"created_at" => fm.created_at = Some(strip_frontmatter_value(&val).to_string()),
"created_by" => fm.created_by = Some(strip_frontmatter_value(&val).to_string()),
"session_id" => fm.session_id = Some(strip_frontmatter_value(&val).to_string()),
"transcript_ref" => {
fm.transcript_ref = Some(strip_frontmatter_value(&val).to_string())
}
"confidence" => fm.confidence = val.parse().ok(),
_ => {}
}
}
}
return (fm, body.trim_start_matches('\n'));
}
(MemoryFrontmatter::default(), content)
}
fn strip_frontmatter_value(value: &str) -> &str {
value.trim().trim_matches('"').trim_matches('\'')
}
fn normalized_frontmatter_value(value: &str) -> String {
strip_frontmatter_value(value)
.trim()
.to_ascii_lowercase()
.replace('-', "_")
}
fn parse_memory_trust(value: &str) -> Option<MemorySourceTrust> {
match normalized_frontmatter_value(value).as_str() {
"system_policy" => Some(MemorySourceTrust::SystemPolicy),
"maintainer_approved" | "maintainer" => Some(MemorySourceTrust::MaintainerApproved),
"default_branch_code" | "default_branch" => Some(MemorySourceTrust::DefaultBranchCode),
"contributor_input" | "contributor" | "untrusted" => {
Some(MemorySourceTrust::ContributorInput)
}
"fork_input" | "fork" => Some(MemorySourceTrust::ForkInput),
"model_inferred" => Some(MemorySourceTrust::ModelInferred),
"unknown" => Some(MemorySourceTrust::Unknown),
_ => None,
}
}
fn parse_memory_visibility(value: &str) -> Option<MemoryVisibility> {
match normalized_frontmatter_value(value).as_str() {
"public_review" | "public" => Some(MemoryVisibility::PublicReview),
"private_review" | "private" => Some(MemoryVisibility::PrivateReview),
"security_private" | "security" => Some(MemoryVisibility::SecurityPrivate),
_ => None,
}
}
// ---------------------------------------------------------------------------
// @include directive expansion
// ---------------------------------------------------------------------------
/// Maximum @include nesting depth.
const MAX_INCLUDE_DEPTH: usize = 10;
/// Expand @include directives in content.
/// Circular references are detected via `visited` set.
pub fn expand_includes(
content: &str,
base_dir: &Path,
visited: &mut HashSet<PathBuf>,
depth: usize,
) -> String {
if depth >= MAX_INCLUDE_DEPTH {
return content.to_string();
}
let mut result = String::with_capacity(content.len());
for line in content.lines() {
let trimmed = line.trim();
if let Some(path_str) = trimmed.strip_prefix("@include ") {
let path_str = path_str.trim();
// Resolve relative to base_dir; expand ~ to home dir.
let include_path = if path_str.starts_with('~') {
memory_home_dir().unwrap_or_default().join(&path_str[2..])
} else if Path::new(path_str).is_absolute() {
PathBuf::from(path_str)
} else {
base_dir.join(path_str)
};
let canonical = include_path.canonicalize().unwrap_or(include_path.clone());
if visited.contains(&canonical) {
result.push_str(&format!(
"<!-- circular @include {} skipped -->\n",
path_str
));
continue;
}
if let Ok(included) = std::fs::read_to_string(&include_path) {
// Check max size.
if included.len() > 40 * 1024 {
result.push_str(&format!(
"<!-- @include {} exceeds 40KB limit -->\n",
path_str
));
continue;
}
visited.insert(canonical);
let expanded = expand_includes(
&included,
include_path.parent().unwrap_or(base_dir),
visited,
depth + 1,
);
result.push_str(&expanded);
result.push('\n');
} else {
result.push_str(&format!("<!-- @include {} not found -->\n", path_str));
}
} else {
result.push_str(line);
result.push('\n');
}
}
result
}
// ---------------------------------------------------------------------------
// Loading API
// ---------------------------------------------------------------------------
const MAX_FILE_SIZE: u64 = 40 * 1024; // 40 KB
/// Load a single AGENTS.md file (respects MAX_FILE_SIZE, expands @includes).
pub fn load_memory_file(path: &Path, scope: MemoryScope) -> Option<MemoryFileInfo> {
let meta = std::fs::metadata(path).ok()?;
if meta.len() > MAX_FILE_SIZE {
eprintln!("WARNING: {} exceeds 40KB limit, skipping", path.display());
return None;
}
let raw = std::fs::read_to_string(path).ok()?;
let mtime = meta.modified().ok();
let (frontmatter, body) = parse_frontmatter(&raw);
let mut visited = HashSet::new();
visited.insert(path.canonicalize().unwrap_or(path.to_path_buf()));
let content = expand_includes(
body,
path.parent().unwrap_or(Path::new(".")),
&mut visited,
0,
);
Some(MemoryFileInfo {
path: path.to_path_buf(),
scope,
content,
frontmatter,
mtime,
})
}
pub fn memory_file_allowed_for_options(file: &MemoryFileInfo, options: &MemoryLoadOptions) -> bool {
if !options.mode.is_hosted_review() {
return true;
}
if memory_is_expired(file.frontmatter.expires_at.as_deref()) {
return false;
}
if file.frontmatter.deleted_at.is_some() {
return false;
}
if matches!(
file.frontmatter.visibility,
Some(MemoryVisibility::SecurityPrivate)
) && !options.allow_security_private
{
return false;
}
file.frontmatter
.trust
.unwrap_or(MemorySourceTrust::Unknown)
.meets_threshold(options.min_trust)
}
fn memory_is_expired(expires_at: Option<&str>) -> bool {
let Some(expires_at) = expires_at else {
return false;
};
let Ok(expires) = chrono::NaiveDate::parse_from_str(expires_at.trim(), "%Y-%m-%d") else {
return false;
};
expires < chrono::Local::now().date_naive()
}
pub fn memory_id(file: &MemoryFileInfo) -> String {
if let Some(id) = file.frontmatter.id.as_deref().filter(|id| !id.is_empty()) {
return id.to_string();
}
let mut hasher = Sha256::new();
hasher.update(file.path.to_string_lossy().as_bytes());
hasher.update(b"\0");
hasher.update(file.content.as_bytes());
let digest = hasher.finalize();
format!("mem_{}", hex::encode(&digest[..8]))
}
pub fn format_memory_file_for_prompt(file: &MemoryFileInfo, hosted: bool) -> String {
let body = if hosted && file.frontmatter.redacted_at.is_some() {
"[REDACTED: memory content removed; retain metadata for audit]"
} else {
file.content.trim()
};
if !hosted {
return body.to_string();
}
let trust = file
.frontmatter
.trust
.map(memory_trust_label)
.unwrap_or("unknown");
let visibility = file
.frontmatter
.visibility
.map(memory_visibility_label)
.unwrap_or("unspecified");
let source = file.frontmatter.source.as_deref().unwrap_or("manual");
let source_ref = file.frontmatter.source_ref.as_deref().unwrap_or("");
let mut attrs = format!(
"id=\"{}\" trust=\"{}\" visibility=\"{}\" source=\"{}\"",
xml_escape_attr(&memory_id(file)),
trust,
visibility,
xml_escape_attr(source)
);
if !source_ref.is_empty() {
attrs.push_str(&format!(" source_ref=\"{}\"", xml_escape_attr(source_ref)));
}
if let Some(session_id) = file.frontmatter.session_id.as_deref() {
attrs.push_str(&format!(" session_id=\"{}\"", xml_escape_attr(session_id)));
}
format!("<memory {}>\n{}\n</memory>", attrs, body)
}
fn memory_trust_label(trust: MemorySourceTrust) -> &'static str {
match trust {
MemorySourceTrust::SystemPolicy => "system-policy",
MemorySourceTrust::MaintainerApproved => "maintainer-approved",
MemorySourceTrust::DefaultBranchCode => "default-branch-code",
MemorySourceTrust::ContributorInput => "contributor-input",
MemorySourceTrust::ForkInput => "fork-input",
MemorySourceTrust::ModelInferred => "model-inferred",
MemorySourceTrust::Unknown => "unknown",
}
}
fn memory_visibility_label(visibility: MemoryVisibility) -> &'static str {
match visibility {
MemoryVisibility::PublicReview => "public-review",
MemoryVisibility::PrivateReview => "private-review",
MemoryVisibility::SecurityPrivate => "security-private",
}
}
fn xml_escape_attr(value: &str) -> String {
value
.replace('&', "&")
.replace('"', """)
.replace('<', "<")
.replace('>', ">")
}
/// Load memory files from a directory for a given scope.
///
/// Loads `AGENTS.md` first (primary/universal standard), then `CLAUDE.md` if
/// present (Claude-specific additions or overrides). Either file may be absent.
fn load_scope_files(dir: &Path, scope: MemoryScope, files: &mut Vec<MemoryFileInfo>) {
for name in &["AGENTS.md", "CLAUDE.md"] {
let path = dir.join(name);
if path.exists() {
if let Some(f) = load_memory_file(&path, scope) {
files.push(f);
}
}
}
}
/// Load all memory files for the given project root, in priority order.
///
/// At each scope `AGENTS.md` is loaded first (universal standard), followed by
/// `CLAUDE.md` if present (Claude-specific context). Either or both may exist.
///
/// Returned list is ordered: Managed (highest) → User → Project → Local.
pub fn load_all_memory_files(project_root: &Path) -> Vec<MemoryFileInfo> {
load_all_memory_files_with_options(project_root, &MemoryLoadOptions::local())
}
/// Load all memory files for the given project root using explicit scope gates.
pub fn load_all_memory_files_with_options(
project_root: &Path,
options: &MemoryLoadOptions,
) -> Vec<MemoryFileInfo> {
let mut files = Vec::new();
// 1. Managed: ~/.coven-code/rules/*.md
if let Some(home) = memory_home_dir() {
if options.allow_managed_rules {
let rules_dir = home.join(".coven-code/rules");
if let Ok(entries) = std::fs::read_dir(&rules_dir) {
let mut paths: Vec<PathBuf> = entries
.flatten()
.filter_map(|e| {
let p = e.path();
if p.extension().is_some_and(|x| x == "md") {
Some(p)
} else {
None
}
})
.collect();
paths.sort();
for p in paths {
if let Some(f) = load_memory_file(&p, MemoryScope::Managed) {
files.push(f);
}
}
}
}
// 2. User: ~/.coven-code/AGENTS.md then ~/.coven-code/CLAUDE.md
if options.allow_user_memory {
load_scope_files(&home.join(".coven-code"), MemoryScope::User, &mut files);
}
}
// 3. Project: {project_root}/AGENTS.md then {project_root}/CLAUDE.md
load_scope_files(project_root, MemoryScope::Project, &mut files);
// 4. Local: {project_root}/.coven-code/AGENTS.md then {project_root}/.coven-code/CLAUDE.md
load_scope_files(
&project_root.join(".coven-code"),
MemoryScope::Local,
&mut files,
);
files
.into_iter()
.filter(|file| memory_file_allowed_for_options(file, options))
.collect()
}
/// Concatenate all memory file contents into a single system-prompt fragment.
pub fn build_memory_prompt(files: &[MemoryFileInfo]) -> String {
files
.iter()
.filter(|f| !f.content.trim().is_empty())
.map(|f| format_memory_file_for_prompt(f, false))
.collect::<Vec<_>>()
.join("\n\n")
}
pub fn build_memory_prompt_with_options(
files: &[MemoryFileInfo],
options: &MemoryLoadOptions,
) -> String {
files
.iter()
.filter(|f| !f.content.trim().is_empty())
.map(|f| format_memory_file_for_prompt(f, options.mode.is_hosted_review()))
.collect::<Vec<_>>()
.join("\n\n")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_frontmatter_basic() {
let content = "---\nmemory_type: project\npriority: 10\n---\nHello world";
let (fm, body) = parse_frontmatter(content);
assert_eq!(fm.memory_type.as_deref(), Some("project"));
assert_eq!(fm.priority, Some(10));
assert_eq!(body.trim(), "Hello world");
}
#[test]
fn parse_frontmatter_hosted_metadata() {
let content = "---\nid: mem_auth\nmemory_type: project\nscope: repo\ntrust: maintainer_approved\nvisibility: public_review\nsource: github_pr\nsource_ref: OpenCoven/coven-code#123\nexpires_at: 2099-12-31\nsession_id: sess-1\nconfidence: 0.9\n---\nUse explicit auth checks.";
let (fm, body) = parse_frontmatter(content);
assert_eq!(fm.id.as_deref(), Some("mem_auth"));
assert_eq!(fm.scope.as_deref(), Some("repo"));
assert_eq!(fm.trust, Some(MemorySourceTrust::MaintainerApproved));
assert_eq!(fm.visibility, Some(MemoryVisibility::PublicReview));
assert_eq!(fm.source.as_deref(), Some("github_pr"));
assert_eq!(fm.source_ref.as_deref(), Some("OpenCoven/coven-code#123"));
assert_eq!(fm.expires_at.as_deref(), Some("2099-12-31"));
assert_eq!(fm.session_id.as_deref(), Some("sess-1"));
assert_eq!(fm.confidence, Some(0.9));
assert_eq!(body.trim(), "Use explicit auth checks.");
}
#[test]
fn parse_frontmatter_none() {
let content = "No frontmatter here";
let (fm, body) = parse_frontmatter(content);
assert!(fm.memory_type.is_none());
assert_eq!(body, content);
}
#[test]
fn load_scope_prefers_agents_then_claude() {
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("AGENTS.md"), "agents content").unwrap();
std::fs::write(tmp.path().join("CLAUDE.md"), "claude content").unwrap();
let files = load_all_memory_files(tmp.path());
// Filter to just the project-scope files from our temp dir.
let project: Vec<_> = files
.iter()
.filter(|f| f.path.starts_with(tmp.path()))
.collect();
assert_eq!(
project.len(),
2,
"both AGENTS.md and CLAUDE.md should be loaded"
);
assert!(
project[0].path.ends_with("AGENTS.md"),
"AGENTS.md must come first"
);
assert!(
project[1].path.ends_with("CLAUDE.md"),
"CLAUDE.md must follow"
);
}
#[test]
fn load_scope_claudemd_only_fallback() {
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("CLAUDE.md"), "claude only").unwrap();
let files = load_all_memory_files(tmp.path());
let project: Vec<_> = files
.iter()
.filter(|f| f.path.starts_with(tmp.path()))
.collect();
assert_eq!(project.len(), 1);
assert!(project[0].path.ends_with("CLAUDE.md"));
}
#[test]
fn hosted_review_excludes_user_memory_by_default() {
let project = tempfile::tempdir().unwrap();
std::fs::write(
project.path().join("AGENTS.md"),
"---\ntrust: maintainer_approved\nvisibility: public_review\n---\nproject memory",
)
.unwrap();
let home = tempfile::tempdir().unwrap();
let coven_code = home.path().join(".coven-code");
std::fs::create_dir_all(&coven_code).unwrap();
std::fs::write(coven_code.join("AGENTS.md"), "user memory").unwrap();
let _lock = crate::coven_shared::COVEN_HOME_ENV_LOCK
.lock()
.unwrap_or_else(|err| err.into_inner());
let original_test_home = std::env::var("COVEN_CODE_TEST_HOME").ok();
let original_home = std::env::var("HOME").ok();
let original_userprofile = std::env::var("USERPROFILE").ok();
std::env::set_var("COVEN_CODE_TEST_HOME", home.path());
std::env::set_var("HOME", home.path());
std::env::set_var("USERPROFILE", home.path());
let files =
load_all_memory_files_with_options(project.path(), &MemoryLoadOptions::hosted_review());
match original_test_home {
Some(value) => std::env::set_var("COVEN_CODE_TEST_HOME", value),
None => std::env::remove_var("COVEN_CODE_TEST_HOME"),
}
match original_home {
Some(value) => std::env::set_var("HOME", value),
None => std::env::remove_var("HOME"),
}
match original_userprofile {
Some(value) => std::env::set_var("USERPROFILE", value),
None => std::env::remove_var("USERPROFILE"),
}
assert!(files.iter().all(|file| file.scope != MemoryScope::User));
assert!(files.iter().any(|file| {
file.scope == MemoryScope::Project && file.content.contains("project memory")
}));
}
#[test]
fn hosted_review_loads_managed_rules_only_when_allowed() {
let project = tempfile::tempdir().unwrap();
let home = tempfile::tempdir().unwrap();
let rules = home.path().join(".coven-code").join("rules");
std::fs::create_dir_all(&rules).unwrap();
std::fs::write(
rules.join("managed.md"),
"---\ntrust: system_policy\nvisibility: public_review\n---\nmanaged hosted policy",
)
.unwrap();
let _lock = crate::coven_shared::COVEN_HOME_ENV_LOCK
.lock()
.unwrap_or_else(|err| err.into_inner());
let original_test_home = std::env::var("COVEN_CODE_TEST_HOME").ok();
let original_home = std::env::var("HOME").ok();
let original_userprofile = std::env::var("USERPROFILE").ok();
std::env::set_var("COVEN_CODE_TEST_HOME", home.path());
std::env::set_var("HOME", home.path());
std::env::set_var("USERPROFILE", home.path());
let default_hosted =
load_all_memory_files_with_options(project.path(), &MemoryLoadOptions::hosted_review());
let mut trusted_policy = MemoryLoadOptions::hosted_review();
trusted_policy.allow_managed_rules = true;
let trusted_hosted = load_all_memory_files_with_options(project.path(), &trusted_policy);
match original_test_home {
Some(value) => std::env::set_var("COVEN_CODE_TEST_HOME", value),
None => std::env::remove_var("COVEN_CODE_TEST_HOME"),
}
match original_home {
Some(value) => std::env::set_var("HOME", value),
None => std::env::remove_var("HOME"),
}
match original_userprofile {
Some(value) => std::env::set_var("USERPROFILE", value),
None => std::env::remove_var("USERPROFILE"),
}
assert!(default_hosted
.iter()
.all(|file| file.scope != MemoryScope::Managed));
assert!(trusted_hosted.iter().any(|file| {
file.scope == MemoryScope::Managed && file.content.contains("managed hosted policy")
}));
}
#[test]
fn hosted_review_excludes_missing_or_untrusted_memory_metadata() {
let project = tempfile::tempdir().unwrap();
std::fs::write(project.path().join("AGENTS.md"), "legacy project memory").unwrap();
std::fs::create_dir_all(project.path().join(".coven-code")).unwrap();
std::fs::write(
project.path().join(".coven-code").join("AGENTS.md"),
"---\ntrust: contributor_input\nvisibility: public_review\n---\nuntrusted memory",
)
.unwrap();
let files =
load_all_memory_files_with_options(project.path(), &MemoryLoadOptions::hosted_review());
assert!(files.is_empty());
}
#[test]
fn hosted_review_excludes_expired_memory() {
let project = tempfile::tempdir().unwrap();
std::fs::write(
project.path().join("AGENTS.md"),
"---\ntrust: maintainer_approved\nvisibility: public_review\nexpires_at: 2000-01-01\n---\nexpired memory",
)
.unwrap();
let files =
load_all_memory_files_with_options(project.path(), &MemoryLoadOptions::hosted_review());
assert!(files.is_empty());
}
#[test]
fn hosted_review_excludes_deleted_memory() {
let project = tempfile::tempdir().unwrap();
std::fs::write(
project.path().join("AGENTS.md"),
"---\ntrust: maintainer_approved\nvisibility: public_review\ndeleted_at: 2026-01-01T00:00:00Z\n---\ndeleted memory",
)
.unwrap();
let files =
load_all_memory_files_with_options(project.path(), &MemoryLoadOptions::hosted_review());
assert!(files.is_empty());
}
#[test]
fn hosted_review_redacts_memory_content_in_prompt() {
let project = tempfile::tempdir().unwrap();
std::fs::write(
project.path().join("AGENTS.md"),
"---\nid: mem_redacted\ntrust: maintainer_approved\nvisibility: public_review\nredacted_at: 2026-01-01T00:00:00Z\n---\noriginal sensitive detail",
)
.unwrap();
let options = MemoryLoadOptions::hosted_review();
let files = load_all_memory_files_with_options(project.path(), &options);
let prompt = build_memory_prompt_with_options(&files, &options);
assert!(prompt.contains("id=\"mem_redacted\""));
assert!(prompt.contains("[REDACTED: memory content removed"));
assert!(!prompt.contains("original sensitive detail"));
}
#[test]
fn hosted_review_excludes_security_private_memory_by_default() {
let project = tempfile::tempdir().unwrap();
std::fs::write(
project.path().join("AGENTS.md"),
"---\ntrust: maintainer_approved\nvisibility: security_private\n---\nprivate memory",
)
.unwrap();
let files =
load_all_memory_files_with_options(project.path(), &MemoryLoadOptions::hosted_review());
assert!(files.is_empty());
}
#[test]
fn hosted_review_renders_memory_ids_and_provenance() {
let project = tempfile::tempdir().unwrap();
std::fs::write(
project.path().join("AGENTS.md"),
"---\nid: mem_review_policy\ntrust: maintainer_approved\nvisibility: public_review\nsource: github_pr\nsource_ref: OpenCoven/coven-code#123\nsession_id: sess-1\n---\nAlways cite auth policy.",
)
.unwrap();
let options = MemoryLoadOptions::hosted_review();
let files = load_all_memory_files_with_options(project.path(), &options);
let prompt = build_memory_prompt_with_options(&files, &options);
assert!(prompt.contains("<memory id=\"mem_review_policy\""));
assert!(prompt.contains("trust=\"maintainer-approved\""));
assert!(prompt.contains("source_ref=\"OpenCoven/coven-code#123\""));
assert!(prompt.contains("session_id=\"sess-1\""));
assert!(prompt.contains("Always cite auth policy."));
}
#[test]
fn local_memory_load_still_includes_user_memory() {
let project = tempfile::tempdir().unwrap();
std::fs::write(project.path().join("AGENTS.md"), "project memory").unwrap();
let home = tempfile::tempdir().unwrap();
let coven_code = home.path().join(".coven-code");
std::fs::create_dir_all(&coven_code).unwrap();
std::fs::write(coven_code.join("AGENTS.md"), "user memory").unwrap();
let _lock = crate::coven_shared::COVEN_HOME_ENV_LOCK
.lock()
.unwrap_or_else(|err| err.into_inner());
let original_test_home = std::env::var("COVEN_CODE_TEST_HOME").ok();
let original_home = std::env::var("HOME").ok();
let original_userprofile = std::env::var("USERPROFILE").ok();
std::env::set_var("COVEN_CODE_TEST_HOME", home.path());
std::env::set_var("HOME", home.path());
std::env::set_var("USERPROFILE", home.path());
let files = load_all_memory_files_with_options(project.path(), &MemoryLoadOptions::local());
match original_test_home {
Some(value) => std::env::set_var("COVEN_CODE_TEST_HOME", value),
None => std::env::remove_var("COVEN_CODE_TEST_HOME"),
}
match original_home {
Some(value) => std::env::set_var("HOME", value),
None => std::env::remove_var("HOME"),
}
match original_userprofile {
Some(value) => std::env::set_var("USERPROFILE", value),
None => std::env::remove_var("USERPROFILE"),
}
assert!(files
.iter()
.any(|file| file.scope == MemoryScope::User && file.content.contains("user memory")));
}
#[test]
fn expand_includes_circular() {
let tmp = tempfile::tempdir().unwrap();
let a = tmp.path().join("a.md");
let b = tmp.path().join("b.md");
std::fs::write(&a, "@include b.md\n").unwrap();
std::fs::write(&b, "@include a.md\ncontent\n").unwrap();
let result = expand_includes(
"@include a.md\n",
tmp.path(),
&mut std::collections::HashSet::new(),
0,
);
// Should not infinite-loop; circular reference comment present.
assert!(result.contains("circular") || result.contains("content"));
}
}