glass-dev 0.3.14

Glass terminal-native development and browser workspace
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
//! GitHub integration through the user's authenticated `gh` CLI.
//!
//! Read-only status remains cheap and cached for the TUI. Review and ship
//! operations are explicit, bounded subprocess calls used by the command
//! palette, task loop, and private cockpit; no shell is involved.

use crate::development::{DevelopmentError, DevelopmentResult};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::path::{Path, PathBuf};
use std::process::{Child, Command, ExitStatus, Stdio};
use std::thread;
use std::time::{Duration, Instant};
const PROBE_INTERVAL: Duration = Duration::from_secs(15);
const PROBE_TIMEOUT: Duration = Duration::from_secs(2);
const REVIEW_TIMEOUT: Duration = Duration::from_secs(8);
const SHIP_TIMEOUT: Duration = Duration::from_secs(20);
const MAX_REMOTE_BYTES: usize = 4 * 1024;
const MAX_REVIEW_BYTES: usize = 64 * 1024;
const MAX_SHIP_OUTPUT_BYTES: usize = 16 * 1024;

/// Parsed GitHub repository owner/name and canonical web URL.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct GitHubRepository {
    /// Repository in `owner/name` form.
    pub name_with_owner: String,
    /// HTTPS repository URL.
    pub web_url: String,
}

/// Availability of the repository remote and authenticated `gh` CLI.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum GitHubAvailability {
    /// No GitHub origin is configured.
    #[default]
    NoRemote,
    /// The configured origin could not be read.
    RemoteUnavailable,
    /// The `gh` executable is unavailable.
    GhUnavailable,
    /// `gh` is installed but not authenticated.
    NotAuthenticated,
    /// Authenticated `gh` status.
    Authenticated,
    /// The bounded authentication probe timed out.
    TimedOut,
}

/// Cached repository and `gh` availability status.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct GitHubStatus {
    /// Parsed GitHub origin, if present.
    pub repository: Option<GitHubRepository>,
    /// Current availability classification.
    pub availability: GitHubAvailability,
}

impl GitHubStatus {
    /// Format a compact status string for the TUI and command palette.
    pub fn summary(&self) -> String {
        match (&self.repository, self.availability) {
            (None, GitHubAvailability::NoRemote) => "no GitHub origin".into(),
            (None, GitHubAvailability::RemoteUnavailable) => "origin unavailable".into(),
            (Some(repository), GitHubAvailability::GhUnavailable) => format!(
                "{} · gh unavailable · install github.com/cli/cli",
                repository.name_with_owner
            ),
            (Some(repository), GitHubAvailability::NotAuthenticated) => format!(
                "{} · gh not authenticated · run `gh auth login`",
                repository.name_with_owner
            ),
            (Some(repository), GitHubAvailability::Authenticated) => {
                format!("{} · gh authenticated", repository.name_with_owner)
            }
            (Some(repository), GitHubAvailability::TimedOut) => format!(
                "{} · gh auth check timed out · retrying automatically",
                repository.name_with_owner
            ),
            (Some(repository), _) => {
                format!("{} · GitHub status unavailable", repository.name_with_owner)
            }
            (None, _) => "GitHub status unavailable".into(),
        }
    }

    /// Whether `gh auth status` succeeded for this repository.
    pub fn is_authenticated(&self) -> bool {
        self.availability == GitHubAvailability::Authenticated
    }
}

#[derive(Debug, Default)]
pub struct GitHubProbeCache {
    root: Option<PathBuf>,
    checked_at: Option<Instant>,
    status: GitHubStatus,
}

impl GitHubProbeCache {
    /// Probe GitHub status, reusing a result for 15 seconds per root.
    pub fn probe(&mut self, root: &Path) -> GitHubStatus {
        if self.root.as_deref() == Some(root)
            && self
                .checked_at
                .is_some_and(|checked_at| checked_at.elapsed() < PROBE_INTERVAL)
        {
            return self.status.clone();
        }

        let status = probe_uncached(root);
        self.root = Some(root.to_path_buf());
        self.checked_at = Some(Instant::now());
        self.status = status.clone();
        status
    }
}

#[derive(Debug, Default)]
pub struct GitHubReviewCache {
    root: Option<PathBuf>,
    checked_at: Option<Instant>,
    review: Option<GitHubReview>,
}

