ai-session-search 1.0.0-rc.4

Local-first search, inspection, export, recovery, and MCP recall across supported AI coding-agent sessions.
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
// SPDX-FileCopyrightText: 2026 Andrew Hundt
// SPDX-License-Identifier: Apache-2.0

use std::fs;
use std::io::ErrorKind;
use std::path::{Component, Path, PathBuf};

use anyhow::{anyhow, bail, Context, Result};
use serde::Serialize;

use crate::config::{SearchScopeConfig, SearchScopeMode};

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum AccessRootOrigin {
    HarnessRoots,
    ExplicitConfig,
    InvocationDirectory,
}

impl AccessRootOrigin {
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::HarnessRoots => "harness-roots",
            Self::ExplicitConfig => "explicit-config",
            Self::InvocationDirectory => "invocation-directory",
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
pub struct AccessRootSource {
    configured_path: PathBuf,
    canonicalized_at_startup: bool,
    origin: AccessRootOrigin,
}

impl AccessRootSource {
    pub fn configured_path(&self) -> &Path {
        &self.configured_path
    }

    pub const fn origin(&self) -> AccessRootOrigin {
        self.origin
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
pub struct AccessRoot {
    canonical_path: PathBuf,
    match_paths: Vec<PathBuf>,
    sources: Vec<AccessRootSource>,
}

impl AccessRoot {
    pub fn path(&self) -> &Path {
        &self.canonical_path
    }

    pub fn configured_path(&self) -> &Path {
        self.sources[0].configured_path()
    }

    pub fn origin(&self) -> AccessRootOrigin {
        self.sources[0].origin()
    }

    pub fn sources(&self) -> &[AccessRootSource] {
        &self.sources
    }

    fn database_prefixes(&self) -> impl Iterator<Item = &str> {
        self.match_paths
            .iter()
            .map(|path| path.to_str().expect("validated access roots are UTF-8"))
    }
}

#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct TrustedAccessInputs {
    pub harness_roots: Vec<PathBuf>,
    pub invocation_directory: Option<PathBuf>,
}

impl TrustedAccessInputs {
    pub(crate) fn capture(config: &SearchScopeConfig, harness_roots: Vec<PathBuf>) -> Result<Self> {
        let invocation_directory = if config.include_invocation_directory {
            Some(std::env::current_dir().map_err(|error| {
                anyhow!("cannot resolve invocation directory for allowed-roots scope: {error}")
            })?)
        } else {
            None
        };
        Ok(Self {
            harness_roots,
            invocation_directory,
        })
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(tag = "mode", rename_all = "kebab-case")]
pub enum EffectiveAccessScope {
    All,
    AllowedRoots { roots: Vec<AccessRoot> },
}

impl EffectiveAccessScope {
    pub fn resolve(config: &SearchScopeConfig, inputs: TrustedAccessInputs) -> Result<Self> {
        if config.mode == SearchScopeMode::All {
            return Ok(Self::All);
        }

        let mut candidates = Vec::new();
        candidates.extend(
            inputs
                .harness_roots
                .into_iter()
                .map(|path| (path, AccessRootOrigin::HarnessRoots)),
        );
        candidates.extend(
            config
                .roots
                .iter()
                .map(|path| (PathBuf::from(path), AccessRootOrigin::ExplicitConfig)),
        );
        if config.include_invocation_directory {
            if let Some(path) = inputs.invocation_directory {
                candidates.push((path, AccessRootOrigin::InvocationDirectory));
            }
        }

        let mut roots = Vec::new();
        for (path, origin) in candidates {
            let candidate = normalize_authority_root(&path, origin).with_context(|| {
                format!("invalid {} access root {:?}", origin_name(origin), path)
            })?;
            if let Some(existing) = roots
                .iter_mut()
                .find(|root: &&mut AccessRoot| root.canonical_path == candidate.canonical_path)
            {
                for path in candidate.match_paths {
                    if !existing.match_paths.contains(&path) {
                        existing.match_paths.push(path);
                    }
                }
                existing.sources.extend(candidate.sources);
            } else {
                roots.push(candidate);
            }
        }

        if roots.is_empty() {
            bail!(
                "search scope mode allowed-roots resolved no authoritative roots; configure search.scope.roots, enable include_invocation_directory, or supply trusted harness roots"
            );
        }
        Ok(Self::AllowedRoots { roots })
    }

