frigg 0.6.0

Frigg gives AI agents local, source-backed code search and navigation without sending whole repositories through every prompt.
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
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
//! Workspace lifecycle tools: attach, detach, prepare, index, and index/precise readiness waits.
//!
//! Handles attach, detach, prepare, index, and readiness waits; adoption paths establish manifest
//! snapshots before search serves.

use super::*;

impl FriggMcpSessionState {
    pub(super) fn new(
        workspace_registry: Arc<RwLock<WorkspaceRegistry>>,
        watch_runtime: Arc<RwLock<Option<Arc<crate::watch::WatchRuntime>>>>,
    ) -> Self {
        Self {
            inner: Arc::new(FriggMcpSessionStateInner {
                display_session_id: Uuid::now_v7().simple().to_string(),
                workspace_registry,
                watch_runtime,
                adopted_repository_ids: RwLock::new(BTreeSet::new()),
                workspace_attach_states: RwLock::new(BTreeMap::new()),
                session_default_repository_id: RwLock::new(None),
                result_handles: RwLock::new(SessionResultHandleCache::default()),
            }),
        }
    }

    pub(super) fn display_session_id(&self) -> String {
        self.inner.display_session_id.clone()
    }
}

impl FriggMcpSessionStateInner {
    fn release_repository_id(&self, repository_id: &str) {
        let (remaining_sessions, runtime_repository_id) = {
            let mut registry = self
                .workspace_registry
                .write()
                .unwrap_or_else(|poisoned| poisoned.into_inner());
            let runtime_repository_id = registry
                .workspace_by_repository_id(repository_id)
                .map(|workspace| workspace.runtime_repository_id)
                .unwrap_or_else(|| repository_id.to_owned());
            let remaining_sessions = registry.mark_session_released(repository_id);
            (remaining_sessions, runtime_repository_id)
        };
        if let Some(watch_runtime) = self
            .watch_runtime
            .read()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
            .as_ref()
            .cloned()
        {
            watch_runtime.release_lease(&runtime_repository_id);
        }
        if remaining_sessions == 0 {
            self.workspace_registry
                .write()
                .unwrap_or_else(|poisoned| poisoned.into_inner())
                .prune_inactive_ephemeral_workspace(repository_id);
        }
    }
}

#[derive(Debug)]
pub(super) struct WorkspaceAdoption {
    pub(super) newly_adopted: bool,
}

pub(super) struct WorkspaceResolutionGuard {
    workspace_registry: Arc<RwLock<WorkspaceRegistry>>,
    repository_id: String,
    active: bool,
}

impl WorkspaceResolutionGuard {
    pub(super) fn new(
        workspace_registry: Arc<RwLock<WorkspaceRegistry>>,
        repository_id: String,
    ) -> Self {
        Self {
            workspace_registry,
            repository_id,
            active: true,
        }
    }

    fn release(&mut self) {
        if !self.active {
            return;
        }
        self.active = false;
        let mut registry = self
            .workspace_registry
            .write()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        registry.mark_workspace_pending_released(&self.repository_id);
        registry.prune_inactive_ephemeral_workspace(&self.repository_id);
    }
}

impl Drop for WorkspaceResolutionGuard {
    fn drop(&mut self) {
        self.release();
    }
}

pub(super) struct WorkspaceAttachRollbackGuard {
    session_state: FriggMcpSessionState,
    repository_id: String,
    previous_default_repository_id: Option<String>,
    set_default: bool,
    created_adoption: bool,
    active: bool,
}

impl WorkspaceAttachRollbackGuard {
    fn new(
        session_state: FriggMcpSessionState,
        repository_id: String,
        previous_default_repository_id: Option<String>,
        set_default: bool,
    ) -> Self {
        {
            let mut states = session_state
                .inner
                .workspace_attach_states
                .write()
                .unwrap_or_else(|poisoned| poisoned.into_inner());
            let state = states.entry(repository_id.clone()).or_default();
            state.in_flight = state.in_flight.saturating_add(1);
        }

        Self {
            session_state,
            repository_id,
            previous_default_repository_id,
            set_default,
            created_adoption: false,
            active: true,
        }
    }

    pub(super) fn mark_created_adoption(&mut self) {
        self.created_adoption = true;
    }

    pub(super) fn disarm(mut self) {
        self.finish(true);
    }