impl GitHubReviewCache {
    /// Fetch review data, reusing a result for 15 seconds per root.
    pub fn review(&mut self, root: &Path) -> GitHubReview {
        if self.root.as_deref() == Some(root)
            && self
                .checked_at
                .is_some_and(|checked_at| checked_at.elapsed() < PROBE_INTERVAL)
            && let Some(review) = &self.review
        {
            return review.clone();
        }
        let review = review(root).unwrap_or_else(|error| GitHubReview {
            repository: None,
            branch: current_branch(root),
            availability: GitHubAvailability::RemoteUnavailable,
            pull_request: None,
            checks: Vec::new(),
            summary: "GitHub review unavailable".into(),
            error: Some(error.to_string()),
        });
        self.root = Some(root.to_path_buf());
        self.checked_at = Some(Instant::now());
        self.review = Some(review.clone());
        review
    }
}

fn probe_uncached(root: &Path) -> GitHubStatus {
    let remote = match read_origin(root) {
        RemoteProbe::Missing => {
            return GitHubStatus::default();
        }
        RemoteProbe::Unavailable => {
            return GitHubStatus {
                repository: None,
                availability: GitHubAvailability::RemoteUnavailable,
            };
        }
        RemoteProbe::Value(remote) => remote,
    };
    let Some(repository) = parse_github_remote(&remote) else {
        return GitHubStatus::default();
    };

    let availability = match run_gh_auth_status(root) {
        GhProbe::Missing => GitHubAvailability::GhUnavailable,
        GhProbe::Authenticated => GitHubAvailability::Authenticated,
        GhProbe::NotAuthenticated => GitHubAvailability::NotAuthenticated,
        GhProbe::TimedOut => GitHubAvailability::TimedOut,
    };
    GitHubStatus {
        repository: Some(repository),
        availability,
    }
}

#[derive(Debug, PartialEq, Eq)]
enum RemoteProbe {
    Missing,
    Unavailable,
    Value(String),
}

fn read_origin(root: &Path) -> RemoteProbe {
    let mut child = match crate::git::git_command(root)
        .args([
            "-c",
            "alias.config=",
            "config",
            "--get",
            "remote.origin.url",
        ])
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::null())
        .spawn()
    {
        Ok(child) => child,
        Err(_) => return RemoteProbe::Unavailable,
    };
    let Some(status) = wait_for_exit(&mut child, PROBE_TIMEOUT) else {
        let _ = child.kill();
        let _ = child.wait();
        return RemoteProbe::Unavailable;
    };
    if !status.success() {
        return RemoteProbe::Missing;
    }
    let output = match child.wait_with_output() {
        Ok(output) if output.stdout.len() <= MAX_REMOTE_BYTES => output.stdout,
        _ => return RemoteProbe::Unavailable,
    };
    let remote = String::from_utf8(output)
        .ok()
        .map(|remote| remote.trim().to_string())
        .filter(|remote| !remote.is_empty());
    remote.map_or(RemoteProbe::Missing, RemoteProbe::Value)
}

#[derive(Debug, PartialEq, Eq)]
enum GhProbe {
    Missing,
    Authenticated,
    NotAuthenticated,
    TimedOut,
}

fn run_gh_auth_status(root: &Path) -> GhProbe {
    let mut child = match Command::new("gh")
        .args(["auth", "status", "--hostname", "github.com"])
        .current_dir(root)
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()
    {
        Ok(child) => child,
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return GhProbe::Missing,
        Err(_) => return GhProbe::NotAuthenticated,
    };
    let Some(status) = wait_for_exit(&mut child, PROBE_TIMEOUT) else {
        let _ = child.kill();
        let _ = child.wait();
        return GhProbe::TimedOut;
    };
    let _ = child.wait();
    if status.success() {
        GhProbe::Authenticated
    } else {
        GhProbe::NotAuthenticated
    }
}

fn wait_for_exit(child: &mut Child, timeout: Duration) -> Option<ExitStatus> {
    let deadline = Instant::now() + timeout;
    loop {
        match child.try_wait() {
            Ok(Some(status)) => return Some(status),
            Ok(None) if Instant::now() < deadline => thread::sleep(Duration::from_millis(10)),
            Ok(None) | Err(_) => return None,
        }
    }
}

