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)]
338 pub pending: String,
339 #[serde(default)]
341 pub pending_attachments: Vec<Attachment>,
342 #[serde(default, skip_serializing_if = "Option::is_none")]
344 pub pending_breaks: Option<Vec<usize>>,
345 #[serde(default)]
350 pub fallback: bool,
351 #[serde(default)]
354 pub persona: String,
355 #[serde(default)]
359 pub persona_dirty: bool,
360 #[serde(default = "solo_implementers")]
363 pub implementers: u8,
364 #[serde(default)]
367 pub implementers_dirty: bool,
368 #[serde(default)]
373 pub notified: Vec<String>,
374 pub created_at: Timestamp,
376 pub updated_at: Timestamp,
378 seat: SeatState,
383}
384
385impl Talk {
386 pub fn short(&self) -> &str {
388 short(&self.id)
389 }
390}
391
392#[derive(Debug, Clone)]
394pub struct Talks {
395 root: PathBuf,
396 lock: Arc<Mutex<()>>,
405}
406
407impl Talks {
408 pub fn open() -> Self {
410 Self::at(crate::run::home().join("talks"))
411 }
412
413 pub fn at(root: PathBuf) -> Self {
416 Self {
417 root,
418 lock: Arc::new(Mutex::new(())),
419 }
420 }
421
422 fn guard(&self) -> Result<StoreGuard<'_>> {
437 let mutex = self.lock.lock().unwrap_or_else(PoisonError::into_inner);
438 std::fs::create_dir_all(&self.root)
439 .with_context(|| format!("create {}", self.root.display()))?;
440 let path = self.root.join(".store.turn");
441 let deadline = std::time::Instant::now() + TAKEOVER_LOCK_TTL * 2;
442 loop {
443 if let Some(file) = TurnLock::take(&path)? {
444 return Ok(StoreGuard {
445 _file: file,
446 _mutex: mutex,
447 });
448 }
449 if std::time::Instant::now() >= deadline {
450 bail!("the talk store is locked by another process");
451 }
452 std::thread::sleep(Duration::from_millis(10));
453 }
454 }
455
456 pub fn root(&self) -> &Path {
458 &self.root
459 }
460
461 pub fn path_of(&self, id: &str) -> PathBuf {
463 self.root.join(format!("{id}.json"))
464 }
465
466 pub fn artifacts_of(&self, id: &str) -> PathBuf {
469 self.root.join(format!("{id}.artifacts"))
470 }
471
472 pub fn attachments_dir(&self, id: &str) -> PathBuf {
476 self.artifacts_of(id).join("attachments")
477 }
478
479 pub fn put_attachment(
488 &self,
489 id: &str,
490 mime: &str,
491 name: &str,
492 data: &[u8],
493 ) -> Result<Attachment> {
494 let dir = self.attachments_dir(id);
495 std::fs::create_dir_all(&dir).with_context(|| format!("create {}", dir.display()))?;
496 let ext = attachment_ext(mime).with_context(|| format!("unsupported mime `{mime}`"))?;
497 let att = Attachment {
498 id: new_attachment_id(),
499 name: name.to_owned(),
500 mime: mime.to_owned(),
501 bytes: data.len() as u64,
502 };
503 std::fs::write(dir.join(format!("{}.{ext}", att.id)), data)
504 .with_context(|| format!("write attachment {}", att.id))?;
505 std::fs::write(
506 dir.join(format!("{}.json", att.id)),
507 serde_json::to_string(&att).context("serialize attachment")?,
508 )
509 .with_context(|| format!("write attachment metadata {}", att.id))?;
510 Ok(att)
511 }
512
513 pub fn attachment_meta(&self, id: &str, att_id: &str) -> Result<Option<Attachment>> {
522 if !valid_attachment_id(att_id) {
523 return Ok(None);
524 }
525 let meta_path = self.attachments_dir(id).join(format!("{att_id}.json"));
526 if !meta_path.is_file() {
527 return Ok(None);
528 }
529 let att = serde_json::from_str(
530 &std::fs::read_to_string(&meta_path)
531 .with_context(|| format!("read {}", meta_path.display()))?,
532 )
533 .with_context(|| format!("parse {}", meta_path.display()))?;
534 Ok(Some(att))
535 }
536
537 pub fn read_attachment(&self, id: &str, att_id: &str) -> Result<Option<(Attachment, Vec<u8>)>> {
541 let Some(att) = self.attachment_meta(id, att_id)? else {
542 return Ok(None);
543 };
544 let ext = attachment_ext(&att.mime).with_context(|| {
545 format!("attachment {att_id} has an unsupported mime `{}`", att.mime)
546 })?;
547 let data_path = self.attachments_dir(id).join(format!("{att_id}.{ext}"));
548 let data =
549 std::fs::read(&data_path).with_context(|| format!("read {}", data_path.display()))?;
550 Ok(Some((att, data)))
551 }
552
553 fn attachment_path(&self, id: &str, att: &Attachment) -> Option<PathBuf> {
570 let ext = attachment_ext(&att.mime)?;
571 let path = self.attachments_dir(id).join(format!("{}.{ext}", att.id));
572 std::path::absolute(&path).ok()
573 }
574
575 pub fn put(&self, t: &mut Talk) -> Result<()> {
584 std::fs::create_dir_all(&self.root)
585 .with_context(|| format!("create {}", self.root.display()))?;
586 t.updated_at = Timestamp::now();
587 let body = serde_json::to_string_pretty(t).context("serialize talk")?;
588 let path = self.path_of(&t.id);
589 let tmp = path.with_extension("json.tmp");
590 write_atomic(&tmp, &path, &body)
591 }
592
593 pub fn get(&self, id: &str) -> Result<Talk> {
595 let resolved = self.resolve_id(id)?;
596 read_path(&self.path_of(&resolved))
597 }
598
599 pub fn list(&self) -> Vec<Talk> {
602 self.list_counting_unreadable().0
603 }
604
605 pub fn list_counting_unreadable(&self) -> (Vec<Talk>, usize) {
608 let mut unreadable = 0;
609 let mut all: Vec<Talk> = std::fs::read_dir(&self.root)
610 .into_iter()
611 .flatten()
612 .flatten()
613 .map(|e| e.path())
614 .filter(|p| p.extension().is_some_and(|x| x == "json"))
615 .filter_map(|p| {
616 let talk = read_path(&p).ok();
617 if talk.is_none() {
618 unreadable += 1;
619 }
620 talk
621 })
622 .collect();
623 all.sort_unstable_by(|a, b| {
624 let rank = |t: &Talk| u8::from(!t.status.open());
625 rank(a).cmp(&rank(b)).then_with(|| b.id.cmp(&a.id))
626 });
627 (all, unreadable)
628 }
629
630 pub fn resolve_id(&self, prefix: &str) -> Result<String> {
632 if self.path_of(prefix).is_file() {
633 return Ok(prefix.to_owned());
634 }
635 let hits: Vec<String> = self
636 .list()
637 .into_iter()
638 .map(|t| t.id)
639 .filter(|id| id.starts_with(prefix) || id.ends_with(prefix))
640 .collect();
641 match hits.len() {
642 1 => Ok(hits.into_iter().next().expect("exactly one hit")),
643 0 => bail!("no talk matches `{prefix}`"),
644 _ => bail!(
645 "`{prefix}` matches {} talks: {}",
646 hits.len(),
647 hits.join(", ")
648 ),
649 }
650 }
651
652 pub fn revision(&self) -> u64 {
655 std::fs::read_dir(&self.root)
656 .into_iter()
657 .flatten()
658 .flatten()
659 .filter(|e| e.path().extension().is_none_or(|x| x != "turn"))
660 .filter(|e| !e.file_name().to_string_lossy().starts_with('.'))
661 .filter_map(|e| e.metadata().ok())
662 .filter_map(|m| m.modified().ok())
663 .filter_map(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
664 .map(|d| d.as_millis() as u64)
665 .max()
666 .unwrap_or(0)
667 }
668
669 pub fn count_open(&self) -> usize {
671 self.list().iter().filter(|t| t.status.open()).count()
672 }
673
674 pub fn turn_path(&self, id: &str) -> PathBuf {
677 self.root.join(format!("{id}.turn"))
678 }
679
680 pub fn claim_turn(&self, id: &str) -> Result<Option<TurnLease>> {
689 self.claim_turn_at(id, Timestamp::now())
690 }
691
692 fn claim_turn_at(&self, id: &str, now: Timestamp) -> Result<Option<TurnLease>> {
693 std::fs::create_dir_all(&self.root)
694 .with_context(|| format!("create {}", self.root.display()))?;
695 let path = self.turn_path(id);
696 let token = fresh_token();
697 if create_turn(&path, &token, now)? {
698 return Ok(Some(TurnLease {
699 talk: id.to_owned(),
700 path,
701 token,
702 }));
703 }
704 if lease_blocks(&path, now) {
705 return Ok(None);
706 }
707 let Some(_lock) = TurnLock::take(&path)? else {
712 return Ok(None);
713 };
714 if lease_blocks(&path, now) {
715 return Ok(None);
716 }
717 let _ = std::fs::remove_file(&path);
718 Ok(create_turn(&path, &token, now)?.then_some(TurnLease {
719 talk: id.to_owned(),
720 path,
721 token,
722 }))
723 }
724
725 pub fn turn_held(&self, id: &str) -> bool {
727 read_turn(&self.turn_path(id)).is_some_and(|r| r.fresh(Timestamp::now()))
728 }
729
730 pub fn remove(&self, id: &str) -> Result<()> {
743 let _guard = self.guard()?;
744 let resolved = self.resolve_id(id)?;
745 let path = self.path_of(&resolved);
746 std::fs::remove_file(&path).with_context(|| format!("remove {}", path.display()))?;
747 let artifacts = self.artifacts_of(&resolved);
748 if artifacts.is_dir() {
749 std::fs::remove_dir_all(&artifacts)
750 .with_context(|| format!("remove {}", artifacts.display()))?;
751 }
752 let _ = std::fs::remove_file(self.turn_path(&resolved));
753 Ok(())
754 }
755}
756
757struct StoreGuard<'a> {
760 _file: TurnLock,
761 _mutex: MutexGuard<'a, ()>,
762}
763
764#[derive(Debug, Serialize, Deserialize)]
767struct TurnRecord {
768 token: String,
769 pid: u32,
770 beat_at: Timestamp,
771}
772
773impl TurnRecord {
774 fn fresh(&self, now: Timestamp) -> bool {
775 now.as_second() - self.beat_at.as_second() <= crate::ask::LEASE_TTL.as_secs() as i64
776 }
777}
778
779fn fresh_token() -> String {
783 static SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
784 let n = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
785 let seed = crate::rng::entropy() ^ n.wrapping_mul(0x9E37_79B9_7F4A_7C15);
786 crate::rng::SplitMix64::new(seed).uuid_v4()
787}
788
789fn read_turn(path: &Path) -> Option<TurnRecord> {
790 serde_json::from_str(&std::fs::read_to_string(path).ok()?).ok()
791}
792
793const TAKEOVER_LOCK_TTL: Duration = Duration::from_secs(10);
795
796const TICKET_TTL: Duration = Duration::from_secs(10);
799
800const TICKET_GENERATIONS: u32 = 16;
802
803const TICKET_SWEEP_AGE: Duration = Duration::from_secs(3600);
805
806fn create_exclusive(path: &Path, body: &str) -> Result<bool> {
808 use std::io::Write as _;
809 match std::fs::OpenOptions::new()
810 .write(true)
811 .create_new(true)
812 .open(path)
813 {
814 Ok(mut f) => {
815 if let Err(e) = f.write_all(body.as_bytes()) {
816 drop(f);
817 let _ = std::fs::remove_file(path);
818 return Err(e).with_context(|| format!("write {}", path.display()));
819 }
820 Ok(true)
821 }
822 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => Ok(false),
823 Err(e) => Err(e).with_context(|| format!("create {}", path.display())),
824 }
825}
826
827fn create_turn(path: &Path, token: &str, now: Timestamp) -> Result<bool> {
828 let record = TurnRecord {
829 token: token.to_owned(),
830 pid: std::process::id(),
831 beat_at: now,
832 };
833 let body = serde_json::to_string(&record).context("serialize turn lease")?;
834 let tmp = path.with_extension(format!("turn.{token}.new"));
837 publish_exclusive(path, &tmp, &body)
838}
839
840fn lease_blocks(path: &Path, now: Timestamp) -> bool {
844 if read_turn(path).is_some_and(|r| r.fresh(now)) {
845 return true;
846 }
847 std::fs::metadata(path).is_ok_and(|m| {
848 m.len() == 0
849 && m.modified()
850 .ok()
851 .and_then(|t| t.elapsed().ok())
852 .is_some_and(|age| age <= TAKEOVER_LOCK_TTL)
853 })
854}
855
856fn link_unsupported(e: &std::io::Error) -> bool {
859 e.kind() == std::io::ErrorKind::Unsupported || (cfg!(windows) && e.raw_os_error() == Some(1))
860}
861
862fn create_in_place(path: &Path, body: &str) -> Result<bool> {
880 use std::io::Write as _;
881 let mut f = match std::fs::OpenOptions::new()
882 .write(true)
883 .create_new(true)
884 .open(path)
885 {
886 Ok(f) => f,
887 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => return Ok(false),
888 Err(e) => return Err(e).with_context(|| format!("create {}", path.display())),
889 };
890 f.write_all(body.as_bytes())
891 .with_context(|| format!("write {}", path.display()))?;
892 Ok(std::fs::read_to_string(path).is_ok_and(|t| t == body))
895}
896
897fn publish_exclusive(path: &Path, tmp: &Path, body: &str) -> Result<bool> {
898 std::fs::write(tmp, body).with_context(|| format!("write {}", tmp.display()))?;
899 #[cfg(test)]
900 let linked = if failpoint::no_link_forced() {
901 Err(std::io::Error::from(std::io::ErrorKind::Unsupported))
902 } else {
903 std::fs::hard_link(tmp, path)
904 };
905 #[cfg(not(test))]
906 let linked = std::fs::hard_link(tmp, path);
907 let out = match linked {
908 Ok(()) => Ok(true),
909 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => Ok(false),
910 Err(e) if link_unsupported(&e) => create_in_place(path, body),
911 Err(e) => Err(e).with_context(|| format!("create {}", path.display())),
912 };
913 let _ = std::fs::remove_file(tmp);
914 out
915}
916
917fn remove_if_carries(path: &Path, expected: &str) -> bool {
928 let gone = path.with_extension(format!("gone.{}", fresh_token()));
929 if std::fs::rename(path, &gone).is_err() {
930 return false;
931 }
932 let found = std::fs::read_to_string(&gone);
933 if found.as_ref().is_ok_and(|t| t == expected) {
934 let _ = std::fs::remove_file(&gone);
935 return true;
936 }
937 if let Ok(body) = found {
938 let back = path.with_extension(format!("back.{}", fresh_token()));
939 match publish_exclusive(path, &back, &body) {
940 Ok(true) => {}
941 Ok(false) | Err(_) => tracing::warn!(
942 "{} was replaced while a stale removal had it aside; \
943 the displaced file is dropped",
944 path.display()
945 ),
946 }
947 }
948 let _ = std::fs::remove_file(&gone);
949 false
950}
951
952struct TurnLock {
956 path: PathBuf,
957 token: String,
958}
959
960impl TurnLock {
961 fn token() -> String {
962 fresh_token()
963 }
964
965 fn publish(path: &Path, token: &str) -> Result<bool> {
969 let tmp = path.with_extension(format!("lock.{token}.new"));
970 publish_exclusive(path, &tmp, token)
971 }
972
973 fn take(lease: &Path) -> Result<Option<Self>> {
974 let path = lease.with_extension("turn.lock");
975 let token = Self::token();
976 if Self::publish(&path, &token)? {
977 return Ok(Some(Self { path, token }));
978 }
979 let Ok(seen) = std::fs::read_to_string(&path) else {
980 return Ok(None);
981 };
982 let key = if !seen.is_empty() && seen.chars().all(|c| c.is_ascii_alphanumeric() || c == '-')
985 {
986 seen.as_str()
987 } else {
988 "invalid"
989 };
990 let aged = std::fs::metadata(&path)
991 .and_then(|m| m.modified())
992 .ok()
993 .and_then(|t| t.elapsed().ok())
994 .is_some_and(|age| age > TAKEOVER_LOCK_TTL);
995 if !aged {
996 return Ok(None);
997 }
998 let mut won = false;
1010 for n in 0..TICKET_GENERATIONS {
1011 let ticket = path.with_extension(format!("lock.{key}.break.{n}"));
1012 if create_exclusive(&ticket, "")? {
1013 won = true;
1014 break;
1015 }
1016 let stale = std::fs::metadata(&ticket)
1017 .and_then(|m| m.modified())
1018 .ok()
1019 .and_then(|t| t.elapsed().ok())
1020 .is_some_and(|age| age > TICKET_TTL);
1021 if !stale {
1022 return Ok(None);
1023 }
1024 }
1025 if !won {
1026 Self::sweep_tickets(&path);
1031 return Ok(None);
1032 }
1033 Self::sweep_tickets(&path);
1034 if !remove_if_carries(&path, &seen) {
1040 return Ok(None);
1041 }
1042 if Self::publish(&path, &token)? {
1043 return Ok(Some(Self { path, token }));
1044 }
1045 Ok(None)
1046 }
1047
1048 fn sweep_tickets(path: &Path) {
1051 let (Some(dir), Some(name)) = (path.parent(), path.file_name().and_then(|n| n.to_str()))
1052 else {
1053 return;
1054 };
1055 let prefix = format!("{name}.");
1056 let Ok(entries) = std::fs::read_dir(dir) else {
1057 return;
1058 };
1059 for entry in entries.flatten() {
1060 let file = entry.file_name();
1061 let Some(file) = file.to_str() else { continue };
1062 if !(file.starts_with(&prefix) && file.contains(".break.")) {
1063 continue;
1064 }
1065 let old = entry
1066 .metadata()
1067 .and_then(|m| m.modified())
1068 .ok()
1069 .and_then(|t| t.elapsed().ok())
1070 .is_some_and(|age| age > TICKET_SWEEP_AGE);
1071 if old {
1072 let _ = std::fs::remove_file(entry.path());
1073 }
1074 }
1075 }
1076
1077 fn take_patiently(lease: &Path) -> Option<Self> {
1079 for _ in 0..50 {
1080 match Self::take(lease) {
1081 Ok(Some(lock)) => return Some(lock),
1082 Ok(None) => std::thread::sleep(Duration::from_millis(10)),
1083 Err(_) => return None,
1084 }
1085 }
1086 None
1087 }
1088}
1089
1090impl Drop for TurnLock {
1091 fn drop(&mut self) {
1092 remove_if_carries(&self.path, &self.token);
1094 }
1095}
1096
1097pub const TURN_BEAT: Duration = Duration::from_secs(20);
1100
1101#[derive(Debug)]
1106pub struct TurnLease {
1107 talk: String,
1108 path: PathBuf,
1109 token: String,
1110}
1111
1112impl TurnLease {
1113 pub fn holds(&self) -> bool {
1115 read_turn(&self.path).is_some_and(|r| r.token == self.token)
1116 }
1117
1118 pub fn beat(&self) -> Result<bool> {
1122 let _lock = TurnLock::take_patiently(&self.path)
1123 .with_context(|| format!("lock {} to renew it", self.path.display()))?;
1124 let Some(mut record) = read_turn(&self.path).filter(|r| r.token == self.token) else {
1125 return Ok(false);
1126 };
1127 record.beat_at = Timestamp::now();
1128 let body = serde_json::to_string(&record).context("serialize turn lease")?;
1129 let tmp = self.path.with_extension(format!("turn.{}.tmp", self.token));
1130 write_atomic(&tmp, &self.path, &body)?;
1131 Ok(true)
1132 }
1133
1134 pub async fn beating<T>(&self, fut: impl std::future::Future<Output = T>) -> Result<T> {
1139 self.beating_every(TURN_BEAT, fut).await
1140 }
1141
1142 async fn beating_every<T>(
1143 &self,
1144 period: Duration,
1145 fut: impl std::future::Future<Output = T>,
1146 ) -> Result<T> {
1147 tokio::pin!(fut);
1148 loop {
1149 match tokio::time::timeout(period, &mut fut).await {
1150 Ok(out) => return Ok(out),
1151 Err(_) => match self.beat() {
1152 Ok(true) => {}
1153 Ok(false) => bail!(
1154 "the turn lease {} was taken over; this turn is stopped",
1155 self.path.display()
1156 ),
1157 Err(e) => tracing::warn!("{e:#}"),
1158 },
1159 }
1160 }
1161 }
1162}
1163
1164impl Drop for TurnLease {
1165 fn drop(&mut self) {
1166 if let Some(_lock) = TurnLock::take_patiently(&self.path) {
1169 if read_turn(&self.path).is_some_and(|r| r.token == self.token) {
1170 let _ = std::fs::remove_file(&self.path);
1171 }
1172 }
1173 }
1174}
1175
1176pub fn begin(store: &Talks, cfg: &Config, repo: PathBuf, agent: Option<&str>) -> Result<Talk> {
1186 begin_with(store, cfg, repo, agent, &Preferred::default())
1187}
1188
1189#[derive(Debug, Default, Clone)]
1193pub struct Preferred {
1194 pub agent: Option<String>,
1196 pub persona: Option<String>,
1198 pub implementers: Option<i64>,
1200}
1201
1202pub fn begin_with(
1209 store: &Talks,
1210 cfg: &Config,
1211 repo: PathBuf,
1212 agent: Option<&str>,
1213 preferred: &Preferred,
1214) -> Result<Talk> {
1215 let repo = repo.canonicalize().unwrap_or(repo);
1218 let head = || -> Result<AgentSpec> {
1221 Ok(agent::pick_chain(
1222 &cfg.agents,
1223 cfg.roles.chatter.as_ref(),
1224 &agent::installed,
1225 "chatter",
1226 )?
1227 .remove(0))
1228 };
1229 let mut fallback = agent.is_none();
1230 let spec = match agent {
1231 Some(id) => agent::pick(&cfg.agents, Some(id), &agent::installed)?,
1232 None => {
1233 match preferred
1234 .agent
1235 .as_deref()
1236 .map(str::trim)
1237 .filter(|id| !id.is_empty())
1238 {
1239 Some(id) => match agent::pick(&cfg.agents, Some(id), &agent::installed) {
1240 Ok(spec) => {
1241 fallback = head().is_ok_and(|head| spec.id == head.id);
1242 spec
1243 }
1244 Err(_) => head()?,
1245 },
1246 None => head()?,
1247 }
1248 }
1249 };
1250 let persona = preferred
1251 .persona
1252 .as_deref()
1253 .and_then(|id| crate::persona::find(&cfg.talk.personas, id))
1254 .filter(|p| !p.is_default())
1255 .map(|p| p.id)
1256 .unwrap_or_default();
1257 let implementers = preferred
1258 .implementers
1259 .and_then(|n| u8::try_from(n).ok())
1260 .and_then(|n| check_implementers(n, cfg).ok())
1261 .unwrap_or(1);
1262
1263 let now = Timestamp::now();
1264 let mut talk = Talk {
1265 pending_breaks: None,
1266 schema: SCHEMA,
1267 id: new_id(),
1268 repo,
1269 agent: spec.id.clone(),
1270 status: TalkStatus::Open,
1271 turns: Vec::new(),
1272 pending: String::new(),
1273 pending_attachments: Vec::new(),
1274 fallback,
1275 persona,
1276 persona_dirty: false,
1277 implementers,
1278 implementers_dirty: false,
1279 notified: Vec::new(),
1280 created_at: now,
1281 updated_at: now,
1282 seat: SeatState::new(SEAT, &spec.id, crate::rng::entropy()),
1283 };
1284 store.put(&mut talk)?;
1285 Ok(talk)
1286}
1287
1288pub fn record(
1295 talk: &mut Talk,
1296 store: &Talks,
1297 text: &str,
1298 attachments: Vec<Attachment>,
1299) -> Result<String> {
1300 let _guard = store.guard()?;
1308 let Ok(fresh) = store.get(&talk.id) else {
1313 bail!("talk {} was deleted", talk.short());
1314 };
1315 talk.status = fresh.status;
1316 talk.pending = fresh.pending;
1319 talk.pending_breaks = fresh.pending_breaks;
1320 talk.pending_attachments = fresh.pending_attachments;
1321 talk.notified = fresh.notified;
1322 if !talk.status.open() {
1323 bail!(
1324 "talk {} is {} and takes no more turns",
1325 talk.short(),
1326 talk.status.as_str()
1327 );
1328 }
1329 let text = text.trim();
1330 if text.is_empty() && attachments.is_empty() {
1331 bail!("nothing to say");
1332 }
1333 talk.turns.push(Turn {
1334 who: Who::Operator,
1335 body: text.to_owned(),
1336 at: Timestamp::now(),
1337 attachments,
1338 usage: None,
1339 breaks: Some(Vec::new()),
1340 posted_by: None,
1341 });
1342 store.put(talk)?;
1343 Ok(text.to_owned())
1344}
1345
1346pub fn queue(
1348 talk: &mut Talk,
1349 store: &Talks,
1350 text: &str,
1351 attachments: Vec<Attachment>,
1352) -> Result<()> {
1353 queue_keyed(talk, store, text, attachments, None).map(|_| ())
1354}
1355
1356pub fn queue_once(talk: &mut Talk, store: &Talks, text: &str, key: &str) -> Result<bool> {
1361 queue_keyed(talk, store, text, Vec::new(), Some(key))
1362}
1363
1364fn queue_keyed(
1365 talk: &mut Talk,
1366 store: &Talks,
1367 text: &str,
1368 attachments: Vec<Attachment>,
1369 key: Option<&str>,
1370) -> Result<bool> {
1371 let text = text.trim();
1372 if text.is_empty() && attachments.is_empty() {
1373 bail!("nothing to say");
1374 }
1375 let _guard = store.guard()?;
1376 let mut fresh = store
1377 .get(&talk.id)
1378 .with_context(|| format!("talk {} was deleted", talk.short()))?;
1379 if !fresh.status.open() {
1380 bail!(
1381 "talk {} is {} and takes no more turns",
1382 fresh.short(),
1383 fresh.status.as_str()
1384 );
1385 }
1386 if let Some(key) = key {
1387 if fresh.notified.iter().any(|k| k == key) {
1388 *talk = fresh;
1389 return Ok(false);
1390 }
1391 fresh.notified.push(key.to_owned());
1392 }
1393 if !text.is_empty() {
1394 if fresh.pending.is_empty() {
1395 fresh.pending = text.to_owned();
1396 fresh.pending_breaks = Some(Vec::new());
1397 } else {
1398 fresh.pending.push_str("\n\n");
1399 if let Some(b) = fresh.pending_breaks.as_mut() {
1400 b.push(fresh.pending.len());
1401 }
1402 fresh.pending.push_str(text);
1403 }
1404 }
1405 fresh.pending_attachments.extend(attachments);
1406 store.put(&mut fresh)?;
1407 *talk = fresh;
1408 Ok(true)
1409}
1410
1411pub fn post(store: &Talks, talk_id: &str, body: &str, by: &str) -> Result<()> {
1416 let body = body.trim();
1417 if body.is_empty() {
1418 bail!("nothing to post");
1419 }
1420 let _guard = store.guard()?;
1421 let mut fresh = store
1422 .get(talk_id)
1423 .with_context(|| format!("talk {talk_id} does not exist"))?;
1424 if !fresh.status.open() {
1425 bail!(
1426 "talk {} is closed and takes no more messages",
1427 fresh.short()
1428 );
1429 }
1430 fresh.turns.push(Turn {
1431 who: Who::Agent,
1432 body: body.to_owned(),
1433 at: Timestamp::now(),
1434 attachments: Vec::new(),
1435 usage: None,
1436 breaks: None,
1437 posted_by: Some(by.to_owned()),
1438 });
1439 store.put(&mut fresh)
1440}
1441
1442pub fn posts_since_last_reply(talk: &Talk) -> Option<String> {
1445 let mut posts: Vec<&Turn> = talk
1446 .turns
1447 .iter()
1448 .rev()
1449 .take_while(|t| t.who == Who::Operator || t.posted_by.is_some())
1450 .filter(|t| t.posted_by.is_some())
1451 .collect();
1452 if posts.is_empty() {
1453 return None;
1454 }
1455 posts.reverse();
1456 let mut out = String::from("# Posted by a task\n\n");
1457 for t in posts {
1458 out.push_str(&format!(
1459 "Task seat {} posted to this conversation: {}\n\n",
1460 short(t.posted_by.as_deref().unwrap_or_default()),
1461 t.body
1462 ));
1463 }
1464 Some(out)
1465}
1466
1467pub fn drain(talk: &mut Talk, store: &Talks) -> Result<Option<String>> {
1469 let _guard = store.guard()?;
1470 let mut fresh = store
1471 .get(&talk.id)
1472 .with_context(|| format!("talk {} was deleted", talk.short()))?;
1473 if !fresh.status.open() || (fresh.pending.is_empty() && fresh.pending_attachments.is_empty()) {
1474 *talk = fresh;
1475 return Ok(None);
1476 }
1477 let text = std::mem::take(&mut fresh.pending);
1478 let attachments = std::mem::take(&mut fresh.pending_attachments);
1479 let breaks = fresh.pending_breaks.take();
1480 fresh.turns.push(Turn {
1481 who: Who::Operator,
1482 body: text.clone(),
1483 at: Timestamp::now(),
1484 attachments,
1485 usage: None,
1486 breaks,
1487 posted_by: None,
1488 });
1489 store.put(&mut fresh)?;
1490 *talk = fresh;
1491 Ok(Some(text))
1492}
1493
1494pub async fn say(
1497 lease: &TurnLease,
1498 talk: &mut Talk,
1499 store: &Talks,
1500 cfg: &Config,
1501 text: &str,
1502 attachments: Vec<Attachment>,
1503) -> Result<()> {
1504 check_lease(lease, talk)?;
1505 let text = record(talk, store, text, attachments)?;
1506 respond(lease, talk, store, cfg, &text).await
1507}
1508
1509pub async fn respond(
1515 lease: &TurnLease,
1516 talk: &mut Talk,
1517 store: &Talks,
1518 cfg: &Config,
1519 text: &str,
1520) -> Result<()> {
1521 check_lease(lease, talk)?;
1522 lease
1523 .beating(turn(talk, store, cfg, text))
1524 .await
1525 .and_then(|done| done)
1526}
1527
1528fn check_lease(lease: &TurnLease, talk: &Talk) -> Result<()> {
1529 if lease.talk != talk.id {
1530 bail!("the turn lease is for talk {}, not {}", lease.talk, talk.id);
1531 }
1532 if !lease.holds() {
1535 bail!("the turn lease for talk {} is no longer held", talk.short());
1536 }
1537 Ok(())
1538}
1539
1540pub fn close(talk: &mut Talk, store: &Talks) -> Result<()> {
1558 let _guard = store.guard()?;
1559 let mut fresh = store
1560 .get(&talk.id)
1561 .with_context(|| format!("talk {} was deleted", talk.short()))?;
1562 fresh.status = TalkStatus::Closed;
1563 fresh.pending.clear();
1565 fresh.pending_breaks = None;
1566 fresh.pending_attachments.clear();
1567 store.put(&mut fresh)?;
1568 *talk = fresh;
1569 Ok(())
1570}
1571
1572pub fn reopen(talk: &mut Talk, store: &Talks) -> Result<()> {
1583 let _guard = store.guard()?;
1584 let mut fresh = store
1585 .get(&talk.id)
1586 .with_context(|| format!("talk {} was deleted", talk.short()))?;
1587 fresh.status = TalkStatus::Open;
1588 store.put(&mut fresh)?;
1589 *talk = fresh;
1590 Ok(())
1591}
1592
1593pub fn switch_agent(talk: &mut Talk, store: &Talks, spec: &AgentSpec) -> Result<bool> {
1606 let _guard = store.guard()?;
1607 let mut fresh = store
1608 .get(&talk.id)
1609 .with_context(|| format!("talk {} was deleted", talk.short()))?;
1610 if fresh.agent == spec.id {
1611 *talk = fresh;
1612 return Ok(false);
1613 }
1614 let from = std::mem::replace(&mut fresh.agent, spec.id.clone());
1615 fresh.seat = SeatState::new(SEAT, &spec.id, crate::rng::entropy());
1616 fresh.fallback = false;
1618 fresh.turns.push(Turn {
1619 breaks: None,
1620 posted_by: None,
1621 who: Who::Agent,
1622 body: format!("{MAGI_NOTE}agent changed from {from} to {}", spec.id),
1623 at: Timestamp::now(),
1624 attachments: Vec::new(),
1625 usage: None,
1626 });
1627 store.put(&mut fresh)?;
1628 *talk = fresh;
1629 Ok(true)
1630}
1631
1632pub fn switch_persona(talk: &mut Talk, store: &Talks, id: &str) -> Result<bool> {
1640 let id = if id.trim() == crate::persona::DEFAULT_ID {
1641 ""
1642 } else {
1643 id.trim()
1644 };
1645 let _guard = store.guard()?;
1646 let mut fresh = store
1647 .get(&talk.id)
1648 .with_context(|| format!("talk {} was deleted", talk.short()))?;
1649 if fresh.persona == id {
1650 *talk = fresh;
1651 return Ok(false);
1652 }
1653 let from = std::mem::replace(&mut fresh.persona, id.to_owned());
1654 fresh.persona_dirty = true;
1655 let label = |p: &str| {
1656 if p.is_empty() {
1657 crate::persona::DEFAULT_ID.to_owned()
1658 } else {
1659 p.to_owned()
1660 }
1661 };
1662 fresh.turns.push(Turn {
1663 breaks: None,
1664 posted_by: None,
1665 who: Who::Agent,
1666 body: format!(
1667 "{MAGI_NOTE}persona changed from {} to {}",
1668 label(&from),
1669 label(id)
1670 ),
1671 at: Timestamp::now(),
1672 attachments: Vec::new(),
1673 usage: None,
1674 });
1675 store.put(&mut fresh)?;
1676 *talk = fresh;
1677 Ok(true)
1678}
1679
1680pub fn clear_pending(talk: &mut Talk, store: &Talks) -> Result<()> {
1682 let _guard = store.guard()?;
1683 let mut fresh = store
1684 .get(&talk.id)
1685 .with_context(|| format!("talk {} was deleted", talk.short()))?;
1686 fresh.pending.clear();
1687 fresh.pending_breaks = None;
1688 fresh.pending_attachments.clear();
1689 store.put(&mut fresh)?;
1690 *talk = fresh;
1691 Ok(())
1692}
1693
1694pub fn clear_pending_if_matches(
1696 talk: &mut Talk,
1697 store: &Talks,
1698 expected_text: &str,
1699 expected_attachments: &[String],
1700) -> Result<bool> {
1701 let _guard = store.guard()?;
1702 let mut fresh = store
1703 .get(&talk.id)
1704 .with_context(|| format!("talk {} was deleted", talk.short()))?;
1705 if !pending_matches(&fresh, expected_text, expected_attachments) {
1706 *talk = fresh;
1707 return Ok(false);
1708 }
1709 fresh.pending.clear();
1710 fresh.pending_breaks = None;
1711 fresh.pending_attachments.clear();
1712 store.put(&mut fresh)?;
1713 *talk = fresh;
1714 Ok(true)
1715}
1716
1717pub fn edit_pending_text(
1721 talk: &mut Talk,
1722 store: &Talks,
1723 text: &str,
1724 expected_text: &str,
1725 expected_attachments: &[String],
1726) -> Result<bool> {
1727 let _guard = store.guard()?;
1728 let mut fresh = store
1729 .get(&talk.id)
1730 .with_context(|| format!("talk {} was deleted", talk.short()))?;
1731 if !pending_matches(&fresh, expected_text, expected_attachments) {
1732 *talk = fresh;
1733 return Ok(false);
1734 }
1735 fresh.pending = text.trim().to_owned();
1736 fresh.pending_breaks = Some(Vec::new());
1737 store.put(&mut fresh)?;
1738 *talk = fresh;
1739 Ok(true)
1740}
1741
1742fn pending_matches(talk: &Talk, expected_text: &str, expected_attachments: &[String]) -> bool {
1743 talk.pending == expected_text
1744 && talk
1745 .pending_attachments
1746 .iter()
1747 .map(|attachment| &attachment.id)
1748 .eq(expected_attachments.iter())
1749}
1750
1751async fn turn(talk: &mut Talk, store: &Talks, cfg: &Config, text: &str) -> Result<()> {
1758 let spec = cfg
1759 .agents
1760 .iter()
1761 .find(|a| a.id == talk.agent)
1762 .with_context(|| {
1763 format!(
1764 "talk {} was opened with agent `{}`, which is no longer in \
1765 the roster; restore it in magi.toml or start a new \
1766 conversation",
1767 talk.short(),
1768 talk.agent
1769 )
1770 })?;
1771
1772 let last_note = attachment_note(
1776 store,
1777 &talk.id,
1778 talk.turns
1779 .last()
1780 .map_or(&[][..], |t| t.attachments.as_slice()),
1781 );
1782
1783 let attachment_paths: Vec<PathBuf> = talk
1789 .turns
1790 .iter()
1791 .flat_map(|t| t.attachments.iter())
1792 .filter_map(|a| store.attachment_path(&talk.id, a))
1793 .collect();
1794
1795 let questions =
1805 crate::run::try_home().map(|home| crate::ask::Questions::at(home.join("questions")));
1806 let consulted = questions
1807 .as_ref()
1808 .is_some_and(|q| crate::consult::pending_consults(q, &talk.id));
1809 let consult_roots: Vec<PathBuf> = match &questions {
1810 Some(q) if consulted => vec![q.root().to_path_buf()],
1811 _ => Vec::new(),
1812 };
1813
1814 let (allow_write, unsandboxed) = turn_access(cfg.talk.allow_write, consulted);
1815
1816 let artifacts = store.artifacts_of(&talk.id);
1817 let operator_turns = talk.turns.iter().filter(|t| t.who == Who::Operator).count();
1820 let stem = format!("turn-{}", operator_turns.max(1));
1821 let cache_dir = cfg.cache_dir();
1824
1825 let mut chain = vec![spec.clone()];
1828 if let Some(choice) = cfg.roles.chatter.as_ref()
1829 && talk.fallback
1830 {
1831 for id in choice.ids() {
1832 if id == talk.agent || chain.iter().any(|s| s.id == id) {
1833 continue;
1834 }
1835 match agent::pick(&cfg.agents, Some(id), &agent::installed) {
1836 Ok(s) => chain.push(s),
1837 Err(e) => tracing::warn!("[roles] chatter: skipping `{id}`: {e:#}"),
1838 }
1839 }
1840 }
1841
1842 let persona = crate::persona::active(&cfg.talk.personas, &talk.persona);
1843 let operator_name = cfg.talk.operator_name();
1844 let persona_update = if talk.persona_dirty {
1845 format!(
1846 "{}\n\n",
1847 crate::persona::update_block_for(persona.as_ref(), operator_name)
1848 )
1849 } else {
1850 String::new()
1851 };
1852
1853 let filing_update = if talk.implementers_dirty {
1856 format!("{}\n\n", filing_update_block(talk.implementers))
1857 } else {
1858 String::new()
1859 };
1860
1861 let mut outcome = None;
1862 let mut fell_back_from: Option<String> = None;
1863 let mut first_try: Option<(String, SeatState)> = None;
1866 for (n, spec) in chain.iter().enumerate() {
1867 if n > 0 {
1868 if first_try.is_none() {
1869 first_try = Some((talk.agent.clone(), talk.seat.clone()));
1870 }
1871 tracing::warn!("chat: falling back from `{}` to `{}`", talk.agent, spec.id);
1872 fell_back_from.get_or_insert_with(|| talk.agent.clone());
1875 talk.agent = spec.id.clone();
1876 talk.seat = SeatState::new(SEAT, &spec.id, crate::rng::entropy());
1877 }
1878 let resuming = agent::has_session(spec.kind, &talk.seat, cfg.graph.sessions);
1879 let first_ever = talk.turns.len() <= 1;
1880 let body = if talk.seat.turns == 0 && first_ever {
1881 format!(
1882 "{}\n\n# Operator\n\n{text}{last_note}",
1883 briefing_for(
1884 &talk.repo,
1885 &cfg.graph.language,
1886 cfg.talk.allow_write,
1887 persona.as_ref(),
1888 operator_name,
1889 talk.implementers
1890 )
1891 )
1892 } else if talk.seat.turns == 0 {
1893 format!(
1896 "{}\n\n{}\n\n# Operator\n\n{text}{last_note}",
1897 briefing_for(
1898 &talk.repo,
1899 &cfg.graph.language,
1900 cfg.talk.allow_write,
1901 persona.as_ref(),
1902 operator_name,
1903 talk.implementers
1904 ),
1905 transcript(talk, store)
1906 )
1907 } else if resuming {
1908 let posts = posts_since_last_reply(talk).unwrap_or_default();
1909 format!("{persona_update}{filing_update}{posts}{text}{last_note}")
1910 } else {
1911 let mut standing = match (&persona, talk.persona_dirty) {
1915 (Some(p), false) => format!("{}\n", crate::persona::section_for(p, operator_name)),
1916 _ => persona_update.clone(),
1917 };
1918 if let (None, Some(n)) = (&persona, operator_name) {
1921 standing.push_str(&format!(
1922 "# Addressing the operator\n{}\n",
1923 crate::persona::addressing(n)
1924 ));
1925 }
1926 if talk.implementers_dirty || talk.implementers != 1 {
1927 standing.push_str(&format!("{}\n\n", filing_update_block(talk.implementers)));
1928 }
1929 format!("{}\n\n{standing}{text}{last_note}", transcript(talk, store))
1930 };
1931 let attempt_stem = if n == 0 {
1932 stem.clone()
1933 } else {
1934 format!("{stem}-{}", spec.id)
1935 };
1936 let inv = Invocation {
1937 cwd: &talk.repo,
1938 prompt: &body,
1939 timeout: turn_timeout(cfg),
1940 allow_write,
1945 unsandboxed,
1946 sessions: cfg.graph.sessions,
1947 artifacts: &artifacts,
1948 stem: &attempt_stem,
1949 run: &talk.id,
1952 node: crate::queue::CHAT_NODE,
1953 cache_dir: cache_dir.as_deref(),
1954 attachments: &attachment_paths,
1955 writable: &consult_roots,
1956 };
1957 let result = agent::invoke(spec, &mut talk.seat, &inv).await;
1958 let advance = agent::chain_advances(&result);
1959 if n == 0 || !advance {
1960 outcome = Some(result);
1961 } else {
1962 tracing::warn!("chat: fallback agent `{}` also failed", spec.id);
1964 }
1965 if !advance {
1966 break;
1967 }
1968 }
1969 if outcome.as_ref().is_some_and(agent::chain_advances) {
1970 if let Some((id, seat)) = first_try {
1973 talk.agent = id;
1974 talk.seat = seat;
1975 fell_back_from = None;
1976 }
1977 }
1978 let outcome = outcome.expect("a chain holds at least one agent");
1979 let note = |why: String| Turn {
1980 breaks: None,
1981 posted_by: None,
1982 who: Who::Agent,
1983 body: format!("{MAGI_NOTE}{why}"),
1984 at: Timestamp::now(),
1985 attachments: Vec::new(),
1986 usage: None,
1987 };
1988 let (reply, failure) = match outcome {
1989 Err(e) => (
1990 note(format!("could not run agent `{}`: {e}", talk.agent)),
1991 Some(format!("could not run agent `{}`: {e}", talk.agent)),
1992 ),
1993 Ok(out) if out.quota_exhausted() => {
1994 let reset = out
1995 .quota
1996 .as_ref()
1997 .and_then(|q| q.reset.clone())
1998 .map_or_else(String::new, |r| format!(" (resets {r})"));
1999 let why = format!(
2000 "agent `{}` is out of quota{reset}; your message is saved, so \
2001 say it again when the window reopens",
2002 talk.agent
2003 );
2004 (note(why.clone()), Some(why))
2005 }
2006 Ok(out) if out.timed_out => {
2007 let why = format!(
2008 "agent `{}` did not answer within {}s; your message is saved",
2009 talk.agent,
2010 turn_timeout(cfg).as_secs()
2011 );
2012 (note(why.clone()), Some(why))
2013 }
2014 Ok(out) if !out.usable() => {
2015 let why = format!(
2016 "agent `{}` produced no answer (exit {}); your message is saved",
2017 talk.agent,
2018 out.exit_code
2019 .map_or_else(|| "unknown".to_owned(), |c| c.to_string())
2020 );
2021 (note(why.clone()), Some(why))
2022 }
2023 Ok(out) => (
2024 Turn {
2025 breaks: None,
2026 posted_by: None,
2027 who: Who::Agent,
2028 body: out.text.trim().to_owned(),
2029 at: Timestamp::now(),
2030 attachments: Vec::new(),
2031 usage: out.context_tokens.map(|context_tokens| TurnUsage {
2034 context_tokens,
2035 agent: talk.agent.clone(),
2036 model: cfg
2037 .agents
2038 .iter()
2039 .find(|a| a.id == talk.agent)
2040 .and_then(|a| a.model.clone()),
2041 }),
2042 },
2043 None,
2044 ),
2045 };
2046
2047 let _guard = store.guard()?;
2059 let Ok(fresh) = store.get(&talk.id) else {
2065 return Ok(());
2066 };
2067 talk.status = fresh.status;
2068 talk.pending = fresh.pending;
2072 talk.pending_breaks = fresh.pending_breaks;
2073 talk.pending_attachments = fresh.pending_attachments;
2074 talk.notified = fresh.notified;
2075 if fresh.turns.len() > talk.turns.len() {
2077 let posted: Vec<Turn> = fresh.turns[talk.turns.len()..]
2078 .iter()
2079 .filter(|t| t.posted_by.is_some())
2080 .cloned()
2081 .collect();
2082 talk.turns.extend(posted);
2083 }
2084 if let Some(from) = fell_back_from.filter(|_| failure.is_none()) {
2085 talk.turns.push(note(format!(
2088 "agent changed from {from} to {} (fallback)",
2089 talk.agent
2090 )));
2091 }
2092 if failure.is_none() {
2095 talk.persona_dirty = false;
2096 talk.implementers_dirty = false;
2097 }
2098 talk.turns.push(reply);
2099 if let Err(put_err) = store.put(talk) {
2100 let lost = talk.turns.pop().expect("just pushed above");
2109 let stash = stash_lost_turn(store, &talk.id, &stem, &lost);
2110 let why = match &stash {
2111 Ok(path) => format!(
2112 "agent `{}` answered, but the reply could not be saved to \
2113 this conversation ({put_err:#}); the raw text was kept at \
2114 {} - your message is saved, ask again",
2115 talk.agent,
2116 path.display()
2117 ),
2118 Err(stash_err) => format!(
2119 "agent `{}` answered, but the reply could not be saved to \
2120 this conversation ({put_err:#}), and it could not be kept \
2121 anywhere else either ({stash_err:#}); your message is \
2122 saved, ask again",
2123 talk.agent
2124 ),
2125 };
2126 talk.turns.push(note(why.clone()));
2127 return match store.put(talk) {
2134 Ok(()) => bail!("{why}"),
2135 Err(note_err) => {
2136 talk.turns.pop();
2156 Err(note_err).context(why)
2157 }
2158 };
2159 }
2160
2161 match failure {
2162 Some(why) => bail!("{why}"),
2163 None => Ok(()),
2164 }
2165}
2166
2167fn transcript(talk: &Talk, store: &Talks) -> String {
2170 let mut out = String::from(
2171 "This conversation cannot resume on the CLI's side, so here is \
2172 everything said so far; answer only the last message.\n",
2173 );
2174 for t in &talk.turns {
2175 let who = match t.who {
2176 Who::Operator => "operator",
2177 Who::Agent if t.body.starts_with(MAGI_NOTE) => "magi",
2178 Who::Agent => "you",
2179 };
2180 out.push_str(&format!("\n## {who}\n\n{}\n", t.body.trim()));
2181 out.push_str(&attachment_note(store, &talk.id, &t.attachments));
2182 }
2183 out
2184}
2185
2186fn attachment_note(store: &Talks, talk_id: &str, attachments: &[Attachment]) -> String {
2191 if attachments.is_empty() {
2192 return String::new();
2193 }
2194 let mut out = String::from(
2195 "\n\nThe operator attached the image(s) below to this message. Open \
2196 and look at each one before you answer.\n",
2197 );
2198 for att in attachments {
2199 if let Some(path) = store.attachment_path(talk_id, att) {
2200 out.push_str(&format!("\n- {} ({})", path.display(), att.mime));
2201 }
2202 }
2203 out.push('\n');
2204 out
2205}
2206
2207pub(crate) fn turn_access(talk_allow_write: bool, consulted: bool) -> (bool, bool) {
2218 (talk_allow_write || consulted, talk_allow_write)
2219}
2220
2221pub fn briefing(repo: &Path, language: &str, allow_write: bool) -> String {
2237 briefing_with(repo, language, allow_write, None, None)
2238}
2239
2240pub fn briefing_with(
2245 repo: &Path,
2246 language: &str,
2247 allow_write: bool,
2248 persona: Option<&crate::persona::Persona>,
2249 operator_name: Option<&str>,
2250) -> String {
2251 briefing_for(repo, language, allow_write, persona, operator_name, 1)
2252}
2253
2254pub const MAX_IMPLEMENTERS: u8 = 3;
2256
2257fn solo_implementers() -> u8 {
2258 1
2259}
2260
2261fn filing_flag(n: u8) -> String {
2264 if n <= 1 {
2265 "--solo".to_owned()
2266 } else {
2267 format!("--implementers {n}")
2268 }
2269}
2270
2271pub fn filing_update_block(n: u8) -> String {
2274 let flag = filing_flag(n);
2275 if n <= 1 {
2276 format!(
2277 "# Task filing update\n\nThe operator changed how many implementers tasks use. \
2278 From now on file with `magi task add {flag} --repo <repo> <instruction>` \
2279 (one implementer, straight into review).\n"
2280 )
2281 } else {
2282 format!(
2283 "# Task filing update\n\nThe operator changed how many implementers tasks use. \
2284 From now on file with `magi task add {flag} --repo <repo> <instruction>` \
2285 ({n} independent implementations compete). Do not pass `--solo` \
2286 together with `--implementers`; drop any earlier `--solo`.\n"
2287 )
2288 }
2289}
2290
2291pub fn check_implementers(n: u8, cfg: &crate::config::Config) -> std::result::Result<u8, String> {
2294 if !(1..=MAX_IMPLEMENTERS).contains(&n) {
2295 return Err(format!(
2296 "implementers must be 1..={MAX_IMPLEMENTERS}, got {n}"
2297 ));
2298 }
2299 if n > 1 {
2300 let mut cfg = cfg.clone();
2301 crate::queue::RunOverrides {
2302 candidates: Some(usize::from(n)),
2303 ..Default::default()
2304 }
2305 .apply(&mut cfg);
2306 cfg.resolve_roles()
2307 .map_err(|e| format!("{n} implementers is not allowed here: {e:#}"))?;
2308 }
2309 Ok(n)
2310}
2311
2312pub fn switch_implementers(talk: &mut Talk, store: &Talks, n: u8) -> Result<bool> {
2315 let _guard = store.guard()?;
2316 let mut fresh = store
2317 .get(&talk.id)
2318 .with_context(|| format!("talk {} was deleted", talk.short()))?;
2319 if fresh.implementers == n {
2320 *talk = fresh;
2321 return Ok(false);
2322 }
2323 let from = std::mem::replace(&mut fresh.implementers, n);
2324 fresh.implementers_dirty = true;
2325 fresh.turns.push(Turn {
2326 breaks: None,
2327 posted_by: None,
2328 who: Who::Agent,
2329 body: format!("{MAGI_NOTE}implementers changed from {from} to {n}"),
2330 at: Timestamp::now(),
2331 attachments: Vec::new(),
2332 usage: None,
2333 });
2334 store.put(&mut fresh)?;
2335 *talk = fresh;
2336 Ok(true)
2337}
2338
2339pub fn briefing_for(
2342 repo: &Path,
2343 language: &str,
2344 allow_write: bool,
2345 persona: Option<&crate::persona::Persona>,
2346 operator_name: Option<&str>,
2347 implementers: u8,
2348) -> String {
2349 let flag = filing_flag(implementers);
2350 let shape = if implementers <= 1 {
2351 "Use --solo: it runs the task through one implementer \
2352 straight into review instead of the usual multi-agent competition, \
2353 which is the right shape for a change this conversation has already \
2354 settled, rather than one still worth several independent takes."
2355 .to_owned()
2356 } else {
2357 format!(
2358 "Use --implementers {implementers}: it has {implementers} \
2359 implementers work on the task independently and compete, which \
2360 is the right shape when several independent takes are worth \
2361 having. Never add --solo to it; the two do not go together."
2362 )
2363 };
2364 let write_policy = if allow_write {
2365 "Write access is enabled for this conversation (`allow_write = \
2366 true`), so you may write files - but only a small, \
2367 already-decided edit the operator names outright in this \
2368 conversation, not an implementation. This is a permission on the \
2369 conversation as a whole, not a property of whichever repository \
2370 it happened to start in: if the operator names a different \
2371 repository for that small edit, the policy allows it there too. \
2372 Your own tool may still confine writes to the repository this \
2373 conversation started in regardless - if a write elsewhere is \
2374 refused, say so plainly rather than working around it. Once you \
2375 have made an edit, say plainly what you edited. Anything bigger, \
2376 or anything still open-ended, still goes through the queue below \
2377 rather than being done here."
2378 } else {
2379 "Do not write files. Implementing a change is not this \
2380 conversation's job; a separate, blind competition of agents does \
2381 that, and a repository this conversation has already edited would \
2382 make their diffs unjudgeable."
2383 };
2384 let mut out = format!(
2385 "You are magi's standing conversation partner for its operator, who \
2386 usually has this open on a phone. Keep replies short: no preamble, \
2387 no restating what they just said.\n\n\
2388 # Repository\n\n{repo}\n\n\
2389 You may look around: read files, run shell commands, search history, \
2390 run tests - whatever answers the question. {write_policy}\n\n\
2391 A short, command-shaped message (\"list\", \"info <id>\", \"show \
2392 3cbf\") is almost always the operator asking you to look something \
2393 up, not an instruction to file - answer it yourself with `magi \
2394 list`, `magi show <id>`, `magi task list`, or the like, the same way \
2395 you would answer any other question in this conversation.\n\n\
2396 # When the operator wants something done\n\n\
2397 Run:\n\n\
2398 magi task add {flag} --repo {repo} <instruction>\n\n\
2399 and tell the operator the task id it prints, so they can follow it \
2400 from the Queue. If it refuses with a duplicate warning (the \
2401 instruction names a branch, commit or pull request that an \
2402 unfinished task, run or PR already owns), do not repeat it with \
2403 --force yourself: tell the operator what it matched and let them \
2404 decide. Write <instruction> so that an implementer who has \
2405 never seen this conversation can act on it alone - it is everything \
2406 they get. {shape}\n\n\
2407 If the operator asks for something in a different repository, \
2408 --repo does not have to be a full path: --repo owner/repo (or just \
2409 repo, when that is unambiguous) is resolved against local checkouts \
2410 the same way `magi repos` lists them. If the command fails because \
2411 nothing matches or more than one checkout shares that name, ask the \
2412 operator which repository they mean (or run `magi repos` yourself \
2413 to see the candidates) rather than guessing.\n\n\
2414 You cannot wait, and you cannot send the operator a message on your \
2415 own: you only speak when they write. A task you file reports back \
2416 into this conversation automatically when it finishes, is held or \
2417 fails, as a message headed \"{notice}\", so never promise to \"tell \
2418 them when it is done\" for anything else.\n\n\
2419 The current state of the code is whatever origin/main holds, not \
2420 whatever a working tree shows: a primary checkout often lags \
2421 upstream, sits on a detached HEAD and carries uncommitted changes. \
2422 Before answering about code, run `git fetch origin` in that \
2423 repository if it is cheap, then read through \
2424 `git show origin/main:<path>` or `git grep <pattern> origin/main`. \
2425 If the working tree differs, say so; if the fetch fails, say that \
2426 too, so the operator knows the answer may be stale.\n\n\
2427 If the operator attached an image (a screenshot, say) that the task \
2428 is about, pass it with `--attach <path>`, using the absolute path \
2429 the turn's attachment note gives; repeat the flag for several. \
2430 `magi task add {flag} --attach <path> <instruction>` copies the \
2431 file into the task, so the implementer receives it. Do not paste the \
2432 path into <instruction> instead: deleting this conversation deletes \
2433 its attachments, and then that path reaches no one.\n",
2434 repo = repo.display(),
2435 notice = crate::prompt::CHAT_TASK_NOTICE_HEADING,
2436 );
2437 out.push_str(&language_note(language));
2438 match (persona, operator_name) {
2439 (Some(p), n) => out.push_str(&crate::persona::section_for(p, n)),
2440 (None, Some(n)) => {
2441 out.push_str("\n# Addressing the operator\n");
2442 out.push_str(&crate::persona::addressing(n));
2443 }
2444 (None, None) => {}
2445 }
2446 out
2447}
2448
2449fn language_note(language: &str) -> String {
2452 if language.trim().is_empty() || language.eq_ignore_ascii_case("en") {
2453 String::new()
2454 } else {
2455 format!("\nHold this conversation in {language}.\n")
2456 }
2457}
2458
2459pub fn tasks_of(queue: &Queue, talk_id: &str) -> Vec<Task> {
2466 let mut tasks: Vec<Task> = queue
2467 .list()
2468 .into_iter()
2469 .filter(|t| matches!(&t.source, Source::Agent { run, .. } if run == talk_id))
2470 .collect();
2471 tasks.sort_unstable_by(|a, b| a.id.cmp(&b.id));
2472 tasks
2473}
2474
2475fn read_path(path: &Path) -> Result<Talk> {
2476 let body = std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;
2477 serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))
2478}
2479
2480const PUT_RETRIES: u32 = 5;
2483
2484fn write_atomic(tmp: &Path, path: &Path, body: &str) -> Result<()> {
2496 let mut last_err = None;
2497 for attempt in 0..PUT_RETRIES {
2498 if attempt > 0 {
2499 std::thread::sleep(Duration::from_millis(20 * u64::from(attempt)));
2500 }
2501 match try_write_atomic(tmp, path, body) {
2502 Ok(()) => return Ok(()),
2503 Err(e) => last_err = Some(e),
2504 }
2505 }
2506 Err(last_err.expect("the loop above always runs at least once"))
2507}
2508
2509fn try_write_atomic(tmp: &Path, path: &Path, body: &str) -> Result<()> {
2510 #[cfg(test)]
2511 if failpoint::take_forced_put_failure() {
2512 bail!("simulated write failure (test)");
2513 }
2514 std::fs::write(tmp, body).with_context(|| format!("write {}", tmp.display()))?;
2515 std::fs::rename(tmp, path).with_context(|| format!("replace {}", path.display()))?;
2516 Ok(())
2517}
2518
2519fn stash_lost_turn(store: &Talks, id: &str, stem: &str, reply: &Turn) -> Result<PathBuf> {
2524 let dir = store.artifacts_of(id);
2525 std::fs::create_dir_all(&dir).with_context(|| format!("create {}", dir.display()))?;
2526 let path = dir.join(format!("{stem}-lost.txt"));
2527 std::fs::write(&path, &reply.body).with_context(|| format!("write {}", path.display()))?;
2528 Ok(path)
2529}
2530
2531#[cfg(test)]
2538mod failpoint {
2539 use std::cell::Cell;
2540
2541 thread_local! {
2542 static FORCE_PUT_FAILURES: Cell<u32> = const { Cell::new(0) };
2543 static FORCE_NO_LINK: Cell<bool> = const { Cell::new(false) };
2544 }
2545
2546 pub(super) fn force_no_link(on: bool) {
2549 FORCE_NO_LINK.with(|c| c.set(on));
2550 }
2551
2552 pub(super) fn no_link_forced() -> bool {
2553 FORCE_NO_LINK.with(Cell::get)
2554 }
2555
2556 pub(super) fn force_put_failures(count: u32) {
2559 FORCE_PUT_FAILURES.with(|c| c.set(count));
2560 }
2561
2562 pub(super) fn take_forced_put_failure() -> bool {
2565 FORCE_PUT_FAILURES.with(|c| {
2566 let n = c.get();
2567 if n == 0 {
2568 false
2569 } else {
2570 c.set(n - 1);
2571 true
2572 }
2573 })
2574 }
2575}
2576
2577fn short(id: &str) -> &str {
2578 id.split('-').next_back().unwrap_or(id)
2579}
2580
2581fn new_id() -> String {
2582 let stamp = jiff::Zoned::now().strftime("%Y%m%d-%H%M%S");
2583 let seed = crate::rng::entropy();
2584 format!("{stamp}-{:04x}", (seed ^ (seed >> 32)) & 0xffff)
2585}
2586
2587fn attachment_ext(mime: &str) -> Option<&'static str> {
2592 match mime {
2593 "image/png" => Some("png"),
2594 "image/jpeg" => Some("jpg"),
2595 "image/gif" => Some("gif"),
2596 "image/webp" => Some("webp"),
2597 _ => None,
2598 }
2599}
2600
2601pub fn valid_attachment_id(id: &str) -> bool {
2606 id.len() == 32
2607 && id
2608 .bytes()
2609 .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
2610}
2611
2612fn new_attachment_id() -> String {
2616 let mut r = crate::rng::SplitMix64::new(crate::rng::entropy());
2617 format!("{:016x}{:016x}", r.next_u64(), r.next_u64())
2618}
2619
2620#[cfg(test)]
2621mod tests {
2622 #[test]
2623 fn turn_access_lifts_the_sandbox_only_for_the_talk_opt_in() {
2624 use super::turn_access;
2625 assert_eq!(turn_access(false, false), (false, false));
2626 assert_eq!(turn_access(true, false), (true, true));
2627 assert_eq!(turn_access(false, true), (true, false));
2629 assert_eq!(turn_access(true, true), (true, true));
2630 }
2631
2632 #[test]
2633 fn the_briefing_points_at_origin_main_not_the_working_tree() {
2634 let b = briefing(Path::new("/r"), "en", false);
2635 assert!(b.contains("origin/main"));
2636 assert!(b.contains("git show origin/main:"));
2637 }
2638 use std::collections::BTreeMap;
2639
2640 use crate::config::{AgentChoice, AgentKind, AgentSpec, Graph};
2641 use crate::queue::{Queue, Source, Task};
2642
2643 use super::*;
2644
2645 fn ctx_agent(id: &str, model: Option<&str>) -> AgentSpec {
2646 AgentSpec {
2647 id: id.to_owned(),
2648 kind: AgentKind::Command,
2649 model: model.map(str::to_owned),
2650 command: Vec::new(),
2651 extra_args: Vec::new(),
2652 env: BTreeMap::new(),
2653 prompt_delivery: None,
2654 }
2655 }
2656
2657 fn ctx_talk(agent: &str, turns: Vec<Turn>) -> Talk {
2658 Talk {
2659 pending_breaks: None,
2660 schema: SCHEMA,
2661 id: "20260904-014455-ab12".to_owned(),
2662 repo: PathBuf::from("."),
2663 agent: agent.to_owned(),
2664 status: TalkStatus::Open,
2665 turns,
2666 pending: String::new(),
2667 pending_attachments: Vec::new(),
2668 fallback: false,
2669 persona: String::new(),
2670 persona_dirty: false,
2671 implementers: 1,
2672 implementers_dirty: false,
2673 notified: Vec::new(),
2674 created_at: Timestamp::now(),
2675 updated_at: Timestamp::now(),
2676 seat: SeatState::new(SEAT, agent, 1),
2677 }
2678 }
2679
2680 fn reply(body: &str, usage: Option<(u64, &str, Option<&str>)>) -> Turn {
2681 Turn {
2682 breaks: None,
2683 posted_by: None,
2684 who: Who::Agent,
2685 body: body.to_owned(),
2686 at: Timestamp::now(),
2687 attachments: Vec::new(),
2688 usage: usage.map(|(t, a, m)| TurnUsage {
2689 context_tokens: t,
2690 agent: a.to_owned(),
2691 model: m.map(str::to_owned),
2692 }),
2693 }
2694 }
2695
2696 fn ctx_config(windows: &[(&str, u64)]) -> Config {
2697 Config {
2698 agents: vec![
2699 ctx_agent("small", Some("small-model")),
2700 ctx_agent("big", Some("big-model")),
2701 ctx_agent("plain", None),
2702 ],
2703 context_windows: windows.iter().map(|(k, v)| ((*k).to_owned(), *v)).collect(),
2704 ..Config::default()
2705 }
2706 }
2707
2708 #[test]
2709 fn context_usage_computes_percent_and_warns_at_eighty() {
2710 let cfg = ctx_config(&[("small-model", 1000)]);
2711 let at = |tokens| {
2712 let t = ctx_talk(
2713 "small",
2714 vec![reply("hi", Some((tokens, "small", Some("small-model"))))],
2715 );
2716 context_usage(&t, Some(&cfg))
2717 };
2718 let u = at(799);
2719 assert_eq!((u.percent, u.warn, u.window), (Some(79), false, Some(1000)));
2720 let u = at(800);
2721 assert_eq!((u.percent, u.warn), (Some(80), true));
2722 let u = at(1500);
2723 assert_eq!((u.percent, u.warn), (Some(150), true));
2724 assert!(!u.since_switch);
2725 }
2726
2727 #[test]
2728 fn context_usage_is_unknown_without_usage_and_never_looks_back() {
2729 let cfg = ctx_config(&[("small-model", 1000)]);
2730 let t = ctx_talk(
2731 "small",
2732 vec![
2733 reply("old", Some((900, "small", Some("small-model")))),
2734 reply("new", None),
2735 ],
2736 );
2737 let u = context_usage(&t, Some(&cfg));
2738 assert!(u.estimated);
2740 assert_ne!(u.tokens, Some(900));
2741 assert!(u.tokens.is_some());
2742 let t = ctx_talk(
2744 "small",
2745 vec![
2746 reply("old", Some((900, "small", Some("small-model")))),
2747 reply("magi: could not run agent", None),
2748 ],
2749 );
2750 assert_eq!(context_usage(&t, Some(&cfg)).tokens, Some(900));
2751 assert_eq!(
2752 context_usage(&ctx_talk("small", Vec::new()), Some(&cfg)).tokens,
2753 None
2754 );
2755 }
2756
2757 #[test]
2758 fn estimate_counts_chars_both_sides_and_standing_prompt() {
2759 let mut t = ctx_talk("small", vec![reply("abcdefg", None)]);
2760 assert_eq!(estimate_context_tokens(&t, 0), Some(2)); let op = Turn {
2762 who: Who::Operator,
2763 ..reply("abcdefg", None)
2764 };
2765 t.turns.push(op);
2766 assert_eq!(estimate_context_tokens(&t, 0), Some(4));
2767 assert!(
2768 estimate_context_tokens(&t, 700).unwrap() > estimate_context_tokens(&t, 0).unwrap()
2769 );
2770 let ja = ctx_talk("small", vec![reply("日本語日本語日", None)]);
2772 assert_eq!(estimate_context_tokens(&ja, 0), Some(2));
2773 let note = ctx_talk("small", vec![reply("magi: could not run agent", None)]);
2775 assert_eq!(estimate_context_tokens(¬e, 1000), None);
2776 assert_eq!(
2777 estimate_context_tokens(&ctx_talk("small", Vec::new()), 1000),
2778 None
2779 );
2780 }
2781
2782 #[test]
2783 fn context_usage_measured_wins_and_estimate_gets_percent_and_warn() {
2784 let cfg = ctx_config(&[("small-model", 1000)]);
2785 let t = ctx_talk(
2786 "small",
2787 vec![reply(
2788 &"x".repeat(5000),
2789 Some((10, "small", Some("small-model"))),
2790 )],
2791 );
2792 let u = context_usage(&t, Some(&cfg));
2793 assert_eq!((u.tokens, u.estimated), (Some(10), false));
2794 let t = ctx_talk("small", vec![reply(&"x".repeat(5000), None)]);
2795 let u = context_usage(&t, Some(&cfg));
2796 assert!(u.estimated && !u.since_switch);
2797 assert_eq!(u.window, Some(1000));
2798 assert!(u.warn && u.percent.unwrap() >= 80);
2799 let t = ctx_talk("small", vec![reply("hi", None)]);
2800 let u = context_usage(&t, Some(&cfg));
2801 assert!(u.estimated && u.percent.is_some());
2802 }
2803
2804 #[test]
2805 fn context_usage_without_a_window_shows_tokens_only() {
2806 let cfg = ctx_config(&[]);
2807 let t = ctx_talk("plain", vec![reply("hi", Some((5000, "plain", None)))]);
2809 let u = context_usage(&t, Some(&cfg));
2810 assert_eq!(
2811 (u.tokens, u.window, u.percent, u.warn),
2812 (Some(5000), None, None, false)
2813 );
2814 let t = ctx_talk(
2815 "small",
2816 vec![reply("hi", Some((5000, "small", Some("small-model"))))],
2817 );
2818 assert_eq!(context_usage(&t, Some(&cfg)).percent, None);
2819 assert_eq!(context_usage(&t, None).window, None);
2821 }
2822
2823 #[test]
2824 fn context_usage_switching_model_changes_the_denominator() {
2825 let cfg = ctx_config(&[("small-model", 1000), ("big-model", 10_000)]);
2826 let used = reply("hi", Some((900, "small", Some("small-model"))));
2827 let before = context_usage(&ctx_talk("small", vec![used.clone()]), Some(&cfg));
2828 assert_eq!(
2829 (before.percent, before.warn, before.since_switch),
2830 (Some(90), true, false)
2831 );
2832 let after = context_usage(&ctx_talk("big", vec![used]), Some(&cfg));
2835 assert_eq!(after.window, Some(10_000));
2836 assert_eq!(
2837 (after.percent, after.warn, after.since_switch),
2838 (Some(9), false, true)
2839 );
2840 assert_eq!(after.model.as_deref(), Some("big-model"));
2841 }
2842
2843 #[test]
2844 fn a_turn_recorded_before_usage_existed_still_reads() {
2845 let old = r#"{"who":"agent","body":"hi","at":"2026-09-04T01:44:55Z"}"#;
2846 let turn: Turn = serde_json::from_str(old).expect("old turn reads");
2847 assert!(turn.usage.is_none());
2848 let json = serde_json::to_string(&turn).expect("serialize");
2849 assert!(
2850 !json.contains("usage"),
2851 "absent usage is not written: {json}"
2852 );
2853 }
2854
2855 fn store() -> (tempfile::TempDir, Talks) {
2857 let tmp = tempfile::tempdir().expect("tempdir");
2858 let talks = Talks::at(tmp.path().join("talks"));
2859 (tmp, talks)
2860 }
2861
2862 fn mock_agent(dir: &Path, script: &str, env: BTreeMap<String, String>) -> AgentSpec {
2866 let path = dir.join("mock-talk-agent.sh");
2867 std::fs::write(&path, script).expect("write mock");
2868 AgentSpec {
2869 id: "mock".to_owned(),
2870 kind: AgentKind::Command,
2871 model: None,
2872 command: vec!["sh".to_owned(), path.to_string_lossy().into_owned()],
2873 extra_args: Vec::new(),
2874 env,
2875 prompt_delivery: None,
2876 }
2877 }
2878
2879 fn config(spec: AgentSpec) -> Config {
2880 Config {
2881 agents: vec![spec],
2882 graph: Graph {
2883 language: "en".to_owned(),
2884 ..Graph::default()
2885 },
2886 ..Config::default()
2887 }
2888 }
2889
2890 const REPLY: &str = "#!/bin/sh\ncat >/dev/null\nprintf '%s\\n' \"$MOCK_REPLY\"\n";
2892
2893 const BROKEN: &str = "#!/bin/sh\ncat >/dev/null\nexit 3\n";
2895
2896 const ECHO: &str = "#!/bin/sh\ncat\n";
2899
2900 fn env(reply: &str) -> BTreeMap<String, String> {
2901 BTreeMap::from([("MOCK_REPLY".to_owned(), reply.to_owned())])
2902 }
2903
2904 #[test]
2905 fn the_frozen_json_field_names_round_trip_through_disk() {
2906 let (tmp, talks) = store();
2907 let mut talk = Talk {
2908 pending_breaks: None,
2909 schema: SCHEMA,
2910 id: "20260904-014455-ab12".to_owned(),
2911 repo: tmp.path().to_owned(),
2912 agent: "sonnet".to_owned(),
2913 status: TalkStatus::Open,
2914 turns: Vec::new(),
2915 pending: String::new(),
2916 pending_attachments: Vec::new(),
2917 fallback: false,
2918 persona: String::new(),
2919 persona_dirty: false,
2920 implementers: 1,
2921 implementers_dirty: false,
2922 notified: Vec::new(),
2923 created_at: Timestamp::now(),
2924 updated_at: Timestamp::now(),
2925 seat: SeatState::new(SEAT, "sonnet", 7),
2926 };
2927 talks.put(&mut talk).expect("put");
2928
2929 let raw = std::fs::read_to_string(talks.path_of(&talk.id)).expect("read back");
2930 let v: serde_json::Value = serde_json::from_str(&raw).expect("parse");
2931 for field in [
2932 "schema",
2933 "id",
2934 "repo",
2935 "agent",
2936 "status",
2937 "turns",
2938 "created_at",
2939 "updated_at",
2940 ] {
2941 assert!(v.get(field).is_some(), "missing field `{field}`");
2942 }
2943 assert_eq!(v["schema"], 1);
2944 assert_eq!(v["status"], "open");
2945
2946 let back = talks.get(&talk.id).expect("get");
2947 assert_eq!(back.id, talk.id);
2948 assert_eq!(back.status, TalkStatus::Open);
2949 }
2950
2951 #[test]
2952 fn opening_a_talk_takes_no_agent_turn() {
2953 let (tmp, talks) = store();
2954 let spec = mock_agent(tmp.path(), BROKEN, BTreeMap::new());
2958 let cfg = config(spec);
2959
2960 let talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
2961 assert_eq!(talk.status, TalkStatus::Open);
2962 assert!(talk.turns.is_empty(), "nothing has been said yet");
2963
2964 let on_disk = talks.get(&talk.id).expect("get");
2965 assert_eq!(on_disk.turns.len(), 0);
2966 }
2967
2968 #[test]
2976 fn chatter_wins_when_set_and_falls_back_to_pick_s_default_order_otherwise() {
2977 let (tmp, talks) = store();
2978 let first_spec = mock_agent(tmp.path(), BROKEN, BTreeMap::new());
2979 let mut chatter_spec = mock_agent(tmp.path(), BROKEN, BTreeMap::new());
2980 chatter_spec.id = "chatter-mock".to_owned();
2981
2982 let mut cfg = Config {
2983 agents: vec![first_spec.clone(), chatter_spec.clone()],
2984 graph: Graph {
2985 language: "en".to_owned(),
2986 ..Graph::default()
2987 },
2988 ..Config::default()
2989 };
2990 cfg.roles.chatter = Some(chatter_spec.id.as_str().into());
2991
2992 let talk =
2993 begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin with chatter set");
2994 assert_eq!(talk.agent, chatter_spec.id, "an explicit chatter must win");
2995
2996 cfg.roles.chatter = None;
2997 let fallback =
2998 begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin with chatter unset");
2999 assert_eq!(
3000 fallback.agent, first_spec.id,
3001 "unset chatter must fall back to agent::pick's own default order"
3002 );
3003 }
3004
3005 #[test]
3008 fn a_talk_recorded_without_attachments_still_reads() {
3009 let (tmp, talks) = store();
3010 let path = talks.path_of("20260904-014455-ab12");
3011 std::fs::create_dir_all(talks.root()).expect("talks dir");
3012 std::fs::write(
3013 &path,
3014 serde_json::json!({
3015 "schema": 1,
3016 "id": "20260904-014455-ab12",
3017 "repo": tmp.path(),
3018 "agent": "sonnet",
3019 "status": "open",
3020 "turns": [
3021 { "who": "operator", "body": "still there?",
3022 "at": Timestamp::now().to_string() },
3023 ],
3024 "created_at": Timestamp::now().to_string(),
3025 "updated_at": Timestamp::now().to_string(),
3026 "seat": SeatState::new(SEAT, "sonnet", 7),
3027 })
3028 .to_string(),
3029 )
3030 .expect("write pre-attachments talk");
3031
3032 let talk = talks.get("20260904-014455-ab12").expect("must still read");
3033 assert!(talk.turns[0].attachments.is_empty());
3034 }
3035
3036 fn lease_store() -> (tempfile::TempDir, Talks, Talks) {
3037 let tmp = tempfile::TempDir::new().expect("tmp");
3038 let root = tmp.path().join("talks");
3039 (tmp, Talks::at(root.clone()), Talks::at(root))
3040 }
3041
3042 #[test]
3043 fn two_starters_on_one_talk_one_wins_and_the_other_is_refused() {
3044 let (_tmp, a, b) = lease_store();
3045 let won = a.claim_turn("t1").expect("claim").expect("first wins");
3046 assert!(
3047 b.claim_turn("t1").expect("claim").is_none(),
3048 "second is refused"
3049 );
3050 assert!(b.turn_held("t1"));
3051 assert!(
3052 b.claim_turn("t2").expect("claim").is_some(),
3053 "other talks are free"
3054 );
3055 drop(won);
3056 }
3057
3058 #[test]
3059 fn a_stale_lease_is_taken_over_and_the_old_guard_cannot_release_it() {
3060 let (_tmp, a, b) = lease_store();
3061 let old = a.claim_turn("t1").expect("claim").expect("held");
3062 let later = Timestamp::now()
3063 .checked_add(jiff::SignedDuration::from_secs(
3064 crate::ask::LEASE_TTL.as_secs() as i64 + 5,
3065 ))
3066 .expect("later");
3067 let new = b
3068 .claim_turn_at("t1", later)
3069 .expect("claim")
3070 .expect("a stale lease is taken over");
3071 drop(old);
3072 assert!(a.turn_held("t1"), "the old guard left the new lease alone");
3073 assert!(new.beat().expect("beat"), "the new owner still beats");
3074 drop(new);
3075 assert!(!a.turn_held("t1"));
3076 }
3077
3078 #[tokio::test]
3079 async fn a_turn_whose_lease_was_taken_over_is_stopped() {
3080 let (_tmp, a, b) = lease_store();
3081 let old = a.claim_turn("t1").expect("claim").expect("held");
3082 let later = Timestamp::now()
3083 .checked_add(jiff::SignedDuration::from_secs(
3084 crate::ask::LEASE_TTL.as_secs() as i64 + 5,
3085 ))
3086 .expect("later");
3087 let _new = b
3088 .claim_turn_at("t1", later)
3089 .expect("claim")
3090 .expect("taken over");
3091 let out = old
3092 .beating_every(Duration::from_millis(10), std::future::pending::<()>())
3093 .await;
3094 assert!(out.is_err(), "the displaced turn must stop, not run on");
3095 }
3096
3097 #[tokio::test]
3098 async fn a_turn_that_finishes_is_returned_and_keeps_its_lease_beating() {
3099 let (_tmp, a, _b) = lease_store();
3100 let lease = a.claim_turn("t1").expect("claim").expect("held");
3101 let out = lease
3102 .beating_every(Duration::from_millis(5), async {
3103 tokio::time::sleep(Duration::from_millis(40)).await;
3104 7
3105 })
3106 .await
3107 .expect("still ours");
3108 assert_eq!(out, 7);
3109 assert!(a.turn_held("t1"));
3110 }
3111
3112 #[test]
3113 fn an_unreadable_lease_counts_as_stale() {
3114 let (_tmp, a, b) = lease_store();
3115 std::fs::create_dir_all(a.root()).expect("dir");
3116 std::fs::write(a.turn_path("t1"), "not json").expect("write");
3117 assert!(!a.turn_held("t1"));
3118 assert!(b.claim_turn("t1").expect("claim").is_some());
3119 }
3120
3121 #[test]
3122 fn without_hard_links_a_claim_is_still_exclusive_and_a_young_placeholder_blocks() {
3123 let (_tmp, a, b) = lease_store();
3124 failpoint::force_no_link(true);
3125 let held = a.claim_turn("t1").expect("claim").expect("first wins");
3126 assert!(b.claim_turn("t1").expect("claim").is_none());
3127 assert!(a.turn_held("t1"));
3128 drop(held);
3129 assert!(!a.turn_held("t1"));
3130 let path = a.turn_path("t1");
3132 assert!(create_exclusive(&path, "").expect("placeholder"));
3133 assert!(b.claim_turn("t1").expect("claim").is_none(), "young: held");
3134 age_file(&path);
3135 assert!(b.claim_turn("t1").expect("claim").is_some(), "old: stale");
3136 let lease = a.turn_path("t2");
3138 let lock = TurnLock::take(&lease).expect("take").expect("lock");
3139 assert!(TurnLock::take(&lease).expect("take").is_none());
3140 drop(lock);
3141 assert!(TurnLock::take(&lease).expect("take").is_some());
3142 failpoint::force_no_link(false);
3143 }
3144
3145 #[test]
3146 fn remove_if_carries_removes_only_the_expected_content() {
3147 let (_tmp, a, _b) = lease_store();
3148 std::fs::create_dir_all(a.root()).expect("dir");
3149 let p = a.root().join("x.turn.lock");
3150 std::fs::write(&p, "mine").expect("write");
3151 assert!(!remove_if_carries(&p, "other"));
3152 assert_eq!(std::fs::read_to_string(&p).expect("kept"), "mine");
3153 assert!(remove_if_carries(&p, "mine"));
3154 assert!(!p.exists());
3155 assert!(!remove_if_carries(&p, "mine"), "absent is not a removal");
3156 }
3157
3158 #[test]
3159 fn a_dropped_lock_does_not_remove_a_lock_taken_over_since() {
3160 let (_tmp, a, _b) = lease_store();
3161 std::fs::create_dir_all(a.root()).expect("dir");
3162 let lease = a.turn_path("t1");
3163 let lock = TurnLock::take(&lease).expect("take").expect("lock");
3164 let path = lock.path.clone();
3165 std::fs::write(&path, "someone-else").expect("replace");
3166 drop(lock);
3167 assert_eq!(
3168 std::fs::read_to_string(&path).expect("kept"),
3169 "someone-else"
3170 );
3171 }
3172
3173 #[test]
3174 fn concurrent_takeovers_of_a_stale_lease_have_one_winner() {
3175 let (_tmp, a, _b) = lease_store();
3176 drop(a.claim_turn("t1").expect("claim").expect("held"));
3177 std::fs::write(
3178 a.turn_path("t1"),
3179 serde_json::to_string(&TurnRecord {
3180 token: "gone".into(),
3181 pid: 1,
3182 beat_at: Timestamp::from_second(1).expect("ts"),
3183 })
3184 .expect("json"),
3185 )
3186 .expect("write");
3187 let wins: Vec<_> = std::thread::scope(|sc| {
3188 let hs: Vec<_> = (0..8)
3189 .map(|_| {
3190 let s = a.clone();
3191 sc.spawn(move || s.claim_turn("t1").expect("claim"))
3192 })
3193 .collect();
3194 hs.into_iter().map(|h| h.join().expect("join")).collect()
3195 });
3196 assert_eq!(wins.iter().filter(|w| w.is_some()).count(), 1);
3197 }
3198
3199 fn age_file(path: &Path) {
3200 let f = std::fs::OpenOptions::new()
3201 .write(true)
3202 .open(path)
3203 .expect("open");
3204 f.set_modified(std::time::SystemTime::now() - std::time::Duration::from_secs(60))
3205 .expect("age");
3206 }
3207
3208 #[test]
3209 fn a_late_taker_of_a_broken_lock_cannot_disturb_its_replacement() {
3210 let (_tmp, a, _b) = lease_store();
3211 let lease = a.turn_path("t1");
3212 let lock = lease.with_extension("turn.lock");
3213 std::fs::create_dir_all(lock.parent().expect("dir")).expect("dir");
3214 std::fs::write(&lock, "t1-dead").expect("dead lock");
3215 age_file(&lock);
3216 let b = TurnLock::take(&lease).expect("take").expect("b wins");
3218 let fresh = std::fs::read_to_string(&lock).expect("read");
3219 assert_eq!(fresh, b.token);
3220 let ticket = std::fs::read_dir(lock.parent().expect("dir"))
3223 .expect("dir")
3224 .flatten()
3225 .map(|e| e.path())
3226 .find(|p| p.to_string_lossy().ends_with(".break.0"))
3227 .expect("ticket");
3228 assert!(!create_exclusive(&ticket, "").expect("ticket"));
3229 assert!(TurnLock::take(&lease).expect("take").is_none());
3230 assert_eq!(std::fs::read_to_string(&lock).expect("read"), fresh);
3231 age_file(&lock);
3233 age_file(&ticket);
3234 std::mem::forget(b);
3235 let c = TurnLock::take(&lease)
3236 .expect("take")
3237 .expect("next generation");
3238 assert_ne!(c.token, fresh);
3239 }
3240
3241 #[test]
3242 fn a_live_ticket_blocks_and_a_stale_one_hands_over_to_the_next_generation() {
3243 let (_tmp, a, _b) = lease_store();
3244 let lease = a.turn_path("t1");
3245 let lock = lease.with_extension("turn.lock");
3246 std::fs::create_dir_all(lock.parent().expect("dir")).expect("dir");
3247 std::fs::write(&lock, "t1-dead").expect("dead lock");
3248 age_file(&lock);
3249 let t0 = lock.with_extension("lock.t1-dead.break.0");
3250 assert!(create_exclusive(&t0, "").expect("ticket"));
3251 assert!(TurnLock::take(&lease).expect("take").is_none());
3253 assert_eq!(std::fs::read_to_string(&lock).expect("read"), "t1-dead");
3254 age_file(&t0);
3256 let c = TurnLock::take(&lease).expect("take").expect("generation 1");
3257 assert_eq!(std::fs::read_to_string(&lock).expect("read"), c.token);
3258 assert!(lock.with_extension("lock.t1-dead.break.1").exists());
3259 assert!(TurnLock::take(&lease).expect("take").is_none());
3260 }
3261
3262 #[test]
3263 fn exhausted_ticket_generations_recover_once_the_sweep_ages_them_out() {
3264 let (_tmp, a, _b) = lease_store();
3265 let lease = a.turn_path("t1");
3266 let lock = lease.with_extension("turn.lock");
3267 std::fs::create_dir_all(lock.parent().expect("dir")).expect("dir");
3268 std::fs::write(&lock, "t1-dead").expect("dead lock");
3269 age_file(&lock);
3270 let tickets: Vec<_> = (0..TICKET_GENERATIONS)
3271 .map(|n| lock.with_extension(format!("lock.t1-dead.break.{n}")))
3272 .collect();
3273 for t in &tickets {
3274 assert!(create_exclusive(t, "").expect("ticket"));
3275 age_file(t);
3276 }
3277 assert!(TurnLock::take(&lease).expect("take").is_none());
3279 assert!(tickets.iter().all(|t| t.exists()));
3280 for t in &tickets {
3282 let f = std::fs::OpenOptions::new()
3283 .write(true)
3284 .open(t)
3285 .expect("open");
3286 f.set_modified(std::time::SystemTime::now() - TICKET_SWEEP_AGE * 2)
3287 .expect("age");
3288 }
3289 assert!(TurnLock::take(&lease).expect("take").is_none());
3290 assert!(TurnLock::take(&lease).expect("take").is_some());
3291 }
3292
3293 #[test]
3294 fn an_aged_empty_lock_is_broken() {
3295 let (_tmp, a, _b) = lease_store();
3296 let lease = a.turn_path("t1");
3297 let lock = lease.with_extension("turn.lock");
3298 std::fs::create_dir_all(lock.parent().expect("dir")).expect("dir");
3299 std::fs::write(&lock, "").expect("empty lock");
3300 age_file(&lock);
3301 assert!(TurnLock::take(&lease).expect("take").is_some());
3302 }
3303
3304 #[test]
3305 fn queued_text_is_durable_combined_and_drained_as_one_operator_turn() {
3306 let (tmp, talks) = store();
3307 let cfg = config(mock_agent(tmp.path(), REPLY, env("reply")));
3308 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
3309
3310 queue(&mut talk, &talks, "first", Vec::new()).expect("queue first");
3311 queue(&mut talk, &talks, "second", Vec::new()).expect("queue second");
3312 let saved = talks.get(&talk.id).expect("reload queued talk");
3313 assert_eq!(saved.pending, "first\n\nsecond");
3314 assert_eq!(saved.pending_breaks, Some(vec!["first\n\n".len()]));
3315 assert!(saved.turns.is_empty(), "a draft is not a transcript turn");
3316
3317 let drained = drain(&mut talk, &talks).expect("drain");
3318 assert_eq!(drained.as_deref(), Some("first\n\nsecond"));
3319 let saved = talks.get(&talk.id).expect("reload drained talk");
3320 assert!(saved.pending.is_empty());
3321 assert_eq!(saved.turns.len(), 1);
3322 assert_eq!(saved.turns[0].body, "first\n\nsecond");
3323 assert_eq!(saved.turns[0].breaks, Some(vec!["first\n\n".len()]));
3324 assert_eq!(saved.pending_breaks, None);
3325 }
3326
3327 #[test]
3328 fn editing_a_queued_draft_preserves_its_attachments_and_rejects_a_stale_snapshot() {
3329 let (tmp, talks) = store();
3330 let cfg = config(mock_agent(tmp.path(), REPLY, env("reply")));
3331 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
3332 let attachment = Attachment {
3333 id: "a".repeat(32),
3334 name: "shot.png".to_owned(),
3335 mime: "image/png".to_owned(),
3336 bytes: 3,
3337 };
3338
3339 queue(&mut talk, &talks, "first", vec![attachment.clone()]).expect("queue");
3340 assert!(
3341 edit_pending_text(
3342 &mut talk,
3343 &talks,
3344 "corrected",
3345 "first",
3346 std::slice::from_ref(&attachment.id),
3347 )
3348 .expect("edit")
3349 );
3350 let saved = talks.get(&talk.id).expect("reload edited draft");
3351 assert_eq!(saved.pending, "corrected");
3352 assert_eq!(saved.pending_attachments, vec![attachment]);
3353
3354 queue(&mut talk, &talks, "later", Vec::new()).expect("queue concurrent draft");
3355 assert!(
3356 !edit_pending_text(
3357 &mut talk,
3358 &talks,
3359 "stale edit",
3360 "corrected",
3361 &["a".repeat(32)],
3362 )
3363 .expect("stale edit is a conflict")
3364 );
3365 assert_eq!(
3366 talks.get(&talk.id).expect("reload after conflict").pending,
3367 "corrected\n\nlater"
3368 );
3369 assert!(
3370 !clear_pending_if_matches(&mut talk, &talks, "corrected", &["a".repeat(32)])
3371 .expect("stale clear is a conflict")
3372 );
3373 assert_eq!(
3374 talks
3375 .get(&talk.id)
3376 .expect("reload after stale clear")
3377 .pending,
3378 "corrected\n\nlater"
3379 );
3380 }
3381
3382 #[tokio::test]
3383 async fn a_reply_save_preserves_pending_accepted_while_the_cli_runs() {
3384 let (tmp, talks) = store();
3385 let slow = "#!/bin/sh\ncat >/dev/null\nsleep 0.1\nprintf reply\n";
3386 let cfg = config(mock_agent(tmp.path(), slow, BTreeMap::new()));
3387 let mut running = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
3388 let id = running.id.clone();
3389 let first = record(&mut running, &talks, "first", Vec::new()).expect("record");
3390
3391 let response_talks = talks.clone();
3392 let response_cfg = cfg.clone();
3393 let reply = tokio::spawn(async move {
3394 respond(
3395 &response_talks.claim_turn(&running.id).unwrap().unwrap(),
3396 &mut running,
3397 &response_talks,
3398 &response_cfg,
3399 &first,
3400 )
3401 .await
3402 });
3403 tokio::time::sleep(std::time::Duration::from_millis(20)).await;
3404
3405 let mut queued = talks.get(&id).expect("queued handle");
3406 queue(&mut queued, &talks, "next", Vec::new()).expect("queue");
3407 reply.await.expect("join").expect("reply");
3408
3409 let saved = talks.get(&id).expect("reload");
3410 assert_eq!(saved.pending, "next");
3411 assert_eq!(saved.pending_breaks, Some(Vec::new()));
3412 assert_eq!(saved.turns.len(), 2, "operator message and reply remain");
3413 }
3414
3415 fn counting_agent(dir: &Path, id: &str, body: &str) -> AgentSpec {
3418 let calls = dir.join(format!("{id}.calls"));
3419 let script = format!(
3420 "#!/bin/sh\necho x >> '{}'\n{body}\n",
3421 calls.to_string_lossy()
3422 );
3423 let path = dir.join(format!("mock-{id}.sh"));
3424 std::fs::write(&path, script).expect("write mock");
3425 AgentSpec {
3426 id: id.to_owned(),
3427 kind: AgentKind::Command,
3428 model: None,
3429 command: vec!["sh".to_owned(), path.to_string_lossy().into_owned()],
3430 extra_args: Vec::new(),
3431 env: BTreeMap::new(),
3432 prompt_delivery: None,
3433 }
3434 }
3435
3436 fn calls(dir: &Path, id: &str) -> usize {
3437 std::fs::read_to_string(dir.join(format!("{id}.calls"))).map_or(0, |s| s.lines().count())
3438 }
3439
3440 fn chain_config(specs: Vec<AgentSpec>, ids: &[&str]) -> Config {
3441 let mut cfg = config(specs[0].clone());
3442 cfg.agents = specs;
3443 cfg.roles.chatter = Some(AgentChoice::Chain(
3444 ids.iter().map(|s| (*s).to_owned()).collect(),
3445 ));
3446 cfg
3447 }
3448
3449 #[tokio::test]
3450 async fn a_chatter_chain_falls_back_resends_the_transcript_and_sticks() {
3451 let (tmp, talks) = store();
3452 let a = counting_agent(tmp.path(), "a", "cat >/dev/null\nexit 3");
3453 let b = counting_agent(tmp.path(), "b", "cat");
3454 let cfg = chain_config(vec![a, b], &["a", "b"]);
3455 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
3456 assert_eq!(talk.agent, "a");
3457
3458 say(
3459 &talks.claim_turn(&talk.id).unwrap().unwrap(),
3460 &mut talk,
3461 &talks,
3462 &cfg,
3463 "hello there",
3464 Vec::new(),
3465 )
3466 .await
3467 .expect("turn");
3468 assert_eq!(calls(tmp.path(), "a"), 1, "each id is tried once");
3469 assert_eq!(calls(tmp.path(), "b"), 1);
3470 assert_eq!(talk.agent, "b", "the switch persists");
3471 assert!(talks.get(&talk.id).unwrap().agent == "b");
3472 let reply = talk.turns.last().unwrap();
3473 assert!(reply.body.contains("hello there"));
3474 assert!(
3475 reply.body.contains("magi task add --solo"),
3476 "a fresh seat gets the full briefing"
3477 );
3478 assert!(
3479 talk.turns
3480 .iter()
3481 .any(|t| t.body.contains("agent changed from a to b")),
3482 "the switch is noted"
3483 );
3484 }
3485
3486 #[tokio::test]
3487 async fn an_exhausted_chatter_chain_fails_like_a_single_seat_and_stays_put() {
3488 let (tmp, talks) = store();
3489 let a = counting_agent(tmp.path(), "a", "cat >/dev/null\nexit 3");
3490 let b = counting_agent(tmp.path(), "b", "cat >/dev/null\nexit 4");
3491 let cfg = chain_config(vec![a, b], &["a", "b", "a"]);
3492 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
3493
3494 let err = say(
3495 &talks.claim_turn(&talk.id).unwrap().unwrap(),
3496 &mut talk,
3497 &talks,
3498 &cfg,
3499 "hi",
3500 Vec::new(),
3501 )
3502 .await
3503 .expect_err("every agent failed");
3504 assert!(err.to_string().contains("`a`"), "{err:#}");
3505 assert_eq!(calls(tmp.path(), "a"), 1);
3506 assert_eq!(calls(tmp.path(), "b"), 1);
3507 assert_eq!(talk.agent, "a", "an exhausted chain leaves the agent alone");
3508 }
3509
3510 #[test]
3511 fn a_chatter_chain_skips_an_unknown_id_at_begin() {
3512 let (tmp, talks) = store();
3513 let b = counting_agent(tmp.path(), "b", "cat");
3514 let cfg = chain_config(vec![b], &["ghost", "b"]);
3515 let talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
3516 assert_eq!(talk.agent, "b");
3517 }
3518
3519 #[tokio::test]
3520 async fn an_explicit_agent_inside_the_chatter_chain_stays_pinned() {
3521 let (tmp, talks) = store();
3522 let a = counting_agent(tmp.path(), "a", "cat >/dev/null\nexit 3");
3523 let b = counting_agent(tmp.path(), "b", "cat");
3524 let cfg = chain_config(vec![a, b], &["a", "b"]);
3525 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), Some("a")).expect("begin");
3526 say(
3527 &talks.claim_turn(&talk.id).unwrap().unwrap(),
3528 &mut talk,
3529 &talks,
3530 &cfg,
3531 "hi",
3532 Vec::new(),
3533 )
3534 .await
3535 .expect_err("a alone, and it fails");
3536 assert_eq!(calls(tmp.path(), "b"), 0);
3537 assert_eq!(talk.agent, "a");
3538 }
3539
3540 #[tokio::test]
3541 async fn an_explicit_agent_does_not_borrow_the_chatter_chain() {
3542 let (tmp, talks) = store();
3543 let a = counting_agent(tmp.path(), "a", "cat >/dev/null\nexit 3");
3544 let b = counting_agent(tmp.path(), "b", "cat");
3545 let c = counting_agent(tmp.path(), "c", "cat >/dev/null\nexit 3");
3546 let cfg = chain_config(vec![a, b, c], &["a", "b"]);
3547 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), Some("c")).expect("begin");
3548 say(
3549 &talks.claim_turn(&talk.id).unwrap().unwrap(),
3550 &mut talk,
3551 &talks,
3552 &cfg,
3553 "hi",
3554 Vec::new(),
3555 )
3556 .await
3557 .expect_err("c alone, and it fails");
3558 assert_eq!(calls(tmp.path(), "b"), 0);
3559 }
3560
3561 #[test]
3562 fn briefing_names_the_operator_with_or_without_a_persona() {
3563 let plain = briefing(Path::new("/repo"), "en", false);
3564 let named = briefing_with(Path::new("/repo"), "en", false, None, Some("Commander"));
3565 assert!(named.starts_with(&plain));
3566 assert!(named.contains("# Addressing the operator"));
3567 assert!(named.contains("\"Commander\""));
3568 let rei = crate::persona::builtin_catalog()
3569 .into_iter()
3570 .find(|p| p.id == "rei")
3571 .expect("rei");
3572 let with = briefing_with(
3573 Path::new("/repo"),
3574 "en",
3575 false,
3576 Some(&rei),
3577 Some("Commander"),
3578 );
3579 assert!(with.contains("\"Commander\""));
3580 assert!(!with.contains("# Addressing the operator"));
3581 }
3582
3583 #[test]
3584 fn briefing_carries_a_persona_section_only_when_one_is_chosen() {
3585 let plain = briefing(Path::new("/repo"), "en", false);
3586 assert_eq!(
3587 plain,
3588 briefing_with(Path::new("/repo"), "en", false, None, None)
3589 );
3590 assert!(!plain.contains("Persona"));
3591 let rei = crate::persona::builtin_catalog()
3592 .into_iter()
3593 .find(|p| p.id == "rei")
3594 .expect("rei");
3595 let with = briefing_with(Path::new("/repo"), "en", false, Some(&rei), None);
3596 assert!(with.starts_with(&plain), "the plain briefing is untouched");
3597 assert!(with.contains("# Persona (tone only)"));
3598 assert!(with.contains("TONE ONLY"));
3599 assert!(with.contains("task ids"));
3600 assert!(with.contains("write policy"));
3601 assert!(with.contains("`magi task add`"));
3602 assert!(with.contains("Rei Ayanami"));
3603 }
3604
3605 #[test]
3606 fn a_talk_written_before_personas_still_loads() {
3607 let (tmp, talks) = store();
3608 let spec = mock_agent(tmp.path(), ECHO, BTreeMap::new());
3609 let cfg = config(spec);
3610 let talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
3611 let path = talks.root.join(format!("{}.json", talk.id));
3612 let mut v: serde_json::Value =
3613 serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
3614 v.as_object_mut().unwrap().remove("persona");
3615 v.as_object_mut().unwrap().remove("persona_dirty");
3616 std::fs::write(&path, v.to_string()).unwrap();
3617 let loaded = talks.get(&talk.id).expect("old record loads");
3618 assert_eq!(loaded.persona, "");
3619 assert!(!loaded.persona_dirty);
3620 }
3621
3622 #[test]
3623 fn the_briefing_files_with_solo_or_the_chosen_implementer_count() {
3624 let repo = Path::new("/repo");
3625 let solo = briefing_for(repo, "", false, None, None, 1);
3626 assert_eq!(solo, briefing(repo, "", false));
3627 assert!(solo.contains("magi task add --solo --repo"));
3628 assert!(solo.contains("magi task add --solo --attach"));
3629 for n in [2u8, 3] {
3630 let b = briefing_for(repo, "", false, None, None, n);
3631 assert!(
3632 b.contains(&format!("magi task add --implementers {n} --repo")),
3633 "{b}"
3634 );
3635 assert!(b.contains(&format!("magi task add --implementers {n} --attach")));
3636 assert!(!b.contains("task add --solo"), "{b}");
3637 assert!(!b.contains("Use --solo"), "{b}");
3638 }
3639 }
3640
3641 #[test]
3642 fn begin_with_applies_remembered_choices_and_drops_unfit_ones_alone() {
3643 let (tmp, talks) = store();
3644 let first = mock_agent(tmp.path(), ECHO, BTreeMap::new());
3645 let mut second = first.clone();
3646 second.id = "second".to_owned();
3647 let mut cfg = config(first.clone());
3648 cfg.agents.push(second.clone());
3649 let open = |p: &Preferred| {
3650 begin_with(&talks, &cfg, tmp.path().to_owned(), None, p).expect("begin")
3651 };
3652
3653 let talk = open(&Preferred {
3654 agent: Some("second".into()),
3655 persona: Some("rei".into()),
3656 implementers: Some(i64::from(check_implementers(3, &cfg).unwrap_or(1))),
3657 });
3658 assert_eq!(talk.agent, "second");
3659 assert!(
3660 !talk.fallback,
3661 "a remembered non-head agent is an explicit choice"
3662 );
3663 assert_eq!(talk.persona, "rei");
3664 assert_eq!(talk.implementers, check_implementers(3, &cfg).unwrap_or(1));
3665 assert!(!talk.persona_dirty && !talk.implementers_dirty);
3666
3667 let head = open(&Preferred {
3669 agent: Some(first.id.clone()),
3670 ..Preferred::default()
3671 });
3672 assert!(head.fallback);
3673
3674 for implementers in [0, 4, -1, 1000] {
3676 let t = open(&Preferred {
3677 agent: Some("gone".into()),
3678 persona: Some("no-such-persona".into()),
3679 implementers: Some(implementers),
3680 });
3681 assert_eq!(t.agent, first.id);
3682 assert!(t.fallback);
3683 assert_eq!(t.persona, "");
3684 assert_eq!(t.implementers, 1);
3685 }
3686
3687 let t = open(&Preferred {
3689 agent: Some("second".into()),
3690 persona: Some("default".into()),
3691 implementers: Some(9),
3692 });
3693 assert_eq!(
3694 (t.agent.as_str(), t.persona.as_str(), t.implementers),
3695 ("second", "", 1)
3696 );
3697
3698 let strict = begin_with(
3700 &talks,
3701 &cfg,
3702 tmp.path().to_owned(),
3703 Some("first-unknown"),
3704 &Preferred {
3705 agent: Some("second".into()),
3706 ..Preferred::default()
3707 },
3708 );
3709 assert!(strict.is_err());
3710 }
3711
3712 #[test]
3713 fn remembered_agent_can_open_when_the_chatter_chain_cannot_resolve() {
3714 let (tmp, talks) = store();
3715 let spec = mock_agent(tmp.path(), ECHO, BTreeMap::new());
3716 let cfg = chain_config(vec![spec.clone()], &["missing-chatter"]);
3719 assert!(begin(&talks, &cfg, tmp.path().to_owned(), None).is_err());
3720 let talk = begin_with(
3721 &talks,
3722 &cfg,
3723 tmp.path().to_owned(),
3724 None,
3725 &Preferred {
3726 agent: Some(spec.id.clone()),
3727 ..Preferred::default()
3728 },
3729 )
3730 .expect("a valid remembered agent does not require a default chain");
3731 assert_eq!(talk.agent, spec.id);
3732 assert!(!talk.fallback);
3733 assert_eq!(talks.get(&talk.id).unwrap().agent, spec.id);
3734 assert!(
3735 begin_with(
3736 &talks,
3737 &cfg,
3738 tmp.path().to_owned(),
3739 None,
3740 &Preferred {
3741 agent: Some("missing-preference".into()),
3742 ..Preferred::default()
3743 },
3744 )
3745 .is_err()
3746 );
3747 }
3748
3749 #[test]
3750 fn implementers_are_validated_and_old_records_load_as_solo() {
3751 let (tmp, talks) = store();
3752 let cfg = config(mock_agent(tmp.path(), ECHO, BTreeMap::new()));
3753 assert_eq!(check_implementers(1, &cfg), Ok(1));
3754 assert_eq!(check_implementers(3, &cfg), Ok(3));
3755 assert!(check_implementers(0, &cfg).is_err());
3756 assert!(check_implementers(4, &cfg).is_err());
3757 let mut empty = cfg.clone();
3758 empty.agents.clear();
3759 assert!(check_implementers(2, &empty).is_err());
3760
3761 let talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
3762 let path = talks.path_of(&talk.id);
3763 let mut v: serde_json::Value =
3764 serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
3765 v.as_object_mut().unwrap().remove("implementers");
3766 v.as_object_mut().unwrap().remove("implementers_dirty");
3767 std::fs::write(&path, v.to_string()).unwrap();
3768 let loaded = talks.get(&talk.id).expect("load");
3769 assert_eq!(loaded.implementers, 1);
3770 assert!(!loaded.implementers_dirty);
3771 }
3772
3773 #[tokio::test]
3774 async fn an_implementers_switch_is_noted_once_and_kept_across_a_failed_turn() {
3775 let (tmp, talks) = store();
3776 let spec = mock_agent(tmp.path(), ECHO, BTreeMap::new());
3777 let cfg = config(spec);
3778 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
3779 let lease = talks.claim_turn(&talk.id).unwrap().unwrap();
3780 say(&lease, &mut talk, &talks, &cfg, "hello", Vec::new())
3781 .await
3782 .expect("first turn");
3783
3784 assert!(switch_implementers(&mut talk, &talks, 2).expect("switch"));
3785 assert!(!switch_implementers(&mut talk, &talks, 2).expect("same"));
3786 assert!(talk.implementers_dirty);
3787 say(&lease, &mut talk, &talks, &cfg, "next", Vec::new())
3788 .await
3789 .expect("turn");
3790 let prompt = &talk.turns.last().unwrap().body;
3791 assert!(prompt.contains("# Task filing update"), "{prompt}");
3792 assert!(prompt.contains("--implementers 2"));
3793 assert!(!talk.implementers_dirty, "cleared after a successful turn");
3794
3795 say(&lease, &mut talk, &talks, &cfg, "again", Vec::new())
3796 .await
3797 .expect("turn");
3798 assert!(
3799 !talk
3800 .turns
3801 .last()
3802 .unwrap()
3803 .body
3804 .contains("# Task filing update")
3805 );
3806
3807 let mut no_sessions = cfg.clone();
3809 no_sessions.graph.sessions = false;
3810 say(&lease, &mut talk, &talks, &no_sessions, "one", Vec::new())
3811 .await
3812 .expect("turn");
3813 say(&lease, &mut talk, &talks, &no_sessions, "two", Vec::new())
3814 .await
3815 .expect("turn");
3816 assert!(talk.turns.last().unwrap().body.contains("--implementers 2"));
3817 }
3818
3819 #[tokio::test]
3820 async fn a_persona_switch_notes_marks_dirty_and_updates_the_next_turn_once() {
3821 let (tmp, talks) = store();
3822 let spec = mock_agent(tmp.path(), ECHO, BTreeMap::new());
3823 let cfg = config(spec);
3824 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
3825 let lease = talks.claim_turn(&talk.id).unwrap().unwrap();
3826 say(&lease, &mut talk, &talks, &cfg, "hello", Vec::new())
3827 .await
3828 .expect("first turn");
3829 assert!(!talk.turns[1].body.contains("Persona"));
3830
3831 assert!(switch_persona(&mut talk, &talks, "misato").expect("switch"));
3832 assert!(!switch_persona(&mut talk, &talks, "misato").expect("same"));
3833 assert!(talk.persona_dirty);
3834 assert!(talk.turns.last().unwrap().body.contains("persona changed"));
3835
3836 say(&lease, &mut talk, &talks, &cfg, "next", Vec::new())
3837 .await
3838 .expect("turn");
3839 let prompt = &talk.turns.last().unwrap().body;
3840 assert!(prompt.contains("# Persona update"), "{prompt}");
3841 assert!(prompt.contains("Misato Katsuragi"));
3842 assert!(!talk.persona_dirty, "cleared after a successful turn");
3843
3844 say(&lease, &mut talk, &talks, &cfg, "again", Vec::new())
3845 .await
3846 .expect("turn");
3847 assert!(!talk.turns.last().unwrap().body.contains("# Persona update"));
3848
3849 assert!(switch_persona(&mut talk, &talks, "default").expect("back"));
3850 assert_eq!(talk.persona, "");
3851 say(&lease, &mut talk, &talks, &cfg, "plain", Vec::new())
3852 .await
3853 .expect("turn");
3854 assert!(
3855 talk.turns
3856 .last()
3857 .unwrap()
3858 .body
3859 .contains("turned the persona off")
3860 );
3861
3862 assert!(switch_persona(&mut talk, &talks, "rei").expect("rei"));
3864 let mut no_sessions = cfg.clone();
3865 no_sessions.graph.sessions = false;
3866 say(&lease, &mut talk, &talks, &no_sessions, "one", Vec::new())
3867 .await
3868 .expect("turn");
3869 say(&lease, &mut talk, &talks, &no_sessions, "two", Vec::new())
3870 .await
3871 .expect("turn");
3872 let last = &talk.turns.last().unwrap().body;
3873 assert!(!talk.persona_dirty);
3874 assert!(last.contains("# Persona (tone only)"), "{last}");
3875 assert!(last.contains("Rei Ayanami"));
3876 }
3877
3878 #[tokio::test]
3879 async fn the_first_turn_carries_the_briefing_and_later_turns_do_not() {
3880 let (tmp, talks) = store();
3881 let spec = mock_agent(tmp.path(), ECHO, BTreeMap::new());
3882 let cfg = config(spec);
3883 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
3884
3885 say(
3886 &talks.claim_turn(&talk.id).unwrap().unwrap(),
3887 &mut talk,
3888 &talks,
3889 &cfg,
3890 "what does the queue module do?",
3891 Vec::new(),
3892 )
3893 .await
3894 .expect("first turn");
3895 let first_prompt = &talk.turns[1].body;
3896 assert!(first_prompt.contains("magi task add --solo"));
3897 assert!(first_prompt.contains("what does the queue module do?"));
3898
3899 say(
3900 &talks.claim_turn(&talk.id).unwrap().unwrap(),
3901 &mut talk,
3902 &talks,
3903 &cfg,
3904 "and how is it locked?",
3905 Vec::new(),
3906 )
3907 .await
3908 .expect("second turn");
3909 let second_prompt = &talk.turns[3].body;
3910 assert!(
3911 !second_prompt.contains("magi task add --solo"),
3912 "the briefing is sent once, not on every turn: {second_prompt}"
3913 );
3914 assert!(second_prompt.contains("and how is it locked?"));
3915 }
3916
3917 #[tokio::test]
3918 async fn switching_agent_resets_the_seat_notes_it_and_resends_the_transcript() {
3919 let (tmp, talks) = store();
3920 let a = mock_agent(tmp.path(), ECHO, BTreeMap::new());
3921 let mut b = a.clone();
3922 b.id = "other".to_owned();
3923 let mut cfg = config(a.clone());
3924 cfg.agents.push(b.clone());
3925 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), Some(&a.id)).expect("begin");
3926 say(
3927 &talks.claim_turn(&talk.id).unwrap().unwrap(),
3928 &mut talk,
3929 &talks,
3930 &cfg,
3931 "remember the walrus",
3932 Vec::new(),
3933 )
3934 .await
3935 .expect("first turn");
3936 let old_session = talk.seat.claude_session.clone();
3937 assert_eq!(talk.seat.turns, 1);
3938
3939 assert!(switch_agent(&mut talk, &talks, &b).expect("switch"));
3940 assert_eq!(talk.agent, "other");
3941 assert_eq!(talk.seat.turns, 0);
3942 assert_eq!(talk.seat.agent, "other");
3943 assert_ne!(talk.seat.claude_session, old_session);
3944 let note = talk.turns.last().expect("note");
3945 assert_eq!(note.who, Who::Agent);
3946 assert!(note.body.starts_with(MAGI_NOTE), "{}", note.body);
3947 assert!(note.body.contains("changed from"), "{}", note.body);
3948 assert_eq!(talks.get(&talk.id).expect("reload").agent, "other");
3949
3950 let before = talk.turns.len();
3951 assert!(!switch_agent(&mut talk, &talks, &b).expect("same agent"));
3952 assert_eq!(talk.turns.len(), before, "a no-op writes no note");
3953
3954 say(
3955 &talks.claim_turn(&talk.id).unwrap().unwrap(),
3956 &mut talk,
3957 &talks,
3958 &cfg,
3959 "what did I say?",
3960 Vec::new(),
3961 )
3962 .await
3963 .expect("turn after switch");
3964 let prompt = &talk.turns.last().expect("reply").body;
3965 assert!(prompt.contains("remember the walrus"), "{prompt}");
3966 assert!(prompt.contains("## magi"), "{prompt}");
3967 assert!(prompt.contains("what did I say?"), "{prompt}");
3968 }
3969
3970 #[tokio::test]
3971 async fn say_appends_the_operator_turn_then_the_agent_turn() {
3972 let (tmp, talks) = store();
3973 let spec = mock_agent(tmp.path(), REPLY, env("go ahead"));
3974 let cfg = config(spec);
3975 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
3976
3977 say(
3978 &talks.claim_turn(&talk.id).unwrap().unwrap(),
3979 &mut talk,
3980 &talks,
3981 &cfg,
3982 "can I rename this function?",
3983 Vec::new(),
3984 )
3985 .await
3986 .expect("say");
3987
3988 assert_eq!(talk.turns.len(), 2);
3989 assert_eq!(talk.turns[0].who, Who::Operator);
3990 assert_eq!(talk.turns[0].body, "can I rename this function?");
3991 assert_eq!(talk.turns[1].who, Who::Agent);
3992 assert_eq!(talk.turns[1].body, "go ahead");
3993 assert_eq!(talks.get(&talk.id).expect("get").turns, talk.turns);
3994 }
3995
3996 #[tokio::test]
3997 async fn a_failed_turn_keeps_the_operator_message_and_says_what_happened() {
3998 let (tmp, talks) = store();
3999 let spec = mock_agent(tmp.path(), BROKEN, BTreeMap::new());
4000 let cfg = config(spec);
4001 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4002
4003 let err = say(
4004 &talks.claim_turn(&talk.id).unwrap().unwrap(),
4005 &mut talk,
4006 &talks,
4007 &cfg,
4008 "check the tests",
4009 Vec::new(),
4010 )
4011 .await
4012 .expect_err("a turn with no answer is an error");
4013 assert!(err.to_string().contains("no answer"), "{err}");
4014
4015 let on_disk = talks.get(&talk.id).expect("get");
4016 assert_eq!(on_disk.turns.len(), 2);
4017 assert_eq!(on_disk.turns[0].body, "check the tests");
4018 let note = &on_disk.turns[1];
4019 assert_eq!(note.who, Who::Agent);
4020 assert!(note.body.starts_with(MAGI_NOTE), "{}", note.body);
4021 assert!(note.body.contains("your message is saved"));
4022 }
4023
4024 #[tokio::test]
4030 async fn a_passing_write_failure_while_saving_the_reply_does_not_lose_it() {
4031 let (tmp, talks) = store();
4032 let spec = mock_agent(tmp.path(), REPLY, env("go ahead"));
4033 let cfg = config(spec);
4034 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4035
4036 let text =
4037 record(&mut talk, &talks, "can I rename this function?", Vec::new()).expect("record");
4038 failpoint::force_put_failures(PUT_RETRIES - 1);
4041 respond(
4042 &talks.claim_turn(&talk.id).unwrap().unwrap(),
4043 &mut talk,
4044 &talks,
4045 &cfg,
4046 &text,
4047 )
4048 .await
4049 .expect("respond must survive a write failure its own retries can outlast");
4050
4051 assert_eq!(talk.turns.len(), 2);
4052 assert_eq!(talk.turns[1].who, Who::Agent);
4053 assert_eq!(talk.turns[1].body, "go ahead");
4054 let on_disk = talks.get(&talk.id).expect("get");
4055 assert_eq!(
4056 on_disk.turns, talk.turns,
4057 "the reply must reach disk despite the early write failures"
4058 );
4059 }
4060
4061 #[tokio::test]
4067 async fn a_persistent_write_failure_while_saving_the_reply_is_never_silent() {
4068 let (tmp, talks) = store();
4069 let spec = mock_agent(tmp.path(), REPLY, env("go ahead"));
4070 let cfg = config(spec);
4071 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4072
4073 let text = record(&mut talk, &talks, "check the tests", Vec::new()).expect("record");
4074 failpoint::force_put_failures(PUT_RETRIES);
4079 let err = respond(
4080 &talks.claim_turn(&talk.id).unwrap().unwrap(),
4081 &mut talk,
4082 &talks,
4083 &cfg,
4084 &text,
4085 )
4086 .await
4087 .expect_err("a reply that cannot be saved must be reported, not swallowed");
4088 assert!(err.to_string().contains("could not be saved"), "{err}");
4089
4090 let on_disk = talks.get(&talk.id).expect("get");
4091 assert_eq!(
4092 on_disk.turns.len(),
4093 2,
4094 "the operator turn plus a visible note"
4095 );
4096 assert_eq!(on_disk.turns[0].body, "check the tests");
4097 let note = &on_disk.turns[1];
4098 assert_eq!(note.who, Who::Agent);
4099 assert!(note.body.starts_with(MAGI_NOTE), "{}", note.body);
4100 assert!(
4101 note.body.contains("could not be saved"),
4102 "the operator must be told the reply is missing, not left staring \
4103 at a gap with no explanation: {}",
4104 note.body
4105 );
4106 assert_eq!(
4107 talk.turns, on_disk.turns,
4108 "the in-memory talk must match what actually landed on disk"
4109 );
4110
4111 let artifacts = talks.artifacts_of(&talk.id);
4114 let stash = std::fs::read_dir(&artifacts)
4115 .expect("artifacts dir")
4116 .filter_map(|e| e.ok())
4117 .find(|e| e.file_name().to_string_lossy().ends_with("-lost.txt"))
4118 .expect("a stash file for the lost reply");
4119 let stashed = std::fs::read_to_string(stash.path()).expect("read stash");
4120 assert_eq!(stashed, "go ahead");
4121
4122 assert_eq!(
4130 on_disk.seat.turns, 1,
4131 "the note's write must carry the turn the CLI actually took"
4132 );
4133 assert_eq!(
4134 on_disk.seat.claude_session, talk.seat.claude_session,
4135 "the session id handed to the CLI must survive the failed reply"
4136 );
4137 assert_eq!(on_disk.seat.captured_session, talk.seat.captured_session);
4138 assert!(
4139 agent::has_session(AgentKind::Command, &on_disk.seat, cfg.graph.sessions),
4140 "the next turn must resume, not open the same session id twice"
4141 );
4142 }
4143
4144 #[tokio::test]
4149 async fn a_write_failure_that_also_loses_the_note_still_reports_it() {
4150 let (tmp, talks) = store();
4151 let spec = mock_agent(tmp.path(), REPLY, env("go ahead"));
4152 let cfg = config(spec);
4153 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4154
4155 let text = record(&mut talk, &talks, "check the tests", Vec::new()).expect("record");
4156 failpoint::force_put_failures(PUT_RETRIES * 2);
4159 let err = respond(
4160 &talks.claim_turn(&talk.id).unwrap().unwrap(),
4161 &mut talk,
4162 &talks,
4163 &cfg,
4164 &text,
4165 )
4166 .await
4167 .expect_err("neither the reply nor the note could be saved");
4168 assert!(err.to_string().contains("could not be saved"), "{err}");
4169
4170 assert_eq!(talk.turns.len(), 1, "only the operator's own turn");
4171 let on_disk = talks.get(&talk.id).expect("get");
4172 assert_eq!(on_disk.turns.len(), 1);
4173
4174 assert_eq!(
4184 on_disk.seat.turns, 0,
4185 "an unwritable file cannot record the turn the CLI took"
4186 );
4187 assert_eq!(
4188 talk.seat.turns, 1,
4189 "the in-memory seat still reports the turn the CLI actually took"
4190 );
4191 assert_eq!(
4192 on_disk.seat.claude_session, talk.seat.claude_session,
4193 "the session id was minted at `begin` and never changes here"
4194 );
4195 }
4196
4197 #[tokio::test]
4201 async fn attachments_reach_the_prompt_and_an_empty_body_is_still_a_turn() {
4202 let (tmp, talks) = store();
4203 let spec = mock_agent(tmp.path(), ECHO, BTreeMap::new());
4204 let cfg = config(spec);
4205 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4206
4207 let att = talks
4208 .put_attachment(
4209 &talk.id,
4210 "image/png",
4211 "screenshot.png",
4212 b"pretend-png-bytes",
4213 )
4214 .expect("put attachment");
4215
4216 say(
4217 &talks.claim_turn(&talk.id).unwrap().unwrap(),
4218 &mut talk,
4219 &talks,
4220 &cfg,
4221 "",
4222 vec![att.clone()],
4223 )
4224 .await
4225 .expect("an empty body with an attachment is still a turn");
4226
4227 let operator_turn = &talk.turns[0];
4228 assert_eq!(operator_turn.who, Who::Operator);
4229 assert_eq!(operator_turn.body, "");
4230 assert_eq!(operator_turn.attachments, vec![att.clone()]);
4231
4232 let prompt = &talk.turns[1].body;
4233 let expected_path = talks
4234 .attachments_dir(&talk.id)
4235 .join(format!("{}.png", att.id));
4236 assert!(
4237 prompt.contains(&expected_path.display().to_string()),
4238 "the agent must be told the attachment's absolute path: {prompt}"
4239 );
4240 assert!(prompt.contains("image/png"), "and its mime: {prompt}");
4241 }
4242
4243 #[test]
4252 fn attachment_path_is_absolute_even_when_the_store_root_is_relative() {
4253 let talks = Talks::at(PathBuf::from("relative-talks-root-for-this-test"));
4254 let att = Attachment {
4255 id: "0".repeat(32),
4256 name: "shot.png".to_owned(),
4257 mime: "image/png".to_owned(),
4258 bytes: 3,
4259 };
4260 let path = talks
4261 .attachment_path("some-talk-id", &att)
4262 .expect("a supported mime always yields a path");
4263 assert!(
4264 path.is_absolute(),
4265 "must be absolute even off a relative store root: {}",
4266 path.display()
4267 );
4268 }
4269
4270 #[tokio::test]
4271 async fn a_turn_past_the_configured_talk_timeout_is_reported_with_that_timeout() {
4272 let (tmp, talks) = store();
4277 let slow = mock_agent(
4278 tmp.path(),
4279 "#!/bin/sh\ncat >/dev/null\nsleep 2\n",
4280 BTreeMap::new(),
4281 );
4282 let mut cfg = config(slow);
4283 cfg.graph.timeout_talk = 1;
4284 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4285
4286 let err = say(
4287 &talks.claim_turn(&talk.id).unwrap().unwrap(),
4288 &mut talk,
4289 &talks,
4290 &cfg,
4291 "check the tests",
4292 Vec::new(),
4293 )
4294 .await
4295 .expect_err("a turn that never answers is an error");
4296 assert!(
4297 err.to_string().contains("did not answer within 1s"),
4298 "{err}"
4299 );
4300
4301 let on_disk = talks.get(&talk.id).expect("get");
4302 let note = on_disk.turns.last().expect("a note turn was recorded");
4303 assert!(
4304 note.body.contains("did not answer within 1s"),
4305 "the transcript must show the configured timeout: {}",
4306 note.body
4307 );
4308 }
4309
4310 #[test]
4311 fn closing_is_idempotent_and_a_closed_talk_takes_no_more_turns() {
4312 let (tmp, talks) = store();
4313 let spec = mock_agent(tmp.path(), REPLY, env("hi"));
4314 let cfg = config(spec);
4315 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4316
4317 close(&mut talk, &talks).expect("close");
4318 assert_eq!(talk.status, TalkStatus::Closed);
4319 close(&mut talk, &talks).expect("closing twice is not an error");
4320
4321 let err =
4322 record(&mut talk, &talks, "still there?", Vec::new()).expect_err("closed talks refuse");
4323 assert!(err.to_string().contains("closed"));
4324 let _ = &cfg; }
4326
4327 #[tokio::test]
4328 async fn a_close_that_lands_while_a_turn_is_in_flight_is_not_undone_by_the_reply() {
4329 let (tmp, talks) = store();
4330 let spec = mock_agent(tmp.path(), REPLY, env("here you go"));
4331 let cfg = config(spec);
4332 let mut in_flight = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4335
4336 let mut closed_elsewhere = talks.get(&in_flight.id).expect("reread");
4340 close(&mut closed_elsewhere, &talks).expect("close");
4341 assert_eq!(
4342 talks.get(&in_flight.id).expect("reread").status,
4343 TalkStatus::Closed,
4344 "the close landed on disk before the turn finished"
4345 );
4346
4347 assert_eq!(in_flight.status, TalkStatus::Open);
4351 respond(
4352 &talks.claim_turn(&in_flight.id).unwrap().unwrap(),
4353 &mut in_flight,
4354 &talks,
4355 &cfg,
4356 "one more question",
4357 )
4358 .await
4359 .expect("the turn itself still completes");
4360
4361 let on_disk = talks.get(&in_flight.id).expect("reread");
4362 assert_eq!(
4363 on_disk.status,
4364 TalkStatus::Closed,
4365 "a close must stick even when a turn that started before it finishes after it"
4366 );
4367 assert!(
4370 on_disk.turns.iter().any(|t| t.body == "here you go"),
4371 "the in-flight turn's own reply is still recorded: {:?}",
4372 on_disk.turns
4373 );
4374 }
4375
4376 #[test]
4377 fn a_close_that_lands_before_record_is_called_is_not_undone_by_it() {
4378 let (tmp, talks) = store();
4379 let spec = mock_agent(tmp.path(), REPLY, env("hi"));
4380 let cfg = config(spec);
4381 let mut stale = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4384
4385 let mut closed_elsewhere = talks.get(&stale.id).expect("reread");
4388 close(&mut closed_elsewhere, &talks).expect("close");
4389 assert_eq!(
4390 talks.get(&stale.id).expect("reread").status,
4391 TalkStatus::Closed,
4392 "the close landed on disk before record was called"
4393 );
4394
4395 assert_eq!(stale.status, TalkStatus::Open);
4399 let err = record(&mut stale, &talks, "still there?", Vec::new())
4400 .expect_err("a close that landed first must be honored, not overwritten");
4401 assert!(err.to_string().contains("closed"));
4402
4403 let on_disk = talks.get(&stale.id).expect("reread");
4404 assert_eq!(
4405 on_disk.status,
4406 TalkStatus::Closed,
4407 "record must not resurrect a conversation closed while its snapshot was stale"
4408 );
4409 assert!(
4410 on_disk.turns.is_empty(),
4411 "the rejected turn must not have been appended: {:?}",
4412 on_disk.turns
4413 );
4414 let _ = &cfg; }
4416
4417 #[test]
4418 fn close_blocks_on_records_guard_rather_than_interleaving_with_it() {
4419 let (tmp, talks) = store();
4420 let spec = mock_agent(tmp.path(), REPLY, env("hi"));
4421 let cfg = config(spec);
4422 let talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4423
4424 let held = talks.guard().unwrap();
4428
4429 let talks2 = talks.clone();
4430 let id = talk.id.clone();
4431 let closing = std::thread::spawn(move || {
4432 let mut talk = talks2.get(&id).expect("get");
4433 close(&mut talk, &talks2).expect("close");
4434 });
4435
4436 std::thread::sleep(Duration::from_millis(50));
4437 assert!(
4438 !closing.is_finished(),
4439 "close must wait for the guard, not read and write while it is held - \
4440 a re-read alone narrows this window without closing it"
4441 );
4442
4443 drop(held);
4444 closing.join().expect("close thread panicked");
4445
4446 assert_eq!(
4447 talks.get(&talk.id).expect("reread").status,
4448 TalkStatus::Closed,
4449 "once the guard is free, close still lands"
4450 );
4451 let _ = &cfg; }
4453
4454 #[test]
4455 fn reopening_a_closed_talk_lets_it_take_turns_again_and_reopening_twice_is_not_an_error() {
4456 let (tmp, talks) = store();
4457 let spec = mock_agent(tmp.path(), REPLY, env("hi"));
4458 let cfg = config(spec);
4459 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4460
4461 close(&mut talk, &talks).expect("close");
4462 assert_eq!(talk.status, TalkStatus::Closed);
4463
4464 reopen(&mut talk, &talks).expect("reopen");
4465 assert_eq!(talk.status, TalkStatus::Open);
4466 assert_eq!(
4467 talks.get(&talk.id).expect("reread").status,
4468 TalkStatus::Open
4469 );
4470
4471 reopen(&mut talk, &talks).expect("reopening an open talk is not an error");
4473 assert_eq!(talk.status, TalkStatus::Open);
4474
4475 record(&mut talk, &talks, "one more thing", Vec::new())
4476 .expect("a reopened talk takes turns again");
4477 let _ = &cfg; }
4479
4480 #[test]
4481 fn removing_a_talk_deletes_its_record_and_artifacts_and_refuses_an_unknown_id() {
4482 let (tmp, talks) = store();
4483 let spec = mock_agent(tmp.path(), REPLY, env("hi"));
4484 let cfg = config(spec);
4485 let talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4486
4487 let artifacts = talks.artifacts_of(&talk.id);
4488 std::fs::create_dir_all(&artifacts).expect("create artifacts dir");
4489 std::fs::write(artifacts.join("turn-1.txt"), "hello").expect("write artifact");
4490
4491 talks.remove(&talk.id).expect("remove");
4492 assert!(!talks.path_of(&talk.id).is_file(), "the record is gone");
4493 assert!(!artifacts.is_dir(), "the artifacts directory is gone");
4494 assert!(
4495 talks.get(&talk.id).is_err(),
4496 "a removed talk cannot be read back"
4497 );
4498
4499 let err = talks
4500 .remove("nonexistent-id")
4501 .expect_err("unknown id refused");
4502 assert!(err.to_string().contains("no talk matches"), "{err}");
4503 let _ = &cfg; }
4505
4506 #[tokio::test]
4507 async fn a_delete_that_lands_while_a_turn_is_in_flight_is_not_undone_by_the_reply() {
4508 let (tmp, talks) = store();
4509 let spec = mock_agent(tmp.path(), REPLY, env("here you go"));
4510 let cfg = config(spec);
4511 let mut in_flight = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4514
4515 talks.remove(&in_flight.id).expect("remove");
4516 assert!(
4517 talks.get(&in_flight.id).is_err(),
4518 "the delete landed on disk before the turn finished"
4519 );
4520
4521 respond(
4524 &talks.claim_turn(&in_flight.id).unwrap().unwrap(),
4525 &mut in_flight,
4526 &talks,
4527 &cfg,
4528 "one more question",
4529 )
4530 .await
4531 .expect("the turn itself still completes rather than erroring");
4532
4533 assert!(
4534 talks.get(&in_flight.id).is_err(),
4535 "a delete must stick even when a turn that started before it finishes after it"
4536 );
4537 }
4538
4539 #[test]
4540 fn a_delete_that_lands_before_record_is_called_is_not_undone_by_it() {
4541 let (tmp, talks) = store();
4542 let spec = mock_agent(tmp.path(), REPLY, env("hi"));
4543 let cfg = config(spec);
4544 let mut stale = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4547
4548 talks.remove(&stale.id).expect("remove");
4549
4550 let err = record(&mut stale, &talks, "still there?", Vec::new())
4554 .expect_err("a delete that landed first must be honored, not overwritten");
4555 assert!(err.to_string().contains("deleted"), "{err}");
4556
4557 assert!(
4558 talks.get(&stale.id).is_err(),
4559 "record must not resurrect a conversation deleted while its snapshot was stale"
4560 );
4561 let _ = &cfg; }
4563
4564 #[test]
4565 fn a_delete_that_lands_before_close_is_called_is_not_undone_by_it() {
4566 let (tmp, talks) = store();
4567 let spec = mock_agent(tmp.path(), REPLY, env("hi"));
4568 let cfg = config(spec);
4569 let mut stale = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4572
4573 talks.remove(&stale.id).expect("remove");
4574
4575 let err = close(&mut stale, &talks)
4579 .expect_err("a delete that landed first must be honored, not overwritten");
4580 assert!(err.to_string().contains("deleted"), "{err}");
4581
4582 assert!(
4583 talks.get(&stale.id).is_err(),
4584 "close must not resurrect a conversation deleted while its snapshot was stale"
4585 );
4586 let _ = &cfg; }
4588
4589 #[test]
4590 fn a_delete_that_lands_before_reopen_is_called_is_not_undone_by_it() {
4591 let (tmp, talks) = store();
4592 let spec = mock_agent(tmp.path(), REPLY, env("hi"));
4593 let cfg = config(spec);
4594 let mut stale = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
4597 close(&mut stale, &talks).expect("close");
4598
4599 talks.remove(&stale.id).expect("remove");
4600
4601 let err = reopen(&mut stale, &talks)
4605 .expect_err("a delete that landed first must be honored, not overwritten");
4606 assert!(err.to_string().contains("deleted"), "{err}");
4607
4608 assert!(
4609 talks.get(&stale.id).is_err(),
4610 "reopen must not resurrect a conversation deleted while its snapshot was stale"
4611 );
4612 let _ = &cfg; }
4614
4615 #[test]
4616 fn list_puts_open_talks_before_closed_ones() {
4617 let (tmp, talks) = store();
4618 let make = |id: &str, status: TalkStatus| {
4619 let mut t = Talk {
4620 pending_breaks: None,
4621 schema: SCHEMA,
4622 id: id.to_owned(),
4623 repo: tmp.path().to_owned(),
4624 agent: "mock".to_owned(),
4625 status,
4626 turns: Vec::new(),
4627 pending: String::new(),
4628 pending_attachments: Vec::new(),
4629 fallback: false,
4630 persona: String::new(),
4631 persona_dirty: false,
4632 implementers: 1,
4633 implementers_dirty: false,
4634 notified: Vec::new(),
4635 created_at: Timestamp::now(),
4636 updated_at: Timestamp::now(),
4637 seat: SeatState::new(SEAT, "mock", 7),
4638 };
4639 talks.put(&mut t).expect("put");
4640 };
4641 make("20260901-000000-0001", TalkStatus::Open);
4642 make("20260902-000000-0002", TalkStatus::Open);
4643 make("20260903-000000-0003", TalkStatus::Closed);
4644
4645 let ids: Vec<String> = talks.list().into_iter().map(|t| t.id).collect();
4646 assert_eq!(
4647 ids,
4648 [
4649 "20260902-000000-0002",
4650 "20260901-000000-0001",
4651 "20260903-000000-0003"
4652 ]
4653 );
4654 assert_eq!(talks.count_open(), 2);
4655 }
4656
4657 #[test]
4658 fn tasks_of_finds_only_this_talks_own_tasks() {
4659 let dir = tempfile::tempdir().expect("tempdir");
4660 let queue = Queue::at(dir.path().join("queue"));
4661
4662 let mut mine = Task::new(
4663 "rework the loader".to_owned(),
4664 "rework the loader".to_owned(),
4665 PathBuf::from("/repo"),
4666 Source::Agent {
4667 run: "20260904-014455-ab12".to_owned(),
4668 node: "chat".to_owned(),
4669 },
4670 );
4671 queue.put(&mut mine).expect("put mine");
4672
4673 let mut theirs = Task::new(
4674 "unrelated".to_owned(),
4675 "unrelated".to_owned(),
4676 PathBuf::from("/repo"),
4677 Source::Agent {
4678 run: "20260904-090000-zz99".to_owned(),
4679 node: "implement".to_owned(),
4680 },
4681 );
4682 queue.put(&mut theirs).expect("put theirs");
4683
4684 let mut human = Task::new(
4685 "typed by hand".to_owned(),
4686 "typed by hand".to_owned(),
4687 PathBuf::from("/repo"),
4688 Source::Human,
4689 );
4690 queue.put(&mut human).expect("put human");
4691
4692 let found = tasks_of(&queue, "20260904-014455-ab12");
4693 assert_eq!(found.len(), 1);
4694 assert_eq!(found[0].id, mine.id);
4695 }
4696
4697 #[test]
4698 fn the_briefing_names_solo_task_add() {
4699 let brief = briefing(Path::new("/repo"), "en", false);
4700 assert!(brief.contains("magi task add --solo"));
4701 assert!(brief.contains("/repo"));
4702 assert!(!brief.contains("Hold this conversation in"));
4703 }
4704
4705 #[test]
4711 fn the_briefing_explains_targeting_a_different_repository_by_name() {
4712 let brief = briefing(Path::new("/repo"), "en", false);
4713 assert!(brief.contains("--repo does not have to be a full path"));
4714 assert!(brief.contains("owner/repo"));
4715 assert!(brief.contains("magi repos"));
4716 assert!(brief.contains("ask the operator"));
4717 }
4718
4719 #[test]
4720 fn the_briefing_tells_the_assistant_to_pass_images_with_attach() {
4721 let brief = briefing(Path::new("/repo"), "en", false);
4722 assert!(brief.contains("--attach <path>"), "{brief}");
4723 assert!(brief.contains("deleting this conversation"), "{brief}");
4724 }
4725
4726 #[test]
4727 fn the_briefing_names_the_language_when_it_is_not_english() {
4728 let brief = briefing(Path::new("/repo"), "Japanese", false);
4729 assert!(brief.contains("Hold this conversation in Japanese"));
4730 }
4731
4732 #[test]
4733 fn the_briefing_forbids_writes_unless_the_repository_opted_in() {
4734 let read_only = briefing(Path::new("/repo"), "en", false);
4735 assert!(read_only.contains("Do not write files"));
4736 assert!(!read_only.contains("allow_write"));
4737
4738 let writable = briefing(Path::new("/repo"), "en", true);
4739 assert!(!writable.contains("Do not write files"));
4740 assert!(writable.contains("allow_write = true"));
4741 assert!(writable.contains("magi task add --solo"));
4744 assert!(writable.contains("say plainly what you"));
4745 }
4746
4747 #[test]
4748 fn the_briefing_says_the_chat_cannot_push_and_tasks_report_back() {
4749 let b = briefing_for(Path::new("/r"), "en", false, None, None, 1);
4750 assert!(
4751 b.contains("cannot send the operator a message on your own"),
4752 "{b}"
4753 );
4754 assert!(b.contains(crate::prompt::CHAT_TASK_NOTICE_HEADING));
4755 }
4756
4757 #[test]
4758 fn a_post_is_replayed_until_the_agent_answers_again() {
4759 let (_tmp, talks) = store();
4760 let mut talk = ctx_talk("mock", Vec::new());
4761 talks.put(&mut talk).expect("put");
4762 post(&talks, &talk.id, " found it ", "20260902-000000-aaaa").expect("post");
4763 let mut talk = talks.get(&talk.id).expect("get");
4764 let block = posts_since_last_reply(&talk).expect("block");
4765 assert!(block.starts_with("# Posted by a task"), "{block}");
4766 assert!(block.contains("found it"));
4767 talk.turns.push(reply("ok", None));
4768 assert!(posts_since_last_reply(&talk).is_none());
4769 assert!(post(&talks, &talk.id, " ", "r").is_err());
4770 close(&mut talk, &talks).expect("close");
4771 assert!(post(&talks, &talk.id, "late", "r").is_err());
4772 }
4773
4774 #[test]
4775 fn queue_once_accepts_a_key_a_single_time_even_after_a_drain() {
4776 let (_tmp, talks) = store();
4777 let mut talk = ctx_talk("mock", Vec::new());
4778 talks.put(&mut talk).expect("put");
4779 assert!(queue_once(&mut talk, &talks, "one", "k").expect("first"));
4780 drain(&mut talk, &talks).expect("drain");
4781 assert!(!queue_once(&mut talk, &talks, "one", "k").expect("again"));
4782 assert!(talks.get(&talk.id).expect("get").pending.is_empty());
4783 }
4784}