    fn finish(&mut self, completed: bool) {
        if !self.active {
            return;
        }
        self.active = false;

        let (rollback_previous_default_repository_id, restore_previous_default_repository_id) = {
            let mut states = self
                .session_state
                .inner
                .workspace_attach_states
                .write()
                .unwrap_or_else(|poisoned| poisoned.into_inner());
            let state = states.entry(self.repository_id.clone()).or_default();
            state.in_flight = state.in_flight.saturating_sub(1);

            if completed {
                state.completed = true;
                state.rollback_requested = false;
                state.rollback_previous_default_repository_id = None;
                if self.set_default {
                    state.default_confirmed = true;
                    state.default_restore_requested = false;
                    state.default_restore_previous_default_repository_id = None;
                }
            } else if self.created_adoption {
                if !state.completed {
                    state.rollback_requested = true;
                    state.rollback_previous_default_repository_id =
                        self.previous_default_repository_id.clone();
                }
                if self.set_default && !state.default_confirmed {
                    state.default_restore_requested = true;
                    state.default_restore_previous_default_repository_id =
                        self.previous_default_repository_id.clone();
                }
            }

            let should_rollback =
                !state.completed && state.rollback_requested && state.in_flight == 0;
            let rollback_previous_default_repository_id =
                should_rollback.then(|| state.rollback_previous_default_repository_id.clone());
            let should_restore_default = state.completed
                && state.default_restore_requested
                && !state.default_confirmed
                && state.in_flight == 0;
            let restore_previous_default_repository_id = should_restore_default
                .then(|| state.default_restore_previous_default_repository_id.clone());
            if state.in_flight == 0
                && (state.completed || should_rollback || !state.rollback_requested)
            {
                states.remove(&self.repository_id);
            }
            (
                rollback_previous_default_repository_id,
                restore_previous_default_repository_id,
            )
        };

        if let Some(previous_default_repository_id) = rollback_previous_default_repository_id {
            self.rollback_adoption(previous_default_repository_id);
        } else if let Some(previous_default_repository_id) = restore_previous_default_repository_id
        {
            self.restore_previous_default(previous_default_repository_id);
        }
    }

    fn rollback_adoption(&self, previous_default_repository_id: Option<String>) {
        let previous_default_repository_id = {
            let mut adopted = self
                .session_state
                .inner
                .adopted_repository_ids
                .write()
                .unwrap_or_else(|poisoned| poisoned.into_inner());
            if !adopted.remove(&self.repository_id) {
                return;
            }
            previous_default_repository_id
                .as_ref()
                .filter(|repository_id| adopted.contains(repository_id.as_str()))
                .cloned()
        };

        {
            let mut current = self
                .session_state
                .inner
                .session_default_repository_id
                .write()
                .unwrap_or_else(|poisoned| poisoned.into_inner());
            if current.as_deref() == Some(self.repository_id.as_str()) {
                *current = previous_default_repository_id;
            }
        }

        self.session_state
            .inner
            .release_repository_id(&self.repository_id);
    }

    fn restore_previous_default(&self, previous_default_repository_id: Option<String>) {
        let previous_default_repository_id = {
            let adopted = self
                .session_state
                .inner
                .adopted_repository_ids
                .read()
                .unwrap_or_else(|poisoned| poisoned.into_inner());
            previous_default_repository_id
                .as_ref()
                .filter(|repository_id| adopted.contains(repository_id.as_str()))
                .cloned()
        };

        let mut current = self
            .session_state
            .inner
            .session_default_repository_id
            .write()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        if current.as_deref() == Some(self.repository_id.as_str()) {
            *current = previous_default_repository_id;
        }
    }
}

impl Drop for WorkspaceAttachRollbackGuard {
    fn drop(&mut self) {
        self.finish(false);
    }
}

impl Drop for FriggMcpSessionStateInner {
    fn drop(&mut self) {
        let adopted_repository_ids = self
            .adopted_repository_ids
            .write()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
            .iter()
            .cloned()
            .collect::<Vec<_>>();
        for repository_id in adopted_repository_ids {
            self.release_repository_id(&repository_id);
        }
    }
}

impl FriggMcpServer {
    pub(super) fn known_workspaces(&self) -> Vec<AttachedWorkspace> {
        self.runtime_state
            .workspace_registry
            .read()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
            .known_workspaces()
    }

