1use std::path::{Path, PathBuf};
52use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
53use std::time::Duration;
54
55use anyhow::{Context, Result, bail};
56use jiff::Timestamp;
57use serde::{Deserialize, Serialize};
58
59use crate::agent::{self, Invocation, SeatState};
60use crate::config::{AgentSpec, Config};
61use crate::queue::{Queue, Source, Task};
62
63pub const SCHEMA: u32 = 1;
65
66fn turn_timeout(cfg: &Config) -> Duration {
77 Duration::from_secs(cfg.graph.timeout_talk)
78}
79
80const SEAT: &str = "talk";
83
84const MAGI_NOTE: &str = "magi: ";
86
87#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
89#[serde(rename_all = "lowercase")]
90pub enum Who {
91 Operator,
93 Agent,
96}
97
98#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
106#[serde(deny_unknown_fields)]
107pub struct Attachment {
108 pub id: String,
110 pub name: String,
112 pub mime: String,
115 pub bytes: u64,
117}
118
119#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
121#[serde(deny_unknown_fields)]
122pub struct ReplyTarget {
123 pub turn: usize,
125 pub message: usize,
127}
128
129#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
131pub struct Reply {
132 pub target: ReplyTarget,
134 pub who: Who,
136 pub excerpt: String,
138}
139
140#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
142pub struct Message {
143 pub body: String,
145 pub attachments: Vec<Attachment>,
147 pub reply: Option<Reply>,
149}
150
151fn resolve_reply(talk: &Talk, target: Option<ReplyTarget>) -> Result<Option<Reply>> {
152 let Some(target) = target else {
153 return Ok(None);
154 };
155 let turn = talk
156 .turns
157 .get(target.turn)
158 .context("invalid reply target")?;
159 let (body, attachments) = if turn.messages.is_empty() {
160 if target.message != 0 {
161 bail!("invalid reply target");
162 }
163 (&turn.body, &turn.attachments)
164 } else {
165 let message = turn
166 .messages
167 .get(target.message)
168 .context("invalid reply target")?;
169 (&message.body, &message.attachments)
170 };
171 let excerpt = if body.trim().is_empty() {
172 format!("{} attachment(s)", attachments.len())
173 } else {
174 body.chars().take(240).collect()
175 };
176 Ok(Some(Reply {
177 target,
178 who: turn.who,
179 excerpt,
180 }))
181}
182
183fn message_prompt(turn: &Turn, talk: &Talk, store: &Talks) -> String {
185 if turn.messages.is_empty() {
186 return turn.body.clone();
187 }
188 turn.messages
189 .iter()
190 .map(|message| match &message.reply {
191 Some(reply) => {
192 let mut quote = format!(
193 "[Reply to {:?}: {}]",
194 reply.who,
195 reply.excerpt.lines().collect::<Vec<_>>().join(" "),
196 );
197 if let Some(target) = talk.turns.get(reply.target.turn) {
198 let attachments: &[Attachment] = if target.messages.is_empty() {
199 &target.attachments
200 } else if let Some(message) = target.messages.get(reply.target.message) {
201 &message.attachments
202 } else {
203 &[]
204 };
205 for attachment in attachments {
206 if let Some(path) = store.attachment_path(&talk.id, attachment) {
207 quote.push_str(&format!(
208 "\nReplied-to image: {} ({})",
209 path.display(),
210 attachment.mime
211 ));
212 }
213 }
214 }
215 format!("{quote}\n{}", message.body)
216 }
217 None => message.body.clone(),
218 })
219 .collect::<Vec<_>>()
220 .join("\n\n")
221}
222
223fn messages_need_no_metadata(messages: &[Message]) -> bool {
226 messages
227 .iter()
228 .all(|message| message.reply.is_none() && message.attachments.is_empty())
229}
230
231#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
233#[serde(deny_unknown_fields)]
234pub struct Turn {
235 pub who: Who,
237 pub body: String,
239 pub at: Timestamp,
241 #[serde(default)]
244 pub attachments: Vec<Attachment>,
245 #[serde(default, skip_serializing_if = "Option::is_none")]
250 pub usage: Option<TurnUsage>,
251 #[serde(default, skip_serializing_if = "Option::is_none")]
258 pub breaks: Option<Vec<usize>>,
259 #[serde(default, skip_serializing_if = "Vec::is_empty")]
260 pub messages: Vec<Message>,
262 #[serde(default, skip_serializing_if = "Option::is_none")]
267 pub posted_by: Option<String>,
268}
269
270#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
278pub struct TurnUsage {
279 pub context_tokens: u64,
281 pub agent: String,
283 #[serde(default)]
285 pub model: Option<String>,
286}
287
288#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
293pub struct ContextUsage {
294 pub tokens: Option<u64>,
296 pub window: Option<u64>,
298 pub percent: Option<u64>,
300 pub warn: bool,
302 pub since_switch: bool,
306 pub model: Option<String>,
308 #[serde(default)]
311 pub estimated: bool,
312}
313
314const CONTEXT_WARN_PERCENT: u64 = 80;
316
317const STANDING_PROMPT_FALLBACK_CHARS: u64 = 7000;
320
321pub fn estimate_context_tokens(talk: &Talk, standing_chars: u64) -> Option<u64> {
334 let mut counted = false;
335 let mut chars = standing_chars;
336 for t in talk.turns.iter().filter(|t| !t.body.starts_with(MAGI_NOTE)) {
337 counted = true;
338 chars += t.body.chars().count() as u64;
339 }
340 counted.then(|| (chars * 2).div_ceil(7))
342}
343
344pub fn context_usage(talk: &Talk, cfg: Option<&Config>) -> ContextUsage {
357 let current = cfg.and_then(|c| c.agents.iter().find(|a| a.id == talk.agent));
358 let model = current.and_then(|a| a.model.clone());
359 let window = cfg
360 .zip(model.as_deref())
361 .and_then(|(c, m)| c.context_window(m))
362 .filter(|w| *w > 0);
363 let usage = talk
364 .turns
365 .iter()
366 .rev()
367 .find(|t| t.who == Who::Agent && !t.body.starts_with(MAGI_NOTE))
368 .and_then(|t| t.usage.as_ref());
369 let measured = usage.map(|u| u.context_tokens);
370 let tokens = measured.or_else(|| {
371 let standing = cfg.map_or(STANDING_PROMPT_FALLBACK_CHARS, |c| {
372 briefing_for(
373 &talk.repo,
374 &c.graph.language,
375 c.talk.allow_write,
376 crate::persona::active(&c.talk.personas, &talk.persona).as_ref(),
377 c.talk.operator_name(),
378 talk.implementers,
379 )
380 .chars()
381 .count() as u64
382 });
383 estimate_context_tokens(talk, standing)
384 });
385 let estimated = measured.is_none() && tokens.is_some();
386 let since_switch =
387 usage.is_some_and(|u| u.agent != talk.agent || (current.is_some() && u.model != model));
388 let (percent, warn) = match (tokens, window) {
389 (Some(t), Some(w)) => (
390 Some(t.saturating_mul(100) / w),
391 t.saturating_mul(100) >= w.saturating_mul(CONTEXT_WARN_PERCENT),
392 ),
393 _ => (None, false),
394 };
395 ContextUsage {
396 tokens,
397 window,
398 percent,
399 warn,
400 since_switch,
401 model,
402 estimated,
403 }
404}
405
406#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
410#[serde(rename_all = "lowercase")]
411pub enum TalkStatus {
412 Open,
415 Closed,
417}
418
419impl TalkStatus {
420 pub fn open(self) -> bool {
422 matches!(self, Self::Open)
423 }
424
425 pub fn as_str(self) -> &'static str {
427 match self {
428 Self::Open => "open",
429 Self::Closed => "closed",
430 }
431 }
432}
433
434#[derive(Debug, Clone, Serialize, Deserialize)]
436#[serde(deny_unknown_fields)]
437pub struct Talk {
438 pub schema: u32,
440 pub id: String,
442 pub repo: PathBuf,
444 pub agent: String,
446 pub status: TalkStatus,
448 pub turns: Vec<Turn>,
450 #[serde(default, skip_serializing_if = "Option::is_none")]
454 pub posts_read_through: Option<usize>,
455 #[serde(default)]
458 pub pending: String,
459 #[serde(default)]
461 pub pending_attachments: Vec<Attachment>,
462 #[serde(default, skip_serializing_if = "Option::is_none")]
464 pub pending_breaks: Option<Vec<usize>>,
465 #[serde(default, skip_serializing_if = "Vec::is_empty")]
466 pub pending_messages: Vec<Message>,
468 #[serde(default)]
473 pub fallback: bool,
474 #[serde(default)]
477 pub persona: String,
478 #[serde(default)]
482 pub persona_dirty: bool,
483 #[serde(default = "solo_implementers")]
486 pub implementers: u8,
487 #[serde(default)]
490 pub implementers_dirty: bool,
491 #[serde(default)]
496 pub notified: Vec<String>,
497 pub created_at: Timestamp,
499 pub updated_at: Timestamp,
501 seat: SeatState,
506}
507
508impl Talk {
509 pub fn short(&self) -> &str {
511 short(&self.id)
512 }
513}
514
515#[derive(Debug, Clone)]
517pub struct Talks {
518 root: PathBuf,
519 lock: Arc<Mutex<()>>,
528}
529
530impl Talks {
531 pub fn open() -> Self {
533 Self::at(crate::run::home().join("talks"))
534 }
535
536 pub fn at(root: PathBuf) -> Self {
539 Self {
540 root,
541 lock: Arc::new(Mutex::new(())),
542 }
543 }
544
545 fn guard(&self) -> Result<StoreGuard<'_>> {
560 let mutex = self.lock.lock().unwrap_or_else(PoisonError::into_inner);
561 std::fs::create_dir_all(&self.root)
562 .with_context(|| format!("create {}", self.root.display()))?;
563 let path = self.root.join(".store.turn");
564 let deadline = std::time::Instant::now() + TAKEOVER_LOCK_TTL * 2;
565 loop {
566 if let Some(file) = TurnLock::take(&path)? {
567 return Ok(StoreGuard {
568 _file: file,
569 _mutex: mutex,
570 });
571 }
572 if std::time::Instant::now() >= deadline {
573 bail!("the talk store is locked by another process");
574 }
575 std::thread::sleep(Duration::from_millis(10));
576 }
577 }
578
579 pub fn root(&self) -> &Path {
581 &self.root
582 }
583
584 pub fn path_of(&self, id: &str) -> PathBuf {
586 self.root.join(format!("{id}.json"))
587 }
588
589 pub fn artifacts_of(&self, id: &str) -> PathBuf {
592 self.root.join(format!("{id}.artifacts"))
593 }
594
595 pub fn attachments_dir(&self, id: &str) -> PathBuf {
599 self.artifacts_of(id).join("attachments")
600 }
601
602 pub fn put_attachment(
611 &self,
612 id: &str,
613 mime: &str,
614 name: &str,
615 data: &[u8],
616 ) -> Result<Attachment> {
617 let dir = self.attachments_dir(id);
618 std::fs::create_dir_all(&dir).with_context(|| format!("create {}", dir.display()))?;
619 let ext = attachment_ext(mime).with_context(|| format!("unsupported mime `{mime}`"))?;
620 let att = Attachment {
621 id: new_attachment_id(),
622 name: name.to_owned(),
623 mime: mime.to_owned(),
624 bytes: data.len() as u64,
625 };
626 std::fs::write(dir.join(format!("{}.{ext}", att.id)), data)
627 .with_context(|| format!("write attachment {}", att.id))?;
628 std::fs::write(
629 dir.join(format!("{}.json", att.id)),
630 serde_json::to_string(&att).context("serialize attachment")?,
631 )
632 .with_context(|| format!("write attachment metadata {}", att.id))?;
633 Ok(att)
634 }
635
636 pub fn attachment_meta(&self, id: &str, att_id: &str) -> Result<Option<Attachment>> {
645 if !valid_attachment_id(att_id) {
646 return Ok(None);
647 }
648 let meta_path = self.attachments_dir(id).join(format!("{att_id}.json"));
649 if !meta_path.is_file() {
650 return Ok(None);
651 }
652 let att = serde_json::from_str(
653 &std::fs::read_to_string(&meta_path)
654 .with_context(|| format!("read {}", meta_path.display()))?,
655 )
656 .with_context(|| format!("parse {}", meta_path.display()))?;
657 Ok(Some(att))
658 }
659
660 pub fn read_attachment(&self, id: &str, att_id: &str) -> Result<Option<(Attachment, Vec<u8>)>> {
664 let Some(att) = self.attachment_meta(id, att_id)? else {
665 return Ok(None);
666 };
667 let ext = attachment_ext(&att.mime).with_context(|| {
668 format!("attachment {att_id} has an unsupported mime `{}`", att.mime)
669 })?;
670 let data_path = self.attachments_dir(id).join(format!("{att_id}.{ext}"));
671 let data =
672 std::fs::read(&data_path).with_context(|| format!("read {}", data_path.display()))?;
673 Ok(Some((att, data)))
674 }
675
676 fn attachment_path(&self, id: &str, att: &Attachment) -> Option<PathBuf> {
693 let ext = attachment_ext(&att.mime)?;
694 let path = self.attachments_dir(id).join(format!("{}.{ext}", att.id));
695 std::path::absolute(&path).ok()
696 }
697
698 pub fn put(&self, t: &mut Talk) -> Result<()> {
707 std::fs::create_dir_all(&self.root)
708 .with_context(|| format!("create {}", self.root.display()))?;
709 t.updated_at = Timestamp::now();
710 let mut persisted = t.clone();
713 for turn in &mut persisted.turns {
714 if turn.attachments.is_empty() && messages_need_no_metadata(&turn.messages) {
715 turn.messages.clear();
716 }
717 }
718 if persisted.pending_attachments.is_empty()
719 && messages_need_no_metadata(&persisted.pending_messages)
720 {
721 persisted.pending_messages.clear();
722 }
723 let body = serde_json::to_string_pretty(&persisted).context("serialize talk")?;
724 let path = self.path_of(&t.id);
725 let tmp = path.with_extension("json.tmp");
726 write_atomic(&tmp, &path, &body)
727 }
728
729 pub fn get(&self, id: &str) -> Result<Talk> {
731 let resolved = self.resolve_id(id)?;
732 read_path(&self.path_of(&resolved))
733 }
734
735 pub fn list(&self) -> Vec<Talk> {
738 self.list_counting_unreadable().0
739 }
740
741 pub fn list_counting_unreadable(&self) -> (Vec<Talk>, usize) {
744 let mut unreadable = 0;
745 let mut all: Vec<Talk> = std::fs::read_dir(&self.root)
746 .into_iter()
747 .flatten()
748 .flatten()
749 .map(|e| e.path())
750 .filter(|p| p.extension().is_some_and(|x| x == "json"))
751 .filter_map(|p| {
752 let talk = read_path(&p).ok();
753 if talk.is_none() {
754 unreadable += 1;
755 }
756 talk
757 })
758 .collect();
759 all.sort_unstable_by(|a, b| {
760 let rank = |t: &Talk| u8::from(!t.status.open());
761 rank(a).cmp(&rank(b)).then_with(|| b.id.cmp(&a.id))
762 });
763 (all, unreadable)
764 }
765
766 pub fn resolve_id(&self, prefix: &str) -> Result<String> {
768 if self.path_of(prefix).is_file() {
769 return Ok(prefix.to_owned());
770 }
771 let hits: Vec<String> = self
772 .list()
773 .into_iter()
774 .map(|t| t.id)
775 .filter(|id| id.starts_with(prefix) || id.ends_with(prefix))
776 .collect();
777 match hits.len() {
778 1 => Ok(hits.into_iter().next().expect("exactly one hit")),
779 0 => bail!("no talk matches `{prefix}`"),
780 _ => bail!(
781 "`{prefix}` matches {} talks: {}",
782 hits.len(),
783 hits.join(", ")
784 ),
785 }
786 }
787
788 pub fn revision(&self) -> u64 {
791 std::fs::read_dir(&self.root)
792 .into_iter()
793 .flatten()
794 .flatten()
795 .filter(|e| e.path().extension().is_none_or(|x| x != "turn"))
796 .filter(|e| !e.file_name().to_string_lossy().starts_with('.'))
797 .filter_map(|e| e.metadata().ok())
798 .filter_map(|m| m.modified().ok())
799 .filter_map(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
800 .map(|d| d.as_millis() as u64)
801 .max()
802 .unwrap_or(0)
803 }
804
805 pub fn count_open(&self) -> usize {
807 self.list().iter().filter(|t| t.status.open()).count()
808 }
809
810 pub fn turn_path(&self, id: &str) -> PathBuf {
813 self.root.join(format!("{id}.turn"))
814 }
815
816 pub fn claim_turn(&self, id: &str) -> Result<Option<TurnLease>> {
825 self.claim_turn_at(id, Timestamp::now())
826 }
827
828 fn claim_turn_at(&self, id: &str, now: Timestamp) -> Result<Option<TurnLease>> {
829 std::fs::create_dir_all(&self.root)
830 .with_context(|| format!("create {}", self.root.display()))?;
831 let path = self.turn_path(id);
832 let token = fresh_token();
833 if create_turn(&path, &token, now)? {
834 return Ok(Some(TurnLease {
835 talk: id.to_owned(),
836 path,
837 token,
838 }));
839 }
840 if lease_blocks(&path, now) {
841 return Ok(None);
842 }
843 let Some(_lock) = TurnLock::take(&path)? else {
848 return Ok(None);
849 };
850 if lease_blocks(&path, now) {
851 return Ok(None);
852 }
853 let _ = std::fs::remove_file(&path);
854 Ok(create_turn(&path, &token, now)?.then_some(TurnLease {
855 talk: id.to_owned(),
856 path,
857 token,
858 }))
859 }
860
861 pub fn turn_held(&self, id: &str) -> bool {
863 read_turn(&self.turn_path(id)).is_some_and(|r| r.fresh(Timestamp::now()))
864 }
865
866 pub fn remove(&self, id: &str) -> Result<()> {
879 let _guard = self.guard()?;
880 let resolved = self.resolve_id(id)?;
881 let path = self.path_of(&resolved);
882 std::fs::remove_file(&path).with_context(|| format!("remove {}", path.display()))?;
883 let artifacts = self.artifacts_of(&resolved);
884 if artifacts.is_dir() {
885 std::fs::remove_dir_all(&artifacts)
886 .with_context(|| format!("remove {}", artifacts.display()))?;
887 }
888 let _ = std::fs::remove_file(self.turn_path(&resolved));
889 Ok(())
890 }
891}
892
893struct StoreGuard<'a> {
896 _file: TurnLock,
897 _mutex: MutexGuard<'a, ()>,
898}
899
900#[derive(Debug, Serialize, Deserialize)]
903struct TurnRecord {
904 token: String,
905 pid: u32,
906 beat_at: Timestamp,
907}
908
909impl TurnRecord {
910 fn fresh(&self, now: Timestamp) -> bool {
911 now.as_second() - self.beat_at.as_second() <= crate::ask::LEASE_TTL.as_secs() as i64
912 }
913}
914
915fn fresh_token() -> String {
919 static SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
920 let n = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
921 let seed = crate::rng::entropy() ^ n.wrapping_mul(0x9E37_79B9_7F4A_7C15);
922 crate::rng::SplitMix64::new(seed).uuid_v4()
923}
924
925fn read_turn(path: &Path) -> Option<TurnRecord> {
926 serde_json::from_str(&std::fs::read_to_string(path).ok()?).ok()
927}
928
929const TAKEOVER_LOCK_TTL: Duration = Duration::from_secs(10);
931
932const TICKET_TTL: Duration = Duration::from_secs(10);
935
936const TICKET_GENERATIONS: u32 = 16;
938
939const TICKET_SWEEP_AGE: Duration = Duration::from_secs(3600);
941
942fn create_exclusive(path: &Path, body: &str) -> Result<bool> {
944 use std::io::Write as _;
945 match std::fs::OpenOptions::new()
946 .write(true)
947 .create_new(true)
948 .open(path)
949 {
950 Ok(mut f) => {
951 if let Err(e) = f.write_all(body.as_bytes()) {
952 drop(f);
953 let _ = std::fs::remove_file(path);
954 return Err(e).with_context(|| format!("write {}", path.display()));
955 }
956 Ok(true)
957 }
958 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => Ok(false),
959 Err(e) => Err(e).with_context(|| format!("create {}", path.display())),
960 }
961}
962
963fn create_turn(path: &Path, token: &str, now: Timestamp) -> Result<bool> {
964 let record = TurnRecord {
965 token: token.to_owned(),
966 pid: std::process::id(),
967 beat_at: now,
968 };
969 let body = serde_json::to_string(&record).context("serialize turn lease")?;
970 let tmp = path.with_extension(format!("turn.{token}.new"));
973 publish_exclusive(path, &tmp, &body)
974}
975
976fn lease_blocks(path: &Path, now: Timestamp) -> bool {
980 if read_turn(path).is_some_and(|r| r.fresh(now)) {
981 return true;
982 }
983 std::fs::metadata(path).is_ok_and(|m| {
984 m.len() == 0
985 && m.modified()
986 .ok()
987 .and_then(|t| t.elapsed().ok())
988 .is_some_and(|age| age <= TAKEOVER_LOCK_TTL)
989 })
990}
991
992fn link_unsupported(e: &std::io::Error) -> bool {
995 e.kind() == std::io::ErrorKind::Unsupported || (cfg!(windows) && e.raw_os_error() == Some(1))
996}
997
998fn create_in_place(path: &Path, body: &str) -> Result<bool> {
1016 use std::io::Write as _;
1017 let mut f = match std::fs::OpenOptions::new()
1018 .write(true)
1019 .create_new(true)
1020 .open(path)
1021 {
1022 Ok(f) => f,
1023 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => return Ok(false),
1024 Err(e) => return Err(e).with_context(|| format!("create {}", path.display())),
1025 };
1026 f.write_all(body.as_bytes())
1027 .with_context(|| format!("write {}", path.display()))?;
1028 Ok(std::fs::read_to_string(path).is_ok_and(|t| t == body))
1031}
1032
1033fn publish_exclusive(path: &Path, tmp: &Path, body: &str) -> Result<bool> {
1034 std::fs::write(tmp, body).with_context(|| format!("write {}", tmp.display()))?;
1035 #[cfg(test)]
1036 let linked = if failpoint::no_link_forced() {
1037 Err(std::io::Error::from(std::io::ErrorKind::Unsupported))
1038 } else {
1039 std::fs::hard_link(tmp, path)
1040 };
1041 #[cfg(not(test))]
1042 let linked = std::fs::hard_link(tmp, path);
1043 let out = match linked {
1044 Ok(()) => Ok(true),
1045 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => Ok(false),
1046 Err(e) if link_unsupported(&e) => create_in_place(path, body),
1047 Err(e) => Err(e).with_context(|| format!("create {}", path.display())),
1048 };
1049 let _ = std::fs::remove_file(tmp);
1050 out
1051}
1052
1053fn remove_if_carries(path: &Path, expected: &str) -> bool {
1064 let gone = path.with_extension(format!("gone.{}", fresh_token()));
1065 if std::fs::rename(path, &gone).is_err() {
1066 return false;
1067 }
1068 let found = std::fs::read_to_string(&gone);
1069 if found.as_ref().is_ok_and(|t| t == expected) {
1070 let _ = std::fs::remove_file(&gone);
1071 return true;
1072 }
1073 if let Ok(body) = found {
1074 let back = path.with_extension(format!("back.{}", fresh_token()));
1075 match publish_exclusive(path, &back, &body) {
1076 Ok(true) => {}
1077 Ok(false) | Err(_) => tracing::warn!(
1078 "{} was replaced while a stale removal had it aside; \
1079 the displaced file is dropped",
1080 path.display()
1081 ),
1082 }
1083 }
1084 let _ = std::fs::remove_file(&gone);
1085 false
1086}
1087
1088struct TurnLock {
1092 path: PathBuf,
1093 token: String,
1094}
1095
1096impl TurnLock {
1097 fn token() -> String {
1098 fresh_token()
1099 }
1100
1101 fn publish(path: &Path, token: &str) -> Result<bool> {
1105 let tmp = path.with_extension(format!("lock.{token}.new"));
1106 publish_exclusive(path, &tmp, token)
1107 }
1108
1109 fn take(lease: &Path) -> Result<Option<Self>> {
1110 let path = lease.with_extension("turn.lock");
1111 let token = Self::token();
1112 if Self::publish(&path, &token)? {
1113 return Ok(Some(Self { path, token }));
1114 }
1115 let Ok(seen) = std::fs::read_to_string(&path) else {
1116 return Ok(None);
1117 };
1118 let key = if !seen.is_empty() && seen.chars().all(|c| c.is_ascii_alphanumeric() || c == '-')
1121 {
1122 seen.as_str()
1123 } else {
1124 "invalid"
1125 };
1126 let aged = std::fs::metadata(&path)
1127 .and_then(|m| m.modified())
1128 .ok()
1129 .and_then(|t| t.elapsed().ok())
1130 .is_some_and(|age| age > TAKEOVER_LOCK_TTL);
1131 if !aged {
1132 return Ok(None);
1133 }
1134 let mut won = false;
1146 for n in 0..TICKET_GENERATIONS {
1147 let ticket = path.with_extension(format!("lock.{key}.break.{n}"));
1148 if create_exclusive(&ticket, "")? {
1149 won = true;
1150 break;
1151 }
1152 let stale = std::fs::metadata(&ticket)
1153 .and_then(|m| m.modified())
1154 .ok()
1155 .and_then(|t| t.elapsed().ok())
1156 .is_some_and(|age| age > TICKET_TTL);
1157 if !stale {
1158 return Ok(None);
1159 }
1160 }
1161 if !won {
1162 Self::sweep_tickets(&path);
1167 return Ok(None);
1168 }
1169 Self::sweep_tickets(&path);
1170 if !remove_if_carries(&path, &seen) {
1176 return Ok(None);
1177 }
1178 if Self::publish(&path, &token)? {
1179 return Ok(Some(Self { path, token }));
1180 }
1181 Ok(None)
1182 }
1183
1184 fn sweep_tickets(path: &Path) {
1187 let (Some(dir), Some(name)) = (path.parent(), path.file_name().and_then(|n| n.to_str()))
1188 else {
1189 return;
1190 };
1191 let prefix = format!("{name}.");
1192 let Ok(entries) = std::fs::read_dir(dir) else {
1193 return;
1194 };
1195 for entry in entries.flatten() {
1196 let file = entry.file_name();
1197 let Some(file) = file.to_str() else { continue };
1198 if !(file.starts_with(&prefix) && file.contains(".break.")) {
1199 continue;
1200 }
1201 let old = entry
1202 .metadata()
1203 .and_then(|m| m.modified())
1204 .ok()
1205 .and_then(|t| t.elapsed().ok())
1206 .is_some_and(|age| age > TICKET_SWEEP_AGE);
1207 if old {
1208 let _ = std::fs::remove_file(entry.path());
1209 }
1210 }
1211 }
1212
1213 fn take_patiently(lease: &Path) -> Option<Self> {
1215 for _ in 0..50 {
1216 match Self::take(lease) {
1217 Ok(Some(lock)) => return Some(lock),
1218 Ok(None) => std::thread::sleep(Duration::from_millis(10)),
1219 Err(_) => return None,
1220 }
1221 }
1222 None
1223 }
1224}
1225
1226impl Drop for TurnLock {
1227 fn drop(&mut self) {
1228 remove_if_carries(&self.path, &self.token);
1230 }
1231}
1232
1233pub const TURN_BEAT: Duration = Duration::from_secs(20);
1236
1237#[derive(Debug)]
1242pub struct TurnLease {
1243 talk: String,
1244 path: PathBuf,
1245 token: String,
1246}
1247
1248impl TurnLease {
1249 pub fn holds(&self) -> bool {
1251 read_turn(&self.path).is_some_and(|r| r.token == self.token)
1252 }
1253
1254 pub fn beat(&self) -> Result<bool> {
1258 let _lock = TurnLock::take_patiently(&self.path)
1259 .with_context(|| format!("lock {} to renew it", self.path.display()))?;
1260 let Some(mut record) = read_turn(&self.path).filter(|r| r.token == self.token) else {
1261 return Ok(false);
1262 };
1263 record.beat_at = Timestamp::now();
1264 let body = serde_json::to_string(&record).context("serialize turn lease")?;
1265 let tmp = self.path.with_extension(format!("turn.{}.tmp", self.token));
1266 write_atomic(&tmp, &self.path, &body)?;
1267 Ok(true)
1268 }
1269
1270 pub async fn beating<T>(&self, fut: impl std::future::Future<Output = T>) -> Result<T> {
1275 self.beating_every(TURN_BEAT, fut).await
1276 }
1277
1278 async fn beating_every<T>(
1279 &self,
1280 period: Duration,
1281 fut: impl std::future::Future<Output = T>,
1282 ) -> Result<T> {
1283 tokio::pin!(fut);
1284 loop {
1285 match tokio::time::timeout(period, &mut fut).await {
1286 Ok(out) => return Ok(out),
1287 Err(_) => match self.beat() {
1288 Ok(true) => {}
1289 Ok(false) => bail!(
1290 "the turn lease {} was taken over; this turn is stopped",
1291 self.path.display()
1292 ),
1293 Err(e) => tracing::warn!("{e:#}"),
1294 },
1295 }
1296 }
1297 }
1298}
1299
1300impl Drop for TurnLease {
1301 fn drop(&mut self) {
1302 if let Some(_lock) = TurnLock::take_patiently(&self.path) {
1305 if read_turn(&self.path).is_some_and(|r| r.token == self.token) {
1306 let _ = std::fs::remove_file(&self.path);
1307 }
1308 }
1309 }
1310}
1311
1312pub fn begin(store: &Talks, cfg: &Config, repo: PathBuf, agent: Option<&str>) -> Result<Talk> {
1322 begin_with(store, cfg, repo, agent, &Preferred::default())
1323}
1324
1325#[derive(Debug, Default, Clone)]
1329pub struct Preferred {
1330 pub agent: Option<String>,
1332 pub persona: Option<String>,
1334 pub implementers: Option<i64>,
1336}
1337
1338pub fn begin_with(
1345 store: &Talks,
1346 cfg: &Config,
1347 repo: PathBuf,
1348 agent: Option<&str>,
1349 preferred: &Preferred,
1350) -> Result<Talk> {
1351 let repo = repo.canonicalize().unwrap_or(repo);
1354 let head = || -> Result<AgentSpec> {
1357 Ok(agent::pick_chain(
1358 &cfg.agents,
1359 cfg.roles.chatter.as_ref(),
1360 &agent::installed,
1361 "chatter",
1362 )?
1363 .remove(0))
1364 };
1365 let mut fallback = agent.is_none();
1366 let spec = match agent {
1367 Some(id) => agent::pick(&cfg.agents, Some(id), &agent::installed)?,
1368 None => {
1369 match preferred
1370 .agent
1371 .as_deref()
1372 .map(str::trim)
1373 .filter(|id| !id.is_empty())
1374 {
1375 Some(id) => match agent::pick(&cfg.agents, Some(id), &agent::installed) {
1376 Ok(spec) => {
1377 fallback = head().is_ok_and(|head| spec.id == head.id);
1378 spec
1379 }
1380 Err(_) => head()?,
1381 },
1382 None => head()?,
1383 }
1384 }
1385 };
1386 let persona = preferred
1387 .persona
1388 .as_deref()
1389 .and_then(|id| crate::persona::find(&cfg.talk.personas, id))
1390 .filter(|p| !p.is_default())
1391 .map(|p| p.id)
1392 .unwrap_or_default();
1393 let implementers = preferred
1394 .implementers
1395 .and_then(|n| u8::try_from(n).ok())
1396 .and_then(|n| check_implementers(n, cfg).ok())
1397 .unwrap_or(1);
1398
1399 let now = Timestamp::now();
1400 let mut talk = Talk {
1401 posts_read_through: Some(0),
1402 pending_breaks: None,
1403 pending_messages: Vec::new(),
1404 schema: SCHEMA,
1405 id: new_id(),
1406 repo,
1407 agent: spec.id.clone(),
1408 status: TalkStatus::Open,
1409 turns: Vec::new(),
1410 pending: String::new(),
1411 pending_attachments: Vec::new(),
1412 fallback,
1413 persona,
1414 persona_dirty: false,
1415 implementers,
1416 implementers_dirty: false,
1417 notified: Vec::new(),
1418 created_at: now,
1419 updated_at: now,
1420 seat: SeatState::new(SEAT, &spec.id, crate::rng::entropy()),
1421 };
1422 store.put(&mut talk)?;
1423 Ok(talk)
1424}
1425
1426pub fn record(
1433 talk: &mut Talk,
1434 store: &Talks,
1435 text: &str,
1436 attachments: Vec<Attachment>,
1437) -> Result<String> {
1438 record_reply(talk, store, text, attachments, None)
1439}
1440
1441pub fn record_reply(
1443 talk: &mut Talk,
1444 store: &Talks,
1445 text: &str,
1446 attachments: Vec<Attachment>,
1447 target: Option<ReplyTarget>,
1448) -> Result<String> {
1449 let _guard = store.guard()?;
1457 let Ok(fresh) = store.get(&talk.id) else {
1462 bail!("talk {} was deleted", talk.short());
1463 };
1464 let reply = resolve_reply(&fresh, target)?;
1465 talk.turns = fresh.turns;
1466 talk.status = fresh.status;
1467 talk.pending = fresh.pending;
1470 talk.pending_breaks = fresh.pending_breaks;
1471 talk.pending_messages = fresh.pending_messages;
1472 talk.pending_attachments = fresh.pending_attachments;
1473 talk.notified = fresh.notified;
1474 if !talk.status.open() {
1475 bail!(
1476 "talk {} is {} and takes no more turns",
1477 talk.short(),
1478 talk.status.as_str()
1479 );
1480 }
1481 let text = text.trim();
1482 if text.is_empty() && attachments.is_empty() {
1483 bail!("nothing to say");
1484 }
1485 talk.turns.push(Turn {
1486 who: Who::Operator,
1487 body: text.to_owned(),
1488 at: Timestamp::now(),
1489 messages: vec![Message {
1490 body: text.to_owned(),
1491 attachments: attachments.clone(),
1492 reply,
1493 }],
1494 attachments,
1495 usage: None,
1496 breaks: Some(Vec::new()),
1497 posted_by: None,
1498 });
1499 store.put(talk)?;
1500 Ok(text.to_owned())
1501}
1502
1503pub fn queue(
1505 talk: &mut Talk,
1506 store: &Talks,
1507 text: &str,
1508 attachments: Vec<Attachment>,
1509) -> Result<()> {
1510 queue_reply(talk, store, text, attachments, None)
1511}
1512
1513pub fn queue_reply(
1515 talk: &mut Talk,
1516 store: &Talks,
1517 text: &str,
1518 attachments: Vec<Attachment>,
1519 target: Option<ReplyTarget>,
1520) -> Result<()> {
1521 queue_keyed(talk, store, text, attachments, None, &|_| false, target).map(|_| ())
1522}
1523
1524pub fn queue_once(talk: &mut Talk, store: &Talks, text: &str, key: &str) -> Result<bool> {
1529 queue_once_matching(talk, store, text, key, &|_| false)
1530}
1531
1532pub(crate) fn queue_once_matching(
1535 talk: &mut Talk,
1536 store: &Talks,
1537 text: &str,
1538 key: &str,
1539 previous: &dyn Fn(&str) -> bool,
1540) -> Result<bool> {
1541 queue_keyed(talk, store, text, Vec::new(), Some(key), previous, None)
1542}
1543
1544fn queue_keyed(
1545 talk: &mut Talk,
1546 store: &Talks,
1547 text: &str,
1548 attachments: Vec<Attachment>,
1549 key: Option<&str>,
1550 previous: &dyn Fn(&str) -> bool,
1551 target: Option<ReplyTarget>,
1552) -> Result<bool> {
1553 let text = text.trim();
1554 if text.is_empty() && attachments.is_empty() {
1555 bail!("nothing to say");
1556 }
1557 let _guard = store.guard()?;
1558 let mut fresh = store
1559 .get(&talk.id)
1560 .with_context(|| format!("talk {} was deleted", talk.short()))?;
1561 if !fresh.status.open() {
1562 bail!(
1563 "talk {} is {} and takes no more turns",
1564 fresh.short(),
1565 fresh.status.as_str()
1566 );
1567 }
1568 if let Some(key) = key {
1569 if fresh.notified.iter().any(|k| k == key || previous(k)) {
1570 *talk = fresh;
1571 return Ok(false);
1572 }
1573 fresh.notified.push(key.to_owned());
1574 }
1575 let reply = resolve_reply(&fresh, target)?;
1576 if fresh.pending_messages.is_empty()
1577 && (!fresh.pending.is_empty() || !fresh.pending_attachments.is_empty())
1578 {
1579 fresh.pending_messages.push(Message {
1580 body: fresh.pending.clone(),
1581 attachments: fresh.pending_attachments.clone(),
1582 reply: None,
1583 });
1584 }
1585 fresh.pending_messages.push(Message {
1586 body: text.to_owned(),
1587 attachments: attachments.clone(),
1588 reply,
1589 });
1590 if !text.is_empty() {
1591 if fresh.pending.is_empty() {
1592 fresh.pending = text.to_owned();
1593 fresh.pending_breaks = Some(Vec::new());
1594 } else {
1595 fresh.pending.push_str("\n\n");
1596 if let Some(b) = fresh.pending_breaks.as_mut() {
1597 b.push(fresh.pending.len());
1598 }
1599 fresh.pending.push_str(text);
1600 }
1601 }
1602 fresh.pending_attachments.extend(attachments);
1603 store.put(&mut fresh)?;
1604 *talk = fresh;
1605 Ok(true)
1606}
1607
1608pub fn post(store: &Talks, talk_id: &str, body: &str, by: &str) -> Result<()> {
1613 let body = body.trim();
1614 if body.is_empty() {
1615 bail!("nothing to post");
1616 }
1617 let _guard = store.guard()?;
1618 let mut fresh = store
1619 .get(talk_id)
1620 .with_context(|| format!("talk {talk_id} does not exist"))?;
1621 if !fresh.status.open() {
1622 bail!(
1623 "talk {} is closed and takes no more messages",
1624 fresh.short()
1625 );
1626 }
1627 fresh.turns.push(Turn {
1628 who: Who::Agent,
1629 body: body.to_owned(),
1630 at: Timestamp::now(),
1631 attachments: Vec::new(),
1632 usage: None,
1633 breaks: None,
1634 messages: Vec::new(),
1635 posted_by: Some(by.to_owned()),
1636 });
1637 store.put(&mut fresh)
1638}
1639
1640fn posts_read_through(talk: &Talk) -> usize {
1642 talk.posts_read_through.unwrap_or_else(|| {
1643 talk.turns
1644 .iter()
1645 .rposition(|t| t.who != Who::Operator && t.posted_by.is_none())
1646 .map_or(0, |i| i + 1)
1647 })
1648}
1649
1650pub fn posts_since_last_reply(talk: &Talk) -> Option<String> {
1652 let posts: Vec<&Turn> = talk
1653 .turns
1654 .iter()
1655 .skip(posts_read_through(talk))
1656 .filter(|t| t.posted_by.is_some())
1657 .collect();
1658 if posts.is_empty() {
1659 return None;
1660 }
1661 let mut out = String::from("# Posted by a task\n\n");
1662 for t in posts {
1663 out.push_str(&format!(
1664 "Task seat {} posted to this conversation: {}\n\n",
1665 short(t.posted_by.as_deref().unwrap_or_default()),
1666 t.body
1667 ));
1668 }
1669 Some(out)
1670}
1671
1672pub fn drain(talk: &mut Talk, store: &Talks) -> Result<Option<String>> {
1674 let _guard = store.guard()?;
1675 let mut fresh = store
1676 .get(&talk.id)
1677 .with_context(|| format!("talk {} was deleted", talk.short()))?;
1678 if !fresh.status.open() || (fresh.pending.is_empty() && fresh.pending_attachments.is_empty()) {
1679 *talk = fresh;
1680 return Ok(None);
1681 }
1682 let text = std::mem::take(&mut fresh.pending);
1683 let attachments = std::mem::take(&mut fresh.pending_attachments);
1684 let breaks = fresh.pending_breaks.take();
1685 let messages = std::mem::take(&mut fresh.pending_messages);
1686 fresh.turns.push(Turn {
1687 who: Who::Operator,
1688 body: text.clone(),
1689 at: Timestamp::now(),
1690 attachments,
1691 usage: None,
1692 breaks,
1693 messages,
1694 posted_by: None,
1695 });
1696 store.put(&mut fresh)?;
1697 *talk = fresh;
1698 Ok(Some(text))
1699}
1700
1701pub async fn say(
1704 lease: &TurnLease,
1705 talk: &mut Talk,
1706 store: &Talks,
1707 cfg: &Config,
1708 text: &str,
1709 attachments: Vec<Attachment>,
1710) -> Result<()> {
1711 check_lease(lease, talk)?;
1712 let text = record(talk, store, text, attachments)?;
1713 respond(lease, talk, store, cfg, &text).await
1714}
1715
1716pub async fn respond(
1722 lease: &TurnLease,
1723 talk: &mut Talk,
1724 store: &Talks,
1725 cfg: &Config,
1726 text: &str,
1727) -> Result<()> {
1728 check_lease(lease, talk)?;
1729 lease
1730 .beating(turn(talk, store, cfg, text))
1731 .await
1732 .and_then(|done| done)
1733}
1734
1735fn check_lease(lease: &TurnLease, talk: &Talk) -> Result<()> {
1736 if lease.talk != talk.id {
1737 bail!("the turn lease is for talk {}, not {}", lease.talk, talk.id);
1738 }
1739 if !lease.holds() {
1742 bail!("the turn lease for talk {} is no longer held", talk.short());
1743 }
1744 Ok(())
1745}
1746
1747pub fn close(talk: &mut Talk, store: &Talks) -> Result<()> {
1765 let _guard = store.guard()?;
1766 let mut fresh = store
1767 .get(&talk.id)
1768 .with_context(|| format!("talk {} was deleted", talk.short()))?;
1769 fresh.status = TalkStatus::Closed;
1770 fresh.pending.clear();
1772 fresh.pending_breaks = None;
1773 fresh.pending_messages.clear();
1774 fresh.pending_attachments.clear();
1775 store.put(&mut fresh)?;
1776 *talk = fresh;
1777 Ok(())
1778}
1779
1780pub fn reopen(talk: &mut Talk, store: &Talks) -> Result<()> {
1791 let _guard = store.guard()?;
1792 let mut fresh = store
1793 .get(&talk.id)
1794 .with_context(|| format!("talk {} was deleted", talk.short()))?;
1795 fresh.status = TalkStatus::Open;
1796 store.put(&mut fresh)?;
1797 *talk = fresh;
1798 Ok(())
1799}
1800
1801pub fn switch_agent(talk: &mut Talk, store: &Talks, spec: &AgentSpec) -> Result<bool> {
1814 let _guard = store.guard()?;
1815 let mut fresh = store
1816 .get(&talk.id)
1817 .with_context(|| format!("talk {} was deleted", talk.short()))?;
1818 if fresh.agent == spec.id {
1819 *talk = fresh;
1820 return Ok(false);
1821 }
1822 let from = std::mem::replace(&mut fresh.agent, spec.id.clone());
1823 fresh.seat = SeatState::new(SEAT, &spec.id, crate::rng::entropy());
1824 fresh.fallback = false;
1826 fresh.turns.push(Turn {
1827 breaks: None,
1828 messages: Vec::new(),
1829 posted_by: None,
1830 who: Who::Agent,
1831 body: format!("{MAGI_NOTE}agent changed from {from} to {}", spec.id),
1832 at: Timestamp::now(),
1833 attachments: Vec::new(),
1834 usage: None,
1835 });
1836 store.put(&mut fresh)?;
1837 *talk = fresh;
1838 Ok(true)
1839}
1840
1841pub fn switch_persona(talk: &mut Talk, store: &Talks, id: &str) -> Result<bool> {
1849 let id = if id.trim() == crate::persona::DEFAULT_ID {
1850 ""
1851 } else {
1852 id.trim()
1853 };
1854 let _guard = store.guard()?;
1855 let mut fresh = store
1856 .get(&talk.id)
1857 .with_context(|| format!("talk {} was deleted", talk.short()))?;
1858 if fresh.persona == id {
1859 *talk = fresh;
1860 return Ok(false);
1861 }
1862 let from = std::mem::replace(&mut fresh.persona, id.to_owned());
1863 fresh.persona_dirty = true;
1864 let label = |p: &str| {
1865 if p.is_empty() {
1866 crate::persona::DEFAULT_ID.to_owned()
1867 } else {
1868 p.to_owned()
1869 }
1870 };
1871 fresh.turns.push(Turn {
1872 breaks: None,
1873 messages: Vec::new(),
1874 posted_by: None,
1875 who: Who::Agent,
1876 body: format!(
1877 "{MAGI_NOTE}persona changed from {} to {}",
1878 label(&from),
1879 label(id)
1880 ),
1881 at: Timestamp::now(),
1882 attachments: Vec::new(),
1883 usage: None,
1884 });
1885 store.put(&mut fresh)?;
1886 *talk = fresh;
1887 Ok(true)
1888}
1889
1890pub fn clear_pending(talk: &mut Talk, store: &Talks) -> Result<()> {
1892 let _guard = store.guard()?;
1893 let mut fresh = store
1894 .get(&talk.id)
1895 .with_context(|| format!("talk {} was deleted", talk.short()))?;
1896 fresh.pending.clear();
1897 fresh.pending_breaks = None;
1898 fresh.pending_messages.clear();
1899 fresh.pending_attachments.clear();
1900 store.put(&mut fresh)?;
1901 *talk = fresh;
1902 Ok(())
1903}
1904
1905pub fn clear_pending_if_matches(
1907 talk: &mut Talk,
1908 store: &Talks,
1909 expected_text: &str,
1910 expected_attachments: &[String],
1911) -> Result<bool> {
1912 let _guard = store.guard()?;
1913 let mut fresh = store
1914 .get(&talk.id)
1915 .with_context(|| format!("talk {} was deleted", talk.short()))?;
1916 if !pending_matches(&fresh, expected_text, expected_attachments) {
1917 *talk = fresh;
1918 return Ok(false);
1919 }
1920 fresh.pending.clear();
1921 fresh.pending_breaks = None;
1922 fresh.pending_messages.clear();
1923 fresh.pending_attachments.clear();
1924 store.put(&mut fresh)?;
1925 *talk = fresh;
1926 Ok(true)
1927}
1928
1929pub fn edit_pending_text(
1933 talk: &mut Talk,
1934 store: &Talks,
1935 text: &str,
1936 expected_text: &str,
1937 expected_attachments: &[String],
1938) -> Result<bool> {
1939 edit_pending_message(talk, store, text, expected_text, expected_attachments, None)
1940}
1941
1942pub fn edit_pending_message(
1944 talk: &mut Talk,
1945 store: &Talks,
1946 text: &str,
1947 expected_text: &str,
1948 expected_attachments: &[String],
1949 message: Option<usize>,
1950) -> Result<bool> {
1951 let _guard = store.guard()?;
1952 let mut fresh = store
1953 .get(&talk.id)
1954 .with_context(|| format!("talk {} was deleted", talk.short()))?;
1955 if !pending_matches(&fresh, expected_text, expected_attachments) {
1956 *talk = fresh;
1957 return Ok(false);
1958 }
1959 if let Some(index) = message {
1960 let edited = fresh
1961 .pending_messages
1962 .get_mut(index)
1963 .context("invalid queued message")?;
1964 if text.trim().is_empty() && edited.attachments.is_empty() {
1965 fresh.pending_messages.remove(index);
1966 } else {
1967 edited.body = text.trim().to_owned();
1968 }
1969 fresh.pending.clear();
1970 fresh.pending_breaks = Some(Vec::new());
1971 fresh.pending_attachments.clear();
1972 for message in &fresh.pending_messages {
1973 if !message.body.is_empty() {
1974 if !fresh.pending.is_empty() {
1975 fresh.pending.push_str("\n\n");
1976 fresh
1977 .pending_breaks
1978 .as_mut()
1979 .expect("initialized")
1980 .push(fresh.pending.len());
1981 }
1982 fresh.pending.push_str(&message.body);
1983 }
1984 fresh
1985 .pending_attachments
1986 .extend(message.attachments.clone());
1987 }
1988 } else {
1989 if fresh.pending_messages.len() > 1
1990 && fresh.pending_messages.iter().any(|m| m.reply.is_some())
1991 {
1992 bail!("edit queued replies individually");
1993 }
1994 let reply = fresh.pending_messages.first().and_then(|m| m.reply.clone());
1995 fresh.pending_messages = vec![Message {
1996 body: text.trim().to_owned(),
1997 attachments: fresh.pending_attachments.clone(),
1998 reply,
1999 }];
2000 fresh.pending = text.trim().to_owned();
2001 fresh.pending_breaks = Some(Vec::new());
2002 }
2003 store.put(&mut fresh)?;
2004 *talk = fresh;
2005 Ok(true)
2006}
2007
2008fn pending_matches(talk: &Talk, expected_text: &str, expected_attachments: &[String]) -> bool {
2009 talk.pending == expected_text
2010 && talk
2011 .pending_attachments
2012 .iter()
2013 .map(|attachment| &attachment.id)
2014 .eq(expected_attachments.iter())
2015}
2016
2017async fn turn(talk: &mut Talk, store: &Talks, cfg: &Config, text: &str) -> Result<()> {
2024 let text = talk
2028 .turns
2029 .last()
2030 .filter(|t| t.who == Who::Operator && t.body == text)
2031 .map(|turn| message_prompt(turn, talk, store))
2032 .unwrap_or_else(|| text.to_owned());
2033 let prompt_turns = talk.turns.len();
2034 talk.posts_read_through = Some(posts_read_through(talk));
2035 let spec = cfg
2036 .agents
2037 .iter()
2038 .find(|a| a.id == talk.agent)
2039 .with_context(|| {
2040 format!(
2041 "talk {} was opened with agent `{}`, which is no longer in \
2042 the roster; restore it in magi.toml or start a new \
2043 conversation",
2044 talk.short(),
2045 talk.agent
2046 )
2047 })?;
2048
2049 let last_note = attachment_note(
2053 store,
2054 &talk.id,
2055 talk.turns
2056 .last()
2057 .map_or(&[][..], |t| t.attachments.as_slice()),
2058 );
2059
2060 let attachment_paths: Vec<PathBuf> = talk
2066 .turns
2067 .iter()
2068 .flat_map(|t| t.attachments.iter())
2069 .filter_map(|a| store.attachment_path(&talk.id, a))
2070 .collect();
2071
2072 let questions =
2082 crate::run::try_home().map(|home| crate::ask::Questions::at(home.join("questions")));
2083 let consulted = questions
2084 .as_ref()
2085 .is_some_and(|q| crate::consult::pending_consults(q, &talk.id));
2086 let consult_roots: Vec<PathBuf> = match &questions {
2087 Some(q) if consulted => vec![q.root().to_path_buf()],
2088 _ => Vec::new(),
2089 };
2090
2091 let (allow_write, unsandboxed) = turn_access(cfg.talk.allow_write, consulted);
2092
2093 let artifacts = store.artifacts_of(&talk.id);
2094 let operator_turns = talk.turns.iter().filter(|t| t.who == Who::Operator).count();
2097 let stem = format!("turn-{}", operator_turns.max(1));
2098 let cache_dir = cfg.cache_dir();
2101
2102 let mut chain = vec![spec.clone()];
2105 if let Some(choice) = cfg.roles.chatter.as_ref()
2106 && talk.fallback
2107 {
2108 for id in choice.ids() {
2109 if id == talk.agent || chain.iter().any(|s| s.id == id) {
2110 continue;
2111 }
2112 match agent::pick(&cfg.agents, Some(id), &agent::installed) {
2113 Ok(s) => chain.push(s),
2114 Err(e) => tracing::warn!("[roles] chatter: skipping `{id}`: {e:#}"),
2115 }
2116 }
2117 }
2118
2119 let persona = crate::persona::active(&cfg.talk.personas, &talk.persona);
2120 let operator_name = cfg.talk.operator_name();
2121 let persona_update = if talk.persona_dirty {
2122 format!(
2123 "{}\n\n",
2124 crate::persona::update_block_for(persona.as_ref(), operator_name)
2125 )
2126 } else {
2127 String::new()
2128 };
2129
2130 let filing_update = if talk.implementers_dirty {
2133 format!("{}\n\n", filing_update_block(talk.implementers))
2134 } else {
2135 String::new()
2136 };
2137
2138 let mut outcome = None;
2139 let mut fell_back_from: Option<String> = None;
2140 let mut first_try: Option<(String, SeatState)> = None;
2143 for (n, spec) in chain.iter().enumerate() {
2144 if n > 0 {
2145 if first_try.is_none() {
2146 first_try = Some((talk.agent.clone(), talk.seat.clone()));
2147 }
2148 tracing::warn!("chat: falling back from `{}` to `{}`", talk.agent, spec.id);
2149 fell_back_from.get_or_insert_with(|| talk.agent.clone());
2152 talk.agent = spec.id.clone();
2153 talk.seat = SeatState::new(SEAT, &spec.id, crate::rng::entropy());
2154 }
2155 let resuming = agent::has_session(spec.kind, &talk.seat, cfg.graph.sessions);
2156 let first_ever = talk.turns.len() <= 1;
2157 let body = if talk.seat.turns == 0 && first_ever {
2158 format!(
2159 "{}\n\n# Operator\n\n{text}{last_note}",
2160 briefing_for(
2161 &talk.repo,
2162 &cfg.graph.language,
2163 cfg.talk.allow_write,
2164 persona.as_ref(),
2165 operator_name,
2166 talk.implementers
2167 )
2168 )
2169 } else if talk.seat.turns == 0 {
2170 format!(
2173 "{}\n\n{}\n\n# Operator\n\n{text}{last_note}",
2174 briefing_for(
2175 &talk.repo,
2176 &cfg.graph.language,
2177 cfg.talk.allow_write,
2178 persona.as_ref(),
2179 operator_name,
2180 talk.implementers
2181 ),
2182 transcript(talk, store)
2183 )
2184 } else if resuming {
2185 let posts = posts_since_last_reply(talk).unwrap_or_default();
2186 format!("{persona_update}{filing_update}{posts}{text}{last_note}")
2187 } else {
2188 let mut standing = match (&persona, talk.persona_dirty) {
2192 (Some(p), false) => format!("{}\n", crate::persona::section_for(p, operator_name)),
2193 _ => persona_update.clone(),
2194 };
2195 if let (None, Some(n)) = (&persona, operator_name) {
2198 standing.push_str(&format!(
2199 "# Addressing the operator\n{}\n",
2200 crate::persona::addressing(n)
2201 ));
2202 }
2203 if talk.implementers_dirty || talk.implementers != 1 {
2204 standing.push_str(&format!("{}\n\n", filing_update_block(talk.implementers)));
2205 }
2206 format!("{}\n\n{standing}{text}{last_note}", transcript(talk, store))
2207 };
2208 let attempt_stem = if n == 0 {
2209 stem.clone()
2210 } else {
2211 format!("{stem}-{}", spec.id)
2212 };
2213 let inv = Invocation {
2214 cwd: &talk.repo,
2215 prompt: &body,
2216 timeout: turn_timeout(cfg),
2217 allow_write,
2222 unsandboxed,
2223 sessions: cfg.graph.sessions,
2224 artifacts: &artifacts,
2225 stem: &attempt_stem,
2226 run: &talk.id,
2229 node: crate::queue::CHAT_NODE,
2230 cache_dir: cache_dir.as_deref(),
2231 attachments: &attachment_paths,
2232 writable: &consult_roots,
2233 };
2234 let result = agent::invoke(spec, &mut talk.seat, &inv).await;
2235 let advance = agent::chain_advances(&result);
2236 if n == 0 || !advance {
2237 outcome = Some(result);
2238 } else {
2239 tracing::warn!("chat: fallback agent `{}` also failed", spec.id);
2241 }
2242 if !advance {
2243 break;
2244 }
2245 }
2246 if outcome.as_ref().is_some_and(agent::chain_advances) {
2247 if let Some((id, seat)) = first_try {
2250 talk.agent = id;
2251 talk.seat = seat;
2252 fell_back_from = None;
2253 }
2254 }
2255 let outcome = outcome.expect("a chain holds at least one agent");
2256 let note = |why: String| Turn {
2257 breaks: None,
2258 messages: Vec::new(),
2259 posted_by: None,
2260 who: Who::Agent,
2261 body: format!("{MAGI_NOTE}{why}"),
2262 at: Timestamp::now(),
2263 attachments: Vec::new(),
2264 usage: None,
2265 };
2266 let (reply, failure) = match outcome {
2267 Err(e) => (
2268 note(format!("could not run agent `{}`: {e}", talk.agent)),
2269 Some(format!("could not run agent `{}`: {e}", talk.agent)),
2270 ),
2271 Ok(out) if out.quota_exhausted() => {
2272 let reset = out
2273 .quota
2274 .as_ref()
2275 .and_then(|q| q.reset.clone())
2276 .map_or_else(String::new, |r| format!(" (resets {r})"));
2277 let why = format!(
2278 "agent `{}` is out of quota{reset}; your message is saved, so \
2279 say it again when the window reopens",
2280 talk.agent
2281 );
2282 (note(why.clone()), Some(why))
2283 }
2284 Ok(out) if out.timed_out => {
2285 let why = format!(
2286 "agent `{}` did not answer within {}s; your message is saved",
2287 talk.agent,
2288 turn_timeout(cfg).as_secs()
2289 );
2290 (note(why.clone()), Some(why))
2291 }
2292 Ok(out) if !out.usable() => {
2293 let why = format!(
2294 "agent `{}` produced no answer (exit {}); your message is saved",
2295 talk.agent,
2296 out.exit_code
2297 .map_or_else(|| "unknown".to_owned(), |c| c.to_string())
2298 );
2299 (note(why.clone()), Some(why))
2300 }
2301 Ok(out) => (
2302 Turn {
2303 breaks: None,
2304 messages: Vec::new(),
2305 posted_by: None,
2306 who: Who::Agent,
2307 body: out.text.trim().to_owned(),
2308 at: Timestamp::now(),
2309 attachments: Vec::new(),
2310 usage: out.context_tokens.map(|context_tokens| TurnUsage {
2313 context_tokens,
2314 agent: talk.agent.clone(),
2315 model: cfg
2316 .agents
2317 .iter()
2318 .find(|a| a.id == talk.agent)
2319 .and_then(|a| a.model.clone()),
2320 }),
2321 },
2322 None,
2323 ),
2324 };
2325
2326 let _guard = store.guard()?;
2338 let Ok(fresh) = store.get(&talk.id) else {
2344 return Ok(());
2345 };
2346 talk.status = fresh.status;
2347 talk.pending = fresh.pending;
2351 talk.pending_breaks = fresh.pending_breaks;
2352 talk.pending_messages = fresh.pending_messages;
2353 talk.pending_attachments = fresh.pending_attachments;
2354 talk.notified = fresh.notified;
2355 if fresh.turns.len() > talk.turns.len() {
2357 let posted: Vec<Turn> = fresh.turns[talk.turns.len()..]
2358 .iter()
2359 .filter(|t| t.posted_by.is_some())
2360 .cloned()
2361 .collect();
2362 talk.turns.extend(posted);
2363 }
2364 if let Some(from) = fell_back_from.filter(|_| failure.is_none()) {
2365 talk.turns.push(note(format!(
2368 "agent changed from {from} to {} (fallback)",
2369 talk.agent
2370 )));
2371 }
2372 if failure.is_none() {
2375 talk.persona_dirty = false;
2376 talk.implementers_dirty = false;
2377 talk.posts_read_through = Some(prompt_turns);
2378 }
2379 talk.turns.push(reply);
2380 if let Err(put_err) = store.put(talk) {
2381 let lost = talk.turns.pop().expect("just pushed above");
2390 let stash = stash_lost_turn(store, &talk.id, &stem, &lost);
2391 let why = match &stash {
2392 Ok(path) => format!(
2393 "agent `{}` answered, but the reply could not be saved to \
2394 this conversation ({put_err:#}); the raw text was kept at \
2395 {} - your message is saved, ask again",
2396 talk.agent,
2397 path.display()
2398 ),
2399 Err(stash_err) => format!(
2400 "agent `{}` answered, but the reply could not be saved to \
2401 this conversation ({put_err:#}), and it could not be kept \
2402 anywhere else either ({stash_err:#}); your message is \
2403 saved, ask again",
2404 talk.agent
2405 ),
2406 };
2407 talk.turns.push(note(why.clone()));
2408 return match store.put(talk) {
2415 Ok(()) => bail!("{why}"),
2416 Err(note_err) => {
2417 talk.turns.pop();
2437 Err(note_err).context(why)
2438 }
2439 };
2440 }
2441
2442 match failure {
2443 Some(why) => bail!("{why}"),
2444 None => Ok(()),
2445 }
2446}
2447
2448fn transcript(talk: &Talk, store: &Talks) -> String {
2451 let mut out = String::from(
2452 "This conversation cannot resume on the CLI's side, so here is \
2453 everything said so far; answer only the last message.\n",
2454 );
2455 for t in &talk.turns {
2456 let who = match t.who {
2457 Who::Operator => "operator",
2458 Who::Agent if t.body.starts_with(MAGI_NOTE) => "magi",
2459 Who::Agent => "you",
2460 };
2461 out.push_str(&format!(
2462 "\n## {who}\n\n{}\n",
2463 message_prompt(t, talk, store).trim()
2464 ));
2465 out.push_str(&attachment_note(store, &talk.id, &t.attachments));
2466 }
2467 out
2468}
2469
2470fn attachment_note(store: &Talks, talk_id: &str, attachments: &[Attachment]) -> String {
2475 if attachments.is_empty() {
2476 return String::new();
2477 }
2478 let mut out = String::from(
2479 "\n\nThe operator attached the image(s) below to this message. Open \
2480 and look at each one before you answer.\n",
2481 );
2482 for att in attachments {
2483 if let Some(path) = store.attachment_path(talk_id, att) {
2484 out.push_str(&format!("\n- {} ({})", path.display(), att.mime));
2485 }
2486 }
2487 out.push('\n');
2488 out
2489}
2490
2491pub(crate) fn turn_access(talk_allow_write: bool, consulted: bool) -> (bool, bool) {
2502 (talk_allow_write || consulted, talk_allow_write)
2503}
2504
2505pub fn briefing(repo: &Path, language: &str, allow_write: bool) -> String {
2521 briefing_with(repo, language, allow_write, None, None)
2522}
2523
2524pub fn briefing_with(
2529 repo: &Path,
2530 language: &str,
2531 allow_write: bool,
2532 persona: Option<&crate::persona::Persona>,
2533 operator_name: Option<&str>,
2534) -> String {
2535 briefing_for(repo, language, allow_write, persona, operator_name, 1)
2536}
2537
2538pub const MAX_IMPLEMENTERS: u8 = 3;
2540
2541fn solo_implementers() -> u8 {
2542 1
2543}
2544
2545fn filing_flag(n: u8) -> String {
2548 if n <= 1 {
2549 "--solo".to_owned()
2550 } else {
2551 format!("--implementers {n}")
2552 }
2553}
2554
2555pub fn filing_update_block(n: u8) -> String {
2558 let flag = filing_flag(n);
2559 if n <= 1 {
2560 format!(
2561 "# Task filing update\n\nThe operator changed how many implementers tasks use. \
2562 From now on file with `magi task add {flag} --repo <repo> <instruction>` \
2563 (one implementer, straight into review).\n"
2564 )
2565 } else {
2566 format!(
2567 "# Task filing update\n\nThe operator changed how many implementers tasks use. \
2568 From now on file with `magi task add {flag} --repo <repo> <instruction>` \
2569 ({n} independent implementations compete). Do not pass `--solo` \
2570 together with `--implementers`; drop any earlier `--solo`.\n"
2571 )
2572 }
2573}
2574
2575pub fn check_implementers(n: u8, cfg: &crate::config::Config) -> std::result::Result<u8, String> {
2578 if !(1..=MAX_IMPLEMENTERS).contains(&n) {
2579 return Err(format!(
2580 "implementers must be 1..={MAX_IMPLEMENTERS}, got {n}"
2581 ));
2582 }
2583 if n > 1 {
2584 let mut cfg = cfg.clone();
2585 crate::queue::RunOverrides {
2586 candidates: Some(usize::from(n)),
2587 ..Default::default()
2588 }
2589 .apply(&mut cfg);
2590 cfg.resolve_roles()
2591 .map_err(|e| format!("{n} implementers is not allowed here: {e:#}"))?;
2592 }
2593 Ok(n)
2594}
2595
2596pub fn switch_implementers(talk: &mut Talk, store: &Talks, n: u8) -> Result<bool> {
2599 let _guard = store.guard()?;
2600 let mut fresh = store
2601 .get(&talk.id)
2602 .with_context(|| format!("talk {} was deleted", talk.short()))?;
2603 if fresh.implementers == n {
2604 *talk = fresh;
2605 return Ok(false);
2606 }
2607 let from = std::mem::replace(&mut fresh.implementers, n);
2608 fresh.implementers_dirty = true;
2609 fresh.turns.push(Turn {
2610 breaks: None,
2611 messages: Vec::new(),
2612 posted_by: None,
2613 who: Who::Agent,
2614 body: format!("{MAGI_NOTE}implementers changed from {from} to {n}"),
2615 at: Timestamp::now(),
2616 attachments: Vec::new(),
2617 usage: None,
2618 });
2619 store.put(&mut fresh)?;
2620 *talk = fresh;
2621 Ok(true)
2622}
2623
2624pub fn briefing_for(
2627 repo: &Path,
2628 language: &str,
2629 allow_write: bool,
2630 persona: Option<&crate::persona::Persona>,
2631 operator_name: Option<&str>,
2632 implementers: u8,
2633) -> String {
2634 let flag = filing_flag(implementers);
2635 let shape = if implementers <= 1 {
2636 "Use --solo: it runs the task through one implementer \
2637 straight into review instead of the usual multi-agent competition, \
2638 which is the right shape for a change this conversation has already \
2639 settled, rather than one still worth several independent takes."
2640 .to_owned()
2641 } else {
2642 format!(
2643 "Use --implementers {implementers}: it has {implementers} \
2644 implementers work on the task independently and compete, which \
2645 is the right shape when several independent takes are worth \
2646 having. Never add --solo to it; the two do not go together."
2647 )
2648 };
2649 let write_policy = if allow_write {
2650 "Write access is enabled for this conversation (`allow_write = \
2651 true`), so you may write files - but only a small, \
2652 already-decided edit the operator names outright in this \
2653 conversation, not an implementation. This is a permission on the \
2654 conversation as a whole, not a property of whichever repository \
2655 it happened to start in: if the operator names a different \
2656 repository for that small edit, the policy allows it there too. \
2657 Your own tool may still confine writes to the repository this \
2658 conversation started in regardless - if a write elsewhere is \
2659 refused, say so plainly rather than working around it. Once you \
2660 have made an edit, say plainly what you edited. Anything bigger, \
2661 or anything still open-ended, still goes through the queue below \
2662 rather than being done here."
2663 } else {
2664 "Do not write files. Implementing a change is not this \
2665 conversation's job; a separate, blind competition of agents does \
2666 that, and a repository this conversation has already edited would \
2667 make their diffs unjudgeable."
2668 };
2669 let mut out = format!(
2670 "You are magi's standing conversation partner for its operator, who \
2671 usually has this open on a phone. Keep replies short: no preamble, \
2672 no restating what they just said.\n\n\
2673 # Repository\n\n{repo}\n\n\
2674 You may look around: read files, run shell commands, search history, \
2675 run tests - whatever answers the question. {write_policy}\n\n\
2676 A short, command-shaped message (\"list\", \"info <id>\", \"show \
2677 3cbf\") is almost always the operator asking you to look something \
2678 up, not an instruction to file - answer it yourself with `magi \
2679 list`, `magi show <id>`, `magi task list`, or the like, the same way \
2680 you would answer any other question in this conversation.\n\n\
2681 # When the operator wants something done\n\n\
2682 Run:\n\n\
2683 magi task add {flag} --repo {repo} <instruction>\n\n\
2684 and tell the operator the task id it prints, so they can follow it \
2685 from the Queue. If it refuses with a duplicate warning (the \
2686 instruction names a branch, commit or pull request that an \
2687 unfinished task, run or PR already owns), do not repeat it with \
2688 --force yourself: tell the operator what it matched and let them \
2689 decide. Write <instruction> so that an implementer who has \
2690 never seen this conversation can act on it alone - it is everything \
2691 they get. {shape}\n\n\
2692 If the operator asks for something in a different repository, \
2693 --repo does not have to be a full path: --repo owner/repo (or just \
2694 repo, when that is unambiguous) is resolved against local checkouts \
2695 the same way `magi repos` lists them. If the command fails because \
2696 nothing matches or more than one checkout shares that name, ask the \
2697 operator which repository they mean (or run `magi repos` yourself \
2698 to see the candidates) rather than guessing.\n\n\
2699 You cannot wait, and you cannot send the operator a message on your \
2700 own: you only speak when they write. A task you file reports back \
2701 into this conversation automatically when it finishes, is held or \
2702 fails, as a message headed \"{notice}\".\n\n\
2703 For a background command you run yourself, register it with \
2704 `magi talk watch --timeout 900 -- <executable> <arguments...>`, for \
2705 example `magi talk watch -- cargo test --locked`. It uses your \
2706 current directory; arguments are passed literally. For shell syntax, \
2707 explicitly call `sh -c`. Only after watch registration succeeds may \
2708 you promise a completion report. Watches default to 900 seconds, \
2709 accept at most 3600 seconds, and share four concurrent slots. Their \
2710 automatic reports resume this conversation through its own turn. \
2711 Never promise to report back on work that is neither a filed task \
2712 nor a successfully registered watch.\n\n\
2713 The current state of the code is whatever origin/main holds, not \
2714 whatever a working tree shows: a primary checkout often lags \
2715 upstream, sits on a detached HEAD and carries uncommitted changes. \
2716 Before answering about code, run `git fetch origin` in that \
2717 repository if it is cheap, then read through \
2718 `git show origin/main:<path>` or `git grep <pattern> origin/main`. \
2719 If the working tree differs, say so; if the fetch fails, say that \
2720 too, so the operator knows the answer may be stale.\n\n\
2721 If the operator attached an image (a screenshot, say) that the task \
2722 is about, pass it with `--attach <path>`, using the absolute path \
2723 the turn's attachment note gives; repeat the flag for several. \
2724 `magi task add {flag} --attach <path> <instruction>` copies the \
2725 file into the task, so the implementer receives it. Do not paste the \
2726 path into <instruction> instead: deleting this conversation deletes \
2727 its attachments, and then that path reaches no one.\n",
2728 repo = repo.display(),
2729 notice = crate::prompt::CHAT_TASK_NOTICE_HEADING,
2730 );
2731 out.push_str(&language_note(language));
2732 match (persona, operator_name) {
2733 (Some(p), n) => out.push_str(&crate::persona::section_for(p, n)),
2734 (None, Some(n)) => {
2735 out.push_str("\n# Addressing the operator\n");
2736 out.push_str(&crate::persona::addressing(n));
2737 }
2738 (None, None) => {}
2739 }
2740 out
2741}
2742
2743fn language_note(language: &str) -> String {
2746 if language.trim().is_empty() || language.eq_ignore_ascii_case("en") {
2747 String::new()
2748 } else {
2749 format!("\nHold this conversation in {language}.\n")
2750 }
2751}
2752
2753pub fn tasks_of(queue: &Queue, talk_id: &str) -> Vec<Task> {
2760 let mut tasks: Vec<Task> = queue
2761 .list()
2762 .into_iter()
2763 .filter(|t| matches!(&t.source, Source::Agent { run, .. } if run == talk_id))
2764 .collect();
2765 tasks.sort_unstable_by(|a, b| a.id.cmp(&b.id));
2766 tasks
2767}
2768
2769fn read_path(path: &Path) -> Result<Talk> {
2770 let body = std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;
2771 let mut talk: Talk =
2772 serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))?;
2773 for turn in &mut talk.turns {
2774 if turn.who == Who::Operator && turn.messages.is_empty() && turn.attachments.is_empty() {
2775 turn.messages = plain_messages(&turn.body, turn.breaks.as_deref());
2776 }
2777 }
2778 if talk.pending_messages.is_empty() && talk.pending_attachments.is_empty() {
2779 talk.pending_messages = plain_messages(&talk.pending, talk.pending_breaks.as_deref());
2780 }
2781 Ok(talk)
2782}
2783
2784fn plain_messages(body: &str, breaks: Option<&[usize]>) -> Vec<Message> {
2786 let Some(breaks) = breaks else {
2787 return Vec::new();
2788 };
2789 if body.is_empty() {
2790 return Vec::new();
2791 }
2792 let mut messages = Vec::new();
2793 let mut start = 0;
2794 for end in breaks
2795 .iter()
2796 .copied()
2797 .chain(std::iter::once(body.len() + 2))
2798 {
2799 let Some(text) = end.checked_sub(2).and_then(|end| body.get(start..end)) else {
2800 return Vec::new();
2801 };
2802 messages.push(Message {
2803 body: text.to_owned(),
2804 attachments: Vec::new(),
2805 reply: None,
2806 });
2807 start = end;
2808 }
2809 messages
2810}
2811
2812const PUT_RETRIES: u32 = 5;
2815
2816fn write_atomic(tmp: &Path, path: &Path, body: &str) -> Result<()> {
2828 let mut last_err = None;
2829 for attempt in 0..PUT_RETRIES {
2830 if attempt > 0 {
2831 std::thread::sleep(Duration::from_millis(20 * u64::from(attempt)));
2832 }
2833 match try_write_atomic(tmp, path, body) {
2834 Ok(()) => return Ok(()),
2835 Err(e) => last_err = Some(e),
2836 }
2837 }
2838 Err(last_err.expect("the loop above always runs at least once"))
2839}
2840
2841fn try_write_atomic(tmp: &Path, path: &Path, body: &str) -> Result<()> {
2842 #[cfg(test)]
2843 if failpoint::take_forced_put_failure() {
2844 bail!("simulated write failure (test)");
2845 }
2846 std::fs::write(tmp, body).with_context(|| format!("write {}", tmp.display()))?;
2847 std::fs::rename(tmp, path).with_context(|| format!("replace {}", path.display()))?;
2848 Ok(())
2849}
2850
2851fn stash_lost_turn(store: &Talks, id: &str, stem: &str, reply: &Turn) -> Result<PathBuf> {
2856 let dir = store.artifacts_of(id);
2857 std::fs::create_dir_all(&dir).with_context(|| format!("create {}", dir.display()))?;
2858 let path = dir.join(format!("{stem}-lost.txt"));
2859 std::fs::write(&path, &reply.body).with_context(|| format!("write {}", path.display()))?;
2860 Ok(path)
2861}
2862
2863#[cfg(test)]
2870mod failpoint {
2871 use std::cell::Cell;
2872
2873 thread_local! {
2874 static FORCE_PUT_FAILURES: Cell<u32> = const { Cell::new(0) };
2875 static FORCE_NO_LINK: Cell<bool> = const { Cell::new(false) };
2876 }
2877
2878 pub(super) fn force_no_link(on: bool) {
2881 FORCE_NO_LINK.with(|c| c.set(on));
2882 }
2883
2884 pub(super) fn no_link_forced() -> bool {
2885 FORCE_NO_LINK.with(Cell::get)
2886 }
2887
2888 pub(super) fn force_put_failures(count: u32) {
2891 FORCE_PUT_FAILURES.with(|c| c.set(count));
2892 }
2893
2894 pub(super) fn take_forced_put_failure() -> bool {
2897 FORCE_PUT_FAILURES.with(|c| {
2898 let n = c.get();
2899 if n == 0 {
2900 false
2901 } else {
2902 c.set(n - 1);
2903 true
2904 }
2905 })
2906 }
2907}
2908
2909fn short(id: &str) -> &str {
2910 id.split('-').next_back().unwrap_or(id)
2911}
2912
2913fn new_id() -> String {
2914 let stamp = jiff::Zoned::now().strftime("%Y%m%d-%H%M%S");
2915 let seed = crate::rng::entropy();
2916 format!("{stamp}-{:04x}", (seed ^ (seed >> 32)) & 0xffff)
2917}
2918
2919fn attachment_ext(mime: &str) -> Option<&'static str> {
2924 match mime {
2925 "image/png" => Some("png"),
2926 "image/jpeg" => Some("jpg"),
2927 "image/gif" => Some("gif"),
2928 "image/webp" => Some("webp"),
2929 _ => None,
2930 }
2931}
2932
2933pub fn valid_attachment_id(id: &str) -> bool {
2938 id.len() == 32
2939 && id
2940 .bytes()
2941 .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
2942}
2943
2944fn new_attachment_id() -> String {
2948 let mut r = crate::rng::SplitMix64::new(crate::rng::entropy());
2949 format!("{:016x}{:016x}", r.next_u64(), r.next_u64())
2950}
2951
2952#[cfg(test)]
2953mod tests {
2954 #[test]
2955 fn turn_access_lifts_the_sandbox_only_for_the_talk_opt_in() {
2956 use super::turn_access;
2957 assert_eq!(turn_access(false, false), (false, false));
2958 assert_eq!(turn_access(true, false), (true, true));
2959 assert_eq!(turn_access(false, true), (true, false));
2961 assert_eq!(turn_access(true, true), (true, true));
2962 }
2963
2964 #[test]
2965 fn the_briefing_points_at_origin_main_not_the_working_tree() {
2966 let b = briefing(Path::new("/r"), "en", false);
2967 assert!(b.contains("origin/main"));
2968 assert!(b.contains("git show origin/main:"));
2969 }
2970 use std::collections::BTreeMap;
2971
2972 use crate::config::{AgentChoice, AgentKind, AgentSpec, Graph};
2973 use crate::queue::{Queue, Source, Task};
2974
2975 use super::*;
2976
2977 fn ctx_agent(id: &str, model: Option<&str>) -> AgentSpec {
2978 AgentSpec {
2979 id: id.to_owned(),
2980 kind: AgentKind::Command,
2981 model: model.map(str::to_owned),
2982 command: Vec::new(),
2983 extra_args: Vec::new(),
2984 env: BTreeMap::new(),
2985 prompt_delivery: None,
2986 }
2987 }
2988
2989 fn ctx_talk(agent: &str, turns: Vec<Turn>) -> Talk {
2990 Talk {
2991 posts_read_through: None,
2992 pending_breaks: None,
2993 pending_messages: Vec::new(),
2994 schema: SCHEMA,
2995 id: "20260904-014455-ab12".to_owned(),
2996 repo: PathBuf::from("."),
2997 agent: agent.to_owned(),
2998 status: TalkStatus::Open,
2999 turns,
3000 pending: String::new(),
3001 pending_attachments: Vec::new(),
3002 fallback: false,
3003 persona: String::new(),
3004 persona_dirty: false,
3005 implementers: 1,
3006 implementers_dirty: false,
3007 notified: Vec::new(),
3008 created_at: Timestamp::now(),
3009 updated_at: Timestamp::now(),
3010 seat: SeatState::new(SEAT, agent, 1),
3011 }
3012 }
3013
3014 fn reply(body: &str, usage: Option<(u64, &str, Option<&str>)>) -> Turn {
3015 Turn {
3016 breaks: None,
3017 messages: Vec::new(),
3018 posted_by: None,
3019 who: Who::Agent,
3020 body: body.to_owned(),
3021 at: Timestamp::now(),
3022 attachments: Vec::new(),
3023 usage: usage.map(|(t, a, m)| TurnUsage {
3024 context_tokens: t,
3025 agent: a.to_owned(),
3026 model: m.map(str::to_owned),
3027 }),
3028 }
3029 }
3030
3031 fn ctx_config(windows: &[(&str, u64)]) -> Config {
3032 Config {
3033 agents: vec![
3034 ctx_agent("small", Some("small-model")),
3035 ctx_agent("big", Some("big-model")),
3036 ctx_agent("plain", None),
3037 ],
3038 context_windows: windows.iter().map(|(k, v)| ((*k).to_owned(), *v)).collect(),
3039 ..Config::default()
3040 }
3041 }
3042
3043 #[test]
3044 fn context_usage_computes_percent_and_warns_at_eighty() {
3045 let cfg = ctx_config(&[("small-model", 1000)]);
3046 let at = |tokens| {
3047 let t = ctx_talk(
3048 "small",
3049 vec![reply("hi", Some((tokens, "small", Some("small-model"))))],
3050 );
3051 context_usage(&t, Some(&cfg))
3052 };
3053 let u = at(799);
3054 assert_eq!((u.percent, u.warn, u.window), (Some(79), false, Some(1000)));
3055 let u = at(800);
3056 assert_eq!((u.percent, u.warn), (Some(80), true));
3057 let u = at(1500);
3058 assert_eq!((u.percent, u.warn), (Some(150), true));
3059 assert!(!u.since_switch);
3060 }
3061
3062 #[test]
3063 fn context_usage_is_unknown_without_usage_and_never_looks_back() {
3064 let cfg = ctx_config(&[("small-model", 1000)]);
3065 let t = ctx_talk(
3066 "small",
3067 vec![
3068 reply("old", Some((900, "small", Some("small-model")))),
3069 reply("new", None),
3070 ],
3071 );
3072 let u = context_usage(&t, Some(&cfg));
3073 assert!(u.estimated);
3075 assert_ne!(u.tokens, Some(900));
3076 assert!(u.tokens.is_some());
3077 let t = ctx_talk(
3079 "small",
3080 vec![
3081 reply("old", Some((900, "small", Some("small-model")))),
3082 reply("magi: could not run agent", None),
3083 ],
3084 );
3085 assert_eq!(context_usage(&t, Some(&cfg)).tokens, Some(900));
3086 assert_eq!(
3087 context_usage(&ctx_talk("small", Vec::new()), Some(&cfg)).tokens,
3088 None
3089 );
3090 }
3091
3092 #[test]
3093 fn estimate_counts_chars_both_sides_and_standing_prompt() {
3094 let mut t = ctx_talk("small", vec![reply("abcdefg", None)]);
3095 assert_eq!(estimate_context_tokens(&t, 0), Some(2)); let op = Turn {
3097 who: Who::Operator,
3098 ..reply("abcdefg", None)
3099 };
3100 t.turns.push(op);
3101 assert_eq!(estimate_context_tokens(&t, 0), Some(4));
3102 assert!(
3103 estimate_context_tokens(&t, 700).unwrap() > estimate_context_tokens(&t, 0).unwrap()
3104 );
3105 let ja = ctx_talk("small", vec![reply("日本語日本語日", None)]);
3107 assert_eq!(estimate_context_tokens(&ja, 0), Some(2));
3108 let note = ctx_talk("small", vec![reply("magi: could not run agent", None)]);
3110 assert_eq!(estimate_context_tokens(¬e, 1000), None);
3111 assert_eq!(
3112 estimate_context_tokens(&ctx_talk("small", Vec::new()), 1000),
3113 None
3114 );
3115 }
3116
3117 #[test]
3118 fn context_usage_measured_wins_and_estimate_gets_percent_and_warn() {
3119 let cfg = ctx_config(&[("small-model", 1000)]);
3120 let t = ctx_talk(
3121 "small",
3122 vec![reply(
3123 &"x".repeat(5000),
3124 Some((10, "small", Some("small-model"))),
3125 )],
3126 );
3127 let u = context_usage(&t, Some(&cfg));
3128 assert_eq!((u.tokens, u.estimated), (Some(10), false));
3129 let t = ctx_talk("small", vec![reply(&"x".repeat(5000), None)]);
3130 let u = context_usage(&t, Some(&cfg));
3131 assert!(u.estimated && !u.since_switch);
3132 assert_eq!(u.window, Some(1000));
3133 assert!(u.warn && u.percent.unwrap() >= 80);
3134 let t = ctx_talk("small", vec![reply("hi", None)]);
3135 let u = context_usage(&t, Some(&cfg));
3136 assert!(u.estimated && u.percent.is_some());
3137 }
3138
3139 #[test]
3140 fn context_usage_without_a_window_shows_tokens_only() {
3141 let cfg = ctx_config(&[]);
3142 let t = ctx_talk("plain", vec![reply("hi", Some((5000, "plain", None)))]);
3144 let u = context_usage(&t, Some(&cfg));
3145 assert_eq!(
3146 (u.tokens, u.window, u.percent, u.warn),
3147 (Some(5000), None, None, false)
3148 );
3149 let t = ctx_talk(
3150 "small",
3151 vec![reply("hi", Some((5000, "small", Some("small-model"))))],
3152 );
3153 assert_eq!(context_usage(&t, Some(&cfg)).percent, None);
3154 assert_eq!(context_usage(&t, None).window, None);
3156 }
3157
3158 #[test]
3159 fn context_usage_switching_model_changes_the_denominator() {
3160 let cfg = ctx_config(&[("small-model", 1000), ("big-model", 10_000)]);
3161 let used = reply("hi", Some((900, "small", Some("small-model"))));
3162 let before = context_usage(&ctx_talk("small", vec![used.clone()]), Some(&cfg));
3163 assert_eq!(
3164 (before.percent, before.warn, before.since_switch),
3165 (Some(90), true, false)
3166 );
3167 let after = context_usage(&ctx_talk("big", vec![used]), Some(&cfg));
3170 assert_eq!(after.window, Some(10_000));
3171 assert_eq!(
3172 (after.percent, after.warn, after.since_switch),
3173 (Some(9), false, true)
3174 );
3175 assert_eq!(after.model.as_deref(), Some("big-model"));
3176 }
3177
3178 #[test]
3179 fn a_turn_recorded_before_usage_existed_still_reads() {
3180 let old = r#"{"who":"agent","body":"hi","at":"2026-09-04T01:44:55Z"}"#;
3181 let turn: Turn = serde_json::from_str(old).expect("old turn reads");
3182 assert!(turn.usage.is_none());
3183 let json = serde_json::to_string(&turn).expect("serialize");
3184 assert!(
3185 !json.contains("usage"),
3186 "absent usage is not written: {json}"
3187 );
3188 }
3189
3190 fn store() -> (tempfile::TempDir, Talks) {
3192 let tmp = tempfile::tempdir().expect("tempdir");
3193 let talks = Talks::at(tmp.path().join("talks"));
3194 (tmp, talks)
3195 }
3196
3197 fn mock_agent(dir: &Path, script: &str, env: BTreeMap<String, String>) -> AgentSpec {
3201 let path = dir.join("mock-talk-agent.sh");
3202 std::fs::write(&path, script).expect("write mock");
3203 AgentSpec {
3204 id: "mock".to_owned(),
3205 kind: AgentKind::Command,
3206 model: None,
3207 command: vec!["sh".to_owned(), path.to_string_lossy().into_owned()],
3208 extra_args: Vec::new(),
3209 env,
3210 prompt_delivery: None,
3211 }
3212 }
3213
3214 fn config(spec: AgentSpec) -> Config {
3215 Config {
3216 agents: vec![spec],
3217 graph: Graph {
3218 language: "en".to_owned(),
3219 ..Graph::default()
3220 },
3221 ..Config::default()
3222 }
3223 }
3224
3225 const REPLY: &str = "#!/bin/sh\ncat >/dev/null\nprintf '%s\\n' \"$MOCK_REPLY\"\n";
3227
3228 const BROKEN: &str = "#!/bin/sh\ncat >/dev/null\nexit 3\n";
3230
3231 const ECHO: &str = "#!/bin/sh\ncat\n";
3234
3235 fn env(reply: &str) -> BTreeMap<String, String> {
3236 BTreeMap::from([("MOCK_REPLY".to_owned(), reply.to_owned())])
3237 }
3238
3239 #[test]
3240 fn the_frozen_json_field_names_round_trip_through_disk() {
3241 let (tmp, talks) = store();
3242 let mut talk = Talk {
3243 posts_read_through: None,
3244 pending_breaks: None,
3245 pending_messages: Vec::new(),
3246 schema: SCHEMA,
3247 id: "20260904-014455-ab12".to_owned(),
3248 repo: tmp.path().to_owned(),
3249 agent: "sonnet".to_owned(),
3250 status: TalkStatus::Open,
3251 turns: Vec::new(),
3252 pending: String::new(),
3253 pending_attachments: Vec::new(),
3254 fallback: false,
3255 persona: String::new(),
3256 persona_dirty: false,
3257 implementers: 1,
3258 implementers_dirty: false,
3259 notified: Vec::new(),
3260 created_at: Timestamp::now(),
3261 updated_at: Timestamp::now(),
3262 seat: SeatState::new(SEAT, "sonnet", 7),
3263 };
3264 talks.put(&mut talk).expect("put");
3265
3266 let raw = std::fs::read_to_string(talks.path_of(&talk.id)).expect("read back");
3267 let v: serde_json::Value = serde_json::from_str(&raw).expect("parse");
3268 for field in [
3269 "schema",
3270 "id",
3271 "repo",
3272 "agent",
3273 "status",
3274 "turns",
3275 "created_at",
3276 "updated_at",
3277 ] {
3278 assert!(v.get(field).is_some(), "missing field `{field}`");
3279 }
3280 assert_eq!(v["schema"], 1);
3281 assert_eq!(v["status"], "open");
3282
3283 let back = talks.get(&talk.id).expect("get");
3284 assert_eq!(back.posts_read_through, None);
3285 assert_eq!(back.id, talk.id);
3286 assert_eq!(back.status, TalkStatus::Open);
3287 }
3288
3289 #[test]
3290 fn opening_a_talk_takes_no_agent_turn() {
3291 let (tmp, talks) = store();
3292 let spec = mock_agent(tmp.path(), BROKEN, BTreeMap::new());
3296 let cfg = config(spec);
3297
3298 let talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
3299 assert_eq!(talk.status, TalkStatus::Open);
3300 assert!(talk.turns.is_empty(), "nothing has been said yet");
3301
3302 let on_disk = talks.get(&talk.id).expect("get");
3303 assert_eq!(on_disk.turns.len(), 0);
3304 }
3305
3306 #[test]
3314 fn chatter_wins_when_set_and_falls_back_to_pick_s_default_order_otherwise() {
3315 let (tmp, talks) = store();
3316 let first_spec = mock_agent(tmp.path(), BROKEN, BTreeMap::new());
3317 let mut chatter_spec = mock_agent(tmp.path(), BROKEN, BTreeMap::new());
3318 chatter_spec.id = "chatter-mock".to_owned();
3319
3320 let mut cfg = Config {
3321 agents: vec![first_spec.clone(), chatter_spec.clone()],
3322 graph: Graph {
3323 language: "en".to_owned(),
3324 ..Graph::default()
3325 },
3326 ..Config::default()
3327 };
3328 cfg.roles.chatter = Some(chatter_spec.id.as_str().into());
3329
3330 let talk =
3331 begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin with chatter set");
3332 assert_eq!(talk.agent, chatter_spec.id, "an explicit chatter must win");
3333
3334 cfg.roles.chatter = None;
3335 let fallback =
3336 begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin with chatter unset");
3337 assert_eq!(
3338 fallback.agent, first_spec.id,
3339 "unset chatter must fall back to agent::pick's own default order"
3340 );
3341 }
3342
3343 #[test]
3346 fn a_talk_recorded_without_attachments_still_reads() {
3347 let (tmp, talks) = store();
3348 let path = talks.path_of("20260904-014455-ab12");
3349 std::fs::create_dir_all(talks.root()).expect("talks dir");
3350 std::fs::write(
3351 &path,
3352 serde_json::json!({
3353 "schema": 1,
3354 "id": "20260904-014455-ab12",
3355 "repo": tmp.path(),
3356 "agent": "sonnet",
3357 "status": "open",
3358 "turns": [
3359 { "who": "operator", "body": "still there?",
3360 "at": Timestamp::now().to_string() },
3361 ],
3362 "created_at": Timestamp::now().to_string(),
3363 "updated_at": Timestamp::now().to_string(),
3364 "seat": SeatState::new(SEAT, "sonnet", 7),
3365 })
3366 .to_string(),
3367 )
3368 .expect("write pre-attachments talk");
3369
3370 let talk = talks.get("20260904-014455-ab12").expect("must still read");
3371 assert!(talk.turns[0].attachments.is_empty());
3372 }
3373
3374 fn lease_store() -> (tempfile::TempDir, Talks, Talks) {
3375 let tmp = tempfile::TempDir::new().expect("tmp");
3376 let root = tmp.path().join("talks");
3377 (tmp, Talks::at(root.clone()), Talks::at(root))
3378 }
3379
3380 #[test]
3381 fn two_starters_on_one_talk_one_wins_and_the_other_is_refused() {
3382 let (_tmp, a, b) = lease_store();
3383 let won = a.claim_turn("t1").expect("claim").expect("first wins");
3384 assert!(
3385 b.claim_turn("t1").expect("claim").is_none(),
3386 "second is refused"
3387 );
3388 assert!(b.turn_held("t1"));
3389 assert!(
3390 b.claim_turn("t2").expect("claim").is_some(),
3391 "other talks are free"
3392 );
3393 drop(won);
3394 }
3395
3396 #[test]
3397 fn a_stale_lease_is_taken_over_and_the_old_guard_cannot_release_it() {
3398 let (_tmp, a, b) = lease_store();
3399 let old = a.claim_turn("t1").expect("claim").expect("held");
3400 let later = Timestamp::now()
3401 .checked_add(jiff::SignedDuration::from_secs(
3402 crate::ask::LEASE_TTL.as_secs() as i64 + 5,
3403 ))
3404 .expect("later");
3405 let new = b
3406 .claim_turn_at("t1", later)
3407 .expect("claim")
3408 .expect("a stale lease is taken over");
3409 drop(old);
3410 assert!(a.turn_held("t1"), "the old guard left the new lease alone");
3411 assert!(new.beat().expect("beat"), "the new owner still beats");
3412 drop(new);
3413 assert!(!a.turn_held("t1"));
3414 }
3415
3416 #[tokio::test]
3417 async fn a_turn_whose_lease_was_taken_over_is_stopped() {
3418 let (_tmp, a, b) = lease_store();
3419 let old = a.claim_turn("t1").expect("claim").expect("held");
3420 let later = Timestamp::now()
3421 .checked_add(jiff::SignedDuration::from_secs(
3422 crate::ask::LEASE_TTL.as_secs() as i64 + 5,
3423 ))
3424 .expect("later");
3425 let _new = b
3426 .claim_turn_at("t1", later)
3427 .expect("claim")
3428 .expect("taken over");
3429 let out = old
3430 .beating_every(Duration::from_millis(10), std::future::pending::<()>())
3431 .await;
3432 assert!(out.is_err(), "the displaced turn must stop, not run on");
3433 }
3434
3435 #[tokio::test]
3436 async fn a_turn_that_finishes_is_returned_and_keeps_its_lease_beating() {
3437 let (_tmp, a, _b) = lease_store();
3438 let lease = a.claim_turn("t1").expect("claim").expect("held");
3439 let out = lease
3440 .beating_every(Duration::from_millis(5), async {
3441 tokio::time::sleep(Duration::from_millis(40)).await;
3442 7
3443 })
3444 .await
3445 .expect("still ours");
3446 assert_eq!(out, 7);
3447 assert!(a.turn_held("t1"));
3448 }
3449
3450 #[test]
3451 fn an_unreadable_lease_counts_as_stale() {
3452 let (_tmp, a, b) = lease_store();
3453 std::fs::create_dir_all(a.root()).expect("dir");
3454 std::fs::write(a.turn_path("t1"), "not json").expect("write");
3455 assert!(!a.turn_held("t1"));
3456 assert!(b.claim_turn("t1").expect("claim").is_some());
3457 }
3458
3459 #[test]
3460 fn without_hard_links_a_claim_is_still_exclusive_and_a_young_placeholder_blocks() {
3461 let (_tmp, a, b) = lease_store();
3462 failpoint::force_no_link(true);
3463 let held = a.claim_turn("t1").expect("claim").expect("first wins");
3464 assert!(b.claim_turn("t1").expect("claim").is_none());
3465 assert!(a.turn_held("t1"));
3466 drop(held);
3467 assert!(!a.turn_held("t1"));
3468 let path = a.turn_path("t1");
3470 assert!(create_exclusive(&path, "").expect("placeholder"));
3471 assert!(b.claim_turn("t1").expect("claim").is_none(), "young: held");
3472 age_file(&path);
3473 assert!(b.claim_turn("t1").expect("claim").is_some(), "old: stale");
3474 let lease = a.turn_path("t2");
3476 let lock = TurnLock::take(&lease).expect("take").expect("lock");
3477 assert!(TurnLock::take(&lease).expect("take").is_none());
3478 drop(lock);
3479 assert!(TurnLock::take(&lease).expect("take").is_some());
3480 failpoint::force_no_link(false);
3481 }
3482
3483 #[test]
3484 fn remove_if_carries_removes_only_the_expected_content() {
3485 let (_tmp, a, _b) = lease_store();
3486 std::fs::create_dir_all(a.root()).expect("dir");
3487 let p = a.root().join("x.turn.lock");
3488 std::fs::write(&p, "mine").expect("write");
3489 assert!(!remove_if_carries(&p, "other"));
3490 assert_eq!(std::fs::read_to_string(&p).expect("kept"), "mine");
3491 assert!(remove_if_carries(&p, "mine"));
3492 assert!(!p.exists());
3493 assert!(!remove_if_carries(&p, "mine"), "absent is not a removal");
3494 }
3495
3496 #[test]
3497 fn a_dropped_lock_does_not_remove_a_lock_taken_over_since() {
3498 let (_tmp, a, _b) = lease_store();
3499 std::fs::create_dir_all(a.root()).expect("dir");
3500 let lease = a.turn_path("t1");
3501 let lock = TurnLock::take(&lease).expect("take").expect("lock");
3502 let path = lock.path.clone();
3503 std::fs::write(&path, "someone-else").expect("replace");
3504 drop(lock);
3505 assert_eq!(
3506 std::fs::read_to_string(&path).expect("kept"),
3507 "someone-else"
3508 );
3509 }
3510
3511 #[test]
3512 fn concurrent_takeovers_of_a_stale_lease_have_one_winner() {
3513 let (_tmp, a, _b) = lease_store();
3514 drop(a.claim_turn("t1").expect("claim").expect("held"));
3515 std::fs::write(
3516 a.turn_path("t1"),
3517 serde_json::to_string(&TurnRecord {
3518 token: "gone".into(),
3519 pid: 1,
3520 beat_at: Timestamp::from_second(1).expect("ts"),
3521 })
3522 .expect("json"),
3523 )
3524 .expect("write");
3525 let wins: Vec<_> = std::thread::scope(|sc| {
3526 let hs: Vec<_> = (0..8)
3527 .map(|_| {
3528 let s = a.clone();
3529 sc.spawn(move || s.claim_turn("t1").expect("claim"))
3530 })
3531 .collect();
3532 hs.into_iter().map(|h| h.join().expect("join")).collect()
3533 });
3534 assert_eq!(wins.iter().filter(|w| w.is_some()).count(), 1);
3535 }
3536
3537 fn age_file(path: &Path) {
3538 let f = std::fs::OpenOptions::new()
3539 .write(true)
3540 .open(path)
3541 .expect("open");
3542 f.set_modified(std::time::SystemTime::now() - std::time::Duration::from_secs(60))
3543 .expect("age");
3544 }
3545
3546 #[test]
3547 fn a_late_taker_of_a_broken_lock_cannot_disturb_its_replacement() {
3548 let (_tmp, a, _b) = lease_store();
3549 let lease = a.turn_path("t1");
3550 let lock = lease.with_extension("turn.lock");
3551 std::fs::create_dir_all(lock.parent().expect("dir")).expect("dir");
3552 std::fs::write(&lock, "t1-dead").expect("dead lock");
3553 age_file(&lock);
3554 let b = TurnLock::take(&lease).expect("take").expect("b wins");
3556 let fresh = std::fs::read_to_string(&lock).expect("read");
3557 assert_eq!(fresh, b.token);
3558 let ticket = std::fs::read_dir(lock.parent().expect("dir"))
3561 .expect("dir")
3562 .flatten()
3563 .map(|e| e.path())
3564 .find(|p| p.to_string_lossy().ends_with(".break.0"))
3565 .expect("ticket");
3566 assert!(!create_exclusive(&ticket, "").expect("ticket"));
3567 assert!(TurnLock::take(&lease).expect("take").is_none());
3568 assert_eq!(std::fs::read_to_string(&lock).expect("read"), fresh);
3569 age_file(&lock);
3571 age_file(&ticket);
3572 std::mem::forget(b);
3573 let c = TurnLock::take(&lease)
3574 .expect("take")
3575 .expect("next generation");
3576 assert_ne!(c.token, fresh);
3577 }
3578
3579 #[test]
3580 fn a_live_ticket_blocks_and_a_stale_one_hands_over_to_the_next_generation() {
3581 let (_tmp, a, _b) = lease_store();
3582 let lease = a.turn_path("t1");
3583 let lock = lease.with_extension("turn.lock");
3584 std::fs::create_dir_all(lock.parent().expect("dir")).expect("dir");
3585 std::fs::write(&lock, "t1-dead").expect("dead lock");
3586 age_file(&lock);
3587 let t0 = lock.with_extension("lock.t1-dead.break.0");
3588 assert!(create_exclusive(&t0, "").expect("ticket"));
3589 assert!(TurnLock::take(&lease).expect("take").is_none());
3591 assert_eq!(std::fs::read_to_string(&lock).expect("read"), "t1-dead");
3592 age_file(&t0);
3594 let c = TurnLock::take(&lease).expect("take").expect("generation 1");
3595 assert_eq!(std::fs::read_to_string(&lock).expect("read"), c.token);
3596 assert!(lock.with_extension("lock.t1-dead.break.1").exists());
3597 assert!(TurnLock::take(&lease).expect("take").is_none());
3598 }
3599
3600 #[test]
3601 fn exhausted_ticket_generations_recover_once_the_sweep_ages_them_out() {
3602 let (_tmp, a, _b) = lease_store();
3603 let lease = a.turn_path("t1");
3604 let lock = lease.with_extension("turn.lock");
3605 std::fs::create_dir_all(lock.parent().expect("dir")).expect("dir");
3606 std::fs::write(&lock, "t1-dead").expect("dead lock");
3607 age_file(&lock);
3608 let tickets: Vec<_> = (0..TICKET_GENERATIONS)
3609 .map(|n| lock.with_extension(format!("lock.t1-dead.break.{n}")))
3610 .collect();
3611 for t in &tickets {
3612 assert!(create_exclusive(t, "").expect("ticket"));
3613 age_file(t);
3614 }
3615 assert!(TurnLock::take(&lease).expect("take").is_none());
3617 assert!(tickets.iter().all(|t| t.exists()));
3618 for t in &tickets {
3620 let f = std::fs::OpenOptions::new()
3621 .write(true)
3622 .open(t)
3623 .expect("open");
3624 f.set_modified(std::time::SystemTime::now() - TICKET_SWEEP_AGE * 2)
3625 .expect("age");
3626 }
3627 assert!(TurnLock::take(&lease).expect("take").is_none());
3628 assert!(TurnLock::take(&lease).expect("take").is_some());
3629 }
3630
3631 #[test]
3632 fn an_aged_empty_lock_is_broken() {
3633 let (_tmp, a, _b) = lease_store();
3634 let lease = a.turn_path("t1");
3635 let lock = lease.with_extension("turn.lock");
3636 std::fs::create_dir_all(lock.parent().expect("dir")).expect("dir");
3637 std::fs::write(&lock, "").expect("empty lock");
3638 age_file(&lock);
3639 assert!(TurnLock::take(&lease).expect("take").is_some());
3640 }
3641
3642 #[test]
3643 fn reply_plain_text_sends_keep_the_old_wire_format() {
3644 let (tmp, talks) = store();
3645 let cfg = config(mock_agent(tmp.path(), REPLY, env("reply")));
3646 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
3647 record(&mut talk, &talks, "original", Vec::new()).expect("record");
3648 queue(&mut talk, &talks, "first", Vec::new()).expect("queue");
3649 queue(&mut talk, &talks, "second", Vec::new()).expect("queue");
3650 let wire: serde_json::Value =
3651 serde_json::from_str(&std::fs::read_to_string(talks.path_of(&talk.id)).unwrap())
3652 .unwrap();
3653 assert!(wire.get("pending_messages").is_none());
3654 assert!(wire["turns"][0].get("messages").is_none());
3655 drain(&mut talk, &talks).expect("drain");
3656 let saved = talks.get(&talk.id).expect("reload");
3657 assert_eq!(saved.turns[1].body, "first\n\nsecond");
3658 assert_eq!(saved.turns[1].breaks, Some(vec![7]));
3659 let wire: serde_json::Value =
3660 serde_json::from_str(&std::fs::read_to_string(talks.path_of(&saved.id)).unwrap())
3661 .unwrap();
3662 for turn in wire["turns"].as_array().expect("turns") {
3664 for field in turn.as_object().expect("turn").keys() {
3665 assert!(
3666 [
3667 "who",
3668 "body",
3669 "at",
3670 "attachments",
3671 "usage",
3672 "breaks",
3673 "posted_by"
3674 ]
3675 .contains(&field.as_str()),
3676 "unknown field for old readers: {field}"
3677 );
3678 }
3679 }
3680 record_reply(
3681 &mut talk,
3682 &talks,
3683 "reply",
3684 Vec::new(),
3685 Some(ReplyTarget {
3686 turn: 1,
3687 message: 1,
3688 }),
3689 )
3690 .expect("reply to reloaded plain text");
3691 assert_eq!(
3692 talk.turns[2].messages[0].reply.as_ref().unwrap().excerpt,
3693 "second"
3694 );
3695 }
3696
3697 #[tokio::test]
3698 async fn reply_image_identity_reaches_fresh_and_followup_prompts_after_reload() {
3699 let (tmp, talks) = store();
3700 let cfg = config(mock_agent(tmp.path(), ECHO, BTreeMap::new()));
3701 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
3702 let first = talks
3703 .put_attachment(&talk.id, "image/png", "first.png", b"first")
3704 .expect("first");
3705 let second = talks
3706 .put_attachment(&talk.id, "image/png", "second.png", b"second")
3707 .expect("second");
3708 let first_path = talks.attachment_path(&talk.id, &first).unwrap();
3709 let second_path = talks.attachment_path(&talk.id, &second).unwrap();
3710 queue(&mut talk, &talks, "", vec![first]).expect("queue first");
3712 queue(&mut talk, &talks, "", vec![second]).expect("queue second");
3713 drain(&mut talk, &talks).expect("drain");
3714 let lease = talks.claim_turn(&talk.id).expect("claim").expect("lease");
3715 for (message, selected, other) in [
3716 (0, &first_path, &second_path),
3717 (1, &second_path, &first_path),
3718 ] {
3719 record_reply(
3720 &mut talk,
3721 &talks,
3722 "describe this",
3723 Vec::new(),
3724 Some(ReplyTarget { turn: 0, message }),
3725 )
3726 .expect("reply");
3727 talk = talks.get(&talk.id).expect("reload");
3728 let quote = message_prompt(talk.turns.last().unwrap(), &talk, &talks);
3729 assert!(quote.contains(selected.to_str().unwrap()));
3730 assert!(!quote.contains(other.to_str().unwrap()));
3731 respond(&lease, &mut talk, &talks, &cfg, "describe this")
3732 .await
3733 .expect("respond");
3734 assert!(
3735 talk.turns
3736 .last()
3737 .unwrap()
3738 .body
3739 .contains(&format!("Replied-to image: {}", selected.display()))
3740 );
3741 }
3742 }
3743
3744 #[test]
3745 fn reply_sends_survive_queue_edit_drain_reload_and_legacy_records() {
3746 let (tmp, talks) = store();
3747 let cfg = config(mock_agent(tmp.path(), REPLY, env("reply")));
3748 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
3749 record(&mut talk, &talks, &"猫".repeat(300), Vec::new()).expect("record");
3750 talk.turns[0].messages.clear();
3752 talks.put(&mut talk).expect("legacy save");
3753 let target = ReplyTarget {
3754 turn: 0,
3755 message: 0,
3756 };
3757 queue_reply(&mut talk, &talks, "first", Vec::new(), Some(target.clone())).expect("first");
3758 queue_reply(&mut talk, &talks, "second", Vec::new(), None).expect("second");
3759 assert!(
3760 edit_pending_message(&mut talk, &talks, "edited", "first\n\nsecond", &[], Some(0))
3761 .expect("edit")
3762 );
3763 drain(&mut talk, &talks).expect("drain");
3764 let saved = talks.get(&talk.id).expect("reload");
3765 assert_eq!(saved.turns[1].body, "edited\n\nsecond");
3766 assert_eq!(saved.turns[1].messages.len(), 2);
3767 let reply = saved.turns[1].messages[0].reply.as_ref().expect("reply");
3768 assert_eq!(reply.target, target);
3769 assert_eq!(reply.excerpt, "猫".repeat(240));
3770 assert!(message_prompt(&saved.turns[1], &saved, &talks).contains("[Reply to Operator:"));
3771 assert!(transcript(&saved, &talks).contains("[Reply to Operator:"));
3772 queue_reply(
3773 &mut talk,
3774 &talks,
3775 "third",
3776 Vec::new(),
3777 Some(ReplyTarget {
3778 turn: 1,
3779 message: 1,
3780 }),
3781 )
3782 .expect("specific send");
3783 assert_eq!(
3784 talk.pending_messages[0]
3785 .reply
3786 .as_ref()
3787 .expect("reply")
3788 .excerpt,
3789 "second"
3790 );
3791 clear_pending(&mut talk, &talks).expect("clear");
3792 assert!(talk.pending_messages.is_empty());
3793 assert!(
3794 record_reply(
3795 &mut talk,
3796 &talks,
3797 "invalid",
3798 Vec::new(),
3799 Some(ReplyTarget {
3800 turn: 1,
3801 message: 2
3802 })
3803 )
3804 .is_err()
3805 );
3806 assert_eq!(talks.get(&talk.id).expect("reload").turns.len(), 2);
3807 }
3808
3809 #[tokio::test]
3810 async fn reply_quotes_reach_fresh_and_followup_prompts_without_changing_body() {
3811 let (tmp, talks) = store();
3812 let cfg = config(mock_agent(tmp.path(), ECHO, BTreeMap::new()));
3813 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
3814 record(&mut talk, &talks, "original", Vec::new()).expect("record");
3815 let target = ReplyTarget {
3816 turn: 0,
3817 message: 0,
3818 };
3819 record_reply(
3820 &mut talk,
3821 &talks,
3822 "answer",
3823 Vec::new(),
3824 Some(target.clone()),
3825 )
3826 .expect("reply");
3827 let lease = talks.claim_turn(&talk.id).expect("claim").expect("lease");
3828 respond(&lease, &mut talk, &talks, &cfg, "answer")
3829 .await
3830 .expect("respond");
3831 assert!(
3832 talk.turns
3833 .last()
3834 .expect("response")
3835 .body
3836 .contains("[Reply to Operator: original]\nanswer")
3837 );
3838 assert_eq!(talk.turns[1].body, "answer");
3839 record_reply(&mut talk, &talks, "followup", Vec::new(), Some(target)).expect("reply");
3840 respond(&lease, &mut talk, &talks, &cfg, "followup")
3841 .await
3842 .expect("respond");
3843 assert!(
3844 talk.turns
3845 .last()
3846 .expect("response")
3847 .body
3848 .contains("[Reply to Operator: original]\nfollowup")
3849 );
3850 }
3851
3852 #[test]
3853 fn queued_text_is_durable_combined_and_drained_as_one_operator_turn() {
3854 let (tmp, talks) = store();
3855 let cfg = config(mock_agent(tmp.path(), REPLY, env("reply")));
3856 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
3857
3858 queue(&mut talk, &talks, "first", Vec::new()).expect("queue first");
3859 queue(&mut talk, &talks, "second", Vec::new()).expect("queue second");
3860 let saved = talks.get(&talk.id).expect("reload queued talk");
3861 assert_eq!(saved.pending, "first\n\nsecond");
3862 assert_eq!(saved.pending_breaks, Some(vec!["first\n\n".len()]));
3863 assert!(saved.turns.is_empty(), "a draft is not a transcript turn");
3864
3865 let drained = drain(&mut talk, &talks).expect("drain");
3866 assert_eq!(drained.as_deref(), Some("first\n\nsecond"));
3867 let saved = talks.get(&talk.id).expect("reload drained talk");
3868 assert!(saved.pending.is_empty());
3869 assert_eq!(saved.turns.len(), 1);
3870 assert_eq!(saved.turns[0].body, "first\n\nsecond");
3871 assert_eq!(saved.turns[0].breaks, Some(vec!["first\n\n".len()]));
3872 assert_eq!(saved.pending_breaks, None);
3873 }
3874
3875 #[test]
3876 fn editing_a_queued_draft_preserves_its_attachments_and_rejects_a_stale_snapshot() {
3877 let (tmp, talks) = store();
3878 let cfg = config(mock_agent(tmp.path(), REPLY, env("reply")));
3879 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
3880 let attachment = Attachment {
3881 id: "a".repeat(32),
3882 name: "shot.png".to_owned(),
3883 mime: "image/png".to_owned(),
3884 bytes: 3,
3885 };
3886
3887 queue(&mut talk, &talks, "first", vec![attachment.clone()]).expect("queue");
3888 assert!(
3889 edit_pending_text(
3890 &mut talk,
3891 &talks,
3892 "corrected",
3893 "first",
3894 std::slice::from_ref(&attachment.id),
3895 )
3896 .expect("edit")
3897 );
3898 let saved = talks.get(&talk.id).expect("reload edited draft");
3899 assert_eq!(saved.pending, "corrected");
3900 assert_eq!(saved.pending_attachments, vec![attachment]);
3901
3902 queue(&mut talk, &talks, "later", Vec::new()).expect("queue concurrent draft");
3903 assert!(
3904 !edit_pending_text(
3905 &mut talk,
3906 &talks,
3907 "stale edit",
3908 "corrected",
3909 &["a".repeat(32)],
3910 )
3911 .expect("stale edit is a conflict")
3912 );
3913 assert_eq!(
3914 talks.get(&talk.id).expect("reload after conflict").pending,
3915 "corrected\n\nlater"
3916 );
3917 assert!(
3918 !clear_pending_if_matches(&mut talk, &talks, "corrected", &["a".repeat(32)])
3919 .expect("stale clear is a conflict")
3920 );
3921 assert_eq!(
3922 talks
3923 .get(&talk.id)
3924 .expect("reload after stale clear")
3925 .pending,
3926 "corrected\n\nlater"
3927 );
3928 }
3929
3930 #[tokio::test]
3931 async fn a_reply_save_preserves_pending_accepted_while_the_cli_runs() {
3932 let (tmp, talks) = store();
3933 let slow = "#!/bin/sh\ncat >/dev/null\nsleep 0.1\nprintf reply\n";
3934 let cfg = config(mock_agent(tmp.path(), slow, BTreeMap::new()));
3935 let mut running = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
3936 let id = running.id.clone();
3937 let first = record(&mut running, &talks, "first", Vec::new()).expect("record");
3938
3939 let response_talks = talks.clone();
3940 let response_cfg = cfg.clone();
3941 let reply = tokio::spawn(async move {
3942 respond(
3943 &response_talks.claim_turn(&running.id).unwrap().unwrap(),
3944 &mut running,
3945 &response_talks,
3946 &response_cfg,
3947 &first,
3948 )
3949 .await
3950 });
3951 tokio::time::sleep(std::time::Duration::from_millis(20)).await;
3952
3953 let mut queued = talks.get(&id).expect("queued handle");
3954 queue(&mut queued, &talks, "next", Vec::new()).expect("queue");
3955 reply.await.expect("join").expect("reply");
3956
3957 let saved = talks.get(&id).expect("reload");
3958 assert_eq!(saved.pending, "next");
3959 assert_eq!(saved.pending_breaks, Some(Vec::new()));
3960 assert_eq!(saved.turns.len(), 2, "operator message and reply remain");
3961 }
3962
3963 #[tokio::test]
3964 async fn posts_during_a_resumed_turn_are_replayed_once_even_after_a_reply_save_failure() {
3965 for lose_reply in [false, true] {
3966 let (tmp, talks) = store();
3967 let cfg = config(mock_agent(tmp.path(), ECHO, BTreeMap::new()));
3968 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
3969 say(
3970 &talks.claim_turn(&talk.id).unwrap().unwrap(),
3971 &mut talk,
3972 &talks,
3973 &cfg,
3974 "establish the session",
3975 Vec::new(),
3976 )
3977 .await
3978 .expect("first turn");
3979 assert!(agent::has_session(
3980 AgentKind::Command,
3981 &talk.seat,
3982 cfg.graph.sessions
3983 ));
3984
3985 post(&talks, &talk.id, "already available", "task-earlier").expect("earlier post");
3986 talk = talks.get(&talk.id).expect("reload earlier post");
3987 let ready = tmp.path().join("ready");
3988 let release = tmp.path().join("release");
3989 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";
3990 let slow_cfg = config(mock_agent(
3991 tmp.path(),
3992 slow,
3993 BTreeMap::from([
3994 ("READY".to_owned(), ready.to_string_lossy().into_owned()),
3995 ("RELEASE".to_owned(), release.to_string_lossy().into_owned()),
3996 ]),
3997 ));
3998 let text = record(&mut talk, &talks, "keep going", Vec::new()).expect("record");
3999 let prompt_turns = talk.turns.len();
4000 let id = talk.id.clone();
4001 let response_talks = talks.clone();
4002 let running = tokio::spawn(async move {
4003 respond(
4004 &response_talks.claim_turn(&talk.id).unwrap().unwrap(),
4005 &mut talk,
4006 &response_talks,
4007 &slow_cfg,
4008 &text,
4009 )
4010 .await
4011 });
4012 tokio::time::timeout(std::time::Duration::from_secs(5), async {
4013 while !ready.exists() {
4014 tokio::time::sleep(std::time::Duration::from_millis(10)).await;
4015 }
4016 })
4017 .await
4018 .expect("CLI read its prompt");
4019 post(&talks, &id, "concurrent task result", "task-one").expect("post");
4020 post(&talks, &id, "second task result", "task-two").expect("second post");
4021 if lose_reply {
4022 failpoint::force_put_failures(PUT_RETRIES);
4023 }
4024 std::fs::write(release, "go").expect("release CLI");
4025 let result = running.await.expect("join");
4026 if lose_reply {
4027 assert!(
4028 result
4029 .unwrap_err()
4030 .to_string()
4031 .contains("could not be saved")
4032 );
4033 } else {
4034 result.expect("reply");
4035 }
4036
4037 let mut saved = talks.get(&id).expect("reload");
4038 assert_eq!(saved.posts_read_through, Some(prompt_turns));
4039 assert_eq!(saved.turns[prompt_turns].body, "concurrent task result");
4040 assert_eq!(saved.turns[prompt_turns + 1].body, "second task result");
4041 assert!(posts_since_last_reply(&saved).is_some());
4042 let cfg = config(mock_agent(tmp.path(), ECHO, BTreeMap::new()));
4043 say(
4044 &talks.claim_turn(&id).unwrap().unwrap(),
4045 &mut saved,
4046 &talks,
4047 &cfg,
4048 "read the results",
4049 Vec::new(),
4050 )
4051 .await
4052 .expect("replay turn");
4053 let prompt = &saved.turns.last().unwrap().body;
4054 assert!(prompt.contains("# Posted by a task"), "{prompt}");
4055 assert!(!prompt.contains("already available"), "{prompt}");
4056 assert!(
4057 prompt
4058 .find("concurrent task result")
4059 .expect("first post in prompt")
4060 < prompt
4061 .find("second task result")
4062 .expect("second post in prompt")
4063 );
4064 let mut saved = talks.get(&id).expect("reload after replay");
4065 assert!(posts_since_last_reply(&saved).is_none());
4066 say(
4067 &talks.claim_turn(&id).unwrap().unwrap(),
4068 &mut saved,
4069 &talks,
4070 &cfg,
4071 "continue",
4072 Vec::new(),
4073 )
4074 .await
4075 .expect("next turn");
4076 assert!(!saved.turns.last().unwrap().body.contains("task result"));
4077 }
4078 }
4079
4080 fn counting_agent(dir: &Path, id: &str, body: &str) -> AgentSpec {
4083 let calls = dir.join(format!("{id}.calls"));
4084 let script = format!(
4085 "#!/bin/sh\necho x >> '{}'\n{body}\n",
4086 calls.to_string_lossy()
4087 );
4088 let path = dir.join(format!("mock-{id}.sh"));
4089 std::fs::write(&path, script).expect("write mock");
4090 AgentSpec {
4091 id: id.to_owned(),
4092 kind: AgentKind::Command,
4093 model: None,
4094 command: vec!["sh".to_owned(), path.to_string_lossy().into_owned()],
4095 extra_args: Vec::new(),
4096 env: BTreeMap::new(),
4097 prompt_delivery: None,
4098 }
4099 }
4100
4101 fn calls(dir: &Path, id: &str) -> usize {
4102 std::fs::read_to_string(dir.join(format!("{id}.calls"))).map_or(0, |s| s.lines().count())
4103 }
4104
4105 fn chain_config(specs: Vec<AgentSpec>, ids: &[&str]) -> Config {
4106 let mut cfg = config(specs[0].clone());
4107 cfg.agents = specs;
4108 cfg.roles.chatter = Some(AgentChoice::Chain(
4109 ids.iter().map(|s| (*s).to_owned()).collect(),
4110 ));
4111 cfg
4112 }
4113
4114 #[tokio::test]
4115 async fn a_chatter_chain_falls_back_resends_the_transcript_and_sticks() {
4116 let (tmp, talks) = store();
4117 let a = counting_agent(tmp.path(), "a", "cat >/dev/null\nexit 3");
4118 let b = counting_agent(tmp.path(), "b", "cat");
4119 let cfg = chain_config(vec![a, b], &["a", "b"]);
4120 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4121 assert_eq!(talk.agent, "a");
4122 post(&talks, &talk.id, "fallback task result", "task").expect("post");
4123 talk = talks.get(&talk.id).expect("reload");
4124
4125 say(
4126 &talks.claim_turn(&talk.id).unwrap().unwrap(),
4127 &mut talk,
4128 &talks,
4129 &cfg,
4130 "hello there",
4131 Vec::new(),
4132 )
4133 .await
4134 .expect("turn");
4135 assert_eq!(calls(tmp.path(), "a"), 1, "each id is tried once");
4136 assert_eq!(calls(tmp.path(), "b"), 1);
4137 assert_eq!(talk.agent, "b", "the switch persists");
4138 assert!(talks.get(&talk.id).unwrap().agent == "b");
4139 let reply = talk.turns.last().unwrap();
4140 assert!(reply.body.contains("hello there"));
4141 assert!(reply.body.contains("fallback task result"));
4142 let saved = talks.get(&talk.id).expect("reload fallback");
4143 assert_eq!(saved.posts_read_through, Some(2));
4144 assert!(posts_since_last_reply(&saved).is_none());
4145 assert!(
4146 reply.body.contains("magi task add --solo"),
4147 "a fresh seat gets the full briefing"
4148 );
4149 assert!(
4150 talk.turns
4151 .iter()
4152 .any(|t| t.body.contains("agent changed from a to b")),
4153 "the switch is noted"
4154 );
4155 }
4156
4157 #[tokio::test]
4158 async fn an_exhausted_chatter_chain_fails_like_a_single_seat_and_stays_put() {
4159 let (tmp, talks) = store();
4160 let a = counting_agent(tmp.path(), "a", "cat >/dev/null\nexit 3");
4161 let b = counting_agent(tmp.path(), "b", "cat >/dev/null\nexit 4");
4162 let cfg = chain_config(vec![a, b], &["a", "b", "a"]);
4163 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4164
4165 let err = say(
4166 &talks.claim_turn(&talk.id).unwrap().unwrap(),
4167 &mut talk,
4168 &talks,
4169 &cfg,
4170 "hi",
4171 Vec::new(),
4172 )
4173 .await
4174 .expect_err("every agent failed");
4175 assert!(err.to_string().contains("`a`"), "{err:#}");
4176 assert_eq!(calls(tmp.path(), "a"), 1);
4177 assert_eq!(calls(tmp.path(), "b"), 1);
4178 assert_eq!(talk.agent, "a", "an exhausted chain leaves the agent alone");
4179 }
4180
4181 #[test]
4182 fn a_chatter_chain_skips_an_unknown_id_at_begin() {
4183 let (tmp, talks) = store();
4184 let b = counting_agent(tmp.path(), "b", "cat");
4185 let cfg = chain_config(vec![b], &["ghost", "b"]);
4186 let talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4187 assert_eq!(talk.agent, "b");
4188 }
4189
4190 #[tokio::test]
4191 async fn an_explicit_agent_inside_the_chatter_chain_stays_pinned() {
4192 let (tmp, talks) = store();
4193 let a = counting_agent(tmp.path(), "a", "cat >/dev/null\nexit 3");
4194 let b = counting_agent(tmp.path(), "b", "cat");
4195 let cfg = chain_config(vec![a, b], &["a", "b"]);
4196 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), Some("a")).expect("begin");
4197 say(
4198 &talks.claim_turn(&talk.id).unwrap().unwrap(),
4199 &mut talk,
4200 &talks,
4201 &cfg,
4202 "hi",
4203 Vec::new(),
4204 )
4205 .await
4206 .expect_err("a alone, and it fails");
4207 assert_eq!(calls(tmp.path(), "b"), 0);
4208 assert_eq!(talk.agent, "a");
4209 }
4210
4211 #[tokio::test]
4212 async fn an_explicit_agent_does_not_borrow_the_chatter_chain() {
4213 let (tmp, talks) = store();
4214 let a = counting_agent(tmp.path(), "a", "cat >/dev/null\nexit 3");
4215 let b = counting_agent(tmp.path(), "b", "cat");
4216 let c = counting_agent(tmp.path(), "c", "cat >/dev/null\nexit 3");
4217 let cfg = chain_config(vec![a, b, c], &["a", "b"]);
4218 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), Some("c")).expect("begin");
4219 say(
4220 &talks.claim_turn(&talk.id).unwrap().unwrap(),
4221 &mut talk,
4222 &talks,
4223 &cfg,
4224 "hi",
4225 Vec::new(),
4226 )
4227 .await
4228 .expect_err("c alone, and it fails");
4229 assert_eq!(calls(tmp.path(), "b"), 0);
4230 }
4231
4232 #[test]
4233 fn briefing_names_the_operator_with_or_without_a_persona() {
4234 let plain = briefing(Path::new("/repo"), "en", false);
4235 let named = briefing_with(Path::new("/repo"), "en", false, None, Some("Commander"));
4236 assert!(named.starts_with(&plain));
4237 assert!(named.contains("# Addressing the operator"));
4238 assert!(named.contains("\"Commander\""));
4239 let rei = crate::persona::builtin_catalog()
4240 .into_iter()
4241 .find(|p| p.id == "rei")
4242 .expect("rei");
4243 let with = briefing_with(
4244 Path::new("/repo"),
4245 "en",
4246 false,
4247 Some(&rei),
4248 Some("Commander"),
4249 );
4250 assert!(with.contains("\"Commander\""));
4251 assert!(!with.contains("# Addressing the operator"));
4252 }
4253
4254 #[test]
4255 fn briefing_carries_a_persona_section_only_when_one_is_chosen() {
4256 let plain = briefing(Path::new("/repo"), "en", false);
4257 assert_eq!(
4258 plain,
4259 briefing_with(Path::new("/repo"), "en", false, None, None)
4260 );
4261 assert!(!plain.contains("Persona"));
4262 let rei = crate::persona::builtin_catalog()
4263 .into_iter()
4264 .find(|p| p.id == "rei")
4265 .expect("rei");
4266 let with = briefing_with(Path::new("/repo"), "en", false, Some(&rei), None);
4267 assert!(with.starts_with(&plain), "the plain briefing is untouched");
4268 assert!(with.contains("# Persona (tone only)"));
4269 assert!(with.contains("TONE ONLY"));
4270 assert!(with.contains("task ids"));
4271 assert!(with.contains("write policy"));
4272 assert!(with.contains("`magi task add`"));
4273 assert!(with.contains("Rei Ayanami"));
4274 }
4275
4276 #[test]
4277 fn a_talk_written_before_personas_still_loads() {
4278 let (tmp, talks) = store();
4279 let spec = mock_agent(tmp.path(), ECHO, BTreeMap::new());
4280 let cfg = config(spec);
4281 let talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4282 let path = talks.root.join(format!("{}.json", talk.id));
4283 let mut v: serde_json::Value =
4284 serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
4285 v.as_object_mut().unwrap().remove("persona");
4286 v.as_object_mut().unwrap().remove("persona_dirty");
4287 std::fs::write(&path, v.to_string()).unwrap();
4288 let loaded = talks.get(&talk.id).expect("old record loads");
4289 assert_eq!(loaded.persona, "");
4290 assert!(!loaded.persona_dirty);
4291 }
4292
4293 #[test]
4294 fn the_briefing_files_with_solo_or_the_chosen_implementer_count() {
4295 let repo = Path::new("/repo");
4296 let solo = briefing_for(repo, "", false, None, None, 1);
4297 assert_eq!(solo, briefing(repo, "", false));
4298 assert!(solo.contains("magi task add --solo --repo"));
4299 assert!(solo.contains("magi task add --solo --attach"));
4300 for n in [2u8, 3] {
4301 let b = briefing_for(repo, "", false, None, None, n);
4302 assert!(
4303 b.contains(&format!("magi task add --implementers {n} --repo")),
4304 "{b}"
4305 );
4306 assert!(b.contains(&format!("magi task add --implementers {n} --attach")));
4307 assert!(!b.contains("task add --solo"), "{b}");
4308 assert!(!b.contains("Use --solo"), "{b}");
4309 }
4310 }
4311
4312 #[test]
4313 fn begin_with_applies_remembered_choices_and_drops_unfit_ones_alone() {
4314 let (tmp, talks) = store();
4315 let first = mock_agent(tmp.path(), ECHO, BTreeMap::new());
4316 let mut second = first.clone();
4317 second.id = "second".to_owned();
4318 let mut cfg = config(first.clone());
4319 cfg.agents.push(second.clone());
4320 let open = |p: &Preferred| {
4321 begin_with(&talks, &cfg, tmp.path().to_owned(), None, p).expect("begin")
4322 };
4323
4324 let talk = open(&Preferred {
4325 agent: Some("second".into()),
4326 persona: Some("rei".into()),
4327 implementers: Some(i64::from(check_implementers(3, &cfg).unwrap_or(1))),
4328 });
4329 assert_eq!(talk.agent, "second");
4330 assert!(
4331 !talk.fallback,
4332 "a remembered non-head agent is an explicit choice"
4333 );
4334 assert_eq!(talk.persona, "rei");
4335 assert_eq!(talk.implementers, check_implementers(3, &cfg).unwrap_or(1));
4336 assert!(!talk.persona_dirty && !talk.implementers_dirty);
4337
4338 let head = open(&Preferred {
4340 agent: Some(first.id.clone()),
4341 ..Preferred::default()
4342 });
4343 assert!(head.fallback);
4344
4345 for implementers in [0, 4, -1, 1000] {
4347 let t = open(&Preferred {
4348 agent: Some("gone".into()),
4349 persona: Some("no-such-persona".into()),
4350 implementers: Some(implementers),
4351 });
4352 assert_eq!(t.agent, first.id);
4353 assert!(t.fallback);
4354 assert_eq!(t.persona, "");
4355 assert_eq!(t.implementers, 1);
4356 }
4357
4358 let t = open(&Preferred {
4360 agent: Some("second".into()),
4361 persona: Some("default".into()),
4362 implementers: Some(9),
4363 });
4364 assert_eq!(
4365 (t.agent.as_str(), t.persona.as_str(), t.implementers),
4366 ("second", "", 1)
4367 );
4368
4369 let strict = begin_with(
4371 &talks,
4372 &cfg,
4373 tmp.path().to_owned(),
4374 Some("first-unknown"),
4375 &Preferred {
4376 agent: Some("second".into()),
4377 ..Preferred::default()
4378 },
4379 );
4380 assert!(strict.is_err());
4381 }
4382
4383 #[test]
4384 fn remembered_agent_can_open_when_the_chatter_chain_cannot_resolve() {
4385 let (tmp, talks) = store();
4386 let spec = mock_agent(tmp.path(), ECHO, BTreeMap::new());
4387 let cfg = chain_config(vec![spec.clone()], &["missing-chatter"]);
4390 assert!(begin(&talks, &cfg, tmp.path().to_owned(), None).is_err());
4391 let talk = begin_with(
4392 &talks,
4393 &cfg,
4394 tmp.path().to_owned(),
4395 None,
4396 &Preferred {
4397 agent: Some(spec.id.clone()),
4398 ..Preferred::default()
4399 },
4400 )
4401 .expect("a valid remembered agent does not require a default chain");
4402 assert_eq!(talk.agent, spec.id);
4403 assert!(!talk.fallback);
4404 assert_eq!(talks.get(&talk.id).unwrap().agent, spec.id);
4405 assert!(
4406 begin_with(
4407 &talks,
4408 &cfg,
4409 tmp.path().to_owned(),
4410 None,
4411 &Preferred {
4412 agent: Some("missing-preference".into()),
4413 ..Preferred::default()
4414 },
4415 )
4416 .is_err()
4417 );
4418 }
4419
4420 #[test]
4421 fn implementers_are_validated_and_old_records_load_as_solo() {
4422 let (tmp, talks) = store();
4423 let cfg = config(mock_agent(tmp.path(), ECHO, BTreeMap::new()));
4424 assert_eq!(check_implementers(1, &cfg), Ok(1));
4425 assert_eq!(check_implementers(3, &cfg), Ok(3));
4426 assert!(check_implementers(0, &cfg).is_err());
4427 assert!(check_implementers(4, &cfg).is_err());
4428 let mut empty = cfg.clone();
4429 empty.agents.clear();
4430 assert!(check_implementers(2, &empty).is_err());
4431
4432 let talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4433 let path = talks.path_of(&talk.id);
4434 let mut v: serde_json::Value =
4435 serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
4436 v.as_object_mut().unwrap().remove("implementers");
4437 v.as_object_mut().unwrap().remove("implementers_dirty");
4438 std::fs::write(&path, v.to_string()).unwrap();
4439 let loaded = talks.get(&talk.id).expect("load");
4440 assert_eq!(loaded.implementers, 1);
4441 assert!(!loaded.implementers_dirty);
4442 }
4443
4444 #[tokio::test]
4445 async fn an_implementers_switch_is_noted_once_and_kept_across_a_failed_turn() {
4446 let (tmp, talks) = store();
4447 let spec = mock_agent(tmp.path(), ECHO, BTreeMap::new());
4448 let cfg = config(spec);
4449 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4450 let lease = talks.claim_turn(&talk.id).unwrap().unwrap();
4451 say(&lease, &mut talk, &talks, &cfg, "hello", Vec::new())
4452 .await
4453 .expect("first turn");
4454
4455 assert!(switch_implementers(&mut talk, &talks, 2).expect("switch"));
4456 assert!(!switch_implementers(&mut talk, &talks, 2).expect("same"));
4457 assert!(talk.implementers_dirty);
4458 say(&lease, &mut talk, &talks, &cfg, "next", Vec::new())
4459 .await
4460 .expect("turn");
4461 let prompt = &talk.turns.last().unwrap().body;
4462 assert!(prompt.contains("# Task filing update"), "{prompt}");
4463 assert!(prompt.contains("--implementers 2"));
4464 assert!(!talk.implementers_dirty, "cleared after a successful turn");
4465
4466 say(&lease, &mut talk, &talks, &cfg, "again", Vec::new())
4467 .await
4468 .expect("turn");
4469 assert!(
4470 !talk
4471 .turns
4472 .last()
4473 .unwrap()
4474 .body
4475 .contains("# Task filing update")
4476 );
4477
4478 let mut no_sessions = cfg.clone();
4480 no_sessions.graph.sessions = false;
4481 say(&lease, &mut talk, &talks, &no_sessions, "one", Vec::new())
4482 .await
4483 .expect("turn");
4484 say(&lease, &mut talk, &talks, &no_sessions, "two", Vec::new())
4485 .await
4486 .expect("turn");
4487 assert!(talk.turns.last().unwrap().body.contains("--implementers 2"));
4488 }
4489
4490 #[tokio::test]
4491 async fn a_persona_switch_notes_marks_dirty_and_updates_the_next_turn_once() {
4492 let (tmp, talks) = store();
4493 let spec = mock_agent(tmp.path(), ECHO, BTreeMap::new());
4494 let cfg = config(spec);
4495 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4496 let lease = talks.claim_turn(&talk.id).unwrap().unwrap();
4497 say(&lease, &mut talk, &talks, &cfg, "hello", Vec::new())
4498 .await
4499 .expect("first turn");
4500 assert!(!talk.turns[1].body.contains("Persona"));
4501
4502 assert!(switch_persona(&mut talk, &talks, "misato").expect("switch"));
4503 assert!(!switch_persona(&mut talk, &talks, "misato").expect("same"));
4504 assert!(talk.persona_dirty);
4505 assert!(talk.turns.last().unwrap().body.contains("persona changed"));
4506
4507 say(&lease, &mut talk, &talks, &cfg, "next", Vec::new())
4508 .await
4509 .expect("turn");
4510 let prompt = &talk.turns.last().unwrap().body;
4511 assert!(prompt.contains("# Persona update"), "{prompt}");
4512 assert!(prompt.contains("Misato Katsuragi"));
4513 assert!(!talk.persona_dirty, "cleared after a successful turn");
4514
4515 say(&lease, &mut talk, &talks, &cfg, "again", Vec::new())
4516 .await
4517 .expect("turn");
4518 assert!(!talk.turns.last().unwrap().body.contains("# Persona update"));
4519
4520 assert!(switch_persona(&mut talk, &talks, "default").expect("back"));
4521 assert_eq!(talk.persona, "");
4522 say(&lease, &mut talk, &talks, &cfg, "plain", Vec::new())
4523 .await
4524 .expect("turn");
4525 assert!(
4526 talk.turns
4527 .last()
4528 .unwrap()
4529 .body
4530 .contains("turned the persona off")
4531 );
4532
4533 assert!(switch_persona(&mut talk, &talks, "rei").expect("rei"));
4535 let mut no_sessions = cfg.clone();
4536 no_sessions.graph.sessions = false;
4537 say(&lease, &mut talk, &talks, &no_sessions, "one", Vec::new())
4538 .await
4539 .expect("turn");
4540 say(&lease, &mut talk, &talks, &no_sessions, "two", Vec::new())
4541 .await
4542 .expect("turn");
4543 let last = &talk.turns.last().unwrap().body;
4544 assert!(!talk.persona_dirty);
4545 assert!(last.contains("# Persona (tone only)"), "{last}");
4546 assert!(last.contains("Rei Ayanami"));
4547 }
4548
4549 #[tokio::test]
4550 async fn the_first_turn_carries_the_briefing_and_later_turns_do_not() {
4551 let (tmp, talks) = store();
4552 let spec = mock_agent(tmp.path(), ECHO, BTreeMap::new());
4553 let cfg = config(spec);
4554 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4555
4556 say(
4557 &talks.claim_turn(&talk.id).unwrap().unwrap(),
4558 &mut talk,
4559 &talks,
4560 &cfg,
4561 "what does the queue module do?",
4562 Vec::new(),
4563 )
4564 .await
4565 .expect("first turn");
4566 let first_prompt = &talk.turns[1].body;
4567 assert!(first_prompt.contains("magi task add --solo"));
4568 assert!(first_prompt.contains("what does the queue module do?"));
4569
4570 say(
4571 &talks.claim_turn(&talk.id).unwrap().unwrap(),
4572 &mut talk,
4573 &talks,
4574 &cfg,
4575 "and how is it locked?",
4576 Vec::new(),
4577 )
4578 .await
4579 .expect("second turn");
4580 let second_prompt = &talk.turns[3].body;
4581 assert!(
4582 !second_prompt.contains("magi task add --solo"),
4583 "the briefing is sent once, not on every turn: {second_prompt}"
4584 );
4585 assert!(second_prompt.contains("and how is it locked?"));
4586 }
4587
4588 #[tokio::test]
4589 async fn switching_agent_resets_the_seat_notes_it_and_resends_the_transcript() {
4590 let (tmp, talks) = store();
4591 let a = mock_agent(tmp.path(), ECHO, BTreeMap::new());
4592 let mut b = a.clone();
4593 b.id = "other".to_owned();
4594 let mut cfg = config(a.clone());
4595 cfg.agents.push(b.clone());
4596 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), Some(&a.id)).expect("begin");
4597 say(
4598 &talks.claim_turn(&talk.id).unwrap().unwrap(),
4599 &mut talk,
4600 &talks,
4601 &cfg,
4602 "remember the walrus",
4603 Vec::new(),
4604 )
4605 .await
4606 .expect("first turn");
4607 let old_session = talk.seat.claude_session.clone();
4608 assert_eq!(talk.seat.turns, 1);
4609
4610 assert!(switch_agent(&mut talk, &talks, &b).expect("switch"));
4611 assert_eq!(talk.agent, "other");
4612 assert_eq!(talk.seat.turns, 0);
4613 assert_eq!(talk.seat.agent, "other");
4614 assert_ne!(talk.seat.claude_session, old_session);
4615 let note = talk.turns.last().expect("note");
4616 assert_eq!(note.who, Who::Agent);
4617 assert!(note.body.starts_with(MAGI_NOTE), "{}", note.body);
4618 assert!(note.body.contains("changed from"), "{}", note.body);
4619 assert_eq!(talks.get(&talk.id).expect("reload").agent, "other");
4620
4621 let before = talk.turns.len();
4622 assert!(!switch_agent(&mut talk, &talks, &b).expect("same agent"));
4623 assert_eq!(talk.turns.len(), before, "a no-op writes no note");
4624
4625 say(
4626 &talks.claim_turn(&talk.id).unwrap().unwrap(),
4627 &mut talk,
4628 &talks,
4629 &cfg,
4630 "what did I say?",
4631 Vec::new(),
4632 )
4633 .await
4634 .expect("turn after switch");
4635 let prompt = &talk.turns.last().expect("reply").body;
4636 assert!(prompt.contains("remember the walrus"), "{prompt}");
4637 assert!(prompt.contains("## magi"), "{prompt}");
4638 assert!(prompt.contains("what did I say?"), "{prompt}");
4639 }
4640
4641 #[tokio::test]
4642 async fn say_appends_the_operator_turn_then_the_agent_turn() {
4643 let (tmp, talks) = store();
4644 let spec = mock_agent(tmp.path(), REPLY, env("go ahead"));
4645 let cfg = config(spec);
4646 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4647
4648 say(
4649 &talks.claim_turn(&talk.id).unwrap().unwrap(),
4650 &mut talk,
4651 &talks,
4652 &cfg,
4653 "can I rename this function?",
4654 Vec::new(),
4655 )
4656 .await
4657 .expect("say");
4658
4659 assert_eq!(talk.turns.len(), 2);
4660 assert_eq!(talk.turns[0].who, Who::Operator);
4661 assert_eq!(talk.turns[0].body, "can I rename this function?");
4662 assert_eq!(talk.turns[1].who, Who::Agent);
4663 assert_eq!(talk.turns[1].body, "go ahead");
4664 assert_eq!(talks.get(&talk.id).expect("get").turns, talk.turns);
4665 }
4666
4667 #[tokio::test]
4668 async fn a_failed_turn_keeps_the_operator_message_and_says_what_happened() {
4669 let (tmp, talks) = store();
4670 let spec = mock_agent(tmp.path(), BROKEN, BTreeMap::new());
4671 let cfg = config(spec);
4672 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4673
4674 talk.posts_read_through = None;
4675 talks.put(&mut talk).expect("save old-format boundary");
4676 post(&talks, &talk.id, "unread task result", "task").expect("post");
4677 talk = talks.get(&talk.id).expect("reload");
4678
4679 let err = say(
4680 &talks.claim_turn(&talk.id).unwrap().unwrap(),
4681 &mut talk,
4682 &talks,
4683 &cfg,
4684 "check the tests",
4685 Vec::new(),
4686 )
4687 .await
4688 .expect_err("a turn with no answer is an error");
4689 assert!(err.to_string().contains("no answer"), "{err}");
4690
4691 let on_disk = talks.get(&talk.id).expect("get");
4692 assert_eq!(on_disk.turns.len(), 3);
4693 assert_eq!(on_disk.posts_read_through, Some(0));
4694 assert!(
4695 posts_since_last_reply(&on_disk)
4696 .unwrap()
4697 .contains("unread task result")
4698 );
4699 assert_eq!(on_disk.turns[1].body, "check the tests");
4700 let note = &on_disk.turns[2];
4701 assert_eq!(note.who, Who::Agent);
4702 assert!(note.body.starts_with(MAGI_NOTE), "{}", note.body);
4703 assert!(note.body.contains("your message is saved"));
4704 }
4705
4706 #[tokio::test]
4712 async fn a_passing_write_failure_while_saving_the_reply_does_not_lose_it() {
4713 let (tmp, talks) = store();
4714 let spec = mock_agent(tmp.path(), REPLY, env("go ahead"));
4715 let cfg = config(spec);
4716 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4717
4718 let text =
4719 record(&mut talk, &talks, "can I rename this function?", Vec::new()).expect("record");
4720 failpoint::force_put_failures(PUT_RETRIES - 1);
4723 respond(
4724 &talks.claim_turn(&talk.id).unwrap().unwrap(),
4725 &mut talk,
4726 &talks,
4727 &cfg,
4728 &text,
4729 )
4730 .await
4731 .expect("respond must survive a write failure its own retries can outlast");
4732
4733 assert_eq!(talk.turns.len(), 2);
4734 assert_eq!(talk.turns[1].who, Who::Agent);
4735 assert_eq!(talk.turns[1].body, "go ahead");
4736 let on_disk = talks.get(&talk.id).expect("get");
4737 assert_eq!(
4738 on_disk.turns, talk.turns,
4739 "the reply must reach disk despite the early write failures"
4740 );
4741 }
4742
4743 #[tokio::test]
4749 async fn a_persistent_write_failure_while_saving_the_reply_is_never_silent() {
4750 let (tmp, talks) = store();
4751 let spec = mock_agent(tmp.path(), REPLY, env("go ahead"));
4752 let cfg = config(spec);
4753 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4754
4755 let text = record(&mut talk, &talks, "check the tests", Vec::new()).expect("record");
4756 failpoint::force_put_failures(PUT_RETRIES);
4761 let err = respond(
4762 &talks.claim_turn(&talk.id).unwrap().unwrap(),
4763 &mut talk,
4764 &talks,
4765 &cfg,
4766 &text,
4767 )
4768 .await
4769 .expect_err("a reply that cannot be saved must be reported, not swallowed");
4770 assert!(err.to_string().contains("could not be saved"), "{err}");
4771
4772 let on_disk = talks.get(&talk.id).expect("get");
4773 assert_eq!(
4774 on_disk.turns.len(),
4775 2,
4776 "the operator turn plus a visible note"
4777 );
4778 assert_eq!(on_disk.turns[0].body, "check the tests");
4779 let note = &on_disk.turns[1];
4780 assert_eq!(note.who, Who::Agent);
4781 assert!(note.body.starts_with(MAGI_NOTE), "{}", note.body);
4782 assert!(
4783 note.body.contains("could not be saved"),
4784 "the operator must be told the reply is missing, not left staring \
4785 at a gap with no explanation: {}",
4786 note.body
4787 );
4788 assert_eq!(
4789 talk.turns, on_disk.turns,
4790 "the in-memory talk must match what actually landed on disk"
4791 );
4792
4793 let artifacts = talks.artifacts_of(&talk.id);
4796 let stash = std::fs::read_dir(&artifacts)
4797 .expect("artifacts dir")
4798 .filter_map(|e| e.ok())
4799 .find(|e| e.file_name().to_string_lossy().ends_with("-lost.txt"))
4800 .expect("a stash file for the lost reply");
4801 let stashed = std::fs::read_to_string(stash.path()).expect("read stash");
4802 assert_eq!(stashed, "go ahead");
4803
4804 assert_eq!(
4812 on_disk.seat.turns, 1,
4813 "the note's write must carry the turn the CLI actually took"
4814 );
4815 assert_eq!(
4816 on_disk.seat.claude_session, talk.seat.claude_session,
4817 "the session id handed to the CLI must survive the failed reply"
4818 );
4819 assert_eq!(on_disk.seat.captured_session, talk.seat.captured_session);
4820 assert!(
4821 agent::has_session(AgentKind::Command, &on_disk.seat, cfg.graph.sessions),
4822 "the next turn must resume, not open the same session id twice"
4823 );
4824 }
4825
4826 #[tokio::test]
4831 async fn a_write_failure_that_also_loses_the_note_still_reports_it() {
4832 let (tmp, talks) = store();
4833 let spec = mock_agent(tmp.path(), REPLY, env("go ahead"));
4834 let cfg = config(spec);
4835 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4836
4837 let text = record(&mut talk, &talks, "check the tests", Vec::new()).expect("record");
4838 failpoint::force_put_failures(PUT_RETRIES * 2);
4841 let err = respond(
4842 &talks.claim_turn(&talk.id).unwrap().unwrap(),
4843 &mut talk,
4844 &talks,
4845 &cfg,
4846 &text,
4847 )
4848 .await
4849 .expect_err("neither the reply nor the note could be saved");
4850 assert!(err.to_string().contains("could not be saved"), "{err}");
4851
4852 assert_eq!(talk.turns.len(), 1, "only the operator's own turn");
4853 let on_disk = talks.get(&talk.id).expect("get");
4854 assert_eq!(on_disk.turns.len(), 1);
4855
4856 assert_eq!(
4866 on_disk.seat.turns, 0,
4867 "an unwritable file cannot record the turn the CLI took"
4868 );
4869 assert_eq!(
4870 talk.seat.turns, 1,
4871 "the in-memory seat still reports the turn the CLI actually took"
4872 );
4873 assert_eq!(
4874 on_disk.seat.claude_session, talk.seat.claude_session,
4875 "the session id was minted at `begin` and never changes here"
4876 );
4877 }
4878
4879 #[tokio::test]
4883 async fn attachments_reach_the_prompt_and_an_empty_body_is_still_a_turn() {
4884 let (tmp, talks) = store();
4885 let spec = mock_agent(tmp.path(), ECHO, BTreeMap::new());
4886 let cfg = config(spec);
4887 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4888
4889 let att = talks
4890 .put_attachment(
4891 &talk.id,
4892 "image/png",
4893 "screenshot.png",
4894 b"pretend-png-bytes",
4895 )
4896 .expect("put attachment");
4897
4898 say(
4899 &talks.claim_turn(&talk.id).unwrap().unwrap(),
4900 &mut talk,
4901 &talks,
4902 &cfg,
4903 "",
4904 vec![att.clone()],
4905 )
4906 .await
4907 .expect("an empty body with an attachment is still a turn");
4908
4909 let operator_turn = &talk.turns[0];
4910 assert_eq!(operator_turn.who, Who::Operator);
4911 assert_eq!(operator_turn.body, "");
4912 assert_eq!(operator_turn.attachments, vec![att.clone()]);
4913
4914 let prompt = &talk.turns[1].body;
4915 let expected_path = talks
4916 .attachments_dir(&talk.id)
4917 .join(format!("{}.png", att.id));
4918 assert!(
4919 prompt.contains(&expected_path.display().to_string()),
4920 "the agent must be told the attachment's absolute path: {prompt}"
4921 );
4922 assert!(prompt.contains("image/png"), "and its mime: {prompt}");
4923 }
4924
4925 #[test]
4934 fn attachment_path_is_absolute_even_when_the_store_root_is_relative() {
4935 let talks = Talks::at(PathBuf::from("relative-talks-root-for-this-test"));
4936 let att = Attachment {
4937 id: "0".repeat(32),
4938 name: "shot.png".to_owned(),
4939 mime: "image/png".to_owned(),
4940 bytes: 3,
4941 };
4942 let path = talks
4943 .attachment_path("some-talk-id", &att)
4944 .expect("a supported mime always yields a path");
4945 assert!(
4946 path.is_absolute(),
4947 "must be absolute even off a relative store root: {}",
4948 path.display()
4949 );
4950 }
4951
4952 #[tokio::test]
4953 async fn a_turn_past_the_configured_talk_timeout_is_reported_with_that_timeout() {
4954 let (tmp, talks) = store();
4959 let slow = mock_agent(
4960 tmp.path(),
4961 "#!/bin/sh\ncat >/dev/null\nsleep 2\n",
4962 BTreeMap::new(),
4963 );
4964 let mut cfg = config(slow);
4965 cfg.graph.timeout_talk = 1;
4966 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4967
4968 let err = say(
4969 &talks.claim_turn(&talk.id).unwrap().unwrap(),
4970 &mut talk,
4971 &talks,
4972 &cfg,
4973 "check the tests",
4974 Vec::new(),
4975 )
4976 .await
4977 .expect_err("a turn that never answers is an error");
4978 assert!(
4979 err.to_string().contains("did not answer within 1s"),
4980 "{err}"
4981 );
4982
4983 let on_disk = talks.get(&talk.id).expect("get");
4984 let note = on_disk.turns.last().expect("a note turn was recorded");
4985 assert!(
4986 note.body.contains("did not answer within 1s"),
4987 "the transcript must show the configured timeout: {}",
4988 note.body
4989 );
4990 }
4991
4992 #[test]
4993 fn closing_is_idempotent_and_a_closed_talk_takes_no_more_turns() {
4994 let (tmp, talks) = store();
4995 let spec = mock_agent(tmp.path(), REPLY, env("hi"));
4996 let cfg = config(spec);
4997 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4998
4999 close(&mut talk, &talks).expect("close");
5000 assert_eq!(talk.status, TalkStatus::Closed);
5001 close(&mut talk, &talks).expect("closing twice is not an error");
5002
5003 let err =
5004 record(&mut talk, &talks, "still there?", Vec::new()).expect_err("closed talks refuse");
5005 assert!(err.to_string().contains("closed"));
5006 let _ = &cfg; }
5008
5009 #[tokio::test]
5010 async fn a_close_that_lands_while_a_turn_is_in_flight_is_not_undone_by_the_reply() {
5011 let (tmp, talks) = store();
5012 let spec = mock_agent(tmp.path(), REPLY, env("here you go"));
5013 let cfg = config(spec);
5014 let mut in_flight = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
5017
5018 let mut closed_elsewhere = talks.get(&in_flight.id).expect("reread");
5022 close(&mut closed_elsewhere, &talks).expect("close");
5023 assert_eq!(
5024 talks.get(&in_flight.id).expect("reread").status,
5025 TalkStatus::Closed,
5026 "the close landed on disk before the turn finished"
5027 );
5028
5029 assert_eq!(in_flight.status, TalkStatus::Open);
5033 respond(
5034 &talks.claim_turn(&in_flight.id).unwrap().unwrap(),
5035 &mut in_flight,
5036 &talks,
5037 &cfg,
5038 "one more question",
5039 )
5040 .await
5041 .expect("the turn itself still completes");
5042
5043 let on_disk = talks.get(&in_flight.id).expect("reread");
5044 assert_eq!(
5045 on_disk.status,
5046 TalkStatus::Closed,
5047 "a close must stick even when a turn that started before it finishes after it"
5048 );
5049 assert!(
5052 on_disk.turns.iter().any(|t| t.body == "here you go"),
5053 "the in-flight turn's own reply is still recorded: {:?}",
5054 on_disk.turns
5055 );
5056 }
5057
5058 #[test]
5059 fn a_close_that_lands_before_record_is_called_is_not_undone_by_it() {
5060 let (tmp, talks) = store();
5061 let spec = mock_agent(tmp.path(), REPLY, env("hi"));
5062 let cfg = config(spec);
5063 let mut stale = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
5066
5067 let mut closed_elsewhere = talks.get(&stale.id).expect("reread");
5070 close(&mut closed_elsewhere, &talks).expect("close");
5071 assert_eq!(
5072 talks.get(&stale.id).expect("reread").status,
5073 TalkStatus::Closed,
5074 "the close landed on disk before record was called"
5075 );
5076
5077 assert_eq!(stale.status, TalkStatus::Open);
5081 let err = record(&mut stale, &talks, "still there?", Vec::new())
5082 .expect_err("a close that landed first must be honored, not overwritten");
5083 assert!(err.to_string().contains("closed"));
5084
5085 let on_disk = talks.get(&stale.id).expect("reread");
5086 assert_eq!(
5087 on_disk.status,
5088 TalkStatus::Closed,
5089 "record must not resurrect a conversation closed while its snapshot was stale"
5090 );
5091 assert!(
5092 on_disk.turns.is_empty(),
5093 "the rejected turn must not have been appended: {:?}",
5094 on_disk.turns
5095 );
5096 let _ = &cfg; }
5098
5099 #[test]
5100 fn close_blocks_on_records_guard_rather_than_interleaving_with_it() {
5101 let (tmp, talks) = store();
5102 let spec = mock_agent(tmp.path(), REPLY, env("hi"));
5103 let cfg = config(spec);
5104 let talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
5105
5106 let held = talks.guard().unwrap();
5110
5111 let talks2 = talks.clone();
5112 let id = talk.id.clone();
5113 let closing = std::thread::spawn(move || {
5114 let mut talk = talks2.get(&id).expect("get");
5115 close(&mut talk, &talks2).expect("close");
5116 });
5117
5118 std::thread::sleep(Duration::from_millis(50));
5119 assert!(
5120 !closing.is_finished(),
5121 "close must wait for the guard, not read and write while it is held - \
5122 a re-read alone narrows this window without closing it"
5123 );
5124
5125 drop(held);
5126 closing.join().expect("close thread panicked");
5127
5128 assert_eq!(
5129 talks.get(&talk.id).expect("reread").status,
5130 TalkStatus::Closed,
5131 "once the guard is free, close still lands"
5132 );
5133 let _ = &cfg; }
5135
5136 #[test]
5137 fn reopening_a_closed_talk_lets_it_take_turns_again_and_reopening_twice_is_not_an_error() {
5138 let (tmp, talks) = store();
5139 let spec = mock_agent(tmp.path(), REPLY, env("hi"));
5140 let cfg = config(spec);
5141 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
5142
5143 close(&mut talk, &talks).expect("close");
5144 assert_eq!(talk.status, TalkStatus::Closed);
5145
5146 reopen(&mut talk, &talks).expect("reopen");
5147 assert_eq!(talk.status, TalkStatus::Open);
5148 assert_eq!(
5149 talks.get(&talk.id).expect("reread").status,
5150 TalkStatus::Open
5151 );
5152
5153 reopen(&mut talk, &talks).expect("reopening an open talk is not an error");
5155 assert_eq!(talk.status, TalkStatus::Open);
5156
5157 record(&mut talk, &talks, "one more thing", Vec::new())
5158 .expect("a reopened talk takes turns again");
5159 let _ = &cfg; }
5161
5162 #[test]
5163 fn removing_a_talk_deletes_its_record_and_artifacts_and_refuses_an_unknown_id() {
5164 let (tmp, talks) = store();
5165 let spec = mock_agent(tmp.path(), REPLY, env("hi"));
5166 let cfg = config(spec);
5167 let talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
5168
5169 let artifacts = talks.artifacts_of(&talk.id);
5170 std::fs::create_dir_all(&artifacts).expect("create artifacts dir");
5171 std::fs::write(artifacts.join("turn-1.txt"), "hello").expect("write artifact");
5172
5173 talks.remove(&talk.id).expect("remove");
5174 assert!(!talks.path_of(&talk.id).is_file(), "the record is gone");
5175 assert!(!artifacts.is_dir(), "the artifacts directory is gone");
5176 assert!(
5177 talks.get(&talk.id).is_err(),
5178 "a removed talk cannot be read back"
5179 );
5180
5181 let err = talks
5182 .remove("nonexistent-id")
5183 .expect_err("unknown id refused");
5184 assert!(err.to_string().contains("no talk matches"), "{err}");
5185 let _ = &cfg; }
5187
5188 #[tokio::test]
5189 async fn a_delete_that_lands_while_a_turn_is_in_flight_is_not_undone_by_the_reply() {
5190 let (tmp, talks) = store();
5191 let spec = mock_agent(tmp.path(), REPLY, env("here you go"));
5192 let cfg = config(spec);
5193 let mut in_flight = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
5196
5197 talks.remove(&in_flight.id).expect("remove");
5198 assert!(
5199 talks.get(&in_flight.id).is_err(),
5200 "the delete landed on disk before the turn finished"
5201 );
5202
5203 respond(
5206 &talks.claim_turn(&in_flight.id).unwrap().unwrap(),
5207 &mut in_flight,
5208 &talks,
5209 &cfg,
5210 "one more question",
5211 )
5212 .await
5213 .expect("the turn itself still completes rather than erroring");
5214
5215 assert!(
5216 talks.get(&in_flight.id).is_err(),
5217 "a delete must stick even when a turn that started before it finishes after it"
5218 );
5219 }
5220
5221 #[test]
5222 fn a_delete_that_lands_before_record_is_called_is_not_undone_by_it() {
5223 let (tmp, talks) = store();
5224 let spec = mock_agent(tmp.path(), REPLY, env("hi"));
5225 let cfg = config(spec);
5226 let mut stale = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
5229
5230 talks.remove(&stale.id).expect("remove");
5231
5232 let err = record(&mut stale, &talks, "still there?", Vec::new())
5236 .expect_err("a delete that landed first must be honored, not overwritten");
5237 assert!(err.to_string().contains("deleted"), "{err}");
5238
5239 assert!(
5240 talks.get(&stale.id).is_err(),
5241 "record must not resurrect a conversation deleted while its snapshot was stale"
5242 );
5243 let _ = &cfg; }
5245
5246 #[test]
5247 fn a_delete_that_lands_before_close_is_called_is_not_undone_by_it() {
5248 let (tmp, talks) = store();
5249 let spec = mock_agent(tmp.path(), REPLY, env("hi"));
5250 let cfg = config(spec);
5251 let mut stale = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
5254
5255 talks.remove(&stale.id).expect("remove");
5256
5257 let err = close(&mut stale, &talks)
5261 .expect_err("a delete that landed first must be honored, not overwritten");
5262 assert!(err.to_string().contains("deleted"), "{err}");
5263
5264 assert!(
5265 talks.get(&stale.id).is_err(),
5266 "close must not resurrect a conversation deleted while its snapshot was stale"
5267 );
5268 let _ = &cfg; }
5270
5271 #[test]
5272 fn a_delete_that_lands_before_reopen_is_called_is_not_undone_by_it() {
5273 let (tmp, talks) = store();
5274 let spec = mock_agent(tmp.path(), REPLY, env("hi"));
5275 let cfg = config(spec);
5276 let mut stale = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
5279 close(&mut stale, &talks).expect("close");
5280
5281 talks.remove(&stale.id).expect("remove");
5282
5283 let err = reopen(&mut stale, &talks)
5287 .expect_err("a delete that landed first must be honored, not overwritten");
5288 assert!(err.to_string().contains("deleted"), "{err}");
5289
5290 assert!(
5291 talks.get(&stale.id).is_err(),
5292 "reopen must not resurrect a conversation deleted while its snapshot was stale"
5293 );
5294 let _ = &cfg; }
5296
5297 #[test]
5298 fn list_puts_open_talks_before_closed_ones() {
5299 let (tmp, talks) = store();
5300 let make = |id: &str, status: TalkStatus| {
5301 let mut t = Talk {
5302 posts_read_through: None,
5303 pending_breaks: None,
5304 pending_messages: Vec::new(),
5305 schema: SCHEMA,
5306 id: id.to_owned(),
5307 repo: tmp.path().to_owned(),
5308 agent: "mock".to_owned(),
5309 status,
5310 turns: Vec::new(),
5311 pending: String::new(),
5312 pending_attachments: Vec::new(),
5313 fallback: false,
5314 persona: String::new(),
5315 persona_dirty: false,
5316 implementers: 1,
5317 implementers_dirty: false,
5318 notified: Vec::new(),
5319 created_at: Timestamp::now(),
5320 updated_at: Timestamp::now(),
5321 seat: SeatState::new(SEAT, "mock", 7),
5322 };
5323 talks.put(&mut t).expect("put");
5324 };
5325 make("20260901-000000-0001", TalkStatus::Open);
5326 make("20260902-000000-0002", TalkStatus::Open);
5327 make("20260903-000000-0003", TalkStatus::Closed);
5328
5329 let ids: Vec<String> = talks.list().into_iter().map(|t| t.id).collect();
5330 assert_eq!(
5331 ids,
5332 [
5333 "20260902-000000-0002",
5334 "20260901-000000-0001",
5335 "20260903-000000-0003"
5336 ]
5337 );
5338 assert_eq!(talks.count_open(), 2);
5339 }
5340
5341 #[test]
5342 fn tasks_of_finds_only_this_talks_own_tasks() {
5343 let dir = tempfile::tempdir().expect("tempdir");
5344 let queue = Queue::at(dir.path().join("queue"));
5345
5346 let mut mine = Task::new(
5347 "rework the loader".to_owned(),
5348 "rework the loader".to_owned(),
5349 PathBuf::from("/repo"),
5350 Source::Agent {
5351 run: "20260904-014455-ab12".to_owned(),
5352 node: "chat".to_owned(),
5353 },
5354 );
5355 queue.put(&mut mine).expect("put mine");
5356
5357 let mut theirs = Task::new(
5358 "unrelated".to_owned(),
5359 "unrelated".to_owned(),
5360 PathBuf::from("/repo"),
5361 Source::Agent {
5362 run: "20260904-090000-zz99".to_owned(),
5363 node: "implement".to_owned(),
5364 },
5365 );
5366 queue.put(&mut theirs).expect("put theirs");
5367
5368 let mut human = Task::new(
5369 "typed by hand".to_owned(),
5370 "typed by hand".to_owned(),
5371 PathBuf::from("/repo"),
5372 Source::Human,
5373 );
5374 queue.put(&mut human).expect("put human");
5375
5376 let found = tasks_of(&queue, "20260904-014455-ab12");
5377 assert_eq!(found.len(), 1);
5378 assert_eq!(found[0].id, mine.id);
5379 }
5380
5381 #[test]
5382 fn the_briefing_names_solo_task_add() {
5383 let brief = briefing(Path::new("/repo"), "en", false);
5384 assert!(brief.contains("magi task add --solo"));
5385 assert!(brief.contains("/repo"));
5386 assert!(!brief.contains("Hold this conversation in"));
5387 }
5388
5389 #[test]
5395 fn the_briefing_explains_targeting_a_different_repository_by_name() {
5396 let brief = briefing(Path::new("/repo"), "en", false);
5397 assert!(brief.contains("--repo does not have to be a full path"));
5398 assert!(brief.contains("owner/repo"));
5399 assert!(brief.contains("magi repos"));
5400 assert!(brief.contains("ask the operator"));
5401 }
5402
5403 #[test]
5404 fn the_briefing_tells_the_assistant_to_pass_images_with_attach() {
5405 let brief = briefing(Path::new("/repo"), "en", false);
5406 assert!(brief.contains("--attach <path>"), "{brief}");
5407 assert!(brief.contains("deleting this conversation"), "{brief}");
5408 }
5409
5410 #[test]
5411 fn the_briefing_names_the_language_when_it_is_not_english() {
5412 let brief = briefing(Path::new("/repo"), "Japanese", false);
5413 assert!(brief.contains("Hold this conversation in Japanese"));
5414 }
5415
5416 #[test]
5417 fn the_briefing_forbids_writes_unless_the_repository_opted_in() {
5418 let read_only = briefing(Path::new("/repo"), "en", false);
5419 assert!(read_only.contains("Do not write files"));
5420 assert!(!read_only.contains("allow_write"));
5421
5422 let writable = briefing(Path::new("/repo"), "en", true);
5423 assert!(!writable.contains("Do not write files"));
5424 assert!(writable.contains("allow_write = true"));
5425 assert!(writable.contains("magi task add --solo"));
5428 assert!(writable.contains("say plainly what you"));
5429 }
5430
5431 #[test]
5432 fn the_briefing_says_the_chat_cannot_push_and_tasks_report_back() {
5433 let b = briefing_for(Path::new("/r"), "en", false, None, None, 1);
5434 assert!(
5435 b.contains("cannot send the operator a message on your own"),
5436 "{b}"
5437 );
5438 assert!(b.contains(crate::prompt::CHAT_TASK_NOTICE_HEADING));
5439 assert!(b.contains("magi talk watch --timeout 900"));
5440 assert!(b.contains("nor a successfully registered watch"));
5441 }
5442
5443 #[test]
5444 fn a_post_is_replayed_until_the_agent_answers_again() {
5445 let (_tmp, talks) = store();
5446 let mut talk = ctx_talk("mock", Vec::new());
5447 talks.put(&mut talk).expect("put");
5448 post(&talks, &talk.id, " found it ", "20260902-000000-aaaa").expect("post");
5449 let mut talk = talks.get(&talk.id).expect("get");
5450 let block = posts_since_last_reply(&talk).expect("block");
5451 assert!(block.starts_with("# Posted by a task"), "{block}");
5452 assert!(block.contains("found it"));
5453 talk.turns.push(reply("ok", None));
5454 assert!(posts_since_last_reply(&talk).is_none());
5455 assert!(post(&talks, &talk.id, " ", "r").is_err());
5456 close(&mut talk, &talks).expect("close");
5457 assert!(post(&talks, &talk.id, "late", "r").is_err());
5458 }
5459
5460 #[test]
5461 fn queue_once_accepts_a_key_a_single_time_even_after_a_drain() {
5462 let (_tmp, talks) = store();
5463 let mut talk = ctx_talk("mock", Vec::new());
5464 talks.put(&mut talk).expect("put");
5465 assert!(queue_once(&mut talk, &talks, "one", "k").expect("first"));
5466 drain(&mut talk, &talks).expect("drain");
5467 assert!(!queue_once(&mut talk, &talks, "one", "k").expect("again"));
5468 assert!(talks.get(&talk.id).expect("get").pending.is_empty());
5469 }
5470}