Skip to main content

surjection_core/apply/
unmanaged.rs

1//! Unmanaged entries (#3, #9): the foreign MCP entries an import scan finds
2//! ([`crate::apply::import::scan_with`]), as findings per client and scope
3//! for the read-only "not managed by Surjection" views and counts, and which
4//! of them this machine has not acknowledged yet (the "new unmanaged
5//! entries" notice).
6//!
7//! [`scan_findings`] lists the same findings as [`findings`] of a full
8//! scan, by name only: no entry is converted to store fields, no preview or
9//! secret extraction is made, and each client file is parsed once. The
10//! notice runs it on focus and file-watcher events.
11//!
12//! Acknowledged findings are a machine-local fact (`state/unmanaged-seen.json`,
13//! never synced): they name client files of this machine. A finding is
14//! identified by [`Source::key`] and the entry name (`claude-code/github`,
15//! `cursor@app-1a2b/postgres`), never by a path, so the id can cross IPC.
16
17use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
18use std::path::{Path, PathBuf};
19
20use serde::{Deserialize, Serialize};
21
22use crate::apply::ApplyEnv;
23use crate::apply::import::{self, Candidate, ScanFilter, Source, source_key};
24use crate::apply::ledger::Ledger;
25use crate::apply::render::DesiredState;
26use crate::apply::write_atomic;
27use crate::error::{CoreError, ErrorCode};
28use crate::fs::Fs;
29use crate::model::applied::Scope;
30use crate::store::Store;
31
32/// The file in `state/`.
33pub const SEEN_FILE: &str = "unmanaged-seen.json";
34pub(crate) const SEEN_SCHEMA: u32 = 1;
35
36/// One foreign entry in one client file.
37#[derive(Debug, Clone, PartialEq, Eq)]
38pub struct Finding {
39    /// `<source key>/<name>` ([`finding_id`]).
40    pub id: String,
41    pub client: &'static str,
42    pub scope: Scope,
43    pub project_id: Option<String>,
44    /// The project's folder, for placeholder paths.
45    pub project_root: Option<PathBuf>,
46    pub name: String,
47    pub file: PathBuf,
48}
49
50/// The id of entry `name` of `source`: `<source key>/<name>`.
51pub fn finding_id(source: &Source, name: &str) -> String {
52    format!("{}/{name}", source.key())
53}
54
55/// One finding per source of each candidate, in scan order.
56pub fn findings(candidates: &[Candidate]) -> Vec<Finding> {
57    let mut out = Vec::new();
58    for candidate in candidates {
59        for source in &candidate.sources {
60            out.push(Finding {
61                id: finding_id(source, &candidate.name),
62                client: source.client,
63                scope: source.scope,
64                project_id: source.project.as_ref().map(|p| p.id.clone()),
65                project_root: source.project.as_ref().map(|p| p.root.clone()),
66                name: candidate.name.clone(),
67                file: source.file.clone(),
68            });
69        }
70    }
71    out
72}
73
74/// The findings [`findings`] gives for a [`import::scan_with`] of the same
75/// files, in the same order, by name only (see the module docs).
76pub fn scan_findings(
77    ax: &ApplyEnv<'_>,
78    desired: &DesiredState,
79    ledger: &Ledger,
80    filter: &ScanFilter,
81) -> Result<(Vec<Finding>, Vec<CoreError>), CoreError> {
82    // Grouped by name in first-seen order, as the scan's candidates are.
83    let mut by_name: Vec<Vec<Finding>> = Vec::new();
84    let mut index: HashMap<String, usize> = HashMap::new();
85    let mut ids: HashSet<String> = HashSet::new();
86    let mut warnings = Vec::new();
87    import::walk(ax, desired, ledger, filter, &mut warnings, &mut |found| {
88        let project_id = found.project.map(|project| project.id.as_str());
89        let key = source_key(
90            found.spec.id,
91            found.slot.as_deref(),
92            found.target.scope,
93            project_id,
94        );
95        let id = format!("{key}/{}", found.name);
96        if !ids.insert(id.clone()) {
97            return Ok(());
98        }
99        let finding = Finding {
100            id,
101            client: found.spec.id,
102            scope: found.target.scope,
103            project_id: project_id.map(str::to_owned),
104            project_root: found.project.map(|project| project.root.clone()),
105            name: found.name,
106            file: found.target.file.clone(),
107        };
108        match index.get(&finding.name) {
109            Some(&at) => by_name[at].push(finding),
110            None => {
111                index.insert(finding.name.clone(), by_name.len());
112                by_name.push(vec![finding]);
113            }
114        }
115        Ok(())
116    })?;
117    Ok((by_name.into_iter().flatten().collect(), warnings))
118}
119
120/// [`scan_findings`] against `store` as this machine sees it
121/// ([`import::store_inputs`]). Read-only: creates nothing.
122pub fn store_findings(
123    store: Option<&Store<'_>>,
124    ax: &ApplyEnv<'_>,
125    filter: &ScanFilter,
126) -> Result<(Vec<Finding>, Vec<CoreError>), CoreError> {
127    let (desired, ledger) = import::store_inputs(store, ax)?;
128    scan_findings(ax, &desired, &ledger, filter)
129}
130
131/// The findings of one client in one scope (one project).
132#[derive(Debug, Clone, PartialEq, Eq)]
133pub struct Group {
134    pub client: &'static str,
135    pub scope: Scope,
136    pub project_id: Option<String>,
137    pub project_root: Option<PathBuf>,
138    /// The files they were found in, in first-seen order.
139    pub files: Vec<PathBuf>,
140    /// `(finding, new)`: `new` when this machine has not acknowledged it.
141    pub entries: Vec<(Finding, bool)>,
142}
143
144/// `findings` per client and scope (and project), each marked new unless
145/// `seen` holds it. Groups are ordered by client, scope and project; their
146/// entries by name.
147pub fn groups(findings: Vec<Finding>, seen: &Seen) -> Vec<Group> {
148    type Key = (&'static str, u8, Option<String>);
149    let rank = |scope: Scope| match scope {
150        Scope::User => 0,
151        Scope::Project => 1,
152        Scope::ProjectLocal => 2,
153    };
154    let mut map: BTreeMap<Key, Group> = BTreeMap::new();
155    for finding in findings {
156        let key = (
157            finding.client,
158            rank(finding.scope),
159            finding.project_id.clone(),
160        );
161        let group = map.entry(key).or_insert_with(|| Group {
162            client: finding.client,
163            scope: finding.scope,
164            project_id: finding.project_id.clone(),
165            project_root: finding.project_root.clone(),
166            files: Vec::new(),
167            entries: Vec::new(),
168        });
169        if !group.files.contains(&finding.file) {
170            group.files.push(finding.file.clone());
171        }
172        let new = !seen.contains(&finding.id);
173        group.entries.push((finding, new));
174    }
175    let mut groups: Vec<Group> = map.into_values().collect();
176    for group in &mut groups {
177        group.entries.sort_by(|a, b| a.0.name.cmp(&b.0.name));
178    }
179    groups
180}
181
182/// The findings this machine acknowledged (`state/unmanaged-seen.json`).
183#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
184pub struct Seen {
185    schema: u32,
186    #[serde(default)]
187    ids: BTreeSet<String>,
188}
189
190impl Seen {
191    /// The acknowledged findings; none when the file is absent.
192    pub fn load(fs: &dyn Fs, state_dir: &Path) -> Result<Self, CoreError> {
193        let path = state_dir.join(SEEN_FILE);
194        if !fs.exists(&path) {
195            return Ok(Self {
196                schema: SEEN_SCHEMA,
197                ids: BTreeSet::new(),
198            });
199        }
200        let text = fs.read_to_string(&path).map_err(|err| {
201            CoreError::new(ErrorCode::IoError, format!("cannot read file: {err}")).with_path(&path)
202        })?;
203        let seen: Self = serde_json::from_str(&text).map_err(|err| {
204            CoreError::new(
205                ErrorCode::ParseError,
206                format!("the file does not parse: {err}"),
207            )
208            .with_path(&path)
209        })?;
210        if seen.schema != SEEN_SCHEMA {
211            return Err(CoreError::new(
212                ErrorCode::UnsupportedSchema,
213                format!("schema {} is not read by this build", seen.schema),
214            )
215            .with_path(&path));
216        }
217        Ok(seen)
218    }
219
220    pub fn contains(&self, id: &str) -> bool {
221        self.ids.contains(id)
222    }
223
224    /// Acknowledges `ids` and writes the file when that changed anything.
225    /// Returns how many were new.
226    pub fn acknowledge(
227        &mut self,
228        fs: &dyn Fs,
229        state_dir: &Path,
230        ids: &[String],
231    ) -> Result<usize, CoreError> {
232        let added = ids
233            .iter()
234            .filter(|id| self.ids.insert((*id).clone()))
235            .count();
236        if added == 0 {
237            return Ok(0);
238        }
239        self.schema = SEEN_SCHEMA;
240        let mut text = serde_json::to_string_pretty(self).map_err(|err| {
241            CoreError::new(ErrorCode::InvalidValue, format!("cannot serialize: {err}"))
242        })?;
243        text.push('\n');
244        fs.create_dir_all(state_dir).map_err(|err| {
245            CoreError::new(
246                ErrorCode::IoError,
247                format!("cannot create directory: {err}"),
248            )
249            .with_path(state_dir)
250        })?;
251        write_atomic(fs, &state_dir.join(SEEN_FILE), text.as_bytes())?;
252        Ok(added)
253    }
254}