/// Parse a GitHub HTTPS or SCP-style remote into repository metadata.
pub fn parse_github_remote(remote: &str) -> Option<GitHubRepository> {
    let remote = remote.trim();
    let path = if let Some(path) = remote.strip_prefix("git@github.com:") {
        path
    } else if let Some((_, authority_and_path)) = remote.split_once("://") {
        let (authority, path) = authority_and_path.split_once('/')?;
        let host = authority.rsplit('@').next()?.to_ascii_lowercase();
        if host != "github.com" {
            return None;
        }
        path
    } else {
        return None;
    };

    let mut segments = path.trim_matches('/').split('/');
    let owner = segments.next()?.trim();
    let repository = segments.next()?.trim_end_matches(".git").trim();
    if segments.next().is_some()
        || !valid_segment(owner)
        || !valid_segment(repository)
        || repository.is_empty()
    {
        return None;
    }
    let name_with_owner = format!("{owner}/{repository}");
    Some(GitHubRepository {
        web_url: format!("https://github.com/{name_with_owner}"),
        name_with_owner,
    })
}

fn valid_segment(segment: &str) -> bool {
    !segment.is_empty()
        && segment.len() <= 128
        && segment
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-'))
}

/// Pull request summary returned by `gh pr view`.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct GitHubPullRequest {
    /// Pull request number.
    pub number: u64,
    /// Pull request title.
    pub title: String,
    /// GitHub pull request state.
    pub state: String,
    /// Pull request web URL.
    pub url: String,
    /// Source branch, when available.
    pub head_branch: Option<String>,
    /// Target branch, when available.
    pub base_branch: Option<String>,
    /// GitHub's review decision, when available.
    pub review_decision: Option<String>,
}

/// One status-check entry associated with a pull request.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct GitHubCheck {
    /// Check or workflow name.
    pub name: String,
    /// Provider-reported status.
    pub status: String,
    /// Provider conclusion, when complete.
    pub conclusion: Option<String>,
    /// Details URL, when supplied.
    pub link: Option<String>,
}

/// Bounded GitHub review projection for a repository branch.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct GitHubReview {
    /// Parsed repository metadata.
    pub repository: Option<GitHubRepository>,
    /// Current branch, when available.
    pub branch: Option<String>,
    /// Remote/authentication availability.
    pub availability: GitHubAvailability,
    /// Pull request for the current branch, when found.
    pub pull_request: Option<GitHubPullRequest>,
    /// Associated status checks.
    pub checks: Vec<GitHubCheck>,
    /// Human-readable summary.
    pub summary: String,
    /// Non-fatal review error, when status was still returned.
    pub error: Option<String>,
}

/// Explicit caller inputs for creating a pull request.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct GitHubShipRequest {
    /// Optional pull request title.
    pub title: Option<String>,
    /// Optional pull request body.
    pub body: Option<String>,
    /// Optional base branch.
    pub base: Option<String>,
    /// Whether to create the pull request as a draft.
    pub draft: bool,
}

/// Result of a successful pull-request creation.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct GitHubShipResult {
    /// Repository receiving the pull request.
    pub repository: GitHubRepository,
    /// Current source branch.
    pub branch: String,
    /// Created pull request URL, when returned by `gh`.
    pub url: Option<String>,
    /// Bounded command output.
    pub output: String,
}

