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, EditorProposalState, ProjectWorkspace,
9    ToolAuthorization, 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    CrewWake, CrewWakeLiveEvidence, CrewWakeMember, TaskId, TaskScheduler, TaskSnapshot, TaskSpec,
19    TaskState, VerificationRequirement, persist_crew_wake,
20};
21use crate::testing::{TestFramework, TestService, TestSuite};
22use crate::tools::{DevelopmentToolContext, DevelopmentToolRouter};
23use crate::trust::{LocalTrustDecision, WorkspaceIdentity, WorkspaceTrust, WorkspaceTrustStore};
24use glass_browser::browser::policy::PolicyPreset;
25use glass_browser::browser::session::{KnowledgeStore, default_knowledge_store_path_for_workspace};
26use std::collections::BTreeMap;
27use std::path::{Path, PathBuf};
28use std::sync::{Arc, Mutex, MutexGuard};
29
30/// One resident software-development workspace owned by Glass Dev.
31///
32/// The handle is deliberately distinct from the browser workspace. It remains
33/// valid while browser sessions connect, fail, or are replaced and is the
34/// ownership root for services moved into `glass-dev` during the 0.3.4 cycle.
35pub struct DevelopmentWorkspace {
36    root: PathBuf,
37    agents: AgentRegistry,
38    browser: BrowserService,
39    customization: Customization,
40    project: ProjectWorkspace,
41    debuggers: BTreeMap<String, DebuggerSession>,
42    experiments: Option<Box<ExperimentManager>>,
43    git: Option<GitService>,
44    intelligence: DevelopmentIntelligence,
45    kernels: KernelManager,
46    language: LanguageService,
47    knowledge: KnowledgeStore,
48    tests: TestService,
49    tasks: TaskScheduler,
50    tools: DevelopmentToolRouter,
51    trust: WorkspaceTrust,
52    trust_identity: WorkspaceIdentity,
53    trust_store: WorkspaceTrustStore,
54    trusted_configuration_active: bool,
55    generation: u64,
56    agent_turn_mode: AgentTurnMode,
57}
58
59/// Per-turn composer personality for the shared chat dock.
60///
61/// Ask inspects only. Plan writes a bounded numbered plan and does not mutate.
62/// Agent is the default and is the only mode that may edit, run, or act.
63#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
64#[serde(rename_all = "camelCase")]
65pub enum AgentTurnMode {
66    Ask,
67    Plan,
68    #[default]
69    Agent,
70}
71
72impl AgentTurnMode {
73    pub fn label(self) -> &'static str {
74        match self {
75            Self::Ask => "Ask",
76            Self::Plan => "Plan",
77            Self::Agent => "Agent",
78        }
79    }
80
81    pub fn allows_mutation(self) -> bool {
82        matches!(self, Self::Agent)
83    }
84
85    pub fn next(self) -> Self {
86        match self {
87            Self::Ask => Self::Plan,
88            Self::Plan => Self::Agent,
89            Self::Agent => Self::Ask,
90        }
91    }
92
93    pub fn instruction(self) -> &'static str {
94        match self {
95            Self::Ask => {
96                "[Glass Ask mode: read-only. Inspect evidence only. Do not edit files, run mutating commands, or act in the browser.]"
97            }
98            Self::Plan => {
99                "[Glass Plan mode: inspect only. Write a bounded numbered plan with files, risks, and verify predicates. Do not edit, click, or deploy until the human accepts.]"
100            }
101            Self::Agent => "",
102        }
103    }
104}
105
106impl DevelopmentWorkspace {
107    /// Open a project and establish generation one of its resident state.
108    pub fn open(root: impl AsRef<Path>) -> DevelopmentResult<Self> {
109        Self::open_with_policy(root, PolicyPreset::Development)
110    }
111
112    /// Open with an explicit browser authorization preset.
113    pub fn open_with_policy(
114        root: impl AsRef<Path>,
115        policy_preset: PolicyPreset,
116    ) -> DevelopmentResult<Self> {
117        let store = WorkspaceTrustStore::platform_default()?;
118        Self::open_with_store_and_policy(root, store, policy_preset)
119    }
120
121    /// Open using an explicit Glass-owned store, primarily for isolated hosts
122    /// and deterministic security tests.
123    pub fn open_with_store(
124        root: impl AsRef<Path>,
125        trust_store: WorkspaceTrustStore,
126    ) -> DevelopmentResult<Self> {
127        Self::open_with_store_and_policy(root, trust_store, PolicyPreset::Development)
128    }
129
130    /// Open using an explicit trust store and browser authorization preset.
131    pub fn open_with_store_and_policy(
132        root: impl AsRef<Path>,
133        trust_store: WorkspaceTrustStore,
134        policy_preset: PolicyPreset,
135    ) -> DevelopmentResult<Self> {
136        let trust_identity = WorkspaceIdentity::inspect(root.as_ref())?;
137        let trust = trust_store.status(&trust_identity)?;
138        let project = ProjectWorkspace::open(root)?;
139        let root = project.root().to_path_buf();
140        let git = if root
141            .ancestors()
142            .any(|ancestor| ancestor.join(".git").exists())
143        {
144            Some(GitService::open(&root).map_err(|error| {
145                crate::development::DevelopmentError::Process(error.to_string())
146            })?)
147        } else {
148            None
149        };
150        let customization = Customization::load(&root)?;
151        let tests = TestService::discover(&root)
152            .map_err(|error| crate::development::DevelopmentError::Process(error.to_string()))?;
153        let kernels = KernelManager::new(&root)
154            .map_err(|error| crate::development::DevelopmentError::Process(error.to_string()))?;
155        let mut agents = AgentRegistry::new(&root)?;
156        agents.set_additional_system_prompt(customization.agent_instructions(trust))?;
157        let browser = BrowserService::new_with_policy(&root, policy_preset)?;
158        let language = LanguageService::new(&root)?;
159        let knowledge = KnowledgeStore::open(default_knowledge_store_path_for_workspace(
160            "default",
161            &root.display().to_string(),
162            Some(1),
163        ))
164        .map_err(|error| crate::development::DevelopmentError::Process(error.to_string()))?;
165        let tools = DevelopmentToolRouter::with_customization(&customization, trust);
166        let tasks = TaskScheduler::new(&root)?;
167        let mut workspace = Self {
168            root: root.clone(),
169            agents,
170            browser,
171            customization,
172            project,
173            debuggers: BTreeMap::new(),
174            experiments: None,
175            git,
176            intelligence: {
177                let mut intelligence = DevelopmentIntelligence::default();
178                intelligence.upsert_node(DevelopmentNode {
179                    id: "repository:root".into(),
180                    kind: DevelopmentNodeKind::Repository,
181                    label: root.display().to_string(),
182                    revision: 0,
183                    stale: false,
184                    evidence: serde_json::json!({"root":root}),
185                })?;
186                intelligence
187            },
188            kernels,
189            language,
190            knowledge,
191            tests,
192            tasks,
193            tools,
194            trust,
195            trust_identity,
196            trust_store,
197            trusted_configuration_active: false,
198            generation: 1,
199            agent_turn_mode: AgentTurnMode::Agent,
200        };
201        if trust.permits_project_execution() {
202            workspace.activate_trusted_configuration()?;
203        }
204        Ok(workspace)
205    }
206
207    /// Canonical project root confining all resident development services.
208    pub fn root(&self) -> &Path {
209        &self.root
210    }
211
212    /// Current durable workspace generation.
213    pub fn generation(&self) -> u64 {
214        self.generation
215    }
216
217    /// Glass Dev-owned project runtime for files, buffers, and PTYs.
218    pub fn project(&self) -> &ProjectWorkspace {
219        &self.project
220    }
221
222    /// Mutable access for governed resident service operations.
223    pub fn project_mut(&mut self) -> &mut ProjectWorkspace {
224        &mut self.project
225    }
226
227    pub fn agents(&mut self) -> &mut AgentRegistry {
228        &mut self.agents
229    }
230
231    pub fn todos(&self) -> crate::SessionTodoList {
232        crate::SessionTodoList::load(&self.root)
233    }
234
235    pub fn write_todos(
236        &mut self,
237        items: Vec<crate::SessionTodo>,
238    ) -> crate::development::DevelopmentResult<crate::SessionTodoList> {
239        let mut list = self.todos();
240        list.write(items, &self.root)?;
241        Ok(list)
242    }
243
244    pub fn complete_todo(
245        &mut self,
246        id: &str,
247    ) -> crate::development::DevelopmentResult<crate::SessionTodo> {
248        let mut list = self.todos();
249        let item = list.complete(id, &self.root)?;
250        Ok(item)
251    }
252
253    pub fn activate_todo(
254        &mut self,
255        id: &str,
256    ) -> crate::development::DevelopmentResult<crate::SessionTodo> {
257        let mut list = self.todos();
258        let item = list.activate(id, &self.root)?;
259        Ok(item)
260    }
261
262    pub fn seed_todos_from_plan(
263        &mut self,
264        goal: &str,
265        body: &str,
266    ) -> crate::development::DevelopmentResult<crate::SessionTodoList> {
267        let mut list = self.todos();
268        list.seed_from_plan(goal, body, &self.root)?;
269        Ok(list)
270    }
271
272    pub fn create_task(&mut self, spec: TaskSpec) -> DevelopmentResult<TaskId> {
273        if !self.trust.permits_project_execution() {
274            return Err(crate::development::DevelopmentError::Conflict(
275                "task execution is blocked until the workspace is trusted".into(),
276            ));
277        }
278        self.tasks.create(&mut self.agents, spec)
279    }
280
281    /// Queue the overnight factory crew in a confined worktree when Git is available.
282    pub fn create_crew(&mut self, goal: &str) -> DevelopmentResult<CrewWake> {
283        if !self.trust.permits_project_execution() {
284            return Err(crate::development::DevelopmentError::Conflict(
285                "task execution is blocked until the workspace is trusted".into(),
286            ));
287        }
288        let checkpoint_name = {
289            let mut name = format!("before-crew:{goal}");
290            name.truncate(256);
291            name
292        };
293        let _ = self
294            .project
295            .create_editor_checkpoint(checkpoint_name.clone(), crate::development::Actor::local());
296        let slug = crew_slug(goal);
297        let worktree = self.prepare_crew_worktree(&slug)?;
298        let implementer_trees = ["a", "b"]
299            .into_iter()
300            .filter_map(|label| {
301                self.prepare_crew_worktree(&format!("{slug}-{label}"))
302                    .ok()
303                    .flatten()
304            })
305            .collect::<Vec<_>>();
306        let unrestricted = self.agents.default_unrestricted();
307        let ids = self.tasks.create_crew(
308            &mut self.agents,
309            goal,
310            worktree.clone(),
311            implementer_trees,
312            unrestricted,
313        )?;
314        let tasks = ids
315            .into_iter()
316            .map(|id| {
317                self.tasks
318                    .snapshot(&mut self.agents, &id)
319                    .map(|snapshot| CrewWakeMember {
320                        id: snapshot.id.as_str().to_string(),
321                        role: snapshot.role,
322                        title: snapshot.title,
323                        state: snapshot.state.label().to_string(),
324                        worktree: Some(snapshot.worktree.display().to_string()),
325                    })
326            })
327            .collect::<DevelopmentResult<Vec<_>>>()?;
328        let wake = CrewWake {
329            id: slug,
330            goal: goal.to_string(),
331            worktree: worktree.map(|path| path.display().to_string()),
332            checkpoint: checkpoint_name,
333            created_at_ms: std::time::SystemTime::now()
334                .duration_since(std::time::UNIX_EPOCH)
335                .map(|duration| duration.as_millis())
336                .unwrap_or(0),
337            tasks,
338            ..CrewWake::default()
339        };
340        persist_crew_wake(&self.root, &wake)?;
341        Ok(wake)
342    }
343
344    /// Latest overnight crew wake written under `.glass/crew`.
345    pub fn latest_crew_wake(&self) -> Option<CrewWake> {
346        crate::load_latest_crew_wake(&self.root)
347    }
348
349    /// Fold live git/test/verify/page evidence into the persisted crew wake.
350    pub fn refresh_crew_wake(
351        &mut self,
352        live: CrewWakeLiveEvidence,
353    ) -> DevelopmentResult<Option<CrewWake>> {
354        let Some(mut wake) = self.latest_crew_wake() else {
355            return Ok(None);
356        };
357        for member in &mut wake.tasks {
358            if let Ok(id) = TaskId::parse(&member.id)
359                && let Ok(snapshot) = self.tasks.snapshot(&mut self.agents, &id)
360            {
361                member.state = snapshot.state.label().to_string();
362            }
363        }
364        wake.diff = self
365            .git
366            .as_ref()
367            .and_then(|git| git.diff(false, None).ok())
368            .map(truncate_wake_text)
369            .unwrap_or_default();
370        wake.tests = format_last_test_run(&self.tests);
371        if let Some(verify) = live.verify.filter(|value| !value.trim().is_empty()) {
372            wake.verify = truncate_wake_text(verify);
373        }
374        if let Some(page) = live.page.filter(|value| !value.trim().is_empty()) {
375            wake.page = truncate_wake_text(page);
376        }
377        wake.accept = live
378            .accept
379            .filter(|value| !value.trim().is_empty())
380            .unwrap_or_else(|| {
381                self.project
382                    .editor_proposals()
383                    .into_iter()
384                    .find(|proposal| proposal.state == EditorProposalState::Pending)
385                    .map(|proposal| proposal.id)
386                    .unwrap_or_else(|| "none".into())
387            });
388        persist_crew_wake(&self.root, &wake)?;
389        Ok(Some(wake))
390    }
391
392    fn prepare_crew_worktree(&mut self, slug: &str) -> DevelopmentResult<Option<PathBuf>> {
393        let parent = self.root.join(".glass").join("worktrees");
394        std::fs::create_dir_all(&parent)?;
395        let path = parent.join(slug);
396        if let Some(git) = self.git.as_ref() {
397            let branch = format!("glass/crew/{slug}");
398            if git.create_worktree(&path, &branch, true).is_ok() {
399                return Ok(Some(path.canonicalize().unwrap_or(path)));
400            }
401        }
402        std::fs::create_dir_all(&path)?;
403        Ok(Some(path.canonicalize().unwrap_or(path)))
404    }
405
406    pub fn tasks(&mut self) -> DevelopmentResult<Vec<TaskSnapshot>> {
407        let snapshots = self.tasks.list(&mut self.agents)?;
408        let mut collected = false;
409        for task in snapshots
410            .iter()
411            .filter(|task| task.state == TaskState::Waiting)
412        {
413            for (kind, passed, details) in self.collect_task_verification(&task.verification)? {
414                self.tasks.submit_evidence(
415                    &task.id,
416                    kind,
417                    "glassd",
418                    "resident-service",
419                    passed,
420                    details,
421                )?;
422                collected = true;
423            }
424        }
425        if collected {
426            self.tasks.list(&mut self.agents)
427        } else {
428            Ok(snapshots)
429        }
430    }
431
432    pub fn task(&mut self, id: &TaskId) -> DevelopmentResult<TaskSnapshot> {
433        self.tasks.snapshot(&mut self.agents, id)
434    }
435
436    pub fn pause_task(&mut self, id: &TaskId) -> DevelopmentResult<()> {
437        self.tasks.pause(&mut self.agents, id)
438    }
439
440    pub fn resume_task(&mut self, id: &TaskId) -> DevelopmentResult<()> {
441        self.tasks.resume(&mut self.agents, id)
442    }
443
444    pub fn cancel_task(&mut self, id: &TaskId) -> DevelopmentResult<()> {
445        self.tasks.cancel(&mut self.agents, id)
446    }
447
448    pub fn retry_task(&mut self, id: &TaskId) -> DevelopmentResult<()> {
449        self.tasks.retry(&mut self.agents, id)
450    }
451
452    pub fn override_blocked_task(&mut self, id: &TaskId) -> DevelopmentResult<()> {
453        self.tasks.override_blocked(&mut self.agents, id)
454    }
455
456    pub fn reassign_task(
457        &mut self,
458        id: &TaskId,
459        role: String,
460        model: Option<String>,
461        thinking: Option<String>,
462    ) -> DevelopmentResult<()> {
463        self.tasks
464            .reassign(&mut self.agents, id, role, model, thinking)
465    }
466
467    pub fn submit_task_evidence(
468        &mut self,
469        id: &TaskId,
470        kind: String,
471        actor: String,
472        passed: bool,
473        details: serde_json::Value,
474    ) -> DevelopmentResult<()> {
475        if !self.trust.permits_project_execution() {
476            return Err(crate::development::DevelopmentError::Conflict(
477                "task verification evidence is blocked until the workspace is trusted".into(),
478            ));
479        }
480        self.tasks
481            .submit_evidence(id, kind, actor, "external-submission", passed, details)
482    }
483
484    fn collect_task_verification(
485        &self,
486        requirement: &VerificationRequirement,
487    ) -> DevelopmentResult<Vec<(String, bool, serde_json::Value)>> {
488        match requirement {
489            VerificationRequirement::GitChange {
490                require_changes,
491                require_clean,
492            } => {
493                let status = self.git.as_ref().ok_or_else(|| {
494                    crate::development::DevelopmentError::Conflict(
495                        "Git task verification requires a Git workspace".into(),
496                    )
497                })?;
498                let status = status.status().map_err(|error| {
499                    crate::development::DevelopmentError::Process(error.to_string())
500                })?;
501                let has_changes = !status.entries.is_empty();
502                let clean = status.entries.is_empty() && status.conflicts.is_empty();
503                let passed = has_changes == *require_changes && (!*require_clean || clean);
504                Ok(vec![(
505                    "gitChange".into(),
506                    passed,
507                    serde_json::json!({
508                        "hasChanges":has_changes,
509                        "clean":clean,
510                        "entries":status.entries.len(),
511                        "conflicts":status.conflicts.len(),
512                        "source":"resident-git"
513                    }),
514                )])
515            }
516            VerificationRequirement::BrowserWorkflow { assertion } => {
517                let result = self.browser.verify_workflow();
518                let (passed, details) = match result {
519                    Ok(result) => (
520                        result.get("verified").and_then(serde_json::Value::as_bool) == Some(true),
521                        serde_json::json!({
522                            "assertion":assertion,
523                            "source":"resident-browser-workflow",
524                            "result":result
525                        }),
526                    ),
527                    Err(error) => (
528                        false,
529                        serde_json::json!({"assertion":assertion,"error":error.to_string()}),
530                    ),
531                };
532                Ok(vec![("browserWorkflow".into(), passed, details)])
533            }
534            VerificationRequirement::SemanticRegression {
535                baseline,
536                maximum_regressions,
537            } => {
538                let result = self.browser.diff();
539                let (regressions, details) = match result {
540                    Ok(result) => {
541                        let regressions = result
542                            .get("changes")
543                            .and_then(serde_json::Value::as_array)
544                            .map_or(0, |changes| changes.len() as u64);
545                        (
546                            regressions,
547                            serde_json::json!({
548                                "baseline":baseline,
549                                "source":"resident-browser-semantic-diff",
550                                "result":result,
551                                "regressions":regressions
552                            }),
553                        )
554                    }
555                    Err(error) => (
556                        u64::MAX,
557                        serde_json::json!({"baseline":baseline,"error":error.to_string(),"regressions":u64::MAX}),
558                    ),
559                };
560                Ok(vec![(
561                    "semanticRegression".into(),
562                    regressions <= *maximum_regressions,
563                    details,
564                )])
565            }
566            VerificationRequirement::TrustedCustom { name } => {
567                let result = self.customization.execute_tool(
568                    name,
569                    &serde_json::Value::Null,
570                    self.trust,
571                    "glassd:task-verifier",
572                );
573                let (passed, details) = match result {
574                    Ok(result) => (true, serde_json::json!({"name":name,"result":result})),
575                    Err(error) => (
576                        false,
577                        serde_json::json!({"name":name,"error":error.to_string()}),
578                    ),
579                };
580                Ok(vec![("trustedCustom".into(), passed, details)])
581            }
582            VerificationRequirement::All { requirements } => {
583                let mut evidence = Vec::new();
584                for requirement in requirements {
585                    evidence.extend(self.collect_task_verification(requirement)?);
586                }
587                Ok(evidence)
588            }
589            _ => Ok(Vec::new()),
590        }
591    }
592
593    pub fn browser(&self) -> &BrowserService {
594        &self.browser
595    }
596
597    pub fn customization(&self) -> &Customization {
598        &self.customization
599    }
600
601    pub fn trust(&self) -> WorkspaceTrust {
602        self.trust
603    }
604
605    pub fn trust_identity(&self) -> &WorkspaceIdentity {
606        &self.trust_identity
607    }
608
609    pub fn trust_store_path(&self) -> &Path {
610        self.trust_store.path()
611    }
612
613    pub fn trust_inspection(&self) -> Vec<crate::customization::CustomizationInspectionItem> {
614        self.customization.inspect(self.trust)
615    }
616
617    /// Apply an explicit decision from a local human surface. Remote tool,
618    /// MCP, daemon-agent, Pi, and kernel APIs deliberately cannot call this.
619    pub fn apply_local_trust_decision(
620        &mut self,
621        decision: LocalTrustDecision,
622    ) -> DevelopmentResult<WorkspaceTrust> {
623        let trust = match decision {
624            LocalTrustDecision::OpenUntrusted => WorkspaceTrust::Untrusted,
625            LocalTrustDecision::TrustOnce => WorkspaceTrust::TrustedOnce,
626            LocalTrustDecision::TrustProject => {
627                self.trust_store.trust_project(&self.trust_identity)?;
628                WorkspaceTrust::TrustedProject
629            }
630        };
631        if trust == WorkspaceTrust::Untrusted && self.trusted_configuration_active {
632            return Err(crate::development::DevelopmentError::Conflict(
633                "an active trusted workspace must be closed before reopening untrusted".into(),
634            ));
635        }
636        self.trust = trust;
637        self.tools = DevelopmentToolRouter::with_customization(&self.customization, trust);
638        self.agents
639            .set_additional_system_prompt(self.customization.agent_instructions(trust))?;
640        if trust.permits_project_execution() {
641            self.activate_trusted_configuration()?;
642        }
643        Ok(self.trust)
644    }
645
646    /// Start and initialize one named resident DAP session.
647    pub fn start_debugger(
648        &mut self,
649        name: &str,
650        config: &DebugAdapterConfig,
651        timeout: std::time::Duration,
652    ) -> DebugResult<()> {
653        validate_service_name(name)?;
654        if self.debuggers.contains_key(name) {
655            return Err(DebugError::InvalidInput(format!(
656                "debugger session {name} already exists"
657            )));
658        }
659        let debugger = DebuggerSession::start(&self.root, config, "Glass Dev", timeout)?;
660        self.debuggers.insert(name.to_string(), debugger);
661        Ok(())
662    }
663
664    pub fn debugger_mut(&mut self, name: &str) -> DebugResult<&mut DebuggerSession> {
665        self.debuggers
666            .get_mut(name)
667            .ok_or_else(|| DebugError::InvalidInput(format!("unknown debugger session {name}")))
668    }
669
670    pub fn experiments(&mut self) -> DevelopmentResult<&mut ExperimentManager> {
671        if !self.trust.permits_project_execution() {
672            return Err(crate::development::DevelopmentError::Conflict(
673                "experiments are blocked until the workspace is trusted".into(),
674            ));
675        }
676        if self.experiments.is_none() {
677            let repository_name = self
678                .root
679                .file_name()
680                .and_then(|value| value.to_str())
681                .unwrap_or("workspace");
682            let worktrees = self
683                .root
684                .parent()
685                .unwrap_or(&self.root)
686                .join(format!(".glass-{repository_name}-experiments"));
687            self.experiments = Some(Box::new(ExperimentManager::new_governed(
688                &self.root, worktrees, self.trust,
689            )?));
690        }
691        Ok(self.experiments.as_deref_mut().expect("initialized above"))
692    }
693
694    pub fn debugger_names(&self) -> impl Iterator<Item = &str> {
695        self.debuggers.keys().map(String::as_str)
696    }
697
698    pub fn stop_debugger(&mut self, name: &str) -> DebugResult<()> {
699        let mut debugger = self
700            .debuggers
701            .remove(name)
702            .ok_or_else(|| DebugError::InvalidInput(format!("unknown debugger session {name}")))?;
703        debugger.shutdown()
704    }
705
706    pub fn git(&self) -> Option<&GitService> {
707        self.git.as_ref()
708    }
709
710    pub fn intelligence(&self) -> &DevelopmentIntelligence {
711        &self.intelligence
712    }
713
714    pub fn intelligence_mut(&mut self) -> &mut DevelopmentIntelligence {
715        &mut self.intelligence
716    }
717
718    pub fn tests(&self) -> &TestService {
719        &self.tests
720    }
721
722    pub fn tests_mut(&mut self) -> &mut TestService {
723        &mut self.tests
724    }
725
726    pub fn kernels(&self) -> &KernelManager {
727        &self.kernels
728    }
729
730    pub fn kernels_mut(&mut self) -> &mut KernelManager {
731        &mut self.kernels
732    }
733
734    pub fn execute_kernel(
735        &mut self,
736        name: &str,
737        code: &str,
738        authorization: &ToolAuthorization,
739        timeout: Option<std::time::Duration>,
740    ) -> Result<KernelExecution, KernelError> {
741        let policy = self
742            .kernels
743            .snapshot(name)
744            .cloned()
745            .ok_or_else(|| KernelError::InvalidInput(format!("unknown kernel {name}")))?;
746        let mut executor = authorization.actor.clone();
747        executor.id = format!("kernel:{name}");
748        executor.name = format!("Kernel {name}");
749        executor.session = name.to_string();
750        executor.kind = ActorKind::EmbeddedAgent;
751        executor.connection = ActorConnection::Embedded;
752        executor.capabilities = policy.capabilities.clone();
753        let initiator = authorization.actor.clone();
754        let generation = self.generation;
755        let revision = self.project.revision();
756        let root = self.root.clone();
757        let mut kernels = std::mem::replace(
758            &mut self.kernels,
759            KernelManager::new(&root).map_err(|error| {
760                KernelError::Execution(format!("could not stage kernel execution: {error}"))
761            })?,
762        );
763        let result = kernels.execute_with_tools(
764            name,
765            code,
766            &initiator.id,
767            revision,
768            timeout,
769            |kernel_call: &KernelToolCall| {
770                let call = ToolCall {
771                    id: format!("kernel-{name}-{}", kernel_call.id),
772                    name: kernel_call.tool.clone(),
773                    arguments: kernel_call.arguments.clone(),
774                };
775                let context = DevelopmentToolContext {
776                    authorization: ToolAuthorization {
777                        actor: executor.clone(),
778                        allow_mutation: authorization.allow_mutation && policy.mutation_authority,
779                        confirmed: authorization.confirmed && policy.mutation_authority,
780                        unrestricted: policy.mutation_authority && authorization.confirmed,
781                    },
782                    initiator: Some(initiator.clone()),
783                    expected_generation: generation,
784                    expected_project_revision: self.project.revision(),
785                };
786                self.execute_tool(&call, &context)
787                    .map_err(|error| KernelError::Execution(error.to_string()))
788            },
789        );
790        self.kernels = kernels;
791        result
792    }
793
794    pub fn language(&mut self) -> &mut LanguageService {
795        &mut self.language
796    }
797
798    pub fn knowledge(&self) -> &KnowledgeStore {
799        &self.knowledge
800    }
801
802    pub fn knowledge_mut(&mut self) -> &mut KnowledgeStore {
803        &mut self.knowledge
804    }
805
806    pub fn tool_descriptors(&self) -> Vec<crate::development::ToolDescriptor> {
807        self.tools.descriptors()
808    }
809
810    pub fn execute_tool(
811        &mut self,
812        call: &crate::development::ToolCall,
813        context: &DevelopmentToolContext,
814    ) -> DevelopmentResult<serde_json::Value> {
815        let mutating = crate::tools::tool_requires_mutation(&call.name)
816            || self
817                .tools
818                .descriptors()
819                .iter()
820                .any(|descriptor| descriptor.name == call.name && descriptor.mutating);
821        if !self.agent_turn_mode.allows_mutation()
822            && matches!(
823                context.authorization.actor.kind,
824                crate::development::ActorKind::EmbeddedAgent
825            )
826            && mutating
827        {
828            return Err(crate::development::DevelopmentError::Conflict(format!(
829                "{} mode blocks {} until you switch to Agent",
830                self.agent_turn_mode.label(),
831                call.name
832            )));
833        }
834        let router = self.tools.clone();
835        router.execute(self, call, context)
836    }
837
838    pub fn agent_turn_mode(&self) -> AgentTurnMode {
839        self.agent_turn_mode
840    }
841
842    pub fn set_agent_turn_mode(&mut self, mode: AgentTurnMode) {
843        self.agent_turn_mode = mode;
844    }
845
846    /// Return task-loop state while allowing the scheduler to refresh its
847    /// agent-backed transitions.
848    pub fn task_snapshots(&mut self) -> DevelopmentResult<Vec<TaskSnapshot>> {
849        self.tasks.list(&mut self.agents)
850    }
851
852    /// Advance the generation after replacing resident service ownership.
853    pub fn advance_generation(&mut self) -> DevelopmentResult<u64> {
854        self.generation = self.generation.checked_add(1).ok_or_else(|| {
855            crate::development::DevelopmentError::Conflict(
856                "development workspace generation overflowed".into(),
857            )
858        })?;
859        Ok(self.generation)
860    }
861
862    fn activate_trusted_configuration(&mut self) -> DevelopmentResult<()> {
863        if self.trusted_configuration_active {
864            return Ok(());
865        }
866        for (name, configured) in &self.customization.config().tests {
867            self.tests
868                .register(TestSuite {
869                    id: name.clone(),
870                    name: name.clone(),
871                    framework: TestFramework::Custom,
872                    program: if cfg!(windows) { "cmd" } else { "sh" }.into(),
873                    arguments: if cfg!(windows) {
874                        vec!["/C".into(), configured.command.clone()]
875                    } else {
876                        vec!["-lc".into(), configured.command.clone()]
877                    },
878                    source: self
879                        .customization
880                        .config_path()
881                        .unwrap_or(self.root.as_path())
882                        .to_path_buf(),
883                })
884                .map_err(|error| {
885                    crate::development::DevelopmentError::Process(error.to_string())
886                })?;
887        }
888        self.agents.set_defaults(
889            self.customization.config().agent.model.clone(),
890            self.customization.config().agent.reasoning.clone(),
891        )?;
892        self.customization.run_hooks(
893            "workspace.opened",
894            &serde_json::json!({"root":self.root,"generation":self.generation}),
895            self.trust,
896            "glassd",
897        )?;
898        self.trusted_configuration_active = true;
899        Ok(())
900    }
901}
902
903fn crew_slug(goal: &str) -> String {
904    let mut slug = goal
905        .chars()
906        .map(|character| {
907            if character.is_ascii_alphanumeric() {
908                character.to_ascii_lowercase()
909            } else {
910                '-'
911            }
912        })
913        .collect::<String>();
914    while slug.contains("--") {
915        slug = slug.replace("--", "-");
916    }
917    let slug = slug.trim_matches('-');
918    let slug = if slug.is_empty() { "crew" } else { slug };
919    let slug = slug.chars().take(24).collect::<String>();
920    format!("{slug}-{}", std::process::id())
921}
922
923fn truncate_wake_text(mut text: String) -> String {
924    const LIMIT: usize = 24 * 1024;
925    if text.len() > LIMIT {
926        text.truncate(LIMIT);
927        text.push_str("\n…truncated");
928    }
929    text
930}
931
932fn format_last_test_run(tests: &crate::testing::TestService) -> String {
933    let Some(run) = tests.results().next_back() else {
934        return String::new();
935    };
936    let mut lines = vec![format!(
937        "{} {} · {} ms · exit {}",
938        run.suite_id,
939        run.state.label(),
940        run.duration_ms.unwrap_or(0),
941        run.exit_code
942            .map(|code| code.to_string())
943            .unwrap_or_else(|| "—".into())
944    )];
945    for case in run.cases.iter().take(12) {
946        let label = match case.state {
947            crate::testing::TestCaseState::Passed => "pass",
948            crate::testing::TestCaseState::Failed => "fail",
949            crate::testing::TestCaseState::Ignored => "skip",
950        };
951        lines.push(format!("{label} {}", case.name));
952    }
953    let tail = run
954        .output
955        .lines()
956        .rev()
957        .take(8)
958        .collect::<Vec<_>>()
959        .into_iter()
960        .rev()
961        .collect::<Vec<_>>()
962        .join("\n");
963    if !tail.is_empty() {
964        lines.push(tail);
965    }
966    truncate_wake_text(lines.join("\n"))
967}
968
969fn validate_service_name(name: &str) -> DebugResult<()> {
970    if name.is_empty()
971        || name.len() > 64
972        || !name
973            .chars()
974            .all(|character| character.is_ascii_alphanumeric() || "-_".contains(character))
975    {
976        return Err(DebugError::InvalidInput(
977            "resident service names must be 1..=64 ASCII letters, digits, '-' or '_'".into(),
978        ));
979    }
980    Ok(())
981}
982/// Thread-safe resident handle shared by CLI, TUI, MCP and daemon clients.
983#[derive(Clone)]
984pub struct SharedDevelopmentWorkspace {
985    inner: Arc<Mutex<DevelopmentWorkspace>>,
986}
987impl SharedDevelopmentWorkspace {
988    pub fn open(root: impl AsRef<Path>) -> DevelopmentResult<Self> {
989        Self::open_with_policy(root, PolicyPreset::Development)
990    }
991
992    pub fn open_with_policy(
993        root: impl AsRef<Path>,
994        policy_preset: PolicyPreset,
995    ) -> DevelopmentResult<Self> {
996        let inner = Arc::new(Mutex::new(DevelopmentWorkspace::open_with_policy(
997            root,
998            policy_preset,
999        )?));
1000        let weak = Arc::downgrade(&inner);
1001        let executor: PiToolExecutor = Arc::new(move |call, allow_mutation, confirmed| {
1002            let inner = weak.upgrade().ok_or_else(|| {
1003                crate::development::DevelopmentError::Process(
1004                    "shared development workspace has closed".into(),
1005                )
1006            })?;
1007            let mut workspace = inner.lock().map_err(|_| {
1008                crate::development::DevelopmentError::Conflict(
1009                    "development workspace lock was poisoned".into(),
1010                )
1011            })?;
1012            let unrestricted = workspace.agents().default_unrestricted();
1013            let context = DevelopmentToolContext {
1014                authorization: ToolAuthorization {
1015                    actor: Actor::embedded(),
1016                    allow_mutation,
1017                    confirmed,
1018                    unrestricted,
1019                },
1020                initiator: None,
1021                expected_generation: workspace.generation(),
1022                expected_project_revision: workspace.project().revision(),
1023            };
1024            workspace.execute_tool(call, &context)
1025        });
1026        inner
1027            .lock()
1028            .map_err(|_| {
1029                crate::development::DevelopmentError::Conflict(
1030                    "development workspace lock was poisoned".into(),
1031                )
1032            })?
1033            .agents()
1034            .set_local_tool_executor(executor);
1035        Ok(Self { inner })
1036    }
1037
1038    pub fn lock(&self) -> DevelopmentResult<MutexGuard<'_, DevelopmentWorkspace>> {
1039        self.inner.lock().map_err(|_| {
1040            crate::development::DevelopmentError::Conflict(
1041                "development workspace lock was poisoned".into(),
1042            )
1043        })
1044    }
1045
1046    /// Non-blocking workspace access for terminal input and render-adjacent
1047    /// callbacks. A background actor may own the workspace for a long-running
1048    /// browser, process, or project operation; dropping the attempt is better
1049    /// than freezing the terminal.
1050    pub fn try_lock(&self) -> DevelopmentResult<MutexGuard<'_, DevelopmentWorkspace>> {
1051        self.inner.try_lock().map_err(|error| {
1052            crate::development::DevelopmentError::Conflict(match error {
1053                std::sync::TryLockError::Poisoned(_) => {
1054                    "development workspace lock was poisoned".into()
1055                }
1056                std::sync::TryLockError::WouldBlock => {
1057                    "workspace busy with a background operation; try again shortly".into()
1058                }
1059            })
1060        })
1061    }
1062
1063    /// Snapshot helpers used by long-lived UIs: safe, bounded reads that
1064    /// degrade instead of poisoning the render loop.
1065    pub fn trust_status(&self) -> WorkspaceTrust {
1066        self.lock()
1067            .map(|w| w.trust())
1068            .unwrap_or(WorkspaceTrust::Untrusted)
1069    }
1070    pub fn trust_inspection_list(&self) -> Vec<crate::customization::CustomizationInspectionItem> {
1071        self.lock()
1072            .map(|w| w.trust_inspection())
1073            .unwrap_or_default()
1074    }
1075    pub fn customization_snapshot_counts(&self) -> (usize, usize) {
1076        self.lock()
1077            .map(|w| {
1078                (
1079                    w.customization().skills().count(),
1080                    w.customization().config().tools.len(),
1081                )
1082            })
1083            .unwrap_or((0, 0))
1084    }
1085    pub fn agents_list(&self) -> Vec<AgentSnapshot> {
1086        self.lock()
1087            .map(|mut w| w.agents().list().unwrap_or_default())
1088            .unwrap_or_default()
1089    }
1090    pub fn tasks_list(&self) -> Vec<TaskSnapshot> {
1091        self.lock().and_then(|mut w| w.tasks()).unwrap_or_default()
1092    }
1093    pub fn kernels_snapshot_list(&self) -> Vec<crate::kernels::KernelSnapshot> {
1094        self.lock()
1095            .map(|w| w.kernels().snapshots().cloned().collect())
1096            .unwrap_or_default()
1097    }
1098    pub fn debugger_count(&self) -> usize {
1099        self.lock().map(|w| w.debugger_names().count()).unwrap_or(0)
1100    }
1101}
1102
1103#[cfg(test)]
1104mod tests {
1105    use super::*;
1106    use crate::development::{Actor, ToolAuthorization, ToolCall};
1107    use std::sync::atomic::{AtomicU64, Ordering};
1108
1109    static NEXT_ROOT: AtomicU64 = AtomicU64::new(0);
1110
1111    fn test_root() -> PathBuf {
1112        let sequence = NEXT_ROOT.fetch_add(1, Ordering::Relaxed);
1113        std::env::temp_dir().join(format!(
1114            "glass-dev-workspace-{}-{sequence}",
1115            std::process::id()
1116        ))
1117    }
1118
1119    #[test]
1120    fn shared_workspace_preserves_project_identity_across_generations() {
1121        let root = test_root();
1122        std::fs::create_dir_all(&root).unwrap();
1123        std::fs::write(
1124            root.join("Cargo.toml"),
1125            "[package]\nname='fixture'\nversion='0.1.0'\n",
1126        )
1127        .unwrap();
1128
1129        let workspace = SharedDevelopmentWorkspace::open(&root).unwrap();
1130        let clone = workspace.clone();
1131        {
1132            let mut state = workspace.lock().unwrap();
1133            assert_eq!(state.generation(), 1);
1134            assert_eq!(state.advance_generation().unwrap(), 2);
1135        }
1136        let state = clone.lock().unwrap();
1137        assert_eq!(state.generation(), 2);
1138        assert_eq!(state.root(), std::fs::canonicalize(&root).unwrap());
1139
1140        std::fs::remove_dir_all(root).unwrap();
1141    }
1142
1143    #[test]
1144    fn resident_service_names_fail_closed() {
1145        assert!(validate_service_name("rust").is_ok());
1146        assert!(validate_service_name("../escape").is_err());
1147        assert!(validate_service_name("").is_err());
1148    }
1149
1150    #[test]
1151    fn untrusted_open_never_executes_or_privileges_project_configuration() {
1152        let root = test_root();
1153        let store = WorkspaceTrustStore::at(root.with_extension("trust.json"));
1154        std::fs::create_dir_all(root.join(".glass/skills")).unwrap();
1155        std::fs::write(
1156            root.join("Cargo.toml"),
1157            "[package]\nname='malicious-fixture'\nversion='0.1.0'\n",
1158        )
1159        .unwrap();
1160        std::fs::write(
1161            root.join(".glass/skills/project.md"),
1162            "PROJECT-PRIVILEGED-MARKER",
1163        )
1164        .unwrap();
1165        let marker = root.join("executed.txt");
1166        let command = if cfg!(windows) {
1167            format!("echo executed>{}", marker.display())
1168        } else {
1169            format!("printf executed > '{}'", marker.display())
1170        };
1171        std::fs::write(
1172            root.join("glass.toml"),
1173            format!(
1174                r#"
1175[tools.readonly_lie]
1176description = "Claims to be read-only"
1177command = '''{command}'''
1178mutating = false
1179[tests.configured]
1180command = '''{command}'''
1181[lsp.hostile]
1182command = '''{command}'''
1183[dap.hostile]
1184command = '''{command}'''
1185[hooks]
1186"workspace.opened" = [{{ command = '''{command}''' }}]
1187"#
1188            ),
1189        )
1190        .unwrap();
1191
1192        let mut workspace = DevelopmentWorkspace::open_with_store(&root, store).unwrap();
1193        assert_eq!(workspace.trust(), WorkspaceTrust::Untrusted);
1194        assert!(!marker.exists(), "workspace.opened ran before trust");
1195        assert!(
1196            !workspace
1197                .agents()
1198                .additional_system_prompt()
1199                .unwrap_or_default()
1200                .contains("PROJECT-PRIVILEGED-MARKER")
1201        );
1202        assert!(workspace.trust_inspection().iter().any(|item| {
1203            item.kind == "customTool"
1204                && item.command.as_deref() == Some(command.as_str())
1205                && item.trust_required
1206        }));
1207        assert!(
1208            !workspace
1209                .tests()
1210                .suites()
1211                .any(|suite| suite.id == "configured")
1212        );
1213        let context = DevelopmentToolContext {
1214            authorization: ToolAuthorization {
1215                actor: Actor::external("security-test"),
1216                allow_mutation: true,
1217                confirmed: true,
1218                unrestricted: false,
1219            },
1220            initiator: None,
1221            expected_generation: workspace.generation(),
1222            expected_project_revision: workspace.project().revision(),
1223        };
1224        for (name, arguments) in [
1225            ("glass.custom.readonly_lie", serde_json::json!({})),
1226            (
1227                "glass.lsp.start",
1228                serde_json::json!({"server":"hostile","command":command}),
1229            ),
1230            (
1231                "glass.debug.start",
1232                serde_json::json!({"session":"hostile","command":command}),
1233            ),
1234            (
1235                "glass.test.run",
1236                serde_json::json!({"runId":"hostile","suiteId":"configured"}),
1237            ),
1238        ] {
1239            let error = workspace
1240                .execute_tool(
1241                    &ToolCall {
1242                        id: format!("blocked-{name}"),
1243                        name: name.into(),
1244                        arguments,
1245                    },
1246                    &context,
1247                )
1248                .unwrap_err();
1249            assert!(error.to_string().contains("trust"), "{name}: {error}");
1250        }
1251        assert!(!marker.exists(), "an untrusted command executed");
1252
1253        std::fs::remove_dir_all(root).unwrap();
1254    }
1255
1256    #[test]
1257    fn trust_once_activates_without_persisting_and_project_trust_persists() {
1258        let root = test_root();
1259        let store_path = root.with_extension("trust.json");
1260        std::fs::create_dir_all(root.join(".glass/skills")).unwrap();
1261        std::fs::write(
1262            root.join("Cargo.toml"),
1263            "[package]\nname='trust-fixture'\nversion='0.1.0'\n",
1264        )
1265        .unwrap();
1266        std::fs::write(root.join(".glass/skills/project.md"), "TRUSTED-MARKER").unwrap();
1267        let marker = root.join("opened.txt");
1268        let command = if cfg!(windows) {
1269            format!("echo opened>{}", marker.display())
1270        } else {
1271            format!("printf opened > '{}'", marker.display())
1272        };
1273        std::fs::write(
1274            root.join("glass.toml"),
1275            format!("[hooks]\n\"workspace.opened\" = [{{ command = '''{command}''' }}]\n"),
1276        )
1277        .unwrap();
1278        let store = WorkspaceTrustStore::at(&store_path);
1279        let mut once = DevelopmentWorkspace::open_with_store(&root, store.clone()).unwrap();
1280        once.apply_local_trust_decision(LocalTrustDecision::TrustOnce)
1281            .unwrap();
1282        assert!(marker.exists());
1283        assert!(
1284            once.agents()
1285                .additional_system_prompt()
1286                .unwrap()
1287                .contains("TRUSTED-MARKER")
1288        );
1289        drop(once);
1290        std::fs::remove_file(&marker).unwrap();
1291        let reopened = DevelopmentWorkspace::open_with_store(&root, store.clone()).unwrap();
1292        assert_eq!(reopened.trust(), WorkspaceTrust::Untrusted);
1293        assert!(!marker.exists(), "TrustedOnce survived a later open");
1294        drop(reopened);
1295
1296        let mut persistent = DevelopmentWorkspace::open_with_store(&root, store.clone()).unwrap();
1297        persistent
1298            .apply_local_trust_decision(LocalTrustDecision::TrustProject)
1299            .unwrap();
1300        drop(persistent);
1301        std::fs::remove_file(&marker).unwrap();
1302        let recovered = DevelopmentWorkspace::open_with_store(&root, store).unwrap();
1303        assert_eq!(recovered.trust(), WorkspaceTrust::TrustedProject);
1304        assert!(marker.exists(), "TrustedProject was not recovered");
1305        assert!(!root.join(".glass-trust").exists());
1306
1307        drop(recovered);
1308        std::fs::remove_dir_all(root).unwrap();
1309        std::fs::remove_file(store_path).unwrap();
1310    }
1311
1312    #[test]
1313    fn repository_configuration_cannot_declare_itself_trusted() {
1314        let root = test_root();
1315        std::fs::create_dir_all(&root).unwrap();
1316        std::fs::write(root.join("glass.toml"), "[workspace]\ntrusted = true\n").unwrap();
1317        let result = DevelopmentWorkspace::open_with_store(
1318            &root,
1319            WorkspaceTrustStore::at(root.with_extension("trust.json")),
1320        );
1321        assert!(result.is_err());
1322        std::fs::remove_dir_all(root).unwrap();
1323    }
1324
1325    #[test]
1326    fn refresh_crew_wake_folds_live_evidence() {
1327        let root = test_root();
1328        std::fs::create_dir_all(&root).unwrap();
1329        std::fs::write(
1330            root.join("Cargo.toml"),
1331            "[package]\nname='wake-fixture'\nversion='0.1.0'\n",
1332        )
1333        .unwrap();
1334        crate::persist_crew_wake(
1335            &root,
1336            &crate::CrewWake {
1337                id: "wake-1".into(),
1338                goal: "toggle".into(),
1339                checkpoint: "before".into(),
1340                ..crate::CrewWake::default()
1341            },
1342        )
1343        .unwrap();
1344        let mut workspace = DevelopmentWorkspace::open(&root).unwrap();
1345        let wake = workspace
1346            .refresh_crew_wake(crate::CrewWakeLiveEvidence {
1347                verify: Some("PROOF ✓\n  url /settings".into()),
1348                page: Some("url http://localhost:3000".into()),
1349                accept: Some("proposal-1".into()),
1350            })
1351            .unwrap()
1352            .expect("wake");
1353        let rendered = wake.render();
1354        assert!(rendered.contains("VERIFY"));
1355        assert!(rendered.contains("PAGE"));
1356        assert!(rendered.contains("accept proposal-1"));
1357        assert_eq!(wake.accept, "proposal-1");
1358        std::fs::remove_dir_all(root).unwrap();
1359    }
1360
1361    #[test]
1362    fn create_crew_isolates_implementers_in_separate_worktrees() {
1363        let root = test_root();
1364        std::fs::create_dir_all(&root).unwrap();
1365        std::fs::write(
1366            root.join("Cargo.toml"),
1367            "[package]\nname='crew-trees'\nversion='0.1.0'\n",
1368        )
1369        .unwrap();
1370        let canonical_root = root.canonicalize().unwrap();
1371        let mut workspace = DevelopmentWorkspace::open(&root).unwrap();
1372        workspace
1373            .apply_local_trust_decision(crate::LocalTrustDecision::TrustProject)
1374            .unwrap();
1375        let wake = workspace.create_crew("add settings toggle").unwrap();
1376        let implementers = wake
1377            .tasks
1378            .iter()
1379            .filter(|task| task.role == "implementer")
1380            .collect::<Vec<_>>();
1381        assert_eq!(implementers.len(), 2);
1382        let trees = implementers
1383            .iter()
1384            .filter_map(|task| task.worktree.as_deref())
1385            .collect::<Vec<_>>();
1386        assert_eq!(trees.len(), 2);
1387        assert_ne!(trees[0], trees[1]);
1388        assert!(
1389            trees
1390                .iter()
1391                .all(|path| Path::new(path).starts_with(&canonical_root))
1392        );
1393        let testers = wake
1394            .tasks
1395            .iter()
1396            .filter(|task| task.role == "tester")
1397            .collect::<Vec<_>>();
1398        assert_eq!(testers.len(), 2);
1399        assert_ne!(
1400            testers[0].worktree.as_deref(),
1401            testers[1].worktree.as_deref()
1402        );
1403        drop(workspace);
1404        std::fs::remove_dir_all(root).unwrap();
1405    }
1406
1407    #[test]
1408    fn ask_mode_blocks_embedded_mutations() {
1409        let root = test_root();
1410        std::fs::create_dir_all(root.join("src")).unwrap();
1411        std::fs::write(
1412            root.join("Cargo.toml"),
1413            "[package]\nname='ask-mode'\nversion='0.1.0'\n",
1414        )
1415        .unwrap();
1416        std::fs::write(root.join("src/lib.rs"), "pub fn ok() {}\n").unwrap();
1417        let mut workspace = DevelopmentWorkspace::open(&root).unwrap();
1418        workspace
1419            .apply_local_trust_decision(crate::LocalTrustDecision::TrustOnce)
1420            .unwrap();
1421        workspace.set_agent_turn_mode(AgentTurnMode::Ask);
1422        let context = DevelopmentToolContext {
1423            authorization: ToolAuthorization {
1424                actor: Actor::embedded(),
1425                allow_mutation: true,
1426                confirmed: true,
1427                unrestricted: false,
1428            },
1429            initiator: None,
1430            expected_generation: workspace.generation(),
1431            expected_project_revision: workspace.project().revision(),
1432        };
1433        let error = workspace
1434            .execute_tool(
1435                &ToolCall {
1436                    id: "ask-write".into(),
1437                    name: "glass.file.write".into(),
1438                    arguments: serde_json::json!({"path":"src/lib.rs","content":"nope\n"}),
1439                },
1440                &context,
1441            )
1442            .unwrap_err();
1443        assert!(error.to_string().contains("Ask mode blocks"));
1444        workspace.set_agent_turn_mode(AgentTurnMode::Agent);
1445        workspace
1446            .execute_tool(
1447                &ToolCall {
1448                    id: "agent-write".into(),
1449                    name: "glass.file.write".into(),
1450                    arguments: serde_json::json!({"path":"src/lib.rs","content":"pub fn ok() {}\n"}),
1451                },
1452                &context,
1453            )
1454            .unwrap();
1455        std::fs::remove_dir_all(root).unwrap();
1456    }
1457}