    pub(super) fn startup_workspaces(&self) -> Vec<AttachedWorkspace> {
        self.runtime_state
            .workspace_registry
            .read()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
            .startup_workspaces()
    }

    pub(super) fn auto_adoptable_workspaces(&self) -> Vec<AttachedWorkspace> {
        self.startup_workspaces()
    }

    pub(super) fn visible_workspaces(&self) -> Vec<AttachedWorkspace> {
        let mut visible = BTreeMap::new();
        {
            let registry = self
                .runtime_state
                .workspace_registry
                .read()
                .unwrap_or_else(|poisoned| poisoned.into_inner());
            for workspace in registry.startup_workspaces() {
                visible.insert(workspace.repository_id.clone(), workspace);
            }
            for repository_id in self
                .session_state
                .inner
                .adopted_repository_ids
                .read()
                .unwrap_or_else(|poisoned| poisoned.into_inner())
                .iter()
            {
                if let Some(workspace) = registry.workspace_by_repository_id(repository_id) {
                    visible.insert(workspace.repository_id.clone(), workspace);
                }
            }
        }
        visible.into_values().collect()
    }

    pub(super) fn attached_workspaces(&self) -> Vec<AttachedWorkspace> {
        let adopted_repository_ids = self
            .session_state
            .inner
            .adopted_repository_ids
            .read()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
            .iter()
            .cloned()
            .collect::<Vec<_>>();
        let registry = self
            .runtime_state
            .workspace_registry
            .read()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        adopted_repository_ids
            .into_iter()
            .filter_map(|repository_id| registry.workspace_by_repository_id(&repository_id))
            .collect()
    }

    pub(super) fn current_repository_id(&self) -> Option<String> {
        self.session_state
            .inner
            .session_default_repository_id
            .read()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
            .clone()
    }

    pub(super) fn set_current_repository_id(&self, repository_id: Option<String>) {
        let mut current = self
            .session_state
            .inner
            .session_default_repository_id
            .write()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        *current = repository_id;
    }

    pub(super) fn is_visible_repository_id(&self, repository_id: &str) -> bool {
        let registry = self
            .runtime_state
            .workspace_registry
            .read()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        if registry.is_startup_repository_id(repository_id) {
            return true;
        }
        let Some(workspace) = registry.workspace_by_any_repository_id(repository_id) else {
            return false;
        };
        self.session_state
            .inner
            .adopted_repository_ids
            .read()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
            .contains(&workspace.repository_id)
    }

    pub(super) fn adopt_workspace(
        &self,
        workspace: &AttachedWorkspace,
        set_default: bool,
    ) -> Result<WorkspaceAdoption, ErrorData> {
        let newly_adopted = {
            let mut adopted = self
                .session_state
                .inner
                .adopted_repository_ids
                .write()
                .unwrap_or_else(|poisoned| poisoned.into_inner());
            adopted.insert(workspace.repository_id.clone())
        };

        if newly_adopted {
            self.runtime_state
                .workspace_registry
                .write()
                .unwrap_or_else(|poisoned| poisoned.into_inner())
                .mark_session_adopted(&workspace.repository_id);
            if let Some(watch_runtime) = self
                .runtime_state
                .watch_runtime
                .read()
                .unwrap_or_else(|poisoned| poisoned.into_inner())
                .as_ref()
                .cloned()
                && let Err(err) = watch_runtime
                    .acquire_lease(workspace)
                    .map_err(Self::map_frigg_error)
            {
                {
                    let mut adopted = self
                        .session_state
                        .inner
                        .adopted_repository_ids
                        .write()
                        .unwrap_or_else(|poisoned| poisoned.into_inner());
                    adopted.remove(&workspace.repository_id);
                }
                self.session_state
                    .inner
                    .release_repository_id(&workspace.repository_id);
                return Err(err);
            }
        }

        if set_default {
            self.set_current_repository_id(Some(workspace.repository_id.clone()));
        }

        Ok(WorkspaceAdoption { newly_adopted })
    }

    pub(super) fn workspace_attach_path_rollback_guard(
        &self,
        path: Option<&str>,
        previous_default_repository_id: Option<String>,
        workspace: &AttachedWorkspace,
        set_default: bool,
    ) -> Option<WorkspaceAttachRollbackGuard> {
        path?;

        Some(WorkspaceAttachRollbackGuard::new(
            self.session_state.clone(),
            workspace.repository_id.clone(),
            previous_default_repository_id,
            set_default,
        ))
    }

