1use std::path::{Path, PathBuf};
12
13use anyhow::{Context, Result, bail};
14use jiff::Timestamp;
15use serde::{Deserialize, Serialize};
16
17pub const SCHEMA: u32 = 1;
20
21pub const CAP: usize = 200;
23
24#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
26#[serde(rename_all = "lowercase")]
27pub enum Severity {
28 Info,
30 Warn,
32 Error,
34}
35
36#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
38#[serde(tag = "kind", rename_all = "lowercase")]
39pub enum Link {
40 Run {
42 id: String,
44 },
45 Task {
47 id: String,
49 },
50 Url {
52 url: String,
54 },
55}
56
57#[derive(Debug, Clone, Serialize, Deserialize)]
59pub struct Notice {
60 pub id: String,
62 pub key: String,
64 pub severity: Severity,
66 pub message: String,
68 #[serde(default)]
70 pub link: Option<Link>,
71 pub first_at: Timestamp,
73 pub last_at: Timestamp,
75 #[serde(default = "one")]
77 pub count: u32,
78 #[serde(default)]
80 pub read_at: Option<Timestamp>,
81 #[serde(default)]
83 pub dismissed_at: Option<Timestamp>,
84 #[serde(default)]
87 pub subjects: Vec<String>,
88 #[serde(default)]
90 pub related_run: Option<String>,
91 #[serde(default)]
95 pub covered_by: Option<String>,
96 #[serde(default)]
100 pub since: Option<Timestamp>,
101 #[serde(default)]
103 pub cause: Option<String>,
104 #[serde(default = "schema")]
106 pub schema: u32,
107 #[serde(default)]
110 pub delivery_id: Option<String>,
111 #[serde(default = "one")]
113 pub generation: u32,
114 #[serde(default)]
116 pub delivered: u32,
117}
118
119fn one() -> u32 {
120 1
121}
122
123fn schema() -> u32 {
124 SCHEMA
125}
126
127impl Notice {
128 pub fn new(severity: Severity, key: &str, message: impl Into<String>) -> Self {
130 let now = Timestamp::now();
131 Self {
132 id: id_of(key),
133 key: key.to_owned(),
134 severity,
135 message: message.into(),
136 link: None,
137 first_at: now,
138 last_at: now,
139 count: 1,
140 read_at: None,
141 dismissed_at: None,
142 subjects: Vec::new(),
143 related_run: None,
144 covered_by: None,
145 since: None,
146 cause: None,
147 schema: SCHEMA,
148 delivery_id: Some(format!("{now}-{:016x}", crate::rng::entropy())),
149 generation: 1,
150 delivered: 0,
151 }
152 }
153
154 pub fn about<I, S>(mut self, subjects: I) -> Self
156 where
157 I: IntoIterator<Item = S>,
158 S: Into<String>,
159 {
160 self.subjects = subjects.into_iter().map(Into::into).collect();
161 self
162 }
163
164 pub fn for_run(mut self, run: Option<String>) -> Self {
166 self.related_run = run;
167 self
168 }
169
170 pub fn info(key: &str, message: impl Into<String>) -> Self {
172 Self::new(Severity::Info, key, message)
173 }
174
175 pub fn warn(key: &str, message: impl Into<String>) -> Self {
177 Self::new(Severity::Warn, key, message)
178 }
179
180 pub fn error(key: &str, message: impl Into<String>) -> Self {
182 Self::new(Severity::Error, key, message)
183 }
184
185 pub fn since(mut self, at: Option<Timestamp>) -> Self {
187 self.since = at;
188 self
189 }
190
191 pub fn cause(mut self, cause: impl Into<String>) -> Self {
193 self.cause = Some(cause.into());
194 self
195 }
196
197 pub fn link(mut self, link: Link) -> Self {
199 self.link = Some(link);
200 self
201 }
202
203 pub fn unread(&self) -> bool {
205 self.read_at.is_none() && self.dismissed_at.is_none()
206 }
207
208 pub fn raise_again(&mut self, again: &Notice, now: Timestamp) -> bool {
215 self.count = self.count.saturating_add(1);
216 let previous_last_at = self.last_at;
217 self.last_at = now;
218 if again.link.is_some() {
219 self.link = again.link.clone();
220 }
221 if again.related_run.is_some() {
222 self.related_run = again.related_run.clone();
223 }
224 if !again.subjects.is_empty() {
225 self.subjects = again.subjects.clone();
226 }
227 let escalated = again.severity > self.severity;
228 let newer_cause = match (self.since, again.since) {
232 (Some(old), Some(new)) => new > old,
233 (None, Some(new)) => {
234 new > previous_last_at || (self.covered_by.is_some() && again.covered_by.is_none())
235 }
236 _ => false,
237 };
238 self.since = self.since.max(again.since);
239 let changed_cause = again
241 .cause
242 .as_ref()
243 .is_some_and(|cause| self.cause.as_ref() != Some(cause));
244 if again.cause.is_some() {
245 self.cause = again.cause.clone();
246 }
247 let relit = escalated || newer_cause || changed_cause;
248 self.message = again.message.clone();
249 if relit {
250 self.generation = self.generation.saturating_add(1);
251 self.severity = self.severity.max(again.severity);
252 self.read_at = None;
253 self.dismissed_at = None;
254 self.covered_by = None;
255 }
256 if let Some(q) = &again.covered_by
259 && !escalated
260 && self.unread()
261 {
262 self.read_at = Some(now);
263 self.covered_by = Some(q.clone());
264 }
265 relit && self.covered_by.is_none()
266 }
267
268 pub fn mark_read(&mut self, now: Timestamp) {
270 if self.read_at.is_none() {
271 self.read_at = Some(now);
272 }
273 }
274
275 pub fn dismiss(&mut self, now: Timestamp) {
277 self.mark_read(now);
278 if self.dismissed_at.is_none() {
279 self.dismissed_at = Some(now);
280 }
281 }
282
283 fn obsolete(&self) -> bool {
286 self.key.starts_with("deputy:")
287 }
288
289 fn visible(&self) -> bool {
291 !self.obsolete() && self.dismissed_at.is_none()
292 }
293
294 fn keep_rank(&self) -> u8 {
296 if self.obsolete() {
297 0
298 } else if self.dismissed_at.is_some() {
299 1
300 } else if self.read_at.is_some() {
301 2
302 } else {
303 3
304 }
305 }
306}
307
308pub fn id_of(key: &str) -> String {
312 let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
313 for b in key.bytes() {
314 hash ^= u64::from(b);
315 hash = hash.wrapping_mul(0x0100_0000_01b3);
316 }
317 let slug: String = key
318 .chars()
319 .map(|c| {
320 if c.is_ascii_alphanumeric() {
321 c.to_ascii_lowercase()
322 } else {
323 '-'
324 }
325 })
326 .take(32)
327 .collect();
328 format!("{slug}-{hash:016x}")
329}
330
331fn valid_id(id: &str) -> bool {
334 !id.is_empty()
335 && id.len() <= 64
336 && id
337 .bytes()
338 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
339}
340
341const LOCK_WAIT: std::time::Duration = std::time::Duration::from_secs(5);
343
344const LOCK_STALE: std::time::Duration = std::time::Duration::from_secs(10);
346
347static TMP_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
349
350#[derive(Debug, Clone)]
352pub struct Notices {
353 root: PathBuf,
354}
355
356impl Notices {
357 pub fn open() -> Self {
359 Self::at(crate::run::home().join("notifications"))
360 }
361
362 pub fn at(root: PathBuf) -> Self {
364 Self { root }
365 }
366
367 pub fn root(&self) -> &Path {
369 &self.root
370 }
371
372 fn path_of(&self, id: &str) -> PathBuf {
373 self.root.join(format!("{id}.json"))
374 }
375
376 fn put(&self, n: &Notice) -> Result<()> {
377 std::fs::create_dir_all(&self.root)
378 .with_context(|| format!("create {}", self.root.display()))?;
379 let body = serde_json::to_string_pretty(n).context("serialize notice")?;
380 let path = self.path_of(&n.id);
381 let tmp = path.with_extension(format!(
384 "json.{}.{}.tmp",
385 std::process::id(),
386 TMP_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
387 ));
388 std::fs::write(&tmp, body).with_context(|| format!("write {}", tmp.display()))?;
389 if let Err(e) = std::fs::rename(&tmp, &path) {
390 let _ = std::fs::remove_file(&tmp);
391 return Err(e).with_context(|| format!("replace {}", path.display()));
392 }
393 Ok(())
394 }
395
396 pub fn get(&self, id: &str) -> Result<Notice> {
398 if !valid_id(id) {
399 bail!("`{id}` is not a notification id");
400 }
401 read_path(&self.path_of(id))
402 }
403
404 fn locked<T>(&self, id: &str, f: impl FnOnce() -> Result<T>) -> Result<T> {
413 std::fs::create_dir_all(&self.root)
414 .with_context(|| format!("create {}", self.root.display()))?;
415 let lock = self.root.join(format!("{id}.lock"));
416 let start = std::time::Instant::now();
417 let retry = crate::lock_file::Retry::new(Some(start + LOCK_WAIT));
418 let mut held = false;
419 while start.elapsed() < LOCK_WAIT {
420 match retry.create(&lock) {
421 Ok(_) => {
422 held = true;
423 break;
424 }
425 Err(_) => {
426 let stale = std::fs::metadata(&lock)
427 .and_then(|m| m.modified())
428 .ok()
429 .and_then(|t| t.elapsed().ok())
430 .is_some_and(|age| age > LOCK_STALE);
431 if stale {
432 let _ = std::fs::remove_file(&lock);
433 } else {
434 std::thread::sleep(std::time::Duration::from_millis(5));
435 }
436 }
437 }
438 }
439 let out = f();
440 if held {
441 let _ = std::fs::remove_file(&lock);
442 }
443 out
444 }
445
446 pub fn raise(&self, incoming: Notice) -> Result<Notice> {
448 self.raise_paged(incoming).map(|(n, _)| n)
449 }
450
451 pub fn raise_with(
453 &self,
454 mut incoming: Notice,
455 notify: &crate::config::Notify,
456 ) -> Result<Notice> {
457 if let Some(home) = self.root.parent()
458 && let Some(q) = covering_question(home, &incoming)
459 {
460 incoming.covered_by = Some(q);
461 }
462 let (notice, page) = self.raise_paged(incoming)?;
463 if page {
464 send_page(
465 Page {
466 run: notice
467 .related_run
468 .clone()
469 .or_else(|| match ¬ice.link {
470 Some(Link::Run { id }) => Some(id.clone()),
471 _ => None,
472 })
473 .unwrap_or_default(),
474 summary: notice.message.clone(),
475 },
476 Some(notify.clone()),
477 );
478 }
479 Ok(notice)
480 }
481
482 pub fn raise_paged(&self, incoming: Notice) -> Result<(Notice, bool)> {
484 let out = self.locked(&incoming.id.clone(), || {
485 let now = Timestamp::now();
486 let (stored, page) = match read_path(&self.path_of(&incoming.id)) {
487 Ok(mut existing) => {
488 let page = existing.raise_again(&incoming, now);
489 (existing, page)
490 }
491 Err(_) => {
492 let mut fresh = incoming;
493 if fresh.covered_by.is_some() {
494 fresh.read_at = Some(now);
495 }
496 let page = fresh.covered_by.is_none();
497 (fresh, page)
498 }
499 };
500 self.put(&stored)?;
501 Ok((stored, page))
502 })?;
503 self.prune();
504 Ok(out)
505 }
506
507 pub fn cover(&self, question: &crate::ask::Question) {
510 for n in self.all() {
511 if n.unread() && covers(question, &n) {
512 let _ = self.update(&n.id, |n| {
513 if n.unread() && covers(question, n) {
516 n.mark_read(Timestamp::now());
517 n.covered_by = Some(question.id.clone());
518 }
519 });
520 }
521 }
522 }
523
524 pub(crate) fn update(&self, id: &str, change: impl FnOnce(&mut Notice)) -> Result<Notice> {
526 if !valid_id(id) {
527 bail!("`{id}` is not a notification id");
528 }
529 self.locked(id, || {
530 let mut n = read_path(&self.path_of(id))?;
531 change(&mut n);
532 self.put(&n)?;
533 Ok(n)
534 })
535 }
536
537 pub(crate) fn all(&self) -> Vec<Notice> {
539 let mut all: Vec<Notice> = std::fs::read_dir(&self.root)
540 .into_iter()
541 .flatten()
542 .flatten()
543 .map(|e| e.path())
544 .filter(|p| p.extension().is_some_and(|x| x == "json"))
545 .filter_map(|p| read_path(&p).ok())
546 .collect();
547 all.sort_by(|a, b| b.last_at.cmp(&a.last_at).then_with(|| a.id.cmp(&b.id)));
548 all
549 }
550
551 pub fn list(&self) -> Vec<Notice> {
553 self.all().into_iter().filter(Notice::visible).collect()
554 }
555
556 pub fn count_unread(&self) -> usize {
558 self.list().iter().filter(|n| n.unread()).count()
559 }
560
561 pub fn mark_read(&self, id: &str) -> Result<Notice> {
563 let now = Timestamp::now();
564 self.update(id, |n| n.mark_read(now))
565 }
566
567 pub fn mark_all_read(&self) -> Result<usize> {
569 let now = Timestamp::now();
570 let mut changed = 0;
571 for n in self.list().into_iter().filter(Notice::unread) {
572 let done = self.update(&n.id, |n| n.mark_read(now));
575 if done.is_ok() {
576 changed += 1;
577 }
578 }
579 Ok(changed)
580 }
581
582 pub fn dismiss(&self, id: &str) -> Result<Notice> {
584 let now = Timestamp::now();
585 self.update(id, |n| n.dismiss(now))
586 }
587
588 fn prune(&self) {
590 let mut all = self.all();
591 if all.len() <= CAP {
592 return;
593 }
594 all.sort_by(|a, b| {
596 b.keep_rank()
597 .cmp(&a.keep_rank())
598 .then_with(|| b.last_at.cmp(&a.last_at))
599 });
600 for n in all
601 .split_off(CAP)
602 .into_iter()
603 .filter(|n| n.obsolete() || !n.unread() || n.delivered >= n.generation)
604 {
605 let _ = std::fs::remove_file(self.path_of(&n.id));
606 }
607 }
608
609 pub fn revision(&self) -> u64 {
613 use std::hash::{Hash as _, Hasher as _};
614 let mut entries: Vec<(std::ffi::OsString, u128)> = std::fs::read_dir(&self.root)
615 .into_iter()
616 .flatten()
617 .flatten()
618 .filter(|e| e.path().extension().is_some_and(|x| x == "json"))
619 .map(|e| {
620 let at = e
621 .metadata()
622 .and_then(|m| m.modified())
623 .ok()
624 .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
625 .map_or(0, |d| d.as_nanos());
626 (e.file_name(), at)
627 })
628 .collect();
629 if entries.is_empty() {
630 return 0;
631 }
632 entries.sort();
633 let mut h = std::collections::hash_map::DefaultHasher::new();
634 entries.hash(&mut h);
635 h.finish()
636 }
637}
638
639fn read_path(path: &Path) -> Result<Notice> {
640 let body = std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;
641 let n: Notice =
642 serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))?;
643 if n.schema > SCHEMA {
644 bail!(
645 "notice {} was written by a newer magi (schema {}, this build speaks up to {SCHEMA})",
646 n.id,
647 n.schema
648 );
649 }
650 Ok(n)
651}
652
653pub(crate) fn detail(value: Option<&str>) -> Option<&str> {
655 clean_text(value)
656}
657
658pub(crate) fn turn_status(code: Option<i32>, timed_out: bool, quota_exhausted: bool) -> String {
660 let mut parts = vec![exit_status(code)];
661 if timed_out {
662 parts.push("time limit reached".to_owned());
663 }
664 if quota_exhausted {
665 parts.push("quota exhausted".to_owned());
666 }
667 parts.join("; ")
668}
669
670pub(crate) fn answerable_question(n: &Notice, questions: &crate::ask::Questions) -> Option<String> {
673 let direct = n.covered_by.as_deref().or_else(|| {
674 ["question:", "deputy-turn:", "repair-owner:", "action:"]
675 .iter()
676 .find_map(|prefix| n.key.strip_prefix(prefix))
677 });
678 let release = if direct.is_none() && n.key.starts_with("release-pr:") {
679 questions
680 .root()
681 .parent()
682 .and_then(|home| crate::release_watch::question_for_notice(home, &n.key))
683 } else {
684 None
685 };
686 let id = direct.or(release.as_deref())?;
687 questions
688 .get(id)
689 .ok()
690 .filter(|q| q.status.open())
691 .map(|q| q.id)
692}
693
694pub fn run_ended(state: &crate::run::RunState) -> Option<Notice> {
700 use crate::run::RunStatus;
701 let failed = matches!(
702 state.status,
703 RunStatus::Blocked | RunStatus::Stalled | RunStatus::Failed
704 );
705 (failed && !state.parked).then(|| {
706 let head_e2e_stop = crate::head_e2e_stop::conclusive(state);
707 let mut notice = Notice::error(
708 &format!("run:{}", state.id),
709 format!(
710 "Run {} ended {}. {}",
711 state.id,
712 state.status.as_str(),
713 run_cause(state)
714 ),
715 )
716 .link(Link::Run {
717 id: state.id.clone(),
718 })
719 .about([state.id.clone()])
720 .since(Some(
721 state
722 .base_sync_recovery
723 .stop
724 .as_ref()
725 .filter(|_| state.base_sync_blocked())
726 .map(|s| s.at)
727 .or_else(|| head_e2e_stop.as_ref().and_then(|s| s.recorded_at))
728 .or_else(|| state.passes.last().map(|p| p.started_at))
729 .unwrap_or(state.created_at),
730 ));
731 if let Some(stop) = head_e2e_stop {
732 notice = notice.cause(stop.id);
733 }
734 notice
735 })
736}
737
738pub fn merged_red(run_id: &str, summary: &str) -> Notice {
744 Notice::warn(&format!("merged-red:{run_id}"), summary).link(Link::Run {
745 id: run_id.to_owned(),
746 })
747}
748
749pub fn exit_status(code: Option<i32>) -> String {
751 match code {
752 Some(code) => format!("exit code {code}"),
753 None => "exit code unavailable".to_owned(),
754 }
755}
756
757pub fn clean_text(s: Option<&str>) -> Option<&str> {
759 s.map(str::trim)
760 .filter(|t| !t.is_empty() && *t != "(no reason given)" && *t != "(none)")
761}
762
763pub fn format_list<T: AsRef<str>>(items: &[T]) -> Option<String> {
766 let non_empty: Vec<&str> = items
767 .iter()
768 .map(|s| s.as_ref().trim())
769 .filter(|s| !s.is_empty())
770 .collect();
771 if non_empty.is_empty() {
772 None
773 } else {
774 Some(non_empty.join(", "))
775 }
776}
777
778pub fn ensure_sentence(text: &str) -> String {
780 let trimmed = text.trim();
781 if trimmed.is_empty() {
782 return String::new();
783 }
784 let trimmed_dot = trimmed.trim_end_matches('.');
785 format!("{trimmed_dot}.")
786}
787
788pub fn task_held(task: &crate::queue::Task) -> Option<Notice> {
802 use crate::queue::{HoldSource, TaskStatus};
803 if task.status != TaskStatus::Held || task.hold_source != Some(HoldSource::Machine) {
804 return None;
805 }
806 if task.has_disk_capacity_cause() {
807 return Some(Notice::warn(&format!("task:{}", task.id),
808 format!("Task {} is waiting for disk capacity and will resume automatically after admission succeeds.", task.short()))
809 .link(Link::Task { id: task.id.clone() }).about([task.id.clone()]).cause("disk-capacity"));
810 }
811 if let Some(run_id) = task.awaiting_landing_run() {
812 return Some(
813 Notice::warn(
814 &format!("task:{}", task.id),
815 format!(
816 "Task {} is ready on its branch (run {}) and awaiting landing.",
817 task.short(),
818 crate::run::short_of(run_id)
819 ),
820 )
821 .link(Link::Task {
822 id: task.id.clone(),
823 })
824 .about([task.id.clone()])
825 .since(task.held_at)
826 .cause(format!("awaiting-landing:{run_id}")),
827 );
828 }
829 let why = clean_text(task.hold_reason.as_deref())
830 .or_else(|| clean_text(task.last_error.as_deref()))
831 .unwrap_or("no reason recorded");
832 let why_sentence = why.trim_end_matches('.');
833 let mut notice = Notice::warn(
834 &format!("task:{}", task.id),
835 format!("Task {} is held: {why_sentence}.", task.short()),
836 )
837 .link(Link::Task {
838 id: task.id.clone(),
839 })
840 .about([task.id.clone()])
841 .since(task.held_at);
842 if let Some(stop_id) = task.head_e2e_stop_id() {
843 notice = notice.cause(stop_id);
844 }
845 Some(notice)
846}
847
848pub fn conductor_resumption(
856 task_id: &str,
857 task_short: &str,
858 reason: Option<&str>,
859 blocked_by: &[String],
860 evidence: &[String],
861 has_question: bool,
862) -> Notice {
863 let mut parts: Vec<String> = Vec::new();
864 parts.push(format!(
865 "Conductor raised a concern for task {task_short} after explicit resumption, but its state was not changed because no verified new blocking evidence was found."
866 ));
867
868 if let Some(r) = clean_text(reason) {
869 parts.push(format!("Concern: {}.", r.trim_end_matches('.')));
870 }
871
872 if has_question {
873 parts.push("An unregistered question was proposed; no reply is required.".to_owned());
874 }
875
876 if let Some(deps) = format_list(blocked_by) {
877 parts.push(format!("Proposed dependencies: {deps}."));
878 }
879
880 if let Some(ev) = format_list(evidence) {
881 parts.push(format!("Cited evidence: {ev}."));
882 }
883
884 parts.push("Existing holds and questions still apply.".to_owned());
885 parts.push(
886 "No reply to this notice is needed. To hold this task, use manual hold via the queue."
887 .to_owned(),
888 );
889
890 Notice::warn(&format!("conductor-resumption:{task_id}"), parts.join(" "))
891 .link(Link::Task {
892 id: task_id.to_owned(),
893 })
894 .about([task_id.to_owned()])
895}
896
897pub fn run_stopped(id: &str, state: &crate::run::RunState) -> Notice {
899 Notice::error(
900 &format!("run:{id}"),
901 format!("Run {} stopped with an error. {}", id, run_cause(state)),
902 )
903 .link(Link::Run { id: id.to_owned() })
904 .about([id.to_owned()])
905 .since(Some(
906 state
907 .base_sync_recovery
908 .stop
909 .as_ref()
910 .filter(|_| state.base_sync_blocked())
911 .map(|s| s.at)
912 .or_else(|| {
913 state
914 .land_sync_recovery
915 .stop
916 .as_ref()
917 .filter(|_| state.land_sync_exhausted())
918 .map(|s| s.at)
919 })
920 .or_else(|| crate::head_e2e_stop::conclusive(state).and_then(|s| s.recorded_at))
921 .or_else(|| state.passes.last().map(|p| p.started_at))
922 .unwrap_or(state.created_at),
923 ))
924}
925
926fn run_cause(state: &crate::run::RunState) -> String {
928 let verification_cause = state.verification_blocking_cause();
929 let cause = state
930 .prep_failure
931 .as_deref()
932 .or_else(|| state.resource_block.as_ref().map(|b| b.detail.as_str()))
933 .or_else(|| {
934 state
935 .candidate_preservation
936 .values()
937 .next()
938 .map(String::as_str)
939 })
940 .or(verification_cause.as_deref())
941 .or_else(|| state.events.last().map(|e| e.message.as_str()));
942 if state.land_sync_exhausted() {
943 return format!(
944 "{} Next: {}",
945 cause.unwrap_or("Landing base synchronization budget exhausted."),
946 state.land_sync_next_action()
947 );
948 }
949 if state.base_sync_blocked() || state.resource_block.is_some() {
950 return format!(
951 "{} Next: {}",
952 cause.unwrap_or("Synchronization stopped."),
953 state.base_sync_next_action()
954 );
955 }
956 cause
957 .and_then(|s| s.lines().find(|line| !line.trim().is_empty()))
958 .unwrap_or("No cause recorded; inspect the run.")
959 .to_owned()
960}
961
962#[derive(Debug, Clone, PartialEq, Eq)]
964pub struct Page {
965 pub run: String,
967 pub summary: String,
969}
970
971static PAGER: std::sync::OnceLock<()> = std::sync::OnceLock::new();
974
975pub fn install_pager() {
977 let _ = PAGER.set(());
978}
979
980fn send_page(page: Page, notify: Option<crate::config::Notify>) {
985 if PAGER.get().is_none() {
986 return;
987 }
988 let spawned = std::thread::Builder::new()
989 .name("notice-pager".into())
990 .spawn(move || {
991 let notify = notify.unwrap_or_else(machine_notify);
992 if notify.command.is_empty() {
993 return;
994 }
995 let rt = match tokio::runtime::Builder::new_current_thread()
996 .enable_all()
997 .build()
998 {
999 Ok(rt) => rt,
1000 Err(e) => return tracing::warn!("could not page about a notification: {e:#}"),
1001 };
1002 if let Err(e) = rt.block_on(crate::ask::notify_text(¬ify, &page.run, &page.summary))
1003 {
1004 tracing::warn!("could not page about a notification: {e:#}");
1005 }
1006 });
1007 if let Err(e) = spawned {
1008 tracing::warn!("could not page about a notification: {e:#}");
1009 }
1010}
1011
1012fn machine_notify() -> crate::config::Notify {
1015 let layers: Vec<PathBuf> = crate::config::Config::machine_layer()
1016 .into_iter()
1017 .filter(|p| p.is_file())
1018 .collect();
1019 match crate::config::Config::load_layers(&layers) {
1020 Ok(c) => c.notify,
1021 Err(e) => {
1022 tracing::warn!("could not read [notify] for a notification: {e:#}");
1023 Default::default()
1024 }
1025 }
1026}
1027
1028pub fn raise(notice: Notice) {
1032 if let Some(home) = crate::run::try_home() {
1033 raise_in(&home, notice);
1034 }
1035}
1036
1037pub fn raise_with(notice: Notice, notify: &crate::config::Notify) {
1039 if let Some(home) = crate::run::try_home() {
1040 raise_in_with(&home, notice, &|page| send_page(page, Some(notify.clone())));
1041 }
1042}
1043
1044pub fn covers(q: &crate::ask::Question, n: &Notice) -> bool {
1061 let recorded_coverage =
1065 q.routed_chat.is_some() && n.covered_by.as_deref() == Some(q.id.as_str());
1066 if !(q.status.open() || recorded_coverage) || !n.subjects.contains(&q.run) {
1067 return false;
1068 }
1069 if n.since.is_some_and(|since| q.asked_at < since) {
1070 return false;
1071 }
1072 let about_task = n.key.starts_with("task:") || n.key.starts_with("handover:");
1073 let about_run = n.key.starts_with("run:");
1074 match q.node.as_str() {
1075 crate::bump::NOTICE_NODE | crate::land::APPROVAL_NODE => false,
1076 _ if q.run_names_task() => about_task,
1077 _ => about_run,
1078 }
1079}
1080
1081fn covering_question(home: &Path, n: &Notice) -> Option<String> {
1082 if n.subjects.is_empty() {
1083 return None;
1084 }
1085 crate::ask::Questions::at(home.join("questions"))
1086 .list()
1087 .into_iter()
1088 .find(|q| covers(q, n))
1089 .map(|q| q.id)
1090}
1091
1092pub fn quiet_for(home: &Path, question: &crate::ask::Question) {
1094 Notices::at(home.join("notifications")).cover(question);
1095}
1096
1097pub fn raise_in(home: &Path, notice: Notice) {
1100 raise_in_with(home, notice, &|page| send_page(page, None));
1101}
1102
1103pub fn raise_in_with(home: &Path, mut notice: Notice, send: &dyn Fn(Page)) {
1106 if let Some(q) = covering_question(home, ¬ice) {
1107 notice.covered_by = Some(q);
1108 }
1109 match Notices::at(home.join("notifications")).raise_paged(notice) {
1110 Ok((n, true)) => send(Page {
1111 run: n
1112 .related_run
1113 .clone()
1114 .or_else(|| match &n.link {
1115 Some(Link::Run { id }) => Some(id.clone()),
1116 _ => None,
1117 })
1118 .unwrap_or_default(),
1119 summary: n.message.clone(),
1120 }),
1121 Ok(_) => {}
1122 Err(e) => tracing::warn!("could not file a notification: {e:#}"),
1123 }
1124}
1125
1126#[cfg(test)]
1127mod tests {
1128 use super::*;
1129
1130 #[test]
1131 fn notification_details_omit_blanks_and_explain_process_results() {
1132 assert_eq!(detail(None), None);
1133 assert_eq!(detail(Some(" \n\t")), None);
1134 assert_eq!(detail(Some(" concern ")), Some("concern"));
1135 assert_eq!(exit_status(Some(7)), "exit code 7");
1136 assert_eq!(exit_status(None), "exit code unavailable");
1137 assert_eq!(
1138 turn_status(None, true, true),
1139 "exit code unavailable; time limit reached; quota exhausted"
1140 );
1141 let mut task = held_task();
1142 task.hold_reason = Some(" ".into());
1143 task.last_error = Some(" failure recorded ".into());
1144 assert!(
1145 task_held(&task)
1146 .unwrap()
1147 .message
1148 .ends_with("failure recorded.")
1149 );
1150 }
1151
1152 #[test]
1153 fn resumption_notice_and_external_page_are_informational() {
1154 let dir = tempfile::tempdir().unwrap();
1155 let n = conductor_resumption(
1156 "t1",
1157 "t1",
1158 Some("Inspection remains a concern."),
1159 &["dep1".into(), " ".into()],
1160 &[],
1161 false,
1162 );
1163 assert!(n.message.contains("Concern: Inspection remains a concern."));
1164 assert!(n.message.contains("Proposed dependencies: dep1."));
1165 assert!(n.message.contains("its state was not changed"));
1166 assert!(
1167 n.message
1168 .contains("Existing holds and questions still apply")
1169 );
1170 assert!(n.message.contains("No reply to this notice is needed"));
1171 assert_eq!(n.link, Some(Link::Task { id: "t1".into() }));
1172 let sent = pages(dir.path(), n.clone());
1173 assert_eq!(sent[0].summary, n.message);
1174 assert!(pages(dir.path(), n).is_empty(), "repeat remains silent");
1175 let empty = conductor_resumption("t2", "t2", Some(" "), &[], &[], false);
1176 for absent in [
1177 "Concern:",
1178 "Proposed dependencies:",
1179 "Some(",
1180 "None",
1181 "[]",
1182 "question:",
1183 "evidence:",
1184 "?",
1185 ] {
1186 assert!(!empty.message.contains(absent), "{absent}");
1187 }
1188 }
1189
1190 #[test]
1191 fn only_currently_open_registered_questions_have_response_links() {
1192 let dir = tempfile::tempdir().unwrap();
1193 let q = ask(dir.path(), "t1", "conduct");
1194 let questions = crate::ask::Questions::at(dir.path().join("questions"));
1195 let mut n = Notice::warn("task:t1", "held");
1196 n.covered_by = Some(q.id.clone());
1197 assert_eq!(answerable_question(&n, &questions), Some(q.id.clone()));
1198 questions
1199 .update(&q.id, |q| {
1200 q.answer(crate::ask::Answer::Text("continue".into()))
1201 })
1202 .unwrap();
1203 assert_eq!(answerable_question(&n, &questions), None);
1204 let abandoned = ask(dir.path(), "t2", "conduct");
1205 let failure = Notice::warn(&format!("question:{}", abandoned.id), "delivery failed");
1206 assert_eq!(
1207 answerable_question(&failure, &questions),
1208 Some(abandoned.id.clone())
1209 );
1210 questions
1211 .update(&abandoned.id, |q| {
1212 q.abandon("run gone");
1213 Ok(())
1214 })
1215 .unwrap();
1216 assert_eq!(answerable_question(&failure, &questions), None);
1217 n.covered_by = Some("missing".into());
1218 assert_eq!(answerable_question(&n, &questions), None);
1219 assert_eq!(
1220 answerable_question(
1221 &conductor_resumption("t1", "t1", None, &[], &[], false),
1222 &questions
1223 ),
1224 None
1225 );
1226 }
1227
1228 #[test]
1229 fn legacy_deputy_warnings_are_hidden_without_hiding_other_namespaces() {
1230 let (_dir, s) = store();
1231 for key in ["deputy:open", "deputy:answered", "deputy:deleted"] {
1233 s.raise(Notice::warn(key, "old exhausted warning")).unwrap();
1234 }
1235 let keys = ["deputy-turn:open", "deputyish:open", "deputy", "task:open"];
1236 for key in keys {
1237 s.raise(Notice::warn(key, "still relevant")).unwrap();
1238 }
1239 assert_eq!(s.list().len(), keys.len());
1240 assert_eq!(s.count_unread(), keys.len());
1241 assert!(s.list().iter().all(|n| keys.contains(&n.key.as_str())));
1242 assert_eq!(s.mark_all_read().unwrap(), keys.len());
1243 assert_eq!(s.count_unread(), 0);
1244 assert!(s.get(&id_of("deputy:open")).unwrap().unread());
1245 }
1246
1247 #[test]
1248 fn obsolete_deputy_warnings_are_pruned_before_current_notices() {
1249 let (_dir, s) = store();
1250 for i in 0..CAP {
1251 let id = s
1252 .raise(Notice::info(&format!("current:{i}"), "keep"))
1253 .unwrap()
1254 .id;
1255 s.dismiss(&id).unwrap();
1256 }
1257 s.raise(Notice::warn("deputy:old", "obsolete")).unwrap();
1259 assert!(s.get(&id_of("deputy:old")).is_err());
1260 assert_eq!(s.all().len(), CAP);
1261 assert!(s.all().iter().all(|n| n.key.starts_with("current:")));
1262 }
1263
1264 #[test]
1265 fn process_exit_status_is_readable_even_without_a_code() {
1266 assert_eq!(exit_status(Some(1)), "exit code 1");
1267 assert_eq!(exit_status(None), "exit code unavailable");
1268 }
1269
1270 fn store() -> (tempfile::TempDir, Notices) {
1271 let dir = tempfile::tempdir().unwrap();
1272 let s = Notices::at(dir.path().join("notifications"));
1273 (dir, s)
1274 }
1275
1276 #[test]
1277 fn a_red_merge_notice_is_keyed_on_the_run_and_raised_once() {
1278 let (_d, s) = store();
1279 let n = merged_red("run-1", "Merged a/b PR #1 with red checks: x (u)");
1280 assert_eq!(n.key, "merged-red:run-1");
1281 assert_eq!(
1282 n.link,
1283 Some(Link::Run {
1284 id: "run-1".to_owned()
1285 })
1286 );
1287 s.raise(merged_red(
1288 "run-1",
1289 "Merged a/b PR #1 with red checks: x (u)",
1290 ))
1291 .unwrap();
1292 s.raise(merged_red(
1293 "run-1",
1294 "Merged a/b PR #1 with red checks: x (u)",
1295 ))
1296 .unwrap();
1297 assert_eq!(s.list().len(), 1);
1298 }
1299
1300 #[test]
1301 fn producer_cause_transitions_page_once_without_using_message_prose() {
1302 let (dir, store) = store();
1303 let sent = std::cell::RefCell::new(Vec::new());
1304 let raise = |cause: &str, message: &str| {
1305 raise_in_with(
1306 dir.path(),
1307 Notice::warn("release-pr:pr", message).cause(cause),
1308 &|p| sent.borrow_mut().push(p),
1309 )
1310 };
1311 raise("approval:h1", "approval is needed");
1312 let id = id_of("release-pr:pr");
1313 store.mark_read(&id).unwrap();
1314 raise("approval:h1", "approval wording updated");
1315 assert!(!store.get(&id).unwrap().unread());
1316 raise("merge-failed:h1", "merge refused");
1317 assert!(store.get(&id).unwrap().unread());
1318 assert_eq!(sent.borrow().len(), 2);
1319 assert_eq!(store.get(&id).unwrap().generation, 2);
1320 store.mark_read(&id).unwrap();
1321 raise("merge-failed:h1", "merge refusal wording updated");
1322 assert_eq!(sent.borrow().len(), 2);
1323 assert!(!store.get(&id).unwrap().unread());
1324 }
1325
1326 #[test]
1327 fn a_repeat_updates_evidence_without_relighting_it() {
1328 let now = Timestamp::now();
1329 let mut n = Notice::warn("task:1", "held");
1330 n.mark_read(now);
1331 n.raise_again(&Notice::warn("task:1", "held"), now);
1332 assert_eq!(n.count, 2);
1333 assert!(n.read_at.is_some(), "identical repeat stays read");
1334 n.raise_again(&Notice::warn("task:1", "held differently"), now);
1335 assert!(!n.unread());
1336 assert_eq!(n.message, "held differently");
1337 }
1338
1339 #[test]
1340 fn a_rise_in_severity_resurrects_a_dismissed_notice_but_a_repeat_does_not() {
1341 let now = Timestamp::now();
1342 let mut n = Notice::warn("task:x", "m");
1343 n.dismiss(now);
1344 n.raise_again(&Notice::warn("task:x", "m"), now);
1345 assert!(n.dismissed_at.is_some(), "tombstone holds");
1346 n.raise_again(&Notice::error("k", "m"), now);
1347 assert!(n.unread());
1348 assert_eq!(n.severity, Severity::Error);
1349 n.raise_again(&Notice::info("k", "other"), now);
1351 assert_eq!(n.severity, Severity::Error);
1352 }
1353
1354 #[test]
1355 fn adding_link_on_repeat_updates_link_without_relighting_read_or_dismissed() {
1356 let now = Timestamp::now();
1357 let mut read_notice = Notice::warn("task:1", "held");
1359 read_notice.mark_read(now);
1360 let link_to_add = Link::Task { id: "1".to_owned() };
1361 let again = Notice::warn("task:1", "held").link(link_to_add.clone());
1362 let relit = read_notice.raise_again(&again, now);
1363 assert!(!relit, "link-only update must not page/relight");
1364 assert!(read_notice.read_at.is_some(), "read notice stays read");
1365 assert_eq!(read_notice.link, Some(link_to_add.clone()));
1366
1367 let mut dismissed_notice = Notice::warn("task:2", "held");
1369 dismissed_notice.dismiss(now);
1370 let link_to_add_2 = Link::Task { id: "2".to_owned() };
1371 let again_2 = Notice::warn("task:2", "held").link(link_to_add_2.clone());
1372 let relit_2 = dismissed_notice.raise_again(&again_2, now);
1373 assert!(!relit_2, "link-only update must not page/relight");
1374 assert!(dismissed_notice.dismissed_at.is_some(), "tombstone holds");
1375 assert_eq!(dismissed_notice.link, Some(link_to_add_2));
1376 }
1377
1378 #[test]
1379 fn identical_raises_share_one_file() {
1380 let (_d, s) = store();
1381 for _ in 0..5 {
1382 s.raise(Notice::error("run:abc", "blocked")).unwrap();
1383 }
1384 let all = s.list();
1385 assert_eq!(all.len(), 1);
1386 assert_eq!(all[0].count, 5);
1387 assert_eq!(s.count_unread(), 1);
1388 }
1389
1390 #[test]
1391 fn transitions_persist_and_dismissed_leave_the_list() {
1392 let (_d, s) = store();
1393 let a = s.raise(Notice::info("a", "one")).unwrap();
1394 let b = s.raise(Notice::warn("b", "two")).unwrap();
1395 assert_eq!(s.count_unread(), 2);
1396 s.mark_read(&a.id).unwrap();
1397 assert_eq!(s.count_unread(), 1);
1398 s.dismiss(&b.id).unwrap();
1399 assert_eq!(s.count_unread(), 0);
1400 assert_eq!(s.list().len(), 1);
1401 s.raise(Notice::warn("b", "two")).unwrap();
1402 assert_eq!(
1403 s.list().len(),
1404 1,
1405 "a tombstone survives a same-message raise"
1406 );
1407 s.raise(Notice::info("c", "three")).unwrap();
1408 assert_eq!(s.mark_all_read().unwrap(), 1);
1409 assert_eq!(s.count_unread(), 0);
1410 }
1411
1412 #[test]
1413 fn the_list_is_newest_first() {
1414 let (_d, s) = store();
1415 let mut old = Notice::info("old", "old");
1416 old.last_at = "2020-01-01T00:00:00Z".parse().unwrap();
1417 s.put(&old).unwrap();
1418 s.raise(Notice::info("new", "new")).unwrap();
1419 let keys: Vec<_> = s.list().into_iter().map(|n| n.key).collect();
1420 assert_eq!(keys, ["new", "old"]);
1421 }
1422
1423 #[test]
1424 fn the_cap_prunes_dismissed_then_read_then_oldest() {
1425 let (_d, s) = store();
1426 let keep = s.raise(Notice::error("keep", "unread")).unwrap();
1427 let gone = s.raise(Notice::info("gone", "dismissed")).unwrap();
1428 s.dismiss(&gone.id).unwrap();
1429 for i in 0..CAP - 1 {
1430 s.raise(Notice::info(&format!("k{i}"), "x")).unwrap();
1431 }
1432 let files = std::fs::read_dir(s.root()).unwrap().count();
1433 assert_eq!(files, CAP);
1434 assert!(
1435 s.get(&keep.id).is_ok(),
1436 "an unread notice outlives a dismissed one"
1437 );
1438 assert!(s.get(&gone.id).is_err(), "the dismissed one went first");
1439 }
1440
1441 #[test]
1442 fn revision_moves_on_write_and_on_removal() {
1443 let (_d, s) = store();
1444 assert_eq!(s.revision(), 0);
1445 let a = s.raise(Notice::info("a", "m")).unwrap();
1446 let r1 = s.revision();
1447 assert_ne!(r1, 0);
1448 s.raise(Notice::info("b", "m")).unwrap();
1449 let r2 = s.revision();
1450 assert_ne!(r1, r2);
1451 std::fs::remove_file(s.path_of(&a.id)).unwrap();
1452 assert_ne!(s.revision(), r2);
1453 }
1454
1455 #[test]
1456 fn ids_are_stable_and_untrusted_ids_are_refused() {
1457 assert_eq!(id_of("run:1"), id_of("run:1"));
1458 assert_ne!(id_of("run:1"), id_of("run-1"));
1459 assert!(valid_id(&id_of("release-bump:20260101-abc")));
1460 let (_d, s) = store();
1461 for bad in ["", "../x", "a/b", "A", "x.json"] {
1462 assert!(s.get(bad).is_err(), "{bad}");
1463 }
1464 }
1465
1466 #[test]
1467 fn a_newer_schema_is_refused_and_an_older_reads() {
1468 let (_d, s) = store();
1469 let mut n = Notice::info("k", "m");
1470 n.schema = SCHEMA + 1;
1471 s.put(&n).unwrap();
1472 assert!(s.get(&n.id).is_err());
1473 let old = r#"{"id":"x-1","key":"x","severity":"warn","message":"m",
1474 "first_at":"2020-01-01T00:00:00Z","last_at":"2020-01-01T00:00:00Z"}"#;
1475 std::fs::write(s.path_of("x-1"), old).unwrap();
1476 assert_eq!(s.get("x-1").unwrap().count, 1);
1477 }
1478
1479 fn state(status: crate::run::RunStatus) -> crate::run::RunState {
1480 let mut st = crate::run::RunState::new(
1481 std::path::PathBuf::from("/repo"),
1482 "main".to_owned(),
1483 "abc1234def".to_owned(),
1484 "task".to_owned(),
1485 crate::config::Config::default(),
1486 );
1487 st.status = status;
1488 st
1489 }
1490
1491 #[test]
1492 fn a_run_that_ended_badly_is_news_unless_it_only_parked() {
1493 use crate::run::RunStatus;
1494 for bad in [RunStatus::Blocked, RunStatus::Stalled, RunStatus::Failed] {
1495 let st = state(bad);
1496 let n = run_ended(&st).expect("news");
1497 assert_eq!(n.key, format!("run:{}", st.id));
1498 assert_eq!(n.severity, Severity::Error);
1499 }
1500 assert!(run_ended(&state(RunStatus::Merged)).is_none());
1501 let mut parked = state(RunStatus::Stalled);
1502 parked.parked = true;
1503 assert!(run_ended(&parked).is_none());
1504 }
1505
1506 #[test]
1507 fn concurrent_writers_of_one_key_all_succeed() {
1508 let (_d, s) = store();
1509 let handles: Vec<_> = (0..8)
1510 .map(|_| {
1511 let s = s.clone();
1512 std::thread::spawn(move || {
1513 for _ in 0..20 {
1514 s.raise(Notice::warn("same", "m")).unwrap();
1515 }
1516 })
1517 })
1518 .collect();
1519 for h in handles {
1520 h.join().unwrap();
1521 }
1522 assert_eq!(s.list().len(), 1);
1523 let stray = std::fs::read_dir(s.root())
1524 .unwrap()
1525 .flatten()
1526 .filter(|e| e.path().extension().is_some_and(|x| x == "tmp"))
1527 .count();
1528 assert_eq!(stray, 0);
1529 }
1530
1531 #[test]
1532 fn a_dead_holders_lock_is_broken_and_no_lock_is_left_behind() {
1533 let (_d, s) = store();
1534 let n = s.raise(Notice::info("k", "m")).unwrap();
1535 let lock = s.root().join(format!("{}.lock", n.id));
1536 std::fs::write(&lock, "").unwrap();
1537 let old = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
1538 std::fs::File::options()
1539 .write(true)
1540 .open(&lock)
1541 .unwrap()
1542 .set_modified(old)
1543 .unwrap();
1544 s.mark_read(&n.id).unwrap();
1545 assert!(!lock.exists());
1546 assert!(s.get(&n.id).unwrap().read_at.is_some());
1547 }
1548
1549 #[test]
1550 fn only_a_machine_hold_is_a_task_notice() {
1551 let mut t = crate::queue::Task::new(
1552 "t".to_owned(),
1553 "do it".to_owned(),
1554 std::path::PathBuf::from("/repo"),
1555 crate::queue::Source::Human,
1556 );
1557 assert!(task_held(&t).is_none());
1558 t.hold_manual(None);
1559 assert!(task_held(&t).is_none(), "the operator's own hold");
1560 t.hold_machine(Some("missing blocker".to_owned()));
1561 let n = task_held(&t).expect("machine hold");
1562 assert_eq!(n.key, format!("task:{}", t.id));
1563 assert!(n.message.contains("missing blocker"));
1564 }
1565
1566 fn held_task() -> crate::queue::Task {
1567 let mut t = crate::queue::Task::new(
1568 "t".to_owned(),
1569 "do it".to_owned(),
1570 std::path::PathBuf::from("/repo"),
1571 crate::queue::Source::Human,
1572 );
1573 t.hold_machine(Some("branch b is checked out".to_owned()));
1574 t
1575 }
1576
1577 fn ask(home: &Path, run: &str, node: &str) -> crate::ask::Question {
1578 let mut q = crate::ask::Question::new(
1579 run.to_owned(),
1580 node.to_owned(),
1581 "conductor".to_owned(),
1582 "cannot resume".to_owned(),
1583 String::new(),
1584 Vec::new(),
1585 );
1586 crate::ask::Questions::at(home.join("questions"))
1587 .put(&mut q)
1588 .unwrap();
1589 q
1590 }
1591
1592 fn unread(home: &Path) -> usize {
1593 Notices::at(home.join("notifications")).count_unread()
1594 }
1595
1596 #[test]
1597 fn a_hold_with_an_open_question_for_the_task_pages_once() {
1598 let dir = tempfile::tempdir().unwrap();
1599 let mut t = held_task();
1600 let q = ask(dir.path(), &t.id, "conduct");
1601 crate::queue::Queue::at(dir.path().join("queue"))
1602 .put(&mut t)
1603 .unwrap();
1604 let s = Notices::at(dir.path().join("notifications"));
1605 assert_eq!(s.count_unread(), 0);
1606 let n = s.list().pop().expect("the record is kept");
1607 assert_eq!(n.covered_by.as_deref(), Some(q.id.as_str()));
1608 assert!(n.message.contains("checked out"));
1609 }
1610
1611 #[test]
1612 fn a_refused_handover_without_a_question_pages_once() {
1613 let dir = tempfile::tempdir().unwrap();
1614 let q = crate::queue::Queue::at(dir.path().join("queue"));
1615 let mut t = held_task();
1616 t.hold_for_handover(Some("magi/x/A".to_owned()), "checked out".to_owned());
1617 q.put(&mut t).unwrap();
1618 q.put(&mut t).unwrap();
1619 let s = Notices::at(dir.path().join("notifications"));
1620 assert_eq!(s.list().len(), 1);
1621 assert_eq!(s.list()[0].key, format!("task:{}", t.id));
1622 assert_eq!(s.count_unread(), 1);
1623 }
1624
1625 #[test]
1626 fn an_older_question_does_not_silence_a_new_hold() {
1627 for node in ["deps", "conduct", "triage"] {
1628 let dir = tempfile::tempdir().unwrap();
1629 let mut t = crate::queue::Task::new(
1630 "t".to_owned(),
1631 "do it".to_owned(),
1632 std::path::PathBuf::from("/repo"),
1633 crate::queue::Source::Human,
1634 );
1635 let old = ask(dir.path(), &t.id, node);
1636 std::thread::sleep(std::time::Duration::from_millis(5));
1637 t.hold_machine(Some("new failure".to_owned()));
1638 crate::queue::Queue::at(dir.path().join("queue"))
1639 .put(&mut t)
1640 .unwrap();
1641 let s = Notices::at(dir.path().join("notifications"));
1642 let n = s.list().pop().unwrap();
1643 assert_eq!(n.covered_by, None, "{node} question {}", old.id);
1644 assert_eq!(s.count_unread(), 1);
1645 }
1646 }
1647
1648 #[test]
1649 fn a_legacy_covered_notice_pages_for_a_new_uncovered_hold() {
1650 let (_d, s) = store();
1651 let mut legacy = Notice::warn("task:x", "held");
1652 legacy.covered_by = Some("q1".to_owned());
1653 let id = legacy.id.clone();
1654 s.raise(legacy).unwrap();
1655 assert!(!s.get(&id).unwrap().unread());
1656 s.raise(Notice::warn("task:x", "held").since(Some(Timestamp::now())))
1657 .unwrap();
1658 let n = s.get(&id).unwrap();
1659 assert!(n.unread());
1660 assert_eq!(n.covered_by, None);
1661 }
1662
1663 #[test]
1664 fn a_newer_cause_relights_a_dismissed_notice() {
1665 let (_d, s) = store();
1666 let t0 = Timestamp::now();
1667 let first = Notice::warn("task:x", "held").since(Some(t0));
1668 let id = first.id.clone();
1669 s.raise(first).unwrap();
1670 s.dismiss(&id).unwrap();
1671 s.raise(Notice::warn("task:x", "held").since(Some(t0)))
1672 .unwrap();
1673 assert!(!s.get(&id).unwrap().unread(), "same cause stays dismissed");
1674 let later = t0 + std::time::Duration::from_secs(1);
1675 s.raise(Notice::warn("task:x", "held").since(Some(later)))
1676 .unwrap();
1677 assert!(s.get(&id).unwrap().unread());
1678 }
1679
1680 #[test]
1681 fn a_hold_with_no_question_still_notifies() {
1682 let dir = tempfile::tempdir().unwrap();
1683 let mut t = held_task();
1684 crate::queue::Queue::at(dir.path().join("queue"))
1685 .put(&mut t)
1686 .unwrap();
1687 assert_eq!(unread(dir.path()), 1);
1688 }
1689
1690 #[test]
1691 fn a_question_for_another_task_does_not_suppress() {
1692 let dir = tempfile::tempdir().unwrap();
1693 let mut t = held_task();
1694 ask(dir.path(), "some-other-task", "conduct");
1695 crate::queue::Queue::at(dir.path().join("queue"))
1696 .put(&mut t)
1697 .unwrap();
1698 assert_eq!(unread(dir.path()), 1);
1699 }
1700
1701 #[test]
1702 fn a_question_filed_after_the_hold_quiets_it_once() {
1703 let dir = tempfile::tempdir().unwrap();
1704 let mut t = held_task();
1705 crate::queue::Queue::at(dir.path().join("queue"))
1706 .put(&mut t)
1707 .unwrap();
1708 assert_eq!(unread(dir.path()), 1);
1709 let q = ask(dir.path(), &t.id, "conduct");
1710 assert_eq!(unread(dir.path()), 0);
1711 let s = Notices::at(dir.path().join("notifications"));
1713 let id = s.list()[0].id.clone();
1714 s.update(&id, |n| n.read_at = None).unwrap();
1715 let mut again = crate::ask::Questions::at(dir.path().join("questions"))
1716 .get(&q.id)
1717 .unwrap();
1718 crate::ask::Questions::at(dir.path().join("questions"))
1719 .put(&mut again)
1720 .unwrap();
1721 assert_eq!(unread(dir.path()), 1);
1722 }
1723
1724 #[test]
1725 fn a_blocked_run_with_an_open_question_is_quiet() {
1726 let dir = tempfile::tempdir().unwrap();
1727 ask(dir.path(), "run-1", "implement");
1728 raise_in(
1729 dir.path(),
1730 Notice::error("run:run-1", "Run r ended blocked.").about(["run-1"]),
1731 );
1732 assert_eq!(unread(dir.path()), 0);
1733 raise_in(
1734 dir.path(),
1735 Notice::error("run:run-2", "Run r ended blocked.").about(["run-2"]),
1736 );
1737 assert_eq!(unread(dir.path()), 1);
1738 }
1739
1740 #[test]
1741 fn escalation_makes_a_covered_notice_unread_again() {
1742 let dir = tempfile::tempdir().unwrap();
1743 ask(dir.path(), "t1", "conduct");
1744 raise_in(dir.path(), Notice::warn("task:t1", "held").about(["t1"]));
1745 assert_eq!(unread(dir.path()), 0);
1746 raise_in(dir.path(), Notice::error("task:t1", "held").about(["t1"]));
1747 assert_eq!(unread(dir.path()), 1);
1748 }
1749
1750 #[test]
1751 fn covers_matches_run_exactly_and_ignores_release_questions() {
1752 let dir = tempfile::tempdir().unwrap();
1753 let n = Notice::warn("task:x", "m").about(["t1"]);
1754 let q = ask(dir.path(), "t1", "conduct");
1755 assert!(covers(&q, &n));
1756 assert!(!covers(&q, &Notice::warn("task:x", "m")));
1757 assert!(!covers(&q, &Notice::warn("task:x", "m").about(["t"])));
1758 let release = ask(dir.path(), "t1", crate::bump::NOTICE_NODE);
1759 assert!(!covers(&release, &n));
1760 }
1761
1762 #[test]
1763 fn a_run_question_does_not_swallow_a_task_hold_and_vice_versa() {
1764 let dir = tempfile::tempdir().unwrap();
1765 ask(dir.path(), "t1", "implement");
1766 raise_in(dir.path(), Notice::warn("task:t1", "held").about(["t1"]));
1767 assert_eq!(unread(dir.path()), 1);
1768 ask(dir.path(), "r1", "conduct");
1769 raise_in(dir.path(), Notice::error("run:r1", "ended").about(["r1"]));
1770 assert_eq!(unread(dir.path()), 2);
1771 }
1772
1773 #[test]
1774 fn a_conduct_question_covers_the_hold_however_late_it_was_filed() {
1775 let dir = tempfile::tempdir().unwrap();
1776 let mut q = crate::ask::Question::new(
1777 "t1".to_owned(),
1778 "conduct".to_owned(),
1779 "conductor".to_owned(),
1780 "s".to_owned(),
1781 String::new(),
1782 Vec::new(),
1783 );
1784 q.asked_at = Timestamp::from_second(Timestamp::now().as_second() - 3600).unwrap();
1785 crate::ask::Questions::at(dir.path().join("questions"))
1786 .put(&mut q)
1787 .unwrap();
1788 raise_in(dir.path(), Notice::warn("task:t1", "held").about(["t1"]));
1789 assert_eq!(unread(dir.path()), 0);
1790 }
1791
1792 fn pages(home: &Path, n: Notice) -> Vec<Page> {
1793 let sent = std::cell::RefCell::new(Vec::new());
1794 raise_in_with(home, n, &|p| sent.borrow_mut().push(p));
1795 sent.into_inner()
1796 }
1797
1798 #[test]
1799 fn a_page_fires_on_new_causes_and_escalation_only() {
1800 let dir = tempfile::tempdir().unwrap();
1801 let h = dir.path();
1802 let n = || Notice::warn("run:p1", "stopped").link(Link::Run { id: "p1".into() });
1803 let first = pages(h, n());
1804 assert_eq!(
1805 first,
1806 vec![Page {
1807 run: "p1".into(),
1808 summary: "stopped".into()
1809 }]
1810 );
1811 assert!(pages(h, n()).is_empty(), "identical re-raise is silent");
1812 assert!(pages(h, Notice::warn("run:p1", "stopped again")).is_empty());
1813 assert_eq!(pages(h, Notice::error("run:p1", "stopped again")).len(), 1);
1814 assert!(pages(h, Notice::error("run:p1", "stopped again")).is_empty());
1815 }
1816
1817 #[test]
1818 fn a_non_run_link_leaves_run_empty() {
1819 let dir = tempfile::tempdir().unwrap();
1820 let n = Notice::warn("task:t1", "held").link(Link::Task { id: "t1".into() });
1821 assert_eq!(pages(dir.path(), n)[0].run, "");
1822 }
1823
1824 #[test]
1825 fn a_dismissed_tombstone_ignores_wording_changes() {
1826 let dir = tempfile::tempdir().unwrap();
1827 let h = dir.path();
1828 pages(h, Notice::warn("disk:r", "low"));
1829 Notices::at(h.join("notifications"))
1830 .dismiss(&id_of("disk:r"))
1831 .unwrap();
1832 assert!(pages(h, Notice::warn("disk:r", "low")).is_empty());
1833 assert!(pages(h, Notice::warn("disk:r", "lower")).is_empty());
1834 }
1835
1836 #[test]
1837 fn a_newer_cause_pages_again() {
1838 let dir = tempfile::tempdir().unwrap();
1839 let h = dir.path();
1840 let at = |s: i64| Some(Timestamp::from_second(s).unwrap());
1841 let n = |s| Notice::warn("task:t2", "held").since(at(s));
1842 assert_eq!(pages(h, n(100)).len(), 1);
1843 assert!(pages(h, n(100)).is_empty());
1844 assert_eq!(pages(h, n(200)).len(), 1);
1845 }
1846
1847 #[test]
1848 fn a_covered_notice_does_not_page() {
1849 let dir = tempfile::tempdir().unwrap();
1850 let h = dir.path();
1851 let q = ask(h, "r9", "implement");
1852 let n = || Notice::error("run:r9", "ended").about(["r9".to_owned()]);
1853 assert!(pages(h, n()).is_empty());
1854 let stored = Notices::at(h.join("notifications"))
1855 .get(&id_of("run:r9"))
1856 .unwrap();
1857 assert_eq!(stored.covered_by.as_deref(), Some(q.id.as_str()));
1858 assert!(pages(h, n()).is_empty());
1859 }
1860
1861 #[test]
1862 fn a_failing_sender_path_never_propagates() {
1863 let notify = crate::config::Notify {
1865 command: vec!["magi-no-such-program-xyz".into()],
1866 };
1867 let rt = tokio::runtime::Builder::new_current_thread()
1868 .enable_all()
1869 .build()
1870 .unwrap();
1871 let r = rt.block_on(crate::ask::notify_text(¬ify, "", "x"));
1872 assert!(r.is_err());
1873 send_page(
1875 Page {
1876 run: String::new(),
1877 summary: "x".into(),
1878 },
1879 Some(notify),
1880 );
1881 }
1882
1883 #[test]
1884 fn formatting_helpers_clean_text_and_lists() {
1885 assert_eq!(clean_text(None), None);
1886 assert_eq!(clean_text(Some("")), None);
1887 assert_eq!(clean_text(Some(" ")), None);
1888 assert_eq!(clean_text(Some("(no reason given)")), None);
1889 assert_eq!(clean_text(Some("(none)")), None);
1890 assert_eq!(clean_text(Some(" real reason ")), Some("real reason"));
1891
1892 let empty: Vec<String> = Vec::new();
1893 assert_eq!(format_list(&empty), None);
1894 assert_eq!(format_list(&["", " "]), None);
1895 assert_eq!(format_list(&["task-1"]), Some("task-1".into()));
1896 assert_eq!(format_list(&["a", "b", "c"]), Some("a, b, c".into()));
1897
1898 assert_eq!(ensure_sentence(""), "");
1899 assert_eq!(ensure_sentence("hello"), "hello.");
1900 assert_eq!(ensure_sentence("hello."), "hello.");
1901 assert_eq!(ensure_sentence("hello.."), "hello.");
1902 }
1903
1904 #[test]
1905 fn conductor_resumption_notice_is_readable_and_non_soliciting() {
1906 let task_id = "20261017-000000-abcd";
1907 let task_short = "abcd";
1908 let reason = "awaiting manual review";
1909 let blocked_by = vec!["dep-1".to_owned(), "dep-2".to_owned()];
1910 let evidence = vec!["check-failed".to_owned()];
1911 let has_question = true;
1912
1913 let notice = conductor_resumption(
1914 task_id,
1915 task_short,
1916 Some(reason),
1917 &blocked_by,
1918 &evidence,
1919 has_question,
1920 );
1921
1922 assert_eq!(notice.key, format!("conductor-resumption:{task_id}"));
1923 assert_eq!(notice.severity, Severity::Warn);
1924 assert_eq!(
1925 notice.link,
1926 Some(Link::Task {
1927 id: task_id.to_owned()
1928 })
1929 );
1930 assert_eq!(notice.subjects, vec![task_id.to_owned()]);
1931
1932 let msg = ¬ice.message;
1933 assert!(msg.contains("Conductor raised a concern for task abcd after explicit resumption"));
1935 assert!(msg.contains("Concern: awaiting manual review."));
1936 assert!(msg.contains("Proposed dependencies: dep-1, dep-2."));
1937 assert!(msg.contains("Cited evidence: check-failed."));
1938 assert!(msg.contains("No reply to this notice is needed."));
1940 assert!(!msg.contains("Some("));
1942 assert!(!msg.contains("None"));
1943 assert!(!msg.contains("[]"));
1944 assert!(!msg.contains("{:?}"));
1945 }
1946
1947 #[test]
1948 fn conductor_resumption_notice_omits_empty_details() {
1949 let task_id = "20261017-000000-abcd";
1950 let notice = conductor_resumption(task_id, "abcd", None, &[], &[], false);
1951
1952 let msg = ¬ice.message;
1953 assert!(!msg.contains("Concern:"));
1954 assert!(!msg.contains("Proposed dependencies:"));
1955 assert!(!msg.contains("Cited evidence:"));
1956 assert!(!msg.contains("unregistered question"));
1957 assert!(!msg.contains("None"));
1958 assert!(!msg.contains("[]"));
1959 assert!(msg.contains("No reply to this notice is needed."));
1960 }
1961}