Skip to main content

glass_dev/
cli.rs

1//! Glass Dev-owned project CLI dispatch.
2
3use crate::development::{
4    Actor, ExperimentManager, HarnessRequest, LinkProvenance, LocalHarness, PiHarness,
5    ProcessSnapshot, ProjectWorkspace, SemanticBreakpoint, SemanticSnapshot,
6};
7use glass_browser::cli::args::{
8    AgentCommand, AgentHarness, ExperimentCommand, NeovimCommand, ProjectCommand,
9    ProjectGraphCommand, ProjectProcessCommand,
10};
11use serde::Serialize;
12use std::time::Duration;
13
14type CliResult<T> = Result<T, Box<dyn std::error::Error>>;
15
16pub fn dispatch_agent(action: &AgentCommand, unrestricted: bool) -> CliResult<()> {
17    match action {
18        AgentCommand::Doctor | AgentCommand::Status => {
19            return print_json(&crate::pi_runtime::pi_readiness()?);
20        }
21        AgentCommand::Setup {
22            sdk_entry,
23            agent_dir,
24            update,
25            login,
26        } => {
27            return print_json(&crate::pi_runtime::setup_pi_runtime(
28                sdk_entry.as_deref(),
29                agent_dir.as_deref(),
30                *update,
31                *login,
32            )?);
33        }
34        _ => {}
35    }
36    let (root, request, adapter) = match action {
37        AgentCommand::Tool { .. } | AgentCommand::ToolFile { .. } => {
38            return Err("agent tool calls use the resident broker path".into());
39        }
40        AgentCommand::Hello { root, harness } => (root, HarnessRequest::Hello, *harness),
41        AgentCommand::Prompt {
42            root,
43            text,
44            harness,
45        } => (
46            root,
47            HarnessRequest::Prompt { text: text.clone() },
48            *harness,
49        ),
50        AgentCommand::Steer {
51            root,
52            text,
53            harness,
54        } => (root, HarnessRequest::Steer { text: text.clone() }, *harness),
55        AgentCommand::FollowUp { root, text } => (
56            root,
57            HarnessRequest::FollowUp { text: text.clone() },
58            AgentHarness::Pi,
59        ),
60        AgentCommand::Models { root } => (root, HarnessRequest::Models, AgentHarness::Pi),
61        AgentCommand::SetModel {
62            root,
63            provider,
64            model_id,
65        } => (
66            root,
67            HarnessRequest::SetModel {
68                provider: provider.clone(),
69                model_id: model_id.clone(),
70            },
71            AgentHarness::Pi,
72        ),
73        AgentCommand::Thinking { root, level } => (
74            root,
75            HarnessRequest::SetThinking {
76                level: level.clone(),
77            },
78            AgentHarness::Pi,
79        ),
80        AgentCommand::Abort { root } => (root, HarnessRequest::Abort, AgentHarness::Pi),
81        AgentCommand::NewSession { root } => (root, HarnessRequest::NewSession, AgentHarness::Pi),
82        AgentCommand::Doctor | AgentCommand::Setup { .. } | AgentCommand::Status => {
83            unreachable!("readiness commands return before harness dispatch")
84        }
85    };
86    let mut workspace = ProjectWorkspace::open(root)?;
87    match adapter {
88        AgentHarness::Local => {
89            let mut harness = LocalHarness::default();
90            print_json(&harness.handle(&mut workspace, request)?)?;
91        }
92        AgentHarness::Pi => {
93            let mut harness = PiHarness::spawn_with_unrestricted(workspace.root(), unrestricted)?;
94            print_json(&harness.request(request)?)?;
95        }
96    }
97    Ok(())
98}
99
100pub fn dispatch_project(action: &ProjectCommand) -> CliResult<()> {
101    match action {
102        ProjectCommand::Inspect { root } => {
103            let workspace = ProjectWorkspace::open(root)?;
104            print_json(&serde_json::json!({
105                "schemaVersion": crate::development::DEVELOPMENT_SCHEMA_VERSION,
106                "root": workspace.root(),
107                "detection": workspace.detection(),
108                "config": workspace.config(),
109                "revision": workspace.revision(),
110            }))?;
111        }
112        ProjectCommand::Files { root } => {
113            let workspace = ProjectWorkspace::open(root)?;
114            print_json(&workspace.list_files_result()?)?;
115        }
116        ProjectCommand::Search { root, query, limit } => {
117            let mut workspace = ProjectWorkspace::open(root)?;
118            print_json(&workspace.search(query, *limit)?)?;
119        }
120        ProjectCommand::Read { root, path } => {
121            let mut workspace = ProjectWorkspace::open(root)?;
122            let content = workspace.read_file(path)?;
123            print_json(&serde_json::json!({"path": path, "content": content}))?;
124        }
125        ProjectCommand::Edit {
126            root,
127            path,
128            content,
129            input,
130        } => {
131            let content = match (content, input) {
132                (Some(content), None) => content.clone(),
133                (None, Some(input)) => std::fs::read_to_string(input)?,
134                (None, None) => {
135                    return Err("project edit requires --content or --input".into());
136                }
137                (Some(_), Some(_)) => unreachable!("clap prevents conflicting edit inputs"),
138            };
139            let mut workspace = ProjectWorkspace::open(root)?;
140            workspace.edit_buffer(path, content, Actor::local())?;
141            print_json(&workspace.save_buffer(path)?)?;
142        }
143        ProjectCommand::Mkdir { root, path } => {
144            let mut workspace = ProjectWorkspace::open(root)?;
145            workspace.create_directory(path, Actor::local())?;
146            print_json(&serde_json::json!({"path": path, "created": true}))?;
147        }
148        ProjectCommand::Rename { root, from, to } => {
149            let mut workspace = ProjectWorkspace::open(root)?;
150            workspace.rename_path(from, to, Actor::local())?;
151            print_json(&serde_json::json!({"from": from, "to": to, "renamed": true}))?;
152        }
153        ProjectCommand::Delete { root, path, yes } => {
154            if !yes {
155                return Err("project delete requires --yes confirmation".into());
156            }
157            let mut workspace = ProjectWorkspace::open(root)?;
158            workspace.delete_path(path, Actor::local())?;
159            print_json(&serde_json::json!({"path": path, "deleted": true}))?;
160        }
161        ProjectCommand::Diagnostics { root, path } => {
162            let mut workspace = ProjectWorkspace::open(root)?;
163            print_json(&workspace.publish_rust_diagnostics(path)?)?;
164        }
165        ProjectCommand::Run {
166            root,
167            name,
168            command,
169            wait,
170        } => {
171            if !wait {
172                return Err("one-shot CLI process runs require --wait; use the TUI for persistent interactive processes".into());
173            }
174            let mut workspace = ProjectWorkspace::open(root)?;
175            let command = command
176                .clone()
177                .or_else(|| detected_command(workspace.detection(), name))
178                .ok_or_else(|| format!("no configured command for process {name}"))?;
179            #[cfg(windows)]
180            let snapshot = workspace.run_command_to_completion(
181                name,
182                &command,
183                std::time::Duration::from_secs(600),
184            )?;
185            #[cfg(not(windows))]
186            let snapshot = {
187                let snapshot = workspace.start_process(name, &command)?;
188                if *wait {
189                    workspace.processes().close_input(name)?;
190                    wait_for_project_process(&mut workspace, name)?
191                } else {
192                    snapshot
193                }
194            };
195            print_json(&snapshot)?;
196        }
197        ProjectCommand::Test { root } => {
198            run_detected_command(root, "test", workspace_test_command)?;
199        }
200        ProjectCommand::Lint { root } => {
201            run_detected_command(root, "lint", workspace_lint_command)?;
202        }
203        ProjectCommand::Process { root, action } => {
204            let mut workspace = ProjectWorkspace::open(root)?;
205            match action {
206                ProjectProcessCommand::List => print_json(&workspace.processes().list_checked()?)?,
207                ProjectProcessCommand::Start {
208                    name,
209                    command,
210                    wait,
211                } => {
212                    if !wait {
213                        return Err("one-shot CLI process starts require --wait; use the TUI for persistent interactive processes".into());
214                    }
215                    #[cfg(windows)]
216                    let snapshot = workspace.run_command_to_completion(
217                        name,
218                        command,
219                        std::time::Duration::from_secs(600),
220                    )?;
221                    #[cfg(not(windows))]
222                    let snapshot = {
223                        workspace.start_process(name, command)?;
224                        if *wait {
225                            workspace.processes().close_input(name)?;
226                            wait_for_project_process(&mut workspace, name)?
227                        } else {
228                            workspace
229                                .processes()
230                                .list()
231                                .into_iter()
232                                .find(|process| process.name == *name)
233                                .ok_or_else(|| format!("process {name} disappeared"))?
234                        }
235                    };
236                    print_json(&snapshot)?;
237                }
238                ProjectProcessCommand::Stop { name } => {
239                    print_json(&workspace.stop_process(name)?)?;
240                }
241                ProjectProcessCommand::Restart { name } => {
242                    print_json(&workspace.processes().restart(name)?)?;
243                }
244                ProjectProcessCommand::Remove { name } => {
245                    print_json(&workspace.processes().remove(name)?)?;
246                }
247                ProjectProcessCommand::Input { name, input } => {
248                    workspace.processes().send_input(name, input)?;
249                    print_json(&serde_json::json!({"name": name, "accepted": true}))?;
250                }
251                ProjectProcessCommand::Resize { name, cols, rows } => {
252                    workspace.processes().resize(name, *cols, *rows)?;
253                    print_json(&serde_json::json!({"name": name, "cols": cols, "rows": rows}))?;
254                }
255                ProjectProcessCommand::Output { name } => {
256                    print_json(&serde_json::json!({
257                        "name": name,
258                        "output": workspace.processes().output(name)?,
259                    }))?;
260                }
261            }
262        }
263        ProjectCommand::Diff { root } => {
264            let mut workspace = ProjectWorkspace::open(root)?;
265            print_json(&workspace.diff()?)?;
266        }
267        ProjectCommand::Link {
268            root,
269            entity,
270            path,
271            start_line,
272            end_line,
273            provenance,
274            confidence,
275            detail,
276        } => {
277            let mut workspace = ProjectWorkspace::open(root)?;
278            let provenance = parse_link_provenance(provenance)?;
279            let link = workspace.link_runtime_source(
280                entity,
281                path,
282                *start_line,
283                *end_line,
284                provenance,
285                detail,
286                *confidence,
287                Actor::local(),
288            )?;
289            print_json(&link)?;
290        }
291        ProjectCommand::Timeline { root } => {
292            let workspace = ProjectWorkspace::open(root)?;
293            print_json(&workspace.timeline().events().collect::<Vec<_>>())?;
294        }
295        ProjectCommand::Graph { root, action } => {
296            let mut workspace = ProjectWorkspace::open(root)?;
297            match action {
298                ProjectGraphCommand::Discover => print_json(&workspace.discover_runtime_links()?)?,
299                ProjectGraphCommand::Entity { entity } => {
300                    print_json(&workspace.graph().links_for(entity))?
301                }
302                ProjectGraphCommand::Source { path, line } => {
303                    print_json(&workspace.graph().entities_for_source(path, *line))?
304                }
305            }
306        }
307        ProjectCommand::Breakpoint {
308            root,
309            kind,
310            entity,
311            before,
312            after,
313        } => {
314            let mut workspace = ProjectWorkspace::open(root)?;
315            workspace.discover_runtime_links()?;
316            let before: SemanticSnapshot = serde_json::from_slice(&std::fs::read(before)?)?;
317            let after: SemanticSnapshot = serde_json::from_slice(&std::fs::read(after)?)?;
318            let breakpoint = match kind.as_str() {
319                "disappears" => SemanticBreakpoint::EntityDisappears { entity_id: entity.clone() },
320                "name-missing" => SemanticBreakpoint::AccessibleNameMissing { entity_id: Some(entity.clone()) },
321                "role-changes" => SemanticBreakpoint::RoleChanges { entity_id: entity.clone() },
322                "actionability-lost" => SemanticBreakpoint::ActionabilityLost { entity_id: entity.clone() },
323                _ => return Err("breakpoint kind must be disappears, name-missing, role-changes, or actionability-lost".into()),
324            };
325            print_json(&workspace.evaluate_semantic_breakpoints(
326                &[breakpoint],
327                &before,
328                &after,
329            )?)?;
330        }
331        ProjectCommand::Replay { root, start, limit } => {
332            let workspace = ProjectWorkspace::open(root)?;
333            print_json(&workspace.replay(*start, *limit)?)?;
334        }
335        ProjectCommand::Neovim { root, action } => {
336            let mut workspace = ProjectWorkspace::open(root)?;
337            match action {
338                NeovimCommand::Probe => print_json(&crate::development::probe_neovim()?)?,
339                NeovimCommand::Start { name, path } => {
340                    print_json(&crate::development::start_neovim(
341                        workspace.processes(),
342                        name,
343                        path.as_deref(),
344                    )?)?
345                }
346            }
347        }
348        ProjectCommand::Experiment { root, action } => {
349            let manager = ExperimentManager::new(root)?;
350            match action {
351                ExperimentCommand::Create { name, port } => {
352                    print_json(&manager.create(name, *port)?)?
353                }
354            }
355        }
356        ProjectCommand::Attach { root, actor } => {
357            let mut workspace = ProjectWorkspace::open(root)?;
358            let actor = Actor::external(actor);
359            workspace.attach_actor(actor.clone())?;
360            print_json(&actor)?;
361        }
362    }
363    Ok(())
364}
365
366fn detected_command(
367    detection: &crate::development::ProjectDetection,
368    name: &str,
369) -> Option<String> {
370    match name {
371        "dev" => detection.dev_command.clone(),
372        "test" => detection.test_command.clone(),
373        "lint" => detection.lint_command.clone(),
374        "build" => detection.build_command.clone(),
375        _ => None,
376    }
377}
378
379fn workspace_test_command(detection: &crate::development::ProjectDetection) -> Option<String> {
380    detection.test_command.clone()
381}
382
383fn workspace_lint_command(detection: &crate::development::ProjectDetection) -> Option<String> {
384    detection.lint_command.clone()
385}
386
387fn run_detected_command(
388    root: &std::path::Path,
389    name: &str,
390    command: fn(&crate::development::ProjectDetection) -> Option<String>,
391) -> CliResult<()> {
392    let mut workspace = ProjectWorkspace::open(root)?;
393    let command = command(workspace.detection())
394        .ok_or_else(|| format!("project has no detected {name} command"))?;
395    print_json(&workspace.run_verification(name, &command, Duration::from_secs(600))?)?;
396    Ok(())
397}
398
399fn wait_for_project_process(
400    workspace: &mut ProjectWorkspace,
401    name: &str,
402) -> CliResult<ProcessSnapshot> {
403    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(600);
404    loop {
405        let snapshots = workspace.processes().poll()?;
406        let snapshot = snapshots
407            .into_iter()
408            .find(|process| process.name == name)
409            .ok_or_else(|| format!("process {name} disappeared"))?;
410        if !matches!(snapshot.state, crate::development::ProcessState::Running) {
411            return Ok(snapshot);
412        }
413        if std::time::Instant::now() >= deadline {
414            workspace.stop_process(name)?;
415            return Err(format!("process {name} exceeded 600 seconds").into());
416        }
417        std::thread::sleep(std::time::Duration::from_millis(20));
418    }
419}
420
421fn parse_link_provenance(value: &str) -> CliResult<LinkProvenance> {
422    match value {
423        "explicit-marker" => Ok(LinkProvenance::ExplicitMarker),
424        "runtime-observation" => Ok(LinkProvenance::RuntimeObservation),
425        "static-analysis" => Ok(LinkProvenance::StaticAnalysis),
426        "inferred" => Ok(LinkProvenance::Inferred),
427        _ => Err(
428            "provenance must be explicit-marker, runtime-observation, static-analysis, or inferred"
429                .into(),
430        ),
431    }
432}
433
434fn print_json<T: Serialize + ?Sized>(value: &T) -> CliResult<()> {
435    println!("{}", serde_json::to_string_pretty(value)?);
436    Ok(())
437}