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 wait = crate::repo_lock::WaitPolicy::new(
2563 Duration::from_secs(cfg.graph.timeout_resource_wait),
2564 || false,
2565 );
2566 let result = wait.scope(agent::invoke(spec, &mut talk.seat, &inv)).await;
2567 let advance = agent::chain_advances(&result);
2568 if n == 0 || !advance {
2569 outcome = Some(result);
2570 } else {
2571 tracing::warn!("chat: fallback agent `{}` also failed", spec.id);
2573 }
2574 if !advance {
2575 break;
2576 }
2577 }
2578 if outcome.as_ref().is_some_and(agent::chain_advances) {
2579 if let Some((id, seat)) = first_try {
2582 talk.agent = id;
2583 talk.seat = seat;
2584 fell_back_from = None;
2585 }
2586 }
2587 let outcome = outcome.expect("a chain holds at least one agent");
2588 let note = |why: String| Turn {
2589 sender: Some(Sender::Magi),
2590 breaks: None,
2591 messages: Vec::new(),
2592 posted_by: None,
2593 who: Who::Agent,
2594 body: format!("{MAGI_NOTE}{why}"),
2595 at: Timestamp::now(),
2596 attachments: Vec::new(),
2597 usage: None,
2598 };
2599 let (reply, failure) = match outcome {
2600 Err(e) => (
2601 note(format!("could not run agent `{}`: {e}", talk.agent)),
2602 Some(format!("could not run agent `{}`: {e}", talk.agent)),
2603 ),
2604 Ok(out) if out.quota_exhausted() => {
2605 let reset = out
2606 .quota
2607 .as_ref()
2608 .and_then(|q| q.reset.clone())
2609 .map_or_else(String::new, |r| format!(" (resets {r})"));
2610 let why = format!(
2611 "agent `{}` is out of quota{reset}; your message is saved, so \
2612 say it again when the window reopens",
2613 talk.agent
2614 );
2615 (note(why.clone()), Some(why))
2616 }
2617 Ok(out) if out.timed_out => {
2618 let why = format!(
2619 "agent `{}` did not answer within {}s; your message is saved",
2620 talk.agent,
2621 turn_timeout(cfg).as_secs()
2622 );
2623 (note(why.clone()), Some(why))
2624 }
2625 Ok(out) if !out.usable() => {
2626 let why = format!(
2627 "agent `{}` produced no answer (exit {}); your message is saved",
2628 talk.agent,
2629 out.exit_code
2630 .map_or_else(|| "unknown".to_owned(), |c| c.to_string())
2631 );
2632 (note(why.clone()), Some(why))
2633 }
2634 Ok(out) => (
2635 Turn {
2636 sender: Some(Sender::Persona),
2637 breaks: None,
2638 messages: Vec::new(),
2639 posted_by: None,
2640 who: Who::Agent,
2641 body: out.text.trim().to_owned(),
2642 at: Timestamp::now(),
2643 attachments: Vec::new(),
2644 usage: out.context_tokens.map(|context_tokens| TurnUsage {
2647 context_tokens,
2648 agent: talk.agent.clone(),
2649 model: cfg
2650 .agents
2651 .iter()
2652 .find(|a| a.id == talk.agent)
2653 .and_then(|a| a.model.clone()),
2654 }),
2655 },
2656 None,
2657 ),
2658 };
2659
2660 let _guard = store.guard()?;
2672 let Ok(fresh) = store.get(&talk.id) else {
2678 return Ok(());
2679 };
2680 talk.status = fresh.status;
2681 talk.pending = fresh.pending;
2685 talk.pending_breaks = fresh.pending_breaks;
2686 talk.pending_messages = fresh.pending_messages;
2687 talk.pending_attachments = fresh.pending_attachments;
2688 talk.notified = fresh.notified;
2689 if fresh.turns.len() > talk.turns.len() {
2691 let posted: Vec<Turn> = fresh.turns[talk.turns.len()..]
2692 .iter()
2693 .filter(|t| t.posted_by.is_some())
2694 .cloned()
2695 .collect();
2696 talk.turns.extend(posted);
2697 }
2698 if let Some(from) = fell_back_from.filter(|_| failure.is_none()) {
2699 talk.turns.push(note(format!(
2702 "agent changed from {from} to {} (fallback)",
2703 talk.agent
2704 )));
2705 }
2706 if failure.is_none() {
2709 talk.persona_dirty = false;
2710 talk.implementers_dirty = false;
2711 talk.posts_read_through = Some(prompt_turns);
2712 }
2713 talk.turns.push(reply);
2714 if let Err(put_err) = store.put(talk) {
2715 let lost = talk.turns.pop().expect("just pushed above");
2724 let stash = stash_lost_turn(store, &talk.id, &stem, &lost);
2725 let why = match &stash {
2726 Ok(path) => format!(
2727 "agent `{}` answered, but the reply could not be saved to \
2728 this conversation ({put_err:#}); the raw text was kept at \
2729 {} - your message is saved, ask again",
2730 talk.agent,
2731 path.display()
2732 ),
2733 Err(stash_err) => format!(
2734 "agent `{}` answered, but the reply could not be saved to \
2735 this conversation ({put_err:#}), and it could not be kept \
2736 anywhere else either ({stash_err:#}); your message is \
2737 saved, ask again",
2738 talk.agent
2739 ),
2740 };
2741 talk.turns.push(note(why.clone()));
2742 return match store.put(talk) {
2749 Ok(()) => bail!("{why}"),
2750 Err(note_err) => {
2751 talk.turns.pop();
2771 Err(note_err).context(why)
2772 }
2773 };
2774 }
2775
2776 match failure {
2777 Some(why) => bail!("{why}"),
2778 None => Ok(()),
2779 }
2780}
2781
2782fn transcript(talk: &Talk, store: &Talks) -> String {
2785 let mut out = String::from(
2786 "This conversation cannot resume on the CLI's side, so here is \
2787 everything said so far; answer only the last message.\n",
2788 );
2789 for t in &talk.turns {
2790 let who = match t.who {
2791 Who::Operator => "operator",
2792 Who::Agent if t.body.starts_with(MAGI_NOTE) => "magi",
2793 Who::Agent => "you",
2794 };
2795 out.push_str(&format!(
2796 "\n## {who}\n\n{}\n",
2797 message_prompt(t, talk, store).trim()
2798 ));
2799 out.push_str(&attachment_note(store, &talk.id, &t.attachments));
2800 }
2801 out
2802}
2803
2804fn attachment_note(store: &Talks, talk_id: &str, attachments: &[Attachment]) -> String {
2809 if attachments.is_empty() {
2810 return String::new();
2811 }
2812 let mut out = String::from(
2813 "\n\nThe operator attached the image(s) below to this message. Open \
2814 and look at each one before you answer.\n",
2815 );
2816 for att in attachments {
2817 if let Some(path) = store.attachment_path(talk_id, att) {
2818 out.push_str(&format!("\n- {} ({})", path.display(), att.mime));
2819 }
2820 }
2821 out.push('\n');
2822 out
2823}
2824
2825pub(crate) fn turn_access(talk_allow_write: bool, consulted: bool) -> (bool, bool) {
2836 (talk_allow_write || consulted, talk_allow_write)
2837}
2838
2839pub fn briefing(repo: &Path, language: &str, allow_write: bool) -> String {
2855 briefing_with(repo, language, allow_write, None, None)
2856}
2857
2858pub fn briefing_with(
2863 repo: &Path,
2864 language: &str,
2865 allow_write: bool,
2866 persona: Option<&crate::persona::Persona>,
2867 operator_name: Option<&str>,
2868) -> String {
2869 briefing_for(repo, language, allow_write, persona, operator_name, 1)
2870}
2871
2872pub const MAX_IMPLEMENTERS: u8 = 3;
2874
2875fn solo_implementers() -> u8 {
2876 1
2877}
2878
2879fn filing_flag(n: u8) -> String {
2882 if n <= 1 {
2883 "--solo".to_owned()
2884 } else {
2885 format!("--implementers {n}")
2886 }
2887}
2888
2889pub fn filing_update_block(n: u8) -> String {
2892 let flag = filing_flag(n);
2893 if n <= 1 {
2894 format!(
2895 "# Task filing update\n\nThe operator changed how many implementers tasks use. \
2896 From now on file with `magi task add {flag} --repo <repo> <instruction>` \
2897 (one implementer, straight into review).\n"
2898 )
2899 } else {
2900 format!(
2901 "# Task filing update\n\nThe operator changed how many implementers tasks use. \
2902 From now on file with `magi task add {flag} --repo <repo> <instruction>` \
2903 ({n} independent implementations compete). Do not pass `--solo` \
2904 together with `--implementers`; drop any earlier `--solo`.\n"
2905 )
2906 }
2907}
2908
2909pub fn check_implementers(n: u8, cfg: &crate::config::Config) -> std::result::Result<u8, String> {
2912 if !(1..=MAX_IMPLEMENTERS).contains(&n) {
2913 return Err(format!(
2914 "implementers must be 1..={MAX_IMPLEMENTERS}, got {n}"
2915 ));
2916 }
2917 if n > 1 {
2918 let mut cfg = cfg.clone();
2919 crate::queue::RunOverrides {
2920 candidates: Some(usize::from(n)),
2921 ..Default::default()
2922 }
2923 .apply(&mut cfg);
2924 cfg.resolve_roles()
2925 .map_err(|e| format!("{n} implementers is not allowed here: {e:#}"))?;
2926 }
2927 Ok(n)
2928}
2929
2930pub fn switch_implementers(talk: &mut Talk, store: &Talks, n: u8) -> Result<bool> {
2933 let _guard = store.guard()?;
2934 let mut fresh = store
2935 .get(&talk.id)
2936 .with_context(|| format!("talk {} was deleted", talk.short()))?;
2937 if fresh.implementers == n {
2938 *talk = fresh;
2939 return Ok(false);
2940 }
2941 let from = std::mem::replace(&mut fresh.implementers, n);
2942 fresh.implementers_dirty = true;
2943 fresh.turns.push(Turn {
2944 sender: Some(Sender::Magi),
2945 breaks: None,
2946 messages: Vec::new(),
2947 posted_by: None,
2948 who: Who::Agent,
2949 body: format!("{MAGI_NOTE}implementers changed from {from} to {n}"),
2950 at: Timestamp::now(),
2951 attachments: Vec::new(),
2952 usage: None,
2953 });
2954 store.put(&mut fresh)?;
2955 *talk = fresh;
2956 Ok(true)
2957}
2958
2959pub fn briefing_for(
2962 repo: &Path,
2963 language: &str,
2964 allow_write: bool,
2965 persona: Option<&crate::persona::Persona>,
2966 operator_name: Option<&str>,
2967 implementers: u8,
2968) -> String {
2969 let flag = filing_flag(implementers);
2970 let shape = if implementers <= 1 {
2971 "Use --solo: it runs the task through one implementer \
2972 straight into review instead of the usual multi-agent competition, \
2973 which is the right shape for a change this conversation has already \
2974 settled, rather than one still worth several independent takes."
2975 .to_owned()
2976 } else {
2977 format!(
2978 "Use --implementers {implementers}: it has {implementers} \
2979 implementers work on the task independently and compete, which \
2980 is the right shape when several independent takes are worth \
2981 having. Never add --solo to it; the two do not go together."
2982 )
2983 };
2984 let write_policy = if allow_write {
2985 "Write access is enabled for this conversation (`allow_write = \
2986 true`), so you may write files - but only a small, \
2987 already-decided edit the operator names outright in this \
2988 conversation, not an implementation. This is a permission on the \
2989 conversation as a whole, not a property of whichever repository \
2990 it happened to start in: if the operator names a different \
2991 repository for that small edit, the policy allows it there too. \
2992 Your own tool may still confine writes to the repository this \
2993 conversation started in regardless - if a write elsewhere is \
2994 refused, say so plainly rather than working around it. Once you \
2995 have made an edit, say plainly what you edited. Anything bigger, \
2996 or anything still open-ended, still goes through the queue below \
2997 rather than being done here."
2998 } else {
2999 "Do not write files. Implementing a change is not this \
3000 conversation's job; a separate, blind competition of agents does \
3001 that, and a repository this conversation has already edited would \
3002 make their diffs unjudgeable."
3003 };
3004 let mut out = format!(
3005 "You are magi's standing conversation partner for its operator, who \
3006 usually has this open on a phone. Keep replies short: no preamble, \
3007 no restating what they just said.\n\n\
3008 # Repository\n\n{repo}\n\n\
3009 You may look around: read files, run shell commands, search history, \
3010 run tests - whatever answers the question. {write_policy}\n\n\
3011 A short, command-shaped message (\"list\", \"info <id>\", \"show \
3012 3cbf\") is almost always the operator asking you to look something \
3013 up, not an instruction to file - answer it yourself with `magi \
3014 list`, `magi show <id>`, `magi task list`, or the like, the same way \
3015 you would answer any other question in this conversation.\n\n\
3016 # Answering existing questions\n\n\
3017 Consultation delivery does not restrict an explicit owner decision. \
3018 Use `magi answer <full-question-id> --reply <exact offered choice> --quote <entire latest owner message>`. \
3019 Direct instructions bind `<full-question-id>: <exact offered choice>`. \
3020 An explicit batch instruction (including `おっけーそれぞれ回答してー`) authorizes \
3021 the immediately preceding persisted recommendations, one row per question: \
3022 `<full-question-id>: <exact offered choice>` or a table with separate ID and choice cells. \
3023 Hold, obsolete-approval dismissal, repair/re-review and non-destructive recovery choices \
3024 may be delegated this way, including cross-chat and never-consulted questions. \
3025 Merge requires `<full-question-id>: merge <displayed head>`. Withdrawal, PR closure, \
3026 replacement that closes the old PR, discard and task completion require an individual \
3027 exact consequence instruction; a batch instruction is insufficient. Public posting requires \
3028 the exact question/content fingerprint reported by the answer command. `use my text` \
3029 requires the question/content fingerprint followed by a newline and the literal replacement title. Report the exact missing evidence. \
3030 Never create another driver or task to apply an answer: existing execution transitions \
3031 retain their state, ownership and confirmation checks. A busy original consultation must \
3032 finish before a non-hold answer. A hold grants no closure or withdrawal. \
3033 Thanks, silence, recommendations alone, conditional/retracted instructions and generated \
3034 messages are not owner authorization.\n\n\
3035 # When the operator wants something done\n\n\
3036 Run:\n\n\
3037 magi task add {flag} --repo {repo} <instruction>\n\n\
3038 and tell the operator the task id it prints, so they can follow it \
3039 from the Queue. If it refuses with a duplicate warning (the \
3040 instruction names a branch, commit or pull request that an \
3041 unfinished task, run or PR already owns), do not repeat it with \
3042 --force yourself: tell the operator what it matched and let them \
3043 decide. Write <instruction> so that an implementer who has \
3044 never seen this conversation can act on it alone - it is everything \
3045 they get. {shape}\n\n\
3046 If the operator asks for something in a different repository, \
3047 --repo does not have to be a full path: --repo owner/repo (or just \
3048 repo, when that is unambiguous) is resolved against local checkouts \
3049 the same way `magi repos` lists them. If the command fails because \
3050 nothing matches or more than one checkout shares that name, ask the \
3051 operator which repository they mean (or run `magi repos` yourself \
3052 to see the candidates) rather than guessing.\n\n\
3053 You cannot wait, and you cannot send the operator a message on your \
3054 own: you only speak when they write. A task you file reports back \
3055 into this conversation automatically when it finishes, is held or \
3056 fails, as a message headed \"{notice}\".\n\n\
3057 For a background command you run yourself, register it with \
3058 `magi talk watch --timeout 900 -- <executable> <arguments...>`, for \
3059 example `magi talk watch -- cargo test --locked`. It uses your \
3060 current directory; arguments are passed literally. For shell syntax, \
3061 explicitly call `sh -c`. Only after watch registration succeeds may \
3062 you promise a completion report. Watches default to 900 seconds, \
3063 accept at most 3600 seconds, and share four concurrent slots. Their \
3064 automatic reports resume this conversation through its own turn. \
3065 Never promise to report back on work that is neither a filed task \
3066 nor a successfully registered watch.\n\n\
3067 The current state of the code is whatever origin/main holds, not \
3068 whatever a working tree shows: a primary checkout often lags \
3069 upstream, sits on a detached HEAD and carries uncommitted changes. \
3070 Before answering about code, run `git fetch origin` in that \
3071 repository if it is cheap, then read through \
3072 `git show origin/main:<path>` or `git grep <pattern> origin/main`. \
3073 If the working tree differs, say so; if the fetch fails, say that \
3074 too, so the operator knows the answer may be stale.\n\n\
3075 If the operator attached an image (a screenshot, say) that the task \
3076 is about, pass it with `--attach <path>`, using the absolute path \
3077 the turn's attachment note gives; repeat the flag for several. \
3078 `magi task add {flag} --attach <path> <instruction>` copies the \
3079 file into the task, so the implementer receives it. Do not paste the \
3080 path into <instruction> instead: deleting this conversation deletes \
3081 its attachments, and then that path reaches no one.\n",
3082 repo = repo.display(),
3083 notice = crate::prompt::CHAT_TASK_NOTICE_HEADING,
3084 );
3085 out.push_str(&language_note(language));
3086 match (persona, operator_name) {
3087 (Some(p), n) => out.push_str(&crate::persona::section_for(p, n)),
3088 (None, Some(n)) => {
3089 out.push_str("\n# Addressing the operator\n");
3090 out.push_str(&crate::persona::addressing(n));
3091 }
3092 (None, None) => {}
3093 }
3094 out
3095}
3096
3097fn language_note(language: &str) -> String {
3100 if language.trim().is_empty() || language.eq_ignore_ascii_case("en") {
3101 String::new()
3102 } else {
3103 format!("\nHold this conversation in {language}.\n")
3104 }
3105}
3106
3107pub fn tasks_of(queue: &Queue, talk_id: &str) -> Vec<Task> {
3114 let mut tasks: Vec<Task> = queue
3115 .list()
3116 .into_iter()
3117 .filter(|t| matches!(&t.source, Source::Agent { run, .. } if run == talk_id))
3118 .collect();
3119 tasks.sort_unstable_by(|a, b| a.id.cmp(&b.id));
3120 tasks
3121}
3122
3123fn read_path(path: &Path) -> Result<Talk> {
3124 let body = std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;
3125 let mut talk: Talk =
3126 serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))?;
3127 for turn in &mut talk.turns {
3128 if turn.who == Who::Operator && turn.messages.is_empty() && turn.attachments.is_empty() {
3129 turn.messages = plain_messages(&turn.body, turn.breaks.as_deref());
3130 }
3131 }
3132 if talk.pending_messages.is_empty() && talk.pending_attachments.is_empty() {
3133 talk.pending_messages = plain_messages(&talk.pending, talk.pending_breaks.as_deref());
3134 }
3135 Ok(talk)
3136}
3137
3138fn plain_messages(body: &str, breaks: Option<&[usize]>) -> Vec<Message> {
3140 let Some(breaks) = breaks else {
3141 return Vec::new();
3142 };
3143 if body.is_empty() {
3144 return Vec::new();
3145 }
3146 let mut messages = Vec::new();
3147 let mut start = 0;
3148 for end in breaks
3149 .iter()
3150 .copied()
3151 .chain(std::iter::once(body.len() + 2))
3152 {
3153 let Some(text) = end.checked_sub(2).and_then(|end| body.get(start..end)) else {
3154 return Vec::new();
3155 };
3156 messages.push(Message {
3157 display: None,
3158 sender: None,
3159 body: text.to_owned(),
3160 attachments: Vec::new(),
3161 reply: None,
3162 });
3163 start = end;
3164 }
3165 messages
3166}
3167
3168const PUT_RETRIES: u32 = 5;
3171
3172fn write_atomic(tmp: &Path, path: &Path, body: &str) -> Result<()> {
3184 let mut last_err = None;
3185 for attempt in 0..PUT_RETRIES {
3186 if attempt > 0 {
3187 std::thread::sleep(Duration::from_millis(20 * u64::from(attempt)));
3188 }
3189 match try_write_atomic(tmp, path, body) {
3190 Ok(()) => return Ok(()),
3191 Err(e) => last_err = Some(e),
3192 }
3193 }
3194 Err(last_err.expect("the loop above always runs at least once"))
3195}
3196
3197fn try_write_atomic(tmp: &Path, path: &Path, body: &str) -> Result<()> {
3198 #[cfg(test)]
3199 if failpoint::take_forced_put_failure() {
3200 bail!("simulated write failure (test)");
3201 }
3202 std::fs::write(tmp, body).with_context(|| format!("write {}", tmp.display()))?;
3203 std::fs::rename(tmp, path).with_context(|| format!("replace {}", path.display()))?;
3204 Ok(())
3205}
3206
3207fn stash_lost_turn(store: &Talks, id: &str, stem: &str, reply: &Turn) -> Result<PathBuf> {
3212 let dir = store.artifacts_of(id);
3213 std::fs::create_dir_all(&dir).with_context(|| format!("create {}", dir.display()))?;
3214 let path = dir.join(format!("{stem}-lost.txt"));
3215 std::fs::write(&path, &reply.body).with_context(|| format!("write {}", path.display()))?;
3216 Ok(path)
3217}
3218
3219#[cfg(test)]
3226mod failpoint {
3227 use std::cell::Cell;
3228
3229 thread_local! {
3230 static FORCE_PUT_FAILURES: Cell<u32> = const { Cell::new(0) };
3231 static FORCE_NO_LINK: Cell<bool> = const { Cell::new(false) };
3232 }
3233
3234 pub(super) fn force_no_link(on: bool) {
3237 FORCE_NO_LINK.with(|c| c.set(on));
3238 }
3239
3240 pub(super) fn no_link_forced() -> bool {
3241 FORCE_NO_LINK.with(Cell::get)
3242 }
3243
3244 pub(super) fn force_put_failures(count: u32) {
3247 FORCE_PUT_FAILURES.with(|c| c.set(count));
3248 }
3249
3250 pub(super) fn take_forced_put_failure() -> bool {
3253 FORCE_PUT_FAILURES.with(|c| {
3254 let n = c.get();
3255 if n == 0 {
3256 false
3257 } else {
3258 c.set(n - 1);
3259 true
3260 }
3261 })
3262 }
3263}
3264
3265fn short(id: &str) -> &str {
3266 id.split('-').next_back().unwrap_or(id)
3267}
3268
3269fn new_id() -> String {
3270 let stamp = jiff::Zoned::now().strftime("%Y%m%d-%H%M%S");
3271 let seed = crate::rng::entropy();
3272 format!("{stamp}-{:04x}", (seed ^ (seed >> 32)) & 0xffff)
3273}
3274
3275fn attachment_ext(mime: &str) -> Option<&'static str> {
3280 match mime {
3281 "image/png" => Some("png"),
3282 "image/jpeg" => Some("jpg"),
3283 "image/gif" => Some("gif"),
3284 "image/webp" => Some("webp"),
3285 _ => None,
3286 }
3287}
3288
3289pub fn valid_attachment_id(id: &str) -> bool {
3294 id.len() == 32
3295 && id
3296 .bytes()
3297 .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
3298}
3299
3300fn new_attachment_id() -> String {
3304 let mut r = crate::rng::SplitMix64::new(crate::rng::entropy());
3305 format!("{:016x}{:016x}", r.next_u64(), r.next_u64())
3306}
3307
3308#[cfg(test)]
3309mod tests {
3310 #[test]
3311 fn turn_access_lifts_the_sandbox_only_for_the_talk_opt_in() {
3312 use super::turn_access;
3313 assert_eq!(turn_access(false, false), (false, false));
3314 assert_eq!(turn_access(true, false), (true, true));
3315 assert_eq!(turn_access(false, true), (true, false));
3317 assert_eq!(turn_access(true, true), (true, true));
3318 }
3319
3320 #[test]
3321 fn the_briefing_points_at_origin_main_not_the_working_tree() {
3322 let b = briefing(Path::new("/r"), "en", false);
3323 assert!(b.contains("origin/main"));
3324 assert!(b.contains("git show origin/main:"));
3325 }
3326 use std::collections::BTreeMap;
3327
3328 use crate::config::{AgentChoice, AgentKind, AgentSpec, Graph};
3329 use crate::queue::{Queue, Source, Task};
3330
3331 use super::*;
3332
3333 fn ctx_agent(id: &str, model: Option<&str>) -> AgentSpec {
3334 AgentSpec {
3335 id: id.to_owned(),
3336 kind: AgentKind::Command,
3337 model: model.map(str::to_owned),
3338 command: Vec::new(),
3339 extra_args: Vec::new(),
3340 env: BTreeMap::new(),
3341 prompt_delivery: None,
3342 }
3343 }
3344
3345 fn ctx_talk(agent: &str, turns: Vec<Turn>) -> Talk {
3346 Talk {
3347 recommendations: Default::default(),
3348 posts_read_through: None,
3349 pending_breaks: None,
3350 pending_messages: Vec::new(),
3351 schema: SCHEMA,
3352 id: "20260904-014455-ab12".to_owned(),
3353 repo: PathBuf::from("."),
3354 agent: agent.to_owned(),
3355 status: TalkStatus::Open,
3356 turns,
3357 pending: String::new(),
3358 pending_attachments: Vec::new(),
3359 fallback: false,
3360 persona: String::new(),
3361 persona_dirty: false,
3362 implementers: 1,
3363 implementers_dirty: false,
3364 notified: Vec::new(),
3365 completion_notices: Vec::new(),
3366 created_at: Timestamp::now(),
3367 updated_at: Timestamp::now(),
3368 seat: SeatState::new(SEAT, agent, 1),
3369 }
3370 }
3371
3372 fn reply(body: &str, usage: Option<(u64, &str, Option<&str>)>) -> Turn {
3373 Turn {
3374 sender: None,
3375 breaks: None,
3376 messages: Vec::new(),
3377 posted_by: None,
3378 who: Who::Agent,
3379 body: body.to_owned(),
3380 at: Timestamp::now(),
3381 attachments: Vec::new(),
3382 usage: usage.map(|(t, a, m)| TurnUsage {
3383 context_tokens: t,
3384 agent: a.to_owned(),
3385 model: m.map(str::to_owned),
3386 }),
3387 }
3388 }
3389
3390 fn ctx_config(windows: &[(&str, u64)]) -> Config {
3391 Config {
3392 agents: vec![
3393 ctx_agent("small", Some("small-model")),
3394 ctx_agent("big", Some("big-model")),
3395 ctx_agent("plain", None),
3396 ],
3397 context_windows: windows.iter().map(|(k, v)| ((*k).to_owned(), *v)).collect(),
3398 ..Config::default()
3399 }
3400 }
3401
3402 #[test]
3403 fn context_usage_computes_percent_and_warns_at_eighty() {
3404 let cfg = ctx_config(&[("small-model", 1000)]);
3405 let at = |tokens| {
3406 let t = ctx_talk(
3407 "small",
3408 vec![reply("hi", Some((tokens, "small", Some("small-model"))))],
3409 );
3410 context_usage(&t, Some(&cfg))
3411 };
3412 let u = at(799);
3413 assert_eq!((u.percent, u.warn, u.window), (Some(79), false, Some(1000)));
3414 let u = at(800);
3415 assert_eq!((u.percent, u.warn), (Some(80), true));
3416 let u = at(1500);
3417 assert_eq!((u.percent, u.warn), (Some(150), true));
3418 assert!(!u.since_switch);
3419 }
3420
3421 #[test]
3422 fn context_usage_is_unknown_without_usage_and_never_looks_back() {
3423 let cfg = ctx_config(&[("small-model", 1000)]);
3424 let t = ctx_talk(
3425 "small",
3426 vec![
3427 reply("old", Some((900, "small", Some("small-model")))),
3428 reply("new", None),
3429 ],
3430 );
3431 let u = context_usage(&t, Some(&cfg));
3432 assert!(u.estimated);
3434 assert_ne!(u.tokens, Some(900));
3435 assert!(u.tokens.is_some());
3436 let t = ctx_talk(
3438 "small",
3439 vec![
3440 reply("old", Some((900, "small", Some("small-model")))),
3441 reply("magi: could not run agent", None),
3442 ],
3443 );
3444 assert_eq!(context_usage(&t, Some(&cfg)).tokens, Some(900));
3445 assert_eq!(
3446 context_usage(&ctx_talk("small", Vec::new()), Some(&cfg)).tokens,
3447 None
3448 );
3449 }
3450
3451 #[test]
3452 fn estimate_counts_chars_both_sides_and_standing_prompt() {
3453 let mut t = ctx_talk("small", vec![reply("abcdefg", None)]);
3454 assert_eq!(estimate_context_tokens(&t, 0), Some(2)); let op = Turn {
3456 sender: None,
3457 who: Who::Operator,
3458 ..reply("abcdefg", None)
3459 };
3460 t.turns.push(op);
3461 assert_eq!(estimate_context_tokens(&t, 0), Some(4));
3462 assert!(
3463 estimate_context_tokens(&t, 700).unwrap() > estimate_context_tokens(&t, 0).unwrap()
3464 );
3465 let ja = ctx_talk("small", vec![reply("日本語日本語日", None)]);
3467 assert_eq!(estimate_context_tokens(&ja, 0), Some(2));
3468 let note = ctx_talk("small", vec![reply("magi: could not run agent", None)]);
3470 assert_eq!(estimate_context_tokens(¬e, 1000), None);
3471 assert_eq!(
3472 estimate_context_tokens(&ctx_talk("small", Vec::new()), 1000),
3473 None
3474 );
3475 }
3476
3477 #[test]
3478 fn context_usage_measured_wins_and_estimate_gets_percent_and_warn() {
3479 let cfg = ctx_config(&[("small-model", 1000)]);
3480 let t = ctx_talk(
3481 "small",
3482 vec![reply(
3483 &"x".repeat(5000),
3484 Some((10, "small", Some("small-model"))),
3485 )],
3486 );
3487 let u = context_usage(&t, Some(&cfg));
3488 assert_eq!((u.tokens, u.estimated), (Some(10), false));
3489 let t = ctx_talk("small", vec![reply(&"x".repeat(5000), None)]);
3490 let u = context_usage(&t, Some(&cfg));
3491 assert!(u.estimated && !u.since_switch);
3492 assert_eq!(u.window, Some(1000));
3493 assert!(u.warn && u.percent.unwrap() >= 80);
3494 let t = ctx_talk("small", vec![reply("hi", None)]);
3495 let u = context_usage(&t, Some(&cfg));
3496 assert!(u.estimated && u.percent.is_some());
3497 }
3498
3499 #[test]
3500 fn context_usage_without_a_window_shows_tokens_only() {
3501 let cfg = ctx_config(&[]);
3502 let t = ctx_talk("plain", vec![reply("hi", Some((5000, "plain", None)))]);
3504 let u = context_usage(&t, Some(&cfg));
3505 assert_eq!(
3506 (u.tokens, u.window, u.percent, u.warn),
3507 (Some(5000), None, None, false)
3508 );
3509 let t = ctx_talk(
3510 "small",
3511 vec![reply("hi", Some((5000, "small", Some("small-model"))))],
3512 );
3513 assert_eq!(context_usage(&t, Some(&cfg)).percent, None);
3514 assert_eq!(context_usage(&t, None).window, None);
3516 }
3517
3518 #[test]
3519 fn context_usage_switching_model_changes_the_denominator() {
3520 let cfg = ctx_config(&[("small-model", 1000), ("big-model", 10_000)]);
3521 let used = reply("hi", Some((900, "small", Some("small-model"))));
3522 let before = context_usage(&ctx_talk("small", vec![used.clone()]), Some(&cfg));
3523 assert_eq!(
3524 (before.percent, before.warn, before.since_switch),
3525 (Some(90), true, false)
3526 );
3527 let after = context_usage(&ctx_talk("big", vec![used]), Some(&cfg));
3530 assert_eq!(after.window, Some(10_000));
3531 assert_eq!(
3532 (after.percent, after.warn, after.since_switch),
3533 (Some(9), false, true)
3534 );
3535 assert_eq!(after.model.as_deref(), Some("big-model"));
3536 }
3537
3538 #[test]
3539 fn a_turn_recorded_before_usage_existed_still_reads() {
3540 let old = r#"{"who":"agent","body":"hi","at":"2026-09-04T01:44:55Z"}"#;
3541 let turn: Turn = serde_json::from_str(old).expect("old turn reads");
3542 assert!(turn.usage.is_none());
3543 let json = serde_json::to_string(&turn).expect("serialize");
3544 assert!(
3545 !json.contains("usage"),
3546 "absent usage is not written: {json}"
3547 );
3548 }
3549
3550 fn store() -> (tempfile::TempDir, Talks) {
3552 let tmp = tempfile::tempdir().expect("tempdir");
3553 let talks = Talks::at(tmp.path().join("talks"));
3554 (tmp, talks)
3555 }
3556
3557 fn mock_agent(dir: &Path, script: &str, env: BTreeMap<String, String>) -> AgentSpec {
3561 let path = dir.join("mock-talk-agent.sh");
3562 std::fs::write(&path, script).expect("write mock");
3563 AgentSpec {
3564 id: "mock".to_owned(),
3565 kind: AgentKind::Command,
3566 model: None,
3567 command: vec!["sh".to_owned(), path.to_string_lossy().into_owned()],
3568 extra_args: Vec::new(),
3569 env,
3570 prompt_delivery: None,
3571 }
3572 }
3573
3574 fn config(spec: AgentSpec) -> Config {
3575 Config {
3576 agents: vec![spec],
3577 graph: Graph {
3578 language: "en".to_owned(),
3579 ..Graph::default()
3580 },
3581 ..Config::default()
3582 }
3583 }
3584
3585 const REPLY: &str = "#!/bin/sh\ncat >/dev/null\nprintf '%s\\n' \"$MOCK_REPLY\"\n";
3587
3588 const BROKEN: &str = "#!/bin/sh\ncat >/dev/null\nexit 3\n";
3590
3591 const ECHO: &str = "#!/bin/sh\ncat\n";
3594
3595 fn env(reply: &str) -> BTreeMap<String, String> {
3596 BTreeMap::from([("MOCK_REPLY".to_owned(), reply.to_owned())])
3597 }
3598
3599 #[test]
3600 fn the_frozen_json_field_names_round_trip_through_disk() {
3601 let (tmp, talks) = store();
3602 let mut talk = Talk {
3603 recommendations: Default::default(),
3604 posts_read_through: None,
3605 pending_breaks: None,
3606 pending_messages: Vec::new(),
3607 schema: SCHEMA,
3608 id: "20260904-014455-ab12".to_owned(),
3609 repo: tmp.path().to_owned(),
3610 agent: "sonnet".to_owned(),
3611 status: TalkStatus::Open,
3612 turns: Vec::new(),
3613 pending: String::new(),
3614 pending_attachments: Vec::new(),
3615 fallback: false,
3616 persona: String::new(),
3617 persona_dirty: false,
3618 implementers: 1,
3619 implementers_dirty: false,
3620 notified: Vec::new(),
3621 completion_notices: Vec::new(),
3622 created_at: Timestamp::now(),
3623 updated_at: Timestamp::now(),
3624 seat: SeatState::new(SEAT, "sonnet", 7),
3625 };
3626 talks.put(&mut talk).expect("put");
3627
3628 let raw = std::fs::read_to_string(talks.path_of(&talk.id)).expect("read back");
3629 let v: serde_json::Value = serde_json::from_str(&raw).expect("parse");
3630 for field in [
3631 "schema",
3632 "id",
3633 "repo",
3634 "agent",
3635 "status",
3636 "turns",
3637 "created_at",
3638 "updated_at",
3639 ] {
3640 assert!(v.get(field).is_some(), "missing field `{field}`");
3641 }
3642 assert_eq!(v["schema"], 1);
3643 assert_eq!(v["status"], "open");
3644
3645 let back = talks.get(&talk.id).expect("get");
3646 assert_eq!(back.posts_read_through, None);
3647 assert_eq!(back.id, talk.id);
3648 assert_eq!(back.status, TalkStatus::Open);
3649 }
3650
3651 #[test]
3652 fn opening_a_talk_takes_no_agent_turn() {
3653 let (tmp, talks) = store();
3654 let spec = mock_agent(tmp.path(), BROKEN, BTreeMap::new());
3658 let cfg = config(spec);
3659
3660 let talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
3661 assert_eq!(talk.status, TalkStatus::Open);
3662 assert!(talk.turns.is_empty(), "nothing has been said yet");
3663
3664 let on_disk = talks.get(&talk.id).expect("get");
3665 assert_eq!(on_disk.turns.len(), 0);
3666 }
3667
3668 #[test]
3676 fn chatter_wins_when_set_and_falls_back_to_pick_s_default_order_otherwise() {
3677 let (tmp, talks) = store();
3678 let first_spec = mock_agent(tmp.path(), BROKEN, BTreeMap::new());
3679 let mut chatter_spec = mock_agent(tmp.path(), BROKEN, BTreeMap::new());
3680 chatter_spec.id = "chatter-mock".to_owned();
3681
3682 let mut cfg = Config {
3683 agents: vec![first_spec.clone(), chatter_spec.clone()],
3684 graph: Graph {
3685 language: "en".to_owned(),
3686 ..Graph::default()
3687 },
3688 ..Config::default()
3689 };
3690 cfg.roles.chatter = Some(chatter_spec.id.as_str().into());
3691
3692 let talk =
3693 begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin with chatter set");
3694 assert_eq!(talk.agent, chatter_spec.id, "an explicit chatter must win");
3695
3696 cfg.roles.chatter = None;
3697 let fallback =
3698 begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin with chatter unset");
3699 assert_eq!(
3700 fallback.agent, first_spec.id,
3701 "unset chatter must fall back to agent::pick's own default order"
3702 );
3703 }
3704
3705 #[test]
3708 fn a_talk_recorded_without_attachments_still_reads() {
3709 let (tmp, talks) = store();
3710 let path = talks.path_of("20260904-014455-ab12");
3711 std::fs::create_dir_all(talks.root()).expect("talks dir");
3712 std::fs::write(
3713 &path,
3714 serde_json::json!({
3715 "schema": 1,
3716 "id": "20260904-014455-ab12",
3717 "repo": tmp.path(),
3718 "agent": "sonnet",
3719 "status": "open",
3720 "turns": [
3721 { "who": "operator", "body": "still there?",
3722 "at": Timestamp::now().to_string() },
3723 ],
3724 "created_at": Timestamp::now().to_string(),
3725 "updated_at": Timestamp::now().to_string(),
3726 "seat": SeatState::new(SEAT, "sonnet", 7),
3727 })
3728 .to_string(),
3729 )
3730 .expect("write pre-attachments talk");
3731
3732 let talk = talks.get("20260904-014455-ab12").expect("must still read");
3733 assert!(talk.turns[0].attachments.is_empty());
3734 }
3735
3736 fn lease_store() -> (tempfile::TempDir, Talks, Talks) {
3737 let tmp = tempfile::TempDir::new().expect("tmp");
3738 let root = tmp.path().join("talks");
3739 (tmp, Talks::at(root.clone()), Talks::at(root))
3740 }
3741
3742 #[test]
3743 fn two_starters_on_one_talk_one_wins_and_the_other_is_refused() {
3744 let (_tmp, a, b) = lease_store();
3745 let won = a.claim_turn("t1").expect("claim").expect("first wins");
3746 assert!(
3747 b.claim_turn("t1").expect("claim").is_none(),
3748 "second is refused"
3749 );
3750 assert!(b.turn_held("t1"));
3751 assert!(
3752 b.claim_turn("t2").expect("claim").is_some(),
3753 "other talks are free"
3754 );
3755 drop(won);
3756 }
3757
3758 #[test]
3759 fn a_stale_lease_is_taken_over_and_the_old_guard_cannot_release_it() {
3760 let (_tmp, a, b) = lease_store();
3761 let old = a.claim_turn("t1").expect("claim").expect("held");
3762 let later = Timestamp::now()
3763 .checked_add(jiff::SignedDuration::from_secs(
3764 crate::ask::LEASE_TTL.as_secs() as i64 + 5,
3765 ))
3766 .expect("later");
3767 let new = b
3768 .claim_turn_at("t1", later)
3769 .expect("claim")
3770 .expect("a stale lease is taken over");
3771 drop(old);
3772 assert!(a.turn_held("t1"), "the old guard left the new lease alone");
3773 assert!(new.beat().expect("beat"), "the new owner still beats");
3774 drop(new);
3775 assert!(!a.turn_held("t1"));
3776 }
3777
3778 #[tokio::test]
3779 async fn a_turn_whose_lease_was_taken_over_is_stopped() {
3780 let (_tmp, a, b) = lease_store();
3781 let old = a.claim_turn("t1").expect("claim").expect("held");
3782 let later = Timestamp::now()
3783 .checked_add(jiff::SignedDuration::from_secs(
3784 crate::ask::LEASE_TTL.as_secs() as i64 + 5,
3785 ))
3786 .expect("later");
3787 let _new = b
3788 .claim_turn_at("t1", later)
3789 .expect("claim")
3790 .expect("taken over");
3791 let out = old
3792 .beating_every(Duration::from_millis(10), std::future::pending::<()>())
3793 .await;
3794 assert!(out.is_err(), "the displaced turn must stop, not run on");
3795 }
3796
3797 #[tokio::test]
3798 async fn a_turn_that_finishes_is_returned_and_keeps_its_lease_beating() {
3799 let (_tmp, a, _b) = lease_store();
3800 let lease = a.claim_turn("t1").expect("claim").expect("held");
3801 let out = lease
3802 .beating_every(Duration::from_millis(5), async {
3803 tokio::time::sleep(Duration::from_millis(40)).await;
3804 7
3805 })
3806 .await
3807 .expect("still ours");
3808 assert_eq!(out, 7);
3809 assert!(a.turn_held("t1"));
3810 }
3811
3812 #[test]
3813 fn an_unreadable_lease_counts_as_stale() {
3814 let (_tmp, a, b) = lease_store();
3815 std::fs::create_dir_all(a.root()).expect("dir");
3816 std::fs::write(a.turn_path("t1"), "not json").expect("write");
3817 assert!(!a.turn_held("t1"));
3818 assert!(b.claim_turn("t1").expect("claim").is_some());
3819 }
3820
3821 #[test]
3822 fn without_hard_links_a_claim_is_still_exclusive_and_a_young_placeholder_blocks() {
3823 let (_tmp, a, b) = lease_store();
3824 failpoint::force_no_link(true);
3825 let held = a.claim_turn("t1").expect("claim").expect("first wins");
3826 assert!(b.claim_turn("t1").expect("claim").is_none());
3827 assert!(a.turn_held("t1"));
3828 drop(held);
3829 assert!(!a.turn_held("t1"));
3830 let path = a.turn_path("t1");
3832 assert!(create_exclusive(&path, "").expect("placeholder"));
3833 assert!(b.claim_turn("t1").expect("claim").is_none(), "young: held");
3834 age_file(&path);
3835 assert!(b.claim_turn("t1").expect("claim").is_some(), "old: stale");
3836 let lease = a.turn_path("t2");
3838 let lock = TurnLock::take(&lease).expect("take").expect("lock");
3839 assert!(TurnLock::take(&lease).expect("take").is_none());
3840 drop(lock);
3841 assert!(TurnLock::take(&lease).expect("take").is_some());
3842 failpoint::force_no_link(false);
3843 }
3844
3845 #[test]
3846 fn remove_if_carries_removes_only_the_expected_content() {
3847 let (_tmp, a, _b) = lease_store();
3848 std::fs::create_dir_all(a.root()).expect("dir");
3849 let p = a.root().join("x.turn.lock");
3850 std::fs::write(&p, "mine").expect("write");
3851 assert!(!remove_if_carries(&p, "other"));
3852 assert_eq!(std::fs::read_to_string(&p).expect("kept"), "mine");
3853 assert!(remove_if_carries(&p, "mine"));
3854 assert!(!p.exists());
3855 assert!(!remove_if_carries(&p, "mine"), "absent is not a removal");
3856 }
3857
3858 #[test]
3859 fn a_dropped_lock_does_not_remove_a_lock_taken_over_since() {
3860 let (_tmp, a, _b) = lease_store();
3861 std::fs::create_dir_all(a.root()).expect("dir");
3862 let lease = a.turn_path("t1");
3863 let lock = TurnLock::take(&lease).expect("take").expect("lock");
3864 let path = lock.path.clone();
3865 std::fs::write(&path, "someone-else").expect("replace");
3866 drop(lock);
3867 assert_eq!(
3868 std::fs::read_to_string(&path).expect("kept"),
3869 "someone-else"
3870 );
3871 }
3872
3873 #[test]
3874 fn concurrent_takeovers_of_a_stale_lease_have_one_winner() {
3875 let (_tmp, a, _b) = lease_store();
3876 drop(a.claim_turn("t1").expect("claim").expect("held"));
3877 std::fs::write(
3878 a.turn_path("t1"),
3879 serde_json::to_string(&TurnRecord {
3880 token: "gone".into(),
3881 pid: 1,
3882 beat_at: Timestamp::from_second(1).expect("ts"),
3883 })
3884 .expect("json"),
3885 )
3886 .expect("write");
3887 let wins: Vec<_> = std::thread::scope(|sc| {
3888 let hs: Vec<_> = (0..8)
3889 .map(|_| {
3890 let s = a.clone();
3891 sc.spawn(move || s.claim_turn("t1").expect("claim"))
3892 })
3893 .collect();
3894 hs.into_iter().map(|h| h.join().expect("join")).collect()
3895 });
3896 assert_eq!(wins.iter().filter(|w| w.is_some()).count(), 1);
3897 }
3898
3899 fn age_file(path: &Path) {
3900 let f = std::fs::OpenOptions::new()
3901 .write(true)
3902 .open(path)
3903 .expect("open");
3904 f.set_modified(std::time::SystemTime::now() - std::time::Duration::from_secs(60))
3905 .expect("age");
3906 }
3907
3908 #[test]
3909 fn a_late_taker_of_a_broken_lock_cannot_disturb_its_replacement() {
3910 let (_tmp, a, _b) = lease_store();
3911 let lease = a.turn_path("t1");
3912 let lock = lease.with_extension("turn.lock");
3913 std::fs::create_dir_all(lock.parent().expect("dir")).expect("dir");
3914 std::fs::write(&lock, "t1-dead").expect("dead lock");
3915 age_file(&lock);
3916 let b = TurnLock::take(&lease).expect("take").expect("b wins");
3918 let fresh = std::fs::read_to_string(&lock).expect("read");
3919 assert_eq!(fresh, b.token);
3920 let ticket = std::fs::read_dir(lock.parent().expect("dir"))
3923 .expect("dir")
3924 .flatten()
3925 .map(|e| e.path())
3926 .find(|p| p.to_string_lossy().ends_with(".break.0"))
3927 .expect("ticket");
3928 assert!(!create_exclusive(&ticket, "").expect("ticket"));
3929 assert!(TurnLock::take(&lease).expect("take").is_none());
3930 assert_eq!(std::fs::read_to_string(&lock).expect("read"), fresh);
3931 age_file(&lock);
3933 age_file(&ticket);
3934 std::mem::forget(b);
3935 let c = TurnLock::take(&lease)
3936 .expect("take")
3937 .expect("next generation");
3938 assert_ne!(c.token, fresh);
3939 }
3940
3941 #[test]
3942 fn a_live_ticket_blocks_and_a_stale_one_hands_over_to_the_next_generation() {
3943 let (_tmp, a, _b) = lease_store();
3944 let lease = a.turn_path("t1");
3945 let lock = lease.with_extension("turn.lock");
3946 std::fs::create_dir_all(lock.parent().expect("dir")).expect("dir");
3947 std::fs::write(&lock, "t1-dead").expect("dead lock");
3948 age_file(&lock);
3949 let t0 = lock.with_extension("lock.t1-dead.break.0");
3950 assert!(create_exclusive(&t0, "").expect("ticket"));
3951 assert!(TurnLock::take(&lease).expect("take").is_none());
3953 assert_eq!(std::fs::read_to_string(&lock).expect("read"), "t1-dead");
3954 age_file(&t0);
3956 let c = TurnLock::take(&lease).expect("take").expect("generation 1");
3957 assert_eq!(std::fs::read_to_string(&lock).expect("read"), c.token);
3958 assert!(lock.with_extension("lock.t1-dead.break.1").exists());
3959 assert!(TurnLock::take(&lease).expect("take").is_none());
3960 }
3961
3962 #[test]
3963 fn exhausted_ticket_generations_recover_once_the_sweep_ages_them_out() {
3964 let (_tmp, a, _b) = lease_store();
3965 let lease = a.turn_path("t1");
3966 let lock = lease.with_extension("turn.lock");
3967 std::fs::create_dir_all(lock.parent().expect("dir")).expect("dir");
3968 std::fs::write(&lock, "t1-dead").expect("dead lock");
3969 age_file(&lock);
3970 let tickets: Vec<_> = (0..TICKET_GENERATIONS)
3971 .map(|n| lock.with_extension(format!("lock.t1-dead.break.{n}")))
3972 .collect();
3973 for t in &tickets {
3974 assert!(create_exclusive(t, "").expect("ticket"));
3975 age_file(t);
3976 }
3977 assert!(TurnLock::take(&lease).expect("take").is_none());
3979 assert!(tickets.iter().all(|t| t.exists()));
3980 for t in &tickets {
3982 let f = std::fs::OpenOptions::new()
3983 .write(true)
3984 .open(t)
3985 .expect("open");
3986 f.set_modified(std::time::SystemTime::now() - TICKET_SWEEP_AGE * 2)
3987 .expect("age");
3988 }
3989 assert!(TurnLock::take(&lease).expect("take").is_none());
3990 assert!(TurnLock::take(&lease).expect("take").is_some());
3991 }
3992
3993 #[test]
3994 fn an_aged_empty_lock_is_broken() {
3995 let (_tmp, a, _b) = lease_store();
3996 let lease = a.turn_path("t1");
3997 let lock = lease.with_extension("turn.lock");
3998 std::fs::create_dir_all(lock.parent().expect("dir")).expect("dir");
3999 std::fs::write(&lock, "").expect("empty lock");
4000 age_file(&lock);
4001 assert!(TurnLock::take(&lease).expect("take").is_some());
4002 }
4003
4004 #[test]
4005 fn reply_plain_text_sends_keep_provenance_and_boundaries() {
4006 let (tmp, talks) = store();
4007 let cfg = config(mock_agent(tmp.path(), REPLY, env("reply")));
4008 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4009 record(&mut talk, &talks, "original", Vec::new()).expect("record");
4010 queue(&mut talk, &talks, "first", Vec::new()).expect("queue");
4011 queue(&mut talk, &talks, "second", Vec::new()).expect("queue");
4012 let wire: serde_json::Value =
4013 serde_json::from_str(&std::fs::read_to_string(talks.path_of(&talk.id)).unwrap())
4014 .unwrap();
4015 assert_eq!(wire["pending_messages"][0]["sender"], "operator");
4016 assert_eq!(wire["turns"][0]["messages"][0]["sender"], "operator");
4017 drain(&mut talk, &talks).expect("drain");
4018 let saved = talks.get(&talk.id).expect("reload");
4019 assert_eq!(saved.turns[1].body, "first\n\nsecond");
4020 assert_eq!(saved.turns[1].breaks, Some(vec![7]));
4021 let wire: serde_json::Value =
4022 serde_json::from_str(&std::fs::read_to_string(talks.path_of(&saved.id)).unwrap())
4023 .unwrap();
4024 for turn in wire["turns"].as_array().expect("turns") {
4026 for field in turn.as_object().expect("turn").keys() {
4027 assert!(
4028 [
4029 "who",
4030 "body",
4031 "at",
4032 "attachments",
4033 "usage",
4034 "breaks",
4035 "posted_by",
4036 "sender",
4037 "messages"
4038 ]
4039 .contains(&field.as_str()),
4040 "unknown turn field: {field}"
4041 );
4042 }
4043 }
4044 record_reply(
4045 &mut talk,
4046 &talks,
4047 "reply",
4048 Vec::new(),
4049 Some(ReplyTarget {
4050 turn: 1,
4051 message: 1,
4052 }),
4053 )
4054 .expect("reply to reloaded plain text");
4055 assert_eq!(
4056 talk.turns[2].messages[0].reply.as_ref().unwrap().excerpt,
4057 "second"
4058 );
4059 }
4060
4061 #[tokio::test]
4062 async fn reply_image_identity_reaches_fresh_and_followup_prompts_after_reload() {
4063 let (tmp, talks) = store();
4064 let cfg = config(mock_agent(tmp.path(), ECHO, BTreeMap::new()));
4065 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4066 let first = talks
4067 .put_attachment(&talk.id, "image/png", "first.png", b"first")
4068 .expect("first");
4069 let second = talks
4070 .put_attachment(&talk.id, "image/png", "second.png", b"second")
4071 .expect("second");
4072 let first_path = talks.attachment_path(&talk.id, &first).unwrap();
4073 let second_path = talks.attachment_path(&talk.id, &second).unwrap();
4074 queue(&mut talk, &talks, "", vec![first]).expect("queue first");
4076 queue(&mut talk, &talks, "", vec![second]).expect("queue second");
4077 drain(&mut talk, &talks).expect("drain");
4078 let lease = talks.claim_turn(&talk.id).expect("claim").expect("lease");
4079 for (message, selected, other) in [
4080 (0, &first_path, &second_path),
4081 (1, &second_path, &first_path),
4082 ] {
4083 record_reply(
4084 &mut talk,
4085 &talks,
4086 "describe this",
4087 Vec::new(),
4088 Some(ReplyTarget { turn: 0, message }),
4089 )
4090 .expect("reply");
4091 talk = talks.get(&talk.id).expect("reload");
4092 let quote = message_prompt(talk.turns.last().unwrap(), &talk, &talks);
4093 assert!(quote.contains(selected.to_str().unwrap()));
4094 assert!(!quote.contains(other.to_str().unwrap()));
4095 respond(&lease, &mut talk, &talks, &cfg, "describe this")
4096 .await
4097 .expect("respond");
4098 assert!(
4099 talk.turns
4100 .last()
4101 .unwrap()
4102 .body
4103 .contains(&format!("Replied-to image: {}", selected.display()))
4104 );
4105 }
4106 }
4107
4108 #[test]
4109 fn reply_sends_survive_queue_edit_drain_reload_and_legacy_records() {
4110 let (tmp, talks) = store();
4111 let cfg = config(mock_agent(tmp.path(), REPLY, env("reply")));
4112 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4113 record(&mut talk, &talks, &"猫".repeat(300), Vec::new()).expect("record");
4114 talk.turns[0].messages.clear();
4116 talks.put(&mut talk).expect("legacy save");
4117 let target = ReplyTarget {
4118 turn: 0,
4119 message: 0,
4120 };
4121 queue_reply(&mut talk, &talks, "first", Vec::new(), Some(target.clone())).expect("first");
4122 queue_reply(&mut talk, &talks, "second", Vec::new(), None).expect("second");
4123 assert!(
4124 edit_pending_message(&mut talk, &talks, "edited", "first\n\nsecond", &[], Some(0))
4125 .expect("edit")
4126 );
4127 drain(&mut talk, &talks).expect("drain");
4128 let saved = talks.get(&talk.id).expect("reload");
4129 assert_eq!(saved.turns[1].body, "edited\n\nsecond");
4130 assert_eq!(saved.turns[1].messages.len(), 2);
4131 let reply = saved.turns[1].messages[0].reply.as_ref().expect("reply");
4132 assert_eq!(reply.target, target);
4133 assert_eq!(reply.excerpt, "猫".repeat(240));
4134 assert!(message_prompt(&saved.turns[1], &saved, &talks).contains("[Reply to Operator:"));
4135 assert!(transcript(&saved, &talks).contains("[Reply to Operator:"));
4136 queue_reply(
4137 &mut talk,
4138 &talks,
4139 "third",
4140 Vec::new(),
4141 Some(ReplyTarget {
4142 turn: 1,
4143 message: 1,
4144 }),
4145 )
4146 .expect("specific send");
4147 assert_eq!(
4148 talk.pending_messages[0]
4149 .reply
4150 .as_ref()
4151 .expect("reply")
4152 .excerpt,
4153 "second"
4154 );
4155 clear_pending(&mut talk, &talks).expect("clear");
4156 assert!(talk.pending_messages.is_empty());
4157 assert!(
4158 record_reply(
4159 &mut talk,
4160 &talks,
4161 "invalid",
4162 Vec::new(),
4163 Some(ReplyTarget {
4164 turn: 1,
4165 message: 2
4166 })
4167 )
4168 .is_err()
4169 );
4170 assert_eq!(talks.get(&talk.id).expect("reload").turns.len(), 2);
4171 }
4172
4173 #[tokio::test]
4174 async fn reply_quotes_reach_fresh_and_followup_prompts_without_changing_body() {
4175 let (tmp, talks) = store();
4176 let cfg = config(mock_agent(tmp.path(), ECHO, BTreeMap::new()));
4177 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4178 record(&mut talk, &talks, "original", Vec::new()).expect("record");
4179 let target = ReplyTarget {
4180 turn: 0,
4181 message: 0,
4182 };
4183 record_reply(
4184 &mut talk,
4185 &talks,
4186 "answer",
4187 Vec::new(),
4188 Some(target.clone()),
4189 )
4190 .expect("reply");
4191 let lease = talks.claim_turn(&talk.id).expect("claim").expect("lease");
4192 respond(&lease, &mut talk, &talks, &cfg, "answer")
4193 .await
4194 .expect("respond");
4195 assert!(
4196 talk.turns
4197 .last()
4198 .expect("response")
4199 .body
4200 .contains("[Reply to Operator: original]\nanswer")
4201 );
4202 assert_eq!(talk.turns[1].body, "answer");
4203 record_reply(&mut talk, &talks, "followup", Vec::new(), Some(target)).expect("reply");
4204 respond(&lease, &mut talk, &talks, &cfg, "followup")
4205 .await
4206 .expect("respond");
4207 assert!(
4208 talk.turns
4209 .last()
4210 .expect("response")
4211 .body
4212 .contains("[Reply to Operator: original]\nfollowup")
4213 );
4214 }
4215
4216 #[test]
4217 fn owner_indentation_survives_record_queue_and_edit() {
4218 let (tmp, talks) = store();
4219 let cfg = config(mock_agent(tmp.path(), REPLY, env("reply")));
4220 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4221 for text in [" Post original", "\tUse rewrite"] {
4222 record_reply(&mut talk, &talks, text, Vec::new(), None).unwrap();
4223 assert_eq!(
4224 talks.get(&talk.id).unwrap().turns.last().unwrap().body,
4225 text
4226 );
4227 queue(&mut talk, &talks, "draft", Vec::new()).unwrap();
4228 assert!(edit_pending_message(&mut talk, &talks, text, "draft", &[], Some(0)).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!(edit_pending_message(&mut talk, &talks, text, text, &[], None).unwrap());
4233 let saved = talks.get(&talk.id).unwrap();
4234 assert_eq!(saved.pending, text);
4235 assert_eq!(saved.pending_messages[0].body, text);
4236 assert_eq!(drain(&mut talk, &talks).unwrap().as_deref(), Some(text));
4237 }
4238 }
4239
4240 #[test]
4241 fn queued_text_is_durable_combined_and_drained_as_one_operator_turn() {
4242 let (tmp, talks) = store();
4243 let cfg = config(mock_agent(tmp.path(), REPLY, env("reply")));
4244 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4245
4246 queue(&mut talk, &talks, "first", Vec::new()).expect("queue first");
4247 queue(&mut talk, &talks, "second", Vec::new()).expect("queue second");
4248 let saved = talks.get(&talk.id).expect("reload queued talk");
4249 assert_eq!(saved.pending, "first\n\nsecond");
4250 assert_eq!(saved.pending_breaks, Some(vec!["first\n\n".len()]));
4251 assert!(saved.turns.is_empty(), "a draft is not a transcript turn");
4252
4253 let drained = drain(&mut talk, &talks).expect("drain");
4254 assert_eq!(drained.as_deref(), Some("first\n\nsecond"));
4255 let saved = talks.get(&talk.id).expect("reload drained talk");
4256 assert!(saved.pending.is_empty());
4257 assert_eq!(saved.turns.len(), 1);
4258 assert_eq!(saved.turns[0].body, "first\n\nsecond");
4259 assert_eq!(saved.turns[0].breaks, Some(vec!["first\n\n".len()]));
4260 assert_eq!(saved.pending_breaks, None);
4261 }
4262
4263 #[test]
4264 fn editing_a_queued_draft_preserves_its_attachments_and_rejects_a_stale_snapshot() {
4265 let (tmp, talks) = store();
4266 let cfg = config(mock_agent(tmp.path(), REPLY, env("reply")));
4267 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4268 let attachment = Attachment {
4269 id: "a".repeat(32),
4270 name: "shot.png".to_owned(),
4271 mime: "image/png".to_owned(),
4272 bytes: 3,
4273 };
4274
4275 queue(&mut talk, &talks, "first", vec![attachment.clone()]).expect("queue");
4276 assert!(
4277 edit_pending_text(
4278 &mut talk,
4279 &talks,
4280 "corrected",
4281 "first",
4282 std::slice::from_ref(&attachment.id),
4283 )
4284 .expect("edit")
4285 );
4286 let saved = talks.get(&talk.id).expect("reload edited draft");
4287 assert_eq!(saved.pending, "corrected");
4288 assert_eq!(saved.pending_attachments, vec![attachment]);
4289
4290 queue(&mut talk, &talks, "later", Vec::new()).expect("queue concurrent draft");
4291 assert!(
4292 !edit_pending_text(
4293 &mut talk,
4294 &talks,
4295 "stale edit",
4296 "corrected",
4297 &["a".repeat(32)],
4298 )
4299 .expect("stale edit is a conflict")
4300 );
4301 assert_eq!(
4302 talks.get(&talk.id).expect("reload after conflict").pending,
4303 "corrected\n\nlater"
4304 );
4305 assert!(
4306 !clear_pending_if_matches(&mut talk, &talks, "corrected", &["a".repeat(32)])
4307 .expect("stale clear is a conflict")
4308 );
4309 assert_eq!(
4310 talks
4311 .get(&talk.id)
4312 .expect("reload after stale clear")
4313 .pending,
4314 "corrected\n\nlater"
4315 );
4316 }
4317
4318 #[tokio::test]
4319 async fn a_reply_save_preserves_pending_accepted_while_the_cli_runs() {
4320 let (tmp, talks) = store();
4321 let slow = "#!/bin/sh\ncat >/dev/null\nsleep 0.1\nprintf reply\n";
4322 let cfg = config(mock_agent(tmp.path(), slow, BTreeMap::new()));
4323 let mut running = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4324 let id = running.id.clone();
4325 let first = record(&mut running, &talks, "first", Vec::new()).expect("record");
4326
4327 let response_talks = talks.clone();
4328 let response_cfg = cfg.clone();
4329 let reply = tokio::spawn(async move {
4330 respond(
4331 &response_talks.claim_turn(&running.id).unwrap().unwrap(),
4332 &mut running,
4333 &response_talks,
4334 &response_cfg,
4335 &first,
4336 )
4337 .await
4338 });
4339 tokio::time::sleep(std::time::Duration::from_millis(20)).await;
4340
4341 let mut queued = talks.get(&id).expect("queued handle");
4342 queue(&mut queued, &talks, "next", Vec::new()).expect("queue");
4343 reply.await.expect("join").expect("reply");
4344
4345 let saved = talks.get(&id).expect("reload");
4346 assert_eq!(saved.pending, "next");
4347 assert_eq!(saved.pending_breaks, Some(Vec::new()));
4348 assert_eq!(saved.turns.len(), 2, "operator message and reply remain");
4349 }
4350
4351 #[tokio::test]
4352 async fn posts_during_a_resumed_turn_are_replayed_once_even_after_a_reply_save_failure() {
4353 for lose_reply in [false, true] {
4354 let (tmp, talks) = store();
4355 let cfg = config(mock_agent(tmp.path(), ECHO, BTreeMap::new()));
4356 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4357 say(
4358 &talks.claim_turn(&talk.id).unwrap().unwrap(),
4359 &mut talk,
4360 &talks,
4361 &cfg,
4362 "establish the session",
4363 Vec::new(),
4364 )
4365 .await
4366 .expect("first turn");
4367 assert!(agent::has_session(
4368 AgentKind::Command,
4369 &talk.seat,
4370 cfg.graph.sessions
4371 ));
4372
4373 post(&talks, &talk.id, "already available", "task-earlier").expect("earlier post");
4374 talk = talks.get(&talk.id).expect("reload earlier post");
4375 let ready = tmp.path().join("ready");
4376 let release = tmp.path().join("release");
4377 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";
4378 let slow_cfg = config(mock_agent(
4379 tmp.path(),
4380 slow,
4381 BTreeMap::from([
4382 ("READY".to_owned(), ready.to_string_lossy().into_owned()),
4383 ("RELEASE".to_owned(), release.to_string_lossy().into_owned()),
4384 ]),
4385 ));
4386 let text = record(&mut talk, &talks, "keep going", Vec::new()).expect("record");
4387 let prompt_turns = talk.turns.len();
4388 let id = talk.id.clone();
4389 let response_talks = talks.clone();
4390 let running = tokio::spawn(async move {
4391 respond(
4392 &response_talks.claim_turn(&talk.id).unwrap().unwrap(),
4393 &mut talk,
4394 &response_talks,
4395 &slow_cfg,
4396 &text,
4397 )
4398 .await
4399 });
4400 tokio::time::timeout(std::time::Duration::from_secs(5), async {
4401 while !ready.exists() {
4402 tokio::time::sleep(std::time::Duration::from_millis(10)).await;
4403 }
4404 })
4405 .await
4406 .expect("CLI read its prompt");
4407 post(&talks, &id, "concurrent task result", "task-one").expect("post");
4408 post(&talks, &id, "second task result", "task-two").expect("second post");
4409 if lose_reply {
4410 failpoint::force_put_failures(PUT_RETRIES);
4411 }
4412 std::fs::write(release, "go").expect("release CLI");
4413 let result = running.await.expect("join");
4414 if lose_reply {
4415 assert!(
4416 result
4417 .unwrap_err()
4418 .to_string()
4419 .contains("could not be saved")
4420 );
4421 } else {
4422 result.expect("reply");
4423 }
4424
4425 let mut saved = talks.get(&id).expect("reload");
4426 assert_eq!(saved.posts_read_through, Some(prompt_turns));
4427 assert_eq!(saved.turns[prompt_turns].body, "concurrent task result");
4428 assert_eq!(saved.turns[prompt_turns + 1].body, "second task result");
4429 assert!(posts_since_last_reply(&saved).is_some());
4430 let cfg = config(mock_agent(tmp.path(), ECHO, BTreeMap::new()));
4431 say(
4432 &talks.claim_turn(&id).unwrap().unwrap(),
4433 &mut saved,
4434 &talks,
4435 &cfg,
4436 "read the results",
4437 Vec::new(),
4438 )
4439 .await
4440 .expect("replay turn");
4441 let prompt = &saved.turns.last().unwrap().body;
4442 assert!(prompt.contains("# Posted by a task"), "{prompt}");
4443 assert!(!prompt.contains("already available"), "{prompt}");
4444 assert!(
4445 prompt
4446 .find("concurrent task result")
4447 .expect("first post in prompt")
4448 < prompt
4449 .find("second task result")
4450 .expect("second post in prompt")
4451 );
4452 let mut saved = talks.get(&id).expect("reload after replay");
4453 assert!(posts_since_last_reply(&saved).is_none());
4454 say(
4455 &talks.claim_turn(&id).unwrap().unwrap(),
4456 &mut saved,
4457 &talks,
4458 &cfg,
4459 "continue",
4460 Vec::new(),
4461 )
4462 .await
4463 .expect("next turn");
4464 assert!(!saved.turns.last().unwrap().body.contains("task result"));
4465 }
4466 }
4467
4468 fn counting_agent(dir: &Path, id: &str, body: &str) -> AgentSpec {
4471 let calls = dir.join(format!("{id}.calls"));
4472 let script = format!(
4473 "#!/bin/sh\necho x >> '{}'\n{body}\n",
4474 calls.to_string_lossy()
4475 );
4476 let path = dir.join(format!("mock-{id}.sh"));
4477 std::fs::write(&path, script).expect("write mock");
4478 AgentSpec {
4479 id: id.to_owned(),
4480 kind: AgentKind::Command,
4481 model: None,
4482 command: vec!["sh".to_owned(), path.to_string_lossy().into_owned()],
4483 extra_args: Vec::new(),
4484 env: BTreeMap::new(),
4485 prompt_delivery: None,
4486 }
4487 }
4488
4489 fn calls(dir: &Path, id: &str) -> usize {
4490 std::fs::read_to_string(dir.join(format!("{id}.calls"))).map_or(0, |s| s.lines().count())
4491 }
4492
4493 fn chain_config(specs: Vec<AgentSpec>, ids: &[&str]) -> Config {
4494 let mut cfg = config(specs[0].clone());
4495 cfg.agents = specs;
4496 cfg.roles.chatter = Some(AgentChoice::Chain(
4497 ids.iter().map(|s| (*s).to_owned()).collect(),
4498 ));
4499 cfg
4500 }
4501
4502 #[tokio::test]
4503 async fn completion_evidence_reaches_fresh_resumed_and_fallback_prompts() {
4504 for fallback in [false, true] {
4505 let (tmp, talks) = store();
4506 let cfg = if fallback {
4507 chain_config(
4508 vec![
4509 counting_agent(tmp.path(), "a", "cat >/dev/null\nexit 3"),
4510 counting_agent(tmp.path(), "b", "cat"),
4511 ],
4512 &["a", "b"],
4513 )
4514 } else {
4515 config(mock_agent(tmp.path(), ECHO, BTreeMap::new()))
4516 };
4517 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).unwrap();
4518 let lease = talks.claim_turn(&talk.id).unwrap().unwrap();
4519 for n in 0..2 {
4520 let text = format!(
4521 "# {}\n\n- Task: `unavailable-{n}`",
4522 crate::prompt::CHAT_TASK_NOTICE_HEADING
4523 );
4524 let reference = crate::chat_notify::CompletionReference {
4525 task: format!("unavailable-{n}"),
4526 run: None,
4527 notice: text.clone(),
4528 };
4529 let key = format!("unavailable-{n}:done");
4530 assert!(
4531 queue_once_matching(
4532 &mut talk,
4533 &talks,
4534 &text,
4535 &key,
4536 &|_| false,
4537 Some(&reference)
4538 )
4539 .unwrap()
4540 );
4541 assert!(
4542 !queue_once_matching(
4543 &mut talk,
4544 &talks,
4545 &text,
4546 &key,
4547 &|_| false,
4548 Some(&reference)
4549 )
4550 .unwrap()
4551 );
4552 talk = talks.get(&talk.id).unwrap();
4553 assert_eq!(talk.completion_notices.len(), n + 1);
4554 let text = drain(&mut talk, &talks).unwrap().unwrap();
4555 respond(&lease, &mut talk, &talks, &cfg, &text)
4556 .await
4557 .unwrap();
4558 let reply = &talk.turns.last().unwrap().body;
4559 assert!(reply.contains("# Verified outcome evidence"), "{reply}");
4560 assert!(reply.contains("Outcome evidence unavailable"));
4561 assert!(reply.contains("Do not file new tasks or edit repositories solely"));
4562 assert!(reply.contains("Explicitly say when no action remains"));
4563 }
4564 record(&mut talk, &talks, "ordinary follow-up", vec![]).unwrap();
4565 assert!(
4566 crate::chat_notify::response_evidence(&talk)
4567 .await
4568 .is_empty(),
4569 "history does not trigger lookups"
4570 );
4571 record(
4572 &mut talk,
4573 &talks,
4574 &format!("# {}\n\nlegacy", crate::prompt::CHAT_TASK_NOTICE_HEADING),
4575 vec![],
4576 )
4577 .unwrap();
4578 assert!(
4579 crate::chat_notify::response_evidence(&talk)
4580 .await
4581 .contains("Legacy notification has no structured task/run reference")
4582 );
4583 }
4584 }
4585
4586 #[tokio::test]
4587 async fn a_chatter_chain_falls_back_resends_the_transcript_and_sticks() {
4588 let (tmp, talks) = store();
4589 let a = counting_agent(tmp.path(), "a", "cat >/dev/null\nexit 3");
4590 let b = counting_agent(tmp.path(), "b", "cat");
4591 let cfg = chain_config(vec![a, b], &["a", "b"]);
4592 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4593 assert_eq!(talk.agent, "a");
4594 post(&talks, &talk.id, "fallback task result", "task").expect("post");
4595 talk = talks.get(&talk.id).expect("reload");
4596
4597 say(
4598 &talks.claim_turn(&talk.id).unwrap().unwrap(),
4599 &mut talk,
4600 &talks,
4601 &cfg,
4602 "hello there",
4603 Vec::new(),
4604 )
4605 .await
4606 .expect("turn");
4607 assert_eq!(calls(tmp.path(), "a"), 1, "each id is tried once");
4608 assert_eq!(calls(tmp.path(), "b"), 1);
4609 assert_eq!(talk.agent, "b", "the switch persists");
4610 assert!(talks.get(&talk.id).unwrap().agent == "b");
4611 let reply = talk.turns.last().unwrap();
4612 assert!(reply.body.contains("hello there"));
4613 assert!(reply.body.contains("fallback task result"));
4614 let saved = talks.get(&talk.id).expect("reload fallback");
4615 assert_eq!(saved.posts_read_through, Some(2));
4616 assert!(posts_since_last_reply(&saved).is_none());
4617 assert!(
4618 reply.body.contains("magi task add --solo"),
4619 "a fresh seat gets the full briefing"
4620 );
4621 assert!(
4622 talk.turns
4623 .iter()
4624 .any(|t| t.body.contains("agent changed from a to b")),
4625 "the switch is noted"
4626 );
4627 }
4628
4629 #[tokio::test]
4630 async fn an_exhausted_chatter_chain_fails_like_a_single_seat_and_stays_put() {
4631 let (tmp, talks) = store();
4632 let a = counting_agent(tmp.path(), "a", "cat >/dev/null\nexit 3");
4633 let b = counting_agent(tmp.path(), "b", "cat >/dev/null\nexit 4");
4634 let cfg = chain_config(vec![a, b], &["a", "b", "a"]);
4635 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4636
4637 let err = say(
4638 &talks.claim_turn(&talk.id).unwrap().unwrap(),
4639 &mut talk,
4640 &talks,
4641 &cfg,
4642 "hi",
4643 Vec::new(),
4644 )
4645 .await
4646 .expect_err("every agent failed");
4647 assert!(err.to_string().contains("`a`"), "{err:#}");
4648 assert_eq!(calls(tmp.path(), "a"), 1);
4649 assert_eq!(calls(tmp.path(), "b"), 1);
4650 assert_eq!(talk.agent, "a", "an exhausted chain leaves the agent alone");
4651 }
4652
4653 #[test]
4654 fn a_chatter_chain_skips_an_unknown_id_at_begin() {
4655 let (tmp, talks) = store();
4656 let b = counting_agent(tmp.path(), "b", "cat");
4657 let cfg = chain_config(vec![b], &["ghost", "b"]);
4658 let talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4659 assert_eq!(talk.agent, "b");
4660 }
4661
4662 #[tokio::test]
4663 async fn an_explicit_agent_inside_the_chatter_chain_stays_pinned() {
4664 let (tmp, talks) = store();
4665 let a = counting_agent(tmp.path(), "a", "cat >/dev/null\nexit 3");
4666 let b = counting_agent(tmp.path(), "b", "cat");
4667 let cfg = chain_config(vec![a, b], &["a", "b"]);
4668 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), Some("a")).expect("begin");
4669 say(
4670 &talks.claim_turn(&talk.id).unwrap().unwrap(),
4671 &mut talk,
4672 &talks,
4673 &cfg,
4674 "hi",
4675 Vec::new(),
4676 )
4677 .await
4678 .expect_err("a alone, and it fails");
4679 assert_eq!(calls(tmp.path(), "b"), 0);
4680 assert_eq!(talk.agent, "a");
4681 }
4682
4683 #[tokio::test]
4684 async fn an_explicit_agent_does_not_borrow_the_chatter_chain() {
4685 let (tmp, talks) = store();
4686 let a = counting_agent(tmp.path(), "a", "cat >/dev/null\nexit 3");
4687 let b = counting_agent(tmp.path(), "b", "cat");
4688 let c = counting_agent(tmp.path(), "c", "cat >/dev/null\nexit 3");
4689 let cfg = chain_config(vec![a, b, c], &["a", "b"]);
4690 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), Some("c")).expect("begin");
4691 say(
4692 &talks.claim_turn(&talk.id).unwrap().unwrap(),
4693 &mut talk,
4694 &talks,
4695 &cfg,
4696 "hi",
4697 Vec::new(),
4698 )
4699 .await
4700 .expect_err("c alone, and it fails");
4701 assert_eq!(calls(tmp.path(), "b"), 0);
4702 }
4703
4704 #[test]
4705 fn briefing_names_the_operator_with_or_without_a_persona() {
4706 let plain = briefing(Path::new("/repo"), "en", false);
4707 let named = briefing_with(Path::new("/repo"), "en", false, None, Some("Commander"));
4708 assert!(named.starts_with(&plain));
4709 assert!(named.contains("# Addressing the operator"));
4710 assert!(named.contains("\"Commander\""));
4711 let rei = crate::persona::builtin_catalog()
4712 .into_iter()
4713 .find(|p| p.id == "rei")
4714 .expect("rei");
4715 let with = briefing_with(
4716 Path::new("/repo"),
4717 "en",
4718 false,
4719 Some(&rei),
4720 Some("Commander"),
4721 );
4722 assert!(with.contains("\"Commander\""));
4723 assert!(!with.contains("# Addressing the operator"));
4724 }
4725
4726 #[test]
4727 fn briefing_carries_a_persona_section_only_when_one_is_chosen() {
4728 let plain = briefing(Path::new("/repo"), "en", false);
4729 assert_eq!(
4730 plain,
4731 briefing_with(Path::new("/repo"), "en", false, None, None)
4732 );
4733 assert!(!plain.contains("Persona"));
4734 let rei = crate::persona::builtin_catalog()
4735 .into_iter()
4736 .find(|p| p.id == "rei")
4737 .expect("rei");
4738 let with = briefing_with(Path::new("/repo"), "en", false, Some(&rei), None);
4739 assert!(with.starts_with(&plain), "the plain briefing is untouched");
4740 assert!(with.contains("# Persona (tone only)"));
4741 assert!(with.contains("TONE ONLY"));
4742 assert!(with.contains("task ids"));
4743 assert!(with.contains("write policy"));
4744 assert!(with.contains("`magi task add`"));
4745 assert!(with.contains("Rei Ayanami"));
4746 }
4747
4748 #[test]
4749 fn a_talk_written_before_personas_still_loads() {
4750 let (tmp, talks) = store();
4751 let spec = mock_agent(tmp.path(), ECHO, BTreeMap::new());
4752 let cfg = config(spec);
4753 let talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4754 let path = talks.root.join(format!("{}.json", talk.id));
4755 let mut v: serde_json::Value =
4756 serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
4757 v.as_object_mut().unwrap().remove("persona");
4758 v.as_object_mut().unwrap().remove("persona_dirty");
4759 std::fs::write(&path, v.to_string()).unwrap();
4760 let loaded = talks.get(&talk.id).expect("old record loads");
4761 assert_eq!(loaded.persona, "");
4762 assert!(!loaded.persona_dirty);
4763 }
4764
4765 #[test]
4766 fn the_briefing_files_with_solo_or_the_chosen_implementer_count() {
4767 let repo = Path::new("/repo");
4768 let solo = briefing_for(repo, "", false, None, None, 1);
4769 assert_eq!(solo, briefing(repo, "", false));
4770 assert!(solo.contains("magi task add --solo --repo"));
4771 assert!(solo.contains("magi task add --solo --attach"));
4772 for n in [2u8, 3] {
4773 let b = briefing_for(repo, "", false, None, None, n);
4774 assert!(
4775 b.contains(&format!("magi task add --implementers {n} --repo")),
4776 "{b}"
4777 );
4778 assert!(b.contains(&format!("magi task add --implementers {n} --attach")));
4779 assert!(!b.contains("task add --solo"), "{b}");
4780 assert!(!b.contains("Use --solo"), "{b}");
4781 }
4782 }
4783
4784 #[test]
4785 fn begin_with_applies_remembered_choices_and_drops_unfit_ones_alone() {
4786 let (tmp, talks) = store();
4787 let first = mock_agent(tmp.path(), ECHO, BTreeMap::new());
4788 let mut second = first.clone();
4789 second.id = "second".to_owned();
4790 let mut cfg = config(first.clone());
4791 cfg.agents.push(second.clone());
4792 let open = |p: &Preferred| {
4793 begin_with(&talks, &cfg, tmp.path().to_owned(), None, p).expect("begin")
4794 };
4795
4796 let talk = open(&Preferred {
4797 agent: Some("second".into()),
4798 persona: Some("rei".into()),
4799 implementers: Some(i64::from(check_implementers(3, &cfg).unwrap_or(1))),
4800 });
4801 assert_eq!(talk.agent, "second");
4802 assert!(
4803 !talk.fallback,
4804 "a remembered non-head agent is an explicit choice"
4805 );
4806 assert_eq!(talk.persona, "rei");
4807 assert_eq!(talk.implementers, check_implementers(3, &cfg).unwrap_or(1));
4808 assert!(!talk.persona_dirty && !talk.implementers_dirty);
4809
4810 let head = open(&Preferred {
4812 agent: Some(first.id.clone()),
4813 ..Preferred::default()
4814 });
4815 assert!(head.fallback);
4816
4817 for implementers in [0, 4, -1, 1000] {
4819 let t = open(&Preferred {
4820 agent: Some("gone".into()),
4821 persona: Some("no-such-persona".into()),
4822 implementers: Some(implementers),
4823 });
4824 assert_eq!(t.agent, first.id);
4825 assert!(t.fallback);
4826 assert_eq!(t.persona, "");
4827 assert_eq!(t.implementers, 1);
4828 }
4829
4830 let t = open(&Preferred {
4832 agent: Some("second".into()),
4833 persona: Some("default".into()),
4834 implementers: Some(9),
4835 });
4836 assert_eq!(
4837 (t.agent.as_str(), t.persona.as_str(), t.implementers),
4838 ("second", "", 1)
4839 );
4840
4841 let strict = begin_with(
4843 &talks,
4844 &cfg,
4845 tmp.path().to_owned(),
4846 Some("first-unknown"),
4847 &Preferred {
4848 agent: Some("second".into()),
4849 ..Preferred::default()
4850 },
4851 );
4852 assert!(strict.is_err());
4853 }
4854
4855 #[test]
4856 fn remembered_agent_can_open_when_the_chatter_chain_cannot_resolve() {
4857 let (tmp, talks) = store();
4858 let spec = mock_agent(tmp.path(), ECHO, BTreeMap::new());
4859 let cfg = chain_config(vec![spec.clone()], &["missing-chatter"]);
4862 assert!(begin(&talks, &cfg, tmp.path().to_owned(), None).is_err());
4863 let talk = begin_with(
4864 &talks,
4865 &cfg,
4866 tmp.path().to_owned(),
4867 None,
4868 &Preferred {
4869 agent: Some(spec.id.clone()),
4870 ..Preferred::default()
4871 },
4872 )
4873 .expect("a valid remembered agent does not require a default chain");
4874 assert_eq!(talk.agent, spec.id);
4875 assert!(!talk.fallback);
4876 assert_eq!(talks.get(&talk.id).unwrap().agent, spec.id);
4877 assert!(
4878 begin_with(
4879 &talks,
4880 &cfg,
4881 tmp.path().to_owned(),
4882 None,
4883 &Preferred {
4884 agent: Some("missing-preference".into()),
4885 ..Preferred::default()
4886 },
4887 )
4888 .is_err()
4889 );
4890 }
4891
4892 #[test]
4893 fn implementers_are_validated_and_old_records_load_as_solo() {
4894 let (tmp, talks) = store();
4895 let cfg = config(mock_agent(tmp.path(), ECHO, BTreeMap::new()));
4896 assert_eq!(check_implementers(1, &cfg), Ok(1));
4897 assert_eq!(check_implementers(3, &cfg), Ok(3));
4898 assert!(check_implementers(0, &cfg).is_err());
4899 assert!(check_implementers(4, &cfg).is_err());
4900 let mut empty = cfg.clone();
4901 empty.agents.clear();
4902 assert!(check_implementers(2, &empty).is_err());
4903
4904 let talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4905 let path = talks.path_of(&talk.id);
4906 let mut v: serde_json::Value =
4907 serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
4908 v.as_object_mut().unwrap().remove("implementers");
4909 v.as_object_mut().unwrap().remove("implementers_dirty");
4910 std::fs::write(&path, v.to_string()).unwrap();
4911 let loaded = talks.get(&talk.id).expect("load");
4912 assert_eq!(loaded.implementers, 1);
4913 assert!(!loaded.implementers_dirty);
4914 }
4915
4916 #[tokio::test]
4917 async fn an_implementers_switch_is_noted_once_and_kept_across_a_failed_turn() {
4918 let (tmp, talks) = store();
4919 let spec = mock_agent(tmp.path(), ECHO, BTreeMap::new());
4920 let cfg = config(spec);
4921 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4922 let lease = talks.claim_turn(&talk.id).unwrap().unwrap();
4923 say(&lease, &mut talk, &talks, &cfg, "hello", Vec::new())
4924 .await
4925 .expect("first turn");
4926
4927 assert!(switch_implementers(&mut talk, &talks, 2).expect("switch"));
4928 assert!(!switch_implementers(&mut talk, &talks, 2).expect("same"));
4929 assert!(talk.implementers_dirty);
4930 say(&lease, &mut talk, &talks, &cfg, "next", Vec::new())
4931 .await
4932 .expect("turn");
4933 let prompt = &talk.turns.last().unwrap().body;
4934 assert!(prompt.contains("# Task filing update"), "{prompt}");
4935 assert!(prompt.contains("--implementers 2"));
4936 assert!(!talk.implementers_dirty, "cleared after a successful turn");
4937
4938 say(&lease, &mut talk, &talks, &cfg, "again", Vec::new())
4939 .await
4940 .expect("turn");
4941 assert!(
4942 !talk
4943 .turns
4944 .last()
4945 .unwrap()
4946 .body
4947 .contains("# Task filing update")
4948 );
4949
4950 let mut no_sessions = cfg.clone();
4952 no_sessions.graph.sessions = false;
4953 say(&lease, &mut talk, &talks, &no_sessions, "one", Vec::new())
4954 .await
4955 .expect("turn");
4956 say(&lease, &mut talk, &talks, &no_sessions, "two", Vec::new())
4957 .await
4958 .expect("turn");
4959 assert!(talk.turns.last().unwrap().body.contains("--implementers 2"));
4960 }
4961
4962 #[tokio::test]
4963 async fn a_persona_switch_notes_marks_dirty_and_updates_the_next_turn_once() {
4964 let (tmp, talks) = store();
4965 let spec = mock_agent(tmp.path(), ECHO, BTreeMap::new());
4966 let cfg = config(spec);
4967 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4968 let lease = talks.claim_turn(&talk.id).unwrap().unwrap();
4969 say(&lease, &mut talk, &talks, &cfg, "hello", Vec::new())
4970 .await
4971 .expect("first turn");
4972 assert!(!talk.turns[1].body.contains("Persona"));
4973
4974 assert!(switch_persona(&mut talk, &talks, "misato").expect("switch"));
4975 assert!(!switch_persona(&mut talk, &talks, "misato").expect("same"));
4976 assert!(talk.persona_dirty);
4977 assert!(talk.turns.last().unwrap().body.contains("persona changed"));
4978
4979 say(&lease, &mut talk, &talks, &cfg, "next", Vec::new())
4980 .await
4981 .expect("turn");
4982 let prompt = &talk.turns.last().unwrap().body;
4983 assert!(prompt.contains("# Persona update"), "{prompt}");
4984 assert!(prompt.contains("Misato Katsuragi"));
4985 assert!(!talk.persona_dirty, "cleared after a successful turn");
4986
4987 say(&lease, &mut talk, &talks, &cfg, "again", Vec::new())
4988 .await
4989 .expect("turn");
4990 assert!(!talk.turns.last().unwrap().body.contains("# Persona update"));
4991
4992 assert!(switch_persona(&mut talk, &talks, "default").expect("back"));
4993 assert_eq!(talk.persona, "");
4994 say(&lease, &mut talk, &talks, &cfg, "plain", Vec::new())
4995 .await
4996 .expect("turn");
4997 assert!(
4998 talk.turns
4999 .last()
5000 .unwrap()
5001 .body
5002 .contains("turned the persona off")
5003 );
5004
5005 assert!(switch_persona(&mut talk, &talks, "rei").expect("rei"));
5007 let mut no_sessions = cfg.clone();
5008 no_sessions.graph.sessions = false;
5009 say(&lease, &mut talk, &talks, &no_sessions, "one", Vec::new())
5010 .await
5011 .expect("turn");
5012 say(&lease, &mut talk, &talks, &no_sessions, "two", Vec::new())
5013 .await
5014 .expect("turn");
5015 let last = &talk.turns.last().unwrap().body;
5016 assert!(!talk.persona_dirty);
5017 assert!(last.contains("# Persona (tone only)"), "{last}");
5018 assert!(last.contains("Rei Ayanami"));
5019 }
5020
5021 #[tokio::test]
5022 async fn the_first_turn_carries_the_briefing_and_later_turns_do_not() {
5023 let (tmp, talks) = store();
5024 let spec = mock_agent(tmp.path(), ECHO, BTreeMap::new());
5025 let cfg = config(spec);
5026 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
5027
5028 say(
5029 &talks.claim_turn(&talk.id).unwrap().unwrap(),
5030 &mut talk,
5031 &talks,
5032 &cfg,
5033 "what does the queue module do?",
5034 Vec::new(),
5035 )
5036 .await
5037 .expect("first turn");
5038 let first_prompt = &talk.turns[1].body;
5039 assert!(first_prompt.contains("magi task add --solo"));
5040 assert!(first_prompt.contains("what does the queue module do?"));
5041
5042 say(
5043 &talks.claim_turn(&talk.id).unwrap().unwrap(),
5044 &mut talk,
5045 &talks,
5046 &cfg,
5047 "and how is it locked?",
5048 Vec::new(),
5049 )
5050 .await
5051 .expect("second turn");
5052 let second_prompt = &talk.turns[3].body;
5053 assert!(
5054 !second_prompt.contains("magi task add --solo"),
5055 "the briefing is sent once, not on every turn: {second_prompt}"
5056 );
5057 assert!(second_prompt.contains("and how is it locked?"));
5058 }
5059
5060 #[tokio::test]
5061 async fn switching_agent_resets_the_seat_notes_it_and_resends_the_transcript() {
5062 let (tmp, talks) = store();
5063 let a = mock_agent(tmp.path(), ECHO, BTreeMap::new());
5064 let mut b = a.clone();
5065 b.id = "other".to_owned();
5066 let mut cfg = config(a.clone());
5067 cfg.agents.push(b.clone());
5068 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), Some(&a.id)).expect("begin");
5069 say(
5070 &talks.claim_turn(&talk.id).unwrap().unwrap(),
5071 &mut talk,
5072 &talks,
5073 &cfg,
5074 "remember the walrus",
5075 Vec::new(),
5076 )
5077 .await
5078 .expect("first turn");
5079 let old_session = talk.seat.claude_session.clone();
5080 assert_eq!(talk.seat.turns, 1);
5081
5082 assert!(switch_agent(&mut talk, &talks, &b).expect("switch"));
5083 assert_eq!(talk.agent, "other");
5084 assert_eq!(talk.seat.turns, 0);
5085 assert_eq!(talk.seat.agent, "other");
5086 assert_ne!(talk.seat.claude_session, old_session);
5087 let note = talk.turns.last().expect("note");
5088 assert_eq!(note.who, Who::Agent);
5089 assert!(note.body.starts_with(MAGI_NOTE), "{}", note.body);
5090 assert!(note.body.contains("changed from"), "{}", note.body);
5091 assert_eq!(talks.get(&talk.id).expect("reload").agent, "other");
5092
5093 let before = talk.turns.len();
5094 assert!(!switch_agent(&mut talk, &talks, &b).expect("same agent"));
5095 assert_eq!(talk.turns.len(), before, "a no-op writes no note");
5096
5097 say(
5098 &talks.claim_turn(&talk.id).unwrap().unwrap(),
5099 &mut talk,
5100 &talks,
5101 &cfg,
5102 "what did I say?",
5103 Vec::new(),
5104 )
5105 .await
5106 .expect("turn after switch");
5107 let prompt = &talk.turns.last().expect("reply").body;
5108 assert!(prompt.contains("remember the walrus"), "{prompt}");
5109 assert!(prompt.contains("## magi"), "{prompt}");
5110 assert!(prompt.contains("what did I say?"), "{prompt}");
5111 }
5112
5113 #[tokio::test]
5114 async fn say_appends_the_operator_turn_then_the_agent_turn() {
5115 let (tmp, talks) = store();
5116 let spec = mock_agent(tmp.path(), REPLY, env("go ahead"));
5117 let cfg = config(spec);
5118 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
5119
5120 say(
5121 &talks.claim_turn(&talk.id).unwrap().unwrap(),
5122 &mut talk,
5123 &talks,
5124 &cfg,
5125 "can I rename this function?",
5126 Vec::new(),
5127 )
5128 .await
5129 .expect("say");
5130
5131 assert_eq!(talk.turns.len(), 2);
5132 assert_eq!(talk.turns[0].who, Who::Operator);
5133 assert_eq!(talk.turns[0].body, "can I rename this function?");
5134 assert_eq!(talk.turns[1].who, Who::Agent);
5135 assert_eq!(talk.turns[1].body, "go ahead");
5136 assert_eq!(talks.get(&talk.id).expect("get").turns, talk.turns);
5137 }
5138
5139 #[tokio::test]
5140 async fn a_failed_turn_keeps_the_operator_message_and_says_what_happened() {
5141 let (tmp, talks) = store();
5142 let spec = mock_agent(tmp.path(), BROKEN, BTreeMap::new());
5143 let cfg = config(spec);
5144 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
5145
5146 talk.posts_read_through = None;
5147 talks.put(&mut talk).expect("save old-format boundary");
5148 post(&talks, &talk.id, "unread task result", "task").expect("post");
5149 talk = talks.get(&talk.id).expect("reload");
5150
5151 let err = say(
5152 &talks.claim_turn(&talk.id).unwrap().unwrap(),
5153 &mut talk,
5154 &talks,
5155 &cfg,
5156 "check the tests",
5157 Vec::new(),
5158 )
5159 .await
5160 .expect_err("a turn with no answer is an error");
5161 assert!(err.to_string().contains("no answer"), "{err}");
5162
5163 let on_disk = talks.get(&talk.id).expect("get");
5164 assert_eq!(on_disk.turns.len(), 3);
5165 assert_eq!(on_disk.posts_read_through, Some(0));
5166 assert!(
5167 posts_since_last_reply(&on_disk)
5168 .unwrap()
5169 .contains("unread task result")
5170 );
5171 assert_eq!(on_disk.turns[1].body, "check the tests");
5172 let note = &on_disk.turns[2];
5173 assert_eq!(note.who, Who::Agent);
5174 assert!(note.body.starts_with(MAGI_NOTE), "{}", note.body);
5175 assert!(note.body.contains("your message is saved"));
5176 }
5177
5178 #[tokio::test]
5184 async fn a_passing_write_failure_while_saving_the_reply_does_not_lose_it() {
5185 let (tmp, talks) = store();
5186 let spec = mock_agent(tmp.path(), REPLY, env("go ahead"));
5187 let cfg = config(spec);
5188 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
5189
5190 let text =
5191 record(&mut talk, &talks, "can I rename this function?", Vec::new()).expect("record");
5192 failpoint::force_put_failures(PUT_RETRIES - 1);
5195 respond(
5196 &talks.claim_turn(&talk.id).unwrap().unwrap(),
5197 &mut talk,
5198 &talks,
5199 &cfg,
5200 &text,
5201 )
5202 .await
5203 .expect("respond must survive a write failure its own retries can outlast");
5204
5205 assert_eq!(talk.turns.len(), 2);
5206 assert_eq!(talk.turns[1].who, Who::Agent);
5207 assert_eq!(talk.turns[1].body, "go ahead");
5208 let on_disk = talks.get(&talk.id).expect("get");
5209 assert_eq!(
5210 on_disk.turns, talk.turns,
5211 "the reply must reach disk despite the early write failures"
5212 );
5213 }
5214
5215 #[tokio::test]
5221 async fn a_persistent_write_failure_while_saving_the_reply_is_never_silent() {
5222 let (tmp, talks) = store();
5223 let spec = mock_agent(tmp.path(), REPLY, env("go ahead"));
5224 let cfg = config(spec);
5225 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
5226
5227 let text = record(&mut talk, &talks, "check the tests", Vec::new()).expect("record");
5228 failpoint::force_put_failures(PUT_RETRIES);
5233 let err = respond(
5234 &talks.claim_turn(&talk.id).unwrap().unwrap(),
5235 &mut talk,
5236 &talks,
5237 &cfg,
5238 &text,
5239 )
5240 .await
5241 .expect_err("a reply that cannot be saved must be reported, not swallowed");
5242 assert!(err.to_string().contains("could not be saved"), "{err}");
5243
5244 let on_disk = talks.get(&talk.id).expect("get");
5245 assert_eq!(
5246 on_disk.turns.len(),
5247 2,
5248 "the operator turn plus a visible note"
5249 );
5250 assert_eq!(on_disk.turns[0].body, "check the tests");
5251 let note = &on_disk.turns[1];
5252 assert_eq!(note.who, Who::Agent);
5253 assert!(note.body.starts_with(MAGI_NOTE), "{}", note.body);
5254 assert!(
5255 note.body.contains("could not be saved"),
5256 "the operator must be told the reply is missing, not left staring \
5257 at a gap with no explanation: {}",
5258 note.body
5259 );
5260 assert_eq!(
5261 talk.turns, on_disk.turns,
5262 "the in-memory talk must match what actually landed on disk"
5263 );
5264
5265 let artifacts = talks.artifacts_of(&talk.id);
5268 let stash = std::fs::read_dir(&artifacts)
5269 .expect("artifacts dir")
5270 .filter_map(|e| e.ok())
5271 .find(|e| e.file_name().to_string_lossy().ends_with("-lost.txt"))
5272 .expect("a stash file for the lost reply");
5273 let stashed = std::fs::read_to_string(stash.path()).expect("read stash");
5274 assert_eq!(stashed, "go ahead");
5275
5276 assert_eq!(
5284 on_disk.seat.turns, 1,
5285 "the note's write must carry the turn the CLI actually took"
5286 );
5287 assert_eq!(
5288 on_disk.seat.claude_session, talk.seat.claude_session,
5289 "the session id handed to the CLI must survive the failed reply"
5290 );
5291 assert_eq!(on_disk.seat.captured_session, talk.seat.captured_session);
5292 assert!(
5293 agent::has_session(AgentKind::Command, &on_disk.seat, cfg.graph.sessions),
5294 "the next turn must resume, not open the same session id twice"
5295 );
5296 }
5297
5298 #[tokio::test]
5303 async fn a_write_failure_that_also_loses_the_note_still_reports_it() {
5304 let (tmp, talks) = store();
5305 let spec = mock_agent(tmp.path(), REPLY, env("go ahead"));
5306 let cfg = config(spec);
5307 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
5308
5309 let text = record(&mut talk, &talks, "check the tests", Vec::new()).expect("record");
5310 failpoint::force_put_failures(PUT_RETRIES * 2);
5313 let err = respond(
5314 &talks.claim_turn(&talk.id).unwrap().unwrap(),
5315 &mut talk,
5316 &talks,
5317 &cfg,
5318 &text,
5319 )
5320 .await
5321 .expect_err("neither the reply nor the note could be saved");
5322 assert!(err.to_string().contains("could not be saved"), "{err}");
5323
5324 assert_eq!(talk.turns.len(), 1, "only the operator's own turn");
5325 let on_disk = talks.get(&talk.id).expect("get");
5326 assert_eq!(on_disk.turns.len(), 1);
5327
5328 assert_eq!(
5338 on_disk.seat.turns, 0,
5339 "an unwritable file cannot record the turn the CLI took"
5340 );
5341 assert_eq!(
5342 talk.seat.turns, 1,
5343 "the in-memory seat still reports the turn the CLI actually took"
5344 );
5345 assert_eq!(
5346 on_disk.seat.claude_session, talk.seat.claude_session,
5347 "the session id was minted at `begin` and never changes here"
5348 );
5349 }
5350
5351 #[tokio::test]
5355 async fn attachments_reach_the_prompt_and_an_empty_body_is_still_a_turn() {
5356 let (tmp, talks) = store();
5357 let spec = mock_agent(tmp.path(), ECHO, BTreeMap::new());
5358 let cfg = config(spec);
5359 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
5360
5361 let att = talks
5362 .put_attachment(
5363 &talk.id,
5364 "image/png",
5365 "screenshot.png",
5366 b"pretend-png-bytes",
5367 )
5368 .expect("put attachment");
5369
5370 say(
5371 &talks.claim_turn(&talk.id).unwrap().unwrap(),
5372 &mut talk,
5373 &talks,
5374 &cfg,
5375 "",
5376 vec![att.clone()],
5377 )
5378 .await
5379 .expect("an empty body with an attachment is still a turn");
5380
5381 let operator_turn = &talk.turns[0];
5382 assert_eq!(operator_turn.who, Who::Operator);
5383 assert_eq!(operator_turn.body, "");
5384 assert_eq!(operator_turn.attachments, vec![att.clone()]);
5385
5386 let prompt = &talk.turns[1].body;
5387 let expected_path = talks
5388 .attachments_dir(&talk.id)
5389 .join(format!("{}.png", att.id));
5390 assert!(
5391 prompt.contains(&expected_path.display().to_string()),
5392 "the agent must be told the attachment's absolute path: {prompt}"
5393 );
5394 assert!(prompt.contains("image/png"), "and its mime: {prompt}");
5395 }
5396
5397 #[test]
5406 fn attachment_path_is_absolute_even_when_the_store_root_is_relative() {
5407 let talks = Talks::at(PathBuf::from("relative-talks-root-for-this-test"));
5408 let att = Attachment {
5409 id: "0".repeat(32),
5410 name: "shot.png".to_owned(),
5411 mime: "image/png".to_owned(),
5412 bytes: 3,
5413 };
5414 let path = talks
5415 .attachment_path("some-talk-id", &att)
5416 .expect("a supported mime always yields a path");
5417 assert!(
5418 path.is_absolute(),
5419 "must be absolute even off a relative store root: {}",
5420 path.display()
5421 );
5422 }
5423
5424 #[tokio::test]
5425 async fn a_turn_past_the_configured_talk_timeout_is_reported_with_that_timeout() {
5426 let (tmp, talks) = store();
5431 let slow = mock_agent(
5432 tmp.path(),
5433 "#!/bin/sh\ncat >/dev/null\nsleep 2\n",
5434 BTreeMap::new(),
5435 );
5436 let mut cfg = config(slow);
5437 cfg.graph.timeout_talk = 1;
5438 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
5439
5440 let err = say(
5441 &talks.claim_turn(&talk.id).unwrap().unwrap(),
5442 &mut talk,
5443 &talks,
5444 &cfg,
5445 "check the tests",
5446 Vec::new(),
5447 )
5448 .await
5449 .expect_err("a turn that never answers is an error");
5450 assert!(
5451 err.to_string().contains("did not answer within 1s"),
5452 "{err}"
5453 );
5454
5455 let on_disk = talks.get(&talk.id).expect("get");
5456 let note = on_disk.turns.last().expect("a note turn was recorded");
5457 assert!(
5458 note.body.contains("did not answer within 1s"),
5459 "the transcript must show the configured timeout: {}",
5460 note.body
5461 );
5462 }
5463
5464 #[test]
5465 fn closing_is_idempotent_and_a_closed_talk_takes_no_more_turns() {
5466 let (tmp, talks) = store();
5467 let spec = mock_agent(tmp.path(), REPLY, env("hi"));
5468 let cfg = config(spec);
5469 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
5470
5471 close(&mut talk, &talks).expect("close");
5472 assert_eq!(talk.status, TalkStatus::Closed);
5473 close(&mut talk, &talks).expect("closing twice is not an error");
5474
5475 let err =
5476 record(&mut talk, &talks, "still there?", Vec::new()).expect_err("closed talks refuse");
5477 assert!(err.to_string().contains("closed"));
5478 let _ = &cfg; }
5480
5481 #[tokio::test]
5482 async fn a_close_that_lands_while_a_turn_is_in_flight_is_not_undone_by_the_reply() {
5483 let (tmp, talks) = store();
5484 let spec = mock_agent(tmp.path(), REPLY, env("here you go"));
5485 let cfg = config(spec);
5486 let mut in_flight = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
5489
5490 let mut closed_elsewhere = talks.get(&in_flight.id).expect("reread");
5494 close(&mut closed_elsewhere, &talks).expect("close");
5495 assert_eq!(
5496 talks.get(&in_flight.id).expect("reread").status,
5497 TalkStatus::Closed,
5498 "the close landed on disk before the turn finished"
5499 );
5500
5501 assert_eq!(in_flight.status, TalkStatus::Open);
5505 respond(
5506 &talks.claim_turn(&in_flight.id).unwrap().unwrap(),
5507 &mut in_flight,
5508 &talks,
5509 &cfg,
5510 "one more question",
5511 )
5512 .await
5513 .expect("the turn itself still completes");
5514
5515 let on_disk = talks.get(&in_flight.id).expect("reread");
5516 assert_eq!(
5517 on_disk.status,
5518 TalkStatus::Closed,
5519 "a close must stick even when a turn that started before it finishes after it"
5520 );
5521 assert!(
5524 on_disk.turns.iter().any(|t| t.body == "here you go"),
5525 "the in-flight turn's own reply is still recorded: {:?}",
5526 on_disk.turns
5527 );
5528 }
5529
5530 #[test]
5531 fn a_close_that_lands_before_record_is_called_is_not_undone_by_it() {
5532 let (tmp, talks) = store();
5533 let spec = mock_agent(tmp.path(), REPLY, env("hi"));
5534 let cfg = config(spec);
5535 let mut stale = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
5538
5539 let mut closed_elsewhere = talks.get(&stale.id).expect("reread");
5542 close(&mut closed_elsewhere, &talks).expect("close");
5543 assert_eq!(
5544 talks.get(&stale.id).expect("reread").status,
5545 TalkStatus::Closed,
5546 "the close landed on disk before record was called"
5547 );
5548
5549 assert_eq!(stale.status, TalkStatus::Open);
5553 let err = record(&mut stale, &talks, "still there?", Vec::new())
5554 .expect_err("a close that landed first must be honored, not overwritten");
5555 assert!(err.to_string().contains("closed"));
5556
5557 let on_disk = talks.get(&stale.id).expect("reread");
5558 assert_eq!(
5559 on_disk.status,
5560 TalkStatus::Closed,
5561 "record must not resurrect a conversation closed while its snapshot was stale"
5562 );
5563 assert!(
5564 on_disk.turns.is_empty(),
5565 "the rejected turn must not have been appended: {:?}",
5566 on_disk.turns
5567 );
5568 let _ = &cfg; }
5570
5571 #[test]
5572 fn consultation_queue_does_not_wait_on_either_conversation_lock() {
5573 for evidence in [true, false] {
5574 let (tmp, talks) = store();
5575 let cfg = config(mock_agent(tmp.path(), REPLY, env("hi")));
5576 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).unwrap();
5577 close(&mut talk, &talks).unwrap();
5578 let answer = evidence.then(|| talks.answer_guard().unwrap());
5579 let file = (!evidence).then(|| {
5580 TurnLock::take(&talks.root.join(".store.turn"))
5581 .unwrap()
5582 .unwrap()
5583 });
5584 assert!(
5585 try_queue_consult(&talks, &talk.id, "consultation", None)
5586 .unwrap()
5587 .is_none()
5588 );
5589 let saved = talks.get(&talk.id).unwrap();
5590 assert_eq!(saved.status, TalkStatus::Closed);
5591 assert!(saved.pending_messages.is_empty());
5592 drop(file);
5593 drop(answer);
5594 assert!(
5595 try_queue_consult(&talks, &talk.id, "consultation", None)
5596 .unwrap()
5597 .is_some()
5598 );
5599 let saved = talks.get(&talk.id).unwrap();
5600 assert_eq!(saved.status, TalkStatus::Open);
5601 assert_eq!(saved.pending, "consultation");
5602 assert_eq!(saved.pending_messages.len(), 1);
5603 assert_eq!(saved.pending_messages[0].sender, Some(Sender::Magi));
5604 }
5605 }
5606
5607 #[test]
5608 fn evidence_try_lock_does_not_wait_for_either_store_handle() {
5609 let (tmp, talks) = store();
5610 let guard = talks.answer_guard().unwrap();
5611 assert!(talks.try_answer_guard().unwrap().is_none());
5613 let other = Talks::at(tmp.path().join("talks"));
5614 assert!(other.try_answer_guard().unwrap().is_none());
5615 drop(guard);
5616 assert!(other.try_answer_guard().unwrap().is_some());
5617 }
5618
5619 #[test]
5620 fn owner_retraction_waits_until_the_authorized_question_is_persisted() {
5621 use crate::ask::{Answer, Question, Questions};
5622 use std::sync::mpsc;
5623
5624 let (tmp, talks) = store();
5625 let cfg = config(mock_agent(tmp.path(), REPLY, env("hi")));
5626 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).unwrap();
5627 let questions = Questions::at(tmp.path().join("questions"));
5628 let mut q = Question::new(
5629 "run".into(),
5630 crate::land::APPROVAL_NODE.into(),
5631 "land".into(),
5632 "Merge?".into(),
5633 String::new(),
5634 vec!["merge".into(), "hold".into()],
5635 );
5636 questions.put(&mut q).unwrap();
5637 let instruction = format!("{}: hold", q.id);
5638 record(&mut talk, &talks, &instruction, vec![]).unwrap();
5639 let (started_tx, started_rx) = mpsc::channel();
5640 let (finished_tx, finished_rx) = mpsc::channel();
5641 std::thread::scope(|scope| {
5642 let mut writer = None;
5643 let (saved, guard) = questions
5644 .update(&q.id, |q| {
5645 let guard = talks.try_answer_guard()?.context("evidence is busy")?;
5646 q.answer_authority = crate::consult::authorize_answer(
5647 q,
5648 &talks,
5649 &questions,
5650 &talk.id,
5651 crate::queue::CHAT_NODE,
5652 "hold",
5653 Some(&instruction),
5654 )?;
5655 assert!(q.answer_authority.is_some());
5656 let talks = talks.clone();
5657 let mut snapshot = talk.clone();
5658 writer = Some(scope.spawn(move || {
5659 started_tx.send(()).unwrap();
5660 queue(&mut snapshot, &talks, "wait", vec![]).unwrap();
5661 finished_tx.send(()).unwrap();
5662 }));
5663 started_rx.recv().unwrap();
5664 assert!(matches!(
5665 finished_rx.recv_timeout(Duration::from_millis(100)),
5666 Err(mpsc::RecvTimeoutError::Timeout)
5667 ));
5668 q.answer(Answer::Choice("hold".into()))?;
5669 Ok(guard)
5671 })
5672 .unwrap();
5673 assert_eq!(saved.resolution().as_deref(), Some("hold"));
5674 assert_eq!(
5675 questions.get(&q.id).unwrap().resolution().as_deref(),
5676 Some("hold")
5677 );
5678 assert!(matches!(
5679 finished_rx.recv_timeout(Duration::from_millis(100)),
5680 Err(mpsc::RecvTimeoutError::Timeout)
5681 ));
5682 drop(guard);
5683 writer.unwrap().join().unwrap();
5684 finished_rx.recv().unwrap();
5685 });
5686 assert_eq!(talks.get(&talk.id).unwrap().pending, "wait");
5687 }
5688
5689 #[test]
5690 fn close_blocks_on_records_guard_rather_than_interleaving_with_it() {
5691 let (tmp, talks) = store();
5692 let spec = mock_agent(tmp.path(), REPLY, env("hi"));
5693 let cfg = config(spec);
5694 let talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
5695
5696 let held = talks.guard().unwrap();
5700
5701 let talks2 = talks.clone();
5702 let id = talk.id.clone();
5703 let closing = std::thread::spawn(move || {
5704 let mut talk = talks2.get(&id).expect("get");
5705 close(&mut talk, &talks2).expect("close");
5706 });
5707
5708 std::thread::sleep(Duration::from_millis(50));
5709 assert!(
5710 !closing.is_finished(),
5711 "close must wait for the guard, not read and write while it is held - \
5712 a re-read alone narrows this window without closing it"
5713 );
5714
5715 drop(held);
5716 closing.join().expect("close thread panicked");
5717
5718 assert_eq!(
5719 talks.get(&talk.id).expect("reread").status,
5720 TalkStatus::Closed,
5721 "once the guard is free, close still lands"
5722 );
5723 let _ = &cfg; }
5725
5726 #[test]
5727 fn reopening_a_closed_talk_lets_it_take_turns_again_and_reopening_twice_is_not_an_error() {
5728 let (tmp, talks) = store();
5729 let spec = mock_agent(tmp.path(), REPLY, env("hi"));
5730 let cfg = config(spec);
5731 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
5732
5733 close(&mut talk, &talks).expect("close");
5734 assert_eq!(talk.status, TalkStatus::Closed);
5735
5736 reopen(&mut talk, &talks).expect("reopen");
5737 assert_eq!(talk.status, TalkStatus::Open);
5738 assert_eq!(
5739 talks.get(&talk.id).expect("reread").status,
5740 TalkStatus::Open
5741 );
5742
5743 reopen(&mut talk, &talks).expect("reopening an open talk is not an error");
5745 assert_eq!(talk.status, TalkStatus::Open);
5746
5747 record(&mut talk, &talks, "one more thing", Vec::new())
5748 .expect("a reopened talk takes turns again");
5749 let _ = &cfg; }
5751
5752 #[test]
5753 fn removing_a_talk_deletes_its_record_and_artifacts_and_refuses_an_unknown_id() {
5754 let (tmp, talks) = store();
5755 let spec = mock_agent(tmp.path(), REPLY, env("hi"));
5756 let cfg = config(spec);
5757 let talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
5758
5759 let artifacts = talks.artifacts_of(&talk.id);
5760 std::fs::create_dir_all(&artifacts).expect("create artifacts dir");
5761 std::fs::write(artifacts.join("turn-1.txt"), "hello").expect("write artifact");
5762
5763 talks.remove(&talk.id).expect("remove");
5764 assert!(!talks.path_of(&talk.id).is_file(), "the record is gone");
5765 assert!(!artifacts.is_dir(), "the artifacts directory is gone");
5766 assert!(
5767 talks.get(&talk.id).is_err(),
5768 "a removed talk cannot be read back"
5769 );
5770
5771 let err = talks
5772 .remove("nonexistent-id")
5773 .expect_err("unknown id refused");
5774 assert!(err.to_string().contains("no talk matches"), "{err}");
5775 let _ = &cfg; }
5777
5778 #[tokio::test]
5779 async fn a_delete_that_lands_while_a_turn_is_in_flight_is_not_undone_by_the_reply() {
5780 let (tmp, talks) = store();
5781 let spec = mock_agent(tmp.path(), REPLY, env("here you go"));
5782 let cfg = config(spec);
5783 let mut in_flight = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
5786
5787 talks.remove(&in_flight.id).expect("remove");
5788 assert!(
5789 talks.get(&in_flight.id).is_err(),
5790 "the delete landed on disk before the turn finished"
5791 );
5792
5793 respond(
5796 &talks.claim_turn(&in_flight.id).unwrap().unwrap(),
5797 &mut in_flight,
5798 &talks,
5799 &cfg,
5800 "one more question",
5801 )
5802 .await
5803 .expect("the turn itself still completes rather than erroring");
5804
5805 assert!(
5806 talks.get(&in_flight.id).is_err(),
5807 "a delete must stick even when a turn that started before it finishes after it"
5808 );
5809 }
5810
5811 #[test]
5812 fn a_delete_that_lands_before_record_is_called_is_not_undone_by_it() {
5813 let (tmp, talks) = store();
5814 let spec = mock_agent(tmp.path(), REPLY, env("hi"));
5815 let cfg = config(spec);
5816 let mut stale = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
5819
5820 talks.remove(&stale.id).expect("remove");
5821
5822 let err = record(&mut stale, &talks, "still there?", Vec::new())
5826 .expect_err("a delete that landed first must be honored, not overwritten");
5827 assert!(err.to_string().contains("deleted"), "{err}");
5828
5829 assert!(
5830 talks.get(&stale.id).is_err(),
5831 "record must not resurrect a conversation deleted while its snapshot was stale"
5832 );
5833 let _ = &cfg; }
5835
5836 #[test]
5837 fn a_delete_that_lands_before_close_is_called_is_not_undone_by_it() {
5838 let (tmp, talks) = store();
5839 let spec = mock_agent(tmp.path(), REPLY, env("hi"));
5840 let cfg = config(spec);
5841 let mut stale = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
5844
5845 talks.remove(&stale.id).expect("remove");
5846
5847 let err = close(&mut stale, &talks)
5851 .expect_err("a delete that landed first must be honored, not overwritten");
5852 assert!(err.to_string().contains("deleted"), "{err}");
5853
5854 assert!(
5855 talks.get(&stale.id).is_err(),
5856 "close must not resurrect a conversation deleted while its snapshot was stale"
5857 );
5858 let _ = &cfg; }
5860
5861 #[test]
5862 fn a_delete_that_lands_before_reopen_is_called_is_not_undone_by_it() {
5863 let (tmp, talks) = store();
5864 let spec = mock_agent(tmp.path(), REPLY, env("hi"));
5865 let cfg = config(spec);
5866 let mut stale = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
5869 close(&mut stale, &talks).expect("close");
5870
5871 talks.remove(&stale.id).expect("remove");
5872
5873 let err = reopen(&mut stale, &talks)
5877 .expect_err("a delete that landed first must be honored, not overwritten");
5878 assert!(err.to_string().contains("deleted"), "{err}");
5879
5880 assert!(
5881 talks.get(&stale.id).is_err(),
5882 "reopen must not resurrect a conversation deleted while its snapshot was stale"
5883 );
5884 let _ = &cfg; }
5886
5887 #[test]
5888 fn list_puts_open_talks_before_closed_ones() {
5889 let (tmp, talks) = store();
5890 let make = |id: &str, status: TalkStatus| {
5891 let mut t = Talk {
5892 recommendations: Default::default(),
5893 posts_read_through: None,
5894 pending_breaks: None,
5895 pending_messages: Vec::new(),
5896 schema: SCHEMA,
5897 id: id.to_owned(),
5898 repo: tmp.path().to_owned(),
5899 agent: "mock".to_owned(),
5900 status,
5901 turns: Vec::new(),
5902 pending: String::new(),
5903 pending_attachments: Vec::new(),
5904 fallback: false,
5905 persona: String::new(),
5906 persona_dirty: false,
5907 implementers: 1,
5908 implementers_dirty: false,
5909 notified: Vec::new(),
5910 completion_notices: Vec::new(),
5911 created_at: Timestamp::now(),
5912 updated_at: Timestamp::now(),
5913 seat: SeatState::new(SEAT, "mock", 7),
5914 };
5915 talks.put(&mut t).expect("put");
5916 };
5917 make("20260901-000000-0001", TalkStatus::Open);
5918 make("20260902-000000-0002", TalkStatus::Open);
5919 make("20260903-000000-0003", TalkStatus::Closed);
5920
5921 let ids: Vec<String> = talks.list().into_iter().map(|t| t.id).collect();
5922 assert_eq!(
5923 ids,
5924 [
5925 "20260902-000000-0002",
5926 "20260901-000000-0001",
5927 "20260903-000000-0003"
5928 ]
5929 );
5930 assert_eq!(talks.count_open(), 2);
5931 }
5932
5933 #[test]
5934 fn tasks_of_finds_only_this_talks_own_tasks() {
5935 let dir = tempfile::tempdir().expect("tempdir");
5936 let queue = Queue::at(dir.path().join("queue"));
5937
5938 let mut mine = Task::new(
5939 "rework the loader".to_owned(),
5940 "rework the loader".to_owned(),
5941 PathBuf::from("/repo"),
5942 Source::Agent {
5943 run: "20260904-014455-ab12".to_owned(),
5944 node: "chat".to_owned(),
5945 },
5946 );
5947 queue.put(&mut mine).expect("put mine");
5948
5949 let mut theirs = Task::new(
5950 "unrelated".to_owned(),
5951 "unrelated".to_owned(),
5952 PathBuf::from("/repo"),
5953 Source::Agent {
5954 run: "20260904-090000-zz99".to_owned(),
5955 node: "implement".to_owned(),
5956 },
5957 );
5958 queue.put(&mut theirs).expect("put theirs");
5959
5960 let mut human = Task::new(
5961 "typed by hand".to_owned(),
5962 "typed by hand".to_owned(),
5963 PathBuf::from("/repo"),
5964 Source::Human,
5965 );
5966 queue.put(&mut human).expect("put human");
5967
5968 let found = tasks_of(&queue, "20260904-014455-ab12");
5969 assert_eq!(found.len(), 1);
5970 assert_eq!(found[0].id, mine.id);
5971 }
5972
5973 #[test]
5974 fn the_briefing_names_solo_task_add() {
5975 let brief = briefing(Path::new("/repo"), "en", false);
5976 assert!(brief.contains("magi task add --solo"));
5977 assert!(brief.contains("/repo"));
5978 assert!(!brief.contains("Hold this conversation in"));
5979 }
5980
5981 #[test]
5987 fn the_briefing_explains_targeting_a_different_repository_by_name() {
5988 let brief = briefing(Path::new("/repo"), "en", false);
5989 assert!(brief.contains("--repo does not have to be a full path"));
5990 assert!(brief.contains("owner/repo"));
5991 assert!(brief.contains("magi repos"));
5992 assert!(brief.contains("ask the operator"));
5993 }
5994
5995 #[test]
5996 fn the_briefing_tells_the_assistant_to_pass_images_with_attach() {
5997 let brief = briefing(Path::new("/repo"), "en", false);
5998 assert!(brief.contains("--attach <path>"), "{brief}");
5999 assert!(brief.contains("deleting this conversation"), "{brief}");
6000 }
6001
6002 #[test]
6003 fn the_briefing_names_the_language_when_it_is_not_english() {
6004 let brief = briefing(Path::new("/repo"), "Japanese", false);
6005 assert!(brief.contains("Hold this conversation in Japanese"));
6006 }
6007
6008 #[test]
6009 fn the_briefing_forbids_writes_unless_the_repository_opted_in() {
6010 let read_only = briefing(Path::new("/repo"), "en", false);
6011 assert!(read_only.contains("Do not write files"));
6012 assert!(!read_only.contains("allow_write"));
6013
6014 let writable = briefing(Path::new("/repo"), "en", true);
6015 assert!(!writable.contains("Do not write files"));
6016 assert!(writable.contains("allow_write = true"));
6017 assert!(writable.contains("magi task add --solo"));
6020 assert!(writable.contains("say plainly what you"));
6021 }
6022
6023 #[test]
6024 fn the_briefing_says_the_chat_cannot_push_and_tasks_report_back() {
6025 let b = briefing_for(Path::new("/r"), "en", false, None, None, 1);
6026 assert!(
6027 b.contains("cannot send the operator a message on your own"),
6028 "{b}"
6029 );
6030 assert!(b.contains(crate::prompt::CHAT_TASK_NOTICE_HEADING));
6031 assert!(b.contains("magi talk watch --timeout 900"));
6032 assert!(b.contains("nor a successfully registered watch"));
6033 }
6034
6035 #[test]
6036 fn a_post_is_replayed_until_the_agent_answers_again() {
6037 let (_tmp, talks) = store();
6038 let mut talk = ctx_talk("mock", Vec::new());
6039 talks.put(&mut talk).expect("put");
6040 post(&talks, &talk.id, " found it ", "20260902-000000-aaaa").expect("post");
6041 let mut talk = talks.get(&talk.id).expect("get");
6042 let block = posts_since_last_reply(&talk).expect("block");
6043 assert!(block.starts_with("# Posted by a task"), "{block}");
6044 assert!(block.contains("found it"));
6045 talk.turns.push(reply("ok", None));
6046 assert!(posts_since_last_reply(&talk).is_none());
6047 assert!(post(&talks, &talk.id, " ", "r").is_err());
6048 close(&mut talk, &talks).expect("close");
6049 assert!(post(&talks, &talk.id, "late", "r").is_err());
6050 }
6051
6052 #[test]
6053 fn queue_once_accepts_a_key_a_single_time_even_after_a_drain() {
6054 let (_tmp, talks) = store();
6055 let mut talk = ctx_talk("mock", Vec::new());
6056 talks.put(&mut talk).expect("put");
6057 assert!(queue_once(&mut talk, &talks, "one", "k").expect("first"));
6058 drain(&mut talk, &talks).expect("drain");
6059 assert!(!queue_once(&mut talk, &talks, "one", "k").expect("again"));
6060 assert!(talks.get(&talk.id).expect("get").pending.is_empty());
6061 }
6062 #[test]
6063 fn sender_mixed_notifications_survive_reload_drain_and_reply() {
6064 let (_tmp, talks) = store();
6065 let mut talk = ctx_talk("mock", Vec::new());
6066 talks.put(&mut talk).unwrap();
6067 queue(&mut talk, &talks, "owner", Vec::new()).unwrap();
6068 assert!(queue_once(&mut talk, &talks, "notice", "n").unwrap());
6069 let mut talk = talks.get(&talk.id).unwrap();
6070 assert_eq!(talk.pending_messages[0].sender, Some(Sender::Operator));
6071 assert_eq!(talk.pending_messages[1].sender, Some(Sender::Magi));
6072 assert!(
6073 edit_pending_message(&mut talk, &talks, "forged", "owner\n\nnotice", &[], Some(1))
6074 .is_err()
6075 );
6076 drain(&mut talk, &talks).unwrap();
6077 let mut talk = talks.get(&talk.id).unwrap();
6078 let turn = talk.turns.last().unwrap();
6079 assert_eq!(turn.who, Who::Operator);
6080 assert_eq!(sender(turn, turn.messages.first()), Sender::Operator);
6081 assert_eq!(sender(turn, turn.messages.get(1)), Sender::Magi);
6082 let reply = resolve_reply(
6083 &talk,
6084 Some(ReplyTarget {
6085 turn: 0,
6086 message: 1,
6087 }),
6088 )
6089 .unwrap()
6090 .unwrap();
6091 assert_eq!(reply.sender, Some(Sender::Magi));
6092 assert!(!queue_once(&mut talk, &talks, "notice", "n").unwrap());
6093 }
6094
6095 #[test]
6096 fn sender_legacy_operator_prose_is_never_migrated_by_heading() {
6097 let mut turn = reply("# Task finished\n\nmagi: operator typed this", None);
6098 turn.who = Who::Operator;
6099 assert_eq!(sender(&turn, None), Sender::Operator);
6100 turn.who = Who::Agent;
6101 turn.body = "magi: failed".into();
6102 assert_eq!(sender(&turn, None), Sender::Magi);
6103 turn.body = "persona reply".into();
6104 assert_eq!(sender(&turn, None), Sender::Persona);
6105 turn.posted_by = Some("task".into());
6106 assert_eq!(sender(&turn, None), Sender::Magi);
6107 turn.posted_by = None;
6108 turn.body = "magi: actual persona words".into();
6109 turn.sender = Some(Sender::Persona);
6110 assert_eq!(sender(&turn, None), Sender::Persona);
6111 }
6112}