Skip to main content

artifactize_core/monitor/
live.rs

1//! The live branches of every project with Runs on this machine, as the desktop's pane lists
2//! them: each Git worktree that exists now with the branch it has checked out (a detached one by
3//! its folder), and each folder outside Git that exists now and holds declarations. A branch's
4//! Runs are its project's Runs on that branch, from whichever folder they ran in; who ran them
5//! makes no branch of its own. The terminal monitor keeps its own catalog of scopes.
6mod current;
7mod loader;
8mod query;
9mod starred;
10mod waiting;
11
12#[cfg(test)]
13mod tests;
14
15pub use crate::store::Unreadable;
16pub use current::{
17    Current, CurrentArtifact, CurrentEdge, CurrentEval, CurrentRun, Plan, current_run, outline,
18    scan, scan_scope,
19};
20pub use loader::{Input, Loader, OpenRun, Opened, Snapshot};
21pub use query::{DEFAULT, Query, Sort, complete, show};
22pub use starred::{star, star_artifact, starred, starred_artifacts};
23pub use waiting::{Waiting, waiting};
24
25use crate::{
26    platform::{FileIdentity, paths},
27    repository::{self, Identity, Worktree},
28    store::CatalogRun,
29    types::{RunId, RunStatus, Timestamp},
30};
31use serde::{Deserialize, Serialize};
32use std::{
33    collections::{BTreeMap, BTreeSet},
34    path::{Path, PathBuf},
35};
36
37/// A branch's name as Git accepts one: not empty, and none of the characters or sequences
38/// `git check-ref-format --branch` refuses. Made at the Git and serde boundaries, so no other
39/// name becomes a branch's key.
40#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
41#[serde(try_from = "String", into = "String")]
42pub struct BranchName(String);
43
44impl BranchName {
45    pub fn as_str(&self) -> &str {
46        &self.0
47    }
48}
49
50impl TryFrom<String> for BranchName {
51    type Error = String;
52
53    fn try_from(name: String) -> Result<Self, String> {
54        // Each `/`-separated part is a name of its own: not empty, not starting with `.`, not
55        // ending with `.lock`.
56        let refused = name.starts_with('-')
57            || name.ends_with('.')
58            || name == "@"
59            || name.contains("..")
60            || name.contains("@{")
61            || name
62                .split('/')
63                .any(|part| part.is_empty() || part.starts_with('.') || part.ends_with(".lock"))
64            || name.chars().any(|c| {
65                c.is_control() || matches!(c, ' ' | '~' | '^' | ':' | '?' | '*' | '[' | '\\')
66            });
67        if refused {
68            Err(format!("not a branch name: {name:?}"))
69        } else {
70            Ok(Self(name))
71        }
72    }
73}
74
75impl From<BranchName> for String {
76    fn from(name: BranchName) -> Self {
77        name.0
78    }
79}
80
81impl std::fmt::Display for BranchName {
82    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
83        f.write_str(&self.0)
84    }
85}
86
87/// How a Git worktree has its project checked out.
88#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
89#[serde(rename_all = "camelCase")]
90pub enum Head {
91    Branch(BranchName),
92    /// A detached worktree, known by its folder.
93    Detached(#[serde(with = "crate::platform::path_serde")] PathBuf),
94}
95
96/// Where a branch lives: a Git repository's checked-out branch, by the repository's common
97/// directory, or a folder outside Git.
98#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
99#[serde(rename_all = "camelCase")]
100pub enum Place {
101    Git {
102        #[serde(with = "crate::platform::path_serde")]
103        common: PathBuf,
104        head: Head,
105    },
106    Folder(#[serde(with = "crate::platform::path_serde")] PathBuf),
107}
108
109impl Place {
110    /// A saved or live checkout's branch. Both the workspace and Git identity are canonical.
111    pub fn for_checkout(workspace: &Path, identity: &Identity) -> Self {
112        match (&identity.common_dir, &identity.worktree_path) {
113            (Some(common), Some(tree)) => Self::Git {
114                common: common.clone(),
115                head: checkout_head(identity.branch.clone(), || tree.clone()),
116            },
117            _ => Self::Folder(workspace.to_owned()),
118        }
119    }
120
121    /// The Run's original branch, even when no worktree currently has it checked out.
122    pub fn recorded_run(run: &crate::store::Run) -> Self {
123        Self::for_checkout(&run.repo_path, &run.repository)
124    }
125
126    /// Refuse a stale path rather than scanning or editing a different branch.
127    pub async fn checked_workspace(&self, workspace: PathBuf) -> Result<PathBuf, String> {
128        let place = self.clone();
129        crate::task::blocking(move || {
130            if !crate::platform::paths::target_is_dir(&workspace) {
131                return Err("This worktree no longer exists.".into());
132            }
133            let path =
134                crate::platform::canonicalize(&workspace).map_err(|error| error.to_string())?;
135            if Self::for_checkout(&path, &repository::identify(&path)) != place {
136                return Err("This branch is no longer checked out in the worktree.".into());
137            }
138            Ok(path)
139        })
140        .await?
141    }
142
143    /// The project the branch belongs to: every branch of a Git repository shares one.
144    pub fn project(&self) -> Project {
145        match self {
146            Self::Git { common, .. } => Project::Git(common.clone()),
147            Self::Folder(path) => Project::Folder(path.clone()),
148        }
149    }
150}
151
152/// A project: a Git repository, by its common directory, or a folder outside Git.
153#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
154#[serde(rename_all = "camelCase")]
155pub enum Project {
156    Git(#[serde(with = "crate::platform::path_serde")] PathBuf),
157    Folder(#[serde(with = "crate::platform::path_serde")] PathBuf),
158}
159
160impl Project {
161    pub fn path(&self) -> &Path {
162        match self {
163            Self::Git(path) | Self::Folder(path) => path,
164        }
165    }
166}
167
168/// One Run of a branch as its chip shows it.
169#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
170#[serde(rename_all = "camelCase")]
171pub struct Chip {
172    pub id: RunId,
173    pub status: RunStatus,
174    pub created_at: Timestamp,
175    pub completed_at: Option<Timestamp>,
176    /// What the requester said it is working on (`verify --comment`).
177    pub comment: Option<crate::types::RunComment>,
178}
179
180/// A live branch and its Runs.
181#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
182pub struct Branch {
183    pub place: Place,
184    /// The project's name: its repository's or folder's.
185    pub project: String,
186    /// The branch, a detached worktree's folder name, or empty for a folder outside Git.
187    pub name: String,
188    /// Where its Current is scanned and its Artifacts' tools run: the worktree (or folder) as it
189    /// is now, at the workspace its newest Run used (or the app was started for) within it.
190    #[serde(with = "crate::platform::path_serde")]
191    pub workspace: PathBuf,
192    /// Its Runs, oldest first.
193    pub runs: Vec<Chip>,
194}
195
196impl Branch {
197    /// A saved Run on an absent branch, shown only while following its exact reference.
198    pub fn historical(run: &crate::store::Run) -> Self {
199        let place = Place::recorded_run(run);
200        let Label {
201            project,
202            branch: name,
203            ..
204        } = label(&place);
205        Self {
206            place,
207            project,
208            name,
209            workspace: run.repo_path.clone(),
210            runs: vec![Chip {
211                id: run.id.clone(),
212                status: run.status(),
213                created_at: run.created_at,
214                completed_at: run.completed_at(),
215                comment: run.comment.clone(),
216            }],
217        }
218    }
219
220    /// In-progress Runs first, then ended Runs, newest first within each group.
221    pub fn timeline(&self) -> impl Iterator<Item = &Chip> {
222        let newest = self.runs.iter().rev();
223        newest
224            .clone()
225            .filter(|chip| chip.status.is_open())
226            .chain(newest.filter(|chip| !chip.status.is_open()))
227    }
228
229    /// The newest Run still in progress, even if a later one already ended.
230    pub fn running(&self) -> Option<&Chip> {
231        self.runs.iter().rev().find(|chip| chip.status.is_open())
232    }
233
234    /// When its newest Run started.
235    pub fn latest(&self) -> Option<Timestamp> {
236        self.runs.last().map(|chip| chip.created_at)
237    }
238}
239
240/// Which project and branch a saved Run ran on, by name, for every Run whether or not its
241/// branch still lives: what a waiting review of it is listed with.
242#[derive(Debug, Clone, Default, PartialEq, Eq)]
243pub struct Label {
244    pub project: String,
245    pub project_key: Option<Project>,
246    pub branch: String,
247}
248
249pub type Labels = BTreeMap<RunId, Label>;
250
251/// Cached Git facts. Identities of old Run records without a saved identity are asked of Git
252/// once; which worktrees exist is asked again on every [`Discovery::rescan`].
253#[derive(Default)]
254pub struct Discovery {
255    identities: BTreeMap<PathBuf, Identity>,
256    trees: BTreeMap<PathBuf, Vec<Worktree>>,
257}
258
259impl Discovery {
260    /// Ask Git again which worktrees exist, on the next listing.
261    pub fn rescan(&mut self) {
262        self.trees.clear();
263    }
264
265    fn identify(&mut self, path: &Path) -> Identity {
266        self.identities
267            .entry(path.to_path_buf())
268            .or_insert_with(|| repository::identify(path))
269            .clone()
270    }
271
272    /// Whether `path` is a folder now.
273    fn is_folder(&self, path: &Path) -> bool {
274        crate::platform::is_directory(path)
275    }
276
277    /// Whether the folder `path` holds declarations.
278    fn declares(&self, path: &Path) -> bool {
279        crate::workspace::has_artifact_marker(path).unwrap_or(false)
280    }
281
282    fn worktrees(&mut self, common: &Path) -> Vec<Worktree> {
283        self.trees
284            .entry(common.to_path_buf())
285            .or_insert_with(|| {
286                repository::worktrees(common)
287                    .into_iter()
288                    .map(|tree| Worktree {
289                        // Saved identities are canonical; a detached head is matched by path.
290                        path: crate::platform::canonicalize(&tree.path).unwrap_or(tree.path),
291                        branch: tree.branch,
292                    })
293                    .collect()
294            })
295            .clone()
296    }
297}
298
299/// Pick one usable spelling per physical directory for this listing. Read each distinct
300/// saved spelling only once, even if many Runs were saved from it.
301#[derive(Default)]
302struct DirectoryKeys {
303    by_path: BTreeMap<PathBuf, PathBuf>,
304    by_identity: BTreeMap<FileIdentity, PathBuf>,
305}
306
307impl DirectoryKeys {
308    fn resolve(&mut self, path: &Path) -> PathBuf {
309        if let Some(key) = self.by_path.get(path) {
310            return key.clone();
311        }
312        let key = paths::directory_identity(path).map_or_else(
313            |_| path.to_owned(),
314            |(id, canonical)| self.by_identity.entry(id).or_insert(canonical).clone(),
315        );
316        self.by_path.insert(path.to_owned(), key.clone());
317        key
318    }
319
320    fn head(&mut self, branch: Option<String>, tree: &Path) -> Head {
321        checkout_head(branch, || self.resolve(tree))
322    }
323}
324
325fn checkout_head(branch: Option<String>, detached: impl FnOnce() -> PathBuf) -> Head {
326    branch
327        .and_then(|name| BranchName::try_from(name).ok())
328        .map_or_else(|| Head::Detached(detached()), Head::Branch)
329}
330
331/// Where `identity` (of the workspace `repo`) lives, and `repo` relative to its worktree.
332/// The head of the worktree at `tree` with `branch` checked out, or detached without one. A
333/// name Git reports that is no branch name is known by the worktree's folder instead.
334fn place_of(identity: &Identity, repo: &Path, keys: &mut DirectoryKeys) -> (Place, PathBuf) {
335    match (&identity.common_dir, &identity.worktree_path) {
336        (Some(common), Some(tree)) => {
337            let head = keys.head(identity.branch.clone(), tree);
338            let relative = paths::relative_beneath(repo, tree).unwrap_or_default();
339            (
340                Place::Git {
341                    common: keys.resolve(common),
342                    head,
343                },
344                relative,
345            )
346        }
347        _ => (Place::Folder(keys.resolve(repo)), PathBuf::new()),
348    }
349}
350
351fn folder_name(path: &Path) -> String {
352    path.file_name().map_or_else(
353        || crate::platform::path_text(path),
354        crate::platform::display_name,
355    )
356}
357
358/// The project's name: a repository's main folder (the parent of its `.git`), a bare
359/// repository's own folder without `.git`, or the folder outside Git.
360fn project_name(place: &Place) -> String {
361    match place {
362        Place::Git { common, .. } if common.file_name().is_some_and(|name| name == ".git") => {
363            folder_name(common.parent().unwrap_or(common))
364        }
365        Place::Git { common, .. } => {
366            let name = folder_name(common);
367            name.strip_suffix(".git")
368                .map_or(name.clone(), str::to_owned)
369        }
370        Place::Folder(path) => folder_name(path),
371    }
372}
373
374fn branch_name(place: &Place) -> String {
375    match place {
376        Place::Git {
377            head: Head::Branch(branch),
378            ..
379        } => branch.to_string(),
380        Place::Git {
381            head: Head::Detached(tree),
382            ..
383        } => folder_name(tree),
384        Place::Folder(_) => String::new(),
385    }
386}
387
388fn label(place: &Place) -> Label {
389    Label {
390        project: project_name(place),
391        project_key: Some(place.project()),
392        branch: branch_name(place),
393    }
394}
395
396impl Label {
397    /// Name a worktree whose Run is not in the current monitor snapshot.
398    pub fn at(repo: &Path) -> Self {
399        Self::for_identity(repo, &crate::repository::identify(repo))
400    }
401
402    /// Name the saved Git head of a worktree, not the branch checked out there today.
403    pub fn for_identity(repo: &Path, identity: &crate::repository::Identity) -> Self {
404        let (place, _) = place_of(identity, repo, &mut DirectoryKeys::default());
405        label(&place)
406    }
407}
408
409/// What the listing of the branches found.
410pub struct Listing {
411    /// The live branches, the most recent Run first.
412    pub branches: Vec<Branch>,
413    pub labels: Labels,
414    /// The branch of the folder the app was started for, when it lives.
415    pub launch: Option<Place>,
416}
417
418/// A branch's Runs so far, and when its newest started with its workspace in the worktree.
419type Grouped = (Vec<Chip>, Option<(Timestamp, PathBuf)>);
420
421/// Resolve only one Run's live branch using the same identities as the timeline listing.
422fn branch_for(run: &crate::store::Run, discovery: &mut Discovery) -> Option<Place> {
423    let row = CatalogRun {
424        id: run.id.clone(),
425        created_at: run.created_at,
426        completed_at: run.completed_at(),
427        repo_path: run.repo_path.clone(),
428        repository: run.repository.clone(),
429        status: run.status(),
430        comment: run.comment.clone(),
431        red: 0,
432        error: 0,
433        waiting: Vec::new(),
434    };
435    branches(&[row], None, discovery)
436        .branches
437        .into_iter()
438        .find(|branch| branch.runs.iter().any(|chip| chip.id == run.id))
439        .map(|branch| branch.place)
440}
441
442/// The live branches of the projects of `runs`, with their Runs, and the branch of `launch`
443/// (the folder the app was started for) even before its project has a Run.
444pub fn branches(runs: &[CatalogRun], launch: Option<&Path>, discovery: &mut Discovery) -> Listing {
445    let mut grouped: BTreeMap<Place, Grouped> = BTreeMap::new();
446    let mut labels = Labels::new();
447    let mut keys = DirectoryKeys::default();
448    let launched = launch.map(|path| {
449        let (place, _) = place_of(&discovery.identify(path), path, &mut keys);
450        (place, path.to_path_buf())
451    });
452    for run in runs {
453        let identity =
454            if run.repository.common_dir.is_some() && run.repository.worktree_path.is_some() {
455                run.repository.clone()
456            } else {
457                discovery.identify(&run.repo_path)
458            };
459        let (place, relative) = place_of(&identity, &run.repo_path, &mut keys);
460        labels.insert(run.id.clone(), label(&place));
461        let (chips, newest) = grouped.entry(place).or_default();
462        chips.push(Chip {
463            id: run.id.clone(),
464            status: run.status,
465            created_at: run.created_at,
466            completed_at: run.completed_at,
467            comment: run.comment.clone(),
468        });
469        if newest.as_ref().is_none_or(|(at, _)| run.created_at >= *at) {
470            *newest = Some((run.created_at, relative));
471        }
472    }
473    let commons: BTreeSet<PathBuf> = grouped
474        .keys()
475        .chain(launched.iter().map(|(place, _)| place))
476        .filter_map(|place| match place {
477            Place::Git { common, .. } => Some(common.clone()),
478            Place::Folder(_) => None,
479        })
480        .collect();
481    let mut live = Vec::new();
482    for common in commons {
483        live.extend(discovery.worktrees(&common).into_iter().map(|tree| {
484            let head = keys.head(tree.branch, &tree.path);
485            (
486                Place::Git {
487                    common: common.clone(),
488                    head,
489                },
490                tree.path,
491            )
492        }));
493    }
494    let folders: BTreeSet<&PathBuf> = grouped
495        .keys()
496        .chain(launched.iter().map(|(place, _)| place))
497        .filter_map(|place| match place {
498            Place::Folder(path) => Some(path),
499            Place::Git { .. } => None,
500        })
501        .collect();
502    // A Run's folder is live while it still holds declarations; the folder the app was started
503    // for is live while it exists, as the CLI takes any folder as `--repo`, its Artifacts
504    // perhaps only in subfolders.
505    let started = |path: &PathBuf| {
506        launched
507            .as_ref()
508            .is_some_and(|(place, _)| matches!(place, Place::Folder(folder) if folder == path))
509    };
510    live.extend(
511        folders
512            .into_iter()
513            .filter(|path| discovery.is_folder(path) && (started(path) || discovery.declares(path)))
514            .map(|path| (Place::Folder(path.clone()), path.clone())),
515    );
516    // Which newest-Run folders still exist, as the filesystem boundary reports.
517    let present: BTreeSet<PathBuf> = live
518        .iter()
519        .filter_map(|(place, tree)| {
520            let (_, newest) = grouped.get(place)?;
521            let folder = tree.join(&newest.as_ref()?.1);
522            discovery.is_folder(&folder).then_some(folder)
523        })
524        .collect();
525    let mut branches: Vec<Branch> = live
526        .into_iter()
527        .map(|(place, tree)| {
528            let (mut runs, newest) = grouped.remove(&place).unwrap_or_default();
529            runs.sort_by(|a, b| (a.created_at, &a.id).cmp(&(b.created_at, &b.id)));
530            let workspace = match &launched {
531                Some((launch, path)) if *launch == place => path.clone(),
532                _ => newest
533                    .map(|(_, relative)| tree.join(relative))
534                    .filter(|path| present.contains(path))
535                    .unwrap_or(tree),
536            };
537            let Label {
538                project, branch, ..
539            } = label(&place);
540            Branch {
541                place,
542                project,
543                name: branch,
544                workspace,
545                runs,
546            }
547        })
548        .collect();
549    query::order(&mut branches, Sort::Recent);
550    let launch = launched
551        .map(|(place, _)| place)
552        .filter(|place| branches.iter().any(|branch| &branch.place == place));
553    Listing {
554        branches,
555        labels,
556        launch,
557    }
558}