Skip to main content

glass_browser/cli/
args.rs

1//! CLI argument definitions (clap).
2//!
3//! Defines the top-level `Cli` struct and all subcommands for one-shot
4//! browser operations, profile management, and server modes.
5
6use clap::{Parser, Subcommand, ValueEnum};
7use std::path::PathBuf;
8
9use crate::browser::policy::{PolicyCapability, PolicyPreset};
10use crate::browser::session::{
11    BatchMode, InteractionMode, PreflightAction, VisualClip, VisualFormat,
12};
13use crate::results::ResponseMode;
14/// Glass — semantic browser execution for humans and agents.
15///
16/// Run `glass` for the interactive terminal workspace, or choose a command for
17/// a bounded one-shot operation. Browser actions share revision guards,
18/// verification, workspace ownership, and typed results across CLI, TUI, MCP,
19/// daemon, and Rust interfaces.
20#[derive(Debug, Parser)]
21#[command(
22    name = "glass",
23    version,
24    about = "Semantic browser execution for humans and agents",
25    disable_help_subcommand = true,
26    after_help = "Start here:\n  glass doctor                         Check browser and local runtime support\n  glass                                Open the interactive terminal workspace\n  glass navigate https://example.com   Open a page in one bounded operation\n  glass observe --level interactive    Inspect current semantic understanding\n  glass task compile task.json ir.json Compile a deterministic browser-free task\n\nUse `glass <command> --help` for command-specific options and examples."
27)]
28pub struct Cli {
29    /// Run trusted local automation without interactive capability or tool approvals.
30    /// Glass Dev also enables unrestricted Pi resources and tools in this mode.
31    #[arg(long, global = true)]
32    pub yolo: bool,
33
34    /// Browser safety preset. Hardened mode fails closed for privileged operations.
35    #[arg(long, global = true, value_enum, default_value_t = PolicyPreset::Development)]
36    pub policy: PolicyPreset,
37
38    /// Explicitly allow a privileged capability under the selected policy.
39    #[arg(long = "policy-allow", global = true, value_enum)]
40    pub policy_allow: Vec<PolicyCapability>,
41
42    /// Return a typed confirmation-required result for this capability.
43    #[arg(long = "policy-confirm", global = true, value_enum)]
44    pub policy_confirm: Vec<PolicyCapability>,
45
46    /// Supply one consumable approval token for a confirmation-required capability.
47    #[arg(long = "policy-confirm-once", global = true, value_enum)]
48    pub policy_confirm_once: Vec<PolicyCapability>,
49
50    /// Opt into the experimental sandboxed extension capability.
51    #[arg(long, global = true)]
52    pub experimental_extensions: bool,
53
54    /// Permit only these exact hosts in hardened mode (repeatable).
55    #[arg(long = "policy-allow-host", global = true)]
56    pub policy_allow_host: Vec<String>,
57
58    /// Deny these exact hosts in hardened mode (repeatable).
59    #[arg(long = "policy-deny-host", global = true)]
60    pub policy_deny_host: Vec<String>,
61
62    /// Named browser profile used for persistent cookies and storage.
63    #[arg(long, global = true, default_value = "default")]
64    pub profile: String,
65
66    /// Use a temporary browser profile without persistence.
67    #[arg(long, global = true)]
68    pub incognito: bool,
69
70    /// Attach to an existing Chrome CDP endpoint instead of launching Chrome.
71    /// The default profile value is ignored in this mode.
72    #[arg(long, global = true)]
73    pub attach: bool,
74
75    /// Attach browser operations to a named persistent local session.
76    /// The session's verified loopback port is resolved before the operation starts.
77    #[arg(long, global = true, value_name = "NAME")]
78    pub session: Option<String>,
79
80    /// Chrome page target ID. Required when the selected endpoint has multiple
81    /// page targets.
82    #[arg(long = "target-id", global = true)]
83    pub target_id: Option<String>,
84
85    /// Chrome frame ID used by commands in this one-shot session.
86    #[arg(long = "frame-id", global = true)]
87    pub frame_id: Option<String>,
88
89    /// Chrome remote debugging port.
90    #[arg(long, global = true, default_value_t = 9222)]
91    pub port: u16,
92
93    /// Show the browser window instead of using headless mode.
94    #[arg(long, global = true)]
95    pub headed: bool,
96    /// CSS viewport dimensions applied before navigation, for example `1280x800`.
97    #[arg(long, global = true, value_name = "WIDTHxHEIGHT")]
98    pub viewport: Option<String>,
99
100    /// Pointer behavior for click actions.
101    #[arg(long, global = true, value_enum, default_value_t = InteractionMode::Human)]
102    pub interaction: InteractionMode,
103
104    /// Enable bounded session audit log of high-risk operations.
105    #[arg(long, global = true)]
106    pub audit: bool,
107
108    /// Emit a bounded JSON failure-trace pack when a browser operation fails.
109    #[arg(long, global = true)]
110    pub trace_on_error: bool,
111
112    /// Path to a Chrome/Chromium binary.
113    #[arg(long = "chrome-path", alias = "chrome", global = true)]
114    pub chrome_path: Option<PathBuf>,
115
116    /// Run the MCP server over stdio.
117    #[arg(long)]
118    pub mcp: bool,
119
120    /// Terminal workspace layout. Auto uses terminal geometry only.
121    #[arg(long = "tui-layout", global = true, value_enum, default_value_t = TuiLayout::Auto)]
122    pub tui_layout: TuiLayout,
123
124    /// Connection transport policy. Auto keeps unmeasured SSH links unknown.
125    #[arg(long = "tui-transport", global = true, value_enum, default_value_t = TuiTransport::Auto)]
126    pub tui_transport: TuiTransport,
127
128    /// Graphics capability override. Auto requires an active protocol probe.
129    #[arg(long = "tui-graphics", global = true, value_enum, default_value_t = TuiGraphics::Auto)]
130    pub tui_graphics: TuiGraphics,
131
132    /// Measured/known round-trip latency for presentation policy diagnostics.
133    #[arg(long = "tui-rtt-ms", global = true)]
134    pub tui_rtt_ms: Option<f64>,
135
136    /// Measured/known effective terminal throughput in megabits per second.
137    #[arg(long = "tui-throughput-mbps", global = true)]
138    pub tui_throughput_mbps: Option<f64>,
139
140    /// Terminal-native live browser policy. Off preserves semantic-only startup.
141    #[arg(long = "tui-live", global = true, value_enum, default_value_t = TuiLiveMode::Off)]
142    pub tui_live: TuiLiveMode,
143
144    /// Preferred terminal-native live browser renderer.
145    #[arg(long = "tui-live-backend", global = true, value_enum, default_value_t = TuiLiveBackend::Auto)]
146    pub tui_live_backend: TuiLiveBackend,
147
148    /// Terminal-native live browser bandwidth and frame-rate profile.
149    #[arg(long = "tui-live-quality", global = true, value_enum, default_value_t = TuiLiveQuality::Balanced)]
150    pub tui_live_quality: TuiLiveQuality,
151
152    /// How ANSI-sampled browser pixels fit inside the terminal App pane.
153    #[arg(long = "tui-live-fit", global = true, value_enum, default_value_t = TuiLiveFit::Contain)]
154    pub tui_live_fit: TuiLiveFit,
155
156    /// Override the per-profile persistent knowledge snapshot path.
157    #[arg(long, global = true)]
158    pub knowledge_store: Option<PathBuf>,
159
160    /// Select the bounded agent-facing response projection.
161    #[arg(long, global = true, value_enum, default_value_t = ResponseMode::Minimal)]
162    pub response_mode: ResponseMode,
163
164    /// One-shot prompt, for example: `navigate to https://example.com`.
165    #[arg(value_name = "PROMPT")]
166    pub prompt: Option<String>,
167
168    #[command(subcommand)]
169    pub command: Option<Commands>,
170}
171
172impl Cli {
173    pub(crate) fn session_cli_flags(&self) -> Vec<String> {
174        let mut args = Vec::new();
175        push_enum_flag(&mut args, "--policy", self.policy);
176        args.push("--profile".into());
177        args.push(self.profile.clone());
178        args.push("--port".into());
179        args.push(self.port.to_string());
180        push_enum_flag(&mut args, "--interaction", self.interaction);
181        if self.yolo {
182            args.push("--yolo".into());
183        }
184        if self.incognito {
185            args.push("--incognito".into());
186        }
187        if self.headed {
188            args.push("--headed".into());
189        }
190        if self.audit {
191            args.push("--audit".into());
192        }
193        if self.experimental_extensions {
194            args.push("--experimental-extensions".into());
195        }
196        if self.trace_on_error {
197            args.push("--trace-on-error".into());
198        }
199        if let Some(path) = &self.chrome_path {
200            args.push("--chrome-path".into());
201            args.push(path.display().to_string());
202        }
203        if let Some(viewport) = &self.viewport {
204            args.push("--viewport".into());
205            args.push(viewport.clone());
206        }
207        for capability in &self.policy_allow {
208            push_enum_flag(&mut args, "--policy-allow", *capability);
209        }
210        for capability in &self.policy_confirm {
211            push_enum_flag(&mut args, "--policy-confirm", *capability);
212        }
213        for capability in &self.policy_confirm_once {
214            push_enum_flag(&mut args, "--policy-confirm-once", *capability);
215        }
216        for host in &self.policy_allow_host {
217            args.push("--policy-allow-host".into());
218            args.push(host.clone());
219        }
220        for host in &self.policy_deny_host {
221            args.push("--policy-deny-host".into());
222            args.push(host.clone());
223        }
224        args
225    }
226
227    pub(crate) fn mcp_cli(&self) -> Self {
228        let mut argv = vec!["glass".into(), "--mcp".into()];
229        argv.extend(self.session_cli_flags());
230        Self::parse_from(argv)
231    }
232}
233
234fn push_enum_flag(args: &mut Vec<String>, flag: &str, value: impl ValueEnum) {
235    if let Some(value) = value.to_possible_value() {
236        args.push(flag.into());
237        args.push(value.get_name().into());
238    }
239}
240
241#[derive(Debug, Clone, Copy, ValueEnum)]
242pub enum McpClient {
243    Generic,
244    ClaudeCode,
245    Codex,
246}
247
248/// Responsive layout policy for the interactive terminal workspace.
249#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum, Default)]
250pub enum TuiLayout {
251    /// Select from terminal geometry only.
252    #[default]
253    Auto,
254    /// Force the multi-pane desktop workspace, including on narrow terminals.
255    Desktop,
256    /// Use a single-pane, phone-friendly workspace and semantic browser output.
257    Mobile,
258    /// Force a condensed workspace independent of transport.
259    Compact,
260}
261
262/// Presentation transport classification. This is independent from layout.
263#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum, Default)]
264pub enum TuiTransport {
265    #[default]
266    Auto,
267    Local,
268    RemoteFast,
269    RemoteConstrained,
270    Mosh,
271    UnknownRemote,
272}
273
274/// Terminal graphics evidence/override, independent from transport and layout.
275#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum, Default)]
276pub enum TuiGraphics {
277    #[default]
278    Auto,
279    Kitty,
280    Sixel,
281    ITermInline,
282    Ansi,
283    SemanticOnly,
284}
285
286#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum, Default)]
287pub enum TuiLiveMode {
288    /// Do not capture continuous browser pixels; explicit screenshots still work.
289    #[default]
290    Off,
291    /// Enable live pixels only when a native Herdr or Kitty backend is detected.
292    Auto,
293    /// Enable live pixels and use the ANSI renderer when native graphics are absent.
294    On,
295}
296
297#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum, Default)]
298pub enum TuiLiveBackend {
299    /// Prefer Herdr, then Kitty, then ANSI according to the live policy.
300    #[default]
301    Auto,
302    /// Use Herdr's owned pane graphics stream.
303    Herdr,
304    /// Emit the Kitty terminal graphics protocol directly.
305    Kitty,
306    /// Render browser pixels as true-color Unicode half blocks.
307    Ansi,
308}
309
310#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum, Default)]
311pub enum TuiLiveQuality {
312    /// Approximately 3 FPS at a compact capture size.
313    Data,
314    /// Approximately 6 FPS with balanced resolution and transfer cost.
315    #[default]
316    Balanced,
317    /// Approximately 12 FPS at the largest bounded pane resolution.
318    Smooth,
319}
320
321#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum, Default)]
322pub enum TuiLiveFit {
323    /// Show the complete frame with letterboxing; native image backends always use this.
324    #[default]
325    Contain,
326    /// Fill the ANSI pane and crop browser edges when aspect ratios differ.
327    Cover,
328    /// Use one source pixel per ANSI half-block sample and crop overflow.
329    Actual,
330}
331
332#[derive(Debug, Subcommand)]
333pub enum Commands {
334    /// Update the Cargo package that owns this executable.
335    Update {
336        /// Print the resolved package, provenance, root, and Cargo command without running it.
337        #[arg(long)]
338        dry_run: bool,
339        /// Install a specific Cargo-compatible version requirement instead of the latest release.
340        #[arg(long)]
341        version: Option<String>,
342        /// Reinstall even when Cargo considers the selected version current.
343        #[arg(long)]
344        force: bool,
345        /// Use this configured Cargo registry. Required to change from an unknown or non-crates.io source.
346        #[arg(long)]
347        registry: Option<String>,
348    },
349
350    /// Download and install a managed Chrome for Testing build.
351    InstallChromium {
352        /// Reinstall the version pinned by this Glass release.
353        #[arg(long)]
354        update: bool,
355    },
356
357    /// Evaluate release evidence and forbidden outcomes without starting a browser.
358    Certify {
359        #[command(subcommand)]
360        action: CertifyCommand,
361    },
362
363    /// Inspect local workspace identity, ownership, and lifecycle state.
364    Workspace {
365        #[command(subcommand)]
366        action: WorkspaceCommand,
367    },
368    /// Inspect and operate the current project development runtime.
369    Project {
370        #[command(subcommand)]
371        action: ProjectCommand,
372    },
373    /// Send a prompt or control request to the local Glass harness.
374    Agent {
375        #[command(subcommand)]
376        action: AgentCommand,
377    },
378    /// Discover and launch installed external coding harnesses.
379    Harness {
380        #[command(subcommand)]
381        action: HarnessCommand,
382    },
383    /// Inspect and manage advisory semantic memory.
384    Memory {
385        #[command(subcommand)]
386        action: MemoryCommand,
387    },
388    /// Validate surface evidence and report capability coverage.
389    Surfaces {
390        #[command(subcommand)]
391        action: SurfaceCommand,
392    },
393    /// Inspect a declared transport-neutral backend profile.
394    Backend {
395        #[command(subcommand)]
396        action: BackendCommand,
397    },
398
399    /// Start and inspect the local daemon lifecycle.
400    Daemon {
401        #[command(subcommand)]
402        action: DaemonCommand,
403    },
404    /// Inspect, compare, or attach a validated replay bundle.
405    Replay {
406        #[command(subcommand)]
407        action: ReplayCommand,
408    },
409    /// Print the versioned Glass capability manifest without starting Chrome.
410    Capabilities,
411
412    /// Inspect local browser, daemon, profile, policy, and store health.
413    Doctor {
414        /// Emit the stable machine-readable diagnostic contract.
415        #[arg(long)]
416        json: bool,
417    },
418
419    /// Print deterministic MCP configuration for a supported client.
420    McpConfig {
421        #[arg(long, value_enum, default_value_t = McpClient::Generic)]
422        client: McpClient,
423        /// Explicitly print the generated JSON configuration.
424        #[arg(long)]
425        print: bool,
426    },
427
428    /// List or manage saved profiles.
429    Profiles {
430        #[command(subcommand)]
431        action: Option<ProfileCommand>,
432    },
433
434    /// Inspect and manage the bounded local knowledge store.
435    Knowledge {
436        #[command(subcommand)]
437        action: KnowledgeCommand,
438    },
439
440    /// Inspect and purge bounded local diagnostic result artifacts.
441    Result {
442        #[command(subcommand)]
443        action: ResultCommand,
444    },
445
446    /// Delete a saved profile.
447    DeleteProfile { name: String },
448
449    /// Navigate to a URL.
450    Navigate {
451        url: String,
452        #[arg(long, default_value_t = 20_000)]
453        timeout_ms: u64,
454        #[arg(long)]
455        expected_revision: Option<u64>,
456    },
457
458    /// Click an element by an explicit ref/name/role/text/CSS/ordinal locator.
459    Click {
460        target: String,
461        #[arg(long)]
462        expected_revision: Option<u64>,
463    },
464
465    /// Resolve a target and report clickability without performing an action.
466    Preflight {
467        target: String,
468        #[arg(long, value_enum, default_value_t = PreflightAction::Click)]
469        action: PreflightAction,
470    },
471
472    /// Click exact viewport coordinates for canvas/map surfaces.
473    ClickAt { x: f64, y: f64 },
474
475    /// Click an element expected to open exactly one causally verified popup.
476    ClickExpectPopup {
477        target: String,
478        #[arg(long)]
479        expected_revision: Option<u64>,
480    },
481
482    /// Double-click an element by an explicit ref/name/role/text/CSS/ordinal locator.
483    DoubleClick {
484        target: String,
485        #[arg(long)]
486        expected_revision: Option<u64>,
487    },
488
489    /// Move the pointer over an element without clicking.
490    Hover { target: String },
491
492    /// Drag one element to another uniquely resolved element.
493    Drag {
494        source: String,
495        destination: String,
496        #[arg(long)]
497        expected_revision: Option<u64>,
498    },
499
500    /// Type text into the focused element, optionally clicking a target first.
501    Type {
502        text: String,
503        #[arg(long)]
504        target: Option<String>,
505        #[arg(long)]
506        expected_revision: Option<u64>,
507    },
508
509    /// Dispatch one complete key press.
510    Key {
511        key: String,
512        #[arg(long)]
513        expected_revision: Option<u64>,
514    },
515
516    /// Dispatch only a key-down event.
517    KeyDown {
518        key: String,
519        #[arg(long)]
520        expected_revision: Option<u64>,
521    },
522
523    /// Dispatch only a key-up event.
524    KeyUp {
525        key: String,
526        #[arg(long)]
527        expected_revision: Option<u64>,
528    },
529
530    /// Dispatch a modifier shortcut such as Control+A.
531    Shortcut {
532        shortcut: String,
533        #[arg(long)]
534        expected_revision: Option<u64>,
535    },
536
537    /// Clear an editable element.
538    Clear {
539        target: String,
540        #[arg(long)]
541        expected_revision: Option<u64>,
542    },
543
544    /// Ensure a checkbox or radio is checked.
545    Check {
546        target: String,
547        #[arg(long)]
548        expected_revision: Option<u64>,
549    },
550
551    /// Ensure a checkbox is unchecked.
552    Uncheck {
553        target: String,
554        #[arg(long)]
555        expected_revision: Option<u64>,
556    },
557
558    /// Select one exact option value.
559    Select {
560        target: String,
561        value: String,
562        #[arg(long)]
563        expected_revision: Option<u64>,
564    },
565
566    /// Set a bounded list of regular files on one file input.
567    Upload {
568        target: String,
569        #[arg(required = true)]
570        files: Vec<PathBuf>,
571        #[arg(long)]
572        expected_revision: Option<u64>,
573    },
574
575    /// Capture a PNG screenshot.
576    Screenshot {
577        #[arg(short, long, default_value = "screenshot.png")]
578        output: String,
579        #[arg(long, value_enum, default_value_t = VisualFormat::Png)]
580        format: VisualFormat,
581        #[arg(long)]
582        quality: Option<u8>,
583        #[arg(long, default_value_t = 1.0)]
584        scale: f64,
585        #[arg(long, conflicts_with_all = ["clip", "target"])]
586        full_page: bool,
587        #[arg(long, conflicts_with_all = ["full_page", "target"])]
588        clip: Option<VisualClip>,
589        #[arg(long, conflicts_with_all = ["full_page", "clip"])]
590        target: Option<String>,
591    },
592
593    /// Print the visible page text.
594    Text,
595
596    /// Print the full DOM tree. This is an explicit deep-inspection request.
597    Dom,
598
599    /// Print compact accessibility and text context.
600    Observe {
601        /// Include the full DOM tree. This is an explicit deep-inspection request.
602        #[arg(long)]
603        deep_dom: bool,
604        /// Include a PNG screenshot in the structured context.
605        #[arg(long)]
606        screenshot: bool,
607        /// Include bounded, policy-gated form field values.
608        #[arg(long)]
609        form_values: bool,
610        /// Return the versioned semantic observation at the requested level.
611        #[arg(long = "level", alias = "semantic-level", value_parser = parse_semantic_level)]
612        semantic_level: Option<String>,
613        /// Expand one semantic region from the current observation.
614        #[arg(long, requires = "semantic_level")]
615        region: Option<String>,
616    },
617
618    /// Capture the bounded task-oriented page inspection contract.
619    InspectPage,
620    /// Run bounded navigation, observation, inspection, and safe target probes for a site manifest.
621    SmokeSites {
622        /// JSON file containing `{ "sites": [...] }`.
623        input: PathBuf,
624        /// Stop after the first site-level failure.
625        #[arg(long)]
626        stop_on_error: bool,
627    },
628
629    /// Resolve target candidates without acting.
630    FindTarget { input: PathBuf },
631
632    /// Run one guarded semantic action and verify an optional postcondition.
633    ActAndVerify {
634        input: PathBuf,
635        #[arg(long)]
636        predicate: Option<String>,
637        #[arg(long, default_value_t = 10_000)]
638        timeout_ms: u64,
639    },
640
641    /// Extract typed records from a fresh semantic region.
642    ExtractStructured { input: PathBuf },
643
644    /// Recover a potentially indeterminate execution conservatively.
645    RecoverRun { execution_id: String },
646
647    /// Scroll the page by CSS pixels.
648    Scroll {
649        #[arg(long, default_value_t = 0.0)]
650        dx: f64,
651        #[arg(long, default_value_t = 600.0)]
652        dy: f64,
653        #[arg(long)]
654        expected_revision: Option<u64>,
655    },
656
657    /// Wait for one explicit browser condition until a bounded deadline.
658    Wait {
659        condition: String,
660        #[arg(long, default_value_t = 10_000)]
661        timeout_ms: u64,
662    },
663
664    /// Collect bounded, redacted console and network evidence.
665    Diagnostics {
666        #[arg(long, default_value_t = 1_000)]
667        duration_ms: u64,
668    },
669
670    /// Accept the currently open JavaScript dialog.
671    AcceptDialog,
672
673    /// Dismiss the currently open JavaScript dialog.
674    DismissDialog,
675
676    /// Dismiss a recognized OneTrust/Cookiebot consent wall.
677    DismissConsent,
678
679    /// Wait for one download into an authorized existing directory.
680    Download {
681        destination: PathBuf,
682        #[arg(long, default_value_t = 30_000)]
683        timeout_ms: u64,
684    },
685
686    /// List discoverable page targets without changing the active target.
687    Targets,
688
689    /// Write a bounded, redacted page-target archive without selecting or closing any target.
690    ArchiveTargets {
691        /// Optional JSON output path. Without it, print the archive to stdout.
692        #[arg(short, long)]
693        output: Option<PathBuf>,
694    },
695
696    /// Create a page target without selecting it.
697    NewTarget { url: String },
698
699    /// Explicitly select the page target used by subsequent commands.
700    SelectTarget { id: String },
701
702    /// Close one page target.
703    CloseTarget { id: String },
704
705    /// List frames in the active page target.
706    Frames,
707
708    /// Explicitly select the frame used by subsequent commands.
709    SelectFrame { id: String },
710
711    /// Evaluate JavaScript in the current page.
712    Evaluate { expression: String },
713
714    /// List all browser cookies for the current page.
715    Cookies,
716
717    /// Export current browser cookies as bounded JSON.
718    ExportCookies { output: PathBuf },
719
720    /// Import browser cookies from bounded JSON.
721    ImportCookies { input: PathBuf },
722
723    /// Save the current page as a PDF.
724    Pdf {
725        #[arg(short, long, default_value = "page.pdf")]
726        output: String,
727        #[arg(long)]
728        background: bool,
729    },
730
731    /// Fill multiple form fields from a JSON value.
732    FillForm {
733        /// JSON array of {target, value} objects.
734        #[arg(long)]
735        fields: String,
736        /// Initial observation revision required before filling.
737        #[arg(long)]
738        expected_revision: Option<u64>,
739    },
740
741    /// Execute a bounded typed batch from a JSON array or stdin.
742    Batch {
743        /// JSON file containing the batch steps; omit to read stdin.
744        input: Option<PathBuf>,
745        #[arg(long)]
746        atomic: bool,
747        /// Revision policy: fixed, chain, or unguarded.
748        #[arg(long, value_enum, default_value_t = BatchMode::Unguarded)]
749        mode: BatchMode,
750        /// Initial observation revision required by fixed and chain modes.
751        #[arg(long)]
752        expected_revision: Option<u64>,
753    },
754
755    #[command(subcommand_precedence_over_arg = true)]
756    Workflow {
757        /// Offline authoring operation. Omit to execute the workflow.
758        #[command(subcommand)]
759        action: Option<WorkflowAuthoringCommand>,
760        /// JSON file containing `{ "workflow": ..., "inputs": ... }`.
761        input: Option<PathBuf>,
762    },
763
764    /// Validate and compile a browser-free Task Protocol task.
765    Task {
766        #[command(subcommand)]
767        action: TaskCommand,
768    },
769
770    /// Inspect or diff browser-free Glass Web IR v1 JSON.
771    Ir {
772        #[command(subcommand)]
773        action: IrCommand,
774    },
775
776    /// Reconcile a workflow checkpoint and execute only its safe pending suffix.
777    WorkflowResume {
778        /// JSON file containing the workflow definition.
779        workflow: PathBuf,
780        /// JSON file containing a workflow checkpoint.
781        checkpoint: PathBuf,
782        /// Optional JSON file containing the workflow input map.
783        #[arg(long)]
784        inputs: Option<PathBuf>,
785    },
786
787    /// Resolve a declared intent from JSON or stdin without dispatching it.
788    ResolveIntent {
789        /// JSON file containing the versioned intent request; omit to read stdin.
790        input: Option<PathBuf>,
791    },
792
793    /// Resolve and execute one explicitly selected intent candidate.
794    ExecuteIntent {
795        /// JSON file containing the versioned execution request; omit to read stdin.
796        input: Option<PathBuf>,
797    },
798
799    /// Evaluate a bounded JSON verification predicate.
800    Verify {
801        /// JSON object such as `{"urlEquals":"https://example.com"}`.
802        predicate: String,
803        #[arg(long, default_value_t = 10_000)]
804        timeout_ms: u64,
805    },
806
807    /// Reconcile revisioned references against the current observation.
808    ReconcileRefs {
809        #[arg(long)]
810        from_revision: u64,
811        /// Stable locators tried positionally after backend identity is gone.
812        #[arg(long = "hint")]
813        hints: Vec<String>,
814        /// Current revisioned landmark/container ref used to narrow relocation.
815        #[arg(long)]
816        scope: Option<String>,
817        #[arg(required = true)]
818        refs: Vec<String>,
819    },
820
821    /// Report a bounded delta from the last compact observation.
822    ObserveDelta,
823
824    /// Export or import a bounded workflow checkpoint.
825    Checkpoint {
826        #[command(subcommand)]
827        action: CheckpointCommand,
828    },
829
830    /// Create, inspect, diff, or purge redacted local session snapshots.
831    Snapshot {
832        #[command(subcommand)]
833        action: SnapshotCommand,
834    },
835
836    /// Read text from the system clipboard.
837    ClipboardRead,
838
839    /// Write text to the system clipboard.
840    ClipboardWrite { text: String },
841
842    /// Launch the browser-first terminal workspace.
843    ///
844    /// `glass browser` is the shortest path to a browser session; `glass browser tui`
845    /// is an explicit equivalent.
846    Browser {
847        #[command(subcommand)]
848        action: Option<BrowserCommand>,
849    },
850
851    /// Start, inspect, and stop a persistent local browser session.
852    Session {
853        #[command(subcommand)]
854        action: SessionCommand,
855    },
856
857    /// Show grouped help and the embedded Glass workflow skills.
858    Help { topic: Option<String> },
859
860    /// Launch the development terminal workspace.
861    Tui,
862}
863
864#[derive(Debug, Subcommand)]
865pub enum BrowserCommand {
866    /// Launch the focused browser terminal workspace.
867    Tui,
868}
869
870#[derive(Debug, Subcommand)]
871pub enum SessionCommand {
872    /// Start one named persistent browser session.
873    Start {
874        #[arg(default_value = "default")]
875        name: String,
876    },
877    /// Inspect one persistent browser session without starting Chrome.
878    Status {
879        #[arg(default_value = "default")]
880        name: String,
881    },
882    /// Stop one persistent browser session and its owned browser.
883    Stop {
884        #[arg(default_value = "default")]
885        name: String,
886    },
887    /// Print the attach command for one persistent browser session.
888    Open {
889        #[arg(default_value = "default")]
890        name: String,
891    },
892    /// Foreground owner used internally by `session start`.
893    #[command(hide = true)]
894    Serve {
895        name: String,
896        #[arg(long)]
897        socket: PathBuf,
898        #[arg(long)]
899        status: PathBuf,
900    },
901}
902
903fn parse_semantic_level(value: &str) -> Result<String, String> {
904    match value {
905        "summary" | "interactive" | "structured" | "detailed" | "raw" => Ok(value.into()),
906        _ => Err("expected summary, interactive, structured, detailed, or raw".into()),
907    }
908}
909
910#[derive(Debug, Subcommand)]
911pub enum ProfileCommand {
912    List,
913    Create { name: String },
914    Delete { name: String },
915}
916
917#[derive(Debug, Subcommand)]
918pub enum KnowledgeCommand {
919    /// List all validated records.
920    List,
921    /// Show one record by ID.
922    Show { record_id: String },
923    /// Explain one record's provenance, lifecycle, and invalidation rules.
924    Explain { record_id: String },
925    /// Print lifecycle and serialized-size statistics.
926    Stats,
927    /// Export the validated snapshot to stdout or a file.
928    Export { output: Option<PathBuf> },
929    /// Import and replace the complete validated snapshot.
930    Import { input: PathBuf },
931    /// Move one record to a non-eligible state.
932    Invalidate {
933        record_id: String,
934        #[arg(value_enum)]
935        state: KnowledgeInvalidationState,
936        #[arg(long)]
937        reason: Option<String>,
938        #[arg(long)]
939        observed_at: Option<String>,
940    },
941    /// Remove every record for one exact origin.
942    Purge { origin: String },
943}
944
945#[derive(Debug, Subcommand)]
946pub enum WorkspaceCommand {
947    List,
948    Inspect { id: String },
949    Suspend { id: String },
950    Resume { id: String },
951    Delete { id: String },
952}
953
954#[derive(Debug, Subcommand)]
955pub enum ProjectCommand {
956    /// Detect the project and print its runtime configuration.
957    Inspect {
958        #[arg(long, default_value = ".")]
959        root: PathBuf,
960    },
961    /// List bounded project files.
962    Files {
963        #[arg(long, default_value = ".")]
964        root: PathBuf,
965    },
966    /// Search files, browser entities, processes, events, and commands.
967    Search {
968        query: String,
969        #[arg(long, default_value_t = 64)]
970        limit: usize,
971        #[arg(long, default_value = ".")]
972        root: PathBuf,
973    },
974    /// Read one workspace-confined file.
975    Read {
976        path: String,
977        #[arg(long, default_value = ".")]
978        root: PathBuf,
979    },
980    /// Edit and save one file through the native buffer contract.
981    Edit {
982        path: String,
983        #[arg(long, conflicts_with = "input")]
984        content: Option<String>,
985        #[arg(long, conflicts_with = "content")]
986        input: Option<PathBuf>,
987        #[arg(long, default_value = ".")]
988        root: PathBuf,
989    },
990    /// Create a workspace-confined directory, including missing parents.
991    Mkdir {
992        path: String,
993        #[arg(long, default_value = ".")]
994        root: PathBuf,
995    },
996    /// Rename or move one workspace-confined file or directory.
997    Rename {
998        from: String,
999        to: String,
1000        #[arg(long, default_value = ".")]
1001        root: PathBuf,
1002    },
1003    /// Delete one file or an empty directory after explicit confirmation.
1004    Delete {
1005        path: String,
1006        #[arg(long)]
1007        yes: bool,
1008        #[arg(long, default_value = ".")]
1009        root: PathBuf,
1010    },
1011    /// Request real diagnostics from rust-analyzer through LSP.
1012    Diagnostics {
1013        path: String,
1014        #[arg(long, default_value = ".")]
1015        root: PathBuf,
1016    },
1017    /// Start a named development process in a real PTY.
1018    Run {
1019        name: String,
1020        #[arg(long)]
1021        command: Option<String>,
1022        #[arg(long)]
1023        wait: bool,
1024        #[arg(long, default_value = ".")]
1025        root: PathBuf,
1026    },
1027    /// Run the detected test command in a PTY and wait for completion.
1028    Test {
1029        #[arg(long, default_value = ".")]
1030        root: PathBuf,
1031    },
1032    /// Run the detected lint command in a PTY and wait for completion.
1033    Lint {
1034        #[arg(long, default_value = ".")]
1035        root: PathBuf,
1036    },
1037    /// Inspect, start, stop, or read a managed process.
1038    Process {
1039        #[arg(long, default_value = ".")]
1040        root: PathBuf,
1041        #[command(subcommand)]
1042        action: ProjectProcessCommand,
1043    },
1044    /// Show code, runtime, semantic, and workflow impact.
1045    Diff {
1046        #[arg(long, default_value = ".")]
1047        root: PathBuf,
1048    },
1049    /// Record an explicit source/runtime relationship with evidence.
1050    Link {
1051        entity: String,
1052        path: String,
1053        #[arg(long)]
1054        start_line: u32,
1055        #[arg(long)]
1056        end_line: u32,
1057        #[arg(long, default_value = "explicit-marker")]
1058        provenance: String,
1059        #[arg(long, default_value_t = 1.0)]
1060        confidence: f32,
1061        #[arg(long, default_value = "explicit project link")]
1062        detail: String,
1063        #[arg(long, default_value = ".")]
1064        root: PathBuf,
1065    },
1066    /// Discover or inspect bidirectional source/runtime graph links.
1067    Graph {
1068        #[arg(long, default_value = ".")]
1069        root: PathBuf,
1070        #[command(subcommand)]
1071        action: ProjectGraphCommand,
1072    },
1073    /// Evaluate one semantic regression breakpoint against two snapshots.
1074    Breakpoint {
1075        kind: String,
1076        entity: String,
1077        before: PathBuf,
1078        after: PathBuf,
1079        #[arg(long, default_value = ".")]
1080        root: PathBuf,
1081    },
1082    /// Show the bounded development timeline.
1083    Timeline {
1084        #[arg(long, default_value = ".")]
1085        root: PathBuf,
1086    },
1087    /// Replay a bounded window of attributed development revisions.
1088    Replay {
1089        #[arg(long, default_value_t = 0)]
1090        start: usize,
1091        #[arg(long, default_value_t = 64)]
1092        limit: usize,
1093        #[arg(long, default_value = ".")]
1094        root: PathBuf,
1095    },
1096    /// Probe or launch Neovim integration.
1097    Neovim {
1098        #[arg(long, default_value = ".")]
1099        root: PathBuf,
1100        #[command(subcommand)]
1101        action: NeovimCommand,
1102    },
1103    /// Create an isolated Git worktree development experiment.
1104    Experiment {
1105        #[arg(long, default_value = ".")]
1106        root: PathBuf,
1107        #[command(subcommand)]
1108        action: ExperimentCommand,
1109    },
1110    /// Attach an external actor to the attributed development timeline.
1111    Attach {
1112        actor: String,
1113        #[arg(long, default_value = ".")]
1114        root: PathBuf,
1115    },
1116}
1117
1118#[derive(Debug, Subcommand)]
1119pub enum ProjectGraphCommand {
1120    Discover,
1121    Entity {
1122        entity: String,
1123    },
1124    Source {
1125        path: String,
1126        #[arg(long)]
1127        line: Option<u32>,
1128    },
1129}
1130
1131#[derive(Debug, Subcommand)]
1132pub enum NeovimCommand {
1133    Probe,
1134    Start {
1135        #[arg(long, default_value = "neovim")]
1136        name: String,
1137        path: Option<PathBuf>,
1138    },
1139}
1140
1141#[derive(Debug, Subcommand)]
1142pub enum ExperimentCommand {
1143    Create {
1144        name: String,
1145        #[arg(long)]
1146        port: u16,
1147    },
1148}
1149
1150#[derive(Debug, Subcommand)]
1151pub enum ProjectProcessCommand {
1152    List,
1153    Start {
1154        name: String,
1155        command: String,
1156        #[arg(long)]
1157        wait: bool,
1158    },
1159    Stop {
1160        name: String,
1161    },
1162    Restart {
1163        name: String,
1164    },
1165    Remove {
1166        name: String,
1167    },
1168    Input {
1169        name: String,
1170        input: String,
1171    },
1172    Resize {
1173        name: String,
1174        cols: u16,
1175        rows: u16,
1176    },
1177    Output {
1178        name: String,
1179    },
1180}
1181
1182#[derive(Debug, Subcommand)]
1183pub enum AgentCommand {
1184    /// Inspect Node, Pi SDK, authentication, model, and session readiness.
1185    Doctor,
1186    /// Install or select the Glass-managed native Pi SDK runtime.
1187    Setup {
1188        /// Select an existing Pi SDK dist/index.js instead of installing one.
1189        #[arg(long)]
1190        sdk_entry: Option<PathBuf>,
1191        /// Use this existing Pi agent directory for credentials and models.
1192        #[arg(long, requires = "sdk_entry")]
1193        agent_dir: Option<PathBuf>,
1194        /// Reinstall the pinned managed SDK even when it is already ready.
1195        #[arg(long)]
1196        update: bool,
1197        /// Open the managed Pi CLI after setup so `/login` can configure auth.
1198        #[arg(long)]
1199        login: bool,
1200    },
1201    /// Print the concise current Glass Agent readiness state.
1202    Status,
1203    /// Delegate one bounded prompt to an installed temporary external agent.
1204    Delegate {
1205        /// External agent id: codex, claude, or opencode.
1206        harness: String,
1207        /// Prompt text, or `-` to read the prompt from stdin.
1208        prompt: String,
1209        #[arg(long, default_value = ".")]
1210        root: PathBuf,
1211        #[arg(long, value_enum, default_value_t = ExternalAgentSandbox::ReadOnly)]
1212        sandbox: ExternalAgentSandbox,
1213        #[arg(long, default_value_t = 600)]
1214        timeout_secs: u64,
1215        /// Permit a workspace-write sandbox. Pair with `--yes`.
1216        #[arg(long)]
1217        allow_mutation: bool,
1218        /// Confirm the exact workspace-write delegation.
1219        #[arg(long)]
1220        yes: bool,
1221    },
1222    /// Execute one schema-validated call through the Glass agent-tool broker.
1223    #[command(hide = true)]
1224    Tool {
1225        call: String,
1226        #[arg(long, default_value = ".")]
1227        root: PathBuf,
1228        #[arg(long)]
1229        allow_mutation: bool,
1230        #[arg(long)]
1231        yes: bool,
1232    },
1233    /// Execute a one-use broker request from a private temporary file.
1234    #[command(hide = true)]
1235    ToolFile {
1236        path: PathBuf,
1237        #[arg(long, default_value = ".")]
1238        root: PathBuf,
1239        #[arg(long)]
1240        allow_mutation: bool,
1241        #[arg(long)]
1242        yes: bool,
1243    },
1244    /// Negotiate the Glass-owned harness protocol.
1245    Hello {
1246        #[arg(long, default_value = ".")]
1247        root: PathBuf,
1248        #[arg(long, value_enum, default_value_t = AgentHarness::Local)]
1249        harness: AgentHarness,
1250    },
1251    /// Run one bounded local prompt through the harness.
1252    Prompt {
1253        text: String,
1254        #[arg(long, default_value = ".")]
1255        root: PathBuf,
1256        #[arg(long, value_enum, default_value_t = AgentHarness::Local)]
1257        harness: AgentHarness,
1258    },
1259    /// Steer the active local harness request.
1260    Steer {
1261        text: String,
1262        #[arg(long, default_value = ".")]
1263        root: PathBuf,
1264        #[arg(long, value_enum, default_value_t = AgentHarness::Pi)]
1265        harness: AgentHarness,
1266    },
1267    /// Queue a follow-up through the native Pi SDK runtime.
1268    FollowUp {
1269        text: String,
1270        #[arg(long, default_value = ".")]
1271        root: PathBuf,
1272    },
1273    /// List models exposed by the native Pi SDK runtime.
1274    Models {
1275        #[arg(long, default_value = ".")]
1276        root: PathBuf,
1277    },
1278    /// Select a Pi provider/model pair.
1279    SetModel {
1280        provider: String,
1281        model_id: String,
1282        #[arg(long, default_value = ".")]
1283        root: PathBuf,
1284    },
1285    /// Set the Pi thinking level.
1286    Thinking {
1287        level: String,
1288        #[arg(long, default_value = ".")]
1289        root: PathBuf,
1290    },
1291    /// Abort the active Pi request.
1292    Abort {
1293        #[arg(long, default_value = ".")]
1294        root: PathBuf,
1295    },
1296    /// Start a fresh Pi session.
1297    NewSession {
1298        #[arg(long, default_value = ".")]
1299        root: PathBuf,
1300    },
1301}
1302
1303#[derive(Debug, Subcommand)]
1304pub enum HarnessCommand {
1305    /// List supported coding harnesses and PATH availability.
1306    List,
1307    /// Launch one installed harness in the selected project directory.
1308    Start {
1309        name: String,
1310        #[arg(long, default_value = ".")]
1311        root: PathBuf,
1312    },
1313}
1314
1315#[derive(Debug, Clone, Copy, ValueEnum)]
1316pub enum AgentHarness {
1317    Local,
1318    Pi,
1319}
1320
1321#[derive(Debug, Clone, Copy, ValueEnum)]
1322pub enum ExternalAgentSandbox {
1323    ReadOnly,
1324    WorkspaceWrite,
1325}
1326
1327#[derive(Debug, Subcommand)]
1328pub enum MemoryCommand {
1329    Status,
1330    Inspect {
1331        record_id: String,
1332    },
1333    Explain {
1334        record_id: String,
1335    },
1336    Forget {
1337        record_id: String,
1338    },
1339    Export {
1340        output: Option<PathBuf>,
1341    },
1342    /// Remove stale, contradicted, and quarantined records.
1343    Prune,
1344    /// Re-read and validate the snapshot from disk.
1345    Reindex,
1346}
1347
1348#[derive(Debug, Subcommand)]
1349pub enum SurfaceCommand {
1350    Inspect { input: PathBuf },
1351    Coverage { input: PathBuf },
1352}
1353
1354#[derive(Debug, Subcommand)]
1355pub enum BackendCommand {
1356    Status { input: PathBuf },
1357    Capabilities { input: PathBuf },
1358    Test { input: PathBuf },
1359}
1360
1361#[derive(Debug, Subcommand)]
1362pub enum ReplayCommand {
1363    Inspect {
1364        scenario: PathBuf,
1365        input: PathBuf,
1366    },
1367    Diff {
1368        scenario: PathBuf,
1369        before: PathBuf,
1370        after: PathBuf,
1371    },
1372    Attach {
1373        scenario: PathBuf,
1374        input: PathBuf,
1375    },
1376}
1377
1378#[derive(Debug, Subcommand)]
1379pub enum SnapshotCommand {
1380    Create,
1381    List,
1382    Inspect { snapshot_id: String },
1383    Diff { from: String, to: String },
1384    Purge,
1385}
1386
1387#[derive(Debug, Subcommand)]
1388pub enum ResultCommand {
1389    /// Show a stored diagnostic artifact, optionally selecting one section.
1390    Show {
1391        result_id: String,
1392        #[arg(long)]
1393        section: Option<String>,
1394    },
1395    /// Purge artifacts older than a bounded duration such as 7d or 24h.
1396    Purge {
1397        #[arg(long = "older-than")]
1398        older_than: String,
1399    },
1400}
1401#[derive(Debug, Clone, Copy, ValueEnum)]
1402pub enum KnowledgeInvalidationState {
1403    Stale,
1404    Contradicted,
1405    Quarantined,
1406}
1407
1408#[derive(Debug, Subcommand)]
1409pub enum WorkflowAuthoringCommand {
1410    /// Compile YAML or JSON source into canonical workflow JSON.
1411    Compile {
1412        input: PathBuf,
1413        #[arg(short, long)]
1414        output: Option<PathBuf>,
1415    },
1416    /// Format a YAML or JSON workflow as deterministic YAML.
1417    Format {
1418        input: PathBuf,
1419        #[arg(short, long)]
1420        output: Option<PathBuf>,
1421    },
1422    /// Show a redacted browser-free execution preview.
1423    Preview { input: PathBuf },
1424    /// Compare two workflow sources and print migration guidance.
1425    Diff { before: PathBuf, after: PathBuf },
1426    /// Import explicit semantic evidence into a reviewable draft.
1427    Record {
1428        /// JSON event envelope; omit to read stdin.
1429        #[arg(long)]
1430        input: Option<PathBuf>,
1431        #[arg(short, long)]
1432        output: Option<PathBuf>,
1433    },
1434    /// Validate authoring source against the canonical workflow contract.
1435    Validate { input: PathBuf },
1436    /// Run static workflow diagnostics without starting a browser.
1437    Lint {
1438        input: PathBuf,
1439        #[arg(long)]
1440        warnings_as_errors: bool,
1441    },
1442    /// List or initialize one of the reviewable workflow starter templates.
1443    Templates {
1444        /// Optional template name; omit to list available templates.
1445        name: Option<String>,
1446        #[arg(short, long)]
1447        output: Option<PathBuf>,
1448    },
1449    /// Initialize one of the five reviewable issue 29 starter templates.
1450    Init {
1451        /// Template name: search, form-submit, paginated-extraction,
1452        /// authenticated-session, or dialog-and-download.
1453        name: String,
1454        #[arg(short, long)]
1455        output: Option<PathBuf>,
1456    },
1457}
1458
1459#[derive(Debug, Subcommand)]
1460pub enum TaskCommand {
1461    /// Validate strict Task Protocol JSON without starting Chrome.
1462    Validate {
1463        /// JSON file containing the authored task.
1464        input: PathBuf,
1465    },
1466    /// Compile strict Task Protocol JSON into a deterministic execution plan.
1467    Compile {
1468        /// JSON file containing the authored task.
1469        input: PathBuf,
1470        /// Stable Glass Web IR v1 JSON used as compilation evidence.
1471        ir: PathBuf,
1472        /// Optional output file for the canonical execution plan.
1473        #[arg(short, long)]
1474        output: Option<PathBuf>,
1475        /// Print a deterministic compilation explanation to stderr.
1476        #[arg(long)]
1477        explain: bool,
1478    },
1479    /// Execute a validated browser-backed Task Protocol task against the current browser.
1480    Execute {
1481        /// JSON file containing the authored task from the form, navigation, dialog,
1482        /// pagination, extraction, or field-read Task Protocol families.
1483        input: PathBuf,
1484        /// Revision from the caller's preceding semantic observation.
1485        #[arg(long)]
1486        expected_revision: u64,
1487        /// Confirm a task whose risk or ambiguity policy requires confirmation.
1488        #[arg(long)]
1489        confirm: bool,
1490    },
1491}
1492
1493#[derive(Debug, Subcommand)]
1494pub enum IrCommand {
1495    /// Validate one Glass Web IR v1 document without starting Chrome.
1496    Validate { input: PathBuf },
1497    /// Print a bounded summary of one validated Glass Web IR v1 document.
1498    Inspect { input: PathBuf },
1499    /// Compute a deterministic diff between two validated Web IR revisions.
1500    Diff {
1501        before: PathBuf,
1502        after: PathBuf,
1503        /// Print the bounded canonical summary instead of detailed changes.
1504        #[arg(long)]
1505        summary: bool,
1506    },
1507    /// Classify one entity's continuity across two validated Web IR revisions.
1508    Continuity {
1509        before: PathBuf,
1510        after: PathBuf,
1511        entity_id: String,
1512    },
1513    /// Print one validated Glass Web IR v1 document in canonical JSON form.
1514    Canonical { input: PathBuf },
1515}
1516
1517#[derive(Debug, Subcommand)]
1518pub enum DaemonCommand {
1519    /// Start the daemon in the background.
1520    Start {
1521        #[arg(long)]
1522        socket: Option<PathBuf>,
1523        #[arg(long)]
1524        status: Option<PathBuf>,
1525    },
1526    /// Read the daemon status contract.
1527    Status {
1528        #[arg(long)]
1529        socket: Option<PathBuf>,
1530        #[arg(long)]
1531        status: Option<PathBuf>,
1532    },
1533    /// Stop the daemon recorded by the status contract.
1534    Stop {
1535        #[arg(long)]
1536        socket: Option<PathBuf>,
1537        #[arg(long)]
1538        status: Option<PathBuf>,
1539    },
1540    /// Check the daemon process, status, and local socket.
1541    Doctor {
1542        #[arg(long)]
1543        socket: Option<PathBuf>,
1544        #[arg(long)]
1545        status: Option<PathBuf>,
1546    },
1547    /// Read the bounded local daemon log tail.
1548    Logs {
1549        #[arg(long)]
1550        status: Option<PathBuf>,
1551    },
1552    /// Acknowledge that interrupted workflows were reconciled from checkpoints.
1553    AcknowledgeRecovery {
1554        #[arg(long)]
1555        status: Option<PathBuf>,
1556        /// Request ID for every recovery record reconciled from a checkpoint.
1557        #[arg(long = "request-id", required = true)]
1558        request_ids: Vec<String>,
1559    },
1560    /// Internal foreground server used by `daemon start`.
1561    #[command(hide = true)]
1562    Serve {
1563        #[arg(long)]
1564        socket: PathBuf,
1565        #[arg(long)]
1566        status: PathBuf,
1567    },
1568}
1569
1570#[derive(Debug, Subcommand)]
1571pub enum CertifyCommand {
1572    /// Run one scenario in a navigated browser fixture and emit evidence.
1573    Run {
1574        /// JSON scenario to execute.
1575        #[arg(long)]
1576        scenario: PathBuf,
1577        /// JSON fixture manifest used to bind controls and faults.
1578        #[arg(long)]
1579        fixture: PathBuf,
1580        /// Fixture URL to navigate before execution.
1581        #[arg(long)]
1582        url: String,
1583        /// Directory containing workflow sources referenced by the scenario.
1584        #[arg(long, default_value = ".")]
1585        workflow_root: PathBuf,
1586        /// Optional JSON object containing declared workflow inputs.
1587        #[arg(long)]
1588        inputs: Option<PathBuf>,
1589        /// Optional path for the redacted evidence bundle.
1590        #[arg(short, long)]
1591        output: Option<PathBuf>,
1592    },
1593    /// Expand a scenario into its manifest-bound execution plan.
1594    Plan {
1595        /// JSON scenario to plan.
1596        #[arg(long)]
1597        scenario: PathBuf,
1598        /// JSON fixture manifest used to bind controls and faults.
1599        #[arg(long)]
1600        fixture: PathBuf,
1601    },
1602    /// Evaluate a release-blocking reliability gate.
1603    Release {
1604        #[arg(long)]
1605        version: String,
1606        /// JSON array of validated reliability scenarios.
1607        #[arg(long)]
1608        scenarios: PathBuf,
1609        /// JSON array of scenario observations and oracle evidence.
1610        #[arg(long)]
1611        observations: PathBuf,
1612        /// Optional JSON array of redacted replay bundles to cross-check.
1613        #[arg(long)]
1614        replays: Option<PathBuf>,
1615    },
1616    /// Validate one redacted replay bundle against its versioned scenario.
1617    Replay {
1618        /// JSON scenario used to validate the replay binding.
1619        #[arg(long)]
1620        scenario: PathBuf,
1621        /// JSON replay bundle to validate.
1622        #[arg(long)]
1623        input: PathBuf,
1624    },
1625    /// Compare two redacted replay bundles for one scenario.
1626    ReplayDiff {
1627        /// JSON scenario used to validate both replay bindings.
1628        #[arg(long)]
1629        scenario: PathBuf,
1630        /// Baseline replay bundle.
1631        #[arg(long)]
1632        before: PathBuf,
1633        /// Candidate replay bundle.
1634        #[arg(long)]
1635        after: PathBuf,
1636    },
1637}
1638
1639#[derive(Debug, Subcommand)]
1640pub enum CheckpointCommand {
1641    Export,
1642    Import { input: Option<PathBuf> },
1643}
1644
1645#[cfg(test)]
1646mod tests {
1647    use super::*;
1648
1649    fn flag_pair(flags: &[String], flag: &str, value: &str) -> bool {
1650        flags
1651            .windows(2)
1652            .any(|pair| pair[0] == flag && pair[1] == value)
1653    }
1654
1655    #[test]
1656    fn default_invocation_is_promptless_and_commandless() {
1657        let cli = Cli::try_parse_from(["glass"]).unwrap();
1658
1659        assert!(cli.prompt.is_none());
1660        assert!(cli.command.is_none());
1661    }
1662
1663    #[test]
1664    fn session_cli_flags_forward_policy_profile_and_port() {
1665        let cli = Cli::try_parse_from([
1666            "glass",
1667            "--policy",
1668            "hardened",
1669            "--profile",
1670            "work",
1671            "--port",
1672            "9333",
1673            "--yolo",
1674            "--incognito",
1675            "--policy-allow-host",
1676            "example.test",
1677            "daemon",
1678            "start",
1679        ])
1680        .unwrap();
1681
1682        let flags = cli.session_cli_flags();
1683        assert!(flag_pair(&flags, "--policy", "hardened"));
1684        assert!(flag_pair(&flags, "--profile", "work"));
1685        assert!(flag_pair(&flags, "--port", "9333"));
1686        assert!(flags.iter().any(|flag| flag == "--yolo"));
1687        assert!(flags.iter().any(|flag| flag == "--incognito"));
1688        assert!(flag_pair(&flags, "--policy-allow-host", "example.test"));
1689
1690        let mcp = cli.mcp_cli();
1691        assert!(mcp.mcp);
1692        assert_eq!(mcp.policy, PolicyPreset::Hardened);
1693        assert_eq!(mcp.profile, "work");
1694        assert_eq!(mcp.port, 9333);
1695        assert!(mcp.yolo);
1696        assert!(mcp.incognito);
1697        assert_eq!(mcp.policy_allow_host, vec!["example.test"]);
1698    }
1699
1700    #[test]
1701    fn tui_is_discoverable_as_an_explicit_command() {
1702        assert!(matches!(
1703            Cli::try_parse_from(["glass", "tui"]).unwrap().command,
1704            Some(Commands::Tui)
1705        ));
1706    }
1707
1708    #[test]
1709    fn browser_and_session_onboarding_commands_parse() {
1710        let browser = Cli::try_parse_from(["glass", "browser"]).unwrap();
1711        assert!(matches!(
1712            browser.command,
1713            Some(Commands::Browser { action: None })
1714        ));
1715
1716        let session = Cli::try_parse_from(["glass", "--session", "work", "observe"]).unwrap();
1717        assert_eq!(session.session.as_deref(), Some("work"));
1718        assert!(matches!(session.command, Some(Commands::Observe { .. })));
1719
1720        let start = Cli::try_parse_from(["glass", "session", "start", "work"]).unwrap();
1721        assert!(matches!(
1722            start.command,
1723            Some(Commands::Session {
1724                action: SessionCommand::Start { ref name }
1725            }) if name == "work"
1726        ));
1727    }
1728    #[test]
1729    fn update_options_are_explicit_and_browser_free() {
1730        let cli = Cli::try_parse_from([
1731            "glass",
1732            "update",
1733            "--dry-run",
1734            "--version",
1735            "0.3.4",
1736            "--force",
1737            "--registry",
1738            "internal",
1739        ])
1740        .unwrap();
1741        assert!(matches!(
1742            cli.command,
1743            Some(Commands::Update {
1744                dry_run: true,
1745                version: Some(ref version),
1746                force: true,
1747                registry: Some(ref registry),
1748            }) if version == "0.3.4" && registry == "internal"
1749        ));
1750    }
1751
1752    #[test]
1753    fn tui_layout_defaults_to_auto_and_accepts_mobile_override() {
1754        let default = Cli::try_parse_from(["glass", "tui"]).unwrap();
1755        assert!(!default.yolo);
1756        assert_eq!(default.tui_layout, TuiLayout::Auto);
1757        assert_eq!(default.tui_live, TuiLiveMode::Off);
1758        assert_eq!(default.tui_live_backend, TuiLiveBackend::Auto);
1759        assert_eq!(default.tui_live_quality, TuiLiveQuality::Balanced);
1760        assert_eq!(default.tui_live_fit, TuiLiveFit::Contain);
1761
1762        let mobile = Cli::try_parse_from([
1763            "glass",
1764            "--tui-layout",
1765            "mobile",
1766            "--tui-live",
1767            "on",
1768            "--tui-live-backend",
1769            "ansi",
1770            "--tui-live-quality",
1771            "data",
1772            "--tui-live-fit",
1773            "cover",
1774            "tui",
1775        ])
1776        .unwrap();
1777        assert_eq!(mobile.tui_layout, TuiLayout::Mobile);
1778        assert_eq!(mobile.tui_live, TuiLiveMode::On);
1779        assert_eq!(mobile.tui_live_backend, TuiLiveBackend::Ansi);
1780        assert_eq!(mobile.tui_live_quality, TuiLiveQuality::Data);
1781        assert_eq!(mobile.tui_live_fit, TuiLiveFit::Cover);
1782    }
1783
1784    #[test]
1785    fn yolo_is_an_explicit_global_opt_in() {
1786        assert!(
1787            Cli::try_parse_from(["glass", "--yolo", "tui"])
1788                .unwrap()
1789                .yolo
1790        );
1791        assert!(
1792            Cli::try_parse_from(["glass", "agent", "hello", "--yolo"])
1793                .unwrap()
1794                .yolo
1795        );
1796    }
1797
1798    #[test]
1799    fn agent_readiness_commands_are_explicit() {
1800        assert!(matches!(
1801            Cli::try_parse_from(["glass", "agent", "doctor"])
1802                .unwrap()
1803                .command,
1804            Some(Commands::Agent {
1805                action: AgentCommand::Doctor
1806            })
1807        ));
1808        assert!(matches!(
1809            Cli::try_parse_from([
1810                "glass",
1811                "agent",
1812                "setup",
1813                "--sdk-entry",
1814                "/opt/pi/dist/index.js",
1815                "--agent-dir",
1816                "/opt/pi/config",
1817                "--update"
1818            ])
1819            .unwrap()
1820            .command,
1821            Some(Commands::Agent {
1822                action: AgentCommand::Setup {
1823                    sdk_entry: Some(_),
1824                    agent_dir: Some(_),
1825                    update: true,
1826                    login: false,
1827                }
1828            })
1829        ));
1830    }
1831
1832    #[test]
1833    fn external_harness_commands_are_available_to_the_cli() {
1834        assert!(matches!(
1835            Cli::try_parse_from(["glass", "harness", "list"])
1836                .unwrap()
1837                .command,
1838            Some(Commands::Harness {
1839                action: HarnessCommand::List
1840            })
1841        ));
1842        assert!(matches!(
1843            Cli::try_parse_from(["glass", "harness", "start", "codex", "--root", "/tmp/project"])
1844                .unwrap()
1845                .command,
1846            Some(Commands::Harness {
1847                action: HarnessCommand::Start { ref name, ref root }
1848            }) if name == "codex" && root == std::path::Path::new("/tmp/project")
1849        ));
1850    }
1851
1852    #[test]
1853    fn observation_and_human_interaction_are_defaults() {
1854        let cli = Cli::try_parse_from(["glass", "observe"]).unwrap();
1855
1856        assert_eq!(cli.interaction, InteractionMode::Human);
1857        assert!(matches!(
1858            cli.command,
1859            Some(Commands::Observe {
1860                deep_dom: false,
1861                screenshot: false,
1862                form_values: false,
1863                semantic_level: None,
1864                region: None,
1865            })
1866        ));
1867    }
1868
1869    #[test]
1870    fn screenshot_and_fast_interaction_require_explicit_flags() {
1871        let cli =
1872            Cli::try_parse_from(["glass", "--interaction", "fast", "observe", "--screenshot"])
1873                .unwrap();
1874
1875        assert_eq!(cli.interaction, InteractionMode::Fast);
1876        assert!(matches!(
1877            cli.command,
1878            Some(Commands::Observe {
1879                deep_dom: false,
1880                screenshot: true,
1881                form_values: false,
1882                semantic_level: None,
1883                region: None,
1884            })
1885        ));
1886    }
1887
1888    #[test]
1889    fn deep_dom_requires_an_explicit_observation_flag() {
1890        let cli = Cli::try_parse_from(["glass", "observe", "--deep-dom"]).unwrap();
1891
1892        assert!(matches!(
1893            cli.command,
1894            Some(Commands::Observe {
1895                deep_dom: true,
1896                screenshot: false,
1897                form_values: false,
1898                semantic_level: None,
1899                region: None,
1900            })
1901        ));
1902    }
1903
1904    #[test]
1905    fn semantic_observation_level_and_region_are_explicit() {
1906        let cli = Cli::try_parse_from([
1907            "glass",
1908            "observe",
1909            "--level",
1910            "interactive",
1911            "--region",
1912            "region_main",
1913        ])
1914        .unwrap();
1915        assert!(matches!(
1916            cli.command,
1917            Some(Commands::Observe {
1918                semantic_level: Some(level),
1919                region: Some(region),
1920                ..
1921            }) if level == "interactive" && region == "region_main"
1922        ));
1923
1924        assert!(Cli::try_parse_from(["glass", "observe", "--level", "verbose"]).is_err());
1925    }
1926
1927    #[test]
1928    fn screenshot_remains_a_separate_explicit_command() {
1929        let cli = Cli::try_parse_from(["glass", "screenshot", "--output", "page.png"]).unwrap();
1930
1931        assert!(matches!(
1932            cli.command,
1933            Some(Commands::Screenshot { output, .. }) if output == "page.png"
1934        ));
1935    }
1936
1937    #[test]
1938    fn double_click_is_an_explicit_action_command() {
1939        let cli = Cli::try_parse_from(["glass", "double-click", "r7:b42"]).unwrap();
1940
1941        assert!(matches!(
1942            cli.command,
1943            Some(Commands::DoubleClick { target, .. }) if target == "r7:b42"
1944        ));
1945    }
1946
1947    #[test]
1948    fn click_expect_popup_is_an_explicit_action_command() {
1949        let cli = Cli::try_parse_from(["glass", "click-expect-popup", "css=#popup"]).unwrap();
1950        assert!(matches!(
1951            cli.command,
1952            Some(Commands::ClickExpectPopup { target, .. }) if target == "css=#popup"
1953        ));
1954    }
1955
1956    #[test]
1957    fn wait_has_an_explicit_condition_and_bounded_default() {
1958        let cli = Cli::try_parse_from(["glass", "wait", "text=Ready"]).unwrap();
1959        assert!(matches!(
1960            cli.command,
1961            Some(Commands::Wait { condition, timeout_ms: 10_000 }) if condition == "text=Ready"
1962        ));
1963    }
1964
1965    #[test]
1966    fn topology_commands_are_explicit() {
1967        assert!(matches!(
1968            Cli::try_parse_from(["glass", "targets"]).unwrap().command,
1969            Some(Commands::Targets)
1970        ));
1971        let cli = Cli::try_parse_from([
1972            "glass",
1973            "--target-id",
1974            "page-1",
1975            "--frame-id",
1976            "frame-1",
1977            "evaluate",
1978            "document.title",
1979        ])
1980        .unwrap();
1981        assert_eq!(cli.target_id.as_deref(), Some("page-1"));
1982        assert_eq!(cli.frame_id.as_deref(), Some("frame-1"));
1983        assert!(matches!(
1984            Cli::try_parse_from(["glass", "select-frame", "frame-1"])
1985                .unwrap()
1986                .command,
1987            Some(Commands::SelectFrame { id }) if id == "frame-1"
1988        ));
1989    }
1990
1991    #[test]
1992    fn archive_targets_accepts_optional_workspace_output() {
1993        let stdout = Cli::try_parse_from(["glass", "archive-targets"])
1994            .unwrap()
1995            .command;
1996        assert!(matches!(
1997            stdout,
1998            Some(Commands::ArchiveTargets { output: None })
1999        ));
2000        let file = Cli::try_parse_from(["glass", "archive-targets", "--output", "targets.json"])
2001            .unwrap()
2002            .command;
2003        assert!(matches!(
2004            file,
2005            Some(Commands::ArchiveTargets {
2006                output: Some(path)
2007            }) if path == std::path::Path::new("targets.json")
2008        ));
2009    }
2010
2011    #[test]
2012    fn complete_input_commands_are_explicit() {
2013        assert!(matches!(
2014            Cli::try_parse_from(["glass", "drag", "css=#from", "css=#to"])
2015                .unwrap()
2016                .command,
2017            Some(Commands::Drag { source, destination, .. }) if source == "css=#from" && destination == "css=#to"
2018        ));
2019        assert!(matches!(
2020            Cli::try_parse_from(["glass", "shortcut", "Control+A"])
2021                .unwrap()
2022                .command,
2023            Some(Commands::Shortcut { shortcut, .. }) if shortcut == "Control+A"
2024        ));
2025        assert!(matches!(
2026            Cli::try_parse_from([
2027                "glass",
2028                "fill-form",
2029                "--fields",
2030                "[]",
2031                "--expected-revision",
2032                "7"
2033            ])
2034            .unwrap()
2035            .command,
2036            Some(Commands::FillForm {
2037                fields,
2038                expected_revision: Some(7)
2039            }) if fields == "[]"
2040        ));
2041    }
2042
2043    #[test]
2044    fn rejects_unknown_interaction_modes() {
2045        assert!(Cli::try_parse_from(["glass", "--interaction", "instant", "observe"]).is_err());
2046    }
2047
2048    #[test]
2049    fn attach_and_target_id_are_explicit_global_options() {
2050        let cli = Cli::try_parse_from([
2051            "glass",
2052            "--attach",
2053            "--port",
2054            "9333",
2055            "--target-id",
2056            "page-2",
2057            "observe",
2058        ])
2059        .unwrap();
2060
2061        assert!(cli.attach);
2062        assert_eq!(cli.port, 9333);
2063        assert_eq!(cli.target_id.as_deref(), Some("page-2"));
2064    }
2065
2066    #[test]
2067    fn workflow_command_accepts_optional_json_input() {
2068        let cli = Cli::try_parse_from(["glass", "workflow", "workflow.json"]).unwrap();
2069        assert!(matches!(
2070            cli.command,
2071            Some(Commands::Workflow {
2072                action: None,
2073                input: Some(path)
2074            })
2075                if path.as_os_str() == "workflow.json"
2076        ));
2077        let cli = Cli::try_parse_from(["glass", "workflow", "validate", "workflow.yaml"]).unwrap();
2078        assert!(matches!(
2079            cli.command,
2080            Some(Commands::Workflow {
2081                action: Some(WorkflowAuthoringCommand::Validate { input }),
2082                input: None,
2083            }) if input.as_os_str() == "workflow.yaml"
2084        ));
2085        let cli = Cli::try_parse_from(["glass", "workflow", "preview", "workflow.yaml"]).unwrap();
2086        assert!(matches!(
2087            cli.command,
2088            Some(Commands::Workflow {
2089                action: Some(WorkflowAuthoringCommand::Preview { input }),
2090                input: None,
2091            }) if input.as_os_str() == "workflow.yaml"
2092        ));
2093        let cli = Cli::try_parse_from([
2094            "glass",
2095            "workflow",
2096            "record",
2097            "--input",
2098            "events.json",
2099            "--output",
2100            "draft.json",
2101        ])
2102        .unwrap();
2103        assert!(matches!(
2104            cli.command,
2105            Some(Commands::Workflow {
2106                action: Some(WorkflowAuthoringCommand::Record { input: Some(input), output: Some(output) }),
2107                input: None,
2108            }) if input.as_os_str() == "events.json" && output.as_os_str() == "draft.json"
2109        ));
2110    }
2111
2112    #[test]
2113    fn certify_release_command_accepts_versioned_evidence_paths() {
2114        let cli = Cli::try_parse_from([
2115            "glass",
2116            "certify",
2117            "release",
2118            "--version",
2119            "0.2.0",
2120            "--scenarios",
2121            "scenarios.json",
2122            "--observations",
2123            "observations.json",
2124        ])
2125        .unwrap();
2126        assert!(matches!(
2127            cli.command,
2128            Some(Commands::Certify {
2129                action: CertifyCommand::Release {
2130                    version,
2131                    scenarios,
2132                    observations,
2133                    replays: None,
2134                },
2135            }) if version == "0.2.0"
2136                && scenarios.as_os_str() == "scenarios.json"
2137                && observations.as_os_str() == "observations.json"
2138        ));
2139    }
2140
2141    #[test]
2142    fn certify_plan_command_accepts_scenario_and_fixture_paths() {
2143        let cli = Cli::try_parse_from([
2144            "glass",
2145            "certify",
2146            "plan",
2147            "--scenario",
2148            "scenario.json",
2149            "--fixture",
2150            "fixture.json",
2151        ])
2152        .unwrap();
2153        assert!(matches!(
2154            cli.command,
2155            Some(Commands::Certify {
2156                action: CertifyCommand::Plan { scenario, fixture },
2157            }) if scenario.as_os_str() == "scenario.json" && fixture.as_os_str() == "fixture.json"
2158        ));
2159    }
2160
2161    #[test]
2162    fn certify_replay_command_accepts_scenario_and_bundle_paths() {
2163        let cli = Cli::try_parse_from([
2164            "glass",
2165            "certify",
2166            "replay",
2167            "--scenario",
2168            "scenario.json",
2169            "--input",
2170            "replay.json",
2171        ])
2172        .unwrap();
2173        assert!(matches!(
2174            cli.command,
2175            Some(Commands::Certify {
2176                action: CertifyCommand::Replay { scenario, input },
2177            }) if scenario.as_os_str() == "scenario.json" && input.as_os_str() == "replay.json"
2178        ));
2179    }
2180
2181    #[test]
2182    fn certify_replay_diff_command_accepts_two_bundle_paths() {
2183        let cli = Cli::try_parse_from([
2184            "glass",
2185            "certify",
2186            "replay-diff",
2187            "--scenario",
2188            "scenario.json",
2189            "--before",
2190            "before.json",
2191            "--after",
2192            "after.json",
2193        ])
2194        .unwrap();
2195        assert!(matches!(
2196            cli.command,
2197            Some(Commands::Certify {
2198                action: CertifyCommand::ReplayDiff { scenario, before, after },
2199            }) if scenario.as_os_str() == "scenario.json"
2200                && before.as_os_str() == "before.json"
2201                && after.as_os_str() == "after.json"
2202        ));
2203    }
2204
2205    #[test]
2206    fn workflow_resume_command_accepts_checkpoint_and_inputs() {
2207        let cli = Cli::try_parse_from([
2208            "glass",
2209            "workflow-resume",
2210            "workflow.json",
2211            "checkpoint.json",
2212            "--inputs",
2213            "inputs.json",
2214        ])
2215        .unwrap();
2216        assert!(matches!(
2217            cli.command,
2218            Some(Commands::WorkflowResume {
2219                workflow,
2220                checkpoint,
2221                inputs: Some(inputs)
2222            }) if workflow.as_os_str() == "workflow.json"
2223                && checkpoint.as_os_str() == "checkpoint.json"
2224                && inputs.as_os_str() == "inputs.json"
2225        ));
2226    }
2227
2228    #[test]
2229    fn resolve_intent_command_accepts_optional_json_input() {
2230        let cli = Cli::try_parse_from(["glass", "resolve-intent", "intent.json"]).unwrap();
2231        assert!(matches!(
2232            cli.command,
2233            Some(Commands::ResolveIntent { input: Some(path) })
2234                if path.as_os_str() == "intent.json"
2235        ));
2236        assert!(Cli::try_parse_from(["glass", "resolve-intent"]).is_ok());
2237    }
2238
2239    #[test]
2240    fn execute_intent_command_accepts_optional_json_input() {
2241        let cli = Cli::try_parse_from(["glass", "execute-intent", "intent.json"]).unwrap();
2242        assert!(matches!(
2243            cli.command,
2244            Some(Commands::ExecuteIntent { input: Some(path) })
2245                if path.as_os_str() == "intent.json"
2246        ));
2247        assert!(Cli::try_parse_from(["glass", "execute-intent"]).is_ok());
2248    }
2249
2250    #[test]
2251    fn reliability_run_command_requires_fixture_url_and_sources() {
2252        let cli = Cli::try_parse_from([
2253            "glass",
2254            "certify",
2255            "run",
2256            "--scenario",
2257            "scenario.json",
2258            "--fixture",
2259            "fixture.json",
2260            "--url",
2261            "http://127.0.0.1:8000/fixture.html",
2262            "--workflow-root",
2263            "fixtures",
2264            "--inputs",
2265            "inputs.json",
2266            "--output",
2267            "evidence.json",
2268        ])
2269        .unwrap();
2270        assert!(matches!(
2271            cli.command,
2272            Some(Commands::Certify {
2273                action: CertifyCommand::Run {
2274                    scenario,
2275                    fixture,
2276                    url,
2277                    workflow_root,
2278                    inputs: Some(inputs),
2279                    output: Some(output),
2280                }
2281            }) if scenario.as_os_str() == "scenario.json"
2282                && fixture.as_os_str() == "fixture.json"
2283                && url == "http://127.0.0.1:8000/fixture.html"
2284                && workflow_root.as_os_str() == "fixtures"
2285                && inputs.as_os_str() == "inputs.json"
2286                && output.as_os_str() == "evidence.json"
2287        ));
2288    }
2289
2290    #[test]
2291    fn capabilities_command_is_explicitly_offline() {
2292        let cli = Cli::try_parse_from(["glass", "capabilities"]).unwrap();
2293        assert!(matches!(cli.command, Some(Commands::Capabilities)));
2294    }
2295
2296    #[test]
2297    fn experimental_extensions_require_an_explicit_global_opt_in() {
2298        let cli =
2299            Cli::try_parse_from(["glass", "--experimental-extensions", "capabilities"]).unwrap();
2300        assert!(cli.experimental_extensions);
2301    }
2302
2303    #[test]
2304    fn daemon_lifecycle_commands_accept_explicit_local_paths() {
2305        let cli = Cli::try_parse_from([
2306            "glass",
2307            "daemon",
2308            "start",
2309            "--socket",
2310            "/tmp/glass.sock",
2311            "--status",
2312            "/tmp/glass.json",
2313        ])
2314        .unwrap();
2315        assert!(matches!(
2316            cli.command,
2317            Some(Commands::Daemon {
2318                action: DaemonCommand::Start { socket: Some(socket), status: Some(status) }
2319            }) if socket.as_os_str() == "/tmp/glass.sock"
2320                && status.as_os_str() == "/tmp/glass.json"
2321        ));
2322    }
2323
2324    #[test]
2325    fn doctor_command_is_available_without_starting_a_browser() {
2326        let cli = Cli::try_parse_from(["glass", "doctor"]).unwrap();
2327        assert!(matches!(
2328            cli.command,
2329            Some(Commands::Doctor { json: false })
2330        ));
2331    }
2332
2333    #[test]
2334    fn knowledge_management_commands_parse_without_browser_startup() {
2335        let cli = Cli::try_parse_from(["glass", "knowledge", "list"]).unwrap();
2336        assert!(matches!(
2337            cli.command,
2338            Some(Commands::Knowledge {
2339                action: KnowledgeCommand::List
2340            })
2341        ));
2342        let cli = Cli::try_parse_from(["glass", "knowledge", "explain", "record-1"]).unwrap();
2343        assert!(matches!(
2344            cli.command,
2345            Some(Commands::Knowledge {
2346                action: KnowledgeCommand::Explain { .. }
2347            })
2348        ));
2349        let cli = Cli::try_parse_from([
2350            "glass",
2351            "--knowledge-store",
2352            "knowledge.json",
2353            "knowledge",
2354            "invalidate",
2355            "record-1",
2356            "stale",
2357        ])
2358        .unwrap();
2359        assert!(matches!(
2360            cli.command,
2361            Some(Commands::Knowledge {
2362                action: KnowledgeCommand::Invalidate { .. }
2363            })
2364        ));
2365    }
2366    #[test]
2367    fn task_compile_command_is_explicitly_offline() {
2368        use clap::CommandFactory;
2369
2370        let cli = Cli::try_parse_from([
2371            "glass",
2372            "task",
2373            "compile",
2374            "task.json",
2375            "web-ir.json",
2376            "--output",
2377            "plan.json",
2378            "--explain",
2379        ])
2380        .unwrap();
2381        assert!(Cli::command().find_subcommand("task").is_some());
2382        assert!(matches!(
2383            cli.command,
2384            Some(Commands::Task {
2385                action: TaskCommand::Compile {
2386                    input,
2387                    ir,
2388                    output: Some(output),
2389                    explain
2390                }
2391            }) if input.as_os_str() == "task.json"
2392                && ir.as_os_str() == "web-ir.json"
2393                && output.as_os_str() == "plan.json"
2394                && explain
2395        ));
2396    }
2397
2398    #[test]
2399    fn task_execute_help_advertises_supported_families() {
2400        use clap::CommandFactory;
2401
2402        let mut command = Cli::command();
2403        let execute = command
2404            .find_subcommand_mut("task")
2405            .and_then(|task| task.find_subcommand_mut("execute"))
2406            .expect("task execute command should be present");
2407        let help = execute.render_help().to_string();
2408        let normalized = help.split_whitespace().collect::<Vec<_>>().join(" ");
2409
2410        assert!(normalized.contains(
2411            "form, navigation, dialog, pagination, extraction, or field-read Task Protocol families"
2412        ));
2413    }
2414    #[test]
2415    fn task_validate_command_is_explicitly_offline() {
2416        let cli = Cli::try_parse_from(["glass", "task", "validate", "task.json"]).unwrap();
2417        assert!(matches!(
2418            cli.command,
2419            Some(Commands::Task {
2420                action: TaskCommand::Validate { input }
2421            }) if input.as_os_str() == "task.json"
2422        ));
2423    }
2424    #[test]
2425    fn ir_commands_are_explicitly_offline() {
2426        let cli = Cli::try_parse_from(["glass", "ir", "inspect", "draft.json"]).unwrap();
2427        assert!(matches!(
2428            cli.command,
2429            Some(Commands::Ir {
2430                action: IrCommand::Inspect { input }
2431            }) if input.as_os_str() == "draft.json"
2432        ));
2433
2434        let cli =
2435            Cli::try_parse_from(["glass", "ir", "diff", "before.json", "after.json"]).unwrap();
2436        assert!(matches!(
2437            cli.command,
2438            Some(Commands::Ir {
2439                action: IrCommand::Diff {
2440                    before,
2441                    after,
2442                    summary
2443                }
2444            }) if before.as_os_str() == "before.json"
2445                && after.as_os_str() == "after.json"
2446                && !summary
2447        ));
2448
2449        let cli = Cli::try_parse_from([
2450            "glass",
2451            "ir",
2452            "diff",
2453            "before.json",
2454            "after.json",
2455            "--summary",
2456        ])
2457        .unwrap();
2458        assert!(matches!(
2459            cli.command,
2460            Some(Commands::Ir {
2461                action: IrCommand::Diff {
2462                    before,
2463                    after,
2464                    summary
2465                }
2466            }) if before.as_os_str() == "before.json"
2467                && after.as_os_str() == "after.json"
2468                && summary
2469        ));
2470
2471        let cli = Cli::try_parse_from([
2472            "glass",
2473            "ir",
2474            "continuity",
2475            "before.json",
2476            "after.json",
2477            "field-1",
2478        ])
2479        .unwrap();
2480        assert!(matches!(
2481            cli.command,
2482            Some(Commands::Ir {
2483                action: IrCommand::Continuity {
2484                    before,
2485                    after,
2486                    entity_id
2487                }
2488            }) if before.as_os_str() == "before.json"
2489                && after.as_os_str() == "after.json"
2490                && entity_id == "field-1"
2491        ));
2492
2493        let cli = Cli::try_parse_from(["glass", "ir", "validate", "draft.json"]).unwrap();
2494        assert!(matches!(
2495            cli.command,
2496            Some(Commands::Ir {
2497                action: IrCommand::Validate { input }
2498            }) if input.as_os_str() == "draft.json"
2499        ));
2500
2501        let cli = Cli::try_parse_from(["glass", "ir", "canonical", "draft.json"]).unwrap();
2502        assert!(matches!(
2503            cli.command,
2504            Some(Commands::Ir {
2505                action: IrCommand::Canonical { input }
2506            }) if input.as_os_str() == "draft.json"
2507        ));
2508    }
2509    #[test]
2510    fn browser_first_and_persistent_session_commands_parse() {
2511        let cli = Cli::try_parse_from(["glass", "browser", "tui"]).unwrap();
2512        assert!(matches!(
2513            cli.command,
2514            Some(Commands::Browser {
2515                action: Some(BrowserCommand::Tui)
2516            })
2517        ));
2518
2519        let cli = Cli::try_parse_from(["glass", "--session", "work", "observe"]).unwrap();
2520        assert_eq!(cli.session.as_deref(), Some("work"));
2521        assert!(matches!(cli.command, Some(Commands::Observe { .. })));
2522
2523        let cli = Cli::try_parse_from(["glass", "session", "status", "work"]).unwrap();
2524        assert!(matches!(
2525            cli.command,
2526            Some(Commands::Session {
2527                action: SessionCommand::Status { name }
2528            }) if name == "work"
2529        ));
2530    }
2531}