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
//! MountManager: CRUD + detection for Mounts (RFC-025).
//!
//! Mirrors `ProjectManager`'s structure for consistency. Mounts are persisted
//! in the `mounts` SQLite table (same `memory.db`).
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::SystemTime;
use anyhow::Result;
use chrono::Utc;
use parking_lot::RwLock;
use oxios_memory::memory::sqlite::MemoryDatabase;
use super::mount_db;
use super::path_promotion;
use super::{DetectionResult, Mount, MountId, MountMeta, MountSource, detect_mounts};
use crate::event_bus::{EventBus, KernelEvent};
/// Errors from MountManager operations.
#[derive(thiserror::Error, Debug)]
pub enum MountManagerError {
/// Mount not found.
#[error("Mount not found: {0}")]
NotFound(MountId),
/// Mount name already taken.
#[error("Mount name already exists: {0}")]
DuplicateName(String),
/// Invalid operation.
#[error("Invalid operation: {0}")]
Invalid(String),
}
/// Manages Mounts: CRUD, lookup, and detection.
///
/// Mounts are persisted in the `mounts` SQLite table
/// (same `memory.db` as memories and the legacy `projects` table).
pub struct MountManager {
/// In-memory index of all Mounts (loaded at startup).
mounts: RwLock<HashMap<MountId, Mount>>,
/// Name → ID index for fast name lookup.
name_index: RwLock<HashMap<String, MountId>>,
/// RFC-025 Phase 5: roots the user has explicitly dismissed (Promo-3).
///
/// When an `AutoPromoted` Mount is removed, its canonicalized root paths
/// are recorded here (and in `mount_dismissals`) so the scanner never
/// re-creates a Mount the user has rejected. Canonicalized form is used
/// so that the comparison is path-stable across symlinks.
dismissed_roots: RwLock<HashSet<PathBuf>>,
/// SQLite database for persistence.
db: Arc<MemoryDatabase>,
/// Event bus for publishing Mount events.
event_bus: Option<EventBus>,
}
impl MountManager {
/// Create a new MountManager, loading existing Mounts from SQLite.
pub fn new(db: Arc<MemoryDatabase>, event_bus: Option<EventBus>) -> Result<Self> {
// Ensure the schema exists (idempotent).
mount_db::ensure_mount_schema(&db.conn())?;
let mut mounts = HashMap::new();
let mut name_index = HashMap::new();
for mount in mount_db::list_mounts(&db.conn())? {
name_index.insert(mount.name.clone(), mount.id);
mounts.insert(mount.id, mount);
}
// Promo-3: load dismissal tombstones so re-promoted mounts stay dead.
let dismissed_roots = mount_db::list_dismissed_roots(&db.conn())?
.into_iter()
.collect::<HashSet<_>>();
tracing::info!(
count = mounts.len(),
dismissed = dismissed_roots.len(),
"MountManager initialized"
);
Ok(Self {
mounts: RwLock::new(mounts),
name_index: RwLock::new(name_index),
dismissed_roots: RwLock::new(dismissed_roots),
db,
event_bus,
})
}
/// List all Mounts.
pub fn list_mounts(&self) -> Vec<Mount> {
self.mounts.read().values().cloned().collect()
}
/// Get a Mount by ID.
pub fn get_mount(&self, id: MountId) -> Option<Mount> {
self.mounts.read().get(&id).cloned()
}
/// Get a Mount by name.
pub fn get_mount_by_name(&self, name: &str) -> Option<Mount> {
let name_index = self.name_index.read();
let id = name_index.get(name)?;
self.mounts.read().get(id).cloned()
}
/// Get several Mounts by ID, preserving the request order. Missing IDs
/// are skipped (they may have been deleted).
pub fn get_mounts_ordered(&self, ids: &[MountId]) -> Vec<Mount> {
let mounts = self.mounts.read();
ids.iter()
.filter_map(|id| mounts.get(id).cloned())
.collect()
}
/// Create a new Mount with the minimal RFC-025 input (name + paths).
pub fn create_mount(
&self,
name: String,
paths: Vec<PathBuf>,
source: MountSource,
) -> Result<Mount> {
let name = validate_mount_name(&name)?;
if paths.is_empty() {
return Err(MountManagerError::Invalid(
"a Mount requires at least one path".to_string(),
)
.into());
}
// Reject overly broad system paths (lightweight safety, not a sandbox).
for p in &paths {
validate_mount_path(p)?;
}
let mut mount = Mount::new(&name, source);
mount.paths = paths;
// Hold the write locks across the uniqueness check, the DB write, and
// the in-memory insert. The previous version used a *read* lock for the
// name check and a *separate* write lock for the insert, leaving a
// TOCTOU window in which two concurrent `create_mount` calls with the
// same name both passed the check. Acquiring both locks in the
// consistent order used throughout the manager (mounts → name_index)
// closes the window entirely.
let mut mounts = self.mounts.write();
let mut name_index = self.name_index.write();
if name_index.contains_key(&name) {
return Err(MountManagerError::DuplicateName(name).into());
}
mount_db::save_mount(&self.db.conn(), &mount)?;
name_index.insert(mount.name.clone(), mount.id);
mounts.insert(mount.id, mount.clone());
drop(name_index);
drop(mounts);
if let Some(ref event_bus) = self.event_bus {
let _ = event_bus.publish(KernelEvent::ProjectCreated {
// Reuse ProjectCreated for now; a MountCreated variant can be
// added when the frontend needs to distinguish them.
project_id: mount.id,
name: mount.name.clone(),
source: source.to_string(),
});
}
tracing::info!(name = %mount.name, id = %mount.id, "Mount created");
Ok(mount)
}
/// Update a Mount's auto-enriched fields (agent-driven, RFC-025 Phase 3).
///
/// Only `auto_description` and `auto_meta` are writable here — `name` and
/// `paths` are user-level and go through [`Self::rename`] / the web API.
pub fn update_enrichment(
&self,
id: MountId,
auto_description: Option<String>,
auto_meta: Option<MountMeta>,
) -> Result<Mount> {
let mut mounts = self.mounts.write();
let mount = mounts.get_mut(&id).ok_or(MountManagerError::NotFound(id))?;
if let Some(desc) = auto_description {
// Bounded per RFC-025 cost guard (≤ 500 chars).
mount.auto_description = desc.chars().take(500).collect();
}
if let Some(meta) = auto_meta {
mount.auto_meta = meta;
}
mount.last_enriched_at = Some(Utc::now());
mount.enrichment_pending = false;
mount.updated_at = Utc::now();
let mount_clone = mount.clone();
drop(mounts);
mount_db::save_mount(&self.db.conn(), &mount_clone)?;
tracing::info!(name = %mount_clone.name, id = %id, "Mount enriched");
Ok(mount_clone)
}
/// Rename a Mount.
pub fn rename(&self, id: MountId, new_name: String) -> Result<Mount> {
let new_name = validate_mount_name(&new_name)?;
let mut mounts = self.mounts.write();
let mut name_index = self.name_index.write();
let mount = mounts.get_mut(&id).ok_or(MountManagerError::NotFound(id))?;
if new_name != mount.name {
if name_index.contains_key(&new_name) {
return Err(MountManagerError::DuplicateName(new_name).into());
}
name_index.remove(&mount.name);
name_index.insert(new_name.clone(), id);
mount.name = new_name;
mount.updated_at = Utc::now();
}
let mount_clone = mount.clone();
drop(mounts);
drop(name_index);
mount_db::save_mount(&self.db.conn(), &mount_clone)?;
Ok(mount_clone)
}
/// Remove a Mount.
///
/// DB-first ordering (matches `create_mount`): if the DB delete fails the
/// in-memory state is left untouched so the caller can retry and the Mount
/// doesn't silently reappear on restart.
///
/// If the Mount was `AutoPromoted`, its canonicalized root paths are
/// recorded as dismissals (tombstones) so the background scanner does
/// not immediately re-promote them (Promo-3). Manual mounts are removed
/// without recording a tombstone (the user may still want auto-promotion
/// for that root).
pub fn remove_mount(&self, id: MountId) -> Result<()> {
// Preserve NotFound semantics + capture the Mount for tombstoning.
let removed = {
let mounts = self.mounts.read();
mounts
.get(&id)
.cloned()
.ok_or(MountManagerError::NotFound(id))?
};
// Delete from the DB before touching memory.
mount_db::delete_mount(&self.db.conn(), &id.to_string())?;
{
let mut mounts = self.mounts.write();
let mut name_index = self.name_index.write();
if let Some(mount) = mounts.remove(&id) {
name_index.remove(&mount.name);
}
}
// Promo-3: tombstone auto-promoted roots so they aren't re-created.
if removed.source == MountSource::AutoPromoted {
self.record_dismissal(&removed.paths);
}
tracing::info!(id = %id, "Mount removed");
Ok(())
}
/// Canonicalize each path and record it as a dismissed root, both
/// in-memory and in SQLite (Promo-3). Best-effort: paths that fail to
/// canonicalize are stored in their raw form so the tombstone still
/// matches the exact string the scanner would normalize to.
fn record_dismissal(&self, paths: &[PathBuf]) {
let to_record: Vec<PathBuf> = paths
.iter()
.map(|p| Self::canonicalize_for_index(p))
.collect();
{
let mut dismissed = self.dismissed_roots.write();
for p in &to_record {
dismissed.insert(p.clone());
}
}
for p in &to_record {
if let Err(e) = mount_db::add_dismissed_root(&self.db.conn(), p) {
tracing::warn!(
path = %p.display(),
error = %e,
"failed to persist mount dismissal"
);
}
}
tracing::debug!(count = to_record.len(), "recorded mount dismissals");
}
/// Canonicalize a path for index comparison, falling back to the raw
/// path when canonicalization fails (e.g. the path was removed).
fn canonicalize_for_index(path: &Path) -> PathBuf {
std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
}
/// RFC-025 Phase 5: is `root` in the dismissed set (Promo-3)?
///
/// Compares against both the canonicalized and raw forms of stored
/// tombstones so that a root matches regardless of symlink resolution.
fn is_dismissed(&self, root: &Path) -> bool {
let dismissed = self.dismissed_roots.read();
if dismissed.contains(root) {
return true;
}
let canonical = Self::canonicalize_for_index(root);
dismissed.contains(&canonical)
}
/// Record that a Mount was used in a session.
pub fn touch(&self, id: MountId) {
let to_save = {
let mut mounts = self.mounts.write();
if let Some(mount) = mounts.get_mut(&id) {
mount.touch();
Some(mount.clone())
} else {
None
}
};
if let Some(mount) = to_save
&& let Err(e) = mount_db::save_mount(&self.db.conn(), &mount)
{
tracing::warn!(id = %id, error = %e, "touch: failed to save Mount");
}
}
/// Try to detect a Mount from a user message.
pub fn detect(&self, message: &str) -> DetectionResult {
let mounts = self.list_mounts();
detect_mounts(message, &mounts)
}
/// Seed `auto_meta` from the filesystem (RFC-025 §Auto-Meta).
///
/// Cheap heuristic detection on marker files. The agent refines this
/// during enrichment. Idempotent — safe to call multiple times.
pub fn seed_auto_meta(&self, id: MountId) -> Result<()> {
let mount = {
let mounts = self.mounts.read();
mounts
.get(&id)
.ok_or(MountManagerError::NotFound(id))?
.clone()
};
let Some(primary) = mount.primary_path().cloned() else {
return Ok(()); // nothing to scan
};
if !primary.exists() {
tracing::debug!(path = %primary.display(), "Mount path missing, skip meta seed");
return Ok(());
}
// detect_meta is cheap heuristics only — it must NOT clear the
// enrichment nudge. Route it directly (not through update_enrichment,
// which would stamp `last_enriched_at` and clear `enrichment_pending`),
// so the agent is still prompted to do real enrichment.
let meta = super::meta_detection::detect_meta(&primary);
let to_save = {
let mut mounts = self.mounts.write();
let Some(mount) = mounts.get_mut(&id) else {
return Ok(()); // removed while detecting
};
mount.auto_meta = meta;
mount.enrichment_pending = true;
mount.last_enriched_at = None;
mount.updated_at = Utc::now();
mount.clone()
};
if let Err(e) = mount_db::save_mount(&self.db.conn(), &to_save) {
tracing::warn!(id = %id, error = %e, "seed_auto_meta: failed to save Mount");
}
tracing::info!(name = %to_save.name, id = %id, "Mount auto_meta seeded");
Ok(())
}
/// Check marker-file drift and set `enrichment_pending` (RFC-025 §Enrichment).
///
/// Compares current marker mtimes against the stored snapshot. Returns
/// `true` if any marker drifted (and the flag was set). Cheap: a handful
/// of `stat()` calls.
pub fn check_drift(&self, id: MountId) -> Result<bool> {
// Acquire a read lock only to clone the primary path and the current
// snapshot, then drop it so the filesystem I/O (snapshot_markers) runs
// lock-free (M8: don't do I/O under the write lock).
let (primary, old_snapshot) = {
let mounts = self.mounts.read();
let mount = mounts.get(&id).ok_or(MountManagerError::NotFound(id))?;
let Some(primary) = mount.primary_path().cloned() else {
return Ok(false);
};
(primary, mount.last_marker_snapshot.clone())
};
// Filesystem I/O — no lock held.
let current = super::meta_detection::snapshot_markers(&primary);
let drifted = markers_drifted(&old_snapshot, ¤t);
let current_map: HashMap<PathBuf, SystemTime> = current.into_iter().collect();
// Re-acquire a write lock to apply results (re-checking the Mount
// still exists — it may have been removed while we read the fs).
let to_save = {
let mut mounts = self.mounts.write();
let Some(mount) = mounts.get_mut(&id) else {
return Ok(drifted);
};
// Skip the mutation + DB write when nothing drifted and the
// snapshot is unchanged (m4: don't write on every drift check).
if !drifted && mount.last_marker_snapshot == current_map {
None
} else {
if drifted {
mount.enrichment_pending = true;
mount.updated_at = Utc::now();
}
// Refresh the snapshot so the next comparison is accurate.
mount.last_marker_snapshot = current_map;
Some(mount.clone())
}
};
if let Some(mount) = to_save
&& let Err(e) = mount_db::save_mount(&self.db.conn(), &mount)
{
tracing::warn!(id = %id, error = %e, "check_drift: failed to save Mount");
}
Ok(drifted)
}
/// Check drift for all Mounts (Dream-time refresh, RFC-025).
///
/// Returns the IDs of Mounts whose content drifted.
pub fn check_all_drift(&self) -> Vec<MountId> {
let ids: Vec<MountId> = self.mounts.read().keys().copied().collect();
let mut drifted = Vec::new();
for id in ids {
match self.check_drift(id) {
Ok(true) => drifted.push(id),
Ok(false) => {}
Err(e) => tracing::warn!(error = %e, %id, "check_drift failed for mount"),
}
}
drifted
}
/// RFC-025 Phase 5: scan session history and auto-create Mounts for paths
/// that cross the frequency threshold.
///
/// Returns the IDs of newly-created Mounts (empty if none promoted). Safe
/// to call repeatedly — paths already covered by an existing Mount are
/// skipped, as are name collisions.
pub fn promote_frequent_paths(
&self,
sessions: &[crate::state_store::Session],
config: &path_promotion::PromotionConfig,
) -> Vec<MountId> {
if !config.enabled {
return Vec::new();
}
let freqs = path_promotion::tally_frequencies(sessions, config);
// Sort deterministically: most frequent first, then alphabetically by
// path. This guarantees that when two roots derive the same name the
// most-used one wins consistently across runs (HashMap iteration order
// is otherwise non-deterministic).
let mut sorted_freqs: Vec<_> = freqs.into_iter().collect();
sorted_freqs.sort_by(|a, b| b.1.count.cmp(&a.1.count).then_with(|| a.0.cmp(&b.0)));
let mut created = Vec::new();
for (root, freq) in sorted_freqs {
if freq.count < config.threshold {
continue;
}
// Skip if any existing Mount already covers this root.
if self.root_already_covered(&root) {
continue;
}
// Promo-3: skip roots the user has explicitly dismissed, so a
// deleted AutoPromoted Mount is not immediately re-created.
if self.is_dismissed(&root) {
tracing::debug!(
path = %root.display(),
"auto-promotion skipped: root was dismissed"
);
continue;
}
// Derive a name from the final path component.
let Some(name) = root
.file_name()
.and_then(|n| n.to_str())
.map(|s| s.to_string())
else {
continue;
};
// Skip if the name is already taken (collision → leave for the
// user to resolve, rather than inventing "name-2").
if self.get_mount_by_name(&name).is_some() {
continue;
}
match self.create_mount(
name.clone(),
vec![root.clone()],
super::MountSource::AutoPromoted,
) {
Ok(mount) => {
tracing::info!(
name = %mount.name,
path = %root.display(),
count = freq.count,
"RFC-025: auto-promoted frequent path to Mount"
);
// Seed auto_meta immediately so the new Mount is useful.
let _ = self.seed_auto_meta(mount.id);
created.push(mount.id);
}
Err(e) => {
tracing::debug!(
path = %root.display(),
error = %e,
"auto-promotion skipped"
);
}
}
}
created
}
/// Returns `true` if some existing Mount's `paths` already includes (or is
/// an ancestor of) `root`, meaning the root is already covered.
fn root_already_covered(&self, root: &PathBuf) -> bool {
let mounts = self.mounts.read();
mounts.values().any(|m| {
m.paths
.iter()
.any(|p| root.starts_with(p) || p.starts_with(root))
})
}
}
/// Compare a stored marker snapshot against the current state.
/// Returns `true` if any marker was added, removed, or changed mtime.
fn markers_drifted(
stored: &HashMap<PathBuf, SystemTime>,
current: &[(std::path::PathBuf, SystemTime)],
) -> bool {
if stored.len() != current.len() {
return true; // marker added or removed
}
for (path, mtime) in current {
match stored.get(path) {
Some(stored_time) if stored_time == mtime => continue,
_ => return true, // new, removed, or changed
}
}
false
}
/// Validate a Mount name (RFC-025): non-empty after trim, ≤ 64 chars (by char
/// count), no control characters. Returns the trimmed name on success.
fn validate_mount_name(name: &str) -> Result<String> {
let trimmed = name.trim();
if trimmed.is_empty() {
return Err(MountManagerError::Invalid("Mount name must not be empty".to_string()).into());
}
if trimmed.chars().count() > 64 {
return Err(MountManagerError::Invalid(
"Mount name must be at most 64 characters".to_string(),
)
.into());
}
if trimmed.chars().any(|c| c.is_control()) {
return Err(MountManagerError::Invalid(
"Mount name must not contain control characters".to_string(),
)
.into());
}
Ok(trimmed.to_string())
}
/// Reject paths that are too broad to be a meaningful project root.
///
/// This is a lightweight safety check, not a full sandbox — AccessManager
/// RBAC enforcement is the real boundary. We only reject the filesystem root
/// and a few system directories that would make detection hijack every path.
fn validate_mount_path(path: &Path) -> Result<()> {
let forbidden = [
"", "/etc", "/dev", "/proc", "/sys", "/var", "/usr", "/bin", "/sbin", "/boot",
];
let normalized = path.to_str().map(|s| s.trim_end_matches('/')).unwrap_or("");
if forbidden.contains(&normalized) {
return Err(MountManagerError::Invalid(format!(
"Mount path '{}' is a system directory; refusing to create an overly broad Mount",
path.display()
))
.into());
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
fn open_manager() -> MountManager {
let db = Arc::new(MemoryDatabase::open_in_memory(64).expect("db"));
MountManager::new(db, None).expect("manager")
}
#[test]
fn test_create_and_get() {
let mgr = open_manager();
let m = mgr
.create_mount(
"oxios".to_string(),
vec![PathBuf::from("/Volumes/MERCURY/PROJECTS/oxios")],
MountSource::Manual,
)
.expect("create");
assert_eq!(mgr.get_mount(m.id).unwrap().name, "oxios");
assert_eq!(mgr.get_mount_by_name("oxios").unwrap().id, m.id);
}
#[test]
fn test_duplicate_name_rejected() {
let mgr = open_manager();
mgr.create_mount(
"oxios".to_string(),
vec![PathBuf::from("/a")],
MountSource::Manual,
)
.expect("first");
let err = mgr
.create_mount(
"oxios".to_string(),
vec![PathBuf::from("/b")],
MountSource::Manual,
)
.unwrap_err();
assert!(err.to_string().contains("already exists"));
}
#[test]
fn test_empty_paths_rejected() {
let mgr = open_manager();
let err = mgr
.create_mount("x".to_string(), vec![], MountSource::Manual)
.unwrap_err();
assert!(err.to_string().contains("at least one path"));
}
#[test]
fn test_system_directory_path_rejected() {
let mgr = open_manager();
for bad in ["/", "/etc", "/dev", "/proc", "/usr"] {
let err = mgr
.create_mount(
"bad".to_string(),
vec![PathBuf::from(bad)],
MountSource::Manual,
)
.unwrap_err();
assert!(
err.to_string().contains("system directory"),
"expected system directory rejection for {bad}"
);
}
}
#[test]
fn test_update_enrichment_bounds_description() {
let mgr = open_manager();
let m = mgr
.create_mount(
"oxios".to_string(),
vec![PathBuf::from("/a")],
MountSource::Manual,
)
.expect("create");
let long = "x".repeat(800);
let updated = mgr
.update_enrichment(m.id, Some(long.clone()), None)
.expect("update");
assert_eq!(updated.auto_description.chars().count(), 500);
assert!(updated.last_enriched_at.is_some());
assert!(!updated.enrichment_pending);
}
#[test]
fn test_remove_mount() {
let mgr = open_manager();
let m = mgr
.create_mount(
"temp".to_string(),
vec![PathBuf::from("/t")],
MountSource::Manual,
)
.expect("create");
mgr.remove_mount(m.id).expect("remove");
assert!(mgr.get_mount(m.id).is_none());
assert!(mgr.get_mount_by_name("temp").is_none());
}
#[test]
fn test_get_mounts_ordered_skips_missing() {
let mgr = open_manager();
let m1 = mgr
.create_mount(
"a".to_string(),
vec![PathBuf::from("/a")],
MountSource::Manual,
)
.unwrap();
let m2 = mgr
.create_mount(
"b".to_string(),
vec![PathBuf::from("/b")],
MountSource::Manual,
)
.unwrap();
let missing = MountId::new_v4();
let got = mgr.get_mounts_ordered(&[m1.id, missing, m2.id]);
assert_eq!(got.len(), 2);
assert_eq!(got[0].name, "a");
assert_eq!(got[1].name, "b");
}
#[test]
fn test_promote_frequent_paths_creates_mount() {
use crate::state_store::{Session, UserMessage};
use chrono::Utc;
let mgr = open_manager();
// Use this crate's own source dir — it has Cargo.toml at its root,
// so normalize_to_root will collapse to the oxios-kernel root.
let root = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let file = root.join("src/lib.rs");
// Frequency is counted per distinct root per session (Promo-7): one
// session's repeated mentions count once. So we need three separate
// sessions to cross the default threshold of 3.
let sessions: Vec<Session> = (0..3)
.map(|_| {
let mut session = Session::new("test");
session.user_messages.push(UserMessage {
content: format!("fix {} please", file.display()),
timestamp: Utc::now(),
});
session
})
.collect();
let config = path_promotion::PromotionConfig::default();
let created = mgr.promote_frequent_paths(&sessions, &config);
assert_eq!(created.len(), 1, "expected exactly one promoted Mount");
let mount = mgr.get_mount(created[0]).expect("promoted mount exists");
assert_eq!(mount.source, MountSource::AutoPromoted);
assert_eq!(mount.name, "oxios-kernel");
// auto_meta should be seeded (Cargo.toml → rust).
assert!(mount.auto_meta.languages.contains(&"rust".to_string()));
}
/// Build `n` sessions each mentioning `root` once (Promo-7: frequency is
/// per distinct root per session, so we vary the *session* count, not
/// the message count within one session).
fn sessions_mentioning(root: &PathBuf, n: u32) -> Vec<crate::state_store::Session> {
use crate::state_store::{Session, UserMessage};
use chrono::Utc;
(0..n)
.map(|_| {
let mut s = Session::new("test");
s.user_messages.push(UserMessage {
content: format!("work on {}/src/lib.rs", root.display()),
timestamp: Utc::now(),
});
s
})
.collect()
}
#[test]
fn test_promote_skips_already_covered_root() {
let mgr = open_manager();
let root = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
// Pre-create a Mount covering this root.
mgr.create_mount(
"manual-kernel".to_string(),
vec![root.clone()],
MountSource::Manual,
)
.unwrap();
// Promo-7: 3 separate sessions (count=3) cross the default threshold,
// so this exercises the coverage-skip path rather than trivially
// passing because the count is below threshold.
let sessions = sessions_mentioning(&root, 3);
let config = path_promotion::PromotionConfig::default();
let created = mgr.promote_frequent_paths(&sessions, &config);
assert!(
created.is_empty(),
"should not promote an already-covered root"
);
}
#[test]
fn test_promote_respects_threshold() {
let mgr = open_manager();
let root = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
// Promo-7: 2 sessions → count=2, below the default threshold of 3.
let sessions = sessions_mentioning(&root, 2);
let config = path_promotion::PromotionConfig::default();
let created = mgr.promote_frequent_paths(&sessions, &config);
assert!(created.is_empty(), "should not promote below threshold");
}
#[test]
fn test_promote_skips_dismissed_root() {
// Promo-3: removing an AutoPromoted Mount must tombstone its root so
// the scanner never re-creates it.
let mgr = open_manager();
let root = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let sessions = sessions_mentioning(&root, 3);
let config = path_promotion::PromotionConfig::default();
// First scan: promotes the root to an AutoPromoted Mount.
let created = mgr.promote_frequent_paths(&sessions, &config);
assert_eq!(created.len(), 1, "expected exactly one promoted Mount");
let promoted_id = created[0];
assert_eq!(
mgr.get_mount(promoted_id).unwrap().source,
MountSource::AutoPromoted
);
// User dismisses it.
mgr.remove_mount(promoted_id).expect("remove");
assert!(mgr.get_mount(promoted_id).is_none());
// Second scan with the same evidence must NOT re-create it.
let recreated = mgr.promote_frequent_paths(&sessions, &config);
assert!(
recreated.is_empty(),
"dismissed root must not be re-promoted (got {:?})",
recreated
);
}
#[test]
fn test_dismissal_only_for_auto_promoted() {
// Promo-3: dismissing a *Manual* Mount must not tombstone the root,
// since the user may still want auto-promotion for it later.
let mgr = open_manager();
let root = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
// Manual mount.
let m = mgr
.create_mount(
"manual-kernel".to_string(),
vec![root.clone()],
MountSource::Manual,
)
.unwrap();
mgr.remove_mount(m.id).expect("remove manual");
// Dismissed set should be empty — no tombstone for manual mounts.
assert!(
mgr.dismissed_roots.read().is_empty(),
"manual removal must not tombstone"
);
// Subsequent promotion is still possible. Promo-7: 3 sessions.
let sessions = sessions_mentioning(&root, 3);
let config = path_promotion::PromotionConfig::default();
let created = mgr.promote_frequent_paths(&sessions, &config);
assert_eq!(
created.len(),
1,
"promotion must still work after manual removal"
);
}
}