Skip to main content

magi/
talk.rs

1//! The standing conversation: a place to think out loud with an agent between
2//! tasks, reachable from a phone.
3//!
4//! This is a conversation that stays open. Ask a question, have the agent
5//! read a file or run a command to check something, talk through an idea,
6//! and when it is time to act, tell it to file the work rather than do it
7//! here. The conversation does not end; it is what the operator opens the
8//! next time something comes up.
9//!
10//! # Talking is not implementing
11//!
12//! Every turn here runs with `allow_write: false` by default, for a reason
13//! that is not security, but attribution. An agent that edits a checkout
14//! mid-conversation leaves a diff that belongs to no run and passed no
15//! review, and on a repository entered into magi's blind competition that
16//! makes every candidate's diff unjudgeable. That is why the default holds
17//! regardless of what a repository's own `magi.toml` says about anything
18//! else. When the operator wants a change made, the agent is told to run
19//! `magi task add --solo` ([`briefing`]) rather than reach for an editor: the
20//! change goes through magi's own queue, on the repository's own terms, and
21//! the operator can watch it happen instead of trusting that it did.
22//!
23//! `[talk] allow_write` ([`crate::config::Talk::allow_write`]) lets a
24//! specific repository opt out of that default - a dotfiles or personal
25//! config checkout that is never entered into a competition and never
26//! reviewed has nothing for the restriction to protect, and filing a task for
27//! a one-line edit there is pure overhead. Turning it on does not turn this
28//! conversation into an implementer: [`briefing`] still sends everything
29//! bigger than a small, operator-named edit to the queue, and still tells the
30//! agent to say what it changed.
31//!
32//! With `[talk] allow_write` on, a codex turn also runs unsandboxed
33//! ([`turn_access`]), as a claude turn already does under `bypassPermissions`:
34//! otherwise `magi task add` (writes to magi's queue under the home directory)
35//! or `git fetch` is refused by the sandbox. Unattended seats never get this.
36//!
37//! `--solo` rather than a plain `magi task add` is the point of pairing this
38//! module with [`crate::queue::Task::solo`]. A task that came out of a
39//! conversation the operator just had is a decision already made, not a
40//! design question worth three independent takes - so it runs through one
41//! implementer and straight into review, the way [`crate::graph::Runner`]
42//! already degrades a single-candidate run.
43//!
44//! # Shape
45//!
46//! The same split [`crate::queue`] uses: [`Talk`] is data plus pure helpers,
47//! [`Talks`] owns the I/O and is constructed with its root, so every test
48//! here drives a real store in a temp directory rather than the operator's
49//! own home.
50
51use std::path::{Path, PathBuf};
52use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
53use std::time::Duration;
54
55use anyhow::{Context, Result, bail};
56use jiff::Timestamp;
57use serde::{Deserialize, Serialize};
58
59use crate::agent::{self, Invocation, SeatState};
60use crate::config::{AgentSpec, Config};
61use crate::queue::{Queue, Source, Task};
62
63/// On-disk format for a conversation. Bumped when a field's meaning changes.
64pub const SCHEMA: u32 = 1;
65
66/// Wall-clock limit for one agent turn. See [`crate::config::Graph::timeout_talk`].
67///
68/// An hour by default. This turn is expected to run several shell commands
69/// and read their output before answering one - "what does this function
70/// do", "is this still true", "run the tests and tell me" - which argues for
71/// an hour rather than the five minutes a short budget once assumed, because
72/// the thing that made a short budget matter - an operator watching a
73/// spinner - is not how this conversation gets used: the operator moves on
74/// to something else while a turn runs and checks back later, so a long turn
75/// spends a held seat, not anyone's attention.
76fn turn_timeout(cfg: &Config) -> Duration {
77    Duration::from_secs(cfg.graph.timeout_talk)
78}
79
80/// Seat name for the conversation's agent, scoping its CLI-side session away
81/// from every other seat magi ever opens.
82const SEAT: &str = "talk";
83
84/// Prefix on a turn magi wrote rather than an agent.
85const MAGI_NOTE: &str = "magi: ";
86
87/// Who said something.
88#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
89#[serde(rename_all = "lowercase")]
90pub enum Who {
91    /// The operator.
92    Operator,
93    /// The conversation's agent - or magi itself, reporting that a turn
94    /// failed. See [`MAGI_NOTE`].
95    Agent,
96}
97
98/// One image the operator attached to a turn.
99///
100/// Never carries the bytes themselves: the picture lives on disk under
101/// [`Talks::attachments_dir`], named by `id` alone. `name` is the filename
102/// the operator's browser reported, kept only for display - it never
103/// contributes to a path, which is what keeps an upload from being able to
104/// traverse outside its own directory.
105#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
106#[serde(deny_unknown_fields)]
107pub struct Attachment {
108    /// Server-minted id; also the file's stem under `attachments_dir`.
109    pub id: String,
110    /// The operator's own filename, for display only.
111    pub name: String,
112    /// Validated by `web` at upload time against a closed whitelist:
113    /// `image/png`, `image/jpeg`, `image/gif`, `image/webp`.
114    pub mime: String,
115    /// Size in bytes, so the phone can show it without a second request.
116    pub bytes: u64,
117}
118
119/// One message in the conversation.
120#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
121#[serde(deny_unknown_fields)]
122pub struct Turn {
123    /// Who wrote it.
124    pub who: Who,
125    /// What they said.
126    pub body: String,
127    /// When it was said.
128    pub at: Timestamp,
129    /// Images attached to this turn. `#[serde(default)]` so a conversation
130    /// recorded before attachments existed still reads.
131    #[serde(default)]
132    pub attachments: Vec<Attachment>,
133    /// What the agent's CLI reported reading for this reply; only ever set on
134    /// an agent reply that carried usage. `#[serde(default)]` so a
135    /// conversation recorded before this field existed still reads, which is
136    /// why [`SCHEMA`] stays put: no existing field changed meaning.
137    #[serde(default, skip_serializing_if = "Option::is_none")]
138    pub usage: Option<TurnUsage>,
139    /// Byte offsets in [`Self::body`] where the second and later messages of
140    /// an operator turn begin. Replies queued while a turn runs are joined
141    /// with a blank line, which an owner's own blank lines cannot be told
142    /// apart from, so the boundary is recorded when it is made. `Some(empty)`
143    /// is one message; `None` is unknown (a turn stored before this field, or
144    /// not an operator turn) and readers fall back to paragraphs.
145    #[serde(default, skip_serializing_if = "Option::is_none")]
146    pub breaks: Option<Vec<usize>>,
147    /// The run id of the task seat that appended this agent turn with
148    /// `magi talk post`. Only ever set on such a turn; the chat's own CLI
149    /// session has not seen it, so [`posts_since_last_reply`] replays it in
150    /// the next prompt. `#[serde(default)]`: [`SCHEMA`] stays put.
151    #[serde(default, skip_serializing_if = "Option::is_none")]
152    pub posted_by: Option<String>,
153}
154
155/// Raw usage of one agent reply, stored as the CLI reported it.
156///
157/// Counts only, never a percentage: the window is configuration
158/// ([`Config::context_window`]) and the conversation's model can change, so a
159/// stored percentage would go stale the moment either did. `agent` and
160/// `model` record who read that many tokens, which is how [`context_usage`]
161/// notices the figure predates a switch.
162#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
163pub struct TurnUsage {
164    /// Input-side tokens the CLI reported - see `agent::context_tokens`.
165    pub context_tokens: u64,
166    /// Roster id that answered.
167    pub agent: String,
168    /// That agent's model at the time (`None`: the CLI's own default).
169    #[serde(default)]
170    pub model: Option<String>,
171}
172
173/// How full the conversation's context window is, as the phone shows it.
174///
175/// Derived at read time and never persisted. `None` means unknown, which the
176/// UI says in words - it is never a made-up 0.
177#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
178pub struct ContextUsage {
179    /// Tokens the last agent reply's turn read, if its CLI reported any.
180    pub tokens: Option<u64>,
181    /// Window of the conversation's *current* model, if one is configured.
182    pub window: Option<u64>,
183    /// `tokens / window`, rounded down, not capped (over 100 is real news).
184    pub percent: Option<u64>,
185    /// 80% or more, judged before rounding: the conversation is getting long.
186    pub warn: bool,
187    /// The conversation's agent or model is not the one that produced
188    /// `tokens`: the figure describes the old session and the next turn
189    /// re-measures it.
190    pub since_switch: bool,
191    /// The current model, if the roster names one.
192    pub model: Option<String>,
193    /// `tokens` is a transcript-length estimate, not a CLI measurement (see
194    /// [`estimate_context_tokens`]). A measured figure is never overridden.
195    #[serde(default)]
196    pub estimated: bool,
197}
198
199/// Fraction (in percent) of the window at which [`ContextUsage::warn`] fires.
200const CONTEXT_WARN_PERCENT: u64 = 80;
201
202/// Allowance for the standing prompt when no config is readable to render
203/// the real [`briefing`].
204const STANDING_PROMPT_FALLBACK_CHARS: u64 = 7000;
205
206/// Rough estimate of the context a conversation occupies, for CLIs whose usage
207/// is cumulative and so is never measured (claude / codex / agy).
208///
209/// Counts the characters (not bytes) of every operator and agent turn, skips
210/// magi's own notes (never sent to the agent), adds `standing_chars` for the
211/// standing prompt, and divides by ~3.5 chars per token, rounding up. `None`
212/// when no turn counts: an empty conversation stays unknown.
213///
214/// Known biases: CJK runs near one token per character, and tool output,
215/// images and the CLI's own system prompt are not counted, so this tends to
216/// under-estimate (the 80% warning comes late); a compacted session is still
217/// counted in full, which over-estimates.
218pub fn estimate_context_tokens(talk: &Talk, standing_chars: u64) -> Option<u64> {
219    let mut counted = false;
220    let mut chars = standing_chars;
221    for t in talk.turns.iter().filter(|t| !t.body.starts_with(MAGI_NOTE)) {
222        counted = true;
223        chars += t.body.chars().count() as u64;
224    }
225    // chars / 3.5, rounded up, in integers.
226    counted.then(|| (chars * 2).div_ceil(7))
227}
228
229/// Context usage of `talk`, measured against its current model.
230///
231/// Only the latest agent reply counts (magi's own notes are skipped) and a
232/// reply without usage makes the answer unknown - older replies are never
233/// consulted, since a stale count passed off as current is worse than "unknown".
234/// The window comes from the *current* agent's model, so switching model moves
235/// the denominator at once.
236///
237/// Switching agent (or model, which is an agent change) mints a fresh CLI
238/// session, so the next turn re-sends the whole transcript and the count
239/// resets or jumps. Until that turn lands, the old figure is reported with
240/// `since_switch` set. Deterministic: same talk and config, same answer.
241pub fn context_usage(talk: &Talk, cfg: Option<&Config>) -> ContextUsage {
242    let current = cfg.and_then(|c| c.agents.iter().find(|a| a.id == talk.agent));
243    let model = current.and_then(|a| a.model.clone());
244    let window = cfg
245        .zip(model.as_deref())
246        .and_then(|(c, m)| c.context_window(m))
247        .filter(|w| *w > 0);
248    let usage = talk
249        .turns
250        .iter()
251        .rev()
252        .find(|t| t.who == Who::Agent && !t.body.starts_with(MAGI_NOTE))
253        .and_then(|t| t.usage.as_ref());
254    let measured = usage.map(|u| u.context_tokens);
255    let tokens = measured.or_else(|| {
256        let standing = cfg.map_or(STANDING_PROMPT_FALLBACK_CHARS, |c| {
257            briefing_for(
258                &talk.repo,
259                &c.graph.language,
260                c.talk.allow_write,
261                crate::persona::active(&c.talk.personas, &talk.persona).as_ref(),
262                c.talk.operator_name(),
263                talk.implementers,
264            )
265            .chars()
266            .count() as u64
267        });
268        estimate_context_tokens(talk, standing)
269    });
270    let estimated = measured.is_none() && tokens.is_some();
271    let since_switch =
272        usage.is_some_and(|u| u.agent != talk.agent || (current.is_some() && u.model != model));
273    let (percent, warn) = match (tokens, window) {
274        (Some(t), Some(w)) => (
275            Some(t.saturating_mul(100) / w),
276            t.saturating_mul(100) >= w.saturating_mul(CONTEXT_WARN_PERCENT),
277        ),
278        _ => (None, false),
279    };
280    ContextUsage {
281        tokens,
282        window,
283        percent,
284        warn,
285        since_switch,
286        model,
287        estimated,
288    }
289}
290
291/// Where a conversation is in its life: this conversation can file any
292/// number of tasks without ending, so it only ever moves once, from open to
293/// closed.
294#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
295#[serde(rename_all = "lowercase")]
296pub enum TalkStatus {
297    /// Still open; the operator may say more, and may have already filed work
298    /// out of it.
299    Open,
300    /// Closed by hand. Kept on disk as a record.
301    Closed,
302}
303
304impl TalkStatus {
305    /// Is this conversation still live?
306    pub fn open(self) -> bool {
307        matches!(self, Self::Open)
308    }
309
310    /// Wire form, for the phone and for logs.
311    pub fn as_str(self) -> &'static str {
312        match self {
313            Self::Open => "open",
314            Self::Closed => "closed",
315        }
316    }
317}
318
319/// One standing conversation.
320#[derive(Debug, Clone, Serialize, Deserialize)]
321#[serde(deny_unknown_fields)]
322pub struct Talk {
323    /// On-disk format version.
324    pub schema: u32,
325    /// Conversation id, e.g. `20260904-014455-ab12`.
326    pub id: String,
327    /// Repository this conversation is about.
328    pub repo: PathBuf,
329    /// Roster agent id holding the conversation.
330    pub agent: String,
331    /// Current state.
332    pub status: TalkStatus,
333    /// Everything said, oldest first.
334    pub turns: Vec<Turn>,
335    /// Text and attachments accepted while the single CLI turn is busy.
336    /// They are durable, but become a real turn only when [`drain`] records them.
337    #[serde(default)]
338    pub pending: String,
339    /// Attachments paired with [`Self::pending`].
340    #[serde(default)]
341    pub pending_attachments: Vec<Attachment>,
342    /// Message boundaries inside [`Self::pending`], as [`Turn::breaks`].
343    #[serde(default, skip_serializing_if = "Option::is_none")]
344    pub pending_breaks: Option<Vec<usize>>,
345    /// May a failed turn fall back through the rest of `[roles] chatter`?
346    /// True only while the agent was chosen by that chain; an explicit
347    /// `--agent` or an operator's switch pins the conversation to its agent
348    /// even when that agent also appears in the chain.
349    #[serde(default)]
350    pub fallback: bool,
351    /// Persona id (see [`crate::persona`]); empty is the plain default voice.
352    /// Independent of [`Self::agent`]: it survives an agent switch.
353    #[serde(default)]
354    pub persona: String,
355    /// The persona changed after the CLI session was last told about it. The
356    /// next resumed turn carries a persona update; cleared only once a turn
357    /// has succeeded (a fresh seat's briefing already holds the new persona).
358    #[serde(default)]
359    pub persona_dirty: bool,
360    /// How many implementers the tasks this chat files use (1..=3; 1 is
361    /// `--solo`). Only the briefing's wording changes; nothing enforces it.
362    #[serde(default = "solo_implementers")]
363    pub implementers: u8,
364    /// [`Self::implementers`] changed after the CLI session was last told;
365    /// cleared only once a turn has succeeded, like [`Self::persona_dirty`].
366    #[serde(default)]
367    pub implementers_dirty: bool,
368    /// Keys of task-completion notices already accepted into this talk (see
369    /// [`queue_once`]). Kept beside [`Self::pending`] and saved in the same
370    /// write, so a crash between this talk and the task's own record cannot
371    /// post twice; never pruned by a drain or a close.
372    #[serde(default)]
373    pub notified: Vec<String>,
374    /// When the conversation was opened.
375    pub created_at: Timestamp,
376    /// Last change to this file.
377    pub updated_at: Timestamp,
378    /// The CLI-side conversation, so a turn after the first costs one
379    /// sentence instead of the whole transcript. Not `pub`: it is magi's
380    /// bookkeeping, and a caller that edited it would detach the record from
381    /// the conversation the model actually holds.
382    seat: SeatState,
383}
384
385impl Talk {
386    /// Short form used in lists and notifications, matching a run's short id.
387    pub fn short(&self) -> &str {
388        short(&self.id)
389    }
390}
391
392/// A conversation store on disk.
393#[derive(Debug, Clone)]
394pub struct Talks {
395    root: PathBuf,
396    /// Serializes the read-modify-write cycle that reads a talk, decides
397    /// something from its `status`, and writes the whole record back.
398    /// [`close`], [`record`] and the tail of [`turn`] all take this before
399    /// that cycle rather than after just the read: a re-read narrows the
400    /// window another writer can land in, but does not close it, since
401    /// nothing stopped that other writer's own put from landing between this
402    /// call's re-read and its own put. Shared across every clone, since every
403    /// clone is a handle onto the same files.
404    lock: Arc<Mutex<()>>,
405}
406
407impl Talks {
408    /// The operator's conversations, `<home>/talks`.
409    pub fn open() -> Self {
410        Self::at(crate::run::home().join("talks"))
411    }
412
413    /// A store at an explicit root. Tests use this, which is why none of them
414    /// need the operator's real home.
415    pub fn at(root: PathBuf) -> Self {
416        Self {
417            root,
418            lock: Arc::new(Mutex::new(())),
419        }
420    }
421
422    /// Claim the right to read-modify-write a talk's `status`. A plain
423    /// `std::sync::Mutex`, not an async one: every caller holds it across a
424    /// handful of small file operations and never across an `.await`, so
425    /// blocking the thread briefly is the right tool, not a reason to reach
426    /// for `tokio::sync::Mutex`. Poisoning recovers rather than propagates -
427    /// one panicking caller must not wedge every talk in the store the way it
428    /// would wedge the loop's own lock; see [`crate::web`]'s `lock_or_recover`,
429    /// which this mirrors.
430    ///
431    /// The mutex only serializes this process. The cycle is also taken under a
432    /// short file lock beside the records, so the CLI (`magi answer
433    /// --ask-chat`) and the web server cannot overwrite each other's draft.
434    /// The file lock is never skipped: a cycle that cannot get it within
435    /// longer than the lock's own expiry fails instead of writing unguarded.
436    fn guard(&self) -> Result<StoreGuard<'_>> {
437        let mutex = self.lock.lock().unwrap_or_else(PoisonError::into_inner);
438        std::fs::create_dir_all(&self.root)
439            .with_context(|| format!("create {}", self.root.display()))?;
440        let path = self.root.join(".store.turn");
441        let deadline = std::time::Instant::now() + TAKEOVER_LOCK_TTL * 2;
442        loop {
443            if let Some(file) = TurnLock::take(&path)? {
444                return Ok(StoreGuard {
445                    _file: file,
446                    _mutex: mutex,
447                });
448            }
449            if std::time::Instant::now() >= deadline {
450                bail!("the talk store is locked by another process");
451            }
452            std::thread::sleep(Duration::from_millis(10));
453        }
454    }
455
456    /// Directory holding the conversation files.
457    pub fn root(&self) -> &Path {
458        &self.root
459    }
460
461    /// Path for one conversation id.
462    pub fn path_of(&self, id: &str) -> PathBuf {
463        self.root.join(format!("{id}.json"))
464    }
465
466    /// Where one conversation's prompts and CLI output are kept, beside the
467    /// record rather than inside it.
468    pub fn artifacts_of(&self, id: &str) -> PathBuf {
469        self.root.join(format!("{id}.artifacts"))
470    }
471
472    /// Where this conversation's attached images live: a subdirectory of
473    /// `artifacts_of`, so deleting the conversation deletes its attachments
474    /// too and nothing here needs its own cleanup path.
475    pub fn attachments_dir(&self, id: &str) -> PathBuf {
476        self.artifacts_of(id).join("attachments")
477    }
478
479    /// Persist one already-validated attachment and return its metadata.
480    ///
481    /// `web::talk_attachment_post` is the only caller: it has already
482    /// checked `mime` against the whitelist and sniffed the bytes, so an
483    /// unrecognised mime reaching here is a bug in that caller, not
484    /// something an operator did. The id is minted here and never taken
485    /// from the client; `name` is stored for display only and never used to
486    /// build a path.
487    pub fn put_attachment(
488        &self,
489        id: &str,
490        mime: &str,
491        name: &str,
492        data: &[u8],
493    ) -> Result<Attachment> {
494        let dir = self.attachments_dir(id);
495        std::fs::create_dir_all(&dir).with_context(|| format!("create {}", dir.display()))?;
496        let ext = attachment_ext(mime).with_context(|| format!("unsupported mime `{mime}`"))?;
497        let att = Attachment {
498            id: new_attachment_id(),
499            name: name.to_owned(),
500            mime: mime.to_owned(),
501            bytes: data.len() as u64,
502        };
503        std::fs::write(dir.join(format!("{}.{ext}", att.id)), data)
504            .with_context(|| format!("write attachment {}", att.id))?;
505        std::fs::write(
506            dir.join(format!("{}.json", att.id)),
507            serde_json::to_string(&att).context("serialize attachment")?,
508        )
509        .with_context(|| format!("write attachment metadata {}", att.id))?;
510        Ok(att)
511    }
512
513    /// Just the metadata, without reading the image bytes back off disk -
514    /// what `web::talk_say` uses to turn an id the operator referenced into
515    /// an [`Attachment`] before appending a [`Turn`], where the bytes
516    /// themselves are of no interest. `None` for an id this conversation
517    /// never stored - including one that merely looks plausible:
518    /// [`valid_attachment_id`] is checked here too, not only by the caller,
519    /// the same defence-in-depth `Questions::panel_asset` uses for its own
520    /// asset ids.
521    pub fn attachment_meta(&self, id: &str, att_id: &str) -> Result<Option<Attachment>> {
522        if !valid_attachment_id(att_id) {
523            return Ok(None);
524        }
525        let meta_path = self.attachments_dir(id).join(format!("{att_id}.json"));
526        if !meta_path.is_file() {
527            return Ok(None);
528        }
529        let att = serde_json::from_str(
530            &std::fs::read_to_string(&meta_path)
531                .with_context(|| format!("read {}", meta_path.display()))?,
532        )
533        .with_context(|| format!("parse {}", meta_path.display()))?;
534        Ok(Some(att))
535    }
536
537    /// A stored attachment's metadata and its bytes together, for serving it
538    /// back on `GET`. `None` under the same conditions as
539    /// [`Talks::attachment_meta`], which this is built on.
540    pub fn read_attachment(&self, id: &str, att_id: &str) -> Result<Option<(Attachment, Vec<u8>)>> {
541        let Some(att) = self.attachment_meta(id, att_id)? else {
542            return Ok(None);
543        };
544        let ext = attachment_ext(&att.mime).with_context(|| {
545            format!("attachment {att_id} has an unsupported mime `{}`", att.mime)
546        })?;
547        let data_path = self.attachments_dir(id).join(format!("{att_id}.{ext}"));
548        let data =
549            std::fs::read(&data_path).with_context(|| format!("read {}", data_path.display()))?;
550        Ok(Some((att, data)))
551    }
552
553    /// Absolute path of one attachment's bytes, for the prompt note [`turn`]
554    /// appends and for [`Invocation::attachments`]. `None` only for a mime
555    /// [`put_attachment`] could never have written, which means the
556    /// attachment did not come from this store.
557    ///
558    /// `self.root` (and so `attachments_dir`) is not guaranteed absolute on
559    /// its own - `run::home()` returns a bare relative `PathBuf` verbatim
560    /// when the operator sets `MAGI_HOME` to a relative path, and nothing
561    /// canonicalizes it on the way in. That is harmless for every other use
562    /// of this store, since its own I/O runs in this process against this
563    /// process's cwd - but this path is handed to a CLI invoked with `cwd:
564    /// &talk.repo`, a different directory, so a relative path here would
565    /// resolve against the wrong place once it reached the prompt.
566    /// `std::path::absolute` fixes it against *this* process's cwd before
567    /// that happens; see `disk::free_bytes_by_os` for the same function used
568    /// the same way elsewhere in this codebase.
569    fn attachment_path(&self, id: &str, att: &Attachment) -> Option<PathBuf> {
570        let ext = attachment_ext(&att.mime)?;
571        let path = self.attachments_dir(id).join(format!("{}.{ext}", att.id));
572        std::path::absolute(&path).ok()
573    }
574
575    /// Write a conversation, atomically, so a process killed mid-write leaves
576    /// the previous state readable rather than a truncated file.
577    ///
578    /// The write-then-rename itself is retried a handful of times - see
579    /// [`write_atomic`] - because a reader with the destination file briefly
580    /// open is exactly the kind of failure that must not cost an agent's
581    /// whole reply; see `turn`'s own tail for what happens when even that is
582    /// not enough.
583    pub fn put(&self, t: &mut Talk) -> Result<()> {
584        std::fs::create_dir_all(&self.root)
585            .with_context(|| format!("create {}", self.root.display()))?;
586        t.updated_at = Timestamp::now();
587        let body = serde_json::to_string_pretty(t).context("serialize talk")?;
588        let path = self.path_of(&t.id);
589        let tmp = path.with_extension("json.tmp");
590        write_atomic(&tmp, &path, &body)
591    }
592
593    /// Load a conversation by id or unambiguous id prefix.
594    pub fn get(&self, id: &str) -> Result<Talk> {
595        let resolved = self.resolve_id(id)?;
596        read_path(&self.path_of(&resolved))
597    }
598
599    /// Every conversation on disk: open first, then newest first, so what the
600    /// operator is still using belongs above what they are done with.
601    pub fn list(&self) -> Vec<Talk> {
602        self.list_counting_unreadable().0
603    }
604
605    /// [`Talks::list`], plus how many `*.json` files could not be read, so a
606    /// caller that reports to the operator can say what it skipped.
607    pub fn list_counting_unreadable(&self) -> (Vec<Talk>, usize) {
608        let mut unreadable = 0;
609        let mut all: Vec<Talk> = std::fs::read_dir(&self.root)
610            .into_iter()
611            .flatten()
612            .flatten()
613            .map(|e| e.path())
614            .filter(|p| p.extension().is_some_and(|x| x == "json"))
615            .filter_map(|p| {
616                let talk = read_path(&p).ok();
617                if talk.is_none() {
618                    unreadable += 1;
619                }
620                talk
621            })
622            .collect();
623        all.sort_unstable_by(|a, b| {
624            let rank = |t: &Talk| u8::from(!t.status.open());
625            rank(a).cmp(&rank(b)).then_with(|| b.id.cmp(&a.id))
626        });
627        (all, unreadable)
628    }
629
630    /// Expand an id prefix to exactly one conversation id.
631    pub fn resolve_id(&self, prefix: &str) -> Result<String> {
632        if self.path_of(prefix).is_file() {
633            return Ok(prefix.to_owned());
634        }
635        let hits: Vec<String> = self
636            .list()
637            .into_iter()
638            .map(|t| t.id)
639            .filter(|id| id.starts_with(prefix) || id.ends_with(prefix))
640            .collect();
641        match hits.len() {
642            1 => Ok(hits.into_iter().next().expect("exactly one hit")),
643            0 => bail!("no talk matches `{prefix}`"),
644            _ => bail!(
645                "`{prefix}` matches {} talks: {}",
646                hits.len(),
647                hits.join(", ")
648            ),
649        }
650    }
651
652    /// Change detection token: the newest modification time in the store, in
653    /// milliseconds.
654    pub fn revision(&self) -> u64 {
655        std::fs::read_dir(&self.root)
656            .into_iter()
657            .flatten()
658            .flatten()
659            .filter(|e| e.path().extension().is_none_or(|x| x != "turn"))
660            .filter(|e| !e.file_name().to_string_lossy().starts_with('.'))
661            .filter_map(|e| e.metadata().ok())
662            .filter_map(|m| m.modified().ok())
663            .filter_map(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
664            .map(|d| d.as_millis() as u64)
665            .max()
666            .unwrap_or(0)
667    }
668
669    /// How many conversations are still open.
670    pub fn count_open(&self) -> usize {
671        self.list().iter().filter(|t| t.status.open()).count()
672    }
673
674    /// Where one conversation's turn lease lives. Not a `*.json`, so
675    /// [`Talks::list`] never sees it.
676    pub fn turn_path(&self, id: &str) -> PathBuf {
677        self.root.join(format!("{id}.turn"))
678    }
679
680    /// Claim the right to run one agent turn in `id`, across processes.
681    ///
682    /// `None` means somebody else holds a fresh lease - the caller reports
683    /// "a turn is already running" and must not start one. A lease is held
684    /// while its last beat is within [`crate::ask::LEASE_TTL`]; pids are never
685    /// consulted. A stale (or unreadable) lease is taken over: renamed to a
686    /// unique name first, so of several takers only the one whose rename wins
687    /// deletes it, and the claim itself is an exclusive create.
688    pub fn claim_turn(&self, id: &str) -> Result<Option<TurnLease>> {
689        self.claim_turn_at(id, Timestamp::now())
690    }
691
692    fn claim_turn_at(&self, id: &str, now: Timestamp) -> Result<Option<TurnLease>> {
693        std::fs::create_dir_all(&self.root)
694            .with_context(|| format!("create {}", self.root.display()))?;
695        let path = self.turn_path(id);
696        let token = fresh_token();
697        if create_turn(&path, &token, now)? {
698            return Ok(Some(TurnLease {
699                talk: id.to_owned(),
700                path,
701                token,
702            }));
703        }
704        if lease_blocks(&path, now) {
705            return Ok(None);
706        }
707        // Stale or unreadable. Every replacement happens under a short-lived
708        // exclusive lock file, so two takers cannot each delete the other's
709        // fresh lease. A taker that finds the lock held simply loses; the lock
710        // itself ages out, so a taker that died inside it cannot wedge the talk.
711        let Some(_lock) = TurnLock::take(&path)? else {
712            return Ok(None);
713        };
714        if lease_blocks(&path, now) {
715            return Ok(None);
716        }
717        let _ = std::fs::remove_file(&path);
718        Ok(create_turn(&path, &token, now)?.then_some(TurnLease {
719            talk: id.to_owned(),
720            path,
721            token,
722        }))
723    }
724
725    /// Is a turn running in `id` anywhere, by a fresh lease?
726    pub fn turn_held(&self, id: &str) -> bool {
727        read_turn(&self.turn_path(id)).is_some_and(|r| r.fresh(Timestamp::now()))
728    }
729
730    /// Remove a conversation from disk, record and artifacts both. The
731    /// operator's way of saying "not just done, gone" - [`close`] alone
732    /// leaves the record as history.
733    ///
734    /// Takes [`Talks::guard`] for the same reason [`close`] does: a delete
735    /// racing a [`record`] or the tail of [`turn`] must not land between
736    /// their own read and write, or the file removed here would look, to
737    /// them, like a record that simply has not been written yet. The other
738    /// half of that story is on their side - both check under this same
739    /// guard that the record they are about to write is still there, and
740    /// give up without writing if it is not, which is what stops their `put`
741    /// from resurrecting a conversation this call already removed.
742    pub fn remove(&self, id: &str) -> Result<()> {
743        let _guard = self.guard()?;
744        let resolved = self.resolve_id(id)?;
745        let path = self.path_of(&resolved);
746        std::fs::remove_file(&path).with_context(|| format!("remove {}", path.display()))?;
747        let artifacts = self.artifacts_of(&resolved);
748        if artifacts.is_dir() {
749            std::fs::remove_dir_all(&artifacts)
750                .with_context(|| format!("remove {}", artifacts.display()))?;
751        }
752        let _ = std::fs::remove_file(self.turn_path(&resolved));
753        Ok(())
754    }
755}
756
757/// What [`Talks::guard`] hands out: the in-process mutex plus the
758/// cross-process file lock. The file lock is released first.
759struct StoreGuard<'a> {
760    _file: TurnLock,
761    _mutex: MutexGuard<'a, ()>,
762}
763
764/// The body of a `<id>.turn` file. `pid` is for a human reading it; nothing
765/// decides on it.
766#[derive(Debug, Serialize, Deserialize)]
767struct TurnRecord {
768    token: String,
769    pid: u32,
770    beat_at: Timestamp,
771}
772
773impl TurnRecord {
774    fn fresh(&self, now: Timestamp) -> bool {
775        now.as_second() - self.beat_at.as_second() <= crate::ask::LEASE_TTL.as_secs() as i64
776    }
777}
778
779/// A token no other caller in this process shares: `rng::entropy` is the
780/// clock and the pid, so two threads in one clock tick would otherwise get the
781/// same token, and with it the same temp file name and the same identity.
782fn fresh_token() -> String {
783    static SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
784    let n = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
785    let seed = crate::rng::entropy() ^ n.wrapping_mul(0x9E37_79B9_7F4A_7C15);
786    crate::rng::SplitMix64::new(seed).uuid_v4()
787}
788
789fn read_turn(path: &Path) -> Option<TurnRecord> {
790    serde_json::from_str(&std::fs::read_to_string(path).ok()?).ok()
791}
792
793/// A takeover lock older than this belonged to a taker that died inside it.
794const TAKEOVER_LOCK_TTL: Duration = Duration::from_secs(10);
795
796/// A break ticket older than this belonged to a taker that died holding it;
797/// the next generation's ticket may then be tried for the same dead token.
798const TICKET_TTL: Duration = Duration::from_secs(10);
799
800/// Most ticket generations tried for one dead token.
801const TICKET_GENERATIONS: u32 = 16;
802
803/// Tickets are forgotten only this long after their last write.
804const TICKET_SWEEP_AGE: Duration = Duration::from_secs(3600);
805
806/// Create `path` exclusively with `body`; `false` when it already exists.
807fn create_exclusive(path: &Path, body: &str) -> Result<bool> {
808    use std::io::Write as _;
809    match std::fs::OpenOptions::new()
810        .write(true)
811        .create_new(true)
812        .open(path)
813    {
814        Ok(mut f) => {
815            if let Err(e) = f.write_all(body.as_bytes()) {
816                drop(f);
817                let _ = std::fs::remove_file(path);
818                return Err(e).with_context(|| format!("write {}", path.display()));
819            }
820            Ok(true)
821        }
822        Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => Ok(false),
823        Err(e) => Err(e).with_context(|| format!("create {}", path.display())),
824    }
825}
826
827fn create_turn(path: &Path, token: &str, now: Timestamp) -> Result<bool> {
828    let record = TurnRecord {
829        token: token.to_owned(),
830        pid: std::process::id(),
831        beat_at: now,
832    };
833    let body = serde_json::to_string(&record).context("serialize turn lease")?;
834    // Written in full under a private name, then published exclusively: a
835    // reader never sees a half-written lease.
836    let tmp = path.with_extension(format!("turn.{token}.new"));
837    publish_exclusive(path, &tmp, &body)
838}
839
840/// Is there a lease at `path` that must not be taken over? A fresh beat, or
841/// an empty file young enough to be a [`publish_exclusive`] placeholder whose
842/// writer has not yet renamed the real record into place.
843fn lease_blocks(path: &Path, now: Timestamp) -> bool {
844    if read_turn(path).is_some_and(|r| r.fresh(now)) {
845        return true;
846    }
847    std::fs::metadata(path).is_ok_and(|m| {
848        m.len() == 0
849            && m.modified()
850                .ok()
851                .and_then(|t| t.elapsed().ok())
852                .is_some_and(|age| age <= TAKEOVER_LOCK_TTL)
853    })
854}
855
856/// Does this error mean the filesystem has no hard links (as opposed to an
857/// ordinary I/O failure, which must not be hidden by a fallback)?
858fn link_unsupported(e: &std::io::Error) -> bool {
859    e.kind() == std::io::ErrorKind::Unsupported || (cfg!(windows) && e.raw_os_error() == Some(1))
860}
861
862/// Publish the finished file `tmp` (holding `body`) at `path` unless `path`
863/// exists; `false` when it does. `tmp` is always removed.
864///
865/// The first choice is `hard_link`, which is exclusive and atomic. Where hard
866/// links are unsupported the fallback is an exclusive `create_new` of `path`
867/// itself, written through that handle (never a `rename` over `path`, which
868/// would let a stalled writer clobber a successor). Readers can briefly see
869/// the file empty: [`lease_blocks`] treats a young empty one as held, and a
870/// lock side treats it as an "invalid" token that cannot be broken for
871/// [`TAKEOVER_LOCK_TTL`]. Residual windows, not closable by path alone: a
872/// reader may see a partly written file for the length of one small write, and
873/// a writer stalled between create and write for longer than the TTL can have
874/// its file replaced; it then finds the path no longer carries its body and
875/// reports `false`.
876/// The no-hard-link path of [`publish_exclusive`]. A failed write never
877/// removes `path`: by then it may belong to a successor, so the half-made file
878/// is left to expire (a young empty one blocks, an unreadable one is stale).
879fn create_in_place(path: &Path, body: &str) -> Result<bool> {
880    use std::io::Write as _;
881    let mut f = match std::fs::OpenOptions::new()
882        .write(true)
883        .create_new(true)
884        .open(path)
885    {
886        Ok(f) => f,
887        Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => return Ok(false),
888        Err(e) => return Err(e).with_context(|| format!("create {}", path.display())),
889    };
890    f.write_all(body.as_bytes())
891        .with_context(|| format!("write {}", path.display()))?;
892    // Written through our own handle, so a stalled writer can only write into
893    // its own file; confirm the path still carries it before claiming it.
894    Ok(std::fs::read_to_string(path).is_ok_and(|t| t == body))
895}
896
897fn publish_exclusive(path: &Path, tmp: &Path, body: &str) -> Result<bool> {
898    std::fs::write(tmp, body).with_context(|| format!("write {}", tmp.display()))?;
899    #[cfg(test)]
900    let linked = if failpoint::no_link_forced() {
901        Err(std::io::Error::from(std::io::ErrorKind::Unsupported))
902    } else {
903        std::fs::hard_link(tmp, path)
904    };
905    #[cfg(not(test))]
906    let linked = std::fs::hard_link(tmp, path);
907    let out = match linked {
908        Ok(()) => Ok(true),
909        Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => Ok(false),
910        Err(e) if link_unsupported(&e) => create_in_place(path, body),
911        Err(e) => Err(e).with_context(|| format!("create {}", path.display())),
912    };
913    let _ = std::fs::remove_file(tmp);
914    out
915}
916
917/// Remove `path` only if it carries exactly `expected`; `true` when it did.
918///
919/// There is no atomic compare-and-unlink on a path, so the file is first
920/// renamed to a private name, which makes the read and the removal act on the
921/// same inode. If it carried something else (a newer holder published between
922/// the caller's read and now) it is put back exclusively, so the wrong lock is
923/// off the path for microseconds instead of deleted. Residual window: in those
924/// microseconds a fourth party can publish at `path`; the restore then loses,
925/// the displaced file is dropped (with a warning) and two holders can overlap
926/// until the survivor's TTL. Path operations alone cannot close that.
927fn remove_if_carries(path: &Path, expected: &str) -> bool {
928    let gone = path.with_extension(format!("gone.{}", fresh_token()));
929    if std::fs::rename(path, &gone).is_err() {
930        return false;
931    }
932    let found = std::fs::read_to_string(&gone);
933    if found.as_ref().is_ok_and(|t| t == expected) {
934        let _ = std::fs::remove_file(&gone);
935        return true;
936    }
937    if let Ok(body) = found {
938        let back = path.with_extension(format!("back.{}", fresh_token()));
939        match publish_exclusive(path, &back, &body) {
940            Ok(true) => {}
941            Ok(false) | Err(_) => tracing::warn!(
942                "{} was replaced while a stale removal had it aside; \
943                 the displaced file is dropped",
944                path.display()
945            ),
946        }
947    }
948    let _ = std::fs::remove_file(&gone);
949    false
950}
951
952/// The short exclusive lock every change to an existing lease (takeover, beat,
953/// release) happens under, so none of them can act on a stale reading. It
954/// ages out after [`TAKEOVER_LOCK_TTL`] in case its holder died inside it.
955struct TurnLock {
956    path: PathBuf,
957    token: String,
958}
959
960impl TurnLock {
961    fn token() -> String {
962        fresh_token()
963    }
964
965    /// Publish `token` at `path` complete (written privately, then published
966    /// exclusively), so nobody reads a half-written token; `false` if `path`
967    /// exists.
968    fn publish(path: &Path, token: &str) -> Result<bool> {
969        let tmp = path.with_extension(format!("lock.{token}.new"));
970        publish_exclusive(path, &tmp, token)
971    }
972
973    fn take(lease: &Path) -> Result<Option<Self>> {
974        let path = lease.with_extension("turn.lock");
975        let token = Self::token();
976        if Self::publish(&path, &token)? {
977            return Ok(Some(Self { path, token }));
978        }
979        let Ok(seen) = std::fs::read_to_string(&path) else {
980            return Ok(None);
981        };
982        // A lock that is not a whole token (an older build wrote it in two
983        // steps) is breakable too, under one fixed ticket name.
984        let key = if !seen.is_empty() && seen.chars().all(|c| c.is_ascii_alphanumeric() || c == '-')
985        {
986            seen.as_str()
987        } else {
988            "invalid"
989        };
990        let aged = std::fs::metadata(&path)
991            .and_then(|m| m.modified())
992            .ok()
993            .and_then(|t| t.elapsed().ok())
994            .is_some_and(|age| age > TAKEOVER_LOCK_TTL);
995        if !aged {
996            return Ok(None);
997        }
998        // Breaking a dead lock is decided by a ticket named after the token
999        // that was judged dead: exactly one taker per generation can create
1000        // it. The lock itself is never moved aside, so a fresh lock made by
1001        // the winner is never off the path, not even for an instant.
1002        //
1003        // The ticket name carries a generation, not the wall clock, so no
1004        // time boundary can let a second taker in while a ticket is alive.
1005        // Generation n+1 is tried only when ticket n is older than
1006        // `TICKET_TTL` (its owner died). Residual risk, same kind as the lock's
1007        // own TTL: an owner stalled past `TICKET_TTL` between creating its
1008        // ticket and publishing can overlap with the next generation's taker.
1009        let mut won = false;
1010        for n in 0..TICKET_GENERATIONS {
1011            let ticket = path.with_extension(format!("lock.{key}.break.{n}"));
1012            if create_exclusive(&ticket, "")? {
1013                won = true;
1014                break;
1015            }
1016            let stale = std::fs::metadata(&ticket)
1017                .and_then(|m| m.modified())
1018                .ok()
1019                .and_then(|t| t.elapsed().ok())
1020                .is_some_and(|age| age > TICKET_TTL);
1021            if !stale {
1022                return Ok(None);
1023            }
1024        }
1025        if !won {
1026            // Every generation was abandoned. A ticket is never unlinked by
1027            // name while it may still be someone's exclusion: only the sweep
1028            // removes tickets, and only ones far older than any taker lives,
1029            // so recovery resumes once they age out.
1030            Self::sweep_tickets(&path);
1031            return Ok(None);
1032        }
1033        Self::sweep_tickets(&path);
1034        // Only the ticket's owner reaches this point for `seen`, but the
1035        // lock's own holder may still release it (its `Drop`) and a third
1036        // taker publish a new one meanwhile, so the removal is verified
1037        // against the content (see [`remove_if_carries`] for the window that
1038        // remains); if the lock changed, leave it.
1039        if !remove_if_carries(&path, &seen) {
1040            return Ok(None);
1041        }
1042        if Self::publish(&path, &token)? {
1043            return Ok(Some(Self { path, token }));
1044        }
1045        Ok(None)
1046    }
1047
1048    /// Forget tickets far older than the lock's TTL. They stay that long so a
1049    /// slow taker that read the same dead token cannot break it a second time.
1050    fn sweep_tickets(path: &Path) {
1051        let (Some(dir), Some(name)) = (path.parent(), path.file_name().and_then(|n| n.to_str()))
1052        else {
1053            return;
1054        };
1055        let prefix = format!("{name}.");
1056        let Ok(entries) = std::fs::read_dir(dir) else {
1057            return;
1058        };
1059        for entry in entries.flatten() {
1060            let file = entry.file_name();
1061            let Some(file) = file.to_str() else { continue };
1062            if !(file.starts_with(&prefix) && file.contains(".break.")) {
1063                continue;
1064            }
1065            let old = entry
1066                .metadata()
1067                .and_then(|m| m.modified())
1068                .ok()
1069                .and_then(|t| t.elapsed().ok())
1070                .is_some_and(|age| age > TICKET_SWEEP_AGE);
1071            if old {
1072                let _ = std::fs::remove_file(entry.path());
1073            }
1074        }
1075    }
1076
1077    /// Wait briefly for the lock; the holders only do a read and a write.
1078    fn take_patiently(lease: &Path) -> Option<Self> {
1079        for _ in 0..50 {
1080            match Self::take(lease) {
1081                Ok(Some(lock)) => return Some(lock),
1082                Ok(None) => std::thread::sleep(Duration::from_millis(10)),
1083                Err(_) => return None,
1084            }
1085        }
1086        None
1087    }
1088}
1089
1090impl Drop for TurnLock {
1091    fn drop(&mut self) {
1092        // Only our own lock: one that aged out and was taken over is not ours.
1093        remove_if_carries(&self.path, &self.token);
1094    }
1095}
1096
1097/// How often a running turn renews its lease: well inside
1098/// [`crate::ask::LEASE_TTL`].
1099pub const TURN_BEAT: Duration = Duration::from_secs(20);
1100
1101/// One talk's cross-process turn slot, released on drop (success, error,
1102/// panic or a dropped handler future alike). Release only removes the file
1103/// while it still carries this lease's token, so a guard that outlived its
1104/// own expiry cannot delete the lease of whoever took over.
1105#[derive(Debug)]
1106pub struct TurnLease {
1107    talk: String,
1108    path: PathBuf,
1109    token: String,
1110}
1111
1112impl TurnLease {
1113    /// Does the lease file still carry this lease's token? A read only.
1114    pub fn holds(&self) -> bool {
1115        read_turn(&self.path).is_some_and(|r| r.token == self.token)
1116    }
1117
1118    /// Renew the lease. `Ok(false)` means it was taken over or removed, so
1119    /// this turn no longer owns the slot; `Err` is a transient failure (the
1120    /// lock stayed busy, a write failed) and the next beat tries again.
1121    pub fn beat(&self) -> Result<bool> {
1122        let _lock = TurnLock::take_patiently(&self.path)
1123            .with_context(|| format!("lock {} to renew it", self.path.display()))?;
1124        let Some(mut record) = read_turn(&self.path).filter(|r| r.token == self.token) else {
1125            return Ok(false);
1126        };
1127        record.beat_at = Timestamp::now();
1128        let body = serde_json::to_string(&record).context("serialize turn lease")?;
1129        let tmp = self.path.with_extension(format!("turn.{}.tmp", self.token));
1130        write_atomic(&tmp, &self.path, &body)?;
1131        Ok(true)
1132    }
1133
1134    /// Run `fut` while renewing this lease every [`TURN_BEAT`]. A transient
1135    /// beat failure is logged and the turn goes on; a lost lease drops `fut`
1136    /// (the turn stops) and is an error, since somebody else may now be
1137    /// running the same conversation.
1138    pub async fn beating<T>(&self, fut: impl std::future::Future<Output = T>) -> Result<T> {
1139        self.beating_every(TURN_BEAT, fut).await
1140    }
1141
1142    async fn beating_every<T>(
1143        &self,
1144        period: Duration,
1145        fut: impl std::future::Future<Output = T>,
1146    ) -> Result<T> {
1147        tokio::pin!(fut);
1148        loop {
1149            match tokio::time::timeout(period, &mut fut).await {
1150                Ok(out) => return Ok(out),
1151                Err(_) => match self.beat() {
1152                    Ok(true) => {}
1153                    Ok(false) => bail!(
1154                        "the turn lease {} was taken over; this turn is stopped",
1155                        self.path.display()
1156                    ),
1157                    Err(e) => tracing::warn!("{e:#}"),
1158                },
1159            }
1160        }
1161    }
1162}
1163
1164impl Drop for TurnLease {
1165    fn drop(&mut self) {
1166        // Under the lock, so a takeover cannot slip in between the check and
1167        // the removal. If the lock stays busy the lease just ages out.
1168        if let Some(_lock) = TurnLock::take_patiently(&self.path) {
1169            if read_turn(&self.path).is_some_and(|r| r.token == self.token) {
1170                let _ = std::fs::remove_file(&self.path);
1171            }
1172        }
1173    }
1174}
1175
1176/// Open a conversation. Takes no agent turn: there is no idea to answer yet,
1177/// and a conversation the operator has not said anything into yet is a
1178/// normal, valid thing to have sitting on the phone.
1179///
1180/// `agent` beats `[roles] chatter`, which beats [`agent::pick`]'s own default
1181/// order (a claude seat, else the first runnable agent in roster order) when
1182/// nothing names a seat at all - see `[roles] chatter`'s own doc in
1183/// [`crate::config`] for why a dedicated field exists rather than reusing a
1184/// judge seat.
1185pub fn begin(store: &Talks, cfg: &Config, repo: PathBuf, agent: Option<&str>) -> Result<Talk> {
1186    begin_with(store, cfg, repo, agent, &Preferred::default())
1187}
1188
1189/// Remembered choices for a new conversation (`POST /api/talks`). Every field
1190/// is soft: one that does not fit `cfg` is dropped on its own and the default
1191/// stands, so a stale remembered value never stops a conversation opening.
1192#[derive(Debug, Default, Clone)]
1193pub struct Preferred {
1194    /// Remembered agent id.
1195    pub agent: Option<String>,
1196    /// Remembered persona id.
1197    pub persona: Option<String>,
1198    /// Remembered implementer count.
1199    pub implementers: Option<i64>,
1200}
1201
1202/// [`begin`] with remembered choices. An explicit `agent` wins over
1203/// `preferred.agent` and keeps its strict error. A preferred agent that is on
1204/// the roster and runnable is an explicit choice (`fallback = false`) unless
1205/// it is the chatter chain's own head. Persona and implementers are applied
1206/// before the single save, so neither is marked dirty: the new seat's briefing
1207/// already carries them.
1208pub fn begin_with(
1209    store: &Talks,
1210    cfg: &Config,
1211    repo: PathBuf,
1212    agent: Option<&str>,
1213    preferred: &Preferred,
1214) -> Result<Talk> {
1215    // Absolute: a relative path means the wrong repository once anything
1216    // other than this process reads it back.
1217    let repo = repo.canonicalize().unwrap_or(repo);
1218    // An explicit agent is a chain of one; otherwise the first id of
1219    // `[roles] chatter` that can run here (later ones are `turn`'s fallbacks).
1220    let head = || -> Result<AgentSpec> {
1221        Ok(agent::pick_chain(
1222            &cfg.agents,
1223            cfg.roles.chatter.as_ref(),
1224            &agent::installed,
1225            "chatter",
1226        )?
1227        .remove(0))
1228    };
1229    let mut fallback = agent.is_none();
1230    let spec = match agent {
1231        Some(id) => agent::pick(&cfg.agents, Some(id), &agent::installed)?,
1232        None => {
1233            match preferred
1234                .agent
1235                .as_deref()
1236                .map(str::trim)
1237                .filter(|id| !id.is_empty())
1238            {
1239                Some(id) => match agent::pick(&cfg.agents, Some(id), &agent::installed) {
1240                    Ok(spec) => {
1241                        fallback = head().is_ok_and(|head| spec.id == head.id);
1242                        spec
1243                    }
1244                    Err(_) => head()?,
1245                },
1246                None => head()?,
1247            }
1248        }
1249    };
1250    let persona = preferred
1251        .persona
1252        .as_deref()
1253        .and_then(|id| crate::persona::find(&cfg.talk.personas, id))
1254        .filter(|p| !p.is_default())
1255        .map(|p| p.id)
1256        .unwrap_or_default();
1257    let implementers = preferred
1258        .implementers
1259        .and_then(|n| u8::try_from(n).ok())
1260        .and_then(|n| check_implementers(n, cfg).ok())
1261        .unwrap_or(1);
1262
1263    let now = Timestamp::now();
1264    let mut talk = Talk {
1265        pending_breaks: None,
1266        schema: SCHEMA,
1267        id: new_id(),
1268        repo,
1269        agent: spec.id.clone(),
1270        status: TalkStatus::Open,
1271        turns: Vec::new(),
1272        pending: String::new(),
1273        pending_attachments: Vec::new(),
1274        fallback,
1275        persona,
1276        persona_dirty: false,
1277        implementers,
1278        implementers_dirty: false,
1279        notified: Vec::new(),
1280        created_at: now,
1281        updated_at: now,
1282        seat: SeatState::new(SEAT, &spec.id, crate::rng::entropy()),
1283    };
1284    store.put(&mut talk)?;
1285    Ok(talk)
1286}
1287
1288/// Append the operator's turn and flush it, without invoking anything.
1289///
1290/// Split out of [`say`] so `POST /api/talks/{id}/say` can answer once the
1291/// message is safely on disk, and run the agent's half in the background -
1292/// holding the connection for a turn that can run fifteen minutes is the
1293/// wrong shape for a phone.
1294pub fn record(
1295    talk: &mut Talk,
1296    store: &Talks,
1297    text: &str,
1298    attachments: Vec<Attachment>,
1299) -> Result<String> {
1300    // `web::talk_say` reads the talk, then awaits config discovery before
1301    // calling this - a gap a concurrent `POST /api/talks/{id}/close` can land
1302    // in. The guard held for the rest of this function is what actually closes
1303    // that gap: re-reading status without it only shrinks the window a
1304    // concurrent `close` could land in between this call's own read and its
1305    // `put`, it does not remove it. See [`Talks::guard`] and the matching
1306    // guard in `turn`, which this mirrors.
1307    let _guard = store.guard()?;
1308    // A concurrent `Talks::remove` can have landed in that same gap. `put`
1309    // writes unconditionally, so trusting the stale `talk` here would recreate
1310    // the file a delete just removed - the record must still be there for a
1311    // turn to have anywhere to append to.
1312    let Ok(fresh) = store.get(&talk.id) else {
1313        bail!("talk {} was deleted", talk.short());
1314    };
1315    talk.status = fresh.status;
1316    // Do not let this older handle overwrite a draft accepted while it was
1317    // waiting for configuration discovery.
1318    talk.pending = fresh.pending;
1319    talk.pending_breaks = fresh.pending_breaks;
1320    talk.pending_attachments = fresh.pending_attachments;
1321    talk.notified = fresh.notified;
1322    if !talk.status.open() {
1323        bail!(
1324            "talk {} is {} and takes no more turns",
1325            talk.short(),
1326            talk.status.as_str()
1327        );
1328    }
1329    let text = text.trim();
1330    if text.is_empty() && attachments.is_empty() {
1331        bail!("nothing to say");
1332    }
1333    talk.turns.push(Turn {
1334        who: Who::Operator,
1335        body: text.to_owned(),
1336        at: Timestamp::now(),
1337        attachments,
1338        usage: None,
1339        breaks: Some(Vec::new()),
1340        posted_by: None,
1341    });
1342    store.put(talk)?;
1343    Ok(text.to_owned())
1344}
1345
1346/// Add an unrecorded message to the durable draft while another turn runs.
1347pub fn queue(
1348    talk: &mut Talk,
1349    store: &Talks,
1350    text: &str,
1351    attachments: Vec<Attachment>,
1352) -> Result<()> {
1353    queue_keyed(talk, store, text, attachments, None).map(|_| ())
1354}
1355
1356/// [`queue`] for a message that must be accepted at most once: `key` is
1357/// recorded in [`Talk::notified`] in the same write as the draft, so a retry
1358/// after a crash (or a second sweep) finds the key and queues nothing.
1359/// Returns whether this call queued it.
1360pub fn queue_once(talk: &mut Talk, store: &Talks, text: &str, key: &str) -> Result<bool> {
1361    queue_keyed(talk, store, text, Vec::new(), Some(key))
1362}
1363
1364fn queue_keyed(
1365    talk: &mut Talk,
1366    store: &Talks,
1367    text: &str,
1368    attachments: Vec<Attachment>,
1369    key: Option<&str>,
1370) -> Result<bool> {
1371    let text = text.trim();
1372    if text.is_empty() && attachments.is_empty() {
1373        bail!("nothing to say");
1374    }
1375    let _guard = store.guard()?;
1376    let mut fresh = store
1377        .get(&talk.id)
1378        .with_context(|| format!("talk {} was deleted", talk.short()))?;
1379    if !fresh.status.open() {
1380        bail!(
1381            "talk {} is {} and takes no more turns",
1382            fresh.short(),
1383            fresh.status.as_str()
1384        );
1385    }
1386    if let Some(key) = key {
1387        if fresh.notified.iter().any(|k| k == key) {
1388            *talk = fresh;
1389            return Ok(false);
1390        }
1391        fresh.notified.push(key.to_owned());
1392    }
1393    if !text.is_empty() {
1394        if fresh.pending.is_empty() {
1395            fresh.pending = text.to_owned();
1396            fresh.pending_breaks = Some(Vec::new());
1397        } else {
1398            fresh.pending.push_str("\n\n");
1399            if let Some(b) = fresh.pending_breaks.as_mut() {
1400                b.push(fresh.pending.len());
1401            }
1402            fresh.pending.push_str(text);
1403        }
1404    }
1405    fresh.pending_attachments.extend(attachments);
1406    store.put(&mut fresh)?;
1407    *talk = fresh;
1408    Ok(true)
1409}
1410
1411/// Append an agent-authored message to the transcript without starting a
1412/// turn (`magi talk post`). `by` is the posting seat's run id. No draft, no
1413/// lease, no agent call: it only writes under the store guard, onto the
1414/// freshest record, so it cannot lose a concurrent reply.
1415pub fn post(store: &Talks, talk_id: &str, body: &str, by: &str) -> Result<()> {
1416    let body = body.trim();
1417    if body.is_empty() {
1418        bail!("nothing to post");
1419    }
1420    let _guard = store.guard()?;
1421    let mut fresh = store
1422        .get(talk_id)
1423        .with_context(|| format!("talk {talk_id} does not exist"))?;
1424    if !fresh.status.open() {
1425        bail!(
1426            "talk {} is closed and takes no more messages",
1427            fresh.short()
1428        );
1429    }
1430    fresh.turns.push(Turn {
1431        who: Who::Agent,
1432        body: body.to_owned(),
1433        at: Timestamp::now(),
1434        attachments: Vec::new(),
1435        usage: None,
1436        breaks: None,
1437        posted_by: Some(by.to_owned()),
1438    });
1439    store.put(&mut fresh)
1440}
1441
1442/// Posts appended by task seats since the chat agent last answered, as a
1443/// prompt block. The agent's CLI session never saw them.
1444pub fn posts_since_last_reply(talk: &Talk) -> Option<String> {
1445    let mut posts: Vec<&Turn> = talk
1446        .turns
1447        .iter()
1448        .rev()
1449        .take_while(|t| t.who == Who::Operator || t.posted_by.is_some())
1450        .filter(|t| t.posted_by.is_some())
1451        .collect();
1452    if posts.is_empty() {
1453        return None;
1454    }
1455    posts.reverse();
1456    let mut out = String::from("# Posted by a task\n\n");
1457    for t in posts {
1458        out.push_str(&format!(
1459            "Task seat {} posted to this conversation: {}\n\n",
1460            short(t.posted_by.as_deref().unwrap_or_default()),
1461            t.body
1462        ));
1463    }
1464    Some(out)
1465}
1466
1467/// Promote the current durable draft to one operator turn.
1468pub fn drain(talk: &mut Talk, store: &Talks) -> Result<Option<String>> {
1469    let _guard = store.guard()?;
1470    let mut fresh = store
1471        .get(&talk.id)
1472        .with_context(|| format!("talk {} was deleted", talk.short()))?;
1473    if !fresh.status.open() || (fresh.pending.is_empty() && fresh.pending_attachments.is_empty()) {
1474        *talk = fresh;
1475        return Ok(None);
1476    }
1477    let text = std::mem::take(&mut fresh.pending);
1478    let attachments = std::mem::take(&mut fresh.pending_attachments);
1479    let breaks = fresh.pending_breaks.take();
1480    fresh.turns.push(Turn {
1481        who: Who::Operator,
1482        body: text.clone(),
1483        at: Timestamp::now(),
1484        attachments,
1485        usage: None,
1486        breaks,
1487        posted_by: None,
1488    });
1489    store.put(&mut fresh)?;
1490    *talk = fresh;
1491    Ok(Some(text))
1492}
1493
1494/// One operator turn and one agent turn, appended - the synchronous form, used
1495/// by tests and by anything that is fine waiting out the turn itself.
1496pub async fn say(
1497    lease: &TurnLease,
1498    talk: &mut Talk,
1499    store: &Talks,
1500    cfg: &Config,
1501    text: &str,
1502    attachments: Vec<Attachment>,
1503) -> Result<()> {
1504    check_lease(lease, talk)?;
1505    let text = record(talk, store, text, attachments)?;
1506    respond(lease, talk, store, cfg, &text).await
1507}
1508
1509/// The agent's half of a turn: invoke, append, flush. Pairs with [`record`].
1510///
1511/// Requires the talk's [`TurnLease`] (from [`Talks::claim_turn`]), so no
1512/// starter can run a turn without holding the cross-process slot. The lease is
1513/// renewed while the turn runs; a lease lost mid-turn stops it with an error.
1514pub async fn respond(
1515    lease: &TurnLease,
1516    talk: &mut Talk,
1517    store: &Talks,
1518    cfg: &Config,
1519    text: &str,
1520) -> Result<()> {
1521    check_lease(lease, talk)?;
1522    lease
1523        .beating(turn(talk, store, cfg, text))
1524        .await
1525        .and_then(|done| done)
1526}
1527
1528fn check_lease(lease: &TurnLease, talk: &Talk) -> Result<()> {
1529    if lease.talk != talk.id {
1530        bail!("the turn lease is for talk {}, not {}", lease.talk, talk.id);
1531    }
1532    // A lease that aged out and was taken over must not start a turn (or
1533    // write the operator's text) at all.
1534    if !lease.holds() {
1535        bail!("the turn lease for talk {} is no longer held", talk.short());
1536    }
1537    Ok(())
1538}
1539
1540/// Close a conversation. Idempotent: closing an already-closed conversation is
1541/// not an error, since the operator's intent - "I am done with this" - is
1542/// already satisfied.
1543///
1544/// Re-reads the record under [`Talks::guard`] rather than trusting the
1545/// caller's copy of `talk`, and writes that fresh copy back rather than the
1546/// one passed in. `web::talk_close` loads `talk` and calls this right after
1547/// with no gap of its own, but without the guard that load can still land
1548/// between a `record` or `turn` elsewhere reading the file and writing it
1549/// back - and a close built on the older snapshot would put it right back,
1550/// silently dropping whatever turn the other call had just appended.
1551///
1552/// If the re-read fails, this errors rather than falling back to the
1553/// caller's stale copy: `talk::begin` always `put`s the record before handing
1554/// out a `Talk`, so the only way a re-read can fail is a concurrent
1555/// [`Talks::remove`] having deleted it, and writing the stale copy back would
1556/// resurrect exactly what that delete removed.
1557pub fn close(talk: &mut Talk, store: &Talks) -> Result<()> {
1558    let _guard = store.guard()?;
1559    let mut fresh = store
1560        .get(&talk.id)
1561        .with_context(|| format!("talk {} was deleted", talk.short()))?;
1562    fresh.status = TalkStatus::Closed;
1563    // A closed conversation must not replay a draft if it is reopened later.
1564    fresh.pending.clear();
1565    fresh.pending_breaks = None;
1566    fresh.pending_attachments.clear();
1567    store.put(&mut fresh)?;
1568    *talk = fresh;
1569    Ok(())
1570}
1571
1572/// Reopen a closed conversation. Idempotent for the same reason [`close`] is:
1573/// reopening an already-open conversation is not an error, since the
1574/// operator's intent - "I want to keep talking about this" - is already
1575/// satisfied.
1576///
1577/// Written symmetrically with [`close`]: re-reads the record under
1578/// [`Talks::guard`] rather than trusting the caller's copy of `talk`, writes
1579/// that fresh copy back rather than the one passed in, and errors rather than
1580/// falling back to the stale copy if the re-read fails, for the same reasons
1581/// `close`'s doc gives.
1582pub fn reopen(talk: &mut Talk, store: &Talks) -> Result<()> {
1583    let _guard = store.guard()?;
1584    let mut fresh = store
1585        .get(&talk.id)
1586        .with_context(|| format!("talk {} was deleted", talk.short()))?;
1587    fresh.status = TalkStatus::Open;
1588    store.put(&mut fresh)?;
1589    *talk = fresh;
1590    Ok(())
1591}
1592
1593/// Hand the conversation to another roster agent.
1594///
1595/// A CLI session belongs to one CLI and cannot be carried to another, so the
1596/// seat is minted afresh rather than edited: the next turn finds
1597/// `seat.turns == 0` and re-sends the transcript, since the new agent has
1598/// heard none of it. A magi-written note records the change in the
1599/// transcript. Returns `false` (and writes nothing, not even a note) when the
1600/// stored talk already uses `spec`.
1601///
1602/// Re-reads under [`Talks::guard`], like [`close`], and errors rather than
1603/// resurrecting a record a concurrent delete removed. Refusing a closed talk
1604/// or a turn in flight is the caller's job: only it can see the latter.
1605pub fn switch_agent(talk: &mut Talk, store: &Talks, spec: &AgentSpec) -> Result<bool> {
1606    let _guard = store.guard()?;
1607    let mut fresh = store
1608        .get(&talk.id)
1609        .with_context(|| format!("talk {} was deleted", talk.short()))?;
1610    if fresh.agent == spec.id {
1611        *talk = fresh;
1612        return Ok(false);
1613    }
1614    let from = std::mem::replace(&mut fresh.agent, spec.id.clone());
1615    fresh.seat = SeatState::new(SEAT, &spec.id, crate::rng::entropy());
1616    // A deliberate switch pins the conversation to the agent chosen.
1617    fresh.fallback = false;
1618    fresh.turns.push(Turn {
1619        breaks: None,
1620        posted_by: None,
1621        who: Who::Agent,
1622        body: format!("{MAGI_NOTE}agent changed from {from} to {}", spec.id),
1623        at: Timestamp::now(),
1624        attachments: Vec::new(),
1625        usage: None,
1626    });
1627    store.put(&mut fresh)?;
1628    *talk = fresh;
1629    Ok(true)
1630}
1631
1632/// Pick the conversation's persona (`""` or `default` is the plain voice).
1633///
1634/// The CLI session keeps its seat: the change is recorded with
1635/// [`Talk::persona_dirty`] and a magi note, and the next turn tells the session
1636/// about it (or its fresh briefing already does). Returns `false` and writes
1637/// nothing when the stored persona is already `id`. Refusing a closed talk, an
1638/// unknown id or a turn in flight is the caller's job.
1639pub fn switch_persona(talk: &mut Talk, store: &Talks, id: &str) -> Result<bool> {
1640    let id = if id.trim() == crate::persona::DEFAULT_ID {
1641        ""
1642    } else {
1643        id.trim()
1644    };
1645    let _guard = store.guard()?;
1646    let mut fresh = store
1647        .get(&talk.id)
1648        .with_context(|| format!("talk {} was deleted", talk.short()))?;
1649    if fresh.persona == id {
1650        *talk = fresh;
1651        return Ok(false);
1652    }
1653    let from = std::mem::replace(&mut fresh.persona, id.to_owned());
1654    fresh.persona_dirty = true;
1655    let label = |p: &str| {
1656        if p.is_empty() {
1657            crate::persona::DEFAULT_ID.to_owned()
1658        } else {
1659            p.to_owned()
1660        }
1661    };
1662    fresh.turns.push(Turn {
1663        breaks: None,
1664        posted_by: None,
1665        who: Who::Agent,
1666        body: format!(
1667            "{MAGI_NOTE}persona changed from {} to {}",
1668            label(&from),
1669            label(id)
1670        ),
1671        at: Timestamp::now(),
1672        attachments: Vec::new(),
1673        usage: None,
1674    });
1675    store.put(&mut fresh)?;
1676    *talk = fresh;
1677    Ok(true)
1678}
1679
1680/// Discard the durable draft without adding a transcript turn.
1681pub fn clear_pending(talk: &mut Talk, store: &Talks) -> Result<()> {
1682    let _guard = store.guard()?;
1683    let mut fresh = store
1684        .get(&talk.id)
1685        .with_context(|| format!("talk {} was deleted", talk.short()))?;
1686    fresh.pending.clear();
1687    fresh.pending_breaks = None;
1688    fresh.pending_attachments.clear();
1689    store.put(&mut fresh)?;
1690    *talk = fresh;
1691    Ok(())
1692}
1693
1694/// Clear a draft only when the caller still sees its complete snapshot.
1695pub fn clear_pending_if_matches(
1696    talk: &mut Talk,
1697    store: &Talks,
1698    expected_text: &str,
1699    expected_attachments: &[String],
1700) -> Result<bool> {
1701    let _guard = store.guard()?;
1702    let mut fresh = store
1703        .get(&talk.id)
1704        .with_context(|| format!("talk {} was deleted", talk.short()))?;
1705    if !pending_matches(&fresh, expected_text, expected_attachments) {
1706        *talk = fresh;
1707        return Ok(false);
1708    }
1709    fresh.pending.clear();
1710    fresh.pending_breaks = None;
1711    fresh.pending_attachments.clear();
1712    store.put(&mut fresh)?;
1713    *talk = fresh;
1714    Ok(true)
1715}
1716
1717/// Replace just the text of the durable draft, but only if the caller's
1718/// snapshot still identifies the entire draft. This refuses to overwrite a
1719/// message another client queued or a draft the drain already promoted.
1720pub fn edit_pending_text(
1721    talk: &mut Talk,
1722    store: &Talks,
1723    text: &str,
1724    expected_text: &str,
1725    expected_attachments: &[String],
1726) -> Result<bool> {
1727    let _guard = store.guard()?;
1728    let mut fresh = store
1729        .get(&talk.id)
1730        .with_context(|| format!("talk {} was deleted", talk.short()))?;
1731    if !pending_matches(&fresh, expected_text, expected_attachments) {
1732        *talk = fresh;
1733        return Ok(false);
1734    }
1735    fresh.pending = text.trim().to_owned();
1736    fresh.pending_breaks = Some(Vec::new());
1737    store.put(&mut fresh)?;
1738    *talk = fresh;
1739    Ok(true)
1740}
1741
1742fn pending_matches(talk: &Talk, expected_text: &str, expected_attachments: &[String]) -> bool {
1743    talk.pending == expected_text
1744        && talk
1745            .pending_attachments
1746            .iter()
1747            .map(|attachment| &attachment.id)
1748            .eq(expected_attachments.iter())
1749}
1750
1751/// Invoke the conversation's agent once and append what it said.
1752///
1753/// The first turn ever taken carries the full [`briefing`], because nothing
1754/// else has told the agent what this conversation is or what it may do.
1755/// Every turn after that resends nothing when the CLI can resume its own
1756/// session, and falls back to [`transcript`] only when it cannot.
1757async fn turn(talk: &mut Talk, store: &Talks, cfg: &Config, text: &str) -> Result<()> {
1758    let spec = cfg
1759        .agents
1760        .iter()
1761        .find(|a| a.id == talk.agent)
1762        .with_context(|| {
1763            format!(
1764                "talk {} was opened with agent `{}`, which is no longer in \
1765                 the roster; restore it in magi.toml or start a new \
1766                 conversation",
1767                talk.short(),
1768                talk.agent
1769            )
1770        })?;
1771
1772    // The newest turn is always the operator message this call is answering
1773    // - `record` appended it before `turn` was ever called - so its own
1774    // attachments are what belong at the end of *this* prompt.
1775    let last_note = attachment_note(
1776        store,
1777        &talk.id,
1778        talk.turns
1779            .last()
1780            .map_or(&[][..], |t| t.attachments.as_slice()),
1781    );
1782
1783    // Every attachment this conversation has ever held, not only this
1784    // turn's: a resumed session gets a fresh process every turn, so a CLI
1785    // whose sandbox needs `--add-dir` (see `agent::build_command`) needs the
1786    // grant again to open an image from an earlier turn, even when nothing
1787    // new was attached just now.
1788    let attachment_paths: Vec<PathBuf> = talk
1789        .turns
1790        .iter()
1791        .flat_map(|t| t.attachments.iter())
1792        .filter_map(|a| store.attachment_path(&talk.id, a))
1793        .collect();
1794
1795    // A question handed to this conversation is answered with `magi answer`,
1796    // which writes the question store; a read-only sandbox refuses that. So
1797    // while such a question is still open - the hand-over turn and the turns
1798    // in which the owner decides - the turn may write, with the question store
1799    // as a writable root. It goes back to read-only once the question is
1800    // answered or abandoned. As for the deputy, what the seat may touch beyond
1801    // that rests on the prompt, not the sandbox.
1802    // `try_home`, not `Questions::open`: a unit test that never pinned a home
1803    // has no store to consult, and must not abort the turn on `run::home()`.
1804    let questions =
1805        crate::run::try_home().map(|home| crate::ask::Questions::at(home.join("questions")));
1806    let consulted = questions
1807        .as_ref()
1808        .is_some_and(|q| crate::consult::pending_consults(q, &talk.id));
1809    let consult_roots: Vec<PathBuf> = match &questions {
1810        Some(q) if consulted => vec![q.root().to_path_buf()],
1811        _ => Vec::new(),
1812    };
1813
1814    let (allow_write, unsandboxed) = turn_access(cfg.talk.allow_write, consulted);
1815
1816    let artifacts = store.artifacts_of(&talk.id);
1817    // From the transcript, not the seat: a switched agent's seat restarts at
1818    // zero and must not overwrite an earlier turn's artifacts.
1819    let operator_turns = talk.turns.iter().filter(|t| t.who == Who::Operator).count();
1820    let stem = format!("turn-{}", operator_turns.max(1));
1821    // The chat's build cache is the same shared one the graph's seats get, so
1822    // a conversation that compiles does not mint another multi-GB target dir.
1823    let cache_dir = cfg.cache_dir();
1824
1825    // The agent holding the conversation, then - only when it came from
1826    // `[roles] chatter` - the rest of that chain, each at most once.
1827    let mut chain = vec![spec.clone()];
1828    if let Some(choice) = cfg.roles.chatter.as_ref()
1829        && talk.fallback
1830    {
1831        for id in choice.ids() {
1832            if id == talk.agent || chain.iter().any(|s| s.id == id) {
1833                continue;
1834            }
1835            match agent::pick(&cfg.agents, Some(id), &agent::installed) {
1836                Ok(s) => chain.push(s),
1837                Err(e) => tracing::warn!("[roles] chatter: skipping `{id}`: {e:#}"),
1838            }
1839        }
1840    }
1841
1842    let persona = crate::persona::active(&cfg.talk.personas, &talk.persona);
1843    let operator_name = cfg.talk.operator_name();
1844    let persona_update = if talk.persona_dirty {
1845        format!(
1846            "{}\n\n",
1847            crate::persona::update_block_for(persona.as_ref(), operator_name)
1848        )
1849    } else {
1850        String::new()
1851    };
1852
1853    // The filing command is not in the transcript either, so a non-Solo count
1854    // rides on every turn that has no session to remember it.
1855    let filing_update = if talk.implementers_dirty {
1856        format!("{}\n\n", filing_update_block(talk.implementers))
1857    } else {
1858        String::new()
1859    };
1860
1861    let mut outcome = None;
1862    let mut fell_back_from: Option<String> = None;
1863    // What the conversation looked like after the first agent's failed try,
1864    // so an exhausted chain leaves exactly what a single failed seat would.
1865    let mut first_try: Option<(String, SeatState)> = None;
1866    for (n, spec) in chain.iter().enumerate() {
1867        if n > 0 {
1868            if first_try.is_none() {
1869                first_try = Some((talk.agent.clone(), talk.seat.clone()));
1870            }
1871            tracing::warn!("chat: falling back from `{}` to `{}`", talk.agent, spec.id);
1872            // A new CLI has none of the old one's conversation: a fresh seat
1873            // puts `has_session` at false and the full transcript is re-sent.
1874            fell_back_from.get_or_insert_with(|| talk.agent.clone());
1875            talk.agent = spec.id.clone();
1876            talk.seat = SeatState::new(SEAT, &spec.id, crate::rng::entropy());
1877        }
1878        let resuming = agent::has_session(spec.kind, &talk.seat, cfg.graph.sessions);
1879        let first_ever = talk.turns.len() <= 1;
1880        let body = if talk.seat.turns == 0 && first_ever {
1881            format!(
1882                "{}\n\n# Operator\n\n{text}{last_note}",
1883                briefing_for(
1884                    &talk.repo,
1885                    &cfg.graph.language,
1886                    cfg.talk.allow_write,
1887                    persona.as_ref(),
1888                    operator_name,
1889                    talk.implementers
1890                )
1891            )
1892        } else if talk.seat.turns == 0 {
1893            // A fresh seat on a conversation that already has history (the
1894            // agent was switched): the briefing, then everything said so far.
1895            format!(
1896                "{}\n\n{}\n\n# Operator\n\n{text}{last_note}",
1897                briefing_for(
1898                    &talk.repo,
1899                    &cfg.graph.language,
1900                    cfg.talk.allow_write,
1901                    persona.as_ref(),
1902                    operator_name,
1903                    talk.implementers
1904                ),
1905                transcript(talk, store)
1906            )
1907        } else if resuming {
1908            let posts = posts_since_last_reply(talk).unwrap_or_default();
1909            format!("{persona_update}{filing_update}{posts}{text}{last_note}")
1910        } else {
1911            // No session to hold the persona: the transcript never stores it,
1912            // so a non-default persona is re-sent on every such turn (the
1913            // update block already carries it when the choice just changed).
1914            let mut standing = match (&persona, talk.persona_dirty) {
1915                (Some(p), false) => format!("{}\n", crate::persona::section_for(p, operator_name)),
1916                _ => persona_update.clone(),
1917            };
1918            // The default voice has no persona section to carry the name, and
1919            // the transcript never stores the briefing's addressing line.
1920            if let (None, Some(n)) = (&persona, operator_name) {
1921                standing.push_str(&format!(
1922                    "# Addressing the operator\n{}\n",
1923                    crate::persona::addressing(n)
1924                ));
1925            }
1926            if talk.implementers_dirty || talk.implementers != 1 {
1927                standing.push_str(&format!("{}\n\n", filing_update_block(talk.implementers)));
1928            }
1929            format!("{}\n\n{standing}{text}{last_note}", transcript(talk, store))
1930        };
1931        let attempt_stem = if n == 0 {
1932            stem.clone()
1933        } else {
1934            format!("{stem}-{}", spec.id)
1935        };
1936        let inv = Invocation {
1937            cwd: &talk.repo,
1938            prompt: &body,
1939            timeout: turn_timeout(cfg),
1940            // Off unless this repository's own config opts in - see
1941            // `crate::config::Talk::allow_write` and this module's doc for why
1942            // the default keeps a conversational edit from landing in a checkout
1943            // no run or review can claim.
1944            allow_write,
1945            unsandboxed,
1946            sessions: cfg.graph.sessions,
1947            artifacts: &artifacts,
1948            stem: &attempt_stem,
1949            // The conversation's own id, so `magi task add` run from inside it is
1950            // attributed to this conversation - see `Source::Agent`.
1951            run: &talk.id,
1952            node: crate::queue::CHAT_NODE,
1953            cache_dir: cache_dir.as_deref(),
1954            attachments: &attachment_paths,
1955            writable: &consult_roots,
1956        };
1957        let result = agent::invoke(spec, &mut talk.seat, &inv).await;
1958        let advance = agent::chain_advances(&result);
1959        if n == 0 || !advance {
1960            outcome = Some(result);
1961        } else {
1962            // A later failure is only logged; the note describes the first.
1963            tracing::warn!("chat: fallback agent `{}` also failed", spec.id);
1964        }
1965        if !advance {
1966            break;
1967        }
1968    }
1969    if outcome.as_ref().is_some_and(agent::chain_advances) {
1970        // Exhausted: back to the agent the conversation had, so the note
1971        // below names it and the next turn starts from it again.
1972        if let Some((id, seat)) = first_try {
1973            talk.agent = id;
1974            talk.seat = seat;
1975            fell_back_from = None;
1976        }
1977    }
1978    let outcome = outcome.expect("a chain holds at least one agent");
1979    let note = |why: String| Turn {
1980        breaks: None,
1981        posted_by: None,
1982        who: Who::Agent,
1983        body: format!("{MAGI_NOTE}{why}"),
1984        at: Timestamp::now(),
1985        attachments: Vec::new(),
1986        usage: None,
1987    };
1988    let (reply, failure) = match outcome {
1989        Err(e) => (
1990            note(format!("could not run agent `{}`: {e}", talk.agent)),
1991            Some(format!("could not run agent `{}`: {e}", talk.agent)),
1992        ),
1993        Ok(out) if out.quota_exhausted() => {
1994            let reset = out
1995                .quota
1996                .as_ref()
1997                .and_then(|q| q.reset.clone())
1998                .map_or_else(String::new, |r| format!(" (resets {r})"));
1999            let why = format!(
2000                "agent `{}` is out of quota{reset}; your message is saved, so \
2001                 say it again when the window reopens",
2002                talk.agent
2003            );
2004            (note(why.clone()), Some(why))
2005        }
2006        Ok(out) if out.timed_out => {
2007            let why = format!(
2008                "agent `{}` did not answer within {}s; your message is saved",
2009                talk.agent,
2010                turn_timeout(cfg).as_secs()
2011            );
2012            (note(why.clone()), Some(why))
2013        }
2014        Ok(out) if !out.usable() => {
2015            let why = format!(
2016                "agent `{}` produced no answer (exit {}); your message is saved",
2017                talk.agent,
2018                out.exit_code
2019                    .map_or_else(|| "unknown".to_owned(), |c| c.to_string())
2020            );
2021            (note(why.clone()), Some(why))
2022        }
2023        Ok(out) => (
2024            Turn {
2025                breaks: None,
2026                posted_by: None,
2027                who: Who::Agent,
2028                body: out.text.trim().to_owned(),
2029                at: Timestamp::now(),
2030                attachments: Vec::new(),
2031                // `talk.agent` is whoever actually answered: a fallback has
2032                // already moved it, and an exhausted chain never reaches here.
2033                usage: out.context_tokens.map(|context_tokens| TurnUsage {
2034                    context_tokens,
2035                    agent: talk.agent.clone(),
2036                    model: cfg
2037                        .agents
2038                        .iter()
2039                        .find(|a| a.id == talk.agent)
2040                        .and_then(|a| a.model.clone()),
2041                }),
2042            },
2043            None,
2044        ),
2045    };
2046
2047    // A close landed on disk while this turn was in flight is read back here
2048    // rather than trusted from the snapshot this call started with. `store`
2049    // holds nothing else this function does not itself own - the turn guard
2050    // in `web::Ui::begin_talk_turn` keeps `turns` and `seat` this call's
2051    // alone to mutate - but `status` is not behind that guard, and an
2052    // operator's close must stick: the whole point of ending a conversation
2053    // is that an agent's answer to the last message before the close cannot
2054    // silently reopen it. The guard is what makes that read-then-write
2055    // section atomic with `close`'s own - taken only for this tail and not
2056    // for the whole invocation above, so one talk's fifteen-minute turn does
2057    // not block another talk's close from proceeding.
2058    let _guard = store.guard()?;
2059    // A delete is the more final version of that same race: `put` writes
2060    // unconditionally, so a talk removed while this turn was in flight must
2061    // stay removed rather than being written back with this turn's reply
2062    // appended to it. The reply is simply given up on - there is no
2063    // conversation left for it to belong to.
2064    let Ok(fresh) = store.get(&talk.id) else {
2065        return Ok(());
2066    };
2067    talk.status = fresh.status;
2068    // `queue` may have accepted another operator message while the CLI was
2069    // running. This handle predates that write, so preserving only `status`
2070    // would overwrite the durable draft when the reply is appended below.
2071    talk.pending = fresh.pending;
2072    talk.pending_breaks = fresh.pending_breaks;
2073    talk.pending_attachments = fresh.pending_attachments;
2074    talk.notified = fresh.notified;
2075    // A `magi talk post` landed while the CLI ran: this handle predates it.
2076    if fresh.turns.len() > talk.turns.len() {
2077        let posted: Vec<Turn> = fresh.turns[talk.turns.len()..]
2078            .iter()
2079            .filter(|t| t.posted_by.is_some())
2080            .cloned()
2081            .collect();
2082        talk.turns.extend(posted);
2083    }
2084    if let Some(from) = fell_back_from.filter(|_| failure.is_none()) {
2085        // The switch persists: quota coming back does not move the chat
2086        // home, an operator's switch does.
2087        talk.turns.push(note(format!(
2088            "agent changed from {from} to {} (fallback)",
2089            talk.agent
2090        )));
2091    }
2092    // The persona is in the session's context only once a turn has answered
2093    // (a failed one may never have reached the agent), so only then is it clean.
2094    if failure.is_none() {
2095        talk.persona_dirty = false;
2096        talk.implementers_dirty = false;
2097    }
2098    talk.turns.push(reply);
2099    if let Err(put_err) = store.put(talk) {
2100        // `Talks::put` already retried the write itself - reaching here
2101        // means a passing race is not what this is. An agent's answer,
2102        // possibly the result of an hour-long call, must not vanish with
2103        // nothing to show for it just because the very last step failed:
2104        // pop it back off, stash its text beside the conversation, and
2105        // replace it with a note the operator can actually see, the same
2106        // mechanism the failure branches above already use for a quota or a
2107        // timeout.
2108        let lost = talk.turns.pop().expect("just pushed above");
2109        let stash = stash_lost_turn(store, &talk.id, &stem, &lost);
2110        let why = match &stash {
2111            Ok(path) => format!(
2112                "agent `{}` answered, but the reply could not be saved to \
2113                 this conversation ({put_err:#}); the raw text was kept at \
2114                 {} - your message is saved, ask again",
2115                talk.agent,
2116                path.display()
2117            ),
2118            Err(stash_err) => format!(
2119                "agent `{}` answered, but the reply could not be saved to \
2120                 this conversation ({put_err:#}), and it could not be kept \
2121                 anywhere else either ({stash_err:#}); your message is \
2122                 saved, ask again",
2123                talk.agent
2124            ),
2125        };
2126        talk.turns.push(note(why.clone()));
2127        // Writing the note also carries the seat this call already advanced -
2128        // `agent::invoke` incremented `turns` and, for a vendor that reports
2129        // its own session id, recorded that too. That is what keeps the next
2130        // turn resuming the session the CLI is already holding instead of
2131        // re-opening it, so losing the reply costs the transcript a turn but
2132        // not the conversation.
2133        return match store.put(talk) {
2134            Ok(()) => bail!("{why}"),
2135            Err(note_err) => {
2136                // Even the short note failed to save, which means this
2137                // conversation's file cannot be written at all right now -
2138                // nothing is left for this call to retry or record. Pop the
2139                // note so `talk.turns` matches the transcript on disk, and
2140                // surface both failures for whoever reads the log.
2141                //
2142                // `talk.seat` is deliberately not wound back to match. The
2143                // CLI really did take the turn and really did consume this
2144                // seat's session id; pretending otherwise would be a second
2145                // untruth on top of the unwritable file, and the handle is
2146                // reloaded from disk by the next `drain` or `get` anyway -
2147                // see `web::drain_loop`. What the seat cannot do is reach
2148                // disk, so the record stays a turn behind the CLI until some
2149                // later write lands, and a turn taken before then re-opens a
2150                // session id the CLI already holds. That is the desync
2151                // `20260907-011805-fb57` is about, and tolerating it belongs
2152                // there rather than here: no write this branch could make
2153                // would help, since a failed write is exactly what put it in
2154                // this position twice over.
2155                talk.turns.pop();
2156                Err(note_err).context(why)
2157            }
2158        };
2159    }
2160
2161    match failure {
2162        Some(why) => bail!("{why}"),
2163        None => Ok(()),
2164    }
2165}
2166
2167/// Everything said so far, as prose, for a CLI that cannot resume its own
2168/// conversation.
2169fn transcript(talk: &Talk, store: &Talks) -> String {
2170    let mut out = String::from(
2171        "This conversation cannot resume on the CLI's side, so here is \
2172         everything said so far; answer only the last message.\n",
2173    );
2174    for t in &talk.turns {
2175        let who = match t.who {
2176            Who::Operator => "operator",
2177            Who::Agent if t.body.starts_with(MAGI_NOTE) => "magi",
2178            Who::Agent => "you",
2179        };
2180        out.push_str(&format!("\n## {who}\n\n{}\n", t.body.trim()));
2181        out.push_str(&attachment_note(store, &talk.id, &t.attachments));
2182    }
2183    out
2184}
2185
2186/// The section named at the end of a turn's body, listing every attachment's
2187/// absolute path and mime so the agent knows exactly what to open. Empty
2188/// when `attachments` is, which is every turn but the rare one carrying an
2189/// image, so a turn with none changes nothing about the prompt.
2190fn attachment_note(store: &Talks, talk_id: &str, attachments: &[Attachment]) -> String {
2191    if attachments.is_empty() {
2192        return String::new();
2193    }
2194    let mut out = String::from(
2195        "\n\nThe operator attached the image(s) below to this message. Open \
2196         and look at each one before you answer.\n",
2197    );
2198    for att in attachments {
2199        if let Some(path) = store.attachment_path(talk_id, att) {
2200            out.push_str(&format!("\n- {} ({})", path.display(), att.mime));
2201        }
2202    }
2203    out.push('\n');
2204    out
2205}
2206
2207/// The briefing the agent opens with, sent once as part of its first turn.
2208///
2209/// Pure, so the properties that matter can be asserted without an interview:
2210/// it names `magi task add --solo` (the route this conversation always has to
2211/// changing anything) and it never tells the agent to write a task *file* of
2212/// its own - that would compete with filing through the queue.
2213/// What a turn may do: `(allow_write, unsandboxed)`. Only the repository's own
2214/// `[talk] allow_write` lifts the CLI sandbox (codex's counterpart of claude's
2215/// `bypassPermissions`); a turn writable merely because a handed-over question
2216/// is open keeps the sandbox and gets just the question store as a writable root.
2217pub(crate) fn turn_access(talk_allow_write: bool, consulted: bool) -> (bool, bool) {
2218    (talk_allow_write || consulted, talk_allow_write)
2219}
2220
2221/// `allow_write` only ever adds an extra permission on top of that; it never
2222/// removes the queue as an option, which is why both branches keep the same
2223/// `# When the operator wants something done` section - `write_policy` is
2224/// the only part that changes.
2225///
2226/// It also tells the agent that `--repo` is not stuck naming this
2227/// conversation's own directory: `resolve_repo` (`src/main.rs`) now accepts a
2228/// short `owner/repo` or bare `repo` name and resolves it against
2229/// `[repos] roots`, the same local checkouts `magi repos` lists. Without this
2230/// line an agent asked to change some other repository has no way to know
2231/// that option exists, and the only path it can see - asking the operator to
2232/// dictate a full path - is exactly the friction this change exists to
2233/// remove. A miss or an ambiguous name still fails the command outright, so
2234/// the instruction is to ask rather than guess when that happens - the
2235/// silent-decision line this task must not cross.
2236pub fn briefing(repo: &Path, language: &str, allow_write: bool) -> String {
2237    briefing_with(repo, language, allow_write, None, None)
2238}
2239
2240/// [`briefing`] plus the selected persona's tone-only section and, when the
2241/// operator has a configured name, how to address them. `None` for both is
2242/// byte-for-byte the plain briefing. A name changed mid-session reaches a
2243/// running CLI session only on its next fresh seat (nothing is persisted).
2244pub fn briefing_with(
2245    repo: &Path,
2246    language: &str,
2247    allow_write: bool,
2248    persona: Option<&crate::persona::Persona>,
2249    operator_name: Option<&str>,
2250) -> String {
2251    briefing_for(repo, language, allow_write, persona, operator_name, 1)
2252}
2253
2254/// The most implementers a chat can ask its filed tasks to use.
2255pub const MAX_IMPLEMENTERS: u8 = 3;
2256
2257fn solo_implementers() -> u8 {
2258    1
2259}
2260
2261/// The `magi task add` flag for `n` implementers: `--solo` for one,
2262/// `--implementers N` otherwise (the two are never combined).
2263fn filing_flag(n: u8) -> String {
2264    if n <= 1 {
2265        "--solo".to_owned()
2266    } else {
2267        format!("--implementers {n}")
2268    }
2269}
2270
2271/// The note a resumed (or transcript-replayed) turn opens with after the
2272/// implementer count changed, or while it is not Solo.
2273pub fn filing_update_block(n: u8) -> String {
2274    let flag = filing_flag(n);
2275    if n <= 1 {
2276        format!(
2277            "# Task filing update\n\nThe operator changed how many implementers tasks use. \
2278             From now on file with `magi task add {flag} --repo <repo> <instruction>` \
2279             (one implementer, straight into review).\n"
2280        )
2281    } else {
2282        format!(
2283            "# Task filing update\n\nThe operator changed how many implementers tasks use. \
2284             From now on file with `magi task add {flag} --repo <repo> <instruction>` \
2285             ({n} independent implementations compete). Do not pass `--solo` \
2286             together with `--implementers`; drop any earlier `--solo`.\n"
2287        )
2288    }
2289}
2290
2291/// Validate a requested implementer count: 1..=3, and one the repository's
2292/// config can actually resolve. Never clamps.
2293pub fn check_implementers(n: u8, cfg: &crate::config::Config) -> std::result::Result<u8, String> {
2294    if !(1..=MAX_IMPLEMENTERS).contains(&n) {
2295        return Err(format!(
2296            "implementers must be 1..={MAX_IMPLEMENTERS}, got {n}"
2297        ));
2298    }
2299    if n > 1 {
2300        let mut cfg = cfg.clone();
2301        crate::queue::RunOverrides {
2302            candidates: Some(usize::from(n)),
2303            ..Default::default()
2304        }
2305        .apply(&mut cfg);
2306        cfg.resolve_roles()
2307            .map_err(|e| format!("{n} implementers is not allowed here: {e:#}"))?;
2308    }
2309    Ok(n)
2310}
2311
2312/// Set how many implementers this chat files tasks with. Same shape as
2313/// [`switch_persona`]: `false` and no write when unchanged.
2314pub fn switch_implementers(talk: &mut Talk, store: &Talks, n: u8) -> Result<bool> {
2315    let _guard = store.guard()?;
2316    let mut fresh = store
2317        .get(&talk.id)
2318        .with_context(|| format!("talk {} was deleted", talk.short()))?;
2319    if fresh.implementers == n {
2320        *talk = fresh;
2321        return Ok(false);
2322    }
2323    let from = std::mem::replace(&mut fresh.implementers, n);
2324    fresh.implementers_dirty = true;
2325    fresh.turns.push(Turn {
2326        breaks: None,
2327        posted_by: None,
2328        who: Who::Agent,
2329        body: format!("{MAGI_NOTE}implementers changed from {from} to {n}"),
2330        at: Timestamp::now(),
2331        attachments: Vec::new(),
2332        usage: None,
2333    });
2334    store.put(&mut fresh)?;
2335    *talk = fresh;
2336    Ok(true)
2337}
2338
2339/// [`briefing_with`] for a chat that files tasks with `implementers`
2340/// implementers (1 is the unchanged `--solo` text).
2341pub fn briefing_for(
2342    repo: &Path,
2343    language: &str,
2344    allow_write: bool,
2345    persona: Option<&crate::persona::Persona>,
2346    operator_name: Option<&str>,
2347    implementers: u8,
2348) -> String {
2349    let flag = filing_flag(implementers);
2350    let shape = if implementers <= 1 {
2351        "Use --solo: it runs the task through one implementer \
2352         straight into review instead of the usual multi-agent competition, \
2353         which is the right shape for a change this conversation has already \
2354         settled, rather than one still worth several independent takes."
2355            .to_owned()
2356    } else {
2357        format!(
2358            "Use --implementers {implementers}: it has {implementers} \
2359             implementers work on the task independently and compete, which \
2360             is the right shape when several independent takes are worth \
2361             having. Never add --solo to it; the two do not go together."
2362        )
2363    };
2364    let write_policy = if allow_write {
2365        "Write access is enabled for this conversation (`allow_write = \
2366         true`), so you may write files - but only a small, \
2367         already-decided edit the operator names outright in this \
2368         conversation, not an implementation. This is a permission on the \
2369         conversation as a whole, not a property of whichever repository \
2370         it happened to start in: if the operator names a different \
2371         repository for that small edit, the policy allows it there too. \
2372         Your own tool may still confine writes to the repository this \
2373         conversation started in regardless - if a write elsewhere is \
2374         refused, say so plainly rather than working around it. Once you \
2375         have made an edit, say plainly what you edited. Anything bigger, \
2376         or anything still open-ended, still goes through the queue below \
2377         rather than being done here."
2378    } else {
2379        "Do not write files. Implementing a change is not this \
2380         conversation's job; a separate, blind competition of agents does \
2381         that, and a repository this conversation has already edited would \
2382         make their diffs unjudgeable."
2383    };
2384    let mut out = format!(
2385        "You are magi's standing conversation partner for its operator, who \
2386         usually has this open on a phone. Keep replies short: no preamble, \
2387         no restating what they just said.\n\n\
2388         # Repository\n\n{repo}\n\n\
2389         You may look around: read files, run shell commands, search history, \
2390         run tests - whatever answers the question. {write_policy}\n\n\
2391         A short, command-shaped message (\"list\", \"info <id>\", \"show \
2392         3cbf\") is almost always the operator asking you to look something \
2393         up, not an instruction to file - answer it yourself with `magi \
2394         list`, `magi show <id>`, `magi task list`, or the like, the same way \
2395         you would answer any other question in this conversation.\n\n\
2396         # When the operator wants something done\n\n\
2397         Run:\n\n\
2398         magi task add {flag} --repo {repo} <instruction>\n\n\
2399         and tell the operator the task id it prints, so they can follow it \
2400         from the Queue. If it refuses with a duplicate warning (the \
2401         instruction names a branch, commit or pull request that an \
2402         unfinished task, run or PR already owns), do not repeat it with \
2403         --force yourself: tell the operator what it matched and let them \
2404         decide. Write <instruction> so that an implementer who has \
2405         never seen this conversation can act on it alone - it is everything \
2406         they get. {shape}\n\n\
2407         If the operator asks for something in a different repository, \
2408         --repo does not have to be a full path: --repo owner/repo (or just \
2409         repo, when that is unambiguous) is resolved against local checkouts \
2410         the same way `magi repos` lists them. If the command fails because \
2411         nothing matches or more than one checkout shares that name, ask the \
2412         operator which repository they mean (or run `magi repos` yourself \
2413         to see the candidates) rather than guessing.\n\n\
2414         You cannot wait, and you cannot send the operator a message on your \
2415         own: you only speak when they write. A task you file reports back \
2416         into this conversation automatically when it finishes, is held or \
2417         fails, as a message headed \"{notice}\", so never promise to \"tell \
2418         them when it is done\" for anything else.\n\n\
2419         The current state of the code is whatever origin/main holds, not \
2420         whatever a working tree shows: a primary checkout often lags \
2421         upstream, sits on a detached HEAD and carries uncommitted changes. \
2422         Before answering about code, run `git fetch origin` in that \
2423         repository if it is cheap, then read through \
2424         `git show origin/main:<path>` or `git grep <pattern> origin/main`. \
2425         If the working tree differs, say so; if the fetch fails, say that \
2426         too, so the operator knows the answer may be stale.\n\n\
2427         If the operator attached an image (a screenshot, say) that the task \
2428         is about, pass it with `--attach <path>`, using the absolute path \
2429         the turn's attachment note gives; repeat the flag for several. \
2430         `magi task add {flag} --attach <path> <instruction>` copies the \
2431         file into the task, so the implementer receives it. Do not paste the \
2432         path into <instruction> instead: deleting this conversation deletes \
2433         its attachments, and then that path reaches no one.\n",
2434        repo = repo.display(),
2435        notice = crate::prompt::CHAT_TASK_NOTICE_HEADING,
2436    );
2437    out.push_str(&language_note(language));
2438    match (persona, operator_name) {
2439        (Some(p), n) => out.push_str(&crate::persona::section_for(p, n)),
2440        (None, Some(n)) => {
2441            out.push_str("\n# Addressing the operator\n");
2442            out.push_str(&crate::persona::addressing(n));
2443        }
2444        (None, None) => {}
2445    }
2446    out
2447}
2448
2449/// The operator is talking, so their language matters here more than in most
2450/// prompts magi sends.
2451fn language_note(language: &str) -> String {
2452    if language.trim().is_empty() || language.eq_ignore_ascii_case("en") {
2453        String::new()
2454    } else {
2455        format!("\nHold this conversation in {language}.\n")
2456    }
2457}
2458
2459/// Queue tasks this conversation has filed, oldest first.
2460///
2461/// A task is this conversation's when its [`Source::Agent`] names this
2462/// conversation's id as `run` - which is exactly what happens when
2463/// `magi task add` is run from inside a turn, because [`turn`] passes the
2464/// conversation's own id as [`Invocation::run`].
2465pub fn tasks_of(queue: &Queue, talk_id: &str) -> Vec<Task> {
2466    let mut tasks: Vec<Task> = queue
2467        .list()
2468        .into_iter()
2469        .filter(|t| matches!(&t.source, Source::Agent { run, .. } if run == talk_id))
2470        .collect();
2471    tasks.sort_unstable_by(|a, b| a.id.cmp(&b.id));
2472    tasks
2473}
2474
2475fn read_path(path: &Path) -> Result<Talk> {
2476    let body = std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;
2477    serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))
2478}
2479
2480/// How many times [`write_atomic`] retries a failed write-then-rename before
2481/// giving up.
2482const PUT_RETRIES: u32 = 5;
2483
2484/// Write `body` to `tmp` and rename it onto `path`, retrying the whole thing
2485/// a handful of times with a short sleep in between.
2486///
2487/// The only failure this is meant to absorb is a passing one - most
2488/// concretely, a reader elsewhere in this process (or another `magi`
2489/// process) with `path` briefly open for `read_to_string` at the exact
2490/// moment this call tries to rename over it. That clears in milliseconds
2491/// once the reader lets go; a caller still failing after several short
2492/// sleeps has something more durable wrong (a full disk, a permissions
2493/// change) that a longer sleep would not fix either, and is left to report
2494/// it.
2495fn write_atomic(tmp: &Path, path: &Path, body: &str) -> Result<()> {
2496    let mut last_err = None;
2497    for attempt in 0..PUT_RETRIES {
2498        if attempt > 0 {
2499            std::thread::sleep(Duration::from_millis(20 * u64::from(attempt)));
2500        }
2501        match try_write_atomic(tmp, path, body) {
2502            Ok(()) => return Ok(()),
2503            Err(e) => last_err = Some(e),
2504        }
2505    }
2506    Err(last_err.expect("the loop above always runs at least once"))
2507}
2508
2509fn try_write_atomic(tmp: &Path, path: &Path, body: &str) -> Result<()> {
2510    #[cfg(test)]
2511    if failpoint::take_forced_put_failure() {
2512        bail!("simulated write failure (test)");
2513    }
2514    std::fs::write(tmp, body).with_context(|| format!("write {}", tmp.display()))?;
2515    std::fs::rename(tmp, path).with_context(|| format!("replace {}", path.display()))?;
2516    Ok(())
2517}
2518
2519/// Last resort when `turn`'s own `store.put` fails even after
2520/// [`write_atomic`]'s retries: keep the generated text somewhere still
2521/// findable rather than let the whole of an agent's answer disappear along
2522/// with the write that was supposed to record it.
2523fn stash_lost_turn(store: &Talks, id: &str, stem: &str, reply: &Turn) -> Result<PathBuf> {
2524    let dir = store.artifacts_of(id);
2525    std::fs::create_dir_all(&dir).with_context(|| format!("create {}", dir.display()))?;
2526    let path = dir.join(format!("{stem}-lost.txt"));
2527    std::fs::write(&path, &reply.body).with_context(|| format!("write {}", path.display()))?;
2528    Ok(path)
2529}
2530
2531/// A test-only seam that lets [`try_write_atomic`] simulate the kind of
2532/// passing I/O race [`write_atomic`] is meant to retry through, without
2533/// depending on real OS-level file-locking behaviour, which differs across
2534/// the three platforms this crate ships on (and, on the one platform where a
2535/// reader really does block a rename, is awkward to trigger deterministically
2536/// in a unit test).
2537#[cfg(test)]
2538mod failpoint {
2539    use std::cell::Cell;
2540
2541    thread_local! {
2542        static FORCE_PUT_FAILURES: Cell<u32> = const { Cell::new(0) };
2543        static FORCE_NO_LINK: Cell<bool> = const { Cell::new(false) };
2544    }
2545
2546    /// While set, `hard_link` on this thread fails as unsupported, so the
2547    /// create-and-rename fallback runs.
2548    pub(super) fn force_no_link(on: bool) {
2549        FORCE_NO_LINK.with(|c| c.set(on));
2550    }
2551
2552    pub(super) fn no_link_forced() -> bool {
2553        FORCE_NO_LINK.with(Cell::get)
2554    }
2555
2556    /// Arrange for the next `count` calls into [`super::try_write_atomic`] to
2557    /// fail before touching the filesystem at all.
2558    pub(super) fn force_put_failures(count: u32) {
2559        FORCE_PUT_FAILURES.with(|c| c.set(count));
2560    }
2561
2562    /// Consumed once per attempt inside [`super::try_write_atomic`]; `true`
2563    /// means simulate this attempt failing.
2564    pub(super) fn take_forced_put_failure() -> bool {
2565        FORCE_PUT_FAILURES.with(|c| {
2566            let n = c.get();
2567            if n == 0 {
2568                false
2569            } else {
2570                c.set(n - 1);
2571                true
2572            }
2573        })
2574    }
2575}
2576
2577fn short(id: &str) -> &str {
2578    id.split('-').next_back().unwrap_or(id)
2579}
2580
2581fn new_id() -> String {
2582    let stamp = jiff::Zoned::now().strftime("%Y%m%d-%H%M%S");
2583    let seed = crate::rng::entropy();
2584    format!("{stamp}-{:04x}", (seed ^ (seed >> 32)) & 0xffff)
2585}
2586
2587/// Extension an attachment's bytes are stored under, from its (already
2588/// validated) mime. The one place this mapping exists on the write side;
2589/// `web`'s own whitelist is what actually decides which mimes are accepted
2590/// in the first place.
2591fn attachment_ext(mime: &str) -> Option<&'static str> {
2592    match mime {
2593        "image/png" => Some("png"),
2594        "image/jpeg" => Some("jpg"),
2595        "image/gif" => Some("gif"),
2596        "image/webp" => Some("webp"),
2597        _ => None,
2598    }
2599}
2600
2601/// Is `id` a shape [`put_attachment`](Talks::put_attachment) could have
2602/// produced? 32 lowercase hex digits and nothing else, checked before an id
2603/// that came from the client is ever allowed to build a path - so `..` and a
2604/// path separator are never even possible.
2605pub fn valid_attachment_id(id: &str) -> bool {
2606    id.len() == 32
2607        && id
2608            .bytes()
2609            .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
2610}
2611
2612/// A fresh attachment id: 128 bits of process entropy as lowercase hex - the
2613/// same "mint it, never take it from the client" rule [`new_id`] follows for
2614/// conversation ids.
2615fn new_attachment_id() -> String {
2616    let mut r = crate::rng::SplitMix64::new(crate::rng::entropy());
2617    format!("{:016x}{:016x}", r.next_u64(), r.next_u64())
2618}
2619
2620#[cfg(test)]
2621mod tests {
2622    #[test]
2623    fn turn_access_lifts_the_sandbox_only_for_the_talk_opt_in() {
2624        use super::turn_access;
2625        assert_eq!(turn_access(false, false), (false, false));
2626        assert_eq!(turn_access(true, false), (true, true));
2627        // A handed-over question opens the question store, never the sandbox.
2628        assert_eq!(turn_access(false, true), (true, false));
2629        assert_eq!(turn_access(true, true), (true, true));
2630    }
2631
2632    #[test]
2633    fn the_briefing_points_at_origin_main_not_the_working_tree() {
2634        let b = briefing(Path::new("/r"), "en", false);
2635        assert!(b.contains("origin/main"));
2636        assert!(b.contains("git show origin/main:"));
2637    }
2638    use std::collections::BTreeMap;
2639
2640    use crate::config::{AgentChoice, AgentKind, AgentSpec, Graph};
2641    use crate::queue::{Queue, Source, Task};
2642
2643    use super::*;
2644
2645    fn ctx_agent(id: &str, model: Option<&str>) -> AgentSpec {
2646        AgentSpec {
2647            id: id.to_owned(),
2648            kind: AgentKind::Command,
2649            model: model.map(str::to_owned),
2650            command: Vec::new(),
2651            extra_args: Vec::new(),
2652            env: BTreeMap::new(),
2653            prompt_delivery: None,
2654        }
2655    }
2656
2657    fn ctx_talk(agent: &str, turns: Vec<Turn>) -> Talk {
2658        Talk {
2659            pending_breaks: None,
2660            schema: SCHEMA,
2661            id: "20260904-014455-ab12".to_owned(),
2662            repo: PathBuf::from("."),
2663            agent: agent.to_owned(),
2664            status: TalkStatus::Open,
2665            turns,
2666            pending: String::new(),
2667            pending_attachments: Vec::new(),
2668            fallback: false,
2669            persona: String::new(),
2670            persona_dirty: false,
2671            implementers: 1,
2672            implementers_dirty: false,
2673            notified: Vec::new(),
2674            created_at: Timestamp::now(),
2675            updated_at: Timestamp::now(),
2676            seat: SeatState::new(SEAT, agent, 1),
2677        }
2678    }
2679
2680    fn reply(body: &str, usage: Option<(u64, &str, Option<&str>)>) -> Turn {
2681        Turn {
2682            breaks: None,
2683            posted_by: None,
2684            who: Who::Agent,
2685            body: body.to_owned(),
2686            at: Timestamp::now(),
2687            attachments: Vec::new(),
2688            usage: usage.map(|(t, a, m)| TurnUsage {
2689                context_tokens: t,
2690                agent: a.to_owned(),
2691                model: m.map(str::to_owned),
2692            }),
2693        }
2694    }
2695
2696    fn ctx_config(windows: &[(&str, u64)]) -> Config {
2697        Config {
2698            agents: vec![
2699                ctx_agent("small", Some("small-model")),
2700                ctx_agent("big", Some("big-model")),
2701                ctx_agent("plain", None),
2702            ],
2703            context_windows: windows.iter().map(|(k, v)| ((*k).to_owned(), *v)).collect(),
2704            ..Config::default()
2705        }
2706    }
2707
2708    #[test]
2709    fn context_usage_computes_percent_and_warns_at_eighty() {
2710        let cfg = ctx_config(&[("small-model", 1000)]);
2711        let at = |tokens| {
2712            let t = ctx_talk(
2713                "small",
2714                vec![reply("hi", Some((tokens, "small", Some("small-model"))))],
2715            );
2716            context_usage(&t, Some(&cfg))
2717        };
2718        let u = at(799);
2719        assert_eq!((u.percent, u.warn, u.window), (Some(79), false, Some(1000)));
2720        let u = at(800);
2721        assert_eq!((u.percent, u.warn), (Some(80), true));
2722        let u = at(1500);
2723        assert_eq!((u.percent, u.warn), (Some(150), true));
2724        assert!(!u.since_switch);
2725    }
2726
2727    #[test]
2728    fn context_usage_is_unknown_without_usage_and_never_looks_back() {
2729        let cfg = ctx_config(&[("small-model", 1000)]);
2730        let t = ctx_talk(
2731            "small",
2732            vec![
2733                reply("old", Some((900, "small", Some("small-model")))),
2734                reply("new", None),
2735            ],
2736        );
2737        let u = context_usage(&t, Some(&cfg));
2738        // No measurement in the latest reply: an estimate, never the stale 900.
2739        assert!(u.estimated);
2740        assert_ne!(u.tokens, Some(900));
2741        assert!(u.tokens.is_some());
2742        // A magi note after the reply neither hides nor replaces it.
2743        let t = ctx_talk(
2744            "small",
2745            vec![
2746                reply("old", Some((900, "small", Some("small-model")))),
2747                reply("magi: could not run agent", None),
2748            ],
2749        );
2750        assert_eq!(context_usage(&t, Some(&cfg)).tokens, Some(900));
2751        assert_eq!(
2752            context_usage(&ctx_talk("small", Vec::new()), Some(&cfg)).tokens,
2753            None
2754        );
2755    }
2756
2757    #[test]
2758    fn estimate_counts_chars_both_sides_and_standing_prompt() {
2759        let mut t = ctx_talk("small", vec![reply("abcdefg", None)]);
2760        assert_eq!(estimate_context_tokens(&t, 0), Some(2)); // 7 chars -> 2
2761        let op = Turn {
2762            who: Who::Operator,
2763            ..reply("abcdefg", None)
2764        };
2765        t.turns.push(op);
2766        assert_eq!(estimate_context_tokens(&t, 0), Some(4));
2767        assert!(
2768            estimate_context_tokens(&t, 700).unwrap() > estimate_context_tokens(&t, 0).unwrap()
2769        );
2770        // Characters, not bytes: 7 kanji are 7 chars.
2771        let ja = ctx_talk("small", vec![reply("日本語日本語日", None)]);
2772        assert_eq!(estimate_context_tokens(&ja, 0), Some(2));
2773        // magi notes are not sent to the agent; with nothing else, unknown.
2774        let note = ctx_talk("small", vec![reply("magi: could not run agent", None)]);
2775        assert_eq!(estimate_context_tokens(&note, 1000), None);
2776        assert_eq!(
2777            estimate_context_tokens(&ctx_talk("small", Vec::new()), 1000),
2778            None
2779        );
2780    }
2781
2782    #[test]
2783    fn context_usage_measured_wins_and_estimate_gets_percent_and_warn() {
2784        let cfg = ctx_config(&[("small-model", 1000)]);
2785        let t = ctx_talk(
2786            "small",
2787            vec![reply(
2788                &"x".repeat(5000),
2789                Some((10, "small", Some("small-model"))),
2790            )],
2791        );
2792        let u = context_usage(&t, Some(&cfg));
2793        assert_eq!((u.tokens, u.estimated), (Some(10), false));
2794        let t = ctx_talk("small", vec![reply(&"x".repeat(5000), None)]);
2795        let u = context_usage(&t, Some(&cfg));
2796        assert!(u.estimated && !u.since_switch);
2797        assert_eq!(u.window, Some(1000));
2798        assert!(u.warn && u.percent.unwrap() >= 80);
2799        let t = ctx_talk("small", vec![reply("hi", None)]);
2800        let u = context_usage(&t, Some(&cfg));
2801        assert!(u.estimated && u.percent.is_some());
2802    }
2803
2804    #[test]
2805    fn context_usage_without_a_window_shows_tokens_only() {
2806        let cfg = ctx_config(&[]);
2807        // No model at all, and a model nothing matches.
2808        let t = ctx_talk("plain", vec![reply("hi", Some((5000, "plain", None)))]);
2809        let u = context_usage(&t, Some(&cfg));
2810        assert_eq!(
2811            (u.tokens, u.window, u.percent, u.warn),
2812            (Some(5000), None, None, false)
2813        );
2814        let t = ctx_talk(
2815            "small",
2816            vec![reply("hi", Some((5000, "small", Some("small-model"))))],
2817        );
2818        assert_eq!(context_usage(&t, Some(&cfg)).percent, None);
2819        // No readable config: same, and no panic.
2820        assert_eq!(context_usage(&t, None).window, None);
2821    }
2822
2823    #[test]
2824    fn context_usage_switching_model_changes_the_denominator() {
2825        let cfg = ctx_config(&[("small-model", 1000), ("big-model", 10_000)]);
2826        let used = reply("hi", Some((900, "small", Some("small-model"))));
2827        let before = context_usage(&ctx_talk("small", vec![used.clone()]), Some(&cfg));
2828        assert_eq!(
2829            (before.percent, before.warn, before.since_switch),
2830            (Some(90), true, false)
2831        );
2832        // Same turns, conversation now on the big model: new denominator, and
2833        // the figure is flagged as describing the previous session.
2834        let after = context_usage(&ctx_talk("big", vec![used]), Some(&cfg));
2835        assert_eq!(after.window, Some(10_000));
2836        assert_eq!(
2837            (after.percent, after.warn, after.since_switch),
2838            (Some(9), false, true)
2839        );
2840        assert_eq!(after.model.as_deref(), Some("big-model"));
2841    }
2842
2843    #[test]
2844    fn a_turn_recorded_before_usage_existed_still_reads() {
2845        let old = r#"{"who":"agent","body":"hi","at":"2026-09-04T01:44:55Z"}"#;
2846        let turn: Turn = serde_json::from_str(old).expect("old turn reads");
2847        assert!(turn.usage.is_none());
2848        let json = serde_json::to_string(&turn).expect("serialize");
2849        assert!(
2850            !json.contains("usage"),
2851            "absent usage is not written: {json}"
2852        );
2853    }
2854
2855    /// A store of its own, with no process-global state.
2856    fn store() -> (tempfile::TempDir, Talks) {
2857        let tmp = tempfile::tempdir().expect("tempdir");
2858        let talks = Talks::at(tmp.path().join("talks"));
2859        (tmp, talks)
2860    }
2861
2862    /// A `kind = "command"` agent whose whole behaviour is a POSIX shell
2863    /// script - see `chat`'s tests for why no test here may spawn a real
2864    /// agent CLI.
2865    fn mock_agent(dir: &Path, script: &str, env: BTreeMap<String, String>) -> AgentSpec {
2866        let path = dir.join("mock-talk-agent.sh");
2867        std::fs::write(&path, script).expect("write mock");
2868        AgentSpec {
2869            id: "mock".to_owned(),
2870            kind: AgentKind::Command,
2871            model: None,
2872            command: vec!["sh".to_owned(), path.to_string_lossy().into_owned()],
2873            extra_args: Vec::new(),
2874            env,
2875            prompt_delivery: None,
2876        }
2877    }
2878
2879    fn config(spec: AgentSpec) -> Config {
2880        Config {
2881            agents: vec![spec],
2882            graph: Graph {
2883                language: "en".to_owned(),
2884                ..Graph::default()
2885            },
2886            ..Config::default()
2887        }
2888    }
2889
2890    /// Echo a canned reply, ignoring the prompt on stdin.
2891    const REPLY: &str = "#!/bin/sh\ncat >/dev/null\nprintf '%s\\n' \"$MOCK_REPLY\"\n";
2892
2893    /// Say nothing and fail, the way a CLI that cannot start does.
2894    const BROKEN: &str = "#!/bin/sh\ncat >/dev/null\nexit 3\n";
2895
2896    /// Reply with the prompt it was given, so a test can inspect exactly what
2897    /// the agent received on stdin.
2898    const ECHO: &str = "#!/bin/sh\ncat\n";
2899
2900    fn env(reply: &str) -> BTreeMap<String, String> {
2901        BTreeMap::from([("MOCK_REPLY".to_owned(), reply.to_owned())])
2902    }
2903
2904    #[test]
2905    fn the_frozen_json_field_names_round_trip_through_disk() {
2906        let (tmp, talks) = store();
2907        let mut talk = Talk {
2908            pending_breaks: None,
2909            schema: SCHEMA,
2910            id: "20260904-014455-ab12".to_owned(),
2911            repo: tmp.path().to_owned(),
2912            agent: "sonnet".to_owned(),
2913            status: TalkStatus::Open,
2914            turns: Vec::new(),
2915            pending: String::new(),
2916            pending_attachments: Vec::new(),
2917            fallback: false,
2918            persona: String::new(),
2919            persona_dirty: false,
2920            implementers: 1,
2921            implementers_dirty: false,
2922            notified: Vec::new(),
2923            created_at: Timestamp::now(),
2924            updated_at: Timestamp::now(),
2925            seat: SeatState::new(SEAT, "sonnet", 7),
2926        };
2927        talks.put(&mut talk).expect("put");
2928
2929        let raw = std::fs::read_to_string(talks.path_of(&talk.id)).expect("read back");
2930        let v: serde_json::Value = serde_json::from_str(&raw).expect("parse");
2931        for field in [
2932            "schema",
2933            "id",
2934            "repo",
2935            "agent",
2936            "status",
2937            "turns",
2938            "created_at",
2939            "updated_at",
2940        ] {
2941            assert!(v.get(field).is_some(), "missing field `{field}`");
2942        }
2943        assert_eq!(v["schema"], 1);
2944        assert_eq!(v["status"], "open");
2945
2946        let back = talks.get(&talk.id).expect("get");
2947        assert_eq!(back.id, talk.id);
2948        assert_eq!(back.status, TalkStatus::Open);
2949    }
2950
2951    #[test]
2952    fn opening_a_talk_takes_no_agent_turn() {
2953        let (tmp, talks) = store();
2954        // A script that would fail loudly if it were ever run: `begin` must
2955        // not invoke anything, since there is nothing yet for an agent to
2956        // answer.
2957        let spec = mock_agent(tmp.path(), BROKEN, BTreeMap::new());
2958        let cfg = config(spec);
2959
2960        let talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
2961        assert_eq!(talk.status, TalkStatus::Open);
2962        assert!(talk.turns.is_empty(), "nothing has been said yet");
2963
2964        let on_disk = talks.get(&talk.id).expect("get");
2965        assert_eq!(on_disk.turns.len(), 0);
2966    }
2967
2968    /// `[roles] chatter`, when set, decides who holds this conversation; unset,
2969    /// it falls back to [`agent::pick`]'s own default order (a claude seat,
2970    /// else the first runnable agent in roster order) rather than to any
2971    /// other role - see `[roles] chatter`'s own doc in [`crate::config`] for
2972    /// why a dedicated field exists at all: opening this against the same
2973    /// seat as a judge is what produced the `agent ... did not answer within
2974    /// 300s` timeout that led to it.
2975    #[test]
2976    fn chatter_wins_when_set_and_falls_back_to_pick_s_default_order_otherwise() {
2977        let (tmp, talks) = store();
2978        let first_spec = mock_agent(tmp.path(), BROKEN, BTreeMap::new());
2979        let mut chatter_spec = mock_agent(tmp.path(), BROKEN, BTreeMap::new());
2980        chatter_spec.id = "chatter-mock".to_owned();
2981
2982        let mut cfg = Config {
2983            agents: vec![first_spec.clone(), chatter_spec.clone()],
2984            graph: Graph {
2985                language: "en".to_owned(),
2986                ..Graph::default()
2987            },
2988            ..Config::default()
2989        };
2990        cfg.roles.chatter = Some(chatter_spec.id.as_str().into());
2991
2992        let talk =
2993            begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin with chatter set");
2994        assert_eq!(talk.agent, chatter_spec.id, "an explicit chatter must win");
2995
2996        cfg.roles.chatter = None;
2997        let fallback =
2998            begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin with chatter unset");
2999        assert_eq!(
3000            fallback.agent, first_spec.id,
3001            "unset chatter must fall back to agent::pick's own default order"
3002        );
3003    }
3004
3005    /// A conversation recorded before attachments existed - schema 1, no
3006    /// `attachments` key on any turn - must still read.
3007    #[test]
3008    fn a_talk_recorded_without_attachments_still_reads() {
3009        let (tmp, talks) = store();
3010        let path = talks.path_of("20260904-014455-ab12");
3011        std::fs::create_dir_all(talks.root()).expect("talks dir");
3012        std::fs::write(
3013            &path,
3014            serde_json::json!({
3015                "schema": 1,
3016                "id": "20260904-014455-ab12",
3017                "repo": tmp.path(),
3018                "agent": "sonnet",
3019                "status": "open",
3020                "turns": [
3021                    { "who": "operator", "body": "still there?",
3022                      "at": Timestamp::now().to_string() },
3023                ],
3024                "created_at": Timestamp::now().to_string(),
3025                "updated_at": Timestamp::now().to_string(),
3026                "seat": SeatState::new(SEAT, "sonnet", 7),
3027            })
3028            .to_string(),
3029        )
3030        .expect("write pre-attachments talk");
3031
3032        let talk = talks.get("20260904-014455-ab12").expect("must still read");
3033        assert!(talk.turns[0].attachments.is_empty());
3034    }
3035
3036    fn lease_store() -> (tempfile::TempDir, Talks, Talks) {
3037        let tmp = tempfile::TempDir::new().expect("tmp");
3038        let root = tmp.path().join("talks");
3039        (tmp, Talks::at(root.clone()), Talks::at(root))
3040    }
3041
3042    #[test]
3043    fn two_starters_on_one_talk_one_wins_and_the_other_is_refused() {
3044        let (_tmp, a, b) = lease_store();
3045        let won = a.claim_turn("t1").expect("claim").expect("first wins");
3046        assert!(
3047            b.claim_turn("t1").expect("claim").is_none(),
3048            "second is refused"
3049        );
3050        assert!(b.turn_held("t1"));
3051        assert!(
3052            b.claim_turn("t2").expect("claim").is_some(),
3053            "other talks are free"
3054        );
3055        drop(won);
3056    }
3057
3058    #[test]
3059    fn a_stale_lease_is_taken_over_and_the_old_guard_cannot_release_it() {
3060        let (_tmp, a, b) = lease_store();
3061        let old = a.claim_turn("t1").expect("claim").expect("held");
3062        let later = Timestamp::now()
3063            .checked_add(jiff::SignedDuration::from_secs(
3064                crate::ask::LEASE_TTL.as_secs() as i64 + 5,
3065            ))
3066            .expect("later");
3067        let new = b
3068            .claim_turn_at("t1", later)
3069            .expect("claim")
3070            .expect("a stale lease is taken over");
3071        drop(old);
3072        assert!(a.turn_held("t1"), "the old guard left the new lease alone");
3073        assert!(new.beat().expect("beat"), "the new owner still beats");
3074        drop(new);
3075        assert!(!a.turn_held("t1"));
3076    }
3077
3078    #[tokio::test]
3079    async fn a_turn_whose_lease_was_taken_over_is_stopped() {
3080        let (_tmp, a, b) = lease_store();
3081        let old = a.claim_turn("t1").expect("claim").expect("held");
3082        let later = Timestamp::now()
3083            .checked_add(jiff::SignedDuration::from_secs(
3084                crate::ask::LEASE_TTL.as_secs() as i64 + 5,
3085            ))
3086            .expect("later");
3087        let _new = b
3088            .claim_turn_at("t1", later)
3089            .expect("claim")
3090            .expect("taken over");
3091        let out = old
3092            .beating_every(Duration::from_millis(10), std::future::pending::<()>())
3093            .await;
3094        assert!(out.is_err(), "the displaced turn must stop, not run on");
3095    }
3096
3097    #[tokio::test]
3098    async fn a_turn_that_finishes_is_returned_and_keeps_its_lease_beating() {
3099        let (_tmp, a, _b) = lease_store();
3100        let lease = a.claim_turn("t1").expect("claim").expect("held");
3101        let out = lease
3102            .beating_every(Duration::from_millis(5), async {
3103                tokio::time::sleep(Duration::from_millis(40)).await;
3104                7
3105            })
3106            .await
3107            .expect("still ours");
3108        assert_eq!(out, 7);
3109        assert!(a.turn_held("t1"));
3110    }
3111
3112    #[test]
3113    fn an_unreadable_lease_counts_as_stale() {
3114        let (_tmp, a, b) = lease_store();
3115        std::fs::create_dir_all(a.root()).expect("dir");
3116        std::fs::write(a.turn_path("t1"), "not json").expect("write");
3117        assert!(!a.turn_held("t1"));
3118        assert!(b.claim_turn("t1").expect("claim").is_some());
3119    }
3120
3121    #[test]
3122    fn without_hard_links_a_claim_is_still_exclusive_and_a_young_placeholder_blocks() {
3123        let (_tmp, a, b) = lease_store();
3124        failpoint::force_no_link(true);
3125        let held = a.claim_turn("t1").expect("claim").expect("first wins");
3126        assert!(b.claim_turn("t1").expect("claim").is_none());
3127        assert!(a.turn_held("t1"));
3128        drop(held);
3129        assert!(!a.turn_held("t1"));
3130        // A writer between its exclusive create and its write: an empty file.
3131        let path = a.turn_path("t1");
3132        assert!(create_exclusive(&path, "").expect("placeholder"));
3133        assert!(b.claim_turn("t1").expect("claim").is_none(), "young: held");
3134        age_file(&path);
3135        assert!(b.claim_turn("t1").expect("claim").is_some(), "old: stale");
3136        // The lock publishes through the same path.
3137        let lease = a.turn_path("t2");
3138        let lock = TurnLock::take(&lease).expect("take").expect("lock");
3139        assert!(TurnLock::take(&lease).expect("take").is_none());
3140        drop(lock);
3141        assert!(TurnLock::take(&lease).expect("take").is_some());
3142        failpoint::force_no_link(false);
3143    }
3144
3145    #[test]
3146    fn remove_if_carries_removes_only_the_expected_content() {
3147        let (_tmp, a, _b) = lease_store();
3148        std::fs::create_dir_all(a.root()).expect("dir");
3149        let p = a.root().join("x.turn.lock");
3150        std::fs::write(&p, "mine").expect("write");
3151        assert!(!remove_if_carries(&p, "other"));
3152        assert_eq!(std::fs::read_to_string(&p).expect("kept"), "mine");
3153        assert!(remove_if_carries(&p, "mine"));
3154        assert!(!p.exists());
3155        assert!(!remove_if_carries(&p, "mine"), "absent is not a removal");
3156    }
3157
3158    #[test]
3159    fn a_dropped_lock_does_not_remove_a_lock_taken_over_since() {
3160        let (_tmp, a, _b) = lease_store();
3161        std::fs::create_dir_all(a.root()).expect("dir");
3162        let lease = a.turn_path("t1");
3163        let lock = TurnLock::take(&lease).expect("take").expect("lock");
3164        let path = lock.path.clone();
3165        std::fs::write(&path, "someone-else").expect("replace");
3166        drop(lock);
3167        assert_eq!(
3168            std::fs::read_to_string(&path).expect("kept"),
3169            "someone-else"
3170        );
3171    }
3172
3173    #[test]
3174    fn concurrent_takeovers_of_a_stale_lease_have_one_winner() {
3175        let (_tmp, a, _b) = lease_store();
3176        drop(a.claim_turn("t1").expect("claim").expect("held"));
3177        std::fs::write(
3178            a.turn_path("t1"),
3179            serde_json::to_string(&TurnRecord {
3180                token: "gone".into(),
3181                pid: 1,
3182                beat_at: Timestamp::from_second(1).expect("ts"),
3183            })
3184            .expect("json"),
3185        )
3186        .expect("write");
3187        let wins: Vec<_> = std::thread::scope(|sc| {
3188            let hs: Vec<_> = (0..8)
3189                .map(|_| {
3190                    let s = a.clone();
3191                    sc.spawn(move || s.claim_turn("t1").expect("claim"))
3192                })
3193                .collect();
3194            hs.into_iter().map(|h| h.join().expect("join")).collect()
3195        });
3196        assert_eq!(wins.iter().filter(|w| w.is_some()).count(), 1);
3197    }
3198
3199    fn age_file(path: &Path) {
3200        let f = std::fs::OpenOptions::new()
3201            .write(true)
3202            .open(path)
3203            .expect("open");
3204        f.set_modified(std::time::SystemTime::now() - std::time::Duration::from_secs(60))
3205            .expect("age");
3206    }
3207
3208    #[test]
3209    fn a_late_taker_of_a_broken_lock_cannot_disturb_its_replacement() {
3210        let (_tmp, a, _b) = lease_store();
3211        let lease = a.turn_path("t1");
3212        let lock = lease.with_extension("turn.lock");
3213        std::fs::create_dir_all(lock.parent().expect("dir")).expect("dir");
3214        std::fs::write(&lock, "t1-dead").expect("dead lock");
3215        age_file(&lock);
3216        // B breaks the dead lock and holds a fresh one.
3217        let b = TurnLock::take(&lease).expect("take").expect("b wins");
3218        let fresh = std::fs::read_to_string(&lock).expect("read");
3219        assert_eq!(fresh, b.token);
3220        // C read the same dead token earlier: its ticket is already spent, and
3221        // the fresh lock is never moved, so a newcomer cannot slip in.
3222        let ticket = std::fs::read_dir(lock.parent().expect("dir"))
3223            .expect("dir")
3224            .flatten()
3225            .map(|e| e.path())
3226            .find(|p| p.to_string_lossy().ends_with(".break.0"))
3227            .expect("ticket");
3228        assert!(!create_exclusive(&ticket, "").expect("ticket"));
3229        assert!(TurnLock::take(&lease).expect("take").is_none());
3230        assert_eq!(std::fs::read_to_string(&lock).expect("read"), fresh);
3231        // A later generation is breakable once the old ticket is stale too.
3232        age_file(&lock);
3233        age_file(&ticket);
3234        std::mem::forget(b);
3235        let c = TurnLock::take(&lease)
3236            .expect("take")
3237            .expect("next generation");
3238        assert_ne!(c.token, fresh);
3239    }
3240
3241    #[test]
3242    fn a_live_ticket_blocks_and_a_stale_one_hands_over_to_the_next_generation() {
3243        let (_tmp, a, _b) = lease_store();
3244        let lease = a.turn_path("t1");
3245        let lock = lease.with_extension("turn.lock");
3246        std::fs::create_dir_all(lock.parent().expect("dir")).expect("dir");
3247        std::fs::write(&lock, "t1-dead").expect("dead lock");
3248        age_file(&lock);
3249        let t0 = lock.with_extension("lock.t1-dead.break.0");
3250        assert!(create_exclusive(&t0, "").expect("ticket"));
3251        // A fresh ticket 0 blocks the same dead token, whatever the clock says.
3252        assert!(TurnLock::take(&lease).expect("take").is_none());
3253        assert_eq!(std::fs::read_to_string(&lock).expect("read"), "t1-dead");
3254        // Once ticket 0 is stale, exactly one taker gets through via ticket 1.
3255        age_file(&t0);
3256        let c = TurnLock::take(&lease).expect("take").expect("generation 1");
3257        assert_eq!(std::fs::read_to_string(&lock).expect("read"), c.token);
3258        assert!(lock.with_extension("lock.t1-dead.break.1").exists());
3259        assert!(TurnLock::take(&lease).expect("take").is_none());
3260    }
3261
3262    #[test]
3263    fn exhausted_ticket_generations_recover_once_the_sweep_ages_them_out() {
3264        let (_tmp, a, _b) = lease_store();
3265        let lease = a.turn_path("t1");
3266        let lock = lease.with_extension("turn.lock");
3267        std::fs::create_dir_all(lock.parent().expect("dir")).expect("dir");
3268        std::fs::write(&lock, "t1-dead").expect("dead lock");
3269        age_file(&lock);
3270        let tickets: Vec<_> = (0..TICKET_GENERATIONS)
3271            .map(|n| lock.with_extension(format!("lock.t1-dead.break.{n}")))
3272            .collect();
3273        for t in &tickets {
3274            assert!(create_exclusive(t, "").expect("ticket"));
3275            age_file(t);
3276        }
3277        // Stale but not yet swept: no recovery, and no ticket is unlinked.
3278        assert!(TurnLock::take(&lease).expect("take").is_none());
3279        assert!(tickets.iter().all(|t| t.exists()));
3280        // Past the sweep age they go, and the next attempt recovers.
3281        for t in &tickets {
3282            let f = std::fs::OpenOptions::new()
3283                .write(true)
3284                .open(t)
3285                .expect("open");
3286            f.set_modified(std::time::SystemTime::now() - TICKET_SWEEP_AGE * 2)
3287                .expect("age");
3288        }
3289        assert!(TurnLock::take(&lease).expect("take").is_none());
3290        assert!(TurnLock::take(&lease).expect("take").is_some());
3291    }
3292
3293    #[test]
3294    fn an_aged_empty_lock_is_broken() {
3295        let (_tmp, a, _b) = lease_store();
3296        let lease = a.turn_path("t1");
3297        let lock = lease.with_extension("turn.lock");
3298        std::fs::create_dir_all(lock.parent().expect("dir")).expect("dir");
3299        std::fs::write(&lock, "").expect("empty lock");
3300        age_file(&lock);
3301        assert!(TurnLock::take(&lease).expect("take").is_some());
3302    }
3303
3304    #[test]
3305    fn queued_text_is_durable_combined_and_drained_as_one_operator_turn() {
3306        let (tmp, talks) = store();
3307        let cfg = config(mock_agent(tmp.path(), REPLY, env("reply")));
3308        let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
3309
3310        queue(&mut talk, &talks, "first", Vec::new()).expect("queue first");
3311        queue(&mut talk, &talks, "second", Vec::new()).expect("queue second");
3312        let saved = talks.get(&talk.id).expect("reload queued talk");
3313        assert_eq!(saved.pending, "first\n\nsecond");
3314        assert_eq!(saved.pending_breaks, Some(vec!["first\n\n".len()]));
3315        assert!(saved.turns.is_empty(), "a draft is not a transcript turn");
3316
3317        let drained = drain(&mut talk, &talks).expect("drain");
3318        assert_eq!(drained.as_deref(), Some("first\n\nsecond"));
3319        let saved = talks.get(&talk.id).expect("reload drained talk");
3320        assert!(saved.pending.is_empty());
3321        assert_eq!(saved.turns.len(), 1);
3322        assert_eq!(saved.turns[0].body, "first\n\nsecond");
3323        assert_eq!(saved.turns[0].breaks, Some(vec!["first\n\n".len()]));
3324        assert_eq!(saved.pending_breaks, None);
3325    }
3326
3327    #[test]
3328    fn editing_a_queued_draft_preserves_its_attachments_and_rejects_a_stale_snapshot() {
3329        let (tmp, talks) = store();
3330        let cfg = config(mock_agent(tmp.path(), REPLY, env("reply")));
3331        let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
3332        let attachment = Attachment {
3333            id: "a".repeat(32),
3334            name: "shot.png".to_owned(),
3335            mime: "image/png".to_owned(),
3336            bytes: 3,
3337        };
3338
3339        queue(&mut talk, &talks, "first", vec![attachment.clone()]).expect("queue");
3340        assert!(
3341            edit_pending_text(
3342                &mut talk,
3343                &talks,
3344                "corrected",
3345                "first",
3346                std::slice::from_ref(&attachment.id),
3347            )
3348            .expect("edit")
3349        );
3350        let saved = talks.get(&talk.id).expect("reload edited draft");
3351        assert_eq!(saved.pending, "corrected");
3352        assert_eq!(saved.pending_attachments, vec![attachment]);
3353
3354        queue(&mut talk, &talks, "later", Vec::new()).expect("queue concurrent draft");
3355        assert!(
3356            !edit_pending_text(
3357                &mut talk,
3358                &talks,
3359                "stale edit",
3360                "corrected",
3361                &["a".repeat(32)],
3362            )
3363            .expect("stale edit is a conflict")
3364        );
3365        assert_eq!(
3366            talks.get(&talk.id).expect("reload after conflict").pending,
3367            "corrected\n\nlater"
3368        );
3369        assert!(
3370            !clear_pending_if_matches(&mut talk, &talks, "corrected", &["a".repeat(32)])
3371                .expect("stale clear is a conflict")
3372        );
3373        assert_eq!(
3374            talks
3375                .get(&talk.id)
3376                .expect("reload after stale clear")
3377                .pending,
3378            "corrected\n\nlater"
3379        );
3380    }
3381
3382    #[tokio::test]
3383    async fn a_reply_save_preserves_pending_accepted_while_the_cli_runs() {
3384        let (tmp, talks) = store();
3385        let slow = "#!/bin/sh\ncat >/dev/null\nsleep 0.1\nprintf reply\n";
3386        let cfg = config(mock_agent(tmp.path(), slow, BTreeMap::new()));
3387        let mut running = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
3388        let id = running.id.clone();
3389        let first = record(&mut running, &talks, "first", Vec::new()).expect("record");
3390
3391        let response_talks = talks.clone();
3392        let response_cfg = cfg.clone();
3393        let reply = tokio::spawn(async move {
3394            respond(
3395                &response_talks.claim_turn(&running.id).unwrap().unwrap(),
3396                &mut running,
3397                &response_talks,
3398                &response_cfg,
3399                &first,
3400            )
3401            .await
3402        });
3403        tokio::time::sleep(std::time::Duration::from_millis(20)).await;
3404
3405        let mut queued = talks.get(&id).expect("queued handle");
3406        queue(&mut queued, &talks, "next", Vec::new()).expect("queue");
3407        reply.await.expect("join").expect("reply");
3408
3409        let saved = talks.get(&id).expect("reload");
3410        assert_eq!(saved.pending, "next");
3411        assert_eq!(saved.pending_breaks, Some(Vec::new()));
3412        assert_eq!(saved.turns.len(), 2, "operator message and reply remain");
3413    }
3414
3415    /// A mock whose script counts its own calls in `<dir>/<id>.calls` before
3416    /// running `body`.
3417    fn counting_agent(dir: &Path, id: &str, body: &str) -> AgentSpec {
3418        let calls = dir.join(format!("{id}.calls"));
3419        let script = format!(
3420            "#!/bin/sh\necho x >> '{}'\n{body}\n",
3421            calls.to_string_lossy()
3422        );
3423        let path = dir.join(format!("mock-{id}.sh"));
3424        std::fs::write(&path, script).expect("write mock");
3425        AgentSpec {
3426            id: id.to_owned(),
3427            kind: AgentKind::Command,
3428            model: None,
3429            command: vec!["sh".to_owned(), path.to_string_lossy().into_owned()],
3430            extra_args: Vec::new(),
3431            env: BTreeMap::new(),
3432            prompt_delivery: None,
3433        }
3434    }
3435
3436    fn calls(dir: &Path, id: &str) -> usize {
3437        std::fs::read_to_string(dir.join(format!("{id}.calls"))).map_or(0, |s| s.lines().count())
3438    }
3439
3440    fn chain_config(specs: Vec<AgentSpec>, ids: &[&str]) -> Config {
3441        let mut cfg = config(specs[0].clone());
3442        cfg.agents = specs;
3443        cfg.roles.chatter = Some(AgentChoice::Chain(
3444            ids.iter().map(|s| (*s).to_owned()).collect(),
3445        ));
3446        cfg
3447    }
3448
3449    #[tokio::test]
3450    async fn a_chatter_chain_falls_back_resends_the_transcript_and_sticks() {
3451        let (tmp, talks) = store();
3452        let a = counting_agent(tmp.path(), "a", "cat >/dev/null\nexit 3");
3453        let b = counting_agent(tmp.path(), "b", "cat");
3454        let cfg = chain_config(vec![a, b], &["a", "b"]);
3455        let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
3456        assert_eq!(talk.agent, "a");
3457
3458        say(
3459            &talks.claim_turn(&talk.id).unwrap().unwrap(),
3460            &mut talk,
3461            &talks,
3462            &cfg,
3463            "hello there",
3464            Vec::new(),
3465        )
3466        .await
3467        .expect("turn");
3468        assert_eq!(calls(tmp.path(), "a"), 1, "each id is tried once");
3469        assert_eq!(calls(tmp.path(), "b"), 1);
3470        assert_eq!(talk.agent, "b", "the switch persists");
3471        assert!(talks.get(&talk.id).unwrap().agent == "b");
3472        let reply = talk.turns.last().unwrap();
3473        assert!(reply.body.contains("hello there"));
3474        assert!(
3475            reply.body.contains("magi task add --solo"),
3476            "a fresh seat gets the full briefing"
3477        );
3478        assert!(
3479            talk.turns
3480                .iter()
3481                .any(|t| t.body.contains("agent changed from a to b")),
3482            "the switch is noted"
3483        );
3484    }
3485
3486    #[tokio::test]
3487    async fn an_exhausted_chatter_chain_fails_like_a_single_seat_and_stays_put() {
3488        let (tmp, talks) = store();
3489        let a = counting_agent(tmp.path(), "a", "cat >/dev/null\nexit 3");
3490        let b = counting_agent(tmp.path(), "b", "cat >/dev/null\nexit 4");
3491        let cfg = chain_config(vec![a, b], &["a", "b", "a"]);
3492        let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
3493
3494        let err = say(
3495            &talks.claim_turn(&talk.id).unwrap().unwrap(),
3496            &mut talk,
3497            &talks,
3498            &cfg,
3499            "hi",
3500            Vec::new(),
3501        )
3502        .await
3503        .expect_err("every agent failed");
3504        assert!(err.to_string().contains("`a`"), "{err:#}");
3505        assert_eq!(calls(tmp.path(), "a"), 1);
3506        assert_eq!(calls(tmp.path(), "b"), 1);
3507        assert_eq!(talk.agent, "a", "an exhausted chain leaves the agent alone");
3508    }
3509
3510    #[test]
3511    fn a_chatter_chain_skips_an_unknown_id_at_begin() {
3512        let (tmp, talks) = store();
3513        let b = counting_agent(tmp.path(), "b", "cat");
3514        let cfg = chain_config(vec![b], &["ghost", "b"]);
3515        let talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
3516        assert_eq!(talk.agent, "b");
3517    }
3518
3519    #[tokio::test]
3520    async fn an_explicit_agent_inside_the_chatter_chain_stays_pinned() {
3521        let (tmp, talks) = store();
3522        let a = counting_agent(tmp.path(), "a", "cat >/dev/null\nexit 3");
3523        let b = counting_agent(tmp.path(), "b", "cat");
3524        let cfg = chain_config(vec![a, b], &["a", "b"]);
3525        let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), Some("a")).expect("begin");
3526        say(
3527            &talks.claim_turn(&talk.id).unwrap().unwrap(),
3528            &mut talk,
3529            &talks,
3530            &cfg,
3531            "hi",
3532            Vec::new(),
3533        )
3534        .await
3535        .expect_err("a alone, and it fails");
3536        assert_eq!(calls(tmp.path(), "b"), 0);
3537        assert_eq!(talk.agent, "a");
3538    }
3539
3540    #[tokio::test]
3541    async fn an_explicit_agent_does_not_borrow_the_chatter_chain() {
3542        let (tmp, talks) = store();
3543        let a = counting_agent(tmp.path(), "a", "cat >/dev/null\nexit 3");
3544        let b = counting_agent(tmp.path(), "b", "cat");
3545        let c = counting_agent(tmp.path(), "c", "cat >/dev/null\nexit 3");
3546        let cfg = chain_config(vec![a, b, c], &["a", "b"]);
3547        let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), Some("c")).expect("begin");
3548        say(
3549            &talks.claim_turn(&talk.id).unwrap().unwrap(),
3550            &mut talk,
3551            &talks,
3552            &cfg,
3553            "hi",
3554            Vec::new(),
3555        )
3556        .await
3557        .expect_err("c alone, and it fails");
3558        assert_eq!(calls(tmp.path(), "b"), 0);
3559    }
3560
3561    #[test]
3562    fn briefing_names_the_operator_with_or_without_a_persona() {
3563        let plain = briefing(Path::new("/repo"), "en", false);
3564        let named = briefing_with(Path::new("/repo"), "en", false, None, Some("Commander"));
3565        assert!(named.starts_with(&plain));
3566        assert!(named.contains("# Addressing the operator"));
3567        assert!(named.contains("\"Commander\""));
3568        let rei = crate::persona::builtin_catalog()
3569            .into_iter()
3570            .find(|p| p.id == "rei")
3571            .expect("rei");
3572        let with = briefing_with(
3573            Path::new("/repo"),
3574            "en",
3575            false,
3576            Some(&rei),
3577            Some("Commander"),
3578        );
3579        assert!(with.contains("\"Commander\""));
3580        assert!(!with.contains("# Addressing the operator"));
3581    }
3582
3583    #[test]
3584    fn briefing_carries_a_persona_section_only_when_one_is_chosen() {
3585        let plain = briefing(Path::new("/repo"), "en", false);
3586        assert_eq!(
3587            plain,
3588            briefing_with(Path::new("/repo"), "en", false, None, None)
3589        );
3590        assert!(!plain.contains("Persona"));
3591        let rei = crate::persona::builtin_catalog()
3592            .into_iter()
3593            .find(|p| p.id == "rei")
3594            .expect("rei");
3595        let with = briefing_with(Path::new("/repo"), "en", false, Some(&rei), None);
3596        assert!(with.starts_with(&plain), "the plain briefing is untouched");
3597        assert!(with.contains("# Persona (tone only)"));
3598        assert!(with.contains("TONE ONLY"));
3599        assert!(with.contains("task ids"));
3600        assert!(with.contains("write policy"));
3601        assert!(with.contains("`magi task add`"));
3602        assert!(with.contains("Rei Ayanami"));
3603    }
3604
3605    #[test]
3606    fn a_talk_written_before_personas_still_loads() {
3607        let (tmp, talks) = store();
3608        let spec = mock_agent(tmp.path(), ECHO, BTreeMap::new());
3609        let cfg = config(spec);
3610        let talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
3611        let path = talks.root.join(format!("{}.json", talk.id));
3612        let mut v: serde_json::Value =
3613            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
3614        v.as_object_mut().unwrap().remove("persona");
3615        v.as_object_mut().unwrap().remove("persona_dirty");
3616        std::fs::write(&path, v.to_string()).unwrap();
3617        let loaded = talks.get(&talk.id).expect("old record loads");
3618        assert_eq!(loaded.persona, "");
3619        assert!(!loaded.persona_dirty);
3620    }
3621
3622    #[test]
3623    fn the_briefing_files_with_solo_or_the_chosen_implementer_count() {
3624        let repo = Path::new("/repo");
3625        let solo = briefing_for(repo, "", false, None, None, 1);
3626        assert_eq!(solo, briefing(repo, "", false));
3627        assert!(solo.contains("magi task add --solo --repo"));
3628        assert!(solo.contains("magi task add --solo --attach"));
3629        for n in [2u8, 3] {
3630            let b = briefing_for(repo, "", false, None, None, n);
3631            assert!(
3632                b.contains(&format!("magi task add --implementers {n} --repo")),
3633                "{b}"
3634            );
3635            assert!(b.contains(&format!("magi task add --implementers {n} --attach")));
3636            assert!(!b.contains("task add --solo"), "{b}");
3637            assert!(!b.contains("Use --solo"), "{b}");
3638        }
3639    }
3640
3641    #[test]
3642    fn begin_with_applies_remembered_choices_and_drops_unfit_ones_alone() {
3643        let (tmp, talks) = store();
3644        let first = mock_agent(tmp.path(), ECHO, BTreeMap::new());
3645        let mut second = first.clone();
3646        second.id = "second".to_owned();
3647        let mut cfg = config(first.clone());
3648        cfg.agents.push(second.clone());
3649        let open = |p: &Preferred| {
3650            begin_with(&talks, &cfg, tmp.path().to_owned(), None, p).expect("begin")
3651        };
3652
3653        let talk = open(&Preferred {
3654            agent: Some("second".into()),
3655            persona: Some("rei".into()),
3656            implementers: Some(i64::from(check_implementers(3, &cfg).unwrap_or(1))),
3657        });
3658        assert_eq!(talk.agent, "second");
3659        assert!(
3660            !talk.fallback,
3661            "a remembered non-head agent is an explicit choice"
3662        );
3663        assert_eq!(talk.persona, "rei");
3664        assert_eq!(talk.implementers, check_implementers(3, &cfg).unwrap_or(1));
3665        assert!(!talk.persona_dirty && !talk.implementers_dirty);
3666
3667        // The chain head chosen again stays a fallback-capable talk.
3668        let head = open(&Preferred {
3669            agent: Some(first.id.clone()),
3670            ..Preferred::default()
3671        });
3672        assert!(head.fallback);
3673
3674        // Each unfit field falls back by itself.
3675        for implementers in [0, 4, -1, 1000] {
3676            let t = open(&Preferred {
3677                agent: Some("gone".into()),
3678                persona: Some("no-such-persona".into()),
3679                implementers: Some(implementers),
3680            });
3681            assert_eq!(t.agent, first.id);
3682            assert!(t.fallback);
3683            assert_eq!(t.persona, "");
3684            assert_eq!(t.implementers, 1);
3685        }
3686
3687        // `default` stays the empty string; a good field survives a bad one.
3688        let t = open(&Preferred {
3689            agent: Some("second".into()),
3690            persona: Some("default".into()),
3691            implementers: Some(9),
3692        });
3693        assert_eq!(
3694            (t.agent.as_str(), t.persona.as_str(), t.implementers),
3695            ("second", "", 1)
3696        );
3697
3698        // An explicit agent still wins and keeps its strict error.
3699        let strict = begin_with(
3700            &talks,
3701            &cfg,
3702            tmp.path().to_owned(),
3703            Some("first-unknown"),
3704            &Preferred {
3705                agent: Some("second".into()),
3706                ..Preferred::default()
3707            },
3708        );
3709        assert!(strict.is_err());
3710    }
3711
3712    #[test]
3713    fn remembered_agent_can_open_when_the_chatter_chain_cannot_resolve() {
3714        let (tmp, talks) = store();
3715        let spec = mock_agent(tmp.path(), ECHO, BTreeMap::new());
3716        // A missing chain member makes head resolution fail independently of
3717        // which subscription CLIs happen to be installed on this machine.
3718        let cfg = chain_config(vec![spec.clone()], &["missing-chatter"]);
3719        assert!(begin(&talks, &cfg, tmp.path().to_owned(), None).is_err());
3720        let talk = begin_with(
3721            &talks,
3722            &cfg,
3723            tmp.path().to_owned(),
3724            None,
3725            &Preferred {
3726                agent: Some(spec.id.clone()),
3727                ..Preferred::default()
3728            },
3729        )
3730        .expect("a valid remembered agent does not require a default chain");
3731        assert_eq!(talk.agent, spec.id);
3732        assert!(!talk.fallback);
3733        assert_eq!(talks.get(&talk.id).unwrap().agent, spec.id);
3734        assert!(
3735            begin_with(
3736                &talks,
3737                &cfg,
3738                tmp.path().to_owned(),
3739                None,
3740                &Preferred {
3741                    agent: Some("missing-preference".into()),
3742                    ..Preferred::default()
3743                },
3744            )
3745            .is_err()
3746        );
3747    }
3748
3749    #[test]
3750    fn implementers_are_validated_and_old_records_load_as_solo() {
3751        let (tmp, talks) = store();
3752        let cfg = config(mock_agent(tmp.path(), ECHO, BTreeMap::new()));
3753        assert_eq!(check_implementers(1, &cfg), Ok(1));
3754        assert_eq!(check_implementers(3, &cfg), Ok(3));
3755        assert!(check_implementers(0, &cfg).is_err());
3756        assert!(check_implementers(4, &cfg).is_err());
3757        let mut empty = cfg.clone();
3758        empty.agents.clear();
3759        assert!(check_implementers(2, &empty).is_err());
3760
3761        let talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
3762        let path = talks.path_of(&talk.id);
3763        let mut v: serde_json::Value =
3764            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
3765        v.as_object_mut().unwrap().remove("implementers");
3766        v.as_object_mut().unwrap().remove("implementers_dirty");
3767        std::fs::write(&path, v.to_string()).unwrap();
3768        let loaded = talks.get(&talk.id).expect("load");
3769        assert_eq!(loaded.implementers, 1);
3770        assert!(!loaded.implementers_dirty);
3771    }
3772
3773    #[tokio::test]
3774    async fn an_implementers_switch_is_noted_once_and_kept_across_a_failed_turn() {
3775        let (tmp, talks) = store();
3776        let spec = mock_agent(tmp.path(), ECHO, BTreeMap::new());
3777        let cfg = config(spec);
3778        let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
3779        let lease = talks.claim_turn(&talk.id).unwrap().unwrap();
3780        say(&lease, &mut talk, &talks, &cfg, "hello", Vec::new())
3781            .await
3782            .expect("first turn");
3783
3784        assert!(switch_implementers(&mut talk, &talks, 2).expect("switch"));
3785        assert!(!switch_implementers(&mut talk, &talks, 2).expect("same"));
3786        assert!(talk.implementers_dirty);
3787        say(&lease, &mut talk, &talks, &cfg, "next", Vec::new())
3788            .await
3789            .expect("turn");
3790        let prompt = &talk.turns.last().unwrap().body;
3791        assert!(prompt.contains("# Task filing update"), "{prompt}");
3792        assert!(prompt.contains("--implementers 2"));
3793        assert!(!talk.implementers_dirty, "cleared after a successful turn");
3794
3795        say(&lease, &mut talk, &talks, &cfg, "again", Vec::new())
3796            .await
3797            .expect("turn");
3798        assert!(
3799            !talk
3800                .turns
3801                .last()
3802                .unwrap()
3803                .body
3804                .contains("# Task filing update")
3805        );
3806
3807        // Without a resumable session the current policy rides on every turn.
3808        let mut no_sessions = cfg.clone();
3809        no_sessions.graph.sessions = false;
3810        say(&lease, &mut talk, &talks, &no_sessions, "one", Vec::new())
3811            .await
3812            .expect("turn");
3813        say(&lease, &mut talk, &talks, &no_sessions, "two", Vec::new())
3814            .await
3815            .expect("turn");
3816        assert!(talk.turns.last().unwrap().body.contains("--implementers 2"));
3817    }
3818
3819    #[tokio::test]
3820    async fn a_persona_switch_notes_marks_dirty_and_updates_the_next_turn_once() {
3821        let (tmp, talks) = store();
3822        let spec = mock_agent(tmp.path(), ECHO, BTreeMap::new());
3823        let cfg = config(spec);
3824        let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
3825        let lease = talks.claim_turn(&talk.id).unwrap().unwrap();
3826        say(&lease, &mut talk, &talks, &cfg, "hello", Vec::new())
3827            .await
3828            .expect("first turn");
3829        assert!(!talk.turns[1].body.contains("Persona"));
3830
3831        assert!(switch_persona(&mut talk, &talks, "misato").expect("switch"));
3832        assert!(!switch_persona(&mut talk, &talks, "misato").expect("same"));
3833        assert!(talk.persona_dirty);
3834        assert!(talk.turns.last().unwrap().body.contains("persona changed"));
3835
3836        say(&lease, &mut talk, &talks, &cfg, "next", Vec::new())
3837            .await
3838            .expect("turn");
3839        let prompt = &talk.turns.last().unwrap().body;
3840        assert!(prompt.contains("# Persona update"), "{prompt}");
3841        assert!(prompt.contains("Misato Katsuragi"));
3842        assert!(!talk.persona_dirty, "cleared after a successful turn");
3843
3844        say(&lease, &mut talk, &talks, &cfg, "again", Vec::new())
3845            .await
3846            .expect("turn");
3847        assert!(!talk.turns.last().unwrap().body.contains("# Persona update"));
3848
3849        assert!(switch_persona(&mut talk, &talks, "default").expect("back"));
3850        assert_eq!(talk.persona, "");
3851        say(&lease, &mut talk, &talks, &cfg, "plain", Vec::new())
3852            .await
3853            .expect("turn");
3854        assert!(
3855            talk.turns
3856                .last()
3857                .unwrap()
3858                .body
3859                .contains("turned the persona off")
3860        );
3861
3862        // Without a resumable session every turn re-sends the persona.
3863        assert!(switch_persona(&mut talk, &talks, "rei").expect("rei"));
3864        let mut no_sessions = cfg.clone();
3865        no_sessions.graph.sessions = false;
3866        say(&lease, &mut talk, &talks, &no_sessions, "one", Vec::new())
3867            .await
3868            .expect("turn");
3869        say(&lease, &mut talk, &talks, &no_sessions, "two", Vec::new())
3870            .await
3871            .expect("turn");
3872        let last = &talk.turns.last().unwrap().body;
3873        assert!(!talk.persona_dirty);
3874        assert!(last.contains("# Persona (tone only)"), "{last}");
3875        assert!(last.contains("Rei Ayanami"));
3876    }
3877
3878    #[tokio::test]
3879    async fn the_first_turn_carries_the_briefing_and_later_turns_do_not() {
3880        let (tmp, talks) = store();
3881        let spec = mock_agent(tmp.path(), ECHO, BTreeMap::new());
3882        let cfg = config(spec);
3883        let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
3884
3885        say(
3886            &talks.claim_turn(&talk.id).unwrap().unwrap(),
3887            &mut talk,
3888            &talks,
3889            &cfg,
3890            "what does the queue module do?",
3891            Vec::new(),
3892        )
3893        .await
3894        .expect("first turn");
3895        let first_prompt = &talk.turns[1].body;
3896        assert!(first_prompt.contains("magi task add --solo"));
3897        assert!(first_prompt.contains("what does the queue module do?"));
3898
3899        say(
3900            &talks.claim_turn(&talk.id).unwrap().unwrap(),
3901            &mut talk,
3902            &talks,
3903            &cfg,
3904            "and how is it locked?",
3905            Vec::new(),
3906        )
3907        .await
3908        .expect("second turn");
3909        let second_prompt = &talk.turns[3].body;
3910        assert!(
3911            !second_prompt.contains("magi task add --solo"),
3912            "the briefing is sent once, not on every turn: {second_prompt}"
3913        );
3914        assert!(second_prompt.contains("and how is it locked?"));
3915    }
3916
3917    #[tokio::test]
3918    async fn switching_agent_resets_the_seat_notes_it_and_resends_the_transcript() {
3919        let (tmp, talks) = store();
3920        let a = mock_agent(tmp.path(), ECHO, BTreeMap::new());
3921        let mut b = a.clone();
3922        b.id = "other".to_owned();
3923        let mut cfg = config(a.clone());
3924        cfg.agents.push(b.clone());
3925        let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), Some(&a.id)).expect("begin");
3926        say(
3927            &talks.claim_turn(&talk.id).unwrap().unwrap(),
3928            &mut talk,
3929            &talks,
3930            &cfg,
3931            "remember the walrus",
3932            Vec::new(),
3933        )
3934        .await
3935        .expect("first turn");
3936        let old_session = talk.seat.claude_session.clone();
3937        assert_eq!(talk.seat.turns, 1);
3938
3939        assert!(switch_agent(&mut talk, &talks, &b).expect("switch"));
3940        assert_eq!(talk.agent, "other");
3941        assert_eq!(talk.seat.turns, 0);
3942        assert_eq!(talk.seat.agent, "other");
3943        assert_ne!(talk.seat.claude_session, old_session);
3944        let note = talk.turns.last().expect("note");
3945        assert_eq!(note.who, Who::Agent);
3946        assert!(note.body.starts_with(MAGI_NOTE), "{}", note.body);
3947        assert!(note.body.contains("changed from"), "{}", note.body);
3948        assert_eq!(talks.get(&talk.id).expect("reload").agent, "other");
3949
3950        let before = talk.turns.len();
3951        assert!(!switch_agent(&mut talk, &talks, &b).expect("same agent"));
3952        assert_eq!(talk.turns.len(), before, "a no-op writes no note");
3953
3954        say(
3955            &talks.claim_turn(&talk.id).unwrap().unwrap(),
3956            &mut talk,
3957            &talks,
3958            &cfg,
3959            "what did I say?",
3960            Vec::new(),
3961        )
3962        .await
3963        .expect("turn after switch");
3964        let prompt = &talk.turns.last().expect("reply").body;
3965        assert!(prompt.contains("remember the walrus"), "{prompt}");
3966        assert!(prompt.contains("## magi"), "{prompt}");
3967        assert!(prompt.contains("what did I say?"), "{prompt}");
3968    }
3969
3970    #[tokio::test]
3971    async fn say_appends_the_operator_turn_then_the_agent_turn() {
3972        let (tmp, talks) = store();
3973        let spec = mock_agent(tmp.path(), REPLY, env("go ahead"));
3974        let cfg = config(spec);
3975        let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
3976
3977        say(
3978            &talks.claim_turn(&talk.id).unwrap().unwrap(),
3979            &mut talk,
3980            &talks,
3981            &cfg,
3982            "can I rename this function?",
3983            Vec::new(),
3984        )
3985        .await
3986        .expect("say");
3987
3988        assert_eq!(talk.turns.len(), 2);
3989        assert_eq!(talk.turns[0].who, Who::Operator);
3990        assert_eq!(talk.turns[0].body, "can I rename this function?");
3991        assert_eq!(talk.turns[1].who, Who::Agent);
3992        assert_eq!(talk.turns[1].body, "go ahead");
3993        assert_eq!(talks.get(&talk.id).expect("get").turns, talk.turns);
3994    }
3995
3996    #[tokio::test]
3997    async fn a_failed_turn_keeps_the_operator_message_and_says_what_happened() {
3998        let (tmp, talks) = store();
3999        let spec = mock_agent(tmp.path(), BROKEN, BTreeMap::new());
4000        let cfg = config(spec);
4001        let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4002
4003        let err = say(
4004            &talks.claim_turn(&talk.id).unwrap().unwrap(),
4005            &mut talk,
4006            &talks,
4007            &cfg,
4008            "check the tests",
4009            Vec::new(),
4010        )
4011        .await
4012        .expect_err("a turn with no answer is an error");
4013        assert!(err.to_string().contains("no answer"), "{err}");
4014
4015        let on_disk = talks.get(&talk.id).expect("get");
4016        assert_eq!(on_disk.turns.len(), 2);
4017        assert_eq!(on_disk.turns[0].body, "check the tests");
4018        let note = &on_disk.turns[1];
4019        assert_eq!(note.who, Who::Agent);
4020        assert!(note.body.starts_with(MAGI_NOTE), "{}", note.body);
4021        assert!(note.body.contains("your message is saved"));
4022    }
4023
4024    /// The failure this stands in for: a reader elsewhere briefly has the
4025    /// talk file open right when `turn` tries to save the reply, and the
4026    /// write-then-rename fails once or twice before the reader lets go.
4027    /// `write_atomic`'s own retries must absorb that with nobody the wiser -
4028    /// no gap in the transcript, no dropped turn.
4029    #[tokio::test]
4030    async fn a_passing_write_failure_while_saving_the_reply_does_not_lose_it() {
4031        let (tmp, talks) = store();
4032        let spec = mock_agent(tmp.path(), REPLY, env("go ahead"));
4033        let cfg = config(spec);
4034        let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4035
4036        let text =
4037            record(&mut talk, &talks, "can I rename this function?", Vec::new()).expect("record");
4038        // One fewer failure than `write_atomic` will retry through, so the
4039        // very last attempt must succeed.
4040        failpoint::force_put_failures(PUT_RETRIES - 1);
4041        respond(
4042            &talks.claim_turn(&talk.id).unwrap().unwrap(),
4043            &mut talk,
4044            &talks,
4045            &cfg,
4046            &text,
4047        )
4048        .await
4049        .expect("respond must survive a write failure its own retries can outlast");
4050
4051        assert_eq!(talk.turns.len(), 2);
4052        assert_eq!(talk.turns[1].who, Who::Agent);
4053        assert_eq!(talk.turns[1].body, "go ahead");
4054        let on_disk = talks.get(&talk.id).expect("get");
4055        assert_eq!(
4056            on_disk.turns, talk.turns,
4057            "the reply must reach disk despite the early write failures"
4058        );
4059    }
4060
4061    /// When the write-then-rename never recovers - standing in for a disk
4062    /// that stays unwritable rather than a reader that eventually lets go -
4063    /// the reply must not disappear without a trace the way it did in the
4064    /// real incident this repository saw: no error on the phone, no note in
4065    /// the transcript, and the turn simply gone from `talks/<id>.json`.
4066    #[tokio::test]
4067    async fn a_persistent_write_failure_while_saving_the_reply_is_never_silent() {
4068        let (tmp, talks) = store();
4069        let spec = mock_agent(tmp.path(), REPLY, env("go ahead"));
4070        let cfg = config(spec);
4071        let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4072
4073        let text = record(&mut talk, &talks, "check the tests", Vec::new()).expect("record");
4074        // Exactly enough forced failures to exhaust the reply's own retries;
4075        // the shorter note that replaces it then saves cleanly, which is the
4076        // common case this exercises - a large write racing something,
4077        // followed by a small one that does not.
4078        failpoint::force_put_failures(PUT_RETRIES);
4079        let err = respond(
4080            &talks.claim_turn(&talk.id).unwrap().unwrap(),
4081            &mut talk,
4082            &talks,
4083            &cfg,
4084            &text,
4085        )
4086        .await
4087        .expect_err("a reply that cannot be saved must be reported, not swallowed");
4088        assert!(err.to_string().contains("could not be saved"), "{err}");
4089
4090        let on_disk = talks.get(&talk.id).expect("get");
4091        assert_eq!(
4092            on_disk.turns.len(),
4093            2,
4094            "the operator turn plus a visible note"
4095        );
4096        assert_eq!(on_disk.turns[0].body, "check the tests");
4097        let note = &on_disk.turns[1];
4098        assert_eq!(note.who, Who::Agent);
4099        assert!(note.body.starts_with(MAGI_NOTE), "{}", note.body);
4100        assert!(
4101            note.body.contains("could not be saved"),
4102            "the operator must be told the reply is missing, not left staring \
4103             at a gap with no explanation: {}",
4104            note.body
4105        );
4106        assert_eq!(
4107            talk.turns, on_disk.turns,
4108            "the in-memory talk must match what actually landed on disk"
4109        );
4110
4111        // The generated answer itself must still be recoverable, not merely
4112        // reported as lost.
4113        let artifacts = talks.artifacts_of(&talk.id);
4114        let stash = std::fs::read_dir(&artifacts)
4115            .expect("artifacts dir")
4116            .filter_map(|e| e.ok())
4117            .find(|e| e.file_name().to_string_lossy().ends_with("-lost.txt"))
4118            .expect("a stash file for the lost reply");
4119        let stashed = std::fs::read_to_string(stash.path()).expect("read stash");
4120        assert_eq!(stashed, "go ahead");
4121
4122        // Losing the reply must not also lose the seat. The CLI took a turn
4123        // and consumed this seat's session id; if the note's write left the
4124        // record claiming otherwise, the next turn would re-open a session
4125        // the CLI is already holding - the `20260907-011805-fb57` desync -
4126        // and would re-send the whole briefing besides. Both decisions read
4127        // the seat straight off disk (`agent::has_session` and `turn`'s own
4128        // `seat.turns == 0` branch), so this is the field that has to match.
4129        assert_eq!(
4130            on_disk.seat.turns, 1,
4131            "the note's write must carry the turn the CLI actually took"
4132        );
4133        assert_eq!(
4134            on_disk.seat.claude_session, talk.seat.claude_session,
4135            "the session id handed to the CLI must survive the failed reply"
4136        );
4137        assert_eq!(on_disk.seat.captured_session, talk.seat.captured_session);
4138        assert!(
4139            agent::has_session(AgentKind::Command, &on_disk.seat, cfg.graph.sessions),
4140            "the next turn must resume, not open the same session id twice"
4141        );
4142    }
4143
4144    /// Even the note can fail to save, if the disk stays unwritable for long
4145    /// enough. `respond` must still report the failure rather than pretend
4146    /// the turn succeeded, and must not leave the in-memory `talk` claiming
4147    /// a turn that never reached disk.
4148    #[tokio::test]
4149    async fn a_write_failure_that_also_loses_the_note_still_reports_it() {
4150        let (tmp, talks) = store();
4151        let spec = mock_agent(tmp.path(), REPLY, env("go ahead"));
4152        let cfg = config(spec);
4153        let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4154
4155        let text = record(&mut talk, &talks, "check the tests", Vec::new()).expect("record");
4156        // Enough forced failures to exhaust the retries for both the reply
4157        // and the note that would have replaced it.
4158        failpoint::force_put_failures(PUT_RETRIES * 2);
4159        let err = respond(
4160            &talks.claim_turn(&talk.id).unwrap().unwrap(),
4161            &mut talk,
4162            &talks,
4163            &cfg,
4164            &text,
4165        )
4166        .await
4167        .expect_err("neither the reply nor the note could be saved");
4168        assert!(err.to_string().contains("could not be saved"), "{err}");
4169
4170        assert_eq!(talk.turns.len(), 1, "only the operator's own turn");
4171        let on_disk = talks.get(&talk.id).expect("get");
4172        assert_eq!(on_disk.turns.len(), 1);
4173
4174        // Nothing at all reached disk, so the seat could not either: the CLI
4175        // took a turn the record does not know about. That is pinned here as
4176        // the known cost of a file that cannot be written twice over, not as
4177        // something this branch could do better - the only way to record the
4178        // seat is the write that just failed. It is also the point where
4179        // this meets `20260907-011805-fb57`: a turn taken before some later
4180        // write lands would re-open a session id the CLI already holds. The
4181        // in-memory seat keeps the truth the CLI reported, which is why it is
4182        // not wound back to match.
4183        assert_eq!(
4184            on_disk.seat.turns, 0,
4185            "an unwritable file cannot record the turn the CLI took"
4186        );
4187        assert_eq!(
4188            talk.seat.turns, 1,
4189            "the in-memory seat still reports the turn the CLI actually took"
4190        );
4191        assert_eq!(
4192            on_disk.seat.claude_session, talk.seat.claude_session,
4193            "the session id was minted at `begin` and never changes here"
4194        );
4195    }
4196
4197    /// An attachment lets the operator send an otherwise-empty message, and
4198    /// its absolute path is what actually reaches the agent's prompt - here
4199    /// on the very first turn, where it has to share the briefing.
4200    #[tokio::test]
4201    async fn attachments_reach_the_prompt_and_an_empty_body_is_still_a_turn() {
4202        let (tmp, talks) = store();
4203        let spec = mock_agent(tmp.path(), ECHO, BTreeMap::new());
4204        let cfg = config(spec);
4205        let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4206
4207        let att = talks
4208            .put_attachment(
4209                &talk.id,
4210                "image/png",
4211                "screenshot.png",
4212                b"pretend-png-bytes",
4213            )
4214            .expect("put attachment");
4215
4216        say(
4217            &talks.claim_turn(&talk.id).unwrap().unwrap(),
4218            &mut talk,
4219            &talks,
4220            &cfg,
4221            "",
4222            vec![att.clone()],
4223        )
4224        .await
4225        .expect("an empty body with an attachment is still a turn");
4226
4227        let operator_turn = &talk.turns[0];
4228        assert_eq!(operator_turn.who, Who::Operator);
4229        assert_eq!(operator_turn.body, "");
4230        assert_eq!(operator_turn.attachments, vec![att.clone()]);
4231
4232        let prompt = &talk.turns[1].body;
4233        let expected_path = talks
4234            .attachments_dir(&talk.id)
4235            .join(format!("{}.png", att.id));
4236        assert!(
4237            prompt.contains(&expected_path.display().to_string()),
4238            "the agent must be told the attachment's absolute path: {prompt}"
4239        );
4240        assert!(prompt.contains("image/png"), "and its mime: {prompt}");
4241    }
4242
4243    /// See `chat`'s test of the same name: `run::home()` returns a bare
4244    /// relative `PathBuf` verbatim when `MAGI_HOME` is set to a relative
4245    /// path, so a `Talks` store built on it has a relative `root` too. That
4246    /// is fine for this store's own I/O, which runs in this process against
4247    /// this process's cwd, but `attachment_path` hands its result to a
4248    /// *different* process invoked with `cwd: &talk.repo` - an uncorrected
4249    /// relative path would resolve against the repository instead of
4250    /// wherever the attachment actually landed.
4251    #[test]
4252    fn attachment_path_is_absolute_even_when_the_store_root_is_relative() {
4253        let talks = Talks::at(PathBuf::from("relative-talks-root-for-this-test"));
4254        let att = Attachment {
4255            id: "0".repeat(32),
4256            name: "shot.png".to_owned(),
4257            mime: "image/png".to_owned(),
4258            bytes: 3,
4259        };
4260        let path = talks
4261            .attachment_path("some-talk-id", &att)
4262            .expect("a supported mime always yields a path");
4263        assert!(
4264            path.is_absolute(),
4265            "must be absolute even off a relative store root: {}",
4266            path.display()
4267        );
4268    }
4269
4270    #[tokio::test]
4271    async fn a_turn_past_the_configured_talk_timeout_is_reported_with_that_timeout() {
4272        // `[graph] timeout_talk` must be the number this module actually
4273        // waits, not a leftover hardcoded fifteen minutes - so the mock
4274        // sleeps past a deliberately tiny override and the failure note is
4275        // checked against that same override, not the old default.
4276        let (tmp, talks) = store();
4277        let slow = mock_agent(
4278            tmp.path(),
4279            "#!/bin/sh\ncat >/dev/null\nsleep 2\n",
4280            BTreeMap::new(),
4281        );
4282        let mut cfg = config(slow);
4283        cfg.graph.timeout_talk = 1;
4284        let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4285
4286        let err = say(
4287            &talks.claim_turn(&talk.id).unwrap().unwrap(),
4288            &mut talk,
4289            &talks,
4290            &cfg,
4291            "check the tests",
4292            Vec::new(),
4293        )
4294        .await
4295        .expect_err("a turn that never answers is an error");
4296        assert!(
4297            err.to_string().contains("did not answer within 1s"),
4298            "{err}"
4299        );
4300
4301        let on_disk = talks.get(&talk.id).expect("get");
4302        let note = on_disk.turns.last().expect("a note turn was recorded");
4303        assert!(
4304            note.body.contains("did not answer within 1s"),
4305            "the transcript must show the configured timeout: {}",
4306            note.body
4307        );
4308    }
4309
4310    #[test]
4311    fn closing_is_idempotent_and_a_closed_talk_takes_no_more_turns() {
4312        let (tmp, talks) = store();
4313        let spec = mock_agent(tmp.path(), REPLY, env("hi"));
4314        let cfg = config(spec);
4315        let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4316
4317        close(&mut talk, &talks).expect("close");
4318        assert_eq!(talk.status, TalkStatus::Closed);
4319        close(&mut talk, &talks).expect("closing twice is not an error");
4320
4321        let err =
4322            record(&mut talk, &talks, "still there?", Vec::new()).expect_err("closed talks refuse");
4323        assert!(err.to_string().contains("closed"));
4324        let _ = &cfg; // config kept only to build the agent above
4325    }
4326
4327    #[tokio::test]
4328    async fn a_close_that_lands_while_a_turn_is_in_flight_is_not_undone_by_the_reply() {
4329        let (tmp, talks) = store();
4330        let spec = mock_agent(tmp.path(), REPLY, env("here you go"));
4331        let cfg = config(spec);
4332        // The in-flight turn's own handle: loaded once, the way a spawned
4333        // background task in `web::talk_say` holds one for the whole turn.
4334        let mut in_flight = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4335
4336        // The operator closes the conversation through a *different* handle
4337        // while the turn above is still running - exactly what a close typed
4338        // on the phone while an agent is mid-answer looks like.
4339        let mut closed_elsewhere = talks.get(&in_flight.id).expect("reread");
4340        close(&mut closed_elsewhere, &talks).expect("close");
4341        assert_eq!(
4342            talks.get(&in_flight.id).expect("reread").status,
4343            TalkStatus::Closed,
4344            "the close landed on disk before the turn finished"
4345        );
4346
4347        // The turn's own handle still says `open` - it was loaded before the
4348        // close - and finishing it must not resurrect the conversation the
4349        // operator already ended.
4350        assert_eq!(in_flight.status, TalkStatus::Open);
4351        respond(
4352            &talks.claim_turn(&in_flight.id).unwrap().unwrap(),
4353            &mut in_flight,
4354            &talks,
4355            &cfg,
4356            "one more question",
4357        )
4358        .await
4359        .expect("the turn itself still completes");
4360
4361        let on_disk = talks.get(&in_flight.id).expect("reread");
4362        assert_eq!(
4363            on_disk.status,
4364            TalkStatus::Closed,
4365            "a close must stick even when a turn that started before it finishes after it"
4366        );
4367        // The reply is not lost either: a turn already in flight when the
4368        // operator closed still gets its answer recorded.
4369        assert!(
4370            on_disk.turns.iter().any(|t| t.body == "here you go"),
4371            "the in-flight turn's own reply is still recorded: {:?}",
4372            on_disk.turns
4373        );
4374    }
4375
4376    #[test]
4377    fn a_close_that_lands_before_record_is_called_is_not_undone_by_it() {
4378        let (tmp, talks) = store();
4379        let spec = mock_agent(tmp.path(), REPLY, env("hi"));
4380        let cfg = config(spec);
4381        // The handle `web::talk_say` would have read before awaiting config
4382        // discovery, then carried across that await into `record`.
4383        let mut stale = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4384
4385        // The operator closes the conversation through a *different* handle
4386        // in the gap between that read and the call to `record` below.
4387        let mut closed_elsewhere = talks.get(&stale.id).expect("reread");
4388        close(&mut closed_elsewhere, &talks).expect("close");
4389        assert_eq!(
4390            talks.get(&stale.id).expect("reread").status,
4391            TalkStatus::Closed,
4392            "the close landed on disk before record was called"
4393        );
4394
4395        // The stale handle still says `open` - it was loaded before the
4396        // close - so a `record` that trusted it would append a turn and
4397        // write the conversation back open, undoing the close.
4398        assert_eq!(stale.status, TalkStatus::Open);
4399        let err = record(&mut stale, &talks, "still there?", Vec::new())
4400            .expect_err("a close that landed first must be honored, not overwritten");
4401        assert!(err.to_string().contains("closed"));
4402
4403        let on_disk = talks.get(&stale.id).expect("reread");
4404        assert_eq!(
4405            on_disk.status,
4406            TalkStatus::Closed,
4407            "record must not resurrect a conversation closed while its snapshot was stale"
4408        );
4409        assert!(
4410            on_disk.turns.is_empty(),
4411            "the rejected turn must not have been appended: {:?}",
4412            on_disk.turns
4413        );
4414        let _ = &cfg; // config kept only to build the agent above
4415    }
4416
4417    #[test]
4418    fn close_blocks_on_records_guard_rather_than_interleaving_with_it() {
4419        let (tmp, talks) = store();
4420        let spec = mock_agent(tmp.path(), REPLY, env("hi"));
4421        let cfg = config(spec);
4422        let talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4423
4424        // Hold the same guard `record`'s read-modify-write section holds for
4425        // the whole of its own read-then-write, standing in for `record`
4426        // being paused between its read and its `put`.
4427        let held = talks.guard().unwrap();
4428
4429        let talks2 = talks.clone();
4430        let id = talk.id.clone();
4431        let closing = std::thread::spawn(move || {
4432            let mut talk = talks2.get(&id).expect("get");
4433            close(&mut talk, &talks2).expect("close");
4434        });
4435
4436        std::thread::sleep(Duration::from_millis(50));
4437        assert!(
4438            !closing.is_finished(),
4439            "close must wait for the guard, not read and write while it is held - \
4440             a re-read alone narrows this window without closing it"
4441        );
4442
4443        drop(held);
4444        closing.join().expect("close thread panicked");
4445
4446        assert_eq!(
4447            talks.get(&talk.id).expect("reread").status,
4448            TalkStatus::Closed,
4449            "once the guard is free, close still lands"
4450        );
4451        let _ = &cfg; // config kept only to build the agent above
4452    }
4453
4454    #[test]
4455    fn reopening_a_closed_talk_lets_it_take_turns_again_and_reopening_twice_is_not_an_error() {
4456        let (tmp, talks) = store();
4457        let spec = mock_agent(tmp.path(), REPLY, env("hi"));
4458        let cfg = config(spec);
4459        let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4460
4461        close(&mut talk, &talks).expect("close");
4462        assert_eq!(talk.status, TalkStatus::Closed);
4463
4464        reopen(&mut talk, &talks).expect("reopen");
4465        assert_eq!(talk.status, TalkStatus::Open);
4466        assert_eq!(
4467            talks.get(&talk.id).expect("reread").status,
4468            TalkStatus::Open
4469        );
4470
4471        // Idempotent: reopening an already-open talk is not an error.
4472        reopen(&mut talk, &talks).expect("reopening an open talk is not an error");
4473        assert_eq!(talk.status, TalkStatus::Open);
4474
4475        record(&mut talk, &talks, "one more thing", Vec::new())
4476            .expect("a reopened talk takes turns again");
4477        let _ = &cfg; // config kept only to build the agent above
4478    }
4479
4480    #[test]
4481    fn removing_a_talk_deletes_its_record_and_artifacts_and_refuses_an_unknown_id() {
4482        let (tmp, talks) = store();
4483        let spec = mock_agent(tmp.path(), REPLY, env("hi"));
4484        let cfg = config(spec);
4485        let talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4486
4487        let artifacts = talks.artifacts_of(&talk.id);
4488        std::fs::create_dir_all(&artifacts).expect("create artifacts dir");
4489        std::fs::write(artifacts.join("turn-1.txt"), "hello").expect("write artifact");
4490
4491        talks.remove(&talk.id).expect("remove");
4492        assert!(!talks.path_of(&talk.id).is_file(), "the record is gone");
4493        assert!(!artifacts.is_dir(), "the artifacts directory is gone");
4494        assert!(
4495            talks.get(&talk.id).is_err(),
4496            "a removed talk cannot be read back"
4497        );
4498
4499        let err = talks
4500            .remove("nonexistent-id")
4501            .expect_err("unknown id refused");
4502        assert!(err.to_string().contains("no talk matches"), "{err}");
4503        let _ = &cfg; // config kept only to build the agent above
4504    }
4505
4506    #[tokio::test]
4507    async fn a_delete_that_lands_while_a_turn_is_in_flight_is_not_undone_by_the_reply() {
4508        let (tmp, talks) = store();
4509        let spec = mock_agent(tmp.path(), REPLY, env("here you go"));
4510        let cfg = config(spec);
4511        // The in-flight turn's own handle, loaded before the delete lands -
4512        // the same shape as the matching close test above.
4513        let mut in_flight = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4514
4515        talks.remove(&in_flight.id).expect("remove");
4516        assert!(
4517            talks.get(&in_flight.id).is_err(),
4518            "the delete landed on disk before the turn finished"
4519        );
4520
4521        // The turn's own handle has no way to know the record is gone -
4522        // finishing it must not write the file back into existence.
4523        respond(
4524            &talks.claim_turn(&in_flight.id).unwrap().unwrap(),
4525            &mut in_flight,
4526            &talks,
4527            &cfg,
4528            "one more question",
4529        )
4530        .await
4531        .expect("the turn itself still completes rather than erroring");
4532
4533        assert!(
4534            talks.get(&in_flight.id).is_err(),
4535            "a delete must stick even when a turn that started before it finishes after it"
4536        );
4537    }
4538
4539    #[test]
4540    fn a_delete_that_lands_before_record_is_called_is_not_undone_by_it() {
4541        let (tmp, talks) = store();
4542        let spec = mock_agent(tmp.path(), REPLY, env("hi"));
4543        let cfg = config(spec);
4544        // The handle `web::talk_say` would have read before awaiting config
4545        // discovery, then carried across that await into `record`.
4546        let mut stale = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4547
4548        talks.remove(&stale.id).expect("remove");
4549
4550        // The stale handle has no way to know the record is gone - a
4551        // `record` that trusted it would append a turn and write the
4552        // conversation back into existence.
4553        let err = record(&mut stale, &talks, "still there?", Vec::new())
4554            .expect_err("a delete that landed first must be honored, not overwritten");
4555        assert!(err.to_string().contains("deleted"), "{err}");
4556
4557        assert!(
4558            talks.get(&stale.id).is_err(),
4559            "record must not resurrect a conversation deleted while its snapshot was stale"
4560        );
4561        let _ = &cfg; // config kept only to build the agent above
4562    }
4563
4564    #[test]
4565    fn a_delete_that_lands_before_close_is_called_is_not_undone_by_it() {
4566        let (tmp, talks) = store();
4567        let spec = mock_agent(tmp.path(), REPLY, env("hi"));
4568        let cfg = config(spec);
4569        // `web::talk_close` loads `talk` and calls `close` right after - this
4570        // stands in for a delete landing in that gap.
4571        let mut stale = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4572
4573        talks.remove(&stale.id).expect("remove");
4574
4575        // The stale handle has no way to know the record is gone - a `close`
4576        // that fell back to it would write the conversation back into
4577        // existence, closed.
4578        let err = close(&mut stale, &talks)
4579            .expect_err("a delete that landed first must be honored, not overwritten");
4580        assert!(err.to_string().contains("deleted"), "{err}");
4581
4582        assert!(
4583            talks.get(&stale.id).is_err(),
4584            "close must not resurrect a conversation deleted while its snapshot was stale"
4585        );
4586        let _ = &cfg; // config kept only to build the agent above
4587    }
4588
4589    #[test]
4590    fn a_delete_that_lands_before_reopen_is_called_is_not_undone_by_it() {
4591        let (tmp, talks) = store();
4592        let spec = mock_agent(tmp.path(), REPLY, env("hi"));
4593        let cfg = config(spec);
4594        // `web::talk_reopen` loads `talk` and calls `reopen` right after -
4595        // this stands in for a delete landing in that gap.
4596        let mut stale = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4597        close(&mut stale, &talks).expect("close");
4598
4599        talks.remove(&stale.id).expect("remove");
4600
4601        // The stale handle has no way to know the record is gone - a
4602        // `reopen` that fell back to it would write the conversation back
4603        // into existence, open.
4604        let err = reopen(&mut stale, &talks)
4605            .expect_err("a delete that landed first must be honored, not overwritten");
4606        assert!(err.to_string().contains("deleted"), "{err}");
4607
4608        assert!(
4609            talks.get(&stale.id).is_err(),
4610            "reopen must not resurrect a conversation deleted while its snapshot was stale"
4611        );
4612        let _ = &cfg; // config kept only to build the agent above
4613    }
4614
4615    #[test]
4616    fn list_puts_open_talks_before_closed_ones() {
4617        let (tmp, talks) = store();
4618        let make = |id: &str, status: TalkStatus| {
4619            let mut t = Talk {
4620                pending_breaks: None,
4621                schema: SCHEMA,
4622                id: id.to_owned(),
4623                repo: tmp.path().to_owned(),
4624                agent: "mock".to_owned(),
4625                status,
4626                turns: Vec::new(),
4627                pending: String::new(),
4628                pending_attachments: Vec::new(),
4629                fallback: false,
4630                persona: String::new(),
4631                persona_dirty: false,
4632                implementers: 1,
4633                implementers_dirty: false,
4634                notified: Vec::new(),
4635                created_at: Timestamp::now(),
4636                updated_at: Timestamp::now(),
4637                seat: SeatState::new(SEAT, "mock", 7),
4638            };
4639            talks.put(&mut t).expect("put");
4640        };
4641        make("20260901-000000-0001", TalkStatus::Open);
4642        make("20260902-000000-0002", TalkStatus::Open);
4643        make("20260903-000000-0003", TalkStatus::Closed);
4644
4645        let ids: Vec<String> = talks.list().into_iter().map(|t| t.id).collect();
4646        assert_eq!(
4647            ids,
4648            [
4649                "20260902-000000-0002",
4650                "20260901-000000-0001",
4651                "20260903-000000-0003"
4652            ]
4653        );
4654        assert_eq!(talks.count_open(), 2);
4655    }
4656
4657    #[test]
4658    fn tasks_of_finds_only_this_talks_own_tasks() {
4659        let dir = tempfile::tempdir().expect("tempdir");
4660        let queue = Queue::at(dir.path().join("queue"));
4661
4662        let mut mine = Task::new(
4663            "rework the loader".to_owned(),
4664            "rework the loader".to_owned(),
4665            PathBuf::from("/repo"),
4666            Source::Agent {
4667                run: "20260904-014455-ab12".to_owned(),
4668                node: "chat".to_owned(),
4669            },
4670        );
4671        queue.put(&mut mine).expect("put mine");
4672
4673        let mut theirs = Task::new(
4674            "unrelated".to_owned(),
4675            "unrelated".to_owned(),
4676            PathBuf::from("/repo"),
4677            Source::Agent {
4678                run: "20260904-090000-zz99".to_owned(),
4679                node: "implement".to_owned(),
4680            },
4681        );
4682        queue.put(&mut theirs).expect("put theirs");
4683
4684        let mut human = Task::new(
4685            "typed by hand".to_owned(),
4686            "typed by hand".to_owned(),
4687            PathBuf::from("/repo"),
4688            Source::Human,
4689        );
4690        queue.put(&mut human).expect("put human");
4691
4692        let found = tasks_of(&queue, "20260904-014455-ab12");
4693        assert_eq!(found.len(), 1);
4694        assert_eq!(found[0].id, mine.id);
4695    }
4696
4697    #[test]
4698    fn the_briefing_names_solo_task_add() {
4699        let brief = briefing(Path::new("/repo"), "en", false);
4700        assert!(brief.contains("magi task add --solo"));
4701        assert!(brief.contains("/repo"));
4702        assert!(!brief.contains("Hold this conversation in"));
4703    }
4704
4705    /// Talk fixes `repo` at the directory the conversation was opened in, so
4706    /// an agent asked to change some other checkout has no path to it unless
4707    /// the briefing itself says `--repo` can take a short name - see
4708    /// `resolve_repo_by_name` in `src/main.rs`, which is what actually
4709    /// resolves it.
4710    #[test]
4711    fn the_briefing_explains_targeting_a_different_repository_by_name() {
4712        let brief = briefing(Path::new("/repo"), "en", false);
4713        assert!(brief.contains("--repo does not have to be a full path"));
4714        assert!(brief.contains("owner/repo"));
4715        assert!(brief.contains("magi repos"));
4716        assert!(brief.contains("ask the operator"));
4717    }
4718
4719    #[test]
4720    fn the_briefing_tells_the_assistant_to_pass_images_with_attach() {
4721        let brief = briefing(Path::new("/repo"), "en", false);
4722        assert!(brief.contains("--attach <path>"), "{brief}");
4723        assert!(brief.contains("deleting this conversation"), "{brief}");
4724    }
4725
4726    #[test]
4727    fn the_briefing_names_the_language_when_it_is_not_english() {
4728        let brief = briefing(Path::new("/repo"), "Japanese", false);
4729        assert!(brief.contains("Hold this conversation in Japanese"));
4730    }
4731
4732    #[test]
4733    fn the_briefing_forbids_writes_unless_the_repository_opted_in() {
4734        let read_only = briefing(Path::new("/repo"), "en", false);
4735        assert!(read_only.contains("Do not write files"));
4736        assert!(!read_only.contains("allow_write"));
4737
4738        let writable = briefing(Path::new("/repo"), "en", true);
4739        assert!(!writable.contains("Do not write files"));
4740        assert!(writable.contains("allow_write = true"));
4741        // Still names the queue for anything past a small named edit, and
4742        // still tells the agent to report what it changed.
4743        assert!(writable.contains("magi task add --solo"));
4744        assert!(writable.contains("say plainly what you"));
4745    }
4746
4747    #[test]
4748    fn the_briefing_says_the_chat_cannot_push_and_tasks_report_back() {
4749        let b = briefing_for(Path::new("/r"), "en", false, None, None, 1);
4750        assert!(
4751            b.contains("cannot send the operator a message on your own"),
4752            "{b}"
4753        );
4754        assert!(b.contains(crate::prompt::CHAT_TASK_NOTICE_HEADING));
4755    }
4756
4757    #[test]
4758    fn a_post_is_replayed_until_the_agent_answers_again() {
4759        let (_tmp, talks) = store();
4760        let mut talk = ctx_talk("mock", Vec::new());
4761        talks.put(&mut talk).expect("put");
4762        post(&talks, &talk.id, "  found it  ", "20260902-000000-aaaa").expect("post");
4763        let mut talk = talks.get(&talk.id).expect("get");
4764        let block = posts_since_last_reply(&talk).expect("block");
4765        assert!(block.starts_with("# Posted by a task"), "{block}");
4766        assert!(block.contains("found it"));
4767        talk.turns.push(reply("ok", None));
4768        assert!(posts_since_last_reply(&talk).is_none());
4769        assert!(post(&talks, &talk.id, "  ", "r").is_err());
4770        close(&mut talk, &talks).expect("close");
4771        assert!(post(&talks, &talk.id, "late", "r").is_err());
4772    }
4773
4774    #[test]
4775    fn queue_once_accepts_a_key_a_single_time_even_after_a_drain() {
4776        let (_tmp, talks) = store();
4777        let mut talk = ctx_talk("mock", Vec::new());
4778        talks.put(&mut talk).expect("put");
4779        assert!(queue_once(&mut talk, &talks, "one", "k").expect("first"));
4780        drain(&mut talk, &talks).expect("drain");
4781        assert!(!queue_once(&mut talk, &talks, "one", "k").expect("again"));
4782        assert!(talks.get(&talk.id).expect("get").pending.is_empty());
4783    }
4784}