garage44.eu/jeroen/pinnacle

logclone: git clone https://garage44.eu/jeroen/pinnacle.git

.. /workbench/src/tasks.rs

raw

//! The workbench's verbs: tasks, each a git worktree on a branch of its
//! own (`agent/<task>`) under the workbench's state, their files, their
//! jobs, and the one thing that leaves the machine, a proposal.
//!
//! A task belongs to the contact that opened it: no other may touch it.
//! Its state is in files (`state/tasks/<id>/`), so a restart loses a job
//! that was running, not the task.

use crate::config::{Config, identifier};
use crate::sandbox::Sandbox;
use pinnacle_json::Value;
use pinnacle_p2p::identity::Key;
use pinnacle_records::verbs::{self, Description, Effect, Param, Type, Verb};
use std::path::{Component, Path, PathBuf};
use std::process::{Child, Command, Stdio};
use std::time::{Duration, Instant};

/// The most of a file `read` answers, and of a job's output `job` shows.
const READ_MAX: usize = 64 * 1024;
/// The most a job's output file holds.
const OUTPUT_MAX: u64 = 1 << 20;
/// The most results `search` gives.
const SEARCH_MAX: usize = 200;
/// The longest `job` waits for a job's end before it answers.
const WAIT_MAX: u64 = 60;

pub fn description() -> Description {
    let p = |name: &str, kind, required, about: &str| Param {
        name: name.into(),
        kind,
        required,
        about: about.into(),
    };
    let task = || p("task", Type::Number, true, "The task, as open answered");
    let path = || {
        p(
            "path",
            Type::Text,
            true,
            "A path in the task's worktree, relative",
        )
    };
    let verb = |name: &str, about: &str, params: Vec<Param>, effect, inverse: Option<&str>, untrusted| Verb {
        name: name.into(),
        about: about.into(),
        params,
        effect,
        inverse: inverse.map(Into::into),
        untrusted,
    };
    Description {
        service: "workbench".into(),
        about: "Code work in a git worktree per task, on a machine with a toolchain".into(),
        verbs: vec![
            verb(
                "repos",
                "The repositories it works in",
                vec![],
                Effect::Reads,
                None,
                false,
            ),
            verb(
                "open",
                "Start a task: a worktree and branch agent/<task> of a repository, from a base branch",
                vec![
                    p("repo", Type::Text, true, "A repository, as repos lists"),
                    p("base", Type::Text, true, "The branch to start from, as main"),
                ],
                Effect::Own,
                Some("close"),
                false,
            ),
            verb(
                "files",
                "The files and folders in a folder of the task",
                vec![
                    task(),
                    p("path", Type::Text, false, "A folder; the top when left out"),
                ],
                Effect::Reads,
                None,
                true,
            ),
            verb(
                "read",
                "A file's text, its lines from a line on",
                vec![
                    task(),
                    path(),
                    p("from", Type::Number, false, "The first line, from 1"),
                    p("lines", Type::Number, false, "How many lines"),
                ],
                Effect::Reads,
                None,
                true,
            ),
            verb(
                "search",
                "The lines that hold a text, in a folder of the task",
                vec![
                    task(),
                    p("text", Type::Text, true, "What to find, as it is written"),
                    p("path", Type::Text, false, "A folder; the top when left out"),
                ],
                Effect::Reads,
                None,
                true,
            ),
            verb(
                "write",
                "Make a file hold a text, whole",
                vec![task(), path(), p("text", Type::Text, true, "The file's new text")],
                Effect::Own,
                Some("write"),
                false,
            ),
            verb(
                "edit",
                "Replace a text that is once in a file with another",
                vec![
                    task(),
                    path(),
                    p("old", Type::Text, true, "The text there now, once"),
                    p("new", Type::Text, true, "What it becomes"),
                ],
                Effect::Own,
                Some("edit"),
                false,
            ),
            verb(
                "remove",
                "Remove a file",
                vec![task(), path()],
                Effect::Own,
                Some("write"),
                false,
            ),
            verb(
                "run",
                "Start one of the machine's jobs (as check, test) in the task, sandboxed: answers with the job",
                vec![
                    task(),
                    p("job", Type::Text, true, "The job's name"),
                    p("package", Type::Text, false, "A package to run it for"),
                    p("filter", Type::Text, false, "Which tests"),
                ],
                Effect::Own,
                None,
                false,
            ),
            verb(
                "job",
                "A job's state and the end of its output, after waiting up to some seconds for it to end",
                vec![
                    task(),
                    p("id", Type::Number, true, "The job, as run answered"),
                    p("wait", Type::Number, false, "Seconds to wait, up to 60"),
                ],
                Effect::Reads,
                None,
                true,
            ),
            verb(
                "diff",
                "What the task changed",
                vec![task()],
                Effect::Reads,
                None,
                true,
            ),
            verb(
                "commit",
                "Commit what the task changed, on its branch",
                vec![task(), p("message", Type::Text, true, "The commit's message")],
                Effect::Own,
                Some("uncommit"),
                false,
            ),
            verb(
                "uncommit",
                "Take back the task's last commit, keeping its changes",
                vec![
                    task(),
                    p("commit", Type::Text, true, "The commit, as commit answered"),
                ],
                Effect::Own,
                None,
                false,
            ),
            verb(
                "propose",
                "Push the task's branch agent/<task> to the repository's remote, for the person to review",
                vec![task()],
                Effect::Out,
                None,
                false,
            ),
            verb(
                "close",
                "End a task: its worktree goes, its branch stays",
                vec![task()],
                Effect::Own,
                None,
                false,
            ),
        ],
    }
}

