1use std::path::{Path, PathBuf};
52use std::sync::{Arc, Mutex, MutexGuard};
53use std::time::Duration;
54
55use anyhow::{Context, Result, bail};
56use jiff::Timestamp;
57use serde::{Deserialize, Serialize};
58
59use crate::agent::{self, Invocation, SeatState};
60use crate::config::{AgentSpec, Config};
61use crate::queue::{Queue, Source, Task};
62
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, Copy, PartialEq, Eq, Serialize, Deserialize)]
100#[serde(rename_all = "lowercase")]
101pub enum Sender {
102 Operator,
104 Persona,
106 Magi,
108}
109
110pub fn sender(turn: &Turn, message: Option<&Message>) -> Sender {
112 message
113 .and_then(|m| m.sender)
114 .or(turn.sender)
115 .unwrap_or_else(|| {
116 if turn.posted_by.is_some()
117 || (turn.who == Who::Agent && turn.body.starts_with(MAGI_NOTE))
118 {
119 Sender::Magi
120 } else if turn.who == Who::Operator {
121 Sender::Operator
122 } else {
123 Sender::Persona
124 }
125 })
126}
127
128#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
136#[serde(deny_unknown_fields)]
137pub struct Attachment {
138 pub id: String,
140 pub name: String,
142 pub mime: String,
145 pub bytes: u64,
147}
148
149#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
151#[serde(deny_unknown_fields)]
152pub struct ReplyTarget {
153 pub turn: usize,
155 pub message: usize,
157}
158
159#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
161pub struct Reply {
162 #[serde(default, skip_serializing_if = "Option::is_none")]
164 pub sender: Option<Sender>,
165 pub target: ReplyTarget,
167 pub who: Who,
169 pub excerpt: String,
171}
172
173#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
175pub struct Message {
176 #[serde(default, skip_serializing_if = "Option::is_none")]
178 pub display: Option<crate::prompt::NoticeDisplay>,
179 #[serde(default, skip_serializing_if = "Option::is_none")]
181 pub sender: Option<Sender>,
182 pub body: String,
184 pub attachments: Vec<Attachment>,
186 pub reply: Option<Reply>,
188}
189
190pub(crate) fn notice_display(
192 talk: &Talk,
193 turn: &Turn,
194 message: Option<&Message>,
195) -> Option<crate::prompt::NoticeDisplay> {
196 if let Some(display) = message.and_then(|m| m.display.as_ref()) {
197 return Some(display.clone());
198 }
199 let body = message.map_or(turn.body.as_str(), |m| m.body.as_str());
200 if sender(turn, message) == Sender::Magi
201 || talk.completion_notices.iter().any(|r| r.notice == body)
202 {
203 crate::prompt::legacy_notice_display(body)
204 } else {
205 None
206 }
207}
208
209fn resolve_reply(talk: &Talk, target: Option<ReplyTarget>) -> Result<Option<Reply>> {
210 let Some(target) = target else {
211 return Ok(None);
212 };
213 let turn = talk
214 .turns
215 .get(target.turn)
216 .context("invalid reply target")?;
217 let (body, attachments) = if turn.messages.is_empty() {
218 if target.message != 0 {
219 bail!("invalid reply target");
220 }
221 (&turn.body, &turn.attachments)
222 } else {
223 let message = turn
224 .messages
225 .get(target.message)
226 .context("invalid reply target")?;
227 (&message.body, &message.attachments)
228 };
229 let display = notice_display(talk, turn, turn.messages.get(target.message));
230 let body = display.as_ref().map_or(body.as_str(), |d| d.facts.as_str());
231 let excerpt = if body.trim().is_empty() {
232 format!("{} attachment(s)", attachments.len())
233 } else {
234 body.chars().take(240).collect()
235 };
236 Ok(Some(Reply {
237 sender: Some(if display.is_some() {
238 Sender::Magi
239 } else {
240 sender(turn, turn.messages.get(target.message))
241 }),
242 target,
243 who: turn.who,
244 excerpt,
245 }))
246}
247
248fn message_prompt(turn: &Turn, talk: &Talk, store: &Talks) -> String {
250 if turn.messages.is_empty() {
251 return turn.body.clone();
252 }
253 turn.messages
254 .iter()
255 .map(|message| match &message.reply {
256 Some(reply) => {
257 let mut quote = format!(
258 "[Reply to {}: {}]",
259 if reply.sender == Some(Sender::Magi) {
260 "MAGI".to_owned()
261 } else {
262 format!("{:?}", reply.who)
263 },
264 reply.excerpt.lines().collect::<Vec<_>>().join(" "),
265 );
266 if let Some(target) = talk.turns.get(reply.target.turn) {
267 let attachments: &[Attachment] = if target.messages.is_empty() {
268 &target.attachments
269 } else if let Some(message) = target.messages.get(reply.target.message) {
270 &message.attachments
271 } else {
272 &[]
273 };
274 for attachment in attachments {
275 if let Some(path) = store.attachment_path(&talk.id, attachment) {
276 quote.push_str(&format!(
277 "\nReplied-to image: {} ({})",
278 path.display(),
279 attachment.mime
280 ));
281 }
282 }
283 }
284 format!("{quote}\n{}", message.body)
285 }
286 None => message.body.clone(),
287 })
288 .collect::<Vec<_>>()
289 .join("\n\n")
290}
291
292fn messages_need_no_metadata(messages: &[Message]) -> bool {
294 messages.iter().all(|message| {
295 message.sender.is_none()
296 && message.display.is_none()
297 && message.reply.is_none()
298 && message.attachments.is_empty()
299 })
300}
301
302#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
304#[serde(deny_unknown_fields)]
305pub struct Turn {
306 #[serde(default, skip_serializing_if = "Option::is_none")]
308 pub sender: Option<Sender>,
309 pub who: Who,
311 pub body: String,
313 pub at: Timestamp,
315 #[serde(default)]
318 pub attachments: Vec<Attachment>,
319 #[serde(default, skip_serializing_if = "Option::is_none")]
324 pub usage: Option<TurnUsage>,
325 #[serde(default, skip_serializing_if = "Option::is_none")]
332 pub breaks: Option<Vec<usize>>,
333 #[serde(default, skip_serializing_if = "Vec::is_empty")]
334 pub messages: Vec<Message>,
336 #[serde(default, skip_serializing_if = "Option::is_none")]
341 pub posted_by: Option<String>,
342}
343
344#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
352pub struct TurnUsage {
353 pub context_tokens: u64,
355 pub agent: String,
357 #[serde(default)]
359 pub model: Option<String>,
360}
361
362#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
367pub struct ContextUsage {
368 pub tokens: Option<u64>,
370 pub window: Option<u64>,
372 pub percent: Option<u64>,
374 pub warn: bool,
376 pub since_switch: bool,
380 pub model: Option<String>,
382 #[serde(default)]
385 pub estimated: bool,
386}
387
388const CONTEXT_WARN_PERCENT: u64 = 80;
390
391const STANDING_PROMPT_FALLBACK_CHARS: u64 = 7000;
394
395pub fn estimate_context_tokens(talk: &Talk, standing_chars: u64) -> Option<u64> {
408 let mut counted = false;
409 let mut chars = standing_chars;
410 for t in talk.turns.iter().filter(|t| !t.body.starts_with(MAGI_NOTE)) {
411 counted = true;
412 chars += t.body.chars().count() as u64;
413 }
414 counted.then(|| (chars * 2).div_ceil(7))
416}
417
418pub fn context_usage(talk: &Talk, cfg: Option<&Config>) -> ContextUsage {
431 let current = cfg.and_then(|c| c.agents.iter().find(|a| a.id == talk.agent));
432 let model = current.and_then(|a| a.model.clone());
433 let window = cfg
434 .zip(model.as_deref())
435 .and_then(|(c, m)| c.context_window(m))
436 .filter(|w| *w > 0);
437 let usage = talk
438 .turns
439 .iter()
440 .rev()
441 .find(|t| t.who == Who::Agent && !t.body.starts_with(MAGI_NOTE))
442 .and_then(|t| t.usage.as_ref());
443 let measured = usage.map(|u| u.context_tokens);
444 let tokens = measured.or_else(|| {
445 let standing = cfg.map_or(STANDING_PROMPT_FALLBACK_CHARS, |c| {
446 briefing_for(
447 &talk.repo,
448 &c.graph.language,
449 c.talk.allow_write,
450 crate::persona::active(&c.talk.personas, &talk.persona).as_ref(),
451 c.talk.operator_name(),
452 talk.implementers,
453 )
454 .chars()
455 .count() as u64
456 });
457 estimate_context_tokens(talk, standing)
458 });
459 let estimated = measured.is_none() && tokens.is_some();
460 let since_switch =
461 usage.is_some_and(|u| u.agent != talk.agent || (current.is_some() && u.model != model));
462 let (percent, warn) = match (tokens, window) {
463 (Some(t), Some(w)) => (
464 Some(t.saturating_mul(100) / w),
465 t.saturating_mul(100) >= w.saturating_mul(CONTEXT_WARN_PERCENT),
466 ),
467 _ => (None, false),
468 };
469 ContextUsage {
470 tokens,
471 window,
472 percent,
473 warn,
474 since_switch,
475 model,
476 estimated,
477 }
478}
479
480#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
484#[serde(rename_all = "lowercase")]
485pub enum TalkStatus {
486 Open,
489 Closed,
491}
492
493impl TalkStatus {
494 pub fn open(self) -> bool {
496 matches!(self, Self::Open)
497 }
498
499 pub fn as_str(self) -> &'static str {
501 match self {
502 Self::Open => "open",
503 Self::Closed => "closed",
504 }
505 }
506}
507
508#[derive(Debug, Clone, Serialize, Deserialize)]
510#[serde(deny_unknown_fields)]
511pub struct Talk {
512 pub schema: u32,
514 pub id: String,
516 pub repo: PathBuf,
518 pub agent: String,
520 pub status: TalkStatus,
522 pub turns: Vec<Turn>,
524 #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
526 pub recommendations: std::collections::BTreeMap<usize, crate::consult::RecommendationManifest>,
527 #[serde(default, skip_serializing_if = "Option::is_none")]
531 pub posts_read_through: Option<usize>,
532 #[serde(default)]
535 pub pending: String,
536 #[serde(default)]
538 pub pending_attachments: Vec<Attachment>,
539 #[serde(default, skip_serializing_if = "Option::is_none")]
541 pub pending_breaks: Option<Vec<usize>>,
542 #[serde(default, skip_serializing_if = "Vec::is_empty")]
543 pub pending_messages: Vec<Message>,
545 #[serde(default)]
550 pub fallback: bool,
551 #[serde(default)]
554 pub persona: String,
555 #[serde(default)]
559 pub persona_dirty: bool,
560 #[serde(default = "solo_implementers")]
563 pub implementers: u8,
564 #[serde(default)]
567 pub implementers_dirty: bool,
568 #[serde(default)]
573 pub notified: Vec<String>,
574 #[serde(default, skip_serializing_if = "Vec::is_empty")]
576 pub completion_notices: Vec<crate::chat_notify::CompletionReference>,
577 pub created_at: Timestamp,
579 pub updated_at: Timestamp,
581 seat: SeatState,
586}
587
588impl Talk {
589 pub fn short(&self) -> &str {
591 short(&self.id)
592 }
593}
594
595#[derive(Debug, Clone)]
597pub struct Talks {
598 root: PathBuf,
599 lock: Arc<Mutex<()>>,
608}
609
610impl Talks {
611 pub fn open() -> Self {
613 Self::at(crate::run::home().join("talks"))
614 }
615
616 pub fn at(root: PathBuf) -> Self {
619 Self {
620 root,
621 lock: Arc::new(Mutex::new(())),
622 }
623 }
624
625 fn guard(&self) -> Result<StoreGuard<'_>> {
640 let answer = self.answer_guard()?;
641 std::fs::create_dir_all(&self.root)
642 .with_context(|| format!("create {}", self.root.display()))?;
643 let path = self.root.join(".store.turn");
644 let deadline = std::time::Instant::now() + TAKEOVER_LOCK_TTL * 2;
645 loop {
646 if let Some(file) = TurnLock::take(&path)? {
647 return Ok(StoreGuard {
648 _file: file,
649 _answer: answer,
650 });
651 }
652 if std::time::Instant::now() >= deadline {
653 bail!("the talk store is locked by another process");
654 }
655 std::thread::sleep(Duration::from_millis(10));
656 }
657 }
658
659 fn try_guard(&self) -> Result<Option<StoreGuard<'_>>> {
661 let Some(answer) = self.try_answer_guard()? else {
662 return Ok(None);
663 };
664 std::fs::create_dir_all(&self.root)
665 .with_context(|| format!("create {}", self.root.display()))?;
666 Ok(
667 TurnLock::take(&self.root.join(".store.turn"))?.map(|file| StoreGuard {
668 _file: file,
669 _answer: answer,
670 }),
671 )
672 }
673
674 pub fn answer_guard(&self) -> Result<AnswerGuard<'_>> {
679 let deadline = std::time::Instant::now() + TAKEOVER_LOCK_TTL * 2;
680 loop {
681 if let Some(guard) = self.try_answer_guard()? {
682 return Ok(guard);
683 }
684 if std::time::Instant::now() >= deadline {
685 bail!("conversation evidence is locked by another process");
686 }
687 std::thread::sleep(Duration::from_millis(10));
688 }
689 }
690
691 pub fn try_answer_guard(&self) -> Result<Option<AnswerGuard<'_>>> {
695 let mutex = match self.lock.try_lock() {
696 Ok(guard) => guard,
697 Err(std::sync::TryLockError::Poisoned(err)) => err.into_inner(),
698 Err(std::sync::TryLockError::WouldBlock) => return Ok(None),
699 };
700 let root = self.answer_lock_root();
703 std::fs::create_dir_all(&root).context("create conversation evidence lock directory")?;
704 let path = root.join("store.turn");
705 Ok(TurnLock::take(&path)?.map(|file| AnswerGuard {
706 _file: file,
707 _mutex: mutex,
708 }))
709 }
710
711 pub fn answer_lock_root(&self) -> PathBuf {
713 self.root.join(".answer-lock")
714 }
715
716 pub fn root(&self) -> &Path {
718 &self.root
719 }
720
721 pub fn path_of(&self, id: &str) -> PathBuf {
723 self.root.join(format!("{id}.json"))
724 }
725
726 pub fn artifacts_of(&self, id: &str) -> PathBuf {
729 self.root.join(format!("{id}.artifacts"))
730 }
731
732 pub fn attachments_dir(&self, id: &str) -> PathBuf {
736 self.artifacts_of(id).join("attachments")
737 }
738
739 pub fn put_attachment(
748 &self,
749 id: &str,
750 mime: &str,
751 name: &str,
752 data: &[u8],
753 ) -> Result<Attachment> {
754 let dir = self.attachments_dir(id);
755 std::fs::create_dir_all(&dir).with_context(|| format!("create {}", dir.display()))?;
756 let ext = attachment_ext(mime).with_context(|| format!("unsupported mime `{mime}`"))?;
757 let att = Attachment {
758 id: new_attachment_id(),
759 name: name.to_owned(),
760 mime: mime.to_owned(),
761 bytes: data.len() as u64,
762 };
763 std::fs::write(dir.join(format!("{}.{ext}", att.id)), data)
764 .with_context(|| format!("write attachment {}", att.id))?;
765 std::fs::write(
766 dir.join(format!("{}.json", att.id)),
767 serde_json::to_string(&att).context("serialize attachment")?,
768 )
769 .with_context(|| format!("write attachment metadata {}", att.id))?;
770 Ok(att)
771 }
772
773 pub fn attachment_meta(&self, id: &str, att_id: &str) -> Result<Option<Attachment>> {
782 if !valid_attachment_id(att_id) {
783 return Ok(None);
784 }
785 let meta_path = self.attachments_dir(id).join(format!("{att_id}.json"));
786 if !meta_path.is_file() {
787 return Ok(None);
788 }
789 let att = serde_json::from_str(
790 &std::fs::read_to_string(&meta_path)
791 .with_context(|| format!("read {}", meta_path.display()))?,
792 )
793 .with_context(|| format!("parse {}", meta_path.display()))?;
794 Ok(Some(att))
795 }
796
797 pub fn read_attachment(&self, id: &str, att_id: &str) -> Result<Option<(Attachment, Vec<u8>)>> {
801 let Some(att) = self.attachment_meta(id, att_id)? else {
802 return Ok(None);
803 };
804 let ext = attachment_ext(&att.mime).with_context(|| {
805 format!("attachment {att_id} has an unsupported mime `{}`", att.mime)
806 })?;
807 let data_path = self.attachments_dir(id).join(format!("{att_id}.{ext}"));
808 let data =
809 std::fs::read(&data_path).with_context(|| format!("read {}", data_path.display()))?;
810 Ok(Some((att, data)))
811 }
812
813 fn attachment_path(&self, id: &str, att: &Attachment) -> Option<PathBuf> {
830 let ext = attachment_ext(&att.mime)?;
831 let path = self.attachments_dir(id).join(format!("{}.{ext}", att.id));
832 std::path::absolute(&path).ok()
833 }
834
835 pub fn put(&self, t: &mut Talk) -> Result<()> {
844 std::fs::create_dir_all(&self.root)
845 .with_context(|| format!("create {}", self.root.display()))?;
846 let previous = self.get(&t.id).ok();
847 let start = previous.as_ref().map_or(0, |old| old.turns.len());
848 if let Some(old) = previous {
850 t.recommendations = old.recommendations;
851 }
852 let questions = crate::ask::Questions::at(
853 self.root
854 .parent()
855 .context("talk store has no home")?
856 .join("questions"),
857 );
858 for (index, turn) in t.turns.iter().enumerate().skip(start) {
859 if turn.who == Who::Agent
860 && sender(turn, None) == Sender::Persona
861 && turn.posted_by.is_none()
862 {
863 t.recommendations.insert(
864 index,
865 crate::consult::recommendation_manifest(&turn.body, &questions),
866 );
867 }
868 }
869 t.updated_at = Timestamp::now();
870 let mut persisted = t.clone();
873 for turn in &mut persisted.turns {
874 if turn.attachments.is_empty() && messages_need_no_metadata(&turn.messages) {
875 turn.messages.clear();
876 }
877 }
878 if persisted.pending_attachments.is_empty()
879 && messages_need_no_metadata(&persisted.pending_messages)
880 {
881 persisted.pending_messages.clear();
882 }
883 let body = serde_json::to_string_pretty(&persisted).context("serialize talk")?;
884 let path = self.path_of(&t.id);
885 let tmp = path.with_extension("json.tmp");
886 write_atomic(&tmp, &path, &body)
887 }
888
889 pub fn get(&self, id: &str) -> Result<Talk> {
891 let resolved = self.resolve_id(id)?;
892 read_path(&self.path_of(&resolved))
893 }
894
895 pub fn list(&self) -> Vec<Talk> {
898 self.list_counting_unreadable().0
899 }
900
901 pub fn list_counting_unreadable(&self) -> (Vec<Talk>, usize) {
904 let mut unreadable = 0;
905 let mut all: Vec<Talk> = std::fs::read_dir(&self.root)
906 .into_iter()
907 .flatten()
908 .flatten()
909 .map(|e| e.path())
910 .filter(|p| p.extension().is_some_and(|x| x == "json"))
911 .filter_map(|p| {
912 let talk = read_path(&p).ok();
913 if talk.is_none() {
914 unreadable += 1;
915 }
916 talk
917 })
918 .collect();
919 all.sort_unstable_by(|a, b| {
920 let rank = |t: &Talk| u8::from(!t.status.open());
921 rank(a).cmp(&rank(b)).then_with(|| b.id.cmp(&a.id))
922 });
923 (all, unreadable)
924 }
925
926 pub fn resolve_id(&self, prefix: &str) -> Result<String> {
928 if self.path_of(prefix).is_file() {
929 return Ok(prefix.to_owned());
930 }
931 let hits: Vec<String> = self
932 .list()
933 .into_iter()
934 .map(|t| t.id)
935 .filter(|id| id.starts_with(prefix) || id.ends_with(prefix))
936 .collect();
937 match hits.len() {
938 1 => Ok(hits.into_iter().next().expect("exactly one hit")),
939 0 => bail!("no talk matches `{prefix}`"),
940 _ => bail!(
941 "`{prefix}` matches {} talks: {}",
942 hits.len(),
943 hits.join(", ")
944 ),
945 }
946 }
947
948 pub fn revision(&self) -> u64 {
951 std::fs::read_dir(&self.root)
952 .into_iter()
953 .flatten()
954 .flatten()
955 .filter(|e| e.path().extension().is_none_or(|x| x != "turn"))
956 .filter(|e| !e.file_name().to_string_lossy().starts_with('.'))
957 .filter_map(|e| e.metadata().ok())
958 .filter_map(|m| m.modified().ok())
959 .filter_map(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
960 .map(|d| d.as_millis() as u64)
961 .max()
962 .unwrap_or(0)
963 }
964
965 pub fn count_open(&self) -> usize {
967 self.list().iter().filter(|t| t.status.open()).count()
968 }
969
970 pub fn turn_path(&self, id: &str) -> PathBuf {
973 self.root.join(format!("{id}.turn"))
974 }
975
976 pub fn claim_turn(&self, id: &str) -> Result<Option<TurnLease>> {
985 self.claim_turn_at(id, Timestamp::now())
986 }
987
988 fn claim_turn_at(&self, id: &str, now: Timestamp) -> Result<Option<TurnLease>> {
989 std::fs::create_dir_all(&self.root)
990 .with_context(|| format!("create {}", self.root.display()))?;
991 let path = self.turn_path(id);
992 let token = fresh_token();
993 if create_turn(&path, &token, now)? {
994 return Ok(Some(TurnLease {
995 talk: id.to_owned(),
996 path,
997 token,
998 }));
999 }
1000 if lease_blocks(&path, now) {
1001 return Ok(None);
1002 }
1003 let Some(_lock) = TurnLock::take(&path)? else {
1008 return Ok(None);
1009 };
1010 if lease_blocks(&path, now) {
1011 return Ok(None);
1012 }
1013 let _ = std::fs::remove_file(&path);
1014 Ok(create_turn(&path, &token, now)?.then_some(TurnLease {
1015 talk: id.to_owned(),
1016 path,
1017 token,
1018 }))
1019 }
1020
1021 pub fn turn_held(&self, id: &str) -> bool {
1023 read_turn(&self.turn_path(id)).is_some_and(|r| r.fresh(Timestamp::now()))
1024 }
1025
1026 pub fn remove(&self, id: &str) -> Result<()> {
1039 let _guard = self.guard()?;
1040 let resolved = self.resolve_id(id)?;
1041 let path = self.path_of(&resolved);
1042 std::fs::remove_file(&path).with_context(|| format!("remove {}", path.display()))?;
1043 let artifacts = self.artifacts_of(&resolved);
1044 if artifacts.is_dir() {
1045 std::fs::remove_dir_all(&artifacts)
1046 .with_context(|| format!("remove {}", artifacts.display()))?;
1047 }
1048 let _ = std::fs::remove_file(self.turn_path(&resolved));
1049 Ok(())
1050 }
1051}
1052
1053struct StoreGuard<'a> {
1056 _file: TurnLock,
1057 _answer: AnswerGuard<'a>,
1058}
1059
1060pub struct AnswerGuard<'a> {
1062 _file: TurnLock,
1063 _mutex: MutexGuard<'a, ()>,
1064}
1065
1066#[derive(Debug, Serialize, Deserialize)]
1069struct TurnRecord {
1070 token: String,
1071 pid: u32,
1072 beat_at: Timestamp,
1073}
1074
1075impl TurnRecord {
1076 fn fresh(&self, now: Timestamp) -> bool {
1077 now.as_second() - self.beat_at.as_second() <= crate::ask::LEASE_TTL.as_secs() as i64
1078 }
1079}
1080
1081fn fresh_token() -> String {
1085 static SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1086 let n = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1087 let seed = crate::rng::entropy() ^ n.wrapping_mul(0x9E37_79B9_7F4A_7C15);
1088 crate::rng::SplitMix64::new(seed).uuid_v4()
1089}
1090
1091fn read_turn(path: &Path) -> Option<TurnRecord> {
1092 serde_json::from_str(&std::fs::read_to_string(path).ok()?).ok()
1093}
1094
1095const TAKEOVER_LOCK_TTL: Duration = Duration::from_secs(10);
1097
1098const TICKET_TTL: Duration = Duration::from_secs(10);
1101
1102const TICKET_GENERATIONS: u32 = 16;
1104
1105const TICKET_SWEEP_AGE: Duration = Duration::from_secs(3600);
1107
1108fn create_exclusive(path: &Path, body: &str) -> Result<bool> {
1110 use std::io::Write as _;
1111 match std::fs::OpenOptions::new()
1112 .write(true)
1113 .create_new(true)
1114 .open(path)
1115 {
1116 Ok(mut f) => {
1117 if let Err(e) = f.write_all(body.as_bytes()) {
1118 drop(f);
1119 let _ = std::fs::remove_file(path);
1120 return Err(e).with_context(|| format!("write {}", path.display()));
1121 }
1122 Ok(true)
1123 }
1124 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => Ok(false),
1125 Err(e) => Err(e).with_context(|| format!("create {}", path.display())),
1126 }
1127}
1128
1129fn create_turn(path: &Path, token: &str, now: Timestamp) -> Result<bool> {
1130 let record = TurnRecord {
1131 token: token.to_owned(),
1132 pid: std::process::id(),
1133 beat_at: now,
1134 };
1135 let body = serde_json::to_string(&record).context("serialize turn lease")?;
1136 let tmp = path.with_extension(format!("turn.{token}.new"));
1139 publish_exclusive(path, &tmp, &body)
1140}
1141
1142fn lease_blocks(path: &Path, now: Timestamp) -> bool {
1146 if read_turn(path).is_some_and(|r| r.fresh(now)) {
1147 return true;
1148 }
1149 std::fs::metadata(path).is_ok_and(|m| {
1150 m.len() == 0
1151 && m.modified()
1152 .ok()
1153 .and_then(|t| t.elapsed().ok())
1154 .is_some_and(|age| age <= TAKEOVER_LOCK_TTL)
1155 })
1156}
1157
1158fn link_unsupported(e: &std::io::Error) -> bool {
1161 e.kind() == std::io::ErrorKind::Unsupported || (cfg!(windows) && e.raw_os_error() == Some(1))
1162}
1163
1164fn create_in_place(path: &Path, body: &str) -> Result<bool> {
1182 use std::io::Write as _;
1183 let mut f = match std::fs::OpenOptions::new()
1184 .write(true)
1185 .create_new(true)
1186 .open(path)
1187 {
1188 Ok(f) => f,
1189 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => return Ok(false),
1190 Err(e) => return Err(e).with_context(|| format!("create {}", path.display())),
1191 };
1192 f.write_all(body.as_bytes())
1193 .with_context(|| format!("write {}", path.display()))?;
1194 Ok(std::fs::read_to_string(path).is_ok_and(|t| t == body))
1197}
1198
1199fn publish_exclusive(path: &Path, tmp: &Path, body: &str) -> Result<bool> {
1200 std::fs::write(tmp, body).with_context(|| format!("write {}", tmp.display()))?;
1201 #[cfg(test)]
1202 let linked = if failpoint::no_link_forced() {
1203 Err(std::io::Error::from(std::io::ErrorKind::Unsupported))
1204 } else {
1205 std::fs::hard_link(tmp, path)
1206 };
1207 #[cfg(not(test))]
1208 let linked = std::fs::hard_link(tmp, path);
1209 let out = match linked {
1210 Ok(()) => Ok(true),
1211 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => Ok(false),
1212 Err(e) if link_unsupported(&e) => create_in_place(path, body),
1213 Err(e) => Err(e).with_context(|| format!("create {}", path.display())),
1214 };
1215 let _ = std::fs::remove_file(tmp);
1216 out
1217}
1218
1219fn remove_if_carries(path: &Path, expected: &str) -> bool {
1230 let gone = path.with_extension(format!("gone.{}", fresh_token()));
1231 if std::fs::rename(path, &gone).is_err() {
1232 return false;
1233 }
1234 let found = std::fs::read_to_string(&gone);
1235 if found.as_ref().is_ok_and(|t| t == expected) {
1236 let _ = std::fs::remove_file(&gone);
1237 return true;
1238 }
1239 if let Ok(body) = found {
1240 let back = path.with_extension(format!("back.{}", fresh_token()));
1241 match publish_exclusive(path, &back, &body) {
1242 Ok(true) => {}
1243 Ok(false) | Err(_) => tracing::warn!(
1244 "{} was replaced while a stale removal had it aside; \
1245 the displaced file is dropped",
1246 path.display()
1247 ),
1248 }
1249 }
1250 let _ = std::fs::remove_file(&gone);
1251 false
1252}
1253
1254struct TurnLock {
1258 path: PathBuf,
1259 token: String,
1260}
1261
1262impl TurnLock {
1263 fn token() -> String {
1264 fresh_token()
1265 }
1266
1267 fn publish(path: &Path, token: &str) -> Result<bool> {
1271 let tmp = path.with_extension(format!("lock.{token}.new"));
1272 publish_exclusive(path, &tmp, token)
1273 }
1274
1275 fn take(lease: &Path) -> Result<Option<Self>> {
1276 let path = lease.with_extension("turn.lock");
1277 let token = Self::token();
1278 if Self::publish(&path, &token)? {
1279 return Ok(Some(Self { path, token }));
1280 }
1281 let Ok(seen) = std::fs::read_to_string(&path) else {
1282 return Ok(None);
1283 };
1284 let key = if !seen.is_empty() && seen.chars().all(|c| c.is_ascii_alphanumeric() || c == '-')
1287 {
1288 seen.as_str()
1289 } else {
1290 "invalid"
1291 };
1292 let aged = std::fs::metadata(&path)
1293 .and_then(|m| m.modified())
1294 .ok()
1295 .and_then(|t| t.elapsed().ok())
1296 .is_some_and(|age| age > TAKEOVER_LOCK_TTL);
1297 if !aged {
1298 return Ok(None);
1299 }
1300 let mut won = false;
1312 for n in 0..TICKET_GENERATIONS {
1313 let ticket = path.with_extension(format!("lock.{key}.break.{n}"));
1314 if create_exclusive(&ticket, "")? {
1315 won = true;
1316 break;
1317 }
1318 let stale = std::fs::metadata(&ticket)
1319 .and_then(|m| m.modified())
1320 .ok()
1321 .and_then(|t| t.elapsed().ok())
1322 .is_some_and(|age| age > TICKET_TTL);
1323 if !stale {
1324 return Ok(None);
1325 }
1326 }
1327 if !won {
1328 Self::sweep_tickets(&path);
1333 return Ok(None);
1334 }
1335 Self::sweep_tickets(&path);
1336 if !remove_if_carries(&path, &seen) {
1342 return Ok(None);
1343 }
1344 if Self::publish(&path, &token)? {
1345 return Ok(Some(Self { path, token }));
1346 }
1347 Ok(None)
1348 }
1349
1350 fn sweep_tickets(path: &Path) {
1353 let (Some(dir), Some(name)) = (path.parent(), path.file_name().and_then(|n| n.to_str()))
1354 else {
1355 return;
1356 };
1357 let prefix = format!("{name}.");
1358 let Ok(entries) = std::fs::read_dir(dir) else {
1359 return;
1360 };
1361 for entry in entries.flatten() {
1362 let file = entry.file_name();
1363 let Some(file) = file.to_str() else { continue };
1364 if !(file.starts_with(&prefix) && file.contains(".break.")) {
1365 continue;
1366 }
1367 let old = entry
1368 .metadata()
1369 .and_then(|m| m.modified())
1370 .ok()
1371 .and_then(|t| t.elapsed().ok())
1372 .is_some_and(|age| age > TICKET_SWEEP_AGE);
1373 if old {
1374 let _ = std::fs::remove_file(entry.path());
1375 }
1376 }
1377 }
1378
1379 fn take_patiently(lease: &Path) -> Option<Self> {
1381 for _ in 0..50 {
1382 match Self::take(lease) {
1383 Ok(Some(lock)) => return Some(lock),
1384 Ok(None) => std::thread::sleep(Duration::from_millis(10)),
1385 Err(_) => return None,
1386 }
1387 }
1388 None
1389 }
1390}
1391
1392impl Drop for TurnLock {
1393 fn drop(&mut self) {
1394 remove_if_carries(&self.path, &self.token);
1396 }
1397}
1398
1399pub const TURN_BEAT: Duration = Duration::from_secs(20);
1402
1403#[derive(Debug)]
1408pub struct TurnLease {
1409 talk: String,
1410 path: PathBuf,
1411 token: String,
1412}
1413
1414impl TurnLease {
1415 pub fn holds(&self) -> bool {
1417 read_turn(&self.path).is_some_and(|r| r.token == self.token)
1418 }
1419
1420 pub fn beat(&self) -> Result<bool> {
1424 let _lock = TurnLock::take_patiently(&self.path)
1425 .with_context(|| format!("lock {} to renew it", self.path.display()))?;
1426 let Some(mut record) = read_turn(&self.path).filter(|r| r.token == self.token) else {
1427 return Ok(false);
1428 };
1429 record.beat_at = Timestamp::now();
1430 let body = serde_json::to_string(&record).context("serialize turn lease")?;
1431 let tmp = self.path.with_extension(format!("turn.{}.tmp", self.token));
1432 write_atomic(&tmp, &self.path, &body)?;
1433 Ok(true)
1434 }
1435
1436 pub async fn beating<T>(&self, fut: impl std::future::Future<Output = T>) -> Result<T> {
1441 self.beating_every(TURN_BEAT, fut).await
1442 }
1443
1444 async fn beating_every<T>(
1445 &self,
1446 period: Duration,
1447 fut: impl std::future::Future<Output = T>,
1448 ) -> Result<T> {
1449 tokio::pin!(fut);
1450 loop {
1451 match tokio::time::timeout(period, &mut fut).await {
1452 Ok(out) => return Ok(out),
1453 Err(_) => match self.beat() {
1454 Ok(true) => {}
1455 Ok(false) => bail!(
1456 "the turn lease {} was taken over; this turn is stopped",
1457 self.path.display()
1458 ),
1459 Err(e) => tracing::warn!("{e:#}"),
1460 },
1461 }
1462 }
1463 }
1464}
1465
1466impl Drop for TurnLease {
1467 fn drop(&mut self) {
1468 if let Some(_lock) = TurnLock::take_patiently(&self.path) {
1471 if read_turn(&self.path).is_some_and(|r| r.token == self.token) {
1472 let _ = std::fs::remove_file(&self.path);
1473 }
1474 }
1475 }
1476}
1477
1478pub fn begin(store: &Talks, cfg: &Config, repo: PathBuf, agent: Option<&str>) -> Result<Talk> {
1488 begin_with(store, cfg, repo, agent, &Preferred::default())
1489}
1490
1491#[derive(Debug, Default, Clone)]
1495pub struct Preferred {
1496 pub agent: Option<String>,
1498 pub persona: Option<String>,
1500 pub implementers: Option<i64>,
1502}
1503
1504pub fn begin_with(
1511 store: &Talks,
1512 cfg: &Config,
1513 repo: PathBuf,
1514 agent: Option<&str>,
1515 preferred: &Preferred,
1516) -> Result<Talk> {
1517 let repo = repo.canonicalize().unwrap_or(repo);
1520 let head = || -> Result<AgentSpec> {
1523 Ok(agent::pick_chain(
1524 &cfg.agents,
1525 cfg.roles.chatter.as_ref(),
1526 &agent::installed,
1527 "chatter",
1528 )?
1529 .remove(0))
1530 };
1531 let mut fallback = agent.is_none();
1532 let spec = match agent {
1533 Some(id) => agent::pick(&cfg.agents, Some(id), &agent::installed)?,
1534 None => {
1535 match preferred
1536 .agent
1537 .as_deref()
1538 .map(str::trim)
1539 .filter(|id| !id.is_empty())
1540 {
1541 Some(id) => match agent::pick(&cfg.agents, Some(id), &agent::installed) {
1542 Ok(spec) => {
1543 fallback = head().is_ok_and(|head| spec.id == head.id);
1544 spec
1545 }
1546 Err(_) => head()?,
1547 },
1548 None => head()?,
1549 }
1550 }
1551 };
1552 let persona = preferred
1553 .persona
1554 .as_deref()
1555 .and_then(|id| crate::persona::find(&cfg.talk.personas, id))
1556 .filter(|p| !p.is_default())
1557 .map(|p| p.id)
1558 .unwrap_or_default();
1559 let implementers = preferred
1560 .implementers
1561 .and_then(|n| u8::try_from(n).ok())
1562 .and_then(|n| check_implementers(n, cfg).ok())
1563 .unwrap_or(1);
1564
1565 let now = Timestamp::now();
1566 let mut talk = Talk {
1567 recommendations: Default::default(),
1568 posts_read_through: Some(0),
1569 pending_breaks: None,
1570 pending_messages: Vec::new(),
1571 schema: SCHEMA,
1572 id: new_id(),
1573 repo,
1574 agent: spec.id.clone(),
1575 status: TalkStatus::Open,
1576 turns: Vec::new(),
1577 pending: String::new(),
1578 pending_attachments: Vec::new(),
1579 fallback,
1580 persona,
1581 persona_dirty: false,
1582 implementers,
1583 implementers_dirty: false,
1584 notified: Vec::new(),
1585 completion_notices: Vec::new(),
1586 created_at: now,
1587 updated_at: now,
1588 seat: SeatState::new(SEAT, &spec.id, crate::rng::entropy()),
1589 };
1590 store.put(&mut talk)?;
1591 Ok(talk)
1592}
1593
1594pub fn record(
1601 talk: &mut Talk,
1602 store: &Talks,
1603 text: &str,
1604 attachments: Vec<Attachment>,
1605) -> Result<String> {
1606 record_reply(talk, store, text, attachments, None)
1607}
1608
1609pub fn record_reply(
1611 talk: &mut Talk,
1612 store: &Talks,
1613 text: &str,
1614 attachments: Vec<Attachment>,
1615 target: Option<ReplyTarget>,
1616) -> Result<String> {
1617 let _guard = store.guard()?;
1625 let Ok(fresh) = store.get(&talk.id) else {
1630 bail!("talk {} was deleted", talk.short());
1631 };
1632 let reply = resolve_reply(&fresh, target)?;
1633 talk.turns = fresh.turns;
1634 talk.status = fresh.status;
1635 talk.pending = fresh.pending;
1638 talk.pending_breaks = fresh.pending_breaks;
1639 talk.pending_messages = fresh.pending_messages;
1640 talk.pending_attachments = fresh.pending_attachments;
1641 talk.notified = fresh.notified;
1642 if !talk.status.open() {
1643 bail!(
1644 "talk {} is {} and takes no more turns",
1645 talk.short(),
1646 talk.status.as_str()
1647 );
1648 }
1649 if text.trim().is_empty() && attachments.is_empty() {
1651 bail!("nothing to say");
1652 }
1653 talk.turns.push(Turn {
1654 sender: Some(Sender::Operator),
1655 who: Who::Operator,
1656 body: text.to_owned(),
1657 at: Timestamp::now(),
1658 messages: vec![Message {
1659 display: None,
1660 sender: Some(Sender::Operator),
1661 body: text.to_owned(),
1662 attachments: attachments.clone(),
1663 reply,
1664 }],
1665 attachments,
1666 usage: None,
1667 breaks: Some(Vec::new()),
1668 posted_by: None,
1669 });
1670 store.put(talk)?;
1671 Ok(text.to_owned())
1672}
1673
1674pub fn queue(
1676 talk: &mut Talk,
1677 store: &Talks,
1678 text: &str,
1679 attachments: Vec<Attachment>,
1680) -> Result<()> {
1681 queue_reply(talk, store, text, attachments, None)
1682}
1683
1684pub fn queue_reply(
1686 talk: &mut Talk,
1687 store: &Talks,
1688 text: &str,
1689 attachments: Vec<Attachment>,
1690 target: Option<ReplyTarget>,
1691) -> Result<()> {
1692 queue_keyed(
1693 talk,
1694 store,
1695 text,
1696 attachments,
1697 None,
1698 &|_| false,
1699 (target, Sender::Operator, None),
1700 )
1701 .map(|_| ())
1702}
1703
1704pub fn queue_once(talk: &mut Talk, store: &Talks, text: &str, key: &str) -> Result<bool> {
1709 queue_once_matching(talk, store, text, key, &|_| false, None)
1710}
1711
1712pub(crate) fn queue_once_matching(
1715 talk: &mut Talk,
1716 store: &Talks,
1717 text: &str,
1718 key: &str,
1719 previous: &dyn Fn(&str) -> bool,
1720 reference: Option<&crate::chat_notify::CompletionReference>,
1721) -> Result<bool> {
1722 queue_keyed(
1723 talk,
1724 store,
1725 text,
1726 Vec::new(),
1727 Some((key, reference)),
1728 previous,
1729 (None, Sender::Magi, None),
1730 )
1731}
1732
1733pub(crate) fn queue_notice(
1735 talk: &mut Talk,
1736 store: &Talks,
1737 text: &str,
1738 key: &str,
1739 previous: &dyn Fn(&str) -> bool,
1740 reference: Option<&crate::chat_notify::CompletionReference>,
1741 display: crate::prompt::NoticeDisplay,
1742) -> Result<bool> {
1743 queue_keyed(
1744 talk,
1745 store,
1746 text,
1747 Vec::new(),
1748 Some((key, reference)),
1749 previous,
1750 (None, Sender::Magi, Some(display)),
1751 )
1752}
1753
1754pub fn queue_magi(talk: &mut Talk, store: &Talks, text: &str) -> Result<()> {
1756 queue_magi_display(talk, store, text, None)
1757}
1758
1759pub(crate) fn queue_magi_display(
1761 talk: &mut Talk,
1762 store: &Talks,
1763 text: &str,
1764 display: Option<crate::prompt::NoticeDisplay>,
1765) -> Result<()> {
1766 queue_keyed(
1767 talk,
1768 store,
1769 text,
1770 Vec::new(),
1771 None,
1772 &|_| false,
1773 (None, Sender::Magi, display),
1774 )
1775 .map(|_| ())
1776}
1777
1778fn queue_keyed(
1779 talk: &mut Talk,
1780 store: &Talks,
1781 text: &str,
1782 attachments: Vec<Attachment>,
1783 key: Option<(&str, Option<&crate::chat_notify::CompletionReference>)>,
1784 previous: &dyn Fn(&str) -> bool,
1785 source: (
1786 Option<ReplyTarget>,
1787 Sender,
1788 Option<crate::prompt::NoticeDisplay>,
1789 ),
1790) -> Result<bool> {
1791 if text.trim().is_empty() && attachments.is_empty() {
1793 bail!("nothing to say");
1794 }
1795 let _guard = store.guard()?;
1796 let mut fresh = store
1797 .get(&talk.id)
1798 .with_context(|| format!("talk {} was deleted", talk.short()))?;
1799 if !fresh.status.open() {
1800 bail!(
1801 "talk {} is {} and takes no more turns",
1802 fresh.short(),
1803 fresh.status.as_str()
1804 );
1805 }
1806 if !append_pending(&mut fresh, text, attachments, key, previous, source)? {
1807 *talk = fresh;
1808 return Ok(false);
1809 }
1810 store.put(&mut fresh)?;
1811 *talk = fresh;
1812 Ok(true)
1813}
1814
1815pub(crate) fn try_queue_consult(
1819 store: &Talks,
1820 id: &str,
1821 text: &str,
1822 display: Option<crate::prompt::NoticeDisplay>,
1823) -> Result<Option<()>> {
1824 let Some(_guard) = store.try_guard()? else {
1825 return Ok(None);
1826 };
1827 let mut fresh = store.get(id).context("read consultation destination")?;
1828 fresh.status = TalkStatus::Open;
1829 append_pending(
1830 &mut fresh,
1831 text,
1832 Vec::new(),
1833 None,
1834 &|_| false,
1835 (None, Sender::Magi, display),
1836 )?;
1837 store.put(&mut fresh)?;
1838 Ok(Some(()))
1839}
1840
1841fn append_pending(
1842 fresh: &mut Talk,
1843 text: &str,
1844 attachments: Vec<Attachment>,
1845 key: Option<(&str, Option<&crate::chat_notify::CompletionReference>)>,
1846 previous: &dyn Fn(&str) -> bool,
1847 source: (
1848 Option<ReplyTarget>,
1849 Sender,
1850 Option<crate::prompt::NoticeDisplay>,
1851 ),
1852) -> Result<bool> {
1853 if let Some((key, reference)) = key {
1854 if fresh.notified.iter().any(|k| k == key || previous(k)) {
1855 return Ok(false);
1856 }
1857 fresh.notified.push(key.to_owned());
1858 if let Some(reference) = reference {
1859 fresh.completion_notices.push(reference.clone());
1860 }
1861 }
1862 let (target, provenance, display) = source;
1863 let reply = resolve_reply(fresh, target)?;
1864 if fresh.pending_messages.is_empty()
1865 && (!fresh.pending.is_empty() || !fresh.pending_attachments.is_empty())
1866 {
1867 fresh.pending_messages.push(Message {
1868 display: None,
1869 sender: None,
1870 body: fresh.pending.clone(),
1871 attachments: fresh.pending_attachments.clone(),
1872 reply: None,
1873 });
1874 }
1875 fresh.pending_messages.push(Message {
1876 display,
1877 sender: Some(provenance),
1878 body: text.to_owned(),
1879 attachments: attachments.clone(),
1880 reply,
1881 });
1882 if !text.is_empty() {
1883 if fresh.pending.is_empty() {
1884 fresh.pending = text.to_owned();
1885 fresh.pending_breaks = Some(Vec::new());
1886 } else {
1887 fresh.pending.push_str("\n\n");
1888 if let Some(b) = fresh.pending_breaks.as_mut() {
1889 b.push(fresh.pending.len());
1890 }
1891 fresh.pending.push_str(text);
1892 }
1893 }
1894 fresh.pending_attachments.extend(attachments);
1895 Ok(true)
1896}
1897
1898pub fn post(store: &Talks, talk_id: &str, body: &str, by: &str) -> Result<()> {
1903 let body = body.trim();
1904 if body.is_empty() {
1905 bail!("nothing to post");
1906 }
1907 let _guard = store.guard()?;
1908 let mut fresh = store
1909 .get(talk_id)
1910 .with_context(|| format!("talk {talk_id} does not exist"))?;
1911 if !fresh.status.open() {
1912 bail!(
1913 "talk {} is closed and takes no more messages",
1914 fresh.short()
1915 );
1916 }
1917 fresh.turns.push(Turn {
1918 sender: Some(Sender::Magi),
1919 who: Who::Agent,
1920 body: body.to_owned(),
1921 at: Timestamp::now(),
1922 attachments: Vec::new(),
1923 usage: None,
1924 breaks: None,
1925 messages: Vec::new(),
1926 posted_by: Some(by.to_owned()),
1927 });
1928 store.put(&mut fresh)
1929}
1930
1931fn posts_read_through(talk: &Talk) -> usize {
1933 talk.posts_read_through.unwrap_or_else(|| {
1934 talk.turns
1935 .iter()
1936 .rposition(|t| t.who != Who::Operator && t.posted_by.is_none())
1937 .map_or(0, |i| i + 1)
1938 })
1939}
1940
1941pub fn posts_since_last_reply(talk: &Talk) -> Option<String> {
1943 let posts: Vec<&Turn> = talk
1944 .turns
1945 .iter()
1946 .skip(posts_read_through(talk))
1947 .filter(|t| t.posted_by.is_some())
1948 .collect();
1949 if posts.is_empty() {
1950 return None;
1951 }
1952 let mut out = String::from("# Posted by a task\n\n");
1953 for t in posts {
1954 out.push_str(&format!(
1955 "Task seat {} posted to this conversation: {}\n\n",
1956 short(t.posted_by.as_deref().unwrap_or_default()),
1957 t.body
1958 ));
1959 }
1960 Some(out)
1961}
1962
1963pub fn drain(talk: &mut Talk, store: &Talks) -> Result<Option<String>> {
1965 let _guard = store.guard()?;
1966 let mut fresh = store
1967 .get(&talk.id)
1968 .with_context(|| format!("talk {} was deleted", talk.short()))?;
1969 if !fresh.status.open() || (fresh.pending.is_empty() && fresh.pending_attachments.is_empty()) {
1970 *talk = fresh;
1971 return Ok(None);
1972 }
1973 let text = std::mem::take(&mut fresh.pending);
1974 let attachments = std::mem::take(&mut fresh.pending_attachments);
1975 let breaks = fresh.pending_breaks.take();
1976 let messages = std::mem::take(&mut fresh.pending_messages);
1977 fresh.turns.push(Turn {
1978 sender: Some(Sender::Operator),
1979 who: Who::Operator,
1980 body: text.clone(),
1981 at: Timestamp::now(),
1982 attachments,
1983 usage: None,
1984 breaks,
1985 messages,
1986 posted_by: None,
1987 });
1988 store.put(&mut fresh)?;
1989 *talk = fresh;
1990 Ok(Some(text))
1991}
1992
1993pub async fn say(
1996 lease: &TurnLease,
1997 talk: &mut Talk,
1998 store: &Talks,
1999 cfg: &Config,
2000 text: &str,
2001 attachments: Vec<Attachment>,
2002) -> Result<()> {
2003 check_lease(lease, talk)?;
2004 let text = record(talk, store, text, attachments)?;
2005 respond(lease, talk, store, cfg, &text).await
2006}
2007
2008pub async fn respond(
2014 lease: &TurnLease,
2015 talk: &mut Talk,
2016 store: &Talks,
2017 cfg: &Config,
2018 text: &str,
2019) -> Result<()> {
2020 check_lease(lease, talk)?;
2021 lease
2022 .beating(turn(talk, store, cfg, text))
2023 .await
2024 .and_then(|done| done)
2025}
2026
2027fn check_lease(lease: &TurnLease, talk: &Talk) -> Result<()> {
2028 if lease.talk != talk.id {
2029 bail!("the turn lease is for talk {}, not {}", lease.talk, talk.id);
2030 }
2031 if !lease.holds() {
2034 bail!("the turn lease for talk {} is no longer held", talk.short());
2035 }
2036 Ok(())
2037}
2038
2039pub fn close(talk: &mut Talk, store: &Talks) -> Result<()> {
2057 let _guard = store.guard()?;
2058 let mut fresh = store
2059 .get(&talk.id)
2060 .with_context(|| format!("talk {} was deleted", talk.short()))?;
2061 fresh.status = TalkStatus::Closed;
2062 fresh.pending.clear();
2064 fresh.pending_breaks = None;
2065 fresh.pending_messages.clear();
2066 fresh.pending_attachments.clear();
2067 store.put(&mut fresh)?;
2068 *talk = fresh;
2069 Ok(())
2070}
2071
2072pub fn reopen(talk: &mut Talk, store: &Talks) -> Result<()> {
2083 let _guard = store.guard()?;
2084 let mut fresh = store
2085 .get(&talk.id)
2086 .with_context(|| format!("talk {} was deleted", talk.short()))?;
2087 fresh.status = TalkStatus::Open;
2088 store.put(&mut fresh)?;
2089 *talk = fresh;
2090 Ok(())
2091}
2092
2093pub fn switch_agent(talk: &mut Talk, store: &Talks, spec: &AgentSpec) -> Result<bool> {
2106 let _guard = store.guard()?;
2107 let mut fresh = store
2108 .get(&talk.id)
2109 .with_context(|| format!("talk {} was deleted", talk.short()))?;
2110 if fresh.agent == spec.id {
2111 *talk = fresh;
2112 return Ok(false);
2113 }
2114 let from = std::mem::replace(&mut fresh.agent, spec.id.clone());
2115 fresh.seat = SeatState::new(SEAT, &spec.id, crate::rng::entropy());
2116 fresh.fallback = false;
2118 fresh.turns.push(Turn {
2119 sender: Some(Sender::Magi),
2120 breaks: None,
2121 messages: Vec::new(),
2122 posted_by: None,
2123 who: Who::Agent,
2124 body: format!("{MAGI_NOTE}agent changed from {from} to {}", spec.id),
2125 at: Timestamp::now(),
2126 attachments: Vec::new(),
2127 usage: None,
2128 });
2129 store.put(&mut fresh)?;
2130 *talk = fresh;
2131 Ok(true)
2132}
2133
2134pub fn switch_persona(talk: &mut Talk, store: &Talks, id: &str) -> Result<bool> {
2142 let id = if id.trim() == crate::persona::DEFAULT_ID {
2143 ""
2144 } else {
2145 id.trim()
2146 };
2147 let _guard = store.guard()?;
2148 let mut fresh = store
2149 .get(&talk.id)
2150 .with_context(|| format!("talk {} was deleted", talk.short()))?;
2151 if fresh.persona == id {
2152 *talk = fresh;
2153 return Ok(false);
2154 }
2155 let from = std::mem::replace(&mut fresh.persona, id.to_owned());
2156 fresh.persona_dirty = true;
2157 let label = |p: &str| {
2158 if p.is_empty() {
2159 crate::persona::DEFAULT_ID.to_owned()
2160 } else {
2161 p.to_owned()
2162 }
2163 };
2164 fresh.turns.push(Turn {
2165 sender: Some(Sender::Magi),
2166 breaks: None,
2167 messages: Vec::new(),
2168 posted_by: None,
2169 who: Who::Agent,
2170 body: format!(
2171 "{MAGI_NOTE}persona changed from {} to {}",
2172 label(&from),
2173 label(id)
2174 ),
2175 at: Timestamp::now(),
2176 attachments: Vec::new(),
2177 usage: None,
2178 });
2179 store.put(&mut fresh)?;
2180 *talk = fresh;
2181 Ok(true)
2182}
2183
2184pub fn clear_pending(talk: &mut Talk, store: &Talks) -> Result<()> {
2186 let _guard = store.guard()?;
2187 let mut fresh = store
2188 .get(&talk.id)
2189 .with_context(|| format!("talk {} was deleted", talk.short()))?;
2190 fresh.pending.clear();
2191 fresh.pending_breaks = None;
2192 fresh.pending_messages.clear();
2193 fresh.pending_attachments.clear();
2194 store.put(&mut fresh)?;
2195 *talk = fresh;
2196 Ok(())
2197}
2198
2199pub fn clear_pending_if_matches(
2201 talk: &mut Talk,
2202 store: &Talks,
2203 expected_text: &str,
2204 expected_attachments: &[String],
2205) -> Result<bool> {
2206 let _guard = store.guard()?;
2207 let mut fresh = store
2208 .get(&talk.id)
2209 .with_context(|| format!("talk {} was deleted", talk.short()))?;
2210 if !pending_matches(&fresh, expected_text, expected_attachments) {
2211 *talk = fresh;
2212 return Ok(false);
2213 }
2214 fresh.pending.clear();
2215 fresh.pending_breaks = None;
2216 fresh.pending_messages.clear();
2217 fresh.pending_attachments.clear();
2218 store.put(&mut fresh)?;
2219 *talk = fresh;
2220 Ok(true)
2221}
2222
2223pub fn edit_pending_text(
2227 talk: &mut Talk,
2228 store: &Talks,
2229 text: &str,
2230 expected_text: &str,
2231 expected_attachments: &[String],
2232) -> Result<bool> {
2233 edit_pending_message(talk, store, text, expected_text, expected_attachments, None)
2234}
2235
2236pub fn edit_pending_message(
2238 talk: &mut Talk,
2239 store: &Talks,
2240 text: &str,
2241 expected_text: &str,
2242 expected_attachments: &[String],
2243 message: Option<usize>,
2244) -> Result<bool> {
2245 let _guard = store.guard()?;
2246 let mut fresh = store
2247 .get(&talk.id)
2248 .with_context(|| format!("talk {} was deleted", talk.short()))?;
2249 if !pending_matches(&fresh, expected_text, expected_attachments) {
2250 *talk = fresh;
2251 return Ok(false);
2252 }
2253 if fresh
2254 .pending_messages
2255 .iter()
2256 .enumerate()
2257 .any(|(i, m)| m.sender == Some(Sender::Magi) && message.is_none_or(|index| index == i))
2258 {
2259 bail!("MAGI messages cannot be edited");
2260 }
2261 if let Some(index) = message {
2262 let edited = fresh
2263 .pending_messages
2264 .get_mut(index)
2265 .context("invalid queued message")?;
2266 if text.trim().is_empty() && edited.attachments.is_empty() {
2267 fresh.pending_messages.remove(index);
2268 } else {
2269 edited.body = text.to_owned();
2270 }
2271 fresh.pending.clear();
2272 fresh.pending_breaks = Some(Vec::new());
2273 fresh.pending_attachments.clear();
2274 for message in &fresh.pending_messages {
2275 if !message.body.is_empty() {
2276 if !fresh.pending.is_empty() {
2277 fresh.pending.push_str("\n\n");
2278 fresh
2279 .pending_breaks
2280 .as_mut()
2281 .expect("initialized")
2282 .push(fresh.pending.len());
2283 }
2284 fresh.pending.push_str(&message.body);
2285 }
2286 fresh
2287 .pending_attachments
2288 .extend(message.attachments.clone());
2289 }
2290 } else {
2291 if fresh.pending_messages.len() > 1
2292 && fresh.pending_messages.iter().any(|m| m.reply.is_some())
2293 {
2294 bail!("edit queued replies individually");
2295 }
2296 let reply = fresh.pending_messages.first().and_then(|m| m.reply.clone());
2297 fresh.pending_messages = vec![Message {
2298 display: None,
2299 sender: Some(Sender::Operator),
2300 body: text.to_owned(),
2301 attachments: fresh.pending_attachments.clone(),
2302 reply,
2303 }];
2304 fresh.pending = text.to_owned();
2305 fresh.pending_breaks = Some(Vec::new());
2306 }
2307 store.put(&mut fresh)?;
2308 *talk = fresh;
2309 Ok(true)
2310}
2311
2312fn pending_matches(talk: &Talk, expected_text: &str, expected_attachments: &[String]) -> bool {
2313 talk.pending == expected_text
2314 && talk
2315 .pending_attachments
2316 .iter()
2317 .map(|attachment| &attachment.id)
2318 .eq(expected_attachments.iter())
2319}
2320
2321async fn turn(talk: &mut Talk, store: &Talks, cfg: &Config, text: &str) -> Result<()> {
2328 let text = talk
2332 .turns
2333 .last()
2334 .filter(|t| t.who == Who::Operator && t.body == text)
2335 .map(|turn| message_prompt(turn, talk, store))
2336 .unwrap_or_else(|| text.to_owned());
2337 let evidence = crate::chat_notify::response_evidence(talk).await;
2338 let text = format!("{text}{evidence}");
2339 let prompt_turns = talk.turns.len();
2340 talk.posts_read_through = Some(posts_read_through(talk));
2341 let spec = cfg
2342 .agents
2343 .iter()
2344 .find(|a| a.id == talk.agent)
2345 .with_context(|| {
2346 format!(
2347 "talk {} was opened with agent `{}`, which is no longer in \
2348 the roster; restore it in magi.toml or start a new \
2349 conversation",
2350 talk.short(),
2351 talk.agent
2352 )
2353 })?;
2354
2355 let last_note = attachment_note(
2359 store,
2360 &talk.id,
2361 talk.turns
2362 .last()
2363 .map_or(&[][..], |t| t.attachments.as_slice()),
2364 );
2365
2366 let attachment_paths: Vec<PathBuf> = talk
2372 .turns
2373 .iter()
2374 .flat_map(|t| t.attachments.iter())
2375 .filter_map(|a| store.attachment_path(&talk.id, a))
2376 .collect();
2377
2378 let questions =
2389 crate::run::try_home().map(|home| crate::ask::Questions::at(home.join("questions")));
2390 let consult_roots = questions.as_ref().map_or_else(Vec::new, |questions| {
2391 crate::consult::answer_write_roots(questions, store, talk)
2392 });
2393 let consulted = !consult_roots.is_empty();
2394
2395 let (allow_write, unsandboxed) = turn_access(cfg.talk.allow_write, consulted);
2396
2397 let artifacts = store.artifacts_of(&talk.id);
2398 let operator_turns = talk.turns.iter().filter(|t| t.who == Who::Operator).count();
2401 let stem = format!("turn-{}", operator_turns.max(1));
2402 let cache_dir = cfg.cache_dir();
2405
2406 let mut chain = vec![spec.clone()];
2409 if let Some(choice) = cfg.roles.chatter.as_ref()
2410 && talk.fallback
2411 {
2412 for id in choice.ids() {
2413 if id == talk.agent || chain.iter().any(|s| s.id == id) {
2414 continue;
2415 }
2416 match agent::pick(&cfg.agents, Some(id), &agent::installed) {
2417 Ok(s) => chain.push(s),
2418 Err(e) => tracing::warn!("[roles] chatter: skipping `{id}`: {e:#}"),
2419 }
2420 }
2421 }
2422
2423 let persona = crate::persona::active(&cfg.talk.personas, &talk.persona);
2424 let operator_name = cfg.talk.operator_name();
2425 let persona_update = if talk.persona_dirty {
2426 format!(
2427 "{}\n\n",
2428 crate::persona::update_block_for(persona.as_ref(), operator_name)
2429 )
2430 } else {
2431 String::new()
2432 };
2433
2434 let filing_update = if talk.implementers_dirty {
2437 format!("{}\n\n", filing_update_block(talk.implementers))
2438 } else {
2439 String::new()
2440 };
2441
2442 let mut outcome = None;
2443 let mut fell_back_from: Option<String> = None;
2444 let mut first_try: Option<(String, SeatState)> = None;
2447 for (n, spec) in chain.iter().enumerate() {
2448 if n > 0 {
2449 if first_try.is_none() {
2450 first_try = Some((talk.agent.clone(), talk.seat.clone()));
2451 }
2452 tracing::warn!("chat: falling back from `{}` to `{}`", talk.agent, spec.id);
2453 fell_back_from.get_or_insert_with(|| talk.agent.clone());
2456 talk.agent = spec.id.clone();
2457 talk.seat = SeatState::new(SEAT, &spec.id, crate::rng::entropy());
2458 }
2459 let resuming = agent::has_session(spec.kind, &talk.seat, cfg.graph.sessions);
2460 let first_ever = talk.turns.len() <= 1;
2461 let body = if talk.seat.turns == 0 && first_ever {
2462 format!(
2463 "{}\n\n# Operator\n\n{text}{last_note}",
2464 briefing_for(
2465 &talk.repo,
2466 &cfg.graph.language,
2467 cfg.talk.allow_write,
2468 persona.as_ref(),
2469 operator_name,
2470 talk.implementers
2471 )
2472 )
2473 } else if talk.seat.turns == 0 {
2474 format!(
2477 "{}\n\n{}\n\n# Operator\n\n{text}{last_note}",
2478 briefing_for(
2479 &talk.repo,
2480 &cfg.graph.language,
2481 cfg.talk.allow_write,
2482 persona.as_ref(),
2483 operator_name,
2484 talk.implementers
2485 ),
2486 transcript(talk, store)
2487 )
2488 } else if resuming {
2489 let posts = posts_since_last_reply(talk).unwrap_or_default();
2490 format!("{persona_update}{filing_update}{posts}{text}{last_note}")
2491 } else {
2492 let mut standing = match (&persona, talk.persona_dirty) {
2496 (Some(p), false) => format!("{}\n", crate::persona::section_for(p, operator_name)),
2497 _ => persona_update.clone(),
2498 };
2499 if let (None, Some(n)) = (&persona, operator_name) {
2502 standing.push_str(&format!(
2503 "# Addressing the operator\n{}\n",
2504 crate::persona::addressing(n)
2505 ));
2506 }
2507 if talk.implementers_dirty || talk.implementers != 1 {
2508 standing.push_str(&format!("{}\n\n", filing_update_block(talk.implementers)));
2509 }
2510 format!("{}\n\n{standing}{text}{last_note}", transcript(talk, store))
2511 };
2512 let current_approvals = questions
2515 .as_ref()
2516 .map(|store| {
2517 store
2518 .list()
2519 .iter()
2520 .filter(|q| {
2521 q.status.open()
2522 && q.node == crate::land::APPROVAL_NODE
2523 && q.consult.as_ref().is_some_and(|c| c.talk == talk.id)
2524 })
2525 .map(crate::prompt::chat_consult)
2526 .collect::<Vec<_>>()
2527 .join("\n\n")
2528 })
2529 .unwrap_or_default();
2530 let body = if current_approvals.is_empty() {
2531 body
2532 } else {
2533 format!("{current_approvals}\n\n# Current operator message\n\n{body}")
2534 };
2535 let attempt_stem = if n == 0 {
2536 stem.clone()
2537 } else {
2538 format!("{stem}-{}", spec.id)
2539 };
2540 let inv = Invocation {
2541 coordination: cfg.coordination.as_ref(),
2542 cwd: &talk.repo,
2543 prompt: &body,
2544 timeout: turn_timeout(cfg),
2545 allow_write,
2550 unsandboxed,
2551 sessions: cfg.graph.sessions,
2552 artifacts: &artifacts,
2553 stem: &attempt_stem,
2554 run: &talk.id,
2557 node: crate::queue::CHAT_NODE,
2558 cache_dir: cache_dir.as_deref(),
2559 attachments: &attachment_paths,
2560 writable: &consult_roots,
2561 };
2562 let result = agent::invoke(spec, &mut talk.seat, &inv).await;
2563 let advance = agent::chain_advances(&result);
2564 if n == 0 || !advance {
2565 outcome = Some(result);
2566 } else {
2567 tracing::warn!("chat: fallback agent `{}` also failed", spec.id);
2569 }
2570 if !advance {
2571 break;
2572 }
2573 }
2574 if outcome.as_ref().is_some_and(agent::chain_advances) {
2575 if let Some((id, seat)) = first_try {
2578 talk.agent = id;
2579 talk.seat = seat;
2580 fell_back_from = None;
2581 }
2582 }
2583 let outcome = outcome.expect("a chain holds at least one agent");
2584 let note = |why: String| Turn {
2585 sender: Some(Sender::Magi),
2586 breaks: None,
2587 messages: Vec::new(),
2588 posted_by: None,
2589 who: Who::Agent,
2590 body: format!("{MAGI_NOTE}{why}"),
2591 at: Timestamp::now(),
2592 attachments: Vec::new(),
2593 usage: None,
2594 };
2595 let (reply, failure) = match outcome {
2596 Err(e) => (
2597 note(format!("could not run agent `{}`: {e}", talk.agent)),
2598 Some(format!("could not run agent `{}`: {e}", talk.agent)),
2599 ),
2600 Ok(out) if out.quota_exhausted() => {
2601 let reset = out
2602 .quota
2603 .as_ref()
2604 .and_then(|q| q.reset.clone())
2605 .map_or_else(String::new, |r| format!(" (resets {r})"));
2606 let why = format!(
2607 "agent `{}` is out of quota{reset}; your message is saved, so \
2608 say it again when the window reopens",
2609 talk.agent
2610 );
2611 (note(why.clone()), Some(why))
2612 }
2613 Ok(out) if out.timed_out => {
2614 let why = format!(
2615 "agent `{}` did not answer within {}s; your message is saved",
2616 talk.agent,
2617 turn_timeout(cfg).as_secs()
2618 );
2619 (note(why.clone()), Some(why))
2620 }
2621 Ok(out) if !out.usable() => {
2622 let why = format!(
2623 "agent `{}` produced no answer (exit {}); your message is saved",
2624 talk.agent,
2625 out.exit_code
2626 .map_or_else(|| "unknown".to_owned(), |c| c.to_string())
2627 );
2628 (note(why.clone()), Some(why))
2629 }
2630 Ok(out) => (
2631 Turn {
2632 sender: Some(Sender::Persona),
2633 breaks: None,
2634 messages: Vec::new(),
2635 posted_by: None,
2636 who: Who::Agent,
2637 body: out.text.trim().to_owned(),
2638 at: Timestamp::now(),
2639 attachments: Vec::new(),
2640 usage: out.context_tokens.map(|context_tokens| TurnUsage {
2643 context_tokens,
2644 agent: talk.agent.clone(),
2645 model: cfg
2646 .agents
2647 .iter()
2648 .find(|a| a.id == talk.agent)
2649 .and_then(|a| a.model.clone()),
2650 }),
2651 },
2652 None,
2653 ),
2654 };
2655
2656 let _guard = store.guard()?;
2668 let Ok(fresh) = store.get(&talk.id) else {
2674 return Ok(());
2675 };
2676 talk.status = fresh.status;
2677 talk.pending = fresh.pending;
2681 talk.pending_breaks = fresh.pending_breaks;
2682 talk.pending_messages = fresh.pending_messages;
2683 talk.pending_attachments = fresh.pending_attachments;
2684 talk.notified = fresh.notified;
2685 if fresh.turns.len() > talk.turns.len() {
2687 let posted: Vec<Turn> = fresh.turns[talk.turns.len()..]
2688 .iter()
2689 .filter(|t| t.posted_by.is_some())
2690 .cloned()
2691 .collect();
2692 talk.turns.extend(posted);
2693 }
2694 if let Some(from) = fell_back_from.filter(|_| failure.is_none()) {
2695 talk.turns.push(note(format!(
2698 "agent changed from {from} to {} (fallback)",
2699 talk.agent
2700 )));
2701 }
2702 if failure.is_none() {
2705 talk.persona_dirty = false;
2706 talk.implementers_dirty = false;
2707 talk.posts_read_through = Some(prompt_turns);
2708 }
2709 talk.turns.push(reply);
2710 if let Err(put_err) = store.put(talk) {
2711 let lost = talk.turns.pop().expect("just pushed above");
2720 let stash = stash_lost_turn(store, &talk.id, &stem, &lost);
2721 let why = match &stash {
2722 Ok(path) => format!(
2723 "agent `{}` answered, but the reply could not be saved to \
2724 this conversation ({put_err:#}); the raw text was kept at \
2725 {} - your message is saved, ask again",
2726 talk.agent,
2727 path.display()
2728 ),
2729 Err(stash_err) => format!(
2730 "agent `{}` answered, but the reply could not be saved to \
2731 this conversation ({put_err:#}), and it could not be kept \
2732 anywhere else either ({stash_err:#}); your message is \
2733 saved, ask again",
2734 talk.agent
2735 ),
2736 };
2737 talk.turns.push(note(why.clone()));
2738 return match store.put(talk) {
2745 Ok(()) => bail!("{why}"),
2746 Err(note_err) => {
2747 talk.turns.pop();
2767 Err(note_err).context(why)
2768 }
2769 };
2770 }
2771
2772 match failure {
2773 Some(why) => bail!("{why}"),
2774 None => Ok(()),
2775 }
2776}
2777
2778fn transcript(talk: &Talk, store: &Talks) -> String {
2781 let mut out = String::from(
2782 "This conversation cannot resume on the CLI's side, so here is \
2783 everything said so far; answer only the last message.\n",
2784 );
2785 for t in &talk.turns {
2786 let who = match t.who {
2787 Who::Operator => "operator",
2788 Who::Agent if t.body.starts_with(MAGI_NOTE) => "magi",
2789 Who::Agent => "you",
2790 };
2791 out.push_str(&format!(
2792 "\n## {who}\n\n{}\n",
2793 message_prompt(t, talk, store).trim()
2794 ));
2795 out.push_str(&attachment_note(store, &talk.id, &t.attachments));
2796 }
2797 out
2798}
2799
2800fn attachment_note(store: &Talks, talk_id: &str, attachments: &[Attachment]) -> String {
2805 if attachments.is_empty() {
2806 return String::new();
2807 }
2808 let mut out = String::from(
2809 "\n\nThe operator attached the image(s) below to this message. Open \
2810 and look at each one before you answer.\n",
2811 );
2812 for att in attachments {
2813 if let Some(path) = store.attachment_path(talk_id, att) {
2814 out.push_str(&format!("\n- {} ({})", path.display(), att.mime));
2815 }
2816 }
2817 out.push('\n');
2818 out
2819}
2820
2821pub(crate) fn turn_access(talk_allow_write: bool, consulted: bool) -> (bool, bool) {
2832 (talk_allow_write || consulted, talk_allow_write)
2833}
2834
2835pub fn briefing(repo: &Path, language: &str, allow_write: bool) -> String {
2851 briefing_with(repo, language, allow_write, None, None)
2852}
2853
2854pub fn briefing_with(
2859 repo: &Path,
2860 language: &str,
2861 allow_write: bool,
2862 persona: Option<&crate::persona::Persona>,
2863 operator_name: Option<&str>,
2864) -> String {
2865 briefing_for(repo, language, allow_write, persona, operator_name, 1)
2866}
2867
2868pub const MAX_IMPLEMENTERS: u8 = 3;
2870
2871fn solo_implementers() -> u8 {
2872 1
2873}
2874
2875fn filing_flag(n: u8) -> String {
2878 if n <= 1 {
2879 "--solo".to_owned()
2880 } else {
2881 format!("--implementers {n}")
2882 }
2883}
2884
2885pub fn filing_update_block(n: u8) -> String {
2888 let flag = filing_flag(n);
2889 if n <= 1 {
2890 format!(
2891 "# Task filing update\n\nThe operator changed how many implementers tasks use. \
2892 From now on file with `magi task add {flag} --repo <repo> <instruction>` \
2893 (one implementer, straight into review).\n"
2894 )
2895 } else {
2896 format!(
2897 "# Task filing update\n\nThe operator changed how many implementers tasks use. \
2898 From now on file with `magi task add {flag} --repo <repo> <instruction>` \
2899 ({n} independent implementations compete). Do not pass `--solo` \
2900 together with `--implementers`; drop any earlier `--solo`.\n"
2901 )
2902 }
2903}
2904
2905pub fn check_implementers(n: u8, cfg: &crate::config::Config) -> std::result::Result<u8, String> {
2908 if !(1..=MAX_IMPLEMENTERS).contains(&n) {
2909 return Err(format!(
2910 "implementers must be 1..={MAX_IMPLEMENTERS}, got {n}"
2911 ));
2912 }
2913 if n > 1 {
2914 let mut cfg = cfg.clone();
2915 crate::queue::RunOverrides {
2916 candidates: Some(usize::from(n)),
2917 ..Default::default()
2918 }
2919 .apply(&mut cfg);
2920 cfg.resolve_roles()
2921 .map_err(|e| format!("{n} implementers is not allowed here: {e:#}"))?;
2922 }
2923 Ok(n)
2924}
2925
2926pub fn switch_implementers(talk: &mut Talk, store: &Talks, n: u8) -> Result<bool> {
2929 let _guard = store.guard()?;
2930 let mut fresh = store
2931 .get(&talk.id)
2932 .with_context(|| format!("talk {} was deleted", talk.short()))?;
2933 if fresh.implementers == n {
2934 *talk = fresh;
2935 return Ok(false);
2936 }
2937 let from = std::mem::replace(&mut fresh.implementers, n);
2938 fresh.implementers_dirty = true;
2939 fresh.turns.push(Turn {
2940 sender: Some(Sender::Magi),
2941 breaks: None,
2942 messages: Vec::new(),
2943 posted_by: None,
2944 who: Who::Agent,
2945 body: format!("{MAGI_NOTE}implementers changed from {from} to {n}"),
2946 at: Timestamp::now(),
2947 attachments: Vec::new(),
2948 usage: None,
2949 });
2950 store.put(&mut fresh)?;
2951 *talk = fresh;
2952 Ok(true)
2953}
2954
2955pub fn briefing_for(
2958 repo: &Path,
2959 language: &str,
2960 allow_write: bool,
2961 persona: Option<&crate::persona::Persona>,
2962 operator_name: Option<&str>,
2963 implementers: u8,
2964) -> String {
2965 let flag = filing_flag(implementers);
2966 let shape = if implementers <= 1 {
2967 "Use --solo: it runs the task through one implementer \
2968 straight into review instead of the usual multi-agent competition, \
2969 which is the right shape for a change this conversation has already \
2970 settled, rather than one still worth several independent takes."
2971 .to_owned()
2972 } else {
2973 format!(
2974 "Use --implementers {implementers}: it has {implementers} \
2975 implementers work on the task independently and compete, which \
2976 is the right shape when several independent takes are worth \
2977 having. Never add --solo to it; the two do not go together."
2978 )
2979 };
2980 let write_policy = if allow_write {
2981 "Write access is enabled for this conversation (`allow_write = \
2982 true`), so you may write files - but only a small, \
2983 already-decided edit the operator names outright in this \
2984 conversation, not an implementation. This is a permission on the \
2985 conversation as a whole, not a property of whichever repository \
2986 it happened to start in: if the operator names a different \
2987 repository for that small edit, the policy allows it there too. \
2988 Your own tool may still confine writes to the repository this \
2989 conversation started in regardless - if a write elsewhere is \
2990 refused, say so plainly rather than working around it. Once you \
2991 have made an edit, say plainly what you edited. Anything bigger, \
2992 or anything still open-ended, still goes through the queue below \
2993 rather than being done here."
2994 } else {
2995 "Do not write files. Implementing a change is not this \
2996 conversation's job; a separate, blind competition of agents does \
2997 that, and a repository this conversation has already edited would \
2998 make their diffs unjudgeable."
2999 };
3000 let mut out = format!(
3001 "You are magi's standing conversation partner for its operator, who \
3002 usually has this open on a phone. Keep replies short: no preamble, \
3003 no restating what they just said.\n\n\
3004 # Repository\n\n{repo}\n\n\
3005 You may look around: read files, run shell commands, search history, \
3006 run tests - whatever answers the question. {write_policy}\n\n\
3007 A short, command-shaped message (\"list\", \"info <id>\", \"show \
3008 3cbf\") is almost always the operator asking you to look something \
3009 up, not an instruction to file - answer it yourself with `magi \
3010 list`, `magi show <id>`, `magi task list`, or the like, the same way \
3011 you would answer any other question in this conversation.\n\n\
3012 # Answering existing questions\n\n\
3013 Consultation delivery does not restrict an explicit owner decision. \
3014 Use `magi answer <full-question-id> --reply <exact offered choice> --quote <entire latest owner message>`. \
3015 Direct instructions bind `<full-question-id>: <exact offered choice>`. \
3016 An explicit batch instruction (including `おっけーそれぞれ回答してー`) authorizes \
3017 the immediately preceding persisted recommendations, one row per question: \
3018 `<full-question-id>: <exact offered choice>` or a table with separate ID and choice cells. \
3019 Hold, obsolete-approval dismissal, repair/re-review and non-destructive recovery choices \
3020 may be delegated this way, including cross-chat and never-consulted questions. \
3021 Merge requires `<full-question-id>: merge <displayed head>`. Withdrawal, PR closure, \
3022 replacement that closes the old PR, discard and task completion require an individual \
3023 exact consequence instruction; a batch instruction is insufficient. Public posting requires \
3024 the exact question/content fingerprint reported by the answer command. `use my text` \
3025 requires the question/content fingerprint followed by a newline and the literal replacement title. Report the exact missing evidence. \
3026 Never create another driver or task to apply an answer: existing execution transitions \
3027 retain their state, ownership and confirmation checks. A busy original consultation must \
3028 finish before a non-hold answer. A hold grants no closure or withdrawal. \
3029 Thanks, silence, recommendations alone, conditional/retracted instructions and generated \
3030 messages are not owner authorization.\n\n\
3031 # When the operator wants something done\n\n\
3032 Run:\n\n\
3033 magi task add {flag} --repo {repo} <instruction>\n\n\
3034 and tell the operator the task id it prints, so they can follow it \
3035 from the Queue. If it refuses with a duplicate warning (the \
3036 instruction names a branch, commit or pull request that an \
3037 unfinished task, run or PR already owns), do not repeat it with \
3038 --force yourself: tell the operator what it matched and let them \
3039 decide. Write <instruction> so that an implementer who has \
3040 never seen this conversation can act on it alone - it is everything \
3041 they get. {shape}\n\n\
3042 If the operator asks for something in a different repository, \
3043 --repo does not have to be a full path: --repo owner/repo (or just \
3044 repo, when that is unambiguous) is resolved against local checkouts \
3045 the same way `magi repos` lists them. If the command fails because \
3046 nothing matches or more than one checkout shares that name, ask the \
3047 operator which repository they mean (or run `magi repos` yourself \
3048 to see the candidates) rather than guessing.\n\n\
3049 You cannot wait, and you cannot send the operator a message on your \
3050 own: you only speak when they write. A task you file reports back \
3051 into this conversation automatically when it finishes, is held or \
3052 fails, as a message headed \"{notice}\".\n\n\
3053 For a background command you run yourself, register it with \
3054 `magi talk watch --timeout 900 -- <executable> <arguments...>`, for \
3055 example `magi talk watch -- cargo test --locked`. It uses your \
3056 current directory; arguments are passed literally. For shell syntax, \
3057 explicitly call `sh -c`. Only after watch registration succeeds may \
3058 you promise a completion report. Watches default to 900 seconds, \
3059 accept at most 3600 seconds, and share four concurrent slots. Their \
3060 automatic reports resume this conversation through its own turn. \
3061 Never promise to report back on work that is neither a filed task \
3062 nor a successfully registered watch.\n\n\
3063 The current state of the code is whatever origin/main holds, not \
3064 whatever a working tree shows: a primary checkout often lags \
3065 upstream, sits on a detached HEAD and carries uncommitted changes. \
3066 Before answering about code, run `git fetch origin` in that \
3067 repository if it is cheap, then read through \
3068 `git show origin/main:<path>` or `git grep <pattern> origin/main`. \
3069 If the working tree differs, say so; if the fetch fails, say that \
3070 too, so the operator knows the answer may be stale.\n\n\
3071 If the operator attached an image (a screenshot, say) that the task \
3072 is about, pass it with `--attach <path>`, using the absolute path \
3073 the turn's attachment note gives; repeat the flag for several. \
3074 `magi task add {flag} --attach <path> <instruction>` copies the \
3075 file into the task, so the implementer receives it. Do not paste the \
3076 path into <instruction> instead: deleting this conversation deletes \
3077 its attachments, and then that path reaches no one.\n",
3078 repo = repo.display(),
3079 notice = crate::prompt::CHAT_TASK_NOTICE_HEADING,
3080 );
3081 out.push_str(&language_note(language));
3082 match (persona, operator_name) {
3083 (Some(p), n) => out.push_str(&crate::persona::section_for(p, n)),
3084 (None, Some(n)) => {
3085 out.push_str("\n# Addressing the operator\n");
3086 out.push_str(&crate::persona::addressing(n));
3087 }
3088 (None, None) => {}
3089 }
3090 out
3091}
3092
3093fn language_note(language: &str) -> String {
3096 if language.trim().is_empty() || language.eq_ignore_ascii_case("en") {
3097 String::new()
3098 } else {
3099 format!("\nHold this conversation in {language}.\n")
3100 }
3101}
3102
3103pub fn tasks_of(queue: &Queue, talk_id: &str) -> Vec<Task> {
3110 let mut tasks: Vec<Task> = queue
3111 .list()
3112 .into_iter()
3113 .filter(|t| matches!(&t.source, Source::Agent { run, .. } if run == talk_id))
3114 .collect();
3115 tasks.sort_unstable_by(|a, b| a.id.cmp(&b.id));
3116 tasks
3117}
3118
3119fn read_path(path: &Path) -> Result<Talk> {
3120 let body = std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;
3121 let mut talk: Talk =
3122 serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))?;
3123 for turn in &mut talk.turns {
3124 if turn.who == Who::Operator && turn.messages.is_empty() && turn.attachments.is_empty() {
3125 turn.messages = plain_messages(&turn.body, turn.breaks.as_deref());
3126 }
3127 }
3128 if talk.pending_messages.is_empty() && talk.pending_attachments.is_empty() {
3129 talk.pending_messages = plain_messages(&talk.pending, talk.pending_breaks.as_deref());
3130 }
3131 Ok(talk)
3132}
3133
3134fn plain_messages(body: &str, breaks: Option<&[usize]>) -> Vec<Message> {
3136 let Some(breaks) = breaks else {
3137 return Vec::new();
3138 };
3139 if body.is_empty() {
3140 return Vec::new();
3141 }
3142 let mut messages = Vec::new();
3143 let mut start = 0;
3144 for end in breaks
3145 .iter()
3146 .copied()
3147 .chain(std::iter::once(body.len() + 2))
3148 {
3149 let Some(text) = end.checked_sub(2).and_then(|end| body.get(start..end)) else {
3150 return Vec::new();
3151 };
3152 messages.push(Message {
3153 display: None,
3154 sender: None,
3155 body: text.to_owned(),
3156 attachments: Vec::new(),
3157 reply: None,
3158 });
3159 start = end;
3160 }
3161 messages
3162}
3163
3164const PUT_RETRIES: u32 = 5;
3167
3168fn write_atomic(tmp: &Path, path: &Path, body: &str) -> Result<()> {
3180 let mut last_err = None;
3181 for attempt in 0..PUT_RETRIES {
3182 if attempt > 0 {
3183 std::thread::sleep(Duration::from_millis(20 * u64::from(attempt)));
3184 }
3185 match try_write_atomic(tmp, path, body) {
3186 Ok(()) => return Ok(()),
3187 Err(e) => last_err = Some(e),
3188 }
3189 }
3190 Err(last_err.expect("the loop above always runs at least once"))
3191}
3192
3193fn try_write_atomic(tmp: &Path, path: &Path, body: &str) -> Result<()> {
3194 #[cfg(test)]
3195 if failpoint::take_forced_put_failure() {
3196 bail!("simulated write failure (test)");
3197 }
3198 std::fs::write(tmp, body).with_context(|| format!("write {}", tmp.display()))?;
3199 std::fs::rename(tmp, path).with_context(|| format!("replace {}", path.display()))?;
3200 Ok(())
3201}
3202
3203fn stash_lost_turn(store: &Talks, id: &str, stem: &str, reply: &Turn) -> Result<PathBuf> {
3208 let dir = store.artifacts_of(id);
3209 std::fs::create_dir_all(&dir).with_context(|| format!("create {}", dir.display()))?;
3210 let path = dir.join(format!("{stem}-lost.txt"));
3211 std::fs::write(&path, &reply.body).with_context(|| format!("write {}", path.display()))?;
3212 Ok(path)
3213}
3214
3215#[cfg(test)]
3222mod failpoint {
3223 use std::cell::Cell;
3224
3225 thread_local! {
3226 static FORCE_PUT_FAILURES: Cell<u32> = const { Cell::new(0) };
3227 static FORCE_NO_LINK: Cell<bool> = const { Cell::new(false) };
3228 }
3229
3230 pub(super) fn force_no_link(on: bool) {
3233 FORCE_NO_LINK.with(|c| c.set(on));
3234 }
3235
3236 pub(super) fn no_link_forced() -> bool {
3237 FORCE_NO_LINK.with(Cell::get)
3238 }
3239
3240 pub(super) fn force_put_failures(count: u32) {
3243 FORCE_PUT_FAILURES.with(|c| c.set(count));
3244 }
3245
3246 pub(super) fn take_forced_put_failure() -> bool {
3249 FORCE_PUT_FAILURES.with(|c| {
3250 let n = c.get();
3251 if n == 0 {
3252 false
3253 } else {
3254 c.set(n - 1);
3255 true
3256 }
3257 })
3258 }
3259}
3260
3261fn short(id: &str) -> &str {
3262 id.split('-').next_back().unwrap_or(id)
3263}
3264
3265fn new_id() -> String {
3266 let stamp = jiff::Zoned::now().strftime("%Y%m%d-%H%M%S");
3267 let seed = crate::rng::entropy();
3268 format!("{stamp}-{:04x}", (seed ^ (seed >> 32)) & 0xffff)
3269}
3270
3271fn attachment_ext(mime: &str) -> Option<&'static str> {
3276 match mime {
3277 "image/png" => Some("png"),
3278 "image/jpeg" => Some("jpg"),
3279 "image/gif" => Some("gif"),
3280 "image/webp" => Some("webp"),
3281 _ => None,
3282 }
3283}
3284
3285pub fn valid_attachment_id(id: &str) -> bool {
3290 id.len() == 32
3291 && id
3292 .bytes()
3293 .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
3294}
3295
3296fn new_attachment_id() -> String {
3300 let mut r = crate::rng::SplitMix64::new(crate::rng::entropy());
3301 format!("{:016x}{:016x}", r.next_u64(), r.next_u64())
3302}
3303
3304#[cfg(test)]
3305mod tests {
3306 #[test]
3307 fn turn_access_lifts_the_sandbox_only_for_the_talk_opt_in() {
3308 use super::turn_access;
3309 assert_eq!(turn_access(false, false), (false, false));
3310 assert_eq!(turn_access(true, false), (true, true));
3311 assert_eq!(turn_access(false, true), (true, false));
3313 assert_eq!(turn_access(true, true), (true, true));
3314 }
3315
3316 #[test]
3317 fn the_briefing_points_at_origin_main_not_the_working_tree() {
3318 let b = briefing(Path::new("/r"), "en", false);
3319 assert!(b.contains("origin/main"));
3320 assert!(b.contains("git show origin/main:"));
3321 }
3322 use std::collections::BTreeMap;
3323
3324 use crate::config::{AgentChoice, AgentKind, AgentSpec, Graph};
3325 use crate::queue::{Queue, Source, Task};
3326
3327 use super::*;
3328
3329 fn ctx_agent(id: &str, model: Option<&str>) -> AgentSpec {
3330 AgentSpec {
3331 id: id.to_owned(),
3332 kind: AgentKind::Command,
3333 model: model.map(str::to_owned),
3334 command: Vec::new(),
3335 extra_args: Vec::new(),
3336 env: BTreeMap::new(),
3337 prompt_delivery: None,
3338 }
3339 }
3340
3341 fn ctx_talk(agent: &str, turns: Vec<Turn>) -> Talk {
3342 Talk {
3343 recommendations: Default::default(),
3344 posts_read_through: None,
3345 pending_breaks: None,
3346 pending_messages: Vec::new(),
3347 schema: SCHEMA,
3348 id: "20260904-014455-ab12".to_owned(),
3349 repo: PathBuf::from("."),
3350 agent: agent.to_owned(),
3351 status: TalkStatus::Open,
3352 turns,
3353 pending: String::new(),
3354 pending_attachments: Vec::new(),
3355 fallback: false,
3356 persona: String::new(),
3357 persona_dirty: false,
3358 implementers: 1,
3359 implementers_dirty: false,
3360 notified: Vec::new(),
3361 completion_notices: Vec::new(),
3362 created_at: Timestamp::now(),
3363 updated_at: Timestamp::now(),
3364 seat: SeatState::new(SEAT, agent, 1),
3365 }
3366 }
3367
3368 fn reply(body: &str, usage: Option<(u64, &str, Option<&str>)>) -> Turn {
3369 Turn {
3370 sender: None,
3371 breaks: None,
3372 messages: Vec::new(),
3373 posted_by: None,
3374 who: Who::Agent,
3375 body: body.to_owned(),
3376 at: Timestamp::now(),
3377 attachments: Vec::new(),
3378 usage: usage.map(|(t, a, m)| TurnUsage {
3379 context_tokens: t,
3380 agent: a.to_owned(),
3381 model: m.map(str::to_owned),
3382 }),
3383 }
3384 }
3385
3386 fn ctx_config(windows: &[(&str, u64)]) -> Config {
3387 Config {
3388 agents: vec![
3389 ctx_agent("small", Some("small-model")),
3390 ctx_agent("big", Some("big-model")),
3391 ctx_agent("plain", None),
3392 ],
3393 context_windows: windows.iter().map(|(k, v)| ((*k).to_owned(), *v)).collect(),
3394 ..Config::default()
3395 }
3396 }
3397
3398 #[test]
3399 fn context_usage_computes_percent_and_warns_at_eighty() {
3400 let cfg = ctx_config(&[("small-model", 1000)]);
3401 let at = |tokens| {
3402 let t = ctx_talk(
3403 "small",
3404 vec![reply("hi", Some((tokens, "small", Some("small-model"))))],
3405 );
3406 context_usage(&t, Some(&cfg))
3407 };
3408 let u = at(799);
3409 assert_eq!((u.percent, u.warn, u.window), (Some(79), false, Some(1000)));
3410 let u = at(800);
3411 assert_eq!((u.percent, u.warn), (Some(80), true));
3412 let u = at(1500);
3413 assert_eq!((u.percent, u.warn), (Some(150), true));
3414 assert!(!u.since_switch);
3415 }
3416
3417 #[test]
3418 fn context_usage_is_unknown_without_usage_and_never_looks_back() {
3419 let cfg = ctx_config(&[("small-model", 1000)]);
3420 let t = ctx_talk(
3421 "small",
3422 vec![
3423 reply("old", Some((900, "small", Some("small-model")))),
3424 reply("new", None),
3425 ],
3426 );
3427 let u = context_usage(&t, Some(&cfg));
3428 assert!(u.estimated);
3430 assert_ne!(u.tokens, Some(900));
3431 assert!(u.tokens.is_some());
3432 let t = ctx_talk(
3434 "small",
3435 vec![
3436 reply("old", Some((900, "small", Some("small-model")))),
3437 reply("magi: could not run agent", None),
3438 ],
3439 );
3440 assert_eq!(context_usage(&t, Some(&cfg)).tokens, Some(900));
3441 assert_eq!(
3442 context_usage(&ctx_talk("small", Vec::new()), Some(&cfg)).tokens,
3443 None
3444 );
3445 }
3446
3447 #[test]
3448 fn estimate_counts_chars_both_sides_and_standing_prompt() {
3449 let mut t = ctx_talk("small", vec![reply("abcdefg", None)]);
3450 assert_eq!(estimate_context_tokens(&t, 0), Some(2)); let op = Turn {
3452 sender: None,
3453 who: Who::Operator,
3454 ..reply("abcdefg", None)
3455 };
3456 t.turns.push(op);
3457 assert_eq!(estimate_context_tokens(&t, 0), Some(4));
3458 assert!(
3459 estimate_context_tokens(&t, 700).unwrap() > estimate_context_tokens(&t, 0).unwrap()
3460 );
3461 let ja = ctx_talk("small", vec![reply("日本語日本語日", None)]);
3463 assert_eq!(estimate_context_tokens(&ja, 0), Some(2));
3464 let note = ctx_talk("small", vec![reply("magi: could not run agent", None)]);
3466 assert_eq!(estimate_context_tokens(¬e, 1000), None);
3467 assert_eq!(
3468 estimate_context_tokens(&ctx_talk("small", Vec::new()), 1000),
3469 None
3470 );
3471 }
3472
3473 #[test]
3474 fn context_usage_measured_wins_and_estimate_gets_percent_and_warn() {
3475 let cfg = ctx_config(&[("small-model", 1000)]);
3476 let t = ctx_talk(
3477 "small",
3478 vec![reply(
3479 &"x".repeat(5000),
3480 Some((10, "small", Some("small-model"))),
3481 )],
3482 );
3483 let u = context_usage(&t, Some(&cfg));
3484 assert_eq!((u.tokens, u.estimated), (Some(10), false));
3485 let t = ctx_talk("small", vec![reply(&"x".repeat(5000), None)]);
3486 let u = context_usage(&t, Some(&cfg));
3487 assert!(u.estimated && !u.since_switch);
3488 assert_eq!(u.window, Some(1000));
3489 assert!(u.warn && u.percent.unwrap() >= 80);
3490 let t = ctx_talk("small", vec![reply("hi", None)]);
3491 let u = context_usage(&t, Some(&cfg));
3492 assert!(u.estimated && u.percent.is_some());
3493 }
3494
3495 #[test]
3496 fn context_usage_without_a_window_shows_tokens_only() {
3497 let cfg = ctx_config(&[]);
3498 let t = ctx_talk("plain", vec![reply("hi", Some((5000, "plain", None)))]);
3500 let u = context_usage(&t, Some(&cfg));
3501 assert_eq!(
3502 (u.tokens, u.window, u.percent, u.warn),
3503 (Some(5000), None, None, false)
3504 );
3505 let t = ctx_talk(
3506 "small",
3507 vec![reply("hi", Some((5000, "small", Some("small-model"))))],
3508 );
3509 assert_eq!(context_usage(&t, Some(&cfg)).percent, None);
3510 assert_eq!(context_usage(&t, None).window, None);
3512 }
3513
3514 #[test]
3515 fn context_usage_switching_model_changes_the_denominator() {
3516 let cfg = ctx_config(&[("small-model", 1000), ("big-model", 10_000)]);
3517 let used = reply("hi", Some((900, "small", Some("small-model"))));
3518 let before = context_usage(&ctx_talk("small", vec![used.clone()]), Some(&cfg));
3519 assert_eq!(
3520 (before.percent, before.warn, before.since_switch),
3521 (Some(90), true, false)
3522 );
3523 let after = context_usage(&ctx_talk("big", vec![used]), Some(&cfg));
3526 assert_eq!(after.window, Some(10_000));
3527 assert_eq!(
3528 (after.percent, after.warn, after.since_switch),
3529 (Some(9), false, true)
3530 );
3531 assert_eq!(after.model.as_deref(), Some("big-model"));
3532 }
3533
3534 #[test]
3535 fn a_turn_recorded_before_usage_existed_still_reads() {
3536 let old = r#"{"who":"agent","body":"hi","at":"2026-09-04T01:44:55Z"}"#;
3537 let turn: Turn = serde_json::from_str(old).expect("old turn reads");
3538 assert!(turn.usage.is_none());
3539 let json = serde_json::to_string(&turn).expect("serialize");
3540 assert!(
3541 !json.contains("usage"),
3542 "absent usage is not written: {json}"
3543 );
3544 }
3545
3546 fn store() -> (tempfile::TempDir, Talks) {
3548 let tmp = tempfile::tempdir().expect("tempdir");
3549 let talks = Talks::at(tmp.path().join("talks"));
3550 (tmp, talks)
3551 }
3552
3553 fn mock_agent(dir: &Path, script: &str, env: BTreeMap<String, String>) -> AgentSpec {
3557 let path = dir.join("mock-talk-agent.sh");
3558 std::fs::write(&path, script).expect("write mock");
3559 AgentSpec {
3560 id: "mock".to_owned(),
3561 kind: AgentKind::Command,
3562 model: None,
3563 command: vec!["sh".to_owned(), path.to_string_lossy().into_owned()],
3564 extra_args: Vec::new(),
3565 env,
3566 prompt_delivery: None,
3567 }
3568 }
3569
3570 fn config(spec: AgentSpec) -> Config {
3571 Config {
3572 agents: vec![spec],
3573 graph: Graph {
3574 language: "en".to_owned(),
3575 ..Graph::default()
3576 },
3577 ..Config::default()
3578 }
3579 }
3580
3581 const REPLY: &str = "#!/bin/sh\ncat >/dev/null\nprintf '%s\\n' \"$MOCK_REPLY\"\n";
3583
3584 const BROKEN: &str = "#!/bin/sh\ncat >/dev/null\nexit 3\n";
3586
3587 const ECHO: &str = "#!/bin/sh\ncat\n";
3590
3591 fn env(reply: &str) -> BTreeMap<String, String> {
3592 BTreeMap::from([("MOCK_REPLY".to_owned(), reply.to_owned())])
3593 }
3594
3595 #[test]
3596 fn the_frozen_json_field_names_round_trip_through_disk() {
3597 let (tmp, talks) = store();
3598 let mut talk = Talk {
3599 recommendations: Default::default(),
3600 posts_read_through: None,
3601 pending_breaks: None,
3602 pending_messages: Vec::new(),
3603 schema: SCHEMA,
3604 id: "20260904-014455-ab12".to_owned(),
3605 repo: tmp.path().to_owned(),
3606 agent: "sonnet".to_owned(),
3607 status: TalkStatus::Open,
3608 turns: Vec::new(),
3609 pending: String::new(),
3610 pending_attachments: Vec::new(),
3611 fallback: false,
3612 persona: String::new(),
3613 persona_dirty: false,
3614 implementers: 1,
3615 implementers_dirty: false,
3616 notified: Vec::new(),
3617 completion_notices: Vec::new(),
3618 created_at: Timestamp::now(),
3619 updated_at: Timestamp::now(),
3620 seat: SeatState::new(SEAT, "sonnet", 7),
3621 };
3622 talks.put(&mut talk).expect("put");
3623
3624 let raw = std::fs::read_to_string(talks.path_of(&talk.id)).expect("read back");
3625 let v: serde_json::Value = serde_json::from_str(&raw).expect("parse");
3626 for field in [
3627 "schema",
3628 "id",
3629 "repo",
3630 "agent",
3631 "status",
3632 "turns",
3633 "created_at",
3634 "updated_at",
3635 ] {
3636 assert!(v.get(field).is_some(), "missing field `{field}`");
3637 }
3638 assert_eq!(v["schema"], 1);
3639 assert_eq!(v["status"], "open");
3640
3641 let back = talks.get(&talk.id).expect("get");
3642 assert_eq!(back.posts_read_through, None);
3643 assert_eq!(back.id, talk.id);
3644 assert_eq!(back.status, TalkStatus::Open);
3645 }
3646
3647 #[test]
3648 fn opening_a_talk_takes_no_agent_turn() {
3649 let (tmp, talks) = store();
3650 let spec = mock_agent(tmp.path(), BROKEN, BTreeMap::new());
3654 let cfg = config(spec);
3655
3656 let talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
3657 assert_eq!(talk.status, TalkStatus::Open);
3658 assert!(talk.turns.is_empty(), "nothing has been said yet");
3659
3660 let on_disk = talks.get(&talk.id).expect("get");
3661 assert_eq!(on_disk.turns.len(), 0);
3662 }
3663
3664 #[test]
3672 fn chatter_wins_when_set_and_falls_back_to_pick_s_default_order_otherwise() {
3673 let (tmp, talks) = store();
3674 let first_spec = mock_agent(tmp.path(), BROKEN, BTreeMap::new());
3675 let mut chatter_spec = mock_agent(tmp.path(), BROKEN, BTreeMap::new());
3676 chatter_spec.id = "chatter-mock".to_owned();
3677
3678 let mut cfg = Config {
3679 agents: vec![first_spec.clone(), chatter_spec.clone()],
3680 graph: Graph {
3681 language: "en".to_owned(),
3682 ..Graph::default()
3683 },
3684 ..Config::default()
3685 };
3686 cfg.roles.chatter = Some(chatter_spec.id.as_str().into());
3687
3688 let talk =
3689 begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin with chatter set");
3690 assert_eq!(talk.agent, chatter_spec.id, "an explicit chatter must win");
3691
3692 cfg.roles.chatter = None;
3693 let fallback =
3694 begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin with chatter unset");
3695 assert_eq!(
3696 fallback.agent, first_spec.id,
3697 "unset chatter must fall back to agent::pick's own default order"
3698 );
3699 }
3700
3701 #[test]
3704 fn a_talk_recorded_without_attachments_still_reads() {
3705 let (tmp, talks) = store();
3706 let path = talks.path_of("20260904-014455-ab12");
3707 std::fs::create_dir_all(talks.root()).expect("talks dir");
3708 std::fs::write(
3709 &path,
3710 serde_json::json!({
3711 "schema": 1,
3712 "id": "20260904-014455-ab12",
3713 "repo": tmp.path(),
3714 "agent": "sonnet",
3715 "status": "open",
3716 "turns": [
3717 { "who": "operator", "body": "still there?",
3718 "at": Timestamp::now().to_string() },
3719 ],
3720 "created_at": Timestamp::now().to_string(),
3721 "updated_at": Timestamp::now().to_string(),
3722 "seat": SeatState::new(SEAT, "sonnet", 7),
3723 })
3724 .to_string(),
3725 )
3726 .expect("write pre-attachments talk");
3727
3728 let talk = talks.get("20260904-014455-ab12").expect("must still read");
3729 assert!(talk.turns[0].attachments.is_empty());
3730 }
3731
3732 fn lease_store() -> (tempfile::TempDir, Talks, Talks) {
3733 let tmp = tempfile::TempDir::new().expect("tmp");
3734 let root = tmp.path().join("talks");
3735 (tmp, Talks::at(root.clone()), Talks::at(root))
3736 }
3737
3738 #[test]
3739 fn two_starters_on_one_talk_one_wins_and_the_other_is_refused() {
3740 let (_tmp, a, b) = lease_store();
3741 let won = a.claim_turn("t1").expect("claim").expect("first wins");
3742 assert!(
3743 b.claim_turn("t1").expect("claim").is_none(),
3744 "second is refused"
3745 );
3746 assert!(b.turn_held("t1"));
3747 assert!(
3748 b.claim_turn("t2").expect("claim").is_some(),
3749 "other talks are free"
3750 );
3751 drop(won);
3752 }
3753
3754 #[test]
3755 fn a_stale_lease_is_taken_over_and_the_old_guard_cannot_release_it() {
3756 let (_tmp, a, b) = lease_store();
3757 let old = a.claim_turn("t1").expect("claim").expect("held");
3758 let later = Timestamp::now()
3759 .checked_add(jiff::SignedDuration::from_secs(
3760 crate::ask::LEASE_TTL.as_secs() as i64 + 5,
3761 ))
3762 .expect("later");
3763 let new = b
3764 .claim_turn_at("t1", later)
3765 .expect("claim")
3766 .expect("a stale lease is taken over");
3767 drop(old);
3768 assert!(a.turn_held("t1"), "the old guard left the new lease alone");
3769 assert!(new.beat().expect("beat"), "the new owner still beats");
3770 drop(new);
3771 assert!(!a.turn_held("t1"));
3772 }
3773
3774 #[tokio::test]
3775 async fn a_turn_whose_lease_was_taken_over_is_stopped() {
3776 let (_tmp, a, b) = lease_store();
3777 let old = a.claim_turn("t1").expect("claim").expect("held");
3778 let later = Timestamp::now()
3779 .checked_add(jiff::SignedDuration::from_secs(
3780 crate::ask::LEASE_TTL.as_secs() as i64 + 5,
3781 ))
3782 .expect("later");
3783 let _new = b
3784 .claim_turn_at("t1", later)
3785 .expect("claim")
3786 .expect("taken over");
3787 let out = old
3788 .beating_every(Duration::from_millis(10), std::future::pending::<()>())
3789 .await;
3790 assert!(out.is_err(), "the displaced turn must stop, not run on");
3791 }
3792
3793 #[tokio::test]
3794 async fn a_turn_that_finishes_is_returned_and_keeps_its_lease_beating() {
3795 let (_tmp, a, _b) = lease_store();
3796 let lease = a.claim_turn("t1").expect("claim").expect("held");
3797 let out = lease
3798 .beating_every(Duration::from_millis(5), async {
3799 tokio::time::sleep(Duration::from_millis(40)).await;
3800 7
3801 })
3802 .await
3803 .expect("still ours");
3804 assert_eq!(out, 7);
3805 assert!(a.turn_held("t1"));
3806 }
3807
3808 #[test]
3809 fn an_unreadable_lease_counts_as_stale() {
3810 let (_tmp, a, b) = lease_store();
3811 std::fs::create_dir_all(a.root()).expect("dir");
3812 std::fs::write(a.turn_path("t1"), "not json").expect("write");
3813 assert!(!a.turn_held("t1"));
3814 assert!(b.claim_turn("t1").expect("claim").is_some());
3815 }
3816
3817 #[test]
3818 fn without_hard_links_a_claim_is_still_exclusive_and_a_young_placeholder_blocks() {
3819 let (_tmp, a, b) = lease_store();
3820 failpoint::force_no_link(true);
3821 let held = a.claim_turn("t1").expect("claim").expect("first wins");
3822 assert!(b.claim_turn("t1").expect("claim").is_none());
3823 assert!(a.turn_held("t1"));
3824 drop(held);
3825 assert!(!a.turn_held("t1"));
3826 let path = a.turn_path("t1");
3828 assert!(create_exclusive(&path, "").expect("placeholder"));
3829 assert!(b.claim_turn("t1").expect("claim").is_none(), "young: held");
3830 age_file(&path);
3831 assert!(b.claim_turn("t1").expect("claim").is_some(), "old: stale");
3832 let lease = a.turn_path("t2");
3834 let lock = TurnLock::take(&lease).expect("take").expect("lock");
3835 assert!(TurnLock::take(&lease).expect("take").is_none());
3836 drop(lock);
3837 assert!(TurnLock::take(&lease).expect("take").is_some());
3838 failpoint::force_no_link(false);
3839 }
3840
3841 #[test]
3842 fn remove_if_carries_removes_only_the_expected_content() {
3843 let (_tmp, a, _b) = lease_store();
3844 std::fs::create_dir_all(a.root()).expect("dir");
3845 let p = a.root().join("x.turn.lock");
3846 std::fs::write(&p, "mine").expect("write");
3847 assert!(!remove_if_carries(&p, "other"));
3848 assert_eq!(std::fs::read_to_string(&p).expect("kept"), "mine");
3849 assert!(remove_if_carries(&p, "mine"));
3850 assert!(!p.exists());
3851 assert!(!remove_if_carries(&p, "mine"), "absent is not a removal");
3852 }
3853
3854 #[test]
3855 fn a_dropped_lock_does_not_remove_a_lock_taken_over_since() {
3856 let (_tmp, a, _b) = lease_store();
3857 std::fs::create_dir_all(a.root()).expect("dir");
3858 let lease = a.turn_path("t1");
3859 let lock = TurnLock::take(&lease).expect("take").expect("lock");
3860 let path = lock.path.clone();
3861 std::fs::write(&path, "someone-else").expect("replace");
3862 drop(lock);
3863 assert_eq!(
3864 std::fs::read_to_string(&path).expect("kept"),
3865 "someone-else"
3866 );
3867 }
3868
3869 #[test]
3870 fn concurrent_takeovers_of_a_stale_lease_have_one_winner() {
3871 let (_tmp, a, _b) = lease_store();
3872 drop(a.claim_turn("t1").expect("claim").expect("held"));
3873 std::fs::write(
3874 a.turn_path("t1"),
3875 serde_json::to_string(&TurnRecord {
3876 token: "gone".into(),
3877 pid: 1,
3878 beat_at: Timestamp::from_second(1).expect("ts"),
3879 })
3880 .expect("json"),
3881 )
3882 .expect("write");
3883 let wins: Vec<_> = std::thread::scope(|sc| {
3884 let hs: Vec<_> = (0..8)
3885 .map(|_| {
3886 let s = a.clone();
3887 sc.spawn(move || s.claim_turn("t1").expect("claim"))
3888 })
3889 .collect();
3890 hs.into_iter().map(|h| h.join().expect("join")).collect()
3891 });
3892 assert_eq!(wins.iter().filter(|w| w.is_some()).count(), 1);
3893 }
3894
3895 fn age_file(path: &Path) {
3896 let f = std::fs::OpenOptions::new()
3897 .write(true)
3898 .open(path)
3899 .expect("open");
3900 f.set_modified(std::time::SystemTime::now() - std::time::Duration::from_secs(60))
3901 .expect("age");
3902 }
3903
3904 #[test]
3905 fn a_late_taker_of_a_broken_lock_cannot_disturb_its_replacement() {
3906 let (_tmp, a, _b) = lease_store();
3907 let lease = a.turn_path("t1");
3908 let lock = lease.with_extension("turn.lock");
3909 std::fs::create_dir_all(lock.parent().expect("dir")).expect("dir");
3910 std::fs::write(&lock, "t1-dead").expect("dead lock");
3911 age_file(&lock);
3912 let b = TurnLock::take(&lease).expect("take").expect("b wins");
3914 let fresh = std::fs::read_to_string(&lock).expect("read");
3915 assert_eq!(fresh, b.token);
3916 let ticket = std::fs::read_dir(lock.parent().expect("dir"))
3919 .expect("dir")
3920 .flatten()
3921 .map(|e| e.path())
3922 .find(|p| p.to_string_lossy().ends_with(".break.0"))
3923 .expect("ticket");
3924 assert!(!create_exclusive(&ticket, "").expect("ticket"));
3925 assert!(TurnLock::take(&lease).expect("take").is_none());
3926 assert_eq!(std::fs::read_to_string(&lock).expect("read"), fresh);
3927 age_file(&lock);
3929 age_file(&ticket);
3930 std::mem::forget(b);
3931 let c = TurnLock::take(&lease)
3932 .expect("take")
3933 .expect("next generation");
3934 assert_ne!(c.token, fresh);
3935 }
3936
3937 #[test]
3938 fn a_live_ticket_blocks_and_a_stale_one_hands_over_to_the_next_generation() {
3939 let (_tmp, a, _b) = lease_store();
3940 let lease = a.turn_path("t1");
3941 let lock = lease.with_extension("turn.lock");
3942 std::fs::create_dir_all(lock.parent().expect("dir")).expect("dir");
3943 std::fs::write(&lock, "t1-dead").expect("dead lock");
3944 age_file(&lock);
3945 let t0 = lock.with_extension("lock.t1-dead.break.0");
3946 assert!(create_exclusive(&t0, "").expect("ticket"));
3947 assert!(TurnLock::take(&lease).expect("take").is_none());
3949 assert_eq!(std::fs::read_to_string(&lock).expect("read"), "t1-dead");
3950 age_file(&t0);
3952 let c = TurnLock::take(&lease).expect("take").expect("generation 1");
3953 assert_eq!(std::fs::read_to_string(&lock).expect("read"), c.token);
3954 assert!(lock.with_extension("lock.t1-dead.break.1").exists());
3955 assert!(TurnLock::take(&lease).expect("take").is_none());
3956 }
3957
3958 #[test]
3959 fn exhausted_ticket_generations_recover_once_the_sweep_ages_them_out() {
3960 let (_tmp, a, _b) = lease_store();
3961 let lease = a.turn_path("t1");
3962 let lock = lease.with_extension("turn.lock");
3963 std::fs::create_dir_all(lock.parent().expect("dir")).expect("dir");
3964 std::fs::write(&lock, "t1-dead").expect("dead lock");
3965 age_file(&lock);
3966 let tickets: Vec<_> = (0..TICKET_GENERATIONS)
3967 .map(|n| lock.with_extension(format!("lock.t1-dead.break.{n}")))
3968 .collect();
3969 for t in &tickets {
3970 assert!(create_exclusive(t, "").expect("ticket"));
3971 age_file(t);
3972 }
3973 assert!(TurnLock::take(&lease).expect("take").is_none());
3975 assert!(tickets.iter().all(|t| t.exists()));
3976 for t in &tickets {
3978 let f = std::fs::OpenOptions::new()
3979 .write(true)
3980 .open(t)
3981 .expect("open");
3982 f.set_modified(std::time::SystemTime::now() - TICKET_SWEEP_AGE * 2)
3983 .expect("age");
3984 }
3985 assert!(TurnLock::take(&lease).expect("take").is_none());
3986 assert!(TurnLock::take(&lease).expect("take").is_some());
3987 }
3988
3989 #[test]
3990 fn an_aged_empty_lock_is_broken() {
3991 let (_tmp, a, _b) = lease_store();
3992 let lease = a.turn_path("t1");
3993 let lock = lease.with_extension("turn.lock");
3994 std::fs::create_dir_all(lock.parent().expect("dir")).expect("dir");
3995 std::fs::write(&lock, "").expect("empty lock");
3996 age_file(&lock);
3997 assert!(TurnLock::take(&lease).expect("take").is_some());
3998 }
3999
4000 #[test]
4001 fn reply_plain_text_sends_keep_provenance_and_boundaries() {
4002 let (tmp, talks) = store();
4003 let cfg = config(mock_agent(tmp.path(), REPLY, env("reply")));
4004 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4005 record(&mut talk, &talks, "original", Vec::new()).expect("record");
4006 queue(&mut talk, &talks, "first", Vec::new()).expect("queue");
4007 queue(&mut talk, &talks, "second", Vec::new()).expect("queue");
4008 let wire: serde_json::Value =
4009 serde_json::from_str(&std::fs::read_to_string(talks.path_of(&talk.id)).unwrap())
4010 .unwrap();
4011 assert_eq!(wire["pending_messages"][0]["sender"], "operator");
4012 assert_eq!(wire["turns"][0]["messages"][0]["sender"], "operator");
4013 drain(&mut talk, &talks).expect("drain");
4014 let saved = talks.get(&talk.id).expect("reload");
4015 assert_eq!(saved.turns[1].body, "first\n\nsecond");
4016 assert_eq!(saved.turns[1].breaks, Some(vec![7]));
4017 let wire: serde_json::Value =
4018 serde_json::from_str(&std::fs::read_to_string(talks.path_of(&saved.id)).unwrap())
4019 .unwrap();
4020 for turn in wire["turns"].as_array().expect("turns") {
4022 for field in turn.as_object().expect("turn").keys() {
4023 assert!(
4024 [
4025 "who",
4026 "body",
4027 "at",
4028 "attachments",
4029 "usage",
4030 "breaks",
4031 "posted_by",
4032 "sender",
4033 "messages"
4034 ]
4035 .contains(&field.as_str()),
4036 "unknown turn field: {field}"
4037 );
4038 }
4039 }
4040 record_reply(
4041 &mut talk,
4042 &talks,
4043 "reply",
4044 Vec::new(),
4045 Some(ReplyTarget {
4046 turn: 1,
4047 message: 1,
4048 }),
4049 )
4050 .expect("reply to reloaded plain text");
4051 assert_eq!(
4052 talk.turns[2].messages[0].reply.as_ref().unwrap().excerpt,
4053 "second"
4054 );
4055 }
4056
4057 #[tokio::test]
4058 async fn reply_image_identity_reaches_fresh_and_followup_prompts_after_reload() {
4059 let (tmp, talks) = store();
4060 let cfg = config(mock_agent(tmp.path(), ECHO, BTreeMap::new()));
4061 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4062 let first = talks
4063 .put_attachment(&talk.id, "image/png", "first.png", b"first")
4064 .expect("first");
4065 let second = talks
4066 .put_attachment(&talk.id, "image/png", "second.png", b"second")
4067 .expect("second");
4068 let first_path = talks.attachment_path(&talk.id, &first).unwrap();
4069 let second_path = talks.attachment_path(&talk.id, &second).unwrap();
4070 queue(&mut talk, &talks, "", vec![first]).expect("queue first");
4072 queue(&mut talk, &talks, "", vec![second]).expect("queue second");
4073 drain(&mut talk, &talks).expect("drain");
4074 let lease = talks.claim_turn(&talk.id).expect("claim").expect("lease");
4075 for (message, selected, other) in [
4076 (0, &first_path, &second_path),
4077 (1, &second_path, &first_path),
4078 ] {
4079 record_reply(
4080 &mut talk,
4081 &talks,
4082 "describe this",
4083 Vec::new(),
4084 Some(ReplyTarget { turn: 0, message }),
4085 )
4086 .expect("reply");
4087 talk = talks.get(&talk.id).expect("reload");
4088 let quote = message_prompt(talk.turns.last().unwrap(), &talk, &talks);
4089 assert!(quote.contains(selected.to_str().unwrap()));
4090 assert!(!quote.contains(other.to_str().unwrap()));
4091 respond(&lease, &mut talk, &talks, &cfg, "describe this")
4092 .await
4093 .expect("respond");
4094 assert!(
4095 talk.turns
4096 .last()
4097 .unwrap()
4098 .body
4099 .contains(&format!("Replied-to image: {}", selected.display()))
4100 );
4101 }
4102 }
4103
4104 #[test]
4105 fn reply_sends_survive_queue_edit_drain_reload_and_legacy_records() {
4106 let (tmp, talks) = store();
4107 let cfg = config(mock_agent(tmp.path(), REPLY, env("reply")));
4108 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4109 record(&mut talk, &talks, &"猫".repeat(300), Vec::new()).expect("record");
4110 talk.turns[0].messages.clear();
4112 talks.put(&mut talk).expect("legacy save");
4113 let target = ReplyTarget {
4114 turn: 0,
4115 message: 0,
4116 };
4117 queue_reply(&mut talk, &talks, "first", Vec::new(), Some(target.clone())).expect("first");
4118 queue_reply(&mut talk, &talks, "second", Vec::new(), None).expect("second");
4119 assert!(
4120 edit_pending_message(&mut talk, &talks, "edited", "first\n\nsecond", &[], Some(0))
4121 .expect("edit")
4122 );
4123 drain(&mut talk, &talks).expect("drain");
4124 let saved = talks.get(&talk.id).expect("reload");
4125 assert_eq!(saved.turns[1].body, "edited\n\nsecond");
4126 assert_eq!(saved.turns[1].messages.len(), 2);
4127 let reply = saved.turns[1].messages[0].reply.as_ref().expect("reply");
4128 assert_eq!(reply.target, target);
4129 assert_eq!(reply.excerpt, "猫".repeat(240));
4130 assert!(message_prompt(&saved.turns[1], &saved, &talks).contains("[Reply to Operator:"));
4131 assert!(transcript(&saved, &talks).contains("[Reply to Operator:"));
4132 queue_reply(
4133 &mut talk,
4134 &talks,
4135 "third",
4136 Vec::new(),
4137 Some(ReplyTarget {
4138 turn: 1,
4139 message: 1,
4140 }),
4141 )
4142 .expect("specific send");
4143 assert_eq!(
4144 talk.pending_messages[0]
4145 .reply
4146 .as_ref()
4147 .expect("reply")
4148 .excerpt,
4149 "second"
4150 );
4151 clear_pending(&mut talk, &talks).expect("clear");
4152 assert!(talk.pending_messages.is_empty());
4153 assert!(
4154 record_reply(
4155 &mut talk,
4156 &talks,
4157 "invalid",
4158 Vec::new(),
4159 Some(ReplyTarget {
4160 turn: 1,
4161 message: 2
4162 })
4163 )
4164 .is_err()
4165 );
4166 assert_eq!(talks.get(&talk.id).expect("reload").turns.len(), 2);
4167 }
4168
4169 #[tokio::test]
4170 async fn reply_quotes_reach_fresh_and_followup_prompts_without_changing_body() {
4171 let (tmp, talks) = store();
4172 let cfg = config(mock_agent(tmp.path(), ECHO, BTreeMap::new()));
4173 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4174 record(&mut talk, &talks, "original", Vec::new()).expect("record");
4175 let target = ReplyTarget {
4176 turn: 0,
4177 message: 0,
4178 };
4179 record_reply(
4180 &mut talk,
4181 &talks,
4182 "answer",
4183 Vec::new(),
4184 Some(target.clone()),
4185 )
4186 .expect("reply");
4187 let lease = talks.claim_turn(&talk.id).expect("claim").expect("lease");
4188 respond(&lease, &mut talk, &talks, &cfg, "answer")
4189 .await
4190 .expect("respond");
4191 assert!(
4192 talk.turns
4193 .last()
4194 .expect("response")
4195 .body
4196 .contains("[Reply to Operator: original]\nanswer")
4197 );
4198 assert_eq!(talk.turns[1].body, "answer");
4199 record_reply(&mut talk, &talks, "followup", Vec::new(), Some(target)).expect("reply");
4200 respond(&lease, &mut talk, &talks, &cfg, "followup")
4201 .await
4202 .expect("respond");
4203 assert!(
4204 talk.turns
4205 .last()
4206 .expect("response")
4207 .body
4208 .contains("[Reply to Operator: original]\nfollowup")
4209 );
4210 }
4211
4212 #[test]
4213 fn owner_indentation_survives_record_queue_and_edit() {
4214 let (tmp, talks) = store();
4215 let cfg = config(mock_agent(tmp.path(), REPLY, env("reply")));
4216 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4217 for text in [" Post original", "\tUse rewrite"] {
4218 record_reply(&mut talk, &talks, text, Vec::new(), None).unwrap();
4219 assert_eq!(
4220 talks.get(&talk.id).unwrap().turns.last().unwrap().body,
4221 text
4222 );
4223 queue(&mut talk, &talks, "draft", Vec::new()).unwrap();
4224 assert!(edit_pending_message(&mut talk, &talks, text, "draft", &[], Some(0)).unwrap());
4225 let saved = talks.get(&talk.id).unwrap();
4226 assert_eq!(saved.pending, text);
4227 assert_eq!(saved.pending_messages[0].body, text);
4228 assert!(edit_pending_message(&mut talk, &talks, text, text, &[], None).unwrap());
4229 let saved = talks.get(&talk.id).unwrap();
4230 assert_eq!(saved.pending, text);
4231 assert_eq!(saved.pending_messages[0].body, text);
4232 assert_eq!(drain(&mut talk, &talks).unwrap().as_deref(), Some(text));
4233 }
4234 }
4235
4236 #[test]
4237 fn queued_text_is_durable_combined_and_drained_as_one_operator_turn() {
4238 let (tmp, talks) = store();
4239 let cfg = config(mock_agent(tmp.path(), REPLY, env("reply")));
4240 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4241
4242 queue(&mut talk, &talks, "first", Vec::new()).expect("queue first");
4243 queue(&mut talk, &talks, "second", Vec::new()).expect("queue second");
4244 let saved = talks.get(&talk.id).expect("reload queued talk");
4245 assert_eq!(saved.pending, "first\n\nsecond");
4246 assert_eq!(saved.pending_breaks, Some(vec!["first\n\n".len()]));
4247 assert!(saved.turns.is_empty(), "a draft is not a transcript turn");
4248
4249 let drained = drain(&mut talk, &talks).expect("drain");
4250 assert_eq!(drained.as_deref(), Some("first\n\nsecond"));
4251 let saved = talks.get(&talk.id).expect("reload drained talk");
4252 assert!(saved.pending.is_empty());
4253 assert_eq!(saved.turns.len(), 1);
4254 assert_eq!(saved.turns[0].body, "first\n\nsecond");
4255 assert_eq!(saved.turns[0].breaks, Some(vec!["first\n\n".len()]));
4256 assert_eq!(saved.pending_breaks, None);
4257 }
4258
4259 #[test]
4260 fn editing_a_queued_draft_preserves_its_attachments_and_rejects_a_stale_snapshot() {
4261 let (tmp, talks) = store();
4262 let cfg = config(mock_agent(tmp.path(), REPLY, env("reply")));
4263 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4264 let attachment = Attachment {
4265 id: "a".repeat(32),
4266 name: "shot.png".to_owned(),
4267 mime: "image/png".to_owned(),
4268 bytes: 3,
4269 };
4270
4271 queue(&mut talk, &talks, "first", vec![attachment.clone()]).expect("queue");
4272 assert!(
4273 edit_pending_text(
4274 &mut talk,
4275 &talks,
4276 "corrected",
4277 "first",
4278 std::slice::from_ref(&attachment.id),
4279 )
4280 .expect("edit")
4281 );
4282 let saved = talks.get(&talk.id).expect("reload edited draft");
4283 assert_eq!(saved.pending, "corrected");
4284 assert_eq!(saved.pending_attachments, vec![attachment]);
4285
4286 queue(&mut talk, &talks, "later", Vec::new()).expect("queue concurrent draft");
4287 assert!(
4288 !edit_pending_text(
4289 &mut talk,
4290 &talks,
4291 "stale edit",
4292 "corrected",
4293 &["a".repeat(32)],
4294 )
4295 .expect("stale edit is a conflict")
4296 );
4297 assert_eq!(
4298 talks.get(&talk.id).expect("reload after conflict").pending,
4299 "corrected\n\nlater"
4300 );
4301 assert!(
4302 !clear_pending_if_matches(&mut talk, &talks, "corrected", &["a".repeat(32)])
4303 .expect("stale clear is a conflict")
4304 );
4305 assert_eq!(
4306 talks
4307 .get(&talk.id)
4308 .expect("reload after stale clear")
4309 .pending,
4310 "corrected\n\nlater"
4311 );
4312 }
4313
4314 #[tokio::test]
4315 async fn a_reply_save_preserves_pending_accepted_while_the_cli_runs() {
4316 let (tmp, talks) = store();
4317 let slow = "#!/bin/sh\ncat >/dev/null\nsleep 0.1\nprintf reply\n";
4318 let cfg = config(mock_agent(tmp.path(), slow, BTreeMap::new()));
4319 let mut running = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4320 let id = running.id.clone();
4321 let first = record(&mut running, &talks, "first", Vec::new()).expect("record");
4322
4323 let response_talks = talks.clone();
4324 let response_cfg = cfg.clone();
4325 let reply = tokio::spawn(async move {
4326 respond(
4327 &response_talks.claim_turn(&running.id).unwrap().unwrap(),
4328 &mut running,
4329 &response_talks,
4330 &response_cfg,
4331 &first,
4332 )
4333 .await
4334 });
4335 tokio::time::sleep(std::time::Duration::from_millis(20)).await;
4336
4337 let mut queued = talks.get(&id).expect("queued handle");
4338 queue(&mut queued, &talks, "next", Vec::new()).expect("queue");
4339 reply.await.expect("join").expect("reply");
4340
4341 let saved = talks.get(&id).expect("reload");
4342 assert_eq!(saved.pending, "next");
4343 assert_eq!(saved.pending_breaks, Some(Vec::new()));
4344 assert_eq!(saved.turns.len(), 2, "operator message and reply remain");
4345 }
4346
4347 #[tokio::test]
4348 async fn posts_during_a_resumed_turn_are_replayed_once_even_after_a_reply_save_failure() {
4349 for lose_reply in [false, true] {
4350 let (tmp, talks) = store();
4351 let cfg = config(mock_agent(tmp.path(), ECHO, BTreeMap::new()));
4352 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4353 say(
4354 &talks.claim_turn(&talk.id).unwrap().unwrap(),
4355 &mut talk,
4356 &talks,
4357 &cfg,
4358 "establish the session",
4359 Vec::new(),
4360 )
4361 .await
4362 .expect("first turn");
4363 assert!(agent::has_session(
4364 AgentKind::Command,
4365 &talk.seat,
4366 cfg.graph.sessions
4367 ));
4368
4369 post(&talks, &talk.id, "already available", "task-earlier").expect("earlier post");
4370 talk = talks.get(&talk.id).expect("reload earlier post");
4371 let ready = tmp.path().join("ready");
4372 let release = tmp.path().join("release");
4373 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";
4374 let slow_cfg = config(mock_agent(
4375 tmp.path(),
4376 slow,
4377 BTreeMap::from([
4378 ("READY".to_owned(), ready.to_string_lossy().into_owned()),
4379 ("RELEASE".to_owned(), release.to_string_lossy().into_owned()),
4380 ]),
4381 ));
4382 let text = record(&mut talk, &talks, "keep going", Vec::new()).expect("record");
4383 let prompt_turns = talk.turns.len();
4384 let id = talk.id.clone();
4385 let response_talks = talks.clone();
4386 let running = tokio::spawn(async move {
4387 respond(
4388 &response_talks.claim_turn(&talk.id).unwrap().unwrap(),
4389 &mut talk,
4390 &response_talks,
4391 &slow_cfg,
4392 &text,
4393 )
4394 .await
4395 });
4396 tokio::time::timeout(std::time::Duration::from_secs(5), async {
4397 while !ready.exists() {
4398 tokio::time::sleep(std::time::Duration::from_millis(10)).await;
4399 }
4400 })
4401 .await
4402 .expect("CLI read its prompt");
4403 post(&talks, &id, "concurrent task result", "task-one").expect("post");
4404 post(&talks, &id, "second task result", "task-two").expect("second post");
4405 if lose_reply {
4406 failpoint::force_put_failures(PUT_RETRIES);
4407 }
4408 std::fs::write(release, "go").expect("release CLI");
4409 let result = running.await.expect("join");
4410 if lose_reply {
4411 assert!(
4412 result
4413 .unwrap_err()
4414 .to_string()
4415 .contains("could not be saved")
4416 );
4417 } else {
4418 result.expect("reply");
4419 }
4420
4421 let mut saved = talks.get(&id).expect("reload");
4422 assert_eq!(saved.posts_read_through, Some(prompt_turns));
4423 assert_eq!(saved.turns[prompt_turns].body, "concurrent task result");
4424 assert_eq!(saved.turns[prompt_turns + 1].body, "second task result");
4425 assert!(posts_since_last_reply(&saved).is_some());
4426 let cfg = config(mock_agent(tmp.path(), ECHO, BTreeMap::new()));
4427 say(
4428 &talks.claim_turn(&id).unwrap().unwrap(),
4429 &mut saved,
4430 &talks,
4431 &cfg,
4432 "read the results",
4433 Vec::new(),
4434 )
4435 .await
4436 .expect("replay turn");
4437 let prompt = &saved.turns.last().unwrap().body;
4438 assert!(prompt.contains("# Posted by a task"), "{prompt}");
4439 assert!(!prompt.contains("already available"), "{prompt}");
4440 assert!(
4441 prompt
4442 .find("concurrent task result")
4443 .expect("first post in prompt")
4444 < prompt
4445 .find("second task result")
4446 .expect("second post in prompt")
4447 );
4448 let mut saved = talks.get(&id).expect("reload after replay");
4449 assert!(posts_since_last_reply(&saved).is_none());
4450 say(
4451 &talks.claim_turn(&id).unwrap().unwrap(),
4452 &mut saved,
4453 &talks,
4454 &cfg,
4455 "continue",
4456 Vec::new(),
4457 )
4458 .await
4459 .expect("next turn");
4460 assert!(!saved.turns.last().unwrap().body.contains("task result"));
4461 }
4462 }
4463
4464 fn counting_agent(dir: &Path, id: &str, body: &str) -> AgentSpec {
4467 let calls = dir.join(format!("{id}.calls"));
4468 let script = format!(
4469 "#!/bin/sh\necho x >> '{}'\n{body}\n",
4470 calls.to_string_lossy()
4471 );
4472 let path = dir.join(format!("mock-{id}.sh"));
4473 std::fs::write(&path, script).expect("write mock");
4474 AgentSpec {
4475 id: id.to_owned(),
4476 kind: AgentKind::Command,
4477 model: None,
4478 command: vec!["sh".to_owned(), path.to_string_lossy().into_owned()],
4479 extra_args: Vec::new(),
4480 env: BTreeMap::new(),
4481 prompt_delivery: None,
4482 }
4483 }
4484
4485 fn calls(dir: &Path, id: &str) -> usize {
4486 std::fs::read_to_string(dir.join(format!("{id}.calls"))).map_or(0, |s| s.lines().count())
4487 }
4488
4489 fn chain_config(specs: Vec<AgentSpec>, ids: &[&str]) -> Config {
4490 let mut cfg = config(specs[0].clone());
4491 cfg.agents = specs;
4492 cfg.roles.chatter = Some(AgentChoice::Chain(
4493 ids.iter().map(|s| (*s).to_owned()).collect(),
4494 ));
4495 cfg
4496 }
4497
4498 #[tokio::test]
4499 async fn completion_evidence_reaches_fresh_resumed_and_fallback_prompts() {
4500 for fallback in [false, true] {
4501 let (tmp, talks) = store();
4502 let cfg = if fallback {
4503 chain_config(
4504 vec![
4505 counting_agent(tmp.path(), "a", "cat >/dev/null\nexit 3"),
4506 counting_agent(tmp.path(), "b", "cat"),
4507 ],
4508 &["a", "b"],
4509 )
4510 } else {
4511 config(mock_agent(tmp.path(), ECHO, BTreeMap::new()))
4512 };
4513 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).unwrap();
4514 let lease = talks.claim_turn(&talk.id).unwrap().unwrap();
4515 for n in 0..2 {
4516 let text = format!(
4517 "# {}\n\n- Task: `unavailable-{n}`",
4518 crate::prompt::CHAT_TASK_NOTICE_HEADING
4519 );
4520 let reference = crate::chat_notify::CompletionReference {
4521 task: format!("unavailable-{n}"),
4522 run: None,
4523 notice: text.clone(),
4524 };
4525 let key = format!("unavailable-{n}:done");
4526 assert!(
4527 queue_once_matching(
4528 &mut talk,
4529 &talks,
4530 &text,
4531 &key,
4532 &|_| false,
4533 Some(&reference)
4534 )
4535 .unwrap()
4536 );
4537 assert!(
4538 !queue_once_matching(
4539 &mut talk,
4540 &talks,
4541 &text,
4542 &key,
4543 &|_| false,
4544 Some(&reference)
4545 )
4546 .unwrap()
4547 );
4548 talk = talks.get(&talk.id).unwrap();
4549 assert_eq!(talk.completion_notices.len(), n + 1);
4550 let text = drain(&mut talk, &talks).unwrap().unwrap();
4551 respond(&lease, &mut talk, &talks, &cfg, &text)
4552 .await
4553 .unwrap();
4554 let reply = &talk.turns.last().unwrap().body;
4555 assert!(reply.contains("# Verified outcome evidence"), "{reply}");
4556 assert!(reply.contains("Outcome evidence unavailable"));
4557 assert!(reply.contains("Do not file new tasks or edit repositories solely"));
4558 assert!(reply.contains("Explicitly say when no action remains"));
4559 }
4560 record(&mut talk, &talks, "ordinary follow-up", vec![]).unwrap();
4561 assert!(
4562 crate::chat_notify::response_evidence(&talk)
4563 .await
4564 .is_empty(),
4565 "history does not trigger lookups"
4566 );
4567 record(
4568 &mut talk,
4569 &talks,
4570 &format!("# {}\n\nlegacy", crate::prompt::CHAT_TASK_NOTICE_HEADING),
4571 vec![],
4572 )
4573 .unwrap();
4574 assert!(
4575 crate::chat_notify::response_evidence(&talk)
4576 .await
4577 .contains("Legacy notification has no structured task/run reference")
4578 );
4579 }
4580 }
4581
4582 #[tokio::test]
4583 async fn a_chatter_chain_falls_back_resends_the_transcript_and_sticks() {
4584 let (tmp, talks) = store();
4585 let a = counting_agent(tmp.path(), "a", "cat >/dev/null\nexit 3");
4586 let b = counting_agent(tmp.path(), "b", "cat");
4587 let cfg = chain_config(vec![a, b], &["a", "b"]);
4588 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4589 assert_eq!(talk.agent, "a");
4590 post(&talks, &talk.id, "fallback task result", "task").expect("post");
4591 talk = talks.get(&talk.id).expect("reload");
4592
4593 say(
4594 &talks.claim_turn(&talk.id).unwrap().unwrap(),
4595 &mut talk,
4596 &talks,
4597 &cfg,
4598 "hello there",
4599 Vec::new(),
4600 )
4601 .await
4602 .expect("turn");
4603 assert_eq!(calls(tmp.path(), "a"), 1, "each id is tried once");
4604 assert_eq!(calls(tmp.path(), "b"), 1);
4605 assert_eq!(talk.agent, "b", "the switch persists");
4606 assert!(talks.get(&talk.id).unwrap().agent == "b");
4607 let reply = talk.turns.last().unwrap();
4608 assert!(reply.body.contains("hello there"));
4609 assert!(reply.body.contains("fallback task result"));
4610 let saved = talks.get(&talk.id).expect("reload fallback");
4611 assert_eq!(saved.posts_read_through, Some(2));
4612 assert!(posts_since_last_reply(&saved).is_none());
4613 assert!(
4614 reply.body.contains("magi task add --solo"),
4615 "a fresh seat gets the full briefing"
4616 );
4617 assert!(
4618 talk.turns
4619 .iter()
4620 .any(|t| t.body.contains("agent changed from a to b")),
4621 "the switch is noted"
4622 );
4623 }
4624
4625 #[tokio::test]
4626 async fn an_exhausted_chatter_chain_fails_like_a_single_seat_and_stays_put() {
4627 let (tmp, talks) = store();
4628 let a = counting_agent(tmp.path(), "a", "cat >/dev/null\nexit 3");
4629 let b = counting_agent(tmp.path(), "b", "cat >/dev/null\nexit 4");
4630 let cfg = chain_config(vec![a, b], &["a", "b", "a"]);
4631 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4632
4633 let err = say(
4634 &talks.claim_turn(&talk.id).unwrap().unwrap(),
4635 &mut talk,
4636 &talks,
4637 &cfg,
4638 "hi",
4639 Vec::new(),
4640 )
4641 .await
4642 .expect_err("every agent failed");
4643 assert!(err.to_string().contains("`a`"), "{err:#}");
4644 assert_eq!(calls(tmp.path(), "a"), 1);
4645 assert_eq!(calls(tmp.path(), "b"), 1);
4646 assert_eq!(talk.agent, "a", "an exhausted chain leaves the agent alone");
4647 }
4648
4649 #[test]
4650 fn a_chatter_chain_skips_an_unknown_id_at_begin() {
4651 let (tmp, talks) = store();
4652 let b = counting_agent(tmp.path(), "b", "cat");
4653 let cfg = chain_config(vec![b], &["ghost", "b"]);
4654 let talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4655 assert_eq!(talk.agent, "b");
4656 }
4657
4658 #[tokio::test]
4659 async fn an_explicit_agent_inside_the_chatter_chain_stays_pinned() {
4660 let (tmp, talks) = store();
4661 let a = counting_agent(tmp.path(), "a", "cat >/dev/null\nexit 3");
4662 let b = counting_agent(tmp.path(), "b", "cat");
4663 let cfg = chain_config(vec![a, b], &["a", "b"]);
4664 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), Some("a")).expect("begin");
4665 say(
4666 &talks.claim_turn(&talk.id).unwrap().unwrap(),
4667 &mut talk,
4668 &talks,
4669 &cfg,
4670 "hi",
4671 Vec::new(),
4672 )
4673 .await
4674 .expect_err("a alone, and it fails");
4675 assert_eq!(calls(tmp.path(), "b"), 0);
4676 assert_eq!(talk.agent, "a");
4677 }
4678
4679 #[tokio::test]
4680 async fn an_explicit_agent_does_not_borrow_the_chatter_chain() {
4681 let (tmp, talks) = store();
4682 let a = counting_agent(tmp.path(), "a", "cat >/dev/null\nexit 3");
4683 let b = counting_agent(tmp.path(), "b", "cat");
4684 let c = counting_agent(tmp.path(), "c", "cat >/dev/null\nexit 3");
4685 let cfg = chain_config(vec![a, b, c], &["a", "b"]);
4686 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), Some("c")).expect("begin");
4687 say(
4688 &talks.claim_turn(&talk.id).unwrap().unwrap(),
4689 &mut talk,
4690 &talks,
4691 &cfg,
4692 "hi",
4693 Vec::new(),
4694 )
4695 .await
4696 .expect_err("c alone, and it fails");
4697 assert_eq!(calls(tmp.path(), "b"), 0);
4698 }
4699
4700 #[test]
4701 fn briefing_names_the_operator_with_or_without_a_persona() {
4702 let plain = briefing(Path::new("/repo"), "en", false);
4703 let named = briefing_with(Path::new("/repo"), "en", false, None, Some("Commander"));
4704 assert!(named.starts_with(&plain));
4705 assert!(named.contains("# Addressing the operator"));
4706 assert!(named.contains("\"Commander\""));
4707 let rei = crate::persona::builtin_catalog()
4708 .into_iter()
4709 .find(|p| p.id == "rei")
4710 .expect("rei");
4711 let with = briefing_with(
4712 Path::new("/repo"),
4713 "en",
4714 false,
4715 Some(&rei),
4716 Some("Commander"),
4717 );
4718 assert!(with.contains("\"Commander\""));
4719 assert!(!with.contains("# Addressing the operator"));
4720 }
4721
4722 #[test]
4723 fn briefing_carries_a_persona_section_only_when_one_is_chosen() {
4724 let plain = briefing(Path::new("/repo"), "en", false);
4725 assert_eq!(
4726 plain,
4727 briefing_with(Path::new("/repo"), "en", false, None, None)
4728 );
4729 assert!(!plain.contains("Persona"));
4730 let rei = crate::persona::builtin_catalog()
4731 .into_iter()
4732 .find(|p| p.id == "rei")
4733 .expect("rei");
4734 let with = briefing_with(Path::new("/repo"), "en", false, Some(&rei), None);
4735 assert!(with.starts_with(&plain), "the plain briefing is untouched");
4736 assert!(with.contains("# Persona (tone only)"));
4737 assert!(with.contains("TONE ONLY"));
4738 assert!(with.contains("task ids"));
4739 assert!(with.contains("write policy"));
4740 assert!(with.contains("`magi task add`"));
4741 assert!(with.contains("Rei Ayanami"));
4742 }
4743
4744 #[test]
4745 fn a_talk_written_before_personas_still_loads() {
4746 let (tmp, talks) = store();
4747 let spec = mock_agent(tmp.path(), ECHO, BTreeMap::new());
4748 let cfg = config(spec);
4749 let talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4750 let path = talks.root.join(format!("{}.json", talk.id));
4751 let mut v: serde_json::Value =
4752 serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
4753 v.as_object_mut().unwrap().remove("persona");
4754 v.as_object_mut().unwrap().remove("persona_dirty");
4755 std::fs::write(&path, v.to_string()).unwrap();
4756 let loaded = talks.get(&talk.id).expect("old record loads");
4757 assert_eq!(loaded.persona, "");
4758 assert!(!loaded.persona_dirty);
4759 }
4760
4761 #[test]
4762 fn the_briefing_files_with_solo_or_the_chosen_implementer_count() {
4763 let repo = Path::new("/repo");
4764 let solo = briefing_for(repo, "", false, None, None, 1);
4765 assert_eq!(solo, briefing(repo, "", false));
4766 assert!(solo.contains("magi task add --solo --repo"));
4767 assert!(solo.contains("magi task add --solo --attach"));
4768 for n in [2u8, 3] {
4769 let b = briefing_for(repo, "", false, None, None, n);
4770 assert!(
4771 b.contains(&format!("magi task add --implementers {n} --repo")),
4772 "{b}"
4773 );
4774 assert!(b.contains(&format!("magi task add --implementers {n} --attach")));
4775 assert!(!b.contains("task add --solo"), "{b}");
4776 assert!(!b.contains("Use --solo"), "{b}");
4777 }
4778 }
4779
4780 #[test]
4781 fn begin_with_applies_remembered_choices_and_drops_unfit_ones_alone() {
4782 let (tmp, talks) = store();
4783 let first = mock_agent(tmp.path(), ECHO, BTreeMap::new());
4784 let mut second = first.clone();
4785 second.id = "second".to_owned();
4786 let mut cfg = config(first.clone());
4787 cfg.agents.push(second.clone());
4788 let open = |p: &Preferred| {
4789 begin_with(&talks, &cfg, tmp.path().to_owned(), None, p).expect("begin")
4790 };
4791
4792 let talk = open(&Preferred {
4793 agent: Some("second".into()),
4794 persona: Some("rei".into()),
4795 implementers: Some(i64::from(check_implementers(3, &cfg).unwrap_or(1))),
4796 });
4797 assert_eq!(talk.agent, "second");
4798 assert!(
4799 !talk.fallback,
4800 "a remembered non-head agent is an explicit choice"
4801 );
4802 assert_eq!(talk.persona, "rei");
4803 assert_eq!(talk.implementers, check_implementers(3, &cfg).unwrap_or(1));
4804 assert!(!talk.persona_dirty && !talk.implementers_dirty);
4805
4806 let head = open(&Preferred {
4808 agent: Some(first.id.clone()),
4809 ..Preferred::default()
4810 });
4811 assert!(head.fallback);
4812
4813 for implementers in [0, 4, -1, 1000] {
4815 let t = open(&Preferred {
4816 agent: Some("gone".into()),
4817 persona: Some("no-such-persona".into()),
4818 implementers: Some(implementers),
4819 });
4820 assert_eq!(t.agent, first.id);
4821 assert!(t.fallback);
4822 assert_eq!(t.persona, "");
4823 assert_eq!(t.implementers, 1);
4824 }
4825
4826 let t = open(&Preferred {
4828 agent: Some("second".into()),
4829 persona: Some("default".into()),
4830 implementers: Some(9),
4831 });
4832 assert_eq!(
4833 (t.agent.as_str(), t.persona.as_str(), t.implementers),
4834 ("second", "", 1)
4835 );
4836
4837 let strict = begin_with(
4839 &talks,
4840 &cfg,
4841 tmp.path().to_owned(),
4842 Some("first-unknown"),
4843 &Preferred {
4844 agent: Some("second".into()),
4845 ..Preferred::default()
4846 },
4847 );
4848 assert!(strict.is_err());
4849 }
4850
4851 #[test]
4852 fn remembered_agent_can_open_when_the_chatter_chain_cannot_resolve() {
4853 let (tmp, talks) = store();
4854 let spec = mock_agent(tmp.path(), ECHO, BTreeMap::new());
4855 let cfg = chain_config(vec![spec.clone()], &["missing-chatter"]);
4858 assert!(begin(&talks, &cfg, tmp.path().to_owned(), None).is_err());
4859 let talk = begin_with(
4860 &talks,
4861 &cfg,
4862 tmp.path().to_owned(),
4863 None,
4864 &Preferred {
4865 agent: Some(spec.id.clone()),
4866 ..Preferred::default()
4867 },
4868 )
4869 .expect("a valid remembered agent does not require a default chain");
4870 assert_eq!(talk.agent, spec.id);
4871 assert!(!talk.fallback);
4872 assert_eq!(talks.get(&talk.id).unwrap().agent, spec.id);
4873 assert!(
4874 begin_with(
4875 &talks,
4876 &cfg,
4877 tmp.path().to_owned(),
4878 None,
4879 &Preferred {
4880 agent: Some("missing-preference".into()),
4881 ..Preferred::default()
4882 },
4883 )
4884 .is_err()
4885 );
4886 }
4887
4888 #[test]
4889 fn implementers_are_validated_and_old_records_load_as_solo() {
4890 let (tmp, talks) = store();
4891 let cfg = config(mock_agent(tmp.path(), ECHO, BTreeMap::new()));
4892 assert_eq!(check_implementers(1, &cfg), Ok(1));
4893 assert_eq!(check_implementers(3, &cfg), Ok(3));
4894 assert!(check_implementers(0, &cfg).is_err());
4895 assert!(check_implementers(4, &cfg).is_err());
4896 let mut empty = cfg.clone();
4897 empty.agents.clear();
4898 assert!(check_implementers(2, &empty).is_err());
4899
4900 let talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4901 let path = talks.path_of(&talk.id);
4902 let mut v: serde_json::Value =
4903 serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
4904 v.as_object_mut().unwrap().remove("implementers");
4905 v.as_object_mut().unwrap().remove("implementers_dirty");
4906 std::fs::write(&path, v.to_string()).unwrap();
4907 let loaded = talks.get(&talk.id).expect("load");
4908 assert_eq!(loaded.implementers, 1);
4909 assert!(!loaded.implementers_dirty);
4910 }
4911
4912 #[tokio::test]
4913 async fn an_implementers_switch_is_noted_once_and_kept_across_a_failed_turn() {
4914 let (tmp, talks) = store();
4915 let spec = mock_agent(tmp.path(), ECHO, BTreeMap::new());
4916 let cfg = config(spec);
4917 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4918 let lease = talks.claim_turn(&talk.id).unwrap().unwrap();
4919 say(&lease, &mut talk, &talks, &cfg, "hello", Vec::new())
4920 .await
4921 .expect("first turn");
4922
4923 assert!(switch_implementers(&mut talk, &talks, 2).expect("switch"));
4924 assert!(!switch_implementers(&mut talk, &talks, 2).expect("same"));
4925 assert!(talk.implementers_dirty);
4926 say(&lease, &mut talk, &talks, &cfg, "next", Vec::new())
4927 .await
4928 .expect("turn");
4929 let prompt = &talk.turns.last().unwrap().body;
4930 assert!(prompt.contains("# Task filing update"), "{prompt}");
4931 assert!(prompt.contains("--implementers 2"));
4932 assert!(!talk.implementers_dirty, "cleared after a successful turn");
4933
4934 say(&lease, &mut talk, &talks, &cfg, "again", Vec::new())
4935 .await
4936 .expect("turn");
4937 assert!(
4938 !talk
4939 .turns
4940 .last()
4941 .unwrap()
4942 .body
4943 .contains("# Task filing update")
4944 );
4945
4946 let mut no_sessions = cfg.clone();
4948 no_sessions.graph.sessions = false;
4949 say(&lease, &mut talk, &talks, &no_sessions, "one", Vec::new())
4950 .await
4951 .expect("turn");
4952 say(&lease, &mut talk, &talks, &no_sessions, "two", Vec::new())
4953 .await
4954 .expect("turn");
4955 assert!(talk.turns.last().unwrap().body.contains("--implementers 2"));
4956 }
4957
4958 #[tokio::test]
4959 async fn a_persona_switch_notes_marks_dirty_and_updates_the_next_turn_once() {
4960 let (tmp, talks) = store();
4961 let spec = mock_agent(tmp.path(), ECHO, BTreeMap::new());
4962 let cfg = config(spec);
4963 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4964 let lease = talks.claim_turn(&talk.id).unwrap().unwrap();
4965 say(&lease, &mut talk, &talks, &cfg, "hello", Vec::new())
4966 .await
4967 .expect("first turn");
4968 assert!(!talk.turns[1].body.contains("Persona"));
4969
4970 assert!(switch_persona(&mut talk, &talks, "misato").expect("switch"));
4971 assert!(!switch_persona(&mut talk, &talks, "misato").expect("same"));
4972 assert!(talk.persona_dirty);
4973 assert!(talk.turns.last().unwrap().body.contains("persona changed"));
4974
4975 say(&lease, &mut talk, &talks, &cfg, "next", Vec::new())
4976 .await
4977 .expect("turn");
4978 let prompt = &talk.turns.last().unwrap().body;
4979 assert!(prompt.contains("# Persona update"), "{prompt}");
4980 assert!(prompt.contains("Misato Katsuragi"));
4981 assert!(!talk.persona_dirty, "cleared after a successful turn");
4982
4983 say(&lease, &mut talk, &talks, &cfg, "again", Vec::new())
4984 .await
4985 .expect("turn");
4986 assert!(!talk.turns.last().unwrap().body.contains("# Persona update"));
4987
4988 assert!(switch_persona(&mut talk, &talks, "default").expect("back"));
4989 assert_eq!(talk.persona, "");
4990 say(&lease, &mut talk, &talks, &cfg, "plain", Vec::new())
4991 .await
4992 .expect("turn");
4993 assert!(
4994 talk.turns
4995 .last()
4996 .unwrap()
4997 .body
4998 .contains("turned the persona off")
4999 );
5000
5001 assert!(switch_persona(&mut talk, &talks, "rei").expect("rei"));
5003 let mut no_sessions = cfg.clone();
5004 no_sessions.graph.sessions = false;
5005 say(&lease, &mut talk, &talks, &no_sessions, "one", Vec::new())
5006 .await
5007 .expect("turn");
5008 say(&lease, &mut talk, &talks, &no_sessions, "two", Vec::new())
5009 .await
5010 .expect("turn");
5011 let last = &talk.turns.last().unwrap().body;
5012 assert!(!talk.persona_dirty);
5013 assert!(last.contains("# Persona (tone only)"), "{last}");
5014 assert!(last.contains("Rei Ayanami"));
5015 }
5016
5017 #[tokio::test]
5018 async fn the_first_turn_carries_the_briefing_and_later_turns_do_not() {
5019 let (tmp, talks) = store();
5020 let spec = mock_agent(tmp.path(), ECHO, BTreeMap::new());
5021 let cfg = config(spec);
5022 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
5023
5024 say(
5025 &talks.claim_turn(&talk.id).unwrap().unwrap(),
5026 &mut talk,
5027 &talks,
5028 &cfg,
5029 "what does the queue module do?",
5030 Vec::new(),
5031 )
5032 .await
5033 .expect("first turn");
5034 let first_prompt = &talk.turns[1].body;
5035 assert!(first_prompt.contains("magi task add --solo"));
5036 assert!(first_prompt.contains("what does the queue module do?"));
5037
5038 say(
5039 &talks.claim_turn(&talk.id).unwrap().unwrap(),
5040 &mut talk,
5041 &talks,
5042 &cfg,
5043 "and how is it locked?",
5044 Vec::new(),
5045 )
5046 .await
5047 .expect("second turn");
5048 let second_prompt = &talk.turns[3].body;
5049 assert!(
5050 !second_prompt.contains("magi task add --solo"),
5051 "the briefing is sent once, not on every turn: {second_prompt}"
5052 );
5053 assert!(second_prompt.contains("and how is it locked?"));
5054 }
5055
5056 #[tokio::test]
5057 async fn switching_agent_resets_the_seat_notes_it_and_resends_the_transcript() {
5058 let (tmp, talks) = store();
5059 let a = mock_agent(tmp.path(), ECHO, BTreeMap::new());
5060 let mut b = a.clone();
5061 b.id = "other".to_owned();
5062 let mut cfg = config(a.clone());
5063 cfg.agents.push(b.clone());
5064 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), Some(&a.id)).expect("begin");
5065 say(
5066 &talks.claim_turn(&talk.id).unwrap().unwrap(),
5067 &mut talk,
5068 &talks,
5069 &cfg,
5070 "remember the walrus",
5071 Vec::new(),
5072 )
5073 .await
5074 .expect("first turn");
5075 let old_session = talk.seat.claude_session.clone();
5076 assert_eq!(talk.seat.turns, 1);
5077
5078 assert!(switch_agent(&mut talk, &talks, &b).expect("switch"));
5079 assert_eq!(talk.agent, "other");
5080 assert_eq!(talk.seat.turns, 0);
5081 assert_eq!(talk.seat.agent, "other");
5082 assert_ne!(talk.seat.claude_session, old_session);
5083 let note = talk.turns.last().expect("note");
5084 assert_eq!(note.who, Who::Agent);
5085 assert!(note.body.starts_with(MAGI_NOTE), "{}", note.body);
5086 assert!(note.body.contains("changed from"), "{}", note.body);
5087 assert_eq!(talks.get(&talk.id).expect("reload").agent, "other");
5088
5089 let before = talk.turns.len();
5090 assert!(!switch_agent(&mut talk, &talks, &b).expect("same agent"));
5091 assert_eq!(talk.turns.len(), before, "a no-op writes no note");
5092
5093 say(
5094 &talks.claim_turn(&talk.id).unwrap().unwrap(),
5095 &mut talk,
5096 &talks,
5097 &cfg,
5098 "what did I say?",
5099 Vec::new(),
5100 )
5101 .await
5102 .expect("turn after switch");
5103 let prompt = &talk.turns.last().expect("reply").body;
5104 assert!(prompt.contains("remember the walrus"), "{prompt}");
5105 assert!(prompt.contains("## magi"), "{prompt}");
5106 assert!(prompt.contains("what did I say?"), "{prompt}");
5107 }
5108
5109 #[tokio::test]
5110 async fn say_appends_the_operator_turn_then_the_agent_turn() {
5111 let (tmp, talks) = store();
5112 let spec = mock_agent(tmp.path(), REPLY, env("go ahead"));
5113 let cfg = config(spec);
5114 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
5115
5116 say(
5117 &talks.claim_turn(&talk.id).unwrap().unwrap(),
5118 &mut talk,
5119 &talks,
5120 &cfg,
5121 "can I rename this function?",
5122 Vec::new(),
5123 )
5124 .await
5125 .expect("say");
5126
5127 assert_eq!(talk.turns.len(), 2);
5128 assert_eq!(talk.turns[0].who, Who::Operator);
5129 assert_eq!(talk.turns[0].body, "can I rename this function?");
5130 assert_eq!(talk.turns[1].who, Who::Agent);
5131 assert_eq!(talk.turns[1].body, "go ahead");
5132 assert_eq!(talks.get(&talk.id).expect("get").turns, talk.turns);
5133 }
5134
5135 #[tokio::test]
5136 async fn a_failed_turn_keeps_the_operator_message_and_says_what_happened() {
5137 let (tmp, talks) = store();
5138 let spec = mock_agent(tmp.path(), BROKEN, BTreeMap::new());
5139 let cfg = config(spec);
5140 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
5141
5142 talk.posts_read_through = None;
5143 talks.put(&mut talk).expect("save old-format boundary");
5144 post(&talks, &talk.id, "unread task result", "task").expect("post");
5145 talk = talks.get(&talk.id).expect("reload");
5146
5147 let err = say(
5148 &talks.claim_turn(&talk.id).unwrap().unwrap(),
5149 &mut talk,
5150 &talks,
5151 &cfg,
5152 "check the tests",
5153 Vec::new(),
5154 )
5155 .await
5156 .expect_err("a turn with no answer is an error");
5157 assert!(err.to_string().contains("no answer"), "{err}");
5158
5159 let on_disk = talks.get(&talk.id).expect("get");
5160 assert_eq!(on_disk.turns.len(), 3);
5161 assert_eq!(on_disk.posts_read_through, Some(0));
5162 assert!(
5163 posts_since_last_reply(&on_disk)
5164 .unwrap()
5165 .contains("unread task result")
5166 );
5167 assert_eq!(on_disk.turns[1].body, "check the tests");
5168 let note = &on_disk.turns[2];
5169 assert_eq!(note.who, Who::Agent);
5170 assert!(note.body.starts_with(MAGI_NOTE), "{}", note.body);
5171 assert!(note.body.contains("your message is saved"));
5172 }
5173
5174 #[tokio::test]
5180 async fn a_passing_write_failure_while_saving_the_reply_does_not_lose_it() {
5181 let (tmp, talks) = store();
5182 let spec = mock_agent(tmp.path(), REPLY, env("go ahead"));
5183 let cfg = config(spec);
5184 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
5185
5186 let text =
5187 record(&mut talk, &talks, "can I rename this function?", Vec::new()).expect("record");
5188 failpoint::force_put_failures(PUT_RETRIES - 1);
5191 respond(
5192 &talks.claim_turn(&talk.id).unwrap().unwrap(),
5193 &mut talk,
5194 &talks,
5195 &cfg,
5196 &text,
5197 )
5198 .await
5199 .expect("respond must survive a write failure its own retries can outlast");
5200
5201 assert_eq!(talk.turns.len(), 2);
5202 assert_eq!(talk.turns[1].who, Who::Agent);
5203 assert_eq!(talk.turns[1].body, "go ahead");
5204 let on_disk = talks.get(&talk.id).expect("get");
5205 assert_eq!(
5206 on_disk.turns, talk.turns,
5207 "the reply must reach disk despite the early write failures"
5208 );
5209 }
5210
5211 #[tokio::test]
5217 async fn a_persistent_write_failure_while_saving_the_reply_is_never_silent() {
5218 let (tmp, talks) = store();
5219 let spec = mock_agent(tmp.path(), REPLY, env("go ahead"));
5220 let cfg = config(spec);
5221 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
5222
5223 let text = record(&mut talk, &talks, "check the tests", Vec::new()).expect("record");
5224 failpoint::force_put_failures(PUT_RETRIES);
5229 let err = respond(
5230 &talks.claim_turn(&talk.id).unwrap().unwrap(),
5231 &mut talk,
5232 &talks,
5233 &cfg,
5234 &text,
5235 )
5236 .await
5237 .expect_err("a reply that cannot be saved must be reported, not swallowed");
5238 assert!(err.to_string().contains("could not be saved"), "{err}");
5239
5240 let on_disk = talks.get(&talk.id).expect("get");
5241 assert_eq!(
5242 on_disk.turns.len(),
5243 2,
5244 "the operator turn plus a visible note"
5245 );
5246 assert_eq!(on_disk.turns[0].body, "check the tests");
5247 let note = &on_disk.turns[1];
5248 assert_eq!(note.who, Who::Agent);
5249 assert!(note.body.starts_with(MAGI_NOTE), "{}", note.body);
5250 assert!(
5251 note.body.contains("could not be saved"),
5252 "the operator must be told the reply is missing, not left staring \
5253 at a gap with no explanation: {}",
5254 note.body
5255 );
5256 assert_eq!(
5257 talk.turns, on_disk.turns,
5258 "the in-memory talk must match what actually landed on disk"
5259 );
5260
5261 let artifacts = talks.artifacts_of(&talk.id);
5264 let stash = std::fs::read_dir(&artifacts)
5265 .expect("artifacts dir")
5266 .filter_map(|e| e.ok())
5267 .find(|e| e.file_name().to_string_lossy().ends_with("-lost.txt"))
5268 .expect("a stash file for the lost reply");
5269 let stashed = std::fs::read_to_string(stash.path()).expect("read stash");
5270 assert_eq!(stashed, "go ahead");
5271
5272 assert_eq!(
5280 on_disk.seat.turns, 1,
5281 "the note's write must carry the turn the CLI actually took"
5282 );
5283 assert_eq!(
5284 on_disk.seat.claude_session, talk.seat.claude_session,
5285 "the session id handed to the CLI must survive the failed reply"
5286 );
5287 assert_eq!(on_disk.seat.captured_session, talk.seat.captured_session);
5288 assert!(
5289 agent::has_session(AgentKind::Command, &on_disk.seat, cfg.graph.sessions),
5290 "the next turn must resume, not open the same session id twice"
5291 );
5292 }
5293
5294 #[tokio::test]
5299 async fn a_write_failure_that_also_loses_the_note_still_reports_it() {
5300 let (tmp, talks) = store();
5301 let spec = mock_agent(tmp.path(), REPLY, env("go ahead"));
5302 let cfg = config(spec);
5303 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
5304
5305 let text = record(&mut talk, &talks, "check the tests", Vec::new()).expect("record");
5306 failpoint::force_put_failures(PUT_RETRIES * 2);
5309 let err = respond(
5310 &talks.claim_turn(&talk.id).unwrap().unwrap(),
5311 &mut talk,
5312 &talks,
5313 &cfg,
5314 &text,
5315 )
5316 .await
5317 .expect_err("neither the reply nor the note could be saved");
5318 assert!(err.to_string().contains("could not be saved"), "{err}");
5319
5320 assert_eq!(talk.turns.len(), 1, "only the operator's own turn");
5321 let on_disk = talks.get(&talk.id).expect("get");
5322 assert_eq!(on_disk.turns.len(), 1);
5323
5324 assert_eq!(
5334 on_disk.seat.turns, 0,
5335 "an unwritable file cannot record the turn the CLI took"
5336 );
5337 assert_eq!(
5338 talk.seat.turns, 1,
5339 "the in-memory seat still reports the turn the CLI actually took"
5340 );
5341 assert_eq!(
5342 on_disk.seat.claude_session, talk.seat.claude_session,
5343 "the session id was minted at `begin` and never changes here"
5344 );
5345 }
5346
5347 #[tokio::test]
5351 async fn attachments_reach_the_prompt_and_an_empty_body_is_still_a_turn() {
5352 let (tmp, talks) = store();
5353 let spec = mock_agent(tmp.path(), ECHO, BTreeMap::new());
5354 let cfg = config(spec);
5355 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
5356
5357 let att = talks
5358 .put_attachment(
5359 &talk.id,
5360 "image/png",
5361 "screenshot.png",
5362 b"pretend-png-bytes",
5363 )
5364 .expect("put attachment");
5365
5366 say(
5367 &talks.claim_turn(&talk.id).unwrap().unwrap(),
5368 &mut talk,
5369 &talks,
5370 &cfg,
5371 "",
5372 vec![att.clone()],
5373 )
5374 .await
5375 .expect("an empty body with an attachment is still a turn");
5376
5377 let operator_turn = &talk.turns[0];
5378 assert_eq!(operator_turn.who, Who::Operator);
5379 assert_eq!(operator_turn.body, "");
5380 assert_eq!(operator_turn.attachments, vec![att.clone()]);
5381
5382 let prompt = &talk.turns[1].body;
5383 let expected_path = talks
5384 .attachments_dir(&talk.id)
5385 .join(format!("{}.png", att.id));
5386 assert!(
5387 prompt.contains(&expected_path.display().to_string()),
5388 "the agent must be told the attachment's absolute path: {prompt}"
5389 );
5390 assert!(prompt.contains("image/png"), "and its mime: {prompt}");
5391 }
5392
5393 #[test]
5402 fn attachment_path_is_absolute_even_when_the_store_root_is_relative() {
5403 let talks = Talks::at(PathBuf::from("relative-talks-root-for-this-test"));
5404 let att = Attachment {
5405 id: "0".repeat(32),
5406 name: "shot.png".to_owned(),
5407 mime: "image/png".to_owned(),
5408 bytes: 3,
5409 };
5410 let path = talks
5411 .attachment_path("some-talk-id", &att)
5412 .expect("a supported mime always yields a path");
5413 assert!(
5414 path.is_absolute(),
5415 "must be absolute even off a relative store root: {}",
5416 path.display()
5417 );
5418 }
5419
5420 #[tokio::test]
5421 async fn a_turn_past_the_configured_talk_timeout_is_reported_with_that_timeout() {
5422 let (tmp, talks) = store();
5427 let slow = mock_agent(
5428 tmp.path(),
5429 "#!/bin/sh\ncat >/dev/null\nsleep 2\n",
5430 BTreeMap::new(),
5431 );
5432 let mut cfg = config(slow);
5433 cfg.graph.timeout_talk = 1;
5434 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
5435
5436 let err = say(
5437 &talks.claim_turn(&talk.id).unwrap().unwrap(),
5438 &mut talk,
5439 &talks,
5440 &cfg,
5441 "check the tests",
5442 Vec::new(),
5443 )
5444 .await
5445 .expect_err("a turn that never answers is an error");
5446 assert!(
5447 err.to_string().contains("did not answer within 1s"),
5448 "{err}"
5449 );
5450
5451 let on_disk = talks.get(&talk.id).expect("get");
5452 let note = on_disk.turns.last().expect("a note turn was recorded");
5453 assert!(
5454 note.body.contains("did not answer within 1s"),
5455 "the transcript must show the configured timeout: {}",
5456 note.body
5457 );
5458 }
5459
5460 #[test]
5461 fn closing_is_idempotent_and_a_closed_talk_takes_no_more_turns() {
5462 let (tmp, talks) = store();
5463 let spec = mock_agent(tmp.path(), REPLY, env("hi"));
5464 let cfg = config(spec);
5465 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
5466
5467 close(&mut talk, &talks).expect("close");
5468 assert_eq!(talk.status, TalkStatus::Closed);
5469 close(&mut talk, &talks).expect("closing twice is not an error");
5470
5471 let err =
5472 record(&mut talk, &talks, "still there?", Vec::new()).expect_err("closed talks refuse");
5473 assert!(err.to_string().contains("closed"));
5474 let _ = &cfg; }
5476
5477 #[tokio::test]
5478 async fn a_close_that_lands_while_a_turn_is_in_flight_is_not_undone_by_the_reply() {
5479 let (tmp, talks) = store();
5480 let spec = mock_agent(tmp.path(), REPLY, env("here you go"));
5481 let cfg = config(spec);
5482 let mut in_flight = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
5485
5486 let mut closed_elsewhere = talks.get(&in_flight.id).expect("reread");
5490 close(&mut closed_elsewhere, &talks).expect("close");
5491 assert_eq!(
5492 talks.get(&in_flight.id).expect("reread").status,
5493 TalkStatus::Closed,
5494 "the close landed on disk before the turn finished"
5495 );
5496
5497 assert_eq!(in_flight.status, TalkStatus::Open);
5501 respond(
5502 &talks.claim_turn(&in_flight.id).unwrap().unwrap(),
5503 &mut in_flight,
5504 &talks,
5505 &cfg,
5506 "one more question",
5507 )
5508 .await
5509 .expect("the turn itself still completes");
5510
5511 let on_disk = talks.get(&in_flight.id).expect("reread");
5512 assert_eq!(
5513 on_disk.status,
5514 TalkStatus::Closed,
5515 "a close must stick even when a turn that started before it finishes after it"
5516 );
5517 assert!(
5520 on_disk.turns.iter().any(|t| t.body == "here you go"),
5521 "the in-flight turn's own reply is still recorded: {:?}",
5522 on_disk.turns
5523 );
5524 }
5525
5526 #[test]
5527 fn a_close_that_lands_before_record_is_called_is_not_undone_by_it() {
5528 let (tmp, talks) = store();
5529 let spec = mock_agent(tmp.path(), REPLY, env("hi"));
5530 let cfg = config(spec);
5531 let mut stale = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
5534
5535 let mut closed_elsewhere = talks.get(&stale.id).expect("reread");
5538 close(&mut closed_elsewhere, &talks).expect("close");
5539 assert_eq!(
5540 talks.get(&stale.id).expect("reread").status,
5541 TalkStatus::Closed,
5542 "the close landed on disk before record was called"
5543 );
5544
5545 assert_eq!(stale.status, TalkStatus::Open);
5549 let err = record(&mut stale, &talks, "still there?", Vec::new())
5550 .expect_err("a close that landed first must be honored, not overwritten");
5551 assert!(err.to_string().contains("closed"));
5552
5553 let on_disk = talks.get(&stale.id).expect("reread");
5554 assert_eq!(
5555 on_disk.status,
5556 TalkStatus::Closed,
5557 "record must not resurrect a conversation closed while its snapshot was stale"
5558 );
5559 assert!(
5560 on_disk.turns.is_empty(),
5561 "the rejected turn must not have been appended: {:?}",
5562 on_disk.turns
5563 );
5564 let _ = &cfg; }
5566
5567 #[test]
5568 fn consultation_queue_does_not_wait_on_either_conversation_lock() {
5569 for evidence in [true, false] {
5570 let (tmp, talks) = store();
5571 let cfg = config(mock_agent(tmp.path(), REPLY, env("hi")));
5572 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).unwrap();
5573 close(&mut talk, &talks).unwrap();
5574 let answer = evidence.then(|| talks.answer_guard().unwrap());
5575 let file = (!evidence).then(|| {
5576 TurnLock::take(&talks.root.join(".store.turn"))
5577 .unwrap()
5578 .unwrap()
5579 });
5580 assert!(
5581 try_queue_consult(&talks, &talk.id, "consultation", None)
5582 .unwrap()
5583 .is_none()
5584 );
5585 let saved = talks.get(&talk.id).unwrap();
5586 assert_eq!(saved.status, TalkStatus::Closed);
5587 assert!(saved.pending_messages.is_empty());
5588 drop(file);
5589 drop(answer);
5590 assert!(
5591 try_queue_consult(&talks, &talk.id, "consultation", None)
5592 .unwrap()
5593 .is_some()
5594 );
5595 let saved = talks.get(&talk.id).unwrap();
5596 assert_eq!(saved.status, TalkStatus::Open);
5597 assert_eq!(saved.pending, "consultation");
5598 assert_eq!(saved.pending_messages.len(), 1);
5599 assert_eq!(saved.pending_messages[0].sender, Some(Sender::Magi));
5600 }
5601 }
5602
5603 #[test]
5604 fn evidence_try_lock_does_not_wait_for_either_store_handle() {
5605 let (tmp, talks) = store();
5606 let guard = talks.answer_guard().unwrap();
5607 assert!(talks.try_answer_guard().unwrap().is_none());
5609 let other = Talks::at(tmp.path().join("talks"));
5610 assert!(other.try_answer_guard().unwrap().is_none());
5611 drop(guard);
5612 assert!(other.try_answer_guard().unwrap().is_some());
5613 }
5614
5615 #[test]
5616 fn owner_retraction_waits_until_the_authorized_question_is_persisted() {
5617 use crate::ask::{Answer, Question, Questions};
5618 use std::sync::mpsc;
5619
5620 let (tmp, talks) = store();
5621 let cfg = config(mock_agent(tmp.path(), REPLY, env("hi")));
5622 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).unwrap();
5623 let questions = Questions::at(tmp.path().join("questions"));
5624 let mut q = Question::new(
5625 "run".into(),
5626 crate::land::APPROVAL_NODE.into(),
5627 "land".into(),
5628 "Merge?".into(),
5629 String::new(),
5630 vec!["merge".into(), "hold".into()],
5631 );
5632 questions.put(&mut q).unwrap();
5633 let instruction = format!("{}: hold", q.id);
5634 record(&mut talk, &talks, &instruction, vec![]).unwrap();
5635 let (started_tx, started_rx) = mpsc::channel();
5636 let (finished_tx, finished_rx) = mpsc::channel();
5637 std::thread::scope(|scope| {
5638 let mut writer = None;
5639 let (saved, guard) = questions
5640 .update(&q.id, |q| {
5641 let guard = talks.try_answer_guard()?.context("evidence is busy")?;
5642 q.answer_authority = crate::consult::authorize_answer(
5643 q,
5644 &talks,
5645 &questions,
5646 &talk.id,
5647 crate::queue::CHAT_NODE,
5648 "hold",
5649 Some(&instruction),
5650 )?;
5651 assert!(q.answer_authority.is_some());
5652 let talks = talks.clone();
5653 let mut snapshot = talk.clone();
5654 writer = Some(scope.spawn(move || {
5655 started_tx.send(()).unwrap();
5656 queue(&mut snapshot, &talks, "wait", vec![]).unwrap();
5657 finished_tx.send(()).unwrap();
5658 }));
5659 started_rx.recv().unwrap();
5660 assert!(matches!(
5661 finished_rx.recv_timeout(Duration::from_millis(100)),
5662 Err(mpsc::RecvTimeoutError::Timeout)
5663 ));
5664 q.answer(Answer::Choice("hold".into()))?;
5665 Ok(guard)
5667 })
5668 .unwrap();
5669 assert_eq!(saved.resolution().as_deref(), Some("hold"));
5670 assert_eq!(
5671 questions.get(&q.id).unwrap().resolution().as_deref(),
5672 Some("hold")
5673 );
5674 assert!(matches!(
5675 finished_rx.recv_timeout(Duration::from_millis(100)),
5676 Err(mpsc::RecvTimeoutError::Timeout)
5677 ));
5678 drop(guard);
5679 writer.unwrap().join().unwrap();
5680 finished_rx.recv().unwrap();
5681 });
5682 assert_eq!(talks.get(&talk.id).unwrap().pending, "wait");
5683 }
5684
5685 #[test]
5686 fn close_blocks_on_records_guard_rather_than_interleaving_with_it() {
5687 let (tmp, talks) = store();
5688 let spec = mock_agent(tmp.path(), REPLY, env("hi"));
5689 let cfg = config(spec);
5690 let talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
5691
5692 let held = talks.guard().unwrap();
5696
5697 let talks2 = talks.clone();
5698 let id = talk.id.clone();
5699 let closing = std::thread::spawn(move || {
5700 let mut talk = talks2.get(&id).expect("get");
5701 close(&mut talk, &talks2).expect("close");
5702 });
5703
5704 std::thread::sleep(Duration::from_millis(50));
5705 assert!(
5706 !closing.is_finished(),
5707 "close must wait for the guard, not read and write while it is held - \
5708 a re-read alone narrows this window without closing it"
5709 );
5710
5711 drop(held);
5712 closing.join().expect("close thread panicked");
5713
5714 assert_eq!(
5715 talks.get(&talk.id).expect("reread").status,
5716 TalkStatus::Closed,
5717 "once the guard is free, close still lands"
5718 );
5719 let _ = &cfg; }
5721
5722 #[test]
5723 fn reopening_a_closed_talk_lets_it_take_turns_again_and_reopening_twice_is_not_an_error() {
5724 let (tmp, talks) = store();
5725 let spec = mock_agent(tmp.path(), REPLY, env("hi"));
5726 let cfg = config(spec);
5727 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
5728
5729 close(&mut talk, &talks).expect("close");
5730 assert_eq!(talk.status, TalkStatus::Closed);
5731
5732 reopen(&mut talk, &talks).expect("reopen");
5733 assert_eq!(talk.status, TalkStatus::Open);
5734 assert_eq!(
5735 talks.get(&talk.id).expect("reread").status,
5736 TalkStatus::Open
5737 );
5738
5739 reopen(&mut talk, &talks).expect("reopening an open talk is not an error");
5741 assert_eq!(talk.status, TalkStatus::Open);
5742
5743 record(&mut talk, &talks, "one more thing", Vec::new())
5744 .expect("a reopened talk takes turns again");
5745 let _ = &cfg; }
5747
5748 #[test]
5749 fn removing_a_talk_deletes_its_record_and_artifacts_and_refuses_an_unknown_id() {
5750 let (tmp, talks) = store();
5751 let spec = mock_agent(tmp.path(), REPLY, env("hi"));
5752 let cfg = config(spec);
5753 let talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
5754
5755 let artifacts = talks.artifacts_of(&talk.id);
5756 std::fs::create_dir_all(&artifacts).expect("create artifacts dir");
5757 std::fs::write(artifacts.join("turn-1.txt"), "hello").expect("write artifact");
5758
5759 talks.remove(&talk.id).expect("remove");
5760 assert!(!talks.path_of(&talk.id).is_file(), "the record is gone");
5761 assert!(!artifacts.is_dir(), "the artifacts directory is gone");
5762 assert!(
5763 talks.get(&talk.id).is_err(),
5764 "a removed talk cannot be read back"
5765 );
5766
5767 let err = talks
5768 .remove("nonexistent-id")
5769 .expect_err("unknown id refused");
5770 assert!(err.to_string().contains("no talk matches"), "{err}");
5771 let _ = &cfg; }
5773
5774 #[tokio::test]
5775 async fn a_delete_that_lands_while_a_turn_is_in_flight_is_not_undone_by_the_reply() {
5776 let (tmp, talks) = store();
5777 let spec = mock_agent(tmp.path(), REPLY, env("here you go"));
5778 let cfg = config(spec);
5779 let mut in_flight = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
5782
5783 talks.remove(&in_flight.id).expect("remove");
5784 assert!(
5785 talks.get(&in_flight.id).is_err(),
5786 "the delete landed on disk before the turn finished"
5787 );
5788
5789 respond(
5792 &talks.claim_turn(&in_flight.id).unwrap().unwrap(),
5793 &mut in_flight,
5794 &talks,
5795 &cfg,
5796 "one more question",
5797 )
5798 .await
5799 .expect("the turn itself still completes rather than erroring");
5800
5801 assert!(
5802 talks.get(&in_flight.id).is_err(),
5803 "a delete must stick even when a turn that started before it finishes after it"
5804 );
5805 }
5806
5807 #[test]
5808 fn a_delete_that_lands_before_record_is_called_is_not_undone_by_it() {
5809 let (tmp, talks) = store();
5810 let spec = mock_agent(tmp.path(), REPLY, env("hi"));
5811 let cfg = config(spec);
5812 let mut stale = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
5815
5816 talks.remove(&stale.id).expect("remove");
5817
5818 let err = record(&mut stale, &talks, "still there?", Vec::new())
5822 .expect_err("a delete that landed first must be honored, not overwritten");
5823 assert!(err.to_string().contains("deleted"), "{err}");
5824
5825 assert!(
5826 talks.get(&stale.id).is_err(),
5827 "record must not resurrect a conversation deleted while its snapshot was stale"
5828 );
5829 let _ = &cfg; }
5831
5832 #[test]
5833 fn a_delete_that_lands_before_close_is_called_is_not_undone_by_it() {
5834 let (tmp, talks) = store();
5835 let spec = mock_agent(tmp.path(), REPLY, env("hi"));
5836 let cfg = config(spec);
5837 let mut stale = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
5840
5841 talks.remove(&stale.id).expect("remove");
5842
5843 let err = close(&mut stale, &talks)
5847 .expect_err("a delete that landed first must be honored, not overwritten");
5848 assert!(err.to_string().contains("deleted"), "{err}");
5849
5850 assert!(
5851 talks.get(&stale.id).is_err(),
5852 "close must not resurrect a conversation deleted while its snapshot was stale"
5853 );
5854 let _ = &cfg; }
5856
5857 #[test]
5858 fn a_delete_that_lands_before_reopen_is_called_is_not_undone_by_it() {
5859 let (tmp, talks) = store();
5860 let spec = mock_agent(tmp.path(), REPLY, env("hi"));
5861 let cfg = config(spec);
5862 let mut stale = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
5865 close(&mut stale, &talks).expect("close");
5866
5867 talks.remove(&stale.id).expect("remove");
5868
5869 let err = reopen(&mut stale, &talks)
5873 .expect_err("a delete that landed first must be honored, not overwritten");
5874 assert!(err.to_string().contains("deleted"), "{err}");
5875
5876 assert!(
5877 talks.get(&stale.id).is_err(),
5878 "reopen must not resurrect a conversation deleted while its snapshot was stale"
5879 );
5880 let _ = &cfg; }
5882
5883 #[test]
5884 fn list_puts_open_talks_before_closed_ones() {
5885 let (tmp, talks) = store();
5886 let make = |id: &str, status: TalkStatus| {
5887 let mut t = Talk {
5888 recommendations: Default::default(),
5889 posts_read_through: None,
5890 pending_breaks: None,
5891 pending_messages: Vec::new(),
5892 schema: SCHEMA,
5893 id: id.to_owned(),
5894 repo: tmp.path().to_owned(),
5895 agent: "mock".to_owned(),
5896 status,
5897 turns: Vec::new(),
5898 pending: String::new(),
5899 pending_attachments: Vec::new(),
5900 fallback: false,
5901 persona: String::new(),
5902 persona_dirty: false,
5903 implementers: 1,
5904 implementers_dirty: false,
5905 notified: Vec::new(),
5906 completion_notices: Vec::new(),
5907 created_at: Timestamp::now(),
5908 updated_at: Timestamp::now(),
5909 seat: SeatState::new(SEAT, "mock", 7),
5910 };
5911 talks.put(&mut t).expect("put");
5912 };
5913 make("20260901-000000-0001", TalkStatus::Open);
5914 make("20260902-000000-0002", TalkStatus::Open);
5915 make("20260903-000000-0003", TalkStatus::Closed);
5916
5917 let ids: Vec<String> = talks.list().into_iter().map(|t| t.id).collect();
5918 assert_eq!(
5919 ids,
5920 [
5921 "20260902-000000-0002",
5922 "20260901-000000-0001",
5923 "20260903-000000-0003"
5924 ]
5925 );
5926 assert_eq!(talks.count_open(), 2);
5927 }
5928
5929 #[test]
5930 fn tasks_of_finds_only_this_talks_own_tasks() {
5931 let dir = tempfile::tempdir().expect("tempdir");
5932 let queue = Queue::at(dir.path().join("queue"));
5933
5934 let mut mine = Task::new(
5935 "rework the loader".to_owned(),
5936 "rework the loader".to_owned(),
5937 PathBuf::from("/repo"),
5938 Source::Agent {
5939 run: "20260904-014455-ab12".to_owned(),
5940 node: "chat".to_owned(),
5941 },
5942 );
5943 queue.put(&mut mine).expect("put mine");
5944
5945 let mut theirs = Task::new(
5946 "unrelated".to_owned(),
5947 "unrelated".to_owned(),
5948 PathBuf::from("/repo"),
5949 Source::Agent {
5950 run: "20260904-090000-zz99".to_owned(),
5951 node: "implement".to_owned(),
5952 },
5953 );
5954 queue.put(&mut theirs).expect("put theirs");
5955
5956 let mut human = Task::new(
5957 "typed by hand".to_owned(),
5958 "typed by hand".to_owned(),
5959 PathBuf::from("/repo"),
5960 Source::Human,
5961 );
5962 queue.put(&mut human).expect("put human");
5963
5964 let found = tasks_of(&queue, "20260904-014455-ab12");
5965 assert_eq!(found.len(), 1);
5966 assert_eq!(found[0].id, mine.id);
5967 }
5968
5969 #[test]
5970 fn the_briefing_names_solo_task_add() {
5971 let brief = briefing(Path::new("/repo"), "en", false);
5972 assert!(brief.contains("magi task add --solo"));
5973 assert!(brief.contains("/repo"));
5974 assert!(!brief.contains("Hold this conversation in"));
5975 }
5976
5977 #[test]
5983 fn the_briefing_explains_targeting_a_different_repository_by_name() {
5984 let brief = briefing(Path::new("/repo"), "en", false);
5985 assert!(brief.contains("--repo does not have to be a full path"));
5986 assert!(brief.contains("owner/repo"));
5987 assert!(brief.contains("magi repos"));
5988 assert!(brief.contains("ask the operator"));
5989 }
5990
5991 #[test]
5992 fn the_briefing_tells_the_assistant_to_pass_images_with_attach() {
5993 let brief = briefing(Path::new("/repo"), "en", false);
5994 assert!(brief.contains("--attach <path>"), "{brief}");
5995 assert!(brief.contains("deleting this conversation"), "{brief}");
5996 }
5997
5998 #[test]
5999 fn the_briefing_names_the_language_when_it_is_not_english() {
6000 let brief = briefing(Path::new("/repo"), "Japanese", false);
6001 assert!(brief.contains("Hold this conversation in Japanese"));
6002 }
6003
6004 #[test]
6005 fn the_briefing_forbids_writes_unless_the_repository_opted_in() {
6006 let read_only = briefing(Path::new("/repo"), "en", false);
6007 assert!(read_only.contains("Do not write files"));
6008 assert!(!read_only.contains("allow_write"));
6009
6010 let writable = briefing(Path::new("/repo"), "en", true);
6011 assert!(!writable.contains("Do not write files"));
6012 assert!(writable.contains("allow_write = true"));
6013 assert!(writable.contains("magi task add --solo"));
6016 assert!(writable.contains("say plainly what you"));
6017 }
6018
6019 #[test]
6020 fn the_briefing_says_the_chat_cannot_push_and_tasks_report_back() {
6021 let b = briefing_for(Path::new("/r"), "en", false, None, None, 1);
6022 assert!(
6023 b.contains("cannot send the operator a message on your own"),
6024 "{b}"
6025 );
6026 assert!(b.contains(crate::prompt::CHAT_TASK_NOTICE_HEADING));
6027 assert!(b.contains("magi talk watch --timeout 900"));
6028 assert!(b.contains("nor a successfully registered watch"));
6029 }
6030
6031 #[test]
6032 fn a_post_is_replayed_until_the_agent_answers_again() {
6033 let (_tmp, talks) = store();
6034 let mut talk = ctx_talk("mock", Vec::new());
6035 talks.put(&mut talk).expect("put");
6036 post(&talks, &talk.id, " found it ", "20260902-000000-aaaa").expect("post");
6037 let mut talk = talks.get(&talk.id).expect("get");
6038 let block = posts_since_last_reply(&talk).expect("block");
6039 assert!(block.starts_with("# Posted by a task"), "{block}");
6040 assert!(block.contains("found it"));
6041 talk.turns.push(reply("ok", None));
6042 assert!(posts_since_last_reply(&talk).is_none());
6043 assert!(post(&talks, &talk.id, " ", "r").is_err());
6044 close(&mut talk, &talks).expect("close");
6045 assert!(post(&talks, &talk.id, "late", "r").is_err());
6046 }
6047
6048 #[test]
6049 fn queue_once_accepts_a_key_a_single_time_even_after_a_drain() {
6050 let (_tmp, talks) = store();
6051 let mut talk = ctx_talk("mock", Vec::new());
6052 talks.put(&mut talk).expect("put");
6053 assert!(queue_once(&mut talk, &talks, "one", "k").expect("first"));
6054 drain(&mut talk, &talks).expect("drain");
6055 assert!(!queue_once(&mut talk, &talks, "one", "k").expect("again"));
6056 assert!(talks.get(&talk.id).expect("get").pending.is_empty());
6057 }
6058 #[test]
6059 fn sender_mixed_notifications_survive_reload_drain_and_reply() {
6060 let (_tmp, talks) = store();
6061 let mut talk = ctx_talk("mock", Vec::new());
6062 talks.put(&mut talk).unwrap();
6063 queue(&mut talk, &talks, "owner", Vec::new()).unwrap();
6064 assert!(queue_once(&mut talk, &talks, "notice", "n").unwrap());
6065 let mut talk = talks.get(&talk.id).unwrap();
6066 assert_eq!(talk.pending_messages[0].sender, Some(Sender::Operator));
6067 assert_eq!(talk.pending_messages[1].sender, Some(Sender::Magi));
6068 assert!(
6069 edit_pending_message(&mut talk, &talks, "forged", "owner\n\nnotice", &[], Some(1))
6070 .is_err()
6071 );
6072 drain(&mut talk, &talks).unwrap();
6073 let mut talk = talks.get(&talk.id).unwrap();
6074 let turn = talk.turns.last().unwrap();
6075 assert_eq!(turn.who, Who::Operator);
6076 assert_eq!(sender(turn, turn.messages.first()), Sender::Operator);
6077 assert_eq!(sender(turn, turn.messages.get(1)), Sender::Magi);
6078 let reply = resolve_reply(
6079 &talk,
6080 Some(ReplyTarget {
6081 turn: 0,
6082 message: 1,
6083 }),
6084 )
6085 .unwrap()
6086 .unwrap();
6087 assert_eq!(reply.sender, Some(Sender::Magi));
6088 assert!(!queue_once(&mut talk, &talks, "notice", "n").unwrap());
6089 }
6090
6091 #[test]
6092 fn sender_legacy_operator_prose_is_never_migrated_by_heading() {
6093 let mut turn = reply("# Task finished\n\nmagi: operator typed this", None);
6094 turn.who = Who::Operator;
6095 assert_eq!(sender(&turn, None), Sender::Operator);
6096 turn.who = Who::Agent;
6097 turn.body = "magi: failed".into();
6098 assert_eq!(sender(&turn, None), Sender::Magi);
6099 turn.body = "persona reply".into();
6100 assert_eq!(sender(&turn, None), Sender::Persona);
6101 turn.posted_by = Some("task".into());
6102 assert_eq!(sender(&turn, None), Sender::Magi);
6103 turn.posted_by = None;
6104 turn.body = "magi: actual persona words".into();
6105 turn.sender = Some(Sender::Persona);
6106 assert_eq!(sender(&turn, None), Sender::Persona);
6107 }
6108}