1use super::{
2 Actor, DevelopmentError, DevelopmentEventKind, DevelopmentGraph, DevelopmentResult,
3 LanguageDiagnostic, LspClient, MAX_BUFFER_BYTES, MAX_FILE_BYTES, MAX_FILE_ENTRIES,
4 ProcessManager, ReplayWindow, SearchHit, SearchKind, SemanticBreakpoint, SemanticBreakpointHit,
5 SemanticSnapshot, SourceLocation, Timeline, read_bounded_utf8,
6};
7use crate::development::diff::{ProjectDiff, build_diff};
8use crate::development::graph::{LinkEvidence, LinkProvenance, RuntimeLink};
9use serde::{Deserialize, Serialize};
10use sha2::{Digest, Sha256};
11use std::{
12 collections::BTreeMap,
13 fs::{self, OpenOptions},
14 io::Write,
15 path::{Component, Path, PathBuf},
16 process::Command,
17 sync::Mutex,
18 time::{Duration, Instant},
19};
20
21#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
22#[serde(rename_all = "camelCase")]
23pub struct GlassProjectConfig {
24 #[serde(default)]
25 pub project: ProjectConfig,
26 #[serde(default)]
27 pub commands: CommandConfig,
28 #[serde(default)]
29 pub browser: BrowserConfig,
30 #[serde(default)]
31 pub editor: EditorConfig,
32 #[serde(default)]
33 pub agent: AgentConfig,
34}
35
36#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
37pub struct ProjectConfig {
38 #[serde(default)]
39 pub name: Option<String>,
40}
41
42#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
43pub struct CommandConfig {
44 #[serde(default)]
45 pub dev: Option<String>,
46 #[serde(default)]
47 pub test: Option<String>,
48 #[serde(default)]
49 pub lint: Option<String>,
50 #[serde(default)]
51 pub build: Option<String>,
52}
53
54#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
55pub struct BrowserConfig {
56 #[serde(default)]
57 pub url: Option<String>,
58}
59
60#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
61pub struct EditorConfig {
62 #[serde(default)]
63 pub engine: Option<String>,
64}
65
66#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
67pub struct AgentConfig {
68 #[serde(default)]
69 pub harness: Option<String>,
70}
71
72#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
73#[serde(rename_all = "camelCase")]
74pub struct ProjectDetection {
75 pub root: PathBuf,
76 pub languages: Vec<String>,
77 pub package_manager: Option<String>,
78 pub framework: Option<String>,
79 pub build_system: Option<String>,
80 pub formatter: Option<String>,
81 pub lsp_servers: Vec<String>,
82 pub git_branch: Option<String>,
83 pub dev_command: Option<String>,
84 pub test_command: Option<String>,
85 pub lint_command: Option<String>,
86 pub build_command: Option<String>,
87 pub browser_url: Option<String>,
88 pub local_development_urls: Vec<String>,
89 pub editor_engine: Option<String>,
90 pub agent_harness: Option<String>,
91 pub config_path: Option<PathBuf>,
92}
93
94#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
95#[serde(rename_all = "camelCase")]
96pub enum FileKind {
97 File,
98 Directory,
99}
100
101#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
102#[serde(rename_all = "camelCase")]
103pub struct FileEntry {
104 pub path: String,
105 pub kind: FileKind,
106 pub bytes: Option<u64>,
107 #[serde(default, skip_serializing_if = "Option::is_none")]
108 pub git_status: Option<String>,
109 #[serde(default)]
110 pub dirty: bool,
111 #[serde(default, skip_serializing_if = "Option::is_none")]
112 pub actor: Option<Actor>,
113}
114
115#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
117#[serde(rename_all = "camelCase")]
118pub struct ProjectTreeResult {
119 pub entries: Vec<FileEntry>,
120 pub truncated: bool,
121 pub limit: usize,
122 pub ignored_directories: Vec<String>,
123 pub skipped_symlinks: usize,
124}
125
126#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
127#[serde(rename_all = "camelCase")]
128pub struct EditorBuffer {
129 pub path: String,
130 pub content: String,
131 pub original_hash: String,
132 pub dirty: bool,
133 pub cursor_line: u32,
134 pub cursor_column: u32,
135 pub actor: Actor,
136}
137
138pub struct ProjectWorkspace {
139 root: PathBuf,
140 detection: ProjectDetection,
141 config: GlassProjectConfig,
142 buffers: BTreeMap<String, EditorBuffer>,
143 undo: BTreeMap<String, Vec<String>>,
144 redo: BTreeMap<String, Vec<String>>,
145 processes: ProcessManager,
146 timeline: Timeline,
147 graph: DevelopmentGraph,
148 graph_path: PathBuf,
149 collaboration: super::CollaborationBus,
150 diagnostics: BTreeMap<String, Vec<LanguageDiagnostic>>,
151 language: Option<LspClient>,
152 tree_cache: Mutex<Option<(Instant, ProjectTreeResult)>>,
153 actors: BTreeMap<String, Actor>,
154 actor: Actor,
155 revision: u64,
156}
157
158impl std::fmt::Debug for ProjectWorkspace {
159 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
160 formatter
161 .debug_struct("ProjectWorkspace")
162 .field("root", &self.root)
163 .field("detection", &self.detection)
164 .field("buffers", &self.buffers.keys().collect::<Vec<_>>())
165 .field("revision", &self.revision)
166 .finish()
167 }
168}
169
170impl ProjectWorkspace {
171 pub fn event_page(
174 root: impl AsRef<Path>,
175 after_id: Option<&str>,
176 limit: usize,
177 ) -> DevelopmentResult<super::DevelopmentEventPage> {
178 let root = canonical_root(root.as_ref())?;
179 Ok(Timeline::for_project(&root)?.events_after(after_id, limit))
180 }
181
182 pub fn timeline_snapshot(
183 root: impl AsRef<Path>,
184 ) -> DevelopmentResult<Vec<super::DevelopmentEvent>> {
185 let root = canonical_root(root.as_ref())?;
186 Ok(Timeline::for_project(&root)?.events().cloned().collect())
187 }
188
189 pub fn open(root: impl AsRef<Path>) -> DevelopmentResult<Self> {
190 let root = canonical_root(root.as_ref())?;
191 let detection = detect_project(&root)?;
192 let config = load_project_config(detection.config_path.as_deref())?;
193 let timeline = Timeline::for_project(&root)?;
194 let graph_path = timeline.path().with_file_name("graph.json");
195 let graph = DevelopmentGraph::load(&graph_path)?;
196 let actor = Actor::local();
197 let mut actors = BTreeMap::new();
198 actors.insert(actor.id.clone(), actor.clone());
199 let embedded = Actor::embedded();
200 actors.insert(embedded.id.clone(), embedded);
201 for event in timeline.events() {
202 if matches!(event.kind, DevelopmentEventKind::ActorJoined) {
203 actors.insert(event.actor.id.clone(), event.actor.clone());
204 }
205 }
206 let mut workspace = Self {
207 root: root.clone(),
208 detection,
209 config,
210 buffers: BTreeMap::new(),
211 undo: BTreeMap::new(),
212 redo: BTreeMap::new(),
213 processes: ProcessManager::new(&root),
214 timeline,
215 graph,
216 graph_path,
217 collaboration: super::CollaborationBus::default(),
218 diagnostics: BTreeMap::new(),
219 language: None,
220 tree_cache: Mutex::new(None),
221 actors,
222 actor,
223 revision: 0,
224 };
225 let _ = workspace.record(
226 DevelopmentEventKind::WorkspaceOpened,
227 serde_json::json!({"root": root}),
228 );
229 Ok(workspace)
230 }
231
232 pub fn root(&self) -> &Path {
233 &self.root
234 }
235
236 pub fn detection(&self) -> &ProjectDetection {
237 &self.detection
238 }
239
240 pub fn config(&self) -> &GlassProjectConfig {
241 &self.config
242 }
243
244 pub fn revision(&self) -> u64 {
245 self.revision
246 }
247
248 pub fn timeline(&self) -> &Timeline {
249 &self.timeline
250 }
251
252 pub fn graph(&self) -> &DevelopmentGraph {
253 &self.graph
254 }
255
256 pub fn diagnostics(&self) -> &BTreeMap<String, Vec<LanguageDiagnostic>> {
257 &self.diagnostics
258 }
259
260 fn invalidate_tree_cache(&self) {
261 if let Ok(mut cache) = self.tree_cache.lock() {
262 *cache = None;
263 }
264 }
265
266 pub fn actors(&self) -> impl Iterator<Item = &Actor> {
267 self.actors.values()
268 }
269
270 pub fn collaboration(&mut self) -> &mut super::CollaborationBus {
271 &mut self.collaboration
272 }
273
274 pub fn attach_actor(&mut self, actor: Actor) -> DevelopmentResult<()> {
275 if self.actors.len() >= 64 && !self.actors.contains_key(&actor.id) {
276 return Err(DevelopmentError::InvalidInput(
277 "workspace cannot contain more than 64 actors".into(),
278 ));
279 }
280 self.record_as(
281 actor.clone(),
282 DevelopmentEventKind::ActorJoined,
283 serde_json::json!({"actorId": actor.id.clone()}),
284 )?;
285 self.actors.insert(actor.id.clone(), actor);
286 Ok(())
287 }
288
289 pub fn processes(&mut self) -> &mut ProcessManager {
290 &mut self.processes
291 }
292
293 pub fn list_files(&self) -> DevelopmentResult<Vec<FileEntry>> {
294 Ok(self.list_files_result()?.entries)
295 }
296
297 pub fn list_files_result(&self) -> DevelopmentResult<ProjectTreeResult> {
299 {
300 let cache = self.tree_cache.lock().map_err(|_| {
301 DevelopmentError::Conflict("project tree cache is unavailable".into())
302 })?;
303 if let Some((created, result)) = cache.as_ref()
304 && created.elapsed() <= Duration::from_millis(250)
305 {
306 return Ok(result.clone());
307 }
308 }
309 let mut result = ProjectTreeResult {
310 entries: Vec::new(),
311 truncated: false,
312 limit: MAX_FILE_ENTRIES,
313 ignored_directories: Vec::new(),
314 skipped_symlinks: 0,
315 };
316 visit_files(&self.root, &self.root, &mut result)?;
317 let git = git_statuses(&self.root);
318 for entry in &mut result.entries {
319 entry.git_status = git.get(&entry.path).cloned();
320 if let Some(buffer) = self.buffers.get(&entry.path) {
321 entry.dirty = buffer.dirty;
322 entry.actor = Some(buffer.actor.clone());
323 }
324 }
325 result
326 .entries
327 .sort_by(|left, right| left.path.cmp(&right.path));
328 result.ignored_directories.sort();
329 result.ignored_directories.dedup();
330 *self.tree_cache.lock().map_err(|_| {
331 DevelopmentError::Conflict("project tree cache is unavailable".into())
332 })? = Some((Instant::now(), result.clone()));
333 Ok(result)
334 }
335
336 pub fn read_file(&mut self, path: &str) -> DevelopmentResult<String> {
337 let (_, relative) = self.resolve_path(path, false)?;
338 let content = self.read_file_snapshot(path)?;
339 self.record(
340 DevelopmentEventKind::FileOpened,
341 serde_json::json!({"path": relative}),
342 )?;
343 Ok(content)
344 }
345
346 pub(crate) fn read_file_snapshot(&self, path: &str) -> DevelopmentResult<String> {
349 let (absolute, _) = self.resolve_path(path, false)?;
350 read_bounded_utf8(&absolute, MAX_FILE_BYTES, "project file")
351 }
352
353 pub fn open_buffer(&mut self, path: &str, actor: Actor) -> DevelopmentResult<EditorBuffer> {
354 let content = self.read_file(path)?;
355 let (_, relative) = self.resolve_path(path, false)?;
356 let buffer = EditorBuffer {
357 path: relative.clone(),
358 original_hash: hash(&content),
359 content,
360 dirty: false,
361 cursor_line: 1,
362 cursor_column: 1,
363 actor,
364 };
365 self.buffers.insert(relative, buffer.clone());
366 Ok(buffer)
367 }
368
369 pub fn buffers(&self) -> impl Iterator<Item = &EditorBuffer> {
370 self.buffers.values()
371 }
372
373 pub fn buffer(&self, path: &str) -> Option<&EditorBuffer> {
374 self.buffers.get(path)
375 }
376
377 pub fn edit_buffer(
378 &mut self,
379 path: &str,
380 content: String,
381 actor: Actor,
382 ) -> DevelopmentResult<()> {
383 if content.len() > MAX_BUFFER_BYTES {
384 return Err(DevelopmentError::InvalidInput(format!(
385 "buffer exceeds the {} byte limit",
386 MAX_BUFFER_BYTES
387 )));
388 }
389 if !self.buffers.contains_key(path) {
390 if self.resolve_path(path, false).is_ok() {
391 self.open_buffer(path, actor.clone())?;
392 } else {
393 let (_, relative) = self.resolve_path(path, true)?;
394 self.buffers.insert(
395 relative.clone(),
396 EditorBuffer {
397 path: relative,
398 content: String::new(),
399 original_hash: hash(""),
400 dirty: false,
401 cursor_line: 1,
402 cursor_column: 1,
403 actor: actor.clone(),
404 },
405 );
406 }
407 }
408 let buffer = self
409 .buffers
410 .get_mut(path)
411 .ok_or_else(|| DevelopmentError::NotFound(format!("buffer {path}")))?;
412 let history = self.undo.entry(path.to_string()).or_default();
413 if history.len() == 256 {
414 history.remove(0);
415 }
416 history.push(buffer.content.clone());
417 self.redo.remove(path);
418 buffer.content = content;
419 buffer.dirty = hash(&buffer.content) != buffer.original_hash;
420 buffer.actor = actor;
421 self.revision = self.revision.saturating_add(1);
422 self.invalidate_tree_cache();
423 Ok(())
424 }
425
426 pub fn save_buffer(&mut self, path: &str) -> DevelopmentResult<EditorBuffer> {
427 let buffer = self
428 .buffers
429 .get(path)
430 .cloned()
431 .ok_or_else(|| DevelopmentError::NotFound(format!("buffer {path}")))?;
432 let disk_hash = match read_existing(&self.root, path) {
433 Ok(content) => hash(&content),
434 Err(DevelopmentError::Io(error)) if error.kind() == std::io::ErrorKind::NotFound => {
435 hash("")
436 }
437 Err(error) => return Err(error),
438 };
439 if disk_hash != buffer.original_hash {
440 return Err(DevelopmentError::Conflict(format!(
441 "{path} changed on disk after the buffer was opened"
442 )));
443 }
444 self.write_file(path, &buffer.content, buffer.actor.clone())?;
445 let mut saved = buffer;
446 saved.original_hash = hash(&saved.content);
447 saved.dirty = false;
448 self.buffers.insert(path.into(), saved.clone());
449 Ok(saved)
450 }
451
452 pub fn undo_buffer(&mut self, path: &str) -> DevelopmentResult<EditorBuffer> {
453 let previous = self
454 .undo
455 .get_mut(path)
456 .and_then(Vec::pop)
457 .ok_or_else(|| DevelopmentError::NotFound(format!("undo history for {path}")))?;
458 let buffer = self
459 .buffers
460 .get_mut(path)
461 .ok_or_else(|| DevelopmentError::NotFound(format!("buffer {path}")))?;
462 self.redo
463 .entry(path.to_string())
464 .or_default()
465 .push(std::mem::replace(&mut buffer.content, previous));
466 buffer.dirty = hash(&buffer.content) != buffer.original_hash;
467 self.revision = self.revision.saturating_add(1);
468 let result = buffer.clone();
469 self.invalidate_tree_cache();
470 Ok(result)
471 }
472
473 pub fn redo_buffer(&mut self, path: &str) -> DevelopmentResult<EditorBuffer> {
474 let next = self
475 .redo
476 .get_mut(path)
477 .and_then(Vec::pop)
478 .ok_or_else(|| DevelopmentError::NotFound(format!("redo history for {path}")))?;
479 let buffer = self
480 .buffers
481 .get_mut(path)
482 .ok_or_else(|| DevelopmentError::NotFound(format!("buffer {path}")))?;
483 self.undo
484 .entry(path.to_string())
485 .or_default()
486 .push(std::mem::replace(&mut buffer.content, next));
487 buffer.dirty = hash(&buffer.content) != buffer.original_hash;
488 self.revision = self.revision.saturating_add(1);
489 let result = buffer.clone();
490 self.invalidate_tree_cache();
491 Ok(result)
492 }
493
494 pub fn replace_in_buffer(
495 &mut self,
496 path: &str,
497 needle: &str,
498 replacement: &str,
499 actor: Actor,
500 ) -> DevelopmentResult<usize> {
501 if needle.is_empty() {
502 return Err(DevelopmentError::InvalidInput(
503 "search text must not be empty".into(),
504 ));
505 }
506 if !self.buffers.contains_key(path) {
507 self.open_buffer(path, actor.clone())?;
508 }
509 let current = self
510 .buffers
511 .get(path)
512 .ok_or_else(|| DevelopmentError::NotFound(format!("buffer {path}")))?
513 .content
514 .clone();
515 let matches = current.matches(needle).count();
516 if matches > 0 {
517 self.edit_buffer(path, current.replace(needle, replacement), actor)?;
518 }
519 Ok(matches)
520 }
521
522 pub fn set_buffer_cursor(
523 &mut self,
524 path: &str,
525 line: u32,
526 column: u32,
527 ) -> DevelopmentResult<()> {
528 if line == 0 || column == 0 {
529 return Err(DevelopmentError::InvalidInput(
530 "editor cursor positions are one-based".into(),
531 ));
532 }
533 let buffer = self
534 .buffers
535 .get_mut(path)
536 .ok_or_else(|| DevelopmentError::NotFound(format!("buffer {path}")))?;
537 buffer.cursor_line = line;
538 buffer.cursor_column = column;
539 Ok(())
540 }
541
542 pub fn rename_path(&mut self, from: &str, to: &str, actor: Actor) -> DevelopmentResult<()> {
543 self.invalidate_tree_cache();
544 let (source, source_relative) = self.resolve_path(from, false)?;
545 let (destination, destination_relative) = self.resolve_path(to, true)?;
546 if destination.exists() {
547 return Err(DevelopmentError::Conflict(format!(
548 "destination already exists: {to}"
549 )));
550 }
551 if let Some(parent) = destination.parent() {
552 fs::create_dir_all(parent)?;
553 }
554 fs::rename(source, destination)?;
555 if let Some(mut buffer) = self.buffers.remove(&source_relative) {
556 buffer.path = destination_relative.clone();
557 self.buffers.insert(destination_relative.clone(), buffer);
558 }
559 if let Some(history) = self.undo.remove(&source_relative) {
560 self.undo.insert(destination_relative.clone(), history);
561 }
562 if let Some(history) = self.redo.remove(&source_relative) {
563 self.redo.insert(destination_relative.clone(), history);
564 }
565 self.revision = self.revision.saturating_add(1);
566 self.record_as(
567 actor,
568 DevelopmentEventKind::FileSaved,
569 serde_json::json!({"operation": "rename", "from": source_relative, "to": destination_relative}),
570 )
571 }
572
573 pub fn create_directory(&mut self, path: &str, actor: Actor) -> DevelopmentResult<()> {
574 self.invalidate_tree_cache();
575 let (absolute, relative) = self.resolve_path(path, true)?;
576 if absolute.exists() {
577 return Err(DevelopmentError::Conflict(format!(
578 "path already exists: {path}"
579 )));
580 }
581 fs::create_dir_all(&absolute)?;
582 self.revision = self.revision.saturating_add(1);
583 self.record_as(
584 actor,
585 DevelopmentEventKind::FileSaved,
586 serde_json::json!({"operation": "mkdir", "path": relative}),
587 )
588 }
589
590 pub fn delete_path(&mut self, path: &str, actor: Actor) -> DevelopmentResult<()> {
591 self.invalidate_tree_cache();
592 let (absolute, relative) = self.resolve_path(path, false)?;
593 let metadata = fs::symlink_metadata(&absolute)?;
594 if metadata.is_dir() {
595 if fs::read_dir(&absolute)?.next().is_some() {
596 return Err(DevelopmentError::Conflict(format!(
597 "refusing to delete non-empty directory: {path}"
598 )));
599 }
600 fs::remove_dir(&absolute)?;
601 } else {
602 fs::remove_file(&absolute)?;
603 }
604 self.buffers.remove(&relative);
605 self.undo.remove(&relative);
606 self.redo.remove(&relative);
607 self.revision = self.revision.saturating_add(1);
608 self.record_as(
609 actor,
610 DevelopmentEventKind::FileSaved,
611 serde_json::json!({"operation": "delete", "path": relative}),
612 )
613 }
614
615 pub fn write_file(&mut self, path: &str, content: &str, actor: Actor) -> DevelopmentResult<()> {
616 self.invalidate_tree_cache();
617 if content.len() > MAX_FILE_BYTES {
618 return Err(DevelopmentError::InvalidInput(format!(
619 "file exceeds the {} byte write limit",
620 MAX_FILE_BYTES
621 )));
622 }
623 let (absolute, relative) = self.resolve_path(path, true)?;
624 let before_hash = fs::read_to_string(&absolute)
625 .ok()
626 .map(|existing| hash(&existing));
627 let parent = absolute
628 .parent()
629 .ok_or_else(|| DevelopmentError::InvalidInput("file has no parent".into()))?;
630 fs::create_dir_all(parent)?;
631 let temporary = absolute.with_extension(format!(
632 "glass-tmp-{}-{}",
633 std::process::id(),
634 self.revision.saturating_add(1)
635 ));
636 {
637 let mut file = OpenOptions::new()
638 .create_new(true)
639 .write(true)
640 .open(&temporary)?;
641 file.write_all(content.as_bytes())?;
642 file.sync_all()?;
643 }
644 if let Err(error) = fs::rename(&temporary, &absolute) {
645 let _ = fs::remove_file(&temporary);
646 return Err(error.into());
647 }
648 self.revision = self.revision.saturating_add(1);
649 self.record_as(
650 actor,
651 DevelopmentEventKind::FileSaved,
652 serde_json::json!({
653 "path": relative,
654 "bytes": content.len(),
655 "beforeHash": before_hash,
656 "afterHash": hash(content)
657 }),
658 )?;
659 if self.processes.list_checked()?.iter().any(|process| {
660 matches!(process.state, super::ProcessState::Running)
661 && (process.name.contains("dev") || process.name.contains("server"))
662 }) {
663 self.record(
664 DevelopmentEventKind::HmrObserved,
665 serde_json::json!({
666 "path": relative,
667 "status": "pending-runtime-observation",
668 "browserUrl": self.detection.browser_url
669 }),
670 )?;
671 }
672 Ok(())
673 }
674
675 pub fn start_process(
676 &mut self,
677 name: &str,
678 command: &str,
679 ) -> DevelopmentResult<super::ProcessSnapshot> {
680 let snapshot = self.processes.start(name, command)?;
681 self.revision = self.revision.saturating_add(1);
682 self.record(
683 DevelopmentEventKind::ProcessStarted,
684 serde_json::json!({
685 "name": name,
686 "commandBytes": command.len(),
687 "commandSha256": hash(command),
688 "pid": snapshot.pid
689 }),
690 )?;
691 Ok(snapshot)
692 }
693
694 pub fn stop_process(&mut self, name: &str) -> DevelopmentResult<super::ProcessSnapshot> {
695 let snapshot = self.processes.stop(name)?;
696 self.revision = self.revision.saturating_add(1);
697 self.record(
698 DevelopmentEventKind::ProcessExited,
699 serde_json::json!({"name": name, "state": snapshot.state}),
700 )?;
701 Ok(snapshot)
702 }
703
704 pub fn run_verification(
705 &mut self,
706 name: &str,
707 command: &str,
708 timeout: Duration,
709 ) -> DevelopmentResult<super::ProcessSnapshot> {
710 self.record(
711 DevelopmentEventKind::TestStarted,
712 serde_json::json!({
713 "name": name,
714 "commandBytes": command.len(),
715 "commandSha256": hash(command)
716 }),
717 )?;
718 #[cfg(windows)]
719 {
720 let snapshot = self.processes.run_bounded(name, command, timeout)?;
721 self.record(
722 DevelopmentEventKind::TestCompleted,
723 serde_json::json!({
724 "name": name,
725 "state": snapshot.state,
726 "outputBytes": snapshot.output.len(),
727 "outputSha256": hash(&snapshot.output)
728 }),
729 )?;
730 return Ok(snapshot);
731 }
732 #[cfg(not(windows))]
733 self.start_process(name, command)?;
734 #[cfg(not(windows))]
735 self.processes.close_input(name)?;
736 #[cfg(not(windows))]
737 let deadline = Instant::now() + timeout;
738 #[cfg(not(windows))]
739 let snapshot = loop {
740 let snapshot = self
741 .processes
742 .poll()?
743 .into_iter()
744 .find(|snapshot| snapshot.name == name)
745 .ok_or_else(|| DevelopmentError::NotFound(format!("process {name}")))?;
746 if !matches!(snapshot.state, super::ProcessState::Running) {
747 break snapshot;
748 }
749 if Instant::now() >= deadline {
750 self.stop_process(name)?;
751 self.record(
752 DevelopmentEventKind::TestCompleted,
753 serde_json::json!({"name": name, "status": "timeout"}),
754 )?;
755 return Err(DevelopmentError::Process(format!(
756 "verification {name} exceeded {} seconds",
757 timeout.as_secs()
758 )));
759 }
760 std::thread::sleep(Duration::from_millis(25));
761 };
762 #[cfg(not(windows))]
763 self.record(
764 DevelopmentEventKind::TestCompleted,
765 serde_json::json!({
766 "name": name,
767 "state": snapshot.state,
768 "outputBytes": snapshot.output.len(),
769 "outputSha256": hash(&snapshot.output)
770 }),
771 )?;
772 #[cfg(not(windows))]
773 Ok(snapshot)
774 }
775
776 pub fn run_command_to_completion(
777 &mut self,
778 name: &str,
779 command: &str,
780 timeout: Duration,
781 ) -> DevelopmentResult<super::ProcessSnapshot> {
782 #[cfg(windows)]
783 return self.processes.run_bounded(name, command, timeout);
784
785 #[cfg(not(windows))]
786 self.start_process(name, command)?;
787 #[cfg(not(windows))]
788 self.processes.close_input(name)?;
789 #[cfg(not(windows))]
790 let deadline = Instant::now() + timeout;
791 #[cfg(not(windows))]
792 loop {
793 let snapshot = self
794 .processes
795 .poll()?
796 .into_iter()
797 .find(|snapshot| snapshot.name == name)
798 .ok_or_else(|| DevelopmentError::NotFound(format!("process {name}")))?;
799 if !matches!(snapshot.state, super::ProcessState::Running) {
800 self.record(
801 DevelopmentEventKind::ProcessExited,
802 serde_json::json!({
803 "name": name,
804 "state": snapshot.state,
805 "outputBytes": snapshot.output.len(),
806 "outputSha256": hash(&snapshot.output)
807 }),
808 )?;
809 return Ok(snapshot);
810 }
811 if Instant::now() >= deadline {
812 self.stop_process(name)?;
813 return Err(DevelopmentError::Process(format!(
814 "command {name} exceeded {} seconds",
815 timeout.as_secs()
816 )));
817 }
818 std::thread::sleep(Duration::from_millis(25));
819 }
820 }
821
822 pub fn confirm_live_update(
827 &mut self,
828 source_path: &str,
829 before_revision: u64,
830 after_revision: u64,
831 semantic_changes: usize,
832 actor: Actor,
833 ) -> DevelopmentResult<()> {
834 self.resolve_path(source_path, false)?;
835 if after_revision <= before_revision {
836 return Err(DevelopmentError::InvalidInput(
837 "live update proof requires a newer browser revision".into(),
838 ));
839 }
840 self.record_as(
841 actor,
842 DevelopmentEventKind::HmrObserved,
843 serde_json::json!({
844 "sourcePath": source_path,
845 "status": "confirmed-runtime-observation",
846 "beforeBrowserRevision": before_revision,
847 "afterBrowserRevision": after_revision,
848 "semanticChanges": semantic_changes,
849 }),
850 )
851 }
852
853 #[allow(clippy::too_many_arguments)]
854 pub fn link_runtime_source(
855 &mut self,
856 entity_id: &str,
857 path: &str,
858 start_line: u32,
859 end_line: u32,
860 provenance: LinkProvenance,
861 detail: &str,
862 confidence: f32,
863 actor: Actor,
864 ) -> DevelopmentResult<RuntimeLink> {
865 let (_, relative) = self.resolve_path(path, false)?;
866 let link = RuntimeLink {
867 entity_id: entity_id.into(),
868 source: SourceLocation::new(relative, start_line, end_line)?,
869 evidence: LinkEvidence {
870 provenance,
871 detail: detail.into(),
872 confidence,
873 },
874 };
875 self.graph.link(link.clone())?;
876 self.graph.save(&self.graph_path)?;
877 self.revision = self.revision.saturating_add(1);
878 self.record_as(
879 actor,
880 DevelopmentEventKind::SourceRuntimeLinked,
881 serde_json::to_value(&link)?,
882 )?;
883 Ok(link)
884 }
885
886 pub fn diff(&mut self) -> DevelopmentResult<ProjectDiff> {
887 build_diff(&self.root, &self.timeline, &self.graph, &mut self.processes)
888 }
889
890 pub fn discover_runtime_links(&mut self) -> DevelopmentResult<Vec<RuntimeLink>> {
891 let discovered = self.graph.discover_explicit_markers(&self.root)?;
892 self.graph.save(&self.graph_path)?;
893 for link in &discovered {
894 self.record(
895 DevelopmentEventKind::SourceRuntimeLinked,
896 serde_json::to_value(link)?,
897 )?;
898 }
899 if !discovered.is_empty() {
900 self.revision = self.revision.saturating_add(1);
901 }
902 Ok(discovered)
903 }
904
905 pub fn publish_rust_diagnostics(
906 &mut self,
907 path: &str,
908 ) -> DevelopmentResult<Vec<LanguageDiagnostic>> {
909 if self.language.is_none() {
910 self.language = Some(LspClient::rust_analyzer(&self.root)?);
911 }
912 let diagnostics = self
913 .language
914 .as_mut()
915 .expect("language client initialized")
916 .diagnostics(path)?;
917 self.diagnostics.insert(path.into(), diagnostics.clone());
918 self.record(
919 DevelopmentEventKind::DiagnosticsPublished,
920 serde_json::json!({"path": path, "count": diagnostics.len(), "diagnostics": diagnostics}),
921 )?;
922 Ok(diagnostics)
923 }
924
925 pub fn evaluate_semantic_breakpoints(
926 &mut self,
927 breakpoints: &[SemanticBreakpoint],
928 before: &SemanticSnapshot,
929 after: &SemanticSnapshot,
930 ) -> DevelopmentResult<Vec<SemanticBreakpointHit>> {
931 let hits = super::evaluate_breakpoints(breakpoints, before, after, &self.graph);
932 for hit in &hits {
933 self.record(
934 DevelopmentEventKind::SemanticBreakpointHit,
935 serde_json::to_value(hit)?,
936 )?;
937 }
938 Ok(hits)
939 }
940
941 pub fn replay(&self, start: usize, limit: usize) -> DevelopmentResult<ReplayWindow> {
942 super::replay(&self.timeline, start, limit)
943 }
944
945 pub fn search(&mut self, query: &str, limit: usize) -> DevelopmentResult<Vec<SearchHit>> {
946 if query.trim().is_empty() || query.len() > 256 || limit == 0 || limit > 256 {
947 return Err(DevelopmentError::InvalidInput(
948 "search requires a 1-256 byte query and a 1-256 result limit".into(),
949 ));
950 }
951 let mut hits = Vec::new();
952 for file in self.list_files()? {
953 if let Some(score) = super::fuzzy_score(query, &file.path) {
954 hits.push(SearchHit {
955 kind: SearchKind::File,
956 label: file.path,
957 detail: file.git_status.unwrap_or_else(|| "project file".into()),
958 score,
959 });
960 }
961 }
962 for entity in self.graph.links.keys() {
963 if let Some(score) = super::fuzzy_score(query, entity) {
964 hits.push(SearchHit {
965 kind: SearchKind::BrowserEntity,
966 label: entity.clone(),
967 detail: "runtime/source graph entity".into(),
968 score,
969 });
970 }
971 }
972 for process in self.processes.list_checked()? {
973 if let Some(score) = super::fuzzy_score(query, &process.name) {
974 hits.push(SearchHit {
975 kind: SearchKind::Process,
976 label: process.name,
977 detail: format!("{:?}", process.state),
978 score,
979 });
980 }
981 }
982 for event in self.timeline.events() {
983 let label = format!("{:?}", event.kind);
984 if let Some(score) = super::fuzzy_score(query, &label) {
985 hits.push(SearchHit {
986 kind: SearchKind::Event,
987 label,
988 detail: event.id.clone(),
989 score,
990 });
991 }
992 }
993 for command in [
994 "project files",
995 "project open",
996 "project diagnostics",
997 "project run",
998 "project diff",
999 "project timeline",
1000 "project replay",
1001 "project graph",
1002 "project experiment",
1003 "project neovim",
1004 "agent prompt",
1005 ] {
1006 if let Some(score) = super::fuzzy_score(query, command) {
1007 hits.push(SearchHit {
1008 kind: SearchKind::Command,
1009 label: command.into(),
1010 detail: "command palette".into(),
1011 score,
1012 });
1013 }
1014 }
1015 Ok(super::rank(hits, limit))
1016 }
1017
1018 pub fn record(
1019 &mut self,
1020 kind: DevelopmentEventKind,
1021 payload: serde_json::Value,
1022 ) -> DevelopmentResult<()> {
1023 self.record_as(self.actor.clone(), kind, payload)
1024 }
1025
1026 pub fn record_as(
1027 &mut self,
1028 actor: Actor,
1029 kind: DevelopmentEventKind,
1030 payload: serde_json::Value,
1031 ) -> DevelopmentResult<()> {
1032 self.timeline
1033 .record(actor, kind, self.root.display().to_string(), payload)?;
1034 Ok(())
1035 }
1036
1037 fn resolve_path(
1038 &self,
1039 input: &str,
1040 allow_missing: bool,
1041 ) -> DevelopmentResult<(PathBuf, String)> {
1042 if input.is_empty() || input.len() > 512 {
1043 return Err(DevelopmentError::InvalidInput(
1044 "relative path must be 1-512 bytes".into(),
1045 ));
1046 }
1047 let path = Path::new(input);
1048 if path.is_absolute()
1049 || path
1050 .components()
1051 .any(|component| matches!(component, Component::ParentDir))
1052 {
1053 return Err(DevelopmentError::PathOutsideWorkspace(path.to_path_buf()));
1054 }
1055 let candidate = self.root.join(path);
1056 let mut existing_parent = candidate
1057 .parent()
1058 .ok_or_else(|| DevelopmentError::InvalidInput("path has no parent".into()))?;
1059 while !existing_parent.exists() {
1060 existing_parent = existing_parent
1061 .parent()
1062 .ok_or_else(|| DevelopmentError::PathOutsideWorkspace(candidate.clone()))?;
1063 }
1064 let canonical_parent = fs::canonicalize(existing_parent)?;
1065 if !canonical_parent.starts_with(&self.root) {
1066 return Err(DevelopmentError::PathOutsideWorkspace(candidate));
1067 }
1068 if candidate.exists() {
1069 let canonical = fs::canonicalize(&candidate)?;
1070 if !canonical.starts_with(&self.root) {
1071 return Err(DevelopmentError::PathOutsideWorkspace(candidate));
1072 }
1073 } else if !allow_missing {
1074 return Err(DevelopmentError::NotFound(input.into()));
1075 }
1076 Ok((candidate, portable_relative_path(path)))
1077 }
1078}
1079
1080fn portable_relative_path(path: &Path) -> String {
1081 path.components()
1082 .map(|component| component.as_os_str().to_string_lossy())
1083 .collect::<Vec<_>>()
1084 .join("/")
1085}
1086
1087pub fn detect_project(root: impl AsRef<Path>) -> DevelopmentResult<ProjectDetection> {
1088 let root = canonical_root(root.as_ref())?;
1089 let config_path = [root.join("glass.toml"), root.join(".glass.toml")]
1090 .into_iter()
1091 .find(|path| path.is_file());
1092 let mut languages = Vec::new();
1093 if root.join("Cargo.toml").is_file() {
1094 languages.push("Rust".into());
1095 }
1096 if root.join("package.json").is_file() {
1097 languages.push("JavaScript/TypeScript".into());
1098 }
1099 if root.join("pyproject.toml").is_file() || root.join("requirements.txt").is_file() {
1100 languages.push("Python".into());
1101 }
1102 if root.join("go.mod").is_file() {
1103 languages.push("Go".into());
1104 }
1105 let package_manager = if root.join("pnpm-lock.yaml").is_file() {
1106 Some("pnpm".into())
1107 } else if root.join("yarn.lock").is_file() {
1108 Some("yarn".into())
1109 } else if root.join("bun.lockb").is_file() || root.join("bun.lock").is_file() {
1110 Some("bun".into())
1111 } else if root.join("package-lock.json").is_file() {
1112 Some("npm".into())
1113 } else if root.join("Cargo.lock").is_file() {
1114 Some("cargo".into())
1115 } else {
1116 None
1117 };
1118 let framework = detect_framework(&root);
1119 let config = load_project_config(config_path.as_deref())?;
1120 let defaults = default_commands(&root, package_manager.as_deref());
1121 let build_system = if root.join("Cargo.toml").is_file() {
1122 Some("cargo".into())
1123 } else if root.join("package.json").is_file() {
1124 Some(package_manager.clone().unwrap_or_else(|| "npm".into()))
1125 } else if root.join("pyproject.toml").is_file() {
1126 Some("pyproject".into())
1127 } else if root.join("go.mod").is_file() {
1128 Some("go".into())
1129 } else {
1130 None
1131 };
1132 let formatter = if root.join("Cargo.toml").is_file() {
1133 Some("rustfmt".into())
1134 } else if root.join("package.json").is_file() {
1135 Some("prettier".into())
1136 } else if root.join("pyproject.toml").is_file() {
1137 Some("ruff format".into())
1138 } else if root.join("go.mod").is_file() {
1139 Some("gofmt".into())
1140 } else {
1141 None
1142 };
1143 let lsp_servers = [
1144 ("Rust", "rust-analyzer"),
1145 ("JavaScript/TypeScript", "typescript-language-server"),
1146 ("Python", "pyright-langserver"),
1147 ("Go", "gopls"),
1148 ]
1149 .into_iter()
1150 .filter(|(language, server)| {
1151 languages.iter().any(|value| value == language) && command_available(server)
1152 })
1153 .map(|(_, server)| server.to_string())
1154 .collect();
1155 let browser_url = config.browser.url;
1156 let local_development_urls = browser_url.iter().cloned().collect();
1157 Ok(ProjectDetection {
1158 root: root.clone(),
1159 languages,
1160 package_manager,
1161 framework,
1162 build_system,
1163 formatter,
1164 lsp_servers,
1165 git_branch: git_branch(&root),
1166 dev_command: config.commands.dev.or(defaults.0),
1167 test_command: config.commands.test.or(defaults.1),
1168 lint_command: config.commands.lint.or(defaults.2),
1169 build_command: config.commands.build.or(defaults.3),
1170 browser_url,
1171 local_development_urls,
1172 editor_engine: config.editor.engine,
1173 agent_harness: config.agent.harness,
1174 config_path,
1175 })
1176}
1177
1178fn load_project_config(path: Option<&Path>) -> DevelopmentResult<GlassProjectConfig> {
1179 path.map(fs::read_to_string)
1180 .transpose()?
1181 .map(|text| {
1182 toml::from_str::<GlassProjectConfig>(&text)
1183 .map_err(|error| DevelopmentError::Config(error.to_string()))
1184 })
1185 .transpose()
1186 .map(Option::unwrap_or_default)
1187}
1188
1189pub(crate) fn canonical_root(root: &Path) -> DevelopmentResult<PathBuf> {
1190 let root = if root.is_file() {
1191 root.parent().unwrap_or(root)
1192 } else {
1193 root
1194 };
1195 let root = fs::canonicalize(root)?;
1196 if !root.is_dir() {
1197 return Err(DevelopmentError::InvalidInput(
1198 "project root must be a directory".into(),
1199 ));
1200 }
1201 Ok(root)
1202}
1203
1204fn visit_files(
1205 root: &Path,
1206 current: &Path,
1207 result: &mut ProjectTreeResult,
1208) -> DevelopmentResult<()> {
1209 if result.entries.len() >= MAX_FILE_ENTRIES {
1210 result.truncated = true;
1211 return Ok(());
1212 }
1213 let mut children =
1214 fs::read_dir(current).map(|entries| entries.collect::<Result<Vec<_>, _>>())??;
1215 children.sort_by_key(|entry| entry.file_name());
1216 for entry in children {
1217 if result.entries.len() >= MAX_FILE_ENTRIES {
1218 result.truncated = true;
1219 break;
1220 }
1221 let path = entry.path();
1222 let name = entry.file_name().to_string_lossy().into_owned();
1223 if name == ".git" || name == "target" || name == "node_modules" || name == ".glass" {
1224 result.ignored_directories.push(name);
1225 continue;
1226 }
1227 let metadata = fs::symlink_metadata(&path)?;
1228 if metadata.file_type().is_symlink() {
1229 result.skipped_symlinks = result.skipped_symlinks.saturating_add(1);
1230 continue;
1231 }
1232 let relative = path
1233 .strip_prefix(root)
1234 .map_err(|_| DevelopmentError::PathOutsideWorkspace(path.clone()))?;
1235 let relative = portable_relative_path(relative);
1236 if metadata.is_dir() {
1237 result.entries.push(FileEntry {
1238 path: relative,
1239 kind: FileKind::Directory,
1240 bytes: None,
1241 git_status: None,
1242 dirty: false,
1243 actor: None,
1244 });
1245 visit_files(root, &path, result)?;
1246 } else if metadata.is_file() {
1247 result.entries.push(FileEntry {
1248 path: relative,
1249 kind: FileKind::File,
1250 bytes: Some(metadata.len()),
1251 git_status: None,
1252 dirty: false,
1253 actor: None,
1254 });
1255 }
1256 }
1257 Ok(())
1258}
1259
1260fn read_existing(root: &Path, path: &str) -> DevelopmentResult<String> {
1261 let absolute = root.join(path);
1262 read_bounded_utf8(&absolute, MAX_BUFFER_BYTES, "existing editor file")
1263}
1264
1265fn hash(content: &str) -> String {
1266 Sha256::digest(content.as_bytes())
1267 .iter()
1268 .map(|byte| format!("{byte:02x}"))
1269 .collect()
1270}
1271
1272fn git_branch(root: &Path) -> Option<String> {
1273 Command::new("git")
1274 .args(["rev-parse", "--abbrev-ref", "HEAD"])
1275 .current_dir(root)
1276 .output()
1277 .ok()
1278 .filter(|output| output.status.success())
1279 .and_then(|output| String::from_utf8(output.stdout).ok())
1280 .map(|branch| branch.trim().to_string())
1281 .filter(|branch| !branch.is_empty())
1282}
1283
1284fn git_statuses(root: &Path) -> BTreeMap<String, String> {
1285 let Some(output) = Command::new("git")
1286 .args(["status", "--porcelain=v1", "-z", "--untracked-files=all"])
1287 .current_dir(root)
1288 .output()
1289 .ok()
1290 .filter(|output| output.status.success())
1291 else {
1292 return BTreeMap::new();
1293 };
1294 let mut statuses = BTreeMap::new();
1295 for entry in output
1296 .stdout
1297 .split(|byte| *byte == 0)
1298 .filter(|entry| entry.len() >= 4)
1299 {
1300 let status = String::from_utf8_lossy(&entry[..2]).trim().to_string();
1301 let path = String::from_utf8_lossy(&entry[3..]).into_owned();
1302 if !path.is_empty() {
1303 statuses.insert(path, status);
1304 }
1305 }
1306 statuses
1307}
1308
1309fn detect_framework(root: &Path) -> Option<String> {
1310 if let Ok(package) = fs::read_to_string(root.join("package.json"))
1311 && let Ok(value) = serde_json::from_str::<serde_json::Value>(&package)
1312 {
1313 let dependencies = value
1314 .get("dependencies")
1315 .and_then(serde_json::Value::as_object);
1316 let dev_dependencies = value
1317 .get("devDependencies")
1318 .and_then(serde_json::Value::as_object);
1319 if let Some(framework) =
1320 ["next", "vite", "react", "vue", "svelte"]
1321 .into_iter()
1322 .find(|framework| {
1323 dependencies.is_some_and(|values| values.contains_key(*framework))
1324 || dev_dependencies.is_some_and(|values| values.contains_key(*framework))
1325 })
1326 {
1327 return Some(framework.into());
1328 }
1329 }
1330 let python = fs::read_to_string(root.join("pyproject.toml"))
1331 .or_else(|_| fs::read_to_string(root.join("requirements.txt")))
1332 .unwrap_or_default()
1333 .to_ascii_lowercase();
1334 ["django", "flask", "fastapi"]
1335 .into_iter()
1336 .find(|framework| python.contains(framework))
1337 .map(str::to_string)
1338}
1339
1340fn default_commands(
1341 root: &Path,
1342 package_manager: Option<&str>,
1343) -> (
1344 Option<String>,
1345 Option<String>,
1346 Option<String>,
1347 Option<String>,
1348) {
1349 if root.join("Cargo.toml").is_file() {
1350 return (
1351 None,
1352 Some("cargo test".into()),
1353 Some("cargo clippy --all-targets --all-features -- -D warnings".into()),
1354 Some("cargo build".into()),
1355 );
1356 }
1357 if root.join("package.json").is_file() {
1358 let manager = package_manager.unwrap_or("npm");
1359 let package = fs::read_to_string(root.join("package.json"))
1360 .ok()
1361 .and_then(|value| serde_json::from_str::<serde_json::Value>(&value).ok());
1362 let command = |script: &str| {
1363 package
1364 .as_ref()
1365 .and_then(|value| value.pointer(&format!("/scripts/{script}")))
1366 .and_then(serde_json::Value::as_str)
1367 .map(|_| format!("{manager} run {script}"))
1368 };
1369 return (
1370 command("dev"),
1371 command("test"),
1372 command("lint"),
1373 command("build"),
1374 );
1375 }
1376 if root.join("pyproject.toml").is_file() {
1377 return (
1378 None,
1379 Some("python -m pytest".into()),
1380 Some("ruff check .".into()),
1381 None,
1382 );
1383 }
1384 if root.join("go.mod").is_file() {
1385 return (
1386 None,
1387 Some("go test ./...".into()),
1388 Some("go vet ./...".into()),
1389 Some("go build ./...".into()),
1390 );
1391 }
1392 (None, None, None, None)
1393}
1394
1395fn command_available(command: &str) -> bool {
1396 Command::new(command)
1397 .arg("--version")
1398 .stdout(std::process::Stdio::null())
1399 .stderr(std::process::Stdio::null())
1400 .status()
1401 .is_ok_and(|status| status.success())
1402}
1403
1404#[cfg(test)]
1405mod tests {
1406 use super::*;
1407 use std::sync::atomic::{AtomicUsize, Ordering};
1408
1409 fn fixture() -> PathBuf {
1410 static NEXT_FIXTURE: AtomicUsize = AtomicUsize::new(0);
1411 let root = std::env::temp_dir().join(format!(
1412 "glass-project-{}-{}",
1413 std::process::id(),
1414 NEXT_FIXTURE.fetch_add(1, Ordering::Relaxed)
1415 ));
1416 let _ = fs::remove_dir_all(&root);
1417 fs::create_dir_all(root.join("src")).unwrap();
1418 fs::write(
1419 root.join("Cargo.toml"),
1420 "[package]\nname='fixture'\nversion='0.1.0'\nedition='2024'\n",
1421 )
1422 .unwrap();
1423 fs::write(root.join("src/main.rs"), "fn main() {}\n").unwrap();
1424 root
1425 }
1426
1427 #[test]
1428 fn detects_cargo_project_and_defaults() {
1429 let root = fixture();
1430 let detection = detect_project(&root).unwrap();
1431 assert_eq!(detection.languages, vec!["Rust"]);
1432 assert_eq!(detection.test_command.as_deref(), Some("cargo test"));
1433 let _ = fs::remove_dir_all(root);
1434 }
1435
1436 #[test]
1437 fn event_feed_reads_do_not_record_monitoring_activity() {
1438 let root = fixture();
1439 drop(ProjectWorkspace::open(&root).unwrap());
1440 let before = ProjectWorkspace::timeline_snapshot(&root).unwrap();
1441 let page = ProjectWorkspace::event_page(&root, None, 64).unwrap();
1442 let after = ProjectWorkspace::timeline_snapshot(&root).unwrap();
1443 assert_eq!(page.events, before);
1444 assert_eq!(after, before);
1445 let _ = fs::remove_dir_all(root);
1446 }
1447
1448 #[test]
1449 fn file_writes_are_confined_and_atomic() {
1450 let root = fixture();
1451 let mut project = ProjectWorkspace::open(&root).unwrap();
1452 project
1453 .write_file("src/lib.rs", "pub fn ok() {}\n", Actor::local())
1454 .unwrap();
1455 assert!(
1456 project
1457 .read_file("src/lib.rs")
1458 .unwrap()
1459 .contains("pub fn ok")
1460 );
1461 assert!(matches!(
1462 project.write_file("../escape", "bad", Actor::local()),
1463 Err(DevelopmentError::PathOutsideWorkspace(_))
1464 ));
1465 let _ = fs::remove_dir_all(root);
1466 }
1467
1468 #[test]
1469 fn editor_save_records_actor_and_clears_dirty_state() {
1470 let root = fixture();
1471 let mut project = ProjectWorkspace::open(&root).unwrap();
1472 project.open_buffer("src/main.rs", Actor::local()).unwrap();
1473 project
1474 .edit_buffer(
1475 "src/main.rs",
1476 "fn main() { println!(\"ok\"); }\n".into(),
1477 Actor::local(),
1478 )
1479 .unwrap();
1480 assert!(project.buffer("src/main.rs").unwrap().dirty);
1481 project.save_buffer("src/main.rs").unwrap();
1482 assert!(!project.buffer("src/main.rs").unwrap().dirty);
1483 assert!(
1484 project
1485 .timeline()
1486 .events()
1487 .any(|event| matches!(event.kind, DevelopmentEventKind::FileSaved))
1488 );
1489 let _ = fs::remove_dir_all(root);
1490 }
1491
1492 #[test]
1493 fn editor_undo_redo_and_external_change_conflicts_are_explicit() {
1494 let root = fixture();
1495 let mut project = ProjectWorkspace::open(&root).unwrap();
1496 project.open_buffer("src/main.rs", Actor::local()).unwrap();
1497 project
1498 .edit_buffer("src/main.rs", "one".into(), Actor::local())
1499 .unwrap();
1500 project
1501 .edit_buffer("src/main.rs", "two".into(), Actor::local())
1502 .unwrap();
1503 assert_eq!(project.undo_buffer("src/main.rs").unwrap().content, "one");
1504 assert_eq!(project.redo_buffer("src/main.rs").unwrap().content, "two");
1505 fs::write(root.join("src/main.rs"), "external").unwrap();
1506 assert!(matches!(
1507 project.save_buffer("src/main.rs"),
1508 Err(DevelopmentError::Conflict(_))
1509 ));
1510 let _ = fs::remove_dir_all(root);
1511 }
1512
1513 #[test]
1514 fn file_operations_support_nested_create_rename_and_safe_delete() {
1515 let root = fixture();
1516 let mut project = ProjectWorkspace::open(&root).unwrap();
1517 project
1518 .edit_buffer("nested/new.txt", "hello".into(), Actor::local())
1519 .unwrap();
1520 project.save_buffer("nested/new.txt").unwrap();
1521 project
1522 .rename_path("nested/new.txt", "nested/renamed.txt", Actor::local())
1523 .unwrap();
1524 assert!(root.join("nested/renamed.txt").is_file());
1525 project
1526 .delete_path("nested/renamed.txt", Actor::local())
1527 .unwrap();
1528 project.delete_path("nested", Actor::local()).unwrap();
1529 assert!(!root.join("nested").exists());
1530 let _ = fs::remove_dir_all(root);
1531 }
1532
1533 #[test]
1534 fn project_tree_reports_ignore_and_symlink_semantics() {
1535 let root = fixture();
1536 fs::create_dir_all(root.join("target/debug")).unwrap();
1537 fs::write(root.join("target/debug/ignored"), "ignored").unwrap();
1538 #[cfg(unix)]
1539 std::os::unix::fs::symlink(root.join("src/main.rs"), root.join("linked.rs")).unwrap();
1540 let project = ProjectWorkspace::open(&root).unwrap();
1541 let tree = project.list_files_result().unwrap();
1542 assert_eq!(tree.limit, MAX_FILE_ENTRIES);
1543 assert!(tree.ignored_directories.contains(&"target".to_string()));
1544 assert!(
1545 !tree
1546 .entries
1547 .iter()
1548 .any(|entry| entry.path.contains("ignored"))
1549 );
1550 #[cfg(unix)]
1551 assert_eq!(tree.skipped_symlinks, 1);
1552 let _ = fs::remove_dir_all(root);
1553 }
1554}