Skip to main content

glass_dev/development/
mod.rs

1//! Terminal-native project development runtime.
2//!
3//! This module owns the local development contracts used by the CLI, MCP, TUI,
4//! and embedded harness. Browser authority remains in the existing browser
5//! runtime: project state can coordinate a live application without duplicating
6//! browser control logic.
7//!
8//! Glass Dev directly owns the concrete project, editor, PTY, language-server,
9//! graph, replay, Neovim, experiment, and agent contracts. There is no browser
10//! feature bridge or disabled compatibility implementation.
11//!
12//! Project paths are resolved beneath one canonical root; reads, output tails,
13//! event logs, and retained buffers have hard bounds. Writes are atomic and
14//! actor-attributed. Runtime claims such as live-update provenance remain
15//! pending until explicit source/runtime evidence or browser revision evidence
16//! supports them. A project session never implies browser mutation authority.
17
18pub mod agent;
19pub mod cockpit;
20pub mod collaboration;
21pub mod debug;
22pub mod diff;
23pub mod editor;
24pub mod events;
25pub mod experiment;
26pub mod graph;
27pub mod language;
28pub mod neovim;
29pub mod process;
30pub mod project;
31pub mod remote_view;
32pub mod replay;
33pub mod search;
34
35use std::{
36    fmt,
37    fs::OpenOptions,
38    io::{self, Read},
39    path::{Path, PathBuf},
40};
41
42pub use agent::{
43    AgentAuthorityContext, AgentContextPacket, AgentToolGateway, BrowserAgentContext, HarnessEvent,
44    HarnessRequest, LocalHarness, PiHarness, PiHarnessOptions, ToolAuthorization, ToolCall,
45    ToolDescriptor, ToolRegistry, resolve_context, resolve_context_with_browser,
46};
47pub use cockpit::{
48    AttentionItem, AttentionState, ReconnectCapsule, ReconnectCapsuleStore,
49    ResidentDevelopmentSessions, VerificationCard, VerificationCheck, attention_inbox,
50};
51pub use collaboration::{CollaborationBus, CollaborationEvent, EditAccess, EditClaim};
52pub use debug::{
53    SemanticBreakpoint, SemanticBreakpointHit, SemanticEntityState, SemanticSnapshot,
54    evaluate_breakpoints,
55};
56pub use diff::{ProjectDiff, build_diff};
57pub use editor::{
58    FoldRegion, SyntaxKind, SyntaxSpan, TextPosition, TextSelection, fold_regions,
59    matching_bracket, syntax_spans,
60};
61pub use events::{
62    Actor, ActorAuthority, ActorConnection, ActorKind, DevelopmentEvent, DevelopmentEventKind,
63    DevelopmentEventPage, Timeline,
64};
65pub use experiment::{
66    ExperimentComparison, ExperimentEvidence, ExperimentManager, ExperimentWorkspace,
67};
68pub use graph::{DevelopmentGraph, LinkEvidence, LinkProvenance, RuntimeLink, SourceLocation};
69pub use language::{
70    DiagnosticPosition, LanguageDiagnostic, LanguageDocument, LanguageResponse, LspClient,
71};
72pub use neovim::{NeovimCapability, probe_neovim, start_neovim};
73pub use process::{ProcessHealth, ProcessManager, ProcessSnapshot, ProcessState};
74pub use project::{
75    CommandConfig, EditorBuffer, FileEntry, FileKind, GlassProjectConfig, ProjectDetection,
76    ProjectTreeResult, ProjectWorkspace, detect_project,
77};
78pub use remote_view::{RemoteFrame, RemoteInput, RemoteView};
79pub use replay::{DevelopmentRevision, ReplayWindow, replay};
80pub use search::{SearchHit, SearchKind, fuzzy_score, rank};
81
82pub const DEVELOPMENT_SCHEMA_VERSION: &str = "glass.development.v1";
83pub const DEVELOPMENT_EVENT_SCHEMA_VERSION: u32 = 1;
84pub const DEVELOPMENT_COCKPIT_SCHEMA_VERSION: u32 = 1;
85pub const MAX_FILE_BYTES: usize = 512 * 1024;
86pub const MAX_BUFFER_BYTES: usize = 1024 * 1024;
87pub const MAX_FILE_ENTRIES: usize = 2_048;
88pub const MAX_TIMELINE_EVENTS: usize = 512;
89pub const MAX_PROCESS_OUTPUT_BYTES: usize = 32 * 1024;
90
91pub(crate) fn read_bounded_utf8(
92    path: &Path,
93    limit: usize,
94    description: &str,
95) -> DevelopmentResult<String> {
96    let mut options = OpenOptions::new();
97    options.read(true);
98    #[cfg(unix)]
99    {
100        use std::os::unix::fs::OpenOptionsExt;
101        options.custom_flags(libc::O_NOFOLLOW);
102    }
103    let file = options.open(path)?;
104    let metadata = file.metadata()?;
105    if !metadata.is_file() {
106        return Err(DevelopmentError::InvalidInput(format!(
107            "{description} is not a regular file"
108        )));
109    }
110    if metadata.len() > limit as u64 {
111        return Err(DevelopmentError::InvalidInput(format!(
112            "{description} exceeds the {limit} byte limit"
113        )));
114    }
115    let mut bytes = Vec::with_capacity(metadata.len().min(limit as u64) as usize);
116    file.take(limit as u64 + 1).read_to_end(&mut bytes)?;
117    if bytes.len() > limit {
118        return Err(DevelopmentError::InvalidInput(format!(
119            "{description} exceeds the {limit} byte limit"
120        )));
121    }
122    String::from_utf8(bytes)
123        .map_err(|_| DevelopmentError::InvalidInput(format!("{description} is not valid UTF-8")))
124}
125
126pub type DevelopmentResult<T> = Result<T, DevelopmentError>;
127
128#[derive(Debug)]
129pub enum DevelopmentError {
130    Io(io::Error),
131    InvalidInput(String),
132    PathOutsideWorkspace(PathBuf),
133    NotFound(String),
134    Config(String),
135    Conflict(String),
136    Process(String),
137    Serialization(String),
138}
139
140impl fmt::Display for DevelopmentError {
141    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
142        match self {
143            Self::Io(error) => write!(formatter, "development I/O error: {error}"),
144            Self::InvalidInput(message) => {
145                write!(formatter, "invalid development input: {message}")
146            }
147            Self::PathOutsideWorkspace(path) => write!(
148                formatter,
149                "path escapes the project workspace: {}",
150                path.display()
151            ),
152            Self::NotFound(value) => write!(formatter, "development resource not found: {value}"),
153            Self::Config(message) => write!(formatter, "invalid glass.toml: {message}"),
154            Self::Conflict(message) => write!(formatter, "development conflict: {message}"),
155            Self::Process(message) => write!(formatter, "development process error: {message}"),
156            Self::Serialization(message) => {
157                write!(formatter, "development serialization error: {message}")
158            }
159        }
160    }
161}
162
163impl std::error::Error for DevelopmentError {}
164
165impl From<io::Error> for DevelopmentError {
166    fn from(error: io::Error) -> Self {
167        Self::Io(error)
168    }
169}
170
171impl From<serde_json::Error> for DevelopmentError {
172    fn from(error: serde_json::Error) -> Self {
173        Self::Serialization(error.to_string())
174    }
175}
176
177#[cfg(test)]
178mod tests {
179    use super::*;
180
181    #[test]
182    fn bounded_utf8_reader_rejects_oversized_and_invalid_files() {
183        let root =
184            std::env::temp_dir().join(format!("glass-bounded-reader-{}", std::process::id()));
185        let _ = std::fs::remove_dir_all(&root);
186        std::fs::create_dir_all(&root).unwrap();
187        let path = root.join("input");
188
189        std::fs::write(&path, b"bounded").unwrap();
190        assert_eq!(read_bounded_utf8(&path, 7, "fixture").unwrap(), "bounded");
191        std::fs::write(&path, b"oversized").unwrap();
192        assert!(read_bounded_utf8(&path, 8, "fixture").is_err());
193        std::fs::write(&path, [0xff]).unwrap();
194        assert!(read_bounded_utf8(&path, 1, "fixture").is_err());
195        #[cfg(unix)]
196        {
197            use std::os::unix::fs::symlink;
198            let target = root.join("target");
199            let link = root.join("link");
200            std::fs::write(&target, b"bounded").unwrap();
201            symlink(&target, &link).unwrap();
202            assert!(read_bounded_utf8(&link, 7, "fixture").is_err());
203        }
204
205        let _ = std::fs::remove_dir_all(root);
206    }
207}