impl GitHubReview {
    /// Render the summary, branch, first eight checks, and any error.
    pub fn display(&self) -> String {
        let checks = self
            .checks
            .iter()
            .take(8)
            .map(|check| {
                format!(
                    "{} {}{}",
                    check.name,
                    check.conclusion.as_deref().unwrap_or(check.status.as_str()),
                    check
                        .link
                        .as_deref()
                        .map(|link| format!(" · {link}"))
                        .unwrap_or_default()
                )
            })
            .collect::<Vec<_>>();
        let mut lines = vec![self.summary.clone()];
        if let Some(branch) = &self.branch {
            lines.push(format!("branch {branch}"));
        }
        lines.extend(checks);
        if let Some(error) = &self.error {
            lines.push(format!("error {error}"));
        }
        lines.join("\n")
    }
}
/// Fetch authenticated pull-request and check status through bounded `gh`
/// subprocess calls. Normal workflow states are returned as data rather than
/// transport errors.
pub fn review(root: &Path) -> DevelopmentResult<GitHubReview> {
    let status = probe_uncached(root);
    let branch = current_branch(root);
    let repository = status.repository.clone();
    if status.availability != GitHubAvailability::Authenticated {
        return Ok(GitHubReview {
            repository,
            branch,
            availability: status.availability,
            pull_request: None,
            checks: Vec::new(),
            summary: status.summary(),
            error: None,
        });
    }

    let (exit, stdout, stderr) = run_gh_capture(
        root,
        &[
            "pr",
            "view",
            "--json",
            "number,title,state,url,headRefName,baseRefName,reviewDecision,statusCheckRollup",
        ],
        REVIEW_TIMEOUT,
        MAX_REVIEW_BYTES,
    )?;
    if !exit.success() {
        let detail = compact_process_output(&stderr, &stdout);
        if detail.to_ascii_lowercase().contains("no pull request") {
            return Ok(GitHubReview {
                repository,
                branch,
                availability: status.availability,
                pull_request: None,
                checks: Vec::new(),
                summary: "No pull request for the current branch".into(),
                error: None,
            });
        }
        return Ok(GitHubReview {
            repository,
            branch,
            availability: status.availability,
            pull_request: None,
            checks: Vec::new(),
            summary: "GitHub pull-request review unavailable".into(),
            error: Some(detail),
        });
    }
    let value: Value = serde_json::from_slice(&stdout)?;
    let pull_request = parse_pull_request(&value)?;
    let mut checks = value
        .get("statusCheckRollup")
        .map(parse_checks)
        .unwrap_or_default();
    if let Some(number) = pull_request
        .as_ref()
        .map(|pull_request| pull_request.number)
    {
        let (checks_exit, checks_stdout, checks_stderr) = run_gh_capture(
            root,
            &[
                "pr",
                "checks",
                &number.to_string(),
                "--json",
                "name,state,conclusion,bucket,link",
            ],
            REVIEW_TIMEOUT,
            MAX_REVIEW_BYTES,
        )?;
        if checks_exit.success() {
            if let Ok(value) = serde_json::from_slice::<Value>(&checks_stdout) {
                checks = parse_checks(&value);
            }
        } else if checks.is_empty() {
            return Ok(GitHubReview {
                repository,
                branch,
                availability: status.availability,
                pull_request,
                checks,
                summary: "Pull request found; checks unavailable".into(),
                error: Some(compact_process_output(&checks_stderr, &checks_stdout)),
            });
        }
    }
    let summary = review_summary(pull_request.as_ref(), &checks);
    Ok(GitHubReview {
        repository,
        branch,
        availability: status.availability,
        pull_request,
        checks,
        summary,
        error: None,
    })
}

/// Create a pull request from the current branch after explicit caller
/// confirmation. Arguments are passed directly to `gh`; no shell is used.
pub fn ship(root: &Path, request: &GitHubShipRequest) -> DevelopmentResult<GitHubShipResult> {
    let status = probe_uncached(root);
    let repository = status
        .repository
        .clone()
        .ok_or_else(|| DevelopmentError::NotFound("GitHub origin is not configured".into()))?;
    if status.availability != GitHubAvailability::Authenticated {
        return Err(DevelopmentError::Conflict(format!(
            "GitHub ship requires authenticated gh CLI ({})",
            status.summary()
        )));
    }
    let branch = current_branch(root).ok_or_else(|| {
        DevelopmentError::Conflict("GitHub ship requires a named current branch".into())
    })?;
    if matches!(branch.as_str(), "main" | "master") {
        return Err(DevelopmentError::Conflict(
            "GitHub ship requires a feature branch, not the default branch".into(),
        ));
    }
    let title = bounded_optional("title", request.title.as_deref(), 512)?;
    let body = bounded_optional("body", request.body.as_deref(), 16 * 1024)?;
    let base = bounded_optional("base", request.base.as_deref(), 256)?;
    let mut args = vec!["pr", "create"];
    if let Some(title) = title.as_deref() {
        args.extend(["--title", title]);
        args.extend(["--body", body.as_deref().unwrap_or("")]);
    } else {
        args.push("--fill");
        if let Some(body) = body.as_deref() {
            args.extend(["--body", body]);
        }
    }
    if let Some(base) = base.as_deref() {
        args.extend(["--base", base]);
    }
    if request.draft {
        args.push("--draft");
    }
    let (exit, stdout, stderr) = run_gh_capture(root, &args, SHIP_TIMEOUT, MAX_SHIP_OUTPUT_BYTES)?;
    let output = compact_process_output(&stdout, &stderr);
    if !exit.success() {
        return Err(DevelopmentError::Process(format!(
            "gh pr create failed: {output}"
        )));
    }
    let url = output
        .split_whitespace()
        .find(|part| part.starts_with("https://github.com/"))
        .map(str::to_string);
    Ok(GitHubShipResult {
        repository,
        branch,
        url,
        output,
    })
}

