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