struct Job {
    task: u64,
    id: u64,
    argv: Vec<String>,
    child: Option<Child>,
    started: Option<Instant>,
}

pub struct Tasks {
    state: PathBuf,
    repos: Vec<(String, PathBuf)>,
    remote: String,
    jobs_allowed: Vec<(String, Vec<String>)>,
    sandbox: Option<Sandbox>,
    job_limit: Duration,
    task_limit: Duration,
    /// Waiting and running, one at a time on the machine.
    jobs: Vec<Job>,
}

fn ok(v: impl Into<Value>) -> verbs::Result {
    verbs::Result::ok(v.into())
}

fn err(why: impl AsRef<str>) -> verbs::Result {
    verbs::Result::error(why.as_ref())
}

/// git, with no hook and no fsmonitor run, no prompt, and the agent's name.
fn git(dir: &Path, args: &[&str]) -> Result<String, String> {
    let out = Command::new("git")
        .arg("-C")
        .arg(dir)
        .args(["-c", "core.hooksPath=/dev/null", "-c", "core.fsmonitor=false"])
        .args([
            "-c",
            "user.name=Pinnacle agent",
            "-c",
            "user.email=agent@pinnacle.invalid",
        ])
        .args(["-c", "commit.gpgsign=false"])
        .args(args)
        .env("GIT_TERMINAL_PROMPT", "0")
        .stdin(Stdio::null())
        .output()
        .map_err(|e| format!("git: {e}"))?;
    let text = String::from_utf8_lossy(&out.stdout).into_owned();
    if out.status.success() {
        Ok(text)
    } else {
        Err(String::from_utf8_lossy(&out.stderr).trim().to_string())
    }
}

/// A branch name the agent may give: an identifier, or one with `/`
/// between identifier parts (`release/1.0`).
fn branch(name: &str) -> bool {
    name.split('/')
        .all(|part| identifier(part) || part.split('.').all(identifier))
}

/// `rel` in `root`, if it stays there: relative, every part a plain name,
/// nothing of `.git`, and no symbolic link on the way.
pub fn inside(root: &Path, rel: &str) -> Result<PathBuf, String> {
    let rel = Path::new(rel);
    if rel.as_os_str().is_empty() || rel.as_os_str().len() > 4096 {
        return Err("no path".into());
    }
    let mut at = root.to_path_buf();
    for c in rel.components() {
        match c {
            Component::Normal(name) if name != ".git" => at.push(name),
            _ => return Err(format!("{} is not a path in the task", rel.display())),
        }
        if at.symlink_metadata().is_ok_and(|m| m.file_type().is_symlink()) {
            return Err(format!("{} goes through a link", rel.display()));
        }
    }
    Ok(at)
}

