Skip to main content

aidaemon_memory/
project.rs

1//! Project memory: what the agent learns about one project, kept as plain
2//! Markdown files in a directory of that project's own, apart from the
3//! owner's personal memory.
4//!
5//! ```text
6//! <root>/<project-id>/memory/
7//!     MEMORY.md                 index, rebuilt after every write
8//!     fact-<key>.md
9//!     procedure-<key>.md
10//!     pitfall-<key>.md
11//!     reference-<key>.md
12//! ```
13//!
14//! Each note is one file with a small front matter (`name`, `description`,
15//! `type`, `category`, `source`, `updated`) and a body. Notes are keyed by
16//! the project's id, so renaming the project or moving its folder keeps
17//! them. A note the owner adds or edits by hand is read like any other; a
18//! file without valid front matter is listed by its file name and never
19//! deleted. The same key in the same project replaces that note and nothing
20//! else: there is no fuzzy matching and nothing crosses projects.
21//!
22//! The files are plain text on disk: callers must never route personal or
23//! identity memory here. Values of registered secrets are redacted before a
24//! note is written.
25
26use std::collections::HashMap;
27use std::fs;
28use std::io::{self, Write as _};
29use std::path::{Path, PathBuf};
30use std::sync::{Arc, Mutex};
31
32use aidaemon_core::ProjectRef;
33
34/// The index file in each project's memory directory.
35pub const INDEX_FILE: &str = "MEMORY.md";
36/// A note's body is at most this many bytes.
37pub const MAX_NOTE_BYTES: usize = 8 * 1024;
38/// The index shown to the model is at most this many characters.
39pub const MAX_INDEX_CHARS: usize = 4 * 1024;
40/// A file larger than this is not read as a note.
41const MAX_READ_BYTES: u64 = 256 * 1024;
42/// At most this many notes are read for an index.
43const MAX_NOTES: usize = 500;
44/// A key is cut to this many characters in a file name.
45const MAX_KEY_CHARS: usize = 80;
46/// A description is cut to this many characters.
47const MAX_DESCRIPTION_CHARS: usize = 160;
48
49/// Where one memory goes on a turn that works in a project.
50#[derive(Debug, Clone, Copy, PartialEq, Eq)]
51pub enum MemoryScope {
52    /// The owner's personal memory, as on any other turn.
53    Personal,
54    /// The project's notes.
55    Project,
56}
57
58impl MemoryScope {
59    pub fn parse(value: &str) -> Option<Self> {
60        match value.trim().to_ascii_lowercase().as_str() {
61            "personal" | "owner" | "global" => Some(MemoryScope::Personal),
62            "project" => Some(MemoryScope::Project),
63            _ => None,
64        }
65    }
66}
67
68/// Categories about the owner and the people around them. They are never
69/// project notes, whatever scope is asked for: notes are plain text on disk,
70/// and who someone is does not belong to a project.
71pub fn category_is_personal_only(category: &str) -> bool {
72    matches!(
73        category.trim().to_ascii_lowercase().as_str(),
74        "user"
75            | "personal"
76            | "profile"
77            | "identity"
78            | "people"
79            | "person"
80            | "relationship"
81            | "relationships"
82            | "family"
83            | "assistant"
84            | "bot"
85            | "health"
86            | "contact"
87    )
88}
89
90/// Where a memory of `category` goes. Without a project, always personal.
91/// In a project, personal-only categories stay personal; otherwise the
92/// `requested` scope wins, and without one a `preference` is personal and
93/// anything else belongs to the project.
94pub fn route(category: &str, requested: Option<MemoryScope>, in_project: bool) -> MemoryScope {
95    if !in_project || category_is_personal_only(category) {
96        return MemoryScope::Personal;
97    }
98    match requested {
99        Some(scope) => scope,
100        None if category.trim().eq_ignore_ascii_case("preference") => MemoryScope::Personal,
101        None => MemoryScope::Project,
102    }
103}
104
105/// The note kind a memory category names (`procedure`, `pitfall`,
106/// `reference`), else a fact.
107pub fn kind_for_category(category: &str) -> NoteKind {
108    match NoteKind::parse(category) {
109        Some(kind) => kind,
110        None => match category.trim().to_ascii_lowercase().as_str() {
111            "error_solution" | "error" | "gotcha" => NoteKind::Pitfall,
112            "how_to" | "howto" | "workflow" => NoteKind::Procedure,
113            _ => NoteKind::Fact,
114        },
115    }
116}
117
118/// The `source` of a [`crate::records::Fact`] that stands for a project
119/// note in an extractor's ALREADY STORED list ([`notes_as_shown_facts`]).
120pub const NOTE_FACT_SOURCE: &str = "project_note";
121
122/// At most this many notes are shown to an extractor.
123const MAX_NOTES_SHOWN: usize = 12;
124
125/// The project's notes as stored facts an extractor is shown, so a
126/// restatement of a note is marked instead of stored again and a correction
127/// names the note it corrects. Each has a negative id, never a store row's.
128pub fn notes_as_shown_facts(entries: &[NoteEntry]) -> Vec<crate::records::Fact> {
129    let long_ago = chrono::DateTime::<chrono::Utc>::from_timestamp(0, 0).unwrap_or_default();
130    entries
131        .iter()
132        .filter(|entry| entry.kind.is_some())
133        .take(MAX_NOTES_SHOWN)
134        .enumerate()
135        .map(|(i, entry)| crate::records::Fact {
136            id: -(i as i64) - 1,
137            category: entry.category.clone().unwrap_or_else(|| {
138                entry
139                    .kind
140                    .map(NoteKind::as_str)
141                    .unwrap_or("project")
142                    .to_string()
143            }),
144            key: entry.name.clone(),
145            value: entry.description.clone(),
146            source: NOTE_FACT_SOURCE.to_string(),
147            created_at: long_ago,
148            updated_at: long_ago,
149            superseded_at: None,
150            recall_count: 0,
151            last_recalled_at: None,
152            channel_id: None,
153            privacy: crate::records::FactPrivacy::Private,
154            first_seen_at: None,
155            source_excerpt: None,
156        })
157        .collect()
158}
159
160/// Whether `fact` stands for a project note ([`notes_as_shown_facts`]).
161pub fn is_note_fact(fact: &crate::records::Fact) -> bool {
162    fact.id < 0 && fact.source == NOTE_FACT_SOURCE
163}
164
165/// What a note holds.
166#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
167pub enum NoteKind {
168    /// A stable fact about the project (a command, a convention, a path).
169    Fact,
170    /// How to do something in this project.
171    Procedure,
172    /// A mistake to avoid here and what works instead.
173    Pitfall,
174    /// Where something is (a document, a dashboard, a ticket).
175    Reference,
176}
177
178impl NoteKind {
179    pub const ALL: [NoteKind; 4] = [
180        NoteKind::Fact,
181        NoteKind::Procedure,
182        NoteKind::Pitfall,
183        NoteKind::Reference,
184    ];
185
186    pub fn as_str(self) -> &'static str {
187        match self {
188            NoteKind::Fact => "fact",
189            NoteKind::Procedure => "procedure",
190            NoteKind::Pitfall => "pitfall",
191            NoteKind::Reference => "reference",
192        }
193    }
194
195    pub fn parse(value: &str) -> Option<Self> {
196        Self::ALL
197            .into_iter()
198            .find(|kind| kind.as_str().eq_ignore_ascii_case(value.trim()))
199    }
200}
201
202/// Who wrote a note.
203#[derive(Debug, Clone, Copy, PartialEq, Eq)]
204pub enum NoteSource {
205    /// The agent, on purpose (a memory tool).
206    Agent,
207    /// Extracted from a conversation in the background.
208    Extracted,
209    /// Learned from how a run went.
210    Learned,
211}
212
213impl NoteSource {
214    pub fn as_str(self) -> &'static str {
215        match self {
216            NoteSource::Agent => "agent",
217            NoteSource::Extracted => "extracted",
218            NoteSource::Learned => "learned",
219        }
220    }
221}
222
223/// One note to write.
224#[derive(Debug, Clone)]
225pub struct NoteWrite {
226    pub kind: NoteKind,
227    /// The note's key; with the kind it names the file.
228    pub key: String,
229    /// The memory category it was given (`technical`, `project`, ...).
230    pub category: Option<String>,
231    /// One line for the index; the body's first line when `None`.
232    pub description: Option<String>,
233    pub body: String,
234    pub source: NoteSource,
235}
236
237/// What a write did.
238#[derive(Debug, Clone, Copy, PartialEq, Eq)]
239pub enum WriteOutcome {
240    Created,
241    Replaced,
242    /// The note already said exactly this.
243    Unchanged,
244}
245
246/// A note as the index lists it.
247#[derive(Debug, Clone, PartialEq, Eq)]
248pub struct NoteEntry {
249    /// `None` for a file without valid front matter.
250    pub kind: Option<NoteKind>,
251    pub name: String,
252    pub file: String,
253    pub description: String,
254    pub category: Option<String>,
255}
256
257/// Why a note was not written.
258#[derive(Debug)]
259pub enum NoteError {
260    /// The key has no letters or digits.
261    EmptyKey,
262    /// The body is empty.
263    EmptyBody,
264    /// The body is over [`MAX_NOTE_BYTES`].
265    TooLarge {
266        bytes: usize,
267    },
268    /// The project's id is not a safe directory name.
269    InvalidProject,
270    /// The target is outside the project's memory directory (a symlink).
271    OutsideDirectory,
272    Io(io::Error),
273}
274
275impl std::fmt::Display for NoteError {
276    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
277        match self {
278            NoteError::EmptyKey => f.write_str("the key needs at least one letter or digit"),
279            NoteError::EmptyBody => f.write_str("the value is empty"),
280            NoteError::TooLarge { bytes } => write!(
281                f,
282                "the value is {bytes} bytes; a project note holds at most {MAX_NOTE_BYTES}"
283            ),
284            NoteError::InvalidProject => f.write_str("the project id is not valid"),
285            NoteError::OutsideDirectory => {
286                f.write_str("the note's path leaves the project's memory directory")
287            }
288            NoteError::Io(error) => write!(f, "{error}"),
289        }
290    }
291}
292
293impl std::error::Error for NoteError {}
294
295impl From<io::Error> for NoteError {
296    fn from(error: io::Error) -> Self {
297        NoteError::Io(error)
298    }
299}
300
301/// Every project's memory, under one root directory.
302pub struct ProjectNotes {
303    root: PathBuf,
304}
305
306/// One lock per project memory directory, shared by every [`ProjectNotes`]
307/// in the process, so writes to one project are serialized however many
308/// handles the host made.
309static LOCKS: std::sync::LazyLock<Mutex<HashMap<PathBuf, Arc<Mutex<()>>>>> =
310    std::sync::LazyLock::new(Mutex::default);
311
312impl std::fmt::Debug for ProjectNotes {
313    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
314        f.debug_struct("ProjectNotes")
315            .field("root", &self.root)
316            .finish()
317    }
318}
319
320impl ProjectNotes {
321    /// Project memory under `root` (created on the first write).
322    pub fn new(root: impl Into<PathBuf>) -> Self {
323        Self { root: root.into() }
324    }
325
326    /// The directory holding every project's memory.
327    pub fn root(&self) -> &Path {
328        &self.root
329    }
330
331    /// `project`'s memory directory, when its id is valid.
332    pub fn dir(&self, project: &ProjectRef) -> Option<PathBuf> {
333        ProjectRef::is_valid_id(&project.id).then(|| self.root.join(&project.id).join("memory"))
334    }
335
336    fn lock(&self, project_id: &str) -> Arc<Mutex<()>> {
337        let key = self.root.join(project_id);
338        let mut locks = LOCKS.lock().unwrap_or_else(|e| e.into_inner());
339        locks
340            .entry(key)
341            .or_insert_with(|| Arc::new(Mutex::new(())))
342            .clone()
343    }
344
345    /// The file name a note of `kind` and `key` is kept in, when the key
346    /// has a letter or digit.
347    pub fn file_name(kind: NoteKind, key: &str) -> Option<String> {
348        let key = note_key(key)?;
349        Some(format!("{}-{key}.md", kind.as_str()))
350    }
351
352    /// Writes (or replaces) one note.
353    pub fn write(&self, project: &ProjectRef, note: &NoteWrite) -> Result<WriteOutcome, NoteError> {
354        let dir = self.dir(project).ok_or(NoteError::InvalidProject)?;
355        let key = note_key(&note.key).ok_or(NoteError::EmptyKey)?;
356        let body = aidaemon_core::redaction::redact_registered(note.body.trim()).into_owned();
357        if body.is_empty() {
358            return Err(NoteError::EmptyBody);
359        }
360        if body.len() > MAX_NOTE_BYTES {
361            return Err(NoteError::TooLarge { bytes: body.len() });
362        }
363        let lock = self.lock(&project.id);
364        let _guard = lock.lock().unwrap_or_else(|e| e.into_inner());
365        fs::create_dir_all(&dir)?;
366        let dir = self.checked_dir(&dir)?;
367        let file = format!("{}-{key}.md", note.kind.as_str());
368        let path = dir.join(&file);
369        refuse_symlink(&path)?;
370        let description = one_line(
371            note.description
372                .as_deref()
373                .filter(|d| !d.trim().is_empty())
374                .unwrap_or_else(|| body.lines().find(|l| !l.trim().is_empty()).unwrap_or("")),
375        );
376        let description = aidaemon_core::redaction::redact_registered(&description).into_owned();
377        let previous = fs::read_to_string(&path).ok();
378        if let Some(previous) = &previous
379            && let Some(parsed) = parse_note(previous)
380            && parsed.body.trim() == body
381            && parsed.description == description
382            && parsed.kind == Some(note.kind)
383            && parsed.category.as_deref() == note.category.as_deref().map(str::trim)
384        {
385            return Ok(WriteOutcome::Unchanged);
386        }
387        let mut text = String::new();
388        text.push_str("---\n");
389        text.push_str(&format!("name: {key}\n"));
390        text.push_str(&format!("description: {description}\n"));
391        text.push_str(&format!("type: {}\n", note.kind.as_str()));
392        if let Some(category) = note.category.as_deref().map(one_line)
393            && !category.is_empty()
394        {
395            text.push_str(&format!("category: {category}\n"));
396        }
397        text.push_str(&format!("source: {}\n", note.source.as_str()));
398        text.push_str(&format!(
399            "updated: {}\n",
400            chrono::Utc::now().format("%Y-%m-%d")
401        ));
402        text.push_str("---\n");
403        text.push_str(&body);
404        text.push('\n');
405        write_atomically(&path, &text)?;
406        self.rebuild_index_locked(&dir)?;
407        Ok(if previous.is_some() {
408            WriteOutcome::Replaced
409        } else {
410            WriteOutcome::Created
411        })
412    }
413
414    /// Deletes the note of `key`, of `kind` or of any kind. Returns whether
415    /// a note was deleted.
416    pub fn delete(
417        &self,
418        project: &ProjectRef,
419        kind: Option<NoteKind>,
420        key: &str,
421    ) -> Result<bool, NoteError> {
422        let dir = self.dir(project).ok_or(NoteError::InvalidProject)?;
423        let Some(key) = note_key(key) else {
424            return Ok(false);
425        };
426        if !dir.is_dir() {
427            return Ok(false);
428        }
429        let lock = self.lock(&project.id);
430        let _guard = lock.lock().unwrap_or_else(|e| e.into_inner());
431        let dir = self.checked_dir(&dir)?;
432        let kinds: Vec<NoteKind> = match kind {
433            Some(kind) => vec![kind],
434            None => NoteKind::ALL.to_vec(),
435        };
436        let mut deleted = false;
437        for kind in kinds {
438            let path = dir.join(format!("{}-{key}.md", kind.as_str()));
439            refuse_symlink(&path)?;
440            match fs::remove_file(&path) {
441                Ok(()) => deleted = true,
442                Err(error) if error.kind() == io::ErrorKind::NotFound => {}
443                Err(error) => return Err(error.into()),
444            }
445        }
446        if deleted {
447            self.rebuild_index_locked(&dir)?;
448        }
449        Ok(deleted)
450    }
451
452    /// The note of `kind` and `key`, as written on disk.
453    pub fn read(&self, project: &ProjectRef, kind: NoteKind, key: &str) -> Option<String> {
454        let dir = self.dir(project)?;
455        let path = dir.join(Self::file_name(kind, key)?);
456        if fs::symlink_metadata(&path).ok()?.file_type().is_symlink() {
457            return None;
458        }
459        fs::read_to_string(path).ok()
460    }
461
462    /// Every note of `project`, sorted by kind then name; empty when it has
463    /// none.
464    pub fn entries(&self, project: &ProjectRef) -> Vec<NoteEntry> {
465        let Some(dir) = self.dir(project) else {
466            return Vec::new();
467        };
468        read_entries(&dir)
469    }
470
471    /// The section shown to the model on `project`'s turns, or `None` when
472    /// the project has no notes.
473    pub fn section(&self, project: &ProjectRef) -> Option<String> {
474        let dir = self.dir(project)?;
475        let entries = read_entries(&dir);
476        if entries.is_empty() {
477            return None;
478        }
479        Some(render_section(project, &dir, &entries))
480    }
481
482    /// The index rebuilt from the notes on disk, after a write the caller
483    /// made outside [`ProjectNotes::write`].
484    pub fn rebuild_index(&self, project: &ProjectRef) -> Result<(), NoteError> {
485        let dir = self.dir(project).ok_or(NoteError::InvalidProject)?;
486        if !dir.is_dir() {
487            return Ok(());
488        }
489        let lock = self.lock(&project.id);
490        let _guard = lock.lock().unwrap_or_else(|e| e.into_inner());
491        let dir = self.checked_dir(&dir)?;
492        self.rebuild_index_locked(&dir)
493    }
494
495    fn rebuild_index_locked(&self, dir: &Path) -> Result<(), NoteError> {
496        let entries = read_entries(dir);
497        let path = dir.join(INDEX_FILE);
498        refuse_symlink(&path)?;
499        if entries.is_empty() {
500            match fs::remove_file(&path) {
501                Ok(()) => {}
502                Err(error) if error.kind() == io::ErrorKind::NotFound => {}
503                Err(error) => return Err(error.into()),
504            }
505            return Ok(());
506        }
507        let mut text = String::from(
508            "# Project memory\n\nGenerated from the notes in this directory; edit the notes, not this file.\n\n",
509        );
510        for entry in &entries {
511            text.push_str(&index_line(entry));
512            text.push('\n');
513        }
514        write_atomically(&path, &text)?;
515        Ok(())
516    }
517
518    /// `dir`, resolved, when it is inside the resolved root.
519    fn checked_dir(&self, dir: &Path) -> Result<PathBuf, NoteError> {
520        let root = dunce_canonical(&self.root)?;
521        let resolved = dunce_canonical(dir)?;
522        if resolved.starts_with(&root) && resolved != root {
523            Ok(resolved)
524        } else {
525            Err(NoteError::OutsideDirectory)
526        }
527    }
528}
529
530/// `path` resolved, without Windows' verbatim prefix.
531fn dunce_canonical(path: &Path) -> io::Result<PathBuf> {
532    let resolved = fs::canonicalize(path)?;
533    #[cfg(windows)]
534    {
535        let text = resolved.to_string_lossy();
536        if let Some(stripped) = text.strip_prefix(r"\\?\")
537            && !stripped.starts_with("UNC\\")
538        {
539            return Ok(PathBuf::from(stripped));
540        }
541    }
542    Ok(resolved)
543}
544
545fn refuse_symlink(path: &Path) -> Result<(), NoteError> {
546    match fs::symlink_metadata(path) {
547        Ok(meta) if meta.file_type().is_symlink() => Err(NoteError::OutsideDirectory),
548        _ => Ok(()),
549    }
550}
551
552/// Writes `text` to a temporary file beside `path`, then renames it over
553/// `path`, so a reader never sees half a note.
554fn write_atomically(path: &Path, text: &str) -> io::Result<()> {
555    let dir = path
556        .parent()
557        .ok_or_else(|| io::Error::other("note path has no directory"))?;
558    let name = path
559        .file_name()
560        .and_then(|n| n.to_str())
561        .ok_or_else(|| io::Error::other("note path has no file name"))?;
562    let temp = dir.join(format!(".{name}.{}.tmp", std::process::id()));
563    {
564        let mut file = fs::File::create(&temp)?;
565        file.write_all(text.as_bytes())?;
566        file.sync_all()?;
567    }
568    if let Err(error) = fs::rename(&temp, path) {
569        let _ = fs::remove_file(&temp);
570        return Err(error);
571    }
572    Ok(())
573}
574
575/// A key as it appears in a file name: lowercase ASCII letters and digits,
576/// other runs as one `_`; `None` without a letter or digit.
577pub fn note_key(key: &str) -> Option<String> {
578    let mut out = String::new();
579    let mut last_sep = true;
580    for ch in key.trim().chars() {
581        if ch.is_ascii_alphanumeric() {
582            out.push(ch.to_ascii_lowercase());
583            last_sep = false;
584        } else if !last_sep {
585            out.push('_');
586            last_sep = true;
587        }
588        if out.len() >= MAX_KEY_CHARS {
589            break;
590        }
591    }
592    let out = out.trim_matches('_').to_string();
593    (!out.is_empty()).then_some(out)
594}
595
596/// `text` on one line, at most [`MAX_DESCRIPTION_CHARS`].
597fn one_line(text: &str) -> String {
598    let line = text.split_whitespace().collect::<Vec<_>>().join(" ");
599    if line.chars().count() <= MAX_DESCRIPTION_CHARS {
600        return line;
601    }
602    let cut: String = line.chars().take(MAX_DESCRIPTION_CHARS - 1).collect();
603    format!("{}…", cut.trim_end())
604}
605
606struct ParsedNote {
607    kind: Option<NoteKind>,
608    name: Option<String>,
609    description: String,
610    category: Option<String>,
611    body: String,
612}
613
614/// A note's front matter and body; `None` without front matter.
615fn parse_note(text: &str) -> Option<ParsedNote> {
616    let text = text.strip_prefix('\u{feff}').unwrap_or(text);
617    let rest = text
618        .strip_prefix("---\n")
619        .or_else(|| text.strip_prefix("---\r\n"))?;
620    let end = rest.find("\n---")?;
621    let (header, after) = rest.split_at(end);
622    let body = after
623        .strip_prefix("\n---")
624        .unwrap_or("")
625        .trim_start_matches(['\r', '\n'])
626        .to_string();
627    let mut parsed = ParsedNote {
628        kind: None,
629        name: None,
630        description: String::new(),
631        category: None,
632        body,
633    };
634    for line in header.lines() {
635        let Some((field, value)) = line.split_once(':') else {
636            continue;
637        };
638        let value = value.trim().trim_matches('"').to_string();
639        match field.trim() {
640            "type" => parsed.kind = NoteKind::parse(&value),
641            "name" if !value.is_empty() => parsed.name = Some(value),
642            "description" => parsed.description = value,
643            "category" if !value.is_empty() => parsed.category = Some(value),
644            _ => {}
645        }
646    }
647    Some(parsed)
648}
649
650/// Every note file in `dir`, sorted by kind (unknown last) then name.
651fn read_entries(dir: &Path) -> Vec<NoteEntry> {
652    let Ok(read) = fs::read_dir(dir) else {
653        return Vec::new();
654    };
655    let mut entries = Vec::new();
656    for item in read.flatten() {
657        if entries.len() >= MAX_NOTES {
658            break;
659        }
660        let file = item.file_name().to_string_lossy().into_owned();
661        if file == INDEX_FILE || file.starts_with('.') || !file.ends_with(".md") {
662            continue;
663        }
664        let Ok(meta) = fs::symlink_metadata(item.path()) else {
665            continue;
666        };
667        if !meta.is_file() || meta.len() > MAX_READ_BYTES {
668            continue;
669        }
670        let Ok(text) = fs::read_to_string(item.path()) else {
671            continue;
672        };
673        let stem = file.trim_end_matches(".md").to_string();
674        let entry = match parse_note(&text) {
675            Some(parsed) => NoteEntry {
676                kind: parsed.kind,
677                name: parsed
678                    .name
679                    .map(|n| one_line(&n))
680                    .unwrap_or_else(|| stem.clone()),
681                file,
682                description: if parsed.description.is_empty() {
683                    one_line(parsed.body.lines().next().unwrap_or(""))
684                } else {
685                    one_line(&parsed.description)
686                },
687                category: parsed.category,
688            },
689            None => NoteEntry {
690                kind: None,
691                name: stem,
692                file,
693                description: one_line(text.lines().find(|l| !l.trim().is_empty()).unwrap_or("")),
694                category: None,
695            },
696        };
697        entries.push(entry);
698    }
699    entries.sort_by(|a, b| {
700        let rank = |entry: &NoteEntry| entry.kind.map(|k| k as usize).unwrap_or(usize::MAX);
701        rank(a).cmp(&rank(b)).then_with(|| a.name.cmp(&b.name))
702    });
703    entries
704}
705
706fn index_line(entry: &NoteEntry) -> String {
707    let kind = entry.kind.map(NoteKind::as_str).unwrap_or("note");
708    if entry.description.is_empty() {
709        format!("- {kind}: [{}]({})", entry.name, entry.file)
710    } else {
711        format!(
712            "- {kind}: [{}]({}) — {}",
713            entry.name, entry.file, entry.description
714        )
715    }
716}
717
718fn render_section(project: &ProjectRef, dir: &Path, entries: &[NoteEntry]) -> String {
719    let mut lines = Vec::with_capacity(entries.len());
720    for entry in entries {
721        lines.push(index_line(entry));
722    }
723    let list = lines.join("\n");
724    let total = list.chars().count();
725    let list = if total > MAX_INDEX_CHARS {
726        let mut cut = String::new();
727        for line in &lines {
728            if cut.chars().count() + line.chars().count() + 1 > MAX_INDEX_CHARS {
729                break;
730            }
731            cut.push_str(line);
732            cut.push('\n');
733        }
734        let shown = cut.chars().count();
735        format!(
736            "{}\n{}",
737            cut.trim_end(),
738            aidaemon_tools::text::truncation_notice_with_hint(
739                shown,
740                total,
741                "List the directory above to see every note.",
742            )
743        )
744    } else {
745        list
746    };
747    format!(
748        "## Project Memory ({name})\n\
749         Notes kept for this project from earlier work, apart from the owner's personal memory. \
750         Read a note's file before relying on its detail; the code is the truth when they differ. \
751         Save what later work in this project should know with remember_fact (scope \"project\").\n\
752         Directory: {dir}\n{list}",
753        name = one_line(&project.name),
754        dir = dir.display(),
755    )
756}
757
758/// One project's notes as a [`Recall`](aidaemon_policies::Recall) backend:
759/// its [`ProjectNotes::section`] as the note, for a memory system that
760/// renders no block of its own to put the section in (wrap it in
761/// [`MemoryInjection`](aidaemon_policies::MemoryInjection)).
762pub struct ProjectNotesRecall {
763    notes: Arc<ProjectNotes>,
764    project: ProjectRef,
765}
766
767impl ProjectNotesRecall {
768    pub fn new(notes: Arc<ProjectNotes>, project: ProjectRef) -> Self {
769        Self { notes, project }
770    }
771
772    async fn section(&self) -> Option<String> {
773        let (notes, project) = (self.notes.clone(), self.project.clone());
774        tokio::task::spawn_blocking(move || notes.section(&project))
775            .await
776            .ok()
777            .flatten()
778    }
779}
780
781/// Which project a conversation is placed in. Recall uses it to keep one
782/// project's conversation history (its episodes) to that project's turns,
783/// and out of other projects' and personal recall.
784#[async_trait::async_trait]
785pub trait SessionProjects: Send + Sync {
786    /// The project `session_id` is placed in; `None` when it is in none.
787    async fn project_of(&self, session_id: &str) -> Option<String>;
788}
789
790#[async_trait::async_trait]
791impl aidaemon_policies::Recall for ProjectNotesRecall {
792    async fn recall(&self, _session_id: &str, _query: &str, _limit: usize) -> Vec<String> {
793        self.section().await.into_iter().collect()
794    }
795
796    async fn render(&self, _session_id: &str, _query: &str, _limit: usize) -> Option<String> {
797        self.section().await
798    }
799}
800
801#[cfg(test)]
802mod tests {
803    use super::*;
804
805    fn project(id: &str) -> ProjectRef {
806        ProjectRef::new(id, "Acme Site", None).unwrap()
807    }
808
809    fn note(key: &str, body: &str) -> NoteWrite {
810        NoteWrite {
811            kind: NoteKind::Fact,
812            key: key.into(),
813            category: Some("technical".into()),
814            description: None,
815            body: body.into(),
816            source: NoteSource::Agent,
817        }
818    }
819
820    #[test]
821    fn routing_keeps_the_owner_personal() {
822        use MemoryScope::*;
823        // Without a project nothing changes.
824        assert_eq!(route("technical", Some(Project), false), Personal);
825        // Who the owner is never becomes a note.
826        assert_eq!(route("user", Some(Project), true), Personal);
827        assert_eq!(route("Family", None, true), Personal);
828        assert_eq!(route("preference", None, true), Personal);
829        assert_eq!(route("preference", Some(Project), true), Project);
830        assert_eq!(route("technical", None, true), Project);
831        assert_eq!(route("project", Some(Personal), true), Personal);
832        assert_eq!(kind_for_category("pitfall"), NoteKind::Pitfall);
833        assert_eq!(kind_for_category("error_solution"), NoteKind::Pitfall);
834        assert_eq!(kind_for_category("technical"), NoteKind::Fact);
835    }
836
837    #[test]
838    fn a_note_round_trips_and_is_indexed() {
839        let temp = tempfile::tempdir().unwrap();
840        let notes = ProjectNotes::new(temp.path());
841        let p = project("project-1");
842        assert_eq!(notes.section(&p), None);
843        let outcome = notes
844            .write(&p, &note("Test Command", "Tests run with `make test`."))
845            .unwrap();
846        assert_eq!(outcome, WriteOutcome::Created);
847        let dir = notes.dir(&p).unwrap();
848        let text = fs::read_to_string(dir.join("fact-test_command.md")).unwrap();
849        assert!(text.contains("name: test_command"));
850        assert!(text.contains("category: technical"));
851        assert!(text.ends_with("Tests run with `make test`.\n"));
852        let index = fs::read_to_string(dir.join(INDEX_FILE)).unwrap();
853        assert!(
854            index.contains("[test_command](fact-test_command.md) — Tests run with `make test`.")
855        );
856        let section = notes.section(&p).unwrap();
857        assert!(section.starts_with("## Project Memory (Acme Site)"));
858        assert!(section.contains("fact-test_command.md"));
859    }
860
861    #[test]
862    fn the_same_key_replaces_only_its_note() {
863        let temp = tempfile::tempdir().unwrap();
864        let notes = ProjectNotes::new(temp.path());
865        let p = project("project-1");
866        notes.write(&p, &note("test_command", "make test")).unwrap();
867        notes.write(&p, &note("test-runner", "make check")).unwrap();
868        assert_eq!(
869            notes.write(&p, &note("test_command", "make test")).unwrap(),
870            WriteOutcome::Unchanged
871        );
872        assert_eq!(
873            notes
874                .write(&p, &note("TEST command", "cargo test"))
875                .unwrap(),
876            WriteOutcome::Replaced
877        );
878        let entries = notes.entries(&p);
879        assert_eq!(entries.len(), 2);
880        assert!(
881            notes
882                .read(&p, NoteKind::Fact, "test_runner")
883                .unwrap()
884                .contains("make check")
885        );
886        assert!(
887            notes
888                .read(&p, NoteKind::Fact, "test_command")
889                .unwrap()
890                .contains("cargo test")
891        );
892    }
893
894    #[test]
895    fn projects_are_apart() {
896        let temp = tempfile::tempdir().unwrap();
897        let notes = ProjectNotes::new(temp.path());
898        notes
899            .write(&project("project-a"), &note("db", "Postgres 16"))
900            .unwrap();
901        assert!(notes.section(&project("project-b")).is_none());
902        assert_eq!(notes.entries(&project("project-a")).len(), 1);
903    }
904
905    #[test]
906    fn delete_removes_the_note_and_the_empty_index() {
907        let temp = tempfile::tempdir().unwrap();
908        let notes = ProjectNotes::new(temp.path());
909        let p = project("project-1");
910        notes.write(&p, &note("db", "Postgres 16")).unwrap();
911        assert!(!notes.delete(&p, None, "other").unwrap());
912        assert!(notes.delete(&p, None, "DB").unwrap());
913        assert!(notes.entries(&p).is_empty());
914        assert!(!notes.dir(&p).unwrap().join(INDEX_FILE).exists());
915        assert!(!notes.delete(&project("project-none"), None, "db").unwrap());
916    }
917
918    #[test]
919    fn hand_edited_and_malformed_notes_are_listed_and_kept() {
920        let temp = tempfile::tempdir().unwrap();
921        let notes = ProjectNotes::new(temp.path());
922        let p = project("project-1");
923        notes.write(&p, &note("db", "Postgres 16")).unwrap();
924        let dir = notes.dir(&p).unwrap();
925        fs::write(
926            dir.join("procedure-release.md"),
927            "---\nname: release\ndescription: How a release is cut\ntype: procedure\n---\nTag, then push.\n",
928        )
929        .unwrap();
930        fs::write(
931            dir.join("scratch.md"),
932            "Remember the staging host is slow.\n",
933        )
934        .unwrap();
935        fs::write(dir.join("notes.txt"), "not a note").unwrap();
936        notes.rebuild_index(&p).unwrap();
937        let entries = notes.entries(&p);
938        let names: Vec<_> = entries.iter().map(|e| e.name.as_str()).collect();
939        assert_eq!(names, ["db", "release", "scratch"]);
940        assert_eq!(entries[2].kind, None);
941        assert_eq!(entries[2].description, "Remember the staging host is slow.");
942        notes.write(&p, &note("db", "Postgres 17")).unwrap();
943        assert!(dir.join("scratch.md").exists());
944        let index = fs::read_to_string(dir.join(INDEX_FILE)).unwrap();
945        assert!(index.contains("note: [scratch](scratch.md)"));
946    }
947
948    #[test]
949    fn limits_and_bad_input_are_refused() {
950        let temp = tempfile::tempdir().unwrap();
951        let notes = ProjectNotes::new(temp.path());
952        let p = project("project-1");
953        assert!(matches!(
954            notes.write(&p, &note("!!!", "x")),
955            Err(NoteError::EmptyKey)
956        ));
957        assert!(matches!(
958            notes.write(&p, &note("k", "  ")),
959            Err(NoteError::EmptyBody)
960        ));
961        assert!(matches!(
962            notes.write(&p, &note("k", &"x".repeat(MAX_NOTE_BYTES + 1))),
963            Err(NoteError::TooLarge { .. })
964        ));
965        let bad = ProjectRef {
966            id: "../escape".into(),
967            name: "x".into(),
968            root: None,
969        };
970        assert!(matches!(
971            notes.write(&bad, &note("k", "v")),
972            Err(NoteError::InvalidProject)
973        ));
974        assert!(!temp.path().join("escape").exists());
975        let long = note_key(&"k".repeat(500)).unwrap();
976        assert_eq!(long.len(), MAX_KEY_CHARS);
977        assert_eq!(note_key("../../etc/passwd").unwrap(), "etc_passwd");
978    }
979
980    #[cfg(unix)]
981    #[test]
982    fn a_symlinked_note_or_directory_is_refused() {
983        let temp = tempfile::tempdir().unwrap();
984        let outside = tempfile::tempdir().unwrap();
985        let notes = ProjectNotes::new(temp.path());
986        let p = project("project-1");
987        notes.write(&p, &note("db", "Postgres")).unwrap();
988        let dir = notes.dir(&p).unwrap();
989        let target = outside.path().join("victim.md");
990        fs::write(&target, "keep").unwrap();
991        std::os::unix::fs::symlink(&target, dir.join("fact-victim.md")).unwrap();
992        assert!(matches!(
993            notes.write(&p, &note("victim", "overwrite")),
994            Err(NoteError::OutsideDirectory)
995        ));
996        assert_eq!(fs::read_to_string(&target).unwrap(), "keep");
997        // A project directory that is a symlink out of the root.
998        let q = project("project-2");
999        fs::create_dir_all(temp.path().join("project-2")).unwrap();
1000        std::os::unix::fs::symlink(outside.path(), temp.path().join("project-2").join("memory"))
1001            .unwrap();
1002        assert!(matches!(
1003            notes.write(&q, &note("x", "y")),
1004            Err(NoteError::OutsideDirectory)
1005        ));
1006        assert!(!outside.path().join("fact-x.md").exists());
1007    }
1008
1009    #[test]
1010    fn the_shown_index_is_bounded() {
1011        let temp = tempfile::tempdir().unwrap();
1012        let notes = ProjectNotes::new(temp.path());
1013        let p = project("project-1");
1014        for i in 0..120 {
1015            notes
1016                .write(&p, &note(&format!("fact_{i:03}"), &"detail ".repeat(20)))
1017                .unwrap();
1018        }
1019        let section = notes.section(&p).unwrap();
1020        let list_start = section.find("\n- ").unwrap();
1021        assert!(section[list_start..].chars().count() < MAX_INDEX_CHARS + 400);
1022        assert!(section.contains("fact_000"));
1023        assert!(!section.contains("fact_119"));
1024    }
1025
1026    #[test]
1027    fn concurrent_writes_keep_every_note() {
1028        let temp = tempfile::tempdir().unwrap();
1029        let notes = Arc::new(ProjectNotes::new(temp.path()));
1030        let p = project("project-1");
1031        let handles: Vec<_> = (0..16)
1032            .map(|i| {
1033                let notes = notes.clone();
1034                let p = p.clone();
1035                std::thread::spawn(move || {
1036                    notes.write(&p, &note(&format!("k{i}"), "v")).unwrap();
1037                })
1038            })
1039            .collect();
1040        for handle in handles {
1041            handle.join().unwrap();
1042        }
1043        assert_eq!(notes.entries(&p).len(), 16);
1044        let index = fs::read_to_string(notes.dir(&p).unwrap().join(INDEX_FILE)).unwrap();
1045        assert_eq!(index.matches("\n- ").count(), 16);
1046        let leftovers = fs::read_dir(notes.dir(&p).unwrap())
1047            .unwrap()
1048            .flatten()
1049            .filter(|e| e.file_name().to_string_lossy().ends_with(".tmp"))
1050            .count();
1051        assert_eq!(leftovers, 0);
1052    }
1053}