fn current_branch(root: &Path) -> Option<String> {
    let output = crate::git::git_command(root)
        .args(["-c", "alias.branch=", "branch", "--show-current"])
        .stdin(Stdio::null())
        .stderr(Stdio::null())
        .output()
        .ok()?;
    if !output.status.success() || output.stdout.len() > MAX_REMOTE_BYTES {
        return None;
    }
    let branch = String::from_utf8(output.stdout).ok()?.trim().to_string();
    (!branch.is_empty()
        && branch.len() <= 256
        && branch
            .bytes()
            .all(|byte| !byte.is_ascii_control() && byte != b' '))
    .then_some(branch)
}

fn run_gh_capture(
    root: &Path,
    args: &[&str],
    timeout: Duration,
    limit: usize,
) -> DevelopmentResult<(ExitStatus, Vec<u8>, Vec<u8>)> {
    let mut child = Command::new("gh")
        .args(args)
        .env("GH_PROMPT_DISABLED", "1")
        .current_dir(root)
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .map_err(|error| {
            if error.kind() == std::io::ErrorKind::NotFound {
                DevelopmentError::NotFound("gh CLI is not installed".into())
            } else {
                DevelopmentError::Process(format!("failed to start gh: {error}"))
            }
        })?;
    let stdout = child
        .stdout
        .take()
        .ok_or_else(|| DevelopmentError::Process("gh stdout was unavailable".into()))?;
    let stderr = child
        .stderr
        .take()
        .ok_or_else(|| DevelopmentError::Process("gh stderr was unavailable".into()))?;
    let stdout_reader = thread::spawn(move || read_gh_output(stdout, limit));
    let stderr_reader = thread::spawn(move || read_gh_output(stderr, limit));
    let Some(status) = wait_for_exit(&mut child, timeout) else {
        let _ = child.kill();
        let _ = child.wait();
        let _ = stdout_reader.join();
        let _ = stderr_reader.join();
        return Err(DevelopmentError::Process(format!(
            "gh command timed out after {} seconds",
            timeout.as_secs()
        )));
    };
    let stdout = join_gh_output(stdout_reader)?;
    let stderr = join_gh_output(stderr_reader)?;
    if stdout.len() > limit || stderr.len() > limit {
        return Err(DevelopmentError::InvalidInput(
            "gh output exceeded the bounded GitHub response limit".into(),
        ));
    }
    Ok((status, stdout, stderr))
}

fn read_gh_output(
    mut stream: impl std::io::Read + Send + 'static,
    limit: usize,
) -> std::io::Result<Vec<u8>> {
    let mut retained = Vec::new();
    let mut chunk = [0_u8; 8192];
    loop {
        let read = stream.read(&mut chunk)?;
        if read == 0 {
            break;
        }
        let remaining = limit.saturating_add(1).saturating_sub(retained.len());
        retained.extend_from_slice(&chunk[..read.min(remaining)]);
        if retained.len() > limit {
            let mut discard = [0_u8; 8192];
            while stream.read(&mut discard)? > 0 {}
            break;
        }
    }
    Ok(retained)
}

fn join_gh_output(
    reader: thread::JoinHandle<std::io::Result<Vec<u8>>>,
) -> DevelopmentResult<Vec<u8>> {
    reader
        .join()
        .map_err(|_| DevelopmentError::Process("gh output reader panicked".into()))?
        .map_err(Into::into)
}

fn compact_process_output(primary: &[u8], secondary: &[u8]) -> String {
    let bytes = if !primary.is_empty() {
        primary
    } else {
        secondary
    };
    String::from_utf8_lossy(bytes)
        .trim()
        .chars()
        .take(2_048)
        .collect()
}

fn parse_pull_request(value: &Value) -> DevelopmentResult<Option<GitHubPullRequest>> {
    if value.is_null() || value.as_object().is_none() {
        return Ok(None);
    }
    let number = value.get("number").and_then(Value::as_u64).ok_or_else(|| {
        DevelopmentError::Serialization("GitHub PR response has no number".into())
    })?;
    let title = bounded_json_text(value, "title", 512)?;
    let state = bounded_json_text(value, "state", 64)?;
    let url = bounded_json_text(value, "url", 2_048)?;
    Ok(Some(GitHubPullRequest {
        number,
        title,
        state,
        url,
        head_branch: optional_json_text(value, "headRefName", 256),
        base_branch: optional_json_text(value, "baseRefName", 256),
        review_decision: optional_json_text(value, "reviewDecision", 128),
    }))
}