impl Tasks {
    pub fn new(config: &Config) -> Result<Tasks, String> {
        std::fs::create_dir_all(config.state.join("tasks")).map_err(|e| e.to_string())?;
        let state = config.state.canonicalize().map_err(|e| e.to_string())?;
        Ok(Tasks {
            state,
            repos: config.repos.clone(),
            remote: config.remote.clone(),
            jobs_allowed: config.jobs.clone(),
            sandbox: Sandbox::find(),
            job_limit: Duration::from_secs(config.job_minutes * 60),
            task_limit: Duration::from_secs(config.task_minutes * 60),
            jobs: Vec::new(),
        })
    }

    fn dir(&self, task: u64) -> PathBuf {
        self.state.join("tasks").join(task.to_string())
    }

    /// Task `task`'s folder, if `contact` opened it.
    fn owned(&self, contact: &Key, task: u64) -> Result<PathBuf, String> {
        let dir = self.dir(task);
        match std::fs::read_to_string(dir.join("owner")) {
            Ok(owner) if owner.trim() == crate::hex(contact) => Ok(dir),
            Ok(_) => Err("that task is another's".into()),
            Err(_) => Err("no such task".into()),
        }
    }

    fn meta(dir: &Path, key: &str) -> String {
        std::fs::read_to_string(dir.join(key))
            .unwrap_or_default()
            .trim()
            .to_string()
    }

