Skip to main content

glass_dev/development/
project.rs

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/// Explicit result envelope for a bounded project-tree traversal.
117#[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    /// Read the persisted event feed without opening a workspace or recording
180    /// a synthetic `workspaceOpened` event. This keeps monitoring read-only.
181    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    /// Return the selected text from a shared buffer, if the selection is non-empty.
321    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    /// Replace the human's current selection and leave the cursor after the replacement.
341    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        let current = self.current_editor_content(&proposal.path)?;
530        let already_applied = current == proposal.proposed;
531        if hash(&proposal.original) != proposal.base_hash
532            || (!already_applied && current != proposal.original)
533        {
534            let revision = self.bump_editor_revision();
535            if let Some(stale) = self.proposals.get_mut(id) {
536                stale.state = super::EditorProposalState::Stale;
537                stale.updated_revision = revision;
538            }
539            self.record_as(
540                actor,
541                DevelopmentEventKind::EditorProposalRejected,
542                serde_json::json!({"id": id, "reason": "stale: base content changed"}),
543            )?;
544            return Err(DevelopmentError::Conflict(format!(
545                "proposal {id} is stale because {} changed",
546                proposal.path
547            )));
548        }
549        let buffer = if already_applied {
550            self.buffer(&proposal.path)
551                .cloned()
552                .ok_or_else(|| DevelopmentError::NotFound(format!("buffer {}", proposal.path)))?
553        } else {
554            self.edit_buffer(&proposal.path, proposal.proposed.clone(), actor.clone())
555                .map(|_| self.buffer(&proposal.path).cloned())?
556                .ok_or_else(|| DevelopmentError::NotFound(format!("buffer {}", proposal.path)))?
557        };
558        let revision = self.bump_editor_revision();
559        if let Some(accepted) = self.proposals.get_mut(id) {
560            accepted.state = super::EditorProposalState::Accepted;
561            accepted.updated_revision = revision;
562        }
563        self.record_as(
564            actor,
565            DevelopmentEventKind::EditorProposalAccepted,
566            serde_json::json!({"id": id, "path": proposal.path}),
567        )?;
568        Ok(buffer)
569    }
570
571    pub fn accept_pending_editor_proposals(
572        &mut self,
573        actor: Actor,
574    ) -> DevelopmentResult<Vec<super::EditorBuffer>> {
575        let ids = self
576            .proposals
577            .values()
578            .filter(|proposal| proposal.state == super::EditorProposalState::Pending)
579            .map(|proposal| proposal.id.clone())
580            .collect::<Vec<_>>();
581        if ids.is_empty() {
582            return Err(DevelopmentError::NotFound(
583                "no pending editor proposals".into(),
584            ));
585        }
586        let mut buffers = Vec::new();
587        for id in ids {
588            buffers.push(self.accept_editor_proposal(&id, actor.clone())?);
589        }
590        Ok(buffers)
591    }
592
593    pub fn reject_editor_proposal(
594        &mut self,
595        id: &str,
596        actor: Actor,
597    ) -> DevelopmentResult<super::EditorProposal> {
598        let current = self
599            .proposals
600            .get(id)
601            .cloned()
602            .ok_or_else(|| DevelopmentError::NotFound(format!("proposal {id}")))?;
603        if current.state != super::EditorProposalState::Pending {
604            return Err(DevelopmentError::Conflict(format!(
605                "proposal {id} is already {:?}",
606                current.state
607            )));
608        }
609        let revision = self.bump_editor_revision();
610        {
611            let proposal = self
612                .proposals
613                .get_mut(id)
614                .ok_or_else(|| DevelopmentError::NotFound(format!("proposal {id}")))?;
615            proposal.state = super::EditorProposalState::Rejected;
616            proposal.updated_revision = revision;
617        }
618        let result = self
619            .proposals
620            .get(id)
621            .cloned()
622            .ok_or_else(|| DevelopmentError::NotFound(format!("proposal {id}")))?;
623        if let Ok(current) = self.current_editor_content(&result.path)
624            && current != result.original
625        {
626            let _ = self.edit_buffer(&result.path, result.original.clone(), actor.clone());
627        }
628        self.record_as(
629            actor,
630            DevelopmentEventKind::EditorProposalRejected,
631            serde_json::to_value(&result)?,
632        )?;
633        Ok(result)
634    }
635
636    pub fn editor_checkpoints(&self) -> Vec<super::EditorCheckpoint> {
637        self.checkpoints.values().cloned().collect()
638    }
639
640    pub fn create_editor_checkpoint(
641        &mut self,
642        name: String,
643        actor: Actor,
644    ) -> DevelopmentResult<super::EditorCheckpoint> {
645        if name.trim().is_empty() || name.len() > 256 {
646            return Err(DevelopmentError::InvalidInput(
647                "checkpoint name must contain 1-256 bytes".into(),
648            ));
649        }
650        let revision = self.bump_editor_revision();
651        let checkpoint = super::EditorCheckpoint {
652            id: self.next_editor_id("checkpoint"),
653            name,
654            actor: actor.clone(),
655            revision,
656            buffers: self.buffers.values().cloned().collect(),
657        };
658        self.checkpoints
659            .insert(checkpoint.id.clone(), checkpoint.clone());
660        self.persist_checkpoints()?;
661        self.record_as(
662            actor,
663            DevelopmentEventKind::EditorCheckpointCreated,
664            serde_json::to_value(&checkpoint)?,
665        )?;
666        Ok(checkpoint)
667    }
668
669    pub fn restore_editor_checkpoint(
670        &mut self,
671        id: &str,
672        actor: Actor,
673    ) -> DevelopmentResult<Vec<EditorBuffer>> {
674        let checkpoint = self
675            .checkpoints
676            .get(id)
677            .cloned()
678            .ok_or_else(|| DevelopmentError::NotFound(format!("checkpoint {id}")))?;
679        for restored in &checkpoint.buffers {
680            if let Some(current) = self.buffers.get(&restored.path) {
681                self.undo
682                    .entry(restored.path.clone())
683                    .or_default()
684                    .push(current.content.clone());
685            }
686            self.buffers.insert(restored.path.clone(), restored.clone());
687        }
688        let revision = self.bump_editor_revision();
689        self.record_as(
690            actor,
691            DevelopmentEventKind::EditorCheckpointRestored,
692            serde_json::json!({"id": id, "revision": revision}),
693        )?;
694        self.invalidate_tree_cache();
695        Ok(checkpoint.buffers)
696    }
697
698    fn validate_editor_path(&self, path: &str) -> DevelopmentResult<()> {
699        if self.buffers.contains_key(path) {
700            return Ok(());
701        }
702        self.resolve_path(path, false).map(|_| ())
703    }
704
705    fn validate_editor_range(
706        &self,
707        path: &str,
708        start_line: u32,
709        end_line: u32,
710    ) -> DevelopmentResult<()> {
711        self.validate_editor_path(path)?;
712        if start_line == 0 || end_line < start_line {
713            return Err(DevelopmentError::InvalidInput(
714                "editor comment range must be one-based and ordered".into(),
715            ));
716        }
717        let content = self
718            .buffers
719            .get(path)
720            .map(|buffer| buffer.content.clone())
721            .map(Ok)
722            .unwrap_or_else(|| self.read_file_snapshot(path))?;
723        let line_count = content.split('\n').count().max(1) as u32;
724        if end_line > line_count {
725            return Err(DevelopmentError::InvalidInput(format!(
726                "editor comment range ends at line {end_line}, but {path} has {line_count} lines"
727            )));
728        }
729        Ok(())
730    }
731
732    fn current_editor_content(&self, path: &str) -> DevelopmentResult<String> {
733        self.buffer_or_file_content(path)
734    }
735
736    pub(crate) fn buffer_or_file_content(&self, path: &str) -> DevelopmentResult<String> {
737        if let Some(buffer) = self.buffers.get(path) {
738            return Ok(buffer.content.clone());
739        }
740        match self.read_file_snapshot(path) {
741            Ok(content) => Ok(content),
742            Err(DevelopmentError::Io(error)) if error.kind() == std::io::ErrorKind::NotFound => {
743                Ok(String::new())
744            }
745            Err(error) => Err(error),
746        }
747    }
748
749    fn find_comment(&self, id: &str) -> DevelopmentResult<(String, usize)> {
750        self.comments
751            .iter()
752            .find_map(|(path, comments)| {
753                comments
754                    .iter()
755                    .position(|comment| comment.id == id)
756                    .map(|index| (path.clone(), index))
757            })
758            .ok_or_else(|| DevelopmentError::NotFound(format!("comment {id}")))
759    }
760
761    fn bump_editor_revision(&mut self) -> u64 {
762        self.revision = self.revision.saturating_add(1);
763        self.revision
764    }
765
766    fn next_editor_id(&mut self, kind: &str) -> String {
767        let id = format!("{kind}-{}-{}", self.revision, self.next_editor_id);
768        self.next_editor_id = self.next_editor_id.saturating_add(1);
769        id
770    }
771
772    fn persist_checkpoints(&self) -> DevelopmentResult<()> {
773        let data = serde_json::to_vec_pretty(&self.checkpoints)?;
774        fs::write(&self.checkpoints_path, data)?;
775        Ok(())
776    }
777
778    pub fn attach_actor(&mut self, actor: Actor) -> DevelopmentResult<()> {
779        if self.actors.len() >= 64 && !self.actors.contains_key(&actor.id) {
780            return Err(DevelopmentError::InvalidInput(
781                "workspace cannot contain more than 64 actors".into(),
782            ));
783        }
784        self.record_as(
785            actor.clone(),
786            DevelopmentEventKind::ActorJoined,
787            serde_json::json!({"actorId": actor.id.clone()}),
788        )?;
789        self.actors.insert(actor.id.clone(), actor);
790        Ok(())
791    }
792
793    pub fn processes(&mut self) -> &mut ProcessManager {
794        &mut self.processes
795    }
796
797    pub fn list_files(&self) -> DevelopmentResult<Vec<FileEntry>> {
798        Ok(self.list_files_result()?.entries)
799    }
800
801    /// Traverse the project with explicit bounds and skip evidence.
802    pub fn list_files_result(&self) -> DevelopmentResult<ProjectTreeResult> {
803        {
804            let cache = self.tree_cache.lock().map_err(|_| {
805                DevelopmentError::Conflict("project tree cache is unavailable".into())
806            })?;
807            if let Some((created, result)) = cache.as_ref()
808                && created.elapsed() <= Duration::from_millis(250)
809            {
810                return Ok(result.clone());
811            }
812        }
813        let mut result = ProjectTreeResult {
814            entries: Vec::new(),
815            truncated: false,
816            limit: MAX_FILE_ENTRIES,
817            ignored_directories: Vec::new(),
818            skipped_symlinks: 0,
819        };
820        visit_files(&self.root, &self.root, &mut result)?;
821        let git = git_statuses(&self.root);
822        for entry in &mut result.entries {
823            entry.git_status = git.get(&entry.path).cloned();
824            if let Some(buffer) = self.buffers.get(&entry.path) {
825                entry.dirty = buffer.dirty;
826                entry.actor = Some(buffer.actor.clone());
827            }
828        }
829        result
830            .entries
831            .sort_by(|left, right| left.path.cmp(&right.path));
832        result.ignored_directories.sort();
833        result.ignored_directories.dedup();
834        *self.tree_cache.lock().map_err(|_| {
835            DevelopmentError::Conflict("project tree cache is unavailable".into())
836        })? = Some((Instant::now(), result.clone()));
837        Ok(result)
838    }
839
840    pub fn read_file(&mut self, path: &str) -> DevelopmentResult<String> {
841        let (_, relative) = self.resolve_path(path, false)?;
842        let content = self.read_file_snapshot(path)?;
843        self.record(
844            DevelopmentEventKind::FileOpened,
845            serde_json::json!({"path": relative}),
846        )?;
847        Ok(content)
848    }
849
850    /// Read a confined file without producing one timeline event per file in a
851    /// bounded aggregate operation such as project grep.
852    pub(crate) fn read_file_snapshot(&self, path: &str) -> DevelopmentResult<String> {
853        let (absolute, _) = self.resolve_path(path, false)?;
854        read_bounded_utf8(&absolute, MAX_FILE_BYTES, "project file")
855    }
856
857    pub fn open_buffer(&mut self, path: &str, actor: Actor) -> DevelopmentResult<EditorBuffer> {
858        let content = self.read_file(path)?;
859        let (_, relative) = self.resolve_path(path, false)?;
860        let buffer = EditorBuffer {
861            path: relative.clone(),
862            original_hash: hash(&content),
863            content,
864            dirty: false,
865            cursor_line: 1,
866            cursor_column: 1,
867            selection: None,
868            actor,
869        };
870        self.buffers.insert(relative, buffer.clone());
871        Ok(buffer)
872    }
873
874    pub fn buffers(&self) -> impl Iterator<Item = &EditorBuffer> {
875        self.buffers.values()
876    }
877
878    pub fn buffer(&self, path: &str) -> Option<&EditorBuffer> {
879        self.buffers.get(path)
880    }
881
882    pub fn edit_buffer(
883        &mut self,
884        path: &str,
885        content: String,
886        actor: Actor,
887    ) -> DevelopmentResult<()> {
888        if content.len() > MAX_BUFFER_BYTES {
889            return Err(DevelopmentError::InvalidInput(format!(
890                "buffer exceeds the {} byte limit",
891                MAX_BUFFER_BYTES
892            )));
893        }
894        if !self.buffers.contains_key(path) {
895            if self.resolve_path(path, false).is_ok() {
896                self.open_buffer(path, actor.clone())?;
897            } else {
898                let (_, relative) = self.resolve_path(path, true)?;
899                self.buffers.insert(
900                    relative.clone(),
901                    EditorBuffer {
902                        path: relative,
903                        content: String::new(),
904                        original_hash: hash(""),
905                        dirty: false,
906                        cursor_line: 1,
907                        cursor_column: 1,
908                        selection: None,
909                        actor: actor.clone(),
910                    },
911                );
912            }
913        }
914        let buffer = self
915            .buffers
916            .get_mut(path)
917            .ok_or_else(|| DevelopmentError::NotFound(format!("buffer {path}")))?;
918        let history = self.undo.entry(path.to_string()).or_default();
919        if history.len() == 256 {
920            history.remove(0);
921        }
922        history.push(buffer.content.clone());
923        self.redo.remove(path);
924        buffer.content = content;
925        buffer.dirty = hash(&buffer.content) != buffer.original_hash;
926        buffer.actor = actor;
927        self.revision = self.revision.saturating_add(1);
928        self.invalidate_tree_cache();
929        Ok(())
930    }
931
932    pub fn save_buffer(&mut self, path: &str) -> DevelopmentResult<EditorBuffer> {
933        let buffer = self
934            .buffers
935            .get(path)
936            .cloned()
937            .ok_or_else(|| DevelopmentError::NotFound(format!("buffer {path}")))?;
938        let disk_hash = match read_existing(&self.root, path) {
939            Ok(content) => hash(&content),
940            Err(DevelopmentError::Io(error)) if error.kind() == std::io::ErrorKind::NotFound => {
941                hash("")
942            }
943            Err(error) => return Err(error),
944        };
945        if disk_hash != buffer.original_hash {
946            return Err(DevelopmentError::Conflict(format!(
947                "{path} changed on disk after the buffer was opened"
948            )));
949        }
950        self.write_file(path, &buffer.content, buffer.actor.clone())?;
951        let mut saved = buffer;
952        saved.original_hash = hash(&saved.content);
953        saved.dirty = false;
954        self.buffers.insert(path.into(), saved.clone());
955        Ok(saved)
956    }
957
958    pub fn undo_buffer(&mut self, path: &str) -> DevelopmentResult<EditorBuffer> {
959        let previous = self
960            .undo
961            .get_mut(path)
962            .and_then(Vec::pop)
963            .ok_or_else(|| DevelopmentError::NotFound(format!("undo history for {path}")))?;
964        let buffer = self
965            .buffers
966            .get_mut(path)
967            .ok_or_else(|| DevelopmentError::NotFound(format!("buffer {path}")))?;
968        self.redo
969            .entry(path.to_string())
970            .or_default()
971            .push(std::mem::replace(&mut buffer.content, previous));
972        buffer.dirty = hash(&buffer.content) != buffer.original_hash;
973        self.revision = self.revision.saturating_add(1);
974        let result = buffer.clone();
975        self.invalidate_tree_cache();
976        Ok(result)
977    }
978
979    pub fn redo_buffer(&mut self, path: &str) -> DevelopmentResult<EditorBuffer> {
980        let next = self
981            .redo
982            .get_mut(path)
983            .and_then(Vec::pop)
984            .ok_or_else(|| DevelopmentError::NotFound(format!("redo history for {path}")))?;
985        let buffer = self
986            .buffers
987            .get_mut(path)
988            .ok_or_else(|| DevelopmentError::NotFound(format!("buffer {path}")))?;
989        self.undo
990            .entry(path.to_string())
991            .or_default()
992            .push(std::mem::replace(&mut buffer.content, next));
993        buffer.dirty = hash(&buffer.content) != buffer.original_hash;
994        self.revision = self.revision.saturating_add(1);
995        let result = buffer.clone();
996        self.invalidate_tree_cache();
997        Ok(result)
998    }
999
1000    pub fn replace_in_buffer(
1001        &mut self,
1002        path: &str,
1003        needle: &str,
1004        replacement: &str,
1005        actor: Actor,
1006    ) -> DevelopmentResult<usize> {
1007        if needle.is_empty() {
1008            return Err(DevelopmentError::InvalidInput(
1009                "search text must not be empty".into(),
1010            ));
1011        }
1012        if !self.buffers.contains_key(path) {
1013            self.open_buffer(path, actor.clone())?;
1014        }
1015        let current = self
1016            .buffers
1017            .get(path)
1018            .ok_or_else(|| DevelopmentError::NotFound(format!("buffer {path}")))?
1019            .content
1020            .clone();
1021        let matches = current.matches(needle).count();
1022        if matches > 0 {
1023            self.edit_buffer(path, current.replace(needle, replacement), actor)?;
1024        }
1025        Ok(matches)
1026    }
1027
1028    pub fn set_buffer_cursor(
1029        &mut self,
1030        path: &str,
1031        line: u32,
1032        column: u32,
1033    ) -> DevelopmentResult<()> {
1034        if line == 0 || column == 0 {
1035            return Err(DevelopmentError::InvalidInput(
1036                "editor cursor positions are one-based".into(),
1037            ));
1038        }
1039        let buffer = self
1040            .buffers
1041            .get_mut(path)
1042            .ok_or_else(|| DevelopmentError::NotFound(format!("buffer {path}")))?;
1043        buffer.cursor_line = line;
1044        buffer.cursor_column = column;
1045        Ok(())
1046    }
1047
1048    pub fn rename_path(&mut self, from: &str, to: &str, actor: Actor) -> DevelopmentResult<()> {
1049        self.invalidate_tree_cache();
1050        let (source, source_relative) = self.resolve_path(from, false)?;
1051        let (destination, destination_relative) = self.resolve_path(to, true)?;
1052        if destination.exists() {
1053            return Err(DevelopmentError::Conflict(format!(
1054                "destination already exists: {to}"
1055            )));
1056        }
1057        if let Some(parent) = destination.parent() {
1058            fs::create_dir_all(parent)?;
1059        }
1060        fs::rename(source, destination)?;
1061        if let Some(mut buffer) = self.buffers.remove(&source_relative) {
1062            buffer.path = destination_relative.clone();
1063            self.buffers.insert(destination_relative.clone(), buffer);
1064        }
1065        if let Some(history) = self.undo.remove(&source_relative) {
1066            self.undo.insert(destination_relative.clone(), history);
1067        }
1068        if let Some(history) = self.redo.remove(&source_relative) {
1069            self.redo.insert(destination_relative.clone(), history);
1070        }
1071        self.revision = self.revision.saturating_add(1);
1072        self.record_as(
1073            actor,
1074            DevelopmentEventKind::FileSaved,
1075            serde_json::json!({"operation": "rename", "from": source_relative, "to": destination_relative}),
1076        )
1077    }
1078
1079    pub fn create_directory(&mut self, path: &str, actor: Actor) -> DevelopmentResult<()> {
1080        self.invalidate_tree_cache();
1081        let (absolute, relative) = self.resolve_path(path, true)?;
1082        if absolute.exists() {
1083            return Err(DevelopmentError::Conflict(format!(
1084                "path already exists: {path}"
1085            )));
1086        }
1087        fs::create_dir_all(&absolute)?;
1088        self.revision = self.revision.saturating_add(1);
1089        self.record_as(
1090            actor,
1091            DevelopmentEventKind::FileSaved,
1092            serde_json::json!({"operation": "mkdir", "path": relative}),
1093        )
1094    }
1095
1096    pub fn delete_path(&mut self, path: &str, actor: Actor) -> DevelopmentResult<()> {
1097        self.invalidate_tree_cache();
1098        let (absolute, relative) = self.resolve_path(path, false)?;
1099        let metadata = fs::symlink_metadata(&absolute)?;
1100        if metadata.is_dir() {
1101            if fs::read_dir(&absolute)?.next().is_some() {
1102                return Err(DevelopmentError::Conflict(format!(
1103                    "refusing to delete non-empty directory: {path}"
1104                )));
1105            }
1106            fs::remove_dir(&absolute)?;
1107        } else {
1108            fs::remove_file(&absolute)?;
1109        }
1110        self.buffers.remove(&relative);
1111        self.undo.remove(&relative);
1112        self.redo.remove(&relative);
1113        self.revision = self.revision.saturating_add(1);
1114        self.record_as(
1115            actor,
1116            DevelopmentEventKind::FileSaved,
1117            serde_json::json!({"operation": "delete", "path": relative}),
1118        )
1119    }
1120
1121    pub fn write_file(&mut self, path: &str, content: &str, actor: Actor) -> DevelopmentResult<()> {
1122        self.invalidate_tree_cache();
1123        if content.len() > MAX_FILE_BYTES {
1124            return Err(DevelopmentError::InvalidInput(format!(
1125                "file exceeds the {} byte write limit",
1126                MAX_FILE_BYTES
1127            )));
1128        }
1129        let (absolute, relative) = self.resolve_path(path, true)?;
1130        let before_hash = fs::read_to_string(&absolute)
1131            .ok()
1132            .map(|existing| hash(&existing));
1133        let parent = absolute
1134            .parent()
1135            .ok_or_else(|| DevelopmentError::InvalidInput("file has no parent".into()))?;
1136        fs::create_dir_all(parent)?;
1137        let temporary = absolute.with_extension(format!(
1138            "glass-tmp-{}-{}",
1139            std::process::id(),
1140            self.revision.saturating_add(1)
1141        ));
1142        {
1143            let mut file = OpenOptions::new()
1144                .create_new(true)
1145                .write(true)
1146                .open(&temporary)?;
1147            file.write_all(content.as_bytes())?;
1148            file.sync_all()?;
1149        }
1150        if let Err(error) = fs::rename(&temporary, &absolute) {
1151            let _ = fs::remove_file(&temporary);
1152            return Err(error.into());
1153        }
1154        self.revision = self.revision.saturating_add(1);
1155        self.record_as(
1156            actor,
1157            DevelopmentEventKind::FileSaved,
1158            serde_json::json!({
1159                "path": relative,
1160                "bytes": content.len(),
1161                "beforeHash": before_hash,
1162                "afterHash": hash(content)
1163            }),
1164        )?;
1165        if self.processes.list_checked()?.iter().any(|process| {
1166            matches!(process.state, super::ProcessState::Running)
1167                && (process.name.contains("dev") || process.name.contains("server"))
1168        }) {
1169            self.record(
1170                DevelopmentEventKind::HmrObserved,
1171                serde_json::json!({
1172                    "path": relative,
1173                    "status": "pending-runtime-observation",
1174                    "browserUrl": self.detection.browser_url
1175                }),
1176            )?;
1177        }
1178        Ok(())
1179    }
1180
1181    pub fn start_process(
1182        &mut self,
1183        name: &str,
1184        command: &str,
1185    ) -> DevelopmentResult<super::ProcessSnapshot> {
1186        let snapshot = self.processes.start(name, command)?;
1187        self.revision = self.revision.saturating_add(1);
1188        self.record(
1189            DevelopmentEventKind::ProcessStarted,
1190            serde_json::json!({
1191                "name": name,
1192                "commandBytes": command.len(),
1193                "commandSha256": hash(command),
1194                "pid": snapshot.pid
1195            }),
1196        )?;
1197        Ok(snapshot)
1198    }
1199
1200    pub fn stop_process(&mut self, name: &str) -> DevelopmentResult<super::ProcessSnapshot> {
1201        let snapshot = self.processes.stop(name)?;
1202        self.revision = self.revision.saturating_add(1);
1203        self.record(
1204            DevelopmentEventKind::ProcessExited,
1205            serde_json::json!({"name": name, "state": snapshot.state}),
1206        )?;
1207        Ok(snapshot)
1208    }
1209
1210    pub fn run_verification(
1211        &mut self,
1212        name: &str,
1213        command: &str,
1214        timeout: Duration,
1215    ) -> DevelopmentResult<super::ProcessSnapshot> {
1216        self.record(
1217            DevelopmentEventKind::TestStarted,
1218            serde_json::json!({
1219                "name": name,
1220                "commandBytes": command.len(),
1221                "commandSha256": hash(command)
1222            }),
1223        )?;
1224        #[cfg(windows)]
1225        {
1226            let snapshot = self.processes.run_bounded(name, command, timeout)?;
1227            self.record(
1228                DevelopmentEventKind::TestCompleted,
1229                serde_json::json!({
1230                    "name": name,
1231                    "state": snapshot.state,
1232                    "outputBytes": snapshot.output.len(),
1233                    "outputSha256": hash(&snapshot.output)
1234                }),
1235            )?;
1236            return Ok(snapshot);
1237        }
1238        #[cfg(not(windows))]
1239        self.start_process(name, command)?;
1240        #[cfg(not(windows))]
1241        self.processes.close_input(name)?;
1242        #[cfg(not(windows))]
1243        let deadline = Instant::now() + timeout;
1244        #[cfg(not(windows))]
1245        let snapshot = loop {
1246            let snapshot = self
1247                .processes
1248                .poll()?
1249                .into_iter()
1250                .find(|snapshot| snapshot.name == name)
1251                .ok_or_else(|| DevelopmentError::NotFound(format!("process {name}")))?;
1252            if !matches!(snapshot.state, super::ProcessState::Running) {
1253                break snapshot;
1254            }
1255            if Instant::now() >= deadline {
1256                self.stop_process(name)?;
1257                self.record(
1258                    DevelopmentEventKind::TestCompleted,
1259                    serde_json::json!({"name": name, "status": "timeout"}),
1260                )?;
1261                return Err(DevelopmentError::Process(format!(
1262                    "verification {name} exceeded {} seconds",
1263                    timeout.as_secs()
1264                )));
1265            }
1266            std::thread::sleep(Duration::from_millis(25));
1267        };
1268        #[cfg(not(windows))]
1269        self.record(
1270            DevelopmentEventKind::TestCompleted,
1271            serde_json::json!({
1272                "name": name,
1273                "state": snapshot.state,
1274                "outputBytes": snapshot.output.len(),
1275                "outputSha256": hash(&snapshot.output)
1276            }),
1277        )?;
1278        #[cfg(not(windows))]
1279        Ok(snapshot)
1280    }
1281
1282    pub fn run_command_to_completion(
1283        &mut self,
1284        name: &str,
1285        command: &str,
1286        timeout: Duration,
1287    ) -> DevelopmentResult<super::ProcessSnapshot> {
1288        #[cfg(windows)]
1289        return self.processes.run_bounded(name, command, timeout);
1290
1291        #[cfg(not(windows))]
1292        self.start_process(name, command)?;
1293        #[cfg(not(windows))]
1294        self.processes.close_input(name)?;
1295        #[cfg(not(windows))]
1296        let deadline = Instant::now() + timeout;
1297        #[cfg(not(windows))]
1298        loop {
1299            let snapshot = self
1300                .processes
1301                .poll()?
1302                .into_iter()
1303                .find(|snapshot| snapshot.name == name)
1304                .ok_or_else(|| DevelopmentError::NotFound(format!("process {name}")))?;
1305            if !matches!(snapshot.state, super::ProcessState::Running) {
1306                self.record(
1307                    DevelopmentEventKind::ProcessExited,
1308                    serde_json::json!({
1309                        "name": name,
1310                        "state": snapshot.state,
1311                        "outputBytes": snapshot.output.len(),
1312                        "outputSha256": hash(&snapshot.output)
1313                    }),
1314                )?;
1315                return Ok(snapshot);
1316            }
1317            if Instant::now() >= deadline {
1318                self.stop_process(name)?;
1319                return Err(DevelopmentError::Process(format!(
1320                    "command {name} exceeded {} seconds",
1321                    timeout.as_secs()
1322                )));
1323            }
1324            std::thread::sleep(Duration::from_millis(25));
1325        }
1326    }
1327
1328    /// Record a live-update proof only after a browser consumer has observed a
1329    /// strictly newer semantic revision. This keeps HMR/build claims tied to
1330    /// caller-supplied browser evidence instead of treating a file save as
1331    /// proof that the running application changed.
1332    pub fn confirm_live_update(
1333        &mut self,
1334        source_path: &str,
1335        before_revision: u64,
1336        after_revision: u64,
1337        semantic_changes: usize,
1338        actor: Actor,
1339    ) -> DevelopmentResult<()> {
1340        self.resolve_path(source_path, false)?;
1341        if after_revision <= before_revision {
1342            return Err(DevelopmentError::InvalidInput(
1343                "live update proof requires a newer browser revision".into(),
1344            ));
1345        }
1346        self.record_as(
1347            actor,
1348            DevelopmentEventKind::HmrObserved,
1349            serde_json::json!({
1350                "sourcePath": source_path,
1351                "status": "confirmed-runtime-observation",
1352                "beforeBrowserRevision": before_revision,
1353                "afterBrowserRevision": after_revision,
1354                "semanticChanges": semantic_changes,
1355            }),
1356        )
1357    }
1358
1359    #[allow(clippy::too_many_arguments)]
1360    pub fn link_runtime_source(
1361        &mut self,
1362        entity_id: &str,
1363        path: &str,
1364        start_line: u32,
1365        end_line: u32,
1366        provenance: LinkProvenance,
1367        detail: &str,
1368        confidence: f32,
1369        actor: Actor,
1370    ) -> DevelopmentResult<RuntimeLink> {
1371        let (_, relative) = self.resolve_path(path, false)?;
1372        let link = RuntimeLink {
1373            entity_id: entity_id.into(),
1374            source: SourceLocation::new(relative, start_line, end_line)?,
1375            evidence: LinkEvidence {
1376                provenance,
1377                detail: detail.into(),
1378                confidence,
1379            },
1380        };
1381        self.graph.link(link.clone())?;
1382        self.graph.save(&self.graph_path)?;
1383        self.revision = self.revision.saturating_add(1);
1384        self.record_as(
1385            actor,
1386            DevelopmentEventKind::SourceRuntimeLinked,
1387            serde_json::to_value(&link)?,
1388        )?;
1389        Ok(link)
1390    }
1391
1392    pub fn diff(&mut self) -> DevelopmentResult<ProjectDiff> {
1393        build_diff(&self.root, &self.timeline, &self.graph, &mut self.processes)
1394    }
1395
1396    pub fn discover_runtime_links(&mut self) -> DevelopmentResult<Vec<RuntimeLink>> {
1397        let discovered = self.graph.discover_explicit_markers(&self.root)?;
1398        self.graph.save(&self.graph_path)?;
1399        for link in &discovered {
1400            self.record(
1401                DevelopmentEventKind::SourceRuntimeLinked,
1402                serde_json::to_value(link)?,
1403            )?;
1404        }
1405        if !discovered.is_empty() {
1406            self.revision = self.revision.saturating_add(1);
1407        }
1408        Ok(discovered)
1409    }
1410
1411    pub fn publish_rust_diagnostics(
1412        &mut self,
1413        path: &str,
1414    ) -> DevelopmentResult<Vec<LanguageDiagnostic>> {
1415        if self.language.is_none() {
1416            self.language = Some(LspClient::rust_analyzer(&self.root)?);
1417        }
1418        let diagnostics = self
1419            .language
1420            .as_mut()
1421            .expect("language client initialized")
1422            .diagnostics(path)?;
1423        self.diagnostics.insert(path.into(), diagnostics.clone());
1424        self.record(
1425            DevelopmentEventKind::DiagnosticsPublished,
1426            serde_json::json!({"path": path, "count": diagnostics.len(), "diagnostics": diagnostics}),
1427        )?;
1428        Ok(diagnostics)
1429    }
1430
1431    pub fn evaluate_semantic_breakpoints(
1432        &mut self,
1433        breakpoints: &[SemanticBreakpoint],
1434        before: &SemanticSnapshot,
1435        after: &SemanticSnapshot,
1436    ) -> DevelopmentResult<Vec<SemanticBreakpointHit>> {
1437        let hits = super::evaluate_breakpoints(breakpoints, before, after, &self.graph);
1438        for hit in &hits {
1439            self.record(
1440                DevelopmentEventKind::SemanticBreakpointHit,
1441                serde_json::to_value(hit)?,
1442            )?;
1443        }
1444        Ok(hits)
1445    }
1446
1447    pub fn replay(&self, start: usize, limit: usize) -> DevelopmentResult<ReplayWindow> {
1448        super::replay(&self.timeline, start, limit)
1449    }
1450
1451    pub fn search(&mut self, query: &str, limit: usize) -> DevelopmentResult<Vec<SearchHit>> {
1452        if query.trim().is_empty() || query.len() > 256 || limit == 0 || limit > 256 {
1453            return Err(DevelopmentError::InvalidInput(
1454                "search requires a 1-256 byte query and a 1-256 result limit".into(),
1455            ));
1456        }
1457        let mut hits = Vec::new();
1458        for file in self.list_files()? {
1459            if let Some(score) = super::fuzzy_score(query, &file.path) {
1460                hits.push(SearchHit {
1461                    kind: SearchKind::File,
1462                    label: file.path,
1463                    detail: file.git_status.unwrap_or_else(|| "project file".into()),
1464                    score,
1465                });
1466            }
1467        }
1468        for entity in self.graph.links.keys() {
1469            if let Some(score) = super::fuzzy_score(query, entity) {
1470                hits.push(SearchHit {
1471                    kind: SearchKind::BrowserEntity,
1472                    label: entity.clone(),
1473                    detail: "runtime/source graph entity".into(),
1474                    score,
1475                });
1476            }
1477        }
1478        for process in self.processes.list_checked()? {
1479            if let Some(score) = super::fuzzy_score(query, &process.name) {
1480                hits.push(SearchHit {
1481                    kind: SearchKind::Process,
1482                    label: process.name,
1483                    detail: format!("{:?}", process.state),
1484                    score,
1485                });
1486            }
1487        }
1488        for event in self.timeline.events() {
1489            let label = format!("{:?}", event.kind);
1490            if let Some(score) = super::fuzzy_score(query, &label) {
1491                hits.push(SearchHit {
1492                    kind: SearchKind::Event,
1493                    label,
1494                    detail: event.id.clone(),
1495                    score,
1496                });
1497            }
1498        }
1499        for command in [
1500            "project files",
1501            "project open",
1502            "project diagnostics",
1503            "project run",
1504            "project diff",
1505            "project timeline",
1506            "project replay",
1507            "project graph",
1508            "project experiment",
1509            "project neovim",
1510            "agent prompt",
1511        ] {
1512            if let Some(score) = super::fuzzy_score(query, command) {
1513                hits.push(SearchHit {
1514                    kind: SearchKind::Command,
1515                    label: command.into(),
1516                    detail: "command palette".into(),
1517                    score,
1518                });
1519            }
1520        }
1521        Ok(super::rank(hits, limit))
1522    }
1523
1524    pub fn record(
1525        &mut self,
1526        kind: DevelopmentEventKind,
1527        payload: serde_json::Value,
1528    ) -> DevelopmentResult<()> {
1529        self.record_as(self.actor.clone(), kind, payload)
1530    }
1531
1532    pub fn record_as(
1533        &mut self,
1534        actor: Actor,
1535        kind: DevelopmentEventKind,
1536        payload: serde_json::Value,
1537    ) -> DevelopmentResult<()> {
1538        self.timeline
1539            .record(actor, kind, self.root.display().to_string(), payload)?;
1540        Ok(())
1541    }
1542
1543    fn resolve_path(
1544        &self,
1545        input: &str,
1546        allow_missing: bool,
1547    ) -> DevelopmentResult<(PathBuf, String)> {
1548        if input.is_empty() || input.len() > 512 {
1549            return Err(DevelopmentError::InvalidInput(
1550                "relative path must be 1-512 bytes".into(),
1551            ));
1552        }
1553        let path = Path::new(input);
1554        if path.is_absolute()
1555            || path
1556                .components()
1557                .any(|component| matches!(component, Component::ParentDir))
1558        {
1559            return Err(DevelopmentError::PathOutsideWorkspace(path.to_path_buf()));
1560        }
1561        let candidate = self.root.join(path);
1562        let mut existing_parent = candidate
1563            .parent()
1564            .ok_or_else(|| DevelopmentError::InvalidInput("path has no parent".into()))?;
1565        while !existing_parent.exists() {
1566            existing_parent = existing_parent
1567                .parent()
1568                .ok_or_else(|| DevelopmentError::PathOutsideWorkspace(candidate.clone()))?;
1569        }
1570        let canonical_parent = fs::canonicalize(existing_parent)?;
1571        if !canonical_parent.starts_with(&self.root) {
1572            return Err(DevelopmentError::PathOutsideWorkspace(candidate));
1573        }
1574        if candidate.exists() {
1575            let canonical = fs::canonicalize(&candidate)?;
1576            if !canonical.starts_with(&self.root) {
1577                return Err(DevelopmentError::PathOutsideWorkspace(candidate));
1578            }
1579        } else if !allow_missing {
1580            return Err(DevelopmentError::NotFound(input.into()));
1581        }
1582        Ok((candidate, portable_relative_path(path)))
1583    }
1584}
1585
1586fn portable_relative_path(path: &Path) -> String {
1587    path.components()
1588        .map(|component| component.as_os_str().to_string_lossy())
1589        .collect::<Vec<_>>()
1590        .join("/")
1591}
1592
1593fn load_editor_checkpoints(
1594    path: &Path,
1595) -> DevelopmentResult<BTreeMap<String, super::EditorCheckpoint>> {
1596    if !path.is_file() {
1597        return Ok(BTreeMap::new());
1598    }
1599    let data = fs::read(path)?;
1600    serde_json::from_slice(&data)
1601        .map_err(|error| DevelopmentError::Config(format!("invalid editor checkpoints: {error}")))
1602}
1603
1604fn comments_from_timeline(timeline: &Timeline) -> BTreeMap<String, Vec<super::EditorComment>> {
1605    let mut comments: BTreeMap<String, Vec<super::EditorComment>> = BTreeMap::new();
1606    for event in timeline.events() {
1607        match event.kind {
1608            DevelopmentEventKind::EditorCommentAdded => {
1609                if let Ok(comment) =
1610                    serde_json::from_value::<super::EditorComment>(event.payload.clone())
1611                {
1612                    comments
1613                        .entry(comment.path.clone())
1614                        .or_default()
1615                        .push(comment);
1616                }
1617            }
1618            DevelopmentEventKind::EditorCommentResolved => {
1619                let Some(id) = event.payload.get("id").and_then(serde_json::Value::as_str) else {
1620                    continue;
1621                };
1622                for comment in comments.values_mut().flat_map(|items| items.iter_mut()) {
1623                    if comment.id == id {
1624                        comment.state = super::EditorCommentState::Resolved;
1625                        if let Some(revision) = event
1626                            .payload
1627                            .get("updatedRevision")
1628                            .and_then(serde_json::Value::as_u64)
1629                        {
1630                            comment.updated_revision = revision;
1631                        }
1632                    }
1633                }
1634            }
1635            _ => {}
1636        }
1637    }
1638    comments
1639}
1640
1641fn proposals_from_timeline(timeline: &Timeline) -> BTreeMap<String, super::EditorProposal> {
1642    let mut proposals = BTreeMap::new();
1643    for event in timeline.events() {
1644        match event.kind {
1645            DevelopmentEventKind::EditorProposalCreated => {
1646                if let Ok(proposal) =
1647                    serde_json::from_value::<super::EditorProposal>(event.payload.clone())
1648                {
1649                    proposals.insert(proposal.id.clone(), proposal);
1650                }
1651            }
1652            DevelopmentEventKind::EditorProposalAccepted
1653            | DevelopmentEventKind::EditorProposalRejected => {
1654                let Some(id) = event.payload.get("id").and_then(serde_json::Value::as_str) else {
1655                    continue;
1656                };
1657                if let Some(proposal) = proposals.get_mut(id) {
1658                    proposal.state =
1659                        if matches!(event.kind, DevelopmentEventKind::EditorProposalAccepted) {
1660                            super::EditorProposalState::Accepted
1661                        } else if event
1662                            .payload
1663                            .get("reason")
1664                            .and_then(serde_json::Value::as_str)
1665                            .is_some_and(|reason| reason.contains("stale"))
1666                        {
1667                            super::EditorProposalState::Stale
1668                        } else {
1669                            super::EditorProposalState::Rejected
1670                        };
1671                }
1672            }
1673            _ => {}
1674        }
1675    }
1676    proposals
1677}
1678
1679pub fn detect_project(root: impl AsRef<Path>) -> DevelopmentResult<ProjectDetection> {
1680    let root = canonical_root(root.as_ref())?;
1681    let config_path = [root.join("glass.toml"), root.join(".glass.toml")]
1682        .into_iter()
1683        .find(|path| path.is_file());
1684    let mut languages = Vec::new();
1685    if root.join("Cargo.toml").is_file() {
1686        languages.push("Rust".into());
1687    }
1688    if root.join("package.json").is_file() {
1689        languages.push("JavaScript/TypeScript".into());
1690    }
1691    if root.join("pyproject.toml").is_file() || root.join("requirements.txt").is_file() {
1692        languages.push("Python".into());
1693    }
1694    if root.join("go.mod").is_file() {
1695        languages.push("Go".into());
1696    }
1697    let package_manager = if root.join("pnpm-lock.yaml").is_file() {
1698        Some("pnpm".into())
1699    } else if root.join("yarn.lock").is_file() {
1700        Some("yarn".into())
1701    } else if root.join("bun.lockb").is_file() || root.join("bun.lock").is_file() {
1702        Some("bun".into())
1703    } else if root.join("package-lock.json").is_file() {
1704        Some("npm".into())
1705    } else if root.join("Cargo.lock").is_file() {
1706        Some("cargo".into())
1707    } else {
1708        None
1709    };
1710    let framework = detect_framework(&root);
1711    let config = load_project_config(config_path.as_deref())?;
1712    let defaults = default_commands(&root, package_manager.as_deref());
1713    let build_system = if root.join("Cargo.toml").is_file() {
1714        Some("cargo".into())
1715    } else if root.join("package.json").is_file() {
1716        Some(package_manager.clone().unwrap_or_else(|| "npm".into()))
1717    } else if root.join("pyproject.toml").is_file() {
1718        Some("pyproject".into())
1719    } else if root.join("go.mod").is_file() {
1720        Some("go".into())
1721    } else {
1722        None
1723    };
1724    let formatter = if root.join("Cargo.toml").is_file() {
1725        Some("rustfmt".into())
1726    } else if root.join("package.json").is_file() {
1727        Some("prettier".into())
1728    } else if root.join("pyproject.toml").is_file() {
1729        Some("ruff format".into())
1730    } else if root.join("go.mod").is_file() {
1731        Some("gofmt".into())
1732    } else {
1733        None
1734    };
1735    let lsp_servers = [
1736        ("Rust", "rust-analyzer"),
1737        ("JavaScript/TypeScript", "typescript-language-server"),
1738        ("Python", "pyright-langserver"),
1739        ("Go", "gopls"),
1740    ]
1741    .into_iter()
1742    .filter(|(language, server)| {
1743        languages.iter().any(|value| value == language) && command_available(server)
1744    })
1745    .map(|(_, server)| server.to_string())
1746    .collect();
1747    let browser_url = config.browser.url;
1748    let local_development_urls = browser_url.iter().cloned().collect();
1749    Ok(ProjectDetection {
1750        root: root.clone(),
1751        languages,
1752        package_manager,
1753        framework,
1754        build_system,
1755        formatter,
1756        lsp_servers,
1757        git_branch: git_branch(&root),
1758        dev_command: config.commands.dev.or(defaults.0),
1759        test_command: config.commands.test.or(defaults.1),
1760        lint_command: config.commands.lint.or(defaults.2),
1761        build_command: config.commands.build.or(defaults.3),
1762        browser_url,
1763        local_development_urls,
1764        editor_engine: config.editor.engine,
1765        agent_harness: config.agent.harness,
1766        config_path,
1767    })
1768}
1769
1770fn load_project_config(path: Option<&Path>) -> DevelopmentResult<GlassProjectConfig> {
1771    path.map(fs::read_to_string)
1772        .transpose()?
1773        .map(|text| {
1774            toml::from_str::<GlassProjectConfig>(&text)
1775                .map_err(|error| DevelopmentError::Config(error.to_string()))
1776        })
1777        .transpose()
1778        .map(Option::unwrap_or_default)
1779}
1780
1781pub(crate) fn canonical_root(root: &Path) -> DevelopmentResult<PathBuf> {
1782    let root = if root.is_file() {
1783        root.parent().unwrap_or(root)
1784    } else {
1785        root
1786    };
1787    let root = fs::canonicalize(root)?;
1788    if !root.is_dir() {
1789        return Err(DevelopmentError::InvalidInput(
1790            "project root must be a directory".into(),
1791        ));
1792    }
1793    Ok(root)
1794}
1795
1796fn visit_files(
1797    root: &Path,
1798    current: &Path,
1799    result: &mut ProjectTreeResult,
1800) -> DevelopmentResult<()> {
1801    if result.entries.len() >= MAX_FILE_ENTRIES {
1802        result.truncated = true;
1803        return Ok(());
1804    }
1805    let mut children =
1806        fs::read_dir(current).map(|entries| entries.collect::<Result<Vec<_>, _>>())??;
1807    children.sort_by_key(|entry| entry.file_name());
1808    for entry in children {
1809        if result.entries.len() >= MAX_FILE_ENTRIES {
1810            result.truncated = true;
1811            break;
1812        }
1813        let path = entry.path();
1814        let name = entry.file_name().to_string_lossy().into_owned();
1815        if name == ".git" || name == "target" || name == "node_modules" || name == ".glass" {
1816            result.ignored_directories.push(name);
1817            continue;
1818        }
1819        let metadata = fs::symlink_metadata(&path)?;
1820        if metadata.file_type().is_symlink() {
1821            result.skipped_symlinks = result.skipped_symlinks.saturating_add(1);
1822            continue;
1823        }
1824        let relative = path
1825            .strip_prefix(root)
1826            .map_err(|_| DevelopmentError::PathOutsideWorkspace(path.clone()))?;
1827        let relative = portable_relative_path(relative);
1828        if metadata.is_dir() {
1829            result.entries.push(FileEntry {
1830                path: relative,
1831                kind: FileKind::Directory,
1832                bytes: None,
1833                git_status: None,
1834                dirty: false,
1835                actor: None,
1836            });
1837            visit_files(root, &path, result)?;
1838        } else if metadata.is_file() {
1839            result.entries.push(FileEntry {
1840                path: relative,
1841                kind: FileKind::File,
1842                bytes: Some(metadata.len()),
1843                git_status: None,
1844                dirty: false,
1845                actor: None,
1846            });
1847        }
1848    }
1849    Ok(())
1850}
1851
1852fn read_existing(root: &Path, path: &str) -> DevelopmentResult<String> {
1853    let absolute = root.join(path);
1854    read_bounded_utf8(&absolute, MAX_BUFFER_BYTES, "existing editor file")
1855}
1856
1857fn hash(content: &str) -> String {
1858    Sha256::digest(content.as_bytes())
1859        .iter()
1860        .map(|byte| format!("{byte:02x}"))
1861        .collect()
1862}
1863
1864fn git_branch(root: &Path) -> Option<String> {
1865    crate::git::git_command(root)
1866        .args([
1867            "-c",
1868            "alias.rev-parse=",
1869            "rev-parse",
1870            "--abbrev-ref",
1871            "HEAD",
1872        ])
1873        .output()
1874        .ok()
1875        .filter(|output| output.status.success())
1876        .and_then(|output| String::from_utf8(output.stdout).ok())
1877        .map(|branch| branch.trim().to_string())
1878        .filter(|branch| !branch.is_empty())
1879}
1880
1881fn git_statuses(root: &Path) -> BTreeMap<String, String> {
1882    let Some(output) = crate::git::git_command(root)
1883        .args([
1884            "-c",
1885            "alias.status=",
1886            "status",
1887            "--porcelain=v1",
1888            "-z",
1889            "--untracked-files=all",
1890        ])
1891        .output()
1892        .ok()
1893        .filter(|output| output.status.success())
1894    else {
1895        return BTreeMap::new();
1896    };
1897    let mut statuses = BTreeMap::new();
1898    for entry in output
1899        .stdout
1900        .split(|byte| *byte == 0)
1901        .filter(|entry| entry.len() >= 4)
1902    {
1903        let status = String::from_utf8_lossy(&entry[..2]).trim().to_string();
1904        let path = String::from_utf8_lossy(&entry[3..]).into_owned();
1905        if !path.is_empty() {
1906            statuses.insert(path, status);
1907        }
1908    }
1909    statuses
1910}
1911
1912fn detect_framework(root: &Path) -> Option<String> {
1913    if let Ok(package) = fs::read_to_string(root.join("package.json"))
1914        && let Ok(value) = serde_json::from_str::<serde_json::Value>(&package)
1915    {
1916        let dependencies = value
1917            .get("dependencies")
1918            .and_then(serde_json::Value::as_object);
1919        let dev_dependencies = value
1920            .get("devDependencies")
1921            .and_then(serde_json::Value::as_object);
1922        if let Some(framework) =
1923            ["next", "vite", "react", "vue", "svelte"]
1924                .into_iter()
1925                .find(|framework| {
1926                    dependencies.is_some_and(|values| values.contains_key(*framework))
1927                        || dev_dependencies.is_some_and(|values| values.contains_key(*framework))
1928                })
1929        {
1930            return Some(framework.into());
1931        }
1932    }
1933    let python = fs::read_to_string(root.join("pyproject.toml"))
1934        .or_else(|_| fs::read_to_string(root.join("requirements.txt")))
1935        .unwrap_or_default()
1936        .to_ascii_lowercase();
1937    ["django", "flask", "fastapi"]
1938        .into_iter()
1939        .find(|framework| python.contains(framework))
1940        .map(str::to_string)
1941}
1942
1943fn default_commands(
1944    root: &Path,
1945    package_manager: Option<&str>,
1946) -> (
1947    Option<String>,
1948    Option<String>,
1949    Option<String>,
1950    Option<String>,
1951) {
1952    if root.join("Cargo.toml").is_file() {
1953        return (
1954            None,
1955            Some("cargo test".into()),
1956            Some("cargo clippy --all-targets --all-features -- -D warnings".into()),
1957            Some("cargo build".into()),
1958        );
1959    }
1960    if root.join("package.json").is_file() {
1961        let manager = package_manager.unwrap_or("npm");
1962        let package = fs::read_to_string(root.join("package.json"))
1963            .ok()
1964            .and_then(|value| serde_json::from_str::<serde_json::Value>(&value).ok());
1965        let command = |script: &str| {
1966            package
1967                .as_ref()
1968                .and_then(|value| value.pointer(&format!("/scripts/{script}")))
1969                .and_then(serde_json::Value::as_str)
1970                .map(|_| format!("{manager} run {script}"))
1971        };
1972        return (
1973            command("dev"),
1974            command("test"),
1975            command("lint"),
1976            command("build"),
1977        );
1978    }
1979    if root.join("pyproject.toml").is_file() {
1980        return (
1981            None,
1982            Some("python -m pytest".into()),
1983            Some("ruff check .".into()),
1984            None,
1985        );
1986    }
1987    if root.join("go.mod").is_file() {
1988        return (
1989            None,
1990            Some("go test ./...".into()),
1991            Some("go vet ./...".into()),
1992            Some("go build ./...".into()),
1993        );
1994    }
1995    (None, None, None, None)
1996}
1997
1998fn command_available(command: &str) -> bool {
1999    Command::new(command)
2000        .arg("--version")
2001        .stdout(std::process::Stdio::null())
2002        .stderr(std::process::Stdio::null())
2003        .status()
2004        .is_ok_and(|status| status.success())
2005}
2006
2007#[cfg(test)]
2008mod tests {
2009    use super::*;
2010    use std::sync::atomic::{AtomicUsize, Ordering};
2011
2012    fn fixture() -> PathBuf {
2013        static NEXT_FIXTURE: AtomicUsize = AtomicUsize::new(0);
2014        let root = std::env::temp_dir().join(format!(
2015            "glass-project-{}-{}",
2016            std::process::id(),
2017            NEXT_FIXTURE.fetch_add(1, Ordering::Relaxed)
2018        ));
2019        let _ = fs::remove_dir_all(&root);
2020        fs::create_dir_all(root.join("src")).unwrap();
2021        fs::write(
2022            root.join("Cargo.toml"),
2023            "[package]\nname='fixture'\nversion='0.1.0'\nedition='2024'\n",
2024        )
2025        .unwrap();
2026        fs::write(root.join("src/main.rs"), "fn main() {}\n").unwrap();
2027        root
2028    }
2029
2030    #[test]
2031    fn detects_cargo_project_and_defaults() {
2032        let root = fixture();
2033        let detection = detect_project(&root).unwrap();
2034        assert_eq!(detection.languages, vec!["Rust"]);
2035        assert_eq!(detection.test_command.as_deref(), Some("cargo test"));
2036        let _ = fs::remove_dir_all(root);
2037    }
2038
2039    #[test]
2040    fn event_feed_reads_do_not_record_monitoring_activity() {
2041        let root = fixture();
2042        drop(ProjectWorkspace::open(&root).unwrap());
2043        let before = ProjectWorkspace::timeline_snapshot(&root).unwrap();
2044        let page = ProjectWorkspace::event_page(&root, None, 64).unwrap();
2045        let after = ProjectWorkspace::timeline_snapshot(&root).unwrap();
2046        assert_eq!(page.events, before);
2047        assert_eq!(after, before);
2048        let _ = fs::remove_dir_all(root);
2049    }
2050
2051    #[test]
2052    fn file_writes_are_confined_and_atomic() {
2053        let root = fixture();
2054        let mut project = ProjectWorkspace::open(&root).unwrap();
2055        project
2056            .write_file("src/lib.rs", "pub fn ok() {}\n", Actor::local())
2057            .unwrap();
2058        assert!(
2059            project
2060                .read_file("src/lib.rs")
2061                .unwrap()
2062                .contains("pub fn ok")
2063        );
2064        assert!(matches!(
2065            project.write_file("../escape", "bad", Actor::local()),
2066            Err(DevelopmentError::PathOutsideWorkspace(_))
2067        ));
2068        let _ = fs::remove_dir_all(root);
2069    }
2070
2071    #[test]
2072    fn editor_save_records_actor_and_clears_dirty_state() {
2073        let root = fixture();
2074        let mut project = ProjectWorkspace::open(&root).unwrap();
2075        project.open_buffer("src/main.rs", Actor::local()).unwrap();
2076        project
2077            .edit_buffer(
2078                "src/main.rs",
2079                "fn main() { println!(\"ok\"); }\n".into(),
2080                Actor::local(),
2081            )
2082            .unwrap();
2083        assert!(project.buffer("src/main.rs").unwrap().dirty);
2084        project.save_buffer("src/main.rs").unwrap();
2085        assert!(!project.buffer("src/main.rs").unwrap().dirty);
2086        assert!(
2087            project
2088                .timeline()
2089                .events()
2090                .any(|event| matches!(event.kind, DevelopmentEventKind::FileSaved))
2091        );
2092        let _ = fs::remove_dir_all(root);
2093    }
2094
2095    #[test]
2096    fn editor_undo_redo_and_external_change_conflicts_are_explicit() {
2097        let root = fixture();
2098        let mut project = ProjectWorkspace::open(&root).unwrap();
2099        project.open_buffer("src/main.rs", Actor::local()).unwrap();
2100        project
2101            .edit_buffer("src/main.rs", "one".into(), Actor::local())
2102            .unwrap();
2103        project
2104            .edit_buffer("src/main.rs", "two".into(), Actor::local())
2105            .unwrap();
2106        assert_eq!(project.undo_buffer("src/main.rs").unwrap().content, "one");
2107        assert_eq!(project.redo_buffer("src/main.rs").unwrap().content, "two");
2108        fs::write(root.join("src/main.rs"), "external").unwrap();
2109        assert!(matches!(
2110            project.save_buffer("src/main.rs"),
2111            Err(DevelopmentError::Conflict(_))
2112        ));
2113        let _ = fs::remove_dir_all(root);
2114    }
2115
2116    #[test]
2117    fn editor_selection_replacement_is_atomic_and_unicode_safe() {
2118        let root = fixture();
2119        let mut project = ProjectWorkspace::open(&root).unwrap();
2120        project.open_buffer("src/main.rs", Actor::local()).unwrap();
2121        project
2122            .edit_buffer("src/main.rs", "αlpha\nβeta\n".into(), Actor::local())
2123            .unwrap();
2124        project
2125            .set_buffer_selection(
2126                "src/main.rs",
2127                Some(crate::development::TextSelection {
2128                    anchor: crate::development::TextPosition { line: 1, column: 2 },
2129                    active: crate::development::TextPosition { line: 2, column: 3 },
2130                }),
2131                Actor::local(),
2132            )
2133            .unwrap();
2134        assert_eq!(
2135            project
2136                .selected_editor_text("src/main.rs")
2137                .unwrap()
2138                .as_deref(),
2139            Some("lpha\nβe")
2140        );
2141        let buffer = project
2142            .replace_buffer_selection("src/main.rs", "X\nY".into(), Actor::local())
2143            .unwrap();
2144        assert_eq!(buffer.content, "αX\nYta\n");
2145        assert_eq!(buffer.cursor_line, 2);
2146        assert_eq!(buffer.cursor_column, 2);
2147        assert!(buffer.selection.is_none());
2148        assert!(matches!(
2149            project.set_buffer_selection(
2150                "src/main.rs",
2151                Some(crate::development::TextSelection {
2152                    anchor: crate::development::TextPosition { line: 9, column: 1 },
2153                    active: crate::development::TextPosition { line: 9, column: 1 },
2154                }),
2155                Actor::local(),
2156            ),
2157            Err(DevelopmentError::InvalidInput(_))
2158        ));
2159        let _ = fs::remove_dir_all(root);
2160    }
2161
2162    #[test]
2163    fn file_operations_support_nested_create_rename_and_safe_delete() {
2164        let root = fixture();
2165        let mut project = ProjectWorkspace::open(&root).unwrap();
2166        project
2167            .edit_buffer("nested/new.txt", "hello".into(), Actor::local())
2168            .unwrap();
2169        project.save_buffer("nested/new.txt").unwrap();
2170        project
2171            .rename_path("nested/new.txt", "nested/renamed.txt", Actor::local())
2172            .unwrap();
2173        assert!(root.join("nested/renamed.txt").is_file());
2174        project
2175            .delete_path("nested/renamed.txt", Actor::local())
2176            .unwrap();
2177        project.delete_path("nested", Actor::local()).unwrap();
2178        assert!(!root.join("nested").exists());
2179        let _ = fs::remove_dir_all(root);
2180    }
2181
2182    #[test]
2183    fn project_tree_reports_ignore_and_symlink_semantics() {
2184        let root = fixture();
2185        fs::create_dir_all(root.join("target/debug")).unwrap();
2186        fs::write(root.join("target/debug/ignored"), "ignored").unwrap();
2187        #[cfg(unix)]
2188        std::os::unix::fs::symlink(root.join("src/main.rs"), root.join("linked.rs")).unwrap();
2189        let project = ProjectWorkspace::open(&root).unwrap();
2190        let tree = project.list_files_result().unwrap();
2191        assert_eq!(tree.limit, MAX_FILE_ENTRIES);
2192        assert!(tree.ignored_directories.contains(&"target".to_string()));
2193        assert!(
2194            !tree
2195                .entries
2196                .iter()
2197                .any(|entry| entry.path.contains("ignored"))
2198        );
2199        #[cfg(unix)]
2200        assert_eq!(tree.skipped_symlinks, 1);
2201        let _ = fs::remove_dir_all(root);
2202    }
2203
2204    #[test]
2205    fn editor_comments_replay_and_proposals_require_approval() {
2206        let root = fixture();
2207        let mut project = ProjectWorkspace::open(&root).unwrap();
2208        project.open_buffer("src/main.rs", Actor::local()).unwrap();
2209        let comment = project
2210            .add_editor_comment(
2211                "src/main.rs",
2212                1,
2213                1,
2214                "Prefer an explicit return here".into(),
2215                Actor::local(),
2216            )
2217            .unwrap();
2218        assert_eq!(project.editor_comments(None).len(), 1);
2219        assert_eq!(project.editor_proposals().len(), 0);
2220        let proposal = project
2221            .propose_editor_change(
2222                "src/main.rs",
2223                "fn main() {}\n".into(),
2224                "fn main() { println!(\"ok\"); }\n".into(),
2225                "Add observable output".into(),
2226                Actor::local(),
2227            )
2228            .unwrap();
2229        assert_eq!(
2230            project.buffer("src/main.rs").unwrap().content,
2231            "fn main() {}\n"
2232        );
2233        project
2234            .accept_editor_proposal(&proposal.id, Actor::local())
2235            .unwrap();
2236        assert_eq!(
2237            project.buffer("src/main.rs").unwrap().content,
2238            "fn main() { println!(\"ok\"); }\n"
2239        );
2240        let second = project
2241            .propose_editor_change(
2242                "src/main.rs",
2243                "fn main() { println!(\"ok\"); }\n".into(),
2244                "fn main() { println!(\"pair\"); }\n".into(),
2245                "Pair-apply already in buffer".into(),
2246                Actor::local(),
2247            )
2248            .unwrap();
2249        project
2250            .edit_buffer(
2251                "src/main.rs",
2252                "fn main() { println!(\"pair\"); }\n".into(),
2253                Actor::local(),
2254            )
2255            .unwrap();
2256        project
2257            .accept_editor_proposal(&second.id, Actor::local())
2258            .unwrap();
2259        assert_eq!(
2260            project
2261                .editor_proposals()
2262                .into_iter()
2263                .find(|item| item.id == second.id)
2264                .unwrap()
2265                .state,
2266            crate::development::EditorProposalState::Accepted
2267        );
2268        let resolved = project
2269            .resolve_editor_comment(&comment.id, Actor::local())
2270            .unwrap();
2271        let revision = project.revision();
2272        assert_eq!(
2273            project
2274                .resolve_editor_comment(&comment.id, Actor::local())
2275                .unwrap(),
2276            resolved
2277        );
2278        assert_eq!(project.revision(), revision);
2279        drop(project);
2280
2281        let reopened = ProjectWorkspace::open(&root).unwrap();
2282        let comments = reopened.editor_comments(Some("src/main.rs"));
2283        assert_eq!(comments.len(), 1);
2284        assert_eq!(
2285            comments[0].state,
2286            crate::development::EditorCommentState::Resolved
2287        );
2288        let _ = fs::remove_dir_all(root);
2289    }
2290
2291    #[test]
2292    fn editor_proposals_become_stale_on_buffer_conflict() {
2293        let root = fixture();
2294        let mut project = ProjectWorkspace::open(&root).unwrap();
2295        project.open_buffer("src/main.rs", Actor::local()).unwrap();
2296        let proposal = project
2297            .propose_editor_change(
2298                "src/main.rs",
2299                "fn main() {}\n".into(),
2300                "fn main() { println!(\"proposal\"); }\n".into(),
2301                "Add output".into(),
2302                Actor::local(),
2303            )
2304            .unwrap();
2305        project
2306            .edit_buffer(
2307                "src/main.rs",
2308                "fn main() { println!(\"human\"); }\n".into(),
2309                Actor::local(),
2310            )
2311            .unwrap();
2312        assert!(matches!(
2313            project.accept_editor_proposal(&proposal.id, Actor::local()),
2314            Err(DevelopmentError::Conflict(_))
2315        ));
2316        assert_eq!(
2317            project.editor_proposals()[0].state,
2318            crate::development::EditorProposalState::Stale
2319        );
2320        let _ = fs::remove_dir_all(root);
2321    }
2322
2323    #[test]
2324    fn accept_pending_editor_proposals_applies_the_pack() {
2325        let root = fixture();
2326        fs::write(root.join("src/lib.rs"), "pub fn old() {}\n").unwrap();
2327        let mut project = ProjectWorkspace::open(&root).unwrap();
2328        project.open_buffer("src/main.rs", Actor::local()).unwrap();
2329        project.open_buffer("src/lib.rs", Actor::local()).unwrap();
2330        project
2331            .propose_editor_change(
2332                "src/main.rs",
2333                "fn main() {}\n".into(),
2334                "fn main() { println!(\"one\"); }\n".into(),
2335                "first".into(),
2336                Actor::local(),
2337            )
2338            .unwrap();
2339        project
2340            .propose_editor_change(
2341                "src/lib.rs",
2342                "pub fn old() {}\n".into(),
2343                "pub fn next() {}\n".into(),
2344                "second".into(),
2345                Actor::local(),
2346            )
2347            .unwrap();
2348        let buffers = project
2349            .accept_pending_editor_proposals(Actor::local())
2350            .unwrap();
2351        assert_eq!(buffers.len(), 2);
2352        assert_eq!(
2353            project.buffer("src/main.rs").unwrap().content,
2354            "fn main() { println!(\"one\"); }\n"
2355        );
2356        assert_eq!(
2357            project.buffer("src/lib.rs").unwrap().content,
2358            "pub fn next() {}\n"
2359        );
2360        assert!(
2361            project
2362                .editor_proposals()
2363                .iter()
2364                .all(|proposal| proposal.state == crate::development::EditorProposalState::Accepted)
2365        );
2366        assert!(matches!(
2367            project.accept_pending_editor_proposals(Actor::local()),
2368            Err(DevelopmentError::NotFound(_))
2369        ));
2370        let _ = fs::remove_dir_all(root);
2371    }
2372
2373    #[test]
2374    fn editor_checkpoints_restore_unsaved_buffers_and_survive_reopen() {
2375        let root = fixture();
2376        let mut project = ProjectWorkspace::open(&root).unwrap();
2377        project
2378            .edit_buffer("src/main.rs", "one\n".into(), Actor::local())
2379            .unwrap();
2380        let checkpoint = project
2381            .create_editor_checkpoint("before experiment".into(), Actor::local())
2382            .unwrap();
2383        project
2384            .edit_buffer("src/main.rs", "two\n".into(), Actor::local())
2385            .unwrap();
2386        project
2387            .restore_editor_checkpoint(&checkpoint.id, Actor::local())
2388            .unwrap();
2389        assert_eq!(project.buffer("src/main.rs").unwrap().content, "one\n");
2390        drop(project);
2391
2392        let reopened = ProjectWorkspace::open(&root).unwrap();
2393        assert_eq!(reopened.editor_checkpoints().len(), 1);
2394        let _ = fs::remove_dir_all(root);
2395    }
2396}