fn parse_checks(value: &Value) -> Vec<GitHubCheck> {
    let values = value
        .as_array()
        .cloned()
        .or_else(|| value.get("contexts").and_then(Value::as_array).cloned())
        .unwrap_or_default();
    values
        .into_iter()
        .take(256)
        .filter_map(|value| {
            let object = value.as_object()?;
            let name = object
                .get("name")
                .or_else(|| object.get("context"))
                .and_then(Value::as_str)?
                .chars()
                .take(256)
                .collect::<String>();
            if name.is_empty() {
                return None;
            }
            let status = object
                .get("status")
                .or_else(|| object.get("state"))
                .or_else(|| object.get("bucket"))
                .and_then(Value::as_str)
                .unwrap_or("unknown")
                .chars()
                .take(64)
                .collect();
            let conclusion = object
                .get("conclusion")
                .and_then(Value::as_str)
                .map(|value| value.chars().take(64).collect());
            let link = object
                .get("link")
                .or_else(|| object.get("detailsUrl"))
                .and_then(Value::as_str)
                .map(|value| value.split(['?', '#']).next().unwrap_or(value))
                .map(|value| value.chars().take(2_048).collect());
            Some(GitHubCheck {
                name,
                status,
                conclusion,
                link,
            })
        })
        .collect()
}

fn review_summary(pull_request: Option<&GitHubPullRequest>, checks: &[GitHubCheck]) -> String {
    let Some(pull_request) = pull_request else {
        return "No pull request for the current branch".into();
    };
    let failing = checks
        .iter()
        .filter(|check| {
            matches!(
                check.conclusion.as_deref().or(Some(check.status.as_str())),
                Some("FAILURE" | "failure" | "ERROR" | "error" | "CANCELLED" | "cancelled")
            )
        })
        .count();
    if failing > 0 {
        format!(
            "PR #{} · {} failing check{}",
            pull_request.number,
            failing,
            if failing == 1 { "" } else { "s" }
        )
    } else if checks.is_empty() {
        format!("PR #{} · checks pending", pull_request.number)
    } else {
        format!(
            "PR #{} · {} checks observed",
            pull_request.number,
            checks.len()
        )
    }
}

fn bounded_optional(
    label: &str,
    value: Option<&str>,
    limit: usize,
) -> DevelopmentResult<Option<String>> {
    value
        .map(|value| {
            if value.is_empty() || value.len() > limit || value.contains('\0') {
                Err(DevelopmentError::InvalidInput(format!(
                    "GitHub {label} must be 1..={limit} bytes without NUL"
                )))
            } else {
                Ok(value.to_string())
            }
        })
        .transpose()
}

fn bounded_json_text(value: &Value, key: &str, limit: usize) -> DevelopmentResult<String> {
    value
        .get(key)
        .and_then(Value::as_str)
        .filter(|value| !value.is_empty() && value.len() <= limit && !value.contains('\0'))
        .map(str::to_string)
        .ok_or_else(|| {
            DevelopmentError::Serialization(format!(
                "GitHub response field {key} is missing or exceeds {limit} bytes"
            ))
        })
}

fn optional_json_text(value: &Value, key: &str, limit: usize) -> Option<String> {
    value
        .get(key)
        .and_then(Value::as_str)
        .filter(|value| !value.is_empty() && value.len() <= limit && !value.contains('\0'))
        .map(str::to_string)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parses_supported_github_remote_forms() {
        for remote in [
            "https://github.com/wanazhar/glass.git",
            "ssh://git@github.com/wanazhar/glass.git",
            "git@github.com:wanazhar/glass.git",
        ] {
            let repository = parse_github_remote(remote).unwrap();
            assert_eq!(repository.name_with_owner, "wanazhar/glass");
            assert_eq!(repository.web_url, "https://github.com/wanazhar/glass");
        }
    }

    #[test]
    fn rejects_non_github_and_unsafe_remote_forms() {
        for remote in [
            "https://gitlab.com/owner/repo.git",
            "git@github.com:owner/repo/extra.git",
            "git@github.com:owner/../repo.git",
            "github.com/owner/repo.git",
        ] {
            assert!(parse_github_remote(remote).is_none(), "{remote}");
        }
    }

    #[test]
    fn status_summary_never_requires_auth_output() {
        let status = GitHubStatus {
            repository: Some(GitHubRepository {
                name_with_owner: "owner/repo".into(),
                web_url: "https://github.com/owner/repo".into(),
            }),
            availability: GitHubAvailability::NotAuthenticated,
        };
        assert_eq!(
            status.summary(),
            "owner/repo · gh not authenticated · run `gh auth login`"
        );
    }
}