    pub const fn is_unrestricted(&self) -> bool {
        matches!(self, Self::All)
    }

    pub fn roots(&self) -> &[AccessRoot] {
        match self {
            Self::All => &[],
            Self::AllowedRoots { roots } => roots,
        }
    }

    pub fn workspace_prefixes(&self) -> impl Iterator<Item = &str> {
        self.roots().iter().flat_map(AccessRoot::database_prefixes)
    }

    pub fn allows_workspace_path(&self, path: &Path) -> bool {
        match self {
            Self::All => true,
            Self::AllowedRoots { roots } => lexical_absolute(path).is_ok_and(|path| {
                roots
                    .iter()
                    .flat_map(|root| &root.match_paths)
                    .any(|root| path.starts_with(root))
            }),
        }
    }

    pub fn validate_stable(&self) -> Result<()> {
        for root in self.roots() {
            for source in &root.sources {
                let current = match fs::canonicalize(&source.configured_path) {
                    Ok(current) => current,
                    Err(error)
                        if error.kind() == ErrorKind::NotFound
                            && !source.canonicalized_at_startup =>
                    {
                        continue;
                    }
                    Err(error) => {
                        return Err(error).with_context(|| {
                            format!(
                                "allowed root {:?} disappeared after scope resolution",
                                source.configured_path
                            )
                        });
                    }
                };
                if !current.is_dir() {
                    bail!(
                        "allowed root {:?} is no longer a directory; refusing to widen access",
                        source.configured_path
                    );
                }
                if current != root.canonical_path {
                    bail!(
                        "allowed root {:?} changed target after scope resolution; refusing to widen access",
                        source.configured_path
                    );
                }
            }
        }
        Ok(())
    }
}

fn origin_name(origin: AccessRootOrigin) -> &'static str {
    origin.as_str()
}

fn normalize_authority_root(path: &Path, origin: AccessRootOrigin) -> Result<AccessRoot> {
    let lexical = lexical_absolute(path)?;
    let (canonical, canonicalized_at_startup) = match fs::canonicalize(&lexical) {
        Ok(path) => {
            if !path.is_dir() {
                bail!("access root exists but is not a directory");
            }
            (lexical_absolute(&path)?, true)
        }
        Err(error)
            if error.kind() == ErrorKind::NotFound
                && origin == AccessRootOrigin::ExplicitConfig =>
        {
            (lexical.clone(), false)
        }
        Err(error) if error.kind() == ErrorKind::NotFound => {
            bail!("trusted runtime access root does not exist")
        }
        Err(error) => {
            return Err(error).with_context(|| format!("cannot resolve access root {lexical:?}"));
        }
    };
    if canonical.parent().is_none() {
        bail!("filesystem roots are not valid allowed-roots entries");
    }
    if lexical.to_str().is_none() || canonical.to_str().is_none() {
        bail!("access roots must be valid UTF-8 for the SQLite path model");
    }
    let mut match_paths = vec![canonical.clone()];
    if lexical != canonical {
        match_paths.push(lexical.clone());
    }
    Ok(AccessRoot {
        canonical_path: canonical,
        match_paths,
        sources: vec![AccessRootSource {
            configured_path: lexical,
            canonicalized_at_startup,
            origin,
        }],
    })
}

pub(crate) fn validate_configured_root(path: &Path) -> Result<()> {
    normalize_authority_root(path, AccessRootOrigin::ExplicitConfig).map(|_| ())
}

pub(crate) fn ensure_raw_sql_allowed(config: &SearchScopeConfig, operation: &str) -> Result<()> {
    if config.mode == SearchScopeMode::AllowedRoots {
        bail!(
            "{operation} is unavailable while search.scope.mode is allowed-roots because arbitrary SQL cannot enforce workspace authority; use typed search, session, message, analysis, file, or export operations"
        );
    }
    Ok(())
}

fn lexical_absolute(path: &Path) -> Result<PathBuf> {
    if !path.is_absolute() {
        bail!("access roots must be absolute paths");
    }
    let mut normalized = PathBuf::new();
    for component in path.components() {
        match component {
            Component::Prefix(_) | Component::RootDir | Component::Normal(_) => {
                normalized.push(component.as_os_str());
            }
            Component::CurDir => {}
            Component::ParentDir => {
                if !normalized.pop() || !normalized.has_root() {
                    return Err(anyhow!("access root escapes its filesystem root"));
                }
            }
        }
    }
    Ok(normalized)
}

#[cfg(test)]
mod tests {
    use super::*;