    pub(super) fn detach_workspace(
        &self,
        repository_id: &str,
    ) -> Result<Option<AttachedWorkspace>, ErrorData> {
        let removed = {
            let mut adopted = self
                .session_state
                .inner
                .adopted_repository_ids
                .write()
                .unwrap_or_else(|poisoned| poisoned.into_inner());
            adopted.remove(repository_id)
        };
        if !removed {
            return Ok(None);
        }
        self.session_state
            .inner
            .workspace_attach_states
            .write()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
            .remove(repository_id);

        if self.current_repository_id().as_deref() == Some(repository_id) {
            self.set_current_repository_id(None);
        }
        let detached_workspace = self
            .runtime_state
            .workspace_registry
            .read()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
            .workspace_by_repository_id(repository_id);
        self.session_state
            .inner
            .release_repository_id(repository_id);

        Ok(detached_workspace)
    }

    pub(super) fn current_workspace(&self) -> Option<AttachedWorkspace> {
        let repository_id = self.current_repository_id()?;
        self.runtime_state
            .workspace_registry
            .read()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
            .workspace_by_repository_id(&repository_id)
    }

    pub(super) fn no_attached_workspaces_error(action: &str) -> ErrorData {
        let attach_path = std::env::current_dir()
            .ok()
            .map(|path| path.display().to_string())
            .unwrap_or_else(|| "<repo root or any file inside it>".to_owned());
        Self::resource_not_found(
            "no repositories are adopted for this session",
            Some(json!({
                "attached_repositories": [],
                "action": action,
                "hint": "Call workspace with next_params.path, then retry.",
                "next_tool": "workspace",
                "next_params": { "path": attach_path },
            })),
        )
    }

    pub(super) fn attached_workspaces_for_repository(
        &self,
        repository_id: Option<&str>,
    ) -> Result<Vec<AttachedWorkspace>, ErrorData> {
        let adopted_repository_ids = self
            .session_state
            .inner
            .adopted_repository_ids
            .read()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
            .iter()
            .cloned()
            .collect::<Vec<_>>();

        if let Some(repository_id) = repository_id.map(str::to_owned) {
            let workspace = {
                let registry = self
                    .runtime_state
                    .workspace_registry
                    .read()
                    .unwrap_or_else(|poisoned| poisoned.into_inner());
                registry.workspace_by_repository_id(&repository_id)
            };
            let Some(workspace) = workspace else {
                return Err(Self::resource_not_found(
                    "repository_id not found",
                    Some(json!({ "repository_id": repository_id })),
                ));
            };

            let is_adopted = adopted_repository_ids
                .iter()
                .any(|id| id == &workspace.repository_id);
            if is_adopted {
                return Ok(vec![workspace]);
            }
            return Err(Self::resource_not_found(
                "repository_id is not adopted for this session",
                Some(json!({
                    "repository_id": repository_id,
                    "attached_repositories": adopted_repository_ids,
                    "hint": "Call workspace with next_params, then retry.",
                    "next_tool": "workspace",
                    "next_params": { "repository_id": workspace.repository_id },
                })),
            ));
        }

        if let Some(repository_id) = self.current_repository_id() {
            let registry = self
                .runtime_state
                .workspace_registry
                .read()
                .unwrap_or_else(|poisoned| poisoned.into_inner());
            let Some(workspace) = registry.workspace_by_repository_id(&repository_id) else {
                return Err(Self::resource_not_found(
                    "repository_id not found",
                    Some(json!({ "repository_id": repository_id })),
                ));
            };
            if adopted_repository_ids
                .iter()
                .any(|id| id == &workspace.repository_id)
            {
                return Ok(vec![workspace]);
            }
            return Err(Self::resource_not_found(
                "current repository is not adopted for this session",
                Some(json!({
                    "repository_id": repository_id,
                    "attached_repositories": adopted_repository_ids,
                    "hint": "Call workspace with next_params, then retry.",
                    "next_tool": "workspace",
                    "next_params": { "repository_id": repository_id },
                })),
            ));
        }

        if adopted_repository_ids.is_empty() {
            let auto_adoptable_workspaces = self.auto_adoptable_workspaces();
            if let [workspace] = auto_adoptable_workspaces.as_slice() {
                self.adopt_workspace(workspace, true)?;
                return Ok(vec![workspace.clone()]);
            }
            if let Ok(current_dir) = std::env::current_dir() {
                let current_dir = current_dir.display().to_string();
                if let Ok((workspace, _, _, _)) = self.resolve_workspace_target(
                    Some(&current_dir),
                    None,
                    WorkspaceResolveMode::GitRoot,
                ) {
                    self.adopt_workspace(&workspace, true)?;
                    return Ok(vec![workspace]);
                }
            }
        }

        let registry = self
            .runtime_state
            .workspace_registry
            .read()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        let workspaces = adopted_repository_ids
            .into_iter()
            .filter_map(|repository_id| registry.workspace_by_repository_id(&repository_id))
            .collect::<Vec<_>>();
        if workspaces.is_empty() {
            return Err(Self::no_attached_workspaces_error("workspace"));
        }

        Ok(workspaces)
    }