    pub fn run(&mut self, contact: &Key, verb: &str, args: &Value) -> verbs::Result {
        let text = |key: &str| args.get(key).as_str().unwrap_or("").to_string();
        if verb == "repos" {
            return ok(Value::Array(
                self.repos.iter().map(|(n, _)| n.as_str().into()).collect(),
            ));
        }
        if verb == "open" {
            return self.open(contact, &text("repo"), &text("base"));
        }
        let task = args.get("task").as_u64().unwrap_or(0);
        let dir = match self.owned(contact, task) {
            Ok(dir) => dir,
            Err(why) => return err(why),
        };
        let tree = dir.join("worktree");
        if !tree.exists() && verb != "close" {
            return err("the task is closed");
        }
        match verb {
            "files" => self.files(&tree, &text("path")),
            "read" => {
                let from = args.get("from").as_u64().unwrap_or(1).max(1) as usize;
                let lines = args.get("lines").as_u64().unwrap_or(2000) as usize;
                match inside(&tree, &text("path")).and_then(|p| std::fs::read(&p).map_err(|e| e.to_string()))
                {
                    Ok(bytes) => {
                        let text = String::from_utf8_lossy(&bytes);
                        let part: Vec<&str> = text.lines().skip(from - 1).take(lines).collect();
                        let mut out = part.join("\n");
                        if out.len() > READ_MAX {
                            out.truncate(out.floor_char_boundary(READ_MAX));
                            out += "\n… (more: read from a later line)";
                        }
                        ok(out)
                    }
                    Err(why) => err(why),
                }
            }
            "search" => self.search(&tree, &text("text"), &text("path")),
            "write" => self.write(&tree, task, &text("path"), Some(text("text"))),
            "remove" => self.write(&tree, task, &text("path"), None),
            "edit" => {
                let (old, new) = (text("old"), text("new"));
                let path = match inside(&tree, &text("path")) {
                    Ok(p) => p,
                    Err(why) => return err(why),
                };
                let Ok(content) = std::fs::read_to_string(&path) else {
                    return err("no such file, or not text");
                };
                match content.matches(&old).count() {
                    1 if !old.is_empty() => {
                        let changed = content.replacen(&old, &new, 1);
                        match std::fs::write(&path, changed) {
                            Ok(()) => ok("edited").undone_by(
                                "edit",
                                Value::object([
                                    ("task", task.into()),
                                    ("path", text("path").into()),
                                    ("old", new.into()),
                                    ("new", old.into()),
                                ]),
                            ),
                            Err(e) => err(e.to_string()),
                        }
                    }
                    0 => err("the old text is not in the file"),
                    n => err(format!("the old text is in the file {n} times: give more of it")),
                }
            }
            "run" => self.start_job(&dir, task, &text("job"), &text("package"), &text("filter")),
            // `job` with a wait is answered by the caller's loop
            // (`Tasks::waiting`), which does not stop for it.
            "job" => self.job(&dir, task, args.get("id").as_u64().unwrap_or(0)),
            "diff" => {
                let status = git(&tree, &["status", "--porcelain", "--untracked-files=all"]);
                let diff = git(&tree, &["diff", "HEAD", "--stat", "--patch"]);
                match (status, diff) {
                    (Ok(status), Ok(diff)) => {
                        let mut out = format!("{status}\n{diff}");
                        if out.len() > READ_MAX {
                            out.truncate(out.floor_char_boundary(READ_MAX));
                            out += "\n… (cut)";
                        }
                        ok(out)
                    }
                    (Err(e), _) | (_, Err(e)) => err(e),
                }
            }
            "commit" => {
                let message = text("message");
                if message.trim().is_empty() {
                    return err("a commit needs a message");
                }
                let made = git(&tree, &["add", "--all"])
                    .and_then(|_| git(&tree, &["commit", "--no-verify", "-m", &message]))
                    .and_then(|_| git(&tree, &["rev-parse", "HEAD"]));
                match made {
                    Ok(sha) => {
                        let sha = sha.trim().to_string();
                        ok(sha.clone()).undone_by(
                            "uncommit",
                            Value::object([("task", task.into()), ("commit", sha.into())]),
                        )
                    }
                    Err(e) => err(e),
                }
            }
            "uncommit" => {
                // Only the commit named, and only while it is the newest.
                let head = git(&tree, &["rev-parse", "HEAD"]).unwrap_or_default();
                let base = Self::meta(&dir, "base-commit");
                if head.trim() != text("commit") || head.trim() == base {
                    return err("that is not the task's newest commit");
                }
                match git(&tree, &["reset", "--soft", "HEAD~1"]) {
                    Ok(_) => ok("taken back, its changes kept"),
                    Err(e) => err(e),
                }
            }
            "propose" => {
                let repo = Self::meta(&dir, "repo");
                let branch = format!("agent/{task}");
                // Only this branch, to the remote the owner named.
                let refspec = format!("refs/heads/{branch}:refs/heads/{branch}");
                let Some((_, clone)) = self.repos.iter().find(|(n, _)| *n == repo) else {
                    return err("its repository is gone");
                };
                match git(clone, &["push", "--no-verify", &self.remote, &refspec]) {
                    Ok(_) => ok(format!("{branch} pushed to {repo}'s {}", self.remote)),
                    Err(e) => err(e),
                }
            }
            "close" => {
                let repo = Self::meta(&dir, "repo");
                if let Some((_, clone)) = self.repos.iter().find(|(n, _)| *n == repo)
                    && tree.exists()
                {
                    let _ = git(
                        clone,
                        &["worktree", "remove", "--force", &tree.display().to_string()],
                    );
                }
                let _ = std::fs::remove_dir_all(dir.join("target"));
                ok(format!("closed; its branch agent/{task} stays"))
            }
            _ => err("no such verb"),
        }
    }

    fn open(&mut self, contact: &Key, repo: &str, base: &str) -> verbs::Result {
        let Some((_, clone)) = self.repos.iter().find(|(n, _)| n == repo).cloned() else {
            return err(format!("no repository “{repo}”: repos lists them"));
        };
        if !branch(base) {
            return err("the base is not a branch's name");
        }
        let next = std::fs::read_dir(self.state.join("tasks"))
            .map(|d| {
                d.filter_map(|e| e.ok()?.file_name().to_str()?.parse::<u64>().ok())
                    .max()
                    .unwrap_or(0)
            })
            .unwrap_or(0)
            + 1;
        let dir = self.dir(next);
        let tree = dir.join("worktree");
        if let Err(e) = std::fs::create_dir_all(dir.join("target")) {
            return err(e.to_string());
        }
        let branch = format!("agent/{next}");
        let made = git(
            &clone,
            &[
                "worktree",
                "add",
                "-b",
                &branch,
                &tree.display().to_string(),
                base,
            ],
        )
        .and_then(|_| git(&tree, &["rev-parse", "HEAD"]));
        match made {
            Ok(sha) => {
                for (key, value) in [
                    ("owner", crate::hex(contact)),
                    ("repo", repo.into()),
                    ("base-commit", sha),
                ] {
                    let _ = std::fs::write(dir.join(key), value.trim());
                }
                ok(next).undone_by("close", Value::object([("task", next.into())]))
            }
            Err(e) => {
                let _ = std::fs::remove_dir_all(&dir);
                err(e)
            }
        }
    }

