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