Skip to main content

zagens_topic_memory/
inject.rs

1//! HTML-comment bounded injection markers.
2
3#[derive(Debug, Clone, Copy)]
4pub struct MemorySectionMarkers {
5    pub start: &'static str,
6    pub end: &'static str,
7}
8
9pub const DEFAULT_MARKERS: MemorySectionMarkers = MemorySectionMarkers {
10    start: "<!-- topic-memory-graph-start -->",
11    end: "<!-- topic-memory-graph-end -->",
12};
13
14/// Insert or replace a bounded memory section in markdown.
15#[must_use]
16pub fn inject_memory_section(
17    existing: &str,
18    content: &str,
19    markers: MemorySectionMarkers,
20) -> String {
21    let section = format!("{}\n{}\n{}", markers.start, content, markers.end);
22    let si = existing.find(markers.start);
23    let ei = existing.find(markers.end);
24    if let (Some(si), Some(ei)) = (si, ei)
25        && ei > si
26    {
27        let after_end = ei + markers.end.len();
28        return format!("{}{}{}", &existing[..si], section, &existing[after_end..]);
29    }
30    let trimmed = existing.trim_end();
31    if trimmed.is_empty() {
32        return section;
33    }
34    format!("{trimmed}\n\n{section}")
35}
36
37#[cfg(test)]
38mod tests {
39    use super::*;
40
41    #[test]
42    fn replaces_existing_section() {
43        let base = format!(
44            "# Agents\n\n{}\nold\n{}\n",
45            DEFAULT_MARKERS.start, DEFAULT_MARKERS.end
46        );
47        let out = inject_memory_section(&base, "new body", DEFAULT_MARKERS);
48        assert!(out.contains("new body"));
49        assert!(!out.contains("old"));
50    }
51}