seyk-core 0.2.0

Local search, evidence and cache engine
Documentation
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
//! Opt-in policy for automatic local-content collections on Unix.
//!
//! The same fixed path policy narrows discovery and every content access. Roots
//! are pinned directories; reads never follow symlinks. This is not an atomic
//! cloud-state or namespace snapshot: a directory can be renamed while traversed,
//! and a file can become dataless between the precheck and content open.

use crate::discovery::{
    ResourceKind, ScopeFilters, audio_byte_limit, discover_with_policy, ensure_allowed_path,
    matches_scope_filters,
};
use crate::pinned_dir::{
    descriptor_stat, ensure_kind, identity, materialized, open_at, open_directory, stat_at,
};
use crate::provider::ReadSeek;
use crate::{
    Error, ProvidedResource, ResourceId, ResourceListing, ResourceProvider, ResourceScope,
    ResourceVersion, Result,
};
use std::collections::HashMap;
use std::fs::File;
use std::io::{self, Read};
use std::os::unix::ffi::OsStrExt;
use std::path::{Component, Path, PathBuf};
use std::sync::{Arc, Mutex};

/// Advertised by the opt-in MCP server. Incompatible policy changes require a new version.
pub const LOCAL_CONTENT_POLICY_VERSION: u32 = 1;

const FORBIDDEN: &[&[u8]] = &[
    b"library",
    b"cache",
    b"caches",
    b".cache",
    b".build",
    b"build",
    b"dist",
    b"target",
    b"node_modules",
    b"__pycache__",
    b".git",
    b".hg",
    b".svn",
    b".venv",
];

fn policy_allows(path: &Path) -> bool {
    let parts: Vec<_> = path
        .components()
        .filter_map(|c| match c {
            Component::Normal(p) => Some(p.as_bytes()),
            _ => None,
        })
        .collect();
    if path
        .components()
        .any(|c| matches!(c, Component::ParentDir | Component::Prefix(_)))
    {
        return false;
    }
    if parts.iter().any(|p| {
        p.starts_with(b".")
            || FORBIDDEN.iter().any(|n| p.eq_ignore_ascii_case(n))
            || p[p.len().saturating_sub(7)..].eq_ignore_ascii_case(b".icloud")
    }) {
        return false;
    }
    // Narrow custom Rust artifact layout, normalized for this semantic policy.
    // Ordinary targets/data remains eligible.
    for (i, part) in parts.iter().enumerate() {
        if (part.eq_ignore_ascii_case(b"debug") || part.eq_ignore_ascii_case(b"release"))
            && i > 0
            && i + 1 < parts.len()
            && parts[i.saturating_sub(3)..i]
                .iter()
                .any(|p| p.eq_ignore_ascii_case(b"target") || p.eq_ignore_ascii_case(b"targets"))
            && [
                b"incremental".as_slice(),
                b".fingerprint",
                b"build",
                b"deps",
                b"examples",
            ]
            .iter()
            .any(|n| parts[i + 1].eq_ignore_ascii_case(n))
        {
            return false;
        }
    }
    true
}

#[derive(Debug)]
struct Root {
    path: PathBuf,
    directory: File,
    identity: (u64, u64),
}

/// Fixed, opt-in content provider. Ordinary `FsProvider` behavior is unchanged.
/// Explicit roots must already identify real directories without any symlink
/// component (including POSIX aliases such as /tmp on macOS).
#[derive(Debug)]
pub struct LocalContentProvider {
    roots: Vec<Root>,
    // Keep the first verified directory identity for each requested deletion
    // scope. Never adopt its replacement during this provider's lifetime.
    deletion_roots: Mutex<HashMap<PathBuf, Arc<Root>>>,
}

fn denied(path: &Path) -> Error {
    Error::io(
        path,
        io::Error::new(
            io::ErrorKind::PermissionDenied,
            "path is outside the fixed local-content policy",
        ),
    )
}
fn version(stat: &libc::stat) -> ResourceVersion {
    ResourceVersion::known(format!(
        "local:{}:{}:{}:{}:{}:{}:{}",
        stat.st_dev,
        stat.st_ino,
        stat.st_size,
        stat.st_mtime,
        stat.st_mtime_nsec,
        stat.st_ctime,
        stat.st_ctime_nsec
    ))
}

// libc time_t and the nanosecond field can independently be i32 or i64.
// Normalize both before arithmetic; unknown timestamps do not exclude a file.
fn timestamp_ns(seconds: impl Into<i64>, nanos: impl Into<i64>) -> Option<i64> {
    seconds
        .into()
        .checked_mul(1_000_000_000)?
        .checked_add(nanos.into())
}