    fn restricted(roots: &[&Path]) -> SearchScopeConfig {
        SearchScopeConfig {
            mode: SearchScopeMode::AllowedRoots,
            roots: roots
                .iter()
                .map(|path| path.to_string_lossy().into_owned())
                .collect(),
            include_invocation_directory: false,
        }
    }

    #[test]
    fn unrestricted_scope_preserves_every_path_and_ignores_unused_inputs() {
        let scope = EffectiveAccessScope::resolve(
            &SearchScopeConfig::default(),
            TrustedAccessInputs {
                harness_roots: vec![PathBuf::from("relative-is-unused")],
                invocation_directory: None,
            },
        )
        .unwrap();
        assert!(scope.is_unrestricted());
        assert!(scope.allows_workspace_path(Path::new("relative-is-still-visible")));
    }

    #[test]
    fn restricted_scope_unions_deduplicates_and_records_origins() {
        let root = tempfile::tempdir().unwrap();
        let configured = root.path().join("configured");
        let harness = root.path().join("harness");
        let invocation = root.path().join("invocation");
        fs::create_dir_all(&configured).unwrap();
        fs::create_dir_all(&harness).unwrap();
        fs::create_dir_all(&invocation).unwrap();
        let mut config = restricted(&[&configured]);
        config.include_invocation_directory = true;

        let scope = EffectiveAccessScope::resolve(
            &config,
            TrustedAccessInputs {
                harness_roots: vec![harness.clone(), configured.clone()],
                invocation_directory: Some(invocation.clone()),
            },
        )
        .unwrap();

        assert_eq!(scope.roots().len(), 3);
        assert_eq!(scope.roots()[0].origin(), AccessRootOrigin::HarnessRoots);
        assert_eq!(scope.roots()[1].origin(), AccessRootOrigin::HarnessRoots);
        assert_eq!(scope.roots()[1].sources().len(), 2);
        assert_eq!(
            scope.roots()[1].sources()[1].origin(),
            AccessRootOrigin::ExplicitConfig
        );
        assert_eq!(
            scope.roots()[2].origin(),
            AccessRootOrigin::InvocationDirectory
        );
        assert!(scope.allows_workspace_path(&harness.join("child")));
        assert!(scope.allows_workspace_path(&configured));
        assert!(scope.allows_workspace_path(&invocation.join("child")));
        assert!(!scope.allows_workspace_path(root.path().join("outside").as_path()));
    }

    #[test]
    fn restricted_scope_fails_closed_without_authoritative_roots() {
        let error = EffectiveAccessScope::resolve(&restricted(&[]), TrustedAccessInputs::default())
            .unwrap_err()
            .to_string();
        assert!(error.contains("resolved no authoritative roots"), "{error}");
    }

    #[test]
    fn roots_require_absolute_non_root_directory_paths() {
        for value in [Path::new("relative"), Path::new("/")] {
            let error = EffectiveAccessScope::resolve(
                &restricted(&[value]),
                TrustedAccessInputs::default(),
            )
            .unwrap_err()
            .to_string();
            assert!(
                error.contains("invalid explicit-config access root"),
                "{error}"
            );
        }
    }

