Cotton code
735 lines · 28.6 KB · RustRaw
//! The Mac's meetings job: the queue that//! `meetings-transcribe --queue` drains by hand, drained by launchd on its own.//!//! launchd wakes `meetings-job wake` every few minutes (the plist's//! `StartInterval`, the meetings job's launchd plist template, rendered//! by `pnpm -s meetings:job:install`). A wake is cheap until there is work://!//! 1. One run at a time: a second wake while one runs stops at [`RunLock`].//! 2. A wake inside a back-off ([`backoff`]) or while a build holds this Mac//!    (the machine-wide build lock's slots, [`build_busy`]) does nothing.//! 3. The sign-in is looked at ([`signed_in`]): the device credential's file//!    and the key file, never their contents said anywhere.//! 4. A new recording is noticed by asking the object what changed in//!    `meetings_meeting` since the version the last run saw ([`probe`]: one//!    `GET /v1/sync`, sealed rows counted, never opened). Nothing changed and//!    no sweep due ([`Schedule::sweep_s`], hourly): the wake ends there.//! 5. Then the run: the models ([`crate::meetings::Engine::check`]), this Mac//!    opened as its device, the queue drained and the summaries written, as//!    `meetings-transcribe --queue` does.//!//! A failure backs off (5 minutes, doubling, at most an hour); a refusal//! (sign-in or models missing) says which in `meetings:job:status`. The log//! ([`Log`], rotated at 1 MiB, three kept) holds ids, durations, counts and//! reason codes only: a meeting's words, names or summary never reach it.use std::fs::{File, OpenOptions};use std::io::Write;use std::path::{Path, PathBuf};use serde::{Deserialize, Serialize};use serde_json::Value;use crate::meetings::{Drained, Engine, MEETING};use crate::summarise::Summarised;pub const LABEL: &str = "com.cottondb.meetings-job";/// When the job runs.#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]pub struct Schedule {    /// launchd's wake (the plist's `StartInterval`), said in the status line.    pub wake_s: i64,    /// A run even when nothing seems new: a recording set waiting again, a    /// phone that gave one back, anything the probe could not see.    pub sweep_s: i64,    /// The first back-off after a failure; it doubles to `backoff_max_s`.    pub backoff_s: i64,    pub backoff_max_s: i64,}impl Default for Schedule {    fn default() -> Self {        Schedule { wake_s: 300, sweep_s: 3600, backoff_s: 300, backoff_max_s: 3600 }    }}/// What the installer wrote (`~/.cottondb/meetings-job/config.json`): paths/// and flags only. The credential is named by its file, never held here.#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]pub struct Config {    pub base: String,    pub device_id: String,    pub token_file: PathBuf,    #[serde(default)]    pub key_file: Option<PathBuf>,    /// The Python holding sherpa-onnx.    pub python: PathBuf,    /// The one models folder, in the `pnpm voice:fetch` layout.    pub models: PathBuf,    /// The checkout whose `scripts/meetings/engine.py` and catalogue the job reads.    pub repo: PathBuf,    #[serde(default)]    pub languages: Vec<String>,    #[serde(default = "yes")]    pub summaries: bool,    #[serde(default)]    pub summary_model: Option<String>,    #[serde(default)]    pub llama_server: Option<PathBuf>,    #[serde(default = "twenty")]    pub most: usize,    #[serde(default)]    pub schedule: Schedule,    /// The machine-wide build lock a wake waits behind; none, `$BUILD_LOCK_DIR`    /// else `/tmp/tinmen-build.lock` ([`build_lock_dir`]).    #[serde(default)]    pub build_lock: Option<PathBuf>,    /// The job's own folder: state, lock.    pub home: PathBuf,    pub log: PathBuf,}fn yes() -> bool {    true}fn twenty() -> usize {    20}impl Config {    pub fn read(path: &Path) -> Result<Config, String> {        let body = std::fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))?;        serde_json::from_str(&body).map_err(|e| format!("{}: {e}", path.display()))    }    /// The engine as this job runs it. The models folder, the Python and the    /// repo reach the engine and the summariser through their environment, as    /// a hand run's do; [`Config::export`] sets them.    pub fn engine(&self) -> Engine {        Engine {            python: self.python.clone(),            script: self.repo.join("scripts/meetings/engine.py"),            languages: self.languages.clone(),            threads: 4,            per_line_language: None,            place: "mac".into(),        }    }    /// The environment a hand run is given, set once at the start of the process.    pub fn export(&self) {        std::env::set_var("MEETINGS_MODELS", &self.models);        std::env::set_var("MEETINGS_PYTHON", &self.python);        std::env::set_var("COTTON_REPO", &self.repo);        if let Some(bin) = &self.llama_server {            std::env::set_var("LLAMA_SERVER", bin);        }    }    fn device(&self) -> crate::device::DeviceArgs {        crate::device::DeviceArgs {            base: Some(self.base.trim_end_matches('/').to_string()),            device_id: Some(self.device_id.clone()),            token_file: Some(self.token_file.clone()),            key_file: self.key_file.clone(),            data_dir: None,        }    }    pub fn state_path(&self) -> PathBuf {        self.home.join("state.json")    }}/// Why the job would not run, said in the status line.#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]pub struct Refusal {    /// `sign_in` or `models`.    pub kind: String,    pub why: String,}impl Refusal {    fn sign_in(why: impl Into<String>) -> Refusal {        Refusal { kind: "sign_in".into(), why: why.into() }    }    fn models(why: impl Into<String>) -> Refusal {        Refusal { kind: "models".into(), why: why.into() }    }    pub fn said(&self) -> String {        match self.kind.as_str() {            "models" => format!("models missing: {}", self.why),            _ => format!("not signed in: {}", self.why),        }    }}/// What one run did, in counts.#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]pub struct Counts {    pub transcribed: usize,    pub failed: usize,    /// Left waiting (a phone claimed it first).    pub left: usize,    pub summarised: usize,}/// The job's memory between wakes (`state.json`).#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]pub struct State {    /// The object's sync version the last run started from.    #[serde(default)]    pub version: Option<i64>,    #[serde(default)]    pub last_wake: Option<i64>,    /// When a run (sweep or new recording) last started.    #[serde(default)]    pub last_run: Option<i64>,    #[serde(default)]    pub last_ok: Option<i64>,    #[serde(default)]    pub last_counts: Option<Counts>,    #[serde(default)]    pub failures: u32,    #[serde(default)]    pub next_try: Option<i64>,    #[serde(default)]    pub failed: Option<String>,    #[serde(default)]    pub refused: Option<Refusal>,    /// The quiet reason last logged (a back-off, a build), so a wake every    /// five minutes says it once, not every time.    #[serde(default)]    pub said: Option<String>,}impl State {    pub fn load(path: &Path) -> State {        std::fs::read_to_string(path).ok().and_then(|b| serde_json::from_str(&b).ok()).unwrap_or_default()    }    pub fn save(&self, path: &Path) -> Result<(), String> {        let body = serde_json::to_string_pretty(self).map_err(|e| e.to_string())?;        let tmp = path.with_extension("json.tmp");        std::fs::write(&tmp, body).map_err(|e| format!("{}: {e}", tmp.display()))?;        std::fs::rename(&tmp, path).map_err(|e| format!("{}: {e}", path.display()))    }}// ── the schedule ────────────────────────────────────────────────────────────/// What a wake does before it asks the object anything.#[derive(Debug, Clone, PartialEq, Eq)]pub enum Gate {    /// Nothing now, for this reason.    Wait(String),    /// A run whatever the probe says: the sweep is due (or asked for).    Sweep,    /// A run only when the probe sees something new.    Probe,}/// The back-off after `failures` failures in a row: `backoff_s`, doubling, at most `backoff_max_s`.pub fn backoff(failures: u32, s: &Schedule) -> i64 {    let doublings = failures.saturating_sub(1).min(30);    s.backoff_s.saturating_mul(1i64 << doublings).min(s.backoff_max_s)}/// The wake's first decision. `forced` is a run asked for by hand/// (`pnpm meetings:job:run`): it skips the back-off and the build's wait./// A clock that went backwards (a reboot, a changed zone) makes the sweep due.pub fn gate(state: &State, now: i64, s: &Schedule, build_busy: bool, forced: bool) -> Gate {    if forced {        return Gate::Sweep;    }    if let Some(next) = state.next_try {        if now < next && next - now <= s.backoff_max_s {            return Gate::Wait(format!("backing off after {} failure{}", state.failures, if state.failures == 1 { "" } else { "s" }));        }    }    if build_busy {        return Gate::Wait("a build holds this Mac".into());    }    match state.last_run {        Some(last) if now >= last && now - last < s.sweep_s => Gate::Probe,        _ => Gate::Sweep,    }}/// Whether the probe saw something new: a row changed since the last run's/// version, a first run, or an object whose version went back (a new database).pub fn changed(state: &State, version: Option<i64>, rows: usize) -> bool {    match (state.version, version) {        (None, _) => true,        (Some(old), Some(now)) if now < old => true,        _ => rows > 0,    }}/// A failed wake: counted, and the next try pushed back.pub fn failed(state: &mut State, now: i64, s: &Schedule, why: String, refused: Option<Refusal>) {    state.failures = state.failures.saturating_add(1);    state.next_try = Some(now + backoff(state.failures, s));    state.failed = Some(why);    state.refused = refused;    state.said = None;}/// A run that went through: the back-off cleared, the version kept.pub fn succeeded(state: &mut State, now: i64, version: Option<i64>, counts: Counts) {    state.failures = 0;    state.next_try = None;    state.failed = None;    state.refused = None;    state.said = None;    state.last_ok = Some(now);    state.last_counts = Some(counts);    if version.is_some() {        state.version = version;    }}// ── one run at a time ───────────────────────────────────────────────────────/// The job's lock, held for the whole run and let go when the process ends/// however it ends (an advisory lock on `run.lock`, never a file left behind).pub struct RunLock(#[allow(dead_code)] File);/// The lock, or `None` when another run holds it.pub fn lock(home: &Path) -> Result<Option<RunLock>, String> {    std::fs::create_dir_all(home).map_err(|e| format!("{}: {e}", home.display()))?;    let path = home.join("run.lock");    let file = OpenOptions::new().create(true).truncate(false).write(true).open(&path).map_err(|e| format!("{}: {e}", path.display()))?;    match file.try_lock() {        Ok(()) => Ok(Some(RunLock(file))),        Err(std::fs::TryLockError::WouldBlock) => Ok(None),        Err(std::fs::TryLockError::Error(e)) => Err(format!("{}: {e}", path.display())),    }}/// The machine-wide build lock's address (`scripts/with-build-lock.sh`).pub fn build_lock_dir() -> PathBuf {    std::env::var_os("BUILD_LOCK_DIR").map(PathBuf::from).unwrap_or_else(|| PathBuf::from("/tmp/tinmen-build.lock"))}/// Whether a build holds either of this Mac's build slots: a slot whose/// holder is alive, or one just being taken (no pid yet, under five minutes old).pub fn build_busy(lock_dir: &Path) -> bool {    let second = PathBuf::from(format!("{}.slot-2", lock_dir.display()));    [lock_dir.to_path_buf(), second].iter().any(|slot| {        if !slot.is_dir() {            return false;        }        match std::fs::read_to_string(slot.join("pid")).ok().and_then(|p| p.trim().parse::<i32>().ok()) {            Some(pid) => alive(pid),            None => slot.metadata().and_then(|m| m.modified()).ok().and_then(|t| t.elapsed().ok()).is_some_and(|age| age.as_secs() < 300),        }    })}fn alive(pid: i32) -> bool {    if pid <= 0 {        return false;    }    // SAFETY: kill with signal 0 sends nothing; it only asks whether the pid exists.    let answer = unsafe { libc::kill(pid, 0) };    answer == 0 || std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM)}// ── the log ─────────────────────────────────────────────────────────────────/// The job's log: one line a fact, rotated at `max` bytes with `keep` old files/// (`.1` the newest). Only this module writes it, from ids, durations, counts/// and reason codes.pub struct Log {    pub path: PathBuf,    pub max: u64,    pub keep: usize,}impl Log {    pub fn new(path: &Path) -> Log {        Log { path: path.to_path_buf(), max: 1 << 20, keep: 3 }    }    fn rotate(&self) {        let size = std::fs::metadata(&self.path).map(|m| m.len()).unwrap_or(0);        if size < self.max {            return;        }        let old = |n: usize| PathBuf::from(format!("{}.{n}", self.path.display()));        let _ = std::fs::remove_file(old(self.keep));        for n in (1..self.keep).rev() {            let _ = std::fs::rename(old(n), old(n + 1));        }        let _ = std::fs::rename(&self.path, old(1));    }    pub fn say(&self, line: &str) {        if let Some(dir) = self.path.parent() {            let _ = std::fs::create_dir_all(dir);        }        self.rotate();        let at = chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true);        if let Ok(mut f) = OpenOptions::new().create(true).append(true).open(&self.path) {            let _ = writeln!(f, "{at} {}", one_line(line));        }    }}/// A sentence from elsewhere (an error) made one short line.pub fn one_line(said: &str) -> String {    let first = said.lines().map(str::trim).find(|l| !l.is_empty()).unwrap_or("");    first.chars().take(400).collect()}/// A reason as a code (`engine_failed`, `model_missing`), or `other`: a/// reason that is not a plain code is never written as it came.pub fn code(why: Option<&str>) -> &str {    match why {        Some(w) if !w.is_empty() && w.len() <= 40 && w.bytes().all(|b| b.is_ascii_lowercase() || b == b'_' || b.is_ascii_digit()) => w,        Some(_) => "other",        None => "",    }}/// A row id as the log may say it: an id, never a sentence.fn id_of(id: &str) -> String {    let id: String = id.chars().filter(|c| c.is_ascii_alphanumeric() || *c == '-' || *c == '_').take(64).collect();    if id.is_empty() {        "?".into()    } else {        id    }}/// One transcribed meeting's log line: id, outcome, counts, seconds.pub fn drained_line(d: &Drained) -> String {    let mut line = format!("meeting {} {}", id_of(&d.meeting), code(Some(&d.status)));    if let Some(why) = d.why.as_deref() {        line.push_str(&format!(" ({})", code(Some(why))));    }    if d.status == "ready" {        line.push_str(&format!(" lines={} speakers={}", d.lines, d.speakers));    }    if let Some(t) = &d.took {        line.push_str(&format!(" audio={:.1}s took={:.1}s windows={}", t.audio_s, t.wall_s, t.windows));    }    line}/// One summarised meeting's log line.pub fn summarised_line(s: &Summarised) -> String {    let mut line = format!("meeting {} {}", id_of(&s.meeting), if s.done { "summarised" } else { "not_summarised" });    if let Some(why) = s.why.as_deref() {        line.push_str(&format!(" ({})", code(Some(why))));    }    if s.done {        line.push_str(&format!(" actions={}", s.actions));    }    if let Some(t) = &s.took {        line.push_str(&format!(" took={:.1}s parts={}", t.seconds, t.parts));    }    line}// ── the checks ──────────────────────────────────────────────────────────────/// This Mac's sign-in, by its files: the device credential `seal-device`/// kept, and the key file when one is named. The credential is read only to/// tell a device's from an assistant's; it is never said, copied or logged.pub fn signed_in(cfg: &Config) -> Result<(), Refusal> {    if cfg.base.trim().is_empty() || cfg.device_id.trim().is_empty() {        return Err(Refusal::sign_in("the job names no object or device id (reinstall with --base and --device-id)"));    }    // What is wrong with the credential's file, said after its path; what it holds is never formatted.    let problem = match std::fs::read_to_string(&cfg.token_file) {        Err(_) => Some("holds no device credential (sign this Mac in with seal-device)"),        Ok(held) if held.trim().is_empty() => Some("is empty (sign this Mac in with seal-device)"),        Ok(held) if held.trim().starts_with("ctn_") => Some("holds an assistant's token, not this Mac's device credential"),        Ok(_) => None,    };    if let Some(problem) = problem {        return Err(Refusal::sign_in(format!("{} {problem}", cfg.token_file.display())));    }    if let Some(vault_file) = &cfg.key_file {        if std::fs::metadata(vault_file).map(|m| m.len() == 0).unwrap_or(true) {            let place = vault_file.display().to_string();            return Err(Refusal::sign_in(format!("no vault key at {place}")));        }    }    Ok(())}/// The models a run reads, by the engine's own check (`engine.py check`).pub fn models_held(cfg: &Config) -> Result<(), Refusal> {    if !cfg.models.is_dir() {        return Err(Refusal::models(format!("no models folder at {}", cfg.models.display())));    }    // The engine's own sentence, without its fetch hint: the status line names what and where.    cfg.engine().check().map(|_| ()).map_err(|why| Refusal::models(one_line(why.split(": pnpm voice:fetch").next().unwrap_or(&why))))}/// What changed in `meetings_meeting` since `since`: the object's version and/// how many rows (sealed, counted, never opened). One `GET /v1/sync`.pub fn probe(cfg: &Config, since: i64) -> Result<(Option<i64>, usize), crate::object::ObjectError> {    let token = std::fs::read_to_string(&cfg.token_file).map_err(|_| crate::object::ObjectError::SignedOut)?.trim().to_string();    let object = crate::object::ObjectClient::new(cfg.base.trim_end_matches('/'), Some(token))?;    let mut version = None;    let mut rows = 0usize;    let mut cursor: Option<String> = None;    loop {        let page: Value = object.sync_page(since.max(0), &[MEETING], cursor.as_deref())?;        rows += page["rows"].as_array().map(Vec::len).unwrap_or(0);        if let Some(v) = page["version"].as_i64() {            version = Some(v);        }        match page["next"].as_str() {            Some(next) if !next.is_empty() && rows < 50_000 => cursor = Some(next.to_string()),            _ => break,        }    }    Ok((version, rows))}// ── a wake ──────────────────────────────────────────────────────────────────pub fn now() -> i64 {    chrono::Utc::now().timestamp()}/// What a wake ended as, for the process's exit code.#[derive(Debug, Clone, PartialEq, Eq)]pub enum Woke {    /// Nothing to do, or done.    Quiet,    Ran(Counts),    Failed(String),    Refused(Refusal),}impl Woke {    pub fn exit(&self) -> u8 {        match self {            Woke::Quiet | Woke::Ran(_) => 0,            Woke::Failed(_) => 1,            Woke::Refused(_) => 3,        }    }}/// Say a quiet reason once.fn quiet(log: &Log, state: &mut State, why: &str) {    if state.said.as_deref() != Some(why) {        log.say(&format!("wake: {why}; nothing now"));        state.said = Some(why.to_string());    }}/// One wake, as launchd starts it (`forced` when asked for by hand).pub fn wake(cfg: &Config, forced: bool) -> Woke {    let log = Log::new(&cfg.log);    let _lock = match lock(&cfg.home) {        Ok(Some(lock)) => lock,        Ok(None) => {            log.say("wake: another run holds the job; this one stops");            return Woke::Quiet;        }        Err(why) => {            log.say(&format!("wake: the lock could not be taken: {}", one_line(&why)));            return Woke::Failed(why);        }    };    let state_path = cfg.state_path();    let mut state = State::load(&state_path);    let now = now();    state.last_wake = Some(now);    let woke = wake_locked(cfg, &log, &mut state, now, forced);    if let Err(why) = state.save(&state_path) {        log.say(&format!("wake: the state could not be kept: {}", one_line(&why)));    }    woke}fn wake_locked(cfg: &Config, log: &Log, state: &mut State, now: i64, forced: bool) -> Woke {    let s = cfg.schedule;    let builds = cfg.build_lock.clone().unwrap_or_else(build_lock_dir);    let gate = gate(state, now, &s, build_busy(&builds), forced);    if let Gate::Wait(why) = &gate {        quiet(log, state, why);        return Woke::Quiet;    }    let refuse = |state: &mut State, refusal: Refusal| {        if state.refused.as_ref() != Some(&refusal) {            log.say(&format!("refused: {}", refusal.said()));        }        failed(state, now, &s, refusal.said(), Some(refusal.clone()));        Woke::Refused(refusal)    };    if let Err(refusal) = signed_in(cfg) {        return refuse(state, refusal);    }    let (version, rows) = match probe(cfg, state.version.unwrap_or(0)) {        Ok(found) => found,        Err(crate::object::ObjectError::SignedOut) => return refuse(state, Refusal::sign_in("the object refused this Mac's device credential (sign it in again with seal-device)")),        Err(why) => {            let why = format!("the object did not answer: {}", one_line(&why.to_string()));            log.say(&format!("failed: {why}; next try in {} min", backoff(state.failures + 1, &s) / 60));            failed(state, now, &s, why.clone(), None);            return Woke::Failed(why);        }    };    let new = changed(state, version, rows);    if gate == Gate::Probe && !new {        state.said = None;        return Woke::Quiet;    }    if let Err(refusal) = models_held(cfg) {        return refuse(state, refusal);    }    let device = match cfg.device().open() {        Ok(device) => device,        Err(why) => return refuse(state, Refusal::sign_in(one_line(&why))),    };    state.last_run = Some(now);    let started = std::time::Instant::now();    log.say(&format!("run: {} ({} changed row{})", if new { "new recordings" } else { "sweep" }, rows, if rows == 1 { "" } else { "s" }));    let work = match tempfile::tempdir() {        Ok(dir) => dir,        Err(e) => {            let why = format!("no work folder: {e}");            log.say(&format!("failed: {why}"));            failed(state, now, &s, why.clone(), None);            return Woke::Failed(why);        }    };    let engine = cfg.engine();    let mut counts = Counts::default();    let drained = crate::meetings::drain(&device.object, &engine, work.path(), cfg.most, &mut |d| {        log.say(&drained_line(d));    });    let drained = match drained {        Ok(done) => done,        Err(why) => {            let why = one_line(&why);            log.say(&format!("failed: {why}; next try in {} min", backoff(state.failures + 1, &s) / 60));            failed(state, now, &s, why.clone(), None);            return Woke::Failed(why);        }    };    for d in &drained {        match d.status.as_str() {            "ready" => counts.transcribed += 1,            "failed" => counts.failed += 1,            _ => counts.left += 1,        }    }    if cfg.summaries {        let id = cfg.summary_model.clone().unwrap_or_else(|| crate::summarise::catalogue().default);        match crate::summarise::drain(&device.object, &id, cfg.most, &mut |m| log.say(&summarised_line(m))) {            Ok(done) => counts.summarised = done.iter().filter(|m| m.done).count(),            Err(why) => log.say(&format!("summaries: {}", one_line(&why))),        }    }    log.say(&format!(        "run done: transcribed={} failed={} left={} summarised={} in {:.1}s",        counts.transcribed,        counts.failed,        counts.left,        counts.summarised,        started.elapsed().as_secs_f64()    ));    succeeded(state, now, version, counts.clone());    Woke::Ran(counts)}/// A dry run on one local file: the lock, the models' check and the engine,/// as a wake runs them, nothing sent anywhere and no state changed; the log/// says what it took in counts only. How a Mac proves the job before it is/// signed in.pub fn dry_run(cfg: &Config, audio: &Path) -> Result<String, String> {    let log = Log::new(&cfg.log);    let Some(_lock) = lock(&cfg.home)? else {        return Err("another run holds the job".into());    };    models_held(cfg).map_err(|r| r.said())?;    let (transcript, took) = crate::meetings::transcribe(&cfg.engine(), audio)?;    let speakers: std::collections::BTreeSet<&str> = transcript.lines.iter().map(|l| l.speaker.as_str()).collect();    let line = format!(        "dry run: lines={} speakers={} languages={} audio={:.1}s took={:.1}s windows={}",        transcript.lines.len(),        speakers.len(),        transcript.languages.len(),        took.audio_s,        took.wall_s,        took.windows    );    log.say(&line);    Ok(line)}// ── the status line ─────────────────────────────────────────────────────────/// How long ago `t` was, from `now`: the status line names no clock time,/// so it never asks the machine what zone it is in.fn ago(now: i64, t: i64) -> String {    match (now - t).max(0) {        s if s < 60 => "just now".into(),        s if s < 3600 => format!("{} min ago", s / 60),        s if s < 86_400 => format!("{} h ago", s / 3600),        s => format!("{} days ago", s / 86_400),    }}/// How long until `t`, from `now`.fn within(now: i64, t: i64) -> String {    match (t - now).max(0) {        s if s < 60 => "within a minute".into(),        s if s < 3600 => format!("in {} min", (s + 59) / 60),        s => format!("in {} h", s / 3600),    }}fn every(seconds: i64) -> String {    match seconds {        s if s % 3600 == 0 && s >= 3600 => if s == 3600 { "hourly".into() } else { format!("every {} h", s / 3600) },        s => format!("every {} min", (s / 60).max(1)),    }}/// The one status line (`pnpm -s meetings:job:status`), and whether the job/// may run (`true`) or is refused, backing off or unloaded (`false`). The/// live checks (`sign_in`, `models`) are this moment's; a refusal they do not/// see again (a vault that would not open) is the last wake's.pub fn status_line(cfg: &Config, state: &State, loaded: bool, sign_in: Result<(), Refusal>, models: Result<(), Refusal>, now: i64) -> (String, bool) {    let head = "meetings job:";    let cadence = format!("wakes {}, sweeps {}", every(cfg.schedule.wake_s), every(cfg.schedule.sweep_s));    if let Err(r) = sign_in.and(models) {        return (format!("{head} refused · {}", r.said()), false);    }    if let Some(r) = state.refused.as_ref().filter(|r| r.kind != "models") {        return (format!("{head} refused · {} (last wake {})", r.said(), state.last_wake.map(|t| ago(now, t)).unwrap_or_default()), false);    }    if !loaded {        return (format!("{head} not loaded · pnpm -s meetings:job:install loads it"), false);    }    let last = match (state.last_ok, &state.last_counts) {        (Some(t), Some(c)) => format!("last run {} ({} transcribed, {} failed, {} summarised)", ago(now, t), c.transcribed, c.failed, c.summarised),        _ => "not run yet".to_string(),    };    if state.failures > 0 {        let next = state.next_try.filter(|t| *t > now).map(|t| format!(" · next try {} (pnpm -s meetings:job:run runs it now)", within(now, t))).unwrap_or_default();        // A refusal the live checks no longer see (the models fetched since) is said as mended.        let why = match &state.refused {            Some(r) if r.kind == "models" => "models were missing, held now".to_string(),            _ => state.failed.clone().unwrap_or_default(),        };        return (format!("{head} backing off · {} failure{}: {why}{next} · {last}", state.failures, if state.failures == 1 { "" } else { "s" }), false);    }    (format!("{head} ready · {last} · {cadence}"), true)}#[cfg(test)]#[path = "meetings_job_tests.rs"]mod tests;