impl LocalContentProvider {
    pub fn new(paths: &[PathBuf]) -> Result<Self> {
        if paths.is_empty() {
            return Err(Error::Config(
                "local-content requires explicit directory roots".into(),
            ));
        }
        let mut roots = Vec::new();
        for path in paths {
            ensure_allowed_path(path)?;
            if !policy_allows(path) {
                return Err(denied(path));
            }
            let directory = open_directory(path).map_err(|e| Error::io(path, e))?;
            let identity = identity(&descriptor_stat(&directory).map_err(|e| Error::io(path, e))?);
            roots.push(Root {
                path: path.clone(),
                directory,
                identity,
            });
        }
        Ok(Self {
            roots,
            deletion_roots: Mutex::new(HashMap::new()),
        })
    }
    /// Exact, non-canonicalized scope names validated when the provider was created.
    pub fn roots(&self) -> Vec<PathBuf> {
        self.roots.iter().map(|r| r.path.clone()).collect()
    }
    /// Metadata-only authorization for original MCP path inputs, before any
    /// caller canonicalization could erase a symlink from the request.
    pub fn validate_path(&self, path: &Path) -> Result<()> {
        let stat = self.stat(path)?;
        match stat.st_mode & libc::S_IFMT {
            libc::S_IFDIR | libc::S_IFREG => Ok(()),
            _ => Err(denied(path)),
        }
    }
    fn root_for(&self, path: &Path) -> Result<&Root> {
        if !policy_allows(path) {
            return Err(denied(path));
        }
        let root = self
            .roots
            .iter()
            .filter(|r| path.starts_with(&r.path))
            .max_by_key(|r| r.path.components().count())
            .ok_or_else(|| denied(path))?;
        let relative = path.strip_prefix(&root.path).map_err(|_| denied(path))?;
        if relative.components().any(|c| match c {
            Component::Normal(n) => n.as_bytes().starts_with(b"."),
            _ => true,
        }) {
            return Err(denied(path));
        }
        Ok(root)
    }
    fn validate_root(&self, root: &Root) -> Result<()> {
        let current = open_directory(&root.path).map_err(|e| Error::io(&root.path, e))?;
        if identity(&descriptor_stat(&current).map_err(|e| Error::io(&root.path, e))?)
            != root.identity
        {
            return Err(Error::ChangedWhileReading {
                resource: ResourceId::from_path(&root.path)?,
            });
        }
        Ok(())
    }
    fn parent(&self, path: &Path) -> Result<(File, std::ffi::OsString)> {
        let root = self.root_for(path)?;
        self.validate_root(root)?;
        let relative = path.strip_prefix(&root.path).map_err(|_| denied(path))?;
        let mut parts = relative.components().peekable();
        let mut directory = root.directory.try_clone().map_err(|e| Error::io(path, e))?;
        while let Some(Component::Normal(name)) = parts.next() {
            if parts.peek().is_none() {
                return Ok((directory, name.to_owned()));
            }
            directory = open_at(&directory, name, true).map_err(|e| Error::io(path, e))?;
        }
        Err(denied(path))
    }
    fn stat(&self, path: &Path) -> Result<libc::stat> {
        ensure_allowed_path(path)?;
        let root = self.root_for(path)?;
        if path == root.path {
            self.validate_root(root)?;
            return descriptor_stat(&root.directory).map_err(|e| Error::io(path, e));
        }
        let (directory, name) = self.parent(path)?;
        let stat = stat_at(&directory, &name).map_err(|e| Error::io(path, e))?;
        if stat.st_mode & libc::S_IFMT == libc::S_IFLNK {
            return Err(denied(path));
        }
        materialized(&stat).map_err(|e| Error::io(path, e))?;
        Ok(stat)
    }
    fn content(&self, path: &Path) -> Result<File> {
        ensure_allowed_path(path)?;
        let (directory, name) = self.parent(path)?;
        open_at(&directory, &name, false).map_err(|e| Error::io(path, e))
    }
    fn directory(&self, path: &Path) -> Result<File> {
        ensure_allowed_path(path)?;
        let root = self.root_for(path)?;
        if path == root.path {
            self.validate_root(root)?;
            return root.directory.try_clone().map_err(|e| Error::io(path, e));
        }
        let (directory, name) = self.parent(path)?;
        open_at(&directory, &name, true).map_err(|e| Error::io(path, e))
    }
    fn validate_deletion_root(&self, root: &Root) -> Result<()> {
        let current = self.directory(&root.path)?;
        if identity(&descriptor_stat(&current).map_err(|e| Error::io(&root.path, e))?)
            != root.identity
        {
            return Err(Error::ChangedWhileReading {
                resource: ResourceId::from_path(&root.path)?,
            });
        }
        Ok(())
    }
}
impl ResourceProvider for LocalContentProvider {
    fn supports_cached_listing(&self) -> bool {
        true
    }

