Skip to main content

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