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 = 26;
153
154const RECOVERY_HOLD_SCHEMA: u32 = 24;
155
156pub(crate) fn dispatch_order(a: &Task, b: &Task) -> std::cmp::Ordering {
162 match (a.upgrade_resume_key(), b.upgrade_resume_key()) {
163 (Some(a), Some(b)) => a.cmp(&b),
164 (Some(_), None) => std::cmp::Ordering::Less,
165 (None, Some(_)) => std::cmp::Ordering::Greater,
166 (None, None) => b.priority.cmp(&a.priority).then(a.id.cmp(&b.id)),
167 }
168}
169
170#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
177#[serde(tag = "kind", rename_all = "snake_case")]
178pub enum MachineHoldCause {
179 DiskCapacity {
181 reason: String,
183 #[serde(default)]
185 before_start: bool,
186 },
187 HeadE2e {
189 stop: crate::head_e2e_stop::Stop,
191 },
192}
193
194#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
196#[serde(rename_all = "lowercase")]
197pub enum HoldSource {
198 Manual,
200 Machine,
202}
203
204impl HoldSource {
205 pub fn label(self) -> &'static str {
207 match self {
208 Self::Manual => "manual",
209 Self::Machine => "machine",
210 }
211 }
212}
213
214#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
217#[serde(tag = "kind", rename_all = "lowercase")]
218pub enum Source {
219 Human,
221 Agent {
224 run: String,
226 node: String,
228 },
229 Issue {
231 number: u64,
233 repo: String,
235 },
236}
237
238pub const CHAT_NODE: &str = "chat";
241
242impl Source {
243 pub fn label(&self) -> String {
245 match self {
246 Self::Human => "human".to_owned(),
247 Self::Agent { run, node } => format!("{node}@{}", short(run)),
248 Self::Issue { number, .. } => format!("issue #{number}"),
249 }
250 }
251}
252
253#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
255#[serde(rename_all = "lowercase")]
256pub enum TaskStatus {
257 Queued,
259 Running,
261 Done,
263 Failed,
265 Held,
267 Blocked,
271 Parked,
276}
277
278impl TaskStatus {
279 pub fn runnable(self) -> bool {
281 matches!(self, Self::Queued | Self::Failed | Self::Parked)
282 }
283
284 pub fn as_str(self) -> &'static str {
286 match self {
287 Self::Queued => "queued",
288 Self::Running => "running",
289 Self::Done => "done",
290 Self::Failed => "failed",
291 Self::Held => "held",
292 Self::Blocked => "blocked",
293 Self::Parked => "parked",
294 }
295 }
296}
297
298#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
301pub struct TaskCounts {
302 pub queued: usize,
304 pub running: usize,
306 pub done: usize,
308 pub failed: usize,
310 pub held: usize,
312 pub blocked: usize,
314 pub parked: usize,
316}
317
318impl TaskCounts {
319 pub fn of(tasks: &[Task]) -> Self {
323 Self::of_statuses(tasks.iter().map(|task| task.status))
324 }
325
326 pub(crate) fn of_statuses(statuses: impl IntoIterator<Item = TaskStatus>) -> Self {
328 let mut counts = Self::default();
329 for status in statuses {
330 match status {
331 TaskStatus::Queued => counts.queued += 1,
332 TaskStatus::Running => counts.running += 1,
333 TaskStatus::Done => counts.done += 1,
334 TaskStatus::Failed => counts.failed += 1,
335 TaskStatus::Held => counts.held += 1,
336 TaskStatus::Blocked => counts.blocked += 1,
337 TaskStatus::Parked => counts.parked += 1,
338 }
339 }
340 counts
341 }
342}
343
344#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
346pub struct Reassignment {
347 pub from: PathBuf,
349 pub to: PathBuf,
351 pub actor: String,
353 pub at: Timestamp,
355 pub run_boundary: usize,
357}
358
359#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
361#[serde(tag = "kind", content = "talk", rename_all = "snake_case")]
362pub enum CompletionActor {
363 Cli,
365 Web,
367 Chat(String),
369 Conductor,
371 DaemonSettle,
373}
374
375#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
377#[serde(rename_all = "snake_case")]
378pub enum CompletionAction {
379 Complete,
381 Reopen,
383}
384
385#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
387pub struct CompletionRunSnapshot {
388 pub id: String,
390 pub status: Option<crate::run::RunStatus>,
392 pub pr_url: Option<String>,
394 pub pr_state: Option<String>,
396 pub pr_head: Option<String>,
398 #[serde(default)]
400 pub branches: Vec<String>,
401 pub error: Option<String>,
403}
404
405impl CompletionRunSnapshot {
406 fn from_run(state: &crate::run::RunState) -> Self {
407 let mut branches: Vec<String> = state
408 .candidates
409 .iter()
410 .map(|candidate| candidate.branch.clone())
411 .collect();
412 if let Some(branch) = &state.pr_head
413 && !branches.contains(branch)
414 {
415 branches.push(branch.clone());
416 }
417 Self {
418 id: state.id.clone(),
419 status: Some(state.status),
420 pr_url: state.pr.as_ref().map(|pr| pr.url.clone()),
421 pr_state: state.pr.as_ref().map(|pr| pr.state.clone()),
422 pr_head: state
423 .pr_merged_head
424 .clone()
425 .or_else(|| state.pr_pushed_head.clone()),
426 branches,
427 error: None,
428 }
429 }
430}
431
432#[derive(Debug, Clone)]
434pub struct CompletionContext {
435 pub actor: CompletionActor,
437 pub reason: Option<String>,
439 pub discard: bool,
441 pub run: Option<CompletionRunSnapshot>,
443 pub unavailable_runs: Vec<String>,
445}
446
447impl CompletionContext {
448 pub fn new(actor: CompletionActor, reason: Option<String>, home: &Path, task: &Task) -> Self {
450 let run = task
451 .runs
452 .last()
453 .map(|id| match crate::run::RunState::load_under(id, home) {
454 Ok(state) => CompletionRunSnapshot::from_run(&state),
455 Err(error) => CompletionRunSnapshot {
456 id: id.clone(),
457 status: None,
458 pr_url: None,
459 pr_state: None,
460 pr_head: None,
461 branches: Vec::new(),
462 error: Some(format!("{error:#}")),
463 },
464 });
465 Self {
466 actor,
467 reason,
468 discard: false,
469 run,
470 unavailable_runs: Vec::new(),
471 }
472 }
473
474 pub fn from_run(
476 actor: CompletionActor,
477 reason: Option<String>,
478 _task: &Task,
479 state: &crate::run::RunState,
480 ) -> Self {
481 Self {
482 actor,
483 reason,
484 discard: false,
485 run: Some(CompletionRunSnapshot::from_run(state)),
486 unavailable_runs: Vec::new(),
487 }
488 }
489}
490
491#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
493pub struct CompletionEvent {
494 pub occurrence: String,
496 pub action: CompletionAction,
498 pub actor: CompletionActor,
500 pub reason: Option<String>,
502 pub discard: bool,
504 pub prior_status: TaskStatus,
506 #[serde(default)]
508 pub prior_hold_reason: Option<String>,
509 #[serde(default)]
511 pub prior_block_reason: Option<String>,
512 #[serde(default)]
514 pub prior_error: Option<String>,
515 pub at: Timestamp,
517 pub run: Option<CompletionRunSnapshot>,
519 #[serde(default, skip_serializing_if = "Vec::is_empty")]
521 pub unavailable_runs: Vec<String>,
522}
523
524#[derive(Debug, Clone, Serialize, Deserialize)]
526#[serde(deny_unknown_fields)]
527pub struct Task {
528 pub schema: u32,
530 pub id: String,
532 pub title: String,
534 pub instruction: String,
536 #[serde(default, skip_serializing_if = "crate::refs::Sources::is_empty")]
538 pub sources: crate::refs::Sources,
539 pub repo: PathBuf,
541 #[serde(default)]
543 pub reassignments: Vec<Reassignment>,
544 pub source: Source,
546 #[serde(default)]
548 pub chat: Option<String>,
549 #[serde(default)]
551 pub priority: i32,
552 #[serde(default)]
563 pub solo: bool,
564 pub status: TaskStatus,
566 #[serde(default)]
568 pub completion_history: Vec<CompletionEvent>,
569 #[serde(default)]
571 pub attempts: usize,
572 #[serde(default)]
574 pub attempt_limit: Option<NonZeroUsize>,
575 #[serde(default)]
578 pub runs: Vec<String>,
579 #[serde(default)]
581 pub startup_failures: Vec<crate::run::StartupFailure>,
582 #[serde(default)]
584 pub last_error: Option<String>,
585 #[serde(default)]
598 pub hold_reason: Option<String>,
599 #[serde(default)]
602 pub hold_source: Option<HoldSource>,
603 #[serde(default, skip_serializing_if = "Option::is_none")]
604 recovery_budget_hold: Option<RecoveryBudgetHold>,
605 #[serde(default)]
607 pub machine_hold_cause: Option<MachineHoldCause>,
608 #[serde(default)]
610 pub disk_resume_run: Option<String>,
611 #[serde(default)]
613 pub disk_checked_at: Option<Timestamp>,
614 #[serde(default)]
626 pub diagnostic: Option<String>,
627 #[serde(default)]
637 pub blocked_by: Vec<String>,
638 #[serde(default)]
641 pub block_reason: Option<String>,
642 #[serde(default)]
655 pub blocked_from: Option<TaskStatus>,
656 #[serde(default)]
658 pub blocked_at: Option<Timestamp>,
659 #[serde(default)]
670 pub answers: Vec<AnsweredQuestion>,
671 #[serde(default)]
677 pub triage_applied: Vec<String>,
678 #[serde(default)]
684 pub actions_applied: Vec<String>,
685 #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
688 pub decision_effects: std::collections::BTreeMap<String, String>,
689 #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
692 pub superseded_resumes: std::collections::BTreeMap<String, String>,
693 #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
697 pub dispatched_resumes: std::collections::BTreeMap<String, String>,
698 #[serde(default)]
700 pub base_recovery_requests: Vec<String>,
701 #[serde(default)]
703 pub land_sync_recovery_requests: Vec<String>,
704 #[serde(default)]
709 pub resume_override: Option<OperatorResume>,
710 #[serde(default, skip_serializing_if = "Option::is_none")]
712 pub sync_only: Option<crate::base_sync_only::Request>,
713 #[serde(default)]
715 pub repair_grants: Vec<crate::repair_budget::Receipt>,
716 #[serde(default)]
718 pub repair_reconciliations: Vec<crate::repair_budget::reconcile::Receipt>,
719 #[serde(default)]
722 pub resumption: Option<Resumption>,
723 #[serde(default)]
725 pub resumption_history: Vec<Resumption>,
726 #[serde(default)]
728 pub operator_decided_at: Option<Timestamp>,
729 #[serde(default)]
741 pub review_branch: Option<String>,
742 #[serde(default)]
744 pub review_instruction: Option<String>,
745 #[serde(default)]
747 pub pr_recovery: Option<crate::pr_recovery::Selection>,
748 #[serde(default)]
751 pub fresh_start: bool,
752 #[serde(default)]
754 pub replacement: Option<crate::merge_decision::Replacement>,
755 #[serde(default)]
766 pub interrupt: bool,
767 #[serde(default)]
790 pub urgent: bool,
791 #[serde(skip)]
796 pub(crate) unfiled: bool,
797 #[serde(default)]
803 pub attachments: Vec<String>,
804 #[serde(default)]
808 pub followup: Option<FollowUp>,
809 #[serde(default)]
815 pub origin_chat: Option<String>,
816 #[serde(default)]
823 pub overrides: Option<RunOverrides>,
824 #[serde(default)]
831 pub review_of: Option<String>,
832 #[serde(default)]
837 pub held_at: Option<Timestamp>,
838 #[serde(default)]
842 pub park_reason: Option<String>,
843 #[serde(default)]
846 pub chat_notice: Option<ChatNotice>,
847 #[serde(default)]
849 pub chat_notices: Vec<String>,
850 #[serde(default)]
853 pub hold_notice_cause: Option<NoticeCause>,
854 #[serde(default)]
859 pub passes: Vec<TaskPass>,
860 #[serde(default)]
864 pub dispatched_at: Option<Timestamp>,
865 #[serde(default)]
867 pub recovery_budget: Option<RecoveryBudget>,
868 #[serde(default)]
871 pub recovery_admission: Option<RecoveryAdmission>,
872 #[serde(default)]
875 pub recovery_generations: Vec<RecoveryBudget>,
876 pub created_at: Timestamp,
878 pub updated_at: Timestamp,
880}
881
882#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
884pub struct RecoveryAdmission {
885 pub base: String,
887 pub inputs: String,
889}
890
891#[derive(Debug, Clone, Serialize, Deserialize)]
892struct RecoveryBudgetHold {
893 admission: RecoveryAdmission,
894 run: String,
895 pass: usize,
896 held_at: Timestamp,
897 decision: Option<Timestamp>,
898 #[serde(default)]
899 legacy: bool,
900}
901
902#[derive(Debug, Clone, Serialize, Deserialize)]
905pub struct RecoveryBudget {
906 pub instruction: String,
908 pub base: String,
910 pub inputs: String,
912 pub stage: String,
914 pub failures: usize,
916 #[serde(default)]
919 pub progress: Option<String>,
920}
921
922impl RecoveryBudget {
923 fn budget_reason(&self) -> String {
924 format!(
925 "[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.",
926 self.failures, self.stage
927 )
928 }
929}
930
931fn recovery_progress(state: &crate::run::RunState) -> Option<String> {
932 use crate::proc::Quiet as _;
933 use std::hash::{Hash, Hasher};
934 let mut patches = Vec::new();
935 for candidate in state.candidates.iter().filter(|c| c.commits > 0) {
936 let output = std::process::Command::new("git")
937 .current_dir(&state.repo)
938 .args(["diff", "--binary", &state.base_commit, &candidate.branch])
939 .quiet()
940 .output()
941 .ok()?;
942 if !output.status.success() {
943 return None;
944 }
945 patches.push(output.stdout);
946 }
947 patches.sort();
948 patches.dedup();
949 let mut hash = std::collections::hash_map::DefaultHasher::new();
950 patches.hash(&mut hash);
951 Some(format!("{:x}", hash.finish()))
952}
953
954pub(crate) fn recovery_inputs(sources: &crate::refs::Sources) -> String {
958 serde_json::to_string(
959 &sources
960 .start_from
961 .iter()
962 .map(|i| ("start", &i.token, &i.sha))
963 .chain(
964 sources
965 .pick_commits
966 .iter()
967 .map(|i| ("pick", &i.token, &i.sha)),
968 )
969 .collect::<Vec<_>>(),
970 )
971 .unwrap_or_default()
972}
973
974#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
976pub struct NoticeCause {
977 pub stage: String,
979 #[serde(default, skip_serializing_if = "Option::is_none")]
982 pub target: Option<String>,
983 pub run: Option<String>,
985 pub pass: Option<usize>,
987}
988
989pub(crate) fn is_done_notice_key(key: &str) -> bool {
991 key == "done"
992 || key
993 .strip_prefix("done#")
994 .is_some_and(|count| !count.is_empty() && count.bytes().all(|b| b.is_ascii_digit()))
995}
996
997#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
999#[serde(rename_all = "snake_case")]
1000pub enum PassCost {
1001 Spent,
1003 Refunded,
1005}
1006
1007#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1009pub struct TaskPass {
1010 pub run: String,
1012 pub pass_index: usize,
1014 pub cost: PassCost,
1016 pub attempts_after: usize,
1018 #[serde(default)]
1020 pub started_at: Option<Timestamp>,
1021 pub settled_at: Timestamp,
1023 #[serde(default)]
1025 pub parked: Option<crate::run::ParkCause>,
1026}
1027
1028#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1030#[serde(rename_all = "lowercase")]
1031pub enum ChatNoticeOutcome {
1032 Posted,
1034 Skipped,
1036}
1037
1038#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1040pub struct ChatNotice {
1041 pub key: String,
1043 pub at: Timestamp,
1045 pub outcome: ChatNoticeOutcome,
1047}
1048
1049#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1051pub struct RunOverrides {
1052 #[serde(default)]
1055 pub inherit_daemon_options: bool,
1056 #[serde(default)]
1058 pub merge: Option<String>,
1059 #[serde(default)]
1061 pub candidates: Option<usize>,
1062 #[serde(default)]
1064 pub judges: Option<usize>,
1065 #[serde(default)]
1067 pub reviewers: Option<usize>,
1068 #[serde(default)]
1070 pub review_rounds: Option<usize>,
1071 #[serde(default)]
1073 pub seed: Option<u64>,
1074 #[serde(default)]
1076 pub config: Option<PathBuf>,
1077 #[serde(default, skip_serializing_if = "Option::is_none")]
1079 pub build_cache: Option<BuildCache>,
1080}
1081
1082impl RunOverrides {
1083 pub fn merge_over(&mut self, other: &RunOverrides) {
1085 macro_rules! take {
1086 ($($f:ident),*) => {$(
1087 if other.$f.is_some() {
1088 self.$f.clone_from(&other.$f);
1089 }
1090 )*};
1091 }
1092 take!(
1093 merge,
1094 candidates,
1095 judges,
1096 reviewers,
1097 review_rounds,
1098 seed,
1099 config,
1100 build_cache
1101 );
1102 }
1103
1104 pub fn apply(&self, config: &mut crate::config::Config) {
1106 if let Some(n) = self.candidates {
1107 config.graph.implementers = n;
1108 }
1109 if let Some(n) = self.judges {
1110 config.graph.judges = n;
1111 }
1112 if let Some(n) = self.reviewers {
1113 config.graph.reviewers = n;
1114 }
1115 if let Some(n) = self.review_rounds {
1116 config.graph.review_rounds = n;
1117 }
1118 if let Some(m) = &self.merge
1119 && let Ok(mode) = crate::daemon::merge_mode(m)
1120 {
1121 config.merge.mode = mode;
1122 }
1123 if let Some(s) = self.seed {
1124 config.blind.seed = Some(s);
1125 }
1126 if let Some(mode) = self.build_cache {
1127 config.verify.build_cache = mode;
1128 }
1129 }
1130}
1131
1132#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1134pub struct FollowUp {
1135 pub run: String,
1137 #[serde(default)]
1139 pub origin_task: Option<String>,
1140 pub pr: String,
1142 pub findings: Vec<String>,
1144 pub generation: u32,
1147}
1148
1149#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1151pub struct Resumption {
1152 pub generation: u64,
1154 pub source: String,
1156 pub question_id: Option<String>,
1158 pub at: Timestamp,
1160 pub instruction: String,
1162 pub answers_through: usize,
1164 pub runs_through: usize,
1167 pub cleared_reason: Option<String>,
1169 #[serde(default)]
1171 pub blocking_evidence: Vec<String>,
1172}
1173
1174#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1177pub struct OperatorResume {
1178 pub question_id: String,
1180 pub at: Timestamp,
1182 #[serde(default)]
1185 pub conductor_rehold: Option<String>,
1186 #[serde(default)]
1189 pub forced: bool,
1190 #[serde(default)]
1197 pub pinned_run: Option<String>,
1198}
1199
1200#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1203pub struct AnsweredQuestion {
1204 pub question: String,
1206 pub answer: String,
1208}
1209
1210fn append_missing<T: PartialEq>(ledger: &mut Vec<T>, entries: Vec<T>) {
1211 for entry in entries {
1212 if !ledger.contains(&entry) {
1213 ledger.push(entry);
1214 }
1215 }
1216}
1217
1218fn prepend_missing_by<T>(ledger: &mut Vec<T>, mut older: Vec<T>, same: impl Fn(&T, &T) -> bool) {
1219 older.retain(|old| !ledger.iter().any(|entry| same(entry, old)));
1220 if !older.is_empty() {
1221 older.append(ledger);
1222 *ledger = older;
1223 }
1224}
1225
1226impl Task {
1227 pub fn new(title: String, instruction: String, repo: PathBuf, source: Source) -> Self {
1229 let now = Timestamp::now();
1230 let origin_chat = match &source {
1231 Source::Agent { run, node } if node == CHAT_NODE => Some(run.clone()),
1232 _ => None,
1233 };
1234 Self {
1235 schema: SCHEMA,
1236 id: new_id(),
1237 title,
1238 instruction,
1239 sources: crate::refs::Sources::default(),
1240 repo,
1241 reassignments: Vec::new(),
1242 source,
1243 chat: None,
1244 priority: 0,
1245 solo: false,
1246 status: TaskStatus::Queued,
1247 completion_history: Vec::new(),
1248 attempts: 0,
1249 attempt_limit: None,
1250 runs: Vec::new(),
1251 startup_failures: Vec::new(),
1252 last_error: None,
1253 hold_reason: None,
1254 hold_source: None,
1255 recovery_budget_hold: None,
1256 machine_hold_cause: None,
1257 disk_resume_run: None,
1258 disk_checked_at: None,
1259 diagnostic: None,
1260 blocked_by: Vec::new(),
1261 block_reason: None,
1262 blocked_from: None,
1263 blocked_at: None,
1264 answers: Vec::new(),
1265 triage_applied: Vec::new(),
1266 actions_applied: Vec::new(),
1267 decision_effects: Default::default(),
1268 superseded_resumes: Default::default(),
1269 dispatched_resumes: Default::default(),
1270 base_recovery_requests: Vec::new(),
1271 land_sync_recovery_requests: Vec::new(),
1272 resume_override: None,
1273 sync_only: None,
1274 repair_grants: Vec::new(),
1275 repair_reconciliations: Vec::new(),
1276 resumption: None,
1277 resumption_history: Vec::new(),
1278 operator_decided_at: None,
1279 review_branch: None,
1280 review_instruction: None,
1281 pr_recovery: None,
1282 fresh_start: false,
1283 replacement: None,
1284 interrupt: false,
1285 urgent: false,
1286 unfiled: true,
1287 attachments: Vec::new(),
1288 followup: None,
1289 origin_chat,
1290 overrides: None,
1291 review_of: None,
1292 held_at: None,
1293 park_reason: None,
1294 chat_notice: None,
1295 chat_notices: Vec::new(),
1296 hold_notice_cause: None,
1297 passes: Vec::new(),
1298 dispatched_at: None,
1299 recovery_budget: None,
1300 recovery_admission: None,
1301 recovery_generations: Vec::new(),
1302 created_at: now,
1303 updated_at: now,
1304 }
1305 }
1306
1307 pub(crate) fn reassign_repository(&mut self, repo: PathBuf, actor: &str) {
1309 self.stamp_schema();
1310 if matches!(self.status, TaskStatus::Failed | TaskStatus::Parked) {
1311 self.hold_manual(Some(
1312 "Repository reassigned; inspect history and release to start fresh.".into(),
1313 ));
1314 }
1315 let at = Timestamp::now();
1316 self.reassignments.push(Reassignment {
1317 from: self.repo.clone(),
1318 to: repo.clone(),
1319 actor: actor.to_owned(),
1320 at,
1321 run_boundary: self.runs.len(),
1322 });
1323 self.repo = repo;
1324 self.review_branch = None;
1325 self.review_instruction = None;
1326 self.pr_recovery = None;
1327 self.replacement = None;
1328 self.interrupt = false;
1329 self.resume_override = None;
1330 self.fresh_start = true;
1331 self.operator_decided_at = Some(at);
1332 }
1333
1334 pub fn publication_branch(&self) -> String {
1336 crate::run::task_pr_branch_name(&self.id, self.reassignments.len())
1337 }
1338
1339 pub fn execution_runs(&self) -> &[String] {
1341 let boundary = self.reassignments.last().map_or(0, |r| r.run_boundary);
1342 self.runs.get(boundary..).unwrap_or_default()
1343 }
1344
1345 pub fn execution_run(&self, run: &str) -> bool {
1347 self.execution_runs().iter().any(|id| id == run)
1348 }
1349
1350 pub(crate) fn assignment_accepts(&self, run: &crate::run::RunState) -> bool {
1352 self.reassignments.last().is_none_or(|boundary| {
1353 self.execution_run(&run.id)
1354 && run.task_assignment == self.reassignments.len()
1355 && run.created_at > boundary.at
1356 && run
1357 .repo
1358 .canonicalize()
1359 .ok()
1360 .zip(self.repo.canonicalize().ok())
1361 .is_some_and(|(run_repo, task_repo)| run_repo == task_repo)
1362 })
1363 }
1364
1365 pub(crate) fn stale_question(&self, q: &crate::ask::Question) -> bool {
1367 self.reassignments
1368 .last()
1369 .is_some_and(|r| q.asked_at <= r.at)
1370 || (self.runs.contains(&q.run) && !self.execution_run(&q.run))
1371 }
1372
1373 pub fn chat_talk(&self) -> Option<&str> {
1375 if let Some(id) = &self.origin_chat {
1376 return Some(id);
1377 }
1378 match &self.source {
1379 Source::Agent { run, node } if node == CHAT_NODE => Some(run),
1380 _ => None,
1381 }
1382 }
1383
1384 pub fn filed_by_chat(&self) -> Option<&str> {
1388 match &self.source {
1389 Source::Agent { run, node } if node == CHAT_NODE => Some(run),
1390 _ => None,
1391 }
1392 }
1393
1394 pub fn chat_notice_key(&self) -> Option<String> {
1397 match self.status {
1398 TaskStatus::Done => Some(
1399 self.completion_history
1400 .iter()
1401 .rev()
1402 .find(|event| event.action == CompletionAction::Complete)
1403 .map_or_else(
1404 || "done".to_owned(),
1405 |event| format!("done:{}", event.occurrence),
1406 ),
1407 ),
1408 TaskStatus::Held => {
1409 let cause = self
1410 .hold_notice_cause
1411 .clone()
1412 .unwrap_or_else(|| self.unresolved_hold_cause());
1413 Some(format!(
1414 "cause:{}",
1415 serde_json::to_string(&cause).expect("cause")
1416 ))
1417 }
1418 TaskStatus::Blocked => {
1419 let ids: std::collections::BTreeSet<_> = self.blocked_by.iter().collect();
1420 let evidence = self
1423 .hold_notice_cause
1424 .as_ref()
1425 .filter(|c| c.stage.starts_with("conductor-evidence:"));
1426 Some(format!(
1427 "dependencies:{}",
1428 serde_json::to_string(&(ids, evidence)).expect("ids")
1429 ))
1430 }
1431 _ => None,
1432 }
1433 }
1434
1435 fn unresolved_hold_cause(&self) -> NoticeCause {
1436 NoticeCause {
1437 stage: "hold".into(),
1438 target: None,
1439 run: self.runs.last().cloned(),
1440 pass: None,
1441 }
1442 }
1443
1444 pub(crate) fn legacy_chat_notice_key(&self) -> Option<String> {
1446 let key = match self.status {
1447 TaskStatus::Held if self.hold_notice_cause.is_none() => Some(format!(
1448 "held#{}",
1449 self.held_at.map(|t| t.to_string()).unwrap_or_default()
1450 )),
1451 TaskStatus::Blocked => Some(format!(
1452 "blocked#{}#{}",
1453 self.blocked_by.join(","),
1454 self.block_reason.as_deref().unwrap_or_default()
1455 )),
1456 _ => None,
1457 };
1458 key.filter(|key| self.legacy_notice_matches(key))
1459 }
1460
1461 pub(crate) fn legacy_notice_matches(&self, key: &str) -> bool {
1462 match self.status {
1463 TaskStatus::Held if self.hold_notice_cause.is_none() => key
1464 .strip_prefix("held#")
1465 .is_some_and(|time| time.is_empty() || time.parse::<Timestamp>().is_ok()),
1466 TaskStatus::Blocked
1467 if self
1468 .hold_notice_cause
1469 .as_ref()
1470 .is_none_or(|c| !c.stage.starts_with("conductor-evidence:")) =>
1471 {
1472 key.strip_prefix("blocked#").is_some_and(|tail| {
1473 let Some((ids, _)) = tail.split_once('#') else {
1474 return false;
1475 };
1476 let old: std::collections::BTreeSet<_> =
1477 ids.split(',').filter(|id| !id.is_empty()).collect();
1478 let current: std::collections::BTreeSet<_> =
1479 self.blocked_by.iter().map(String::as_str).collect();
1480 old == current
1481 })
1482 }
1483 _ => false,
1484 }
1485 }
1486
1487 fn import_chat_notice(&mut self) {
1488 if let Some(n) = &self.chat_notice {
1489 let key = if is_done_notice_key(&n.key) {
1490 "done".to_owned()
1491 } else if self.legacy_notice_matches(&n.key) {
1492 self.chat_notice_key().unwrap_or_else(|| n.key.clone())
1493 } else {
1494 n.key.clone()
1495 };
1496 if !self.chat_notices.contains(&key) {
1497 self.chat_notices.push(key);
1498 }
1499 }
1500 }
1501
1502 pub(crate) fn notice_cause(&mut self, stage: &str, run: Option<&str>, pass: Option<usize>) {
1505 self.import_chat_notice();
1506 self.hold_notice_cause = Some(NoticeCause {
1507 stage: stage.to_owned(),
1508 target: None,
1509 run: run.map(str::to_owned),
1510 pass,
1511 });
1512 }
1513
1514 pub(crate) fn startup_notice_cause(&mut self, stage: &str) {
1517 let recovery_only = matches!(
1518 stage,
1519 "startup-source" | "startup-candidates" | "startup-public-head"
1520 );
1521 match self.hold_notice_cause.as_ref() {
1522 Some(cause) if recovery_only && !cause.stage.starts_with("startup-") => return,
1523 None if recovery_only
1524 && self
1525 .chat_notice
1526 .as_ref()
1527 .is_some_and(|n| !is_done_notice_key(&n.key)) =>
1528 {
1529 return;
1530 }
1531 _ => {}
1532 }
1533 self.notice_cause(stage, None, None);
1534 }
1535
1536 pub(crate) fn fail_startup(
1539 &mut self,
1540 stage: &str,
1541 why: impl Into<String>,
1542 max_attempts: usize,
1543 ) {
1544 let unresolved = self.hold_notice_cause.clone();
1545 self.fail(why, max_attempts);
1546 self.hold_notice_cause = unresolved;
1547 self.startup_notice_cause(stage);
1548 }
1549
1550 pub(crate) fn fail_startup_target(
1552 &mut self,
1553 stage: &str,
1554 target: String,
1555 why: impl Into<String>,
1556 max_attempts: usize,
1557 ) {
1558 self.fail_startup(stage, why, max_attempts);
1559 if let Some(cause) = self.hold_notice_cause.as_mut() {
1560 cause.target = Some(target);
1561 }
1562 }
1563
1564 pub fn chat_notice_due(&self) -> Option<String> {
1566 self.filed_by_chat()?;
1567 if self.schema < 13 {
1568 return None;
1569 }
1570 let key = self.chat_notice_key()?;
1571 if self.chat_notices.contains(&key) {
1572 return None;
1573 }
1574 match &self.chat_notice {
1575 Some(n)
1576 if n.key == key
1577 || (key == "done" && is_done_notice_key(&n.key))
1578 || self.legacy_notice_matches(&n.key) =>
1579 {
1580 None
1581 }
1582 _ => Some(key),
1583 }
1584 }
1585
1586 pub fn short(&self) -> &str {
1588 short(&self.id)
1589 }
1590
1591 pub fn mark_triage_applied(&mut self, question_id: &str) {
1593 if !self.triage_applied(question_id) {
1594 self.triage_applied.push(question_id.to_owned());
1595 }
1596 }
1597
1598 pub fn action_applied(&self, question_id: &str) -> bool {
1601 self.actions_applied.iter().any(|id| id == question_id)
1602 }
1603
1604 pub fn mark_action_applied(&mut self, question_id: &str) {
1606 if !self.action_applied(question_id) {
1607 self.actions_applied.push(question_id.to_owned());
1608 }
1609 }
1610
1611 pub fn triage_applied(&self, question_id: &str) -> bool {
1613 self.triage_applied.iter().any(|id| id == question_id)
1614 }
1615
1616 pub fn start(&mut self, run: String) {
1629 self.stamp_schema();
1630 self.status = TaskStatus::Running;
1631 self.attempts += 1;
1632 self.runs.retain(|id| id != &run);
1633 if let Some(pin) = &self.resume_override
1634 && pin.pinned_run.as_ref() == Some(&run)
1635 && !pin.question_id.is_empty()
1636 {
1637 self.dispatched_resumes
1638 .insert(pin.question_id.clone(), run.clone());
1639 }
1640 self.runs.push(run);
1641 self.last_error = None;
1642 self.park_reason = None;
1643 self.fresh_start = false;
1644 self.interrupt = false;
1645 self.resume_override = None;
1647 self.disk_resume_run = None;
1650 }
1651
1652 pub fn record_startup_failure(&mut self, failure: crate::run::StartupFailure) {
1654 if !self.startup_failures.iter().any(|f| f.run == failure.run) {
1655 self.startup_failures.push(failure);
1656 }
1657 }
1658
1659 pub fn link_run(&mut self, run: &str) -> bool {
1664 if self.runs.iter().any(|r| r == run) {
1665 return false;
1666 }
1667 self.runs.push(run.to_owned());
1668 true
1669 }
1670
1671 pub fn succeed(&mut self, context: CompletionContext) {
1681 if self.status == TaskStatus::Done {
1682 return;
1683 }
1684 self.record_completion(CompletionAction::Complete, context);
1685 self.stamp_schema();
1686 self.status = TaskStatus::Done;
1687 if let Some(pin) = self.resume_override.take()
1688 && !pin.question_id.is_empty()
1689 && let Some(run) = pin.pinned_run
1690 {
1691 self.superseded_resumes.insert(pin.question_id, run);
1694 }
1695 self.sync_only = None;
1696 self.last_error = None;
1697 self.park_reason = None;
1698 self.hold_reason = None;
1699 self.hold_source = None;
1700 self.machine_hold_cause = None;
1701 self.disk_resume_run = None;
1702 self.disk_checked_at = None;
1703 self.diagnostic = None;
1704 self.blocked_by.clear();
1705 self.block_reason = None;
1706 self.blocked_from = None;
1707 }
1708
1709 pub fn already_landed(&mut self, note: impl Into<String>, mut context: CompletionContext) {
1717 let note = note.into();
1718 if context.reason.is_none() {
1719 context.reason = Some(note.clone());
1720 }
1721 self.succeed(context);
1722 self.attempts = self.attempts.saturating_sub(1);
1723 self.last_error = Some(note);
1724 }
1725
1726 fn record_completion(&mut self, action: CompletionAction, context: CompletionContext) {
1727 self.completion_history.push(CompletionEvent {
1728 occurrence: format!(
1729 "{}-{:016x}{:016x}",
1730 Timestamp::now(),
1731 crate::rng::entropy(),
1732 crate::rng::entropy()
1733 ),
1734 action,
1735 actor: context.actor,
1736 reason: context.reason,
1737 discard: context.discard,
1738 prior_status: self.status,
1739 at: Timestamp::now(),
1740 prior_hold_reason: self.hold_reason.clone(),
1741 prior_block_reason: self.block_reason.clone(),
1742 prior_error: self.last_error.clone(),
1743 run: context.run,
1744 unavailable_runs: context.unavailable_runs,
1745 });
1746 self.stamp_schema();
1747 }
1748
1749 pub fn reopen(&mut self, context: CompletionContext) -> Result<()> {
1752 anyhow::ensure!(
1753 self.status == TaskStatus::Done,
1754 "only a done task can be reopened"
1755 );
1756 anyhow::ensure!(
1757 context
1758 .reason
1759 .as_deref()
1760 .is_some_and(|reason| !reason.trim().is_empty()),
1761 "reopen requires a non-empty reason"
1762 );
1763 let reason = context.reason.clone();
1764 self.record_completion(CompletionAction::Reopen, context);
1765 self.hold_manual(reason);
1766 self.resume_override = None;
1767 self.fresh_start = false;
1768 self.last_error = None;
1769 self.diagnostic = None;
1770 Ok(())
1771 }
1772
1773 pub fn superseded_attempts(&self, last_run_succeeded: bool) -> &[String] {
1803 if self.status != TaskStatus::Done || !last_run_succeeded || self.execution_runs().len() < 2
1804 {
1805 return &[];
1806 }
1807 &self.execution_runs()[..self.execution_runs().len() - 1]
1808 }
1809
1810 pub fn successor_of(&self, run: &str) -> Option<&String> {
1818 let runs = self.execution_runs();
1819 let pos = runs.iter().rposition(|r| r == run)?;
1820 runs.get(pos + 1)
1821 }
1822
1823 pub fn earlier_attempts(&self) -> &[String] {
1830 self.execution_runs()
1831 }
1832
1833 fn preserve_legacy_build_cache(&mut self) {
1834 if self.schema < 23 {
1835 let overrides = self.overrides.get_or_insert_with(|| RunOverrides {
1836 inherit_daemon_options: true,
1837 ..RunOverrides::default()
1838 });
1839 overrides.build_cache.get_or_insert(BuildCache::Shared);
1840 }
1841 }
1842
1843 fn stamp_schema(&mut self) {
1848 self.preserve_legacy_build_cache();
1849 if self.schema < RECOVERY_HOLD_SCHEMA && self.recovery_budget_hold.is_none() {
1850 self.recovery_budget_hold = self.legacy_recovery_budget_hold();
1851 }
1852 self.schema = self.schema.max(SCHEMA);
1853 }
1854
1855 fn note_held(&mut self) {
1858 self.stamp_schema();
1859 self.recovery_budget_hold = None;
1860 let continuing = self.status == TaskStatus::Held
1861 || (self.status == TaskStatus::Blocked
1862 && (self.blocked_from == Some(TaskStatus::Held)
1863 || (self.blocked_from.is_none()
1864 && (self.hold_reason.is_some() || self.hold_source.is_some()))));
1865 if !continuing || self.held_at.is_none() {
1866 self.held_at = Some(Timestamp::now());
1867 }
1868 }
1869
1870 pub fn fail(&mut self, why: impl Into<String>, max_attempts: usize) {
1886 let why = why.into();
1887 if self.status == TaskStatus::Running {
1888 let run = self.runs.last().cloned();
1889 self.notice_cause("run-failed", run.as_deref(), Some(self.attempts));
1890 }
1891 self.diagnostic = None;
1892 self.park_reason = None;
1893 self.status = if self.attempts >= self.effective_attempt_limit(max_attempts) {
1894 self.note_held();
1895 self.hold_source = Some(HoldSource::Machine);
1896 self.machine_hold_cause = None;
1897 self.disk_resume_run = None;
1898 self.disk_checked_at = None;
1899 self.hold_reason = Some(why.clone());
1900 TaskStatus::Held
1901 } else {
1902 TaskStatus::Failed
1903 };
1904 self.last_error = Some(why);
1905 }
1906
1907 pub fn stall(&mut self, why: impl Into<String>) {
1917 self.last_error = Some(why.into());
1918 self.diagnostic = None;
1919 self.attempts = self.attempts.saturating_sub(1);
1920 self.status = TaskStatus::Failed;
1921 }
1922
1923 pub fn park(&mut self, why: impl Into<String>) {
1929 self.diagnostic = None;
1930 self.attempts = self.attempts.saturating_sub(1);
1931 self.status = TaskStatus::Parked;
1932 self.park_reason = Some(why.into());
1933 self.stamp_schema();
1936 }
1937
1938 pub fn record_pass(
1940 &mut self,
1941 run: &str,
1942 pass_index: usize,
1943 attempts_before: usize,
1944 parked: Option<crate::run::ParkCause>,
1945 ) {
1946 self.record_pass_at(run, pass_index, None, attempts_before, parked);
1947 }
1948
1949 pub fn record_pass_at(
1952 &mut self,
1953 run: &str,
1954 pass_index: usize,
1955 started_at: Option<Timestamp>,
1956 attempts_before: usize,
1957 parked: Option<crate::run::ParkCause>,
1958 ) {
1959 if self
1960 .passes
1961 .iter()
1962 .any(|p| p.run == run && p.pass_index == pass_index)
1963 {
1964 return;
1965 }
1966 let cost = if self.attempts < attempts_before {
1967 PassCost::Refunded
1968 } else {
1969 PassCost::Spent
1970 };
1971 self.passes.push(TaskPass {
1972 run: run.to_owned(),
1973 pass_index,
1974 started_at: self.dispatched_at.or(started_at),
1975 cost,
1976 attempts_after: self.attempts,
1977 settled_at: Timestamp::now(),
1978 parked,
1979 });
1980 self.stamp_schema();
1981 }
1982
1983 pub(crate) fn upgrade_resume_key(&self) -> Option<(Timestamp, &str)> {
1986 if self.status != TaskStatus::Parked || self.fresh_start {
1987 return None;
1988 }
1989 let pass = self.passes.last()?;
1990 if self.execution_runs().last() != Some(&pass.run)
1991 || !matches!(pass.parked, Some(crate::run::ParkCause::Upgrade { .. }))
1992 {
1993 return None;
1994 }
1995 Some((pass.started_at.unwrap_or(pass.settled_at), &self.id))
1998 }
1999
2000 pub fn operator_held(&self) -> bool {
2006 self.status == TaskStatus::Held && !matches!(self.hold_source, Some(HoldSource::Machine))
2007 }
2008
2009 pub fn hold_manual(&mut self, reason: Option<String>) {
2019 self.operator_decided_at = Some(Timestamp::now());
2021 if self.status != TaskStatus::Running && self.sync_only.take().is_some() {
2022 self.resume_override = None;
2023 }
2024 self.hold_unrequested_retry(reason);
2025 }
2026
2027 pub(crate) fn hold_unrequested_retry(&mut self, reason: Option<String>) {
2030 self.park_reason = None;
2031 self.note_held();
2032 self.status = TaskStatus::Held;
2033 if reason.is_some() {
2034 self.hold_reason = reason;
2035 }
2036 self.hold_source = Some(HoldSource::Manual);
2037 self.machine_hold_cause = None;
2038 self.disk_resume_run = None;
2039 self.disk_checked_at = None;
2040 self.blocked_by.clear();
2041 self.block_reason = None;
2042 self.blocked_from = None;
2043 }
2044
2045 pub(crate) fn hold_after_sync_only(&mut self, reason: String) {
2046 let recovery_hold = self.recovery_budget_hold.take();
2047 self.hold_unrequested_retry(Some(reason));
2048 self.recovery_budget_hold = recovery_hold;
2049 }
2050
2051 pub fn hold_machine(&mut self, reason: Option<String>) {
2056 self.park_reason = None;
2057 self.note_held();
2058 self.status = TaskStatus::Held;
2059 if reason.is_some() {
2060 self.hold_reason = reason;
2061 }
2062 self.hold_source = Some(HoldSource::Machine);
2063 self.machine_hold_cause = None;
2064 self.disk_resume_run = None;
2065 self.disk_checked_at = None;
2066 self.blocked_by.clear();
2067 self.block_reason = None;
2068 self.blocked_from = None;
2069 }
2070
2071 pub(crate) fn mark_disk_capacity(&mut self) {
2073 self.machine_hold_cause = Some(MachineHoldCause::DiskCapacity {
2074 reason: self.hold_reason.clone().unwrap_or_default(),
2075 before_start: false,
2076 });
2077 }
2078
2079 pub(crate) fn mark_startup_disk_capacity(&mut self) {
2080 self.machine_hold_cause = Some(MachineHoldCause::DiskCapacity {
2081 reason: self.hold_reason.clone().unwrap_or_default(),
2082 before_start: true,
2083 });
2084 }
2085
2086 pub(crate) fn disk_wait_run(&self) -> Option<&String> {
2087 if self.has_disk_capacity_cause()
2088 && matches!(
2089 self.machine_hold_cause,
2090 Some(MachineHoldCause::DiskCapacity {
2091 before_start: true,
2092 ..
2093 })
2094 )
2095 {
2096 None
2097 } else {
2098 self.execution_runs().last()
2099 }
2100 }
2101
2102 pub fn has_disk_capacity_cause(&self) -> bool {
2104 matches!(
2105 (&self.machine_hold_cause, self.hold_reason.as_deref()),
2106 (Some(MachineHoldCause::DiskCapacity { reason, .. }), Some(now)) if reason == now
2107 )
2108 }
2109
2110 pub(crate) fn resume_disk_wait(&mut self) {
2112 let retained = self.disk_wait_run().cloned();
2113 self.status = TaskStatus::Queued;
2114 self.held_at = None;
2115 self.hold_source = None;
2116 self.hold_reason = None;
2117 self.machine_hold_cause = None;
2118 self.last_error = None;
2119 self.disk_resume_run = retained;
2120 }
2121
2122 pub(crate) fn hold_head_e2e(
2124 &mut self,
2125 stop: crate::head_e2e_stop::Stop,
2126 reason: String,
2127 last_error: String,
2128 ) {
2129 self.hold_machine(Some(reason));
2130 self.last_error = Some(last_error);
2131 self.machine_hold_cause = Some(MachineHoldCause::HeadE2e { stop });
2132 }
2133
2134 pub(crate) fn head_e2e_notice(&mut self, stop: &crate::head_e2e_stop::Stop) {
2136 if let Some(at) = stop.recorded_at {
2137 self.held_at = Some(at);
2138 }
2139 self.notice_cause(crate::head_e2e_stop::NOTICE_STAGE, Some(&stop.run), None);
2140 if let Some(cause) = &mut self.hold_notice_cause {
2141 cause.target = Some(stop.id.clone());
2142 }
2143 }
2144
2145 pub fn has_head_e2e_cause(&self) -> bool {
2147 matches!(
2148 self.machine_hold_cause,
2149 Some(MachineHoldCause::HeadE2e { .. })
2150 )
2151 }
2152
2153 pub fn head_e2e_stop_id(&self) -> Option<&str> {
2155 if let Some(MachineHoldCause::HeadE2e { stop }) = &self.machine_hold_cause {
2156 return Some(stop.id.as_str());
2157 }
2158 self.hold_notice_cause
2159 .as_ref()
2160 .filter(|c| c.stage == crate::head_e2e_stop::NOTICE_STAGE)
2161 .and_then(|c| c.target.as_deref())
2162 }
2163
2164 pub(crate) fn resume_head_e2e_wait(&mut self) {
2167 self.status = TaskStatus::Queued;
2168 self.held_at = None;
2169 self.hold_source = None;
2170 self.hold_reason = None;
2171 self.machine_hold_cause = None;
2172 self.last_error = None;
2173 self.diagnostic = None;
2174 self.blocked_by.clear();
2175 self.block_reason = None;
2176 self.blocked_from = None;
2177 }
2178
2179 pub fn block(&mut self, blocked_by: Vec<String>, reason: Option<String>) {
2189 self.stamp_schema();
2190 let before: std::collections::BTreeSet<_> = self.blocked_by.iter().collect();
2191 let after: std::collections::BTreeSet<_> = blocked_by.iter().collect();
2192 if self.status != TaskStatus::Blocked || before != after {
2193 self.blocked_at = Some(Timestamp::now());
2194 }
2195 if self.status != TaskStatus::Blocked {
2196 self.blocked_from = Some(self.status);
2197 }
2198 self.status = TaskStatus::Blocked;
2199 self.blocked_by = blocked_by;
2200 self.block_reason = reason;
2201 }
2202
2203 pub fn unblock(&mut self, resolved_id: &str) {
2226 if self.status != TaskStatus::Blocked {
2227 return;
2228 }
2229 self.blocked_by.retain(|id| id != resolved_id);
2230 self.restore_if_unblocked();
2231 }
2232
2233 pub fn dependency_deleted(&mut self, deleted_id: &str) -> bool {
2244 if self.status != TaskStatus::Blocked || !self.blocked_by.iter().any(|b| b == deleted_id) {
2245 return false;
2246 }
2247 self.blocked_by.retain(|id| id != deleted_id);
2248 self.restore_if_unblocked();
2249 true
2250 }
2251
2252 fn restore_if_unblocked(&mut self) {
2256 if self.blocked_by.is_empty() {
2257 self.status = match self.blocked_from {
2258 Some(TaskStatus::Running) => TaskStatus::Queued,
2259 Some(other) => other,
2260 None if self.hold_reason.is_some() || self.hold_source.is_some() => {
2261 TaskStatus::Held
2262 }
2263 None => TaskStatus::Queued,
2264 };
2265 self.block_reason = None;
2266 self.blocked_from = None;
2267 }
2268 }
2269
2270 pub fn record_answer(&mut self, question: String, answer: String) {
2275 self.answers.push(AnsweredQuestion { question, answer });
2276 }
2277
2278 pub fn request_review(&mut self, branch: String) {
2282 self.release();
2283 self.review_branch = Some(branch);
2284 self.review_instruction = Some(self.instruction.clone());
2285 }
2286
2287 pub fn requeue(&mut self) {
2290 self.release();
2291 self.review_branch = None;
2293 self.review_instruction = None;
2294 self.fresh_start = true;
2295 }
2296
2297 pub fn hold_for_handover(&mut self, branch: Option<String>, reason: String) {
2306 if branch.is_some() {
2307 self.review_branch = branch;
2308 self.review_instruction = Some(self.instruction.clone());
2309 }
2310 self.hold_machine(Some(reason));
2311 }
2312
2313 pub fn set_urgent(&mut self, urgent: bool) -> Result<()> {
2315 if !matches!(self.status, TaskStatus::Queued | TaskStatus::Held) {
2316 bail!(
2317 "task {} is {}; urgent can only change while queued or held; \
2318 wait for the active attempt to finish and requeue or hold the task first",
2319 self.short(),
2320 self.status.as_str()
2321 );
2322 }
2323 self.urgent = urgent;
2324 Ok(())
2325 }
2326
2327 pub fn set_priority(&mut self, priority: i32) -> Result<()> {
2336 if self.status == TaskStatus::Running {
2337 bail!(
2338 "task {} is running; its priority cannot be changed until \
2339 this attempt finishes",
2340 self.short()
2341 );
2342 }
2343 self.priority = priority;
2344 Ok(())
2345 }
2346
2347 pub fn set_interrupt(&mut self, interrupt: bool) -> Result<()> {
2362 if interrupt && !self.status.runnable() {
2363 bail!(
2364 "task {} is {}; only a queued or failed task can be marked \
2365 to interrupt",
2366 self.short(),
2367 self.status.as_str()
2368 );
2369 }
2370 self.interrupt = interrupt;
2371 Ok(())
2372 }
2373
2374 pub fn effective_attempt_limit(&self, daemon_limit: usize) -> usize {
2376 self.attempt_limit.map_or(daemon_limit, NonZeroUsize::get)
2377 }
2378
2379 pub fn change_attempt_limit(&mut self, limit: Option<NonZeroUsize>) -> Result<()> {
2382 if !matches!(self.status, TaskStatus::Queued | TaskStatus::Held) {
2383 bail!("only queued or held tasks can change the attempt limit");
2384 }
2385 self.stamp_schema();
2386 self.attempt_limit = limit;
2387 Ok(())
2388 }
2389
2390 pub fn implementers(&self) -> Option<usize> {
2392 if self.solo {
2393 Some(1)
2394 } else {
2395 self.overrides.as_ref().and_then(|o| o.candidates)
2396 }
2397 }
2398
2399 pub fn build_cache_override(
2403 &self,
2404 config: &crate::config::Config,
2405 ) -> Option<(BuildCache, &'static str)> {
2406 self.overrides
2407 .as_ref()
2408 .and_then(|o| o.build_cache)
2409 .map(|mode| (mode, "task-override"))
2410 .or_else(|| {
2411 (self.urgent && crate::build_target::urgent_isolation(config))
2412 .then_some((BuildCache::Isolated, "urgent"))
2413 })
2414 }
2415
2416 pub fn change_build_cache(&mut self, mode: Option<BuildCache>) -> Result<()> {
2419 if !matches!(self.status, TaskStatus::Queued | TaskStatus::Held) {
2420 bail!(
2421 "task {} is {}; only queued or held tasks can change build cache",
2422 self.short(),
2423 self.status.as_str()
2424 );
2425 }
2426 self.stamp_schema();
2427 if self.overrides.is_some() || mode.is_some() {
2428 let overrides = self.overrides.get_or_insert_with(|| RunOverrides {
2429 inherit_daemon_options: true,
2430 ..RunOverrides::default()
2431 });
2432 overrides.build_cache = mode;
2433 }
2434 Ok(())
2435 }
2436
2437 pub fn change_implementers(&mut self, count: u8) -> Result<()> {
2440 self.check_implementers_editable()?;
2441 let explicit = self.overrides.as_ref().and_then(|o| o.config.as_deref());
2442 let (mut config, _) = crate::config::Config::discover(&self.repo, explicit)?;
2443 if let Some(o) = &self.overrides {
2444 o.apply(&mut config);
2445 }
2446 self.set_implementers(count, &config)
2447 }
2448
2449 fn check_implementers_editable(&self) -> Result<()> {
2450 if !matches!(self.status, TaskStatus::Queued | TaskStatus::Held) {
2451 bail!(
2452 "task {} is {}; only queued or held tasks can change implementers",
2453 self.short(),
2454 self.status.as_str()
2455 );
2456 }
2457 Ok(())
2458 }
2459
2460 pub fn set_implementers(&mut self, count: u8, config: &crate::config::Config) -> Result<()> {
2462 self.check_implementers_editable()?;
2463 crate::talk::check_implementers(count, config).map_err(anyhow::Error::msg)?;
2464 self.stamp_schema();
2465 self.solo = count == 1;
2466 let mut overrides = self.overrides.clone().unwrap_or_else(|| RunOverrides {
2467 inherit_daemon_options: true,
2468 ..Default::default()
2469 });
2470 overrides.candidates = (count > 1).then_some(usize::from(count));
2471 let mut settings = overrides.clone();
2472 settings.inherit_daemon_options = false;
2473 self.overrides = if overrides.inherit_daemon_options && settings == RunOverrides::default()
2475 {
2476 None
2477 } else {
2478 Some(overrides)
2479 };
2480 Ok(())
2481 }
2482
2483 pub fn edit(&mut self, title: String, instruction: String) -> Result<()> {
2495 if !matches!(self.status, TaskStatus::Queued | TaskStatus::Held) {
2496 bail!(
2497 "task {} is {}; only a queued or held task's instruction can \
2498 be edited",
2499 self.short(),
2500 self.status.as_str()
2501 );
2502 }
2503 if self.review_branch.is_some() && self.review_instruction.is_none() {
2506 self.review_instruction = Some(self.instruction.clone());
2507 }
2508 if self.instruction != instruction {
2509 self.resume_override = None;
2512 }
2513 if self.status == TaskStatus::Held && self.machine_hold_cause.is_some() {
2514 self.hold_manual(self.hold_reason.clone());
2515 }
2516 self.machine_hold_cause = None;
2517 self.disk_resume_run = None;
2518 self.disk_checked_at = None;
2519 self.title = title;
2520 self.instruction = instruction;
2521 Ok(())
2522 }
2523
2524 pub fn handed_off(&mut self, why: impl Into<String>) {
2544 let why = why.into();
2545 self.diagnostic = None;
2546 self.note_held();
2547 self.status = TaskStatus::Held;
2548 self.hold_source = Some(HoldSource::Machine);
2549 self.machine_hold_cause = None;
2550 self.disk_resume_run = None;
2551 self.disk_checked_at = None;
2552 self.hold_reason = Some(why.clone());
2553 self.last_error = Some(why);
2554 }
2555
2556 pub fn release_operator(&mut self, source: &str, question_id: Option<&str>) {
2558 self.recovery_budget = None;
2559 self.recovery_generations.clear();
2560 self.recovery_admission = None;
2561 if self
2562 .resumption
2563 .as_ref()
2564 .is_some_and(|r| r.instruction != self.instruction)
2565 {
2566 self.resume_override = None;
2569 }
2570 let approval = Resumption {
2571 generation: self.resumption.as_ref().map_or(1, |r| r.generation + 1),
2572 source: source.to_owned(),
2573 question_id: question_id.map(str::to_owned),
2574 at: Timestamp::now(),
2575 instruction: self.instruction.clone(),
2576 answers_through: self.answers.len(),
2577 runs_through: self.runs.len(),
2578 blocking_evidence: Vec::new(),
2579 cleared_reason: self
2580 .hold_reason
2581 .clone()
2582 .or_else(|| self.block_reason.clone()),
2583 };
2584 self.release();
2585 self.operator_decided_at = Some(approval.at);
2586 if let Some(previous) = self.resumption.replace(approval) {
2587 self.resumption_history.push(previous);
2588 }
2589 }
2590
2591 pub(crate) fn recovery_failed(&mut self, state: &crate::run::RunState) {
2593 let (base, inputs) = self.recovery_admission.as_ref().map_or_else(
2594 || (state.base_commit.clone(), recovery_inputs(&state.sources)),
2595 |a| (a.base.clone(), a.inputs.clone()),
2596 );
2597 let progress = recovery_progress(state);
2598 let stage = if state.prep_failure.is_some() {
2599 "preparation"
2600 } else {
2601 "execution"
2602 };
2603 let matches = |b: &RecoveryBudget| {
2604 b.instruction == self.instruction
2605 && b.base == base
2606 && b.inputs == inputs
2607 && (progress.is_none() || b.progress == progress)
2608 };
2609 if !self.recovery_budget.as_ref().is_some_and(matches) {
2610 let previous = self
2611 .recovery_generations
2612 .iter()
2613 .position(matches)
2614 .map(|index| self.recovery_generations.remove(index));
2615 if let Some(old) = self.recovery_budget.take() {
2616 self.recovery_generations.push(old);
2617 }
2618 self.recovery_budget = previous;
2619 }
2620 if let Some(budget) = &mut self.recovery_budget {
2621 budget.failures = budget.failures.saturating_add(1);
2622 budget.stage = stage.to_owned();
2623 } else {
2624 self.recovery_budget = Some(RecoveryBudget {
2625 instruction: self.instruction.clone(),
2626 base,
2627 inputs,
2628 stage: stage.to_owned(),
2629 failures: 1,
2630 progress,
2631 });
2632 }
2633 }
2634
2635 pub(crate) fn recovery_exhausted(
2636 &self,
2637 base: &str,
2638 inputs: &str,
2639 limit: usize,
2640 ) -> Option<String> {
2641 let same_input = |b: &&RecoveryBudget| {
2642 b.instruction == self.instruction && b.base == base && b.inputs == inputs
2643 };
2644 let budget = self
2645 .recovery_budget
2646 .as_ref()
2647 .filter(same_input)
2648 .or_else(|| self.recovery_generations.iter().rev().find(same_input))?;
2649 (budget.failures >= limit.max(1)).then(|| budget.budget_reason())
2650 }
2651
2652 pub(crate) fn hold_recovery_budget(&mut self, reason: String, admission: RecoveryAdmission) {
2653 self.hold_unrequested_retry(Some(reason));
2654 if let Some(pass) = self.passes.last()
2655 && self.execution_runs().last() == Some(&pass.run)
2656 {
2657 self.recovery_budget_hold = Some(RecoveryBudgetHold {
2658 admission,
2659 run: pass.run.clone(),
2660 pass: pass.pass_index,
2661 held_at: self.held_at.expect("hold timestamp just recorded"),
2662 decision: self.operator_decided_at,
2663 legacy: false,
2664 });
2665 }
2666 }
2667
2668 fn matches_budget_hold(&self, admission: &RecoveryAdmission) -> bool {
2669 self.status == TaskStatus::Held
2670 && self.hold_source == Some(HoldSource::Manual)
2671 && self.machine_hold_cause.is_none()
2672 && self.recovery_budget.as_ref().is_some_and(|budget| {
2673 budget.instruction == self.instruction
2674 && budget.base == admission.base
2675 && budget.inputs == admission.inputs
2676 && budget.stage == "execution"
2677 && budget.failures > 0
2678 && self
2679 .hold_reason
2680 .as_ref()
2681 .is_some_and(|reason| *reason == budget.budget_reason())
2682 })
2683 }
2684
2685 fn legacy_recovery_budget_hold(&self) -> Option<RecoveryBudgetHold> {
2686 let held_at = self.held_at?;
2687 let settled = self.passes.last()?;
2688 let admission = self.recovery_admission.as_ref()?;
2689 if !self.matches_budget_hold(admission)
2690 || self.execution_runs().last() != Some(&settled.run)
2691 || settled.cost != PassCost::Spent
2692 || settled.parked.is_some()
2693 || settled.settled_at > held_at
2694 || self.operator_decided_at.is_some_and(|at| at >= held_at)
2695 {
2696 return None;
2697 }
2698 Some(RecoveryBudgetHold {
2699 admission: admission.clone(),
2700 run: settled.run.clone(),
2701 pass: settled.pass_index,
2702 held_at,
2703 decision: self.operator_decided_at,
2704 legacy: true,
2705 })
2706 }
2707
2708 pub(crate) fn held_for_recovery_budget(&self, run: &crate::run::RunState) -> bool {
2709 let (Some(held_at), Some(settled), Some(pass), Some(admission)) = (
2710 self.held_at,
2711 self.passes.last(),
2712 run.passes.last(),
2713 self.recovery_admission.as_ref(),
2714 ) else {
2715 return false;
2716 };
2717 if !self.matches_budget_hold(admission)
2718 || self.execution_runs().last() != Some(&run.id)
2719 || settled.run != run.id
2720 || settled.pass_index != pass.index
2721 || settled.cost != PassCost::Spent
2722 || settled.parked.is_some()
2723 || settled.settled_at < pass.started_at
2724 || settled.settled_at > held_at
2725 || self.operator_decided_at.is_some_and(|at| at >= held_at)
2726 || !crate::daemon::compatible_run_instruction(run, self)
2727 {
2728 return false;
2729 }
2730 match &self.recovery_budget_hold {
2731 Some(hold) => {
2732 hold.run == run.id
2733 && hold.pass == pass.index
2734 && hold.held_at == held_at
2735 && hold.decision == self.operator_decided_at
2736 && &hold.admission == admission
2737 && (!hold.legacy
2738 || self
2739 .operator_decided_at
2740 .is_none_or(|at| at < pass.started_at))
2741 }
2742 None => {
2743 self.schema < RECOVERY_HOLD_SCHEMA
2744 && self
2745 .operator_decided_at
2746 .is_none_or(|at| at < pass.started_at)
2747 }
2748 }
2749 }
2750
2751 pub(crate) fn queue_repair(&mut self, receipt: &crate::repair_budget::Receipt) {
2752 self.stamp_schema();
2753 self.repair_grants.push(receipt.clone());
2754 self.status = TaskStatus::Queued;
2755 self.hold_source = None;
2756 self.hold_reason = None;
2757 self.held_at = None;
2758 self.recovery_budget_hold = None;
2759 self.resume_override = Some(OperatorResume {
2760 question_id: String::new(),
2761 at: receipt.at,
2762 conductor_rehold: None,
2763 forced: true,
2764 pinned_run: Some(receipt.request.run.clone()),
2765 });
2766 }
2767
2768 pub fn release(&mut self) {
2772 self.import_chat_notice();
2775 if self.hold_notice_cause.is_none()
2776 && matches!(self.status, TaskStatus::Held | TaskStatus::Blocked)
2777 {
2778 self.hold_notice_cause = Some(self.unresolved_hold_cause());
2779 }
2780 let refused_handover = self.status == TaskStatus::Held
2781 && self.hold_source == Some(HoldSource::Machine)
2782 && self.review_branch.is_some()
2783 && self
2784 .review_instruction
2785 .as_ref()
2786 .is_none_or(|i| *i == self.instruction);
2787 self.status = TaskStatus::Queued;
2788 self.held_at = None;
2789 self.attempts = 0;
2790 self.last_error = None;
2791 self.park_reason = None;
2792 self.hold_reason = None;
2795 self.hold_source = None;
2796 self.machine_hold_cause = None;
2797 self.disk_resume_run = None;
2798 self.disk_checked_at = None;
2799 self.diagnostic = None;
2800 self.blocked_by.clear();
2805 self.block_reason = None;
2806 self.blocked_from = None;
2807 if !refused_handover {
2811 self.review_branch = None;
2812 self.review_instruction = None;
2813 }
2814 self.fresh_start = false;
2815 }
2816}
2817
2818fn copy_new(dir: &Path, src: &Path, name: &str) -> Result<(String, PathBuf)> {
2822 use std::io::ErrorKind;
2823 let (stem, ext) = match name.rfind('.') {
2824 Some(i) if i > 0 => (&name[..i], &name[i..]),
2825 _ => (name, ""),
2826 };
2827 for n in 1u32.. {
2828 let candidate = if n == 1 {
2829 name.to_owned()
2830 } else {
2831 let suffix = format!("-{n}");
2832 let room = 64usize.saturating_sub(suffix.len() + ext.len());
2833 let stem: String = stem.chars().take(room).collect();
2834 format!("{stem}{suffix}{ext}")
2835 };
2836 if !crate::ask::valid_asset_name(&candidate) {
2837 bail!("no valid attachment name is left for `{name}`");
2838 }
2839 let path = dir.join(&candidate);
2840 match std::fs::OpenOptions::new()
2841 .write(true)
2842 .create_new(true)
2843 .open(&path)
2844 {
2845 Ok(mut out) => {
2846 let copied = std::fs::File::open(src)
2847 .and_then(|mut input| std::io::copy(&mut input, &mut out));
2848 if let Err(e) = copied {
2849 drop(out);
2850 let _ = std::fs::remove_file(&path);
2851 return Err(e).with_context(|| format!("copy {}", src.display()));
2852 }
2853 return Ok((candidate, path));
2854 }
2855 Err(e) if e.kind() == ErrorKind::AlreadyExists => continue,
2856 Err(e) => return Err(e).with_context(|| format!("create {}", path.display())),
2857 }
2858 }
2859 unreachable!("the counter never runs out")
2860}
2861
2862const TASK_LOCK_STALE: std::time::Duration = std::time::Duration::from_secs(10);
2865
2866pub(crate) struct TaskLock {
2869 path: PathBuf,
2870 token: String,
2871}
2872
2873fn owner_token() -> String {
2876 static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
2877 let n = COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2878 let mut r = crate::rng::SplitMix64::new(crate::rng::entropy() ^ n.rotate_left(32));
2879 format!("{}-{:016x}", std::process::id(), r.next_u64())
2880}
2881
2882fn break_marker(path: &Path, token: &str) -> PathBuf {
2885 let mut h: u64 = 0xcbf29ce484222325;
2886 for b in token.bytes() {
2887 h ^= u64::from(b);
2888 h = h.wrapping_mul(0x100000001b3);
2889 }
2890 let mut name = path.as_os_str().to_owned();
2891 name.push(format!(".break-{h:016x}"));
2892 PathBuf::from(name)
2893}
2894
2895fn older_than_stale(path: &Path) -> bool {
2896 std::fs::metadata(path)
2897 .and_then(|m| m.modified())
2898 .ok()
2899 .and_then(|t| t.elapsed().ok())
2900 .is_some_and(|age| age > TASK_LOCK_STALE)
2901}
2902
2903fn writer_may_be_gone(token: &str) -> bool {
2904 let Some(pid) = token
2905 .split_once('-')
2906 .and_then(|(pid, _)| pid.parse::<u32>().ok())
2907 else {
2908 return true;
2911 };
2912 if pid == std::process::id() {
2913 return false;
2914 }
2915 crate::proc::pid_status(pid) == Some(false)
2917}
2918
2919const MAX_MARKER_DEPTH: u8 = 3;
2923
2924fn take_marker(
2930 path: &Path,
2931 token: &str,
2932 depth: u8,
2933 retry: crate::lock_file::Retry,
2934) -> Option<(PathBuf, String)> {
2935 use std::io::Write;
2936 let marker = break_marker(path, token);
2937 for _ in 0..2 {
2938 match retry.create(&marker) {
2939 Ok(mut f) => {
2940 let mine = owner_token();
2941 if f.write_all(mine.as_bytes()).is_err() {
2942 drop(f);
2943 let _ = std::fs::remove_file(&marker);
2944 return None;
2945 }
2946 return Some((marker, mine));
2947 }
2948 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
2949 let judged = std::fs::read_to_string(&marker).ok();
2950 match judged.filter(|_| older_than_stale(&marker)) {
2951 Some(judged) if depth < MAX_MARKER_DEPTH => {
2952 remove_lock_if(&marker, &judged, true, depth + 1, retry)?;
2953 }
2954 _ => return None,
2955 }
2956 }
2957 Err(_) => return None,
2958 }
2959 }
2960 None
2961}
2962
2963fn remove_lock_if(
2968 path: &Path,
2969 token: &str,
2970 require_stale: bool,
2971 depth: u8,
2972 retry: crate::lock_file::Retry,
2973) -> Option<bool> {
2974 let (marker, mine) = take_marker(path, token, depth, retry)?;
2975 let still = std::fs::read_to_string(path).is_ok_and(|c| c == token)
2976 && (!require_stale || older_than_stale(path) && writer_may_be_gone(token));
2977 if still {
2978 let _ = std::fs::remove_file(path);
2979 }
2980 if depth >= MAX_MARKER_DEPTH {
2982 if std::fs::read_to_string(&marker).is_ok_and(|c| c == mine) {
2983 let _ = std::fs::remove_file(&marker);
2984 }
2985 } else {
2986 let _ = remove_lock_if(&marker, &mine, false, depth + 1, retry);
2987 }
2988 Some(still)
2989}
2990
2991#[cfg(test)]
2994fn break_stale(path: &Path, judged: &str) -> bool {
2995 break_stale_with(path, judged, crate::lock_file::Retry::new(None))
2996}
2997
2998fn break_stale_with(path: &Path, judged: &str, retry: crate::lock_file::Retry) -> bool {
2999 remove_lock_if(path, judged, true, 0, retry).unwrap_or(false)
3000}
3001
3002impl Drop for TaskLock {
3003 fn drop(&mut self) {
3004 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2);
3005 let retry = crate::lock_file::Retry::new(Some(deadline));
3006 loop {
3007 match remove_lock_if(&self.path, &self.token, false, 0, retry) {
3008 Some(_) => return,
3009 None if std::time::Instant::now() > deadline => return,
3010 None => std::thread::sleep(std::time::Duration::from_millis(5)),
3011 }
3012 }
3013 }
3014}
3015
3016#[derive(Debug, thiserror::Error)]
3017#[error("task changed during completion decision; reload and inspect it")]
3018pub(crate) struct CompletionSnapshotChanged;
3019
3020#[derive(Debug, Clone)]
3022pub struct Queue {
3023 root: PathBuf,
3024 ids: IdSource,
3025}
3026
3027fn validate_attachments(sources: &[PathBuf]) -> Result<Vec<(&PathBuf, &str)>> {
3028 let mut wanted = Vec::new();
3029 for src in sources {
3030 let name = src
3031 .file_name()
3032 .and_then(|n| n.to_str())
3033 .with_context(|| format!("`{}` has no usable file name", src.display()))?;
3034 if !crate::ask::valid_asset_name(name) {
3035 bail!(
3036 "attachment name `{name}` must match ^[A-Za-z0-9][A-Za-z0-9._-]{{0,63}}$ \
3037 with no `..`; rename the file and try again"
3038 );
3039 }
3040 if !src.is_file() {
3041 bail!("attachment `{}` is not a file", src.display());
3042 }
3043 wanted.push((src, name));
3044 }
3045 Ok(wanted)
3046}
3047
3048impl Queue {
3049 pub fn open() -> Self {
3051 Self::at(crate::run::home().join("queue"))
3052 }
3053
3054 pub fn at(root: PathBuf) -> Self {
3057 Self {
3058 root,
3059 ids: IdSource::new(new_id),
3060 }
3061 }
3062
3063 #[doc(hidden)]
3066 pub fn with_id_source(mut self, f: impl Fn() -> String + Send + Sync + 'static) -> Self {
3067 self.ids = IdSource::custom(f);
3068 self
3069 }
3070
3071 fn file_with(
3082 &self,
3083 task: &mut Task,
3084 hook: impl FnMut(&mut Task) -> Result<bool>,
3085 undo: impl FnMut(&mut Task),
3086 ) -> Result<()> {
3087 self.reserve_id(task, hook, undo, true)
3088 }
3089
3090 fn reserve_id(
3098 &self,
3099 task: &mut Task,
3100 mut hook: impl FnMut(&mut Task) -> Result<bool>,
3101 mut undo: impl FnMut(&mut Task),
3102 store: bool,
3103 ) -> Result<()> {
3104 let redraw_first = self.ids.is_custom() && task.attachments.is_empty();
3105 let initial = task.id.clone();
3106 self.ids
3107 .reserve((!redraw_first).then_some(initial.as_str()), "task", |id| {
3108 task.id = id.to_owned();
3109 let _lock = self.lock_task(&task.id)?;
3110 if path_exists(&self.path_of(&task.id))? || !hook(task)? {
3111 return Ok(false);
3112 }
3113 if store {
3114 if let Err(e) = self.write_record(task) {
3115 undo(task);
3116 return Err(e);
3117 }
3118 task.unfiled = false;
3119 }
3120 Ok(true)
3121 })?;
3122 Ok(())
3123 }
3124
3125 fn id_in_use(&self, id: &str, check_attachments: bool) -> Result<bool> {
3130 if path_exists(&self.lock_path(id))? {
3131 return Ok(true);
3132 }
3133 Ok(check_attachments && path_exists(&self.attachments_dir(id))?)
3134 }
3135
3136 fn plain_filing_hook(&self, task: &Task) -> Result<bool> {
3140 Ok(!self.id_in_use(&task.id, task.attachments.is_empty())?)
3141 }
3142
3143 pub fn file_claimed(&self, task: &mut Task) -> Result<Claim> {
3146 let mut claim = None;
3147 self.file_with(
3148 task,
3149 |t| {
3150 if self.id_in_use(&t.id, true)? {
3151 return Ok(false);
3152 }
3153 claim = Some(self.claim(&t.id)?);
3154 Ok(true)
3155 },
3156 |_| {},
3157 )?;
3158 claim.context("claim missing after filing")
3159 }
3160
3161 pub fn root(&self) -> &Path {
3163 &self.root
3164 }
3165
3166 pub fn path_of(&self, id: &str) -> PathBuf {
3168 self.root.join(format!("{id}.json"))
3169 }
3170
3171 pub fn attachments_dir(&self, id: &str) -> PathBuf {
3174 self.root.join(format!("{id}.attachments"))
3175 }
3176
3177 pub fn attach(&self, task: &mut Task, sources: &[PathBuf]) -> Result<Vec<String>> {
3188 let wanted = validate_attachments(sources)?;
3189 if task.unfiled && task.attachments.is_empty() {
3190 let names = std::cell::RefCell::new(Vec::new());
3193 self.reserve_id(
3194 task,
3195 |t| {
3196 if self.id_in_use(&t.id, true)? {
3197 return Ok(false);
3198 }
3199 *names.borrow_mut() = self.copy_attachments(t, &wanted)?;
3200 Ok(true)
3201 },
3202 |_| {},
3203 false,
3204 )?;
3205 return Ok(names.into_inner());
3206 }
3207 self.copy_attachments(task, &wanted)
3208 }
3209
3210 fn copy_attachments(
3212 &self,
3213 task: &mut Task,
3214 wanted: &[(&PathBuf, &str)],
3215 ) -> Result<Vec<String>> {
3216 let dir = self.attachments_dir(&task.id);
3217 let existed = dir.is_dir();
3218 std::fs::create_dir_all(&dir).with_context(|| format!("create {}", dir.display()))?;
3219 let mut created: Vec<PathBuf> = Vec::new();
3220 let mut names = Vec::new();
3221 let mut copy_all = || -> Result<()> {
3222 for (src, name) in wanted {
3223 let (stored, path) = copy_new(&dir, src, name)?;
3224 created.push(path);
3225 names.push(stored);
3226 }
3227 Ok(())
3228 };
3229 if let Err(e) = copy_all() {
3230 for path in &created {
3231 let _ = std::fs::remove_file(path);
3232 }
3233 if !existed {
3234 let _ = std::fs::remove_dir(&dir);
3235 }
3236 return Err(e);
3237 }
3238 task.attachments.extend(names.iter().cloned());
3239 Ok(names)
3240 }
3241
3242 pub fn attach_and_put(&self, task: &mut Task, sources: &[PathBuf]) -> Result<Vec<String>> {
3253 if task.unfiled && task.attachments.is_empty() {
3254 return self.attach_and_file(task, sources);
3255 }
3256 let dir = self.attachments_dir(&task.id);
3257 let existed = dir.is_dir();
3258 let before = task.attachments.len();
3259 let names = self.attach(task, sources)?;
3260 if let Err(e) = self.put(task) {
3261 for name in &names {
3262 let _ = std::fs::remove_file(dir.join(name));
3263 }
3264 if !existed {
3265 let _ = std::fs::remove_dir(&dir);
3266 }
3267 task.attachments.truncate(before);
3268 return Err(e);
3269 }
3270 Ok(names)
3271 }
3272
3273 fn attach_and_file(&self, task: &mut Task, sources: &[PathBuf]) -> Result<Vec<String>> {
3277 let wanted = validate_attachments(sources)?;
3278 let before = task.attachments.len();
3279 let names = std::cell::RefCell::new(Vec::new());
3280 let result = self.file_with(
3281 task,
3282 |t| {
3283 if self.id_in_use(&t.id, true)? {
3284 return Ok(false);
3285 }
3286 *names.borrow_mut() = self.copy_attachments(t, &wanted)?;
3287 Ok(true)
3288 },
3289 |t| {
3290 let dir = self.attachments_dir(&t.id);
3291 for name in names.borrow().iter() {
3292 let _ = std::fs::remove_file(dir.join(name));
3293 }
3294 let _ = std::fs::remove_dir(&dir);
3296 t.attachments.truncate(before);
3297 },
3298 );
3299 result.map(|()| names.into_inner())
3300 }
3301
3302 pub fn attachment_paths(&self, task: &Task) -> Vec<PathBuf> {
3306 let dir = self.attachments_dir(&task.id);
3307 task.attachments
3308 .iter()
3309 .map(|n| {
3310 let p = dir.join(n);
3311 std::path::absolute(&p).unwrap_or(p)
3312 })
3313 .collect()
3314 }
3315
3316 pub fn put(&self, task: &mut Task) -> Result<()> {
3325 if task.unfiled {
3326 return self.file_with(task, |t| self.plain_filing_hook(t), |_| {});
3328 }
3329 let _lock = self.lock_task(&task.id)?;
3330 self.put_unlocked(task)
3331 }
3332
3333 pub fn create_new(&self, task: &mut Task) -> Result<bool> {
3338 let _lock = self.lock_task(&task.id)?;
3339 if path_exists(&self.path_of(&task.id))? {
3340 return Ok(false);
3341 }
3342 self.write_record(task)?;
3343 task.unfiled = false;
3344 Ok(true)
3345 }
3346
3347 fn put_unlocked(&self, task: &mut Task) -> Result<()> {
3349 self.merge_stored(task);
3350 if let Some(boundary) = task.reassignments.last() {
3351 let stored = self.get(&task.id)?;
3352 anyhow::ensure!(
3353 task.reassignments == stored.reassignments
3354 && task.repo == stored.repo
3355 && task.runs.get(..boundary.run_boundary)
3356 == stored.runs.get(..boundary.run_boundary),
3357 "historical repository execution cannot be restarted; reload the task"
3358 );
3359 }
3360 self.write_record(task)
3361 }
3362
3363 pub(crate) fn commit_base_recovery(
3365 &self,
3366 task: &mut Task,
3367 expected: &serde_json::Value,
3368 ) -> Result<()> {
3369 let _lock = self.lock_task(&task.id)?;
3370 anyhow::ensure!(
3371 serde_json::to_value(self.get(&task.id)?)? == *expected,
3372 "task changed during base recovery; inspect the pending authorization"
3373 );
3374 self.put_unlocked(task)
3376 }
3377
3378 pub(crate) fn commit_land_sync_recovery(
3380 &self,
3381 task: &mut Task,
3382 expected: &serde_json::Value,
3383 ) -> Result<()> {
3384 let _lock = self.lock_task(&task.id)?;
3385 anyhow::ensure!(
3386 serde_json::to_value(self.get(&task.id)?)? == *expected,
3387 "task changed during landing base-sync recovery; inspect the pending authorization"
3388 );
3389 self.put_unlocked(task)
3390 }
3391
3392 pub(crate) fn commit_repair_grant(
3393 &self,
3394 task: &mut Task,
3395 expected: &serde_json::Value,
3396 ) -> Result<()> {
3397 let _lock = self.lock_task(&task.id)?;
3398 anyhow::ensure!(
3399 serde_json::to_value(self.get(&task.id)?)? == *expected,
3400 "repair grant refused: task changed during admission"
3401 );
3402 self.write_record(task)
3403 .context(crate::repair_budget::PublicationUnknown)
3404 }
3405
3406 pub(crate) fn commit_disk_wait(&self, task: &mut Task, expected: &Task) -> Result<()> {
3408 let _lock = self.lock_task(&task.id)?;
3409 anyhow::ensure!(
3410 serde_json::to_value(self.get(&task.id)?)? == serde_json::to_value(expected)?,
3411 "task changed during disk monitoring"
3412 );
3413 task.stamp_schema();
3414 self.write_record_inner(task, false)
3415 }
3416
3417 pub(crate) fn commit_reassignment(&self, task: &mut Task, expected: &Task) -> Result<()> {
3419 let _lock = self.lock_task(&task.id)?;
3420 let stored = self.get(&task.id)?;
3421 anyhow::ensure!(
3422 serde_json::to_value(&stored)? == serde_json::to_value(expected)?
3423 && stored.reassignments.len() + 1 == task.reassignments.len()
3424 && stored.repo == task.reassignments.last().expect("new boundary").from
3425 && stored.runs == task.runs,
3426 "task changed during reassignment; retry after inspecting it"
3427 );
3428 self.write_record(task)
3429 }
3430
3431 pub(crate) fn commit_completion(&self, task: &mut Task, expected: &Task) -> Result<()> {
3433 let _lock = self.lock_task(&task.id)?;
3434 anyhow::ensure!(
3435 serde_json::to_value(self.get(&task.id)?)? == serde_json::to_value(expected)?,
3436 CompletionSnapshotChanged
3437 );
3438 self.write_record(task)
3439 }
3440
3441 fn merge_stored(&self, task: &mut Task) {
3443 if let Ok(mut stored) = read_path(&self.path_of(&task.id)) {
3444 stored.import_chat_notice();
3445 let local_decision = task.completion_history.iter().any(|event| {
3448 !stored
3449 .completion_history
3450 .iter()
3451 .any(|saved| saved.occurrence == event.occurrence)
3452 && event.at > stored.updated_at
3453 });
3454 let unseen_decision = stored.completion_history.iter().any(|event| {
3455 !task
3456 .completion_history
3457 .iter()
3458 .any(|mine| mine.occurrence == event.occurrence)
3459 });
3460 let mut history = std::mem::take(&mut stored.completion_history);
3461 for event in std::mem::take(&mut task.completion_history) {
3462 if !history
3463 .iter()
3464 .any(|stored| stored.occurrence == event.occurrence)
3465 {
3466 history.push(event);
3467 }
3468 }
3469 if unseen_decision {
3470 task.import_chat_notice();
3473 let mut stale = std::mem::replace(task, stored);
3474 append_missing(&mut task.answers, stale.answers);
3475 if task.reassignments == stale.reassignments {
3476 append_missing(&mut task.runs, stale.runs);
3477 }
3478 for (ledger, entries) in [
3479 (&mut task.decision_effects, stale.decision_effects),
3480 (&mut task.superseded_resumes, stale.superseded_resumes),
3481 (&mut task.dispatched_resumes, stale.dispatched_resumes),
3482 ] {
3483 for (key, value) in entries {
3484 ledger.entry(key).or_insert(value);
3485 }
3486 }
3487 append_missing(&mut task.actions_applied, stale.actions_applied);
3488 append_missing(&mut task.triage_applied, stale.triage_applied);
3489 append_missing(&mut task.chat_notices, stale.chat_notices);
3490 append_missing(
3491 &mut task.base_recovery_requests,
3492 stale.base_recovery_requests,
3493 );
3494 append_missing(
3495 &mut task.land_sync_recovery_requests,
3496 stale.land_sync_recovery_requests,
3497 );
3498 prepend_missing_by(&mut task.repair_grants, stale.repair_grants, |a, b| {
3501 a.request.request == b.request.request
3502 });
3503 prepend_missing_by(
3504 &mut task.repair_reconciliations,
3505 stale.repair_reconciliations,
3506 |a, b| a.request.request == b.request.request,
3507 );
3508 stale.resumption_history.extend(stale.resumption);
3511 stale.resumption_history.retain(|approval| {
3512 task.resumption
3513 .as_ref()
3514 .is_none_or(|r| r.at != approval.at || r.generation != approval.generation)
3515 });
3516 prepend_missing_by(
3517 &mut task.resumption_history,
3518 stale.resumption_history,
3519 |a, b| a.at == b.at && a.generation == b.generation,
3520 );
3521 for failure in stale.startup_failures {
3522 task.record_startup_failure(failure);
3523 }
3524 for pass in stale.passes {
3525 if !task.passes.iter().any(|stored| {
3526 stored.run == pass.run && stored.pass_index == pass.pass_index
3527 }) {
3528 task.passes.push(pass);
3529 }
3530 }
3531 task.completion_history = history;
3532 if !task.decision_effects.is_empty() {
3533 task.stamp_schema();
3534 }
3535 return;
3536 }
3537 if stored.reassignments.len() > task.reassignments.len() {
3538 let stale = std::mem::replace(task, stored.clone());
3541 for answer in stale.answers {
3542 if !task.answers.contains(&answer) {
3543 task.answers.push(answer);
3544 }
3545 }
3546 }
3547 if task.updated_at < stored.updated_at
3550 && (task.sync_only != stored.sync_only
3551 || stored.sync_only.is_some()
3552 || stored
3553 .recovery_budget_hold
3554 .as_ref()
3555 .is_some_and(|hold| hold.held_at > task.updated_at)
3556 || stored.repair_grants.last().is_some_and(|grant| {
3557 task.repair_grants.last() != Some(grant)
3558 || stored.operator_decided_at > task.operator_decided_at
3559 || stored
3560 .resume_override
3561 .as_ref()
3562 .is_some_and(|pin| pin.at > task.updated_at)
3563 || (task.resume_override != stored.resume_override
3564 && task
3565 .resume_override
3566 .as_ref()
3567 .is_some_and(|pin| pin.at == grant.at))
3568 }))
3569 && task
3570 .operator_decided_at
3571 .is_none_or(|at| at <= stored.updated_at)
3572 && task
3573 .resume_override
3574 .as_ref()
3575 .is_none_or(|pin| pin.at <= stored.updated_at)
3576 && !local_decision
3577 {
3578 *task = stored.clone();
3579 }
3580 task.completion_history = history;
3581 append_missing(
3582 &mut task.base_recovery_requests,
3583 stored.base_recovery_requests,
3584 );
3585 append_missing(
3586 &mut task.land_sync_recovery_requests,
3587 stored.land_sync_recovery_requests,
3588 );
3589 append_missing(&mut task.actions_applied, stored.actions_applied);
3590 append_missing(&mut task.triage_applied, stored.triage_applied);
3591 for receipt in &stored.repair_grants {
3592 if !task
3593 .repair_grants
3594 .iter()
3595 .any(|r| r.request.request == receipt.request.request)
3596 {
3597 task.repair_grants.push(receipt.clone());
3599 }
3600 }
3601 for receipt in &stored.repair_reconciliations {
3602 if !task.repair_reconciliations.contains(receipt) {
3603 task.repair_reconciliations.push(receipt.clone());
3606 task.resume_override = stored.resume_override.clone();
3607 task.status = stored.status;
3608 task.hold_source = stored.hold_source;
3609 task.machine_hold_cause = stored.machine_hold_cause.clone();
3610 task.disk_resume_run = stored.disk_resume_run.clone();
3611 task.disk_checked_at = stored.disk_checked_at;
3612 task.hold_reason = stored.hold_reason.clone();
3613 task.held_at = stored.held_at;
3614 }
3615 }
3616 task.superseded_resumes.extend(stored.superseded_resumes);
3617 task.dispatched_resumes.extend(stored.dispatched_resumes);
3618 if task.status != TaskStatus::Running
3619 && let Some(pin) = &stored.resume_override
3620 && !pin.question_id.is_empty()
3621 && let Some(run) = &pin.pinned_run
3622 && task.resume_override.as_ref().is_none_or(|next| {
3623 next.question_id != pin.question_id || next.pinned_run != pin.pinned_run
3624 })
3625 {
3626 task.superseded_resumes
3627 .insert(pin.question_id.clone(), run.clone());
3628 }
3629 for (id, receipt) in stored.decision_effects {
3632 task.decision_effects.insert(id, receipt);
3633 }
3634 if !task.decision_effects.is_empty() {
3635 task.stamp_schema();
3636 }
3637 if task.chat.is_none() {
3640 task.chat = stored.chat.clone();
3641 }
3642 append_missing(&mut task.chat_notices, stored.chat_notices);
3643 for failure in stored.startup_failures {
3644 task.record_startup_failure(failure);
3645 }
3646 append_missing(&mut task.runs, stored.runs);
3647 for p in stored.passes {
3648 if !task
3649 .passes
3650 .iter()
3651 .any(|q| q.run == p.run && q.pass_index == p.pass_index)
3652 {
3653 task.passes.push(p);
3654 }
3655 }
3656 if let Some(n) = stored.chat_notice
3659 && task.chat_notice.as_ref().is_none_or(|mine| mine.at < n.at)
3660 {
3661 task.chat_notice = Some(n);
3662 }
3663 }
3664 }
3665
3666 pub(crate) fn write_startup_history(&self, task: &Task) -> Result<()> {
3669 let path = self.path_of(&task.id);
3670 let tmp = path.with_extension("json.tmp");
3671 std::fs::write(&tmp, serde_json::to_vec_pretty(task)?)?;
3672 std::fs::rename(tmp, path)?;
3673 Ok(())
3674 }
3675
3676 fn write_record(&self, task: &mut Task) -> Result<()> {
3678 self.write_record_inner(task, true)
3679 }
3680
3681 fn write_record_inner(&self, task: &mut Task, notify: bool) -> Result<()> {
3682 task.import_chat_notice();
3683 if task.status != TaskStatus::Held && task.sync_only.is_none() {
3684 task.recovery_budget_hold = None;
3685 }
3686 task.updated_at = Timestamp::now();
3687 std::fs::create_dir_all(&self.root)
3688 .with_context(|| format!("create {}", self.root.display()))?;
3689 let body = serde_json::to_string_pretty(task).context("serialize task")?;
3690 let path = self.path_of(&task.id);
3691 let tmp = path.with_extension("json.tmp");
3692 std::fs::write(&tmp, &body).with_context(|| format!("write {}", tmp.display()))?;
3693 std::fs::rename(&tmp, &path).with_context(|| format!("replace {}", path.display()))?;
3694 if let (Some(notice), Some(home)) = (
3699 notify.then(|| crate::notices::task_held(task)).flatten(),
3700 self.root.parent().filter(|p| !p.as_os_str().is_empty()),
3701 ) {
3702 crate::notices::raise_in(home, notice);
3703 }
3704 Ok(())
3705 }
3706
3707 pub fn modify(&self, id: &str, f: impl FnOnce(&mut Task) -> bool) -> Result<bool> {
3712 let id = self.resolve_id(id)?;
3713 let _lock = self.lock_task(&id)?;
3714 let mut task = self.get(&id)?;
3715 if !f(&mut task) {
3716 return Ok(false);
3717 }
3718 self.put_unlocked(&mut task)?;
3719 Ok(true)
3720 }
3721
3722 pub fn link_run(&self, id: &str, run: &str) -> Result<Task> {
3727 let id = self.resolve_id(id)?;
3728 let _lock = self.lock_task(&id)?;
3731 let mut task = self.get(&id)?;
3732 if task.link_run(run) {
3733 self.put_unlocked(&mut task)?;
3734 }
3735 Ok(task)
3736 }
3737
3738 pub(crate) fn lock_task(&self, id: &str) -> Result<TaskLock> {
3746 std::fs::create_dir_all(&self.root)
3747 .with_context(|| format!("create {}", self.root.display()))?;
3748 let path = self.root.join(format!("{id}.write-lock"));
3749 let started = std::time::Instant::now();
3750 let retry = crate::lock_file::Retry::task_write(started + TASK_LOCK_STALE);
3751 let marker_retry = crate::lock_file::Retry::new(Some(started + TASK_LOCK_STALE));
3752 loop {
3753 match retry.create(&path) {
3754 Ok(mut file) => {
3755 use std::io::Write;
3756 let token = owner_token();
3757 if let Err(e) = file.write_all(token.as_bytes()) {
3758 drop(file);
3759 let _ = std::fs::remove_file(&path);
3760 return Err(e).with_context(|| format!("lock {}", path.display()));
3761 }
3762 return Ok(TaskLock { path, token });
3763 }
3764 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
3765 let judged = std::fs::read_to_string(&path).ok();
3768 let broken = judged
3769 .filter(|_| older_than_stale(&path))
3770 .is_some_and(|judged| break_stale_with(&path, &judged, marker_retry));
3771 if !broken {
3775 if started.elapsed() > TASK_LOCK_STALE {
3776 bail!("could not lock task {id}");
3777 }
3778 std::thread::sleep(std::time::Duration::from_millis(15));
3779 }
3780 }
3781 Err(e) => return Err(e).with_context(|| format!("lock {}", path.display())),
3782 }
3783 }
3784 }
3785
3786 pub fn get(&self, id: &str) -> Result<Task> {
3788 let resolved = self.resolve_id(id)?;
3789 read_path(&self.path_of(&resolved))
3790 }
3791
3792 pub fn remove(&self, id: &str, in_flight: bool, questions: &Questions) -> Result<Removal> {
3824 self.remove_with_receipt(id, in_flight, questions, None)
3825 }
3826
3827 pub(crate) fn discard_triage(
3829 &self,
3830 id: &str,
3831 questions: &Questions,
3832 inquiry: &str,
3833 ) -> Result<Removal> {
3834 self.remove_with_receipt(id, false, questions, Some(inquiry))
3835 }
3836
3837 pub(crate) fn triage_discard_applied(&self, id: &str, inquiry: &str) -> Result<bool> {
3838 let path = self
3839 .root
3840 .join("triage-discard")
3841 .join(format!("{inquiry}.json"));
3842 let bytes = match std::fs::read(path) {
3843 Ok(bytes) => bytes,
3844 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(false),
3845 Err(e) => return Err(e.into()),
3846 };
3847 let receipt: Task = serde_json::from_slice(&bytes)?;
3848 Ok(receipt.id == id && !self.path_of(id).exists())
3849 }
3850
3851 fn remove_with_receipt(
3852 &self,
3853 id: &str,
3854 in_flight: bool,
3855 questions: &Questions,
3856 inquiry: Option<&str>,
3857 ) -> Result<Removal> {
3858 let resolved = self.resolve_id(id)?;
3859 if in_flight {
3860 bail!("task {resolved} is being run by a live daemon right now");
3861 }
3862 let receipt = inquiry.map(|q| self.root.join("triage-discard").join(format!("{q}.json")));
3863 if let Some(path) = &receipt {
3864 std::fs::create_dir_all(path.parent().expect("receipt directory"))?;
3865 }
3866 self.write_tombstone(&resolved)?;
3867 if let Err(e) = self.remove_record_with_attachments(&resolved, |p| match &receipt {
3868 Some(path) => std::fs::rename(p, path),
3869 None => std::fs::remove_file(p),
3870 }) {
3871 if self.path_of(&resolved).exists() {
3875 let _ = std::fs::remove_file(self.tombstone_path(&resolved));
3876 }
3877 return Err(e);
3878 }
3879 let (released, still_blocked) = self.release_dependents_of(&resolved, questions);
3880 Ok(Removal {
3881 id: resolved,
3882 released,
3883 still_blocked,
3884 })
3885 }
3886
3887 fn tombstone_path(&self, id: &str) -> PathBuf {
3890 self.root.join(format!("{id}.removed"))
3891 }
3892
3893 fn write_tombstone(&self, id: &str) -> Result<()> {
3894 let path = self.tombstone_path(id);
3895 let tmp = self.root.join(format!("{id}.removed.tmp"));
3896 std::fs::write(&tmp, b"")
3897 .and_then(|()| std::fs::rename(&tmp, &path))
3898 .with_context(|| format!("write {}", path.display()))
3899 }
3900
3901 fn was_deleted(&self, id: &str) -> bool {
3905 self.tombstone_path(id).is_file() && !self.path_of(id).exists()
3906 }
3907
3908 pub fn apply_deleted_blockers(&self, task: &mut Task, questions: &Questions) -> Vec<String> {
3912 let deleted = deleted_blockers(self, questions, &task.blocked_by);
3913 deleted
3914 .into_iter()
3915 .filter(|id| task.dependency_deleted(id))
3916 .collect()
3917 }
3918
3919 pub fn note_dependency_deleted(&self, dependent: &Task, deleted: &str) {
3923 let Some(home) = self.root.parent().filter(|p| !p.as_os_str().is_empty()) else {
3924 return;
3925 };
3926 let ja = crate::lang::is_japanese(&crate::lang::of_repo(&dependent.repo));
3927 let waiting = dependent.status == TaskStatus::Blocked;
3928 let message = match (ja, waiting) {
3929 (true, false) => format!(
3930 "タスク {} は、待っていた {} が削除されたため待機を解除し、元の状態に戻しました",
3931 dependent.short(),
3932 short(deleted)
3933 ),
3934 (true, true) => format!(
3935 "タスク {} は、待っていた {} が削除されたため、残りの依存を待っています",
3936 dependent.short(),
3937 short(deleted)
3938 ),
3939 (false, false) => format!(
3940 "Task {} stopped waiting on {} because it was deleted, and returned to its previous state",
3941 dependent.short(),
3942 short(deleted)
3943 ),
3944 (false, true) => format!(
3945 "Task {} stopped waiting on {} because it was deleted, and is still waiting on its other dependencies",
3946 dependent.short(),
3947 short(deleted)
3948 ),
3949 };
3950 crate::notices::raise_in(
3951 home,
3952 crate::notices::Notice::info(
3953 &format!("unblocked:{}:{}", dependent.id, deleted),
3954 message,
3955 )
3956 .link(crate::notices::Link::Task {
3957 id: dependent.id.clone(),
3958 }),
3959 );
3960 }
3961
3962 fn release_dependents_of(
3967 &self,
3968 dependency: &str,
3969 questions: &Questions,
3970 ) -> (Vec<String>, Vec<String>) {
3971 let (mut released, mut still_blocked) = (Vec::new(), Vec::new());
3972 for listed in self.list() {
3973 if listed.status != TaskStatus::Blocked || !listed.blocked_by.iter().any(|b| {
3974 matches!(crate::queue::dependency(self, questions, b), Dependency::Deleted(id) if id == dependency)
3975 }) {
3976 continue;
3977 }
3978 let Ok(_claim) = self.claim(&listed.id) else {
3979 continue;
3980 };
3981 let Ok(mut task) = self.get(&listed.id) else {
3982 continue;
3983 };
3984 let references: Vec<String> = task.blocked_by.iter().filter(|id| {
3985 matches!(crate::queue::dependency(self, questions, id), Dependency::Deleted(full) if full == dependency)
3986 }).cloned().collect();
3987 if references.is_empty() {
3988 continue;
3989 }
3990 for reference in references {
3991 task.dependency_deleted(&reference);
3992 }
3993 if self.put(&mut task).is_err() {
3994 continue;
3995 }
3996 self.note_dependency_deleted(&task, dependency);
3997 if task.status == TaskStatus::Blocked {
3998 still_blocked.push(task.id.clone());
3999 } else {
4000 released.push(task.id.clone());
4001 }
4002 }
4003 (released, still_blocked)
4004 }
4005
4006 fn remove_record_with_attachments(
4010 &self,
4011 resolved: &str,
4012 remove_record: impl FnOnce(&Path) -> std::io::Result<()>,
4013 ) -> Result<()> {
4014 self.sweep_removed_attachments();
4021 let attachments = self.attachments_dir(resolved);
4022 let aside = self.root.join(format!("{resolved}.attachments.removing"));
4023 let moved = match std::fs::rename(&attachments, &aside) {
4024 Ok(()) => true,
4025 Err(e) if e.kind() == std::io::ErrorKind::NotFound => false,
4026 Err(e) => {
4027 return Err(e).with_context(|| format!("remove {}", attachments.display()));
4028 }
4029 };
4030 let path = self.path_of(resolved);
4031 if let Err(e) = remove_record(&path) {
4032 if moved {
4033 let _ = std::fs::rename(&aside, &attachments);
4034 }
4035 return Err(e).with_context(|| format!("remove {}", path.display()));
4036 }
4037 if moved {
4038 if let Err(e) = std::fs::remove_dir_all(&aside) {
4039 tracing::warn!("leftover attachments {}: {e}", aside.display());
4040 }
4041 }
4042 let lock = self.lock_path(resolved);
4043 if let Err(e) = std::fs::remove_file(&lock) {
4044 if e.kind() != std::io::ErrorKind::NotFound {
4045 return Err(e).with_context(|| format!("remove {}", lock.display()));
4046 }
4047 }
4048 Ok(())
4049 }
4050
4051 fn sweep_removed_attachments(&self) {
4057 let Ok(entries) = std::fs::read_dir(&self.root) else {
4058 return;
4059 };
4060 for entry in entries.flatten() {
4061 let name = entry.file_name();
4062 let name = name.to_string_lossy();
4063 let Some(id) = name.strip_suffix(".attachments.removing") else {
4064 continue;
4065 };
4066 if !self.path_of(id).exists() {
4069 if let Err(e) = std::fs::remove_dir_all(entry.path()) {
4070 tracing::warn!("leftover attachments {}: {e}", entry.path().display());
4071 }
4072 }
4073 }
4074 self.sweep_tombstones();
4075 }
4076
4077 fn sweep_tombstones(&self) {
4086 let Ok(entries) = std::fs::read_dir(&self.root) else {
4087 return;
4088 };
4089 let tasks = self.list();
4090 for entry in entries.flatten() {
4091 let name = entry.file_name();
4092 let name = name.to_string_lossy();
4093 let Some(id) = name.strip_suffix(".removed") else {
4094 continue;
4095 };
4096 if self.path_of(id).exists()
4097 || tasks.iter().any(|t| {
4098 t.blocked_by
4099 .iter()
4100 .any(|b| id.starts_with(b) || id.ends_with(b))
4101 })
4102 {
4103 continue;
4104 }
4105 let old = entry
4106 .metadata()
4107 .and_then(|m| m.modified())
4108 .ok()
4109 .and_then(|m| m.elapsed().ok())
4110 .is_some_and(|age| age >= TOMBSTONE_GRACE);
4111 if old {
4112 let _ = std::fs::remove_file(entry.path());
4113 }
4114 }
4115 }
4116
4117 fn lock_path(&self, id: &str) -> PathBuf {
4120 self.root.join(format!("{id}.lock"))
4121 }
4122
4123 pub fn list(&self) -> Vec<Task> {
4136 #[cfg(test)]
4137 LIST_READS.with(|count| count.set(count.get() + 1));
4138 let mut tasks: Vec<Task> = std::fs::read_dir(&self.root)
4139 .into_iter()
4140 .flatten()
4141 .flatten()
4142 .map(|e| e.path())
4143 .filter(|p| p.extension().is_some_and(|x| x == "json"))
4144 .filter_map(|p| read_path(&p).ok())
4145 .collect();
4146 tasks.sort_unstable_by(|a, b| b.priority.cmp(&a.priority).then_with(|| b.id.cmp(&a.id)));
4147 tasks
4148 }
4149
4150 pub fn unreadable(&self) -> Vec<PathBuf> {
4154 std::fs::read_dir(&self.root)
4155 .into_iter()
4156 .flatten()
4157 .flatten()
4158 .map(|e| e.path())
4159 .filter(|p| p.extension().is_some_and(|x| x == "json"))
4160 .filter(|p| read_path(p).is_err())
4161 .collect()
4162 }
4163
4164 pub fn superseded(&self) -> HashMap<String, String> {
4177 let mut by = HashMap::new();
4178 for task in self.list() {
4179 for earlier in &task.runs {
4180 if let Some(later) = task.successor_of(earlier) {
4181 by.insert(earlier.clone(), later.clone());
4182 }
4183 }
4184 }
4185 by
4186 }
4187
4188 pub fn superseded_by(&self, run: &str) -> Option<String> {
4196 for task in self.list() {
4197 if task.runs.iter().any(|r| r == run) {
4198 return task.successor_of(run).cloned();
4199 }
4200 }
4201 None
4202 }
4203
4204 pub fn latest_attempt(&self, run: &str) -> Option<String> {
4215 for task in self.list() {
4216 if task.runs.iter().any(|r| r == run) {
4217 return task.runs.last().filter(|last| **last != run).cloned();
4218 }
4219 }
4220 None
4221 }
4222
4223 pub fn next_runnable(&self) -> Option<Task> {
4228 let mut runnable: Vec<Task> = self
4229 .list()
4230 .into_iter()
4231 .filter(|t| t.status.runnable())
4232 .collect();
4233 runnable.sort_unstable_by(dispatch_order);
4234 runnable.into_iter().next()
4235 }
4236
4237 pub fn claim(&self, id: &str) -> Result<Claim> {
4244 std::fs::create_dir_all(&self.root)
4245 .with_context(|| format!("create {}", self.root.display()))?;
4246 let path = self.lock_path(id);
4247 let retry = crate::lock_file::Retry::new(None);
4248 match retry.create(&path) {
4249 Ok(mut f) => {
4250 use std::io::Write as _;
4251 let _ = writeln!(f, "{}", std::process::id());
4253 Ok(Claim { path })
4254 }
4255 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
4256 bail!("task {id} is already claimed ({} exists)", path.display())
4257 }
4258 Err(e) => Err(e).with_context(|| format!("lock {}", path.display())),
4259 }
4260 }
4261
4262 pub fn resolve_id(&self, prefix: &str) -> Result<String> {
4264 if !prefix.is_empty()
4265 && prefix != "."
4266 && prefix != ".."
4267 && !prefix.contains(['/', '\\'])
4268 && self.path_of(prefix).is_file()
4269 {
4270 return Ok(prefix.to_owned());
4271 }
4272 let ids = record_ids(&self.root, "json")?;
4273 match resolve_reference(prefix, ids.iter().map(String::as_str)) {
4274 Reference::Found(id) => Ok(id),
4275 Reference::Missing => bail!("no task matches `{prefix}`"),
4276 Reference::Ambiguous => bail!("`{prefix}` matches multiple tasks"),
4277 }
4278 }
4279
4280 pub fn revision(&self) -> u64 {
4287 self.revision_excluding(&std::collections::BTreeSet::new())
4288 }
4289
4290 pub fn revision_excluding(&self, skip: &std::collections::BTreeSet<String>) -> u64 {
4293 use std::hash::{Hash as _, Hasher as _};
4294
4295 let mut entries: Vec<(String, u64)> = std::fs::read_dir(&self.root)
4296 .into_iter()
4297 .flatten()
4298 .flatten()
4299 .filter(|e| e.path().extension().is_some_and(|ext| ext == "json"))
4300 .filter(|e| {
4301 let path = e.path();
4302 !path
4303 .file_stem()
4304 .is_some_and(|stem| skip.contains(stem.to_string_lossy().as_ref()))
4305 })
4306 .filter_map(|e| {
4307 let name = e.file_name().to_string_lossy().into_owned();
4308 let mtime = e
4309 .metadata()
4310 .ok()?
4311 .modified()
4312 .ok()?
4313 .duration_since(std::time::UNIX_EPOCH)
4314 .ok()?
4315 .as_millis() as u64;
4316 Some((name, mtime))
4317 })
4318 .collect();
4319
4320 if entries.is_empty() {
4321 return 0;
4322 }
4323
4324 entries.sort_unstable();
4325 let mut hasher = std::hash::DefaultHasher::new();
4326 for (name, mtime) in &entries {
4327 name.hash(&mut hasher);
4328 mtime.hash(&mut hasher);
4329 }
4330 let h = hasher.finish();
4331 if h == 0 { 1 } else { h }
4332 }
4333}
4334
4335const TOMBSTONE_GRACE: std::time::Duration = std::time::Duration::from_secs(3600);
4338
4339#[derive(Debug, Clone)]
4341pub struct Removal {
4342 pub id: String,
4344 pub released: Vec<String>,
4348 pub still_blocked: Vec<String>,
4351}
4352
4353#[derive(Debug)]
4355pub struct Claim {
4356 path: PathBuf,
4357}
4358
4359impl Drop for Claim {
4360 fn drop(&mut self) {
4361 let _ = std::fs::remove_file(&self.path);
4362 }
4363}
4364
4365pub fn title_from(instruction: &str, max: usize) -> String {
4368 let Some(line) = first_line(instruction) else {
4369 return "(empty task)".to_owned();
4370 };
4371 if line.chars().count() <= max {
4372 return line.to_owned();
4373 }
4374 let head: String = line.chars().take(max.saturating_sub(1)).collect();
4375 format!("{head}…")
4376}
4377
4378pub(crate) fn first_line(instruction: &str) -> Option<&str> {
4384 let line = instruction
4385 .lines()
4386 .map(str::trim)
4387 .find(|l| !l.is_empty())?
4388 .trim_start_matches(['#', '-', '*', '>', ' '])
4389 .trim();
4390 (!line.is_empty()).then_some(line)
4391}
4392
4393#[cfg(test)]
4394thread_local! {
4395 pub(crate) static TASK_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4396}
4397
4398fn read_path(path: &Path) -> Result<Task> {
4399 #[cfg(test)]
4400 TASK_READS.with(|count| count.set(count.get() + 1));
4401 let body = std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;
4402 let mut task: Task =
4403 serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))?;
4404 if task.schema > SCHEMA {
4410 bail!(
4411 "task {} was written by a different magi (schema {}, this build \
4412 speaks {SCHEMA})",
4413 task.id,
4414 task.schema
4415 );
4416 }
4417 task.preserve_legacy_build_cache();
4418 if task.schema < 22
4419 && task.status == TaskStatus::Held
4420 && task.hold_source == Some(HoldSource::Machine)
4421 && task.resume_override.is_none()
4422 && task
4423 .hold_reason
4424 .as_deref()
4425 .is_some_and(crate::disk::is_gate_reason)
4426 {
4427 task.mark_disk_capacity();
4428 }
4429 Ok(task)
4430}
4431
4432#[derive(Debug, PartialEq, Eq)]
4435pub(crate) enum Reference {
4436 Found(String),
4437 Missing,
4438 Ambiguous,
4439}
4440
4441pub(crate) fn resolve_reference<'a>(id: &str, ids: impl Iterator<Item = &'a str>) -> Reference {
4442 let mut hits = Vec::new();
4443 for candidate in ids {
4444 if candidate == id {
4445 return Reference::Found(candidate.to_owned());
4446 }
4447 if candidate.starts_with(id) || candidate.ends_with(id) {
4448 hits.push(candidate);
4449 }
4450 }
4451 match hits.as_slice() {
4452 [] => Reference::Missing,
4453 [one] => Reference::Found((*one).to_owned()),
4454 _ => Reference::Ambiguous,
4455 }
4456}
4457
4458pub(crate) fn record_ids(root: &Path, extension: &str) -> Result<Vec<String>> {
4461 let entries = match std::fs::read_dir(root) {
4462 Ok(entries) => entries,
4463 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
4464 Err(e) => return Err(e.into()),
4465 };
4466 let mut ids = Vec::new();
4467 for entry in entries {
4468 let path = entry?.path();
4469 if path.extension().is_some_and(|e| e == extension)
4470 && let Some(id) = path.file_stem().and_then(|s| s.to_str())
4471 {
4472 ids.push(id.to_owned());
4473 }
4474 }
4475 Ok(ids)
4476}
4477
4478#[derive(Debug, PartialEq, Eq)]
4481pub enum Dependency {
4482 Task(String),
4484 Question(String),
4486 Deleted(String),
4488 Missing,
4490 Ambiguous,
4492 Unknown,
4494}
4495
4496pub fn dependency(queue: &Queue, questions: &Questions, id: &str) -> Dependency {
4498 let (Ok(tasks), Ok(qs), Ok(removed)) = (
4499 record_ids(queue.root(), "json"),
4500 record_ids(questions.root(), "json"),
4501 record_ids(queue.root(), "removed"),
4502 ) else {
4503 return Dependency::Unknown;
4504 };
4505 let mut ids = tasks
4508 .iter()
4509 .chain(qs.iter())
4510 .chain(removed.iter())
4511 .cloned()
4512 .collect::<Vec<_>>();
4513 ids.sort();
4514 ids.dedup();
4515 match resolve_reference(id, ids.iter().map(String::as_str)) {
4516 Reference::Found(id) if tasks.contains(&id) => Dependency::Task(id),
4517 Reference::Found(id) if qs.contains(&id) => Dependency::Question(id),
4518 Reference::Found(id) if queue.was_deleted(&id) => Dependency::Deleted(id),
4519 Reference::Found(_) => Dependency::Unknown,
4520 Reference::Missing => Dependency::Missing,
4521 Reference::Ambiguous => Dependency::Ambiguous,
4522 }
4523}
4524
4525pub fn normalize_blockers(queue: &Queue, questions: &Questions, ids: &mut [String]) {
4527 for id in ids {
4528 if let Dependency::Task(full) | Dependency::Question(full) | Dependency::Deleted(full) =
4529 dependency(queue, questions, id)
4530 {
4531 *id = full;
4532 }
4533 }
4534}
4535
4536pub fn dependency_facts(queue: &Queue, questions: &Questions) -> String {
4539 let inventory = crate::blockers::Inventory::load(queue, questions);
4540 let mut text = String::from(
4541 "Current authoritative queue (historical missing-task claims may be stale; unreadable or ambiguous references must keep waiting):\n",
4542 );
4543 match record_ids(queue.root(), "json") {
4544 Ok(ids) => {
4545 for id in ids {
4546 match queue.get(&id) {
4547 Ok(task) => text.push_str(&format!(
4548 "{}: {}; blocked_by={:?}; chain={:?}\n",
4549 task.id,
4550 task.status.as_str(),
4551 task.blocked_by,
4552 inventory.waits_on(&task)
4553 )),
4554 Err(_) => text.push_str(&format!("{id}: exists, state unreadable\n")),
4555 }
4556 }
4557 }
4558 Err(_) => text.push_str("Queue inventory unreadable: existence is unknown.\n"),
4559 }
4560 text
4561}
4562
4563pub fn missing_blockers(
4565 queue: &Queue,
4566 questions: &Questions,
4567 blocked_by: &[String],
4568) -> Vec<String> {
4569 blocked_by
4570 .iter()
4571 .filter(|id| dependency(queue, questions, id) == Dependency::Missing)
4572 .cloned()
4573 .collect()
4574}
4575
4576pub fn deleted_blockers(
4579 queue: &Queue,
4580 questions: &Questions,
4581 blocked_by: &[String],
4582) -> Vec<String> {
4583 blocked_by
4584 .iter()
4585 .filter(|id| matches!(dependency(queue, questions, id), Dependency::Deleted(_)))
4586 .cloned()
4587 .collect()
4588}
4589
4590pub fn missing_blocker_hold_reason(blocked_by: &[String], missing: &[String]) -> String {
4602 missing_blocker_hold_reason_in(blocked_by, missing, "en")
4603}
4604
4605pub fn missing_blocker_hold_reason_in(
4607 blocked_by: &[String],
4608 missing: &[String],
4609 language: &str,
4610) -> String {
4611 if crate::lang::is_japanese(language) {
4612 format!(
4613 "{} を待っていましたが、{} はディスク上に存在しません - `magi task triage` を参照",
4614 blocked_by.join(", "),
4615 missing.join(", "),
4616 )
4617 } else {
4618 format!(
4619 "blocked on {} but {} no longer exist(s) on disk - see `magi task triage`",
4620 blocked_by.join(", "),
4621 missing.join(", "),
4622 )
4623 }
4624}
4625
4626pub fn short(id: &str) -> &str {
4628 id.split('-').next_back().unwrap_or(id)
4629}
4630
4631fn new_id() -> String {
4632 let stamp = jiff::Zoned::now().strftime("%Y%m%d-%H%M%S");
4633 let seed = crate::rng::entropy();
4634 format!("{stamp}-{:04x}", (seed ^ (seed >> 32)) & 0xffff)
4635}
4636
4637#[cfg(test)]
4638mod tests {
4639 #[test]
4640 fn reassignment_clears_repository_bound_execution_selections() {
4641 let mut task = Task::new(
4642 "move".into(),
4643 "evidence".into(),
4644 "old".into(),
4645 Source::Human,
4646 );
4647 task.review_branch = Some("old-review".into());
4648 task.review_instruction = Some("old criteria".into());
4649 task.pr_recovery = Some(crate::pr_recovery::Selection {
4650 url: "https://example.invalid/pull/1".into(),
4651 branch: "old-pr".into(),
4652 head: "head".into(),
4653 source_head: None,
4654 source_run: None,
4655 source_proof: None,
4656 disposition: None,
4657 instruction: "old criteria".into(),
4658 approved_at: Timestamp::now(),
4659 });
4660 task.replacement = Some(crate::merge_decision::Replacement {
4661 question: "owner".into(),
4662 run: "old-run".into(),
4663 pr: "https://example.invalid/pull/1".into(),
4664 agent: "worker".into(),
4665 context: "evidence".into(),
4666 });
4667 task.resume_override = Some(OperatorResume {
4668 question_id: "old-question".into(),
4669 at: Timestamp::now(),
4670 conductor_rehold: None,
4671 forced: true,
4672 pinned_run: Some("old-run".into()),
4673 });
4674 task.interrupt = true;
4675 task.reassign_repository("new".into(), "test");
4676 assert!(task.review_branch.is_none());
4677 assert!(task.review_instruction.is_none());
4678 assert!(task.pr_recovery.is_none());
4679 assert!(task.replacement.is_none());
4680 assert!(task.resume_override.is_none());
4681 assert!(!task.interrupt);
4682 assert!(task.fresh_start);
4683 assert_eq!(task.instruction, "evidence");
4684 }
4685
4686 #[test]
4687 fn explicit_resumption_is_not_invented_for_legacy_or_automatic_release() {
4688 let t = Task::new(
4689 "retry".into(),
4690 "do it".into(),
4691 PathBuf::from("."),
4692 Source::Human,
4693 );
4694 let mut value = serde_json::to_value(&t).unwrap();
4695 for field in ["resumption", "resumption_history", "operator_decided_at"] {
4696 value.as_object_mut().unwrap().remove(field);
4697 }
4698 value["schema"] = serde_json::json!(15);
4699 let mut legacy: Task = serde_json::from_value(value).unwrap();
4700 legacy.hold_machine(Some("automatic retry".into()));
4701 legacy.release();
4702 assert!(legacy.resumption.is_none());
4703 assert!(legacy.resumption_history.is_empty());
4704 assert!(legacy.operator_decided_at.is_none());
4705 legacy.release_operator("cli", None);
4706 legacy.start("run".into());
4707 let reloaded: Task =
4708 serde_json::from_str(&serde_json::to_string(&legacy).unwrap()).unwrap();
4709 assert!(reloaded.resume_override.is_none());
4710 assert_eq!(reloaded.resumption.as_ref().unwrap().generation, 1);
4711 }
4712
4713 #[test]
4714 fn merge_over_lets_the_later_choice_win_and_keeps_the_rest() {
4715 let mut base = RunOverrides {
4716 merge: Some("pr".to_owned()),
4717 candidates: Some(3),
4718 ..RunOverrides::default()
4719 };
4720 base.merge_over(&RunOverrides {
4721 merge: Some("none".to_owned()),
4722 seed: Some(7),
4723 ..RunOverrides::default()
4724 });
4725 assert_eq!(base.merge.as_deref(), Some("none"));
4726 assert_eq!(base.candidates, Some(3));
4727 assert_eq!(base.seed, Some(7));
4728 }
4729
4730 #[test]
4731 fn an_already_landed_task_is_done_with_its_attempt_refunded() {
4732 let mut t = task("relanded");
4733 t.attempts = 1;
4734 t.status = TaskStatus::Running;
4735 t.already_landed("already in main as 0e368de", completion(&t));
4736 assert_eq!(t.status, TaskStatus::Done);
4737 assert_eq!(t.attempts, 0);
4738 assert!(t.hold_reason.is_none());
4739 assert_eq!(t.last_error.as_deref(), Some("already in main as 0e368de"));
4740 }
4741
4742 #[test]
4743 fn missing_blocker_reason_follows_the_language() {
4744 let b = vec!["a".to_owned()];
4745 let en = missing_blocker_hold_reason_in(&b, &b, "en");
4746 assert_eq!(en, missing_blocker_hold_reason(&b, &b));
4747 assert!(en.starts_with("blocked on a"));
4748 assert!(missing_blocker_hold_reason_in(&b, &b, "ja").contains("存在しません"));
4749 assert_eq!(missing_blocker_hold_reason_in(&b, &b, "de"), en);
4750 }
4751
4752 use super::*;
4753
4754 fn completion(task: &Task) -> CompletionContext {
4755 CompletionContext::new(CompletionActor::Cli, None, Path::new("."), task)
4756 }
4757
4758 #[test]
4759 fn completion_retains_the_hold_dependency_and_failure_it_clears() {
4760 let mut held = task("held evidence");
4761 held.hold_manual(Some("owner approval required".into()));
4762 held.last_error = Some("review budget exhausted".into());
4763 held.succeed(completion(&held));
4764 let event = held.completion_history.last().unwrap();
4765 assert_eq!(event.prior_status, TaskStatus::Held);
4766 assert_eq!(
4767 event.prior_hold_reason.as_deref(),
4768 Some("owner approval required")
4769 );
4770 assert_eq!(
4771 event.prior_error.as_deref(),
4772 Some("review budget exhausted")
4773 );
4774 assert!(held.hold_reason.is_none());
4775 assert!(held.last_error.is_none());
4776 let mut blocked = task("dependency evidence");
4777 blocked.block(
4778 vec!["dependency".into()],
4779 Some("waiting on migration".into()),
4780 );
4781 blocked.succeed(completion(&blocked));
4782 let event = blocked.completion_history.last().unwrap();
4783 assert_eq!(event.prior_status, TaskStatus::Blocked);
4784 assert_eq!(
4785 event.prior_block_reason.as_deref(),
4786 Some("waiting on migration")
4787 );
4788 assert!(blocked.block_reason.is_none());
4789 assert!(blocked.blocked_by.is_empty());
4790 let saved = serde_json::to_vec(&held).unwrap();
4791 let restored: Task = serde_json::from_slice(&saved).unwrap();
4792 assert_eq!(restored.completion_history, held.completion_history);
4793 }
4794
4795 #[test]
4796 fn completion_audit_is_append_only_under_stale_puts() {
4797 let dir = tempfile::tempdir().unwrap();
4798 let queue = Queue::at(dir.path().join("queue"));
4799 let mut current = task("audited");
4800 current.hold_manual(Some("inspect".into()));
4801 queue.put(&mut current).unwrap();
4802 let mut stale = queue.get(¤t.id).unwrap();
4803 current.succeed(completion(¤t));
4804 queue.put(&mut current).unwrap();
4805 let original = current.completion_history[0].clone();
4806 stale.last_error = Some("stale control state".into());
4807 queue.put(&mut stale).unwrap();
4808 assert_eq!(stale.status, TaskStatus::Done);
4809 assert_eq!(stale.completion_history, vec![original.clone()]);
4810 let mut context = completion(¤t);
4811 context.reason = Some("not actually finished".into());
4812 current.reopen(context).unwrap();
4813 queue.put(&mut current).unwrap();
4814 stale.completion_history[0].actor = CompletionActor::Web;
4815 stale.completion_history[0].reason = Some("rewritten evidence".into());
4816 queue.put(&mut stale).unwrap();
4817 assert_eq!(stale.status, TaskStatus::Held);
4818 assert_eq!(stale.hold_reason.as_deref(), Some("not actually finished"));
4819 assert_eq!(stale.completion_history[0], original);
4820 assert_eq!(stale.completion_history, current.completion_history);
4821 }
4822
4823 #[test]
4824 fn a_writer_missing_a_reopen_contributes_receipts_but_not_authority() {
4825 let (_dir, q) = queue();
4826 let mut current = task("durable receipts");
4827 q.put(&mut current).unwrap();
4828 let mut stale = current.clone();
4829 let grant: crate::repair_budget::Receipt = serde_json::from_value(serde_json::json!({
4830 "request": {
4831 "task": current.id, "run": "old-run", "kind": "gate", "rounds": 1,
4832 "head": "old-head", "expect_pass": 0, "request": "old-grant", "reason": "retry"
4833 },
4834 "at": stale.updated_at, "contract": "old-contract"
4835 }))
4836 .unwrap();
4837 stale.release_operator("triage", Some("triage-question"));
4838 stale.queue_repair(&grant);
4839 let reconciliation: crate::repair_budget::reconcile::Receipt =
4840 serde_json::from_value(serde_json::json!({
4841 "request": {
4842 "task": current.id, "run": "old-run", "head": "old-head", "expect_pass": 0,
4843 "receipt": "old-grant", "question": "triage-question", "answer_at": grant.at,
4844 "request": "reconciliation", "reason": "retain the answer"
4845 },
4846 "grant": grant, "source": "answer", "application": "release",
4847 "decision": grant.at, "superseded_questions": []
4848 }))
4849 .unwrap();
4850 stale.repair_reconciliations.push(reconciliation.clone());
4851 stale.triage_applied.push("triage-question".into());
4852 stale.actions_applied.push("choice".into());
4853 stale.base_recovery_requests.push("base-request".into());
4854 stale.chat_notices.push("delivery".into());
4855 stale.chat_notice = Some(ChatNotice {
4856 key: "other-delivery".into(),
4857 at: grant.at,
4858 outcome: ChatNoticeOutcome::Posted,
4859 });
4860 for ledger in [
4861 &mut stale.decision_effects,
4862 &mut stale.dispatched_resumes,
4863 &mut stale.superseded_resumes,
4864 ] {
4865 ledger.insert("shared".into(), "stale".into());
4866 ledger.insert("only-stale".into(), "receipt".into());
4867 }
4868
4869 let mut latest_grant = grant.clone();
4870 latest_grant.request.request = "new-grant".into();
4871 current.queue_repair(&latest_grant);
4872 for ledger in [
4873 &mut current.decision_effects,
4874 &mut current.dispatched_resumes,
4875 &mut current.superseded_resumes,
4876 ] {
4877 ledger.insert("shared".into(), "committed".into());
4878 }
4879 current.succeed(completion(¤t));
4880 let mut context = completion(¤t);
4881 context.reason = Some("inspect again".into());
4882 current.reopen(context).unwrap();
4883 q.put(&mut current).unwrap();
4884
4885 for _ in 0..2 {
4886 q.put(&mut stale.clone()).unwrap();
4887 let saved = q.get(¤t.id).unwrap();
4888 assert_eq!(saved.status, TaskStatus::Held);
4889 assert_eq!(saved.hold_reason, current.hold_reason);
4890 assert_eq!(saved.operator_decided_at, current.operator_decided_at);
4891 assert_eq!(saved.completion_history, current.completion_history);
4892 assert!(saved.resume_override.is_none());
4893 assert!(saved.resumption.is_none());
4894 assert_eq!(
4895 saved.resumption_history,
4896 [stale.resumption.clone().unwrap()]
4897 );
4898 assert_eq!(saved.triage_applied, ["triage-question"]);
4899 assert_eq!(saved.actions_applied, ["choice"]);
4900 assert_eq!(saved.base_recovery_requests, ["base-request"]);
4901 assert_eq!(saved.chat_notices, ["delivery", "other-delivery"]);
4902 assert_eq!(saved.repair_grants, [grant.clone(), latest_grant.clone()]);
4903 assert_eq!(
4904 saved.repair_reconciliations,
4905 std::slice::from_ref(&reconciliation)
4906 );
4907 for ledger in [
4908 saved.decision_effects,
4909 saved.dispatched_resumes,
4910 saved.superseded_resumes,
4911 ] {
4912 assert_eq!(ledger["shared"], "committed");
4913 assert_eq!(ledger["only-stale"], "receipt");
4914 }
4915 }
4916 }
4917
4918 #[test]
4919 fn repeated_completion_only_notifies_for_new_occurrences() {
4920 let mut task = chat_task();
4921 task.succeed(completion(&task));
4922 let first = task.chat_notice_key().unwrap();
4923 task.chat_notices.push(first.clone());
4924 task.succeed(completion(&task));
4925 assert_eq!(task.completion_history.len(), 1, "idempotent while done");
4926 assert_eq!(task.chat_notice_due(), None);
4927 let mut context = completion(&task);
4928 context.reason = Some("inspect".into());
4929 task.reopen(context).unwrap();
4930 task.succeed(completion(&task));
4931 let second = task.chat_notice_key().unwrap();
4932 assert_ne!(first, second);
4933 assert_eq!(task.chat_notice_due(), Some(second));
4934 assert_eq!(task.completion_history.len(), 3);
4935 }
4936
4937 #[test]
4938 fn old_tasks_have_unknown_completion_provenance_not_invented_events() {
4939 let mut task = task("legacy");
4940 task.status = TaskStatus::Done;
4941 let mut value = serde_json::to_value(&task).unwrap();
4942 value.as_object_mut().unwrap().remove("completion_history");
4943 let task: Task = serde_json::from_value(value).unwrap();
4944 assert!(task.completion_history.is_empty());
4945 assert_eq!(task.chat_notice_key().as_deref(), Some("done"));
4946 }
4947
4948 #[test]
4949 fn triage_applied_survives_release_and_old_records_read_as_empty() {
4950 let mut t = Task::new(
4951 "t".to_owned(),
4952 "i".to_owned(),
4953 PathBuf::from("r"),
4954 Source::Human,
4955 );
4956 t.mark_triage_applied("q1");
4957 t.mark_triage_applied("q1");
4958 t.hold_machine(Some("x".to_owned()));
4959 t.release();
4960 assert_eq!(t.triage_applied, ["q1"]);
4961 assert!(t.triage_applied("q1") && !t.triage_applied("q2"));
4962
4963 let mut v = serde_json::to_value(&t).unwrap();
4964 v.as_object_mut().unwrap().remove("triage_applied");
4965 let old: Task = serde_json::from_value(v).unwrap();
4966 assert!(old.triage_applied.is_empty());
4967 }
4968
4969 #[test]
4970 fn task_counts_of_empty_is_all_zero() {
4971 assert_eq!(TaskCounts::of(&[]), TaskCounts::default());
4972 }
4973
4974 #[test]
4975 fn task_counts_of_tallies_every_status() {
4976 let mut queued = Task::new(
4977 "q".to_owned(),
4978 "i".to_owned(),
4979 PathBuf::from("."),
4980 Source::Human,
4981 );
4982 queued.status = TaskStatus::Queued;
4983 let mut running = queued.clone();
4984 running.status = TaskStatus::Running;
4985 let mut done = queued.clone();
4986 done.status = TaskStatus::Done;
4987 let mut failed = queued.clone();
4988 failed.status = TaskStatus::Failed;
4989 let mut held = queued.clone();
4990 held.status = TaskStatus::Held;
4991 let mut blocked = queued.clone();
4992 blocked.status = TaskStatus::Blocked;
4993
4994 let mut parked = queued.clone();
4995 parked.status = TaskStatus::Parked;
4996
4997 let counts = TaskCounts::of(&[
4998 queued,
4999 running,
5000 done.clone(),
5001 done,
5002 failed,
5003 held,
5004 blocked,
5005 parked,
5006 ]);
5007 assert_eq!(
5008 counts,
5009 TaskCounts {
5010 queued: 1,
5011 running: 1,
5012 done: 2,
5013 failed: 1,
5014 held: 1,
5015 blocked: 1,
5016 parked: 1,
5017 }
5018 );
5019 }
5020
5021 #[test]
5022 fn task_implementers_persist_normalized_without_losing_history() {
5023 let (_dir, q) = queue();
5024 let mut t = task("keep me");
5025 t.hold_manual(Some("waiting".into()));
5026 t.runs.push("earlier-run".into());
5027 t.attachments.push("reference.txt".into());
5028 let cfg: crate::config::Config =
5029 toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
5030 .unwrap();
5031 q.put(&mut t).unwrap();
5032 let original = serde_json::to_value(&t).unwrap();
5033 for n in [2, 1, 2] {
5034 t.set_implementers(n, &cfg).unwrap();
5035 q.put(&mut t).unwrap();
5036 t = q.get(&t.id).unwrap();
5037 assert_eq!(t.implementers(), Some(usize::from(n)));
5038 assert_eq!(t.solo, n == 1);
5039 if n == 1 {
5040 assert!(t.overrides.is_none());
5041 }
5042 let mut actual = serde_json::to_value(&t).unwrap();
5043 for field in ["solo", "overrides", "updated_at"] {
5044 actual[field] = original[field].clone();
5045 }
5046 assert_eq!(actual, original);
5047 }
5048 t.overrides.as_mut().unwrap().judges = Some(2);
5049 t.set_implementers(1, &cfg).unwrap();
5050 assert_eq!(t.overrides.as_ref().unwrap().judges, Some(2));
5051 assert_eq!(t.overrides.as_ref().unwrap().candidates, None);
5052 }
5053
5054 #[test]
5055 fn task_implementers_old_records_keep_inheritance_until_changed() {
5056 let mut value = serde_json::to_value(task("old task")).unwrap();
5057 value.as_object_mut().unwrap().remove("solo");
5058 value.as_object_mut().unwrap().remove("overrides");
5059 let mut old: Task = serde_json::from_value(value).unwrap();
5060 assert_eq!(old.implementers(), None);
5061 old.set_implementers(1, &crate::config::Config::default())
5062 .unwrap();
5063 assert!(old.solo);
5064 assert!(old.overrides.is_none());
5065 }
5066
5067 #[test]
5068 fn task_implementers_reject_invalid_counts_and_states() {
5069 let cfg = crate::config::Config::default();
5070 let mut t = task("unchanged");
5071 for n in [0, 4, 255] {
5072 assert!(t.set_implementers(n, &cfg).is_err());
5073 }
5074 for status in [
5075 TaskStatus::Running,
5076 TaskStatus::Done,
5077 TaskStatus::Failed,
5078 TaskStatus::Blocked,
5079 TaskStatus::Parked,
5080 ] {
5081 t.status = status;
5082 let before = serde_json::to_value(&t).unwrap();
5083 assert!(t.set_implementers(1, &cfg).is_err());
5084 assert_eq!(serde_json::to_value(&t).unwrap(), before);
5085 }
5086 }
5087
5088 fn queue() -> (tempfile::TempDir, Queue) {
5091 let dir = tempfile::tempdir().unwrap();
5092 let q = Queue::at(dir.path().join("queue"));
5093 (dir, q)
5094 }
5095
5096 #[test]
5097 fn base_recovery_commit_retains_decision_and_superseded_resume_evidence() {
5098 let (_dir, q) = queue();
5099 let mut original = task("base recovery");
5100 original
5101 .decision_effects
5102 .insert("old-effect".into(), "receipt".into());
5103 original
5104 .dispatched_resumes
5105 .insert("dispatched".into(), "prior-run".into());
5106 original.resume_override = Some(OperatorResume {
5107 question_id: "prior-decision".into(),
5108 at: Timestamp::now(),
5109 conductor_rehold: None,
5110 forced: true,
5111 pinned_run: Some("retained-run".into()),
5112 });
5113 q.put(&mut original).unwrap();
5114 let expected = serde_json::to_value(&original).unwrap();
5115 let mut recovered = original.clone();
5116 recovered.base_recovery_requests.push("chat/request".into());
5117 recovered
5118 .resume_override
5119 .as_mut()
5120 .unwrap()
5121 .question_id
5122 .clear();
5123 q.commit_base_recovery(&mut recovered, &expected).unwrap();
5124 let saved = q.get(&original.id).unwrap();
5125 assert_eq!(saved.decision_effects, original.decision_effects);
5126 assert_eq!(saved.dispatched_resumes, original.dispatched_resumes);
5127 assert_eq!(
5128 saved
5129 .superseded_resumes
5130 .get("prior-decision")
5131 .map(String::as_str),
5132 Some("retained-run")
5133 );
5134 assert_eq!(saved.base_recovery_requests, ["chat/request"]);
5135 assert!(saved.resume_override.unwrap().question_id.is_empty());
5136 assert!(q.commit_base_recovery(&mut recovered, &expected).is_err());
5137 }
5138
5139 #[test]
5140 fn a_stale_write_does_not_drop_the_recorded_task_chat() {
5141 let (_dir, q) = queue();
5142 let mut stale = task("chat");
5143 q.put(&mut stale).unwrap();
5144 let mut fresh = q.get(&stale.id).unwrap();
5145 fresh.chat = Some("talk-1".to_owned());
5146 q.put(&mut fresh).unwrap();
5147 q.put(&mut stale).unwrap();
5148 assert_eq!(q.get(&stale.id).unwrap().chat.as_deref(), Some("talk-1"));
5149 }
5150
5151 #[test]
5152 fn putting_a_machine_held_task_files_a_notification_beside_the_queue() {
5153 let dir = tempfile::tempdir().unwrap();
5154 let q = Queue::at(dir.path().join("queue"));
5155 let mut t = task("held");
5156 q.put(&mut t).unwrap();
5157 assert_eq!(
5158 crate::notices::Notices::at(dir.path().join("notifications"))
5159 .list()
5160 .len(),
5161 0
5162 );
5163 t.hold_machine(Some("out of attempts".to_owned()));
5164 q.put(&mut t).unwrap();
5165 let listed = crate::notices::Notices::at(dir.path().join("notifications")).list();
5166 assert_eq!(listed.len(), 1);
5167 assert!(listed[0].message.contains("out of attempts"));
5168 }
5169
5170 #[test]
5171 fn start_consumes_the_disk_resume_pin() {
5172 let mut t = task("pin");
5173 t.disk_resume_run = Some("run-1".into());
5174 t.start("run-1".into());
5175 assert!(t.disk_resume_run.is_none());
5176 }
5177
5178 fn task(title: &str) -> Task {
5179 Task::new(
5180 title.to_owned(),
5181 format!("do {title}"),
5182 PathBuf::from("."),
5183 Source::Human,
5184 )
5185 }
5186
5187 #[test]
5188 fn attempt_limit_inherits_old_records_and_controls_failure() {
5189 let mut t = task("budget");
5190 let mut old = serde_json::to_value(&t).unwrap();
5191 old.as_object_mut().unwrap().remove("attempt_limit");
5192 old["schema"] = serde_json::json!(15);
5193 let legacy: Task = serde_json::from_value(old).unwrap();
5194 assert_eq!(legacy.attempt_limit, None);
5195 assert_eq!(legacy.effective_attempt_limit(2), 2);
5196 t.attempts = 2;
5197 t.change_attempt_limit(NonZeroUsize::new(3)).unwrap();
5198 t.fail("retry", 1);
5199 assert_eq!(t.status, TaskStatus::Failed);
5200 t.attempts = 3;
5201 t.fail("stop", 10);
5202 assert_eq!(t.status, TaskStatus::Held);
5203 t.change_attempt_limit(None).unwrap();
5204 assert_eq!(t.status, TaskStatus::Held);
5205 assert_eq!(t.attempts, 3);
5206 t.fail("inherit", 4);
5207 assert_eq!(t.status, TaskStatus::Failed);
5208 for status in [
5209 TaskStatus::Running,
5210 TaskStatus::Done,
5211 TaskStatus::Failed,
5212 TaskStatus::Blocked,
5213 TaskStatus::Parked,
5214 ] {
5215 t.status = status;
5216 assert!(t.change_attempt_limit(NonZeroUsize::new(1)).is_err());
5217 assert_eq!(t.attempt_limit, None);
5218 }
5219 }
5220
5221 #[test]
5222 fn earlier_attempts_is_every_recorded_run_and_agrees_with_the_display() {
5223 let mut t = task("retried");
5224 assert!(
5225 t.earlier_attempts().is_empty(),
5226 "a first attempt takes nothing over"
5227 );
5228 t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned()];
5229 assert_eq!(t.earlier_attempts(), ["aaaa", "bbbb"]);
5230 assert_eq!(t.successor_of("aaaa"), Some(&"bbbb".to_owned()));
5232 assert_eq!(t.successor_of("bbbb"), None);
5233 assert_eq!(t.successor_of("zzzz"), None);
5234 }
5235
5236 #[test]
5237 fn resumed_runs_are_superseded_only_after_their_last_occurrence() {
5238 let (_dir, q) = queue();
5239 let mut t = task("resumed");
5240 for (runs, successor) in [
5241 (vec!["aaaa", "aaaa"], None),
5242 (vec!["aaaa", "bbbb", "aaaa"], None),
5243 (vec!["aaaa", "aaaa", "bbbb"], Some("bbbb")),
5244 (vec!["aaaa", "bbbb", "aaaa", "cccc"], Some("cccc")),
5245 ] {
5246 t.runs = runs.into_iter().map(str::to_owned).collect();
5247 q.put(&mut t).unwrap();
5248
5249 assert_eq!(t.successor_of("aaaa").map(String::as_str), successor);
5250 assert_eq!(q.superseded_by("aaaa").as_deref(), successor);
5251 assert_eq!(q.superseded().get("aaaa").map(String::as_str), successor);
5252 }
5253 }
5254
5255 #[test]
5256 fn superseded_by_names_the_next_attempt_and_none_for_the_last() {
5257 let (_dir, q) = queue();
5258 let mut t = task("retried");
5259 t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned(), "cccc".to_owned()];
5260 q.put(&mut t).unwrap();
5261
5262 assert_eq!(q.superseded_by("aaaa"), Some("bbbb".to_owned()));
5263 assert_eq!(q.superseded_by("bbbb"), Some("cccc".to_owned()));
5264 assert_eq!(
5265 q.superseded_by("cccc"),
5266 None,
5267 "the latest attempt replaces nothing"
5268 );
5269 assert_eq!(
5270 q.superseded_by("never-heard-of-it"),
5271 None,
5272 "a run belonging to no task on this queue is not superseded"
5273 );
5274
5275 let mut by = HashMap::new();
5276 by.insert("aaaa".to_owned(), "bbbb".to_owned());
5277 by.insert("bbbb".to_owned(), "cccc".to_owned());
5278 assert_eq!(
5279 q.superseded(),
5280 by,
5281 "the whole-map and single-run forms must agree"
5282 );
5283 }
5284
5285 #[test]
5286 fn superseded_attempts_is_empty_until_the_task_is_done() {
5287 let mut t = task("retried");
5288 t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned()];
5289 t.status = TaskStatus::Failed;
5290 assert_eq!(
5291 t.superseded_attempts(true),
5292 &[] as &[String],
5293 "a task still retrying has no attempt yet that a later one made moot"
5294 );
5295
5296 t.status = TaskStatus::Running;
5297 assert_eq!(t.superseded_attempts(true), &[] as &[String]);
5298 }
5299
5300 #[test]
5301 fn superseded_attempts_names_every_run_before_the_one_that_succeeded() {
5302 let mut t = task("retried");
5303 t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned(), "cccc".to_owned()];
5304 t.status = TaskStatus::Done;
5305 assert_eq!(
5306 t.superseded_attempts(true),
5307 &["aaaa".to_owned(), "bbbb".to_owned()],
5308 "cccc is the attempt whose success made the task done, and stays out"
5309 );
5310 }
5311
5312 #[test]
5313 fn superseded_attempts_is_empty_for_a_done_task_with_only_one_attempt() {
5314 let mut t = task("first try landed");
5315 t.runs = vec!["aaaa".to_owned()];
5316 t.status = TaskStatus::Done;
5317 assert_eq!(t.superseded_attempts(true), &[] as &[String]);
5318 }
5319
5320 #[test]
5321 fn superseded_attempts_is_empty_when_the_last_run_never_actually_succeeded() {
5322 let mut t = task("closed by hand after a manual merge");
5329 t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned()];
5330 t.status = TaskStatus::Done;
5331 assert_eq!(
5332 t.superseded_attempts(false),
5333 &[] as &[String],
5334 "nothing here is provably why the task is done, so nothing is superseded"
5335 );
5336 }
5337
5338 #[test]
5339 fn latest_attempt_names_the_chain_s_current_head_not_just_the_next_one() {
5340 let (_dir, q) = queue();
5341 let mut t = task("retried twice");
5342 t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned(), "cccc".to_owned()];
5343 q.put(&mut t).unwrap();
5344
5345 assert_eq!(
5346 q.latest_attempt("aaaa"),
5347 Some("cccc".to_owned()),
5348 "an old attempt points straight at the chain's current head, not the \
5349 next attempt in the middle of it"
5350 );
5351 assert_eq!(q.latest_attempt("bbbb"), Some("cccc".to_owned()));
5352 assert_eq!(
5353 q.latest_attempt("cccc"),
5354 None,
5355 "the latest attempt is not superseded by anything"
5356 );
5357 assert_eq!(
5358 q.latest_attempt("never-heard-of-it"),
5359 None,
5360 "a run belonging to no task on this queue is not superseded"
5361 );
5362 }
5363
5364 #[test]
5365 fn a_markdown_heading_is_the_title_not_decoration() {
5366 assert_eq!(
5371 title_from("# Rework the config loader\n\nIt re-reads it.\n", 40),
5372 "Rework the config loader"
5373 );
5374 assert_eq!(title_from("- fix the thing", 40), "fix the thing");
5375 assert_eq!(title_from("> quoted task", 40), "quoted task");
5376 assert_eq!(title_from(" \n\n", 40), "(empty task)");
5378 assert_eq!(title_from("###\n", 40), "(empty task)");
5379 }
5380
5381 #[test]
5382 fn a_long_title_is_elided_by_characters_not_bytes() {
5383 let long = "課題".repeat(30);
5385 let title = title_from(&long, 10);
5386 assert_eq!(title.chars().count(), 10);
5387 assert!(title.ends_with('…'));
5388 }
5389
5390 #[test]
5391 fn priority_wins_and_ties_break_oldest_first() {
5392 let (_dir, q) = queue();
5393 let mut a = task("first");
5394 let mut b = task("second");
5395 let mut c = task("urgent");
5396 a.id = "20260101-000001-aaaa".to_owned();
5398 b.id = "20260101-000002-bbbb".to_owned();
5399 c.id = "20260101-000003-cccc".to_owned();
5400 c.priority = 5;
5401 for t in [&mut a, &mut b, &mut c] {
5402 q.put(t).unwrap();
5403 }
5404
5405 assert_eq!(q.next_runnable().unwrap().id, c.id);
5407 c.hold_machine(None);
5408 q.put(&mut c).unwrap();
5409 assert_eq!(q.next_runnable().unwrap().id, a.id);
5411 assert_eq!(q.list().len(), 3, "b is still waiting its turn");
5412 }
5413
5414 #[test]
5415 fn a_blocked_task_never_starves_another_runnable_one() {
5416 let (_dir, q) = queue();
5417 let mut blocked = task("blocked");
5418 blocked.block(vec!["something".to_owned()], None);
5419 q.put(&mut blocked).unwrap();
5420
5421 let mut runnable = task("free to go");
5422 q.put(&mut runnable).unwrap();
5423
5424 let next = q.next_runnable().expect("a runnable task is still offered");
5425 assert_eq!(next.id, runnable.id);
5426 }
5427
5428 #[test]
5429 fn a_held_task_is_never_offered_to_the_loop() {
5430 let (_dir, q) = queue();
5431 let mut t = task("held");
5432 q.put(&mut t).unwrap();
5433 assert!(q.next_runnable().is_some());
5434
5435 t.hold_machine(None);
5436 q.put(&mut t).unwrap();
5437 assert!(
5438 q.next_runnable().is_none(),
5439 "a held task must wait for a human"
5440 );
5441
5442 t.status = TaskStatus::Failed;
5444 q.put(&mut t).unwrap();
5445 assert!(q.next_runnable().is_some());
5446 }
5447
5448 #[test]
5449 fn attempts_are_capped_and_then_the_task_is_held() {
5450 let mut t = task("doomed");
5451
5452 t.start("run-1".to_owned());
5453 t.fail("gate red", 2);
5454 assert_eq!(t.status, TaskStatus::Failed, "one attempt of two: retry");
5455
5456 t.start("run-2".to_owned());
5457 t.fail("gate red", 2);
5458 assert_eq!(
5459 t.status,
5460 TaskStatus::Held,
5461 "out of attempts: stop spending money on it"
5462 );
5463 assert_eq!(t.runs, ["run-1", "run-2"]);
5464 assert_eq!(t.last_error.as_deref(), Some("gate red"));
5465 assert_eq!(
5466 t.hold_reason.as_deref(),
5467 Some("gate red"),
5468 "the hold must say why, not leave hold_reason null next to a \
5469 populated last_error"
5470 );
5471 }
5472
5473 #[test]
5474 fn handing_off_a_task_records_a_hold_reason_too() {
5475 let mut t = task("left a pull request");
5476 t.start("run-1".to_owned());
5477 t.handed_off("run ended with a pull request open [run run-1]");
5478 assert_eq!(t.status, TaskStatus::Held);
5479 assert_eq!(t.hold_source, Some(HoldSource::Machine));
5480 assert_eq!(
5481 t.hold_reason.as_deref(),
5482 Some("run ended with a pull request open [run run-1]")
5483 );
5484 assert_eq!(t.hold_reason, t.last_error);
5485 }
5486
5487 #[test]
5488 fn a_quota_stall_is_refunded_so_the_backlog_survives_the_night() {
5489 let mut t = task("stalled by quota");
5490
5491 t.start("run-1".to_owned());
5492 assert_eq!(t.attempts, 1);
5493 t.stall("judge-1, judge-2 out of quota");
5494 assert_eq!(
5495 t.attempts, 0,
5496 "a closed quota window must not spend the task's retry budget"
5497 );
5498 assert_eq!(t.status, TaskStatus::Failed, "the loop should retry it");
5499 assert_eq!(
5500 t.last_error.as_deref(),
5501 Some("judge-1, judge-2 out of quota")
5502 );
5503
5504 for _ in 0..20 {
5507 t.start("run-n".to_owned());
5508 t.stall("still out of quota");
5509 }
5510 t.start("run-real".to_owned());
5511 t.fail("gate red", 2);
5512 assert_eq!(
5513 t.status,
5514 TaskStatus::Failed,
5515 "the first attempt that was really judged is attempt one"
5516 );
5517 }
5518
5519 #[test]
5520 fn releasing_a_held_task_gives_it_a_real_second_chance() {
5521 let mut t = task("retry me");
5522 t.start("run-1".to_owned());
5523 t.fail("gate red", 1);
5524 assert_eq!(t.status, TaskStatus::Held);
5525
5526 t.release();
5527 assert_eq!(t.status, TaskStatus::Queued);
5528 assert_eq!(t.attempts, 0);
5531 assert!(t.last_error.is_none());
5532 assert_eq!(
5533 t.runs.len(),
5534 1,
5535 "history is kept: attempts reset, evidence does not"
5536 );
5537 }
5538
5539 #[test]
5540 fn a_hold_reason_survives_and_a_release_clears_it() {
5541 let mut t = task("waiting on something else");
5542 t.hold_manual(Some(
5543 "waiting for 20260101-000000-aaaa to land first".to_owned(),
5544 ));
5545 assert_eq!(t.status, TaskStatus::Held);
5546 assert_eq!(
5547 t.hold_reason.as_deref(),
5548 Some("waiting for 20260101-000000-aaaa to land first")
5549 );
5550
5551 t.hold_manual(None);
5553 assert_eq!(
5554 t.hold_reason.as_deref(),
5555 Some("waiting for 20260101-000000-aaaa to land first"),
5556 "a bare re-hold keeps whatever a human already wrote down"
5557 );
5558
5559 let mut plain = task("no reason given");
5561 plain.hold_manual(None);
5562 assert_eq!(plain.status, TaskStatus::Held);
5563 assert!(plain.hold_reason.is_none());
5564
5565 t.release();
5566 assert_eq!(t.status, TaskStatus::Queued);
5567 assert!(
5568 t.hold_reason.is_none(),
5569 "a stale reason must not greet the next person who holds this task"
5570 );
5571 }
5572
5573 #[test]
5574 fn closing_a_held_task_as_done_clears_its_hold_reason_too() {
5575 let mut t = task("landed by hand while held");
5580 t.hold_manual(Some("waiting on 3ed9".to_owned()));
5581 assert_eq!(t.hold_reason.as_deref(), Some("waiting on 3ed9"));
5582
5583 t.succeed(completion(&t));
5584 assert_eq!(t.status, TaskStatus::Done);
5585 assert!(
5586 t.hold_reason.is_none(),
5587 "a done task cannot still be waiting on something"
5588 );
5589 }
5590
5591 #[test]
5592 fn holding_or_closing_a_blocked_task_clears_its_dependency_too() {
5593 let mut held = task("held straight out of blocked");
5600 held.block(
5601 vec!["20260101-000000-dead".to_owned()],
5602 Some("waiting on the migration script".to_owned()),
5603 );
5604 assert_eq!(held.status, TaskStatus::Blocked);
5605
5606 held.hold_manual(None);
5607 assert_eq!(held.status, TaskStatus::Held);
5608 assert!(
5609 held.blocked_by.is_empty(),
5610 "hold overrides the wait, same as release"
5611 );
5612 assert!(held.block_reason.is_none());
5613
5614 let mut done = task("closed straight out of blocked");
5615 done.block(
5616 vec!["20260101-000000-dead".to_owned()],
5617 Some("waiting on the migration script".to_owned()),
5618 );
5619 done.succeed(completion(&done));
5620 assert_eq!(done.status, TaskStatus::Done);
5621 assert!(
5622 done.blocked_by.is_empty(),
5623 "a done task cannot still be waiting on a dependency"
5624 );
5625 assert!(done.block_reason.is_none());
5626 }
5627
5628 #[test]
5629 fn a_blocked_task_is_never_offered_to_the_loop() {
5630 let mut t = task("blocked");
5631 assert!(t.status.runnable());
5632 t.block(
5633 vec!["dep-id".to_owned()],
5634 Some("waits on dep-id".to_owned()),
5635 );
5636 assert_eq!(t.status, TaskStatus::Blocked);
5637 assert!(!t.status.runnable());
5638 assert_eq!(TaskStatus::Blocked.as_str(), "blocked");
5639 }
5640
5641 #[test]
5642 fn unblocking_the_last_dependency_returns_the_task_to_queued() {
5643 let mut t = task("blocked on two");
5644 t.block(
5645 vec!["a".to_owned(), "b".to_owned()],
5646 Some("waits on a and b".to_owned()),
5647 );
5648
5649 t.unblock("a");
5650 assert_eq!(t.status, TaskStatus::Blocked, "b is still outstanding");
5651 assert_eq!(t.blocked_by, ["b"]);
5652
5653 t.unblock("b");
5654 assert_eq!(t.status, TaskStatus::Queued);
5655 assert!(t.blocked_by.is_empty());
5656 assert!(t.block_reason.is_none());
5657 }
5658
5659 #[test]
5660 fn unblocking_an_id_on_a_task_that_is_not_blocked_is_a_no_op() {
5661 let mut t = task("never blocked");
5662 t.unblock("whatever");
5663 assert_eq!(t.status, TaskStatus::Queued);
5664 }
5665
5666 #[test]
5667 fn a_held_task_blocked_on_a_question_returns_to_held_not_queued() {
5668 let mut t = task("held, then asked about");
5673 t.hold_machine(Some("out of attempts".to_owned()));
5674 assert_eq!(t.status, TaskStatus::Held);
5675
5676 t.block(vec!["q1".to_owned()], Some("what now?".to_owned()));
5677 assert_eq!(t.status, TaskStatus::Blocked);
5678
5679 t.record_answer("what now?".to_owned(), "leave it held".to_owned());
5680 t.unblock("q1");
5681 assert_eq!(t.status, TaskStatus::Held, "must restore, not requeue");
5682 assert_eq!(t.hold_reason.as_deref(), Some("out of attempts"));
5683 assert_eq!(t.hold_source, Some(HoldSource::Machine));
5684 assert!(t.blocked_from.is_none(), "consumed once restored");
5685 }
5686
5687 #[test]
5688 fn a_manually_held_task_blocked_on_a_question_returns_to_held() {
5689 let mut t = task("manually held, then asked about");
5690 t.hold_manual(Some("waiting on a dependency".to_owned()));
5691
5692 t.block(vec!["q1".to_owned()], None);
5693 t.unblock("q1");
5694
5695 assert_eq!(t.status, TaskStatus::Held);
5696 assert_eq!(t.hold_source, Some(HoldSource::Manual));
5697 }
5698
5699 #[test]
5700 fn re_blocking_an_already_blocked_task_keeps_the_original_blocked_from() {
5701 let mut t = task("held, blocked twice");
5705 t.hold_machine(None);
5706 t.block(vec!["q1".to_owned()], Some("first".to_owned()));
5707 t.block(
5708 vec!["q1".to_owned(), "q2".to_owned()],
5709 Some("second".to_owned()),
5710 );
5711
5712 t.unblock("q1");
5713 assert_eq!(t.status, TaskStatus::Blocked, "q2 still outstanding");
5714 t.unblock("q2");
5715 assert_eq!(t.status, TaskStatus::Held);
5716 }
5717
5718 #[test]
5719 fn unblocking_a_task_blocked_while_running_lands_on_queued_not_running() {
5720 let mut t = task("blocked mid-run");
5724 t.start("run-1".to_owned());
5725 assert_eq!(t.status, TaskStatus::Running);
5726
5727 t.block(vec!["q1".to_owned()], None);
5728 t.unblock("q1");
5729 assert_eq!(t.status, TaskStatus::Queued);
5730 }
5731
5732 #[test]
5733 fn a_pre_schema_4_blocked_record_with_hold_evidence_restores_to_held() {
5734 let mut t = task("legacy record, held before it was blocked");
5740 t.hold_source = Some(HoldSource::Machine);
5741 t.hold_reason = Some("legacy hold reason".to_owned());
5742 t.status = TaskStatus::Blocked;
5743 t.blocked_by = vec!["q1".to_owned()];
5744 t.blocked_from = None;
5745
5746 t.unblock("q1");
5747 assert_eq!(t.status, TaskStatus::Held);
5748 }
5749
5750 #[test]
5751 fn a_pre_schema_4_blocked_record_with_no_hold_evidence_restores_to_queued() {
5752 let mut t = task("legacy record, ordinary dependency block");
5753 t.status = TaskStatus::Blocked;
5754 t.blocked_by = vec!["dep".to_owned()];
5755 t.blocked_from = None;
5756
5757 t.unblock("dep");
5758 assert_eq!(t.status, TaskStatus::Queued);
5759 }
5760
5761 #[test]
5762 fn answering_a_question_is_recorded_and_survives_a_release() {
5763 let mut t = task("asked something");
5764 t.block(vec!["q1".to_owned()], Some("which backend?".to_owned()));
5765 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
5766 t.unblock("q1");
5767 assert_eq!(t.status, TaskStatus::Queued);
5768 assert_eq!(t.answers.len(), 1);
5769 assert_eq!(t.answers[0].answer, "SQLite");
5770
5771 t.release();
5775 assert_eq!(t.answers.len(), 1, "the answer is not lost on release");
5776 }
5777
5778 #[test]
5779 fn resumption_review_branch_requires_unchanged_authored_criteria() {
5780 for source in ["cli", "web"] {
5781 let mut t = task("review old candidate");
5782 t.request_review("candidate-A".into());
5783 t.hold_for_handover(Some("candidate-A".into()), "handover refused".into());
5784 let mut unchanged = t.clone();
5785 unchanged.release_operator(source, None);
5786 assert_eq!(unchanged.review_branch.as_deref(), Some("candidate-A"));
5787 t.edit(
5788 "review approved head".into(),
5789 "Reuse measured PR head B; fix Clippy; review".into(),
5790 )
5791 .unwrap();
5792 t.release_operator(source, None);
5793 assert!(t.review_branch.is_none());
5794 assert!(t.review_instruction.is_none());
5795 let mut legacy = unchanged;
5797 legacy.review_instruction = None;
5798 legacy.hold_for_handover(None, "still checked out".into());
5799 legacy
5800 .edit("new plan".into(), "Reuse measured PR head B".into())
5801 .unwrap();
5802 legacy.release_operator(source, None);
5803 assert!(legacy.review_branch.is_none());
5804 }
5805 }
5806
5807 #[test]
5808 fn a_refused_handover_keeps_the_review_branch_across_release() {
5809 let mut t = task("refused takeover");
5810 t.start("run-1".to_owned());
5811 t.hold_for_handover(Some("magi/eba2/A".to_owned()), "checked out".to_owned());
5812 assert_eq!(t.status, TaskStatus::Held);
5813 assert_eq!(t.attempts, 1);
5814 t.release();
5815 assert_eq!(t.status, TaskStatus::Queued);
5816 assert_eq!(t.attempts, 0);
5817 assert_eq!(t.review_branch.as_deref(), Some("magi/eba2/A"));
5818
5819 t.hold_for_handover(None, "again".to_owned());
5821 t.requeue();
5822 assert!(t.review_branch.is_none());
5823
5824 let mut m = task("manual");
5826 m.review_branch = Some("magi/x/A".to_owned());
5827 m.hold_manual(None);
5828 m.release();
5829 assert!(m.review_branch.is_none());
5830 }
5831
5832 #[test]
5833 fn requesting_review_requeues_the_task_and_remembers_the_branch() {
5834 let mut t = task("blocked run with a surviving branch");
5835 t.start("run-1".to_owned());
5836 t.fail("blocked with major findings", 5);
5837 assert_eq!(t.status, TaskStatus::Failed);
5838
5839 t.request_review("magi/eba2/A".to_owned());
5840 assert_eq!(t.status, TaskStatus::Queued);
5841 assert_eq!(t.attempts, 0);
5842 assert_eq!(t.review_branch.as_deref(), Some("magi/eba2/A"));
5843
5844 t.release();
5846 assert!(t.review_branch.is_none());
5847 }
5848
5849 #[test]
5850 fn conductor_requeue_but_not_an_ordinary_release_forces_a_fresh_start() {
5851 let mut t = task("retry");
5852 t.start("run-1".to_owned());
5853 t.requeue();
5854 assert!(t.fresh_start);
5855
5856 t.release();
5857 assert!(!t.fresh_start);
5858 }
5859
5860 #[test]
5861 fn urgent_only_changes_queued_or_held_and_preserves_settings() {
5862 for status in [
5863 TaskStatus::Queued,
5864 TaskStatus::Held,
5865 TaskStatus::Running,
5866 TaskStatus::Done,
5867 TaskStatus::Failed,
5868 TaskStatus::Blocked,
5869 TaskStatus::Parked,
5870 ] {
5871 let mut t = task("urgent settings");
5872 t.status = status;
5873 t.attempts = 2;
5874 t.hold_reason = Some("waiting".into());
5875 t.priority = 7;
5876 t.interrupt = true;
5877 let before = serde_json::to_value(&t).unwrap();
5878 for urgent in [true, true, false, false] {
5879 let result = t.set_urgent(urgent);
5880 let mut expected = before.clone();
5881 if matches!(status, TaskStatus::Queued | TaskStatus::Held) {
5882 result.unwrap();
5883 expected["urgent"] = urgent.into();
5884 } else {
5885 let error = result.unwrap_err().to_string();
5886 assert!(error.contains(status.as_str()), "{error}");
5887 assert!(error.contains("queued or held"), "{error}");
5888 }
5889 assert_eq!(serde_json::to_value(&t).unwrap(), expected);
5890 }
5891 }
5892 }
5893
5894 #[test]
5895 fn priority_can_be_changed_while_queued_but_not_while_running() {
5896 let mut t = task("reprioritise me");
5897 t.set_priority(5).unwrap();
5898 assert_eq!(t.priority, 5);
5899
5900 t.start("run-1".to_owned());
5901 let err = t.set_priority(9).unwrap_err().to_string();
5902 assert!(err.contains("running"), "{err}");
5903 assert_eq!(t.priority, 5, "the rejected write must not partially apply");
5904 }
5905
5906 #[test]
5907 fn interrupt_can_be_marked_while_queued_but_not_while_running() {
5908 let mut t = task("interrupt me");
5909 assert!(!t.interrupt, "off unless asked, same as any other task");
5910
5911 t.set_interrupt(true).unwrap();
5912 assert!(t.interrupt);
5913
5914 t.start("run-1".to_owned());
5915 assert!(
5916 !t.interrupt,
5917 "the mark is one-shot: dispatching the task fulfils it, \
5918 whatever the run that follows ends up doing"
5919 );
5920 let err = t.set_interrupt(true).unwrap_err().to_string();
5921 assert!(err.contains("running"), "{err}");
5922 t.set_interrupt(false).unwrap();
5925 assert!(!t.interrupt);
5926 }
5927
5928 #[test]
5932 fn a_failed_run_does_not_leave_the_task_still_marked_to_interrupt() {
5933 let mut t = task("interrupt me");
5934 t.set_interrupt(true).unwrap();
5935 t.start("run-1".to_owned());
5936 t.fail("mock failure", 5);
5937 assert_eq!(t.status, TaskStatus::Failed);
5938 assert!(
5939 !t.interrupt,
5940 "one attempt already spent the mark; a retry is an ordinary \
5941 requeue, not a fresh interrupt request"
5942 );
5943 }
5944
5945 #[test]
5946 fn changing_priority_moves_a_task_ahead_in_the_real_queue_order() {
5947 let (_dir, q) = queue();
5948 let mut a = task("first filed");
5949 let mut b = task("second filed");
5950 a.id = "20260101-000001-aaaa".to_owned();
5951 b.id = "20260101-000002-bbbb".to_owned();
5952 q.put(&mut a).unwrap();
5953 q.put(&mut b).unwrap();
5954
5955 assert_eq!(
5956 q.next_runnable().unwrap().id,
5957 a.id,
5958 "with equal priority the older task goes first, so a burst of \
5959 new work cannot starve it"
5960 );
5961 assert_eq!(
5962 q.list()[0].id,
5963 b.id,
5964 "but the list an operator reads is newest first, the same as \
5965 before priority existed - a's turn to run does not make it the \
5966 newest task"
5967 );
5968
5969 let mut a = q.get(&a.id).unwrap();
5970 a.set_priority(10).unwrap();
5971 q.put(&mut a).unwrap();
5972
5973 assert_eq!(
5974 q.next_runnable().unwrap().id,
5975 a.id,
5976 "a raised priority must be reflected the moment it is saved"
5977 );
5978 assert_eq!(
5982 q.list()[0].id,
5983 a.id,
5984 "the raised task must sort first in the list an operator reads, \
5985 not only in next_runnable's own ordering"
5986 );
5987 }
5988
5989 #[test]
5990 fn editing_replaces_title_and_instruction_but_keeps_identity_and_history() {
5991 let mut t = Task::new(
5992 "old title".to_owned(),
5993 "old instruction".to_owned(),
5994 PathBuf::from("/repo"),
5995 Source::Agent {
5996 run: "20260101-000000-beef".to_owned(),
5997 node: "implement".to_owned(),
5998 },
5999 );
6000 let id = t.id.clone();
6001 let created_at = t.created_at;
6002 t.runs.push("20260101-000000-beef".to_owned());
6003
6004 t.edit("new title".to_owned(), "new instruction".to_owned())
6005 .unwrap();
6006
6007 assert_eq!(t.title, "new title");
6008 assert_eq!(t.instruction, "new instruction");
6009 assert_eq!(t.id, id, "editing must not mint a new id");
6010 assert_eq!(t.created_at, created_at);
6011 assert_eq!(
6012 t.source,
6013 Source::Agent {
6014 run: "20260101-000000-beef".to_owned(),
6015 node: "implement".to_owned(),
6016 },
6017 "editing must not turn agent attribution into human"
6018 );
6019 assert_eq!(t.runs, ["20260101-000000-beef"]);
6020 }
6021
6022 #[test]
6023 fn editing_is_refused_once_a_task_is_running_or_finished() {
6024 let mut running = task("in flight");
6025 running.start("run-1".to_owned());
6026 let err = running
6027 .edit("x".to_owned(), "y".to_owned())
6028 .unwrap_err()
6029 .to_string();
6030 assert!(err.contains("running"), "{err}");
6031
6032 let mut done = task("finished");
6033 done.succeed(completion(&done));
6034 let err = done
6035 .edit("x".to_owned(), "y".to_owned())
6036 .unwrap_err()
6037 .to_string();
6038 assert!(err.contains("done"), "{err}");
6039
6040 let mut queued = task("waiting");
6042 queued.edit("x".to_owned(), "y".to_owned()).unwrap();
6043 let mut held = task("parked");
6044 held.hold_machine(None);
6045 held.edit("x".to_owned(), "y".to_owned()).unwrap();
6046 }
6047
6048 #[test]
6049 fn a_task_recorded_without_a_hold_reason_still_reads_as_none() {
6050 let (_dir, q) = queue();
6051 let path = q.path_of("20260101-000000-aaaa");
6052 std::fs::create_dir_all(q.root()).unwrap();
6053 std::fs::write(
6054 &path,
6055 serde_json::json!({
6056 "schema": SCHEMA,
6057 "id": "20260101-000000-aaaa",
6058 "title": "from before hold reasons existed",
6059 "instruction": "from before hold reasons existed",
6060 "repo": ".",
6061 "source": { "kind": "human" },
6062 "status": "held",
6063 "created_at": Timestamp::now().to_string(),
6064 "updated_at": Timestamp::now().to_string(),
6065 })
6066 .to_string(),
6067 )
6068 .unwrap();
6069
6070 let task = q.get("20260101-000000-aaaa").expect("must still read");
6071 assert!(task.hold_reason.is_none());
6072 assert!(task.operator_held());
6073 }
6074
6075 #[test]
6076 fn a_legacy_reasoned_hold_defaults_to_operator_protection() {
6077 let (_dir, q) = queue();
6078 let path = q.path_of("20260101-000000-bbbb");
6079 std::fs::create_dir_all(q.root()).unwrap();
6080 std::fs::write(
6081 &path,
6082 serde_json::json!({
6083 "schema": 2,
6084 "id": "20260101-000000-bbbb",
6085 "title": "old manual recovery",
6086 "instruction": "old manual recovery",
6087 "repo": ".",
6088 "source": { "kind": "human" },
6089 "status": "held",
6090 "hold_reason": "active manual recovery run20260912-224242-daf5",
6091 "created_at": Timestamp::now().to_string(),
6092 "updated_at": Timestamp::now().to_string(),
6093 })
6094 .to_string(),
6095 )
6096 .unwrap();
6097
6098 let task = q.get("20260101-000000-bbbb").expect("must still read");
6099 assert_eq!(task.hold_source, None);
6100 assert!(task.operator_held());
6101 }
6102
6103 #[test]
6104 fn a_task_recorded_without_a_diagnostic_still_reads_as_none() {
6105 let (_dir, q) = queue();
6106 let path = q.path_of("20260101-000000-aaaa");
6107 std::fs::create_dir_all(q.root()).unwrap();
6108 std::fs::write(
6109 &path,
6110 serde_json::json!({
6111 "schema": SCHEMA,
6112 "id": "20260101-000000-aaaa",
6113 "title": "from before diagnostics existed",
6114 "instruction": "from before diagnostics existed",
6115 "repo": ".",
6116 "source": { "kind": "human" },
6117 "status": "held",
6118 "created_at": Timestamp::now().to_string(),
6119 "updated_at": Timestamp::now().to_string(),
6120 })
6121 .to_string(),
6122 )
6123 .unwrap();
6124
6125 let task = q.get("20260101-000000-aaaa").expect("must still read");
6126 assert!(task.diagnostic.is_none());
6127 }
6128
6129 #[test]
6130 fn a_schema_1_task_with_no_blocking_fields_still_reads() {
6131 let (_dir, q) = queue();
6135 let path = q.path_of("20260101-000000-aaaa");
6136 std::fs::create_dir_all(q.root()).unwrap();
6137 std::fs::write(
6138 &path,
6139 serde_json::json!({
6140 "schema": 1,
6141 "id": "20260101-000000-aaaa",
6142 "title": "from before blocking existed",
6143 "instruction": "from before blocking existed",
6144 "repo": ".",
6145 "source": { "kind": "human" },
6146 "status": "queued",
6147 "created_at": Timestamp::now().to_string(),
6148 "updated_at": Timestamp::now().to_string(),
6149 })
6150 .to_string(),
6151 )
6152 .unwrap();
6153
6154 let task = q.get("20260101-000000-aaaa").expect("must still read");
6155 assert!(task.blocked_by.is_empty());
6156 assert!(task.block_reason.is_none());
6157 assert!(task.answers.is_empty());
6158 assert!(task.review_branch.is_none());
6159 }
6160
6161 #[test]
6162 fn releasing_or_finishing_a_task_clears_its_stale_diagnostic() {
6163 let mut held = task("diagnosed");
6168 held.start("run-1".to_owned());
6169 held.fail("gate red", 1);
6170 held.diagnostic = Some("cargo test failed: ...".to_owned());
6171 assert_eq!(held.status, TaskStatus::Held);
6172
6173 held.release();
6174 assert!(held.diagnostic.is_none());
6175
6176 held.diagnostic = Some("cargo test failed: ...".to_owned());
6177 held.succeed(completion(&held));
6178 assert!(held.diagnostic.is_none());
6179 }
6180
6181 #[test]
6182 fn failing_a_task_always_clears_whatever_diagnostic_it_carried() {
6183 let mut t = task("retried");
6184 t.start("run-1".to_owned());
6185 t.diagnostic = Some("stale evidence from a previous hold".to_owned());
6186 t.fail("unrelated config error", 5);
6187 assert_eq!(t.status, TaskStatus::Failed);
6188 assert!(
6189 t.diagnostic.is_none(),
6190 "fail() must not let an old diagnostic outlive the run that produced it"
6191 );
6192 }
6193
6194 #[test]
6195 fn a_claim_is_exclusive_and_releases_on_drop() {
6196 let (_dir, q) = queue();
6197 let mut t = task("contended");
6198 q.put(&mut t).unwrap();
6199
6200 let held = q.claim(&t.id).unwrap();
6201 assert!(
6202 q.claim(&t.id).is_err(),
6203 "two daemons must not drive one task into two runs"
6204 );
6205 drop(held);
6206 assert!(q.claim(&t.id).is_ok(), "a released claim is reclaimable");
6207 }
6208
6209 #[test]
6210 fn a_round_trip_survives_disk() {
6211 let (_dir, q) = queue();
6212 let mut t = Task::new(
6213 "titled".to_owned(),
6214 "body".to_owned(),
6215 PathBuf::from("/repo"),
6216 Source::Agent {
6217 run: "20260101-000000-beef".to_owned(),
6218 node: "implement".to_owned(),
6219 },
6220 );
6221 t.priority = 3;
6222 q.put(&mut t).unwrap();
6223
6224 let back = q.get(&t.id).unwrap();
6225 assert_eq!(back.id, t.id);
6226 assert_eq!(back.priority, 3);
6227 assert_eq!(back.source.label(), "implement@beef");
6228 assert_eq!(q.get(t.short()).unwrap().id, t.id);
6230 }
6231
6232 #[test]
6233 fn an_unreadable_task_does_not_take_the_queue_down() {
6234 let (_dir, q) = queue();
6235 let mut t = task("fine");
6236 q.put(&mut t).unwrap();
6237 std::fs::write(q.root().join("broken.json"), "{ not json").unwrap();
6238
6239 let listed = q.list();
6240 assert_eq!(listed.len(), 1, "the readable task still lists");
6241 assert_eq!(listed[0].id, t.id);
6242 }
6243
6244 #[test]
6245 fn a_task_recorded_without_a_solo_field_still_reads_as_not_solo() {
6246 let (_dir, q) = queue();
6247 let path = q.path_of("20260101-000000-aaaa");
6248 std::fs::create_dir_all(q.root()).unwrap();
6249 std::fs::write(
6250 &path,
6251 serde_json::json!({
6252 "schema": SCHEMA,
6253 "id": "20260101-000000-aaaa",
6254 "title": "from before solo existed",
6255 "instruction": "from before solo existed",
6256 "repo": ".",
6257 "source": { "kind": "human" },
6258 "status": "queued",
6259 "created_at": Timestamp::now().to_string(),
6260 "updated_at": Timestamp::now().to_string(),
6261 })
6262 .to_string(),
6263 )
6264 .unwrap();
6265
6266 let task = q.get("20260101-000000-aaaa").expect("must still read");
6267 assert!(!task.solo, "a queue file with no `solo` field means false");
6268 }
6269
6270 #[test]
6271 fn a_task_recorded_without_an_urgent_field_still_reads_as_not_urgent() {
6272 let (_dir, q) = queue();
6273 let path = q.path_of("20260101-000000-bbbb");
6274 std::fs::create_dir_all(q.root()).unwrap();
6275 std::fs::write(
6276 &path,
6277 serde_json::json!({
6278 "schema": SCHEMA,
6279 "id": "20260101-000000-bbbb",
6280 "title": "from before urgent existed",
6281 "instruction": "from before urgent existed",
6282 "repo": ".",
6283 "source": { "kind": "human" },
6284 "status": "queued",
6285 "created_at": Timestamp::now().to_string(),
6286 "updated_at": Timestamp::now().to_string(),
6287 })
6288 .to_string(),
6289 )
6290 .unwrap();
6291
6292 let task = q.get("20260101-000000-bbbb").expect("must still read");
6293 assert!(
6294 !task.urgent,
6295 "a queue file with no `urgent` field means false, same as `solo`"
6296 );
6297 }
6298
6299 #[test]
6300 fn a_task_from_a_future_schema_is_refused_rather_than_guessed_at() {
6301 let (_dir, q) = queue();
6302 let mut t = task("from the future");
6303 q.put(&mut t).unwrap();
6304 let path = q.path_of(&t.id);
6305 let body = std::fs::read_to_string(&path)
6306 .unwrap()
6307 .replace(&format!("\"schema\": {SCHEMA}"), "\"schema\": 99");
6308 std::fs::write(&path, body).unwrap();
6309
6310 let err = q.get(&t.id).unwrap_err().to_string();
6311 assert!(err.contains("schema 99"), "{err}");
6312 }
6313
6314 #[test]
6315 fn revision_moves_when_the_queue_changes() {
6316 let (_dir, q) = queue();
6317 assert_eq!(q.revision(), 0, "an empty queue has no revision");
6318 let mut t = task("first");
6319 q.put(&mut t).unwrap();
6320 assert!(q.revision() > 0, "a written task moves the revision");
6321 }
6322
6323 #[test]
6324 fn revision_moves_when_deleting_an_older_task() {
6325 let (dir, q) = queue();
6326 let questions = Questions::at(dir.path().join("questions"));
6327 let mut t1 = task("older");
6328 q.put(&mut t1).unwrap();
6329 std::thread::sleep(std::time::Duration::from_millis(10));
6331 let mut t2 = task("newer");
6332 q.put(&mut t2).unwrap();
6333
6334 let rev_before = q.revision();
6335 q.remove(&t1.id, false, &questions).unwrap();
6336 let rev_after = q.revision();
6337
6338 assert_ne!(
6339 rev_before, rev_after,
6340 "deleting an older task must change the revision so other clients see the deletion"
6341 );
6342 }
6343
6344 #[test]
6345 fn removing_a_task_takes_it_out_of_the_listing() {
6346 let (dir, q) = queue();
6347 let questions = Questions::at(dir.path().join("questions"));
6348 let mut t = task("delete me");
6349 q.put(&mut t).unwrap();
6350 let removed = q.remove(t.short(), false, &questions).unwrap();
6351 assert_eq!(removed.id, t.id, "a prefix resolves before deleting");
6352 assert!(removed.released.is_empty() && removed.still_blocked.is_empty());
6353 assert!(q.list().is_empty());
6354 assert!(
6355 q.remove(&t.id, false, &questions).is_err(),
6356 "removing twice is an error"
6357 );
6358 }
6359
6360 #[test]
6361 fn removing_a_task_takes_its_stale_lock_with_it() {
6362 let (dir, q) = queue();
6363 let questions = Questions::at(dir.path().join("questions"));
6364 let mut t = task("interrupted");
6365 q.put(&mut t).unwrap();
6366
6367 let claim = q.claim(&t.id).unwrap();
6370 std::mem::forget(claim);
6371 assert!(
6372 q.claim(&t.id).is_err(),
6373 "the orphaned lock is what makes the task look claimed"
6374 );
6375
6376 let err = q.remove(&t.id, true, &questions).unwrap_err().to_string();
6378 assert!(err.contains("live daemon"), "{err}");
6379 assert!(q.get(&t.id).is_ok(), "a refused delete keeps the task");
6380
6381 q.remove(&t.id, false, &questions).unwrap();
6383 assert!(q.list().is_empty());
6384 let mut again = task("interrupted");
6385 again.id = t.id.clone();
6386 q.put(&mut again).unwrap();
6387 assert!(
6388 q.claim(&t.id).is_ok(),
6389 "a task that comes back must be claimable, which a left-behind lock would prevent"
6390 );
6391 }
6392
6393 fn notices_of(dir: &Path) -> Vec<crate::notices::Notice> {
6394 crate::notices::Notices::at(dir.join("notifications")).list()
6395 }
6396
6397 #[test]
6398 fn removing_a_sole_dependency_releases_the_dependent_without_a_hold() {
6399 let (dir, q) = queue();
6400 let questions = Questions::at(dir.path().join("questions"));
6401 let mut dep = task("dependency");
6402 q.put(&mut dep).unwrap();
6403 let mut blocked = task("waiting");
6404 blocked.block(vec![dep.id.clone()], Some("waits".to_owned()));
6405 q.put(&mut blocked).unwrap();
6406
6407 let removed = q.remove(&dep.id, false, &questions).unwrap();
6408 assert_eq!(removed.released, [blocked.id.clone()]);
6409 assert!(removed.still_blocked.is_empty());
6410
6411 let after = q.get(&blocked.id).unwrap();
6412 assert_eq!(after.status, TaskStatus::Queued);
6413 assert!(after.blocked_by.is_empty());
6414 assert!(after.block_reason.is_none());
6415 let notes = notices_of(dir.path());
6416 assert_eq!(notes.len(), 1, "{notes:?}");
6417 assert_eq!(notes[0].severity, crate::notices::Severity::Info);
6418 assert_eq!(
6419 notes[0].link,
6420 Some(crate::notices::Link::Task {
6421 id: blocked.id.clone(),
6422 })
6423 );
6424 }
6425
6426 #[test]
6427 fn removing_one_of_two_dependencies_keeps_the_other() {
6428 let (dir, q) = queue();
6429 let questions = Questions::at(dir.path().join("questions"));
6430 let mut dep = task("dependency");
6431 q.put(&mut dep).unwrap();
6432 let mut other = task("other");
6433 q.put(&mut other).unwrap();
6434 let mut blocked = task("waiting");
6435 blocked.block(
6436 vec![dep.id.clone(), other.id.clone()],
6437 Some("waits on both".to_owned()),
6438 );
6439 q.put(&mut blocked).unwrap();
6440
6441 let removed = q.remove(&dep.id, false, &questions).unwrap();
6442 assert!(removed.released.is_empty());
6443 assert_eq!(removed.still_blocked, [blocked.id.clone()]);
6444
6445 let after = q.get(&blocked.id).unwrap();
6446 assert_eq!(after.status, TaskStatus::Blocked);
6447 assert_eq!(after.blocked_by, [other.id.clone()]);
6448 assert!(missing_blockers(&q, &questions, &after.blocked_by).is_empty());
6451 }
6452
6453 #[test]
6454 fn a_dependency_deleted_before_its_dependents_were_rewritten_is_released_later() {
6455 let (dir, q) = queue();
6456 let questions = Questions::at(dir.path().join("questions"));
6457 let mut dep = task("dependency");
6458 q.put(&mut dep).unwrap();
6459 let mut blocked = task("waiting");
6460 blocked.block(vec![dep.id.clone()], None);
6461 q.put(&mut blocked).unwrap();
6462
6463 let claim = q.claim(&blocked.id).unwrap();
6465 let removed = q.remove(&dep.id, false, &questions).unwrap();
6466 assert!(removed.released.is_empty());
6467 drop(claim);
6468
6469 let mut task = q.get(&blocked.id).unwrap();
6470 assert_eq!(task.status, TaskStatus::Blocked);
6471 assert!(missing_blockers(&q, &questions, &task.blocked_by).is_empty());
6472 assert_eq!(
6473 q.apply_deleted_blockers(&mut task, &questions),
6474 [dep.id.clone()]
6475 );
6476 assert_eq!(task.status, TaskStatus::Queued);
6477 }
6478
6479 #[test]
6480 fn dependency_resolution_short_deleted_reference_releases_only_its_waiters() {
6481 let (dir, q) = queue();
6482 let questions = Questions::at(dir.path().join("questions"));
6483 let mut dep = task("dependency");
6484 dep.id = "20261013-193611-ca5b".into();
6485 q.put(&mut dep).unwrap();
6486 let mut waiting = task("waiting");
6487 waiting.block(vec!["ca5b".into()], None);
6488 q.put(&mut waiting).unwrap();
6489 q.remove(&dep.id, false, &questions).unwrap();
6490 assert_eq!(q.get(&waiting.id).unwrap().status, TaskStatus::Queued);
6491 assert_eq!(
6492 dependency(&q, &questions, "ca5b"),
6493 Dependency::Deleted(dep.id)
6494 );
6495 }
6496
6497 #[test]
6498 fn dependency_resolution_preserves_cross_store_ambiguity_and_exact_ids() {
6499 let (dir, queue) = queue();
6500 let questions = Questions::at(dir.path().join("questions"));
6501 let mut dep = task("dependency");
6502 dep.id = "20261013-193611-ca5b".into();
6503 queue.put(&mut dep).unwrap();
6504 std::fs::create_dir_all(questions.root()).unwrap();
6505 let question_id = "20261014-193611-ca5b";
6506 std::fs::write(questions.path_of(question_id), "unreadable question").unwrap();
6507 assert_eq!(questions.resolve_id("ca5b").unwrap(), question_id);
6508 assert_eq!(
6509 dependency(&queue, &questions, "ca5b"),
6510 Dependency::Ambiguous
6511 );
6512 assert_eq!(
6513 dependency(&queue, &questions, &dep.id),
6514 Dependency::Task(dep.id)
6515 );
6516 assert_eq!(
6517 dependency(&queue, &questions, question_id),
6518 Dependency::Question(question_id.into())
6519 );
6520 assert_eq!(
6521 dependency(&queue, &questions, "missing"),
6522 Dependency::Missing
6523 );
6524 }
6525
6526 #[test]
6527 fn dependency_resolution_directory_errors_are_unknown_not_missing() {
6528 let dir = tempfile::tempdir().unwrap();
6529 let q = Queue::at(dir.path().join("not-a-directory"));
6530 std::fs::write(q.root(), "file").unwrap();
6531 let questions = Questions::at(dir.path().join("questions"));
6532 assert_eq!(dependency(&q, &questions, "ca5b"), Dependency::Unknown);
6533 assert!(missing_blockers(&q, &questions, &["ca5b".into()]).is_empty());
6534 }
6535
6536 #[test]
6537 fn a_dependency_without_a_tombstone_is_still_missing() {
6538 let (dir, q) = queue();
6539 let questions = Questions::at(dir.path().join("questions"));
6540 let mut dep = task("dependency");
6541 q.put(&mut dep).unwrap();
6542 std::fs::remove_file(q.path_of(&dep.id)).unwrap();
6543 assert_eq!(
6544 missing_blockers(&q, &questions, std::slice::from_ref(&dep.id)),
6545 [dep.id.clone()]
6546 );
6547 assert!(deleted_blockers(&q, &questions, std::slice::from_ref(&dep.id)).is_empty());
6548 }
6549
6550 #[test]
6551 fn a_held_dependent_is_left_alone_by_a_dependency_deletion() {
6552 let mut t = task("held");
6553 t.hold_machine(Some("because".to_owned()));
6554 t.blocked_by = vec!["gone".to_owned()];
6555 assert!(!t.dependency_deleted("gone"));
6556 assert_eq!(t.status, TaskStatus::Held);
6557 }
6558
6559 #[test]
6560 fn a_failed_record_removal_takes_the_tombstone_back() {
6561 let (_dir, q) = queue();
6562 let mut t = task("stays");
6563 q.put(&mut t).unwrap();
6564 q.write_tombstone(&t.id).unwrap();
6565 let err = q.remove_record_with_attachments(&t.id, |_| Err(std::io::Error::other("nope")));
6566 assert!(err.is_err());
6567 assert!(!q.was_deleted(&t.id));
6570 }
6571
6572 fn source_file(dir: &Path, name: &str, body: &str) -> PathBuf {
6573 let p = dir.join(name);
6574 std::fs::write(&p, body).unwrap();
6575 p
6576 }
6577
6578 #[test]
6579 fn an_attachment_copy_survives_deleting_its_source() {
6580 let (dir, q) = queue();
6581 let src = source_file(dir.path(), "shot.png", "pixels");
6582 let mut t = task("with a picture");
6583 let names = q.attach(&mut t, std::slice::from_ref(&src)).unwrap();
6584 q.put(&mut t).unwrap();
6585 std::fs::remove_file(&src).unwrap();
6586 assert_eq!(names, ["shot.png"]);
6587 let loaded = q.get(&t.id).unwrap();
6588 let paths = q.attachment_paths(&loaded);
6589 assert_eq!(paths.len(), 1);
6590 assert_eq!(std::fs::read_to_string(&paths[0]).unwrap(), "pixels");
6591 }
6592
6593 #[test]
6594 fn attachment_names_that_could_traverse_or_are_odd_are_refused() {
6595 let (dir, q) = queue();
6596 let mut t = task("bad names");
6597 for name in ["a..b.png", ".hidden", "with space.png", "-x.png"] {
6598 let src = source_file(dir.path(), name, "x");
6599 assert!(
6600 q.attach(&mut t, &[src]).is_err(),
6601 "`{name}` must be refused"
6602 );
6603 }
6604 assert!(!crate::ask::valid_asset_name("C:foo.png"));
6608 #[cfg(not(windows))]
6609 {
6610 let src = source_file(dir.path(), "C:foo.png", "x");
6611 assert!(q.attach(&mut t, &[src]).is_err());
6612 }
6613 let long = format!("{}.png", "a".repeat(70));
6614 let src = source_file(dir.path(), &long, "x");
6615 assert!(q.attach(&mut t, &[src]).is_err());
6616 assert!(t.attachments.is_empty());
6617 assert!(!q.attachments_dir(&t.id).exists());
6618 }
6619
6620 #[test]
6621 fn a_taken_attachment_name_is_numbered_not_overwritten() {
6622 let (dir, q) = queue();
6623 let a = source_file(dir.path(), "shot.png", "one");
6624 let sub = dir.path().join("other");
6625 std::fs::create_dir_all(&sub).unwrap();
6626 let b = source_file(&sub, "shot.png", "two");
6627 let mut t = task("collision");
6628 q.attach(&mut t, &[a]).unwrap();
6629 q.attach(&mut t, &[b]).unwrap();
6630 assert_eq!(t.attachments, ["shot.png", "shot-2.png"]);
6631 let paths = q.attachment_paths(&t);
6632 assert_eq!(std::fs::read_to_string(&paths[0]).unwrap(), "one");
6633 assert_eq!(std::fs::read_to_string(&paths[1]).unwrap(), "two");
6634 }
6635
6636 #[test]
6637 fn a_renumbered_name_stays_inside_the_length_bound() {
6638 let (dir, q) = queue();
6639 let name = format!("{}.png", "a".repeat(60));
6640 assert_eq!(name.len(), 64);
6641 let a = source_file(dir.path(), &name, "one");
6642 let sub = dir.path().join("other");
6643 std::fs::create_dir_all(&sub).unwrap();
6644 let b = source_file(&sub, &name, "two");
6645 let mut t = task("long");
6646 q.attach(&mut t, &[a, b]).unwrap();
6647 assert_eq!(t.attachments.len(), 2);
6648 assert!(
6649 t.attachments
6650 .iter()
6651 .all(|n| crate::ask::valid_asset_name(n))
6652 );
6653 assert!(t.attachments[1].ends_with("-2.png"));
6654 }
6655
6656 #[test]
6657 fn a_failed_attach_keeps_existing_attachments_and_leaves_no_partial_copy() {
6658 let (dir, q) = queue();
6659 let good = source_file(dir.path(), "good.png", "ok");
6660 let mut t = task("partial");
6661 q.attach(&mut t, &[good]).unwrap();
6662 let more = source_file(dir.path(), "more.png", "ok");
6663 let missing = dir.path().join("missing.png");
6664 assert!(q.attach(&mut t, &[more, missing]).is_err());
6665 assert_eq!(t.attachments, ["good.png"]);
6666 let on_disk: Vec<_> = std::fs::read_dir(q.attachments_dir(&t.id))
6667 .unwrap()
6668 .flatten()
6669 .collect();
6670 assert_eq!(on_disk.len(), 1);
6671 }
6672
6673 fn block_put(q: &Queue, t: &Task) -> PathBuf {
6675 let tmp = q.path_of(&t.id).with_extension("json.tmp");
6676 std::fs::create_dir_all(&tmp).unwrap();
6677 tmp
6678 }
6679
6680 #[test]
6681 fn a_failed_put_leaves_no_new_attachment_directory() {
6682 let (dir, q) = queue();
6683 let mut t = task("fresh");
6684 let tmp = block_put(&q, &t);
6685 let src = source_file(dir.path(), "shot.png", "x");
6686 assert!(q.attach_and_put(&mut t, &[src]).is_err());
6687 assert!(t.attachments.is_empty());
6688 assert!(!q.attachments_dir(&t.id).exists());
6689 assert!(!q.path_of(&t.id).exists());
6690 std::fs::remove_dir(tmp).unwrap();
6691 }
6692
6693 #[test]
6694 fn a_failed_put_removes_only_the_copy_it_just_made() {
6695 let (dir, q) = queue();
6696 let mut t = task("edited");
6697 let first = source_file(dir.path(), "first.png", "1");
6698 q.attach_and_put(&mut t, &[first]).unwrap();
6699 block_put(&q, &t);
6700 let second = source_file(dir.path(), "second.png", "2");
6701 assert!(q.attach_and_put(&mut t, &[second]).is_err());
6702 assert_eq!(t.attachments, ["first.png"]);
6703 let on_disk: Vec<_> = std::fs::read_dir(q.attachments_dir(&t.id))
6704 .unwrap()
6705 .flatten()
6706 .map(|e| e.file_name().to_string_lossy().into_owned())
6707 .collect();
6708 assert_eq!(on_disk, ["first.png"]);
6709 assert_eq!(q.get(&t.id).unwrap().attachments, ["first.png"]);
6710 }
6711
6712 #[test]
6713 fn a_leftover_removing_directory_is_swept_by_the_next_removal() {
6714 let (dir, q) = queue();
6715 let questions = Questions::at(dir.path().join("questions"));
6716 let gone = task("gone");
6717 let mut other = task("other");
6718 let mut live = task("live");
6719 q.put(&mut other).unwrap();
6720 q.put(&mut live).unwrap();
6721 let orphan = q.root.join(format!("{}.attachments.removing", gone.id));
6724 std::fs::create_dir_all(&orphan).unwrap();
6725 std::fs::write(orphan.join("shot.png"), "x").unwrap();
6726 let busy = q.root.join(format!("{}.attachments.removing", live.id));
6729 std::fs::create_dir_all(&busy).unwrap();
6730
6731 q.remove(&other.id, false, &questions).unwrap();
6732 assert!(!orphan.exists(), "an orphan is swept");
6733 assert!(busy.exists(), "a removal in progress is left alone");
6734 }
6735
6736 #[test]
6737 fn a_blocked_aside_rename_fails_the_removal_and_loses_nothing() {
6738 let (dir, q) = queue();
6739 let questions = Questions::at(dir.path().join("questions"));
6740 let mut t = task("stuck");
6741 let src = source_file(dir.path(), "shot.png", "x");
6742 q.attach_and_put(&mut t, &[src]).unwrap();
6743 let aside = q.root.join(format!("{}.attachments.removing", t.id));
6746 std::fs::create_dir_all(&aside).unwrap();
6747 std::fs::write(aside.join("old.png"), "o").unwrap();
6748 assert!(q.remove(&t.id, false, &questions).is_err());
6749 assert!(q.path_of(&t.id).exists());
6750 assert!(q.attachments_dir(&t.id).join("shot.png").is_file());
6751 }
6752
6753 #[test]
6754 fn a_failed_record_removal_puts_the_attachments_back() {
6755 let (dir, q) = queue();
6756 let mut t = task("rollback");
6757 let src = source_file(dir.path(), "shot.png", "x");
6758 q.attach_and_put(&mut t, &[src]).unwrap();
6759 let err = q
6760 .remove_record_with_attachments(&t.id, |_| {
6761 Err(std::io::Error::other("injected failure"))
6762 })
6763 .unwrap_err();
6764 assert!(format!("{err:#}").contains("injected failure"));
6765 assert!(q.path_of(&t.id).exists());
6766 assert!(q.attachments_dir(&t.id).join("shot.png").is_file());
6767 assert!(
6768 !q.root
6769 .join(format!("{}.attachments.removing", t.id))
6770 .exists()
6771 );
6772 }
6773
6774 #[test]
6775 fn editing_a_task_keeps_its_attachments() {
6776 let (dir, q) = queue();
6777 let src = source_file(dir.path(), "shot.png", "x");
6778 let mut t = task("editable");
6779 q.attach(&mut t, &[src]).unwrap();
6780 t.edit("new".to_owned(), "new text".to_owned()).unwrap();
6781 q.put(&mut t).unwrap();
6782 assert_eq!(q.get(&t.id).unwrap().attachments, ["shot.png"]);
6783 }
6784
6785 #[test]
6786 fn removing_a_task_deletes_its_attachments() {
6787 let (dir, q) = queue();
6788 let questions = Questions::at(dir.path().join("questions"));
6789 let src = source_file(dir.path(), "shot.png", "x");
6790 let mut t = task("doomed");
6791 q.attach(&mut t, &[src]).unwrap();
6792 q.put(&mut t).unwrap();
6793 assert!(q.attachments_dir(&t.id).is_dir());
6794 q.remove(&t.id, false, &questions).unwrap();
6795 assert!(!q.attachments_dir(&t.id).exists());
6796 assert!(q.list().is_empty());
6797 }
6798
6799 #[test]
6800 fn a_task_written_before_attachments_still_reads() {
6801 let (_dir, q) = queue();
6802 let mut t = task("old");
6803 q.put(&mut t).unwrap();
6804 let path = q.path_of(&t.id);
6805 let mut v: serde_json::Value =
6806 serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
6807 v.as_object_mut().unwrap().remove("attachments");
6808 std::fs::write(&path, v.to_string()).unwrap();
6809 assert!(q.get(&t.id).unwrap().attachments.is_empty());
6810 }
6811
6812 #[test]
6813 fn attachment_paths_are_absolute_even_when_the_root_is_relative() {
6814 let q = Queue::at(PathBuf::from("relative-queue"));
6815 let mut t = task("rel");
6816 t.attachments.push("shot.png".to_owned());
6817 let paths = q.attachment_paths(&t);
6818 assert!(paths[0].is_absolute(), "{}", paths[0].display());
6819 assert!(paths[0].ends_with(format!("{}.attachments/shot.png", t.id)));
6820 }
6821
6822 fn upgrade_parked(id: &str, started: &str) -> Task {
6823 let mut t = task(id);
6824 t.id = id.into();
6825 t.start(format!("run-{id}"));
6826 t.park("upgrade");
6827 t.record_pass_at(
6828 &format!("run-{id}"),
6829 0,
6830 Some(started.parse().unwrap()),
6831 1,
6832 Some(crate::run::ParkCause::Upgrade {
6833 from: "old".into(),
6834 to: None,
6835 }),
6836 );
6837 t
6838 }
6839
6840 #[test]
6841 fn upgrade_resume_order_follows_dispatch_claim_not_graph_start() {
6842 let stamp = |id: &str, dispatched: &str, started: &str| {
6844 let mut t = task(id);
6845 t.id = id.into();
6846 t.start(format!("run-{id}"));
6847 t.park("upgrade");
6848 t.dispatched_at = Some(dispatched.parse().unwrap());
6849 t.record_pass_at(
6850 &format!("run-{id}"),
6851 0,
6852 Some(started.parse().unwrap()),
6853 1,
6854 Some(crate::run::ParkCause::Upgrade {
6855 from: "old".into(),
6856 to: None,
6857 }),
6858 );
6859 t
6860 };
6861 let a = stamp("a", "2026-10-22T00:00:01Z", "2026-10-22T00:00:09Z");
6862 let b = stamp("b", "2026-10-22T00:00:02Z", "2026-10-22T00:00:03Z");
6863 assert!(dispatch_order(&a, &b).is_lt());
6864 }
6865
6866 #[test]
6867 fn upgrade_resume_order_survives_queue_reload_and_reversed_settlement() {
6868 let (_dir, q) = queue();
6869 let mut later = upgrade_parked("later", "2026-10-22T00:00:02Z");
6870 let mut earlier = upgrade_parked("earlier", "2026-10-22T00:00:01Z");
6871 earlier.priority = -10;
6872 let mut fresh = task("fresh");
6873 fresh.id = "newer".into();
6874 fresh.priority = 100;
6875 for t in [&mut fresh, &mut later, &mut earlier] {
6876 q.put(t).unwrap();
6877 }
6878 let reloaded = Queue::at(q.root().to_owned());
6879 let mut tasks = reloaded.list();
6880 tasks.sort_unstable_by(dispatch_order);
6881 assert_eq!(
6882 tasks.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
6883 vec!["earlier", "later", "newer"]
6884 );
6885 assert_eq!(reloaded.next_runnable().unwrap().id, "earlier");
6886 assert_eq!(reloaded.get("earlier").unwrap().attempts, 0);
6887 }
6888
6889 #[test]
6890 fn upgrade_resume_legacy_order_uses_settlement_and_id() {
6891 let mut a = upgrade_parked("a", "2026-10-22T00:00:02Z");
6892 let mut b = upgrade_parked("b", "2026-10-22T00:00:01Z");
6893 for t in [&mut a, &mut b] {
6894 let mut value = serde_json::to_value(&*t).unwrap();
6895 value["passes"][0]
6896 .as_object_mut()
6897 .unwrap()
6898 .remove("started_at");
6899 *t = serde_json::from_value(value).unwrap();
6900 }
6901 assert!(dispatch_order(&a, &b).is_lt());
6902 b.passes[0].settled_at = a.passes[0].settled_at;
6903 assert!(dispatch_order(&a, &b).is_lt());
6904 }
6905
6906 #[test]
6907 fn upgrade_resume_key_excludes_other_parks_and_explicit_task_changes() {
6908 let original = upgrade_parked("a", "2026-10-22T00:00:01Z");
6909 assert!(original.upgrade_resume_key().is_some());
6910 for cause in [
6911 crate::run::ParkCause::Operator,
6912 crate::run::ParkCause::Question,
6913 crate::run::ParkCause::Interrupt {
6914 reason: "interrupt".into(),
6915 },
6916 crate::run::ParkCause::Unspecified,
6917 ] {
6918 let mut t = original.clone();
6919 t.passes[0].parked = Some(cause);
6920 assert!(t.upgrade_resume_key().is_none());
6921 let mut fresh = task("fresh");
6922 fresh.priority = 1;
6923 assert!(dispatch_order(&fresh, &t).is_lt());
6924 }
6925 let mut t = original.clone();
6926 t.release();
6927 assert!(t.upgrade_resume_key().is_none());
6928 t.edit("edited".into(), "new instruction".into()).unwrap();
6929 assert!(t.upgrade_resume_key().is_none());
6930 let mut t = original.clone();
6931 t.requeue();
6932 t.status = TaskStatus::Parked;
6933 assert!(t.upgrade_resume_key().is_none());
6934 let mut t = original.clone();
6935 t.start("different-run".into());
6936 t.park("no upgrade");
6937 assert!(t.upgrade_resume_key().is_none());
6938 }
6939
6940 #[test]
6941 fn explicitly_resumed_older_run_becomes_current_without_duplicate_history() {
6942 let dir = tempfile::tempdir().unwrap();
6943 let q = Queue::at(dir.path().join("queue"));
6944 let mut t = task("resume");
6945 t.start("A".into());
6946 t.record_pass("A", 0, 1, None);
6947 t.start("B".into());
6948 q.put(&mut t).unwrap();
6949 assert_eq!(t.runs, vec!["A", "B"]);
6950 t.start("A".into());
6951 t.record_pass("A", 1, 3, None);
6952 q.put(&mut t).unwrap();
6953 let saved = q.get(&t.id).unwrap();
6954 assert_eq!(saved.runs, vec!["B", "A"]);
6955 assert_eq!(saved.runs.last().map(String::as_str), Some("A"));
6956 assert_eq!(saved.attempts, 3);
6957 assert_eq!(saved.passes.len(), 2);
6958 assert_eq!(saved.passes[0].run, "A");
6959 assert_eq!(saved.passes[1].run, "A");
6960 }
6961
6962 #[test]
6963 fn repeated_start_records_one_run_and_separate_passes() {
6964 let mut t = task("resume");
6965 t.start("same-run".into());
6966 t.record_pass("same-run", 0, 1, None);
6967 t.start("same-run".into());
6968 t.record_pass("same-run", 1, 2, None);
6969 assert_eq!(t.runs, vec!["same-run"]);
6970 assert_eq!(t.attempts, 2);
6971 assert_eq!(t.passes.len(), 2);
6972 }
6973
6974 #[test]
6975 fn link_run_adds_a_run_once_and_touches_nothing_else() {
6976 let dir = tempfile::tempdir().unwrap();
6977 let queue = Queue::at(dir.path().join("queue"));
6978 let mut t = Task::new(
6979 "t".to_owned(),
6980 "do it".to_owned(),
6981 PathBuf::from("."),
6982 Source::Human,
6983 );
6984 queue.put(&mut t).unwrap();
6985 let before = queue.get(&t.id).unwrap();
6986
6987 let linked = queue.link_run(&t.id[..4], "20260930-092817-ec34").unwrap();
6988 assert_eq!(linked.runs, vec!["20260930-092817-ec34".to_owned()]);
6989 assert_eq!(linked.status, before.status);
6990 assert_eq!(linked.attempts, before.attempts);
6991 assert_eq!(linked.interrupt, before.interrupt);
6992
6993 let again = queue.link_run(&t.id, "20260930-092817-ec34").unwrap();
6994 assert_eq!(again.runs.len(), 1, "linking twice must not duplicate");
6995 assert_eq!(queue.get(&t.id).unwrap().runs.len(), 1);
6996 assert!(queue.link_run("no-such-task", "r").is_err());
6997 }
6998
6999 #[test]
7000 fn put_keeps_a_run_linked_after_the_writer_took_its_snapshot() {
7001 let dir = tempfile::tempdir().unwrap();
7002 let queue = Queue::at(dir.path().join("queue"));
7003 let mut t = Task::new(
7004 "t".to_owned(),
7005 "do it".to_owned(),
7006 PathBuf::from("."),
7007 Source::Human,
7008 );
7009 queue.put(&mut t).unwrap();
7010 let mut snapshot = queue.get(&t.id).unwrap();
7012 queue.link_run(&t.id, "20260930-092817-ec34").unwrap();
7013
7014 snapshot.start("20260930-000000-aaaa".to_owned());
7015 queue.put(&mut snapshot).unwrap();
7016
7017 let stored = queue.get(&t.id).unwrap();
7018 assert!(stored.runs.contains(&"20260930-092817-ec34".to_owned()));
7019 assert!(stored.runs.contains(&"20260930-000000-aaaa".to_owned()));
7020 assert_eq!(stored.attempts, 1);
7021 }
7022
7023 #[test]
7024 fn concurrent_links_and_daemon_saves_lose_nothing() {
7025 let dir = tempfile::tempdir().unwrap();
7026 let queue = Queue::at(dir.path().join("queue"));
7027 let mut t = Task::new(
7028 "t".to_owned(),
7029 "do it".to_owned(),
7030 PathBuf::from("."),
7031 Source::Human,
7032 );
7033 queue.put(&mut t).unwrap();
7034 let id = t.id.clone();
7035
7036 let linkers: Vec<_> = (0..4)
7037 .map(|n| {
7038 let (queue, id) = (queue.clone(), id.clone());
7039 std::thread::spawn(move || {
7040 for k in 0..10 {
7041 queue
7042 .link_run(&id, &format!("20260930-00000{n}-l{k:03}"))
7043 .unwrap();
7044 }
7045 })
7046 })
7047 .collect();
7048 let mut mine = queue.get(&id).unwrap();
7051 for k in 0..10 {
7052 mine.start(format!("20260930-000009-d{k:03}"));
7053 queue.put(&mut mine).unwrap();
7054 }
7055 for l in linkers {
7056 l.join().unwrap();
7057 }
7058
7059 let stored = queue.get(&id).unwrap();
7060 assert_eq!(stored.runs.len(), 50, "{:?}", stored.runs);
7061 assert_eq!(
7062 stored.attempts, 10,
7063 "linking never rewinds the daemon's work"
7064 );
7065 }
7066
7067 fn age_lock(path: &Path) {
7068 let f = std::fs::OpenOptions::new().write(true).open(path).unwrap();
7069 f.set_modified(std::time::SystemTime::now() - std::time::Duration::from_secs(60))
7070 .unwrap();
7071 }
7072
7073 #[test]
7074 fn concurrent_stale_takeover_yields_one_holder() {
7075 use std::sync::atomic::{AtomicUsize, Ordering};
7076 use std::sync::{Arc, Barrier};
7077 for _ in 0..5 {
7078 let dir = tempfile::tempdir().unwrap();
7079 let q = Queue::at(dir.path().to_path_buf());
7080 let lock = dir.path().join("t.write-lock");
7081 std::fs::write(&lock, "dead-0000").unwrap();
7082 age_lock(&lock);
7083 let n = 6;
7084 let barrier = Arc::new(Barrier::new(n));
7085 let (now, max) = (Arc::new(AtomicUsize::new(0)), Arc::new(AtomicUsize::new(0)));
7086 let handles: Vec<_> = (0..n)
7087 .map(|_| {
7088 let (q, b, now, max) = (q.clone(), barrier.clone(), now.clone(), max.clone());
7089 std::thread::spawn(move || {
7090 b.wait();
7091 let g = q.lock_task("t").unwrap();
7092 let held = now.fetch_add(1, Ordering::SeqCst) + 1;
7093 max.fetch_max(held, Ordering::SeqCst);
7094 std::thread::sleep(std::time::Duration::from_millis(20));
7095 now.fetch_sub(1, Ordering::SeqCst);
7096 drop(g);
7097 })
7098 })
7099 .collect();
7100 for h in handles {
7101 h.join().unwrap();
7102 }
7103 assert_eq!(max.load(Ordering::SeqCst), 1);
7104 assert!(!lock.exists());
7105 }
7106 }
7107
7108 #[test]
7109 fn dropping_a_replaced_lock_leaves_the_new_holders_token() {
7110 let dir = tempfile::tempdir().unwrap();
7111 let q = Queue::at(dir.path().to_path_buf());
7112 let lock = dir.path().join("t.write-lock");
7113 let a = q.lock_task("t").unwrap();
7114 let replacement = owner_token();
7117 std::fs::write(&lock, &replacement).unwrap();
7118 drop(a);
7119 assert_eq!(std::fs::read_to_string(&lock).unwrap(), replacement);
7120 }
7121
7122 #[test]
7123 fn aged_live_task_lock_excludes_updates_until_retirement_releases_it() {
7124 let dir = tempfile::tempdir().unwrap();
7125 let q = Queue::at(dir.path().to_path_buf());
7126 let held = q.lock_task("t").unwrap();
7127 let path = dir.path().join("t.write-lock");
7128 age_lock(&path);
7129 assert!(!break_stale(&path, &held.token));
7130 let (started_tx, started_rx) = std::sync::mpsc::channel();
7131 let (acquired_tx, acquired_rx) = std::sync::mpsc::channel();
7132 let updater = std::thread::spawn(move || {
7133 started_tx.send(()).unwrap();
7134 let _write = q.lock_task("t").unwrap();
7135 acquired_tx.send(()).unwrap();
7136 });
7137 started_rx.recv().unwrap();
7138 assert!(
7139 acquired_rx
7140 .recv_timeout(std::time::Duration::from_millis(100))
7141 .is_err()
7142 );
7143 assert_eq!(std::fs::read_to_string(&path).unwrap(), held.token);
7144 drop(held);
7145 acquired_rx
7146 .recv_timeout(std::time::Duration::from_secs(2))
7147 .unwrap();
7148 updater.join().unwrap();
7149 assert!(!path.exists());
7150 }
7151
7152 #[test]
7153 fn break_stale_leaves_a_lock_that_replaced_the_one_judged() {
7154 let dir = tempfile::tempdir().unwrap();
7155 let lock = dir.path().join("t.write-lock");
7156 std::fs::write(&lock, "new-token").unwrap();
7157 assert!(!break_stale(&lock, "old-token"));
7158 assert_eq!(std::fs::read_to_string(&lock).unwrap(), "new-token");
7159 assert!(!break_stale(&lock, "new-token"));
7161 assert!(lock.exists());
7162 age_lock(&lock);
7163 assert!(break_stale(&lock, "new-token"));
7164 assert!(!lock.exists());
7165 }
7166
7167 #[test]
7168 fn a_stale_break_marker_is_recovered_and_a_fresh_one_is_respected() {
7169 let dir = tempfile::tempdir().unwrap();
7170 let lock = dir.path().join("t.write-lock");
7171 std::fs::write(&lock, "dead-1").unwrap();
7172 age_lock(&lock);
7173 let marker = break_marker(&lock, "dead-1");
7174 std::fs::write(&marker, "crashed-remover").unwrap();
7175 assert!(!break_stale(&lock, "dead-1"));
7177 assert!(lock.exists());
7178 age_lock(&marker);
7180 assert!(break_stale(&lock, "dead-1"));
7181 assert!(!lock.exists());
7182 assert!(!marker.exists());
7183 }
7184
7185 fn chat_task() -> Task {
7186 Task::new(
7187 "t".to_owned(),
7188 "do t".to_owned(),
7189 PathBuf::from("."),
7190 Source::Agent {
7191 run: "20260902-000000-beef".to_owned(),
7192 node: CHAT_NODE.to_owned(),
7193 },
7194 )
7195 }
7196
7197 #[test]
7198 fn a_blocked_hold_keeps_its_anchor_but_a_new_run_starts_a_new_hold() {
7199 let mut t = chat_task();
7200 t.hold_machine(Some("waiting".into()));
7201 let old: Timestamp = "2020-01-01T00:00:00Z".parse().unwrap();
7202 t.held_at = Some(old);
7203 t.block(vec!["decision".into()], None);
7204 t.hold_machine(Some("same waiting decision".into()));
7205 assert_eq!(t.held_at, Some(old));
7206 t.start("real-new-run".into());
7207 t.fail("new failure", 1);
7208 assert_ne!(
7209 t.held_at,
7210 Some(old),
7211 "old answers cannot approve a new hold"
7212 );
7213 }
7214
7215 #[test]
7216 fn legacy_delivery_survives_upgrade_and_a_no_progress_run_link() {
7217 let (_dir, queue) = queue();
7218 let mut t = chat_task();
7219 t.start("old-run".into());
7220 t.hold_machine(Some("operator is considering recovery".into()));
7221 t.chat_notice = Some(ChatNotice {
7222 key: format!("held#{}", t.held_at.unwrap()),
7223 at: Timestamp::now(),
7224 outcome: ChatNoticeOutcome::Posted,
7225 });
7226 let mut raw = serde_json::to_value(&t).unwrap();
7227 raw.as_object_mut().unwrap().remove("chat_notices");
7228 raw.as_object_mut().unwrap().remove("hold_notice_cause");
7229 std::fs::create_dir_all(queue.path_of(&t.id).parent().unwrap()).unwrap();
7230 std::fs::write(queue.path_of(&t.id), serde_json::to_string(&raw).unwrap()).unwrap();
7231 assert_eq!(queue.get(&t.id).unwrap().chat_notice_due(), None);
7232 queue
7233 .modify(&t.id, |task| {
7234 task.requeue();
7235 task.link_run("unprepared-run");
7236 task.startup_notice_cause("startup-source");
7237 task.fail("same unresolved preflight", 0);
7238 true
7239 })
7240 .unwrap();
7241 assert_eq!(queue.get(&t.id).unwrap().chat_notice_due(), None);
7242 queue
7243 .modify(&t.id, |task| {
7244 task.succeed(completion(task));
7245 true
7246 })
7247 .unwrap();
7248 assert!(
7249 queue
7250 .get(&t.id)
7251 .unwrap()
7252 .chat_notice_due()
7253 .unwrap()
7254 .starts_with("done:")
7255 );
7256 }
7257
7258 #[test]
7259 fn a_dependency_wait_does_not_change_when_released_and_blocked_again() {
7260 let mut t = chat_task();
7261 t.block(vec!["a".into(), "b".into()], Some("waiting".into()));
7262 let key = t.chat_notice_key().unwrap();
7263 t.chat_notices.push(key);
7264 t.release();
7265 t.block(
7266 vec!["b".into(), "a".into(), "a".into()],
7267 Some("still waiting on prerequisites".into()),
7268 );
7269 assert_eq!(t.chat_notice_due(), None);
7270 t.block(
7271 vec!["new-question".into()],
7272 Some("different decision".into()),
7273 );
7274 assert!(t.chat_notice_due().is_some());
7275 }
7276
7277 #[test]
7278 fn running_startup_failures_preserve_stage_and_report_distinct_blockers() {
7279 let mut t = chat_task();
7280 t.start("existing-run".into());
7281 t.fail("implementation failed", 1);
7282 let failed = t.chat_notice_key().unwrap();
7283 t.chat_notices.push(failed.clone());
7284 t.release_operator("test", None);
7285 t.start("existing-run".into());
7286 t.fail_startup("startup-source", "same unresolved recovery source", 1);
7287 assert_eq!(
7288 t.chat_notice_due(),
7289 None,
7290 "no-progress recovery stays quiet"
7291 );
7292 t.release_operator("test", None);
7293 t.start("existing-run".into());
7294 t.fail_startup("startup-attachments", "attachment missing", 1);
7295 let attachments = t.chat_notice_due().expect("new attachment blocker");
7296 assert_ne!(attachments, failed);
7297 assert_eq!(
7298 t.hold_notice_cause.as_ref().unwrap().stage,
7299 "startup-attachments"
7300 );
7301 t.chat_notices.push(attachments);
7302 t.release_operator("test", None);
7303 t.start("existing-run".into());
7304 t.fail_startup(
7305 "startup-attachments",
7306 "same missing attachment, reworded",
7307 1,
7308 );
7309 assert_eq!(
7310 t.chat_notice_due(),
7311 None,
7312 "same stage after attempt counter reset"
7313 );
7314 t.release_operator("test", None);
7315 t.start("existing-run".into());
7316 t.fail_startup("startup-config", "different preflight stage", 1);
7317 assert!(t.chat_notice_due().is_some());
7318 assert_eq!(
7319 t.hold_notice_cause.as_ref().unwrap().stage,
7320 "startup-config"
7321 );
7322 }
7323
7324 #[test]
7325 fn structured_causes_preserve_no_progress_retries_and_report_new_passes() {
7326 let mut t = chat_task();
7327 t.hold_machine(Some("startup source missing".into()));
7328 t.startup_notice_cause("startup-source");
7329 let first = t.chat_notice_key().unwrap();
7330 t.chat_notices.push(first.clone());
7331 t.release_operator("test", None);
7332 t.startup_notice_cause("startup-source");
7333 t.hold_machine(Some("same source cannot be read".into()));
7334 assert_eq!(t.chat_notice_due(), None);
7335 t.startup_notice_cause("startup-config");
7336 assert!(t.chat_notice_due().is_some(), "different startup stage");
7337 t.notice_cause("failed", Some("existing-run"), Some(0));
7338 let run_failure = t.chat_notice_key().unwrap();
7339 t.chat_notices.push(run_failure.clone());
7340 t.release_operator("test", None);
7341 t.startup_notice_cause("startup-source");
7342 t.hold_machine(Some("no new work happened".into()));
7343 assert_eq!(t.chat_notice_due(), None);
7344 t.notice_cause("failed", Some("existing-run"), Some(1));
7345 assert!(t.chat_notice_due().is_some(), "a real resumed pass failed");
7346 assert_ne!(t.chat_notice_key().unwrap(), run_failure);
7347 }
7348
7349 #[test]
7350 fn legacy_hold_baseline_does_not_replay_or_hide_new_failures_and_completion() {
7351 let mut t = chat_task();
7352 t.hold_machine(Some("still waiting".into()));
7353 t.chat_notice = Some(ChatNotice {
7354 key: "held#2026-10-14T00:00:00Z".into(),
7355 at: Timestamp::now(),
7356 outcome: ChatNoticeOutcome::Posted,
7357 });
7358 assert_eq!(t.chat_notice_due(), None, "old hold baseline");
7359 t.import_chat_notice();
7360 t.notice_cause("failed", Some("new-run"), Some(0));
7361 assert!(t.chat_notice_due().is_some(), "new producer evidence");
7362 t.succeed(completion(&t));
7363 assert!(t.chat_notice_due().unwrap().starts_with("done:"));
7364 }
7365
7366 #[test]
7367 fn a_chat_notice_is_due_only_for_a_final_state_and_only_once() {
7368 let mut t = chat_task();
7369 assert_eq!(t.chat_notice_due(), None, "queued");
7370 t.start("r1".to_owned());
7371 assert_eq!(t.chat_notice_due(), None, "running");
7372 t.fail("boom", 3);
7373 assert_eq!(t.status, TaskStatus::Failed);
7374 assert_eq!(t.chat_notice_due(), None, "a retried failure is not final");
7375 t.start("r2".to_owned());
7376 t.park("upgrade");
7377 assert_eq!(t.chat_notice_due(), None, "parked");
7378 t.fail("boom", 1);
7379 assert_eq!(t.status, TaskStatus::Held);
7380 let key = t
7381 .chat_notice_due()
7382 .expect("held on the last attempt is final");
7383 t.chat_notice = Some(ChatNotice {
7384 key,
7385 at: Timestamp::now(),
7386 outcome: ChatNoticeOutcome::Posted,
7387 });
7388 assert_eq!(t.chat_notice_due(), None, "same hold, no second notice");
7389 t.release();
7390 assert_eq!(t.chat_notice_due(), None, "requeued after a release");
7391 t.start("r3".to_owned());
7392 t.succeed(completion(&t));
7393 assert!(t.chat_notice_due().is_some(), "done is a new final state");
7394 }
7395
7396 #[test]
7397 fn legacy_completion_receipts_do_not_suppress_new_occurrences() {
7398 for key in ["done", "done#0", "done#1", "done#12"] {
7399 let mut t = chat_task();
7400 t.status = TaskStatus::Done;
7401 t.chat_notice = Some(ChatNotice {
7402 key: key.to_owned(),
7403 at: Timestamp::now(),
7404 outcome: ChatNoticeOutcome::Posted,
7405 });
7406 assert_eq!(t.chat_notice_key().as_deref(), Some("done"));
7407 assert_eq!(t.chat_notice_due(), None, "legacy recorded key: {key}");
7408 let mut context = completion(&t);
7409 context.reason = Some("inspect again".into());
7410 t.reopen(context).unwrap();
7411 t.start("r2".to_owned());
7412 t.succeed(completion(&t));
7413 assert!(t.chat_notice_key().unwrap().starts_with("done:"));
7414 assert!(
7415 t.chat_notice_due().is_some(),
7416 "new occurrence, old receipt: {key}"
7417 );
7418 }
7419 }
7420
7421 #[test]
7422 fn a_release_without_progress_keeps_the_unresolved_notice_cause() {
7423 let mut t = chat_task();
7424 t.hold_manual(Some("wait".to_owned()));
7425 let first = t.chat_notice_due().expect("held");
7426 t.chat_notice = Some(ChatNotice {
7427 key: first.clone(),
7428 at: Timestamp::now(),
7429 outcome: ChatNoticeOutcome::Posted,
7430 });
7431 t.hold_manual(Some("still waiting".to_owned()));
7432 assert_eq!(t.chat_notice_due(), None, "a re-hold keeps its start");
7433 t.release();
7434 std::thread::sleep(std::time::Duration::from_millis(5));
7435 t.hold_manual(None);
7436 assert_eq!(t.chat_notice_due(), None, "no progress, same cause");
7437 }
7438
7439 #[test]
7440 fn a_chat_notice_needs_a_chat_source_and_a_current_schema() {
7441 let mut human = task("h");
7442 human.succeed(completion(&human));
7443 assert_eq!(human.chat_notice_due(), None);
7444 let mut inherited = task("i");
7446 inherited.origin_chat = Some("20260902-000000-beef".to_owned());
7447 inherited.succeed(completion(&inherited));
7448 assert_eq!(inherited.chat_notice_due(), None);
7449 let mut old = chat_task();
7450 old.schema = 12;
7451 old.status = TaskStatus::Done;
7452 assert_eq!(old.chat_notice_due(), None, "history is not replayed");
7453 let mut live = chat_task();
7454 live.schema = 12;
7455 live.start("r1".to_owned());
7456 live.succeed(completion(&live));
7457 assert!(live.chat_notice_due().is_some(), "started by this build");
7458 let mut held = chat_task();
7459 held.schema = 12;
7460 held.hold_machine(Some("config".to_owned()));
7461 assert!(held.chat_notice_due().is_some(), "held before any start");
7462 }
7463
7464 #[test]
7465 fn a_stale_snapshot_does_not_rewind_a_recorded_chat_notice() {
7466 let tmp = tempfile::tempdir().expect("tempdir");
7467 let q = Queue::at(tmp.path().join("queue"));
7468 let mut t = chat_task();
7469 t.succeed(completion(&t));
7470 q.put(&mut t).expect("put");
7471 let mut stale = q.get(&t.id).expect("get");
7472 let key = t.chat_notice_due().expect("due");
7473 q.modify(&t.id, |x| {
7474 x.chat_notice = Some(ChatNotice {
7475 key: key.clone(),
7476 at: Timestamp::now(),
7477 outcome: ChatNoticeOutcome::Posted,
7478 });
7479 true
7480 })
7481 .expect("modify");
7482 q.put(&mut stale).expect("stale put");
7483 assert_eq!(q.get(&t.id).expect("get").chat_notice_due(), None);
7484 }
7485
7486 #[test]
7487 fn empty_sources_are_omitted_so_older_builds_still_read_the_task() {
7488 let mut t = task("plain");
7491 let value = serde_json::to_value(&t).unwrap();
7492 assert!(value.get("sources").is_none(), "{value}");
7493 t.sources.pick_commits.push(crate::refs::Input {
7494 token: "abc1234".into(),
7495 sha: "a".repeat(40),
7496 provenance: crate::refs::Provenance::ExplicitCli,
7497 });
7498 let value = serde_json::to_value(&t).unwrap();
7499 assert_eq!(value["sources"]["pick_commits"][0]["sha"], "a".repeat(40));
7500 let restored: Task = serde_json::from_value(value).unwrap();
7501 assert_eq!(restored.sources, t.sources);
7502 }
7503
7504 fn queue_with_ids(dir: &Path, ids: &[&str]) -> Queue {
7506 let ids: Vec<String> = ids.iter().map(|s| (*s).to_owned()).collect();
7507 let n = std::sync::atomic::AtomicUsize::new(0);
7508 Queue::at(dir.join("queue")).with_id_source(move || {
7509 let i = n.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
7510 ids.get(i)
7511 .cloned()
7512 .unwrap_or_else(|| format!("20260101-000000-f{i:03x}"))
7513 })
7514 }
7515
7516 const TAKEN: &str = "20260101-000000-aaaa";
7517
7518 #[test]
7519 fn a_new_task_never_merges_into_a_record_with_its_candidate_id() {
7520 let dir = tempfile::tempdir().unwrap();
7521 let q = queue_with_ids(dir.path(), &[TAKEN, TAKEN]);
7522 let mut first = task("first");
7523 first.start("run-1".into());
7524 first.succeed(completion(&first));
7525 q.put(&mut first).unwrap();
7526 assert_eq!(first.id, TAKEN);
7527 let stored_before = q.get(&first.id).unwrap();
7528 assert!(!stored_before.runs.is_empty());
7529
7530 let mut second = task("second");
7531 q.put(&mut second).unwrap();
7532
7533 assert_ne!(second.id, first.id);
7534 assert!(second.runs.is_empty());
7535 assert!(second.passes.is_empty());
7536 assert!(second.chat_notices.is_empty());
7537 assert!(second.chat_notice.is_none());
7538 assert_eq!(second.chat_notice_due(), task("fresh").chat_notice_due());
7539 let a = q.get(&first.id).unwrap();
7540 let b = q.get(&second.id).unwrap();
7541 assert_eq!(a.title, "first");
7542 assert_eq!(a.runs, stored_before.runs);
7543 assert_eq!(a.passes, stored_before.passes);
7544 assert_eq!(a.chat_notices, stored_before.chat_notices);
7545 assert_eq!(a.chat_notice, stored_before.chat_notice);
7546 assert_eq!(a.chat_notice_due(), stored_before.chat_notice_due());
7547 assert_eq!(b.title, "second");
7548 assert!(b.runs.is_empty());
7549 assert!(b.passes.is_empty());
7550 assert!(b.chat_notice.is_none());
7551
7552 let mut again = q.get(&second.id).unwrap();
7554 again.title = "second, edited".into();
7555 q.put(&mut again).unwrap();
7556 assert_eq!(q.get(&second.id).unwrap().title, "second, edited");
7557 assert_eq!(q.list().len(), 2);
7558 }
7559
7560 #[test]
7561 fn a_new_task_skips_an_id_with_an_orphaned_claim_or_attachments() {
7562 let dir = tempfile::tempdir().unwrap();
7563 let q = queue_with_ids(dir.path(), &["orphan-lock", "orphan-dir", "free"]);
7564 std::fs::create_dir_all(q.root()).unwrap();
7565 std::fs::write(q.root().join("orphan-lock.lock"), "x").unwrap();
7566 std::fs::create_dir_all(q.attachments_dir("orphan-dir")).unwrap();
7567 let mut t = task("t");
7568 q.put(&mut t).unwrap();
7569 assert_eq!(t.id, "free");
7570 }
7571
7572 #[test]
7573 fn a_claimed_new_task_holds_the_claim_on_the_reserved_id() {
7574 let dir = tempfile::tempdir().unwrap();
7575 let q = queue_with_ids(dir.path(), &[TAKEN, TAKEN]);
7576 let mut first = task("first");
7577 q.put(&mut first).unwrap();
7578 let mut second = task("second");
7579 let claim = q.file_claimed(&mut second).unwrap();
7580 assert_ne!(second.id, first.id);
7581 assert!(q.claim(&second.id).is_err());
7582 assert!(q.claim(&first.id).is_ok(), "the first task was not claimed");
7583 drop(claim);
7584 }
7585
7586 #[test]
7587 fn an_attached_new_task_skips_a_taken_id() {
7588 let dir = tempfile::tempdir().unwrap();
7589 let q = queue_with_ids(dir.path(), &[TAKEN, TAKEN]);
7590 let mut first = task("first");
7591 q.put(&mut first).unwrap();
7592 let src = source_file(dir.path(), "shot.png", "x");
7593 let mut second = task("second");
7594 q.attach_and_put(&mut second, &[src]).unwrap();
7595 assert_ne!(second.id, first.id);
7596 assert!(!q.attachments_dir(&first.id).exists());
7597 assert_eq!(q.attachment_paths(&second).len(), 1);
7598 assert!(q.attachment_paths(&second)[0].is_file());
7599 }
7600
7601 #[test]
7602 fn attaching_before_putting_a_new_task_reserves_the_id() {
7603 let dir = tempfile::tempdir().unwrap();
7604 let q = queue_with_ids(dir.path(), &[TAKEN, TAKEN]);
7605 let mut first = task("first");
7606 q.put(&mut first).unwrap();
7607 let src = source_file(dir.path(), "shot.png", "x");
7608 let mut second = task("second");
7609 q.attach(&mut second, &[src]).unwrap();
7610 assert_ne!(second.id, first.id);
7611 assert!(q.attachments_dir(&second.id).is_dir());
7612 q.put(&mut second).unwrap();
7613 assert_eq!(q.get(&second.id).unwrap().attachments.len(), 1);
7614 assert_eq!(q.get(&first.id).unwrap().title, "first");
7615 assert!(q.get(&first.id).unwrap().attachments.is_empty());
7616 }
7617
7618 #[test]
7619 fn create_new_keeps_its_already_exists_meaning() {
7620 let dir = tempfile::tempdir().unwrap();
7621 let q = Queue::at(dir.path().join("queue"));
7622 let mut a = task("a");
7623 a.id = "fixed-id".into();
7624 assert!(q.create_new(&mut a).unwrap());
7625 let mut b = task("b");
7626 b.id = "fixed-id".into();
7627 assert!(!q.create_new(&mut b).unwrap());
7628 assert_eq!(q.get("fixed-id").unwrap().title, "a");
7629 }
7630
7631 #[test]
7632 fn filing_gives_up_when_no_id_is_ever_free() {
7633 let dir = tempfile::tempdir().unwrap();
7634 let q = Queue::at(dir.path().join("queue")).with_id_source(|| TAKEN.to_owned());
7635 let mut first = task("first");
7636 q.put(&mut first).unwrap();
7637 let mut second = task("second");
7638 assert!(q.put(&mut second).is_err());
7639 assert_eq!(q.get(&first.id).unwrap().title, "first");
7640 }
7641}