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 = 27;
154
155const RECOVERY_HOLD_SCHEMA: u32 = 24;
156
157pub(crate) fn dispatch_order(a: &Task, b: &Task) -> std::cmp::Ordering {
163 match (a.upgrade_resume_key(), b.upgrade_resume_key()) {
164 (Some(a), Some(b)) => a.cmp(&b),
165 (Some(_), None) => std::cmp::Ordering::Less,
166 (None, Some(_)) => std::cmp::Ordering::Greater,
167 (None, None) => b.priority.cmp(&a.priority).then(a.id.cmp(&b.id)),
168 }
169}
170
171#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
178#[serde(tag = "kind", rename_all = "snake_case")]
179pub enum MachineHoldCause {
180 DiskCapacity {
182 reason: String,
184 #[serde(default)]
186 before_start: bool,
187 },
188 HeadE2e {
190 stop: crate::head_e2e_stop::Stop,
192 },
193}
194
195#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
197#[serde(rename_all = "lowercase")]
198pub enum HoldSource {
199 Manual,
201 Machine,
203}
204
205impl HoldSource {
206 pub fn label(self) -> &'static str {
208 match self {
209 Self::Manual => "manual",
210 Self::Machine => "machine",
211 }
212 }
213}
214
215#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
218#[serde(tag = "kind", rename_all = "lowercase")]
219pub enum Source {
220 Human,
222 Agent {
225 run: String,
227 node: String,
229 },
230 Issue {
232 number: u64,
234 repo: String,
236 },
237}
238
239#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
241pub struct IssueRef {
242 pub number: u64,
244 pub repo: String,
246}
247
248pub const CHAT_NODE: &str = "chat";
251
252impl Source {
253 pub fn label(&self) -> String {
255 match self {
256 Self::Human => "human".to_owned(),
257 Self::Agent { run, node } => format!("{node}@{}", short(run)),
258 Self::Issue { number, .. } => format!("issue #{number}"),
259 }
260 }
261}
262
263#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
265#[serde(rename_all = "lowercase")]
266pub enum TaskStatus {
267 Queued,
269 Running,
271 Done,
273 Failed,
275 Held,
277 Blocked,
281 Parked,
286}
287
288impl TaskStatus {
289 pub fn runnable(self) -> bool {
291 matches!(self, Self::Queued | Self::Failed | Self::Parked)
292 }
293
294 pub fn as_str(self) -> &'static str {
296 match self {
297 Self::Queued => "queued",
298 Self::Running => "running",
299 Self::Done => "done",
300 Self::Failed => "failed",
301 Self::Held => "held",
302 Self::Blocked => "blocked",
303 Self::Parked => "parked",
304 }
305 }
306}
307
308#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
311pub struct TaskCounts {
312 pub queued: usize,
314 pub running: usize,
316 pub done: usize,
318 pub failed: usize,
320 pub held: usize,
322 pub blocked: usize,
324 pub parked: usize,
326}
327
328impl TaskCounts {
329 pub fn of(tasks: &[Task]) -> Self {
333 Self::of_statuses(tasks.iter().map(|task| task.status))
334 }
335
336 pub(crate) fn of_statuses(statuses: impl IntoIterator<Item = TaskStatus>) -> Self {
338 let mut counts = Self::default();
339 for status in statuses {
340 match status {
341 TaskStatus::Queued => counts.queued += 1,
342 TaskStatus::Running => counts.running += 1,
343 TaskStatus::Done => counts.done += 1,
344 TaskStatus::Failed => counts.failed += 1,
345 TaskStatus::Held => counts.held += 1,
346 TaskStatus::Blocked => counts.blocked += 1,
347 TaskStatus::Parked => counts.parked += 1,
348 }
349 }
350 counts
351 }
352}
353
354#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
356pub struct Reassignment {
357 pub from: PathBuf,
359 pub to: PathBuf,
361 pub actor: String,
363 pub at: Timestamp,
365 pub run_boundary: usize,
367}
368
369#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
371#[serde(tag = "kind", content = "talk", rename_all = "snake_case")]
372pub enum CompletionActor {
373 Cli,
375 Web,
377 Chat(String),
379 Conductor,
381 DaemonSettle,
383}
384
385#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
387#[serde(rename_all = "snake_case")]
388pub enum CompletionAction {
389 Complete,
391 Reopen,
393}
394
395#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
397pub struct CompletionRunSnapshot {
398 pub id: String,
400 pub status: Option<crate::run::RunStatus>,
402 pub pr_url: Option<String>,
404 pub pr_state: Option<String>,
406 pub pr_head: Option<String>,
408 #[serde(default)]
410 pub branches: Vec<String>,
411 pub error: Option<String>,
413}
414
415impl CompletionRunSnapshot {
416 fn from_run(state: &crate::run::RunState) -> Self {
417 let mut branches: Vec<String> = state
418 .candidates
419 .iter()
420 .map(|candidate| candidate.branch.clone())
421 .collect();
422 if let Some(branch) = &state.pr_head
423 && !branches.contains(branch)
424 {
425 branches.push(branch.clone());
426 }
427 Self {
428 id: state.id.clone(),
429 status: Some(state.status),
430 pr_url: state.pr.as_ref().map(|pr| pr.url.clone()),
431 pr_state: state.pr.as_ref().map(|pr| pr.state.clone()),
432 pr_head: state
433 .pr_merged_head
434 .clone()
435 .or_else(|| state.pr_pushed_head.clone()),
436 branches,
437 error: None,
438 }
439 }
440}
441
442#[derive(Debug, Clone)]
444pub struct CompletionContext {
445 pub actor: CompletionActor,
447 pub reason: Option<String>,
449 pub discard: bool,
451 pub run: Option<CompletionRunSnapshot>,
453 pub unavailable_runs: Vec<String>,
455}
456
457impl CompletionContext {
458 pub fn new(actor: CompletionActor, reason: Option<String>, home: &Path, task: &Task) -> Self {
460 let run = task
461 .runs
462 .last()
463 .map(|id| match crate::run::RunState::load_under(id, home) {
464 Ok(state) => CompletionRunSnapshot::from_run(&state),
465 Err(error) => CompletionRunSnapshot {
466 id: id.clone(),
467 status: None,
468 pr_url: None,
469 pr_state: None,
470 pr_head: None,
471 branches: Vec::new(),
472 error: Some(format!("{error:#}")),
473 },
474 });
475 Self {
476 actor,
477 reason,
478 discard: false,
479 run,
480 unavailable_runs: Vec::new(),
481 }
482 }
483
484 pub fn from_run(
486 actor: CompletionActor,
487 reason: Option<String>,
488 _task: &Task,
489 state: &crate::run::RunState,
490 ) -> Self {
491 Self {
492 actor,
493 reason,
494 discard: false,
495 run: Some(CompletionRunSnapshot::from_run(state)),
496 unavailable_runs: Vec::new(),
497 }
498 }
499}
500
501#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
503pub struct CompletionEvent {
504 pub occurrence: String,
506 pub action: CompletionAction,
508 pub actor: CompletionActor,
510 pub reason: Option<String>,
512 pub discard: bool,
514 pub prior_status: TaskStatus,
516 #[serde(default)]
518 pub prior_hold_reason: Option<String>,
519 #[serde(default)]
521 pub prior_block_reason: Option<String>,
522 #[serde(default)]
524 pub prior_error: Option<String>,
525 pub at: Timestamp,
527 pub run: Option<CompletionRunSnapshot>,
529 #[serde(default, skip_serializing_if = "Vec::is_empty")]
531 pub unavailable_runs: Vec<String>,
532}
533
534#[derive(Debug, Clone, Serialize, Deserialize)]
536#[serde(deny_unknown_fields)]
537pub struct Task {
538 pub schema: u32,
540 pub id: String,
542 pub title: String,
544 pub instruction: String,
546 #[serde(default, skip_serializing_if = "crate::refs::Sources::is_empty")]
548 pub sources: crate::refs::Sources,
549 pub repo: PathBuf,
551 #[serde(default)]
553 pub reassignments: Vec<Reassignment>,
554 pub source: Source,
556 #[serde(default, skip_serializing_if = "Option::is_none")]
558 pub issue: Option<IssueRef>,
559 #[serde(default)]
561 pub chat: Option<String>,
562 #[serde(default)]
564 pub priority: i32,
565 #[serde(default)]
576 pub solo: bool,
577 pub status: TaskStatus,
579 #[serde(default)]
581 pub completion_history: Vec<CompletionEvent>,
582 #[serde(default)]
584 pub attempts: usize,
585 #[serde(default)]
587 pub attempt_limit: Option<NonZeroUsize>,
588 #[serde(default)]
591 pub runs: Vec<String>,
592 #[serde(default)]
594 pub startup_failures: Vec<crate::run::StartupFailure>,
595 #[serde(default)]
597 pub last_error: Option<String>,
598 #[serde(default)]
611 pub hold_reason: Option<String>,
612 #[serde(default)]
615 pub hold_source: Option<HoldSource>,
616 #[serde(default, skip_serializing_if = "Option::is_none")]
617 recovery_budget_hold: Option<RecoveryBudgetHold>,
618 #[serde(default)]
620 pub machine_hold_cause: Option<MachineHoldCause>,
621 #[serde(default)]
623 pub disk_resume_run: Option<String>,
624 #[serde(default)]
626 pub disk_checked_at: Option<Timestamp>,
627 #[serde(default)]
639 pub diagnostic: Option<String>,
640 #[serde(default)]
650 pub blocked_by: Vec<String>,
651 #[serde(default)]
654 pub block_reason: Option<String>,
655 #[serde(default)]
668 pub blocked_from: Option<TaskStatus>,
669 #[serde(default)]
671 pub blocked_at: Option<Timestamp>,
672 #[serde(default)]
683 pub answers: Vec<AnsweredQuestion>,
684 #[serde(default)]
690 pub triage_applied: Vec<String>,
691 #[serde(default)]
697 pub actions_applied: Vec<String>,
698 #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
701 pub decision_effects: std::collections::BTreeMap<String, String>,
702 #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
705 pub superseded_resumes: std::collections::BTreeMap<String, String>,
706 #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
710 pub dispatched_resumes: std::collections::BTreeMap<String, String>,
711 #[serde(default)]
713 pub base_recovery_requests: Vec<String>,
714 #[serde(default)]
716 pub land_sync_recovery_requests: Vec<String>,
717 #[serde(default)]
722 pub resume_override: Option<OperatorResume>,
723 #[serde(default, skip_serializing_if = "Option::is_none")]
725 pub sync_only: Option<crate::base_sync_only::Request>,
726 #[serde(default)]
728 pub repair_grants: Vec<crate::repair_budget::Receipt>,
729 #[serde(default)]
731 pub repair_reconciliations: Vec<crate::repair_budget::reconcile::Receipt>,
732 #[serde(default)]
735 pub resumption: Option<Resumption>,
736 #[serde(default)]
738 pub resumption_history: Vec<Resumption>,
739 #[serde(default)]
741 pub operator_decided_at: Option<Timestamp>,
742 #[serde(default)]
754 pub review_branch: Option<String>,
755 #[serde(default)]
757 pub review_instruction: Option<String>,
758 #[serde(default)]
760 pub pr_recovery: Option<crate::pr_recovery::Selection>,
761 #[serde(default)]
764 pub fresh_start: bool,
765 #[serde(default)]
767 pub replacement: Option<crate::merge_decision::Replacement>,
768 #[serde(default)]
779 pub interrupt: bool,
780 #[serde(default)]
803 pub urgent: bool,
804 #[serde(default)]
818 pub immediate: bool,
819 #[serde(skip)]
824 pub(crate) unfiled: bool,
825 #[serde(default)]
831 pub attachments: Vec<String>,
832 #[serde(default)]
836 pub followup: Option<FollowUp>,
837 #[serde(default)]
843 pub origin_chat: Option<String>,
844 #[serde(default)]
851 pub overrides: Option<RunOverrides>,
852 #[serde(default)]
859 pub review_of: Option<String>,
860 #[serde(default)]
865 pub held_at: Option<Timestamp>,
866 #[serde(default)]
870 pub park_reason: Option<String>,
871 #[serde(default)]
874 pub chat_notice: Option<ChatNotice>,
875 #[serde(default)]
877 pub chat_notices: Vec<String>,
878 #[serde(default)]
881 pub hold_notice_cause: Option<NoticeCause>,
882 #[serde(default)]
887 pub passes: Vec<TaskPass>,
888 #[serde(default)]
892 pub dispatched_at: Option<Timestamp>,
893 #[serde(default)]
895 pub recovery_budget: Option<RecoveryBudget>,
896 #[serde(default)]
899 pub recovery_admission: Option<RecoveryAdmission>,
900 #[serde(default)]
903 pub recovery_generations: Vec<RecoveryBudget>,
904 pub created_at: Timestamp,
906 pub updated_at: Timestamp,
908}
909
910#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
912pub struct RecoveryAdmission {
913 pub base: String,
915 pub inputs: String,
917}
918
919#[derive(Debug, Clone, Serialize, Deserialize)]
920struct RecoveryBudgetHold {
921 admission: RecoveryAdmission,
922 run: String,
923 pass: usize,
924 held_at: Timestamp,
925 decision: Option<Timestamp>,
926 #[serde(default)]
927 legacy: bool,
928}
929
930#[derive(Debug, Clone, Serialize, Deserialize)]
933pub struct RecoveryBudget {
934 pub instruction: String,
936 pub base: String,
938 pub inputs: String,
940 pub stage: String,
942 pub failures: usize,
944 #[serde(default)]
947 pub progress: Option<String>,
948}
949
950impl RecoveryBudget {
951 fn budget_reason(&self) -> String {
952 format!(
953 "[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.",
954 self.failures, self.stage
955 )
956 }
957}
958
959fn recovery_progress(state: &crate::run::RunState) -> Option<String> {
960 use crate::proc::Quiet as _;
961 use std::hash::{Hash, Hasher};
962 let mut patches = Vec::new();
963 for candidate in state.candidates.iter().filter(|c| c.commits > 0) {
964 let output = std::process::Command::new("git")
965 .current_dir(&state.repo)
966 .args(["diff", "--binary", &state.base_commit, &candidate.branch])
967 .quiet()
968 .output()
969 .ok()?;
970 if !output.status.success() {
971 return None;
972 }
973 patches.push(output.stdout);
974 }
975 patches.sort();
976 patches.dedup();
977 let mut hash = std::collections::hash_map::DefaultHasher::new();
978 patches.hash(&mut hash);
979 Some(format!("{:x}", hash.finish()))
980}
981
982pub(crate) fn recovery_inputs(sources: &crate::refs::Sources) -> String {
986 serde_json::to_string(
987 &sources
988 .start_from
989 .iter()
990 .map(|i| ("start", &i.token, &i.sha))
991 .chain(
992 sources
993 .pick_commits
994 .iter()
995 .map(|i| ("pick", &i.token, &i.sha)),
996 )
997 .collect::<Vec<_>>(),
998 )
999 .unwrap_or_default()
1000}
1001
1002#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1004pub struct NoticeCause {
1005 pub stage: String,
1007 #[serde(default, skip_serializing_if = "Option::is_none")]
1010 pub target: Option<String>,
1011 pub run: Option<String>,
1013 pub pass: Option<usize>,
1015}
1016
1017pub(crate) fn is_done_notice_key(key: &str) -> bool {
1019 key == "done"
1020 || key
1021 .strip_prefix("done#")
1022 .is_some_and(|count| !count.is_empty() && count.bytes().all(|b| b.is_ascii_digit()))
1023}
1024
1025#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1027#[serde(rename_all = "snake_case")]
1028pub enum PassCost {
1029 Spent,
1031 Refunded,
1033}
1034
1035#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1037pub struct TaskPass {
1038 pub run: String,
1040 pub pass_index: usize,
1042 pub cost: PassCost,
1044 pub attempts_after: usize,
1046 #[serde(default)]
1048 pub started_at: Option<Timestamp>,
1049 pub settled_at: Timestamp,
1051 #[serde(default)]
1053 pub parked: Option<crate::run::ParkCause>,
1054}
1055
1056#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1058#[serde(rename_all = "lowercase")]
1059pub enum ChatNoticeOutcome {
1060 Posted,
1062 Skipped,
1064}
1065
1066#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1068pub struct ChatNotice {
1069 pub key: String,
1071 pub at: Timestamp,
1073 pub outcome: ChatNoticeOutcome,
1075}
1076
1077#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1079pub struct RunOverrides {
1080 #[serde(default)]
1083 pub inherit_daemon_options: bool,
1084 #[serde(default)]
1086 pub merge: Option<String>,
1087 #[serde(default)]
1089 pub candidates: Option<usize>,
1090 #[serde(default)]
1092 pub judges: Option<usize>,
1093 #[serde(default)]
1095 pub reviewers: Option<usize>,
1096 #[serde(default)]
1098 pub review_rounds: Option<usize>,
1099 #[serde(default)]
1101 pub seed: Option<u64>,
1102 #[serde(default)]
1104 pub config: Option<PathBuf>,
1105 #[serde(default, skip_serializing_if = "Option::is_none")]
1107 pub build_cache: Option<BuildCache>,
1108}
1109
1110impl RunOverrides {
1111 pub fn merge_over(&mut self, other: &RunOverrides) {
1113 macro_rules! take {
1114 ($($f:ident),*) => {$(
1115 if other.$f.is_some() {
1116 self.$f.clone_from(&other.$f);
1117 }
1118 )*};
1119 }
1120 take!(
1121 merge,
1122 candidates,
1123 judges,
1124 reviewers,
1125 review_rounds,
1126 seed,
1127 config,
1128 build_cache
1129 );
1130 }
1131
1132 pub fn apply(&self, config: &mut crate::config::Config) {
1134 if let Some(n) = self.candidates {
1135 config.graph.implementers = n;
1136 }
1137 if let Some(n) = self.judges {
1138 config.graph.judges = n;
1139 }
1140 if let Some(n) = self.reviewers {
1141 config.graph.reviewers = n;
1142 }
1143 if let Some(n) = self.review_rounds {
1144 config.graph.review_rounds = n;
1145 }
1146 if let Some(m) = &self.merge
1147 && let Ok(mode) = crate::daemon::merge_mode(m)
1148 {
1149 config.merge.mode = mode;
1150 }
1151 if let Some(s) = self.seed {
1152 config.blind.seed = Some(s);
1153 }
1154 if let Some(mode) = self.build_cache {
1155 config.verify.build_cache = mode;
1156 }
1157 }
1158}
1159
1160#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1162pub struct FollowUp {
1163 pub run: String,
1165 #[serde(default)]
1167 pub origin_task: Option<String>,
1168 pub pr: String,
1170 pub findings: Vec<String>,
1172 pub generation: u32,
1175}
1176
1177#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1179pub struct Resumption {
1180 pub generation: u64,
1182 pub source: String,
1184 pub question_id: Option<String>,
1186 pub at: Timestamp,
1188 pub instruction: String,
1190 pub answers_through: usize,
1192 pub runs_through: usize,
1195 pub cleared_reason: Option<String>,
1197 #[serde(default)]
1199 pub blocking_evidence: Vec<String>,
1200}
1201
1202#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1205pub struct OperatorResume {
1206 pub question_id: String,
1208 pub at: Timestamp,
1210 #[serde(default)]
1213 pub conductor_rehold: Option<String>,
1214 #[serde(default)]
1217 pub forced: bool,
1218 #[serde(default)]
1225 pub pinned_run: Option<String>,
1226}
1227
1228#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1231pub struct AnsweredQuestion {
1232 pub question: String,
1234 pub answer: String,
1236}
1237
1238fn append_missing<T: PartialEq>(ledger: &mut Vec<T>, entries: Vec<T>) {
1239 for entry in entries {
1240 if !ledger.contains(&entry) {
1241 ledger.push(entry);
1242 }
1243 }
1244}
1245
1246fn prepend_missing_by<T>(ledger: &mut Vec<T>, mut older: Vec<T>, same: impl Fn(&T, &T) -> bool) {
1247 older.retain(|old| !ledger.iter().any(|entry| same(entry, old)));
1248 if !older.is_empty() {
1249 older.append(ledger);
1250 *ledger = older;
1251 }
1252}
1253
1254impl Task {
1255 pub fn new(title: String, instruction: String, repo: PathBuf, source: Source) -> Self {
1257 let now = Timestamp::now();
1258 let origin_chat = match &source {
1259 Source::Agent { run, node } if node == CHAT_NODE => Some(run.clone()),
1260 _ => None,
1261 };
1262 Self {
1263 schema: SCHEMA,
1264 id: new_id(),
1265 title,
1266 instruction,
1267 sources: crate::refs::Sources::default(),
1268 repo,
1269 reassignments: Vec::new(),
1270 source,
1271 issue: None,
1272 chat: None,
1273 priority: 0,
1274 solo: false,
1275 status: TaskStatus::Queued,
1276 completion_history: Vec::new(),
1277 attempts: 0,
1278 attempt_limit: None,
1279 runs: Vec::new(),
1280 startup_failures: Vec::new(),
1281 last_error: None,
1282 hold_reason: None,
1283 hold_source: None,
1284 recovery_budget_hold: None,
1285 machine_hold_cause: None,
1286 disk_resume_run: None,
1287 disk_checked_at: None,
1288 diagnostic: None,
1289 blocked_by: Vec::new(),
1290 block_reason: None,
1291 blocked_from: None,
1292 blocked_at: None,
1293 answers: Vec::new(),
1294 triage_applied: Vec::new(),
1295 actions_applied: Vec::new(),
1296 decision_effects: Default::default(),
1297 superseded_resumes: Default::default(),
1298 dispatched_resumes: Default::default(),
1299 base_recovery_requests: Vec::new(),
1300 land_sync_recovery_requests: Vec::new(),
1301 resume_override: None,
1302 sync_only: None,
1303 repair_grants: Vec::new(),
1304 repair_reconciliations: Vec::new(),
1305 resumption: None,
1306 resumption_history: Vec::new(),
1307 operator_decided_at: None,
1308 review_branch: None,
1309 review_instruction: None,
1310 pr_recovery: None,
1311 fresh_start: false,
1312 replacement: None,
1313 interrupt: false,
1314 urgent: false,
1315 immediate: false,
1316 unfiled: true,
1317 attachments: Vec::new(),
1318 followup: None,
1319 origin_chat,
1320 overrides: None,
1321 review_of: None,
1322 held_at: None,
1323 park_reason: None,
1324 chat_notice: None,
1325 chat_notices: Vec::new(),
1326 hold_notice_cause: None,
1327 passes: Vec::new(),
1328 dispatched_at: None,
1329 recovery_budget: None,
1330 recovery_admission: None,
1331 recovery_generations: Vec::new(),
1332 created_at: now,
1333 updated_at: now,
1334 }
1335 }
1336
1337 pub(crate) fn reassign_repository(&mut self, repo: PathBuf, actor: &str) {
1339 self.stamp_schema();
1340 if matches!(self.status, TaskStatus::Failed | TaskStatus::Parked) {
1341 self.hold_manual(Some(
1342 "Repository reassigned; inspect history and release to start fresh.".into(),
1343 ));
1344 }
1345 let at = Timestamp::now();
1346 self.reassignments.push(Reassignment {
1347 from: self.repo.clone(),
1348 to: repo.clone(),
1349 actor: actor.to_owned(),
1350 at,
1351 run_boundary: self.runs.len(),
1352 });
1353 self.repo = repo;
1354 self.review_branch = None;
1355 self.review_instruction = None;
1356 self.pr_recovery = None;
1357 self.replacement = None;
1358 self.interrupt = false;
1359 self.resume_override = None;
1360 self.fresh_start = true;
1361 self.operator_decided_at = Some(at);
1362 }
1363
1364 pub fn publication_branch(&self) -> String {
1366 crate::run::task_pr_branch_name(&self.id, self.reassignments.len())
1367 }
1368
1369 pub fn execution_runs(&self) -> &[String] {
1371 let boundary = self.reassignments.last().map_or(0, |r| r.run_boundary);
1372 self.runs.get(boundary..).unwrap_or_default()
1373 }
1374
1375 pub fn stale_pr_attention(&self, home: &Path) -> Option<String> {
1377 if self.status != TaskStatus::Done {
1378 return None;
1379 }
1380 let run = crate::run::RunState::load_under(self.execution_runs().last()?, home).ok()?;
1381 self.assignment_accepts(&run)
1382 .then(|| run.stale_pr_cause())
1383 .flatten()
1384 }
1385
1386 pub fn execution_run(&self, run: &str) -> bool {
1388 self.execution_runs().iter().any(|id| id == run)
1389 }
1390
1391 pub(crate) fn assignment_accepts(&self, run: &crate::run::RunState) -> bool {
1393 self.reassignments.last().is_none_or(|boundary| {
1394 self.execution_run(&run.id)
1395 && run.task_assignment == self.reassignments.len()
1396 && run.created_at > boundary.at
1397 && run
1398 .repo
1399 .canonicalize()
1400 .ok()
1401 .zip(self.repo.canonicalize().ok())
1402 .is_some_and(|(run_repo, task_repo)| run_repo == task_repo)
1403 })
1404 }
1405
1406 pub(crate) fn stale_question(&self, q: &crate::ask::Question) -> bool {
1408 self.reassignments
1409 .last()
1410 .is_some_and(|r| q.asked_at <= r.at)
1411 || (self.runs.contains(&q.run) && !self.execution_run(&q.run))
1412 }
1413
1414 pub fn chat_talk(&self) -> Option<&str> {
1416 if let Some(id) = &self.origin_chat {
1417 return Some(id);
1418 }
1419 match &self.source {
1420 Source::Agent { run, node } if node == CHAT_NODE => Some(run),
1421 _ => None,
1422 }
1423 }
1424
1425 pub fn filed_by_chat(&self) -> Option<&str> {
1429 match &self.source {
1430 Source::Agent { run, node } if node == CHAT_NODE => Some(run),
1431 _ => None,
1432 }
1433 }
1434
1435 pub fn issue_ref(&self) -> Option<IssueRef> {
1437 self.issue.clone().or_else(|| match &self.source {
1438 Source::Issue { number, repo } => Some(IssueRef {
1439 number: *number,
1440 repo: repo.clone(),
1441 }),
1442 _ => None,
1443 })
1444 }
1445
1446 pub fn source_label(&self) -> String {
1448 let actor = self.source.label();
1449 match &self.issue {
1450 Some(issue) if self.source == Source::Human => format!("issue #{}", issue.number),
1451 Some(issue) => format!("{actor} · issue #{}", issue.number),
1452 None => actor,
1453 }
1454 }
1455
1456 pub fn chat_notice_key(&self) -> Option<String> {
1459 match self.status {
1460 TaskStatus::Done => Some(
1461 self.completion_history
1462 .iter()
1463 .rev()
1464 .find(|event| event.action == CompletionAction::Complete)
1465 .map_or_else(
1466 || "done".to_owned(),
1467 |event| format!("done:{}", event.occurrence),
1468 ),
1469 ),
1470 TaskStatus::Held => {
1471 let cause = self
1472 .hold_notice_cause
1473 .clone()
1474 .unwrap_or_else(|| self.unresolved_hold_cause());
1475 Some(format!(
1476 "cause:{}",
1477 serde_json::to_string(&cause).expect("cause")
1478 ))
1479 }
1480 TaskStatus::Blocked => {
1481 let ids: std::collections::BTreeSet<_> = self.blocked_by.iter().collect();
1482 let evidence = self
1485 .hold_notice_cause
1486 .as_ref()
1487 .filter(|c| c.stage.starts_with("conductor-evidence:"));
1488 Some(format!(
1489 "dependencies:{}",
1490 serde_json::to_string(&(ids, evidence)).expect("ids")
1491 ))
1492 }
1493 _ => None,
1494 }
1495 }
1496
1497 fn unresolved_hold_cause(&self) -> NoticeCause {
1498 NoticeCause {
1499 stage: "hold".into(),
1500 target: None,
1501 run: self.runs.last().cloned(),
1502 pass: None,
1503 }
1504 }
1505
1506 pub(crate) fn legacy_chat_notice_key(&self) -> Option<String> {
1508 let key = match self.status {
1509 TaskStatus::Held if self.hold_notice_cause.is_none() => Some(format!(
1510 "held#{}",
1511 self.held_at.map(|t| t.to_string()).unwrap_or_default()
1512 )),
1513 TaskStatus::Blocked => Some(format!(
1514 "blocked#{}#{}",
1515 self.blocked_by.join(","),
1516 self.block_reason.as_deref().unwrap_or_default()
1517 )),
1518 _ => None,
1519 };
1520 key.filter(|key| self.legacy_notice_matches(key))
1521 }
1522
1523 pub(crate) fn legacy_notice_matches(&self, key: &str) -> bool {
1524 match self.status {
1525 TaskStatus::Held if self.hold_notice_cause.is_none() => key
1526 .strip_prefix("held#")
1527 .is_some_and(|time| time.is_empty() || time.parse::<Timestamp>().is_ok()),
1528 TaskStatus::Blocked
1529 if self
1530 .hold_notice_cause
1531 .as_ref()
1532 .is_none_or(|c| !c.stage.starts_with("conductor-evidence:")) =>
1533 {
1534 key.strip_prefix("blocked#").is_some_and(|tail| {
1535 let Some((ids, _)) = tail.split_once('#') else {
1536 return false;
1537 };
1538 let old: std::collections::BTreeSet<_> =
1539 ids.split(',').filter(|id| !id.is_empty()).collect();
1540 let current: std::collections::BTreeSet<_> =
1541 self.blocked_by.iter().map(String::as_str).collect();
1542 old == current
1543 })
1544 }
1545 _ => false,
1546 }
1547 }
1548
1549 fn import_chat_notice(&mut self) {
1550 if let Some(n) = &self.chat_notice {
1551 let key = if is_done_notice_key(&n.key) {
1552 "done".to_owned()
1553 } else if self.legacy_notice_matches(&n.key) {
1554 self.chat_notice_key().unwrap_or_else(|| n.key.clone())
1555 } else {
1556 n.key.clone()
1557 };
1558 if !self.chat_notices.contains(&key) {
1559 self.chat_notices.push(key);
1560 }
1561 }
1562 }
1563
1564 pub(crate) fn notice_cause(&mut self, stage: &str, run: Option<&str>, pass: Option<usize>) {
1567 self.import_chat_notice();
1568 self.hold_notice_cause = Some(NoticeCause {
1569 stage: stage.to_owned(),
1570 target: None,
1571 run: run.map(str::to_owned),
1572 pass,
1573 });
1574 }
1575
1576 pub(crate) fn startup_notice_cause(&mut self, stage: &str) {
1579 let recovery_only = matches!(
1580 stage,
1581 "startup-source" | "startup-candidates" | "startup-public-head"
1582 );
1583 match self.hold_notice_cause.as_ref() {
1584 Some(cause) if recovery_only && !cause.stage.starts_with("startup-") => return,
1585 None if recovery_only
1586 && self
1587 .chat_notice
1588 .as_ref()
1589 .is_some_and(|n| !is_done_notice_key(&n.key)) =>
1590 {
1591 return;
1592 }
1593 _ => {}
1594 }
1595 self.notice_cause(stage, None, None);
1596 }
1597
1598 pub(crate) fn fail_startup(
1601 &mut self,
1602 stage: &str,
1603 why: impl Into<String>,
1604 max_attempts: usize,
1605 ) {
1606 let unresolved = self.hold_notice_cause.clone();
1607 self.fail(why, max_attempts);
1608 self.hold_notice_cause = unresolved;
1609 self.startup_notice_cause(stage);
1610 }
1611
1612 pub(crate) fn fail_startup_target(
1614 &mut self,
1615 stage: &str,
1616 target: String,
1617 why: impl Into<String>,
1618 max_attempts: usize,
1619 ) {
1620 self.fail_startup(stage, why, max_attempts);
1621 if let Some(cause) = self.hold_notice_cause.as_mut() {
1622 cause.target = Some(target);
1623 }
1624 }
1625
1626 pub fn chat_notice_due(&self) -> Option<String> {
1628 self.filed_by_chat()?;
1629 if self.schema < 13 {
1630 return None;
1631 }
1632 let key = self.chat_notice_key()?;
1633 if self.chat_notices.contains(&key) {
1634 return None;
1635 }
1636 match &self.chat_notice {
1637 Some(n)
1638 if n.key == key
1639 || (key == "done" && is_done_notice_key(&n.key))
1640 || self.legacy_notice_matches(&n.key) =>
1641 {
1642 None
1643 }
1644 _ => Some(key),
1645 }
1646 }
1647
1648 pub fn short(&self) -> &str {
1650 short(&self.id)
1651 }
1652
1653 pub fn mark_triage_applied(&mut self, question_id: &str) {
1655 if !self.triage_applied(question_id) {
1656 self.triage_applied.push(question_id.to_owned());
1657 }
1658 }
1659
1660 pub fn action_applied(&self, question_id: &str) -> bool {
1663 self.actions_applied.iter().any(|id| id == question_id)
1664 }
1665
1666 pub fn mark_action_applied(&mut self, question_id: &str) {
1668 if !self.action_applied(question_id) {
1669 self.actions_applied.push(question_id.to_owned());
1670 }
1671 }
1672
1673 pub fn triage_applied(&self, question_id: &str) -> bool {
1675 self.triage_applied.iter().any(|id| id == question_id)
1676 }
1677
1678 pub fn start(&mut self, run: String) {
1691 self.stamp_schema();
1692 self.status = TaskStatus::Running;
1693 self.attempts += 1;
1694 self.runs.retain(|id| id != &run);
1695 if let Some(pin) = &self.resume_override
1696 && pin.pinned_run.as_ref() == Some(&run)
1697 && !pin.question_id.is_empty()
1698 {
1699 self.dispatched_resumes
1700 .insert(pin.question_id.clone(), run.clone());
1701 }
1702 self.runs.push(run);
1703 self.last_error = None;
1704 self.park_reason = None;
1705 self.fresh_start = false;
1706 self.interrupt = false;
1707 self.resume_override = None;
1709 self.disk_resume_run = None;
1712 }
1713
1714 pub fn record_startup_failure(&mut self, failure: crate::run::StartupFailure) {
1716 if !self.startup_failures.iter().any(|f| f.run == failure.run) {
1717 self.startup_failures.push(failure);
1718 }
1719 }
1720
1721 pub fn link_run(&mut self, run: &str) -> bool {
1726 if self.runs.iter().any(|r| r == run) {
1727 return false;
1728 }
1729 self.runs.push(run.to_owned());
1730 true
1731 }
1732
1733 pub fn succeed(&mut self, context: CompletionContext) {
1743 if self.status == TaskStatus::Done {
1744 return;
1745 }
1746 self.record_completion(CompletionAction::Complete, context);
1747 self.stamp_schema();
1748 self.status = TaskStatus::Done;
1749 if let Some(pin) = self.resume_override.take()
1750 && !pin.question_id.is_empty()
1751 && let Some(run) = pin.pinned_run
1752 {
1753 self.superseded_resumes.insert(pin.question_id, run);
1756 }
1757 self.sync_only = None;
1758 self.last_error = None;
1759 self.park_reason = None;
1760 self.hold_reason = None;
1761 self.hold_source = None;
1762 self.machine_hold_cause = None;
1763 self.disk_resume_run = None;
1764 self.disk_checked_at = None;
1765 self.diagnostic = None;
1766 self.blocked_by.clear();
1767 self.block_reason = None;
1768 self.blocked_from = None;
1769 }
1770
1771 pub fn already_landed(&mut self, note: impl Into<String>, mut context: CompletionContext) {
1779 let note = note.into();
1780 if context.reason.is_none() {
1781 context.reason = Some(note.clone());
1782 }
1783 self.succeed(context);
1784 self.attempts = self.attempts.saturating_sub(1);
1785 self.last_error = Some(note);
1786 }
1787
1788 fn record_completion(&mut self, action: CompletionAction, context: CompletionContext) {
1789 self.completion_history.push(CompletionEvent {
1790 occurrence: format!(
1791 "{}-{:016x}{:016x}",
1792 Timestamp::now(),
1793 crate::rng::entropy(),
1794 crate::rng::entropy()
1795 ),
1796 action,
1797 actor: context.actor,
1798 reason: context.reason,
1799 discard: context.discard,
1800 prior_status: self.status,
1801 at: Timestamp::now(),
1802 prior_hold_reason: self.hold_reason.clone(),
1803 prior_block_reason: self.block_reason.clone(),
1804 prior_error: self.last_error.clone(),
1805 run: context.run,
1806 unavailable_runs: context.unavailable_runs,
1807 });
1808 self.stamp_schema();
1809 }
1810
1811 pub fn reopen(&mut self, context: CompletionContext) -> Result<()> {
1814 anyhow::ensure!(
1815 self.status == TaskStatus::Done,
1816 "only a done task can be reopened"
1817 );
1818 anyhow::ensure!(
1819 context
1820 .reason
1821 .as_deref()
1822 .is_some_and(|reason| !reason.trim().is_empty()),
1823 "reopen requires a non-empty reason"
1824 );
1825 let reason = context.reason.clone();
1826 self.record_completion(CompletionAction::Reopen, context);
1827 self.hold_manual(reason);
1828 self.resume_override = None;
1829 self.fresh_start = false;
1830 self.last_error = None;
1831 self.diagnostic = None;
1832 Ok(())
1833 }
1834
1835 pub fn superseded_attempts(&self, last_run_succeeded: bool) -> &[String] {
1865 if self.status != TaskStatus::Done || !last_run_succeeded || self.execution_runs().len() < 2
1866 {
1867 return &[];
1868 }
1869 &self.execution_runs()[..self.execution_runs().len() - 1]
1870 }
1871
1872 pub fn successor_of(&self, run: &str) -> Option<&String> {
1880 let runs = self.execution_runs();
1881 let pos = runs.iter().rposition(|r| r == run)?;
1882 runs.get(pos + 1)
1883 }
1884
1885 pub fn earlier_attempts(&self) -> &[String] {
1892 self.execution_runs()
1893 }
1894
1895 fn preserve_legacy_build_cache(&mut self) {
1896 if self.schema < 23 {
1897 let overrides = self.overrides.get_or_insert_with(|| RunOverrides {
1898 inherit_daemon_options: true,
1899 ..RunOverrides::default()
1900 });
1901 overrides.build_cache.get_or_insert(BuildCache::Shared);
1902 }
1903 }
1904
1905 fn stamp_schema(&mut self) {
1910 self.preserve_legacy_build_cache();
1911 if self.schema < RECOVERY_HOLD_SCHEMA && self.recovery_budget_hold.is_none() {
1912 self.recovery_budget_hold = self.legacy_recovery_budget_hold();
1913 }
1914 self.schema = self.schema.max(SCHEMA);
1915 }
1916
1917 fn note_held(&mut self) {
1920 self.stamp_schema();
1921 self.recovery_budget_hold = None;
1922 let continuing = self.status == TaskStatus::Held
1923 || (self.status == TaskStatus::Blocked
1924 && (self.blocked_from == Some(TaskStatus::Held)
1925 || (self.blocked_from.is_none()
1926 && (self.hold_reason.is_some() || self.hold_source.is_some()))));
1927 if !continuing || self.held_at.is_none() {
1928 self.held_at = Some(Timestamp::now());
1929 }
1930 }
1931
1932 pub fn fail(&mut self, why: impl Into<String>, max_attempts: usize) {
1948 let why = why.into();
1949 if self.status == TaskStatus::Running {
1950 let run = self.runs.last().cloned();
1951 self.notice_cause("run-failed", run.as_deref(), Some(self.attempts));
1952 }
1953 self.diagnostic = None;
1954 self.park_reason = None;
1955 self.status = if self.attempts >= self.effective_attempt_limit(max_attempts) {
1956 self.note_held();
1957 self.hold_source = Some(HoldSource::Machine);
1958 self.machine_hold_cause = None;
1959 self.disk_resume_run = None;
1960 self.disk_checked_at = None;
1961 self.hold_reason = Some(why.clone());
1962 TaskStatus::Held
1963 } else {
1964 TaskStatus::Failed
1965 };
1966 self.last_error = Some(why);
1967 }
1968
1969 pub fn stall(&mut self, why: impl Into<String>) {
1979 self.last_error = Some(why.into());
1980 self.diagnostic = None;
1981 self.attempts = self.attempts.saturating_sub(1);
1982 self.status = TaskStatus::Failed;
1983 }
1984
1985 pub fn park(&mut self, why: impl Into<String>) {
1991 self.diagnostic = None;
1992 self.attempts = self.attempts.saturating_sub(1);
1993 self.status = TaskStatus::Parked;
1994 self.park_reason = Some(why.into());
1995 self.stamp_schema();
1998 }
1999
2000 pub fn record_pass(
2002 &mut self,
2003 run: &str,
2004 pass_index: usize,
2005 attempts_before: usize,
2006 parked: Option<crate::run::ParkCause>,
2007 ) {
2008 self.record_pass_at(run, pass_index, None, attempts_before, parked);
2009 }
2010
2011 pub fn record_pass_at(
2014 &mut self,
2015 run: &str,
2016 pass_index: usize,
2017 started_at: Option<Timestamp>,
2018 attempts_before: usize,
2019 parked: Option<crate::run::ParkCause>,
2020 ) {
2021 if self
2022 .passes
2023 .iter()
2024 .any(|p| p.run == run && p.pass_index == pass_index)
2025 {
2026 return;
2027 }
2028 let cost = if self.attempts < attempts_before {
2029 PassCost::Refunded
2030 } else {
2031 PassCost::Spent
2032 };
2033 self.passes.push(TaskPass {
2034 run: run.to_owned(),
2035 pass_index,
2036 started_at: self.dispatched_at.or(started_at),
2037 cost,
2038 attempts_after: self.attempts,
2039 settled_at: Timestamp::now(),
2040 parked,
2041 });
2042 self.stamp_schema();
2043 }
2044
2045 pub(crate) fn upgrade_resume_key(&self) -> Option<(Timestamp, &str)> {
2048 if self.status != TaskStatus::Parked || self.fresh_start {
2049 return None;
2050 }
2051 let pass = self.passes.last()?;
2052 if self.execution_runs().last() != Some(&pass.run)
2053 || !matches!(pass.parked, Some(crate::run::ParkCause::Upgrade { .. }))
2054 {
2055 return None;
2056 }
2057 Some((pass.started_at.unwrap_or(pass.settled_at), &self.id))
2060 }
2061
2062 pub fn operator_held(&self) -> bool {
2068 self.status == TaskStatus::Held && !matches!(self.hold_source, Some(HoldSource::Machine))
2069 }
2070
2071 pub fn hold_manual(&mut self, reason: Option<String>) {
2081 self.operator_decided_at = Some(Timestamp::now());
2083 if self.status != TaskStatus::Running && self.sync_only.take().is_some() {
2084 self.resume_override = None;
2085 }
2086 self.hold_unrequested_retry(reason);
2087 }
2088
2089 pub(crate) fn hold_unrequested_retry(&mut self, reason: Option<String>) {
2092 self.park_reason = None;
2093 self.note_held();
2094 self.status = TaskStatus::Held;
2095 if reason.is_some() {
2096 self.hold_reason = reason;
2097 }
2098 self.hold_source = Some(HoldSource::Manual);
2099 self.machine_hold_cause = None;
2100 self.disk_resume_run = None;
2101 self.disk_checked_at = None;
2102 self.blocked_by.clear();
2103 self.block_reason = None;
2104 self.blocked_from = None;
2105 }
2106
2107 pub(crate) fn hold_after_sync_only(&mut self, reason: String) {
2108 let recovery_hold = self.recovery_budget_hold.take();
2109 self.hold_unrequested_retry(Some(reason));
2110 self.recovery_budget_hold = recovery_hold;
2111 }
2112
2113 pub fn hold_machine(&mut self, reason: Option<String>) {
2118 self.park_reason = None;
2119 self.note_held();
2120 self.status = TaskStatus::Held;
2121 if reason.is_some() {
2122 self.hold_reason = reason;
2123 }
2124 self.hold_source = Some(HoldSource::Machine);
2125 self.machine_hold_cause = None;
2126 self.disk_resume_run = None;
2127 self.disk_checked_at = None;
2128 self.blocked_by.clear();
2129 self.block_reason = None;
2130 self.blocked_from = None;
2131 }
2132
2133 pub(crate) fn mark_disk_capacity(&mut self) {
2135 self.machine_hold_cause = Some(MachineHoldCause::DiskCapacity {
2136 reason: self.hold_reason.clone().unwrap_or_default(),
2137 before_start: false,
2138 });
2139 }
2140
2141 pub(crate) fn mark_startup_disk_capacity(&mut self) {
2142 self.machine_hold_cause = Some(MachineHoldCause::DiskCapacity {
2143 reason: self.hold_reason.clone().unwrap_or_default(),
2144 before_start: true,
2145 });
2146 }
2147
2148 pub(crate) fn disk_wait_run(&self) -> Option<&String> {
2149 if self.has_disk_capacity_cause()
2150 && matches!(
2151 self.machine_hold_cause,
2152 Some(MachineHoldCause::DiskCapacity {
2153 before_start: true,
2154 ..
2155 })
2156 )
2157 {
2158 None
2159 } else {
2160 self.execution_runs().last()
2161 }
2162 }
2163
2164 pub fn has_disk_capacity_cause(&self) -> bool {
2166 matches!(
2167 (&self.machine_hold_cause, self.hold_reason.as_deref()),
2168 (Some(MachineHoldCause::DiskCapacity { reason, .. }), Some(now)) if reason == now
2169 )
2170 }
2171
2172 pub(crate) fn resume_disk_wait(&mut self) {
2174 let retained = self.disk_wait_run().cloned();
2175 self.status = TaskStatus::Queued;
2176 self.held_at = None;
2177 self.hold_source = None;
2178 self.hold_reason = None;
2179 self.machine_hold_cause = None;
2180 self.last_error = None;
2181 self.disk_resume_run = retained;
2182 }
2183
2184 pub(crate) fn hold_head_e2e(
2186 &mut self,
2187 stop: crate::head_e2e_stop::Stop,
2188 reason: String,
2189 last_error: String,
2190 ) {
2191 self.hold_machine(Some(reason));
2192 self.last_error = Some(last_error);
2193 self.machine_hold_cause = Some(MachineHoldCause::HeadE2e { stop });
2194 }
2195
2196 pub(crate) fn head_e2e_notice(&mut self, stop: &crate::head_e2e_stop::Stop) {
2198 if let Some(at) = stop.recorded_at {
2199 self.held_at = Some(at);
2200 }
2201 self.notice_cause(crate::head_e2e_stop::NOTICE_STAGE, Some(&stop.run), None);
2202 if let Some(cause) = &mut self.hold_notice_cause {
2203 cause.target = Some(stop.id.clone());
2204 }
2205 }
2206
2207 pub fn has_head_e2e_cause(&self) -> bool {
2209 matches!(
2210 self.machine_hold_cause,
2211 Some(MachineHoldCause::HeadE2e { .. })
2212 )
2213 }
2214
2215 pub fn head_e2e_stop_id(&self) -> Option<&str> {
2217 if let Some(MachineHoldCause::HeadE2e { stop }) = &self.machine_hold_cause {
2218 return Some(stop.id.as_str());
2219 }
2220 self.hold_notice_cause
2221 .as_ref()
2222 .filter(|c| c.stage == crate::head_e2e_stop::NOTICE_STAGE)
2223 .and_then(|c| c.target.as_deref())
2224 }
2225
2226 pub(crate) fn resume_head_e2e_wait(&mut self) {
2229 self.status = TaskStatus::Queued;
2230 self.held_at = None;
2231 self.hold_source = None;
2232 self.hold_reason = None;
2233 self.machine_hold_cause = None;
2234 self.last_error = None;
2235 self.diagnostic = None;
2236 self.blocked_by.clear();
2237 self.block_reason = None;
2238 self.blocked_from = None;
2239 }
2240
2241 pub fn block(&mut self, blocked_by: Vec<String>, reason: Option<String>) {
2251 self.stamp_schema();
2252 let before: std::collections::BTreeSet<_> = self.blocked_by.iter().collect();
2253 let after: std::collections::BTreeSet<_> = blocked_by.iter().collect();
2254 if self.status != TaskStatus::Blocked || before != after {
2255 self.blocked_at = Some(Timestamp::now());
2256 }
2257 if self.status != TaskStatus::Blocked {
2258 self.blocked_from = Some(self.status);
2259 }
2260 self.status = TaskStatus::Blocked;
2261 self.blocked_by = blocked_by;
2262 self.block_reason = reason;
2263 }
2264
2265 pub fn unblock(&mut self, resolved_id: &str) {
2288 if self.status != TaskStatus::Blocked {
2289 return;
2290 }
2291 self.blocked_by.retain(|id| id != resolved_id);
2292 self.restore_if_unblocked();
2293 }
2294
2295 pub fn dependency_deleted(&mut self, deleted_id: &str) -> bool {
2306 if self.status != TaskStatus::Blocked || !self.blocked_by.iter().any(|b| b == deleted_id) {
2307 return false;
2308 }
2309 self.blocked_by.retain(|id| id != deleted_id);
2310 self.restore_if_unblocked();
2311 true
2312 }
2313
2314 fn restore_if_unblocked(&mut self) {
2318 if self.blocked_by.is_empty() {
2319 self.status = match self.blocked_from {
2320 Some(TaskStatus::Running) => TaskStatus::Queued,
2321 Some(other) => other,
2322 None if self.hold_reason.is_some() || self.hold_source.is_some() => {
2323 TaskStatus::Held
2324 }
2325 None => TaskStatus::Queued,
2326 };
2327 self.block_reason = None;
2328 self.blocked_from = None;
2329 }
2330 }
2331
2332 pub fn record_answer(&mut self, question: String, answer: String) {
2337 self.answers.push(AnsweredQuestion { question, answer });
2338 }
2339
2340 pub fn request_review(&mut self, branch: String) {
2344 self.release();
2345 self.review_branch = Some(branch);
2346 self.review_instruction = Some(self.instruction.clone());
2347 }
2348
2349 pub fn requeue(&mut self) {
2352 self.release();
2353 self.review_branch = None;
2355 self.review_instruction = None;
2356 self.fresh_start = true;
2357 }
2358
2359 pub fn hold_for_handover(&mut self, branch: Option<String>, reason: String) {
2368 if branch.is_some() {
2369 self.review_branch = branch;
2370 self.review_instruction = Some(self.instruction.clone());
2371 }
2372 self.hold_machine(Some(reason));
2373 }
2374
2375 pub fn set_urgent(&mut self, urgent: bool) -> Result<()> {
2377 if !matches!(self.status, TaskStatus::Queued | TaskStatus::Held) {
2378 bail!(
2379 "task {} is {}; urgent can only change while queued or held; \
2380 wait for the active attempt to finish and requeue or hold the task first",
2381 self.short(),
2382 self.status.as_str()
2383 );
2384 }
2385 self.urgent = urgent;
2386 Ok(())
2387 }
2388
2389 pub fn set_immediate(&mut self, immediate: bool) -> Result<()> {
2393 if !matches!(self.status, TaskStatus::Queued | TaskStatus::Held) {
2394 bail!(
2395 "task {} is {}; immediate can only change while queued or held; \
2396 wait for the active attempt to finish and requeue or hold the task first",
2397 self.short(),
2398 self.status.as_str()
2399 );
2400 }
2401 self.immediate = immediate;
2402 Ok(())
2403 }
2404
2405 pub fn set_priority(&mut self, priority: i32) -> Result<()> {
2414 if self.status == TaskStatus::Running {
2415 bail!(
2416 "task {} is running; its priority cannot be changed until \
2417 this attempt finishes",
2418 self.short()
2419 );
2420 }
2421 self.priority = priority;
2422 Ok(())
2423 }
2424
2425 pub fn set_interrupt(&mut self, interrupt: bool) -> Result<()> {
2440 if interrupt && !self.status.runnable() {
2441 bail!(
2442 "task {} is {}; only a queued or failed task can be marked \
2443 to interrupt",
2444 self.short(),
2445 self.status.as_str()
2446 );
2447 }
2448 self.interrupt = interrupt;
2449 Ok(())
2450 }
2451
2452 pub fn effective_attempt_limit(&self, daemon_limit: usize) -> usize {
2454 self.attempt_limit.map_or(daemon_limit, NonZeroUsize::get)
2455 }
2456
2457 pub fn change_attempt_limit(&mut self, limit: Option<NonZeroUsize>) -> Result<()> {
2460 if !matches!(self.status, TaskStatus::Queued | TaskStatus::Held) {
2461 bail!("only queued or held tasks can change the attempt limit");
2462 }
2463 self.stamp_schema();
2464 self.attempt_limit = limit;
2465 Ok(())
2466 }
2467
2468 pub fn implementers(&self) -> Option<usize> {
2470 if self.solo {
2471 Some(1)
2472 } else {
2473 self.overrides.as_ref().and_then(|o| o.candidates)
2474 }
2475 }
2476
2477 pub fn build_cache_override(
2482 &self,
2483 config: &crate::config::Config,
2484 ) -> Option<(BuildCache, &'static str)> {
2485 self.overrides
2486 .as_ref()
2487 .and_then(|o| o.build_cache)
2488 .map(|mode| (mode, "task-override"))
2489 .or_else(|| {
2490 ((self.immediate || self.urgent) && crate::build_target::urgent_isolation(config))
2491 .then_some((
2492 BuildCache::Isolated,
2493 if self.immediate {
2494 "immediate"
2495 } else {
2496 "urgent"
2497 },
2498 ))
2499 })
2500 }
2501
2502 pub fn change_build_cache(&mut self, mode: Option<BuildCache>) -> Result<()> {
2505 if !matches!(self.status, TaskStatus::Queued | TaskStatus::Held) {
2506 bail!(
2507 "task {} is {}; only queued or held tasks can change build cache",
2508 self.short(),
2509 self.status.as_str()
2510 );
2511 }
2512 self.stamp_schema();
2513 if self.overrides.is_some() || mode.is_some() {
2514 let overrides = self.overrides.get_or_insert_with(|| RunOverrides {
2515 inherit_daemon_options: true,
2516 ..RunOverrides::default()
2517 });
2518 overrides.build_cache = mode;
2519 }
2520 Ok(())
2521 }
2522
2523 pub fn change_implementers(&mut self, count: u8) -> Result<()> {
2526 self.check_implementers_editable()?;
2527 let explicit = self.overrides.as_ref().and_then(|o| o.config.as_deref());
2528 let (mut config, _) = crate::config::Config::discover(&self.repo, explicit)?;
2529 if let Some(o) = &self.overrides {
2530 o.apply(&mut config);
2531 }
2532 self.set_implementers(count, &config)
2533 }
2534
2535 fn check_implementers_editable(&self) -> Result<()> {
2536 if !matches!(self.status, TaskStatus::Queued | TaskStatus::Held) {
2537 bail!(
2538 "task {} is {}; only queued or held tasks can change implementers",
2539 self.short(),
2540 self.status.as_str()
2541 );
2542 }
2543 Ok(())
2544 }
2545
2546 pub fn set_implementers(&mut self, count: u8, config: &crate::config::Config) -> Result<()> {
2548 self.check_implementers_editable()?;
2549 crate::talk::check_implementers(count, config).map_err(anyhow::Error::msg)?;
2550 self.stamp_schema();
2551 self.solo = count == 1;
2552 let mut overrides = self.overrides.clone().unwrap_or_else(|| RunOverrides {
2553 inherit_daemon_options: true,
2554 ..Default::default()
2555 });
2556 overrides.candidates = (count > 1).then_some(usize::from(count));
2557 let mut settings = overrides.clone();
2558 settings.inherit_daemon_options = false;
2559 self.overrides = if overrides.inherit_daemon_options && settings == RunOverrides::default()
2561 {
2562 None
2563 } else {
2564 Some(overrides)
2565 };
2566 Ok(())
2567 }
2568
2569 pub fn edit(&mut self, title: String, instruction: String) -> Result<()> {
2581 if !matches!(self.status, TaskStatus::Queued | TaskStatus::Held) {
2582 bail!(
2583 "task {} is {}; only a queued or held task's instruction can \
2584 be edited",
2585 self.short(),
2586 self.status.as_str()
2587 );
2588 }
2589 if self.review_branch.is_some() && self.review_instruction.is_none() {
2592 self.review_instruction = Some(self.instruction.clone());
2593 }
2594 if self.instruction != instruction {
2595 self.resume_override = None;
2598 }
2599 if self.status == TaskStatus::Held && self.machine_hold_cause.is_some() {
2600 self.hold_manual(self.hold_reason.clone());
2601 }
2602 self.machine_hold_cause = None;
2603 self.disk_resume_run = None;
2604 self.disk_checked_at = None;
2605 self.title = title;
2606 self.instruction = instruction;
2607 Ok(())
2608 }
2609
2610 pub fn handed_off(&mut self, why: impl Into<String>) {
2630 let why = why.into();
2631 self.diagnostic = None;
2632 self.note_held();
2633 self.status = TaskStatus::Held;
2634 self.hold_source = Some(HoldSource::Machine);
2635 self.machine_hold_cause = None;
2636 self.disk_resume_run = None;
2637 self.disk_checked_at = None;
2638 self.hold_reason = Some(why.clone());
2639 self.last_error = Some(why);
2640 }
2641
2642 pub fn release_operator(&mut self, source: &str, question_id: Option<&str>) {
2644 self.recovery_budget = None;
2645 self.recovery_generations.clear();
2646 self.recovery_admission = None;
2647 if self
2648 .resumption
2649 .as_ref()
2650 .is_some_and(|r| r.instruction != self.instruction)
2651 {
2652 self.resume_override = None;
2655 }
2656 let approval = Resumption {
2657 generation: self.resumption.as_ref().map_or(1, |r| r.generation + 1),
2658 source: source.to_owned(),
2659 question_id: question_id.map(str::to_owned),
2660 at: Timestamp::now(),
2661 instruction: self.instruction.clone(),
2662 answers_through: self.answers.len(),
2663 runs_through: self.runs.len(),
2664 blocking_evidence: Vec::new(),
2665 cleared_reason: self
2666 .hold_reason
2667 .clone()
2668 .or_else(|| self.block_reason.clone()),
2669 };
2670 self.release();
2671 self.operator_decided_at = Some(approval.at);
2672 if let Some(previous) = self.resumption.replace(approval) {
2673 self.resumption_history.push(previous);
2674 }
2675 }
2676
2677 pub(crate) fn recovery_failed(&mut self, state: &crate::run::RunState) {
2679 let (base, inputs) = self.recovery_admission.as_ref().map_or_else(
2680 || (state.base_commit.clone(), recovery_inputs(&state.sources)),
2681 |a| (a.base.clone(), a.inputs.clone()),
2682 );
2683 let progress = recovery_progress(state);
2684 let stage = if state.prep_failure.is_some() {
2685 "preparation"
2686 } else {
2687 "execution"
2688 };
2689 let matches = |b: &RecoveryBudget| {
2690 b.instruction == self.instruction
2691 && b.base == base
2692 && b.inputs == inputs
2693 && (progress.is_none() || b.progress == progress)
2694 };
2695 if !self.recovery_budget.as_ref().is_some_and(matches) {
2696 let previous = self
2697 .recovery_generations
2698 .iter()
2699 .position(matches)
2700 .map(|index| self.recovery_generations.remove(index));
2701 if let Some(old) = self.recovery_budget.take() {
2702 self.recovery_generations.push(old);
2703 }
2704 self.recovery_budget = previous;
2705 }
2706 if let Some(budget) = &mut self.recovery_budget {
2707 budget.failures = budget.failures.saturating_add(1);
2708 budget.stage = stage.to_owned();
2709 } else {
2710 self.recovery_budget = Some(RecoveryBudget {
2711 instruction: self.instruction.clone(),
2712 base,
2713 inputs,
2714 stage: stage.to_owned(),
2715 failures: 1,
2716 progress,
2717 });
2718 }
2719 }
2720
2721 pub(crate) fn recovery_exhausted(
2722 &self,
2723 base: &str,
2724 inputs: &str,
2725 limit: usize,
2726 ) -> Option<String> {
2727 let same_input = |b: &&RecoveryBudget| {
2728 b.instruction == self.instruction && b.base == base && b.inputs == inputs
2729 };
2730 let budget = self
2731 .recovery_budget
2732 .as_ref()
2733 .filter(same_input)
2734 .or_else(|| self.recovery_generations.iter().rev().find(same_input))?;
2735 (budget.failures >= limit.max(1)).then(|| budget.budget_reason())
2736 }
2737
2738 pub(crate) fn hold_recovery_budget(&mut self, reason: String, admission: RecoveryAdmission) {
2739 self.hold_unrequested_retry(Some(reason));
2740 if let Some(pass) = self.passes.last()
2741 && self.execution_runs().last() == Some(&pass.run)
2742 {
2743 self.recovery_budget_hold = Some(RecoveryBudgetHold {
2744 admission,
2745 run: pass.run.clone(),
2746 pass: pass.pass_index,
2747 held_at: self.held_at.expect("hold timestamp just recorded"),
2748 decision: self.operator_decided_at,
2749 legacy: false,
2750 });
2751 }
2752 }
2753
2754 fn matches_budget_hold(&self, admission: &RecoveryAdmission) -> bool {
2755 self.status == TaskStatus::Held
2756 && self.hold_source == Some(HoldSource::Manual)
2757 && self.machine_hold_cause.is_none()
2758 && self.recovery_budget.as_ref().is_some_and(|budget| {
2759 budget.instruction == self.instruction
2760 && budget.base == admission.base
2761 && budget.inputs == admission.inputs
2762 && budget.stage == "execution"
2763 && budget.failures > 0
2764 && self
2765 .hold_reason
2766 .as_ref()
2767 .is_some_and(|reason| *reason == budget.budget_reason())
2768 })
2769 }
2770
2771 fn legacy_recovery_budget_hold(&self) -> Option<RecoveryBudgetHold> {
2772 let held_at = self.held_at?;
2773 let settled = self.passes.last()?;
2774 let admission = self.recovery_admission.as_ref()?;
2775 if !self.matches_budget_hold(admission)
2776 || self.execution_runs().last() != Some(&settled.run)
2777 || settled.cost != PassCost::Spent
2778 || settled.parked.is_some()
2779 || settled.settled_at > held_at
2780 || self.operator_decided_at.is_some_and(|at| at >= held_at)
2781 {
2782 return None;
2783 }
2784 Some(RecoveryBudgetHold {
2785 admission: admission.clone(),
2786 run: settled.run.clone(),
2787 pass: settled.pass_index,
2788 held_at,
2789 decision: self.operator_decided_at,
2790 legacy: true,
2791 })
2792 }
2793
2794 pub(crate) fn held_for_recovery_budget(&self, run: &crate::run::RunState) -> bool {
2795 let (Some(held_at), Some(settled), Some(pass), Some(admission)) = (
2796 self.held_at,
2797 self.passes.last(),
2798 run.passes.last(),
2799 self.recovery_admission.as_ref(),
2800 ) else {
2801 return false;
2802 };
2803 if !self.matches_budget_hold(admission)
2804 || self.execution_runs().last() != Some(&run.id)
2805 || settled.run != run.id
2806 || settled.pass_index != pass.index
2807 || settled.cost != PassCost::Spent
2808 || settled.parked.is_some()
2809 || settled.settled_at < pass.started_at
2810 || settled.settled_at > held_at
2811 || self.operator_decided_at.is_some_and(|at| at >= held_at)
2812 || !crate::daemon::compatible_run_instruction(run, self)
2813 {
2814 return false;
2815 }
2816 match &self.recovery_budget_hold {
2817 Some(hold) => {
2818 hold.run == run.id
2819 && hold.pass == pass.index
2820 && hold.held_at == held_at
2821 && hold.decision == self.operator_decided_at
2822 && &hold.admission == admission
2823 && (!hold.legacy
2824 || self
2825 .operator_decided_at
2826 .is_none_or(|at| at < pass.started_at))
2827 }
2828 None => {
2829 self.schema < RECOVERY_HOLD_SCHEMA
2830 && self
2831 .operator_decided_at
2832 .is_none_or(|at| at < pass.started_at)
2833 }
2834 }
2835 }
2836
2837 pub(crate) fn queue_repair(&mut self, receipt: &crate::repair_budget::Receipt) {
2838 self.stamp_schema();
2839 self.repair_grants.push(receipt.clone());
2840 self.status = TaskStatus::Queued;
2841 self.hold_source = None;
2842 self.hold_reason = None;
2843 self.held_at = None;
2844 self.recovery_budget_hold = None;
2845 self.resume_override = Some(OperatorResume {
2846 question_id: String::new(),
2847 at: receipt.at,
2848 conductor_rehold: None,
2849 forced: true,
2850 pinned_run: Some(receipt.request.run.clone()),
2851 });
2852 }
2853
2854 pub fn release(&mut self) {
2858 self.import_chat_notice();
2861 if self.hold_notice_cause.is_none()
2862 && matches!(self.status, TaskStatus::Held | TaskStatus::Blocked)
2863 {
2864 self.hold_notice_cause = Some(self.unresolved_hold_cause());
2865 }
2866 let refused_handover = self.status == TaskStatus::Held
2867 && self.hold_source == Some(HoldSource::Machine)
2868 && self.review_branch.is_some()
2869 && self
2870 .review_instruction
2871 .as_ref()
2872 .is_none_or(|i| *i == self.instruction);
2873 self.status = TaskStatus::Queued;
2874 self.held_at = None;
2875 self.attempts = 0;
2876 self.last_error = None;
2877 self.park_reason = None;
2878 self.hold_reason = None;
2881 self.hold_source = None;
2882 self.machine_hold_cause = None;
2883 self.disk_resume_run = None;
2884 self.disk_checked_at = None;
2885 self.diagnostic = None;
2886 self.blocked_by.clear();
2891 self.block_reason = None;
2892 self.blocked_from = None;
2893 if !refused_handover {
2897 self.review_branch = None;
2898 self.review_instruction = None;
2899 }
2900 self.fresh_start = false;
2901 }
2902}
2903
2904fn copy_new(dir: &Path, src: &Path, name: &str) -> Result<(String, PathBuf)> {
2908 use std::io::ErrorKind;
2909 let (stem, ext) = match name.rfind('.') {
2910 Some(i) if i > 0 => (&name[..i], &name[i..]),
2911 _ => (name, ""),
2912 };
2913 for n in 1u32.. {
2914 let candidate = if n == 1 {
2915 name.to_owned()
2916 } else {
2917 let suffix = format!("-{n}");
2918 let room = 64usize.saturating_sub(suffix.len() + ext.len());
2919 let stem: String = stem.chars().take(room).collect();
2920 format!("{stem}{suffix}{ext}")
2921 };
2922 if !crate::ask::valid_asset_name(&candidate) {
2923 bail!("no valid attachment name is left for `{name}`");
2924 }
2925 let path = dir.join(&candidate);
2926 match std::fs::OpenOptions::new()
2927 .write(true)
2928 .create_new(true)
2929 .open(&path)
2930 {
2931 Ok(mut out) => {
2932 let copied = std::fs::File::open(src)
2933 .and_then(|mut input| std::io::copy(&mut input, &mut out));
2934 if let Err(e) = copied {
2935 drop(out);
2936 let _ = std::fs::remove_file(&path);
2937 return Err(e).with_context(|| format!("copy {}", src.display()));
2938 }
2939 return Ok((candidate, path));
2940 }
2941 Err(e) if e.kind() == ErrorKind::AlreadyExists => continue,
2942 Err(e) => return Err(e).with_context(|| format!("create {}", path.display())),
2943 }
2944 }
2945 unreachable!("the counter never runs out")
2946}
2947
2948const TASK_LOCK_STALE: std::time::Duration = std::time::Duration::from_secs(10);
2951
2952pub(crate) struct TaskLock {
2955 path: PathBuf,
2956 token: String,
2957}
2958
2959fn owner_token() -> String {
2962 static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
2963 let n = COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2964 let mut r = crate::rng::SplitMix64::new(crate::rng::entropy() ^ n.rotate_left(32));
2965 format!("{}-{:016x}", std::process::id(), r.next_u64())
2966}
2967
2968fn break_marker(path: &Path, token: &str) -> PathBuf {
2971 let mut h: u64 = 0xcbf29ce484222325;
2972 for b in token.bytes() {
2973 h ^= u64::from(b);
2974 h = h.wrapping_mul(0x100000001b3);
2975 }
2976 let mut name = path.as_os_str().to_owned();
2977 name.push(format!(".break-{h:016x}"));
2978 PathBuf::from(name)
2979}
2980
2981fn older_than_stale(path: &Path) -> bool {
2982 std::fs::metadata(path)
2983 .and_then(|m| m.modified())
2984 .ok()
2985 .and_then(|t| t.elapsed().ok())
2986 .is_some_and(|age| age > TASK_LOCK_STALE)
2987}
2988
2989fn writer_may_be_gone(token: &str) -> bool {
2990 let Some(pid) = token
2991 .split_once('-')
2992 .and_then(|(pid, _)| pid.parse::<u32>().ok())
2993 else {
2994 return true;
2997 };
2998 if pid == std::process::id() {
2999 return false;
3000 }
3001 crate::proc::pid_status(pid) == Some(false)
3003}
3004
3005const MAX_MARKER_DEPTH: u8 = 3;
3009
3010fn take_marker(
3016 path: &Path,
3017 token: &str,
3018 depth: u8,
3019 retry: crate::lock_file::Retry,
3020) -> Option<(PathBuf, String)> {
3021 use std::io::Write;
3022 let marker = break_marker(path, token);
3023 for _ in 0..2 {
3024 match retry.create(&marker) {
3025 Ok(mut f) => {
3026 let mine = owner_token();
3027 if f.write_all(mine.as_bytes()).is_err() {
3028 drop(f);
3029 let _ = std::fs::remove_file(&marker);
3030 return None;
3031 }
3032 return Some((marker, mine));
3033 }
3034 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
3035 let judged = std::fs::read_to_string(&marker).ok();
3036 match judged.filter(|_| older_than_stale(&marker)) {
3037 Some(judged) if depth < MAX_MARKER_DEPTH => {
3038 remove_lock_if(&marker, &judged, true, depth + 1, retry)?;
3039 }
3040 _ => return None,
3041 }
3042 }
3043 Err(_) => return None,
3044 }
3045 }
3046 None
3047}
3048
3049fn remove_lock_if(
3054 path: &Path,
3055 token: &str,
3056 require_stale: bool,
3057 depth: u8,
3058 retry: crate::lock_file::Retry,
3059) -> Option<bool> {
3060 let (marker, mine) = take_marker(path, token, depth, retry)?;
3061 let still = std::fs::read_to_string(path).is_ok_and(|c| c == token)
3062 && (!require_stale || older_than_stale(path) && writer_may_be_gone(token));
3063 if still {
3064 let _ = std::fs::remove_file(path);
3065 }
3066 if depth >= MAX_MARKER_DEPTH {
3068 if std::fs::read_to_string(&marker).is_ok_and(|c| c == mine) {
3069 let _ = std::fs::remove_file(&marker);
3070 }
3071 } else {
3072 let _ = remove_lock_if(&marker, &mine, false, depth + 1, retry);
3073 }
3074 Some(still)
3075}
3076
3077#[cfg(test)]
3080fn break_stale(path: &Path, judged: &str) -> bool {
3081 break_stale_with(path, judged, crate::lock_file::Retry::new(None))
3082}
3083
3084fn break_stale_with(path: &Path, judged: &str, retry: crate::lock_file::Retry) -> bool {
3085 remove_lock_if(path, judged, true, 0, retry).unwrap_or(false)
3086}
3087
3088impl Drop for TaskLock {
3089 fn drop(&mut self) {
3090 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2);
3091 let retry = crate::lock_file::Retry::new(Some(deadline));
3092 loop {
3093 match remove_lock_if(&self.path, &self.token, false, 0, retry) {
3094 Some(_) => return,
3095 None if std::time::Instant::now() > deadline => return,
3096 None => std::thread::sleep(std::time::Duration::from_millis(5)),
3097 }
3098 }
3099 }
3100}
3101
3102#[derive(Debug, thiserror::Error)]
3103#[error("task changed during completion decision; reload and inspect it")]
3104pub(crate) struct CompletionSnapshotChanged;
3105
3106#[derive(Debug, Clone)]
3108pub struct Queue {
3109 root: PathBuf,
3110 ids: IdSource,
3111}
3112
3113fn validate_attachments(sources: &[PathBuf]) -> Result<Vec<(&PathBuf, &str)>> {
3114 let mut wanted = Vec::new();
3115 for src in sources {
3116 let name = src
3117 .file_name()
3118 .and_then(|n| n.to_str())
3119 .with_context(|| format!("`{}` has no usable file name", src.display()))?;
3120 if !crate::ask::valid_asset_name(name) {
3121 bail!(
3122 "attachment name `{name}` must match ^[A-Za-z0-9][A-Za-z0-9._-]{{0,63}}$ \
3123 with no `..`; rename the file and try again"
3124 );
3125 }
3126 if !src.is_file() {
3127 bail!("attachment `{}` is not a file", src.display());
3128 }
3129 wanted.push((src, name));
3130 }
3131 Ok(wanted)
3132}
3133
3134impl Queue {
3135 pub fn open() -> Self {
3137 Self::at(crate::run::home().join("queue"))
3138 }
3139
3140 pub fn at(root: PathBuf) -> Self {
3143 Self {
3144 root,
3145 ids: IdSource::new(new_id),
3146 }
3147 }
3148
3149 #[doc(hidden)]
3152 pub fn with_id_source(mut self, f: impl Fn() -> String + Send + Sync + 'static) -> Self {
3153 self.ids = IdSource::custom(f);
3154 self
3155 }
3156
3157 fn file_with(
3168 &self,
3169 task: &mut Task,
3170 hook: impl FnMut(&mut Task) -> Result<bool>,
3171 undo: impl FnMut(&mut Task),
3172 ) -> Result<()> {
3173 self.reserve_id(task, hook, undo, true)
3174 }
3175
3176 fn reserve_id(
3184 &self,
3185 task: &mut Task,
3186 mut hook: impl FnMut(&mut Task) -> Result<bool>,
3187 mut undo: impl FnMut(&mut Task),
3188 store: bool,
3189 ) -> Result<()> {
3190 let redraw_first = self.ids.is_custom() && task.attachments.is_empty();
3191 let initial = task.id.clone();
3192 self.ids
3193 .reserve((!redraw_first).then_some(initial.as_str()), "task", |id| {
3194 task.id = id.to_owned();
3195 let _lock = self.lock_task(&task.id)?;
3196 if path_exists(&self.path_of(&task.id))? || !hook(task)? {
3197 return Ok(false);
3198 }
3199 if store {
3200 if let Err(e) = self.write_record(task) {
3201 undo(task);
3202 return Err(e);
3203 }
3204 task.unfiled = false;
3205 }
3206 Ok(true)
3207 })?;
3208 Ok(())
3209 }
3210
3211 fn id_in_use(&self, id: &str, check_attachments: bool) -> Result<bool> {
3216 if path_exists(&self.lock_path(id))? {
3217 return Ok(true);
3218 }
3219 Ok(check_attachments && path_exists(&self.attachments_dir(id))?)
3220 }
3221
3222 fn plain_filing_hook(&self, task: &Task) -> Result<bool> {
3226 Ok(!self.id_in_use(&task.id, task.attachments.is_empty())?)
3227 }
3228
3229 pub fn file_claimed(&self, task: &mut Task) -> Result<Claim> {
3232 let mut claim = None;
3233 self.file_with(
3234 task,
3235 |t| {
3236 if self.id_in_use(&t.id, true)? {
3237 return Ok(false);
3238 }
3239 claim = Some(self.claim(&t.id)?);
3240 Ok(true)
3241 },
3242 |_| {},
3243 )?;
3244 claim.context("claim missing after filing")
3245 }
3246
3247 pub fn root(&self) -> &Path {
3249 &self.root
3250 }
3251
3252 pub fn path_of(&self, id: &str) -> PathBuf {
3254 self.root.join(format!("{id}.json"))
3255 }
3256
3257 pub fn attachments_dir(&self, id: &str) -> PathBuf {
3260 self.root.join(format!("{id}.attachments"))
3261 }
3262
3263 pub fn attach(&self, task: &mut Task, sources: &[PathBuf]) -> Result<Vec<String>> {
3274 let wanted = validate_attachments(sources)?;
3275 if task.unfiled && task.attachments.is_empty() {
3276 let names = std::cell::RefCell::new(Vec::new());
3279 self.reserve_id(
3280 task,
3281 |t| {
3282 if self.id_in_use(&t.id, true)? {
3283 return Ok(false);
3284 }
3285 *names.borrow_mut() = self.copy_attachments(t, &wanted)?;
3286 Ok(true)
3287 },
3288 |_| {},
3289 false,
3290 )?;
3291 return Ok(names.into_inner());
3292 }
3293 self.copy_attachments(task, &wanted)
3294 }
3295
3296 fn copy_attachments(
3298 &self,
3299 task: &mut Task,
3300 wanted: &[(&PathBuf, &str)],
3301 ) -> Result<Vec<String>> {
3302 let dir = self.attachments_dir(&task.id);
3303 let existed = dir.is_dir();
3304 std::fs::create_dir_all(&dir).with_context(|| format!("create {}", dir.display()))?;
3305 let mut created: Vec<PathBuf> = Vec::new();
3306 let mut names = Vec::new();
3307 let mut copy_all = || -> Result<()> {
3308 for (src, name) in wanted {
3309 let (stored, path) = copy_new(&dir, src, name)?;
3310 created.push(path);
3311 names.push(stored);
3312 }
3313 Ok(())
3314 };
3315 if let Err(e) = copy_all() {
3316 for path in &created {
3317 let _ = std::fs::remove_file(path);
3318 }
3319 if !existed {
3320 let _ = std::fs::remove_dir(&dir);
3321 }
3322 return Err(e);
3323 }
3324 task.attachments.extend(names.iter().cloned());
3325 Ok(names)
3326 }
3327
3328 pub fn attach_and_put(&self, task: &mut Task, sources: &[PathBuf]) -> Result<Vec<String>> {
3339 if task.unfiled && task.attachments.is_empty() {
3340 return self.attach_and_file(task, sources);
3341 }
3342 let dir = self.attachments_dir(&task.id);
3343 let existed = dir.is_dir();
3344 let before = task.attachments.len();
3345 let names = self.attach(task, sources)?;
3346 if let Err(e) = self.put(task) {
3347 for name in &names {
3348 let _ = std::fs::remove_file(dir.join(name));
3349 }
3350 if !existed {
3351 let _ = std::fs::remove_dir(&dir);
3352 }
3353 task.attachments.truncate(before);
3354 return Err(e);
3355 }
3356 Ok(names)
3357 }
3358
3359 fn attach_and_file(&self, task: &mut Task, sources: &[PathBuf]) -> Result<Vec<String>> {
3363 let wanted = validate_attachments(sources)?;
3364 let before = task.attachments.len();
3365 let names = std::cell::RefCell::new(Vec::new());
3366 let result = self.file_with(
3367 task,
3368 |t| {
3369 if self.id_in_use(&t.id, true)? {
3370 return Ok(false);
3371 }
3372 *names.borrow_mut() = self.copy_attachments(t, &wanted)?;
3373 Ok(true)
3374 },
3375 |t| {
3376 let dir = self.attachments_dir(&t.id);
3377 for name in names.borrow().iter() {
3378 let _ = std::fs::remove_file(dir.join(name));
3379 }
3380 let _ = std::fs::remove_dir(&dir);
3382 t.attachments.truncate(before);
3383 },
3384 );
3385 result.map(|()| names.into_inner())
3386 }
3387
3388 pub fn attachment_paths(&self, task: &Task) -> Vec<PathBuf> {
3392 let dir = self.attachments_dir(&task.id);
3393 task.attachments
3394 .iter()
3395 .map(|n| {
3396 let p = dir.join(n);
3397 std::path::absolute(&p).unwrap_or(p)
3398 })
3399 .collect()
3400 }
3401
3402 pub fn put(&self, task: &mut Task) -> Result<()> {
3411 if task.unfiled {
3412 return self.file_with(task, |t| self.plain_filing_hook(t), |_| {});
3414 }
3415 let _lock = self.lock_task(&task.id)?;
3416 self.put_unlocked(task)
3417 }
3418
3419 pub fn create_new(&self, task: &mut Task) -> Result<bool> {
3424 let _lock = self.lock_task(&task.id)?;
3425 if path_exists(&self.path_of(&task.id))? {
3426 return Ok(false);
3427 }
3428 self.write_record(task)?;
3429 task.unfiled = false;
3430 Ok(true)
3431 }
3432
3433 fn put_unlocked(&self, task: &mut Task) -> Result<()> {
3435 self.merge_stored(task);
3436 if let Some(boundary) = task.reassignments.last() {
3437 let stored = self.get(&task.id)?;
3438 anyhow::ensure!(
3439 task.reassignments == stored.reassignments
3440 && task.repo == stored.repo
3441 && task.runs.get(..boundary.run_boundary)
3442 == stored.runs.get(..boundary.run_boundary),
3443 "historical repository execution cannot be restarted; reload the task"
3444 );
3445 }
3446 self.write_record(task)
3447 }
3448
3449 pub(crate) fn commit_base_recovery(
3451 &self,
3452 task: &mut Task,
3453 expected: &serde_json::Value,
3454 ) -> Result<()> {
3455 let _lock = self.lock_task(&task.id)?;
3456 anyhow::ensure!(
3457 serde_json::to_value(self.get(&task.id)?)? == *expected,
3458 "task changed during base recovery; inspect the pending authorization"
3459 );
3460 self.put_unlocked(task)
3462 }
3463
3464 pub(crate) fn commit_land_sync_recovery(
3466 &self,
3467 task: &mut Task,
3468 expected: &serde_json::Value,
3469 ) -> Result<()> {
3470 let _lock = self.lock_task(&task.id)?;
3471 anyhow::ensure!(
3472 serde_json::to_value(self.get(&task.id)?)? == *expected,
3473 "task changed during landing base-sync recovery; inspect the pending authorization"
3474 );
3475 self.put_unlocked(task)
3476 }
3477
3478 pub(crate) fn commit_repair_grant(
3479 &self,
3480 task: &mut Task,
3481 expected: &serde_json::Value,
3482 ) -> Result<()> {
3483 let _lock = self.lock_task(&task.id)?;
3484 anyhow::ensure!(
3485 serde_json::to_value(self.get(&task.id)?)? == *expected,
3486 "repair grant refused: task changed during admission"
3487 );
3488 self.write_record(task)
3489 .context(crate::repair_budget::PublicationUnknown)
3490 }
3491
3492 pub(crate) fn commit_disk_wait(&self, task: &mut Task, expected: &Task) -> Result<()> {
3494 let _lock = self.lock_task(&task.id)?;
3495 anyhow::ensure!(
3496 serde_json::to_value(self.get(&task.id)?)? == serde_json::to_value(expected)?,
3497 "task changed during disk monitoring"
3498 );
3499 task.stamp_schema();
3500 self.write_record_inner(task, false)
3501 }
3502
3503 pub(crate) fn commit_reassignment(&self, task: &mut Task, expected: &Task) -> Result<()> {
3505 let _lock = self.lock_task(&task.id)?;
3506 let stored = self.get(&task.id)?;
3507 anyhow::ensure!(
3508 serde_json::to_value(&stored)? == serde_json::to_value(expected)?
3509 && stored.reassignments.len() + 1 == task.reassignments.len()
3510 && stored.repo == task.reassignments.last().expect("new boundary").from
3511 && stored.runs == task.runs,
3512 "task changed during reassignment; retry after inspecting it"
3513 );
3514 self.write_record(task)
3515 }
3516
3517 pub(crate) fn commit_completion(&self, task: &mut Task, expected: &Task) -> Result<()> {
3519 let _lock = self.lock_task(&task.id)?;
3520 anyhow::ensure!(
3521 serde_json::to_value(self.get(&task.id)?)? == serde_json::to_value(expected)?,
3522 CompletionSnapshotChanged
3523 );
3524 self.write_record(task)
3525 }
3526
3527 fn merge_stored(&self, task: &mut Task) {
3529 if let Ok(mut stored) = read_path(&self.path_of(&task.id)) {
3530 stored.import_chat_notice();
3531 let local_decision = task.completion_history.iter().any(|event| {
3534 !stored
3535 .completion_history
3536 .iter()
3537 .any(|saved| saved.occurrence == event.occurrence)
3538 && event.at > stored.updated_at
3539 });
3540 let unseen_decision = stored.completion_history.iter().any(|event| {
3541 !task
3542 .completion_history
3543 .iter()
3544 .any(|mine| mine.occurrence == event.occurrence)
3545 });
3546 let mut history = std::mem::take(&mut stored.completion_history);
3547 for event in std::mem::take(&mut task.completion_history) {
3548 if !history
3549 .iter()
3550 .any(|stored| stored.occurrence == event.occurrence)
3551 {
3552 history.push(event);
3553 }
3554 }
3555 if unseen_decision {
3556 task.import_chat_notice();
3559 let mut stale = std::mem::replace(task, stored);
3560 append_missing(&mut task.answers, stale.answers);
3561 if task.reassignments == stale.reassignments {
3562 append_missing(&mut task.runs, stale.runs);
3563 }
3564 for (ledger, entries) in [
3565 (&mut task.decision_effects, stale.decision_effects),
3566 (&mut task.superseded_resumes, stale.superseded_resumes),
3567 (&mut task.dispatched_resumes, stale.dispatched_resumes),
3568 ] {
3569 for (key, value) in entries {
3570 ledger.entry(key).or_insert(value);
3571 }
3572 }
3573 append_missing(&mut task.actions_applied, stale.actions_applied);
3574 append_missing(&mut task.triage_applied, stale.triage_applied);
3575 append_missing(&mut task.chat_notices, stale.chat_notices);
3576 append_missing(
3577 &mut task.base_recovery_requests,
3578 stale.base_recovery_requests,
3579 );
3580 append_missing(
3581 &mut task.land_sync_recovery_requests,
3582 stale.land_sync_recovery_requests,
3583 );
3584 prepend_missing_by(&mut task.repair_grants, stale.repair_grants, |a, b| {
3587 a.request.request == b.request.request
3588 });
3589 prepend_missing_by(
3590 &mut task.repair_reconciliations,
3591 stale.repair_reconciliations,
3592 |a, b| a.request.request == b.request.request,
3593 );
3594 stale.resumption_history.extend(stale.resumption);
3597 stale.resumption_history.retain(|approval| {
3598 task.resumption
3599 .as_ref()
3600 .is_none_or(|r| r.at != approval.at || r.generation != approval.generation)
3601 });
3602 prepend_missing_by(
3603 &mut task.resumption_history,
3604 stale.resumption_history,
3605 |a, b| a.at == b.at && a.generation == b.generation,
3606 );
3607 for failure in stale.startup_failures {
3608 task.record_startup_failure(failure);
3609 }
3610 for pass in stale.passes {
3611 if !task.passes.iter().any(|stored| {
3612 stored.run == pass.run && stored.pass_index == pass.pass_index
3613 }) {
3614 task.passes.push(pass);
3615 }
3616 }
3617 task.completion_history = history;
3618 if !task.decision_effects.is_empty() {
3619 task.stamp_schema();
3620 }
3621 return;
3622 }
3623 if stored.reassignments.len() > task.reassignments.len() {
3624 let stale = std::mem::replace(task, stored.clone());
3627 for answer in stale.answers {
3628 if !task.answers.contains(&answer) {
3629 task.answers.push(answer);
3630 }
3631 }
3632 }
3633 if task.updated_at < stored.updated_at
3636 && (task.sync_only != stored.sync_only
3637 || stored.sync_only.is_some()
3638 || stored
3639 .recovery_budget_hold
3640 .as_ref()
3641 .is_some_and(|hold| hold.held_at > task.updated_at)
3642 || stored.repair_grants.last().is_some_and(|grant| {
3643 task.repair_grants.last() != Some(grant)
3644 || stored.operator_decided_at > task.operator_decided_at
3645 || stored
3646 .resume_override
3647 .as_ref()
3648 .is_some_and(|pin| pin.at > task.updated_at)
3649 || (task.resume_override != stored.resume_override
3650 && task
3651 .resume_override
3652 .as_ref()
3653 .is_some_and(|pin| pin.at == grant.at))
3654 }))
3655 && task
3656 .operator_decided_at
3657 .is_none_or(|at| at <= stored.updated_at)
3658 && task
3659 .resume_override
3660 .as_ref()
3661 .is_none_or(|pin| pin.at <= stored.updated_at)
3662 && !local_decision
3663 {
3664 *task = stored.clone();
3665 }
3666 task.completion_history = history;
3667 append_missing(
3668 &mut task.base_recovery_requests,
3669 stored.base_recovery_requests,
3670 );
3671 append_missing(
3672 &mut task.land_sync_recovery_requests,
3673 stored.land_sync_recovery_requests,
3674 );
3675 append_missing(&mut task.actions_applied, stored.actions_applied);
3676 append_missing(&mut task.triage_applied, stored.triage_applied);
3677 for receipt in &stored.repair_grants {
3678 if !task
3679 .repair_grants
3680 .iter()
3681 .any(|r| r.request.request == receipt.request.request)
3682 {
3683 task.repair_grants.push(receipt.clone());
3685 }
3686 }
3687 for receipt in &stored.repair_reconciliations {
3688 if !task.repair_reconciliations.contains(receipt) {
3689 task.repair_reconciliations.push(receipt.clone());
3692 task.resume_override = stored.resume_override.clone();
3693 task.status = stored.status;
3694 task.hold_source = stored.hold_source;
3695 task.machine_hold_cause = stored.machine_hold_cause.clone();
3696 task.disk_resume_run = stored.disk_resume_run.clone();
3697 task.disk_checked_at = stored.disk_checked_at;
3698 task.hold_reason = stored.hold_reason.clone();
3699 task.held_at = stored.held_at;
3700 }
3701 }
3702 task.superseded_resumes.extend(stored.superseded_resumes);
3703 task.dispatched_resumes.extend(stored.dispatched_resumes);
3704 if task.status != TaskStatus::Running
3705 && let Some(pin) = &stored.resume_override
3706 && !pin.question_id.is_empty()
3707 && let Some(run) = &pin.pinned_run
3708 && task.resume_override.as_ref().is_none_or(|next| {
3709 next.question_id != pin.question_id || next.pinned_run != pin.pinned_run
3710 })
3711 {
3712 task.superseded_resumes
3713 .insert(pin.question_id.clone(), run.clone());
3714 }
3715 for (id, receipt) in stored.decision_effects {
3718 task.decision_effects.insert(id, receipt);
3719 }
3720 if !task.decision_effects.is_empty() {
3721 task.stamp_schema();
3722 }
3723 if task.chat.is_none() {
3726 task.chat = stored.chat.clone();
3727 }
3728 if task.issue.is_none() {
3729 task.issue = stored.issue.clone();
3730 }
3731 append_missing(&mut task.chat_notices, stored.chat_notices);
3732 for failure in stored.startup_failures {
3733 task.record_startup_failure(failure);
3734 }
3735 append_missing(&mut task.runs, stored.runs);
3736 for p in stored.passes {
3737 if !task
3738 .passes
3739 .iter()
3740 .any(|q| q.run == p.run && q.pass_index == p.pass_index)
3741 {
3742 task.passes.push(p);
3743 }
3744 }
3745 if let Some(n) = stored.chat_notice
3748 && task.chat_notice.as_ref().is_none_or(|mine| mine.at < n.at)
3749 {
3750 task.chat_notice = Some(n);
3751 }
3752 }
3753 }
3754
3755 pub(crate) fn write_startup_history(&self, task: &Task) -> Result<()> {
3758 let path = self.path_of(&task.id);
3759 let tmp = path.with_extension("json.tmp");
3760 std::fs::write(&tmp, serde_json::to_vec_pretty(task)?)?;
3761 std::fs::rename(tmp, path)?;
3762 Ok(())
3763 }
3764
3765 fn write_record(&self, task: &mut Task) -> Result<()> {
3767 self.write_record_inner(task, true)
3768 }
3769
3770 fn write_record_inner(&self, task: &mut Task, notify: bool) -> Result<()> {
3771 task.import_chat_notice();
3772 if task.status != TaskStatus::Held && task.sync_only.is_none() {
3773 task.recovery_budget_hold = None;
3774 }
3775 task.updated_at = Timestamp::now();
3776 std::fs::create_dir_all(&self.root)
3777 .with_context(|| format!("create {}", self.root.display()))?;
3778 let body = serde_json::to_string_pretty(task).context("serialize task")?;
3779 let path = self.path_of(&task.id);
3780 let tmp = path.with_extension("json.tmp");
3781 std::fs::write(&tmp, &body).with_context(|| format!("write {}", tmp.display()))?;
3782 std::fs::rename(&tmp, &path).with_context(|| format!("replace {}", path.display()))?;
3783 if let (Some(notice), Some(home)) = (
3788 notify.then(|| crate::notices::task_held(task)).flatten(),
3789 self.root.parent().filter(|p| !p.as_os_str().is_empty()),
3790 ) {
3791 crate::notices::raise_in(home, notice);
3792 }
3793 Ok(())
3794 }
3795
3796 pub fn modify(&self, id: &str, f: impl FnOnce(&mut Task) -> bool) -> Result<bool> {
3801 let id = self.resolve_id(id)?;
3802 let _lock = self.lock_task(&id)?;
3803 let mut task = self.get(&id)?;
3804 if !f(&mut task) {
3805 return Ok(false);
3806 }
3807 self.put_unlocked(&mut task)?;
3808 Ok(true)
3809 }
3810
3811 pub fn link_run(&self, id: &str, run: &str) -> Result<Task> {
3816 let id = self.resolve_id(id)?;
3817 let _lock = self.lock_task(&id)?;
3820 let mut task = self.get(&id)?;
3821 if task.link_run(run) {
3822 self.put_unlocked(&mut task)?;
3823 }
3824 Ok(task)
3825 }
3826
3827 pub(crate) fn lock_task(&self, id: &str) -> Result<TaskLock> {
3835 std::fs::create_dir_all(&self.root)
3836 .with_context(|| format!("create {}", self.root.display()))?;
3837 let path = self.root.join(format!("{id}.write-lock"));
3838 let started = std::time::Instant::now();
3839 let retry = crate::lock_file::Retry::task_write(started + TASK_LOCK_STALE);
3840 let marker_retry = crate::lock_file::Retry::new(Some(started + TASK_LOCK_STALE));
3841 loop {
3842 match retry.create(&path) {
3843 Ok(mut file) => {
3844 use std::io::Write;
3845 let token = owner_token();
3846 if let Err(e) = file.write_all(token.as_bytes()) {
3847 drop(file);
3848 let _ = std::fs::remove_file(&path);
3849 return Err(e).with_context(|| format!("lock {}", path.display()));
3850 }
3851 return Ok(TaskLock { path, token });
3852 }
3853 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
3854 let judged = std::fs::read_to_string(&path).ok();
3857 let broken = judged
3858 .filter(|_| older_than_stale(&path))
3859 .is_some_and(|judged| break_stale_with(&path, &judged, marker_retry));
3860 if !broken {
3864 if started.elapsed() > TASK_LOCK_STALE {
3865 bail!("could not lock task {id}");
3866 }
3867 std::thread::sleep(std::time::Duration::from_millis(15));
3868 }
3869 }
3870 Err(e) => return Err(e).with_context(|| format!("lock {}", path.display())),
3871 }
3872 }
3873 }
3874
3875 pub fn get(&self, id: &str) -> Result<Task> {
3877 let resolved = self.resolve_id(id)?;
3878 read_path(&self.path_of(&resolved))
3879 }
3880
3881 pub fn remove(&self, id: &str, in_flight: bool, questions: &Questions) -> Result<Removal> {
3913 self.remove_with_receipt(id, in_flight, questions, None)
3914 }
3915
3916 pub(crate) fn discard_triage(
3918 &self,
3919 id: &str,
3920 questions: &Questions,
3921 inquiry: &str,
3922 ) -> Result<Removal> {
3923 self.remove_with_receipt(id, false, questions, Some(inquiry))
3924 }
3925
3926 pub(crate) fn triage_discard_applied(&self, id: &str, inquiry: &str) -> Result<bool> {
3927 let path = self
3928 .root
3929 .join("triage-discard")
3930 .join(format!("{inquiry}.json"));
3931 let bytes = match std::fs::read(path) {
3932 Ok(bytes) => bytes,
3933 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(false),
3934 Err(e) => return Err(e.into()),
3935 };
3936 let receipt: Task = serde_json::from_slice(&bytes)?;
3937 Ok(receipt.id == id && !self.path_of(id).exists())
3938 }
3939
3940 fn remove_with_receipt(
3941 &self,
3942 id: &str,
3943 in_flight: bool,
3944 questions: &Questions,
3945 inquiry: Option<&str>,
3946 ) -> Result<Removal> {
3947 let resolved = self.resolve_id(id)?;
3948 if in_flight {
3949 bail!("task {resolved} is being run by a live daemon right now");
3950 }
3951 let receipt = inquiry.map(|q| self.root.join("triage-discard").join(format!("{q}.json")));
3952 if let Some(path) = &receipt {
3953 std::fs::create_dir_all(path.parent().expect("receipt directory"))?;
3954 }
3955 self.write_tombstone(&resolved)?;
3956 if let Err(e) = self.remove_record_with_attachments(&resolved, |p| match &receipt {
3957 Some(path) => std::fs::rename(p, path),
3958 None => std::fs::remove_file(p),
3959 }) {
3960 if self.path_of(&resolved).exists() {
3964 let _ = std::fs::remove_file(self.tombstone_path(&resolved));
3965 }
3966 return Err(e);
3967 }
3968 let (released, still_blocked) = self.release_dependents_of(&resolved, questions);
3969 Ok(Removal {
3970 id: resolved,
3971 released,
3972 still_blocked,
3973 })
3974 }
3975
3976 fn tombstone_path(&self, id: &str) -> PathBuf {
3979 self.root.join(format!("{id}.removed"))
3980 }
3981
3982 fn write_tombstone(&self, id: &str) -> Result<()> {
3983 let path = self.tombstone_path(id);
3984 let tmp = self.root.join(format!("{id}.removed.tmp"));
3985 std::fs::write(&tmp, b"")
3986 .and_then(|()| std::fs::rename(&tmp, &path))
3987 .with_context(|| format!("write {}", path.display()))
3988 }
3989
3990 fn was_deleted(&self, id: &str) -> bool {
3994 self.tombstone_path(id).is_file() && !self.path_of(id).exists()
3995 }
3996
3997 pub fn apply_deleted_blockers(&self, task: &mut Task, questions: &Questions) -> Vec<String> {
4001 let deleted = deleted_blockers(self, questions, &task.blocked_by);
4002 deleted
4003 .into_iter()
4004 .filter(|id| task.dependency_deleted(id))
4005 .collect()
4006 }
4007
4008 pub fn note_dependency_deleted(&self, dependent: &Task, deleted: &str) {
4012 let Some(home) = self.root.parent().filter(|p| !p.as_os_str().is_empty()) else {
4013 return;
4014 };
4015 let ja = crate::lang::is_japanese(&crate::lang::of_repo(&dependent.repo));
4016 let waiting = dependent.status == TaskStatus::Blocked;
4017 let message = match (ja, waiting) {
4018 (true, false) => format!(
4019 "タスク {} は、待っていた {} が削除されたため待機を解除し、元の状態に戻しました",
4020 dependent.short(),
4021 short(deleted)
4022 ),
4023 (true, true) => format!(
4024 "タスク {} は、待っていた {} が削除されたため、残りの依存を待っています",
4025 dependent.short(),
4026 short(deleted)
4027 ),
4028 (false, false) => format!(
4029 "Task {} stopped waiting on {} because it was deleted, and returned to its previous state",
4030 dependent.short(),
4031 short(deleted)
4032 ),
4033 (false, true) => format!(
4034 "Task {} stopped waiting on {} because it was deleted, and is still waiting on its other dependencies",
4035 dependent.short(),
4036 short(deleted)
4037 ),
4038 };
4039 crate::notices::raise_in(
4040 home,
4041 crate::notices::Notice::info(
4042 &format!("unblocked:{}:{}", dependent.id, deleted),
4043 message,
4044 )
4045 .link(crate::notices::Link::Task {
4046 id: dependent.id.clone(),
4047 }),
4048 );
4049 }
4050
4051 fn release_dependents_of(
4056 &self,
4057 dependency: &str,
4058 questions: &Questions,
4059 ) -> (Vec<String>, Vec<String>) {
4060 let (mut released, mut still_blocked) = (Vec::new(), Vec::new());
4061 for listed in self.list() {
4062 if listed.status != TaskStatus::Blocked || !listed.blocked_by.iter().any(|b| {
4063 matches!(crate::queue::dependency(self, questions, b), Dependency::Deleted(id) if id == dependency)
4064 }) {
4065 continue;
4066 }
4067 let Ok(_claim) = self.claim(&listed.id) else {
4068 continue;
4069 };
4070 let Ok(mut task) = self.get(&listed.id) else {
4071 continue;
4072 };
4073 let references: Vec<String> = task.blocked_by.iter().filter(|id| {
4074 matches!(crate::queue::dependency(self, questions, id), Dependency::Deleted(full) if full == dependency)
4075 }).cloned().collect();
4076 if references.is_empty() {
4077 continue;
4078 }
4079 for reference in references {
4080 task.dependency_deleted(&reference);
4081 }
4082 if self.put(&mut task).is_err() {
4083 continue;
4084 }
4085 self.note_dependency_deleted(&task, dependency);
4086 if task.status == TaskStatus::Blocked {
4087 still_blocked.push(task.id.clone());
4088 } else {
4089 released.push(task.id.clone());
4090 }
4091 }
4092 (released, still_blocked)
4093 }
4094
4095 fn remove_record_with_attachments(
4099 &self,
4100 resolved: &str,
4101 remove_record: impl FnOnce(&Path) -> std::io::Result<()>,
4102 ) -> Result<()> {
4103 self.sweep_removed_attachments();
4110 let attachments = self.attachments_dir(resolved);
4111 let aside = self.root.join(format!("{resolved}.attachments.removing"));
4112 let moved = match std::fs::rename(&attachments, &aside) {
4113 Ok(()) => true,
4114 Err(e) if e.kind() == std::io::ErrorKind::NotFound => false,
4115 Err(e) => {
4116 return Err(e).with_context(|| format!("remove {}", attachments.display()));
4117 }
4118 };
4119 let path = self.path_of(resolved);
4120 if let Err(e) = remove_record(&path) {
4121 if moved {
4122 let _ = std::fs::rename(&aside, &attachments);
4123 }
4124 return Err(e).with_context(|| format!("remove {}", path.display()));
4125 }
4126 if moved {
4127 if let Err(e) = std::fs::remove_dir_all(&aside) {
4128 tracing::warn!("leftover attachments {}: {e}", aside.display());
4129 }
4130 }
4131 let lock = self.lock_path(resolved);
4132 if let Err(e) = std::fs::remove_file(&lock) {
4133 if e.kind() != std::io::ErrorKind::NotFound {
4134 return Err(e).with_context(|| format!("remove {}", lock.display()));
4135 }
4136 }
4137 Ok(())
4138 }
4139
4140 fn sweep_removed_attachments(&self) {
4146 let Ok(entries) = std::fs::read_dir(&self.root) else {
4147 return;
4148 };
4149 for entry in entries.flatten() {
4150 let name = entry.file_name();
4151 let name = name.to_string_lossy();
4152 let Some(id) = name.strip_suffix(".attachments.removing") else {
4153 continue;
4154 };
4155 if !self.path_of(id).exists() {
4158 if let Err(e) = std::fs::remove_dir_all(entry.path()) {
4159 tracing::warn!("leftover attachments {}: {e}", entry.path().display());
4160 }
4161 }
4162 }
4163 self.sweep_tombstones();
4164 }
4165
4166 fn sweep_tombstones(&self) {
4175 let Ok(entries) = std::fs::read_dir(&self.root) else {
4176 return;
4177 };
4178 let tasks = self.list();
4179 for entry in entries.flatten() {
4180 let name = entry.file_name();
4181 let name = name.to_string_lossy();
4182 let Some(id) = name.strip_suffix(".removed") else {
4183 continue;
4184 };
4185 if self.path_of(id).exists()
4186 || tasks.iter().any(|t| {
4187 t.blocked_by
4188 .iter()
4189 .any(|b| id.starts_with(b) || id.ends_with(b))
4190 })
4191 {
4192 continue;
4193 }
4194 let old = entry
4195 .metadata()
4196 .and_then(|m| m.modified())
4197 .ok()
4198 .and_then(|m| m.elapsed().ok())
4199 .is_some_and(|age| age >= TOMBSTONE_GRACE);
4200 if old {
4201 let _ = std::fs::remove_file(entry.path());
4202 }
4203 }
4204 }
4205
4206 fn lock_path(&self, id: &str) -> PathBuf {
4209 self.root.join(format!("{id}.lock"))
4210 }
4211
4212 pub fn list(&self) -> Vec<Task> {
4225 #[cfg(test)]
4226 LIST_READS.with(|count| count.set(count.get() + 1));
4227 let mut tasks: Vec<Task> = std::fs::read_dir(&self.root)
4228 .into_iter()
4229 .flatten()
4230 .flatten()
4231 .map(|e| e.path())
4232 .filter(|p| p.extension().is_some_and(|x| x == "json"))
4233 .filter_map(|p| read_path(&p).ok())
4234 .collect();
4235 tasks.sort_unstable_by(|a, b| b.priority.cmp(&a.priority).then_with(|| b.id.cmp(&a.id)));
4236 tasks
4237 }
4238
4239 pub fn unreadable(&self) -> Vec<PathBuf> {
4243 std::fs::read_dir(&self.root)
4244 .into_iter()
4245 .flatten()
4246 .flatten()
4247 .map(|e| e.path())
4248 .filter(|p| p.extension().is_some_and(|x| x == "json"))
4249 .filter(|p| read_path(p).is_err())
4250 .collect()
4251 }
4252
4253 pub fn superseded(&self) -> HashMap<String, String> {
4266 let mut by = HashMap::new();
4267 for task in self.list() {
4268 for earlier in &task.runs {
4269 if let Some(later) = task.successor_of(earlier) {
4270 by.insert(earlier.clone(), later.clone());
4271 }
4272 }
4273 }
4274 by
4275 }
4276
4277 pub fn superseded_by(&self, run: &str) -> Option<String> {
4285 for task in self.list() {
4286 if task.runs.iter().any(|r| r == run) {
4287 return task.successor_of(run).cloned();
4288 }
4289 }
4290 None
4291 }
4292
4293 pub fn latest_attempt(&self, run: &str) -> Option<String> {
4304 for task in self.list() {
4305 if task.runs.iter().any(|r| r == run) {
4306 return task.runs.last().filter(|last| **last != run).cloned();
4307 }
4308 }
4309 None
4310 }
4311
4312 pub fn next_runnable(&self) -> Option<Task> {
4317 let mut runnable: Vec<Task> = self
4318 .list()
4319 .into_iter()
4320 .filter(|t| t.status.runnable())
4321 .collect();
4322 runnable.sort_unstable_by(dispatch_order);
4323 runnable.into_iter().next()
4324 }
4325
4326 pub fn claim(&self, id: &str) -> Result<Claim> {
4333 std::fs::create_dir_all(&self.root)
4334 .with_context(|| format!("create {}", self.root.display()))?;
4335 let path = self.lock_path(id);
4336 let retry = crate::lock_file::Retry::new(None);
4337 match retry.create(&path) {
4338 Ok(mut f) => {
4339 use std::io::Write as _;
4340 let _ = writeln!(f, "{}", std::process::id());
4342 Ok(Claim { path })
4343 }
4344 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
4345 bail!("task {id} is already claimed ({} exists)", path.display())
4346 }
4347 Err(e) => Err(e).with_context(|| format!("lock {}", path.display())),
4348 }
4349 }
4350
4351 #[must_use]
4354 pub fn is_claimed(&self, id: &str) -> bool {
4355 self.lock_path(id).exists()
4356 }
4357
4358 pub fn resolve_id(&self, prefix: &str) -> Result<String> {
4360 if !prefix.is_empty()
4361 && prefix != "."
4362 && prefix != ".."
4363 && !prefix.contains(['/', '\\'])
4364 && self.path_of(prefix).is_file()
4365 {
4366 return Ok(prefix.to_owned());
4367 }
4368 let ids = record_ids(&self.root, "json")?;
4369 match resolve_reference(prefix, ids.iter().map(String::as_str)) {
4370 Reference::Found(id) => Ok(id),
4371 Reference::Missing => bail!("no task matches `{prefix}`"),
4372 Reference::Ambiguous => bail!("`{prefix}` matches multiple tasks"),
4373 }
4374 }
4375
4376 pub fn revision(&self) -> u64 {
4383 self.revision_excluding(&std::collections::BTreeSet::new())
4384 }
4385
4386 pub fn revision_excluding(&self, skip: &std::collections::BTreeSet<String>) -> u64 {
4389 use std::hash::{Hash as _, Hasher as _};
4390
4391 let mut entries: Vec<(String, u64)> = std::fs::read_dir(&self.root)
4392 .into_iter()
4393 .flatten()
4394 .flatten()
4395 .filter(|e| e.path().extension().is_some_and(|ext| ext == "json"))
4396 .filter(|e| {
4397 let path = e.path();
4398 !path
4399 .file_stem()
4400 .is_some_and(|stem| skip.contains(stem.to_string_lossy().as_ref()))
4401 })
4402 .filter_map(|e| {
4403 let name = e.file_name().to_string_lossy().into_owned();
4404 let mtime = e
4405 .metadata()
4406 .ok()?
4407 .modified()
4408 .ok()?
4409 .duration_since(std::time::UNIX_EPOCH)
4410 .ok()?
4411 .as_millis() as u64;
4412 Some((name, mtime))
4413 })
4414 .collect();
4415
4416 if entries.is_empty() {
4417 return 0;
4418 }
4419
4420 entries.sort_unstable();
4421 let mut hasher = std::hash::DefaultHasher::new();
4422 for (name, mtime) in &entries {
4423 name.hash(&mut hasher);
4424 mtime.hash(&mut hasher);
4425 }
4426 let h = hasher.finish();
4427 if h == 0 { 1 } else { h }
4428 }
4429}
4430
4431const TOMBSTONE_GRACE: std::time::Duration = std::time::Duration::from_secs(3600);
4434
4435#[derive(Debug, Clone)]
4437pub struct Removal {
4438 pub id: String,
4440 pub released: Vec<String>,
4444 pub still_blocked: Vec<String>,
4447}
4448
4449#[derive(Debug)]
4451pub struct Claim {
4452 path: PathBuf,
4453}
4454
4455impl Drop for Claim {
4456 fn drop(&mut self) {
4457 let _ = std::fs::remove_file(&self.path);
4458 }
4459}
4460
4461pub fn title_from(instruction: &str, max: usize) -> String {
4464 let Some(line) = first_line(instruction) else {
4465 return "(empty task)".to_owned();
4466 };
4467 if line.chars().count() <= max {
4468 return line.to_owned();
4469 }
4470 let head: String = line.chars().take(max.saturating_sub(1)).collect();
4471 format!("{head}…")
4472}
4473
4474pub(crate) fn first_line(instruction: &str) -> Option<&str> {
4480 let line = instruction
4481 .lines()
4482 .map(str::trim)
4483 .find(|l| !l.is_empty())?
4484 .trim_start_matches(['#', '-', '*', '>', ' '])
4485 .trim();
4486 (!line.is_empty()).then_some(line)
4487}
4488
4489#[cfg(test)]
4490thread_local! {
4491 pub(crate) static TASK_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4492}
4493
4494fn read_path(path: &Path) -> Result<Task> {
4495 #[cfg(test)]
4496 TASK_READS.with(|count| count.set(count.get() + 1));
4497 let body = std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;
4498 let mut task: Task =
4499 serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))?;
4500 if task.schema > SCHEMA {
4506 bail!(
4507 "task {} was written by a different magi (schema {}, this build \
4508 speaks {SCHEMA})",
4509 task.id,
4510 task.schema
4511 );
4512 }
4513 task.preserve_legacy_build_cache();
4514 if task.schema < 22
4515 && task.status == TaskStatus::Held
4516 && task.hold_source == Some(HoldSource::Machine)
4517 && task.resume_override.is_none()
4518 && task
4519 .hold_reason
4520 .as_deref()
4521 .is_some_and(crate::disk::is_gate_reason)
4522 {
4523 task.mark_disk_capacity();
4524 }
4525 Ok(task)
4526}
4527
4528#[derive(Debug, PartialEq, Eq)]
4531pub(crate) enum Reference {
4532 Found(String),
4533 Missing,
4534 Ambiguous,
4535}
4536
4537pub(crate) fn resolve_reference<'a>(id: &str, ids: impl Iterator<Item = &'a str>) -> Reference {
4538 let mut hits = Vec::new();
4539 for candidate in ids {
4540 if candidate == id {
4541 return Reference::Found(candidate.to_owned());
4542 }
4543 if candidate.starts_with(id) || candidate.ends_with(id) {
4544 hits.push(candidate);
4545 }
4546 }
4547 match hits.as_slice() {
4548 [] => Reference::Missing,
4549 [one] => Reference::Found((*one).to_owned()),
4550 _ => Reference::Ambiguous,
4551 }
4552}
4553
4554pub(crate) fn record_ids(root: &Path, extension: &str) -> Result<Vec<String>> {
4557 let entries = match std::fs::read_dir(root) {
4558 Ok(entries) => entries,
4559 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
4560 Err(e) => return Err(e.into()),
4561 };
4562 let mut ids = Vec::new();
4563 for entry in entries {
4564 let path = entry?.path();
4565 if path.extension().is_some_and(|e| e == extension)
4566 && let Some(id) = path.file_stem().and_then(|s| s.to_str())
4567 {
4568 ids.push(id.to_owned());
4569 }
4570 }
4571 Ok(ids)
4572}
4573
4574#[derive(Debug, PartialEq, Eq)]
4577pub enum Dependency {
4578 Task(String),
4580 Question(String),
4582 Deleted(String),
4584 Missing,
4586 Ambiguous,
4588 Unknown,
4590}
4591
4592pub fn dependency(queue: &Queue, questions: &Questions, id: &str) -> Dependency {
4594 let (Ok(tasks), Ok(qs), Ok(removed)) = (
4595 record_ids(queue.root(), "json"),
4596 record_ids(questions.root(), "json"),
4597 record_ids(queue.root(), "removed"),
4598 ) else {
4599 return Dependency::Unknown;
4600 };
4601 let mut ids = tasks
4604 .iter()
4605 .chain(qs.iter())
4606 .chain(removed.iter())
4607 .cloned()
4608 .collect::<Vec<_>>();
4609 ids.sort();
4610 ids.dedup();
4611 match resolve_reference(id, ids.iter().map(String::as_str)) {
4612 Reference::Found(id) if tasks.contains(&id) => Dependency::Task(id),
4613 Reference::Found(id) if qs.contains(&id) => Dependency::Question(id),
4614 Reference::Found(id) if queue.was_deleted(&id) => Dependency::Deleted(id),
4615 Reference::Found(_) => Dependency::Unknown,
4616 Reference::Missing => Dependency::Missing,
4617 Reference::Ambiguous => Dependency::Ambiguous,
4618 }
4619}
4620
4621pub fn normalize_blockers(queue: &Queue, questions: &Questions, ids: &mut [String]) {
4623 for id in ids {
4624 if let Dependency::Task(full) | Dependency::Question(full) | Dependency::Deleted(full) =
4625 dependency(queue, questions, id)
4626 {
4627 *id = full;
4628 }
4629 }
4630}
4631
4632pub fn dependency_facts(queue: &Queue, questions: &Questions) -> String {
4635 let inventory = crate::blockers::Inventory::load(queue, questions);
4636 let mut text = String::from(
4637 "Current authoritative queue (historical missing-task claims may be stale; unreadable or ambiguous references must keep waiting):\n",
4638 );
4639 match record_ids(queue.root(), "json") {
4640 Ok(ids) => {
4641 for id in ids {
4642 match queue.get(&id) {
4643 Ok(task) => text.push_str(&format!(
4644 "{}: {}; blocked_by={:?}; chain={:?}\n",
4645 task.id,
4646 task.status.as_str(),
4647 task.blocked_by,
4648 inventory.waits_on(&task)
4649 )),
4650 Err(_) => text.push_str(&format!("{id}: exists, state unreadable\n")),
4651 }
4652 }
4653 }
4654 Err(_) => text.push_str("Queue inventory unreadable: existence is unknown.\n"),
4655 }
4656 text
4657}
4658
4659pub fn missing_blockers(
4661 queue: &Queue,
4662 questions: &Questions,
4663 blocked_by: &[String],
4664) -> Vec<String> {
4665 blocked_by
4666 .iter()
4667 .filter(|id| dependency(queue, questions, id) == Dependency::Missing)
4668 .cloned()
4669 .collect()
4670}
4671
4672pub fn deleted_blockers(
4675 queue: &Queue,
4676 questions: &Questions,
4677 blocked_by: &[String],
4678) -> Vec<String> {
4679 blocked_by
4680 .iter()
4681 .filter(|id| matches!(dependency(queue, questions, id), Dependency::Deleted(_)))
4682 .cloned()
4683 .collect()
4684}
4685
4686pub fn missing_blocker_hold_reason(blocked_by: &[String], missing: &[String]) -> String {
4698 missing_blocker_hold_reason_in(blocked_by, missing, "en")
4699}
4700
4701pub fn missing_blocker_hold_reason_in(
4703 blocked_by: &[String],
4704 missing: &[String],
4705 language: &str,
4706) -> String {
4707 if crate::lang::is_japanese(language) {
4708 format!(
4709 "{} を待っていましたが、{} はディスク上に存在しません - `magi task triage` を参照",
4710 blocked_by.join(", "),
4711 missing.join(", "),
4712 )
4713 } else {
4714 format!(
4715 "blocked on {} but {} no longer exist(s) on disk - see `magi task triage`",
4716 blocked_by.join(", "),
4717 missing.join(", "),
4718 )
4719 }
4720}
4721
4722pub fn short(id: &str) -> &str {
4724 id.split('-').next_back().unwrap_or(id)
4725}
4726
4727fn new_id() -> String {
4728 let stamp = jiff::Zoned::now().strftime("%Y%m%d-%H%M%S");
4729 let seed = crate::rng::entropy();
4730 format!("{stamp}-{:04x}", (seed ^ (seed >> 32)) & 0xffff)
4731}
4732
4733#[cfg(test)]
4734mod tests {
4735 #[test]
4736 fn reassignment_clears_repository_bound_execution_selections() {
4737 let mut task = Task::new(
4738 "move".into(),
4739 "evidence".into(),
4740 "old".into(),
4741 Source::Human,
4742 );
4743 task.review_branch = Some("old-review".into());
4744 task.review_instruction = Some("old criteria".into());
4745 task.pr_recovery = Some(crate::pr_recovery::Selection {
4746 url: "https://example.invalid/pull/1".into(),
4747 branch: "old-pr".into(),
4748 head: "head".into(),
4749 source_head: None,
4750 source_run: None,
4751 source_proof: None,
4752 disposition: None,
4753 instruction: "old criteria".into(),
4754 approved_at: Timestamp::now(),
4755 });
4756 task.replacement = Some(crate::merge_decision::Replacement {
4757 question: "owner".into(),
4758 run: "old-run".into(),
4759 pr: "https://example.invalid/pull/1".into(),
4760 agent: "worker".into(),
4761 context: "evidence".into(),
4762 });
4763 task.resume_override = Some(OperatorResume {
4764 question_id: "old-question".into(),
4765 at: Timestamp::now(),
4766 conductor_rehold: None,
4767 forced: true,
4768 pinned_run: Some("old-run".into()),
4769 });
4770 task.interrupt = true;
4771 task.reassign_repository("new".into(), "test");
4772 assert!(task.review_branch.is_none());
4773 assert!(task.review_instruction.is_none());
4774 assert!(task.pr_recovery.is_none());
4775 assert!(task.replacement.is_none());
4776 assert!(task.resume_override.is_none());
4777 assert!(!task.interrupt);
4778 assert!(task.fresh_start);
4779 assert_eq!(task.instruction, "evidence");
4780 }
4781
4782 #[test]
4783 fn explicit_resumption_is_not_invented_for_legacy_or_automatic_release() {
4784 let t = Task::new(
4785 "retry".into(),
4786 "do it".into(),
4787 PathBuf::from("."),
4788 Source::Human,
4789 );
4790 let mut value = serde_json::to_value(&t).unwrap();
4791 for field in ["resumption", "resumption_history", "operator_decided_at"] {
4792 value.as_object_mut().unwrap().remove(field);
4793 }
4794 value["schema"] = serde_json::json!(15);
4795 let mut legacy: Task = serde_json::from_value(value).unwrap();
4796 legacy.hold_machine(Some("automatic retry".into()));
4797 legacy.release();
4798 assert!(legacy.resumption.is_none());
4799 assert!(legacy.resumption_history.is_empty());
4800 assert!(legacy.operator_decided_at.is_none());
4801 legacy.release_operator("cli", None);
4802 legacy.start("run".into());
4803 let reloaded: Task =
4804 serde_json::from_str(&serde_json::to_string(&legacy).unwrap()).unwrap();
4805 assert!(reloaded.resume_override.is_none());
4806 assert_eq!(reloaded.resumption.as_ref().unwrap().generation, 1);
4807 }
4808
4809 #[test]
4810 fn merge_over_lets_the_later_choice_win_and_keeps_the_rest() {
4811 let mut base = RunOverrides {
4812 merge: Some("pr".to_owned()),
4813 candidates: Some(3),
4814 ..RunOverrides::default()
4815 };
4816 base.merge_over(&RunOverrides {
4817 merge: Some("none".to_owned()),
4818 seed: Some(7),
4819 ..RunOverrides::default()
4820 });
4821 assert_eq!(base.merge.as_deref(), Some("none"));
4822 assert_eq!(base.candidates, Some(3));
4823 assert_eq!(base.seed, Some(7));
4824 }
4825
4826 #[test]
4827 fn an_already_landed_task_is_done_with_its_attempt_refunded() {
4828 let mut t = task("relanded");
4829 t.attempts = 1;
4830 t.status = TaskStatus::Running;
4831 t.already_landed("already in main as 0e368de", completion(&t));
4832 assert_eq!(t.status, TaskStatus::Done);
4833 assert_eq!(t.attempts, 0);
4834 assert!(t.hold_reason.is_none());
4835 assert_eq!(t.last_error.as_deref(), Some("already in main as 0e368de"));
4836 }
4837
4838 #[test]
4839 fn missing_blocker_reason_follows_the_language() {
4840 let b = vec!["a".to_owned()];
4841 let en = missing_blocker_hold_reason_in(&b, &b, "en");
4842 assert_eq!(en, missing_blocker_hold_reason(&b, &b));
4843 assert!(en.starts_with("blocked on a"));
4844 assert!(missing_blocker_hold_reason_in(&b, &b, "ja").contains("存在しません"));
4845 assert_eq!(missing_blocker_hold_reason_in(&b, &b, "de"), en);
4846 }
4847
4848 use super::*;
4849
4850 fn completion(task: &Task) -> CompletionContext {
4851 CompletionContext::new(CompletionActor::Cli, None, Path::new("."), task)
4852 }
4853
4854 #[test]
4855 fn completion_retains_the_hold_dependency_and_failure_it_clears() {
4856 let mut held = task("held evidence");
4857 held.hold_manual(Some("owner approval required".into()));
4858 held.last_error = Some("review budget exhausted".into());
4859 held.succeed(completion(&held));
4860 let event = held.completion_history.last().unwrap();
4861 assert_eq!(event.prior_status, TaskStatus::Held);
4862 assert_eq!(
4863 event.prior_hold_reason.as_deref(),
4864 Some("owner approval required")
4865 );
4866 assert_eq!(
4867 event.prior_error.as_deref(),
4868 Some("review budget exhausted")
4869 );
4870 assert!(held.hold_reason.is_none());
4871 assert!(held.last_error.is_none());
4872 let mut blocked = task("dependency evidence");
4873 blocked.block(
4874 vec!["dependency".into()],
4875 Some("waiting on migration".into()),
4876 );
4877 blocked.succeed(completion(&blocked));
4878 let event = blocked.completion_history.last().unwrap();
4879 assert_eq!(event.prior_status, TaskStatus::Blocked);
4880 assert_eq!(
4881 event.prior_block_reason.as_deref(),
4882 Some("waiting on migration")
4883 );
4884 assert!(blocked.block_reason.is_none());
4885 assert!(blocked.blocked_by.is_empty());
4886 let saved = serde_json::to_vec(&held).unwrap();
4887 let restored: Task = serde_json::from_slice(&saved).unwrap();
4888 assert_eq!(restored.completion_history, held.completion_history);
4889 }
4890
4891 #[test]
4892 fn completion_audit_is_append_only_under_stale_puts() {
4893 let dir = tempfile::tempdir().unwrap();
4894 let queue = Queue::at(dir.path().join("queue"));
4895 let mut current = task("audited");
4896 current.hold_manual(Some("inspect".into()));
4897 queue.put(&mut current).unwrap();
4898 let mut stale = queue.get(¤t.id).unwrap();
4899 current.succeed(completion(¤t));
4900 queue.put(&mut current).unwrap();
4901 let original = current.completion_history[0].clone();
4902 stale.last_error = Some("stale control state".into());
4903 queue.put(&mut stale).unwrap();
4904 assert_eq!(stale.status, TaskStatus::Done);
4905 assert_eq!(stale.completion_history, vec![original.clone()]);
4906 let mut context = completion(¤t);
4907 context.reason = Some("not actually finished".into());
4908 current.reopen(context).unwrap();
4909 queue.put(&mut current).unwrap();
4910 stale.completion_history[0].actor = CompletionActor::Web;
4911 stale.completion_history[0].reason = Some("rewritten evidence".into());
4912 queue.put(&mut stale).unwrap();
4913 assert_eq!(stale.status, TaskStatus::Held);
4914 assert_eq!(stale.hold_reason.as_deref(), Some("not actually finished"));
4915 assert_eq!(stale.completion_history[0], original);
4916 assert_eq!(stale.completion_history, current.completion_history);
4917 }
4918
4919 #[test]
4920 fn a_writer_missing_a_reopen_contributes_receipts_but_not_authority() {
4921 let (_dir, q) = queue();
4922 let mut current = task("durable receipts");
4923 q.put(&mut current).unwrap();
4924 let mut stale = current.clone();
4925 let grant: crate::repair_budget::Receipt = serde_json::from_value(serde_json::json!({
4926 "request": {
4927 "task": current.id, "run": "old-run", "kind": "gate", "rounds": 1,
4928 "head": "old-head", "expect_pass": 0, "request": "old-grant", "reason": "retry"
4929 },
4930 "at": stale.updated_at, "contract": "old-contract"
4931 }))
4932 .unwrap();
4933 stale.release_operator("triage", Some("triage-question"));
4934 stale.queue_repair(&grant);
4935 let reconciliation: crate::repair_budget::reconcile::Receipt =
4936 serde_json::from_value(serde_json::json!({
4937 "request": {
4938 "task": current.id, "run": "old-run", "head": "old-head", "expect_pass": 0,
4939 "receipt": "old-grant", "question": "triage-question", "answer_at": grant.at,
4940 "request": "reconciliation", "reason": "retain the answer"
4941 },
4942 "grant": grant, "source": "answer", "application": "release",
4943 "decision": grant.at, "superseded_questions": []
4944 }))
4945 .unwrap();
4946 stale.repair_reconciliations.push(reconciliation.clone());
4947 stale.triage_applied.push("triage-question".into());
4948 stale.actions_applied.push("choice".into());
4949 stale.base_recovery_requests.push("base-request".into());
4950 stale.chat_notices.push("delivery".into());
4951 stale.chat_notice = Some(ChatNotice {
4952 key: "other-delivery".into(),
4953 at: grant.at,
4954 outcome: ChatNoticeOutcome::Posted,
4955 });
4956 for ledger in [
4957 &mut stale.decision_effects,
4958 &mut stale.dispatched_resumes,
4959 &mut stale.superseded_resumes,
4960 ] {
4961 ledger.insert("shared".into(), "stale".into());
4962 ledger.insert("only-stale".into(), "receipt".into());
4963 }
4964
4965 let mut latest_grant = grant.clone();
4966 latest_grant.request.request = "new-grant".into();
4967 current.queue_repair(&latest_grant);
4968 for ledger in [
4969 &mut current.decision_effects,
4970 &mut current.dispatched_resumes,
4971 &mut current.superseded_resumes,
4972 ] {
4973 ledger.insert("shared".into(), "committed".into());
4974 }
4975 current.succeed(completion(¤t));
4976 let mut context = completion(¤t);
4977 context.reason = Some("inspect again".into());
4978 current.reopen(context).unwrap();
4979 q.put(&mut current).unwrap();
4980
4981 for _ in 0..2 {
4982 q.put(&mut stale.clone()).unwrap();
4983 let saved = q.get(¤t.id).unwrap();
4984 assert_eq!(saved.status, TaskStatus::Held);
4985 assert_eq!(saved.hold_reason, current.hold_reason);
4986 assert_eq!(saved.operator_decided_at, current.operator_decided_at);
4987 assert_eq!(saved.completion_history, current.completion_history);
4988 assert!(saved.resume_override.is_none());
4989 assert!(saved.resumption.is_none());
4990 assert_eq!(
4991 saved.resumption_history,
4992 [stale.resumption.clone().unwrap()]
4993 );
4994 assert_eq!(saved.triage_applied, ["triage-question"]);
4995 assert_eq!(saved.actions_applied, ["choice"]);
4996 assert_eq!(saved.base_recovery_requests, ["base-request"]);
4997 assert_eq!(saved.chat_notices, ["delivery", "other-delivery"]);
4998 assert_eq!(saved.repair_grants, [grant.clone(), latest_grant.clone()]);
4999 assert_eq!(
5000 saved.repair_reconciliations,
5001 std::slice::from_ref(&reconciliation)
5002 );
5003 for ledger in [
5004 saved.decision_effects,
5005 saved.dispatched_resumes,
5006 saved.superseded_resumes,
5007 ] {
5008 assert_eq!(ledger["shared"], "committed");
5009 assert_eq!(ledger["only-stale"], "receipt");
5010 }
5011 }
5012 }
5013
5014 #[test]
5015 fn repeated_completion_only_notifies_for_new_occurrences() {
5016 let mut task = chat_task();
5017 task.succeed(completion(&task));
5018 let first = task.chat_notice_key().unwrap();
5019 task.chat_notices.push(first.clone());
5020 task.succeed(completion(&task));
5021 assert_eq!(task.completion_history.len(), 1, "idempotent while done");
5022 assert_eq!(task.chat_notice_due(), None);
5023 let mut context = completion(&task);
5024 context.reason = Some("inspect".into());
5025 task.reopen(context).unwrap();
5026 task.succeed(completion(&task));
5027 let second = task.chat_notice_key().unwrap();
5028 assert_ne!(first, second);
5029 assert_eq!(task.chat_notice_due(), Some(second));
5030 assert_eq!(task.completion_history.len(), 3);
5031 }
5032
5033 #[test]
5034 fn old_tasks_have_unknown_completion_provenance_not_invented_events() {
5035 let mut task = task("legacy");
5036 task.status = TaskStatus::Done;
5037 let mut value = serde_json::to_value(&task).unwrap();
5038 value.as_object_mut().unwrap().remove("completion_history");
5039 let task: Task = serde_json::from_value(value).unwrap();
5040 assert!(task.completion_history.is_empty());
5041 assert_eq!(task.chat_notice_key().as_deref(), Some("done"));
5042 }
5043
5044 #[test]
5045 fn triage_applied_survives_release_and_old_records_read_as_empty() {
5046 let mut t = Task::new(
5047 "t".to_owned(),
5048 "i".to_owned(),
5049 PathBuf::from("r"),
5050 Source::Human,
5051 );
5052 t.mark_triage_applied("q1");
5053 t.mark_triage_applied("q1");
5054 t.hold_machine(Some("x".to_owned()));
5055 t.release();
5056 assert_eq!(t.triage_applied, ["q1"]);
5057 assert!(t.triage_applied("q1") && !t.triage_applied("q2"));
5058
5059 let mut v = serde_json::to_value(&t).unwrap();
5060 v.as_object_mut().unwrap().remove("triage_applied");
5061 let old: Task = serde_json::from_value(v).unwrap();
5062 assert!(old.triage_applied.is_empty());
5063 }
5064
5065 #[test]
5066 fn task_counts_of_empty_is_all_zero() {
5067 assert_eq!(TaskCounts::of(&[]), TaskCounts::default());
5068 }
5069
5070 #[test]
5071 fn task_counts_of_tallies_every_status() {
5072 let mut queued = Task::new(
5073 "q".to_owned(),
5074 "i".to_owned(),
5075 PathBuf::from("."),
5076 Source::Human,
5077 );
5078 queued.status = TaskStatus::Queued;
5079 let mut running = queued.clone();
5080 running.status = TaskStatus::Running;
5081 let mut done = queued.clone();
5082 done.status = TaskStatus::Done;
5083 let mut failed = queued.clone();
5084 failed.status = TaskStatus::Failed;
5085 let mut held = queued.clone();
5086 held.status = TaskStatus::Held;
5087 let mut blocked = queued.clone();
5088 blocked.status = TaskStatus::Blocked;
5089
5090 let mut parked = queued.clone();
5091 parked.status = TaskStatus::Parked;
5092
5093 let counts = TaskCounts::of(&[
5094 queued,
5095 running,
5096 done.clone(),
5097 done,
5098 failed,
5099 held,
5100 blocked,
5101 parked,
5102 ]);
5103 assert_eq!(
5104 counts,
5105 TaskCounts {
5106 queued: 1,
5107 running: 1,
5108 done: 2,
5109 failed: 1,
5110 held: 1,
5111 blocked: 1,
5112 parked: 1,
5113 }
5114 );
5115 }
5116
5117 #[test]
5118 fn task_implementers_persist_normalized_without_losing_history() {
5119 let (_dir, q) = queue();
5120 let mut t = task("keep me");
5121 t.hold_manual(Some("waiting".into()));
5122 t.runs.push("earlier-run".into());
5123 t.attachments.push("reference.txt".into());
5124 let cfg: crate::config::Config =
5125 toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
5126 .unwrap();
5127 q.put(&mut t).unwrap();
5128 let original = serde_json::to_value(&t).unwrap();
5129 for n in [2, 1, 2] {
5130 t.set_implementers(n, &cfg).unwrap();
5131 q.put(&mut t).unwrap();
5132 t = q.get(&t.id).unwrap();
5133 assert_eq!(t.implementers(), Some(usize::from(n)));
5134 assert_eq!(t.solo, n == 1);
5135 if n == 1 {
5136 assert!(t.overrides.is_none());
5137 }
5138 let mut actual = serde_json::to_value(&t).unwrap();
5139 for field in ["solo", "overrides", "updated_at"] {
5140 actual[field] = original[field].clone();
5141 }
5142 assert_eq!(actual, original);
5143 }
5144 t.overrides.as_mut().unwrap().judges = Some(2);
5145 t.set_implementers(1, &cfg).unwrap();
5146 assert_eq!(t.overrides.as_ref().unwrap().judges, Some(2));
5147 assert_eq!(t.overrides.as_ref().unwrap().candidates, None);
5148 }
5149
5150 #[test]
5151 fn task_implementers_old_records_keep_inheritance_until_changed() {
5152 let mut value = serde_json::to_value(task("old task")).unwrap();
5153 value.as_object_mut().unwrap().remove("solo");
5154 value.as_object_mut().unwrap().remove("overrides");
5155 let mut old: Task = serde_json::from_value(value).unwrap();
5156 assert_eq!(old.implementers(), None);
5157 old.set_implementers(1, &crate::config::Config::default())
5158 .unwrap();
5159 assert!(old.solo);
5160 assert!(old.overrides.is_none());
5161 }
5162
5163 #[test]
5164 fn task_implementers_reject_invalid_counts_and_states() {
5165 let cfg = crate::config::Config::default();
5166 let mut t = task("unchanged");
5167 for n in [0, 4, 255] {
5168 assert!(t.set_implementers(n, &cfg).is_err());
5169 }
5170 for status in [
5171 TaskStatus::Running,
5172 TaskStatus::Done,
5173 TaskStatus::Failed,
5174 TaskStatus::Blocked,
5175 TaskStatus::Parked,
5176 ] {
5177 t.status = status;
5178 let before = serde_json::to_value(&t).unwrap();
5179 assert!(t.set_implementers(1, &cfg).is_err());
5180 assert_eq!(serde_json::to_value(&t).unwrap(), before);
5181 }
5182 }
5183
5184 fn queue() -> (tempfile::TempDir, Queue) {
5187 let dir = tempfile::tempdir().unwrap();
5188 let q = Queue::at(dir.path().join("queue"));
5189 (dir, q)
5190 }
5191
5192 #[test]
5193 fn base_recovery_commit_retains_decision_and_superseded_resume_evidence() {
5194 let (_dir, q) = queue();
5195 let mut original = task("base recovery");
5196 original
5197 .decision_effects
5198 .insert("old-effect".into(), "receipt".into());
5199 original
5200 .dispatched_resumes
5201 .insert("dispatched".into(), "prior-run".into());
5202 original.resume_override = Some(OperatorResume {
5203 question_id: "prior-decision".into(),
5204 at: Timestamp::now(),
5205 conductor_rehold: None,
5206 forced: true,
5207 pinned_run: Some("retained-run".into()),
5208 });
5209 q.put(&mut original).unwrap();
5210 let expected = serde_json::to_value(&original).unwrap();
5211 let mut recovered = original.clone();
5212 recovered.base_recovery_requests.push("chat/request".into());
5213 recovered
5214 .resume_override
5215 .as_mut()
5216 .unwrap()
5217 .question_id
5218 .clear();
5219 q.commit_base_recovery(&mut recovered, &expected).unwrap();
5220 let saved = q.get(&original.id).unwrap();
5221 assert_eq!(saved.decision_effects, original.decision_effects);
5222 assert_eq!(saved.dispatched_resumes, original.dispatched_resumes);
5223 assert_eq!(
5224 saved
5225 .superseded_resumes
5226 .get("prior-decision")
5227 .map(String::as_str),
5228 Some("retained-run")
5229 );
5230 assert_eq!(saved.base_recovery_requests, ["chat/request"]);
5231 assert!(saved.resume_override.unwrap().question_id.is_empty());
5232 assert!(q.commit_base_recovery(&mut recovered, &expected).is_err());
5233 }
5234
5235 #[test]
5236 fn a_stale_write_does_not_drop_the_recorded_task_chat() {
5237 let (_dir, q) = queue();
5238 let mut stale = task("chat");
5239 q.put(&mut stale).unwrap();
5240 let mut fresh = q.get(&stale.id).unwrap();
5241 fresh.chat = Some("talk-1".to_owned());
5242 q.put(&mut fresh).unwrap();
5243 q.put(&mut stale).unwrap();
5244 assert_eq!(q.get(&stale.id).unwrap().chat.as_deref(), Some("talk-1"));
5245 }
5246
5247 #[test]
5248 fn putting_a_machine_held_task_files_a_notification_beside_the_queue() {
5249 let dir = tempfile::tempdir().unwrap();
5250 let q = Queue::at(dir.path().join("queue"));
5251 let mut t = task("held");
5252 q.put(&mut t).unwrap();
5253 assert_eq!(
5254 crate::notices::Notices::at(dir.path().join("notifications"))
5255 .list()
5256 .len(),
5257 0
5258 );
5259 t.hold_machine(Some("out of attempts".to_owned()));
5260 q.put(&mut t).unwrap();
5261 let listed = crate::notices::Notices::at(dir.path().join("notifications")).list();
5262 assert_eq!(listed.len(), 1);
5263 assert!(listed[0].message.contains("out of attempts"));
5264 }
5265
5266 #[test]
5267 fn start_consumes_the_disk_resume_pin() {
5268 let mut t = task("pin");
5269 t.disk_resume_run = Some("run-1".into());
5270 t.start("run-1".into());
5271 assert!(t.disk_resume_run.is_none());
5272 }
5273
5274 fn task(title: &str) -> Task {
5275 Task::new(
5276 title.to_owned(),
5277 format!("do {title}"),
5278 PathBuf::from("."),
5279 Source::Human,
5280 )
5281 }
5282
5283 #[test]
5284 fn issue_provenance_survives_queue_round_trip_without_inventing_chat() {
5285 let dir = tempfile::tempdir().unwrap();
5286 let q = Queue::at(dir.path().to_path_buf());
5287 let issue = IssueRef {
5288 number: 42,
5289 repo: "owner/repo".into(),
5290 };
5291 for source in [
5292 Source::Human,
5293 Source::Agent {
5294 run: "20260101-010101-abcd".into(),
5295 node: CHAT_NODE.into(),
5296 },
5297 ] {
5298 let mut t = task("issue");
5299 t.source = source;
5300 t.issue = Some(issue.clone());
5301 q.put(&mut t).unwrap();
5302 let saved = q.get(&t.id).unwrap();
5303 assert_eq!(saved.issue_ref(), Some(issue.clone()));
5304 assert_eq!(saved.source, t.source);
5305 assert_eq!(saved.filed_by_chat(), t.filed_by_chat());
5306 assert_eq!(saved.chat_talk(), t.filed_by_chat());
5307 if saved.source == Source::Human {
5308 assert_eq!(saved.source_label(), "issue #42");
5309 } else {
5310 assert!(saved.source_label().contains("issue #42"));
5311 }
5312 let mut stale = saved;
5313 stale.issue = None;
5314 q.put(&mut stale).unwrap();
5315 assert_eq!(q.get(&t.id).unwrap().issue_ref(), Some(issue.clone()));
5316 }
5317 let mut old = serde_json::to_value(task("legacy")).unwrap();
5318 old["schema"] = serde_json::json!(26);
5319 old["source"] = serde_json::json!({"kind":"issue","number":42,"repo":"owner/repo"});
5320 let legacy: Task = serde_json::from_value(old).unwrap();
5321 assert_eq!(legacy.issue_ref(), Some(issue));
5322 assert_eq!(legacy.filed_by_chat(), None);
5323 assert_eq!(legacy.chat_talk(), None);
5324 assert_eq!(legacy.source_label(), "issue #42");
5325 }
5326
5327 #[test]
5328 fn attempt_limit_inherits_old_records_and_controls_failure() {
5329 let mut t = task("budget");
5330 let mut old = serde_json::to_value(&t).unwrap();
5331 old.as_object_mut().unwrap().remove("attempt_limit");
5332 old["schema"] = serde_json::json!(15);
5333 let legacy: Task = serde_json::from_value(old).unwrap();
5334 assert_eq!(legacy.attempt_limit, None);
5335 assert_eq!(legacy.effective_attempt_limit(2), 2);
5336 t.attempts = 2;
5337 t.change_attempt_limit(NonZeroUsize::new(3)).unwrap();
5338 t.fail("retry", 1);
5339 assert_eq!(t.status, TaskStatus::Failed);
5340 t.attempts = 3;
5341 t.fail("stop", 10);
5342 assert_eq!(t.status, TaskStatus::Held);
5343 t.change_attempt_limit(None).unwrap();
5344 assert_eq!(t.status, TaskStatus::Held);
5345 assert_eq!(t.attempts, 3);
5346 t.fail("inherit", 4);
5347 assert_eq!(t.status, TaskStatus::Failed);
5348 for status in [
5349 TaskStatus::Running,
5350 TaskStatus::Done,
5351 TaskStatus::Failed,
5352 TaskStatus::Blocked,
5353 TaskStatus::Parked,
5354 ] {
5355 t.status = status;
5356 assert!(t.change_attempt_limit(NonZeroUsize::new(1)).is_err());
5357 assert_eq!(t.attempt_limit, None);
5358 }
5359 }
5360
5361 #[test]
5362 fn earlier_attempts_is_every_recorded_run_and_agrees_with_the_display() {
5363 let mut t = task("retried");
5364 assert!(
5365 t.earlier_attempts().is_empty(),
5366 "a first attempt takes nothing over"
5367 );
5368 t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned()];
5369 assert_eq!(t.earlier_attempts(), ["aaaa", "bbbb"]);
5370 assert_eq!(t.successor_of("aaaa"), Some(&"bbbb".to_owned()));
5372 assert_eq!(t.successor_of("bbbb"), None);
5373 assert_eq!(t.successor_of("zzzz"), None);
5374 }
5375
5376 #[test]
5377 fn resumed_runs_are_superseded_only_after_their_last_occurrence() {
5378 let (_dir, q) = queue();
5379 let mut t = task("resumed");
5380 for (runs, successor) in [
5381 (vec!["aaaa", "aaaa"], None),
5382 (vec!["aaaa", "bbbb", "aaaa"], None),
5383 (vec!["aaaa", "aaaa", "bbbb"], Some("bbbb")),
5384 (vec!["aaaa", "bbbb", "aaaa", "cccc"], Some("cccc")),
5385 ] {
5386 t.runs = runs.into_iter().map(str::to_owned).collect();
5387 q.put(&mut t).unwrap();
5388
5389 assert_eq!(t.successor_of("aaaa").map(String::as_str), successor);
5390 assert_eq!(q.superseded_by("aaaa").as_deref(), successor);
5391 assert_eq!(q.superseded().get("aaaa").map(String::as_str), successor);
5392 }
5393 }
5394
5395 #[test]
5396 fn superseded_by_names_the_next_attempt_and_none_for_the_last() {
5397 let (_dir, q) = queue();
5398 let mut t = task("retried");
5399 t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned(), "cccc".to_owned()];
5400 q.put(&mut t).unwrap();
5401
5402 assert_eq!(q.superseded_by("aaaa"), Some("bbbb".to_owned()));
5403 assert_eq!(q.superseded_by("bbbb"), Some("cccc".to_owned()));
5404 assert_eq!(
5405 q.superseded_by("cccc"),
5406 None,
5407 "the latest attempt replaces nothing"
5408 );
5409 assert_eq!(
5410 q.superseded_by("never-heard-of-it"),
5411 None,
5412 "a run belonging to no task on this queue is not superseded"
5413 );
5414
5415 let mut by = HashMap::new();
5416 by.insert("aaaa".to_owned(), "bbbb".to_owned());
5417 by.insert("bbbb".to_owned(), "cccc".to_owned());
5418 assert_eq!(
5419 q.superseded(),
5420 by,
5421 "the whole-map and single-run forms must agree"
5422 );
5423 }
5424
5425 #[test]
5426 fn superseded_attempts_is_empty_until_the_task_is_done() {
5427 let mut t = task("retried");
5428 t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned()];
5429 t.status = TaskStatus::Failed;
5430 assert_eq!(
5431 t.superseded_attempts(true),
5432 &[] as &[String],
5433 "a task still retrying has no attempt yet that a later one made moot"
5434 );
5435
5436 t.status = TaskStatus::Running;
5437 assert_eq!(t.superseded_attempts(true), &[] as &[String]);
5438 }
5439
5440 #[test]
5441 fn superseded_attempts_names_every_run_before_the_one_that_succeeded() {
5442 let mut t = task("retried");
5443 t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned(), "cccc".to_owned()];
5444 t.status = TaskStatus::Done;
5445 assert_eq!(
5446 t.superseded_attempts(true),
5447 &["aaaa".to_owned(), "bbbb".to_owned()],
5448 "cccc is the attempt whose success made the task done, and stays out"
5449 );
5450 }
5451
5452 #[test]
5453 fn superseded_attempts_is_empty_for_a_done_task_with_only_one_attempt() {
5454 let mut t = task("first try landed");
5455 t.runs = vec!["aaaa".to_owned()];
5456 t.status = TaskStatus::Done;
5457 assert_eq!(t.superseded_attempts(true), &[] as &[String]);
5458 }
5459
5460 #[test]
5461 fn superseded_attempts_is_empty_when_the_last_run_never_actually_succeeded() {
5462 let mut t = task("closed by hand after a manual merge");
5469 t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned()];
5470 t.status = TaskStatus::Done;
5471 assert_eq!(
5472 t.superseded_attempts(false),
5473 &[] as &[String],
5474 "nothing here is provably why the task is done, so nothing is superseded"
5475 );
5476 }
5477
5478 #[test]
5479 fn latest_attempt_names_the_chain_s_current_head_not_just_the_next_one() {
5480 let (_dir, q) = queue();
5481 let mut t = task("retried twice");
5482 t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned(), "cccc".to_owned()];
5483 q.put(&mut t).unwrap();
5484
5485 assert_eq!(
5486 q.latest_attempt("aaaa"),
5487 Some("cccc".to_owned()),
5488 "an old attempt points straight at the chain's current head, not the \
5489 next attempt in the middle of it"
5490 );
5491 assert_eq!(q.latest_attempt("bbbb"), Some("cccc".to_owned()));
5492 assert_eq!(
5493 q.latest_attempt("cccc"),
5494 None,
5495 "the latest attempt is not superseded by anything"
5496 );
5497 assert_eq!(
5498 q.latest_attempt("never-heard-of-it"),
5499 None,
5500 "a run belonging to no task on this queue is not superseded"
5501 );
5502 }
5503
5504 #[test]
5505 fn a_markdown_heading_is_the_title_not_decoration() {
5506 assert_eq!(
5511 title_from("# Rework the config loader\n\nIt re-reads it.\n", 40),
5512 "Rework the config loader"
5513 );
5514 assert_eq!(title_from("- fix the thing", 40), "fix the thing");
5515 assert_eq!(title_from("> quoted task", 40), "quoted task");
5516 assert_eq!(title_from(" \n\n", 40), "(empty task)");
5518 assert_eq!(title_from("###\n", 40), "(empty task)");
5519 }
5520
5521 #[test]
5522 fn a_long_title_is_elided_by_characters_not_bytes() {
5523 let long = "課題".repeat(30);
5525 let title = title_from(&long, 10);
5526 assert_eq!(title.chars().count(), 10);
5527 assert!(title.ends_with('…'));
5528 }
5529
5530 #[test]
5531 fn priority_wins_and_ties_break_oldest_first() {
5532 let (_dir, q) = queue();
5533 let mut a = task("first");
5534 let mut b = task("second");
5535 let mut c = task("urgent");
5536 a.id = "20260101-000001-aaaa".to_owned();
5538 b.id = "20260101-000002-bbbb".to_owned();
5539 c.id = "20260101-000003-cccc".to_owned();
5540 c.priority = 5;
5541 for t in [&mut a, &mut b, &mut c] {
5542 q.put(t).unwrap();
5543 }
5544
5545 assert_eq!(q.next_runnable().unwrap().id, c.id);
5547 c.hold_machine(None);
5548 q.put(&mut c).unwrap();
5549 assert_eq!(q.next_runnable().unwrap().id, a.id);
5551 assert_eq!(q.list().len(), 3, "b is still waiting its turn");
5552 }
5553
5554 #[test]
5555 fn a_blocked_task_never_starves_another_runnable_one() {
5556 let (_dir, q) = queue();
5557 let mut blocked = task("blocked");
5558 blocked.block(vec!["something".to_owned()], None);
5559 q.put(&mut blocked).unwrap();
5560
5561 let mut runnable = task("free to go");
5562 q.put(&mut runnable).unwrap();
5563
5564 let next = q.next_runnable().expect("a runnable task is still offered");
5565 assert_eq!(next.id, runnable.id);
5566 }
5567
5568 #[test]
5569 fn a_held_task_is_never_offered_to_the_loop() {
5570 let (_dir, q) = queue();
5571 let mut t = task("held");
5572 q.put(&mut t).unwrap();
5573 assert!(q.next_runnable().is_some());
5574
5575 t.hold_machine(None);
5576 q.put(&mut t).unwrap();
5577 assert!(
5578 q.next_runnable().is_none(),
5579 "a held task must wait for a human"
5580 );
5581
5582 t.status = TaskStatus::Failed;
5584 q.put(&mut t).unwrap();
5585 assert!(q.next_runnable().is_some());
5586 }
5587
5588 #[test]
5589 fn attempts_are_capped_and_then_the_task_is_held() {
5590 let mut t = task("doomed");
5591
5592 t.start("run-1".to_owned());
5593 t.fail("gate red", 2);
5594 assert_eq!(t.status, TaskStatus::Failed, "one attempt of two: retry");
5595
5596 t.start("run-2".to_owned());
5597 t.fail("gate red", 2);
5598 assert_eq!(
5599 t.status,
5600 TaskStatus::Held,
5601 "out of attempts: stop spending money on it"
5602 );
5603 assert_eq!(t.runs, ["run-1", "run-2"]);
5604 assert_eq!(t.last_error.as_deref(), Some("gate red"));
5605 assert_eq!(
5606 t.hold_reason.as_deref(),
5607 Some("gate red"),
5608 "the hold must say why, not leave hold_reason null next to a \
5609 populated last_error"
5610 );
5611 }
5612
5613 #[test]
5614 fn handing_off_a_task_records_a_hold_reason_too() {
5615 let mut t = task("left a pull request");
5616 t.start("run-1".to_owned());
5617 t.handed_off("run ended with a pull request open [run run-1]");
5618 assert_eq!(t.status, TaskStatus::Held);
5619 assert_eq!(t.hold_source, Some(HoldSource::Machine));
5620 assert_eq!(
5621 t.hold_reason.as_deref(),
5622 Some("run ended with a pull request open [run run-1]")
5623 );
5624 assert_eq!(t.hold_reason, t.last_error);
5625 }
5626
5627 #[test]
5628 fn a_quota_stall_is_refunded_so_the_backlog_survives_the_night() {
5629 let mut t = task("stalled by quota");
5630
5631 t.start("run-1".to_owned());
5632 assert_eq!(t.attempts, 1);
5633 t.stall("judge-1, judge-2 out of quota");
5634 assert_eq!(
5635 t.attempts, 0,
5636 "a closed quota window must not spend the task's retry budget"
5637 );
5638 assert_eq!(t.status, TaskStatus::Failed, "the loop should retry it");
5639 assert_eq!(
5640 t.last_error.as_deref(),
5641 Some("judge-1, judge-2 out of quota")
5642 );
5643
5644 for _ in 0..20 {
5647 t.start("run-n".to_owned());
5648 t.stall("still out of quota");
5649 }
5650 t.start("run-real".to_owned());
5651 t.fail("gate red", 2);
5652 assert_eq!(
5653 t.status,
5654 TaskStatus::Failed,
5655 "the first attempt that was really judged is attempt one"
5656 );
5657 }
5658
5659 #[test]
5660 fn releasing_a_held_task_gives_it_a_real_second_chance() {
5661 let mut t = task("retry me");
5662 t.start("run-1".to_owned());
5663 t.fail("gate red", 1);
5664 assert_eq!(t.status, TaskStatus::Held);
5665
5666 t.release();
5667 assert_eq!(t.status, TaskStatus::Queued);
5668 assert_eq!(t.attempts, 0);
5671 assert!(t.last_error.is_none());
5672 assert_eq!(
5673 t.runs.len(),
5674 1,
5675 "history is kept: attempts reset, evidence does not"
5676 );
5677 }
5678
5679 #[test]
5680 fn a_hold_reason_survives_and_a_release_clears_it() {
5681 let mut t = task("waiting on something else");
5682 t.hold_manual(Some(
5683 "waiting for 20260101-000000-aaaa to land first".to_owned(),
5684 ));
5685 assert_eq!(t.status, TaskStatus::Held);
5686 assert_eq!(
5687 t.hold_reason.as_deref(),
5688 Some("waiting for 20260101-000000-aaaa to land first")
5689 );
5690
5691 t.hold_manual(None);
5693 assert_eq!(
5694 t.hold_reason.as_deref(),
5695 Some("waiting for 20260101-000000-aaaa to land first"),
5696 "a bare re-hold keeps whatever a human already wrote down"
5697 );
5698
5699 let mut plain = task("no reason given");
5701 plain.hold_manual(None);
5702 assert_eq!(plain.status, TaskStatus::Held);
5703 assert!(plain.hold_reason.is_none());
5704
5705 t.release();
5706 assert_eq!(t.status, TaskStatus::Queued);
5707 assert!(
5708 t.hold_reason.is_none(),
5709 "a stale reason must not greet the next person who holds this task"
5710 );
5711 }
5712
5713 #[test]
5714 fn closing_a_held_task_as_done_clears_its_hold_reason_too() {
5715 let mut t = task("landed by hand while held");
5720 t.hold_manual(Some("waiting on 3ed9".to_owned()));
5721 assert_eq!(t.hold_reason.as_deref(), Some("waiting on 3ed9"));
5722
5723 t.succeed(completion(&t));
5724 assert_eq!(t.status, TaskStatus::Done);
5725 assert!(
5726 t.hold_reason.is_none(),
5727 "a done task cannot still be waiting on something"
5728 );
5729 }
5730
5731 #[test]
5732 fn holding_or_closing_a_blocked_task_clears_its_dependency_too() {
5733 let mut held = task("held straight out of blocked");
5740 held.block(
5741 vec!["20260101-000000-dead".to_owned()],
5742 Some("waiting on the migration script".to_owned()),
5743 );
5744 assert_eq!(held.status, TaskStatus::Blocked);
5745
5746 held.hold_manual(None);
5747 assert_eq!(held.status, TaskStatus::Held);
5748 assert!(
5749 held.blocked_by.is_empty(),
5750 "hold overrides the wait, same as release"
5751 );
5752 assert!(held.block_reason.is_none());
5753
5754 let mut done = task("closed straight out of blocked");
5755 done.block(
5756 vec!["20260101-000000-dead".to_owned()],
5757 Some("waiting on the migration script".to_owned()),
5758 );
5759 done.succeed(completion(&done));
5760 assert_eq!(done.status, TaskStatus::Done);
5761 assert!(
5762 done.blocked_by.is_empty(),
5763 "a done task cannot still be waiting on a dependency"
5764 );
5765 assert!(done.block_reason.is_none());
5766 }
5767
5768 #[test]
5769 fn a_blocked_task_is_never_offered_to_the_loop() {
5770 let mut t = task("blocked");
5771 assert!(t.status.runnable());
5772 t.block(
5773 vec!["dep-id".to_owned()],
5774 Some("waits on dep-id".to_owned()),
5775 );
5776 assert_eq!(t.status, TaskStatus::Blocked);
5777 assert!(!t.status.runnable());
5778 assert_eq!(TaskStatus::Blocked.as_str(), "blocked");
5779 }
5780
5781 #[test]
5782 fn unblocking_the_last_dependency_returns_the_task_to_queued() {
5783 let mut t = task("blocked on two");
5784 t.block(
5785 vec!["a".to_owned(), "b".to_owned()],
5786 Some("waits on a and b".to_owned()),
5787 );
5788
5789 t.unblock("a");
5790 assert_eq!(t.status, TaskStatus::Blocked, "b is still outstanding");
5791 assert_eq!(t.blocked_by, ["b"]);
5792
5793 t.unblock("b");
5794 assert_eq!(t.status, TaskStatus::Queued);
5795 assert!(t.blocked_by.is_empty());
5796 assert!(t.block_reason.is_none());
5797 }
5798
5799 #[test]
5800 fn unblocking_an_id_on_a_task_that_is_not_blocked_is_a_no_op() {
5801 let mut t = task("never blocked");
5802 t.unblock("whatever");
5803 assert_eq!(t.status, TaskStatus::Queued);
5804 }
5805
5806 #[test]
5807 fn a_held_task_blocked_on_a_question_returns_to_held_not_queued() {
5808 let mut t = task("held, then asked about");
5813 t.hold_machine(Some("out of attempts".to_owned()));
5814 assert_eq!(t.status, TaskStatus::Held);
5815
5816 t.block(vec!["q1".to_owned()], Some("what now?".to_owned()));
5817 assert_eq!(t.status, TaskStatus::Blocked);
5818
5819 t.record_answer("what now?".to_owned(), "leave it held".to_owned());
5820 t.unblock("q1");
5821 assert_eq!(t.status, TaskStatus::Held, "must restore, not requeue");
5822 assert_eq!(t.hold_reason.as_deref(), Some("out of attempts"));
5823 assert_eq!(t.hold_source, Some(HoldSource::Machine));
5824 assert!(t.blocked_from.is_none(), "consumed once restored");
5825 }
5826
5827 #[test]
5828 fn a_manually_held_task_blocked_on_a_question_returns_to_held() {
5829 let mut t = task("manually held, then asked about");
5830 t.hold_manual(Some("waiting on a dependency".to_owned()));
5831
5832 t.block(vec!["q1".to_owned()], None);
5833 t.unblock("q1");
5834
5835 assert_eq!(t.status, TaskStatus::Held);
5836 assert_eq!(t.hold_source, Some(HoldSource::Manual));
5837 }
5838
5839 #[test]
5840 fn re_blocking_an_already_blocked_task_keeps_the_original_blocked_from() {
5841 let mut t = task("held, blocked twice");
5845 t.hold_machine(None);
5846 t.block(vec!["q1".to_owned()], Some("first".to_owned()));
5847 t.block(
5848 vec!["q1".to_owned(), "q2".to_owned()],
5849 Some("second".to_owned()),
5850 );
5851
5852 t.unblock("q1");
5853 assert_eq!(t.status, TaskStatus::Blocked, "q2 still outstanding");
5854 t.unblock("q2");
5855 assert_eq!(t.status, TaskStatus::Held);
5856 }
5857
5858 #[test]
5859 fn unblocking_a_task_blocked_while_running_lands_on_queued_not_running() {
5860 let mut t = task("blocked mid-run");
5864 t.start("run-1".to_owned());
5865 assert_eq!(t.status, TaskStatus::Running);
5866
5867 t.block(vec!["q1".to_owned()], None);
5868 t.unblock("q1");
5869 assert_eq!(t.status, TaskStatus::Queued);
5870 }
5871
5872 #[test]
5873 fn a_pre_schema_4_blocked_record_with_hold_evidence_restores_to_held() {
5874 let mut t = task("legacy record, held before it was blocked");
5880 t.hold_source = Some(HoldSource::Machine);
5881 t.hold_reason = Some("legacy hold reason".to_owned());
5882 t.status = TaskStatus::Blocked;
5883 t.blocked_by = vec!["q1".to_owned()];
5884 t.blocked_from = None;
5885
5886 t.unblock("q1");
5887 assert_eq!(t.status, TaskStatus::Held);
5888 }
5889
5890 #[test]
5891 fn a_pre_schema_4_blocked_record_with_no_hold_evidence_restores_to_queued() {
5892 let mut t = task("legacy record, ordinary dependency block");
5893 t.status = TaskStatus::Blocked;
5894 t.blocked_by = vec!["dep".to_owned()];
5895 t.blocked_from = None;
5896
5897 t.unblock("dep");
5898 assert_eq!(t.status, TaskStatus::Queued);
5899 }
5900
5901 #[test]
5902 fn answering_a_question_is_recorded_and_survives_a_release() {
5903 let mut t = task("asked something");
5904 t.block(vec!["q1".to_owned()], Some("which backend?".to_owned()));
5905 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
5906 t.unblock("q1");
5907 assert_eq!(t.status, TaskStatus::Queued);
5908 assert_eq!(t.answers.len(), 1);
5909 assert_eq!(t.answers[0].answer, "SQLite");
5910
5911 t.release();
5915 assert_eq!(t.answers.len(), 1, "the answer is not lost on release");
5916 }
5917
5918 #[test]
5919 fn resumption_review_branch_requires_unchanged_authored_criteria() {
5920 for source in ["cli", "web"] {
5921 let mut t = task("review old candidate");
5922 t.request_review("candidate-A".into());
5923 t.hold_for_handover(Some("candidate-A".into()), "handover refused".into());
5924 let mut unchanged = t.clone();
5925 unchanged.release_operator(source, None);
5926 assert_eq!(unchanged.review_branch.as_deref(), Some("candidate-A"));
5927 t.edit(
5928 "review approved head".into(),
5929 "Reuse measured PR head B; fix Clippy; review".into(),
5930 )
5931 .unwrap();
5932 t.release_operator(source, None);
5933 assert!(t.review_branch.is_none());
5934 assert!(t.review_instruction.is_none());
5935 let mut legacy = unchanged;
5937 legacy.review_instruction = None;
5938 legacy.hold_for_handover(None, "still checked out".into());
5939 legacy
5940 .edit("new plan".into(), "Reuse measured PR head B".into())
5941 .unwrap();
5942 legacy.release_operator(source, None);
5943 assert!(legacy.review_branch.is_none());
5944 }
5945 }
5946
5947 #[test]
5948 fn a_refused_handover_keeps_the_review_branch_across_release() {
5949 let mut t = task("refused takeover");
5950 t.start("run-1".to_owned());
5951 t.hold_for_handover(Some("magi/eba2/A".to_owned()), "checked out".to_owned());
5952 assert_eq!(t.status, TaskStatus::Held);
5953 assert_eq!(t.attempts, 1);
5954 t.release();
5955 assert_eq!(t.status, TaskStatus::Queued);
5956 assert_eq!(t.attempts, 0);
5957 assert_eq!(t.review_branch.as_deref(), Some("magi/eba2/A"));
5958
5959 t.hold_for_handover(None, "again".to_owned());
5961 t.requeue();
5962 assert!(t.review_branch.is_none());
5963
5964 let mut m = task("manual");
5966 m.review_branch = Some("magi/x/A".to_owned());
5967 m.hold_manual(None);
5968 m.release();
5969 assert!(m.review_branch.is_none());
5970 }
5971
5972 #[test]
5973 fn requesting_review_requeues_the_task_and_remembers_the_branch() {
5974 let mut t = task("blocked run with a surviving branch");
5975 t.start("run-1".to_owned());
5976 t.fail("blocked with major findings", 5);
5977 assert_eq!(t.status, TaskStatus::Failed);
5978
5979 t.request_review("magi/eba2/A".to_owned());
5980 assert_eq!(t.status, TaskStatus::Queued);
5981 assert_eq!(t.attempts, 0);
5982 assert_eq!(t.review_branch.as_deref(), Some("magi/eba2/A"));
5983
5984 t.release();
5986 assert!(t.review_branch.is_none());
5987 }
5988
5989 #[test]
5990 fn conductor_requeue_but_not_an_ordinary_release_forces_a_fresh_start() {
5991 let mut t = task("retry");
5992 t.start("run-1".to_owned());
5993 t.requeue();
5994 assert!(t.fresh_start);
5995
5996 t.release();
5997 assert!(!t.fresh_start);
5998 }
5999
6000 #[test]
6001 fn urgent_only_changes_queued_or_held_and_preserves_settings() {
6002 for status in [
6003 TaskStatus::Queued,
6004 TaskStatus::Held,
6005 TaskStatus::Running,
6006 TaskStatus::Done,
6007 TaskStatus::Failed,
6008 TaskStatus::Blocked,
6009 TaskStatus::Parked,
6010 ] {
6011 let mut t = task("urgent settings");
6012 t.status = status;
6013 t.attempts = 2;
6014 t.hold_reason = Some("waiting".into());
6015 t.priority = 7;
6016 t.interrupt = true;
6017 let before = serde_json::to_value(&t).unwrap();
6018 for urgent in [true, true, false, false] {
6019 let result = t.set_urgent(urgent);
6020 let mut expected = before.clone();
6021 if matches!(status, TaskStatus::Queued | TaskStatus::Held) {
6022 result.unwrap();
6023 expected["urgent"] = urgent.into();
6024 } else {
6025 let error = result.unwrap_err().to_string();
6026 assert!(error.contains(status.as_str()), "{error}");
6027 assert!(error.contains("queued or held"), "{error}");
6028 }
6029 assert_eq!(serde_json::to_value(&t).unwrap(), expected);
6030 }
6031 }
6032 }
6033
6034 #[test]
6035 fn immediate_only_changes_queued_or_held_and_preserves_settings() {
6036 for status in [
6037 TaskStatus::Queued,
6038 TaskStatus::Held,
6039 TaskStatus::Running,
6040 TaskStatus::Done,
6041 TaskStatus::Failed,
6042 TaskStatus::Blocked,
6043 TaskStatus::Parked,
6044 ] {
6045 let mut t = task("immediate settings");
6046 t.status = status;
6047 t.attempts = 2;
6048 t.hold_reason = Some("waiting".into());
6049 t.priority = 7;
6050 t.interrupt = true;
6051 t.urgent = true;
6052 let before = serde_json::to_value(&t).unwrap();
6053 for immediate in [true, true, false, false] {
6054 let result = t.set_immediate(immediate);
6055 let mut expected = before.clone();
6056 if matches!(status, TaskStatus::Queued | TaskStatus::Held) {
6057 result.unwrap();
6058 expected["immediate"] = immediate.into();
6059 } else {
6060 let error = result.unwrap_err().to_string();
6061 assert!(error.contains(status.as_str()), "{error}");
6062 assert!(error.contains("queued or held"), "{error}");
6063 }
6064 assert_eq!(serde_json::to_value(&t).unwrap(), expected);
6065 assert!(t.urgent, "changing immediate must preserve saved urgent");
6066 }
6067 }
6068 }
6069
6070 #[test]
6071 fn a_task_recorded_without_an_immediate_field_still_reads_as_not_immediate() {
6072 let (_dir, q) = queue();
6073 let path = q.path_of("20260101-000000-imm0");
6074 std::fs::create_dir_all(q.root()).unwrap();
6075 std::fs::write(
6076 &path,
6077 serde_json::json!({
6078 "schema": SCHEMA,
6079 "id": "20260101-000000-imm0",
6080 "title": "from before immediate existed",
6081 "instruction": "from before immediate existed",
6082 "repo": ".",
6083 "source": { "kind": "human" },
6084 "status": "queued",
6085 "urgent": true,
6086 "created_at": Timestamp::now().to_string(),
6087 "updated_at": Timestamp::now().to_string(),
6088 })
6089 .to_string(),
6090 )
6091 .unwrap();
6092
6093 let task = q.get("20260101-000000-imm0").expect("must still read");
6094 assert!(!task.immediate);
6095 assert!(task.urgent);
6096 }
6097
6098 #[test]
6099 fn immediate_reuses_urgent_isolation_and_explicit_cache_wins() {
6100 let mut cfg = crate::config::Config::default();
6101 cfg.verify.e2e = vec!["CARGO_TARGET_DIR=/tmp/shared-target cargo test".into()];
6102 let mut t = task("immediate cache");
6103
6104 t.set_immediate(true).unwrap();
6105 assert_eq!(
6106 t.build_cache_override(&cfg),
6107 Some((BuildCache::Isolated, "immediate"))
6108 );
6109
6110 t.set_urgent(true).unwrap();
6112 assert_eq!(
6113 t.build_cache_override(&cfg),
6114 Some((BuildCache::Isolated, "immediate"))
6115 );
6116
6117 t.change_build_cache(Some(BuildCache::Shared)).unwrap();
6119 assert_eq!(
6120 t.build_cache_override(&cfg),
6121 Some((BuildCache::Shared, "task-override"))
6122 );
6123
6124 t.change_build_cache(None).unwrap();
6126 assert_eq!(
6127 t.build_cache_override(&cfg),
6128 Some((BuildCache::Isolated, "immediate"))
6129 );
6130 t.set_immediate(false).unwrap();
6131 assert_eq!(
6132 t.build_cache_override(&cfg),
6133 Some((BuildCache::Isolated, "urgent"))
6134 );
6135
6136 t.set_immediate(true).unwrap();
6138 cfg.verify.e2e = vec!["CARGO_TARGET_DIR=/tmp/shared-target cargo test | tee log".into()];
6139 assert_eq!(t.build_cache_override(&cfg), None);
6140 }
6141
6142 #[test]
6143 fn priority_can_be_changed_while_queued_but_not_while_running() {
6144 let mut t = task("reprioritise me");
6145 t.set_priority(5).unwrap();
6146 assert_eq!(t.priority, 5);
6147
6148 t.start("run-1".to_owned());
6149 let err = t.set_priority(9).unwrap_err().to_string();
6150 assert!(err.contains("running"), "{err}");
6151 assert_eq!(t.priority, 5, "the rejected write must not partially apply");
6152 }
6153
6154 #[test]
6155 fn interrupt_can_be_marked_while_queued_but_not_while_running() {
6156 let mut t = task("interrupt me");
6157 assert!(!t.interrupt, "off unless asked, same as any other task");
6158
6159 t.set_interrupt(true).unwrap();
6160 assert!(t.interrupt);
6161
6162 t.start("run-1".to_owned());
6163 assert!(
6164 !t.interrupt,
6165 "the mark is one-shot: dispatching the task fulfils it, \
6166 whatever the run that follows ends up doing"
6167 );
6168 let err = t.set_interrupt(true).unwrap_err().to_string();
6169 assert!(err.contains("running"), "{err}");
6170 t.set_interrupt(false).unwrap();
6173 assert!(!t.interrupt);
6174 }
6175
6176 #[test]
6180 fn a_failed_run_does_not_leave_the_task_still_marked_to_interrupt() {
6181 let mut t = task("interrupt me");
6182 t.set_interrupt(true).unwrap();
6183 t.start("run-1".to_owned());
6184 t.fail("mock failure", 5);
6185 assert_eq!(t.status, TaskStatus::Failed);
6186 assert!(
6187 !t.interrupt,
6188 "one attempt already spent the mark; a retry is an ordinary \
6189 requeue, not a fresh interrupt request"
6190 );
6191 }
6192
6193 #[test]
6194 fn changing_priority_moves_a_task_ahead_in_the_real_queue_order() {
6195 let (_dir, q) = queue();
6196 let mut a = task("first filed");
6197 let mut b = task("second filed");
6198 a.id = "20260101-000001-aaaa".to_owned();
6199 b.id = "20260101-000002-bbbb".to_owned();
6200 q.put(&mut a).unwrap();
6201 q.put(&mut b).unwrap();
6202
6203 assert_eq!(
6204 q.next_runnable().unwrap().id,
6205 a.id,
6206 "with equal priority the older task goes first, so a burst of \
6207 new work cannot starve it"
6208 );
6209 assert_eq!(
6210 q.list()[0].id,
6211 b.id,
6212 "but the list an operator reads is newest first, the same as \
6213 before priority existed - a's turn to run does not make it the \
6214 newest task"
6215 );
6216
6217 let mut a = q.get(&a.id).unwrap();
6218 a.set_priority(10).unwrap();
6219 q.put(&mut a).unwrap();
6220
6221 assert_eq!(
6222 q.next_runnable().unwrap().id,
6223 a.id,
6224 "a raised priority must be reflected the moment it is saved"
6225 );
6226 assert_eq!(
6230 q.list()[0].id,
6231 a.id,
6232 "the raised task must sort first in the list an operator reads, \
6233 not only in next_runnable's own ordering"
6234 );
6235 }
6236
6237 #[test]
6238 fn editing_replaces_title_and_instruction_but_keeps_identity_and_history() {
6239 let mut t = Task::new(
6240 "old title".to_owned(),
6241 "old instruction".to_owned(),
6242 PathBuf::from("/repo"),
6243 Source::Agent {
6244 run: "20260101-000000-beef".to_owned(),
6245 node: "implement".to_owned(),
6246 },
6247 );
6248 let id = t.id.clone();
6249 let created_at = t.created_at;
6250 t.runs.push("20260101-000000-beef".to_owned());
6251
6252 t.edit("new title".to_owned(), "new instruction".to_owned())
6253 .unwrap();
6254
6255 assert_eq!(t.title, "new title");
6256 assert_eq!(t.instruction, "new instruction");
6257 assert_eq!(t.id, id, "editing must not mint a new id");
6258 assert_eq!(t.created_at, created_at);
6259 assert_eq!(
6260 t.source,
6261 Source::Agent {
6262 run: "20260101-000000-beef".to_owned(),
6263 node: "implement".to_owned(),
6264 },
6265 "editing must not turn agent attribution into human"
6266 );
6267 assert_eq!(t.runs, ["20260101-000000-beef"]);
6268 }
6269
6270 #[test]
6271 fn editing_is_refused_once_a_task_is_running_or_finished() {
6272 let mut running = task("in flight");
6273 running.start("run-1".to_owned());
6274 let err = running
6275 .edit("x".to_owned(), "y".to_owned())
6276 .unwrap_err()
6277 .to_string();
6278 assert!(err.contains("running"), "{err}");
6279
6280 let mut done = task("finished");
6281 done.succeed(completion(&done));
6282 let err = done
6283 .edit("x".to_owned(), "y".to_owned())
6284 .unwrap_err()
6285 .to_string();
6286 assert!(err.contains("done"), "{err}");
6287
6288 let mut queued = task("waiting");
6290 queued.edit("x".to_owned(), "y".to_owned()).unwrap();
6291 let mut held = task("parked");
6292 held.hold_machine(None);
6293 held.edit("x".to_owned(), "y".to_owned()).unwrap();
6294 }
6295
6296 #[test]
6297 fn a_task_recorded_without_a_hold_reason_still_reads_as_none() {
6298 let (_dir, q) = queue();
6299 let path = q.path_of("20260101-000000-aaaa");
6300 std::fs::create_dir_all(q.root()).unwrap();
6301 std::fs::write(
6302 &path,
6303 serde_json::json!({
6304 "schema": SCHEMA,
6305 "id": "20260101-000000-aaaa",
6306 "title": "from before hold reasons existed",
6307 "instruction": "from before hold reasons existed",
6308 "repo": ".",
6309 "source": { "kind": "human" },
6310 "status": "held",
6311 "created_at": Timestamp::now().to_string(),
6312 "updated_at": Timestamp::now().to_string(),
6313 })
6314 .to_string(),
6315 )
6316 .unwrap();
6317
6318 let task = q.get("20260101-000000-aaaa").expect("must still read");
6319 assert!(task.hold_reason.is_none());
6320 assert!(task.operator_held());
6321 }
6322
6323 #[test]
6324 fn a_legacy_reasoned_hold_defaults_to_operator_protection() {
6325 let (_dir, q) = queue();
6326 let path = q.path_of("20260101-000000-bbbb");
6327 std::fs::create_dir_all(q.root()).unwrap();
6328 std::fs::write(
6329 &path,
6330 serde_json::json!({
6331 "schema": 2,
6332 "id": "20260101-000000-bbbb",
6333 "title": "old manual recovery",
6334 "instruction": "old manual recovery",
6335 "repo": ".",
6336 "source": { "kind": "human" },
6337 "status": "held",
6338 "hold_reason": "active manual recovery run20260912-224242-daf5",
6339 "created_at": Timestamp::now().to_string(),
6340 "updated_at": Timestamp::now().to_string(),
6341 })
6342 .to_string(),
6343 )
6344 .unwrap();
6345
6346 let task = q.get("20260101-000000-bbbb").expect("must still read");
6347 assert_eq!(task.hold_source, None);
6348 assert!(task.operator_held());
6349 }
6350
6351 #[test]
6352 fn a_task_recorded_without_a_diagnostic_still_reads_as_none() {
6353 let (_dir, q) = queue();
6354 let path = q.path_of("20260101-000000-aaaa");
6355 std::fs::create_dir_all(q.root()).unwrap();
6356 std::fs::write(
6357 &path,
6358 serde_json::json!({
6359 "schema": SCHEMA,
6360 "id": "20260101-000000-aaaa",
6361 "title": "from before diagnostics existed",
6362 "instruction": "from before diagnostics existed",
6363 "repo": ".",
6364 "source": { "kind": "human" },
6365 "status": "held",
6366 "created_at": Timestamp::now().to_string(),
6367 "updated_at": Timestamp::now().to_string(),
6368 })
6369 .to_string(),
6370 )
6371 .unwrap();
6372
6373 let task = q.get("20260101-000000-aaaa").expect("must still read");
6374 assert!(task.diagnostic.is_none());
6375 }
6376
6377 #[test]
6378 fn a_schema_1_task_with_no_blocking_fields_still_reads() {
6379 let (_dir, q) = queue();
6383 let path = q.path_of("20260101-000000-aaaa");
6384 std::fs::create_dir_all(q.root()).unwrap();
6385 std::fs::write(
6386 &path,
6387 serde_json::json!({
6388 "schema": 1,
6389 "id": "20260101-000000-aaaa",
6390 "title": "from before blocking existed",
6391 "instruction": "from before blocking existed",
6392 "repo": ".",
6393 "source": { "kind": "human" },
6394 "status": "queued",
6395 "created_at": Timestamp::now().to_string(),
6396 "updated_at": Timestamp::now().to_string(),
6397 })
6398 .to_string(),
6399 )
6400 .unwrap();
6401
6402 let task = q.get("20260101-000000-aaaa").expect("must still read");
6403 assert!(task.blocked_by.is_empty());
6404 assert!(task.block_reason.is_none());
6405 assert!(task.answers.is_empty());
6406 assert!(task.review_branch.is_none());
6407 }
6408
6409 #[test]
6410 fn releasing_or_finishing_a_task_clears_its_stale_diagnostic() {
6411 let mut held = task("diagnosed");
6416 held.start("run-1".to_owned());
6417 held.fail("gate red", 1);
6418 held.diagnostic = Some("cargo test failed: ...".to_owned());
6419 assert_eq!(held.status, TaskStatus::Held);
6420
6421 held.release();
6422 assert!(held.diagnostic.is_none());
6423
6424 held.diagnostic = Some("cargo test failed: ...".to_owned());
6425 held.succeed(completion(&held));
6426 assert!(held.diagnostic.is_none());
6427 }
6428
6429 #[test]
6430 fn failing_a_task_always_clears_whatever_diagnostic_it_carried() {
6431 let mut t = task("retried");
6432 t.start("run-1".to_owned());
6433 t.diagnostic = Some("stale evidence from a previous hold".to_owned());
6434 t.fail("unrelated config error", 5);
6435 assert_eq!(t.status, TaskStatus::Failed);
6436 assert!(
6437 t.diagnostic.is_none(),
6438 "fail() must not let an old diagnostic outlive the run that produced it"
6439 );
6440 }
6441
6442 #[test]
6443 fn a_claim_is_exclusive_and_releases_on_drop() {
6444 let (_dir, q) = queue();
6445 let mut t = task("contended");
6446 q.put(&mut t).unwrap();
6447
6448 let held = q.claim(&t.id).unwrap();
6449 assert!(
6450 q.claim(&t.id).is_err(),
6451 "two daemons must not drive one task into two runs"
6452 );
6453 drop(held);
6454 assert!(q.claim(&t.id).is_ok(), "a released claim is reclaimable");
6455 }
6456
6457 #[test]
6458 fn a_round_trip_survives_disk() {
6459 let (_dir, q) = queue();
6460 let mut t = Task::new(
6461 "titled".to_owned(),
6462 "body".to_owned(),
6463 PathBuf::from("/repo"),
6464 Source::Agent {
6465 run: "20260101-000000-beef".to_owned(),
6466 node: "implement".to_owned(),
6467 },
6468 );
6469 t.priority = 3;
6470 q.put(&mut t).unwrap();
6471
6472 let back = q.get(&t.id).unwrap();
6473 assert_eq!(back.id, t.id);
6474 assert_eq!(back.priority, 3);
6475 assert_eq!(back.source.label(), "implement@beef");
6476 assert_eq!(q.get(t.short()).unwrap().id, t.id);
6478 }
6479
6480 #[test]
6481 fn an_unreadable_task_does_not_take_the_queue_down() {
6482 let (_dir, q) = queue();
6483 let mut t = task("fine");
6484 q.put(&mut t).unwrap();
6485 std::fs::write(q.root().join("broken.json"), "{ not json").unwrap();
6486
6487 let listed = q.list();
6488 assert_eq!(listed.len(), 1, "the readable task still lists");
6489 assert_eq!(listed[0].id, t.id);
6490 }
6491
6492 #[test]
6493 fn a_task_recorded_without_a_solo_field_still_reads_as_not_solo() {
6494 let (_dir, q) = queue();
6495 let path = q.path_of("20260101-000000-aaaa");
6496 std::fs::create_dir_all(q.root()).unwrap();
6497 std::fs::write(
6498 &path,
6499 serde_json::json!({
6500 "schema": SCHEMA,
6501 "id": "20260101-000000-aaaa",
6502 "title": "from before solo existed",
6503 "instruction": "from before solo existed",
6504 "repo": ".",
6505 "source": { "kind": "human" },
6506 "status": "queued",
6507 "created_at": Timestamp::now().to_string(),
6508 "updated_at": Timestamp::now().to_string(),
6509 })
6510 .to_string(),
6511 )
6512 .unwrap();
6513
6514 let task = q.get("20260101-000000-aaaa").expect("must still read");
6515 assert!(!task.solo, "a queue file with no `solo` field means false");
6516 }
6517
6518 #[test]
6519 fn a_task_recorded_without_an_urgent_field_still_reads_as_not_urgent() {
6520 let (_dir, q) = queue();
6521 let path = q.path_of("20260101-000000-bbbb");
6522 std::fs::create_dir_all(q.root()).unwrap();
6523 std::fs::write(
6524 &path,
6525 serde_json::json!({
6526 "schema": SCHEMA,
6527 "id": "20260101-000000-bbbb",
6528 "title": "from before urgent existed",
6529 "instruction": "from before urgent existed",
6530 "repo": ".",
6531 "source": { "kind": "human" },
6532 "status": "queued",
6533 "created_at": Timestamp::now().to_string(),
6534 "updated_at": Timestamp::now().to_string(),
6535 })
6536 .to_string(),
6537 )
6538 .unwrap();
6539
6540 let task = q.get("20260101-000000-bbbb").expect("must still read");
6541 assert!(
6542 !task.urgent,
6543 "a queue file with no `urgent` field means false, same as `solo`"
6544 );
6545 }
6546
6547 #[test]
6548 fn a_task_from_a_future_schema_is_refused_rather_than_guessed_at() {
6549 let (_dir, q) = queue();
6550 let mut t = task("from the future");
6551 q.put(&mut t).unwrap();
6552 let path = q.path_of(&t.id);
6553 let body = std::fs::read_to_string(&path)
6554 .unwrap()
6555 .replace(&format!("\"schema\": {SCHEMA}"), "\"schema\": 99");
6556 std::fs::write(&path, body).unwrap();
6557
6558 let err = q.get(&t.id).unwrap_err().to_string();
6559 assert!(err.contains("schema 99"), "{err}");
6560 }
6561
6562 #[test]
6563 fn revision_moves_when_the_queue_changes() {
6564 let (_dir, q) = queue();
6565 assert_eq!(q.revision(), 0, "an empty queue has no revision");
6566 let mut t = task("first");
6567 q.put(&mut t).unwrap();
6568 assert!(q.revision() > 0, "a written task moves the revision");
6569 }
6570
6571 #[test]
6572 fn revision_moves_when_deleting_an_older_task() {
6573 let (dir, q) = queue();
6574 let questions = Questions::at(dir.path().join("questions"));
6575 let mut t1 = task("older");
6576 q.put(&mut t1).unwrap();
6577 std::thread::sleep(std::time::Duration::from_millis(10));
6579 let mut t2 = task("newer");
6580 q.put(&mut t2).unwrap();
6581
6582 let rev_before = q.revision();
6583 q.remove(&t1.id, false, &questions).unwrap();
6584 let rev_after = q.revision();
6585
6586 assert_ne!(
6587 rev_before, rev_after,
6588 "deleting an older task must change the revision so other clients see the deletion"
6589 );
6590 }
6591
6592 #[test]
6593 fn removing_a_task_takes_it_out_of_the_listing() {
6594 let (dir, q) = queue();
6595 let questions = Questions::at(dir.path().join("questions"));
6596 let mut t = task("delete me");
6597 q.put(&mut t).unwrap();
6598 let removed = q.remove(t.short(), false, &questions).unwrap();
6599 assert_eq!(removed.id, t.id, "a prefix resolves before deleting");
6600 assert!(removed.released.is_empty() && removed.still_blocked.is_empty());
6601 assert!(q.list().is_empty());
6602 assert!(
6603 q.remove(&t.id, false, &questions).is_err(),
6604 "removing twice is an error"
6605 );
6606 }
6607
6608 #[test]
6609 fn removing_a_task_takes_its_stale_lock_with_it() {
6610 let (dir, q) = queue();
6611 let questions = Questions::at(dir.path().join("questions"));
6612 let mut t = task("interrupted");
6613 q.put(&mut t).unwrap();
6614
6615 let claim = q.claim(&t.id).unwrap();
6618 std::mem::forget(claim);
6619 assert!(
6620 q.claim(&t.id).is_err(),
6621 "the orphaned lock is what makes the task look claimed"
6622 );
6623
6624 let err = q.remove(&t.id, true, &questions).unwrap_err().to_string();
6626 assert!(err.contains("live daemon"), "{err}");
6627 assert!(q.get(&t.id).is_ok(), "a refused delete keeps the task");
6628
6629 q.remove(&t.id, false, &questions).unwrap();
6631 assert!(q.list().is_empty());
6632 let mut again = task("interrupted");
6633 again.id = t.id.clone();
6634 q.put(&mut again).unwrap();
6635 assert!(
6636 q.claim(&t.id).is_ok(),
6637 "a task that comes back must be claimable, which a left-behind lock would prevent"
6638 );
6639 }
6640
6641 fn notices_of(dir: &Path) -> Vec<crate::notices::Notice> {
6642 crate::notices::Notices::at(dir.join("notifications")).list()
6643 }
6644
6645 #[test]
6646 fn removing_a_sole_dependency_releases_the_dependent_without_a_hold() {
6647 let (dir, q) = queue();
6648 let questions = Questions::at(dir.path().join("questions"));
6649 let mut dep = task("dependency");
6650 q.put(&mut dep).unwrap();
6651 let mut blocked = task("waiting");
6652 blocked.block(vec![dep.id.clone()], Some("waits".to_owned()));
6653 q.put(&mut blocked).unwrap();
6654
6655 let removed = q.remove(&dep.id, false, &questions).unwrap();
6656 assert_eq!(removed.released, [blocked.id.clone()]);
6657 assert!(removed.still_blocked.is_empty());
6658
6659 let after = q.get(&blocked.id).unwrap();
6660 assert_eq!(after.status, TaskStatus::Queued);
6661 assert!(after.blocked_by.is_empty());
6662 assert!(after.block_reason.is_none());
6663 let notes = notices_of(dir.path());
6664 assert_eq!(notes.len(), 1, "{notes:?}");
6665 assert_eq!(notes[0].severity, crate::notices::Severity::Info);
6666 assert_eq!(
6667 notes[0].link,
6668 Some(crate::notices::Link::Task {
6669 id: blocked.id.clone(),
6670 })
6671 );
6672 }
6673
6674 #[test]
6675 fn removing_one_of_two_dependencies_keeps_the_other() {
6676 let (dir, q) = queue();
6677 let questions = Questions::at(dir.path().join("questions"));
6678 let mut dep = task("dependency");
6679 q.put(&mut dep).unwrap();
6680 let mut other = task("other");
6681 q.put(&mut other).unwrap();
6682 let mut blocked = task("waiting");
6683 blocked.block(
6684 vec![dep.id.clone(), other.id.clone()],
6685 Some("waits on both".to_owned()),
6686 );
6687 q.put(&mut blocked).unwrap();
6688
6689 let removed = q.remove(&dep.id, false, &questions).unwrap();
6690 assert!(removed.released.is_empty());
6691 assert_eq!(removed.still_blocked, [blocked.id.clone()]);
6692
6693 let after = q.get(&blocked.id).unwrap();
6694 assert_eq!(after.status, TaskStatus::Blocked);
6695 assert_eq!(after.blocked_by, [other.id.clone()]);
6696 assert!(missing_blockers(&q, &questions, &after.blocked_by).is_empty());
6699 }
6700
6701 #[test]
6702 fn a_dependency_deleted_before_its_dependents_were_rewritten_is_released_later() {
6703 let (dir, q) = queue();
6704 let questions = Questions::at(dir.path().join("questions"));
6705 let mut dep = task("dependency");
6706 q.put(&mut dep).unwrap();
6707 let mut blocked = task("waiting");
6708 blocked.block(vec![dep.id.clone()], None);
6709 q.put(&mut blocked).unwrap();
6710
6711 let claim = q.claim(&blocked.id).unwrap();
6713 let removed = q.remove(&dep.id, false, &questions).unwrap();
6714 assert!(removed.released.is_empty());
6715 drop(claim);
6716
6717 let mut task = q.get(&blocked.id).unwrap();
6718 assert_eq!(task.status, TaskStatus::Blocked);
6719 assert!(missing_blockers(&q, &questions, &task.blocked_by).is_empty());
6720 assert_eq!(
6721 q.apply_deleted_blockers(&mut task, &questions),
6722 [dep.id.clone()]
6723 );
6724 assert_eq!(task.status, TaskStatus::Queued);
6725 }
6726
6727 #[test]
6728 fn dependency_resolution_short_deleted_reference_releases_only_its_waiters() {
6729 let (dir, q) = queue();
6730 let questions = Questions::at(dir.path().join("questions"));
6731 let mut dep = task("dependency");
6732 dep.id = "20261013-193611-ca5b".into();
6733 q.put(&mut dep).unwrap();
6734 let mut waiting = task("waiting");
6735 waiting.block(vec!["ca5b".into()], None);
6736 q.put(&mut waiting).unwrap();
6737 q.remove(&dep.id, false, &questions).unwrap();
6738 assert_eq!(q.get(&waiting.id).unwrap().status, TaskStatus::Queued);
6739 assert_eq!(
6740 dependency(&q, &questions, "ca5b"),
6741 Dependency::Deleted(dep.id)
6742 );
6743 }
6744
6745 #[test]
6746 fn dependency_resolution_preserves_cross_store_ambiguity_and_exact_ids() {
6747 let (dir, queue) = queue();
6748 let questions = Questions::at(dir.path().join("questions"));
6749 let mut dep = task("dependency");
6750 dep.id = "20261013-193611-ca5b".into();
6751 queue.put(&mut dep).unwrap();
6752 std::fs::create_dir_all(questions.root()).unwrap();
6753 let question_id = "20261014-193611-ca5b";
6754 std::fs::write(questions.path_of(question_id), "unreadable question").unwrap();
6755 assert_eq!(questions.resolve_id("ca5b").unwrap(), question_id);
6756 assert_eq!(
6757 dependency(&queue, &questions, "ca5b"),
6758 Dependency::Ambiguous
6759 );
6760 assert_eq!(
6761 dependency(&queue, &questions, &dep.id),
6762 Dependency::Task(dep.id)
6763 );
6764 assert_eq!(
6765 dependency(&queue, &questions, question_id),
6766 Dependency::Question(question_id.into())
6767 );
6768 assert_eq!(
6769 dependency(&queue, &questions, "missing"),
6770 Dependency::Missing
6771 );
6772 }
6773
6774 #[test]
6775 fn dependency_resolution_directory_errors_are_unknown_not_missing() {
6776 let dir = tempfile::tempdir().unwrap();
6777 let q = Queue::at(dir.path().join("not-a-directory"));
6778 std::fs::write(q.root(), "file").unwrap();
6779 let questions = Questions::at(dir.path().join("questions"));
6780 assert_eq!(dependency(&q, &questions, "ca5b"), Dependency::Unknown);
6781 assert!(missing_blockers(&q, &questions, &["ca5b".into()]).is_empty());
6782 }
6783
6784 #[test]
6785 fn a_dependency_without_a_tombstone_is_still_missing() {
6786 let (dir, q) = queue();
6787 let questions = Questions::at(dir.path().join("questions"));
6788 let mut dep = task("dependency");
6789 q.put(&mut dep).unwrap();
6790 std::fs::remove_file(q.path_of(&dep.id)).unwrap();
6791 assert_eq!(
6792 missing_blockers(&q, &questions, std::slice::from_ref(&dep.id)),
6793 [dep.id.clone()]
6794 );
6795 assert!(deleted_blockers(&q, &questions, std::slice::from_ref(&dep.id)).is_empty());
6796 }
6797
6798 #[test]
6799 fn a_held_dependent_is_left_alone_by_a_dependency_deletion() {
6800 let mut t = task("held");
6801 t.hold_machine(Some("because".to_owned()));
6802 t.blocked_by = vec!["gone".to_owned()];
6803 assert!(!t.dependency_deleted("gone"));
6804 assert_eq!(t.status, TaskStatus::Held);
6805 }
6806
6807 #[test]
6808 fn a_failed_record_removal_takes_the_tombstone_back() {
6809 let (_dir, q) = queue();
6810 let mut t = task("stays");
6811 q.put(&mut t).unwrap();
6812 q.write_tombstone(&t.id).unwrap();
6813 let err = q.remove_record_with_attachments(&t.id, |_| Err(std::io::Error::other("nope")));
6814 assert!(err.is_err());
6815 assert!(!q.was_deleted(&t.id));
6818 }
6819
6820 fn source_file(dir: &Path, name: &str, body: &str) -> PathBuf {
6821 let p = dir.join(name);
6822 std::fs::write(&p, body).unwrap();
6823 p
6824 }
6825
6826 #[test]
6827 fn an_attachment_copy_survives_deleting_its_source() {
6828 let (dir, q) = queue();
6829 let src = source_file(dir.path(), "shot.png", "pixels");
6830 let mut t = task("with a picture");
6831 let names = q.attach(&mut t, std::slice::from_ref(&src)).unwrap();
6832 q.put(&mut t).unwrap();
6833 std::fs::remove_file(&src).unwrap();
6834 assert_eq!(names, ["shot.png"]);
6835 let loaded = q.get(&t.id).unwrap();
6836 let paths = q.attachment_paths(&loaded);
6837 assert_eq!(paths.len(), 1);
6838 assert_eq!(std::fs::read_to_string(&paths[0]).unwrap(), "pixels");
6839 }
6840
6841 #[test]
6842 fn attachment_names_that_could_traverse_or_are_odd_are_refused() {
6843 let (dir, q) = queue();
6844 let mut t = task("bad names");
6845 for name in ["a..b.png", ".hidden", "with space.png", "-x.png"] {
6846 let src = source_file(dir.path(), name, "x");
6847 assert!(
6848 q.attach(&mut t, &[src]).is_err(),
6849 "`{name}` must be refused"
6850 );
6851 }
6852 assert!(!crate::ask::valid_asset_name("C:foo.png"));
6856 #[cfg(not(windows))]
6857 {
6858 let src = source_file(dir.path(), "C:foo.png", "x");
6859 assert!(q.attach(&mut t, &[src]).is_err());
6860 }
6861 let long = format!("{}.png", "a".repeat(70));
6862 let src = source_file(dir.path(), &long, "x");
6863 assert!(q.attach(&mut t, &[src]).is_err());
6864 assert!(t.attachments.is_empty());
6865 assert!(!q.attachments_dir(&t.id).exists());
6866 }
6867
6868 #[test]
6869 fn a_taken_attachment_name_is_numbered_not_overwritten() {
6870 let (dir, q) = queue();
6871 let a = source_file(dir.path(), "shot.png", "one");
6872 let sub = dir.path().join("other");
6873 std::fs::create_dir_all(&sub).unwrap();
6874 let b = source_file(&sub, "shot.png", "two");
6875 let mut t = task("collision");
6876 q.attach(&mut t, &[a]).unwrap();
6877 q.attach(&mut t, &[b]).unwrap();
6878 assert_eq!(t.attachments, ["shot.png", "shot-2.png"]);
6879 let paths = q.attachment_paths(&t);
6880 assert_eq!(std::fs::read_to_string(&paths[0]).unwrap(), "one");
6881 assert_eq!(std::fs::read_to_string(&paths[1]).unwrap(), "two");
6882 }
6883
6884 #[test]
6885 fn a_renumbered_name_stays_inside_the_length_bound() {
6886 let (dir, q) = queue();
6887 let name = format!("{}.png", "a".repeat(60));
6888 assert_eq!(name.len(), 64);
6889 let a = source_file(dir.path(), &name, "one");
6890 let sub = dir.path().join("other");
6891 std::fs::create_dir_all(&sub).unwrap();
6892 let b = source_file(&sub, &name, "two");
6893 let mut t = task("long");
6894 q.attach(&mut t, &[a, b]).unwrap();
6895 assert_eq!(t.attachments.len(), 2);
6896 assert!(
6897 t.attachments
6898 .iter()
6899 .all(|n| crate::ask::valid_asset_name(n))
6900 );
6901 assert!(t.attachments[1].ends_with("-2.png"));
6902 }
6903
6904 #[test]
6905 fn a_failed_attach_keeps_existing_attachments_and_leaves_no_partial_copy() {
6906 let (dir, q) = queue();
6907 let good = source_file(dir.path(), "good.png", "ok");
6908 let mut t = task("partial");
6909 q.attach(&mut t, &[good]).unwrap();
6910 let more = source_file(dir.path(), "more.png", "ok");
6911 let missing = dir.path().join("missing.png");
6912 assert!(q.attach(&mut t, &[more, missing]).is_err());
6913 assert_eq!(t.attachments, ["good.png"]);
6914 let on_disk: Vec<_> = std::fs::read_dir(q.attachments_dir(&t.id))
6915 .unwrap()
6916 .flatten()
6917 .collect();
6918 assert_eq!(on_disk.len(), 1);
6919 }
6920
6921 fn block_put(q: &Queue, t: &Task) -> PathBuf {
6923 let tmp = q.path_of(&t.id).with_extension("json.tmp");
6924 std::fs::create_dir_all(&tmp).unwrap();
6925 tmp
6926 }
6927
6928 #[test]
6929 fn a_failed_put_leaves_no_new_attachment_directory() {
6930 let (dir, q) = queue();
6931 let mut t = task("fresh");
6932 let tmp = block_put(&q, &t);
6933 let src = source_file(dir.path(), "shot.png", "x");
6934 assert!(q.attach_and_put(&mut t, &[src]).is_err());
6935 assert!(t.attachments.is_empty());
6936 assert!(!q.attachments_dir(&t.id).exists());
6937 assert!(!q.path_of(&t.id).exists());
6938 std::fs::remove_dir(tmp).unwrap();
6939 }
6940
6941 #[test]
6942 fn a_failed_put_removes_only_the_copy_it_just_made() {
6943 let (dir, q) = queue();
6944 let mut t = task("edited");
6945 let first = source_file(dir.path(), "first.png", "1");
6946 q.attach_and_put(&mut t, &[first]).unwrap();
6947 block_put(&q, &t);
6948 let second = source_file(dir.path(), "second.png", "2");
6949 assert!(q.attach_and_put(&mut t, &[second]).is_err());
6950 assert_eq!(t.attachments, ["first.png"]);
6951 let on_disk: Vec<_> = std::fs::read_dir(q.attachments_dir(&t.id))
6952 .unwrap()
6953 .flatten()
6954 .map(|e| e.file_name().to_string_lossy().into_owned())
6955 .collect();
6956 assert_eq!(on_disk, ["first.png"]);
6957 assert_eq!(q.get(&t.id).unwrap().attachments, ["first.png"]);
6958 }
6959
6960 #[test]
6961 fn a_leftover_removing_directory_is_swept_by_the_next_removal() {
6962 let (dir, q) = queue();
6963 let questions = Questions::at(dir.path().join("questions"));
6964 let gone = task("gone");
6965 let mut other = task("other");
6966 let mut live = task("live");
6967 q.put(&mut other).unwrap();
6968 q.put(&mut live).unwrap();
6969 let orphan = q.root.join(format!("{}.attachments.removing", gone.id));
6972 std::fs::create_dir_all(&orphan).unwrap();
6973 std::fs::write(orphan.join("shot.png"), "x").unwrap();
6974 let busy = q.root.join(format!("{}.attachments.removing", live.id));
6977 std::fs::create_dir_all(&busy).unwrap();
6978
6979 q.remove(&other.id, false, &questions).unwrap();
6980 assert!(!orphan.exists(), "an orphan is swept");
6981 assert!(busy.exists(), "a removal in progress is left alone");
6982 }
6983
6984 #[test]
6985 fn a_blocked_aside_rename_fails_the_removal_and_loses_nothing() {
6986 let (dir, q) = queue();
6987 let questions = Questions::at(dir.path().join("questions"));
6988 let mut t = task("stuck");
6989 let src = source_file(dir.path(), "shot.png", "x");
6990 q.attach_and_put(&mut t, &[src]).unwrap();
6991 let aside = q.root.join(format!("{}.attachments.removing", t.id));
6994 std::fs::create_dir_all(&aside).unwrap();
6995 std::fs::write(aside.join("old.png"), "o").unwrap();
6996 assert!(q.remove(&t.id, false, &questions).is_err());
6997 assert!(q.path_of(&t.id).exists());
6998 assert!(q.attachments_dir(&t.id).join("shot.png").is_file());
6999 }
7000
7001 #[test]
7002 fn a_failed_record_removal_puts_the_attachments_back() {
7003 let (dir, q) = queue();
7004 let mut t = task("rollback");
7005 let src = source_file(dir.path(), "shot.png", "x");
7006 q.attach_and_put(&mut t, &[src]).unwrap();
7007 let err = q
7008 .remove_record_with_attachments(&t.id, |_| {
7009 Err(std::io::Error::other("injected failure"))
7010 })
7011 .unwrap_err();
7012 assert!(format!("{err:#}").contains("injected failure"));
7013 assert!(q.path_of(&t.id).exists());
7014 assert!(q.attachments_dir(&t.id).join("shot.png").is_file());
7015 assert!(
7016 !q.root
7017 .join(format!("{}.attachments.removing", t.id))
7018 .exists()
7019 );
7020 }
7021
7022 #[test]
7023 fn editing_a_task_keeps_its_attachments() {
7024 let (dir, q) = queue();
7025 let src = source_file(dir.path(), "shot.png", "x");
7026 let mut t = task("editable");
7027 q.attach(&mut t, &[src]).unwrap();
7028 t.edit("new".to_owned(), "new text".to_owned()).unwrap();
7029 q.put(&mut t).unwrap();
7030 assert_eq!(q.get(&t.id).unwrap().attachments, ["shot.png"]);
7031 }
7032
7033 #[test]
7034 fn removing_a_task_deletes_its_attachments() {
7035 let (dir, q) = queue();
7036 let questions = Questions::at(dir.path().join("questions"));
7037 let src = source_file(dir.path(), "shot.png", "x");
7038 let mut t = task("doomed");
7039 q.attach(&mut t, &[src]).unwrap();
7040 q.put(&mut t).unwrap();
7041 assert!(q.attachments_dir(&t.id).is_dir());
7042 q.remove(&t.id, false, &questions).unwrap();
7043 assert!(!q.attachments_dir(&t.id).exists());
7044 assert!(q.list().is_empty());
7045 }
7046
7047 #[test]
7048 fn a_task_written_before_attachments_still_reads() {
7049 let (_dir, q) = queue();
7050 let mut t = task("old");
7051 q.put(&mut t).unwrap();
7052 let path = q.path_of(&t.id);
7053 let mut v: serde_json::Value =
7054 serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
7055 v.as_object_mut().unwrap().remove("attachments");
7056 std::fs::write(&path, v.to_string()).unwrap();
7057 assert!(q.get(&t.id).unwrap().attachments.is_empty());
7058 }
7059
7060 #[test]
7061 fn attachment_paths_are_absolute_even_when_the_root_is_relative() {
7062 let q = Queue::at(PathBuf::from("relative-queue"));
7063 let mut t = task("rel");
7064 t.attachments.push("shot.png".to_owned());
7065 let paths = q.attachment_paths(&t);
7066 assert!(paths[0].is_absolute(), "{}", paths[0].display());
7067 assert!(paths[0].ends_with(format!("{}.attachments/shot.png", t.id)));
7068 }
7069
7070 fn upgrade_parked(id: &str, started: &str) -> Task {
7071 let mut t = task(id);
7072 t.id = id.into();
7073 t.start(format!("run-{id}"));
7074 t.park("upgrade");
7075 t.record_pass_at(
7076 &format!("run-{id}"),
7077 0,
7078 Some(started.parse().unwrap()),
7079 1,
7080 Some(crate::run::ParkCause::Upgrade {
7081 from: "old".into(),
7082 to: None,
7083 }),
7084 );
7085 t
7086 }
7087
7088 #[test]
7089 fn upgrade_resume_order_follows_dispatch_claim_not_graph_start() {
7090 let stamp = |id: &str, dispatched: &str, started: &str| {
7092 let mut t = task(id);
7093 t.id = id.into();
7094 t.start(format!("run-{id}"));
7095 t.park("upgrade");
7096 t.dispatched_at = Some(dispatched.parse().unwrap());
7097 t.record_pass_at(
7098 &format!("run-{id}"),
7099 0,
7100 Some(started.parse().unwrap()),
7101 1,
7102 Some(crate::run::ParkCause::Upgrade {
7103 from: "old".into(),
7104 to: None,
7105 }),
7106 );
7107 t
7108 };
7109 let a = stamp("a", "2026-10-22T00:00:01Z", "2026-10-22T00:00:09Z");
7110 let b = stamp("b", "2026-10-22T00:00:02Z", "2026-10-22T00:00:03Z");
7111 assert!(dispatch_order(&a, &b).is_lt());
7112 }
7113
7114 #[test]
7115 fn upgrade_resume_order_survives_queue_reload_and_reversed_settlement() {
7116 let (_dir, q) = queue();
7117 let mut later = upgrade_parked("later", "2026-10-22T00:00:02Z");
7118 let mut earlier = upgrade_parked("earlier", "2026-10-22T00:00:01Z");
7119 earlier.priority = -10;
7120 let mut fresh = task("fresh");
7121 fresh.id = "newer".into();
7122 fresh.priority = 100;
7123 for t in [&mut fresh, &mut later, &mut earlier] {
7124 q.put(t).unwrap();
7125 }
7126 let reloaded = Queue::at(q.root().to_owned());
7127 let mut tasks = reloaded.list();
7128 tasks.sort_unstable_by(dispatch_order);
7129 assert_eq!(
7130 tasks.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
7131 vec!["earlier", "later", "newer"]
7132 );
7133 assert_eq!(reloaded.next_runnable().unwrap().id, "earlier");
7134 assert_eq!(reloaded.get("earlier").unwrap().attempts, 0);
7135 }
7136
7137 #[test]
7138 fn upgrade_resume_legacy_order_uses_settlement_and_id() {
7139 let mut a = upgrade_parked("a", "2026-10-22T00:00:02Z");
7140 let mut b = upgrade_parked("b", "2026-10-22T00:00:01Z");
7141 for t in [&mut a, &mut b] {
7142 let mut value = serde_json::to_value(&*t).unwrap();
7143 value["passes"][0]
7144 .as_object_mut()
7145 .unwrap()
7146 .remove("started_at");
7147 *t = serde_json::from_value(value).unwrap();
7148 }
7149 assert!(dispatch_order(&a, &b).is_lt());
7150 b.passes[0].settled_at = a.passes[0].settled_at;
7151 assert!(dispatch_order(&a, &b).is_lt());
7152 }
7153
7154 #[test]
7155 fn upgrade_resume_key_excludes_other_parks_and_explicit_task_changes() {
7156 let original = upgrade_parked("a", "2026-10-22T00:00:01Z");
7157 assert!(original.upgrade_resume_key().is_some());
7158 for cause in [
7159 crate::run::ParkCause::Operator,
7160 crate::run::ParkCause::Question,
7161 crate::run::ParkCause::Interrupt {
7162 reason: "interrupt".into(),
7163 },
7164 crate::run::ParkCause::Unspecified,
7165 ] {
7166 let mut t = original.clone();
7167 t.passes[0].parked = Some(cause);
7168 assert!(t.upgrade_resume_key().is_none());
7169 let mut fresh = task("fresh");
7170 fresh.priority = 1;
7171 assert!(dispatch_order(&fresh, &t).is_lt());
7172 }
7173 let mut t = original.clone();
7174 t.release();
7175 assert!(t.upgrade_resume_key().is_none());
7176 t.edit("edited".into(), "new instruction".into()).unwrap();
7177 assert!(t.upgrade_resume_key().is_none());
7178 let mut t = original.clone();
7179 t.requeue();
7180 t.status = TaskStatus::Parked;
7181 assert!(t.upgrade_resume_key().is_none());
7182 let mut t = original.clone();
7183 t.start("different-run".into());
7184 t.park("no upgrade");
7185 assert!(t.upgrade_resume_key().is_none());
7186 }
7187
7188 #[test]
7189 fn explicitly_resumed_older_run_becomes_current_without_duplicate_history() {
7190 let dir = tempfile::tempdir().unwrap();
7191 let q = Queue::at(dir.path().join("queue"));
7192 let mut t = task("resume");
7193 t.start("A".into());
7194 t.record_pass("A", 0, 1, None);
7195 t.start("B".into());
7196 q.put(&mut t).unwrap();
7197 assert_eq!(t.runs, vec!["A", "B"]);
7198 t.start("A".into());
7199 t.record_pass("A", 1, 3, None);
7200 q.put(&mut t).unwrap();
7201 let saved = q.get(&t.id).unwrap();
7202 assert_eq!(saved.runs, vec!["B", "A"]);
7203 assert_eq!(saved.runs.last().map(String::as_str), Some("A"));
7204 assert_eq!(saved.attempts, 3);
7205 assert_eq!(saved.passes.len(), 2);
7206 assert_eq!(saved.passes[0].run, "A");
7207 assert_eq!(saved.passes[1].run, "A");
7208 }
7209
7210 #[test]
7211 fn repeated_start_records_one_run_and_separate_passes() {
7212 let mut t = task("resume");
7213 t.start("same-run".into());
7214 t.record_pass("same-run", 0, 1, None);
7215 t.start("same-run".into());
7216 t.record_pass("same-run", 1, 2, None);
7217 assert_eq!(t.runs, vec!["same-run"]);
7218 assert_eq!(t.attempts, 2);
7219 assert_eq!(t.passes.len(), 2);
7220 }
7221
7222 #[test]
7223 fn link_run_adds_a_run_once_and_touches_nothing_else() {
7224 let dir = tempfile::tempdir().unwrap();
7225 let queue = Queue::at(dir.path().join("queue"));
7226 let mut t = Task::new(
7227 "t".to_owned(),
7228 "do it".to_owned(),
7229 PathBuf::from("."),
7230 Source::Human,
7231 );
7232 queue.put(&mut t).unwrap();
7233 let before = queue.get(&t.id).unwrap();
7234
7235 let linked = queue.link_run(&t.id[..4], "20260930-092817-ec34").unwrap();
7236 assert_eq!(linked.runs, vec!["20260930-092817-ec34".to_owned()]);
7237 assert_eq!(linked.status, before.status);
7238 assert_eq!(linked.attempts, before.attempts);
7239 assert_eq!(linked.interrupt, before.interrupt);
7240
7241 let again = queue.link_run(&t.id, "20260930-092817-ec34").unwrap();
7242 assert_eq!(again.runs.len(), 1, "linking twice must not duplicate");
7243 assert_eq!(queue.get(&t.id).unwrap().runs.len(), 1);
7244 assert!(queue.link_run("no-such-task", "r").is_err());
7245 }
7246
7247 #[test]
7248 fn put_keeps_a_run_linked_after_the_writer_took_its_snapshot() {
7249 let dir = tempfile::tempdir().unwrap();
7250 let queue = Queue::at(dir.path().join("queue"));
7251 let mut t = Task::new(
7252 "t".to_owned(),
7253 "do it".to_owned(),
7254 PathBuf::from("."),
7255 Source::Human,
7256 );
7257 queue.put(&mut t).unwrap();
7258 let mut snapshot = queue.get(&t.id).unwrap();
7260 queue.link_run(&t.id, "20260930-092817-ec34").unwrap();
7261
7262 snapshot.start("20260930-000000-aaaa".to_owned());
7263 queue.put(&mut snapshot).unwrap();
7264
7265 let stored = queue.get(&t.id).unwrap();
7266 assert!(stored.runs.contains(&"20260930-092817-ec34".to_owned()));
7267 assert!(stored.runs.contains(&"20260930-000000-aaaa".to_owned()));
7268 assert_eq!(stored.attempts, 1);
7269 }
7270
7271 #[test]
7272 fn concurrent_links_and_daemon_saves_lose_nothing() {
7273 let dir = tempfile::tempdir().unwrap();
7274 let queue = Queue::at(dir.path().join("queue"));
7275 let mut t = Task::new(
7276 "t".to_owned(),
7277 "do it".to_owned(),
7278 PathBuf::from("."),
7279 Source::Human,
7280 );
7281 queue.put(&mut t).unwrap();
7282 let id = t.id.clone();
7283
7284 let linkers: Vec<_> = (0..4)
7285 .map(|n| {
7286 let (queue, id) = (queue.clone(), id.clone());
7287 std::thread::spawn(move || {
7288 for k in 0..10 {
7289 queue
7290 .link_run(&id, &format!("20260930-00000{n}-l{k:03}"))
7291 .unwrap();
7292 }
7293 })
7294 })
7295 .collect();
7296 let mut mine = queue.get(&id).unwrap();
7299 for k in 0..10 {
7300 mine.start(format!("20260930-000009-d{k:03}"));
7301 queue.put(&mut mine).unwrap();
7302 }
7303 for l in linkers {
7304 l.join().unwrap();
7305 }
7306
7307 let stored = queue.get(&id).unwrap();
7308 assert_eq!(stored.runs.len(), 50, "{:?}", stored.runs);
7309 assert_eq!(
7310 stored.attempts, 10,
7311 "linking never rewinds the daemon's work"
7312 );
7313 }
7314
7315 fn age_lock(path: &Path) {
7316 let f = std::fs::OpenOptions::new().write(true).open(path).unwrap();
7317 f.set_modified(std::time::SystemTime::now() - std::time::Duration::from_secs(60))
7318 .unwrap();
7319 }
7320
7321 #[test]
7322 fn concurrent_stale_takeover_yields_one_holder() {
7323 use std::sync::atomic::{AtomicUsize, Ordering};
7324 use std::sync::{Arc, Barrier};
7325 for _ in 0..5 {
7326 let dir = tempfile::tempdir().unwrap();
7327 let q = Queue::at(dir.path().to_path_buf());
7328 let lock = dir.path().join("t.write-lock");
7329 std::fs::write(&lock, "dead-0000").unwrap();
7330 age_lock(&lock);
7331 let n = 6;
7332 let barrier = Arc::new(Barrier::new(n));
7333 let (now, max) = (Arc::new(AtomicUsize::new(0)), Arc::new(AtomicUsize::new(0)));
7334 let handles: Vec<_> = (0..n)
7335 .map(|_| {
7336 let (q, b, now, max) = (q.clone(), barrier.clone(), now.clone(), max.clone());
7337 std::thread::spawn(move || {
7338 b.wait();
7339 let g = q.lock_task("t").unwrap();
7340 let held = now.fetch_add(1, Ordering::SeqCst) + 1;
7341 max.fetch_max(held, Ordering::SeqCst);
7342 std::thread::sleep(std::time::Duration::from_millis(20));
7343 now.fetch_sub(1, Ordering::SeqCst);
7344 drop(g);
7345 })
7346 })
7347 .collect();
7348 for h in handles {
7349 h.join().unwrap();
7350 }
7351 assert_eq!(max.load(Ordering::SeqCst), 1);
7352 assert!(!lock.exists());
7353 }
7354 }
7355
7356 #[test]
7357 fn dropping_a_replaced_lock_leaves_the_new_holders_token() {
7358 let dir = tempfile::tempdir().unwrap();
7359 let q = Queue::at(dir.path().to_path_buf());
7360 let lock = dir.path().join("t.write-lock");
7361 let a = q.lock_task("t").unwrap();
7362 let replacement = owner_token();
7365 std::fs::write(&lock, &replacement).unwrap();
7366 drop(a);
7367 assert_eq!(std::fs::read_to_string(&lock).unwrap(), replacement);
7368 }
7369
7370 #[test]
7371 fn aged_live_task_lock_excludes_updates_until_retirement_releases_it() {
7372 let dir = tempfile::tempdir().unwrap();
7373 let q = Queue::at(dir.path().to_path_buf());
7374 let held = q.lock_task("t").unwrap();
7375 let path = dir.path().join("t.write-lock");
7376 age_lock(&path);
7377 assert!(!break_stale(&path, &held.token));
7378 let (started_tx, started_rx) = std::sync::mpsc::channel();
7379 let (acquired_tx, acquired_rx) = std::sync::mpsc::channel();
7380 let updater = std::thread::spawn(move || {
7381 started_tx.send(()).unwrap();
7382 let _write = q.lock_task("t").unwrap();
7383 acquired_tx.send(()).unwrap();
7384 });
7385 started_rx.recv().unwrap();
7386 assert!(
7387 acquired_rx
7388 .recv_timeout(std::time::Duration::from_millis(100))
7389 .is_err()
7390 );
7391 assert_eq!(std::fs::read_to_string(&path).unwrap(), held.token);
7392 drop(held);
7393 acquired_rx
7394 .recv_timeout(std::time::Duration::from_secs(2))
7395 .unwrap();
7396 updater.join().unwrap();
7397 assert!(!path.exists());
7398 }
7399
7400 #[test]
7401 fn break_stale_leaves_a_lock_that_replaced_the_one_judged() {
7402 let dir = tempfile::tempdir().unwrap();
7403 let lock = dir.path().join("t.write-lock");
7404 std::fs::write(&lock, "new-token").unwrap();
7405 assert!(!break_stale(&lock, "old-token"));
7406 assert_eq!(std::fs::read_to_string(&lock).unwrap(), "new-token");
7407 assert!(!break_stale(&lock, "new-token"));
7409 assert!(lock.exists());
7410 age_lock(&lock);
7411 assert!(break_stale(&lock, "new-token"));
7412 assert!(!lock.exists());
7413 }
7414
7415 #[test]
7416 fn a_stale_break_marker_is_recovered_and_a_fresh_one_is_respected() {
7417 let dir = tempfile::tempdir().unwrap();
7418 let lock = dir.path().join("t.write-lock");
7419 std::fs::write(&lock, "dead-1").unwrap();
7420 age_lock(&lock);
7421 let marker = break_marker(&lock, "dead-1");
7422 std::fs::write(&marker, "crashed-remover").unwrap();
7423 assert!(!break_stale(&lock, "dead-1"));
7425 assert!(lock.exists());
7426 age_lock(&marker);
7428 assert!(break_stale(&lock, "dead-1"));
7429 assert!(!lock.exists());
7430 assert!(!marker.exists());
7431 }
7432
7433 fn chat_task() -> Task {
7434 Task::new(
7435 "t".to_owned(),
7436 "do t".to_owned(),
7437 PathBuf::from("."),
7438 Source::Agent {
7439 run: "20260902-000000-beef".to_owned(),
7440 node: CHAT_NODE.to_owned(),
7441 },
7442 )
7443 }
7444
7445 #[test]
7446 fn a_blocked_hold_keeps_its_anchor_but_a_new_run_starts_a_new_hold() {
7447 let mut t = chat_task();
7448 t.hold_machine(Some("waiting".into()));
7449 let old: Timestamp = "2020-01-01T00:00:00Z".parse().unwrap();
7450 t.held_at = Some(old);
7451 t.block(vec!["decision".into()], None);
7452 t.hold_machine(Some("same waiting decision".into()));
7453 assert_eq!(t.held_at, Some(old));
7454 t.start("real-new-run".into());
7455 t.fail("new failure", 1);
7456 assert_ne!(
7457 t.held_at,
7458 Some(old),
7459 "old answers cannot approve a new hold"
7460 );
7461 }
7462
7463 #[test]
7464 fn legacy_delivery_survives_upgrade_and_a_no_progress_run_link() {
7465 let (_dir, queue) = queue();
7466 let mut t = chat_task();
7467 t.start("old-run".into());
7468 t.hold_machine(Some("operator is considering recovery".into()));
7469 t.chat_notice = Some(ChatNotice {
7470 key: format!("held#{}", t.held_at.unwrap()),
7471 at: Timestamp::now(),
7472 outcome: ChatNoticeOutcome::Posted,
7473 });
7474 let mut raw = serde_json::to_value(&t).unwrap();
7475 raw.as_object_mut().unwrap().remove("chat_notices");
7476 raw.as_object_mut().unwrap().remove("hold_notice_cause");
7477 std::fs::create_dir_all(queue.path_of(&t.id).parent().unwrap()).unwrap();
7478 std::fs::write(queue.path_of(&t.id), serde_json::to_string(&raw).unwrap()).unwrap();
7479 assert_eq!(queue.get(&t.id).unwrap().chat_notice_due(), None);
7480 queue
7481 .modify(&t.id, |task| {
7482 task.requeue();
7483 task.link_run("unprepared-run");
7484 task.startup_notice_cause("startup-source");
7485 task.fail("same unresolved preflight", 0);
7486 true
7487 })
7488 .unwrap();
7489 assert_eq!(queue.get(&t.id).unwrap().chat_notice_due(), None);
7490 queue
7491 .modify(&t.id, |task| {
7492 task.succeed(completion(task));
7493 true
7494 })
7495 .unwrap();
7496 assert!(
7497 queue
7498 .get(&t.id)
7499 .unwrap()
7500 .chat_notice_due()
7501 .unwrap()
7502 .starts_with("done:")
7503 );
7504 }
7505
7506 #[test]
7507 fn a_dependency_wait_does_not_change_when_released_and_blocked_again() {
7508 let mut t = chat_task();
7509 t.block(vec!["a".into(), "b".into()], Some("waiting".into()));
7510 let key = t.chat_notice_key().unwrap();
7511 t.chat_notices.push(key);
7512 t.release();
7513 t.block(
7514 vec!["b".into(), "a".into(), "a".into()],
7515 Some("still waiting on prerequisites".into()),
7516 );
7517 assert_eq!(t.chat_notice_due(), None);
7518 t.block(
7519 vec!["new-question".into()],
7520 Some("different decision".into()),
7521 );
7522 assert!(t.chat_notice_due().is_some());
7523 }
7524
7525 #[test]
7526 fn running_startup_failures_preserve_stage_and_report_distinct_blockers() {
7527 let mut t = chat_task();
7528 t.start("existing-run".into());
7529 t.fail("implementation failed", 1);
7530 let failed = t.chat_notice_key().unwrap();
7531 t.chat_notices.push(failed.clone());
7532 t.release_operator("test", None);
7533 t.start("existing-run".into());
7534 t.fail_startup("startup-source", "same unresolved recovery source", 1);
7535 assert_eq!(
7536 t.chat_notice_due(),
7537 None,
7538 "no-progress recovery stays quiet"
7539 );
7540 t.release_operator("test", None);
7541 t.start("existing-run".into());
7542 t.fail_startup("startup-attachments", "attachment missing", 1);
7543 let attachments = t.chat_notice_due().expect("new attachment blocker");
7544 assert_ne!(attachments, failed);
7545 assert_eq!(
7546 t.hold_notice_cause.as_ref().unwrap().stage,
7547 "startup-attachments"
7548 );
7549 t.chat_notices.push(attachments);
7550 t.release_operator("test", None);
7551 t.start("existing-run".into());
7552 t.fail_startup(
7553 "startup-attachments",
7554 "same missing attachment, reworded",
7555 1,
7556 );
7557 assert_eq!(
7558 t.chat_notice_due(),
7559 None,
7560 "same stage after attempt counter reset"
7561 );
7562 t.release_operator("test", None);
7563 t.start("existing-run".into());
7564 t.fail_startup("startup-config", "different preflight stage", 1);
7565 assert!(t.chat_notice_due().is_some());
7566 assert_eq!(
7567 t.hold_notice_cause.as_ref().unwrap().stage,
7568 "startup-config"
7569 );
7570 }
7571
7572 #[test]
7573 fn structured_causes_preserve_no_progress_retries_and_report_new_passes() {
7574 let mut t = chat_task();
7575 t.hold_machine(Some("startup source missing".into()));
7576 t.startup_notice_cause("startup-source");
7577 let first = t.chat_notice_key().unwrap();
7578 t.chat_notices.push(first.clone());
7579 t.release_operator("test", None);
7580 t.startup_notice_cause("startup-source");
7581 t.hold_machine(Some("same source cannot be read".into()));
7582 assert_eq!(t.chat_notice_due(), None);
7583 t.startup_notice_cause("startup-config");
7584 assert!(t.chat_notice_due().is_some(), "different startup stage");
7585 t.notice_cause("failed", Some("existing-run"), Some(0));
7586 let run_failure = t.chat_notice_key().unwrap();
7587 t.chat_notices.push(run_failure.clone());
7588 t.release_operator("test", None);
7589 t.startup_notice_cause("startup-source");
7590 t.hold_machine(Some("no new work happened".into()));
7591 assert_eq!(t.chat_notice_due(), None);
7592 t.notice_cause("failed", Some("existing-run"), Some(1));
7593 assert!(t.chat_notice_due().is_some(), "a real resumed pass failed");
7594 assert_ne!(t.chat_notice_key().unwrap(), run_failure);
7595 }
7596
7597 #[test]
7598 fn legacy_hold_baseline_does_not_replay_or_hide_new_failures_and_completion() {
7599 let mut t = chat_task();
7600 t.hold_machine(Some("still waiting".into()));
7601 t.chat_notice = Some(ChatNotice {
7602 key: "held#2026-10-14T00:00:00Z".into(),
7603 at: Timestamp::now(),
7604 outcome: ChatNoticeOutcome::Posted,
7605 });
7606 assert_eq!(t.chat_notice_due(), None, "old hold baseline");
7607 t.import_chat_notice();
7608 t.notice_cause("failed", Some("new-run"), Some(0));
7609 assert!(t.chat_notice_due().is_some(), "new producer evidence");
7610 t.succeed(completion(&t));
7611 assert!(t.chat_notice_due().unwrap().starts_with("done:"));
7612 }
7613
7614 #[test]
7615 fn a_chat_notice_is_due_only_for_a_final_state_and_only_once() {
7616 let mut t = chat_task();
7617 assert_eq!(t.chat_notice_due(), None, "queued");
7618 t.start("r1".to_owned());
7619 assert_eq!(t.chat_notice_due(), None, "running");
7620 t.fail("boom", 3);
7621 assert_eq!(t.status, TaskStatus::Failed);
7622 assert_eq!(t.chat_notice_due(), None, "a retried failure is not final");
7623 t.start("r2".to_owned());
7624 t.park("upgrade");
7625 assert_eq!(t.chat_notice_due(), None, "parked");
7626 t.fail("boom", 1);
7627 assert_eq!(t.status, TaskStatus::Held);
7628 let key = t
7629 .chat_notice_due()
7630 .expect("held on the last attempt is final");
7631 t.chat_notice = Some(ChatNotice {
7632 key,
7633 at: Timestamp::now(),
7634 outcome: ChatNoticeOutcome::Posted,
7635 });
7636 assert_eq!(t.chat_notice_due(), None, "same hold, no second notice");
7637 t.release();
7638 assert_eq!(t.chat_notice_due(), None, "requeued after a release");
7639 t.start("r3".to_owned());
7640 t.succeed(completion(&t));
7641 assert!(t.chat_notice_due().is_some(), "done is a new final state");
7642 }
7643
7644 #[test]
7645 fn legacy_completion_receipts_do_not_suppress_new_occurrences() {
7646 for key in ["done", "done#0", "done#1", "done#12"] {
7647 let mut t = chat_task();
7648 t.status = TaskStatus::Done;
7649 t.chat_notice = Some(ChatNotice {
7650 key: key.to_owned(),
7651 at: Timestamp::now(),
7652 outcome: ChatNoticeOutcome::Posted,
7653 });
7654 assert_eq!(t.chat_notice_key().as_deref(), Some("done"));
7655 assert_eq!(t.chat_notice_due(), None, "legacy recorded key: {key}");
7656 let mut context = completion(&t);
7657 context.reason = Some("inspect again".into());
7658 t.reopen(context).unwrap();
7659 t.start("r2".to_owned());
7660 t.succeed(completion(&t));
7661 assert!(t.chat_notice_key().unwrap().starts_with("done:"));
7662 assert!(
7663 t.chat_notice_due().is_some(),
7664 "new occurrence, old receipt: {key}"
7665 );
7666 }
7667 }
7668
7669 #[test]
7670 fn a_release_without_progress_keeps_the_unresolved_notice_cause() {
7671 let mut t = chat_task();
7672 t.hold_manual(Some("wait".to_owned()));
7673 let first = t.chat_notice_due().expect("held");
7674 t.chat_notice = Some(ChatNotice {
7675 key: first.clone(),
7676 at: Timestamp::now(),
7677 outcome: ChatNoticeOutcome::Posted,
7678 });
7679 t.hold_manual(Some("still waiting".to_owned()));
7680 assert_eq!(t.chat_notice_due(), None, "a re-hold keeps its start");
7681 t.release();
7682 std::thread::sleep(std::time::Duration::from_millis(5));
7683 t.hold_manual(None);
7684 assert_eq!(t.chat_notice_due(), None, "no progress, same cause");
7685 }
7686
7687 #[test]
7688 fn a_chat_notice_needs_a_chat_source_and_a_current_schema() {
7689 let mut human = task("h");
7690 human.succeed(completion(&human));
7691 assert_eq!(human.chat_notice_due(), None);
7692 let mut inherited = task("i");
7694 inherited.origin_chat = Some("20260902-000000-beef".to_owned());
7695 inherited.succeed(completion(&inherited));
7696 assert_eq!(inherited.chat_notice_due(), None);
7697 let mut old = chat_task();
7698 old.schema = 12;
7699 old.status = TaskStatus::Done;
7700 assert_eq!(old.chat_notice_due(), None, "history is not replayed");
7701 let mut live = chat_task();
7702 live.schema = 12;
7703 live.start("r1".to_owned());
7704 live.succeed(completion(&live));
7705 assert!(live.chat_notice_due().is_some(), "started by this build");
7706 let mut held = chat_task();
7707 held.schema = 12;
7708 held.hold_machine(Some("config".to_owned()));
7709 assert!(held.chat_notice_due().is_some(), "held before any start");
7710 }
7711
7712 #[test]
7713 fn a_stale_snapshot_does_not_rewind_a_recorded_chat_notice() {
7714 let tmp = tempfile::tempdir().expect("tempdir");
7715 let q = Queue::at(tmp.path().join("queue"));
7716 let mut t = chat_task();
7717 t.succeed(completion(&t));
7718 q.put(&mut t).expect("put");
7719 let mut stale = q.get(&t.id).expect("get");
7720 let key = t.chat_notice_due().expect("due");
7721 q.modify(&t.id, |x| {
7722 x.chat_notice = Some(ChatNotice {
7723 key: key.clone(),
7724 at: Timestamp::now(),
7725 outcome: ChatNoticeOutcome::Posted,
7726 });
7727 true
7728 })
7729 .expect("modify");
7730 q.put(&mut stale).expect("stale put");
7731 assert_eq!(q.get(&t.id).expect("get").chat_notice_due(), None);
7732 }
7733
7734 #[test]
7735 fn empty_sources_are_omitted_so_older_builds_still_read_the_task() {
7736 let mut t = task("plain");
7739 let value = serde_json::to_value(&t).unwrap();
7740 assert!(value.get("sources").is_none(), "{value}");
7741 t.sources.pick_commits.push(crate::refs::Input {
7742 token: "abc1234".into(),
7743 sha: "a".repeat(40),
7744 provenance: crate::refs::Provenance::ExplicitCli,
7745 });
7746 let value = serde_json::to_value(&t).unwrap();
7747 assert_eq!(value["sources"]["pick_commits"][0]["sha"], "a".repeat(40));
7748 let restored: Task = serde_json::from_value(value).unwrap();
7749 assert_eq!(restored.sources, t.sources);
7750 }
7751
7752 fn queue_with_ids(dir: &Path, ids: &[&str]) -> Queue {
7754 let ids: Vec<String> = ids.iter().map(|s| (*s).to_owned()).collect();
7755 let n = std::sync::atomic::AtomicUsize::new(0);
7756 Queue::at(dir.join("queue")).with_id_source(move || {
7757 let i = n.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
7758 ids.get(i)
7759 .cloned()
7760 .unwrap_or_else(|| format!("20260101-000000-f{i:03x}"))
7761 })
7762 }
7763
7764 const TAKEN: &str = "20260101-000000-aaaa";
7765
7766 #[test]
7767 fn a_new_task_never_merges_into_a_record_with_its_candidate_id() {
7768 let dir = tempfile::tempdir().unwrap();
7769 let q = queue_with_ids(dir.path(), &[TAKEN, TAKEN]);
7770 let mut first = task("first");
7771 first.start("run-1".into());
7772 first.succeed(completion(&first));
7773 q.put(&mut first).unwrap();
7774 assert_eq!(first.id, TAKEN);
7775 let stored_before = q.get(&first.id).unwrap();
7776 assert!(!stored_before.runs.is_empty());
7777
7778 let mut second = task("second");
7779 q.put(&mut second).unwrap();
7780
7781 assert_ne!(second.id, first.id);
7782 assert!(second.runs.is_empty());
7783 assert!(second.passes.is_empty());
7784 assert!(second.chat_notices.is_empty());
7785 assert!(second.chat_notice.is_none());
7786 assert_eq!(second.chat_notice_due(), task("fresh").chat_notice_due());
7787 let a = q.get(&first.id).unwrap();
7788 let b = q.get(&second.id).unwrap();
7789 assert_eq!(a.title, "first");
7790 assert_eq!(a.runs, stored_before.runs);
7791 assert_eq!(a.passes, stored_before.passes);
7792 assert_eq!(a.chat_notices, stored_before.chat_notices);
7793 assert_eq!(a.chat_notice, stored_before.chat_notice);
7794 assert_eq!(a.chat_notice_due(), stored_before.chat_notice_due());
7795 assert_eq!(b.title, "second");
7796 assert!(b.runs.is_empty());
7797 assert!(b.passes.is_empty());
7798 assert!(b.chat_notice.is_none());
7799
7800 let mut again = q.get(&second.id).unwrap();
7802 again.title = "second, edited".into();
7803 q.put(&mut again).unwrap();
7804 assert_eq!(q.get(&second.id).unwrap().title, "second, edited");
7805 assert_eq!(q.list().len(), 2);
7806 }
7807
7808 #[test]
7809 fn a_new_task_skips_an_id_with_an_orphaned_claim_or_attachments() {
7810 let dir = tempfile::tempdir().unwrap();
7811 let q = queue_with_ids(dir.path(), &["orphan-lock", "orphan-dir", "free"]);
7812 std::fs::create_dir_all(q.root()).unwrap();
7813 std::fs::write(q.root().join("orphan-lock.lock"), "x").unwrap();
7814 std::fs::create_dir_all(q.attachments_dir("orphan-dir")).unwrap();
7815 let mut t = task("t");
7816 q.put(&mut t).unwrap();
7817 assert_eq!(t.id, "free");
7818 }
7819
7820 #[test]
7821 fn a_claimed_new_task_holds_the_claim_on_the_reserved_id() {
7822 let dir = tempfile::tempdir().unwrap();
7823 let q = queue_with_ids(dir.path(), &[TAKEN, TAKEN]);
7824 let mut first = task("first");
7825 q.put(&mut first).unwrap();
7826 let mut second = task("second");
7827 let claim = q.file_claimed(&mut second).unwrap();
7828 assert_ne!(second.id, first.id);
7829 assert!(q.claim(&second.id).is_err());
7830 assert!(q.claim(&first.id).is_ok(), "the first task was not claimed");
7831 drop(claim);
7832 }
7833
7834 #[test]
7835 fn an_attached_new_task_skips_a_taken_id() {
7836 let dir = tempfile::tempdir().unwrap();
7837 let q = queue_with_ids(dir.path(), &[TAKEN, TAKEN]);
7838 let mut first = task("first");
7839 q.put(&mut first).unwrap();
7840 let src = source_file(dir.path(), "shot.png", "x");
7841 let mut second = task("second");
7842 q.attach_and_put(&mut second, &[src]).unwrap();
7843 assert_ne!(second.id, first.id);
7844 assert!(!q.attachments_dir(&first.id).exists());
7845 assert_eq!(q.attachment_paths(&second).len(), 1);
7846 assert!(q.attachment_paths(&second)[0].is_file());
7847 }
7848
7849 #[test]
7850 fn attaching_before_putting_a_new_task_reserves_the_id() {
7851 let dir = tempfile::tempdir().unwrap();
7852 let q = queue_with_ids(dir.path(), &[TAKEN, TAKEN]);
7853 let mut first = task("first");
7854 q.put(&mut first).unwrap();
7855 let src = source_file(dir.path(), "shot.png", "x");
7856 let mut second = task("second");
7857 q.attach(&mut second, &[src]).unwrap();
7858 assert_ne!(second.id, first.id);
7859 assert!(q.attachments_dir(&second.id).is_dir());
7860 q.put(&mut second).unwrap();
7861 assert_eq!(q.get(&second.id).unwrap().attachments.len(), 1);
7862 assert_eq!(q.get(&first.id).unwrap().title, "first");
7863 assert!(q.get(&first.id).unwrap().attachments.is_empty());
7864 }
7865
7866 #[test]
7867 fn create_new_keeps_its_already_exists_meaning() {
7868 let dir = tempfile::tempdir().unwrap();
7869 let q = Queue::at(dir.path().join("queue"));
7870 let mut a = task("a");
7871 a.id = "fixed-id".into();
7872 assert!(q.create_new(&mut a).unwrap());
7873 let mut b = task("b");
7874 b.id = "fixed-id".into();
7875 assert!(!q.create_new(&mut b).unwrap());
7876 assert_eq!(q.get("fixed-id").unwrap().title, "a");
7877 }
7878
7879 #[test]
7880 fn filing_gives_up_when_no_id_is_ever_free() {
7881 let dir = tempfile::tempdir().unwrap();
7882 let q = Queue::at(dir.path().join("queue")).with_id_source(|| TAKEN.to_owned());
7883 let mut first = task("first");
7884 q.put(&mut first).unwrap();
7885 let mut second = task("second");
7886 assert!(q.put(&mut second).is_err());
7887 assert_eq!(q.get(&first.id).unwrap().title, "first");
7888 }
7889}