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
18/// Resident agent and harness tool contracts.
19pub mod agent;
20/// Development cockpit and attention projections.
21pub mod cockpit;
22/// Collaboration bus and edit claims.
23pub mod collaboration;
24/// Semantic debugging and breakpoint evaluation.
25pub mod debug;
26/// Project diff construction and summaries.
27pub mod diff;
28/// Low-level bounded editor helpers; the TUI renderer is private and separate.
29pub mod editor;
30/// Durable actor-attributed development events.
31pub mod events;
32/// Experiment workspace and evidence support.
33pub mod experiment;
34/// Source/runtime development graph contracts.
35pub mod graph;
36/// Language documents, diagnostics, and LSP clients.
37pub mod language;
38/// Neovim capability probing and startup.
39pub mod neovim;
40/// Bounded process management and snapshots.
41pub mod process;
42/// Project files, commands, configuration, and detection.
43pub mod project;
44/// Remote-view state and input/frame types.
45pub mod remote_view;
46/// Revision identifiers and bounded replay.
47pub mod replay;
48/// Search hit types and ranking helpers.
49pub mod search;
50
51/// Agent authority, harness handoff, and tool registry contracts.
52pub use agent::{
53    AgentAuthorityContext, AgentContextPacket, AgentToolGateway, BrowserAgentContext, HarnessEvent,
54    HarnessRequest, LocalHarness, PiHarness, PiHarnessOptions, ToolAuthorization, ToolCall,
55    ToolDescriptor, ToolRegistry, resolve_context, resolve_context_with_browser,
56};
57/// Cockpit attention, verification, and reconnect projections.
58pub use cockpit::{
59    AttentionItem, AttentionState, LocalCockpit, ReconnectCapsule, ReconnectCapsuleStore,
60    ResidentDevelopmentSessions, VerificationCard, VerificationCheck, attention_inbox,
61};
62/// Collaboration events and edit-access claims.
63pub use collaboration::{CollaborationBus, CollaborationEvent, EditAccess, EditClaim};
64/// Semantic breakpoint and snapshot types.
65pub use debug::{
66    SemanticBreakpoint, SemanticBreakpointHit, SemanticEntityState, SemanticSnapshot,
67    evaluate_breakpoints,
68};
69/// Project diff model and builder.
70pub use diff::{ProjectDiff, build_diff};
71/// Low-level editor positions, syntax spans, folds, and matching helpers.
72pub use editor::{
73    EditorCheckpoint, EditorComment, EditorCommentState, EditorProposal, EditorProposalState,
74    FoldRegion, SyntaxKind, SyntaxSpan, TextPosition, TextSelection, fold_regions,
75    matching_bracket, syntax_spans,
76};
77/// Actor, authority, timeline, and serialized development events.
78pub use events::{
79    Actor, ActorAuthority, ActorConnection, ActorKind, DevelopmentEvent, DevelopmentEventKind,
80    DevelopmentEventPage, Timeline,
81};
82/// Experiment comparison, evidence, and workspace management.
83pub use experiment::{
84    ExperimentComparison, ExperimentEvidence, ExperimentManager, ExperimentWorkspace,
85};
86/// Development graph nodes, links, provenance, and source locations.
87pub use graph::{DevelopmentGraph, LinkEvidence, LinkProvenance, RuntimeLink, SourceLocation};
88/// Language documents, diagnostics, responses, and client.
89pub use language::{
90    DiagnosticPosition, LanguageDiagnostic, LanguageDocument, LanguageResponse, LspClient,
91};
92/// Neovim capability probe and startup helpers.
93pub use neovim::{NeovimCapability, probe_neovim, start_neovim};
94/// Process health, state, and bounded snapshots.
95pub use process::{ProcessHealth, ProcessManager, ProcessSnapshot, ProcessState};
96/// Project files, commands, configuration, and detection.
97pub use project::{
98    CommandConfig, EditorBuffer, FileEntry, FileKind, GlassProjectConfig, ProjectDetection,
99    ProjectTreeResult, ProjectWorkspace, detect_project,
100};
101/// Remote-view state and input/frame types.
102pub use remote_view::{RemoteFrame, RemoteInput, RemoteView};
103/// Revision identifiers and bounded replay.
104pub use replay::{DevelopmentRevision, ReplayWindow, replay};
105/// Search hit types and ranking helpers.
106pub use search::{SearchHit, SearchKind, fuzzy_score, rank};
107use std::{
108    fmt,
109    fs::OpenOptions,
110    io::{self, Read},
111    path::{Path, PathBuf},
112};
113
114/// Version identifier for the top-level development payload schema.
115pub const DEVELOPMENT_SCHEMA_VERSION: &str = "glass.development.v1";
116/// Version of serialized development timeline events.
117pub const DEVELOPMENT_EVENT_SCHEMA_VERSION: u32 = 1;
118/// Version of serialized cockpit snapshots.
119pub const DEVELOPMENT_COCKPIT_SCHEMA_VERSION: u32 = 2;
120/// Maximum bytes read from one project file.
121pub const MAX_FILE_BYTES: usize = 512 * 1024;
122/// Maximum bytes retained in an editor or process buffer.
123pub const MAX_BUFFER_BYTES: usize = 1024 * 1024;
124/// Maximum entries returned by bounded project-tree scans.
125pub const MAX_FILE_ENTRIES: usize = 2_048;
126/// Maximum retained timeline events.
127pub const MAX_TIMELINE_EVENTS: usize = 512;
128/// Maximum retained process output bytes.
129pub const MAX_PROCESS_OUTPUT_BYTES: usize = 32 * 1024;
130
131pub(crate) fn read_bounded_utf8(
132    path: &Path,
133    limit: usize,
134    description: &str,
135) -> DevelopmentResult<String> {
136    let mut options = OpenOptions::new();
137    options.read(true);
138    #[cfg(unix)]
139    {
140        use std::os::unix::fs::OpenOptionsExt;
141        options.custom_flags(libc::O_NOFOLLOW);
142    }
143    let file = options.open(path)?;
144    let metadata = file.metadata()?;
145    if !metadata.is_file() {
146        return Err(DevelopmentError::InvalidInput(format!(
147            "{description} is not a regular file"
148        )));
149    }
150    if metadata.len() > limit as u64 {
151        return Err(DevelopmentError::InvalidInput(format!(
152            "{description} exceeds the {limit} byte limit"
153        )));
154    }
155    let mut bytes = Vec::with_capacity(metadata.len().min(limit as u64) as usize);
156    file.take(limit as u64 + 1).read_to_end(&mut bytes)?;
157    if bytes.len() > limit {
158        return Err(DevelopmentError::InvalidInput(format!(
159            "{description} exceeds the {limit} byte limit"
160        )));
161    }
162    String::from_utf8(bytes)
163        .map_err(|_| DevelopmentError::InvalidInput(format!("{description} is not valid UTF-8")))
164}
165
166/// Result type returned by development services and bounded helpers.
167pub type DevelopmentResult<T> = Result<T, DevelopmentError>;
168
169/// Errors produced while resolving, reading, or executing development work.
170#[derive(Debug)]
171pub enum DevelopmentError {
172    /// Filesystem or operating-system I/O failure.
173    Io(io::Error),
174    /// Caller input violates a documented bound or format.
175    InvalidInput(String),
176    /// A path resolves outside the canonical project workspace.
177    PathOutsideWorkspace(PathBuf),
178    /// A requested project resource does not exist.
179    NotFound(String),
180    /// Project configuration is invalid or cannot be loaded.
181    Config(String),
182    /// The requested operation conflicts with current runtime state.
183    Conflict(String),
184    /// A managed process or subprocess failed.
185    Process(String),
186    /// Serialization or deserialization failed.
187    Serialization(String),
188}
189
190impl fmt::Display for DevelopmentError {
191    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
192        match self {
193            Self::Io(error) => write!(formatter, "development I/O error: {error}"),
194            Self::InvalidInput(message) => {
195                write!(formatter, "invalid development input: {message}")
196            }
197            Self::PathOutsideWorkspace(path) => write!(
198                formatter,
199                "path escapes the project workspace: {}",
200                path.display()
201            ),
202            Self::NotFound(value) => write!(formatter, "development resource not found: {value}"),
203            Self::Config(message) => write!(formatter, "invalid glass.toml: {message}"),
204            Self::Conflict(message) => write!(formatter, "development conflict: {message}"),
205            Self::Process(message) => write!(formatter, "development process error: {message}"),
206            Self::Serialization(message) => {
207                write!(formatter, "development serialization error: {message}")
208            }
209        }
210    }
211}
212
213impl std::error::Error for DevelopmentError {}
214
215impl From<io::Error> for DevelopmentError {
216    fn from(error: io::Error) -> Self {
217        Self::Io(error)
218    }
219}
220
221impl From<serde_json::Error> for DevelopmentError {
222    fn from(error: serde_json::Error) -> Self {
223        Self::Serialization(error.to_string())
224    }
225}
226
227#[cfg(test)]
228mod tests {
229    use super::*;
230
231    #[test]
232    fn bounded_utf8_reader_rejects_oversized_and_invalid_files() {
233        let root =
234            std::env::temp_dir().join(format!("glass-bounded-reader-{}", std::process::id()));
235        let _ = std::fs::remove_dir_all(&root);
236        std::fs::create_dir_all(&root).unwrap();
237        let path = root.join("input");
238
239        std::fs::write(&path, b"bounded").unwrap();
240        assert_eq!(read_bounded_utf8(&path, 7, "fixture").unwrap(), "bounded");
241        std::fs::write(&path, b"oversized").unwrap();
242        assert!(read_bounded_utf8(&path, 8, "fixture").is_err());
243        std::fs::write(&path, [0xff]).unwrap();
244        assert!(read_bounded_utf8(&path, 1, "fixture").is_err());
245        #[cfg(unix)]
246        {
247            use std::os::unix::fs::symlink;
248            let target = root.join("target");
249            let link = root.join("link");
250            std::fs::write(&target, b"bounded").unwrap();
251            symlink(&target, &link).unwrap();
252            assert!(read_bounded_utf8(&link, 7, "fixture").is_err());
253        }
254
255        let _ = std::fs::remove_dir_all(root);
256    }
257}