    fn files(&self, tree: &Path, rel: &str) -> verbs::Result {
        let dir = if rel.is_empty() || rel == "." {
            Ok(tree.to_path_buf())
        } else {
            inside(tree, rel)
        };
        let entries = dir.and_then(|d| std::fs::read_dir(d).map_err(|e| e.to_string()));
        match entries {
            Ok(entries) => {
                let mut names: Vec<String> = entries
                    .filter_map(|e| {
                        let e = e.ok()?;
                        let name = e.file_name().to_str()?.to_string();
                        if name == ".git" {
                            return None;
                        }
                        Some(if e.file_type().ok()?.is_dir() {
                            name + "/"
                        } else {
                            name
                        })
                    })
                    .collect();
                names.sort();
                ok(Value::Array(names.into_iter().map(Value::from).collect()))
            }
            Err(why) => err(why),
        }
    }

    fn search(&self, tree: &Path, needle: &str, rel: &str) -> verbs::Result {
        if needle.is_empty() {
            return err("search for some text");
        }
        let start = if rel.is_empty() {
            Ok(tree.to_path_buf())
        } else {
            inside(tree, rel)
        };
        let Ok(start) = start else {
            return err("not a folder in the task");
        };
        let mut found = Vec::new();
        let mut stack = vec![start];
        while let Some(dir) = stack.pop() {
            let Ok(entries) = std::fs::read_dir(&dir) else {
                continue;
            };
            let mut entries: Vec<_> = entries.filter_map(Result::ok).collect();
            entries.sort_by_key(|e| e.file_name());
            for e in entries {
                let name = e.file_name();
                let Ok(kind) = e.file_type() else { continue };
                if name == ".git" || name == "target" || kind.is_symlink() {
                    continue;
                }
                if kind.is_dir() {
                    stack.push(e.path());
                    continue;
                }
                let Ok(text) = std::fs::read_to_string(e.path()) else {
                    continue;
                };
                let shown = e
                    .path()
                    .strip_prefix(tree)
                    .map(|p| p.display().to_string())
                    .unwrap_or_default();
                for (n, line) in text.lines().enumerate() {
                    if line.contains(needle) {
                        let line: String = line.chars().take(200).collect();
                        found.push(Value::from(format!("{shown}:{}: {line}", n + 1)));
                        if found.len() >= SEARCH_MAX {
                            return ok(Value::Array(found));
                        }
                    }
                }
            }
        }
        ok(Value::Array(found))
    }

    /// A file written whole (`text`), or removed (None); undone by writing
    /// back what was there, or removing what was not.
    fn write(&self, tree: &Path, task: u64, rel: &str, text: Option<String>) -> verbs::Result {
        let path = match inside(tree, rel) {
            Ok(p) => p,
            Err(why) => return err(why),
        };
        let before = std::fs::read_to_string(&path).ok();
        if path.exists() && before.is_none() {
            return err("not a text file");
        }
        let done = match &text {
            Some(text) => path
                .parent()
                .map_or(Ok(()), std::fs::create_dir_all)
                .and_then(|()| std::fs::write(&path, text)),
            None => std::fs::remove_file(&path),
        };
        if let Err(e) = done {
            return err(e.to_string());
        }
        let undo = match before {
            Some(old) => (
                "write",
                Value::object([("task", task.into()), ("path", rel.into()), ("text", old.into())]),
            ),
            None => (
                "remove",
                Value::object([("task", task.into()), ("path", rel.into())]),
            ),
        };
        ok(if text.is_some() { "written" } else { "removed" }).undone_by(undo.0, undo.1)
    }

