1use std::path::{Path, PathBuf};
52use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
53use std::time::Duration;
54
55use anyhow::{Context, Result, bail};
56use jiff::Timestamp;
57use serde::{Deserialize, Serialize};
58
59use crate::agent::{self, Invocation, SeatState};
60use crate::config::{AgentSpec, Config};
61use crate::queue::{Queue, Source, Task};
62
63pub const SCHEMA: u32 = 1;
65
66fn turn_timeout(cfg: &Config) -> Duration {
77 Duration::from_secs(cfg.graph.timeout_talk)
78}
79
80const SEAT: &str = "talk";
83
84const MAGI_NOTE: &str = "magi: ";
86
87#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
89#[serde(rename_all = "lowercase")]
90pub enum Who {
91 Operator,
93 Agent,
96}
97
98#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
106#[serde(deny_unknown_fields)]
107pub struct Attachment {
108 pub id: String,
110 pub name: String,
112 pub mime: String,
115 pub bytes: u64,
117}
118
119#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
121#[serde(deny_unknown_fields)]
122pub struct Turn {
123 pub who: Who,
125 pub body: String,
127 pub at: Timestamp,
129 #[serde(default)]
132 pub attachments: Vec<Attachment>,
133 #[serde(default, skip_serializing_if = "Option::is_none")]
138 pub usage: Option<TurnUsage>,
139 #[serde(default, skip_serializing_if = "Option::is_none")]
146 pub breaks: Option<Vec<usize>>,
147 #[serde(default, skip_serializing_if = "Option::is_none")]
152 pub posted_by: Option<String>,
153}
154
155#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
163pub struct TurnUsage {
164 pub context_tokens: u64,
166 pub agent: String,
168 #[serde(default)]
170 pub model: Option<String>,
171}
172
173#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
178pub struct ContextUsage {
179 pub tokens: Option<u64>,
181 pub window: Option<u64>,
183 pub percent: Option<u64>,
185 pub warn: bool,
187 pub since_switch: bool,
191 pub model: Option<String>,
193 #[serde(default)]
196 pub estimated: bool,
197}
198
199const CONTEXT_WARN_PERCENT: u64 = 80;
201
202const STANDING_PROMPT_FALLBACK_CHARS: u64 = 7000;
205
206pub fn estimate_context_tokens(talk: &Talk, standing_chars: u64) -> Option<u64> {
219 let mut counted = false;
220 let mut chars = standing_chars;
221 for t in talk.turns.iter().filter(|t| !t.body.starts_with(MAGI_NOTE)) {
222 counted = true;
223 chars += t.body.chars().count() as u64;
224 }
225 counted.then(|| (chars * 2).div_ceil(7))
227}
228
229pub fn context_usage(talk: &Talk, cfg: Option<&Config>) -> ContextUsage {
242 let current = cfg.and_then(|c| c.agents.iter().find(|a| a.id == talk.agent));
243 let model = current.and_then(|a| a.model.clone());
244 let window = cfg
245 .zip(model.as_deref())
246 .and_then(|(c, m)| c.context_window(m))
247 .filter(|w| *w > 0);
248 let usage = talk
249 .turns
250 .iter()
251 .rev()
252 .find(|t| t.who == Who::Agent && !t.body.starts_with(MAGI_NOTE))
253 .and_then(|t| t.usage.as_ref());
254 let measured = usage.map(|u| u.context_tokens);
255 let tokens = measured.or_else(|| {
256 let standing = cfg.map_or(STANDING_PROMPT_FALLBACK_CHARS, |c| {
257 briefing_for(
258 &talk.repo,
259 &c.graph.language,
260 c.talk.allow_write,
261 crate::persona::active(&c.talk.personas, &talk.persona).as_ref(),
262 c.talk.operator_name(),
263 talk.implementers,
264 )
265 .chars()
266 .count() as u64
267 });
268 estimate_context_tokens(talk, standing)
269 });
270 let estimated = measured.is_none() && tokens.is_some();
271 let since_switch =
272 usage.is_some_and(|u| u.agent != talk.agent || (current.is_some() && u.model != model));
273 let (percent, warn) = match (tokens, window) {
274 (Some(t), Some(w)) => (
275 Some(t.saturating_mul(100) / w),
276 t.saturating_mul(100) >= w.saturating_mul(CONTEXT_WARN_PERCENT),
277 ),
278 _ => (None, false),
279 };
280 ContextUsage {
281 tokens,
282 window,
283 percent,
284 warn,
285 since_switch,
286 model,
287 estimated,
288 }
289}
290
291#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
295#[serde(rename_all = "lowercase")]
296pub enum TalkStatus {
297 Open,
300 Closed,
302}
303
304impl TalkStatus {
305 pub fn open(self) -> bool {
307 matches!(self, Self::Open)
308 }
309
310 pub fn as_str(self) -> &'static str {
312 match self {
313 Self::Open => "open",
314 Self::Closed => "closed",
315 }
316 }
317}
318
319#[derive(Debug, Clone, Serialize, Deserialize)]
321#[serde(deny_unknown_fields)]
322pub struct Talk {
323 pub schema: u32,
325 pub id: String,
327 pub repo: PathBuf,
329 pub agent: String,
331 pub status: TalkStatus,
333 pub turns: Vec<Turn>,
335 #[serde(default, skip_serializing_if = "Option::is_none")]
339 pub posts_read_through: Option<usize>,
340 #[serde(default)]
343 pub pending: String,
344 #[serde(default)]
346 pub pending_attachments: Vec<Attachment>,
347 #[serde(default, skip_serializing_if = "Option::is_none")]
349 pub pending_breaks: Option<Vec<usize>>,
350 #[serde(default)]
355 pub fallback: bool,
356 #[serde(default)]
359 pub persona: String,
360 #[serde(default)]
364 pub persona_dirty: bool,
365 #[serde(default = "solo_implementers")]
368 pub implementers: u8,
369 #[serde(default)]
372 pub implementers_dirty: bool,
373 #[serde(default)]
378 pub notified: Vec<String>,
379 pub created_at: Timestamp,
381 pub updated_at: Timestamp,
383 seat: SeatState,
388}
389
390impl Talk {
391 pub fn short(&self) -> &str {
393 short(&self.id)
394 }
395}
396
397#[derive(Debug, Clone)]
399pub struct Talks {
400 root: PathBuf,
401 lock: Arc<Mutex<()>>,
410}
411
412impl Talks {
413 pub fn open() -> Self {
415 Self::at(crate::run::home().join("talks"))
416 }
417
418 pub fn at(root: PathBuf) -> Self {
421 Self {
422 root,
423 lock: Arc::new(Mutex::new(())),
424 }
425 }
426
427 fn guard(&self) -> Result<StoreGuard<'_>> {
442 let mutex = self.lock.lock().unwrap_or_else(PoisonError::into_inner);
443 std::fs::create_dir_all(&self.root)
444 .with_context(|| format!("create {}", self.root.display()))?;
445 let path = self.root.join(".store.turn");
446 let deadline = std::time::Instant::now() + TAKEOVER_LOCK_TTL * 2;
447 loop {
448 if let Some(file) = TurnLock::take(&path)? {
449 return Ok(StoreGuard {
450 _file: file,
451 _mutex: mutex,
452 });
453 }
454 if std::time::Instant::now() >= deadline {
455 bail!("the talk store is locked by another process");
456 }
457 std::thread::sleep(Duration::from_millis(10));
458 }
459 }
460
461 pub fn root(&self) -> &Path {
463 &self.root
464 }
465
466 pub fn path_of(&self, id: &str) -> PathBuf {
468 self.root.join(format!("{id}.json"))
469 }
470
471 pub fn artifacts_of(&self, id: &str) -> PathBuf {
474 self.root.join(format!("{id}.artifacts"))
475 }
476
477 pub fn attachments_dir(&self, id: &str) -> PathBuf {
481 self.artifacts_of(id).join("attachments")
482 }
483
484 pub fn put_attachment(
493 &self,
494 id: &str,
495 mime: &str,
496 name: &str,
497 data: &[u8],
498 ) -> Result<Attachment> {
499 let dir = self.attachments_dir(id);
500 std::fs::create_dir_all(&dir).with_context(|| format!("create {}", dir.display()))?;
501 let ext = attachment_ext(mime).with_context(|| format!("unsupported mime `{mime}`"))?;
502 let att = Attachment {
503 id: new_attachment_id(),
504 name: name.to_owned(),
505 mime: mime.to_owned(),
506 bytes: data.len() as u64,
507 };
508 std::fs::write(dir.join(format!("{}.{ext}", att.id)), data)
509 .with_context(|| format!("write attachment {}", att.id))?;
510 std::fs::write(
511 dir.join(format!("{}.json", att.id)),
512 serde_json::to_string(&att).context("serialize attachment")?,
513 )
514 .with_context(|| format!("write attachment metadata {}", att.id))?;
515 Ok(att)
516 }
517
518 pub fn attachment_meta(&self, id: &str, att_id: &str) -> Result<Option<Attachment>> {
527 if !valid_attachment_id(att_id) {
528 return Ok(None);
529 }
530 let meta_path = self.attachments_dir(id).join(format!("{att_id}.json"));
531 if !meta_path.is_file() {
532 return Ok(None);
533 }
534 let att = serde_json::from_str(
535 &std::fs::read_to_string(&meta_path)
536 .with_context(|| format!("read {}", meta_path.display()))?,
537 )
538 .with_context(|| format!("parse {}", meta_path.display()))?;
539 Ok(Some(att))
540 }
541
542 pub fn read_attachment(&self, id: &str, att_id: &str) -> Result<Option<(Attachment, Vec<u8>)>> {
546 let Some(att) = self.attachment_meta(id, att_id)? else {
547 return Ok(None);
548 };
549 let ext = attachment_ext(&att.mime).with_context(|| {
550 format!("attachment {att_id} has an unsupported mime `{}`", att.mime)
551 })?;
552 let data_path = self.attachments_dir(id).join(format!("{att_id}.{ext}"));
553 let data =
554 std::fs::read(&data_path).with_context(|| format!("read {}", data_path.display()))?;
555 Ok(Some((att, data)))
556 }
557
558 fn attachment_path(&self, id: &str, att: &Attachment) -> Option<PathBuf> {
575 let ext = attachment_ext(&att.mime)?;
576 let path = self.attachments_dir(id).join(format!("{}.{ext}", att.id));
577 std::path::absolute(&path).ok()
578 }
579
580 pub fn put(&self, t: &mut Talk) -> Result<()> {
589 std::fs::create_dir_all(&self.root)
590 .with_context(|| format!("create {}", self.root.display()))?;
591 t.updated_at = Timestamp::now();
592 let body = serde_json::to_string_pretty(t).context("serialize talk")?;
593 let path = self.path_of(&t.id);
594 let tmp = path.with_extension("json.tmp");
595 write_atomic(&tmp, &path, &body)
596 }
597
598 pub fn get(&self, id: &str) -> Result<Talk> {
600 let resolved = self.resolve_id(id)?;
601 read_path(&self.path_of(&resolved))
602 }
603
604 pub fn list(&self) -> Vec<Talk> {
607 self.list_counting_unreadable().0
608 }
609
610 pub fn list_counting_unreadable(&self) -> (Vec<Talk>, usize) {
613 let mut unreadable = 0;
614 let mut all: Vec<Talk> = std::fs::read_dir(&self.root)
615 .into_iter()
616 .flatten()
617 .flatten()
618 .map(|e| e.path())
619 .filter(|p| p.extension().is_some_and(|x| x == "json"))
620 .filter_map(|p| {
621 let talk = read_path(&p).ok();
622 if talk.is_none() {
623 unreadable += 1;
624 }
625 talk
626 })
627 .collect();
628 all.sort_unstable_by(|a, b| {
629 let rank = |t: &Talk| u8::from(!t.status.open());
630 rank(a).cmp(&rank(b)).then_with(|| b.id.cmp(&a.id))
631 });
632 (all, unreadable)
633 }
634
635 pub fn resolve_id(&self, prefix: &str) -> Result<String> {
637 if self.path_of(prefix).is_file() {
638 return Ok(prefix.to_owned());
639 }
640 let hits: Vec<String> = self
641 .list()
642 .into_iter()
643 .map(|t| t.id)
644 .filter(|id| id.starts_with(prefix) || id.ends_with(prefix))
645 .collect();
646 match hits.len() {
647 1 => Ok(hits.into_iter().next().expect("exactly one hit")),
648 0 => bail!("no talk matches `{prefix}`"),
649 _ => bail!(
650 "`{prefix}` matches {} talks: {}",
651 hits.len(),
652 hits.join(", ")
653 ),
654 }
655 }
656
657 pub fn revision(&self) -> u64 {
660 std::fs::read_dir(&self.root)
661 .into_iter()
662 .flatten()
663 .flatten()
664 .filter(|e| e.path().extension().is_none_or(|x| x != "turn"))
665 .filter(|e| !e.file_name().to_string_lossy().starts_with('.'))
666 .filter_map(|e| e.metadata().ok())
667 .filter_map(|m| m.modified().ok())
668 .filter_map(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
669 .map(|d| d.as_millis() as u64)
670 .max()
671 .unwrap_or(0)
672 }
673
674 pub fn count_open(&self) -> usize {
676 self.list().iter().filter(|t| t.status.open()).count()
677 }
678
679 pub fn turn_path(&self, id: &str) -> PathBuf {
682 self.root.join(format!("{id}.turn"))
683 }
684
685 pub fn claim_turn(&self, id: &str) -> Result<Option<TurnLease>> {
694 self.claim_turn_at(id, Timestamp::now())
695 }
696
697 fn claim_turn_at(&self, id: &str, now: Timestamp) -> Result<Option<TurnLease>> {
698 std::fs::create_dir_all(&self.root)
699 .with_context(|| format!("create {}", self.root.display()))?;
700 let path = self.turn_path(id);
701 let token = fresh_token();
702 if create_turn(&path, &token, now)? {
703 return Ok(Some(TurnLease {
704 talk: id.to_owned(),
705 path,
706 token,
707 }));
708 }
709 if lease_blocks(&path, now) {
710 return Ok(None);
711 }
712 let Some(_lock) = TurnLock::take(&path)? else {
717 return Ok(None);
718 };
719 if lease_blocks(&path, now) {
720 return Ok(None);
721 }
722 let _ = std::fs::remove_file(&path);
723 Ok(create_turn(&path, &token, now)?.then_some(TurnLease {
724 talk: id.to_owned(),
725 path,
726 token,
727 }))
728 }
729
730 pub fn turn_held(&self, id: &str) -> bool {
732 read_turn(&self.turn_path(id)).is_some_and(|r| r.fresh(Timestamp::now()))
733 }
734
735 pub fn remove(&self, id: &str) -> Result<()> {
748 let _guard = self.guard()?;
749 let resolved = self.resolve_id(id)?;
750 let path = self.path_of(&resolved);
751 std::fs::remove_file(&path).with_context(|| format!("remove {}", path.display()))?;
752 let artifacts = self.artifacts_of(&resolved);
753 if artifacts.is_dir() {
754 std::fs::remove_dir_all(&artifacts)
755 .with_context(|| format!("remove {}", artifacts.display()))?;
756 }
757 let _ = std::fs::remove_file(self.turn_path(&resolved));
758 Ok(())
759 }
760}
761
762struct StoreGuard<'a> {
765 _file: TurnLock,
766 _mutex: MutexGuard<'a, ()>,
767}
768
769#[derive(Debug, Serialize, Deserialize)]
772struct TurnRecord {
773 token: String,
774 pid: u32,
775 beat_at: Timestamp,
776}
777
778impl TurnRecord {
779 fn fresh(&self, now: Timestamp) -> bool {
780 now.as_second() - self.beat_at.as_second() <= crate::ask::LEASE_TTL.as_secs() as i64
781 }
782}
783
784fn fresh_token() -> String {
788 static SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
789 let n = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
790 let seed = crate::rng::entropy() ^ n.wrapping_mul(0x9E37_79B9_7F4A_7C15);
791 crate::rng::SplitMix64::new(seed).uuid_v4()
792}
793
794fn read_turn(path: &Path) -> Option<TurnRecord> {
795 serde_json::from_str(&std::fs::read_to_string(path).ok()?).ok()
796}
797
798const TAKEOVER_LOCK_TTL: Duration = Duration::from_secs(10);
800
801const TICKET_TTL: Duration = Duration::from_secs(10);
804
805const TICKET_GENERATIONS: u32 = 16;
807
808const TICKET_SWEEP_AGE: Duration = Duration::from_secs(3600);
810
811fn create_exclusive(path: &Path, body: &str) -> Result<bool> {
813 use std::io::Write as _;
814 match std::fs::OpenOptions::new()
815 .write(true)
816 .create_new(true)
817 .open(path)
818 {
819 Ok(mut f) => {
820 if let Err(e) = f.write_all(body.as_bytes()) {
821 drop(f);
822 let _ = std::fs::remove_file(path);
823 return Err(e).with_context(|| format!("write {}", path.display()));
824 }
825 Ok(true)
826 }
827 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => Ok(false),
828 Err(e) => Err(e).with_context(|| format!("create {}", path.display())),
829 }
830}
831
832fn create_turn(path: &Path, token: &str, now: Timestamp) -> Result<bool> {
833 let record = TurnRecord {
834 token: token.to_owned(),
835 pid: std::process::id(),
836 beat_at: now,
837 };
838 let body = serde_json::to_string(&record).context("serialize turn lease")?;
839 let tmp = path.with_extension(format!("turn.{token}.new"));
842 publish_exclusive(path, &tmp, &body)
843}
844
845fn lease_blocks(path: &Path, now: Timestamp) -> bool {
849 if read_turn(path).is_some_and(|r| r.fresh(now)) {
850 return true;
851 }
852 std::fs::metadata(path).is_ok_and(|m| {
853 m.len() == 0
854 && m.modified()
855 .ok()
856 .and_then(|t| t.elapsed().ok())
857 .is_some_and(|age| age <= TAKEOVER_LOCK_TTL)
858 })
859}
860
861fn link_unsupported(e: &std::io::Error) -> bool {
864 e.kind() == std::io::ErrorKind::Unsupported || (cfg!(windows) && e.raw_os_error() == Some(1))
865}
866
867fn create_in_place(path: &Path, body: &str) -> Result<bool> {
885 use std::io::Write as _;
886 let mut f = match std::fs::OpenOptions::new()
887 .write(true)
888 .create_new(true)
889 .open(path)
890 {
891 Ok(f) => f,
892 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => return Ok(false),
893 Err(e) => return Err(e).with_context(|| format!("create {}", path.display())),
894 };
895 f.write_all(body.as_bytes())
896 .with_context(|| format!("write {}", path.display()))?;
897 Ok(std::fs::read_to_string(path).is_ok_and(|t| t == body))
900}
901
902fn publish_exclusive(path: &Path, tmp: &Path, body: &str) -> Result<bool> {
903 std::fs::write(tmp, body).with_context(|| format!("write {}", tmp.display()))?;
904 #[cfg(test)]
905 let linked = if failpoint::no_link_forced() {
906 Err(std::io::Error::from(std::io::ErrorKind::Unsupported))
907 } else {
908 std::fs::hard_link(tmp, path)
909 };
910 #[cfg(not(test))]
911 let linked = std::fs::hard_link(tmp, path);
912 let out = match linked {
913 Ok(()) => Ok(true),
914 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => Ok(false),
915 Err(e) if link_unsupported(&e) => create_in_place(path, body),
916 Err(e) => Err(e).with_context(|| format!("create {}", path.display())),
917 };
918 let _ = std::fs::remove_file(tmp);
919 out
920}
921
922fn remove_if_carries(path: &Path, expected: &str) -> bool {
933 let gone = path.with_extension(format!("gone.{}", fresh_token()));
934 if std::fs::rename(path, &gone).is_err() {
935 return false;
936 }
937 let found = std::fs::read_to_string(&gone);
938 if found.as_ref().is_ok_and(|t| t == expected) {
939 let _ = std::fs::remove_file(&gone);
940 return true;
941 }
942 if let Ok(body) = found {
943 let back = path.with_extension(format!("back.{}", fresh_token()));
944 match publish_exclusive(path, &back, &body) {
945 Ok(true) => {}
946 Ok(false) | Err(_) => tracing::warn!(
947 "{} was replaced while a stale removal had it aside; \
948 the displaced file is dropped",
949 path.display()
950 ),
951 }
952 }
953 let _ = std::fs::remove_file(&gone);
954 false
955}
956
957struct TurnLock {
961 path: PathBuf,
962 token: String,
963}
964
965impl TurnLock {
966 fn token() -> String {
967 fresh_token()
968 }
969
970 fn publish(path: &Path, token: &str) -> Result<bool> {
974 let tmp = path.with_extension(format!("lock.{token}.new"));
975 publish_exclusive(path, &tmp, token)
976 }
977
978 fn take(lease: &Path) -> Result<Option<Self>> {
979 let path = lease.with_extension("turn.lock");
980 let token = Self::token();
981 if Self::publish(&path, &token)? {
982 return Ok(Some(Self { path, token }));
983 }
984 let Ok(seen) = std::fs::read_to_string(&path) else {
985 return Ok(None);
986 };
987 let key = if !seen.is_empty() && seen.chars().all(|c| c.is_ascii_alphanumeric() || c == '-')
990 {
991 seen.as_str()
992 } else {
993 "invalid"
994 };
995 let aged = std::fs::metadata(&path)
996 .and_then(|m| m.modified())
997 .ok()
998 .and_then(|t| t.elapsed().ok())
999 .is_some_and(|age| age > TAKEOVER_LOCK_TTL);
1000 if !aged {
1001 return Ok(None);
1002 }
1003 let mut won = false;
1015 for n in 0..TICKET_GENERATIONS {
1016 let ticket = path.with_extension(format!("lock.{key}.break.{n}"));
1017 if create_exclusive(&ticket, "")? {
1018 won = true;
1019 break;
1020 }
1021 let stale = std::fs::metadata(&ticket)
1022 .and_then(|m| m.modified())
1023 .ok()
1024 .and_then(|t| t.elapsed().ok())
1025 .is_some_and(|age| age > TICKET_TTL);
1026 if !stale {
1027 return Ok(None);
1028 }
1029 }
1030 if !won {
1031 Self::sweep_tickets(&path);
1036 return Ok(None);
1037 }
1038 Self::sweep_tickets(&path);
1039 if !remove_if_carries(&path, &seen) {
1045 return Ok(None);
1046 }
1047 if Self::publish(&path, &token)? {
1048 return Ok(Some(Self { path, token }));
1049 }
1050 Ok(None)
1051 }
1052
1053 fn sweep_tickets(path: &Path) {
1056 let (Some(dir), Some(name)) = (path.parent(), path.file_name().and_then(|n| n.to_str()))
1057 else {
1058 return;
1059 };
1060 let prefix = format!("{name}.");
1061 let Ok(entries) = std::fs::read_dir(dir) else {
1062 return;
1063 };
1064 for entry in entries.flatten() {
1065 let file = entry.file_name();
1066 let Some(file) = file.to_str() else { continue };
1067 if !(file.starts_with(&prefix) && file.contains(".break.")) {
1068 continue;
1069 }
1070 let old = entry
1071 .metadata()
1072 .and_then(|m| m.modified())
1073 .ok()
1074 .and_then(|t| t.elapsed().ok())
1075 .is_some_and(|age| age > TICKET_SWEEP_AGE);
1076 if old {
1077 let _ = std::fs::remove_file(entry.path());
1078 }
1079 }
1080 }
1081
1082 fn take_patiently(lease: &Path) -> Option<Self> {
1084 for _ in 0..50 {
1085 match Self::take(lease) {
1086 Ok(Some(lock)) => return Some(lock),
1087 Ok(None) => std::thread::sleep(Duration::from_millis(10)),
1088 Err(_) => return None,
1089 }
1090 }
1091 None
1092 }
1093}
1094
1095impl Drop for TurnLock {
1096 fn drop(&mut self) {
1097 remove_if_carries(&self.path, &self.token);
1099 }
1100}
1101
1102pub const TURN_BEAT: Duration = Duration::from_secs(20);
1105
1106#[derive(Debug)]
1111pub struct TurnLease {
1112 talk: String,
1113 path: PathBuf,
1114 token: String,
1115}
1116
1117impl TurnLease {
1118 pub fn holds(&self) -> bool {
1120 read_turn(&self.path).is_some_and(|r| r.token == self.token)
1121 }
1122
1123 pub fn beat(&self) -> Result<bool> {
1127 let _lock = TurnLock::take_patiently(&self.path)
1128 .with_context(|| format!("lock {} to renew it", self.path.display()))?;
1129 let Some(mut record) = read_turn(&self.path).filter(|r| r.token == self.token) else {
1130 return Ok(false);
1131 };
1132 record.beat_at = Timestamp::now();
1133 let body = serde_json::to_string(&record).context("serialize turn lease")?;
1134 let tmp = self.path.with_extension(format!("turn.{}.tmp", self.token));
1135 write_atomic(&tmp, &self.path, &body)?;
1136 Ok(true)
1137 }
1138
1139 pub async fn beating<T>(&self, fut: impl std::future::Future<Output = T>) -> Result<T> {
1144 self.beating_every(TURN_BEAT, fut).await
1145 }
1146
1147 async fn beating_every<T>(
1148 &self,
1149 period: Duration,
1150 fut: impl std::future::Future<Output = T>,
1151 ) -> Result<T> {
1152 tokio::pin!(fut);
1153 loop {
1154 match tokio::time::timeout(period, &mut fut).await {
1155 Ok(out) => return Ok(out),
1156 Err(_) => match self.beat() {
1157 Ok(true) => {}
1158 Ok(false) => bail!(
1159 "the turn lease {} was taken over; this turn is stopped",
1160 self.path.display()
1161 ),
1162 Err(e) => tracing::warn!("{e:#}"),
1163 },
1164 }
1165 }
1166 }
1167}
1168
1169impl Drop for TurnLease {
1170 fn drop(&mut self) {
1171 if let Some(_lock) = TurnLock::take_patiently(&self.path) {
1174 if read_turn(&self.path).is_some_and(|r| r.token == self.token) {
1175 let _ = std::fs::remove_file(&self.path);
1176 }
1177 }
1178 }
1179}
1180
1181pub fn begin(store: &Talks, cfg: &Config, repo: PathBuf, agent: Option<&str>) -> Result<Talk> {
1191 begin_with(store, cfg, repo, agent, &Preferred::default())
1192}
1193
1194#[derive(Debug, Default, Clone)]
1198pub struct Preferred {
1199 pub agent: Option<String>,
1201 pub persona: Option<String>,
1203 pub implementers: Option<i64>,
1205}
1206
1207pub fn begin_with(
1214 store: &Talks,
1215 cfg: &Config,
1216 repo: PathBuf,
1217 agent: Option<&str>,
1218 preferred: &Preferred,
1219) -> Result<Talk> {
1220 let repo = repo.canonicalize().unwrap_or(repo);
1223 let head = || -> Result<AgentSpec> {
1226 Ok(agent::pick_chain(
1227 &cfg.agents,
1228 cfg.roles.chatter.as_ref(),
1229 &agent::installed,
1230 "chatter",
1231 )?
1232 .remove(0))
1233 };
1234 let mut fallback = agent.is_none();
1235 let spec = match agent {
1236 Some(id) => agent::pick(&cfg.agents, Some(id), &agent::installed)?,
1237 None => {
1238 match preferred
1239 .agent
1240 .as_deref()
1241 .map(str::trim)
1242 .filter(|id| !id.is_empty())
1243 {
1244 Some(id) => match agent::pick(&cfg.agents, Some(id), &agent::installed) {
1245 Ok(spec) => {
1246 fallback = head().is_ok_and(|head| spec.id == head.id);
1247 spec
1248 }
1249 Err(_) => head()?,
1250 },
1251 None => head()?,
1252 }
1253 }
1254 };
1255 let persona = preferred
1256 .persona
1257 .as_deref()
1258 .and_then(|id| crate::persona::find(&cfg.talk.personas, id))
1259 .filter(|p| !p.is_default())
1260 .map(|p| p.id)
1261 .unwrap_or_default();
1262 let implementers = preferred
1263 .implementers
1264 .and_then(|n| u8::try_from(n).ok())
1265 .and_then(|n| check_implementers(n, cfg).ok())
1266 .unwrap_or(1);
1267
1268 let now = Timestamp::now();
1269 let mut talk = Talk {
1270 posts_read_through: Some(0),
1271 pending_breaks: None,
1272 schema: SCHEMA,
1273 id: new_id(),
1274 repo,
1275 agent: spec.id.clone(),
1276 status: TalkStatus::Open,
1277 turns: Vec::new(),
1278 pending: String::new(),
1279 pending_attachments: Vec::new(),
1280 fallback,
1281 persona,
1282 persona_dirty: false,
1283 implementers,
1284 implementers_dirty: false,
1285 notified: Vec::new(),
1286 created_at: now,
1287 updated_at: now,
1288 seat: SeatState::new(SEAT, &spec.id, crate::rng::entropy()),
1289 };
1290 store.put(&mut talk)?;
1291 Ok(talk)
1292}
1293
1294pub fn record(
1301 talk: &mut Talk,
1302 store: &Talks,
1303 text: &str,
1304 attachments: Vec<Attachment>,
1305) -> Result<String> {
1306 let _guard = store.guard()?;
1314 let Ok(fresh) = store.get(&talk.id) else {
1319 bail!("talk {} was deleted", talk.short());
1320 };
1321 talk.status = fresh.status;
1322 talk.pending = fresh.pending;
1325 talk.pending_breaks = fresh.pending_breaks;
1326 talk.pending_attachments = fresh.pending_attachments;
1327 talk.notified = fresh.notified;
1328 if !talk.status.open() {
1329 bail!(
1330 "talk {} is {} and takes no more turns",
1331 talk.short(),
1332 talk.status.as_str()
1333 );
1334 }
1335 let text = text.trim();
1336 if text.is_empty() && attachments.is_empty() {
1337 bail!("nothing to say");
1338 }
1339 talk.turns.push(Turn {
1340 who: Who::Operator,
1341 body: text.to_owned(),
1342 at: Timestamp::now(),
1343 attachments,
1344 usage: None,
1345 breaks: Some(Vec::new()),
1346 posted_by: None,
1347 });
1348 store.put(talk)?;
1349 Ok(text.to_owned())
1350}
1351
1352pub fn queue(
1354 talk: &mut Talk,
1355 store: &Talks,
1356 text: &str,
1357 attachments: Vec<Attachment>,
1358) -> Result<()> {
1359 queue_keyed(talk, store, text, attachments, None).map(|_| ())
1360}
1361
1362pub fn queue_once(talk: &mut Talk, store: &Talks, text: &str, key: &str) -> Result<bool> {
1367 queue_keyed(talk, store, text, Vec::new(), Some(key))
1368}
1369
1370fn queue_keyed(
1371 talk: &mut Talk,
1372 store: &Talks,
1373 text: &str,
1374 attachments: Vec<Attachment>,
1375 key: Option<&str>,
1376) -> Result<bool> {
1377 let text = text.trim();
1378 if text.is_empty() && attachments.is_empty() {
1379 bail!("nothing to say");
1380 }
1381 let _guard = store.guard()?;
1382 let mut fresh = store
1383 .get(&talk.id)
1384 .with_context(|| format!("talk {} was deleted", talk.short()))?;
1385 if !fresh.status.open() {
1386 bail!(
1387 "talk {} is {} and takes no more turns",
1388 fresh.short(),
1389 fresh.status.as_str()
1390 );
1391 }
1392 if let Some(key) = key {
1393 if fresh.notified.iter().any(|k| k == key) {
1394 *talk = fresh;
1395 return Ok(false);
1396 }
1397 fresh.notified.push(key.to_owned());
1398 }
1399 if !text.is_empty() {
1400 if fresh.pending.is_empty() {
1401 fresh.pending = text.to_owned();
1402 fresh.pending_breaks = Some(Vec::new());
1403 } else {
1404 fresh.pending.push_str("\n\n");
1405 if let Some(b) = fresh.pending_breaks.as_mut() {
1406 b.push(fresh.pending.len());
1407 }
1408 fresh.pending.push_str(text);
1409 }
1410 }
1411 fresh.pending_attachments.extend(attachments);
1412 store.put(&mut fresh)?;
1413 *talk = fresh;
1414 Ok(true)
1415}
1416
1417pub fn post(store: &Talks, talk_id: &str, body: &str, by: &str) -> Result<()> {
1422 let body = body.trim();
1423 if body.is_empty() {
1424 bail!("nothing to post");
1425 }
1426 let _guard = store.guard()?;
1427 let mut fresh = store
1428 .get(talk_id)
1429 .with_context(|| format!("talk {talk_id} does not exist"))?;
1430 if !fresh.status.open() {
1431 bail!(
1432 "talk {} is closed and takes no more messages",
1433 fresh.short()
1434 );
1435 }
1436 fresh.turns.push(Turn {
1437 who: Who::Agent,
1438 body: body.to_owned(),
1439 at: Timestamp::now(),
1440 attachments: Vec::new(),
1441 usage: None,
1442 breaks: None,
1443 posted_by: Some(by.to_owned()),
1444 });
1445 store.put(&mut fresh)
1446}
1447
1448fn posts_read_through(talk: &Talk) -> usize {
1450 talk.posts_read_through.unwrap_or_else(|| {
1451 talk.turns
1452 .iter()
1453 .rposition(|t| t.who != Who::Operator && t.posted_by.is_none())
1454 .map_or(0, |i| i + 1)
1455 })
1456}
1457
1458pub fn posts_since_last_reply(talk: &Talk) -> Option<String> {
1460 let posts: Vec<&Turn> = talk
1461 .turns
1462 .iter()
1463 .skip(posts_read_through(talk))
1464 .filter(|t| t.posted_by.is_some())
1465 .collect();
1466 if posts.is_empty() {
1467 return None;
1468 }
1469 let mut out = String::from("# Posted by a task\n\n");
1470 for t in posts {
1471 out.push_str(&format!(
1472 "Task seat {} posted to this conversation: {}\n\n",
1473 short(t.posted_by.as_deref().unwrap_or_default()),
1474 t.body
1475 ));
1476 }
1477 Some(out)
1478}
1479
1480pub fn drain(talk: &mut Talk, store: &Talks) -> Result<Option<String>> {
1482 let _guard = store.guard()?;
1483 let mut fresh = store
1484 .get(&talk.id)
1485 .with_context(|| format!("talk {} was deleted", talk.short()))?;
1486 if !fresh.status.open() || (fresh.pending.is_empty() && fresh.pending_attachments.is_empty()) {
1487 *talk = fresh;
1488 return Ok(None);
1489 }
1490 let text = std::mem::take(&mut fresh.pending);
1491 let attachments = std::mem::take(&mut fresh.pending_attachments);
1492 let breaks = fresh.pending_breaks.take();
1493 fresh.turns.push(Turn {
1494 who: Who::Operator,
1495 body: text.clone(),
1496 at: Timestamp::now(),
1497 attachments,
1498 usage: None,
1499 breaks,
1500 posted_by: None,
1501 });
1502 store.put(&mut fresh)?;
1503 *talk = fresh;
1504 Ok(Some(text))
1505}
1506
1507pub async fn say(
1510 lease: &TurnLease,
1511 talk: &mut Talk,
1512 store: &Talks,
1513 cfg: &Config,
1514 text: &str,
1515 attachments: Vec<Attachment>,
1516) -> Result<()> {
1517 check_lease(lease, talk)?;
1518 let text = record(talk, store, text, attachments)?;
1519 respond(lease, talk, store, cfg, &text).await
1520}
1521
1522pub async fn respond(
1528 lease: &TurnLease,
1529 talk: &mut Talk,
1530 store: &Talks,
1531 cfg: &Config,
1532 text: &str,
1533) -> Result<()> {
1534 check_lease(lease, talk)?;
1535 lease
1536 .beating(turn(talk, store, cfg, text))
1537 .await
1538 .and_then(|done| done)
1539}
1540
1541fn check_lease(lease: &TurnLease, talk: &Talk) -> Result<()> {
1542 if lease.talk != talk.id {
1543 bail!("the turn lease is for talk {}, not {}", lease.talk, talk.id);
1544 }
1545 if !lease.holds() {
1548 bail!("the turn lease for talk {} is no longer held", talk.short());
1549 }
1550 Ok(())
1551}
1552
1553pub fn close(talk: &mut Talk, store: &Talks) -> Result<()> {
1571 let _guard = store.guard()?;
1572 let mut fresh = store
1573 .get(&talk.id)
1574 .with_context(|| format!("talk {} was deleted", talk.short()))?;
1575 fresh.status = TalkStatus::Closed;
1576 fresh.pending.clear();
1578 fresh.pending_breaks = None;
1579 fresh.pending_attachments.clear();
1580 store.put(&mut fresh)?;
1581 *talk = fresh;
1582 Ok(())
1583}
1584
1585pub fn reopen(talk: &mut Talk, store: &Talks) -> Result<()> {
1596 let _guard = store.guard()?;
1597 let mut fresh = store
1598 .get(&talk.id)
1599 .with_context(|| format!("talk {} was deleted", talk.short()))?;
1600 fresh.status = TalkStatus::Open;
1601 store.put(&mut fresh)?;
1602 *talk = fresh;
1603 Ok(())
1604}
1605
1606pub fn switch_agent(talk: &mut Talk, store: &Talks, spec: &AgentSpec) -> Result<bool> {
1619 let _guard = store.guard()?;
1620 let mut fresh = store
1621 .get(&talk.id)
1622 .with_context(|| format!("talk {} was deleted", talk.short()))?;
1623 if fresh.agent == spec.id {
1624 *talk = fresh;
1625 return Ok(false);
1626 }
1627 let from = std::mem::replace(&mut fresh.agent, spec.id.clone());
1628 fresh.seat = SeatState::new(SEAT, &spec.id, crate::rng::entropy());
1629 fresh.fallback = false;
1631 fresh.turns.push(Turn {
1632 breaks: None,
1633 posted_by: None,
1634 who: Who::Agent,
1635 body: format!("{MAGI_NOTE}agent changed from {from} to {}", spec.id),
1636 at: Timestamp::now(),
1637 attachments: Vec::new(),
1638 usage: None,
1639 });
1640 store.put(&mut fresh)?;
1641 *talk = fresh;
1642 Ok(true)
1643}
1644
1645pub fn switch_persona(talk: &mut Talk, store: &Talks, id: &str) -> Result<bool> {
1653 let id = if id.trim() == crate::persona::DEFAULT_ID {
1654 ""
1655 } else {
1656 id.trim()
1657 };
1658 let _guard = store.guard()?;
1659 let mut fresh = store
1660 .get(&talk.id)
1661 .with_context(|| format!("talk {} was deleted", talk.short()))?;
1662 if fresh.persona == id {
1663 *talk = fresh;
1664 return Ok(false);
1665 }
1666 let from = std::mem::replace(&mut fresh.persona, id.to_owned());
1667 fresh.persona_dirty = true;
1668 let label = |p: &str| {
1669 if p.is_empty() {
1670 crate::persona::DEFAULT_ID.to_owned()
1671 } else {
1672 p.to_owned()
1673 }
1674 };
1675 fresh.turns.push(Turn {
1676 breaks: None,
1677 posted_by: None,
1678 who: Who::Agent,
1679 body: format!(
1680 "{MAGI_NOTE}persona changed from {} to {}",
1681 label(&from),
1682 label(id)
1683 ),
1684 at: Timestamp::now(),
1685 attachments: Vec::new(),
1686 usage: None,
1687 });
1688 store.put(&mut fresh)?;
1689 *talk = fresh;
1690 Ok(true)
1691}
1692
1693pub fn clear_pending(talk: &mut Talk, store: &Talks) -> Result<()> {
1695 let _guard = store.guard()?;
1696 let mut fresh = store
1697 .get(&talk.id)
1698 .with_context(|| format!("talk {} was deleted", talk.short()))?;
1699 fresh.pending.clear();
1700 fresh.pending_breaks = None;
1701 fresh.pending_attachments.clear();
1702 store.put(&mut fresh)?;
1703 *talk = fresh;
1704 Ok(())
1705}
1706
1707pub fn clear_pending_if_matches(
1709 talk: &mut Talk,
1710 store: &Talks,
1711 expected_text: &str,
1712 expected_attachments: &[String],
1713) -> Result<bool> {
1714 let _guard = store.guard()?;
1715 let mut fresh = store
1716 .get(&talk.id)
1717 .with_context(|| format!("talk {} was deleted", talk.short()))?;
1718 if !pending_matches(&fresh, expected_text, expected_attachments) {
1719 *talk = fresh;
1720 return Ok(false);
1721 }
1722 fresh.pending.clear();
1723 fresh.pending_breaks = None;
1724 fresh.pending_attachments.clear();
1725 store.put(&mut fresh)?;
1726 *talk = fresh;
1727 Ok(true)
1728}
1729
1730pub fn edit_pending_text(
1734 talk: &mut Talk,
1735 store: &Talks,
1736 text: &str,
1737 expected_text: &str,
1738 expected_attachments: &[String],
1739) -> Result<bool> {
1740 let _guard = store.guard()?;
1741 let mut fresh = store
1742 .get(&talk.id)
1743 .with_context(|| format!("talk {} was deleted", talk.short()))?;
1744 if !pending_matches(&fresh, expected_text, expected_attachments) {
1745 *talk = fresh;
1746 return Ok(false);
1747 }
1748 fresh.pending = text.trim().to_owned();
1749 fresh.pending_breaks = Some(Vec::new());
1750 store.put(&mut fresh)?;
1751 *talk = fresh;
1752 Ok(true)
1753}
1754
1755fn pending_matches(talk: &Talk, expected_text: &str, expected_attachments: &[String]) -> bool {
1756 talk.pending == expected_text
1757 && talk
1758 .pending_attachments
1759 .iter()
1760 .map(|attachment| &attachment.id)
1761 .eq(expected_attachments.iter())
1762}
1763
1764async fn turn(talk: &mut Talk, store: &Talks, cfg: &Config, text: &str) -> Result<()> {
1771 let prompt_turns = talk.turns.len();
1775 talk.posts_read_through = Some(posts_read_through(talk));
1776 let spec = cfg
1777 .agents
1778 .iter()
1779 .find(|a| a.id == talk.agent)
1780 .with_context(|| {
1781 format!(
1782 "talk {} was opened with agent `{}`, which is no longer in \
1783 the roster; restore it in magi.toml or start a new \
1784 conversation",
1785 talk.short(),
1786 talk.agent
1787 )
1788 })?;
1789
1790 let last_note = attachment_note(
1794 store,
1795 &talk.id,
1796 talk.turns
1797 .last()
1798 .map_or(&[][..], |t| t.attachments.as_slice()),
1799 );
1800
1801 let attachment_paths: Vec<PathBuf> = talk
1807 .turns
1808 .iter()
1809 .flat_map(|t| t.attachments.iter())
1810 .filter_map(|a| store.attachment_path(&talk.id, a))
1811 .collect();
1812
1813 let questions =
1823 crate::run::try_home().map(|home| crate::ask::Questions::at(home.join("questions")));
1824 let consulted = questions
1825 .as_ref()
1826 .is_some_and(|q| crate::consult::pending_consults(q, &talk.id));
1827 let consult_roots: Vec<PathBuf> = match &questions {
1828 Some(q) if consulted => vec![q.root().to_path_buf()],
1829 _ => Vec::new(),
1830 };
1831
1832 let (allow_write, unsandboxed) = turn_access(cfg.talk.allow_write, consulted);
1833
1834 let artifacts = store.artifacts_of(&talk.id);
1835 let operator_turns = talk.turns.iter().filter(|t| t.who == Who::Operator).count();
1838 let stem = format!("turn-{}", operator_turns.max(1));
1839 let cache_dir = cfg.cache_dir();
1842
1843 let mut chain = vec![spec.clone()];
1846 if let Some(choice) = cfg.roles.chatter.as_ref()
1847 && talk.fallback
1848 {
1849 for id in choice.ids() {
1850 if id == talk.agent || chain.iter().any(|s| s.id == id) {
1851 continue;
1852 }
1853 match agent::pick(&cfg.agents, Some(id), &agent::installed) {
1854 Ok(s) => chain.push(s),
1855 Err(e) => tracing::warn!("[roles] chatter: skipping `{id}`: {e:#}"),
1856 }
1857 }
1858 }
1859
1860 let persona = crate::persona::active(&cfg.talk.personas, &talk.persona);
1861 let operator_name = cfg.talk.operator_name();
1862 let persona_update = if talk.persona_dirty {
1863 format!(
1864 "{}\n\n",
1865 crate::persona::update_block_for(persona.as_ref(), operator_name)
1866 )
1867 } else {
1868 String::new()
1869 };
1870
1871 let filing_update = if talk.implementers_dirty {
1874 format!("{}\n\n", filing_update_block(talk.implementers))
1875 } else {
1876 String::new()
1877 };
1878
1879 let mut outcome = None;
1880 let mut fell_back_from: Option<String> = None;
1881 let mut first_try: Option<(String, SeatState)> = None;
1884 for (n, spec) in chain.iter().enumerate() {
1885 if n > 0 {
1886 if first_try.is_none() {
1887 first_try = Some((talk.agent.clone(), talk.seat.clone()));
1888 }
1889 tracing::warn!("chat: falling back from `{}` to `{}`", talk.agent, spec.id);
1890 fell_back_from.get_or_insert_with(|| talk.agent.clone());
1893 talk.agent = spec.id.clone();
1894 talk.seat = SeatState::new(SEAT, &spec.id, crate::rng::entropy());
1895 }
1896 let resuming = agent::has_session(spec.kind, &talk.seat, cfg.graph.sessions);
1897 let first_ever = talk.turns.len() <= 1;
1898 let body = if talk.seat.turns == 0 && first_ever {
1899 format!(
1900 "{}\n\n# Operator\n\n{text}{last_note}",
1901 briefing_for(
1902 &talk.repo,
1903 &cfg.graph.language,
1904 cfg.talk.allow_write,
1905 persona.as_ref(),
1906 operator_name,
1907 talk.implementers
1908 )
1909 )
1910 } else if talk.seat.turns == 0 {
1911 format!(
1914 "{}\n\n{}\n\n# Operator\n\n{text}{last_note}",
1915 briefing_for(
1916 &talk.repo,
1917 &cfg.graph.language,
1918 cfg.talk.allow_write,
1919 persona.as_ref(),
1920 operator_name,
1921 talk.implementers
1922 ),
1923 transcript(talk, store)
1924 )
1925 } else if resuming {
1926 let posts = posts_since_last_reply(talk).unwrap_or_default();
1927 format!("{persona_update}{filing_update}{posts}{text}{last_note}")
1928 } else {
1929 let mut standing = match (&persona, talk.persona_dirty) {
1933 (Some(p), false) => format!("{}\n", crate::persona::section_for(p, operator_name)),
1934 _ => persona_update.clone(),
1935 };
1936 if let (None, Some(n)) = (&persona, operator_name) {
1939 standing.push_str(&format!(
1940 "# Addressing the operator\n{}\n",
1941 crate::persona::addressing(n)
1942 ));
1943 }
1944 if talk.implementers_dirty || talk.implementers != 1 {
1945 standing.push_str(&format!("{}\n\n", filing_update_block(talk.implementers)));
1946 }
1947 format!("{}\n\n{standing}{text}{last_note}", transcript(talk, store))
1948 };
1949 let attempt_stem = if n == 0 {
1950 stem.clone()
1951 } else {
1952 format!("{stem}-{}", spec.id)
1953 };
1954 let inv = Invocation {
1955 cwd: &talk.repo,
1956 prompt: &body,
1957 timeout: turn_timeout(cfg),
1958 allow_write,
1963 unsandboxed,
1964 sessions: cfg.graph.sessions,
1965 artifacts: &artifacts,
1966 stem: &attempt_stem,
1967 run: &talk.id,
1970 node: crate::queue::CHAT_NODE,
1971 cache_dir: cache_dir.as_deref(),
1972 attachments: &attachment_paths,
1973 writable: &consult_roots,
1974 };
1975 let result = agent::invoke(spec, &mut talk.seat, &inv).await;
1976 let advance = agent::chain_advances(&result);
1977 if n == 0 || !advance {
1978 outcome = Some(result);
1979 } else {
1980 tracing::warn!("chat: fallback agent `{}` also failed", spec.id);
1982 }
1983 if !advance {
1984 break;
1985 }
1986 }
1987 if outcome.as_ref().is_some_and(agent::chain_advances) {
1988 if let Some((id, seat)) = first_try {
1991 talk.agent = id;
1992 talk.seat = seat;
1993 fell_back_from = None;
1994 }
1995 }
1996 let outcome = outcome.expect("a chain holds at least one agent");
1997 let note = |why: String| Turn {
1998 breaks: None,
1999 posted_by: None,
2000 who: Who::Agent,
2001 body: format!("{MAGI_NOTE}{why}"),
2002 at: Timestamp::now(),
2003 attachments: Vec::new(),
2004 usage: None,
2005 };
2006 let (reply, failure) = match outcome {
2007 Err(e) => (
2008 note(format!("could not run agent `{}`: {e}", talk.agent)),
2009 Some(format!("could not run agent `{}`: {e}", talk.agent)),
2010 ),
2011 Ok(out) if out.quota_exhausted() => {
2012 let reset = out
2013 .quota
2014 .as_ref()
2015 .and_then(|q| q.reset.clone())
2016 .map_or_else(String::new, |r| format!(" (resets {r})"));
2017 let why = format!(
2018 "agent `{}` is out of quota{reset}; your message is saved, so \
2019 say it again when the window reopens",
2020 talk.agent
2021 );
2022 (note(why.clone()), Some(why))
2023 }
2024 Ok(out) if out.timed_out => {
2025 let why = format!(
2026 "agent `{}` did not answer within {}s; your message is saved",
2027 talk.agent,
2028 turn_timeout(cfg).as_secs()
2029 );
2030 (note(why.clone()), Some(why))
2031 }
2032 Ok(out) if !out.usable() => {
2033 let why = format!(
2034 "agent `{}` produced no answer (exit {}); your message is saved",
2035 talk.agent,
2036 out.exit_code
2037 .map_or_else(|| "unknown".to_owned(), |c| c.to_string())
2038 );
2039 (note(why.clone()), Some(why))
2040 }
2041 Ok(out) => (
2042 Turn {
2043 breaks: None,
2044 posted_by: None,
2045 who: Who::Agent,
2046 body: out.text.trim().to_owned(),
2047 at: Timestamp::now(),
2048 attachments: Vec::new(),
2049 usage: out.context_tokens.map(|context_tokens| TurnUsage {
2052 context_tokens,
2053 agent: talk.agent.clone(),
2054 model: cfg
2055 .agents
2056 .iter()
2057 .find(|a| a.id == talk.agent)
2058 .and_then(|a| a.model.clone()),
2059 }),
2060 },
2061 None,
2062 ),
2063 };
2064
2065 let _guard = store.guard()?;
2077 let Ok(fresh) = store.get(&talk.id) else {
2083 return Ok(());
2084 };
2085 talk.status = fresh.status;
2086 talk.pending = fresh.pending;
2090 talk.pending_breaks = fresh.pending_breaks;
2091 talk.pending_attachments = fresh.pending_attachments;
2092 talk.notified = fresh.notified;
2093 if fresh.turns.len() > talk.turns.len() {
2095 let posted: Vec<Turn> = fresh.turns[talk.turns.len()..]
2096 .iter()
2097 .filter(|t| t.posted_by.is_some())
2098 .cloned()
2099 .collect();
2100 talk.turns.extend(posted);
2101 }
2102 if let Some(from) = fell_back_from.filter(|_| failure.is_none()) {
2103 talk.turns.push(note(format!(
2106 "agent changed from {from} to {} (fallback)",
2107 talk.agent
2108 )));
2109 }
2110 if failure.is_none() {
2113 talk.persona_dirty = false;
2114 talk.implementers_dirty = false;
2115 talk.posts_read_through = Some(prompt_turns);
2116 }
2117 talk.turns.push(reply);
2118 if let Err(put_err) = store.put(talk) {
2119 let lost = talk.turns.pop().expect("just pushed above");
2128 let stash = stash_lost_turn(store, &talk.id, &stem, &lost);
2129 let why = match &stash {
2130 Ok(path) => format!(
2131 "agent `{}` answered, but the reply could not be saved to \
2132 this conversation ({put_err:#}); the raw text was kept at \
2133 {} - your message is saved, ask again",
2134 talk.agent,
2135 path.display()
2136 ),
2137 Err(stash_err) => format!(
2138 "agent `{}` answered, but the reply could not be saved to \
2139 this conversation ({put_err:#}), and it could not be kept \
2140 anywhere else either ({stash_err:#}); your message is \
2141 saved, ask again",
2142 talk.agent
2143 ),
2144 };
2145 talk.turns.push(note(why.clone()));
2146 return match store.put(talk) {
2153 Ok(()) => bail!("{why}"),
2154 Err(note_err) => {
2155 talk.turns.pop();
2175 Err(note_err).context(why)
2176 }
2177 };
2178 }
2179
2180 match failure {
2181 Some(why) => bail!("{why}"),
2182 None => Ok(()),
2183 }
2184}
2185
2186fn transcript(talk: &Talk, store: &Talks) -> String {
2189 let mut out = String::from(
2190 "This conversation cannot resume on the CLI's side, so here is \
2191 everything said so far; answer only the last message.\n",
2192 );
2193 for t in &talk.turns {
2194 let who = match t.who {
2195 Who::Operator => "operator",
2196 Who::Agent if t.body.starts_with(MAGI_NOTE) => "magi",
2197 Who::Agent => "you",
2198 };
2199 out.push_str(&format!("\n## {who}\n\n{}\n", t.body.trim()));
2200 out.push_str(&attachment_note(store, &talk.id, &t.attachments));
2201 }
2202 out
2203}
2204
2205fn attachment_note(store: &Talks, talk_id: &str, attachments: &[Attachment]) -> String {
2210 if attachments.is_empty() {
2211 return String::new();
2212 }
2213 let mut out = String::from(
2214 "\n\nThe operator attached the image(s) below to this message. Open \
2215 and look at each one before you answer.\n",
2216 );
2217 for att in attachments {
2218 if let Some(path) = store.attachment_path(talk_id, att) {
2219 out.push_str(&format!("\n- {} ({})", path.display(), att.mime));
2220 }
2221 }
2222 out.push('\n');
2223 out
2224}
2225
2226pub(crate) fn turn_access(talk_allow_write: bool, consulted: bool) -> (bool, bool) {
2237 (talk_allow_write || consulted, talk_allow_write)
2238}
2239
2240pub fn briefing(repo: &Path, language: &str, allow_write: bool) -> String {
2256 briefing_with(repo, language, allow_write, None, None)
2257}
2258
2259pub fn briefing_with(
2264 repo: &Path,
2265 language: &str,
2266 allow_write: bool,
2267 persona: Option<&crate::persona::Persona>,
2268 operator_name: Option<&str>,
2269) -> String {
2270 briefing_for(repo, language, allow_write, persona, operator_name, 1)
2271}
2272
2273pub const MAX_IMPLEMENTERS: u8 = 3;
2275
2276fn solo_implementers() -> u8 {
2277 1
2278}
2279
2280fn filing_flag(n: u8) -> String {
2283 if n <= 1 {
2284 "--solo".to_owned()
2285 } else {
2286 format!("--implementers {n}")
2287 }
2288}
2289
2290pub fn filing_update_block(n: u8) -> String {
2293 let flag = filing_flag(n);
2294 if n <= 1 {
2295 format!(
2296 "# Task filing update\n\nThe operator changed how many implementers tasks use. \
2297 From now on file with `magi task add {flag} --repo <repo> <instruction>` \
2298 (one implementer, straight into review).\n"
2299 )
2300 } else {
2301 format!(
2302 "# Task filing update\n\nThe operator changed how many implementers tasks use. \
2303 From now on file with `magi task add {flag} --repo <repo> <instruction>` \
2304 ({n} independent implementations compete). Do not pass `--solo` \
2305 together with `--implementers`; drop any earlier `--solo`.\n"
2306 )
2307 }
2308}
2309
2310pub fn check_implementers(n: u8, cfg: &crate::config::Config) -> std::result::Result<u8, String> {
2313 if !(1..=MAX_IMPLEMENTERS).contains(&n) {
2314 return Err(format!(
2315 "implementers must be 1..={MAX_IMPLEMENTERS}, got {n}"
2316 ));
2317 }
2318 if n > 1 {
2319 let mut cfg = cfg.clone();
2320 crate::queue::RunOverrides {
2321 candidates: Some(usize::from(n)),
2322 ..Default::default()
2323 }
2324 .apply(&mut cfg);
2325 cfg.resolve_roles()
2326 .map_err(|e| format!("{n} implementers is not allowed here: {e:#}"))?;
2327 }
2328 Ok(n)
2329}
2330
2331pub fn switch_implementers(talk: &mut Talk, store: &Talks, n: u8) -> Result<bool> {
2334 let _guard = store.guard()?;
2335 let mut fresh = store
2336 .get(&talk.id)
2337 .with_context(|| format!("talk {} was deleted", talk.short()))?;
2338 if fresh.implementers == n {
2339 *talk = fresh;
2340 return Ok(false);
2341 }
2342 let from = std::mem::replace(&mut fresh.implementers, n);
2343 fresh.implementers_dirty = true;
2344 fresh.turns.push(Turn {
2345 breaks: None,
2346 posted_by: None,
2347 who: Who::Agent,
2348 body: format!("{MAGI_NOTE}implementers changed from {from} to {n}"),
2349 at: Timestamp::now(),
2350 attachments: Vec::new(),
2351 usage: None,
2352 });
2353 store.put(&mut fresh)?;
2354 *talk = fresh;
2355 Ok(true)
2356}
2357
2358pub fn briefing_for(
2361 repo: &Path,
2362 language: &str,
2363 allow_write: bool,
2364 persona: Option<&crate::persona::Persona>,
2365 operator_name: Option<&str>,
2366 implementers: u8,
2367) -> String {
2368 let flag = filing_flag(implementers);
2369 let shape = if implementers <= 1 {
2370 "Use --solo: it runs the task through one implementer \
2371 straight into review instead of the usual multi-agent competition, \
2372 which is the right shape for a change this conversation has already \
2373 settled, rather than one still worth several independent takes."
2374 .to_owned()
2375 } else {
2376 format!(
2377 "Use --implementers {implementers}: it has {implementers} \
2378 implementers work on the task independently and compete, which \
2379 is the right shape when several independent takes are worth \
2380 having. Never add --solo to it; the two do not go together."
2381 )
2382 };
2383 let write_policy = if allow_write {
2384 "Write access is enabled for this conversation (`allow_write = \
2385 true`), so you may write files - but only a small, \
2386 already-decided edit the operator names outright in this \
2387 conversation, not an implementation. This is a permission on the \
2388 conversation as a whole, not a property of whichever repository \
2389 it happened to start in: if the operator names a different \
2390 repository for that small edit, the policy allows it there too. \
2391 Your own tool may still confine writes to the repository this \
2392 conversation started in regardless - if a write elsewhere is \
2393 refused, say so plainly rather than working around it. Once you \
2394 have made an edit, say plainly what you edited. Anything bigger, \
2395 or anything still open-ended, still goes through the queue below \
2396 rather than being done here."
2397 } else {
2398 "Do not write files. Implementing a change is not this \
2399 conversation's job; a separate, blind competition of agents does \
2400 that, and a repository this conversation has already edited would \
2401 make their diffs unjudgeable."
2402 };
2403 let mut out = format!(
2404 "You are magi's standing conversation partner for its operator, who \
2405 usually has this open on a phone. Keep replies short: no preamble, \
2406 no restating what they just said.\n\n\
2407 # Repository\n\n{repo}\n\n\
2408 You may look around: read files, run shell commands, search history, \
2409 run tests - whatever answers the question. {write_policy}\n\n\
2410 A short, command-shaped message (\"list\", \"info <id>\", \"show \
2411 3cbf\") is almost always the operator asking you to look something \
2412 up, not an instruction to file - answer it yourself with `magi \
2413 list`, `magi show <id>`, `magi task list`, or the like, the same way \
2414 you would answer any other question in this conversation.\n\n\
2415 # When the operator wants something done\n\n\
2416 Run:\n\n\
2417 magi task add {flag} --repo {repo} <instruction>\n\n\
2418 and tell the operator the task id it prints, so they can follow it \
2419 from the Queue. If it refuses with a duplicate warning (the \
2420 instruction names a branch, commit or pull request that an \
2421 unfinished task, run or PR already owns), do not repeat it with \
2422 --force yourself: tell the operator what it matched and let them \
2423 decide. Write <instruction> so that an implementer who has \
2424 never seen this conversation can act on it alone - it is everything \
2425 they get. {shape}\n\n\
2426 If the operator asks for something in a different repository, \
2427 --repo does not have to be a full path: --repo owner/repo (or just \
2428 repo, when that is unambiguous) is resolved against local checkouts \
2429 the same way `magi repos` lists them. If the command fails because \
2430 nothing matches or more than one checkout shares that name, ask the \
2431 operator which repository they mean (or run `magi repos` yourself \
2432 to see the candidates) rather than guessing.\n\n\
2433 You cannot wait, and you cannot send the operator a message on your \
2434 own: you only speak when they write. A task you file reports back \
2435 into this conversation automatically when it finishes, is held or \
2436 fails, as a message headed \"{notice}\", so never promise to \"tell \
2437 them when it is done\" for anything else.\n\n\
2438 The current state of the code is whatever origin/main holds, not \
2439 whatever a working tree shows: a primary checkout often lags \
2440 upstream, sits on a detached HEAD and carries uncommitted changes. \
2441 Before answering about code, run `git fetch origin` in that \
2442 repository if it is cheap, then read through \
2443 `git show origin/main:<path>` or `git grep <pattern> origin/main`. \
2444 If the working tree differs, say so; if the fetch fails, say that \
2445 too, so the operator knows the answer may be stale.\n\n\
2446 If the operator attached an image (a screenshot, say) that the task \
2447 is about, pass it with `--attach <path>`, using the absolute path \
2448 the turn's attachment note gives; repeat the flag for several. \
2449 `magi task add {flag} --attach <path> <instruction>` copies the \
2450 file into the task, so the implementer receives it. Do not paste the \
2451 path into <instruction> instead: deleting this conversation deletes \
2452 its attachments, and then that path reaches no one.\n",
2453 repo = repo.display(),
2454 notice = crate::prompt::CHAT_TASK_NOTICE_HEADING,
2455 );
2456 out.push_str(&language_note(language));
2457 match (persona, operator_name) {
2458 (Some(p), n) => out.push_str(&crate::persona::section_for(p, n)),
2459 (None, Some(n)) => {
2460 out.push_str("\n# Addressing the operator\n");
2461 out.push_str(&crate::persona::addressing(n));
2462 }
2463 (None, None) => {}
2464 }
2465 out
2466}
2467
2468fn language_note(language: &str) -> String {
2471 if language.trim().is_empty() || language.eq_ignore_ascii_case("en") {
2472 String::new()
2473 } else {
2474 format!("\nHold this conversation in {language}.\n")
2475 }
2476}
2477
2478pub fn tasks_of(queue: &Queue, talk_id: &str) -> Vec<Task> {
2485 let mut tasks: Vec<Task> = queue
2486 .list()
2487 .into_iter()
2488 .filter(|t| matches!(&t.source, Source::Agent { run, .. } if run == talk_id))
2489 .collect();
2490 tasks.sort_unstable_by(|a, b| a.id.cmp(&b.id));
2491 tasks
2492}
2493
2494fn read_path(path: &Path) -> Result<Talk> {
2495 let body = std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;
2496 serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))
2497}
2498
2499const PUT_RETRIES: u32 = 5;
2502
2503fn write_atomic(tmp: &Path, path: &Path, body: &str) -> Result<()> {
2515 let mut last_err = None;
2516 for attempt in 0..PUT_RETRIES {
2517 if attempt > 0 {
2518 std::thread::sleep(Duration::from_millis(20 * u64::from(attempt)));
2519 }
2520 match try_write_atomic(tmp, path, body) {
2521 Ok(()) => return Ok(()),
2522 Err(e) => last_err = Some(e),
2523 }
2524 }
2525 Err(last_err.expect("the loop above always runs at least once"))
2526}
2527
2528fn try_write_atomic(tmp: &Path, path: &Path, body: &str) -> Result<()> {
2529 #[cfg(test)]
2530 if failpoint::take_forced_put_failure() {
2531 bail!("simulated write failure (test)");
2532 }
2533 std::fs::write(tmp, body).with_context(|| format!("write {}", tmp.display()))?;
2534 std::fs::rename(tmp, path).with_context(|| format!("replace {}", path.display()))?;
2535 Ok(())
2536}
2537
2538fn stash_lost_turn(store: &Talks, id: &str, stem: &str, reply: &Turn) -> Result<PathBuf> {
2543 let dir = store.artifacts_of(id);
2544 std::fs::create_dir_all(&dir).with_context(|| format!("create {}", dir.display()))?;
2545 let path = dir.join(format!("{stem}-lost.txt"));
2546 std::fs::write(&path, &reply.body).with_context(|| format!("write {}", path.display()))?;
2547 Ok(path)
2548}
2549
2550#[cfg(test)]
2557mod failpoint {
2558 use std::cell::Cell;
2559
2560 thread_local! {
2561 static FORCE_PUT_FAILURES: Cell<u32> = const { Cell::new(0) };
2562 static FORCE_NO_LINK: Cell<bool> = const { Cell::new(false) };
2563 }
2564
2565 pub(super) fn force_no_link(on: bool) {
2568 FORCE_NO_LINK.with(|c| c.set(on));
2569 }
2570
2571 pub(super) fn no_link_forced() -> bool {
2572 FORCE_NO_LINK.with(Cell::get)
2573 }
2574
2575 pub(super) fn force_put_failures(count: u32) {
2578 FORCE_PUT_FAILURES.with(|c| c.set(count));
2579 }
2580
2581 pub(super) fn take_forced_put_failure() -> bool {
2584 FORCE_PUT_FAILURES.with(|c| {
2585 let n = c.get();
2586 if n == 0 {
2587 false
2588 } else {
2589 c.set(n - 1);
2590 true
2591 }
2592 })
2593 }
2594}
2595
2596fn short(id: &str) -> &str {
2597 id.split('-').next_back().unwrap_or(id)
2598}
2599
2600fn new_id() -> String {
2601 let stamp = jiff::Zoned::now().strftime("%Y%m%d-%H%M%S");
2602 let seed = crate::rng::entropy();
2603 format!("{stamp}-{:04x}", (seed ^ (seed >> 32)) & 0xffff)
2604}
2605
2606fn attachment_ext(mime: &str) -> Option<&'static str> {
2611 match mime {
2612 "image/png" => Some("png"),
2613 "image/jpeg" => Some("jpg"),
2614 "image/gif" => Some("gif"),
2615 "image/webp" => Some("webp"),
2616 _ => None,
2617 }
2618}
2619
2620pub fn valid_attachment_id(id: &str) -> bool {
2625 id.len() == 32
2626 && id
2627 .bytes()
2628 .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
2629}
2630
2631fn new_attachment_id() -> String {
2635 let mut r = crate::rng::SplitMix64::new(crate::rng::entropy());
2636 format!("{:016x}{:016x}", r.next_u64(), r.next_u64())
2637}
2638
2639#[cfg(test)]
2640mod tests {
2641 #[test]
2642 fn turn_access_lifts_the_sandbox_only_for_the_talk_opt_in() {
2643 use super::turn_access;
2644 assert_eq!(turn_access(false, false), (false, false));
2645 assert_eq!(turn_access(true, false), (true, true));
2646 assert_eq!(turn_access(false, true), (true, false));
2648 assert_eq!(turn_access(true, true), (true, true));
2649 }
2650
2651 #[test]
2652 fn the_briefing_points_at_origin_main_not_the_working_tree() {
2653 let b = briefing(Path::new("/r"), "en", false);
2654 assert!(b.contains("origin/main"));
2655 assert!(b.contains("git show origin/main:"));
2656 }
2657 use std::collections::BTreeMap;
2658
2659 use crate::config::{AgentChoice, AgentKind, AgentSpec, Graph};
2660 use crate::queue::{Queue, Source, Task};
2661
2662 use super::*;
2663
2664 fn ctx_agent(id: &str, model: Option<&str>) -> AgentSpec {
2665 AgentSpec {
2666 id: id.to_owned(),
2667 kind: AgentKind::Command,
2668 model: model.map(str::to_owned),
2669 command: Vec::new(),
2670 extra_args: Vec::new(),
2671 env: BTreeMap::new(),
2672 prompt_delivery: None,
2673 }
2674 }
2675
2676 fn ctx_talk(agent: &str, turns: Vec<Turn>) -> Talk {
2677 Talk {
2678 posts_read_through: None,
2679 pending_breaks: None,
2680 schema: SCHEMA,
2681 id: "20260904-014455-ab12".to_owned(),
2682 repo: PathBuf::from("."),
2683 agent: agent.to_owned(),
2684 status: TalkStatus::Open,
2685 turns,
2686 pending: String::new(),
2687 pending_attachments: Vec::new(),
2688 fallback: false,
2689 persona: String::new(),
2690 persona_dirty: false,
2691 implementers: 1,
2692 implementers_dirty: false,
2693 notified: Vec::new(),
2694 created_at: Timestamp::now(),
2695 updated_at: Timestamp::now(),
2696 seat: SeatState::new(SEAT, agent, 1),
2697 }
2698 }
2699
2700 fn reply(body: &str, usage: Option<(u64, &str, Option<&str>)>) -> Turn {
2701 Turn {
2702 breaks: None,
2703 posted_by: None,
2704 who: Who::Agent,
2705 body: body.to_owned(),
2706 at: Timestamp::now(),
2707 attachments: Vec::new(),
2708 usage: usage.map(|(t, a, m)| TurnUsage {
2709 context_tokens: t,
2710 agent: a.to_owned(),
2711 model: m.map(str::to_owned),
2712 }),
2713 }
2714 }
2715
2716 fn ctx_config(windows: &[(&str, u64)]) -> Config {
2717 Config {
2718 agents: vec![
2719 ctx_agent("small", Some("small-model")),
2720 ctx_agent("big", Some("big-model")),
2721 ctx_agent("plain", None),
2722 ],
2723 context_windows: windows.iter().map(|(k, v)| ((*k).to_owned(), *v)).collect(),
2724 ..Config::default()
2725 }
2726 }
2727
2728 #[test]
2729 fn context_usage_computes_percent_and_warns_at_eighty() {
2730 let cfg = ctx_config(&[("small-model", 1000)]);
2731 let at = |tokens| {
2732 let t = ctx_talk(
2733 "small",
2734 vec![reply("hi", Some((tokens, "small", Some("small-model"))))],
2735 );
2736 context_usage(&t, Some(&cfg))
2737 };
2738 let u = at(799);
2739 assert_eq!((u.percent, u.warn, u.window), (Some(79), false, Some(1000)));
2740 let u = at(800);
2741 assert_eq!((u.percent, u.warn), (Some(80), true));
2742 let u = at(1500);
2743 assert_eq!((u.percent, u.warn), (Some(150), true));
2744 assert!(!u.since_switch);
2745 }
2746
2747 #[test]
2748 fn context_usage_is_unknown_without_usage_and_never_looks_back() {
2749 let cfg = ctx_config(&[("small-model", 1000)]);
2750 let t = ctx_talk(
2751 "small",
2752 vec![
2753 reply("old", Some((900, "small", Some("small-model")))),
2754 reply("new", None),
2755 ],
2756 );
2757 let u = context_usage(&t, Some(&cfg));
2758 assert!(u.estimated);
2760 assert_ne!(u.tokens, Some(900));
2761 assert!(u.tokens.is_some());
2762 let t = ctx_talk(
2764 "small",
2765 vec![
2766 reply("old", Some((900, "small", Some("small-model")))),
2767 reply("magi: could not run agent", None),
2768 ],
2769 );
2770 assert_eq!(context_usage(&t, Some(&cfg)).tokens, Some(900));
2771 assert_eq!(
2772 context_usage(&ctx_talk("small", Vec::new()), Some(&cfg)).tokens,
2773 None
2774 );
2775 }
2776
2777 #[test]
2778 fn estimate_counts_chars_both_sides_and_standing_prompt() {
2779 let mut t = ctx_talk("small", vec![reply("abcdefg", None)]);
2780 assert_eq!(estimate_context_tokens(&t, 0), Some(2)); let op = Turn {
2782 who: Who::Operator,
2783 ..reply("abcdefg", None)
2784 };
2785 t.turns.push(op);
2786 assert_eq!(estimate_context_tokens(&t, 0), Some(4));
2787 assert!(
2788 estimate_context_tokens(&t, 700).unwrap() > estimate_context_tokens(&t, 0).unwrap()
2789 );
2790 let ja = ctx_talk("small", vec![reply("日本語日本語日", None)]);
2792 assert_eq!(estimate_context_tokens(&ja, 0), Some(2));
2793 let note = ctx_talk("small", vec![reply("magi: could not run agent", None)]);
2795 assert_eq!(estimate_context_tokens(¬e, 1000), None);
2796 assert_eq!(
2797 estimate_context_tokens(&ctx_talk("small", Vec::new()), 1000),
2798 None
2799 );
2800 }
2801
2802 #[test]
2803 fn context_usage_measured_wins_and_estimate_gets_percent_and_warn() {
2804 let cfg = ctx_config(&[("small-model", 1000)]);
2805 let t = ctx_talk(
2806 "small",
2807 vec![reply(
2808 &"x".repeat(5000),
2809 Some((10, "small", Some("small-model"))),
2810 )],
2811 );
2812 let u = context_usage(&t, Some(&cfg));
2813 assert_eq!((u.tokens, u.estimated), (Some(10), false));
2814 let t = ctx_talk("small", vec![reply(&"x".repeat(5000), None)]);
2815 let u = context_usage(&t, Some(&cfg));
2816 assert!(u.estimated && !u.since_switch);
2817 assert_eq!(u.window, Some(1000));
2818 assert!(u.warn && u.percent.unwrap() >= 80);
2819 let t = ctx_talk("small", vec![reply("hi", None)]);
2820 let u = context_usage(&t, Some(&cfg));
2821 assert!(u.estimated && u.percent.is_some());
2822 }
2823
2824 #[test]
2825 fn context_usage_without_a_window_shows_tokens_only() {
2826 let cfg = ctx_config(&[]);
2827 let t = ctx_talk("plain", vec![reply("hi", Some((5000, "plain", None)))]);
2829 let u = context_usage(&t, Some(&cfg));
2830 assert_eq!(
2831 (u.tokens, u.window, u.percent, u.warn),
2832 (Some(5000), None, None, false)
2833 );
2834 let t = ctx_talk(
2835 "small",
2836 vec![reply("hi", Some((5000, "small", Some("small-model"))))],
2837 );
2838 assert_eq!(context_usage(&t, Some(&cfg)).percent, None);
2839 assert_eq!(context_usage(&t, None).window, None);
2841 }
2842
2843 #[test]
2844 fn context_usage_switching_model_changes_the_denominator() {
2845 let cfg = ctx_config(&[("small-model", 1000), ("big-model", 10_000)]);
2846 let used = reply("hi", Some((900, "small", Some("small-model"))));
2847 let before = context_usage(&ctx_talk("small", vec![used.clone()]), Some(&cfg));
2848 assert_eq!(
2849 (before.percent, before.warn, before.since_switch),
2850 (Some(90), true, false)
2851 );
2852 let after = context_usage(&ctx_talk("big", vec![used]), Some(&cfg));
2855 assert_eq!(after.window, Some(10_000));
2856 assert_eq!(
2857 (after.percent, after.warn, after.since_switch),
2858 (Some(9), false, true)
2859 );
2860 assert_eq!(after.model.as_deref(), Some("big-model"));
2861 }
2862
2863 #[test]
2864 fn a_turn_recorded_before_usage_existed_still_reads() {
2865 let old = r#"{"who":"agent","body":"hi","at":"2026-09-04T01:44:55Z"}"#;
2866 let turn: Turn = serde_json::from_str(old).expect("old turn reads");
2867 assert!(turn.usage.is_none());
2868 let json = serde_json::to_string(&turn).expect("serialize");
2869 assert!(
2870 !json.contains("usage"),
2871 "absent usage is not written: {json}"
2872 );
2873 }
2874
2875 fn store() -> (tempfile::TempDir, Talks) {
2877 let tmp = tempfile::tempdir().expect("tempdir");
2878 let talks = Talks::at(tmp.path().join("talks"));
2879 (tmp, talks)
2880 }
2881
2882 fn mock_agent(dir: &Path, script: &str, env: BTreeMap<String, String>) -> AgentSpec {
2886 let path = dir.join("mock-talk-agent.sh");
2887 std::fs::write(&path, script).expect("write mock");
2888 AgentSpec {
2889 id: "mock".to_owned(),
2890 kind: AgentKind::Command,
2891 model: None,
2892 command: vec!["sh".to_owned(), path.to_string_lossy().into_owned()],
2893 extra_args: Vec::new(),
2894 env,
2895 prompt_delivery: None,
2896 }
2897 }
2898
2899 fn config(spec: AgentSpec) -> Config {
2900 Config {
2901 agents: vec![spec],
2902 graph: Graph {
2903 language: "en".to_owned(),
2904 ..Graph::default()
2905 },
2906 ..Config::default()
2907 }
2908 }
2909
2910 const REPLY: &str = "#!/bin/sh\ncat >/dev/null\nprintf '%s\\n' \"$MOCK_REPLY\"\n";
2912
2913 const BROKEN: &str = "#!/bin/sh\ncat >/dev/null\nexit 3\n";
2915
2916 const ECHO: &str = "#!/bin/sh\ncat\n";
2919
2920 fn env(reply: &str) -> BTreeMap<String, String> {
2921 BTreeMap::from([("MOCK_REPLY".to_owned(), reply.to_owned())])
2922 }
2923
2924 #[test]
2925 fn the_frozen_json_field_names_round_trip_through_disk() {
2926 let (tmp, talks) = store();
2927 let mut talk = Talk {
2928 posts_read_through: None,
2929 pending_breaks: None,
2930 schema: SCHEMA,
2931 id: "20260904-014455-ab12".to_owned(),
2932 repo: tmp.path().to_owned(),
2933 agent: "sonnet".to_owned(),
2934 status: TalkStatus::Open,
2935 turns: Vec::new(),
2936 pending: String::new(),
2937 pending_attachments: Vec::new(),
2938 fallback: false,
2939 persona: String::new(),
2940 persona_dirty: false,
2941 implementers: 1,
2942 implementers_dirty: false,
2943 notified: Vec::new(),
2944 created_at: Timestamp::now(),
2945 updated_at: Timestamp::now(),
2946 seat: SeatState::new(SEAT, "sonnet", 7),
2947 };
2948 talks.put(&mut talk).expect("put");
2949
2950 let raw = std::fs::read_to_string(talks.path_of(&talk.id)).expect("read back");
2951 let v: serde_json::Value = serde_json::from_str(&raw).expect("parse");
2952 for field in [
2953 "schema",
2954 "id",
2955 "repo",
2956 "agent",
2957 "status",
2958 "turns",
2959 "created_at",
2960 "updated_at",
2961 ] {
2962 assert!(v.get(field).is_some(), "missing field `{field}`");
2963 }
2964 assert_eq!(v["schema"], 1);
2965 assert_eq!(v["status"], "open");
2966
2967 let back = talks.get(&talk.id).expect("get");
2968 assert_eq!(back.posts_read_through, None);
2969 assert_eq!(back.id, talk.id);
2970 assert_eq!(back.status, TalkStatus::Open);
2971 }
2972
2973 #[test]
2974 fn opening_a_talk_takes_no_agent_turn() {
2975 let (tmp, talks) = store();
2976 let spec = mock_agent(tmp.path(), BROKEN, BTreeMap::new());
2980 let cfg = config(spec);
2981
2982 let talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
2983 assert_eq!(talk.status, TalkStatus::Open);
2984 assert!(talk.turns.is_empty(), "nothing has been said yet");
2985
2986 let on_disk = talks.get(&talk.id).expect("get");
2987 assert_eq!(on_disk.turns.len(), 0);
2988 }
2989
2990 #[test]
2998 fn chatter_wins_when_set_and_falls_back_to_pick_s_default_order_otherwise() {
2999 let (tmp, talks) = store();
3000 let first_spec = mock_agent(tmp.path(), BROKEN, BTreeMap::new());
3001 let mut chatter_spec = mock_agent(tmp.path(), BROKEN, BTreeMap::new());
3002 chatter_spec.id = "chatter-mock".to_owned();
3003
3004 let mut cfg = Config {
3005 agents: vec![first_spec.clone(), chatter_spec.clone()],
3006 graph: Graph {
3007 language: "en".to_owned(),
3008 ..Graph::default()
3009 },
3010 ..Config::default()
3011 };
3012 cfg.roles.chatter = Some(chatter_spec.id.as_str().into());
3013
3014 let talk =
3015 begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin with chatter set");
3016 assert_eq!(talk.agent, chatter_spec.id, "an explicit chatter must win");
3017
3018 cfg.roles.chatter = None;
3019 let fallback =
3020 begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin with chatter unset");
3021 assert_eq!(
3022 fallback.agent, first_spec.id,
3023 "unset chatter must fall back to agent::pick's own default order"
3024 );
3025 }
3026
3027 #[test]
3030 fn a_talk_recorded_without_attachments_still_reads() {
3031 let (tmp, talks) = store();
3032 let path = talks.path_of("20260904-014455-ab12");
3033 std::fs::create_dir_all(talks.root()).expect("talks dir");
3034 std::fs::write(
3035 &path,
3036 serde_json::json!({
3037 "schema": 1,
3038 "id": "20260904-014455-ab12",
3039 "repo": tmp.path(),
3040 "agent": "sonnet",
3041 "status": "open",
3042 "turns": [
3043 { "who": "operator", "body": "still there?",
3044 "at": Timestamp::now().to_string() },
3045 ],
3046 "created_at": Timestamp::now().to_string(),
3047 "updated_at": Timestamp::now().to_string(),
3048 "seat": SeatState::new(SEAT, "sonnet", 7),
3049 })
3050 .to_string(),
3051 )
3052 .expect("write pre-attachments talk");
3053
3054 let talk = talks.get("20260904-014455-ab12").expect("must still read");
3055 assert!(talk.turns[0].attachments.is_empty());
3056 }
3057
3058 fn lease_store() -> (tempfile::TempDir, Talks, Talks) {
3059 let tmp = tempfile::TempDir::new().expect("tmp");
3060 let root = tmp.path().join("talks");
3061 (tmp, Talks::at(root.clone()), Talks::at(root))
3062 }
3063
3064 #[test]
3065 fn two_starters_on_one_talk_one_wins_and_the_other_is_refused() {
3066 let (_tmp, a, b) = lease_store();
3067 let won = a.claim_turn("t1").expect("claim").expect("first wins");
3068 assert!(
3069 b.claim_turn("t1").expect("claim").is_none(),
3070 "second is refused"
3071 );
3072 assert!(b.turn_held("t1"));
3073 assert!(
3074 b.claim_turn("t2").expect("claim").is_some(),
3075 "other talks are free"
3076 );
3077 drop(won);
3078 }
3079
3080 #[test]
3081 fn a_stale_lease_is_taken_over_and_the_old_guard_cannot_release_it() {
3082 let (_tmp, a, b) = lease_store();
3083 let old = a.claim_turn("t1").expect("claim").expect("held");
3084 let later = Timestamp::now()
3085 .checked_add(jiff::SignedDuration::from_secs(
3086 crate::ask::LEASE_TTL.as_secs() as i64 + 5,
3087 ))
3088 .expect("later");
3089 let new = b
3090 .claim_turn_at("t1", later)
3091 .expect("claim")
3092 .expect("a stale lease is taken over");
3093 drop(old);
3094 assert!(a.turn_held("t1"), "the old guard left the new lease alone");
3095 assert!(new.beat().expect("beat"), "the new owner still beats");
3096 drop(new);
3097 assert!(!a.turn_held("t1"));
3098 }
3099
3100 #[tokio::test]
3101 async fn a_turn_whose_lease_was_taken_over_is_stopped() {
3102 let (_tmp, a, b) = lease_store();
3103 let old = a.claim_turn("t1").expect("claim").expect("held");
3104 let later = Timestamp::now()
3105 .checked_add(jiff::SignedDuration::from_secs(
3106 crate::ask::LEASE_TTL.as_secs() as i64 + 5,
3107 ))
3108 .expect("later");
3109 let _new = b
3110 .claim_turn_at("t1", later)
3111 .expect("claim")
3112 .expect("taken over");
3113 let out = old
3114 .beating_every(Duration::from_millis(10), std::future::pending::<()>())
3115 .await;
3116 assert!(out.is_err(), "the displaced turn must stop, not run on");
3117 }
3118
3119 #[tokio::test]
3120 async fn a_turn_that_finishes_is_returned_and_keeps_its_lease_beating() {
3121 let (_tmp, a, _b) = lease_store();
3122 let lease = a.claim_turn("t1").expect("claim").expect("held");
3123 let out = lease
3124 .beating_every(Duration::from_millis(5), async {
3125 tokio::time::sleep(Duration::from_millis(40)).await;
3126 7
3127 })
3128 .await
3129 .expect("still ours");
3130 assert_eq!(out, 7);
3131 assert!(a.turn_held("t1"));
3132 }
3133
3134 #[test]
3135 fn an_unreadable_lease_counts_as_stale() {
3136 let (_tmp, a, b) = lease_store();
3137 std::fs::create_dir_all(a.root()).expect("dir");
3138 std::fs::write(a.turn_path("t1"), "not json").expect("write");
3139 assert!(!a.turn_held("t1"));
3140 assert!(b.claim_turn("t1").expect("claim").is_some());
3141 }
3142
3143 #[test]
3144 fn without_hard_links_a_claim_is_still_exclusive_and_a_young_placeholder_blocks() {
3145 let (_tmp, a, b) = lease_store();
3146 failpoint::force_no_link(true);
3147 let held = a.claim_turn("t1").expect("claim").expect("first wins");
3148 assert!(b.claim_turn("t1").expect("claim").is_none());
3149 assert!(a.turn_held("t1"));
3150 drop(held);
3151 assert!(!a.turn_held("t1"));
3152 let path = a.turn_path("t1");
3154 assert!(create_exclusive(&path, "").expect("placeholder"));
3155 assert!(b.claim_turn("t1").expect("claim").is_none(), "young: held");
3156 age_file(&path);
3157 assert!(b.claim_turn("t1").expect("claim").is_some(), "old: stale");
3158 let lease = a.turn_path("t2");
3160 let lock = TurnLock::take(&lease).expect("take").expect("lock");
3161 assert!(TurnLock::take(&lease).expect("take").is_none());
3162 drop(lock);
3163 assert!(TurnLock::take(&lease).expect("take").is_some());
3164 failpoint::force_no_link(false);
3165 }
3166
3167 #[test]
3168 fn remove_if_carries_removes_only_the_expected_content() {
3169 let (_tmp, a, _b) = lease_store();
3170 std::fs::create_dir_all(a.root()).expect("dir");
3171 let p = a.root().join("x.turn.lock");
3172 std::fs::write(&p, "mine").expect("write");
3173 assert!(!remove_if_carries(&p, "other"));
3174 assert_eq!(std::fs::read_to_string(&p).expect("kept"), "mine");
3175 assert!(remove_if_carries(&p, "mine"));
3176 assert!(!p.exists());
3177 assert!(!remove_if_carries(&p, "mine"), "absent is not a removal");
3178 }
3179
3180 #[test]
3181 fn a_dropped_lock_does_not_remove_a_lock_taken_over_since() {
3182 let (_tmp, a, _b) = lease_store();
3183 std::fs::create_dir_all(a.root()).expect("dir");
3184 let lease = a.turn_path("t1");
3185 let lock = TurnLock::take(&lease).expect("take").expect("lock");
3186 let path = lock.path.clone();
3187 std::fs::write(&path, "someone-else").expect("replace");
3188 drop(lock);
3189 assert_eq!(
3190 std::fs::read_to_string(&path).expect("kept"),
3191 "someone-else"
3192 );
3193 }
3194
3195 #[test]
3196 fn concurrent_takeovers_of_a_stale_lease_have_one_winner() {
3197 let (_tmp, a, _b) = lease_store();
3198 drop(a.claim_turn("t1").expect("claim").expect("held"));
3199 std::fs::write(
3200 a.turn_path("t1"),
3201 serde_json::to_string(&TurnRecord {
3202 token: "gone".into(),
3203 pid: 1,
3204 beat_at: Timestamp::from_second(1).expect("ts"),
3205 })
3206 .expect("json"),
3207 )
3208 .expect("write");
3209 let wins: Vec<_> = std::thread::scope(|sc| {
3210 let hs: Vec<_> = (0..8)
3211 .map(|_| {
3212 let s = a.clone();
3213 sc.spawn(move || s.claim_turn("t1").expect("claim"))
3214 })
3215 .collect();
3216 hs.into_iter().map(|h| h.join().expect("join")).collect()
3217 });
3218 assert_eq!(wins.iter().filter(|w| w.is_some()).count(), 1);
3219 }
3220
3221 fn age_file(path: &Path) {
3222 let f = std::fs::OpenOptions::new()
3223 .write(true)
3224 .open(path)
3225 .expect("open");
3226 f.set_modified(std::time::SystemTime::now() - std::time::Duration::from_secs(60))
3227 .expect("age");
3228 }
3229
3230 #[test]
3231 fn a_late_taker_of_a_broken_lock_cannot_disturb_its_replacement() {
3232 let (_tmp, a, _b) = lease_store();
3233 let lease = a.turn_path("t1");
3234 let lock = lease.with_extension("turn.lock");
3235 std::fs::create_dir_all(lock.parent().expect("dir")).expect("dir");
3236 std::fs::write(&lock, "t1-dead").expect("dead lock");
3237 age_file(&lock);
3238 let b = TurnLock::take(&lease).expect("take").expect("b wins");
3240 let fresh = std::fs::read_to_string(&lock).expect("read");
3241 assert_eq!(fresh, b.token);
3242 let ticket = std::fs::read_dir(lock.parent().expect("dir"))
3245 .expect("dir")
3246 .flatten()
3247 .map(|e| e.path())
3248 .find(|p| p.to_string_lossy().ends_with(".break.0"))
3249 .expect("ticket");
3250 assert!(!create_exclusive(&ticket, "").expect("ticket"));
3251 assert!(TurnLock::take(&lease).expect("take").is_none());
3252 assert_eq!(std::fs::read_to_string(&lock).expect("read"), fresh);
3253 age_file(&lock);
3255 age_file(&ticket);
3256 std::mem::forget(b);
3257 let c = TurnLock::take(&lease)
3258 .expect("take")
3259 .expect("next generation");
3260 assert_ne!(c.token, fresh);
3261 }
3262
3263 #[test]
3264 fn a_live_ticket_blocks_and_a_stale_one_hands_over_to_the_next_generation() {
3265 let (_tmp, a, _b) = lease_store();
3266 let lease = a.turn_path("t1");
3267 let lock = lease.with_extension("turn.lock");
3268 std::fs::create_dir_all(lock.parent().expect("dir")).expect("dir");
3269 std::fs::write(&lock, "t1-dead").expect("dead lock");
3270 age_file(&lock);
3271 let t0 = lock.with_extension("lock.t1-dead.break.0");
3272 assert!(create_exclusive(&t0, "").expect("ticket"));
3273 assert!(TurnLock::take(&lease).expect("take").is_none());
3275 assert_eq!(std::fs::read_to_string(&lock).expect("read"), "t1-dead");
3276 age_file(&t0);
3278 let c = TurnLock::take(&lease).expect("take").expect("generation 1");
3279 assert_eq!(std::fs::read_to_string(&lock).expect("read"), c.token);
3280 assert!(lock.with_extension("lock.t1-dead.break.1").exists());
3281 assert!(TurnLock::take(&lease).expect("take").is_none());
3282 }
3283
3284 #[test]
3285 fn exhausted_ticket_generations_recover_once_the_sweep_ages_them_out() {
3286 let (_tmp, a, _b) = lease_store();
3287 let lease = a.turn_path("t1");
3288 let lock = lease.with_extension("turn.lock");
3289 std::fs::create_dir_all(lock.parent().expect("dir")).expect("dir");
3290 std::fs::write(&lock, "t1-dead").expect("dead lock");
3291 age_file(&lock);
3292 let tickets: Vec<_> = (0..TICKET_GENERATIONS)
3293 .map(|n| lock.with_extension(format!("lock.t1-dead.break.{n}")))
3294 .collect();
3295 for t in &tickets {
3296 assert!(create_exclusive(t, "").expect("ticket"));
3297 age_file(t);
3298 }
3299 assert!(TurnLock::take(&lease).expect("take").is_none());
3301 assert!(tickets.iter().all(|t| t.exists()));
3302 for t in &tickets {
3304 let f = std::fs::OpenOptions::new()
3305 .write(true)
3306 .open(t)
3307 .expect("open");
3308 f.set_modified(std::time::SystemTime::now() - TICKET_SWEEP_AGE * 2)
3309 .expect("age");
3310 }
3311 assert!(TurnLock::take(&lease).expect("take").is_none());
3312 assert!(TurnLock::take(&lease).expect("take").is_some());
3313 }
3314
3315 #[test]
3316 fn an_aged_empty_lock_is_broken() {
3317 let (_tmp, a, _b) = lease_store();
3318 let lease = a.turn_path("t1");
3319 let lock = lease.with_extension("turn.lock");
3320 std::fs::create_dir_all(lock.parent().expect("dir")).expect("dir");
3321 std::fs::write(&lock, "").expect("empty lock");
3322 age_file(&lock);
3323 assert!(TurnLock::take(&lease).expect("take").is_some());
3324 }
3325
3326 #[test]
3327 fn queued_text_is_durable_combined_and_drained_as_one_operator_turn() {
3328 let (tmp, talks) = store();
3329 let cfg = config(mock_agent(tmp.path(), REPLY, env("reply")));
3330 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
3331
3332 queue(&mut talk, &talks, "first", Vec::new()).expect("queue first");
3333 queue(&mut talk, &talks, "second", Vec::new()).expect("queue second");
3334 let saved = talks.get(&talk.id).expect("reload queued talk");
3335 assert_eq!(saved.pending, "first\n\nsecond");
3336 assert_eq!(saved.pending_breaks, Some(vec!["first\n\n".len()]));
3337 assert!(saved.turns.is_empty(), "a draft is not a transcript turn");
3338
3339 let drained = drain(&mut talk, &talks).expect("drain");
3340 assert_eq!(drained.as_deref(), Some("first\n\nsecond"));
3341 let saved = talks.get(&talk.id).expect("reload drained talk");
3342 assert!(saved.pending.is_empty());
3343 assert_eq!(saved.turns.len(), 1);
3344 assert_eq!(saved.turns[0].body, "first\n\nsecond");
3345 assert_eq!(saved.turns[0].breaks, Some(vec!["first\n\n".len()]));
3346 assert_eq!(saved.pending_breaks, None);
3347 }
3348
3349 #[test]
3350 fn editing_a_queued_draft_preserves_its_attachments_and_rejects_a_stale_snapshot() {
3351 let (tmp, talks) = store();
3352 let cfg = config(mock_agent(tmp.path(), REPLY, env("reply")));
3353 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
3354 let attachment = Attachment {
3355 id: "a".repeat(32),
3356 name: "shot.png".to_owned(),
3357 mime: "image/png".to_owned(),
3358 bytes: 3,
3359 };
3360
3361 queue(&mut talk, &talks, "first", vec![attachment.clone()]).expect("queue");
3362 assert!(
3363 edit_pending_text(
3364 &mut talk,
3365 &talks,
3366 "corrected",
3367 "first",
3368 std::slice::from_ref(&attachment.id),
3369 )
3370 .expect("edit")
3371 );
3372 let saved = talks.get(&talk.id).expect("reload edited draft");
3373 assert_eq!(saved.pending, "corrected");
3374 assert_eq!(saved.pending_attachments, vec![attachment]);
3375
3376 queue(&mut talk, &talks, "later", Vec::new()).expect("queue concurrent draft");
3377 assert!(
3378 !edit_pending_text(
3379 &mut talk,
3380 &talks,
3381 "stale edit",
3382 "corrected",
3383 &["a".repeat(32)],
3384 )
3385 .expect("stale edit is a conflict")
3386 );
3387 assert_eq!(
3388 talks.get(&talk.id).expect("reload after conflict").pending,
3389 "corrected\n\nlater"
3390 );
3391 assert!(
3392 !clear_pending_if_matches(&mut talk, &talks, "corrected", &["a".repeat(32)])
3393 .expect("stale clear is a conflict")
3394 );
3395 assert_eq!(
3396 talks
3397 .get(&talk.id)
3398 .expect("reload after stale clear")
3399 .pending,
3400 "corrected\n\nlater"
3401 );
3402 }
3403
3404 #[tokio::test]
3405 async fn a_reply_save_preserves_pending_accepted_while_the_cli_runs() {
3406 let (tmp, talks) = store();
3407 let slow = "#!/bin/sh\ncat >/dev/null\nsleep 0.1\nprintf reply\n";
3408 let cfg = config(mock_agent(tmp.path(), slow, BTreeMap::new()));
3409 let mut running = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
3410 let id = running.id.clone();
3411 let first = record(&mut running, &talks, "first", Vec::new()).expect("record");
3412
3413 let response_talks = talks.clone();
3414 let response_cfg = cfg.clone();
3415 let reply = tokio::spawn(async move {
3416 respond(
3417 &response_talks.claim_turn(&running.id).unwrap().unwrap(),
3418 &mut running,
3419 &response_talks,
3420 &response_cfg,
3421 &first,
3422 )
3423 .await
3424 });
3425 tokio::time::sleep(std::time::Duration::from_millis(20)).await;
3426
3427 let mut queued = talks.get(&id).expect("queued handle");
3428 queue(&mut queued, &talks, "next", Vec::new()).expect("queue");
3429 reply.await.expect("join").expect("reply");
3430
3431 let saved = talks.get(&id).expect("reload");
3432 assert_eq!(saved.pending, "next");
3433 assert_eq!(saved.pending_breaks, Some(Vec::new()));
3434 assert_eq!(saved.turns.len(), 2, "operator message and reply remain");
3435 }
3436
3437 #[tokio::test]
3438 async fn posts_during_a_resumed_turn_are_replayed_once_even_after_a_reply_save_failure() {
3439 for lose_reply in [false, true] {
3440 let (tmp, talks) = store();
3441 let cfg = config(mock_agent(tmp.path(), ECHO, BTreeMap::new()));
3442 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
3443 say(
3444 &talks.claim_turn(&talk.id).unwrap().unwrap(),
3445 &mut talk,
3446 &talks,
3447 &cfg,
3448 "establish the session",
3449 Vec::new(),
3450 )
3451 .await
3452 .expect("first turn");
3453 assert!(agent::has_session(
3454 AgentKind::Command,
3455 &talk.seat,
3456 cfg.graph.sessions
3457 ));
3458
3459 post(&talks, &talk.id, "already available", "task-earlier").expect("earlier post");
3460 talk = talks.get(&talk.id).expect("reload earlier post");
3461 let ready = tmp.path().join("ready");
3462 let release = tmp.path().join("release");
3463 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";
3464 let slow_cfg = config(mock_agent(
3465 tmp.path(),
3466 slow,
3467 BTreeMap::from([
3468 ("READY".to_owned(), ready.to_string_lossy().into_owned()),
3469 ("RELEASE".to_owned(), release.to_string_lossy().into_owned()),
3470 ]),
3471 ));
3472 let text = record(&mut talk, &talks, "keep going", Vec::new()).expect("record");
3473 let prompt_turns = talk.turns.len();
3474 let id = talk.id.clone();
3475 let response_talks = talks.clone();
3476 let running = tokio::spawn(async move {
3477 respond(
3478 &response_talks.claim_turn(&talk.id).unwrap().unwrap(),
3479 &mut talk,
3480 &response_talks,
3481 &slow_cfg,
3482 &text,
3483 )
3484 .await
3485 });
3486 tokio::time::timeout(std::time::Duration::from_secs(5), async {
3487 while !ready.exists() {
3488 tokio::time::sleep(std::time::Duration::from_millis(10)).await;
3489 }
3490 })
3491 .await
3492 .expect("CLI read its prompt");
3493 post(&talks, &id, "concurrent task result", "task-one").expect("post");
3494 post(&talks, &id, "second task result", "task-two").expect("second post");
3495 if lose_reply {
3496 failpoint::force_put_failures(PUT_RETRIES);
3497 }
3498 std::fs::write(release, "go").expect("release CLI");
3499 let result = running.await.expect("join");
3500 if lose_reply {
3501 assert!(
3502 result
3503 .unwrap_err()
3504 .to_string()
3505 .contains("could not be saved")
3506 );
3507 } else {
3508 result.expect("reply");
3509 }
3510
3511 let mut saved = talks.get(&id).expect("reload");
3512 assert_eq!(saved.posts_read_through, Some(prompt_turns));
3513 assert_eq!(saved.turns[prompt_turns].body, "concurrent task result");
3514 assert_eq!(saved.turns[prompt_turns + 1].body, "second task result");
3515 assert!(posts_since_last_reply(&saved).is_some());
3516 let cfg = config(mock_agent(tmp.path(), ECHO, BTreeMap::new()));
3517 say(
3518 &talks.claim_turn(&id).unwrap().unwrap(),
3519 &mut saved,
3520 &talks,
3521 &cfg,
3522 "read the results",
3523 Vec::new(),
3524 )
3525 .await
3526 .expect("replay turn");
3527 let prompt = &saved.turns.last().unwrap().body;
3528 assert!(prompt.contains("# Posted by a task"), "{prompt}");
3529 assert!(!prompt.contains("already available"), "{prompt}");
3530 assert!(
3531 prompt
3532 .find("concurrent task result")
3533 .expect("first post in prompt")
3534 < prompt
3535 .find("second task result")
3536 .expect("second post in prompt")
3537 );
3538 let mut saved = talks.get(&id).expect("reload after replay");
3539 assert!(posts_since_last_reply(&saved).is_none());
3540 say(
3541 &talks.claim_turn(&id).unwrap().unwrap(),
3542 &mut saved,
3543 &talks,
3544 &cfg,
3545 "continue",
3546 Vec::new(),
3547 )
3548 .await
3549 .expect("next turn");
3550 assert!(!saved.turns.last().unwrap().body.contains("task result"));
3551 }
3552 }
3553
3554 fn counting_agent(dir: &Path, id: &str, body: &str) -> AgentSpec {
3557 let calls = dir.join(format!("{id}.calls"));
3558 let script = format!(
3559 "#!/bin/sh\necho x >> '{}'\n{body}\n",
3560 calls.to_string_lossy()
3561 );
3562 let path = dir.join(format!("mock-{id}.sh"));
3563 std::fs::write(&path, script).expect("write mock");
3564 AgentSpec {
3565 id: id.to_owned(),
3566 kind: AgentKind::Command,
3567 model: None,
3568 command: vec!["sh".to_owned(), path.to_string_lossy().into_owned()],
3569 extra_args: Vec::new(),
3570 env: BTreeMap::new(),
3571 prompt_delivery: None,
3572 }
3573 }
3574
3575 fn calls(dir: &Path, id: &str) -> usize {
3576 std::fs::read_to_string(dir.join(format!("{id}.calls"))).map_or(0, |s| s.lines().count())
3577 }
3578
3579 fn chain_config(specs: Vec<AgentSpec>, ids: &[&str]) -> Config {
3580 let mut cfg = config(specs[0].clone());
3581 cfg.agents = specs;
3582 cfg.roles.chatter = Some(AgentChoice::Chain(
3583 ids.iter().map(|s| (*s).to_owned()).collect(),
3584 ));
3585 cfg
3586 }
3587
3588 #[tokio::test]
3589 async fn a_chatter_chain_falls_back_resends_the_transcript_and_sticks() {
3590 let (tmp, talks) = store();
3591 let a = counting_agent(tmp.path(), "a", "cat >/dev/null\nexit 3");
3592 let b = counting_agent(tmp.path(), "b", "cat");
3593 let cfg = chain_config(vec![a, b], &["a", "b"]);
3594 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
3595 assert_eq!(talk.agent, "a");
3596 post(&talks, &talk.id, "fallback task result", "task").expect("post");
3597 talk = talks.get(&talk.id).expect("reload");
3598
3599 say(
3600 &talks.claim_turn(&talk.id).unwrap().unwrap(),
3601 &mut talk,
3602 &talks,
3603 &cfg,
3604 "hello there",
3605 Vec::new(),
3606 )
3607 .await
3608 .expect("turn");
3609 assert_eq!(calls(tmp.path(), "a"), 1, "each id is tried once");
3610 assert_eq!(calls(tmp.path(), "b"), 1);
3611 assert_eq!(talk.agent, "b", "the switch persists");
3612 assert!(talks.get(&talk.id).unwrap().agent == "b");
3613 let reply = talk.turns.last().unwrap();
3614 assert!(reply.body.contains("hello there"));
3615 assert!(reply.body.contains("fallback task result"));
3616 let saved = talks.get(&talk.id).expect("reload fallback");
3617 assert_eq!(saved.posts_read_through, Some(2));
3618 assert!(posts_since_last_reply(&saved).is_none());
3619 assert!(
3620 reply.body.contains("magi task add --solo"),
3621 "a fresh seat gets the full briefing"
3622 );
3623 assert!(
3624 talk.turns
3625 .iter()
3626 .any(|t| t.body.contains("agent changed from a to b")),
3627 "the switch is noted"
3628 );
3629 }
3630
3631 #[tokio::test]
3632 async fn an_exhausted_chatter_chain_fails_like_a_single_seat_and_stays_put() {
3633 let (tmp, talks) = store();
3634 let a = counting_agent(tmp.path(), "a", "cat >/dev/null\nexit 3");
3635 let b = counting_agent(tmp.path(), "b", "cat >/dev/null\nexit 4");
3636 let cfg = chain_config(vec![a, b], &["a", "b", "a"]);
3637 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
3638
3639 let err = say(
3640 &talks.claim_turn(&talk.id).unwrap().unwrap(),
3641 &mut talk,
3642 &talks,
3643 &cfg,
3644 "hi",
3645 Vec::new(),
3646 )
3647 .await
3648 .expect_err("every agent failed");
3649 assert!(err.to_string().contains("`a`"), "{err:#}");
3650 assert_eq!(calls(tmp.path(), "a"), 1);
3651 assert_eq!(calls(tmp.path(), "b"), 1);
3652 assert_eq!(talk.agent, "a", "an exhausted chain leaves the agent alone");
3653 }
3654
3655 #[test]
3656 fn a_chatter_chain_skips_an_unknown_id_at_begin() {
3657 let (tmp, talks) = store();
3658 let b = counting_agent(tmp.path(), "b", "cat");
3659 let cfg = chain_config(vec![b], &["ghost", "b"]);
3660 let talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
3661 assert_eq!(talk.agent, "b");
3662 }
3663
3664 #[tokio::test]
3665 async fn an_explicit_agent_inside_the_chatter_chain_stays_pinned() {
3666 let (tmp, talks) = store();
3667 let a = counting_agent(tmp.path(), "a", "cat >/dev/null\nexit 3");
3668 let b = counting_agent(tmp.path(), "b", "cat");
3669 let cfg = chain_config(vec![a, b], &["a", "b"]);
3670 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), Some("a")).expect("begin");
3671 say(
3672 &talks.claim_turn(&talk.id).unwrap().unwrap(),
3673 &mut talk,
3674 &talks,
3675 &cfg,
3676 "hi",
3677 Vec::new(),
3678 )
3679 .await
3680 .expect_err("a alone, and it fails");
3681 assert_eq!(calls(tmp.path(), "b"), 0);
3682 assert_eq!(talk.agent, "a");
3683 }
3684
3685 #[tokio::test]
3686 async fn an_explicit_agent_does_not_borrow_the_chatter_chain() {
3687 let (tmp, talks) = store();
3688 let a = counting_agent(tmp.path(), "a", "cat >/dev/null\nexit 3");
3689 let b = counting_agent(tmp.path(), "b", "cat");
3690 let c = counting_agent(tmp.path(), "c", "cat >/dev/null\nexit 3");
3691 let cfg = chain_config(vec![a, b, c], &["a", "b"]);
3692 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), Some("c")).expect("begin");
3693 say(
3694 &talks.claim_turn(&talk.id).unwrap().unwrap(),
3695 &mut talk,
3696 &talks,
3697 &cfg,
3698 "hi",
3699 Vec::new(),
3700 )
3701 .await
3702 .expect_err("c alone, and it fails");
3703 assert_eq!(calls(tmp.path(), "b"), 0);
3704 }
3705
3706 #[test]
3707 fn briefing_names_the_operator_with_or_without_a_persona() {
3708 let plain = briefing(Path::new("/repo"), "en", false);
3709 let named = briefing_with(Path::new("/repo"), "en", false, None, Some("Commander"));
3710 assert!(named.starts_with(&plain));
3711 assert!(named.contains("# Addressing the operator"));
3712 assert!(named.contains("\"Commander\""));
3713 let rei = crate::persona::builtin_catalog()
3714 .into_iter()
3715 .find(|p| p.id == "rei")
3716 .expect("rei");
3717 let with = briefing_with(
3718 Path::new("/repo"),
3719 "en",
3720 false,
3721 Some(&rei),
3722 Some("Commander"),
3723 );
3724 assert!(with.contains("\"Commander\""));
3725 assert!(!with.contains("# Addressing the operator"));
3726 }
3727
3728 #[test]
3729 fn briefing_carries_a_persona_section_only_when_one_is_chosen() {
3730 let plain = briefing(Path::new("/repo"), "en", false);
3731 assert_eq!(
3732 plain,
3733 briefing_with(Path::new("/repo"), "en", false, None, None)
3734 );
3735 assert!(!plain.contains("Persona"));
3736 let rei = crate::persona::builtin_catalog()
3737 .into_iter()
3738 .find(|p| p.id == "rei")
3739 .expect("rei");
3740 let with = briefing_with(Path::new("/repo"), "en", false, Some(&rei), None);
3741 assert!(with.starts_with(&plain), "the plain briefing is untouched");
3742 assert!(with.contains("# Persona (tone only)"));
3743 assert!(with.contains("TONE ONLY"));
3744 assert!(with.contains("task ids"));
3745 assert!(with.contains("write policy"));
3746 assert!(with.contains("`magi task add`"));
3747 assert!(with.contains("Rei Ayanami"));
3748 }
3749
3750 #[test]
3751 fn a_talk_written_before_personas_still_loads() {
3752 let (tmp, talks) = store();
3753 let spec = mock_agent(tmp.path(), ECHO, BTreeMap::new());
3754 let cfg = config(spec);
3755 let talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
3756 let path = talks.root.join(format!("{}.json", talk.id));
3757 let mut v: serde_json::Value =
3758 serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
3759 v.as_object_mut().unwrap().remove("persona");
3760 v.as_object_mut().unwrap().remove("persona_dirty");
3761 std::fs::write(&path, v.to_string()).unwrap();
3762 let loaded = talks.get(&talk.id).expect("old record loads");
3763 assert_eq!(loaded.persona, "");
3764 assert!(!loaded.persona_dirty);
3765 }
3766
3767 #[test]
3768 fn the_briefing_files_with_solo_or_the_chosen_implementer_count() {
3769 let repo = Path::new("/repo");
3770 let solo = briefing_for(repo, "", false, None, None, 1);
3771 assert_eq!(solo, briefing(repo, "", false));
3772 assert!(solo.contains("magi task add --solo --repo"));
3773 assert!(solo.contains("magi task add --solo --attach"));
3774 for n in [2u8, 3] {
3775 let b = briefing_for(repo, "", false, None, None, n);
3776 assert!(
3777 b.contains(&format!("magi task add --implementers {n} --repo")),
3778 "{b}"
3779 );
3780 assert!(b.contains(&format!("magi task add --implementers {n} --attach")));
3781 assert!(!b.contains("task add --solo"), "{b}");
3782 assert!(!b.contains("Use --solo"), "{b}");
3783 }
3784 }
3785
3786 #[test]
3787 fn begin_with_applies_remembered_choices_and_drops_unfit_ones_alone() {
3788 let (tmp, talks) = store();
3789 let first = mock_agent(tmp.path(), ECHO, BTreeMap::new());
3790 let mut second = first.clone();
3791 second.id = "second".to_owned();
3792 let mut cfg = config(first.clone());
3793 cfg.agents.push(second.clone());
3794 let open = |p: &Preferred| {
3795 begin_with(&talks, &cfg, tmp.path().to_owned(), None, p).expect("begin")
3796 };
3797
3798 let talk = open(&Preferred {
3799 agent: Some("second".into()),
3800 persona: Some("rei".into()),
3801 implementers: Some(i64::from(check_implementers(3, &cfg).unwrap_or(1))),
3802 });
3803 assert_eq!(talk.agent, "second");
3804 assert!(
3805 !talk.fallback,
3806 "a remembered non-head agent is an explicit choice"
3807 );
3808 assert_eq!(talk.persona, "rei");
3809 assert_eq!(talk.implementers, check_implementers(3, &cfg).unwrap_or(1));
3810 assert!(!talk.persona_dirty && !talk.implementers_dirty);
3811
3812 let head = open(&Preferred {
3814 agent: Some(first.id.clone()),
3815 ..Preferred::default()
3816 });
3817 assert!(head.fallback);
3818
3819 for implementers in [0, 4, -1, 1000] {
3821 let t = open(&Preferred {
3822 agent: Some("gone".into()),
3823 persona: Some("no-such-persona".into()),
3824 implementers: Some(implementers),
3825 });
3826 assert_eq!(t.agent, first.id);
3827 assert!(t.fallback);
3828 assert_eq!(t.persona, "");
3829 assert_eq!(t.implementers, 1);
3830 }
3831
3832 let t = open(&Preferred {
3834 agent: Some("second".into()),
3835 persona: Some("default".into()),
3836 implementers: Some(9),
3837 });
3838 assert_eq!(
3839 (t.agent.as_str(), t.persona.as_str(), t.implementers),
3840 ("second", "", 1)
3841 );
3842
3843 let strict = begin_with(
3845 &talks,
3846 &cfg,
3847 tmp.path().to_owned(),
3848 Some("first-unknown"),
3849 &Preferred {
3850 agent: Some("second".into()),
3851 ..Preferred::default()
3852 },
3853 );
3854 assert!(strict.is_err());
3855 }
3856
3857 #[test]
3858 fn remembered_agent_can_open_when_the_chatter_chain_cannot_resolve() {
3859 let (tmp, talks) = store();
3860 let spec = mock_agent(tmp.path(), ECHO, BTreeMap::new());
3861 let cfg = chain_config(vec![spec.clone()], &["missing-chatter"]);
3864 assert!(begin(&talks, &cfg, tmp.path().to_owned(), None).is_err());
3865 let talk = begin_with(
3866 &talks,
3867 &cfg,
3868 tmp.path().to_owned(),
3869 None,
3870 &Preferred {
3871 agent: Some(spec.id.clone()),
3872 ..Preferred::default()
3873 },
3874 )
3875 .expect("a valid remembered agent does not require a default chain");
3876 assert_eq!(talk.agent, spec.id);
3877 assert!(!talk.fallback);
3878 assert_eq!(talks.get(&talk.id).unwrap().agent, spec.id);
3879 assert!(
3880 begin_with(
3881 &talks,
3882 &cfg,
3883 tmp.path().to_owned(),
3884 None,
3885 &Preferred {
3886 agent: Some("missing-preference".into()),
3887 ..Preferred::default()
3888 },
3889 )
3890 .is_err()
3891 );
3892 }
3893
3894 #[test]
3895 fn implementers_are_validated_and_old_records_load_as_solo() {
3896 let (tmp, talks) = store();
3897 let cfg = config(mock_agent(tmp.path(), ECHO, BTreeMap::new()));
3898 assert_eq!(check_implementers(1, &cfg), Ok(1));
3899 assert_eq!(check_implementers(3, &cfg), Ok(3));
3900 assert!(check_implementers(0, &cfg).is_err());
3901 assert!(check_implementers(4, &cfg).is_err());
3902 let mut empty = cfg.clone();
3903 empty.agents.clear();
3904 assert!(check_implementers(2, &empty).is_err());
3905
3906 let talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
3907 let path = talks.path_of(&talk.id);
3908 let mut v: serde_json::Value =
3909 serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
3910 v.as_object_mut().unwrap().remove("implementers");
3911 v.as_object_mut().unwrap().remove("implementers_dirty");
3912 std::fs::write(&path, v.to_string()).unwrap();
3913 let loaded = talks.get(&talk.id).expect("load");
3914 assert_eq!(loaded.implementers, 1);
3915 assert!(!loaded.implementers_dirty);
3916 }
3917
3918 #[tokio::test]
3919 async fn an_implementers_switch_is_noted_once_and_kept_across_a_failed_turn() {
3920 let (tmp, talks) = store();
3921 let spec = mock_agent(tmp.path(), ECHO, BTreeMap::new());
3922 let cfg = config(spec);
3923 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
3924 let lease = talks.claim_turn(&talk.id).unwrap().unwrap();
3925 say(&lease, &mut talk, &talks, &cfg, "hello", Vec::new())
3926 .await
3927 .expect("first turn");
3928
3929 assert!(switch_implementers(&mut talk, &talks, 2).expect("switch"));
3930 assert!(!switch_implementers(&mut talk, &talks, 2).expect("same"));
3931 assert!(talk.implementers_dirty);
3932 say(&lease, &mut talk, &talks, &cfg, "next", Vec::new())
3933 .await
3934 .expect("turn");
3935 let prompt = &talk.turns.last().unwrap().body;
3936 assert!(prompt.contains("# Task filing update"), "{prompt}");
3937 assert!(prompt.contains("--implementers 2"));
3938 assert!(!talk.implementers_dirty, "cleared after a successful turn");
3939
3940 say(&lease, &mut talk, &talks, &cfg, "again", Vec::new())
3941 .await
3942 .expect("turn");
3943 assert!(
3944 !talk
3945 .turns
3946 .last()
3947 .unwrap()
3948 .body
3949 .contains("# Task filing update")
3950 );
3951
3952 let mut no_sessions = cfg.clone();
3954 no_sessions.graph.sessions = false;
3955 say(&lease, &mut talk, &talks, &no_sessions, "one", Vec::new())
3956 .await
3957 .expect("turn");
3958 say(&lease, &mut talk, &talks, &no_sessions, "two", Vec::new())
3959 .await
3960 .expect("turn");
3961 assert!(talk.turns.last().unwrap().body.contains("--implementers 2"));
3962 }
3963
3964 #[tokio::test]
3965 async fn a_persona_switch_notes_marks_dirty_and_updates_the_next_turn_once() {
3966 let (tmp, talks) = store();
3967 let spec = mock_agent(tmp.path(), ECHO, BTreeMap::new());
3968 let cfg = config(spec);
3969 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
3970 let lease = talks.claim_turn(&talk.id).unwrap().unwrap();
3971 say(&lease, &mut talk, &talks, &cfg, "hello", Vec::new())
3972 .await
3973 .expect("first turn");
3974 assert!(!talk.turns[1].body.contains("Persona"));
3975
3976 assert!(switch_persona(&mut talk, &talks, "misato").expect("switch"));
3977 assert!(!switch_persona(&mut talk, &talks, "misato").expect("same"));
3978 assert!(talk.persona_dirty);
3979 assert!(talk.turns.last().unwrap().body.contains("persona changed"));
3980
3981 say(&lease, &mut talk, &talks, &cfg, "next", Vec::new())
3982 .await
3983 .expect("turn");
3984 let prompt = &talk.turns.last().unwrap().body;
3985 assert!(prompt.contains("# Persona update"), "{prompt}");
3986 assert!(prompt.contains("Misato Katsuragi"));
3987 assert!(!talk.persona_dirty, "cleared after a successful turn");
3988
3989 say(&lease, &mut talk, &talks, &cfg, "again", Vec::new())
3990 .await
3991 .expect("turn");
3992 assert!(!talk.turns.last().unwrap().body.contains("# Persona update"));
3993
3994 assert!(switch_persona(&mut talk, &talks, "default").expect("back"));
3995 assert_eq!(talk.persona, "");
3996 say(&lease, &mut talk, &talks, &cfg, "plain", Vec::new())
3997 .await
3998 .expect("turn");
3999 assert!(
4000 talk.turns
4001 .last()
4002 .unwrap()
4003 .body
4004 .contains("turned the persona off")
4005 );
4006
4007 assert!(switch_persona(&mut talk, &talks, "rei").expect("rei"));
4009 let mut no_sessions = cfg.clone();
4010 no_sessions.graph.sessions = false;
4011 say(&lease, &mut talk, &talks, &no_sessions, "one", Vec::new())
4012 .await
4013 .expect("turn");
4014 say(&lease, &mut talk, &talks, &no_sessions, "two", Vec::new())
4015 .await
4016 .expect("turn");
4017 let last = &talk.turns.last().unwrap().body;
4018 assert!(!talk.persona_dirty);
4019 assert!(last.contains("# Persona (tone only)"), "{last}");
4020 assert!(last.contains("Rei Ayanami"));
4021 }
4022
4023 #[tokio::test]
4024 async fn the_first_turn_carries_the_briefing_and_later_turns_do_not() {
4025 let (tmp, talks) = store();
4026 let spec = mock_agent(tmp.path(), ECHO, BTreeMap::new());
4027 let cfg = config(spec);
4028 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4029
4030 say(
4031 &talks.claim_turn(&talk.id).unwrap().unwrap(),
4032 &mut talk,
4033 &talks,
4034 &cfg,
4035 "what does the queue module do?",
4036 Vec::new(),
4037 )
4038 .await
4039 .expect("first turn");
4040 let first_prompt = &talk.turns[1].body;
4041 assert!(first_prompt.contains("magi task add --solo"));
4042 assert!(first_prompt.contains("what does the queue module do?"));
4043
4044 say(
4045 &talks.claim_turn(&talk.id).unwrap().unwrap(),
4046 &mut talk,
4047 &talks,
4048 &cfg,
4049 "and how is it locked?",
4050 Vec::new(),
4051 )
4052 .await
4053 .expect("second turn");
4054 let second_prompt = &talk.turns[3].body;
4055 assert!(
4056 !second_prompt.contains("magi task add --solo"),
4057 "the briefing is sent once, not on every turn: {second_prompt}"
4058 );
4059 assert!(second_prompt.contains("and how is it locked?"));
4060 }
4061
4062 #[tokio::test]
4063 async fn switching_agent_resets_the_seat_notes_it_and_resends_the_transcript() {
4064 let (tmp, talks) = store();
4065 let a = mock_agent(tmp.path(), ECHO, BTreeMap::new());
4066 let mut b = a.clone();
4067 b.id = "other".to_owned();
4068 let mut cfg = config(a.clone());
4069 cfg.agents.push(b.clone());
4070 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), Some(&a.id)).expect("begin");
4071 say(
4072 &talks.claim_turn(&talk.id).unwrap().unwrap(),
4073 &mut talk,
4074 &talks,
4075 &cfg,
4076 "remember the walrus",
4077 Vec::new(),
4078 )
4079 .await
4080 .expect("first turn");
4081 let old_session = talk.seat.claude_session.clone();
4082 assert_eq!(talk.seat.turns, 1);
4083
4084 assert!(switch_agent(&mut talk, &talks, &b).expect("switch"));
4085 assert_eq!(talk.agent, "other");
4086 assert_eq!(talk.seat.turns, 0);
4087 assert_eq!(talk.seat.agent, "other");
4088 assert_ne!(talk.seat.claude_session, old_session);
4089 let note = talk.turns.last().expect("note");
4090 assert_eq!(note.who, Who::Agent);
4091 assert!(note.body.starts_with(MAGI_NOTE), "{}", note.body);
4092 assert!(note.body.contains("changed from"), "{}", note.body);
4093 assert_eq!(talks.get(&talk.id).expect("reload").agent, "other");
4094
4095 let before = talk.turns.len();
4096 assert!(!switch_agent(&mut talk, &talks, &b).expect("same agent"));
4097 assert_eq!(talk.turns.len(), before, "a no-op writes no note");
4098
4099 say(
4100 &talks.claim_turn(&talk.id).unwrap().unwrap(),
4101 &mut talk,
4102 &talks,
4103 &cfg,
4104 "what did I say?",
4105 Vec::new(),
4106 )
4107 .await
4108 .expect("turn after switch");
4109 let prompt = &talk.turns.last().expect("reply").body;
4110 assert!(prompt.contains("remember the walrus"), "{prompt}");
4111 assert!(prompt.contains("## magi"), "{prompt}");
4112 assert!(prompt.contains("what did I say?"), "{prompt}");
4113 }
4114
4115 #[tokio::test]
4116 async fn say_appends_the_operator_turn_then_the_agent_turn() {
4117 let (tmp, talks) = store();
4118 let spec = mock_agent(tmp.path(), REPLY, env("go ahead"));
4119 let cfg = config(spec);
4120 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4121
4122 say(
4123 &talks.claim_turn(&talk.id).unwrap().unwrap(),
4124 &mut talk,
4125 &talks,
4126 &cfg,
4127 "can I rename this function?",
4128 Vec::new(),
4129 )
4130 .await
4131 .expect("say");
4132
4133 assert_eq!(talk.turns.len(), 2);
4134 assert_eq!(talk.turns[0].who, Who::Operator);
4135 assert_eq!(talk.turns[0].body, "can I rename this function?");
4136 assert_eq!(talk.turns[1].who, Who::Agent);
4137 assert_eq!(talk.turns[1].body, "go ahead");
4138 assert_eq!(talks.get(&talk.id).expect("get").turns, talk.turns);
4139 }
4140
4141 #[tokio::test]
4142 async fn a_failed_turn_keeps_the_operator_message_and_says_what_happened() {
4143 let (tmp, talks) = store();
4144 let spec = mock_agent(tmp.path(), BROKEN, BTreeMap::new());
4145 let cfg = config(spec);
4146 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4147
4148 talk.posts_read_through = None;
4149 talks.put(&mut talk).expect("save old-format boundary");
4150 post(&talks, &talk.id, "unread task result", "task").expect("post");
4151 talk = talks.get(&talk.id).expect("reload");
4152
4153 let err = say(
4154 &talks.claim_turn(&talk.id).unwrap().unwrap(),
4155 &mut talk,
4156 &talks,
4157 &cfg,
4158 "check the tests",
4159 Vec::new(),
4160 )
4161 .await
4162 .expect_err("a turn with no answer is an error");
4163 assert!(err.to_string().contains("no answer"), "{err}");
4164
4165 let on_disk = talks.get(&talk.id).expect("get");
4166 assert_eq!(on_disk.turns.len(), 3);
4167 assert_eq!(on_disk.posts_read_through, Some(0));
4168 assert!(
4169 posts_since_last_reply(&on_disk)
4170 .unwrap()
4171 .contains("unread task result")
4172 );
4173 assert_eq!(on_disk.turns[1].body, "check the tests");
4174 let note = &on_disk.turns[2];
4175 assert_eq!(note.who, Who::Agent);
4176 assert!(note.body.starts_with(MAGI_NOTE), "{}", note.body);
4177 assert!(note.body.contains("your message is saved"));
4178 }
4179
4180 #[tokio::test]
4186 async fn a_passing_write_failure_while_saving_the_reply_does_not_lose_it() {
4187 let (tmp, talks) = store();
4188 let spec = mock_agent(tmp.path(), REPLY, env("go ahead"));
4189 let cfg = config(spec);
4190 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4191
4192 let text =
4193 record(&mut talk, &talks, "can I rename this function?", Vec::new()).expect("record");
4194 failpoint::force_put_failures(PUT_RETRIES - 1);
4197 respond(
4198 &talks.claim_turn(&talk.id).unwrap().unwrap(),
4199 &mut talk,
4200 &talks,
4201 &cfg,
4202 &text,
4203 )
4204 .await
4205 .expect("respond must survive a write failure its own retries can outlast");
4206
4207 assert_eq!(talk.turns.len(), 2);
4208 assert_eq!(talk.turns[1].who, Who::Agent);
4209 assert_eq!(talk.turns[1].body, "go ahead");
4210 let on_disk = talks.get(&talk.id).expect("get");
4211 assert_eq!(
4212 on_disk.turns, talk.turns,
4213 "the reply must reach disk despite the early write failures"
4214 );
4215 }
4216
4217 #[tokio::test]
4223 async fn a_persistent_write_failure_while_saving_the_reply_is_never_silent() {
4224 let (tmp, talks) = store();
4225 let spec = mock_agent(tmp.path(), REPLY, env("go ahead"));
4226 let cfg = config(spec);
4227 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4228
4229 let text = record(&mut talk, &talks, "check the tests", Vec::new()).expect("record");
4230 failpoint::force_put_failures(PUT_RETRIES);
4235 let err = respond(
4236 &talks.claim_turn(&talk.id).unwrap().unwrap(),
4237 &mut talk,
4238 &talks,
4239 &cfg,
4240 &text,
4241 )
4242 .await
4243 .expect_err("a reply that cannot be saved must be reported, not swallowed");
4244 assert!(err.to_string().contains("could not be saved"), "{err}");
4245
4246 let on_disk = talks.get(&talk.id).expect("get");
4247 assert_eq!(
4248 on_disk.turns.len(),
4249 2,
4250 "the operator turn plus a visible note"
4251 );
4252 assert_eq!(on_disk.turns[0].body, "check the tests");
4253 let note = &on_disk.turns[1];
4254 assert_eq!(note.who, Who::Agent);
4255 assert!(note.body.starts_with(MAGI_NOTE), "{}", note.body);
4256 assert!(
4257 note.body.contains("could not be saved"),
4258 "the operator must be told the reply is missing, not left staring \
4259 at a gap with no explanation: {}",
4260 note.body
4261 );
4262 assert_eq!(
4263 talk.turns, on_disk.turns,
4264 "the in-memory talk must match what actually landed on disk"
4265 );
4266
4267 let artifacts = talks.artifacts_of(&talk.id);
4270 let stash = std::fs::read_dir(&artifacts)
4271 .expect("artifacts dir")
4272 .filter_map(|e| e.ok())
4273 .find(|e| e.file_name().to_string_lossy().ends_with("-lost.txt"))
4274 .expect("a stash file for the lost reply");
4275 let stashed = std::fs::read_to_string(stash.path()).expect("read stash");
4276 assert_eq!(stashed, "go ahead");
4277
4278 assert_eq!(
4286 on_disk.seat.turns, 1,
4287 "the note's write must carry the turn the CLI actually took"
4288 );
4289 assert_eq!(
4290 on_disk.seat.claude_session, talk.seat.claude_session,
4291 "the session id handed to the CLI must survive the failed reply"
4292 );
4293 assert_eq!(on_disk.seat.captured_session, talk.seat.captured_session);
4294 assert!(
4295 agent::has_session(AgentKind::Command, &on_disk.seat, cfg.graph.sessions),
4296 "the next turn must resume, not open the same session id twice"
4297 );
4298 }
4299
4300 #[tokio::test]
4305 async fn a_write_failure_that_also_loses_the_note_still_reports_it() {
4306 let (tmp, talks) = store();
4307 let spec = mock_agent(tmp.path(), REPLY, env("go ahead"));
4308 let cfg = config(spec);
4309 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4310
4311 let text = record(&mut talk, &talks, "check the tests", Vec::new()).expect("record");
4312 failpoint::force_put_failures(PUT_RETRIES * 2);
4315 let err = respond(
4316 &talks.claim_turn(&talk.id).unwrap().unwrap(),
4317 &mut talk,
4318 &talks,
4319 &cfg,
4320 &text,
4321 )
4322 .await
4323 .expect_err("neither the reply nor the note could be saved");
4324 assert!(err.to_string().contains("could not be saved"), "{err}");
4325
4326 assert_eq!(talk.turns.len(), 1, "only the operator's own turn");
4327 let on_disk = talks.get(&talk.id).expect("get");
4328 assert_eq!(on_disk.turns.len(), 1);
4329
4330 assert_eq!(
4340 on_disk.seat.turns, 0,
4341 "an unwritable file cannot record the turn the CLI took"
4342 );
4343 assert_eq!(
4344 talk.seat.turns, 1,
4345 "the in-memory seat still reports the turn the CLI actually took"
4346 );
4347 assert_eq!(
4348 on_disk.seat.claude_session, talk.seat.claude_session,
4349 "the session id was minted at `begin` and never changes here"
4350 );
4351 }
4352
4353 #[tokio::test]
4357 async fn attachments_reach_the_prompt_and_an_empty_body_is_still_a_turn() {
4358 let (tmp, talks) = store();
4359 let spec = mock_agent(tmp.path(), ECHO, BTreeMap::new());
4360 let cfg = config(spec);
4361 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4362
4363 let att = talks
4364 .put_attachment(
4365 &talk.id,
4366 "image/png",
4367 "screenshot.png",
4368 b"pretend-png-bytes",
4369 )
4370 .expect("put attachment");
4371
4372 say(
4373 &talks.claim_turn(&talk.id).unwrap().unwrap(),
4374 &mut talk,
4375 &talks,
4376 &cfg,
4377 "",
4378 vec![att.clone()],
4379 )
4380 .await
4381 .expect("an empty body with an attachment is still a turn");
4382
4383 let operator_turn = &talk.turns[0];
4384 assert_eq!(operator_turn.who, Who::Operator);
4385 assert_eq!(operator_turn.body, "");
4386 assert_eq!(operator_turn.attachments, vec![att.clone()]);
4387
4388 let prompt = &talk.turns[1].body;
4389 let expected_path = talks
4390 .attachments_dir(&talk.id)
4391 .join(format!("{}.png", att.id));
4392 assert!(
4393 prompt.contains(&expected_path.display().to_string()),
4394 "the agent must be told the attachment's absolute path: {prompt}"
4395 );
4396 assert!(prompt.contains("image/png"), "and its mime: {prompt}");
4397 }
4398
4399 #[test]
4408 fn attachment_path_is_absolute_even_when_the_store_root_is_relative() {
4409 let talks = Talks::at(PathBuf::from("relative-talks-root-for-this-test"));
4410 let att = Attachment {
4411 id: "0".repeat(32),
4412 name: "shot.png".to_owned(),
4413 mime: "image/png".to_owned(),
4414 bytes: 3,
4415 };
4416 let path = talks
4417 .attachment_path("some-talk-id", &att)
4418 .expect("a supported mime always yields a path");
4419 assert!(
4420 path.is_absolute(),
4421 "must be absolute even off a relative store root: {}",
4422 path.display()
4423 );
4424 }
4425
4426 #[tokio::test]
4427 async fn a_turn_past_the_configured_talk_timeout_is_reported_with_that_timeout() {
4428 let (tmp, talks) = store();
4433 let slow = mock_agent(
4434 tmp.path(),
4435 "#!/bin/sh\ncat >/dev/null\nsleep 2\n",
4436 BTreeMap::new(),
4437 );
4438 let mut cfg = config(slow);
4439 cfg.graph.timeout_talk = 1;
4440 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4441
4442 let err = say(
4443 &talks.claim_turn(&talk.id).unwrap().unwrap(),
4444 &mut talk,
4445 &talks,
4446 &cfg,
4447 "check the tests",
4448 Vec::new(),
4449 )
4450 .await
4451 .expect_err("a turn that never answers is an error");
4452 assert!(
4453 err.to_string().contains("did not answer within 1s"),
4454 "{err}"
4455 );
4456
4457 let on_disk = talks.get(&talk.id).expect("get");
4458 let note = on_disk.turns.last().expect("a note turn was recorded");
4459 assert!(
4460 note.body.contains("did not answer within 1s"),
4461 "the transcript must show the configured timeout: {}",
4462 note.body
4463 );
4464 }
4465
4466 #[test]
4467 fn closing_is_idempotent_and_a_closed_talk_takes_no_more_turns() {
4468 let (tmp, talks) = store();
4469 let spec = mock_agent(tmp.path(), REPLY, env("hi"));
4470 let cfg = config(spec);
4471 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4472
4473 close(&mut talk, &talks).expect("close");
4474 assert_eq!(talk.status, TalkStatus::Closed);
4475 close(&mut talk, &talks).expect("closing twice is not an error");
4476
4477 let err =
4478 record(&mut talk, &talks, "still there?", Vec::new()).expect_err("closed talks refuse");
4479 assert!(err.to_string().contains("closed"));
4480 let _ = &cfg; }
4482
4483 #[tokio::test]
4484 async fn a_close_that_lands_while_a_turn_is_in_flight_is_not_undone_by_the_reply() {
4485 let (tmp, talks) = store();
4486 let spec = mock_agent(tmp.path(), REPLY, env("here you go"));
4487 let cfg = config(spec);
4488 let mut in_flight = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4491
4492 let mut closed_elsewhere = talks.get(&in_flight.id).expect("reread");
4496 close(&mut closed_elsewhere, &talks).expect("close");
4497 assert_eq!(
4498 talks.get(&in_flight.id).expect("reread").status,
4499 TalkStatus::Closed,
4500 "the close landed on disk before the turn finished"
4501 );
4502
4503 assert_eq!(in_flight.status, TalkStatus::Open);
4507 respond(
4508 &talks.claim_turn(&in_flight.id).unwrap().unwrap(),
4509 &mut in_flight,
4510 &talks,
4511 &cfg,
4512 "one more question",
4513 )
4514 .await
4515 .expect("the turn itself still completes");
4516
4517 let on_disk = talks.get(&in_flight.id).expect("reread");
4518 assert_eq!(
4519 on_disk.status,
4520 TalkStatus::Closed,
4521 "a close must stick even when a turn that started before it finishes after it"
4522 );
4523 assert!(
4526 on_disk.turns.iter().any(|t| t.body == "here you go"),
4527 "the in-flight turn's own reply is still recorded: {:?}",
4528 on_disk.turns
4529 );
4530 }
4531
4532 #[test]
4533 fn a_close_that_lands_before_record_is_called_is_not_undone_by_it() {
4534 let (tmp, talks) = store();
4535 let spec = mock_agent(tmp.path(), REPLY, env("hi"));
4536 let cfg = config(spec);
4537 let mut stale = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4540
4541 let mut closed_elsewhere = talks.get(&stale.id).expect("reread");
4544 close(&mut closed_elsewhere, &talks).expect("close");
4545 assert_eq!(
4546 talks.get(&stale.id).expect("reread").status,
4547 TalkStatus::Closed,
4548 "the close landed on disk before record was called"
4549 );
4550
4551 assert_eq!(stale.status, TalkStatus::Open);
4555 let err = record(&mut stale, &talks, "still there?", Vec::new())
4556 .expect_err("a close that landed first must be honored, not overwritten");
4557 assert!(err.to_string().contains("closed"));
4558
4559 let on_disk = talks.get(&stale.id).expect("reread");
4560 assert_eq!(
4561 on_disk.status,
4562 TalkStatus::Closed,
4563 "record must not resurrect a conversation closed while its snapshot was stale"
4564 );
4565 assert!(
4566 on_disk.turns.is_empty(),
4567 "the rejected turn must not have been appended: {:?}",
4568 on_disk.turns
4569 );
4570 let _ = &cfg; }
4572
4573 #[test]
4574 fn close_blocks_on_records_guard_rather_than_interleaving_with_it() {
4575 let (tmp, talks) = store();
4576 let spec = mock_agent(tmp.path(), REPLY, env("hi"));
4577 let cfg = config(spec);
4578 let talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4579
4580 let held = talks.guard().unwrap();
4584
4585 let talks2 = talks.clone();
4586 let id = talk.id.clone();
4587 let closing = std::thread::spawn(move || {
4588 let mut talk = talks2.get(&id).expect("get");
4589 close(&mut talk, &talks2).expect("close");
4590 });
4591
4592 std::thread::sleep(Duration::from_millis(50));
4593 assert!(
4594 !closing.is_finished(),
4595 "close must wait for the guard, not read and write while it is held - \
4596 a re-read alone narrows this window without closing it"
4597 );
4598
4599 drop(held);
4600 closing.join().expect("close thread panicked");
4601
4602 assert_eq!(
4603 talks.get(&talk.id).expect("reread").status,
4604 TalkStatus::Closed,
4605 "once the guard is free, close still lands"
4606 );
4607 let _ = &cfg; }
4609
4610 #[test]
4611 fn reopening_a_closed_talk_lets_it_take_turns_again_and_reopening_twice_is_not_an_error() {
4612 let (tmp, talks) = store();
4613 let spec = mock_agent(tmp.path(), REPLY, env("hi"));
4614 let cfg = config(spec);
4615 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4616
4617 close(&mut talk, &talks).expect("close");
4618 assert_eq!(talk.status, TalkStatus::Closed);
4619
4620 reopen(&mut talk, &talks).expect("reopen");
4621 assert_eq!(talk.status, TalkStatus::Open);
4622 assert_eq!(
4623 talks.get(&talk.id).expect("reread").status,
4624 TalkStatus::Open
4625 );
4626
4627 reopen(&mut talk, &talks).expect("reopening an open talk is not an error");
4629 assert_eq!(talk.status, TalkStatus::Open);
4630
4631 record(&mut talk, &talks, "one more thing", Vec::new())
4632 .expect("a reopened talk takes turns again");
4633 let _ = &cfg; }
4635
4636 #[test]
4637 fn removing_a_talk_deletes_its_record_and_artifacts_and_refuses_an_unknown_id() {
4638 let (tmp, talks) = store();
4639 let spec = mock_agent(tmp.path(), REPLY, env("hi"));
4640 let cfg = config(spec);
4641 let talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4642
4643 let artifacts = talks.artifacts_of(&talk.id);
4644 std::fs::create_dir_all(&artifacts).expect("create artifacts dir");
4645 std::fs::write(artifacts.join("turn-1.txt"), "hello").expect("write artifact");
4646
4647 talks.remove(&talk.id).expect("remove");
4648 assert!(!talks.path_of(&talk.id).is_file(), "the record is gone");
4649 assert!(!artifacts.is_dir(), "the artifacts directory is gone");
4650 assert!(
4651 talks.get(&talk.id).is_err(),
4652 "a removed talk cannot be read back"
4653 );
4654
4655 let err = talks
4656 .remove("nonexistent-id")
4657 .expect_err("unknown id refused");
4658 assert!(err.to_string().contains("no talk matches"), "{err}");
4659 let _ = &cfg; }
4661
4662 #[tokio::test]
4663 async fn a_delete_that_lands_while_a_turn_is_in_flight_is_not_undone_by_the_reply() {
4664 let (tmp, talks) = store();
4665 let spec = mock_agent(tmp.path(), REPLY, env("here you go"));
4666 let cfg = config(spec);
4667 let mut in_flight = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4670
4671 talks.remove(&in_flight.id).expect("remove");
4672 assert!(
4673 talks.get(&in_flight.id).is_err(),
4674 "the delete landed on disk before the turn finished"
4675 );
4676
4677 respond(
4680 &talks.claim_turn(&in_flight.id).unwrap().unwrap(),
4681 &mut in_flight,
4682 &talks,
4683 &cfg,
4684 "one more question",
4685 )
4686 .await
4687 .expect("the turn itself still completes rather than erroring");
4688
4689 assert!(
4690 talks.get(&in_flight.id).is_err(),
4691 "a delete must stick even when a turn that started before it finishes after it"
4692 );
4693 }
4694
4695 #[test]
4696 fn a_delete_that_lands_before_record_is_called_is_not_undone_by_it() {
4697 let (tmp, talks) = store();
4698 let spec = mock_agent(tmp.path(), REPLY, env("hi"));
4699 let cfg = config(spec);
4700 let mut stale = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4703
4704 talks.remove(&stale.id).expect("remove");
4705
4706 let err = record(&mut stale, &talks, "still there?", Vec::new())
4710 .expect_err("a delete that landed first must be honored, not overwritten");
4711 assert!(err.to_string().contains("deleted"), "{err}");
4712
4713 assert!(
4714 talks.get(&stale.id).is_err(),
4715 "record must not resurrect a conversation deleted while its snapshot was stale"
4716 );
4717 let _ = &cfg; }
4719
4720 #[test]
4721 fn a_delete_that_lands_before_close_is_called_is_not_undone_by_it() {
4722 let (tmp, talks) = store();
4723 let spec = mock_agent(tmp.path(), REPLY, env("hi"));
4724 let cfg = config(spec);
4725 let mut stale = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4728
4729 talks.remove(&stale.id).expect("remove");
4730
4731 let err = close(&mut stale, &talks)
4735 .expect_err("a delete that landed first must be honored, not overwritten");
4736 assert!(err.to_string().contains("deleted"), "{err}");
4737
4738 assert!(
4739 talks.get(&stale.id).is_err(),
4740 "close must not resurrect a conversation deleted while its snapshot was stale"
4741 );
4742 let _ = &cfg; }
4744
4745 #[test]
4746 fn a_delete_that_lands_before_reopen_is_called_is_not_undone_by_it() {
4747 let (tmp, talks) = store();
4748 let spec = mock_agent(tmp.path(), REPLY, env("hi"));
4749 let cfg = config(spec);
4750 let mut stale = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4753 close(&mut stale, &talks).expect("close");
4754
4755 talks.remove(&stale.id).expect("remove");
4756
4757 let err = reopen(&mut stale, &talks)
4761 .expect_err("a delete that landed first must be honored, not overwritten");
4762 assert!(err.to_string().contains("deleted"), "{err}");
4763
4764 assert!(
4765 talks.get(&stale.id).is_err(),
4766 "reopen must not resurrect a conversation deleted while its snapshot was stale"
4767 );
4768 let _ = &cfg; }
4770
4771 #[test]
4772 fn list_puts_open_talks_before_closed_ones() {
4773 let (tmp, talks) = store();
4774 let make = |id: &str, status: TalkStatus| {
4775 let mut t = Talk {
4776 posts_read_through: None,
4777 pending_breaks: None,
4778 schema: SCHEMA,
4779 id: id.to_owned(),
4780 repo: tmp.path().to_owned(),
4781 agent: "mock".to_owned(),
4782 status,
4783 turns: Vec::new(),
4784 pending: String::new(),
4785 pending_attachments: Vec::new(),
4786 fallback: false,
4787 persona: String::new(),
4788 persona_dirty: false,
4789 implementers: 1,
4790 implementers_dirty: false,
4791 notified: Vec::new(),
4792 created_at: Timestamp::now(),
4793 updated_at: Timestamp::now(),
4794 seat: SeatState::new(SEAT, "mock", 7),
4795 };
4796 talks.put(&mut t).expect("put");
4797 };
4798 make("20260901-000000-0001", TalkStatus::Open);
4799 make("20260902-000000-0002", TalkStatus::Open);
4800 make("20260903-000000-0003", TalkStatus::Closed);
4801
4802 let ids: Vec<String> = talks.list().into_iter().map(|t| t.id).collect();
4803 assert_eq!(
4804 ids,
4805 [
4806 "20260902-000000-0002",
4807 "20260901-000000-0001",
4808 "20260903-000000-0003"
4809 ]
4810 );
4811 assert_eq!(talks.count_open(), 2);
4812 }
4813
4814 #[test]
4815 fn tasks_of_finds_only_this_talks_own_tasks() {
4816 let dir = tempfile::tempdir().expect("tempdir");
4817 let queue = Queue::at(dir.path().join("queue"));
4818
4819 let mut mine = Task::new(
4820 "rework the loader".to_owned(),
4821 "rework the loader".to_owned(),
4822 PathBuf::from("/repo"),
4823 Source::Agent {
4824 run: "20260904-014455-ab12".to_owned(),
4825 node: "chat".to_owned(),
4826 },
4827 );
4828 queue.put(&mut mine).expect("put mine");
4829
4830 let mut theirs = Task::new(
4831 "unrelated".to_owned(),
4832 "unrelated".to_owned(),
4833 PathBuf::from("/repo"),
4834 Source::Agent {
4835 run: "20260904-090000-zz99".to_owned(),
4836 node: "implement".to_owned(),
4837 },
4838 );
4839 queue.put(&mut theirs).expect("put theirs");
4840
4841 let mut human = Task::new(
4842 "typed by hand".to_owned(),
4843 "typed by hand".to_owned(),
4844 PathBuf::from("/repo"),
4845 Source::Human,
4846 );
4847 queue.put(&mut human).expect("put human");
4848
4849 let found = tasks_of(&queue, "20260904-014455-ab12");
4850 assert_eq!(found.len(), 1);
4851 assert_eq!(found[0].id, mine.id);
4852 }
4853
4854 #[test]
4855 fn the_briefing_names_solo_task_add() {
4856 let brief = briefing(Path::new("/repo"), "en", false);
4857 assert!(brief.contains("magi task add --solo"));
4858 assert!(brief.contains("/repo"));
4859 assert!(!brief.contains("Hold this conversation in"));
4860 }
4861
4862 #[test]
4868 fn the_briefing_explains_targeting_a_different_repository_by_name() {
4869 let brief = briefing(Path::new("/repo"), "en", false);
4870 assert!(brief.contains("--repo does not have to be a full path"));
4871 assert!(brief.contains("owner/repo"));
4872 assert!(brief.contains("magi repos"));
4873 assert!(brief.contains("ask the operator"));
4874 }
4875
4876 #[test]
4877 fn the_briefing_tells_the_assistant_to_pass_images_with_attach() {
4878 let brief = briefing(Path::new("/repo"), "en", false);
4879 assert!(brief.contains("--attach <path>"), "{brief}");
4880 assert!(brief.contains("deleting this conversation"), "{brief}");
4881 }
4882
4883 #[test]
4884 fn the_briefing_names_the_language_when_it_is_not_english() {
4885 let brief = briefing(Path::new("/repo"), "Japanese", false);
4886 assert!(brief.contains("Hold this conversation in Japanese"));
4887 }
4888
4889 #[test]
4890 fn the_briefing_forbids_writes_unless_the_repository_opted_in() {
4891 let read_only = briefing(Path::new("/repo"), "en", false);
4892 assert!(read_only.contains("Do not write files"));
4893 assert!(!read_only.contains("allow_write"));
4894
4895 let writable = briefing(Path::new("/repo"), "en", true);
4896 assert!(!writable.contains("Do not write files"));
4897 assert!(writable.contains("allow_write = true"));
4898 assert!(writable.contains("magi task add --solo"));
4901 assert!(writable.contains("say plainly what you"));
4902 }
4903
4904 #[test]
4905 fn the_briefing_says_the_chat_cannot_push_and_tasks_report_back() {
4906 let b = briefing_for(Path::new("/r"), "en", false, None, None, 1);
4907 assert!(
4908 b.contains("cannot send the operator a message on your own"),
4909 "{b}"
4910 );
4911 assert!(b.contains(crate::prompt::CHAT_TASK_NOTICE_HEADING));
4912 }
4913
4914 #[test]
4915 fn a_post_is_replayed_until_the_agent_answers_again() {
4916 let (_tmp, talks) = store();
4917 let mut talk = ctx_talk("mock", Vec::new());
4918 talks.put(&mut talk).expect("put");
4919 post(&talks, &talk.id, " found it ", "20260902-000000-aaaa").expect("post");
4920 let mut talk = talks.get(&talk.id).expect("get");
4921 let block = posts_since_last_reply(&talk).expect("block");
4922 assert!(block.starts_with("# Posted by a task"), "{block}");
4923 assert!(block.contains("found it"));
4924 talk.turns.push(reply("ok", None));
4925 assert!(posts_since_last_reply(&talk).is_none());
4926 assert!(post(&talks, &talk.id, " ", "r").is_err());
4927 close(&mut talk, &talks).expect("close");
4928 assert!(post(&talks, &talk.id, "late", "r").is_err());
4929 }
4930
4931 #[test]
4932 fn queue_once_accepts_a_key_a_single_time_even_after_a_drain() {
4933 let (_tmp, talks) = store();
4934 let mut talk = ctx_talk("mock", Vec::new());
4935 talks.put(&mut talk).expect("put");
4936 assert!(queue_once(&mut talk, &talks, "one", "k").expect("first"));
4937 drain(&mut talk, &talks).expect("drain");
4938 assert!(!queue_once(&mut talk, &talks, "one", "k").expect("again"));
4939 assert!(talks.get(&talk.id).expect("get").pending.is_empty());
4940 }
4941}