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