    fn list_cached(
        &self,
        scope: &ResourceScope,
        ids: &[ResourceId],
    ) -> Result<Vec<ProvidedResource>> {
        let filters = ScopeFilters::new(&scope.discovery)?;
        let mut roots = Vec::new();
        for id in &scope.roots {
            let path = id
                .to_file_path()
                .ok_or_else(|| Error::Config("local-content requires file resources".into()))?;
            // Verify the requested scope through the configured root's pinned
            // identity, even for an empty cache. No descendant enumeration.
            let stat = self.stat(&path)?;
            let file = stat.st_mode & libc::S_IFMT == libc::S_IFREG;
            ensure_kind(&stat, !file).map_err(|e| Error::io(&path, e))?;
            roots.push((path, file));
        }
        let mut resources = Vec::new();
        for id in ids {
            let Some(path) = id.to_file_path() else {
                continue;
            };
            if !policy_allows(&path) || ensure_allowed_path(&path).is_err() {
                continue;
            }
            let explicit = roots.iter().any(|(root, file)| *file && path == *root);
            if !explicit
                && !roots
                    .iter()
                    .any(|(root, file)| !file && filters.matches(&path, root))
            {
                continue;
            }
            // Explicit files retain discovery's unknown-extension and filter
            // semantics; the fixed local policy cannot be disabled by either.
            let kind = match ResourceKind::from_path(&path) {
                Some(kind) => kind,
                None if explicit => ResourceKind::Text(crate::segment::TextFormat::Plain),
                None => continue,
            };
            let Ok(stat) = self.stat(&path) else { continue };
            if ensure_kind(&stat, false).is_err() {
                continue;
            }
            let limit = if kind == ResourceKind::Audio {
                let Ok(limit) = audio_byte_limit(scope.discovery.max_audio_duration_secs) else {
                    continue;
                };
                limit
            } else {
                scope.discovery.max_file_bytes
            };
            if stat.st_size < 0 || stat.st_size as u64 > limit {
                continue;
            }
            resources.push((
                path.clone(),
                ProvidedResource {
                    id: id.clone(),
                    kind,
                    size_bytes: stat.st_size as u64,
                    modified_ns: timestamp_ns(stat.st_mtime, stat.st_mtime_nsec),
                    version: version(&stat),
                    title: path.file_stem().map(|s| s.to_string_lossy().into_owned()),
                },
            ));
        }
        resources.sort_by(|a, b| {
            a.0.cmp(&b.0)
                .then_with(|| a.1.id.as_str().cmp(b.1.id.as_str()))
        });
        resources.dedup_by(|a, b| a.0 == b.0);
        Ok(resources
            .into_iter()
            .map(|(_, resource)| resource)
            .collect())
    }

    fn list(&self, scope: &ResourceScope) -> Result<Vec<ProvidedResource>> {
        Ok(self.list_walked(scope)?.resources)
    }

