Skip to main content

kernel_apis/
memory_pointers.rs

1//! File-linked memory as pointers: when a cell writes a file (a checked `write()`/`edit()` or any other change the
2//! after-cell snapshot finds) that matches a typed record's `pathGlobs`, the lane's next cell result ends with one
3//! line per record, `[memory] <id> <type>: <situation>`, never the record's content: the model reads it with
4//! `memory.get(id)` when it wants it. At most [`MAX_POINTERS`] lines per cell; each record is pointed at once per
5//! session. The setting `memory.filePointers: false` turns this off.
6
7use crate::memory_records::{Glob, IndexEntry, RecordIndex};
8use host::file_hooks::{CellChanges, CellObserver, inside};
9use serde_json::{Map, Value};
10use std::collections::HashSet;
11use std::path::Path;
12use std::sync::{Arc, Mutex};
13
14/// Pointer lines per cell.
15pub const MAX_POINTERS: usize = 3;
16
17/// Whether the settings leave file pointers on (`memory.filePointers`, default true).
18pub fn file_pointers_enabled(settings: &Value) -> bool {
19    settings["memory"]["filePointers"] != false
20}
21
22/// A session's pointer observer, or `None` when the settings turn pointers off (what the composition root registers
23/// with the session's file hooks).
24pub fn session_pointers(
25    settings: &Value,
26    index: Arc<RecordIndex>,
27    filters: Map<String, Value>,
28) -> Option<Arc<dyn CellObserver>> {
29    file_pointers_enabled(settings).then(|| Arc::new(MemoryPointers::new(index, filters)) as Arc<dyn CellObserver>)
30}
31
32/// One pointer line.
33pub fn pointer_line(entry: &IndexEntry) -> String {
34    format!("[memory] {} {}: {}", entry.id, entry.typed.kind, entry.typed.situation)
35}
36
37/// The pointers of one session, over the shared record index.
38pub struct MemoryPointers {
39    index: Arc<RecordIndex>,
40    /// Scope → identity tags of the session: only its own, its project's and the machine's records apply.
41    filters: Map<String, Value>,
42    /// Records already pointed at in this session.
43    delivered: Mutex<HashSet<String>>,
44}
45
46impl MemoryPointers {
47    pub fn new(index: Arc<RecordIndex>, filters: Map<String, Value>) -> MemoryPointers {
48        MemoryPointers {
49            index,
50            filters,
51            delivered: Mutex::new(HashSet::new()),
52        }
53    }
54
55    /// The pointer lines for a cell that wrote `paths` (relative to the session directory, with `/`).
56    pub fn pointers_for(&self, paths: &[String]) -> Vec<String> {
57        if paths.is_empty() {
58            return Vec::new();
59        }
60        let Ok(entries) = self.index.entries() else {
61            return Vec::new();
62        };
63        let mut delivered = jsrt::sync::lock(&self.delivered);
64        let mut lines = Vec::new();
65        for entry in entries {
66            if lines.len() == MAX_POINTERS {
67                break;
68            }
69            if entry.typed.path_globs.is_empty() || delivered.contains(&entry.id) || !entry.visible(&self.filters) {
70                continue;
71            }
72            let globs: Vec<Glob> = entry
73                .typed
74                .path_globs
75                .iter()
76                .filter_map(|pattern| Glob::new(pattern).ok())
77                .collect();
78            if paths.iter().any(|path| globs.iter().any(|glob| glob.matches(path))) {
79                delivered.insert(entry.id.clone());
80                lines.push(pointer_line(&entry));
81            }
82        }
83        lines
84    }
85}
86
87impl CellObserver for MemoryPointers {
88    fn cell_changed(&self, changes: &CellChanges, cwd: &Path, _lane: &str) -> Vec<String> {
89        let paths: Vec<String> = changes
90            .files
91            .iter()
92            .chain(&changes.checked)
93            .filter_map(|path| inside(cwd, path))
94            .map(|relative| relative.replace('\\', "/"))
95            .collect();
96        self.pointers_for(&paths)
97    }
98}