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