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(default)]
805 pub immediate: bool,
806 #[serde(skip)]
811 pub(crate) unfiled: bool,
812 #[serde(default)]
818 pub attachments: Vec<String>,
819 #[serde(default)]
823 pub followup: Option<FollowUp>,
824 #[serde(default)]
830 pub origin_chat: Option<String>,
831 #[serde(default)]
838 pub overrides: Option<RunOverrides>,
839 #[serde(default)]
846 pub review_of: Option<String>,
847 #[serde(default)]
852 pub held_at: Option<Timestamp>,
853 #[serde(default)]
857 pub park_reason: Option<String>,
858 #[serde(default)]
861 pub chat_notice: Option<ChatNotice>,
862 #[serde(default)]
864 pub chat_notices: Vec<String>,
865 #[serde(default)]
868 pub hold_notice_cause: Option<NoticeCause>,
869 #[serde(default)]
874 pub passes: Vec<TaskPass>,
875 #[serde(default)]
879 pub dispatched_at: Option<Timestamp>,
880 #[serde(default)]
882 pub recovery_budget: Option<RecoveryBudget>,
883 #[serde(default)]
886 pub recovery_admission: Option<RecoveryAdmission>,
887 #[serde(default)]
890 pub recovery_generations: Vec<RecoveryBudget>,
891 pub created_at: Timestamp,
893 pub updated_at: Timestamp,
895}
896
897#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
899pub struct RecoveryAdmission {
900 pub base: String,
902 pub inputs: String,
904}
905
906#[derive(Debug, Clone, Serialize, Deserialize)]
907struct RecoveryBudgetHold {
908 admission: RecoveryAdmission,
909 run: String,
910 pass: usize,
911 held_at: Timestamp,
912 decision: Option<Timestamp>,
913 #[serde(default)]
914 legacy: bool,
915}
916
917#[derive(Debug, Clone, Serialize, Deserialize)]
920pub struct RecoveryBudget {
921 pub instruction: String,
923 pub base: String,
925 pub inputs: String,
927 pub stage: String,
929 pub failures: usize,
931 #[serde(default)]
934 pub progress: Option<String>,
935}
936
937impl RecoveryBudget {
938 fn budget_reason(&self) -> String {
939 format!(
940 "[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.",
941 self.failures, self.stage
942 )
943 }
944}
945
946fn recovery_progress(state: &crate::run::RunState) -> Option<String> {
947 use crate::proc::Quiet as _;
948 use std::hash::{Hash, Hasher};
949 let mut patches = Vec::new();
950 for candidate in state.candidates.iter().filter(|c| c.commits > 0) {
951 let output = std::process::Command::new("git")
952 .current_dir(&state.repo)
953 .args(["diff", "--binary", &state.base_commit, &candidate.branch])
954 .quiet()
955 .output()
956 .ok()?;
957 if !output.status.success() {
958 return None;
959 }
960 patches.push(output.stdout);
961 }
962 patches.sort();
963 patches.dedup();
964 let mut hash = std::collections::hash_map::DefaultHasher::new();
965 patches.hash(&mut hash);
966 Some(format!("{:x}", hash.finish()))
967}
968
969pub(crate) fn recovery_inputs(sources: &crate::refs::Sources) -> String {
973 serde_json::to_string(
974 &sources
975 .start_from
976 .iter()
977 .map(|i| ("start", &i.token, &i.sha))
978 .chain(
979 sources
980 .pick_commits
981 .iter()
982 .map(|i| ("pick", &i.token, &i.sha)),
983 )
984 .collect::<Vec<_>>(),
985 )
986 .unwrap_or_default()
987}
988
989#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
991pub struct NoticeCause {
992 pub stage: String,
994 #[serde(default, skip_serializing_if = "Option::is_none")]
997 pub target: Option<String>,
998 pub run: Option<String>,
1000 pub pass: Option<usize>,
1002}
1003
1004pub(crate) fn is_done_notice_key(key: &str) -> bool {
1006 key == "done"
1007 || key
1008 .strip_prefix("done#")
1009 .is_some_and(|count| !count.is_empty() && count.bytes().all(|b| b.is_ascii_digit()))
1010}
1011
1012#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1014#[serde(rename_all = "snake_case")]
1015pub enum PassCost {
1016 Spent,
1018 Refunded,
1020}
1021
1022#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1024pub struct TaskPass {
1025 pub run: String,
1027 pub pass_index: usize,
1029 pub cost: PassCost,
1031 pub attempts_after: usize,
1033 #[serde(default)]
1035 pub started_at: Option<Timestamp>,
1036 pub settled_at: Timestamp,
1038 #[serde(default)]
1040 pub parked: Option<crate::run::ParkCause>,
1041}
1042
1043#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1045#[serde(rename_all = "lowercase")]
1046pub enum ChatNoticeOutcome {
1047 Posted,
1049 Skipped,
1051}
1052
1053#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1055pub struct ChatNotice {
1056 pub key: String,
1058 pub at: Timestamp,
1060 pub outcome: ChatNoticeOutcome,
1062}
1063
1064#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1066pub struct RunOverrides {
1067 #[serde(default)]
1070 pub inherit_daemon_options: bool,
1071 #[serde(default)]
1073 pub merge: Option<String>,
1074 #[serde(default)]
1076 pub candidates: Option<usize>,
1077 #[serde(default)]
1079 pub judges: Option<usize>,
1080 #[serde(default)]
1082 pub reviewers: Option<usize>,
1083 #[serde(default)]
1085 pub review_rounds: Option<usize>,
1086 #[serde(default)]
1088 pub seed: Option<u64>,
1089 #[serde(default)]
1091 pub config: Option<PathBuf>,
1092 #[serde(default, skip_serializing_if = "Option::is_none")]
1094 pub build_cache: Option<BuildCache>,
1095}
1096
1097impl RunOverrides {
1098 pub fn merge_over(&mut self, other: &RunOverrides) {
1100 macro_rules! take {
1101 ($($f:ident),*) => {$(
1102 if other.$f.is_some() {
1103 self.$f.clone_from(&other.$f);
1104 }
1105 )*};
1106 }
1107 take!(
1108 merge,
1109 candidates,
1110 judges,
1111 reviewers,
1112 review_rounds,
1113 seed,
1114 config,
1115 build_cache
1116 );
1117 }
1118
1119 pub fn apply(&self, config: &mut crate::config::Config) {
1121 if let Some(n) = self.candidates {
1122 config.graph.implementers = n;
1123 }
1124 if let Some(n) = self.judges {
1125 config.graph.judges = n;
1126 }
1127 if let Some(n) = self.reviewers {
1128 config.graph.reviewers = n;
1129 }
1130 if let Some(n) = self.review_rounds {
1131 config.graph.review_rounds = n;
1132 }
1133 if let Some(m) = &self.merge
1134 && let Ok(mode) = crate::daemon::merge_mode(m)
1135 {
1136 config.merge.mode = mode;
1137 }
1138 if let Some(s) = self.seed {
1139 config.blind.seed = Some(s);
1140 }
1141 if let Some(mode) = self.build_cache {
1142 config.verify.build_cache = mode;
1143 }
1144 }
1145}
1146
1147#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1149pub struct FollowUp {
1150 pub run: String,
1152 #[serde(default)]
1154 pub origin_task: Option<String>,
1155 pub pr: String,
1157 pub findings: Vec<String>,
1159 pub generation: u32,
1162}
1163
1164#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1166pub struct Resumption {
1167 pub generation: u64,
1169 pub source: String,
1171 pub question_id: Option<String>,
1173 pub at: Timestamp,
1175 pub instruction: String,
1177 pub answers_through: usize,
1179 pub runs_through: usize,
1182 pub cleared_reason: Option<String>,
1184 #[serde(default)]
1186 pub blocking_evidence: Vec<String>,
1187}
1188
1189#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1192pub struct OperatorResume {
1193 pub question_id: String,
1195 pub at: Timestamp,
1197 #[serde(default)]
1200 pub conductor_rehold: Option<String>,
1201 #[serde(default)]
1204 pub forced: bool,
1205 #[serde(default)]
1212 pub pinned_run: Option<String>,
1213}
1214
1215#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1218pub struct AnsweredQuestion {
1219 pub question: String,
1221 pub answer: String,
1223}
1224
1225fn append_missing<T: PartialEq>(ledger: &mut Vec<T>, entries: Vec<T>) {
1226 for entry in entries {
1227 if !ledger.contains(&entry) {
1228 ledger.push(entry);
1229 }
1230 }
1231}
1232
1233fn prepend_missing_by<T>(ledger: &mut Vec<T>, mut older: Vec<T>, same: impl Fn(&T, &T) -> bool) {
1234 older.retain(|old| !ledger.iter().any(|entry| same(entry, old)));
1235 if !older.is_empty() {
1236 older.append(ledger);
1237 *ledger = older;
1238 }
1239}
1240
1241impl Task {
1242 pub fn new(title: String, instruction: String, repo: PathBuf, source: Source) -> Self {
1244 let now = Timestamp::now();
1245 let origin_chat = match &source {
1246 Source::Agent { run, node } if node == CHAT_NODE => Some(run.clone()),
1247 _ => None,
1248 };
1249 Self {
1250 schema: SCHEMA,
1251 id: new_id(),
1252 title,
1253 instruction,
1254 sources: crate::refs::Sources::default(),
1255 repo,
1256 reassignments: Vec::new(),
1257 source,
1258 chat: None,
1259 priority: 0,
1260 solo: false,
1261 status: TaskStatus::Queued,
1262 completion_history: Vec::new(),
1263 attempts: 0,
1264 attempt_limit: None,
1265 runs: Vec::new(),
1266 startup_failures: Vec::new(),
1267 last_error: None,
1268 hold_reason: None,
1269 hold_source: None,
1270 recovery_budget_hold: None,
1271 machine_hold_cause: None,
1272 disk_resume_run: None,
1273 disk_checked_at: None,
1274 diagnostic: None,
1275 blocked_by: Vec::new(),
1276 block_reason: None,
1277 blocked_from: None,
1278 blocked_at: None,
1279 answers: Vec::new(),
1280 triage_applied: Vec::new(),
1281 actions_applied: Vec::new(),
1282 decision_effects: Default::default(),
1283 superseded_resumes: Default::default(),
1284 dispatched_resumes: Default::default(),
1285 base_recovery_requests: Vec::new(),
1286 land_sync_recovery_requests: Vec::new(),
1287 resume_override: None,
1288 sync_only: None,
1289 repair_grants: Vec::new(),
1290 repair_reconciliations: Vec::new(),
1291 resumption: None,
1292 resumption_history: Vec::new(),
1293 operator_decided_at: None,
1294 review_branch: None,
1295 review_instruction: None,
1296 pr_recovery: None,
1297 fresh_start: false,
1298 replacement: None,
1299 interrupt: false,
1300 urgent: false,
1301 immediate: false,
1302 unfiled: true,
1303 attachments: Vec::new(),
1304 followup: None,
1305 origin_chat,
1306 overrides: None,
1307 review_of: None,
1308 held_at: None,
1309 park_reason: None,
1310 chat_notice: None,
1311 chat_notices: Vec::new(),
1312 hold_notice_cause: None,
1313 passes: Vec::new(),
1314 dispatched_at: None,
1315 recovery_budget: None,
1316 recovery_admission: None,
1317 recovery_generations: Vec::new(),
1318 created_at: now,
1319 updated_at: now,
1320 }
1321 }
1322
1323 pub(crate) fn reassign_repository(&mut self, repo: PathBuf, actor: &str) {
1325 self.stamp_schema();
1326 if matches!(self.status, TaskStatus::Failed | TaskStatus::Parked) {
1327 self.hold_manual(Some(
1328 "Repository reassigned; inspect history and release to start fresh.".into(),
1329 ));
1330 }
1331 let at = Timestamp::now();
1332 self.reassignments.push(Reassignment {
1333 from: self.repo.clone(),
1334 to: repo.clone(),
1335 actor: actor.to_owned(),
1336 at,
1337 run_boundary: self.runs.len(),
1338 });
1339 self.repo = repo;
1340 self.review_branch = None;
1341 self.review_instruction = None;
1342 self.pr_recovery = None;
1343 self.replacement = None;
1344 self.interrupt = false;
1345 self.resume_override = None;
1346 self.fresh_start = true;
1347 self.operator_decided_at = Some(at);
1348 }
1349
1350 pub fn publication_branch(&self) -> String {
1352 crate::run::task_pr_branch_name(&self.id, self.reassignments.len())
1353 }
1354
1355 pub fn execution_runs(&self) -> &[String] {
1357 let boundary = self.reassignments.last().map_or(0, |r| r.run_boundary);
1358 self.runs.get(boundary..).unwrap_or_default()
1359 }
1360
1361 pub fn execution_run(&self, run: &str) -> bool {
1363 self.execution_runs().iter().any(|id| id == run)
1364 }
1365
1366 pub(crate) fn assignment_accepts(&self, run: &crate::run::RunState) -> bool {
1368 self.reassignments.last().is_none_or(|boundary| {
1369 self.execution_run(&run.id)
1370 && run.task_assignment == self.reassignments.len()
1371 && run.created_at > boundary.at
1372 && run
1373 .repo
1374 .canonicalize()
1375 .ok()
1376 .zip(self.repo.canonicalize().ok())
1377 .is_some_and(|(run_repo, task_repo)| run_repo == task_repo)
1378 })
1379 }
1380
1381 pub(crate) fn stale_question(&self, q: &crate::ask::Question) -> bool {
1383 self.reassignments
1384 .last()
1385 .is_some_and(|r| q.asked_at <= r.at)
1386 || (self.runs.contains(&q.run) && !self.execution_run(&q.run))
1387 }
1388
1389 pub fn chat_talk(&self) -> Option<&str> {
1391 if let Some(id) = &self.origin_chat {
1392 return Some(id);
1393 }
1394 match &self.source {
1395 Source::Agent { run, node } if node == CHAT_NODE => Some(run),
1396 _ => None,
1397 }
1398 }
1399
1400 pub fn filed_by_chat(&self) -> Option<&str> {
1404 match &self.source {
1405 Source::Agent { run, node } if node == CHAT_NODE => Some(run),
1406 _ => None,
1407 }
1408 }
1409
1410 pub fn chat_notice_key(&self) -> Option<String> {
1413 match self.status {
1414 TaskStatus::Done => Some(
1415 self.completion_history
1416 .iter()
1417 .rev()
1418 .find(|event| event.action == CompletionAction::Complete)
1419 .map_or_else(
1420 || "done".to_owned(),
1421 |event| format!("done:{}", event.occurrence),
1422 ),
1423 ),
1424 TaskStatus::Held => {
1425 let cause = self
1426 .hold_notice_cause
1427 .clone()
1428 .unwrap_or_else(|| self.unresolved_hold_cause());
1429 Some(format!(
1430 "cause:{}",
1431 serde_json::to_string(&cause).expect("cause")
1432 ))
1433 }
1434 TaskStatus::Blocked => {
1435 let ids: std::collections::BTreeSet<_> = self.blocked_by.iter().collect();
1436 let evidence = self
1439 .hold_notice_cause
1440 .as_ref()
1441 .filter(|c| c.stage.starts_with("conductor-evidence:"));
1442 Some(format!(
1443 "dependencies:{}",
1444 serde_json::to_string(&(ids, evidence)).expect("ids")
1445 ))
1446 }
1447 _ => None,
1448 }
1449 }
1450
1451 fn unresolved_hold_cause(&self) -> NoticeCause {
1452 NoticeCause {
1453 stage: "hold".into(),
1454 target: None,
1455 run: self.runs.last().cloned(),
1456 pass: None,
1457 }
1458 }
1459
1460 pub(crate) fn legacy_chat_notice_key(&self) -> Option<String> {
1462 let key = match self.status {
1463 TaskStatus::Held if self.hold_notice_cause.is_none() => Some(format!(
1464 "held#{}",
1465 self.held_at.map(|t| t.to_string()).unwrap_or_default()
1466 )),
1467 TaskStatus::Blocked => Some(format!(
1468 "blocked#{}#{}",
1469 self.blocked_by.join(","),
1470 self.block_reason.as_deref().unwrap_or_default()
1471 )),
1472 _ => None,
1473 };
1474 key.filter(|key| self.legacy_notice_matches(key))
1475 }
1476
1477 pub(crate) fn legacy_notice_matches(&self, key: &str) -> bool {
1478 match self.status {
1479 TaskStatus::Held if self.hold_notice_cause.is_none() => key
1480 .strip_prefix("held#")
1481 .is_some_and(|time| time.is_empty() || time.parse::<Timestamp>().is_ok()),
1482 TaskStatus::Blocked
1483 if self
1484 .hold_notice_cause
1485 .as_ref()
1486 .is_none_or(|c| !c.stage.starts_with("conductor-evidence:")) =>
1487 {
1488 key.strip_prefix("blocked#").is_some_and(|tail| {
1489 let Some((ids, _)) = tail.split_once('#') else {
1490 return false;
1491 };
1492 let old: std::collections::BTreeSet<_> =
1493 ids.split(',').filter(|id| !id.is_empty()).collect();
1494 let current: std::collections::BTreeSet<_> =
1495 self.blocked_by.iter().map(String::as_str).collect();
1496 old == current
1497 })
1498 }
1499 _ => false,
1500 }
1501 }
1502
1503 fn import_chat_notice(&mut self) {
1504 if let Some(n) = &self.chat_notice {
1505 let key = if is_done_notice_key(&n.key) {
1506 "done".to_owned()
1507 } else if self.legacy_notice_matches(&n.key) {
1508 self.chat_notice_key().unwrap_or_else(|| n.key.clone())
1509 } else {
1510 n.key.clone()
1511 };
1512 if !self.chat_notices.contains(&key) {
1513 self.chat_notices.push(key);
1514 }
1515 }
1516 }
1517
1518 pub(crate) fn notice_cause(&mut self, stage: &str, run: Option<&str>, pass: Option<usize>) {
1521 self.import_chat_notice();
1522 self.hold_notice_cause = Some(NoticeCause {
1523 stage: stage.to_owned(),
1524 target: None,
1525 run: run.map(str::to_owned),
1526 pass,
1527 });
1528 }
1529
1530 pub(crate) fn startup_notice_cause(&mut self, stage: &str) {
1533 let recovery_only = matches!(
1534 stage,
1535 "startup-source" | "startup-candidates" | "startup-public-head"
1536 );
1537 match self.hold_notice_cause.as_ref() {
1538 Some(cause) if recovery_only && !cause.stage.starts_with("startup-") => return,
1539 None if recovery_only
1540 && self
1541 .chat_notice
1542 .as_ref()
1543 .is_some_and(|n| !is_done_notice_key(&n.key)) =>
1544 {
1545 return;
1546 }
1547 _ => {}
1548 }
1549 self.notice_cause(stage, None, None);
1550 }
1551
1552 pub(crate) fn fail_startup(
1555 &mut self,
1556 stage: &str,
1557 why: impl Into<String>,
1558 max_attempts: usize,
1559 ) {
1560 let unresolved = self.hold_notice_cause.clone();
1561 self.fail(why, max_attempts);
1562 self.hold_notice_cause = unresolved;
1563 self.startup_notice_cause(stage);
1564 }
1565
1566 pub(crate) fn fail_startup_target(
1568 &mut self,
1569 stage: &str,
1570 target: String,
1571 why: impl Into<String>,
1572 max_attempts: usize,
1573 ) {
1574 self.fail_startup(stage, why, max_attempts);
1575 if let Some(cause) = self.hold_notice_cause.as_mut() {
1576 cause.target = Some(target);
1577 }
1578 }
1579
1580 pub fn chat_notice_due(&self) -> Option<String> {
1582 self.filed_by_chat()?;
1583 if self.schema < 13 {
1584 return None;
1585 }
1586 let key = self.chat_notice_key()?;
1587 if self.chat_notices.contains(&key) {
1588 return None;
1589 }
1590 match &self.chat_notice {
1591 Some(n)
1592 if n.key == key
1593 || (key == "done" && is_done_notice_key(&n.key))
1594 || self.legacy_notice_matches(&n.key) =>
1595 {
1596 None
1597 }
1598 _ => Some(key),
1599 }
1600 }
1601
1602 pub fn short(&self) -> &str {
1604 short(&self.id)
1605 }
1606
1607 pub fn mark_triage_applied(&mut self, question_id: &str) {
1609 if !self.triage_applied(question_id) {
1610 self.triage_applied.push(question_id.to_owned());
1611 }
1612 }
1613
1614 pub fn action_applied(&self, question_id: &str) -> bool {
1617 self.actions_applied.iter().any(|id| id == question_id)
1618 }
1619
1620 pub fn mark_action_applied(&mut self, question_id: &str) {
1622 if !self.action_applied(question_id) {
1623 self.actions_applied.push(question_id.to_owned());
1624 }
1625 }
1626
1627 pub fn triage_applied(&self, question_id: &str) -> bool {
1629 self.triage_applied.iter().any(|id| id == question_id)
1630 }
1631
1632 pub fn start(&mut self, run: String) {
1645 self.stamp_schema();
1646 self.status = TaskStatus::Running;
1647 self.attempts += 1;
1648 self.runs.retain(|id| id != &run);
1649 if let Some(pin) = &self.resume_override
1650 && pin.pinned_run.as_ref() == Some(&run)
1651 && !pin.question_id.is_empty()
1652 {
1653 self.dispatched_resumes
1654 .insert(pin.question_id.clone(), run.clone());
1655 }
1656 self.runs.push(run);
1657 self.last_error = None;
1658 self.park_reason = None;
1659 self.fresh_start = false;
1660 self.interrupt = false;
1661 self.resume_override = None;
1663 self.disk_resume_run = None;
1666 }
1667
1668 pub fn record_startup_failure(&mut self, failure: crate::run::StartupFailure) {
1670 if !self.startup_failures.iter().any(|f| f.run == failure.run) {
1671 self.startup_failures.push(failure);
1672 }
1673 }
1674
1675 pub fn link_run(&mut self, run: &str) -> bool {
1680 if self.runs.iter().any(|r| r == run) {
1681 return false;
1682 }
1683 self.runs.push(run.to_owned());
1684 true
1685 }
1686
1687 pub fn succeed(&mut self, context: CompletionContext) {
1697 if self.status == TaskStatus::Done {
1698 return;
1699 }
1700 self.record_completion(CompletionAction::Complete, context);
1701 self.stamp_schema();
1702 self.status = TaskStatus::Done;
1703 if let Some(pin) = self.resume_override.take()
1704 && !pin.question_id.is_empty()
1705 && let Some(run) = pin.pinned_run
1706 {
1707 self.superseded_resumes.insert(pin.question_id, run);
1710 }
1711 self.sync_only = None;
1712 self.last_error = None;
1713 self.park_reason = None;
1714 self.hold_reason = None;
1715 self.hold_source = None;
1716 self.machine_hold_cause = None;
1717 self.disk_resume_run = None;
1718 self.disk_checked_at = None;
1719 self.diagnostic = None;
1720 self.blocked_by.clear();
1721 self.block_reason = None;
1722 self.blocked_from = None;
1723 }
1724
1725 pub fn already_landed(&mut self, note: impl Into<String>, mut context: CompletionContext) {
1733 let note = note.into();
1734 if context.reason.is_none() {
1735 context.reason = Some(note.clone());
1736 }
1737 self.succeed(context);
1738 self.attempts = self.attempts.saturating_sub(1);
1739 self.last_error = Some(note);
1740 }
1741
1742 fn record_completion(&mut self, action: CompletionAction, context: CompletionContext) {
1743 self.completion_history.push(CompletionEvent {
1744 occurrence: format!(
1745 "{}-{:016x}{:016x}",
1746 Timestamp::now(),
1747 crate::rng::entropy(),
1748 crate::rng::entropy()
1749 ),
1750 action,
1751 actor: context.actor,
1752 reason: context.reason,
1753 discard: context.discard,
1754 prior_status: self.status,
1755 at: Timestamp::now(),
1756 prior_hold_reason: self.hold_reason.clone(),
1757 prior_block_reason: self.block_reason.clone(),
1758 prior_error: self.last_error.clone(),
1759 run: context.run,
1760 unavailable_runs: context.unavailable_runs,
1761 });
1762 self.stamp_schema();
1763 }
1764
1765 pub fn reopen(&mut self, context: CompletionContext) -> Result<()> {
1768 anyhow::ensure!(
1769 self.status == TaskStatus::Done,
1770 "only a done task can be reopened"
1771 );
1772 anyhow::ensure!(
1773 context
1774 .reason
1775 .as_deref()
1776 .is_some_and(|reason| !reason.trim().is_empty()),
1777 "reopen requires a non-empty reason"
1778 );
1779 let reason = context.reason.clone();
1780 self.record_completion(CompletionAction::Reopen, context);
1781 self.hold_manual(reason);
1782 self.resume_override = None;
1783 self.fresh_start = false;
1784 self.last_error = None;
1785 self.diagnostic = None;
1786 Ok(())
1787 }
1788
1789 pub fn superseded_attempts(&self, last_run_succeeded: bool) -> &[String] {
1819 if self.status != TaskStatus::Done || !last_run_succeeded || self.execution_runs().len() < 2
1820 {
1821 return &[];
1822 }
1823 &self.execution_runs()[..self.execution_runs().len() - 1]
1824 }
1825
1826 pub fn successor_of(&self, run: &str) -> Option<&String> {
1834 let runs = self.execution_runs();
1835 let pos = runs.iter().rposition(|r| r == run)?;
1836 runs.get(pos + 1)
1837 }
1838
1839 pub fn earlier_attempts(&self) -> &[String] {
1846 self.execution_runs()
1847 }
1848
1849 fn preserve_legacy_build_cache(&mut self) {
1850 if self.schema < 23 {
1851 let overrides = self.overrides.get_or_insert_with(|| RunOverrides {
1852 inherit_daemon_options: true,
1853 ..RunOverrides::default()
1854 });
1855 overrides.build_cache.get_or_insert(BuildCache::Shared);
1856 }
1857 }
1858
1859 fn stamp_schema(&mut self) {
1864 self.preserve_legacy_build_cache();
1865 if self.schema < RECOVERY_HOLD_SCHEMA && self.recovery_budget_hold.is_none() {
1866 self.recovery_budget_hold = self.legacy_recovery_budget_hold();
1867 }
1868 self.schema = self.schema.max(SCHEMA);
1869 }
1870
1871 fn note_held(&mut self) {
1874 self.stamp_schema();
1875 self.recovery_budget_hold = None;
1876 let continuing = self.status == TaskStatus::Held
1877 || (self.status == TaskStatus::Blocked
1878 && (self.blocked_from == Some(TaskStatus::Held)
1879 || (self.blocked_from.is_none()
1880 && (self.hold_reason.is_some() || self.hold_source.is_some()))));
1881 if !continuing || self.held_at.is_none() {
1882 self.held_at = Some(Timestamp::now());
1883 }
1884 }
1885
1886 pub fn fail(&mut self, why: impl Into<String>, max_attempts: usize) {
1902 let why = why.into();
1903 if self.status == TaskStatus::Running {
1904 let run = self.runs.last().cloned();
1905 self.notice_cause("run-failed", run.as_deref(), Some(self.attempts));
1906 }
1907 self.diagnostic = None;
1908 self.park_reason = None;
1909 self.status = if self.attempts >= self.effective_attempt_limit(max_attempts) {
1910 self.note_held();
1911 self.hold_source = Some(HoldSource::Machine);
1912 self.machine_hold_cause = None;
1913 self.disk_resume_run = None;
1914 self.disk_checked_at = None;
1915 self.hold_reason = Some(why.clone());
1916 TaskStatus::Held
1917 } else {
1918 TaskStatus::Failed
1919 };
1920 self.last_error = Some(why);
1921 }
1922
1923 pub fn stall(&mut self, why: impl Into<String>) {
1933 self.last_error = Some(why.into());
1934 self.diagnostic = None;
1935 self.attempts = self.attempts.saturating_sub(1);
1936 self.status = TaskStatus::Failed;
1937 }
1938
1939 pub fn park(&mut self, why: impl Into<String>) {
1945 self.diagnostic = None;
1946 self.attempts = self.attempts.saturating_sub(1);
1947 self.status = TaskStatus::Parked;
1948 self.park_reason = Some(why.into());
1949 self.stamp_schema();
1952 }
1953
1954 pub fn record_pass(
1956 &mut self,
1957 run: &str,
1958 pass_index: usize,
1959 attempts_before: usize,
1960 parked: Option<crate::run::ParkCause>,
1961 ) {
1962 self.record_pass_at(run, pass_index, None, attempts_before, parked);
1963 }
1964
1965 pub fn record_pass_at(
1968 &mut self,
1969 run: &str,
1970 pass_index: usize,
1971 started_at: Option<Timestamp>,
1972 attempts_before: usize,
1973 parked: Option<crate::run::ParkCause>,
1974 ) {
1975 if self
1976 .passes
1977 .iter()
1978 .any(|p| p.run == run && p.pass_index == pass_index)
1979 {
1980 return;
1981 }
1982 let cost = if self.attempts < attempts_before {
1983 PassCost::Refunded
1984 } else {
1985 PassCost::Spent
1986 };
1987 self.passes.push(TaskPass {
1988 run: run.to_owned(),
1989 pass_index,
1990 started_at: self.dispatched_at.or(started_at),
1991 cost,
1992 attempts_after: self.attempts,
1993 settled_at: Timestamp::now(),
1994 parked,
1995 });
1996 self.stamp_schema();
1997 }
1998
1999 pub(crate) fn upgrade_resume_key(&self) -> Option<(Timestamp, &str)> {
2002 if self.status != TaskStatus::Parked || self.fresh_start {
2003 return None;
2004 }
2005 let pass = self.passes.last()?;
2006 if self.execution_runs().last() != Some(&pass.run)
2007 || !matches!(pass.parked, Some(crate::run::ParkCause::Upgrade { .. }))
2008 {
2009 return None;
2010 }
2011 Some((pass.started_at.unwrap_or(pass.settled_at), &self.id))
2014 }
2015
2016 pub fn operator_held(&self) -> bool {
2022 self.status == TaskStatus::Held && !matches!(self.hold_source, Some(HoldSource::Machine))
2023 }
2024
2025 pub fn hold_manual(&mut self, reason: Option<String>) {
2035 self.operator_decided_at = Some(Timestamp::now());
2037 if self.status != TaskStatus::Running && self.sync_only.take().is_some() {
2038 self.resume_override = None;
2039 }
2040 self.hold_unrequested_retry(reason);
2041 }
2042
2043 pub(crate) fn hold_unrequested_retry(&mut self, reason: Option<String>) {
2046 self.park_reason = None;
2047 self.note_held();
2048 self.status = TaskStatus::Held;
2049 if reason.is_some() {
2050 self.hold_reason = reason;
2051 }
2052 self.hold_source = Some(HoldSource::Manual);
2053 self.machine_hold_cause = None;
2054 self.disk_resume_run = None;
2055 self.disk_checked_at = None;
2056 self.blocked_by.clear();
2057 self.block_reason = None;
2058 self.blocked_from = None;
2059 }
2060
2061 pub(crate) fn hold_after_sync_only(&mut self, reason: String) {
2062 let recovery_hold = self.recovery_budget_hold.take();
2063 self.hold_unrequested_retry(Some(reason));
2064 self.recovery_budget_hold = recovery_hold;
2065 }
2066
2067 pub fn hold_machine(&mut self, reason: Option<String>) {
2072 self.park_reason = None;
2073 self.note_held();
2074 self.status = TaskStatus::Held;
2075 if reason.is_some() {
2076 self.hold_reason = reason;
2077 }
2078 self.hold_source = Some(HoldSource::Machine);
2079 self.machine_hold_cause = None;
2080 self.disk_resume_run = None;
2081 self.disk_checked_at = None;
2082 self.blocked_by.clear();
2083 self.block_reason = None;
2084 self.blocked_from = None;
2085 }
2086
2087 pub(crate) fn mark_disk_capacity(&mut self) {
2089 self.machine_hold_cause = Some(MachineHoldCause::DiskCapacity {
2090 reason: self.hold_reason.clone().unwrap_or_default(),
2091 before_start: false,
2092 });
2093 }
2094
2095 pub(crate) fn mark_startup_disk_capacity(&mut self) {
2096 self.machine_hold_cause = Some(MachineHoldCause::DiskCapacity {
2097 reason: self.hold_reason.clone().unwrap_or_default(),
2098 before_start: true,
2099 });
2100 }
2101
2102 pub(crate) fn disk_wait_run(&self) -> Option<&String> {
2103 if self.has_disk_capacity_cause()
2104 && matches!(
2105 self.machine_hold_cause,
2106 Some(MachineHoldCause::DiskCapacity {
2107 before_start: true,
2108 ..
2109 })
2110 )
2111 {
2112 None
2113 } else {
2114 self.execution_runs().last()
2115 }
2116 }
2117
2118 pub fn has_disk_capacity_cause(&self) -> bool {
2120 matches!(
2121 (&self.machine_hold_cause, self.hold_reason.as_deref()),
2122 (Some(MachineHoldCause::DiskCapacity { reason, .. }), Some(now)) if reason == now
2123 )
2124 }
2125
2126 pub(crate) fn resume_disk_wait(&mut self) {
2128 let retained = self.disk_wait_run().cloned();
2129 self.status = TaskStatus::Queued;
2130 self.held_at = None;
2131 self.hold_source = None;
2132 self.hold_reason = None;
2133 self.machine_hold_cause = None;
2134 self.last_error = None;
2135 self.disk_resume_run = retained;
2136 }
2137
2138 pub(crate) fn hold_head_e2e(
2140 &mut self,
2141 stop: crate::head_e2e_stop::Stop,
2142 reason: String,
2143 last_error: String,
2144 ) {
2145 self.hold_machine(Some(reason));
2146 self.last_error = Some(last_error);
2147 self.machine_hold_cause = Some(MachineHoldCause::HeadE2e { stop });
2148 }
2149
2150 pub(crate) fn head_e2e_notice(&mut self, stop: &crate::head_e2e_stop::Stop) {
2152 if let Some(at) = stop.recorded_at {
2153 self.held_at = Some(at);
2154 }
2155 self.notice_cause(crate::head_e2e_stop::NOTICE_STAGE, Some(&stop.run), None);
2156 if let Some(cause) = &mut self.hold_notice_cause {
2157 cause.target = Some(stop.id.clone());
2158 }
2159 }
2160
2161 pub fn has_head_e2e_cause(&self) -> bool {
2163 matches!(
2164 self.machine_hold_cause,
2165 Some(MachineHoldCause::HeadE2e { .. })
2166 )
2167 }
2168
2169 pub fn head_e2e_stop_id(&self) -> Option<&str> {
2171 if let Some(MachineHoldCause::HeadE2e { stop }) = &self.machine_hold_cause {
2172 return Some(stop.id.as_str());
2173 }
2174 self.hold_notice_cause
2175 .as_ref()
2176 .filter(|c| c.stage == crate::head_e2e_stop::NOTICE_STAGE)
2177 .and_then(|c| c.target.as_deref())
2178 }
2179
2180 pub(crate) fn resume_head_e2e_wait(&mut self) {
2183 self.status = TaskStatus::Queued;
2184 self.held_at = None;
2185 self.hold_source = None;
2186 self.hold_reason = None;
2187 self.machine_hold_cause = None;
2188 self.last_error = None;
2189 self.diagnostic = None;
2190 self.blocked_by.clear();
2191 self.block_reason = None;
2192 self.blocked_from = None;
2193 }
2194
2195 pub fn block(&mut self, blocked_by: Vec<String>, reason: Option<String>) {
2205 self.stamp_schema();
2206 let before: std::collections::BTreeSet<_> = self.blocked_by.iter().collect();
2207 let after: std::collections::BTreeSet<_> = blocked_by.iter().collect();
2208 if self.status != TaskStatus::Blocked || before != after {
2209 self.blocked_at = Some(Timestamp::now());
2210 }
2211 if self.status != TaskStatus::Blocked {
2212 self.blocked_from = Some(self.status);
2213 }
2214 self.status = TaskStatus::Blocked;
2215 self.blocked_by = blocked_by;
2216 self.block_reason = reason;
2217 }
2218
2219 pub fn unblock(&mut self, resolved_id: &str) {
2242 if self.status != TaskStatus::Blocked {
2243 return;
2244 }
2245 self.blocked_by.retain(|id| id != resolved_id);
2246 self.restore_if_unblocked();
2247 }
2248
2249 pub fn dependency_deleted(&mut self, deleted_id: &str) -> bool {
2260 if self.status != TaskStatus::Blocked || !self.blocked_by.iter().any(|b| b == deleted_id) {
2261 return false;
2262 }
2263 self.blocked_by.retain(|id| id != deleted_id);
2264 self.restore_if_unblocked();
2265 true
2266 }
2267
2268 fn restore_if_unblocked(&mut self) {
2272 if self.blocked_by.is_empty() {
2273 self.status = match self.blocked_from {
2274 Some(TaskStatus::Running) => TaskStatus::Queued,
2275 Some(other) => other,
2276 None if self.hold_reason.is_some() || self.hold_source.is_some() => {
2277 TaskStatus::Held
2278 }
2279 None => TaskStatus::Queued,
2280 };
2281 self.block_reason = None;
2282 self.blocked_from = None;
2283 }
2284 }
2285
2286 pub fn record_answer(&mut self, question: String, answer: String) {
2291 self.answers.push(AnsweredQuestion { question, answer });
2292 }
2293
2294 pub fn request_review(&mut self, branch: String) {
2298 self.release();
2299 self.review_branch = Some(branch);
2300 self.review_instruction = Some(self.instruction.clone());
2301 }
2302
2303 pub fn requeue(&mut self) {
2306 self.release();
2307 self.review_branch = None;
2309 self.review_instruction = None;
2310 self.fresh_start = true;
2311 }
2312
2313 pub fn hold_for_handover(&mut self, branch: Option<String>, reason: String) {
2322 if branch.is_some() {
2323 self.review_branch = branch;
2324 self.review_instruction = Some(self.instruction.clone());
2325 }
2326 self.hold_machine(Some(reason));
2327 }
2328
2329 pub fn set_urgent(&mut self, urgent: bool) -> Result<()> {
2331 if !matches!(self.status, TaskStatus::Queued | TaskStatus::Held) {
2332 bail!(
2333 "task {} is {}; urgent can only change while queued or held; \
2334 wait for the active attempt to finish and requeue or hold the task first",
2335 self.short(),
2336 self.status.as_str()
2337 );
2338 }
2339 self.urgent = urgent;
2340 Ok(())
2341 }
2342
2343 pub fn set_immediate(&mut self, immediate: bool) -> Result<()> {
2347 if !matches!(self.status, TaskStatus::Queued | TaskStatus::Held) {
2348 bail!(
2349 "task {} is {}; immediate can only change while queued or held; \
2350 wait for the active attempt to finish and requeue or hold the task first",
2351 self.short(),
2352 self.status.as_str()
2353 );
2354 }
2355 self.immediate = immediate;
2356 Ok(())
2357 }
2358
2359 pub fn set_priority(&mut self, priority: i32) -> Result<()> {
2368 if self.status == TaskStatus::Running {
2369 bail!(
2370 "task {} is running; its priority cannot be changed until \
2371 this attempt finishes",
2372 self.short()
2373 );
2374 }
2375 self.priority = priority;
2376 Ok(())
2377 }
2378
2379 pub fn set_interrupt(&mut self, interrupt: bool) -> Result<()> {
2394 if interrupt && !self.status.runnable() {
2395 bail!(
2396 "task {} is {}; only a queued or failed task can be marked \
2397 to interrupt",
2398 self.short(),
2399 self.status.as_str()
2400 );
2401 }
2402 self.interrupt = interrupt;
2403 Ok(())
2404 }
2405
2406 pub fn effective_attempt_limit(&self, daemon_limit: usize) -> usize {
2408 self.attempt_limit.map_or(daemon_limit, NonZeroUsize::get)
2409 }
2410
2411 pub fn change_attempt_limit(&mut self, limit: Option<NonZeroUsize>) -> Result<()> {
2414 if !matches!(self.status, TaskStatus::Queued | TaskStatus::Held) {
2415 bail!("only queued or held tasks can change the attempt limit");
2416 }
2417 self.stamp_schema();
2418 self.attempt_limit = limit;
2419 Ok(())
2420 }
2421
2422 pub fn implementers(&self) -> Option<usize> {
2424 if self.solo {
2425 Some(1)
2426 } else {
2427 self.overrides.as_ref().and_then(|o| o.candidates)
2428 }
2429 }
2430
2431 pub fn build_cache_override(
2436 &self,
2437 config: &crate::config::Config,
2438 ) -> Option<(BuildCache, &'static str)> {
2439 self.overrides
2440 .as_ref()
2441 .and_then(|o| o.build_cache)
2442 .map(|mode| (mode, "task-override"))
2443 .or_else(|| {
2444 ((self.immediate || self.urgent) && crate::build_target::urgent_isolation(config))
2445 .then_some((
2446 BuildCache::Isolated,
2447 if self.immediate {
2448 "immediate"
2449 } else {
2450 "urgent"
2451 },
2452 ))
2453 })
2454 }
2455
2456 pub fn change_build_cache(&mut self, mode: Option<BuildCache>) -> Result<()> {
2459 if !matches!(self.status, TaskStatus::Queued | TaskStatus::Held) {
2460 bail!(
2461 "task {} is {}; only queued or held tasks can change build cache",
2462 self.short(),
2463 self.status.as_str()
2464 );
2465 }
2466 self.stamp_schema();
2467 if self.overrides.is_some() || mode.is_some() {
2468 let overrides = self.overrides.get_or_insert_with(|| RunOverrides {
2469 inherit_daemon_options: true,
2470 ..RunOverrides::default()
2471 });
2472 overrides.build_cache = mode;
2473 }
2474 Ok(())
2475 }
2476
2477 pub fn change_implementers(&mut self, count: u8) -> Result<()> {
2480 self.check_implementers_editable()?;
2481 let explicit = self.overrides.as_ref().and_then(|o| o.config.as_deref());
2482 let (mut config, _) = crate::config::Config::discover(&self.repo, explicit)?;
2483 if let Some(o) = &self.overrides {
2484 o.apply(&mut config);
2485 }
2486 self.set_implementers(count, &config)
2487 }
2488
2489 fn check_implementers_editable(&self) -> Result<()> {
2490 if !matches!(self.status, TaskStatus::Queued | TaskStatus::Held) {
2491 bail!(
2492 "task {} is {}; only queued or held tasks can change implementers",
2493 self.short(),
2494 self.status.as_str()
2495 );
2496 }
2497 Ok(())
2498 }
2499
2500 pub fn set_implementers(&mut self, count: u8, config: &crate::config::Config) -> Result<()> {
2502 self.check_implementers_editable()?;
2503 crate::talk::check_implementers(count, config).map_err(anyhow::Error::msg)?;
2504 self.stamp_schema();
2505 self.solo = count == 1;
2506 let mut overrides = self.overrides.clone().unwrap_or_else(|| RunOverrides {
2507 inherit_daemon_options: true,
2508 ..Default::default()
2509 });
2510 overrides.candidates = (count > 1).then_some(usize::from(count));
2511 let mut settings = overrides.clone();
2512 settings.inherit_daemon_options = false;
2513 self.overrides = if overrides.inherit_daemon_options && settings == RunOverrides::default()
2515 {
2516 None
2517 } else {
2518 Some(overrides)
2519 };
2520 Ok(())
2521 }
2522
2523 pub fn edit(&mut self, title: String, instruction: String) -> Result<()> {
2535 if !matches!(self.status, TaskStatus::Queued | TaskStatus::Held) {
2536 bail!(
2537 "task {} is {}; only a queued or held task's instruction can \
2538 be edited",
2539 self.short(),
2540 self.status.as_str()
2541 );
2542 }
2543 if self.review_branch.is_some() && self.review_instruction.is_none() {
2546 self.review_instruction = Some(self.instruction.clone());
2547 }
2548 if self.instruction != instruction {
2549 self.resume_override = None;
2552 }
2553 if self.status == TaskStatus::Held && self.machine_hold_cause.is_some() {
2554 self.hold_manual(self.hold_reason.clone());
2555 }
2556 self.machine_hold_cause = None;
2557 self.disk_resume_run = None;
2558 self.disk_checked_at = None;
2559 self.title = title;
2560 self.instruction = instruction;
2561 Ok(())
2562 }
2563
2564 pub fn handed_off(&mut self, why: impl Into<String>) {
2584 let why = why.into();
2585 self.diagnostic = None;
2586 self.note_held();
2587 self.status = TaskStatus::Held;
2588 self.hold_source = Some(HoldSource::Machine);
2589 self.machine_hold_cause = None;
2590 self.disk_resume_run = None;
2591 self.disk_checked_at = None;
2592 self.hold_reason = Some(why.clone());
2593 self.last_error = Some(why);
2594 }
2595
2596 pub fn release_operator(&mut self, source: &str, question_id: Option<&str>) {
2598 self.recovery_budget = None;
2599 self.recovery_generations.clear();
2600 self.recovery_admission = None;
2601 if self
2602 .resumption
2603 .as_ref()
2604 .is_some_and(|r| r.instruction != self.instruction)
2605 {
2606 self.resume_override = None;
2609 }
2610 let approval = Resumption {
2611 generation: self.resumption.as_ref().map_or(1, |r| r.generation + 1),
2612 source: source.to_owned(),
2613 question_id: question_id.map(str::to_owned),
2614 at: Timestamp::now(),
2615 instruction: self.instruction.clone(),
2616 answers_through: self.answers.len(),
2617 runs_through: self.runs.len(),
2618 blocking_evidence: Vec::new(),
2619 cleared_reason: self
2620 .hold_reason
2621 .clone()
2622 .or_else(|| self.block_reason.clone()),
2623 };
2624 self.release();
2625 self.operator_decided_at = Some(approval.at);
2626 if let Some(previous) = self.resumption.replace(approval) {
2627 self.resumption_history.push(previous);
2628 }
2629 }
2630
2631 pub(crate) fn recovery_failed(&mut self, state: &crate::run::RunState) {
2633 let (base, inputs) = self.recovery_admission.as_ref().map_or_else(
2634 || (state.base_commit.clone(), recovery_inputs(&state.sources)),
2635 |a| (a.base.clone(), a.inputs.clone()),
2636 );
2637 let progress = recovery_progress(state);
2638 let stage = if state.prep_failure.is_some() {
2639 "preparation"
2640 } else {
2641 "execution"
2642 };
2643 let matches = |b: &RecoveryBudget| {
2644 b.instruction == self.instruction
2645 && b.base == base
2646 && b.inputs == inputs
2647 && (progress.is_none() || b.progress == progress)
2648 };
2649 if !self.recovery_budget.as_ref().is_some_and(matches) {
2650 let previous = self
2651 .recovery_generations
2652 .iter()
2653 .position(matches)
2654 .map(|index| self.recovery_generations.remove(index));
2655 if let Some(old) = self.recovery_budget.take() {
2656 self.recovery_generations.push(old);
2657 }
2658 self.recovery_budget = previous;
2659 }
2660 if let Some(budget) = &mut self.recovery_budget {
2661 budget.failures = budget.failures.saturating_add(1);
2662 budget.stage = stage.to_owned();
2663 } else {
2664 self.recovery_budget = Some(RecoveryBudget {
2665 instruction: self.instruction.clone(),
2666 base,
2667 inputs,
2668 stage: stage.to_owned(),
2669 failures: 1,
2670 progress,
2671 });
2672 }
2673 }
2674
2675 pub(crate) fn recovery_exhausted(
2676 &self,
2677 base: &str,
2678 inputs: &str,
2679 limit: usize,
2680 ) -> Option<String> {
2681 let same_input = |b: &&RecoveryBudget| {
2682 b.instruction == self.instruction && b.base == base && b.inputs == inputs
2683 };
2684 let budget = self
2685 .recovery_budget
2686 .as_ref()
2687 .filter(same_input)
2688 .or_else(|| self.recovery_generations.iter().rev().find(same_input))?;
2689 (budget.failures >= limit.max(1)).then(|| budget.budget_reason())
2690 }
2691
2692 pub(crate) fn hold_recovery_budget(&mut self, reason: String, admission: RecoveryAdmission) {
2693 self.hold_unrequested_retry(Some(reason));
2694 if let Some(pass) = self.passes.last()
2695 && self.execution_runs().last() == Some(&pass.run)
2696 {
2697 self.recovery_budget_hold = Some(RecoveryBudgetHold {
2698 admission,
2699 run: pass.run.clone(),
2700 pass: pass.pass_index,
2701 held_at: self.held_at.expect("hold timestamp just recorded"),
2702 decision: self.operator_decided_at,
2703 legacy: false,
2704 });
2705 }
2706 }
2707
2708 fn matches_budget_hold(&self, admission: &RecoveryAdmission) -> bool {
2709 self.status == TaskStatus::Held
2710 && self.hold_source == Some(HoldSource::Manual)
2711 && self.machine_hold_cause.is_none()
2712 && self.recovery_budget.as_ref().is_some_and(|budget| {
2713 budget.instruction == self.instruction
2714 && budget.base == admission.base
2715 && budget.inputs == admission.inputs
2716 && budget.stage == "execution"
2717 && budget.failures > 0
2718 && self
2719 .hold_reason
2720 .as_ref()
2721 .is_some_and(|reason| *reason == budget.budget_reason())
2722 })
2723 }
2724
2725 fn legacy_recovery_budget_hold(&self) -> Option<RecoveryBudgetHold> {
2726 let held_at = self.held_at?;
2727 let settled = self.passes.last()?;
2728 let admission = self.recovery_admission.as_ref()?;
2729 if !self.matches_budget_hold(admission)
2730 || self.execution_runs().last() != Some(&settled.run)
2731 || settled.cost != PassCost::Spent
2732 || settled.parked.is_some()
2733 || settled.settled_at > held_at
2734 || self.operator_decided_at.is_some_and(|at| at >= held_at)
2735 {
2736 return None;
2737 }
2738 Some(RecoveryBudgetHold {
2739 admission: admission.clone(),
2740 run: settled.run.clone(),
2741 pass: settled.pass_index,
2742 held_at,
2743 decision: self.operator_decided_at,
2744 legacy: true,
2745 })
2746 }
2747
2748 pub(crate) fn held_for_recovery_budget(&self, run: &crate::run::RunState) -> bool {
2749 let (Some(held_at), Some(settled), Some(pass), Some(admission)) = (
2750 self.held_at,
2751 self.passes.last(),
2752 run.passes.last(),
2753 self.recovery_admission.as_ref(),
2754 ) else {
2755 return false;
2756 };
2757 if !self.matches_budget_hold(admission)
2758 || self.execution_runs().last() != Some(&run.id)
2759 || settled.run != run.id
2760 || settled.pass_index != pass.index
2761 || settled.cost != PassCost::Spent
2762 || settled.parked.is_some()
2763 || settled.settled_at < pass.started_at
2764 || settled.settled_at > held_at
2765 || self.operator_decided_at.is_some_and(|at| at >= held_at)
2766 || !crate::daemon::compatible_run_instruction(run, self)
2767 {
2768 return false;
2769 }
2770 match &self.recovery_budget_hold {
2771 Some(hold) => {
2772 hold.run == run.id
2773 && hold.pass == pass.index
2774 && hold.held_at == held_at
2775 && hold.decision == self.operator_decided_at
2776 && &hold.admission == admission
2777 && (!hold.legacy
2778 || self
2779 .operator_decided_at
2780 .is_none_or(|at| at < pass.started_at))
2781 }
2782 None => {
2783 self.schema < RECOVERY_HOLD_SCHEMA
2784 && self
2785 .operator_decided_at
2786 .is_none_or(|at| at < pass.started_at)
2787 }
2788 }
2789 }
2790
2791 pub(crate) fn queue_repair(&mut self, receipt: &crate::repair_budget::Receipt) {
2792 self.stamp_schema();
2793 self.repair_grants.push(receipt.clone());
2794 self.status = TaskStatus::Queued;
2795 self.hold_source = None;
2796 self.hold_reason = None;
2797 self.held_at = None;
2798 self.recovery_budget_hold = None;
2799 self.resume_override = Some(OperatorResume {
2800 question_id: String::new(),
2801 at: receipt.at,
2802 conductor_rehold: None,
2803 forced: true,
2804 pinned_run: Some(receipt.request.run.clone()),
2805 });
2806 }
2807
2808 pub fn release(&mut self) {
2812 self.import_chat_notice();
2815 if self.hold_notice_cause.is_none()
2816 && matches!(self.status, TaskStatus::Held | TaskStatus::Blocked)
2817 {
2818 self.hold_notice_cause = Some(self.unresolved_hold_cause());
2819 }
2820 let refused_handover = self.status == TaskStatus::Held
2821 && self.hold_source == Some(HoldSource::Machine)
2822 && self.review_branch.is_some()
2823 && self
2824 .review_instruction
2825 .as_ref()
2826 .is_none_or(|i| *i == self.instruction);
2827 self.status = TaskStatus::Queued;
2828 self.held_at = None;
2829 self.attempts = 0;
2830 self.last_error = None;
2831 self.park_reason = None;
2832 self.hold_reason = None;
2835 self.hold_source = None;
2836 self.machine_hold_cause = None;
2837 self.disk_resume_run = None;
2838 self.disk_checked_at = None;
2839 self.diagnostic = None;
2840 self.blocked_by.clear();
2845 self.block_reason = None;
2846 self.blocked_from = None;
2847 if !refused_handover {
2851 self.review_branch = None;
2852 self.review_instruction = None;
2853 }
2854 self.fresh_start = false;
2855 }
2856}
2857
2858fn copy_new(dir: &Path, src: &Path, name: &str) -> Result<(String, PathBuf)> {
2862 use std::io::ErrorKind;
2863 let (stem, ext) = match name.rfind('.') {
2864 Some(i) if i > 0 => (&name[..i], &name[i..]),
2865 _ => (name, ""),
2866 };
2867 for n in 1u32.. {
2868 let candidate = if n == 1 {
2869 name.to_owned()
2870 } else {
2871 let suffix = format!("-{n}");
2872 let room = 64usize.saturating_sub(suffix.len() + ext.len());
2873 let stem: String = stem.chars().take(room).collect();
2874 format!("{stem}{suffix}{ext}")
2875 };
2876 if !crate::ask::valid_asset_name(&candidate) {
2877 bail!("no valid attachment name is left for `{name}`");
2878 }
2879 let path = dir.join(&candidate);
2880 match std::fs::OpenOptions::new()
2881 .write(true)
2882 .create_new(true)
2883 .open(&path)
2884 {
2885 Ok(mut out) => {
2886 let copied = std::fs::File::open(src)
2887 .and_then(|mut input| std::io::copy(&mut input, &mut out));
2888 if let Err(e) = copied {
2889 drop(out);
2890 let _ = std::fs::remove_file(&path);
2891 return Err(e).with_context(|| format!("copy {}", src.display()));
2892 }
2893 return Ok((candidate, path));
2894 }
2895 Err(e) if e.kind() == ErrorKind::AlreadyExists => continue,
2896 Err(e) => return Err(e).with_context(|| format!("create {}", path.display())),
2897 }
2898 }
2899 unreachable!("the counter never runs out")
2900}
2901
2902const TASK_LOCK_STALE: std::time::Duration = std::time::Duration::from_secs(10);
2905
2906pub(crate) struct TaskLock {
2909 path: PathBuf,
2910 token: String,
2911}
2912
2913fn owner_token() -> String {
2916 static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
2917 let n = COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2918 let mut r = crate::rng::SplitMix64::new(crate::rng::entropy() ^ n.rotate_left(32));
2919 format!("{}-{:016x}", std::process::id(), r.next_u64())
2920}
2921
2922fn break_marker(path: &Path, token: &str) -> PathBuf {
2925 let mut h: u64 = 0xcbf29ce484222325;
2926 for b in token.bytes() {
2927 h ^= u64::from(b);
2928 h = h.wrapping_mul(0x100000001b3);
2929 }
2930 let mut name = path.as_os_str().to_owned();
2931 name.push(format!(".break-{h:016x}"));
2932 PathBuf::from(name)
2933}
2934
2935fn older_than_stale(path: &Path) -> bool {
2936 std::fs::metadata(path)
2937 .and_then(|m| m.modified())
2938 .ok()
2939 .and_then(|t| t.elapsed().ok())
2940 .is_some_and(|age| age > TASK_LOCK_STALE)
2941}
2942
2943fn writer_may_be_gone(token: &str) -> bool {
2944 let Some(pid) = token
2945 .split_once('-')
2946 .and_then(|(pid, _)| pid.parse::<u32>().ok())
2947 else {
2948 return true;
2951 };
2952 if pid == std::process::id() {
2953 return false;
2954 }
2955 crate::proc::pid_status(pid) == Some(false)
2957}
2958
2959const MAX_MARKER_DEPTH: u8 = 3;
2963
2964fn take_marker(
2970 path: &Path,
2971 token: &str,
2972 depth: u8,
2973 retry: crate::lock_file::Retry,
2974) -> Option<(PathBuf, String)> {
2975 use std::io::Write;
2976 let marker = break_marker(path, token);
2977 for _ in 0..2 {
2978 match retry.create(&marker) {
2979 Ok(mut f) => {
2980 let mine = owner_token();
2981 if f.write_all(mine.as_bytes()).is_err() {
2982 drop(f);
2983 let _ = std::fs::remove_file(&marker);
2984 return None;
2985 }
2986 return Some((marker, mine));
2987 }
2988 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
2989 let judged = std::fs::read_to_string(&marker).ok();
2990 match judged.filter(|_| older_than_stale(&marker)) {
2991 Some(judged) if depth < MAX_MARKER_DEPTH => {
2992 remove_lock_if(&marker, &judged, true, depth + 1, retry)?;
2993 }
2994 _ => return None,
2995 }
2996 }
2997 Err(_) => return None,
2998 }
2999 }
3000 None
3001}
3002
3003fn remove_lock_if(
3008 path: &Path,
3009 token: &str,
3010 require_stale: bool,
3011 depth: u8,
3012 retry: crate::lock_file::Retry,
3013) -> Option<bool> {
3014 let (marker, mine) = take_marker(path, token, depth, retry)?;
3015 let still = std::fs::read_to_string(path).is_ok_and(|c| c == token)
3016 && (!require_stale || older_than_stale(path) && writer_may_be_gone(token));
3017 if still {
3018 let _ = std::fs::remove_file(path);
3019 }
3020 if depth >= MAX_MARKER_DEPTH {
3022 if std::fs::read_to_string(&marker).is_ok_and(|c| c == mine) {
3023 let _ = std::fs::remove_file(&marker);
3024 }
3025 } else {
3026 let _ = remove_lock_if(&marker, &mine, false, depth + 1, retry);
3027 }
3028 Some(still)
3029}
3030
3031#[cfg(test)]
3034fn break_stale(path: &Path, judged: &str) -> bool {
3035 break_stale_with(path, judged, crate::lock_file::Retry::new(None))
3036}
3037
3038fn break_stale_with(path: &Path, judged: &str, retry: crate::lock_file::Retry) -> bool {
3039 remove_lock_if(path, judged, true, 0, retry).unwrap_or(false)
3040}
3041
3042impl Drop for TaskLock {
3043 fn drop(&mut self) {
3044 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2);
3045 let retry = crate::lock_file::Retry::new(Some(deadline));
3046 loop {
3047 match remove_lock_if(&self.path, &self.token, false, 0, retry) {
3048 Some(_) => return,
3049 None if std::time::Instant::now() > deadline => return,
3050 None => std::thread::sleep(std::time::Duration::from_millis(5)),
3051 }
3052 }
3053 }
3054}
3055
3056#[derive(Debug, thiserror::Error)]
3057#[error("task changed during completion decision; reload and inspect it")]
3058pub(crate) struct CompletionSnapshotChanged;
3059
3060#[derive(Debug, Clone)]
3062pub struct Queue {
3063 root: PathBuf,
3064 ids: IdSource,
3065}
3066
3067fn validate_attachments(sources: &[PathBuf]) -> Result<Vec<(&PathBuf, &str)>> {
3068 let mut wanted = Vec::new();
3069 for src in sources {
3070 let name = src
3071 .file_name()
3072 .and_then(|n| n.to_str())
3073 .with_context(|| format!("`{}` has no usable file name", src.display()))?;
3074 if !crate::ask::valid_asset_name(name) {
3075 bail!(
3076 "attachment name `{name}` must match ^[A-Za-z0-9][A-Za-z0-9._-]{{0,63}}$ \
3077 with no `..`; rename the file and try again"
3078 );
3079 }
3080 if !src.is_file() {
3081 bail!("attachment `{}` is not a file", src.display());
3082 }
3083 wanted.push((src, name));
3084 }
3085 Ok(wanted)
3086}
3087
3088impl Queue {
3089 pub fn open() -> Self {
3091 Self::at(crate::run::home().join("queue"))
3092 }
3093
3094 pub fn at(root: PathBuf) -> Self {
3097 Self {
3098 root,
3099 ids: IdSource::new(new_id),
3100 }
3101 }
3102
3103 #[doc(hidden)]
3106 pub fn with_id_source(mut self, f: impl Fn() -> String + Send + Sync + 'static) -> Self {
3107 self.ids = IdSource::custom(f);
3108 self
3109 }
3110
3111 fn file_with(
3122 &self,
3123 task: &mut Task,
3124 hook: impl FnMut(&mut Task) -> Result<bool>,
3125 undo: impl FnMut(&mut Task),
3126 ) -> Result<()> {
3127 self.reserve_id(task, hook, undo, true)
3128 }
3129
3130 fn reserve_id(
3138 &self,
3139 task: &mut Task,
3140 mut hook: impl FnMut(&mut Task) -> Result<bool>,
3141 mut undo: impl FnMut(&mut Task),
3142 store: bool,
3143 ) -> Result<()> {
3144 let redraw_first = self.ids.is_custom() && task.attachments.is_empty();
3145 let initial = task.id.clone();
3146 self.ids
3147 .reserve((!redraw_first).then_some(initial.as_str()), "task", |id| {
3148 task.id = id.to_owned();
3149 let _lock = self.lock_task(&task.id)?;
3150 if path_exists(&self.path_of(&task.id))? || !hook(task)? {
3151 return Ok(false);
3152 }
3153 if store {
3154 if let Err(e) = self.write_record(task) {
3155 undo(task);
3156 return Err(e);
3157 }
3158 task.unfiled = false;
3159 }
3160 Ok(true)
3161 })?;
3162 Ok(())
3163 }
3164
3165 fn id_in_use(&self, id: &str, check_attachments: bool) -> Result<bool> {
3170 if path_exists(&self.lock_path(id))? {
3171 return Ok(true);
3172 }
3173 Ok(check_attachments && path_exists(&self.attachments_dir(id))?)
3174 }
3175
3176 fn plain_filing_hook(&self, task: &Task) -> Result<bool> {
3180 Ok(!self.id_in_use(&task.id, task.attachments.is_empty())?)
3181 }
3182
3183 pub fn file_claimed(&self, task: &mut Task) -> Result<Claim> {
3186 let mut claim = None;
3187 self.file_with(
3188 task,
3189 |t| {
3190 if self.id_in_use(&t.id, true)? {
3191 return Ok(false);
3192 }
3193 claim = Some(self.claim(&t.id)?);
3194 Ok(true)
3195 },
3196 |_| {},
3197 )?;
3198 claim.context("claim missing after filing")
3199 }
3200
3201 pub fn root(&self) -> &Path {
3203 &self.root
3204 }
3205
3206 pub fn path_of(&self, id: &str) -> PathBuf {
3208 self.root.join(format!("{id}.json"))
3209 }
3210
3211 pub fn attachments_dir(&self, id: &str) -> PathBuf {
3214 self.root.join(format!("{id}.attachments"))
3215 }
3216
3217 pub fn attach(&self, task: &mut Task, sources: &[PathBuf]) -> Result<Vec<String>> {
3228 let wanted = validate_attachments(sources)?;
3229 if task.unfiled && task.attachments.is_empty() {
3230 let names = std::cell::RefCell::new(Vec::new());
3233 self.reserve_id(
3234 task,
3235 |t| {
3236 if self.id_in_use(&t.id, true)? {
3237 return Ok(false);
3238 }
3239 *names.borrow_mut() = self.copy_attachments(t, &wanted)?;
3240 Ok(true)
3241 },
3242 |_| {},
3243 false,
3244 )?;
3245 return Ok(names.into_inner());
3246 }
3247 self.copy_attachments(task, &wanted)
3248 }
3249
3250 fn copy_attachments(
3252 &self,
3253 task: &mut Task,
3254 wanted: &[(&PathBuf, &str)],
3255 ) -> Result<Vec<String>> {
3256 let dir = self.attachments_dir(&task.id);
3257 let existed = dir.is_dir();
3258 std::fs::create_dir_all(&dir).with_context(|| format!("create {}", dir.display()))?;
3259 let mut created: Vec<PathBuf> = Vec::new();
3260 let mut names = Vec::new();
3261 let mut copy_all = || -> Result<()> {
3262 for (src, name) in wanted {
3263 let (stored, path) = copy_new(&dir, src, name)?;
3264 created.push(path);
3265 names.push(stored);
3266 }
3267 Ok(())
3268 };
3269 if let Err(e) = copy_all() {
3270 for path in &created {
3271 let _ = std::fs::remove_file(path);
3272 }
3273 if !existed {
3274 let _ = std::fs::remove_dir(&dir);
3275 }
3276 return Err(e);
3277 }
3278 task.attachments.extend(names.iter().cloned());
3279 Ok(names)
3280 }
3281
3282 pub fn attach_and_put(&self, task: &mut Task, sources: &[PathBuf]) -> Result<Vec<String>> {
3293 if task.unfiled && task.attachments.is_empty() {
3294 return self.attach_and_file(task, sources);
3295 }
3296 let dir = self.attachments_dir(&task.id);
3297 let existed = dir.is_dir();
3298 let before = task.attachments.len();
3299 let names = self.attach(task, sources)?;
3300 if let Err(e) = self.put(task) {
3301 for name in &names {
3302 let _ = std::fs::remove_file(dir.join(name));
3303 }
3304 if !existed {
3305 let _ = std::fs::remove_dir(&dir);
3306 }
3307 task.attachments.truncate(before);
3308 return Err(e);
3309 }
3310 Ok(names)
3311 }
3312
3313 fn attach_and_file(&self, task: &mut Task, sources: &[PathBuf]) -> Result<Vec<String>> {
3317 let wanted = validate_attachments(sources)?;
3318 let before = task.attachments.len();
3319 let names = std::cell::RefCell::new(Vec::new());
3320 let result = self.file_with(
3321 task,
3322 |t| {
3323 if self.id_in_use(&t.id, true)? {
3324 return Ok(false);
3325 }
3326 *names.borrow_mut() = self.copy_attachments(t, &wanted)?;
3327 Ok(true)
3328 },
3329 |t| {
3330 let dir = self.attachments_dir(&t.id);
3331 for name in names.borrow().iter() {
3332 let _ = std::fs::remove_file(dir.join(name));
3333 }
3334 let _ = std::fs::remove_dir(&dir);
3336 t.attachments.truncate(before);
3337 },
3338 );
3339 result.map(|()| names.into_inner())
3340 }
3341
3342 pub fn attachment_paths(&self, task: &Task) -> Vec<PathBuf> {
3346 let dir = self.attachments_dir(&task.id);
3347 task.attachments
3348 .iter()
3349 .map(|n| {
3350 let p = dir.join(n);
3351 std::path::absolute(&p).unwrap_or(p)
3352 })
3353 .collect()
3354 }
3355
3356 pub fn put(&self, task: &mut Task) -> Result<()> {
3365 if task.unfiled {
3366 return self.file_with(task, |t| self.plain_filing_hook(t), |_| {});
3368 }
3369 let _lock = self.lock_task(&task.id)?;
3370 self.put_unlocked(task)
3371 }
3372
3373 pub fn create_new(&self, task: &mut Task) -> Result<bool> {
3378 let _lock = self.lock_task(&task.id)?;
3379 if path_exists(&self.path_of(&task.id))? {
3380 return Ok(false);
3381 }
3382 self.write_record(task)?;
3383 task.unfiled = false;
3384 Ok(true)
3385 }
3386
3387 fn put_unlocked(&self, task: &mut Task) -> Result<()> {
3389 self.merge_stored(task);
3390 if let Some(boundary) = task.reassignments.last() {
3391 let stored = self.get(&task.id)?;
3392 anyhow::ensure!(
3393 task.reassignments == stored.reassignments
3394 && task.repo == stored.repo
3395 && task.runs.get(..boundary.run_boundary)
3396 == stored.runs.get(..boundary.run_boundary),
3397 "historical repository execution cannot be restarted; reload the task"
3398 );
3399 }
3400 self.write_record(task)
3401 }
3402
3403 pub(crate) fn commit_base_recovery(
3405 &self,
3406 task: &mut Task,
3407 expected: &serde_json::Value,
3408 ) -> Result<()> {
3409 let _lock = self.lock_task(&task.id)?;
3410 anyhow::ensure!(
3411 serde_json::to_value(self.get(&task.id)?)? == *expected,
3412 "task changed during base recovery; inspect the pending authorization"
3413 );
3414 self.put_unlocked(task)
3416 }
3417
3418 pub(crate) fn commit_land_sync_recovery(
3420 &self,
3421 task: &mut Task,
3422 expected: &serde_json::Value,
3423 ) -> Result<()> {
3424 let _lock = self.lock_task(&task.id)?;
3425 anyhow::ensure!(
3426 serde_json::to_value(self.get(&task.id)?)? == *expected,
3427 "task changed during landing base-sync recovery; inspect the pending authorization"
3428 );
3429 self.put_unlocked(task)
3430 }
3431
3432 pub(crate) fn commit_repair_grant(
3433 &self,
3434 task: &mut Task,
3435 expected: &serde_json::Value,
3436 ) -> Result<()> {
3437 let _lock = self.lock_task(&task.id)?;
3438 anyhow::ensure!(
3439 serde_json::to_value(self.get(&task.id)?)? == *expected,
3440 "repair grant refused: task changed during admission"
3441 );
3442 self.write_record(task)
3443 .context(crate::repair_budget::PublicationUnknown)
3444 }
3445
3446 pub(crate) fn commit_disk_wait(&self, task: &mut Task, expected: &Task) -> Result<()> {
3448 let _lock = self.lock_task(&task.id)?;
3449 anyhow::ensure!(
3450 serde_json::to_value(self.get(&task.id)?)? == serde_json::to_value(expected)?,
3451 "task changed during disk monitoring"
3452 );
3453 task.stamp_schema();
3454 self.write_record_inner(task, false)
3455 }
3456
3457 pub(crate) fn commit_reassignment(&self, task: &mut Task, expected: &Task) -> Result<()> {
3459 let _lock = self.lock_task(&task.id)?;
3460 let stored = self.get(&task.id)?;
3461 anyhow::ensure!(
3462 serde_json::to_value(&stored)? == serde_json::to_value(expected)?
3463 && stored.reassignments.len() + 1 == task.reassignments.len()
3464 && stored.repo == task.reassignments.last().expect("new boundary").from
3465 && stored.runs == task.runs,
3466 "task changed during reassignment; retry after inspecting it"
3467 );
3468 self.write_record(task)
3469 }
3470
3471 pub(crate) fn commit_completion(&self, task: &mut Task, expected: &Task) -> Result<()> {
3473 let _lock = self.lock_task(&task.id)?;
3474 anyhow::ensure!(
3475 serde_json::to_value(self.get(&task.id)?)? == serde_json::to_value(expected)?,
3476 CompletionSnapshotChanged
3477 );
3478 self.write_record(task)
3479 }
3480
3481 fn merge_stored(&self, task: &mut Task) {
3483 if let Ok(mut stored) = read_path(&self.path_of(&task.id)) {
3484 stored.import_chat_notice();
3485 let local_decision = task.completion_history.iter().any(|event| {
3488 !stored
3489 .completion_history
3490 .iter()
3491 .any(|saved| saved.occurrence == event.occurrence)
3492 && event.at > stored.updated_at
3493 });
3494 let unseen_decision = stored.completion_history.iter().any(|event| {
3495 !task
3496 .completion_history
3497 .iter()
3498 .any(|mine| mine.occurrence == event.occurrence)
3499 });
3500 let mut history = std::mem::take(&mut stored.completion_history);
3501 for event in std::mem::take(&mut task.completion_history) {
3502 if !history
3503 .iter()
3504 .any(|stored| stored.occurrence == event.occurrence)
3505 {
3506 history.push(event);
3507 }
3508 }
3509 if unseen_decision {
3510 task.import_chat_notice();
3513 let mut stale = std::mem::replace(task, stored);
3514 append_missing(&mut task.answers, stale.answers);
3515 if task.reassignments == stale.reassignments {
3516 append_missing(&mut task.runs, stale.runs);
3517 }
3518 for (ledger, entries) in [
3519 (&mut task.decision_effects, stale.decision_effects),
3520 (&mut task.superseded_resumes, stale.superseded_resumes),
3521 (&mut task.dispatched_resumes, stale.dispatched_resumes),
3522 ] {
3523 for (key, value) in entries {
3524 ledger.entry(key).or_insert(value);
3525 }
3526 }
3527 append_missing(&mut task.actions_applied, stale.actions_applied);
3528 append_missing(&mut task.triage_applied, stale.triage_applied);
3529 append_missing(&mut task.chat_notices, stale.chat_notices);
3530 append_missing(
3531 &mut task.base_recovery_requests,
3532 stale.base_recovery_requests,
3533 );
3534 append_missing(
3535 &mut task.land_sync_recovery_requests,
3536 stale.land_sync_recovery_requests,
3537 );
3538 prepend_missing_by(&mut task.repair_grants, stale.repair_grants, |a, b| {
3541 a.request.request == b.request.request
3542 });
3543 prepend_missing_by(
3544 &mut task.repair_reconciliations,
3545 stale.repair_reconciliations,
3546 |a, b| a.request.request == b.request.request,
3547 );
3548 stale.resumption_history.extend(stale.resumption);
3551 stale.resumption_history.retain(|approval| {
3552 task.resumption
3553 .as_ref()
3554 .is_none_or(|r| r.at != approval.at || r.generation != approval.generation)
3555 });
3556 prepend_missing_by(
3557 &mut task.resumption_history,
3558 stale.resumption_history,
3559 |a, b| a.at == b.at && a.generation == b.generation,
3560 );
3561 for failure in stale.startup_failures {
3562 task.record_startup_failure(failure);
3563 }
3564 for pass in stale.passes {
3565 if !task.passes.iter().any(|stored| {
3566 stored.run == pass.run && stored.pass_index == pass.pass_index
3567 }) {
3568 task.passes.push(pass);
3569 }
3570 }
3571 task.completion_history = history;
3572 if !task.decision_effects.is_empty() {
3573 task.stamp_schema();
3574 }
3575 return;
3576 }
3577 if stored.reassignments.len() > task.reassignments.len() {
3578 let stale = std::mem::replace(task, stored.clone());
3581 for answer in stale.answers {
3582 if !task.answers.contains(&answer) {
3583 task.answers.push(answer);
3584 }
3585 }
3586 }
3587 if task.updated_at < stored.updated_at
3590 && (task.sync_only != stored.sync_only
3591 || stored.sync_only.is_some()
3592 || stored
3593 .recovery_budget_hold
3594 .as_ref()
3595 .is_some_and(|hold| hold.held_at > task.updated_at)
3596 || stored.repair_grants.last().is_some_and(|grant| {
3597 task.repair_grants.last() != Some(grant)
3598 || stored.operator_decided_at > task.operator_decided_at
3599 || stored
3600 .resume_override
3601 .as_ref()
3602 .is_some_and(|pin| pin.at > task.updated_at)
3603 || (task.resume_override != stored.resume_override
3604 && task
3605 .resume_override
3606 .as_ref()
3607 .is_some_and(|pin| pin.at == grant.at))
3608 }))
3609 && task
3610 .operator_decided_at
3611 .is_none_or(|at| at <= stored.updated_at)
3612 && task
3613 .resume_override
3614 .as_ref()
3615 .is_none_or(|pin| pin.at <= stored.updated_at)
3616 && !local_decision
3617 {
3618 *task = stored.clone();
3619 }
3620 task.completion_history = history;
3621 append_missing(
3622 &mut task.base_recovery_requests,
3623 stored.base_recovery_requests,
3624 );
3625 append_missing(
3626 &mut task.land_sync_recovery_requests,
3627 stored.land_sync_recovery_requests,
3628 );
3629 append_missing(&mut task.actions_applied, stored.actions_applied);
3630 append_missing(&mut task.triage_applied, stored.triage_applied);
3631 for receipt in &stored.repair_grants {
3632 if !task
3633 .repair_grants
3634 .iter()
3635 .any(|r| r.request.request == receipt.request.request)
3636 {
3637 task.repair_grants.push(receipt.clone());
3639 }
3640 }
3641 for receipt in &stored.repair_reconciliations {
3642 if !task.repair_reconciliations.contains(receipt) {
3643 task.repair_reconciliations.push(receipt.clone());
3646 task.resume_override = stored.resume_override.clone();
3647 task.status = stored.status;
3648 task.hold_source = stored.hold_source;
3649 task.machine_hold_cause = stored.machine_hold_cause.clone();
3650 task.disk_resume_run = stored.disk_resume_run.clone();
3651 task.disk_checked_at = stored.disk_checked_at;
3652 task.hold_reason = stored.hold_reason.clone();
3653 task.held_at = stored.held_at;
3654 }
3655 }
3656 task.superseded_resumes.extend(stored.superseded_resumes);
3657 task.dispatched_resumes.extend(stored.dispatched_resumes);
3658 if task.status != TaskStatus::Running
3659 && let Some(pin) = &stored.resume_override
3660 && !pin.question_id.is_empty()
3661 && let Some(run) = &pin.pinned_run
3662 && task.resume_override.as_ref().is_none_or(|next| {
3663 next.question_id != pin.question_id || next.pinned_run != pin.pinned_run
3664 })
3665 {
3666 task.superseded_resumes
3667 .insert(pin.question_id.clone(), run.clone());
3668 }
3669 for (id, receipt) in stored.decision_effects {
3672 task.decision_effects.insert(id, receipt);
3673 }
3674 if !task.decision_effects.is_empty() {
3675 task.stamp_schema();
3676 }
3677 if task.chat.is_none() {
3680 task.chat = stored.chat.clone();
3681 }
3682 append_missing(&mut task.chat_notices, stored.chat_notices);
3683 for failure in stored.startup_failures {
3684 task.record_startup_failure(failure);
3685 }
3686 append_missing(&mut task.runs, stored.runs);
3687 for p in stored.passes {
3688 if !task
3689 .passes
3690 .iter()
3691 .any(|q| q.run == p.run && q.pass_index == p.pass_index)
3692 {
3693 task.passes.push(p);
3694 }
3695 }
3696 if let Some(n) = stored.chat_notice
3699 && task.chat_notice.as_ref().is_none_or(|mine| mine.at < n.at)
3700 {
3701 task.chat_notice = Some(n);
3702 }
3703 }
3704 }
3705
3706 pub(crate) fn write_startup_history(&self, task: &Task) -> Result<()> {
3709 let path = self.path_of(&task.id);
3710 let tmp = path.with_extension("json.tmp");
3711 std::fs::write(&tmp, serde_json::to_vec_pretty(task)?)?;
3712 std::fs::rename(tmp, path)?;
3713 Ok(())
3714 }
3715
3716 fn write_record(&self, task: &mut Task) -> Result<()> {
3718 self.write_record_inner(task, true)
3719 }
3720
3721 fn write_record_inner(&self, task: &mut Task, notify: bool) -> Result<()> {
3722 task.import_chat_notice();
3723 if task.status != TaskStatus::Held && task.sync_only.is_none() {
3724 task.recovery_budget_hold = None;
3725 }
3726 task.updated_at = Timestamp::now();
3727 std::fs::create_dir_all(&self.root)
3728 .with_context(|| format!("create {}", self.root.display()))?;
3729 let body = serde_json::to_string_pretty(task).context("serialize task")?;
3730 let path = self.path_of(&task.id);
3731 let tmp = path.with_extension("json.tmp");
3732 std::fs::write(&tmp, &body).with_context(|| format!("write {}", tmp.display()))?;
3733 std::fs::rename(&tmp, &path).with_context(|| format!("replace {}", path.display()))?;
3734 if let (Some(notice), Some(home)) = (
3739 notify.then(|| crate::notices::task_held(task)).flatten(),
3740 self.root.parent().filter(|p| !p.as_os_str().is_empty()),
3741 ) {
3742 crate::notices::raise_in(home, notice);
3743 }
3744 Ok(())
3745 }
3746
3747 pub fn modify(&self, id: &str, f: impl FnOnce(&mut Task) -> bool) -> Result<bool> {
3752 let id = self.resolve_id(id)?;
3753 let _lock = self.lock_task(&id)?;
3754 let mut task = self.get(&id)?;
3755 if !f(&mut task) {
3756 return Ok(false);
3757 }
3758 self.put_unlocked(&mut task)?;
3759 Ok(true)
3760 }
3761
3762 pub fn link_run(&self, id: &str, run: &str) -> Result<Task> {
3767 let id = self.resolve_id(id)?;
3768 let _lock = self.lock_task(&id)?;
3771 let mut task = self.get(&id)?;
3772 if task.link_run(run) {
3773 self.put_unlocked(&mut task)?;
3774 }
3775 Ok(task)
3776 }
3777
3778 pub(crate) fn lock_task(&self, id: &str) -> Result<TaskLock> {
3786 std::fs::create_dir_all(&self.root)
3787 .with_context(|| format!("create {}", self.root.display()))?;
3788 let path = self.root.join(format!("{id}.write-lock"));
3789 let started = std::time::Instant::now();
3790 let retry = crate::lock_file::Retry::task_write(started + TASK_LOCK_STALE);
3791 let marker_retry = crate::lock_file::Retry::new(Some(started + TASK_LOCK_STALE));
3792 loop {
3793 match retry.create(&path) {
3794 Ok(mut file) => {
3795 use std::io::Write;
3796 let token = owner_token();
3797 if let Err(e) = file.write_all(token.as_bytes()) {
3798 drop(file);
3799 let _ = std::fs::remove_file(&path);
3800 return Err(e).with_context(|| format!("lock {}", path.display()));
3801 }
3802 return Ok(TaskLock { path, token });
3803 }
3804 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
3805 let judged = std::fs::read_to_string(&path).ok();
3808 let broken = judged
3809 .filter(|_| older_than_stale(&path))
3810 .is_some_and(|judged| break_stale_with(&path, &judged, marker_retry));
3811 if !broken {
3815 if started.elapsed() > TASK_LOCK_STALE {
3816 bail!("could not lock task {id}");
3817 }
3818 std::thread::sleep(std::time::Duration::from_millis(15));
3819 }
3820 }
3821 Err(e) => return Err(e).with_context(|| format!("lock {}", path.display())),
3822 }
3823 }
3824 }
3825
3826 pub fn get(&self, id: &str) -> Result<Task> {
3828 let resolved = self.resolve_id(id)?;
3829 read_path(&self.path_of(&resolved))
3830 }
3831
3832 pub fn remove(&self, id: &str, in_flight: bool, questions: &Questions) -> Result<Removal> {
3864 self.remove_with_receipt(id, in_flight, questions, None)
3865 }
3866
3867 pub(crate) fn discard_triage(
3869 &self,
3870 id: &str,
3871 questions: &Questions,
3872 inquiry: &str,
3873 ) -> Result<Removal> {
3874 self.remove_with_receipt(id, false, questions, Some(inquiry))
3875 }
3876
3877 pub(crate) fn triage_discard_applied(&self, id: &str, inquiry: &str) -> Result<bool> {
3878 let path = self
3879 .root
3880 .join("triage-discard")
3881 .join(format!("{inquiry}.json"));
3882 let bytes = match std::fs::read(path) {
3883 Ok(bytes) => bytes,
3884 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(false),
3885 Err(e) => return Err(e.into()),
3886 };
3887 let receipt: Task = serde_json::from_slice(&bytes)?;
3888 Ok(receipt.id == id && !self.path_of(id).exists())
3889 }
3890
3891 fn remove_with_receipt(
3892 &self,
3893 id: &str,
3894 in_flight: bool,
3895 questions: &Questions,
3896 inquiry: Option<&str>,
3897 ) -> Result<Removal> {
3898 let resolved = self.resolve_id(id)?;
3899 if in_flight {
3900 bail!("task {resolved} is being run by a live daemon right now");
3901 }
3902 let receipt = inquiry.map(|q| self.root.join("triage-discard").join(format!("{q}.json")));
3903 if let Some(path) = &receipt {
3904 std::fs::create_dir_all(path.parent().expect("receipt directory"))?;
3905 }
3906 self.write_tombstone(&resolved)?;
3907 if let Err(e) = self.remove_record_with_attachments(&resolved, |p| match &receipt {
3908 Some(path) => std::fs::rename(p, path),
3909 None => std::fs::remove_file(p),
3910 }) {
3911 if self.path_of(&resolved).exists() {
3915 let _ = std::fs::remove_file(self.tombstone_path(&resolved));
3916 }
3917 return Err(e);
3918 }
3919 let (released, still_blocked) = self.release_dependents_of(&resolved, questions);
3920 Ok(Removal {
3921 id: resolved,
3922 released,
3923 still_blocked,
3924 })
3925 }
3926
3927 fn tombstone_path(&self, id: &str) -> PathBuf {
3930 self.root.join(format!("{id}.removed"))
3931 }
3932
3933 fn write_tombstone(&self, id: &str) -> Result<()> {
3934 let path = self.tombstone_path(id);
3935 let tmp = self.root.join(format!("{id}.removed.tmp"));
3936 std::fs::write(&tmp, b"")
3937 .and_then(|()| std::fs::rename(&tmp, &path))
3938 .with_context(|| format!("write {}", path.display()))
3939 }
3940
3941 fn was_deleted(&self, id: &str) -> bool {
3945 self.tombstone_path(id).is_file() && !self.path_of(id).exists()
3946 }
3947
3948 pub fn apply_deleted_blockers(&self, task: &mut Task, questions: &Questions) -> Vec<String> {
3952 let deleted = deleted_blockers(self, questions, &task.blocked_by);
3953 deleted
3954 .into_iter()
3955 .filter(|id| task.dependency_deleted(id))
3956 .collect()
3957 }
3958
3959 pub fn note_dependency_deleted(&self, dependent: &Task, deleted: &str) {
3963 let Some(home) = self.root.parent().filter(|p| !p.as_os_str().is_empty()) else {
3964 return;
3965 };
3966 let ja = crate::lang::is_japanese(&crate::lang::of_repo(&dependent.repo));
3967 let waiting = dependent.status == TaskStatus::Blocked;
3968 let message = match (ja, waiting) {
3969 (true, false) => format!(
3970 "タスク {} は、待っていた {} が削除されたため待機を解除し、元の状態に戻しました",
3971 dependent.short(),
3972 short(deleted)
3973 ),
3974 (true, true) => format!(
3975 "タスク {} は、待っていた {} が削除されたため、残りの依存を待っています",
3976 dependent.short(),
3977 short(deleted)
3978 ),
3979 (false, false) => format!(
3980 "Task {} stopped waiting on {} because it was deleted, and returned to its previous state",
3981 dependent.short(),
3982 short(deleted)
3983 ),
3984 (false, true) => format!(
3985 "Task {} stopped waiting on {} because it was deleted, and is still waiting on its other dependencies",
3986 dependent.short(),
3987 short(deleted)
3988 ),
3989 };
3990 crate::notices::raise_in(
3991 home,
3992 crate::notices::Notice::info(
3993 &format!("unblocked:{}:{}", dependent.id, deleted),
3994 message,
3995 )
3996 .link(crate::notices::Link::Task {
3997 id: dependent.id.clone(),
3998 }),
3999 );
4000 }
4001
4002 fn release_dependents_of(
4007 &self,
4008 dependency: &str,
4009 questions: &Questions,
4010 ) -> (Vec<String>, Vec<String>) {
4011 let (mut released, mut still_blocked) = (Vec::new(), Vec::new());
4012 for listed in self.list() {
4013 if listed.status != TaskStatus::Blocked || !listed.blocked_by.iter().any(|b| {
4014 matches!(crate::queue::dependency(self, questions, b), Dependency::Deleted(id) if id == dependency)
4015 }) {
4016 continue;
4017 }
4018 let Ok(_claim) = self.claim(&listed.id) else {
4019 continue;
4020 };
4021 let Ok(mut task) = self.get(&listed.id) else {
4022 continue;
4023 };
4024 let references: Vec<String> = task.blocked_by.iter().filter(|id| {
4025 matches!(crate::queue::dependency(self, questions, id), Dependency::Deleted(full) if full == dependency)
4026 }).cloned().collect();
4027 if references.is_empty() {
4028 continue;
4029 }
4030 for reference in references {
4031 task.dependency_deleted(&reference);
4032 }
4033 if self.put(&mut task).is_err() {
4034 continue;
4035 }
4036 self.note_dependency_deleted(&task, dependency);
4037 if task.status == TaskStatus::Blocked {
4038 still_blocked.push(task.id.clone());
4039 } else {
4040 released.push(task.id.clone());
4041 }
4042 }
4043 (released, still_blocked)
4044 }
4045
4046 fn remove_record_with_attachments(
4050 &self,
4051 resolved: &str,
4052 remove_record: impl FnOnce(&Path) -> std::io::Result<()>,
4053 ) -> Result<()> {
4054 self.sweep_removed_attachments();
4061 let attachments = self.attachments_dir(resolved);
4062 let aside = self.root.join(format!("{resolved}.attachments.removing"));
4063 let moved = match std::fs::rename(&attachments, &aside) {
4064 Ok(()) => true,
4065 Err(e) if e.kind() == std::io::ErrorKind::NotFound => false,
4066 Err(e) => {
4067 return Err(e).with_context(|| format!("remove {}", attachments.display()));
4068 }
4069 };
4070 let path = self.path_of(resolved);
4071 if let Err(e) = remove_record(&path) {
4072 if moved {
4073 let _ = std::fs::rename(&aside, &attachments);
4074 }
4075 return Err(e).with_context(|| format!("remove {}", path.display()));
4076 }
4077 if moved {
4078 if let Err(e) = std::fs::remove_dir_all(&aside) {
4079 tracing::warn!("leftover attachments {}: {e}", aside.display());
4080 }
4081 }
4082 let lock = self.lock_path(resolved);
4083 if let Err(e) = std::fs::remove_file(&lock) {
4084 if e.kind() != std::io::ErrorKind::NotFound {
4085 return Err(e).with_context(|| format!("remove {}", lock.display()));
4086 }
4087 }
4088 Ok(())
4089 }
4090
4091 fn sweep_removed_attachments(&self) {
4097 let Ok(entries) = std::fs::read_dir(&self.root) else {
4098 return;
4099 };
4100 for entry in entries.flatten() {
4101 let name = entry.file_name();
4102 let name = name.to_string_lossy();
4103 let Some(id) = name.strip_suffix(".attachments.removing") else {
4104 continue;
4105 };
4106 if !self.path_of(id).exists() {
4109 if let Err(e) = std::fs::remove_dir_all(entry.path()) {
4110 tracing::warn!("leftover attachments {}: {e}", entry.path().display());
4111 }
4112 }
4113 }
4114 self.sweep_tombstones();
4115 }
4116
4117 fn sweep_tombstones(&self) {
4126 let Ok(entries) = std::fs::read_dir(&self.root) else {
4127 return;
4128 };
4129 let tasks = self.list();
4130 for entry in entries.flatten() {
4131 let name = entry.file_name();
4132 let name = name.to_string_lossy();
4133 let Some(id) = name.strip_suffix(".removed") else {
4134 continue;
4135 };
4136 if self.path_of(id).exists()
4137 || tasks.iter().any(|t| {
4138 t.blocked_by
4139 .iter()
4140 .any(|b| id.starts_with(b) || id.ends_with(b))
4141 })
4142 {
4143 continue;
4144 }
4145 let old = entry
4146 .metadata()
4147 .and_then(|m| m.modified())
4148 .ok()
4149 .and_then(|m| m.elapsed().ok())
4150 .is_some_and(|age| age >= TOMBSTONE_GRACE);
4151 if old {
4152 let _ = std::fs::remove_file(entry.path());
4153 }
4154 }
4155 }
4156
4157 fn lock_path(&self, id: &str) -> PathBuf {
4160 self.root.join(format!("{id}.lock"))
4161 }
4162
4163 pub fn list(&self) -> Vec<Task> {
4176 #[cfg(test)]
4177 LIST_READS.with(|count| count.set(count.get() + 1));
4178 let mut tasks: Vec<Task> = std::fs::read_dir(&self.root)
4179 .into_iter()
4180 .flatten()
4181 .flatten()
4182 .map(|e| e.path())
4183 .filter(|p| p.extension().is_some_and(|x| x == "json"))
4184 .filter_map(|p| read_path(&p).ok())
4185 .collect();
4186 tasks.sort_unstable_by(|a, b| b.priority.cmp(&a.priority).then_with(|| b.id.cmp(&a.id)));
4187 tasks
4188 }
4189
4190 pub fn unreadable(&self) -> Vec<PathBuf> {
4194 std::fs::read_dir(&self.root)
4195 .into_iter()
4196 .flatten()
4197 .flatten()
4198 .map(|e| e.path())
4199 .filter(|p| p.extension().is_some_and(|x| x == "json"))
4200 .filter(|p| read_path(p).is_err())
4201 .collect()
4202 }
4203
4204 pub fn superseded(&self) -> HashMap<String, String> {
4217 let mut by = HashMap::new();
4218 for task in self.list() {
4219 for earlier in &task.runs {
4220 if let Some(later) = task.successor_of(earlier) {
4221 by.insert(earlier.clone(), later.clone());
4222 }
4223 }
4224 }
4225 by
4226 }
4227
4228 pub fn superseded_by(&self, run: &str) -> Option<String> {
4236 for task in self.list() {
4237 if task.runs.iter().any(|r| r == run) {
4238 return task.successor_of(run).cloned();
4239 }
4240 }
4241 None
4242 }
4243
4244 pub fn latest_attempt(&self, run: &str) -> Option<String> {
4255 for task in self.list() {
4256 if task.runs.iter().any(|r| r == run) {
4257 return task.runs.last().filter(|last| **last != run).cloned();
4258 }
4259 }
4260 None
4261 }
4262
4263 pub fn next_runnable(&self) -> Option<Task> {
4268 let mut runnable: Vec<Task> = self
4269 .list()
4270 .into_iter()
4271 .filter(|t| t.status.runnable())
4272 .collect();
4273 runnable.sort_unstable_by(dispatch_order);
4274 runnable.into_iter().next()
4275 }
4276
4277 pub fn claim(&self, id: &str) -> Result<Claim> {
4284 std::fs::create_dir_all(&self.root)
4285 .with_context(|| format!("create {}", self.root.display()))?;
4286 let path = self.lock_path(id);
4287 let retry = crate::lock_file::Retry::new(None);
4288 match retry.create(&path) {
4289 Ok(mut f) => {
4290 use std::io::Write as _;
4291 let _ = writeln!(f, "{}", std::process::id());
4293 Ok(Claim { path })
4294 }
4295 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
4296 bail!("task {id} is already claimed ({} exists)", path.display())
4297 }
4298 Err(e) => Err(e).with_context(|| format!("lock {}", path.display())),
4299 }
4300 }
4301
4302 #[must_use]
4305 pub fn is_claimed(&self, id: &str) -> bool {
4306 self.lock_path(id).exists()
4307 }
4308
4309 pub fn resolve_id(&self, prefix: &str) -> Result<String> {
4311 if !prefix.is_empty()
4312 && prefix != "."
4313 && prefix != ".."
4314 && !prefix.contains(['/', '\\'])
4315 && self.path_of(prefix).is_file()
4316 {
4317 return Ok(prefix.to_owned());
4318 }
4319 let ids = record_ids(&self.root, "json")?;
4320 match resolve_reference(prefix, ids.iter().map(String::as_str)) {
4321 Reference::Found(id) => Ok(id),
4322 Reference::Missing => bail!("no task matches `{prefix}`"),
4323 Reference::Ambiguous => bail!("`{prefix}` matches multiple tasks"),
4324 }
4325 }
4326
4327 pub fn revision(&self) -> u64 {
4334 self.revision_excluding(&std::collections::BTreeSet::new())
4335 }
4336
4337 pub fn revision_excluding(&self, skip: &std::collections::BTreeSet<String>) -> u64 {
4340 use std::hash::{Hash as _, Hasher as _};
4341
4342 let mut entries: Vec<(String, u64)> = std::fs::read_dir(&self.root)
4343 .into_iter()
4344 .flatten()
4345 .flatten()
4346 .filter(|e| e.path().extension().is_some_and(|ext| ext == "json"))
4347 .filter(|e| {
4348 let path = e.path();
4349 !path
4350 .file_stem()
4351 .is_some_and(|stem| skip.contains(stem.to_string_lossy().as_ref()))
4352 })
4353 .filter_map(|e| {
4354 let name = e.file_name().to_string_lossy().into_owned();
4355 let mtime = e
4356 .metadata()
4357 .ok()?
4358 .modified()
4359 .ok()?
4360 .duration_since(std::time::UNIX_EPOCH)
4361 .ok()?
4362 .as_millis() as u64;
4363 Some((name, mtime))
4364 })
4365 .collect();
4366
4367 if entries.is_empty() {
4368 return 0;
4369 }
4370
4371 entries.sort_unstable();
4372 let mut hasher = std::hash::DefaultHasher::new();
4373 for (name, mtime) in &entries {
4374 name.hash(&mut hasher);
4375 mtime.hash(&mut hasher);
4376 }
4377 let h = hasher.finish();
4378 if h == 0 { 1 } else { h }
4379 }
4380}
4381
4382const TOMBSTONE_GRACE: std::time::Duration = std::time::Duration::from_secs(3600);
4385
4386#[derive(Debug, Clone)]
4388pub struct Removal {
4389 pub id: String,
4391 pub released: Vec<String>,
4395 pub still_blocked: Vec<String>,
4398}
4399
4400#[derive(Debug)]
4402pub struct Claim {
4403 path: PathBuf,
4404}
4405
4406impl Drop for Claim {
4407 fn drop(&mut self) {
4408 let _ = std::fs::remove_file(&self.path);
4409 }
4410}
4411
4412pub fn title_from(instruction: &str, max: usize) -> String {
4415 let Some(line) = first_line(instruction) else {
4416 return "(empty task)".to_owned();
4417 };
4418 if line.chars().count() <= max {
4419 return line.to_owned();
4420 }
4421 let head: String = line.chars().take(max.saturating_sub(1)).collect();
4422 format!("{head}…")
4423}
4424
4425pub(crate) fn first_line(instruction: &str) -> Option<&str> {
4431 let line = instruction
4432 .lines()
4433 .map(str::trim)
4434 .find(|l| !l.is_empty())?
4435 .trim_start_matches(['#', '-', '*', '>', ' '])
4436 .trim();
4437 (!line.is_empty()).then_some(line)
4438}
4439
4440#[cfg(test)]
4441thread_local! {
4442 pub(crate) static TASK_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4443}
4444
4445fn read_path(path: &Path) -> Result<Task> {
4446 #[cfg(test)]
4447 TASK_READS.with(|count| count.set(count.get() + 1));
4448 let body = std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;
4449 let mut task: Task =
4450 serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))?;
4451 if task.schema > SCHEMA {
4457 bail!(
4458 "task {} was written by a different magi (schema {}, this build \
4459 speaks {SCHEMA})",
4460 task.id,
4461 task.schema
4462 );
4463 }
4464 task.preserve_legacy_build_cache();
4465 if task.schema < 22
4466 && task.status == TaskStatus::Held
4467 && task.hold_source == Some(HoldSource::Machine)
4468 && task.resume_override.is_none()
4469 && task
4470 .hold_reason
4471 .as_deref()
4472 .is_some_and(crate::disk::is_gate_reason)
4473 {
4474 task.mark_disk_capacity();
4475 }
4476 Ok(task)
4477}
4478
4479#[derive(Debug, PartialEq, Eq)]
4482pub(crate) enum Reference {
4483 Found(String),
4484 Missing,
4485 Ambiguous,
4486}
4487
4488pub(crate) fn resolve_reference<'a>(id: &str, ids: impl Iterator<Item = &'a str>) -> Reference {
4489 let mut hits = Vec::new();
4490 for candidate in ids {
4491 if candidate == id {
4492 return Reference::Found(candidate.to_owned());
4493 }
4494 if candidate.starts_with(id) || candidate.ends_with(id) {
4495 hits.push(candidate);
4496 }
4497 }
4498 match hits.as_slice() {
4499 [] => Reference::Missing,
4500 [one] => Reference::Found((*one).to_owned()),
4501 _ => Reference::Ambiguous,
4502 }
4503}
4504
4505pub(crate) fn record_ids(root: &Path, extension: &str) -> Result<Vec<String>> {
4508 let entries = match std::fs::read_dir(root) {
4509 Ok(entries) => entries,
4510 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
4511 Err(e) => return Err(e.into()),
4512 };
4513 let mut ids = Vec::new();
4514 for entry in entries {
4515 let path = entry?.path();
4516 if path.extension().is_some_and(|e| e == extension)
4517 && let Some(id) = path.file_stem().and_then(|s| s.to_str())
4518 {
4519 ids.push(id.to_owned());
4520 }
4521 }
4522 Ok(ids)
4523}
4524
4525#[derive(Debug, PartialEq, Eq)]
4528pub enum Dependency {
4529 Task(String),
4531 Question(String),
4533 Deleted(String),
4535 Missing,
4537 Ambiguous,
4539 Unknown,
4541}
4542
4543pub fn dependency(queue: &Queue, questions: &Questions, id: &str) -> Dependency {
4545 let (Ok(tasks), Ok(qs), Ok(removed)) = (
4546 record_ids(queue.root(), "json"),
4547 record_ids(questions.root(), "json"),
4548 record_ids(queue.root(), "removed"),
4549 ) else {
4550 return Dependency::Unknown;
4551 };
4552 let mut ids = tasks
4555 .iter()
4556 .chain(qs.iter())
4557 .chain(removed.iter())
4558 .cloned()
4559 .collect::<Vec<_>>();
4560 ids.sort();
4561 ids.dedup();
4562 match resolve_reference(id, ids.iter().map(String::as_str)) {
4563 Reference::Found(id) if tasks.contains(&id) => Dependency::Task(id),
4564 Reference::Found(id) if qs.contains(&id) => Dependency::Question(id),
4565 Reference::Found(id) if queue.was_deleted(&id) => Dependency::Deleted(id),
4566 Reference::Found(_) => Dependency::Unknown,
4567 Reference::Missing => Dependency::Missing,
4568 Reference::Ambiguous => Dependency::Ambiguous,
4569 }
4570}
4571
4572pub fn normalize_blockers(queue: &Queue, questions: &Questions, ids: &mut [String]) {
4574 for id in ids {
4575 if let Dependency::Task(full) | Dependency::Question(full) | Dependency::Deleted(full) =
4576 dependency(queue, questions, id)
4577 {
4578 *id = full;
4579 }
4580 }
4581}
4582
4583pub fn dependency_facts(queue: &Queue, questions: &Questions) -> String {
4586 let inventory = crate::blockers::Inventory::load(queue, questions);
4587 let mut text = String::from(
4588 "Current authoritative queue (historical missing-task claims may be stale; unreadable or ambiguous references must keep waiting):\n",
4589 );
4590 match record_ids(queue.root(), "json") {
4591 Ok(ids) => {
4592 for id in ids {
4593 match queue.get(&id) {
4594 Ok(task) => text.push_str(&format!(
4595 "{}: {}; blocked_by={:?}; chain={:?}\n",
4596 task.id,
4597 task.status.as_str(),
4598 task.blocked_by,
4599 inventory.waits_on(&task)
4600 )),
4601 Err(_) => text.push_str(&format!("{id}: exists, state unreadable\n")),
4602 }
4603 }
4604 }
4605 Err(_) => text.push_str("Queue inventory unreadable: existence is unknown.\n"),
4606 }
4607 text
4608}
4609
4610pub fn missing_blockers(
4612 queue: &Queue,
4613 questions: &Questions,
4614 blocked_by: &[String],
4615) -> Vec<String> {
4616 blocked_by
4617 .iter()
4618 .filter(|id| dependency(queue, questions, id) == Dependency::Missing)
4619 .cloned()
4620 .collect()
4621}
4622
4623pub fn deleted_blockers(
4626 queue: &Queue,
4627 questions: &Questions,
4628 blocked_by: &[String],
4629) -> Vec<String> {
4630 blocked_by
4631 .iter()
4632 .filter(|id| matches!(dependency(queue, questions, id), Dependency::Deleted(_)))
4633 .cloned()
4634 .collect()
4635}
4636
4637pub fn missing_blocker_hold_reason(blocked_by: &[String], missing: &[String]) -> String {
4649 missing_blocker_hold_reason_in(blocked_by, missing, "en")
4650}
4651
4652pub fn missing_blocker_hold_reason_in(
4654 blocked_by: &[String],
4655 missing: &[String],
4656 language: &str,
4657) -> String {
4658 if crate::lang::is_japanese(language) {
4659 format!(
4660 "{} を待っていましたが、{} はディスク上に存在しません - `magi task triage` を参照",
4661 blocked_by.join(", "),
4662 missing.join(", "),
4663 )
4664 } else {
4665 format!(
4666 "blocked on {} but {} no longer exist(s) on disk - see `magi task triage`",
4667 blocked_by.join(", "),
4668 missing.join(", "),
4669 )
4670 }
4671}
4672
4673pub fn short(id: &str) -> &str {
4675 id.split('-').next_back().unwrap_or(id)
4676}
4677
4678fn new_id() -> String {
4679 let stamp = jiff::Zoned::now().strftime("%Y%m%d-%H%M%S");
4680 let seed = crate::rng::entropy();
4681 format!("{stamp}-{:04x}", (seed ^ (seed >> 32)) & 0xffff)
4682}
4683
4684#[cfg(test)]
4685mod tests {
4686 #[test]
4687 fn reassignment_clears_repository_bound_execution_selections() {
4688 let mut task = Task::new(
4689 "move".into(),
4690 "evidence".into(),
4691 "old".into(),
4692 Source::Human,
4693 );
4694 task.review_branch = Some("old-review".into());
4695 task.review_instruction = Some("old criteria".into());
4696 task.pr_recovery = Some(crate::pr_recovery::Selection {
4697 url: "https://example.invalid/pull/1".into(),
4698 branch: "old-pr".into(),
4699 head: "head".into(),
4700 source_head: None,
4701 source_run: None,
4702 source_proof: None,
4703 disposition: None,
4704 instruction: "old criteria".into(),
4705 approved_at: Timestamp::now(),
4706 });
4707 task.replacement = Some(crate::merge_decision::Replacement {
4708 question: "owner".into(),
4709 run: "old-run".into(),
4710 pr: "https://example.invalid/pull/1".into(),
4711 agent: "worker".into(),
4712 context: "evidence".into(),
4713 });
4714 task.resume_override = Some(OperatorResume {
4715 question_id: "old-question".into(),
4716 at: Timestamp::now(),
4717 conductor_rehold: None,
4718 forced: true,
4719 pinned_run: Some("old-run".into()),
4720 });
4721 task.interrupt = true;
4722 task.reassign_repository("new".into(), "test");
4723 assert!(task.review_branch.is_none());
4724 assert!(task.review_instruction.is_none());
4725 assert!(task.pr_recovery.is_none());
4726 assert!(task.replacement.is_none());
4727 assert!(task.resume_override.is_none());
4728 assert!(!task.interrupt);
4729 assert!(task.fresh_start);
4730 assert_eq!(task.instruction, "evidence");
4731 }
4732
4733 #[test]
4734 fn explicit_resumption_is_not_invented_for_legacy_or_automatic_release() {
4735 let t = Task::new(
4736 "retry".into(),
4737 "do it".into(),
4738 PathBuf::from("."),
4739 Source::Human,
4740 );
4741 let mut value = serde_json::to_value(&t).unwrap();
4742 for field in ["resumption", "resumption_history", "operator_decided_at"] {
4743 value.as_object_mut().unwrap().remove(field);
4744 }
4745 value["schema"] = serde_json::json!(15);
4746 let mut legacy: Task = serde_json::from_value(value).unwrap();
4747 legacy.hold_machine(Some("automatic retry".into()));
4748 legacy.release();
4749 assert!(legacy.resumption.is_none());
4750 assert!(legacy.resumption_history.is_empty());
4751 assert!(legacy.operator_decided_at.is_none());
4752 legacy.release_operator("cli", None);
4753 legacy.start("run".into());
4754 let reloaded: Task =
4755 serde_json::from_str(&serde_json::to_string(&legacy).unwrap()).unwrap();
4756 assert!(reloaded.resume_override.is_none());
4757 assert_eq!(reloaded.resumption.as_ref().unwrap().generation, 1);
4758 }
4759
4760 #[test]
4761 fn merge_over_lets_the_later_choice_win_and_keeps_the_rest() {
4762 let mut base = RunOverrides {
4763 merge: Some("pr".to_owned()),
4764 candidates: Some(3),
4765 ..RunOverrides::default()
4766 };
4767 base.merge_over(&RunOverrides {
4768 merge: Some("none".to_owned()),
4769 seed: Some(7),
4770 ..RunOverrides::default()
4771 });
4772 assert_eq!(base.merge.as_deref(), Some("none"));
4773 assert_eq!(base.candidates, Some(3));
4774 assert_eq!(base.seed, Some(7));
4775 }
4776
4777 #[test]
4778 fn an_already_landed_task_is_done_with_its_attempt_refunded() {
4779 let mut t = task("relanded");
4780 t.attempts = 1;
4781 t.status = TaskStatus::Running;
4782 t.already_landed("already in main as 0e368de", completion(&t));
4783 assert_eq!(t.status, TaskStatus::Done);
4784 assert_eq!(t.attempts, 0);
4785 assert!(t.hold_reason.is_none());
4786 assert_eq!(t.last_error.as_deref(), Some("already in main as 0e368de"));
4787 }
4788
4789 #[test]
4790 fn missing_blocker_reason_follows_the_language() {
4791 let b = vec!["a".to_owned()];
4792 let en = missing_blocker_hold_reason_in(&b, &b, "en");
4793 assert_eq!(en, missing_blocker_hold_reason(&b, &b));
4794 assert!(en.starts_with("blocked on a"));
4795 assert!(missing_blocker_hold_reason_in(&b, &b, "ja").contains("存在しません"));
4796 assert_eq!(missing_blocker_hold_reason_in(&b, &b, "de"), en);
4797 }
4798
4799 use super::*;
4800
4801 fn completion(task: &Task) -> CompletionContext {
4802 CompletionContext::new(CompletionActor::Cli, None, Path::new("."), task)
4803 }
4804
4805 #[test]
4806 fn completion_retains_the_hold_dependency_and_failure_it_clears() {
4807 let mut held = task("held evidence");
4808 held.hold_manual(Some("owner approval required".into()));
4809 held.last_error = Some("review budget exhausted".into());
4810 held.succeed(completion(&held));
4811 let event = held.completion_history.last().unwrap();
4812 assert_eq!(event.prior_status, TaskStatus::Held);
4813 assert_eq!(
4814 event.prior_hold_reason.as_deref(),
4815 Some("owner approval required")
4816 );
4817 assert_eq!(
4818 event.prior_error.as_deref(),
4819 Some("review budget exhausted")
4820 );
4821 assert!(held.hold_reason.is_none());
4822 assert!(held.last_error.is_none());
4823 let mut blocked = task("dependency evidence");
4824 blocked.block(
4825 vec!["dependency".into()],
4826 Some("waiting on migration".into()),
4827 );
4828 blocked.succeed(completion(&blocked));
4829 let event = blocked.completion_history.last().unwrap();
4830 assert_eq!(event.prior_status, TaskStatus::Blocked);
4831 assert_eq!(
4832 event.prior_block_reason.as_deref(),
4833 Some("waiting on migration")
4834 );
4835 assert!(blocked.block_reason.is_none());
4836 assert!(blocked.blocked_by.is_empty());
4837 let saved = serde_json::to_vec(&held).unwrap();
4838 let restored: Task = serde_json::from_slice(&saved).unwrap();
4839 assert_eq!(restored.completion_history, held.completion_history);
4840 }
4841
4842 #[test]
4843 fn completion_audit_is_append_only_under_stale_puts() {
4844 let dir = tempfile::tempdir().unwrap();
4845 let queue = Queue::at(dir.path().join("queue"));
4846 let mut current = task("audited");
4847 current.hold_manual(Some("inspect".into()));
4848 queue.put(&mut current).unwrap();
4849 let mut stale = queue.get(¤t.id).unwrap();
4850 current.succeed(completion(¤t));
4851 queue.put(&mut current).unwrap();
4852 let original = current.completion_history[0].clone();
4853 stale.last_error = Some("stale control state".into());
4854 queue.put(&mut stale).unwrap();
4855 assert_eq!(stale.status, TaskStatus::Done);
4856 assert_eq!(stale.completion_history, vec![original.clone()]);
4857 let mut context = completion(¤t);
4858 context.reason = Some("not actually finished".into());
4859 current.reopen(context).unwrap();
4860 queue.put(&mut current).unwrap();
4861 stale.completion_history[0].actor = CompletionActor::Web;
4862 stale.completion_history[0].reason = Some("rewritten evidence".into());
4863 queue.put(&mut stale).unwrap();
4864 assert_eq!(stale.status, TaskStatus::Held);
4865 assert_eq!(stale.hold_reason.as_deref(), Some("not actually finished"));
4866 assert_eq!(stale.completion_history[0], original);
4867 assert_eq!(stale.completion_history, current.completion_history);
4868 }
4869
4870 #[test]
4871 fn a_writer_missing_a_reopen_contributes_receipts_but_not_authority() {
4872 let (_dir, q) = queue();
4873 let mut current = task("durable receipts");
4874 q.put(&mut current).unwrap();
4875 let mut stale = current.clone();
4876 let grant: crate::repair_budget::Receipt = serde_json::from_value(serde_json::json!({
4877 "request": {
4878 "task": current.id, "run": "old-run", "kind": "gate", "rounds": 1,
4879 "head": "old-head", "expect_pass": 0, "request": "old-grant", "reason": "retry"
4880 },
4881 "at": stale.updated_at, "contract": "old-contract"
4882 }))
4883 .unwrap();
4884 stale.release_operator("triage", Some("triage-question"));
4885 stale.queue_repair(&grant);
4886 let reconciliation: crate::repair_budget::reconcile::Receipt =
4887 serde_json::from_value(serde_json::json!({
4888 "request": {
4889 "task": current.id, "run": "old-run", "head": "old-head", "expect_pass": 0,
4890 "receipt": "old-grant", "question": "triage-question", "answer_at": grant.at,
4891 "request": "reconciliation", "reason": "retain the answer"
4892 },
4893 "grant": grant, "source": "answer", "application": "release",
4894 "decision": grant.at, "superseded_questions": []
4895 }))
4896 .unwrap();
4897 stale.repair_reconciliations.push(reconciliation.clone());
4898 stale.triage_applied.push("triage-question".into());
4899 stale.actions_applied.push("choice".into());
4900 stale.base_recovery_requests.push("base-request".into());
4901 stale.chat_notices.push("delivery".into());
4902 stale.chat_notice = Some(ChatNotice {
4903 key: "other-delivery".into(),
4904 at: grant.at,
4905 outcome: ChatNoticeOutcome::Posted,
4906 });
4907 for ledger in [
4908 &mut stale.decision_effects,
4909 &mut stale.dispatched_resumes,
4910 &mut stale.superseded_resumes,
4911 ] {
4912 ledger.insert("shared".into(), "stale".into());
4913 ledger.insert("only-stale".into(), "receipt".into());
4914 }
4915
4916 let mut latest_grant = grant.clone();
4917 latest_grant.request.request = "new-grant".into();
4918 current.queue_repair(&latest_grant);
4919 for ledger in [
4920 &mut current.decision_effects,
4921 &mut current.dispatched_resumes,
4922 &mut current.superseded_resumes,
4923 ] {
4924 ledger.insert("shared".into(), "committed".into());
4925 }
4926 current.succeed(completion(¤t));
4927 let mut context = completion(¤t);
4928 context.reason = Some("inspect again".into());
4929 current.reopen(context).unwrap();
4930 q.put(&mut current).unwrap();
4931
4932 for _ in 0..2 {
4933 q.put(&mut stale.clone()).unwrap();
4934 let saved = q.get(¤t.id).unwrap();
4935 assert_eq!(saved.status, TaskStatus::Held);
4936 assert_eq!(saved.hold_reason, current.hold_reason);
4937 assert_eq!(saved.operator_decided_at, current.operator_decided_at);
4938 assert_eq!(saved.completion_history, current.completion_history);
4939 assert!(saved.resume_override.is_none());
4940 assert!(saved.resumption.is_none());
4941 assert_eq!(
4942 saved.resumption_history,
4943 [stale.resumption.clone().unwrap()]
4944 );
4945 assert_eq!(saved.triage_applied, ["triage-question"]);
4946 assert_eq!(saved.actions_applied, ["choice"]);
4947 assert_eq!(saved.base_recovery_requests, ["base-request"]);
4948 assert_eq!(saved.chat_notices, ["delivery", "other-delivery"]);
4949 assert_eq!(saved.repair_grants, [grant.clone(), latest_grant.clone()]);
4950 assert_eq!(
4951 saved.repair_reconciliations,
4952 std::slice::from_ref(&reconciliation)
4953 );
4954 for ledger in [
4955 saved.decision_effects,
4956 saved.dispatched_resumes,
4957 saved.superseded_resumes,
4958 ] {
4959 assert_eq!(ledger["shared"], "committed");
4960 assert_eq!(ledger["only-stale"], "receipt");
4961 }
4962 }
4963 }
4964
4965 #[test]
4966 fn repeated_completion_only_notifies_for_new_occurrences() {
4967 let mut task = chat_task();
4968 task.succeed(completion(&task));
4969 let first = task.chat_notice_key().unwrap();
4970 task.chat_notices.push(first.clone());
4971 task.succeed(completion(&task));
4972 assert_eq!(task.completion_history.len(), 1, "idempotent while done");
4973 assert_eq!(task.chat_notice_due(), None);
4974 let mut context = completion(&task);
4975 context.reason = Some("inspect".into());
4976 task.reopen(context).unwrap();
4977 task.succeed(completion(&task));
4978 let second = task.chat_notice_key().unwrap();
4979 assert_ne!(first, second);
4980 assert_eq!(task.chat_notice_due(), Some(second));
4981 assert_eq!(task.completion_history.len(), 3);
4982 }
4983
4984 #[test]
4985 fn old_tasks_have_unknown_completion_provenance_not_invented_events() {
4986 let mut task = task("legacy");
4987 task.status = TaskStatus::Done;
4988 let mut value = serde_json::to_value(&task).unwrap();
4989 value.as_object_mut().unwrap().remove("completion_history");
4990 let task: Task = serde_json::from_value(value).unwrap();
4991 assert!(task.completion_history.is_empty());
4992 assert_eq!(task.chat_notice_key().as_deref(), Some("done"));
4993 }
4994
4995 #[test]
4996 fn triage_applied_survives_release_and_old_records_read_as_empty() {
4997 let mut t = Task::new(
4998 "t".to_owned(),
4999 "i".to_owned(),
5000 PathBuf::from("r"),
5001 Source::Human,
5002 );
5003 t.mark_triage_applied("q1");
5004 t.mark_triage_applied("q1");
5005 t.hold_machine(Some("x".to_owned()));
5006 t.release();
5007 assert_eq!(t.triage_applied, ["q1"]);
5008 assert!(t.triage_applied("q1") && !t.triage_applied("q2"));
5009
5010 let mut v = serde_json::to_value(&t).unwrap();
5011 v.as_object_mut().unwrap().remove("triage_applied");
5012 let old: Task = serde_json::from_value(v).unwrap();
5013 assert!(old.triage_applied.is_empty());
5014 }
5015
5016 #[test]
5017 fn task_counts_of_empty_is_all_zero() {
5018 assert_eq!(TaskCounts::of(&[]), TaskCounts::default());
5019 }
5020
5021 #[test]
5022 fn task_counts_of_tallies_every_status() {
5023 let mut queued = Task::new(
5024 "q".to_owned(),
5025 "i".to_owned(),
5026 PathBuf::from("."),
5027 Source::Human,
5028 );
5029 queued.status = TaskStatus::Queued;
5030 let mut running = queued.clone();
5031 running.status = TaskStatus::Running;
5032 let mut done = queued.clone();
5033 done.status = TaskStatus::Done;
5034 let mut failed = queued.clone();
5035 failed.status = TaskStatus::Failed;
5036 let mut held = queued.clone();
5037 held.status = TaskStatus::Held;
5038 let mut blocked = queued.clone();
5039 blocked.status = TaskStatus::Blocked;
5040
5041 let mut parked = queued.clone();
5042 parked.status = TaskStatus::Parked;
5043
5044 let counts = TaskCounts::of(&[
5045 queued,
5046 running,
5047 done.clone(),
5048 done,
5049 failed,
5050 held,
5051 blocked,
5052 parked,
5053 ]);
5054 assert_eq!(
5055 counts,
5056 TaskCounts {
5057 queued: 1,
5058 running: 1,
5059 done: 2,
5060 failed: 1,
5061 held: 1,
5062 blocked: 1,
5063 parked: 1,
5064 }
5065 );
5066 }
5067
5068 #[test]
5069 fn task_implementers_persist_normalized_without_losing_history() {
5070 let (_dir, q) = queue();
5071 let mut t = task("keep me");
5072 t.hold_manual(Some("waiting".into()));
5073 t.runs.push("earlier-run".into());
5074 t.attachments.push("reference.txt".into());
5075 let cfg: crate::config::Config =
5076 toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
5077 .unwrap();
5078 q.put(&mut t).unwrap();
5079 let original = serde_json::to_value(&t).unwrap();
5080 for n in [2, 1, 2] {
5081 t.set_implementers(n, &cfg).unwrap();
5082 q.put(&mut t).unwrap();
5083 t = q.get(&t.id).unwrap();
5084 assert_eq!(t.implementers(), Some(usize::from(n)));
5085 assert_eq!(t.solo, n == 1);
5086 if n == 1 {
5087 assert!(t.overrides.is_none());
5088 }
5089 let mut actual = serde_json::to_value(&t).unwrap();
5090 for field in ["solo", "overrides", "updated_at"] {
5091 actual[field] = original[field].clone();
5092 }
5093 assert_eq!(actual, original);
5094 }
5095 t.overrides.as_mut().unwrap().judges = Some(2);
5096 t.set_implementers(1, &cfg).unwrap();
5097 assert_eq!(t.overrides.as_ref().unwrap().judges, Some(2));
5098 assert_eq!(t.overrides.as_ref().unwrap().candidates, None);
5099 }
5100
5101 #[test]
5102 fn task_implementers_old_records_keep_inheritance_until_changed() {
5103 let mut value = serde_json::to_value(task("old task")).unwrap();
5104 value.as_object_mut().unwrap().remove("solo");
5105 value.as_object_mut().unwrap().remove("overrides");
5106 let mut old: Task = serde_json::from_value(value).unwrap();
5107 assert_eq!(old.implementers(), None);
5108 old.set_implementers(1, &crate::config::Config::default())
5109 .unwrap();
5110 assert!(old.solo);
5111 assert!(old.overrides.is_none());
5112 }
5113
5114 #[test]
5115 fn task_implementers_reject_invalid_counts_and_states() {
5116 let cfg = crate::config::Config::default();
5117 let mut t = task("unchanged");
5118 for n in [0, 4, 255] {
5119 assert!(t.set_implementers(n, &cfg).is_err());
5120 }
5121 for status in [
5122 TaskStatus::Running,
5123 TaskStatus::Done,
5124 TaskStatus::Failed,
5125 TaskStatus::Blocked,
5126 TaskStatus::Parked,
5127 ] {
5128 t.status = status;
5129 let before = serde_json::to_value(&t).unwrap();
5130 assert!(t.set_implementers(1, &cfg).is_err());
5131 assert_eq!(serde_json::to_value(&t).unwrap(), before);
5132 }
5133 }
5134
5135 fn queue() -> (tempfile::TempDir, Queue) {
5138 let dir = tempfile::tempdir().unwrap();
5139 let q = Queue::at(dir.path().join("queue"));
5140 (dir, q)
5141 }
5142
5143 #[test]
5144 fn base_recovery_commit_retains_decision_and_superseded_resume_evidence() {
5145 let (_dir, q) = queue();
5146 let mut original = task("base recovery");
5147 original
5148 .decision_effects
5149 .insert("old-effect".into(), "receipt".into());
5150 original
5151 .dispatched_resumes
5152 .insert("dispatched".into(), "prior-run".into());
5153 original.resume_override = Some(OperatorResume {
5154 question_id: "prior-decision".into(),
5155 at: Timestamp::now(),
5156 conductor_rehold: None,
5157 forced: true,
5158 pinned_run: Some("retained-run".into()),
5159 });
5160 q.put(&mut original).unwrap();
5161 let expected = serde_json::to_value(&original).unwrap();
5162 let mut recovered = original.clone();
5163 recovered.base_recovery_requests.push("chat/request".into());
5164 recovered
5165 .resume_override
5166 .as_mut()
5167 .unwrap()
5168 .question_id
5169 .clear();
5170 q.commit_base_recovery(&mut recovered, &expected).unwrap();
5171 let saved = q.get(&original.id).unwrap();
5172 assert_eq!(saved.decision_effects, original.decision_effects);
5173 assert_eq!(saved.dispatched_resumes, original.dispatched_resumes);
5174 assert_eq!(
5175 saved
5176 .superseded_resumes
5177 .get("prior-decision")
5178 .map(String::as_str),
5179 Some("retained-run")
5180 );
5181 assert_eq!(saved.base_recovery_requests, ["chat/request"]);
5182 assert!(saved.resume_override.unwrap().question_id.is_empty());
5183 assert!(q.commit_base_recovery(&mut recovered, &expected).is_err());
5184 }
5185
5186 #[test]
5187 fn a_stale_write_does_not_drop_the_recorded_task_chat() {
5188 let (_dir, q) = queue();
5189 let mut stale = task("chat");
5190 q.put(&mut stale).unwrap();
5191 let mut fresh = q.get(&stale.id).unwrap();
5192 fresh.chat = Some("talk-1".to_owned());
5193 q.put(&mut fresh).unwrap();
5194 q.put(&mut stale).unwrap();
5195 assert_eq!(q.get(&stale.id).unwrap().chat.as_deref(), Some("talk-1"));
5196 }
5197
5198 #[test]
5199 fn putting_a_machine_held_task_files_a_notification_beside_the_queue() {
5200 let dir = tempfile::tempdir().unwrap();
5201 let q = Queue::at(dir.path().join("queue"));
5202 let mut t = task("held");
5203 q.put(&mut t).unwrap();
5204 assert_eq!(
5205 crate::notices::Notices::at(dir.path().join("notifications"))
5206 .list()
5207 .len(),
5208 0
5209 );
5210 t.hold_machine(Some("out of attempts".to_owned()));
5211 q.put(&mut t).unwrap();
5212 let listed = crate::notices::Notices::at(dir.path().join("notifications")).list();
5213 assert_eq!(listed.len(), 1);
5214 assert!(listed[0].message.contains("out of attempts"));
5215 }
5216
5217 #[test]
5218 fn start_consumes_the_disk_resume_pin() {
5219 let mut t = task("pin");
5220 t.disk_resume_run = Some("run-1".into());
5221 t.start("run-1".into());
5222 assert!(t.disk_resume_run.is_none());
5223 }
5224
5225 fn task(title: &str) -> Task {
5226 Task::new(
5227 title.to_owned(),
5228 format!("do {title}"),
5229 PathBuf::from("."),
5230 Source::Human,
5231 )
5232 }
5233
5234 #[test]
5235 fn attempt_limit_inherits_old_records_and_controls_failure() {
5236 let mut t = task("budget");
5237 let mut old = serde_json::to_value(&t).unwrap();
5238 old.as_object_mut().unwrap().remove("attempt_limit");
5239 old["schema"] = serde_json::json!(15);
5240 let legacy: Task = serde_json::from_value(old).unwrap();
5241 assert_eq!(legacy.attempt_limit, None);
5242 assert_eq!(legacy.effective_attempt_limit(2), 2);
5243 t.attempts = 2;
5244 t.change_attempt_limit(NonZeroUsize::new(3)).unwrap();
5245 t.fail("retry", 1);
5246 assert_eq!(t.status, TaskStatus::Failed);
5247 t.attempts = 3;
5248 t.fail("stop", 10);
5249 assert_eq!(t.status, TaskStatus::Held);
5250 t.change_attempt_limit(None).unwrap();
5251 assert_eq!(t.status, TaskStatus::Held);
5252 assert_eq!(t.attempts, 3);
5253 t.fail("inherit", 4);
5254 assert_eq!(t.status, TaskStatus::Failed);
5255 for status in [
5256 TaskStatus::Running,
5257 TaskStatus::Done,
5258 TaskStatus::Failed,
5259 TaskStatus::Blocked,
5260 TaskStatus::Parked,
5261 ] {
5262 t.status = status;
5263 assert!(t.change_attempt_limit(NonZeroUsize::new(1)).is_err());
5264 assert_eq!(t.attempt_limit, None);
5265 }
5266 }
5267
5268 #[test]
5269 fn earlier_attempts_is_every_recorded_run_and_agrees_with_the_display() {
5270 let mut t = task("retried");
5271 assert!(
5272 t.earlier_attempts().is_empty(),
5273 "a first attempt takes nothing over"
5274 );
5275 t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned()];
5276 assert_eq!(t.earlier_attempts(), ["aaaa", "bbbb"]);
5277 assert_eq!(t.successor_of("aaaa"), Some(&"bbbb".to_owned()));
5279 assert_eq!(t.successor_of("bbbb"), None);
5280 assert_eq!(t.successor_of("zzzz"), None);
5281 }
5282
5283 #[test]
5284 fn resumed_runs_are_superseded_only_after_their_last_occurrence() {
5285 let (_dir, q) = queue();
5286 let mut t = task("resumed");
5287 for (runs, successor) in [
5288 (vec!["aaaa", "aaaa"], None),
5289 (vec!["aaaa", "bbbb", "aaaa"], None),
5290 (vec!["aaaa", "aaaa", "bbbb"], Some("bbbb")),
5291 (vec!["aaaa", "bbbb", "aaaa", "cccc"], Some("cccc")),
5292 ] {
5293 t.runs = runs.into_iter().map(str::to_owned).collect();
5294 q.put(&mut t).unwrap();
5295
5296 assert_eq!(t.successor_of("aaaa").map(String::as_str), successor);
5297 assert_eq!(q.superseded_by("aaaa").as_deref(), successor);
5298 assert_eq!(q.superseded().get("aaaa").map(String::as_str), successor);
5299 }
5300 }
5301
5302 #[test]
5303 fn superseded_by_names_the_next_attempt_and_none_for_the_last() {
5304 let (_dir, q) = queue();
5305 let mut t = task("retried");
5306 t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned(), "cccc".to_owned()];
5307 q.put(&mut t).unwrap();
5308
5309 assert_eq!(q.superseded_by("aaaa"), Some("bbbb".to_owned()));
5310 assert_eq!(q.superseded_by("bbbb"), Some("cccc".to_owned()));
5311 assert_eq!(
5312 q.superseded_by("cccc"),
5313 None,
5314 "the latest attempt replaces nothing"
5315 );
5316 assert_eq!(
5317 q.superseded_by("never-heard-of-it"),
5318 None,
5319 "a run belonging to no task on this queue is not superseded"
5320 );
5321
5322 let mut by = HashMap::new();
5323 by.insert("aaaa".to_owned(), "bbbb".to_owned());
5324 by.insert("bbbb".to_owned(), "cccc".to_owned());
5325 assert_eq!(
5326 q.superseded(),
5327 by,
5328 "the whole-map and single-run forms must agree"
5329 );
5330 }
5331
5332 #[test]
5333 fn superseded_attempts_is_empty_until_the_task_is_done() {
5334 let mut t = task("retried");
5335 t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned()];
5336 t.status = TaskStatus::Failed;
5337 assert_eq!(
5338 t.superseded_attempts(true),
5339 &[] as &[String],
5340 "a task still retrying has no attempt yet that a later one made moot"
5341 );
5342
5343 t.status = TaskStatus::Running;
5344 assert_eq!(t.superseded_attempts(true), &[] as &[String]);
5345 }
5346
5347 #[test]
5348 fn superseded_attempts_names_every_run_before_the_one_that_succeeded() {
5349 let mut t = task("retried");
5350 t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned(), "cccc".to_owned()];
5351 t.status = TaskStatus::Done;
5352 assert_eq!(
5353 t.superseded_attempts(true),
5354 &["aaaa".to_owned(), "bbbb".to_owned()],
5355 "cccc is the attempt whose success made the task done, and stays out"
5356 );
5357 }
5358
5359 #[test]
5360 fn superseded_attempts_is_empty_for_a_done_task_with_only_one_attempt() {
5361 let mut t = task("first try landed");
5362 t.runs = vec!["aaaa".to_owned()];
5363 t.status = TaskStatus::Done;
5364 assert_eq!(t.superseded_attempts(true), &[] as &[String]);
5365 }
5366
5367 #[test]
5368 fn superseded_attempts_is_empty_when_the_last_run_never_actually_succeeded() {
5369 let mut t = task("closed by hand after a manual merge");
5376 t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned()];
5377 t.status = TaskStatus::Done;
5378 assert_eq!(
5379 t.superseded_attempts(false),
5380 &[] as &[String],
5381 "nothing here is provably why the task is done, so nothing is superseded"
5382 );
5383 }
5384
5385 #[test]
5386 fn latest_attempt_names_the_chain_s_current_head_not_just_the_next_one() {
5387 let (_dir, q) = queue();
5388 let mut t = task("retried twice");
5389 t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned(), "cccc".to_owned()];
5390 q.put(&mut t).unwrap();
5391
5392 assert_eq!(
5393 q.latest_attempt("aaaa"),
5394 Some("cccc".to_owned()),
5395 "an old attempt points straight at the chain's current head, not the \
5396 next attempt in the middle of it"
5397 );
5398 assert_eq!(q.latest_attempt("bbbb"), Some("cccc".to_owned()));
5399 assert_eq!(
5400 q.latest_attempt("cccc"),
5401 None,
5402 "the latest attempt is not superseded by anything"
5403 );
5404 assert_eq!(
5405 q.latest_attempt("never-heard-of-it"),
5406 None,
5407 "a run belonging to no task on this queue is not superseded"
5408 );
5409 }
5410
5411 #[test]
5412 fn a_markdown_heading_is_the_title_not_decoration() {
5413 assert_eq!(
5418 title_from("# Rework the config loader\n\nIt re-reads it.\n", 40),
5419 "Rework the config loader"
5420 );
5421 assert_eq!(title_from("- fix the thing", 40), "fix the thing");
5422 assert_eq!(title_from("> quoted task", 40), "quoted task");
5423 assert_eq!(title_from(" \n\n", 40), "(empty task)");
5425 assert_eq!(title_from("###\n", 40), "(empty task)");
5426 }
5427
5428 #[test]
5429 fn a_long_title_is_elided_by_characters_not_bytes() {
5430 let long = "課題".repeat(30);
5432 let title = title_from(&long, 10);
5433 assert_eq!(title.chars().count(), 10);
5434 assert!(title.ends_with('…'));
5435 }
5436
5437 #[test]
5438 fn priority_wins_and_ties_break_oldest_first() {
5439 let (_dir, q) = queue();
5440 let mut a = task("first");
5441 let mut b = task("second");
5442 let mut c = task("urgent");
5443 a.id = "20260101-000001-aaaa".to_owned();
5445 b.id = "20260101-000002-bbbb".to_owned();
5446 c.id = "20260101-000003-cccc".to_owned();
5447 c.priority = 5;
5448 for t in [&mut a, &mut b, &mut c] {
5449 q.put(t).unwrap();
5450 }
5451
5452 assert_eq!(q.next_runnable().unwrap().id, c.id);
5454 c.hold_machine(None);
5455 q.put(&mut c).unwrap();
5456 assert_eq!(q.next_runnable().unwrap().id, a.id);
5458 assert_eq!(q.list().len(), 3, "b is still waiting its turn");
5459 }
5460
5461 #[test]
5462 fn a_blocked_task_never_starves_another_runnable_one() {
5463 let (_dir, q) = queue();
5464 let mut blocked = task("blocked");
5465 blocked.block(vec!["something".to_owned()], None);
5466 q.put(&mut blocked).unwrap();
5467
5468 let mut runnable = task("free to go");
5469 q.put(&mut runnable).unwrap();
5470
5471 let next = q.next_runnable().expect("a runnable task is still offered");
5472 assert_eq!(next.id, runnable.id);
5473 }
5474
5475 #[test]
5476 fn a_held_task_is_never_offered_to_the_loop() {
5477 let (_dir, q) = queue();
5478 let mut t = task("held");
5479 q.put(&mut t).unwrap();
5480 assert!(q.next_runnable().is_some());
5481
5482 t.hold_machine(None);
5483 q.put(&mut t).unwrap();
5484 assert!(
5485 q.next_runnable().is_none(),
5486 "a held task must wait for a human"
5487 );
5488
5489 t.status = TaskStatus::Failed;
5491 q.put(&mut t).unwrap();
5492 assert!(q.next_runnable().is_some());
5493 }
5494
5495 #[test]
5496 fn attempts_are_capped_and_then_the_task_is_held() {
5497 let mut t = task("doomed");
5498
5499 t.start("run-1".to_owned());
5500 t.fail("gate red", 2);
5501 assert_eq!(t.status, TaskStatus::Failed, "one attempt of two: retry");
5502
5503 t.start("run-2".to_owned());
5504 t.fail("gate red", 2);
5505 assert_eq!(
5506 t.status,
5507 TaskStatus::Held,
5508 "out of attempts: stop spending money on it"
5509 );
5510 assert_eq!(t.runs, ["run-1", "run-2"]);
5511 assert_eq!(t.last_error.as_deref(), Some("gate red"));
5512 assert_eq!(
5513 t.hold_reason.as_deref(),
5514 Some("gate red"),
5515 "the hold must say why, not leave hold_reason null next to a \
5516 populated last_error"
5517 );
5518 }
5519
5520 #[test]
5521 fn handing_off_a_task_records_a_hold_reason_too() {
5522 let mut t = task("left a pull request");
5523 t.start("run-1".to_owned());
5524 t.handed_off("run ended with a pull request open [run run-1]");
5525 assert_eq!(t.status, TaskStatus::Held);
5526 assert_eq!(t.hold_source, Some(HoldSource::Machine));
5527 assert_eq!(
5528 t.hold_reason.as_deref(),
5529 Some("run ended with a pull request open [run run-1]")
5530 );
5531 assert_eq!(t.hold_reason, t.last_error);
5532 }
5533
5534 #[test]
5535 fn a_quota_stall_is_refunded_so_the_backlog_survives_the_night() {
5536 let mut t = task("stalled by quota");
5537
5538 t.start("run-1".to_owned());
5539 assert_eq!(t.attempts, 1);
5540 t.stall("judge-1, judge-2 out of quota");
5541 assert_eq!(
5542 t.attempts, 0,
5543 "a closed quota window must not spend the task's retry budget"
5544 );
5545 assert_eq!(t.status, TaskStatus::Failed, "the loop should retry it");
5546 assert_eq!(
5547 t.last_error.as_deref(),
5548 Some("judge-1, judge-2 out of quota")
5549 );
5550
5551 for _ in 0..20 {
5554 t.start("run-n".to_owned());
5555 t.stall("still out of quota");
5556 }
5557 t.start("run-real".to_owned());
5558 t.fail("gate red", 2);
5559 assert_eq!(
5560 t.status,
5561 TaskStatus::Failed,
5562 "the first attempt that was really judged is attempt one"
5563 );
5564 }
5565
5566 #[test]
5567 fn releasing_a_held_task_gives_it_a_real_second_chance() {
5568 let mut t = task("retry me");
5569 t.start("run-1".to_owned());
5570 t.fail("gate red", 1);
5571 assert_eq!(t.status, TaskStatus::Held);
5572
5573 t.release();
5574 assert_eq!(t.status, TaskStatus::Queued);
5575 assert_eq!(t.attempts, 0);
5578 assert!(t.last_error.is_none());
5579 assert_eq!(
5580 t.runs.len(),
5581 1,
5582 "history is kept: attempts reset, evidence does not"
5583 );
5584 }
5585
5586 #[test]
5587 fn a_hold_reason_survives_and_a_release_clears_it() {
5588 let mut t = task("waiting on something else");
5589 t.hold_manual(Some(
5590 "waiting for 20260101-000000-aaaa to land first".to_owned(),
5591 ));
5592 assert_eq!(t.status, TaskStatus::Held);
5593 assert_eq!(
5594 t.hold_reason.as_deref(),
5595 Some("waiting for 20260101-000000-aaaa to land first")
5596 );
5597
5598 t.hold_manual(None);
5600 assert_eq!(
5601 t.hold_reason.as_deref(),
5602 Some("waiting for 20260101-000000-aaaa to land first"),
5603 "a bare re-hold keeps whatever a human already wrote down"
5604 );
5605
5606 let mut plain = task("no reason given");
5608 plain.hold_manual(None);
5609 assert_eq!(plain.status, TaskStatus::Held);
5610 assert!(plain.hold_reason.is_none());
5611
5612 t.release();
5613 assert_eq!(t.status, TaskStatus::Queued);
5614 assert!(
5615 t.hold_reason.is_none(),
5616 "a stale reason must not greet the next person who holds this task"
5617 );
5618 }
5619
5620 #[test]
5621 fn closing_a_held_task_as_done_clears_its_hold_reason_too() {
5622 let mut t = task("landed by hand while held");
5627 t.hold_manual(Some("waiting on 3ed9".to_owned()));
5628 assert_eq!(t.hold_reason.as_deref(), Some("waiting on 3ed9"));
5629
5630 t.succeed(completion(&t));
5631 assert_eq!(t.status, TaskStatus::Done);
5632 assert!(
5633 t.hold_reason.is_none(),
5634 "a done task cannot still be waiting on something"
5635 );
5636 }
5637
5638 #[test]
5639 fn holding_or_closing_a_blocked_task_clears_its_dependency_too() {
5640 let mut held = task("held straight out of blocked");
5647 held.block(
5648 vec!["20260101-000000-dead".to_owned()],
5649 Some("waiting on the migration script".to_owned()),
5650 );
5651 assert_eq!(held.status, TaskStatus::Blocked);
5652
5653 held.hold_manual(None);
5654 assert_eq!(held.status, TaskStatus::Held);
5655 assert!(
5656 held.blocked_by.is_empty(),
5657 "hold overrides the wait, same as release"
5658 );
5659 assert!(held.block_reason.is_none());
5660
5661 let mut done = task("closed straight out of blocked");
5662 done.block(
5663 vec!["20260101-000000-dead".to_owned()],
5664 Some("waiting on the migration script".to_owned()),
5665 );
5666 done.succeed(completion(&done));
5667 assert_eq!(done.status, TaskStatus::Done);
5668 assert!(
5669 done.blocked_by.is_empty(),
5670 "a done task cannot still be waiting on a dependency"
5671 );
5672 assert!(done.block_reason.is_none());
5673 }
5674
5675 #[test]
5676 fn a_blocked_task_is_never_offered_to_the_loop() {
5677 let mut t = task("blocked");
5678 assert!(t.status.runnable());
5679 t.block(
5680 vec!["dep-id".to_owned()],
5681 Some("waits on dep-id".to_owned()),
5682 );
5683 assert_eq!(t.status, TaskStatus::Blocked);
5684 assert!(!t.status.runnable());
5685 assert_eq!(TaskStatus::Blocked.as_str(), "blocked");
5686 }
5687
5688 #[test]
5689 fn unblocking_the_last_dependency_returns_the_task_to_queued() {
5690 let mut t = task("blocked on two");
5691 t.block(
5692 vec!["a".to_owned(), "b".to_owned()],
5693 Some("waits on a and b".to_owned()),
5694 );
5695
5696 t.unblock("a");
5697 assert_eq!(t.status, TaskStatus::Blocked, "b is still outstanding");
5698 assert_eq!(t.blocked_by, ["b"]);
5699
5700 t.unblock("b");
5701 assert_eq!(t.status, TaskStatus::Queued);
5702 assert!(t.blocked_by.is_empty());
5703 assert!(t.block_reason.is_none());
5704 }
5705
5706 #[test]
5707 fn unblocking_an_id_on_a_task_that_is_not_blocked_is_a_no_op() {
5708 let mut t = task("never blocked");
5709 t.unblock("whatever");
5710 assert_eq!(t.status, TaskStatus::Queued);
5711 }
5712
5713 #[test]
5714 fn a_held_task_blocked_on_a_question_returns_to_held_not_queued() {
5715 let mut t = task("held, then asked about");
5720 t.hold_machine(Some("out of attempts".to_owned()));
5721 assert_eq!(t.status, TaskStatus::Held);
5722
5723 t.block(vec!["q1".to_owned()], Some("what now?".to_owned()));
5724 assert_eq!(t.status, TaskStatus::Blocked);
5725
5726 t.record_answer("what now?".to_owned(), "leave it held".to_owned());
5727 t.unblock("q1");
5728 assert_eq!(t.status, TaskStatus::Held, "must restore, not requeue");
5729 assert_eq!(t.hold_reason.as_deref(), Some("out of attempts"));
5730 assert_eq!(t.hold_source, Some(HoldSource::Machine));
5731 assert!(t.blocked_from.is_none(), "consumed once restored");
5732 }
5733
5734 #[test]
5735 fn a_manually_held_task_blocked_on_a_question_returns_to_held() {
5736 let mut t = task("manually held, then asked about");
5737 t.hold_manual(Some("waiting on a dependency".to_owned()));
5738
5739 t.block(vec!["q1".to_owned()], None);
5740 t.unblock("q1");
5741
5742 assert_eq!(t.status, TaskStatus::Held);
5743 assert_eq!(t.hold_source, Some(HoldSource::Manual));
5744 }
5745
5746 #[test]
5747 fn re_blocking_an_already_blocked_task_keeps_the_original_blocked_from() {
5748 let mut t = task("held, blocked twice");
5752 t.hold_machine(None);
5753 t.block(vec!["q1".to_owned()], Some("first".to_owned()));
5754 t.block(
5755 vec!["q1".to_owned(), "q2".to_owned()],
5756 Some("second".to_owned()),
5757 );
5758
5759 t.unblock("q1");
5760 assert_eq!(t.status, TaskStatus::Blocked, "q2 still outstanding");
5761 t.unblock("q2");
5762 assert_eq!(t.status, TaskStatus::Held);
5763 }
5764
5765 #[test]
5766 fn unblocking_a_task_blocked_while_running_lands_on_queued_not_running() {
5767 let mut t = task("blocked mid-run");
5771 t.start("run-1".to_owned());
5772 assert_eq!(t.status, TaskStatus::Running);
5773
5774 t.block(vec!["q1".to_owned()], None);
5775 t.unblock("q1");
5776 assert_eq!(t.status, TaskStatus::Queued);
5777 }
5778
5779 #[test]
5780 fn a_pre_schema_4_blocked_record_with_hold_evidence_restores_to_held() {
5781 let mut t = task("legacy record, held before it was blocked");
5787 t.hold_source = Some(HoldSource::Machine);
5788 t.hold_reason = Some("legacy hold reason".to_owned());
5789 t.status = TaskStatus::Blocked;
5790 t.blocked_by = vec!["q1".to_owned()];
5791 t.blocked_from = None;
5792
5793 t.unblock("q1");
5794 assert_eq!(t.status, TaskStatus::Held);
5795 }
5796
5797 #[test]
5798 fn a_pre_schema_4_blocked_record_with_no_hold_evidence_restores_to_queued() {
5799 let mut t = task("legacy record, ordinary dependency block");
5800 t.status = TaskStatus::Blocked;
5801 t.blocked_by = vec!["dep".to_owned()];
5802 t.blocked_from = None;
5803
5804 t.unblock("dep");
5805 assert_eq!(t.status, TaskStatus::Queued);
5806 }
5807
5808 #[test]
5809 fn answering_a_question_is_recorded_and_survives_a_release() {
5810 let mut t = task("asked something");
5811 t.block(vec!["q1".to_owned()], Some("which backend?".to_owned()));
5812 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
5813 t.unblock("q1");
5814 assert_eq!(t.status, TaskStatus::Queued);
5815 assert_eq!(t.answers.len(), 1);
5816 assert_eq!(t.answers[0].answer, "SQLite");
5817
5818 t.release();
5822 assert_eq!(t.answers.len(), 1, "the answer is not lost on release");
5823 }
5824
5825 #[test]
5826 fn resumption_review_branch_requires_unchanged_authored_criteria() {
5827 for source in ["cli", "web"] {
5828 let mut t = task("review old candidate");
5829 t.request_review("candidate-A".into());
5830 t.hold_for_handover(Some("candidate-A".into()), "handover refused".into());
5831 let mut unchanged = t.clone();
5832 unchanged.release_operator(source, None);
5833 assert_eq!(unchanged.review_branch.as_deref(), Some("candidate-A"));
5834 t.edit(
5835 "review approved head".into(),
5836 "Reuse measured PR head B; fix Clippy; review".into(),
5837 )
5838 .unwrap();
5839 t.release_operator(source, None);
5840 assert!(t.review_branch.is_none());
5841 assert!(t.review_instruction.is_none());
5842 let mut legacy = unchanged;
5844 legacy.review_instruction = None;
5845 legacy.hold_for_handover(None, "still checked out".into());
5846 legacy
5847 .edit("new plan".into(), "Reuse measured PR head B".into())
5848 .unwrap();
5849 legacy.release_operator(source, None);
5850 assert!(legacy.review_branch.is_none());
5851 }
5852 }
5853
5854 #[test]
5855 fn a_refused_handover_keeps_the_review_branch_across_release() {
5856 let mut t = task("refused takeover");
5857 t.start("run-1".to_owned());
5858 t.hold_for_handover(Some("magi/eba2/A".to_owned()), "checked out".to_owned());
5859 assert_eq!(t.status, TaskStatus::Held);
5860 assert_eq!(t.attempts, 1);
5861 t.release();
5862 assert_eq!(t.status, TaskStatus::Queued);
5863 assert_eq!(t.attempts, 0);
5864 assert_eq!(t.review_branch.as_deref(), Some("magi/eba2/A"));
5865
5866 t.hold_for_handover(None, "again".to_owned());
5868 t.requeue();
5869 assert!(t.review_branch.is_none());
5870
5871 let mut m = task("manual");
5873 m.review_branch = Some("magi/x/A".to_owned());
5874 m.hold_manual(None);
5875 m.release();
5876 assert!(m.review_branch.is_none());
5877 }
5878
5879 #[test]
5880 fn requesting_review_requeues_the_task_and_remembers_the_branch() {
5881 let mut t = task("blocked run with a surviving branch");
5882 t.start("run-1".to_owned());
5883 t.fail("blocked with major findings", 5);
5884 assert_eq!(t.status, TaskStatus::Failed);
5885
5886 t.request_review("magi/eba2/A".to_owned());
5887 assert_eq!(t.status, TaskStatus::Queued);
5888 assert_eq!(t.attempts, 0);
5889 assert_eq!(t.review_branch.as_deref(), Some("magi/eba2/A"));
5890
5891 t.release();
5893 assert!(t.review_branch.is_none());
5894 }
5895
5896 #[test]
5897 fn conductor_requeue_but_not_an_ordinary_release_forces_a_fresh_start() {
5898 let mut t = task("retry");
5899 t.start("run-1".to_owned());
5900 t.requeue();
5901 assert!(t.fresh_start);
5902
5903 t.release();
5904 assert!(!t.fresh_start);
5905 }
5906
5907 #[test]
5908 fn urgent_only_changes_queued_or_held_and_preserves_settings() {
5909 for status in [
5910 TaskStatus::Queued,
5911 TaskStatus::Held,
5912 TaskStatus::Running,
5913 TaskStatus::Done,
5914 TaskStatus::Failed,
5915 TaskStatus::Blocked,
5916 TaskStatus::Parked,
5917 ] {
5918 let mut t = task("urgent settings");
5919 t.status = status;
5920 t.attempts = 2;
5921 t.hold_reason = Some("waiting".into());
5922 t.priority = 7;
5923 t.interrupt = true;
5924 let before = serde_json::to_value(&t).unwrap();
5925 for urgent in [true, true, false, false] {
5926 let result = t.set_urgent(urgent);
5927 let mut expected = before.clone();
5928 if matches!(status, TaskStatus::Queued | TaskStatus::Held) {
5929 result.unwrap();
5930 expected["urgent"] = urgent.into();
5931 } else {
5932 let error = result.unwrap_err().to_string();
5933 assert!(error.contains(status.as_str()), "{error}");
5934 assert!(error.contains("queued or held"), "{error}");
5935 }
5936 assert_eq!(serde_json::to_value(&t).unwrap(), expected);
5937 }
5938 }
5939 }
5940
5941 #[test]
5942 fn immediate_only_changes_queued_or_held_and_preserves_settings() {
5943 for status in [
5944 TaskStatus::Queued,
5945 TaskStatus::Held,
5946 TaskStatus::Running,
5947 TaskStatus::Done,
5948 TaskStatus::Failed,
5949 TaskStatus::Blocked,
5950 TaskStatus::Parked,
5951 ] {
5952 let mut t = task("immediate settings");
5953 t.status = status;
5954 t.attempts = 2;
5955 t.hold_reason = Some("waiting".into());
5956 t.priority = 7;
5957 t.interrupt = true;
5958 t.urgent = true;
5959 let before = serde_json::to_value(&t).unwrap();
5960 for immediate in [true, true, false, false] {
5961 let result = t.set_immediate(immediate);
5962 let mut expected = before.clone();
5963 if matches!(status, TaskStatus::Queued | TaskStatus::Held) {
5964 result.unwrap();
5965 expected["immediate"] = immediate.into();
5966 } else {
5967 let error = result.unwrap_err().to_string();
5968 assert!(error.contains(status.as_str()), "{error}");
5969 assert!(error.contains("queued or held"), "{error}");
5970 }
5971 assert_eq!(serde_json::to_value(&t).unwrap(), expected);
5972 assert!(t.urgent, "changing immediate must preserve saved urgent");
5973 }
5974 }
5975 }
5976
5977 #[test]
5978 fn a_task_recorded_without_an_immediate_field_still_reads_as_not_immediate() {
5979 let (_dir, q) = queue();
5980 let path = q.path_of("20260101-000000-imm0");
5981 std::fs::create_dir_all(q.root()).unwrap();
5982 std::fs::write(
5983 &path,
5984 serde_json::json!({
5985 "schema": SCHEMA,
5986 "id": "20260101-000000-imm0",
5987 "title": "from before immediate existed",
5988 "instruction": "from before immediate existed",
5989 "repo": ".",
5990 "source": { "kind": "human" },
5991 "status": "queued",
5992 "urgent": true,
5993 "created_at": Timestamp::now().to_string(),
5994 "updated_at": Timestamp::now().to_string(),
5995 })
5996 .to_string(),
5997 )
5998 .unwrap();
5999
6000 let task = q.get("20260101-000000-imm0").expect("must still read");
6001 assert!(!task.immediate);
6002 assert!(task.urgent);
6003 }
6004
6005 #[test]
6006 fn immediate_reuses_urgent_isolation_and_explicit_cache_wins() {
6007 let mut cfg = crate::config::Config::default();
6008 cfg.verify.e2e = vec!["CARGO_TARGET_DIR=/tmp/shared-target cargo test".into()];
6009 let mut t = task("immediate cache");
6010
6011 t.set_immediate(true).unwrap();
6012 assert_eq!(
6013 t.build_cache_override(&cfg),
6014 Some((BuildCache::Isolated, "immediate"))
6015 );
6016
6017 t.set_urgent(true).unwrap();
6019 assert_eq!(
6020 t.build_cache_override(&cfg),
6021 Some((BuildCache::Isolated, "immediate"))
6022 );
6023
6024 t.change_build_cache(Some(BuildCache::Shared)).unwrap();
6026 assert_eq!(
6027 t.build_cache_override(&cfg),
6028 Some((BuildCache::Shared, "task-override"))
6029 );
6030
6031 t.change_build_cache(None).unwrap();
6033 assert_eq!(
6034 t.build_cache_override(&cfg),
6035 Some((BuildCache::Isolated, "immediate"))
6036 );
6037 t.set_immediate(false).unwrap();
6038 assert_eq!(
6039 t.build_cache_override(&cfg),
6040 Some((BuildCache::Isolated, "urgent"))
6041 );
6042
6043 t.set_immediate(true).unwrap();
6045 cfg.verify.e2e = vec!["CARGO_TARGET_DIR=/tmp/shared-target cargo test | tee log".into()];
6046 assert_eq!(t.build_cache_override(&cfg), None);
6047 }
6048
6049 #[test]
6050 fn priority_can_be_changed_while_queued_but_not_while_running() {
6051 let mut t = task("reprioritise me");
6052 t.set_priority(5).unwrap();
6053 assert_eq!(t.priority, 5);
6054
6055 t.start("run-1".to_owned());
6056 let err = t.set_priority(9).unwrap_err().to_string();
6057 assert!(err.contains("running"), "{err}");
6058 assert_eq!(t.priority, 5, "the rejected write must not partially apply");
6059 }
6060
6061 #[test]
6062 fn interrupt_can_be_marked_while_queued_but_not_while_running() {
6063 let mut t = task("interrupt me");
6064 assert!(!t.interrupt, "off unless asked, same as any other task");
6065
6066 t.set_interrupt(true).unwrap();
6067 assert!(t.interrupt);
6068
6069 t.start("run-1".to_owned());
6070 assert!(
6071 !t.interrupt,
6072 "the mark is one-shot: dispatching the task fulfils it, \
6073 whatever the run that follows ends up doing"
6074 );
6075 let err = t.set_interrupt(true).unwrap_err().to_string();
6076 assert!(err.contains("running"), "{err}");
6077 t.set_interrupt(false).unwrap();
6080 assert!(!t.interrupt);
6081 }
6082
6083 #[test]
6087 fn a_failed_run_does_not_leave_the_task_still_marked_to_interrupt() {
6088 let mut t = task("interrupt me");
6089 t.set_interrupt(true).unwrap();
6090 t.start("run-1".to_owned());
6091 t.fail("mock failure", 5);
6092 assert_eq!(t.status, TaskStatus::Failed);
6093 assert!(
6094 !t.interrupt,
6095 "one attempt already spent the mark; a retry is an ordinary \
6096 requeue, not a fresh interrupt request"
6097 );
6098 }
6099
6100 #[test]
6101 fn changing_priority_moves_a_task_ahead_in_the_real_queue_order() {
6102 let (_dir, q) = queue();
6103 let mut a = task("first filed");
6104 let mut b = task("second filed");
6105 a.id = "20260101-000001-aaaa".to_owned();
6106 b.id = "20260101-000002-bbbb".to_owned();
6107 q.put(&mut a).unwrap();
6108 q.put(&mut b).unwrap();
6109
6110 assert_eq!(
6111 q.next_runnable().unwrap().id,
6112 a.id,
6113 "with equal priority the older task goes first, so a burst of \
6114 new work cannot starve it"
6115 );
6116 assert_eq!(
6117 q.list()[0].id,
6118 b.id,
6119 "but the list an operator reads is newest first, the same as \
6120 before priority existed - a's turn to run does not make it the \
6121 newest task"
6122 );
6123
6124 let mut a = q.get(&a.id).unwrap();
6125 a.set_priority(10).unwrap();
6126 q.put(&mut a).unwrap();
6127
6128 assert_eq!(
6129 q.next_runnable().unwrap().id,
6130 a.id,
6131 "a raised priority must be reflected the moment it is saved"
6132 );
6133 assert_eq!(
6137 q.list()[0].id,
6138 a.id,
6139 "the raised task must sort first in the list an operator reads, \
6140 not only in next_runnable's own ordering"
6141 );
6142 }
6143
6144 #[test]
6145 fn editing_replaces_title_and_instruction_but_keeps_identity_and_history() {
6146 let mut t = Task::new(
6147 "old title".to_owned(),
6148 "old instruction".to_owned(),
6149 PathBuf::from("/repo"),
6150 Source::Agent {
6151 run: "20260101-000000-beef".to_owned(),
6152 node: "implement".to_owned(),
6153 },
6154 );
6155 let id = t.id.clone();
6156 let created_at = t.created_at;
6157 t.runs.push("20260101-000000-beef".to_owned());
6158
6159 t.edit("new title".to_owned(), "new instruction".to_owned())
6160 .unwrap();
6161
6162 assert_eq!(t.title, "new title");
6163 assert_eq!(t.instruction, "new instruction");
6164 assert_eq!(t.id, id, "editing must not mint a new id");
6165 assert_eq!(t.created_at, created_at);
6166 assert_eq!(
6167 t.source,
6168 Source::Agent {
6169 run: "20260101-000000-beef".to_owned(),
6170 node: "implement".to_owned(),
6171 },
6172 "editing must not turn agent attribution into human"
6173 );
6174 assert_eq!(t.runs, ["20260101-000000-beef"]);
6175 }
6176
6177 #[test]
6178 fn editing_is_refused_once_a_task_is_running_or_finished() {
6179 let mut running = task("in flight");
6180 running.start("run-1".to_owned());
6181 let err = running
6182 .edit("x".to_owned(), "y".to_owned())
6183 .unwrap_err()
6184 .to_string();
6185 assert!(err.contains("running"), "{err}");
6186
6187 let mut done = task("finished");
6188 done.succeed(completion(&done));
6189 let err = done
6190 .edit("x".to_owned(), "y".to_owned())
6191 .unwrap_err()
6192 .to_string();
6193 assert!(err.contains("done"), "{err}");
6194
6195 let mut queued = task("waiting");
6197 queued.edit("x".to_owned(), "y".to_owned()).unwrap();
6198 let mut held = task("parked");
6199 held.hold_machine(None);
6200 held.edit("x".to_owned(), "y".to_owned()).unwrap();
6201 }
6202
6203 #[test]
6204 fn a_task_recorded_without_a_hold_reason_still_reads_as_none() {
6205 let (_dir, q) = queue();
6206 let path = q.path_of("20260101-000000-aaaa");
6207 std::fs::create_dir_all(q.root()).unwrap();
6208 std::fs::write(
6209 &path,
6210 serde_json::json!({
6211 "schema": SCHEMA,
6212 "id": "20260101-000000-aaaa",
6213 "title": "from before hold reasons existed",
6214 "instruction": "from before hold reasons existed",
6215 "repo": ".",
6216 "source": { "kind": "human" },
6217 "status": "held",
6218 "created_at": Timestamp::now().to_string(),
6219 "updated_at": Timestamp::now().to_string(),
6220 })
6221 .to_string(),
6222 )
6223 .unwrap();
6224
6225 let task = q.get("20260101-000000-aaaa").expect("must still read");
6226 assert!(task.hold_reason.is_none());
6227 assert!(task.operator_held());
6228 }
6229
6230 #[test]
6231 fn a_legacy_reasoned_hold_defaults_to_operator_protection() {
6232 let (_dir, q) = queue();
6233 let path = q.path_of("20260101-000000-bbbb");
6234 std::fs::create_dir_all(q.root()).unwrap();
6235 std::fs::write(
6236 &path,
6237 serde_json::json!({
6238 "schema": 2,
6239 "id": "20260101-000000-bbbb",
6240 "title": "old manual recovery",
6241 "instruction": "old manual recovery",
6242 "repo": ".",
6243 "source": { "kind": "human" },
6244 "status": "held",
6245 "hold_reason": "active manual recovery run20260912-224242-daf5",
6246 "created_at": Timestamp::now().to_string(),
6247 "updated_at": Timestamp::now().to_string(),
6248 })
6249 .to_string(),
6250 )
6251 .unwrap();
6252
6253 let task = q.get("20260101-000000-bbbb").expect("must still read");
6254 assert_eq!(task.hold_source, None);
6255 assert!(task.operator_held());
6256 }
6257
6258 #[test]
6259 fn a_task_recorded_without_a_diagnostic_still_reads_as_none() {
6260 let (_dir, q) = queue();
6261 let path = q.path_of("20260101-000000-aaaa");
6262 std::fs::create_dir_all(q.root()).unwrap();
6263 std::fs::write(
6264 &path,
6265 serde_json::json!({
6266 "schema": SCHEMA,
6267 "id": "20260101-000000-aaaa",
6268 "title": "from before diagnostics existed",
6269 "instruction": "from before diagnostics existed",
6270 "repo": ".",
6271 "source": { "kind": "human" },
6272 "status": "held",
6273 "created_at": Timestamp::now().to_string(),
6274 "updated_at": Timestamp::now().to_string(),
6275 })
6276 .to_string(),
6277 )
6278 .unwrap();
6279
6280 let task = q.get("20260101-000000-aaaa").expect("must still read");
6281 assert!(task.diagnostic.is_none());
6282 }
6283
6284 #[test]
6285 fn a_schema_1_task_with_no_blocking_fields_still_reads() {
6286 let (_dir, q) = queue();
6290 let path = q.path_of("20260101-000000-aaaa");
6291 std::fs::create_dir_all(q.root()).unwrap();
6292 std::fs::write(
6293 &path,
6294 serde_json::json!({
6295 "schema": 1,
6296 "id": "20260101-000000-aaaa",
6297 "title": "from before blocking existed",
6298 "instruction": "from before blocking existed",
6299 "repo": ".",
6300 "source": { "kind": "human" },
6301 "status": "queued",
6302 "created_at": Timestamp::now().to_string(),
6303 "updated_at": Timestamp::now().to_string(),
6304 })
6305 .to_string(),
6306 )
6307 .unwrap();
6308
6309 let task = q.get("20260101-000000-aaaa").expect("must still read");
6310 assert!(task.blocked_by.is_empty());
6311 assert!(task.block_reason.is_none());
6312 assert!(task.answers.is_empty());
6313 assert!(task.review_branch.is_none());
6314 }
6315
6316 #[test]
6317 fn releasing_or_finishing_a_task_clears_its_stale_diagnostic() {
6318 let mut held = task("diagnosed");
6323 held.start("run-1".to_owned());
6324 held.fail("gate red", 1);
6325 held.diagnostic = Some("cargo test failed: ...".to_owned());
6326 assert_eq!(held.status, TaskStatus::Held);
6327
6328 held.release();
6329 assert!(held.diagnostic.is_none());
6330
6331 held.diagnostic = Some("cargo test failed: ...".to_owned());
6332 held.succeed(completion(&held));
6333 assert!(held.diagnostic.is_none());
6334 }
6335
6336 #[test]
6337 fn failing_a_task_always_clears_whatever_diagnostic_it_carried() {
6338 let mut t = task("retried");
6339 t.start("run-1".to_owned());
6340 t.diagnostic = Some("stale evidence from a previous hold".to_owned());
6341 t.fail("unrelated config error", 5);
6342 assert_eq!(t.status, TaskStatus::Failed);
6343 assert!(
6344 t.diagnostic.is_none(),
6345 "fail() must not let an old diagnostic outlive the run that produced it"
6346 );
6347 }
6348
6349 #[test]
6350 fn a_claim_is_exclusive_and_releases_on_drop() {
6351 let (_dir, q) = queue();
6352 let mut t = task("contended");
6353 q.put(&mut t).unwrap();
6354
6355 let held = q.claim(&t.id).unwrap();
6356 assert!(
6357 q.claim(&t.id).is_err(),
6358 "two daemons must not drive one task into two runs"
6359 );
6360 drop(held);
6361 assert!(q.claim(&t.id).is_ok(), "a released claim is reclaimable");
6362 }
6363
6364 #[test]
6365 fn a_round_trip_survives_disk() {
6366 let (_dir, q) = queue();
6367 let mut t = Task::new(
6368 "titled".to_owned(),
6369 "body".to_owned(),
6370 PathBuf::from("/repo"),
6371 Source::Agent {
6372 run: "20260101-000000-beef".to_owned(),
6373 node: "implement".to_owned(),
6374 },
6375 );
6376 t.priority = 3;
6377 q.put(&mut t).unwrap();
6378
6379 let back = q.get(&t.id).unwrap();
6380 assert_eq!(back.id, t.id);
6381 assert_eq!(back.priority, 3);
6382 assert_eq!(back.source.label(), "implement@beef");
6383 assert_eq!(q.get(t.short()).unwrap().id, t.id);
6385 }
6386
6387 #[test]
6388 fn an_unreadable_task_does_not_take_the_queue_down() {
6389 let (_dir, q) = queue();
6390 let mut t = task("fine");
6391 q.put(&mut t).unwrap();
6392 std::fs::write(q.root().join("broken.json"), "{ not json").unwrap();
6393
6394 let listed = q.list();
6395 assert_eq!(listed.len(), 1, "the readable task still lists");
6396 assert_eq!(listed[0].id, t.id);
6397 }
6398
6399 #[test]
6400 fn a_task_recorded_without_a_solo_field_still_reads_as_not_solo() {
6401 let (_dir, q) = queue();
6402 let path = q.path_of("20260101-000000-aaaa");
6403 std::fs::create_dir_all(q.root()).unwrap();
6404 std::fs::write(
6405 &path,
6406 serde_json::json!({
6407 "schema": SCHEMA,
6408 "id": "20260101-000000-aaaa",
6409 "title": "from before solo existed",
6410 "instruction": "from before solo existed",
6411 "repo": ".",
6412 "source": { "kind": "human" },
6413 "status": "queued",
6414 "created_at": Timestamp::now().to_string(),
6415 "updated_at": Timestamp::now().to_string(),
6416 })
6417 .to_string(),
6418 )
6419 .unwrap();
6420
6421 let task = q.get("20260101-000000-aaaa").expect("must still read");
6422 assert!(!task.solo, "a queue file with no `solo` field means false");
6423 }
6424
6425 #[test]
6426 fn a_task_recorded_without_an_urgent_field_still_reads_as_not_urgent() {
6427 let (_dir, q) = queue();
6428 let path = q.path_of("20260101-000000-bbbb");
6429 std::fs::create_dir_all(q.root()).unwrap();
6430 std::fs::write(
6431 &path,
6432 serde_json::json!({
6433 "schema": SCHEMA,
6434 "id": "20260101-000000-bbbb",
6435 "title": "from before urgent existed",
6436 "instruction": "from before urgent existed",
6437 "repo": ".",
6438 "source": { "kind": "human" },
6439 "status": "queued",
6440 "created_at": Timestamp::now().to_string(),
6441 "updated_at": Timestamp::now().to_string(),
6442 })
6443 .to_string(),
6444 )
6445 .unwrap();
6446
6447 let task = q.get("20260101-000000-bbbb").expect("must still read");
6448 assert!(
6449 !task.urgent,
6450 "a queue file with no `urgent` field means false, same as `solo`"
6451 );
6452 }
6453
6454 #[test]
6455 fn a_task_from_a_future_schema_is_refused_rather_than_guessed_at() {
6456 let (_dir, q) = queue();
6457 let mut t = task("from the future");
6458 q.put(&mut t).unwrap();
6459 let path = q.path_of(&t.id);
6460 let body = std::fs::read_to_string(&path)
6461 .unwrap()
6462 .replace(&format!("\"schema\": {SCHEMA}"), "\"schema\": 99");
6463 std::fs::write(&path, body).unwrap();
6464
6465 let err = q.get(&t.id).unwrap_err().to_string();
6466 assert!(err.contains("schema 99"), "{err}");
6467 }
6468
6469 #[test]
6470 fn revision_moves_when_the_queue_changes() {
6471 let (_dir, q) = queue();
6472 assert_eq!(q.revision(), 0, "an empty queue has no revision");
6473 let mut t = task("first");
6474 q.put(&mut t).unwrap();
6475 assert!(q.revision() > 0, "a written task moves the revision");
6476 }
6477
6478 #[test]
6479 fn revision_moves_when_deleting_an_older_task() {
6480 let (dir, q) = queue();
6481 let questions = Questions::at(dir.path().join("questions"));
6482 let mut t1 = task("older");
6483 q.put(&mut t1).unwrap();
6484 std::thread::sleep(std::time::Duration::from_millis(10));
6486 let mut t2 = task("newer");
6487 q.put(&mut t2).unwrap();
6488
6489 let rev_before = q.revision();
6490 q.remove(&t1.id, false, &questions).unwrap();
6491 let rev_after = q.revision();
6492
6493 assert_ne!(
6494 rev_before, rev_after,
6495 "deleting an older task must change the revision so other clients see the deletion"
6496 );
6497 }
6498
6499 #[test]
6500 fn removing_a_task_takes_it_out_of_the_listing() {
6501 let (dir, q) = queue();
6502 let questions = Questions::at(dir.path().join("questions"));
6503 let mut t = task("delete me");
6504 q.put(&mut t).unwrap();
6505 let removed = q.remove(t.short(), false, &questions).unwrap();
6506 assert_eq!(removed.id, t.id, "a prefix resolves before deleting");
6507 assert!(removed.released.is_empty() && removed.still_blocked.is_empty());
6508 assert!(q.list().is_empty());
6509 assert!(
6510 q.remove(&t.id, false, &questions).is_err(),
6511 "removing twice is an error"
6512 );
6513 }
6514
6515 #[test]
6516 fn removing_a_task_takes_its_stale_lock_with_it() {
6517 let (dir, q) = queue();
6518 let questions = Questions::at(dir.path().join("questions"));
6519 let mut t = task("interrupted");
6520 q.put(&mut t).unwrap();
6521
6522 let claim = q.claim(&t.id).unwrap();
6525 std::mem::forget(claim);
6526 assert!(
6527 q.claim(&t.id).is_err(),
6528 "the orphaned lock is what makes the task look claimed"
6529 );
6530
6531 let err = q.remove(&t.id, true, &questions).unwrap_err().to_string();
6533 assert!(err.contains("live daemon"), "{err}");
6534 assert!(q.get(&t.id).is_ok(), "a refused delete keeps the task");
6535
6536 q.remove(&t.id, false, &questions).unwrap();
6538 assert!(q.list().is_empty());
6539 let mut again = task("interrupted");
6540 again.id = t.id.clone();
6541 q.put(&mut again).unwrap();
6542 assert!(
6543 q.claim(&t.id).is_ok(),
6544 "a task that comes back must be claimable, which a left-behind lock would prevent"
6545 );
6546 }
6547
6548 fn notices_of(dir: &Path) -> Vec<crate::notices::Notice> {
6549 crate::notices::Notices::at(dir.join("notifications")).list()
6550 }
6551
6552 #[test]
6553 fn removing_a_sole_dependency_releases_the_dependent_without_a_hold() {
6554 let (dir, q) = queue();
6555 let questions = Questions::at(dir.path().join("questions"));
6556 let mut dep = task("dependency");
6557 q.put(&mut dep).unwrap();
6558 let mut blocked = task("waiting");
6559 blocked.block(vec![dep.id.clone()], Some("waits".to_owned()));
6560 q.put(&mut blocked).unwrap();
6561
6562 let removed = q.remove(&dep.id, false, &questions).unwrap();
6563 assert_eq!(removed.released, [blocked.id.clone()]);
6564 assert!(removed.still_blocked.is_empty());
6565
6566 let after = q.get(&blocked.id).unwrap();
6567 assert_eq!(after.status, TaskStatus::Queued);
6568 assert!(after.blocked_by.is_empty());
6569 assert!(after.block_reason.is_none());
6570 let notes = notices_of(dir.path());
6571 assert_eq!(notes.len(), 1, "{notes:?}");
6572 assert_eq!(notes[0].severity, crate::notices::Severity::Info);
6573 assert_eq!(
6574 notes[0].link,
6575 Some(crate::notices::Link::Task {
6576 id: blocked.id.clone(),
6577 })
6578 );
6579 }
6580
6581 #[test]
6582 fn removing_one_of_two_dependencies_keeps_the_other() {
6583 let (dir, q) = queue();
6584 let questions = Questions::at(dir.path().join("questions"));
6585 let mut dep = task("dependency");
6586 q.put(&mut dep).unwrap();
6587 let mut other = task("other");
6588 q.put(&mut other).unwrap();
6589 let mut blocked = task("waiting");
6590 blocked.block(
6591 vec![dep.id.clone(), other.id.clone()],
6592 Some("waits on both".to_owned()),
6593 );
6594 q.put(&mut blocked).unwrap();
6595
6596 let removed = q.remove(&dep.id, false, &questions).unwrap();
6597 assert!(removed.released.is_empty());
6598 assert_eq!(removed.still_blocked, [blocked.id.clone()]);
6599
6600 let after = q.get(&blocked.id).unwrap();
6601 assert_eq!(after.status, TaskStatus::Blocked);
6602 assert_eq!(after.blocked_by, [other.id.clone()]);
6603 assert!(missing_blockers(&q, &questions, &after.blocked_by).is_empty());
6606 }
6607
6608 #[test]
6609 fn a_dependency_deleted_before_its_dependents_were_rewritten_is_released_later() {
6610 let (dir, q) = queue();
6611 let questions = Questions::at(dir.path().join("questions"));
6612 let mut dep = task("dependency");
6613 q.put(&mut dep).unwrap();
6614 let mut blocked = task("waiting");
6615 blocked.block(vec![dep.id.clone()], None);
6616 q.put(&mut blocked).unwrap();
6617
6618 let claim = q.claim(&blocked.id).unwrap();
6620 let removed = q.remove(&dep.id, false, &questions).unwrap();
6621 assert!(removed.released.is_empty());
6622 drop(claim);
6623
6624 let mut task = q.get(&blocked.id).unwrap();
6625 assert_eq!(task.status, TaskStatus::Blocked);
6626 assert!(missing_blockers(&q, &questions, &task.blocked_by).is_empty());
6627 assert_eq!(
6628 q.apply_deleted_blockers(&mut task, &questions),
6629 [dep.id.clone()]
6630 );
6631 assert_eq!(task.status, TaskStatus::Queued);
6632 }
6633
6634 #[test]
6635 fn dependency_resolution_short_deleted_reference_releases_only_its_waiters() {
6636 let (dir, q) = queue();
6637 let questions = Questions::at(dir.path().join("questions"));
6638 let mut dep = task("dependency");
6639 dep.id = "20261013-193611-ca5b".into();
6640 q.put(&mut dep).unwrap();
6641 let mut waiting = task("waiting");
6642 waiting.block(vec!["ca5b".into()], None);
6643 q.put(&mut waiting).unwrap();
6644 q.remove(&dep.id, false, &questions).unwrap();
6645 assert_eq!(q.get(&waiting.id).unwrap().status, TaskStatus::Queued);
6646 assert_eq!(
6647 dependency(&q, &questions, "ca5b"),
6648 Dependency::Deleted(dep.id)
6649 );
6650 }
6651
6652 #[test]
6653 fn dependency_resolution_preserves_cross_store_ambiguity_and_exact_ids() {
6654 let (dir, queue) = queue();
6655 let questions = Questions::at(dir.path().join("questions"));
6656 let mut dep = task("dependency");
6657 dep.id = "20261013-193611-ca5b".into();
6658 queue.put(&mut dep).unwrap();
6659 std::fs::create_dir_all(questions.root()).unwrap();
6660 let question_id = "20261014-193611-ca5b";
6661 std::fs::write(questions.path_of(question_id), "unreadable question").unwrap();
6662 assert_eq!(questions.resolve_id("ca5b").unwrap(), question_id);
6663 assert_eq!(
6664 dependency(&queue, &questions, "ca5b"),
6665 Dependency::Ambiguous
6666 );
6667 assert_eq!(
6668 dependency(&queue, &questions, &dep.id),
6669 Dependency::Task(dep.id)
6670 );
6671 assert_eq!(
6672 dependency(&queue, &questions, question_id),
6673 Dependency::Question(question_id.into())
6674 );
6675 assert_eq!(
6676 dependency(&queue, &questions, "missing"),
6677 Dependency::Missing
6678 );
6679 }
6680
6681 #[test]
6682 fn dependency_resolution_directory_errors_are_unknown_not_missing() {
6683 let dir = tempfile::tempdir().unwrap();
6684 let q = Queue::at(dir.path().join("not-a-directory"));
6685 std::fs::write(q.root(), "file").unwrap();
6686 let questions = Questions::at(dir.path().join("questions"));
6687 assert_eq!(dependency(&q, &questions, "ca5b"), Dependency::Unknown);
6688 assert!(missing_blockers(&q, &questions, &["ca5b".into()]).is_empty());
6689 }
6690
6691 #[test]
6692 fn a_dependency_without_a_tombstone_is_still_missing() {
6693 let (dir, q) = queue();
6694 let questions = Questions::at(dir.path().join("questions"));
6695 let mut dep = task("dependency");
6696 q.put(&mut dep).unwrap();
6697 std::fs::remove_file(q.path_of(&dep.id)).unwrap();
6698 assert_eq!(
6699 missing_blockers(&q, &questions, std::slice::from_ref(&dep.id)),
6700 [dep.id.clone()]
6701 );
6702 assert!(deleted_blockers(&q, &questions, std::slice::from_ref(&dep.id)).is_empty());
6703 }
6704
6705 #[test]
6706 fn a_held_dependent_is_left_alone_by_a_dependency_deletion() {
6707 let mut t = task("held");
6708 t.hold_machine(Some("because".to_owned()));
6709 t.blocked_by = vec!["gone".to_owned()];
6710 assert!(!t.dependency_deleted("gone"));
6711 assert_eq!(t.status, TaskStatus::Held);
6712 }
6713
6714 #[test]
6715 fn a_failed_record_removal_takes_the_tombstone_back() {
6716 let (_dir, q) = queue();
6717 let mut t = task("stays");
6718 q.put(&mut t).unwrap();
6719 q.write_tombstone(&t.id).unwrap();
6720 let err = q.remove_record_with_attachments(&t.id, |_| Err(std::io::Error::other("nope")));
6721 assert!(err.is_err());
6722 assert!(!q.was_deleted(&t.id));
6725 }
6726
6727 fn source_file(dir: &Path, name: &str, body: &str) -> PathBuf {
6728 let p = dir.join(name);
6729 std::fs::write(&p, body).unwrap();
6730 p
6731 }
6732
6733 #[test]
6734 fn an_attachment_copy_survives_deleting_its_source() {
6735 let (dir, q) = queue();
6736 let src = source_file(dir.path(), "shot.png", "pixels");
6737 let mut t = task("with a picture");
6738 let names = q.attach(&mut t, std::slice::from_ref(&src)).unwrap();
6739 q.put(&mut t).unwrap();
6740 std::fs::remove_file(&src).unwrap();
6741 assert_eq!(names, ["shot.png"]);
6742 let loaded = q.get(&t.id).unwrap();
6743 let paths = q.attachment_paths(&loaded);
6744 assert_eq!(paths.len(), 1);
6745 assert_eq!(std::fs::read_to_string(&paths[0]).unwrap(), "pixels");
6746 }
6747
6748 #[test]
6749 fn attachment_names_that_could_traverse_or_are_odd_are_refused() {
6750 let (dir, q) = queue();
6751 let mut t = task("bad names");
6752 for name in ["a..b.png", ".hidden", "with space.png", "-x.png"] {
6753 let src = source_file(dir.path(), name, "x");
6754 assert!(
6755 q.attach(&mut t, &[src]).is_err(),
6756 "`{name}` must be refused"
6757 );
6758 }
6759 assert!(!crate::ask::valid_asset_name("C:foo.png"));
6763 #[cfg(not(windows))]
6764 {
6765 let src = source_file(dir.path(), "C:foo.png", "x");
6766 assert!(q.attach(&mut t, &[src]).is_err());
6767 }
6768 let long = format!("{}.png", "a".repeat(70));
6769 let src = source_file(dir.path(), &long, "x");
6770 assert!(q.attach(&mut t, &[src]).is_err());
6771 assert!(t.attachments.is_empty());
6772 assert!(!q.attachments_dir(&t.id).exists());
6773 }
6774
6775 #[test]
6776 fn a_taken_attachment_name_is_numbered_not_overwritten() {
6777 let (dir, q) = queue();
6778 let a = source_file(dir.path(), "shot.png", "one");
6779 let sub = dir.path().join("other");
6780 std::fs::create_dir_all(&sub).unwrap();
6781 let b = source_file(&sub, "shot.png", "two");
6782 let mut t = task("collision");
6783 q.attach(&mut t, &[a]).unwrap();
6784 q.attach(&mut t, &[b]).unwrap();
6785 assert_eq!(t.attachments, ["shot.png", "shot-2.png"]);
6786 let paths = q.attachment_paths(&t);
6787 assert_eq!(std::fs::read_to_string(&paths[0]).unwrap(), "one");
6788 assert_eq!(std::fs::read_to_string(&paths[1]).unwrap(), "two");
6789 }
6790
6791 #[test]
6792 fn a_renumbered_name_stays_inside_the_length_bound() {
6793 let (dir, q) = queue();
6794 let name = format!("{}.png", "a".repeat(60));
6795 assert_eq!(name.len(), 64);
6796 let a = source_file(dir.path(), &name, "one");
6797 let sub = dir.path().join("other");
6798 std::fs::create_dir_all(&sub).unwrap();
6799 let b = source_file(&sub, &name, "two");
6800 let mut t = task("long");
6801 q.attach(&mut t, &[a, b]).unwrap();
6802 assert_eq!(t.attachments.len(), 2);
6803 assert!(
6804 t.attachments
6805 .iter()
6806 .all(|n| crate::ask::valid_asset_name(n))
6807 );
6808 assert!(t.attachments[1].ends_with("-2.png"));
6809 }
6810
6811 #[test]
6812 fn a_failed_attach_keeps_existing_attachments_and_leaves_no_partial_copy() {
6813 let (dir, q) = queue();
6814 let good = source_file(dir.path(), "good.png", "ok");
6815 let mut t = task("partial");
6816 q.attach(&mut t, &[good]).unwrap();
6817 let more = source_file(dir.path(), "more.png", "ok");
6818 let missing = dir.path().join("missing.png");
6819 assert!(q.attach(&mut t, &[more, missing]).is_err());
6820 assert_eq!(t.attachments, ["good.png"]);
6821 let on_disk: Vec<_> = std::fs::read_dir(q.attachments_dir(&t.id))
6822 .unwrap()
6823 .flatten()
6824 .collect();
6825 assert_eq!(on_disk.len(), 1);
6826 }
6827
6828 fn block_put(q: &Queue, t: &Task) -> PathBuf {
6830 let tmp = q.path_of(&t.id).with_extension("json.tmp");
6831 std::fs::create_dir_all(&tmp).unwrap();
6832 tmp
6833 }
6834
6835 #[test]
6836 fn a_failed_put_leaves_no_new_attachment_directory() {
6837 let (dir, q) = queue();
6838 let mut t = task("fresh");
6839 let tmp = block_put(&q, &t);
6840 let src = source_file(dir.path(), "shot.png", "x");
6841 assert!(q.attach_and_put(&mut t, &[src]).is_err());
6842 assert!(t.attachments.is_empty());
6843 assert!(!q.attachments_dir(&t.id).exists());
6844 assert!(!q.path_of(&t.id).exists());
6845 std::fs::remove_dir(tmp).unwrap();
6846 }
6847
6848 #[test]
6849 fn a_failed_put_removes_only_the_copy_it_just_made() {
6850 let (dir, q) = queue();
6851 let mut t = task("edited");
6852 let first = source_file(dir.path(), "first.png", "1");
6853 q.attach_and_put(&mut t, &[first]).unwrap();
6854 block_put(&q, &t);
6855 let second = source_file(dir.path(), "second.png", "2");
6856 assert!(q.attach_and_put(&mut t, &[second]).is_err());
6857 assert_eq!(t.attachments, ["first.png"]);
6858 let on_disk: Vec<_> = std::fs::read_dir(q.attachments_dir(&t.id))
6859 .unwrap()
6860 .flatten()
6861 .map(|e| e.file_name().to_string_lossy().into_owned())
6862 .collect();
6863 assert_eq!(on_disk, ["first.png"]);
6864 assert_eq!(q.get(&t.id).unwrap().attachments, ["first.png"]);
6865 }
6866
6867 #[test]
6868 fn a_leftover_removing_directory_is_swept_by_the_next_removal() {
6869 let (dir, q) = queue();
6870 let questions = Questions::at(dir.path().join("questions"));
6871 let gone = task("gone");
6872 let mut other = task("other");
6873 let mut live = task("live");
6874 q.put(&mut other).unwrap();
6875 q.put(&mut live).unwrap();
6876 let orphan = q.root.join(format!("{}.attachments.removing", gone.id));
6879 std::fs::create_dir_all(&orphan).unwrap();
6880 std::fs::write(orphan.join("shot.png"), "x").unwrap();
6881 let busy = q.root.join(format!("{}.attachments.removing", live.id));
6884 std::fs::create_dir_all(&busy).unwrap();
6885
6886 q.remove(&other.id, false, &questions).unwrap();
6887 assert!(!orphan.exists(), "an orphan is swept");
6888 assert!(busy.exists(), "a removal in progress is left alone");
6889 }
6890
6891 #[test]
6892 fn a_blocked_aside_rename_fails_the_removal_and_loses_nothing() {
6893 let (dir, q) = queue();
6894 let questions = Questions::at(dir.path().join("questions"));
6895 let mut t = task("stuck");
6896 let src = source_file(dir.path(), "shot.png", "x");
6897 q.attach_and_put(&mut t, &[src]).unwrap();
6898 let aside = q.root.join(format!("{}.attachments.removing", t.id));
6901 std::fs::create_dir_all(&aside).unwrap();
6902 std::fs::write(aside.join("old.png"), "o").unwrap();
6903 assert!(q.remove(&t.id, false, &questions).is_err());
6904 assert!(q.path_of(&t.id).exists());
6905 assert!(q.attachments_dir(&t.id).join("shot.png").is_file());
6906 }
6907
6908 #[test]
6909 fn a_failed_record_removal_puts_the_attachments_back() {
6910 let (dir, q) = queue();
6911 let mut t = task("rollback");
6912 let src = source_file(dir.path(), "shot.png", "x");
6913 q.attach_and_put(&mut t, &[src]).unwrap();
6914 let err = q
6915 .remove_record_with_attachments(&t.id, |_| {
6916 Err(std::io::Error::other("injected failure"))
6917 })
6918 .unwrap_err();
6919 assert!(format!("{err:#}").contains("injected failure"));
6920 assert!(q.path_of(&t.id).exists());
6921 assert!(q.attachments_dir(&t.id).join("shot.png").is_file());
6922 assert!(
6923 !q.root
6924 .join(format!("{}.attachments.removing", t.id))
6925 .exists()
6926 );
6927 }
6928
6929 #[test]
6930 fn editing_a_task_keeps_its_attachments() {
6931 let (dir, q) = queue();
6932 let src = source_file(dir.path(), "shot.png", "x");
6933 let mut t = task("editable");
6934 q.attach(&mut t, &[src]).unwrap();
6935 t.edit("new".to_owned(), "new text".to_owned()).unwrap();
6936 q.put(&mut t).unwrap();
6937 assert_eq!(q.get(&t.id).unwrap().attachments, ["shot.png"]);
6938 }
6939
6940 #[test]
6941 fn removing_a_task_deletes_its_attachments() {
6942 let (dir, q) = queue();
6943 let questions = Questions::at(dir.path().join("questions"));
6944 let src = source_file(dir.path(), "shot.png", "x");
6945 let mut t = task("doomed");
6946 q.attach(&mut t, &[src]).unwrap();
6947 q.put(&mut t).unwrap();
6948 assert!(q.attachments_dir(&t.id).is_dir());
6949 q.remove(&t.id, false, &questions).unwrap();
6950 assert!(!q.attachments_dir(&t.id).exists());
6951 assert!(q.list().is_empty());
6952 }
6953
6954 #[test]
6955 fn a_task_written_before_attachments_still_reads() {
6956 let (_dir, q) = queue();
6957 let mut t = task("old");
6958 q.put(&mut t).unwrap();
6959 let path = q.path_of(&t.id);
6960 let mut v: serde_json::Value =
6961 serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
6962 v.as_object_mut().unwrap().remove("attachments");
6963 std::fs::write(&path, v.to_string()).unwrap();
6964 assert!(q.get(&t.id).unwrap().attachments.is_empty());
6965 }
6966
6967 #[test]
6968 fn attachment_paths_are_absolute_even_when_the_root_is_relative() {
6969 let q = Queue::at(PathBuf::from("relative-queue"));
6970 let mut t = task("rel");
6971 t.attachments.push("shot.png".to_owned());
6972 let paths = q.attachment_paths(&t);
6973 assert!(paths[0].is_absolute(), "{}", paths[0].display());
6974 assert!(paths[0].ends_with(format!("{}.attachments/shot.png", t.id)));
6975 }
6976
6977 fn upgrade_parked(id: &str, started: &str) -> Task {
6978 let mut t = task(id);
6979 t.id = id.into();
6980 t.start(format!("run-{id}"));
6981 t.park("upgrade");
6982 t.record_pass_at(
6983 &format!("run-{id}"),
6984 0,
6985 Some(started.parse().unwrap()),
6986 1,
6987 Some(crate::run::ParkCause::Upgrade {
6988 from: "old".into(),
6989 to: None,
6990 }),
6991 );
6992 t
6993 }
6994
6995 #[test]
6996 fn upgrade_resume_order_follows_dispatch_claim_not_graph_start() {
6997 let stamp = |id: &str, dispatched: &str, started: &str| {
6999 let mut t = task(id);
7000 t.id = id.into();
7001 t.start(format!("run-{id}"));
7002 t.park("upgrade");
7003 t.dispatched_at = Some(dispatched.parse().unwrap());
7004 t.record_pass_at(
7005 &format!("run-{id}"),
7006 0,
7007 Some(started.parse().unwrap()),
7008 1,
7009 Some(crate::run::ParkCause::Upgrade {
7010 from: "old".into(),
7011 to: None,
7012 }),
7013 );
7014 t
7015 };
7016 let a = stamp("a", "2026-10-22T00:00:01Z", "2026-10-22T00:00:09Z");
7017 let b = stamp("b", "2026-10-22T00:00:02Z", "2026-10-22T00:00:03Z");
7018 assert!(dispatch_order(&a, &b).is_lt());
7019 }
7020
7021 #[test]
7022 fn upgrade_resume_order_survives_queue_reload_and_reversed_settlement() {
7023 let (_dir, q) = queue();
7024 let mut later = upgrade_parked("later", "2026-10-22T00:00:02Z");
7025 let mut earlier = upgrade_parked("earlier", "2026-10-22T00:00:01Z");
7026 earlier.priority = -10;
7027 let mut fresh = task("fresh");
7028 fresh.id = "newer".into();
7029 fresh.priority = 100;
7030 for t in [&mut fresh, &mut later, &mut earlier] {
7031 q.put(t).unwrap();
7032 }
7033 let reloaded = Queue::at(q.root().to_owned());
7034 let mut tasks = reloaded.list();
7035 tasks.sort_unstable_by(dispatch_order);
7036 assert_eq!(
7037 tasks.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
7038 vec!["earlier", "later", "newer"]
7039 );
7040 assert_eq!(reloaded.next_runnable().unwrap().id, "earlier");
7041 assert_eq!(reloaded.get("earlier").unwrap().attempts, 0);
7042 }
7043
7044 #[test]
7045 fn upgrade_resume_legacy_order_uses_settlement_and_id() {
7046 let mut a = upgrade_parked("a", "2026-10-22T00:00:02Z");
7047 let mut b = upgrade_parked("b", "2026-10-22T00:00:01Z");
7048 for t in [&mut a, &mut b] {
7049 let mut value = serde_json::to_value(&*t).unwrap();
7050 value["passes"][0]
7051 .as_object_mut()
7052 .unwrap()
7053 .remove("started_at");
7054 *t = serde_json::from_value(value).unwrap();
7055 }
7056 assert!(dispatch_order(&a, &b).is_lt());
7057 b.passes[0].settled_at = a.passes[0].settled_at;
7058 assert!(dispatch_order(&a, &b).is_lt());
7059 }
7060
7061 #[test]
7062 fn upgrade_resume_key_excludes_other_parks_and_explicit_task_changes() {
7063 let original = upgrade_parked("a", "2026-10-22T00:00:01Z");
7064 assert!(original.upgrade_resume_key().is_some());
7065 for cause in [
7066 crate::run::ParkCause::Operator,
7067 crate::run::ParkCause::Question,
7068 crate::run::ParkCause::Interrupt {
7069 reason: "interrupt".into(),
7070 },
7071 crate::run::ParkCause::Unspecified,
7072 ] {
7073 let mut t = original.clone();
7074 t.passes[0].parked = Some(cause);
7075 assert!(t.upgrade_resume_key().is_none());
7076 let mut fresh = task("fresh");
7077 fresh.priority = 1;
7078 assert!(dispatch_order(&fresh, &t).is_lt());
7079 }
7080 let mut t = original.clone();
7081 t.release();
7082 assert!(t.upgrade_resume_key().is_none());
7083 t.edit("edited".into(), "new instruction".into()).unwrap();
7084 assert!(t.upgrade_resume_key().is_none());
7085 let mut t = original.clone();
7086 t.requeue();
7087 t.status = TaskStatus::Parked;
7088 assert!(t.upgrade_resume_key().is_none());
7089 let mut t = original.clone();
7090 t.start("different-run".into());
7091 t.park("no upgrade");
7092 assert!(t.upgrade_resume_key().is_none());
7093 }
7094
7095 #[test]
7096 fn explicitly_resumed_older_run_becomes_current_without_duplicate_history() {
7097 let dir = tempfile::tempdir().unwrap();
7098 let q = Queue::at(dir.path().join("queue"));
7099 let mut t = task("resume");
7100 t.start("A".into());
7101 t.record_pass("A", 0, 1, None);
7102 t.start("B".into());
7103 q.put(&mut t).unwrap();
7104 assert_eq!(t.runs, vec!["A", "B"]);
7105 t.start("A".into());
7106 t.record_pass("A", 1, 3, None);
7107 q.put(&mut t).unwrap();
7108 let saved = q.get(&t.id).unwrap();
7109 assert_eq!(saved.runs, vec!["B", "A"]);
7110 assert_eq!(saved.runs.last().map(String::as_str), Some("A"));
7111 assert_eq!(saved.attempts, 3);
7112 assert_eq!(saved.passes.len(), 2);
7113 assert_eq!(saved.passes[0].run, "A");
7114 assert_eq!(saved.passes[1].run, "A");
7115 }
7116
7117 #[test]
7118 fn repeated_start_records_one_run_and_separate_passes() {
7119 let mut t = task("resume");
7120 t.start("same-run".into());
7121 t.record_pass("same-run", 0, 1, None);
7122 t.start("same-run".into());
7123 t.record_pass("same-run", 1, 2, None);
7124 assert_eq!(t.runs, vec!["same-run"]);
7125 assert_eq!(t.attempts, 2);
7126 assert_eq!(t.passes.len(), 2);
7127 }
7128
7129 #[test]
7130 fn link_run_adds_a_run_once_and_touches_nothing_else() {
7131 let dir = tempfile::tempdir().unwrap();
7132 let queue = Queue::at(dir.path().join("queue"));
7133 let mut t = Task::new(
7134 "t".to_owned(),
7135 "do it".to_owned(),
7136 PathBuf::from("."),
7137 Source::Human,
7138 );
7139 queue.put(&mut t).unwrap();
7140 let before = queue.get(&t.id).unwrap();
7141
7142 let linked = queue.link_run(&t.id[..4], "20260930-092817-ec34").unwrap();
7143 assert_eq!(linked.runs, vec!["20260930-092817-ec34".to_owned()]);
7144 assert_eq!(linked.status, before.status);
7145 assert_eq!(linked.attempts, before.attempts);
7146 assert_eq!(linked.interrupt, before.interrupt);
7147
7148 let again = queue.link_run(&t.id, "20260930-092817-ec34").unwrap();
7149 assert_eq!(again.runs.len(), 1, "linking twice must not duplicate");
7150 assert_eq!(queue.get(&t.id).unwrap().runs.len(), 1);
7151 assert!(queue.link_run("no-such-task", "r").is_err());
7152 }
7153
7154 #[test]
7155 fn put_keeps_a_run_linked_after_the_writer_took_its_snapshot() {
7156 let dir = tempfile::tempdir().unwrap();
7157 let queue = Queue::at(dir.path().join("queue"));
7158 let mut t = Task::new(
7159 "t".to_owned(),
7160 "do it".to_owned(),
7161 PathBuf::from("."),
7162 Source::Human,
7163 );
7164 queue.put(&mut t).unwrap();
7165 let mut snapshot = queue.get(&t.id).unwrap();
7167 queue.link_run(&t.id, "20260930-092817-ec34").unwrap();
7168
7169 snapshot.start("20260930-000000-aaaa".to_owned());
7170 queue.put(&mut snapshot).unwrap();
7171
7172 let stored = queue.get(&t.id).unwrap();
7173 assert!(stored.runs.contains(&"20260930-092817-ec34".to_owned()));
7174 assert!(stored.runs.contains(&"20260930-000000-aaaa".to_owned()));
7175 assert_eq!(stored.attempts, 1);
7176 }
7177
7178 #[test]
7179 fn concurrent_links_and_daemon_saves_lose_nothing() {
7180 let dir = tempfile::tempdir().unwrap();
7181 let queue = Queue::at(dir.path().join("queue"));
7182 let mut t = Task::new(
7183 "t".to_owned(),
7184 "do it".to_owned(),
7185 PathBuf::from("."),
7186 Source::Human,
7187 );
7188 queue.put(&mut t).unwrap();
7189 let id = t.id.clone();
7190
7191 let linkers: Vec<_> = (0..4)
7192 .map(|n| {
7193 let (queue, id) = (queue.clone(), id.clone());
7194 std::thread::spawn(move || {
7195 for k in 0..10 {
7196 queue
7197 .link_run(&id, &format!("20260930-00000{n}-l{k:03}"))
7198 .unwrap();
7199 }
7200 })
7201 })
7202 .collect();
7203 let mut mine = queue.get(&id).unwrap();
7206 for k in 0..10 {
7207 mine.start(format!("20260930-000009-d{k:03}"));
7208 queue.put(&mut mine).unwrap();
7209 }
7210 for l in linkers {
7211 l.join().unwrap();
7212 }
7213
7214 let stored = queue.get(&id).unwrap();
7215 assert_eq!(stored.runs.len(), 50, "{:?}", stored.runs);
7216 assert_eq!(
7217 stored.attempts, 10,
7218 "linking never rewinds the daemon's work"
7219 );
7220 }
7221
7222 fn age_lock(path: &Path) {
7223 let f = std::fs::OpenOptions::new().write(true).open(path).unwrap();
7224 f.set_modified(std::time::SystemTime::now() - std::time::Duration::from_secs(60))
7225 .unwrap();
7226 }
7227
7228 #[test]
7229 fn concurrent_stale_takeover_yields_one_holder() {
7230 use std::sync::atomic::{AtomicUsize, Ordering};
7231 use std::sync::{Arc, Barrier};
7232 for _ in 0..5 {
7233 let dir = tempfile::tempdir().unwrap();
7234 let q = Queue::at(dir.path().to_path_buf());
7235 let lock = dir.path().join("t.write-lock");
7236 std::fs::write(&lock, "dead-0000").unwrap();
7237 age_lock(&lock);
7238 let n = 6;
7239 let barrier = Arc::new(Barrier::new(n));
7240 let (now, max) = (Arc::new(AtomicUsize::new(0)), Arc::new(AtomicUsize::new(0)));
7241 let handles: Vec<_> = (0..n)
7242 .map(|_| {
7243 let (q, b, now, max) = (q.clone(), barrier.clone(), now.clone(), max.clone());
7244 std::thread::spawn(move || {
7245 b.wait();
7246 let g = q.lock_task("t").unwrap();
7247 let held = now.fetch_add(1, Ordering::SeqCst) + 1;
7248 max.fetch_max(held, Ordering::SeqCst);
7249 std::thread::sleep(std::time::Duration::from_millis(20));
7250 now.fetch_sub(1, Ordering::SeqCst);
7251 drop(g);
7252 })
7253 })
7254 .collect();
7255 for h in handles {
7256 h.join().unwrap();
7257 }
7258 assert_eq!(max.load(Ordering::SeqCst), 1);
7259 assert!(!lock.exists());
7260 }
7261 }
7262
7263 #[test]
7264 fn dropping_a_replaced_lock_leaves_the_new_holders_token() {
7265 let dir = tempfile::tempdir().unwrap();
7266 let q = Queue::at(dir.path().to_path_buf());
7267 let lock = dir.path().join("t.write-lock");
7268 let a = q.lock_task("t").unwrap();
7269 let replacement = owner_token();
7272 std::fs::write(&lock, &replacement).unwrap();
7273 drop(a);
7274 assert_eq!(std::fs::read_to_string(&lock).unwrap(), replacement);
7275 }
7276
7277 #[test]
7278 fn aged_live_task_lock_excludes_updates_until_retirement_releases_it() {
7279 let dir = tempfile::tempdir().unwrap();
7280 let q = Queue::at(dir.path().to_path_buf());
7281 let held = q.lock_task("t").unwrap();
7282 let path = dir.path().join("t.write-lock");
7283 age_lock(&path);
7284 assert!(!break_stale(&path, &held.token));
7285 let (started_tx, started_rx) = std::sync::mpsc::channel();
7286 let (acquired_tx, acquired_rx) = std::sync::mpsc::channel();
7287 let updater = std::thread::spawn(move || {
7288 started_tx.send(()).unwrap();
7289 let _write = q.lock_task("t").unwrap();
7290 acquired_tx.send(()).unwrap();
7291 });
7292 started_rx.recv().unwrap();
7293 assert!(
7294 acquired_rx
7295 .recv_timeout(std::time::Duration::from_millis(100))
7296 .is_err()
7297 );
7298 assert_eq!(std::fs::read_to_string(&path).unwrap(), held.token);
7299 drop(held);
7300 acquired_rx
7301 .recv_timeout(std::time::Duration::from_secs(2))
7302 .unwrap();
7303 updater.join().unwrap();
7304 assert!(!path.exists());
7305 }
7306
7307 #[test]
7308 fn break_stale_leaves_a_lock_that_replaced_the_one_judged() {
7309 let dir = tempfile::tempdir().unwrap();
7310 let lock = dir.path().join("t.write-lock");
7311 std::fs::write(&lock, "new-token").unwrap();
7312 assert!(!break_stale(&lock, "old-token"));
7313 assert_eq!(std::fs::read_to_string(&lock).unwrap(), "new-token");
7314 assert!(!break_stale(&lock, "new-token"));
7316 assert!(lock.exists());
7317 age_lock(&lock);
7318 assert!(break_stale(&lock, "new-token"));
7319 assert!(!lock.exists());
7320 }
7321
7322 #[test]
7323 fn a_stale_break_marker_is_recovered_and_a_fresh_one_is_respected() {
7324 let dir = tempfile::tempdir().unwrap();
7325 let lock = dir.path().join("t.write-lock");
7326 std::fs::write(&lock, "dead-1").unwrap();
7327 age_lock(&lock);
7328 let marker = break_marker(&lock, "dead-1");
7329 std::fs::write(&marker, "crashed-remover").unwrap();
7330 assert!(!break_stale(&lock, "dead-1"));
7332 assert!(lock.exists());
7333 age_lock(&marker);
7335 assert!(break_stale(&lock, "dead-1"));
7336 assert!(!lock.exists());
7337 assert!(!marker.exists());
7338 }
7339
7340 fn chat_task() -> Task {
7341 Task::new(
7342 "t".to_owned(),
7343 "do t".to_owned(),
7344 PathBuf::from("."),
7345 Source::Agent {
7346 run: "20260902-000000-beef".to_owned(),
7347 node: CHAT_NODE.to_owned(),
7348 },
7349 )
7350 }
7351
7352 #[test]
7353 fn a_blocked_hold_keeps_its_anchor_but_a_new_run_starts_a_new_hold() {
7354 let mut t = chat_task();
7355 t.hold_machine(Some("waiting".into()));
7356 let old: Timestamp = "2020-01-01T00:00:00Z".parse().unwrap();
7357 t.held_at = Some(old);
7358 t.block(vec!["decision".into()], None);
7359 t.hold_machine(Some("same waiting decision".into()));
7360 assert_eq!(t.held_at, Some(old));
7361 t.start("real-new-run".into());
7362 t.fail("new failure", 1);
7363 assert_ne!(
7364 t.held_at,
7365 Some(old),
7366 "old answers cannot approve a new hold"
7367 );
7368 }
7369
7370 #[test]
7371 fn legacy_delivery_survives_upgrade_and_a_no_progress_run_link() {
7372 let (_dir, queue) = queue();
7373 let mut t = chat_task();
7374 t.start("old-run".into());
7375 t.hold_machine(Some("operator is considering recovery".into()));
7376 t.chat_notice = Some(ChatNotice {
7377 key: format!("held#{}", t.held_at.unwrap()),
7378 at: Timestamp::now(),
7379 outcome: ChatNoticeOutcome::Posted,
7380 });
7381 let mut raw = serde_json::to_value(&t).unwrap();
7382 raw.as_object_mut().unwrap().remove("chat_notices");
7383 raw.as_object_mut().unwrap().remove("hold_notice_cause");
7384 std::fs::create_dir_all(queue.path_of(&t.id).parent().unwrap()).unwrap();
7385 std::fs::write(queue.path_of(&t.id), serde_json::to_string(&raw).unwrap()).unwrap();
7386 assert_eq!(queue.get(&t.id).unwrap().chat_notice_due(), None);
7387 queue
7388 .modify(&t.id, |task| {
7389 task.requeue();
7390 task.link_run("unprepared-run");
7391 task.startup_notice_cause("startup-source");
7392 task.fail("same unresolved preflight", 0);
7393 true
7394 })
7395 .unwrap();
7396 assert_eq!(queue.get(&t.id).unwrap().chat_notice_due(), None);
7397 queue
7398 .modify(&t.id, |task| {
7399 task.succeed(completion(task));
7400 true
7401 })
7402 .unwrap();
7403 assert!(
7404 queue
7405 .get(&t.id)
7406 .unwrap()
7407 .chat_notice_due()
7408 .unwrap()
7409 .starts_with("done:")
7410 );
7411 }
7412
7413 #[test]
7414 fn a_dependency_wait_does_not_change_when_released_and_blocked_again() {
7415 let mut t = chat_task();
7416 t.block(vec!["a".into(), "b".into()], Some("waiting".into()));
7417 let key = t.chat_notice_key().unwrap();
7418 t.chat_notices.push(key);
7419 t.release();
7420 t.block(
7421 vec!["b".into(), "a".into(), "a".into()],
7422 Some("still waiting on prerequisites".into()),
7423 );
7424 assert_eq!(t.chat_notice_due(), None);
7425 t.block(
7426 vec!["new-question".into()],
7427 Some("different decision".into()),
7428 );
7429 assert!(t.chat_notice_due().is_some());
7430 }
7431
7432 #[test]
7433 fn running_startup_failures_preserve_stage_and_report_distinct_blockers() {
7434 let mut t = chat_task();
7435 t.start("existing-run".into());
7436 t.fail("implementation failed", 1);
7437 let failed = t.chat_notice_key().unwrap();
7438 t.chat_notices.push(failed.clone());
7439 t.release_operator("test", None);
7440 t.start("existing-run".into());
7441 t.fail_startup("startup-source", "same unresolved recovery source", 1);
7442 assert_eq!(
7443 t.chat_notice_due(),
7444 None,
7445 "no-progress recovery stays quiet"
7446 );
7447 t.release_operator("test", None);
7448 t.start("existing-run".into());
7449 t.fail_startup("startup-attachments", "attachment missing", 1);
7450 let attachments = t.chat_notice_due().expect("new attachment blocker");
7451 assert_ne!(attachments, failed);
7452 assert_eq!(
7453 t.hold_notice_cause.as_ref().unwrap().stage,
7454 "startup-attachments"
7455 );
7456 t.chat_notices.push(attachments);
7457 t.release_operator("test", None);
7458 t.start("existing-run".into());
7459 t.fail_startup(
7460 "startup-attachments",
7461 "same missing attachment, reworded",
7462 1,
7463 );
7464 assert_eq!(
7465 t.chat_notice_due(),
7466 None,
7467 "same stage after attempt counter reset"
7468 );
7469 t.release_operator("test", None);
7470 t.start("existing-run".into());
7471 t.fail_startup("startup-config", "different preflight stage", 1);
7472 assert!(t.chat_notice_due().is_some());
7473 assert_eq!(
7474 t.hold_notice_cause.as_ref().unwrap().stage,
7475 "startup-config"
7476 );
7477 }
7478
7479 #[test]
7480 fn structured_causes_preserve_no_progress_retries_and_report_new_passes() {
7481 let mut t = chat_task();
7482 t.hold_machine(Some("startup source missing".into()));
7483 t.startup_notice_cause("startup-source");
7484 let first = t.chat_notice_key().unwrap();
7485 t.chat_notices.push(first.clone());
7486 t.release_operator("test", None);
7487 t.startup_notice_cause("startup-source");
7488 t.hold_machine(Some("same source cannot be read".into()));
7489 assert_eq!(t.chat_notice_due(), None);
7490 t.startup_notice_cause("startup-config");
7491 assert!(t.chat_notice_due().is_some(), "different startup stage");
7492 t.notice_cause("failed", Some("existing-run"), Some(0));
7493 let run_failure = t.chat_notice_key().unwrap();
7494 t.chat_notices.push(run_failure.clone());
7495 t.release_operator("test", None);
7496 t.startup_notice_cause("startup-source");
7497 t.hold_machine(Some("no new work happened".into()));
7498 assert_eq!(t.chat_notice_due(), None);
7499 t.notice_cause("failed", Some("existing-run"), Some(1));
7500 assert!(t.chat_notice_due().is_some(), "a real resumed pass failed");
7501 assert_ne!(t.chat_notice_key().unwrap(), run_failure);
7502 }
7503
7504 #[test]
7505 fn legacy_hold_baseline_does_not_replay_or_hide_new_failures_and_completion() {
7506 let mut t = chat_task();
7507 t.hold_machine(Some("still waiting".into()));
7508 t.chat_notice = Some(ChatNotice {
7509 key: "held#2026-10-14T00:00:00Z".into(),
7510 at: Timestamp::now(),
7511 outcome: ChatNoticeOutcome::Posted,
7512 });
7513 assert_eq!(t.chat_notice_due(), None, "old hold baseline");
7514 t.import_chat_notice();
7515 t.notice_cause("failed", Some("new-run"), Some(0));
7516 assert!(t.chat_notice_due().is_some(), "new producer evidence");
7517 t.succeed(completion(&t));
7518 assert!(t.chat_notice_due().unwrap().starts_with("done:"));
7519 }
7520
7521 #[test]
7522 fn a_chat_notice_is_due_only_for_a_final_state_and_only_once() {
7523 let mut t = chat_task();
7524 assert_eq!(t.chat_notice_due(), None, "queued");
7525 t.start("r1".to_owned());
7526 assert_eq!(t.chat_notice_due(), None, "running");
7527 t.fail("boom", 3);
7528 assert_eq!(t.status, TaskStatus::Failed);
7529 assert_eq!(t.chat_notice_due(), None, "a retried failure is not final");
7530 t.start("r2".to_owned());
7531 t.park("upgrade");
7532 assert_eq!(t.chat_notice_due(), None, "parked");
7533 t.fail("boom", 1);
7534 assert_eq!(t.status, TaskStatus::Held);
7535 let key = t
7536 .chat_notice_due()
7537 .expect("held on the last attempt is final");
7538 t.chat_notice = Some(ChatNotice {
7539 key,
7540 at: Timestamp::now(),
7541 outcome: ChatNoticeOutcome::Posted,
7542 });
7543 assert_eq!(t.chat_notice_due(), None, "same hold, no second notice");
7544 t.release();
7545 assert_eq!(t.chat_notice_due(), None, "requeued after a release");
7546 t.start("r3".to_owned());
7547 t.succeed(completion(&t));
7548 assert!(t.chat_notice_due().is_some(), "done is a new final state");
7549 }
7550
7551 #[test]
7552 fn legacy_completion_receipts_do_not_suppress_new_occurrences() {
7553 for key in ["done", "done#0", "done#1", "done#12"] {
7554 let mut t = chat_task();
7555 t.status = TaskStatus::Done;
7556 t.chat_notice = Some(ChatNotice {
7557 key: key.to_owned(),
7558 at: Timestamp::now(),
7559 outcome: ChatNoticeOutcome::Posted,
7560 });
7561 assert_eq!(t.chat_notice_key().as_deref(), Some("done"));
7562 assert_eq!(t.chat_notice_due(), None, "legacy recorded key: {key}");
7563 let mut context = completion(&t);
7564 context.reason = Some("inspect again".into());
7565 t.reopen(context).unwrap();
7566 t.start("r2".to_owned());
7567 t.succeed(completion(&t));
7568 assert!(t.chat_notice_key().unwrap().starts_with("done:"));
7569 assert!(
7570 t.chat_notice_due().is_some(),
7571 "new occurrence, old receipt: {key}"
7572 );
7573 }
7574 }
7575
7576 #[test]
7577 fn a_release_without_progress_keeps_the_unresolved_notice_cause() {
7578 let mut t = chat_task();
7579 t.hold_manual(Some("wait".to_owned()));
7580 let first = t.chat_notice_due().expect("held");
7581 t.chat_notice = Some(ChatNotice {
7582 key: first.clone(),
7583 at: Timestamp::now(),
7584 outcome: ChatNoticeOutcome::Posted,
7585 });
7586 t.hold_manual(Some("still waiting".to_owned()));
7587 assert_eq!(t.chat_notice_due(), None, "a re-hold keeps its start");
7588 t.release();
7589 std::thread::sleep(std::time::Duration::from_millis(5));
7590 t.hold_manual(None);
7591 assert_eq!(t.chat_notice_due(), None, "no progress, same cause");
7592 }
7593
7594 #[test]
7595 fn a_chat_notice_needs_a_chat_source_and_a_current_schema() {
7596 let mut human = task("h");
7597 human.succeed(completion(&human));
7598 assert_eq!(human.chat_notice_due(), None);
7599 let mut inherited = task("i");
7601 inherited.origin_chat = Some("20260902-000000-beef".to_owned());
7602 inherited.succeed(completion(&inherited));
7603 assert_eq!(inherited.chat_notice_due(), None);
7604 let mut old = chat_task();
7605 old.schema = 12;
7606 old.status = TaskStatus::Done;
7607 assert_eq!(old.chat_notice_due(), None, "history is not replayed");
7608 let mut live = chat_task();
7609 live.schema = 12;
7610 live.start("r1".to_owned());
7611 live.succeed(completion(&live));
7612 assert!(live.chat_notice_due().is_some(), "started by this build");
7613 let mut held = chat_task();
7614 held.schema = 12;
7615 held.hold_machine(Some("config".to_owned()));
7616 assert!(held.chat_notice_due().is_some(), "held before any start");
7617 }
7618
7619 #[test]
7620 fn a_stale_snapshot_does_not_rewind_a_recorded_chat_notice() {
7621 let tmp = tempfile::tempdir().expect("tempdir");
7622 let q = Queue::at(tmp.path().join("queue"));
7623 let mut t = chat_task();
7624 t.succeed(completion(&t));
7625 q.put(&mut t).expect("put");
7626 let mut stale = q.get(&t.id).expect("get");
7627 let key = t.chat_notice_due().expect("due");
7628 q.modify(&t.id, |x| {
7629 x.chat_notice = Some(ChatNotice {
7630 key: key.clone(),
7631 at: Timestamp::now(),
7632 outcome: ChatNoticeOutcome::Posted,
7633 });
7634 true
7635 })
7636 .expect("modify");
7637 q.put(&mut stale).expect("stale put");
7638 assert_eq!(q.get(&t.id).expect("get").chat_notice_due(), None);
7639 }
7640
7641 #[test]
7642 fn empty_sources_are_omitted_so_older_builds_still_read_the_task() {
7643 let mut t = task("plain");
7646 let value = serde_json::to_value(&t).unwrap();
7647 assert!(value.get("sources").is_none(), "{value}");
7648 t.sources.pick_commits.push(crate::refs::Input {
7649 token: "abc1234".into(),
7650 sha: "a".repeat(40),
7651 provenance: crate::refs::Provenance::ExplicitCli,
7652 });
7653 let value = serde_json::to_value(&t).unwrap();
7654 assert_eq!(value["sources"]["pick_commits"][0]["sha"], "a".repeat(40));
7655 let restored: Task = serde_json::from_value(value).unwrap();
7656 assert_eq!(restored.sources, t.sources);
7657 }
7658
7659 fn queue_with_ids(dir: &Path, ids: &[&str]) -> Queue {
7661 let ids: Vec<String> = ids.iter().map(|s| (*s).to_owned()).collect();
7662 let n = std::sync::atomic::AtomicUsize::new(0);
7663 Queue::at(dir.join("queue")).with_id_source(move || {
7664 let i = n.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
7665 ids.get(i)
7666 .cloned()
7667 .unwrap_or_else(|| format!("20260101-000000-f{i:03x}"))
7668 })
7669 }
7670
7671 const TAKEN: &str = "20260101-000000-aaaa";
7672
7673 #[test]
7674 fn a_new_task_never_merges_into_a_record_with_its_candidate_id() {
7675 let dir = tempfile::tempdir().unwrap();
7676 let q = queue_with_ids(dir.path(), &[TAKEN, TAKEN]);
7677 let mut first = task("first");
7678 first.start("run-1".into());
7679 first.succeed(completion(&first));
7680 q.put(&mut first).unwrap();
7681 assert_eq!(first.id, TAKEN);
7682 let stored_before = q.get(&first.id).unwrap();
7683 assert!(!stored_before.runs.is_empty());
7684
7685 let mut second = task("second");
7686 q.put(&mut second).unwrap();
7687
7688 assert_ne!(second.id, first.id);
7689 assert!(second.runs.is_empty());
7690 assert!(second.passes.is_empty());
7691 assert!(second.chat_notices.is_empty());
7692 assert!(second.chat_notice.is_none());
7693 assert_eq!(second.chat_notice_due(), task("fresh").chat_notice_due());
7694 let a = q.get(&first.id).unwrap();
7695 let b = q.get(&second.id).unwrap();
7696 assert_eq!(a.title, "first");
7697 assert_eq!(a.runs, stored_before.runs);
7698 assert_eq!(a.passes, stored_before.passes);
7699 assert_eq!(a.chat_notices, stored_before.chat_notices);
7700 assert_eq!(a.chat_notice, stored_before.chat_notice);
7701 assert_eq!(a.chat_notice_due(), stored_before.chat_notice_due());
7702 assert_eq!(b.title, "second");
7703 assert!(b.runs.is_empty());
7704 assert!(b.passes.is_empty());
7705 assert!(b.chat_notice.is_none());
7706
7707 let mut again = q.get(&second.id).unwrap();
7709 again.title = "second, edited".into();
7710 q.put(&mut again).unwrap();
7711 assert_eq!(q.get(&second.id).unwrap().title, "second, edited");
7712 assert_eq!(q.list().len(), 2);
7713 }
7714
7715 #[test]
7716 fn a_new_task_skips_an_id_with_an_orphaned_claim_or_attachments() {
7717 let dir = tempfile::tempdir().unwrap();
7718 let q = queue_with_ids(dir.path(), &["orphan-lock", "orphan-dir", "free"]);
7719 std::fs::create_dir_all(q.root()).unwrap();
7720 std::fs::write(q.root().join("orphan-lock.lock"), "x").unwrap();
7721 std::fs::create_dir_all(q.attachments_dir("orphan-dir")).unwrap();
7722 let mut t = task("t");
7723 q.put(&mut t).unwrap();
7724 assert_eq!(t.id, "free");
7725 }
7726
7727 #[test]
7728 fn a_claimed_new_task_holds_the_claim_on_the_reserved_id() {
7729 let dir = tempfile::tempdir().unwrap();
7730 let q = queue_with_ids(dir.path(), &[TAKEN, TAKEN]);
7731 let mut first = task("first");
7732 q.put(&mut first).unwrap();
7733 let mut second = task("second");
7734 let claim = q.file_claimed(&mut second).unwrap();
7735 assert_ne!(second.id, first.id);
7736 assert!(q.claim(&second.id).is_err());
7737 assert!(q.claim(&first.id).is_ok(), "the first task was not claimed");
7738 drop(claim);
7739 }
7740
7741 #[test]
7742 fn an_attached_new_task_skips_a_taken_id() {
7743 let dir = tempfile::tempdir().unwrap();
7744 let q = queue_with_ids(dir.path(), &[TAKEN, TAKEN]);
7745 let mut first = task("first");
7746 q.put(&mut first).unwrap();
7747 let src = source_file(dir.path(), "shot.png", "x");
7748 let mut second = task("second");
7749 q.attach_and_put(&mut second, &[src]).unwrap();
7750 assert_ne!(second.id, first.id);
7751 assert!(!q.attachments_dir(&first.id).exists());
7752 assert_eq!(q.attachment_paths(&second).len(), 1);
7753 assert!(q.attachment_paths(&second)[0].is_file());
7754 }
7755
7756 #[test]
7757 fn attaching_before_putting_a_new_task_reserves_the_id() {
7758 let dir = tempfile::tempdir().unwrap();
7759 let q = queue_with_ids(dir.path(), &[TAKEN, TAKEN]);
7760 let mut first = task("first");
7761 q.put(&mut first).unwrap();
7762 let src = source_file(dir.path(), "shot.png", "x");
7763 let mut second = task("second");
7764 q.attach(&mut second, &[src]).unwrap();
7765 assert_ne!(second.id, first.id);
7766 assert!(q.attachments_dir(&second.id).is_dir());
7767 q.put(&mut second).unwrap();
7768 assert_eq!(q.get(&second.id).unwrap().attachments.len(), 1);
7769 assert_eq!(q.get(&first.id).unwrap().title, "first");
7770 assert!(q.get(&first.id).unwrap().attachments.is_empty());
7771 }
7772
7773 #[test]
7774 fn create_new_keeps_its_already_exists_meaning() {
7775 let dir = tempfile::tempdir().unwrap();
7776 let q = Queue::at(dir.path().join("queue"));
7777 let mut a = task("a");
7778 a.id = "fixed-id".into();
7779 assert!(q.create_new(&mut a).unwrap());
7780 let mut b = task("b");
7781 b.id = "fixed-id".into();
7782 assert!(!q.create_new(&mut b).unwrap());
7783 assert_eq!(q.get("fixed-id").unwrap().title, "a");
7784 }
7785
7786 #[test]
7787 fn filing_gives_up_when_no_id_is_ever_free() {
7788 let dir = tempfile::tempdir().unwrap();
7789 let q = Queue::at(dir.path().join("queue")).with_id_source(|| TAKEN.to_owned());
7790 let mut first = task("first");
7791 q.put(&mut first).unwrap();
7792 let mut second = task("second");
7793 assert!(q.put(&mut second).is_err());
7794 assert_eq!(q.get(&first.id).unwrap().title, "first");
7795 }
7796}