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 stale_pr_attention(&self, home: &Path) -> Option<String> {
1363 if self.status != TaskStatus::Done {
1364 return None;
1365 }
1366 let run = crate::run::RunState::load_under(self.execution_runs().last()?, home).ok()?;
1367 self.assignment_accepts(&run)
1368 .then(|| run.stale_pr_cause())
1369 .flatten()
1370 }
1371
1372 pub fn execution_run(&self, run: &str) -> bool {
1374 self.execution_runs().iter().any(|id| id == run)
1375 }
1376
1377 pub(crate) fn assignment_accepts(&self, run: &crate::run::RunState) -> bool {
1379 self.reassignments.last().is_none_or(|boundary| {
1380 self.execution_run(&run.id)
1381 && run.task_assignment == self.reassignments.len()
1382 && run.created_at > boundary.at
1383 && run
1384 .repo
1385 .canonicalize()
1386 .ok()
1387 .zip(self.repo.canonicalize().ok())
1388 .is_some_and(|(run_repo, task_repo)| run_repo == task_repo)
1389 })
1390 }
1391
1392 pub(crate) fn stale_question(&self, q: &crate::ask::Question) -> bool {
1394 self.reassignments
1395 .last()
1396 .is_some_and(|r| q.asked_at <= r.at)
1397 || (self.runs.contains(&q.run) && !self.execution_run(&q.run))
1398 }
1399
1400 pub fn chat_talk(&self) -> Option<&str> {
1402 if let Some(id) = &self.origin_chat {
1403 return Some(id);
1404 }
1405 match &self.source {
1406 Source::Agent { run, node } if node == CHAT_NODE => Some(run),
1407 _ => None,
1408 }
1409 }
1410
1411 pub fn filed_by_chat(&self) -> Option<&str> {
1415 match &self.source {
1416 Source::Agent { run, node } if node == CHAT_NODE => Some(run),
1417 _ => None,
1418 }
1419 }
1420
1421 pub fn chat_notice_key(&self) -> Option<String> {
1424 match self.status {
1425 TaskStatus::Done => Some(
1426 self.completion_history
1427 .iter()
1428 .rev()
1429 .find(|event| event.action == CompletionAction::Complete)
1430 .map_or_else(
1431 || "done".to_owned(),
1432 |event| format!("done:{}", event.occurrence),
1433 ),
1434 ),
1435 TaskStatus::Held => {
1436 let cause = self
1437 .hold_notice_cause
1438 .clone()
1439 .unwrap_or_else(|| self.unresolved_hold_cause());
1440 Some(format!(
1441 "cause:{}",
1442 serde_json::to_string(&cause).expect("cause")
1443 ))
1444 }
1445 TaskStatus::Blocked => {
1446 let ids: std::collections::BTreeSet<_> = self.blocked_by.iter().collect();
1447 let evidence = self
1450 .hold_notice_cause
1451 .as_ref()
1452 .filter(|c| c.stage.starts_with("conductor-evidence:"));
1453 Some(format!(
1454 "dependencies:{}",
1455 serde_json::to_string(&(ids, evidence)).expect("ids")
1456 ))
1457 }
1458 _ => None,
1459 }
1460 }
1461
1462 fn unresolved_hold_cause(&self) -> NoticeCause {
1463 NoticeCause {
1464 stage: "hold".into(),
1465 target: None,
1466 run: self.runs.last().cloned(),
1467 pass: None,
1468 }
1469 }
1470
1471 pub(crate) fn legacy_chat_notice_key(&self) -> Option<String> {
1473 let key = match self.status {
1474 TaskStatus::Held if self.hold_notice_cause.is_none() => Some(format!(
1475 "held#{}",
1476 self.held_at.map(|t| t.to_string()).unwrap_or_default()
1477 )),
1478 TaskStatus::Blocked => Some(format!(
1479 "blocked#{}#{}",
1480 self.blocked_by.join(","),
1481 self.block_reason.as_deref().unwrap_or_default()
1482 )),
1483 _ => None,
1484 };
1485 key.filter(|key| self.legacy_notice_matches(key))
1486 }
1487
1488 pub(crate) fn legacy_notice_matches(&self, key: &str) -> bool {
1489 match self.status {
1490 TaskStatus::Held if self.hold_notice_cause.is_none() => key
1491 .strip_prefix("held#")
1492 .is_some_and(|time| time.is_empty() || time.parse::<Timestamp>().is_ok()),
1493 TaskStatus::Blocked
1494 if self
1495 .hold_notice_cause
1496 .as_ref()
1497 .is_none_or(|c| !c.stage.starts_with("conductor-evidence:")) =>
1498 {
1499 key.strip_prefix("blocked#").is_some_and(|tail| {
1500 let Some((ids, _)) = tail.split_once('#') else {
1501 return false;
1502 };
1503 let old: std::collections::BTreeSet<_> =
1504 ids.split(',').filter(|id| !id.is_empty()).collect();
1505 let current: std::collections::BTreeSet<_> =
1506 self.blocked_by.iter().map(String::as_str).collect();
1507 old == current
1508 })
1509 }
1510 _ => false,
1511 }
1512 }
1513
1514 fn import_chat_notice(&mut self) {
1515 if let Some(n) = &self.chat_notice {
1516 let key = if is_done_notice_key(&n.key) {
1517 "done".to_owned()
1518 } else if self.legacy_notice_matches(&n.key) {
1519 self.chat_notice_key().unwrap_or_else(|| n.key.clone())
1520 } else {
1521 n.key.clone()
1522 };
1523 if !self.chat_notices.contains(&key) {
1524 self.chat_notices.push(key);
1525 }
1526 }
1527 }
1528
1529 pub(crate) fn notice_cause(&mut self, stage: &str, run: Option<&str>, pass: Option<usize>) {
1532 self.import_chat_notice();
1533 self.hold_notice_cause = Some(NoticeCause {
1534 stage: stage.to_owned(),
1535 target: None,
1536 run: run.map(str::to_owned),
1537 pass,
1538 });
1539 }
1540
1541 pub(crate) fn startup_notice_cause(&mut self, stage: &str) {
1544 let recovery_only = matches!(
1545 stage,
1546 "startup-source" | "startup-candidates" | "startup-public-head"
1547 );
1548 match self.hold_notice_cause.as_ref() {
1549 Some(cause) if recovery_only && !cause.stage.starts_with("startup-") => return,
1550 None if recovery_only
1551 && self
1552 .chat_notice
1553 .as_ref()
1554 .is_some_and(|n| !is_done_notice_key(&n.key)) =>
1555 {
1556 return;
1557 }
1558 _ => {}
1559 }
1560 self.notice_cause(stage, None, None);
1561 }
1562
1563 pub(crate) fn fail_startup(
1566 &mut self,
1567 stage: &str,
1568 why: impl Into<String>,
1569 max_attempts: usize,
1570 ) {
1571 let unresolved = self.hold_notice_cause.clone();
1572 self.fail(why, max_attempts);
1573 self.hold_notice_cause = unresolved;
1574 self.startup_notice_cause(stage);
1575 }
1576
1577 pub(crate) fn fail_startup_target(
1579 &mut self,
1580 stage: &str,
1581 target: String,
1582 why: impl Into<String>,
1583 max_attempts: usize,
1584 ) {
1585 self.fail_startup(stage, why, max_attempts);
1586 if let Some(cause) = self.hold_notice_cause.as_mut() {
1587 cause.target = Some(target);
1588 }
1589 }
1590
1591 pub fn chat_notice_due(&self) -> Option<String> {
1593 self.filed_by_chat()?;
1594 if self.schema < 13 {
1595 return None;
1596 }
1597 let key = self.chat_notice_key()?;
1598 if self.chat_notices.contains(&key) {
1599 return None;
1600 }
1601 match &self.chat_notice {
1602 Some(n)
1603 if n.key == key
1604 || (key == "done" && is_done_notice_key(&n.key))
1605 || self.legacy_notice_matches(&n.key) =>
1606 {
1607 None
1608 }
1609 _ => Some(key),
1610 }
1611 }
1612
1613 pub fn short(&self) -> &str {
1615 short(&self.id)
1616 }
1617
1618 pub fn mark_triage_applied(&mut self, question_id: &str) {
1620 if !self.triage_applied(question_id) {
1621 self.triage_applied.push(question_id.to_owned());
1622 }
1623 }
1624
1625 pub fn action_applied(&self, question_id: &str) -> bool {
1628 self.actions_applied.iter().any(|id| id == question_id)
1629 }
1630
1631 pub fn mark_action_applied(&mut self, question_id: &str) {
1633 if !self.action_applied(question_id) {
1634 self.actions_applied.push(question_id.to_owned());
1635 }
1636 }
1637
1638 pub fn triage_applied(&self, question_id: &str) -> bool {
1640 self.triage_applied.iter().any(|id| id == question_id)
1641 }
1642
1643 pub fn start(&mut self, run: String) {
1656 self.stamp_schema();
1657 self.status = TaskStatus::Running;
1658 self.attempts += 1;
1659 self.runs.retain(|id| id != &run);
1660 if let Some(pin) = &self.resume_override
1661 && pin.pinned_run.as_ref() == Some(&run)
1662 && !pin.question_id.is_empty()
1663 {
1664 self.dispatched_resumes
1665 .insert(pin.question_id.clone(), run.clone());
1666 }
1667 self.runs.push(run);
1668 self.last_error = None;
1669 self.park_reason = None;
1670 self.fresh_start = false;
1671 self.interrupt = false;
1672 self.resume_override = None;
1674 self.disk_resume_run = None;
1677 }
1678
1679 pub fn record_startup_failure(&mut self, failure: crate::run::StartupFailure) {
1681 if !self.startup_failures.iter().any(|f| f.run == failure.run) {
1682 self.startup_failures.push(failure);
1683 }
1684 }
1685
1686 pub fn link_run(&mut self, run: &str) -> bool {
1691 if self.runs.iter().any(|r| r == run) {
1692 return false;
1693 }
1694 self.runs.push(run.to_owned());
1695 true
1696 }
1697
1698 pub fn succeed(&mut self, context: CompletionContext) {
1708 if self.status == TaskStatus::Done {
1709 return;
1710 }
1711 self.record_completion(CompletionAction::Complete, context);
1712 self.stamp_schema();
1713 self.status = TaskStatus::Done;
1714 if let Some(pin) = self.resume_override.take()
1715 && !pin.question_id.is_empty()
1716 && let Some(run) = pin.pinned_run
1717 {
1718 self.superseded_resumes.insert(pin.question_id, run);
1721 }
1722 self.sync_only = None;
1723 self.last_error = None;
1724 self.park_reason = None;
1725 self.hold_reason = None;
1726 self.hold_source = None;
1727 self.machine_hold_cause = None;
1728 self.disk_resume_run = None;
1729 self.disk_checked_at = None;
1730 self.diagnostic = None;
1731 self.blocked_by.clear();
1732 self.block_reason = None;
1733 self.blocked_from = None;
1734 }
1735
1736 pub fn already_landed(&mut self, note: impl Into<String>, mut context: CompletionContext) {
1744 let note = note.into();
1745 if context.reason.is_none() {
1746 context.reason = Some(note.clone());
1747 }
1748 self.succeed(context);
1749 self.attempts = self.attempts.saturating_sub(1);
1750 self.last_error = Some(note);
1751 }
1752
1753 fn record_completion(&mut self, action: CompletionAction, context: CompletionContext) {
1754 self.completion_history.push(CompletionEvent {
1755 occurrence: format!(
1756 "{}-{:016x}{:016x}",
1757 Timestamp::now(),
1758 crate::rng::entropy(),
1759 crate::rng::entropy()
1760 ),
1761 action,
1762 actor: context.actor,
1763 reason: context.reason,
1764 discard: context.discard,
1765 prior_status: self.status,
1766 at: Timestamp::now(),
1767 prior_hold_reason: self.hold_reason.clone(),
1768 prior_block_reason: self.block_reason.clone(),
1769 prior_error: self.last_error.clone(),
1770 run: context.run,
1771 unavailable_runs: context.unavailable_runs,
1772 });
1773 self.stamp_schema();
1774 }
1775
1776 pub fn reopen(&mut self, context: CompletionContext) -> Result<()> {
1779 anyhow::ensure!(
1780 self.status == TaskStatus::Done,
1781 "only a done task can be reopened"
1782 );
1783 anyhow::ensure!(
1784 context
1785 .reason
1786 .as_deref()
1787 .is_some_and(|reason| !reason.trim().is_empty()),
1788 "reopen requires a non-empty reason"
1789 );
1790 let reason = context.reason.clone();
1791 self.record_completion(CompletionAction::Reopen, context);
1792 self.hold_manual(reason);
1793 self.resume_override = None;
1794 self.fresh_start = false;
1795 self.last_error = None;
1796 self.diagnostic = None;
1797 Ok(())
1798 }
1799
1800 pub fn superseded_attempts(&self, last_run_succeeded: bool) -> &[String] {
1830 if self.status != TaskStatus::Done || !last_run_succeeded || self.execution_runs().len() < 2
1831 {
1832 return &[];
1833 }
1834 &self.execution_runs()[..self.execution_runs().len() - 1]
1835 }
1836
1837 pub fn successor_of(&self, run: &str) -> Option<&String> {
1845 let runs = self.execution_runs();
1846 let pos = runs.iter().rposition(|r| r == run)?;
1847 runs.get(pos + 1)
1848 }
1849
1850 pub fn earlier_attempts(&self) -> &[String] {
1857 self.execution_runs()
1858 }
1859
1860 fn preserve_legacy_build_cache(&mut self) {
1861 if self.schema < 23 {
1862 let overrides = self.overrides.get_or_insert_with(|| RunOverrides {
1863 inherit_daemon_options: true,
1864 ..RunOverrides::default()
1865 });
1866 overrides.build_cache.get_or_insert(BuildCache::Shared);
1867 }
1868 }
1869
1870 fn stamp_schema(&mut self) {
1875 self.preserve_legacy_build_cache();
1876 if self.schema < RECOVERY_HOLD_SCHEMA && self.recovery_budget_hold.is_none() {
1877 self.recovery_budget_hold = self.legacy_recovery_budget_hold();
1878 }
1879 self.schema = self.schema.max(SCHEMA);
1880 }
1881
1882 fn note_held(&mut self) {
1885 self.stamp_schema();
1886 self.recovery_budget_hold = None;
1887 let continuing = self.status == TaskStatus::Held
1888 || (self.status == TaskStatus::Blocked
1889 && (self.blocked_from == Some(TaskStatus::Held)
1890 || (self.blocked_from.is_none()
1891 && (self.hold_reason.is_some() || self.hold_source.is_some()))));
1892 if !continuing || self.held_at.is_none() {
1893 self.held_at = Some(Timestamp::now());
1894 }
1895 }
1896
1897 pub fn fail(&mut self, why: impl Into<String>, max_attempts: usize) {
1913 let why = why.into();
1914 if self.status == TaskStatus::Running {
1915 let run = self.runs.last().cloned();
1916 self.notice_cause("run-failed", run.as_deref(), Some(self.attempts));
1917 }
1918 self.diagnostic = None;
1919 self.park_reason = None;
1920 self.status = if self.attempts >= self.effective_attempt_limit(max_attempts) {
1921 self.note_held();
1922 self.hold_source = Some(HoldSource::Machine);
1923 self.machine_hold_cause = None;
1924 self.disk_resume_run = None;
1925 self.disk_checked_at = None;
1926 self.hold_reason = Some(why.clone());
1927 TaskStatus::Held
1928 } else {
1929 TaskStatus::Failed
1930 };
1931 self.last_error = Some(why);
1932 }
1933
1934 pub fn stall(&mut self, why: impl Into<String>) {
1944 self.last_error = Some(why.into());
1945 self.diagnostic = None;
1946 self.attempts = self.attempts.saturating_sub(1);
1947 self.status = TaskStatus::Failed;
1948 }
1949
1950 pub fn park(&mut self, why: impl Into<String>) {
1956 self.diagnostic = None;
1957 self.attempts = self.attempts.saturating_sub(1);
1958 self.status = TaskStatus::Parked;
1959 self.park_reason = Some(why.into());
1960 self.stamp_schema();
1963 }
1964
1965 pub fn record_pass(
1967 &mut self,
1968 run: &str,
1969 pass_index: usize,
1970 attempts_before: usize,
1971 parked: Option<crate::run::ParkCause>,
1972 ) {
1973 self.record_pass_at(run, pass_index, None, attempts_before, parked);
1974 }
1975
1976 pub fn record_pass_at(
1979 &mut self,
1980 run: &str,
1981 pass_index: usize,
1982 started_at: Option<Timestamp>,
1983 attempts_before: usize,
1984 parked: Option<crate::run::ParkCause>,
1985 ) {
1986 if self
1987 .passes
1988 .iter()
1989 .any(|p| p.run == run && p.pass_index == pass_index)
1990 {
1991 return;
1992 }
1993 let cost = if self.attempts < attempts_before {
1994 PassCost::Refunded
1995 } else {
1996 PassCost::Spent
1997 };
1998 self.passes.push(TaskPass {
1999 run: run.to_owned(),
2000 pass_index,
2001 started_at: self.dispatched_at.or(started_at),
2002 cost,
2003 attempts_after: self.attempts,
2004 settled_at: Timestamp::now(),
2005 parked,
2006 });
2007 self.stamp_schema();
2008 }
2009
2010 pub(crate) fn upgrade_resume_key(&self) -> Option<(Timestamp, &str)> {
2013 if self.status != TaskStatus::Parked || self.fresh_start {
2014 return None;
2015 }
2016 let pass = self.passes.last()?;
2017 if self.execution_runs().last() != Some(&pass.run)
2018 || !matches!(pass.parked, Some(crate::run::ParkCause::Upgrade { .. }))
2019 {
2020 return None;
2021 }
2022 Some((pass.started_at.unwrap_or(pass.settled_at), &self.id))
2025 }
2026
2027 pub fn operator_held(&self) -> bool {
2033 self.status == TaskStatus::Held && !matches!(self.hold_source, Some(HoldSource::Machine))
2034 }
2035
2036 pub fn hold_manual(&mut self, reason: Option<String>) {
2046 self.operator_decided_at = Some(Timestamp::now());
2048 if self.status != TaskStatus::Running && self.sync_only.take().is_some() {
2049 self.resume_override = None;
2050 }
2051 self.hold_unrequested_retry(reason);
2052 }
2053
2054 pub(crate) fn hold_unrequested_retry(&mut self, reason: Option<String>) {
2057 self.park_reason = None;
2058 self.note_held();
2059 self.status = TaskStatus::Held;
2060 if reason.is_some() {
2061 self.hold_reason = reason;
2062 }
2063 self.hold_source = Some(HoldSource::Manual);
2064 self.machine_hold_cause = None;
2065 self.disk_resume_run = None;
2066 self.disk_checked_at = None;
2067 self.blocked_by.clear();
2068 self.block_reason = None;
2069 self.blocked_from = None;
2070 }
2071
2072 pub(crate) fn hold_after_sync_only(&mut self, reason: String) {
2073 let recovery_hold = self.recovery_budget_hold.take();
2074 self.hold_unrequested_retry(Some(reason));
2075 self.recovery_budget_hold = recovery_hold;
2076 }
2077
2078 pub fn hold_machine(&mut self, reason: Option<String>) {
2083 self.park_reason = None;
2084 self.note_held();
2085 self.status = TaskStatus::Held;
2086 if reason.is_some() {
2087 self.hold_reason = reason;
2088 }
2089 self.hold_source = Some(HoldSource::Machine);
2090 self.machine_hold_cause = None;
2091 self.disk_resume_run = None;
2092 self.disk_checked_at = None;
2093 self.blocked_by.clear();
2094 self.block_reason = None;
2095 self.blocked_from = None;
2096 }
2097
2098 pub(crate) fn mark_disk_capacity(&mut self) {
2100 self.machine_hold_cause = Some(MachineHoldCause::DiskCapacity {
2101 reason: self.hold_reason.clone().unwrap_or_default(),
2102 before_start: false,
2103 });
2104 }
2105
2106 pub(crate) fn mark_startup_disk_capacity(&mut self) {
2107 self.machine_hold_cause = Some(MachineHoldCause::DiskCapacity {
2108 reason: self.hold_reason.clone().unwrap_or_default(),
2109 before_start: true,
2110 });
2111 }
2112
2113 pub(crate) fn disk_wait_run(&self) -> Option<&String> {
2114 if self.has_disk_capacity_cause()
2115 && matches!(
2116 self.machine_hold_cause,
2117 Some(MachineHoldCause::DiskCapacity {
2118 before_start: true,
2119 ..
2120 })
2121 )
2122 {
2123 None
2124 } else {
2125 self.execution_runs().last()
2126 }
2127 }
2128
2129 pub fn has_disk_capacity_cause(&self) -> bool {
2131 matches!(
2132 (&self.machine_hold_cause, self.hold_reason.as_deref()),
2133 (Some(MachineHoldCause::DiskCapacity { reason, .. }), Some(now)) if reason == now
2134 )
2135 }
2136
2137 pub(crate) fn resume_disk_wait(&mut self) {
2139 let retained = self.disk_wait_run().cloned();
2140 self.status = TaskStatus::Queued;
2141 self.held_at = None;
2142 self.hold_source = None;
2143 self.hold_reason = None;
2144 self.machine_hold_cause = None;
2145 self.last_error = None;
2146 self.disk_resume_run = retained;
2147 }
2148
2149 pub(crate) fn hold_head_e2e(
2151 &mut self,
2152 stop: crate::head_e2e_stop::Stop,
2153 reason: String,
2154 last_error: String,
2155 ) {
2156 self.hold_machine(Some(reason));
2157 self.last_error = Some(last_error);
2158 self.machine_hold_cause = Some(MachineHoldCause::HeadE2e { stop });
2159 }
2160
2161 pub(crate) fn head_e2e_notice(&mut self, stop: &crate::head_e2e_stop::Stop) {
2163 if let Some(at) = stop.recorded_at {
2164 self.held_at = Some(at);
2165 }
2166 self.notice_cause(crate::head_e2e_stop::NOTICE_STAGE, Some(&stop.run), None);
2167 if let Some(cause) = &mut self.hold_notice_cause {
2168 cause.target = Some(stop.id.clone());
2169 }
2170 }
2171
2172 pub fn has_head_e2e_cause(&self) -> bool {
2174 matches!(
2175 self.machine_hold_cause,
2176 Some(MachineHoldCause::HeadE2e { .. })
2177 )
2178 }
2179
2180 pub fn head_e2e_stop_id(&self) -> Option<&str> {
2182 if let Some(MachineHoldCause::HeadE2e { stop }) = &self.machine_hold_cause {
2183 return Some(stop.id.as_str());
2184 }
2185 self.hold_notice_cause
2186 .as_ref()
2187 .filter(|c| c.stage == crate::head_e2e_stop::NOTICE_STAGE)
2188 .and_then(|c| c.target.as_deref())
2189 }
2190
2191 pub(crate) fn resume_head_e2e_wait(&mut self) {
2194 self.status = TaskStatus::Queued;
2195 self.held_at = None;
2196 self.hold_source = None;
2197 self.hold_reason = None;
2198 self.machine_hold_cause = None;
2199 self.last_error = None;
2200 self.diagnostic = None;
2201 self.blocked_by.clear();
2202 self.block_reason = None;
2203 self.blocked_from = None;
2204 }
2205
2206 pub fn block(&mut self, blocked_by: Vec<String>, reason: Option<String>) {
2216 self.stamp_schema();
2217 let before: std::collections::BTreeSet<_> = self.blocked_by.iter().collect();
2218 let after: std::collections::BTreeSet<_> = blocked_by.iter().collect();
2219 if self.status != TaskStatus::Blocked || before != after {
2220 self.blocked_at = Some(Timestamp::now());
2221 }
2222 if self.status != TaskStatus::Blocked {
2223 self.blocked_from = Some(self.status);
2224 }
2225 self.status = TaskStatus::Blocked;
2226 self.blocked_by = blocked_by;
2227 self.block_reason = reason;
2228 }
2229
2230 pub fn unblock(&mut self, resolved_id: &str) {
2253 if self.status != TaskStatus::Blocked {
2254 return;
2255 }
2256 self.blocked_by.retain(|id| id != resolved_id);
2257 self.restore_if_unblocked();
2258 }
2259
2260 pub fn dependency_deleted(&mut self, deleted_id: &str) -> bool {
2271 if self.status != TaskStatus::Blocked || !self.blocked_by.iter().any(|b| b == deleted_id) {
2272 return false;
2273 }
2274 self.blocked_by.retain(|id| id != deleted_id);
2275 self.restore_if_unblocked();
2276 true
2277 }
2278
2279 fn restore_if_unblocked(&mut self) {
2283 if self.blocked_by.is_empty() {
2284 self.status = match self.blocked_from {
2285 Some(TaskStatus::Running) => TaskStatus::Queued,
2286 Some(other) => other,
2287 None if self.hold_reason.is_some() || self.hold_source.is_some() => {
2288 TaskStatus::Held
2289 }
2290 None => TaskStatus::Queued,
2291 };
2292 self.block_reason = None;
2293 self.blocked_from = None;
2294 }
2295 }
2296
2297 pub fn record_answer(&mut self, question: String, answer: String) {
2302 self.answers.push(AnsweredQuestion { question, answer });
2303 }
2304
2305 pub fn request_review(&mut self, branch: String) {
2309 self.release();
2310 self.review_branch = Some(branch);
2311 self.review_instruction = Some(self.instruction.clone());
2312 }
2313
2314 pub fn requeue(&mut self) {
2317 self.release();
2318 self.review_branch = None;
2320 self.review_instruction = None;
2321 self.fresh_start = true;
2322 }
2323
2324 pub fn hold_for_handover(&mut self, branch: Option<String>, reason: String) {
2333 if branch.is_some() {
2334 self.review_branch = branch;
2335 self.review_instruction = Some(self.instruction.clone());
2336 }
2337 self.hold_machine(Some(reason));
2338 }
2339
2340 pub fn set_urgent(&mut self, urgent: bool) -> Result<()> {
2342 if !matches!(self.status, TaskStatus::Queued | TaskStatus::Held) {
2343 bail!(
2344 "task {} is {}; urgent can only change while queued or held; \
2345 wait for the active attempt to finish and requeue or hold the task first",
2346 self.short(),
2347 self.status.as_str()
2348 );
2349 }
2350 self.urgent = urgent;
2351 Ok(())
2352 }
2353
2354 pub fn set_immediate(&mut self, immediate: bool) -> Result<()> {
2358 if !matches!(self.status, TaskStatus::Queued | TaskStatus::Held) {
2359 bail!(
2360 "task {} is {}; immediate can only change while queued or held; \
2361 wait for the active attempt to finish and requeue or hold the task first",
2362 self.short(),
2363 self.status.as_str()
2364 );
2365 }
2366 self.immediate = immediate;
2367 Ok(())
2368 }
2369
2370 pub fn set_priority(&mut self, priority: i32) -> Result<()> {
2379 if self.status == TaskStatus::Running {
2380 bail!(
2381 "task {} is running; its priority cannot be changed until \
2382 this attempt finishes",
2383 self.short()
2384 );
2385 }
2386 self.priority = priority;
2387 Ok(())
2388 }
2389
2390 pub fn set_interrupt(&mut self, interrupt: bool) -> Result<()> {
2405 if interrupt && !self.status.runnable() {
2406 bail!(
2407 "task {} is {}; only a queued or failed task can be marked \
2408 to interrupt",
2409 self.short(),
2410 self.status.as_str()
2411 );
2412 }
2413 self.interrupt = interrupt;
2414 Ok(())
2415 }
2416
2417 pub fn effective_attempt_limit(&self, daemon_limit: usize) -> usize {
2419 self.attempt_limit.map_or(daemon_limit, NonZeroUsize::get)
2420 }
2421
2422 pub fn change_attempt_limit(&mut self, limit: Option<NonZeroUsize>) -> Result<()> {
2425 if !matches!(self.status, TaskStatus::Queued | TaskStatus::Held) {
2426 bail!("only queued or held tasks can change the attempt limit");
2427 }
2428 self.stamp_schema();
2429 self.attempt_limit = limit;
2430 Ok(())
2431 }
2432
2433 pub fn implementers(&self) -> Option<usize> {
2435 if self.solo {
2436 Some(1)
2437 } else {
2438 self.overrides.as_ref().and_then(|o| o.candidates)
2439 }
2440 }
2441
2442 pub fn build_cache_override(
2447 &self,
2448 config: &crate::config::Config,
2449 ) -> Option<(BuildCache, &'static str)> {
2450 self.overrides
2451 .as_ref()
2452 .and_then(|o| o.build_cache)
2453 .map(|mode| (mode, "task-override"))
2454 .or_else(|| {
2455 ((self.immediate || self.urgent) && crate::build_target::urgent_isolation(config))
2456 .then_some((
2457 BuildCache::Isolated,
2458 if self.immediate {
2459 "immediate"
2460 } else {
2461 "urgent"
2462 },
2463 ))
2464 })
2465 }
2466
2467 pub fn change_build_cache(&mut self, mode: Option<BuildCache>) -> Result<()> {
2470 if !matches!(self.status, TaskStatus::Queued | TaskStatus::Held) {
2471 bail!(
2472 "task {} is {}; only queued or held tasks can change build cache",
2473 self.short(),
2474 self.status.as_str()
2475 );
2476 }
2477 self.stamp_schema();
2478 if self.overrides.is_some() || mode.is_some() {
2479 let overrides = self.overrides.get_or_insert_with(|| RunOverrides {
2480 inherit_daemon_options: true,
2481 ..RunOverrides::default()
2482 });
2483 overrides.build_cache = mode;
2484 }
2485 Ok(())
2486 }
2487
2488 pub fn change_implementers(&mut self, count: u8) -> Result<()> {
2491 self.check_implementers_editable()?;
2492 let explicit = self.overrides.as_ref().and_then(|o| o.config.as_deref());
2493 let (mut config, _) = crate::config::Config::discover(&self.repo, explicit)?;
2494 if let Some(o) = &self.overrides {
2495 o.apply(&mut config);
2496 }
2497 self.set_implementers(count, &config)
2498 }
2499
2500 fn check_implementers_editable(&self) -> Result<()> {
2501 if !matches!(self.status, TaskStatus::Queued | TaskStatus::Held) {
2502 bail!(
2503 "task {} is {}; only queued or held tasks can change implementers",
2504 self.short(),
2505 self.status.as_str()
2506 );
2507 }
2508 Ok(())
2509 }
2510
2511 pub fn set_implementers(&mut self, count: u8, config: &crate::config::Config) -> Result<()> {
2513 self.check_implementers_editable()?;
2514 crate::talk::check_implementers(count, config).map_err(anyhow::Error::msg)?;
2515 self.stamp_schema();
2516 self.solo = count == 1;
2517 let mut overrides = self.overrides.clone().unwrap_or_else(|| RunOverrides {
2518 inherit_daemon_options: true,
2519 ..Default::default()
2520 });
2521 overrides.candidates = (count > 1).then_some(usize::from(count));
2522 let mut settings = overrides.clone();
2523 settings.inherit_daemon_options = false;
2524 self.overrides = if overrides.inherit_daemon_options && settings == RunOverrides::default()
2526 {
2527 None
2528 } else {
2529 Some(overrides)
2530 };
2531 Ok(())
2532 }
2533
2534 pub fn edit(&mut self, title: String, instruction: String) -> Result<()> {
2546 if !matches!(self.status, TaskStatus::Queued | TaskStatus::Held) {
2547 bail!(
2548 "task {} is {}; only a queued or held task's instruction can \
2549 be edited",
2550 self.short(),
2551 self.status.as_str()
2552 );
2553 }
2554 if self.review_branch.is_some() && self.review_instruction.is_none() {
2557 self.review_instruction = Some(self.instruction.clone());
2558 }
2559 if self.instruction != instruction {
2560 self.resume_override = None;
2563 }
2564 if self.status == TaskStatus::Held && self.machine_hold_cause.is_some() {
2565 self.hold_manual(self.hold_reason.clone());
2566 }
2567 self.machine_hold_cause = None;
2568 self.disk_resume_run = None;
2569 self.disk_checked_at = None;
2570 self.title = title;
2571 self.instruction = instruction;
2572 Ok(())
2573 }
2574
2575 pub fn handed_off(&mut self, why: impl Into<String>) {
2595 let why = why.into();
2596 self.diagnostic = None;
2597 self.note_held();
2598 self.status = TaskStatus::Held;
2599 self.hold_source = Some(HoldSource::Machine);
2600 self.machine_hold_cause = None;
2601 self.disk_resume_run = None;
2602 self.disk_checked_at = None;
2603 self.hold_reason = Some(why.clone());
2604 self.last_error = Some(why);
2605 }
2606
2607 pub fn release_operator(&mut self, source: &str, question_id: Option<&str>) {
2609 self.recovery_budget = None;
2610 self.recovery_generations.clear();
2611 self.recovery_admission = None;
2612 if self
2613 .resumption
2614 .as_ref()
2615 .is_some_and(|r| r.instruction != self.instruction)
2616 {
2617 self.resume_override = None;
2620 }
2621 let approval = Resumption {
2622 generation: self.resumption.as_ref().map_or(1, |r| r.generation + 1),
2623 source: source.to_owned(),
2624 question_id: question_id.map(str::to_owned),
2625 at: Timestamp::now(),
2626 instruction: self.instruction.clone(),
2627 answers_through: self.answers.len(),
2628 runs_through: self.runs.len(),
2629 blocking_evidence: Vec::new(),
2630 cleared_reason: self
2631 .hold_reason
2632 .clone()
2633 .or_else(|| self.block_reason.clone()),
2634 };
2635 self.release();
2636 self.operator_decided_at = Some(approval.at);
2637 if let Some(previous) = self.resumption.replace(approval) {
2638 self.resumption_history.push(previous);
2639 }
2640 }
2641
2642 pub(crate) fn recovery_failed(&mut self, state: &crate::run::RunState) {
2644 let (base, inputs) = self.recovery_admission.as_ref().map_or_else(
2645 || (state.base_commit.clone(), recovery_inputs(&state.sources)),
2646 |a| (a.base.clone(), a.inputs.clone()),
2647 );
2648 let progress = recovery_progress(state);
2649 let stage = if state.prep_failure.is_some() {
2650 "preparation"
2651 } else {
2652 "execution"
2653 };
2654 let matches = |b: &RecoveryBudget| {
2655 b.instruction == self.instruction
2656 && b.base == base
2657 && b.inputs == inputs
2658 && (progress.is_none() || b.progress == progress)
2659 };
2660 if !self.recovery_budget.as_ref().is_some_and(matches) {
2661 let previous = self
2662 .recovery_generations
2663 .iter()
2664 .position(matches)
2665 .map(|index| self.recovery_generations.remove(index));
2666 if let Some(old) = self.recovery_budget.take() {
2667 self.recovery_generations.push(old);
2668 }
2669 self.recovery_budget = previous;
2670 }
2671 if let Some(budget) = &mut self.recovery_budget {
2672 budget.failures = budget.failures.saturating_add(1);
2673 budget.stage = stage.to_owned();
2674 } else {
2675 self.recovery_budget = Some(RecoveryBudget {
2676 instruction: self.instruction.clone(),
2677 base,
2678 inputs,
2679 stage: stage.to_owned(),
2680 failures: 1,
2681 progress,
2682 });
2683 }
2684 }
2685
2686 pub(crate) fn recovery_exhausted(
2687 &self,
2688 base: &str,
2689 inputs: &str,
2690 limit: usize,
2691 ) -> Option<String> {
2692 let same_input = |b: &&RecoveryBudget| {
2693 b.instruction == self.instruction && b.base == base && b.inputs == inputs
2694 };
2695 let budget = self
2696 .recovery_budget
2697 .as_ref()
2698 .filter(same_input)
2699 .or_else(|| self.recovery_generations.iter().rev().find(same_input))?;
2700 (budget.failures >= limit.max(1)).then(|| budget.budget_reason())
2701 }
2702
2703 pub(crate) fn hold_recovery_budget(&mut self, reason: String, admission: RecoveryAdmission) {
2704 self.hold_unrequested_retry(Some(reason));
2705 if let Some(pass) = self.passes.last()
2706 && self.execution_runs().last() == Some(&pass.run)
2707 {
2708 self.recovery_budget_hold = Some(RecoveryBudgetHold {
2709 admission,
2710 run: pass.run.clone(),
2711 pass: pass.pass_index,
2712 held_at: self.held_at.expect("hold timestamp just recorded"),
2713 decision: self.operator_decided_at,
2714 legacy: false,
2715 });
2716 }
2717 }
2718
2719 fn matches_budget_hold(&self, admission: &RecoveryAdmission) -> bool {
2720 self.status == TaskStatus::Held
2721 && self.hold_source == Some(HoldSource::Manual)
2722 && self.machine_hold_cause.is_none()
2723 && self.recovery_budget.as_ref().is_some_and(|budget| {
2724 budget.instruction == self.instruction
2725 && budget.base == admission.base
2726 && budget.inputs == admission.inputs
2727 && budget.stage == "execution"
2728 && budget.failures > 0
2729 && self
2730 .hold_reason
2731 .as_ref()
2732 .is_some_and(|reason| *reason == budget.budget_reason())
2733 })
2734 }
2735
2736 fn legacy_recovery_budget_hold(&self) -> Option<RecoveryBudgetHold> {
2737 let held_at = self.held_at?;
2738 let settled = self.passes.last()?;
2739 let admission = self.recovery_admission.as_ref()?;
2740 if !self.matches_budget_hold(admission)
2741 || self.execution_runs().last() != Some(&settled.run)
2742 || settled.cost != PassCost::Spent
2743 || settled.parked.is_some()
2744 || settled.settled_at > held_at
2745 || self.operator_decided_at.is_some_and(|at| at >= held_at)
2746 {
2747 return None;
2748 }
2749 Some(RecoveryBudgetHold {
2750 admission: admission.clone(),
2751 run: settled.run.clone(),
2752 pass: settled.pass_index,
2753 held_at,
2754 decision: self.operator_decided_at,
2755 legacy: true,
2756 })
2757 }
2758
2759 pub(crate) fn held_for_recovery_budget(&self, run: &crate::run::RunState) -> bool {
2760 let (Some(held_at), Some(settled), Some(pass), Some(admission)) = (
2761 self.held_at,
2762 self.passes.last(),
2763 run.passes.last(),
2764 self.recovery_admission.as_ref(),
2765 ) else {
2766 return false;
2767 };
2768 if !self.matches_budget_hold(admission)
2769 || self.execution_runs().last() != Some(&run.id)
2770 || settled.run != run.id
2771 || settled.pass_index != pass.index
2772 || settled.cost != PassCost::Spent
2773 || settled.parked.is_some()
2774 || settled.settled_at < pass.started_at
2775 || settled.settled_at > held_at
2776 || self.operator_decided_at.is_some_and(|at| at >= held_at)
2777 || !crate::daemon::compatible_run_instruction(run, self)
2778 {
2779 return false;
2780 }
2781 match &self.recovery_budget_hold {
2782 Some(hold) => {
2783 hold.run == run.id
2784 && hold.pass == pass.index
2785 && hold.held_at == held_at
2786 && hold.decision == self.operator_decided_at
2787 && &hold.admission == admission
2788 && (!hold.legacy
2789 || self
2790 .operator_decided_at
2791 .is_none_or(|at| at < pass.started_at))
2792 }
2793 None => {
2794 self.schema < RECOVERY_HOLD_SCHEMA
2795 && self
2796 .operator_decided_at
2797 .is_none_or(|at| at < pass.started_at)
2798 }
2799 }
2800 }
2801
2802 pub(crate) fn queue_repair(&mut self, receipt: &crate::repair_budget::Receipt) {
2803 self.stamp_schema();
2804 self.repair_grants.push(receipt.clone());
2805 self.status = TaskStatus::Queued;
2806 self.hold_source = None;
2807 self.hold_reason = None;
2808 self.held_at = None;
2809 self.recovery_budget_hold = None;
2810 self.resume_override = Some(OperatorResume {
2811 question_id: String::new(),
2812 at: receipt.at,
2813 conductor_rehold: None,
2814 forced: true,
2815 pinned_run: Some(receipt.request.run.clone()),
2816 });
2817 }
2818
2819 pub fn release(&mut self) {
2823 self.import_chat_notice();
2826 if self.hold_notice_cause.is_none()
2827 && matches!(self.status, TaskStatus::Held | TaskStatus::Blocked)
2828 {
2829 self.hold_notice_cause = Some(self.unresolved_hold_cause());
2830 }
2831 let refused_handover = self.status == TaskStatus::Held
2832 && self.hold_source == Some(HoldSource::Machine)
2833 && self.review_branch.is_some()
2834 && self
2835 .review_instruction
2836 .as_ref()
2837 .is_none_or(|i| *i == self.instruction);
2838 self.status = TaskStatus::Queued;
2839 self.held_at = None;
2840 self.attempts = 0;
2841 self.last_error = None;
2842 self.park_reason = None;
2843 self.hold_reason = None;
2846 self.hold_source = None;
2847 self.machine_hold_cause = None;
2848 self.disk_resume_run = None;
2849 self.disk_checked_at = None;
2850 self.diagnostic = None;
2851 self.blocked_by.clear();
2856 self.block_reason = None;
2857 self.blocked_from = None;
2858 if !refused_handover {
2862 self.review_branch = None;
2863 self.review_instruction = None;
2864 }
2865 self.fresh_start = false;
2866 }
2867}
2868
2869fn copy_new(dir: &Path, src: &Path, name: &str) -> Result<(String, PathBuf)> {
2873 use std::io::ErrorKind;
2874 let (stem, ext) = match name.rfind('.') {
2875 Some(i) if i > 0 => (&name[..i], &name[i..]),
2876 _ => (name, ""),
2877 };
2878 for n in 1u32.. {
2879 let candidate = if n == 1 {
2880 name.to_owned()
2881 } else {
2882 let suffix = format!("-{n}");
2883 let room = 64usize.saturating_sub(suffix.len() + ext.len());
2884 let stem: String = stem.chars().take(room).collect();
2885 format!("{stem}{suffix}{ext}")
2886 };
2887 if !crate::ask::valid_asset_name(&candidate) {
2888 bail!("no valid attachment name is left for `{name}`");
2889 }
2890 let path = dir.join(&candidate);
2891 match std::fs::OpenOptions::new()
2892 .write(true)
2893 .create_new(true)
2894 .open(&path)
2895 {
2896 Ok(mut out) => {
2897 let copied = std::fs::File::open(src)
2898 .and_then(|mut input| std::io::copy(&mut input, &mut out));
2899 if let Err(e) = copied {
2900 drop(out);
2901 let _ = std::fs::remove_file(&path);
2902 return Err(e).with_context(|| format!("copy {}", src.display()));
2903 }
2904 return Ok((candidate, path));
2905 }
2906 Err(e) if e.kind() == ErrorKind::AlreadyExists => continue,
2907 Err(e) => return Err(e).with_context(|| format!("create {}", path.display())),
2908 }
2909 }
2910 unreachable!("the counter never runs out")
2911}
2912
2913const TASK_LOCK_STALE: std::time::Duration = std::time::Duration::from_secs(10);
2916
2917pub(crate) struct TaskLock {
2920 path: PathBuf,
2921 token: String,
2922}
2923
2924fn owner_token() -> String {
2927 static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
2928 let n = COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2929 let mut r = crate::rng::SplitMix64::new(crate::rng::entropy() ^ n.rotate_left(32));
2930 format!("{}-{:016x}", std::process::id(), r.next_u64())
2931}
2932
2933fn break_marker(path: &Path, token: &str) -> PathBuf {
2936 let mut h: u64 = 0xcbf29ce484222325;
2937 for b in token.bytes() {
2938 h ^= u64::from(b);
2939 h = h.wrapping_mul(0x100000001b3);
2940 }
2941 let mut name = path.as_os_str().to_owned();
2942 name.push(format!(".break-{h:016x}"));
2943 PathBuf::from(name)
2944}
2945
2946fn older_than_stale(path: &Path) -> bool {
2947 std::fs::metadata(path)
2948 .and_then(|m| m.modified())
2949 .ok()
2950 .and_then(|t| t.elapsed().ok())
2951 .is_some_and(|age| age > TASK_LOCK_STALE)
2952}
2953
2954fn writer_may_be_gone(token: &str) -> bool {
2955 let Some(pid) = token
2956 .split_once('-')
2957 .and_then(|(pid, _)| pid.parse::<u32>().ok())
2958 else {
2959 return true;
2962 };
2963 if pid == std::process::id() {
2964 return false;
2965 }
2966 crate::proc::pid_status(pid) == Some(false)
2968}
2969
2970const MAX_MARKER_DEPTH: u8 = 3;
2974
2975fn take_marker(
2981 path: &Path,
2982 token: &str,
2983 depth: u8,
2984 retry: crate::lock_file::Retry,
2985) -> Option<(PathBuf, String)> {
2986 use std::io::Write;
2987 let marker = break_marker(path, token);
2988 for _ in 0..2 {
2989 match retry.create(&marker) {
2990 Ok(mut f) => {
2991 let mine = owner_token();
2992 if f.write_all(mine.as_bytes()).is_err() {
2993 drop(f);
2994 let _ = std::fs::remove_file(&marker);
2995 return None;
2996 }
2997 return Some((marker, mine));
2998 }
2999 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
3000 let judged = std::fs::read_to_string(&marker).ok();
3001 match judged.filter(|_| older_than_stale(&marker)) {
3002 Some(judged) if depth < MAX_MARKER_DEPTH => {
3003 remove_lock_if(&marker, &judged, true, depth + 1, retry)?;
3004 }
3005 _ => return None,
3006 }
3007 }
3008 Err(_) => return None,
3009 }
3010 }
3011 None
3012}
3013
3014fn remove_lock_if(
3019 path: &Path,
3020 token: &str,
3021 require_stale: bool,
3022 depth: u8,
3023 retry: crate::lock_file::Retry,
3024) -> Option<bool> {
3025 let (marker, mine) = take_marker(path, token, depth, retry)?;
3026 let still = std::fs::read_to_string(path).is_ok_and(|c| c == token)
3027 && (!require_stale || older_than_stale(path) && writer_may_be_gone(token));
3028 if still {
3029 let _ = std::fs::remove_file(path);
3030 }
3031 if depth >= MAX_MARKER_DEPTH {
3033 if std::fs::read_to_string(&marker).is_ok_and(|c| c == mine) {
3034 let _ = std::fs::remove_file(&marker);
3035 }
3036 } else {
3037 let _ = remove_lock_if(&marker, &mine, false, depth + 1, retry);
3038 }
3039 Some(still)
3040}
3041
3042#[cfg(test)]
3045fn break_stale(path: &Path, judged: &str) -> bool {
3046 break_stale_with(path, judged, crate::lock_file::Retry::new(None))
3047}
3048
3049fn break_stale_with(path: &Path, judged: &str, retry: crate::lock_file::Retry) -> bool {
3050 remove_lock_if(path, judged, true, 0, retry).unwrap_or(false)
3051}
3052
3053impl Drop for TaskLock {
3054 fn drop(&mut self) {
3055 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2);
3056 let retry = crate::lock_file::Retry::new(Some(deadline));
3057 loop {
3058 match remove_lock_if(&self.path, &self.token, false, 0, retry) {
3059 Some(_) => return,
3060 None if std::time::Instant::now() > deadline => return,
3061 None => std::thread::sleep(std::time::Duration::from_millis(5)),
3062 }
3063 }
3064 }
3065}
3066
3067#[derive(Debug, thiserror::Error)]
3068#[error("task changed during completion decision; reload and inspect it")]
3069pub(crate) struct CompletionSnapshotChanged;
3070
3071#[derive(Debug, Clone)]
3073pub struct Queue {
3074 root: PathBuf,
3075 ids: IdSource,
3076}
3077
3078fn validate_attachments(sources: &[PathBuf]) -> Result<Vec<(&PathBuf, &str)>> {
3079 let mut wanted = Vec::new();
3080 for src in sources {
3081 let name = src
3082 .file_name()
3083 .and_then(|n| n.to_str())
3084 .with_context(|| format!("`{}` has no usable file name", src.display()))?;
3085 if !crate::ask::valid_asset_name(name) {
3086 bail!(
3087 "attachment name `{name}` must match ^[A-Za-z0-9][A-Za-z0-9._-]{{0,63}}$ \
3088 with no `..`; rename the file and try again"
3089 );
3090 }
3091 if !src.is_file() {
3092 bail!("attachment `{}` is not a file", src.display());
3093 }
3094 wanted.push((src, name));
3095 }
3096 Ok(wanted)
3097}
3098
3099impl Queue {
3100 pub fn open() -> Self {
3102 Self::at(crate::run::home().join("queue"))
3103 }
3104
3105 pub fn at(root: PathBuf) -> Self {
3108 Self {
3109 root,
3110 ids: IdSource::new(new_id),
3111 }
3112 }
3113
3114 #[doc(hidden)]
3117 pub fn with_id_source(mut self, f: impl Fn() -> String + Send + Sync + 'static) -> Self {
3118 self.ids = IdSource::custom(f);
3119 self
3120 }
3121
3122 fn file_with(
3133 &self,
3134 task: &mut Task,
3135 hook: impl FnMut(&mut Task) -> Result<bool>,
3136 undo: impl FnMut(&mut Task),
3137 ) -> Result<()> {
3138 self.reserve_id(task, hook, undo, true)
3139 }
3140
3141 fn reserve_id(
3149 &self,
3150 task: &mut Task,
3151 mut hook: impl FnMut(&mut Task) -> Result<bool>,
3152 mut undo: impl FnMut(&mut Task),
3153 store: bool,
3154 ) -> Result<()> {
3155 let redraw_first = self.ids.is_custom() && task.attachments.is_empty();
3156 let initial = task.id.clone();
3157 self.ids
3158 .reserve((!redraw_first).then_some(initial.as_str()), "task", |id| {
3159 task.id = id.to_owned();
3160 let _lock = self.lock_task(&task.id)?;
3161 if path_exists(&self.path_of(&task.id))? || !hook(task)? {
3162 return Ok(false);
3163 }
3164 if store {
3165 if let Err(e) = self.write_record(task) {
3166 undo(task);
3167 return Err(e);
3168 }
3169 task.unfiled = false;
3170 }
3171 Ok(true)
3172 })?;
3173 Ok(())
3174 }
3175
3176 fn id_in_use(&self, id: &str, check_attachments: bool) -> Result<bool> {
3181 if path_exists(&self.lock_path(id))? {
3182 return Ok(true);
3183 }
3184 Ok(check_attachments && path_exists(&self.attachments_dir(id))?)
3185 }
3186
3187 fn plain_filing_hook(&self, task: &Task) -> Result<bool> {
3191 Ok(!self.id_in_use(&task.id, task.attachments.is_empty())?)
3192 }
3193
3194 pub fn file_claimed(&self, task: &mut Task) -> Result<Claim> {
3197 let mut claim = None;
3198 self.file_with(
3199 task,
3200 |t| {
3201 if self.id_in_use(&t.id, true)? {
3202 return Ok(false);
3203 }
3204 claim = Some(self.claim(&t.id)?);
3205 Ok(true)
3206 },
3207 |_| {},
3208 )?;
3209 claim.context("claim missing after filing")
3210 }
3211
3212 pub fn root(&self) -> &Path {
3214 &self.root
3215 }
3216
3217 pub fn path_of(&self, id: &str) -> PathBuf {
3219 self.root.join(format!("{id}.json"))
3220 }
3221
3222 pub fn attachments_dir(&self, id: &str) -> PathBuf {
3225 self.root.join(format!("{id}.attachments"))
3226 }
3227
3228 pub fn attach(&self, task: &mut Task, sources: &[PathBuf]) -> Result<Vec<String>> {
3239 let wanted = validate_attachments(sources)?;
3240 if task.unfiled && task.attachments.is_empty() {
3241 let names = std::cell::RefCell::new(Vec::new());
3244 self.reserve_id(
3245 task,
3246 |t| {
3247 if self.id_in_use(&t.id, true)? {
3248 return Ok(false);
3249 }
3250 *names.borrow_mut() = self.copy_attachments(t, &wanted)?;
3251 Ok(true)
3252 },
3253 |_| {},
3254 false,
3255 )?;
3256 return Ok(names.into_inner());
3257 }
3258 self.copy_attachments(task, &wanted)
3259 }
3260
3261 fn copy_attachments(
3263 &self,
3264 task: &mut Task,
3265 wanted: &[(&PathBuf, &str)],
3266 ) -> Result<Vec<String>> {
3267 let dir = self.attachments_dir(&task.id);
3268 let existed = dir.is_dir();
3269 std::fs::create_dir_all(&dir).with_context(|| format!("create {}", dir.display()))?;
3270 let mut created: Vec<PathBuf> = Vec::new();
3271 let mut names = Vec::new();
3272 let mut copy_all = || -> Result<()> {
3273 for (src, name) in wanted {
3274 let (stored, path) = copy_new(&dir, src, name)?;
3275 created.push(path);
3276 names.push(stored);
3277 }
3278 Ok(())
3279 };
3280 if let Err(e) = copy_all() {
3281 for path in &created {
3282 let _ = std::fs::remove_file(path);
3283 }
3284 if !existed {
3285 let _ = std::fs::remove_dir(&dir);
3286 }
3287 return Err(e);
3288 }
3289 task.attachments.extend(names.iter().cloned());
3290 Ok(names)
3291 }
3292
3293 pub fn attach_and_put(&self, task: &mut Task, sources: &[PathBuf]) -> Result<Vec<String>> {
3304 if task.unfiled && task.attachments.is_empty() {
3305 return self.attach_and_file(task, sources);
3306 }
3307 let dir = self.attachments_dir(&task.id);
3308 let existed = dir.is_dir();
3309 let before = task.attachments.len();
3310 let names = self.attach(task, sources)?;
3311 if let Err(e) = self.put(task) {
3312 for name in &names {
3313 let _ = std::fs::remove_file(dir.join(name));
3314 }
3315 if !existed {
3316 let _ = std::fs::remove_dir(&dir);
3317 }
3318 task.attachments.truncate(before);
3319 return Err(e);
3320 }
3321 Ok(names)
3322 }
3323
3324 fn attach_and_file(&self, task: &mut Task, sources: &[PathBuf]) -> Result<Vec<String>> {
3328 let wanted = validate_attachments(sources)?;
3329 let before = task.attachments.len();
3330 let names = std::cell::RefCell::new(Vec::new());
3331 let result = self.file_with(
3332 task,
3333 |t| {
3334 if self.id_in_use(&t.id, true)? {
3335 return Ok(false);
3336 }
3337 *names.borrow_mut() = self.copy_attachments(t, &wanted)?;
3338 Ok(true)
3339 },
3340 |t| {
3341 let dir = self.attachments_dir(&t.id);
3342 for name in names.borrow().iter() {
3343 let _ = std::fs::remove_file(dir.join(name));
3344 }
3345 let _ = std::fs::remove_dir(&dir);
3347 t.attachments.truncate(before);
3348 },
3349 );
3350 result.map(|()| names.into_inner())
3351 }
3352
3353 pub fn attachment_paths(&self, task: &Task) -> Vec<PathBuf> {
3357 let dir = self.attachments_dir(&task.id);
3358 task.attachments
3359 .iter()
3360 .map(|n| {
3361 let p = dir.join(n);
3362 std::path::absolute(&p).unwrap_or(p)
3363 })
3364 .collect()
3365 }
3366
3367 pub fn put(&self, task: &mut Task) -> Result<()> {
3376 if task.unfiled {
3377 return self.file_with(task, |t| self.plain_filing_hook(t), |_| {});
3379 }
3380 let _lock = self.lock_task(&task.id)?;
3381 self.put_unlocked(task)
3382 }
3383
3384 pub fn create_new(&self, task: &mut Task) -> Result<bool> {
3389 let _lock = self.lock_task(&task.id)?;
3390 if path_exists(&self.path_of(&task.id))? {
3391 return Ok(false);
3392 }
3393 self.write_record(task)?;
3394 task.unfiled = false;
3395 Ok(true)
3396 }
3397
3398 fn put_unlocked(&self, task: &mut Task) -> Result<()> {
3400 self.merge_stored(task);
3401 if let Some(boundary) = task.reassignments.last() {
3402 let stored = self.get(&task.id)?;
3403 anyhow::ensure!(
3404 task.reassignments == stored.reassignments
3405 && task.repo == stored.repo
3406 && task.runs.get(..boundary.run_boundary)
3407 == stored.runs.get(..boundary.run_boundary),
3408 "historical repository execution cannot be restarted; reload the task"
3409 );
3410 }
3411 self.write_record(task)
3412 }
3413
3414 pub(crate) fn commit_base_recovery(
3416 &self,
3417 task: &mut Task,
3418 expected: &serde_json::Value,
3419 ) -> Result<()> {
3420 let _lock = self.lock_task(&task.id)?;
3421 anyhow::ensure!(
3422 serde_json::to_value(self.get(&task.id)?)? == *expected,
3423 "task changed during base recovery; inspect the pending authorization"
3424 );
3425 self.put_unlocked(task)
3427 }
3428
3429 pub(crate) fn commit_land_sync_recovery(
3431 &self,
3432 task: &mut Task,
3433 expected: &serde_json::Value,
3434 ) -> Result<()> {
3435 let _lock = self.lock_task(&task.id)?;
3436 anyhow::ensure!(
3437 serde_json::to_value(self.get(&task.id)?)? == *expected,
3438 "task changed during landing base-sync recovery; inspect the pending authorization"
3439 );
3440 self.put_unlocked(task)
3441 }
3442
3443 pub(crate) fn commit_repair_grant(
3444 &self,
3445 task: &mut Task,
3446 expected: &serde_json::Value,
3447 ) -> Result<()> {
3448 let _lock = self.lock_task(&task.id)?;
3449 anyhow::ensure!(
3450 serde_json::to_value(self.get(&task.id)?)? == *expected,
3451 "repair grant refused: task changed during admission"
3452 );
3453 self.write_record(task)
3454 .context(crate::repair_budget::PublicationUnknown)
3455 }
3456
3457 pub(crate) fn commit_disk_wait(&self, task: &mut Task, expected: &Task) -> Result<()> {
3459 let _lock = self.lock_task(&task.id)?;
3460 anyhow::ensure!(
3461 serde_json::to_value(self.get(&task.id)?)? == serde_json::to_value(expected)?,
3462 "task changed during disk monitoring"
3463 );
3464 task.stamp_schema();
3465 self.write_record_inner(task, false)
3466 }
3467
3468 pub(crate) fn commit_reassignment(&self, task: &mut Task, expected: &Task) -> Result<()> {
3470 let _lock = self.lock_task(&task.id)?;
3471 let stored = self.get(&task.id)?;
3472 anyhow::ensure!(
3473 serde_json::to_value(&stored)? == serde_json::to_value(expected)?
3474 && stored.reassignments.len() + 1 == task.reassignments.len()
3475 && stored.repo == task.reassignments.last().expect("new boundary").from
3476 && stored.runs == task.runs,
3477 "task changed during reassignment; retry after inspecting it"
3478 );
3479 self.write_record(task)
3480 }
3481
3482 pub(crate) fn commit_completion(&self, task: &mut Task, expected: &Task) -> Result<()> {
3484 let _lock = self.lock_task(&task.id)?;
3485 anyhow::ensure!(
3486 serde_json::to_value(self.get(&task.id)?)? == serde_json::to_value(expected)?,
3487 CompletionSnapshotChanged
3488 );
3489 self.write_record(task)
3490 }
3491
3492 fn merge_stored(&self, task: &mut Task) {
3494 if let Ok(mut stored) = read_path(&self.path_of(&task.id)) {
3495 stored.import_chat_notice();
3496 let local_decision = task.completion_history.iter().any(|event| {
3499 !stored
3500 .completion_history
3501 .iter()
3502 .any(|saved| saved.occurrence == event.occurrence)
3503 && event.at > stored.updated_at
3504 });
3505 let unseen_decision = stored.completion_history.iter().any(|event| {
3506 !task
3507 .completion_history
3508 .iter()
3509 .any(|mine| mine.occurrence == event.occurrence)
3510 });
3511 let mut history = std::mem::take(&mut stored.completion_history);
3512 for event in std::mem::take(&mut task.completion_history) {
3513 if !history
3514 .iter()
3515 .any(|stored| stored.occurrence == event.occurrence)
3516 {
3517 history.push(event);
3518 }
3519 }
3520 if unseen_decision {
3521 task.import_chat_notice();
3524 let mut stale = std::mem::replace(task, stored);
3525 append_missing(&mut task.answers, stale.answers);
3526 if task.reassignments == stale.reassignments {
3527 append_missing(&mut task.runs, stale.runs);
3528 }
3529 for (ledger, entries) in [
3530 (&mut task.decision_effects, stale.decision_effects),
3531 (&mut task.superseded_resumes, stale.superseded_resumes),
3532 (&mut task.dispatched_resumes, stale.dispatched_resumes),
3533 ] {
3534 for (key, value) in entries {
3535 ledger.entry(key).or_insert(value);
3536 }
3537 }
3538 append_missing(&mut task.actions_applied, stale.actions_applied);
3539 append_missing(&mut task.triage_applied, stale.triage_applied);
3540 append_missing(&mut task.chat_notices, stale.chat_notices);
3541 append_missing(
3542 &mut task.base_recovery_requests,
3543 stale.base_recovery_requests,
3544 );
3545 append_missing(
3546 &mut task.land_sync_recovery_requests,
3547 stale.land_sync_recovery_requests,
3548 );
3549 prepend_missing_by(&mut task.repair_grants, stale.repair_grants, |a, b| {
3552 a.request.request == b.request.request
3553 });
3554 prepend_missing_by(
3555 &mut task.repair_reconciliations,
3556 stale.repair_reconciliations,
3557 |a, b| a.request.request == b.request.request,
3558 );
3559 stale.resumption_history.extend(stale.resumption);
3562 stale.resumption_history.retain(|approval| {
3563 task.resumption
3564 .as_ref()
3565 .is_none_or(|r| r.at != approval.at || r.generation != approval.generation)
3566 });
3567 prepend_missing_by(
3568 &mut task.resumption_history,
3569 stale.resumption_history,
3570 |a, b| a.at == b.at && a.generation == b.generation,
3571 );
3572 for failure in stale.startup_failures {
3573 task.record_startup_failure(failure);
3574 }
3575 for pass in stale.passes {
3576 if !task.passes.iter().any(|stored| {
3577 stored.run == pass.run && stored.pass_index == pass.pass_index
3578 }) {
3579 task.passes.push(pass);
3580 }
3581 }
3582 task.completion_history = history;
3583 if !task.decision_effects.is_empty() {
3584 task.stamp_schema();
3585 }
3586 return;
3587 }
3588 if stored.reassignments.len() > task.reassignments.len() {
3589 let stale = std::mem::replace(task, stored.clone());
3592 for answer in stale.answers {
3593 if !task.answers.contains(&answer) {
3594 task.answers.push(answer);
3595 }
3596 }
3597 }
3598 if task.updated_at < stored.updated_at
3601 && (task.sync_only != stored.sync_only
3602 || stored.sync_only.is_some()
3603 || stored
3604 .recovery_budget_hold
3605 .as_ref()
3606 .is_some_and(|hold| hold.held_at > task.updated_at)
3607 || stored.repair_grants.last().is_some_and(|grant| {
3608 task.repair_grants.last() != Some(grant)
3609 || stored.operator_decided_at > task.operator_decided_at
3610 || stored
3611 .resume_override
3612 .as_ref()
3613 .is_some_and(|pin| pin.at > task.updated_at)
3614 || (task.resume_override != stored.resume_override
3615 && task
3616 .resume_override
3617 .as_ref()
3618 .is_some_and(|pin| pin.at == grant.at))
3619 }))
3620 && task
3621 .operator_decided_at
3622 .is_none_or(|at| at <= stored.updated_at)
3623 && task
3624 .resume_override
3625 .as_ref()
3626 .is_none_or(|pin| pin.at <= stored.updated_at)
3627 && !local_decision
3628 {
3629 *task = stored.clone();
3630 }
3631 task.completion_history = history;
3632 append_missing(
3633 &mut task.base_recovery_requests,
3634 stored.base_recovery_requests,
3635 );
3636 append_missing(
3637 &mut task.land_sync_recovery_requests,
3638 stored.land_sync_recovery_requests,
3639 );
3640 append_missing(&mut task.actions_applied, stored.actions_applied);
3641 append_missing(&mut task.triage_applied, stored.triage_applied);
3642 for receipt in &stored.repair_grants {
3643 if !task
3644 .repair_grants
3645 .iter()
3646 .any(|r| r.request.request == receipt.request.request)
3647 {
3648 task.repair_grants.push(receipt.clone());
3650 }
3651 }
3652 for receipt in &stored.repair_reconciliations {
3653 if !task.repair_reconciliations.contains(receipt) {
3654 task.repair_reconciliations.push(receipt.clone());
3657 task.resume_override = stored.resume_override.clone();
3658 task.status = stored.status;
3659 task.hold_source = stored.hold_source;
3660 task.machine_hold_cause = stored.machine_hold_cause.clone();
3661 task.disk_resume_run = stored.disk_resume_run.clone();
3662 task.disk_checked_at = stored.disk_checked_at;
3663 task.hold_reason = stored.hold_reason.clone();
3664 task.held_at = stored.held_at;
3665 }
3666 }
3667 task.superseded_resumes.extend(stored.superseded_resumes);
3668 task.dispatched_resumes.extend(stored.dispatched_resumes);
3669 if task.status != TaskStatus::Running
3670 && let Some(pin) = &stored.resume_override
3671 && !pin.question_id.is_empty()
3672 && let Some(run) = &pin.pinned_run
3673 && task.resume_override.as_ref().is_none_or(|next| {
3674 next.question_id != pin.question_id || next.pinned_run != pin.pinned_run
3675 })
3676 {
3677 task.superseded_resumes
3678 .insert(pin.question_id.clone(), run.clone());
3679 }
3680 for (id, receipt) in stored.decision_effects {
3683 task.decision_effects.insert(id, receipt);
3684 }
3685 if !task.decision_effects.is_empty() {
3686 task.stamp_schema();
3687 }
3688 if task.chat.is_none() {
3691 task.chat = stored.chat.clone();
3692 }
3693 append_missing(&mut task.chat_notices, stored.chat_notices);
3694 for failure in stored.startup_failures {
3695 task.record_startup_failure(failure);
3696 }
3697 append_missing(&mut task.runs, stored.runs);
3698 for p in stored.passes {
3699 if !task
3700 .passes
3701 .iter()
3702 .any(|q| q.run == p.run && q.pass_index == p.pass_index)
3703 {
3704 task.passes.push(p);
3705 }
3706 }
3707 if let Some(n) = stored.chat_notice
3710 && task.chat_notice.as_ref().is_none_or(|mine| mine.at < n.at)
3711 {
3712 task.chat_notice = Some(n);
3713 }
3714 }
3715 }
3716
3717 pub(crate) fn write_startup_history(&self, task: &Task) -> Result<()> {
3720 let path = self.path_of(&task.id);
3721 let tmp = path.with_extension("json.tmp");
3722 std::fs::write(&tmp, serde_json::to_vec_pretty(task)?)?;
3723 std::fs::rename(tmp, path)?;
3724 Ok(())
3725 }
3726
3727 fn write_record(&self, task: &mut Task) -> Result<()> {
3729 self.write_record_inner(task, true)
3730 }
3731
3732 fn write_record_inner(&self, task: &mut Task, notify: bool) -> Result<()> {
3733 task.import_chat_notice();
3734 if task.status != TaskStatus::Held && task.sync_only.is_none() {
3735 task.recovery_budget_hold = None;
3736 }
3737 task.updated_at = Timestamp::now();
3738 std::fs::create_dir_all(&self.root)
3739 .with_context(|| format!("create {}", self.root.display()))?;
3740 let body = serde_json::to_string_pretty(task).context("serialize task")?;
3741 let path = self.path_of(&task.id);
3742 let tmp = path.with_extension("json.tmp");
3743 std::fs::write(&tmp, &body).with_context(|| format!("write {}", tmp.display()))?;
3744 std::fs::rename(&tmp, &path).with_context(|| format!("replace {}", path.display()))?;
3745 if let (Some(notice), Some(home)) = (
3750 notify.then(|| crate::notices::task_held(task)).flatten(),
3751 self.root.parent().filter(|p| !p.as_os_str().is_empty()),
3752 ) {
3753 crate::notices::raise_in(home, notice);
3754 }
3755 Ok(())
3756 }
3757
3758 pub fn modify(&self, id: &str, f: impl FnOnce(&mut Task) -> bool) -> Result<bool> {
3763 let id = self.resolve_id(id)?;
3764 let _lock = self.lock_task(&id)?;
3765 let mut task = self.get(&id)?;
3766 if !f(&mut task) {
3767 return Ok(false);
3768 }
3769 self.put_unlocked(&mut task)?;
3770 Ok(true)
3771 }
3772
3773 pub fn link_run(&self, id: &str, run: &str) -> Result<Task> {
3778 let id = self.resolve_id(id)?;
3779 let _lock = self.lock_task(&id)?;
3782 let mut task = self.get(&id)?;
3783 if task.link_run(run) {
3784 self.put_unlocked(&mut task)?;
3785 }
3786 Ok(task)
3787 }
3788
3789 pub(crate) fn lock_task(&self, id: &str) -> Result<TaskLock> {
3797 std::fs::create_dir_all(&self.root)
3798 .with_context(|| format!("create {}", self.root.display()))?;
3799 let path = self.root.join(format!("{id}.write-lock"));
3800 let started = std::time::Instant::now();
3801 let retry = crate::lock_file::Retry::task_write(started + TASK_LOCK_STALE);
3802 let marker_retry = crate::lock_file::Retry::new(Some(started + TASK_LOCK_STALE));
3803 loop {
3804 match retry.create(&path) {
3805 Ok(mut file) => {
3806 use std::io::Write;
3807 let token = owner_token();
3808 if let Err(e) = file.write_all(token.as_bytes()) {
3809 drop(file);
3810 let _ = std::fs::remove_file(&path);
3811 return Err(e).with_context(|| format!("lock {}", path.display()));
3812 }
3813 return Ok(TaskLock { path, token });
3814 }
3815 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
3816 let judged = std::fs::read_to_string(&path).ok();
3819 let broken = judged
3820 .filter(|_| older_than_stale(&path))
3821 .is_some_and(|judged| break_stale_with(&path, &judged, marker_retry));
3822 if !broken {
3826 if started.elapsed() > TASK_LOCK_STALE {
3827 bail!("could not lock task {id}");
3828 }
3829 std::thread::sleep(std::time::Duration::from_millis(15));
3830 }
3831 }
3832 Err(e) => return Err(e).with_context(|| format!("lock {}", path.display())),
3833 }
3834 }
3835 }
3836
3837 pub fn get(&self, id: &str) -> Result<Task> {
3839 let resolved = self.resolve_id(id)?;
3840 read_path(&self.path_of(&resolved))
3841 }
3842
3843 pub fn remove(&self, id: &str, in_flight: bool, questions: &Questions) -> Result<Removal> {
3875 self.remove_with_receipt(id, in_flight, questions, None)
3876 }
3877
3878 pub(crate) fn discard_triage(
3880 &self,
3881 id: &str,
3882 questions: &Questions,
3883 inquiry: &str,
3884 ) -> Result<Removal> {
3885 self.remove_with_receipt(id, false, questions, Some(inquiry))
3886 }
3887
3888 pub(crate) fn triage_discard_applied(&self, id: &str, inquiry: &str) -> Result<bool> {
3889 let path = self
3890 .root
3891 .join("triage-discard")
3892 .join(format!("{inquiry}.json"));
3893 let bytes = match std::fs::read(path) {
3894 Ok(bytes) => bytes,
3895 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(false),
3896 Err(e) => return Err(e.into()),
3897 };
3898 let receipt: Task = serde_json::from_slice(&bytes)?;
3899 Ok(receipt.id == id && !self.path_of(id).exists())
3900 }
3901
3902 fn remove_with_receipt(
3903 &self,
3904 id: &str,
3905 in_flight: bool,
3906 questions: &Questions,
3907 inquiry: Option<&str>,
3908 ) -> Result<Removal> {
3909 let resolved = self.resolve_id(id)?;
3910 if in_flight {
3911 bail!("task {resolved} is being run by a live daemon right now");
3912 }
3913 let receipt = inquiry.map(|q| self.root.join("triage-discard").join(format!("{q}.json")));
3914 if let Some(path) = &receipt {
3915 std::fs::create_dir_all(path.parent().expect("receipt directory"))?;
3916 }
3917 self.write_tombstone(&resolved)?;
3918 if let Err(e) = self.remove_record_with_attachments(&resolved, |p| match &receipt {
3919 Some(path) => std::fs::rename(p, path),
3920 None => std::fs::remove_file(p),
3921 }) {
3922 if self.path_of(&resolved).exists() {
3926 let _ = std::fs::remove_file(self.tombstone_path(&resolved));
3927 }
3928 return Err(e);
3929 }
3930 let (released, still_blocked) = self.release_dependents_of(&resolved, questions);
3931 Ok(Removal {
3932 id: resolved,
3933 released,
3934 still_blocked,
3935 })
3936 }
3937
3938 fn tombstone_path(&self, id: &str) -> PathBuf {
3941 self.root.join(format!("{id}.removed"))
3942 }
3943
3944 fn write_tombstone(&self, id: &str) -> Result<()> {
3945 let path = self.tombstone_path(id);
3946 let tmp = self.root.join(format!("{id}.removed.tmp"));
3947 std::fs::write(&tmp, b"")
3948 .and_then(|()| std::fs::rename(&tmp, &path))
3949 .with_context(|| format!("write {}", path.display()))
3950 }
3951
3952 fn was_deleted(&self, id: &str) -> bool {
3956 self.tombstone_path(id).is_file() && !self.path_of(id).exists()
3957 }
3958
3959 pub fn apply_deleted_blockers(&self, task: &mut Task, questions: &Questions) -> Vec<String> {
3963 let deleted = deleted_blockers(self, questions, &task.blocked_by);
3964 deleted
3965 .into_iter()
3966 .filter(|id| task.dependency_deleted(id))
3967 .collect()
3968 }
3969
3970 pub fn note_dependency_deleted(&self, dependent: &Task, deleted: &str) {
3974 let Some(home) = self.root.parent().filter(|p| !p.as_os_str().is_empty()) else {
3975 return;
3976 };
3977 let ja = crate::lang::is_japanese(&crate::lang::of_repo(&dependent.repo));
3978 let waiting = dependent.status == TaskStatus::Blocked;
3979 let message = match (ja, waiting) {
3980 (true, false) => format!(
3981 "タスク {} は、待っていた {} が削除されたため待機を解除し、元の状態に戻しました",
3982 dependent.short(),
3983 short(deleted)
3984 ),
3985 (true, true) => format!(
3986 "タスク {} は、待っていた {} が削除されたため、残りの依存を待っています",
3987 dependent.short(),
3988 short(deleted)
3989 ),
3990 (false, false) => format!(
3991 "Task {} stopped waiting on {} because it was deleted, and returned to its previous state",
3992 dependent.short(),
3993 short(deleted)
3994 ),
3995 (false, true) => format!(
3996 "Task {} stopped waiting on {} because it was deleted, and is still waiting on its other dependencies",
3997 dependent.short(),
3998 short(deleted)
3999 ),
4000 };
4001 crate::notices::raise_in(
4002 home,
4003 crate::notices::Notice::info(
4004 &format!("unblocked:{}:{}", dependent.id, deleted),
4005 message,
4006 )
4007 .link(crate::notices::Link::Task {
4008 id: dependent.id.clone(),
4009 }),
4010 );
4011 }
4012
4013 fn release_dependents_of(
4018 &self,
4019 dependency: &str,
4020 questions: &Questions,
4021 ) -> (Vec<String>, Vec<String>) {
4022 let (mut released, mut still_blocked) = (Vec::new(), Vec::new());
4023 for listed in self.list() {
4024 if listed.status != TaskStatus::Blocked || !listed.blocked_by.iter().any(|b| {
4025 matches!(crate::queue::dependency(self, questions, b), Dependency::Deleted(id) if id == dependency)
4026 }) {
4027 continue;
4028 }
4029 let Ok(_claim) = self.claim(&listed.id) else {
4030 continue;
4031 };
4032 let Ok(mut task) = self.get(&listed.id) else {
4033 continue;
4034 };
4035 let references: Vec<String> = task.blocked_by.iter().filter(|id| {
4036 matches!(crate::queue::dependency(self, questions, id), Dependency::Deleted(full) if full == dependency)
4037 }).cloned().collect();
4038 if references.is_empty() {
4039 continue;
4040 }
4041 for reference in references {
4042 task.dependency_deleted(&reference);
4043 }
4044 if self.put(&mut task).is_err() {
4045 continue;
4046 }
4047 self.note_dependency_deleted(&task, dependency);
4048 if task.status == TaskStatus::Blocked {
4049 still_blocked.push(task.id.clone());
4050 } else {
4051 released.push(task.id.clone());
4052 }
4053 }
4054 (released, still_blocked)
4055 }
4056
4057 fn remove_record_with_attachments(
4061 &self,
4062 resolved: &str,
4063 remove_record: impl FnOnce(&Path) -> std::io::Result<()>,
4064 ) -> Result<()> {
4065 self.sweep_removed_attachments();
4072 let attachments = self.attachments_dir(resolved);
4073 let aside = self.root.join(format!("{resolved}.attachments.removing"));
4074 let moved = match std::fs::rename(&attachments, &aside) {
4075 Ok(()) => true,
4076 Err(e) if e.kind() == std::io::ErrorKind::NotFound => false,
4077 Err(e) => {
4078 return Err(e).with_context(|| format!("remove {}", attachments.display()));
4079 }
4080 };
4081 let path = self.path_of(resolved);
4082 if let Err(e) = remove_record(&path) {
4083 if moved {
4084 let _ = std::fs::rename(&aside, &attachments);
4085 }
4086 return Err(e).with_context(|| format!("remove {}", path.display()));
4087 }
4088 if moved {
4089 if let Err(e) = std::fs::remove_dir_all(&aside) {
4090 tracing::warn!("leftover attachments {}: {e}", aside.display());
4091 }
4092 }
4093 let lock = self.lock_path(resolved);
4094 if let Err(e) = std::fs::remove_file(&lock) {
4095 if e.kind() != std::io::ErrorKind::NotFound {
4096 return Err(e).with_context(|| format!("remove {}", lock.display()));
4097 }
4098 }
4099 Ok(())
4100 }
4101
4102 fn sweep_removed_attachments(&self) {
4108 let Ok(entries) = std::fs::read_dir(&self.root) else {
4109 return;
4110 };
4111 for entry in entries.flatten() {
4112 let name = entry.file_name();
4113 let name = name.to_string_lossy();
4114 let Some(id) = name.strip_suffix(".attachments.removing") else {
4115 continue;
4116 };
4117 if !self.path_of(id).exists() {
4120 if let Err(e) = std::fs::remove_dir_all(entry.path()) {
4121 tracing::warn!("leftover attachments {}: {e}", entry.path().display());
4122 }
4123 }
4124 }
4125 self.sweep_tombstones();
4126 }
4127
4128 fn sweep_tombstones(&self) {
4137 let Ok(entries) = std::fs::read_dir(&self.root) else {
4138 return;
4139 };
4140 let tasks = self.list();
4141 for entry in entries.flatten() {
4142 let name = entry.file_name();
4143 let name = name.to_string_lossy();
4144 let Some(id) = name.strip_suffix(".removed") else {
4145 continue;
4146 };
4147 if self.path_of(id).exists()
4148 || tasks.iter().any(|t| {
4149 t.blocked_by
4150 .iter()
4151 .any(|b| id.starts_with(b) || id.ends_with(b))
4152 })
4153 {
4154 continue;
4155 }
4156 let old = entry
4157 .metadata()
4158 .and_then(|m| m.modified())
4159 .ok()
4160 .and_then(|m| m.elapsed().ok())
4161 .is_some_and(|age| age >= TOMBSTONE_GRACE);
4162 if old {
4163 let _ = std::fs::remove_file(entry.path());
4164 }
4165 }
4166 }
4167
4168 fn lock_path(&self, id: &str) -> PathBuf {
4171 self.root.join(format!("{id}.lock"))
4172 }
4173
4174 pub fn list(&self) -> Vec<Task> {
4187 #[cfg(test)]
4188 LIST_READS.with(|count| count.set(count.get() + 1));
4189 let mut tasks: Vec<Task> = std::fs::read_dir(&self.root)
4190 .into_iter()
4191 .flatten()
4192 .flatten()
4193 .map(|e| e.path())
4194 .filter(|p| p.extension().is_some_and(|x| x == "json"))
4195 .filter_map(|p| read_path(&p).ok())
4196 .collect();
4197 tasks.sort_unstable_by(|a, b| b.priority.cmp(&a.priority).then_with(|| b.id.cmp(&a.id)));
4198 tasks
4199 }
4200
4201 pub fn unreadable(&self) -> Vec<PathBuf> {
4205 std::fs::read_dir(&self.root)
4206 .into_iter()
4207 .flatten()
4208 .flatten()
4209 .map(|e| e.path())
4210 .filter(|p| p.extension().is_some_and(|x| x == "json"))
4211 .filter(|p| read_path(p).is_err())
4212 .collect()
4213 }
4214
4215 pub fn superseded(&self) -> HashMap<String, String> {
4228 let mut by = HashMap::new();
4229 for task in self.list() {
4230 for earlier in &task.runs {
4231 if let Some(later) = task.successor_of(earlier) {
4232 by.insert(earlier.clone(), later.clone());
4233 }
4234 }
4235 }
4236 by
4237 }
4238
4239 pub fn superseded_by(&self, run: &str) -> Option<String> {
4247 for task in self.list() {
4248 if task.runs.iter().any(|r| r == run) {
4249 return task.successor_of(run).cloned();
4250 }
4251 }
4252 None
4253 }
4254
4255 pub fn latest_attempt(&self, run: &str) -> Option<String> {
4266 for task in self.list() {
4267 if task.runs.iter().any(|r| r == run) {
4268 return task.runs.last().filter(|last| **last != run).cloned();
4269 }
4270 }
4271 None
4272 }
4273
4274 pub fn next_runnable(&self) -> Option<Task> {
4279 let mut runnable: Vec<Task> = self
4280 .list()
4281 .into_iter()
4282 .filter(|t| t.status.runnable())
4283 .collect();
4284 runnable.sort_unstable_by(dispatch_order);
4285 runnable.into_iter().next()
4286 }
4287
4288 pub fn claim(&self, id: &str) -> Result<Claim> {
4295 std::fs::create_dir_all(&self.root)
4296 .with_context(|| format!("create {}", self.root.display()))?;
4297 let path = self.lock_path(id);
4298 let retry = crate::lock_file::Retry::new(None);
4299 match retry.create(&path) {
4300 Ok(mut f) => {
4301 use std::io::Write as _;
4302 let _ = writeln!(f, "{}", std::process::id());
4304 Ok(Claim { path })
4305 }
4306 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
4307 bail!("task {id} is already claimed ({} exists)", path.display())
4308 }
4309 Err(e) => Err(e).with_context(|| format!("lock {}", path.display())),
4310 }
4311 }
4312
4313 #[must_use]
4316 pub fn is_claimed(&self, id: &str) -> bool {
4317 self.lock_path(id).exists()
4318 }
4319
4320 pub fn resolve_id(&self, prefix: &str) -> Result<String> {
4322 if !prefix.is_empty()
4323 && prefix != "."
4324 && prefix != ".."
4325 && !prefix.contains(['/', '\\'])
4326 && self.path_of(prefix).is_file()
4327 {
4328 return Ok(prefix.to_owned());
4329 }
4330 let ids = record_ids(&self.root, "json")?;
4331 match resolve_reference(prefix, ids.iter().map(String::as_str)) {
4332 Reference::Found(id) => Ok(id),
4333 Reference::Missing => bail!("no task matches `{prefix}`"),
4334 Reference::Ambiguous => bail!("`{prefix}` matches multiple tasks"),
4335 }
4336 }
4337
4338 pub fn revision(&self) -> u64 {
4345 self.revision_excluding(&std::collections::BTreeSet::new())
4346 }
4347
4348 pub fn revision_excluding(&self, skip: &std::collections::BTreeSet<String>) -> u64 {
4351 use std::hash::{Hash as _, Hasher as _};
4352
4353 let mut entries: Vec<(String, u64)> = std::fs::read_dir(&self.root)
4354 .into_iter()
4355 .flatten()
4356 .flatten()
4357 .filter(|e| e.path().extension().is_some_and(|ext| ext == "json"))
4358 .filter(|e| {
4359 let path = e.path();
4360 !path
4361 .file_stem()
4362 .is_some_and(|stem| skip.contains(stem.to_string_lossy().as_ref()))
4363 })
4364 .filter_map(|e| {
4365 let name = e.file_name().to_string_lossy().into_owned();
4366 let mtime = e
4367 .metadata()
4368 .ok()?
4369 .modified()
4370 .ok()?
4371 .duration_since(std::time::UNIX_EPOCH)
4372 .ok()?
4373 .as_millis() as u64;
4374 Some((name, mtime))
4375 })
4376 .collect();
4377
4378 if entries.is_empty() {
4379 return 0;
4380 }
4381
4382 entries.sort_unstable();
4383 let mut hasher = std::hash::DefaultHasher::new();
4384 for (name, mtime) in &entries {
4385 name.hash(&mut hasher);
4386 mtime.hash(&mut hasher);
4387 }
4388 let h = hasher.finish();
4389 if h == 0 { 1 } else { h }
4390 }
4391}
4392
4393const TOMBSTONE_GRACE: std::time::Duration = std::time::Duration::from_secs(3600);
4396
4397#[derive(Debug, Clone)]
4399pub struct Removal {
4400 pub id: String,
4402 pub released: Vec<String>,
4406 pub still_blocked: Vec<String>,
4409}
4410
4411#[derive(Debug)]
4413pub struct Claim {
4414 path: PathBuf,
4415}
4416
4417impl Drop for Claim {
4418 fn drop(&mut self) {
4419 let _ = std::fs::remove_file(&self.path);
4420 }
4421}
4422
4423pub fn title_from(instruction: &str, max: usize) -> String {
4426 let Some(line) = first_line(instruction) else {
4427 return "(empty task)".to_owned();
4428 };
4429 if line.chars().count() <= max {
4430 return line.to_owned();
4431 }
4432 let head: String = line.chars().take(max.saturating_sub(1)).collect();
4433 format!("{head}…")
4434}
4435
4436pub(crate) fn first_line(instruction: &str) -> Option<&str> {
4442 let line = instruction
4443 .lines()
4444 .map(str::trim)
4445 .find(|l| !l.is_empty())?
4446 .trim_start_matches(['#', '-', '*', '>', ' '])
4447 .trim();
4448 (!line.is_empty()).then_some(line)
4449}
4450
4451#[cfg(test)]
4452thread_local! {
4453 pub(crate) static TASK_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4454}
4455
4456fn read_path(path: &Path) -> Result<Task> {
4457 #[cfg(test)]
4458 TASK_READS.with(|count| count.set(count.get() + 1));
4459 let body = std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;
4460 let mut task: Task =
4461 serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))?;
4462 if task.schema > SCHEMA {
4468 bail!(
4469 "task {} was written by a different magi (schema {}, this build \
4470 speaks {SCHEMA})",
4471 task.id,
4472 task.schema
4473 );
4474 }
4475 task.preserve_legacy_build_cache();
4476 if task.schema < 22
4477 && task.status == TaskStatus::Held
4478 && task.hold_source == Some(HoldSource::Machine)
4479 && task.resume_override.is_none()
4480 && task
4481 .hold_reason
4482 .as_deref()
4483 .is_some_and(crate::disk::is_gate_reason)
4484 {
4485 task.mark_disk_capacity();
4486 }
4487 Ok(task)
4488}
4489
4490#[derive(Debug, PartialEq, Eq)]
4493pub(crate) enum Reference {
4494 Found(String),
4495 Missing,
4496 Ambiguous,
4497}
4498
4499pub(crate) fn resolve_reference<'a>(id: &str, ids: impl Iterator<Item = &'a str>) -> Reference {
4500 let mut hits = Vec::new();
4501 for candidate in ids {
4502 if candidate == id {
4503 return Reference::Found(candidate.to_owned());
4504 }
4505 if candidate.starts_with(id) || candidate.ends_with(id) {
4506 hits.push(candidate);
4507 }
4508 }
4509 match hits.as_slice() {
4510 [] => Reference::Missing,
4511 [one] => Reference::Found((*one).to_owned()),
4512 _ => Reference::Ambiguous,
4513 }
4514}
4515
4516pub(crate) fn record_ids(root: &Path, extension: &str) -> Result<Vec<String>> {
4519 let entries = match std::fs::read_dir(root) {
4520 Ok(entries) => entries,
4521 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
4522 Err(e) => return Err(e.into()),
4523 };
4524 let mut ids = Vec::new();
4525 for entry in entries {
4526 let path = entry?.path();
4527 if path.extension().is_some_and(|e| e == extension)
4528 && let Some(id) = path.file_stem().and_then(|s| s.to_str())
4529 {
4530 ids.push(id.to_owned());
4531 }
4532 }
4533 Ok(ids)
4534}
4535
4536#[derive(Debug, PartialEq, Eq)]
4539pub enum Dependency {
4540 Task(String),
4542 Question(String),
4544 Deleted(String),
4546 Missing,
4548 Ambiguous,
4550 Unknown,
4552}
4553
4554pub fn dependency(queue: &Queue, questions: &Questions, id: &str) -> Dependency {
4556 let (Ok(tasks), Ok(qs), Ok(removed)) = (
4557 record_ids(queue.root(), "json"),
4558 record_ids(questions.root(), "json"),
4559 record_ids(queue.root(), "removed"),
4560 ) else {
4561 return Dependency::Unknown;
4562 };
4563 let mut ids = tasks
4566 .iter()
4567 .chain(qs.iter())
4568 .chain(removed.iter())
4569 .cloned()
4570 .collect::<Vec<_>>();
4571 ids.sort();
4572 ids.dedup();
4573 match resolve_reference(id, ids.iter().map(String::as_str)) {
4574 Reference::Found(id) if tasks.contains(&id) => Dependency::Task(id),
4575 Reference::Found(id) if qs.contains(&id) => Dependency::Question(id),
4576 Reference::Found(id) if queue.was_deleted(&id) => Dependency::Deleted(id),
4577 Reference::Found(_) => Dependency::Unknown,
4578 Reference::Missing => Dependency::Missing,
4579 Reference::Ambiguous => Dependency::Ambiguous,
4580 }
4581}
4582
4583pub fn normalize_blockers(queue: &Queue, questions: &Questions, ids: &mut [String]) {
4585 for id in ids {
4586 if let Dependency::Task(full) | Dependency::Question(full) | Dependency::Deleted(full) =
4587 dependency(queue, questions, id)
4588 {
4589 *id = full;
4590 }
4591 }
4592}
4593
4594pub fn dependency_facts(queue: &Queue, questions: &Questions) -> String {
4597 let inventory = crate::blockers::Inventory::load(queue, questions);
4598 let mut text = String::from(
4599 "Current authoritative queue (historical missing-task claims may be stale; unreadable or ambiguous references must keep waiting):\n",
4600 );
4601 match record_ids(queue.root(), "json") {
4602 Ok(ids) => {
4603 for id in ids {
4604 match queue.get(&id) {
4605 Ok(task) => text.push_str(&format!(
4606 "{}: {}; blocked_by={:?}; chain={:?}\n",
4607 task.id,
4608 task.status.as_str(),
4609 task.blocked_by,
4610 inventory.waits_on(&task)
4611 )),
4612 Err(_) => text.push_str(&format!("{id}: exists, state unreadable\n")),
4613 }
4614 }
4615 }
4616 Err(_) => text.push_str("Queue inventory unreadable: existence is unknown.\n"),
4617 }
4618 text
4619}
4620
4621pub fn missing_blockers(
4623 queue: &Queue,
4624 questions: &Questions,
4625 blocked_by: &[String],
4626) -> Vec<String> {
4627 blocked_by
4628 .iter()
4629 .filter(|id| dependency(queue, questions, id) == Dependency::Missing)
4630 .cloned()
4631 .collect()
4632}
4633
4634pub fn deleted_blockers(
4637 queue: &Queue,
4638 questions: &Questions,
4639 blocked_by: &[String],
4640) -> Vec<String> {
4641 blocked_by
4642 .iter()
4643 .filter(|id| matches!(dependency(queue, questions, id), Dependency::Deleted(_)))
4644 .cloned()
4645 .collect()
4646}
4647
4648pub fn missing_blocker_hold_reason(blocked_by: &[String], missing: &[String]) -> String {
4660 missing_blocker_hold_reason_in(blocked_by, missing, "en")
4661}
4662
4663pub fn missing_blocker_hold_reason_in(
4665 blocked_by: &[String],
4666 missing: &[String],
4667 language: &str,
4668) -> String {
4669 if crate::lang::is_japanese(language) {
4670 format!(
4671 "{} を待っていましたが、{} はディスク上に存在しません - `magi task triage` を参照",
4672 blocked_by.join(", "),
4673 missing.join(", "),
4674 )
4675 } else {
4676 format!(
4677 "blocked on {} but {} no longer exist(s) on disk - see `magi task triage`",
4678 blocked_by.join(", "),
4679 missing.join(", "),
4680 )
4681 }
4682}
4683
4684pub fn short(id: &str) -> &str {
4686 id.split('-').next_back().unwrap_or(id)
4687}
4688
4689fn new_id() -> String {
4690 let stamp = jiff::Zoned::now().strftime("%Y%m%d-%H%M%S");
4691 let seed = crate::rng::entropy();
4692 format!("{stamp}-{:04x}", (seed ^ (seed >> 32)) & 0xffff)
4693}
4694
4695#[cfg(test)]
4696mod tests {
4697 #[test]
4698 fn reassignment_clears_repository_bound_execution_selections() {
4699 let mut task = Task::new(
4700 "move".into(),
4701 "evidence".into(),
4702 "old".into(),
4703 Source::Human,
4704 );
4705 task.review_branch = Some("old-review".into());
4706 task.review_instruction = Some("old criteria".into());
4707 task.pr_recovery = Some(crate::pr_recovery::Selection {
4708 url: "https://example.invalid/pull/1".into(),
4709 branch: "old-pr".into(),
4710 head: "head".into(),
4711 source_head: None,
4712 source_run: None,
4713 source_proof: None,
4714 disposition: None,
4715 instruction: "old criteria".into(),
4716 approved_at: Timestamp::now(),
4717 });
4718 task.replacement = Some(crate::merge_decision::Replacement {
4719 question: "owner".into(),
4720 run: "old-run".into(),
4721 pr: "https://example.invalid/pull/1".into(),
4722 agent: "worker".into(),
4723 context: "evidence".into(),
4724 });
4725 task.resume_override = Some(OperatorResume {
4726 question_id: "old-question".into(),
4727 at: Timestamp::now(),
4728 conductor_rehold: None,
4729 forced: true,
4730 pinned_run: Some("old-run".into()),
4731 });
4732 task.interrupt = true;
4733 task.reassign_repository("new".into(), "test");
4734 assert!(task.review_branch.is_none());
4735 assert!(task.review_instruction.is_none());
4736 assert!(task.pr_recovery.is_none());
4737 assert!(task.replacement.is_none());
4738 assert!(task.resume_override.is_none());
4739 assert!(!task.interrupt);
4740 assert!(task.fresh_start);
4741 assert_eq!(task.instruction, "evidence");
4742 }
4743
4744 #[test]
4745 fn explicit_resumption_is_not_invented_for_legacy_or_automatic_release() {
4746 let t = Task::new(
4747 "retry".into(),
4748 "do it".into(),
4749 PathBuf::from("."),
4750 Source::Human,
4751 );
4752 let mut value = serde_json::to_value(&t).unwrap();
4753 for field in ["resumption", "resumption_history", "operator_decided_at"] {
4754 value.as_object_mut().unwrap().remove(field);
4755 }
4756 value["schema"] = serde_json::json!(15);
4757 let mut legacy: Task = serde_json::from_value(value).unwrap();
4758 legacy.hold_machine(Some("automatic retry".into()));
4759 legacy.release();
4760 assert!(legacy.resumption.is_none());
4761 assert!(legacy.resumption_history.is_empty());
4762 assert!(legacy.operator_decided_at.is_none());
4763 legacy.release_operator("cli", None);
4764 legacy.start("run".into());
4765 let reloaded: Task =
4766 serde_json::from_str(&serde_json::to_string(&legacy).unwrap()).unwrap();
4767 assert!(reloaded.resume_override.is_none());
4768 assert_eq!(reloaded.resumption.as_ref().unwrap().generation, 1);
4769 }
4770
4771 #[test]
4772 fn merge_over_lets_the_later_choice_win_and_keeps_the_rest() {
4773 let mut base = RunOverrides {
4774 merge: Some("pr".to_owned()),
4775 candidates: Some(3),
4776 ..RunOverrides::default()
4777 };
4778 base.merge_over(&RunOverrides {
4779 merge: Some("none".to_owned()),
4780 seed: Some(7),
4781 ..RunOverrides::default()
4782 });
4783 assert_eq!(base.merge.as_deref(), Some("none"));
4784 assert_eq!(base.candidates, Some(3));
4785 assert_eq!(base.seed, Some(7));
4786 }
4787
4788 #[test]
4789 fn an_already_landed_task_is_done_with_its_attempt_refunded() {
4790 let mut t = task("relanded");
4791 t.attempts = 1;
4792 t.status = TaskStatus::Running;
4793 t.already_landed("already in main as 0e368de", completion(&t));
4794 assert_eq!(t.status, TaskStatus::Done);
4795 assert_eq!(t.attempts, 0);
4796 assert!(t.hold_reason.is_none());
4797 assert_eq!(t.last_error.as_deref(), Some("already in main as 0e368de"));
4798 }
4799
4800 #[test]
4801 fn missing_blocker_reason_follows_the_language() {
4802 let b = vec!["a".to_owned()];
4803 let en = missing_blocker_hold_reason_in(&b, &b, "en");
4804 assert_eq!(en, missing_blocker_hold_reason(&b, &b));
4805 assert!(en.starts_with("blocked on a"));
4806 assert!(missing_blocker_hold_reason_in(&b, &b, "ja").contains("存在しません"));
4807 assert_eq!(missing_blocker_hold_reason_in(&b, &b, "de"), en);
4808 }
4809
4810 use super::*;
4811
4812 fn completion(task: &Task) -> CompletionContext {
4813 CompletionContext::new(CompletionActor::Cli, None, Path::new("."), task)
4814 }
4815
4816 #[test]
4817 fn completion_retains_the_hold_dependency_and_failure_it_clears() {
4818 let mut held = task("held evidence");
4819 held.hold_manual(Some("owner approval required".into()));
4820 held.last_error = Some("review budget exhausted".into());
4821 held.succeed(completion(&held));
4822 let event = held.completion_history.last().unwrap();
4823 assert_eq!(event.prior_status, TaskStatus::Held);
4824 assert_eq!(
4825 event.prior_hold_reason.as_deref(),
4826 Some("owner approval required")
4827 );
4828 assert_eq!(
4829 event.prior_error.as_deref(),
4830 Some("review budget exhausted")
4831 );
4832 assert!(held.hold_reason.is_none());
4833 assert!(held.last_error.is_none());
4834 let mut blocked = task("dependency evidence");
4835 blocked.block(
4836 vec!["dependency".into()],
4837 Some("waiting on migration".into()),
4838 );
4839 blocked.succeed(completion(&blocked));
4840 let event = blocked.completion_history.last().unwrap();
4841 assert_eq!(event.prior_status, TaskStatus::Blocked);
4842 assert_eq!(
4843 event.prior_block_reason.as_deref(),
4844 Some("waiting on migration")
4845 );
4846 assert!(blocked.block_reason.is_none());
4847 assert!(blocked.blocked_by.is_empty());
4848 let saved = serde_json::to_vec(&held).unwrap();
4849 let restored: Task = serde_json::from_slice(&saved).unwrap();
4850 assert_eq!(restored.completion_history, held.completion_history);
4851 }
4852
4853 #[test]
4854 fn completion_audit_is_append_only_under_stale_puts() {
4855 let dir = tempfile::tempdir().unwrap();
4856 let queue = Queue::at(dir.path().join("queue"));
4857 let mut current = task("audited");
4858 current.hold_manual(Some("inspect".into()));
4859 queue.put(&mut current).unwrap();
4860 let mut stale = queue.get(¤t.id).unwrap();
4861 current.succeed(completion(¤t));
4862 queue.put(&mut current).unwrap();
4863 let original = current.completion_history[0].clone();
4864 stale.last_error = Some("stale control state".into());
4865 queue.put(&mut stale).unwrap();
4866 assert_eq!(stale.status, TaskStatus::Done);
4867 assert_eq!(stale.completion_history, vec![original.clone()]);
4868 let mut context = completion(¤t);
4869 context.reason = Some("not actually finished".into());
4870 current.reopen(context).unwrap();
4871 queue.put(&mut current).unwrap();
4872 stale.completion_history[0].actor = CompletionActor::Web;
4873 stale.completion_history[0].reason = Some("rewritten evidence".into());
4874 queue.put(&mut stale).unwrap();
4875 assert_eq!(stale.status, TaskStatus::Held);
4876 assert_eq!(stale.hold_reason.as_deref(), Some("not actually finished"));
4877 assert_eq!(stale.completion_history[0], original);
4878 assert_eq!(stale.completion_history, current.completion_history);
4879 }
4880
4881 #[test]
4882 fn a_writer_missing_a_reopen_contributes_receipts_but_not_authority() {
4883 let (_dir, q) = queue();
4884 let mut current = task("durable receipts");
4885 q.put(&mut current).unwrap();
4886 let mut stale = current.clone();
4887 let grant: crate::repair_budget::Receipt = serde_json::from_value(serde_json::json!({
4888 "request": {
4889 "task": current.id, "run": "old-run", "kind": "gate", "rounds": 1,
4890 "head": "old-head", "expect_pass": 0, "request": "old-grant", "reason": "retry"
4891 },
4892 "at": stale.updated_at, "contract": "old-contract"
4893 }))
4894 .unwrap();
4895 stale.release_operator("triage", Some("triage-question"));
4896 stale.queue_repair(&grant);
4897 let reconciliation: crate::repair_budget::reconcile::Receipt =
4898 serde_json::from_value(serde_json::json!({
4899 "request": {
4900 "task": current.id, "run": "old-run", "head": "old-head", "expect_pass": 0,
4901 "receipt": "old-grant", "question": "triage-question", "answer_at": grant.at,
4902 "request": "reconciliation", "reason": "retain the answer"
4903 },
4904 "grant": grant, "source": "answer", "application": "release",
4905 "decision": grant.at, "superseded_questions": []
4906 }))
4907 .unwrap();
4908 stale.repair_reconciliations.push(reconciliation.clone());
4909 stale.triage_applied.push("triage-question".into());
4910 stale.actions_applied.push("choice".into());
4911 stale.base_recovery_requests.push("base-request".into());
4912 stale.chat_notices.push("delivery".into());
4913 stale.chat_notice = Some(ChatNotice {
4914 key: "other-delivery".into(),
4915 at: grant.at,
4916 outcome: ChatNoticeOutcome::Posted,
4917 });
4918 for ledger in [
4919 &mut stale.decision_effects,
4920 &mut stale.dispatched_resumes,
4921 &mut stale.superseded_resumes,
4922 ] {
4923 ledger.insert("shared".into(), "stale".into());
4924 ledger.insert("only-stale".into(), "receipt".into());
4925 }
4926
4927 let mut latest_grant = grant.clone();
4928 latest_grant.request.request = "new-grant".into();
4929 current.queue_repair(&latest_grant);
4930 for ledger in [
4931 &mut current.decision_effects,
4932 &mut current.dispatched_resumes,
4933 &mut current.superseded_resumes,
4934 ] {
4935 ledger.insert("shared".into(), "committed".into());
4936 }
4937 current.succeed(completion(¤t));
4938 let mut context = completion(¤t);
4939 context.reason = Some("inspect again".into());
4940 current.reopen(context).unwrap();
4941 q.put(&mut current).unwrap();
4942
4943 for _ in 0..2 {
4944 q.put(&mut stale.clone()).unwrap();
4945 let saved = q.get(¤t.id).unwrap();
4946 assert_eq!(saved.status, TaskStatus::Held);
4947 assert_eq!(saved.hold_reason, current.hold_reason);
4948 assert_eq!(saved.operator_decided_at, current.operator_decided_at);
4949 assert_eq!(saved.completion_history, current.completion_history);
4950 assert!(saved.resume_override.is_none());
4951 assert!(saved.resumption.is_none());
4952 assert_eq!(
4953 saved.resumption_history,
4954 [stale.resumption.clone().unwrap()]
4955 );
4956 assert_eq!(saved.triage_applied, ["triage-question"]);
4957 assert_eq!(saved.actions_applied, ["choice"]);
4958 assert_eq!(saved.base_recovery_requests, ["base-request"]);
4959 assert_eq!(saved.chat_notices, ["delivery", "other-delivery"]);
4960 assert_eq!(saved.repair_grants, [grant.clone(), latest_grant.clone()]);
4961 assert_eq!(
4962 saved.repair_reconciliations,
4963 std::slice::from_ref(&reconciliation)
4964 );
4965 for ledger in [
4966 saved.decision_effects,
4967 saved.dispatched_resumes,
4968 saved.superseded_resumes,
4969 ] {
4970 assert_eq!(ledger["shared"], "committed");
4971 assert_eq!(ledger["only-stale"], "receipt");
4972 }
4973 }
4974 }
4975
4976 #[test]
4977 fn repeated_completion_only_notifies_for_new_occurrences() {
4978 let mut task = chat_task();
4979 task.succeed(completion(&task));
4980 let first = task.chat_notice_key().unwrap();
4981 task.chat_notices.push(first.clone());
4982 task.succeed(completion(&task));
4983 assert_eq!(task.completion_history.len(), 1, "idempotent while done");
4984 assert_eq!(task.chat_notice_due(), None);
4985 let mut context = completion(&task);
4986 context.reason = Some("inspect".into());
4987 task.reopen(context).unwrap();
4988 task.succeed(completion(&task));
4989 let second = task.chat_notice_key().unwrap();
4990 assert_ne!(first, second);
4991 assert_eq!(task.chat_notice_due(), Some(second));
4992 assert_eq!(task.completion_history.len(), 3);
4993 }
4994
4995 #[test]
4996 fn old_tasks_have_unknown_completion_provenance_not_invented_events() {
4997 let mut task = task("legacy");
4998 task.status = TaskStatus::Done;
4999 let mut value = serde_json::to_value(&task).unwrap();
5000 value.as_object_mut().unwrap().remove("completion_history");
5001 let task: Task = serde_json::from_value(value).unwrap();
5002 assert!(task.completion_history.is_empty());
5003 assert_eq!(task.chat_notice_key().as_deref(), Some("done"));
5004 }
5005
5006 #[test]
5007 fn triage_applied_survives_release_and_old_records_read_as_empty() {
5008 let mut t = Task::new(
5009 "t".to_owned(),
5010 "i".to_owned(),
5011 PathBuf::from("r"),
5012 Source::Human,
5013 );
5014 t.mark_triage_applied("q1");
5015 t.mark_triage_applied("q1");
5016 t.hold_machine(Some("x".to_owned()));
5017 t.release();
5018 assert_eq!(t.triage_applied, ["q1"]);
5019 assert!(t.triage_applied("q1") && !t.triage_applied("q2"));
5020
5021 let mut v = serde_json::to_value(&t).unwrap();
5022 v.as_object_mut().unwrap().remove("triage_applied");
5023 let old: Task = serde_json::from_value(v).unwrap();
5024 assert!(old.triage_applied.is_empty());
5025 }
5026
5027 #[test]
5028 fn task_counts_of_empty_is_all_zero() {
5029 assert_eq!(TaskCounts::of(&[]), TaskCounts::default());
5030 }
5031
5032 #[test]
5033 fn task_counts_of_tallies_every_status() {
5034 let mut queued = Task::new(
5035 "q".to_owned(),
5036 "i".to_owned(),
5037 PathBuf::from("."),
5038 Source::Human,
5039 );
5040 queued.status = TaskStatus::Queued;
5041 let mut running = queued.clone();
5042 running.status = TaskStatus::Running;
5043 let mut done = queued.clone();
5044 done.status = TaskStatus::Done;
5045 let mut failed = queued.clone();
5046 failed.status = TaskStatus::Failed;
5047 let mut held = queued.clone();
5048 held.status = TaskStatus::Held;
5049 let mut blocked = queued.clone();
5050 blocked.status = TaskStatus::Blocked;
5051
5052 let mut parked = queued.clone();
5053 parked.status = TaskStatus::Parked;
5054
5055 let counts = TaskCounts::of(&[
5056 queued,
5057 running,
5058 done.clone(),
5059 done,
5060 failed,
5061 held,
5062 blocked,
5063 parked,
5064 ]);
5065 assert_eq!(
5066 counts,
5067 TaskCounts {
5068 queued: 1,
5069 running: 1,
5070 done: 2,
5071 failed: 1,
5072 held: 1,
5073 blocked: 1,
5074 parked: 1,
5075 }
5076 );
5077 }
5078
5079 #[test]
5080 fn task_implementers_persist_normalized_without_losing_history() {
5081 let (_dir, q) = queue();
5082 let mut t = task("keep me");
5083 t.hold_manual(Some("waiting".into()));
5084 t.runs.push("earlier-run".into());
5085 t.attachments.push("reference.txt".into());
5086 let cfg: crate::config::Config =
5087 toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
5088 .unwrap();
5089 q.put(&mut t).unwrap();
5090 let original = serde_json::to_value(&t).unwrap();
5091 for n in [2, 1, 2] {
5092 t.set_implementers(n, &cfg).unwrap();
5093 q.put(&mut t).unwrap();
5094 t = q.get(&t.id).unwrap();
5095 assert_eq!(t.implementers(), Some(usize::from(n)));
5096 assert_eq!(t.solo, n == 1);
5097 if n == 1 {
5098 assert!(t.overrides.is_none());
5099 }
5100 let mut actual = serde_json::to_value(&t).unwrap();
5101 for field in ["solo", "overrides", "updated_at"] {
5102 actual[field] = original[field].clone();
5103 }
5104 assert_eq!(actual, original);
5105 }
5106 t.overrides.as_mut().unwrap().judges = Some(2);
5107 t.set_implementers(1, &cfg).unwrap();
5108 assert_eq!(t.overrides.as_ref().unwrap().judges, Some(2));
5109 assert_eq!(t.overrides.as_ref().unwrap().candidates, None);
5110 }
5111
5112 #[test]
5113 fn task_implementers_old_records_keep_inheritance_until_changed() {
5114 let mut value = serde_json::to_value(task("old task")).unwrap();
5115 value.as_object_mut().unwrap().remove("solo");
5116 value.as_object_mut().unwrap().remove("overrides");
5117 let mut old: Task = serde_json::from_value(value).unwrap();
5118 assert_eq!(old.implementers(), None);
5119 old.set_implementers(1, &crate::config::Config::default())
5120 .unwrap();
5121 assert!(old.solo);
5122 assert!(old.overrides.is_none());
5123 }
5124
5125 #[test]
5126 fn task_implementers_reject_invalid_counts_and_states() {
5127 let cfg = crate::config::Config::default();
5128 let mut t = task("unchanged");
5129 for n in [0, 4, 255] {
5130 assert!(t.set_implementers(n, &cfg).is_err());
5131 }
5132 for status in [
5133 TaskStatus::Running,
5134 TaskStatus::Done,
5135 TaskStatus::Failed,
5136 TaskStatus::Blocked,
5137 TaskStatus::Parked,
5138 ] {
5139 t.status = status;
5140 let before = serde_json::to_value(&t).unwrap();
5141 assert!(t.set_implementers(1, &cfg).is_err());
5142 assert_eq!(serde_json::to_value(&t).unwrap(), before);
5143 }
5144 }
5145
5146 fn queue() -> (tempfile::TempDir, Queue) {
5149 let dir = tempfile::tempdir().unwrap();
5150 let q = Queue::at(dir.path().join("queue"));
5151 (dir, q)
5152 }
5153
5154 #[test]
5155 fn base_recovery_commit_retains_decision_and_superseded_resume_evidence() {
5156 let (_dir, q) = queue();
5157 let mut original = task("base recovery");
5158 original
5159 .decision_effects
5160 .insert("old-effect".into(), "receipt".into());
5161 original
5162 .dispatched_resumes
5163 .insert("dispatched".into(), "prior-run".into());
5164 original.resume_override = Some(OperatorResume {
5165 question_id: "prior-decision".into(),
5166 at: Timestamp::now(),
5167 conductor_rehold: None,
5168 forced: true,
5169 pinned_run: Some("retained-run".into()),
5170 });
5171 q.put(&mut original).unwrap();
5172 let expected = serde_json::to_value(&original).unwrap();
5173 let mut recovered = original.clone();
5174 recovered.base_recovery_requests.push("chat/request".into());
5175 recovered
5176 .resume_override
5177 .as_mut()
5178 .unwrap()
5179 .question_id
5180 .clear();
5181 q.commit_base_recovery(&mut recovered, &expected).unwrap();
5182 let saved = q.get(&original.id).unwrap();
5183 assert_eq!(saved.decision_effects, original.decision_effects);
5184 assert_eq!(saved.dispatched_resumes, original.dispatched_resumes);
5185 assert_eq!(
5186 saved
5187 .superseded_resumes
5188 .get("prior-decision")
5189 .map(String::as_str),
5190 Some("retained-run")
5191 );
5192 assert_eq!(saved.base_recovery_requests, ["chat/request"]);
5193 assert!(saved.resume_override.unwrap().question_id.is_empty());
5194 assert!(q.commit_base_recovery(&mut recovered, &expected).is_err());
5195 }
5196
5197 #[test]
5198 fn a_stale_write_does_not_drop_the_recorded_task_chat() {
5199 let (_dir, q) = queue();
5200 let mut stale = task("chat");
5201 q.put(&mut stale).unwrap();
5202 let mut fresh = q.get(&stale.id).unwrap();
5203 fresh.chat = Some("talk-1".to_owned());
5204 q.put(&mut fresh).unwrap();
5205 q.put(&mut stale).unwrap();
5206 assert_eq!(q.get(&stale.id).unwrap().chat.as_deref(), Some("talk-1"));
5207 }
5208
5209 #[test]
5210 fn putting_a_machine_held_task_files_a_notification_beside_the_queue() {
5211 let dir = tempfile::tempdir().unwrap();
5212 let q = Queue::at(dir.path().join("queue"));
5213 let mut t = task("held");
5214 q.put(&mut t).unwrap();
5215 assert_eq!(
5216 crate::notices::Notices::at(dir.path().join("notifications"))
5217 .list()
5218 .len(),
5219 0
5220 );
5221 t.hold_machine(Some("out of attempts".to_owned()));
5222 q.put(&mut t).unwrap();
5223 let listed = crate::notices::Notices::at(dir.path().join("notifications")).list();
5224 assert_eq!(listed.len(), 1);
5225 assert!(listed[0].message.contains("out of attempts"));
5226 }
5227
5228 #[test]
5229 fn start_consumes_the_disk_resume_pin() {
5230 let mut t = task("pin");
5231 t.disk_resume_run = Some("run-1".into());
5232 t.start("run-1".into());
5233 assert!(t.disk_resume_run.is_none());
5234 }
5235
5236 fn task(title: &str) -> Task {
5237 Task::new(
5238 title.to_owned(),
5239 format!("do {title}"),
5240 PathBuf::from("."),
5241 Source::Human,
5242 )
5243 }
5244
5245 #[test]
5246 fn attempt_limit_inherits_old_records_and_controls_failure() {
5247 let mut t = task("budget");
5248 let mut old = serde_json::to_value(&t).unwrap();
5249 old.as_object_mut().unwrap().remove("attempt_limit");
5250 old["schema"] = serde_json::json!(15);
5251 let legacy: Task = serde_json::from_value(old).unwrap();
5252 assert_eq!(legacy.attempt_limit, None);
5253 assert_eq!(legacy.effective_attempt_limit(2), 2);
5254 t.attempts = 2;
5255 t.change_attempt_limit(NonZeroUsize::new(3)).unwrap();
5256 t.fail("retry", 1);
5257 assert_eq!(t.status, TaskStatus::Failed);
5258 t.attempts = 3;
5259 t.fail("stop", 10);
5260 assert_eq!(t.status, TaskStatus::Held);
5261 t.change_attempt_limit(None).unwrap();
5262 assert_eq!(t.status, TaskStatus::Held);
5263 assert_eq!(t.attempts, 3);
5264 t.fail("inherit", 4);
5265 assert_eq!(t.status, TaskStatus::Failed);
5266 for status in [
5267 TaskStatus::Running,
5268 TaskStatus::Done,
5269 TaskStatus::Failed,
5270 TaskStatus::Blocked,
5271 TaskStatus::Parked,
5272 ] {
5273 t.status = status;
5274 assert!(t.change_attempt_limit(NonZeroUsize::new(1)).is_err());
5275 assert_eq!(t.attempt_limit, None);
5276 }
5277 }
5278
5279 #[test]
5280 fn earlier_attempts_is_every_recorded_run_and_agrees_with_the_display() {
5281 let mut t = task("retried");
5282 assert!(
5283 t.earlier_attempts().is_empty(),
5284 "a first attempt takes nothing over"
5285 );
5286 t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned()];
5287 assert_eq!(t.earlier_attempts(), ["aaaa", "bbbb"]);
5288 assert_eq!(t.successor_of("aaaa"), Some(&"bbbb".to_owned()));
5290 assert_eq!(t.successor_of("bbbb"), None);
5291 assert_eq!(t.successor_of("zzzz"), None);
5292 }
5293
5294 #[test]
5295 fn resumed_runs_are_superseded_only_after_their_last_occurrence() {
5296 let (_dir, q) = queue();
5297 let mut t = task("resumed");
5298 for (runs, successor) in [
5299 (vec!["aaaa", "aaaa"], None),
5300 (vec!["aaaa", "bbbb", "aaaa"], None),
5301 (vec!["aaaa", "aaaa", "bbbb"], Some("bbbb")),
5302 (vec!["aaaa", "bbbb", "aaaa", "cccc"], Some("cccc")),
5303 ] {
5304 t.runs = runs.into_iter().map(str::to_owned).collect();
5305 q.put(&mut t).unwrap();
5306
5307 assert_eq!(t.successor_of("aaaa").map(String::as_str), successor);
5308 assert_eq!(q.superseded_by("aaaa").as_deref(), successor);
5309 assert_eq!(q.superseded().get("aaaa").map(String::as_str), successor);
5310 }
5311 }
5312
5313 #[test]
5314 fn superseded_by_names_the_next_attempt_and_none_for_the_last() {
5315 let (_dir, q) = queue();
5316 let mut t = task("retried");
5317 t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned(), "cccc".to_owned()];
5318 q.put(&mut t).unwrap();
5319
5320 assert_eq!(q.superseded_by("aaaa"), Some("bbbb".to_owned()));
5321 assert_eq!(q.superseded_by("bbbb"), Some("cccc".to_owned()));
5322 assert_eq!(
5323 q.superseded_by("cccc"),
5324 None,
5325 "the latest attempt replaces nothing"
5326 );
5327 assert_eq!(
5328 q.superseded_by("never-heard-of-it"),
5329 None,
5330 "a run belonging to no task on this queue is not superseded"
5331 );
5332
5333 let mut by = HashMap::new();
5334 by.insert("aaaa".to_owned(), "bbbb".to_owned());
5335 by.insert("bbbb".to_owned(), "cccc".to_owned());
5336 assert_eq!(
5337 q.superseded(),
5338 by,
5339 "the whole-map and single-run forms must agree"
5340 );
5341 }
5342
5343 #[test]
5344 fn superseded_attempts_is_empty_until_the_task_is_done() {
5345 let mut t = task("retried");
5346 t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned()];
5347 t.status = TaskStatus::Failed;
5348 assert_eq!(
5349 t.superseded_attempts(true),
5350 &[] as &[String],
5351 "a task still retrying has no attempt yet that a later one made moot"
5352 );
5353
5354 t.status = TaskStatus::Running;
5355 assert_eq!(t.superseded_attempts(true), &[] as &[String]);
5356 }
5357
5358 #[test]
5359 fn superseded_attempts_names_every_run_before_the_one_that_succeeded() {
5360 let mut t = task("retried");
5361 t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned(), "cccc".to_owned()];
5362 t.status = TaskStatus::Done;
5363 assert_eq!(
5364 t.superseded_attempts(true),
5365 &["aaaa".to_owned(), "bbbb".to_owned()],
5366 "cccc is the attempt whose success made the task done, and stays out"
5367 );
5368 }
5369
5370 #[test]
5371 fn superseded_attempts_is_empty_for_a_done_task_with_only_one_attempt() {
5372 let mut t = task("first try landed");
5373 t.runs = vec!["aaaa".to_owned()];
5374 t.status = TaskStatus::Done;
5375 assert_eq!(t.superseded_attempts(true), &[] as &[String]);
5376 }
5377
5378 #[test]
5379 fn superseded_attempts_is_empty_when_the_last_run_never_actually_succeeded() {
5380 let mut t = task("closed by hand after a manual merge");
5387 t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned()];
5388 t.status = TaskStatus::Done;
5389 assert_eq!(
5390 t.superseded_attempts(false),
5391 &[] as &[String],
5392 "nothing here is provably why the task is done, so nothing is superseded"
5393 );
5394 }
5395
5396 #[test]
5397 fn latest_attempt_names_the_chain_s_current_head_not_just_the_next_one() {
5398 let (_dir, q) = queue();
5399 let mut t = task("retried twice");
5400 t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned(), "cccc".to_owned()];
5401 q.put(&mut t).unwrap();
5402
5403 assert_eq!(
5404 q.latest_attempt("aaaa"),
5405 Some("cccc".to_owned()),
5406 "an old attempt points straight at the chain's current head, not the \
5407 next attempt in the middle of it"
5408 );
5409 assert_eq!(q.latest_attempt("bbbb"), Some("cccc".to_owned()));
5410 assert_eq!(
5411 q.latest_attempt("cccc"),
5412 None,
5413 "the latest attempt is not superseded by anything"
5414 );
5415 assert_eq!(
5416 q.latest_attempt("never-heard-of-it"),
5417 None,
5418 "a run belonging to no task on this queue is not superseded"
5419 );
5420 }
5421
5422 #[test]
5423 fn a_markdown_heading_is_the_title_not_decoration() {
5424 assert_eq!(
5429 title_from("# Rework the config loader\n\nIt re-reads it.\n", 40),
5430 "Rework the config loader"
5431 );
5432 assert_eq!(title_from("- fix the thing", 40), "fix the thing");
5433 assert_eq!(title_from("> quoted task", 40), "quoted task");
5434 assert_eq!(title_from(" \n\n", 40), "(empty task)");
5436 assert_eq!(title_from("###\n", 40), "(empty task)");
5437 }
5438
5439 #[test]
5440 fn a_long_title_is_elided_by_characters_not_bytes() {
5441 let long = "課題".repeat(30);
5443 let title = title_from(&long, 10);
5444 assert_eq!(title.chars().count(), 10);
5445 assert!(title.ends_with('…'));
5446 }
5447
5448 #[test]
5449 fn priority_wins_and_ties_break_oldest_first() {
5450 let (_dir, q) = queue();
5451 let mut a = task("first");
5452 let mut b = task("second");
5453 let mut c = task("urgent");
5454 a.id = "20260101-000001-aaaa".to_owned();
5456 b.id = "20260101-000002-bbbb".to_owned();
5457 c.id = "20260101-000003-cccc".to_owned();
5458 c.priority = 5;
5459 for t in [&mut a, &mut b, &mut c] {
5460 q.put(t).unwrap();
5461 }
5462
5463 assert_eq!(q.next_runnable().unwrap().id, c.id);
5465 c.hold_machine(None);
5466 q.put(&mut c).unwrap();
5467 assert_eq!(q.next_runnable().unwrap().id, a.id);
5469 assert_eq!(q.list().len(), 3, "b is still waiting its turn");
5470 }
5471
5472 #[test]
5473 fn a_blocked_task_never_starves_another_runnable_one() {
5474 let (_dir, q) = queue();
5475 let mut blocked = task("blocked");
5476 blocked.block(vec!["something".to_owned()], None);
5477 q.put(&mut blocked).unwrap();
5478
5479 let mut runnable = task("free to go");
5480 q.put(&mut runnable).unwrap();
5481
5482 let next = q.next_runnable().expect("a runnable task is still offered");
5483 assert_eq!(next.id, runnable.id);
5484 }
5485
5486 #[test]
5487 fn a_held_task_is_never_offered_to_the_loop() {
5488 let (_dir, q) = queue();
5489 let mut t = task("held");
5490 q.put(&mut t).unwrap();
5491 assert!(q.next_runnable().is_some());
5492
5493 t.hold_machine(None);
5494 q.put(&mut t).unwrap();
5495 assert!(
5496 q.next_runnable().is_none(),
5497 "a held task must wait for a human"
5498 );
5499
5500 t.status = TaskStatus::Failed;
5502 q.put(&mut t).unwrap();
5503 assert!(q.next_runnable().is_some());
5504 }
5505
5506 #[test]
5507 fn attempts_are_capped_and_then_the_task_is_held() {
5508 let mut t = task("doomed");
5509
5510 t.start("run-1".to_owned());
5511 t.fail("gate red", 2);
5512 assert_eq!(t.status, TaskStatus::Failed, "one attempt of two: retry");
5513
5514 t.start("run-2".to_owned());
5515 t.fail("gate red", 2);
5516 assert_eq!(
5517 t.status,
5518 TaskStatus::Held,
5519 "out of attempts: stop spending money on it"
5520 );
5521 assert_eq!(t.runs, ["run-1", "run-2"]);
5522 assert_eq!(t.last_error.as_deref(), Some("gate red"));
5523 assert_eq!(
5524 t.hold_reason.as_deref(),
5525 Some("gate red"),
5526 "the hold must say why, not leave hold_reason null next to a \
5527 populated last_error"
5528 );
5529 }
5530
5531 #[test]
5532 fn handing_off_a_task_records_a_hold_reason_too() {
5533 let mut t = task("left a pull request");
5534 t.start("run-1".to_owned());
5535 t.handed_off("run ended with a pull request open [run run-1]");
5536 assert_eq!(t.status, TaskStatus::Held);
5537 assert_eq!(t.hold_source, Some(HoldSource::Machine));
5538 assert_eq!(
5539 t.hold_reason.as_deref(),
5540 Some("run ended with a pull request open [run run-1]")
5541 );
5542 assert_eq!(t.hold_reason, t.last_error);
5543 }
5544
5545 #[test]
5546 fn a_quota_stall_is_refunded_so_the_backlog_survives_the_night() {
5547 let mut t = task("stalled by quota");
5548
5549 t.start("run-1".to_owned());
5550 assert_eq!(t.attempts, 1);
5551 t.stall("judge-1, judge-2 out of quota");
5552 assert_eq!(
5553 t.attempts, 0,
5554 "a closed quota window must not spend the task's retry budget"
5555 );
5556 assert_eq!(t.status, TaskStatus::Failed, "the loop should retry it");
5557 assert_eq!(
5558 t.last_error.as_deref(),
5559 Some("judge-1, judge-2 out of quota")
5560 );
5561
5562 for _ in 0..20 {
5565 t.start("run-n".to_owned());
5566 t.stall("still out of quota");
5567 }
5568 t.start("run-real".to_owned());
5569 t.fail("gate red", 2);
5570 assert_eq!(
5571 t.status,
5572 TaskStatus::Failed,
5573 "the first attempt that was really judged is attempt one"
5574 );
5575 }
5576
5577 #[test]
5578 fn releasing_a_held_task_gives_it_a_real_second_chance() {
5579 let mut t = task("retry me");
5580 t.start("run-1".to_owned());
5581 t.fail("gate red", 1);
5582 assert_eq!(t.status, TaskStatus::Held);
5583
5584 t.release();
5585 assert_eq!(t.status, TaskStatus::Queued);
5586 assert_eq!(t.attempts, 0);
5589 assert!(t.last_error.is_none());
5590 assert_eq!(
5591 t.runs.len(),
5592 1,
5593 "history is kept: attempts reset, evidence does not"
5594 );
5595 }
5596
5597 #[test]
5598 fn a_hold_reason_survives_and_a_release_clears_it() {
5599 let mut t = task("waiting on something else");
5600 t.hold_manual(Some(
5601 "waiting for 20260101-000000-aaaa to land first".to_owned(),
5602 ));
5603 assert_eq!(t.status, TaskStatus::Held);
5604 assert_eq!(
5605 t.hold_reason.as_deref(),
5606 Some("waiting for 20260101-000000-aaaa to land first")
5607 );
5608
5609 t.hold_manual(None);
5611 assert_eq!(
5612 t.hold_reason.as_deref(),
5613 Some("waiting for 20260101-000000-aaaa to land first"),
5614 "a bare re-hold keeps whatever a human already wrote down"
5615 );
5616
5617 let mut plain = task("no reason given");
5619 plain.hold_manual(None);
5620 assert_eq!(plain.status, TaskStatus::Held);
5621 assert!(plain.hold_reason.is_none());
5622
5623 t.release();
5624 assert_eq!(t.status, TaskStatus::Queued);
5625 assert!(
5626 t.hold_reason.is_none(),
5627 "a stale reason must not greet the next person who holds this task"
5628 );
5629 }
5630
5631 #[test]
5632 fn closing_a_held_task_as_done_clears_its_hold_reason_too() {
5633 let mut t = task("landed by hand while held");
5638 t.hold_manual(Some("waiting on 3ed9".to_owned()));
5639 assert_eq!(t.hold_reason.as_deref(), Some("waiting on 3ed9"));
5640
5641 t.succeed(completion(&t));
5642 assert_eq!(t.status, TaskStatus::Done);
5643 assert!(
5644 t.hold_reason.is_none(),
5645 "a done task cannot still be waiting on something"
5646 );
5647 }
5648
5649 #[test]
5650 fn holding_or_closing_a_blocked_task_clears_its_dependency_too() {
5651 let mut held = task("held straight out of blocked");
5658 held.block(
5659 vec!["20260101-000000-dead".to_owned()],
5660 Some("waiting on the migration script".to_owned()),
5661 );
5662 assert_eq!(held.status, TaskStatus::Blocked);
5663
5664 held.hold_manual(None);
5665 assert_eq!(held.status, TaskStatus::Held);
5666 assert!(
5667 held.blocked_by.is_empty(),
5668 "hold overrides the wait, same as release"
5669 );
5670 assert!(held.block_reason.is_none());
5671
5672 let mut done = task("closed straight out of blocked");
5673 done.block(
5674 vec!["20260101-000000-dead".to_owned()],
5675 Some("waiting on the migration script".to_owned()),
5676 );
5677 done.succeed(completion(&done));
5678 assert_eq!(done.status, TaskStatus::Done);
5679 assert!(
5680 done.blocked_by.is_empty(),
5681 "a done task cannot still be waiting on a dependency"
5682 );
5683 assert!(done.block_reason.is_none());
5684 }
5685
5686 #[test]
5687 fn a_blocked_task_is_never_offered_to_the_loop() {
5688 let mut t = task("blocked");
5689 assert!(t.status.runnable());
5690 t.block(
5691 vec!["dep-id".to_owned()],
5692 Some("waits on dep-id".to_owned()),
5693 );
5694 assert_eq!(t.status, TaskStatus::Blocked);
5695 assert!(!t.status.runnable());
5696 assert_eq!(TaskStatus::Blocked.as_str(), "blocked");
5697 }
5698
5699 #[test]
5700 fn unblocking_the_last_dependency_returns_the_task_to_queued() {
5701 let mut t = task("blocked on two");
5702 t.block(
5703 vec!["a".to_owned(), "b".to_owned()],
5704 Some("waits on a and b".to_owned()),
5705 );
5706
5707 t.unblock("a");
5708 assert_eq!(t.status, TaskStatus::Blocked, "b is still outstanding");
5709 assert_eq!(t.blocked_by, ["b"]);
5710
5711 t.unblock("b");
5712 assert_eq!(t.status, TaskStatus::Queued);
5713 assert!(t.blocked_by.is_empty());
5714 assert!(t.block_reason.is_none());
5715 }
5716
5717 #[test]
5718 fn unblocking_an_id_on_a_task_that_is_not_blocked_is_a_no_op() {
5719 let mut t = task("never blocked");
5720 t.unblock("whatever");
5721 assert_eq!(t.status, TaskStatus::Queued);
5722 }
5723
5724 #[test]
5725 fn a_held_task_blocked_on_a_question_returns_to_held_not_queued() {
5726 let mut t = task("held, then asked about");
5731 t.hold_machine(Some("out of attempts".to_owned()));
5732 assert_eq!(t.status, TaskStatus::Held);
5733
5734 t.block(vec!["q1".to_owned()], Some("what now?".to_owned()));
5735 assert_eq!(t.status, TaskStatus::Blocked);
5736
5737 t.record_answer("what now?".to_owned(), "leave it held".to_owned());
5738 t.unblock("q1");
5739 assert_eq!(t.status, TaskStatus::Held, "must restore, not requeue");
5740 assert_eq!(t.hold_reason.as_deref(), Some("out of attempts"));
5741 assert_eq!(t.hold_source, Some(HoldSource::Machine));
5742 assert!(t.blocked_from.is_none(), "consumed once restored");
5743 }
5744
5745 #[test]
5746 fn a_manually_held_task_blocked_on_a_question_returns_to_held() {
5747 let mut t = task("manually held, then asked about");
5748 t.hold_manual(Some("waiting on a dependency".to_owned()));
5749
5750 t.block(vec!["q1".to_owned()], None);
5751 t.unblock("q1");
5752
5753 assert_eq!(t.status, TaskStatus::Held);
5754 assert_eq!(t.hold_source, Some(HoldSource::Manual));
5755 }
5756
5757 #[test]
5758 fn re_blocking_an_already_blocked_task_keeps_the_original_blocked_from() {
5759 let mut t = task("held, blocked twice");
5763 t.hold_machine(None);
5764 t.block(vec!["q1".to_owned()], Some("first".to_owned()));
5765 t.block(
5766 vec!["q1".to_owned(), "q2".to_owned()],
5767 Some("second".to_owned()),
5768 );
5769
5770 t.unblock("q1");
5771 assert_eq!(t.status, TaskStatus::Blocked, "q2 still outstanding");
5772 t.unblock("q2");
5773 assert_eq!(t.status, TaskStatus::Held);
5774 }
5775
5776 #[test]
5777 fn unblocking_a_task_blocked_while_running_lands_on_queued_not_running() {
5778 let mut t = task("blocked mid-run");
5782 t.start("run-1".to_owned());
5783 assert_eq!(t.status, TaskStatus::Running);
5784
5785 t.block(vec!["q1".to_owned()], None);
5786 t.unblock("q1");
5787 assert_eq!(t.status, TaskStatus::Queued);
5788 }
5789
5790 #[test]
5791 fn a_pre_schema_4_blocked_record_with_hold_evidence_restores_to_held() {
5792 let mut t = task("legacy record, held before it was blocked");
5798 t.hold_source = Some(HoldSource::Machine);
5799 t.hold_reason = Some("legacy hold reason".to_owned());
5800 t.status = TaskStatus::Blocked;
5801 t.blocked_by = vec!["q1".to_owned()];
5802 t.blocked_from = None;
5803
5804 t.unblock("q1");
5805 assert_eq!(t.status, TaskStatus::Held);
5806 }
5807
5808 #[test]
5809 fn a_pre_schema_4_blocked_record_with_no_hold_evidence_restores_to_queued() {
5810 let mut t = task("legacy record, ordinary dependency block");
5811 t.status = TaskStatus::Blocked;
5812 t.blocked_by = vec!["dep".to_owned()];
5813 t.blocked_from = None;
5814
5815 t.unblock("dep");
5816 assert_eq!(t.status, TaskStatus::Queued);
5817 }
5818
5819 #[test]
5820 fn answering_a_question_is_recorded_and_survives_a_release() {
5821 let mut t = task("asked something");
5822 t.block(vec!["q1".to_owned()], Some("which backend?".to_owned()));
5823 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
5824 t.unblock("q1");
5825 assert_eq!(t.status, TaskStatus::Queued);
5826 assert_eq!(t.answers.len(), 1);
5827 assert_eq!(t.answers[0].answer, "SQLite");
5828
5829 t.release();
5833 assert_eq!(t.answers.len(), 1, "the answer is not lost on release");
5834 }
5835
5836 #[test]
5837 fn resumption_review_branch_requires_unchanged_authored_criteria() {
5838 for source in ["cli", "web"] {
5839 let mut t = task("review old candidate");
5840 t.request_review("candidate-A".into());
5841 t.hold_for_handover(Some("candidate-A".into()), "handover refused".into());
5842 let mut unchanged = t.clone();
5843 unchanged.release_operator(source, None);
5844 assert_eq!(unchanged.review_branch.as_deref(), Some("candidate-A"));
5845 t.edit(
5846 "review approved head".into(),
5847 "Reuse measured PR head B; fix Clippy; review".into(),
5848 )
5849 .unwrap();
5850 t.release_operator(source, None);
5851 assert!(t.review_branch.is_none());
5852 assert!(t.review_instruction.is_none());
5853 let mut legacy = unchanged;
5855 legacy.review_instruction = None;
5856 legacy.hold_for_handover(None, "still checked out".into());
5857 legacy
5858 .edit("new plan".into(), "Reuse measured PR head B".into())
5859 .unwrap();
5860 legacy.release_operator(source, None);
5861 assert!(legacy.review_branch.is_none());
5862 }
5863 }
5864
5865 #[test]
5866 fn a_refused_handover_keeps_the_review_branch_across_release() {
5867 let mut t = task("refused takeover");
5868 t.start("run-1".to_owned());
5869 t.hold_for_handover(Some("magi/eba2/A".to_owned()), "checked out".to_owned());
5870 assert_eq!(t.status, TaskStatus::Held);
5871 assert_eq!(t.attempts, 1);
5872 t.release();
5873 assert_eq!(t.status, TaskStatus::Queued);
5874 assert_eq!(t.attempts, 0);
5875 assert_eq!(t.review_branch.as_deref(), Some("magi/eba2/A"));
5876
5877 t.hold_for_handover(None, "again".to_owned());
5879 t.requeue();
5880 assert!(t.review_branch.is_none());
5881
5882 let mut m = task("manual");
5884 m.review_branch = Some("magi/x/A".to_owned());
5885 m.hold_manual(None);
5886 m.release();
5887 assert!(m.review_branch.is_none());
5888 }
5889
5890 #[test]
5891 fn requesting_review_requeues_the_task_and_remembers_the_branch() {
5892 let mut t = task("blocked run with a surviving branch");
5893 t.start("run-1".to_owned());
5894 t.fail("blocked with major findings", 5);
5895 assert_eq!(t.status, TaskStatus::Failed);
5896
5897 t.request_review("magi/eba2/A".to_owned());
5898 assert_eq!(t.status, TaskStatus::Queued);
5899 assert_eq!(t.attempts, 0);
5900 assert_eq!(t.review_branch.as_deref(), Some("magi/eba2/A"));
5901
5902 t.release();
5904 assert!(t.review_branch.is_none());
5905 }
5906
5907 #[test]
5908 fn conductor_requeue_but_not_an_ordinary_release_forces_a_fresh_start() {
5909 let mut t = task("retry");
5910 t.start("run-1".to_owned());
5911 t.requeue();
5912 assert!(t.fresh_start);
5913
5914 t.release();
5915 assert!(!t.fresh_start);
5916 }
5917
5918 #[test]
5919 fn urgent_only_changes_queued_or_held_and_preserves_settings() {
5920 for status in [
5921 TaskStatus::Queued,
5922 TaskStatus::Held,
5923 TaskStatus::Running,
5924 TaskStatus::Done,
5925 TaskStatus::Failed,
5926 TaskStatus::Blocked,
5927 TaskStatus::Parked,
5928 ] {
5929 let mut t = task("urgent settings");
5930 t.status = status;
5931 t.attempts = 2;
5932 t.hold_reason = Some("waiting".into());
5933 t.priority = 7;
5934 t.interrupt = true;
5935 let before = serde_json::to_value(&t).unwrap();
5936 for urgent in [true, true, false, false] {
5937 let result = t.set_urgent(urgent);
5938 let mut expected = before.clone();
5939 if matches!(status, TaskStatus::Queued | TaskStatus::Held) {
5940 result.unwrap();
5941 expected["urgent"] = urgent.into();
5942 } else {
5943 let error = result.unwrap_err().to_string();
5944 assert!(error.contains(status.as_str()), "{error}");
5945 assert!(error.contains("queued or held"), "{error}");
5946 }
5947 assert_eq!(serde_json::to_value(&t).unwrap(), expected);
5948 }
5949 }
5950 }
5951
5952 #[test]
5953 fn immediate_only_changes_queued_or_held_and_preserves_settings() {
5954 for status in [
5955 TaskStatus::Queued,
5956 TaskStatus::Held,
5957 TaskStatus::Running,
5958 TaskStatus::Done,
5959 TaskStatus::Failed,
5960 TaskStatus::Blocked,
5961 TaskStatus::Parked,
5962 ] {
5963 let mut t = task("immediate settings");
5964 t.status = status;
5965 t.attempts = 2;
5966 t.hold_reason = Some("waiting".into());
5967 t.priority = 7;
5968 t.interrupt = true;
5969 t.urgent = true;
5970 let before = serde_json::to_value(&t).unwrap();
5971 for immediate in [true, true, false, false] {
5972 let result = t.set_immediate(immediate);
5973 let mut expected = before.clone();
5974 if matches!(status, TaskStatus::Queued | TaskStatus::Held) {
5975 result.unwrap();
5976 expected["immediate"] = immediate.into();
5977 } else {
5978 let error = result.unwrap_err().to_string();
5979 assert!(error.contains(status.as_str()), "{error}");
5980 assert!(error.contains("queued or held"), "{error}");
5981 }
5982 assert_eq!(serde_json::to_value(&t).unwrap(), expected);
5983 assert!(t.urgent, "changing immediate must preserve saved urgent");
5984 }
5985 }
5986 }
5987
5988 #[test]
5989 fn a_task_recorded_without_an_immediate_field_still_reads_as_not_immediate() {
5990 let (_dir, q) = queue();
5991 let path = q.path_of("20260101-000000-imm0");
5992 std::fs::create_dir_all(q.root()).unwrap();
5993 std::fs::write(
5994 &path,
5995 serde_json::json!({
5996 "schema": SCHEMA,
5997 "id": "20260101-000000-imm0",
5998 "title": "from before immediate existed",
5999 "instruction": "from before immediate existed",
6000 "repo": ".",
6001 "source": { "kind": "human" },
6002 "status": "queued",
6003 "urgent": true,
6004 "created_at": Timestamp::now().to_string(),
6005 "updated_at": Timestamp::now().to_string(),
6006 })
6007 .to_string(),
6008 )
6009 .unwrap();
6010
6011 let task = q.get("20260101-000000-imm0").expect("must still read");
6012 assert!(!task.immediate);
6013 assert!(task.urgent);
6014 }
6015
6016 #[test]
6017 fn immediate_reuses_urgent_isolation_and_explicit_cache_wins() {
6018 let mut cfg = crate::config::Config::default();
6019 cfg.verify.e2e = vec!["CARGO_TARGET_DIR=/tmp/shared-target cargo test".into()];
6020 let mut t = task("immediate cache");
6021
6022 t.set_immediate(true).unwrap();
6023 assert_eq!(
6024 t.build_cache_override(&cfg),
6025 Some((BuildCache::Isolated, "immediate"))
6026 );
6027
6028 t.set_urgent(true).unwrap();
6030 assert_eq!(
6031 t.build_cache_override(&cfg),
6032 Some((BuildCache::Isolated, "immediate"))
6033 );
6034
6035 t.change_build_cache(Some(BuildCache::Shared)).unwrap();
6037 assert_eq!(
6038 t.build_cache_override(&cfg),
6039 Some((BuildCache::Shared, "task-override"))
6040 );
6041
6042 t.change_build_cache(None).unwrap();
6044 assert_eq!(
6045 t.build_cache_override(&cfg),
6046 Some((BuildCache::Isolated, "immediate"))
6047 );
6048 t.set_immediate(false).unwrap();
6049 assert_eq!(
6050 t.build_cache_override(&cfg),
6051 Some((BuildCache::Isolated, "urgent"))
6052 );
6053
6054 t.set_immediate(true).unwrap();
6056 cfg.verify.e2e = vec!["CARGO_TARGET_DIR=/tmp/shared-target cargo test | tee log".into()];
6057 assert_eq!(t.build_cache_override(&cfg), None);
6058 }
6059
6060 #[test]
6061 fn priority_can_be_changed_while_queued_but_not_while_running() {
6062 let mut t = task("reprioritise me");
6063 t.set_priority(5).unwrap();
6064 assert_eq!(t.priority, 5);
6065
6066 t.start("run-1".to_owned());
6067 let err = t.set_priority(9).unwrap_err().to_string();
6068 assert!(err.contains("running"), "{err}");
6069 assert_eq!(t.priority, 5, "the rejected write must not partially apply");
6070 }
6071
6072 #[test]
6073 fn interrupt_can_be_marked_while_queued_but_not_while_running() {
6074 let mut t = task("interrupt me");
6075 assert!(!t.interrupt, "off unless asked, same as any other task");
6076
6077 t.set_interrupt(true).unwrap();
6078 assert!(t.interrupt);
6079
6080 t.start("run-1".to_owned());
6081 assert!(
6082 !t.interrupt,
6083 "the mark is one-shot: dispatching the task fulfils it, \
6084 whatever the run that follows ends up doing"
6085 );
6086 let err = t.set_interrupt(true).unwrap_err().to_string();
6087 assert!(err.contains("running"), "{err}");
6088 t.set_interrupt(false).unwrap();
6091 assert!(!t.interrupt);
6092 }
6093
6094 #[test]
6098 fn a_failed_run_does_not_leave_the_task_still_marked_to_interrupt() {
6099 let mut t = task("interrupt me");
6100 t.set_interrupt(true).unwrap();
6101 t.start("run-1".to_owned());
6102 t.fail("mock failure", 5);
6103 assert_eq!(t.status, TaskStatus::Failed);
6104 assert!(
6105 !t.interrupt,
6106 "one attempt already spent the mark; a retry is an ordinary \
6107 requeue, not a fresh interrupt request"
6108 );
6109 }
6110
6111 #[test]
6112 fn changing_priority_moves_a_task_ahead_in_the_real_queue_order() {
6113 let (_dir, q) = queue();
6114 let mut a = task("first filed");
6115 let mut b = task("second filed");
6116 a.id = "20260101-000001-aaaa".to_owned();
6117 b.id = "20260101-000002-bbbb".to_owned();
6118 q.put(&mut a).unwrap();
6119 q.put(&mut b).unwrap();
6120
6121 assert_eq!(
6122 q.next_runnable().unwrap().id,
6123 a.id,
6124 "with equal priority the older task goes first, so a burst of \
6125 new work cannot starve it"
6126 );
6127 assert_eq!(
6128 q.list()[0].id,
6129 b.id,
6130 "but the list an operator reads is newest first, the same as \
6131 before priority existed - a's turn to run does not make it the \
6132 newest task"
6133 );
6134
6135 let mut a = q.get(&a.id).unwrap();
6136 a.set_priority(10).unwrap();
6137 q.put(&mut a).unwrap();
6138
6139 assert_eq!(
6140 q.next_runnable().unwrap().id,
6141 a.id,
6142 "a raised priority must be reflected the moment it is saved"
6143 );
6144 assert_eq!(
6148 q.list()[0].id,
6149 a.id,
6150 "the raised task must sort first in the list an operator reads, \
6151 not only in next_runnable's own ordering"
6152 );
6153 }
6154
6155 #[test]
6156 fn editing_replaces_title_and_instruction_but_keeps_identity_and_history() {
6157 let mut t = Task::new(
6158 "old title".to_owned(),
6159 "old instruction".to_owned(),
6160 PathBuf::from("/repo"),
6161 Source::Agent {
6162 run: "20260101-000000-beef".to_owned(),
6163 node: "implement".to_owned(),
6164 },
6165 );
6166 let id = t.id.clone();
6167 let created_at = t.created_at;
6168 t.runs.push("20260101-000000-beef".to_owned());
6169
6170 t.edit("new title".to_owned(), "new instruction".to_owned())
6171 .unwrap();
6172
6173 assert_eq!(t.title, "new title");
6174 assert_eq!(t.instruction, "new instruction");
6175 assert_eq!(t.id, id, "editing must not mint a new id");
6176 assert_eq!(t.created_at, created_at);
6177 assert_eq!(
6178 t.source,
6179 Source::Agent {
6180 run: "20260101-000000-beef".to_owned(),
6181 node: "implement".to_owned(),
6182 },
6183 "editing must not turn agent attribution into human"
6184 );
6185 assert_eq!(t.runs, ["20260101-000000-beef"]);
6186 }
6187
6188 #[test]
6189 fn editing_is_refused_once_a_task_is_running_or_finished() {
6190 let mut running = task("in flight");
6191 running.start("run-1".to_owned());
6192 let err = running
6193 .edit("x".to_owned(), "y".to_owned())
6194 .unwrap_err()
6195 .to_string();
6196 assert!(err.contains("running"), "{err}");
6197
6198 let mut done = task("finished");
6199 done.succeed(completion(&done));
6200 let err = done
6201 .edit("x".to_owned(), "y".to_owned())
6202 .unwrap_err()
6203 .to_string();
6204 assert!(err.contains("done"), "{err}");
6205
6206 let mut queued = task("waiting");
6208 queued.edit("x".to_owned(), "y".to_owned()).unwrap();
6209 let mut held = task("parked");
6210 held.hold_machine(None);
6211 held.edit("x".to_owned(), "y".to_owned()).unwrap();
6212 }
6213
6214 #[test]
6215 fn a_task_recorded_without_a_hold_reason_still_reads_as_none() {
6216 let (_dir, q) = queue();
6217 let path = q.path_of("20260101-000000-aaaa");
6218 std::fs::create_dir_all(q.root()).unwrap();
6219 std::fs::write(
6220 &path,
6221 serde_json::json!({
6222 "schema": SCHEMA,
6223 "id": "20260101-000000-aaaa",
6224 "title": "from before hold reasons existed",
6225 "instruction": "from before hold reasons existed",
6226 "repo": ".",
6227 "source": { "kind": "human" },
6228 "status": "held",
6229 "created_at": Timestamp::now().to_string(),
6230 "updated_at": Timestamp::now().to_string(),
6231 })
6232 .to_string(),
6233 )
6234 .unwrap();
6235
6236 let task = q.get("20260101-000000-aaaa").expect("must still read");
6237 assert!(task.hold_reason.is_none());
6238 assert!(task.operator_held());
6239 }
6240
6241 #[test]
6242 fn a_legacy_reasoned_hold_defaults_to_operator_protection() {
6243 let (_dir, q) = queue();
6244 let path = q.path_of("20260101-000000-bbbb");
6245 std::fs::create_dir_all(q.root()).unwrap();
6246 std::fs::write(
6247 &path,
6248 serde_json::json!({
6249 "schema": 2,
6250 "id": "20260101-000000-bbbb",
6251 "title": "old manual recovery",
6252 "instruction": "old manual recovery",
6253 "repo": ".",
6254 "source": { "kind": "human" },
6255 "status": "held",
6256 "hold_reason": "active manual recovery run20260912-224242-daf5",
6257 "created_at": Timestamp::now().to_string(),
6258 "updated_at": Timestamp::now().to_string(),
6259 })
6260 .to_string(),
6261 )
6262 .unwrap();
6263
6264 let task = q.get("20260101-000000-bbbb").expect("must still read");
6265 assert_eq!(task.hold_source, None);
6266 assert!(task.operator_held());
6267 }
6268
6269 #[test]
6270 fn a_task_recorded_without_a_diagnostic_still_reads_as_none() {
6271 let (_dir, q) = queue();
6272 let path = q.path_of("20260101-000000-aaaa");
6273 std::fs::create_dir_all(q.root()).unwrap();
6274 std::fs::write(
6275 &path,
6276 serde_json::json!({
6277 "schema": SCHEMA,
6278 "id": "20260101-000000-aaaa",
6279 "title": "from before diagnostics existed",
6280 "instruction": "from before diagnostics existed",
6281 "repo": ".",
6282 "source": { "kind": "human" },
6283 "status": "held",
6284 "created_at": Timestamp::now().to_string(),
6285 "updated_at": Timestamp::now().to_string(),
6286 })
6287 .to_string(),
6288 )
6289 .unwrap();
6290
6291 let task = q.get("20260101-000000-aaaa").expect("must still read");
6292 assert!(task.diagnostic.is_none());
6293 }
6294
6295 #[test]
6296 fn a_schema_1_task_with_no_blocking_fields_still_reads() {
6297 let (_dir, q) = queue();
6301 let path = q.path_of("20260101-000000-aaaa");
6302 std::fs::create_dir_all(q.root()).unwrap();
6303 std::fs::write(
6304 &path,
6305 serde_json::json!({
6306 "schema": 1,
6307 "id": "20260101-000000-aaaa",
6308 "title": "from before blocking existed",
6309 "instruction": "from before blocking existed",
6310 "repo": ".",
6311 "source": { "kind": "human" },
6312 "status": "queued",
6313 "created_at": Timestamp::now().to_string(),
6314 "updated_at": Timestamp::now().to_string(),
6315 })
6316 .to_string(),
6317 )
6318 .unwrap();
6319
6320 let task = q.get("20260101-000000-aaaa").expect("must still read");
6321 assert!(task.blocked_by.is_empty());
6322 assert!(task.block_reason.is_none());
6323 assert!(task.answers.is_empty());
6324 assert!(task.review_branch.is_none());
6325 }
6326
6327 #[test]
6328 fn releasing_or_finishing_a_task_clears_its_stale_diagnostic() {
6329 let mut held = task("diagnosed");
6334 held.start("run-1".to_owned());
6335 held.fail("gate red", 1);
6336 held.diagnostic = Some("cargo test failed: ...".to_owned());
6337 assert_eq!(held.status, TaskStatus::Held);
6338
6339 held.release();
6340 assert!(held.diagnostic.is_none());
6341
6342 held.diagnostic = Some("cargo test failed: ...".to_owned());
6343 held.succeed(completion(&held));
6344 assert!(held.diagnostic.is_none());
6345 }
6346
6347 #[test]
6348 fn failing_a_task_always_clears_whatever_diagnostic_it_carried() {
6349 let mut t = task("retried");
6350 t.start("run-1".to_owned());
6351 t.diagnostic = Some("stale evidence from a previous hold".to_owned());
6352 t.fail("unrelated config error", 5);
6353 assert_eq!(t.status, TaskStatus::Failed);
6354 assert!(
6355 t.diagnostic.is_none(),
6356 "fail() must not let an old diagnostic outlive the run that produced it"
6357 );
6358 }
6359
6360 #[test]
6361 fn a_claim_is_exclusive_and_releases_on_drop() {
6362 let (_dir, q) = queue();
6363 let mut t = task("contended");
6364 q.put(&mut t).unwrap();
6365
6366 let held = q.claim(&t.id).unwrap();
6367 assert!(
6368 q.claim(&t.id).is_err(),
6369 "two daemons must not drive one task into two runs"
6370 );
6371 drop(held);
6372 assert!(q.claim(&t.id).is_ok(), "a released claim is reclaimable");
6373 }
6374
6375 #[test]
6376 fn a_round_trip_survives_disk() {
6377 let (_dir, q) = queue();
6378 let mut t = Task::new(
6379 "titled".to_owned(),
6380 "body".to_owned(),
6381 PathBuf::from("/repo"),
6382 Source::Agent {
6383 run: "20260101-000000-beef".to_owned(),
6384 node: "implement".to_owned(),
6385 },
6386 );
6387 t.priority = 3;
6388 q.put(&mut t).unwrap();
6389
6390 let back = q.get(&t.id).unwrap();
6391 assert_eq!(back.id, t.id);
6392 assert_eq!(back.priority, 3);
6393 assert_eq!(back.source.label(), "implement@beef");
6394 assert_eq!(q.get(t.short()).unwrap().id, t.id);
6396 }
6397
6398 #[test]
6399 fn an_unreadable_task_does_not_take_the_queue_down() {
6400 let (_dir, q) = queue();
6401 let mut t = task("fine");
6402 q.put(&mut t).unwrap();
6403 std::fs::write(q.root().join("broken.json"), "{ not json").unwrap();
6404
6405 let listed = q.list();
6406 assert_eq!(listed.len(), 1, "the readable task still lists");
6407 assert_eq!(listed[0].id, t.id);
6408 }
6409
6410 #[test]
6411 fn a_task_recorded_without_a_solo_field_still_reads_as_not_solo() {
6412 let (_dir, q) = queue();
6413 let path = q.path_of("20260101-000000-aaaa");
6414 std::fs::create_dir_all(q.root()).unwrap();
6415 std::fs::write(
6416 &path,
6417 serde_json::json!({
6418 "schema": SCHEMA,
6419 "id": "20260101-000000-aaaa",
6420 "title": "from before solo existed",
6421 "instruction": "from before solo existed",
6422 "repo": ".",
6423 "source": { "kind": "human" },
6424 "status": "queued",
6425 "created_at": Timestamp::now().to_string(),
6426 "updated_at": Timestamp::now().to_string(),
6427 })
6428 .to_string(),
6429 )
6430 .unwrap();
6431
6432 let task = q.get("20260101-000000-aaaa").expect("must still read");
6433 assert!(!task.solo, "a queue file with no `solo` field means false");
6434 }
6435
6436 #[test]
6437 fn a_task_recorded_without_an_urgent_field_still_reads_as_not_urgent() {
6438 let (_dir, q) = queue();
6439 let path = q.path_of("20260101-000000-bbbb");
6440 std::fs::create_dir_all(q.root()).unwrap();
6441 std::fs::write(
6442 &path,
6443 serde_json::json!({
6444 "schema": SCHEMA,
6445 "id": "20260101-000000-bbbb",
6446 "title": "from before urgent existed",
6447 "instruction": "from before urgent existed",
6448 "repo": ".",
6449 "source": { "kind": "human" },
6450 "status": "queued",
6451 "created_at": Timestamp::now().to_string(),
6452 "updated_at": Timestamp::now().to_string(),
6453 })
6454 .to_string(),
6455 )
6456 .unwrap();
6457
6458 let task = q.get("20260101-000000-bbbb").expect("must still read");
6459 assert!(
6460 !task.urgent,
6461 "a queue file with no `urgent` field means false, same as `solo`"
6462 );
6463 }
6464
6465 #[test]
6466 fn a_task_from_a_future_schema_is_refused_rather_than_guessed_at() {
6467 let (_dir, q) = queue();
6468 let mut t = task("from the future");
6469 q.put(&mut t).unwrap();
6470 let path = q.path_of(&t.id);
6471 let body = std::fs::read_to_string(&path)
6472 .unwrap()
6473 .replace(&format!("\"schema\": {SCHEMA}"), "\"schema\": 99");
6474 std::fs::write(&path, body).unwrap();
6475
6476 let err = q.get(&t.id).unwrap_err().to_string();
6477 assert!(err.contains("schema 99"), "{err}");
6478 }
6479
6480 #[test]
6481 fn revision_moves_when_the_queue_changes() {
6482 let (_dir, q) = queue();
6483 assert_eq!(q.revision(), 0, "an empty queue has no revision");
6484 let mut t = task("first");
6485 q.put(&mut t).unwrap();
6486 assert!(q.revision() > 0, "a written task moves the revision");
6487 }
6488
6489 #[test]
6490 fn revision_moves_when_deleting_an_older_task() {
6491 let (dir, q) = queue();
6492 let questions = Questions::at(dir.path().join("questions"));
6493 let mut t1 = task("older");
6494 q.put(&mut t1).unwrap();
6495 std::thread::sleep(std::time::Duration::from_millis(10));
6497 let mut t2 = task("newer");
6498 q.put(&mut t2).unwrap();
6499
6500 let rev_before = q.revision();
6501 q.remove(&t1.id, false, &questions).unwrap();
6502 let rev_after = q.revision();
6503
6504 assert_ne!(
6505 rev_before, rev_after,
6506 "deleting an older task must change the revision so other clients see the deletion"
6507 );
6508 }
6509
6510 #[test]
6511 fn removing_a_task_takes_it_out_of_the_listing() {
6512 let (dir, q) = queue();
6513 let questions = Questions::at(dir.path().join("questions"));
6514 let mut t = task("delete me");
6515 q.put(&mut t).unwrap();
6516 let removed = q.remove(t.short(), false, &questions).unwrap();
6517 assert_eq!(removed.id, t.id, "a prefix resolves before deleting");
6518 assert!(removed.released.is_empty() && removed.still_blocked.is_empty());
6519 assert!(q.list().is_empty());
6520 assert!(
6521 q.remove(&t.id, false, &questions).is_err(),
6522 "removing twice is an error"
6523 );
6524 }
6525
6526 #[test]
6527 fn removing_a_task_takes_its_stale_lock_with_it() {
6528 let (dir, q) = queue();
6529 let questions = Questions::at(dir.path().join("questions"));
6530 let mut t = task("interrupted");
6531 q.put(&mut t).unwrap();
6532
6533 let claim = q.claim(&t.id).unwrap();
6536 std::mem::forget(claim);
6537 assert!(
6538 q.claim(&t.id).is_err(),
6539 "the orphaned lock is what makes the task look claimed"
6540 );
6541
6542 let err = q.remove(&t.id, true, &questions).unwrap_err().to_string();
6544 assert!(err.contains("live daemon"), "{err}");
6545 assert!(q.get(&t.id).is_ok(), "a refused delete keeps the task");
6546
6547 q.remove(&t.id, false, &questions).unwrap();
6549 assert!(q.list().is_empty());
6550 let mut again = task("interrupted");
6551 again.id = t.id.clone();
6552 q.put(&mut again).unwrap();
6553 assert!(
6554 q.claim(&t.id).is_ok(),
6555 "a task that comes back must be claimable, which a left-behind lock would prevent"
6556 );
6557 }
6558
6559 fn notices_of(dir: &Path) -> Vec<crate::notices::Notice> {
6560 crate::notices::Notices::at(dir.join("notifications")).list()
6561 }
6562
6563 #[test]
6564 fn removing_a_sole_dependency_releases_the_dependent_without_a_hold() {
6565 let (dir, q) = queue();
6566 let questions = Questions::at(dir.path().join("questions"));
6567 let mut dep = task("dependency");
6568 q.put(&mut dep).unwrap();
6569 let mut blocked = task("waiting");
6570 blocked.block(vec![dep.id.clone()], Some("waits".to_owned()));
6571 q.put(&mut blocked).unwrap();
6572
6573 let removed = q.remove(&dep.id, false, &questions).unwrap();
6574 assert_eq!(removed.released, [blocked.id.clone()]);
6575 assert!(removed.still_blocked.is_empty());
6576
6577 let after = q.get(&blocked.id).unwrap();
6578 assert_eq!(after.status, TaskStatus::Queued);
6579 assert!(after.blocked_by.is_empty());
6580 assert!(after.block_reason.is_none());
6581 let notes = notices_of(dir.path());
6582 assert_eq!(notes.len(), 1, "{notes:?}");
6583 assert_eq!(notes[0].severity, crate::notices::Severity::Info);
6584 assert_eq!(
6585 notes[0].link,
6586 Some(crate::notices::Link::Task {
6587 id: blocked.id.clone(),
6588 })
6589 );
6590 }
6591
6592 #[test]
6593 fn removing_one_of_two_dependencies_keeps_the_other() {
6594 let (dir, q) = queue();
6595 let questions = Questions::at(dir.path().join("questions"));
6596 let mut dep = task("dependency");
6597 q.put(&mut dep).unwrap();
6598 let mut other = task("other");
6599 q.put(&mut other).unwrap();
6600 let mut blocked = task("waiting");
6601 blocked.block(
6602 vec![dep.id.clone(), other.id.clone()],
6603 Some("waits on both".to_owned()),
6604 );
6605 q.put(&mut blocked).unwrap();
6606
6607 let removed = q.remove(&dep.id, false, &questions).unwrap();
6608 assert!(removed.released.is_empty());
6609 assert_eq!(removed.still_blocked, [blocked.id.clone()]);
6610
6611 let after = q.get(&blocked.id).unwrap();
6612 assert_eq!(after.status, TaskStatus::Blocked);
6613 assert_eq!(after.blocked_by, [other.id.clone()]);
6614 assert!(missing_blockers(&q, &questions, &after.blocked_by).is_empty());
6617 }
6618
6619 #[test]
6620 fn a_dependency_deleted_before_its_dependents_were_rewritten_is_released_later() {
6621 let (dir, q) = queue();
6622 let questions = Questions::at(dir.path().join("questions"));
6623 let mut dep = task("dependency");
6624 q.put(&mut dep).unwrap();
6625 let mut blocked = task("waiting");
6626 blocked.block(vec![dep.id.clone()], None);
6627 q.put(&mut blocked).unwrap();
6628
6629 let claim = q.claim(&blocked.id).unwrap();
6631 let removed = q.remove(&dep.id, false, &questions).unwrap();
6632 assert!(removed.released.is_empty());
6633 drop(claim);
6634
6635 let mut task = q.get(&blocked.id).unwrap();
6636 assert_eq!(task.status, TaskStatus::Blocked);
6637 assert!(missing_blockers(&q, &questions, &task.blocked_by).is_empty());
6638 assert_eq!(
6639 q.apply_deleted_blockers(&mut task, &questions),
6640 [dep.id.clone()]
6641 );
6642 assert_eq!(task.status, TaskStatus::Queued);
6643 }
6644
6645 #[test]
6646 fn dependency_resolution_short_deleted_reference_releases_only_its_waiters() {
6647 let (dir, q) = queue();
6648 let questions = Questions::at(dir.path().join("questions"));
6649 let mut dep = task("dependency");
6650 dep.id = "20261013-193611-ca5b".into();
6651 q.put(&mut dep).unwrap();
6652 let mut waiting = task("waiting");
6653 waiting.block(vec!["ca5b".into()], None);
6654 q.put(&mut waiting).unwrap();
6655 q.remove(&dep.id, false, &questions).unwrap();
6656 assert_eq!(q.get(&waiting.id).unwrap().status, TaskStatus::Queued);
6657 assert_eq!(
6658 dependency(&q, &questions, "ca5b"),
6659 Dependency::Deleted(dep.id)
6660 );
6661 }
6662
6663 #[test]
6664 fn dependency_resolution_preserves_cross_store_ambiguity_and_exact_ids() {
6665 let (dir, queue) = queue();
6666 let questions = Questions::at(dir.path().join("questions"));
6667 let mut dep = task("dependency");
6668 dep.id = "20261013-193611-ca5b".into();
6669 queue.put(&mut dep).unwrap();
6670 std::fs::create_dir_all(questions.root()).unwrap();
6671 let question_id = "20261014-193611-ca5b";
6672 std::fs::write(questions.path_of(question_id), "unreadable question").unwrap();
6673 assert_eq!(questions.resolve_id("ca5b").unwrap(), question_id);
6674 assert_eq!(
6675 dependency(&queue, &questions, "ca5b"),
6676 Dependency::Ambiguous
6677 );
6678 assert_eq!(
6679 dependency(&queue, &questions, &dep.id),
6680 Dependency::Task(dep.id)
6681 );
6682 assert_eq!(
6683 dependency(&queue, &questions, question_id),
6684 Dependency::Question(question_id.into())
6685 );
6686 assert_eq!(
6687 dependency(&queue, &questions, "missing"),
6688 Dependency::Missing
6689 );
6690 }
6691
6692 #[test]
6693 fn dependency_resolution_directory_errors_are_unknown_not_missing() {
6694 let dir = tempfile::tempdir().unwrap();
6695 let q = Queue::at(dir.path().join("not-a-directory"));
6696 std::fs::write(q.root(), "file").unwrap();
6697 let questions = Questions::at(dir.path().join("questions"));
6698 assert_eq!(dependency(&q, &questions, "ca5b"), Dependency::Unknown);
6699 assert!(missing_blockers(&q, &questions, &["ca5b".into()]).is_empty());
6700 }
6701
6702 #[test]
6703 fn a_dependency_without_a_tombstone_is_still_missing() {
6704 let (dir, q) = queue();
6705 let questions = Questions::at(dir.path().join("questions"));
6706 let mut dep = task("dependency");
6707 q.put(&mut dep).unwrap();
6708 std::fs::remove_file(q.path_of(&dep.id)).unwrap();
6709 assert_eq!(
6710 missing_blockers(&q, &questions, std::slice::from_ref(&dep.id)),
6711 [dep.id.clone()]
6712 );
6713 assert!(deleted_blockers(&q, &questions, std::slice::from_ref(&dep.id)).is_empty());
6714 }
6715
6716 #[test]
6717 fn a_held_dependent_is_left_alone_by_a_dependency_deletion() {
6718 let mut t = task("held");
6719 t.hold_machine(Some("because".to_owned()));
6720 t.blocked_by = vec!["gone".to_owned()];
6721 assert!(!t.dependency_deleted("gone"));
6722 assert_eq!(t.status, TaskStatus::Held);
6723 }
6724
6725 #[test]
6726 fn a_failed_record_removal_takes_the_tombstone_back() {
6727 let (_dir, q) = queue();
6728 let mut t = task("stays");
6729 q.put(&mut t).unwrap();
6730 q.write_tombstone(&t.id).unwrap();
6731 let err = q.remove_record_with_attachments(&t.id, |_| Err(std::io::Error::other("nope")));
6732 assert!(err.is_err());
6733 assert!(!q.was_deleted(&t.id));
6736 }
6737
6738 fn source_file(dir: &Path, name: &str, body: &str) -> PathBuf {
6739 let p = dir.join(name);
6740 std::fs::write(&p, body).unwrap();
6741 p
6742 }
6743
6744 #[test]
6745 fn an_attachment_copy_survives_deleting_its_source() {
6746 let (dir, q) = queue();
6747 let src = source_file(dir.path(), "shot.png", "pixels");
6748 let mut t = task("with a picture");
6749 let names = q.attach(&mut t, std::slice::from_ref(&src)).unwrap();
6750 q.put(&mut t).unwrap();
6751 std::fs::remove_file(&src).unwrap();
6752 assert_eq!(names, ["shot.png"]);
6753 let loaded = q.get(&t.id).unwrap();
6754 let paths = q.attachment_paths(&loaded);
6755 assert_eq!(paths.len(), 1);
6756 assert_eq!(std::fs::read_to_string(&paths[0]).unwrap(), "pixels");
6757 }
6758
6759 #[test]
6760 fn attachment_names_that_could_traverse_or_are_odd_are_refused() {
6761 let (dir, q) = queue();
6762 let mut t = task("bad names");
6763 for name in ["a..b.png", ".hidden", "with space.png", "-x.png"] {
6764 let src = source_file(dir.path(), name, "x");
6765 assert!(
6766 q.attach(&mut t, &[src]).is_err(),
6767 "`{name}` must be refused"
6768 );
6769 }
6770 assert!(!crate::ask::valid_asset_name("C:foo.png"));
6774 #[cfg(not(windows))]
6775 {
6776 let src = source_file(dir.path(), "C:foo.png", "x");
6777 assert!(q.attach(&mut t, &[src]).is_err());
6778 }
6779 let long = format!("{}.png", "a".repeat(70));
6780 let src = source_file(dir.path(), &long, "x");
6781 assert!(q.attach(&mut t, &[src]).is_err());
6782 assert!(t.attachments.is_empty());
6783 assert!(!q.attachments_dir(&t.id).exists());
6784 }
6785
6786 #[test]
6787 fn a_taken_attachment_name_is_numbered_not_overwritten() {
6788 let (dir, q) = queue();
6789 let a = source_file(dir.path(), "shot.png", "one");
6790 let sub = dir.path().join("other");
6791 std::fs::create_dir_all(&sub).unwrap();
6792 let b = source_file(&sub, "shot.png", "two");
6793 let mut t = task("collision");
6794 q.attach(&mut t, &[a]).unwrap();
6795 q.attach(&mut t, &[b]).unwrap();
6796 assert_eq!(t.attachments, ["shot.png", "shot-2.png"]);
6797 let paths = q.attachment_paths(&t);
6798 assert_eq!(std::fs::read_to_string(&paths[0]).unwrap(), "one");
6799 assert_eq!(std::fs::read_to_string(&paths[1]).unwrap(), "two");
6800 }
6801
6802 #[test]
6803 fn a_renumbered_name_stays_inside_the_length_bound() {
6804 let (dir, q) = queue();
6805 let name = format!("{}.png", "a".repeat(60));
6806 assert_eq!(name.len(), 64);
6807 let a = source_file(dir.path(), &name, "one");
6808 let sub = dir.path().join("other");
6809 std::fs::create_dir_all(&sub).unwrap();
6810 let b = source_file(&sub, &name, "two");
6811 let mut t = task("long");
6812 q.attach(&mut t, &[a, b]).unwrap();
6813 assert_eq!(t.attachments.len(), 2);
6814 assert!(
6815 t.attachments
6816 .iter()
6817 .all(|n| crate::ask::valid_asset_name(n))
6818 );
6819 assert!(t.attachments[1].ends_with("-2.png"));
6820 }
6821
6822 #[test]
6823 fn a_failed_attach_keeps_existing_attachments_and_leaves_no_partial_copy() {
6824 let (dir, q) = queue();
6825 let good = source_file(dir.path(), "good.png", "ok");
6826 let mut t = task("partial");
6827 q.attach(&mut t, &[good]).unwrap();
6828 let more = source_file(dir.path(), "more.png", "ok");
6829 let missing = dir.path().join("missing.png");
6830 assert!(q.attach(&mut t, &[more, missing]).is_err());
6831 assert_eq!(t.attachments, ["good.png"]);
6832 let on_disk: Vec<_> = std::fs::read_dir(q.attachments_dir(&t.id))
6833 .unwrap()
6834 .flatten()
6835 .collect();
6836 assert_eq!(on_disk.len(), 1);
6837 }
6838
6839 fn block_put(q: &Queue, t: &Task) -> PathBuf {
6841 let tmp = q.path_of(&t.id).with_extension("json.tmp");
6842 std::fs::create_dir_all(&tmp).unwrap();
6843 tmp
6844 }
6845
6846 #[test]
6847 fn a_failed_put_leaves_no_new_attachment_directory() {
6848 let (dir, q) = queue();
6849 let mut t = task("fresh");
6850 let tmp = block_put(&q, &t);
6851 let src = source_file(dir.path(), "shot.png", "x");
6852 assert!(q.attach_and_put(&mut t, &[src]).is_err());
6853 assert!(t.attachments.is_empty());
6854 assert!(!q.attachments_dir(&t.id).exists());
6855 assert!(!q.path_of(&t.id).exists());
6856 std::fs::remove_dir(tmp).unwrap();
6857 }
6858
6859 #[test]
6860 fn a_failed_put_removes_only_the_copy_it_just_made() {
6861 let (dir, q) = queue();
6862 let mut t = task("edited");
6863 let first = source_file(dir.path(), "first.png", "1");
6864 q.attach_and_put(&mut t, &[first]).unwrap();
6865 block_put(&q, &t);
6866 let second = source_file(dir.path(), "second.png", "2");
6867 assert!(q.attach_and_put(&mut t, &[second]).is_err());
6868 assert_eq!(t.attachments, ["first.png"]);
6869 let on_disk: Vec<_> = std::fs::read_dir(q.attachments_dir(&t.id))
6870 .unwrap()
6871 .flatten()
6872 .map(|e| e.file_name().to_string_lossy().into_owned())
6873 .collect();
6874 assert_eq!(on_disk, ["first.png"]);
6875 assert_eq!(q.get(&t.id).unwrap().attachments, ["first.png"]);
6876 }
6877
6878 #[test]
6879 fn a_leftover_removing_directory_is_swept_by_the_next_removal() {
6880 let (dir, q) = queue();
6881 let questions = Questions::at(dir.path().join("questions"));
6882 let gone = task("gone");
6883 let mut other = task("other");
6884 let mut live = task("live");
6885 q.put(&mut other).unwrap();
6886 q.put(&mut live).unwrap();
6887 let orphan = q.root.join(format!("{}.attachments.removing", gone.id));
6890 std::fs::create_dir_all(&orphan).unwrap();
6891 std::fs::write(orphan.join("shot.png"), "x").unwrap();
6892 let busy = q.root.join(format!("{}.attachments.removing", live.id));
6895 std::fs::create_dir_all(&busy).unwrap();
6896
6897 q.remove(&other.id, false, &questions).unwrap();
6898 assert!(!orphan.exists(), "an orphan is swept");
6899 assert!(busy.exists(), "a removal in progress is left alone");
6900 }
6901
6902 #[test]
6903 fn a_blocked_aside_rename_fails_the_removal_and_loses_nothing() {
6904 let (dir, q) = queue();
6905 let questions = Questions::at(dir.path().join("questions"));
6906 let mut t = task("stuck");
6907 let src = source_file(dir.path(), "shot.png", "x");
6908 q.attach_and_put(&mut t, &[src]).unwrap();
6909 let aside = q.root.join(format!("{}.attachments.removing", t.id));
6912 std::fs::create_dir_all(&aside).unwrap();
6913 std::fs::write(aside.join("old.png"), "o").unwrap();
6914 assert!(q.remove(&t.id, false, &questions).is_err());
6915 assert!(q.path_of(&t.id).exists());
6916 assert!(q.attachments_dir(&t.id).join("shot.png").is_file());
6917 }
6918
6919 #[test]
6920 fn a_failed_record_removal_puts_the_attachments_back() {
6921 let (dir, q) = queue();
6922 let mut t = task("rollback");
6923 let src = source_file(dir.path(), "shot.png", "x");
6924 q.attach_and_put(&mut t, &[src]).unwrap();
6925 let err = q
6926 .remove_record_with_attachments(&t.id, |_| {
6927 Err(std::io::Error::other("injected failure"))
6928 })
6929 .unwrap_err();
6930 assert!(format!("{err:#}").contains("injected failure"));
6931 assert!(q.path_of(&t.id).exists());
6932 assert!(q.attachments_dir(&t.id).join("shot.png").is_file());
6933 assert!(
6934 !q.root
6935 .join(format!("{}.attachments.removing", t.id))
6936 .exists()
6937 );
6938 }
6939
6940 #[test]
6941 fn editing_a_task_keeps_its_attachments() {
6942 let (dir, q) = queue();
6943 let src = source_file(dir.path(), "shot.png", "x");
6944 let mut t = task("editable");
6945 q.attach(&mut t, &[src]).unwrap();
6946 t.edit("new".to_owned(), "new text".to_owned()).unwrap();
6947 q.put(&mut t).unwrap();
6948 assert_eq!(q.get(&t.id).unwrap().attachments, ["shot.png"]);
6949 }
6950
6951 #[test]
6952 fn removing_a_task_deletes_its_attachments() {
6953 let (dir, q) = queue();
6954 let questions = Questions::at(dir.path().join("questions"));
6955 let src = source_file(dir.path(), "shot.png", "x");
6956 let mut t = task("doomed");
6957 q.attach(&mut t, &[src]).unwrap();
6958 q.put(&mut t).unwrap();
6959 assert!(q.attachments_dir(&t.id).is_dir());
6960 q.remove(&t.id, false, &questions).unwrap();
6961 assert!(!q.attachments_dir(&t.id).exists());
6962 assert!(q.list().is_empty());
6963 }
6964
6965 #[test]
6966 fn a_task_written_before_attachments_still_reads() {
6967 let (_dir, q) = queue();
6968 let mut t = task("old");
6969 q.put(&mut t).unwrap();
6970 let path = q.path_of(&t.id);
6971 let mut v: serde_json::Value =
6972 serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
6973 v.as_object_mut().unwrap().remove("attachments");
6974 std::fs::write(&path, v.to_string()).unwrap();
6975 assert!(q.get(&t.id).unwrap().attachments.is_empty());
6976 }
6977
6978 #[test]
6979 fn attachment_paths_are_absolute_even_when_the_root_is_relative() {
6980 let q = Queue::at(PathBuf::from("relative-queue"));
6981 let mut t = task("rel");
6982 t.attachments.push("shot.png".to_owned());
6983 let paths = q.attachment_paths(&t);
6984 assert!(paths[0].is_absolute(), "{}", paths[0].display());
6985 assert!(paths[0].ends_with(format!("{}.attachments/shot.png", t.id)));
6986 }
6987
6988 fn upgrade_parked(id: &str, started: &str) -> Task {
6989 let mut t = task(id);
6990 t.id = id.into();
6991 t.start(format!("run-{id}"));
6992 t.park("upgrade");
6993 t.record_pass_at(
6994 &format!("run-{id}"),
6995 0,
6996 Some(started.parse().unwrap()),
6997 1,
6998 Some(crate::run::ParkCause::Upgrade {
6999 from: "old".into(),
7000 to: None,
7001 }),
7002 );
7003 t
7004 }
7005
7006 #[test]
7007 fn upgrade_resume_order_follows_dispatch_claim_not_graph_start() {
7008 let stamp = |id: &str, dispatched: &str, started: &str| {
7010 let mut t = task(id);
7011 t.id = id.into();
7012 t.start(format!("run-{id}"));
7013 t.park("upgrade");
7014 t.dispatched_at = Some(dispatched.parse().unwrap());
7015 t.record_pass_at(
7016 &format!("run-{id}"),
7017 0,
7018 Some(started.parse().unwrap()),
7019 1,
7020 Some(crate::run::ParkCause::Upgrade {
7021 from: "old".into(),
7022 to: None,
7023 }),
7024 );
7025 t
7026 };
7027 let a = stamp("a", "2026-10-22T00:00:01Z", "2026-10-22T00:00:09Z");
7028 let b = stamp("b", "2026-10-22T00:00:02Z", "2026-10-22T00:00:03Z");
7029 assert!(dispatch_order(&a, &b).is_lt());
7030 }
7031
7032 #[test]
7033 fn upgrade_resume_order_survives_queue_reload_and_reversed_settlement() {
7034 let (_dir, q) = queue();
7035 let mut later = upgrade_parked("later", "2026-10-22T00:00:02Z");
7036 let mut earlier = upgrade_parked("earlier", "2026-10-22T00:00:01Z");
7037 earlier.priority = -10;
7038 let mut fresh = task("fresh");
7039 fresh.id = "newer".into();
7040 fresh.priority = 100;
7041 for t in [&mut fresh, &mut later, &mut earlier] {
7042 q.put(t).unwrap();
7043 }
7044 let reloaded = Queue::at(q.root().to_owned());
7045 let mut tasks = reloaded.list();
7046 tasks.sort_unstable_by(dispatch_order);
7047 assert_eq!(
7048 tasks.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
7049 vec!["earlier", "later", "newer"]
7050 );
7051 assert_eq!(reloaded.next_runnable().unwrap().id, "earlier");
7052 assert_eq!(reloaded.get("earlier").unwrap().attempts, 0);
7053 }
7054
7055 #[test]
7056 fn upgrade_resume_legacy_order_uses_settlement_and_id() {
7057 let mut a = upgrade_parked("a", "2026-10-22T00:00:02Z");
7058 let mut b = upgrade_parked("b", "2026-10-22T00:00:01Z");
7059 for t in [&mut a, &mut b] {
7060 let mut value = serde_json::to_value(&*t).unwrap();
7061 value["passes"][0]
7062 .as_object_mut()
7063 .unwrap()
7064 .remove("started_at");
7065 *t = serde_json::from_value(value).unwrap();
7066 }
7067 assert!(dispatch_order(&a, &b).is_lt());
7068 b.passes[0].settled_at = a.passes[0].settled_at;
7069 assert!(dispatch_order(&a, &b).is_lt());
7070 }
7071
7072 #[test]
7073 fn upgrade_resume_key_excludes_other_parks_and_explicit_task_changes() {
7074 let original = upgrade_parked("a", "2026-10-22T00:00:01Z");
7075 assert!(original.upgrade_resume_key().is_some());
7076 for cause in [
7077 crate::run::ParkCause::Operator,
7078 crate::run::ParkCause::Question,
7079 crate::run::ParkCause::Interrupt {
7080 reason: "interrupt".into(),
7081 },
7082 crate::run::ParkCause::Unspecified,
7083 ] {
7084 let mut t = original.clone();
7085 t.passes[0].parked = Some(cause);
7086 assert!(t.upgrade_resume_key().is_none());
7087 let mut fresh = task("fresh");
7088 fresh.priority = 1;
7089 assert!(dispatch_order(&fresh, &t).is_lt());
7090 }
7091 let mut t = original.clone();
7092 t.release();
7093 assert!(t.upgrade_resume_key().is_none());
7094 t.edit("edited".into(), "new instruction".into()).unwrap();
7095 assert!(t.upgrade_resume_key().is_none());
7096 let mut t = original.clone();
7097 t.requeue();
7098 t.status = TaskStatus::Parked;
7099 assert!(t.upgrade_resume_key().is_none());
7100 let mut t = original.clone();
7101 t.start("different-run".into());
7102 t.park("no upgrade");
7103 assert!(t.upgrade_resume_key().is_none());
7104 }
7105
7106 #[test]
7107 fn explicitly_resumed_older_run_becomes_current_without_duplicate_history() {
7108 let dir = tempfile::tempdir().unwrap();
7109 let q = Queue::at(dir.path().join("queue"));
7110 let mut t = task("resume");
7111 t.start("A".into());
7112 t.record_pass("A", 0, 1, None);
7113 t.start("B".into());
7114 q.put(&mut t).unwrap();
7115 assert_eq!(t.runs, vec!["A", "B"]);
7116 t.start("A".into());
7117 t.record_pass("A", 1, 3, None);
7118 q.put(&mut t).unwrap();
7119 let saved = q.get(&t.id).unwrap();
7120 assert_eq!(saved.runs, vec!["B", "A"]);
7121 assert_eq!(saved.runs.last().map(String::as_str), Some("A"));
7122 assert_eq!(saved.attempts, 3);
7123 assert_eq!(saved.passes.len(), 2);
7124 assert_eq!(saved.passes[0].run, "A");
7125 assert_eq!(saved.passes[1].run, "A");
7126 }
7127
7128 #[test]
7129 fn repeated_start_records_one_run_and_separate_passes() {
7130 let mut t = task("resume");
7131 t.start("same-run".into());
7132 t.record_pass("same-run", 0, 1, None);
7133 t.start("same-run".into());
7134 t.record_pass("same-run", 1, 2, None);
7135 assert_eq!(t.runs, vec!["same-run"]);
7136 assert_eq!(t.attempts, 2);
7137 assert_eq!(t.passes.len(), 2);
7138 }
7139
7140 #[test]
7141 fn link_run_adds_a_run_once_and_touches_nothing_else() {
7142 let dir = tempfile::tempdir().unwrap();
7143 let queue = Queue::at(dir.path().join("queue"));
7144 let mut t = Task::new(
7145 "t".to_owned(),
7146 "do it".to_owned(),
7147 PathBuf::from("."),
7148 Source::Human,
7149 );
7150 queue.put(&mut t).unwrap();
7151 let before = queue.get(&t.id).unwrap();
7152
7153 let linked = queue.link_run(&t.id[..4], "20260930-092817-ec34").unwrap();
7154 assert_eq!(linked.runs, vec!["20260930-092817-ec34".to_owned()]);
7155 assert_eq!(linked.status, before.status);
7156 assert_eq!(linked.attempts, before.attempts);
7157 assert_eq!(linked.interrupt, before.interrupt);
7158
7159 let again = queue.link_run(&t.id, "20260930-092817-ec34").unwrap();
7160 assert_eq!(again.runs.len(), 1, "linking twice must not duplicate");
7161 assert_eq!(queue.get(&t.id).unwrap().runs.len(), 1);
7162 assert!(queue.link_run("no-such-task", "r").is_err());
7163 }
7164
7165 #[test]
7166 fn put_keeps_a_run_linked_after_the_writer_took_its_snapshot() {
7167 let dir = tempfile::tempdir().unwrap();
7168 let queue = Queue::at(dir.path().join("queue"));
7169 let mut t = Task::new(
7170 "t".to_owned(),
7171 "do it".to_owned(),
7172 PathBuf::from("."),
7173 Source::Human,
7174 );
7175 queue.put(&mut t).unwrap();
7176 let mut snapshot = queue.get(&t.id).unwrap();
7178 queue.link_run(&t.id, "20260930-092817-ec34").unwrap();
7179
7180 snapshot.start("20260930-000000-aaaa".to_owned());
7181 queue.put(&mut snapshot).unwrap();
7182
7183 let stored = queue.get(&t.id).unwrap();
7184 assert!(stored.runs.contains(&"20260930-092817-ec34".to_owned()));
7185 assert!(stored.runs.contains(&"20260930-000000-aaaa".to_owned()));
7186 assert_eq!(stored.attempts, 1);
7187 }
7188
7189 #[test]
7190 fn concurrent_links_and_daemon_saves_lose_nothing() {
7191 let dir = tempfile::tempdir().unwrap();
7192 let queue = Queue::at(dir.path().join("queue"));
7193 let mut t = Task::new(
7194 "t".to_owned(),
7195 "do it".to_owned(),
7196 PathBuf::from("."),
7197 Source::Human,
7198 );
7199 queue.put(&mut t).unwrap();
7200 let id = t.id.clone();
7201
7202 let linkers: Vec<_> = (0..4)
7203 .map(|n| {
7204 let (queue, id) = (queue.clone(), id.clone());
7205 std::thread::spawn(move || {
7206 for k in 0..10 {
7207 queue
7208 .link_run(&id, &format!("20260930-00000{n}-l{k:03}"))
7209 .unwrap();
7210 }
7211 })
7212 })
7213 .collect();
7214 let mut mine = queue.get(&id).unwrap();
7217 for k in 0..10 {
7218 mine.start(format!("20260930-000009-d{k:03}"));
7219 queue.put(&mut mine).unwrap();
7220 }
7221 for l in linkers {
7222 l.join().unwrap();
7223 }
7224
7225 let stored = queue.get(&id).unwrap();
7226 assert_eq!(stored.runs.len(), 50, "{:?}", stored.runs);
7227 assert_eq!(
7228 stored.attempts, 10,
7229 "linking never rewinds the daemon's work"
7230 );
7231 }
7232
7233 fn age_lock(path: &Path) {
7234 let f = std::fs::OpenOptions::new().write(true).open(path).unwrap();
7235 f.set_modified(std::time::SystemTime::now() - std::time::Duration::from_secs(60))
7236 .unwrap();
7237 }
7238
7239 #[test]
7240 fn concurrent_stale_takeover_yields_one_holder() {
7241 use std::sync::atomic::{AtomicUsize, Ordering};
7242 use std::sync::{Arc, Barrier};
7243 for _ in 0..5 {
7244 let dir = tempfile::tempdir().unwrap();
7245 let q = Queue::at(dir.path().to_path_buf());
7246 let lock = dir.path().join("t.write-lock");
7247 std::fs::write(&lock, "dead-0000").unwrap();
7248 age_lock(&lock);
7249 let n = 6;
7250 let barrier = Arc::new(Barrier::new(n));
7251 let (now, max) = (Arc::new(AtomicUsize::new(0)), Arc::new(AtomicUsize::new(0)));
7252 let handles: Vec<_> = (0..n)
7253 .map(|_| {
7254 let (q, b, now, max) = (q.clone(), barrier.clone(), now.clone(), max.clone());
7255 std::thread::spawn(move || {
7256 b.wait();
7257 let g = q.lock_task("t").unwrap();
7258 let held = now.fetch_add(1, Ordering::SeqCst) + 1;
7259 max.fetch_max(held, Ordering::SeqCst);
7260 std::thread::sleep(std::time::Duration::from_millis(20));
7261 now.fetch_sub(1, Ordering::SeqCst);
7262 drop(g);
7263 })
7264 })
7265 .collect();
7266 for h in handles {
7267 h.join().unwrap();
7268 }
7269 assert_eq!(max.load(Ordering::SeqCst), 1);
7270 assert!(!lock.exists());
7271 }
7272 }
7273
7274 #[test]
7275 fn dropping_a_replaced_lock_leaves_the_new_holders_token() {
7276 let dir = tempfile::tempdir().unwrap();
7277 let q = Queue::at(dir.path().to_path_buf());
7278 let lock = dir.path().join("t.write-lock");
7279 let a = q.lock_task("t").unwrap();
7280 let replacement = owner_token();
7283 std::fs::write(&lock, &replacement).unwrap();
7284 drop(a);
7285 assert_eq!(std::fs::read_to_string(&lock).unwrap(), replacement);
7286 }
7287
7288 #[test]
7289 fn aged_live_task_lock_excludes_updates_until_retirement_releases_it() {
7290 let dir = tempfile::tempdir().unwrap();
7291 let q = Queue::at(dir.path().to_path_buf());
7292 let held = q.lock_task("t").unwrap();
7293 let path = dir.path().join("t.write-lock");
7294 age_lock(&path);
7295 assert!(!break_stale(&path, &held.token));
7296 let (started_tx, started_rx) = std::sync::mpsc::channel();
7297 let (acquired_tx, acquired_rx) = std::sync::mpsc::channel();
7298 let updater = std::thread::spawn(move || {
7299 started_tx.send(()).unwrap();
7300 let _write = q.lock_task("t").unwrap();
7301 acquired_tx.send(()).unwrap();
7302 });
7303 started_rx.recv().unwrap();
7304 assert!(
7305 acquired_rx
7306 .recv_timeout(std::time::Duration::from_millis(100))
7307 .is_err()
7308 );
7309 assert_eq!(std::fs::read_to_string(&path).unwrap(), held.token);
7310 drop(held);
7311 acquired_rx
7312 .recv_timeout(std::time::Duration::from_secs(2))
7313 .unwrap();
7314 updater.join().unwrap();
7315 assert!(!path.exists());
7316 }
7317
7318 #[test]
7319 fn break_stale_leaves_a_lock_that_replaced_the_one_judged() {
7320 let dir = tempfile::tempdir().unwrap();
7321 let lock = dir.path().join("t.write-lock");
7322 std::fs::write(&lock, "new-token").unwrap();
7323 assert!(!break_stale(&lock, "old-token"));
7324 assert_eq!(std::fs::read_to_string(&lock).unwrap(), "new-token");
7325 assert!(!break_stale(&lock, "new-token"));
7327 assert!(lock.exists());
7328 age_lock(&lock);
7329 assert!(break_stale(&lock, "new-token"));
7330 assert!(!lock.exists());
7331 }
7332
7333 #[test]
7334 fn a_stale_break_marker_is_recovered_and_a_fresh_one_is_respected() {
7335 let dir = tempfile::tempdir().unwrap();
7336 let lock = dir.path().join("t.write-lock");
7337 std::fs::write(&lock, "dead-1").unwrap();
7338 age_lock(&lock);
7339 let marker = break_marker(&lock, "dead-1");
7340 std::fs::write(&marker, "crashed-remover").unwrap();
7341 assert!(!break_stale(&lock, "dead-1"));
7343 assert!(lock.exists());
7344 age_lock(&marker);
7346 assert!(break_stale(&lock, "dead-1"));
7347 assert!(!lock.exists());
7348 assert!(!marker.exists());
7349 }
7350
7351 fn chat_task() -> Task {
7352 Task::new(
7353 "t".to_owned(),
7354 "do t".to_owned(),
7355 PathBuf::from("."),
7356 Source::Agent {
7357 run: "20260902-000000-beef".to_owned(),
7358 node: CHAT_NODE.to_owned(),
7359 },
7360 )
7361 }
7362
7363 #[test]
7364 fn a_blocked_hold_keeps_its_anchor_but_a_new_run_starts_a_new_hold() {
7365 let mut t = chat_task();
7366 t.hold_machine(Some("waiting".into()));
7367 let old: Timestamp = "2020-01-01T00:00:00Z".parse().unwrap();
7368 t.held_at = Some(old);
7369 t.block(vec!["decision".into()], None);
7370 t.hold_machine(Some("same waiting decision".into()));
7371 assert_eq!(t.held_at, Some(old));
7372 t.start("real-new-run".into());
7373 t.fail("new failure", 1);
7374 assert_ne!(
7375 t.held_at,
7376 Some(old),
7377 "old answers cannot approve a new hold"
7378 );
7379 }
7380
7381 #[test]
7382 fn legacy_delivery_survives_upgrade_and_a_no_progress_run_link() {
7383 let (_dir, queue) = queue();
7384 let mut t = chat_task();
7385 t.start("old-run".into());
7386 t.hold_machine(Some("operator is considering recovery".into()));
7387 t.chat_notice = Some(ChatNotice {
7388 key: format!("held#{}", t.held_at.unwrap()),
7389 at: Timestamp::now(),
7390 outcome: ChatNoticeOutcome::Posted,
7391 });
7392 let mut raw = serde_json::to_value(&t).unwrap();
7393 raw.as_object_mut().unwrap().remove("chat_notices");
7394 raw.as_object_mut().unwrap().remove("hold_notice_cause");
7395 std::fs::create_dir_all(queue.path_of(&t.id).parent().unwrap()).unwrap();
7396 std::fs::write(queue.path_of(&t.id), serde_json::to_string(&raw).unwrap()).unwrap();
7397 assert_eq!(queue.get(&t.id).unwrap().chat_notice_due(), None);
7398 queue
7399 .modify(&t.id, |task| {
7400 task.requeue();
7401 task.link_run("unprepared-run");
7402 task.startup_notice_cause("startup-source");
7403 task.fail("same unresolved preflight", 0);
7404 true
7405 })
7406 .unwrap();
7407 assert_eq!(queue.get(&t.id).unwrap().chat_notice_due(), None);
7408 queue
7409 .modify(&t.id, |task| {
7410 task.succeed(completion(task));
7411 true
7412 })
7413 .unwrap();
7414 assert!(
7415 queue
7416 .get(&t.id)
7417 .unwrap()
7418 .chat_notice_due()
7419 .unwrap()
7420 .starts_with("done:")
7421 );
7422 }
7423
7424 #[test]
7425 fn a_dependency_wait_does_not_change_when_released_and_blocked_again() {
7426 let mut t = chat_task();
7427 t.block(vec!["a".into(), "b".into()], Some("waiting".into()));
7428 let key = t.chat_notice_key().unwrap();
7429 t.chat_notices.push(key);
7430 t.release();
7431 t.block(
7432 vec!["b".into(), "a".into(), "a".into()],
7433 Some("still waiting on prerequisites".into()),
7434 );
7435 assert_eq!(t.chat_notice_due(), None);
7436 t.block(
7437 vec!["new-question".into()],
7438 Some("different decision".into()),
7439 );
7440 assert!(t.chat_notice_due().is_some());
7441 }
7442
7443 #[test]
7444 fn running_startup_failures_preserve_stage_and_report_distinct_blockers() {
7445 let mut t = chat_task();
7446 t.start("existing-run".into());
7447 t.fail("implementation failed", 1);
7448 let failed = t.chat_notice_key().unwrap();
7449 t.chat_notices.push(failed.clone());
7450 t.release_operator("test", None);
7451 t.start("existing-run".into());
7452 t.fail_startup("startup-source", "same unresolved recovery source", 1);
7453 assert_eq!(
7454 t.chat_notice_due(),
7455 None,
7456 "no-progress recovery stays quiet"
7457 );
7458 t.release_operator("test", None);
7459 t.start("existing-run".into());
7460 t.fail_startup("startup-attachments", "attachment missing", 1);
7461 let attachments = t.chat_notice_due().expect("new attachment blocker");
7462 assert_ne!(attachments, failed);
7463 assert_eq!(
7464 t.hold_notice_cause.as_ref().unwrap().stage,
7465 "startup-attachments"
7466 );
7467 t.chat_notices.push(attachments);
7468 t.release_operator("test", None);
7469 t.start("existing-run".into());
7470 t.fail_startup(
7471 "startup-attachments",
7472 "same missing attachment, reworded",
7473 1,
7474 );
7475 assert_eq!(
7476 t.chat_notice_due(),
7477 None,
7478 "same stage after attempt counter reset"
7479 );
7480 t.release_operator("test", None);
7481 t.start("existing-run".into());
7482 t.fail_startup("startup-config", "different preflight stage", 1);
7483 assert!(t.chat_notice_due().is_some());
7484 assert_eq!(
7485 t.hold_notice_cause.as_ref().unwrap().stage,
7486 "startup-config"
7487 );
7488 }
7489
7490 #[test]
7491 fn structured_causes_preserve_no_progress_retries_and_report_new_passes() {
7492 let mut t = chat_task();
7493 t.hold_machine(Some("startup source missing".into()));
7494 t.startup_notice_cause("startup-source");
7495 let first = t.chat_notice_key().unwrap();
7496 t.chat_notices.push(first.clone());
7497 t.release_operator("test", None);
7498 t.startup_notice_cause("startup-source");
7499 t.hold_machine(Some("same source cannot be read".into()));
7500 assert_eq!(t.chat_notice_due(), None);
7501 t.startup_notice_cause("startup-config");
7502 assert!(t.chat_notice_due().is_some(), "different startup stage");
7503 t.notice_cause("failed", Some("existing-run"), Some(0));
7504 let run_failure = t.chat_notice_key().unwrap();
7505 t.chat_notices.push(run_failure.clone());
7506 t.release_operator("test", None);
7507 t.startup_notice_cause("startup-source");
7508 t.hold_machine(Some("no new work happened".into()));
7509 assert_eq!(t.chat_notice_due(), None);
7510 t.notice_cause("failed", Some("existing-run"), Some(1));
7511 assert!(t.chat_notice_due().is_some(), "a real resumed pass failed");
7512 assert_ne!(t.chat_notice_key().unwrap(), run_failure);
7513 }
7514
7515 #[test]
7516 fn legacy_hold_baseline_does_not_replay_or_hide_new_failures_and_completion() {
7517 let mut t = chat_task();
7518 t.hold_machine(Some("still waiting".into()));
7519 t.chat_notice = Some(ChatNotice {
7520 key: "held#2026-10-14T00:00:00Z".into(),
7521 at: Timestamp::now(),
7522 outcome: ChatNoticeOutcome::Posted,
7523 });
7524 assert_eq!(t.chat_notice_due(), None, "old hold baseline");
7525 t.import_chat_notice();
7526 t.notice_cause("failed", Some("new-run"), Some(0));
7527 assert!(t.chat_notice_due().is_some(), "new producer evidence");
7528 t.succeed(completion(&t));
7529 assert!(t.chat_notice_due().unwrap().starts_with("done:"));
7530 }
7531
7532 #[test]
7533 fn a_chat_notice_is_due_only_for_a_final_state_and_only_once() {
7534 let mut t = chat_task();
7535 assert_eq!(t.chat_notice_due(), None, "queued");
7536 t.start("r1".to_owned());
7537 assert_eq!(t.chat_notice_due(), None, "running");
7538 t.fail("boom", 3);
7539 assert_eq!(t.status, TaskStatus::Failed);
7540 assert_eq!(t.chat_notice_due(), None, "a retried failure is not final");
7541 t.start("r2".to_owned());
7542 t.park("upgrade");
7543 assert_eq!(t.chat_notice_due(), None, "parked");
7544 t.fail("boom", 1);
7545 assert_eq!(t.status, TaskStatus::Held);
7546 let key = t
7547 .chat_notice_due()
7548 .expect("held on the last attempt is final");
7549 t.chat_notice = Some(ChatNotice {
7550 key,
7551 at: Timestamp::now(),
7552 outcome: ChatNoticeOutcome::Posted,
7553 });
7554 assert_eq!(t.chat_notice_due(), None, "same hold, no second notice");
7555 t.release();
7556 assert_eq!(t.chat_notice_due(), None, "requeued after a release");
7557 t.start("r3".to_owned());
7558 t.succeed(completion(&t));
7559 assert!(t.chat_notice_due().is_some(), "done is a new final state");
7560 }
7561
7562 #[test]
7563 fn legacy_completion_receipts_do_not_suppress_new_occurrences() {
7564 for key in ["done", "done#0", "done#1", "done#12"] {
7565 let mut t = chat_task();
7566 t.status = TaskStatus::Done;
7567 t.chat_notice = Some(ChatNotice {
7568 key: key.to_owned(),
7569 at: Timestamp::now(),
7570 outcome: ChatNoticeOutcome::Posted,
7571 });
7572 assert_eq!(t.chat_notice_key().as_deref(), Some("done"));
7573 assert_eq!(t.chat_notice_due(), None, "legacy recorded key: {key}");
7574 let mut context = completion(&t);
7575 context.reason = Some("inspect again".into());
7576 t.reopen(context).unwrap();
7577 t.start("r2".to_owned());
7578 t.succeed(completion(&t));
7579 assert!(t.chat_notice_key().unwrap().starts_with("done:"));
7580 assert!(
7581 t.chat_notice_due().is_some(),
7582 "new occurrence, old receipt: {key}"
7583 );
7584 }
7585 }
7586
7587 #[test]
7588 fn a_release_without_progress_keeps_the_unresolved_notice_cause() {
7589 let mut t = chat_task();
7590 t.hold_manual(Some("wait".to_owned()));
7591 let first = t.chat_notice_due().expect("held");
7592 t.chat_notice = Some(ChatNotice {
7593 key: first.clone(),
7594 at: Timestamp::now(),
7595 outcome: ChatNoticeOutcome::Posted,
7596 });
7597 t.hold_manual(Some("still waiting".to_owned()));
7598 assert_eq!(t.chat_notice_due(), None, "a re-hold keeps its start");
7599 t.release();
7600 std::thread::sleep(std::time::Duration::from_millis(5));
7601 t.hold_manual(None);
7602 assert_eq!(t.chat_notice_due(), None, "no progress, same cause");
7603 }
7604
7605 #[test]
7606 fn a_chat_notice_needs_a_chat_source_and_a_current_schema() {
7607 let mut human = task("h");
7608 human.succeed(completion(&human));
7609 assert_eq!(human.chat_notice_due(), None);
7610 let mut inherited = task("i");
7612 inherited.origin_chat = Some("20260902-000000-beef".to_owned());
7613 inherited.succeed(completion(&inherited));
7614 assert_eq!(inherited.chat_notice_due(), None);
7615 let mut old = chat_task();
7616 old.schema = 12;
7617 old.status = TaskStatus::Done;
7618 assert_eq!(old.chat_notice_due(), None, "history is not replayed");
7619 let mut live = chat_task();
7620 live.schema = 12;
7621 live.start("r1".to_owned());
7622 live.succeed(completion(&live));
7623 assert!(live.chat_notice_due().is_some(), "started by this build");
7624 let mut held = chat_task();
7625 held.schema = 12;
7626 held.hold_machine(Some("config".to_owned()));
7627 assert!(held.chat_notice_due().is_some(), "held before any start");
7628 }
7629
7630 #[test]
7631 fn a_stale_snapshot_does_not_rewind_a_recorded_chat_notice() {
7632 let tmp = tempfile::tempdir().expect("tempdir");
7633 let q = Queue::at(tmp.path().join("queue"));
7634 let mut t = chat_task();
7635 t.succeed(completion(&t));
7636 q.put(&mut t).expect("put");
7637 let mut stale = q.get(&t.id).expect("get");
7638 let key = t.chat_notice_due().expect("due");
7639 q.modify(&t.id, |x| {
7640 x.chat_notice = Some(ChatNotice {
7641 key: key.clone(),
7642 at: Timestamp::now(),
7643 outcome: ChatNoticeOutcome::Posted,
7644 });
7645 true
7646 })
7647 .expect("modify");
7648 q.put(&mut stale).expect("stale put");
7649 assert_eq!(q.get(&t.id).expect("get").chat_notice_due(), None);
7650 }
7651
7652 #[test]
7653 fn empty_sources_are_omitted_so_older_builds_still_read_the_task() {
7654 let mut t = task("plain");
7657 let value = serde_json::to_value(&t).unwrap();
7658 assert!(value.get("sources").is_none(), "{value}");
7659 t.sources.pick_commits.push(crate::refs::Input {
7660 token: "abc1234".into(),
7661 sha: "a".repeat(40),
7662 provenance: crate::refs::Provenance::ExplicitCli,
7663 });
7664 let value = serde_json::to_value(&t).unwrap();
7665 assert_eq!(value["sources"]["pick_commits"][0]["sha"], "a".repeat(40));
7666 let restored: Task = serde_json::from_value(value).unwrap();
7667 assert_eq!(restored.sources, t.sources);
7668 }
7669
7670 fn queue_with_ids(dir: &Path, ids: &[&str]) -> Queue {
7672 let ids: Vec<String> = ids.iter().map(|s| (*s).to_owned()).collect();
7673 let n = std::sync::atomic::AtomicUsize::new(0);
7674 Queue::at(dir.join("queue")).with_id_source(move || {
7675 let i = n.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
7676 ids.get(i)
7677 .cloned()
7678 .unwrap_or_else(|| format!("20260101-000000-f{i:03x}"))
7679 })
7680 }
7681
7682 const TAKEN: &str = "20260101-000000-aaaa";
7683
7684 #[test]
7685 fn a_new_task_never_merges_into_a_record_with_its_candidate_id() {
7686 let dir = tempfile::tempdir().unwrap();
7687 let q = queue_with_ids(dir.path(), &[TAKEN, TAKEN]);
7688 let mut first = task("first");
7689 first.start("run-1".into());
7690 first.succeed(completion(&first));
7691 q.put(&mut first).unwrap();
7692 assert_eq!(first.id, TAKEN);
7693 let stored_before = q.get(&first.id).unwrap();
7694 assert!(!stored_before.runs.is_empty());
7695
7696 let mut second = task("second");
7697 q.put(&mut second).unwrap();
7698
7699 assert_ne!(second.id, first.id);
7700 assert!(second.runs.is_empty());
7701 assert!(second.passes.is_empty());
7702 assert!(second.chat_notices.is_empty());
7703 assert!(second.chat_notice.is_none());
7704 assert_eq!(second.chat_notice_due(), task("fresh").chat_notice_due());
7705 let a = q.get(&first.id).unwrap();
7706 let b = q.get(&second.id).unwrap();
7707 assert_eq!(a.title, "first");
7708 assert_eq!(a.runs, stored_before.runs);
7709 assert_eq!(a.passes, stored_before.passes);
7710 assert_eq!(a.chat_notices, stored_before.chat_notices);
7711 assert_eq!(a.chat_notice, stored_before.chat_notice);
7712 assert_eq!(a.chat_notice_due(), stored_before.chat_notice_due());
7713 assert_eq!(b.title, "second");
7714 assert!(b.runs.is_empty());
7715 assert!(b.passes.is_empty());
7716 assert!(b.chat_notice.is_none());
7717
7718 let mut again = q.get(&second.id).unwrap();
7720 again.title = "second, edited".into();
7721 q.put(&mut again).unwrap();
7722 assert_eq!(q.get(&second.id).unwrap().title, "second, edited");
7723 assert_eq!(q.list().len(), 2);
7724 }
7725
7726 #[test]
7727 fn a_new_task_skips_an_id_with_an_orphaned_claim_or_attachments() {
7728 let dir = tempfile::tempdir().unwrap();
7729 let q = queue_with_ids(dir.path(), &["orphan-lock", "orphan-dir", "free"]);
7730 std::fs::create_dir_all(q.root()).unwrap();
7731 std::fs::write(q.root().join("orphan-lock.lock"), "x").unwrap();
7732 std::fs::create_dir_all(q.attachments_dir("orphan-dir")).unwrap();
7733 let mut t = task("t");
7734 q.put(&mut t).unwrap();
7735 assert_eq!(t.id, "free");
7736 }
7737
7738 #[test]
7739 fn a_claimed_new_task_holds_the_claim_on_the_reserved_id() {
7740 let dir = tempfile::tempdir().unwrap();
7741 let q = queue_with_ids(dir.path(), &[TAKEN, TAKEN]);
7742 let mut first = task("first");
7743 q.put(&mut first).unwrap();
7744 let mut second = task("second");
7745 let claim = q.file_claimed(&mut second).unwrap();
7746 assert_ne!(second.id, first.id);
7747 assert!(q.claim(&second.id).is_err());
7748 assert!(q.claim(&first.id).is_ok(), "the first task was not claimed");
7749 drop(claim);
7750 }
7751
7752 #[test]
7753 fn an_attached_new_task_skips_a_taken_id() {
7754 let dir = tempfile::tempdir().unwrap();
7755 let q = queue_with_ids(dir.path(), &[TAKEN, TAKEN]);
7756 let mut first = task("first");
7757 q.put(&mut first).unwrap();
7758 let src = source_file(dir.path(), "shot.png", "x");
7759 let mut second = task("second");
7760 q.attach_and_put(&mut second, &[src]).unwrap();
7761 assert_ne!(second.id, first.id);
7762 assert!(!q.attachments_dir(&first.id).exists());
7763 assert_eq!(q.attachment_paths(&second).len(), 1);
7764 assert!(q.attachment_paths(&second)[0].is_file());
7765 }
7766
7767 #[test]
7768 fn attaching_before_putting_a_new_task_reserves_the_id() {
7769 let dir = tempfile::tempdir().unwrap();
7770 let q = queue_with_ids(dir.path(), &[TAKEN, TAKEN]);
7771 let mut first = task("first");
7772 q.put(&mut first).unwrap();
7773 let src = source_file(dir.path(), "shot.png", "x");
7774 let mut second = task("second");
7775 q.attach(&mut second, &[src]).unwrap();
7776 assert_ne!(second.id, first.id);
7777 assert!(q.attachments_dir(&second.id).is_dir());
7778 q.put(&mut second).unwrap();
7779 assert_eq!(q.get(&second.id).unwrap().attachments.len(), 1);
7780 assert_eq!(q.get(&first.id).unwrap().title, "first");
7781 assert!(q.get(&first.id).unwrap().attachments.is_empty());
7782 }
7783
7784 #[test]
7785 fn create_new_keeps_its_already_exists_meaning() {
7786 let dir = tempfile::tempdir().unwrap();
7787 let q = Queue::at(dir.path().join("queue"));
7788 let mut a = task("a");
7789 a.id = "fixed-id".into();
7790 assert!(q.create_new(&mut a).unwrap());
7791 let mut b = task("b");
7792 b.id = "fixed-id".into();
7793 assert!(!q.create_new(&mut b).unwrap());
7794 assert_eq!(q.get("fixed-id").unwrap().title, "a");
7795 }
7796
7797 #[test]
7798 fn filing_gives_up_when_no_id_is_ever_free() {
7799 let dir = tempfile::tempdir().unwrap();
7800 let q = Queue::at(dir.path().join("queue")).with_id_source(|| TAKEN.to_owned());
7801 let mut first = task("first");
7802 q.put(&mut first).unwrap();
7803 let mut second = task("second");
7804 assert!(q.put(&mut second).is_err());
7805 assert_eq!(q.get(&first.id).unwrap().title, "first");
7806 }
7807}