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 = 30;
167
168const RECOVERY_HOLD_SCHEMA: u32 = 24;
169const REOPEN_HOLD_SCHEMA: u32 = 28;
170const COMPLETION_REPORT_SCHEMA: u32 = 30;
171
172pub(crate) fn dispatch_order(a: &Task, b: &Task) -> std::cmp::Ordering {
178 match (a.upgrade_resume_key(), b.upgrade_resume_key()) {
179 (Some(a), Some(b)) => a.cmp(&b),
180 (Some(_), None) => std::cmp::Ordering::Less,
181 (None, Some(_)) => std::cmp::Ordering::Greater,
182 (None, None) => b.priority.cmp(&a.priority).then(a.id.cmp(&b.id)),
183 }
184}
185
186#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
193#[serde(tag = "kind", rename_all = "snake_case")]
194pub enum MachineHoldCause {
195 DiskCapacity {
197 reason: String,
199 #[serde(default)]
201 before_start: bool,
202 },
203 HeadE2e {
205 stop: crate::head_e2e_stop::Stop,
207 },
208 AwaitingLanding {
210 run: String,
212 reason: String,
214 },
215}
216
217#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
221pub struct InvestigationResult {
222 pub text: String,
224 #[serde(default)]
226 pub instruction_rev: u64,
227 pub recorded_at: Timestamp,
229}
230
231#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
233#[serde(rename_all = "lowercase")]
234pub enum HoldSource {
235 Manual,
237 Machine,
239}
240
241impl HoldSource {
242 pub fn label(self) -> &'static str {
244 match self {
245 Self::Manual => "manual",
246 Self::Machine => "machine",
247 }
248 }
249}
250
251#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
254#[serde(tag = "kind", rename_all = "lowercase")]
255pub enum Source {
256 Human,
258 Agent {
261 run: String,
263 node: String,
265 },
266 Issue {
268 number: u64,
270 repo: String,
272 },
273}
274
275#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
277pub struct IssueRef {
278 pub number: u64,
280 pub repo: String,
282}
283
284pub const CHAT_NODE: &str = "chat";
287
288impl Source {
289 pub fn label(&self) -> String {
291 match self {
292 Self::Human => "human".to_owned(),
293 Self::Agent { run, node } => format!("{node}@{}", short(run)),
294 Self::Issue { number, .. } => format!("issue #{number}"),
295 }
296 }
297}
298
299#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
301#[serde(rename_all = "lowercase")]
302pub enum TaskStatus {
303 Queued,
305 Running,
307 Done,
309 Failed,
311 Held,
313 Blocked,
317 Parked,
322}
323
324impl TaskStatus {
325 pub fn runnable(self) -> bool {
327 matches!(self, Self::Queued | Self::Failed | Self::Parked)
328 }
329
330 pub fn as_str(self) -> &'static str {
332 match self {
333 Self::Queued => "queued",
334 Self::Running => "running",
335 Self::Done => "done",
336 Self::Failed => "failed",
337 Self::Held => "held",
338 Self::Blocked => "blocked",
339 Self::Parked => "parked",
340 }
341 }
342}
343
344#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
347pub struct TaskCounts {
348 pub queued: usize,
350 pub running: usize,
352 pub done: usize,
354 pub failed: usize,
356 pub held: usize,
358 pub blocked: usize,
360 pub parked: usize,
362}
363
364impl TaskCounts {
365 pub fn of(tasks: &[Task]) -> Self {
369 Self::of_statuses(tasks.iter().map(|task| task.status))
370 }
371
372 pub(crate) fn of_statuses(statuses: impl IntoIterator<Item = TaskStatus>) -> Self {
374 let mut counts = Self::default();
375 for status in statuses {
376 match status {
377 TaskStatus::Queued => counts.queued += 1,
378 TaskStatus::Running => counts.running += 1,
379 TaskStatus::Done => counts.done += 1,
380 TaskStatus::Failed => counts.failed += 1,
381 TaskStatus::Held => counts.held += 1,
382 TaskStatus::Blocked => counts.blocked += 1,
383 TaskStatus::Parked => counts.parked += 1,
384 }
385 }
386 counts
387 }
388}
389
390#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
392pub struct Reassignment {
393 pub from: PathBuf,
395 pub to: PathBuf,
397 pub actor: String,
399 pub at: Timestamp,
401 pub run_boundary: usize,
403}
404
405#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
407#[serde(tag = "kind", content = "talk", rename_all = "snake_case")]
408pub enum CompletionActor {
409 Cli,
411 Web,
413 Chat(String),
415 Conductor,
417 DaemonSettle,
419}
420
421#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
423#[serde(rename_all = "snake_case")]
424pub enum CompletionAction {
425 Complete,
427 Reopen,
429}
430
431#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
433struct ReopenHold {
434 occurrence: String,
435 held_at: Timestamp,
436 decision: Option<Timestamp>,
437 #[serde(default)]
438 legacy: bool,
439}
440
441#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
443pub struct CompletionRunSnapshot {
444 pub id: String,
446 pub status: Option<crate::run::RunStatus>,
448 pub pr_url: Option<String>,
450 pub pr_state: Option<String>,
452 pub pr_head: Option<String>,
454 #[serde(default)]
456 pub branches: Vec<String>,
457 pub error: Option<String>,
459}
460
461impl CompletionRunSnapshot {
462 fn from_run(state: &crate::run::RunState) -> Self {
463 let mut branches: Vec<String> = state
464 .candidates
465 .iter()
466 .map(|candidate| candidate.branch.clone())
467 .collect();
468 if let Some(branch) = &state.pr_head
469 && !branches.contains(branch)
470 {
471 branches.push(branch.clone());
472 }
473 Self {
474 id: state.id.clone(),
475 status: Some(state.status),
476 pr_url: state.pr.as_ref().map(|pr| pr.url.clone()),
477 pr_state: state.pr.as_ref().map(|pr| pr.state.clone()),
478 pr_head: state
479 .pr_merged_head
480 .clone()
481 .or_else(|| state.pr_pushed_head.clone()),
482 branches,
483 error: None,
484 }
485 }
486}
487
488#[derive(Debug, Clone)]
490pub struct CompletionContext {
491 pub actor: CompletionActor,
493 pub reason: Option<String>,
495 pub discard: bool,
497 pub run: Option<CompletionRunSnapshot>,
499 pub unavailable_runs: Vec<String>,
501}
502
503impl CompletionContext {
504 pub fn new(actor: CompletionActor, reason: Option<String>, home: &Path, task: &Task) -> Self {
506 let run = task
507 .runs
508 .last()
509 .map(|id| match crate::run::RunState::load_under(id, home) {
510 Ok(state) => CompletionRunSnapshot::from_run(&state),
511 Err(error) => CompletionRunSnapshot {
512 id: id.clone(),
513 status: None,
514 pr_url: None,
515 pr_state: None,
516 pr_head: None,
517 branches: Vec::new(),
518 error: Some(format!("{error:#}")),
519 },
520 });
521 Self {
522 actor,
523 reason,
524 discard: false,
525 run,
526 unavailable_runs: Vec::new(),
527 }
528 }
529
530 pub fn from_run(
532 actor: CompletionActor,
533 reason: Option<String>,
534 _task: &Task,
535 state: &crate::run::RunState,
536 ) -> Self {
537 Self {
538 actor,
539 reason,
540 discard: false,
541 run: Some(CompletionRunSnapshot::from_run(state)),
542 unavailable_runs: Vec::new(),
543 }
544 }
545}
546
547#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
549pub struct CompletionEvent {
550 pub occurrence: String,
552 pub action: CompletionAction,
554 pub actor: CompletionActor,
556 pub reason: Option<String>,
558 pub discard: bool,
560 pub prior_status: TaskStatus,
562 #[serde(default)]
564 pub prior_hold_reason: Option<String>,
565 #[serde(default)]
567 pub prior_block_reason: Option<String>,
568 #[serde(default)]
570 pub prior_error: Option<String>,
571 pub at: Timestamp,
573 #[serde(default)]
575 pub schema: u32,
576 pub run: Option<CompletionRunSnapshot>,
578 #[serde(default, skip_serializing_if = "Vec::is_empty")]
580 pub unavailable_runs: Vec<String>,
581}
582
583#[derive(Debug, Clone, Serialize, Deserialize)]
585#[serde(deny_unknown_fields)]
586pub struct Task {
587 pub schema: u32,
589 pub id: String,
591 pub title: String,
593 pub instruction: String,
595 #[serde(default)]
597 pub instruction_rev: u64,
598 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
600 pub investigation: bool,
601 #[serde(default, skip_serializing_if = "Option::is_none")]
603 pub completion_result: Option<InvestigationResult>,
604 #[serde(default, skip_serializing_if = "Option::is_none")]
607 pub landing: Option<crate::landing::LandingNote>,
608 #[serde(default, skip_serializing_if = "crate::refs::Sources::is_empty")]
610 pub sources: crate::refs::Sources,
611 pub repo: PathBuf,
613 #[serde(default)]
615 pub reassignments: Vec<Reassignment>,
616 pub source: Source,
618 #[serde(default, skip_serializing_if = "Option::is_none")]
620 pub issue: Option<IssueRef>,
621 #[serde(default)]
623 pub chat: Option<String>,
624 #[serde(default)]
626 pub priority: i32,
627 #[serde(default)]
638 pub solo: bool,
639 pub status: TaskStatus,
641 #[serde(default)]
643 pub completion_history: Vec<CompletionEvent>,
644 #[serde(default)]
646 pub attempts: usize,
647 #[serde(default)]
649 pub attempt_limit: Option<NonZeroUsize>,
650 #[serde(default)]
653 pub runs: Vec<String>,
654 #[serde(default)]
656 pub startup_failures: Vec<crate::run::StartupFailure>,
657 #[serde(default)]
659 pub last_error: Option<String>,
660 #[serde(default)]
673 pub hold_reason: Option<String>,
674 #[serde(default)]
677 pub hold_source: Option<HoldSource>,
678 #[serde(default, skip_serializing_if = "Option::is_none")]
679 recovery_budget_hold: Option<RecoveryBudgetHold>,
680 #[serde(default, skip_serializing_if = "Option::is_none")]
683 reopen_hold: Option<ReopenHold>,
684 #[serde(default)]
686 pub machine_hold_cause: Option<MachineHoldCause>,
687 #[serde(default)]
689 pub disk_resume_run: Option<String>,
690 #[serde(default)]
692 pub disk_checked_at: Option<Timestamp>,
693 #[serde(default)]
705 pub diagnostic: Option<String>,
706 #[serde(default)]
716 pub blocked_by: Vec<String>,
717 #[serde(default)]
720 pub block_reason: Option<String>,
721 #[serde(default)]
734 pub blocked_from: Option<TaskStatus>,
735 #[serde(default)]
737 pub blocked_at: Option<Timestamp>,
738 #[serde(default)]
749 pub answers: Vec<AnsweredQuestion>,
750 #[serde(default)]
756 pub triage_applied: Vec<String>,
757 #[serde(default)]
763 pub actions_applied: Vec<String>,
764 #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
767 pub decision_effects: std::collections::BTreeMap<String, String>,
768 #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
771 pub superseded_resumes: std::collections::BTreeMap<String, String>,
772 #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
776 pub dispatched_resumes: std::collections::BTreeMap<String, String>,
777 #[serde(default)]
779 pub base_recovery_requests: Vec<String>,
780 #[serde(default)]
782 pub land_sync_recovery_requests: Vec<String>,
783 #[serde(default)]
785 pub instruction_revision_requests: Vec<String>,
786 #[serde(default)]
791 pub resume_override: Option<OperatorResume>,
792 #[serde(default, skip_serializing_if = "Option::is_none")]
794 pub sync_only: Option<crate::base_sync_only::Request>,
795 #[serde(default)]
797 pub repair_grants: Vec<crate::repair_budget::Receipt>,
798 #[serde(default)]
800 pub repair_reconciliations: Vec<crate::repair_budget::reconcile::Receipt>,
801 #[serde(default)]
804 pub resumption: Option<Resumption>,
805 #[serde(default)]
807 pub resumption_history: Vec<Resumption>,
808 #[serde(default)]
810 pub operator_decided_at: Option<Timestamp>,
811 #[serde(default)]
823 pub review_branch: Option<String>,
824 #[serde(default)]
826 pub review_instruction: Option<String>,
827 #[serde(default)]
829 pub pr_recovery: Option<crate::pr_recovery::Selection>,
830 #[serde(default)]
833 pub fresh_start: bool,
834 #[serde(default)]
836 pub replacement: Option<crate::merge_decision::Replacement>,
837 #[serde(default)]
848 pub interrupt: bool,
849 #[serde(default)]
872 pub urgent: bool,
873 #[serde(default)]
887 pub immediate: bool,
888 #[serde(skip)]
893 pub(crate) unfiled: bool,
894 #[serde(default)]
900 pub attachments: Vec<String>,
901 #[serde(default)]
905 pub followup: Option<FollowUp>,
906 #[serde(default)]
912 pub origin_chat: Option<String>,
913 #[serde(default)]
920 pub overrides: Option<RunOverrides>,
921 #[serde(default)]
928 pub review_of: Option<String>,
929 #[serde(default)]
934 pub held_at: Option<Timestamp>,
935 #[serde(default)]
939 pub park_reason: Option<String>,
940 #[serde(default)]
943 pub chat_notice: Option<ChatNotice>,
944 #[serde(default, skip_serializing_if = "ChatReservation::is_none")]
947 pub chat_reservation: ChatReservation,
948 #[serde(default)]
950 pub chat_notices: Vec<String>,
951 #[serde(default)]
954 pub hold_notice_cause: Option<NoticeCause>,
955 #[serde(default)]
960 pub passes: Vec<TaskPass>,
961 #[serde(default)]
965 pub dispatched_at: Option<Timestamp>,
966 #[serde(default)]
968 pub recovery_budget: Option<RecoveryBudget>,
969 #[serde(default)]
972 pub recovery_admission: Option<RecoveryAdmission>,
973 #[serde(default)]
976 pub recovery_generations: Vec<RecoveryBudget>,
977 pub created_at: Timestamp,
979 pub updated_at: Timestamp,
981}
982
983#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
985pub struct RecoveryAdmission {
986 pub base: String,
988 pub inputs: String,
990}
991
992#[derive(Debug, Clone, Serialize, Deserialize)]
993struct RecoveryBudgetHold {
994 admission: RecoveryAdmission,
995 run: String,
996 pass: usize,
997 held_at: Timestamp,
998 decision: Option<Timestamp>,
999 #[serde(default)]
1000 legacy: bool,
1001}
1002
1003#[derive(Debug, Clone, Serialize, Deserialize)]
1006pub struct RecoveryBudget {
1007 pub instruction: String,
1009 pub base: String,
1011 pub inputs: String,
1013 pub stage: String,
1015 pub failures: usize,
1017 #[serde(default)]
1020 pub progress: Option<String>,
1021}
1022
1023impl RecoveryBudget {
1024 fn budget_reason(&self) -> String {
1025 format!(
1026 "[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.",
1027 self.failures, self.stage
1028 )
1029 }
1030}
1031
1032fn recovery_progress(state: &crate::run::RunState) -> Option<String> {
1033 use crate::proc::Quiet as _;
1034 use std::hash::{Hash, Hasher};
1035 let mut patches = Vec::new();
1036 for candidate in state.candidates.iter().filter(|c| c.commits > 0) {
1037 let output = std::process::Command::new("git")
1038 .current_dir(&state.repo)
1039 .args(["diff", "--binary", &state.base_commit, &candidate.branch])
1040 .quiet()
1041 .output()
1042 .ok()?;
1043 if !output.status.success() {
1044 return None;
1045 }
1046 patches.push(output.stdout);
1047 }
1048 patches.sort();
1049 patches.dedup();
1050 let mut hash = std::collections::hash_map::DefaultHasher::new();
1051 patches.hash(&mut hash);
1052 Some(format!("{:x}", hash.finish()))
1053}
1054
1055pub(crate) fn recovery_inputs(sources: &crate::refs::Sources) -> String {
1059 serde_json::to_string(
1060 &sources
1061 .start_from
1062 .iter()
1063 .map(|i| ("start", &i.token, &i.sha))
1064 .chain(
1065 sources
1066 .pick_commits
1067 .iter()
1068 .map(|i| ("pick", &i.token, &i.sha)),
1069 )
1070 .collect::<Vec<_>>(),
1071 )
1072 .unwrap_or_default()
1073}
1074
1075#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1077pub struct NoticeCause {
1078 pub stage: String,
1080 #[serde(default, skip_serializing_if = "Option::is_none")]
1083 pub target: Option<String>,
1084 pub run: Option<String>,
1086 pub pass: Option<usize>,
1088}
1089
1090pub(crate) fn is_done_notice_key(key: &str) -> bool {
1092 key == "done"
1093 || key
1094 .strip_prefix("done#")
1095 .is_some_and(|count| !count.is_empty() && count.bytes().all(|b| b.is_ascii_digit()))
1096}
1097
1098#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1100#[serde(rename_all = "snake_case")]
1101pub enum PassCost {
1102 Spent,
1104 Refunded,
1106}
1107
1108#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1110pub struct TaskPass {
1111 pub run: String,
1113 pub pass_index: usize,
1115 pub cost: PassCost,
1117 pub attempts_after: usize,
1119 #[serde(default)]
1121 pub started_at: Option<Timestamp>,
1122 pub settled_at: Timestamp,
1124 #[serde(default)]
1126 pub parked: Option<crate::run::ParkCause>,
1127}
1128
1129#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
1132#[serde(rename_all = "snake_case")]
1133pub enum ChatReservation {
1134 #[default]
1136 None,
1137 Pending,
1140 Established,
1142}
1143
1144impl ChatReservation {
1145 fn is_none(&self) -> bool {
1146 *self == Self::None
1147 }
1148}
1149
1150#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1152#[serde(rename_all = "lowercase")]
1153pub enum ChatNoticeOutcome {
1154 Posted,
1156 Skipped,
1158}
1159
1160#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1162pub struct ChatNotice {
1163 pub key: String,
1165 pub at: Timestamp,
1167 pub outcome: ChatNoticeOutcome,
1169}
1170
1171#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1173pub struct RunOverrides {
1174 #[serde(default)]
1177 pub inherit_daemon_options: bool,
1178 #[serde(default)]
1180 pub merge: Option<String>,
1181 #[serde(default)]
1183 pub candidates: Option<usize>,
1184 #[serde(default)]
1186 pub judges: Option<usize>,
1187 #[serde(default)]
1189 pub reviewers: Option<usize>,
1190 #[serde(default)]
1192 pub review_rounds: Option<usize>,
1193 #[serde(default)]
1195 pub seed: Option<u64>,
1196 #[serde(default)]
1198 pub config: Option<PathBuf>,
1199 #[serde(default, skip_serializing_if = "Option::is_none")]
1201 pub build_cache: Option<BuildCache>,
1202}
1203
1204impl RunOverrides {
1205 pub fn merge_over(&mut self, other: &RunOverrides) {
1207 macro_rules! take {
1208 ($($f:ident),*) => {$(
1209 if other.$f.is_some() {
1210 self.$f.clone_from(&other.$f);
1211 }
1212 )*};
1213 }
1214 take!(
1215 merge,
1216 candidates,
1217 judges,
1218 reviewers,
1219 review_rounds,
1220 seed,
1221 config,
1222 build_cache
1223 );
1224 }
1225
1226 pub fn apply(&self, config: &mut crate::config::Config) {
1228 if let Some(n) = self.candidates {
1229 config.graph.implementers = n;
1230 }
1231 if let Some(n) = self.judges {
1232 config.graph.judges = n;
1233 }
1234 if let Some(n) = self.reviewers {
1235 config.graph.reviewers = n;
1236 }
1237 if let Some(n) = self.review_rounds {
1238 config.graph.review_rounds = n;
1239 }
1240 if let Some(m) = &self.merge
1241 && let Ok(mode) = crate::daemon::merge_mode(m)
1242 {
1243 config.merge.mode = mode;
1244 }
1245 if let Some(s) = self.seed {
1246 config.blind.seed = Some(s);
1247 }
1248 if let Some(mode) = self.build_cache {
1249 config.verify.build_cache = mode;
1250 }
1251 }
1252}
1253
1254#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1256pub struct FollowUp {
1257 pub run: String,
1259 #[serde(default)]
1261 pub origin_task: Option<String>,
1262 pub pr: String,
1264 pub findings: Vec<String>,
1266 pub generation: u32,
1269}
1270
1271#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1273pub struct Resumption {
1274 pub generation: u64,
1276 pub source: String,
1278 pub question_id: Option<String>,
1280 pub at: Timestamp,
1282 pub instruction: String,
1284 pub answers_through: usize,
1286 pub runs_through: usize,
1289 pub cleared_reason: Option<String>,
1291 #[serde(default)]
1293 pub blocking_evidence: Vec<String>,
1294}
1295
1296#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1299pub struct OperatorResume {
1300 pub question_id: String,
1302 pub at: Timestamp,
1304 #[serde(default)]
1307 pub conductor_rehold: Option<String>,
1308 #[serde(default)]
1311 pub forced: bool,
1312 #[serde(default)]
1319 pub pinned_run: Option<String>,
1320}
1321
1322#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1325pub struct AnsweredQuestion {
1326 pub question: String,
1328 pub answer: String,
1330}
1331
1332fn append_missing<T: PartialEq>(ledger: &mut Vec<T>, entries: Vec<T>) {
1333 for entry in entries {
1334 if !ledger.contains(&entry) {
1335 ledger.push(entry);
1336 }
1337 }
1338}
1339
1340fn prepend_missing_by<T>(ledger: &mut Vec<T>, mut older: Vec<T>, same: impl Fn(&T, &T) -> bool) {
1341 older.retain(|old| !ledger.iter().any(|entry| same(entry, old)));
1342 if !older.is_empty() {
1343 older.append(ledger);
1344 *ledger = older;
1345 }
1346}
1347
1348impl Task {
1349 pub fn new(title: String, instruction: String, repo: PathBuf, source: Source) -> Self {
1351 let now = Timestamp::now();
1352 let origin_chat = match &source {
1353 Source::Agent { run, node } if node == CHAT_NODE => Some(run.clone()),
1354 _ => None,
1355 };
1356 Self {
1357 schema: SCHEMA,
1358 id: new_id(),
1359 title,
1360 instruction,
1361 instruction_rev: 0,
1362 investigation: false,
1363 completion_result: None,
1364 landing: None,
1365 sources: crate::refs::Sources::default(),
1366 repo,
1367 reassignments: Vec::new(),
1368 source,
1369 issue: None,
1370 chat: None,
1371 priority: 0,
1372 solo: false,
1373 status: TaskStatus::Queued,
1374 completion_history: Vec::new(),
1375 attempts: 0,
1376 attempt_limit: None,
1377 runs: Vec::new(),
1378 startup_failures: Vec::new(),
1379 last_error: None,
1380 hold_reason: None,
1381 hold_source: None,
1382 recovery_budget_hold: None,
1383 reopen_hold: None,
1384 machine_hold_cause: None,
1385 disk_resume_run: None,
1386 disk_checked_at: None,
1387 diagnostic: None,
1388 blocked_by: Vec::new(),
1389 block_reason: None,
1390 blocked_from: None,
1391 blocked_at: None,
1392 answers: Vec::new(),
1393 triage_applied: Vec::new(),
1394 actions_applied: Vec::new(),
1395 decision_effects: Default::default(),
1396 superseded_resumes: Default::default(),
1397 dispatched_resumes: Default::default(),
1398 base_recovery_requests: Vec::new(),
1399 land_sync_recovery_requests: Vec::new(),
1400 instruction_revision_requests: Vec::new(),
1401 resume_override: None,
1402 sync_only: None,
1403 repair_grants: Vec::new(),
1404 repair_reconciliations: Vec::new(),
1405 resumption: None,
1406 resumption_history: Vec::new(),
1407 operator_decided_at: None,
1408 review_branch: None,
1409 review_instruction: None,
1410 pr_recovery: None,
1411 fresh_start: false,
1412 replacement: None,
1413 interrupt: false,
1414 urgent: false,
1415 immediate: false,
1416 unfiled: true,
1417 attachments: Vec::new(),
1418 followup: None,
1419 origin_chat,
1420 overrides: None,
1421 review_of: None,
1422 held_at: None,
1423 park_reason: None,
1424 chat_notice: None,
1425 chat_reservation: ChatReservation::None,
1426 chat_notices: Vec::new(),
1427 hold_notice_cause: None,
1428 passes: Vec::new(),
1429 dispatched_at: None,
1430 recovery_budget: None,
1431 recovery_admission: None,
1432 recovery_generations: Vec::new(),
1433 created_at: now,
1434 updated_at: now,
1435 }
1436 }
1437
1438 pub(crate) fn reassign_repository(&mut self, repo: PathBuf, actor: &str) {
1440 self.stamp_schema();
1441 if matches!(self.status, TaskStatus::Failed | TaskStatus::Parked) {
1442 self.hold_manual(Some(
1443 "Repository reassigned; inspect history and release to start fresh.".into(),
1444 ));
1445 }
1446 let at = Timestamp::now();
1447 self.reassignments.push(Reassignment {
1448 from: self.repo.clone(),
1449 to: repo.clone(),
1450 actor: actor.to_owned(),
1451 at,
1452 run_boundary: self.runs.len(),
1453 });
1454 self.repo = repo;
1455 self.review_branch = None;
1456 self.review_instruction = None;
1457 self.pr_recovery = None;
1458 self.replacement = None;
1459 self.interrupt = false;
1460 self.resume_override = None;
1461 self.fresh_start = true;
1462 self.operator_decided_at = Some(at);
1463 }
1464
1465 pub fn publication_branch(&self) -> String {
1467 crate::run::task_pr_branch_name(&self.id, self.reassignments.len())
1468 }
1469
1470 pub fn execution_runs(&self) -> &[String] {
1472 let boundary = self.reassignments.last().map_or(0, |r| r.run_boundary);
1473 self.runs.get(boundary..).unwrap_or_default()
1474 }
1475
1476 pub fn stale_pr_attention(&self, home: &Path) -> Option<String> {
1478 if self.status != TaskStatus::Done {
1479 return None;
1480 }
1481 let run = crate::run::RunState::load_under(self.execution_runs().last()?, home).ok()?;
1482 self.assignment_accepts(&run)
1483 .then(|| run.stale_pr_cause())
1484 .flatten()
1485 }
1486
1487 pub fn execution_run(&self, run: &str) -> bool {
1489 self.execution_runs().iter().any(|id| id == run)
1490 }
1491
1492 pub(crate) fn assignment_accepts(&self, run: &crate::run::RunState) -> bool {
1494 self.reassignments.last().is_none_or(|boundary| {
1495 self.execution_run(&run.id)
1496 && run.task_assignment == self.reassignments.len()
1497 && run.created_at > boundary.at
1498 && run
1499 .repo
1500 .canonicalize()
1501 .ok()
1502 .zip(self.repo.canonicalize().ok())
1503 .is_some_and(|(run_repo, task_repo)| run_repo == task_repo)
1504 })
1505 }
1506
1507 pub(crate) fn stale_question(&self, q: &crate::ask::Question) -> bool {
1509 self.reassignments
1510 .last()
1511 .is_some_and(|r| q.asked_at <= r.at)
1512 || (self.runs.contains(&q.run) && !self.execution_run(&q.run))
1513 }
1514
1515 pub fn chat_talk(&self) -> Option<&str> {
1517 if let Some(id) = &self.origin_chat {
1518 return Some(id);
1519 }
1520 match &self.source {
1521 Source::Agent { run, node } if node == CHAT_NODE => Some(run),
1522 _ => None,
1523 }
1524 }
1525
1526 pub fn filed_by_chat(&self) -> Option<&str> {
1530 match &self.source {
1531 Source::Agent { run, node } if node == CHAT_NODE => Some(run),
1532 _ => None,
1533 }
1534 }
1535
1536 pub fn issue_ref(&self) -> Option<IssueRef> {
1538 self.issue.clone().or_else(|| match &self.source {
1539 Source::Issue { number, repo } => Some(IssueRef {
1540 number: *number,
1541 repo: repo.clone(),
1542 }),
1543 _ => None,
1544 })
1545 }
1546
1547 pub fn source_label(&self) -> String {
1549 let actor = self.source.label();
1550 match &self.issue {
1551 Some(issue) if self.source == Source::Human => format!("issue #{}", issue.number),
1552 Some(issue) => format!("{actor} · issue #{}", issue.number),
1553 None => actor,
1554 }
1555 }
1556
1557 pub fn chat_notice_key(&self) -> Option<String> {
1560 match self.status {
1561 TaskStatus::Done => Some(
1562 self.completion_history
1563 .iter()
1564 .rev()
1565 .find(|event| event.action == CompletionAction::Complete)
1566 .map_or_else(
1567 || "done".to_owned(),
1568 |event| format!("done:{}", event.occurrence),
1569 ),
1570 ),
1571 TaskStatus::Held => {
1572 let cause = self
1573 .hold_notice_cause
1574 .clone()
1575 .unwrap_or_else(|| self.unresolved_hold_cause());
1576 Some(format!(
1577 "cause:{}",
1578 serde_json::to_string(&cause).expect("cause")
1579 ))
1580 }
1581 TaskStatus::Blocked => {
1582 let ids: std::collections::BTreeSet<_> = self.blocked_by.iter().collect();
1583 let evidence = self
1586 .hold_notice_cause
1587 .as_ref()
1588 .filter(|c| c.stage.starts_with("conductor-evidence:"));
1589 Some(format!(
1590 "dependencies:{}",
1591 serde_json::to_string(&(ids, evidence)).expect("ids")
1592 ))
1593 }
1594 _ => None,
1595 }
1596 }
1597
1598 fn unresolved_hold_cause(&self) -> NoticeCause {
1599 NoticeCause {
1600 stage: "hold".into(),
1601 target: None,
1602 run: self.runs.last().cloned(),
1603 pass: None,
1604 }
1605 }
1606
1607 pub(crate) fn legacy_chat_notice_key(&self) -> Option<String> {
1609 let key = match self.status {
1610 TaskStatus::Held if self.hold_notice_cause.is_none() => Some(format!(
1611 "held#{}",
1612 self.held_at.map(|t| t.to_string()).unwrap_or_default()
1613 )),
1614 TaskStatus::Blocked => Some(format!(
1615 "blocked#{}#{}",
1616 self.blocked_by.join(","),
1617 self.block_reason.as_deref().unwrap_or_default()
1618 )),
1619 _ => None,
1620 };
1621 key.filter(|key| self.legacy_notice_matches(key))
1622 }
1623
1624 pub(crate) fn legacy_notice_matches(&self, key: &str) -> bool {
1625 match self.status {
1626 TaskStatus::Held if self.hold_notice_cause.is_none() => key
1627 .strip_prefix("held#")
1628 .is_some_and(|time| time.is_empty() || time.parse::<Timestamp>().is_ok()),
1629 TaskStatus::Blocked
1630 if self
1631 .hold_notice_cause
1632 .as_ref()
1633 .is_none_or(|c| !c.stage.starts_with("conductor-evidence:")) =>
1634 {
1635 key.strip_prefix("blocked#").is_some_and(|tail| {
1636 let Some((ids, _)) = tail.split_once('#') else {
1637 return false;
1638 };
1639 let old: std::collections::BTreeSet<_> =
1640 ids.split(',').filter(|id| !id.is_empty()).collect();
1641 let current: std::collections::BTreeSet<_> =
1642 self.blocked_by.iter().map(String::as_str).collect();
1643 old == current
1644 })
1645 }
1646 _ => false,
1647 }
1648 }
1649
1650 fn import_chat_notice(&mut self) {
1651 if let Some(n) = &self.chat_notice {
1652 let key = if is_done_notice_key(&n.key) {
1653 "done".to_owned()
1654 } else if self.legacy_notice_matches(&n.key) {
1655 self.chat_notice_key().unwrap_or_else(|| n.key.clone())
1656 } else {
1657 n.key.clone()
1658 };
1659 if !self.chat_notices.contains(&key) {
1660 self.chat_notices.push(key);
1661 }
1662 }
1663 }
1664
1665 pub(crate) fn notice_cause(&mut self, stage: &str, run: Option<&str>, pass: Option<usize>) {
1668 self.import_chat_notice();
1669 self.hold_notice_cause = Some(NoticeCause {
1670 stage: stage.to_owned(),
1671 target: None,
1672 run: run.map(str::to_owned),
1673 pass,
1674 });
1675 }
1676
1677 pub(crate) fn startup_notice_cause(&mut self, stage: &str) {
1680 let recovery_only = matches!(
1681 stage,
1682 "startup-source" | "startup-candidates" | "startup-public-head"
1683 );
1684 match self.hold_notice_cause.as_ref() {
1685 Some(cause) if recovery_only && !cause.stage.starts_with("startup-") => return,
1686 None if recovery_only
1687 && self
1688 .chat_notice
1689 .as_ref()
1690 .is_some_and(|n| !is_done_notice_key(&n.key)) =>
1691 {
1692 return;
1693 }
1694 _ => {}
1695 }
1696 self.notice_cause(stage, None, None);
1697 }
1698
1699 pub(crate) fn fail_startup(
1702 &mut self,
1703 stage: &str,
1704 why: impl Into<String>,
1705 max_attempts: usize,
1706 ) {
1707 let unresolved = self.hold_notice_cause.clone();
1708 self.fail(why, max_attempts);
1709 self.hold_notice_cause = unresolved;
1710 self.startup_notice_cause(stage);
1711 }
1712
1713 pub(crate) fn fail_startup_target(
1715 &mut self,
1716 stage: &str,
1717 target: String,
1718 why: impl Into<String>,
1719 max_attempts: usize,
1720 ) {
1721 self.fail_startup(stage, why, max_attempts);
1722 if let Some(cause) = self.hold_notice_cause.as_mut() {
1723 cause.target = Some(target);
1724 }
1725 }
1726
1727 pub fn chat_notice_due(&self) -> Option<String> {
1732 if self.schema < 13 {
1733 return None;
1734 }
1735 if self.filed_by_chat().is_none() && !self.completed_by_current_build() {
1736 return None;
1737 }
1738 let key = self.chat_notice_key()?;
1739 if self.chat_notices.contains(&key) {
1740 return None;
1741 }
1742 match &self.chat_notice {
1743 Some(n)
1744 if n.key == key
1745 || (key == "done" && is_done_notice_key(&n.key))
1746 || self.legacy_notice_matches(&n.key) =>
1747 {
1748 None
1749 }
1750 _ => Some(key),
1751 }
1752 }
1753
1754 fn completed_by_current_build(&self) -> bool {
1757 self.status == TaskStatus::Done
1758 && !matches!(self.source, Source::Agent { .. })
1759 && self
1760 .completion_history
1761 .iter()
1762 .rev()
1763 .find(|event| event.action == CompletionAction::Complete)
1764 .is_some_and(|event| event.schema >= COMPLETION_REPORT_SCHEMA)
1765 }
1766
1767 pub fn short(&self) -> &str {
1769 short(&self.id)
1770 }
1771
1772 pub fn mark_triage_applied(&mut self, question_id: &str) {
1774 if !self.triage_applied(question_id) {
1775 self.triage_applied.push(question_id.to_owned());
1776 }
1777 }
1778
1779 pub fn action_applied(&self, question_id: &str) -> bool {
1782 self.actions_applied.iter().any(|id| id == question_id)
1783 }
1784
1785 pub fn mark_action_applied(&mut self, question_id: &str) {
1787 if !self.action_applied(question_id) {
1788 self.actions_applied.push(question_id.to_owned());
1789 }
1790 }
1791
1792 pub fn triage_applied(&self, question_id: &str) -> bool {
1794 self.triage_applied.iter().any(|id| id == question_id)
1795 }
1796
1797 pub fn start(&mut self, run: String) {
1810 self.stamp_schema();
1811 self.status = TaskStatus::Running;
1812 self.attempts += 1;
1813 self.runs.retain(|id| id != &run);
1814 if let Some(pin) = &self.resume_override
1815 && pin.pinned_run.as_ref() == Some(&run)
1816 && !pin.question_id.is_empty()
1817 {
1818 self.dispatched_resumes
1819 .insert(pin.question_id.clone(), run.clone());
1820 }
1821 self.runs.push(run);
1822 self.last_error = None;
1823 self.park_reason = None;
1824 self.fresh_start = false;
1825 self.interrupt = false;
1826 self.resume_override = None;
1828 self.disk_resume_run = None;
1831 }
1832
1833 pub fn record_startup_failure(&mut self, failure: crate::run::StartupFailure) {
1835 if !self.startup_failures.iter().any(|f| f.run == failure.run) {
1836 self.startup_failures.push(failure);
1837 }
1838 }
1839
1840 pub fn link_run(&mut self, run: &str) -> bool {
1845 if self.runs.iter().any(|r| r == run) {
1846 return false;
1847 }
1848 self.runs.push(run.to_owned());
1849 true
1850 }
1851
1852 pub fn succeed(&mut self, context: CompletionContext) {
1862 if self.status == TaskStatus::Done {
1863 return;
1864 }
1865 self.record_completion(CompletionAction::Complete, context);
1866 self.stamp_schema();
1867 self.status = TaskStatus::Done;
1868 self.landing = None;
1869 if let Some(pin) = self.resume_override.take()
1870 && !pin.question_id.is_empty()
1871 && let Some(run) = pin.pinned_run
1872 {
1873 self.superseded_resumes.insert(pin.question_id, run);
1876 }
1877 self.sync_only = None;
1878 self.last_error = None;
1879 self.park_reason = None;
1880 self.hold_reason = None;
1881 self.hold_source = None;
1882 self.machine_hold_cause = None;
1883 self.disk_resume_run = None;
1884 self.disk_checked_at = None;
1885 self.diagnostic = None;
1886 self.blocked_by.clear();
1887 self.block_reason = None;
1888 self.blocked_from = None;
1889 }
1890
1891 pub fn already_landed(&mut self, note: impl Into<String>, mut context: CompletionContext) {
1899 let note = note.into();
1900 if context.reason.is_none() {
1901 context.reason = Some(note.clone());
1902 }
1903 self.succeed(context);
1904 self.attempts = self.attempts.saturating_sub(1);
1905 self.last_error = Some(note);
1906 }
1907
1908 fn record_completion(&mut self, action: CompletionAction, context: CompletionContext) {
1909 self.completion_history.push(CompletionEvent {
1910 occurrence: format!(
1911 "{}-{:016x}{:016x}",
1912 Timestamp::now(),
1913 crate::rng::entropy(),
1914 crate::rng::entropy()
1915 ),
1916 action,
1917 actor: context.actor,
1918 reason: context.reason,
1919 discard: context.discard,
1920 prior_status: self.status,
1921 at: Timestamp::now(),
1922 schema: SCHEMA,
1923 prior_hold_reason: self.hold_reason.clone(),
1924 prior_block_reason: self.block_reason.clone(),
1925 prior_error: self.last_error.clone(),
1926 run: context.run,
1927 unavailable_runs: context.unavailable_runs,
1928 });
1929 self.stamp_schema();
1930 }
1931
1932 pub fn reopen(&mut self, context: CompletionContext) -> Result<()> {
1935 anyhow::ensure!(
1936 self.status == TaskStatus::Done,
1937 "only a done task can be reopened"
1938 );
1939 anyhow::ensure!(
1940 context
1941 .reason
1942 .as_deref()
1943 .is_some_and(|reason| !reason.trim().is_empty()),
1944 "reopen requires a non-empty reason"
1945 );
1946 let reason = context.reason.clone();
1947 self.record_completion(CompletionAction::Reopen, context);
1948 self.hold_manual(reason);
1949 self.resume_override = None;
1950 self.reopen_hold =
1951 self.held_at
1952 .zip(self.completion_history.last())
1953 .map(|(held_at, event)| ReopenHold {
1954 occurrence: event.occurrence.clone(),
1955 held_at,
1956 decision: self.operator_decided_at,
1957 legacy: false,
1958 });
1959 self.fresh_start = false;
1960 self.last_error = None;
1961 self.diagnostic = None;
1962 Ok(())
1963 }
1964
1965 pub fn superseded_attempts(&self, last_run_succeeded: bool) -> &[String] {
1995 if self.status != TaskStatus::Done || !last_run_succeeded || self.execution_runs().len() < 2
1996 {
1997 return &[];
1998 }
1999 &self.execution_runs()[..self.execution_runs().len() - 1]
2000 }
2001
2002 pub fn successor_of(&self, run: &str) -> Option<&String> {
2010 let runs = self.execution_runs();
2011 let pos = runs.iter().rposition(|r| r == run)?;
2012 runs.get(pos + 1)
2013 }
2014
2015 pub fn earlier_attempts(&self) -> &[String] {
2022 self.execution_runs()
2023 }
2024
2025 fn preserve_legacy_build_cache(&mut self) {
2026 if self.schema < 23 {
2027 let overrides = self.overrides.get_or_insert_with(|| RunOverrides {
2028 inherit_daemon_options: true,
2029 ..RunOverrides::default()
2030 });
2031 overrides.build_cache.get_or_insert(BuildCache::Shared);
2032 }
2033 }
2034
2035 fn stamp_schema(&mut self) {
2040 self.preserve_legacy_build_cache();
2041 if self.schema < RECOVERY_HOLD_SCHEMA && self.recovery_budget_hold.is_none() {
2042 self.recovery_budget_hold = self.legacy_recovery_budget_hold();
2043 }
2044 self.snapshot_legacy_reopen_hold();
2045 self.schema = self.schema.max(SCHEMA);
2046 }
2047
2048 fn note_held(&mut self) {
2051 self.stamp_schema();
2052 self.recovery_budget_hold = None;
2053 self.reopen_hold = None;
2054 let continuing = self.status == TaskStatus::Held
2055 || (self.status == TaskStatus::Blocked
2056 && (self.blocked_from == Some(TaskStatus::Held)
2057 || (self.blocked_from.is_none()
2058 && (self.hold_reason.is_some() || self.hold_source.is_some()))));
2059 if !continuing || self.held_at.is_none() {
2060 self.held_at = Some(Timestamp::now());
2061 }
2062 }
2063
2064 pub fn fail(&mut self, why: impl Into<String>, max_attempts: usize) {
2080 let why = why.into();
2081 if self.status == TaskStatus::Running {
2082 let run = self.runs.last().cloned();
2083 self.notice_cause("run-failed", run.as_deref(), Some(self.attempts));
2084 }
2085 self.diagnostic = None;
2086 self.park_reason = None;
2087 self.status = if self.attempts >= self.effective_attempt_limit(max_attempts) {
2088 self.note_held();
2089 self.hold_source = Some(HoldSource::Machine);
2090 self.machine_hold_cause = None;
2091 self.disk_resume_run = None;
2092 self.disk_checked_at = None;
2093 self.hold_reason = Some(why.clone());
2094 TaskStatus::Held
2095 } else {
2096 TaskStatus::Failed
2097 };
2098 self.last_error = Some(why);
2099 }
2100
2101 pub fn stall(&mut self, why: impl Into<String>) {
2111 self.last_error = Some(why.into());
2112 self.diagnostic = None;
2113 self.attempts = self.attempts.saturating_sub(1);
2114 self.status = TaskStatus::Failed;
2115 }
2116
2117 pub fn park(&mut self, why: impl Into<String>) {
2123 self.diagnostic = None;
2124 self.attempts = self.attempts.saturating_sub(1);
2125 self.status = TaskStatus::Parked;
2126 self.park_reason = Some(why.into());
2127 self.stamp_schema();
2130 }
2131
2132 pub fn record_pass(
2134 &mut self,
2135 run: &str,
2136 pass_index: usize,
2137 attempts_before: usize,
2138 parked: Option<crate::run::ParkCause>,
2139 ) {
2140 self.record_pass_at(run, pass_index, None, attempts_before, parked);
2141 }
2142
2143 pub fn record_pass_at(
2146 &mut self,
2147 run: &str,
2148 pass_index: usize,
2149 started_at: Option<Timestamp>,
2150 attempts_before: usize,
2151 parked: Option<crate::run::ParkCause>,
2152 ) {
2153 if self
2154 .passes
2155 .iter()
2156 .any(|p| p.run == run && p.pass_index == pass_index)
2157 {
2158 return;
2159 }
2160 let cost = if self.attempts < attempts_before {
2161 PassCost::Refunded
2162 } else {
2163 PassCost::Spent
2164 };
2165 self.passes.push(TaskPass {
2166 run: run.to_owned(),
2167 pass_index,
2168 started_at: self.dispatched_at.or(started_at),
2169 cost,
2170 attempts_after: self.attempts,
2171 settled_at: Timestamp::now(),
2172 parked,
2173 });
2174 self.stamp_schema();
2175 }
2176
2177 pub(crate) fn upgrade_resume_key(&self) -> Option<(Timestamp, &str)> {
2180 if self.status != TaskStatus::Parked || self.fresh_start {
2181 return None;
2182 }
2183 let pass = self.passes.last()?;
2184 if self.execution_runs().last() != Some(&pass.run)
2185 || !matches!(pass.parked, Some(crate::run::ParkCause::Upgrade { .. }))
2186 {
2187 return None;
2188 }
2189 Some((pass.started_at.unwrap_or(pass.settled_at), &self.id))
2192 }
2193
2194 pub fn operator_held(&self) -> bool {
2200 self.status == TaskStatus::Held && !matches!(self.hold_source, Some(HoldSource::Machine))
2201 }
2202
2203 pub fn hold_manual(&mut self, reason: Option<String>) {
2213 self.operator_decided_at = Some(Timestamp::now());
2215 if self.status != TaskStatus::Running && self.sync_only.take().is_some() {
2216 self.resume_override = None;
2217 }
2218 self.hold_unrequested_retry(reason);
2219 }
2220
2221 pub(crate) fn hold_unrequested_retry(&mut self, reason: Option<String>) {
2224 self.park_reason = None;
2225 self.note_held();
2226 self.status = TaskStatus::Held;
2227 if reason.is_some() {
2228 self.hold_reason = reason;
2229 }
2230 self.hold_source = Some(HoldSource::Manual);
2231 self.machine_hold_cause = None;
2232 self.disk_resume_run = None;
2233 self.disk_checked_at = None;
2234 self.blocked_by.clear();
2235 self.block_reason = None;
2236 self.blocked_from = None;
2237 }
2238
2239 pub(crate) fn hold_after_sync_only(&mut self, reason: String) {
2240 let recovery_hold = self.recovery_budget_hold.take();
2241 self.hold_unrequested_retry(Some(reason));
2242 self.recovery_budget_hold = recovery_hold;
2243 }
2244
2245 pub fn hold_machine(&mut self, reason: Option<String>) {
2250 self.park_reason = None;
2251 self.note_held();
2252 self.status = TaskStatus::Held;
2253 if reason.is_some() {
2254 self.hold_reason = reason;
2255 }
2256 self.hold_source = Some(HoldSource::Machine);
2257 self.machine_hold_cause = None;
2258 self.disk_resume_run = None;
2259 self.disk_checked_at = None;
2260 self.blocked_by.clear();
2261 self.block_reason = None;
2262 self.blocked_from = None;
2263 }
2264
2265 pub(crate) fn mark_disk_capacity(&mut self) {
2267 self.machine_hold_cause = Some(MachineHoldCause::DiskCapacity {
2268 reason: self.hold_reason.clone().unwrap_or_default(),
2269 before_start: false,
2270 });
2271 }
2272
2273 pub(crate) fn mark_startup_disk_capacity(&mut self) {
2274 self.machine_hold_cause = Some(MachineHoldCause::DiskCapacity {
2275 reason: self.hold_reason.clone().unwrap_or_default(),
2276 before_start: true,
2277 });
2278 }
2279
2280 pub(crate) fn disk_wait_run(&self) -> Option<&String> {
2281 if self.has_disk_capacity_cause()
2282 && matches!(
2283 self.machine_hold_cause,
2284 Some(MachineHoldCause::DiskCapacity {
2285 before_start: true,
2286 ..
2287 })
2288 )
2289 {
2290 None
2291 } else {
2292 self.execution_runs().last()
2293 }
2294 }
2295
2296 pub fn has_disk_capacity_cause(&self) -> bool {
2298 matches!(
2299 (&self.machine_hold_cause, self.hold_reason.as_deref()),
2300 (Some(MachineHoldCause::DiskCapacity { reason, .. }), Some(now)) if reason == now
2301 )
2302 }
2303
2304 pub(crate) fn resume_disk_wait(&mut self) {
2306 let retained = self.disk_wait_run().cloned();
2307 self.status = TaskStatus::Queued;
2308 self.held_at = None;
2309 self.hold_source = None;
2310 self.hold_reason = None;
2311 self.machine_hold_cause = None;
2312 self.last_error = None;
2313 self.disk_resume_run = retained;
2314 }
2315
2316 pub(crate) fn hold_head_e2e(
2318 &mut self,
2319 stop: crate::head_e2e_stop::Stop,
2320 reason: String,
2321 last_error: String,
2322 ) {
2323 self.hold_machine(Some(reason));
2324 self.last_error = Some(last_error);
2325 self.machine_hold_cause = Some(MachineHoldCause::HeadE2e { stop });
2326 }
2327
2328 pub(crate) fn head_e2e_notice(&mut self, stop: &crate::head_e2e_stop::Stop) {
2330 if let Some(at) = stop.recorded_at {
2331 self.held_at = Some(at);
2332 }
2333 self.notice_cause(crate::head_e2e_stop::NOTICE_STAGE, Some(&stop.run), None);
2334 if let Some(cause) = &mut self.hold_notice_cause {
2335 cause.target = Some(stop.id.clone());
2336 }
2337 }
2338
2339 pub fn has_head_e2e_cause(&self) -> bool {
2341 matches!(
2342 self.machine_hold_cause,
2343 Some(MachineHoldCause::HeadE2e { .. })
2344 )
2345 }
2346
2347 pub(crate) fn hold_awaiting_landing(&mut self, run: String, reason: String) {
2350 self.hold_machine(Some(reason.clone()));
2351 self.last_error = Some(reason.clone());
2352 self.machine_hold_cause = Some(MachineHoldCause::AwaitingLanding { run, reason });
2353 self.stamp_schema();
2354 }
2355
2356 pub fn has_awaiting_landing_cause(&self) -> bool {
2358 self.status == TaskStatus::Held
2359 && matches!(
2360 self.machine_hold_cause,
2361 Some(MachineHoldCause::AwaitingLanding { .. })
2362 )
2363 }
2364
2365 pub fn awaiting_landing_run(&self) -> Option<&str> {
2367 if self.status != TaskStatus::Held {
2368 return None;
2369 }
2370 match &self.machine_hold_cause {
2371 Some(MachineHoldCause::AwaitingLanding { run, .. }) => Some(run.as_str()),
2372 _ => None,
2373 }
2374 }
2375
2376 pub fn completed_by_discard(&self) -> bool {
2378 self.status == TaskStatus::Done
2379 && self
2380 .completion_history
2381 .last()
2382 .is_some_and(|event| event.action == CompletionAction::Complete && event.discard)
2383 }
2384
2385 pub fn current_investigation_result(&self) -> Option<&str> {
2387 self.completion_result
2388 .as_ref()
2389 .filter(|res| {
2390 res.instruction_rev == self.instruction_rev && !res.text.trim().is_empty()
2391 })
2392 .map(|res| res.text.as_str())
2393 }
2394
2395 pub fn validate_investigation_result<'a>(
2398 &'a self,
2399 result: Option<&'a str>,
2400 ) -> Result<Option<&'a str>> {
2401 if !self.investigation {
2402 return Ok(None);
2403 }
2404 if let Some(raw) = result {
2405 let trimmed = raw.trim();
2406 anyhow::ensure!(
2407 !trimmed.is_empty(),
2408 "an investigation requires a nonblank --result"
2409 );
2410 return Ok(Some(trimmed));
2411 }
2412 self.current_investigation_result()
2413 .map(Some)
2414 .context("an investigation requires a nonblank --result")
2415 }
2416
2417 pub fn record_investigation_result(&mut self, result: Option<&str>) -> Result<()> {
2419 if !self.investigation {
2420 return Ok(());
2421 }
2422 let text = self
2423 .validate_investigation_result(result)?
2424 .expect("investigation validated nonblank")
2425 .to_owned();
2426 if result.is_some()
2427 || self
2428 .completion_result
2429 .as_ref()
2430 .is_none_or(|existing| existing.instruction_rev != self.instruction_rev)
2431 {
2432 self.completion_result = Some(InvestigationResult {
2433 text,
2434 instruction_rev: self.instruction_rev,
2435 recorded_at: Timestamp::now(),
2436 });
2437 self.stamp_schema();
2438 }
2439 Ok(())
2440 }
2441
2442 pub fn head_e2e_stop_id(&self) -> Option<&str> {
2444 if let Some(MachineHoldCause::HeadE2e { stop }) = &self.machine_hold_cause {
2445 return Some(stop.id.as_str());
2446 }
2447 self.hold_notice_cause
2448 .as_ref()
2449 .filter(|c| c.stage == crate::head_e2e_stop::NOTICE_STAGE)
2450 .and_then(|c| c.target.as_deref())
2451 }
2452
2453 pub(crate) fn resume_head_e2e_wait(&mut self) {
2456 self.status = TaskStatus::Queued;
2457 self.held_at = None;
2458 self.hold_source = None;
2459 self.hold_reason = None;
2460 self.machine_hold_cause = None;
2461 self.last_error = None;
2462 self.diagnostic = None;
2463 self.blocked_by.clear();
2464 self.block_reason = None;
2465 self.blocked_from = None;
2466 }
2467
2468 pub fn block(&mut self, blocked_by: Vec<String>, reason: Option<String>) {
2478 self.stamp_schema();
2479 let before: std::collections::BTreeSet<_> = self.blocked_by.iter().collect();
2480 let after: std::collections::BTreeSet<_> = blocked_by.iter().collect();
2481 if self.status != TaskStatus::Blocked || before != after {
2482 self.blocked_at = Some(Timestamp::now());
2483 }
2484 if self.status != TaskStatus::Blocked {
2485 self.blocked_from = Some(self.status);
2486 }
2487 self.status = TaskStatus::Blocked;
2488 self.blocked_by = blocked_by;
2489 self.block_reason = reason;
2490 }
2491
2492 pub fn unblock(&mut self, resolved_id: &str) {
2515 if self.status != TaskStatus::Blocked {
2516 return;
2517 }
2518 self.blocked_by.retain(|id| id != resolved_id);
2519 self.restore_if_unblocked();
2520 }
2521
2522 pub fn dependency_deleted(&mut self, deleted_id: &str) -> bool {
2533 if self.status != TaskStatus::Blocked || !self.blocked_by.iter().any(|b| b == deleted_id) {
2534 return false;
2535 }
2536 self.blocked_by.retain(|id| id != deleted_id);
2537 self.restore_if_unblocked();
2538 true
2539 }
2540
2541 fn restore_if_unblocked(&mut self) {
2545 if self.blocked_by.is_empty() {
2546 self.status = match self.blocked_from {
2547 Some(TaskStatus::Running) => TaskStatus::Queued,
2548 Some(other) => other,
2549 None if self.hold_reason.is_some() || self.hold_source.is_some() => {
2550 TaskStatus::Held
2551 }
2552 None => TaskStatus::Queued,
2553 };
2554 self.block_reason = None;
2555 self.blocked_from = None;
2556 }
2557 }
2558
2559 pub fn record_answer(&mut self, question: String, answer: String) {
2564 self.answers.push(AnsweredQuestion { question, answer });
2565 }
2566
2567 pub fn request_review(&mut self, branch: String) {
2571 self.release();
2572 self.review_branch = Some(branch);
2573 self.review_instruction = Some(self.instruction.clone());
2574 }
2575
2576 pub fn requeue(&mut self) {
2579 self.release();
2580 self.review_branch = None;
2582 self.review_instruction = None;
2583 self.fresh_start = true;
2584 }
2585
2586 pub fn hold_for_handover(&mut self, branch: Option<String>, reason: String) {
2595 if branch.is_some() {
2596 self.review_branch = branch;
2597 self.review_instruction = Some(self.instruction.clone());
2598 }
2599 self.hold_machine(Some(reason));
2600 }
2601
2602 pub fn set_urgent(&mut self, urgent: bool) -> Result<()> {
2604 if !matches!(self.status, TaskStatus::Queued | TaskStatus::Held) {
2605 bail!(
2606 "task {} is {}; urgent can only change while queued or held; \
2607 wait for the active attempt to finish and requeue or hold the task first",
2608 self.short(),
2609 self.status.as_str()
2610 );
2611 }
2612 self.urgent = urgent;
2613 Ok(())
2614 }
2615
2616 pub fn set_immediate(&mut self, immediate: bool) -> Result<()> {
2620 if !matches!(self.status, TaskStatus::Queued | TaskStatus::Held) {
2621 bail!(
2622 "task {} is {}; immediate can only change while queued or held; \
2623 wait for the active attempt to finish and requeue or hold the task first",
2624 self.short(),
2625 self.status.as_str()
2626 );
2627 }
2628 self.immediate = immediate;
2629 Ok(())
2630 }
2631
2632 pub fn set_priority(&mut self, priority: i32) -> Result<()> {
2641 if self.status == TaskStatus::Running {
2642 bail!(
2643 "task {} is running; its priority cannot be changed until \
2644 this attempt finishes",
2645 self.short()
2646 );
2647 }
2648 self.priority = priority;
2649 Ok(())
2650 }
2651
2652 pub fn set_interrupt(&mut self, interrupt: bool) -> Result<()> {
2667 if interrupt && !self.status.runnable() {
2668 bail!(
2669 "task {} is {}; only a queued or failed task can be marked \
2670 to interrupt",
2671 self.short(),
2672 self.status.as_str()
2673 );
2674 }
2675 self.interrupt = interrupt;
2676 Ok(())
2677 }
2678
2679 pub fn effective_attempt_limit(&self, daemon_limit: usize) -> usize {
2681 self.attempt_limit.map_or(daemon_limit, NonZeroUsize::get)
2682 }
2683
2684 pub fn change_attempt_limit(&mut self, limit: Option<NonZeroUsize>) -> Result<()> {
2687 if !matches!(self.status, TaskStatus::Queued | TaskStatus::Held) {
2688 bail!("only queued or held tasks can change the attempt limit");
2689 }
2690 self.stamp_schema();
2691 self.attempt_limit = limit;
2692 Ok(())
2693 }
2694
2695 pub fn implementers(&self) -> Option<usize> {
2697 if self.solo {
2698 Some(1)
2699 } else {
2700 self.overrides.as_ref().and_then(|o| o.candidates)
2701 }
2702 }
2703
2704 pub fn build_cache_override(
2709 &self,
2710 config: &crate::config::Config,
2711 ) -> Option<(BuildCache, &'static str)> {
2712 self.overrides
2713 .as_ref()
2714 .and_then(|o| o.build_cache)
2715 .map(|mode| (mode, "task-override"))
2716 .or_else(|| {
2717 ((self.immediate || self.urgent) && crate::build_target::urgent_isolation(config))
2718 .then_some((
2719 BuildCache::Isolated,
2720 if self.immediate {
2721 "immediate"
2722 } else {
2723 "urgent"
2724 },
2725 ))
2726 })
2727 }
2728
2729 pub fn change_build_cache(&mut self, mode: Option<BuildCache>) -> Result<()> {
2732 if !matches!(self.status, TaskStatus::Queued | TaskStatus::Held) {
2733 bail!(
2734 "task {} is {}; only queued or held tasks can change build cache",
2735 self.short(),
2736 self.status.as_str()
2737 );
2738 }
2739 self.stamp_schema();
2740 if self.overrides.is_some() || mode.is_some() {
2741 let overrides = self.overrides.get_or_insert_with(|| RunOverrides {
2742 inherit_daemon_options: true,
2743 ..RunOverrides::default()
2744 });
2745 overrides.build_cache = mode;
2746 }
2747 Ok(())
2748 }
2749
2750 pub fn change_implementers(&mut self, count: u8) -> Result<()> {
2753 self.check_implementers_editable()?;
2754 let explicit = self.overrides.as_ref().and_then(|o| o.config.as_deref());
2755 let (mut config, _) = crate::config::Config::discover(&self.repo, explicit)?;
2756 if let Some(o) = &self.overrides {
2757 o.apply(&mut config);
2758 }
2759 self.set_implementers(count, &config)
2760 }
2761
2762 fn check_implementers_editable(&self) -> Result<()> {
2763 if !matches!(self.status, TaskStatus::Queued | TaskStatus::Held) {
2764 bail!(
2765 "task {} is {}; only queued or held tasks can change implementers",
2766 self.short(),
2767 self.status.as_str()
2768 );
2769 }
2770 Ok(())
2771 }
2772
2773 pub fn set_implementers(&mut self, count: u8, config: &crate::config::Config) -> Result<()> {
2775 self.check_implementers_editable()?;
2776 crate::talk::check_implementers(count, config).map_err(anyhow::Error::msg)?;
2777 self.stamp_schema();
2778 self.solo = count == 1;
2779 let mut overrides = self.overrides.clone().unwrap_or_else(|| RunOverrides {
2780 inherit_daemon_options: true,
2781 ..Default::default()
2782 });
2783 overrides.candidates = (count > 1).then_some(usize::from(count));
2784 let mut settings = overrides.clone();
2785 settings.inherit_daemon_options = false;
2786 self.overrides = if overrides.inherit_daemon_options && settings == RunOverrides::default()
2788 {
2789 None
2790 } else {
2791 Some(overrides)
2792 };
2793 Ok(())
2794 }
2795
2796 pub fn edit(&mut self, title: String, instruction: String) -> Result<()> {
2808 if !matches!(self.status, TaskStatus::Queued | TaskStatus::Held) {
2809 bail!(
2810 "task {} is {}; only a queued or held task's instruction can \
2811 be edited",
2812 self.short(),
2813 self.status.as_str()
2814 );
2815 }
2816 if self.review_branch.is_some() && self.review_instruction.is_none() {
2819 self.review_instruction = Some(self.instruction.clone());
2820 }
2821 let instruction_changed = self.instruction != instruction;
2822 if instruction_changed {
2823 self.instruction_rev = self.instruction_rev.saturating_add(1);
2827 self.completion_result = None;
2828 self.landing = None;
2829 self.resume_override = None;
2830 self.stamp_schema();
2831 }
2832 let keep_awaiting_landing = !instruction_changed && self.has_awaiting_landing_cause();
2833 if !keep_awaiting_landing {
2834 if self.status == TaskStatus::Held && self.machine_hold_cause.is_some() {
2835 self.hold_manual(self.hold_reason.clone());
2836 }
2837 self.machine_hold_cause = None;
2838 }
2839 self.disk_resume_run = None;
2840 self.disk_checked_at = None;
2841 self.title = title;
2842 self.instruction = instruction;
2843 Ok(())
2844 }
2845
2846 pub fn handed_off(&mut self, why: impl Into<String>) {
2866 let why = why.into();
2867 self.diagnostic = None;
2868 self.note_held();
2869 self.status = TaskStatus::Held;
2870 self.hold_source = Some(HoldSource::Machine);
2871 self.machine_hold_cause = None;
2872 self.disk_resume_run = None;
2873 self.disk_checked_at = None;
2874 self.hold_reason = Some(why.clone());
2875 self.last_error = Some(why);
2876 }
2877
2878 pub fn release_operator(&mut self, source: &str, question_id: Option<&str>) {
2880 self.recovery_budget = None;
2881 self.recovery_generations.clear();
2882 self.recovery_admission = None;
2883 if self
2884 .resumption
2885 .as_ref()
2886 .is_some_and(|r| r.instruction != self.instruction)
2887 {
2888 self.resume_override = None;
2891 }
2892 let approval = Resumption {
2893 generation: self.resumption.as_ref().map_or(1, |r| r.generation + 1),
2894 source: source.to_owned(),
2895 question_id: question_id.map(str::to_owned),
2896 at: Timestamp::now(),
2897 instruction: self.instruction.clone(),
2898 answers_through: self.answers.len(),
2899 runs_through: self.runs.len(),
2900 blocking_evidence: Vec::new(),
2901 cleared_reason: self
2902 .hold_reason
2903 .clone()
2904 .or_else(|| self.block_reason.clone()),
2905 };
2906 self.release();
2907 self.operator_decided_at = Some(approval.at);
2908 if let Some(previous) = self.resumption.replace(approval) {
2909 self.resumption_history.push(previous);
2910 }
2911 }
2912
2913 pub(crate) fn recovery_failed(&mut self, state: &crate::run::RunState) {
2915 let (base, inputs) = self.recovery_admission.as_ref().map_or_else(
2916 || (state.base_commit.clone(), recovery_inputs(&state.sources)),
2917 |a| (a.base.clone(), a.inputs.clone()),
2918 );
2919 let progress = recovery_progress(state);
2920 let stage = if state.prep_failure.is_some() {
2921 "preparation"
2922 } else {
2923 "execution"
2924 };
2925 let matches = |b: &RecoveryBudget| {
2926 b.instruction == self.instruction
2927 && b.base == base
2928 && b.inputs == inputs
2929 && (progress.is_none() || b.progress == progress)
2930 };
2931 if !self.recovery_budget.as_ref().is_some_and(matches) {
2932 let previous = self
2933 .recovery_generations
2934 .iter()
2935 .position(matches)
2936 .map(|index| self.recovery_generations.remove(index));
2937 if let Some(old) = self.recovery_budget.take() {
2938 self.recovery_generations.push(old);
2939 }
2940 self.recovery_budget = previous;
2941 }
2942 if let Some(budget) = &mut self.recovery_budget {
2943 budget.failures = budget.failures.saturating_add(1);
2944 budget.stage = stage.to_owned();
2945 } else {
2946 self.recovery_budget = Some(RecoveryBudget {
2947 instruction: self.instruction.clone(),
2948 base,
2949 inputs,
2950 stage: stage.to_owned(),
2951 failures: 1,
2952 progress,
2953 });
2954 }
2955 }
2956
2957 pub(crate) fn recovery_exhausted(
2958 &self,
2959 base: &str,
2960 inputs: &str,
2961 limit: usize,
2962 ) -> Option<String> {
2963 let same_input = |b: &&RecoveryBudget| {
2964 b.instruction == self.instruction && b.base == base && b.inputs == inputs
2965 };
2966 let budget = self
2967 .recovery_budget
2968 .as_ref()
2969 .filter(same_input)
2970 .or_else(|| self.recovery_generations.iter().rev().find(same_input))?;
2971 (budget.failures >= limit.max(1)).then(|| budget.budget_reason())
2972 }
2973
2974 pub(crate) fn hold_recovery_budget(&mut self, reason: String, admission: RecoveryAdmission) {
2975 self.hold_unrequested_retry(Some(reason));
2976 if let Some(pass) = self.passes.last()
2977 && self.execution_runs().last() == Some(&pass.run)
2978 {
2979 self.recovery_budget_hold = Some(RecoveryBudgetHold {
2980 admission,
2981 run: pass.run.clone(),
2982 pass: pass.pass_index,
2983 held_at: self.held_at.expect("hold timestamp just recorded"),
2984 decision: self.operator_decided_at,
2985 legacy: false,
2986 });
2987 }
2988 }
2989
2990 fn matches_budget_hold(&self, admission: &RecoveryAdmission) -> bool {
2991 self.status == TaskStatus::Held
2992 && self.hold_source == Some(HoldSource::Manual)
2993 && self.machine_hold_cause.is_none()
2994 && self.recovery_budget.as_ref().is_some_and(|budget| {
2995 budget.instruction == self.instruction
2996 && budget.base == admission.base
2997 && budget.inputs == admission.inputs
2998 && budget.stage == "execution"
2999 && budget.failures > 0
3000 && self
3001 .hold_reason
3002 .as_ref()
3003 .is_some_and(|reason| *reason == budget.budget_reason())
3004 })
3005 }
3006
3007 fn legacy_recovery_budget_hold(&self) -> Option<RecoveryBudgetHold> {
3008 let held_at = self.held_at?;
3009 let settled = self.passes.last()?;
3010 let admission = self.recovery_admission.as_ref()?;
3011 if !self.matches_budget_hold(admission)
3012 || self.execution_runs().last() != Some(&settled.run)
3013 || settled.cost != PassCost::Spent
3014 || settled.parked.is_some()
3015 || settled.settled_at > held_at
3016 || self.operator_decided_at.is_some_and(|at| at >= held_at)
3017 {
3018 return None;
3019 }
3020 Some(RecoveryBudgetHold {
3021 admission: admission.clone(),
3022 run: settled.run.clone(),
3023 pass: settled.pass_index,
3024 held_at,
3025 decision: self.operator_decided_at,
3026 legacy: true,
3027 })
3028 }
3029
3030 pub(crate) fn held_for_recovery_budget(&self, run: &crate::run::RunState) -> bool {
3031 let (Some(held_at), Some(settled), Some(pass), Some(admission)) = (
3032 self.held_at,
3033 self.passes.last(),
3034 run.passes.last(),
3035 self.recovery_admission.as_ref(),
3036 ) else {
3037 return false;
3038 };
3039 if !self.matches_budget_hold(admission)
3040 || self.execution_runs().last() != Some(&run.id)
3041 || settled.run != run.id
3042 || settled.pass_index != pass.index
3043 || settled.cost != PassCost::Spent
3044 || settled.parked.is_some()
3045 || settled.settled_at < pass.started_at
3046 || settled.settled_at > held_at
3047 || self.operator_decided_at.is_some_and(|at| at >= held_at)
3048 || !crate::daemon::compatible_run_instruction(run, self)
3049 {
3050 return false;
3051 }
3052 match &self.recovery_budget_hold {
3053 Some(hold) => {
3054 hold.run == run.id
3055 && hold.pass == pass.index
3056 && hold.held_at == held_at
3057 && hold.decision == self.operator_decided_at
3058 && &hold.admission == admission
3059 && (!hold.legacy
3060 || self
3061 .operator_decided_at
3062 .is_none_or(|at| at < pass.started_at))
3063 }
3064 None => {
3065 self.schema < RECOVERY_HOLD_SCHEMA
3066 && self
3067 .operator_decided_at
3068 .is_none_or(|at| at < pass.started_at)
3069 }
3070 }
3071 }
3072
3073 pub(crate) fn queue_repair(&mut self, receipt: &crate::repair_budget::Receipt) {
3074 self.stamp_schema();
3075 self.repair_grants.push(receipt.clone());
3076 self.status = TaskStatus::Queued;
3077 self.hold_source = None;
3078 self.hold_reason = None;
3079 self.held_at = None;
3080 self.recovery_budget_hold = None;
3081 self.reopen_hold = None;
3082 self.resume_override = Some(OperatorResume {
3083 question_id: String::new(),
3084 at: receipt.at,
3085 conductor_rehold: None,
3086 forced: true,
3087 pinned_run: Some(receipt.request.run.clone()),
3088 });
3089 }
3090
3091 fn snapshot_legacy_reopen_hold(&mut self) {
3094 if self.schema >= REOPEN_HOLD_SCHEMA || self.reopen_hold.is_some() {
3095 return;
3096 }
3097 let Some(event) = self.completion_history.last() else {
3098 return;
3099 };
3100 if event.action == CompletionAction::Reopen
3101 && self.status == TaskStatus::Held
3102 && self.hold_source == Some(HoldSource::Manual)
3103 && event.reason.is_some()
3104 && self.hold_reason == event.reason
3105 && let (Some(held_at), Some(decision)) = (self.held_at, self.operator_decided_at)
3106 && held_at >= event.at
3107 && decision >= event.at
3108 {
3109 self.reopen_hold = Some(ReopenHold {
3110 occurrence: event.occurrence.clone(),
3111 held_at,
3112 decision: Some(decision),
3113 legacy: true,
3114 });
3115 }
3116 }
3117
3118 pub(crate) fn held_by_reopen(
3121 &self,
3122 occurrence: &str,
3123 run: &str,
3124 legacy_confirmation: Option<&str>,
3125 ) -> bool {
3126 let Some(event) = self.completion_history.last() else {
3127 return false;
3128 };
3129 if self.status != TaskStatus::Held
3130 || self.hold_source != Some(HoldSource::Manual)
3131 || !self.blocked_by.is_empty()
3132 || self.resume_override.is_some()
3133 || self.fresh_start
3134 || event.action != CompletionAction::Reopen
3135 || event.occurrence != occurrence
3136 || event.run.as_ref().map(|r| r.id.as_str()) != Some(run)
3137 || event.reason.is_none()
3138 || self.hold_reason != event.reason
3139 {
3140 return false;
3141 }
3142 let (Some(held_at), Some(decided), Some(hold)) =
3143 (self.held_at, self.operator_decided_at, &self.reopen_hold)
3144 else {
3145 return false;
3146 };
3147 hold.occurrence == occurrence
3148 && hold.held_at == held_at
3149 && hold.decision == Some(decided)
3150 && if hold.legacy {
3151 legacy_confirmation == Some(format!("{held_at}/{decided}").as_str())
3152 } else {
3153 legacy_confirmation.is_none()
3154 }
3155 }
3156
3157 pub fn release(&mut self) {
3161 self.import_chat_notice();
3164 if self.hold_notice_cause.is_none()
3165 && matches!(self.status, TaskStatus::Held | TaskStatus::Blocked)
3166 {
3167 self.hold_notice_cause = Some(self.unresolved_hold_cause());
3168 }
3169 let refused_handover = self.status == TaskStatus::Held
3170 && self.hold_source == Some(HoldSource::Machine)
3171 && self.review_branch.is_some()
3172 && self
3173 .review_instruction
3174 .as_ref()
3175 .is_none_or(|i| *i == self.instruction);
3176 self.status = TaskStatus::Queued;
3177 self.held_at = None;
3178 self.attempts = 0;
3179 self.last_error = None;
3180 self.park_reason = None;
3181 self.hold_reason = None;
3184 self.hold_source = None;
3185 self.machine_hold_cause = None;
3186 self.disk_resume_run = None;
3187 self.disk_checked_at = None;
3188 self.diagnostic = None;
3189 self.blocked_by.clear();
3194 self.block_reason = None;
3195 self.blocked_from = None;
3196 if !refused_handover {
3200 self.review_branch = None;
3201 self.review_instruction = None;
3202 }
3203 self.fresh_start = false;
3204 }
3205}
3206
3207fn copy_new(dir: &Path, src: &Path, name: &str) -> Result<(String, PathBuf)> {
3211 use std::io::ErrorKind;
3212 let (stem, ext) = match name.rfind('.') {
3213 Some(i) if i > 0 => (&name[..i], &name[i..]),
3214 _ => (name, ""),
3215 };
3216 for n in 1u32.. {
3217 let candidate = if n == 1 {
3218 name.to_owned()
3219 } else {
3220 let suffix = format!("-{n}");
3221 let room = 64usize.saturating_sub(suffix.len() + ext.len());
3222 let stem: String = stem.chars().take(room).collect();
3223 format!("{stem}{suffix}{ext}")
3224 };
3225 if !crate::ask::valid_asset_name(&candidate) {
3226 bail!("no valid attachment name is left for `{name}`");
3227 }
3228 let path = dir.join(&candidate);
3229 match std::fs::OpenOptions::new()
3230 .write(true)
3231 .create_new(true)
3232 .open(&path)
3233 {
3234 Ok(mut out) => {
3235 let copied = std::fs::File::open(src)
3236 .and_then(|mut input| std::io::copy(&mut input, &mut out));
3237 if let Err(e) = copied {
3238 drop(out);
3239 let _ = std::fs::remove_file(&path);
3240 return Err(e).with_context(|| format!("copy {}", src.display()));
3241 }
3242 return Ok((candidate, path));
3243 }
3244 Err(e) if e.kind() == ErrorKind::AlreadyExists => continue,
3245 Err(e) => return Err(e).with_context(|| format!("create {}", path.display())),
3246 }
3247 }
3248 unreachable!("the counter never runs out")
3249}
3250
3251const TASK_LOCK_STALE: std::time::Duration = std::time::Duration::from_secs(10);
3254
3255pub(crate) struct TaskLock {
3258 path: PathBuf,
3259 token: String,
3260}
3261
3262fn owner_token() -> String {
3265 static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
3266 let n = COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3267 let mut r = crate::rng::SplitMix64::new(crate::rng::entropy() ^ n.rotate_left(32));
3268 format!("{}-{:016x}", std::process::id(), r.next_u64())
3269}
3270
3271fn break_marker(path: &Path, token: &str) -> PathBuf {
3274 let mut h: u64 = 0xcbf29ce484222325;
3275 for b in token.bytes() {
3276 h ^= u64::from(b);
3277 h = h.wrapping_mul(0x100000001b3);
3278 }
3279 let mut name = path.as_os_str().to_owned();
3280 name.push(format!(".break-{h:016x}"));
3281 PathBuf::from(name)
3282}
3283
3284fn older_than_stale(path: &Path) -> bool {
3285 std::fs::metadata(path)
3286 .and_then(|m| m.modified())
3287 .ok()
3288 .and_then(|t| t.elapsed().ok())
3289 .is_some_and(|age| age > TASK_LOCK_STALE)
3290}
3291
3292fn writer_may_be_gone(token: &str) -> bool {
3293 let Some(pid) = token
3294 .split_once('-')
3295 .and_then(|(pid, _)| pid.parse::<u32>().ok())
3296 else {
3297 return true;
3300 };
3301 if pid == std::process::id() {
3302 return false;
3303 }
3304 crate::proc::pid_status(pid) == Some(false)
3306}
3307
3308const MAX_MARKER_DEPTH: u8 = 3;
3312
3313fn take_marker(
3319 path: &Path,
3320 token: &str,
3321 depth: u8,
3322 retry: crate::lock_file::Retry,
3323) -> Option<(PathBuf, String)> {
3324 use std::io::Write;
3325 let marker = break_marker(path, token);
3326 for _ in 0..2 {
3327 match retry.create(&marker) {
3328 Ok(mut f) => {
3329 let mine = owner_token();
3330 if f.write_all(mine.as_bytes()).is_err() {
3331 drop(f);
3332 let _ = std::fs::remove_file(&marker);
3333 return None;
3334 }
3335 return Some((marker, mine));
3336 }
3337 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
3338 let judged = std::fs::read_to_string(&marker).ok();
3339 match judged.filter(|_| older_than_stale(&marker)) {
3340 Some(judged) if depth < MAX_MARKER_DEPTH => {
3341 remove_lock_if(&marker, &judged, true, depth + 1, retry)?;
3342 }
3343 _ => return None,
3344 }
3345 }
3346 Err(_) => return None,
3347 }
3348 }
3349 None
3350}
3351
3352fn remove_lock_if(
3357 path: &Path,
3358 token: &str,
3359 require_stale: bool,
3360 depth: u8,
3361 retry: crate::lock_file::Retry,
3362) -> Option<bool> {
3363 let (marker, mine) = take_marker(path, token, depth, retry)?;
3364 let still = std::fs::read_to_string(path).is_ok_and(|c| c == token)
3365 && (!require_stale || older_than_stale(path) && writer_may_be_gone(token));
3366 if still {
3367 let _ = std::fs::remove_file(path);
3368 }
3369 if depth >= MAX_MARKER_DEPTH {
3371 if std::fs::read_to_string(&marker).is_ok_and(|c| c == mine) {
3372 let _ = std::fs::remove_file(&marker);
3373 }
3374 } else {
3375 let _ = remove_lock_if(&marker, &mine, false, depth + 1, retry);
3376 }
3377 Some(still)
3378}
3379
3380#[cfg(test)]
3383fn break_stale(path: &Path, judged: &str) -> bool {
3384 break_stale_with(path, judged, crate::lock_file::Retry::new(None))
3385}
3386
3387fn break_stale_with(path: &Path, judged: &str, retry: crate::lock_file::Retry) -> bool {
3388 remove_lock_if(path, judged, true, 0, retry).unwrap_or(false)
3389}
3390
3391impl Drop for TaskLock {
3392 fn drop(&mut self) {
3393 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2);
3394 let retry = crate::lock_file::Retry::new(Some(deadline));
3395 loop {
3396 match remove_lock_if(&self.path, &self.token, false, 0, retry) {
3397 Some(_) => return,
3398 None if std::time::Instant::now() > deadline => return,
3399 None => std::thread::sleep(std::time::Duration::from_millis(5)),
3400 }
3401 }
3402 }
3403}
3404
3405#[derive(Debug, thiserror::Error)]
3406#[error("task changed during completion decision; reload and inspect it")]
3407pub(crate) struct CompletionSnapshotChanged;
3408
3409#[derive(Debug, Clone)]
3411pub struct Queue {
3412 root: PathBuf,
3413 ids: IdSource,
3414}
3415
3416fn validate_attachments(sources: &[PathBuf]) -> Result<Vec<(&PathBuf, &str)>> {
3417 let mut wanted = Vec::new();
3418 for src in sources {
3419 let name = src
3420 .file_name()
3421 .and_then(|n| n.to_str())
3422 .with_context(|| format!("`{}` has no usable file name", src.display()))?;
3423 if !crate::ask::valid_asset_name(name) {
3424 bail!(
3425 "attachment name `{name}` must match ^[A-Za-z0-9][A-Za-z0-9._-]{{0,63}}$ \
3426 with no `..`; rename the file and try again"
3427 );
3428 }
3429 if !src.is_file() {
3430 bail!("attachment `{}` is not a file", src.display());
3431 }
3432 wanted.push((src, name));
3433 }
3434 Ok(wanted)
3435}
3436
3437impl Queue {
3438 pub fn open() -> Self {
3440 Self::at(crate::run::home().join("queue"))
3441 }
3442
3443 pub fn at(root: PathBuf) -> Self {
3446 Self {
3447 root,
3448 ids: IdSource::new(new_id),
3449 }
3450 }
3451
3452 #[doc(hidden)]
3455 pub fn with_id_source(mut self, f: impl Fn() -> String + Send + Sync + 'static) -> Self {
3456 self.ids = IdSource::custom(f);
3457 self
3458 }
3459
3460 fn file_with(
3471 &self,
3472 task: &mut Task,
3473 hook: impl FnMut(&mut Task) -> Result<bool>,
3474 undo: impl FnMut(&mut Task),
3475 ) -> Result<()> {
3476 self.reserve_id(task, hook, undo, true)
3477 }
3478
3479 fn reserve_id(
3487 &self,
3488 task: &mut Task,
3489 mut hook: impl FnMut(&mut Task) -> Result<bool>,
3490 mut undo: impl FnMut(&mut Task),
3491 store: bool,
3492 ) -> Result<()> {
3493 let redraw_first = self.ids.is_custom() && task.attachments.is_empty();
3494 let initial = task.id.clone();
3495 self.ids
3496 .reserve((!redraw_first).then_some(initial.as_str()), "task", |id| {
3497 task.id = id.to_owned();
3498 let _lock = self.lock_task(&task.id)?;
3499 if path_exists(&self.path_of(&task.id))? || !hook(task)? {
3500 return Ok(false);
3501 }
3502 if store {
3503 if let Err(e) = self.write_record(task) {
3504 undo(task);
3505 return Err(e);
3506 }
3507 task.unfiled = false;
3508 }
3509 Ok(true)
3510 })?;
3511 Ok(())
3512 }
3513
3514 fn id_in_use(&self, id: &str, check_attachments: bool) -> Result<bool> {
3519 if path_exists(&self.lock_path(id))? || path_exists(&self.filing_reservation_path(id))? {
3520 return Ok(true);
3521 }
3522 Ok(check_attachments && path_exists(&self.attachments_dir(id))?)
3523 }
3524
3525 fn plain_filing_hook(&self, task: &Task) -> Result<bool> {
3529 Ok(!self.id_in_use(&task.id, task.attachments.is_empty())?)
3530 }
3531
3532 pub fn file_claimed(&self, task: &mut Task) -> Result<Claim> {
3535 let mut claim = None;
3536 self.file_with(
3537 task,
3538 |t| {
3539 if self.id_in_use(&t.id, true)? {
3540 return Ok(false);
3541 }
3542 claim = Some(self.claim(&t.id)?);
3543 Ok(true)
3544 },
3545 |_| {},
3546 )?;
3547 claim.context("claim missing after filing")
3548 }
3549
3550 pub fn root(&self) -> &Path {
3552 &self.root
3553 }
3554
3555 pub fn path_of(&self, id: &str) -> PathBuf {
3557 self.root.join(format!("{id}.json"))
3558 }
3559
3560 pub fn attachments_dir(&self, id: &str) -> PathBuf {
3563 self.root.join(format!("{id}.attachments"))
3564 }
3565
3566 pub fn attach(&self, task: &mut Task, sources: &[PathBuf]) -> Result<Vec<String>> {
3577 let wanted = validate_attachments(sources)?;
3578 if task.unfiled && task.attachments.is_empty() {
3579 let names = std::cell::RefCell::new(Vec::new());
3582 self.reserve_id(
3583 task,
3584 |t| {
3585 if self.id_in_use(&t.id, true)? {
3586 return Ok(false);
3587 }
3588 *names.borrow_mut() = self.copy_attachments(t, &wanted)?;
3589 Ok(true)
3590 },
3591 |_| {},
3592 false,
3593 )?;
3594 return Ok(names.into_inner());
3595 }
3596 self.copy_attachments(task, &wanted)
3597 }
3598
3599 fn copy_attachments(
3601 &self,
3602 task: &mut Task,
3603 wanted: &[(&PathBuf, &str)],
3604 ) -> Result<Vec<String>> {
3605 let dir = self.attachments_dir(&task.id);
3606 let existed = dir.is_dir();
3607 std::fs::create_dir_all(&dir).with_context(|| format!("create {}", dir.display()))?;
3608 let mut created: Vec<PathBuf> = Vec::new();
3609 let mut names = Vec::new();
3610 let mut copy_all = || -> Result<()> {
3611 for (src, name) in wanted {
3612 let (stored, path) = copy_new(&dir, src, name)?;
3613 created.push(path);
3614 names.push(stored);
3615 }
3616 Ok(())
3617 };
3618 if let Err(e) = copy_all() {
3619 for path in &created {
3620 let _ = std::fs::remove_file(path);
3621 }
3622 if !existed {
3623 let _ = std::fs::remove_dir(&dir);
3624 }
3625 return Err(e);
3626 }
3627 task.attachments.extend(names.iter().cloned());
3628 Ok(names)
3629 }
3630
3631 pub fn attach_and_put(&self, task: &mut Task, sources: &[PathBuf]) -> Result<Vec<String>> {
3642 if task.unfiled && task.attachments.is_empty() {
3643 return self.attach_and_file(task, sources);
3644 }
3645 let dir = self.attachments_dir(&task.id);
3646 let existed = dir.is_dir();
3647 let before = task.attachments.len();
3648 let names = self.attach(task, sources)?;
3649 if let Err(e) = self.put(task) {
3650 for name in &names {
3651 let _ = std::fs::remove_file(dir.join(name));
3652 }
3653 if !existed {
3654 let _ = std::fs::remove_dir(&dir);
3655 }
3656 task.attachments.truncate(before);
3657 return Err(e);
3658 }
3659 Ok(names)
3660 }
3661
3662 fn attach_and_file(&self, task: &mut Task, sources: &[PathBuf]) -> Result<Vec<String>> {
3666 let wanted = validate_attachments(sources)?;
3667 let before = task.attachments.len();
3668 let names = std::cell::RefCell::new(Vec::new());
3669 let result = self.file_with(
3670 task,
3671 |t| {
3672 if self.id_in_use(&t.id, true)? {
3673 return Ok(false);
3674 }
3675 *names.borrow_mut() = self.copy_attachments(t, &wanted)?;
3676 Ok(true)
3677 },
3678 |t| {
3679 let dir = self.attachments_dir(&t.id);
3680 for name in names.borrow().iter() {
3681 let _ = std::fs::remove_file(dir.join(name));
3682 }
3683 let _ = std::fs::remove_dir(&dir);
3685 t.attachments.truncate(before);
3686 },
3687 );
3688 result.map(|()| names.into_inner())
3689 }
3690
3691 pub fn attachment_paths(&self, task: &Task) -> Vec<PathBuf> {
3695 let dir = self.attachments_dir(&task.id);
3696 task.attachments
3697 .iter()
3698 .map(|n| {
3699 let p = dir.join(n);
3700 std::path::absolute(&p).unwrap_or(p)
3701 })
3702 .collect()
3703 }
3704
3705 pub fn put(&self, task: &mut Task) -> Result<()> {
3714 if task.unfiled {
3715 return self.file_with(task, |t| self.plain_filing_hook(t), |_| {});
3717 }
3718 let _lock = self.lock_task(&task.id)?;
3719 self.put_unlocked(task)
3720 }
3721
3722 pub fn create_new(&self, task: &mut Task) -> Result<bool> {
3727 let _lock = self.lock_task(&task.id)?;
3728 if path_exists(&self.path_of(&task.id))?
3729 || path_exists(&self.filing_reservation_path(&task.id))?
3730 {
3731 return Ok(false);
3732 }
3733 self.write_record(task)?;
3734 task.unfiled = false;
3735 Ok(true)
3736 }
3737
3738 fn filing_reservation_path(&self, id: &str) -> PathBuf {
3739 self.root.join(format!("{id}.filing-reservation"))
3740 }
3741
3742 pub(crate) fn reserve_unused_id(&self) -> Result<String> {
3747 let mut chosen = String::new();
3748 self.ids.reserve(None, "task", |id| {
3749 let _lock = self.lock_task(id)?;
3750 if path_exists(&self.path_of(id))?
3751 || path_exists(&self.tombstone_path(id))?
3752 || self.id_in_use(id, true)?
3753 {
3754 return Ok(false);
3755 }
3756 std::fs::File::create_new(self.filing_reservation_path(id))?.sync_all()?;
3757 chosen = id.to_owned();
3758 Ok(true)
3759 })?;
3760 Ok(chosen)
3761 }
3762
3763 pub(crate) fn file_with_exact_id(
3773 &self,
3774 task: &mut Task,
3775 sources: &[PathBuf],
3776 allow_clean_unfiled_attachments: bool,
3777 verify_attachments: impl FnOnce(&Task) -> Result<()>,
3778 ) -> Result<bool> {
3779 let wanted = validate_attachments(sources)?;
3780 let _lock = self.lock_task(&task.id)?;
3781 anyhow::ensure!(
3782 path_exists(&self.filing_reservation_path(&task.id))?,
3783 "task id {} has no durable filing reservation",
3784 task.id
3785 );
3786 if path_exists(&self.path_of(&task.id))? {
3787 return Ok(false);
3788 }
3789 anyhow::ensure!(
3791 !path_exists(&self.tombstone_path(&task.id))?,
3792 "reserved task {} was deleted; refusing to file it again",
3793 task.id
3794 );
3795 if path_exists(&self.lock_path(&task.id))? {
3796 bail!(
3797 "reserved task id {} is claimed; cannot finish filing",
3798 task.id
3799 );
3800 }
3801 let dir = self.attachments_dir(&task.id);
3802 if path_exists(&dir)? {
3803 if allow_clean_unfiled_attachments {
3804 std::fs::remove_dir_all(&dir)
3805 .with_context(|| format!("clean partial attachments {}", dir.display()))?;
3806 } else {
3807 bail!(
3808 "reserved task id {} already has an attachment directory",
3809 task.id
3810 );
3811 }
3812 }
3813 if !wanted.is_empty() {
3814 let before = task.attachments.len();
3815 let names = self.copy_attachments(task, &wanted)?;
3816 if let Err(e) = verify_attachments(task).and_then(|()| self.write_record(task)) {
3817 for name in &names {
3818 let _ = std::fs::remove_file(dir.join(name));
3819 }
3820 let _ = std::fs::remove_dir(&dir);
3821 task.attachments.truncate(before);
3822 return Err(e);
3823 }
3824 } else {
3825 verify_attachments(task)?;
3826 self.write_record(task)?;
3827 }
3828 task.unfiled = false;
3829 Ok(true)
3830 }
3831
3832 fn put_unlocked(&self, task: &mut Task) -> Result<()> {
3834 self.merge_stored(task);
3835 if let Some(boundary) = task.reassignments.last() {
3836 let stored = self.get(&task.id)?;
3837 anyhow::ensure!(
3838 task.reassignments == stored.reassignments
3839 && task.repo == stored.repo
3840 && task.runs.get(..boundary.run_boundary)
3841 == stored.runs.get(..boundary.run_boundary),
3842 "historical repository execution cannot be restarted; reload the task"
3843 );
3844 }
3845 self.write_record(task)
3846 }
3847
3848 pub(crate) fn commit_base_recovery(
3850 &self,
3851 task: &mut Task,
3852 expected: &serde_json::Value,
3853 ) -> Result<()> {
3854 let _lock = self.lock_task(&task.id)?;
3855 anyhow::ensure!(
3856 serde_json::to_value(self.get(&task.id)?)? == *expected,
3857 "task changed during base recovery; inspect the pending authorization"
3858 );
3859 self.put_unlocked(task)
3861 }
3862
3863 pub(crate) fn commit_land_sync_recovery(
3865 &self,
3866 task: &mut Task,
3867 expected: &serde_json::Value,
3868 ) -> Result<()> {
3869 let _lock = self.lock_task(&task.id)?;
3870 anyhow::ensure!(
3871 serde_json::to_value(self.get(&task.id)?)? == *expected,
3872 "task changed during landing base-sync recovery; inspect the pending authorization"
3873 );
3874 self.put_unlocked(task)
3875 }
3876
3877 pub(crate) fn commit_instruction_revision(
3879 &self,
3880 task: &mut Task,
3881 expected: &serde_json::Value,
3882 ) -> Result<()> {
3883 let _lock = self.lock_task(&task.id)?;
3884 anyhow::ensure!(
3885 serde_json::to_value(self.get(&task.id)?)? == *expected,
3886 "task changed during instruction revision; inspect the pending receipt"
3887 );
3888 self.put_unlocked(task)
3889 }
3890
3891 pub(crate) fn commit_repair_grant(
3892 &self,
3893 task: &mut Task,
3894 expected: &serde_json::Value,
3895 ) -> Result<()> {
3896 let _lock = self.lock_task(&task.id)?;
3897 anyhow::ensure!(
3898 serde_json::to_value(self.get(&task.id)?)? == *expected,
3899 "repair grant refused: task changed during admission"
3900 );
3901 self.write_record(task)
3902 .context(crate::repair_budget::PublicationUnknown)
3903 }
3904
3905 pub(crate) fn commit_disk_wait(&self, task: &mut Task, expected: &Task) -> Result<()> {
3907 let _lock = self.lock_task(&task.id)?;
3908 anyhow::ensure!(
3909 serde_json::to_value(self.get(&task.id)?)? == serde_json::to_value(expected)?,
3910 "task changed during disk monitoring"
3911 );
3912 task.stamp_schema();
3913 self.write_record_inner(task, false)
3914 }
3915
3916 pub(crate) fn commit_reassignment(&self, task: &mut Task, expected: &Task) -> Result<()> {
3918 let _lock = self.lock_task(&task.id)?;
3919 let stored = self.get(&task.id)?;
3920 anyhow::ensure!(
3921 serde_json::to_value(&stored)? == serde_json::to_value(expected)?
3922 && stored.reassignments.len() + 1 == task.reassignments.len()
3923 && stored.repo == task.reassignments.last().expect("new boundary").from
3924 && stored.runs == task.runs,
3925 "task changed during reassignment; retry after inspecting it"
3926 );
3927 self.write_record(task)
3928 }
3929
3930 pub(crate) fn commit_completion(&self, task: &mut Task, expected: &Task) -> Result<()> {
3932 let _lock = self.lock_task(&task.id)?;
3933 anyhow::ensure!(
3934 serde_json::to_value(self.get(&task.id)?)? == serde_json::to_value(expected)?,
3935 CompletionSnapshotChanged
3936 );
3937 self.write_record(task)
3938 }
3939
3940 fn merge_stored(&self, task: &mut Task) {
3942 if let Ok(mut stored) = read_path(&self.path_of(&task.id)) {
3943 stored.import_chat_notice();
3944 let local_decision = task.completion_history.iter().any(|event| {
3947 !stored
3948 .completion_history
3949 .iter()
3950 .any(|saved| saved.occurrence == event.occurrence)
3951 && event.at > stored.updated_at
3952 });
3953 let unseen_decision = stored.completion_history.iter().any(|event| {
3954 !task
3955 .completion_history
3956 .iter()
3957 .any(|mine| mine.occurrence == event.occurrence)
3958 });
3959 let mut history = std::mem::take(&mut stored.completion_history);
3960 for event in std::mem::take(&mut task.completion_history) {
3961 if !history
3962 .iter()
3963 .any(|stored| stored.occurrence == event.occurrence)
3964 {
3965 history.push(event);
3966 }
3967 }
3968 if unseen_decision {
3969 task.import_chat_notice();
3972 let mut stale = std::mem::replace(task, stored);
3973 append_missing(&mut task.answers, stale.answers);
3974 if task.reassignments == stale.reassignments {
3975 append_missing(&mut task.runs, stale.runs);
3976 }
3977 for (ledger, entries) in [
3978 (&mut task.decision_effects, stale.decision_effects),
3979 (&mut task.superseded_resumes, stale.superseded_resumes),
3980 (&mut task.dispatched_resumes, stale.dispatched_resumes),
3981 ] {
3982 for (key, value) in entries {
3983 ledger.entry(key).or_insert(value);
3984 }
3985 }
3986 append_missing(&mut task.actions_applied, stale.actions_applied);
3987 append_missing(&mut task.triage_applied, stale.triage_applied);
3988 append_missing(&mut task.chat_notices, stale.chat_notices);
3989 append_missing(
3990 &mut task.base_recovery_requests,
3991 stale.base_recovery_requests,
3992 );
3993 append_missing(
3994 &mut task.land_sync_recovery_requests,
3995 stale.land_sync_recovery_requests,
3996 );
3997 append_missing(
3998 &mut task.instruction_revision_requests,
3999 stale.instruction_revision_requests,
4000 );
4001 prepend_missing_by(&mut task.repair_grants, stale.repair_grants, |a, b| {
4004 a.request.request == b.request.request
4005 });
4006 prepend_missing_by(
4007 &mut task.repair_reconciliations,
4008 stale.repair_reconciliations,
4009 |a, b| a.request.request == b.request.request,
4010 );
4011 stale.resumption_history.extend(stale.resumption);
4014 stale.resumption_history.retain(|approval| {
4015 task.resumption
4016 .as_ref()
4017 .is_none_or(|r| r.at != approval.at || r.generation != approval.generation)
4018 });
4019 prepend_missing_by(
4020 &mut task.resumption_history,
4021 stale.resumption_history,
4022 |a, b| a.at == b.at && a.generation == b.generation,
4023 );
4024 for failure in stale.startup_failures {
4025 task.record_startup_failure(failure);
4026 }
4027 for pass in stale.passes {
4028 if !task.passes.iter().any(|stored| {
4029 stored.run == pass.run && stored.pass_index == pass.pass_index
4030 }) {
4031 task.passes.push(pass);
4032 }
4033 }
4034 task.completion_history = history;
4035 if !task.decision_effects.is_empty() {
4036 task.stamp_schema();
4037 }
4038 return;
4039 }
4040 if stored.reassignments.len() > task.reassignments.len() {
4041 let stale = std::mem::replace(task, stored.clone());
4044 for answer in stale.answers {
4045 if !task.answers.contains(&answer) {
4046 task.answers.push(answer);
4047 }
4048 }
4049 }
4050 if task.updated_at < stored.updated_at
4053 && (task.sync_only != stored.sync_only
4054 || stored.sync_only.is_some()
4055 || (task.reopen_hold.is_some() && task.reopen_hold != stored.reopen_hold)
4056 || stored
4057 .recovery_budget_hold
4058 .as_ref()
4059 .is_some_and(|hold| hold.held_at > task.updated_at)
4060 || stored.repair_grants.last().is_some_and(|grant| {
4061 task.repair_grants.last() != Some(grant)
4062 || stored.operator_decided_at > task.operator_decided_at
4063 || stored
4064 .resume_override
4065 .as_ref()
4066 .is_some_and(|pin| pin.at > task.updated_at)
4067 || (task.resume_override != stored.resume_override
4068 && task
4069 .resume_override
4070 .as_ref()
4071 .is_some_and(|pin| pin.at == grant.at))
4072 }))
4073 && task
4074 .operator_decided_at
4075 .is_none_or(|at| at <= stored.updated_at)
4076 && task
4077 .resume_override
4078 .as_ref()
4079 .is_none_or(|pin| pin.at <= stored.updated_at)
4080 && !local_decision
4081 {
4082 *task = stored.clone();
4083 }
4084 task.completion_history = history;
4085 append_missing(
4086 &mut task.base_recovery_requests,
4087 stored.base_recovery_requests,
4088 );
4089 append_missing(
4090 &mut task.land_sync_recovery_requests,
4091 stored.land_sync_recovery_requests,
4092 );
4093 append_missing(
4094 &mut task.instruction_revision_requests,
4095 stored.instruction_revision_requests,
4096 );
4097 append_missing(&mut task.actions_applied, stored.actions_applied);
4098 append_missing(&mut task.triage_applied, stored.triage_applied);
4099 for receipt in &stored.repair_grants {
4100 if !task
4101 .repair_grants
4102 .iter()
4103 .any(|r| r.request.request == receipt.request.request)
4104 {
4105 task.repair_grants.push(receipt.clone());
4107 }
4108 }
4109 for receipt in &stored.repair_reconciliations {
4110 if !task.repair_reconciliations.contains(receipt) {
4111 task.repair_reconciliations.push(receipt.clone());
4114 task.resume_override = stored.resume_override.clone();
4115 task.status = stored.status;
4116 task.hold_source = stored.hold_source;
4117 task.machine_hold_cause = stored.machine_hold_cause.clone();
4118 task.disk_resume_run = stored.disk_resume_run.clone();
4119 task.disk_checked_at = stored.disk_checked_at;
4120 task.hold_reason = stored.hold_reason.clone();
4121 task.held_at = stored.held_at;
4122 }
4123 }
4124 task.superseded_resumes.extend(stored.superseded_resumes);
4125 task.dispatched_resumes.extend(stored.dispatched_resumes);
4126 if task.status != TaskStatus::Running
4127 && let Some(pin) = &stored.resume_override
4128 && !pin.question_id.is_empty()
4129 && let Some(run) = &pin.pinned_run
4130 && task.resume_override.as_ref().is_none_or(|next| {
4131 next.question_id != pin.question_id || next.pinned_run != pin.pinned_run
4132 })
4133 {
4134 task.superseded_resumes
4135 .insert(pin.question_id.clone(), run.clone());
4136 }
4137 for (id, receipt) in stored.decision_effects {
4140 task.decision_effects.insert(id, receipt);
4141 }
4142 if !task.decision_effects.is_empty() {
4143 task.stamp_schema();
4144 }
4145 if task.chat.is_none() {
4148 task.chat = stored.chat.clone();
4149 }
4150 if task.issue.is_none() {
4151 task.issue = stored.issue.clone();
4152 }
4153 append_missing(&mut task.chat_notices, stored.chat_notices);
4154 task.chat_reservation = task.chat_reservation.max(stored.chat_reservation);
4155 for failure in stored.startup_failures {
4156 task.record_startup_failure(failure);
4157 }
4158 append_missing(&mut task.runs, stored.runs);
4159 for p in stored.passes {
4160 if !task
4161 .passes
4162 .iter()
4163 .any(|q| q.run == p.run && q.pass_index == p.pass_index)
4164 {
4165 task.passes.push(p);
4166 }
4167 }
4168 if let Some(n) = stored.chat_notice
4171 && task.chat_notice.as_ref().is_none_or(|mine| mine.at < n.at)
4172 {
4173 task.chat_notice = Some(n);
4174 }
4175 if task.landing.is_none()
4177 && let Some(note) = stored.landing
4178 && task.status == stored.status
4179 && task.instruction_rev == stored.instruction_rev
4180 && task.investigation == stored.investigation
4181 && task.execution_runs().last() == Some(¬e.run)
4182 {
4183 task.landing = Some(note);
4184 }
4185 }
4186 }
4187
4188 pub(crate) fn cache_landing(
4191 &self,
4192 observed: &Task,
4193 note: crate::landing::LandingNote,
4194 ) -> Result<()> {
4195 let Ok(_claim) = self.claim(&observed.id) else {
4196 return Ok(());
4197 };
4198 let _lock = self.lock_task(&observed.id)?;
4199 let mut task = self.get(&observed.id)?;
4200 if task.updated_at == observed.updated_at
4201 && task.status == observed.status
4202 && task.investigation == observed.investigation
4203 && task.instruction_rev == observed.instruction_rev
4204 && task.landing == observed.landing
4205 && task.repo == observed.repo
4206 && task.reassignments == observed.reassignments
4207 && (crate::landing::audited_run(&task) == Some(note.run.as_str())
4208 || crate::landing::awaiting_landing_run(&task) == Some(note.run.as_str()))
4209 {
4210 task.stamp_schema();
4211 task.landing = Some(note);
4212 self.write_startup_history(&task)?;
4213 }
4214 Ok(())
4215 }
4216
4217 pub(crate) fn write_startup_history(&self, task: &Task) -> Result<()> {
4220 let path = self.path_of(&task.id);
4221 let tmp = path.with_extension("json.tmp");
4222 std::fs::write(&tmp, serde_json::to_vec_pretty(task)?)?;
4223 std::fs::rename(tmp, path)?;
4224 Ok(())
4225 }
4226
4227 fn write_record(&self, task: &mut Task) -> Result<()> {
4229 self.write_record_inner(task, true)
4230 }
4231
4232 fn write_record_inner(&self, task: &mut Task, notify: bool) -> Result<()> {
4233 if task.investigation
4234 || task.completion_result.is_some()
4235 || task.instruction_rev > 0
4236 || task.landing.is_some()
4237 {
4238 task.stamp_schema();
4239 }
4240 task.import_chat_notice();
4241 if task.status != TaskStatus::Held && task.sync_only.is_none() {
4242 task.recovery_budget_hold = None;
4243 }
4244 task.updated_at = Timestamp::now();
4245 std::fs::create_dir_all(&self.root)
4246 .with_context(|| format!("create {}", self.root.display()))?;
4247 let body = serde_json::to_string_pretty(task).context("serialize task")?;
4248 let path = self.path_of(&task.id);
4249 let tmp = path.with_extension("json.tmp");
4250 std::fs::write(&tmp, &body).with_context(|| format!("write {}", tmp.display()))?;
4251 std::fs::rename(&tmp, &path).with_context(|| format!("replace {}", path.display()))?;
4252 if let (Some(notice), Some(home)) = (
4257 notify.then(|| crate::notices::task_held(task)).flatten(),
4258 self.root.parent().filter(|p| !p.as_os_str().is_empty()),
4259 ) {
4260 crate::notices::raise_in(home, notice);
4261 }
4262 Ok(())
4263 }
4264
4265 pub fn modify(&self, id: &str, f: impl FnOnce(&mut Task) -> bool) -> Result<bool> {
4270 let id = self.resolve_id(id)?;
4271 let _lock = self.lock_task(&id)?;
4272 let mut task = self.get(&id)?;
4273 if !f(&mut task) {
4274 return Ok(false);
4275 }
4276 self.put_unlocked(&mut task)?;
4277 Ok(true)
4278 }
4279
4280 pub fn link_run(&self, id: &str, run: &str) -> Result<Task> {
4285 let id = self.resolve_id(id)?;
4286 let _lock = self.lock_task(&id)?;
4289 let mut task = self.get(&id)?;
4290 if task.link_run(run) {
4291 self.put_unlocked(&mut task)?;
4292 }
4293 Ok(task)
4294 }
4295
4296 pub(crate) fn lock_task(&self, id: &str) -> Result<TaskLock> {
4304 std::fs::create_dir_all(&self.root)
4305 .with_context(|| format!("create {}", self.root.display()))?;
4306 let path = self.root.join(format!("{id}.write-lock"));
4307 let started = std::time::Instant::now();
4308 let retry = crate::lock_file::Retry::task_write(started + TASK_LOCK_STALE);
4309 let marker_retry = crate::lock_file::Retry::new(Some(started + TASK_LOCK_STALE));
4310 loop {
4311 match retry.create(&path) {
4312 Ok(mut file) => {
4313 use std::io::Write;
4314 let token = owner_token();
4315 if let Err(e) = file.write_all(token.as_bytes()) {
4316 drop(file);
4317 let _ = std::fs::remove_file(&path);
4318 return Err(e).with_context(|| format!("lock {}", path.display()));
4319 }
4320 return Ok(TaskLock { path, token });
4321 }
4322 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
4323 let judged = std::fs::read_to_string(&path).ok();
4326 let broken = judged
4327 .filter(|_| older_than_stale(&path))
4328 .is_some_and(|judged| break_stale_with(&path, &judged, marker_retry));
4329 if !broken {
4333 if started.elapsed() > TASK_LOCK_STALE {
4334 bail!("could not lock task {id}");
4335 }
4336 std::thread::sleep(std::time::Duration::from_millis(15));
4337 }
4338 }
4339 Err(e) => return Err(e).with_context(|| format!("lock {}", path.display())),
4340 }
4341 }
4342 }
4343
4344 pub fn get(&self, id: &str) -> Result<Task> {
4346 let resolved = self.resolve_id(id)?;
4347 read_path(&self.path_of(&resolved))
4348 }
4349
4350 pub fn remove(&self, id: &str, in_flight: bool, questions: &Questions) -> Result<Removal> {
4382 self.remove_with_receipt(id, in_flight, questions, None)
4383 }
4384
4385 pub(crate) fn discard_triage(
4387 &self,
4388 id: &str,
4389 questions: &Questions,
4390 inquiry: &str,
4391 ) -> Result<Removal> {
4392 self.remove_with_receipt(id, false, questions, Some(inquiry))
4393 }
4394
4395 pub(crate) fn triage_discard_applied(&self, id: &str, inquiry: &str) -> Result<bool> {
4396 let path = self
4397 .root
4398 .join("triage-discard")
4399 .join(format!("{inquiry}.json"));
4400 let bytes = match std::fs::read(path) {
4401 Ok(bytes) => bytes,
4402 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(false),
4403 Err(e) => return Err(e.into()),
4404 };
4405 let receipt: Task = serde_json::from_slice(&bytes)?;
4406 Ok(receipt.id == id && !self.path_of(id).exists())
4407 }
4408
4409 fn remove_with_receipt(
4410 &self,
4411 id: &str,
4412 in_flight: bool,
4413 questions: &Questions,
4414 inquiry: Option<&str>,
4415 ) -> Result<Removal> {
4416 let resolved = self.resolve_id(id)?;
4417 if in_flight {
4418 bail!("task {resolved} is being run by a live daemon right now");
4419 }
4420 let receipt = inquiry.map(|q| self.root.join("triage-discard").join(format!("{q}.json")));
4421 if let Some(path) = &receipt {
4422 std::fs::create_dir_all(path.parent().expect("receipt directory"))?;
4423 }
4424 self.write_tombstone(&resolved)?;
4425 if let Err(e) = self.remove_record_with_attachments(&resolved, |p| match &receipt {
4426 Some(path) => std::fs::rename(p, path),
4427 None => std::fs::remove_file(p),
4428 }) {
4429 if self.path_of(&resolved).exists() {
4433 let _ = std::fs::remove_file(self.tombstone_path(&resolved));
4434 }
4435 return Err(e);
4436 }
4437 let (released, still_blocked) = self.release_dependents_of(&resolved, questions);
4438 Ok(Removal {
4439 id: resolved,
4440 released,
4441 still_blocked,
4442 })
4443 }
4444
4445 fn tombstone_path(&self, id: &str) -> PathBuf {
4448 self.root.join(format!("{id}.removed"))
4449 }
4450
4451 fn write_tombstone(&self, id: &str) -> Result<()> {
4452 let path = self.tombstone_path(id);
4453 let tmp = self.root.join(format!("{id}.removed.tmp"));
4454 std::fs::write(&tmp, b"")
4455 .and_then(|()| std::fs::rename(&tmp, &path))
4456 .with_context(|| format!("write {}", path.display()))
4457 }
4458
4459 fn was_deleted(&self, id: &str) -> bool {
4463 self.tombstone_path(id).is_file() && !self.path_of(id).exists()
4464 }
4465
4466 pub fn apply_deleted_blockers(&self, task: &mut Task, questions: &Questions) -> Vec<String> {
4470 let deleted = deleted_blockers(self, questions, &task.blocked_by);
4471 deleted
4472 .into_iter()
4473 .filter(|id| task.dependency_deleted(id))
4474 .collect()
4475 }
4476
4477 pub fn note_dependency_deleted(&self, dependent: &Task, deleted: &str) {
4481 let Some(home) = self.root.parent().filter(|p| !p.as_os_str().is_empty()) else {
4482 return;
4483 };
4484 let ja = crate::lang::is_japanese(&crate::lang::of_repo(&dependent.repo));
4485 let waiting = dependent.status == TaskStatus::Blocked;
4486 let message = match (ja, waiting) {
4487 (true, false) => format!(
4488 "タスク {} は、待っていた {} が削除されたため待機を解除し、元の状態に戻しました",
4489 dependent.short(),
4490 short(deleted)
4491 ),
4492 (true, true) => format!(
4493 "タスク {} は、待っていた {} が削除されたため、残りの依存を待っています",
4494 dependent.short(),
4495 short(deleted)
4496 ),
4497 (false, false) => format!(
4498 "Task {} stopped waiting on {} because it was deleted, and returned to its previous state",
4499 dependent.short(),
4500 short(deleted)
4501 ),
4502 (false, true) => format!(
4503 "Task {} stopped waiting on {} because it was deleted, and is still waiting on its other dependencies",
4504 dependent.short(),
4505 short(deleted)
4506 ),
4507 };
4508 crate::notices::raise_in(
4509 home,
4510 crate::notices::Notice::info(
4511 &format!("unblocked:{}:{}", dependent.id, deleted),
4512 message,
4513 )
4514 .link(crate::notices::Link::Task {
4515 id: dependent.id.clone(),
4516 }),
4517 );
4518 }
4519
4520 fn release_dependents_of(
4525 &self,
4526 dependency: &str,
4527 questions: &Questions,
4528 ) -> (Vec<String>, Vec<String>) {
4529 let (mut released, mut still_blocked) = (Vec::new(), Vec::new());
4530 for listed in self.list() {
4531 if listed.status != TaskStatus::Blocked || !listed.blocked_by.iter().any(|b| {
4532 matches!(crate::queue::dependency(self, questions, b), Dependency::Deleted(id) if id == dependency)
4533 }) {
4534 continue;
4535 }
4536 let Ok(_claim) = self.claim(&listed.id) else {
4537 continue;
4538 };
4539 let Ok(mut task) = self.get(&listed.id) else {
4540 continue;
4541 };
4542 let references: Vec<String> = task.blocked_by.iter().filter(|id| {
4543 matches!(crate::queue::dependency(self, questions, id), Dependency::Deleted(full) if full == dependency)
4544 }).cloned().collect();
4545 if references.is_empty() {
4546 continue;
4547 }
4548 for reference in references {
4549 task.dependency_deleted(&reference);
4550 }
4551 if self.put(&mut task).is_err() {
4552 continue;
4553 }
4554 self.note_dependency_deleted(&task, dependency);
4555 if task.status == TaskStatus::Blocked {
4556 still_blocked.push(task.id.clone());
4557 } else {
4558 released.push(task.id.clone());
4559 }
4560 }
4561 (released, still_blocked)
4562 }
4563
4564 fn remove_record_with_attachments(
4568 &self,
4569 resolved: &str,
4570 remove_record: impl FnOnce(&Path) -> std::io::Result<()>,
4571 ) -> Result<()> {
4572 self.sweep_removed_attachments();
4579 let attachments = self.attachments_dir(resolved);
4580 let aside = self.root.join(format!("{resolved}.attachments.removing"));
4581 let moved = match std::fs::rename(&attachments, &aside) {
4582 Ok(()) => true,
4583 Err(e) if e.kind() == std::io::ErrorKind::NotFound => false,
4584 Err(e) => {
4585 return Err(e).with_context(|| format!("remove {}", attachments.display()));
4586 }
4587 };
4588 let path = self.path_of(resolved);
4589 if let Err(e) = remove_record(&path) {
4590 if moved {
4591 let _ = std::fs::rename(&aside, &attachments);
4592 }
4593 return Err(e).with_context(|| format!("remove {}", path.display()));
4594 }
4595 if moved {
4596 if let Err(e) = std::fs::remove_dir_all(&aside) {
4597 tracing::warn!("leftover attachments {}: {e}", aside.display());
4598 }
4599 }
4600 let lock = self.lock_path(resolved);
4601 if let Err(e) = std::fs::remove_file(&lock) {
4602 if e.kind() != std::io::ErrorKind::NotFound {
4603 return Err(e).with_context(|| format!("remove {}", lock.display()));
4604 }
4605 }
4606 Ok(())
4607 }
4608
4609 fn sweep_removed_attachments(&self) {
4615 let Ok(entries) = std::fs::read_dir(&self.root) else {
4616 return;
4617 };
4618 for entry in entries.flatten() {
4619 let name = entry.file_name();
4620 let name = name.to_string_lossy();
4621 let Some(id) = name.strip_suffix(".attachments.removing") else {
4622 continue;
4623 };
4624 if !self.path_of(id).exists() {
4627 if let Err(e) = std::fs::remove_dir_all(entry.path()) {
4628 tracing::warn!("leftover attachments {}: {e}", entry.path().display());
4629 }
4630 }
4631 }
4632 self.sweep_tombstones();
4633 }
4634
4635 fn sweep_tombstones(&self) {
4644 let Ok(entries) = std::fs::read_dir(&self.root) else {
4645 return;
4646 };
4647 let tasks = self.list();
4648 for entry in entries.flatten() {
4649 let name = entry.file_name();
4650 let name = name.to_string_lossy();
4651 let Some(id) = name.strip_suffix(".removed") else {
4652 continue;
4653 };
4654 if self.path_of(id).exists()
4655 || tasks.iter().any(|t| {
4656 t.blocked_by
4657 .iter()
4658 .any(|b| id.starts_with(b) || id.ends_with(b))
4659 })
4660 {
4661 continue;
4662 }
4663 let old = entry
4664 .metadata()
4665 .and_then(|m| m.modified())
4666 .ok()
4667 .and_then(|m| m.elapsed().ok())
4668 .is_some_and(|age| age >= TOMBSTONE_GRACE);
4669 if old {
4670 let _ = std::fs::remove_file(entry.path());
4671 }
4672 }
4673 }
4674
4675 fn lock_path(&self, id: &str) -> PathBuf {
4678 self.root.join(format!("{id}.lock"))
4679 }
4680
4681 pub fn list(&self) -> Vec<Task> {
4694 #[cfg(test)]
4695 LIST_READS.with(|count| count.set(count.get() + 1));
4696 let mut tasks: Vec<Task> = std::fs::read_dir(&self.root)
4697 .into_iter()
4698 .flatten()
4699 .flatten()
4700 .map(|e| e.path())
4701 .filter(|p| p.extension().is_some_and(|x| x == "json"))
4702 .filter_map(|p| read_path(&p).ok())
4703 .collect();
4704 tasks.sort_unstable_by(|a, b| b.priority.cmp(&a.priority).then_with(|| b.id.cmp(&a.id)));
4705 tasks
4706 }
4707
4708 pub fn unreadable(&self) -> Vec<PathBuf> {
4712 std::fs::read_dir(&self.root)
4713 .into_iter()
4714 .flatten()
4715 .flatten()
4716 .map(|e| e.path())
4717 .filter(|p| p.extension().is_some_and(|x| x == "json"))
4718 .filter(|p| read_path(p).is_err())
4719 .collect()
4720 }
4721
4722 pub fn superseded(&self) -> HashMap<String, String> {
4735 let mut by = HashMap::new();
4736 for task in self.list() {
4737 for earlier in &task.runs {
4738 if let Some(later) = task.successor_of(earlier) {
4739 by.insert(earlier.clone(), later.clone());
4740 }
4741 }
4742 }
4743 by
4744 }
4745
4746 pub fn superseded_by(&self, run: &str) -> Option<String> {
4754 for task in self.list() {
4755 if task.runs.iter().any(|r| r == run) {
4756 return task.successor_of(run).cloned();
4757 }
4758 }
4759 None
4760 }
4761
4762 pub fn latest_attempt(&self, run: &str) -> Option<String> {
4773 for task in self.list() {
4774 if task.runs.iter().any(|r| r == run) {
4775 return task.runs.last().filter(|last| **last != run).cloned();
4776 }
4777 }
4778 None
4779 }
4780
4781 pub fn next_runnable(&self) -> Option<Task> {
4786 let mut runnable: Vec<Task> = self
4787 .list()
4788 .into_iter()
4789 .filter(|t| t.status.runnable())
4790 .collect();
4791 runnable.sort_unstable_by(dispatch_order);
4792 runnable.into_iter().next()
4793 }
4794
4795 pub fn claim(&self, id: &str) -> Result<Claim> {
4802 let claim = self.claim_for_instruction_revision(id)?;
4803 if let Some(home) = self.root.parent()
4806 && let Ok(task) = self.get(id)
4807 && let Some(run) = task.execution_runs().last()
4808 && let Ok(state) = crate::run::RunState::load_under(run, home)
4809 && let Some(revision) = state.instruction_revisions.last()
4810 {
4811 anyhow::ensure!(
4812 task.instruction_revision_requests
4813 .contains(&revision.request),
4814 InstructionAdoptionPending
4815 );
4816 }
4817 Ok(claim)
4818 }
4819
4820 pub(crate) fn claim_for_instruction_revision(&self, id: &str) -> Result<Claim> {
4823 std::fs::create_dir_all(&self.root)
4824 .with_context(|| format!("create {}", self.root.display()))?;
4825 let path = self.lock_path(id);
4826 let retry = crate::lock_file::Retry::new(None);
4827 match retry.create(&path) {
4828 Ok(mut f) => {
4829 use std::io::Write as _;
4830 let _ = writeln!(f, "{}", std::process::id());
4832 Ok(Claim { path })
4833 }
4834 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
4835 bail!("task {id} is already claimed ({} exists)", path.display())
4836 }
4837 Err(e) => Err(e).with_context(|| format!("lock {}", path.display())),
4838 }
4839 }
4840
4841 #[must_use]
4844 pub fn is_claimed(&self, id: &str) -> bool {
4845 self.lock_path(id).exists()
4846 }
4847
4848 pub fn resolve_id(&self, prefix: &str) -> Result<String> {
4850 if !prefix.is_empty()
4851 && prefix != "."
4852 && prefix != ".."
4853 && !prefix.contains(['/', '\\'])
4854 && self.path_of(prefix).is_file()
4855 {
4856 return Ok(prefix.to_owned());
4857 }
4858 let ids = record_ids(&self.root, "json")?;
4859 match resolve_reference(prefix, ids.iter().map(String::as_str)) {
4860 Reference::Found(id) => Ok(id),
4861 Reference::Missing => bail!("no task matches `{prefix}`"),
4862 Reference::Ambiguous => bail!("`{prefix}` matches multiple tasks"),
4863 }
4864 }
4865
4866 pub fn revision(&self) -> u64 {
4873 self.revision_excluding(&std::collections::BTreeSet::new())
4874 }
4875
4876 pub fn revision_excluding(&self, skip: &std::collections::BTreeSet<String>) -> u64 {
4879 use std::hash::{Hash as _, Hasher as _};
4880
4881 let mut entries: Vec<(String, u64)> = std::fs::read_dir(&self.root)
4882 .into_iter()
4883 .flatten()
4884 .flatten()
4885 .filter(|e| e.path().extension().is_some_and(|ext| ext == "json"))
4886 .filter(|e| {
4887 let path = e.path();
4888 !path
4889 .file_stem()
4890 .is_some_and(|stem| skip.contains(stem.to_string_lossy().as_ref()))
4891 })
4892 .filter_map(|e| {
4893 let name = e.file_name().to_string_lossy().into_owned();
4894 let mtime = e
4895 .metadata()
4896 .ok()?
4897 .modified()
4898 .ok()?
4899 .duration_since(std::time::UNIX_EPOCH)
4900 .ok()?
4901 .as_millis() as u64;
4902 Some((name, mtime))
4903 })
4904 .collect();
4905
4906 if entries.is_empty() {
4907 return 0;
4908 }
4909
4910 entries.sort_unstable();
4911 let mut hasher = std::hash::DefaultHasher::new();
4912 for (name, mtime) in &entries {
4913 name.hash(&mut hasher);
4914 mtime.hash(&mut hasher);
4915 }
4916 let h = hasher.finish();
4917 if h == 0 { 1 } else { h }
4918 }
4919}
4920
4921const TOMBSTONE_GRACE: std::time::Duration = std::time::Duration::from_secs(3600);
4924
4925#[derive(Debug, Clone)]
4927pub struct Removal {
4928 pub id: String,
4930 pub released: Vec<String>,
4934 pub still_blocked: Vec<String>,
4937}
4938
4939#[derive(Debug, thiserror::Error)]
4940#[error("interrupted instruction adoption; replay the owner request before claiming the task")]
4941pub(crate) struct InstructionAdoptionPending;
4942
4943#[derive(Debug)]
4945pub struct Claim {
4946 path: PathBuf,
4947}
4948
4949impl Drop for Claim {
4950 fn drop(&mut self) {
4951 let _ = std::fs::remove_file(&self.path);
4952 }
4953}
4954
4955pub fn title_from(instruction: &str, max: usize) -> String {
4958 let Some(line) = first_line(instruction) else {
4959 return "(empty task)".to_owned();
4960 };
4961 if line.chars().count() <= max {
4962 return line.to_owned();
4963 }
4964 let head: String = line.chars().take(max.saturating_sub(1)).collect();
4965 format!("{head}…")
4966}
4967
4968pub(crate) fn first_line(instruction: &str) -> Option<&str> {
4974 let line = instruction
4975 .lines()
4976 .map(str::trim)
4977 .find(|l| !l.is_empty())?
4978 .trim_start_matches(['#', '-', '*', '>', ' '])
4979 .trim();
4980 (!line.is_empty()).then_some(line)
4981}
4982
4983#[cfg(test)]
4984thread_local! {
4985 pub(crate) static TASK_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4986}
4987
4988fn read_path(path: &Path) -> Result<Task> {
4989 #[cfg(test)]
4990 TASK_READS.with(|count| count.set(count.get() + 1));
4991 let body = std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;
4992 let mut task: Task =
4993 serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))?;
4994 if task.schema > SCHEMA {
5000 bail!(
5001 "task {} was written by a different magi (schema {}, this build \
5002 speaks {SCHEMA})",
5003 task.id,
5004 task.schema
5005 );
5006 }
5007 task.preserve_legacy_build_cache();
5008 task.snapshot_legacy_reopen_hold();
5009 if task.schema < 22
5010 && task.status == TaskStatus::Held
5011 && task.hold_source == Some(HoldSource::Machine)
5012 && task.resume_override.is_none()
5013 && task
5014 .hold_reason
5015 .as_deref()
5016 .is_some_and(crate::disk::is_gate_reason)
5017 {
5018 task.mark_disk_capacity();
5019 }
5020 Ok(task)
5021}
5022
5023#[derive(Debug, PartialEq, Eq)]
5026pub(crate) enum Reference {
5027 Found(String),
5028 Missing,
5029 Ambiguous,
5030}
5031
5032pub(crate) fn resolve_reference<'a>(id: &str, ids: impl Iterator<Item = &'a str>) -> Reference {
5033 let mut hits = Vec::new();
5034 for candidate in ids {
5035 if candidate == id {
5036 return Reference::Found(candidate.to_owned());
5037 }
5038 if candidate.starts_with(id) || candidate.ends_with(id) {
5039 hits.push(candidate);
5040 }
5041 }
5042 match hits.as_slice() {
5043 [] => Reference::Missing,
5044 [one] => Reference::Found((*one).to_owned()),
5045 _ => Reference::Ambiguous,
5046 }
5047}
5048
5049pub(crate) fn record_ids(root: &Path, extension: &str) -> Result<Vec<String>> {
5052 let entries = match std::fs::read_dir(root) {
5053 Ok(entries) => entries,
5054 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
5055 Err(e) => return Err(e.into()),
5056 };
5057 let mut ids = Vec::new();
5058 for entry in entries {
5059 let path = entry?.path();
5060 if path.extension().is_some_and(|e| e == extension)
5061 && let Some(id) = path.file_stem().and_then(|s| s.to_str())
5062 {
5063 ids.push(id.to_owned());
5064 }
5065 }
5066 Ok(ids)
5067}
5068
5069#[derive(Debug, PartialEq, Eq)]
5072pub enum Dependency {
5073 Task(String),
5075 Question(String),
5077 Deleted(String),
5079 Missing,
5081 Ambiguous,
5083 Unknown,
5085}
5086
5087pub fn dependency(queue: &Queue, questions: &Questions, id: &str) -> Dependency {
5089 let (Ok(tasks), Ok(qs), Ok(removed)) = (
5090 record_ids(queue.root(), "json"),
5091 record_ids(questions.root(), "json"),
5092 record_ids(queue.root(), "removed"),
5093 ) else {
5094 return Dependency::Unknown;
5095 };
5096 let mut ids = tasks
5099 .iter()
5100 .chain(qs.iter())
5101 .chain(removed.iter())
5102 .cloned()
5103 .collect::<Vec<_>>();
5104 ids.sort();
5105 ids.dedup();
5106 match resolve_reference(id, ids.iter().map(String::as_str)) {
5107 Reference::Found(id) if tasks.contains(&id) => Dependency::Task(id),
5108 Reference::Found(id) if qs.contains(&id) => Dependency::Question(id),
5109 Reference::Found(id) if queue.was_deleted(&id) => Dependency::Deleted(id),
5110 Reference::Found(_) => Dependency::Unknown,
5111 Reference::Missing => Dependency::Missing,
5112 Reference::Ambiguous => Dependency::Ambiguous,
5113 }
5114}
5115
5116pub fn normalize_blockers(queue: &Queue, questions: &Questions, ids: &mut [String]) {
5118 for id in ids {
5119 if let Dependency::Task(full) | Dependency::Question(full) | Dependency::Deleted(full) =
5120 dependency(queue, questions, id)
5121 {
5122 *id = full;
5123 }
5124 }
5125}
5126
5127pub fn dependency_facts(queue: &Queue, questions: &Questions) -> String {
5130 let inventory = crate::blockers::Inventory::load(queue, questions);
5131 let mut text = String::from(
5132 "Current authoritative queue (historical missing-task claims may be stale; unreadable or ambiguous references must keep waiting):\n",
5133 );
5134 match record_ids(queue.root(), "json") {
5135 Ok(ids) => {
5136 for id in ids {
5137 match queue.get(&id) {
5138 Ok(task) => text.push_str(&format!(
5139 "{}: {}; blocked_by={:?}; chain={:?}\n",
5140 task.id,
5141 task.status.as_str(),
5142 task.blocked_by,
5143 inventory.waits_on(&task)
5144 )),
5145 Err(_) => text.push_str(&format!("{id}: exists, state unreadable\n")),
5146 }
5147 }
5148 }
5149 Err(_) => text.push_str("Queue inventory unreadable: existence is unknown.\n"),
5150 }
5151 text
5152}
5153
5154pub fn missing_blockers(
5156 queue: &Queue,
5157 questions: &Questions,
5158 blocked_by: &[String],
5159) -> Vec<String> {
5160 blocked_by
5161 .iter()
5162 .filter(|id| dependency(queue, questions, id) == Dependency::Missing)
5163 .cloned()
5164 .collect()
5165}
5166
5167pub fn deleted_blockers(
5170 queue: &Queue,
5171 questions: &Questions,
5172 blocked_by: &[String],
5173) -> Vec<String> {
5174 blocked_by
5175 .iter()
5176 .filter(|id| matches!(dependency(queue, questions, id), Dependency::Deleted(_)))
5177 .cloned()
5178 .collect()
5179}
5180
5181pub fn missing_blocker_hold_reason(blocked_by: &[String], missing: &[String]) -> String {
5193 missing_blocker_hold_reason_in(blocked_by, missing, "en")
5194}
5195
5196pub fn missing_blocker_hold_reason_in(
5198 blocked_by: &[String],
5199 missing: &[String],
5200 language: &str,
5201) -> String {
5202 if crate::lang::is_japanese(language) {
5203 format!(
5204 "{} を待っていましたが、{} はディスク上に存在しません - `magi task triage` を参照",
5205 blocked_by.join(", "),
5206 missing.join(", "),
5207 )
5208 } else {
5209 format!(
5210 "blocked on {} but {} no longer exist(s) on disk - see `magi task triage`",
5211 blocked_by.join(", "),
5212 missing.join(", "),
5213 )
5214 }
5215}
5216
5217pub fn short(id: &str) -> &str {
5219 id.split('-').next_back().unwrap_or(id)
5220}
5221
5222fn new_id() -> String {
5223 let stamp = jiff::Zoned::now().strftime("%Y%m%d-%H%M%S");
5224 let seed = crate::rng::entropy();
5225 format!("{stamp}-{:04x}", (seed ^ (seed >> 32)) & 0xffff)
5226}
5227
5228#[cfg(test)]
5229mod tests {
5230 #[test]
5231 fn reassignment_clears_repository_bound_execution_selections() {
5232 let mut task = Task::new(
5233 "move".into(),
5234 "evidence".into(),
5235 "old".into(),
5236 Source::Human,
5237 );
5238 task.review_branch = Some("old-review".into());
5239 task.review_instruction = Some("old criteria".into());
5240 task.pr_recovery = Some(crate::pr_recovery::Selection {
5241 url: "https://example.invalid/pull/1".into(),
5242 branch: "old-pr".into(),
5243 head: "head".into(),
5244 source_head: None,
5245 source_run: None,
5246 source_proof: None,
5247 disposition: None,
5248 instruction: "old criteria".into(),
5249 approved_at: Timestamp::now(),
5250 });
5251 task.replacement = Some(crate::merge_decision::Replacement {
5252 question: "owner".into(),
5253 run: "old-run".into(),
5254 pr: "https://example.invalid/pull/1".into(),
5255 agent: "worker".into(),
5256 context: "evidence".into(),
5257 });
5258 task.resume_override = Some(OperatorResume {
5259 question_id: "old-question".into(),
5260 at: Timestamp::now(),
5261 conductor_rehold: None,
5262 forced: true,
5263 pinned_run: Some("old-run".into()),
5264 });
5265 task.interrupt = true;
5266 task.reassign_repository("new".into(), "test");
5267 assert!(task.review_branch.is_none());
5268 assert!(task.review_instruction.is_none());
5269 assert!(task.pr_recovery.is_none());
5270 assert!(task.replacement.is_none());
5271 assert!(task.resume_override.is_none());
5272 assert!(!task.interrupt);
5273 assert!(task.fresh_start);
5274 assert_eq!(task.instruction, "evidence");
5275 }
5276
5277 #[test]
5278 fn explicit_resumption_is_not_invented_for_legacy_or_automatic_release() {
5279 let t = Task::new(
5280 "retry".into(),
5281 "do it".into(),
5282 PathBuf::from("."),
5283 Source::Human,
5284 );
5285 let mut value = serde_json::to_value(&t).unwrap();
5286 for field in ["resumption", "resumption_history", "operator_decided_at"] {
5287 value.as_object_mut().unwrap().remove(field);
5288 }
5289 value["schema"] = serde_json::json!(15);
5290 let mut legacy: Task = serde_json::from_value(value).unwrap();
5291 legacy.hold_machine(Some("automatic retry".into()));
5292 legacy.release();
5293 assert!(legacy.resumption.is_none());
5294 assert!(legacy.resumption_history.is_empty());
5295 assert!(legacy.operator_decided_at.is_none());
5296 legacy.release_operator("cli", None);
5297 legacy.start("run".into());
5298 let reloaded: Task =
5299 serde_json::from_str(&serde_json::to_string(&legacy).unwrap()).unwrap();
5300 assert!(reloaded.resume_override.is_none());
5301 assert_eq!(reloaded.resumption.as_ref().unwrap().generation, 1);
5302 }
5303
5304 #[test]
5305 fn merge_over_lets_the_later_choice_win_and_keeps_the_rest() {
5306 let mut base = RunOverrides {
5307 merge: Some("pr".to_owned()),
5308 candidates: Some(3),
5309 ..RunOverrides::default()
5310 };
5311 base.merge_over(&RunOverrides {
5312 merge: Some("none".to_owned()),
5313 seed: Some(7),
5314 ..RunOverrides::default()
5315 });
5316 assert_eq!(base.merge.as_deref(), Some("none"));
5317 assert_eq!(base.candidates, Some(3));
5318 assert_eq!(base.seed, Some(7));
5319 }
5320
5321 #[test]
5322 fn an_already_landed_task_is_done_with_its_attempt_refunded() {
5323 let mut t = task("relanded");
5324 t.attempts = 1;
5325 t.status = TaskStatus::Running;
5326 t.already_landed("already in main as 0e368de", completion(&t));
5327 assert_eq!(t.status, TaskStatus::Done);
5328 assert_eq!(t.attempts, 0);
5329 assert!(t.hold_reason.is_none());
5330 assert_eq!(t.last_error.as_deref(), Some("already in main as 0e368de"));
5331 }
5332
5333 #[test]
5334 fn missing_blocker_reason_follows_the_language() {
5335 let b = vec!["a".to_owned()];
5336 let en = missing_blocker_hold_reason_in(&b, &b, "en");
5337 assert_eq!(en, missing_blocker_hold_reason(&b, &b));
5338 assert!(en.starts_with("blocked on a"));
5339 assert!(missing_blocker_hold_reason_in(&b, &b, "ja").contains("存在しません"));
5340 assert_eq!(missing_blocker_hold_reason_in(&b, &b, "de"), en);
5341 }
5342
5343 use super::*;
5344
5345 fn completion(task: &Task) -> CompletionContext {
5346 CompletionContext::new(CompletionActor::Cli, None, Path::new("."), task)
5347 }
5348
5349 #[test]
5350 fn completion_retains_the_hold_dependency_and_failure_it_clears() {
5351 let mut held = task("held evidence");
5352 held.hold_manual(Some("owner approval required".into()));
5353 held.last_error = Some("review budget exhausted".into());
5354 held.succeed(completion(&held));
5355 let event = held.completion_history.last().unwrap();
5356 assert_eq!(event.prior_status, TaskStatus::Held);
5357 assert_eq!(
5358 event.prior_hold_reason.as_deref(),
5359 Some("owner approval required")
5360 );
5361 assert_eq!(
5362 event.prior_error.as_deref(),
5363 Some("review budget exhausted")
5364 );
5365 assert!(held.hold_reason.is_none());
5366 assert!(held.last_error.is_none());
5367 let mut blocked = task("dependency evidence");
5368 blocked.block(
5369 vec!["dependency".into()],
5370 Some("waiting on migration".into()),
5371 );
5372 blocked.succeed(completion(&blocked));
5373 let event = blocked.completion_history.last().unwrap();
5374 assert_eq!(event.prior_status, TaskStatus::Blocked);
5375 assert_eq!(
5376 event.prior_block_reason.as_deref(),
5377 Some("waiting on migration")
5378 );
5379 assert!(blocked.block_reason.is_none());
5380 assert!(blocked.blocked_by.is_empty());
5381 let saved = serde_json::to_vec(&held).unwrap();
5382 let restored: Task = serde_json::from_slice(&saved).unwrap();
5383 assert_eq!(restored.completion_history, held.completion_history);
5384 }
5385
5386 #[test]
5387 fn completion_audit_is_append_only_under_stale_puts() {
5388 let dir = tempfile::tempdir().unwrap();
5389 let queue = Queue::at(dir.path().join("queue"));
5390 let mut current = task("audited");
5391 current.hold_manual(Some("inspect".into()));
5392 queue.put(&mut current).unwrap();
5393 let mut stale = queue.get(¤t.id).unwrap();
5394 current.succeed(completion(¤t));
5395 queue.put(&mut current).unwrap();
5396 let original = current.completion_history[0].clone();
5397 stale.last_error = Some("stale control state".into());
5398 queue.put(&mut stale).unwrap();
5399 assert_eq!(stale.status, TaskStatus::Done);
5400 assert_eq!(stale.completion_history, vec![original.clone()]);
5401 let mut context = completion(¤t);
5402 context.reason = Some("not actually finished".into());
5403 current.reopen(context).unwrap();
5404 queue.put(&mut current).unwrap();
5405 stale.completion_history[0].actor = CompletionActor::Web;
5406 stale.completion_history[0].reason = Some("rewritten evidence".into());
5407 queue.put(&mut stale).unwrap();
5408 assert_eq!(stale.status, TaskStatus::Held);
5409 assert_eq!(stale.hold_reason.as_deref(), Some("not actually finished"));
5410 assert_eq!(stale.completion_history[0], original);
5411 assert_eq!(stale.completion_history, current.completion_history);
5412 }
5413
5414 #[test]
5415 fn a_writer_missing_a_reopen_contributes_receipts_but_not_authority() {
5416 let (_dir, q) = queue();
5417 let mut current = task("durable receipts");
5418 q.put(&mut current).unwrap();
5419 let mut stale = current.clone();
5420 let grant: crate::repair_budget::Receipt = serde_json::from_value(serde_json::json!({
5421 "request": {
5422 "task": current.id, "run": "old-run", "kind": "gate", "rounds": 1,
5423 "head": "old-head", "expect_pass": 0, "request": "old-grant", "reason": "retry"
5424 },
5425 "at": stale.updated_at, "contract": "old-contract"
5426 }))
5427 .unwrap();
5428 stale.release_operator("triage", Some("triage-question"));
5429 stale.queue_repair(&grant);
5430 let reconciliation: crate::repair_budget::reconcile::Receipt =
5431 serde_json::from_value(serde_json::json!({
5432 "request": {
5433 "task": current.id, "run": "old-run", "head": "old-head", "expect_pass": 0,
5434 "receipt": "old-grant", "question": "triage-question", "answer_at": grant.at,
5435 "request": "reconciliation", "reason": "retain the answer"
5436 },
5437 "grant": grant, "source": "answer", "application": "release",
5438 "decision": grant.at, "superseded_questions": []
5439 }))
5440 .unwrap();
5441 stale.repair_reconciliations.push(reconciliation.clone());
5442 stale.triage_applied.push("triage-question".into());
5443 stale.actions_applied.push("choice".into());
5444 stale.base_recovery_requests.push("base-request".into());
5445 stale.chat_notices.push("delivery".into());
5446 stale.chat_notice = Some(ChatNotice {
5447 key: "other-delivery".into(),
5448 at: grant.at,
5449 outcome: ChatNoticeOutcome::Posted,
5450 });
5451 for ledger in [
5452 &mut stale.decision_effects,
5453 &mut stale.dispatched_resumes,
5454 &mut stale.superseded_resumes,
5455 ] {
5456 ledger.insert("shared".into(), "stale".into());
5457 ledger.insert("only-stale".into(), "receipt".into());
5458 }
5459
5460 let mut latest_grant = grant.clone();
5461 latest_grant.request.request = "new-grant".into();
5462 current.queue_repair(&latest_grant);
5463 for ledger in [
5464 &mut current.decision_effects,
5465 &mut current.dispatched_resumes,
5466 &mut current.superseded_resumes,
5467 ] {
5468 ledger.insert("shared".into(), "committed".into());
5469 }
5470 current.succeed(completion(¤t));
5471 let mut context = completion(¤t);
5472 context.reason = Some("inspect again".into());
5473 current.reopen(context).unwrap();
5474 q.put(&mut current).unwrap();
5475
5476 for _ in 0..2 {
5477 q.put(&mut stale.clone()).unwrap();
5478 let saved = q.get(¤t.id).unwrap();
5479 assert_eq!(saved.status, TaskStatus::Held);
5480 assert_eq!(saved.hold_reason, current.hold_reason);
5481 assert_eq!(saved.operator_decided_at, current.operator_decided_at);
5482 assert_eq!(saved.completion_history, current.completion_history);
5483 assert!(saved.resume_override.is_none());
5484 assert!(saved.resumption.is_none());
5485 assert_eq!(
5486 saved.resumption_history,
5487 [stale.resumption.clone().unwrap()]
5488 );
5489 assert_eq!(saved.triage_applied, ["triage-question"]);
5490 assert_eq!(saved.actions_applied, ["choice"]);
5491 assert_eq!(saved.base_recovery_requests, ["base-request"]);
5492 assert_eq!(saved.chat_notices, ["delivery", "other-delivery"]);
5493 assert_eq!(saved.repair_grants, [grant.clone(), latest_grant.clone()]);
5494 assert_eq!(
5495 saved.repair_reconciliations,
5496 std::slice::from_ref(&reconciliation)
5497 );
5498 for ledger in [
5499 saved.decision_effects,
5500 saved.dispatched_resumes,
5501 saved.superseded_resumes,
5502 ] {
5503 assert_eq!(ledger["shared"], "committed");
5504 assert_eq!(ledger["only-stale"], "receipt");
5505 }
5506 }
5507 }
5508
5509 #[test]
5510 fn repeated_completion_only_notifies_for_new_occurrences() {
5511 let mut task = chat_task();
5512 task.succeed(completion(&task));
5513 let first = task.chat_notice_key().unwrap();
5514 task.chat_notices.push(first.clone());
5515 task.succeed(completion(&task));
5516 assert_eq!(task.completion_history.len(), 1, "idempotent while done");
5517 assert_eq!(task.chat_notice_due(), None);
5518 let mut context = completion(&task);
5519 context.reason = Some("inspect".into());
5520 task.reopen(context).unwrap();
5521 task.succeed(completion(&task));
5522 let second = task.chat_notice_key().unwrap();
5523 assert_ne!(first, second);
5524 assert_eq!(task.chat_notice_due(), Some(second));
5525 assert_eq!(task.completion_history.len(), 3);
5526 }
5527
5528 #[test]
5529 fn old_tasks_have_unknown_completion_provenance_not_invented_events() {
5530 let mut task = task("legacy");
5531 task.status = TaskStatus::Done;
5532 let mut value = serde_json::to_value(&task).unwrap();
5533 value.as_object_mut().unwrap().remove("completion_history");
5534 let task: Task = serde_json::from_value(value).unwrap();
5535 assert!(task.completion_history.is_empty());
5536 assert_eq!(task.chat_notice_key().as_deref(), Some("done"));
5537 }
5538
5539 #[test]
5540 fn triage_applied_survives_release_and_old_records_read_as_empty() {
5541 let mut t = Task::new(
5542 "t".to_owned(),
5543 "i".to_owned(),
5544 PathBuf::from("r"),
5545 Source::Human,
5546 );
5547 t.mark_triage_applied("q1");
5548 t.mark_triage_applied("q1");
5549 t.hold_machine(Some("x".to_owned()));
5550 t.release();
5551 assert_eq!(t.triage_applied, ["q1"]);
5552 assert!(t.triage_applied("q1") && !t.triage_applied("q2"));
5553
5554 let mut v = serde_json::to_value(&t).unwrap();
5555 v.as_object_mut().unwrap().remove("triage_applied");
5556 let old: Task = serde_json::from_value(v).unwrap();
5557 assert!(old.triage_applied.is_empty());
5558 }
5559
5560 #[test]
5561 fn task_counts_of_empty_is_all_zero() {
5562 assert_eq!(TaskCounts::of(&[]), TaskCounts::default());
5563 }
5564
5565 #[test]
5566 fn task_counts_of_tallies_every_status() {
5567 let mut queued = Task::new(
5568 "q".to_owned(),
5569 "i".to_owned(),
5570 PathBuf::from("."),
5571 Source::Human,
5572 );
5573 queued.status = TaskStatus::Queued;
5574 let mut running = queued.clone();
5575 running.status = TaskStatus::Running;
5576 let mut done = queued.clone();
5577 done.status = TaskStatus::Done;
5578 let mut failed = queued.clone();
5579 failed.status = TaskStatus::Failed;
5580 let mut held = queued.clone();
5581 held.status = TaskStatus::Held;
5582 let mut blocked = queued.clone();
5583 blocked.status = TaskStatus::Blocked;
5584
5585 let mut parked = queued.clone();
5586 parked.status = TaskStatus::Parked;
5587
5588 let counts = TaskCounts::of(&[
5589 queued,
5590 running,
5591 done.clone(),
5592 done,
5593 failed,
5594 held,
5595 blocked,
5596 parked,
5597 ]);
5598 assert_eq!(
5599 counts,
5600 TaskCounts {
5601 queued: 1,
5602 running: 1,
5603 done: 2,
5604 failed: 1,
5605 held: 1,
5606 blocked: 1,
5607 parked: 1,
5608 }
5609 );
5610 }
5611
5612 #[test]
5613 fn task_implementers_persist_normalized_without_losing_history() {
5614 let (_dir, q) = queue();
5615 let mut t = task("keep me");
5616 t.hold_manual(Some("waiting".into()));
5617 t.runs.push("earlier-run".into());
5618 t.attachments.push("reference.txt".into());
5619 let cfg: crate::config::Config =
5620 toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
5621 .unwrap();
5622 q.put(&mut t).unwrap();
5623 let original = serde_json::to_value(&t).unwrap();
5624 for n in [2, 1, 2] {
5625 t.set_implementers(n, &cfg).unwrap();
5626 q.put(&mut t).unwrap();
5627 t = q.get(&t.id).unwrap();
5628 assert_eq!(t.implementers(), Some(usize::from(n)));
5629 assert_eq!(t.solo, n == 1);
5630 if n == 1 {
5631 assert!(t.overrides.is_none());
5632 }
5633 let mut actual = serde_json::to_value(&t).unwrap();
5634 for field in ["solo", "overrides", "updated_at"] {
5635 actual[field] = original[field].clone();
5636 }
5637 assert_eq!(actual, original);
5638 }
5639 t.overrides.as_mut().unwrap().judges = Some(2);
5640 t.set_implementers(1, &cfg).unwrap();
5641 assert_eq!(t.overrides.as_ref().unwrap().judges, Some(2));
5642 assert_eq!(t.overrides.as_ref().unwrap().candidates, None);
5643 }
5644
5645 #[test]
5646 fn task_implementers_old_records_keep_inheritance_until_changed() {
5647 let mut value = serde_json::to_value(task("old task")).unwrap();
5648 value.as_object_mut().unwrap().remove("solo");
5649 value.as_object_mut().unwrap().remove("overrides");
5650 let mut old: Task = serde_json::from_value(value).unwrap();
5651 assert_eq!(old.implementers(), None);
5652 old.set_implementers(1, &crate::config::Config::default())
5653 .unwrap();
5654 assert!(old.solo);
5655 assert!(old.overrides.is_none());
5656 }
5657
5658 #[test]
5659 fn task_implementers_reject_invalid_counts_and_states() {
5660 let cfg = crate::config::Config::default();
5661 let mut t = task("unchanged");
5662 for n in [0, 4, 255] {
5663 assert!(t.set_implementers(n, &cfg).is_err());
5664 }
5665 for status in [
5666 TaskStatus::Running,
5667 TaskStatus::Done,
5668 TaskStatus::Failed,
5669 TaskStatus::Blocked,
5670 TaskStatus::Parked,
5671 ] {
5672 t.status = status;
5673 let before = serde_json::to_value(&t).unwrap();
5674 assert!(t.set_implementers(1, &cfg).is_err());
5675 assert_eq!(serde_json::to_value(&t).unwrap(), before);
5676 }
5677 }
5678
5679 fn queue() -> (tempfile::TempDir, Queue) {
5682 let dir = tempfile::tempdir().unwrap();
5683 let q = Queue::at(dir.path().join("queue"));
5684 (dir, q)
5685 }
5686
5687 #[test]
5688 fn base_recovery_commit_retains_decision_and_superseded_resume_evidence() {
5689 let (_dir, q) = queue();
5690 let mut original = task("base recovery");
5691 original
5692 .decision_effects
5693 .insert("old-effect".into(), "receipt".into());
5694 original
5695 .dispatched_resumes
5696 .insert("dispatched".into(), "prior-run".into());
5697 original.resume_override = Some(OperatorResume {
5698 question_id: "prior-decision".into(),
5699 at: Timestamp::now(),
5700 conductor_rehold: None,
5701 forced: true,
5702 pinned_run: Some("retained-run".into()),
5703 });
5704 q.put(&mut original).unwrap();
5705 let expected = serde_json::to_value(&original).unwrap();
5706 let mut recovered = original.clone();
5707 recovered.base_recovery_requests.push("chat/request".into());
5708 recovered
5709 .resume_override
5710 .as_mut()
5711 .unwrap()
5712 .question_id
5713 .clear();
5714 q.commit_base_recovery(&mut recovered, &expected).unwrap();
5715 let saved = q.get(&original.id).unwrap();
5716 assert_eq!(saved.decision_effects, original.decision_effects);
5717 assert_eq!(saved.dispatched_resumes, original.dispatched_resumes);
5718 assert_eq!(
5719 saved
5720 .superseded_resumes
5721 .get("prior-decision")
5722 .map(String::as_str),
5723 Some("retained-run")
5724 );
5725 assert_eq!(saved.base_recovery_requests, ["chat/request"]);
5726 assert!(saved.resume_override.unwrap().question_id.is_empty());
5727 assert!(q.commit_base_recovery(&mut recovered, &expected).is_err());
5728 }
5729
5730 #[test]
5731 fn a_stale_write_does_not_drop_the_recorded_task_chat() {
5732 let (_dir, q) = queue();
5733 let mut stale = task("chat");
5734 q.put(&mut stale).unwrap();
5735 let mut fresh = q.get(&stale.id).unwrap();
5736 fresh.chat = Some("talk-1".to_owned());
5737 q.put(&mut fresh).unwrap();
5738 q.put(&mut stale).unwrap();
5739 assert_eq!(q.get(&stale.id).unwrap().chat.as_deref(), Some("talk-1"));
5740 }
5741
5742 #[test]
5743 fn putting_a_machine_held_task_files_a_notification_beside_the_queue() {
5744 let dir = tempfile::tempdir().unwrap();
5745 let q = Queue::at(dir.path().join("queue"));
5746 let mut t = task("held");
5747 q.put(&mut t).unwrap();
5748 assert_eq!(
5749 crate::notices::Notices::at(dir.path().join("notifications"))
5750 .list()
5751 .len(),
5752 0
5753 );
5754 t.hold_machine(Some("out of attempts".to_owned()));
5755 q.put(&mut t).unwrap();
5756 let listed = crate::notices::Notices::at(dir.path().join("notifications")).list();
5757 assert_eq!(listed.len(), 1);
5758 assert!(listed[0].message.contains("out of attempts"));
5759 }
5760
5761 #[test]
5762 fn start_consumes_the_disk_resume_pin() {
5763 let mut t = task("pin");
5764 t.disk_resume_run = Some("run-1".into());
5765 t.start("run-1".into());
5766 assert!(t.disk_resume_run.is_none());
5767 }
5768
5769 fn task(title: &str) -> Task {
5770 Task::new(
5771 title.to_owned(),
5772 format!("do {title}"),
5773 PathBuf::from("."),
5774 Source::Human,
5775 )
5776 }
5777
5778 #[test]
5779 fn issue_provenance_survives_queue_round_trip_without_inventing_chat() {
5780 let dir = tempfile::tempdir().unwrap();
5781 let q = Queue::at(dir.path().to_path_buf());
5782 let issue = IssueRef {
5783 number: 42,
5784 repo: "owner/repo".into(),
5785 };
5786 for source in [
5787 Source::Human,
5788 Source::Agent {
5789 run: "20260101-010101-abcd".into(),
5790 node: CHAT_NODE.into(),
5791 },
5792 ] {
5793 let mut t = task("issue");
5794 t.source = source;
5795 t.issue = Some(issue.clone());
5796 q.put(&mut t).unwrap();
5797 let saved = q.get(&t.id).unwrap();
5798 assert_eq!(saved.issue_ref(), Some(issue.clone()));
5799 assert_eq!(saved.source, t.source);
5800 assert_eq!(saved.filed_by_chat(), t.filed_by_chat());
5801 assert_eq!(saved.chat_talk(), t.filed_by_chat());
5802 if saved.source == Source::Human {
5803 assert_eq!(saved.source_label(), "issue #42");
5804 } else {
5805 assert!(saved.source_label().contains("issue #42"));
5806 }
5807 let mut stale = saved;
5808 stale.issue = None;
5809 q.put(&mut stale).unwrap();
5810 assert_eq!(q.get(&t.id).unwrap().issue_ref(), Some(issue.clone()));
5811 }
5812 let mut old = serde_json::to_value(task("legacy")).unwrap();
5813 old["schema"] = serde_json::json!(26);
5814 old["source"] = serde_json::json!({"kind":"issue","number":42,"repo":"owner/repo"});
5815 let legacy: Task = serde_json::from_value(old).unwrap();
5816 assert_eq!(legacy.issue_ref(), Some(issue));
5817 assert_eq!(legacy.filed_by_chat(), None);
5818 assert_eq!(legacy.chat_talk(), None);
5819 assert_eq!(legacy.source_label(), "issue #42");
5820 }
5821
5822 #[test]
5823 fn attempt_limit_inherits_old_records_and_controls_failure() {
5824 let mut t = task("budget");
5825 let mut old = serde_json::to_value(&t).unwrap();
5826 old.as_object_mut().unwrap().remove("attempt_limit");
5827 old["schema"] = serde_json::json!(15);
5828 let legacy: Task = serde_json::from_value(old).unwrap();
5829 assert_eq!(legacy.attempt_limit, None);
5830 assert_eq!(legacy.effective_attempt_limit(2), 2);
5831 t.attempts = 2;
5832 t.change_attempt_limit(NonZeroUsize::new(3)).unwrap();
5833 t.fail("retry", 1);
5834 assert_eq!(t.status, TaskStatus::Failed);
5835 t.attempts = 3;
5836 t.fail("stop", 10);
5837 assert_eq!(t.status, TaskStatus::Held);
5838 t.change_attempt_limit(None).unwrap();
5839 assert_eq!(t.status, TaskStatus::Held);
5840 assert_eq!(t.attempts, 3);
5841 t.fail("inherit", 4);
5842 assert_eq!(t.status, TaskStatus::Failed);
5843 for status in [
5844 TaskStatus::Running,
5845 TaskStatus::Done,
5846 TaskStatus::Failed,
5847 TaskStatus::Blocked,
5848 TaskStatus::Parked,
5849 ] {
5850 t.status = status;
5851 assert!(t.change_attempt_limit(NonZeroUsize::new(1)).is_err());
5852 assert_eq!(t.attempt_limit, None);
5853 }
5854 }
5855
5856 #[test]
5857 fn earlier_attempts_is_every_recorded_run_and_agrees_with_the_display() {
5858 let mut t = task("retried");
5859 assert!(
5860 t.earlier_attempts().is_empty(),
5861 "a first attempt takes nothing over"
5862 );
5863 t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned()];
5864 assert_eq!(t.earlier_attempts(), ["aaaa", "bbbb"]);
5865 assert_eq!(t.successor_of("aaaa"), Some(&"bbbb".to_owned()));
5867 assert_eq!(t.successor_of("bbbb"), None);
5868 assert_eq!(t.successor_of("zzzz"), None);
5869 }
5870
5871 #[test]
5872 fn resumed_runs_are_superseded_only_after_their_last_occurrence() {
5873 let (_dir, q) = queue();
5874 let mut t = task("resumed");
5875 for (runs, successor) in [
5876 (vec!["aaaa", "aaaa"], None),
5877 (vec!["aaaa", "bbbb", "aaaa"], None),
5878 (vec!["aaaa", "aaaa", "bbbb"], Some("bbbb")),
5879 (vec!["aaaa", "bbbb", "aaaa", "cccc"], Some("cccc")),
5880 ] {
5881 t.runs = runs.into_iter().map(str::to_owned).collect();
5882 q.put(&mut t).unwrap();
5883
5884 assert_eq!(t.successor_of("aaaa").map(String::as_str), successor);
5885 assert_eq!(q.superseded_by("aaaa").as_deref(), successor);
5886 assert_eq!(q.superseded().get("aaaa").map(String::as_str), successor);
5887 }
5888 }
5889
5890 #[test]
5891 fn superseded_by_names_the_next_attempt_and_none_for_the_last() {
5892 let (_dir, q) = queue();
5893 let mut t = task("retried");
5894 t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned(), "cccc".to_owned()];
5895 q.put(&mut t).unwrap();
5896
5897 assert_eq!(q.superseded_by("aaaa"), Some("bbbb".to_owned()));
5898 assert_eq!(q.superseded_by("bbbb"), Some("cccc".to_owned()));
5899 assert_eq!(
5900 q.superseded_by("cccc"),
5901 None,
5902 "the latest attempt replaces nothing"
5903 );
5904 assert_eq!(
5905 q.superseded_by("never-heard-of-it"),
5906 None,
5907 "a run belonging to no task on this queue is not superseded"
5908 );
5909
5910 let mut by = HashMap::new();
5911 by.insert("aaaa".to_owned(), "bbbb".to_owned());
5912 by.insert("bbbb".to_owned(), "cccc".to_owned());
5913 assert_eq!(
5914 q.superseded(),
5915 by,
5916 "the whole-map and single-run forms must agree"
5917 );
5918 }
5919
5920 #[test]
5921 fn superseded_attempts_is_empty_until_the_task_is_done() {
5922 let mut t = task("retried");
5923 t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned()];
5924 t.status = TaskStatus::Failed;
5925 assert_eq!(
5926 t.superseded_attempts(true),
5927 &[] as &[String],
5928 "a task still retrying has no attempt yet that a later one made moot"
5929 );
5930
5931 t.status = TaskStatus::Running;
5932 assert_eq!(t.superseded_attempts(true), &[] as &[String]);
5933 }
5934
5935 #[test]
5936 fn superseded_attempts_names_every_run_before_the_one_that_succeeded() {
5937 let mut t = task("retried");
5938 t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned(), "cccc".to_owned()];
5939 t.status = TaskStatus::Done;
5940 assert_eq!(
5941 t.superseded_attempts(true),
5942 &["aaaa".to_owned(), "bbbb".to_owned()],
5943 "cccc is the attempt whose success made the task done, and stays out"
5944 );
5945 }
5946
5947 #[test]
5948 fn superseded_attempts_is_empty_for_a_done_task_with_only_one_attempt() {
5949 let mut t = task("first try landed");
5950 t.runs = vec!["aaaa".to_owned()];
5951 t.status = TaskStatus::Done;
5952 assert_eq!(t.superseded_attempts(true), &[] as &[String]);
5953 }
5954
5955 #[test]
5956 fn superseded_attempts_is_empty_when_the_last_run_never_actually_succeeded() {
5957 let mut t = task("closed by hand after a manual merge");
5964 t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned()];
5965 t.status = TaskStatus::Done;
5966 assert_eq!(
5967 t.superseded_attempts(false),
5968 &[] as &[String],
5969 "nothing here is provably why the task is done, so nothing is superseded"
5970 );
5971 }
5972
5973 #[test]
5974 fn latest_attempt_names_the_chain_s_current_head_not_just_the_next_one() {
5975 let (_dir, q) = queue();
5976 let mut t = task("retried twice");
5977 t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned(), "cccc".to_owned()];
5978 q.put(&mut t).unwrap();
5979
5980 assert_eq!(
5981 q.latest_attempt("aaaa"),
5982 Some("cccc".to_owned()),
5983 "an old attempt points straight at the chain's current head, not the \
5984 next attempt in the middle of it"
5985 );
5986 assert_eq!(q.latest_attempt("bbbb"), Some("cccc".to_owned()));
5987 assert_eq!(
5988 q.latest_attempt("cccc"),
5989 None,
5990 "the latest attempt is not superseded by anything"
5991 );
5992 assert_eq!(
5993 q.latest_attempt("never-heard-of-it"),
5994 None,
5995 "a run belonging to no task on this queue is not superseded"
5996 );
5997 }
5998
5999 #[test]
6000 fn a_markdown_heading_is_the_title_not_decoration() {
6001 assert_eq!(
6006 title_from("# Rework the config loader\n\nIt re-reads it.\n", 40),
6007 "Rework the config loader"
6008 );
6009 assert_eq!(title_from("- fix the thing", 40), "fix the thing");
6010 assert_eq!(title_from("> quoted task", 40), "quoted task");
6011 assert_eq!(title_from(" \n\n", 40), "(empty task)");
6013 assert_eq!(title_from("###\n", 40), "(empty task)");
6014 }
6015
6016 #[test]
6017 fn a_long_title_is_elided_by_characters_not_bytes() {
6018 let long = "課題".repeat(30);
6020 let title = title_from(&long, 10);
6021 assert_eq!(title.chars().count(), 10);
6022 assert!(title.ends_with('…'));
6023 }
6024
6025 #[test]
6026 fn priority_wins_and_ties_break_oldest_first() {
6027 let (_dir, q) = queue();
6028 let mut a = task("first");
6029 let mut b = task("second");
6030 let mut c = task("urgent");
6031 a.id = "20260101-000001-aaaa".to_owned();
6033 b.id = "20260101-000002-bbbb".to_owned();
6034 c.id = "20260101-000003-cccc".to_owned();
6035 c.priority = 5;
6036 for t in [&mut a, &mut b, &mut c] {
6037 q.put(t).unwrap();
6038 }
6039
6040 assert_eq!(q.next_runnable().unwrap().id, c.id);
6042 c.hold_machine(None);
6043 q.put(&mut c).unwrap();
6044 assert_eq!(q.next_runnable().unwrap().id, a.id);
6046 assert_eq!(q.list().len(), 3, "b is still waiting its turn");
6047 }
6048
6049 #[test]
6050 fn a_blocked_task_never_starves_another_runnable_one() {
6051 let (_dir, q) = queue();
6052 let mut blocked = task("blocked");
6053 blocked.block(vec!["something".to_owned()], None);
6054 q.put(&mut blocked).unwrap();
6055
6056 let mut runnable = task("free to go");
6057 q.put(&mut runnable).unwrap();
6058
6059 let next = q.next_runnable().expect("a runnable task is still offered");
6060 assert_eq!(next.id, runnable.id);
6061 }
6062
6063 #[test]
6064 fn a_held_task_is_never_offered_to_the_loop() {
6065 let (_dir, q) = queue();
6066 let mut t = task("held");
6067 q.put(&mut t).unwrap();
6068 assert!(q.next_runnable().is_some());
6069
6070 t.hold_machine(None);
6071 q.put(&mut t).unwrap();
6072 assert!(
6073 q.next_runnable().is_none(),
6074 "a held task must wait for a human"
6075 );
6076
6077 t.status = TaskStatus::Failed;
6079 q.put(&mut t).unwrap();
6080 assert!(q.next_runnable().is_some());
6081 }
6082
6083 #[test]
6084 fn attempts_are_capped_and_then_the_task_is_held() {
6085 let mut t = task("doomed");
6086
6087 t.start("run-1".to_owned());
6088 t.fail("gate red", 2);
6089 assert_eq!(t.status, TaskStatus::Failed, "one attempt of two: retry");
6090
6091 t.start("run-2".to_owned());
6092 t.fail("gate red", 2);
6093 assert_eq!(
6094 t.status,
6095 TaskStatus::Held,
6096 "out of attempts: stop spending money on it"
6097 );
6098 assert_eq!(t.runs, ["run-1", "run-2"]);
6099 assert_eq!(t.last_error.as_deref(), Some("gate red"));
6100 assert_eq!(
6101 t.hold_reason.as_deref(),
6102 Some("gate red"),
6103 "the hold must say why, not leave hold_reason null next to a \
6104 populated last_error"
6105 );
6106 }
6107
6108 #[test]
6109 fn handing_off_a_task_records_a_hold_reason_too() {
6110 let mut t = task("left a pull request");
6111 t.start("run-1".to_owned());
6112 t.handed_off("run ended with a pull request open [run run-1]");
6113 assert_eq!(t.status, TaskStatus::Held);
6114 assert_eq!(t.hold_source, Some(HoldSource::Machine));
6115 assert_eq!(
6116 t.hold_reason.as_deref(),
6117 Some("run ended with a pull request open [run run-1]")
6118 );
6119 assert_eq!(t.hold_reason, t.last_error);
6120 }
6121
6122 #[test]
6123 fn a_quota_stall_is_refunded_so_the_backlog_survives_the_night() {
6124 let mut t = task("stalled by quota");
6125
6126 t.start("run-1".to_owned());
6127 assert_eq!(t.attempts, 1);
6128 t.stall("judge-1, judge-2 out of quota");
6129 assert_eq!(
6130 t.attempts, 0,
6131 "a closed quota window must not spend the task's retry budget"
6132 );
6133 assert_eq!(t.status, TaskStatus::Failed, "the loop should retry it");
6134 assert_eq!(
6135 t.last_error.as_deref(),
6136 Some("judge-1, judge-2 out of quota")
6137 );
6138
6139 for _ in 0..20 {
6142 t.start("run-n".to_owned());
6143 t.stall("still out of quota");
6144 }
6145 t.start("run-real".to_owned());
6146 t.fail("gate red", 2);
6147 assert_eq!(
6148 t.status,
6149 TaskStatus::Failed,
6150 "the first attempt that was really judged is attempt one"
6151 );
6152 }
6153
6154 #[test]
6155 fn releasing_a_held_task_gives_it_a_real_second_chance() {
6156 let mut t = task("retry me");
6157 t.start("run-1".to_owned());
6158 t.fail("gate red", 1);
6159 assert_eq!(t.status, TaskStatus::Held);
6160
6161 t.release();
6162 assert_eq!(t.status, TaskStatus::Queued);
6163 assert_eq!(t.attempts, 0);
6166 assert!(t.last_error.is_none());
6167 assert_eq!(
6168 t.runs.len(),
6169 1,
6170 "history is kept: attempts reset, evidence does not"
6171 );
6172 }
6173
6174 #[test]
6175 fn a_hold_reason_survives_and_a_release_clears_it() {
6176 let mut t = task("waiting on something else");
6177 t.hold_manual(Some(
6178 "waiting for 20260101-000000-aaaa to land first".to_owned(),
6179 ));
6180 assert_eq!(t.status, TaskStatus::Held);
6181 assert_eq!(
6182 t.hold_reason.as_deref(),
6183 Some("waiting for 20260101-000000-aaaa to land first")
6184 );
6185
6186 t.hold_manual(None);
6188 assert_eq!(
6189 t.hold_reason.as_deref(),
6190 Some("waiting for 20260101-000000-aaaa to land first"),
6191 "a bare re-hold keeps whatever a human already wrote down"
6192 );
6193
6194 let mut plain = task("no reason given");
6196 plain.hold_manual(None);
6197 assert_eq!(plain.status, TaskStatus::Held);
6198 assert!(plain.hold_reason.is_none());
6199
6200 t.release();
6201 assert_eq!(t.status, TaskStatus::Queued);
6202 assert!(
6203 t.hold_reason.is_none(),
6204 "a stale reason must not greet the next person who holds this task"
6205 );
6206 }
6207
6208 #[test]
6209 fn closing_a_held_task_as_done_clears_its_hold_reason_too() {
6210 let mut t = task("landed by hand while held");
6215 t.hold_manual(Some("waiting on 3ed9".to_owned()));
6216 assert_eq!(t.hold_reason.as_deref(), Some("waiting on 3ed9"));
6217
6218 t.succeed(completion(&t));
6219 assert_eq!(t.status, TaskStatus::Done);
6220 assert!(
6221 t.hold_reason.is_none(),
6222 "a done task cannot still be waiting on something"
6223 );
6224 }
6225
6226 #[test]
6227 fn holding_or_closing_a_blocked_task_clears_its_dependency_too() {
6228 let mut held = task("held straight out of blocked");
6235 held.block(
6236 vec!["20260101-000000-dead".to_owned()],
6237 Some("waiting on the migration script".to_owned()),
6238 );
6239 assert_eq!(held.status, TaskStatus::Blocked);
6240
6241 held.hold_manual(None);
6242 assert_eq!(held.status, TaskStatus::Held);
6243 assert!(
6244 held.blocked_by.is_empty(),
6245 "hold overrides the wait, same as release"
6246 );
6247 assert!(held.block_reason.is_none());
6248
6249 let mut done = task("closed straight out of blocked");
6250 done.block(
6251 vec!["20260101-000000-dead".to_owned()],
6252 Some("waiting on the migration script".to_owned()),
6253 );
6254 done.succeed(completion(&done));
6255 assert_eq!(done.status, TaskStatus::Done);
6256 assert!(
6257 done.blocked_by.is_empty(),
6258 "a done task cannot still be waiting on a dependency"
6259 );
6260 assert!(done.block_reason.is_none());
6261 }
6262
6263 #[test]
6264 fn a_blocked_task_is_never_offered_to_the_loop() {
6265 let mut t = task("blocked");
6266 assert!(t.status.runnable());
6267 t.block(
6268 vec!["dep-id".to_owned()],
6269 Some("waits on dep-id".to_owned()),
6270 );
6271 assert_eq!(t.status, TaskStatus::Blocked);
6272 assert!(!t.status.runnable());
6273 assert_eq!(TaskStatus::Blocked.as_str(), "blocked");
6274 }
6275
6276 #[test]
6277 fn unblocking_the_last_dependency_returns_the_task_to_queued() {
6278 let mut t = task("blocked on two");
6279 t.block(
6280 vec!["a".to_owned(), "b".to_owned()],
6281 Some("waits on a and b".to_owned()),
6282 );
6283
6284 t.unblock("a");
6285 assert_eq!(t.status, TaskStatus::Blocked, "b is still outstanding");
6286 assert_eq!(t.blocked_by, ["b"]);
6287
6288 t.unblock("b");
6289 assert_eq!(t.status, TaskStatus::Queued);
6290 assert!(t.blocked_by.is_empty());
6291 assert!(t.block_reason.is_none());
6292 }
6293
6294 #[test]
6295 fn unblocking_an_id_on_a_task_that_is_not_blocked_is_a_no_op() {
6296 let mut t = task("never blocked");
6297 t.unblock("whatever");
6298 assert_eq!(t.status, TaskStatus::Queued);
6299 }
6300
6301 #[test]
6302 fn a_held_task_blocked_on_a_question_returns_to_held_not_queued() {
6303 let mut t = task("held, then asked about");
6308 t.hold_machine(Some("out of attempts".to_owned()));
6309 assert_eq!(t.status, TaskStatus::Held);
6310
6311 t.block(vec!["q1".to_owned()], Some("what now?".to_owned()));
6312 assert_eq!(t.status, TaskStatus::Blocked);
6313
6314 t.record_answer("what now?".to_owned(), "leave it held".to_owned());
6315 t.unblock("q1");
6316 assert_eq!(t.status, TaskStatus::Held, "must restore, not requeue");
6317 assert_eq!(t.hold_reason.as_deref(), Some("out of attempts"));
6318 assert_eq!(t.hold_source, Some(HoldSource::Machine));
6319 assert!(t.blocked_from.is_none(), "consumed once restored");
6320 }
6321
6322 #[test]
6323 fn a_manually_held_task_blocked_on_a_question_returns_to_held() {
6324 let mut t = task("manually held, then asked about");
6325 t.hold_manual(Some("waiting on a dependency".to_owned()));
6326
6327 t.block(vec!["q1".to_owned()], None);
6328 t.unblock("q1");
6329
6330 assert_eq!(t.status, TaskStatus::Held);
6331 assert_eq!(t.hold_source, Some(HoldSource::Manual));
6332 }
6333
6334 #[test]
6335 fn re_blocking_an_already_blocked_task_keeps_the_original_blocked_from() {
6336 let mut t = task("held, blocked twice");
6340 t.hold_machine(None);
6341 t.block(vec!["q1".to_owned()], Some("first".to_owned()));
6342 t.block(
6343 vec!["q1".to_owned(), "q2".to_owned()],
6344 Some("second".to_owned()),
6345 );
6346
6347 t.unblock("q1");
6348 assert_eq!(t.status, TaskStatus::Blocked, "q2 still outstanding");
6349 t.unblock("q2");
6350 assert_eq!(t.status, TaskStatus::Held);
6351 }
6352
6353 #[test]
6354 fn unblocking_a_task_blocked_while_running_lands_on_queued_not_running() {
6355 let mut t = task("blocked mid-run");
6359 t.start("run-1".to_owned());
6360 assert_eq!(t.status, TaskStatus::Running);
6361
6362 t.block(vec!["q1".to_owned()], None);
6363 t.unblock("q1");
6364 assert_eq!(t.status, TaskStatus::Queued);
6365 }
6366
6367 #[test]
6368 fn a_pre_schema_4_blocked_record_with_hold_evidence_restores_to_held() {
6369 let mut t = task("legacy record, held before it was blocked");
6375 t.hold_source = Some(HoldSource::Machine);
6376 t.hold_reason = Some("legacy hold reason".to_owned());
6377 t.status = TaskStatus::Blocked;
6378 t.blocked_by = vec!["q1".to_owned()];
6379 t.blocked_from = None;
6380
6381 t.unblock("q1");
6382 assert_eq!(t.status, TaskStatus::Held);
6383 }
6384
6385 #[test]
6386 fn a_pre_schema_4_blocked_record_with_no_hold_evidence_restores_to_queued() {
6387 let mut t = task("legacy record, ordinary dependency block");
6388 t.status = TaskStatus::Blocked;
6389 t.blocked_by = vec!["dep".to_owned()];
6390 t.blocked_from = None;
6391
6392 t.unblock("dep");
6393 assert_eq!(t.status, TaskStatus::Queued);
6394 }
6395
6396 #[test]
6397 fn answering_a_question_is_recorded_and_survives_a_release() {
6398 let mut t = task("asked something");
6399 t.block(vec!["q1".to_owned()], Some("which backend?".to_owned()));
6400 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
6401 t.unblock("q1");
6402 assert_eq!(t.status, TaskStatus::Queued);
6403 assert_eq!(t.answers.len(), 1);
6404 assert_eq!(t.answers[0].answer, "SQLite");
6405
6406 t.release();
6410 assert_eq!(t.answers.len(), 1, "the answer is not lost on release");
6411 }
6412
6413 #[test]
6414 fn resumption_review_branch_requires_unchanged_authored_criteria() {
6415 for source in ["cli", "web"] {
6416 let mut t = task("review old candidate");
6417 t.request_review("candidate-A".into());
6418 t.hold_for_handover(Some("candidate-A".into()), "handover refused".into());
6419 let mut unchanged = t.clone();
6420 unchanged.release_operator(source, None);
6421 assert_eq!(unchanged.review_branch.as_deref(), Some("candidate-A"));
6422 t.edit(
6423 "review approved head".into(),
6424 "Reuse measured PR head B; fix Clippy; review".into(),
6425 )
6426 .unwrap();
6427 t.release_operator(source, None);
6428 assert!(t.review_branch.is_none());
6429 assert!(t.review_instruction.is_none());
6430 let mut legacy = unchanged;
6432 legacy.review_instruction = None;
6433 legacy.hold_for_handover(None, "still checked out".into());
6434 legacy
6435 .edit("new plan".into(), "Reuse measured PR head B".into())
6436 .unwrap();
6437 legacy.release_operator(source, None);
6438 assert!(legacy.review_branch.is_none());
6439 }
6440 }
6441
6442 #[test]
6443 fn a_refused_handover_keeps_the_review_branch_across_release() {
6444 let mut t = task("refused takeover");
6445 t.start("run-1".to_owned());
6446 t.hold_for_handover(Some("magi/eba2/A".to_owned()), "checked out".to_owned());
6447 assert_eq!(t.status, TaskStatus::Held);
6448 assert_eq!(t.attempts, 1);
6449 t.release();
6450 assert_eq!(t.status, TaskStatus::Queued);
6451 assert_eq!(t.attempts, 0);
6452 assert_eq!(t.review_branch.as_deref(), Some("magi/eba2/A"));
6453
6454 t.hold_for_handover(None, "again".to_owned());
6456 t.requeue();
6457 assert!(t.review_branch.is_none());
6458
6459 let mut m = task("manual");
6461 m.review_branch = Some("magi/x/A".to_owned());
6462 m.hold_manual(None);
6463 m.release();
6464 assert!(m.review_branch.is_none());
6465 }
6466
6467 #[test]
6468 fn requesting_review_requeues_the_task_and_remembers_the_branch() {
6469 let mut t = task("blocked run with a surviving branch");
6470 t.start("run-1".to_owned());
6471 t.fail("blocked with major findings", 5);
6472 assert_eq!(t.status, TaskStatus::Failed);
6473
6474 t.request_review("magi/eba2/A".to_owned());
6475 assert_eq!(t.status, TaskStatus::Queued);
6476 assert_eq!(t.attempts, 0);
6477 assert_eq!(t.review_branch.as_deref(), Some("magi/eba2/A"));
6478
6479 t.release();
6481 assert!(t.review_branch.is_none());
6482 }
6483
6484 #[test]
6485 fn conductor_requeue_but_not_an_ordinary_release_forces_a_fresh_start() {
6486 let mut t = task("retry");
6487 t.start("run-1".to_owned());
6488 t.requeue();
6489 assert!(t.fresh_start);
6490
6491 t.release();
6492 assert!(!t.fresh_start);
6493 }
6494
6495 #[test]
6496 fn urgent_only_changes_queued_or_held_and_preserves_settings() {
6497 for status in [
6498 TaskStatus::Queued,
6499 TaskStatus::Held,
6500 TaskStatus::Running,
6501 TaskStatus::Done,
6502 TaskStatus::Failed,
6503 TaskStatus::Blocked,
6504 TaskStatus::Parked,
6505 ] {
6506 let mut t = task("urgent settings");
6507 t.status = status;
6508 t.attempts = 2;
6509 t.hold_reason = Some("waiting".into());
6510 t.priority = 7;
6511 t.interrupt = true;
6512 let before = serde_json::to_value(&t).unwrap();
6513 for urgent in [true, true, false, false] {
6514 let result = t.set_urgent(urgent);
6515 let mut expected = before.clone();
6516 if matches!(status, TaskStatus::Queued | TaskStatus::Held) {
6517 result.unwrap();
6518 expected["urgent"] = urgent.into();
6519 } else {
6520 let error = result.unwrap_err().to_string();
6521 assert!(error.contains(status.as_str()), "{error}");
6522 assert!(error.contains("queued or held"), "{error}");
6523 }
6524 assert_eq!(serde_json::to_value(&t).unwrap(), expected);
6525 }
6526 }
6527 }
6528
6529 #[test]
6530 fn immediate_only_changes_queued_or_held_and_preserves_settings() {
6531 for status in [
6532 TaskStatus::Queued,
6533 TaskStatus::Held,
6534 TaskStatus::Running,
6535 TaskStatus::Done,
6536 TaskStatus::Failed,
6537 TaskStatus::Blocked,
6538 TaskStatus::Parked,
6539 ] {
6540 let mut t = task("immediate settings");
6541 t.status = status;
6542 t.attempts = 2;
6543 t.hold_reason = Some("waiting".into());
6544 t.priority = 7;
6545 t.interrupt = true;
6546 t.urgent = true;
6547 let before = serde_json::to_value(&t).unwrap();
6548 for immediate in [true, true, false, false] {
6549 let result = t.set_immediate(immediate);
6550 let mut expected = before.clone();
6551 if matches!(status, TaskStatus::Queued | TaskStatus::Held) {
6552 result.unwrap();
6553 expected["immediate"] = immediate.into();
6554 } else {
6555 let error = result.unwrap_err().to_string();
6556 assert!(error.contains(status.as_str()), "{error}");
6557 assert!(error.contains("queued or held"), "{error}");
6558 }
6559 assert_eq!(serde_json::to_value(&t).unwrap(), expected);
6560 assert!(t.urgent, "changing immediate must preserve saved urgent");
6561 }
6562 }
6563 }
6564
6565 #[test]
6566 fn a_task_recorded_without_an_immediate_field_still_reads_as_not_immediate() {
6567 let (_dir, q) = queue();
6568 let path = q.path_of("20260101-000000-imm0");
6569 std::fs::create_dir_all(q.root()).unwrap();
6570 std::fs::write(
6571 &path,
6572 serde_json::json!({
6573 "schema": SCHEMA,
6574 "id": "20260101-000000-imm0",
6575 "title": "from before immediate existed",
6576 "instruction": "from before immediate existed",
6577 "repo": ".",
6578 "source": { "kind": "human" },
6579 "status": "queued",
6580 "urgent": true,
6581 "created_at": Timestamp::now().to_string(),
6582 "updated_at": Timestamp::now().to_string(),
6583 })
6584 .to_string(),
6585 )
6586 .unwrap();
6587
6588 let task = q.get("20260101-000000-imm0").expect("must still read");
6589 assert!(!task.immediate);
6590 assert!(task.urgent);
6591 }
6592
6593 #[test]
6594 fn immediate_reuses_urgent_isolation_and_explicit_cache_wins() {
6595 let mut cfg = crate::config::Config::default();
6596 cfg.verify.e2e = vec!["CARGO_TARGET_DIR=/tmp/shared-target cargo test".into()];
6597 let mut t = task("immediate cache");
6598
6599 t.set_immediate(true).unwrap();
6600 assert_eq!(
6601 t.build_cache_override(&cfg),
6602 Some((BuildCache::Isolated, "immediate"))
6603 );
6604
6605 t.set_urgent(true).unwrap();
6607 assert_eq!(
6608 t.build_cache_override(&cfg),
6609 Some((BuildCache::Isolated, "immediate"))
6610 );
6611
6612 t.change_build_cache(Some(BuildCache::Shared)).unwrap();
6614 assert_eq!(
6615 t.build_cache_override(&cfg),
6616 Some((BuildCache::Shared, "task-override"))
6617 );
6618
6619 t.change_build_cache(None).unwrap();
6621 assert_eq!(
6622 t.build_cache_override(&cfg),
6623 Some((BuildCache::Isolated, "immediate"))
6624 );
6625 t.set_immediate(false).unwrap();
6626 assert_eq!(
6627 t.build_cache_override(&cfg),
6628 Some((BuildCache::Isolated, "urgent"))
6629 );
6630
6631 t.set_immediate(true).unwrap();
6633 cfg.verify.e2e = vec!["CARGO_TARGET_DIR=/tmp/shared-target cargo test | tee log".into()];
6634 assert_eq!(t.build_cache_override(&cfg), None);
6635 }
6636
6637 #[test]
6638 fn priority_can_be_changed_while_queued_but_not_while_running() {
6639 let mut t = task("reprioritise me");
6640 t.set_priority(5).unwrap();
6641 assert_eq!(t.priority, 5);
6642
6643 t.start("run-1".to_owned());
6644 let err = t.set_priority(9).unwrap_err().to_string();
6645 assert!(err.contains("running"), "{err}");
6646 assert_eq!(t.priority, 5, "the rejected write must not partially apply");
6647 }
6648
6649 #[test]
6650 fn interrupt_can_be_marked_while_queued_but_not_while_running() {
6651 let mut t = task("interrupt me");
6652 assert!(!t.interrupt, "off unless asked, same as any other task");
6653
6654 t.set_interrupt(true).unwrap();
6655 assert!(t.interrupt);
6656
6657 t.start("run-1".to_owned());
6658 assert!(
6659 !t.interrupt,
6660 "the mark is one-shot: dispatching the task fulfils it, \
6661 whatever the run that follows ends up doing"
6662 );
6663 let err = t.set_interrupt(true).unwrap_err().to_string();
6664 assert!(err.contains("running"), "{err}");
6665 t.set_interrupt(false).unwrap();
6668 assert!(!t.interrupt);
6669 }
6670
6671 #[test]
6675 fn a_failed_run_does_not_leave_the_task_still_marked_to_interrupt() {
6676 let mut t = task("interrupt me");
6677 t.set_interrupt(true).unwrap();
6678 t.start("run-1".to_owned());
6679 t.fail("mock failure", 5);
6680 assert_eq!(t.status, TaskStatus::Failed);
6681 assert!(
6682 !t.interrupt,
6683 "one attempt already spent the mark; a retry is an ordinary \
6684 requeue, not a fresh interrupt request"
6685 );
6686 }
6687
6688 #[test]
6689 fn changing_priority_moves_a_task_ahead_in_the_real_queue_order() {
6690 let (_dir, q) = queue();
6691 let mut a = task("first filed");
6692 let mut b = task("second filed");
6693 a.id = "20260101-000001-aaaa".to_owned();
6694 b.id = "20260101-000002-bbbb".to_owned();
6695 q.put(&mut a).unwrap();
6696 q.put(&mut b).unwrap();
6697
6698 assert_eq!(
6699 q.next_runnable().unwrap().id,
6700 a.id,
6701 "with equal priority the older task goes first, so a burst of \
6702 new work cannot starve it"
6703 );
6704 assert_eq!(
6705 q.list()[0].id,
6706 b.id,
6707 "but the list an operator reads is newest first, the same as \
6708 before priority existed - a's turn to run does not make it the \
6709 newest task"
6710 );
6711
6712 let mut a = q.get(&a.id).unwrap();
6713 a.set_priority(10).unwrap();
6714 q.put(&mut a).unwrap();
6715
6716 assert_eq!(
6717 q.next_runnable().unwrap().id,
6718 a.id,
6719 "a raised priority must be reflected the moment it is saved"
6720 );
6721 assert_eq!(
6725 q.list()[0].id,
6726 a.id,
6727 "the raised task must sort first in the list an operator reads, \
6728 not only in next_runnable's own ordering"
6729 );
6730 }
6731
6732 #[test]
6733 fn editing_replaces_title_and_instruction_but_keeps_identity_and_history() {
6734 let mut t = Task::new(
6735 "old title".to_owned(),
6736 "old instruction".to_owned(),
6737 PathBuf::from("/repo"),
6738 Source::Agent {
6739 run: "20260101-000000-beef".to_owned(),
6740 node: "implement".to_owned(),
6741 },
6742 );
6743 let id = t.id.clone();
6744 let created_at = t.created_at;
6745 t.runs.push("20260101-000000-beef".to_owned());
6746
6747 t.edit("new title".to_owned(), "new instruction".to_owned())
6748 .unwrap();
6749
6750 assert_eq!(t.title, "new title");
6751 assert_eq!(t.instruction, "new instruction");
6752 assert_eq!(t.id, id, "editing must not mint a new id");
6753 assert_eq!(t.created_at, created_at);
6754 assert_eq!(
6755 t.source,
6756 Source::Agent {
6757 run: "20260101-000000-beef".to_owned(),
6758 node: "implement".to_owned(),
6759 },
6760 "editing must not turn agent attribution into human"
6761 );
6762 assert_eq!(t.runs, ["20260101-000000-beef"]);
6763 }
6764
6765 #[test]
6766 fn editing_is_refused_once_a_task_is_running_or_finished() {
6767 let mut running = task("in flight");
6768 running.start("run-1".to_owned());
6769 let err = running
6770 .edit("x".to_owned(), "y".to_owned())
6771 .unwrap_err()
6772 .to_string();
6773 assert!(err.contains("running"), "{err}");
6774
6775 let mut done = task("finished");
6776 done.succeed(completion(&done));
6777 let err = done
6778 .edit("x".to_owned(), "y".to_owned())
6779 .unwrap_err()
6780 .to_string();
6781 assert!(err.contains("done"), "{err}");
6782
6783 let mut queued = task("waiting");
6785 queued.edit("x".to_owned(), "y".to_owned()).unwrap();
6786 let mut held = task("parked");
6787 held.hold_machine(None);
6788 held.edit("x".to_owned(), "y".to_owned()).unwrap();
6789 }
6790
6791 #[test]
6792 fn a_task_recorded_without_a_hold_reason_still_reads_as_none() {
6793 let (_dir, q) = queue();
6794 let path = q.path_of("20260101-000000-aaaa");
6795 std::fs::create_dir_all(q.root()).unwrap();
6796 std::fs::write(
6797 &path,
6798 serde_json::json!({
6799 "schema": SCHEMA,
6800 "id": "20260101-000000-aaaa",
6801 "title": "from before hold reasons existed",
6802 "instruction": "from before hold reasons existed",
6803 "repo": ".",
6804 "source": { "kind": "human" },
6805 "status": "held",
6806 "created_at": Timestamp::now().to_string(),
6807 "updated_at": Timestamp::now().to_string(),
6808 })
6809 .to_string(),
6810 )
6811 .unwrap();
6812
6813 let task = q.get("20260101-000000-aaaa").expect("must still read");
6814 assert!(task.hold_reason.is_none());
6815 assert!(task.operator_held());
6816 }
6817
6818 #[test]
6819 fn a_legacy_reasoned_hold_defaults_to_operator_protection() {
6820 let (_dir, q) = queue();
6821 let path = q.path_of("20260101-000000-bbbb");
6822 std::fs::create_dir_all(q.root()).unwrap();
6823 std::fs::write(
6824 &path,
6825 serde_json::json!({
6826 "schema": 2,
6827 "id": "20260101-000000-bbbb",
6828 "title": "old manual recovery",
6829 "instruction": "old manual recovery",
6830 "repo": ".",
6831 "source": { "kind": "human" },
6832 "status": "held",
6833 "hold_reason": "active manual recovery run20260912-224242-daf5",
6834 "created_at": Timestamp::now().to_string(),
6835 "updated_at": Timestamp::now().to_string(),
6836 })
6837 .to_string(),
6838 )
6839 .unwrap();
6840
6841 let task = q.get("20260101-000000-bbbb").expect("must still read");
6842 assert_eq!(task.hold_source, None);
6843 assert!(task.operator_held());
6844 }
6845
6846 #[test]
6847 fn a_task_recorded_without_a_diagnostic_still_reads_as_none() {
6848 let (_dir, q) = queue();
6849 let path = q.path_of("20260101-000000-aaaa");
6850 std::fs::create_dir_all(q.root()).unwrap();
6851 std::fs::write(
6852 &path,
6853 serde_json::json!({
6854 "schema": SCHEMA,
6855 "id": "20260101-000000-aaaa",
6856 "title": "from before diagnostics existed",
6857 "instruction": "from before diagnostics existed",
6858 "repo": ".",
6859 "source": { "kind": "human" },
6860 "status": "held",
6861 "created_at": Timestamp::now().to_string(),
6862 "updated_at": Timestamp::now().to_string(),
6863 })
6864 .to_string(),
6865 )
6866 .unwrap();
6867
6868 let task = q.get("20260101-000000-aaaa").expect("must still read");
6869 assert!(task.diagnostic.is_none());
6870 }
6871
6872 #[test]
6873 fn a_schema_1_task_with_no_blocking_fields_still_reads() {
6874 let (_dir, q) = queue();
6878 let path = q.path_of("20260101-000000-aaaa");
6879 std::fs::create_dir_all(q.root()).unwrap();
6880 std::fs::write(
6881 &path,
6882 serde_json::json!({
6883 "schema": 1,
6884 "id": "20260101-000000-aaaa",
6885 "title": "from before blocking existed",
6886 "instruction": "from before blocking existed",
6887 "repo": ".",
6888 "source": { "kind": "human" },
6889 "status": "queued",
6890 "created_at": Timestamp::now().to_string(),
6891 "updated_at": Timestamp::now().to_string(),
6892 })
6893 .to_string(),
6894 )
6895 .unwrap();
6896
6897 let task = q.get("20260101-000000-aaaa").expect("must still read");
6898 assert!(task.blocked_by.is_empty());
6899 assert!(task.block_reason.is_none());
6900 assert!(task.answers.is_empty());
6901 assert!(task.review_branch.is_none());
6902 }
6903
6904 #[test]
6905 fn releasing_or_finishing_a_task_clears_its_stale_diagnostic() {
6906 let mut held = task("diagnosed");
6911 held.start("run-1".to_owned());
6912 held.fail("gate red", 1);
6913 held.diagnostic = Some("cargo test failed: ...".to_owned());
6914 assert_eq!(held.status, TaskStatus::Held);
6915
6916 held.release();
6917 assert!(held.diagnostic.is_none());
6918
6919 held.diagnostic = Some("cargo test failed: ...".to_owned());
6920 held.succeed(completion(&held));
6921 assert!(held.diagnostic.is_none());
6922 }
6923
6924 #[test]
6925 fn failing_a_task_always_clears_whatever_diagnostic_it_carried() {
6926 let mut t = task("retried");
6927 t.start("run-1".to_owned());
6928 t.diagnostic = Some("stale evidence from a previous hold".to_owned());
6929 t.fail("unrelated config error", 5);
6930 assert_eq!(t.status, TaskStatus::Failed);
6931 assert!(
6932 t.diagnostic.is_none(),
6933 "fail() must not let an old diagnostic outlive the run that produced it"
6934 );
6935 }
6936
6937 #[test]
6938 fn a_claim_is_exclusive_and_releases_on_drop() {
6939 let (_dir, q) = queue();
6940 let mut t = task("contended");
6941 q.put(&mut t).unwrap();
6942
6943 let held = q.claim(&t.id).unwrap();
6944 assert!(
6945 q.claim(&t.id).is_err(),
6946 "two daemons must not drive one task into two runs"
6947 );
6948 drop(held);
6949 assert!(q.claim(&t.id).is_ok(), "a released claim is reclaimable");
6950 }
6951
6952 #[test]
6953 fn a_round_trip_survives_disk() {
6954 let (_dir, q) = queue();
6955 let mut t = Task::new(
6956 "titled".to_owned(),
6957 "body".to_owned(),
6958 PathBuf::from("/repo"),
6959 Source::Agent {
6960 run: "20260101-000000-beef".to_owned(),
6961 node: "implement".to_owned(),
6962 },
6963 );
6964 t.priority = 3;
6965 q.put(&mut t).unwrap();
6966
6967 let back = q.get(&t.id).unwrap();
6968 assert_eq!(back.id, t.id);
6969 assert_eq!(back.priority, 3);
6970 assert_eq!(back.source.label(), "implement@beef");
6971 assert_eq!(q.get(t.short()).unwrap().id, t.id);
6973 }
6974
6975 #[test]
6976 fn an_unreadable_task_does_not_take_the_queue_down() {
6977 let (_dir, q) = queue();
6978 let mut t = task("fine");
6979 q.put(&mut t).unwrap();
6980 std::fs::write(q.root().join("broken.json"), "{ not json").unwrap();
6981
6982 let listed = q.list();
6983 assert_eq!(listed.len(), 1, "the readable task still lists");
6984 assert_eq!(listed[0].id, t.id);
6985 }
6986
6987 #[test]
6988 fn a_task_recorded_without_a_solo_field_still_reads_as_not_solo() {
6989 let (_dir, q) = queue();
6990 let path = q.path_of("20260101-000000-aaaa");
6991 std::fs::create_dir_all(q.root()).unwrap();
6992 std::fs::write(
6993 &path,
6994 serde_json::json!({
6995 "schema": SCHEMA,
6996 "id": "20260101-000000-aaaa",
6997 "title": "from before solo existed",
6998 "instruction": "from before solo existed",
6999 "repo": ".",
7000 "source": { "kind": "human" },
7001 "status": "queued",
7002 "created_at": Timestamp::now().to_string(),
7003 "updated_at": Timestamp::now().to_string(),
7004 })
7005 .to_string(),
7006 )
7007 .unwrap();
7008
7009 let task = q.get("20260101-000000-aaaa").expect("must still read");
7010 assert!(!task.solo, "a queue file with no `solo` field means false");
7011 }
7012
7013 #[test]
7014 fn a_task_recorded_without_an_urgent_field_still_reads_as_not_urgent() {
7015 let (_dir, q) = queue();
7016 let path = q.path_of("20260101-000000-bbbb");
7017 std::fs::create_dir_all(q.root()).unwrap();
7018 std::fs::write(
7019 &path,
7020 serde_json::json!({
7021 "schema": SCHEMA,
7022 "id": "20260101-000000-bbbb",
7023 "title": "from before urgent existed",
7024 "instruction": "from before urgent existed",
7025 "repo": ".",
7026 "source": { "kind": "human" },
7027 "status": "queued",
7028 "created_at": Timestamp::now().to_string(),
7029 "updated_at": Timestamp::now().to_string(),
7030 })
7031 .to_string(),
7032 )
7033 .unwrap();
7034
7035 let task = q.get("20260101-000000-bbbb").expect("must still read");
7036 assert!(
7037 !task.urgent,
7038 "a queue file with no `urgent` field means false, same as `solo`"
7039 );
7040 }
7041
7042 #[test]
7043 fn a_task_from_a_future_schema_is_refused_rather_than_guessed_at() {
7044 let (_dir, q) = queue();
7045 let mut t = task("from the future");
7046 q.put(&mut t).unwrap();
7047 let path = q.path_of(&t.id);
7048 let body = std::fs::read_to_string(&path)
7049 .unwrap()
7050 .replace(&format!("\"schema\": {SCHEMA}"), "\"schema\": 99");
7051 std::fs::write(&path, body).unwrap();
7052
7053 let err = q.get(&t.id).unwrap_err().to_string();
7054 assert!(err.contains("schema 99"), "{err}");
7055 }
7056
7057 #[test]
7058 fn revision_moves_when_the_queue_changes() {
7059 let (_dir, q) = queue();
7060 assert_eq!(q.revision(), 0, "an empty queue has no revision");
7061 let mut t = task("first");
7062 q.put(&mut t).unwrap();
7063 assert!(q.revision() > 0, "a written task moves the revision");
7064 }
7065
7066 #[test]
7067 fn revision_moves_when_deleting_an_older_task() {
7068 let (dir, q) = queue();
7069 let questions = Questions::at(dir.path().join("questions"));
7070 let mut t1 = task("older");
7071 q.put(&mut t1).unwrap();
7072 std::thread::sleep(std::time::Duration::from_millis(10));
7074 let mut t2 = task("newer");
7075 q.put(&mut t2).unwrap();
7076
7077 let rev_before = q.revision();
7078 q.remove(&t1.id, false, &questions).unwrap();
7079 let rev_after = q.revision();
7080
7081 assert_ne!(
7082 rev_before, rev_after,
7083 "deleting an older task must change the revision so other clients see the deletion"
7084 );
7085 }
7086
7087 #[test]
7088 fn removing_a_task_takes_it_out_of_the_listing() {
7089 let (dir, q) = queue();
7090 let questions = Questions::at(dir.path().join("questions"));
7091 let mut t = task("delete me");
7092 q.put(&mut t).unwrap();
7093 let removed = q.remove(t.short(), false, &questions).unwrap();
7094 assert_eq!(removed.id, t.id, "a prefix resolves before deleting");
7095 assert!(removed.released.is_empty() && removed.still_blocked.is_empty());
7096 assert!(q.list().is_empty());
7097 assert!(
7098 q.remove(&t.id, false, &questions).is_err(),
7099 "removing twice is an error"
7100 );
7101 }
7102
7103 #[test]
7104 fn removing_a_task_takes_its_stale_lock_with_it() {
7105 let (dir, q) = queue();
7106 let questions = Questions::at(dir.path().join("questions"));
7107 let mut t = task("interrupted");
7108 q.put(&mut t).unwrap();
7109
7110 let claim = q.claim(&t.id).unwrap();
7113 std::mem::forget(claim);
7114 assert!(
7115 q.claim(&t.id).is_err(),
7116 "the orphaned lock is what makes the task look claimed"
7117 );
7118
7119 let err = q.remove(&t.id, true, &questions).unwrap_err().to_string();
7121 assert!(err.contains("live daemon"), "{err}");
7122 assert!(q.get(&t.id).is_ok(), "a refused delete keeps the task");
7123
7124 q.remove(&t.id, false, &questions).unwrap();
7126 assert!(q.list().is_empty());
7127 let mut again = task("interrupted");
7128 again.id = t.id.clone();
7129 q.put(&mut again).unwrap();
7130 assert!(
7131 q.claim(&t.id).is_ok(),
7132 "a task that comes back must be claimable, which a left-behind lock would prevent"
7133 );
7134 }
7135
7136 fn notices_of(dir: &Path) -> Vec<crate::notices::Notice> {
7137 crate::notices::Notices::at(dir.join("notifications")).list()
7138 }
7139
7140 #[test]
7141 fn removing_a_sole_dependency_releases_the_dependent_without_a_hold() {
7142 let (dir, q) = queue();
7143 let questions = Questions::at(dir.path().join("questions"));
7144 let mut dep = task("dependency");
7145 q.put(&mut dep).unwrap();
7146 let mut blocked = task("waiting");
7147 blocked.block(vec![dep.id.clone()], Some("waits".to_owned()));
7148 q.put(&mut blocked).unwrap();
7149
7150 let removed = q.remove(&dep.id, false, &questions).unwrap();
7151 assert_eq!(removed.released, [blocked.id.clone()]);
7152 assert!(removed.still_blocked.is_empty());
7153
7154 let after = q.get(&blocked.id).unwrap();
7155 assert_eq!(after.status, TaskStatus::Queued);
7156 assert!(after.blocked_by.is_empty());
7157 assert!(after.block_reason.is_none());
7158 let notes = notices_of(dir.path());
7159 assert_eq!(notes.len(), 1, "{notes:?}");
7160 assert_eq!(notes[0].severity, crate::notices::Severity::Info);
7161 assert_eq!(
7162 notes[0].link,
7163 Some(crate::notices::Link::Task {
7164 id: blocked.id.clone(),
7165 })
7166 );
7167 }
7168
7169 #[test]
7170 fn removing_one_of_two_dependencies_keeps_the_other() {
7171 let (dir, q) = queue();
7172 let questions = Questions::at(dir.path().join("questions"));
7173 let mut dep = task("dependency");
7174 q.put(&mut dep).unwrap();
7175 let mut other = task("other");
7176 q.put(&mut other).unwrap();
7177 let mut blocked = task("waiting");
7178 blocked.block(
7179 vec![dep.id.clone(), other.id.clone()],
7180 Some("waits on both".to_owned()),
7181 );
7182 q.put(&mut blocked).unwrap();
7183
7184 let removed = q.remove(&dep.id, false, &questions).unwrap();
7185 assert!(removed.released.is_empty());
7186 assert_eq!(removed.still_blocked, [blocked.id.clone()]);
7187
7188 let after = q.get(&blocked.id).unwrap();
7189 assert_eq!(after.status, TaskStatus::Blocked);
7190 assert_eq!(after.blocked_by, [other.id.clone()]);
7191 assert!(missing_blockers(&q, &questions, &after.blocked_by).is_empty());
7194 }
7195
7196 #[test]
7197 fn a_dependency_deleted_before_its_dependents_were_rewritten_is_released_later() {
7198 let (dir, q) = queue();
7199 let questions = Questions::at(dir.path().join("questions"));
7200 let mut dep = task("dependency");
7201 q.put(&mut dep).unwrap();
7202 let mut blocked = task("waiting");
7203 blocked.block(vec![dep.id.clone()], None);
7204 q.put(&mut blocked).unwrap();
7205
7206 let claim = q.claim(&blocked.id).unwrap();
7208 let removed = q.remove(&dep.id, false, &questions).unwrap();
7209 assert!(removed.released.is_empty());
7210 drop(claim);
7211
7212 let mut task = q.get(&blocked.id).unwrap();
7213 assert_eq!(task.status, TaskStatus::Blocked);
7214 assert!(missing_blockers(&q, &questions, &task.blocked_by).is_empty());
7215 assert_eq!(
7216 q.apply_deleted_blockers(&mut task, &questions),
7217 [dep.id.clone()]
7218 );
7219 assert_eq!(task.status, TaskStatus::Queued);
7220 }
7221
7222 #[test]
7223 fn dependency_resolution_short_deleted_reference_releases_only_its_waiters() {
7224 let (dir, q) = queue();
7225 let questions = Questions::at(dir.path().join("questions"));
7226 let mut dep = task("dependency");
7227 dep.id = "20261013-193611-ca5b".into();
7228 q.put(&mut dep).unwrap();
7229 let mut waiting = task("waiting");
7230 waiting.block(vec!["ca5b".into()], None);
7231 q.put(&mut waiting).unwrap();
7232 q.remove(&dep.id, false, &questions).unwrap();
7233 assert_eq!(q.get(&waiting.id).unwrap().status, TaskStatus::Queued);
7234 assert_eq!(
7235 dependency(&q, &questions, "ca5b"),
7236 Dependency::Deleted(dep.id)
7237 );
7238 }
7239
7240 #[test]
7241 fn dependency_resolution_preserves_cross_store_ambiguity_and_exact_ids() {
7242 let (dir, queue) = queue();
7243 let questions = Questions::at(dir.path().join("questions"));
7244 let mut dep = task("dependency");
7245 dep.id = "20261013-193611-ca5b".into();
7246 queue.put(&mut dep).unwrap();
7247 std::fs::create_dir_all(questions.root()).unwrap();
7248 let question_id = "20261014-193611-ca5b";
7249 std::fs::write(questions.path_of(question_id), "unreadable question").unwrap();
7250 assert_eq!(questions.resolve_id("ca5b").unwrap(), question_id);
7251 assert_eq!(
7252 dependency(&queue, &questions, "ca5b"),
7253 Dependency::Ambiguous
7254 );
7255 assert_eq!(
7256 dependency(&queue, &questions, &dep.id),
7257 Dependency::Task(dep.id)
7258 );
7259 assert_eq!(
7260 dependency(&queue, &questions, question_id),
7261 Dependency::Question(question_id.into())
7262 );
7263 assert_eq!(
7264 dependency(&queue, &questions, "missing"),
7265 Dependency::Missing
7266 );
7267 }
7268
7269 #[test]
7270 fn dependency_resolution_directory_errors_are_unknown_not_missing() {
7271 let dir = tempfile::tempdir().unwrap();
7272 let q = Queue::at(dir.path().join("not-a-directory"));
7273 std::fs::write(q.root(), "file").unwrap();
7274 let questions = Questions::at(dir.path().join("questions"));
7275 assert_eq!(dependency(&q, &questions, "ca5b"), Dependency::Unknown);
7276 assert!(missing_blockers(&q, &questions, &["ca5b".into()]).is_empty());
7277 }
7278
7279 #[test]
7280 fn a_dependency_without_a_tombstone_is_still_missing() {
7281 let (dir, q) = queue();
7282 let questions = Questions::at(dir.path().join("questions"));
7283 let mut dep = task("dependency");
7284 q.put(&mut dep).unwrap();
7285 std::fs::remove_file(q.path_of(&dep.id)).unwrap();
7286 assert_eq!(
7287 missing_blockers(&q, &questions, std::slice::from_ref(&dep.id)),
7288 [dep.id.clone()]
7289 );
7290 assert!(deleted_blockers(&q, &questions, std::slice::from_ref(&dep.id)).is_empty());
7291 }
7292
7293 #[test]
7294 fn a_held_dependent_is_left_alone_by_a_dependency_deletion() {
7295 let mut t = task("held");
7296 t.hold_machine(Some("because".to_owned()));
7297 t.blocked_by = vec!["gone".to_owned()];
7298 assert!(!t.dependency_deleted("gone"));
7299 assert_eq!(t.status, TaskStatus::Held);
7300 }
7301
7302 #[test]
7303 fn a_failed_record_removal_takes_the_tombstone_back() {
7304 let (_dir, q) = queue();
7305 let mut t = task("stays");
7306 q.put(&mut t).unwrap();
7307 q.write_tombstone(&t.id).unwrap();
7308 let err = q.remove_record_with_attachments(&t.id, |_| Err(std::io::Error::other("nope")));
7309 assert!(err.is_err());
7310 assert!(!q.was_deleted(&t.id));
7313 }
7314
7315 fn source_file(dir: &Path, name: &str, body: &str) -> PathBuf {
7316 let p = dir.join(name);
7317 std::fs::write(&p, body).unwrap();
7318 p
7319 }
7320
7321 #[test]
7322 fn an_attachment_copy_survives_deleting_its_source() {
7323 let (dir, q) = queue();
7324 let src = source_file(dir.path(), "shot.png", "pixels");
7325 let mut t = task("with a picture");
7326 let names = q.attach(&mut t, std::slice::from_ref(&src)).unwrap();
7327 q.put(&mut t).unwrap();
7328 std::fs::remove_file(&src).unwrap();
7329 assert_eq!(names, ["shot.png"]);
7330 let loaded = q.get(&t.id).unwrap();
7331 let paths = q.attachment_paths(&loaded);
7332 assert_eq!(paths.len(), 1);
7333 assert_eq!(std::fs::read_to_string(&paths[0]).unwrap(), "pixels");
7334 }
7335
7336 #[test]
7337 fn attachment_names_that_could_traverse_or_are_odd_are_refused() {
7338 let (dir, q) = queue();
7339 let mut t = task("bad names");
7340 for name in ["a..b.png", ".hidden", "with space.png", "-x.png"] {
7341 let src = source_file(dir.path(), name, "x");
7342 assert!(
7343 q.attach(&mut t, &[src]).is_err(),
7344 "`{name}` must be refused"
7345 );
7346 }
7347 assert!(!crate::ask::valid_asset_name("C:foo.png"));
7351 #[cfg(not(windows))]
7352 {
7353 let src = source_file(dir.path(), "C:foo.png", "x");
7354 assert!(q.attach(&mut t, &[src]).is_err());
7355 }
7356 let long = format!("{}.png", "a".repeat(70));
7357 let src = source_file(dir.path(), &long, "x");
7358 assert!(q.attach(&mut t, &[src]).is_err());
7359 assert!(t.attachments.is_empty());
7360 assert!(!q.attachments_dir(&t.id).exists());
7361 }
7362
7363 #[test]
7364 fn a_taken_attachment_name_is_numbered_not_overwritten() {
7365 let (dir, q) = queue();
7366 let a = source_file(dir.path(), "shot.png", "one");
7367 let sub = dir.path().join("other");
7368 std::fs::create_dir_all(&sub).unwrap();
7369 let b = source_file(&sub, "shot.png", "two");
7370 let mut t = task("collision");
7371 q.attach(&mut t, &[a]).unwrap();
7372 q.attach(&mut t, &[b]).unwrap();
7373 assert_eq!(t.attachments, ["shot.png", "shot-2.png"]);
7374 let paths = q.attachment_paths(&t);
7375 assert_eq!(std::fs::read_to_string(&paths[0]).unwrap(), "one");
7376 assert_eq!(std::fs::read_to_string(&paths[1]).unwrap(), "two");
7377 }
7378
7379 #[test]
7380 fn a_renumbered_name_stays_inside_the_length_bound() {
7381 let (dir, q) = queue();
7382 let name = format!("{}.png", "a".repeat(60));
7383 assert_eq!(name.len(), 64);
7384 let a = source_file(dir.path(), &name, "one");
7385 let sub = dir.path().join("other");
7386 std::fs::create_dir_all(&sub).unwrap();
7387 let b = source_file(&sub, &name, "two");
7388 let mut t = task("long");
7389 q.attach(&mut t, &[a, b]).unwrap();
7390 assert_eq!(t.attachments.len(), 2);
7391 assert!(
7392 t.attachments
7393 .iter()
7394 .all(|n| crate::ask::valid_asset_name(n))
7395 );
7396 assert!(t.attachments[1].ends_with("-2.png"));
7397 }
7398
7399 #[test]
7400 fn a_failed_attach_keeps_existing_attachments_and_leaves_no_partial_copy() {
7401 let (dir, q) = queue();
7402 let good = source_file(dir.path(), "good.png", "ok");
7403 let mut t = task("partial");
7404 q.attach(&mut t, &[good]).unwrap();
7405 let more = source_file(dir.path(), "more.png", "ok");
7406 let missing = dir.path().join("missing.png");
7407 assert!(q.attach(&mut t, &[more, missing]).is_err());
7408 assert_eq!(t.attachments, ["good.png"]);
7409 let on_disk: Vec<_> = std::fs::read_dir(q.attachments_dir(&t.id))
7410 .unwrap()
7411 .flatten()
7412 .collect();
7413 assert_eq!(on_disk.len(), 1);
7414 }
7415
7416 fn block_put(q: &Queue, t: &Task) -> PathBuf {
7418 let tmp = q.path_of(&t.id).with_extension("json.tmp");
7419 std::fs::create_dir_all(&tmp).unwrap();
7420 tmp
7421 }
7422
7423 #[test]
7424 fn a_failed_put_leaves_no_new_attachment_directory() {
7425 let (dir, q) = queue();
7426 let mut t = task("fresh");
7427 let tmp = block_put(&q, &t);
7428 let src = source_file(dir.path(), "shot.png", "x");
7429 assert!(q.attach_and_put(&mut t, &[src]).is_err());
7430 assert!(t.attachments.is_empty());
7431 assert!(!q.attachments_dir(&t.id).exists());
7432 assert!(!q.path_of(&t.id).exists());
7433 std::fs::remove_dir(tmp).unwrap();
7434 }
7435
7436 #[test]
7437 fn a_failed_put_removes_only_the_copy_it_just_made() {
7438 let (dir, q) = queue();
7439 let mut t = task("edited");
7440 let first = source_file(dir.path(), "first.png", "1");
7441 q.attach_and_put(&mut t, &[first]).unwrap();
7442 block_put(&q, &t);
7443 let second = source_file(dir.path(), "second.png", "2");
7444 assert!(q.attach_and_put(&mut t, &[second]).is_err());
7445 assert_eq!(t.attachments, ["first.png"]);
7446 let on_disk: Vec<_> = std::fs::read_dir(q.attachments_dir(&t.id))
7447 .unwrap()
7448 .flatten()
7449 .map(|e| e.file_name().to_string_lossy().into_owned())
7450 .collect();
7451 assert_eq!(on_disk, ["first.png"]);
7452 assert_eq!(q.get(&t.id).unwrap().attachments, ["first.png"]);
7453 }
7454
7455 #[test]
7456 fn a_leftover_removing_directory_is_swept_by_the_next_removal() {
7457 let (dir, q) = queue();
7458 let questions = Questions::at(dir.path().join("questions"));
7459 let gone = task("gone");
7460 let mut other = task("other");
7461 let mut live = task("live");
7462 q.put(&mut other).unwrap();
7463 q.put(&mut live).unwrap();
7464 let orphan = q.root.join(format!("{}.attachments.removing", gone.id));
7467 std::fs::create_dir_all(&orphan).unwrap();
7468 std::fs::write(orphan.join("shot.png"), "x").unwrap();
7469 let busy = q.root.join(format!("{}.attachments.removing", live.id));
7472 std::fs::create_dir_all(&busy).unwrap();
7473
7474 q.remove(&other.id, false, &questions).unwrap();
7475 assert!(!orphan.exists(), "an orphan is swept");
7476 assert!(busy.exists(), "a removal in progress is left alone");
7477 }
7478
7479 #[test]
7480 fn a_blocked_aside_rename_fails_the_removal_and_loses_nothing() {
7481 let (dir, q) = queue();
7482 let questions = Questions::at(dir.path().join("questions"));
7483 let mut t = task("stuck");
7484 let src = source_file(dir.path(), "shot.png", "x");
7485 q.attach_and_put(&mut t, &[src]).unwrap();
7486 let aside = q.root.join(format!("{}.attachments.removing", t.id));
7489 std::fs::create_dir_all(&aside).unwrap();
7490 std::fs::write(aside.join("old.png"), "o").unwrap();
7491 assert!(q.remove(&t.id, false, &questions).is_err());
7492 assert!(q.path_of(&t.id).exists());
7493 assert!(q.attachments_dir(&t.id).join("shot.png").is_file());
7494 }
7495
7496 #[test]
7497 fn a_failed_record_removal_puts_the_attachments_back() {
7498 let (dir, q) = queue();
7499 let mut t = task("rollback");
7500 let src = source_file(dir.path(), "shot.png", "x");
7501 q.attach_and_put(&mut t, &[src]).unwrap();
7502 let err = q
7503 .remove_record_with_attachments(&t.id, |_| {
7504 Err(std::io::Error::other("injected failure"))
7505 })
7506 .unwrap_err();
7507 assert!(format!("{err:#}").contains("injected failure"));
7508 assert!(q.path_of(&t.id).exists());
7509 assert!(q.attachments_dir(&t.id).join("shot.png").is_file());
7510 assert!(
7511 !q.root
7512 .join(format!("{}.attachments.removing", t.id))
7513 .exists()
7514 );
7515 }
7516
7517 #[test]
7518 fn editing_a_task_keeps_its_attachments() {
7519 let (dir, q) = queue();
7520 let src = source_file(dir.path(), "shot.png", "x");
7521 let mut t = task("editable");
7522 q.attach(&mut t, &[src]).unwrap();
7523 t.edit("new".to_owned(), "new text".to_owned()).unwrap();
7524 q.put(&mut t).unwrap();
7525 assert_eq!(q.get(&t.id).unwrap().attachments, ["shot.png"]);
7526 }
7527
7528 #[test]
7529 fn removing_a_task_deletes_its_attachments() {
7530 let (dir, q) = queue();
7531 let questions = Questions::at(dir.path().join("questions"));
7532 let src = source_file(dir.path(), "shot.png", "x");
7533 let mut t = task("doomed");
7534 q.attach(&mut t, &[src]).unwrap();
7535 q.put(&mut t).unwrap();
7536 assert!(q.attachments_dir(&t.id).is_dir());
7537 q.remove(&t.id, false, &questions).unwrap();
7538 assert!(!q.attachments_dir(&t.id).exists());
7539 assert!(q.list().is_empty());
7540 }
7541
7542 #[test]
7543 fn a_task_written_before_attachments_still_reads() {
7544 let (_dir, q) = queue();
7545 let mut t = task("old");
7546 q.put(&mut t).unwrap();
7547 let path = q.path_of(&t.id);
7548 let mut v: serde_json::Value =
7549 serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
7550 v.as_object_mut().unwrap().remove("attachments");
7551 std::fs::write(&path, v.to_string()).unwrap();
7552 assert!(q.get(&t.id).unwrap().attachments.is_empty());
7553 }
7554
7555 #[test]
7556 fn attachment_paths_are_absolute_even_when_the_root_is_relative() {
7557 let q = Queue::at(PathBuf::from("relative-queue"));
7558 let mut t = task("rel");
7559 t.attachments.push("shot.png".to_owned());
7560 let paths = q.attachment_paths(&t);
7561 assert!(paths[0].is_absolute(), "{}", paths[0].display());
7562 assert!(paths[0].ends_with(format!("{}.attachments/shot.png", t.id)));
7563 }
7564
7565 fn upgrade_parked(id: &str, started: &str) -> Task {
7566 let mut t = task(id);
7567 t.id = id.into();
7568 t.start(format!("run-{id}"));
7569 t.park("upgrade");
7570 t.record_pass_at(
7571 &format!("run-{id}"),
7572 0,
7573 Some(started.parse().unwrap()),
7574 1,
7575 Some(crate::run::ParkCause::Upgrade {
7576 from: "old".into(),
7577 to: None,
7578 }),
7579 );
7580 t
7581 }
7582
7583 #[test]
7584 fn upgrade_resume_order_follows_dispatch_claim_not_graph_start() {
7585 let stamp = |id: &str, dispatched: &str, started: &str| {
7587 let mut t = task(id);
7588 t.id = id.into();
7589 t.start(format!("run-{id}"));
7590 t.park("upgrade");
7591 t.dispatched_at = Some(dispatched.parse().unwrap());
7592 t.record_pass_at(
7593 &format!("run-{id}"),
7594 0,
7595 Some(started.parse().unwrap()),
7596 1,
7597 Some(crate::run::ParkCause::Upgrade {
7598 from: "old".into(),
7599 to: None,
7600 }),
7601 );
7602 t
7603 };
7604 let a = stamp("a", "2026-10-22T00:00:01Z", "2026-10-22T00:00:09Z");
7605 let b = stamp("b", "2026-10-22T00:00:02Z", "2026-10-22T00:00:03Z");
7606 assert!(dispatch_order(&a, &b).is_lt());
7607 }
7608
7609 #[test]
7610 fn upgrade_resume_order_survives_queue_reload_and_reversed_settlement() {
7611 let (_dir, q) = queue();
7612 let mut later = upgrade_parked("later", "2026-10-22T00:00:02Z");
7613 let mut earlier = upgrade_parked("earlier", "2026-10-22T00:00:01Z");
7614 earlier.priority = -10;
7615 let mut fresh = task("fresh");
7616 fresh.id = "newer".into();
7617 fresh.priority = 100;
7618 for t in [&mut fresh, &mut later, &mut earlier] {
7619 q.put(t).unwrap();
7620 }
7621 let reloaded = Queue::at(q.root().to_owned());
7622 let mut tasks = reloaded.list();
7623 tasks.sort_unstable_by(dispatch_order);
7624 assert_eq!(
7625 tasks.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
7626 vec!["earlier", "later", "newer"]
7627 );
7628 assert_eq!(reloaded.next_runnable().unwrap().id, "earlier");
7629 assert_eq!(reloaded.get("earlier").unwrap().attempts, 0);
7630 }
7631
7632 #[test]
7633 fn upgrade_resume_legacy_order_uses_settlement_and_id() {
7634 let mut a = upgrade_parked("a", "2026-10-22T00:00:02Z");
7635 let mut b = upgrade_parked("b", "2026-10-22T00:00:01Z");
7636 for t in [&mut a, &mut b] {
7637 let mut value = serde_json::to_value(&*t).unwrap();
7638 value["passes"][0]
7639 .as_object_mut()
7640 .unwrap()
7641 .remove("started_at");
7642 *t = serde_json::from_value(value).unwrap();
7643 }
7644 assert!(dispatch_order(&a, &b).is_lt());
7645 b.passes[0].settled_at = a.passes[0].settled_at;
7646 assert!(dispatch_order(&a, &b).is_lt());
7647 }
7648
7649 #[test]
7650 fn upgrade_resume_key_excludes_other_parks_and_explicit_task_changes() {
7651 let original = upgrade_parked("a", "2026-10-22T00:00:01Z");
7652 assert!(original.upgrade_resume_key().is_some());
7653 for cause in [
7654 crate::run::ParkCause::Operator,
7655 crate::run::ParkCause::Question,
7656 crate::run::ParkCause::Interrupt {
7657 reason: "interrupt".into(),
7658 },
7659 crate::run::ParkCause::Unspecified,
7660 ] {
7661 let mut t = original.clone();
7662 t.passes[0].parked = Some(cause);
7663 assert!(t.upgrade_resume_key().is_none());
7664 let mut fresh = task("fresh");
7665 fresh.priority = 1;
7666 assert!(dispatch_order(&fresh, &t).is_lt());
7667 }
7668 let mut t = original.clone();
7669 t.release();
7670 assert!(t.upgrade_resume_key().is_none());
7671 t.edit("edited".into(), "new instruction".into()).unwrap();
7672 assert!(t.upgrade_resume_key().is_none());
7673 let mut t = original.clone();
7674 t.requeue();
7675 t.status = TaskStatus::Parked;
7676 assert!(t.upgrade_resume_key().is_none());
7677 let mut t = original.clone();
7678 t.start("different-run".into());
7679 t.park("no upgrade");
7680 assert!(t.upgrade_resume_key().is_none());
7681 }
7682
7683 #[test]
7684 fn explicitly_resumed_older_run_becomes_current_without_duplicate_history() {
7685 let dir = tempfile::tempdir().unwrap();
7686 let q = Queue::at(dir.path().join("queue"));
7687 let mut t = task("resume");
7688 t.start("A".into());
7689 t.record_pass("A", 0, 1, None);
7690 t.start("B".into());
7691 q.put(&mut t).unwrap();
7692 assert_eq!(t.runs, vec!["A", "B"]);
7693 t.start("A".into());
7694 t.record_pass("A", 1, 3, None);
7695 q.put(&mut t).unwrap();
7696 let saved = q.get(&t.id).unwrap();
7697 assert_eq!(saved.runs, vec!["B", "A"]);
7698 assert_eq!(saved.runs.last().map(String::as_str), Some("A"));
7699 assert_eq!(saved.attempts, 3);
7700 assert_eq!(saved.passes.len(), 2);
7701 assert_eq!(saved.passes[0].run, "A");
7702 assert_eq!(saved.passes[1].run, "A");
7703 }
7704
7705 #[test]
7706 fn repeated_start_records_one_run_and_separate_passes() {
7707 let mut t = task("resume");
7708 t.start("same-run".into());
7709 t.record_pass("same-run", 0, 1, None);
7710 t.start("same-run".into());
7711 t.record_pass("same-run", 1, 2, None);
7712 assert_eq!(t.runs, vec!["same-run"]);
7713 assert_eq!(t.attempts, 2);
7714 assert_eq!(t.passes.len(), 2);
7715 }
7716
7717 #[test]
7718 fn link_run_adds_a_run_once_and_touches_nothing_else() {
7719 let dir = tempfile::tempdir().unwrap();
7720 let queue = Queue::at(dir.path().join("queue"));
7721 let mut t = Task::new(
7722 "t".to_owned(),
7723 "do it".to_owned(),
7724 PathBuf::from("."),
7725 Source::Human,
7726 );
7727 queue.put(&mut t).unwrap();
7728 let before = queue.get(&t.id).unwrap();
7729
7730 let linked = queue.link_run(&t.id[..4], "20260930-092817-ec34").unwrap();
7731 assert_eq!(linked.runs, vec!["20260930-092817-ec34".to_owned()]);
7732 assert_eq!(linked.status, before.status);
7733 assert_eq!(linked.attempts, before.attempts);
7734 assert_eq!(linked.interrupt, before.interrupt);
7735
7736 let again = queue.link_run(&t.id, "20260930-092817-ec34").unwrap();
7737 assert_eq!(again.runs.len(), 1, "linking twice must not duplicate");
7738 assert_eq!(queue.get(&t.id).unwrap().runs.len(), 1);
7739 assert!(queue.link_run("no-such-task", "r").is_err());
7740 }
7741
7742 #[test]
7743 fn put_keeps_a_run_linked_after_the_writer_took_its_snapshot() {
7744 let dir = tempfile::tempdir().unwrap();
7745 let queue = Queue::at(dir.path().join("queue"));
7746 let mut t = Task::new(
7747 "t".to_owned(),
7748 "do it".to_owned(),
7749 PathBuf::from("."),
7750 Source::Human,
7751 );
7752 queue.put(&mut t).unwrap();
7753 let mut snapshot = queue.get(&t.id).unwrap();
7755 queue.link_run(&t.id, "20260930-092817-ec34").unwrap();
7756
7757 snapshot.start("20260930-000000-aaaa".to_owned());
7758 queue.put(&mut snapshot).unwrap();
7759
7760 let stored = queue.get(&t.id).unwrap();
7761 assert!(stored.runs.contains(&"20260930-092817-ec34".to_owned()));
7762 assert!(stored.runs.contains(&"20260930-000000-aaaa".to_owned()));
7763 assert_eq!(stored.attempts, 1);
7764 }
7765
7766 #[test]
7767 fn concurrent_links_and_daemon_saves_lose_nothing() {
7768 let dir = tempfile::tempdir().unwrap();
7769 let queue = Queue::at(dir.path().join("queue"));
7770 let mut t = Task::new(
7771 "t".to_owned(),
7772 "do it".to_owned(),
7773 PathBuf::from("."),
7774 Source::Human,
7775 );
7776 queue.put(&mut t).unwrap();
7777 let id = t.id.clone();
7778
7779 let linkers: Vec<_> = (0..4)
7780 .map(|n| {
7781 let (queue, id) = (queue.clone(), id.clone());
7782 std::thread::spawn(move || {
7783 for k in 0..10 {
7784 queue
7785 .link_run(&id, &format!("20260930-00000{n}-l{k:03}"))
7786 .unwrap();
7787 }
7788 })
7789 })
7790 .collect();
7791 let mut mine = queue.get(&id).unwrap();
7794 for k in 0..10 {
7795 mine.start(format!("20260930-000009-d{k:03}"));
7796 queue.put(&mut mine).unwrap();
7797 }
7798 for l in linkers {
7799 l.join().unwrap();
7800 }
7801
7802 let stored = queue.get(&id).unwrap();
7803 assert_eq!(stored.runs.len(), 50, "{:?}", stored.runs);
7804 assert_eq!(
7805 stored.attempts, 10,
7806 "linking never rewinds the daemon's work"
7807 );
7808 }
7809
7810 fn age_lock(path: &Path) {
7811 let f = std::fs::OpenOptions::new().write(true).open(path).unwrap();
7812 f.set_modified(std::time::SystemTime::now() - std::time::Duration::from_secs(60))
7813 .unwrap();
7814 }
7815
7816 #[test]
7817 fn concurrent_stale_takeover_yields_one_holder() {
7818 use std::sync::atomic::{AtomicUsize, Ordering};
7819 use std::sync::{Arc, Barrier};
7820 for _ in 0..5 {
7821 let dir = tempfile::tempdir().unwrap();
7822 let q = Queue::at(dir.path().to_path_buf());
7823 let lock = dir.path().join("t.write-lock");
7824 std::fs::write(&lock, "dead-0000").unwrap();
7825 age_lock(&lock);
7826 let n = 6;
7827 let barrier = Arc::new(Barrier::new(n));
7828 let (now, max) = (Arc::new(AtomicUsize::new(0)), Arc::new(AtomicUsize::new(0)));
7829 let handles: Vec<_> = (0..n)
7830 .map(|_| {
7831 let (q, b, now, max) = (q.clone(), barrier.clone(), now.clone(), max.clone());
7832 std::thread::spawn(move || {
7833 b.wait();
7834 let g = q.lock_task("t").unwrap();
7835 let held = now.fetch_add(1, Ordering::SeqCst) + 1;
7836 max.fetch_max(held, Ordering::SeqCst);
7837 std::thread::sleep(std::time::Duration::from_millis(20));
7838 now.fetch_sub(1, Ordering::SeqCst);
7839 drop(g);
7840 })
7841 })
7842 .collect();
7843 for h in handles {
7844 h.join().unwrap();
7845 }
7846 assert_eq!(max.load(Ordering::SeqCst), 1);
7847 assert!(!lock.exists());
7848 }
7849 }
7850
7851 #[test]
7852 fn dropping_a_replaced_lock_leaves_the_new_holders_token() {
7853 let dir = tempfile::tempdir().unwrap();
7854 let q = Queue::at(dir.path().to_path_buf());
7855 let lock = dir.path().join("t.write-lock");
7856 let a = q.lock_task("t").unwrap();
7857 let replacement = owner_token();
7860 std::fs::write(&lock, &replacement).unwrap();
7861 drop(a);
7862 assert_eq!(std::fs::read_to_string(&lock).unwrap(), replacement);
7863 }
7864
7865 #[test]
7866 fn aged_live_task_lock_excludes_updates_until_retirement_releases_it() {
7867 let dir = tempfile::tempdir().unwrap();
7868 let q = Queue::at(dir.path().to_path_buf());
7869 let held = q.lock_task("t").unwrap();
7870 let path = dir.path().join("t.write-lock");
7871 age_lock(&path);
7872 assert!(!break_stale(&path, &held.token));
7873 let (started_tx, started_rx) = std::sync::mpsc::channel();
7874 let (acquired_tx, acquired_rx) = std::sync::mpsc::channel();
7875 let updater = std::thread::spawn(move || {
7876 started_tx.send(()).unwrap();
7877 let _write = q.lock_task("t").unwrap();
7878 acquired_tx.send(()).unwrap();
7879 });
7880 started_rx.recv().unwrap();
7881 assert!(
7882 acquired_rx
7883 .recv_timeout(std::time::Duration::from_millis(100))
7884 .is_err()
7885 );
7886 assert_eq!(std::fs::read_to_string(&path).unwrap(), held.token);
7887 drop(held);
7888 acquired_rx
7889 .recv_timeout(std::time::Duration::from_secs(2))
7890 .unwrap();
7891 updater.join().unwrap();
7892 assert!(!path.exists());
7893 }
7894
7895 #[test]
7896 fn break_stale_leaves_a_lock_that_replaced_the_one_judged() {
7897 let dir = tempfile::tempdir().unwrap();
7898 let lock = dir.path().join("t.write-lock");
7899 std::fs::write(&lock, "new-token").unwrap();
7900 assert!(!break_stale(&lock, "old-token"));
7901 assert_eq!(std::fs::read_to_string(&lock).unwrap(), "new-token");
7902 assert!(!break_stale(&lock, "new-token"));
7904 assert!(lock.exists());
7905 age_lock(&lock);
7906 assert!(break_stale(&lock, "new-token"));
7907 assert!(!lock.exists());
7908 }
7909
7910 #[test]
7911 fn a_stale_break_marker_is_recovered_and_a_fresh_one_is_respected() {
7912 let dir = tempfile::tempdir().unwrap();
7913 let lock = dir.path().join("t.write-lock");
7914 std::fs::write(&lock, "dead-1").unwrap();
7915 age_lock(&lock);
7916 let marker = break_marker(&lock, "dead-1");
7917 std::fs::write(&marker, "crashed-remover").unwrap();
7918 assert!(!break_stale(&lock, "dead-1"));
7920 assert!(lock.exists());
7921 age_lock(&marker);
7923 assert!(break_stale(&lock, "dead-1"));
7924 assert!(!lock.exists());
7925 assert!(!marker.exists());
7926 }
7927
7928 fn chat_task() -> Task {
7929 Task::new(
7930 "t".to_owned(),
7931 "do t".to_owned(),
7932 PathBuf::from("."),
7933 Source::Agent {
7934 run: "20260902-000000-beef".to_owned(),
7935 node: CHAT_NODE.to_owned(),
7936 },
7937 )
7938 }
7939
7940 #[test]
7941 fn a_blocked_hold_keeps_its_anchor_but_a_new_run_starts_a_new_hold() {
7942 let mut t = chat_task();
7943 t.hold_machine(Some("waiting".into()));
7944 let old: Timestamp = "2020-01-01T00:00:00Z".parse().unwrap();
7945 t.held_at = Some(old);
7946 t.block(vec!["decision".into()], None);
7947 t.hold_machine(Some("same waiting decision".into()));
7948 assert_eq!(t.held_at, Some(old));
7949 t.start("real-new-run".into());
7950 t.fail("new failure", 1);
7951 assert_ne!(
7952 t.held_at,
7953 Some(old),
7954 "old answers cannot approve a new hold"
7955 );
7956 }
7957
7958 #[test]
7959 fn legacy_delivery_survives_upgrade_and_a_no_progress_run_link() {
7960 let (_dir, queue) = queue();
7961 let mut t = chat_task();
7962 t.start("old-run".into());
7963 t.hold_machine(Some("operator is considering recovery".into()));
7964 t.chat_notice = Some(ChatNotice {
7965 key: format!("held#{}", t.held_at.unwrap()),
7966 at: Timestamp::now(),
7967 outcome: ChatNoticeOutcome::Posted,
7968 });
7969 let mut raw = serde_json::to_value(&t).unwrap();
7970 raw.as_object_mut().unwrap().remove("chat_notices");
7971 raw.as_object_mut().unwrap().remove("hold_notice_cause");
7972 std::fs::create_dir_all(queue.path_of(&t.id).parent().unwrap()).unwrap();
7973 std::fs::write(queue.path_of(&t.id), serde_json::to_string(&raw).unwrap()).unwrap();
7974 assert_eq!(queue.get(&t.id).unwrap().chat_notice_due(), None);
7975 queue
7976 .modify(&t.id, |task| {
7977 task.requeue();
7978 task.link_run("unprepared-run");
7979 task.startup_notice_cause("startup-source");
7980 task.fail("same unresolved preflight", 0);
7981 true
7982 })
7983 .unwrap();
7984 assert_eq!(queue.get(&t.id).unwrap().chat_notice_due(), None);
7985 queue
7986 .modify(&t.id, |task| {
7987 task.succeed(completion(task));
7988 true
7989 })
7990 .unwrap();
7991 assert!(
7992 queue
7993 .get(&t.id)
7994 .unwrap()
7995 .chat_notice_due()
7996 .unwrap()
7997 .starts_with("done:")
7998 );
7999 }
8000
8001 #[test]
8002 fn a_dependency_wait_does_not_change_when_released_and_blocked_again() {
8003 let mut t = chat_task();
8004 t.block(vec!["a".into(), "b".into()], Some("waiting".into()));
8005 let key = t.chat_notice_key().unwrap();
8006 t.chat_notices.push(key);
8007 t.release();
8008 t.block(
8009 vec!["b".into(), "a".into(), "a".into()],
8010 Some("still waiting on prerequisites".into()),
8011 );
8012 assert_eq!(t.chat_notice_due(), None);
8013 t.block(
8014 vec!["new-question".into()],
8015 Some("different decision".into()),
8016 );
8017 assert!(t.chat_notice_due().is_some());
8018 }
8019
8020 #[test]
8021 fn running_startup_failures_preserve_stage_and_report_distinct_blockers() {
8022 let mut t = chat_task();
8023 t.start("existing-run".into());
8024 t.fail("implementation failed", 1);
8025 let failed = t.chat_notice_key().unwrap();
8026 t.chat_notices.push(failed.clone());
8027 t.release_operator("test", None);
8028 t.start("existing-run".into());
8029 t.fail_startup("startup-source", "same unresolved recovery source", 1);
8030 assert_eq!(
8031 t.chat_notice_due(),
8032 None,
8033 "no-progress recovery stays quiet"
8034 );
8035 t.release_operator("test", None);
8036 t.start("existing-run".into());
8037 t.fail_startup("startup-attachments", "attachment missing", 1);
8038 let attachments = t.chat_notice_due().expect("new attachment blocker");
8039 assert_ne!(attachments, failed);
8040 assert_eq!(
8041 t.hold_notice_cause.as_ref().unwrap().stage,
8042 "startup-attachments"
8043 );
8044 t.chat_notices.push(attachments);
8045 t.release_operator("test", None);
8046 t.start("existing-run".into());
8047 t.fail_startup(
8048 "startup-attachments",
8049 "same missing attachment, reworded",
8050 1,
8051 );
8052 assert_eq!(
8053 t.chat_notice_due(),
8054 None,
8055 "same stage after attempt counter reset"
8056 );
8057 t.release_operator("test", None);
8058 t.start("existing-run".into());
8059 t.fail_startup("startup-config", "different preflight stage", 1);
8060 assert!(t.chat_notice_due().is_some());
8061 assert_eq!(
8062 t.hold_notice_cause.as_ref().unwrap().stage,
8063 "startup-config"
8064 );
8065 }
8066
8067 #[test]
8068 fn structured_causes_preserve_no_progress_retries_and_report_new_passes() {
8069 let mut t = chat_task();
8070 t.hold_machine(Some("startup source missing".into()));
8071 t.startup_notice_cause("startup-source");
8072 let first = t.chat_notice_key().unwrap();
8073 t.chat_notices.push(first.clone());
8074 t.release_operator("test", None);
8075 t.startup_notice_cause("startup-source");
8076 t.hold_machine(Some("same source cannot be read".into()));
8077 assert_eq!(t.chat_notice_due(), None);
8078 t.startup_notice_cause("startup-config");
8079 assert!(t.chat_notice_due().is_some(), "different startup stage");
8080 t.notice_cause("failed", Some("existing-run"), Some(0));
8081 let run_failure = t.chat_notice_key().unwrap();
8082 t.chat_notices.push(run_failure.clone());
8083 t.release_operator("test", None);
8084 t.startup_notice_cause("startup-source");
8085 t.hold_machine(Some("no new work happened".into()));
8086 assert_eq!(t.chat_notice_due(), None);
8087 t.notice_cause("failed", Some("existing-run"), Some(1));
8088 assert!(t.chat_notice_due().is_some(), "a real resumed pass failed");
8089 assert_ne!(t.chat_notice_key().unwrap(), run_failure);
8090 }
8091
8092 #[test]
8093 fn legacy_hold_baseline_does_not_replay_or_hide_new_failures_and_completion() {
8094 let mut t = chat_task();
8095 t.hold_machine(Some("still waiting".into()));
8096 t.chat_notice = Some(ChatNotice {
8097 key: "held#2026-10-14T00:00:00Z".into(),
8098 at: Timestamp::now(),
8099 outcome: ChatNoticeOutcome::Posted,
8100 });
8101 assert_eq!(t.chat_notice_due(), None, "old hold baseline");
8102 t.import_chat_notice();
8103 t.notice_cause("failed", Some("new-run"), Some(0));
8104 assert!(t.chat_notice_due().is_some(), "new producer evidence");
8105 t.succeed(completion(&t));
8106 assert!(t.chat_notice_due().unwrap().starts_with("done:"));
8107 }
8108
8109 #[test]
8110 fn a_chat_notice_is_due_only_for_a_final_state_and_only_once() {
8111 let mut t = chat_task();
8112 assert_eq!(t.chat_notice_due(), None, "queued");
8113 t.start("r1".to_owned());
8114 assert_eq!(t.chat_notice_due(), None, "running");
8115 t.fail("boom", 3);
8116 assert_eq!(t.status, TaskStatus::Failed);
8117 assert_eq!(t.chat_notice_due(), None, "a retried failure is not final");
8118 t.start("r2".to_owned());
8119 t.park("upgrade");
8120 assert_eq!(t.chat_notice_due(), None, "parked");
8121 t.fail("boom", 1);
8122 assert_eq!(t.status, TaskStatus::Held);
8123 let key = t
8124 .chat_notice_due()
8125 .expect("held on the last attempt is final");
8126 t.chat_notice = Some(ChatNotice {
8127 key,
8128 at: Timestamp::now(),
8129 outcome: ChatNoticeOutcome::Posted,
8130 });
8131 assert_eq!(t.chat_notice_due(), None, "same hold, no second notice");
8132 t.release();
8133 assert_eq!(t.chat_notice_due(), None, "requeued after a release");
8134 t.start("r3".to_owned());
8135 t.succeed(completion(&t));
8136 assert!(t.chat_notice_due().is_some(), "done is a new final state");
8137 }
8138
8139 #[test]
8140 fn legacy_completion_receipts_do_not_suppress_new_occurrences() {
8141 for key in ["done", "done#0", "done#1", "done#12"] {
8142 let mut t = chat_task();
8143 t.status = TaskStatus::Done;
8144 t.chat_notice = Some(ChatNotice {
8145 key: key.to_owned(),
8146 at: Timestamp::now(),
8147 outcome: ChatNoticeOutcome::Posted,
8148 });
8149 assert_eq!(t.chat_notice_key().as_deref(), Some("done"));
8150 assert_eq!(t.chat_notice_due(), None, "legacy recorded key: {key}");
8151 let mut context = completion(&t);
8152 context.reason = Some("inspect again".into());
8153 t.reopen(context).unwrap();
8154 t.start("r2".to_owned());
8155 t.succeed(completion(&t));
8156 assert!(t.chat_notice_key().unwrap().starts_with("done:"));
8157 assert!(
8158 t.chat_notice_due().is_some(),
8159 "new occurrence, old receipt: {key}"
8160 );
8161 }
8162 }
8163
8164 #[test]
8165 fn a_release_without_progress_keeps_the_unresolved_notice_cause() {
8166 let mut t = chat_task();
8167 t.hold_manual(Some("wait".to_owned()));
8168 let first = t.chat_notice_due().expect("held");
8169 t.chat_notice = Some(ChatNotice {
8170 key: first.clone(),
8171 at: Timestamp::now(),
8172 outcome: ChatNoticeOutcome::Posted,
8173 });
8174 t.hold_manual(Some("still waiting".to_owned()));
8175 assert_eq!(t.chat_notice_due(), None, "a re-hold keeps its start");
8176 t.release();
8177 std::thread::sleep(std::time::Duration::from_millis(5));
8178 t.hold_manual(None);
8179 assert_eq!(t.chat_notice_due(), None, "no progress, same cause");
8180 }
8181
8182 fn human_key(t: &Task) -> Option<String> {
8183 t.chat_notice_key().filter(|k| k.starts_with("done:"))
8184 }
8185
8186 #[test]
8187 fn a_chat_notice_needs_a_chat_source_and_a_current_schema() {
8188 let mut human = task("h");
8189 human.succeed(completion(&human));
8190 assert!(
8191 human
8192 .chat_notice_due()
8193 .is_some_and(|k| k.starts_with("done:")),
8194 "a completion this build recorded reaches the linked task chat"
8195 );
8196 human.completion_history[0].schema = COMPLETION_REPORT_SCHEMA - 1;
8197 assert_eq!(
8198 human.chat_notice_due(),
8199 None,
8200 "an older completion stays quiet"
8201 );
8202 let mut held_human = task("hh");
8203 held_human.hold_manual(None);
8204 assert_eq!(
8205 held_human.chat_notice_due(),
8206 None,
8207 "only completion is reported"
8208 );
8209 let mut inherited = task("i");
8211 inherited.origin_chat = Some("20260902-000000-beef".to_owned());
8212 inherited.succeed(completion(&inherited));
8213 assert_eq!(
8214 inherited.chat_notice_due(),
8215 human_key(&inherited),
8216 "reported as a human-filed completion, not as a chat's own task"
8217 );
8218 assert_eq!(inherited.filed_by_chat(), None);
8219 let mut old = chat_task();
8220 old.schema = 12;
8221 old.status = TaskStatus::Done;
8222 assert_eq!(old.chat_notice_due(), None, "history is not replayed");
8223 let mut live = chat_task();
8224 live.schema = 12;
8225 live.start("r1".to_owned());
8226 live.succeed(completion(&live));
8227 assert!(live.chat_notice_due().is_some(), "started by this build");
8228 let mut held = chat_task();
8229 held.schema = 12;
8230 held.hold_machine(Some("config".to_owned()));
8231 assert!(held.chat_notice_due().is_some(), "held before any start");
8232 }
8233
8234 #[test]
8235 fn a_stale_snapshot_does_not_rewind_a_recorded_chat_notice() {
8236 let tmp = tempfile::tempdir().expect("tempdir");
8237 let q = Queue::at(tmp.path().join("queue"));
8238 let mut t = chat_task();
8239 t.succeed(completion(&t));
8240 q.put(&mut t).expect("put");
8241 let mut stale = q.get(&t.id).expect("get");
8242 let key = t.chat_notice_due().expect("due");
8243 q.modify(&t.id, |x| {
8244 x.chat_notice = Some(ChatNotice {
8245 key: key.clone(),
8246 at: Timestamp::now(),
8247 outcome: ChatNoticeOutcome::Posted,
8248 });
8249 true
8250 })
8251 .expect("modify");
8252 q.put(&mut stale).expect("stale put");
8253 assert_eq!(q.get(&t.id).expect("get").chat_notice_due(), None);
8254 }
8255
8256 #[test]
8257 fn empty_sources_are_omitted_so_older_builds_still_read_the_task() {
8258 let mut t = task("plain");
8261 let value = serde_json::to_value(&t).unwrap();
8262 assert!(value.get("sources").is_none(), "{value}");
8263 t.sources.pick_commits.push(crate::refs::Input {
8264 token: "abc1234".into(),
8265 sha: "a".repeat(40),
8266 provenance: crate::refs::Provenance::ExplicitCli,
8267 });
8268 let value = serde_json::to_value(&t).unwrap();
8269 assert_eq!(value["sources"]["pick_commits"][0]["sha"], "a".repeat(40));
8270 let restored: Task = serde_json::from_value(value).unwrap();
8271 assert_eq!(restored.sources, t.sources);
8272 }
8273
8274 fn queue_with_ids(dir: &Path, ids: &[&str]) -> Queue {
8276 let ids: Vec<String> = ids.iter().map(|s| (*s).to_owned()).collect();
8277 let n = std::sync::atomic::AtomicUsize::new(0);
8278 Queue::at(dir.join("queue")).with_id_source(move || {
8279 let i = n.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
8280 ids.get(i)
8281 .cloned()
8282 .unwrap_or_else(|| format!("20260101-000000-f{i:03x}"))
8283 })
8284 }
8285
8286 const TAKEN: &str = "20260101-000000-aaaa";
8287
8288 #[test]
8289 fn a_new_task_never_merges_into_a_record_with_its_candidate_id() {
8290 let dir = tempfile::tempdir().unwrap();
8291 let q = queue_with_ids(dir.path(), &[TAKEN, TAKEN]);
8292 let mut first = task("first");
8293 first.start("run-1".into());
8294 first.succeed(completion(&first));
8295 q.put(&mut first).unwrap();
8296 assert_eq!(first.id, TAKEN);
8297 let stored_before = q.get(&first.id).unwrap();
8298 assert!(!stored_before.runs.is_empty());
8299
8300 let mut second = task("second");
8301 q.put(&mut second).unwrap();
8302
8303 assert_ne!(second.id, first.id);
8304 assert!(second.runs.is_empty());
8305 assert!(second.passes.is_empty());
8306 assert!(second.chat_notices.is_empty());
8307 assert!(second.chat_notice.is_none());
8308 assert_eq!(second.chat_notice_due(), task("fresh").chat_notice_due());
8309 let a = q.get(&first.id).unwrap();
8310 let b = q.get(&second.id).unwrap();
8311 assert_eq!(a.title, "first");
8312 assert_eq!(a.runs, stored_before.runs);
8313 assert_eq!(a.passes, stored_before.passes);
8314 assert_eq!(a.chat_notices, stored_before.chat_notices);
8315 assert_eq!(a.chat_notice, stored_before.chat_notice);
8316 assert_eq!(a.chat_notice_due(), stored_before.chat_notice_due());
8317 assert_eq!(b.title, "second");
8318 assert!(b.runs.is_empty());
8319 assert!(b.passes.is_empty());
8320 assert!(b.chat_notice.is_none());
8321
8322 let mut again = q.get(&second.id).unwrap();
8324 again.title = "second, edited".into();
8325 q.put(&mut again).unwrap();
8326 assert_eq!(q.get(&second.id).unwrap().title, "second, edited");
8327 assert_eq!(q.list().len(), 2);
8328 }
8329
8330 #[test]
8331 fn a_new_task_skips_an_id_with_an_orphaned_claim_or_attachments() {
8332 let dir = tempfile::tempdir().unwrap();
8333 let q = queue_with_ids(dir.path(), &["orphan-lock", "orphan-dir", "free"]);
8334 std::fs::create_dir_all(q.root()).unwrap();
8335 std::fs::write(q.root().join("orphan-lock.lock"), "x").unwrap();
8336 std::fs::create_dir_all(q.attachments_dir("orphan-dir")).unwrap();
8337 let mut t = task("t");
8338 q.put(&mut t).unwrap();
8339 assert_eq!(t.id, "free");
8340 }
8341
8342 #[test]
8343 fn a_claimed_new_task_holds_the_claim_on_the_reserved_id() {
8344 let dir = tempfile::tempdir().unwrap();
8345 let q = queue_with_ids(dir.path(), &[TAKEN, TAKEN]);
8346 let mut first = task("first");
8347 q.put(&mut first).unwrap();
8348 let mut second = task("second");
8349 let claim = q.file_claimed(&mut second).unwrap();
8350 assert_ne!(second.id, first.id);
8351 assert!(q.claim(&second.id).is_err());
8352 assert!(q.claim(&first.id).is_ok(), "the first task was not claimed");
8353 drop(claim);
8354 }
8355
8356 #[test]
8357 fn an_attached_new_task_skips_a_taken_id() {
8358 let dir = tempfile::tempdir().unwrap();
8359 let q = queue_with_ids(dir.path(), &[TAKEN, TAKEN]);
8360 let mut first = task("first");
8361 q.put(&mut first).unwrap();
8362 let src = source_file(dir.path(), "shot.png", "x");
8363 let mut second = task("second");
8364 q.attach_and_put(&mut second, &[src]).unwrap();
8365 assert_ne!(second.id, first.id);
8366 assert!(!q.attachments_dir(&first.id).exists());
8367 assert_eq!(q.attachment_paths(&second).len(), 1);
8368 assert!(q.attachment_paths(&second)[0].is_file());
8369 }
8370
8371 #[test]
8372 fn attaching_before_putting_a_new_task_reserves_the_id() {
8373 let dir = tempfile::tempdir().unwrap();
8374 let q = queue_with_ids(dir.path(), &[TAKEN, TAKEN]);
8375 let mut first = task("first");
8376 q.put(&mut first).unwrap();
8377 let src = source_file(dir.path(), "shot.png", "x");
8378 let mut second = task("second");
8379 q.attach(&mut second, &[src]).unwrap();
8380 assert_ne!(second.id, first.id);
8381 assert!(q.attachments_dir(&second.id).is_dir());
8382 q.put(&mut second).unwrap();
8383 assert_eq!(q.get(&second.id).unwrap().attachments.len(), 1);
8384 assert_eq!(q.get(&first.id).unwrap().title, "first");
8385 assert!(q.get(&first.id).unwrap().attachments.is_empty());
8386 }
8387
8388 #[test]
8389 fn create_new_keeps_its_already_exists_meaning() {
8390 let dir = tempfile::tempdir().unwrap();
8391 let q = Queue::at(dir.path().join("queue"));
8392 let mut a = task("a");
8393 a.id = "fixed-id".into();
8394 assert!(q.create_new(&mut a).unwrap());
8395 let mut b = task("b");
8396 b.id = "fixed-id".into();
8397 assert!(!q.create_new(&mut b).unwrap());
8398 assert_eq!(q.get("fixed-id").unwrap().title, "a");
8399 }
8400
8401 #[test]
8402 fn filing_gives_up_when_no_id_is_ever_free() {
8403 let dir = tempfile::tempdir().unwrap();
8404 let q = Queue::at(dir.path().join("queue")).with_id_source(|| TAKEN.to_owned());
8405 let mut first = task("first");
8406 q.put(&mut first).unwrap();
8407 let mut second = task("second");
8408 assert!(q.put(&mut second).is_err());
8409 assert_eq!(q.get(&first.id).unwrap().title, "first");
8410 }
8411}