    fn start_job(&mut self, dir: &Path, task: u64, name: &str, package: &str, filter: &str) -> verbs::Result {
        if self.sandbox.is_none() {
            return err("this machine has no sandbox, so it runs no jobs");
        }
        let Some((_, argv)) = self.jobs_allowed.iter().find(|(n, _)| n == name) else {
            let names: Vec<&str> = self.jobs_allowed.iter().map(|(n, _)| n.as_str()).collect();
            return err(format!("no job “{name}”: there are {}", names.join(", ")));
        };
        for (what, value) in [("package", package), ("filter", filter)] {
            if !value.is_empty() && !identifier(value) {
                return err(format!("the {what} is not a name"));
            }
        }
        let used = Duration::from_secs(Self::meta(dir, "seconds").parse().unwrap_or(0));
        if used >= self.task_limit {
            return err("the task has used its minutes of jobs");
        }
        let mut full = Vec::new();
        for word in argv {
            match word.as_str() {
                "{package}" if !package.is_empty() => full.extend(["-p".to_string(), package.to_string()]),
                "{filter}" if !filter.is_empty() => full.push(filter.to_string()),
                "{package}" | "{filter}" => {}
                w => full.push(w.to_string()),
            }
        }
        let id = std::fs::read_dir(dir.join("jobs"))
            .map(|d| {
                d.filter_map(|e| e.ok()?.path().file_stem()?.to_str()?.parse::<u64>().ok())
                    .max()
                    .unwrap_or(0)
            })
            .unwrap_or(0)
            + 1;
        let _ = std::fs::create_dir_all(dir.join("jobs"));
        let _ = std::fs::write(dir.join("jobs").join(format!("{id}.state")), "waiting");
        self.jobs.push(Job {
            task,
            id,
            argv: full,
            child: None,
            started: None,
        });
        self.tick();
        ok(id)
    }

    /// Starts the next job when none runs; ends one past its time.
    pub fn tick(&mut self) {
        let Some(sandbox) = self.sandbox else { return };
        // The one running: ended, or past its time.
        if let Some(i) = self.jobs.iter().position(|j| j.child.is_some()) {
            let job = &mut self.jobs[i];
            let dir = self.state.join("tasks").join(job.task.to_string());
            let late = job.started.is_some_and(|s| s.elapsed() > self.job_limit);
            // Output past its bound stops it too.
            let log = dir.join("jobs").join(format!("{}.log", job.id));
            let loud = std::fs::metadata(&log).is_ok_and(|m| m.len() > OUTPUT_MAX);
            let child = job.child.as_mut().unwrap();
            let ended = match child.try_wait() {
                Ok(Some(status)) => Some(
                    status
                        .code()
                        .map_or("ended by a signal".to_string(), |c| format!("exit {c}")),
                ),
                Ok(None) if late || loud => {
                    let _ = child.kill();
                    let _ = child.wait();
                    Some(
                        if late {
                            "stopped: past its time"
                        } else {
                            "stopped: too much output"
                        }
                        .into(),
                    )
                }
                Ok(None) => None,
                Err(e) => Some(format!("lost: {e}")),
            };
            let Some(ended) = ended else { return };
            let seconds = job.started.map_or(0, |s| s.elapsed().as_secs());
            let used: u64 = Self::meta(&dir, "seconds").parse().unwrap_or(0);
            let _ = std::fs::write(dir.join("seconds"), (used + seconds).to_string());
            let _ = std::fs::write(dir.join("jobs").join(format!("{}.state", job.id)), ended);
            self.jobs.remove(i);
        }
        // The next waiting.
        let Some(job) = self.jobs.first_mut() else { return };
        let dir = self.state.join("tasks").join(job.task.to_string());
        let log = dir.join("jobs").join(format!("{}.log", job.id));
        let output = std::fs::File::create(&log);
        let spawned = output.and_then(|out| {
            let err = out.try_clone()?;
            sandbox
                .command(&job.argv, &dir.join("worktree"), &dir.join("target"))
                .stdin(Stdio::null())
                .stdout(out)
                .stderr(err)
                .spawn()
        });
        let state = dir.join("jobs").join(format!("{}.state", job.id));
        match spawned {
            Ok(child) => {
                println!(
                    "workbench: task {} job {}: {}",
                    job.task,
                    job.id,
                    job.argv.join(" ")
                );
                let _ = std::fs::write(&state, "running");
                job.child = Some(child);
                job.started = Some(Instant::now());
            }
            Err(e) => {
                let _ = std::fs::write(&state, format!("could not start: {e}"));
                self.jobs.remove(0);
            }
        }
    }

