1use super::editor::{selection_offsets, text_position_at_offset, text_position_offset};
2use super::{
3 Actor, DevelopmentError, DevelopmentEventKind, DevelopmentGraph, DevelopmentResult,
4 LanguageDiagnostic, LspClient, MAX_BUFFER_BYTES, MAX_FILE_BYTES, MAX_FILE_ENTRIES,
5 ProcessManager, ReplayWindow, SearchHit, SearchKind, SemanticBreakpoint, SemanticBreakpointHit,
6 SemanticSnapshot, SourceLocation, Timeline, read_bounded_utf8,
7};
8use crate::development::diff::{ProjectDiff, build_diff};
9use crate::development::graph::{LinkEvidence, LinkProvenance, RuntimeLink};
10use serde::{Deserialize, Serialize};
11use sha2::{Digest, Sha256};
12use std::{
13 collections::BTreeMap,
14 fs::{self, OpenOptions},
15 io::Write,
16 path::{Component, Path, PathBuf},
17 process::Command,
18 sync::Mutex,
19 time::{Duration, Instant},
20};
21
22#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
23#[serde(rename_all = "camelCase")]
24pub struct GlassProjectConfig {
25 #[serde(default)]
26 pub project: ProjectConfig,
27 #[serde(default)]
28 pub commands: CommandConfig,
29 #[serde(default)]
30 pub browser: BrowserConfig,
31 #[serde(default)]
32 pub editor: EditorConfig,
33 #[serde(default)]
34 pub agent: AgentConfig,
35}
36
37#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
38pub struct ProjectConfig {
39 #[serde(default)]
40 pub name: Option<String>,
41}
42
43#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
44pub struct CommandConfig {
45 #[serde(default)]
46 pub dev: Option<String>,
47 #[serde(default)]
48 pub test: Option<String>,
49 #[serde(default)]
50 pub lint: Option<String>,
51 #[serde(default)]
52 pub build: Option<String>,
53}
54
55#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
56pub struct BrowserConfig {
57 #[serde(default)]
58 pub url: Option<String>,
59}
60
61#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
62pub struct EditorConfig {
63 #[serde(default)]
64 pub engine: Option<String>,
65}
66
67#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
68pub struct AgentConfig {
69 #[serde(default)]
70 pub harness: Option<String>,
71}
72
73#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
74#[serde(rename_all = "camelCase")]
75pub struct ProjectDetection {
76 pub root: PathBuf,
77 pub languages: Vec<String>,
78 pub package_manager: Option<String>,
79 pub framework: Option<String>,
80 pub build_system: Option<String>,
81 pub formatter: Option<String>,
82 pub lsp_servers: Vec<String>,
83 pub git_branch: Option<String>,
84 pub dev_command: Option<String>,
85 pub test_command: Option<String>,
86 pub lint_command: Option<String>,
87 pub build_command: Option<String>,
88 pub browser_url: Option<String>,
89 pub local_development_urls: Vec<String>,
90 pub editor_engine: Option<String>,
91 pub agent_harness: Option<String>,
92 pub config_path: Option<PathBuf>,
93}
94
95#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
96#[serde(rename_all = "camelCase")]
97pub enum FileKind {
98 File,
99 Directory,
100}
101
102#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
103#[serde(rename_all = "camelCase")]
104pub struct FileEntry {
105 pub path: String,
106 pub kind: FileKind,
107 pub bytes: Option<u64>,
108 #[serde(default, skip_serializing_if = "Option::is_none")]
109 pub git_status: Option<String>,
110 #[serde(default)]
111 pub dirty: bool,
112 #[serde(default, skip_serializing_if = "Option::is_none")]
113 pub actor: Option<Actor>,
114}
115
116#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
118#[serde(rename_all = "camelCase")]
119pub struct ProjectTreeResult {
120 pub entries: Vec<FileEntry>,
121 pub truncated: bool,
122 pub limit: usize,
123 pub ignored_directories: Vec<String>,
124 pub skipped_symlinks: usize,
125}
126
127#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
128#[serde(rename_all = "camelCase")]
129pub struct EditorBuffer {
130 pub path: String,
131 pub content: String,
132 pub original_hash: String,
133 pub dirty: bool,
134 pub cursor_line: u32,
135 pub cursor_column: u32,
136 #[serde(default, skip_serializing_if = "Option::is_none")]
137 pub selection: Option<super::TextSelection>,
138 pub actor: Actor,
139}
140
141pub struct ProjectWorkspace {
142 root: PathBuf,
143 detection: ProjectDetection,
144 config: GlassProjectConfig,
145 buffers: BTreeMap<String, EditorBuffer>,
146 undo: BTreeMap<String, Vec<String>>,
147 redo: BTreeMap<String, Vec<String>>,
148 processes: ProcessManager,
149 timeline: Timeline,
150 graph: DevelopmentGraph,
151 graph_path: PathBuf,
152 collaboration: super::CollaborationBus,
153 diagnostics: BTreeMap<String, Vec<LanguageDiagnostic>>,
154 language: Option<LspClient>,
155 tree_cache: Mutex<Option<(Instant, ProjectTreeResult)>>,
156 actors: BTreeMap<String, Actor>,
157 actor: Actor,
158 revision: u64,
159 comments: BTreeMap<String, Vec<super::EditorComment>>,
160 proposals: BTreeMap<String, super::EditorProposal>,
161 checkpoints: BTreeMap<String, super::EditorCheckpoint>,
162 checkpoints_path: PathBuf,
163 next_editor_id: u64,
164}
165
166impl std::fmt::Debug for ProjectWorkspace {
167 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
168 formatter
169 .debug_struct("ProjectWorkspace")
170 .field("root", &self.root)
171 .field("detection", &self.detection)
172 .field("buffers", &self.buffers.keys().collect::<Vec<_>>())
173 .field("revision", &self.revision)
174 .finish()
175 }
176}
177
178impl ProjectWorkspace {
179 pub fn event_page(
182 root: impl AsRef<Path>,
183 after_id: Option<&str>,
184 limit: usize,
185 ) -> DevelopmentResult<super::DevelopmentEventPage> {
186 let root = canonical_root(root.as_ref())?;
187 Ok(Timeline::for_project(&root)?.events_after(after_id, limit))
188 }
189
190 pub fn timeline_snapshot(
191 root: impl AsRef<Path>,
192 ) -> DevelopmentResult<Vec<super::DevelopmentEvent>> {
193 let root = canonical_root(root.as_ref())?;
194 Ok(Timeline::for_project(&root)?.events().cloned().collect())
195 }
196
197 pub fn open(root: impl AsRef<Path>) -> DevelopmentResult<Self> {
198 let root = canonical_root(root.as_ref())?;
199 let detection = detect_project(&root)?;
200 let config = load_project_config(detection.config_path.as_deref())?;
201 let timeline = Timeline::for_project(&root)?;
202 let graph_path = timeline.path().with_file_name("graph.json");
203 let checkpoints_path = timeline.path().with_file_name("editor-checkpoints.json");
204 let graph = DevelopmentGraph::load(&graph_path)?;
205 let checkpoints = load_editor_checkpoints(&checkpoints_path)?;
206 let comments = comments_from_timeline(&timeline);
207 let proposals = proposals_from_timeline(&timeline);
208 let next_editor_id = timeline.events().count() as u64 + 1;
209 let actor = Actor::local();
210 let mut actors = BTreeMap::new();
211 actors.insert(actor.id.clone(), actor.clone());
212 let embedded = Actor::embedded();
213 actors.insert(embedded.id.clone(), embedded);
214 for event in timeline.events() {
215 if matches!(event.kind, DevelopmentEventKind::ActorJoined) {
216 actors.insert(event.actor.id.clone(), event.actor.clone());
217 }
218 }
219 let mut workspace = Self {
220 root: root.clone(),
221 detection,
222 config,
223 buffers: BTreeMap::new(),
224 undo: BTreeMap::new(),
225 redo: BTreeMap::new(),
226 processes: ProcessManager::new(&root),
227 timeline,
228 graph,
229 graph_path,
230 collaboration: super::CollaborationBus::default(),
231 diagnostics: BTreeMap::new(),
232 language: None,
233 tree_cache: Mutex::new(None),
234 actors,
235 actor,
236 revision: 0,
237 comments,
238 proposals,
239 checkpoints,
240 checkpoints_path,
241 next_editor_id,
242 };
243 let _ = workspace.record(
244 DevelopmentEventKind::WorkspaceOpened,
245 serde_json::json!({"root": root}),
246 );
247 Ok(workspace)
248 }
249
250 pub fn root(&self) -> &Path {
251 &self.root
252 }
253
254 pub fn detection(&self) -> &ProjectDetection {
255 &self.detection
256 }
257
258 pub fn config(&self) -> &GlassProjectConfig {
259 &self.config
260 }
261
262 pub fn revision(&self) -> u64 {
263 self.revision
264 }
265
266 pub fn timeline(&self) -> &Timeline {
267 &self.timeline
268 }
269
270 pub fn graph(&self) -> &DevelopmentGraph {
271 &self.graph
272 }
273
274 pub fn diagnostics(&self) -> &BTreeMap<String, Vec<LanguageDiagnostic>> {
275 &self.diagnostics
276 }
277
278 fn invalidate_tree_cache(&self) {
279 if let Ok(mut cache) = self.tree_cache.lock() {
280 *cache = None;
281 }
282 }
283
284 pub fn actors(&self) -> impl Iterator<Item = &Actor> {
285 self.actors.values()
286 }
287
288 pub fn collaboration(&mut self) -> &mut super::CollaborationBus {
289 &mut self.collaboration
290 }
291
292 pub fn set_buffer_selection(
293 &mut self,
294 path: &str,
295 selection: Option<super::TextSelection>,
296 actor: Actor,
297 ) -> DevelopmentResult<EditorBuffer> {
298 let content = self
299 .buffers
300 .get(path)
301 .map(|buffer| buffer.content.clone())
302 .ok_or_else(|| DevelopmentError::NotFound(format!("buffer {path}")))?;
303 if let Some(selection) = selection.as_ref()
304 && (text_position_offset(&content, selection.anchor).is_none()
305 || text_position_offset(&content, selection.active).is_none())
306 {
307 return Err(DevelopmentError::InvalidInput(
308 "editor selection positions must be one-based and within the buffer".into(),
309 ));
310 }
311 let buffer = self
312 .buffers
313 .get_mut(path)
314 .ok_or_else(|| DevelopmentError::NotFound(format!("buffer {path}")))?;
315 buffer.selection = selection;
316 buffer.actor = actor;
317 Ok(buffer.clone())
318 }
319
320 pub fn selected_editor_text(&self, path: &str) -> DevelopmentResult<Option<String>> {
322 let buffer = self
323 .buffers
324 .get(path)
325 .ok_or_else(|| DevelopmentError::NotFound(format!("buffer {path}")))?;
326 let Some(selection) = buffer.selection.as_ref() else {
327 return Ok(None);
328 };
329 let Some((start, end)) = selection_offsets(&buffer.content, selection) else {
330 return Err(DevelopmentError::InvalidInput(
331 "editor selection positions must be one-based and within the buffer".into(),
332 ));
333 };
334 if start == end {
335 return Ok(None);
336 }
337 Ok(Some(buffer.content[start..end].to_string()))
338 }
339
340 pub fn replace_buffer_selection(
342 &mut self,
343 path: &str,
344 replacement: String,
345 actor: Actor,
346 ) -> DevelopmentResult<EditorBuffer> {
347 let buffer = self
348 .buffers
349 .get(path)
350 .cloned()
351 .ok_or_else(|| DevelopmentError::NotFound(format!("buffer {path}")))?;
352 let selection = buffer.selection.as_ref().ok_or_else(|| {
353 DevelopmentError::InvalidInput(format!("editor buffer {path} has no selection"))
354 })?;
355 let Some((start, end)) = selection_offsets(&buffer.content, selection) else {
356 return Err(DevelopmentError::InvalidInput(
357 "editor selection positions must be one-based and within the buffer".into(),
358 ));
359 };
360 if start == end {
361 return Err(DevelopmentError::InvalidInput(format!(
362 "editor buffer {path} has an empty selection"
363 )));
364 }
365 let mut content = buffer.content;
366 content.replace_range(start..end, &replacement);
367 let cursor =
368 text_position_at_offset(&content, start + replacement.len()).ok_or_else(|| {
369 DevelopmentError::InvalidInput(
370 "replacement ended at an invalid UTF-8 boundary".into(),
371 )
372 })?;
373 self.edit_buffer(path, content, actor.clone())?;
374 self.set_buffer_cursor(path, cursor.line, cursor.column)?;
375 self.set_buffer_selection(path, None, actor)?;
376 self.buffer(path)
377 .cloned()
378 .ok_or_else(|| DevelopmentError::NotFound(format!("buffer {path}")))
379 }
380
381 pub fn editor_comments(&self, path: Option<&str>) -> Vec<super::EditorComment> {
382 self.comments
383 .values()
384 .flat_map(|comments| comments.iter())
385 .filter(|comment| path.is_none_or(|path| path == comment.path))
386 .cloned()
387 .collect()
388 }
389
390 pub fn add_editor_comment(
391 &mut self,
392 path: &str,
393 start_line: u32,
394 end_line: u32,
395 text: String,
396 actor: Actor,
397 ) -> DevelopmentResult<super::EditorComment> {
398 self.validate_editor_range(path, start_line, end_line)?;
399 if text.trim().is_empty() || text.len() > 16 * 1024 {
400 return Err(DevelopmentError::InvalidInput(
401 "editor comment must contain 1-16384 bytes".into(),
402 ));
403 }
404 let revision = self.bump_editor_revision();
405 let comment = super::EditorComment {
406 id: self.next_editor_id("comment"),
407 path: path.into(),
408 start_line,
409 end_line,
410 text,
411 actor: actor.clone(),
412 state: super::EditorCommentState::Open,
413 created_revision: revision,
414 updated_revision: revision,
415 };
416 self.record_as(
417 actor,
418 DevelopmentEventKind::EditorCommentAdded,
419 serde_json::to_value(&comment)?,
420 )?;
421 self.comments
422 .entry(path.into())
423 .or_default()
424 .push(comment.clone());
425 Ok(comment)
426 }
427
428 pub fn resolve_editor_comment(
429 &mut self,
430 id: &str,
431 actor: Actor,
432 ) -> DevelopmentResult<super::EditorComment> {
433 let (path, index) = self.find_comment(id)?;
434 let current = self
435 .comments
436 .get(&path)
437 .and_then(|comments| comments.get(index))
438 .cloned()
439 .ok_or_else(|| DevelopmentError::NotFound(format!("comment {id}")))?;
440 if current.state == super::EditorCommentState::Resolved {
441 return Ok(current);
442 }
443 let revision = self.bump_editor_revision();
444 let comment = self
445 .comments
446 .get_mut(&path)
447 .and_then(|comments| comments.get_mut(index))
448 .ok_or_else(|| DevelopmentError::NotFound(format!("comment {id}")))?;
449 comment.state = super::EditorCommentState::Resolved;
450 comment.updated_revision = revision;
451 let result = comment.clone();
452 self.record_as(
453 actor,
454 DevelopmentEventKind::EditorCommentResolved,
455 serde_json::to_value(&result)?,
456 )?;
457 Ok(result)
458 }
459
460 pub fn editor_proposals(&self) -> Vec<super::EditorProposal> {
461 self.proposals.values().cloned().collect()
462 }
463
464 pub fn propose_editor_change(
465 &mut self,
466 path: &str,
467 original: String,
468 proposed: String,
469 summary: String,
470 actor: Actor,
471 ) -> DevelopmentResult<super::EditorProposal> {
472 self.validate_editor_path(path)?;
473 if original.len() > MAX_BUFFER_BYTES || proposed.len() > MAX_BUFFER_BYTES {
474 return Err(DevelopmentError::InvalidInput(format!(
475 "editor proposal exceeds the {} byte buffer limit",
476 MAX_BUFFER_BYTES
477 )));
478 }
479 if summary.trim().is_empty() || summary.len() > 1024 {
480 return Err(DevelopmentError::InvalidInput(
481 "editor proposal summary must contain 1-1024 bytes".into(),
482 ));
483 }
484 let current = self.current_editor_content(path)?;
485 if current != original {
486 return Err(DevelopmentError::Conflict(format!(
487 "editor buffer {path} changed before the proposal was created"
488 )));
489 }
490 let revision = self.bump_editor_revision();
491 let proposal = super::EditorProposal {
492 id: self.next_editor_id("proposal"),
493 path: path.into(),
494 summary,
495 actor: actor.clone(),
496 base_hash: hash(&original),
497 base_revision: revision,
498 original,
499 proposed,
500 state: super::EditorProposalState::Pending,
501 created_revision: revision,
502 updated_revision: revision,
503 };
504 self.record_as(
505 actor,
506 DevelopmentEventKind::EditorProposalCreated,
507 serde_json::to_value(&proposal)?,
508 )?;
509 self.proposals.insert(proposal.id.clone(), proposal.clone());
510 Ok(proposal)
511 }
512
513 pub fn accept_editor_proposal(
514 &mut self,
515 id: &str,
516 actor: Actor,
517 ) -> DevelopmentResult<EditorBuffer> {
518 let proposal = self
519 .proposals
520 .get(id)
521 .cloned()
522 .ok_or_else(|| DevelopmentError::NotFound(format!("proposal {id}")))?;
523 if proposal.state != super::EditorProposalState::Pending {
524 return Err(DevelopmentError::Conflict(format!(
525 "proposal {id} is already {:?}",
526 proposal.state
527 )));
528 }
529 if self.current_editor_content(&proposal.path)? != proposal.original
530 || hash(&proposal.original) != proposal.base_hash
531 {
532 let revision = self.bump_editor_revision();
533 if let Some(stale) = self.proposals.get_mut(id) {
534 stale.state = super::EditorProposalState::Stale;
535 stale.updated_revision = revision;
536 }
537 self.record_as(
538 actor,
539 DevelopmentEventKind::EditorProposalRejected,
540 serde_json::json!({"id": id, "reason": "stale: base content changed"}),
541 )?;
542 return Err(DevelopmentError::Conflict(format!(
543 "proposal {id} is stale because {} changed",
544 proposal.path
545 )));
546 }
547 let buffer = self
548 .edit_buffer(&proposal.path, proposal.proposed.clone(), actor.clone())
549 .map(|_| self.buffer(&proposal.path).cloned())?
550 .ok_or_else(|| DevelopmentError::NotFound(format!("buffer {}", proposal.path)))?;
551 let revision = self.bump_editor_revision();
552 if let Some(accepted) = self.proposals.get_mut(id) {
553 accepted.state = super::EditorProposalState::Accepted;
554 accepted.updated_revision = revision;
555 }
556 self.record_as(
557 actor,
558 DevelopmentEventKind::EditorProposalAccepted,
559 serde_json::json!({"id": id, "path": proposal.path}),
560 )?;
561 Ok(buffer)
562 }
563
564 pub fn reject_editor_proposal(
565 &mut self,
566 id: &str,
567 actor: Actor,
568 ) -> DevelopmentResult<super::EditorProposal> {
569 let current = self
570 .proposals
571 .get(id)
572 .cloned()
573 .ok_or_else(|| DevelopmentError::NotFound(format!("proposal {id}")))?;
574 if current.state != super::EditorProposalState::Pending {
575 return Err(DevelopmentError::Conflict(format!(
576 "proposal {id} is already {:?}",
577 current.state
578 )));
579 }
580 let revision = self.bump_editor_revision();
581 let proposal = self
582 .proposals
583 .get_mut(id)
584 .ok_or_else(|| DevelopmentError::NotFound(format!("proposal {id}")))?;
585 proposal.state = super::EditorProposalState::Rejected;
586 proposal.updated_revision = revision;
587 let result = proposal.clone();
588 self.record_as(
589 actor,
590 DevelopmentEventKind::EditorProposalRejected,
591 serde_json::to_value(&result)?,
592 )?;
593 Ok(result)
594 }
595
596 pub fn editor_checkpoints(&self) -> Vec<super::EditorCheckpoint> {
597 self.checkpoints.values().cloned().collect()
598 }
599
600 pub fn create_editor_checkpoint(
601 &mut self,
602 name: String,
603 actor: Actor,
604 ) -> DevelopmentResult<super::EditorCheckpoint> {
605 if name.trim().is_empty() || name.len() > 256 {
606 return Err(DevelopmentError::InvalidInput(
607 "checkpoint name must contain 1-256 bytes".into(),
608 ));
609 }
610 let revision = self.bump_editor_revision();
611 let checkpoint = super::EditorCheckpoint {
612 id: self.next_editor_id("checkpoint"),
613 name,
614 actor: actor.clone(),
615 revision,
616 buffers: self.buffers.values().cloned().collect(),
617 };
618 self.checkpoints
619 .insert(checkpoint.id.clone(), checkpoint.clone());
620 self.persist_checkpoints()?;
621 self.record_as(
622 actor,
623 DevelopmentEventKind::EditorCheckpointCreated,
624 serde_json::to_value(&checkpoint)?,
625 )?;
626 Ok(checkpoint)
627 }
628
629 pub fn restore_editor_checkpoint(
630 &mut self,
631 id: &str,
632 actor: Actor,
633 ) -> DevelopmentResult<Vec<EditorBuffer>> {
634 let checkpoint = self
635 .checkpoints
636 .get(id)
637 .cloned()
638 .ok_or_else(|| DevelopmentError::NotFound(format!("checkpoint {id}")))?;
639 for restored in &checkpoint.buffers {
640 if let Some(current) = self.buffers.get(&restored.path) {
641 self.undo
642 .entry(restored.path.clone())
643 .or_default()
644 .push(current.content.clone());
645 }
646 self.buffers.insert(restored.path.clone(), restored.clone());
647 }
648 let revision = self.bump_editor_revision();
649 self.record_as(
650 actor,
651 DevelopmentEventKind::EditorCheckpointRestored,
652 serde_json::json!({"id": id, "revision": revision}),
653 )?;
654 self.invalidate_tree_cache();
655 Ok(checkpoint.buffers)
656 }
657
658 fn validate_editor_path(&self, path: &str) -> DevelopmentResult<()> {
659 if self.buffers.contains_key(path) {
660 return Ok(());
661 }
662 self.resolve_path(path, false).map(|_| ())
663 }
664
665 fn validate_editor_range(
666 &self,
667 path: &str,
668 start_line: u32,
669 end_line: u32,
670 ) -> DevelopmentResult<()> {
671 self.validate_editor_path(path)?;
672 if start_line == 0 || end_line < start_line {
673 return Err(DevelopmentError::InvalidInput(
674 "editor comment range must be one-based and ordered".into(),
675 ));
676 }
677 let content = self
678 .buffers
679 .get(path)
680 .map(|buffer| buffer.content.clone())
681 .map(Ok)
682 .unwrap_or_else(|| self.read_file_snapshot(path))?;
683 let line_count = content.split('\n').count().max(1) as u32;
684 if end_line > line_count {
685 return Err(DevelopmentError::InvalidInput(format!(
686 "editor comment range ends at line {end_line}, but {path} has {line_count} lines"
687 )));
688 }
689 Ok(())
690 }
691
692 fn current_editor_content(&self, path: &str) -> DevelopmentResult<String> {
693 if let Some(buffer) = self.buffers.get(path) {
694 return Ok(buffer.content.clone());
695 }
696 self.read_file_snapshot(path)
697 }
698
699 fn find_comment(&self, id: &str) -> DevelopmentResult<(String, usize)> {
700 self.comments
701 .iter()
702 .find_map(|(path, comments)| {
703 comments
704 .iter()
705 .position(|comment| comment.id == id)
706 .map(|index| (path.clone(), index))
707 })
708 .ok_or_else(|| DevelopmentError::NotFound(format!("comment {id}")))
709 }
710
711 fn bump_editor_revision(&mut self) -> u64 {
712 self.revision = self.revision.saturating_add(1);
713 self.revision
714 }
715
716 fn next_editor_id(&mut self, kind: &str) -> String {
717 let id = format!("{kind}-{}-{}", self.revision, self.next_editor_id);
718 self.next_editor_id = self.next_editor_id.saturating_add(1);
719 id
720 }
721
722 fn persist_checkpoints(&self) -> DevelopmentResult<()> {
723 let data = serde_json::to_vec_pretty(&self.checkpoints)?;
724 fs::write(&self.checkpoints_path, data)?;
725 Ok(())
726 }
727
728 pub fn attach_actor(&mut self, actor: Actor) -> DevelopmentResult<()> {
729 if self.actors.len() >= 64 && !self.actors.contains_key(&actor.id) {
730 return Err(DevelopmentError::InvalidInput(
731 "workspace cannot contain more than 64 actors".into(),
732 ));
733 }
734 self.record_as(
735 actor.clone(),
736 DevelopmentEventKind::ActorJoined,
737 serde_json::json!({"actorId": actor.id.clone()}),
738 )?;
739 self.actors.insert(actor.id.clone(), actor);
740 Ok(())
741 }
742
743 pub fn processes(&mut self) -> &mut ProcessManager {
744 &mut self.processes
745 }
746
747 pub fn list_files(&self) -> DevelopmentResult<Vec<FileEntry>> {
748 Ok(self.list_files_result()?.entries)
749 }
750
751 pub fn list_files_result(&self) -> DevelopmentResult<ProjectTreeResult> {
753 {
754 let cache = self.tree_cache.lock().map_err(|_| {
755 DevelopmentError::Conflict("project tree cache is unavailable".into())
756 })?;
757 if let Some((created, result)) = cache.as_ref()
758 && created.elapsed() <= Duration::from_millis(250)
759 {
760 return Ok(result.clone());
761 }
762 }
763 let mut result = ProjectTreeResult {
764 entries: Vec::new(),
765 truncated: false,
766 limit: MAX_FILE_ENTRIES,
767 ignored_directories: Vec::new(),
768 skipped_symlinks: 0,
769 };
770 visit_files(&self.root, &self.root, &mut result)?;
771 let git = git_statuses(&self.root);
772 for entry in &mut result.entries {
773 entry.git_status = git.get(&entry.path).cloned();
774 if let Some(buffer) = self.buffers.get(&entry.path) {
775 entry.dirty = buffer.dirty;
776 entry.actor = Some(buffer.actor.clone());
777 }
778 }
779 result
780 .entries
781 .sort_by(|left, right| left.path.cmp(&right.path));
782 result.ignored_directories.sort();
783 result.ignored_directories.dedup();
784 *self.tree_cache.lock().map_err(|_| {
785 DevelopmentError::Conflict("project tree cache is unavailable".into())
786 })? = Some((Instant::now(), result.clone()));
787 Ok(result)
788 }
789
790 pub fn read_file(&mut self, path: &str) -> DevelopmentResult<String> {
791 let (_, relative) = self.resolve_path(path, false)?;
792 let content = self.read_file_snapshot(path)?;
793 self.record(
794 DevelopmentEventKind::FileOpened,
795 serde_json::json!({"path": relative}),
796 )?;
797 Ok(content)
798 }
799
800 pub(crate) fn read_file_snapshot(&self, path: &str) -> DevelopmentResult<String> {
803 let (absolute, _) = self.resolve_path(path, false)?;
804 read_bounded_utf8(&absolute, MAX_FILE_BYTES, "project file")
805 }
806
807 pub fn open_buffer(&mut self, path: &str, actor: Actor) -> DevelopmentResult<EditorBuffer> {
808 let content = self.read_file(path)?;
809 let (_, relative) = self.resolve_path(path, false)?;
810 let buffer = EditorBuffer {
811 path: relative.clone(),
812 original_hash: hash(&content),
813 content,
814 dirty: false,
815 cursor_line: 1,
816 cursor_column: 1,
817 selection: None,
818 actor,
819 };
820 self.buffers.insert(relative, buffer.clone());
821 Ok(buffer)
822 }
823
824 pub fn buffers(&self) -> impl Iterator<Item = &EditorBuffer> {
825 self.buffers.values()
826 }
827
828 pub fn buffer(&self, path: &str) -> Option<&EditorBuffer> {
829 self.buffers.get(path)
830 }
831
832 pub fn edit_buffer(
833 &mut self,
834 path: &str,
835 content: String,
836 actor: Actor,
837 ) -> DevelopmentResult<()> {
838 if content.len() > MAX_BUFFER_BYTES {
839 return Err(DevelopmentError::InvalidInput(format!(
840 "buffer exceeds the {} byte limit",
841 MAX_BUFFER_BYTES
842 )));
843 }
844 if !self.buffers.contains_key(path) {
845 if self.resolve_path(path, false).is_ok() {
846 self.open_buffer(path, actor.clone())?;
847 } else {
848 let (_, relative) = self.resolve_path(path, true)?;
849 self.buffers.insert(
850 relative.clone(),
851 EditorBuffer {
852 path: relative,
853 content: String::new(),
854 original_hash: hash(""),
855 dirty: false,
856 cursor_line: 1,
857 cursor_column: 1,
858 selection: None,
859 actor: actor.clone(),
860 },
861 );
862 }
863 }
864 let buffer = self
865 .buffers
866 .get_mut(path)
867 .ok_or_else(|| DevelopmentError::NotFound(format!("buffer {path}")))?;
868 let history = self.undo.entry(path.to_string()).or_default();
869 if history.len() == 256 {
870 history.remove(0);
871 }
872 history.push(buffer.content.clone());
873 self.redo.remove(path);
874 buffer.content = content;
875 buffer.dirty = hash(&buffer.content) != buffer.original_hash;
876 buffer.actor = actor;
877 self.revision = self.revision.saturating_add(1);
878 self.invalidate_tree_cache();
879 Ok(())
880 }
881
882 pub fn save_buffer(&mut self, path: &str) -> DevelopmentResult<EditorBuffer> {
883 let buffer = self
884 .buffers
885 .get(path)
886 .cloned()
887 .ok_or_else(|| DevelopmentError::NotFound(format!("buffer {path}")))?;
888 let disk_hash = match read_existing(&self.root, path) {
889 Ok(content) => hash(&content),
890 Err(DevelopmentError::Io(error)) if error.kind() == std::io::ErrorKind::NotFound => {
891 hash("")
892 }
893 Err(error) => return Err(error),
894 };
895 if disk_hash != buffer.original_hash {
896 return Err(DevelopmentError::Conflict(format!(
897 "{path} changed on disk after the buffer was opened"
898 )));
899 }
900 self.write_file(path, &buffer.content, buffer.actor.clone())?;
901 let mut saved = buffer;
902 saved.original_hash = hash(&saved.content);
903 saved.dirty = false;
904 self.buffers.insert(path.into(), saved.clone());
905 Ok(saved)
906 }
907
908 pub fn undo_buffer(&mut self, path: &str) -> DevelopmentResult<EditorBuffer> {
909 let previous = self
910 .undo
911 .get_mut(path)
912 .and_then(Vec::pop)
913 .ok_or_else(|| DevelopmentError::NotFound(format!("undo history for {path}")))?;
914 let buffer = self
915 .buffers
916 .get_mut(path)
917 .ok_or_else(|| DevelopmentError::NotFound(format!("buffer {path}")))?;
918 self.redo
919 .entry(path.to_string())
920 .or_default()
921 .push(std::mem::replace(&mut buffer.content, previous));
922 buffer.dirty = hash(&buffer.content) != buffer.original_hash;
923 self.revision = self.revision.saturating_add(1);
924 let result = buffer.clone();
925 self.invalidate_tree_cache();
926 Ok(result)
927 }
928
929 pub fn redo_buffer(&mut self, path: &str) -> DevelopmentResult<EditorBuffer> {
930 let next = self
931 .redo
932 .get_mut(path)
933 .and_then(Vec::pop)
934 .ok_or_else(|| DevelopmentError::NotFound(format!("redo history for {path}")))?;
935 let buffer = self
936 .buffers
937 .get_mut(path)
938 .ok_or_else(|| DevelopmentError::NotFound(format!("buffer {path}")))?;
939 self.undo
940 .entry(path.to_string())
941 .or_default()
942 .push(std::mem::replace(&mut buffer.content, next));
943 buffer.dirty = hash(&buffer.content) != buffer.original_hash;
944 self.revision = self.revision.saturating_add(1);
945 let result = buffer.clone();
946 self.invalidate_tree_cache();
947 Ok(result)
948 }
949
950 pub fn replace_in_buffer(
951 &mut self,
952 path: &str,
953 needle: &str,
954 replacement: &str,
955 actor: Actor,
956 ) -> DevelopmentResult<usize> {
957 if needle.is_empty() {
958 return Err(DevelopmentError::InvalidInput(
959 "search text must not be empty".into(),
960 ));
961 }
962 if !self.buffers.contains_key(path) {
963 self.open_buffer(path, actor.clone())?;
964 }
965 let current = self
966 .buffers
967 .get(path)
968 .ok_or_else(|| DevelopmentError::NotFound(format!("buffer {path}")))?
969 .content
970 .clone();
971 let matches = current.matches(needle).count();
972 if matches > 0 {
973 self.edit_buffer(path, current.replace(needle, replacement), actor)?;
974 }
975 Ok(matches)
976 }
977
978 pub fn set_buffer_cursor(
979 &mut self,
980 path: &str,
981 line: u32,
982 column: u32,
983 ) -> DevelopmentResult<()> {
984 if line == 0 || column == 0 {
985 return Err(DevelopmentError::InvalidInput(
986 "editor cursor positions are one-based".into(),
987 ));
988 }
989 let buffer = self
990 .buffers
991 .get_mut(path)
992 .ok_or_else(|| DevelopmentError::NotFound(format!("buffer {path}")))?;
993 buffer.cursor_line = line;
994 buffer.cursor_column = column;
995 Ok(())
996 }
997
998 pub fn rename_path(&mut self, from: &str, to: &str, actor: Actor) -> DevelopmentResult<()> {
999 self.invalidate_tree_cache();
1000 let (source, source_relative) = self.resolve_path(from, false)?;
1001 let (destination, destination_relative) = self.resolve_path(to, true)?;
1002 if destination.exists() {
1003 return Err(DevelopmentError::Conflict(format!(
1004 "destination already exists: {to}"
1005 )));
1006 }
1007 if let Some(parent) = destination.parent() {
1008 fs::create_dir_all(parent)?;
1009 }
1010 fs::rename(source, destination)?;
1011 if let Some(mut buffer) = self.buffers.remove(&source_relative) {
1012 buffer.path = destination_relative.clone();
1013 self.buffers.insert(destination_relative.clone(), buffer);
1014 }
1015 if let Some(history) = self.undo.remove(&source_relative) {
1016 self.undo.insert(destination_relative.clone(), history);
1017 }
1018 if let Some(history) = self.redo.remove(&source_relative) {
1019 self.redo.insert(destination_relative.clone(), history);
1020 }
1021 self.revision = self.revision.saturating_add(1);
1022 self.record_as(
1023 actor,
1024 DevelopmentEventKind::FileSaved,
1025 serde_json::json!({"operation": "rename", "from": source_relative, "to": destination_relative}),
1026 )
1027 }
1028
1029 pub fn create_directory(&mut self, path: &str, actor: Actor) -> DevelopmentResult<()> {
1030 self.invalidate_tree_cache();
1031 let (absolute, relative) = self.resolve_path(path, true)?;
1032 if absolute.exists() {
1033 return Err(DevelopmentError::Conflict(format!(
1034 "path already exists: {path}"
1035 )));
1036 }
1037 fs::create_dir_all(&absolute)?;
1038 self.revision = self.revision.saturating_add(1);
1039 self.record_as(
1040 actor,
1041 DevelopmentEventKind::FileSaved,
1042 serde_json::json!({"operation": "mkdir", "path": relative}),
1043 )
1044 }
1045
1046 pub fn delete_path(&mut self, path: &str, actor: Actor) -> DevelopmentResult<()> {
1047 self.invalidate_tree_cache();
1048 let (absolute, relative) = self.resolve_path(path, false)?;
1049 let metadata = fs::symlink_metadata(&absolute)?;
1050 if metadata.is_dir() {
1051 if fs::read_dir(&absolute)?.next().is_some() {
1052 return Err(DevelopmentError::Conflict(format!(
1053 "refusing to delete non-empty directory: {path}"
1054 )));
1055 }
1056 fs::remove_dir(&absolute)?;
1057 } else {
1058 fs::remove_file(&absolute)?;
1059 }
1060 self.buffers.remove(&relative);
1061 self.undo.remove(&relative);
1062 self.redo.remove(&relative);
1063 self.revision = self.revision.saturating_add(1);
1064 self.record_as(
1065 actor,
1066 DevelopmentEventKind::FileSaved,
1067 serde_json::json!({"operation": "delete", "path": relative}),
1068 )
1069 }
1070
1071 pub fn write_file(&mut self, path: &str, content: &str, actor: Actor) -> DevelopmentResult<()> {
1072 self.invalidate_tree_cache();
1073 if content.len() > MAX_FILE_BYTES {
1074 return Err(DevelopmentError::InvalidInput(format!(
1075 "file exceeds the {} byte write limit",
1076 MAX_FILE_BYTES
1077 )));
1078 }
1079 let (absolute, relative) = self.resolve_path(path, true)?;
1080 let before_hash = fs::read_to_string(&absolute)
1081 .ok()
1082 .map(|existing| hash(&existing));
1083 let parent = absolute
1084 .parent()
1085 .ok_or_else(|| DevelopmentError::InvalidInput("file has no parent".into()))?;
1086 fs::create_dir_all(parent)?;
1087 let temporary = absolute.with_extension(format!(
1088 "glass-tmp-{}-{}",
1089 std::process::id(),
1090 self.revision.saturating_add(1)
1091 ));
1092 {
1093 let mut file = OpenOptions::new()
1094 .create_new(true)
1095 .write(true)
1096 .open(&temporary)?;
1097 file.write_all(content.as_bytes())?;
1098 file.sync_all()?;
1099 }
1100 if let Err(error) = fs::rename(&temporary, &absolute) {
1101 let _ = fs::remove_file(&temporary);
1102 return Err(error.into());
1103 }
1104 self.revision = self.revision.saturating_add(1);
1105 self.record_as(
1106 actor,
1107 DevelopmentEventKind::FileSaved,
1108 serde_json::json!({
1109 "path": relative,
1110 "bytes": content.len(),
1111 "beforeHash": before_hash,
1112 "afterHash": hash(content)
1113 }),
1114 )?;
1115 if self.processes.list_checked()?.iter().any(|process| {
1116 matches!(process.state, super::ProcessState::Running)
1117 && (process.name.contains("dev") || process.name.contains("server"))
1118 }) {
1119 self.record(
1120 DevelopmentEventKind::HmrObserved,
1121 serde_json::json!({
1122 "path": relative,
1123 "status": "pending-runtime-observation",
1124 "browserUrl": self.detection.browser_url
1125 }),
1126 )?;
1127 }
1128 Ok(())
1129 }
1130
1131 pub fn start_process(
1132 &mut self,
1133 name: &str,
1134 command: &str,
1135 ) -> DevelopmentResult<super::ProcessSnapshot> {
1136 let snapshot = self.processes.start(name, command)?;
1137 self.revision = self.revision.saturating_add(1);
1138 self.record(
1139 DevelopmentEventKind::ProcessStarted,
1140 serde_json::json!({
1141 "name": name,
1142 "commandBytes": command.len(),
1143 "commandSha256": hash(command),
1144 "pid": snapshot.pid
1145 }),
1146 )?;
1147 Ok(snapshot)
1148 }
1149
1150 pub fn stop_process(&mut self, name: &str) -> DevelopmentResult<super::ProcessSnapshot> {
1151 let snapshot = self.processes.stop(name)?;
1152 self.revision = self.revision.saturating_add(1);
1153 self.record(
1154 DevelopmentEventKind::ProcessExited,
1155 serde_json::json!({"name": name, "state": snapshot.state}),
1156 )?;
1157 Ok(snapshot)
1158 }
1159
1160 pub fn run_verification(
1161 &mut self,
1162 name: &str,
1163 command: &str,
1164 timeout: Duration,
1165 ) -> DevelopmentResult<super::ProcessSnapshot> {
1166 self.record(
1167 DevelopmentEventKind::TestStarted,
1168 serde_json::json!({
1169 "name": name,
1170 "commandBytes": command.len(),
1171 "commandSha256": hash(command)
1172 }),
1173 )?;
1174 #[cfg(windows)]
1175 {
1176 let snapshot = self.processes.run_bounded(name, command, timeout)?;
1177 self.record(
1178 DevelopmentEventKind::TestCompleted,
1179 serde_json::json!({
1180 "name": name,
1181 "state": snapshot.state,
1182 "outputBytes": snapshot.output.len(),
1183 "outputSha256": hash(&snapshot.output)
1184 }),
1185 )?;
1186 return Ok(snapshot);
1187 }
1188 #[cfg(not(windows))]
1189 self.start_process(name, command)?;
1190 #[cfg(not(windows))]
1191 self.processes.close_input(name)?;
1192 #[cfg(not(windows))]
1193 let deadline = Instant::now() + timeout;
1194 #[cfg(not(windows))]
1195 let snapshot = loop {
1196 let snapshot = self
1197 .processes
1198 .poll()?
1199 .into_iter()
1200 .find(|snapshot| snapshot.name == name)
1201 .ok_or_else(|| DevelopmentError::NotFound(format!("process {name}")))?;
1202 if !matches!(snapshot.state, super::ProcessState::Running) {
1203 break snapshot;
1204 }
1205 if Instant::now() >= deadline {
1206 self.stop_process(name)?;
1207 self.record(
1208 DevelopmentEventKind::TestCompleted,
1209 serde_json::json!({"name": name, "status": "timeout"}),
1210 )?;
1211 return Err(DevelopmentError::Process(format!(
1212 "verification {name} exceeded {} seconds",
1213 timeout.as_secs()
1214 )));
1215 }
1216 std::thread::sleep(Duration::from_millis(25));
1217 };
1218 #[cfg(not(windows))]
1219 self.record(
1220 DevelopmentEventKind::TestCompleted,
1221 serde_json::json!({
1222 "name": name,
1223 "state": snapshot.state,
1224 "outputBytes": snapshot.output.len(),
1225 "outputSha256": hash(&snapshot.output)
1226 }),
1227 )?;
1228 #[cfg(not(windows))]
1229 Ok(snapshot)
1230 }
1231
1232 pub fn run_command_to_completion(
1233 &mut self,
1234 name: &str,
1235 command: &str,
1236 timeout: Duration,
1237 ) -> DevelopmentResult<super::ProcessSnapshot> {
1238 #[cfg(windows)]
1239 return self.processes.run_bounded(name, command, timeout);
1240
1241 #[cfg(not(windows))]
1242 self.start_process(name, command)?;
1243 #[cfg(not(windows))]
1244 self.processes.close_input(name)?;
1245 #[cfg(not(windows))]
1246 let deadline = Instant::now() + timeout;
1247 #[cfg(not(windows))]
1248 loop {
1249 let snapshot = self
1250 .processes
1251 .poll()?
1252 .into_iter()
1253 .find(|snapshot| snapshot.name == name)
1254 .ok_or_else(|| DevelopmentError::NotFound(format!("process {name}")))?;
1255 if !matches!(snapshot.state, super::ProcessState::Running) {
1256 self.record(
1257 DevelopmentEventKind::ProcessExited,
1258 serde_json::json!({
1259 "name": name,
1260 "state": snapshot.state,
1261 "outputBytes": snapshot.output.len(),
1262 "outputSha256": hash(&snapshot.output)
1263 }),
1264 )?;
1265 return Ok(snapshot);
1266 }
1267 if Instant::now() >= deadline {
1268 self.stop_process(name)?;
1269 return Err(DevelopmentError::Process(format!(
1270 "command {name} exceeded {} seconds",
1271 timeout.as_secs()
1272 )));
1273 }
1274 std::thread::sleep(Duration::from_millis(25));
1275 }
1276 }
1277
1278 pub fn confirm_live_update(
1283 &mut self,
1284 source_path: &str,
1285 before_revision: u64,
1286 after_revision: u64,
1287 semantic_changes: usize,
1288 actor: Actor,
1289 ) -> DevelopmentResult<()> {
1290 self.resolve_path(source_path, false)?;
1291 if after_revision <= before_revision {
1292 return Err(DevelopmentError::InvalidInput(
1293 "live update proof requires a newer browser revision".into(),
1294 ));
1295 }
1296 self.record_as(
1297 actor,
1298 DevelopmentEventKind::HmrObserved,
1299 serde_json::json!({
1300 "sourcePath": source_path,
1301 "status": "confirmed-runtime-observation",
1302 "beforeBrowserRevision": before_revision,
1303 "afterBrowserRevision": after_revision,
1304 "semanticChanges": semantic_changes,
1305 }),
1306 )
1307 }
1308
1309 #[allow(clippy::too_many_arguments)]
1310 pub fn link_runtime_source(
1311 &mut self,
1312 entity_id: &str,
1313 path: &str,
1314 start_line: u32,
1315 end_line: u32,
1316 provenance: LinkProvenance,
1317 detail: &str,
1318 confidence: f32,
1319 actor: Actor,
1320 ) -> DevelopmentResult<RuntimeLink> {
1321 let (_, relative) = self.resolve_path(path, false)?;
1322 let link = RuntimeLink {
1323 entity_id: entity_id.into(),
1324 source: SourceLocation::new(relative, start_line, end_line)?,
1325 evidence: LinkEvidence {
1326 provenance,
1327 detail: detail.into(),
1328 confidence,
1329 },
1330 };
1331 self.graph.link(link.clone())?;
1332 self.graph.save(&self.graph_path)?;
1333 self.revision = self.revision.saturating_add(1);
1334 self.record_as(
1335 actor,
1336 DevelopmentEventKind::SourceRuntimeLinked,
1337 serde_json::to_value(&link)?,
1338 )?;
1339 Ok(link)
1340 }
1341
1342 pub fn diff(&mut self) -> DevelopmentResult<ProjectDiff> {
1343 build_diff(&self.root, &self.timeline, &self.graph, &mut self.processes)
1344 }
1345
1346 pub fn discover_runtime_links(&mut self) -> DevelopmentResult<Vec<RuntimeLink>> {
1347 let discovered = self.graph.discover_explicit_markers(&self.root)?;
1348 self.graph.save(&self.graph_path)?;
1349 for link in &discovered {
1350 self.record(
1351 DevelopmentEventKind::SourceRuntimeLinked,
1352 serde_json::to_value(link)?,
1353 )?;
1354 }
1355 if !discovered.is_empty() {
1356 self.revision = self.revision.saturating_add(1);
1357 }
1358 Ok(discovered)
1359 }
1360
1361 pub fn publish_rust_diagnostics(
1362 &mut self,
1363 path: &str,
1364 ) -> DevelopmentResult<Vec<LanguageDiagnostic>> {
1365 if self.language.is_none() {
1366 self.language = Some(LspClient::rust_analyzer(&self.root)?);
1367 }
1368 let diagnostics = self
1369 .language
1370 .as_mut()
1371 .expect("language client initialized")
1372 .diagnostics(path)?;
1373 self.diagnostics.insert(path.into(), diagnostics.clone());
1374 self.record(
1375 DevelopmentEventKind::DiagnosticsPublished,
1376 serde_json::json!({"path": path, "count": diagnostics.len(), "diagnostics": diagnostics}),
1377 )?;
1378 Ok(diagnostics)
1379 }
1380
1381 pub fn evaluate_semantic_breakpoints(
1382 &mut self,
1383 breakpoints: &[SemanticBreakpoint],
1384 before: &SemanticSnapshot,
1385 after: &SemanticSnapshot,
1386 ) -> DevelopmentResult<Vec<SemanticBreakpointHit>> {
1387 let hits = super::evaluate_breakpoints(breakpoints, before, after, &self.graph);
1388 for hit in &hits {
1389 self.record(
1390 DevelopmentEventKind::SemanticBreakpointHit,
1391 serde_json::to_value(hit)?,
1392 )?;
1393 }
1394 Ok(hits)
1395 }
1396
1397 pub fn replay(&self, start: usize, limit: usize) -> DevelopmentResult<ReplayWindow> {
1398 super::replay(&self.timeline, start, limit)
1399 }
1400
1401 pub fn search(&mut self, query: &str, limit: usize) -> DevelopmentResult<Vec<SearchHit>> {
1402 if query.trim().is_empty() || query.len() > 256 || limit == 0 || limit > 256 {
1403 return Err(DevelopmentError::InvalidInput(
1404 "search requires a 1-256 byte query and a 1-256 result limit".into(),
1405 ));
1406 }
1407 let mut hits = Vec::new();
1408 for file in self.list_files()? {
1409 if let Some(score) = super::fuzzy_score(query, &file.path) {
1410 hits.push(SearchHit {
1411 kind: SearchKind::File,
1412 label: file.path,
1413 detail: file.git_status.unwrap_or_else(|| "project file".into()),
1414 score,
1415 });
1416 }
1417 }
1418 for entity in self.graph.links.keys() {
1419 if let Some(score) = super::fuzzy_score(query, entity) {
1420 hits.push(SearchHit {
1421 kind: SearchKind::BrowserEntity,
1422 label: entity.clone(),
1423 detail: "runtime/source graph entity".into(),
1424 score,
1425 });
1426 }
1427 }
1428 for process in self.processes.list_checked()? {
1429 if let Some(score) = super::fuzzy_score(query, &process.name) {
1430 hits.push(SearchHit {
1431 kind: SearchKind::Process,
1432 label: process.name,
1433 detail: format!("{:?}", process.state),
1434 score,
1435 });
1436 }
1437 }
1438 for event in self.timeline.events() {
1439 let label = format!("{:?}", event.kind);
1440 if let Some(score) = super::fuzzy_score(query, &label) {
1441 hits.push(SearchHit {
1442 kind: SearchKind::Event,
1443 label,
1444 detail: event.id.clone(),
1445 score,
1446 });
1447 }
1448 }
1449 for command in [
1450 "project files",
1451 "project open",
1452 "project diagnostics",
1453 "project run",
1454 "project diff",
1455 "project timeline",
1456 "project replay",
1457 "project graph",
1458 "project experiment",
1459 "project neovim",
1460 "agent prompt",
1461 ] {
1462 if let Some(score) = super::fuzzy_score(query, command) {
1463 hits.push(SearchHit {
1464 kind: SearchKind::Command,
1465 label: command.into(),
1466 detail: "command palette".into(),
1467 score,
1468 });
1469 }
1470 }
1471 Ok(super::rank(hits, limit))
1472 }
1473
1474 pub fn record(
1475 &mut self,
1476 kind: DevelopmentEventKind,
1477 payload: serde_json::Value,
1478 ) -> DevelopmentResult<()> {
1479 self.record_as(self.actor.clone(), kind, payload)
1480 }
1481
1482 pub fn record_as(
1483 &mut self,
1484 actor: Actor,
1485 kind: DevelopmentEventKind,
1486 payload: serde_json::Value,
1487 ) -> DevelopmentResult<()> {
1488 self.timeline
1489 .record(actor, kind, self.root.display().to_string(), payload)?;
1490 Ok(())
1491 }
1492
1493 fn resolve_path(
1494 &self,
1495 input: &str,
1496 allow_missing: bool,
1497 ) -> DevelopmentResult<(PathBuf, String)> {
1498 if input.is_empty() || input.len() > 512 {
1499 return Err(DevelopmentError::InvalidInput(
1500 "relative path must be 1-512 bytes".into(),
1501 ));
1502 }
1503 let path = Path::new(input);
1504 if path.is_absolute()
1505 || path
1506 .components()
1507 .any(|component| matches!(component, Component::ParentDir))
1508 {
1509 return Err(DevelopmentError::PathOutsideWorkspace(path.to_path_buf()));
1510 }
1511 let candidate = self.root.join(path);
1512 let mut existing_parent = candidate
1513 .parent()
1514 .ok_or_else(|| DevelopmentError::InvalidInput("path has no parent".into()))?;
1515 while !existing_parent.exists() {
1516 existing_parent = existing_parent
1517 .parent()
1518 .ok_or_else(|| DevelopmentError::PathOutsideWorkspace(candidate.clone()))?;
1519 }
1520 let canonical_parent = fs::canonicalize(existing_parent)?;
1521 if !canonical_parent.starts_with(&self.root) {
1522 return Err(DevelopmentError::PathOutsideWorkspace(candidate));
1523 }
1524 if candidate.exists() {
1525 let canonical = fs::canonicalize(&candidate)?;
1526 if !canonical.starts_with(&self.root) {
1527 return Err(DevelopmentError::PathOutsideWorkspace(candidate));
1528 }
1529 } else if !allow_missing {
1530 return Err(DevelopmentError::NotFound(input.into()));
1531 }
1532 Ok((candidate, portable_relative_path(path)))
1533 }
1534}
1535
1536fn portable_relative_path(path: &Path) -> String {
1537 path.components()
1538 .map(|component| component.as_os_str().to_string_lossy())
1539 .collect::<Vec<_>>()
1540 .join("/")
1541}
1542
1543fn load_editor_checkpoints(
1544 path: &Path,
1545) -> DevelopmentResult<BTreeMap<String, super::EditorCheckpoint>> {
1546 if !path.is_file() {
1547 return Ok(BTreeMap::new());
1548 }
1549 let data = fs::read(path)?;
1550 serde_json::from_slice(&data)
1551 .map_err(|error| DevelopmentError::Config(format!("invalid editor checkpoints: {error}")))
1552}
1553
1554fn comments_from_timeline(timeline: &Timeline) -> BTreeMap<String, Vec<super::EditorComment>> {
1555 let mut comments: BTreeMap<String, Vec<super::EditorComment>> = BTreeMap::new();
1556 for event in timeline.events() {
1557 match event.kind {
1558 DevelopmentEventKind::EditorCommentAdded => {
1559 if let Ok(comment) =
1560 serde_json::from_value::<super::EditorComment>(event.payload.clone())
1561 {
1562 comments
1563 .entry(comment.path.clone())
1564 .or_default()
1565 .push(comment);
1566 }
1567 }
1568 DevelopmentEventKind::EditorCommentResolved => {
1569 let Some(id) = event.payload.get("id").and_then(serde_json::Value::as_str) else {
1570 continue;
1571 };
1572 for comment in comments.values_mut().flat_map(|items| items.iter_mut()) {
1573 if comment.id == id {
1574 comment.state = super::EditorCommentState::Resolved;
1575 if let Some(revision) = event
1576 .payload
1577 .get("updatedRevision")
1578 .and_then(serde_json::Value::as_u64)
1579 {
1580 comment.updated_revision = revision;
1581 }
1582 }
1583 }
1584 }
1585 _ => {}
1586 }
1587 }
1588 comments
1589}
1590
1591fn proposals_from_timeline(timeline: &Timeline) -> BTreeMap<String, super::EditorProposal> {
1592 let mut proposals = BTreeMap::new();
1593 for event in timeline.events() {
1594 match event.kind {
1595 DevelopmentEventKind::EditorProposalCreated => {
1596 if let Ok(proposal) =
1597 serde_json::from_value::<super::EditorProposal>(event.payload.clone())
1598 {
1599 proposals.insert(proposal.id.clone(), proposal);
1600 }
1601 }
1602 DevelopmentEventKind::EditorProposalAccepted
1603 | DevelopmentEventKind::EditorProposalRejected => {
1604 let Some(id) = event.payload.get("id").and_then(serde_json::Value::as_str) else {
1605 continue;
1606 };
1607 if let Some(proposal) = proposals.get_mut(id) {
1608 proposal.state =
1609 if matches!(event.kind, DevelopmentEventKind::EditorProposalAccepted) {
1610 super::EditorProposalState::Accepted
1611 } else if event
1612 .payload
1613 .get("reason")
1614 .and_then(serde_json::Value::as_str)
1615 .is_some_and(|reason| reason.contains("stale"))
1616 {
1617 super::EditorProposalState::Stale
1618 } else {
1619 super::EditorProposalState::Rejected
1620 };
1621 }
1622 }
1623 _ => {}
1624 }
1625 }
1626 proposals
1627}
1628
1629pub fn detect_project(root: impl AsRef<Path>) -> DevelopmentResult<ProjectDetection> {
1630 let root = canonical_root(root.as_ref())?;
1631 let config_path = [root.join("glass.toml"), root.join(".glass.toml")]
1632 .into_iter()
1633 .find(|path| path.is_file());
1634 let mut languages = Vec::new();
1635 if root.join("Cargo.toml").is_file() {
1636 languages.push("Rust".into());
1637 }
1638 if root.join("package.json").is_file() {
1639 languages.push("JavaScript/TypeScript".into());
1640 }
1641 if root.join("pyproject.toml").is_file() || root.join("requirements.txt").is_file() {
1642 languages.push("Python".into());
1643 }
1644 if root.join("go.mod").is_file() {
1645 languages.push("Go".into());
1646 }
1647 let package_manager = if root.join("pnpm-lock.yaml").is_file() {
1648 Some("pnpm".into())
1649 } else if root.join("yarn.lock").is_file() {
1650 Some("yarn".into())
1651 } else if root.join("bun.lockb").is_file() || root.join("bun.lock").is_file() {
1652 Some("bun".into())
1653 } else if root.join("package-lock.json").is_file() {
1654 Some("npm".into())
1655 } else if root.join("Cargo.lock").is_file() {
1656 Some("cargo".into())
1657 } else {
1658 None
1659 };
1660 let framework = detect_framework(&root);
1661 let config = load_project_config(config_path.as_deref())?;
1662 let defaults = default_commands(&root, package_manager.as_deref());
1663 let build_system = if root.join("Cargo.toml").is_file() {
1664 Some("cargo".into())
1665 } else if root.join("package.json").is_file() {
1666 Some(package_manager.clone().unwrap_or_else(|| "npm".into()))
1667 } else if root.join("pyproject.toml").is_file() {
1668 Some("pyproject".into())
1669 } else if root.join("go.mod").is_file() {
1670 Some("go".into())
1671 } else {
1672 None
1673 };
1674 let formatter = if root.join("Cargo.toml").is_file() {
1675 Some("rustfmt".into())
1676 } else if root.join("package.json").is_file() {
1677 Some("prettier".into())
1678 } else if root.join("pyproject.toml").is_file() {
1679 Some("ruff format".into())
1680 } else if root.join("go.mod").is_file() {
1681 Some("gofmt".into())
1682 } else {
1683 None
1684 };
1685 let lsp_servers = [
1686 ("Rust", "rust-analyzer"),
1687 ("JavaScript/TypeScript", "typescript-language-server"),
1688 ("Python", "pyright-langserver"),
1689 ("Go", "gopls"),
1690 ]
1691 .into_iter()
1692 .filter(|(language, server)| {
1693 languages.iter().any(|value| value == language) && command_available(server)
1694 })
1695 .map(|(_, server)| server.to_string())
1696 .collect();
1697 let browser_url = config.browser.url;
1698 let local_development_urls = browser_url.iter().cloned().collect();
1699 Ok(ProjectDetection {
1700 root: root.clone(),
1701 languages,
1702 package_manager,
1703 framework,
1704 build_system,
1705 formatter,
1706 lsp_servers,
1707 git_branch: git_branch(&root),
1708 dev_command: config.commands.dev.or(defaults.0),
1709 test_command: config.commands.test.or(defaults.1),
1710 lint_command: config.commands.lint.or(defaults.2),
1711 build_command: config.commands.build.or(defaults.3),
1712 browser_url,
1713 local_development_urls,
1714 editor_engine: config.editor.engine,
1715 agent_harness: config.agent.harness,
1716 config_path,
1717 })
1718}
1719
1720fn load_project_config(path: Option<&Path>) -> DevelopmentResult<GlassProjectConfig> {
1721 path.map(fs::read_to_string)
1722 .transpose()?
1723 .map(|text| {
1724 toml::from_str::<GlassProjectConfig>(&text)
1725 .map_err(|error| DevelopmentError::Config(error.to_string()))
1726 })
1727 .transpose()
1728 .map(Option::unwrap_or_default)
1729}
1730
1731pub(crate) fn canonical_root(root: &Path) -> DevelopmentResult<PathBuf> {
1732 let root = if root.is_file() {
1733 root.parent().unwrap_or(root)
1734 } else {
1735 root
1736 };
1737 let root = fs::canonicalize(root)?;
1738 if !root.is_dir() {
1739 return Err(DevelopmentError::InvalidInput(
1740 "project root must be a directory".into(),
1741 ));
1742 }
1743 Ok(root)
1744}
1745
1746fn visit_files(
1747 root: &Path,
1748 current: &Path,
1749 result: &mut ProjectTreeResult,
1750) -> DevelopmentResult<()> {
1751 if result.entries.len() >= MAX_FILE_ENTRIES {
1752 result.truncated = true;
1753 return Ok(());
1754 }
1755 let mut children =
1756 fs::read_dir(current).map(|entries| entries.collect::<Result<Vec<_>, _>>())??;
1757 children.sort_by_key(|entry| entry.file_name());
1758 for entry in children {
1759 if result.entries.len() >= MAX_FILE_ENTRIES {
1760 result.truncated = true;
1761 break;
1762 }
1763 let path = entry.path();
1764 let name = entry.file_name().to_string_lossy().into_owned();
1765 if name == ".git" || name == "target" || name == "node_modules" || name == ".glass" {
1766 result.ignored_directories.push(name);
1767 continue;
1768 }
1769 let metadata = fs::symlink_metadata(&path)?;
1770 if metadata.file_type().is_symlink() {
1771 result.skipped_symlinks = result.skipped_symlinks.saturating_add(1);
1772 continue;
1773 }
1774 let relative = path
1775 .strip_prefix(root)
1776 .map_err(|_| DevelopmentError::PathOutsideWorkspace(path.clone()))?;
1777 let relative = portable_relative_path(relative);
1778 if metadata.is_dir() {
1779 result.entries.push(FileEntry {
1780 path: relative,
1781 kind: FileKind::Directory,
1782 bytes: None,
1783 git_status: None,
1784 dirty: false,
1785 actor: None,
1786 });
1787 visit_files(root, &path, result)?;
1788 } else if metadata.is_file() {
1789 result.entries.push(FileEntry {
1790 path: relative,
1791 kind: FileKind::File,
1792 bytes: Some(metadata.len()),
1793 git_status: None,
1794 dirty: false,
1795 actor: None,
1796 });
1797 }
1798 }
1799 Ok(())
1800}
1801
1802fn read_existing(root: &Path, path: &str) -> DevelopmentResult<String> {
1803 let absolute = root.join(path);
1804 read_bounded_utf8(&absolute, MAX_BUFFER_BYTES, "existing editor file")
1805}
1806
1807fn hash(content: &str) -> String {
1808 Sha256::digest(content.as_bytes())
1809 .iter()
1810 .map(|byte| format!("{byte:02x}"))
1811 .collect()
1812}
1813
1814fn git_branch(root: &Path) -> Option<String> {
1815 Command::new("git")
1816 .args(["rev-parse", "--abbrev-ref", "HEAD"])
1817 .current_dir(root)
1818 .output()
1819 .ok()
1820 .filter(|output| output.status.success())
1821 .and_then(|output| String::from_utf8(output.stdout).ok())
1822 .map(|branch| branch.trim().to_string())
1823 .filter(|branch| !branch.is_empty())
1824}
1825
1826fn git_statuses(root: &Path) -> BTreeMap<String, String> {
1827 let Some(output) = Command::new("git")
1828 .args(["status", "--porcelain=v1", "-z", "--untracked-files=all"])
1829 .current_dir(root)
1830 .output()
1831 .ok()
1832 .filter(|output| output.status.success())
1833 else {
1834 return BTreeMap::new();
1835 };
1836 let mut statuses = BTreeMap::new();
1837 for entry in output
1838 .stdout
1839 .split(|byte| *byte == 0)
1840 .filter(|entry| entry.len() >= 4)
1841 {
1842 let status = String::from_utf8_lossy(&entry[..2]).trim().to_string();
1843 let path = String::from_utf8_lossy(&entry[3..]).into_owned();
1844 if !path.is_empty() {
1845 statuses.insert(path, status);
1846 }
1847 }
1848 statuses
1849}
1850
1851fn detect_framework(root: &Path) -> Option<String> {
1852 if let Ok(package) = fs::read_to_string(root.join("package.json"))
1853 && let Ok(value) = serde_json::from_str::<serde_json::Value>(&package)
1854 {
1855 let dependencies = value
1856 .get("dependencies")
1857 .and_then(serde_json::Value::as_object);
1858 let dev_dependencies = value
1859 .get("devDependencies")
1860 .and_then(serde_json::Value::as_object);
1861 if let Some(framework) =
1862 ["next", "vite", "react", "vue", "svelte"]
1863 .into_iter()
1864 .find(|framework| {
1865 dependencies.is_some_and(|values| values.contains_key(*framework))
1866 || dev_dependencies.is_some_and(|values| values.contains_key(*framework))
1867 })
1868 {
1869 return Some(framework.into());
1870 }
1871 }
1872 let python = fs::read_to_string(root.join("pyproject.toml"))
1873 .or_else(|_| fs::read_to_string(root.join("requirements.txt")))
1874 .unwrap_or_default()
1875 .to_ascii_lowercase();
1876 ["django", "flask", "fastapi"]
1877 .into_iter()
1878 .find(|framework| python.contains(framework))
1879 .map(str::to_string)
1880}
1881
1882fn default_commands(
1883 root: &Path,
1884 package_manager: Option<&str>,
1885) -> (
1886 Option<String>,
1887 Option<String>,
1888 Option<String>,
1889 Option<String>,
1890) {
1891 if root.join("Cargo.toml").is_file() {
1892 return (
1893 None,
1894 Some("cargo test".into()),
1895 Some("cargo clippy --all-targets --all-features -- -D warnings".into()),
1896 Some("cargo build".into()),
1897 );
1898 }
1899 if root.join("package.json").is_file() {
1900 let manager = package_manager.unwrap_or("npm");
1901 let package = fs::read_to_string(root.join("package.json"))
1902 .ok()
1903 .and_then(|value| serde_json::from_str::<serde_json::Value>(&value).ok());
1904 let command = |script: &str| {
1905 package
1906 .as_ref()
1907 .and_then(|value| value.pointer(&format!("/scripts/{script}")))
1908 .and_then(serde_json::Value::as_str)
1909 .map(|_| format!("{manager} run {script}"))
1910 };
1911 return (
1912 command("dev"),
1913 command("test"),
1914 command("lint"),
1915 command("build"),
1916 );
1917 }
1918 if root.join("pyproject.toml").is_file() {
1919 return (
1920 None,
1921 Some("python -m pytest".into()),
1922 Some("ruff check .".into()),
1923 None,
1924 );
1925 }
1926 if root.join("go.mod").is_file() {
1927 return (
1928 None,
1929 Some("go test ./...".into()),
1930 Some("go vet ./...".into()),
1931 Some("go build ./...".into()),
1932 );
1933 }
1934 (None, None, None, None)
1935}
1936
1937fn command_available(command: &str) -> bool {
1938 Command::new(command)
1939 .arg("--version")
1940 .stdout(std::process::Stdio::null())
1941 .stderr(std::process::Stdio::null())
1942 .status()
1943 .is_ok_and(|status| status.success())
1944}
1945
1946#[cfg(test)]
1947mod tests {
1948 use super::*;
1949 use std::sync::atomic::{AtomicUsize, Ordering};
1950
1951 fn fixture() -> PathBuf {
1952 static NEXT_FIXTURE: AtomicUsize = AtomicUsize::new(0);
1953 let root = std::env::temp_dir().join(format!(
1954 "glass-project-{}-{}",
1955 std::process::id(),
1956 NEXT_FIXTURE.fetch_add(1, Ordering::Relaxed)
1957 ));
1958 let _ = fs::remove_dir_all(&root);
1959 fs::create_dir_all(root.join("src")).unwrap();
1960 fs::write(
1961 root.join("Cargo.toml"),
1962 "[package]\nname='fixture'\nversion='0.1.0'\nedition='2024'\n",
1963 )
1964 .unwrap();
1965 fs::write(root.join("src/main.rs"), "fn main() {}\n").unwrap();
1966 root
1967 }
1968
1969 #[test]
1970 fn detects_cargo_project_and_defaults() {
1971 let root = fixture();
1972 let detection = detect_project(&root).unwrap();
1973 assert_eq!(detection.languages, vec!["Rust"]);
1974 assert_eq!(detection.test_command.as_deref(), Some("cargo test"));
1975 let _ = fs::remove_dir_all(root);
1976 }
1977
1978 #[test]
1979 fn event_feed_reads_do_not_record_monitoring_activity() {
1980 let root = fixture();
1981 drop(ProjectWorkspace::open(&root).unwrap());
1982 let before = ProjectWorkspace::timeline_snapshot(&root).unwrap();
1983 let page = ProjectWorkspace::event_page(&root, None, 64).unwrap();
1984 let after = ProjectWorkspace::timeline_snapshot(&root).unwrap();
1985 assert_eq!(page.events, before);
1986 assert_eq!(after, before);
1987 let _ = fs::remove_dir_all(root);
1988 }
1989
1990 #[test]
1991 fn file_writes_are_confined_and_atomic() {
1992 let root = fixture();
1993 let mut project = ProjectWorkspace::open(&root).unwrap();
1994 project
1995 .write_file("src/lib.rs", "pub fn ok() {}\n", Actor::local())
1996 .unwrap();
1997 assert!(
1998 project
1999 .read_file("src/lib.rs")
2000 .unwrap()
2001 .contains("pub fn ok")
2002 );
2003 assert!(matches!(
2004 project.write_file("../escape", "bad", Actor::local()),
2005 Err(DevelopmentError::PathOutsideWorkspace(_))
2006 ));
2007 let _ = fs::remove_dir_all(root);
2008 }
2009
2010 #[test]
2011 fn editor_save_records_actor_and_clears_dirty_state() {
2012 let root = fixture();
2013 let mut project = ProjectWorkspace::open(&root).unwrap();
2014 project.open_buffer("src/main.rs", Actor::local()).unwrap();
2015 project
2016 .edit_buffer(
2017 "src/main.rs",
2018 "fn main() { println!(\"ok\"); }\n".into(),
2019 Actor::local(),
2020 )
2021 .unwrap();
2022 assert!(project.buffer("src/main.rs").unwrap().dirty);
2023 project.save_buffer("src/main.rs").unwrap();
2024 assert!(!project.buffer("src/main.rs").unwrap().dirty);
2025 assert!(
2026 project
2027 .timeline()
2028 .events()
2029 .any(|event| matches!(event.kind, DevelopmentEventKind::FileSaved))
2030 );
2031 let _ = fs::remove_dir_all(root);
2032 }
2033
2034 #[test]
2035 fn editor_undo_redo_and_external_change_conflicts_are_explicit() {
2036 let root = fixture();
2037 let mut project = ProjectWorkspace::open(&root).unwrap();
2038 project.open_buffer("src/main.rs", Actor::local()).unwrap();
2039 project
2040 .edit_buffer("src/main.rs", "one".into(), Actor::local())
2041 .unwrap();
2042 project
2043 .edit_buffer("src/main.rs", "two".into(), Actor::local())
2044 .unwrap();
2045 assert_eq!(project.undo_buffer("src/main.rs").unwrap().content, "one");
2046 assert_eq!(project.redo_buffer("src/main.rs").unwrap().content, "two");
2047 fs::write(root.join("src/main.rs"), "external").unwrap();
2048 assert!(matches!(
2049 project.save_buffer("src/main.rs"),
2050 Err(DevelopmentError::Conflict(_))
2051 ));
2052 let _ = fs::remove_dir_all(root);
2053 }
2054
2055 #[test]
2056 fn editor_selection_replacement_is_atomic_and_unicode_safe() {
2057 let root = fixture();
2058 let mut project = ProjectWorkspace::open(&root).unwrap();
2059 project.open_buffer("src/main.rs", Actor::local()).unwrap();
2060 project
2061 .edit_buffer("src/main.rs", "αlpha\nβeta\n".into(), Actor::local())
2062 .unwrap();
2063 project
2064 .set_buffer_selection(
2065 "src/main.rs",
2066 Some(crate::development::TextSelection {
2067 anchor: crate::development::TextPosition { line: 1, column: 2 },
2068 active: crate::development::TextPosition { line: 2, column: 3 },
2069 }),
2070 Actor::local(),
2071 )
2072 .unwrap();
2073 assert_eq!(
2074 project
2075 .selected_editor_text("src/main.rs")
2076 .unwrap()
2077 .as_deref(),
2078 Some("lpha\nβe")
2079 );
2080 let buffer = project
2081 .replace_buffer_selection("src/main.rs", "X\nY".into(), Actor::local())
2082 .unwrap();
2083 assert_eq!(buffer.content, "αX\nYta\n");
2084 assert_eq!(buffer.cursor_line, 2);
2085 assert_eq!(buffer.cursor_column, 2);
2086 assert!(buffer.selection.is_none());
2087 assert!(matches!(
2088 project.set_buffer_selection(
2089 "src/main.rs",
2090 Some(crate::development::TextSelection {
2091 anchor: crate::development::TextPosition { line: 9, column: 1 },
2092 active: crate::development::TextPosition { line: 9, column: 1 },
2093 }),
2094 Actor::local(),
2095 ),
2096 Err(DevelopmentError::InvalidInput(_))
2097 ));
2098 let _ = fs::remove_dir_all(root);
2099 }
2100
2101 #[test]
2102 fn file_operations_support_nested_create_rename_and_safe_delete() {
2103 let root = fixture();
2104 let mut project = ProjectWorkspace::open(&root).unwrap();
2105 project
2106 .edit_buffer("nested/new.txt", "hello".into(), Actor::local())
2107 .unwrap();
2108 project.save_buffer("nested/new.txt").unwrap();
2109 project
2110 .rename_path("nested/new.txt", "nested/renamed.txt", Actor::local())
2111 .unwrap();
2112 assert!(root.join("nested/renamed.txt").is_file());
2113 project
2114 .delete_path("nested/renamed.txt", Actor::local())
2115 .unwrap();
2116 project.delete_path("nested", Actor::local()).unwrap();
2117 assert!(!root.join("nested").exists());
2118 let _ = fs::remove_dir_all(root);
2119 }
2120
2121 #[test]
2122 fn project_tree_reports_ignore_and_symlink_semantics() {
2123 let root = fixture();
2124 fs::create_dir_all(root.join("target/debug")).unwrap();
2125 fs::write(root.join("target/debug/ignored"), "ignored").unwrap();
2126 #[cfg(unix)]
2127 std::os::unix::fs::symlink(root.join("src/main.rs"), root.join("linked.rs")).unwrap();
2128 let project = ProjectWorkspace::open(&root).unwrap();
2129 let tree = project.list_files_result().unwrap();
2130 assert_eq!(tree.limit, MAX_FILE_ENTRIES);
2131 assert!(tree.ignored_directories.contains(&"target".to_string()));
2132 assert!(
2133 !tree
2134 .entries
2135 .iter()
2136 .any(|entry| entry.path.contains("ignored"))
2137 );
2138 #[cfg(unix)]
2139 assert_eq!(tree.skipped_symlinks, 1);
2140 let _ = fs::remove_dir_all(root);
2141 }
2142
2143 #[test]
2144 fn editor_comments_replay_and_proposals_require_approval() {
2145 let root = fixture();
2146 let mut project = ProjectWorkspace::open(&root).unwrap();
2147 project.open_buffer("src/main.rs", Actor::local()).unwrap();
2148 let comment = project
2149 .add_editor_comment(
2150 "src/main.rs",
2151 1,
2152 1,
2153 "Prefer an explicit return here".into(),
2154 Actor::local(),
2155 )
2156 .unwrap();
2157 assert_eq!(project.editor_comments(None).len(), 1);
2158 assert_eq!(project.editor_proposals().len(), 0);
2159 let proposal = project
2160 .propose_editor_change(
2161 "src/main.rs",
2162 "fn main() {}\n".into(),
2163 "fn main() { println!(\"ok\"); }\n".into(),
2164 "Add observable output".into(),
2165 Actor::local(),
2166 )
2167 .unwrap();
2168 assert_eq!(
2169 project.buffer("src/main.rs").unwrap().content,
2170 "fn main() {}\n"
2171 );
2172 project
2173 .accept_editor_proposal(&proposal.id, Actor::local())
2174 .unwrap();
2175 assert_eq!(
2176 project.buffer("src/main.rs").unwrap().content,
2177 "fn main() { println!(\"ok\"); }\n"
2178 );
2179 let resolved = project
2180 .resolve_editor_comment(&comment.id, Actor::local())
2181 .unwrap();
2182 let revision = project.revision();
2183 assert_eq!(
2184 project
2185 .resolve_editor_comment(&comment.id, Actor::local())
2186 .unwrap(),
2187 resolved
2188 );
2189 assert_eq!(project.revision(), revision);
2190 drop(project);
2191
2192 let reopened = ProjectWorkspace::open(&root).unwrap();
2193 let comments = reopened.editor_comments(Some("src/main.rs"));
2194 assert_eq!(comments.len(), 1);
2195 assert_eq!(
2196 comments[0].state,
2197 crate::development::EditorCommentState::Resolved
2198 );
2199 let _ = fs::remove_dir_all(root);
2200 }
2201
2202 #[test]
2203 fn editor_proposals_become_stale_on_buffer_conflict() {
2204 let root = fixture();
2205 let mut project = ProjectWorkspace::open(&root).unwrap();
2206 project.open_buffer("src/main.rs", Actor::local()).unwrap();
2207 let proposal = project
2208 .propose_editor_change(
2209 "src/main.rs",
2210 "fn main() {}\n".into(),
2211 "fn main() { println!(\"proposal\"); }\n".into(),
2212 "Add output".into(),
2213 Actor::local(),
2214 )
2215 .unwrap();
2216 project
2217 .edit_buffer(
2218 "src/main.rs",
2219 "fn main() { println!(\"human\"); }\n".into(),
2220 Actor::local(),
2221 )
2222 .unwrap();
2223 assert!(matches!(
2224 project.accept_editor_proposal(&proposal.id, Actor::local()),
2225 Err(DevelopmentError::Conflict(_))
2226 ));
2227 assert_eq!(
2228 project.editor_proposals()[0].state,
2229 crate::development::EditorProposalState::Stale
2230 );
2231 let _ = fs::remove_dir_all(root);
2232 }
2233
2234 #[test]
2235 fn editor_checkpoints_restore_unsaved_buffers_and_survive_reopen() {
2236 let root = fixture();
2237 let mut project = ProjectWorkspace::open(&root).unwrap();
2238 project
2239 .edit_buffer("src/main.rs", "one\n".into(), Actor::local())
2240 .unwrap();
2241 let checkpoint = project
2242 .create_editor_checkpoint("before experiment".into(), Actor::local())
2243 .unwrap();
2244 project
2245 .edit_buffer("src/main.rs", "two\n".into(), Actor::local())
2246 .unwrap();
2247 project
2248 .restore_editor_checkpoint(&checkpoint.id, Actor::local())
2249 .unwrap();
2250 assert_eq!(project.buffer("src/main.rs").unwrap().content, "one\n");
2251 drop(project);
2252
2253 let reopened = ProjectWorkspace::open(&root).unwrap();
2254 assert_eq!(reopened.editor_checkpoints().len(), 1);
2255 let _ = fs::remove_dir_all(root);
2256 }
2257}