    pub(super) fn roots_for_repository(
        &self,
        repository_id: Option<&str>,
    ) -> Result<Vec<(String, PathBuf)>, ErrorData> {
        Ok(self
            .attached_workspaces_for_repository(repository_id)?
            .into_iter()
            .map(|workspace| (workspace.repository_id, workspace.root))
            .collect())
    }

    pub(super) fn effective_attach_directory(path: &Path) -> Result<PathBuf, ErrorData> {
        if path.exists() {
            let metadata = fs::metadata(path).map_err(|err| {
                Self::invalid_params(
                    format!("failed to inspect attach path {}: {err}", path.display()),
                    Some(json!({ "path": path.display().to_string() })),
                )
            })?;
            let directory = if metadata.is_dir() {
                path.to_path_buf()
            } else {
                path.parent().map(Path::to_path_buf).ok_or_else(|| {
                    Self::invalid_params(
                        "workspace_attach path has no parent directory",
                        Some(json!({ "path": path.display().to_string() })),
                    )
                })?
            };
            return directory.canonicalize().map_err(|err| {
                Self::invalid_params(
                    format!(
                        "failed to canonicalize attach path {}: {err}",
                        directory.display()
                    ),
                    Some(json!({ "path": path.display().to_string() })),
                )
            });
        }

        Self::canonicalize_existing_ancestor(path)?.ok_or_else(|| {
            Self::invalid_params(
                "workspace_attach path does not exist and has no existing ancestor",
                Some(json!({ "path": path.display().to_string() })),
            )
        })
    }

    pub(super) fn find_git_root(start: &Path) -> Option<PathBuf> {
        start.ancestors().find_map(|ancestor| {
            ancestor
                .join(".git")
                .exists()
                .then(|| ancestor.to_path_buf())
        })
    }

    pub(super) fn relative_attach_path_has_parent(path: &Path) -> bool {
        path.components()
            .any(|component| matches!(component, std::path::Component::ParentDir))
    }

    pub(super) fn authorized_attach_roots(&self) -> Vec<PathBuf> {
        let mut roots = BTreeSet::new();
        for workspace in self.startup_workspaces() {
            roots.insert(workspace.root);
        }
        for workspace in self.attached_workspaces() {
            roots.insert(workspace.root);
        }
        if let Ok(current_dir) = std::env::current_dir() {
            let current_root = Self::find_git_root(&current_dir).unwrap_or(current_dir);
            roots.insert(
                current_root
                    .canonicalize()
                    .unwrap_or_else(|_| current_root.to_path_buf()),
            );
        }
        roots.into_iter().collect()
    }

    pub(super) fn authorize_attach_root(&self, root: &Path) -> Result<(), ErrorData> {
        let root = root.canonicalize().map_err(|err| {
            Self::invalid_params(
                format!(
                    "failed to canonicalize attach root {}: {err}",
                    root.display()
                ),
                Some(json!({ "path": root.display().to_string() })),
            )
        })?;
        let authorized_roots = self.authorized_attach_roots();
        if authorized_roots
            .iter()
            .any(|authorized_root| root.starts_with(authorized_root))
        {
            return Ok(());
        }

        Err(Self::access_denied(
            "workspace attach path is outside authorized workspace roots",
            Some(json!({
                "path": root.display().to_string(),
                "authorized_roots": authorized_roots
                    .iter()
                    .map(|root| root.display().to_string())
                    .collect::<Vec<_>>(),
            })),
        ))
    }
}