    /// How long to hold a `job` call before answering it: until the job
    /// ends, or the seconds asked for (at most a minute) pass. None to
    /// answer at once.
    pub fn waiting(&self, contact: &Key, args: &Value) -> Option<Instant> {
        let task = args.get("task").as_u64()?;
        let id = args.get("id").as_u64()?;
        let wait = args.get("wait").as_u64().unwrap_or(0).min(WAIT_MAX);
        let dir = self.owned(contact, task).ok()?;
        (wait > 0 && self.running(&dir, task, id)).then(|| Instant::now() + Duration::from_secs(wait))
    }

    /// Whether job `id` of `task` still waits or runs.
    pub fn running(&self, dir: &Path, task: u64, id: u64) -> bool {
        let state = std::fs::read_to_string(dir.join("jobs").join(format!("{id}.state"))).unwrap_or_default();
        (state == "running" || state == "waiting") && self.jobs.iter().any(|j| j.task == task && j.id == id)
    }

    pub fn task_dir(&self, contact: &Key, task: u64) -> Option<PathBuf> {
        self.owned(contact, task).ok()
    }

    fn job(&self, dir: &Path, task: u64, id: u64) -> verbs::Result {
        let state = std::fs::read_to_string(dir.join("jobs").join(format!("{id}.state"))).unwrap_or_default();
        if state.is_empty() {
            return err("no such job");
        }
        // Waiting or running in its file, but not here: the workbench
        // restarted under it.
        let busy = state == "running" || state == "waiting";
        let state = if busy && !self.jobs.iter().any(|j| j.task == task && j.id == id) {
            "lost: the workbench restarted".to_string()
        } else {
            state
        };
        let log = std::fs::read(dir.join("jobs").join(format!("{id}.log"))).unwrap_or_default();
        let tail = &log[log.len().saturating_sub(8 * 1024)..];
        ok(Value::object([
            ("state", state.into()),
            ("output", String::from_utf8_lossy(tail).into_owned().into()),
        ]))
    }
}

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

    #[test]
    fn paths_stay_in_the_task() {
        let root = std::env::temp_dir().join(format!("wb-inside-{}", std::process::id()));
        std::fs::create_dir_all(root.join("src")).unwrap();
        assert!(inside(&root, "src/main.rs").is_ok());
        assert!(inside(&root, "new/dir/file").is_ok());
        for bad in [
            "",
            "/etc/passwd",
            "../x",
            "src/../../x",
            ".git/config",
            "a/.git/hooks",
            "./x",
        ] {
            assert!(inside(&root, bad).is_err(), "{bad}");
        }
        #[cfg(unix)]
        {
            std::os::unix::fs::symlink("/etc", root.join("out")).unwrap();
            assert!(inside(&root, "out/passwd").is_err());
        }
        std::fs::remove_dir_all(&root).unwrap();
    }

    #[test]
    fn branches() {
        for good in ["main", "release/1.0", "session/s855"] {
            assert!(branch(good), "{good}");
        }
        for bad in ["-x", "a..b", "a b", "", "x;y", "/main", "--force"] {
            assert!(!branch(bad), "{bad}");
        }
    }

    #[test]
    fn the_description_is_whole() {
        let d = description();
        for v in &d.verbs {
            if let Some(inverse) = &v.inverse {
                assert!(
                    d.verb(inverse).is_some(),
                    "{} undone by no verb {inverse}",
                    v.name
                );
            }
        }
        assert_eq!(d.verb("propose").unwrap().effect, Effect::Out);
        assert!(d.verbs.iter().filter(|v| v.effect == Effect::Out).count() == 1);
    }
}