1#[cfg(test)]
34thread_local! {
35 pub(crate) static LIST_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
36}
37
38use std::collections::HashMap;
39use std::num::NonZeroUsize;
40use std::path::{Path, PathBuf};
41
42use anyhow::{Context, Result, bail};
43use jiff::Timestamp;
44use serde::{Deserialize, Serialize};
45
46use crate::ask::Questions;
47use crate::config::BuildCache;
48use crate::id_reserve::{IdSource, path_exists};
49
50pub const SCHEMA: u32 = 24;
149
150const RECOVERY_HOLD_SCHEMA: u32 = 24;
151
152pub(crate) fn dispatch_order(a: &Task, b: &Task) -> std::cmp::Ordering {
158 match (a.upgrade_resume_key(), b.upgrade_resume_key()) {
159 (Some(a), Some(b)) => a.cmp(&b),
160 (Some(_), None) => std::cmp::Ordering::Less,
161 (None, Some(_)) => std::cmp::Ordering::Greater,
162 (None, None) => b.priority.cmp(&a.priority).then(a.id.cmp(&b.id)),
163 }
164}
165
166#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
173#[serde(tag = "kind", rename_all = "snake_case")]
174pub enum MachineHoldCause {
175 DiskCapacity {
177 reason: String,
179 #[serde(default)]
181 before_start: bool,
182 },
183}
184
185#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
187#[serde(rename_all = "lowercase")]
188pub enum HoldSource {
189 Manual,
191 Machine,
193}
194
195impl HoldSource {
196 pub fn label(self) -> &'static str {
198 match self {
199 Self::Manual => "manual",
200 Self::Machine => "machine",
201 }
202 }
203}
204
205#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
208#[serde(tag = "kind", rename_all = "lowercase")]
209pub enum Source {
210 Human,
212 Agent {
215 run: String,
217 node: String,
219 },
220 Issue {
222 number: u64,
224 repo: String,
226 },
227}
228
229pub const CHAT_NODE: &str = "chat";
232
233impl Source {
234 pub fn label(&self) -> String {
236 match self {
237 Self::Human => "human".to_owned(),
238 Self::Agent { run, node } => format!("{node}@{}", short(run)),
239 Self::Issue { number, .. } => format!("issue #{number}"),
240 }
241 }
242}
243
244#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
246#[serde(rename_all = "lowercase")]
247pub enum TaskStatus {
248 Queued,
250 Running,
252 Done,
254 Failed,
256 Held,
258 Blocked,
262 Parked,
267}
268
269impl TaskStatus {
270 pub fn runnable(self) -> bool {
272 matches!(self, Self::Queued | Self::Failed | Self::Parked)
273 }
274
275 pub fn as_str(self) -> &'static str {
277 match self {
278 Self::Queued => "queued",
279 Self::Running => "running",
280 Self::Done => "done",
281 Self::Failed => "failed",
282 Self::Held => "held",
283 Self::Blocked => "blocked",
284 Self::Parked => "parked",
285 }
286 }
287}
288
289#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
292pub struct TaskCounts {
293 pub queued: usize,
295 pub running: usize,
297 pub done: usize,
299 pub failed: usize,
301 pub held: usize,
303 pub blocked: usize,
305 pub parked: usize,
307}
308
309impl TaskCounts {
310 pub fn of(tasks: &[Task]) -> Self {
314 Self::of_statuses(tasks.iter().map(|task| task.status))
315 }
316
317 pub(crate) fn of_statuses(statuses: impl IntoIterator<Item = TaskStatus>) -> Self {
319 let mut counts = Self::default();
320 for status in statuses {
321 match status {
322 TaskStatus::Queued => counts.queued += 1,
323 TaskStatus::Running => counts.running += 1,
324 TaskStatus::Done => counts.done += 1,
325 TaskStatus::Failed => counts.failed += 1,
326 TaskStatus::Held => counts.held += 1,
327 TaskStatus::Blocked => counts.blocked += 1,
328 TaskStatus::Parked => counts.parked += 1,
329 }
330 }
331 counts
332 }
333}
334
335#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
337pub struct Reassignment {
338 pub from: PathBuf,
340 pub to: PathBuf,
342 pub actor: String,
344 pub at: Timestamp,
346 pub run_boundary: usize,
348}
349
350#[derive(Debug, Clone, Serialize, Deserialize)]
352#[serde(deny_unknown_fields)]
353pub struct Task {
354 pub schema: u32,
356 pub id: String,
358 pub title: String,
360 pub instruction: String,
362 #[serde(default, skip_serializing_if = "crate::refs::Sources::is_empty")]
364 pub sources: crate::refs::Sources,
365 pub repo: PathBuf,
367 #[serde(default)]
369 pub reassignments: Vec<Reassignment>,
370 pub source: Source,
372 #[serde(default)]
374 pub chat: Option<String>,
375 #[serde(default)]
377 pub priority: i32,
378 #[serde(default)]
389 pub solo: bool,
390 pub status: TaskStatus,
392 #[serde(default)]
394 pub attempts: usize,
395 #[serde(default)]
397 pub attempt_limit: Option<NonZeroUsize>,
398 #[serde(default)]
401 pub runs: Vec<String>,
402 #[serde(default)]
404 pub startup_failures: Vec<crate::run::StartupFailure>,
405 #[serde(default)]
407 pub last_error: Option<String>,
408 #[serde(default)]
421 pub hold_reason: Option<String>,
422 #[serde(default)]
425 pub hold_source: Option<HoldSource>,
426 #[serde(default, skip_serializing_if = "Option::is_none")]
427 recovery_budget_hold: Option<RecoveryBudgetHold>,
428 #[serde(default)]
430 pub machine_hold_cause: Option<MachineHoldCause>,
431 #[serde(default)]
433 pub disk_resume_run: Option<String>,
434 #[serde(default)]
436 pub disk_checked_at: Option<Timestamp>,
437 #[serde(default)]
449 pub diagnostic: Option<String>,
450 #[serde(default)]
460 pub blocked_by: Vec<String>,
461 #[serde(default)]
464 pub block_reason: Option<String>,
465 #[serde(default)]
478 pub blocked_from: Option<TaskStatus>,
479 #[serde(default)]
481 pub blocked_at: Option<Timestamp>,
482 #[serde(default)]
493 pub answers: Vec<AnsweredQuestion>,
494 #[serde(default)]
500 pub triage_applied: Vec<String>,
501 #[serde(default)]
507 pub actions_applied: Vec<String>,
508 #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
511 pub decision_effects: std::collections::BTreeMap<String, String>,
512 #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
515 pub superseded_resumes: std::collections::BTreeMap<String, String>,
516 #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
520 pub dispatched_resumes: std::collections::BTreeMap<String, String>,
521 #[serde(default)]
523 pub base_recovery_requests: Vec<String>,
524 #[serde(default)]
529 pub resume_override: Option<OperatorResume>,
530 #[serde(default)]
532 pub repair_grants: Vec<crate::repair_budget::Receipt>,
533 #[serde(default)]
535 pub repair_reconciliations: Vec<crate::repair_budget::reconcile::Receipt>,
536 #[serde(default)]
539 pub resumption: Option<Resumption>,
540 #[serde(default)]
542 pub resumption_history: Vec<Resumption>,
543 #[serde(default)]
545 pub operator_decided_at: Option<Timestamp>,
546 #[serde(default)]
558 pub review_branch: Option<String>,
559 #[serde(default)]
561 pub review_instruction: Option<String>,
562 #[serde(default)]
564 pub pr_recovery: Option<crate::pr_recovery::Selection>,
565 #[serde(default)]
568 pub fresh_start: bool,
569 #[serde(default)]
571 pub replacement: Option<crate::merge_decision::Replacement>,
572 #[serde(default)]
583 pub interrupt: bool,
584 #[serde(default)]
607 pub urgent: bool,
608 #[serde(skip)]
613 pub(crate) unfiled: bool,
614 #[serde(default)]
620 pub attachments: Vec<String>,
621 #[serde(default)]
625 pub followup: Option<FollowUp>,
626 #[serde(default)]
632 pub origin_chat: Option<String>,
633 #[serde(default)]
640 pub overrides: Option<RunOverrides>,
641 #[serde(default)]
648 pub review_of: Option<String>,
649 #[serde(default)]
654 pub held_at: Option<Timestamp>,
655 #[serde(default)]
659 pub park_reason: Option<String>,
660 #[serde(default)]
663 pub chat_notice: Option<ChatNotice>,
664 #[serde(default)]
666 pub chat_notices: Vec<String>,
667 #[serde(default)]
670 pub hold_notice_cause: Option<NoticeCause>,
671 #[serde(default)]
676 pub passes: Vec<TaskPass>,
677 #[serde(default)]
681 pub dispatched_at: Option<Timestamp>,
682 #[serde(default)]
684 pub recovery_budget: Option<RecoveryBudget>,
685 #[serde(default)]
688 pub recovery_admission: Option<RecoveryAdmission>,
689 #[serde(default)]
692 pub recovery_generations: Vec<RecoveryBudget>,
693 pub created_at: Timestamp,
695 pub updated_at: Timestamp,
697}
698
699#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
701pub struct RecoveryAdmission {
702 pub base: String,
704 pub inputs: String,
706}
707
708#[derive(Debug, Clone, Serialize, Deserialize)]
709struct RecoveryBudgetHold {
710 admission: RecoveryAdmission,
711 run: String,
712 pass: usize,
713 held_at: Timestamp,
714 decision: Option<Timestamp>,
715 #[serde(default)]
716 legacy: bool,
717}
718
719#[derive(Debug, Clone, Serialize, Deserialize)]
722pub struct RecoveryBudget {
723 pub instruction: String,
725 pub base: String,
727 pub inputs: String,
729 pub stage: String,
731 pub failures: usize,
733 #[serde(default)]
736 pub progress: Option<String>,
737}
738
739impl RecoveryBudget {
740 fn budget_reason(&self) -> String {
741 format!(
742 "[recovery-budget] {} failed passes against unchanged inputs ({}). Inspect the retained recovery sources and correct the cause, change the inputs, or explicitly release the task to approve another generation. Automatic requeue does not reset this budget.",
743 self.failures, self.stage
744 )
745 }
746}
747
748fn recovery_progress(state: &crate::run::RunState) -> Option<String> {
749 use crate::proc::Quiet as _;
750 use std::hash::{Hash, Hasher};
751 let mut patches = Vec::new();
752 for candidate in state.candidates.iter().filter(|c| c.commits > 0) {
753 let output = std::process::Command::new("git")
754 .current_dir(&state.repo)
755 .args(["diff", "--binary", &state.base_commit, &candidate.branch])
756 .quiet()
757 .output()
758 .ok()?;
759 if !output.status.success() {
760 return None;
761 }
762 patches.push(output.stdout);
763 }
764 patches.sort();
765 patches.dedup();
766 let mut hash = std::collections::hash_map::DefaultHasher::new();
767 patches.hash(&mut hash);
768 Some(format!("{:x}", hash.finish()))
769}
770
771pub(crate) fn recovery_inputs(sources: &crate::refs::Sources) -> String {
775 serde_json::to_string(
776 &sources
777 .start_from
778 .iter()
779 .map(|i| ("start", &i.token, &i.sha))
780 .chain(
781 sources
782 .pick_commits
783 .iter()
784 .map(|i| ("pick", &i.token, &i.sha)),
785 )
786 .collect::<Vec<_>>(),
787 )
788 .unwrap_or_default()
789}
790
791#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
793pub struct NoticeCause {
794 pub stage: String,
796 #[serde(default, skip_serializing_if = "Option::is_none")]
799 pub target: Option<String>,
800 pub run: Option<String>,
802 pub pass: Option<usize>,
804}
805
806pub(crate) fn is_done_notice_key(key: &str) -> bool {
808 key == "done"
809 || key
810 .strip_prefix("done#")
811 .is_some_and(|count| !count.is_empty() && count.bytes().all(|b| b.is_ascii_digit()))
812}
813
814#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
816#[serde(rename_all = "snake_case")]
817pub enum PassCost {
818 Spent,
820 Refunded,
822}
823
824#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
826pub struct TaskPass {
827 pub run: String,
829 pub pass_index: usize,
831 pub cost: PassCost,
833 pub attempts_after: usize,
835 #[serde(default)]
837 pub started_at: Option<Timestamp>,
838 pub settled_at: Timestamp,
840 #[serde(default)]
842 pub parked: Option<crate::run::ParkCause>,
843}
844
845#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
847#[serde(rename_all = "lowercase")]
848pub enum ChatNoticeOutcome {
849 Posted,
851 Skipped,
853}
854
855#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
857pub struct ChatNotice {
858 pub key: String,
860 pub at: Timestamp,
862 pub outcome: ChatNoticeOutcome,
864}
865
866#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
868pub struct RunOverrides {
869 #[serde(default)]
872 pub inherit_daemon_options: bool,
873 #[serde(default)]
875 pub merge: Option<String>,
876 #[serde(default)]
878 pub candidates: Option<usize>,
879 #[serde(default)]
881 pub judges: Option<usize>,
882 #[serde(default)]
884 pub reviewers: Option<usize>,
885 #[serde(default)]
887 pub review_rounds: Option<usize>,
888 #[serde(default)]
890 pub seed: Option<u64>,
891 #[serde(default)]
893 pub config: Option<PathBuf>,
894 #[serde(default, skip_serializing_if = "Option::is_none")]
896 pub build_cache: Option<BuildCache>,
897}
898
899impl RunOverrides {
900 pub fn merge_over(&mut self, other: &RunOverrides) {
902 macro_rules! take {
903 ($($f:ident),*) => {$(
904 if other.$f.is_some() {
905 self.$f.clone_from(&other.$f);
906 }
907 )*};
908 }
909 take!(
910 merge,
911 candidates,
912 judges,
913 reviewers,
914 review_rounds,
915 seed,
916 config,
917 build_cache
918 );
919 }
920
921 pub fn apply(&self, config: &mut crate::config::Config) {
923 if let Some(n) = self.candidates {
924 config.graph.implementers = n;
925 }
926 if let Some(n) = self.judges {
927 config.graph.judges = n;
928 }
929 if let Some(n) = self.reviewers {
930 config.graph.reviewers = n;
931 }
932 if let Some(n) = self.review_rounds {
933 config.graph.review_rounds = n;
934 }
935 if let Some(m) = &self.merge
936 && let Ok(mode) = crate::daemon::merge_mode(m)
937 {
938 config.merge.mode = mode;
939 }
940 if let Some(s) = self.seed {
941 config.blind.seed = Some(s);
942 }
943 if let Some(mode) = self.build_cache {
944 config.verify.build_cache = mode;
945 }
946 }
947}
948
949#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
951pub struct FollowUp {
952 pub run: String,
954 #[serde(default)]
956 pub origin_task: Option<String>,
957 pub pr: String,
959 pub findings: Vec<String>,
961 pub generation: u32,
964}
965
966#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
968pub struct Resumption {
969 pub generation: u64,
971 pub source: String,
973 pub question_id: Option<String>,
975 pub at: Timestamp,
977 pub instruction: String,
979 pub answers_through: usize,
981 pub runs_through: usize,
984 pub cleared_reason: Option<String>,
986 #[serde(default)]
988 pub blocking_evidence: Vec<String>,
989}
990
991#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
994pub struct OperatorResume {
995 pub question_id: String,
997 pub at: Timestamp,
999 #[serde(default)]
1002 pub conductor_rehold: Option<String>,
1003 #[serde(default)]
1006 pub forced: bool,
1007 #[serde(default)]
1014 pub pinned_run: Option<String>,
1015}
1016
1017#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1020pub struct AnsweredQuestion {
1021 pub question: String,
1023 pub answer: String,
1025}
1026
1027impl Task {
1028 pub fn new(title: String, instruction: String, repo: PathBuf, source: Source) -> Self {
1030 let now = Timestamp::now();
1031 let origin_chat = match &source {
1032 Source::Agent { run, node } if node == CHAT_NODE => Some(run.clone()),
1033 _ => None,
1034 };
1035 Self {
1036 schema: SCHEMA,
1037 id: new_id(),
1038 title,
1039 instruction,
1040 sources: crate::refs::Sources::default(),
1041 repo,
1042 reassignments: Vec::new(),
1043 source,
1044 chat: None,
1045 priority: 0,
1046 solo: false,
1047 status: TaskStatus::Queued,
1048 attempts: 0,
1049 attempt_limit: None,
1050 runs: Vec::new(),
1051 startup_failures: Vec::new(),
1052 last_error: None,
1053 hold_reason: None,
1054 hold_source: None,
1055 recovery_budget_hold: None,
1056 machine_hold_cause: None,
1057 disk_resume_run: None,
1058 disk_checked_at: None,
1059 diagnostic: None,
1060 blocked_by: Vec::new(),
1061 block_reason: None,
1062 blocked_from: None,
1063 blocked_at: None,
1064 answers: Vec::new(),
1065 triage_applied: Vec::new(),
1066 actions_applied: Vec::new(),
1067 decision_effects: Default::default(),
1068 superseded_resumes: Default::default(),
1069 dispatched_resumes: Default::default(),
1070 base_recovery_requests: Vec::new(),
1071 resume_override: None,
1072 repair_grants: Vec::new(),
1073 repair_reconciliations: Vec::new(),
1074 resumption: None,
1075 resumption_history: Vec::new(),
1076 operator_decided_at: None,
1077 review_branch: None,
1078 review_instruction: None,
1079 pr_recovery: None,
1080 fresh_start: false,
1081 replacement: None,
1082 interrupt: false,
1083 urgent: false,
1084 unfiled: true,
1085 attachments: Vec::new(),
1086 followup: None,
1087 origin_chat,
1088 overrides: None,
1089 review_of: None,
1090 held_at: None,
1091 park_reason: None,
1092 chat_notice: None,
1093 chat_notices: Vec::new(),
1094 hold_notice_cause: None,
1095 passes: Vec::new(),
1096 dispatched_at: None,
1097 recovery_budget: None,
1098 recovery_admission: None,
1099 recovery_generations: Vec::new(),
1100 created_at: now,
1101 updated_at: now,
1102 }
1103 }
1104
1105 pub(crate) fn reassign_repository(&mut self, repo: PathBuf, actor: &str) {
1107 self.stamp_schema();
1108 if matches!(self.status, TaskStatus::Failed | TaskStatus::Parked) {
1109 self.hold_manual(Some(
1110 "Repository reassigned; inspect history and release to start fresh.".into(),
1111 ));
1112 }
1113 let at = Timestamp::now();
1114 self.reassignments.push(Reassignment {
1115 from: self.repo.clone(),
1116 to: repo.clone(),
1117 actor: actor.to_owned(),
1118 at,
1119 run_boundary: self.runs.len(),
1120 });
1121 self.repo = repo;
1122 self.review_branch = None;
1123 self.review_instruction = None;
1124 self.pr_recovery = None;
1125 self.replacement = None;
1126 self.interrupt = false;
1127 self.resume_override = None;
1128 self.fresh_start = true;
1129 self.operator_decided_at = Some(at);
1130 }
1131
1132 pub fn publication_branch(&self) -> String {
1134 crate::run::task_pr_branch_name(&self.id, self.reassignments.len())
1135 }
1136
1137 pub fn execution_runs(&self) -> &[String] {
1139 let boundary = self.reassignments.last().map_or(0, |r| r.run_boundary);
1140 self.runs.get(boundary..).unwrap_or_default()
1141 }
1142
1143 pub fn execution_run(&self, run: &str) -> bool {
1145 self.execution_runs().iter().any(|id| id == run)
1146 }
1147
1148 pub(crate) fn assignment_accepts(&self, run: &crate::run::RunState) -> bool {
1150 self.reassignments.last().is_none_or(|boundary| {
1151 self.execution_run(&run.id)
1152 && run.task_assignment == self.reassignments.len()
1153 && run.created_at > boundary.at
1154 && run
1155 .repo
1156 .canonicalize()
1157 .ok()
1158 .zip(self.repo.canonicalize().ok())
1159 .is_some_and(|(run_repo, task_repo)| run_repo == task_repo)
1160 })
1161 }
1162
1163 pub(crate) fn stale_question(&self, q: &crate::ask::Question) -> bool {
1165 self.reassignments
1166 .last()
1167 .is_some_and(|r| q.asked_at <= r.at)
1168 || (self.runs.contains(&q.run) && !self.execution_run(&q.run))
1169 }
1170
1171 pub fn chat_talk(&self) -> Option<&str> {
1173 if let Some(id) = &self.origin_chat {
1174 return Some(id);
1175 }
1176 match &self.source {
1177 Source::Agent { run, node } if node == CHAT_NODE => Some(run),
1178 _ => None,
1179 }
1180 }
1181
1182 pub fn filed_by_chat(&self) -> Option<&str> {
1186 match &self.source {
1187 Source::Agent { run, node } if node == CHAT_NODE => Some(run),
1188 _ => None,
1189 }
1190 }
1191
1192 pub fn chat_notice_key(&self) -> Option<String> {
1195 match self.status {
1196 TaskStatus::Done => Some("done".to_owned()),
1197 TaskStatus::Held => {
1198 let cause = self
1199 .hold_notice_cause
1200 .clone()
1201 .unwrap_or_else(|| self.unresolved_hold_cause());
1202 Some(format!(
1203 "cause:{}",
1204 serde_json::to_string(&cause).expect("cause")
1205 ))
1206 }
1207 TaskStatus::Blocked => {
1208 let ids: std::collections::BTreeSet<_> = self.blocked_by.iter().collect();
1209 let evidence = self
1212 .hold_notice_cause
1213 .as_ref()
1214 .filter(|c| c.stage.starts_with("conductor-evidence:"));
1215 Some(format!(
1216 "dependencies:{}",
1217 serde_json::to_string(&(ids, evidence)).expect("ids")
1218 ))
1219 }
1220 _ => None,
1221 }
1222 }
1223
1224 fn unresolved_hold_cause(&self) -> NoticeCause {
1225 NoticeCause {
1226 stage: "hold".into(),
1227 target: None,
1228 run: self.runs.last().cloned(),
1229 pass: None,
1230 }
1231 }
1232
1233 pub(crate) fn legacy_chat_notice_key(&self) -> Option<String> {
1235 let key = match self.status {
1236 TaskStatus::Held if self.hold_notice_cause.is_none() => Some(format!(
1237 "held#{}",
1238 self.held_at.map(|t| t.to_string()).unwrap_or_default()
1239 )),
1240 TaskStatus::Blocked => Some(format!(
1241 "blocked#{}#{}",
1242 self.blocked_by.join(","),
1243 self.block_reason.as_deref().unwrap_or_default()
1244 )),
1245 _ => None,
1246 };
1247 key.filter(|key| self.legacy_notice_matches(key))
1248 }
1249
1250 pub(crate) fn legacy_notice_matches(&self, key: &str) -> bool {
1251 match self.status {
1252 TaskStatus::Held if self.hold_notice_cause.is_none() => key
1253 .strip_prefix("held#")
1254 .is_some_and(|time| time.is_empty() || time.parse::<Timestamp>().is_ok()),
1255 TaskStatus::Blocked
1256 if self
1257 .hold_notice_cause
1258 .as_ref()
1259 .is_none_or(|c| !c.stage.starts_with("conductor-evidence:")) =>
1260 {
1261 key.strip_prefix("blocked#").is_some_and(|tail| {
1262 let Some((ids, _)) = tail.split_once('#') else {
1263 return false;
1264 };
1265 let old: std::collections::BTreeSet<_> =
1266 ids.split(',').filter(|id| !id.is_empty()).collect();
1267 let current: std::collections::BTreeSet<_> =
1268 self.blocked_by.iter().map(String::as_str).collect();
1269 old == current
1270 })
1271 }
1272 _ => false,
1273 }
1274 }
1275
1276 fn import_chat_notice(&mut self) {
1277 if let Some(n) = &self.chat_notice {
1278 let key = if is_done_notice_key(&n.key) {
1279 "done".to_owned()
1280 } else if self.legacy_notice_matches(&n.key) {
1281 self.chat_notice_key().unwrap_or_else(|| n.key.clone())
1282 } else {
1283 n.key.clone()
1284 };
1285 if !self.chat_notices.contains(&key) {
1286 self.chat_notices.push(key);
1287 }
1288 }
1289 }
1290
1291 pub(crate) fn notice_cause(&mut self, stage: &str, run: Option<&str>, pass: Option<usize>) {
1294 self.import_chat_notice();
1295 self.hold_notice_cause = Some(NoticeCause {
1296 stage: stage.to_owned(),
1297 target: None,
1298 run: run.map(str::to_owned),
1299 pass,
1300 });
1301 }
1302
1303 pub(crate) fn startup_notice_cause(&mut self, stage: &str) {
1306 let recovery_only = matches!(
1307 stage,
1308 "startup-source" | "startup-candidates" | "startup-public-head"
1309 );
1310 match self.hold_notice_cause.as_ref() {
1311 Some(cause) if recovery_only && !cause.stage.starts_with("startup-") => return,
1312 None if recovery_only
1313 && self
1314 .chat_notice
1315 .as_ref()
1316 .is_some_and(|n| !is_done_notice_key(&n.key)) =>
1317 {
1318 return;
1319 }
1320 _ => {}
1321 }
1322 self.notice_cause(stage, None, None);
1323 }
1324
1325 pub(crate) fn fail_startup(
1328 &mut self,
1329 stage: &str,
1330 why: impl Into<String>,
1331 max_attempts: usize,
1332 ) {
1333 let unresolved = self.hold_notice_cause.clone();
1334 self.fail(why, max_attempts);
1335 self.hold_notice_cause = unresolved;
1336 self.startup_notice_cause(stage);
1337 }
1338
1339 pub(crate) fn fail_startup_target(
1341 &mut self,
1342 stage: &str,
1343 target: String,
1344 why: impl Into<String>,
1345 max_attempts: usize,
1346 ) {
1347 self.fail_startup(stage, why, max_attempts);
1348 if let Some(cause) = self.hold_notice_cause.as_mut() {
1349 cause.target = Some(target);
1350 }
1351 }
1352
1353 pub fn chat_notice_due(&self) -> Option<String> {
1355 self.filed_by_chat()?;
1356 if self.schema < 13 {
1357 return None;
1358 }
1359 let key = self.chat_notice_key()?;
1360 if self.chat_notices.contains(&key) {
1361 return None;
1362 }
1363 match &self.chat_notice {
1364 Some(n)
1365 if n.key == key
1366 || (key == "done" && is_done_notice_key(&n.key))
1367 || self.legacy_notice_matches(&n.key) =>
1368 {
1369 None
1370 }
1371 _ => Some(key),
1372 }
1373 }
1374
1375 pub fn short(&self) -> &str {
1377 short(&self.id)
1378 }
1379
1380 pub fn mark_triage_applied(&mut self, question_id: &str) {
1382 if !self.triage_applied(question_id) {
1383 self.triage_applied.push(question_id.to_owned());
1384 }
1385 }
1386
1387 pub fn action_applied(&self, question_id: &str) -> bool {
1390 self.actions_applied.iter().any(|id| id == question_id)
1391 }
1392
1393 pub fn mark_action_applied(&mut self, question_id: &str) {
1395 if !self.action_applied(question_id) {
1396 self.actions_applied.push(question_id.to_owned());
1397 }
1398 }
1399
1400 pub fn triage_applied(&self, question_id: &str) -> bool {
1402 self.triage_applied.iter().any(|id| id == question_id)
1403 }
1404
1405 pub fn start(&mut self, run: String) {
1418 self.stamp_schema();
1419 self.status = TaskStatus::Running;
1420 self.attempts += 1;
1421 self.runs.retain(|id| id != &run);
1422 if let Some(pin) = &self.resume_override
1423 && pin.pinned_run.as_ref() == Some(&run)
1424 && !pin.question_id.is_empty()
1425 {
1426 self.dispatched_resumes
1427 .insert(pin.question_id.clone(), run.clone());
1428 }
1429 self.runs.push(run);
1430 self.last_error = None;
1431 self.park_reason = None;
1432 self.fresh_start = false;
1433 self.interrupt = false;
1434 self.resume_override = None;
1436 self.disk_resume_run = None;
1439 }
1440
1441 pub fn record_startup_failure(&mut self, failure: crate::run::StartupFailure) {
1443 if !self.startup_failures.iter().any(|f| f.run == failure.run) {
1444 self.startup_failures.push(failure);
1445 }
1446 }
1447
1448 pub fn link_run(&mut self, run: &str) -> bool {
1453 if self.runs.iter().any(|r| r == run) {
1454 return false;
1455 }
1456 self.runs.push(run.to_owned());
1457 true
1458 }
1459
1460 pub fn succeed(&mut self) {
1470 self.stamp_schema();
1471 self.status = TaskStatus::Done;
1472 self.resume_override = None;
1473 self.last_error = None;
1474 self.park_reason = None;
1475 self.hold_reason = None;
1476 self.hold_source = None;
1477 self.machine_hold_cause = None;
1478 self.disk_resume_run = None;
1479 self.disk_checked_at = None;
1480 self.diagnostic = None;
1481 self.blocked_by.clear();
1482 self.block_reason = None;
1483 self.blocked_from = None;
1484 }
1485
1486 pub fn already_landed(&mut self, note: impl Into<String>) {
1494 self.succeed();
1495 self.attempts = self.attempts.saturating_sub(1);
1496 self.last_error = Some(note.into());
1497 }
1498
1499 pub fn superseded_attempts(&self, last_run_succeeded: bool) -> &[String] {
1529 if self.status != TaskStatus::Done || !last_run_succeeded || self.execution_runs().len() < 2
1530 {
1531 return &[];
1532 }
1533 &self.execution_runs()[..self.execution_runs().len() - 1]
1534 }
1535
1536 pub fn successor_of(&self, run: &str) -> Option<&String> {
1544 let runs = self.execution_runs();
1545 let pos = runs.iter().rposition(|r| r == run)?;
1546 runs.get(pos + 1)
1547 }
1548
1549 pub fn earlier_attempts(&self) -> &[String] {
1556 self.execution_runs()
1557 }
1558
1559 fn preserve_legacy_build_cache(&mut self) {
1560 if self.schema < 23 {
1561 let overrides = self.overrides.get_or_insert_with(|| RunOverrides {
1562 inherit_daemon_options: true,
1563 ..RunOverrides::default()
1564 });
1565 overrides.build_cache.get_or_insert(BuildCache::Shared);
1566 }
1567 }
1568
1569 fn stamp_schema(&mut self) {
1574 self.preserve_legacy_build_cache();
1575 if self.schema < RECOVERY_HOLD_SCHEMA && self.recovery_budget_hold.is_none() {
1576 self.recovery_budget_hold = self.legacy_recovery_budget_hold();
1577 }
1578 self.schema = self.schema.max(SCHEMA);
1579 }
1580
1581 fn note_held(&mut self) {
1584 self.stamp_schema();
1585 self.recovery_budget_hold = None;
1586 let continuing = self.status == TaskStatus::Held
1587 || (self.status == TaskStatus::Blocked
1588 && (self.blocked_from == Some(TaskStatus::Held)
1589 || (self.blocked_from.is_none()
1590 && (self.hold_reason.is_some() || self.hold_source.is_some()))));
1591 if !continuing || self.held_at.is_none() {
1592 self.held_at = Some(Timestamp::now());
1593 }
1594 }
1595
1596 pub fn fail(&mut self, why: impl Into<String>, max_attempts: usize) {
1612 let why = why.into();
1613 if self.status == TaskStatus::Running {
1614 let run = self.runs.last().cloned();
1615 self.notice_cause("run-failed", run.as_deref(), Some(self.attempts));
1616 }
1617 self.diagnostic = None;
1618 self.park_reason = None;
1619 self.status = if self.attempts >= self.effective_attempt_limit(max_attempts) {
1620 self.note_held();
1621 self.hold_source = Some(HoldSource::Machine);
1622 self.machine_hold_cause = None;
1623 self.disk_resume_run = None;
1624 self.disk_checked_at = None;
1625 self.hold_reason = Some(why.clone());
1626 TaskStatus::Held
1627 } else {
1628 TaskStatus::Failed
1629 };
1630 self.last_error = Some(why);
1631 }
1632
1633 pub fn stall(&mut self, why: impl Into<String>) {
1643 self.last_error = Some(why.into());
1644 self.diagnostic = None;
1645 self.attempts = self.attempts.saturating_sub(1);
1646 self.status = TaskStatus::Failed;
1647 }
1648
1649 pub fn park(&mut self, why: impl Into<String>) {
1655 self.diagnostic = None;
1656 self.attempts = self.attempts.saturating_sub(1);
1657 self.status = TaskStatus::Parked;
1658 self.park_reason = Some(why.into());
1659 self.stamp_schema();
1662 }
1663
1664 pub fn record_pass(
1666 &mut self,
1667 run: &str,
1668 pass_index: usize,
1669 attempts_before: usize,
1670 parked: Option<crate::run::ParkCause>,
1671 ) {
1672 self.record_pass_at(run, pass_index, None, attempts_before, parked);
1673 }
1674
1675 pub fn record_pass_at(
1678 &mut self,
1679 run: &str,
1680 pass_index: usize,
1681 started_at: Option<Timestamp>,
1682 attempts_before: usize,
1683 parked: Option<crate::run::ParkCause>,
1684 ) {
1685 if self
1686 .passes
1687 .iter()
1688 .any(|p| p.run == run && p.pass_index == pass_index)
1689 {
1690 return;
1691 }
1692 let cost = if self.attempts < attempts_before {
1693 PassCost::Refunded
1694 } else {
1695 PassCost::Spent
1696 };
1697 self.passes.push(TaskPass {
1698 run: run.to_owned(),
1699 pass_index,
1700 started_at: self.dispatched_at.or(started_at),
1701 cost,
1702 attempts_after: self.attempts,
1703 settled_at: Timestamp::now(),
1704 parked,
1705 });
1706 self.stamp_schema();
1707 }
1708
1709 pub(crate) fn upgrade_resume_key(&self) -> Option<(Timestamp, &str)> {
1712 if self.status != TaskStatus::Parked || self.fresh_start {
1713 return None;
1714 }
1715 let pass = self.passes.last()?;
1716 if self.execution_runs().last() != Some(&pass.run)
1717 || !matches!(pass.parked, Some(crate::run::ParkCause::Upgrade { .. }))
1718 {
1719 return None;
1720 }
1721 Some((pass.started_at.unwrap_or(pass.settled_at), &self.id))
1724 }
1725
1726 pub fn operator_held(&self) -> bool {
1732 self.status == TaskStatus::Held && !matches!(self.hold_source, Some(HoldSource::Machine))
1733 }
1734
1735 pub fn hold_manual(&mut self, reason: Option<String>) {
1745 self.operator_decided_at = Some(Timestamp::now());
1747 self.hold_unrequested_retry(reason);
1748 }
1749
1750 pub(crate) fn hold_unrequested_retry(&mut self, reason: Option<String>) {
1753 self.park_reason = None;
1754 self.note_held();
1755 self.status = TaskStatus::Held;
1756 if reason.is_some() {
1757 self.hold_reason = reason;
1758 }
1759 self.hold_source = Some(HoldSource::Manual);
1760 self.machine_hold_cause = None;
1761 self.disk_resume_run = None;
1762 self.disk_checked_at = None;
1763 self.blocked_by.clear();
1764 self.block_reason = None;
1765 self.blocked_from = None;
1766 }
1767
1768 pub fn hold_machine(&mut self, reason: Option<String>) {
1773 self.park_reason = None;
1774 self.note_held();
1775 self.status = TaskStatus::Held;
1776 if reason.is_some() {
1777 self.hold_reason = reason;
1778 }
1779 self.hold_source = Some(HoldSource::Machine);
1780 self.machine_hold_cause = None;
1781 self.disk_resume_run = None;
1782 self.disk_checked_at = None;
1783 self.blocked_by.clear();
1784 self.block_reason = None;
1785 self.blocked_from = None;
1786 }
1787
1788 pub(crate) fn mark_disk_capacity(&mut self) {
1790 self.machine_hold_cause = Some(MachineHoldCause::DiskCapacity {
1791 reason: self.hold_reason.clone().unwrap_or_default(),
1792 before_start: false,
1793 });
1794 }
1795
1796 pub(crate) fn mark_startup_disk_capacity(&mut self) {
1797 self.machine_hold_cause = Some(MachineHoldCause::DiskCapacity {
1798 reason: self.hold_reason.clone().unwrap_or_default(),
1799 before_start: true,
1800 });
1801 }
1802
1803 pub(crate) fn disk_wait_run(&self) -> Option<&String> {
1804 if self.has_disk_capacity_cause()
1805 && matches!(
1806 self.machine_hold_cause,
1807 Some(MachineHoldCause::DiskCapacity {
1808 before_start: true,
1809 ..
1810 })
1811 )
1812 {
1813 None
1814 } else {
1815 self.execution_runs().last()
1816 }
1817 }
1818
1819 pub fn has_disk_capacity_cause(&self) -> bool {
1821 matches!(
1822 (&self.machine_hold_cause, self.hold_reason.as_deref()),
1823 (Some(MachineHoldCause::DiskCapacity { reason, .. }), Some(now)) if reason == now
1824 )
1825 }
1826
1827 pub(crate) fn resume_disk_wait(&mut self) {
1829 let retained = self.disk_wait_run().cloned();
1830 self.status = TaskStatus::Queued;
1831 self.held_at = None;
1832 self.hold_source = None;
1833 self.hold_reason = None;
1834 self.machine_hold_cause = None;
1835 self.last_error = None;
1836 self.disk_resume_run = retained;
1837 }
1838
1839 pub fn block(&mut self, blocked_by: Vec<String>, reason: Option<String>) {
1849 self.stamp_schema();
1850 let before: std::collections::BTreeSet<_> = self.blocked_by.iter().collect();
1851 let after: std::collections::BTreeSet<_> = blocked_by.iter().collect();
1852 if self.status != TaskStatus::Blocked || before != after {
1853 self.blocked_at = Some(Timestamp::now());
1854 }
1855 if self.status != TaskStatus::Blocked {
1856 self.blocked_from = Some(self.status);
1857 }
1858 self.status = TaskStatus::Blocked;
1859 self.blocked_by = blocked_by;
1860 self.block_reason = reason;
1861 }
1862
1863 pub fn unblock(&mut self, resolved_id: &str) {
1886 if self.status != TaskStatus::Blocked {
1887 return;
1888 }
1889 self.blocked_by.retain(|id| id != resolved_id);
1890 self.restore_if_unblocked();
1891 }
1892
1893 pub fn dependency_deleted(&mut self, deleted_id: &str) -> bool {
1904 if self.status != TaskStatus::Blocked || !self.blocked_by.iter().any(|b| b == deleted_id) {
1905 return false;
1906 }
1907 self.blocked_by.retain(|id| id != deleted_id);
1908 self.restore_if_unblocked();
1909 true
1910 }
1911
1912 fn restore_if_unblocked(&mut self) {
1916 if self.blocked_by.is_empty() {
1917 self.status = match self.blocked_from {
1918 Some(TaskStatus::Running) => TaskStatus::Queued,
1919 Some(other) => other,
1920 None if self.hold_reason.is_some() || self.hold_source.is_some() => {
1921 TaskStatus::Held
1922 }
1923 None => TaskStatus::Queued,
1924 };
1925 self.block_reason = None;
1926 self.blocked_from = None;
1927 }
1928 }
1929
1930 pub fn record_answer(&mut self, question: String, answer: String) {
1935 self.answers.push(AnsweredQuestion { question, answer });
1936 }
1937
1938 pub fn request_review(&mut self, branch: String) {
1942 self.release();
1943 self.review_branch = Some(branch);
1944 self.review_instruction = Some(self.instruction.clone());
1945 }
1946
1947 pub fn requeue(&mut self) {
1950 self.release();
1951 self.review_branch = None;
1953 self.review_instruction = None;
1954 self.fresh_start = true;
1955 }
1956
1957 pub fn hold_for_handover(&mut self, branch: Option<String>, reason: String) {
1966 if branch.is_some() {
1967 self.review_branch = branch;
1968 self.review_instruction = Some(self.instruction.clone());
1969 }
1970 self.hold_machine(Some(reason));
1971 }
1972
1973 pub fn set_urgent(&mut self, urgent: bool) -> Result<()> {
1975 if !matches!(self.status, TaskStatus::Queued | TaskStatus::Held) {
1976 bail!(
1977 "task {} is {}; urgent can only change while queued or held; \
1978 wait for the active attempt to finish and requeue or hold the task first",
1979 self.short(),
1980 self.status.as_str()
1981 );
1982 }
1983 self.urgent = urgent;
1984 Ok(())
1985 }
1986
1987 pub fn set_priority(&mut self, priority: i32) -> Result<()> {
1996 if self.status == TaskStatus::Running {
1997 bail!(
1998 "task {} is running; its priority cannot be changed until \
1999 this attempt finishes",
2000 self.short()
2001 );
2002 }
2003 self.priority = priority;
2004 Ok(())
2005 }
2006
2007 pub fn set_interrupt(&mut self, interrupt: bool) -> Result<()> {
2022 if interrupt && !self.status.runnable() {
2023 bail!(
2024 "task {} is {}; only a queued or failed task can be marked \
2025 to interrupt",
2026 self.short(),
2027 self.status.as_str()
2028 );
2029 }
2030 self.interrupt = interrupt;
2031 Ok(())
2032 }
2033
2034 pub fn effective_attempt_limit(&self, daemon_limit: usize) -> usize {
2036 self.attempt_limit.map_or(daemon_limit, NonZeroUsize::get)
2037 }
2038
2039 pub fn change_attempt_limit(&mut self, limit: Option<NonZeroUsize>) -> Result<()> {
2042 if !matches!(self.status, TaskStatus::Queued | TaskStatus::Held) {
2043 bail!("only queued or held tasks can change the attempt limit");
2044 }
2045 self.stamp_schema();
2046 self.attempt_limit = limit;
2047 Ok(())
2048 }
2049
2050 pub fn implementers(&self) -> Option<usize> {
2052 if self.solo {
2053 Some(1)
2054 } else {
2055 self.overrides.as_ref().and_then(|o| o.candidates)
2056 }
2057 }
2058
2059 pub fn build_cache_override(
2063 &self,
2064 config: &crate::config::Config,
2065 ) -> Option<(BuildCache, &'static str)> {
2066 self.overrides
2067 .as_ref()
2068 .and_then(|o| o.build_cache)
2069 .map(|mode| (mode, "task-override"))
2070 .or_else(|| {
2071 (self.urgent && crate::build_target::urgent_isolation(config))
2072 .then_some((BuildCache::Isolated, "urgent"))
2073 })
2074 }
2075
2076 pub fn change_build_cache(&mut self, mode: Option<BuildCache>) -> Result<()> {
2079 if !matches!(self.status, TaskStatus::Queued | TaskStatus::Held) {
2080 bail!(
2081 "task {} is {}; only queued or held tasks can change build cache",
2082 self.short(),
2083 self.status.as_str()
2084 );
2085 }
2086 self.stamp_schema();
2087 if self.overrides.is_some() || mode.is_some() {
2088 let overrides = self.overrides.get_or_insert_with(|| RunOverrides {
2089 inherit_daemon_options: true,
2090 ..RunOverrides::default()
2091 });
2092 overrides.build_cache = mode;
2093 }
2094 Ok(())
2095 }
2096
2097 pub fn change_implementers(&mut self, count: u8) -> Result<()> {
2100 self.check_implementers_editable()?;
2101 let explicit = self.overrides.as_ref().and_then(|o| o.config.as_deref());
2102 let (mut config, _) = crate::config::Config::discover(&self.repo, explicit)?;
2103 if let Some(o) = &self.overrides {
2104 o.apply(&mut config);
2105 }
2106 self.set_implementers(count, &config)
2107 }
2108
2109 fn check_implementers_editable(&self) -> Result<()> {
2110 if !matches!(self.status, TaskStatus::Queued | TaskStatus::Held) {
2111 bail!(
2112 "task {} is {}; only queued or held tasks can change implementers",
2113 self.short(),
2114 self.status.as_str()
2115 );
2116 }
2117 Ok(())
2118 }
2119
2120 pub fn set_implementers(&mut self, count: u8, config: &crate::config::Config) -> Result<()> {
2122 self.check_implementers_editable()?;
2123 crate::talk::check_implementers(count, config).map_err(anyhow::Error::msg)?;
2124 self.stamp_schema();
2125 self.solo = count == 1;
2126 let mut overrides = self.overrides.clone().unwrap_or_else(|| RunOverrides {
2127 inherit_daemon_options: true,
2128 ..Default::default()
2129 });
2130 overrides.candidates = (count > 1).then_some(usize::from(count));
2131 let mut settings = overrides.clone();
2132 settings.inherit_daemon_options = false;
2133 self.overrides = if overrides.inherit_daemon_options && settings == RunOverrides::default()
2135 {
2136 None
2137 } else {
2138 Some(overrides)
2139 };
2140 Ok(())
2141 }
2142
2143 pub fn edit(&mut self, title: String, instruction: String) -> Result<()> {
2155 if !matches!(self.status, TaskStatus::Queued | TaskStatus::Held) {
2156 bail!(
2157 "task {} is {}; only a queued or held task's instruction can \
2158 be edited",
2159 self.short(),
2160 self.status.as_str()
2161 );
2162 }
2163 if self.review_branch.is_some() && self.review_instruction.is_none() {
2166 self.review_instruction = Some(self.instruction.clone());
2167 }
2168 if self.instruction != instruction {
2169 self.resume_override = None;
2172 }
2173 if self.status == TaskStatus::Held && self.machine_hold_cause.is_some() {
2174 self.hold_manual(self.hold_reason.clone());
2175 }
2176 self.machine_hold_cause = None;
2177 self.disk_resume_run = None;
2178 self.disk_checked_at = None;
2179 self.title = title;
2180 self.instruction = instruction;
2181 Ok(())
2182 }
2183
2184 pub fn handed_off(&mut self, why: impl Into<String>) {
2204 let why = why.into();
2205 self.diagnostic = None;
2206 self.note_held();
2207 self.status = TaskStatus::Held;
2208 self.hold_source = Some(HoldSource::Machine);
2209 self.machine_hold_cause = None;
2210 self.disk_resume_run = None;
2211 self.disk_checked_at = None;
2212 self.hold_reason = Some(why.clone());
2213 self.last_error = Some(why);
2214 }
2215
2216 pub fn release_operator(&mut self, source: &str, question_id: Option<&str>) {
2218 self.recovery_budget = None;
2219 self.recovery_generations.clear();
2220 self.recovery_admission = None;
2221 if self
2222 .resumption
2223 .as_ref()
2224 .is_some_and(|r| r.instruction != self.instruction)
2225 {
2226 self.resume_override = None;
2229 }
2230 let approval = Resumption {
2231 generation: self.resumption.as_ref().map_or(1, |r| r.generation + 1),
2232 source: source.to_owned(),
2233 question_id: question_id.map(str::to_owned),
2234 at: Timestamp::now(),
2235 instruction: self.instruction.clone(),
2236 answers_through: self.answers.len(),
2237 runs_through: self.runs.len(),
2238 blocking_evidence: Vec::new(),
2239 cleared_reason: self
2240 .hold_reason
2241 .clone()
2242 .or_else(|| self.block_reason.clone()),
2243 };
2244 self.release();
2245 self.operator_decided_at = Some(approval.at);
2246 if let Some(previous) = self.resumption.replace(approval) {
2247 self.resumption_history.push(previous);
2248 }
2249 }
2250
2251 pub(crate) fn recovery_failed(&mut self, state: &crate::run::RunState) {
2253 let (base, inputs) = self.recovery_admission.as_ref().map_or_else(
2254 || (state.base_commit.clone(), recovery_inputs(&state.sources)),
2255 |a| (a.base.clone(), a.inputs.clone()),
2256 );
2257 let progress = recovery_progress(state);
2258 let stage = if state.prep_failure.is_some() {
2259 "preparation"
2260 } else {
2261 "execution"
2262 };
2263 let matches = |b: &RecoveryBudget| {
2264 b.instruction == self.instruction
2265 && b.base == base
2266 && b.inputs == inputs
2267 && (progress.is_none() || b.progress == progress)
2268 };
2269 if !self.recovery_budget.as_ref().is_some_and(matches) {
2270 let previous = self
2271 .recovery_generations
2272 .iter()
2273 .position(matches)
2274 .map(|index| self.recovery_generations.remove(index));
2275 if let Some(old) = self.recovery_budget.take() {
2276 self.recovery_generations.push(old);
2277 }
2278 self.recovery_budget = previous;
2279 }
2280 if let Some(budget) = &mut self.recovery_budget {
2281 budget.failures = budget.failures.saturating_add(1);
2282 budget.stage = stage.to_owned();
2283 } else {
2284 self.recovery_budget = Some(RecoveryBudget {
2285 instruction: self.instruction.clone(),
2286 base,
2287 inputs,
2288 stage: stage.to_owned(),
2289 failures: 1,
2290 progress,
2291 });
2292 }
2293 }
2294
2295 pub(crate) fn recovery_exhausted(
2296 &self,
2297 base: &str,
2298 inputs: &str,
2299 limit: usize,
2300 ) -> Option<String> {
2301 let same_input = |b: &&RecoveryBudget| {
2302 b.instruction == self.instruction && b.base == base && b.inputs == inputs
2303 };
2304 let budget = self
2305 .recovery_budget
2306 .as_ref()
2307 .filter(same_input)
2308 .or_else(|| self.recovery_generations.iter().rev().find(same_input))?;
2309 (budget.failures >= limit.max(1)).then(|| budget.budget_reason())
2310 }
2311
2312 pub(crate) fn hold_recovery_budget(&mut self, reason: String, admission: RecoveryAdmission) {
2313 self.hold_unrequested_retry(Some(reason));
2314 if let Some(pass) = self.passes.last()
2315 && self.execution_runs().last() == Some(&pass.run)
2316 {
2317 self.recovery_budget_hold = Some(RecoveryBudgetHold {
2318 admission,
2319 run: pass.run.clone(),
2320 pass: pass.pass_index,
2321 held_at: self.held_at.expect("hold timestamp just recorded"),
2322 decision: self.operator_decided_at,
2323 legacy: false,
2324 });
2325 }
2326 }
2327
2328 fn matches_budget_hold(&self, admission: &RecoveryAdmission) -> bool {
2329 self.status == TaskStatus::Held
2330 && self.hold_source == Some(HoldSource::Manual)
2331 && self.machine_hold_cause.is_none()
2332 && self.recovery_budget.as_ref().is_some_and(|budget| {
2333 budget.instruction == self.instruction
2334 && budget.base == admission.base
2335 && budget.inputs == admission.inputs
2336 && budget.stage == "execution"
2337 && budget.failures > 0
2338 && self
2339 .hold_reason
2340 .as_ref()
2341 .is_some_and(|reason| *reason == budget.budget_reason())
2342 })
2343 }
2344
2345 fn legacy_recovery_budget_hold(&self) -> Option<RecoveryBudgetHold> {
2346 let held_at = self.held_at?;
2347 let settled = self.passes.last()?;
2348 let admission = self.recovery_admission.as_ref()?;
2349 if !self.matches_budget_hold(admission)
2350 || self.execution_runs().last() != Some(&settled.run)
2351 || settled.cost != PassCost::Spent
2352 || settled.parked.is_some()
2353 || settled.settled_at > held_at
2354 || self.operator_decided_at.is_some_and(|at| at >= held_at)
2355 {
2356 return None;
2357 }
2358 Some(RecoveryBudgetHold {
2359 admission: admission.clone(),
2360 run: settled.run.clone(),
2361 pass: settled.pass_index,
2362 held_at,
2363 decision: self.operator_decided_at,
2364 legacy: true,
2365 })
2366 }
2367
2368 pub(crate) fn held_for_recovery_budget(&self, run: &crate::run::RunState) -> bool {
2369 let (Some(held_at), Some(settled), Some(pass), Some(admission)) = (
2370 self.held_at,
2371 self.passes.last(),
2372 run.passes.last(),
2373 self.recovery_admission.as_ref(),
2374 ) else {
2375 return false;
2376 };
2377 if !self.matches_budget_hold(admission)
2378 || self.execution_runs().last() != Some(&run.id)
2379 || settled.run != run.id
2380 || settled.pass_index != pass.index
2381 || settled.cost != PassCost::Spent
2382 || settled.parked.is_some()
2383 || settled.settled_at < pass.started_at
2384 || settled.settled_at > held_at
2385 || self.operator_decided_at.is_some_and(|at| at >= held_at)
2386 || !crate::daemon::compatible_run_instruction(run, self)
2387 {
2388 return false;
2389 }
2390 match &self.recovery_budget_hold {
2391 Some(hold) => {
2392 hold.run == run.id
2393 && hold.pass == pass.index
2394 && hold.held_at == held_at
2395 && hold.decision == self.operator_decided_at
2396 && &hold.admission == admission
2397 && (!hold.legacy
2398 || self
2399 .operator_decided_at
2400 .is_none_or(|at| at < pass.started_at))
2401 }
2402 None => {
2403 self.schema < RECOVERY_HOLD_SCHEMA
2404 && self
2405 .operator_decided_at
2406 .is_none_or(|at| at < pass.started_at)
2407 }
2408 }
2409 }
2410
2411 pub(crate) fn queue_repair(&mut self, receipt: &crate::repair_budget::Receipt) {
2412 self.stamp_schema();
2413 self.repair_grants.push(receipt.clone());
2414 self.status = TaskStatus::Queued;
2415 self.hold_source = None;
2416 self.hold_reason = None;
2417 self.held_at = None;
2418 self.recovery_budget_hold = None;
2419 self.resume_override = Some(OperatorResume {
2420 question_id: String::new(),
2421 at: receipt.at,
2422 conductor_rehold: None,
2423 forced: true,
2424 pinned_run: Some(receipt.request.run.clone()),
2425 });
2426 }
2427
2428 pub fn release(&mut self) {
2432 self.import_chat_notice();
2435 if self.hold_notice_cause.is_none()
2436 && matches!(self.status, TaskStatus::Held | TaskStatus::Blocked)
2437 {
2438 self.hold_notice_cause = Some(self.unresolved_hold_cause());
2439 }
2440 let refused_handover = self.status == TaskStatus::Held
2441 && self.hold_source == Some(HoldSource::Machine)
2442 && self.review_branch.is_some()
2443 && self
2444 .review_instruction
2445 .as_ref()
2446 .is_none_or(|i| *i == self.instruction);
2447 self.status = TaskStatus::Queued;
2448 self.held_at = None;
2449 self.attempts = 0;
2450 self.last_error = None;
2451 self.park_reason = None;
2452 self.hold_reason = None;
2455 self.hold_source = None;
2456 self.machine_hold_cause = None;
2457 self.disk_resume_run = None;
2458 self.disk_checked_at = None;
2459 self.diagnostic = None;
2460 self.blocked_by.clear();
2465 self.block_reason = None;
2466 self.blocked_from = None;
2467 if !refused_handover {
2471 self.review_branch = None;
2472 self.review_instruction = None;
2473 }
2474 self.fresh_start = false;
2475 }
2476}
2477
2478fn copy_new(dir: &Path, src: &Path, name: &str) -> Result<(String, PathBuf)> {
2482 use std::io::ErrorKind;
2483 let (stem, ext) = match name.rfind('.') {
2484 Some(i) if i > 0 => (&name[..i], &name[i..]),
2485 _ => (name, ""),
2486 };
2487 for n in 1u32.. {
2488 let candidate = if n == 1 {
2489 name.to_owned()
2490 } else {
2491 let suffix = format!("-{n}");
2492 let room = 64usize.saturating_sub(suffix.len() + ext.len());
2493 let stem: String = stem.chars().take(room).collect();
2494 format!("{stem}{suffix}{ext}")
2495 };
2496 if !crate::ask::valid_asset_name(&candidate) {
2497 bail!("no valid attachment name is left for `{name}`");
2498 }
2499 let path = dir.join(&candidate);
2500 match std::fs::OpenOptions::new()
2501 .write(true)
2502 .create_new(true)
2503 .open(&path)
2504 {
2505 Ok(mut out) => {
2506 let copied = std::fs::File::open(src)
2507 .and_then(|mut input| std::io::copy(&mut input, &mut out));
2508 if let Err(e) = copied {
2509 drop(out);
2510 let _ = std::fs::remove_file(&path);
2511 return Err(e).with_context(|| format!("copy {}", src.display()));
2512 }
2513 return Ok((candidate, path));
2514 }
2515 Err(e) if e.kind() == ErrorKind::AlreadyExists => continue,
2516 Err(e) => return Err(e).with_context(|| format!("create {}", path.display())),
2517 }
2518 }
2519 unreachable!("the counter never runs out")
2520}
2521
2522const TASK_LOCK_STALE: std::time::Duration = std::time::Duration::from_secs(10);
2525
2526pub(crate) struct TaskLock {
2529 path: PathBuf,
2530 token: String,
2531}
2532
2533fn owner_token() -> String {
2536 static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
2537 let n = COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2538 let mut r = crate::rng::SplitMix64::new(crate::rng::entropy() ^ n.rotate_left(32));
2539 format!("{}-{:016x}", std::process::id(), r.next_u64())
2540}
2541
2542fn break_marker(path: &Path, token: &str) -> PathBuf {
2545 let mut h: u64 = 0xcbf29ce484222325;
2546 for b in token.bytes() {
2547 h ^= u64::from(b);
2548 h = h.wrapping_mul(0x100000001b3);
2549 }
2550 let mut name = path.as_os_str().to_owned();
2551 name.push(format!(".break-{h:016x}"));
2552 PathBuf::from(name)
2553}
2554
2555fn older_than_stale(path: &Path) -> bool {
2556 std::fs::metadata(path)
2557 .and_then(|m| m.modified())
2558 .ok()
2559 .and_then(|t| t.elapsed().ok())
2560 .is_some_and(|age| age > TASK_LOCK_STALE)
2561}
2562
2563fn writer_may_be_gone(token: &str) -> bool {
2564 let Some(pid) = token
2565 .split_once('-')
2566 .and_then(|(pid, _)| pid.parse::<u32>().ok())
2567 else {
2568 return true;
2571 };
2572 if pid == std::process::id() {
2573 return false;
2574 }
2575 crate::proc::pid_status(pid) == Some(false)
2577}
2578
2579const MAX_MARKER_DEPTH: u8 = 3;
2583
2584fn take_marker(
2590 path: &Path,
2591 token: &str,
2592 depth: u8,
2593 retry: crate::lock_file::Retry,
2594) -> Option<(PathBuf, String)> {
2595 use std::io::Write;
2596 let marker = break_marker(path, token);
2597 for _ in 0..2 {
2598 match retry.create(&marker) {
2599 Ok(mut f) => {
2600 let mine = owner_token();
2601 if f.write_all(mine.as_bytes()).is_err() {
2602 drop(f);
2603 let _ = std::fs::remove_file(&marker);
2604 return None;
2605 }
2606 return Some((marker, mine));
2607 }
2608 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
2609 let judged = std::fs::read_to_string(&marker).ok();
2610 match judged.filter(|_| older_than_stale(&marker)) {
2611 Some(judged) if depth < MAX_MARKER_DEPTH => {
2612 remove_lock_if(&marker, &judged, true, depth + 1, retry)?;
2613 }
2614 _ => return None,
2615 }
2616 }
2617 Err(_) => return None,
2618 }
2619 }
2620 None
2621}
2622
2623fn remove_lock_if(
2628 path: &Path,
2629 token: &str,
2630 require_stale: bool,
2631 depth: u8,
2632 retry: crate::lock_file::Retry,
2633) -> Option<bool> {
2634 let (marker, mine) = take_marker(path, token, depth, retry)?;
2635 let still = std::fs::read_to_string(path).is_ok_and(|c| c == token)
2636 && (!require_stale || older_than_stale(path) && writer_may_be_gone(token));
2637 if still {
2638 let _ = std::fs::remove_file(path);
2639 }
2640 if depth >= MAX_MARKER_DEPTH {
2642 if std::fs::read_to_string(&marker).is_ok_and(|c| c == mine) {
2643 let _ = std::fs::remove_file(&marker);
2644 }
2645 } else {
2646 let _ = remove_lock_if(&marker, &mine, false, depth + 1, retry);
2647 }
2648 Some(still)
2649}
2650
2651#[cfg(test)]
2654fn break_stale(path: &Path, judged: &str) -> bool {
2655 break_stale_with(path, judged, crate::lock_file::Retry::new(None))
2656}
2657
2658fn break_stale_with(path: &Path, judged: &str, retry: crate::lock_file::Retry) -> bool {
2659 remove_lock_if(path, judged, true, 0, retry).unwrap_or(false)
2660}
2661
2662impl Drop for TaskLock {
2663 fn drop(&mut self) {
2664 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2);
2665 let retry = crate::lock_file::Retry::new(Some(deadline));
2666 loop {
2667 match remove_lock_if(&self.path, &self.token, false, 0, retry) {
2668 Some(_) => return,
2669 None if std::time::Instant::now() > deadline => return,
2670 None => std::thread::sleep(std::time::Duration::from_millis(5)),
2671 }
2672 }
2673 }
2674}
2675
2676#[derive(Debug, Clone)]
2678pub struct Queue {
2679 root: PathBuf,
2680 ids: IdSource,
2681}
2682
2683fn validate_attachments(sources: &[PathBuf]) -> Result<Vec<(&PathBuf, &str)>> {
2684 let mut wanted = Vec::new();
2685 for src in sources {
2686 let name = src
2687 .file_name()
2688 .and_then(|n| n.to_str())
2689 .with_context(|| format!("`{}` has no usable file name", src.display()))?;
2690 if !crate::ask::valid_asset_name(name) {
2691 bail!(
2692 "attachment name `{name}` must match ^[A-Za-z0-9][A-Za-z0-9._-]{{0,63}}$ \
2693 with no `..`; rename the file and try again"
2694 );
2695 }
2696 if !src.is_file() {
2697 bail!("attachment `{}` is not a file", src.display());
2698 }
2699 wanted.push((src, name));
2700 }
2701 Ok(wanted)
2702}
2703
2704impl Queue {
2705 pub fn open() -> Self {
2707 Self::at(crate::run::home().join("queue"))
2708 }
2709
2710 pub fn at(root: PathBuf) -> Self {
2713 Self {
2714 root,
2715 ids: IdSource::new(new_id),
2716 }
2717 }
2718
2719 #[doc(hidden)]
2722 pub fn with_id_source(mut self, f: impl Fn() -> String + Send + Sync + 'static) -> Self {
2723 self.ids = IdSource::custom(f);
2724 self
2725 }
2726
2727 fn file_with(
2738 &self,
2739 task: &mut Task,
2740 hook: impl FnMut(&mut Task) -> Result<bool>,
2741 undo: impl FnMut(&mut Task),
2742 ) -> Result<()> {
2743 self.reserve_id(task, hook, undo, true)
2744 }
2745
2746 fn reserve_id(
2754 &self,
2755 task: &mut Task,
2756 mut hook: impl FnMut(&mut Task) -> Result<bool>,
2757 mut undo: impl FnMut(&mut Task),
2758 store: bool,
2759 ) -> Result<()> {
2760 let redraw_first = self.ids.is_custom() && task.attachments.is_empty();
2761 let initial = task.id.clone();
2762 self.ids
2763 .reserve((!redraw_first).then_some(initial.as_str()), "task", |id| {
2764 task.id = id.to_owned();
2765 let _lock = self.lock_task(&task.id)?;
2766 if path_exists(&self.path_of(&task.id))? || !hook(task)? {
2767 return Ok(false);
2768 }
2769 if store {
2770 if let Err(e) = self.write_record(task) {
2771 undo(task);
2772 return Err(e);
2773 }
2774 task.unfiled = false;
2775 }
2776 Ok(true)
2777 })?;
2778 Ok(())
2779 }
2780
2781 fn id_in_use(&self, id: &str, check_attachments: bool) -> Result<bool> {
2786 if path_exists(&self.lock_path(id))? {
2787 return Ok(true);
2788 }
2789 Ok(check_attachments && path_exists(&self.attachments_dir(id))?)
2790 }
2791
2792 fn plain_filing_hook(&self, task: &Task) -> Result<bool> {
2796 Ok(!self.id_in_use(&task.id, task.attachments.is_empty())?)
2797 }
2798
2799 pub fn file_claimed(&self, task: &mut Task) -> Result<Claim> {
2802 let mut claim = None;
2803 self.file_with(
2804 task,
2805 |t| {
2806 if self.id_in_use(&t.id, true)? {
2807 return Ok(false);
2808 }
2809 claim = Some(self.claim(&t.id)?);
2810 Ok(true)
2811 },
2812 |_| {},
2813 )?;
2814 claim.context("claim missing after filing")
2815 }
2816
2817 pub fn root(&self) -> &Path {
2819 &self.root
2820 }
2821
2822 pub fn path_of(&self, id: &str) -> PathBuf {
2824 self.root.join(format!("{id}.json"))
2825 }
2826
2827 pub fn attachments_dir(&self, id: &str) -> PathBuf {
2830 self.root.join(format!("{id}.attachments"))
2831 }
2832
2833 pub fn attach(&self, task: &mut Task, sources: &[PathBuf]) -> Result<Vec<String>> {
2844 let wanted = validate_attachments(sources)?;
2845 if task.unfiled && task.attachments.is_empty() {
2846 let names = std::cell::RefCell::new(Vec::new());
2849 self.reserve_id(
2850 task,
2851 |t| {
2852 if self.id_in_use(&t.id, true)? {
2853 return Ok(false);
2854 }
2855 *names.borrow_mut() = self.copy_attachments(t, &wanted)?;
2856 Ok(true)
2857 },
2858 |_| {},
2859 false,
2860 )?;
2861 return Ok(names.into_inner());
2862 }
2863 self.copy_attachments(task, &wanted)
2864 }
2865
2866 fn copy_attachments(
2868 &self,
2869 task: &mut Task,
2870 wanted: &[(&PathBuf, &str)],
2871 ) -> Result<Vec<String>> {
2872 let dir = self.attachments_dir(&task.id);
2873 let existed = dir.is_dir();
2874 std::fs::create_dir_all(&dir).with_context(|| format!("create {}", dir.display()))?;
2875 let mut created: Vec<PathBuf> = Vec::new();
2876 let mut names = Vec::new();
2877 let mut copy_all = || -> Result<()> {
2878 for (src, name) in wanted {
2879 let (stored, path) = copy_new(&dir, src, name)?;
2880 created.push(path);
2881 names.push(stored);
2882 }
2883 Ok(())
2884 };
2885 if let Err(e) = copy_all() {
2886 for path in &created {
2887 let _ = std::fs::remove_file(path);
2888 }
2889 if !existed {
2890 let _ = std::fs::remove_dir(&dir);
2891 }
2892 return Err(e);
2893 }
2894 task.attachments.extend(names.iter().cloned());
2895 Ok(names)
2896 }
2897
2898 pub fn attach_and_put(&self, task: &mut Task, sources: &[PathBuf]) -> Result<Vec<String>> {
2909 if task.unfiled && task.attachments.is_empty() {
2910 return self.attach_and_file(task, sources);
2911 }
2912 let dir = self.attachments_dir(&task.id);
2913 let existed = dir.is_dir();
2914 let before = task.attachments.len();
2915 let names = self.attach(task, sources)?;
2916 if let Err(e) = self.put(task) {
2917 for name in &names {
2918 let _ = std::fs::remove_file(dir.join(name));
2919 }
2920 if !existed {
2921 let _ = std::fs::remove_dir(&dir);
2922 }
2923 task.attachments.truncate(before);
2924 return Err(e);
2925 }
2926 Ok(names)
2927 }
2928
2929 fn attach_and_file(&self, task: &mut Task, sources: &[PathBuf]) -> Result<Vec<String>> {
2933 let wanted = validate_attachments(sources)?;
2934 let before = task.attachments.len();
2935 let names = std::cell::RefCell::new(Vec::new());
2936 let result = self.file_with(
2937 task,
2938 |t| {
2939 if self.id_in_use(&t.id, true)? {
2940 return Ok(false);
2941 }
2942 *names.borrow_mut() = self.copy_attachments(t, &wanted)?;
2943 Ok(true)
2944 },
2945 |t| {
2946 let dir = self.attachments_dir(&t.id);
2947 for name in names.borrow().iter() {
2948 let _ = std::fs::remove_file(dir.join(name));
2949 }
2950 let _ = std::fs::remove_dir(&dir);
2952 t.attachments.truncate(before);
2953 },
2954 );
2955 result.map(|()| names.into_inner())
2956 }
2957
2958 pub fn attachment_paths(&self, task: &Task) -> Vec<PathBuf> {
2962 let dir = self.attachments_dir(&task.id);
2963 task.attachments
2964 .iter()
2965 .map(|n| {
2966 let p = dir.join(n);
2967 std::path::absolute(&p).unwrap_or(p)
2968 })
2969 .collect()
2970 }
2971
2972 pub fn put(&self, task: &mut Task) -> Result<()> {
2981 if task.unfiled {
2982 return self.file_with(task, |t| self.plain_filing_hook(t), |_| {});
2984 }
2985 let _lock = self.lock_task(&task.id)?;
2986 self.put_unlocked(task)
2987 }
2988
2989 pub fn create_new(&self, task: &mut Task) -> Result<bool> {
2994 let _lock = self.lock_task(&task.id)?;
2995 if path_exists(&self.path_of(&task.id))? {
2996 return Ok(false);
2997 }
2998 self.write_record(task)?;
2999 task.unfiled = false;
3000 Ok(true)
3001 }
3002
3003 fn put_unlocked(&self, task: &mut Task) -> Result<()> {
3005 self.merge_stored(task);
3006 if let Some(boundary) = task.reassignments.last() {
3007 let stored = self.get(&task.id)?;
3008 anyhow::ensure!(
3009 task.reassignments == stored.reassignments
3010 && task.repo == stored.repo
3011 && task.runs.get(..boundary.run_boundary)
3012 == stored.runs.get(..boundary.run_boundary),
3013 "historical repository execution cannot be restarted; reload the task"
3014 );
3015 }
3016 self.write_record(task)
3017 }
3018
3019 pub(crate) fn commit_base_recovery(
3021 &self,
3022 task: &mut Task,
3023 expected: &serde_json::Value,
3024 ) -> Result<()> {
3025 let _lock = self.lock_task(&task.id)?;
3026 anyhow::ensure!(
3027 serde_json::to_value(self.get(&task.id)?)? == *expected,
3028 "task changed during base recovery; inspect the pending authorization"
3029 );
3030 self.put_unlocked(task)
3032 }
3033
3034 pub(crate) fn commit_repair_grant(
3035 &self,
3036 task: &mut Task,
3037 expected: &serde_json::Value,
3038 ) -> Result<()> {
3039 let _lock = self.lock_task(&task.id)?;
3040 anyhow::ensure!(
3041 serde_json::to_value(self.get(&task.id)?)? == *expected,
3042 "repair grant refused: task changed during admission"
3043 );
3044 self.write_record(task)
3045 .context(crate::repair_budget::PublicationUnknown)
3046 }
3047
3048 pub(crate) fn commit_disk_wait(&self, task: &mut Task, expected: &Task) -> Result<()> {
3050 let _lock = self.lock_task(&task.id)?;
3051 anyhow::ensure!(
3052 serde_json::to_value(self.get(&task.id)?)? == serde_json::to_value(expected)?,
3053 "task changed during disk monitoring"
3054 );
3055 task.stamp_schema();
3056 self.write_record_inner(task, false)
3057 }
3058
3059 pub(crate) fn commit_reassignment(&self, task: &mut Task, expected: &Task) -> Result<()> {
3061 let _lock = self.lock_task(&task.id)?;
3062 let stored = self.get(&task.id)?;
3063 anyhow::ensure!(
3064 serde_json::to_value(&stored)? == serde_json::to_value(expected)?
3065 && stored.reassignments.len() + 1 == task.reassignments.len()
3066 && stored.repo == task.reassignments.last().expect("new boundary").from
3067 && stored.runs == task.runs,
3068 "task changed during reassignment; retry after inspecting it"
3069 );
3070 self.write_record(task)
3071 }
3072
3073 fn merge_stored(&self, task: &mut Task) {
3075 if let Ok(mut stored) = read_path(&self.path_of(&task.id)) {
3076 stored.import_chat_notice();
3077 if stored.reassignments.len() > task.reassignments.len() {
3078 let stale = std::mem::replace(task, stored.clone());
3081 for answer in stale.answers {
3082 if !task.answers.contains(&answer) {
3083 task.answers.push(answer);
3084 }
3085 }
3086 }
3087 if task.updated_at < stored.updated_at
3090 && (stored
3091 .recovery_budget_hold
3092 .as_ref()
3093 .is_some_and(|hold| hold.held_at > task.updated_at)
3094 || stored.repair_grants.last().is_some_and(|grant| {
3095 task.repair_grants.last() != Some(grant)
3096 || stored.operator_decided_at > task.operator_decided_at
3097 || stored
3098 .resume_override
3099 .as_ref()
3100 .is_some_and(|pin| pin.at > task.updated_at)
3101 || (task.resume_override != stored.resume_override
3102 && task
3103 .resume_override
3104 .as_ref()
3105 .is_some_and(|pin| pin.at == grant.at))
3106 }))
3107 && task
3108 .operator_decided_at
3109 .is_none_or(|at| at <= stored.updated_at)
3110 && task
3111 .resume_override
3112 .as_ref()
3113 .is_none_or(|pin| pin.at <= stored.updated_at)
3114 {
3115 *task = stored.clone();
3116 }
3117 for key in &stored.base_recovery_requests {
3118 if !task.base_recovery_requests.contains(key) {
3119 task.base_recovery_requests.push(key.clone());
3120 }
3121 }
3122 for receipt in &stored.repair_grants {
3123 if !task
3124 .repair_grants
3125 .iter()
3126 .any(|r| r.request.request == receipt.request.request)
3127 {
3128 task.repair_grants.push(receipt.clone());
3130 }
3131 }
3132 for receipt in &stored.repair_reconciliations {
3133 if !task.repair_reconciliations.contains(receipt) {
3134 task.repair_reconciliations.push(receipt.clone());
3137 task.resume_override = stored.resume_override.clone();
3138 task.status = stored.status;
3139 task.hold_source = stored.hold_source;
3140 task.machine_hold_cause = stored.machine_hold_cause.clone();
3141 task.disk_resume_run = stored.disk_resume_run.clone();
3142 task.disk_checked_at = stored.disk_checked_at;
3143 task.hold_reason = stored.hold_reason.clone();
3144 task.held_at = stored.held_at;
3145 }
3146 }
3147 task.superseded_resumes.extend(stored.superseded_resumes);
3148 task.dispatched_resumes.extend(stored.dispatched_resumes);
3149 if task.status != TaskStatus::Running
3150 && let Some(pin) = &stored.resume_override
3151 && !pin.question_id.is_empty()
3152 && let Some(run) = &pin.pinned_run
3153 && task.resume_override.as_ref().is_none_or(|next| {
3154 next.question_id != pin.question_id || next.pinned_run != pin.pinned_run
3155 })
3156 {
3157 task.superseded_resumes
3158 .insert(pin.question_id.clone(), run.clone());
3159 }
3160 for (id, receipt) in stored.decision_effects {
3163 task.decision_effects.insert(id, receipt);
3164 }
3165 if !task.decision_effects.is_empty() {
3166 task.stamp_schema();
3167 }
3168 if task.chat.is_none() {
3171 task.chat = stored.chat.clone();
3172 }
3173 for key in stored.chat_notices {
3174 if !task.chat_notices.contains(&key) {
3175 task.chat_notices.push(key);
3176 }
3177 }
3178 for failure in stored.startup_failures {
3179 task.record_startup_failure(failure);
3180 }
3181 for run in stored.runs {
3182 if !task.runs.contains(&run) {
3183 task.runs.push(run);
3184 }
3185 }
3186 for p in stored.passes {
3187 if !task
3188 .passes
3189 .iter()
3190 .any(|q| q.run == p.run && q.pass_index == p.pass_index)
3191 {
3192 task.passes.push(p);
3193 }
3194 }
3195 if let Some(n) = stored.chat_notice
3198 && task.chat_notice.as_ref().is_none_or(|mine| mine.at < n.at)
3199 {
3200 task.chat_notice = Some(n);
3201 }
3202 }
3203 }
3204
3205 pub(crate) fn write_startup_history(&self, task: &Task) -> Result<()> {
3208 let path = self.path_of(&task.id);
3209 let tmp = path.with_extension("json.tmp");
3210 std::fs::write(&tmp, serde_json::to_vec_pretty(task)?)?;
3211 std::fs::rename(tmp, path)?;
3212 Ok(())
3213 }
3214
3215 fn write_record(&self, task: &mut Task) -> Result<()> {
3217 self.write_record_inner(task, true)
3218 }
3219
3220 fn write_record_inner(&self, task: &mut Task, notify: bool) -> Result<()> {
3221 task.import_chat_notice();
3222 if task.status != TaskStatus::Held {
3223 task.recovery_budget_hold = None;
3224 }
3225 task.updated_at = Timestamp::now();
3226 std::fs::create_dir_all(&self.root)
3227 .with_context(|| format!("create {}", self.root.display()))?;
3228 let body = serde_json::to_string_pretty(task).context("serialize task")?;
3229 let path = self.path_of(&task.id);
3230 let tmp = path.with_extension("json.tmp");
3231 std::fs::write(&tmp, &body).with_context(|| format!("write {}", tmp.display()))?;
3232 std::fs::rename(&tmp, &path).with_context(|| format!("replace {}", path.display()))?;
3233 if let (Some(notice), Some(home)) = (
3238 notify.then(|| crate::notices::task_held(task)).flatten(),
3239 self.root.parent().filter(|p| !p.as_os_str().is_empty()),
3240 ) {
3241 crate::notices::raise_in(home, notice);
3242 }
3243 Ok(())
3244 }
3245
3246 pub fn modify(&self, id: &str, f: impl FnOnce(&mut Task) -> bool) -> Result<bool> {
3251 let id = self.resolve_id(id)?;
3252 let _lock = self.lock_task(&id)?;
3253 let mut task = self.get(&id)?;
3254 if !f(&mut task) {
3255 return Ok(false);
3256 }
3257 self.put_unlocked(&mut task)?;
3258 Ok(true)
3259 }
3260
3261 pub fn link_run(&self, id: &str, run: &str) -> Result<Task> {
3266 let id = self.resolve_id(id)?;
3267 let _lock = self.lock_task(&id)?;
3270 let mut task = self.get(&id)?;
3271 if task.link_run(run) {
3272 self.put_unlocked(&mut task)?;
3273 }
3274 Ok(task)
3275 }
3276
3277 pub(crate) fn lock_task(&self, id: &str) -> Result<TaskLock> {
3285 std::fs::create_dir_all(&self.root)
3286 .with_context(|| format!("create {}", self.root.display()))?;
3287 let path = self.root.join(format!("{id}.write-lock"));
3288 let started = std::time::Instant::now();
3289 let retry = crate::lock_file::Retry::task_write(started + TASK_LOCK_STALE);
3290 let marker_retry = crate::lock_file::Retry::new(Some(started + TASK_LOCK_STALE));
3291 loop {
3292 match retry.create(&path) {
3293 Ok(mut file) => {
3294 use std::io::Write;
3295 let token = owner_token();
3296 if let Err(e) = file.write_all(token.as_bytes()) {
3297 drop(file);
3298 let _ = std::fs::remove_file(&path);
3299 return Err(e).with_context(|| format!("lock {}", path.display()));
3300 }
3301 return Ok(TaskLock { path, token });
3302 }
3303 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
3304 let judged = std::fs::read_to_string(&path).ok();
3307 let broken = judged
3308 .filter(|_| older_than_stale(&path))
3309 .is_some_and(|judged| break_stale_with(&path, &judged, marker_retry));
3310 if !broken {
3314 if started.elapsed() > TASK_LOCK_STALE {
3315 bail!("could not lock task {id}");
3316 }
3317 std::thread::sleep(std::time::Duration::from_millis(15));
3318 }
3319 }
3320 Err(e) => return Err(e).with_context(|| format!("lock {}", path.display())),
3321 }
3322 }
3323 }
3324
3325 pub fn get(&self, id: &str) -> Result<Task> {
3327 let resolved = self.resolve_id(id)?;
3328 read_path(&self.path_of(&resolved))
3329 }
3330
3331 pub fn remove(&self, id: &str, in_flight: bool, questions: &Questions) -> Result<Removal> {
3363 self.remove_with_receipt(id, in_flight, questions, None)
3364 }
3365
3366 pub(crate) fn discard_triage(
3368 &self,
3369 id: &str,
3370 questions: &Questions,
3371 inquiry: &str,
3372 ) -> Result<Removal> {
3373 self.remove_with_receipt(id, false, questions, Some(inquiry))
3374 }
3375
3376 pub(crate) fn triage_discard_applied(&self, id: &str, inquiry: &str) -> Result<bool> {
3377 let path = self
3378 .root
3379 .join("triage-discard")
3380 .join(format!("{inquiry}.json"));
3381 let bytes = match std::fs::read(path) {
3382 Ok(bytes) => bytes,
3383 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(false),
3384 Err(e) => return Err(e.into()),
3385 };
3386 let receipt: Task = serde_json::from_slice(&bytes)?;
3387 Ok(receipt.id == id && !self.path_of(id).exists())
3388 }
3389
3390 fn remove_with_receipt(
3391 &self,
3392 id: &str,
3393 in_flight: bool,
3394 questions: &Questions,
3395 inquiry: Option<&str>,
3396 ) -> Result<Removal> {
3397 let resolved = self.resolve_id(id)?;
3398 if in_flight {
3399 bail!("task {resolved} is being run by a live daemon right now");
3400 }
3401 let receipt = inquiry.map(|q| self.root.join("triage-discard").join(format!("{q}.json")));
3402 if let Some(path) = &receipt {
3403 std::fs::create_dir_all(path.parent().expect("receipt directory"))?;
3404 }
3405 self.write_tombstone(&resolved)?;
3406 if let Err(e) = self.remove_record_with_attachments(&resolved, |p| match &receipt {
3407 Some(path) => std::fs::rename(p, path),
3408 None => std::fs::remove_file(p),
3409 }) {
3410 if self.path_of(&resolved).exists() {
3414 let _ = std::fs::remove_file(self.tombstone_path(&resolved));
3415 }
3416 return Err(e);
3417 }
3418 let (released, still_blocked) = self.release_dependents_of(&resolved, questions);
3419 Ok(Removal {
3420 id: resolved,
3421 released,
3422 still_blocked,
3423 })
3424 }
3425
3426 fn tombstone_path(&self, id: &str) -> PathBuf {
3429 self.root.join(format!("{id}.removed"))
3430 }
3431
3432 fn write_tombstone(&self, id: &str) -> Result<()> {
3433 let path = self.tombstone_path(id);
3434 let tmp = self.root.join(format!("{id}.removed.tmp"));
3435 std::fs::write(&tmp, b"")
3436 .and_then(|()| std::fs::rename(&tmp, &path))
3437 .with_context(|| format!("write {}", path.display()))
3438 }
3439
3440 fn was_deleted(&self, id: &str) -> bool {
3444 self.tombstone_path(id).is_file() && !self.path_of(id).exists()
3445 }
3446
3447 pub fn apply_deleted_blockers(&self, task: &mut Task, questions: &Questions) -> Vec<String> {
3451 let deleted = deleted_blockers(self, questions, &task.blocked_by);
3452 deleted
3453 .into_iter()
3454 .filter(|id| task.dependency_deleted(id))
3455 .collect()
3456 }
3457
3458 pub fn note_dependency_deleted(&self, dependent: &Task, deleted: &str) {
3462 let Some(home) = self.root.parent().filter(|p| !p.as_os_str().is_empty()) else {
3463 return;
3464 };
3465 let ja = crate::lang::is_japanese(&crate::lang::of_repo(&dependent.repo));
3466 let waiting = dependent.status == TaskStatus::Blocked;
3467 let message = match (ja, waiting) {
3468 (true, false) => format!(
3469 "タスク {} は、待っていた {} が削除されたため待機を解除し、元の状態に戻しました",
3470 dependent.short(),
3471 short(deleted)
3472 ),
3473 (true, true) => format!(
3474 "タスク {} は、待っていた {} が削除されたため、残りの依存を待っています",
3475 dependent.short(),
3476 short(deleted)
3477 ),
3478 (false, false) => format!(
3479 "Task {} stopped waiting on {} because it was deleted, and returned to its previous state",
3480 dependent.short(),
3481 short(deleted)
3482 ),
3483 (false, true) => format!(
3484 "Task {} stopped waiting on {} because it was deleted, and is still waiting on its other dependencies",
3485 dependent.short(),
3486 short(deleted)
3487 ),
3488 };
3489 crate::notices::raise_in(
3490 home,
3491 crate::notices::Notice::info(
3492 &format!("unblocked:{}:{}", dependent.id, deleted),
3493 message,
3494 )
3495 .link(crate::notices::Link::Task {
3496 id: dependent.id.clone(),
3497 }),
3498 );
3499 }
3500
3501 fn release_dependents_of(
3506 &self,
3507 dependency: &str,
3508 questions: &Questions,
3509 ) -> (Vec<String>, Vec<String>) {
3510 let (mut released, mut still_blocked) = (Vec::new(), Vec::new());
3511 for listed in self.list() {
3512 if listed.status != TaskStatus::Blocked || !listed.blocked_by.iter().any(|b| {
3513 matches!(crate::queue::dependency(self, questions, b), Dependency::Deleted(id) if id == dependency)
3514 }) {
3515 continue;
3516 }
3517 let Ok(_claim) = self.claim(&listed.id) else {
3518 continue;
3519 };
3520 let Ok(mut task) = self.get(&listed.id) else {
3521 continue;
3522 };
3523 let references: Vec<String> = task.blocked_by.iter().filter(|id| {
3524 matches!(crate::queue::dependency(self, questions, id), Dependency::Deleted(full) if full == dependency)
3525 }).cloned().collect();
3526 if references.is_empty() {
3527 continue;
3528 }
3529 for reference in references {
3530 task.dependency_deleted(&reference);
3531 }
3532 if self.put(&mut task).is_err() {
3533 continue;
3534 }
3535 self.note_dependency_deleted(&task, dependency);
3536 if task.status == TaskStatus::Blocked {
3537 still_blocked.push(task.id.clone());
3538 } else {
3539 released.push(task.id.clone());
3540 }
3541 }
3542 (released, still_blocked)
3543 }
3544
3545 fn remove_record_with_attachments(
3549 &self,
3550 resolved: &str,
3551 remove_record: impl FnOnce(&Path) -> std::io::Result<()>,
3552 ) -> Result<()> {
3553 self.sweep_removed_attachments();
3560 let attachments = self.attachments_dir(resolved);
3561 let aside = self.root.join(format!("{resolved}.attachments.removing"));
3562 let moved = match std::fs::rename(&attachments, &aside) {
3563 Ok(()) => true,
3564 Err(e) if e.kind() == std::io::ErrorKind::NotFound => false,
3565 Err(e) => {
3566 return Err(e).with_context(|| format!("remove {}", attachments.display()));
3567 }
3568 };
3569 let path = self.path_of(resolved);
3570 if let Err(e) = remove_record(&path) {
3571 if moved {
3572 let _ = std::fs::rename(&aside, &attachments);
3573 }
3574 return Err(e).with_context(|| format!("remove {}", path.display()));
3575 }
3576 if moved {
3577 if let Err(e) = std::fs::remove_dir_all(&aside) {
3578 tracing::warn!("leftover attachments {}: {e}", aside.display());
3579 }
3580 }
3581 let lock = self.lock_path(resolved);
3582 if let Err(e) = std::fs::remove_file(&lock) {
3583 if e.kind() != std::io::ErrorKind::NotFound {
3584 return Err(e).with_context(|| format!("remove {}", lock.display()));
3585 }
3586 }
3587 Ok(())
3588 }
3589
3590 fn sweep_removed_attachments(&self) {
3596 let Ok(entries) = std::fs::read_dir(&self.root) else {
3597 return;
3598 };
3599 for entry in entries.flatten() {
3600 let name = entry.file_name();
3601 let name = name.to_string_lossy();
3602 let Some(id) = name.strip_suffix(".attachments.removing") else {
3603 continue;
3604 };
3605 if !self.path_of(id).exists() {
3608 if let Err(e) = std::fs::remove_dir_all(entry.path()) {
3609 tracing::warn!("leftover attachments {}: {e}", entry.path().display());
3610 }
3611 }
3612 }
3613 self.sweep_tombstones();
3614 }
3615
3616 fn sweep_tombstones(&self) {
3625 let Ok(entries) = std::fs::read_dir(&self.root) else {
3626 return;
3627 };
3628 let tasks = self.list();
3629 for entry in entries.flatten() {
3630 let name = entry.file_name();
3631 let name = name.to_string_lossy();
3632 let Some(id) = name.strip_suffix(".removed") else {
3633 continue;
3634 };
3635 if self.path_of(id).exists()
3636 || tasks.iter().any(|t| {
3637 t.blocked_by
3638 .iter()
3639 .any(|b| id.starts_with(b) || id.ends_with(b))
3640 })
3641 {
3642 continue;
3643 }
3644 let old = entry
3645 .metadata()
3646 .and_then(|m| m.modified())
3647 .ok()
3648 .and_then(|m| m.elapsed().ok())
3649 .is_some_and(|age| age >= TOMBSTONE_GRACE);
3650 if old {
3651 let _ = std::fs::remove_file(entry.path());
3652 }
3653 }
3654 }
3655
3656 fn lock_path(&self, id: &str) -> PathBuf {
3659 self.root.join(format!("{id}.lock"))
3660 }
3661
3662 pub fn list(&self) -> Vec<Task> {
3675 #[cfg(test)]
3676 LIST_READS.with(|count| count.set(count.get() + 1));
3677 let mut tasks: Vec<Task> = std::fs::read_dir(&self.root)
3678 .into_iter()
3679 .flatten()
3680 .flatten()
3681 .map(|e| e.path())
3682 .filter(|p| p.extension().is_some_and(|x| x == "json"))
3683 .filter_map(|p| read_path(&p).ok())
3684 .collect();
3685 tasks.sort_unstable_by(|a, b| b.priority.cmp(&a.priority).then_with(|| b.id.cmp(&a.id)));
3686 tasks
3687 }
3688
3689 pub fn unreadable(&self) -> Vec<PathBuf> {
3693 std::fs::read_dir(&self.root)
3694 .into_iter()
3695 .flatten()
3696 .flatten()
3697 .map(|e| e.path())
3698 .filter(|p| p.extension().is_some_and(|x| x == "json"))
3699 .filter(|p| read_path(p).is_err())
3700 .collect()
3701 }
3702
3703 pub fn superseded(&self) -> HashMap<String, String> {
3716 let mut by = HashMap::new();
3717 for task in self.list() {
3718 for earlier in &task.runs {
3719 if let Some(later) = task.successor_of(earlier) {
3720 by.insert(earlier.clone(), later.clone());
3721 }
3722 }
3723 }
3724 by
3725 }
3726
3727 pub fn superseded_by(&self, run: &str) -> Option<String> {
3735 for task in self.list() {
3736 if task.runs.iter().any(|r| r == run) {
3737 return task.successor_of(run).cloned();
3738 }
3739 }
3740 None
3741 }
3742
3743 pub fn latest_attempt(&self, run: &str) -> Option<String> {
3754 for task in self.list() {
3755 if task.runs.iter().any(|r| r == run) {
3756 return task.runs.last().filter(|last| **last != run).cloned();
3757 }
3758 }
3759 None
3760 }
3761
3762 pub fn next_runnable(&self) -> Option<Task> {
3767 let mut runnable: Vec<Task> = self
3768 .list()
3769 .into_iter()
3770 .filter(|t| t.status.runnable())
3771 .collect();
3772 runnable.sort_unstable_by(dispatch_order);
3773 runnable.into_iter().next()
3774 }
3775
3776 pub fn claim(&self, id: &str) -> Result<Claim> {
3783 std::fs::create_dir_all(&self.root)
3784 .with_context(|| format!("create {}", self.root.display()))?;
3785 let path = self.lock_path(id);
3786 let retry = crate::lock_file::Retry::new(None);
3787 match retry.create(&path) {
3788 Ok(mut f) => {
3789 use std::io::Write as _;
3790 let _ = writeln!(f, "{}", std::process::id());
3792 Ok(Claim { path })
3793 }
3794 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
3795 bail!("task {id} is already claimed ({} exists)", path.display())
3796 }
3797 Err(e) => Err(e).with_context(|| format!("lock {}", path.display())),
3798 }
3799 }
3800
3801 pub fn resolve_id(&self, prefix: &str) -> Result<String> {
3803 if !prefix.is_empty()
3804 && prefix != "."
3805 && prefix != ".."
3806 && !prefix.contains(['/', '\\'])
3807 && self.path_of(prefix).is_file()
3808 {
3809 return Ok(prefix.to_owned());
3810 }
3811 let ids = record_ids(&self.root, "json")?;
3812 match resolve_reference(prefix, ids.iter().map(String::as_str)) {
3813 Reference::Found(id) => Ok(id),
3814 Reference::Missing => bail!("no task matches `{prefix}`"),
3815 Reference::Ambiguous => bail!("`{prefix}` matches multiple tasks"),
3816 }
3817 }
3818
3819 pub fn revision(&self) -> u64 {
3826 self.revision_excluding(&std::collections::BTreeSet::new())
3827 }
3828
3829 pub fn revision_excluding(&self, skip: &std::collections::BTreeSet<String>) -> u64 {
3832 use std::hash::{Hash as _, Hasher as _};
3833
3834 let mut entries: Vec<(String, u64)> = std::fs::read_dir(&self.root)
3835 .into_iter()
3836 .flatten()
3837 .flatten()
3838 .filter(|e| e.path().extension().is_some_and(|ext| ext == "json"))
3839 .filter(|e| {
3840 let path = e.path();
3841 !path
3842 .file_stem()
3843 .is_some_and(|stem| skip.contains(stem.to_string_lossy().as_ref()))
3844 })
3845 .filter_map(|e| {
3846 let name = e.file_name().to_string_lossy().into_owned();
3847 let mtime = e
3848 .metadata()
3849 .ok()?
3850 .modified()
3851 .ok()?
3852 .duration_since(std::time::UNIX_EPOCH)
3853 .ok()?
3854 .as_millis() as u64;
3855 Some((name, mtime))
3856 })
3857 .collect();
3858
3859 if entries.is_empty() {
3860 return 0;
3861 }
3862
3863 entries.sort_unstable();
3864 let mut hasher = std::hash::DefaultHasher::new();
3865 for (name, mtime) in &entries {
3866 name.hash(&mut hasher);
3867 mtime.hash(&mut hasher);
3868 }
3869 let h = hasher.finish();
3870 if h == 0 { 1 } else { h }
3871 }
3872}
3873
3874const TOMBSTONE_GRACE: std::time::Duration = std::time::Duration::from_secs(3600);
3877
3878#[derive(Debug, Clone)]
3880pub struct Removal {
3881 pub id: String,
3883 pub released: Vec<String>,
3887 pub still_blocked: Vec<String>,
3890}
3891
3892#[derive(Debug)]
3894pub struct Claim {
3895 path: PathBuf,
3896}
3897
3898impl Drop for Claim {
3899 fn drop(&mut self) {
3900 let _ = std::fs::remove_file(&self.path);
3901 }
3902}
3903
3904pub fn title_from(instruction: &str, max: usize) -> String {
3907 let Some(line) = first_line(instruction) else {
3908 return "(empty task)".to_owned();
3909 };
3910 if line.chars().count() <= max {
3911 return line.to_owned();
3912 }
3913 let head: String = line.chars().take(max.saturating_sub(1)).collect();
3914 format!("{head}…")
3915}
3916
3917pub(crate) fn first_line(instruction: &str) -> Option<&str> {
3923 let line = instruction
3924 .lines()
3925 .map(str::trim)
3926 .find(|l| !l.is_empty())?
3927 .trim_start_matches(['#', '-', '*', '>', ' '])
3928 .trim();
3929 (!line.is_empty()).then_some(line)
3930}
3931
3932#[cfg(test)]
3933thread_local! {
3934 pub(crate) static TASK_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3935}
3936
3937fn read_path(path: &Path) -> Result<Task> {
3938 #[cfg(test)]
3939 TASK_READS.with(|count| count.set(count.get() + 1));
3940 let body = std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;
3941 let mut task: Task =
3942 serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))?;
3943 if task.schema > SCHEMA {
3949 bail!(
3950 "task {} was written by a different magi (schema {}, this build \
3951 speaks {SCHEMA})",
3952 task.id,
3953 task.schema
3954 );
3955 }
3956 task.preserve_legacy_build_cache();
3957 if task.schema < 22
3958 && task.status == TaskStatus::Held
3959 && task.hold_source == Some(HoldSource::Machine)
3960 && task.resume_override.is_none()
3961 && task
3962 .hold_reason
3963 .as_deref()
3964 .is_some_and(crate::disk::is_gate_reason)
3965 {
3966 task.mark_disk_capacity();
3967 }
3968 Ok(task)
3969}
3970
3971#[derive(Debug, PartialEq, Eq)]
3974pub(crate) enum Reference {
3975 Found(String),
3976 Missing,
3977 Ambiguous,
3978}
3979
3980pub(crate) fn resolve_reference<'a>(id: &str, ids: impl Iterator<Item = &'a str>) -> Reference {
3981 let mut hits = Vec::new();
3982 for candidate in ids {
3983 if candidate == id {
3984 return Reference::Found(candidate.to_owned());
3985 }
3986 if candidate.starts_with(id) || candidate.ends_with(id) {
3987 hits.push(candidate);
3988 }
3989 }
3990 match hits.as_slice() {
3991 [] => Reference::Missing,
3992 [one] => Reference::Found((*one).to_owned()),
3993 _ => Reference::Ambiguous,
3994 }
3995}
3996
3997pub(crate) fn record_ids(root: &Path, extension: &str) -> Result<Vec<String>> {
4000 let entries = match std::fs::read_dir(root) {
4001 Ok(entries) => entries,
4002 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
4003 Err(e) => return Err(e.into()),
4004 };
4005 let mut ids = Vec::new();
4006 for entry in entries {
4007 let path = entry?.path();
4008 if path.extension().is_some_and(|e| e == extension)
4009 && let Some(id) = path.file_stem().and_then(|s| s.to_str())
4010 {
4011 ids.push(id.to_owned());
4012 }
4013 }
4014 Ok(ids)
4015}
4016
4017#[derive(Debug, PartialEq, Eq)]
4020pub enum Dependency {
4021 Task(String),
4023 Question(String),
4025 Deleted(String),
4027 Missing,
4029 Ambiguous,
4031 Unknown,
4033}
4034
4035pub fn dependency(queue: &Queue, questions: &Questions, id: &str) -> Dependency {
4037 let (Ok(tasks), Ok(qs), Ok(removed)) = (
4038 record_ids(queue.root(), "json"),
4039 record_ids(questions.root(), "json"),
4040 record_ids(queue.root(), "removed"),
4041 ) else {
4042 return Dependency::Unknown;
4043 };
4044 let mut ids = tasks
4047 .iter()
4048 .chain(qs.iter())
4049 .chain(removed.iter())
4050 .cloned()
4051 .collect::<Vec<_>>();
4052 ids.sort();
4053 ids.dedup();
4054 match resolve_reference(id, ids.iter().map(String::as_str)) {
4055 Reference::Found(id) if tasks.contains(&id) => Dependency::Task(id),
4056 Reference::Found(id) if qs.contains(&id) => Dependency::Question(id),
4057 Reference::Found(id) if queue.was_deleted(&id) => Dependency::Deleted(id),
4058 Reference::Found(_) => Dependency::Unknown,
4059 Reference::Missing => Dependency::Missing,
4060 Reference::Ambiguous => Dependency::Ambiguous,
4061 }
4062}
4063
4064pub fn normalize_blockers(queue: &Queue, questions: &Questions, ids: &mut [String]) {
4066 for id in ids {
4067 if let Dependency::Task(full) | Dependency::Question(full) | Dependency::Deleted(full) =
4068 dependency(queue, questions, id)
4069 {
4070 *id = full;
4071 }
4072 }
4073}
4074
4075pub fn dependency_facts(queue: &Queue, questions: &Questions) -> String {
4078 let inventory = crate::blockers::Inventory::load(queue, questions);
4079 let mut text = String::from(
4080 "Current authoritative queue (historical missing-task claims may be stale; unreadable or ambiguous references must keep waiting):\n",
4081 );
4082 match record_ids(queue.root(), "json") {
4083 Ok(ids) => {
4084 for id in ids {
4085 match queue.get(&id) {
4086 Ok(task) => text.push_str(&format!(
4087 "{}: {}; blocked_by={:?}; chain={:?}\n",
4088 task.id,
4089 task.status.as_str(),
4090 task.blocked_by,
4091 inventory.waits_on(&task)
4092 )),
4093 Err(_) => text.push_str(&format!("{id}: exists, state unreadable\n")),
4094 }
4095 }
4096 }
4097 Err(_) => text.push_str("Queue inventory unreadable: existence is unknown.\n"),
4098 }
4099 text
4100}
4101
4102pub fn missing_blockers(
4104 queue: &Queue,
4105 questions: &Questions,
4106 blocked_by: &[String],
4107) -> Vec<String> {
4108 blocked_by
4109 .iter()
4110 .filter(|id| dependency(queue, questions, id) == Dependency::Missing)
4111 .cloned()
4112 .collect()
4113}
4114
4115pub fn deleted_blockers(
4118 queue: &Queue,
4119 questions: &Questions,
4120 blocked_by: &[String],
4121) -> Vec<String> {
4122 blocked_by
4123 .iter()
4124 .filter(|id| matches!(dependency(queue, questions, id), Dependency::Deleted(_)))
4125 .cloned()
4126 .collect()
4127}
4128
4129pub fn missing_blocker_hold_reason(blocked_by: &[String], missing: &[String]) -> String {
4141 missing_blocker_hold_reason_in(blocked_by, missing, "en")
4142}
4143
4144pub fn missing_blocker_hold_reason_in(
4146 blocked_by: &[String],
4147 missing: &[String],
4148 language: &str,
4149) -> String {
4150 if crate::lang::is_japanese(language) {
4151 format!(
4152 "{} を待っていましたが、{} はディスク上に存在しません - `magi task triage` を参照",
4153 blocked_by.join(", "),
4154 missing.join(", "),
4155 )
4156 } else {
4157 format!(
4158 "blocked on {} but {} no longer exist(s) on disk - see `magi task triage`",
4159 blocked_by.join(", "),
4160 missing.join(", "),
4161 )
4162 }
4163}
4164
4165pub fn short(id: &str) -> &str {
4167 id.split('-').next_back().unwrap_or(id)
4168}
4169
4170fn new_id() -> String {
4171 let stamp = jiff::Zoned::now().strftime("%Y%m%d-%H%M%S");
4172 let seed = crate::rng::entropy();
4173 format!("{stamp}-{:04x}", (seed ^ (seed >> 32)) & 0xffff)
4174}
4175
4176#[cfg(test)]
4177mod tests {
4178 #[test]
4179 fn reassignment_clears_repository_bound_execution_selections() {
4180 let mut task = Task::new(
4181 "move".into(),
4182 "evidence".into(),
4183 "old".into(),
4184 Source::Human,
4185 );
4186 task.review_branch = Some("old-review".into());
4187 task.review_instruction = Some("old criteria".into());
4188 task.pr_recovery = Some(crate::pr_recovery::Selection {
4189 url: "https://example.invalid/pull/1".into(),
4190 branch: "old-pr".into(),
4191 head: "head".into(),
4192 source_head: None,
4193 source_run: None,
4194 source_proof: None,
4195 disposition: None,
4196 instruction: "old criteria".into(),
4197 approved_at: Timestamp::now(),
4198 });
4199 task.replacement = Some(crate::merge_decision::Replacement {
4200 question: "owner".into(),
4201 run: "old-run".into(),
4202 pr: "https://example.invalid/pull/1".into(),
4203 agent: "worker".into(),
4204 context: "evidence".into(),
4205 });
4206 task.resume_override = Some(OperatorResume {
4207 question_id: "old-question".into(),
4208 at: Timestamp::now(),
4209 conductor_rehold: None,
4210 forced: true,
4211 pinned_run: Some("old-run".into()),
4212 });
4213 task.interrupt = true;
4214 task.reassign_repository("new".into(), "test");
4215 assert!(task.review_branch.is_none());
4216 assert!(task.review_instruction.is_none());
4217 assert!(task.pr_recovery.is_none());
4218 assert!(task.replacement.is_none());
4219 assert!(task.resume_override.is_none());
4220 assert!(!task.interrupt);
4221 assert!(task.fresh_start);
4222 assert_eq!(task.instruction, "evidence");
4223 }
4224
4225 #[test]
4226 fn explicit_resumption_is_not_invented_for_legacy_or_automatic_release() {
4227 let t = Task::new(
4228 "retry".into(),
4229 "do it".into(),
4230 PathBuf::from("."),
4231 Source::Human,
4232 );
4233 let mut value = serde_json::to_value(&t).unwrap();
4234 for field in ["resumption", "resumption_history", "operator_decided_at"] {
4235 value.as_object_mut().unwrap().remove(field);
4236 }
4237 value["schema"] = serde_json::json!(15);
4238 let mut legacy: Task = serde_json::from_value(value).unwrap();
4239 legacy.hold_machine(Some("automatic retry".into()));
4240 legacy.release();
4241 assert!(legacy.resumption.is_none());
4242 assert!(legacy.resumption_history.is_empty());
4243 assert!(legacy.operator_decided_at.is_none());
4244 legacy.release_operator("cli", None);
4245 legacy.start("run".into());
4246 let reloaded: Task =
4247 serde_json::from_str(&serde_json::to_string(&legacy).unwrap()).unwrap();
4248 assert!(reloaded.resume_override.is_none());
4249 assert_eq!(reloaded.resumption.as_ref().unwrap().generation, 1);
4250 }
4251
4252 #[test]
4253 fn merge_over_lets_the_later_choice_win_and_keeps_the_rest() {
4254 let mut base = RunOverrides {
4255 merge: Some("pr".to_owned()),
4256 candidates: Some(3),
4257 ..RunOverrides::default()
4258 };
4259 base.merge_over(&RunOverrides {
4260 merge: Some("none".to_owned()),
4261 seed: Some(7),
4262 ..RunOverrides::default()
4263 });
4264 assert_eq!(base.merge.as_deref(), Some("none"));
4265 assert_eq!(base.candidates, Some(3));
4266 assert_eq!(base.seed, Some(7));
4267 }
4268
4269 #[test]
4270 fn an_already_landed_task_is_done_with_its_attempt_refunded() {
4271 let mut t = task("relanded");
4272 t.attempts = 1;
4273 t.status = TaskStatus::Running;
4274 t.already_landed("already in main as 0e368de");
4275 assert_eq!(t.status, TaskStatus::Done);
4276 assert_eq!(t.attempts, 0);
4277 assert!(t.hold_reason.is_none());
4278 assert_eq!(t.last_error.as_deref(), Some("already in main as 0e368de"));
4279 }
4280
4281 #[test]
4282 fn missing_blocker_reason_follows_the_language() {
4283 let b = vec!["a".to_owned()];
4284 let en = missing_blocker_hold_reason_in(&b, &b, "en");
4285 assert_eq!(en, missing_blocker_hold_reason(&b, &b));
4286 assert!(en.starts_with("blocked on a"));
4287 assert!(missing_blocker_hold_reason_in(&b, &b, "ja").contains("存在しません"));
4288 assert_eq!(missing_blocker_hold_reason_in(&b, &b, "de"), en);
4289 }
4290
4291 use super::*;
4292
4293 #[test]
4294 fn triage_applied_survives_release_and_old_records_read_as_empty() {
4295 let mut t = Task::new(
4296 "t".to_owned(),
4297 "i".to_owned(),
4298 PathBuf::from("r"),
4299 Source::Human,
4300 );
4301 t.mark_triage_applied("q1");
4302 t.mark_triage_applied("q1");
4303 t.hold_machine(Some("x".to_owned()));
4304 t.release();
4305 assert_eq!(t.triage_applied, ["q1"]);
4306 assert!(t.triage_applied("q1") && !t.triage_applied("q2"));
4307
4308 let mut v = serde_json::to_value(&t).unwrap();
4309 v.as_object_mut().unwrap().remove("triage_applied");
4310 let old: Task = serde_json::from_value(v).unwrap();
4311 assert!(old.triage_applied.is_empty());
4312 }
4313
4314 #[test]
4315 fn task_counts_of_empty_is_all_zero() {
4316 assert_eq!(TaskCounts::of(&[]), TaskCounts::default());
4317 }
4318
4319 #[test]
4320 fn task_counts_of_tallies_every_status() {
4321 let mut queued = Task::new(
4322 "q".to_owned(),
4323 "i".to_owned(),
4324 PathBuf::from("."),
4325 Source::Human,
4326 );
4327 queued.status = TaskStatus::Queued;
4328 let mut running = queued.clone();
4329 running.status = TaskStatus::Running;
4330 let mut done = queued.clone();
4331 done.status = TaskStatus::Done;
4332 let mut failed = queued.clone();
4333 failed.status = TaskStatus::Failed;
4334 let mut held = queued.clone();
4335 held.status = TaskStatus::Held;
4336 let mut blocked = queued.clone();
4337 blocked.status = TaskStatus::Blocked;
4338
4339 let mut parked = queued.clone();
4340 parked.status = TaskStatus::Parked;
4341
4342 let counts = TaskCounts::of(&[
4343 queued,
4344 running,
4345 done.clone(),
4346 done,
4347 failed,
4348 held,
4349 blocked,
4350 parked,
4351 ]);
4352 assert_eq!(
4353 counts,
4354 TaskCounts {
4355 queued: 1,
4356 running: 1,
4357 done: 2,
4358 failed: 1,
4359 held: 1,
4360 blocked: 1,
4361 parked: 1,
4362 }
4363 );
4364 }
4365
4366 #[test]
4367 fn task_implementers_persist_normalized_without_losing_history() {
4368 let (_dir, q) = queue();
4369 let mut t = task("keep me");
4370 t.hold_manual(Some("waiting".into()));
4371 t.runs.push("earlier-run".into());
4372 t.attachments.push("reference.txt".into());
4373 let cfg: crate::config::Config =
4374 toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
4375 .unwrap();
4376 q.put(&mut t).unwrap();
4377 let original = serde_json::to_value(&t).unwrap();
4378 for n in [2, 1, 2] {
4379 t.set_implementers(n, &cfg).unwrap();
4380 q.put(&mut t).unwrap();
4381 t = q.get(&t.id).unwrap();
4382 assert_eq!(t.implementers(), Some(usize::from(n)));
4383 assert_eq!(t.solo, n == 1);
4384 if n == 1 {
4385 assert!(t.overrides.is_none());
4386 }
4387 let mut actual = serde_json::to_value(&t).unwrap();
4388 for field in ["solo", "overrides", "updated_at"] {
4389 actual[field] = original[field].clone();
4390 }
4391 assert_eq!(actual, original);
4392 }
4393 t.overrides.as_mut().unwrap().judges = Some(2);
4394 t.set_implementers(1, &cfg).unwrap();
4395 assert_eq!(t.overrides.as_ref().unwrap().judges, Some(2));
4396 assert_eq!(t.overrides.as_ref().unwrap().candidates, None);
4397 }
4398
4399 #[test]
4400 fn task_implementers_old_records_keep_inheritance_until_changed() {
4401 let mut value = serde_json::to_value(task("old task")).unwrap();
4402 value.as_object_mut().unwrap().remove("solo");
4403 value.as_object_mut().unwrap().remove("overrides");
4404 let mut old: Task = serde_json::from_value(value).unwrap();
4405 assert_eq!(old.implementers(), None);
4406 old.set_implementers(1, &crate::config::Config::default())
4407 .unwrap();
4408 assert!(old.solo);
4409 assert!(old.overrides.is_none());
4410 }
4411
4412 #[test]
4413 fn task_implementers_reject_invalid_counts_and_states() {
4414 let cfg = crate::config::Config::default();
4415 let mut t = task("unchanged");
4416 for n in [0, 4, 255] {
4417 assert!(t.set_implementers(n, &cfg).is_err());
4418 }
4419 for status in [
4420 TaskStatus::Running,
4421 TaskStatus::Done,
4422 TaskStatus::Failed,
4423 TaskStatus::Blocked,
4424 TaskStatus::Parked,
4425 ] {
4426 t.status = status;
4427 let before = serde_json::to_value(&t).unwrap();
4428 assert!(t.set_implementers(1, &cfg).is_err());
4429 assert_eq!(serde_json::to_value(&t).unwrap(), before);
4430 }
4431 }
4432
4433 fn queue() -> (tempfile::TempDir, Queue) {
4436 let dir = tempfile::tempdir().unwrap();
4437 let q = Queue::at(dir.path().join("queue"));
4438 (dir, q)
4439 }
4440
4441 #[test]
4442 fn base_recovery_commit_retains_decision_and_superseded_resume_evidence() {
4443 let (_dir, q) = queue();
4444 let mut original = task("base recovery");
4445 original
4446 .decision_effects
4447 .insert("old-effect".into(), "receipt".into());
4448 original
4449 .dispatched_resumes
4450 .insert("dispatched".into(), "prior-run".into());
4451 original.resume_override = Some(OperatorResume {
4452 question_id: "prior-decision".into(),
4453 at: Timestamp::now(),
4454 conductor_rehold: None,
4455 forced: true,
4456 pinned_run: Some("retained-run".into()),
4457 });
4458 q.put(&mut original).unwrap();
4459 let expected = serde_json::to_value(&original).unwrap();
4460 let mut recovered = original.clone();
4461 recovered.base_recovery_requests.push("chat/request".into());
4462 recovered
4463 .resume_override
4464 .as_mut()
4465 .unwrap()
4466 .question_id
4467 .clear();
4468 q.commit_base_recovery(&mut recovered, &expected).unwrap();
4469 let saved = q.get(&original.id).unwrap();
4470 assert_eq!(saved.decision_effects, original.decision_effects);
4471 assert_eq!(saved.dispatched_resumes, original.dispatched_resumes);
4472 assert_eq!(
4473 saved
4474 .superseded_resumes
4475 .get("prior-decision")
4476 .map(String::as_str),
4477 Some("retained-run")
4478 );
4479 assert_eq!(saved.base_recovery_requests, ["chat/request"]);
4480 assert!(saved.resume_override.unwrap().question_id.is_empty());
4481 assert!(q.commit_base_recovery(&mut recovered, &expected).is_err());
4482 }
4483
4484 #[test]
4485 fn a_stale_write_does_not_drop_the_recorded_task_chat() {
4486 let (_dir, q) = queue();
4487 let mut stale = task("chat");
4488 q.put(&mut stale).unwrap();
4489 let mut fresh = q.get(&stale.id).unwrap();
4490 fresh.chat = Some("talk-1".to_owned());
4491 q.put(&mut fresh).unwrap();
4492 q.put(&mut stale).unwrap();
4493 assert_eq!(q.get(&stale.id).unwrap().chat.as_deref(), Some("talk-1"));
4494 }
4495
4496 #[test]
4497 fn putting_a_machine_held_task_files_a_notification_beside_the_queue() {
4498 let dir = tempfile::tempdir().unwrap();
4499 let q = Queue::at(dir.path().join("queue"));
4500 let mut t = task("held");
4501 q.put(&mut t).unwrap();
4502 assert_eq!(
4503 crate::notices::Notices::at(dir.path().join("notifications"))
4504 .list()
4505 .len(),
4506 0
4507 );
4508 t.hold_machine(Some("out of attempts".to_owned()));
4509 q.put(&mut t).unwrap();
4510 let listed = crate::notices::Notices::at(dir.path().join("notifications")).list();
4511 assert_eq!(listed.len(), 1);
4512 assert!(listed[0].message.contains("out of attempts"));
4513 }
4514
4515 #[test]
4516 fn start_consumes_the_disk_resume_pin() {
4517 let mut t = task("pin");
4518 t.disk_resume_run = Some("run-1".into());
4519 t.start("run-1".into());
4520 assert!(t.disk_resume_run.is_none());
4521 }
4522
4523 fn task(title: &str) -> Task {
4524 Task::new(
4525 title.to_owned(),
4526 format!("do {title}"),
4527 PathBuf::from("."),
4528 Source::Human,
4529 )
4530 }
4531
4532 #[test]
4533 fn attempt_limit_inherits_old_records_and_controls_failure() {
4534 let mut t = task("budget");
4535 let mut old = serde_json::to_value(&t).unwrap();
4536 old.as_object_mut().unwrap().remove("attempt_limit");
4537 old["schema"] = serde_json::json!(15);
4538 let legacy: Task = serde_json::from_value(old).unwrap();
4539 assert_eq!(legacy.attempt_limit, None);
4540 assert_eq!(legacy.effective_attempt_limit(2), 2);
4541 t.attempts = 2;
4542 t.change_attempt_limit(NonZeroUsize::new(3)).unwrap();
4543 t.fail("retry", 1);
4544 assert_eq!(t.status, TaskStatus::Failed);
4545 t.attempts = 3;
4546 t.fail("stop", 10);
4547 assert_eq!(t.status, TaskStatus::Held);
4548 t.change_attempt_limit(None).unwrap();
4549 assert_eq!(t.status, TaskStatus::Held);
4550 assert_eq!(t.attempts, 3);
4551 t.fail("inherit", 4);
4552 assert_eq!(t.status, TaskStatus::Failed);
4553 for status in [
4554 TaskStatus::Running,
4555 TaskStatus::Done,
4556 TaskStatus::Failed,
4557 TaskStatus::Blocked,
4558 TaskStatus::Parked,
4559 ] {
4560 t.status = status;
4561 assert!(t.change_attempt_limit(NonZeroUsize::new(1)).is_err());
4562 assert_eq!(t.attempt_limit, None);
4563 }
4564 }
4565
4566 #[test]
4567 fn earlier_attempts_is_every_recorded_run_and_agrees_with_the_display() {
4568 let mut t = task("retried");
4569 assert!(
4570 t.earlier_attempts().is_empty(),
4571 "a first attempt takes nothing over"
4572 );
4573 t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned()];
4574 assert_eq!(t.earlier_attempts(), ["aaaa", "bbbb"]);
4575 assert_eq!(t.successor_of("aaaa"), Some(&"bbbb".to_owned()));
4577 assert_eq!(t.successor_of("bbbb"), None);
4578 assert_eq!(t.successor_of("zzzz"), None);
4579 }
4580
4581 #[test]
4582 fn resumed_runs_are_superseded_only_after_their_last_occurrence() {
4583 let (_dir, q) = queue();
4584 let mut t = task("resumed");
4585 for (runs, successor) in [
4586 (vec!["aaaa", "aaaa"], None),
4587 (vec!["aaaa", "bbbb", "aaaa"], None),
4588 (vec!["aaaa", "aaaa", "bbbb"], Some("bbbb")),
4589 (vec!["aaaa", "bbbb", "aaaa", "cccc"], Some("cccc")),
4590 ] {
4591 t.runs = runs.into_iter().map(str::to_owned).collect();
4592 q.put(&mut t).unwrap();
4593
4594 assert_eq!(t.successor_of("aaaa").map(String::as_str), successor);
4595 assert_eq!(q.superseded_by("aaaa").as_deref(), successor);
4596 assert_eq!(q.superseded().get("aaaa").map(String::as_str), successor);
4597 }
4598 }
4599
4600 #[test]
4601 fn superseded_by_names_the_next_attempt_and_none_for_the_last() {
4602 let (_dir, q) = queue();
4603 let mut t = task("retried");
4604 t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned(), "cccc".to_owned()];
4605 q.put(&mut t).unwrap();
4606
4607 assert_eq!(q.superseded_by("aaaa"), Some("bbbb".to_owned()));
4608 assert_eq!(q.superseded_by("bbbb"), Some("cccc".to_owned()));
4609 assert_eq!(
4610 q.superseded_by("cccc"),
4611 None,
4612 "the latest attempt replaces nothing"
4613 );
4614 assert_eq!(
4615 q.superseded_by("never-heard-of-it"),
4616 None,
4617 "a run belonging to no task on this queue is not superseded"
4618 );
4619
4620 let mut by = HashMap::new();
4621 by.insert("aaaa".to_owned(), "bbbb".to_owned());
4622 by.insert("bbbb".to_owned(), "cccc".to_owned());
4623 assert_eq!(
4624 q.superseded(),
4625 by,
4626 "the whole-map and single-run forms must agree"
4627 );
4628 }
4629
4630 #[test]
4631 fn superseded_attempts_is_empty_until_the_task_is_done() {
4632 let mut t = task("retried");
4633 t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned()];
4634 t.status = TaskStatus::Failed;
4635 assert_eq!(
4636 t.superseded_attempts(true),
4637 &[] as &[String],
4638 "a task still retrying has no attempt yet that a later one made moot"
4639 );
4640
4641 t.status = TaskStatus::Running;
4642 assert_eq!(t.superseded_attempts(true), &[] as &[String]);
4643 }
4644
4645 #[test]
4646 fn superseded_attempts_names_every_run_before_the_one_that_succeeded() {
4647 let mut t = task("retried");
4648 t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned(), "cccc".to_owned()];
4649 t.status = TaskStatus::Done;
4650 assert_eq!(
4651 t.superseded_attempts(true),
4652 &["aaaa".to_owned(), "bbbb".to_owned()],
4653 "cccc is the attempt whose success made the task done, and stays out"
4654 );
4655 }
4656
4657 #[test]
4658 fn superseded_attempts_is_empty_for_a_done_task_with_only_one_attempt() {
4659 let mut t = task("first try landed");
4660 t.runs = vec!["aaaa".to_owned()];
4661 t.status = TaskStatus::Done;
4662 assert_eq!(t.superseded_attempts(true), &[] as &[String]);
4663 }
4664
4665 #[test]
4666 fn superseded_attempts_is_empty_when_the_last_run_never_actually_succeeded() {
4667 let mut t = task("closed by hand after a manual merge");
4674 t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned()];
4675 t.status = TaskStatus::Done;
4676 assert_eq!(
4677 t.superseded_attempts(false),
4678 &[] as &[String],
4679 "nothing here is provably why the task is done, so nothing is superseded"
4680 );
4681 }
4682
4683 #[test]
4684 fn latest_attempt_names_the_chain_s_current_head_not_just_the_next_one() {
4685 let (_dir, q) = queue();
4686 let mut t = task("retried twice");
4687 t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned(), "cccc".to_owned()];
4688 q.put(&mut t).unwrap();
4689
4690 assert_eq!(
4691 q.latest_attempt("aaaa"),
4692 Some("cccc".to_owned()),
4693 "an old attempt points straight at the chain's current head, not the \
4694 next attempt in the middle of it"
4695 );
4696 assert_eq!(q.latest_attempt("bbbb"), Some("cccc".to_owned()));
4697 assert_eq!(
4698 q.latest_attempt("cccc"),
4699 None,
4700 "the latest attempt is not superseded by anything"
4701 );
4702 assert_eq!(
4703 q.latest_attempt("never-heard-of-it"),
4704 None,
4705 "a run belonging to no task on this queue is not superseded"
4706 );
4707 }
4708
4709 #[test]
4710 fn a_markdown_heading_is_the_title_not_decoration() {
4711 assert_eq!(
4716 title_from("# Rework the config loader\n\nIt re-reads it.\n", 40),
4717 "Rework the config loader"
4718 );
4719 assert_eq!(title_from("- fix the thing", 40), "fix the thing");
4720 assert_eq!(title_from("> quoted task", 40), "quoted task");
4721 assert_eq!(title_from(" \n\n", 40), "(empty task)");
4723 assert_eq!(title_from("###\n", 40), "(empty task)");
4724 }
4725
4726 #[test]
4727 fn a_long_title_is_elided_by_characters_not_bytes() {
4728 let long = "課題".repeat(30);
4730 let title = title_from(&long, 10);
4731 assert_eq!(title.chars().count(), 10);
4732 assert!(title.ends_with('…'));
4733 }
4734
4735 #[test]
4736 fn priority_wins_and_ties_break_oldest_first() {
4737 let (_dir, q) = queue();
4738 let mut a = task("first");
4739 let mut b = task("second");
4740 let mut c = task("urgent");
4741 a.id = "20260101-000001-aaaa".to_owned();
4743 b.id = "20260101-000002-bbbb".to_owned();
4744 c.id = "20260101-000003-cccc".to_owned();
4745 c.priority = 5;
4746 for t in [&mut a, &mut b, &mut c] {
4747 q.put(t).unwrap();
4748 }
4749
4750 assert_eq!(q.next_runnable().unwrap().id, c.id);
4752 c.hold_machine(None);
4753 q.put(&mut c).unwrap();
4754 assert_eq!(q.next_runnable().unwrap().id, a.id);
4756 assert_eq!(q.list().len(), 3, "b is still waiting its turn");
4757 }
4758
4759 #[test]
4760 fn a_blocked_task_never_starves_another_runnable_one() {
4761 let (_dir, q) = queue();
4762 let mut blocked = task("blocked");
4763 blocked.block(vec!["something".to_owned()], None);
4764 q.put(&mut blocked).unwrap();
4765
4766 let mut runnable = task("free to go");
4767 q.put(&mut runnable).unwrap();
4768
4769 let next = q.next_runnable().expect("a runnable task is still offered");
4770 assert_eq!(next.id, runnable.id);
4771 }
4772
4773 #[test]
4774 fn a_held_task_is_never_offered_to_the_loop() {
4775 let (_dir, q) = queue();
4776 let mut t = task("held");
4777 q.put(&mut t).unwrap();
4778 assert!(q.next_runnable().is_some());
4779
4780 t.hold_machine(None);
4781 q.put(&mut t).unwrap();
4782 assert!(
4783 q.next_runnable().is_none(),
4784 "a held task must wait for a human"
4785 );
4786
4787 t.status = TaskStatus::Failed;
4789 q.put(&mut t).unwrap();
4790 assert!(q.next_runnable().is_some());
4791 }
4792
4793 #[test]
4794 fn attempts_are_capped_and_then_the_task_is_held() {
4795 let mut t = task("doomed");
4796
4797 t.start("run-1".to_owned());
4798 t.fail("gate red", 2);
4799 assert_eq!(t.status, TaskStatus::Failed, "one attempt of two: retry");
4800
4801 t.start("run-2".to_owned());
4802 t.fail("gate red", 2);
4803 assert_eq!(
4804 t.status,
4805 TaskStatus::Held,
4806 "out of attempts: stop spending money on it"
4807 );
4808 assert_eq!(t.runs, ["run-1", "run-2"]);
4809 assert_eq!(t.last_error.as_deref(), Some("gate red"));
4810 assert_eq!(
4811 t.hold_reason.as_deref(),
4812 Some("gate red"),
4813 "the hold must say why, not leave hold_reason null next to a \
4814 populated last_error"
4815 );
4816 }
4817
4818 #[test]
4819 fn handing_off_a_task_records_a_hold_reason_too() {
4820 let mut t = task("left a pull request");
4821 t.start("run-1".to_owned());
4822 t.handed_off("run ended with a pull request open [run run-1]");
4823 assert_eq!(t.status, TaskStatus::Held);
4824 assert_eq!(t.hold_source, Some(HoldSource::Machine));
4825 assert_eq!(
4826 t.hold_reason.as_deref(),
4827 Some("run ended with a pull request open [run run-1]")
4828 );
4829 assert_eq!(t.hold_reason, t.last_error);
4830 }
4831
4832 #[test]
4833 fn a_quota_stall_is_refunded_so_the_backlog_survives_the_night() {
4834 let mut t = task("stalled by quota");
4835
4836 t.start("run-1".to_owned());
4837 assert_eq!(t.attempts, 1);
4838 t.stall("judge-1, judge-2 out of quota");
4839 assert_eq!(
4840 t.attempts, 0,
4841 "a closed quota window must not spend the task's retry budget"
4842 );
4843 assert_eq!(t.status, TaskStatus::Failed, "the loop should retry it");
4844 assert_eq!(
4845 t.last_error.as_deref(),
4846 Some("judge-1, judge-2 out of quota")
4847 );
4848
4849 for _ in 0..20 {
4852 t.start("run-n".to_owned());
4853 t.stall("still out of quota");
4854 }
4855 t.start("run-real".to_owned());
4856 t.fail("gate red", 2);
4857 assert_eq!(
4858 t.status,
4859 TaskStatus::Failed,
4860 "the first attempt that was really judged is attempt one"
4861 );
4862 }
4863
4864 #[test]
4865 fn releasing_a_held_task_gives_it_a_real_second_chance() {
4866 let mut t = task("retry me");
4867 t.start("run-1".to_owned());
4868 t.fail("gate red", 1);
4869 assert_eq!(t.status, TaskStatus::Held);
4870
4871 t.release();
4872 assert_eq!(t.status, TaskStatus::Queued);
4873 assert_eq!(t.attempts, 0);
4876 assert!(t.last_error.is_none());
4877 assert_eq!(
4878 t.runs.len(),
4879 1,
4880 "history is kept: attempts reset, evidence does not"
4881 );
4882 }
4883
4884 #[test]
4885 fn a_hold_reason_survives_and_a_release_clears_it() {
4886 let mut t = task("waiting on something else");
4887 t.hold_manual(Some(
4888 "waiting for 20260101-000000-aaaa to land first".to_owned(),
4889 ));
4890 assert_eq!(t.status, TaskStatus::Held);
4891 assert_eq!(
4892 t.hold_reason.as_deref(),
4893 Some("waiting for 20260101-000000-aaaa to land first")
4894 );
4895
4896 t.hold_manual(None);
4898 assert_eq!(
4899 t.hold_reason.as_deref(),
4900 Some("waiting for 20260101-000000-aaaa to land first"),
4901 "a bare re-hold keeps whatever a human already wrote down"
4902 );
4903
4904 let mut plain = task("no reason given");
4906 plain.hold_manual(None);
4907 assert_eq!(plain.status, TaskStatus::Held);
4908 assert!(plain.hold_reason.is_none());
4909
4910 t.release();
4911 assert_eq!(t.status, TaskStatus::Queued);
4912 assert!(
4913 t.hold_reason.is_none(),
4914 "a stale reason must not greet the next person who holds this task"
4915 );
4916 }
4917
4918 #[test]
4919 fn closing_a_held_task_as_done_clears_its_hold_reason_too() {
4920 let mut t = task("landed by hand while held");
4925 t.hold_manual(Some("waiting on 3ed9".to_owned()));
4926 assert_eq!(t.hold_reason.as_deref(), Some("waiting on 3ed9"));
4927
4928 t.succeed();
4929 assert_eq!(t.status, TaskStatus::Done);
4930 assert!(
4931 t.hold_reason.is_none(),
4932 "a done task cannot still be waiting on something"
4933 );
4934 }
4935
4936 #[test]
4937 fn holding_or_closing_a_blocked_task_clears_its_dependency_too() {
4938 let mut held = task("held straight out of blocked");
4945 held.block(
4946 vec!["20260101-000000-dead".to_owned()],
4947 Some("waiting on the migration script".to_owned()),
4948 );
4949 assert_eq!(held.status, TaskStatus::Blocked);
4950
4951 held.hold_manual(None);
4952 assert_eq!(held.status, TaskStatus::Held);
4953 assert!(
4954 held.blocked_by.is_empty(),
4955 "hold overrides the wait, same as release"
4956 );
4957 assert!(held.block_reason.is_none());
4958
4959 let mut done = task("closed straight out of blocked");
4960 done.block(
4961 vec!["20260101-000000-dead".to_owned()],
4962 Some("waiting on the migration script".to_owned()),
4963 );
4964 done.succeed();
4965 assert_eq!(done.status, TaskStatus::Done);
4966 assert!(
4967 done.blocked_by.is_empty(),
4968 "a done task cannot still be waiting on a dependency"
4969 );
4970 assert!(done.block_reason.is_none());
4971 }
4972
4973 #[test]
4974 fn a_blocked_task_is_never_offered_to_the_loop() {
4975 let mut t = task("blocked");
4976 assert!(t.status.runnable());
4977 t.block(
4978 vec!["dep-id".to_owned()],
4979 Some("waits on dep-id".to_owned()),
4980 );
4981 assert_eq!(t.status, TaskStatus::Blocked);
4982 assert!(!t.status.runnable());
4983 assert_eq!(TaskStatus::Blocked.as_str(), "blocked");
4984 }
4985
4986 #[test]
4987 fn unblocking_the_last_dependency_returns_the_task_to_queued() {
4988 let mut t = task("blocked on two");
4989 t.block(
4990 vec!["a".to_owned(), "b".to_owned()],
4991 Some("waits on a and b".to_owned()),
4992 );
4993
4994 t.unblock("a");
4995 assert_eq!(t.status, TaskStatus::Blocked, "b is still outstanding");
4996 assert_eq!(t.blocked_by, ["b"]);
4997
4998 t.unblock("b");
4999 assert_eq!(t.status, TaskStatus::Queued);
5000 assert!(t.blocked_by.is_empty());
5001 assert!(t.block_reason.is_none());
5002 }
5003
5004 #[test]
5005 fn unblocking_an_id_on_a_task_that_is_not_blocked_is_a_no_op() {
5006 let mut t = task("never blocked");
5007 t.unblock("whatever");
5008 assert_eq!(t.status, TaskStatus::Queued);
5009 }
5010
5011 #[test]
5012 fn a_held_task_blocked_on_a_question_returns_to_held_not_queued() {
5013 let mut t = task("held, then asked about");
5018 t.hold_machine(Some("out of attempts".to_owned()));
5019 assert_eq!(t.status, TaskStatus::Held);
5020
5021 t.block(vec!["q1".to_owned()], Some("what now?".to_owned()));
5022 assert_eq!(t.status, TaskStatus::Blocked);
5023
5024 t.record_answer("what now?".to_owned(), "leave it held".to_owned());
5025 t.unblock("q1");
5026 assert_eq!(t.status, TaskStatus::Held, "must restore, not requeue");
5027 assert_eq!(t.hold_reason.as_deref(), Some("out of attempts"));
5028 assert_eq!(t.hold_source, Some(HoldSource::Machine));
5029 assert!(t.blocked_from.is_none(), "consumed once restored");
5030 }
5031
5032 #[test]
5033 fn a_manually_held_task_blocked_on_a_question_returns_to_held() {
5034 let mut t = task("manually held, then asked about");
5035 t.hold_manual(Some("waiting on a dependency".to_owned()));
5036
5037 t.block(vec!["q1".to_owned()], None);
5038 t.unblock("q1");
5039
5040 assert_eq!(t.status, TaskStatus::Held);
5041 assert_eq!(t.hold_source, Some(HoldSource::Manual));
5042 }
5043
5044 #[test]
5045 fn re_blocking_an_already_blocked_task_keeps_the_original_blocked_from() {
5046 let mut t = task("held, blocked twice");
5050 t.hold_machine(None);
5051 t.block(vec!["q1".to_owned()], Some("first".to_owned()));
5052 t.block(
5053 vec!["q1".to_owned(), "q2".to_owned()],
5054 Some("second".to_owned()),
5055 );
5056
5057 t.unblock("q1");
5058 assert_eq!(t.status, TaskStatus::Blocked, "q2 still outstanding");
5059 t.unblock("q2");
5060 assert_eq!(t.status, TaskStatus::Held);
5061 }
5062
5063 #[test]
5064 fn unblocking_a_task_blocked_while_running_lands_on_queued_not_running() {
5065 let mut t = task("blocked mid-run");
5069 t.start("run-1".to_owned());
5070 assert_eq!(t.status, TaskStatus::Running);
5071
5072 t.block(vec!["q1".to_owned()], None);
5073 t.unblock("q1");
5074 assert_eq!(t.status, TaskStatus::Queued);
5075 }
5076
5077 #[test]
5078 fn a_pre_schema_4_blocked_record_with_hold_evidence_restores_to_held() {
5079 let mut t = task("legacy record, held before it was blocked");
5085 t.hold_source = Some(HoldSource::Machine);
5086 t.hold_reason = Some("legacy hold reason".to_owned());
5087 t.status = TaskStatus::Blocked;
5088 t.blocked_by = vec!["q1".to_owned()];
5089 t.blocked_from = None;
5090
5091 t.unblock("q1");
5092 assert_eq!(t.status, TaskStatus::Held);
5093 }
5094
5095 #[test]
5096 fn a_pre_schema_4_blocked_record_with_no_hold_evidence_restores_to_queued() {
5097 let mut t = task("legacy record, ordinary dependency block");
5098 t.status = TaskStatus::Blocked;
5099 t.blocked_by = vec!["dep".to_owned()];
5100 t.blocked_from = None;
5101
5102 t.unblock("dep");
5103 assert_eq!(t.status, TaskStatus::Queued);
5104 }
5105
5106 #[test]
5107 fn answering_a_question_is_recorded_and_survives_a_release() {
5108 let mut t = task("asked something");
5109 t.block(vec!["q1".to_owned()], Some("which backend?".to_owned()));
5110 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
5111 t.unblock("q1");
5112 assert_eq!(t.status, TaskStatus::Queued);
5113 assert_eq!(t.answers.len(), 1);
5114 assert_eq!(t.answers[0].answer, "SQLite");
5115
5116 t.release();
5120 assert_eq!(t.answers.len(), 1, "the answer is not lost on release");
5121 }
5122
5123 #[test]
5124 fn resumption_review_branch_requires_unchanged_authored_criteria() {
5125 for source in ["cli", "web"] {
5126 let mut t = task("review old candidate");
5127 t.request_review("candidate-A".into());
5128 t.hold_for_handover(Some("candidate-A".into()), "handover refused".into());
5129 let mut unchanged = t.clone();
5130 unchanged.release_operator(source, None);
5131 assert_eq!(unchanged.review_branch.as_deref(), Some("candidate-A"));
5132 t.edit(
5133 "review approved head".into(),
5134 "Reuse measured PR head B; fix Clippy; review".into(),
5135 )
5136 .unwrap();
5137 t.release_operator(source, None);
5138 assert!(t.review_branch.is_none());
5139 assert!(t.review_instruction.is_none());
5140 let mut legacy = unchanged;
5142 legacy.review_instruction = None;
5143 legacy.hold_for_handover(None, "still checked out".into());
5144 legacy
5145 .edit("new plan".into(), "Reuse measured PR head B".into())
5146 .unwrap();
5147 legacy.release_operator(source, None);
5148 assert!(legacy.review_branch.is_none());
5149 }
5150 }
5151
5152 #[test]
5153 fn a_refused_handover_keeps_the_review_branch_across_release() {
5154 let mut t = task("refused takeover");
5155 t.start("run-1".to_owned());
5156 t.hold_for_handover(Some("magi/eba2/A".to_owned()), "checked out".to_owned());
5157 assert_eq!(t.status, TaskStatus::Held);
5158 assert_eq!(t.attempts, 1);
5159 t.release();
5160 assert_eq!(t.status, TaskStatus::Queued);
5161 assert_eq!(t.attempts, 0);
5162 assert_eq!(t.review_branch.as_deref(), Some("magi/eba2/A"));
5163
5164 t.hold_for_handover(None, "again".to_owned());
5166 t.requeue();
5167 assert!(t.review_branch.is_none());
5168
5169 let mut m = task("manual");
5171 m.review_branch = Some("magi/x/A".to_owned());
5172 m.hold_manual(None);
5173 m.release();
5174 assert!(m.review_branch.is_none());
5175 }
5176
5177 #[test]
5178 fn requesting_review_requeues_the_task_and_remembers_the_branch() {
5179 let mut t = task("blocked run with a surviving branch");
5180 t.start("run-1".to_owned());
5181 t.fail("blocked with major findings", 5);
5182 assert_eq!(t.status, TaskStatus::Failed);
5183
5184 t.request_review("magi/eba2/A".to_owned());
5185 assert_eq!(t.status, TaskStatus::Queued);
5186 assert_eq!(t.attempts, 0);
5187 assert_eq!(t.review_branch.as_deref(), Some("magi/eba2/A"));
5188
5189 t.release();
5191 assert!(t.review_branch.is_none());
5192 }
5193
5194 #[test]
5195 fn conductor_requeue_but_not_an_ordinary_release_forces_a_fresh_start() {
5196 let mut t = task("retry");
5197 t.start("run-1".to_owned());
5198 t.requeue();
5199 assert!(t.fresh_start);
5200
5201 t.release();
5202 assert!(!t.fresh_start);
5203 }
5204
5205 #[test]
5206 fn urgent_only_changes_queued_or_held_and_preserves_settings() {
5207 for status in [
5208 TaskStatus::Queued,
5209 TaskStatus::Held,
5210 TaskStatus::Running,
5211 TaskStatus::Done,
5212 TaskStatus::Failed,
5213 TaskStatus::Blocked,
5214 TaskStatus::Parked,
5215 ] {
5216 let mut t = task("urgent settings");
5217 t.status = status;
5218 t.attempts = 2;
5219 t.hold_reason = Some("waiting".into());
5220 t.priority = 7;
5221 t.interrupt = true;
5222 let before = serde_json::to_value(&t).unwrap();
5223 for urgent in [true, true, false, false] {
5224 let result = t.set_urgent(urgent);
5225 let mut expected = before.clone();
5226 if matches!(status, TaskStatus::Queued | TaskStatus::Held) {
5227 result.unwrap();
5228 expected["urgent"] = urgent.into();
5229 } else {
5230 let error = result.unwrap_err().to_string();
5231 assert!(error.contains(status.as_str()), "{error}");
5232 assert!(error.contains("queued or held"), "{error}");
5233 }
5234 assert_eq!(serde_json::to_value(&t).unwrap(), expected);
5235 }
5236 }
5237 }
5238
5239 #[test]
5240 fn priority_can_be_changed_while_queued_but_not_while_running() {
5241 let mut t = task("reprioritise me");
5242 t.set_priority(5).unwrap();
5243 assert_eq!(t.priority, 5);
5244
5245 t.start("run-1".to_owned());
5246 let err = t.set_priority(9).unwrap_err().to_string();
5247 assert!(err.contains("running"), "{err}");
5248 assert_eq!(t.priority, 5, "the rejected write must not partially apply");
5249 }
5250
5251 #[test]
5252 fn interrupt_can_be_marked_while_queued_but_not_while_running() {
5253 let mut t = task("interrupt me");
5254 assert!(!t.interrupt, "off unless asked, same as any other task");
5255
5256 t.set_interrupt(true).unwrap();
5257 assert!(t.interrupt);
5258
5259 t.start("run-1".to_owned());
5260 assert!(
5261 !t.interrupt,
5262 "the mark is one-shot: dispatching the task fulfils it, \
5263 whatever the run that follows ends up doing"
5264 );
5265 let err = t.set_interrupt(true).unwrap_err().to_string();
5266 assert!(err.contains("running"), "{err}");
5267 t.set_interrupt(false).unwrap();
5270 assert!(!t.interrupt);
5271 }
5272
5273 #[test]
5277 fn a_failed_run_does_not_leave_the_task_still_marked_to_interrupt() {
5278 let mut t = task("interrupt me");
5279 t.set_interrupt(true).unwrap();
5280 t.start("run-1".to_owned());
5281 t.fail("mock failure", 5);
5282 assert_eq!(t.status, TaskStatus::Failed);
5283 assert!(
5284 !t.interrupt,
5285 "one attempt already spent the mark; a retry is an ordinary \
5286 requeue, not a fresh interrupt request"
5287 );
5288 }
5289
5290 #[test]
5291 fn changing_priority_moves_a_task_ahead_in_the_real_queue_order() {
5292 let (_dir, q) = queue();
5293 let mut a = task("first filed");
5294 let mut b = task("second filed");
5295 a.id = "20260101-000001-aaaa".to_owned();
5296 b.id = "20260101-000002-bbbb".to_owned();
5297 q.put(&mut a).unwrap();
5298 q.put(&mut b).unwrap();
5299
5300 assert_eq!(
5301 q.next_runnable().unwrap().id,
5302 a.id,
5303 "with equal priority the older task goes first, so a burst of \
5304 new work cannot starve it"
5305 );
5306 assert_eq!(
5307 q.list()[0].id,
5308 b.id,
5309 "but the list an operator reads is newest first, the same as \
5310 before priority existed - a's turn to run does not make it the \
5311 newest task"
5312 );
5313
5314 let mut a = q.get(&a.id).unwrap();
5315 a.set_priority(10).unwrap();
5316 q.put(&mut a).unwrap();
5317
5318 assert_eq!(
5319 q.next_runnable().unwrap().id,
5320 a.id,
5321 "a raised priority must be reflected the moment it is saved"
5322 );
5323 assert_eq!(
5327 q.list()[0].id,
5328 a.id,
5329 "the raised task must sort first in the list an operator reads, \
5330 not only in next_runnable's own ordering"
5331 );
5332 }
5333
5334 #[test]
5335 fn editing_replaces_title_and_instruction_but_keeps_identity_and_history() {
5336 let mut t = Task::new(
5337 "old title".to_owned(),
5338 "old instruction".to_owned(),
5339 PathBuf::from("/repo"),
5340 Source::Agent {
5341 run: "20260101-000000-beef".to_owned(),
5342 node: "implement".to_owned(),
5343 },
5344 );
5345 let id = t.id.clone();
5346 let created_at = t.created_at;
5347 t.runs.push("20260101-000000-beef".to_owned());
5348
5349 t.edit("new title".to_owned(), "new instruction".to_owned())
5350 .unwrap();
5351
5352 assert_eq!(t.title, "new title");
5353 assert_eq!(t.instruction, "new instruction");
5354 assert_eq!(t.id, id, "editing must not mint a new id");
5355 assert_eq!(t.created_at, created_at);
5356 assert_eq!(
5357 t.source,
5358 Source::Agent {
5359 run: "20260101-000000-beef".to_owned(),
5360 node: "implement".to_owned(),
5361 },
5362 "editing must not turn agent attribution into human"
5363 );
5364 assert_eq!(t.runs, ["20260101-000000-beef"]);
5365 }
5366
5367 #[test]
5368 fn editing_is_refused_once_a_task_is_running_or_finished() {
5369 let mut running = task("in flight");
5370 running.start("run-1".to_owned());
5371 let err = running
5372 .edit("x".to_owned(), "y".to_owned())
5373 .unwrap_err()
5374 .to_string();
5375 assert!(err.contains("running"), "{err}");
5376
5377 let mut done = task("finished");
5378 done.succeed();
5379 let err = done
5380 .edit("x".to_owned(), "y".to_owned())
5381 .unwrap_err()
5382 .to_string();
5383 assert!(err.contains("done"), "{err}");
5384
5385 let mut queued = task("waiting");
5387 queued.edit("x".to_owned(), "y".to_owned()).unwrap();
5388 let mut held = task("parked");
5389 held.hold_machine(None);
5390 held.edit("x".to_owned(), "y".to_owned()).unwrap();
5391 }
5392
5393 #[test]
5394 fn a_task_recorded_without_a_hold_reason_still_reads_as_none() {
5395 let (_dir, q) = queue();
5396 let path = q.path_of("20260101-000000-aaaa");
5397 std::fs::create_dir_all(q.root()).unwrap();
5398 std::fs::write(
5399 &path,
5400 serde_json::json!({
5401 "schema": SCHEMA,
5402 "id": "20260101-000000-aaaa",
5403 "title": "from before hold reasons existed",
5404 "instruction": "from before hold reasons existed",
5405 "repo": ".",
5406 "source": { "kind": "human" },
5407 "status": "held",
5408 "created_at": Timestamp::now().to_string(),
5409 "updated_at": Timestamp::now().to_string(),
5410 })
5411 .to_string(),
5412 )
5413 .unwrap();
5414
5415 let task = q.get("20260101-000000-aaaa").expect("must still read");
5416 assert!(task.hold_reason.is_none());
5417 assert!(task.operator_held());
5418 }
5419
5420 #[test]
5421 fn a_legacy_reasoned_hold_defaults_to_operator_protection() {
5422 let (_dir, q) = queue();
5423 let path = q.path_of("20260101-000000-bbbb");
5424 std::fs::create_dir_all(q.root()).unwrap();
5425 std::fs::write(
5426 &path,
5427 serde_json::json!({
5428 "schema": 2,
5429 "id": "20260101-000000-bbbb",
5430 "title": "old manual recovery",
5431 "instruction": "old manual recovery",
5432 "repo": ".",
5433 "source": { "kind": "human" },
5434 "status": "held",
5435 "hold_reason": "active manual recovery run20260912-224242-daf5",
5436 "created_at": Timestamp::now().to_string(),
5437 "updated_at": Timestamp::now().to_string(),
5438 })
5439 .to_string(),
5440 )
5441 .unwrap();
5442
5443 let task = q.get("20260101-000000-bbbb").expect("must still read");
5444 assert_eq!(task.hold_source, None);
5445 assert!(task.operator_held());
5446 }
5447
5448 #[test]
5449 fn a_task_recorded_without_a_diagnostic_still_reads_as_none() {
5450 let (_dir, q) = queue();
5451 let path = q.path_of("20260101-000000-aaaa");
5452 std::fs::create_dir_all(q.root()).unwrap();
5453 std::fs::write(
5454 &path,
5455 serde_json::json!({
5456 "schema": SCHEMA,
5457 "id": "20260101-000000-aaaa",
5458 "title": "from before diagnostics existed",
5459 "instruction": "from before diagnostics existed",
5460 "repo": ".",
5461 "source": { "kind": "human" },
5462 "status": "held",
5463 "created_at": Timestamp::now().to_string(),
5464 "updated_at": Timestamp::now().to_string(),
5465 })
5466 .to_string(),
5467 )
5468 .unwrap();
5469
5470 let task = q.get("20260101-000000-aaaa").expect("must still read");
5471 assert!(task.diagnostic.is_none());
5472 }
5473
5474 #[test]
5475 fn a_schema_1_task_with_no_blocking_fields_still_reads() {
5476 let (_dir, q) = queue();
5480 let path = q.path_of("20260101-000000-aaaa");
5481 std::fs::create_dir_all(q.root()).unwrap();
5482 std::fs::write(
5483 &path,
5484 serde_json::json!({
5485 "schema": 1,
5486 "id": "20260101-000000-aaaa",
5487 "title": "from before blocking existed",
5488 "instruction": "from before blocking existed",
5489 "repo": ".",
5490 "source": { "kind": "human" },
5491 "status": "queued",
5492 "created_at": Timestamp::now().to_string(),
5493 "updated_at": Timestamp::now().to_string(),
5494 })
5495 .to_string(),
5496 )
5497 .unwrap();
5498
5499 let task = q.get("20260101-000000-aaaa").expect("must still read");
5500 assert!(task.blocked_by.is_empty());
5501 assert!(task.block_reason.is_none());
5502 assert!(task.answers.is_empty());
5503 assert!(task.review_branch.is_none());
5504 }
5505
5506 #[test]
5507 fn releasing_or_finishing_a_task_clears_its_stale_diagnostic() {
5508 let mut held = task("diagnosed");
5513 held.start("run-1".to_owned());
5514 held.fail("gate red", 1);
5515 held.diagnostic = Some("cargo test failed: ...".to_owned());
5516 assert_eq!(held.status, TaskStatus::Held);
5517
5518 held.release();
5519 assert!(held.diagnostic.is_none());
5520
5521 held.diagnostic = Some("cargo test failed: ...".to_owned());
5522 held.succeed();
5523 assert!(held.diagnostic.is_none());
5524 }
5525
5526 #[test]
5527 fn failing_a_task_always_clears_whatever_diagnostic_it_carried() {
5528 let mut t = task("retried");
5529 t.start("run-1".to_owned());
5530 t.diagnostic = Some("stale evidence from a previous hold".to_owned());
5531 t.fail("unrelated config error", 5);
5532 assert_eq!(t.status, TaskStatus::Failed);
5533 assert!(
5534 t.diagnostic.is_none(),
5535 "fail() must not let an old diagnostic outlive the run that produced it"
5536 );
5537 }
5538
5539 #[test]
5540 fn a_claim_is_exclusive_and_releases_on_drop() {
5541 let (_dir, q) = queue();
5542 let mut t = task("contended");
5543 q.put(&mut t).unwrap();
5544
5545 let held = q.claim(&t.id).unwrap();
5546 assert!(
5547 q.claim(&t.id).is_err(),
5548 "two daemons must not drive one task into two runs"
5549 );
5550 drop(held);
5551 assert!(q.claim(&t.id).is_ok(), "a released claim is reclaimable");
5552 }
5553
5554 #[test]
5555 fn a_round_trip_survives_disk() {
5556 let (_dir, q) = queue();
5557 let mut t = Task::new(
5558 "titled".to_owned(),
5559 "body".to_owned(),
5560 PathBuf::from("/repo"),
5561 Source::Agent {
5562 run: "20260101-000000-beef".to_owned(),
5563 node: "implement".to_owned(),
5564 },
5565 );
5566 t.priority = 3;
5567 q.put(&mut t).unwrap();
5568
5569 let back = q.get(&t.id).unwrap();
5570 assert_eq!(back.id, t.id);
5571 assert_eq!(back.priority, 3);
5572 assert_eq!(back.source.label(), "implement@beef");
5573 assert_eq!(q.get(t.short()).unwrap().id, t.id);
5575 }
5576
5577 #[test]
5578 fn an_unreadable_task_does_not_take_the_queue_down() {
5579 let (_dir, q) = queue();
5580 let mut t = task("fine");
5581 q.put(&mut t).unwrap();
5582 std::fs::write(q.root().join("broken.json"), "{ not json").unwrap();
5583
5584 let listed = q.list();
5585 assert_eq!(listed.len(), 1, "the readable task still lists");
5586 assert_eq!(listed[0].id, t.id);
5587 }
5588
5589 #[test]
5590 fn a_task_recorded_without_a_solo_field_still_reads_as_not_solo() {
5591 let (_dir, q) = queue();
5592 let path = q.path_of("20260101-000000-aaaa");
5593 std::fs::create_dir_all(q.root()).unwrap();
5594 std::fs::write(
5595 &path,
5596 serde_json::json!({
5597 "schema": SCHEMA,
5598 "id": "20260101-000000-aaaa",
5599 "title": "from before solo existed",
5600 "instruction": "from before solo existed",
5601 "repo": ".",
5602 "source": { "kind": "human" },
5603 "status": "queued",
5604 "created_at": Timestamp::now().to_string(),
5605 "updated_at": Timestamp::now().to_string(),
5606 })
5607 .to_string(),
5608 )
5609 .unwrap();
5610
5611 let task = q.get("20260101-000000-aaaa").expect("must still read");
5612 assert!(!task.solo, "a queue file with no `solo` field means false");
5613 }
5614
5615 #[test]
5616 fn a_task_recorded_without_an_urgent_field_still_reads_as_not_urgent() {
5617 let (_dir, q) = queue();
5618 let path = q.path_of("20260101-000000-bbbb");
5619 std::fs::create_dir_all(q.root()).unwrap();
5620 std::fs::write(
5621 &path,
5622 serde_json::json!({
5623 "schema": SCHEMA,
5624 "id": "20260101-000000-bbbb",
5625 "title": "from before urgent existed",
5626 "instruction": "from before urgent existed",
5627 "repo": ".",
5628 "source": { "kind": "human" },
5629 "status": "queued",
5630 "created_at": Timestamp::now().to_string(),
5631 "updated_at": Timestamp::now().to_string(),
5632 })
5633 .to_string(),
5634 )
5635 .unwrap();
5636
5637 let task = q.get("20260101-000000-bbbb").expect("must still read");
5638 assert!(
5639 !task.urgent,
5640 "a queue file with no `urgent` field means false, same as `solo`"
5641 );
5642 }
5643
5644 #[test]
5645 fn a_task_from_a_future_schema_is_refused_rather_than_guessed_at() {
5646 let (_dir, q) = queue();
5647 let mut t = task("from the future");
5648 q.put(&mut t).unwrap();
5649 let path = q.path_of(&t.id);
5650 let body = std::fs::read_to_string(&path)
5651 .unwrap()
5652 .replace(&format!("\"schema\": {SCHEMA}"), "\"schema\": 99");
5653 std::fs::write(&path, body).unwrap();
5654
5655 let err = q.get(&t.id).unwrap_err().to_string();
5656 assert!(err.contains("schema 99"), "{err}");
5657 }
5658
5659 #[test]
5660 fn revision_moves_when_the_queue_changes() {
5661 let (_dir, q) = queue();
5662 assert_eq!(q.revision(), 0, "an empty queue has no revision");
5663 let mut t = task("first");
5664 q.put(&mut t).unwrap();
5665 assert!(q.revision() > 0, "a written task moves the revision");
5666 }
5667
5668 #[test]
5669 fn revision_moves_when_deleting_an_older_task() {
5670 let (dir, q) = queue();
5671 let questions = Questions::at(dir.path().join("questions"));
5672 let mut t1 = task("older");
5673 q.put(&mut t1).unwrap();
5674 std::thread::sleep(std::time::Duration::from_millis(10));
5676 let mut t2 = task("newer");
5677 q.put(&mut t2).unwrap();
5678
5679 let rev_before = q.revision();
5680 q.remove(&t1.id, false, &questions).unwrap();
5681 let rev_after = q.revision();
5682
5683 assert_ne!(
5684 rev_before, rev_after,
5685 "deleting an older task must change the revision so other clients see the deletion"
5686 );
5687 }
5688
5689 #[test]
5690 fn removing_a_task_takes_it_out_of_the_listing() {
5691 let (dir, q) = queue();
5692 let questions = Questions::at(dir.path().join("questions"));
5693 let mut t = task("delete me");
5694 q.put(&mut t).unwrap();
5695 let removed = q.remove(t.short(), false, &questions).unwrap();
5696 assert_eq!(removed.id, t.id, "a prefix resolves before deleting");
5697 assert!(removed.released.is_empty() && removed.still_blocked.is_empty());
5698 assert!(q.list().is_empty());
5699 assert!(
5700 q.remove(&t.id, false, &questions).is_err(),
5701 "removing twice is an error"
5702 );
5703 }
5704
5705 #[test]
5706 fn removing_a_task_takes_its_stale_lock_with_it() {
5707 let (dir, q) = queue();
5708 let questions = Questions::at(dir.path().join("questions"));
5709 let mut t = task("interrupted");
5710 q.put(&mut t).unwrap();
5711
5712 let claim = q.claim(&t.id).unwrap();
5715 std::mem::forget(claim);
5716 assert!(
5717 q.claim(&t.id).is_err(),
5718 "the orphaned lock is what makes the task look claimed"
5719 );
5720
5721 let err = q.remove(&t.id, true, &questions).unwrap_err().to_string();
5723 assert!(err.contains("live daemon"), "{err}");
5724 assert!(q.get(&t.id).is_ok(), "a refused delete keeps the task");
5725
5726 q.remove(&t.id, false, &questions).unwrap();
5728 assert!(q.list().is_empty());
5729 let mut again = task("interrupted");
5730 again.id = t.id.clone();
5731 q.put(&mut again).unwrap();
5732 assert!(
5733 q.claim(&t.id).is_ok(),
5734 "a task that comes back must be claimable, which a left-behind lock would prevent"
5735 );
5736 }
5737
5738 fn notices_of(dir: &Path) -> Vec<crate::notices::Notice> {
5739 crate::notices::Notices::at(dir.join("notifications")).list()
5740 }
5741
5742 #[test]
5743 fn removing_a_sole_dependency_releases_the_dependent_without_a_hold() {
5744 let (dir, q) = queue();
5745 let questions = Questions::at(dir.path().join("questions"));
5746 let mut dep = task("dependency");
5747 q.put(&mut dep).unwrap();
5748 let mut blocked = task("waiting");
5749 blocked.block(vec![dep.id.clone()], Some("waits".to_owned()));
5750 q.put(&mut blocked).unwrap();
5751
5752 let removed = q.remove(&dep.id, false, &questions).unwrap();
5753 assert_eq!(removed.released, [blocked.id.clone()]);
5754 assert!(removed.still_blocked.is_empty());
5755
5756 let after = q.get(&blocked.id).unwrap();
5757 assert_eq!(after.status, TaskStatus::Queued);
5758 assert!(after.blocked_by.is_empty());
5759 assert!(after.block_reason.is_none());
5760 let notes = notices_of(dir.path());
5761 assert_eq!(notes.len(), 1, "{notes:?}");
5762 assert_eq!(notes[0].severity, crate::notices::Severity::Info);
5763 assert_eq!(
5764 notes[0].link,
5765 Some(crate::notices::Link::Task {
5766 id: blocked.id.clone(),
5767 })
5768 );
5769 }
5770
5771 #[test]
5772 fn removing_one_of_two_dependencies_keeps_the_other() {
5773 let (dir, q) = queue();
5774 let questions = Questions::at(dir.path().join("questions"));
5775 let mut dep = task("dependency");
5776 q.put(&mut dep).unwrap();
5777 let mut other = task("other");
5778 q.put(&mut other).unwrap();
5779 let mut blocked = task("waiting");
5780 blocked.block(
5781 vec![dep.id.clone(), other.id.clone()],
5782 Some("waits on both".to_owned()),
5783 );
5784 q.put(&mut blocked).unwrap();
5785
5786 let removed = q.remove(&dep.id, false, &questions).unwrap();
5787 assert!(removed.released.is_empty());
5788 assert_eq!(removed.still_blocked, [blocked.id.clone()]);
5789
5790 let after = q.get(&blocked.id).unwrap();
5791 assert_eq!(after.status, TaskStatus::Blocked);
5792 assert_eq!(after.blocked_by, [other.id.clone()]);
5793 assert!(missing_blockers(&q, &questions, &after.blocked_by).is_empty());
5796 }
5797
5798 #[test]
5799 fn a_dependency_deleted_before_its_dependents_were_rewritten_is_released_later() {
5800 let (dir, q) = queue();
5801 let questions = Questions::at(dir.path().join("questions"));
5802 let mut dep = task("dependency");
5803 q.put(&mut dep).unwrap();
5804 let mut blocked = task("waiting");
5805 blocked.block(vec![dep.id.clone()], None);
5806 q.put(&mut blocked).unwrap();
5807
5808 let claim = q.claim(&blocked.id).unwrap();
5810 let removed = q.remove(&dep.id, false, &questions).unwrap();
5811 assert!(removed.released.is_empty());
5812 drop(claim);
5813
5814 let mut task = q.get(&blocked.id).unwrap();
5815 assert_eq!(task.status, TaskStatus::Blocked);
5816 assert!(missing_blockers(&q, &questions, &task.blocked_by).is_empty());
5817 assert_eq!(
5818 q.apply_deleted_blockers(&mut task, &questions),
5819 [dep.id.clone()]
5820 );
5821 assert_eq!(task.status, TaskStatus::Queued);
5822 }
5823
5824 #[test]
5825 fn dependency_resolution_short_deleted_reference_releases_only_its_waiters() {
5826 let (dir, q) = queue();
5827 let questions = Questions::at(dir.path().join("questions"));
5828 let mut dep = task("dependency");
5829 dep.id = "20261013-193611-ca5b".into();
5830 q.put(&mut dep).unwrap();
5831 let mut waiting = task("waiting");
5832 waiting.block(vec!["ca5b".into()], None);
5833 q.put(&mut waiting).unwrap();
5834 q.remove(&dep.id, false, &questions).unwrap();
5835 assert_eq!(q.get(&waiting.id).unwrap().status, TaskStatus::Queued);
5836 assert_eq!(
5837 dependency(&q, &questions, "ca5b"),
5838 Dependency::Deleted(dep.id)
5839 );
5840 }
5841
5842 #[test]
5843 fn dependency_resolution_preserves_cross_store_ambiguity_and_exact_ids() {
5844 let (dir, queue) = queue();
5845 let questions = Questions::at(dir.path().join("questions"));
5846 let mut dep = task("dependency");
5847 dep.id = "20261013-193611-ca5b".into();
5848 queue.put(&mut dep).unwrap();
5849 std::fs::create_dir_all(questions.root()).unwrap();
5850 let question_id = "20261014-193611-ca5b";
5851 std::fs::write(questions.path_of(question_id), "unreadable question").unwrap();
5852 assert_eq!(questions.resolve_id("ca5b").unwrap(), question_id);
5853 assert_eq!(
5854 dependency(&queue, &questions, "ca5b"),
5855 Dependency::Ambiguous
5856 );
5857 assert_eq!(
5858 dependency(&queue, &questions, &dep.id),
5859 Dependency::Task(dep.id)
5860 );
5861 assert_eq!(
5862 dependency(&queue, &questions, question_id),
5863 Dependency::Question(question_id.into())
5864 );
5865 assert_eq!(
5866 dependency(&queue, &questions, "missing"),
5867 Dependency::Missing
5868 );
5869 }
5870
5871 #[test]
5872 fn dependency_resolution_directory_errors_are_unknown_not_missing() {
5873 let dir = tempfile::tempdir().unwrap();
5874 let q = Queue::at(dir.path().join("not-a-directory"));
5875 std::fs::write(q.root(), "file").unwrap();
5876 let questions = Questions::at(dir.path().join("questions"));
5877 assert_eq!(dependency(&q, &questions, "ca5b"), Dependency::Unknown);
5878 assert!(missing_blockers(&q, &questions, &["ca5b".into()]).is_empty());
5879 }
5880
5881 #[test]
5882 fn a_dependency_without_a_tombstone_is_still_missing() {
5883 let (dir, q) = queue();
5884 let questions = Questions::at(dir.path().join("questions"));
5885 let mut dep = task("dependency");
5886 q.put(&mut dep).unwrap();
5887 std::fs::remove_file(q.path_of(&dep.id)).unwrap();
5888 assert_eq!(
5889 missing_blockers(&q, &questions, std::slice::from_ref(&dep.id)),
5890 [dep.id.clone()]
5891 );
5892 assert!(deleted_blockers(&q, &questions, std::slice::from_ref(&dep.id)).is_empty());
5893 }
5894
5895 #[test]
5896 fn a_held_dependent_is_left_alone_by_a_dependency_deletion() {
5897 let mut t = task("held");
5898 t.hold_machine(Some("because".to_owned()));
5899 t.blocked_by = vec!["gone".to_owned()];
5900 assert!(!t.dependency_deleted("gone"));
5901 assert_eq!(t.status, TaskStatus::Held);
5902 }
5903
5904 #[test]
5905 fn a_failed_record_removal_takes_the_tombstone_back() {
5906 let (_dir, q) = queue();
5907 let mut t = task("stays");
5908 q.put(&mut t).unwrap();
5909 q.write_tombstone(&t.id).unwrap();
5910 let err = q.remove_record_with_attachments(&t.id, |_| Err(std::io::Error::other("nope")));
5911 assert!(err.is_err());
5912 assert!(!q.was_deleted(&t.id));
5915 }
5916
5917 fn source_file(dir: &Path, name: &str, body: &str) -> PathBuf {
5918 let p = dir.join(name);
5919 std::fs::write(&p, body).unwrap();
5920 p
5921 }
5922
5923 #[test]
5924 fn an_attachment_copy_survives_deleting_its_source() {
5925 let (dir, q) = queue();
5926 let src = source_file(dir.path(), "shot.png", "pixels");
5927 let mut t = task("with a picture");
5928 let names = q.attach(&mut t, std::slice::from_ref(&src)).unwrap();
5929 q.put(&mut t).unwrap();
5930 std::fs::remove_file(&src).unwrap();
5931 assert_eq!(names, ["shot.png"]);
5932 let loaded = q.get(&t.id).unwrap();
5933 let paths = q.attachment_paths(&loaded);
5934 assert_eq!(paths.len(), 1);
5935 assert_eq!(std::fs::read_to_string(&paths[0]).unwrap(), "pixels");
5936 }
5937
5938 #[test]
5939 fn attachment_names_that_could_traverse_or_are_odd_are_refused() {
5940 let (dir, q) = queue();
5941 let mut t = task("bad names");
5942 for name in ["a..b.png", ".hidden", "with space.png", "-x.png"] {
5943 let src = source_file(dir.path(), name, "x");
5944 assert!(
5945 q.attach(&mut t, &[src]).is_err(),
5946 "`{name}` must be refused"
5947 );
5948 }
5949 assert!(!crate::ask::valid_asset_name("C:foo.png"));
5953 #[cfg(not(windows))]
5954 {
5955 let src = source_file(dir.path(), "C:foo.png", "x");
5956 assert!(q.attach(&mut t, &[src]).is_err());
5957 }
5958 let long = format!("{}.png", "a".repeat(70));
5959 let src = source_file(dir.path(), &long, "x");
5960 assert!(q.attach(&mut t, &[src]).is_err());
5961 assert!(t.attachments.is_empty());
5962 assert!(!q.attachments_dir(&t.id).exists());
5963 }
5964
5965 #[test]
5966 fn a_taken_attachment_name_is_numbered_not_overwritten() {
5967 let (dir, q) = queue();
5968 let a = source_file(dir.path(), "shot.png", "one");
5969 let sub = dir.path().join("other");
5970 std::fs::create_dir_all(&sub).unwrap();
5971 let b = source_file(&sub, "shot.png", "two");
5972 let mut t = task("collision");
5973 q.attach(&mut t, &[a]).unwrap();
5974 q.attach(&mut t, &[b]).unwrap();
5975 assert_eq!(t.attachments, ["shot.png", "shot-2.png"]);
5976 let paths = q.attachment_paths(&t);
5977 assert_eq!(std::fs::read_to_string(&paths[0]).unwrap(), "one");
5978 assert_eq!(std::fs::read_to_string(&paths[1]).unwrap(), "two");
5979 }
5980
5981 #[test]
5982 fn a_renumbered_name_stays_inside_the_length_bound() {
5983 let (dir, q) = queue();
5984 let name = format!("{}.png", "a".repeat(60));
5985 assert_eq!(name.len(), 64);
5986 let a = source_file(dir.path(), &name, "one");
5987 let sub = dir.path().join("other");
5988 std::fs::create_dir_all(&sub).unwrap();
5989 let b = source_file(&sub, &name, "two");
5990 let mut t = task("long");
5991 q.attach(&mut t, &[a, b]).unwrap();
5992 assert_eq!(t.attachments.len(), 2);
5993 assert!(
5994 t.attachments
5995 .iter()
5996 .all(|n| crate::ask::valid_asset_name(n))
5997 );
5998 assert!(t.attachments[1].ends_with("-2.png"));
5999 }
6000
6001 #[test]
6002 fn a_failed_attach_keeps_existing_attachments_and_leaves_no_partial_copy() {
6003 let (dir, q) = queue();
6004 let good = source_file(dir.path(), "good.png", "ok");
6005 let mut t = task("partial");
6006 q.attach(&mut t, &[good]).unwrap();
6007 let more = source_file(dir.path(), "more.png", "ok");
6008 let missing = dir.path().join("missing.png");
6009 assert!(q.attach(&mut t, &[more, missing]).is_err());
6010 assert_eq!(t.attachments, ["good.png"]);
6011 let on_disk: Vec<_> = std::fs::read_dir(q.attachments_dir(&t.id))
6012 .unwrap()
6013 .flatten()
6014 .collect();
6015 assert_eq!(on_disk.len(), 1);
6016 }
6017
6018 fn block_put(q: &Queue, t: &Task) -> PathBuf {
6020 let tmp = q.path_of(&t.id).with_extension("json.tmp");
6021 std::fs::create_dir_all(&tmp).unwrap();
6022 tmp
6023 }
6024
6025 #[test]
6026 fn a_failed_put_leaves_no_new_attachment_directory() {
6027 let (dir, q) = queue();
6028 let mut t = task("fresh");
6029 let tmp = block_put(&q, &t);
6030 let src = source_file(dir.path(), "shot.png", "x");
6031 assert!(q.attach_and_put(&mut t, &[src]).is_err());
6032 assert!(t.attachments.is_empty());
6033 assert!(!q.attachments_dir(&t.id).exists());
6034 assert!(!q.path_of(&t.id).exists());
6035 std::fs::remove_dir(tmp).unwrap();
6036 }
6037
6038 #[test]
6039 fn a_failed_put_removes_only_the_copy_it_just_made() {
6040 let (dir, q) = queue();
6041 let mut t = task("edited");
6042 let first = source_file(dir.path(), "first.png", "1");
6043 q.attach_and_put(&mut t, &[first]).unwrap();
6044 block_put(&q, &t);
6045 let second = source_file(dir.path(), "second.png", "2");
6046 assert!(q.attach_and_put(&mut t, &[second]).is_err());
6047 assert_eq!(t.attachments, ["first.png"]);
6048 let on_disk: Vec<_> = std::fs::read_dir(q.attachments_dir(&t.id))
6049 .unwrap()
6050 .flatten()
6051 .map(|e| e.file_name().to_string_lossy().into_owned())
6052 .collect();
6053 assert_eq!(on_disk, ["first.png"]);
6054 assert_eq!(q.get(&t.id).unwrap().attachments, ["first.png"]);
6055 }
6056
6057 #[test]
6058 fn a_leftover_removing_directory_is_swept_by_the_next_removal() {
6059 let (dir, q) = queue();
6060 let questions = Questions::at(dir.path().join("questions"));
6061 let gone = task("gone");
6062 let mut other = task("other");
6063 let mut live = task("live");
6064 q.put(&mut other).unwrap();
6065 q.put(&mut live).unwrap();
6066 let orphan = q.root.join(format!("{}.attachments.removing", gone.id));
6069 std::fs::create_dir_all(&orphan).unwrap();
6070 std::fs::write(orphan.join("shot.png"), "x").unwrap();
6071 let busy = q.root.join(format!("{}.attachments.removing", live.id));
6074 std::fs::create_dir_all(&busy).unwrap();
6075
6076 q.remove(&other.id, false, &questions).unwrap();
6077 assert!(!orphan.exists(), "an orphan is swept");
6078 assert!(busy.exists(), "a removal in progress is left alone");
6079 }
6080
6081 #[test]
6082 fn a_blocked_aside_rename_fails_the_removal_and_loses_nothing() {
6083 let (dir, q) = queue();
6084 let questions = Questions::at(dir.path().join("questions"));
6085 let mut t = task("stuck");
6086 let src = source_file(dir.path(), "shot.png", "x");
6087 q.attach_and_put(&mut t, &[src]).unwrap();
6088 let aside = q.root.join(format!("{}.attachments.removing", t.id));
6091 std::fs::create_dir_all(&aside).unwrap();
6092 std::fs::write(aside.join("old.png"), "o").unwrap();
6093 assert!(q.remove(&t.id, false, &questions).is_err());
6094 assert!(q.path_of(&t.id).exists());
6095 assert!(q.attachments_dir(&t.id).join("shot.png").is_file());
6096 }
6097
6098 #[test]
6099 fn a_failed_record_removal_puts_the_attachments_back() {
6100 let (dir, q) = queue();
6101 let mut t = task("rollback");
6102 let src = source_file(dir.path(), "shot.png", "x");
6103 q.attach_and_put(&mut t, &[src]).unwrap();
6104 let err = q
6105 .remove_record_with_attachments(&t.id, |_| {
6106 Err(std::io::Error::other("injected failure"))
6107 })
6108 .unwrap_err();
6109 assert!(format!("{err:#}").contains("injected failure"));
6110 assert!(q.path_of(&t.id).exists());
6111 assert!(q.attachments_dir(&t.id).join("shot.png").is_file());
6112 assert!(
6113 !q.root
6114 .join(format!("{}.attachments.removing", t.id))
6115 .exists()
6116 );
6117 }
6118
6119 #[test]
6120 fn editing_a_task_keeps_its_attachments() {
6121 let (dir, q) = queue();
6122 let src = source_file(dir.path(), "shot.png", "x");
6123 let mut t = task("editable");
6124 q.attach(&mut t, &[src]).unwrap();
6125 t.edit("new".to_owned(), "new text".to_owned()).unwrap();
6126 q.put(&mut t).unwrap();
6127 assert_eq!(q.get(&t.id).unwrap().attachments, ["shot.png"]);
6128 }
6129
6130 #[test]
6131 fn removing_a_task_deletes_its_attachments() {
6132 let (dir, q) = queue();
6133 let questions = Questions::at(dir.path().join("questions"));
6134 let src = source_file(dir.path(), "shot.png", "x");
6135 let mut t = task("doomed");
6136 q.attach(&mut t, &[src]).unwrap();
6137 q.put(&mut t).unwrap();
6138 assert!(q.attachments_dir(&t.id).is_dir());
6139 q.remove(&t.id, false, &questions).unwrap();
6140 assert!(!q.attachments_dir(&t.id).exists());
6141 assert!(q.list().is_empty());
6142 }
6143
6144 #[test]
6145 fn a_task_written_before_attachments_still_reads() {
6146 let (_dir, q) = queue();
6147 let mut t = task("old");
6148 q.put(&mut t).unwrap();
6149 let path = q.path_of(&t.id);
6150 let mut v: serde_json::Value =
6151 serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
6152 v.as_object_mut().unwrap().remove("attachments");
6153 std::fs::write(&path, v.to_string()).unwrap();
6154 assert!(q.get(&t.id).unwrap().attachments.is_empty());
6155 }
6156
6157 #[test]
6158 fn attachment_paths_are_absolute_even_when_the_root_is_relative() {
6159 let q = Queue::at(PathBuf::from("relative-queue"));
6160 let mut t = task("rel");
6161 t.attachments.push("shot.png".to_owned());
6162 let paths = q.attachment_paths(&t);
6163 assert!(paths[0].is_absolute(), "{}", paths[0].display());
6164 assert!(paths[0].ends_with(format!("{}.attachments/shot.png", t.id)));
6165 }
6166
6167 fn upgrade_parked(id: &str, started: &str) -> Task {
6168 let mut t = task(id);
6169 t.id = id.into();
6170 t.start(format!("run-{id}"));
6171 t.park("upgrade");
6172 t.record_pass_at(
6173 &format!("run-{id}"),
6174 0,
6175 Some(started.parse().unwrap()),
6176 1,
6177 Some(crate::run::ParkCause::Upgrade {
6178 from: "old".into(),
6179 to: None,
6180 }),
6181 );
6182 t
6183 }
6184
6185 #[test]
6186 fn upgrade_resume_order_follows_dispatch_claim_not_graph_start() {
6187 let stamp = |id: &str, dispatched: &str, started: &str| {
6189 let mut t = task(id);
6190 t.id = id.into();
6191 t.start(format!("run-{id}"));
6192 t.park("upgrade");
6193 t.dispatched_at = Some(dispatched.parse().unwrap());
6194 t.record_pass_at(
6195 &format!("run-{id}"),
6196 0,
6197 Some(started.parse().unwrap()),
6198 1,
6199 Some(crate::run::ParkCause::Upgrade {
6200 from: "old".into(),
6201 to: None,
6202 }),
6203 );
6204 t
6205 };
6206 let a = stamp("a", "2026-10-22T00:00:01Z", "2026-10-22T00:00:09Z");
6207 let b = stamp("b", "2026-10-22T00:00:02Z", "2026-10-22T00:00:03Z");
6208 assert!(dispatch_order(&a, &b).is_lt());
6209 }
6210
6211 #[test]
6212 fn upgrade_resume_order_survives_queue_reload_and_reversed_settlement() {
6213 let (_dir, q) = queue();
6214 let mut later = upgrade_parked("later", "2026-10-22T00:00:02Z");
6215 let mut earlier = upgrade_parked("earlier", "2026-10-22T00:00:01Z");
6216 earlier.priority = -10;
6217 let mut fresh = task("fresh");
6218 fresh.id = "newer".into();
6219 fresh.priority = 100;
6220 for t in [&mut fresh, &mut later, &mut earlier] {
6221 q.put(t).unwrap();
6222 }
6223 let reloaded = Queue::at(q.root().to_owned());
6224 let mut tasks = reloaded.list();
6225 tasks.sort_unstable_by(dispatch_order);
6226 assert_eq!(
6227 tasks.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
6228 vec!["earlier", "later", "newer"]
6229 );
6230 assert_eq!(reloaded.next_runnable().unwrap().id, "earlier");
6231 assert_eq!(reloaded.get("earlier").unwrap().attempts, 0);
6232 }
6233
6234 #[test]
6235 fn upgrade_resume_legacy_order_uses_settlement_and_id() {
6236 let mut a = upgrade_parked("a", "2026-10-22T00:00:02Z");
6237 let mut b = upgrade_parked("b", "2026-10-22T00:00:01Z");
6238 for t in [&mut a, &mut b] {
6239 let mut value = serde_json::to_value(&*t).unwrap();
6240 value["passes"][0]
6241 .as_object_mut()
6242 .unwrap()
6243 .remove("started_at");
6244 *t = serde_json::from_value(value).unwrap();
6245 }
6246 assert!(dispatch_order(&a, &b).is_lt());
6247 b.passes[0].settled_at = a.passes[0].settled_at;
6248 assert!(dispatch_order(&a, &b).is_lt());
6249 }
6250
6251 #[test]
6252 fn upgrade_resume_key_excludes_other_parks_and_explicit_task_changes() {
6253 let original = upgrade_parked("a", "2026-10-22T00:00:01Z");
6254 assert!(original.upgrade_resume_key().is_some());
6255 for cause in [
6256 crate::run::ParkCause::Operator,
6257 crate::run::ParkCause::Question,
6258 crate::run::ParkCause::Interrupt {
6259 reason: "interrupt".into(),
6260 },
6261 crate::run::ParkCause::Unspecified,
6262 ] {
6263 let mut t = original.clone();
6264 t.passes[0].parked = Some(cause);
6265 assert!(t.upgrade_resume_key().is_none());
6266 let mut fresh = task("fresh");
6267 fresh.priority = 1;
6268 assert!(dispatch_order(&fresh, &t).is_lt());
6269 }
6270 let mut t = original.clone();
6271 t.release();
6272 assert!(t.upgrade_resume_key().is_none());
6273 t.edit("edited".into(), "new instruction".into()).unwrap();
6274 assert!(t.upgrade_resume_key().is_none());
6275 let mut t = original.clone();
6276 t.requeue();
6277 t.status = TaskStatus::Parked;
6278 assert!(t.upgrade_resume_key().is_none());
6279 let mut t = original.clone();
6280 t.start("different-run".into());
6281 t.park("no upgrade");
6282 assert!(t.upgrade_resume_key().is_none());
6283 }
6284
6285 #[test]
6286 fn explicitly_resumed_older_run_becomes_current_without_duplicate_history() {
6287 let dir = tempfile::tempdir().unwrap();
6288 let q = Queue::at(dir.path().join("queue"));
6289 let mut t = task("resume");
6290 t.start("A".into());
6291 t.record_pass("A", 0, 1, None);
6292 t.start("B".into());
6293 q.put(&mut t).unwrap();
6294 assert_eq!(t.runs, vec!["A", "B"]);
6295 t.start("A".into());
6296 t.record_pass("A", 1, 3, None);
6297 q.put(&mut t).unwrap();
6298 let saved = q.get(&t.id).unwrap();
6299 assert_eq!(saved.runs, vec!["B", "A"]);
6300 assert_eq!(saved.runs.last().map(String::as_str), Some("A"));
6301 assert_eq!(saved.attempts, 3);
6302 assert_eq!(saved.passes.len(), 2);
6303 assert_eq!(saved.passes[0].run, "A");
6304 assert_eq!(saved.passes[1].run, "A");
6305 }
6306
6307 #[test]
6308 fn repeated_start_records_one_run_and_separate_passes() {
6309 let mut t = task("resume");
6310 t.start("same-run".into());
6311 t.record_pass("same-run", 0, 1, None);
6312 t.start("same-run".into());
6313 t.record_pass("same-run", 1, 2, None);
6314 assert_eq!(t.runs, vec!["same-run"]);
6315 assert_eq!(t.attempts, 2);
6316 assert_eq!(t.passes.len(), 2);
6317 }
6318
6319 #[test]
6320 fn link_run_adds_a_run_once_and_touches_nothing_else() {
6321 let dir = tempfile::tempdir().unwrap();
6322 let queue = Queue::at(dir.path().join("queue"));
6323 let mut t = Task::new(
6324 "t".to_owned(),
6325 "do it".to_owned(),
6326 PathBuf::from("."),
6327 Source::Human,
6328 );
6329 queue.put(&mut t).unwrap();
6330 let before = queue.get(&t.id).unwrap();
6331
6332 let linked = queue.link_run(&t.id[..4], "20260930-092817-ec34").unwrap();
6333 assert_eq!(linked.runs, vec!["20260930-092817-ec34".to_owned()]);
6334 assert_eq!(linked.status, before.status);
6335 assert_eq!(linked.attempts, before.attempts);
6336 assert_eq!(linked.interrupt, before.interrupt);
6337
6338 let again = queue.link_run(&t.id, "20260930-092817-ec34").unwrap();
6339 assert_eq!(again.runs.len(), 1, "linking twice must not duplicate");
6340 assert_eq!(queue.get(&t.id).unwrap().runs.len(), 1);
6341 assert!(queue.link_run("no-such-task", "r").is_err());
6342 }
6343
6344 #[test]
6345 fn put_keeps_a_run_linked_after_the_writer_took_its_snapshot() {
6346 let dir = tempfile::tempdir().unwrap();
6347 let queue = Queue::at(dir.path().join("queue"));
6348 let mut t = Task::new(
6349 "t".to_owned(),
6350 "do it".to_owned(),
6351 PathBuf::from("."),
6352 Source::Human,
6353 );
6354 queue.put(&mut t).unwrap();
6355 let mut snapshot = queue.get(&t.id).unwrap();
6357 queue.link_run(&t.id, "20260930-092817-ec34").unwrap();
6358
6359 snapshot.start("20260930-000000-aaaa".to_owned());
6360 queue.put(&mut snapshot).unwrap();
6361
6362 let stored = queue.get(&t.id).unwrap();
6363 assert!(stored.runs.contains(&"20260930-092817-ec34".to_owned()));
6364 assert!(stored.runs.contains(&"20260930-000000-aaaa".to_owned()));
6365 assert_eq!(stored.attempts, 1);
6366 }
6367
6368 #[test]
6369 fn concurrent_links_and_daemon_saves_lose_nothing() {
6370 let dir = tempfile::tempdir().unwrap();
6371 let queue = Queue::at(dir.path().join("queue"));
6372 let mut t = Task::new(
6373 "t".to_owned(),
6374 "do it".to_owned(),
6375 PathBuf::from("."),
6376 Source::Human,
6377 );
6378 queue.put(&mut t).unwrap();
6379 let id = t.id.clone();
6380
6381 let linkers: Vec<_> = (0..4)
6382 .map(|n| {
6383 let (queue, id) = (queue.clone(), id.clone());
6384 std::thread::spawn(move || {
6385 for k in 0..10 {
6386 queue
6387 .link_run(&id, &format!("20260930-00000{n}-l{k:03}"))
6388 .unwrap();
6389 }
6390 })
6391 })
6392 .collect();
6393 let mut mine = queue.get(&id).unwrap();
6396 for k in 0..10 {
6397 mine.start(format!("20260930-000009-d{k:03}"));
6398 queue.put(&mut mine).unwrap();
6399 }
6400 for l in linkers {
6401 l.join().unwrap();
6402 }
6403
6404 let stored = queue.get(&id).unwrap();
6405 assert_eq!(stored.runs.len(), 50, "{:?}", stored.runs);
6406 assert_eq!(
6407 stored.attempts, 10,
6408 "linking never rewinds the daemon's work"
6409 );
6410 }
6411
6412 fn age_lock(path: &Path) {
6413 let f = std::fs::OpenOptions::new().write(true).open(path).unwrap();
6414 f.set_modified(std::time::SystemTime::now() - std::time::Duration::from_secs(60))
6415 .unwrap();
6416 }
6417
6418 #[test]
6419 fn concurrent_stale_takeover_yields_one_holder() {
6420 use std::sync::atomic::{AtomicUsize, Ordering};
6421 use std::sync::{Arc, Barrier};
6422 for _ in 0..5 {
6423 let dir = tempfile::tempdir().unwrap();
6424 let q = Queue::at(dir.path().to_path_buf());
6425 let lock = dir.path().join("t.write-lock");
6426 std::fs::write(&lock, "dead-0000").unwrap();
6427 age_lock(&lock);
6428 let n = 6;
6429 let barrier = Arc::new(Barrier::new(n));
6430 let (now, max) = (Arc::new(AtomicUsize::new(0)), Arc::new(AtomicUsize::new(0)));
6431 let handles: Vec<_> = (0..n)
6432 .map(|_| {
6433 let (q, b, now, max) = (q.clone(), barrier.clone(), now.clone(), max.clone());
6434 std::thread::spawn(move || {
6435 b.wait();
6436 let g = q.lock_task("t").unwrap();
6437 let held = now.fetch_add(1, Ordering::SeqCst) + 1;
6438 max.fetch_max(held, Ordering::SeqCst);
6439 std::thread::sleep(std::time::Duration::from_millis(20));
6440 now.fetch_sub(1, Ordering::SeqCst);
6441 drop(g);
6442 })
6443 })
6444 .collect();
6445 for h in handles {
6446 h.join().unwrap();
6447 }
6448 assert_eq!(max.load(Ordering::SeqCst), 1);
6449 assert!(!lock.exists());
6450 }
6451 }
6452
6453 #[test]
6454 fn dropping_a_replaced_lock_leaves_the_new_holders_token() {
6455 let dir = tempfile::tempdir().unwrap();
6456 let q = Queue::at(dir.path().to_path_buf());
6457 let lock = dir.path().join("t.write-lock");
6458 let a = q.lock_task("t").unwrap();
6459 let replacement = owner_token();
6462 std::fs::write(&lock, &replacement).unwrap();
6463 drop(a);
6464 assert_eq!(std::fs::read_to_string(&lock).unwrap(), replacement);
6465 }
6466
6467 #[test]
6468 fn aged_live_task_lock_excludes_updates_until_retirement_releases_it() {
6469 let dir = tempfile::tempdir().unwrap();
6470 let q = Queue::at(dir.path().to_path_buf());
6471 let held = q.lock_task("t").unwrap();
6472 let path = dir.path().join("t.write-lock");
6473 age_lock(&path);
6474 assert!(!break_stale(&path, &held.token));
6475 let (started_tx, started_rx) = std::sync::mpsc::channel();
6476 let (acquired_tx, acquired_rx) = std::sync::mpsc::channel();
6477 let updater = std::thread::spawn(move || {
6478 started_tx.send(()).unwrap();
6479 let _write = q.lock_task("t").unwrap();
6480 acquired_tx.send(()).unwrap();
6481 });
6482 started_rx.recv().unwrap();
6483 assert!(
6484 acquired_rx
6485 .recv_timeout(std::time::Duration::from_millis(100))
6486 .is_err()
6487 );
6488 assert_eq!(std::fs::read_to_string(&path).unwrap(), held.token);
6489 drop(held);
6490 acquired_rx
6491 .recv_timeout(std::time::Duration::from_secs(2))
6492 .unwrap();
6493 updater.join().unwrap();
6494 assert!(!path.exists());
6495 }
6496
6497 #[test]
6498 fn break_stale_leaves_a_lock_that_replaced_the_one_judged() {
6499 let dir = tempfile::tempdir().unwrap();
6500 let lock = dir.path().join("t.write-lock");
6501 std::fs::write(&lock, "new-token").unwrap();
6502 assert!(!break_stale(&lock, "old-token"));
6503 assert_eq!(std::fs::read_to_string(&lock).unwrap(), "new-token");
6504 assert!(!break_stale(&lock, "new-token"));
6506 assert!(lock.exists());
6507 age_lock(&lock);
6508 assert!(break_stale(&lock, "new-token"));
6509 assert!(!lock.exists());
6510 }
6511
6512 #[test]
6513 fn a_stale_break_marker_is_recovered_and_a_fresh_one_is_respected() {
6514 let dir = tempfile::tempdir().unwrap();
6515 let lock = dir.path().join("t.write-lock");
6516 std::fs::write(&lock, "dead-1").unwrap();
6517 age_lock(&lock);
6518 let marker = break_marker(&lock, "dead-1");
6519 std::fs::write(&marker, "crashed-remover").unwrap();
6520 assert!(!break_stale(&lock, "dead-1"));
6522 assert!(lock.exists());
6523 age_lock(&marker);
6525 assert!(break_stale(&lock, "dead-1"));
6526 assert!(!lock.exists());
6527 assert!(!marker.exists());
6528 }
6529
6530 fn chat_task() -> Task {
6531 Task::new(
6532 "t".to_owned(),
6533 "do t".to_owned(),
6534 PathBuf::from("."),
6535 Source::Agent {
6536 run: "20260902-000000-beef".to_owned(),
6537 node: CHAT_NODE.to_owned(),
6538 },
6539 )
6540 }
6541
6542 #[test]
6543 fn a_blocked_hold_keeps_its_anchor_but_a_new_run_starts_a_new_hold() {
6544 let mut t = chat_task();
6545 t.hold_machine(Some("waiting".into()));
6546 let old: Timestamp = "2020-01-01T00:00:00Z".parse().unwrap();
6547 t.held_at = Some(old);
6548 t.block(vec!["decision".into()], None);
6549 t.hold_machine(Some("same waiting decision".into()));
6550 assert_eq!(t.held_at, Some(old));
6551 t.start("real-new-run".into());
6552 t.fail("new failure", 1);
6553 assert_ne!(
6554 t.held_at,
6555 Some(old),
6556 "old answers cannot approve a new hold"
6557 );
6558 }
6559
6560 #[test]
6561 fn legacy_delivery_survives_upgrade_and_a_no_progress_run_link() {
6562 let (_dir, queue) = queue();
6563 let mut t = chat_task();
6564 t.start("old-run".into());
6565 t.hold_machine(Some("operator is considering recovery".into()));
6566 t.chat_notice = Some(ChatNotice {
6567 key: format!("held#{}", t.held_at.unwrap()),
6568 at: Timestamp::now(),
6569 outcome: ChatNoticeOutcome::Posted,
6570 });
6571 let mut raw = serde_json::to_value(&t).unwrap();
6572 raw.as_object_mut().unwrap().remove("chat_notices");
6573 raw.as_object_mut().unwrap().remove("hold_notice_cause");
6574 std::fs::create_dir_all(queue.path_of(&t.id).parent().unwrap()).unwrap();
6575 std::fs::write(queue.path_of(&t.id), serde_json::to_string(&raw).unwrap()).unwrap();
6576 assert_eq!(queue.get(&t.id).unwrap().chat_notice_due(), None);
6577 queue
6578 .modify(&t.id, |task| {
6579 task.requeue();
6580 task.link_run("unprepared-run");
6581 task.startup_notice_cause("startup-source");
6582 task.fail("same unresolved preflight", 0);
6583 true
6584 })
6585 .unwrap();
6586 assert_eq!(queue.get(&t.id).unwrap().chat_notice_due(), None);
6587 queue
6588 .modify(&t.id, |task| {
6589 task.succeed();
6590 true
6591 })
6592 .unwrap();
6593 assert_eq!(
6594 queue.get(&t.id).unwrap().chat_notice_due().as_deref(),
6595 Some("done")
6596 );
6597 }
6598
6599 #[test]
6600 fn a_dependency_wait_does_not_change_when_released_and_blocked_again() {
6601 let mut t = chat_task();
6602 t.block(vec!["a".into(), "b".into()], Some("waiting".into()));
6603 let key = t.chat_notice_key().unwrap();
6604 t.chat_notices.push(key);
6605 t.release();
6606 t.block(
6607 vec!["b".into(), "a".into(), "a".into()],
6608 Some("still waiting on prerequisites".into()),
6609 );
6610 assert_eq!(t.chat_notice_due(), None);
6611 t.block(
6612 vec!["new-question".into()],
6613 Some("different decision".into()),
6614 );
6615 assert!(t.chat_notice_due().is_some());
6616 }
6617
6618 #[test]
6619 fn running_startup_failures_preserve_stage_and_report_distinct_blockers() {
6620 let mut t = chat_task();
6621 t.start("existing-run".into());
6622 t.fail("implementation failed", 1);
6623 let failed = t.chat_notice_key().unwrap();
6624 t.chat_notices.push(failed.clone());
6625 t.release_operator("test", None);
6626 t.start("existing-run".into());
6627 t.fail_startup("startup-source", "same unresolved recovery source", 1);
6628 assert_eq!(
6629 t.chat_notice_due(),
6630 None,
6631 "no-progress recovery stays quiet"
6632 );
6633 t.release_operator("test", None);
6634 t.start("existing-run".into());
6635 t.fail_startup("startup-attachments", "attachment missing", 1);
6636 let attachments = t.chat_notice_due().expect("new attachment blocker");
6637 assert_ne!(attachments, failed);
6638 assert_eq!(
6639 t.hold_notice_cause.as_ref().unwrap().stage,
6640 "startup-attachments"
6641 );
6642 t.chat_notices.push(attachments);
6643 t.release_operator("test", None);
6644 t.start("existing-run".into());
6645 t.fail_startup(
6646 "startup-attachments",
6647 "same missing attachment, reworded",
6648 1,
6649 );
6650 assert_eq!(
6651 t.chat_notice_due(),
6652 None,
6653 "same stage after attempt counter reset"
6654 );
6655 t.release_operator("test", None);
6656 t.start("existing-run".into());
6657 t.fail_startup("startup-config", "different preflight stage", 1);
6658 assert!(t.chat_notice_due().is_some());
6659 assert_eq!(
6660 t.hold_notice_cause.as_ref().unwrap().stage,
6661 "startup-config"
6662 );
6663 }
6664
6665 #[test]
6666 fn structured_causes_preserve_no_progress_retries_and_report_new_passes() {
6667 let mut t = chat_task();
6668 t.hold_machine(Some("startup source missing".into()));
6669 t.startup_notice_cause("startup-source");
6670 let first = t.chat_notice_key().unwrap();
6671 t.chat_notices.push(first.clone());
6672 t.release_operator("test", None);
6673 t.startup_notice_cause("startup-source");
6674 t.hold_machine(Some("same source cannot be read".into()));
6675 assert_eq!(t.chat_notice_due(), None);
6676 t.startup_notice_cause("startup-config");
6677 assert!(t.chat_notice_due().is_some(), "different startup stage");
6678 t.notice_cause("failed", Some("existing-run"), Some(0));
6679 let run_failure = t.chat_notice_key().unwrap();
6680 t.chat_notices.push(run_failure.clone());
6681 t.release_operator("test", None);
6682 t.startup_notice_cause("startup-source");
6683 t.hold_machine(Some("no new work happened".into()));
6684 assert_eq!(t.chat_notice_due(), None);
6685 t.notice_cause("failed", Some("existing-run"), Some(1));
6686 assert!(t.chat_notice_due().is_some(), "a real resumed pass failed");
6687 assert_ne!(t.chat_notice_key().unwrap(), run_failure);
6688 }
6689
6690 #[test]
6691 fn legacy_hold_baseline_does_not_replay_or_hide_new_failures_and_completion() {
6692 let mut t = chat_task();
6693 t.hold_machine(Some("still waiting".into()));
6694 t.chat_notice = Some(ChatNotice {
6695 key: "held#2026-10-14T00:00:00Z".into(),
6696 at: Timestamp::now(),
6697 outcome: ChatNoticeOutcome::Posted,
6698 });
6699 assert_eq!(t.chat_notice_due(), None, "old hold baseline");
6700 t.import_chat_notice();
6701 t.notice_cause("failed", Some("new-run"), Some(0));
6702 assert!(t.chat_notice_due().is_some(), "new producer evidence");
6703 t.succeed();
6704 assert_eq!(t.chat_notice_due().as_deref(), Some("done"));
6705 }
6706
6707 #[test]
6708 fn a_chat_notice_is_due_only_for_a_final_state_and_only_once() {
6709 let mut t = chat_task();
6710 assert_eq!(t.chat_notice_due(), None, "queued");
6711 t.start("r1".to_owned());
6712 assert_eq!(t.chat_notice_due(), None, "running");
6713 t.fail("boom", 3);
6714 assert_eq!(t.status, TaskStatus::Failed);
6715 assert_eq!(t.chat_notice_due(), None, "a retried failure is not final");
6716 t.start("r2".to_owned());
6717 t.park("upgrade");
6718 assert_eq!(t.chat_notice_due(), None, "parked");
6719 t.fail("boom", 1);
6720 assert_eq!(t.status, TaskStatus::Held);
6721 let key = t
6722 .chat_notice_due()
6723 .expect("held on the last attempt is final");
6724 t.chat_notice = Some(ChatNotice {
6725 key,
6726 at: Timestamp::now(),
6727 outcome: ChatNoticeOutcome::Posted,
6728 });
6729 assert_eq!(t.chat_notice_due(), None, "same hold, no second notice");
6730 t.release();
6731 assert_eq!(t.chat_notice_due(), None, "requeued after a release");
6732 t.start("r3".to_owned());
6733 t.succeed();
6734 assert!(t.chat_notice_due().is_some(), "done is a new final state");
6735 }
6736
6737 #[test]
6738 fn completed_chat_notices_keep_current_and_legacy_keys_after_requeue() {
6739 for key in ["done", "done#0", "done#1", "done#12"] {
6740 let mut t = chat_task();
6741 t.start("r1".to_owned());
6742 t.succeed();
6743 t.chat_notice = Some(ChatNotice {
6744 key: key.to_owned(),
6745 at: Timestamp::now(),
6746 outcome: ChatNoticeOutcome::Posted,
6747 });
6748 t.requeue();
6749 t.start("r2".to_owned());
6750 t.succeed();
6751 assert_eq!(t.chat_notice_key().as_deref(), Some("done"));
6752 assert_eq!(t.chat_notice_due(), None, "recorded key: {key}");
6753 }
6754 }
6755
6756 #[test]
6757 fn a_release_without_progress_keeps_the_unresolved_notice_cause() {
6758 let mut t = chat_task();
6759 t.hold_manual(Some("wait".to_owned()));
6760 let first = t.chat_notice_due().expect("held");
6761 t.chat_notice = Some(ChatNotice {
6762 key: first.clone(),
6763 at: Timestamp::now(),
6764 outcome: ChatNoticeOutcome::Posted,
6765 });
6766 t.hold_manual(Some("still waiting".to_owned()));
6767 assert_eq!(t.chat_notice_due(), None, "a re-hold keeps its start");
6768 t.release();
6769 std::thread::sleep(std::time::Duration::from_millis(5));
6770 t.hold_manual(None);
6771 assert_eq!(t.chat_notice_due(), None, "no progress, same cause");
6772 }
6773
6774 #[test]
6775 fn a_chat_notice_needs_a_chat_source_and_a_current_schema() {
6776 let mut human = task("h");
6777 human.succeed();
6778 assert_eq!(human.chat_notice_due(), None);
6779 let mut inherited = task("i");
6781 inherited.origin_chat = Some("20260902-000000-beef".to_owned());
6782 inherited.succeed();
6783 assert_eq!(inherited.chat_notice_due(), None);
6784 let mut old = chat_task();
6785 old.schema = 12;
6786 old.status = TaskStatus::Done;
6787 assert_eq!(old.chat_notice_due(), None, "history is not replayed");
6788 let mut live = chat_task();
6789 live.schema = 12;
6790 live.start("r1".to_owned());
6791 live.succeed();
6792 assert!(live.chat_notice_due().is_some(), "started by this build");
6793 let mut held = chat_task();
6794 held.schema = 12;
6795 held.hold_machine(Some("config".to_owned()));
6796 assert!(held.chat_notice_due().is_some(), "held before any start");
6797 }
6798
6799 #[test]
6800 fn a_stale_snapshot_does_not_rewind_a_recorded_chat_notice() {
6801 let tmp = tempfile::tempdir().expect("tempdir");
6802 let q = Queue::at(tmp.path().join("queue"));
6803 let mut t = chat_task();
6804 t.succeed();
6805 q.put(&mut t).expect("put");
6806 let mut stale = q.get(&t.id).expect("get");
6807 let key = t.chat_notice_due().expect("due");
6808 q.modify(&t.id, |x| {
6809 x.chat_notice = Some(ChatNotice {
6810 key: key.clone(),
6811 at: Timestamp::now(),
6812 outcome: ChatNoticeOutcome::Posted,
6813 });
6814 true
6815 })
6816 .expect("modify");
6817 q.put(&mut stale).expect("stale put");
6818 assert_eq!(q.get(&t.id).expect("get").chat_notice_due(), None);
6819 }
6820
6821 #[test]
6822 fn empty_sources_are_omitted_so_older_builds_still_read_the_task() {
6823 let mut t = task("plain");
6826 let value = serde_json::to_value(&t).unwrap();
6827 assert!(value.get("sources").is_none(), "{value}");
6828 t.sources.pick_commits.push(crate::refs::Input {
6829 token: "abc1234".into(),
6830 sha: "a".repeat(40),
6831 provenance: crate::refs::Provenance::ExplicitCli,
6832 });
6833 let value = serde_json::to_value(&t).unwrap();
6834 assert_eq!(value["sources"]["pick_commits"][0]["sha"], "a".repeat(40));
6835 let restored: Task = serde_json::from_value(value).unwrap();
6836 assert_eq!(restored.sources, t.sources);
6837 }
6838
6839 fn queue_with_ids(dir: &Path, ids: &[&str]) -> Queue {
6841 let ids: Vec<String> = ids.iter().map(|s| (*s).to_owned()).collect();
6842 let n = std::sync::atomic::AtomicUsize::new(0);
6843 Queue::at(dir.join("queue")).with_id_source(move || {
6844 let i = n.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
6845 ids.get(i)
6846 .cloned()
6847 .unwrap_or_else(|| format!("20260101-000000-f{i:03x}"))
6848 })
6849 }
6850
6851 const TAKEN: &str = "20260101-000000-aaaa";
6852
6853 #[test]
6854 fn a_new_task_never_merges_into_a_record_with_its_candidate_id() {
6855 let dir = tempfile::tempdir().unwrap();
6856 let q = queue_with_ids(dir.path(), &[TAKEN, TAKEN]);
6857 let mut first = task("first");
6858 first.start("run-1".into());
6859 first.succeed();
6860 q.put(&mut first).unwrap();
6861 assert_eq!(first.id, TAKEN);
6862 let stored_before = q.get(&first.id).unwrap();
6863 assert!(!stored_before.runs.is_empty());
6864
6865 let mut second = task("second");
6866 q.put(&mut second).unwrap();
6867
6868 assert_ne!(second.id, first.id);
6869 assert!(second.runs.is_empty());
6870 assert!(second.passes.is_empty());
6871 assert!(second.chat_notices.is_empty());
6872 assert!(second.chat_notice.is_none());
6873 assert_eq!(second.chat_notice_due(), task("fresh").chat_notice_due());
6874 let a = q.get(&first.id).unwrap();
6875 let b = q.get(&second.id).unwrap();
6876 assert_eq!(a.title, "first");
6877 assert_eq!(a.runs, stored_before.runs);
6878 assert_eq!(a.passes, stored_before.passes);
6879 assert_eq!(a.chat_notices, stored_before.chat_notices);
6880 assert_eq!(a.chat_notice, stored_before.chat_notice);
6881 assert_eq!(a.chat_notice_due(), stored_before.chat_notice_due());
6882 assert_eq!(b.title, "second");
6883 assert!(b.runs.is_empty());
6884 assert!(b.passes.is_empty());
6885 assert!(b.chat_notice.is_none());
6886
6887 let mut again = q.get(&second.id).unwrap();
6889 again.title = "second, edited".into();
6890 q.put(&mut again).unwrap();
6891 assert_eq!(q.get(&second.id).unwrap().title, "second, edited");
6892 assert_eq!(q.list().len(), 2);
6893 }
6894
6895 #[test]
6896 fn a_new_task_skips_an_id_with_an_orphaned_claim_or_attachments() {
6897 let dir = tempfile::tempdir().unwrap();
6898 let q = queue_with_ids(dir.path(), &["orphan-lock", "orphan-dir", "free"]);
6899 std::fs::create_dir_all(q.root()).unwrap();
6900 std::fs::write(q.root().join("orphan-lock.lock"), "x").unwrap();
6901 std::fs::create_dir_all(q.attachments_dir("orphan-dir")).unwrap();
6902 let mut t = task("t");
6903 q.put(&mut t).unwrap();
6904 assert_eq!(t.id, "free");
6905 }
6906
6907 #[test]
6908 fn a_claimed_new_task_holds_the_claim_on_the_reserved_id() {
6909 let dir = tempfile::tempdir().unwrap();
6910 let q = queue_with_ids(dir.path(), &[TAKEN, TAKEN]);
6911 let mut first = task("first");
6912 q.put(&mut first).unwrap();
6913 let mut second = task("second");
6914 let claim = q.file_claimed(&mut second).unwrap();
6915 assert_ne!(second.id, first.id);
6916 assert!(q.claim(&second.id).is_err());
6917 assert!(q.claim(&first.id).is_ok(), "the first task was not claimed");
6918 drop(claim);
6919 }
6920
6921 #[test]
6922 fn an_attached_new_task_skips_a_taken_id() {
6923 let dir = tempfile::tempdir().unwrap();
6924 let q = queue_with_ids(dir.path(), &[TAKEN, TAKEN]);
6925 let mut first = task("first");
6926 q.put(&mut first).unwrap();
6927 let src = source_file(dir.path(), "shot.png", "x");
6928 let mut second = task("second");
6929 q.attach_and_put(&mut second, &[src]).unwrap();
6930 assert_ne!(second.id, first.id);
6931 assert!(!q.attachments_dir(&first.id).exists());
6932 assert_eq!(q.attachment_paths(&second).len(), 1);
6933 assert!(q.attachment_paths(&second)[0].is_file());
6934 }
6935
6936 #[test]
6937 fn attaching_before_putting_a_new_task_reserves_the_id() {
6938 let dir = tempfile::tempdir().unwrap();
6939 let q = queue_with_ids(dir.path(), &[TAKEN, TAKEN]);
6940 let mut first = task("first");
6941 q.put(&mut first).unwrap();
6942 let src = source_file(dir.path(), "shot.png", "x");
6943 let mut second = task("second");
6944 q.attach(&mut second, &[src]).unwrap();
6945 assert_ne!(second.id, first.id);
6946 assert!(q.attachments_dir(&second.id).is_dir());
6947 q.put(&mut second).unwrap();
6948 assert_eq!(q.get(&second.id).unwrap().attachments.len(), 1);
6949 assert_eq!(q.get(&first.id).unwrap().title, "first");
6950 assert!(q.get(&first.id).unwrap().attachments.is_empty());
6951 }
6952
6953 #[test]
6954 fn create_new_keeps_its_already_exists_meaning() {
6955 let dir = tempfile::tempdir().unwrap();
6956 let q = Queue::at(dir.path().join("queue"));
6957 let mut a = task("a");
6958 a.id = "fixed-id".into();
6959 assert!(q.create_new(&mut a).unwrap());
6960 let mut b = task("b");
6961 b.id = "fixed-id".into();
6962 assert!(!q.create_new(&mut b).unwrap());
6963 assert_eq!(q.get("fixed-id").unwrap().title, "a");
6964 }
6965
6966 #[test]
6967 fn filing_gives_up_when_no_id_is_ever_free() {
6968 let dir = tempfile::tempdir().unwrap();
6969 let q = Queue::at(dir.path().join("queue")).with_id_source(|| TAKEN.to_owned());
6970 let mut first = task("first");
6971 q.put(&mut first).unwrap();
6972 let mut second = task("second");
6973 assert!(q.put(&mut second).is_err());
6974 assert_eq!(q.get(&first.id).unwrap().title, "first");
6975 }
6976}