    fn list_walked(&self, scope: &ResourceScope) -> Result<ResourceListing> {
        let paths = scope
            .roots
            .iter()
            .map(|id| {
                id.to_file_path()
                    .ok_or_else(|| Error::Config("local-content requires file resources".into()))
            })
            .collect::<Result<Vec<_>>>()?;
        for path in &paths {
            self.stat(path)?;
        }
        let walked = discover_with_policy(&paths, &scope.discovery, |p| self.stat(p).is_ok())?;
        let resources = walked
            .resources
            .into_iter()
            .filter_map(|r| {
                // Discovery is metadata-only and path-based. Revalidate through the
                // pinned scope; only the confined content method can return bytes.
                let stat = self.stat(&r.path).ok()?;
                ensure_kind(&stat, false).ok()?;
                Some(Ok(ProvidedResource {
                    id: ResourceId::from_path(&r.path).ok()?,
                    kind: r.kind,
                    size_bytes: stat.st_size as u64,
                    modified_ns: timestamp_ns(stat.st_mtime, stat.st_mtime_nsec),
                    version: version(&stat),
                    title: r.path.file_stem().map(|s| s.to_string_lossy().into_owned()),
                }))
            })
            .collect::<Result<_>>()?;
        Ok(ResourceListing {
            resources,
            walked_roots: Some(
                walked
                    .walked_roots
                    .iter()
                    .map(ResourceId::from_path)
                    .collect::<Result<_>>()?,
            ),
        })
    }
    fn read(&self, id: &ResourceId) -> Result<Vec<u8>> {
        let path = id
            .to_file_path()
            .ok_or_else(|| Error::Config("local-content requires file resources".into()))?;
        let mut file = self.content(&path)?;
        let before = descriptor_stat(&file).map_err(|e| Error::io(&path, e))?;
        let mut bytes = Vec::new();
        file.read_to_end(&mut bytes)
            .map_err(|e| Error::io(&path, e))?;
        let after = descriptor_stat(&file).map_err(|e| Error::io(&path, e))?;
        ensure_kind(&after, false).map_err(|e| Error::io(&path, e))?;
        if !version(&before).matches(&version(&after)) {
            return Err(Error::ChangedWhileReading {
                resource: id.clone(),
            });
        }
        Ok(bytes)
    }
    fn open(&self, id: &ResourceId) -> Result<Box<dyn ReadSeek>> {
        let path = id
            .to_file_path()
            .ok_or_else(|| Error::Config("local-content requires file resources".into()))?;
        Ok(Box::new(self.content(&path)?))
    }
    fn version(&self, id: &ResourceId) -> Result<ResourceVersion> {
        let path = id
            .to_file_path()
            .ok_or_else(|| Error::Config("local-content requires file resources".into()))?;
        let stat = self.stat(&path)?;
        ensure_kind(&stat, false).map_err(|e| Error::io(&path, e))?;
        Ok(version(&stat))
    }
    fn deletion_scope(&self, scope: &ResourceScope) -> Result<ResourceScope> {
        let mut verified = Vec::new();
        for id in &scope.roots {
            let path = id
                .to_file_path()
                .ok_or_else(|| Error::Config("local-content requires file resources".into()))?;
            let directory = self.directory(&path)?;
            let identity = identity(&descriptor_stat(&directory).map_err(|e| Error::io(&path, e))?);
            verified.push(Root {
                path,
                directory,
                identity,
            });
        }
        let mut anchors = self
            .deletion_roots
            .lock()
            .map_err(|_| Error::Config("deletion scope lock poisoned".into()))?;
        for root in verified {
            if let Some(pinned) = anchors.get(&root.path) {
                if root.identity != pinned.identity {
                    return Err(Error::ChangedWhileReading {
                        resource: ResourceId::from_path(&root.path)?,
                    });
                }
            } else {
                anchors.insert(root.path.clone(), Arc::new(root));
            }
        }
        Ok(scope.clone())
    }
    fn is_deleted(&self, id: &ResourceId, scope: &ResourceScope) -> Result<bool> {
        let Some(path) = id.to_file_path() else {
            return Ok(false);
        };
        if !scope.contains(id) {
            return Ok(false);
        }
        let Ok(configured_root) = self.root_for(&path) else {
            return Ok(false);
        };
        let mut eligible = Vec::new();
        for id in &scope.roots {
            let Some(root) = id.to_file_path() else {
                continue;
            };
            if path.starts_with(&root) && matches_scope_filters(&path, &root, &scope.discovery)? {
                eligible.push(root);
            }
        }
        let Some(root) = eligible.into_iter().max_by_key(|r| r.components().count()) else {
            return Ok(false);
        };
        let pinned = self
            .deletion_roots
            .lock()
            .map_err(|_| Error::Config("deletion scope lock poisoned".into()))?
            .get(&root)
            .cloned()
            .ok_or_else(|| Error::Config("deletion scope has not been verified".into()))?;
        self.validate_root(configured_root)?;
        self.validate_deletion_root(&pinned)?;
        let mut directory = pinned
            .directory
            .try_clone()
            .map_err(|e| Error::io(&path, e))?;
        let relative = path.strip_prefix(&root).map_err(|_| denied(&path))?;
        let mut parts = relative.components().peekable();
        while let Some(Component::Normal(name)) = parts.next() {
            match stat_at(&directory, name) {
                Ok(_) if parts.peek().is_none() => return Ok(false),
                Ok(_) => {
                    directory = open_at(&directory, name, true).map_err(|e| Error::io(&path, e))?
                }
                Err(e) if e.raw_os_error() == Some(libc::ENOENT) => {
                    // A missing child never authorizes deletion if either the
                    // configured root or requested scope changed during the walk.
                    self.validate_root(configured_root)?;
                    self.validate_deletion_root(&pinned)?;
                    return Ok(true);
                }
                Err(e) => return Err(Error::io(&path, e)),
            }
        }
        Ok(false)
    }
}

#[cfg(test)]
mod timestamp_tests {
    use super::timestamp_ns;
    #[test]
    fn native_i32_and_i64_timestamp_fields_produce_i64_nanoseconds() {
        let expected: Option<i64> = Some(2_000_000_007);
        assert_eq!(timestamp_ns(2_i32, 7_i32), expected);
        assert_eq!(timestamp_ns(2_i64, 7_i32), expected);
        assert_eq!(timestamp_ns(2_i64, 7_i64), expected);
        assert_eq!(
            timestamp_ns(i32::MAX, 7_i32),
            Some(2_147_483_647_000_000_007)
        );
        assert_eq!(timestamp_ns(i64::MAX, 0_i32), None);
    }
}