Skip to main content

magi/
waiter.rs

1//! The waiter: something that keeps waiting on a question after the process
2//! that asked it is gone.
3//!
4//! `magi ask` blocks in the agent's own shell tool, and that tool kills a wait
5//! that runs long (see `ask::WAIT_SLICE`). An agent can also background the
6//! call and simply finish. Either way the question outlives the only process
7//! that would have read the owner's answer, and the owner's reply lands in a
8//! file nobody is polling - the phone then says "waiting for the agent" while
9//! there is no agent to wait for.
10//!
11//! This module is the guarantee that something is always on the other end. It
12//! runs inside `magi serve`, on its own cadence rather than the queue's, and
13//! for every question a `magi ask` filed it decides one of three things:
14//!
15//! - **the asker is still there** (its [`Lease`] is fresh): do nothing. A
16//!   second agent must never be started while the first is blocked;
17//! - **the asker is gone and the owner has said or answered something the agent
18//!   has not read**: resume the *same seat's* CLI session with the question,
19//!   the thread so far and the owner's words, so the agent that holds the
20//!   context carries on;
21//! - **nobody answered before `answer_timeout`**: abandon it, in the same words
22//!   the asker would have used.
23//!
24//! # Shape
25//!
26//! Same split as [`crate::queue`] and [`crate::ask`]: [`decide`] is pure - a
27//! question, a lease, a clock and a bool in, an [`Action`] out - and every
28//! filesystem or process effect is in [`Waiter::tick`]. State lives on disk (the
29//! question record and its lease), so a restarted daemon picks up exactly where
30//! the last one stopped, including an answer nobody has read yet.
31//!
32//! # What it will not do
33//!
34//! It never starts a fresh consultant. If the seat's session cannot be resumed
35//! (`agent::has_session` says no, the working directory is gone, the run is
36//! over, the agent left the roster) the question stays as it is, the owner
37//! gets a notification saying why, and nothing else runs. A new agent would
38//! have to be caught up on everything the first one knew, and would act on the
39//! owner's words without the context they were written against.
40//!
41//! It never assumes a resume worked either: a turn that fails or times out
42//! leaves the word undelivered, and a later tick tries again.
43
44use std::collections::HashMap;
45use std::path::PathBuf;
46use std::time::{Duration, Instant};
47
48use anyhow::Result;
49use jiff::Timestamp;
50
51use crate::agent::{self, Invocation, SeatState};
52use crate::ask::{Lease, Question, QuestionStatus, Questions, Waiter as Note, WaiterKind, Who};
53use crate::config::{AgentSpec, Config};
54use crate::notices::{self, Notice};
55use crate::prompt;
56use crate::run::RunState;
57
58/// How often the waiter looks at the store.
59pub const TICK: Duration = Duration::from_secs(5);
60
61/// Wall-clock limit for one resumed turn. A resumed agent may go on to do real
62/// work once it has the owner's word, but it is one conversation turn, not a
63/// whole node.
64const DELIVERY_TIMEOUT: Duration = Duration::from_secs(15 * 60);
65
66/// How long a failed or refused delivery is left alone before the same input
67/// is tried again. Long enough not to hammer a seat that is out of quota,
68/// short enough that a fixed problem does not wait a day.
69const RETRY_AFTER: Duration = Duration::from_secs(10 * 60);
70
71#[derive(serde::Serialize, serde::Deserialize)]
72struct Retry {
73    key: String,
74    until: i64,
75}
76
77fn retry_path(store: &Questions, id: &str) -> PathBuf {
78    store.root().join(format!("{id}.waiter-retry.json"))
79}
80
81fn retry_blocked(store: &Questions, id: &str, key: &str, now: Timestamp) -> bool {
82    std::fs::read(retry_path(store, id))
83        .ok()
84        .and_then(|bytes| serde_json::from_slice::<Retry>(&bytes).ok())
85        .is_some_and(|retry| retry.key == key && now.as_second() < retry.until)
86}
87
88/// What the agent has not read yet.
89#[derive(Debug, Clone, PartialEq, Eq)]
90pub enum Word {
91    /// The owner spoke back without deciding.
92    Said(String),
93    /// The owner decided.
94    Answered(String),
95}
96
97/// What to do about one question, this tick.
98#[derive(Debug, Clone, PartialEq, Eq)]
99pub enum Action {
100    /// Nothing: not ours, someone is waiting, or nothing new to hand over.
101    Idle,
102    /// The deadline passed with no answer and nobody waiting.
103    Expire,
104    /// Resume the asking seat with this.
105    Deliver(Word),
106}
107
108/// The whole decision, with no I/O.
109///
110/// `seat_busy` is whether the asking seat's CLI is still mid-turn - the agent
111/// that exited its `magi ask` may not have exited itself, and resuming a
112/// conversation that is running would fork it.
113///
114/// Order matters: a word the owner gave before the deadline is delivered even
115/// if the deadline has passed by the time the waiter looks, and only then does
116/// an unanswered question expire.
117pub fn decide(
118    q: &Question,
119    lease: Option<&Lease>,
120    seat_busy: bool,
121    default_timeout: u64,
122    now: Timestamp,
123) -> Action {
124    decide_owned(q, lease, seat_busy, default_timeout, now, false)
125}
126
127/// [`decide`], told whether the daemon owns the answer's action.
128///
129/// `daemon_owns_action` is true when the daemon will apply the action (the
130/// task exists and is in a state `daemon::decide_action` acts on). An answer
131/// that carries a [`crate::ask::ChoiceAction`] is then the daemon's alone
132/// (`daemon::apply_choice_actions`, idempotent through `Task::actions_applied`
133/// under the task's claim): resuming the dead seat here as well would run the
134/// same seat twice when the action is a resume or a requeue. With no task
135/// there is no one to apply it, so the words are delivered as before.
136pub fn decide_owned(
137    q: &Question,
138    lease: Option<&Lease>,
139    seat_busy: bool,
140    default_timeout: u64,
141    now: Timestamp,
142    daemon_owns_action: bool,
143) -> Action {
144    if q.routed_task.is_some() || q.cwd.is_none() || lease.is_some_and(|l| l.fresh(now)) {
145        return Action::Idle;
146    }
147    match q.status {
148        QuestionStatus::Abandoned => Action::Idle,
149        QuestionStatus::Answered => match q.resolution() {
150            _ if q.chosen_action().is_some_and(|a| a.maintenance())
151                || (daemon_owns_action && q.chosen_action().is_some()) =>
152            {
153                Action::Idle
154            }
155            Some(a) if !q.answer_delivered && !seat_busy => Action::Deliver(Word::Answered(a)),
156            _ => Action::Idle,
157        },
158        QuestionStatus::Open => {
159            if let Some(said) = q.unread_from_owner() {
160                if seat_busy {
161                    return Action::Idle;
162                }
163                return Action::Deliver(Word::Said(said));
164            }
165            let secs = if q.answer_timeout > 0 {
166                q.answer_timeout
167            } else {
168                default_timeout
169            };
170            let deadline = q.last_activity().saturating_add(secs as i64);
171            if now.as_second() > deadline {
172                Action::Expire
173            } else {
174                Action::Idle
175            }
176        }
177    }
178}
179
180/// Everything needed to resume one seat.
181struct Target {
182    coordination: Option<crate::config::Coordination>,
183    fetched_base: Option<crate::run::FetchedBase>,
184    spec: AgentSpec,
185    seat: SeatState,
186    cwd: PathBuf,
187    sessions: bool,
188    allow_write: bool,
189    language: String,
190}
191
192/// The waiter's state: the store it watches and what it must remember between
193/// ticks (only which inputs it has already failed on).
194pub struct Waiter {
195    store: Questions,
196    home: PathBuf,
197    /// The config the conductor runs under, for a question the conductor asked
198    /// (it has no run whose snapshot could say).
199    conduct_cfg: Option<Config>,
200    /// `answer_timeout` for a question that did not record its own.
201    default_timeout: u64,
202    /// Inputs already tried and failed, by question id: `(key, until)`.
203    memo: HashMap<String, (String, Instant)>,
204}
205
206impl Waiter {
207    /// A waiter over `store`, with `home` as the magi home its runs live under.
208    pub fn new(store: Questions, home: PathBuf, conduct_cfg: Option<Config>) -> Self {
209        let default_timeout = conduct_cfg
210            .as_ref()
211            .map_or(Config::default().graph.answer_timeout, |c| {
212                c.graph.answer_timeout
213            });
214        Self {
215            store,
216            home,
217            conduct_cfg,
218            default_timeout,
219            memo: HashMap::new(),
220        }
221    }
222
223    /// Admission check without starting a process for an idle question store.
224    pub fn has_work(&self, now: Timestamp) -> bool {
225        self.store.list().iter().any(|q| {
226            let lease = self.store.read_lease(&q.id);
227            match decide_owned(
228                q,
229                lease.as_ref(),
230                false,
231                self.default_timeout,
232                now,
233                self.daemon_owns_action(q),
234            ) {
235                Action::Idle => false,
236                Action::Expire => true,
237                Action::Deliver(_) if q.deputy.is_some() => crate::deputy::exhausted_past_deadline(
238                    q,
239                    crate::deputy::can_start(self.conduct_cfg.as_ref(), crate::deputy::agent_of(q)),
240                    self.default_timeout,
241                    now,
242                ),
243                Action::Deliver(word) => {
244                    let key = format!("{}:{:?}", q.thread.len(), word);
245                    !self.seat_busy(q, now) && !retry_blocked(&self.store, &q.id, &key, now)
246                }
247            }
248        })
249    }
250
251    /// Is this question's asking seat still mid-turn?
252    fn seat_busy(&self, q: &Question, now: Timestamp) -> bool {
253        if q.run == crate::conduct::NODE {
254            return crate::conduct::busy(&self.home);
255        }
256        RunState::load_under(&q.run, &self.home).is_ok_and(|s| {
257            s.seats_active()
258                .any(|(k, a)| *k == q.seat && a.remaining_secs(now) > 0)
259        })
260    }
261
262    /// Whether the daemon applies this question's chosen action, so the
263    /// waiter must not deliver the answer (see [`decide_owned`]).
264    fn daemon_owns_action(&self, q: &Question) -> bool {
265        q.chosen_action().is_some_and(|a| a.maintenance())
266            || crate::daemon::task_of_question(
267                &crate::queue::Queue::at(self.home.join("queue")).list(),
268                q,
269            )
270            .is_some_and(|t| crate::daemon::action_standing(t, q).daemon_owns())
271    }
272
273    /// Look at every question once and act on what needs acting on. `halt` is
274    /// asked between questions and during a delivery: true means the daemon is
275    /// parking, and whatever is in flight is dropped, undelivered and
276    /// resumable.
277    pub async fn tick(&mut self, now: Timestamp, halt: &(dyn Fn() -> bool + Sync)) {
278        for q in self.store.list() {
279            if halt() {
280                return;
281            }
282            if crate::task_chat::routes(&q, &self.home) {
283                continue;
284            }
285            let lease = self.store.read_lease(&q.id);
286            let owned = self.daemon_owns_action(&q);
287            match decide_owned(&q, lease.as_ref(), false, self.default_timeout, now, owned) {
288                Action::Idle => {}
289                Action::Expire => self.expire(&q),
290                Action::Deliver(word) => {
291                    // A question with a deputy is the deputy's to read
292                    // (`crate::deputy`); resuming the conductor's own seat
293                    // here would fork a conversation that is not its own.
294                    if q.deputy.is_some() {
295                        // Unless that deputy is spent: then nobody will read
296                        // the word, and the deadline still has to retire the
297                        // question.
298                        if crate::deputy::exhausted_past_deadline(
299                            &q,
300                            crate::deputy::can_start(
301                                self.conduct_cfg.as_ref(),
302                                crate::deputy::agent_of(&q),
303                            ),
304                            self.default_timeout,
305                            now,
306                        ) {
307                            self.expire(&q);
308                        }
309                        continue;
310                    }
311                    if self.seat_busy(&q, now) {
312                        continue;
313                    }
314                    let key = format!("{}:{:?}", q.thread.len(), word);
315                    if retry_blocked(&self.store, &q.id, &key, now)
316                        || matches!(self.memo.get(&q.id), Some((k, until)) if *k == key && Instant::now() < *until)
317                    {
318                        continue;
319                    }
320                    if let Err(e) = self.deliver(&q, &word, halt).await {
321                        tracing::warn!("question {}: {e:#}", q.short());
322                    }
323                }
324            }
325        }
326    }
327
328    /// Abandon an unanswered question whose deadline passed with nobody
329    /// waiting - the words the asker's own wait would have used.
330    fn expire(&self, q: &Question) {
331        let secs = if q.answer_timeout > 0 {
332            q.answer_timeout
333        } else {
334            self.default_timeout
335        };
336        let startable =
337            crate::deputy::can_start(self.conduct_cfg.as_ref(), crate::deputy::agent_of(q));
338        let why = format!("no answer within {}s of asking", secs.max(1));
339        let done = self.store.update(&q.id, |r| {
340            // Decided again on the record as it is now: the owner may have
341            // spoken since the tick read it, and a word given in time is
342            // delivered, not abandoned.
343            let now = Timestamp::now();
344            let lease = self.store.read_lease(&r.id);
345            if decide(r, lease.as_ref(), false, self.default_timeout, now) != Action::Expire
346                && !(lease.as_ref().is_none_or(|l| !l.fresh(now))
347                    && crate::deputy::exhausted_past_deadline(
348                        r,
349                        startable,
350                        self.default_timeout,
351                        now,
352                    ))
353            {
354                return Ok(false);
355            }
356            r.abandon(&why);
357            r.waiter = None;
358            Ok(true)
359        });
360        match done {
361            Ok((_, false)) => {}
362            Ok((_, true)) => {
363                self.store.drop_lease(&q.id);
364                tracing::warn!(
365                    "question {} went unanswered for {secs}s with nobody waiting; \
366                     it stays as the record of it",
367                    q.short()
368                );
369            }
370            Err(e) => tracing::warn!("could not expire question {}: {e:#}", q.short()),
371        }
372    }
373
374    /// Admission uses the very same target resolution as actual delivery.
375    pub fn can_resume(&self, q: &Question) -> bool {
376        self.target(q).is_ok()
377    }
378
379    /// Work out how to resume the seat, or why it cannot be.
380    fn target(&self, q: &Question) -> std::result::Result<Target, String> {
381        let cwd = q
382            .cwd
383            .as_deref()
384            .map(PathBuf::from)
385            .filter(|p| p.is_dir())
386            .ok_or("the directory the agent was working in is gone")?;
387        let (cfg, seat, allow_write, fetched_base) = if q.run == crate::conduct::NODE {
388            let cfg = self
389                .conduct_cfg
390                .clone()
391                .ok_or("the conductor's configuration is not available")?;
392            let seat = crate::conduct::load_seat(&self.home)
393                .ok_or("the conductor has no recorded session")?;
394            (cfg, seat, false, None)
395        } else {
396            let state = RunState::load_under(&q.run, &self.home)
397                .map_err(|_| "the run that asked is gone".to_owned())?;
398            if !state.status.resumable() {
399                return Err(format!(
400                    "the run that asked has already {}",
401                    state.status.as_str()
402                ));
403            }
404            let seat = state
405                .seats
406                .get(&q.seat)
407                .cloned()
408                .ok_or("the run has no record of the asking seat")?;
409            let write = matches!(q.node.as_str(), "implement" | "fix");
410            (state.config, seat, write, state.fetched_base)
411        };
412        let spec = cfg
413            .agent(&seat.agent)
414            .map_err(|_| format!("agent `{}` is no longer in the roster", seat.agent))?
415            .clone();
416        if !agent::has_session(spec.kind, &seat, cfg.graph.sessions) {
417            return Err("the seat has no session to resume".to_owned());
418        }
419        Ok(Target {
420            coordination: cfg.coordination.clone(),
421            fetched_base,
422            spec,
423            seat,
424            cwd,
425            sessions: cfg.graph.sessions,
426            allow_write,
427            language: cfg.graph.language.clone(),
428        })
429    }
430
431    /// Say why the owner's word cannot reach anybody, once per input.
432    fn refuse(&mut self, q: &Question, key: String, why: &str) {
433        tracing::warn!("question {} cannot be delivered: {why}", q.short());
434        notices::raise_in(
435            &self.home,
436            Notice::warn(
437                &format!("question:{}", q.id),
438                format!(
439                    "Question {} \"{}\": what you said cannot reach the agent \
440                     ({why}). It is recorded, but nothing will read it.",
441                    q.short(),
442                    q.summary
443                ),
444            )
445            .link(if q.run_names_task() {
446                notices::Link::Task { id: q.run.clone() }
447            } else {
448                notices::Link::Run { id: q.run.clone() }
449            }),
450        );
451        let _ = self.store.update(&q.id, |r| {
452            r.waiter = None;
453            Ok(())
454        });
455        let retry = Retry {
456            key: key.clone(),
457            until: Timestamp::now()
458                .as_second()
459                .saturating_add(RETRY_AFTER.as_secs() as i64),
460        };
461        let written = serde_json::to_vec(&retry)
462            .map_err(anyhow::Error::from)
463            .and_then(|bytes| {
464                std::fs::write(retry_path(&self.store, &q.id), bytes).map_err(Into::into)
465            });
466        if let Err(error) = written {
467            tracing::warn!(
468                "question {} retry cooldown could not be saved: {error:#}",
469                q.short()
470            );
471        }
472        self.memo
473            .insert(q.id.clone(), (key, Instant::now() + RETRY_AFTER));
474    }
475
476    /// Resume the asking seat with the owner's word.
477    async fn deliver(
478        &mut self,
479        q: &Question,
480        word: &Word,
481        halt: &(dyn Fn() -> bool + Sync),
482    ) -> Result<()> {
483        let key = format!("{}:{:?}", q.thread.len(), word);
484        let mut target = match self.target(q) {
485            Ok(t) => t,
486            Err(why) => {
487                self.refuse(q, key, &why);
488                return Ok(());
489            }
490        };
491
492        let claim = self.store.root().join(format!("{}.claim", q.id));
493        if !take_claim(&claim, DELIVERY_TIMEOUT + Duration::from_secs(60)) {
494            return Ok(());
495        }
496        let _release = Release(claim);
497
498        // Re-read under the claim: the asker may have come back, or the owner
499        // may have said more, since the tick's copy was taken.
500        let q = self.store.get(&q.id)?;
501        if crate::task_chat::routes(&q, &self.home) {
502            return Ok(());
503        }
504        let now = Timestamp::now();
505        let lease = self.store.read_lease(&q.id);
506        let owned = self.daemon_owns_action(&q);
507        let Action::Deliver(word) =
508            decide_owned(&q, lease.as_ref(), false, self.default_timeout, now, owned)
509        else {
510            return Ok(());
511        };
512        let snapshot = q.thread.len();
513
514        // Ownership of an action answer is settled against the daemon's task
515        // claim: hold it while the lease goes up, so the daemon either sees the
516        // fresh lease or has already applied the action (and we step aside).
517        // A claim held by a running competition is not the daemon applying an
518        // action; that case is delivered, with the re-check below.
519        let queue = crate::queue::Queue::at(self.home.join("queue"));
520        let task_id = crate::daemon::task_of_question(&queue.list(), &q).map(|t| t.id.clone());
521        // Never go on without the claim: a failed claim means an attempt (or
522        // the daemon) holds the task, and whatever it does next decides who
523        // owns this answer. Step aside; the next tick judges it afresh.
524        let _task_claim = match (&task_id, q.chosen_action()) {
525            (Some(id), Some(_)) => match queue.claim(id) {
526                Ok(c) => Some(c),
527                Err(e) => {
528                    tracing::debug!(
529                        "question {}: task claim not available ({e:#}), deferring delivery",
530                        q.short()
531                    );
532                    return Ok(());
533                }
534            },
535            _ => None,
536        };
537        // Applied, stale and pending are all stop conditions; only a busy task
538        // (or no action at all) is delivered to.
539        let task_still_ours = || {
540            if q.chosen_action().is_some_and(|a| a.maintenance()) {
541                false
542            } else {
543                match &task_id {
544                    Some(id) => queue
545                        .get(id)
546                        .map(|t| !crate::daemon::action_standing(&t, &q).daemon_owns())
547                        .unwrap_or(true),
548                    None => true,
549                }
550            }
551        };
552        if !task_still_ours() {
553            return Ok(());
554        }
555
556        self.store.beat(&q.id, WaiterKind::Daemon);
557        // Re-check after the lease is up: a daemon that decided before it
558        // existed has by now written its mark (or is blocked on our claim).
559        if !task_still_ours() {
560            return Ok(());
561        }
562        self.store.update(&q.id, |r| {
563            r.waiter = Some(Note {
564                kind: WaiterKind::Daemon,
565                since: now,
566            });
567            Ok(())
568        })?;
569        tracing::info!(
570            "question {}: the asker is gone, resuming seat {} with the owner's word",
571            q.short(),
572            q.seat
573        );
574
575        let thread: Vec<(&str, &str)> = q
576            .thread
577            .iter()
578            .map(|t| {
579                (
580                    if t.who == Who::Operator {
581                        "operator"
582                    } else {
583                        "agent"
584                    },
585                    t.body.as_str(),
586                )
587            })
588            .collect();
589        // What the owner said and the agent has not read has its own section in
590        // the prompt, so the recap stops at what it already read.
591        let shown = match word {
592            Word::Said(_) => &thread[..q.delivered_turns.min(thread.len())],
593            Word::Answered(_) => &thread[..],
594        };
595        let owner_word = match &word {
596            Word::Said(s) => prompt::OwnerWord::Said(s),
597            Word::Answered(a) => prompt::OwnerWord::Answered(a),
598        };
599        let body = prompt::question_resumed(
600            &q.id,
601            &q.summary,
602            &q.detail,
603            shown,
604            &owner_word,
605            &target.language,
606        );
607
608        let artifacts = self.store.root().join(format!("{}.delivery", q.id));
609        let stem = format!("deliver-{}", now.as_second());
610        let cache_dir = None;
611        let inv = Invocation {
612            coordination: target.coordination.as_ref(),
613            fetched_base: target.fetched_base.as_ref(),
614            cwd: &target.cwd,
615            prompt: &body,
616            timeout: DELIVERY_TIMEOUT,
617            allow_write: target.allow_write,
618            unsandboxed: false,
619            sessions: target.sessions,
620            artifacts: &artifacts,
621            stem: &stem,
622            run: &q.run,
623            node: &q.node,
624            cache_dir,
625            attachments: &[],
626            writable: &[],
627        };
628
629        let store = self.store.clone();
630        let id = q.id.clone();
631        let out = {
632            let fut = agent::invoke(&target.spec, &mut target.seat, &inv);
633            tokio::pin!(fut);
634            let mut beat = tokio::time::interval(Duration::from_secs(1));
635            let mut beats = 0u32;
636            loop {
637                tokio::select! {
638                    r = &mut fut => break Some(r),
639                    _ = beat.tick() => {
640                        if halt() {
641                            break None;
642                        }
643                        beats += 1;
644                        if beats % 20 == 0 {
645                            store.beat(&id, WaiterKind::Daemon);
646                        }
647                    }
648                }
649            }
650        };
651
652        let Some(out) = out else {
653            // Parking: leave everything as it was, resumable.
654            let _ = self.store.update(&q.id, |r| {
655                r.waiter = None;
656                Ok(())
657            });
658            return Ok(());
659        };
660        let out = match out {
661            Ok(o) if o.usable() => o,
662            other => {
663                let why = match other {
664                    Ok(o) if o.timed_out => "the resumed turn timed out".to_owned(),
665                    Ok(o) if o.quota_exhausted() => "the agent is out of quota".to_owned(),
666                    Ok(o) => format!(
667                        "the resumed turn failed ({})",
668                        notices::exit_status(o.exit_code)
669                    ),
670                    Err(e) => format!("the agent could not be started: {e:#}"),
671                };
672                self.refuse(&q, key, &why);
673                return Ok(());
674            }
675        };
676
677        let text = out.text.trim().to_owned();
678        self.store.update(&q.id, |r| {
679            r.waiter = None;
680            match &word {
681                Word::Answered(_) => r.answer_delivered = true,
682                Word::Said(_) => {
683                    r.delivered_turns = r.delivered_turns.max(snapshot);
684                    // An agent that answered in prose instead of calling
685                    // `magi ask --thread` still spoke; keep it on the record so
686                    // the owner reads it. If it did use --thread, or the owner
687                    // said more meanwhile, the record already moved on.
688                    let agent_spoke = r.thread[snapshot.min(r.thread.len())..]
689                        .iter()
690                        .any(|t| t.who == Who::Agent);
691                    if !agent_spoke && r.thread.len() == snapshot && r.status.open() {
692                        let choices = r.choices.clone();
693                        r.reply(text, choices)?;
694                    }
695                }
696            }
697            Ok(())
698        })?;
699        self.memo.remove(&q.id);
700        let _ = std::fs::remove_file(retry_path(&self.store, &q.id));
701        Ok(())
702    }
703}
704
705/// Take the delivery claim, so two waiters (`magi serve` twice, or a stray
706/// second daemon) cannot resume the same seat at once. A claim older than a
707/// whole delivery plus slack was left by a process that died.
708pub(crate) fn take_claim(path: &std::path::Path, stale_after: Duration) -> bool {
709    let retry = crate::lock_file::Retry::new(None);
710    let attempt = || retry.create(path).is_ok();
711    if attempt() {
712        return true;
713    }
714    let stale = std::fs::metadata(path)
715        .and_then(|m| m.modified())
716        .ok()
717        .and_then(|t| t.elapsed().ok())
718        .is_some_and(|age| age > stale_after);
719    if stale {
720        let _ = std::fs::remove_file(path);
721        return attempt();
722    }
723    false
724}
725
726/// Removes the delivery claim when the delivery ends, however it ends.
727pub(crate) struct Release(pub(crate) PathBuf);
728
729impl Drop for Release {
730    fn drop(&mut self) {
731        let _ = std::fs::remove_file(&self.0);
732    }
733}
734
735#[cfg(test)]
736mod tests {
737    use super::*;
738
739    #[test]
740    fn retry_backoff_survives_a_new_finite_waiter() {
741        let home = tempfile::tempdir().expect("home");
742        let store = Questions::at(home.path().join("questions"));
743        std::fs::create_dir_all(store.root()).expect("questions");
744        let retry = Retry {
745            key: "input".to_owned(),
746            until: 700,
747        };
748        std::fs::write(
749            retry_path(&store, "question"),
750            serde_json::to_vec(&retry).expect("retry"),
751        )
752        .expect("save retry");
753        let reopened = Questions::at(home.path().join("questions"));
754        assert!(retry_blocked(&reopened, "question", "input", ts(699)));
755        assert!(!retry_blocked(
756            &reopened,
757            "question",
758            "different input",
759            ts(699)
760        ));
761        assert!(!retry_blocked(&reopened, "question", "input", ts(700)));
762    }
763
764    fn ts(secs: i64) -> Timestamp {
765        Timestamp::from_second(secs).unwrap()
766    }
767
768    fn asked(at: i64) -> Question {
769        let mut q = Question::new(
770            "run".into(),
771            "implement".into(),
772            "impl-A".into(),
773            "which?".into(),
774            String::new(),
775            vec![],
776        );
777        q.cwd = Some("/tmp".into());
778        q.asked_at = ts(at);
779        q.answer_timeout = 1000;
780        q
781    }
782
783    fn lease(at: i64) -> Lease {
784        Lease {
785            kind: WaiterKind::Asker,
786            pid: 1,
787            beat_at: ts(at),
788        }
789    }
790
791    #[test]
792    fn a_fresh_lease_means_nobody_else_acts() {
793        let mut q = asked(0);
794        q.say("why?").unwrap();
795        assert_eq!(
796            decide(&q, Some(&lease(95)), false, 86_400, ts(100)),
797            Action::Idle
798        );
799    }
800
801    #[test]
802    fn a_stale_lease_delivers_what_the_owner_said() {
803        let mut q = asked(0);
804        q.say("why?").unwrap();
805        assert_eq!(
806            decide(&q, Some(&lease(0)), false, 86_400, ts(500)),
807            Action::Deliver(Word::Said("why?".into()))
808        );
809        assert_eq!(
810            decide(&q, None, true, 86_400, ts(500)),
811            Action::Idle,
812            "a seat still mid-turn is not resumed"
813        );
814    }
815
816    #[test]
817    fn an_answer_nobody_read_is_delivered_once() {
818        let mut q = asked(0);
819        q.choices = vec!["A".into()];
820        q.answer(crate::ask::Answer::Choice("A".into())).unwrap();
821        assert_eq!(
822            decide(&q, None, false, 86_400, ts(10)),
823            Action::Deliver(Word::Answered("A".into()))
824        );
825        q.answer_delivered = true;
826        assert_eq!(decide(&q, None, false, 86_400, ts(10)), Action::Idle);
827    }
828
829    #[test]
830    fn only_asked_questions_and_only_before_the_deadline() {
831        let mut q = asked(0);
832        assert_eq!(decide(&q, None, false, 86_400, ts(999)), Action::Idle);
833        assert_eq!(decide(&q, None, false, 86_400, ts(1001)), Action::Expire);
834        q.cwd = None;
835        assert_eq!(decide(&q, None, false, 86_400, ts(1001)), Action::Idle);
836    }
837
838    #[test]
839    fn the_deadline_runs_from_the_last_turn_not_from_asking() {
840        let mut q = asked(0);
841        q.thread.push(crate::ask::Turn {
842            who: Who::Agent,
843            body: "context".into(),
844            at: ts(4000),
845            note: None,
846        });
847        q.delivered_turns = 1;
848        assert_eq!(decide(&q, None, false, 86_400, ts(4500)), Action::Idle);
849        assert_eq!(decide(&q, None, false, 86_400, ts(5001)), Action::Expire);
850    }
851
852    #[test]
853    fn a_word_given_in_time_is_delivered_after_the_deadline() {
854        let mut q = asked(0);
855        q.say("wait").unwrap();
856        assert!(matches!(
857            decide(&q, None, false, 86_400, ts(5000)),
858            Action::Deliver(_)
859        ));
860    }
861
862    #[test]
863    fn an_action_answer_is_left_to_the_daemon() {
864        let mut q = asked(0);
865        q.choices = vec!["A".into()];
866        q.actions
867            .insert("A".into(), crate::ask::ChoiceAction::Requeue);
868        q.answer(crate::ask::Answer::Choice("A".into())).unwrap();
869        assert_eq!(
870            decide_owned(&q, None, false, 86_400, ts(10), true),
871            Action::Idle,
872            "the daemon applies the action; the waiter must not also resume the seat"
873        );
874        // Delivered or not, a stale lease changes nothing.
875        q.answer_delivered = true;
876        assert_eq!(
877            decide_owned(&q, None, false, 86_400, ts(10), true),
878            Action::Idle
879        );
880        // No task to apply it: the words are delivered as before.
881        q.answer_delivered = false;
882        assert_eq!(
883            decide_owned(&q, None, false, 86_400, ts(10), false),
884            Action::Deliver(Word::Answered("A".into()))
885        );
886        // No action: delivered even when a task exists.
887        let mut plain = asked(0);
888        plain.choices = vec!["A".into()];
889        plain
890            .answer(crate::ask::Answer::Choice("A".into()))
891            .unwrap();
892        assert_eq!(
893            decide_owned(&plain, None, false, 86_400, ts(10), true),
894            Action::Deliver(Word::Answered("A".into()))
895        );
896    }
897}