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, skip_serializing_if = "Option::is_none")]
532 pub sync_only: Option<crate::base_sync_only::Request>,
533 #[serde(default)]
535 pub repair_grants: Vec<crate::repair_budget::Receipt>,
536 #[serde(default)]
538 pub repair_reconciliations: Vec<crate::repair_budget::reconcile::Receipt>,
539 #[serde(default)]
542 pub resumption: Option<Resumption>,
543 #[serde(default)]
545 pub resumption_history: Vec<Resumption>,
546 #[serde(default)]
548 pub operator_decided_at: Option<Timestamp>,
549 #[serde(default)]
561 pub review_branch: Option<String>,
562 #[serde(default)]
564 pub review_instruction: Option<String>,
565 #[serde(default)]
567 pub pr_recovery: Option<crate::pr_recovery::Selection>,
568 #[serde(default)]
571 pub fresh_start: bool,
572 #[serde(default)]
574 pub replacement: Option<crate::merge_decision::Replacement>,
575 #[serde(default)]
586 pub interrupt: bool,
587 #[serde(default)]
610 pub urgent: bool,
611 #[serde(skip)]
616 pub(crate) unfiled: bool,
617 #[serde(default)]
623 pub attachments: Vec<String>,
624 #[serde(default)]
628 pub followup: Option<FollowUp>,
629 #[serde(default)]
635 pub origin_chat: Option<String>,
636 #[serde(default)]
643 pub overrides: Option<RunOverrides>,
644 #[serde(default)]
651 pub review_of: Option<String>,
652 #[serde(default)]
657 pub held_at: Option<Timestamp>,
658 #[serde(default)]
662 pub park_reason: Option<String>,
663 #[serde(default)]
666 pub chat_notice: Option<ChatNotice>,
667 #[serde(default)]
669 pub chat_notices: Vec<String>,
670 #[serde(default)]
673 pub hold_notice_cause: Option<NoticeCause>,
674 #[serde(default)]
679 pub passes: Vec<TaskPass>,
680 #[serde(default)]
684 pub dispatched_at: Option<Timestamp>,
685 #[serde(default)]
687 pub recovery_budget: Option<RecoveryBudget>,
688 #[serde(default)]
691 pub recovery_admission: Option<RecoveryAdmission>,
692 #[serde(default)]
695 pub recovery_generations: Vec<RecoveryBudget>,
696 pub created_at: Timestamp,
698 pub updated_at: Timestamp,
700}
701
702#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
704pub struct RecoveryAdmission {
705 pub base: String,
707 pub inputs: String,
709}
710
711#[derive(Debug, Clone, Serialize, Deserialize)]
712struct RecoveryBudgetHold {
713 admission: RecoveryAdmission,
714 run: String,
715 pass: usize,
716 held_at: Timestamp,
717 decision: Option<Timestamp>,
718 #[serde(default)]
719 legacy: bool,
720}
721
722#[derive(Debug, Clone, Serialize, Deserialize)]
725pub struct RecoveryBudget {
726 pub instruction: String,
728 pub base: String,
730 pub inputs: String,
732 pub stage: String,
734 pub failures: usize,
736 #[serde(default)]
739 pub progress: Option<String>,
740}
741
742impl RecoveryBudget {
743 fn budget_reason(&self) -> String {
744 format!(
745 "[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.",
746 self.failures, self.stage
747 )
748 }
749}
750
751fn recovery_progress(state: &crate::run::RunState) -> Option<String> {
752 use crate::proc::Quiet as _;
753 use std::hash::{Hash, Hasher};
754 let mut patches = Vec::new();
755 for candidate in state.candidates.iter().filter(|c| c.commits > 0) {
756 let output = std::process::Command::new("git")
757 .current_dir(&state.repo)
758 .args(["diff", "--binary", &state.base_commit, &candidate.branch])
759 .quiet()
760 .output()
761 .ok()?;
762 if !output.status.success() {
763 return None;
764 }
765 patches.push(output.stdout);
766 }
767 patches.sort();
768 patches.dedup();
769 let mut hash = std::collections::hash_map::DefaultHasher::new();
770 patches.hash(&mut hash);
771 Some(format!("{:x}", hash.finish()))
772}
773
774pub(crate) fn recovery_inputs(sources: &crate::refs::Sources) -> String {
778 serde_json::to_string(
779 &sources
780 .start_from
781 .iter()
782 .map(|i| ("start", &i.token, &i.sha))
783 .chain(
784 sources
785 .pick_commits
786 .iter()
787 .map(|i| ("pick", &i.token, &i.sha)),
788 )
789 .collect::<Vec<_>>(),
790 )
791 .unwrap_or_default()
792}
793
794#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
796pub struct NoticeCause {
797 pub stage: String,
799 #[serde(default, skip_serializing_if = "Option::is_none")]
802 pub target: Option<String>,
803 pub run: Option<String>,
805 pub pass: Option<usize>,
807}
808
809pub(crate) fn is_done_notice_key(key: &str) -> bool {
811 key == "done"
812 || key
813 .strip_prefix("done#")
814 .is_some_and(|count| !count.is_empty() && count.bytes().all(|b| b.is_ascii_digit()))
815}
816
817#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
819#[serde(rename_all = "snake_case")]
820pub enum PassCost {
821 Spent,
823 Refunded,
825}
826
827#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
829pub struct TaskPass {
830 pub run: String,
832 pub pass_index: usize,
834 pub cost: PassCost,
836 pub attempts_after: usize,
838 #[serde(default)]
840 pub started_at: Option<Timestamp>,
841 pub settled_at: Timestamp,
843 #[serde(default)]
845 pub parked: Option<crate::run::ParkCause>,
846}
847
848#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
850#[serde(rename_all = "lowercase")]
851pub enum ChatNoticeOutcome {
852 Posted,
854 Skipped,
856}
857
858#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
860pub struct ChatNotice {
861 pub key: String,
863 pub at: Timestamp,
865 pub outcome: ChatNoticeOutcome,
867}
868
869#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
871pub struct RunOverrides {
872 #[serde(default)]
875 pub inherit_daemon_options: bool,
876 #[serde(default)]
878 pub merge: Option<String>,
879 #[serde(default)]
881 pub candidates: Option<usize>,
882 #[serde(default)]
884 pub judges: Option<usize>,
885 #[serde(default)]
887 pub reviewers: Option<usize>,
888 #[serde(default)]
890 pub review_rounds: Option<usize>,
891 #[serde(default)]
893 pub seed: Option<u64>,
894 #[serde(default)]
896 pub config: Option<PathBuf>,
897 #[serde(default, skip_serializing_if = "Option::is_none")]
899 pub build_cache: Option<BuildCache>,
900}
901
902impl RunOverrides {
903 pub fn merge_over(&mut self, other: &RunOverrides) {
905 macro_rules! take {
906 ($($f:ident),*) => {$(
907 if other.$f.is_some() {
908 self.$f.clone_from(&other.$f);
909 }
910 )*};
911 }
912 take!(
913 merge,
914 candidates,
915 judges,
916 reviewers,
917 review_rounds,
918 seed,
919 config,
920 build_cache
921 );
922 }
923
924 pub fn apply(&self, config: &mut crate::config::Config) {
926 if let Some(n) = self.candidates {
927 config.graph.implementers = n;
928 }
929 if let Some(n) = self.judges {
930 config.graph.judges = n;
931 }
932 if let Some(n) = self.reviewers {
933 config.graph.reviewers = n;
934 }
935 if let Some(n) = self.review_rounds {
936 config.graph.review_rounds = n;
937 }
938 if let Some(m) = &self.merge
939 && let Ok(mode) = crate::daemon::merge_mode(m)
940 {
941 config.merge.mode = mode;
942 }
943 if let Some(s) = self.seed {
944 config.blind.seed = Some(s);
945 }
946 if let Some(mode) = self.build_cache {
947 config.verify.build_cache = mode;
948 }
949 }
950}
951
952#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
954pub struct FollowUp {
955 pub run: String,
957 #[serde(default)]
959 pub origin_task: Option<String>,
960 pub pr: String,
962 pub findings: Vec<String>,
964 pub generation: u32,
967}
968
969#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
971pub struct Resumption {
972 pub generation: u64,
974 pub source: String,
976 pub question_id: Option<String>,
978 pub at: Timestamp,
980 pub instruction: String,
982 pub answers_through: usize,
984 pub runs_through: usize,
987 pub cleared_reason: Option<String>,
989 #[serde(default)]
991 pub blocking_evidence: Vec<String>,
992}
993
994#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
997pub struct OperatorResume {
998 pub question_id: String,
1000 pub at: Timestamp,
1002 #[serde(default)]
1005 pub conductor_rehold: Option<String>,
1006 #[serde(default)]
1009 pub forced: bool,
1010 #[serde(default)]
1017 pub pinned_run: Option<String>,
1018}
1019
1020#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1023pub struct AnsweredQuestion {
1024 pub question: String,
1026 pub answer: String,
1028}
1029
1030impl Task {
1031 pub fn new(title: String, instruction: String, repo: PathBuf, source: Source) -> Self {
1033 let now = Timestamp::now();
1034 let origin_chat = match &source {
1035 Source::Agent { run, node } if node == CHAT_NODE => Some(run.clone()),
1036 _ => None,
1037 };
1038 Self {
1039 schema: SCHEMA,
1040 id: new_id(),
1041 title,
1042 instruction,
1043 sources: crate::refs::Sources::default(),
1044 repo,
1045 reassignments: Vec::new(),
1046 source,
1047 chat: None,
1048 priority: 0,
1049 solo: false,
1050 status: TaskStatus::Queued,
1051 attempts: 0,
1052 attempt_limit: None,
1053 runs: Vec::new(),
1054 startup_failures: Vec::new(),
1055 last_error: None,
1056 hold_reason: None,
1057 hold_source: None,
1058 recovery_budget_hold: None,
1059 machine_hold_cause: None,
1060 disk_resume_run: None,
1061 disk_checked_at: None,
1062 diagnostic: None,
1063 blocked_by: Vec::new(),
1064 block_reason: None,
1065 blocked_from: None,
1066 blocked_at: None,
1067 answers: Vec::new(),
1068 triage_applied: Vec::new(),
1069 actions_applied: Vec::new(),
1070 decision_effects: Default::default(),
1071 superseded_resumes: Default::default(),
1072 dispatched_resumes: Default::default(),
1073 base_recovery_requests: Vec::new(),
1074 resume_override: None,
1075 sync_only: None,
1076 repair_grants: Vec::new(),
1077 repair_reconciliations: Vec::new(),
1078 resumption: None,
1079 resumption_history: Vec::new(),
1080 operator_decided_at: None,
1081 review_branch: None,
1082 review_instruction: None,
1083 pr_recovery: None,
1084 fresh_start: false,
1085 replacement: None,
1086 interrupt: false,
1087 urgent: false,
1088 unfiled: true,
1089 attachments: Vec::new(),
1090 followup: None,
1091 origin_chat,
1092 overrides: None,
1093 review_of: None,
1094 held_at: None,
1095 park_reason: None,
1096 chat_notice: None,
1097 chat_notices: Vec::new(),
1098 hold_notice_cause: None,
1099 passes: Vec::new(),
1100 dispatched_at: None,
1101 recovery_budget: None,
1102 recovery_admission: None,
1103 recovery_generations: Vec::new(),
1104 created_at: now,
1105 updated_at: now,
1106 }
1107 }
1108
1109 pub(crate) fn reassign_repository(&mut self, repo: PathBuf, actor: &str) {
1111 self.stamp_schema();
1112 if matches!(self.status, TaskStatus::Failed | TaskStatus::Parked) {
1113 self.hold_manual(Some(
1114 "Repository reassigned; inspect history and release to start fresh.".into(),
1115 ));
1116 }
1117 let at = Timestamp::now();
1118 self.reassignments.push(Reassignment {
1119 from: self.repo.clone(),
1120 to: repo.clone(),
1121 actor: actor.to_owned(),
1122 at,
1123 run_boundary: self.runs.len(),
1124 });
1125 self.repo = repo;
1126 self.review_branch = None;
1127 self.review_instruction = None;
1128 self.pr_recovery = None;
1129 self.replacement = None;
1130 self.interrupt = false;
1131 self.resume_override = None;
1132 self.fresh_start = true;
1133 self.operator_decided_at = Some(at);
1134 }
1135
1136 pub fn publication_branch(&self) -> String {
1138 crate::run::task_pr_branch_name(&self.id, self.reassignments.len())
1139 }
1140
1141 pub fn execution_runs(&self) -> &[String] {
1143 let boundary = self.reassignments.last().map_or(0, |r| r.run_boundary);
1144 self.runs.get(boundary..).unwrap_or_default()
1145 }
1146
1147 pub fn execution_run(&self, run: &str) -> bool {
1149 self.execution_runs().iter().any(|id| id == run)
1150 }
1151
1152 pub(crate) fn assignment_accepts(&self, run: &crate::run::RunState) -> bool {
1154 self.reassignments.last().is_none_or(|boundary| {
1155 self.execution_run(&run.id)
1156 && run.task_assignment == self.reassignments.len()
1157 && run.created_at > boundary.at
1158 && run
1159 .repo
1160 .canonicalize()
1161 .ok()
1162 .zip(self.repo.canonicalize().ok())
1163 .is_some_and(|(run_repo, task_repo)| run_repo == task_repo)
1164 })
1165 }
1166
1167 pub(crate) fn stale_question(&self, q: &crate::ask::Question) -> bool {
1169 self.reassignments
1170 .last()
1171 .is_some_and(|r| q.asked_at <= r.at)
1172 || (self.runs.contains(&q.run) && !self.execution_run(&q.run))
1173 }
1174
1175 pub fn chat_talk(&self) -> Option<&str> {
1177 if let Some(id) = &self.origin_chat {
1178 return Some(id);
1179 }
1180 match &self.source {
1181 Source::Agent { run, node } if node == CHAT_NODE => Some(run),
1182 _ => None,
1183 }
1184 }
1185
1186 pub fn filed_by_chat(&self) -> Option<&str> {
1190 match &self.source {
1191 Source::Agent { run, node } if node == CHAT_NODE => Some(run),
1192 _ => None,
1193 }
1194 }
1195
1196 pub fn chat_notice_key(&self) -> Option<String> {
1199 match self.status {
1200 TaskStatus::Done => Some("done".to_owned()),
1201 TaskStatus::Held => {
1202 let cause = self
1203 .hold_notice_cause
1204 .clone()
1205 .unwrap_or_else(|| self.unresolved_hold_cause());
1206 Some(format!(
1207 "cause:{}",
1208 serde_json::to_string(&cause).expect("cause")
1209 ))
1210 }
1211 TaskStatus::Blocked => {
1212 let ids: std::collections::BTreeSet<_> = self.blocked_by.iter().collect();
1213 let evidence = self
1216 .hold_notice_cause
1217 .as_ref()
1218 .filter(|c| c.stage.starts_with("conductor-evidence:"));
1219 Some(format!(
1220 "dependencies:{}",
1221 serde_json::to_string(&(ids, evidence)).expect("ids")
1222 ))
1223 }
1224 _ => None,
1225 }
1226 }
1227
1228 fn unresolved_hold_cause(&self) -> NoticeCause {
1229 NoticeCause {
1230 stage: "hold".into(),
1231 target: None,
1232 run: self.runs.last().cloned(),
1233 pass: None,
1234 }
1235 }
1236
1237 pub(crate) fn legacy_chat_notice_key(&self) -> Option<String> {
1239 let key = match self.status {
1240 TaskStatus::Held if self.hold_notice_cause.is_none() => Some(format!(
1241 "held#{}",
1242 self.held_at.map(|t| t.to_string()).unwrap_or_default()
1243 )),
1244 TaskStatus::Blocked => Some(format!(
1245 "blocked#{}#{}",
1246 self.blocked_by.join(","),
1247 self.block_reason.as_deref().unwrap_or_default()
1248 )),
1249 _ => None,
1250 };
1251 key.filter(|key| self.legacy_notice_matches(key))
1252 }
1253
1254 pub(crate) fn legacy_notice_matches(&self, key: &str) -> bool {
1255 match self.status {
1256 TaskStatus::Held if self.hold_notice_cause.is_none() => key
1257 .strip_prefix("held#")
1258 .is_some_and(|time| time.is_empty() || time.parse::<Timestamp>().is_ok()),
1259 TaskStatus::Blocked
1260 if self
1261 .hold_notice_cause
1262 .as_ref()
1263 .is_none_or(|c| !c.stage.starts_with("conductor-evidence:")) =>
1264 {
1265 key.strip_prefix("blocked#").is_some_and(|tail| {
1266 let Some((ids, _)) = tail.split_once('#') else {
1267 return false;
1268 };
1269 let old: std::collections::BTreeSet<_> =
1270 ids.split(',').filter(|id| !id.is_empty()).collect();
1271 let current: std::collections::BTreeSet<_> =
1272 self.blocked_by.iter().map(String::as_str).collect();
1273 old == current
1274 })
1275 }
1276 _ => false,
1277 }
1278 }
1279
1280 fn import_chat_notice(&mut self) {
1281 if let Some(n) = &self.chat_notice {
1282 let key = if is_done_notice_key(&n.key) {
1283 "done".to_owned()
1284 } else if self.legacy_notice_matches(&n.key) {
1285 self.chat_notice_key().unwrap_or_else(|| n.key.clone())
1286 } else {
1287 n.key.clone()
1288 };
1289 if !self.chat_notices.contains(&key) {
1290 self.chat_notices.push(key);
1291 }
1292 }
1293 }
1294
1295 pub(crate) fn notice_cause(&mut self, stage: &str, run: Option<&str>, pass: Option<usize>) {
1298 self.import_chat_notice();
1299 self.hold_notice_cause = Some(NoticeCause {
1300 stage: stage.to_owned(),
1301 target: None,
1302 run: run.map(str::to_owned),
1303 pass,
1304 });
1305 }
1306
1307 pub(crate) fn startup_notice_cause(&mut self, stage: &str) {
1310 let recovery_only = matches!(
1311 stage,
1312 "startup-source" | "startup-candidates" | "startup-public-head"
1313 );
1314 match self.hold_notice_cause.as_ref() {
1315 Some(cause) if recovery_only && !cause.stage.starts_with("startup-") => return,
1316 None if recovery_only
1317 && self
1318 .chat_notice
1319 .as_ref()
1320 .is_some_and(|n| !is_done_notice_key(&n.key)) =>
1321 {
1322 return;
1323 }
1324 _ => {}
1325 }
1326 self.notice_cause(stage, None, None);
1327 }
1328
1329 pub(crate) fn fail_startup(
1332 &mut self,
1333 stage: &str,
1334 why: impl Into<String>,
1335 max_attempts: usize,
1336 ) {
1337 let unresolved = self.hold_notice_cause.clone();
1338 self.fail(why, max_attempts);
1339 self.hold_notice_cause = unresolved;
1340 self.startup_notice_cause(stage);
1341 }
1342
1343 pub(crate) fn fail_startup_target(
1345 &mut self,
1346 stage: &str,
1347 target: String,
1348 why: impl Into<String>,
1349 max_attempts: usize,
1350 ) {
1351 self.fail_startup(stage, why, max_attempts);
1352 if let Some(cause) = self.hold_notice_cause.as_mut() {
1353 cause.target = Some(target);
1354 }
1355 }
1356
1357 pub fn chat_notice_due(&self) -> Option<String> {
1359 self.filed_by_chat()?;
1360 if self.schema < 13 {
1361 return None;
1362 }
1363 let key = self.chat_notice_key()?;
1364 if self.chat_notices.contains(&key) {
1365 return None;
1366 }
1367 match &self.chat_notice {
1368 Some(n)
1369 if n.key == key
1370 || (key == "done" && is_done_notice_key(&n.key))
1371 || self.legacy_notice_matches(&n.key) =>
1372 {
1373 None
1374 }
1375 _ => Some(key),
1376 }
1377 }
1378
1379 pub fn short(&self) -> &str {
1381 short(&self.id)
1382 }
1383
1384 pub fn mark_triage_applied(&mut self, question_id: &str) {
1386 if !self.triage_applied(question_id) {
1387 self.triage_applied.push(question_id.to_owned());
1388 }
1389 }
1390
1391 pub fn action_applied(&self, question_id: &str) -> bool {
1394 self.actions_applied.iter().any(|id| id == question_id)
1395 }
1396
1397 pub fn mark_action_applied(&mut self, question_id: &str) {
1399 if !self.action_applied(question_id) {
1400 self.actions_applied.push(question_id.to_owned());
1401 }
1402 }
1403
1404 pub fn triage_applied(&self, question_id: &str) -> bool {
1406 self.triage_applied.iter().any(|id| id == question_id)
1407 }
1408
1409 pub fn start(&mut self, run: String) {
1422 self.stamp_schema();
1423 self.status = TaskStatus::Running;
1424 self.attempts += 1;
1425 self.runs.retain(|id| id != &run);
1426 if let Some(pin) = &self.resume_override
1427 && pin.pinned_run.as_ref() == Some(&run)
1428 && !pin.question_id.is_empty()
1429 {
1430 self.dispatched_resumes
1431 .insert(pin.question_id.clone(), run.clone());
1432 }
1433 self.runs.push(run);
1434 self.last_error = None;
1435 self.park_reason = None;
1436 self.fresh_start = false;
1437 self.interrupt = false;
1438 self.resume_override = None;
1440 self.disk_resume_run = None;
1443 }
1444
1445 pub fn record_startup_failure(&mut self, failure: crate::run::StartupFailure) {
1447 if !self.startup_failures.iter().any(|f| f.run == failure.run) {
1448 self.startup_failures.push(failure);
1449 }
1450 }
1451
1452 pub fn link_run(&mut self, run: &str) -> bool {
1457 if self.runs.iter().any(|r| r == run) {
1458 return false;
1459 }
1460 self.runs.push(run.to_owned());
1461 true
1462 }
1463
1464 pub fn succeed(&mut self) {
1474 self.stamp_schema();
1475 self.status = TaskStatus::Done;
1476 self.resume_override = None;
1477 self.sync_only = None;
1478 self.last_error = None;
1479 self.park_reason = None;
1480 self.hold_reason = None;
1481 self.hold_source = None;
1482 self.machine_hold_cause = None;
1483 self.disk_resume_run = None;
1484 self.disk_checked_at = None;
1485 self.diagnostic = None;
1486 self.blocked_by.clear();
1487 self.block_reason = None;
1488 self.blocked_from = None;
1489 }
1490
1491 pub fn already_landed(&mut self, note: impl Into<String>) {
1499 self.succeed();
1500 self.attempts = self.attempts.saturating_sub(1);
1501 self.last_error = Some(note.into());
1502 }
1503
1504 pub fn superseded_attempts(&self, last_run_succeeded: bool) -> &[String] {
1534 if self.status != TaskStatus::Done || !last_run_succeeded || self.execution_runs().len() < 2
1535 {
1536 return &[];
1537 }
1538 &self.execution_runs()[..self.execution_runs().len() - 1]
1539 }
1540
1541 pub fn successor_of(&self, run: &str) -> Option<&String> {
1549 let runs = self.execution_runs();
1550 let pos = runs.iter().rposition(|r| r == run)?;
1551 runs.get(pos + 1)
1552 }
1553
1554 pub fn earlier_attempts(&self) -> &[String] {
1561 self.execution_runs()
1562 }
1563
1564 fn preserve_legacy_build_cache(&mut self) {
1565 if self.schema < 23 {
1566 let overrides = self.overrides.get_or_insert_with(|| RunOverrides {
1567 inherit_daemon_options: true,
1568 ..RunOverrides::default()
1569 });
1570 overrides.build_cache.get_or_insert(BuildCache::Shared);
1571 }
1572 }
1573
1574 fn stamp_schema(&mut self) {
1579 self.preserve_legacy_build_cache();
1580 if self.schema < RECOVERY_HOLD_SCHEMA && self.recovery_budget_hold.is_none() {
1581 self.recovery_budget_hold = self.legacy_recovery_budget_hold();
1582 }
1583 self.schema = self.schema.max(SCHEMA);
1584 }
1585
1586 fn note_held(&mut self) {
1589 self.stamp_schema();
1590 self.recovery_budget_hold = None;
1591 let continuing = self.status == TaskStatus::Held
1592 || (self.status == TaskStatus::Blocked
1593 && (self.blocked_from == Some(TaskStatus::Held)
1594 || (self.blocked_from.is_none()
1595 && (self.hold_reason.is_some() || self.hold_source.is_some()))));
1596 if !continuing || self.held_at.is_none() {
1597 self.held_at = Some(Timestamp::now());
1598 }
1599 }
1600
1601 pub fn fail(&mut self, why: impl Into<String>, max_attempts: usize) {
1617 let why = why.into();
1618 if self.status == TaskStatus::Running {
1619 let run = self.runs.last().cloned();
1620 self.notice_cause("run-failed", run.as_deref(), Some(self.attempts));
1621 }
1622 self.diagnostic = None;
1623 self.park_reason = None;
1624 self.status = if self.attempts >= self.effective_attempt_limit(max_attempts) {
1625 self.note_held();
1626 self.hold_source = Some(HoldSource::Machine);
1627 self.machine_hold_cause = None;
1628 self.disk_resume_run = None;
1629 self.disk_checked_at = None;
1630 self.hold_reason = Some(why.clone());
1631 TaskStatus::Held
1632 } else {
1633 TaskStatus::Failed
1634 };
1635 self.last_error = Some(why);
1636 }
1637
1638 pub fn stall(&mut self, why: impl Into<String>) {
1648 self.last_error = Some(why.into());
1649 self.diagnostic = None;
1650 self.attempts = self.attempts.saturating_sub(1);
1651 self.status = TaskStatus::Failed;
1652 }
1653
1654 pub fn park(&mut self, why: impl Into<String>) {
1660 self.diagnostic = None;
1661 self.attempts = self.attempts.saturating_sub(1);
1662 self.status = TaskStatus::Parked;
1663 self.park_reason = Some(why.into());
1664 self.stamp_schema();
1667 }
1668
1669 pub fn record_pass(
1671 &mut self,
1672 run: &str,
1673 pass_index: usize,
1674 attempts_before: usize,
1675 parked: Option<crate::run::ParkCause>,
1676 ) {
1677 self.record_pass_at(run, pass_index, None, attempts_before, parked);
1678 }
1679
1680 pub fn record_pass_at(
1683 &mut self,
1684 run: &str,
1685 pass_index: usize,
1686 started_at: Option<Timestamp>,
1687 attempts_before: usize,
1688 parked: Option<crate::run::ParkCause>,
1689 ) {
1690 if self
1691 .passes
1692 .iter()
1693 .any(|p| p.run == run && p.pass_index == pass_index)
1694 {
1695 return;
1696 }
1697 let cost = if self.attempts < attempts_before {
1698 PassCost::Refunded
1699 } else {
1700 PassCost::Spent
1701 };
1702 self.passes.push(TaskPass {
1703 run: run.to_owned(),
1704 pass_index,
1705 started_at: self.dispatched_at.or(started_at),
1706 cost,
1707 attempts_after: self.attempts,
1708 settled_at: Timestamp::now(),
1709 parked,
1710 });
1711 self.stamp_schema();
1712 }
1713
1714 pub(crate) fn upgrade_resume_key(&self) -> Option<(Timestamp, &str)> {
1717 if self.status != TaskStatus::Parked || self.fresh_start {
1718 return None;
1719 }
1720 let pass = self.passes.last()?;
1721 if self.execution_runs().last() != Some(&pass.run)
1722 || !matches!(pass.parked, Some(crate::run::ParkCause::Upgrade { .. }))
1723 {
1724 return None;
1725 }
1726 Some((pass.started_at.unwrap_or(pass.settled_at), &self.id))
1729 }
1730
1731 pub fn operator_held(&self) -> bool {
1737 self.status == TaskStatus::Held && !matches!(self.hold_source, Some(HoldSource::Machine))
1738 }
1739
1740 pub fn hold_manual(&mut self, reason: Option<String>) {
1750 self.operator_decided_at = Some(Timestamp::now());
1752 if self.status != TaskStatus::Running && self.sync_only.take().is_some() {
1753 self.resume_override = None;
1754 }
1755 self.hold_unrequested_retry(reason);
1756 }
1757
1758 pub(crate) fn hold_unrequested_retry(&mut self, reason: Option<String>) {
1761 self.park_reason = None;
1762 self.note_held();
1763 self.status = TaskStatus::Held;
1764 if reason.is_some() {
1765 self.hold_reason = reason;
1766 }
1767 self.hold_source = Some(HoldSource::Manual);
1768 self.machine_hold_cause = None;
1769 self.disk_resume_run = None;
1770 self.disk_checked_at = None;
1771 self.blocked_by.clear();
1772 self.block_reason = None;
1773 self.blocked_from = None;
1774 }
1775
1776 pub(crate) fn hold_after_sync_only(&mut self, reason: String) {
1777 let recovery_hold = self.recovery_budget_hold.take();
1778 self.hold_unrequested_retry(Some(reason));
1779 self.recovery_budget_hold = recovery_hold;
1780 }
1781
1782 pub fn hold_machine(&mut self, reason: Option<String>) {
1787 self.park_reason = None;
1788 self.note_held();
1789 self.status = TaskStatus::Held;
1790 if reason.is_some() {
1791 self.hold_reason = reason;
1792 }
1793 self.hold_source = Some(HoldSource::Machine);
1794 self.machine_hold_cause = None;
1795 self.disk_resume_run = None;
1796 self.disk_checked_at = None;
1797 self.blocked_by.clear();
1798 self.block_reason = None;
1799 self.blocked_from = None;
1800 }
1801
1802 pub(crate) fn mark_disk_capacity(&mut self) {
1804 self.machine_hold_cause = Some(MachineHoldCause::DiskCapacity {
1805 reason: self.hold_reason.clone().unwrap_or_default(),
1806 before_start: false,
1807 });
1808 }
1809
1810 pub(crate) fn mark_startup_disk_capacity(&mut self) {
1811 self.machine_hold_cause = Some(MachineHoldCause::DiskCapacity {
1812 reason: self.hold_reason.clone().unwrap_or_default(),
1813 before_start: true,
1814 });
1815 }
1816
1817 pub(crate) fn disk_wait_run(&self) -> Option<&String> {
1818 if self.has_disk_capacity_cause()
1819 && matches!(
1820 self.machine_hold_cause,
1821 Some(MachineHoldCause::DiskCapacity {
1822 before_start: true,
1823 ..
1824 })
1825 )
1826 {
1827 None
1828 } else {
1829 self.execution_runs().last()
1830 }
1831 }
1832
1833 pub fn has_disk_capacity_cause(&self) -> bool {
1835 matches!(
1836 (&self.machine_hold_cause, self.hold_reason.as_deref()),
1837 (Some(MachineHoldCause::DiskCapacity { reason, .. }), Some(now)) if reason == now
1838 )
1839 }
1840
1841 pub(crate) fn resume_disk_wait(&mut self) {
1843 let retained = self.disk_wait_run().cloned();
1844 self.status = TaskStatus::Queued;
1845 self.held_at = None;
1846 self.hold_source = None;
1847 self.hold_reason = None;
1848 self.machine_hold_cause = None;
1849 self.last_error = None;
1850 self.disk_resume_run = retained;
1851 }
1852
1853 pub fn block(&mut self, blocked_by: Vec<String>, reason: Option<String>) {
1863 self.stamp_schema();
1864 let before: std::collections::BTreeSet<_> = self.blocked_by.iter().collect();
1865 let after: std::collections::BTreeSet<_> = blocked_by.iter().collect();
1866 if self.status != TaskStatus::Blocked || before != after {
1867 self.blocked_at = Some(Timestamp::now());
1868 }
1869 if self.status != TaskStatus::Blocked {
1870 self.blocked_from = Some(self.status);
1871 }
1872 self.status = TaskStatus::Blocked;
1873 self.blocked_by = blocked_by;
1874 self.block_reason = reason;
1875 }
1876
1877 pub fn unblock(&mut self, resolved_id: &str) {
1900 if self.status != TaskStatus::Blocked {
1901 return;
1902 }
1903 self.blocked_by.retain(|id| id != resolved_id);
1904 self.restore_if_unblocked();
1905 }
1906
1907 pub fn dependency_deleted(&mut self, deleted_id: &str) -> bool {
1918 if self.status != TaskStatus::Blocked || !self.blocked_by.iter().any(|b| b == deleted_id) {
1919 return false;
1920 }
1921 self.blocked_by.retain(|id| id != deleted_id);
1922 self.restore_if_unblocked();
1923 true
1924 }
1925
1926 fn restore_if_unblocked(&mut self) {
1930 if self.blocked_by.is_empty() {
1931 self.status = match self.blocked_from {
1932 Some(TaskStatus::Running) => TaskStatus::Queued,
1933 Some(other) => other,
1934 None if self.hold_reason.is_some() || self.hold_source.is_some() => {
1935 TaskStatus::Held
1936 }
1937 None => TaskStatus::Queued,
1938 };
1939 self.block_reason = None;
1940 self.blocked_from = None;
1941 }
1942 }
1943
1944 pub fn record_answer(&mut self, question: String, answer: String) {
1949 self.answers.push(AnsweredQuestion { question, answer });
1950 }
1951
1952 pub fn request_review(&mut self, branch: String) {
1956 self.release();
1957 self.review_branch = Some(branch);
1958 self.review_instruction = Some(self.instruction.clone());
1959 }
1960
1961 pub fn requeue(&mut self) {
1964 self.release();
1965 self.review_branch = None;
1967 self.review_instruction = None;
1968 self.fresh_start = true;
1969 }
1970
1971 pub fn hold_for_handover(&mut self, branch: Option<String>, reason: String) {
1980 if branch.is_some() {
1981 self.review_branch = branch;
1982 self.review_instruction = Some(self.instruction.clone());
1983 }
1984 self.hold_machine(Some(reason));
1985 }
1986
1987 pub fn set_urgent(&mut self, urgent: bool) -> Result<()> {
1989 if !matches!(self.status, TaskStatus::Queued | TaskStatus::Held) {
1990 bail!(
1991 "task {} is {}; urgent can only change while queued or held; \
1992 wait for the active attempt to finish and requeue or hold the task first",
1993 self.short(),
1994 self.status.as_str()
1995 );
1996 }
1997 self.urgent = urgent;
1998 Ok(())
1999 }
2000
2001 pub fn set_priority(&mut self, priority: i32) -> Result<()> {
2010 if self.status == TaskStatus::Running {
2011 bail!(
2012 "task {} is running; its priority cannot be changed until \
2013 this attempt finishes",
2014 self.short()
2015 );
2016 }
2017 self.priority = priority;
2018 Ok(())
2019 }
2020
2021 pub fn set_interrupt(&mut self, interrupt: bool) -> Result<()> {
2036 if interrupt && !self.status.runnable() {
2037 bail!(
2038 "task {} is {}; only a queued or failed task can be marked \
2039 to interrupt",
2040 self.short(),
2041 self.status.as_str()
2042 );
2043 }
2044 self.interrupt = interrupt;
2045 Ok(())
2046 }
2047
2048 pub fn effective_attempt_limit(&self, daemon_limit: usize) -> usize {
2050 self.attempt_limit.map_or(daemon_limit, NonZeroUsize::get)
2051 }
2052
2053 pub fn change_attempt_limit(&mut self, limit: Option<NonZeroUsize>) -> Result<()> {
2056 if !matches!(self.status, TaskStatus::Queued | TaskStatus::Held) {
2057 bail!("only queued or held tasks can change the attempt limit");
2058 }
2059 self.stamp_schema();
2060 self.attempt_limit = limit;
2061 Ok(())
2062 }
2063
2064 pub fn implementers(&self) -> Option<usize> {
2066 if self.solo {
2067 Some(1)
2068 } else {
2069 self.overrides.as_ref().and_then(|o| o.candidates)
2070 }
2071 }
2072
2073 pub fn build_cache_override(
2077 &self,
2078 config: &crate::config::Config,
2079 ) -> Option<(BuildCache, &'static str)> {
2080 self.overrides
2081 .as_ref()
2082 .and_then(|o| o.build_cache)
2083 .map(|mode| (mode, "task-override"))
2084 .or_else(|| {
2085 (self.urgent && crate::build_target::urgent_isolation(config))
2086 .then_some((BuildCache::Isolated, "urgent"))
2087 })
2088 }
2089
2090 pub fn change_build_cache(&mut self, mode: Option<BuildCache>) -> Result<()> {
2093 if !matches!(self.status, TaskStatus::Queued | TaskStatus::Held) {
2094 bail!(
2095 "task {} is {}; only queued or held tasks can change build cache",
2096 self.short(),
2097 self.status.as_str()
2098 );
2099 }
2100 self.stamp_schema();
2101 if self.overrides.is_some() || mode.is_some() {
2102 let overrides = self.overrides.get_or_insert_with(|| RunOverrides {
2103 inherit_daemon_options: true,
2104 ..RunOverrides::default()
2105 });
2106 overrides.build_cache = mode;
2107 }
2108 Ok(())
2109 }
2110
2111 pub fn change_implementers(&mut self, count: u8) -> Result<()> {
2114 self.check_implementers_editable()?;
2115 let explicit = self.overrides.as_ref().and_then(|o| o.config.as_deref());
2116 let (mut config, _) = crate::config::Config::discover(&self.repo, explicit)?;
2117 if let Some(o) = &self.overrides {
2118 o.apply(&mut config);
2119 }
2120 self.set_implementers(count, &config)
2121 }
2122
2123 fn check_implementers_editable(&self) -> Result<()> {
2124 if !matches!(self.status, TaskStatus::Queued | TaskStatus::Held) {
2125 bail!(
2126 "task {} is {}; only queued or held tasks can change implementers",
2127 self.short(),
2128 self.status.as_str()
2129 );
2130 }
2131 Ok(())
2132 }
2133
2134 pub fn set_implementers(&mut self, count: u8, config: &crate::config::Config) -> Result<()> {
2136 self.check_implementers_editable()?;
2137 crate::talk::check_implementers(count, config).map_err(anyhow::Error::msg)?;
2138 self.stamp_schema();
2139 self.solo = count == 1;
2140 let mut overrides = self.overrides.clone().unwrap_or_else(|| RunOverrides {
2141 inherit_daemon_options: true,
2142 ..Default::default()
2143 });
2144 overrides.candidates = (count > 1).then_some(usize::from(count));
2145 let mut settings = overrides.clone();
2146 settings.inherit_daemon_options = false;
2147 self.overrides = if overrides.inherit_daemon_options && settings == RunOverrides::default()
2149 {
2150 None
2151 } else {
2152 Some(overrides)
2153 };
2154 Ok(())
2155 }
2156
2157 pub fn edit(&mut self, title: String, instruction: String) -> Result<()> {
2169 if !matches!(self.status, TaskStatus::Queued | TaskStatus::Held) {
2170 bail!(
2171 "task {} is {}; only a queued or held task's instruction can \
2172 be edited",
2173 self.short(),
2174 self.status.as_str()
2175 );
2176 }
2177 if self.review_branch.is_some() && self.review_instruction.is_none() {
2180 self.review_instruction = Some(self.instruction.clone());
2181 }
2182 if self.instruction != instruction {
2183 self.resume_override = None;
2186 }
2187 if self.status == TaskStatus::Held && self.machine_hold_cause.is_some() {
2188 self.hold_manual(self.hold_reason.clone());
2189 }
2190 self.machine_hold_cause = None;
2191 self.disk_resume_run = None;
2192 self.disk_checked_at = None;
2193 self.title = title;
2194 self.instruction = instruction;
2195 Ok(())
2196 }
2197
2198 pub fn handed_off(&mut self, why: impl Into<String>) {
2218 let why = why.into();
2219 self.diagnostic = None;
2220 self.note_held();
2221 self.status = TaskStatus::Held;
2222 self.hold_source = Some(HoldSource::Machine);
2223 self.machine_hold_cause = None;
2224 self.disk_resume_run = None;
2225 self.disk_checked_at = None;
2226 self.hold_reason = Some(why.clone());
2227 self.last_error = Some(why);
2228 }
2229
2230 pub fn release_operator(&mut self, source: &str, question_id: Option<&str>) {
2232 self.recovery_budget = None;
2233 self.recovery_generations.clear();
2234 self.recovery_admission = None;
2235 if self
2236 .resumption
2237 .as_ref()
2238 .is_some_and(|r| r.instruction != self.instruction)
2239 {
2240 self.resume_override = None;
2243 }
2244 let approval = Resumption {
2245 generation: self.resumption.as_ref().map_or(1, |r| r.generation + 1),
2246 source: source.to_owned(),
2247 question_id: question_id.map(str::to_owned),
2248 at: Timestamp::now(),
2249 instruction: self.instruction.clone(),
2250 answers_through: self.answers.len(),
2251 runs_through: self.runs.len(),
2252 blocking_evidence: Vec::new(),
2253 cleared_reason: self
2254 .hold_reason
2255 .clone()
2256 .or_else(|| self.block_reason.clone()),
2257 };
2258 self.release();
2259 self.operator_decided_at = Some(approval.at);
2260 if let Some(previous) = self.resumption.replace(approval) {
2261 self.resumption_history.push(previous);
2262 }
2263 }
2264
2265 pub(crate) fn recovery_failed(&mut self, state: &crate::run::RunState) {
2267 let (base, inputs) = self.recovery_admission.as_ref().map_or_else(
2268 || (state.base_commit.clone(), recovery_inputs(&state.sources)),
2269 |a| (a.base.clone(), a.inputs.clone()),
2270 );
2271 let progress = recovery_progress(state);
2272 let stage = if state.prep_failure.is_some() {
2273 "preparation"
2274 } else {
2275 "execution"
2276 };
2277 let matches = |b: &RecoveryBudget| {
2278 b.instruction == self.instruction
2279 && b.base == base
2280 && b.inputs == inputs
2281 && (progress.is_none() || b.progress == progress)
2282 };
2283 if !self.recovery_budget.as_ref().is_some_and(matches) {
2284 let previous = self
2285 .recovery_generations
2286 .iter()
2287 .position(matches)
2288 .map(|index| self.recovery_generations.remove(index));
2289 if let Some(old) = self.recovery_budget.take() {
2290 self.recovery_generations.push(old);
2291 }
2292 self.recovery_budget = previous;
2293 }
2294 if let Some(budget) = &mut self.recovery_budget {
2295 budget.failures = budget.failures.saturating_add(1);
2296 budget.stage = stage.to_owned();
2297 } else {
2298 self.recovery_budget = Some(RecoveryBudget {
2299 instruction: self.instruction.clone(),
2300 base,
2301 inputs,
2302 stage: stage.to_owned(),
2303 failures: 1,
2304 progress,
2305 });
2306 }
2307 }
2308
2309 pub(crate) fn recovery_exhausted(
2310 &self,
2311 base: &str,
2312 inputs: &str,
2313 limit: usize,
2314 ) -> Option<String> {
2315 let same_input = |b: &&RecoveryBudget| {
2316 b.instruction == self.instruction && b.base == base && b.inputs == inputs
2317 };
2318 let budget = self
2319 .recovery_budget
2320 .as_ref()
2321 .filter(same_input)
2322 .or_else(|| self.recovery_generations.iter().rev().find(same_input))?;
2323 (budget.failures >= limit.max(1)).then(|| budget.budget_reason())
2324 }
2325
2326 pub(crate) fn hold_recovery_budget(&mut self, reason: String, admission: RecoveryAdmission) {
2327 self.hold_unrequested_retry(Some(reason));
2328 if let Some(pass) = self.passes.last()
2329 && self.execution_runs().last() == Some(&pass.run)
2330 {
2331 self.recovery_budget_hold = Some(RecoveryBudgetHold {
2332 admission,
2333 run: pass.run.clone(),
2334 pass: pass.pass_index,
2335 held_at: self.held_at.expect("hold timestamp just recorded"),
2336 decision: self.operator_decided_at,
2337 legacy: false,
2338 });
2339 }
2340 }
2341
2342 fn matches_budget_hold(&self, admission: &RecoveryAdmission) -> bool {
2343 self.status == TaskStatus::Held
2344 && self.hold_source == Some(HoldSource::Manual)
2345 && self.machine_hold_cause.is_none()
2346 && self.recovery_budget.as_ref().is_some_and(|budget| {
2347 budget.instruction == self.instruction
2348 && budget.base == admission.base
2349 && budget.inputs == admission.inputs
2350 && budget.stage == "execution"
2351 && budget.failures > 0
2352 && self
2353 .hold_reason
2354 .as_ref()
2355 .is_some_and(|reason| *reason == budget.budget_reason())
2356 })
2357 }
2358
2359 fn legacy_recovery_budget_hold(&self) -> Option<RecoveryBudgetHold> {
2360 let held_at = self.held_at?;
2361 let settled = self.passes.last()?;
2362 let admission = self.recovery_admission.as_ref()?;
2363 if !self.matches_budget_hold(admission)
2364 || self.execution_runs().last() != Some(&settled.run)
2365 || settled.cost != PassCost::Spent
2366 || settled.parked.is_some()
2367 || settled.settled_at > held_at
2368 || self.operator_decided_at.is_some_and(|at| at >= held_at)
2369 {
2370 return None;
2371 }
2372 Some(RecoveryBudgetHold {
2373 admission: admission.clone(),
2374 run: settled.run.clone(),
2375 pass: settled.pass_index,
2376 held_at,
2377 decision: self.operator_decided_at,
2378 legacy: true,
2379 })
2380 }
2381
2382 pub(crate) fn held_for_recovery_budget(&self, run: &crate::run::RunState) -> bool {
2383 let (Some(held_at), Some(settled), Some(pass), Some(admission)) = (
2384 self.held_at,
2385 self.passes.last(),
2386 run.passes.last(),
2387 self.recovery_admission.as_ref(),
2388 ) else {
2389 return false;
2390 };
2391 if !self.matches_budget_hold(admission)
2392 || self.execution_runs().last() != Some(&run.id)
2393 || settled.run != run.id
2394 || settled.pass_index != pass.index
2395 || settled.cost != PassCost::Spent
2396 || settled.parked.is_some()
2397 || settled.settled_at < pass.started_at
2398 || settled.settled_at > held_at
2399 || self.operator_decided_at.is_some_and(|at| at >= held_at)
2400 || !crate::daemon::compatible_run_instruction(run, self)
2401 {
2402 return false;
2403 }
2404 match &self.recovery_budget_hold {
2405 Some(hold) => {
2406 hold.run == run.id
2407 && hold.pass == pass.index
2408 && hold.held_at == held_at
2409 && hold.decision == self.operator_decided_at
2410 && &hold.admission == admission
2411 && (!hold.legacy
2412 || self
2413 .operator_decided_at
2414 .is_none_or(|at| at < pass.started_at))
2415 }
2416 None => {
2417 self.schema < RECOVERY_HOLD_SCHEMA
2418 && self
2419 .operator_decided_at
2420 .is_none_or(|at| at < pass.started_at)
2421 }
2422 }
2423 }
2424
2425 pub(crate) fn queue_repair(&mut self, receipt: &crate::repair_budget::Receipt) {
2426 self.stamp_schema();
2427 self.repair_grants.push(receipt.clone());
2428 self.status = TaskStatus::Queued;
2429 self.hold_source = None;
2430 self.hold_reason = None;
2431 self.held_at = None;
2432 self.recovery_budget_hold = None;
2433 self.resume_override = Some(OperatorResume {
2434 question_id: String::new(),
2435 at: receipt.at,
2436 conductor_rehold: None,
2437 forced: true,
2438 pinned_run: Some(receipt.request.run.clone()),
2439 });
2440 }
2441
2442 pub fn release(&mut self) {
2446 self.import_chat_notice();
2449 if self.hold_notice_cause.is_none()
2450 && matches!(self.status, TaskStatus::Held | TaskStatus::Blocked)
2451 {
2452 self.hold_notice_cause = Some(self.unresolved_hold_cause());
2453 }
2454 let refused_handover = self.status == TaskStatus::Held
2455 && self.hold_source == Some(HoldSource::Machine)
2456 && self.review_branch.is_some()
2457 && self
2458 .review_instruction
2459 .as_ref()
2460 .is_none_or(|i| *i == self.instruction);
2461 self.status = TaskStatus::Queued;
2462 self.held_at = None;
2463 self.attempts = 0;
2464 self.last_error = None;
2465 self.park_reason = None;
2466 self.hold_reason = None;
2469 self.hold_source = None;
2470 self.machine_hold_cause = None;
2471 self.disk_resume_run = None;
2472 self.disk_checked_at = None;
2473 self.diagnostic = None;
2474 self.blocked_by.clear();
2479 self.block_reason = None;
2480 self.blocked_from = None;
2481 if !refused_handover {
2485 self.review_branch = None;
2486 self.review_instruction = None;
2487 }
2488 self.fresh_start = false;
2489 }
2490}
2491
2492fn copy_new(dir: &Path, src: &Path, name: &str) -> Result<(String, PathBuf)> {
2496 use std::io::ErrorKind;
2497 let (stem, ext) = match name.rfind('.') {
2498 Some(i) if i > 0 => (&name[..i], &name[i..]),
2499 _ => (name, ""),
2500 };
2501 for n in 1u32.. {
2502 let candidate = if n == 1 {
2503 name.to_owned()
2504 } else {
2505 let suffix = format!("-{n}");
2506 let room = 64usize.saturating_sub(suffix.len() + ext.len());
2507 let stem: String = stem.chars().take(room).collect();
2508 format!("{stem}{suffix}{ext}")
2509 };
2510 if !crate::ask::valid_asset_name(&candidate) {
2511 bail!("no valid attachment name is left for `{name}`");
2512 }
2513 let path = dir.join(&candidate);
2514 match std::fs::OpenOptions::new()
2515 .write(true)
2516 .create_new(true)
2517 .open(&path)
2518 {
2519 Ok(mut out) => {
2520 let copied = std::fs::File::open(src)
2521 .and_then(|mut input| std::io::copy(&mut input, &mut out));
2522 if let Err(e) = copied {
2523 drop(out);
2524 let _ = std::fs::remove_file(&path);
2525 return Err(e).with_context(|| format!("copy {}", src.display()));
2526 }
2527 return Ok((candidate, path));
2528 }
2529 Err(e) if e.kind() == ErrorKind::AlreadyExists => continue,
2530 Err(e) => return Err(e).with_context(|| format!("create {}", path.display())),
2531 }
2532 }
2533 unreachable!("the counter never runs out")
2534}
2535
2536const TASK_LOCK_STALE: std::time::Duration = std::time::Duration::from_secs(10);
2539
2540pub(crate) struct TaskLock {
2543 path: PathBuf,
2544 token: String,
2545}
2546
2547fn owner_token() -> String {
2550 static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
2551 let n = COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2552 let mut r = crate::rng::SplitMix64::new(crate::rng::entropy() ^ n.rotate_left(32));
2553 format!("{}-{:016x}", std::process::id(), r.next_u64())
2554}
2555
2556fn break_marker(path: &Path, token: &str) -> PathBuf {
2559 let mut h: u64 = 0xcbf29ce484222325;
2560 for b in token.bytes() {
2561 h ^= u64::from(b);
2562 h = h.wrapping_mul(0x100000001b3);
2563 }
2564 let mut name = path.as_os_str().to_owned();
2565 name.push(format!(".break-{h:016x}"));
2566 PathBuf::from(name)
2567}
2568
2569fn older_than_stale(path: &Path) -> bool {
2570 std::fs::metadata(path)
2571 .and_then(|m| m.modified())
2572 .ok()
2573 .and_then(|t| t.elapsed().ok())
2574 .is_some_and(|age| age > TASK_LOCK_STALE)
2575}
2576
2577fn writer_may_be_gone(token: &str) -> bool {
2578 let Some(pid) = token
2579 .split_once('-')
2580 .and_then(|(pid, _)| pid.parse::<u32>().ok())
2581 else {
2582 return true;
2585 };
2586 if pid == std::process::id() {
2587 return false;
2588 }
2589 crate::proc::pid_status(pid) == Some(false)
2591}
2592
2593const MAX_MARKER_DEPTH: u8 = 3;
2597
2598fn take_marker(
2604 path: &Path,
2605 token: &str,
2606 depth: u8,
2607 retry: crate::lock_file::Retry,
2608) -> Option<(PathBuf, String)> {
2609 use std::io::Write;
2610 let marker = break_marker(path, token);
2611 for _ in 0..2 {
2612 match retry.create(&marker) {
2613 Ok(mut f) => {
2614 let mine = owner_token();
2615 if f.write_all(mine.as_bytes()).is_err() {
2616 drop(f);
2617 let _ = std::fs::remove_file(&marker);
2618 return None;
2619 }
2620 return Some((marker, mine));
2621 }
2622 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
2623 let judged = std::fs::read_to_string(&marker).ok();
2624 match judged.filter(|_| older_than_stale(&marker)) {
2625 Some(judged) if depth < MAX_MARKER_DEPTH => {
2626 remove_lock_if(&marker, &judged, true, depth + 1, retry)?;
2627 }
2628 _ => return None,
2629 }
2630 }
2631 Err(_) => return None,
2632 }
2633 }
2634 None
2635}
2636
2637fn remove_lock_if(
2642 path: &Path,
2643 token: &str,
2644 require_stale: bool,
2645 depth: u8,
2646 retry: crate::lock_file::Retry,
2647) -> Option<bool> {
2648 let (marker, mine) = take_marker(path, token, depth, retry)?;
2649 let still = std::fs::read_to_string(path).is_ok_and(|c| c == token)
2650 && (!require_stale || older_than_stale(path) && writer_may_be_gone(token));
2651 if still {
2652 let _ = std::fs::remove_file(path);
2653 }
2654 if depth >= MAX_MARKER_DEPTH {
2656 if std::fs::read_to_string(&marker).is_ok_and(|c| c == mine) {
2657 let _ = std::fs::remove_file(&marker);
2658 }
2659 } else {
2660 let _ = remove_lock_if(&marker, &mine, false, depth + 1, retry);
2661 }
2662 Some(still)
2663}
2664
2665#[cfg(test)]
2668fn break_stale(path: &Path, judged: &str) -> bool {
2669 break_stale_with(path, judged, crate::lock_file::Retry::new(None))
2670}
2671
2672fn break_stale_with(path: &Path, judged: &str, retry: crate::lock_file::Retry) -> bool {
2673 remove_lock_if(path, judged, true, 0, retry).unwrap_or(false)
2674}
2675
2676impl Drop for TaskLock {
2677 fn drop(&mut self) {
2678 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2);
2679 let retry = crate::lock_file::Retry::new(Some(deadline));
2680 loop {
2681 match remove_lock_if(&self.path, &self.token, false, 0, retry) {
2682 Some(_) => return,
2683 None if std::time::Instant::now() > deadline => return,
2684 None => std::thread::sleep(std::time::Duration::from_millis(5)),
2685 }
2686 }
2687 }
2688}
2689
2690#[derive(Debug, Clone)]
2692pub struct Queue {
2693 root: PathBuf,
2694 ids: IdSource,
2695}
2696
2697fn validate_attachments(sources: &[PathBuf]) -> Result<Vec<(&PathBuf, &str)>> {
2698 let mut wanted = Vec::new();
2699 for src in sources {
2700 let name = src
2701 .file_name()
2702 .and_then(|n| n.to_str())
2703 .with_context(|| format!("`{}` has no usable file name", src.display()))?;
2704 if !crate::ask::valid_asset_name(name) {
2705 bail!(
2706 "attachment name `{name}` must match ^[A-Za-z0-9][A-Za-z0-9._-]{{0,63}}$ \
2707 with no `..`; rename the file and try again"
2708 );
2709 }
2710 if !src.is_file() {
2711 bail!("attachment `{}` is not a file", src.display());
2712 }
2713 wanted.push((src, name));
2714 }
2715 Ok(wanted)
2716}
2717
2718impl Queue {
2719 pub fn open() -> Self {
2721 Self::at(crate::run::home().join("queue"))
2722 }
2723
2724 pub fn at(root: PathBuf) -> Self {
2727 Self {
2728 root,
2729 ids: IdSource::new(new_id),
2730 }
2731 }
2732
2733 #[doc(hidden)]
2736 pub fn with_id_source(mut self, f: impl Fn() -> String + Send + Sync + 'static) -> Self {
2737 self.ids = IdSource::custom(f);
2738 self
2739 }
2740
2741 fn file_with(
2752 &self,
2753 task: &mut Task,
2754 hook: impl FnMut(&mut Task) -> Result<bool>,
2755 undo: impl FnMut(&mut Task),
2756 ) -> Result<()> {
2757 self.reserve_id(task, hook, undo, true)
2758 }
2759
2760 fn reserve_id(
2768 &self,
2769 task: &mut Task,
2770 mut hook: impl FnMut(&mut Task) -> Result<bool>,
2771 mut undo: impl FnMut(&mut Task),
2772 store: bool,
2773 ) -> Result<()> {
2774 let redraw_first = self.ids.is_custom() && task.attachments.is_empty();
2775 let initial = task.id.clone();
2776 self.ids
2777 .reserve((!redraw_first).then_some(initial.as_str()), "task", |id| {
2778 task.id = id.to_owned();
2779 let _lock = self.lock_task(&task.id)?;
2780 if path_exists(&self.path_of(&task.id))? || !hook(task)? {
2781 return Ok(false);
2782 }
2783 if store {
2784 if let Err(e) = self.write_record(task) {
2785 undo(task);
2786 return Err(e);
2787 }
2788 task.unfiled = false;
2789 }
2790 Ok(true)
2791 })?;
2792 Ok(())
2793 }
2794
2795 fn id_in_use(&self, id: &str, check_attachments: bool) -> Result<bool> {
2800 if path_exists(&self.lock_path(id))? {
2801 return Ok(true);
2802 }
2803 Ok(check_attachments && path_exists(&self.attachments_dir(id))?)
2804 }
2805
2806 fn plain_filing_hook(&self, task: &Task) -> Result<bool> {
2810 Ok(!self.id_in_use(&task.id, task.attachments.is_empty())?)
2811 }
2812
2813 pub fn file_claimed(&self, task: &mut Task) -> Result<Claim> {
2816 let mut claim = None;
2817 self.file_with(
2818 task,
2819 |t| {
2820 if self.id_in_use(&t.id, true)? {
2821 return Ok(false);
2822 }
2823 claim = Some(self.claim(&t.id)?);
2824 Ok(true)
2825 },
2826 |_| {},
2827 )?;
2828 claim.context("claim missing after filing")
2829 }
2830
2831 pub fn root(&self) -> &Path {
2833 &self.root
2834 }
2835
2836 pub fn path_of(&self, id: &str) -> PathBuf {
2838 self.root.join(format!("{id}.json"))
2839 }
2840
2841 pub fn attachments_dir(&self, id: &str) -> PathBuf {
2844 self.root.join(format!("{id}.attachments"))
2845 }
2846
2847 pub fn attach(&self, task: &mut Task, sources: &[PathBuf]) -> Result<Vec<String>> {
2858 let wanted = validate_attachments(sources)?;
2859 if task.unfiled && task.attachments.is_empty() {
2860 let names = std::cell::RefCell::new(Vec::new());
2863 self.reserve_id(
2864 task,
2865 |t| {
2866 if self.id_in_use(&t.id, true)? {
2867 return Ok(false);
2868 }
2869 *names.borrow_mut() = self.copy_attachments(t, &wanted)?;
2870 Ok(true)
2871 },
2872 |_| {},
2873 false,
2874 )?;
2875 return Ok(names.into_inner());
2876 }
2877 self.copy_attachments(task, &wanted)
2878 }
2879
2880 fn copy_attachments(
2882 &self,
2883 task: &mut Task,
2884 wanted: &[(&PathBuf, &str)],
2885 ) -> Result<Vec<String>> {
2886 let dir = self.attachments_dir(&task.id);
2887 let existed = dir.is_dir();
2888 std::fs::create_dir_all(&dir).with_context(|| format!("create {}", dir.display()))?;
2889 let mut created: Vec<PathBuf> = Vec::new();
2890 let mut names = Vec::new();
2891 let mut copy_all = || -> Result<()> {
2892 for (src, name) in wanted {
2893 let (stored, path) = copy_new(&dir, src, name)?;
2894 created.push(path);
2895 names.push(stored);
2896 }
2897 Ok(())
2898 };
2899 if let Err(e) = copy_all() {
2900 for path in &created {
2901 let _ = std::fs::remove_file(path);
2902 }
2903 if !existed {
2904 let _ = std::fs::remove_dir(&dir);
2905 }
2906 return Err(e);
2907 }
2908 task.attachments.extend(names.iter().cloned());
2909 Ok(names)
2910 }
2911
2912 pub fn attach_and_put(&self, task: &mut Task, sources: &[PathBuf]) -> Result<Vec<String>> {
2923 if task.unfiled && task.attachments.is_empty() {
2924 return self.attach_and_file(task, sources);
2925 }
2926 let dir = self.attachments_dir(&task.id);
2927 let existed = dir.is_dir();
2928 let before = task.attachments.len();
2929 let names = self.attach(task, sources)?;
2930 if let Err(e) = self.put(task) {
2931 for name in &names {
2932 let _ = std::fs::remove_file(dir.join(name));
2933 }
2934 if !existed {
2935 let _ = std::fs::remove_dir(&dir);
2936 }
2937 task.attachments.truncate(before);
2938 return Err(e);
2939 }
2940 Ok(names)
2941 }
2942
2943 fn attach_and_file(&self, task: &mut Task, sources: &[PathBuf]) -> Result<Vec<String>> {
2947 let wanted = validate_attachments(sources)?;
2948 let before = task.attachments.len();
2949 let names = std::cell::RefCell::new(Vec::new());
2950 let result = self.file_with(
2951 task,
2952 |t| {
2953 if self.id_in_use(&t.id, true)? {
2954 return Ok(false);
2955 }
2956 *names.borrow_mut() = self.copy_attachments(t, &wanted)?;
2957 Ok(true)
2958 },
2959 |t| {
2960 let dir = self.attachments_dir(&t.id);
2961 for name in names.borrow().iter() {
2962 let _ = std::fs::remove_file(dir.join(name));
2963 }
2964 let _ = std::fs::remove_dir(&dir);
2966 t.attachments.truncate(before);
2967 },
2968 );
2969 result.map(|()| names.into_inner())
2970 }
2971
2972 pub fn attachment_paths(&self, task: &Task) -> Vec<PathBuf> {
2976 let dir = self.attachments_dir(&task.id);
2977 task.attachments
2978 .iter()
2979 .map(|n| {
2980 let p = dir.join(n);
2981 std::path::absolute(&p).unwrap_or(p)
2982 })
2983 .collect()
2984 }
2985
2986 pub fn put(&self, task: &mut Task) -> Result<()> {
2995 if task.unfiled {
2996 return self.file_with(task, |t| self.plain_filing_hook(t), |_| {});
2998 }
2999 let _lock = self.lock_task(&task.id)?;
3000 self.put_unlocked(task)
3001 }
3002
3003 pub fn create_new(&self, task: &mut Task) -> Result<bool> {
3008 let _lock = self.lock_task(&task.id)?;
3009 if path_exists(&self.path_of(&task.id))? {
3010 return Ok(false);
3011 }
3012 self.write_record(task)?;
3013 task.unfiled = false;
3014 Ok(true)
3015 }
3016
3017 fn put_unlocked(&self, task: &mut Task) -> Result<()> {
3019 self.merge_stored(task);
3020 if let Some(boundary) = task.reassignments.last() {
3021 let stored = self.get(&task.id)?;
3022 anyhow::ensure!(
3023 task.reassignments == stored.reassignments
3024 && task.repo == stored.repo
3025 && task.runs.get(..boundary.run_boundary)
3026 == stored.runs.get(..boundary.run_boundary),
3027 "historical repository execution cannot be restarted; reload the task"
3028 );
3029 }
3030 self.write_record(task)
3031 }
3032
3033 pub(crate) fn commit_base_recovery(
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 "task changed during base recovery; inspect the pending authorization"
3043 );
3044 self.put_unlocked(task)
3046 }
3047
3048 pub(crate) fn commit_repair_grant(
3049 &self,
3050 task: &mut Task,
3051 expected: &serde_json::Value,
3052 ) -> Result<()> {
3053 let _lock = self.lock_task(&task.id)?;
3054 anyhow::ensure!(
3055 serde_json::to_value(self.get(&task.id)?)? == *expected,
3056 "repair grant refused: task changed during admission"
3057 );
3058 self.write_record(task)
3059 .context(crate::repair_budget::PublicationUnknown)
3060 }
3061
3062 pub(crate) fn commit_disk_wait(&self, task: &mut Task, expected: &Task) -> Result<()> {
3064 let _lock = self.lock_task(&task.id)?;
3065 anyhow::ensure!(
3066 serde_json::to_value(self.get(&task.id)?)? == serde_json::to_value(expected)?,
3067 "task changed during disk monitoring"
3068 );
3069 task.stamp_schema();
3070 self.write_record_inner(task, false)
3071 }
3072
3073 pub(crate) fn commit_reassignment(&self, task: &mut Task, expected: &Task) -> Result<()> {
3075 let _lock = self.lock_task(&task.id)?;
3076 let stored = self.get(&task.id)?;
3077 anyhow::ensure!(
3078 serde_json::to_value(&stored)? == serde_json::to_value(expected)?
3079 && stored.reassignments.len() + 1 == task.reassignments.len()
3080 && stored.repo == task.reassignments.last().expect("new boundary").from
3081 && stored.runs == task.runs,
3082 "task changed during reassignment; retry after inspecting it"
3083 );
3084 self.write_record(task)
3085 }
3086
3087 fn merge_stored(&self, task: &mut Task) {
3089 if let Ok(mut stored) = read_path(&self.path_of(&task.id)) {
3090 stored.import_chat_notice();
3091 if stored.reassignments.len() > task.reassignments.len() {
3092 let stale = std::mem::replace(task, stored.clone());
3095 for answer in stale.answers {
3096 if !task.answers.contains(&answer) {
3097 task.answers.push(answer);
3098 }
3099 }
3100 }
3101 if task.updated_at < stored.updated_at
3104 && (task.sync_only != stored.sync_only
3105 || stored.sync_only.is_some()
3106 || stored
3107 .recovery_budget_hold
3108 .as_ref()
3109 .is_some_and(|hold| hold.held_at > task.updated_at)
3110 || stored.repair_grants.last().is_some_and(|grant| {
3111 task.repair_grants.last() != Some(grant)
3112 || stored.operator_decided_at > task.operator_decided_at
3113 || stored
3114 .resume_override
3115 .as_ref()
3116 .is_some_and(|pin| pin.at > task.updated_at)
3117 || (task.resume_override != stored.resume_override
3118 && task
3119 .resume_override
3120 .as_ref()
3121 .is_some_and(|pin| pin.at == grant.at))
3122 }))
3123 && task
3124 .operator_decided_at
3125 .is_none_or(|at| at <= stored.updated_at)
3126 && task
3127 .resume_override
3128 .as_ref()
3129 .is_none_or(|pin| pin.at <= stored.updated_at)
3130 {
3131 *task = stored.clone();
3132 }
3133 for key in &stored.base_recovery_requests {
3134 if !task.base_recovery_requests.contains(key) {
3135 task.base_recovery_requests.push(key.clone());
3136 }
3137 }
3138 for receipt in &stored.repair_grants {
3139 if !task
3140 .repair_grants
3141 .iter()
3142 .any(|r| r.request.request == receipt.request.request)
3143 {
3144 task.repair_grants.push(receipt.clone());
3146 }
3147 }
3148 for receipt in &stored.repair_reconciliations {
3149 if !task.repair_reconciliations.contains(receipt) {
3150 task.repair_reconciliations.push(receipt.clone());
3153 task.resume_override = stored.resume_override.clone();
3154 task.status = stored.status;
3155 task.hold_source = stored.hold_source;
3156 task.machine_hold_cause = stored.machine_hold_cause.clone();
3157 task.disk_resume_run = stored.disk_resume_run.clone();
3158 task.disk_checked_at = stored.disk_checked_at;
3159 task.hold_reason = stored.hold_reason.clone();
3160 task.held_at = stored.held_at;
3161 }
3162 }
3163 task.superseded_resumes.extend(stored.superseded_resumes);
3164 task.dispatched_resumes.extend(stored.dispatched_resumes);
3165 if task.status != TaskStatus::Running
3166 && let Some(pin) = &stored.resume_override
3167 && !pin.question_id.is_empty()
3168 && let Some(run) = &pin.pinned_run
3169 && task.resume_override.as_ref().is_none_or(|next| {
3170 next.question_id != pin.question_id || next.pinned_run != pin.pinned_run
3171 })
3172 {
3173 task.superseded_resumes
3174 .insert(pin.question_id.clone(), run.clone());
3175 }
3176 for (id, receipt) in stored.decision_effects {
3179 task.decision_effects.insert(id, receipt);
3180 }
3181 if !task.decision_effects.is_empty() {
3182 task.stamp_schema();
3183 }
3184 if task.chat.is_none() {
3187 task.chat = stored.chat.clone();
3188 }
3189 for key in stored.chat_notices {
3190 if !task.chat_notices.contains(&key) {
3191 task.chat_notices.push(key);
3192 }
3193 }
3194 for failure in stored.startup_failures {
3195 task.record_startup_failure(failure);
3196 }
3197 for run in stored.runs {
3198 if !task.runs.contains(&run) {
3199 task.runs.push(run);
3200 }
3201 }
3202 for p in stored.passes {
3203 if !task
3204 .passes
3205 .iter()
3206 .any(|q| q.run == p.run && q.pass_index == p.pass_index)
3207 {
3208 task.passes.push(p);
3209 }
3210 }
3211 if let Some(n) = stored.chat_notice
3214 && task.chat_notice.as_ref().is_none_or(|mine| mine.at < n.at)
3215 {
3216 task.chat_notice = Some(n);
3217 }
3218 }
3219 }
3220
3221 pub(crate) fn write_startup_history(&self, task: &Task) -> Result<()> {
3224 let path = self.path_of(&task.id);
3225 let tmp = path.with_extension("json.tmp");
3226 std::fs::write(&tmp, serde_json::to_vec_pretty(task)?)?;
3227 std::fs::rename(tmp, path)?;
3228 Ok(())
3229 }
3230
3231 fn write_record(&self, task: &mut Task) -> Result<()> {
3233 self.write_record_inner(task, true)
3234 }
3235
3236 fn write_record_inner(&self, task: &mut Task, notify: bool) -> Result<()> {
3237 task.import_chat_notice();
3238 if task.status != TaskStatus::Held && task.sync_only.is_none() {
3239 task.recovery_budget_hold = None;
3240 }
3241 task.updated_at = Timestamp::now();
3242 std::fs::create_dir_all(&self.root)
3243 .with_context(|| format!("create {}", self.root.display()))?;
3244 let body = serde_json::to_string_pretty(task).context("serialize task")?;
3245 let path = self.path_of(&task.id);
3246 let tmp = path.with_extension("json.tmp");
3247 std::fs::write(&tmp, &body).with_context(|| format!("write {}", tmp.display()))?;
3248 std::fs::rename(&tmp, &path).with_context(|| format!("replace {}", path.display()))?;
3249 if let (Some(notice), Some(home)) = (
3254 notify.then(|| crate::notices::task_held(task)).flatten(),
3255 self.root.parent().filter(|p| !p.as_os_str().is_empty()),
3256 ) {
3257 crate::notices::raise_in(home, notice);
3258 }
3259 Ok(())
3260 }
3261
3262 pub fn modify(&self, id: &str, f: impl FnOnce(&mut Task) -> bool) -> Result<bool> {
3267 let id = self.resolve_id(id)?;
3268 let _lock = self.lock_task(&id)?;
3269 let mut task = self.get(&id)?;
3270 if !f(&mut task) {
3271 return Ok(false);
3272 }
3273 self.put_unlocked(&mut task)?;
3274 Ok(true)
3275 }
3276
3277 pub fn link_run(&self, id: &str, run: &str) -> Result<Task> {
3282 let id = self.resolve_id(id)?;
3283 let _lock = self.lock_task(&id)?;
3286 let mut task = self.get(&id)?;
3287 if task.link_run(run) {
3288 self.put_unlocked(&mut task)?;
3289 }
3290 Ok(task)
3291 }
3292
3293 pub(crate) fn lock_task(&self, id: &str) -> Result<TaskLock> {
3301 std::fs::create_dir_all(&self.root)
3302 .with_context(|| format!("create {}", self.root.display()))?;
3303 let path = self.root.join(format!("{id}.write-lock"));
3304 let started = std::time::Instant::now();
3305 let retry = crate::lock_file::Retry::task_write(started + TASK_LOCK_STALE);
3306 let marker_retry = crate::lock_file::Retry::new(Some(started + TASK_LOCK_STALE));
3307 loop {
3308 match retry.create(&path) {
3309 Ok(mut file) => {
3310 use std::io::Write;
3311 let token = owner_token();
3312 if let Err(e) = file.write_all(token.as_bytes()) {
3313 drop(file);
3314 let _ = std::fs::remove_file(&path);
3315 return Err(e).with_context(|| format!("lock {}", path.display()));
3316 }
3317 return Ok(TaskLock { path, token });
3318 }
3319 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
3320 let judged = std::fs::read_to_string(&path).ok();
3323 let broken = judged
3324 .filter(|_| older_than_stale(&path))
3325 .is_some_and(|judged| break_stale_with(&path, &judged, marker_retry));
3326 if !broken {
3330 if started.elapsed() > TASK_LOCK_STALE {
3331 bail!("could not lock task {id}");
3332 }
3333 std::thread::sleep(std::time::Duration::from_millis(15));
3334 }
3335 }
3336 Err(e) => return Err(e).with_context(|| format!("lock {}", path.display())),
3337 }
3338 }
3339 }
3340
3341 pub fn get(&self, id: &str) -> Result<Task> {
3343 let resolved = self.resolve_id(id)?;
3344 read_path(&self.path_of(&resolved))
3345 }
3346
3347 pub fn remove(&self, id: &str, in_flight: bool, questions: &Questions) -> Result<Removal> {
3379 self.remove_with_receipt(id, in_flight, questions, None)
3380 }
3381
3382 pub(crate) fn discard_triage(
3384 &self,
3385 id: &str,
3386 questions: &Questions,
3387 inquiry: &str,
3388 ) -> Result<Removal> {
3389 self.remove_with_receipt(id, false, questions, Some(inquiry))
3390 }
3391
3392 pub(crate) fn triage_discard_applied(&self, id: &str, inquiry: &str) -> Result<bool> {
3393 let path = self
3394 .root
3395 .join("triage-discard")
3396 .join(format!("{inquiry}.json"));
3397 let bytes = match std::fs::read(path) {
3398 Ok(bytes) => bytes,
3399 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(false),
3400 Err(e) => return Err(e.into()),
3401 };
3402 let receipt: Task = serde_json::from_slice(&bytes)?;
3403 Ok(receipt.id == id && !self.path_of(id).exists())
3404 }
3405
3406 fn remove_with_receipt(
3407 &self,
3408 id: &str,
3409 in_flight: bool,
3410 questions: &Questions,
3411 inquiry: Option<&str>,
3412 ) -> Result<Removal> {
3413 let resolved = self.resolve_id(id)?;
3414 if in_flight {
3415 bail!("task {resolved} is being run by a live daemon right now");
3416 }
3417 let receipt = inquiry.map(|q| self.root.join("triage-discard").join(format!("{q}.json")));
3418 if let Some(path) = &receipt {
3419 std::fs::create_dir_all(path.parent().expect("receipt directory"))?;
3420 }
3421 self.write_tombstone(&resolved)?;
3422 if let Err(e) = self.remove_record_with_attachments(&resolved, |p| match &receipt {
3423 Some(path) => std::fs::rename(p, path),
3424 None => std::fs::remove_file(p),
3425 }) {
3426 if self.path_of(&resolved).exists() {
3430 let _ = std::fs::remove_file(self.tombstone_path(&resolved));
3431 }
3432 return Err(e);
3433 }
3434 let (released, still_blocked) = self.release_dependents_of(&resolved, questions);
3435 Ok(Removal {
3436 id: resolved,
3437 released,
3438 still_blocked,
3439 })
3440 }
3441
3442 fn tombstone_path(&self, id: &str) -> PathBuf {
3445 self.root.join(format!("{id}.removed"))
3446 }
3447
3448 fn write_tombstone(&self, id: &str) -> Result<()> {
3449 let path = self.tombstone_path(id);
3450 let tmp = self.root.join(format!("{id}.removed.tmp"));
3451 std::fs::write(&tmp, b"")
3452 .and_then(|()| std::fs::rename(&tmp, &path))
3453 .with_context(|| format!("write {}", path.display()))
3454 }
3455
3456 fn was_deleted(&self, id: &str) -> bool {
3460 self.tombstone_path(id).is_file() && !self.path_of(id).exists()
3461 }
3462
3463 pub fn apply_deleted_blockers(&self, task: &mut Task, questions: &Questions) -> Vec<String> {
3467 let deleted = deleted_blockers(self, questions, &task.blocked_by);
3468 deleted
3469 .into_iter()
3470 .filter(|id| task.dependency_deleted(id))
3471 .collect()
3472 }
3473
3474 pub fn note_dependency_deleted(&self, dependent: &Task, deleted: &str) {
3478 let Some(home) = self.root.parent().filter(|p| !p.as_os_str().is_empty()) else {
3479 return;
3480 };
3481 let ja = crate::lang::is_japanese(&crate::lang::of_repo(&dependent.repo));
3482 let waiting = dependent.status == TaskStatus::Blocked;
3483 let message = match (ja, waiting) {
3484 (true, false) => format!(
3485 "タスク {} は、待っていた {} が削除されたため待機を解除し、元の状態に戻しました",
3486 dependent.short(),
3487 short(deleted)
3488 ),
3489 (true, true) => format!(
3490 "タスク {} は、待っていた {} が削除されたため、残りの依存を待っています",
3491 dependent.short(),
3492 short(deleted)
3493 ),
3494 (false, false) => format!(
3495 "Task {} stopped waiting on {} because it was deleted, and returned to its previous state",
3496 dependent.short(),
3497 short(deleted)
3498 ),
3499 (false, true) => format!(
3500 "Task {} stopped waiting on {} because it was deleted, and is still waiting on its other dependencies",
3501 dependent.short(),
3502 short(deleted)
3503 ),
3504 };
3505 crate::notices::raise_in(
3506 home,
3507 crate::notices::Notice::info(
3508 &format!("unblocked:{}:{}", dependent.id, deleted),
3509 message,
3510 )
3511 .link(crate::notices::Link::Task {
3512 id: dependent.id.clone(),
3513 }),
3514 );
3515 }
3516
3517 fn release_dependents_of(
3522 &self,
3523 dependency: &str,
3524 questions: &Questions,
3525 ) -> (Vec<String>, Vec<String>) {
3526 let (mut released, mut still_blocked) = (Vec::new(), Vec::new());
3527 for listed in self.list() {
3528 if listed.status != TaskStatus::Blocked || !listed.blocked_by.iter().any(|b| {
3529 matches!(crate::queue::dependency(self, questions, b), Dependency::Deleted(id) if id == dependency)
3530 }) {
3531 continue;
3532 }
3533 let Ok(_claim) = self.claim(&listed.id) else {
3534 continue;
3535 };
3536 let Ok(mut task) = self.get(&listed.id) else {
3537 continue;
3538 };
3539 let references: Vec<String> = task.blocked_by.iter().filter(|id| {
3540 matches!(crate::queue::dependency(self, questions, id), Dependency::Deleted(full) if full == dependency)
3541 }).cloned().collect();
3542 if references.is_empty() {
3543 continue;
3544 }
3545 for reference in references {
3546 task.dependency_deleted(&reference);
3547 }
3548 if self.put(&mut task).is_err() {
3549 continue;
3550 }
3551 self.note_dependency_deleted(&task, dependency);
3552 if task.status == TaskStatus::Blocked {
3553 still_blocked.push(task.id.clone());
3554 } else {
3555 released.push(task.id.clone());
3556 }
3557 }
3558 (released, still_blocked)
3559 }
3560
3561 fn remove_record_with_attachments(
3565 &self,
3566 resolved: &str,
3567 remove_record: impl FnOnce(&Path) -> std::io::Result<()>,
3568 ) -> Result<()> {
3569 self.sweep_removed_attachments();
3576 let attachments = self.attachments_dir(resolved);
3577 let aside = self.root.join(format!("{resolved}.attachments.removing"));
3578 let moved = match std::fs::rename(&attachments, &aside) {
3579 Ok(()) => true,
3580 Err(e) if e.kind() == std::io::ErrorKind::NotFound => false,
3581 Err(e) => {
3582 return Err(e).with_context(|| format!("remove {}", attachments.display()));
3583 }
3584 };
3585 let path = self.path_of(resolved);
3586 if let Err(e) = remove_record(&path) {
3587 if moved {
3588 let _ = std::fs::rename(&aside, &attachments);
3589 }
3590 return Err(e).with_context(|| format!("remove {}", path.display()));
3591 }
3592 if moved {
3593 if let Err(e) = std::fs::remove_dir_all(&aside) {
3594 tracing::warn!("leftover attachments {}: {e}", aside.display());
3595 }
3596 }
3597 let lock = self.lock_path(resolved);
3598 if let Err(e) = std::fs::remove_file(&lock) {
3599 if e.kind() != std::io::ErrorKind::NotFound {
3600 return Err(e).with_context(|| format!("remove {}", lock.display()));
3601 }
3602 }
3603 Ok(())
3604 }
3605
3606 fn sweep_removed_attachments(&self) {
3612 let Ok(entries) = std::fs::read_dir(&self.root) else {
3613 return;
3614 };
3615 for entry in entries.flatten() {
3616 let name = entry.file_name();
3617 let name = name.to_string_lossy();
3618 let Some(id) = name.strip_suffix(".attachments.removing") else {
3619 continue;
3620 };
3621 if !self.path_of(id).exists() {
3624 if let Err(e) = std::fs::remove_dir_all(entry.path()) {
3625 tracing::warn!("leftover attachments {}: {e}", entry.path().display());
3626 }
3627 }
3628 }
3629 self.sweep_tombstones();
3630 }
3631
3632 fn sweep_tombstones(&self) {
3641 let Ok(entries) = std::fs::read_dir(&self.root) else {
3642 return;
3643 };
3644 let tasks = self.list();
3645 for entry in entries.flatten() {
3646 let name = entry.file_name();
3647 let name = name.to_string_lossy();
3648 let Some(id) = name.strip_suffix(".removed") else {
3649 continue;
3650 };
3651 if self.path_of(id).exists()
3652 || tasks.iter().any(|t| {
3653 t.blocked_by
3654 .iter()
3655 .any(|b| id.starts_with(b) || id.ends_with(b))
3656 })
3657 {
3658 continue;
3659 }
3660 let old = entry
3661 .metadata()
3662 .and_then(|m| m.modified())
3663 .ok()
3664 .and_then(|m| m.elapsed().ok())
3665 .is_some_and(|age| age >= TOMBSTONE_GRACE);
3666 if old {
3667 let _ = std::fs::remove_file(entry.path());
3668 }
3669 }
3670 }
3671
3672 fn lock_path(&self, id: &str) -> PathBuf {
3675 self.root.join(format!("{id}.lock"))
3676 }
3677
3678 pub fn list(&self) -> Vec<Task> {
3691 #[cfg(test)]
3692 LIST_READS.with(|count| count.set(count.get() + 1));
3693 let mut tasks: Vec<Task> = 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_map(|p| read_path(&p).ok())
3700 .collect();
3701 tasks.sort_unstable_by(|a, b| b.priority.cmp(&a.priority).then_with(|| b.id.cmp(&a.id)));
3702 tasks
3703 }
3704
3705 pub fn unreadable(&self) -> Vec<PathBuf> {
3709 std::fs::read_dir(&self.root)
3710 .into_iter()
3711 .flatten()
3712 .flatten()
3713 .map(|e| e.path())
3714 .filter(|p| p.extension().is_some_and(|x| x == "json"))
3715 .filter(|p| read_path(p).is_err())
3716 .collect()
3717 }
3718
3719 pub fn superseded(&self) -> HashMap<String, String> {
3732 let mut by = HashMap::new();
3733 for task in self.list() {
3734 for earlier in &task.runs {
3735 if let Some(later) = task.successor_of(earlier) {
3736 by.insert(earlier.clone(), later.clone());
3737 }
3738 }
3739 }
3740 by
3741 }
3742
3743 pub fn superseded_by(&self, run: &str) -> Option<String> {
3751 for task in self.list() {
3752 if task.runs.iter().any(|r| r == run) {
3753 return task.successor_of(run).cloned();
3754 }
3755 }
3756 None
3757 }
3758
3759 pub fn latest_attempt(&self, run: &str) -> Option<String> {
3770 for task in self.list() {
3771 if task.runs.iter().any(|r| r == run) {
3772 return task.runs.last().filter(|last| **last != run).cloned();
3773 }
3774 }
3775 None
3776 }
3777
3778 pub fn next_runnable(&self) -> Option<Task> {
3783 let mut runnable: Vec<Task> = self
3784 .list()
3785 .into_iter()
3786 .filter(|t| t.status.runnable())
3787 .collect();
3788 runnable.sort_unstable_by(dispatch_order);
3789 runnable.into_iter().next()
3790 }
3791
3792 pub fn claim(&self, id: &str) -> Result<Claim> {
3799 std::fs::create_dir_all(&self.root)
3800 .with_context(|| format!("create {}", self.root.display()))?;
3801 let path = self.lock_path(id);
3802 let retry = crate::lock_file::Retry::new(None);
3803 match retry.create(&path) {
3804 Ok(mut f) => {
3805 use std::io::Write as _;
3806 let _ = writeln!(f, "{}", std::process::id());
3808 Ok(Claim { path })
3809 }
3810 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
3811 bail!("task {id} is already claimed ({} exists)", path.display())
3812 }
3813 Err(e) => Err(e).with_context(|| format!("lock {}", path.display())),
3814 }
3815 }
3816
3817 pub fn resolve_id(&self, prefix: &str) -> Result<String> {
3819 if !prefix.is_empty()
3820 && prefix != "."
3821 && prefix != ".."
3822 && !prefix.contains(['/', '\\'])
3823 && self.path_of(prefix).is_file()
3824 {
3825 return Ok(prefix.to_owned());
3826 }
3827 let ids = record_ids(&self.root, "json")?;
3828 match resolve_reference(prefix, ids.iter().map(String::as_str)) {
3829 Reference::Found(id) => Ok(id),
3830 Reference::Missing => bail!("no task matches `{prefix}`"),
3831 Reference::Ambiguous => bail!("`{prefix}` matches multiple tasks"),
3832 }
3833 }
3834
3835 pub fn revision(&self) -> u64 {
3842 self.revision_excluding(&std::collections::BTreeSet::new())
3843 }
3844
3845 pub fn revision_excluding(&self, skip: &std::collections::BTreeSet<String>) -> u64 {
3848 use std::hash::{Hash as _, Hasher as _};
3849
3850 let mut entries: Vec<(String, u64)> = std::fs::read_dir(&self.root)
3851 .into_iter()
3852 .flatten()
3853 .flatten()
3854 .filter(|e| e.path().extension().is_some_and(|ext| ext == "json"))
3855 .filter(|e| {
3856 let path = e.path();
3857 !path
3858 .file_stem()
3859 .is_some_and(|stem| skip.contains(stem.to_string_lossy().as_ref()))
3860 })
3861 .filter_map(|e| {
3862 let name = e.file_name().to_string_lossy().into_owned();
3863 let mtime = e
3864 .metadata()
3865 .ok()?
3866 .modified()
3867 .ok()?
3868 .duration_since(std::time::UNIX_EPOCH)
3869 .ok()?
3870 .as_millis() as u64;
3871 Some((name, mtime))
3872 })
3873 .collect();
3874
3875 if entries.is_empty() {
3876 return 0;
3877 }
3878
3879 entries.sort_unstable();
3880 let mut hasher = std::hash::DefaultHasher::new();
3881 for (name, mtime) in &entries {
3882 name.hash(&mut hasher);
3883 mtime.hash(&mut hasher);
3884 }
3885 let h = hasher.finish();
3886 if h == 0 { 1 } else { h }
3887 }
3888}
3889
3890const TOMBSTONE_GRACE: std::time::Duration = std::time::Duration::from_secs(3600);
3893
3894#[derive(Debug, Clone)]
3896pub struct Removal {
3897 pub id: String,
3899 pub released: Vec<String>,
3903 pub still_blocked: Vec<String>,
3906}
3907
3908#[derive(Debug)]
3910pub struct Claim {
3911 path: PathBuf,
3912}
3913
3914impl Drop for Claim {
3915 fn drop(&mut self) {
3916 let _ = std::fs::remove_file(&self.path);
3917 }
3918}
3919
3920pub fn title_from(instruction: &str, max: usize) -> String {
3923 let Some(line) = first_line(instruction) else {
3924 return "(empty task)".to_owned();
3925 };
3926 if line.chars().count() <= max {
3927 return line.to_owned();
3928 }
3929 let head: String = line.chars().take(max.saturating_sub(1)).collect();
3930 format!("{head}…")
3931}
3932
3933pub(crate) fn first_line(instruction: &str) -> Option<&str> {
3939 let line = instruction
3940 .lines()
3941 .map(str::trim)
3942 .find(|l| !l.is_empty())?
3943 .trim_start_matches(['#', '-', '*', '>', ' '])
3944 .trim();
3945 (!line.is_empty()).then_some(line)
3946}
3947
3948#[cfg(test)]
3949thread_local! {
3950 pub(crate) static TASK_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3951}
3952
3953fn read_path(path: &Path) -> Result<Task> {
3954 #[cfg(test)]
3955 TASK_READS.with(|count| count.set(count.get() + 1));
3956 let body = std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;
3957 let mut task: Task =
3958 serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))?;
3959 if task.schema > SCHEMA {
3965 bail!(
3966 "task {} was written by a different magi (schema {}, this build \
3967 speaks {SCHEMA})",
3968 task.id,
3969 task.schema
3970 );
3971 }
3972 task.preserve_legacy_build_cache();
3973 if task.schema < 22
3974 && task.status == TaskStatus::Held
3975 && task.hold_source == Some(HoldSource::Machine)
3976 && task.resume_override.is_none()
3977 && task
3978 .hold_reason
3979 .as_deref()
3980 .is_some_and(crate::disk::is_gate_reason)
3981 {
3982 task.mark_disk_capacity();
3983 }
3984 Ok(task)
3985}
3986
3987#[derive(Debug, PartialEq, Eq)]
3990pub(crate) enum Reference {
3991 Found(String),
3992 Missing,
3993 Ambiguous,
3994}
3995
3996pub(crate) fn resolve_reference<'a>(id: &str, ids: impl Iterator<Item = &'a str>) -> Reference {
3997 let mut hits = Vec::new();
3998 for candidate in ids {
3999 if candidate == id {
4000 return Reference::Found(candidate.to_owned());
4001 }
4002 if candidate.starts_with(id) || candidate.ends_with(id) {
4003 hits.push(candidate);
4004 }
4005 }
4006 match hits.as_slice() {
4007 [] => Reference::Missing,
4008 [one] => Reference::Found((*one).to_owned()),
4009 _ => Reference::Ambiguous,
4010 }
4011}
4012
4013pub(crate) fn record_ids(root: &Path, extension: &str) -> Result<Vec<String>> {
4016 let entries = match std::fs::read_dir(root) {
4017 Ok(entries) => entries,
4018 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
4019 Err(e) => return Err(e.into()),
4020 };
4021 let mut ids = Vec::new();
4022 for entry in entries {
4023 let path = entry?.path();
4024 if path.extension().is_some_and(|e| e == extension)
4025 && let Some(id) = path.file_stem().and_then(|s| s.to_str())
4026 {
4027 ids.push(id.to_owned());
4028 }
4029 }
4030 Ok(ids)
4031}
4032
4033#[derive(Debug, PartialEq, Eq)]
4036pub enum Dependency {
4037 Task(String),
4039 Question(String),
4041 Deleted(String),
4043 Missing,
4045 Ambiguous,
4047 Unknown,
4049}
4050
4051pub fn dependency(queue: &Queue, questions: &Questions, id: &str) -> Dependency {
4053 let (Ok(tasks), Ok(qs), Ok(removed)) = (
4054 record_ids(queue.root(), "json"),
4055 record_ids(questions.root(), "json"),
4056 record_ids(queue.root(), "removed"),
4057 ) else {
4058 return Dependency::Unknown;
4059 };
4060 let mut ids = tasks
4063 .iter()
4064 .chain(qs.iter())
4065 .chain(removed.iter())
4066 .cloned()
4067 .collect::<Vec<_>>();
4068 ids.sort();
4069 ids.dedup();
4070 match resolve_reference(id, ids.iter().map(String::as_str)) {
4071 Reference::Found(id) if tasks.contains(&id) => Dependency::Task(id),
4072 Reference::Found(id) if qs.contains(&id) => Dependency::Question(id),
4073 Reference::Found(id) if queue.was_deleted(&id) => Dependency::Deleted(id),
4074 Reference::Found(_) => Dependency::Unknown,
4075 Reference::Missing => Dependency::Missing,
4076 Reference::Ambiguous => Dependency::Ambiguous,
4077 }
4078}
4079
4080pub fn normalize_blockers(queue: &Queue, questions: &Questions, ids: &mut [String]) {
4082 for id in ids {
4083 if let Dependency::Task(full) | Dependency::Question(full) | Dependency::Deleted(full) =
4084 dependency(queue, questions, id)
4085 {
4086 *id = full;
4087 }
4088 }
4089}
4090
4091pub fn dependency_facts(queue: &Queue, questions: &Questions) -> String {
4094 let inventory = crate::blockers::Inventory::load(queue, questions);
4095 let mut text = String::from(
4096 "Current authoritative queue (historical missing-task claims may be stale; unreadable or ambiguous references must keep waiting):\n",
4097 );
4098 match record_ids(queue.root(), "json") {
4099 Ok(ids) => {
4100 for id in ids {
4101 match queue.get(&id) {
4102 Ok(task) => text.push_str(&format!(
4103 "{}: {}; blocked_by={:?}; chain={:?}\n",
4104 task.id,
4105 task.status.as_str(),
4106 task.blocked_by,
4107 inventory.waits_on(&task)
4108 )),
4109 Err(_) => text.push_str(&format!("{id}: exists, state unreadable\n")),
4110 }
4111 }
4112 }
4113 Err(_) => text.push_str("Queue inventory unreadable: existence is unknown.\n"),
4114 }
4115 text
4116}
4117
4118pub fn missing_blockers(
4120 queue: &Queue,
4121 questions: &Questions,
4122 blocked_by: &[String],
4123) -> Vec<String> {
4124 blocked_by
4125 .iter()
4126 .filter(|id| dependency(queue, questions, id) == Dependency::Missing)
4127 .cloned()
4128 .collect()
4129}
4130
4131pub fn deleted_blockers(
4134 queue: &Queue,
4135 questions: &Questions,
4136 blocked_by: &[String],
4137) -> Vec<String> {
4138 blocked_by
4139 .iter()
4140 .filter(|id| matches!(dependency(queue, questions, id), Dependency::Deleted(_)))
4141 .cloned()
4142 .collect()
4143}
4144
4145pub fn missing_blocker_hold_reason(blocked_by: &[String], missing: &[String]) -> String {
4157 missing_blocker_hold_reason_in(blocked_by, missing, "en")
4158}
4159
4160pub fn missing_blocker_hold_reason_in(
4162 blocked_by: &[String],
4163 missing: &[String],
4164 language: &str,
4165) -> String {
4166 if crate::lang::is_japanese(language) {
4167 format!(
4168 "{} を待っていましたが、{} はディスク上に存在しません - `magi task triage` を参照",
4169 blocked_by.join(", "),
4170 missing.join(", "),
4171 )
4172 } else {
4173 format!(
4174 "blocked on {} but {} no longer exist(s) on disk - see `magi task triage`",
4175 blocked_by.join(", "),
4176 missing.join(", "),
4177 )
4178 }
4179}
4180
4181pub fn short(id: &str) -> &str {
4183 id.split('-').next_back().unwrap_or(id)
4184}
4185
4186fn new_id() -> String {
4187 let stamp = jiff::Zoned::now().strftime("%Y%m%d-%H%M%S");
4188 let seed = crate::rng::entropy();
4189 format!("{stamp}-{:04x}", (seed ^ (seed >> 32)) & 0xffff)
4190}
4191
4192#[cfg(test)]
4193mod tests {
4194 #[test]
4195 fn reassignment_clears_repository_bound_execution_selections() {
4196 let mut task = Task::new(
4197 "move".into(),
4198 "evidence".into(),
4199 "old".into(),
4200 Source::Human,
4201 );
4202 task.review_branch = Some("old-review".into());
4203 task.review_instruction = Some("old criteria".into());
4204 task.pr_recovery = Some(crate::pr_recovery::Selection {
4205 url: "https://example.invalid/pull/1".into(),
4206 branch: "old-pr".into(),
4207 head: "head".into(),
4208 source_head: None,
4209 source_run: None,
4210 source_proof: None,
4211 disposition: None,
4212 instruction: "old criteria".into(),
4213 approved_at: Timestamp::now(),
4214 });
4215 task.replacement = Some(crate::merge_decision::Replacement {
4216 question: "owner".into(),
4217 run: "old-run".into(),
4218 pr: "https://example.invalid/pull/1".into(),
4219 agent: "worker".into(),
4220 context: "evidence".into(),
4221 });
4222 task.resume_override = Some(OperatorResume {
4223 question_id: "old-question".into(),
4224 at: Timestamp::now(),
4225 conductor_rehold: None,
4226 forced: true,
4227 pinned_run: Some("old-run".into()),
4228 });
4229 task.interrupt = true;
4230 task.reassign_repository("new".into(), "test");
4231 assert!(task.review_branch.is_none());
4232 assert!(task.review_instruction.is_none());
4233 assert!(task.pr_recovery.is_none());
4234 assert!(task.replacement.is_none());
4235 assert!(task.resume_override.is_none());
4236 assert!(!task.interrupt);
4237 assert!(task.fresh_start);
4238 assert_eq!(task.instruction, "evidence");
4239 }
4240
4241 #[test]
4242 fn explicit_resumption_is_not_invented_for_legacy_or_automatic_release() {
4243 let t = Task::new(
4244 "retry".into(),
4245 "do it".into(),
4246 PathBuf::from("."),
4247 Source::Human,
4248 );
4249 let mut value = serde_json::to_value(&t).unwrap();
4250 for field in ["resumption", "resumption_history", "operator_decided_at"] {
4251 value.as_object_mut().unwrap().remove(field);
4252 }
4253 value["schema"] = serde_json::json!(15);
4254 let mut legacy: Task = serde_json::from_value(value).unwrap();
4255 legacy.hold_machine(Some("automatic retry".into()));
4256 legacy.release();
4257 assert!(legacy.resumption.is_none());
4258 assert!(legacy.resumption_history.is_empty());
4259 assert!(legacy.operator_decided_at.is_none());
4260 legacy.release_operator("cli", None);
4261 legacy.start("run".into());
4262 let reloaded: Task =
4263 serde_json::from_str(&serde_json::to_string(&legacy).unwrap()).unwrap();
4264 assert!(reloaded.resume_override.is_none());
4265 assert_eq!(reloaded.resumption.as_ref().unwrap().generation, 1);
4266 }
4267
4268 #[test]
4269 fn merge_over_lets_the_later_choice_win_and_keeps_the_rest() {
4270 let mut base = RunOverrides {
4271 merge: Some("pr".to_owned()),
4272 candidates: Some(3),
4273 ..RunOverrides::default()
4274 };
4275 base.merge_over(&RunOverrides {
4276 merge: Some("none".to_owned()),
4277 seed: Some(7),
4278 ..RunOverrides::default()
4279 });
4280 assert_eq!(base.merge.as_deref(), Some("none"));
4281 assert_eq!(base.candidates, Some(3));
4282 assert_eq!(base.seed, Some(7));
4283 }
4284
4285 #[test]
4286 fn an_already_landed_task_is_done_with_its_attempt_refunded() {
4287 let mut t = task("relanded");
4288 t.attempts = 1;
4289 t.status = TaskStatus::Running;
4290 t.already_landed("already in main as 0e368de");
4291 assert_eq!(t.status, TaskStatus::Done);
4292 assert_eq!(t.attempts, 0);
4293 assert!(t.hold_reason.is_none());
4294 assert_eq!(t.last_error.as_deref(), Some("already in main as 0e368de"));
4295 }
4296
4297 #[test]
4298 fn missing_blocker_reason_follows_the_language() {
4299 let b = vec!["a".to_owned()];
4300 let en = missing_blocker_hold_reason_in(&b, &b, "en");
4301 assert_eq!(en, missing_blocker_hold_reason(&b, &b));
4302 assert!(en.starts_with("blocked on a"));
4303 assert!(missing_blocker_hold_reason_in(&b, &b, "ja").contains("存在しません"));
4304 assert_eq!(missing_blocker_hold_reason_in(&b, &b, "de"), en);
4305 }
4306
4307 use super::*;
4308
4309 #[test]
4310 fn triage_applied_survives_release_and_old_records_read_as_empty() {
4311 let mut t = Task::new(
4312 "t".to_owned(),
4313 "i".to_owned(),
4314 PathBuf::from("r"),
4315 Source::Human,
4316 );
4317 t.mark_triage_applied("q1");
4318 t.mark_triage_applied("q1");
4319 t.hold_machine(Some("x".to_owned()));
4320 t.release();
4321 assert_eq!(t.triage_applied, ["q1"]);
4322 assert!(t.triage_applied("q1") && !t.triage_applied("q2"));
4323
4324 let mut v = serde_json::to_value(&t).unwrap();
4325 v.as_object_mut().unwrap().remove("triage_applied");
4326 let old: Task = serde_json::from_value(v).unwrap();
4327 assert!(old.triage_applied.is_empty());
4328 }
4329
4330 #[test]
4331 fn task_counts_of_empty_is_all_zero() {
4332 assert_eq!(TaskCounts::of(&[]), TaskCounts::default());
4333 }
4334
4335 #[test]
4336 fn task_counts_of_tallies_every_status() {
4337 let mut queued = Task::new(
4338 "q".to_owned(),
4339 "i".to_owned(),
4340 PathBuf::from("."),
4341 Source::Human,
4342 );
4343 queued.status = TaskStatus::Queued;
4344 let mut running = queued.clone();
4345 running.status = TaskStatus::Running;
4346 let mut done = queued.clone();
4347 done.status = TaskStatus::Done;
4348 let mut failed = queued.clone();
4349 failed.status = TaskStatus::Failed;
4350 let mut held = queued.clone();
4351 held.status = TaskStatus::Held;
4352 let mut blocked = queued.clone();
4353 blocked.status = TaskStatus::Blocked;
4354
4355 let mut parked = queued.clone();
4356 parked.status = TaskStatus::Parked;
4357
4358 let counts = TaskCounts::of(&[
4359 queued,
4360 running,
4361 done.clone(),
4362 done,
4363 failed,
4364 held,
4365 blocked,
4366 parked,
4367 ]);
4368 assert_eq!(
4369 counts,
4370 TaskCounts {
4371 queued: 1,
4372 running: 1,
4373 done: 2,
4374 failed: 1,
4375 held: 1,
4376 blocked: 1,
4377 parked: 1,
4378 }
4379 );
4380 }
4381
4382 #[test]
4383 fn task_implementers_persist_normalized_without_losing_history() {
4384 let (_dir, q) = queue();
4385 let mut t = task("keep me");
4386 t.hold_manual(Some("waiting".into()));
4387 t.runs.push("earlier-run".into());
4388 t.attachments.push("reference.txt".into());
4389 let cfg: crate::config::Config =
4390 toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
4391 .unwrap();
4392 q.put(&mut t).unwrap();
4393 let original = serde_json::to_value(&t).unwrap();
4394 for n in [2, 1, 2] {
4395 t.set_implementers(n, &cfg).unwrap();
4396 q.put(&mut t).unwrap();
4397 t = q.get(&t.id).unwrap();
4398 assert_eq!(t.implementers(), Some(usize::from(n)));
4399 assert_eq!(t.solo, n == 1);
4400 if n == 1 {
4401 assert!(t.overrides.is_none());
4402 }
4403 let mut actual = serde_json::to_value(&t).unwrap();
4404 for field in ["solo", "overrides", "updated_at"] {
4405 actual[field] = original[field].clone();
4406 }
4407 assert_eq!(actual, original);
4408 }
4409 t.overrides.as_mut().unwrap().judges = Some(2);
4410 t.set_implementers(1, &cfg).unwrap();
4411 assert_eq!(t.overrides.as_ref().unwrap().judges, Some(2));
4412 assert_eq!(t.overrides.as_ref().unwrap().candidates, None);
4413 }
4414
4415 #[test]
4416 fn task_implementers_old_records_keep_inheritance_until_changed() {
4417 let mut value = serde_json::to_value(task("old task")).unwrap();
4418 value.as_object_mut().unwrap().remove("solo");
4419 value.as_object_mut().unwrap().remove("overrides");
4420 let mut old: Task = serde_json::from_value(value).unwrap();
4421 assert_eq!(old.implementers(), None);
4422 old.set_implementers(1, &crate::config::Config::default())
4423 .unwrap();
4424 assert!(old.solo);
4425 assert!(old.overrides.is_none());
4426 }
4427
4428 #[test]
4429 fn task_implementers_reject_invalid_counts_and_states() {
4430 let cfg = crate::config::Config::default();
4431 let mut t = task("unchanged");
4432 for n in [0, 4, 255] {
4433 assert!(t.set_implementers(n, &cfg).is_err());
4434 }
4435 for status in [
4436 TaskStatus::Running,
4437 TaskStatus::Done,
4438 TaskStatus::Failed,
4439 TaskStatus::Blocked,
4440 TaskStatus::Parked,
4441 ] {
4442 t.status = status;
4443 let before = serde_json::to_value(&t).unwrap();
4444 assert!(t.set_implementers(1, &cfg).is_err());
4445 assert_eq!(serde_json::to_value(&t).unwrap(), before);
4446 }
4447 }
4448
4449 fn queue() -> (tempfile::TempDir, Queue) {
4452 let dir = tempfile::tempdir().unwrap();
4453 let q = Queue::at(dir.path().join("queue"));
4454 (dir, q)
4455 }
4456
4457 #[test]
4458 fn base_recovery_commit_retains_decision_and_superseded_resume_evidence() {
4459 let (_dir, q) = queue();
4460 let mut original = task("base recovery");
4461 original
4462 .decision_effects
4463 .insert("old-effect".into(), "receipt".into());
4464 original
4465 .dispatched_resumes
4466 .insert("dispatched".into(), "prior-run".into());
4467 original.resume_override = Some(OperatorResume {
4468 question_id: "prior-decision".into(),
4469 at: Timestamp::now(),
4470 conductor_rehold: None,
4471 forced: true,
4472 pinned_run: Some("retained-run".into()),
4473 });
4474 q.put(&mut original).unwrap();
4475 let expected = serde_json::to_value(&original).unwrap();
4476 let mut recovered = original.clone();
4477 recovered.base_recovery_requests.push("chat/request".into());
4478 recovered
4479 .resume_override
4480 .as_mut()
4481 .unwrap()
4482 .question_id
4483 .clear();
4484 q.commit_base_recovery(&mut recovered, &expected).unwrap();
4485 let saved = q.get(&original.id).unwrap();
4486 assert_eq!(saved.decision_effects, original.decision_effects);
4487 assert_eq!(saved.dispatched_resumes, original.dispatched_resumes);
4488 assert_eq!(
4489 saved
4490 .superseded_resumes
4491 .get("prior-decision")
4492 .map(String::as_str),
4493 Some("retained-run")
4494 );
4495 assert_eq!(saved.base_recovery_requests, ["chat/request"]);
4496 assert!(saved.resume_override.unwrap().question_id.is_empty());
4497 assert!(q.commit_base_recovery(&mut recovered, &expected).is_err());
4498 }
4499
4500 #[test]
4501 fn a_stale_write_does_not_drop_the_recorded_task_chat() {
4502 let (_dir, q) = queue();
4503 let mut stale = task("chat");
4504 q.put(&mut stale).unwrap();
4505 let mut fresh = q.get(&stale.id).unwrap();
4506 fresh.chat = Some("talk-1".to_owned());
4507 q.put(&mut fresh).unwrap();
4508 q.put(&mut stale).unwrap();
4509 assert_eq!(q.get(&stale.id).unwrap().chat.as_deref(), Some("talk-1"));
4510 }
4511
4512 #[test]
4513 fn putting_a_machine_held_task_files_a_notification_beside_the_queue() {
4514 let dir = tempfile::tempdir().unwrap();
4515 let q = Queue::at(dir.path().join("queue"));
4516 let mut t = task("held");
4517 q.put(&mut t).unwrap();
4518 assert_eq!(
4519 crate::notices::Notices::at(dir.path().join("notifications"))
4520 .list()
4521 .len(),
4522 0
4523 );
4524 t.hold_machine(Some("out of attempts".to_owned()));
4525 q.put(&mut t).unwrap();
4526 let listed = crate::notices::Notices::at(dir.path().join("notifications")).list();
4527 assert_eq!(listed.len(), 1);
4528 assert!(listed[0].message.contains("out of attempts"));
4529 }
4530
4531 #[test]
4532 fn start_consumes_the_disk_resume_pin() {
4533 let mut t = task("pin");
4534 t.disk_resume_run = Some("run-1".into());
4535 t.start("run-1".into());
4536 assert!(t.disk_resume_run.is_none());
4537 }
4538
4539 fn task(title: &str) -> Task {
4540 Task::new(
4541 title.to_owned(),
4542 format!("do {title}"),
4543 PathBuf::from("."),
4544 Source::Human,
4545 )
4546 }
4547
4548 #[test]
4549 fn attempt_limit_inherits_old_records_and_controls_failure() {
4550 let mut t = task("budget");
4551 let mut old = serde_json::to_value(&t).unwrap();
4552 old.as_object_mut().unwrap().remove("attempt_limit");
4553 old["schema"] = serde_json::json!(15);
4554 let legacy: Task = serde_json::from_value(old).unwrap();
4555 assert_eq!(legacy.attempt_limit, None);
4556 assert_eq!(legacy.effective_attempt_limit(2), 2);
4557 t.attempts = 2;
4558 t.change_attempt_limit(NonZeroUsize::new(3)).unwrap();
4559 t.fail("retry", 1);
4560 assert_eq!(t.status, TaskStatus::Failed);
4561 t.attempts = 3;
4562 t.fail("stop", 10);
4563 assert_eq!(t.status, TaskStatus::Held);
4564 t.change_attempt_limit(None).unwrap();
4565 assert_eq!(t.status, TaskStatus::Held);
4566 assert_eq!(t.attempts, 3);
4567 t.fail("inherit", 4);
4568 assert_eq!(t.status, TaskStatus::Failed);
4569 for status in [
4570 TaskStatus::Running,
4571 TaskStatus::Done,
4572 TaskStatus::Failed,
4573 TaskStatus::Blocked,
4574 TaskStatus::Parked,
4575 ] {
4576 t.status = status;
4577 assert!(t.change_attempt_limit(NonZeroUsize::new(1)).is_err());
4578 assert_eq!(t.attempt_limit, None);
4579 }
4580 }
4581
4582 #[test]
4583 fn earlier_attempts_is_every_recorded_run_and_agrees_with_the_display() {
4584 let mut t = task("retried");
4585 assert!(
4586 t.earlier_attempts().is_empty(),
4587 "a first attempt takes nothing over"
4588 );
4589 t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned()];
4590 assert_eq!(t.earlier_attempts(), ["aaaa", "bbbb"]);
4591 assert_eq!(t.successor_of("aaaa"), Some(&"bbbb".to_owned()));
4593 assert_eq!(t.successor_of("bbbb"), None);
4594 assert_eq!(t.successor_of("zzzz"), None);
4595 }
4596
4597 #[test]
4598 fn resumed_runs_are_superseded_only_after_their_last_occurrence() {
4599 let (_dir, q) = queue();
4600 let mut t = task("resumed");
4601 for (runs, successor) in [
4602 (vec!["aaaa", "aaaa"], None),
4603 (vec!["aaaa", "bbbb", "aaaa"], None),
4604 (vec!["aaaa", "aaaa", "bbbb"], Some("bbbb")),
4605 (vec!["aaaa", "bbbb", "aaaa", "cccc"], Some("cccc")),
4606 ] {
4607 t.runs = runs.into_iter().map(str::to_owned).collect();
4608 q.put(&mut t).unwrap();
4609
4610 assert_eq!(t.successor_of("aaaa").map(String::as_str), successor);
4611 assert_eq!(q.superseded_by("aaaa").as_deref(), successor);
4612 assert_eq!(q.superseded().get("aaaa").map(String::as_str), successor);
4613 }
4614 }
4615
4616 #[test]
4617 fn superseded_by_names_the_next_attempt_and_none_for_the_last() {
4618 let (_dir, q) = queue();
4619 let mut t = task("retried");
4620 t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned(), "cccc".to_owned()];
4621 q.put(&mut t).unwrap();
4622
4623 assert_eq!(q.superseded_by("aaaa"), Some("bbbb".to_owned()));
4624 assert_eq!(q.superseded_by("bbbb"), Some("cccc".to_owned()));
4625 assert_eq!(
4626 q.superseded_by("cccc"),
4627 None,
4628 "the latest attempt replaces nothing"
4629 );
4630 assert_eq!(
4631 q.superseded_by("never-heard-of-it"),
4632 None,
4633 "a run belonging to no task on this queue is not superseded"
4634 );
4635
4636 let mut by = HashMap::new();
4637 by.insert("aaaa".to_owned(), "bbbb".to_owned());
4638 by.insert("bbbb".to_owned(), "cccc".to_owned());
4639 assert_eq!(
4640 q.superseded(),
4641 by,
4642 "the whole-map and single-run forms must agree"
4643 );
4644 }
4645
4646 #[test]
4647 fn superseded_attempts_is_empty_until_the_task_is_done() {
4648 let mut t = task("retried");
4649 t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned()];
4650 t.status = TaskStatus::Failed;
4651 assert_eq!(
4652 t.superseded_attempts(true),
4653 &[] as &[String],
4654 "a task still retrying has no attempt yet that a later one made moot"
4655 );
4656
4657 t.status = TaskStatus::Running;
4658 assert_eq!(t.superseded_attempts(true), &[] as &[String]);
4659 }
4660
4661 #[test]
4662 fn superseded_attempts_names_every_run_before_the_one_that_succeeded() {
4663 let mut t = task("retried");
4664 t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned(), "cccc".to_owned()];
4665 t.status = TaskStatus::Done;
4666 assert_eq!(
4667 t.superseded_attempts(true),
4668 &["aaaa".to_owned(), "bbbb".to_owned()],
4669 "cccc is the attempt whose success made the task done, and stays out"
4670 );
4671 }
4672
4673 #[test]
4674 fn superseded_attempts_is_empty_for_a_done_task_with_only_one_attempt() {
4675 let mut t = task("first try landed");
4676 t.runs = vec!["aaaa".to_owned()];
4677 t.status = TaskStatus::Done;
4678 assert_eq!(t.superseded_attempts(true), &[] as &[String]);
4679 }
4680
4681 #[test]
4682 fn superseded_attempts_is_empty_when_the_last_run_never_actually_succeeded() {
4683 let mut t = task("closed by hand after a manual merge");
4690 t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned()];
4691 t.status = TaskStatus::Done;
4692 assert_eq!(
4693 t.superseded_attempts(false),
4694 &[] as &[String],
4695 "nothing here is provably why the task is done, so nothing is superseded"
4696 );
4697 }
4698
4699 #[test]
4700 fn latest_attempt_names_the_chain_s_current_head_not_just_the_next_one() {
4701 let (_dir, q) = queue();
4702 let mut t = task("retried twice");
4703 t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned(), "cccc".to_owned()];
4704 q.put(&mut t).unwrap();
4705
4706 assert_eq!(
4707 q.latest_attempt("aaaa"),
4708 Some("cccc".to_owned()),
4709 "an old attempt points straight at the chain's current head, not the \
4710 next attempt in the middle of it"
4711 );
4712 assert_eq!(q.latest_attempt("bbbb"), Some("cccc".to_owned()));
4713 assert_eq!(
4714 q.latest_attempt("cccc"),
4715 None,
4716 "the latest attempt is not superseded by anything"
4717 );
4718 assert_eq!(
4719 q.latest_attempt("never-heard-of-it"),
4720 None,
4721 "a run belonging to no task on this queue is not superseded"
4722 );
4723 }
4724
4725 #[test]
4726 fn a_markdown_heading_is_the_title_not_decoration() {
4727 assert_eq!(
4732 title_from("# Rework the config loader\n\nIt re-reads it.\n", 40),
4733 "Rework the config loader"
4734 );
4735 assert_eq!(title_from("- fix the thing", 40), "fix the thing");
4736 assert_eq!(title_from("> quoted task", 40), "quoted task");
4737 assert_eq!(title_from(" \n\n", 40), "(empty task)");
4739 assert_eq!(title_from("###\n", 40), "(empty task)");
4740 }
4741
4742 #[test]
4743 fn a_long_title_is_elided_by_characters_not_bytes() {
4744 let long = "課題".repeat(30);
4746 let title = title_from(&long, 10);
4747 assert_eq!(title.chars().count(), 10);
4748 assert!(title.ends_with('…'));
4749 }
4750
4751 #[test]
4752 fn priority_wins_and_ties_break_oldest_first() {
4753 let (_dir, q) = queue();
4754 let mut a = task("first");
4755 let mut b = task("second");
4756 let mut c = task("urgent");
4757 a.id = "20260101-000001-aaaa".to_owned();
4759 b.id = "20260101-000002-bbbb".to_owned();
4760 c.id = "20260101-000003-cccc".to_owned();
4761 c.priority = 5;
4762 for t in [&mut a, &mut b, &mut c] {
4763 q.put(t).unwrap();
4764 }
4765
4766 assert_eq!(q.next_runnable().unwrap().id, c.id);
4768 c.hold_machine(None);
4769 q.put(&mut c).unwrap();
4770 assert_eq!(q.next_runnable().unwrap().id, a.id);
4772 assert_eq!(q.list().len(), 3, "b is still waiting its turn");
4773 }
4774
4775 #[test]
4776 fn a_blocked_task_never_starves_another_runnable_one() {
4777 let (_dir, q) = queue();
4778 let mut blocked = task("blocked");
4779 blocked.block(vec!["something".to_owned()], None);
4780 q.put(&mut blocked).unwrap();
4781
4782 let mut runnable = task("free to go");
4783 q.put(&mut runnable).unwrap();
4784
4785 let next = q.next_runnable().expect("a runnable task is still offered");
4786 assert_eq!(next.id, runnable.id);
4787 }
4788
4789 #[test]
4790 fn a_held_task_is_never_offered_to_the_loop() {
4791 let (_dir, q) = queue();
4792 let mut t = task("held");
4793 q.put(&mut t).unwrap();
4794 assert!(q.next_runnable().is_some());
4795
4796 t.hold_machine(None);
4797 q.put(&mut t).unwrap();
4798 assert!(
4799 q.next_runnable().is_none(),
4800 "a held task must wait for a human"
4801 );
4802
4803 t.status = TaskStatus::Failed;
4805 q.put(&mut t).unwrap();
4806 assert!(q.next_runnable().is_some());
4807 }
4808
4809 #[test]
4810 fn attempts_are_capped_and_then_the_task_is_held() {
4811 let mut t = task("doomed");
4812
4813 t.start("run-1".to_owned());
4814 t.fail("gate red", 2);
4815 assert_eq!(t.status, TaskStatus::Failed, "one attempt of two: retry");
4816
4817 t.start("run-2".to_owned());
4818 t.fail("gate red", 2);
4819 assert_eq!(
4820 t.status,
4821 TaskStatus::Held,
4822 "out of attempts: stop spending money on it"
4823 );
4824 assert_eq!(t.runs, ["run-1", "run-2"]);
4825 assert_eq!(t.last_error.as_deref(), Some("gate red"));
4826 assert_eq!(
4827 t.hold_reason.as_deref(),
4828 Some("gate red"),
4829 "the hold must say why, not leave hold_reason null next to a \
4830 populated last_error"
4831 );
4832 }
4833
4834 #[test]
4835 fn handing_off_a_task_records_a_hold_reason_too() {
4836 let mut t = task("left a pull request");
4837 t.start("run-1".to_owned());
4838 t.handed_off("run ended with a pull request open [run run-1]");
4839 assert_eq!(t.status, TaskStatus::Held);
4840 assert_eq!(t.hold_source, Some(HoldSource::Machine));
4841 assert_eq!(
4842 t.hold_reason.as_deref(),
4843 Some("run ended with a pull request open [run run-1]")
4844 );
4845 assert_eq!(t.hold_reason, t.last_error);
4846 }
4847
4848 #[test]
4849 fn a_quota_stall_is_refunded_so_the_backlog_survives_the_night() {
4850 let mut t = task("stalled by quota");
4851
4852 t.start("run-1".to_owned());
4853 assert_eq!(t.attempts, 1);
4854 t.stall("judge-1, judge-2 out of quota");
4855 assert_eq!(
4856 t.attempts, 0,
4857 "a closed quota window must not spend the task's retry budget"
4858 );
4859 assert_eq!(t.status, TaskStatus::Failed, "the loop should retry it");
4860 assert_eq!(
4861 t.last_error.as_deref(),
4862 Some("judge-1, judge-2 out of quota")
4863 );
4864
4865 for _ in 0..20 {
4868 t.start("run-n".to_owned());
4869 t.stall("still out of quota");
4870 }
4871 t.start("run-real".to_owned());
4872 t.fail("gate red", 2);
4873 assert_eq!(
4874 t.status,
4875 TaskStatus::Failed,
4876 "the first attempt that was really judged is attempt one"
4877 );
4878 }
4879
4880 #[test]
4881 fn releasing_a_held_task_gives_it_a_real_second_chance() {
4882 let mut t = task("retry me");
4883 t.start("run-1".to_owned());
4884 t.fail("gate red", 1);
4885 assert_eq!(t.status, TaskStatus::Held);
4886
4887 t.release();
4888 assert_eq!(t.status, TaskStatus::Queued);
4889 assert_eq!(t.attempts, 0);
4892 assert!(t.last_error.is_none());
4893 assert_eq!(
4894 t.runs.len(),
4895 1,
4896 "history is kept: attempts reset, evidence does not"
4897 );
4898 }
4899
4900 #[test]
4901 fn a_hold_reason_survives_and_a_release_clears_it() {
4902 let mut t = task("waiting on something else");
4903 t.hold_manual(Some(
4904 "waiting for 20260101-000000-aaaa to land first".to_owned(),
4905 ));
4906 assert_eq!(t.status, TaskStatus::Held);
4907 assert_eq!(
4908 t.hold_reason.as_deref(),
4909 Some("waiting for 20260101-000000-aaaa to land first")
4910 );
4911
4912 t.hold_manual(None);
4914 assert_eq!(
4915 t.hold_reason.as_deref(),
4916 Some("waiting for 20260101-000000-aaaa to land first"),
4917 "a bare re-hold keeps whatever a human already wrote down"
4918 );
4919
4920 let mut plain = task("no reason given");
4922 plain.hold_manual(None);
4923 assert_eq!(plain.status, TaskStatus::Held);
4924 assert!(plain.hold_reason.is_none());
4925
4926 t.release();
4927 assert_eq!(t.status, TaskStatus::Queued);
4928 assert!(
4929 t.hold_reason.is_none(),
4930 "a stale reason must not greet the next person who holds this task"
4931 );
4932 }
4933
4934 #[test]
4935 fn closing_a_held_task_as_done_clears_its_hold_reason_too() {
4936 let mut t = task("landed by hand while held");
4941 t.hold_manual(Some("waiting on 3ed9".to_owned()));
4942 assert_eq!(t.hold_reason.as_deref(), Some("waiting on 3ed9"));
4943
4944 t.succeed();
4945 assert_eq!(t.status, TaskStatus::Done);
4946 assert!(
4947 t.hold_reason.is_none(),
4948 "a done task cannot still be waiting on something"
4949 );
4950 }
4951
4952 #[test]
4953 fn holding_or_closing_a_blocked_task_clears_its_dependency_too() {
4954 let mut held = task("held straight out of blocked");
4961 held.block(
4962 vec!["20260101-000000-dead".to_owned()],
4963 Some("waiting on the migration script".to_owned()),
4964 );
4965 assert_eq!(held.status, TaskStatus::Blocked);
4966
4967 held.hold_manual(None);
4968 assert_eq!(held.status, TaskStatus::Held);
4969 assert!(
4970 held.blocked_by.is_empty(),
4971 "hold overrides the wait, same as release"
4972 );
4973 assert!(held.block_reason.is_none());
4974
4975 let mut done = task("closed straight out of blocked");
4976 done.block(
4977 vec!["20260101-000000-dead".to_owned()],
4978 Some("waiting on the migration script".to_owned()),
4979 );
4980 done.succeed();
4981 assert_eq!(done.status, TaskStatus::Done);
4982 assert!(
4983 done.blocked_by.is_empty(),
4984 "a done task cannot still be waiting on a dependency"
4985 );
4986 assert!(done.block_reason.is_none());
4987 }
4988
4989 #[test]
4990 fn a_blocked_task_is_never_offered_to_the_loop() {
4991 let mut t = task("blocked");
4992 assert!(t.status.runnable());
4993 t.block(
4994 vec!["dep-id".to_owned()],
4995 Some("waits on dep-id".to_owned()),
4996 );
4997 assert_eq!(t.status, TaskStatus::Blocked);
4998 assert!(!t.status.runnable());
4999 assert_eq!(TaskStatus::Blocked.as_str(), "blocked");
5000 }
5001
5002 #[test]
5003 fn unblocking_the_last_dependency_returns_the_task_to_queued() {
5004 let mut t = task("blocked on two");
5005 t.block(
5006 vec!["a".to_owned(), "b".to_owned()],
5007 Some("waits on a and b".to_owned()),
5008 );
5009
5010 t.unblock("a");
5011 assert_eq!(t.status, TaskStatus::Blocked, "b is still outstanding");
5012 assert_eq!(t.blocked_by, ["b"]);
5013
5014 t.unblock("b");
5015 assert_eq!(t.status, TaskStatus::Queued);
5016 assert!(t.blocked_by.is_empty());
5017 assert!(t.block_reason.is_none());
5018 }
5019
5020 #[test]
5021 fn unblocking_an_id_on_a_task_that_is_not_blocked_is_a_no_op() {
5022 let mut t = task("never blocked");
5023 t.unblock("whatever");
5024 assert_eq!(t.status, TaskStatus::Queued);
5025 }
5026
5027 #[test]
5028 fn a_held_task_blocked_on_a_question_returns_to_held_not_queued() {
5029 let mut t = task("held, then asked about");
5034 t.hold_machine(Some("out of attempts".to_owned()));
5035 assert_eq!(t.status, TaskStatus::Held);
5036
5037 t.block(vec!["q1".to_owned()], Some("what now?".to_owned()));
5038 assert_eq!(t.status, TaskStatus::Blocked);
5039
5040 t.record_answer("what now?".to_owned(), "leave it held".to_owned());
5041 t.unblock("q1");
5042 assert_eq!(t.status, TaskStatus::Held, "must restore, not requeue");
5043 assert_eq!(t.hold_reason.as_deref(), Some("out of attempts"));
5044 assert_eq!(t.hold_source, Some(HoldSource::Machine));
5045 assert!(t.blocked_from.is_none(), "consumed once restored");
5046 }
5047
5048 #[test]
5049 fn a_manually_held_task_blocked_on_a_question_returns_to_held() {
5050 let mut t = task("manually held, then asked about");
5051 t.hold_manual(Some("waiting on a dependency".to_owned()));
5052
5053 t.block(vec!["q1".to_owned()], None);
5054 t.unblock("q1");
5055
5056 assert_eq!(t.status, TaskStatus::Held);
5057 assert_eq!(t.hold_source, Some(HoldSource::Manual));
5058 }
5059
5060 #[test]
5061 fn re_blocking_an_already_blocked_task_keeps_the_original_blocked_from() {
5062 let mut t = task("held, blocked twice");
5066 t.hold_machine(None);
5067 t.block(vec!["q1".to_owned()], Some("first".to_owned()));
5068 t.block(
5069 vec!["q1".to_owned(), "q2".to_owned()],
5070 Some("second".to_owned()),
5071 );
5072
5073 t.unblock("q1");
5074 assert_eq!(t.status, TaskStatus::Blocked, "q2 still outstanding");
5075 t.unblock("q2");
5076 assert_eq!(t.status, TaskStatus::Held);
5077 }
5078
5079 #[test]
5080 fn unblocking_a_task_blocked_while_running_lands_on_queued_not_running() {
5081 let mut t = task("blocked mid-run");
5085 t.start("run-1".to_owned());
5086 assert_eq!(t.status, TaskStatus::Running);
5087
5088 t.block(vec!["q1".to_owned()], None);
5089 t.unblock("q1");
5090 assert_eq!(t.status, TaskStatus::Queued);
5091 }
5092
5093 #[test]
5094 fn a_pre_schema_4_blocked_record_with_hold_evidence_restores_to_held() {
5095 let mut t = task("legacy record, held before it was blocked");
5101 t.hold_source = Some(HoldSource::Machine);
5102 t.hold_reason = Some("legacy hold reason".to_owned());
5103 t.status = TaskStatus::Blocked;
5104 t.blocked_by = vec!["q1".to_owned()];
5105 t.blocked_from = None;
5106
5107 t.unblock("q1");
5108 assert_eq!(t.status, TaskStatus::Held);
5109 }
5110
5111 #[test]
5112 fn a_pre_schema_4_blocked_record_with_no_hold_evidence_restores_to_queued() {
5113 let mut t = task("legacy record, ordinary dependency block");
5114 t.status = TaskStatus::Blocked;
5115 t.blocked_by = vec!["dep".to_owned()];
5116 t.blocked_from = None;
5117
5118 t.unblock("dep");
5119 assert_eq!(t.status, TaskStatus::Queued);
5120 }
5121
5122 #[test]
5123 fn answering_a_question_is_recorded_and_survives_a_release() {
5124 let mut t = task("asked something");
5125 t.block(vec!["q1".to_owned()], Some("which backend?".to_owned()));
5126 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
5127 t.unblock("q1");
5128 assert_eq!(t.status, TaskStatus::Queued);
5129 assert_eq!(t.answers.len(), 1);
5130 assert_eq!(t.answers[0].answer, "SQLite");
5131
5132 t.release();
5136 assert_eq!(t.answers.len(), 1, "the answer is not lost on release");
5137 }
5138
5139 #[test]
5140 fn resumption_review_branch_requires_unchanged_authored_criteria() {
5141 for source in ["cli", "web"] {
5142 let mut t = task("review old candidate");
5143 t.request_review("candidate-A".into());
5144 t.hold_for_handover(Some("candidate-A".into()), "handover refused".into());
5145 let mut unchanged = t.clone();
5146 unchanged.release_operator(source, None);
5147 assert_eq!(unchanged.review_branch.as_deref(), Some("candidate-A"));
5148 t.edit(
5149 "review approved head".into(),
5150 "Reuse measured PR head B; fix Clippy; review".into(),
5151 )
5152 .unwrap();
5153 t.release_operator(source, None);
5154 assert!(t.review_branch.is_none());
5155 assert!(t.review_instruction.is_none());
5156 let mut legacy = unchanged;
5158 legacy.review_instruction = None;
5159 legacy.hold_for_handover(None, "still checked out".into());
5160 legacy
5161 .edit("new plan".into(), "Reuse measured PR head B".into())
5162 .unwrap();
5163 legacy.release_operator(source, None);
5164 assert!(legacy.review_branch.is_none());
5165 }
5166 }
5167
5168 #[test]
5169 fn a_refused_handover_keeps_the_review_branch_across_release() {
5170 let mut t = task("refused takeover");
5171 t.start("run-1".to_owned());
5172 t.hold_for_handover(Some("magi/eba2/A".to_owned()), "checked out".to_owned());
5173 assert_eq!(t.status, TaskStatus::Held);
5174 assert_eq!(t.attempts, 1);
5175 t.release();
5176 assert_eq!(t.status, TaskStatus::Queued);
5177 assert_eq!(t.attempts, 0);
5178 assert_eq!(t.review_branch.as_deref(), Some("magi/eba2/A"));
5179
5180 t.hold_for_handover(None, "again".to_owned());
5182 t.requeue();
5183 assert!(t.review_branch.is_none());
5184
5185 let mut m = task("manual");
5187 m.review_branch = Some("magi/x/A".to_owned());
5188 m.hold_manual(None);
5189 m.release();
5190 assert!(m.review_branch.is_none());
5191 }
5192
5193 #[test]
5194 fn requesting_review_requeues_the_task_and_remembers_the_branch() {
5195 let mut t = task("blocked run with a surviving branch");
5196 t.start("run-1".to_owned());
5197 t.fail("blocked with major findings", 5);
5198 assert_eq!(t.status, TaskStatus::Failed);
5199
5200 t.request_review("magi/eba2/A".to_owned());
5201 assert_eq!(t.status, TaskStatus::Queued);
5202 assert_eq!(t.attempts, 0);
5203 assert_eq!(t.review_branch.as_deref(), Some("magi/eba2/A"));
5204
5205 t.release();
5207 assert!(t.review_branch.is_none());
5208 }
5209
5210 #[test]
5211 fn conductor_requeue_but_not_an_ordinary_release_forces_a_fresh_start() {
5212 let mut t = task("retry");
5213 t.start("run-1".to_owned());
5214 t.requeue();
5215 assert!(t.fresh_start);
5216
5217 t.release();
5218 assert!(!t.fresh_start);
5219 }
5220
5221 #[test]
5222 fn urgent_only_changes_queued_or_held_and_preserves_settings() {
5223 for status in [
5224 TaskStatus::Queued,
5225 TaskStatus::Held,
5226 TaskStatus::Running,
5227 TaskStatus::Done,
5228 TaskStatus::Failed,
5229 TaskStatus::Blocked,
5230 TaskStatus::Parked,
5231 ] {
5232 let mut t = task("urgent settings");
5233 t.status = status;
5234 t.attempts = 2;
5235 t.hold_reason = Some("waiting".into());
5236 t.priority = 7;
5237 t.interrupt = true;
5238 let before = serde_json::to_value(&t).unwrap();
5239 for urgent in [true, true, false, false] {
5240 let result = t.set_urgent(urgent);
5241 let mut expected = before.clone();
5242 if matches!(status, TaskStatus::Queued | TaskStatus::Held) {
5243 result.unwrap();
5244 expected["urgent"] = urgent.into();
5245 } else {
5246 let error = result.unwrap_err().to_string();
5247 assert!(error.contains(status.as_str()), "{error}");
5248 assert!(error.contains("queued or held"), "{error}");
5249 }
5250 assert_eq!(serde_json::to_value(&t).unwrap(), expected);
5251 }
5252 }
5253 }
5254
5255 #[test]
5256 fn priority_can_be_changed_while_queued_but_not_while_running() {
5257 let mut t = task("reprioritise me");
5258 t.set_priority(5).unwrap();
5259 assert_eq!(t.priority, 5);
5260
5261 t.start("run-1".to_owned());
5262 let err = t.set_priority(9).unwrap_err().to_string();
5263 assert!(err.contains("running"), "{err}");
5264 assert_eq!(t.priority, 5, "the rejected write must not partially apply");
5265 }
5266
5267 #[test]
5268 fn interrupt_can_be_marked_while_queued_but_not_while_running() {
5269 let mut t = task("interrupt me");
5270 assert!(!t.interrupt, "off unless asked, same as any other task");
5271
5272 t.set_interrupt(true).unwrap();
5273 assert!(t.interrupt);
5274
5275 t.start("run-1".to_owned());
5276 assert!(
5277 !t.interrupt,
5278 "the mark is one-shot: dispatching the task fulfils it, \
5279 whatever the run that follows ends up doing"
5280 );
5281 let err = t.set_interrupt(true).unwrap_err().to_string();
5282 assert!(err.contains("running"), "{err}");
5283 t.set_interrupt(false).unwrap();
5286 assert!(!t.interrupt);
5287 }
5288
5289 #[test]
5293 fn a_failed_run_does_not_leave_the_task_still_marked_to_interrupt() {
5294 let mut t = task("interrupt me");
5295 t.set_interrupt(true).unwrap();
5296 t.start("run-1".to_owned());
5297 t.fail("mock failure", 5);
5298 assert_eq!(t.status, TaskStatus::Failed);
5299 assert!(
5300 !t.interrupt,
5301 "one attempt already spent the mark; a retry is an ordinary \
5302 requeue, not a fresh interrupt request"
5303 );
5304 }
5305
5306 #[test]
5307 fn changing_priority_moves_a_task_ahead_in_the_real_queue_order() {
5308 let (_dir, q) = queue();
5309 let mut a = task("first filed");
5310 let mut b = task("second filed");
5311 a.id = "20260101-000001-aaaa".to_owned();
5312 b.id = "20260101-000002-bbbb".to_owned();
5313 q.put(&mut a).unwrap();
5314 q.put(&mut b).unwrap();
5315
5316 assert_eq!(
5317 q.next_runnable().unwrap().id,
5318 a.id,
5319 "with equal priority the older task goes first, so a burst of \
5320 new work cannot starve it"
5321 );
5322 assert_eq!(
5323 q.list()[0].id,
5324 b.id,
5325 "but the list an operator reads is newest first, the same as \
5326 before priority existed - a's turn to run does not make it the \
5327 newest task"
5328 );
5329
5330 let mut a = q.get(&a.id).unwrap();
5331 a.set_priority(10).unwrap();
5332 q.put(&mut a).unwrap();
5333
5334 assert_eq!(
5335 q.next_runnable().unwrap().id,
5336 a.id,
5337 "a raised priority must be reflected the moment it is saved"
5338 );
5339 assert_eq!(
5343 q.list()[0].id,
5344 a.id,
5345 "the raised task must sort first in the list an operator reads, \
5346 not only in next_runnable's own ordering"
5347 );
5348 }
5349
5350 #[test]
5351 fn editing_replaces_title_and_instruction_but_keeps_identity_and_history() {
5352 let mut t = Task::new(
5353 "old title".to_owned(),
5354 "old instruction".to_owned(),
5355 PathBuf::from("/repo"),
5356 Source::Agent {
5357 run: "20260101-000000-beef".to_owned(),
5358 node: "implement".to_owned(),
5359 },
5360 );
5361 let id = t.id.clone();
5362 let created_at = t.created_at;
5363 t.runs.push("20260101-000000-beef".to_owned());
5364
5365 t.edit("new title".to_owned(), "new instruction".to_owned())
5366 .unwrap();
5367
5368 assert_eq!(t.title, "new title");
5369 assert_eq!(t.instruction, "new instruction");
5370 assert_eq!(t.id, id, "editing must not mint a new id");
5371 assert_eq!(t.created_at, created_at);
5372 assert_eq!(
5373 t.source,
5374 Source::Agent {
5375 run: "20260101-000000-beef".to_owned(),
5376 node: "implement".to_owned(),
5377 },
5378 "editing must not turn agent attribution into human"
5379 );
5380 assert_eq!(t.runs, ["20260101-000000-beef"]);
5381 }
5382
5383 #[test]
5384 fn editing_is_refused_once_a_task_is_running_or_finished() {
5385 let mut running = task("in flight");
5386 running.start("run-1".to_owned());
5387 let err = running
5388 .edit("x".to_owned(), "y".to_owned())
5389 .unwrap_err()
5390 .to_string();
5391 assert!(err.contains("running"), "{err}");
5392
5393 let mut done = task("finished");
5394 done.succeed();
5395 let err = done
5396 .edit("x".to_owned(), "y".to_owned())
5397 .unwrap_err()
5398 .to_string();
5399 assert!(err.contains("done"), "{err}");
5400
5401 let mut queued = task("waiting");
5403 queued.edit("x".to_owned(), "y".to_owned()).unwrap();
5404 let mut held = task("parked");
5405 held.hold_machine(None);
5406 held.edit("x".to_owned(), "y".to_owned()).unwrap();
5407 }
5408
5409 #[test]
5410 fn a_task_recorded_without_a_hold_reason_still_reads_as_none() {
5411 let (_dir, q) = queue();
5412 let path = q.path_of("20260101-000000-aaaa");
5413 std::fs::create_dir_all(q.root()).unwrap();
5414 std::fs::write(
5415 &path,
5416 serde_json::json!({
5417 "schema": SCHEMA,
5418 "id": "20260101-000000-aaaa",
5419 "title": "from before hold reasons existed",
5420 "instruction": "from before hold reasons existed",
5421 "repo": ".",
5422 "source": { "kind": "human" },
5423 "status": "held",
5424 "created_at": Timestamp::now().to_string(),
5425 "updated_at": Timestamp::now().to_string(),
5426 })
5427 .to_string(),
5428 )
5429 .unwrap();
5430
5431 let task = q.get("20260101-000000-aaaa").expect("must still read");
5432 assert!(task.hold_reason.is_none());
5433 assert!(task.operator_held());
5434 }
5435
5436 #[test]
5437 fn a_legacy_reasoned_hold_defaults_to_operator_protection() {
5438 let (_dir, q) = queue();
5439 let path = q.path_of("20260101-000000-bbbb");
5440 std::fs::create_dir_all(q.root()).unwrap();
5441 std::fs::write(
5442 &path,
5443 serde_json::json!({
5444 "schema": 2,
5445 "id": "20260101-000000-bbbb",
5446 "title": "old manual recovery",
5447 "instruction": "old manual recovery",
5448 "repo": ".",
5449 "source": { "kind": "human" },
5450 "status": "held",
5451 "hold_reason": "active manual recovery run20260912-224242-daf5",
5452 "created_at": Timestamp::now().to_string(),
5453 "updated_at": Timestamp::now().to_string(),
5454 })
5455 .to_string(),
5456 )
5457 .unwrap();
5458
5459 let task = q.get("20260101-000000-bbbb").expect("must still read");
5460 assert_eq!(task.hold_source, None);
5461 assert!(task.operator_held());
5462 }
5463
5464 #[test]
5465 fn a_task_recorded_without_a_diagnostic_still_reads_as_none() {
5466 let (_dir, q) = queue();
5467 let path = q.path_of("20260101-000000-aaaa");
5468 std::fs::create_dir_all(q.root()).unwrap();
5469 std::fs::write(
5470 &path,
5471 serde_json::json!({
5472 "schema": SCHEMA,
5473 "id": "20260101-000000-aaaa",
5474 "title": "from before diagnostics existed",
5475 "instruction": "from before diagnostics existed",
5476 "repo": ".",
5477 "source": { "kind": "human" },
5478 "status": "held",
5479 "created_at": Timestamp::now().to_string(),
5480 "updated_at": Timestamp::now().to_string(),
5481 })
5482 .to_string(),
5483 )
5484 .unwrap();
5485
5486 let task = q.get("20260101-000000-aaaa").expect("must still read");
5487 assert!(task.diagnostic.is_none());
5488 }
5489
5490 #[test]
5491 fn a_schema_1_task_with_no_blocking_fields_still_reads() {
5492 let (_dir, q) = queue();
5496 let path = q.path_of("20260101-000000-aaaa");
5497 std::fs::create_dir_all(q.root()).unwrap();
5498 std::fs::write(
5499 &path,
5500 serde_json::json!({
5501 "schema": 1,
5502 "id": "20260101-000000-aaaa",
5503 "title": "from before blocking existed",
5504 "instruction": "from before blocking existed",
5505 "repo": ".",
5506 "source": { "kind": "human" },
5507 "status": "queued",
5508 "created_at": Timestamp::now().to_string(),
5509 "updated_at": Timestamp::now().to_string(),
5510 })
5511 .to_string(),
5512 )
5513 .unwrap();
5514
5515 let task = q.get("20260101-000000-aaaa").expect("must still read");
5516 assert!(task.blocked_by.is_empty());
5517 assert!(task.block_reason.is_none());
5518 assert!(task.answers.is_empty());
5519 assert!(task.review_branch.is_none());
5520 }
5521
5522 #[test]
5523 fn releasing_or_finishing_a_task_clears_its_stale_diagnostic() {
5524 let mut held = task("diagnosed");
5529 held.start("run-1".to_owned());
5530 held.fail("gate red", 1);
5531 held.diagnostic = Some("cargo test failed: ...".to_owned());
5532 assert_eq!(held.status, TaskStatus::Held);
5533
5534 held.release();
5535 assert!(held.diagnostic.is_none());
5536
5537 held.diagnostic = Some("cargo test failed: ...".to_owned());
5538 held.succeed();
5539 assert!(held.diagnostic.is_none());
5540 }
5541
5542 #[test]
5543 fn failing_a_task_always_clears_whatever_diagnostic_it_carried() {
5544 let mut t = task("retried");
5545 t.start("run-1".to_owned());
5546 t.diagnostic = Some("stale evidence from a previous hold".to_owned());
5547 t.fail("unrelated config error", 5);
5548 assert_eq!(t.status, TaskStatus::Failed);
5549 assert!(
5550 t.diagnostic.is_none(),
5551 "fail() must not let an old diagnostic outlive the run that produced it"
5552 );
5553 }
5554
5555 #[test]
5556 fn a_claim_is_exclusive_and_releases_on_drop() {
5557 let (_dir, q) = queue();
5558 let mut t = task("contended");
5559 q.put(&mut t).unwrap();
5560
5561 let held = q.claim(&t.id).unwrap();
5562 assert!(
5563 q.claim(&t.id).is_err(),
5564 "two daemons must not drive one task into two runs"
5565 );
5566 drop(held);
5567 assert!(q.claim(&t.id).is_ok(), "a released claim is reclaimable");
5568 }
5569
5570 #[test]
5571 fn a_round_trip_survives_disk() {
5572 let (_dir, q) = queue();
5573 let mut t = Task::new(
5574 "titled".to_owned(),
5575 "body".to_owned(),
5576 PathBuf::from("/repo"),
5577 Source::Agent {
5578 run: "20260101-000000-beef".to_owned(),
5579 node: "implement".to_owned(),
5580 },
5581 );
5582 t.priority = 3;
5583 q.put(&mut t).unwrap();
5584
5585 let back = q.get(&t.id).unwrap();
5586 assert_eq!(back.id, t.id);
5587 assert_eq!(back.priority, 3);
5588 assert_eq!(back.source.label(), "implement@beef");
5589 assert_eq!(q.get(t.short()).unwrap().id, t.id);
5591 }
5592
5593 #[test]
5594 fn an_unreadable_task_does_not_take_the_queue_down() {
5595 let (_dir, q) = queue();
5596 let mut t = task("fine");
5597 q.put(&mut t).unwrap();
5598 std::fs::write(q.root().join("broken.json"), "{ not json").unwrap();
5599
5600 let listed = q.list();
5601 assert_eq!(listed.len(), 1, "the readable task still lists");
5602 assert_eq!(listed[0].id, t.id);
5603 }
5604
5605 #[test]
5606 fn a_task_recorded_without_a_solo_field_still_reads_as_not_solo() {
5607 let (_dir, q) = queue();
5608 let path = q.path_of("20260101-000000-aaaa");
5609 std::fs::create_dir_all(q.root()).unwrap();
5610 std::fs::write(
5611 &path,
5612 serde_json::json!({
5613 "schema": SCHEMA,
5614 "id": "20260101-000000-aaaa",
5615 "title": "from before solo existed",
5616 "instruction": "from before solo existed",
5617 "repo": ".",
5618 "source": { "kind": "human" },
5619 "status": "queued",
5620 "created_at": Timestamp::now().to_string(),
5621 "updated_at": Timestamp::now().to_string(),
5622 })
5623 .to_string(),
5624 )
5625 .unwrap();
5626
5627 let task = q.get("20260101-000000-aaaa").expect("must still read");
5628 assert!(!task.solo, "a queue file with no `solo` field means false");
5629 }
5630
5631 #[test]
5632 fn a_task_recorded_without_an_urgent_field_still_reads_as_not_urgent() {
5633 let (_dir, q) = queue();
5634 let path = q.path_of("20260101-000000-bbbb");
5635 std::fs::create_dir_all(q.root()).unwrap();
5636 std::fs::write(
5637 &path,
5638 serde_json::json!({
5639 "schema": SCHEMA,
5640 "id": "20260101-000000-bbbb",
5641 "title": "from before urgent existed",
5642 "instruction": "from before urgent existed",
5643 "repo": ".",
5644 "source": { "kind": "human" },
5645 "status": "queued",
5646 "created_at": Timestamp::now().to_string(),
5647 "updated_at": Timestamp::now().to_string(),
5648 })
5649 .to_string(),
5650 )
5651 .unwrap();
5652
5653 let task = q.get("20260101-000000-bbbb").expect("must still read");
5654 assert!(
5655 !task.urgent,
5656 "a queue file with no `urgent` field means false, same as `solo`"
5657 );
5658 }
5659
5660 #[test]
5661 fn a_task_from_a_future_schema_is_refused_rather_than_guessed_at() {
5662 let (_dir, q) = queue();
5663 let mut t = task("from the future");
5664 q.put(&mut t).unwrap();
5665 let path = q.path_of(&t.id);
5666 let body = std::fs::read_to_string(&path)
5667 .unwrap()
5668 .replace(&format!("\"schema\": {SCHEMA}"), "\"schema\": 99");
5669 std::fs::write(&path, body).unwrap();
5670
5671 let err = q.get(&t.id).unwrap_err().to_string();
5672 assert!(err.contains("schema 99"), "{err}");
5673 }
5674
5675 #[test]
5676 fn revision_moves_when_the_queue_changes() {
5677 let (_dir, q) = queue();
5678 assert_eq!(q.revision(), 0, "an empty queue has no revision");
5679 let mut t = task("first");
5680 q.put(&mut t).unwrap();
5681 assert!(q.revision() > 0, "a written task moves the revision");
5682 }
5683
5684 #[test]
5685 fn revision_moves_when_deleting_an_older_task() {
5686 let (dir, q) = queue();
5687 let questions = Questions::at(dir.path().join("questions"));
5688 let mut t1 = task("older");
5689 q.put(&mut t1).unwrap();
5690 std::thread::sleep(std::time::Duration::from_millis(10));
5692 let mut t2 = task("newer");
5693 q.put(&mut t2).unwrap();
5694
5695 let rev_before = q.revision();
5696 q.remove(&t1.id, false, &questions).unwrap();
5697 let rev_after = q.revision();
5698
5699 assert_ne!(
5700 rev_before, rev_after,
5701 "deleting an older task must change the revision so other clients see the deletion"
5702 );
5703 }
5704
5705 #[test]
5706 fn removing_a_task_takes_it_out_of_the_listing() {
5707 let (dir, q) = queue();
5708 let questions = Questions::at(dir.path().join("questions"));
5709 let mut t = task("delete me");
5710 q.put(&mut t).unwrap();
5711 let removed = q.remove(t.short(), false, &questions).unwrap();
5712 assert_eq!(removed.id, t.id, "a prefix resolves before deleting");
5713 assert!(removed.released.is_empty() && removed.still_blocked.is_empty());
5714 assert!(q.list().is_empty());
5715 assert!(
5716 q.remove(&t.id, false, &questions).is_err(),
5717 "removing twice is an error"
5718 );
5719 }
5720
5721 #[test]
5722 fn removing_a_task_takes_its_stale_lock_with_it() {
5723 let (dir, q) = queue();
5724 let questions = Questions::at(dir.path().join("questions"));
5725 let mut t = task("interrupted");
5726 q.put(&mut t).unwrap();
5727
5728 let claim = q.claim(&t.id).unwrap();
5731 std::mem::forget(claim);
5732 assert!(
5733 q.claim(&t.id).is_err(),
5734 "the orphaned lock is what makes the task look claimed"
5735 );
5736
5737 let err = q.remove(&t.id, true, &questions).unwrap_err().to_string();
5739 assert!(err.contains("live daemon"), "{err}");
5740 assert!(q.get(&t.id).is_ok(), "a refused delete keeps the task");
5741
5742 q.remove(&t.id, false, &questions).unwrap();
5744 assert!(q.list().is_empty());
5745 let mut again = task("interrupted");
5746 again.id = t.id.clone();
5747 q.put(&mut again).unwrap();
5748 assert!(
5749 q.claim(&t.id).is_ok(),
5750 "a task that comes back must be claimable, which a left-behind lock would prevent"
5751 );
5752 }
5753
5754 fn notices_of(dir: &Path) -> Vec<crate::notices::Notice> {
5755 crate::notices::Notices::at(dir.join("notifications")).list()
5756 }
5757
5758 #[test]
5759 fn removing_a_sole_dependency_releases_the_dependent_without_a_hold() {
5760 let (dir, q) = queue();
5761 let questions = Questions::at(dir.path().join("questions"));
5762 let mut dep = task("dependency");
5763 q.put(&mut dep).unwrap();
5764 let mut blocked = task("waiting");
5765 blocked.block(vec![dep.id.clone()], Some("waits".to_owned()));
5766 q.put(&mut blocked).unwrap();
5767
5768 let removed = q.remove(&dep.id, false, &questions).unwrap();
5769 assert_eq!(removed.released, [blocked.id.clone()]);
5770 assert!(removed.still_blocked.is_empty());
5771
5772 let after = q.get(&blocked.id).unwrap();
5773 assert_eq!(after.status, TaskStatus::Queued);
5774 assert!(after.blocked_by.is_empty());
5775 assert!(after.block_reason.is_none());
5776 let notes = notices_of(dir.path());
5777 assert_eq!(notes.len(), 1, "{notes:?}");
5778 assert_eq!(notes[0].severity, crate::notices::Severity::Info);
5779 assert_eq!(
5780 notes[0].link,
5781 Some(crate::notices::Link::Task {
5782 id: blocked.id.clone(),
5783 })
5784 );
5785 }
5786
5787 #[test]
5788 fn removing_one_of_two_dependencies_keeps_the_other() {
5789 let (dir, q) = queue();
5790 let questions = Questions::at(dir.path().join("questions"));
5791 let mut dep = task("dependency");
5792 q.put(&mut dep).unwrap();
5793 let mut other = task("other");
5794 q.put(&mut other).unwrap();
5795 let mut blocked = task("waiting");
5796 blocked.block(
5797 vec![dep.id.clone(), other.id.clone()],
5798 Some("waits on both".to_owned()),
5799 );
5800 q.put(&mut blocked).unwrap();
5801
5802 let removed = q.remove(&dep.id, false, &questions).unwrap();
5803 assert!(removed.released.is_empty());
5804 assert_eq!(removed.still_blocked, [blocked.id.clone()]);
5805
5806 let after = q.get(&blocked.id).unwrap();
5807 assert_eq!(after.status, TaskStatus::Blocked);
5808 assert_eq!(after.blocked_by, [other.id.clone()]);
5809 assert!(missing_blockers(&q, &questions, &after.blocked_by).is_empty());
5812 }
5813
5814 #[test]
5815 fn a_dependency_deleted_before_its_dependents_were_rewritten_is_released_later() {
5816 let (dir, q) = queue();
5817 let questions = Questions::at(dir.path().join("questions"));
5818 let mut dep = task("dependency");
5819 q.put(&mut dep).unwrap();
5820 let mut blocked = task("waiting");
5821 blocked.block(vec![dep.id.clone()], None);
5822 q.put(&mut blocked).unwrap();
5823
5824 let claim = q.claim(&blocked.id).unwrap();
5826 let removed = q.remove(&dep.id, false, &questions).unwrap();
5827 assert!(removed.released.is_empty());
5828 drop(claim);
5829
5830 let mut task = q.get(&blocked.id).unwrap();
5831 assert_eq!(task.status, TaskStatus::Blocked);
5832 assert!(missing_blockers(&q, &questions, &task.blocked_by).is_empty());
5833 assert_eq!(
5834 q.apply_deleted_blockers(&mut task, &questions),
5835 [dep.id.clone()]
5836 );
5837 assert_eq!(task.status, TaskStatus::Queued);
5838 }
5839
5840 #[test]
5841 fn dependency_resolution_short_deleted_reference_releases_only_its_waiters() {
5842 let (dir, q) = queue();
5843 let questions = Questions::at(dir.path().join("questions"));
5844 let mut dep = task("dependency");
5845 dep.id = "20261013-193611-ca5b".into();
5846 q.put(&mut dep).unwrap();
5847 let mut waiting = task("waiting");
5848 waiting.block(vec!["ca5b".into()], None);
5849 q.put(&mut waiting).unwrap();
5850 q.remove(&dep.id, false, &questions).unwrap();
5851 assert_eq!(q.get(&waiting.id).unwrap().status, TaskStatus::Queued);
5852 assert_eq!(
5853 dependency(&q, &questions, "ca5b"),
5854 Dependency::Deleted(dep.id)
5855 );
5856 }
5857
5858 #[test]
5859 fn dependency_resolution_preserves_cross_store_ambiguity_and_exact_ids() {
5860 let (dir, queue) = queue();
5861 let questions = Questions::at(dir.path().join("questions"));
5862 let mut dep = task("dependency");
5863 dep.id = "20261013-193611-ca5b".into();
5864 queue.put(&mut dep).unwrap();
5865 std::fs::create_dir_all(questions.root()).unwrap();
5866 let question_id = "20261014-193611-ca5b";
5867 std::fs::write(questions.path_of(question_id), "unreadable question").unwrap();
5868 assert_eq!(questions.resolve_id("ca5b").unwrap(), question_id);
5869 assert_eq!(
5870 dependency(&queue, &questions, "ca5b"),
5871 Dependency::Ambiguous
5872 );
5873 assert_eq!(
5874 dependency(&queue, &questions, &dep.id),
5875 Dependency::Task(dep.id)
5876 );
5877 assert_eq!(
5878 dependency(&queue, &questions, question_id),
5879 Dependency::Question(question_id.into())
5880 );
5881 assert_eq!(
5882 dependency(&queue, &questions, "missing"),
5883 Dependency::Missing
5884 );
5885 }
5886
5887 #[test]
5888 fn dependency_resolution_directory_errors_are_unknown_not_missing() {
5889 let dir = tempfile::tempdir().unwrap();
5890 let q = Queue::at(dir.path().join("not-a-directory"));
5891 std::fs::write(q.root(), "file").unwrap();
5892 let questions = Questions::at(dir.path().join("questions"));
5893 assert_eq!(dependency(&q, &questions, "ca5b"), Dependency::Unknown);
5894 assert!(missing_blockers(&q, &questions, &["ca5b".into()]).is_empty());
5895 }
5896
5897 #[test]
5898 fn a_dependency_without_a_tombstone_is_still_missing() {
5899 let (dir, q) = queue();
5900 let questions = Questions::at(dir.path().join("questions"));
5901 let mut dep = task("dependency");
5902 q.put(&mut dep).unwrap();
5903 std::fs::remove_file(q.path_of(&dep.id)).unwrap();
5904 assert_eq!(
5905 missing_blockers(&q, &questions, std::slice::from_ref(&dep.id)),
5906 [dep.id.clone()]
5907 );
5908 assert!(deleted_blockers(&q, &questions, std::slice::from_ref(&dep.id)).is_empty());
5909 }
5910
5911 #[test]
5912 fn a_held_dependent_is_left_alone_by_a_dependency_deletion() {
5913 let mut t = task("held");
5914 t.hold_machine(Some("because".to_owned()));
5915 t.blocked_by = vec!["gone".to_owned()];
5916 assert!(!t.dependency_deleted("gone"));
5917 assert_eq!(t.status, TaskStatus::Held);
5918 }
5919
5920 #[test]
5921 fn a_failed_record_removal_takes_the_tombstone_back() {
5922 let (_dir, q) = queue();
5923 let mut t = task("stays");
5924 q.put(&mut t).unwrap();
5925 q.write_tombstone(&t.id).unwrap();
5926 let err = q.remove_record_with_attachments(&t.id, |_| Err(std::io::Error::other("nope")));
5927 assert!(err.is_err());
5928 assert!(!q.was_deleted(&t.id));
5931 }
5932
5933 fn source_file(dir: &Path, name: &str, body: &str) -> PathBuf {
5934 let p = dir.join(name);
5935 std::fs::write(&p, body).unwrap();
5936 p
5937 }
5938
5939 #[test]
5940 fn an_attachment_copy_survives_deleting_its_source() {
5941 let (dir, q) = queue();
5942 let src = source_file(dir.path(), "shot.png", "pixels");
5943 let mut t = task("with a picture");
5944 let names = q.attach(&mut t, std::slice::from_ref(&src)).unwrap();
5945 q.put(&mut t).unwrap();
5946 std::fs::remove_file(&src).unwrap();
5947 assert_eq!(names, ["shot.png"]);
5948 let loaded = q.get(&t.id).unwrap();
5949 let paths = q.attachment_paths(&loaded);
5950 assert_eq!(paths.len(), 1);
5951 assert_eq!(std::fs::read_to_string(&paths[0]).unwrap(), "pixels");
5952 }
5953
5954 #[test]
5955 fn attachment_names_that_could_traverse_or_are_odd_are_refused() {
5956 let (dir, q) = queue();
5957 let mut t = task("bad names");
5958 for name in ["a..b.png", ".hidden", "with space.png", "-x.png"] {
5959 let src = source_file(dir.path(), name, "x");
5960 assert!(
5961 q.attach(&mut t, &[src]).is_err(),
5962 "`{name}` must be refused"
5963 );
5964 }
5965 assert!(!crate::ask::valid_asset_name("C:foo.png"));
5969 #[cfg(not(windows))]
5970 {
5971 let src = source_file(dir.path(), "C:foo.png", "x");
5972 assert!(q.attach(&mut t, &[src]).is_err());
5973 }
5974 let long = format!("{}.png", "a".repeat(70));
5975 let src = source_file(dir.path(), &long, "x");
5976 assert!(q.attach(&mut t, &[src]).is_err());
5977 assert!(t.attachments.is_empty());
5978 assert!(!q.attachments_dir(&t.id).exists());
5979 }
5980
5981 #[test]
5982 fn a_taken_attachment_name_is_numbered_not_overwritten() {
5983 let (dir, q) = queue();
5984 let a = source_file(dir.path(), "shot.png", "one");
5985 let sub = dir.path().join("other");
5986 std::fs::create_dir_all(&sub).unwrap();
5987 let b = source_file(&sub, "shot.png", "two");
5988 let mut t = task("collision");
5989 q.attach(&mut t, &[a]).unwrap();
5990 q.attach(&mut t, &[b]).unwrap();
5991 assert_eq!(t.attachments, ["shot.png", "shot-2.png"]);
5992 let paths = q.attachment_paths(&t);
5993 assert_eq!(std::fs::read_to_string(&paths[0]).unwrap(), "one");
5994 assert_eq!(std::fs::read_to_string(&paths[1]).unwrap(), "two");
5995 }
5996
5997 #[test]
5998 fn a_renumbered_name_stays_inside_the_length_bound() {
5999 let (dir, q) = queue();
6000 let name = format!("{}.png", "a".repeat(60));
6001 assert_eq!(name.len(), 64);
6002 let a = source_file(dir.path(), &name, "one");
6003 let sub = dir.path().join("other");
6004 std::fs::create_dir_all(&sub).unwrap();
6005 let b = source_file(&sub, &name, "two");
6006 let mut t = task("long");
6007 q.attach(&mut t, &[a, b]).unwrap();
6008 assert_eq!(t.attachments.len(), 2);
6009 assert!(
6010 t.attachments
6011 .iter()
6012 .all(|n| crate::ask::valid_asset_name(n))
6013 );
6014 assert!(t.attachments[1].ends_with("-2.png"));
6015 }
6016
6017 #[test]
6018 fn a_failed_attach_keeps_existing_attachments_and_leaves_no_partial_copy() {
6019 let (dir, q) = queue();
6020 let good = source_file(dir.path(), "good.png", "ok");
6021 let mut t = task("partial");
6022 q.attach(&mut t, &[good]).unwrap();
6023 let more = source_file(dir.path(), "more.png", "ok");
6024 let missing = dir.path().join("missing.png");
6025 assert!(q.attach(&mut t, &[more, missing]).is_err());
6026 assert_eq!(t.attachments, ["good.png"]);
6027 let on_disk: Vec<_> = std::fs::read_dir(q.attachments_dir(&t.id))
6028 .unwrap()
6029 .flatten()
6030 .collect();
6031 assert_eq!(on_disk.len(), 1);
6032 }
6033
6034 fn block_put(q: &Queue, t: &Task) -> PathBuf {
6036 let tmp = q.path_of(&t.id).with_extension("json.tmp");
6037 std::fs::create_dir_all(&tmp).unwrap();
6038 tmp
6039 }
6040
6041 #[test]
6042 fn a_failed_put_leaves_no_new_attachment_directory() {
6043 let (dir, q) = queue();
6044 let mut t = task("fresh");
6045 let tmp = block_put(&q, &t);
6046 let src = source_file(dir.path(), "shot.png", "x");
6047 assert!(q.attach_and_put(&mut t, &[src]).is_err());
6048 assert!(t.attachments.is_empty());
6049 assert!(!q.attachments_dir(&t.id).exists());
6050 assert!(!q.path_of(&t.id).exists());
6051 std::fs::remove_dir(tmp).unwrap();
6052 }
6053
6054 #[test]
6055 fn a_failed_put_removes_only_the_copy_it_just_made() {
6056 let (dir, q) = queue();
6057 let mut t = task("edited");
6058 let first = source_file(dir.path(), "first.png", "1");
6059 q.attach_and_put(&mut t, &[first]).unwrap();
6060 block_put(&q, &t);
6061 let second = source_file(dir.path(), "second.png", "2");
6062 assert!(q.attach_and_put(&mut t, &[second]).is_err());
6063 assert_eq!(t.attachments, ["first.png"]);
6064 let on_disk: Vec<_> = std::fs::read_dir(q.attachments_dir(&t.id))
6065 .unwrap()
6066 .flatten()
6067 .map(|e| e.file_name().to_string_lossy().into_owned())
6068 .collect();
6069 assert_eq!(on_disk, ["first.png"]);
6070 assert_eq!(q.get(&t.id).unwrap().attachments, ["first.png"]);
6071 }
6072
6073 #[test]
6074 fn a_leftover_removing_directory_is_swept_by_the_next_removal() {
6075 let (dir, q) = queue();
6076 let questions = Questions::at(dir.path().join("questions"));
6077 let gone = task("gone");
6078 let mut other = task("other");
6079 let mut live = task("live");
6080 q.put(&mut other).unwrap();
6081 q.put(&mut live).unwrap();
6082 let orphan = q.root.join(format!("{}.attachments.removing", gone.id));
6085 std::fs::create_dir_all(&orphan).unwrap();
6086 std::fs::write(orphan.join("shot.png"), "x").unwrap();
6087 let busy = q.root.join(format!("{}.attachments.removing", live.id));
6090 std::fs::create_dir_all(&busy).unwrap();
6091
6092 q.remove(&other.id, false, &questions).unwrap();
6093 assert!(!orphan.exists(), "an orphan is swept");
6094 assert!(busy.exists(), "a removal in progress is left alone");
6095 }
6096
6097 #[test]
6098 fn a_blocked_aside_rename_fails_the_removal_and_loses_nothing() {
6099 let (dir, q) = queue();
6100 let questions = Questions::at(dir.path().join("questions"));
6101 let mut t = task("stuck");
6102 let src = source_file(dir.path(), "shot.png", "x");
6103 q.attach_and_put(&mut t, &[src]).unwrap();
6104 let aside = q.root.join(format!("{}.attachments.removing", t.id));
6107 std::fs::create_dir_all(&aside).unwrap();
6108 std::fs::write(aside.join("old.png"), "o").unwrap();
6109 assert!(q.remove(&t.id, false, &questions).is_err());
6110 assert!(q.path_of(&t.id).exists());
6111 assert!(q.attachments_dir(&t.id).join("shot.png").is_file());
6112 }
6113
6114 #[test]
6115 fn a_failed_record_removal_puts_the_attachments_back() {
6116 let (dir, q) = queue();
6117 let mut t = task("rollback");
6118 let src = source_file(dir.path(), "shot.png", "x");
6119 q.attach_and_put(&mut t, &[src]).unwrap();
6120 let err = q
6121 .remove_record_with_attachments(&t.id, |_| {
6122 Err(std::io::Error::other("injected failure"))
6123 })
6124 .unwrap_err();
6125 assert!(format!("{err:#}").contains("injected failure"));
6126 assert!(q.path_of(&t.id).exists());
6127 assert!(q.attachments_dir(&t.id).join("shot.png").is_file());
6128 assert!(
6129 !q.root
6130 .join(format!("{}.attachments.removing", t.id))
6131 .exists()
6132 );
6133 }
6134
6135 #[test]
6136 fn editing_a_task_keeps_its_attachments() {
6137 let (dir, q) = queue();
6138 let src = source_file(dir.path(), "shot.png", "x");
6139 let mut t = task("editable");
6140 q.attach(&mut t, &[src]).unwrap();
6141 t.edit("new".to_owned(), "new text".to_owned()).unwrap();
6142 q.put(&mut t).unwrap();
6143 assert_eq!(q.get(&t.id).unwrap().attachments, ["shot.png"]);
6144 }
6145
6146 #[test]
6147 fn removing_a_task_deletes_its_attachments() {
6148 let (dir, q) = queue();
6149 let questions = Questions::at(dir.path().join("questions"));
6150 let src = source_file(dir.path(), "shot.png", "x");
6151 let mut t = task("doomed");
6152 q.attach(&mut t, &[src]).unwrap();
6153 q.put(&mut t).unwrap();
6154 assert!(q.attachments_dir(&t.id).is_dir());
6155 q.remove(&t.id, false, &questions).unwrap();
6156 assert!(!q.attachments_dir(&t.id).exists());
6157 assert!(q.list().is_empty());
6158 }
6159
6160 #[test]
6161 fn a_task_written_before_attachments_still_reads() {
6162 let (_dir, q) = queue();
6163 let mut t = task("old");
6164 q.put(&mut t).unwrap();
6165 let path = q.path_of(&t.id);
6166 let mut v: serde_json::Value =
6167 serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
6168 v.as_object_mut().unwrap().remove("attachments");
6169 std::fs::write(&path, v.to_string()).unwrap();
6170 assert!(q.get(&t.id).unwrap().attachments.is_empty());
6171 }
6172
6173 #[test]
6174 fn attachment_paths_are_absolute_even_when_the_root_is_relative() {
6175 let q = Queue::at(PathBuf::from("relative-queue"));
6176 let mut t = task("rel");
6177 t.attachments.push("shot.png".to_owned());
6178 let paths = q.attachment_paths(&t);
6179 assert!(paths[0].is_absolute(), "{}", paths[0].display());
6180 assert!(paths[0].ends_with(format!("{}.attachments/shot.png", t.id)));
6181 }
6182
6183 fn upgrade_parked(id: &str, started: &str) -> Task {
6184 let mut t = task(id);
6185 t.id = id.into();
6186 t.start(format!("run-{id}"));
6187 t.park("upgrade");
6188 t.record_pass_at(
6189 &format!("run-{id}"),
6190 0,
6191 Some(started.parse().unwrap()),
6192 1,
6193 Some(crate::run::ParkCause::Upgrade {
6194 from: "old".into(),
6195 to: None,
6196 }),
6197 );
6198 t
6199 }
6200
6201 #[test]
6202 fn upgrade_resume_order_follows_dispatch_claim_not_graph_start() {
6203 let stamp = |id: &str, dispatched: &str, started: &str| {
6205 let mut t = task(id);
6206 t.id = id.into();
6207 t.start(format!("run-{id}"));
6208 t.park("upgrade");
6209 t.dispatched_at = Some(dispatched.parse().unwrap());
6210 t.record_pass_at(
6211 &format!("run-{id}"),
6212 0,
6213 Some(started.parse().unwrap()),
6214 1,
6215 Some(crate::run::ParkCause::Upgrade {
6216 from: "old".into(),
6217 to: None,
6218 }),
6219 );
6220 t
6221 };
6222 let a = stamp("a", "2026-10-22T00:00:01Z", "2026-10-22T00:00:09Z");
6223 let b = stamp("b", "2026-10-22T00:00:02Z", "2026-10-22T00:00:03Z");
6224 assert!(dispatch_order(&a, &b).is_lt());
6225 }
6226
6227 #[test]
6228 fn upgrade_resume_order_survives_queue_reload_and_reversed_settlement() {
6229 let (_dir, q) = queue();
6230 let mut later = upgrade_parked("later", "2026-10-22T00:00:02Z");
6231 let mut earlier = upgrade_parked("earlier", "2026-10-22T00:00:01Z");
6232 earlier.priority = -10;
6233 let mut fresh = task("fresh");
6234 fresh.id = "newer".into();
6235 fresh.priority = 100;
6236 for t in [&mut fresh, &mut later, &mut earlier] {
6237 q.put(t).unwrap();
6238 }
6239 let reloaded = Queue::at(q.root().to_owned());
6240 let mut tasks = reloaded.list();
6241 tasks.sort_unstable_by(dispatch_order);
6242 assert_eq!(
6243 tasks.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
6244 vec!["earlier", "later", "newer"]
6245 );
6246 assert_eq!(reloaded.next_runnable().unwrap().id, "earlier");
6247 assert_eq!(reloaded.get("earlier").unwrap().attempts, 0);
6248 }
6249
6250 #[test]
6251 fn upgrade_resume_legacy_order_uses_settlement_and_id() {
6252 let mut a = upgrade_parked("a", "2026-10-22T00:00:02Z");
6253 let mut b = upgrade_parked("b", "2026-10-22T00:00:01Z");
6254 for t in [&mut a, &mut b] {
6255 let mut value = serde_json::to_value(&*t).unwrap();
6256 value["passes"][0]
6257 .as_object_mut()
6258 .unwrap()
6259 .remove("started_at");
6260 *t = serde_json::from_value(value).unwrap();
6261 }
6262 assert!(dispatch_order(&a, &b).is_lt());
6263 b.passes[0].settled_at = a.passes[0].settled_at;
6264 assert!(dispatch_order(&a, &b).is_lt());
6265 }
6266
6267 #[test]
6268 fn upgrade_resume_key_excludes_other_parks_and_explicit_task_changes() {
6269 let original = upgrade_parked("a", "2026-10-22T00:00:01Z");
6270 assert!(original.upgrade_resume_key().is_some());
6271 for cause in [
6272 crate::run::ParkCause::Operator,
6273 crate::run::ParkCause::Question,
6274 crate::run::ParkCause::Interrupt {
6275 reason: "interrupt".into(),
6276 },
6277 crate::run::ParkCause::Unspecified,
6278 ] {
6279 let mut t = original.clone();
6280 t.passes[0].parked = Some(cause);
6281 assert!(t.upgrade_resume_key().is_none());
6282 let mut fresh = task("fresh");
6283 fresh.priority = 1;
6284 assert!(dispatch_order(&fresh, &t).is_lt());
6285 }
6286 let mut t = original.clone();
6287 t.release();
6288 assert!(t.upgrade_resume_key().is_none());
6289 t.edit("edited".into(), "new instruction".into()).unwrap();
6290 assert!(t.upgrade_resume_key().is_none());
6291 let mut t = original.clone();
6292 t.requeue();
6293 t.status = TaskStatus::Parked;
6294 assert!(t.upgrade_resume_key().is_none());
6295 let mut t = original.clone();
6296 t.start("different-run".into());
6297 t.park("no upgrade");
6298 assert!(t.upgrade_resume_key().is_none());
6299 }
6300
6301 #[test]
6302 fn explicitly_resumed_older_run_becomes_current_without_duplicate_history() {
6303 let dir = tempfile::tempdir().unwrap();
6304 let q = Queue::at(dir.path().join("queue"));
6305 let mut t = task("resume");
6306 t.start("A".into());
6307 t.record_pass("A", 0, 1, None);
6308 t.start("B".into());
6309 q.put(&mut t).unwrap();
6310 assert_eq!(t.runs, vec!["A", "B"]);
6311 t.start("A".into());
6312 t.record_pass("A", 1, 3, None);
6313 q.put(&mut t).unwrap();
6314 let saved = q.get(&t.id).unwrap();
6315 assert_eq!(saved.runs, vec!["B", "A"]);
6316 assert_eq!(saved.runs.last().map(String::as_str), Some("A"));
6317 assert_eq!(saved.attempts, 3);
6318 assert_eq!(saved.passes.len(), 2);
6319 assert_eq!(saved.passes[0].run, "A");
6320 assert_eq!(saved.passes[1].run, "A");
6321 }
6322
6323 #[test]
6324 fn repeated_start_records_one_run_and_separate_passes() {
6325 let mut t = task("resume");
6326 t.start("same-run".into());
6327 t.record_pass("same-run", 0, 1, None);
6328 t.start("same-run".into());
6329 t.record_pass("same-run", 1, 2, None);
6330 assert_eq!(t.runs, vec!["same-run"]);
6331 assert_eq!(t.attempts, 2);
6332 assert_eq!(t.passes.len(), 2);
6333 }
6334
6335 #[test]
6336 fn link_run_adds_a_run_once_and_touches_nothing_else() {
6337 let dir = tempfile::tempdir().unwrap();
6338 let queue = Queue::at(dir.path().join("queue"));
6339 let mut t = Task::new(
6340 "t".to_owned(),
6341 "do it".to_owned(),
6342 PathBuf::from("."),
6343 Source::Human,
6344 );
6345 queue.put(&mut t).unwrap();
6346 let before = queue.get(&t.id).unwrap();
6347
6348 let linked = queue.link_run(&t.id[..4], "20260930-092817-ec34").unwrap();
6349 assert_eq!(linked.runs, vec!["20260930-092817-ec34".to_owned()]);
6350 assert_eq!(linked.status, before.status);
6351 assert_eq!(linked.attempts, before.attempts);
6352 assert_eq!(linked.interrupt, before.interrupt);
6353
6354 let again = queue.link_run(&t.id, "20260930-092817-ec34").unwrap();
6355 assert_eq!(again.runs.len(), 1, "linking twice must not duplicate");
6356 assert_eq!(queue.get(&t.id).unwrap().runs.len(), 1);
6357 assert!(queue.link_run("no-such-task", "r").is_err());
6358 }
6359
6360 #[test]
6361 fn put_keeps_a_run_linked_after_the_writer_took_its_snapshot() {
6362 let dir = tempfile::tempdir().unwrap();
6363 let queue = Queue::at(dir.path().join("queue"));
6364 let mut t = Task::new(
6365 "t".to_owned(),
6366 "do it".to_owned(),
6367 PathBuf::from("."),
6368 Source::Human,
6369 );
6370 queue.put(&mut t).unwrap();
6371 let mut snapshot = queue.get(&t.id).unwrap();
6373 queue.link_run(&t.id, "20260930-092817-ec34").unwrap();
6374
6375 snapshot.start("20260930-000000-aaaa".to_owned());
6376 queue.put(&mut snapshot).unwrap();
6377
6378 let stored = queue.get(&t.id).unwrap();
6379 assert!(stored.runs.contains(&"20260930-092817-ec34".to_owned()));
6380 assert!(stored.runs.contains(&"20260930-000000-aaaa".to_owned()));
6381 assert_eq!(stored.attempts, 1);
6382 }
6383
6384 #[test]
6385 fn concurrent_links_and_daemon_saves_lose_nothing() {
6386 let dir = tempfile::tempdir().unwrap();
6387 let queue = Queue::at(dir.path().join("queue"));
6388 let mut t = Task::new(
6389 "t".to_owned(),
6390 "do it".to_owned(),
6391 PathBuf::from("."),
6392 Source::Human,
6393 );
6394 queue.put(&mut t).unwrap();
6395 let id = t.id.clone();
6396
6397 let linkers: Vec<_> = (0..4)
6398 .map(|n| {
6399 let (queue, id) = (queue.clone(), id.clone());
6400 std::thread::spawn(move || {
6401 for k in 0..10 {
6402 queue
6403 .link_run(&id, &format!("20260930-00000{n}-l{k:03}"))
6404 .unwrap();
6405 }
6406 })
6407 })
6408 .collect();
6409 let mut mine = queue.get(&id).unwrap();
6412 for k in 0..10 {
6413 mine.start(format!("20260930-000009-d{k:03}"));
6414 queue.put(&mut mine).unwrap();
6415 }
6416 for l in linkers {
6417 l.join().unwrap();
6418 }
6419
6420 let stored = queue.get(&id).unwrap();
6421 assert_eq!(stored.runs.len(), 50, "{:?}", stored.runs);
6422 assert_eq!(
6423 stored.attempts, 10,
6424 "linking never rewinds the daemon's work"
6425 );
6426 }
6427
6428 fn age_lock(path: &Path) {
6429 let f = std::fs::OpenOptions::new().write(true).open(path).unwrap();
6430 f.set_modified(std::time::SystemTime::now() - std::time::Duration::from_secs(60))
6431 .unwrap();
6432 }
6433
6434 #[test]
6435 fn concurrent_stale_takeover_yields_one_holder() {
6436 use std::sync::atomic::{AtomicUsize, Ordering};
6437 use std::sync::{Arc, Barrier};
6438 for _ in 0..5 {
6439 let dir = tempfile::tempdir().unwrap();
6440 let q = Queue::at(dir.path().to_path_buf());
6441 let lock = dir.path().join("t.write-lock");
6442 std::fs::write(&lock, "dead-0000").unwrap();
6443 age_lock(&lock);
6444 let n = 6;
6445 let barrier = Arc::new(Barrier::new(n));
6446 let (now, max) = (Arc::new(AtomicUsize::new(0)), Arc::new(AtomicUsize::new(0)));
6447 let handles: Vec<_> = (0..n)
6448 .map(|_| {
6449 let (q, b, now, max) = (q.clone(), barrier.clone(), now.clone(), max.clone());
6450 std::thread::spawn(move || {
6451 b.wait();
6452 let g = q.lock_task("t").unwrap();
6453 let held = now.fetch_add(1, Ordering::SeqCst) + 1;
6454 max.fetch_max(held, Ordering::SeqCst);
6455 std::thread::sleep(std::time::Duration::from_millis(20));
6456 now.fetch_sub(1, Ordering::SeqCst);
6457 drop(g);
6458 })
6459 })
6460 .collect();
6461 for h in handles {
6462 h.join().unwrap();
6463 }
6464 assert_eq!(max.load(Ordering::SeqCst), 1);
6465 assert!(!lock.exists());
6466 }
6467 }
6468
6469 #[test]
6470 fn dropping_a_replaced_lock_leaves_the_new_holders_token() {
6471 let dir = tempfile::tempdir().unwrap();
6472 let q = Queue::at(dir.path().to_path_buf());
6473 let lock = dir.path().join("t.write-lock");
6474 let a = q.lock_task("t").unwrap();
6475 let replacement = owner_token();
6478 std::fs::write(&lock, &replacement).unwrap();
6479 drop(a);
6480 assert_eq!(std::fs::read_to_string(&lock).unwrap(), replacement);
6481 }
6482
6483 #[test]
6484 fn aged_live_task_lock_excludes_updates_until_retirement_releases_it() {
6485 let dir = tempfile::tempdir().unwrap();
6486 let q = Queue::at(dir.path().to_path_buf());
6487 let held = q.lock_task("t").unwrap();
6488 let path = dir.path().join("t.write-lock");
6489 age_lock(&path);
6490 assert!(!break_stale(&path, &held.token));
6491 let (started_tx, started_rx) = std::sync::mpsc::channel();
6492 let (acquired_tx, acquired_rx) = std::sync::mpsc::channel();
6493 let updater = std::thread::spawn(move || {
6494 started_tx.send(()).unwrap();
6495 let _write = q.lock_task("t").unwrap();
6496 acquired_tx.send(()).unwrap();
6497 });
6498 started_rx.recv().unwrap();
6499 assert!(
6500 acquired_rx
6501 .recv_timeout(std::time::Duration::from_millis(100))
6502 .is_err()
6503 );
6504 assert_eq!(std::fs::read_to_string(&path).unwrap(), held.token);
6505 drop(held);
6506 acquired_rx
6507 .recv_timeout(std::time::Duration::from_secs(2))
6508 .unwrap();
6509 updater.join().unwrap();
6510 assert!(!path.exists());
6511 }
6512
6513 #[test]
6514 fn break_stale_leaves_a_lock_that_replaced_the_one_judged() {
6515 let dir = tempfile::tempdir().unwrap();
6516 let lock = dir.path().join("t.write-lock");
6517 std::fs::write(&lock, "new-token").unwrap();
6518 assert!(!break_stale(&lock, "old-token"));
6519 assert_eq!(std::fs::read_to_string(&lock).unwrap(), "new-token");
6520 assert!(!break_stale(&lock, "new-token"));
6522 assert!(lock.exists());
6523 age_lock(&lock);
6524 assert!(break_stale(&lock, "new-token"));
6525 assert!(!lock.exists());
6526 }
6527
6528 #[test]
6529 fn a_stale_break_marker_is_recovered_and_a_fresh_one_is_respected() {
6530 let dir = tempfile::tempdir().unwrap();
6531 let lock = dir.path().join("t.write-lock");
6532 std::fs::write(&lock, "dead-1").unwrap();
6533 age_lock(&lock);
6534 let marker = break_marker(&lock, "dead-1");
6535 std::fs::write(&marker, "crashed-remover").unwrap();
6536 assert!(!break_stale(&lock, "dead-1"));
6538 assert!(lock.exists());
6539 age_lock(&marker);
6541 assert!(break_stale(&lock, "dead-1"));
6542 assert!(!lock.exists());
6543 assert!(!marker.exists());
6544 }
6545
6546 fn chat_task() -> Task {
6547 Task::new(
6548 "t".to_owned(),
6549 "do t".to_owned(),
6550 PathBuf::from("."),
6551 Source::Agent {
6552 run: "20260902-000000-beef".to_owned(),
6553 node: CHAT_NODE.to_owned(),
6554 },
6555 )
6556 }
6557
6558 #[test]
6559 fn a_blocked_hold_keeps_its_anchor_but_a_new_run_starts_a_new_hold() {
6560 let mut t = chat_task();
6561 t.hold_machine(Some("waiting".into()));
6562 let old: Timestamp = "2020-01-01T00:00:00Z".parse().unwrap();
6563 t.held_at = Some(old);
6564 t.block(vec!["decision".into()], None);
6565 t.hold_machine(Some("same waiting decision".into()));
6566 assert_eq!(t.held_at, Some(old));
6567 t.start("real-new-run".into());
6568 t.fail("new failure", 1);
6569 assert_ne!(
6570 t.held_at,
6571 Some(old),
6572 "old answers cannot approve a new hold"
6573 );
6574 }
6575
6576 #[test]
6577 fn legacy_delivery_survives_upgrade_and_a_no_progress_run_link() {
6578 let (_dir, queue) = queue();
6579 let mut t = chat_task();
6580 t.start("old-run".into());
6581 t.hold_machine(Some("operator is considering recovery".into()));
6582 t.chat_notice = Some(ChatNotice {
6583 key: format!("held#{}", t.held_at.unwrap()),
6584 at: Timestamp::now(),
6585 outcome: ChatNoticeOutcome::Posted,
6586 });
6587 let mut raw = serde_json::to_value(&t).unwrap();
6588 raw.as_object_mut().unwrap().remove("chat_notices");
6589 raw.as_object_mut().unwrap().remove("hold_notice_cause");
6590 std::fs::create_dir_all(queue.path_of(&t.id).parent().unwrap()).unwrap();
6591 std::fs::write(queue.path_of(&t.id), serde_json::to_string(&raw).unwrap()).unwrap();
6592 assert_eq!(queue.get(&t.id).unwrap().chat_notice_due(), None);
6593 queue
6594 .modify(&t.id, |task| {
6595 task.requeue();
6596 task.link_run("unprepared-run");
6597 task.startup_notice_cause("startup-source");
6598 task.fail("same unresolved preflight", 0);
6599 true
6600 })
6601 .unwrap();
6602 assert_eq!(queue.get(&t.id).unwrap().chat_notice_due(), None);
6603 queue
6604 .modify(&t.id, |task| {
6605 task.succeed();
6606 true
6607 })
6608 .unwrap();
6609 assert_eq!(
6610 queue.get(&t.id).unwrap().chat_notice_due().as_deref(),
6611 Some("done")
6612 );
6613 }
6614
6615 #[test]
6616 fn a_dependency_wait_does_not_change_when_released_and_blocked_again() {
6617 let mut t = chat_task();
6618 t.block(vec!["a".into(), "b".into()], Some("waiting".into()));
6619 let key = t.chat_notice_key().unwrap();
6620 t.chat_notices.push(key);
6621 t.release();
6622 t.block(
6623 vec!["b".into(), "a".into(), "a".into()],
6624 Some("still waiting on prerequisites".into()),
6625 );
6626 assert_eq!(t.chat_notice_due(), None);
6627 t.block(
6628 vec!["new-question".into()],
6629 Some("different decision".into()),
6630 );
6631 assert!(t.chat_notice_due().is_some());
6632 }
6633
6634 #[test]
6635 fn running_startup_failures_preserve_stage_and_report_distinct_blockers() {
6636 let mut t = chat_task();
6637 t.start("existing-run".into());
6638 t.fail("implementation failed", 1);
6639 let failed = t.chat_notice_key().unwrap();
6640 t.chat_notices.push(failed.clone());
6641 t.release_operator("test", None);
6642 t.start("existing-run".into());
6643 t.fail_startup("startup-source", "same unresolved recovery source", 1);
6644 assert_eq!(
6645 t.chat_notice_due(),
6646 None,
6647 "no-progress recovery stays quiet"
6648 );
6649 t.release_operator("test", None);
6650 t.start("existing-run".into());
6651 t.fail_startup("startup-attachments", "attachment missing", 1);
6652 let attachments = t.chat_notice_due().expect("new attachment blocker");
6653 assert_ne!(attachments, failed);
6654 assert_eq!(
6655 t.hold_notice_cause.as_ref().unwrap().stage,
6656 "startup-attachments"
6657 );
6658 t.chat_notices.push(attachments);
6659 t.release_operator("test", None);
6660 t.start("existing-run".into());
6661 t.fail_startup(
6662 "startup-attachments",
6663 "same missing attachment, reworded",
6664 1,
6665 );
6666 assert_eq!(
6667 t.chat_notice_due(),
6668 None,
6669 "same stage after attempt counter reset"
6670 );
6671 t.release_operator("test", None);
6672 t.start("existing-run".into());
6673 t.fail_startup("startup-config", "different preflight stage", 1);
6674 assert!(t.chat_notice_due().is_some());
6675 assert_eq!(
6676 t.hold_notice_cause.as_ref().unwrap().stage,
6677 "startup-config"
6678 );
6679 }
6680
6681 #[test]
6682 fn structured_causes_preserve_no_progress_retries_and_report_new_passes() {
6683 let mut t = chat_task();
6684 t.hold_machine(Some("startup source missing".into()));
6685 t.startup_notice_cause("startup-source");
6686 let first = t.chat_notice_key().unwrap();
6687 t.chat_notices.push(first.clone());
6688 t.release_operator("test", None);
6689 t.startup_notice_cause("startup-source");
6690 t.hold_machine(Some("same source cannot be read".into()));
6691 assert_eq!(t.chat_notice_due(), None);
6692 t.startup_notice_cause("startup-config");
6693 assert!(t.chat_notice_due().is_some(), "different startup stage");
6694 t.notice_cause("failed", Some("existing-run"), Some(0));
6695 let run_failure = t.chat_notice_key().unwrap();
6696 t.chat_notices.push(run_failure.clone());
6697 t.release_operator("test", None);
6698 t.startup_notice_cause("startup-source");
6699 t.hold_machine(Some("no new work happened".into()));
6700 assert_eq!(t.chat_notice_due(), None);
6701 t.notice_cause("failed", Some("existing-run"), Some(1));
6702 assert!(t.chat_notice_due().is_some(), "a real resumed pass failed");
6703 assert_ne!(t.chat_notice_key().unwrap(), run_failure);
6704 }
6705
6706 #[test]
6707 fn legacy_hold_baseline_does_not_replay_or_hide_new_failures_and_completion() {
6708 let mut t = chat_task();
6709 t.hold_machine(Some("still waiting".into()));
6710 t.chat_notice = Some(ChatNotice {
6711 key: "held#2026-10-14T00:00:00Z".into(),
6712 at: Timestamp::now(),
6713 outcome: ChatNoticeOutcome::Posted,
6714 });
6715 assert_eq!(t.chat_notice_due(), None, "old hold baseline");
6716 t.import_chat_notice();
6717 t.notice_cause("failed", Some("new-run"), Some(0));
6718 assert!(t.chat_notice_due().is_some(), "new producer evidence");
6719 t.succeed();
6720 assert_eq!(t.chat_notice_due().as_deref(), Some("done"));
6721 }
6722
6723 #[test]
6724 fn a_chat_notice_is_due_only_for_a_final_state_and_only_once() {
6725 let mut t = chat_task();
6726 assert_eq!(t.chat_notice_due(), None, "queued");
6727 t.start("r1".to_owned());
6728 assert_eq!(t.chat_notice_due(), None, "running");
6729 t.fail("boom", 3);
6730 assert_eq!(t.status, TaskStatus::Failed);
6731 assert_eq!(t.chat_notice_due(), None, "a retried failure is not final");
6732 t.start("r2".to_owned());
6733 t.park("upgrade");
6734 assert_eq!(t.chat_notice_due(), None, "parked");
6735 t.fail("boom", 1);
6736 assert_eq!(t.status, TaskStatus::Held);
6737 let key = t
6738 .chat_notice_due()
6739 .expect("held on the last attempt is final");
6740 t.chat_notice = Some(ChatNotice {
6741 key,
6742 at: Timestamp::now(),
6743 outcome: ChatNoticeOutcome::Posted,
6744 });
6745 assert_eq!(t.chat_notice_due(), None, "same hold, no second notice");
6746 t.release();
6747 assert_eq!(t.chat_notice_due(), None, "requeued after a release");
6748 t.start("r3".to_owned());
6749 t.succeed();
6750 assert!(t.chat_notice_due().is_some(), "done is a new final state");
6751 }
6752
6753 #[test]
6754 fn completed_chat_notices_keep_current_and_legacy_keys_after_requeue() {
6755 for key in ["done", "done#0", "done#1", "done#12"] {
6756 let mut t = chat_task();
6757 t.start("r1".to_owned());
6758 t.succeed();
6759 t.chat_notice = Some(ChatNotice {
6760 key: key.to_owned(),
6761 at: Timestamp::now(),
6762 outcome: ChatNoticeOutcome::Posted,
6763 });
6764 t.requeue();
6765 t.start("r2".to_owned());
6766 t.succeed();
6767 assert_eq!(t.chat_notice_key().as_deref(), Some("done"));
6768 assert_eq!(t.chat_notice_due(), None, "recorded key: {key}");
6769 }
6770 }
6771
6772 #[test]
6773 fn a_release_without_progress_keeps_the_unresolved_notice_cause() {
6774 let mut t = chat_task();
6775 t.hold_manual(Some("wait".to_owned()));
6776 let first = t.chat_notice_due().expect("held");
6777 t.chat_notice = Some(ChatNotice {
6778 key: first.clone(),
6779 at: Timestamp::now(),
6780 outcome: ChatNoticeOutcome::Posted,
6781 });
6782 t.hold_manual(Some("still waiting".to_owned()));
6783 assert_eq!(t.chat_notice_due(), None, "a re-hold keeps its start");
6784 t.release();
6785 std::thread::sleep(std::time::Duration::from_millis(5));
6786 t.hold_manual(None);
6787 assert_eq!(t.chat_notice_due(), None, "no progress, same cause");
6788 }
6789
6790 #[test]
6791 fn a_chat_notice_needs_a_chat_source_and_a_current_schema() {
6792 let mut human = task("h");
6793 human.succeed();
6794 assert_eq!(human.chat_notice_due(), None);
6795 let mut inherited = task("i");
6797 inherited.origin_chat = Some("20260902-000000-beef".to_owned());
6798 inherited.succeed();
6799 assert_eq!(inherited.chat_notice_due(), None);
6800 let mut old = chat_task();
6801 old.schema = 12;
6802 old.status = TaskStatus::Done;
6803 assert_eq!(old.chat_notice_due(), None, "history is not replayed");
6804 let mut live = chat_task();
6805 live.schema = 12;
6806 live.start("r1".to_owned());
6807 live.succeed();
6808 assert!(live.chat_notice_due().is_some(), "started by this build");
6809 let mut held = chat_task();
6810 held.schema = 12;
6811 held.hold_machine(Some("config".to_owned()));
6812 assert!(held.chat_notice_due().is_some(), "held before any start");
6813 }
6814
6815 #[test]
6816 fn a_stale_snapshot_does_not_rewind_a_recorded_chat_notice() {
6817 let tmp = tempfile::tempdir().expect("tempdir");
6818 let q = Queue::at(tmp.path().join("queue"));
6819 let mut t = chat_task();
6820 t.succeed();
6821 q.put(&mut t).expect("put");
6822 let mut stale = q.get(&t.id).expect("get");
6823 let key = t.chat_notice_due().expect("due");
6824 q.modify(&t.id, |x| {
6825 x.chat_notice = Some(ChatNotice {
6826 key: key.clone(),
6827 at: Timestamp::now(),
6828 outcome: ChatNoticeOutcome::Posted,
6829 });
6830 true
6831 })
6832 .expect("modify");
6833 q.put(&mut stale).expect("stale put");
6834 assert_eq!(q.get(&t.id).expect("get").chat_notice_due(), None);
6835 }
6836
6837 #[test]
6838 fn empty_sources_are_omitted_so_older_builds_still_read_the_task() {
6839 let mut t = task("plain");
6842 let value = serde_json::to_value(&t).unwrap();
6843 assert!(value.get("sources").is_none(), "{value}");
6844 t.sources.pick_commits.push(crate::refs::Input {
6845 token: "abc1234".into(),
6846 sha: "a".repeat(40),
6847 provenance: crate::refs::Provenance::ExplicitCli,
6848 });
6849 let value = serde_json::to_value(&t).unwrap();
6850 assert_eq!(value["sources"]["pick_commits"][0]["sha"], "a".repeat(40));
6851 let restored: Task = serde_json::from_value(value).unwrap();
6852 assert_eq!(restored.sources, t.sources);
6853 }
6854
6855 fn queue_with_ids(dir: &Path, ids: &[&str]) -> Queue {
6857 let ids: Vec<String> = ids.iter().map(|s| (*s).to_owned()).collect();
6858 let n = std::sync::atomic::AtomicUsize::new(0);
6859 Queue::at(dir.join("queue")).with_id_source(move || {
6860 let i = n.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
6861 ids.get(i)
6862 .cloned()
6863 .unwrap_or_else(|| format!("20260101-000000-f{i:03x}"))
6864 })
6865 }
6866
6867 const TAKEN: &str = "20260101-000000-aaaa";
6868
6869 #[test]
6870 fn a_new_task_never_merges_into_a_record_with_its_candidate_id() {
6871 let dir = tempfile::tempdir().unwrap();
6872 let q = queue_with_ids(dir.path(), &[TAKEN, TAKEN]);
6873 let mut first = task("first");
6874 first.start("run-1".into());
6875 first.succeed();
6876 q.put(&mut first).unwrap();
6877 assert_eq!(first.id, TAKEN);
6878 let stored_before = q.get(&first.id).unwrap();
6879 assert!(!stored_before.runs.is_empty());
6880
6881 let mut second = task("second");
6882 q.put(&mut second).unwrap();
6883
6884 assert_ne!(second.id, first.id);
6885 assert!(second.runs.is_empty());
6886 assert!(second.passes.is_empty());
6887 assert!(second.chat_notices.is_empty());
6888 assert!(second.chat_notice.is_none());
6889 assert_eq!(second.chat_notice_due(), task("fresh").chat_notice_due());
6890 let a = q.get(&first.id).unwrap();
6891 let b = q.get(&second.id).unwrap();
6892 assert_eq!(a.title, "first");
6893 assert_eq!(a.runs, stored_before.runs);
6894 assert_eq!(a.passes, stored_before.passes);
6895 assert_eq!(a.chat_notices, stored_before.chat_notices);
6896 assert_eq!(a.chat_notice, stored_before.chat_notice);
6897 assert_eq!(a.chat_notice_due(), stored_before.chat_notice_due());
6898 assert_eq!(b.title, "second");
6899 assert!(b.runs.is_empty());
6900 assert!(b.passes.is_empty());
6901 assert!(b.chat_notice.is_none());
6902
6903 let mut again = q.get(&second.id).unwrap();
6905 again.title = "second, edited".into();
6906 q.put(&mut again).unwrap();
6907 assert_eq!(q.get(&second.id).unwrap().title, "second, edited");
6908 assert_eq!(q.list().len(), 2);
6909 }
6910
6911 #[test]
6912 fn a_new_task_skips_an_id_with_an_orphaned_claim_or_attachments() {
6913 let dir = tempfile::tempdir().unwrap();
6914 let q = queue_with_ids(dir.path(), &["orphan-lock", "orphan-dir", "free"]);
6915 std::fs::create_dir_all(q.root()).unwrap();
6916 std::fs::write(q.root().join("orphan-lock.lock"), "x").unwrap();
6917 std::fs::create_dir_all(q.attachments_dir("orphan-dir")).unwrap();
6918 let mut t = task("t");
6919 q.put(&mut t).unwrap();
6920 assert_eq!(t.id, "free");
6921 }
6922
6923 #[test]
6924 fn a_claimed_new_task_holds_the_claim_on_the_reserved_id() {
6925 let dir = tempfile::tempdir().unwrap();
6926 let q = queue_with_ids(dir.path(), &[TAKEN, TAKEN]);
6927 let mut first = task("first");
6928 q.put(&mut first).unwrap();
6929 let mut second = task("second");
6930 let claim = q.file_claimed(&mut second).unwrap();
6931 assert_ne!(second.id, first.id);
6932 assert!(q.claim(&second.id).is_err());
6933 assert!(q.claim(&first.id).is_ok(), "the first task was not claimed");
6934 drop(claim);
6935 }
6936
6937 #[test]
6938 fn an_attached_new_task_skips_a_taken_id() {
6939 let dir = tempfile::tempdir().unwrap();
6940 let q = queue_with_ids(dir.path(), &[TAKEN, TAKEN]);
6941 let mut first = task("first");
6942 q.put(&mut first).unwrap();
6943 let src = source_file(dir.path(), "shot.png", "x");
6944 let mut second = task("second");
6945 q.attach_and_put(&mut second, &[src]).unwrap();
6946 assert_ne!(second.id, first.id);
6947 assert!(!q.attachments_dir(&first.id).exists());
6948 assert_eq!(q.attachment_paths(&second).len(), 1);
6949 assert!(q.attachment_paths(&second)[0].is_file());
6950 }
6951
6952 #[test]
6953 fn attaching_before_putting_a_new_task_reserves_the_id() {
6954 let dir = tempfile::tempdir().unwrap();
6955 let q = queue_with_ids(dir.path(), &[TAKEN, TAKEN]);
6956 let mut first = task("first");
6957 q.put(&mut first).unwrap();
6958 let src = source_file(dir.path(), "shot.png", "x");
6959 let mut second = task("second");
6960 q.attach(&mut second, &[src]).unwrap();
6961 assert_ne!(second.id, first.id);
6962 assert!(q.attachments_dir(&second.id).is_dir());
6963 q.put(&mut second).unwrap();
6964 assert_eq!(q.get(&second.id).unwrap().attachments.len(), 1);
6965 assert_eq!(q.get(&first.id).unwrap().title, "first");
6966 assert!(q.get(&first.id).unwrap().attachments.is_empty());
6967 }
6968
6969 #[test]
6970 fn create_new_keeps_its_already_exists_meaning() {
6971 let dir = tempfile::tempdir().unwrap();
6972 let q = Queue::at(dir.path().join("queue"));
6973 let mut a = task("a");
6974 a.id = "fixed-id".into();
6975 assert!(q.create_new(&mut a).unwrap());
6976 let mut b = task("b");
6977 b.id = "fixed-id".into();
6978 assert!(!q.create_new(&mut b).unwrap());
6979 assert_eq!(q.get("fixed-id").unwrap().title, "a");
6980 }
6981
6982 #[test]
6983 fn filing_gives_up_when_no_id_is_ever_free() {
6984 let dir = tempfile::tempdir().unwrap();
6985 let q = Queue::at(dir.path().join("queue")).with_id_source(|| TAKEN.to_owned());
6986 let mut first = task("first");
6987 q.put(&mut first).unwrap();
6988 let mut second = task("second");
6989 assert!(q.put(&mut second).is_err());
6990 assert_eq!(q.get(&first.id).unwrap().title, "first");
6991 }
6992}