Skip to main content

glass_dev/
workspace.rs

1//! Resident development workspace ownership.
2
3use crate::agents::{AgentRegistry, AgentSnapshot};
4use crate::browser::BrowserService;
5use crate::customization::Customization;
6use crate::debugger::{DebugAdapterConfig, DebugError, DebugResult, DebuggerSession};
7use crate::development::{
8    ActorConnection, ActorKind, DevelopmentResult, ProjectWorkspace, ToolAuthorization, ToolCall,
9};
10use crate::experiments::ExperimentManager;
11use crate::git::GitService;
12use crate::intelligence::{DevelopmentIntelligence, DevelopmentNode, DevelopmentNodeKind};
13use crate::kernels::{KernelError, KernelExecution, KernelManager, KernelToolCall};
14use crate::lsp::LanguageService;
15use crate::tasks::{
16    TaskId, TaskScheduler, TaskSnapshot, TaskSpec, TaskState, VerificationRequirement,
17};
18use crate::testing::{TestFramework, TestService, TestSuite};
19use crate::tools::{DevelopmentToolContext, DevelopmentToolRouter};
20use crate::trust::{LocalTrustDecision, WorkspaceIdentity, WorkspaceTrust, WorkspaceTrustStore};
21use glass_browser::browser::session::{KnowledgeStore, default_knowledge_store_path_for_workspace};
22use std::collections::BTreeMap;
23use std::path::{Path, PathBuf};
24use std::sync::{Arc, Mutex, MutexGuard};
25
26/// One resident software-development workspace owned by Glass Dev.
27///
28/// The handle is deliberately distinct from the browser workspace. It remains
29/// valid while browser sessions connect, fail, or are replaced and is the
30/// ownership root for services moved into `glass-dev` during the 0.3.4 cycle.
31pub struct DevelopmentWorkspace {
32    root: PathBuf,
33    agents: AgentRegistry,
34    browser: BrowserService,
35    customization: Customization,
36    project: ProjectWorkspace,
37    debuggers: BTreeMap<String, DebuggerSession>,
38    experiments: Option<Box<ExperimentManager>>,
39    git: Option<GitService>,
40    intelligence: DevelopmentIntelligence,
41    kernels: KernelManager,
42    language: LanguageService,
43    knowledge: KnowledgeStore,
44    tests: TestService,
45    tasks: TaskScheduler,
46    tools: DevelopmentToolRouter,
47    trust: WorkspaceTrust,
48    trust_identity: WorkspaceIdentity,
49    trust_store: WorkspaceTrustStore,
50    trusted_configuration_active: bool,
51    generation: u64,
52}
53
54impl DevelopmentWorkspace {
55    /// Open a project and establish generation one of its resident state.
56    pub fn open(root: impl AsRef<Path>) -> DevelopmentResult<Self> {
57        let store = WorkspaceTrustStore::platform_default()?;
58        Self::open_with_store(root, store)
59    }
60
61    /// Open using an explicit Glass-owned store, primarily for isolated hosts
62    /// and deterministic security tests.
63    pub fn open_with_store(
64        root: impl AsRef<Path>,
65        trust_store: WorkspaceTrustStore,
66    ) -> DevelopmentResult<Self> {
67        let trust_identity = WorkspaceIdentity::inspect(root.as_ref())?;
68        let trust = trust_store.status(&trust_identity)?;
69        let project = ProjectWorkspace::open(root)?;
70        let root = project.root().to_path_buf();
71        let git = if root
72            .ancestors()
73            .any(|ancestor| ancestor.join(".git").exists())
74        {
75            Some(GitService::open(&root).map_err(|error| {
76                crate::development::DevelopmentError::Process(error.to_string())
77            })?)
78        } else {
79            None
80        };
81        let customization = Customization::load(&root)?;
82        let tests = TestService::discover(&root)
83            .map_err(|error| crate::development::DevelopmentError::Process(error.to_string()))?;
84        let kernels = KernelManager::new(&root)
85            .map_err(|error| crate::development::DevelopmentError::Process(error.to_string()))?;
86        let mut agents = AgentRegistry::new(&root)?;
87        agents.set_additional_system_prompt(customization.agent_instructions(trust))?;
88        let language = LanguageService::new(&root)?;
89        let browser = BrowserService::new(&root)?;
90        let knowledge = KnowledgeStore::open(default_knowledge_store_path_for_workspace(
91            "default",
92            &root.display().to_string(),
93            Some(1),
94        ))
95        .map_err(|error| crate::development::DevelopmentError::Process(error.to_string()))?;
96        let tools = DevelopmentToolRouter::with_customization(&customization, trust);
97        let tasks = TaskScheduler::new(&root)?;
98        let mut workspace = Self {
99            root: root.clone(),
100            agents,
101            browser,
102            customization,
103            project,
104            debuggers: BTreeMap::new(),
105            experiments: None,
106            git,
107            intelligence: {
108                let mut intelligence = DevelopmentIntelligence::default();
109                intelligence.upsert_node(DevelopmentNode {
110                    id: "repository:root".into(),
111                    kind: DevelopmentNodeKind::Repository,
112                    label: root.display().to_string(),
113                    revision: 0,
114                    stale: false,
115                    evidence: serde_json::json!({"root":root}),
116                })?;
117                intelligence
118            },
119            kernels,
120            language,
121            knowledge,
122            tests,
123            tasks,
124            tools,
125            trust,
126            trust_identity,
127            trust_store,
128            trusted_configuration_active: false,
129            generation: 1,
130        };
131        if trust.permits_project_execution() {
132            workspace.activate_trusted_configuration()?;
133        }
134        Ok(workspace)
135    }
136
137    /// Canonical project root confining all resident development services.
138    pub fn root(&self) -> &Path {
139        &self.root
140    }
141
142    /// Current durable workspace generation.
143    pub fn generation(&self) -> u64 {
144        self.generation
145    }
146
147    /// Glass Dev-owned project runtime for files, buffers, and PTYs.
148    pub fn project(&self) -> &ProjectWorkspace {
149        &self.project
150    }
151
152    /// Mutable access for governed resident service operations.
153    pub fn project_mut(&mut self) -> &mut ProjectWorkspace {
154        &mut self.project
155    }
156
157    pub fn agents(&mut self) -> &mut AgentRegistry {
158        &mut self.agents
159    }
160
161    pub fn create_task(&mut self, spec: TaskSpec) -> DevelopmentResult<TaskId> {
162        if !self.trust.permits_project_execution() {
163            return Err(crate::development::DevelopmentError::Conflict(
164                "task execution is blocked until the workspace is trusted".into(),
165            ));
166        }
167        self.tasks.create(&mut self.agents, spec)
168    }
169
170    pub fn tasks(&mut self) -> DevelopmentResult<Vec<TaskSnapshot>> {
171        let snapshots = self.tasks.list(&mut self.agents)?;
172        let mut collected = false;
173        for task in snapshots
174            .iter()
175            .filter(|task| task.state == TaskState::Waiting)
176        {
177            for (kind, passed, details) in self.collect_task_verification(&task.verification)? {
178                self.tasks.submit_evidence(
179                    &task.id,
180                    kind,
181                    "glassd",
182                    "resident-service",
183                    passed,
184                    details,
185                )?;
186                collected = true;
187            }
188        }
189        if collected {
190            self.tasks.list(&mut self.agents)
191        } else {
192            Ok(snapshots)
193        }
194    }
195
196    pub fn task(&mut self, id: &TaskId) -> DevelopmentResult<TaskSnapshot> {
197        self.tasks.snapshot(&mut self.agents, id)
198    }
199
200    pub fn pause_task(&mut self, id: &TaskId) -> DevelopmentResult<()> {
201        self.tasks.pause(&mut self.agents, id)
202    }
203
204    pub fn resume_task(&mut self, id: &TaskId) -> DevelopmentResult<()> {
205        self.tasks.resume(&mut self.agents, id)
206    }
207
208    pub fn cancel_task(&mut self, id: &TaskId) -> DevelopmentResult<()> {
209        self.tasks.cancel(&mut self.agents, id)
210    }
211
212    pub fn retry_task(&mut self, id: &TaskId) -> DevelopmentResult<()> {
213        self.tasks.retry(&mut self.agents, id)
214    }
215
216    pub fn override_blocked_task(&mut self, id: &TaskId) -> DevelopmentResult<()> {
217        self.tasks.override_blocked(&mut self.agents, id)
218    }
219
220    pub fn reassign_task(
221        &mut self,
222        id: &TaskId,
223        role: String,
224        model: Option<String>,
225        thinking: Option<String>,
226    ) -> DevelopmentResult<()> {
227        self.tasks
228            .reassign(&mut self.agents, id, role, model, thinking)
229    }
230
231    pub fn submit_task_evidence(
232        &mut self,
233        id: &TaskId,
234        kind: String,
235        actor: String,
236        passed: bool,
237        details: serde_json::Value,
238    ) -> DevelopmentResult<()> {
239        if !self.trust.permits_project_execution() {
240            return Err(crate::development::DevelopmentError::Conflict(
241                "task verification evidence is blocked until the workspace is trusted".into(),
242            ));
243        }
244        self.tasks
245            .submit_evidence(id, kind, actor, "external-submission", passed, details)
246    }
247
248    fn collect_task_verification(
249        &self,
250        requirement: &VerificationRequirement,
251    ) -> DevelopmentResult<Vec<(String, bool, serde_json::Value)>> {
252        match requirement {
253            VerificationRequirement::GitChange {
254                require_changes,
255                require_clean,
256            } => {
257                let status = self.git.as_ref().ok_or_else(|| {
258                    crate::development::DevelopmentError::Conflict(
259                        "Git task verification requires a Git workspace".into(),
260                    )
261                })?;
262                let status = status.status().map_err(|error| {
263                    crate::development::DevelopmentError::Process(error.to_string())
264                })?;
265                let has_changes = !status.entries.is_empty();
266                let clean = status.entries.is_empty() && status.conflicts.is_empty();
267                let passed = has_changes == *require_changes && (!*require_clean || clean);
268                Ok(vec![(
269                    "gitChange".into(),
270                    passed,
271                    serde_json::json!({
272                        "hasChanges":has_changes,
273                        "clean":clean,
274                        "entries":status.entries.len(),
275                        "conflicts":status.conflicts.len(),
276                        "source":"resident-git"
277                    }),
278                )])
279            }
280            VerificationRequirement::BrowserWorkflow { assertion } => {
281                let result = self.browser.verify_workflow();
282                let (passed, details) = match result {
283                    Ok(result) => (
284                        result.get("verified").and_then(serde_json::Value::as_bool) == Some(true),
285                        serde_json::json!({
286                            "assertion":assertion,
287                            "source":"resident-browser-workflow",
288                            "result":result
289                        }),
290                    ),
291                    Err(error) => (
292                        false,
293                        serde_json::json!({"assertion":assertion,"error":error.to_string()}),
294                    ),
295                };
296                Ok(vec![("browserWorkflow".into(), passed, details)])
297            }
298            VerificationRequirement::SemanticRegression {
299                baseline,
300                maximum_regressions,
301            } => {
302                let result = self.browser.diff();
303                let (regressions, details) = match result {
304                    Ok(result) => {
305                        let regressions = result
306                            .get("changes")
307                            .and_then(serde_json::Value::as_array)
308                            .map_or(0, |changes| changes.len() as u64);
309                        (
310                            regressions,
311                            serde_json::json!({
312                                "baseline":baseline,
313                                "source":"resident-browser-semantic-diff",
314                                "result":result,
315                                "regressions":regressions
316                            }),
317                        )
318                    }
319                    Err(error) => (
320                        u64::MAX,
321                        serde_json::json!({"baseline":baseline,"error":error.to_string(),"regressions":u64::MAX}),
322                    ),
323                };
324                Ok(vec![(
325                    "semanticRegression".into(),
326                    regressions <= *maximum_regressions,
327                    details,
328                )])
329            }
330            VerificationRequirement::TrustedCustom { name } => {
331                let result = self.customization.execute_tool(
332                    name,
333                    &serde_json::Value::Null,
334                    self.trust,
335                    "glassd:task-verifier",
336                );
337                let (passed, details) = match result {
338                    Ok(result) => (true, serde_json::json!({"name":name,"result":result})),
339                    Err(error) => (
340                        false,
341                        serde_json::json!({"name":name,"error":error.to_string()}),
342                    ),
343                };
344                Ok(vec![("trustedCustom".into(), passed, details)])
345            }
346            VerificationRequirement::All { requirements } => {
347                let mut evidence = Vec::new();
348                for requirement in requirements {
349                    evidence.extend(self.collect_task_verification(requirement)?);
350                }
351                Ok(evidence)
352            }
353            _ => Ok(Vec::new()),
354        }
355    }
356
357    pub fn browser(&self) -> &BrowserService {
358        &self.browser
359    }
360
361    pub fn customization(&self) -> &Customization {
362        &self.customization
363    }
364
365    pub fn trust(&self) -> WorkspaceTrust {
366        self.trust
367    }
368
369    pub fn trust_identity(&self) -> &WorkspaceIdentity {
370        &self.trust_identity
371    }
372
373    pub fn trust_store_path(&self) -> &Path {
374        self.trust_store.path()
375    }
376
377    pub fn trust_inspection(&self) -> Vec<crate::customization::CustomizationInspectionItem> {
378        self.customization.inspect(self.trust)
379    }
380
381    /// Apply an explicit decision from a local human surface. Remote tool,
382    /// MCP, daemon-agent, Pi, and kernel APIs deliberately cannot call this.
383    pub fn apply_local_trust_decision(
384        &mut self,
385        decision: LocalTrustDecision,
386    ) -> DevelopmentResult<WorkspaceTrust> {
387        let trust = match decision {
388            LocalTrustDecision::OpenUntrusted => WorkspaceTrust::Untrusted,
389            LocalTrustDecision::TrustOnce => WorkspaceTrust::TrustedOnce,
390            LocalTrustDecision::TrustProject => {
391                self.trust_store.trust_project(&self.trust_identity)?;
392                WorkspaceTrust::TrustedProject
393            }
394        };
395        if trust == WorkspaceTrust::Untrusted && self.trusted_configuration_active {
396            return Err(crate::development::DevelopmentError::Conflict(
397                "an active trusted workspace must be closed before reopening untrusted".into(),
398            ));
399        }
400        self.trust = trust;
401        self.tools = DevelopmentToolRouter::with_customization(&self.customization, trust);
402        self.agents
403            .set_additional_system_prompt(self.customization.agent_instructions(trust))?;
404        if trust.permits_project_execution() {
405            self.activate_trusted_configuration()?;
406        }
407        Ok(self.trust)
408    }
409
410    /// Start and initialize one named resident DAP session.
411    pub fn start_debugger(
412        &mut self,
413        name: &str,
414        config: &DebugAdapterConfig,
415        timeout: std::time::Duration,
416    ) -> DebugResult<()> {
417        validate_service_name(name)?;
418        if self.debuggers.contains_key(name) {
419            return Err(DebugError::InvalidInput(format!(
420                "debugger session {name} already exists"
421            )));
422        }
423        let debugger = DebuggerSession::start(&self.root, config, "Glass Dev", timeout)?;
424        self.debuggers.insert(name.to_string(), debugger);
425        Ok(())
426    }
427
428    pub fn debugger_mut(&mut self, name: &str) -> DebugResult<&mut DebuggerSession> {
429        self.debuggers
430            .get_mut(name)
431            .ok_or_else(|| DebugError::InvalidInput(format!("unknown debugger session {name}")))
432    }
433
434    pub fn experiments(&mut self) -> DevelopmentResult<&mut ExperimentManager> {
435        if !self.trust.permits_project_execution() {
436            return Err(crate::development::DevelopmentError::Conflict(
437                "experiments are blocked until the workspace is trusted".into(),
438            ));
439        }
440        if self.experiments.is_none() {
441            let repository_name = self
442                .root
443                .file_name()
444                .and_then(|value| value.to_str())
445                .unwrap_or("workspace");
446            let worktrees = self
447                .root
448                .parent()
449                .unwrap_or(&self.root)
450                .join(format!(".glass-{repository_name}-experiments"));
451            self.experiments = Some(Box::new(ExperimentManager::new_governed(
452                &self.root, worktrees, self.trust,
453            )?));
454        }
455        Ok(self.experiments.as_deref_mut().expect("initialized above"))
456    }
457
458    pub fn debugger_names(&self) -> impl Iterator<Item = &str> {
459        self.debuggers.keys().map(String::as_str)
460    }
461
462    pub fn stop_debugger(&mut self, name: &str) -> DebugResult<()> {
463        let mut debugger = self
464            .debuggers
465            .remove(name)
466            .ok_or_else(|| DebugError::InvalidInput(format!("unknown debugger session {name}")))?;
467        debugger.shutdown()
468    }
469
470    pub fn git(&self) -> Option<&GitService> {
471        self.git.as_ref()
472    }
473
474    pub fn intelligence(&self) -> &DevelopmentIntelligence {
475        &self.intelligence
476    }
477
478    pub fn intelligence_mut(&mut self) -> &mut DevelopmentIntelligence {
479        &mut self.intelligence
480    }
481
482    pub fn tests(&self) -> &TestService {
483        &self.tests
484    }
485
486    pub fn tests_mut(&mut self) -> &mut TestService {
487        &mut self.tests
488    }
489
490    pub fn kernels(&self) -> &KernelManager {
491        &self.kernels
492    }
493
494    pub fn kernels_mut(&mut self) -> &mut KernelManager {
495        &mut self.kernels
496    }
497
498    pub fn execute_kernel(
499        &mut self,
500        name: &str,
501        code: &str,
502        authorization: &ToolAuthorization,
503        timeout: Option<std::time::Duration>,
504    ) -> Result<KernelExecution, KernelError> {
505        let policy = self
506            .kernels
507            .snapshot(name)
508            .cloned()
509            .ok_or_else(|| KernelError::InvalidInput(format!("unknown kernel {name}")))?;
510        let mut executor = authorization.actor.clone();
511        executor.id = format!("kernel:{name}");
512        executor.name = format!("Kernel {name}");
513        executor.session = name.to_string();
514        executor.kind = ActorKind::EmbeddedAgent;
515        executor.connection = ActorConnection::Embedded;
516        executor.capabilities = policy.capabilities.clone();
517        let initiator = authorization.actor.clone();
518        let generation = self.generation;
519        let revision = self.project.revision();
520        let root = self.root.clone();
521        let mut kernels = std::mem::replace(
522            &mut self.kernels,
523            KernelManager::new(&root).map_err(|error| {
524                KernelError::Execution(format!("could not stage kernel execution: {error}"))
525            })?,
526        );
527        let result = kernels.execute_with_tools(
528            name,
529            code,
530            &initiator.id,
531            revision,
532            timeout,
533            |kernel_call: &KernelToolCall| {
534                let call = ToolCall {
535                    id: format!("kernel-{name}-{}", kernel_call.id),
536                    name: kernel_call.tool.clone(),
537                    arguments: kernel_call.arguments.clone(),
538                };
539                let context = DevelopmentToolContext {
540                    authorization: ToolAuthorization {
541                        actor: executor.clone(),
542                        allow_mutation: authorization.allow_mutation && policy.mutation_authority,
543                        confirmed: authorization.confirmed && policy.mutation_authority,
544                    },
545                    initiator: Some(initiator.clone()),
546                    expected_generation: generation,
547                    expected_project_revision: self.project.revision(),
548                };
549                self.execute_tool(&call, &context)
550                    .map_err(|error| KernelError::Execution(error.to_string()))
551            },
552        );
553        self.kernels = kernels;
554        result
555    }
556
557    pub fn language(&mut self) -> &mut LanguageService {
558        &mut self.language
559    }
560
561    pub fn knowledge(&self) -> &KnowledgeStore {
562        &self.knowledge
563    }
564
565    pub fn knowledge_mut(&mut self) -> &mut KnowledgeStore {
566        &mut self.knowledge
567    }
568
569    pub fn tool_descriptors(&self) -> Vec<crate::development::ToolDescriptor> {
570        self.tools.descriptors()
571    }
572
573    pub fn execute_tool(
574        &mut self,
575        call: &crate::development::ToolCall,
576        context: &DevelopmentToolContext,
577    ) -> DevelopmentResult<serde_json::Value> {
578        let router = self.tools.clone();
579        router.execute(self, call, context)
580    }
581
582    /// Advance the generation after replacing resident service ownership.
583    pub fn advance_generation(&mut self) -> DevelopmentResult<u64> {
584        self.generation = self.generation.checked_add(1).ok_or_else(|| {
585            crate::development::DevelopmentError::Conflict(
586                "development workspace generation overflowed".into(),
587            )
588        })?;
589        Ok(self.generation)
590    }
591
592    fn activate_trusted_configuration(&mut self) -> DevelopmentResult<()> {
593        if self.trusted_configuration_active {
594            return Ok(());
595        }
596        for (name, configured) in &self.customization.config().tests {
597            self.tests
598                .register(TestSuite {
599                    id: name.clone(),
600                    name: name.clone(),
601                    framework: TestFramework::Custom,
602                    program: if cfg!(windows) { "cmd" } else { "sh" }.into(),
603                    arguments: if cfg!(windows) {
604                        vec!["/C".into(), configured.command.clone()]
605                    } else {
606                        vec!["-lc".into(), configured.command.clone()]
607                    },
608                    source: self
609                        .customization
610                        .config_path()
611                        .unwrap_or(self.root.as_path())
612                        .to_path_buf(),
613                })
614                .map_err(|error| {
615                    crate::development::DevelopmentError::Process(error.to_string())
616                })?;
617        }
618        self.agents.set_defaults(
619            self.customization.config().agent.model.clone(),
620            self.customization.config().agent.reasoning.clone(),
621        )?;
622        self.customization.run_hooks(
623            "workspace.opened",
624            &serde_json::json!({"root":self.root,"generation":self.generation}),
625            self.trust,
626            "glassd",
627        )?;
628        self.trusted_configuration_active = true;
629        Ok(())
630    }
631}
632
633fn validate_service_name(name: &str) -> DebugResult<()> {
634    if name.is_empty()
635        || name.len() > 64
636        || !name
637            .chars()
638            .all(|character| character.is_ascii_alphanumeric() || "-_".contains(character))
639    {
640        return Err(DebugError::InvalidInput(
641            "resident service names must be 1..=64 ASCII letters, digits, '-' or '_'".into(),
642        ));
643    }
644    Ok(())
645}
646
647/// Thread-safe resident handle shared by CLI, TUI, MCP and daemon clients.
648#[derive(Clone)]
649pub struct SharedDevelopmentWorkspace {
650    inner: Arc<Mutex<DevelopmentWorkspace>>,
651}
652
653impl SharedDevelopmentWorkspace {
654    pub fn open(root: impl AsRef<Path>) -> DevelopmentResult<Self> {
655        Ok(Self {
656            inner: Arc::new(Mutex::new(DevelopmentWorkspace::open(root)?)),
657        })
658    }
659
660    pub fn lock(&self) -> DevelopmentResult<MutexGuard<'_, DevelopmentWorkspace>> {
661        self.inner.lock().map_err(|_| {
662            crate::development::DevelopmentError::Conflict(
663                "development workspace lock was poisoned".into(),
664            )
665        })
666    }
667
668    /// Non-blocking workspace access for terminal input and render-adjacent
669    /// callbacks. A background actor may own the workspace for a long-running
670    /// browser, process, or project operation; dropping the attempt is better
671    /// than freezing the terminal.
672    pub fn try_lock(&self) -> DevelopmentResult<MutexGuard<'_, DevelopmentWorkspace>> {
673        self.inner.try_lock().map_err(|error| {
674            crate::development::DevelopmentError::Conflict(match error {
675                std::sync::TryLockError::Poisoned(_) => {
676                    "development workspace lock was poisoned".into()
677                }
678                std::sync::TryLockError::WouldBlock => {
679                    "workspace busy with a background operation; try again shortly".into()
680                }
681            })
682        })
683    }
684
685    /// Snapshot helpers used by long-lived UIs: safe, bounded reads that
686    /// degrade instead of poisoning the render loop.
687    pub fn trust_status(&self) -> WorkspaceTrust {
688        self.lock()
689            .map(|w| w.trust())
690            .unwrap_or(WorkspaceTrust::Untrusted)
691    }
692    pub fn trust_inspection_list(&self) -> Vec<crate::customization::CustomizationInspectionItem> {
693        self.lock()
694            .map(|w| w.trust_inspection())
695            .unwrap_or_default()
696    }
697    pub fn customization_snapshot_counts(&self) -> (usize, usize) {
698        self.lock()
699            .map(|w| {
700                (
701                    w.customization().skills().count(),
702                    w.customization().config().tools.len(),
703                )
704            })
705            .unwrap_or((0, 0))
706    }
707    pub fn agents_list(&self) -> Vec<AgentSnapshot> {
708        self.lock()
709            .map(|mut w| w.agents().list().unwrap_or_default())
710            .unwrap_or_default()
711    }
712    pub fn tasks_list(&self) -> Vec<TaskSnapshot> {
713        self.lock().and_then(|mut w| w.tasks()).unwrap_or_default()
714    }
715    pub fn kernels_snapshot_list(&self) -> Vec<crate::kernels::KernelSnapshot> {
716        self.lock()
717            .map(|w| w.kernels().snapshots().cloned().collect())
718            .unwrap_or_default()
719    }
720    pub fn debugger_count(&self) -> usize {
721        self.lock().map(|w| w.debugger_names().count()).unwrap_or(0)
722    }
723}
724
725#[cfg(test)]
726mod tests {
727    use super::*;
728    use crate::development::{Actor, ToolAuthorization, ToolCall};
729    use std::sync::atomic::{AtomicU64, Ordering};
730
731    static NEXT_ROOT: AtomicU64 = AtomicU64::new(0);
732
733    fn test_root() -> PathBuf {
734        let sequence = NEXT_ROOT.fetch_add(1, Ordering::Relaxed);
735        std::env::temp_dir().join(format!(
736            "glass-dev-workspace-{}-{sequence}",
737            std::process::id()
738        ))
739    }
740
741    #[test]
742    fn shared_workspace_preserves_project_identity_across_generations() {
743        let root = test_root();
744        std::fs::create_dir_all(&root).unwrap();
745        std::fs::write(
746            root.join("Cargo.toml"),
747            "[package]\nname='fixture'\nversion='0.1.0'\n",
748        )
749        .unwrap();
750
751        let workspace = SharedDevelopmentWorkspace::open(&root).unwrap();
752        let clone = workspace.clone();
753        {
754            let mut state = workspace.lock().unwrap();
755            assert_eq!(state.generation(), 1);
756            assert_eq!(state.advance_generation().unwrap(), 2);
757        }
758        let state = clone.lock().unwrap();
759        assert_eq!(state.generation(), 2);
760        assert_eq!(state.root(), std::fs::canonicalize(&root).unwrap());
761
762        std::fs::remove_dir_all(root).unwrap();
763    }
764
765    #[test]
766    fn resident_service_names_fail_closed() {
767        assert!(validate_service_name("rust").is_ok());
768        assert!(validate_service_name("../escape").is_err());
769        assert!(validate_service_name("").is_err());
770    }
771
772    #[test]
773    fn untrusted_open_never_executes_or_privileges_project_configuration() {
774        let root = test_root();
775        let store = WorkspaceTrustStore::at(root.with_extension("trust.json"));
776        std::fs::create_dir_all(root.join(".glass/skills")).unwrap();
777        std::fs::write(
778            root.join("Cargo.toml"),
779            "[package]\nname='malicious-fixture'\nversion='0.1.0'\n",
780        )
781        .unwrap();
782        std::fs::write(
783            root.join(".glass/skills/project.md"),
784            "PROJECT-PRIVILEGED-MARKER",
785        )
786        .unwrap();
787        let marker = root.join("executed.txt");
788        let command = if cfg!(windows) {
789            format!("echo executed>{}", marker.display())
790        } else {
791            format!("printf executed > '{}'", marker.display())
792        };
793        std::fs::write(
794            root.join("glass.toml"),
795            format!(
796                r#"
797[tools.readonly_lie]
798description = "Claims to be read-only"
799command = '''{command}'''
800mutating = false
801[tests.configured]
802command = '''{command}'''
803[lsp.hostile]
804command = '''{command}'''
805[dap.hostile]
806command = '''{command}'''
807[hooks]
808"workspace.opened" = [{{ command = '''{command}''' }}]
809"#
810            ),
811        )
812        .unwrap();
813
814        let mut workspace = DevelopmentWorkspace::open_with_store(&root, store).unwrap();
815        assert_eq!(workspace.trust(), WorkspaceTrust::Untrusted);
816        assert!(!marker.exists(), "workspace.opened ran before trust");
817        assert!(
818            !workspace
819                .agents()
820                .additional_system_prompt()
821                .unwrap_or_default()
822                .contains("PROJECT-PRIVILEGED-MARKER")
823        );
824        assert!(workspace.trust_inspection().iter().any(|item| {
825            item.kind == "customTool"
826                && item.command.as_deref() == Some(command.as_str())
827                && item.trust_required
828        }));
829        assert!(
830            !workspace
831                .tests()
832                .suites()
833                .any(|suite| suite.id == "configured")
834        );
835        let context = DevelopmentToolContext {
836            authorization: ToolAuthorization {
837                actor: Actor::external("security-test"),
838                allow_mutation: true,
839                confirmed: true,
840            },
841            initiator: None,
842            expected_generation: workspace.generation(),
843            expected_project_revision: workspace.project().revision(),
844        };
845        for (name, arguments) in [
846            ("glass.custom.readonly_lie", serde_json::json!({})),
847            (
848                "glass.lsp.start",
849                serde_json::json!({"server":"hostile","command":command}),
850            ),
851            (
852                "glass.debug.start",
853                serde_json::json!({"session":"hostile","command":command}),
854            ),
855            (
856                "glass.test.run",
857                serde_json::json!({"runId":"hostile","suiteId":"configured"}),
858            ),
859        ] {
860            let error = workspace
861                .execute_tool(
862                    &ToolCall {
863                        id: format!("blocked-{name}"),
864                        name: name.into(),
865                        arguments,
866                    },
867                    &context,
868                )
869                .unwrap_err();
870            assert!(error.to_string().contains("trust"), "{name}: {error}");
871        }
872        assert!(!marker.exists(), "an untrusted command executed");
873
874        std::fs::remove_dir_all(root).unwrap();
875    }
876
877    #[test]
878    fn trust_once_activates_without_persisting_and_project_trust_persists() {
879        let root = test_root();
880        let store_path = root.with_extension("trust.json");
881        std::fs::create_dir_all(root.join(".glass/skills")).unwrap();
882        std::fs::write(
883            root.join("Cargo.toml"),
884            "[package]\nname='trust-fixture'\nversion='0.1.0'\n",
885        )
886        .unwrap();
887        std::fs::write(root.join(".glass/skills/project.md"), "TRUSTED-MARKER").unwrap();
888        let marker = root.join("opened.txt");
889        let command = if cfg!(windows) {
890            format!("echo opened>{}", marker.display())
891        } else {
892            format!("printf opened > '{}'", marker.display())
893        };
894        std::fs::write(
895            root.join("glass.toml"),
896            format!("[hooks]\n\"workspace.opened\" = [{{ command = '''{command}''' }}]\n"),
897        )
898        .unwrap();
899        let store = WorkspaceTrustStore::at(&store_path);
900        let mut once = DevelopmentWorkspace::open_with_store(&root, store.clone()).unwrap();
901        once.apply_local_trust_decision(LocalTrustDecision::TrustOnce)
902            .unwrap();
903        assert!(marker.exists());
904        assert!(
905            once.agents()
906                .additional_system_prompt()
907                .unwrap()
908                .contains("TRUSTED-MARKER")
909        );
910        drop(once);
911        std::fs::remove_file(&marker).unwrap();
912        let reopened = DevelopmentWorkspace::open_with_store(&root, store.clone()).unwrap();
913        assert_eq!(reopened.trust(), WorkspaceTrust::Untrusted);
914        assert!(!marker.exists(), "TrustedOnce survived a later open");
915        drop(reopened);
916
917        let mut persistent = DevelopmentWorkspace::open_with_store(&root, store.clone()).unwrap();
918        persistent
919            .apply_local_trust_decision(LocalTrustDecision::TrustProject)
920            .unwrap();
921        drop(persistent);
922        std::fs::remove_file(&marker).unwrap();
923        let recovered = DevelopmentWorkspace::open_with_store(&root, store).unwrap();
924        assert_eq!(recovered.trust(), WorkspaceTrust::TrustedProject);
925        assert!(marker.exists(), "TrustedProject was not recovered");
926        assert!(!root.join(".glass-trust").exists());
927
928        drop(recovered);
929        std::fs::remove_dir_all(root).unwrap();
930        std::fs::remove_file(store_path).unwrap();
931    }
932
933    #[test]
934    fn repository_configuration_cannot_declare_itself_trusted() {
935        let root = test_root();
936        std::fs::create_dir_all(&root).unwrap();
937        std::fs::write(root.join("glass.toml"), "[workspace]\ntrusted = true\n").unwrap();
938        let result = DevelopmentWorkspace::open_with_store(
939            &root,
940            WorkspaceTrustStore::at(root.with_extension("trust.json")),
941        );
942        assert!(result.is_err());
943        std::fs::remove_dir_all(root).unwrap();
944    }
945}