    #[test]
    fn arbitrary_sql_is_allowed_only_for_unrestricted_scope() {
        ensure_raw_sql_allowed(&SearchScopeConfig::default(), "test query").unwrap();
        let error = ensure_raw_sql_allowed(&restricted(&[Path::new("/configured")]), "test query")
            .unwrap_err()
            .to_string();
        assert!(error.contains("test query is unavailable"));
        assert!(error.contains("arbitrary SQL cannot enforce workspace authority"));
    }

    #[test]
    fn lexical_normalization_preserves_component_boundaries() {
        let root = tempfile::tempdir().unwrap();
        let allowed = root.path().join("a/inside/../allowed");
        fs::create_dir_all(root.path().join("a/allowed")).unwrap();
        let scope =
            EffectiveAccessScope::resolve(&restricted(&[&allowed]), TrustedAccessInputs::default())
                .unwrap();
        assert!(scope.allows_workspace_path(&root.path().join("a/allowed/child")));
        assert!(!scope.allows_workspace_path(&root.path().join("a/allowed-sibling")));
    }

    #[cfg(unix)]
    #[test]
    fn existing_symlink_keeps_lexical_alias_and_fails_closed_after_retarget() {
        use std::os::unix::fs::symlink;

        let root = tempfile::tempdir().unwrap();
        let target = root.path().join("target");
        let alias = root.path().join("alias");
        fs::create_dir(&target).unwrap();
        symlink(&target, &alias).unwrap();

        let scope =
            EffectiveAccessScope::resolve(&restricted(&[&alias]), TrustedAccessInputs::default())
                .unwrap();
        assert_eq!(scope.roots()[0].path(), target.canonicalize().unwrap());
        assert!(scope.allows_workspace_path(&scope.roots()[0].path().join("child")));
        assert!(scope.allows_workspace_path(&alias.join("child")));
        scope.validate_stable().unwrap();

        let other = root.path().join("other");
        fs::create_dir(&other).unwrap();
        fs::remove_file(&alias).unwrap();
        symlink(&other, &alias).unwrap();
        let error = scope.validate_stable().unwrap_err().to_string();
        assert!(error.contains("changed target"), "{error}");
    }

    #[cfg(unix)]
    #[test]
    fn every_deduplicated_symlink_alias_is_revalidated() {
        use std::os::unix::fs::symlink;

        let root = tempfile::tempdir().unwrap();
        let target = root.path().join("target");
        let other = root.path().join("other");
        let configured_alias = root.path().join("configured-alias");
        let harness_alias = root.path().join("harness-alias");
        fs::create_dir(&target).unwrap();
        fs::create_dir(&other).unwrap();
        symlink(&target, &configured_alias).unwrap();
        symlink(&target, &harness_alias).unwrap();

        let scope = EffectiveAccessScope::resolve(
            &restricted(&[&configured_alias]),
            TrustedAccessInputs {
                harness_roots: vec![harness_alias],
                invocation_directory: None,
            },
        )
        .unwrap();
        assert_eq!(scope.roots().len(), 1);
        assert_eq!(scope.roots()[0].sources().len(), 2);

        fs::remove_file(&configured_alias).unwrap();
        symlink(&other, &configured_alias).unwrap();
        let error = scope.validate_stable().unwrap_err().to_string();
        assert!(error.contains("changed target"), "{error}");
    }

    #[cfg(unix)]
    #[test]
    fn configured_root_missing_at_startup_rejects_later_symlink_target() {
        use std::os::unix::fs::symlink;

        let root = tempfile::tempdir().unwrap();
        let configured = root.path().join("future-root");
        let outside = root.path().join("outside");
        fs::create_dir(&outside).unwrap();

        let scope = EffectiveAccessScope::resolve(
            &restricted(&[&configured]),
            TrustedAccessInputs::default(),
        )
        .unwrap();
        scope.validate_stable().unwrap();

        symlink(&outside, &configured).unwrap();
        let error = scope.validate_stable().unwrap_err().to_string();
        assert!(error.contains("changed target"), "{error}");
    }
}