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 fn assign_chat_destination(&mut self) {
1539 if self.chat_reservation == ChatReservation::Pending && self.chat.is_none() {
1540 self.chat = Some(format!("task-{}", self.id));
1541 }
1542 }
1543
1544 pub fn issue_ref(&self) -> Option<IssueRef> {
1546 self.issue.clone().or_else(|| match &self.source {
1547 Source::Issue { number, repo } => Some(IssueRef {
1548 number: *number,
1549 repo: repo.clone(),
1550 }),
1551 _ => None,
1552 })
1553 }
1554
1555 pub fn source_label(&self) -> String {
1557 let actor = self.source.label();
1558 match &self.issue {
1559 Some(issue) if self.source == Source::Human => format!("issue #{}", issue.number),
1560 Some(issue) => format!("{actor} · issue #{}", issue.number),
1561 None => actor,
1562 }
1563 }
1564
1565 pub fn chat_notice_key(&self) -> Option<String> {
1568 match self.status {
1569 TaskStatus::Done => Some(
1570 self.completion_history
1571 .iter()
1572 .rev()
1573 .find(|event| event.action == CompletionAction::Complete)
1574 .map_or_else(
1575 || "done".to_owned(),
1576 |event| format!("done:{}", event.occurrence),
1577 ),
1578 ),
1579 TaskStatus::Held => {
1580 let cause = self
1581 .hold_notice_cause
1582 .clone()
1583 .unwrap_or_else(|| self.unresolved_hold_cause());
1584 Some(format!(
1585 "cause:{}",
1586 serde_json::to_string(&cause).expect("cause")
1587 ))
1588 }
1589 TaskStatus::Blocked => {
1590 let ids: std::collections::BTreeSet<_> = self.blocked_by.iter().collect();
1591 let evidence = self
1594 .hold_notice_cause
1595 .as_ref()
1596 .filter(|c| c.stage.starts_with("conductor-evidence:"));
1597 Some(format!(
1598 "dependencies:{}",
1599 serde_json::to_string(&(ids, evidence)).expect("ids")
1600 ))
1601 }
1602 _ => None,
1603 }
1604 }
1605
1606 fn unresolved_hold_cause(&self) -> NoticeCause {
1607 NoticeCause {
1608 stage: "hold".into(),
1609 target: None,
1610 run: self.runs.last().cloned(),
1611 pass: None,
1612 }
1613 }
1614
1615 pub(crate) fn legacy_chat_notice_key(&self) -> Option<String> {
1617 let key = match self.status {
1618 TaskStatus::Held if self.hold_notice_cause.is_none() => Some(format!(
1619 "held#{}",
1620 self.held_at.map(|t| t.to_string()).unwrap_or_default()
1621 )),
1622 TaskStatus::Blocked => Some(format!(
1623 "blocked#{}#{}",
1624 self.blocked_by.join(","),
1625 self.block_reason.as_deref().unwrap_or_default()
1626 )),
1627 _ => None,
1628 };
1629 key.filter(|key| self.legacy_notice_matches(key))
1630 }
1631
1632 pub(crate) fn legacy_notice_matches(&self, key: &str) -> bool {
1633 match self.status {
1634 TaskStatus::Held if self.hold_notice_cause.is_none() => key
1635 .strip_prefix("held#")
1636 .is_some_and(|time| time.is_empty() || time.parse::<Timestamp>().is_ok()),
1637 TaskStatus::Blocked
1638 if self
1639 .hold_notice_cause
1640 .as_ref()
1641 .is_none_or(|c| !c.stage.starts_with("conductor-evidence:")) =>
1642 {
1643 key.strip_prefix("blocked#").is_some_and(|tail| {
1644 let Some((ids, _)) = tail.split_once('#') else {
1645 return false;
1646 };
1647 let old: std::collections::BTreeSet<_> =
1648 ids.split(',').filter(|id| !id.is_empty()).collect();
1649 let current: std::collections::BTreeSet<_> =
1650 self.blocked_by.iter().map(String::as_str).collect();
1651 old == current
1652 })
1653 }
1654 _ => false,
1655 }
1656 }
1657
1658 fn import_chat_notice(&mut self) {
1659 if let Some(n) = &self.chat_notice {
1660 let key = if is_done_notice_key(&n.key) {
1661 "done".to_owned()
1662 } else if self.legacy_notice_matches(&n.key) {
1663 self.chat_notice_key().unwrap_or_else(|| n.key.clone())
1664 } else {
1665 n.key.clone()
1666 };
1667 if !self.chat_notices.contains(&key) {
1668 self.chat_notices.push(key);
1669 }
1670 }
1671 }
1672
1673 pub(crate) fn notice_cause(&mut self, stage: &str, run: Option<&str>, pass: Option<usize>) {
1676 self.import_chat_notice();
1677 self.hold_notice_cause = Some(NoticeCause {
1678 stage: stage.to_owned(),
1679 target: None,
1680 run: run.map(str::to_owned),
1681 pass,
1682 });
1683 }
1684
1685 pub(crate) fn startup_notice_cause(&mut self, stage: &str) {
1688 let recovery_only = matches!(
1689 stage,
1690 "startup-source" | "startup-candidates" | "startup-public-head"
1691 );
1692 match self.hold_notice_cause.as_ref() {
1693 Some(cause) if recovery_only && !cause.stage.starts_with("startup-") => return,
1694 None if recovery_only
1695 && self
1696 .chat_notice
1697 .as_ref()
1698 .is_some_and(|n| !is_done_notice_key(&n.key)) =>
1699 {
1700 return;
1701 }
1702 _ => {}
1703 }
1704 self.notice_cause(stage, None, None);
1705 }
1706
1707 pub(crate) fn fail_startup(
1710 &mut self,
1711 stage: &str,
1712 why: impl Into<String>,
1713 max_attempts: usize,
1714 ) {
1715 let unresolved = self.hold_notice_cause.clone();
1716 self.fail(why, max_attempts);
1717 self.hold_notice_cause = unresolved;
1718 self.startup_notice_cause(stage);
1719 }
1720
1721 pub(crate) fn fail_startup_target(
1723 &mut self,
1724 stage: &str,
1725 target: String,
1726 why: impl Into<String>,
1727 max_attempts: usize,
1728 ) {
1729 self.fail_startup(stage, why, max_attempts);
1730 if let Some(cause) = self.hold_notice_cause.as_mut() {
1731 cause.target = Some(target);
1732 }
1733 }
1734
1735 pub fn chat_notice_due(&self) -> Option<String> {
1740 if self.schema < 13 {
1741 return None;
1742 }
1743 if self.filed_by_chat().is_none() && !self.completed_by_current_build() {
1744 return None;
1745 }
1746 let key = self.chat_notice_key()?;
1747 if self.chat_notices.contains(&key) {
1748 return None;
1749 }
1750 match &self.chat_notice {
1751 Some(n)
1752 if n.key == key
1753 || (key == "done" && is_done_notice_key(&n.key))
1754 || self.legacy_notice_matches(&n.key) =>
1755 {
1756 None
1757 }
1758 _ => Some(key),
1759 }
1760 }
1761
1762 fn completed_by_current_build(&self) -> bool {
1765 self.status == TaskStatus::Done
1766 && !matches!(self.source, Source::Agent { .. })
1767 && self
1768 .completion_history
1769 .iter()
1770 .rev()
1771 .find(|event| event.action == CompletionAction::Complete)
1772 .is_some_and(|event| event.schema >= COMPLETION_REPORT_SCHEMA)
1773 }
1774
1775 pub fn short(&self) -> &str {
1777 short(&self.id)
1778 }
1779
1780 pub fn mark_triage_applied(&mut self, question_id: &str) {
1782 if !self.triage_applied(question_id) {
1783 self.triage_applied.push(question_id.to_owned());
1784 }
1785 }
1786
1787 pub fn action_applied(&self, question_id: &str) -> bool {
1790 self.actions_applied.iter().any(|id| id == question_id)
1791 }
1792
1793 pub fn mark_action_applied(&mut self, question_id: &str) {
1795 if !self.action_applied(question_id) {
1796 self.actions_applied.push(question_id.to_owned());
1797 }
1798 }
1799
1800 pub fn triage_applied(&self, question_id: &str) -> bool {
1802 self.triage_applied.iter().any(|id| id == question_id)
1803 }
1804
1805 pub fn start(&mut self, run: String) {
1818 self.stamp_schema();
1819 self.status = TaskStatus::Running;
1820 self.attempts += 1;
1821 self.runs.retain(|id| id != &run);
1822 if let Some(pin) = &self.resume_override
1823 && pin.pinned_run.as_ref() == Some(&run)
1824 && !pin.question_id.is_empty()
1825 {
1826 self.dispatched_resumes
1827 .insert(pin.question_id.clone(), run.clone());
1828 }
1829 self.runs.push(run);
1830 self.last_error = None;
1831 self.park_reason = None;
1832 self.fresh_start = false;
1833 self.interrupt = false;
1834 self.resume_override = None;
1836 self.disk_resume_run = None;
1839 }
1840
1841 pub fn record_startup_failure(&mut self, failure: crate::run::StartupFailure) {
1843 if !self.startup_failures.iter().any(|f| f.run == failure.run) {
1844 self.startup_failures.push(failure);
1845 }
1846 }
1847
1848 pub fn link_run(&mut self, run: &str) -> bool {
1853 if self.runs.iter().any(|r| r == run) {
1854 return false;
1855 }
1856 self.runs.push(run.to_owned());
1857 true
1858 }
1859
1860 pub fn succeed(&mut self, context: CompletionContext) {
1870 if self.status == TaskStatus::Done {
1871 return;
1872 }
1873 self.record_completion(CompletionAction::Complete, context);
1874 self.stamp_schema();
1875 self.status = TaskStatus::Done;
1876 self.landing = None;
1877 if let Some(pin) = self.resume_override.take()
1878 && !pin.question_id.is_empty()
1879 && let Some(run) = pin.pinned_run
1880 {
1881 self.superseded_resumes.insert(pin.question_id, run);
1884 }
1885 self.sync_only = None;
1886 self.last_error = None;
1887 self.park_reason = None;
1888 self.hold_reason = None;
1889 self.hold_source = None;
1890 self.machine_hold_cause = None;
1891 self.disk_resume_run = None;
1892 self.disk_checked_at = None;
1893 self.diagnostic = None;
1894 self.blocked_by.clear();
1895 self.block_reason = None;
1896 self.blocked_from = None;
1897 }
1898
1899 pub fn already_landed(&mut self, note: impl Into<String>, mut context: CompletionContext) {
1907 let note = note.into();
1908 if context.reason.is_none() {
1909 context.reason = Some(note.clone());
1910 }
1911 self.succeed(context);
1912 self.attempts = self.attempts.saturating_sub(1);
1913 self.last_error = Some(note);
1914 }
1915
1916 fn record_completion(&mut self, action: CompletionAction, context: CompletionContext) {
1917 self.completion_history.push(CompletionEvent {
1918 occurrence: format!(
1919 "{}-{:016x}{:016x}",
1920 Timestamp::now(),
1921 crate::rng::entropy(),
1922 crate::rng::entropy()
1923 ),
1924 action,
1925 actor: context.actor,
1926 reason: context.reason,
1927 discard: context.discard,
1928 prior_status: self.status,
1929 at: Timestamp::now(),
1930 schema: SCHEMA,
1931 prior_hold_reason: self.hold_reason.clone(),
1932 prior_block_reason: self.block_reason.clone(),
1933 prior_error: self.last_error.clone(),
1934 run: context.run,
1935 unavailable_runs: context.unavailable_runs,
1936 });
1937 self.stamp_schema();
1938 }
1939
1940 pub fn reopen(&mut self, context: CompletionContext) -> Result<()> {
1943 anyhow::ensure!(
1944 self.status == TaskStatus::Done,
1945 "only a done task can be reopened"
1946 );
1947 anyhow::ensure!(
1948 context
1949 .reason
1950 .as_deref()
1951 .is_some_and(|reason| !reason.trim().is_empty()),
1952 "reopen requires a non-empty reason"
1953 );
1954 let reason = context.reason.clone();
1955 self.record_completion(CompletionAction::Reopen, context);
1956 self.hold_manual(reason);
1957 self.resume_override = None;
1958 self.reopen_hold =
1959 self.held_at
1960 .zip(self.completion_history.last())
1961 .map(|(held_at, event)| ReopenHold {
1962 occurrence: event.occurrence.clone(),
1963 held_at,
1964 decision: self.operator_decided_at,
1965 legacy: false,
1966 });
1967 self.fresh_start = false;
1968 self.last_error = None;
1969 self.diagnostic = None;
1970 Ok(())
1971 }
1972
1973 pub fn superseded_attempts(&self, last_run_succeeded: bool) -> &[String] {
2003 if self.status != TaskStatus::Done || !last_run_succeeded || self.execution_runs().len() < 2
2004 {
2005 return &[];
2006 }
2007 &self.execution_runs()[..self.execution_runs().len() - 1]
2008 }
2009
2010 pub fn successor_of(&self, run: &str) -> Option<&String> {
2018 let runs = self.execution_runs();
2019 let pos = runs.iter().rposition(|r| r == run)?;
2020 runs.get(pos + 1)
2021 }
2022
2023 pub fn earlier_attempts(&self) -> &[String] {
2030 self.execution_runs()
2031 }
2032
2033 fn preserve_legacy_build_cache(&mut self) {
2034 if self.schema < 23 {
2035 let overrides = self.overrides.get_or_insert_with(|| RunOverrides {
2036 inherit_daemon_options: true,
2037 ..RunOverrides::default()
2038 });
2039 overrides.build_cache.get_or_insert(BuildCache::Shared);
2040 }
2041 }
2042
2043 fn stamp_schema(&mut self) {
2048 self.preserve_legacy_build_cache();
2049 if self.schema < RECOVERY_HOLD_SCHEMA && self.recovery_budget_hold.is_none() {
2050 self.recovery_budget_hold = self.legacy_recovery_budget_hold();
2051 }
2052 self.snapshot_legacy_reopen_hold();
2053 self.schema = self.schema.max(SCHEMA);
2054 }
2055
2056 fn note_held(&mut self) {
2059 self.stamp_schema();
2060 self.recovery_budget_hold = None;
2061 self.reopen_hold = None;
2062 let continuing = self.status == TaskStatus::Held
2063 || (self.status == TaskStatus::Blocked
2064 && (self.blocked_from == Some(TaskStatus::Held)
2065 || (self.blocked_from.is_none()
2066 && (self.hold_reason.is_some() || self.hold_source.is_some()))));
2067 if !continuing || self.held_at.is_none() {
2068 self.held_at = Some(Timestamp::now());
2069 }
2070 }
2071
2072 pub fn fail(&mut self, why: impl Into<String>, max_attempts: usize) {
2088 let why = why.into();
2089 if self.status == TaskStatus::Running {
2090 let run = self.runs.last().cloned();
2091 self.notice_cause("run-failed", run.as_deref(), Some(self.attempts));
2092 }
2093 self.diagnostic = None;
2094 self.park_reason = None;
2095 self.status = if self.attempts >= self.effective_attempt_limit(max_attempts) {
2096 self.note_held();
2097 self.hold_source = Some(HoldSource::Machine);
2098 self.machine_hold_cause = None;
2099 self.disk_resume_run = None;
2100 self.disk_checked_at = None;
2101 self.hold_reason = Some(why.clone());
2102 TaskStatus::Held
2103 } else {
2104 TaskStatus::Failed
2105 };
2106 self.last_error = Some(why);
2107 }
2108
2109 pub fn stall(&mut self, why: impl Into<String>) {
2119 self.last_error = Some(why.into());
2120 self.diagnostic = None;
2121 self.attempts = self.attempts.saturating_sub(1);
2122 self.status = TaskStatus::Failed;
2123 }
2124
2125 pub fn park(&mut self, why: impl Into<String>) {
2131 self.diagnostic = None;
2132 self.attempts = self.attempts.saturating_sub(1);
2133 self.status = TaskStatus::Parked;
2134 self.park_reason = Some(why.into());
2135 self.stamp_schema();
2138 }
2139
2140 pub fn record_pass(
2142 &mut self,
2143 run: &str,
2144 pass_index: usize,
2145 attempts_before: usize,
2146 parked: Option<crate::run::ParkCause>,
2147 ) {
2148 self.record_pass_at(run, pass_index, None, attempts_before, parked);
2149 }
2150
2151 pub fn record_pass_at(
2154 &mut self,
2155 run: &str,
2156 pass_index: usize,
2157 started_at: Option<Timestamp>,
2158 attempts_before: usize,
2159 parked: Option<crate::run::ParkCause>,
2160 ) {
2161 if self
2162 .passes
2163 .iter()
2164 .any(|p| p.run == run && p.pass_index == pass_index)
2165 {
2166 return;
2167 }
2168 let cost = if self.attempts < attempts_before {
2169 PassCost::Refunded
2170 } else {
2171 PassCost::Spent
2172 };
2173 self.passes.push(TaskPass {
2174 run: run.to_owned(),
2175 pass_index,
2176 started_at: self.dispatched_at.or(started_at),
2177 cost,
2178 attempts_after: self.attempts,
2179 settled_at: Timestamp::now(),
2180 parked,
2181 });
2182 self.stamp_schema();
2183 }
2184
2185 pub(crate) fn upgrade_resume_key(&self) -> Option<(Timestamp, &str)> {
2188 if self.status != TaskStatus::Parked || self.fresh_start {
2189 return None;
2190 }
2191 let pass = self.passes.last()?;
2192 if self.execution_runs().last() != Some(&pass.run)
2193 || !matches!(pass.parked, Some(crate::run::ParkCause::Upgrade { .. }))
2194 {
2195 return None;
2196 }
2197 Some((pass.started_at.unwrap_or(pass.settled_at), &self.id))
2200 }
2201
2202 pub fn operator_held(&self) -> bool {
2208 self.status == TaskStatus::Held && !matches!(self.hold_source, Some(HoldSource::Machine))
2209 }
2210
2211 pub fn hold_manual(&mut self, reason: Option<String>) {
2221 self.operator_decided_at = Some(Timestamp::now());
2223 if self.status != TaskStatus::Running && self.sync_only.take().is_some() {
2224 self.resume_override = None;
2225 }
2226 self.hold_unrequested_retry(reason);
2227 }
2228
2229 pub(crate) fn hold_unrequested_retry(&mut self, reason: Option<String>) {
2232 self.park_reason = None;
2233 self.note_held();
2234 self.status = TaskStatus::Held;
2235 if reason.is_some() {
2236 self.hold_reason = reason;
2237 }
2238 self.hold_source = Some(HoldSource::Manual);
2239 self.machine_hold_cause = None;
2240 self.disk_resume_run = None;
2241 self.disk_checked_at = None;
2242 self.blocked_by.clear();
2243 self.block_reason = None;
2244 self.blocked_from = None;
2245 }
2246
2247 pub(crate) fn hold_after_sync_only(&mut self, reason: String) {
2248 let recovery_hold = self.recovery_budget_hold.take();
2249 self.hold_unrequested_retry(Some(reason));
2250 self.recovery_budget_hold = recovery_hold;
2251 }
2252
2253 pub fn hold_machine(&mut self, reason: Option<String>) {
2258 self.park_reason = None;
2259 self.note_held();
2260 self.status = TaskStatus::Held;
2261 if reason.is_some() {
2262 self.hold_reason = reason;
2263 }
2264 self.hold_source = Some(HoldSource::Machine);
2265 self.machine_hold_cause = None;
2266 self.disk_resume_run = None;
2267 self.disk_checked_at = None;
2268 self.blocked_by.clear();
2269 self.block_reason = None;
2270 self.blocked_from = None;
2271 }
2272
2273 pub(crate) fn mark_disk_capacity(&mut self) {
2275 self.machine_hold_cause = Some(MachineHoldCause::DiskCapacity {
2276 reason: self.hold_reason.clone().unwrap_or_default(),
2277 before_start: false,
2278 });
2279 }
2280
2281 pub(crate) fn mark_startup_disk_capacity(&mut self) {
2282 self.machine_hold_cause = Some(MachineHoldCause::DiskCapacity {
2283 reason: self.hold_reason.clone().unwrap_or_default(),
2284 before_start: true,
2285 });
2286 }
2287
2288 pub(crate) fn disk_wait_run(&self) -> Option<&String> {
2289 if self.has_disk_capacity_cause()
2290 && matches!(
2291 self.machine_hold_cause,
2292 Some(MachineHoldCause::DiskCapacity {
2293 before_start: true,
2294 ..
2295 })
2296 )
2297 {
2298 None
2299 } else {
2300 self.execution_runs().last()
2301 }
2302 }
2303
2304 pub fn has_disk_capacity_cause(&self) -> bool {
2306 matches!(
2307 (&self.machine_hold_cause, self.hold_reason.as_deref()),
2308 (Some(MachineHoldCause::DiskCapacity { reason, .. }), Some(now)) if reason == now
2309 )
2310 }
2311
2312 pub(crate) fn resume_disk_wait(&mut self) {
2314 let retained = self.disk_wait_run().cloned();
2315 self.status = TaskStatus::Queued;
2316 self.held_at = None;
2317 self.hold_source = None;
2318 self.hold_reason = None;
2319 self.machine_hold_cause = None;
2320 self.last_error = None;
2321 self.disk_resume_run = retained;
2322 }
2323
2324 pub(crate) fn hold_head_e2e(
2326 &mut self,
2327 stop: crate::head_e2e_stop::Stop,
2328 reason: String,
2329 last_error: String,
2330 ) {
2331 self.hold_machine(Some(reason));
2332 self.last_error = Some(last_error);
2333 self.machine_hold_cause = Some(MachineHoldCause::HeadE2e { stop });
2334 }
2335
2336 pub(crate) fn head_e2e_notice(&mut self, stop: &crate::head_e2e_stop::Stop) {
2338 if let Some(at) = stop.recorded_at {
2339 self.held_at = Some(at);
2340 }
2341 self.notice_cause(crate::head_e2e_stop::NOTICE_STAGE, Some(&stop.run), None);
2342 if let Some(cause) = &mut self.hold_notice_cause {
2343 cause.target = Some(stop.id.clone());
2344 }
2345 }
2346
2347 pub fn has_head_e2e_cause(&self) -> bool {
2349 matches!(
2350 self.machine_hold_cause,
2351 Some(MachineHoldCause::HeadE2e { .. })
2352 )
2353 }
2354
2355 pub(crate) fn hold_awaiting_landing(&mut self, run: String, reason: String) {
2358 self.hold_machine(Some(reason.clone()));
2359 self.last_error = Some(reason.clone());
2360 self.machine_hold_cause = Some(MachineHoldCause::AwaitingLanding { run, reason });
2361 self.stamp_schema();
2362 }
2363
2364 pub fn has_awaiting_landing_cause(&self) -> bool {
2366 self.status == TaskStatus::Held
2367 && matches!(
2368 self.machine_hold_cause,
2369 Some(MachineHoldCause::AwaitingLanding { .. })
2370 )
2371 }
2372
2373 pub fn awaiting_landing_run(&self) -> Option<&str> {
2375 if self.status != TaskStatus::Held {
2376 return None;
2377 }
2378 match &self.machine_hold_cause {
2379 Some(MachineHoldCause::AwaitingLanding { run, .. }) => Some(run.as_str()),
2380 _ => None,
2381 }
2382 }
2383
2384 pub fn completed_by_discard(&self) -> bool {
2386 self.status == TaskStatus::Done
2387 && self
2388 .completion_history
2389 .last()
2390 .is_some_and(|event| event.action == CompletionAction::Complete && event.discard)
2391 }
2392
2393 pub fn current_investigation_result(&self) -> Option<&str> {
2395 self.completion_result
2396 .as_ref()
2397 .filter(|res| {
2398 res.instruction_rev == self.instruction_rev && !res.text.trim().is_empty()
2399 })
2400 .map(|res| res.text.as_str())
2401 }
2402
2403 pub fn validate_investigation_result<'a>(
2406 &'a self,
2407 result: Option<&'a str>,
2408 ) -> Result<Option<&'a str>> {
2409 if !self.investigation {
2410 return Ok(None);
2411 }
2412 if let Some(raw) = result {
2413 let trimmed = raw.trim();
2414 anyhow::ensure!(
2415 !trimmed.is_empty(),
2416 "an investigation requires a nonblank --result"
2417 );
2418 return Ok(Some(trimmed));
2419 }
2420 self.current_investigation_result()
2421 .map(Some)
2422 .context("an investigation requires a nonblank --result")
2423 }
2424
2425 pub fn record_investigation_result(&mut self, result: Option<&str>) -> Result<()> {
2427 if !self.investigation {
2428 return Ok(());
2429 }
2430 let text = self
2431 .validate_investigation_result(result)?
2432 .expect("investigation validated nonblank")
2433 .to_owned();
2434 if result.is_some()
2435 || self
2436 .completion_result
2437 .as_ref()
2438 .is_none_or(|existing| existing.instruction_rev != self.instruction_rev)
2439 {
2440 self.completion_result = Some(InvestigationResult {
2441 text,
2442 instruction_rev: self.instruction_rev,
2443 recorded_at: Timestamp::now(),
2444 });
2445 self.stamp_schema();
2446 }
2447 Ok(())
2448 }
2449
2450 pub fn head_e2e_stop_id(&self) -> Option<&str> {
2452 if let Some(MachineHoldCause::HeadE2e { stop }) = &self.machine_hold_cause {
2453 return Some(stop.id.as_str());
2454 }
2455 self.hold_notice_cause
2456 .as_ref()
2457 .filter(|c| c.stage == crate::head_e2e_stop::NOTICE_STAGE)
2458 .and_then(|c| c.target.as_deref())
2459 }
2460
2461 pub(crate) fn resume_head_e2e_wait(&mut self) {
2464 self.status = TaskStatus::Queued;
2465 self.held_at = None;
2466 self.hold_source = None;
2467 self.hold_reason = None;
2468 self.machine_hold_cause = None;
2469 self.last_error = None;
2470 self.diagnostic = None;
2471 self.blocked_by.clear();
2472 self.block_reason = None;
2473 self.blocked_from = None;
2474 }
2475
2476 pub fn block(&mut self, blocked_by: Vec<String>, reason: Option<String>) {
2486 self.stamp_schema();
2487 let before: std::collections::BTreeSet<_> = self.blocked_by.iter().collect();
2488 let after: std::collections::BTreeSet<_> = blocked_by.iter().collect();
2489 if self.status != TaskStatus::Blocked || before != after {
2490 self.blocked_at = Some(Timestamp::now());
2491 }
2492 if self.status != TaskStatus::Blocked {
2493 self.blocked_from = Some(self.status);
2494 }
2495 self.status = TaskStatus::Blocked;
2496 self.blocked_by = blocked_by;
2497 self.block_reason = reason;
2498 }
2499
2500 pub fn unblock(&mut self, resolved_id: &str) {
2523 if self.status != TaskStatus::Blocked {
2524 return;
2525 }
2526 self.blocked_by.retain(|id| id != resolved_id);
2527 self.restore_if_unblocked();
2528 }
2529
2530 pub fn dependency_deleted(&mut self, deleted_id: &str) -> bool {
2541 if self.status != TaskStatus::Blocked || !self.blocked_by.iter().any(|b| b == deleted_id) {
2542 return false;
2543 }
2544 self.blocked_by.retain(|id| id != deleted_id);
2545 self.restore_if_unblocked();
2546 true
2547 }
2548
2549 fn restore_if_unblocked(&mut self) {
2553 if self.blocked_by.is_empty() {
2554 self.status = match self.blocked_from {
2555 Some(TaskStatus::Running) => TaskStatus::Queued,
2556 Some(other) => other,
2557 None if self.hold_reason.is_some() || self.hold_source.is_some() => {
2558 TaskStatus::Held
2559 }
2560 None => TaskStatus::Queued,
2561 };
2562 self.block_reason = None;
2563 self.blocked_from = None;
2564 }
2565 }
2566
2567 pub fn record_answer(&mut self, question: String, answer: String) {
2572 self.answers.push(AnsweredQuestion { question, answer });
2573 }
2574
2575 pub fn request_review(&mut self, branch: String) {
2579 self.release();
2580 self.review_branch = Some(branch);
2581 self.review_instruction = Some(self.instruction.clone());
2582 }
2583
2584 pub fn requeue(&mut self) {
2587 self.release();
2588 self.review_branch = None;
2590 self.review_instruction = None;
2591 self.fresh_start = true;
2592 }
2593
2594 pub fn hold_for_handover(&mut self, branch: Option<String>, reason: String) {
2603 if branch.is_some() {
2604 self.review_branch = branch;
2605 self.review_instruction = Some(self.instruction.clone());
2606 }
2607 self.hold_machine(Some(reason));
2608 }
2609
2610 pub fn set_urgent(&mut self, urgent: bool) -> Result<()> {
2612 if !matches!(self.status, TaskStatus::Queued | TaskStatus::Held) {
2613 bail!(
2614 "task {} is {}; urgent can only change while queued or held; \
2615 wait for the active attempt to finish and requeue or hold the task first",
2616 self.short(),
2617 self.status.as_str()
2618 );
2619 }
2620 self.urgent = urgent;
2621 Ok(())
2622 }
2623
2624 pub fn set_immediate(&mut self, immediate: bool) -> Result<()> {
2628 if !matches!(self.status, TaskStatus::Queued | TaskStatus::Held) {
2629 bail!(
2630 "task {} is {}; immediate can only change while queued or held; \
2631 wait for the active attempt to finish and requeue or hold the task first",
2632 self.short(),
2633 self.status.as_str()
2634 );
2635 }
2636 self.immediate = immediate;
2637 Ok(())
2638 }
2639
2640 pub fn set_priority(&mut self, priority: i32) -> Result<()> {
2649 if self.status == TaskStatus::Running {
2650 bail!(
2651 "task {} is running; its priority cannot be changed until \
2652 this attempt finishes",
2653 self.short()
2654 );
2655 }
2656 self.priority = priority;
2657 Ok(())
2658 }
2659
2660 pub fn set_interrupt(&mut self, interrupt: bool) -> Result<()> {
2675 if interrupt && !self.status.runnable() {
2676 bail!(
2677 "task {} is {}; only a queued or failed task can be marked \
2678 to interrupt",
2679 self.short(),
2680 self.status.as_str()
2681 );
2682 }
2683 self.interrupt = interrupt;
2684 Ok(())
2685 }
2686
2687 pub fn effective_attempt_limit(&self, daemon_limit: usize) -> usize {
2689 self.attempt_limit.map_or(daemon_limit, NonZeroUsize::get)
2690 }
2691
2692 pub fn change_attempt_limit(&mut self, limit: Option<NonZeroUsize>) -> Result<()> {
2695 if !matches!(self.status, TaskStatus::Queued | TaskStatus::Held) {
2696 bail!("only queued or held tasks can change the attempt limit");
2697 }
2698 self.stamp_schema();
2699 self.attempt_limit = limit;
2700 Ok(())
2701 }
2702
2703 pub fn implementers(&self) -> Option<usize> {
2705 if self.solo {
2706 Some(1)
2707 } else {
2708 self.overrides.as_ref().and_then(|o| o.candidates)
2709 }
2710 }
2711
2712 pub fn build_cache_override(
2717 &self,
2718 config: &crate::config::Config,
2719 ) -> Option<(BuildCache, &'static str)> {
2720 self.overrides
2721 .as_ref()
2722 .and_then(|o| o.build_cache)
2723 .map(|mode| (mode, "task-override"))
2724 .or_else(|| {
2725 ((self.immediate || self.urgent) && crate::build_target::urgent_isolation(config))
2726 .then_some((
2727 BuildCache::Isolated,
2728 if self.immediate {
2729 "immediate"
2730 } else {
2731 "urgent"
2732 },
2733 ))
2734 })
2735 }
2736
2737 pub fn change_build_cache(&mut self, mode: Option<BuildCache>) -> Result<()> {
2740 if !matches!(self.status, TaskStatus::Queued | TaskStatus::Held) {
2741 bail!(
2742 "task {} is {}; only queued or held tasks can change build cache",
2743 self.short(),
2744 self.status.as_str()
2745 );
2746 }
2747 self.stamp_schema();
2748 if self.overrides.is_some() || mode.is_some() {
2749 let overrides = self.overrides.get_or_insert_with(|| RunOverrides {
2750 inherit_daemon_options: true,
2751 ..RunOverrides::default()
2752 });
2753 overrides.build_cache = mode;
2754 }
2755 Ok(())
2756 }
2757
2758 pub fn change_implementers(&mut self, count: u8) -> Result<()> {
2761 self.check_implementers_editable()?;
2762 let explicit = self.overrides.as_ref().and_then(|o| o.config.as_deref());
2763 let (mut config, _) = crate::config::Config::discover(&self.repo, explicit)?;
2764 if let Some(o) = &self.overrides {
2765 o.apply(&mut config);
2766 }
2767 self.set_implementers(count, &config)
2768 }
2769
2770 fn check_implementers_editable(&self) -> Result<()> {
2771 if !matches!(self.status, TaskStatus::Queued | TaskStatus::Held) {
2772 bail!(
2773 "task {} is {}; only queued or held tasks can change implementers",
2774 self.short(),
2775 self.status.as_str()
2776 );
2777 }
2778 Ok(())
2779 }
2780
2781 pub fn set_implementers(&mut self, count: u8, config: &crate::config::Config) -> Result<()> {
2783 self.check_implementers_editable()?;
2784 crate::talk::check_implementers(count, config).map_err(anyhow::Error::msg)?;
2785 self.stamp_schema();
2786 self.solo = count == 1;
2787 let mut overrides = self.overrides.clone().unwrap_or_else(|| RunOverrides {
2788 inherit_daemon_options: true,
2789 ..Default::default()
2790 });
2791 overrides.candidates = (count > 1).then_some(usize::from(count));
2792 let mut settings = overrides.clone();
2793 settings.inherit_daemon_options = false;
2794 self.overrides = if overrides.inherit_daemon_options && settings == RunOverrides::default()
2796 {
2797 None
2798 } else {
2799 Some(overrides)
2800 };
2801 Ok(())
2802 }
2803
2804 pub fn edit(&mut self, title: String, instruction: String) -> Result<()> {
2816 if !matches!(self.status, TaskStatus::Queued | TaskStatus::Held) {
2817 bail!(
2818 "task {} is {}; only a queued or held task's instruction can \
2819 be edited",
2820 self.short(),
2821 self.status.as_str()
2822 );
2823 }
2824 if self.review_branch.is_some() && self.review_instruction.is_none() {
2827 self.review_instruction = Some(self.instruction.clone());
2828 }
2829 let instruction_changed = self.instruction != instruction;
2830 if instruction_changed {
2831 self.instruction_rev = self.instruction_rev.saturating_add(1);
2835 self.completion_result = None;
2836 self.landing = None;
2837 self.resume_override = None;
2838 self.stamp_schema();
2839 }
2840 let keep_awaiting_landing = !instruction_changed && self.has_awaiting_landing_cause();
2841 if !keep_awaiting_landing {
2842 if self.status == TaskStatus::Held && self.machine_hold_cause.is_some() {
2843 self.hold_manual(self.hold_reason.clone());
2844 }
2845 self.machine_hold_cause = None;
2846 }
2847 self.disk_resume_run = None;
2848 self.disk_checked_at = None;
2849 self.title = title;
2850 self.instruction = instruction;
2851 Ok(())
2852 }
2853
2854 pub fn handed_off(&mut self, why: impl Into<String>) {
2874 let why = why.into();
2875 self.diagnostic = None;
2876 self.note_held();
2877 self.status = TaskStatus::Held;
2878 self.hold_source = Some(HoldSource::Machine);
2879 self.machine_hold_cause = None;
2880 self.disk_resume_run = None;
2881 self.disk_checked_at = None;
2882 self.hold_reason = Some(why.clone());
2883 self.last_error = Some(why);
2884 }
2885
2886 pub fn release_operator(&mut self, source: &str, question_id: Option<&str>) {
2888 self.recovery_budget = None;
2889 self.recovery_generations.clear();
2890 self.recovery_admission = None;
2891 if self
2892 .resumption
2893 .as_ref()
2894 .is_some_and(|r| r.instruction != self.instruction)
2895 {
2896 self.resume_override = None;
2899 }
2900 let approval = Resumption {
2901 generation: self.resumption.as_ref().map_or(1, |r| r.generation + 1),
2902 source: source.to_owned(),
2903 question_id: question_id.map(str::to_owned),
2904 at: Timestamp::now(),
2905 instruction: self.instruction.clone(),
2906 answers_through: self.answers.len(),
2907 runs_through: self.runs.len(),
2908 blocking_evidence: Vec::new(),
2909 cleared_reason: self
2910 .hold_reason
2911 .clone()
2912 .or_else(|| self.block_reason.clone()),
2913 };
2914 self.release();
2915 self.operator_decided_at = Some(approval.at);
2916 if let Some(previous) = self.resumption.replace(approval) {
2917 self.resumption_history.push(previous);
2918 }
2919 }
2920
2921 pub(crate) fn recovery_failed(&mut self, state: &crate::run::RunState) {
2923 let (base, inputs) = self.recovery_admission.as_ref().map_or_else(
2924 || (state.base_commit.clone(), recovery_inputs(&state.sources)),
2925 |a| (a.base.clone(), a.inputs.clone()),
2926 );
2927 let progress = recovery_progress(state);
2928 let stage = if state.prep_failure.is_some() {
2929 "preparation"
2930 } else {
2931 "execution"
2932 };
2933 let matches = |b: &RecoveryBudget| {
2934 b.instruction == self.instruction
2935 && b.base == base
2936 && b.inputs == inputs
2937 && (progress.is_none() || b.progress == progress)
2938 };
2939 if !self.recovery_budget.as_ref().is_some_and(matches) {
2940 let previous = self
2941 .recovery_generations
2942 .iter()
2943 .position(matches)
2944 .map(|index| self.recovery_generations.remove(index));
2945 if let Some(old) = self.recovery_budget.take() {
2946 self.recovery_generations.push(old);
2947 }
2948 self.recovery_budget = previous;
2949 }
2950 if let Some(budget) = &mut self.recovery_budget {
2951 budget.failures = budget.failures.saturating_add(1);
2952 budget.stage = stage.to_owned();
2953 } else {
2954 self.recovery_budget = Some(RecoveryBudget {
2955 instruction: self.instruction.clone(),
2956 base,
2957 inputs,
2958 stage: stage.to_owned(),
2959 failures: 1,
2960 progress,
2961 });
2962 }
2963 }
2964
2965 pub(crate) fn recovery_exhausted(
2966 &self,
2967 base: &str,
2968 inputs: &str,
2969 limit: usize,
2970 ) -> Option<String> {
2971 let same_input = |b: &&RecoveryBudget| {
2972 b.instruction == self.instruction && b.base == base && b.inputs == inputs
2973 };
2974 let budget = self
2975 .recovery_budget
2976 .as_ref()
2977 .filter(same_input)
2978 .or_else(|| self.recovery_generations.iter().rev().find(same_input))?;
2979 (budget.failures >= limit.max(1)).then(|| budget.budget_reason())
2980 }
2981
2982 pub(crate) fn hold_recovery_budget(&mut self, reason: String, admission: RecoveryAdmission) {
2983 self.hold_unrequested_retry(Some(reason));
2984 if let Some(pass) = self.passes.last()
2985 && self.execution_runs().last() == Some(&pass.run)
2986 {
2987 self.recovery_budget_hold = Some(RecoveryBudgetHold {
2988 admission,
2989 run: pass.run.clone(),
2990 pass: pass.pass_index,
2991 held_at: self.held_at.expect("hold timestamp just recorded"),
2992 decision: self.operator_decided_at,
2993 legacy: false,
2994 });
2995 }
2996 }
2997
2998 fn matches_budget_hold(&self, admission: &RecoveryAdmission) -> bool {
2999 self.status == TaskStatus::Held
3000 && self.hold_source == Some(HoldSource::Manual)
3001 && self.machine_hold_cause.is_none()
3002 && self.recovery_budget.as_ref().is_some_and(|budget| {
3003 budget.instruction == self.instruction
3004 && budget.base == admission.base
3005 && budget.inputs == admission.inputs
3006 && budget.stage == "execution"
3007 && budget.failures > 0
3008 && self
3009 .hold_reason
3010 .as_ref()
3011 .is_some_and(|reason| *reason == budget.budget_reason())
3012 })
3013 }
3014
3015 fn legacy_recovery_budget_hold(&self) -> Option<RecoveryBudgetHold> {
3016 let held_at = self.held_at?;
3017 let settled = self.passes.last()?;
3018 let admission = self.recovery_admission.as_ref()?;
3019 if !self.matches_budget_hold(admission)
3020 || self.execution_runs().last() != Some(&settled.run)
3021 || settled.cost != PassCost::Spent
3022 || settled.parked.is_some()
3023 || settled.settled_at > held_at
3024 || self.operator_decided_at.is_some_and(|at| at >= held_at)
3025 {
3026 return None;
3027 }
3028 Some(RecoveryBudgetHold {
3029 admission: admission.clone(),
3030 run: settled.run.clone(),
3031 pass: settled.pass_index,
3032 held_at,
3033 decision: self.operator_decided_at,
3034 legacy: true,
3035 })
3036 }
3037
3038 pub(crate) fn held_for_recovery_budget(&self, run: &crate::run::RunState) -> bool {
3039 let (Some(held_at), Some(settled), Some(pass), Some(admission)) = (
3040 self.held_at,
3041 self.passes.last(),
3042 run.passes.last(),
3043 self.recovery_admission.as_ref(),
3044 ) else {
3045 return false;
3046 };
3047 if !self.matches_budget_hold(admission)
3048 || self.execution_runs().last() != Some(&run.id)
3049 || settled.run != run.id
3050 || settled.pass_index != pass.index
3051 || settled.cost != PassCost::Spent
3052 || settled.parked.is_some()
3053 || settled.settled_at < pass.started_at
3054 || settled.settled_at > held_at
3055 || self.operator_decided_at.is_some_and(|at| at >= held_at)
3056 || !crate::daemon::compatible_run_instruction(run, self)
3057 {
3058 return false;
3059 }
3060 match &self.recovery_budget_hold {
3061 Some(hold) => {
3062 hold.run == run.id
3063 && hold.pass == pass.index
3064 && hold.held_at == held_at
3065 && hold.decision == self.operator_decided_at
3066 && &hold.admission == admission
3067 && (!hold.legacy
3068 || self
3069 .operator_decided_at
3070 .is_none_or(|at| at < pass.started_at))
3071 }
3072 None => {
3073 self.schema < RECOVERY_HOLD_SCHEMA
3074 && self
3075 .operator_decided_at
3076 .is_none_or(|at| at < pass.started_at)
3077 }
3078 }
3079 }
3080
3081 pub(crate) fn queue_repair(&mut self, receipt: &crate::repair_budget::Receipt) {
3082 self.stamp_schema();
3083 self.repair_grants.push(receipt.clone());
3084 self.status = TaskStatus::Queued;
3085 self.hold_source = None;
3086 self.hold_reason = None;
3087 self.held_at = None;
3088 self.recovery_budget_hold = None;
3089 self.reopen_hold = None;
3090 self.resume_override = Some(OperatorResume {
3091 question_id: String::new(),
3092 at: receipt.at,
3093 conductor_rehold: None,
3094 forced: true,
3095 pinned_run: Some(receipt.request.run.clone()),
3096 });
3097 }
3098
3099 fn snapshot_legacy_reopen_hold(&mut self) {
3102 if self.schema >= REOPEN_HOLD_SCHEMA || self.reopen_hold.is_some() {
3103 return;
3104 }
3105 let Some(event) = self.completion_history.last() else {
3106 return;
3107 };
3108 if event.action == CompletionAction::Reopen
3109 && self.status == TaskStatus::Held
3110 && self.hold_source == Some(HoldSource::Manual)
3111 && event.reason.is_some()
3112 && self.hold_reason == event.reason
3113 && let (Some(held_at), Some(decision)) = (self.held_at, self.operator_decided_at)
3114 && held_at >= event.at
3115 && decision >= event.at
3116 {
3117 self.reopen_hold = Some(ReopenHold {
3118 occurrence: event.occurrence.clone(),
3119 held_at,
3120 decision: Some(decision),
3121 legacy: true,
3122 });
3123 }
3124 }
3125
3126 pub(crate) fn held_by_reopen(
3129 &self,
3130 occurrence: &str,
3131 run: &str,
3132 legacy_confirmation: Option<&str>,
3133 ) -> bool {
3134 let Some(event) = self.completion_history.last() else {
3135 return false;
3136 };
3137 if self.status != TaskStatus::Held
3138 || self.hold_source != Some(HoldSource::Manual)
3139 || !self.blocked_by.is_empty()
3140 || self.resume_override.is_some()
3141 || self.fresh_start
3142 || event.action != CompletionAction::Reopen
3143 || event.occurrence != occurrence
3144 || event.run.as_ref().map(|r| r.id.as_str()) != Some(run)
3145 || event.reason.is_none()
3146 || self.hold_reason != event.reason
3147 {
3148 return false;
3149 }
3150 let (Some(held_at), Some(decided), Some(hold)) =
3151 (self.held_at, self.operator_decided_at, &self.reopen_hold)
3152 else {
3153 return false;
3154 };
3155 hold.occurrence == occurrence
3156 && hold.held_at == held_at
3157 && hold.decision == Some(decided)
3158 && if hold.legacy {
3159 legacy_confirmation == Some(format!("{held_at}/{decided}").as_str())
3160 } else {
3161 legacy_confirmation.is_none()
3162 }
3163 }
3164
3165 pub fn release(&mut self) {
3169 self.import_chat_notice();
3172 if self.hold_notice_cause.is_none()
3173 && matches!(self.status, TaskStatus::Held | TaskStatus::Blocked)
3174 {
3175 self.hold_notice_cause = Some(self.unresolved_hold_cause());
3176 }
3177 let refused_handover = self.status == TaskStatus::Held
3178 && self.hold_source == Some(HoldSource::Machine)
3179 && self.review_branch.is_some()
3180 && self
3181 .review_instruction
3182 .as_ref()
3183 .is_none_or(|i| *i == self.instruction);
3184 self.status = TaskStatus::Queued;
3185 self.held_at = None;
3186 self.attempts = 0;
3187 self.last_error = None;
3188 self.park_reason = None;
3189 self.hold_reason = None;
3192 self.hold_source = None;
3193 self.machine_hold_cause = None;
3194 self.disk_resume_run = None;
3195 self.disk_checked_at = None;
3196 self.diagnostic = None;
3197 self.blocked_by.clear();
3202 self.block_reason = None;
3203 self.blocked_from = None;
3204 if !refused_handover {
3208 self.review_branch = None;
3209 self.review_instruction = None;
3210 }
3211 self.fresh_start = false;
3212 }
3213}
3214
3215fn copy_new(dir: &Path, src: &Path, name: &str) -> Result<(String, PathBuf)> {
3219 use std::io::ErrorKind;
3220 let (stem, ext) = match name.rfind('.') {
3221 Some(i) if i > 0 => (&name[..i], &name[i..]),
3222 _ => (name, ""),
3223 };
3224 for n in 1u32.. {
3225 let candidate = if n == 1 {
3226 name.to_owned()
3227 } else {
3228 let suffix = format!("-{n}");
3229 let room = 64usize.saturating_sub(suffix.len() + ext.len());
3230 let stem: String = stem.chars().take(room).collect();
3231 format!("{stem}{suffix}{ext}")
3232 };
3233 if !crate::ask::valid_asset_name(&candidate) {
3234 bail!("no valid attachment name is left for `{name}`");
3235 }
3236 let path = dir.join(&candidate);
3237 match std::fs::OpenOptions::new()
3238 .write(true)
3239 .create_new(true)
3240 .open(&path)
3241 {
3242 Ok(mut out) => {
3243 let copied = std::fs::File::open(src)
3244 .and_then(|mut input| std::io::copy(&mut input, &mut out));
3245 if let Err(e) = copied {
3246 drop(out);
3247 let _ = std::fs::remove_file(&path);
3248 return Err(e).with_context(|| format!("copy {}", src.display()));
3249 }
3250 return Ok((candidate, path));
3251 }
3252 Err(e) if e.kind() == ErrorKind::AlreadyExists => continue,
3253 Err(e) => return Err(e).with_context(|| format!("create {}", path.display())),
3254 }
3255 }
3256 unreachable!("the counter never runs out")
3257}
3258
3259const TASK_LOCK_STALE: std::time::Duration = std::time::Duration::from_secs(10);
3262
3263pub(crate) struct TaskLock {
3266 path: PathBuf,
3267 token: String,
3268}
3269
3270fn owner_token() -> String {
3273 static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
3274 let n = COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3275 let mut r = crate::rng::SplitMix64::new(crate::rng::entropy() ^ n.rotate_left(32));
3276 format!("{}-{:016x}", std::process::id(), r.next_u64())
3277}
3278
3279fn break_marker(path: &Path, token: &str) -> PathBuf {
3282 let mut h: u64 = 0xcbf29ce484222325;
3283 for b in token.bytes() {
3284 h ^= u64::from(b);
3285 h = h.wrapping_mul(0x100000001b3);
3286 }
3287 let mut name = path.as_os_str().to_owned();
3288 name.push(format!(".break-{h:016x}"));
3289 PathBuf::from(name)
3290}
3291
3292fn older_than_stale(path: &Path) -> bool {
3293 std::fs::metadata(path)
3294 .and_then(|m| m.modified())
3295 .ok()
3296 .and_then(|t| t.elapsed().ok())
3297 .is_some_and(|age| age > TASK_LOCK_STALE)
3298}
3299
3300fn writer_may_be_gone(token: &str) -> bool {
3301 let Some(pid) = token
3302 .split_once('-')
3303 .and_then(|(pid, _)| pid.parse::<u32>().ok())
3304 else {
3305 return true;
3308 };
3309 if pid == std::process::id() {
3310 return false;
3311 }
3312 crate::proc::pid_status(pid) == Some(false)
3314}
3315
3316const MAX_MARKER_DEPTH: u8 = 3;
3320
3321fn take_marker(
3327 path: &Path,
3328 token: &str,
3329 depth: u8,
3330 retry: crate::lock_file::Retry,
3331) -> Option<(PathBuf, String)> {
3332 use std::io::Write;
3333 let marker = break_marker(path, token);
3334 for _ in 0..2 {
3335 match retry.create(&marker) {
3336 Ok(mut f) => {
3337 let mine = owner_token();
3338 if f.write_all(mine.as_bytes()).is_err() {
3339 drop(f);
3340 let _ = std::fs::remove_file(&marker);
3341 return None;
3342 }
3343 return Some((marker, mine));
3344 }
3345 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
3346 let judged = std::fs::read_to_string(&marker).ok();
3347 match judged.filter(|_| older_than_stale(&marker)) {
3348 Some(judged) if depth < MAX_MARKER_DEPTH => {
3349 remove_lock_if(&marker, &judged, true, depth + 1, retry)?;
3350 }
3351 _ => return None,
3352 }
3353 }
3354 Err(_) => return None,
3355 }
3356 }
3357 None
3358}
3359
3360fn remove_lock_if(
3365 path: &Path,
3366 token: &str,
3367 require_stale: bool,
3368 depth: u8,
3369 retry: crate::lock_file::Retry,
3370) -> Option<bool> {
3371 let (marker, mine) = take_marker(path, token, depth, retry)?;
3372 let still = std::fs::read_to_string(path).is_ok_and(|c| c == token)
3373 && (!require_stale || older_than_stale(path) && writer_may_be_gone(token));
3374 if still {
3375 let _ = std::fs::remove_file(path);
3376 }
3377 if depth >= MAX_MARKER_DEPTH {
3379 if std::fs::read_to_string(&marker).is_ok_and(|c| c == mine) {
3380 let _ = std::fs::remove_file(&marker);
3381 }
3382 } else {
3383 let _ = remove_lock_if(&marker, &mine, false, depth + 1, retry);
3384 }
3385 Some(still)
3386}
3387
3388#[cfg(test)]
3391fn break_stale(path: &Path, judged: &str) -> bool {
3392 break_stale_with(path, judged, crate::lock_file::Retry::new(None))
3393}
3394
3395fn break_stale_with(path: &Path, judged: &str, retry: crate::lock_file::Retry) -> bool {
3396 remove_lock_if(path, judged, true, 0, retry).unwrap_or(false)
3397}
3398
3399impl Drop for TaskLock {
3400 fn drop(&mut self) {
3401 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2);
3402 let retry = crate::lock_file::Retry::new(Some(deadline));
3403 loop {
3404 match remove_lock_if(&self.path, &self.token, false, 0, retry) {
3405 Some(_) => return,
3406 None if std::time::Instant::now() > deadline => return,
3407 None => std::thread::sleep(std::time::Duration::from_millis(5)),
3408 }
3409 }
3410 }
3411}
3412
3413#[derive(Debug, thiserror::Error)]
3414#[error("task changed during completion decision; reload and inspect it")]
3415pub(crate) struct CompletionSnapshotChanged;
3416
3417#[derive(Debug, Clone)]
3419pub struct Queue {
3420 root: PathBuf,
3421 ids: IdSource,
3422}
3423
3424fn validate_attachments(sources: &[PathBuf]) -> Result<Vec<(&PathBuf, &str)>> {
3425 let mut wanted = Vec::new();
3426 for src in sources {
3427 let name = src
3428 .file_name()
3429 .and_then(|n| n.to_str())
3430 .with_context(|| format!("`{}` has no usable file name", src.display()))?;
3431 if !crate::ask::valid_asset_name(name) {
3432 bail!(
3433 "attachment name `{name}` must match ^[A-Za-z0-9][A-Za-z0-9._-]{{0,63}}$ \
3434 with no `..`; rename the file and try again"
3435 );
3436 }
3437 if !src.is_file() {
3438 bail!("attachment `{}` is not a file", src.display());
3439 }
3440 wanted.push((src, name));
3441 }
3442 Ok(wanted)
3443}
3444
3445impl Queue {
3446 pub fn open() -> Self {
3448 Self::at(crate::run::home().join("queue"))
3449 }
3450
3451 pub fn at(root: PathBuf) -> Self {
3454 Self {
3455 root,
3456 ids: IdSource::new(new_id),
3457 }
3458 }
3459
3460 #[doc(hidden)]
3463 pub fn with_id_source(mut self, f: impl Fn() -> String + Send + Sync + 'static) -> Self {
3464 self.ids = IdSource::custom(f);
3465 self
3466 }
3467
3468 fn file_with(
3479 &self,
3480 task: &mut Task,
3481 hook: impl FnMut(&mut Task) -> Result<bool>,
3482 undo: impl FnMut(&mut Task),
3483 ) -> Result<()> {
3484 self.reserve_id(task, hook, undo, true)
3485 }
3486
3487 fn reserve_id(
3495 &self,
3496 task: &mut Task,
3497 mut hook: impl FnMut(&mut Task) -> Result<bool>,
3498 mut undo: impl FnMut(&mut Task),
3499 store: bool,
3500 ) -> Result<()> {
3501 let redraw_first = self.ids.is_custom() && task.attachments.is_empty();
3502 let initial = task.id.clone();
3503 self.ids
3504 .reserve((!redraw_first).then_some(initial.as_str()), "task", |id| {
3505 task.id = id.to_owned();
3506 let _lock = self.lock_task(&task.id)?;
3507 if path_exists(&self.path_of(&task.id))? || !hook(task)? {
3508 return Ok(false);
3509 }
3510 if store {
3511 task.assign_chat_destination();
3512 if let Err(e) = self.write_record(task) {
3513 undo(task);
3514 return Err(e);
3515 }
3516 task.unfiled = false;
3517 }
3518 Ok(true)
3519 })?;
3520 Ok(())
3521 }
3522
3523 fn id_in_use(&self, id: &str, check_attachments: bool) -> Result<bool> {
3528 if path_exists(&self.lock_path(id))? || path_exists(&self.filing_reservation_path(id))? {
3529 return Ok(true);
3530 }
3531 Ok(check_attachments && path_exists(&self.attachments_dir(id))?)
3532 }
3533
3534 fn plain_filing_hook(&self, task: &Task) -> Result<bool> {
3538 Ok(!self.id_in_use(&task.id, task.attachments.is_empty())?)
3539 }
3540
3541 pub fn file_claimed(&self, task: &mut Task) -> Result<Claim> {
3544 let mut claim = None;
3545 self.file_with(
3546 task,
3547 |t| {
3548 if self.id_in_use(&t.id, true)? {
3549 return Ok(false);
3550 }
3551 claim = Some(self.claim(&t.id)?);
3552 Ok(true)
3553 },
3554 |_| {},
3555 )?;
3556 claim.context("claim missing after filing")
3557 }
3558
3559 pub fn root(&self) -> &Path {
3561 &self.root
3562 }
3563
3564 pub fn path_of(&self, id: &str) -> PathBuf {
3566 self.root.join(format!("{id}.json"))
3567 }
3568
3569 pub fn attachments_dir(&self, id: &str) -> PathBuf {
3572 self.root.join(format!("{id}.attachments"))
3573 }
3574
3575 pub fn attach(&self, task: &mut Task, sources: &[PathBuf]) -> Result<Vec<String>> {
3586 let wanted = validate_attachments(sources)?;
3587 if task.unfiled && task.attachments.is_empty() {
3588 let names = std::cell::RefCell::new(Vec::new());
3591 self.reserve_id(
3592 task,
3593 |t| {
3594 if self.id_in_use(&t.id, true)? {
3595 return Ok(false);
3596 }
3597 *names.borrow_mut() = self.copy_attachments(t, &wanted)?;
3598 Ok(true)
3599 },
3600 |_| {},
3601 false,
3602 )?;
3603 return Ok(names.into_inner());
3604 }
3605 self.copy_attachments(task, &wanted)
3606 }
3607
3608 fn copy_attachments(
3610 &self,
3611 task: &mut Task,
3612 wanted: &[(&PathBuf, &str)],
3613 ) -> Result<Vec<String>> {
3614 let dir = self.attachments_dir(&task.id);
3615 let existed = dir.is_dir();
3616 std::fs::create_dir_all(&dir).with_context(|| format!("create {}", dir.display()))?;
3617 let mut created: Vec<PathBuf> = Vec::new();
3618 let mut names = Vec::new();
3619 let mut copy_all = || -> Result<()> {
3620 for (src, name) in wanted {
3621 let (stored, path) = copy_new(&dir, src, name)?;
3622 created.push(path);
3623 names.push(stored);
3624 }
3625 Ok(())
3626 };
3627 if let Err(e) = copy_all() {
3628 for path in &created {
3629 let _ = std::fs::remove_file(path);
3630 }
3631 if !existed {
3632 let _ = std::fs::remove_dir(&dir);
3633 }
3634 return Err(e);
3635 }
3636 task.attachments.extend(names.iter().cloned());
3637 Ok(names)
3638 }
3639
3640 pub fn attach_and_put(&self, task: &mut Task, sources: &[PathBuf]) -> Result<Vec<String>> {
3651 if task.unfiled && task.attachments.is_empty() {
3652 return self.attach_and_file(task, sources);
3653 }
3654 let dir = self.attachments_dir(&task.id);
3655 let existed = dir.is_dir();
3656 let before = task.attachments.len();
3657 let names = self.attach(task, sources)?;
3658 if let Err(e) = self.put(task) {
3659 for name in &names {
3660 let _ = std::fs::remove_file(dir.join(name));
3661 }
3662 if !existed {
3663 let _ = std::fs::remove_dir(&dir);
3664 }
3665 task.attachments.truncate(before);
3666 return Err(e);
3667 }
3668 Ok(names)
3669 }
3670
3671 fn attach_and_file(&self, task: &mut Task, sources: &[PathBuf]) -> Result<Vec<String>> {
3675 let wanted = validate_attachments(sources)?;
3676 let before = task.attachments.len();
3677 let names = std::cell::RefCell::new(Vec::new());
3678 let result = self.file_with(
3679 task,
3680 |t| {
3681 if self.id_in_use(&t.id, true)? {
3682 return Ok(false);
3683 }
3684 *names.borrow_mut() = self.copy_attachments(t, &wanted)?;
3685 Ok(true)
3686 },
3687 |t| {
3688 let dir = self.attachments_dir(&t.id);
3689 for name in names.borrow().iter() {
3690 let _ = std::fs::remove_file(dir.join(name));
3691 }
3692 let _ = std::fs::remove_dir(&dir);
3694 t.attachments.truncate(before);
3695 },
3696 );
3697 result.map(|()| names.into_inner())
3698 }
3699
3700 pub fn attachment_paths(&self, task: &Task) -> Vec<PathBuf> {
3704 let dir = self.attachments_dir(&task.id);
3705 task.attachments
3706 .iter()
3707 .map(|n| {
3708 let p = dir.join(n);
3709 std::path::absolute(&p).unwrap_or(p)
3710 })
3711 .collect()
3712 }
3713
3714 pub fn put(&self, task: &mut Task) -> Result<()> {
3723 if task.unfiled {
3724 return self.file_with(task, |t| self.plain_filing_hook(t), |_| {});
3726 }
3727 let _lock = self.lock_task(&task.id)?;
3728 self.put_unlocked(task)
3729 }
3730
3731 pub fn create_new(&self, task: &mut Task) -> Result<bool> {
3736 let _lock = self.lock_task(&task.id)?;
3737 if path_exists(&self.path_of(&task.id))?
3738 || path_exists(&self.filing_reservation_path(&task.id))?
3739 {
3740 return Ok(false);
3741 }
3742 task.assign_chat_destination();
3743 self.write_record(task)?;
3744 task.unfiled = false;
3745 Ok(true)
3746 }
3747
3748 fn filing_reservation_path(&self, id: &str) -> PathBuf {
3749 self.root.join(format!("{id}.filing-reservation"))
3750 }
3751
3752 pub(crate) fn reserve_unused_id(&self) -> Result<String> {
3757 let mut chosen = String::new();
3758 self.ids.reserve(None, "task", |id| {
3759 let _lock = self.lock_task(id)?;
3760 if path_exists(&self.path_of(id))?
3761 || path_exists(&self.tombstone_path(id))?
3762 || self.id_in_use(id, true)?
3763 {
3764 return Ok(false);
3765 }
3766 std::fs::File::create_new(self.filing_reservation_path(id))?.sync_all()?;
3767 chosen = id.to_owned();
3768 Ok(true)
3769 })?;
3770 Ok(chosen)
3771 }
3772
3773 pub(crate) fn file_with_exact_id(
3783 &self,
3784 task: &mut Task,
3785 sources: &[PathBuf],
3786 allow_clean_unfiled_attachments: bool,
3787 verify_attachments: impl FnOnce(&Task) -> Result<()>,
3788 ) -> Result<bool> {
3789 let wanted = validate_attachments(sources)?;
3790 let _lock = self.lock_task(&task.id)?;
3791 anyhow::ensure!(
3792 path_exists(&self.filing_reservation_path(&task.id))?,
3793 "task id {} has no durable filing reservation",
3794 task.id
3795 );
3796 if path_exists(&self.path_of(&task.id))? {
3797 return Ok(false);
3798 }
3799 anyhow::ensure!(
3801 !path_exists(&self.tombstone_path(&task.id))?,
3802 "reserved task {} was deleted; refusing to file it again",
3803 task.id
3804 );
3805 if path_exists(&self.lock_path(&task.id))? {
3806 bail!(
3807 "reserved task id {} is claimed; cannot finish filing",
3808 task.id
3809 );
3810 }
3811 let dir = self.attachments_dir(&task.id);
3812 if path_exists(&dir)? {
3813 if allow_clean_unfiled_attachments {
3814 std::fs::remove_dir_all(&dir)
3815 .with_context(|| format!("clean partial attachments {}", dir.display()))?;
3816 } else {
3817 bail!(
3818 "reserved task id {} already has an attachment directory",
3819 task.id
3820 );
3821 }
3822 }
3823 if !wanted.is_empty() {
3824 let before = task.attachments.len();
3825 let names = self.copy_attachments(task, &wanted)?;
3826 if let Err(e) = verify_attachments(task).and_then(|()| self.write_record(task)) {
3827 for name in &names {
3828 let _ = std::fs::remove_file(dir.join(name));
3829 }
3830 let _ = std::fs::remove_dir(&dir);
3831 task.attachments.truncate(before);
3832 return Err(e);
3833 }
3834 } else {
3835 verify_attachments(task)?;
3836 self.write_record(task)?;
3837 }
3838 task.unfiled = false;
3839 Ok(true)
3840 }
3841
3842 fn put_unlocked(&self, task: &mut Task) -> Result<()> {
3844 self.merge_stored(task);
3845 if let Some(boundary) = task.reassignments.last() {
3846 let stored = self.get(&task.id)?;
3847 anyhow::ensure!(
3848 task.reassignments == stored.reassignments
3849 && task.repo == stored.repo
3850 && task.runs.get(..boundary.run_boundary)
3851 == stored.runs.get(..boundary.run_boundary),
3852 "historical repository execution cannot be restarted; reload the task"
3853 );
3854 }
3855 self.write_record(task)
3856 }
3857
3858 pub(crate) fn commit_base_recovery(
3860 &self,
3861 task: &mut Task,
3862 expected: &serde_json::Value,
3863 ) -> Result<()> {
3864 let _lock = self.lock_task(&task.id)?;
3865 anyhow::ensure!(
3866 serde_json::to_value(self.get(&task.id)?)? == *expected,
3867 "task changed during base recovery; inspect the pending authorization"
3868 );
3869 self.put_unlocked(task)
3871 }
3872
3873 pub(crate) fn commit_land_sync_recovery(
3875 &self,
3876 task: &mut Task,
3877 expected: &serde_json::Value,
3878 ) -> Result<()> {
3879 let _lock = self.lock_task(&task.id)?;
3880 anyhow::ensure!(
3881 serde_json::to_value(self.get(&task.id)?)? == *expected,
3882 "task changed during landing base-sync recovery; inspect the pending authorization"
3883 );
3884 self.put_unlocked(task)
3885 }
3886
3887 pub(crate) fn commit_instruction_revision(
3889 &self,
3890 task: &mut Task,
3891 expected: &serde_json::Value,
3892 ) -> Result<()> {
3893 let _lock = self.lock_task(&task.id)?;
3894 anyhow::ensure!(
3895 serde_json::to_value(self.get(&task.id)?)? == *expected,
3896 "task changed during instruction revision; inspect the pending receipt"
3897 );
3898 self.put_unlocked(task)
3899 }
3900
3901 pub(crate) fn commit_repair_grant(
3902 &self,
3903 task: &mut Task,
3904 expected: &serde_json::Value,
3905 ) -> Result<()> {
3906 let _lock = self.lock_task(&task.id)?;
3907 anyhow::ensure!(
3908 serde_json::to_value(self.get(&task.id)?)? == *expected,
3909 "repair grant refused: task changed during admission"
3910 );
3911 self.write_record(task)
3912 .context(crate::repair_budget::PublicationUnknown)
3913 }
3914
3915 pub(crate) fn commit_disk_wait(&self, task: &mut Task, expected: &Task) -> Result<()> {
3917 let _lock = self.lock_task(&task.id)?;
3918 anyhow::ensure!(
3919 serde_json::to_value(self.get(&task.id)?)? == serde_json::to_value(expected)?,
3920 "task changed during disk monitoring"
3921 );
3922 task.stamp_schema();
3923 self.write_record_inner(task, false)
3924 }
3925
3926 pub(crate) fn commit_reassignment(&self, task: &mut Task, expected: &Task) -> Result<()> {
3928 let _lock = self.lock_task(&task.id)?;
3929 let stored = self.get(&task.id)?;
3930 anyhow::ensure!(
3931 serde_json::to_value(&stored)? == serde_json::to_value(expected)?
3932 && stored.reassignments.len() + 1 == task.reassignments.len()
3933 && stored.repo == task.reassignments.last().expect("new boundary").from
3934 && stored.runs == task.runs,
3935 "task changed during reassignment; retry after inspecting it"
3936 );
3937 self.write_record(task)
3938 }
3939
3940 pub(crate) fn commit_completion(&self, task: &mut Task, expected: &Task) -> Result<()> {
3942 let _lock = self.lock_task(&task.id)?;
3943 anyhow::ensure!(
3944 serde_json::to_value(self.get(&task.id)?)? == serde_json::to_value(expected)?,
3945 CompletionSnapshotChanged
3946 );
3947 self.write_record(task)
3948 }
3949
3950 fn merge_stored(&self, task: &mut Task) {
3952 if let Ok(mut stored) = read_path(&self.path_of(&task.id)) {
3953 stored.import_chat_notice();
3954 let local_decision = task.completion_history.iter().any(|event| {
3957 !stored
3958 .completion_history
3959 .iter()
3960 .any(|saved| saved.occurrence == event.occurrence)
3961 && event.at > stored.updated_at
3962 });
3963 let unseen_decision = stored.completion_history.iter().any(|event| {
3964 !task
3965 .completion_history
3966 .iter()
3967 .any(|mine| mine.occurrence == event.occurrence)
3968 });
3969 let mut history = std::mem::take(&mut stored.completion_history);
3970 for event in std::mem::take(&mut task.completion_history) {
3971 if !history
3972 .iter()
3973 .any(|stored| stored.occurrence == event.occurrence)
3974 {
3975 history.push(event);
3976 }
3977 }
3978 if unseen_decision {
3979 task.import_chat_notice();
3982 let mut stale = std::mem::replace(task, stored);
3983 append_missing(&mut task.answers, stale.answers);
3984 if task.reassignments == stale.reassignments {
3985 append_missing(&mut task.runs, stale.runs);
3986 }
3987 for (ledger, entries) in [
3988 (&mut task.decision_effects, stale.decision_effects),
3989 (&mut task.superseded_resumes, stale.superseded_resumes),
3990 (&mut task.dispatched_resumes, stale.dispatched_resumes),
3991 ] {
3992 for (key, value) in entries {
3993 ledger.entry(key).or_insert(value);
3994 }
3995 }
3996 append_missing(&mut task.actions_applied, stale.actions_applied);
3997 append_missing(&mut task.triage_applied, stale.triage_applied);
3998 append_missing(&mut task.chat_notices, stale.chat_notices);
3999 append_missing(
4000 &mut task.base_recovery_requests,
4001 stale.base_recovery_requests,
4002 );
4003 append_missing(
4004 &mut task.land_sync_recovery_requests,
4005 stale.land_sync_recovery_requests,
4006 );
4007 append_missing(
4008 &mut task.instruction_revision_requests,
4009 stale.instruction_revision_requests,
4010 );
4011 prepend_missing_by(&mut task.repair_grants, stale.repair_grants, |a, b| {
4014 a.request.request == b.request.request
4015 });
4016 prepend_missing_by(
4017 &mut task.repair_reconciliations,
4018 stale.repair_reconciliations,
4019 |a, b| a.request.request == b.request.request,
4020 );
4021 stale.resumption_history.extend(stale.resumption);
4024 stale.resumption_history.retain(|approval| {
4025 task.resumption
4026 .as_ref()
4027 .is_none_or(|r| r.at != approval.at || r.generation != approval.generation)
4028 });
4029 prepend_missing_by(
4030 &mut task.resumption_history,
4031 stale.resumption_history,
4032 |a, b| a.at == b.at && a.generation == b.generation,
4033 );
4034 for failure in stale.startup_failures {
4035 task.record_startup_failure(failure);
4036 }
4037 for pass in stale.passes {
4038 if !task.passes.iter().any(|stored| {
4039 stored.run == pass.run && stored.pass_index == pass.pass_index
4040 }) {
4041 task.passes.push(pass);
4042 }
4043 }
4044 task.completion_history = history;
4045 if !task.decision_effects.is_empty() {
4046 task.stamp_schema();
4047 }
4048 return;
4049 }
4050 if stored.reassignments.len() > task.reassignments.len() {
4051 let stale = std::mem::replace(task, stored.clone());
4054 for answer in stale.answers {
4055 if !task.answers.contains(&answer) {
4056 task.answers.push(answer);
4057 }
4058 }
4059 }
4060 if task.updated_at < stored.updated_at
4063 && (task.sync_only != stored.sync_only
4064 || stored.sync_only.is_some()
4065 || (task.reopen_hold.is_some() && task.reopen_hold != stored.reopen_hold)
4066 || stored
4067 .recovery_budget_hold
4068 .as_ref()
4069 .is_some_and(|hold| hold.held_at > task.updated_at)
4070 || stored.repair_grants.last().is_some_and(|grant| {
4071 task.repair_grants.last() != Some(grant)
4072 || stored.operator_decided_at > task.operator_decided_at
4073 || stored
4074 .resume_override
4075 .as_ref()
4076 .is_some_and(|pin| pin.at > task.updated_at)
4077 || (task.resume_override != stored.resume_override
4078 && task
4079 .resume_override
4080 .as_ref()
4081 .is_some_and(|pin| pin.at == grant.at))
4082 }))
4083 && task
4084 .operator_decided_at
4085 .is_none_or(|at| at <= stored.updated_at)
4086 && task
4087 .resume_override
4088 .as_ref()
4089 .is_none_or(|pin| pin.at <= stored.updated_at)
4090 && !local_decision
4091 {
4092 *task = stored.clone();
4093 }
4094 task.completion_history = history;
4095 append_missing(
4096 &mut task.base_recovery_requests,
4097 stored.base_recovery_requests,
4098 );
4099 append_missing(
4100 &mut task.land_sync_recovery_requests,
4101 stored.land_sync_recovery_requests,
4102 );
4103 append_missing(
4104 &mut task.instruction_revision_requests,
4105 stored.instruction_revision_requests,
4106 );
4107 append_missing(&mut task.actions_applied, stored.actions_applied);
4108 append_missing(&mut task.triage_applied, stored.triage_applied);
4109 for receipt in &stored.repair_grants {
4110 if !task
4111 .repair_grants
4112 .iter()
4113 .any(|r| r.request.request == receipt.request.request)
4114 {
4115 task.repair_grants.push(receipt.clone());
4117 }
4118 }
4119 for receipt in &stored.repair_reconciliations {
4120 if !task.repair_reconciliations.contains(receipt) {
4121 task.repair_reconciliations.push(receipt.clone());
4124 task.resume_override = stored.resume_override.clone();
4125 task.status = stored.status;
4126 task.hold_source = stored.hold_source;
4127 task.machine_hold_cause = stored.machine_hold_cause.clone();
4128 task.disk_resume_run = stored.disk_resume_run.clone();
4129 task.disk_checked_at = stored.disk_checked_at;
4130 task.hold_reason = stored.hold_reason.clone();
4131 task.held_at = stored.held_at;
4132 }
4133 }
4134 task.superseded_resumes.extend(stored.superseded_resumes);
4135 task.dispatched_resumes.extend(stored.dispatched_resumes);
4136 if task.status != TaskStatus::Running
4137 && let Some(pin) = &stored.resume_override
4138 && !pin.question_id.is_empty()
4139 && let Some(run) = &pin.pinned_run
4140 && task.resume_override.as_ref().is_none_or(|next| {
4141 next.question_id != pin.question_id || next.pinned_run != pin.pinned_run
4142 })
4143 {
4144 task.superseded_resumes
4145 .insert(pin.question_id.clone(), run.clone());
4146 }
4147 for (id, receipt) in stored.decision_effects {
4150 task.decision_effects.insert(id, receipt);
4151 }
4152 if !task.decision_effects.is_empty() {
4153 task.stamp_schema();
4154 }
4155 if task.chat.is_none() {
4158 task.chat = stored.chat.clone();
4159 }
4160 if task.issue.is_none() {
4161 task.issue = stored.issue.clone();
4162 }
4163 append_missing(&mut task.chat_notices, stored.chat_notices);
4164 task.chat_reservation = task.chat_reservation.max(stored.chat_reservation);
4165 for failure in stored.startup_failures {
4166 task.record_startup_failure(failure);
4167 }
4168 append_missing(&mut task.runs, stored.runs);
4169 for p in stored.passes {
4170 if !task
4171 .passes
4172 .iter()
4173 .any(|q| q.run == p.run && q.pass_index == p.pass_index)
4174 {
4175 task.passes.push(p);
4176 }
4177 }
4178 if let Some(n) = stored.chat_notice
4181 && task.chat_notice.as_ref().is_none_or(|mine| mine.at < n.at)
4182 {
4183 task.chat_notice = Some(n);
4184 }
4185 if task.landing.is_none()
4187 && let Some(note) = stored.landing
4188 && task.status == stored.status
4189 && task.instruction_rev == stored.instruction_rev
4190 && task.investigation == stored.investigation
4191 && task.execution_runs().last() == Some(¬e.run)
4192 {
4193 task.landing = Some(note);
4194 }
4195 }
4196 }
4197
4198 pub(crate) fn cache_landing(
4201 &self,
4202 observed: &Task,
4203 note: crate::landing::LandingNote,
4204 ) -> Result<()> {
4205 let Ok(_claim) = self.claim(&observed.id) else {
4206 return Ok(());
4207 };
4208 let _lock = self.lock_task(&observed.id)?;
4209 let mut task = self.get(&observed.id)?;
4210 if task.updated_at == observed.updated_at
4211 && task.status == observed.status
4212 && task.investigation == observed.investigation
4213 && task.instruction_rev == observed.instruction_rev
4214 && task.landing == observed.landing
4215 && task.repo == observed.repo
4216 && task.reassignments == observed.reassignments
4217 && (crate::landing::audited_run(&task) == Some(note.run.as_str())
4218 || crate::landing::awaiting_landing_run(&task) == Some(note.run.as_str()))
4219 {
4220 task.stamp_schema();
4221 task.landing = Some(note);
4222 self.write_startup_history(&task)?;
4223 }
4224 Ok(())
4225 }
4226
4227 pub(crate) fn write_startup_history(&self, task: &Task) -> Result<()> {
4230 let path = self.path_of(&task.id);
4231 let tmp = path.with_extension("json.tmp");
4232 std::fs::write(&tmp, serde_json::to_vec_pretty(task)?)?;
4233 std::fs::rename(tmp, path)?;
4234 Ok(())
4235 }
4236
4237 fn write_record(&self, task: &mut Task) -> Result<()> {
4239 self.write_record_inner(task, true)
4240 }
4241
4242 fn write_record_inner(&self, task: &mut Task, notify: bool) -> Result<()> {
4243 if task.investigation
4244 || task.completion_result.is_some()
4245 || task.instruction_rev > 0
4246 || task.landing.is_some()
4247 {
4248 task.stamp_schema();
4249 }
4250 task.import_chat_notice();
4251 if task.status != TaskStatus::Held && task.sync_only.is_none() {
4252 task.recovery_budget_hold = None;
4253 }
4254 task.updated_at = Timestamp::now();
4255 std::fs::create_dir_all(&self.root)
4256 .with_context(|| format!("create {}", self.root.display()))?;
4257 let body = serde_json::to_string_pretty(task).context("serialize task")?;
4258 let path = self.path_of(&task.id);
4259 let tmp = path.with_extension("json.tmp");
4260 std::fs::write(&tmp, &body).with_context(|| format!("write {}", tmp.display()))?;
4261 std::fs::rename(&tmp, &path).with_context(|| format!("replace {}", path.display()))?;
4262 if let (Some(notice), Some(home)) = (
4267 notify.then(|| crate::notices::task_held(task)).flatten(),
4268 self.root.parent().filter(|p| !p.as_os_str().is_empty()),
4269 ) {
4270 crate::notices::raise_in(home, notice);
4271 }
4272 Ok(())
4273 }
4274
4275 pub fn modify(&self, id: &str, f: impl FnOnce(&mut Task) -> bool) -> Result<bool> {
4280 let id = self.resolve_id(id)?;
4281 let _lock = self.lock_task(&id)?;
4282 let mut task = self.get(&id)?;
4283 if !f(&mut task) {
4284 return Ok(false);
4285 }
4286 self.put_unlocked(&mut task)?;
4287 Ok(true)
4288 }
4289
4290 pub fn link_run(&self, id: &str, run: &str) -> Result<Task> {
4295 let id = self.resolve_id(id)?;
4296 let _lock = self.lock_task(&id)?;
4299 let mut task = self.get(&id)?;
4300 if task.link_run(run) {
4301 self.put_unlocked(&mut task)?;
4302 }
4303 Ok(task)
4304 }
4305
4306 pub(crate) fn lock_task(&self, id: &str) -> Result<TaskLock> {
4314 std::fs::create_dir_all(&self.root)
4315 .with_context(|| format!("create {}", self.root.display()))?;
4316 let path = self.root.join(format!("{id}.write-lock"));
4317 let started = std::time::Instant::now();
4318 let retry = crate::lock_file::Retry::task_write(started + TASK_LOCK_STALE);
4319 let marker_retry = crate::lock_file::Retry::new(Some(started + TASK_LOCK_STALE));
4320 loop {
4321 match retry.create(&path) {
4322 Ok(mut file) => {
4323 use std::io::Write;
4324 let token = owner_token();
4325 if let Err(e) = file.write_all(token.as_bytes()) {
4326 drop(file);
4327 let _ = std::fs::remove_file(&path);
4328 return Err(e).with_context(|| format!("lock {}", path.display()));
4329 }
4330 return Ok(TaskLock { path, token });
4331 }
4332 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
4333 let judged = std::fs::read_to_string(&path).ok();
4336 let broken = judged
4337 .filter(|_| older_than_stale(&path))
4338 .is_some_and(|judged| break_stale_with(&path, &judged, marker_retry));
4339 if !broken {
4343 if started.elapsed() > TASK_LOCK_STALE {
4344 bail!("could not lock task {id}");
4345 }
4346 std::thread::sleep(std::time::Duration::from_millis(15));
4347 }
4348 }
4349 Err(e) => return Err(e).with_context(|| format!("lock {}", path.display())),
4350 }
4351 }
4352 }
4353
4354 pub fn get(&self, id: &str) -> Result<Task> {
4356 let resolved = self.resolve_id(id)?;
4357 read_path(&self.path_of(&resolved))
4358 }
4359
4360 pub fn remove(&self, id: &str, in_flight: bool, questions: &Questions) -> Result<Removal> {
4392 self.remove_with_receipt(id, in_flight, questions, None)
4393 }
4394
4395 pub(crate) fn discard_triage(
4397 &self,
4398 id: &str,
4399 questions: &Questions,
4400 inquiry: &str,
4401 ) -> Result<Removal> {
4402 self.remove_with_receipt(id, false, questions, Some(inquiry))
4403 }
4404
4405 pub(crate) fn triage_discard_applied(&self, id: &str, inquiry: &str) -> Result<bool> {
4406 let path = self
4407 .root
4408 .join("triage-discard")
4409 .join(format!("{inquiry}.json"));
4410 let bytes = match std::fs::read(path) {
4411 Ok(bytes) => bytes,
4412 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(false),
4413 Err(e) => return Err(e.into()),
4414 };
4415 let receipt: Task = serde_json::from_slice(&bytes)?;
4416 Ok(receipt.id == id && !self.path_of(id).exists())
4417 }
4418
4419 fn remove_with_receipt(
4420 &self,
4421 id: &str,
4422 in_flight: bool,
4423 questions: &Questions,
4424 inquiry: Option<&str>,
4425 ) -> Result<Removal> {
4426 let resolved = self.resolve_id(id)?;
4427 if in_flight {
4428 bail!("task {resolved} is being run by a live daemon right now");
4429 }
4430 let receipt = inquiry.map(|q| self.root.join("triage-discard").join(format!("{q}.json")));
4431 if let Some(path) = &receipt {
4432 std::fs::create_dir_all(path.parent().expect("receipt directory"))?;
4433 }
4434 self.write_tombstone(&resolved)?;
4435 if let Err(e) = self.remove_record_with_attachments(&resolved, |p| match &receipt {
4436 Some(path) => std::fs::rename(p, path),
4437 None => std::fs::remove_file(p),
4438 }) {
4439 if self.path_of(&resolved).exists() {
4443 let _ = std::fs::remove_file(self.tombstone_path(&resolved));
4444 }
4445 return Err(e);
4446 }
4447 let (released, still_blocked) = self.release_dependents_of(&resolved, questions);
4448 Ok(Removal {
4449 id: resolved,
4450 released,
4451 still_blocked,
4452 })
4453 }
4454
4455 fn tombstone_path(&self, id: &str) -> PathBuf {
4458 self.root.join(format!("{id}.removed"))
4459 }
4460
4461 fn write_tombstone(&self, id: &str) -> Result<()> {
4462 let path = self.tombstone_path(id);
4463 let tmp = self.root.join(format!("{id}.removed.tmp"));
4464 std::fs::write(&tmp, b"")
4465 .and_then(|()| std::fs::rename(&tmp, &path))
4466 .with_context(|| format!("write {}", path.display()))
4467 }
4468
4469 fn was_deleted(&self, id: &str) -> bool {
4473 self.tombstone_path(id).is_file() && !self.path_of(id).exists()
4474 }
4475
4476 pub fn apply_deleted_blockers(&self, task: &mut Task, questions: &Questions) -> Vec<String> {
4480 let deleted = deleted_blockers(self, questions, &task.blocked_by);
4481 deleted
4482 .into_iter()
4483 .filter(|id| task.dependency_deleted(id))
4484 .collect()
4485 }
4486
4487 pub fn note_dependency_deleted(&self, dependent: &Task, deleted: &str) {
4491 let Some(home) = self.root.parent().filter(|p| !p.as_os_str().is_empty()) else {
4492 return;
4493 };
4494 let ja = crate::lang::is_japanese(&crate::lang::of_repo(&dependent.repo));
4495 let waiting = dependent.status == TaskStatus::Blocked;
4496 let message = match (ja, waiting) {
4497 (true, false) => format!(
4498 "タスク {} は、待っていた {} が削除されたため待機を解除し、元の状態に戻しました",
4499 dependent.short(),
4500 short(deleted)
4501 ),
4502 (true, true) => format!(
4503 "タスク {} は、待っていた {} が削除されたため、残りの依存を待っています",
4504 dependent.short(),
4505 short(deleted)
4506 ),
4507 (false, false) => format!(
4508 "Task {} stopped waiting on {} because it was deleted, and returned to its previous state",
4509 dependent.short(),
4510 short(deleted)
4511 ),
4512 (false, true) => format!(
4513 "Task {} stopped waiting on {} because it was deleted, and is still waiting on its other dependencies",
4514 dependent.short(),
4515 short(deleted)
4516 ),
4517 };
4518 crate::notices::raise_in(
4519 home,
4520 crate::notices::Notice::info(
4521 &format!("unblocked:{}:{}", dependent.id, deleted),
4522 message,
4523 )
4524 .link(crate::notices::Link::Task {
4525 id: dependent.id.clone(),
4526 }),
4527 );
4528 }
4529
4530 fn release_dependents_of(
4535 &self,
4536 dependency: &str,
4537 questions: &Questions,
4538 ) -> (Vec<String>, Vec<String>) {
4539 let (mut released, mut still_blocked) = (Vec::new(), Vec::new());
4540 for listed in self.list() {
4541 if listed.status != TaskStatus::Blocked || !listed.blocked_by.iter().any(|b| {
4542 matches!(crate::queue::dependency(self, questions, b), Dependency::Deleted(id) if id == dependency)
4543 }) {
4544 continue;
4545 }
4546 let Ok(_claim) = self.claim(&listed.id) else {
4547 continue;
4548 };
4549 let Ok(mut task) = self.get(&listed.id) else {
4550 continue;
4551 };
4552 let references: Vec<String> = task.blocked_by.iter().filter(|id| {
4553 matches!(crate::queue::dependency(self, questions, id), Dependency::Deleted(full) if full == dependency)
4554 }).cloned().collect();
4555 if references.is_empty() {
4556 continue;
4557 }
4558 for reference in references {
4559 task.dependency_deleted(&reference);
4560 }
4561 if self.put(&mut task).is_err() {
4562 continue;
4563 }
4564 self.note_dependency_deleted(&task, dependency);
4565 if task.status == TaskStatus::Blocked {
4566 still_blocked.push(task.id.clone());
4567 } else {
4568 released.push(task.id.clone());
4569 }
4570 }
4571 (released, still_blocked)
4572 }
4573
4574 fn remove_record_with_attachments(
4578 &self,
4579 resolved: &str,
4580 remove_record: impl FnOnce(&Path) -> std::io::Result<()>,
4581 ) -> Result<()> {
4582 self.sweep_removed_attachments();
4589 let attachments = self.attachments_dir(resolved);
4590 let aside = self.root.join(format!("{resolved}.attachments.removing"));
4591 let moved = match std::fs::rename(&attachments, &aside) {
4592 Ok(()) => true,
4593 Err(e) if e.kind() == std::io::ErrorKind::NotFound => false,
4594 Err(e) => {
4595 return Err(e).with_context(|| format!("remove {}", attachments.display()));
4596 }
4597 };
4598 let path = self.path_of(resolved);
4599 if let Err(e) = remove_record(&path) {
4600 if moved {
4601 let _ = std::fs::rename(&aside, &attachments);
4602 }
4603 return Err(e).with_context(|| format!("remove {}", path.display()));
4604 }
4605 if moved {
4606 if let Err(e) = std::fs::remove_dir_all(&aside) {
4607 tracing::warn!("leftover attachments {}: {e}", aside.display());
4608 }
4609 }
4610 let lock = self.lock_path(resolved);
4611 if let Err(e) = std::fs::remove_file(&lock) {
4612 if e.kind() != std::io::ErrorKind::NotFound {
4613 return Err(e).with_context(|| format!("remove {}", lock.display()));
4614 }
4615 }
4616 Ok(())
4617 }
4618
4619 fn sweep_removed_attachments(&self) {
4625 let Ok(entries) = std::fs::read_dir(&self.root) else {
4626 return;
4627 };
4628 for entry in entries.flatten() {
4629 let name = entry.file_name();
4630 let name = name.to_string_lossy();
4631 let Some(id) = name.strip_suffix(".attachments.removing") else {
4632 continue;
4633 };
4634 if !self.path_of(id).exists() {
4637 if let Err(e) = std::fs::remove_dir_all(entry.path()) {
4638 tracing::warn!("leftover attachments {}: {e}", entry.path().display());
4639 }
4640 }
4641 }
4642 self.sweep_tombstones();
4643 }
4644
4645 fn sweep_tombstones(&self) {
4654 let Ok(entries) = std::fs::read_dir(&self.root) else {
4655 return;
4656 };
4657 let tasks = self.list();
4658 for entry in entries.flatten() {
4659 let name = entry.file_name();
4660 let name = name.to_string_lossy();
4661 let Some(id) = name.strip_suffix(".removed") else {
4662 continue;
4663 };
4664 if self.path_of(id).exists()
4665 || tasks.iter().any(|t| {
4666 t.blocked_by
4667 .iter()
4668 .any(|b| id.starts_with(b) || id.ends_with(b))
4669 })
4670 {
4671 continue;
4672 }
4673 let old = entry
4674 .metadata()
4675 .and_then(|m| m.modified())
4676 .ok()
4677 .and_then(|m| m.elapsed().ok())
4678 .is_some_and(|age| age >= TOMBSTONE_GRACE);
4679 if old {
4680 let _ = std::fs::remove_file(entry.path());
4681 }
4682 }
4683 }
4684
4685 fn lock_path(&self, id: &str) -> PathBuf {
4688 self.root.join(format!("{id}.lock"))
4689 }
4690
4691 pub fn list(&self) -> Vec<Task> {
4704 #[cfg(test)]
4705 LIST_READS.with(|count| count.set(count.get() + 1));
4706 let mut tasks: Vec<Task> = std::fs::read_dir(&self.root)
4707 .into_iter()
4708 .flatten()
4709 .flatten()
4710 .map(|e| e.path())
4711 .filter(|p| p.extension().is_some_and(|x| x == "json"))
4712 .filter_map(|p| read_path(&p).ok())
4713 .collect();
4714 tasks.sort_unstable_by(|a, b| b.priority.cmp(&a.priority).then_with(|| b.id.cmp(&a.id)));
4715 tasks
4716 }
4717
4718 pub fn unreadable(&self) -> Vec<PathBuf> {
4722 std::fs::read_dir(&self.root)
4723 .into_iter()
4724 .flatten()
4725 .flatten()
4726 .map(|e| e.path())
4727 .filter(|p| p.extension().is_some_and(|x| x == "json"))
4728 .filter(|p| read_path(p).is_err())
4729 .collect()
4730 }
4731
4732 pub fn superseded(&self) -> HashMap<String, String> {
4745 let mut by = HashMap::new();
4746 for task in self.list() {
4747 for earlier in &task.runs {
4748 if let Some(later) = task.successor_of(earlier) {
4749 by.insert(earlier.clone(), later.clone());
4750 }
4751 }
4752 }
4753 by
4754 }
4755
4756 pub fn superseded_by(&self, run: &str) -> Option<String> {
4764 for task in self.list() {
4765 if task.runs.iter().any(|r| r == run) {
4766 return task.successor_of(run).cloned();
4767 }
4768 }
4769 None
4770 }
4771
4772 pub fn latest_attempt(&self, run: &str) -> Option<String> {
4783 for task in self.list() {
4784 if task.runs.iter().any(|r| r == run) {
4785 return task.runs.last().filter(|last| **last != run).cloned();
4786 }
4787 }
4788 None
4789 }
4790
4791 pub fn next_runnable(&self) -> Option<Task> {
4796 let mut runnable: Vec<Task> = self
4797 .list()
4798 .into_iter()
4799 .filter(|t| t.status.runnable())
4800 .collect();
4801 runnable.sort_unstable_by(dispatch_order);
4802 runnable.into_iter().next()
4803 }
4804
4805 pub fn claim(&self, id: &str) -> Result<Claim> {
4812 let claim = self.claim_for_instruction_revision(id)?;
4813 if let Some(home) = self.root.parent()
4816 && let Ok(task) = self.get(id)
4817 && let Some(run) = task.execution_runs().last()
4818 && let Ok(state) = crate::run::RunState::load_under(run, home)
4819 && let Some(revision) = state.instruction_revisions.last()
4820 {
4821 anyhow::ensure!(
4822 task.instruction_revision_requests
4823 .contains(&revision.request),
4824 InstructionAdoptionPending
4825 );
4826 }
4827 Ok(claim)
4828 }
4829
4830 pub(crate) fn claim_for_instruction_revision(&self, id: &str) -> Result<Claim> {
4833 std::fs::create_dir_all(&self.root)
4834 .with_context(|| format!("create {}", self.root.display()))?;
4835 let path = self.lock_path(id);
4836 let retry = crate::lock_file::Retry::new(None);
4837 match retry.create(&path) {
4838 Ok(mut f) => {
4839 use std::io::Write as _;
4840 let _ = writeln!(f, "{}", std::process::id());
4842 Ok(Claim { path })
4843 }
4844 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
4845 bail!("task {id} is already claimed ({} exists)", path.display())
4846 }
4847 Err(e) => Err(e).with_context(|| format!("lock {}", path.display())),
4848 }
4849 }
4850
4851 #[must_use]
4854 pub fn is_claimed(&self, id: &str) -> bool {
4855 self.lock_path(id).exists()
4856 }
4857
4858 pub fn resolve_id(&self, prefix: &str) -> Result<String> {
4860 if !prefix.is_empty()
4861 && prefix != "."
4862 && prefix != ".."
4863 && !prefix.contains(['/', '\\'])
4864 && self.path_of(prefix).is_file()
4865 {
4866 return Ok(prefix.to_owned());
4867 }
4868 let ids = record_ids(&self.root, "json")?;
4869 match resolve_reference(prefix, ids.iter().map(String::as_str)) {
4870 Reference::Found(id) => Ok(id),
4871 Reference::Missing => bail!("no task matches `{prefix}`"),
4872 Reference::Ambiguous => bail!("`{prefix}` matches multiple tasks"),
4873 }
4874 }
4875
4876 pub fn revision(&self) -> u64 {
4883 self.revision_excluding(&std::collections::BTreeSet::new())
4884 }
4885
4886 pub fn revision_excluding(&self, skip: &std::collections::BTreeSet<String>) -> u64 {
4889 use std::hash::{Hash as _, Hasher as _};
4890
4891 let mut entries: Vec<(String, u64)> = std::fs::read_dir(&self.root)
4892 .into_iter()
4893 .flatten()
4894 .flatten()
4895 .filter(|e| e.path().extension().is_some_and(|ext| ext == "json"))
4896 .filter(|e| {
4897 let path = e.path();
4898 !path
4899 .file_stem()
4900 .is_some_and(|stem| skip.contains(stem.to_string_lossy().as_ref()))
4901 })
4902 .filter_map(|e| {
4903 let name = e.file_name().to_string_lossy().into_owned();
4904 let mtime = e
4905 .metadata()
4906 .ok()?
4907 .modified()
4908 .ok()?
4909 .duration_since(std::time::UNIX_EPOCH)
4910 .ok()?
4911 .as_millis() as u64;
4912 Some((name, mtime))
4913 })
4914 .collect();
4915
4916 if entries.is_empty() {
4917 return 0;
4918 }
4919
4920 entries.sort_unstable();
4921 let mut hasher = std::hash::DefaultHasher::new();
4922 for (name, mtime) in &entries {
4923 name.hash(&mut hasher);
4924 mtime.hash(&mut hasher);
4925 }
4926 let h = hasher.finish();
4927 if h == 0 { 1 } else { h }
4928 }
4929}
4930
4931const TOMBSTONE_GRACE: std::time::Duration = std::time::Duration::from_secs(3600);
4934
4935#[derive(Debug, Clone)]
4937pub struct Removal {
4938 pub id: String,
4940 pub released: Vec<String>,
4944 pub still_blocked: Vec<String>,
4947}
4948
4949#[derive(Debug, thiserror::Error)]
4950#[error("interrupted instruction adoption; replay the owner request before claiming the task")]
4951pub(crate) struct InstructionAdoptionPending;
4952
4953#[derive(Debug)]
4955pub struct Claim {
4956 path: PathBuf,
4957}
4958
4959impl Drop for Claim {
4960 fn drop(&mut self) {
4961 let _ = std::fs::remove_file(&self.path);
4962 }
4963}
4964
4965pub fn title_from(instruction: &str, max: usize) -> String {
4968 let Some(line) = first_line(instruction) else {
4969 return "(empty task)".to_owned();
4970 };
4971 if line.chars().count() <= max {
4972 return line.to_owned();
4973 }
4974 let head: String = line.chars().take(max.saturating_sub(1)).collect();
4975 format!("{head}…")
4976}
4977
4978pub(crate) fn first_line(instruction: &str) -> Option<&str> {
4984 let line = instruction
4985 .lines()
4986 .map(str::trim)
4987 .find(|l| !l.is_empty())?
4988 .trim_start_matches(['#', '-', '*', '>', ' '])
4989 .trim();
4990 (!line.is_empty()).then_some(line)
4991}
4992
4993#[cfg(test)]
4994thread_local! {
4995 pub(crate) static TASK_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4996}
4997
4998fn read_path(path: &Path) -> Result<Task> {
4999 #[cfg(test)]
5000 TASK_READS.with(|count| count.set(count.get() + 1));
5001 let body = std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;
5002 let mut task: Task =
5003 serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))?;
5004 if task.schema > SCHEMA {
5010 bail!(
5011 "task {} was written by a different magi (schema {}, this build \
5012 speaks {SCHEMA})",
5013 task.id,
5014 task.schema
5015 );
5016 }
5017 task.preserve_legacy_build_cache();
5018 task.snapshot_legacy_reopen_hold();
5019 if task.schema < 22
5020 && task.status == TaskStatus::Held
5021 && task.hold_source == Some(HoldSource::Machine)
5022 && task.resume_override.is_none()
5023 && task
5024 .hold_reason
5025 .as_deref()
5026 .is_some_and(crate::disk::is_gate_reason)
5027 {
5028 task.mark_disk_capacity();
5029 }
5030 Ok(task)
5031}
5032
5033#[derive(Debug, PartialEq, Eq)]
5036pub(crate) enum Reference {
5037 Found(String),
5038 Missing,
5039 Ambiguous,
5040}
5041
5042pub(crate) fn resolve_reference<'a>(id: &str, ids: impl Iterator<Item = &'a str>) -> Reference {
5043 let mut hits = Vec::new();
5044 for candidate in ids {
5045 if candidate == id {
5046 return Reference::Found(candidate.to_owned());
5047 }
5048 if candidate.starts_with(id) || candidate.ends_with(id) {
5049 hits.push(candidate);
5050 }
5051 }
5052 match hits.as_slice() {
5053 [] => Reference::Missing,
5054 [one] => Reference::Found((*one).to_owned()),
5055 _ => Reference::Ambiguous,
5056 }
5057}
5058
5059pub(crate) fn record_ids(root: &Path, extension: &str) -> Result<Vec<String>> {
5062 let entries = match std::fs::read_dir(root) {
5063 Ok(entries) => entries,
5064 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
5065 Err(e) => return Err(e.into()),
5066 };
5067 let mut ids = Vec::new();
5068 for entry in entries {
5069 let path = entry?.path();
5070 if path.extension().is_some_and(|e| e == extension)
5071 && let Some(id) = path.file_stem().and_then(|s| s.to_str())
5072 {
5073 ids.push(id.to_owned());
5074 }
5075 }
5076 Ok(ids)
5077}
5078
5079#[derive(Debug, PartialEq, Eq)]
5082pub enum Dependency {
5083 Task(String),
5085 Question(String),
5087 Deleted(String),
5089 Missing,
5091 Ambiguous,
5093 Unknown,
5095}
5096
5097pub fn dependency(queue: &Queue, questions: &Questions, id: &str) -> Dependency {
5099 let (Ok(tasks), Ok(qs), Ok(removed)) = (
5100 record_ids(queue.root(), "json"),
5101 record_ids(questions.root(), "json"),
5102 record_ids(queue.root(), "removed"),
5103 ) else {
5104 return Dependency::Unknown;
5105 };
5106 let mut ids = tasks
5109 .iter()
5110 .chain(qs.iter())
5111 .chain(removed.iter())
5112 .cloned()
5113 .collect::<Vec<_>>();
5114 ids.sort();
5115 ids.dedup();
5116 match resolve_reference(id, ids.iter().map(String::as_str)) {
5117 Reference::Found(id) if tasks.contains(&id) => Dependency::Task(id),
5118 Reference::Found(id) if qs.contains(&id) => Dependency::Question(id),
5119 Reference::Found(id) if queue.was_deleted(&id) => Dependency::Deleted(id),
5120 Reference::Found(_) => Dependency::Unknown,
5121 Reference::Missing => Dependency::Missing,
5122 Reference::Ambiguous => Dependency::Ambiguous,
5123 }
5124}
5125
5126pub fn normalize_blockers(queue: &Queue, questions: &Questions, ids: &mut [String]) {
5128 for id in ids {
5129 if let Dependency::Task(full) | Dependency::Question(full) | Dependency::Deleted(full) =
5130 dependency(queue, questions, id)
5131 {
5132 *id = full;
5133 }
5134 }
5135}
5136
5137pub fn dependency_facts(queue: &Queue, questions: &Questions) -> String {
5140 let inventory = crate::blockers::Inventory::load(queue, questions);
5141 let mut text = String::from(
5142 "Current authoritative queue (historical missing-task claims may be stale; unreadable or ambiguous references must keep waiting):\n",
5143 );
5144 match record_ids(queue.root(), "json") {
5145 Ok(ids) => {
5146 for id in ids {
5147 match queue.get(&id) {
5148 Ok(task) => text.push_str(&format!(
5149 "{}: {}; blocked_by={:?}; chain={:?}\n",
5150 task.id,
5151 task.status.as_str(),
5152 task.blocked_by,
5153 inventory.waits_on(&task)
5154 )),
5155 Err(_) => text.push_str(&format!("{id}: exists, state unreadable\n")),
5156 }
5157 }
5158 }
5159 Err(_) => text.push_str("Queue inventory unreadable: existence is unknown.\n"),
5160 }
5161 text
5162}
5163
5164pub fn missing_blockers(
5166 queue: &Queue,
5167 questions: &Questions,
5168 blocked_by: &[String],
5169) -> Vec<String> {
5170 blocked_by
5171 .iter()
5172 .filter(|id| dependency(queue, questions, id) == Dependency::Missing)
5173 .cloned()
5174 .collect()
5175}
5176
5177pub fn deleted_blockers(
5180 queue: &Queue,
5181 questions: &Questions,
5182 blocked_by: &[String],
5183) -> Vec<String> {
5184 blocked_by
5185 .iter()
5186 .filter(|id| matches!(dependency(queue, questions, id), Dependency::Deleted(_)))
5187 .cloned()
5188 .collect()
5189}
5190
5191pub fn missing_blocker_hold_reason(blocked_by: &[String], missing: &[String]) -> String {
5203 missing_blocker_hold_reason_in(blocked_by, missing, "en")
5204}
5205
5206pub fn missing_blocker_hold_reason_in(
5208 blocked_by: &[String],
5209 missing: &[String],
5210 language: &str,
5211) -> String {
5212 if crate::lang::is_japanese(language) {
5213 format!(
5214 "{} を待っていましたが、{} はディスク上に存在しません - `magi task triage` を参照",
5215 blocked_by.join(", "),
5216 missing.join(", "),
5217 )
5218 } else {
5219 format!(
5220 "blocked on {} but {} no longer exist(s) on disk - see `magi task triage`",
5221 blocked_by.join(", "),
5222 missing.join(", "),
5223 )
5224 }
5225}
5226
5227pub fn short(id: &str) -> &str {
5229 id.split('-').next_back().unwrap_or(id)
5230}
5231
5232fn new_id() -> String {
5233 let stamp = jiff::Zoned::now().strftime("%Y%m%d-%H%M%S");
5234 let seed = crate::rng::entropy();
5235 format!("{stamp}-{:04x}", (seed ^ (seed >> 32)) & 0xffff)
5236}
5237
5238#[cfg(test)]
5239mod tests {
5240 #[test]
5241 fn reassignment_clears_repository_bound_execution_selections() {
5242 let mut task = Task::new(
5243 "move".into(),
5244 "evidence".into(),
5245 "old".into(),
5246 Source::Human,
5247 );
5248 task.review_branch = Some("old-review".into());
5249 task.review_instruction = Some("old criteria".into());
5250 task.pr_recovery = Some(crate::pr_recovery::Selection {
5251 url: "https://example.invalid/pull/1".into(),
5252 branch: "old-pr".into(),
5253 head: "head".into(),
5254 source_head: None,
5255 source_run: None,
5256 source_proof: None,
5257 disposition: None,
5258 instruction: "old criteria".into(),
5259 approved_at: Timestamp::now(),
5260 });
5261 task.replacement = Some(crate::merge_decision::Replacement {
5262 question: "owner".into(),
5263 run: "old-run".into(),
5264 pr: "https://example.invalid/pull/1".into(),
5265 agent: "worker".into(),
5266 context: "evidence".into(),
5267 });
5268 task.resume_override = Some(OperatorResume {
5269 question_id: "old-question".into(),
5270 at: Timestamp::now(),
5271 conductor_rehold: None,
5272 forced: true,
5273 pinned_run: Some("old-run".into()),
5274 });
5275 task.interrupt = true;
5276 task.reassign_repository("new".into(), "test");
5277 assert!(task.review_branch.is_none());
5278 assert!(task.review_instruction.is_none());
5279 assert!(task.pr_recovery.is_none());
5280 assert!(task.replacement.is_none());
5281 assert!(task.resume_override.is_none());
5282 assert!(!task.interrupt);
5283 assert!(task.fresh_start);
5284 assert_eq!(task.instruction, "evidence");
5285 }
5286
5287 #[test]
5288 fn explicit_resumption_is_not_invented_for_legacy_or_automatic_release() {
5289 let t = Task::new(
5290 "retry".into(),
5291 "do it".into(),
5292 PathBuf::from("."),
5293 Source::Human,
5294 );
5295 let mut value = serde_json::to_value(&t).unwrap();
5296 for field in ["resumption", "resumption_history", "operator_decided_at"] {
5297 value.as_object_mut().unwrap().remove(field);
5298 }
5299 value["schema"] = serde_json::json!(15);
5300 let mut legacy: Task = serde_json::from_value(value).unwrap();
5301 legacy.hold_machine(Some("automatic retry".into()));
5302 legacy.release();
5303 assert!(legacy.resumption.is_none());
5304 assert!(legacy.resumption_history.is_empty());
5305 assert!(legacy.operator_decided_at.is_none());
5306 legacy.release_operator("cli", None);
5307 legacy.start("run".into());
5308 let reloaded: Task =
5309 serde_json::from_str(&serde_json::to_string(&legacy).unwrap()).unwrap();
5310 assert!(reloaded.resume_override.is_none());
5311 assert_eq!(reloaded.resumption.as_ref().unwrap().generation, 1);
5312 }
5313
5314 #[test]
5315 fn merge_over_lets_the_later_choice_win_and_keeps_the_rest() {
5316 let mut base = RunOverrides {
5317 merge: Some("pr".to_owned()),
5318 candidates: Some(3),
5319 ..RunOverrides::default()
5320 };
5321 base.merge_over(&RunOverrides {
5322 merge: Some("none".to_owned()),
5323 seed: Some(7),
5324 ..RunOverrides::default()
5325 });
5326 assert_eq!(base.merge.as_deref(), Some("none"));
5327 assert_eq!(base.candidates, Some(3));
5328 assert_eq!(base.seed, Some(7));
5329 }
5330
5331 #[test]
5332 fn an_already_landed_task_is_done_with_its_attempt_refunded() {
5333 let mut t = task("relanded");
5334 t.attempts = 1;
5335 t.status = TaskStatus::Running;
5336 t.already_landed("already in main as 0e368de", completion(&t));
5337 assert_eq!(t.status, TaskStatus::Done);
5338 assert_eq!(t.attempts, 0);
5339 assert!(t.hold_reason.is_none());
5340 assert_eq!(t.last_error.as_deref(), Some("already in main as 0e368de"));
5341 }
5342
5343 #[test]
5344 fn missing_blocker_reason_follows_the_language() {
5345 let b = vec!["a".to_owned()];
5346 let en = missing_blocker_hold_reason_in(&b, &b, "en");
5347 assert_eq!(en, missing_blocker_hold_reason(&b, &b));
5348 assert!(en.starts_with("blocked on a"));
5349 assert!(missing_blocker_hold_reason_in(&b, &b, "ja").contains("存在しません"));
5350 assert_eq!(missing_blocker_hold_reason_in(&b, &b, "de"), en);
5351 }
5352
5353 use super::*;
5354
5355 fn completion(task: &Task) -> CompletionContext {
5356 CompletionContext::new(CompletionActor::Cli, None, Path::new("."), task)
5357 }
5358
5359 #[test]
5360 fn completion_retains_the_hold_dependency_and_failure_it_clears() {
5361 let mut held = task("held evidence");
5362 held.hold_manual(Some("owner approval required".into()));
5363 held.last_error = Some("review budget exhausted".into());
5364 held.succeed(completion(&held));
5365 let event = held.completion_history.last().unwrap();
5366 assert_eq!(event.prior_status, TaskStatus::Held);
5367 assert_eq!(
5368 event.prior_hold_reason.as_deref(),
5369 Some("owner approval required")
5370 );
5371 assert_eq!(
5372 event.prior_error.as_deref(),
5373 Some("review budget exhausted")
5374 );
5375 assert!(held.hold_reason.is_none());
5376 assert!(held.last_error.is_none());
5377 let mut blocked = task("dependency evidence");
5378 blocked.block(
5379 vec!["dependency".into()],
5380 Some("waiting on migration".into()),
5381 );
5382 blocked.succeed(completion(&blocked));
5383 let event = blocked.completion_history.last().unwrap();
5384 assert_eq!(event.prior_status, TaskStatus::Blocked);
5385 assert_eq!(
5386 event.prior_block_reason.as_deref(),
5387 Some("waiting on migration")
5388 );
5389 assert!(blocked.block_reason.is_none());
5390 assert!(blocked.blocked_by.is_empty());
5391 let saved = serde_json::to_vec(&held).unwrap();
5392 let restored: Task = serde_json::from_slice(&saved).unwrap();
5393 assert_eq!(restored.completion_history, held.completion_history);
5394 }
5395
5396 #[test]
5397 fn completion_audit_is_append_only_under_stale_puts() {
5398 let dir = tempfile::tempdir().unwrap();
5399 let queue = Queue::at(dir.path().join("queue"));
5400 let mut current = task("audited");
5401 current.hold_manual(Some("inspect".into()));
5402 queue.put(&mut current).unwrap();
5403 let mut stale = queue.get(¤t.id).unwrap();
5404 current.succeed(completion(¤t));
5405 queue.put(&mut current).unwrap();
5406 let original = current.completion_history[0].clone();
5407 stale.last_error = Some("stale control state".into());
5408 queue.put(&mut stale).unwrap();
5409 assert_eq!(stale.status, TaskStatus::Done);
5410 assert_eq!(stale.completion_history, vec![original.clone()]);
5411 let mut context = completion(¤t);
5412 context.reason = Some("not actually finished".into());
5413 current.reopen(context).unwrap();
5414 queue.put(&mut current).unwrap();
5415 stale.completion_history[0].actor = CompletionActor::Web;
5416 stale.completion_history[0].reason = Some("rewritten evidence".into());
5417 queue.put(&mut stale).unwrap();
5418 assert_eq!(stale.status, TaskStatus::Held);
5419 assert_eq!(stale.hold_reason.as_deref(), Some("not actually finished"));
5420 assert_eq!(stale.completion_history[0], original);
5421 assert_eq!(stale.completion_history, current.completion_history);
5422 }
5423
5424 #[test]
5425 fn a_writer_missing_a_reopen_contributes_receipts_but_not_authority() {
5426 let (_dir, q) = queue();
5427 let mut current = task("durable receipts");
5428 q.put(&mut current).unwrap();
5429 let mut stale = current.clone();
5430 let grant: crate::repair_budget::Receipt = serde_json::from_value(serde_json::json!({
5431 "request": {
5432 "task": current.id, "run": "old-run", "kind": "gate", "rounds": 1,
5433 "head": "old-head", "expect_pass": 0, "request": "old-grant", "reason": "retry"
5434 },
5435 "at": stale.updated_at, "contract": "old-contract"
5436 }))
5437 .unwrap();
5438 stale.release_operator("triage", Some("triage-question"));
5439 stale.queue_repair(&grant);
5440 let reconciliation: crate::repair_budget::reconcile::Receipt =
5441 serde_json::from_value(serde_json::json!({
5442 "request": {
5443 "task": current.id, "run": "old-run", "head": "old-head", "expect_pass": 0,
5444 "receipt": "old-grant", "question": "triage-question", "answer_at": grant.at,
5445 "request": "reconciliation", "reason": "retain the answer"
5446 },
5447 "grant": grant, "source": "answer", "application": "release",
5448 "decision": grant.at, "superseded_questions": []
5449 }))
5450 .unwrap();
5451 stale.repair_reconciliations.push(reconciliation.clone());
5452 stale.triage_applied.push("triage-question".into());
5453 stale.actions_applied.push("choice".into());
5454 stale.base_recovery_requests.push("base-request".into());
5455 stale.chat_notices.push("delivery".into());
5456 stale.chat_notice = Some(ChatNotice {
5457 key: "other-delivery".into(),
5458 at: grant.at,
5459 outcome: ChatNoticeOutcome::Posted,
5460 });
5461 for ledger in [
5462 &mut stale.decision_effects,
5463 &mut stale.dispatched_resumes,
5464 &mut stale.superseded_resumes,
5465 ] {
5466 ledger.insert("shared".into(), "stale".into());
5467 ledger.insert("only-stale".into(), "receipt".into());
5468 }
5469
5470 let mut latest_grant = grant.clone();
5471 latest_grant.request.request = "new-grant".into();
5472 current.queue_repair(&latest_grant);
5473 for ledger in [
5474 &mut current.decision_effects,
5475 &mut current.dispatched_resumes,
5476 &mut current.superseded_resumes,
5477 ] {
5478 ledger.insert("shared".into(), "committed".into());
5479 }
5480 current.succeed(completion(¤t));
5481 let mut context = completion(¤t);
5482 context.reason = Some("inspect again".into());
5483 current.reopen(context).unwrap();
5484 q.put(&mut current).unwrap();
5485
5486 for _ in 0..2 {
5487 q.put(&mut stale.clone()).unwrap();
5488 let saved = q.get(¤t.id).unwrap();
5489 assert_eq!(saved.status, TaskStatus::Held);
5490 assert_eq!(saved.hold_reason, current.hold_reason);
5491 assert_eq!(saved.operator_decided_at, current.operator_decided_at);
5492 assert_eq!(saved.completion_history, current.completion_history);
5493 assert!(saved.resume_override.is_none());
5494 assert!(saved.resumption.is_none());
5495 assert_eq!(
5496 saved.resumption_history,
5497 [stale.resumption.clone().unwrap()]
5498 );
5499 assert_eq!(saved.triage_applied, ["triage-question"]);
5500 assert_eq!(saved.actions_applied, ["choice"]);
5501 assert_eq!(saved.base_recovery_requests, ["base-request"]);
5502 assert_eq!(saved.chat_notices, ["delivery", "other-delivery"]);
5503 assert_eq!(saved.repair_grants, [grant.clone(), latest_grant.clone()]);
5504 assert_eq!(
5505 saved.repair_reconciliations,
5506 std::slice::from_ref(&reconciliation)
5507 );
5508 for ledger in [
5509 saved.decision_effects,
5510 saved.dispatched_resumes,
5511 saved.superseded_resumes,
5512 ] {
5513 assert_eq!(ledger["shared"], "committed");
5514 assert_eq!(ledger["only-stale"], "receipt");
5515 }
5516 }
5517 }
5518
5519 #[test]
5520 fn repeated_completion_only_notifies_for_new_occurrences() {
5521 let mut task = chat_task();
5522 task.succeed(completion(&task));
5523 let first = task.chat_notice_key().unwrap();
5524 task.chat_notices.push(first.clone());
5525 task.succeed(completion(&task));
5526 assert_eq!(task.completion_history.len(), 1, "idempotent while done");
5527 assert_eq!(task.chat_notice_due(), None);
5528 let mut context = completion(&task);
5529 context.reason = Some("inspect".into());
5530 task.reopen(context).unwrap();
5531 task.succeed(completion(&task));
5532 let second = task.chat_notice_key().unwrap();
5533 assert_ne!(first, second);
5534 assert_eq!(task.chat_notice_due(), Some(second));
5535 assert_eq!(task.completion_history.len(), 3);
5536 }
5537
5538 #[test]
5539 fn old_tasks_have_unknown_completion_provenance_not_invented_events() {
5540 let mut task = task("legacy");
5541 task.status = TaskStatus::Done;
5542 let mut value = serde_json::to_value(&task).unwrap();
5543 value.as_object_mut().unwrap().remove("completion_history");
5544 let task: Task = serde_json::from_value(value).unwrap();
5545 assert!(task.completion_history.is_empty());
5546 assert_eq!(task.chat_notice_key().as_deref(), Some("done"));
5547 }
5548
5549 #[test]
5550 fn triage_applied_survives_release_and_old_records_read_as_empty() {
5551 let mut t = Task::new(
5552 "t".to_owned(),
5553 "i".to_owned(),
5554 PathBuf::from("r"),
5555 Source::Human,
5556 );
5557 t.mark_triage_applied("q1");
5558 t.mark_triage_applied("q1");
5559 t.hold_machine(Some("x".to_owned()));
5560 t.release();
5561 assert_eq!(t.triage_applied, ["q1"]);
5562 assert!(t.triage_applied("q1") && !t.triage_applied("q2"));
5563
5564 let mut v = serde_json::to_value(&t).unwrap();
5565 v.as_object_mut().unwrap().remove("triage_applied");
5566 let old: Task = serde_json::from_value(v).unwrap();
5567 assert!(old.triage_applied.is_empty());
5568 }
5569
5570 #[test]
5571 fn task_counts_of_empty_is_all_zero() {
5572 assert_eq!(TaskCounts::of(&[]), TaskCounts::default());
5573 }
5574
5575 #[test]
5576 fn task_counts_of_tallies_every_status() {
5577 let mut queued = Task::new(
5578 "q".to_owned(),
5579 "i".to_owned(),
5580 PathBuf::from("."),
5581 Source::Human,
5582 );
5583 queued.status = TaskStatus::Queued;
5584 let mut running = queued.clone();
5585 running.status = TaskStatus::Running;
5586 let mut done = queued.clone();
5587 done.status = TaskStatus::Done;
5588 let mut failed = queued.clone();
5589 failed.status = TaskStatus::Failed;
5590 let mut held = queued.clone();
5591 held.status = TaskStatus::Held;
5592 let mut blocked = queued.clone();
5593 blocked.status = TaskStatus::Blocked;
5594
5595 let mut parked = queued.clone();
5596 parked.status = TaskStatus::Parked;
5597
5598 let counts = TaskCounts::of(&[
5599 queued,
5600 running,
5601 done.clone(),
5602 done,
5603 failed,
5604 held,
5605 blocked,
5606 parked,
5607 ]);
5608 assert_eq!(
5609 counts,
5610 TaskCounts {
5611 queued: 1,
5612 running: 1,
5613 done: 2,
5614 failed: 1,
5615 held: 1,
5616 blocked: 1,
5617 parked: 1,
5618 }
5619 );
5620 }
5621
5622 #[test]
5623 fn task_implementers_persist_normalized_without_losing_history() {
5624 let (_dir, q) = queue();
5625 let mut t = task("keep me");
5626 t.hold_manual(Some("waiting".into()));
5627 t.runs.push("earlier-run".into());
5628 t.attachments.push("reference.txt".into());
5629 let cfg: crate::config::Config =
5630 toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
5631 .unwrap();
5632 q.put(&mut t).unwrap();
5633 let original = serde_json::to_value(&t).unwrap();
5634 for n in [2, 1, 2] {
5635 t.set_implementers(n, &cfg).unwrap();
5636 q.put(&mut t).unwrap();
5637 t = q.get(&t.id).unwrap();
5638 assert_eq!(t.implementers(), Some(usize::from(n)));
5639 assert_eq!(t.solo, n == 1);
5640 if n == 1 {
5641 assert!(t.overrides.is_none());
5642 }
5643 let mut actual = serde_json::to_value(&t).unwrap();
5644 for field in ["solo", "overrides", "updated_at"] {
5645 actual[field] = original[field].clone();
5646 }
5647 assert_eq!(actual, original);
5648 }
5649 t.overrides.as_mut().unwrap().judges = Some(2);
5650 t.set_implementers(1, &cfg).unwrap();
5651 assert_eq!(t.overrides.as_ref().unwrap().judges, Some(2));
5652 assert_eq!(t.overrides.as_ref().unwrap().candidates, None);
5653 }
5654
5655 #[test]
5656 fn task_implementers_old_records_keep_inheritance_until_changed() {
5657 let mut value = serde_json::to_value(task("old task")).unwrap();
5658 value.as_object_mut().unwrap().remove("solo");
5659 value.as_object_mut().unwrap().remove("overrides");
5660 let mut old: Task = serde_json::from_value(value).unwrap();
5661 assert_eq!(old.implementers(), None);
5662 old.set_implementers(1, &crate::config::Config::default())
5663 .unwrap();
5664 assert!(old.solo);
5665 assert!(old.overrides.is_none());
5666 }
5667
5668 #[test]
5669 fn task_implementers_reject_invalid_counts_and_states() {
5670 let cfg = crate::config::Config::default();
5671 let mut t = task("unchanged");
5672 for n in [0, 4, 255] {
5673 assert!(t.set_implementers(n, &cfg).is_err());
5674 }
5675 for status in [
5676 TaskStatus::Running,
5677 TaskStatus::Done,
5678 TaskStatus::Failed,
5679 TaskStatus::Blocked,
5680 TaskStatus::Parked,
5681 ] {
5682 t.status = status;
5683 let before = serde_json::to_value(&t).unwrap();
5684 assert!(t.set_implementers(1, &cfg).is_err());
5685 assert_eq!(serde_json::to_value(&t).unwrap(), before);
5686 }
5687 }
5688
5689 fn queue() -> (tempfile::TempDir, Queue) {
5692 let dir = tempfile::tempdir().unwrap();
5693 let q = Queue::at(dir.path().join("queue"));
5694 (dir, q)
5695 }
5696
5697 #[test]
5698 fn base_recovery_commit_retains_decision_and_superseded_resume_evidence() {
5699 let (_dir, q) = queue();
5700 let mut original = task("base recovery");
5701 original
5702 .decision_effects
5703 .insert("old-effect".into(), "receipt".into());
5704 original
5705 .dispatched_resumes
5706 .insert("dispatched".into(), "prior-run".into());
5707 original.resume_override = Some(OperatorResume {
5708 question_id: "prior-decision".into(),
5709 at: Timestamp::now(),
5710 conductor_rehold: None,
5711 forced: true,
5712 pinned_run: Some("retained-run".into()),
5713 });
5714 q.put(&mut original).unwrap();
5715 let expected = serde_json::to_value(&original).unwrap();
5716 let mut recovered = original.clone();
5717 recovered.base_recovery_requests.push("chat/request".into());
5718 recovered
5719 .resume_override
5720 .as_mut()
5721 .unwrap()
5722 .question_id
5723 .clear();
5724 q.commit_base_recovery(&mut recovered, &expected).unwrap();
5725 let saved = q.get(&original.id).unwrap();
5726 assert_eq!(saved.decision_effects, original.decision_effects);
5727 assert_eq!(saved.dispatched_resumes, original.dispatched_resumes);
5728 assert_eq!(
5729 saved
5730 .superseded_resumes
5731 .get("prior-decision")
5732 .map(String::as_str),
5733 Some("retained-run")
5734 );
5735 assert_eq!(saved.base_recovery_requests, ["chat/request"]);
5736 assert!(saved.resume_override.unwrap().question_id.is_empty());
5737 assert!(q.commit_base_recovery(&mut recovered, &expected).is_err());
5738 }
5739
5740 #[test]
5741 fn a_stale_write_does_not_drop_the_recorded_task_chat() {
5742 let (_dir, q) = queue();
5743 let mut stale = task("chat");
5744 q.put(&mut stale).unwrap();
5745 let mut fresh = q.get(&stale.id).unwrap();
5746 fresh.chat = Some("talk-1".to_owned());
5747 q.put(&mut fresh).unwrap();
5748 q.put(&mut stale).unwrap();
5749 assert_eq!(q.get(&stale.id).unwrap().chat.as_deref(), Some("talk-1"));
5750 }
5751
5752 #[test]
5753 fn putting_a_machine_held_task_files_a_notification_beside_the_queue() {
5754 let dir = tempfile::tempdir().unwrap();
5755 let q = Queue::at(dir.path().join("queue"));
5756 let mut t = task("held");
5757 q.put(&mut t).unwrap();
5758 assert_eq!(
5759 crate::notices::Notices::at(dir.path().join("notifications"))
5760 .list()
5761 .len(),
5762 0
5763 );
5764 t.hold_machine(Some("out of attempts".to_owned()));
5765 q.put(&mut t).unwrap();
5766 let listed = crate::notices::Notices::at(dir.path().join("notifications")).list();
5767 assert_eq!(listed.len(), 1);
5768 assert!(listed[0].message.contains("out of attempts"));
5769 }
5770
5771 #[test]
5772 fn start_consumes_the_disk_resume_pin() {
5773 let mut t = task("pin");
5774 t.disk_resume_run = Some("run-1".into());
5775 t.start("run-1".into());
5776 assert!(t.disk_resume_run.is_none());
5777 }
5778
5779 fn task(title: &str) -> Task {
5780 Task::new(
5781 title.to_owned(),
5782 format!("do {title}"),
5783 PathBuf::from("."),
5784 Source::Human,
5785 )
5786 }
5787
5788 #[test]
5789 fn issue_provenance_survives_queue_round_trip_without_inventing_chat() {
5790 let dir = tempfile::tempdir().unwrap();
5791 let q = Queue::at(dir.path().to_path_buf());
5792 let issue = IssueRef {
5793 number: 42,
5794 repo: "owner/repo".into(),
5795 };
5796 for source in [
5797 Source::Human,
5798 Source::Agent {
5799 run: "20260101-010101-abcd".into(),
5800 node: CHAT_NODE.into(),
5801 },
5802 ] {
5803 let mut t = task("issue");
5804 t.source = source;
5805 t.issue = Some(issue.clone());
5806 q.put(&mut t).unwrap();
5807 let saved = q.get(&t.id).unwrap();
5808 assert_eq!(saved.issue_ref(), Some(issue.clone()));
5809 assert_eq!(saved.source, t.source);
5810 assert_eq!(saved.filed_by_chat(), t.filed_by_chat());
5811 assert_eq!(saved.chat_talk(), t.filed_by_chat());
5812 if saved.source == Source::Human {
5813 assert_eq!(saved.source_label(), "issue #42");
5814 } else {
5815 assert!(saved.source_label().contains("issue #42"));
5816 }
5817 let mut stale = saved;
5818 stale.issue = None;
5819 q.put(&mut stale).unwrap();
5820 assert_eq!(q.get(&t.id).unwrap().issue_ref(), Some(issue.clone()));
5821 }
5822 let mut old = serde_json::to_value(task("legacy")).unwrap();
5823 old["schema"] = serde_json::json!(26);
5824 old["source"] = serde_json::json!({"kind":"issue","number":42,"repo":"owner/repo"});
5825 let legacy: Task = serde_json::from_value(old).unwrap();
5826 assert_eq!(legacy.issue_ref(), Some(issue));
5827 assert_eq!(legacy.filed_by_chat(), None);
5828 assert_eq!(legacy.chat_talk(), None);
5829 assert_eq!(legacy.source_label(), "issue #42");
5830 }
5831
5832 #[test]
5833 fn attempt_limit_inherits_old_records_and_controls_failure() {
5834 let mut t = task("budget");
5835 let mut old = serde_json::to_value(&t).unwrap();
5836 old.as_object_mut().unwrap().remove("attempt_limit");
5837 old["schema"] = serde_json::json!(15);
5838 let legacy: Task = serde_json::from_value(old).unwrap();
5839 assert_eq!(legacy.attempt_limit, None);
5840 assert_eq!(legacy.effective_attempt_limit(2), 2);
5841 t.attempts = 2;
5842 t.change_attempt_limit(NonZeroUsize::new(3)).unwrap();
5843 t.fail("retry", 1);
5844 assert_eq!(t.status, TaskStatus::Failed);
5845 t.attempts = 3;
5846 t.fail("stop", 10);
5847 assert_eq!(t.status, TaskStatus::Held);
5848 t.change_attempt_limit(None).unwrap();
5849 assert_eq!(t.status, TaskStatus::Held);
5850 assert_eq!(t.attempts, 3);
5851 t.fail("inherit", 4);
5852 assert_eq!(t.status, TaskStatus::Failed);
5853 for status in [
5854 TaskStatus::Running,
5855 TaskStatus::Done,
5856 TaskStatus::Failed,
5857 TaskStatus::Blocked,
5858 TaskStatus::Parked,
5859 ] {
5860 t.status = status;
5861 assert!(t.change_attempt_limit(NonZeroUsize::new(1)).is_err());
5862 assert_eq!(t.attempt_limit, None);
5863 }
5864 }
5865
5866 #[test]
5867 fn earlier_attempts_is_every_recorded_run_and_agrees_with_the_display() {
5868 let mut t = task("retried");
5869 assert!(
5870 t.earlier_attempts().is_empty(),
5871 "a first attempt takes nothing over"
5872 );
5873 t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned()];
5874 assert_eq!(t.earlier_attempts(), ["aaaa", "bbbb"]);
5875 assert_eq!(t.successor_of("aaaa"), Some(&"bbbb".to_owned()));
5877 assert_eq!(t.successor_of("bbbb"), None);
5878 assert_eq!(t.successor_of("zzzz"), None);
5879 }
5880
5881 #[test]
5882 fn resumed_runs_are_superseded_only_after_their_last_occurrence() {
5883 let (_dir, q) = queue();
5884 let mut t = task("resumed");
5885 for (runs, successor) in [
5886 (vec!["aaaa", "aaaa"], None),
5887 (vec!["aaaa", "bbbb", "aaaa"], None),
5888 (vec!["aaaa", "aaaa", "bbbb"], Some("bbbb")),
5889 (vec!["aaaa", "bbbb", "aaaa", "cccc"], Some("cccc")),
5890 ] {
5891 t.runs = runs.into_iter().map(str::to_owned).collect();
5892 q.put(&mut t).unwrap();
5893
5894 assert_eq!(t.successor_of("aaaa").map(String::as_str), successor);
5895 assert_eq!(q.superseded_by("aaaa").as_deref(), successor);
5896 assert_eq!(q.superseded().get("aaaa").map(String::as_str), successor);
5897 }
5898 }
5899
5900 #[test]
5901 fn superseded_by_names_the_next_attempt_and_none_for_the_last() {
5902 let (_dir, q) = queue();
5903 let mut t = task("retried");
5904 t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned(), "cccc".to_owned()];
5905 q.put(&mut t).unwrap();
5906
5907 assert_eq!(q.superseded_by("aaaa"), Some("bbbb".to_owned()));
5908 assert_eq!(q.superseded_by("bbbb"), Some("cccc".to_owned()));
5909 assert_eq!(
5910 q.superseded_by("cccc"),
5911 None,
5912 "the latest attempt replaces nothing"
5913 );
5914 assert_eq!(
5915 q.superseded_by("never-heard-of-it"),
5916 None,
5917 "a run belonging to no task on this queue is not superseded"
5918 );
5919
5920 let mut by = HashMap::new();
5921 by.insert("aaaa".to_owned(), "bbbb".to_owned());
5922 by.insert("bbbb".to_owned(), "cccc".to_owned());
5923 assert_eq!(
5924 q.superseded(),
5925 by,
5926 "the whole-map and single-run forms must agree"
5927 );
5928 }
5929
5930 #[test]
5931 fn superseded_attempts_is_empty_until_the_task_is_done() {
5932 let mut t = task("retried");
5933 t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned()];
5934 t.status = TaskStatus::Failed;
5935 assert_eq!(
5936 t.superseded_attempts(true),
5937 &[] as &[String],
5938 "a task still retrying has no attempt yet that a later one made moot"
5939 );
5940
5941 t.status = TaskStatus::Running;
5942 assert_eq!(t.superseded_attempts(true), &[] as &[String]);
5943 }
5944
5945 #[test]
5946 fn superseded_attempts_names_every_run_before_the_one_that_succeeded() {
5947 let mut t = task("retried");
5948 t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned(), "cccc".to_owned()];
5949 t.status = TaskStatus::Done;
5950 assert_eq!(
5951 t.superseded_attempts(true),
5952 &["aaaa".to_owned(), "bbbb".to_owned()],
5953 "cccc is the attempt whose success made the task done, and stays out"
5954 );
5955 }
5956
5957 #[test]
5958 fn superseded_attempts_is_empty_for_a_done_task_with_only_one_attempt() {
5959 let mut t = task("first try landed");
5960 t.runs = vec!["aaaa".to_owned()];
5961 t.status = TaskStatus::Done;
5962 assert_eq!(t.superseded_attempts(true), &[] as &[String]);
5963 }
5964
5965 #[test]
5966 fn superseded_attempts_is_empty_when_the_last_run_never_actually_succeeded() {
5967 let mut t = task("closed by hand after a manual merge");
5974 t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned()];
5975 t.status = TaskStatus::Done;
5976 assert_eq!(
5977 t.superseded_attempts(false),
5978 &[] as &[String],
5979 "nothing here is provably why the task is done, so nothing is superseded"
5980 );
5981 }
5982
5983 #[test]
5984 fn latest_attempt_names_the_chain_s_current_head_not_just_the_next_one() {
5985 let (_dir, q) = queue();
5986 let mut t = task("retried twice");
5987 t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned(), "cccc".to_owned()];
5988 q.put(&mut t).unwrap();
5989
5990 assert_eq!(
5991 q.latest_attempt("aaaa"),
5992 Some("cccc".to_owned()),
5993 "an old attempt points straight at the chain's current head, not the \
5994 next attempt in the middle of it"
5995 );
5996 assert_eq!(q.latest_attempt("bbbb"), Some("cccc".to_owned()));
5997 assert_eq!(
5998 q.latest_attempt("cccc"),
5999 None,
6000 "the latest attempt is not superseded by anything"
6001 );
6002 assert_eq!(
6003 q.latest_attempt("never-heard-of-it"),
6004 None,
6005 "a run belonging to no task on this queue is not superseded"
6006 );
6007 }
6008
6009 #[test]
6010 fn a_markdown_heading_is_the_title_not_decoration() {
6011 assert_eq!(
6016 title_from("# Rework the config loader\n\nIt re-reads it.\n", 40),
6017 "Rework the config loader"
6018 );
6019 assert_eq!(title_from("- fix the thing", 40), "fix the thing");
6020 assert_eq!(title_from("> quoted task", 40), "quoted task");
6021 assert_eq!(title_from(" \n\n", 40), "(empty task)");
6023 assert_eq!(title_from("###\n", 40), "(empty task)");
6024 }
6025
6026 #[test]
6027 fn a_long_title_is_elided_by_characters_not_bytes() {
6028 let long = "課題".repeat(30);
6030 let title = title_from(&long, 10);
6031 assert_eq!(title.chars().count(), 10);
6032 assert!(title.ends_with('…'));
6033 }
6034
6035 #[test]
6036 fn priority_wins_and_ties_break_oldest_first() {
6037 let (_dir, q) = queue();
6038 let mut a = task("first");
6039 let mut b = task("second");
6040 let mut c = task("urgent");
6041 a.id = "20260101-000001-aaaa".to_owned();
6043 b.id = "20260101-000002-bbbb".to_owned();
6044 c.id = "20260101-000003-cccc".to_owned();
6045 c.priority = 5;
6046 for t in [&mut a, &mut b, &mut c] {
6047 q.put(t).unwrap();
6048 }
6049
6050 assert_eq!(q.next_runnable().unwrap().id, c.id);
6052 c.hold_machine(None);
6053 q.put(&mut c).unwrap();
6054 assert_eq!(q.next_runnable().unwrap().id, a.id);
6056 assert_eq!(q.list().len(), 3, "b is still waiting its turn");
6057 }
6058
6059 #[test]
6060 fn a_blocked_task_never_starves_another_runnable_one() {
6061 let (_dir, q) = queue();
6062 let mut blocked = task("blocked");
6063 blocked.block(vec!["something".to_owned()], None);
6064 q.put(&mut blocked).unwrap();
6065
6066 let mut runnable = task("free to go");
6067 q.put(&mut runnable).unwrap();
6068
6069 let next = q.next_runnable().expect("a runnable task is still offered");
6070 assert_eq!(next.id, runnable.id);
6071 }
6072
6073 #[test]
6074 fn a_held_task_is_never_offered_to_the_loop() {
6075 let (_dir, q) = queue();
6076 let mut t = task("held");
6077 q.put(&mut t).unwrap();
6078 assert!(q.next_runnable().is_some());
6079
6080 t.hold_machine(None);
6081 q.put(&mut t).unwrap();
6082 assert!(
6083 q.next_runnable().is_none(),
6084 "a held task must wait for a human"
6085 );
6086
6087 t.status = TaskStatus::Failed;
6089 q.put(&mut t).unwrap();
6090 assert!(q.next_runnable().is_some());
6091 }
6092
6093 #[test]
6094 fn attempts_are_capped_and_then_the_task_is_held() {
6095 let mut t = task("doomed");
6096
6097 t.start("run-1".to_owned());
6098 t.fail("gate red", 2);
6099 assert_eq!(t.status, TaskStatus::Failed, "one attempt of two: retry");
6100
6101 t.start("run-2".to_owned());
6102 t.fail("gate red", 2);
6103 assert_eq!(
6104 t.status,
6105 TaskStatus::Held,
6106 "out of attempts: stop spending money on it"
6107 );
6108 assert_eq!(t.runs, ["run-1", "run-2"]);
6109 assert_eq!(t.last_error.as_deref(), Some("gate red"));
6110 assert_eq!(
6111 t.hold_reason.as_deref(),
6112 Some("gate red"),
6113 "the hold must say why, not leave hold_reason null next to a \
6114 populated last_error"
6115 );
6116 }
6117
6118 #[test]
6119 fn handing_off_a_task_records_a_hold_reason_too() {
6120 let mut t = task("left a pull request");
6121 t.start("run-1".to_owned());
6122 t.handed_off("run ended with a pull request open [run run-1]");
6123 assert_eq!(t.status, TaskStatus::Held);
6124 assert_eq!(t.hold_source, Some(HoldSource::Machine));
6125 assert_eq!(
6126 t.hold_reason.as_deref(),
6127 Some("run ended with a pull request open [run run-1]")
6128 );
6129 assert_eq!(t.hold_reason, t.last_error);
6130 }
6131
6132 #[test]
6133 fn a_quota_stall_is_refunded_so_the_backlog_survives_the_night() {
6134 let mut t = task("stalled by quota");
6135
6136 t.start("run-1".to_owned());
6137 assert_eq!(t.attempts, 1);
6138 t.stall("judge-1, judge-2 out of quota");
6139 assert_eq!(
6140 t.attempts, 0,
6141 "a closed quota window must not spend the task's retry budget"
6142 );
6143 assert_eq!(t.status, TaskStatus::Failed, "the loop should retry it");
6144 assert_eq!(
6145 t.last_error.as_deref(),
6146 Some("judge-1, judge-2 out of quota")
6147 );
6148
6149 for _ in 0..20 {
6152 t.start("run-n".to_owned());
6153 t.stall("still out of quota");
6154 }
6155 t.start("run-real".to_owned());
6156 t.fail("gate red", 2);
6157 assert_eq!(
6158 t.status,
6159 TaskStatus::Failed,
6160 "the first attempt that was really judged is attempt one"
6161 );
6162 }
6163
6164 #[test]
6165 fn releasing_a_held_task_gives_it_a_real_second_chance() {
6166 let mut t = task("retry me");
6167 t.start("run-1".to_owned());
6168 t.fail("gate red", 1);
6169 assert_eq!(t.status, TaskStatus::Held);
6170
6171 t.release();
6172 assert_eq!(t.status, TaskStatus::Queued);
6173 assert_eq!(t.attempts, 0);
6176 assert!(t.last_error.is_none());
6177 assert_eq!(
6178 t.runs.len(),
6179 1,
6180 "history is kept: attempts reset, evidence does not"
6181 );
6182 }
6183
6184 #[test]
6185 fn a_hold_reason_survives_and_a_release_clears_it() {
6186 let mut t = task("waiting on something else");
6187 t.hold_manual(Some(
6188 "waiting for 20260101-000000-aaaa to land first".to_owned(),
6189 ));
6190 assert_eq!(t.status, TaskStatus::Held);
6191 assert_eq!(
6192 t.hold_reason.as_deref(),
6193 Some("waiting for 20260101-000000-aaaa to land first")
6194 );
6195
6196 t.hold_manual(None);
6198 assert_eq!(
6199 t.hold_reason.as_deref(),
6200 Some("waiting for 20260101-000000-aaaa to land first"),
6201 "a bare re-hold keeps whatever a human already wrote down"
6202 );
6203
6204 let mut plain = task("no reason given");
6206 plain.hold_manual(None);
6207 assert_eq!(plain.status, TaskStatus::Held);
6208 assert!(plain.hold_reason.is_none());
6209
6210 t.release();
6211 assert_eq!(t.status, TaskStatus::Queued);
6212 assert!(
6213 t.hold_reason.is_none(),
6214 "a stale reason must not greet the next person who holds this task"
6215 );
6216 }
6217
6218 #[test]
6219 fn closing_a_held_task_as_done_clears_its_hold_reason_too() {
6220 let mut t = task("landed by hand while held");
6225 t.hold_manual(Some("waiting on 3ed9".to_owned()));
6226 assert_eq!(t.hold_reason.as_deref(), Some("waiting on 3ed9"));
6227
6228 t.succeed(completion(&t));
6229 assert_eq!(t.status, TaskStatus::Done);
6230 assert!(
6231 t.hold_reason.is_none(),
6232 "a done task cannot still be waiting on something"
6233 );
6234 }
6235
6236 #[test]
6237 fn holding_or_closing_a_blocked_task_clears_its_dependency_too() {
6238 let mut held = task("held straight out of blocked");
6245 held.block(
6246 vec!["20260101-000000-dead".to_owned()],
6247 Some("waiting on the migration script".to_owned()),
6248 );
6249 assert_eq!(held.status, TaskStatus::Blocked);
6250
6251 held.hold_manual(None);
6252 assert_eq!(held.status, TaskStatus::Held);
6253 assert!(
6254 held.blocked_by.is_empty(),
6255 "hold overrides the wait, same as release"
6256 );
6257 assert!(held.block_reason.is_none());
6258
6259 let mut done = task("closed straight out of blocked");
6260 done.block(
6261 vec!["20260101-000000-dead".to_owned()],
6262 Some("waiting on the migration script".to_owned()),
6263 );
6264 done.succeed(completion(&done));
6265 assert_eq!(done.status, TaskStatus::Done);
6266 assert!(
6267 done.blocked_by.is_empty(),
6268 "a done task cannot still be waiting on a dependency"
6269 );
6270 assert!(done.block_reason.is_none());
6271 }
6272
6273 #[test]
6274 fn a_blocked_task_is_never_offered_to_the_loop() {
6275 let mut t = task("blocked");
6276 assert!(t.status.runnable());
6277 t.block(
6278 vec!["dep-id".to_owned()],
6279 Some("waits on dep-id".to_owned()),
6280 );
6281 assert_eq!(t.status, TaskStatus::Blocked);
6282 assert!(!t.status.runnable());
6283 assert_eq!(TaskStatus::Blocked.as_str(), "blocked");
6284 }
6285
6286 #[test]
6287 fn unblocking_the_last_dependency_returns_the_task_to_queued() {
6288 let mut t = task("blocked on two");
6289 t.block(
6290 vec!["a".to_owned(), "b".to_owned()],
6291 Some("waits on a and b".to_owned()),
6292 );
6293
6294 t.unblock("a");
6295 assert_eq!(t.status, TaskStatus::Blocked, "b is still outstanding");
6296 assert_eq!(t.blocked_by, ["b"]);
6297
6298 t.unblock("b");
6299 assert_eq!(t.status, TaskStatus::Queued);
6300 assert!(t.blocked_by.is_empty());
6301 assert!(t.block_reason.is_none());
6302 }
6303
6304 #[test]
6305 fn unblocking_an_id_on_a_task_that_is_not_blocked_is_a_no_op() {
6306 let mut t = task("never blocked");
6307 t.unblock("whatever");
6308 assert_eq!(t.status, TaskStatus::Queued);
6309 }
6310
6311 #[test]
6312 fn a_held_task_blocked_on_a_question_returns_to_held_not_queued() {
6313 let mut t = task("held, then asked about");
6318 t.hold_machine(Some("out of attempts".to_owned()));
6319 assert_eq!(t.status, TaskStatus::Held);
6320
6321 t.block(vec!["q1".to_owned()], Some("what now?".to_owned()));
6322 assert_eq!(t.status, TaskStatus::Blocked);
6323
6324 t.record_answer("what now?".to_owned(), "leave it held".to_owned());
6325 t.unblock("q1");
6326 assert_eq!(t.status, TaskStatus::Held, "must restore, not requeue");
6327 assert_eq!(t.hold_reason.as_deref(), Some("out of attempts"));
6328 assert_eq!(t.hold_source, Some(HoldSource::Machine));
6329 assert!(t.blocked_from.is_none(), "consumed once restored");
6330 }
6331
6332 #[test]
6333 fn a_manually_held_task_blocked_on_a_question_returns_to_held() {
6334 let mut t = task("manually held, then asked about");
6335 t.hold_manual(Some("waiting on a dependency".to_owned()));
6336
6337 t.block(vec!["q1".to_owned()], None);
6338 t.unblock("q1");
6339
6340 assert_eq!(t.status, TaskStatus::Held);
6341 assert_eq!(t.hold_source, Some(HoldSource::Manual));
6342 }
6343
6344 #[test]
6345 fn re_blocking_an_already_blocked_task_keeps_the_original_blocked_from() {
6346 let mut t = task("held, blocked twice");
6350 t.hold_machine(None);
6351 t.block(vec!["q1".to_owned()], Some("first".to_owned()));
6352 t.block(
6353 vec!["q1".to_owned(), "q2".to_owned()],
6354 Some("second".to_owned()),
6355 );
6356
6357 t.unblock("q1");
6358 assert_eq!(t.status, TaskStatus::Blocked, "q2 still outstanding");
6359 t.unblock("q2");
6360 assert_eq!(t.status, TaskStatus::Held);
6361 }
6362
6363 #[test]
6364 fn unblocking_a_task_blocked_while_running_lands_on_queued_not_running() {
6365 let mut t = task("blocked mid-run");
6369 t.start("run-1".to_owned());
6370 assert_eq!(t.status, TaskStatus::Running);
6371
6372 t.block(vec!["q1".to_owned()], None);
6373 t.unblock("q1");
6374 assert_eq!(t.status, TaskStatus::Queued);
6375 }
6376
6377 #[test]
6378 fn a_pre_schema_4_blocked_record_with_hold_evidence_restores_to_held() {
6379 let mut t = task("legacy record, held before it was blocked");
6385 t.hold_source = Some(HoldSource::Machine);
6386 t.hold_reason = Some("legacy hold reason".to_owned());
6387 t.status = TaskStatus::Blocked;
6388 t.blocked_by = vec!["q1".to_owned()];
6389 t.blocked_from = None;
6390
6391 t.unblock("q1");
6392 assert_eq!(t.status, TaskStatus::Held);
6393 }
6394
6395 #[test]
6396 fn a_pre_schema_4_blocked_record_with_no_hold_evidence_restores_to_queued() {
6397 let mut t = task("legacy record, ordinary dependency block");
6398 t.status = TaskStatus::Blocked;
6399 t.blocked_by = vec!["dep".to_owned()];
6400 t.blocked_from = None;
6401
6402 t.unblock("dep");
6403 assert_eq!(t.status, TaskStatus::Queued);
6404 }
6405
6406 #[test]
6407 fn answering_a_question_is_recorded_and_survives_a_release() {
6408 let mut t = task("asked something");
6409 t.block(vec!["q1".to_owned()], Some("which backend?".to_owned()));
6410 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
6411 t.unblock("q1");
6412 assert_eq!(t.status, TaskStatus::Queued);
6413 assert_eq!(t.answers.len(), 1);
6414 assert_eq!(t.answers[0].answer, "SQLite");
6415
6416 t.release();
6420 assert_eq!(t.answers.len(), 1, "the answer is not lost on release");
6421 }
6422
6423 #[test]
6424 fn resumption_review_branch_requires_unchanged_authored_criteria() {
6425 for source in ["cli", "web"] {
6426 let mut t = task("review old candidate");
6427 t.request_review("candidate-A".into());
6428 t.hold_for_handover(Some("candidate-A".into()), "handover refused".into());
6429 let mut unchanged = t.clone();
6430 unchanged.release_operator(source, None);
6431 assert_eq!(unchanged.review_branch.as_deref(), Some("candidate-A"));
6432 t.edit(
6433 "review approved head".into(),
6434 "Reuse measured PR head B; fix Clippy; review".into(),
6435 )
6436 .unwrap();
6437 t.release_operator(source, None);
6438 assert!(t.review_branch.is_none());
6439 assert!(t.review_instruction.is_none());
6440 let mut legacy = unchanged;
6442 legacy.review_instruction = None;
6443 legacy.hold_for_handover(None, "still checked out".into());
6444 legacy
6445 .edit("new plan".into(), "Reuse measured PR head B".into())
6446 .unwrap();
6447 legacy.release_operator(source, None);
6448 assert!(legacy.review_branch.is_none());
6449 }
6450 }
6451
6452 #[test]
6453 fn a_refused_handover_keeps_the_review_branch_across_release() {
6454 let mut t = task("refused takeover");
6455 t.start("run-1".to_owned());
6456 t.hold_for_handover(Some("magi/eba2/A".to_owned()), "checked out".to_owned());
6457 assert_eq!(t.status, TaskStatus::Held);
6458 assert_eq!(t.attempts, 1);
6459 t.release();
6460 assert_eq!(t.status, TaskStatus::Queued);
6461 assert_eq!(t.attempts, 0);
6462 assert_eq!(t.review_branch.as_deref(), Some("magi/eba2/A"));
6463
6464 t.hold_for_handover(None, "again".to_owned());
6466 t.requeue();
6467 assert!(t.review_branch.is_none());
6468
6469 let mut m = task("manual");
6471 m.review_branch = Some("magi/x/A".to_owned());
6472 m.hold_manual(None);
6473 m.release();
6474 assert!(m.review_branch.is_none());
6475 }
6476
6477 #[test]
6478 fn requesting_review_requeues_the_task_and_remembers_the_branch() {
6479 let mut t = task("blocked run with a surviving branch");
6480 t.start("run-1".to_owned());
6481 t.fail("blocked with major findings", 5);
6482 assert_eq!(t.status, TaskStatus::Failed);
6483
6484 t.request_review("magi/eba2/A".to_owned());
6485 assert_eq!(t.status, TaskStatus::Queued);
6486 assert_eq!(t.attempts, 0);
6487 assert_eq!(t.review_branch.as_deref(), Some("magi/eba2/A"));
6488
6489 t.release();
6491 assert!(t.review_branch.is_none());
6492 }
6493
6494 #[test]
6495 fn conductor_requeue_but_not_an_ordinary_release_forces_a_fresh_start() {
6496 let mut t = task("retry");
6497 t.start("run-1".to_owned());
6498 t.requeue();
6499 assert!(t.fresh_start);
6500
6501 t.release();
6502 assert!(!t.fresh_start);
6503 }
6504
6505 #[test]
6506 fn urgent_only_changes_queued_or_held_and_preserves_settings() {
6507 for status in [
6508 TaskStatus::Queued,
6509 TaskStatus::Held,
6510 TaskStatus::Running,
6511 TaskStatus::Done,
6512 TaskStatus::Failed,
6513 TaskStatus::Blocked,
6514 TaskStatus::Parked,
6515 ] {
6516 let mut t = task("urgent settings");
6517 t.status = status;
6518 t.attempts = 2;
6519 t.hold_reason = Some("waiting".into());
6520 t.priority = 7;
6521 t.interrupt = true;
6522 let before = serde_json::to_value(&t).unwrap();
6523 for urgent in [true, true, false, false] {
6524 let result = t.set_urgent(urgent);
6525 let mut expected = before.clone();
6526 if matches!(status, TaskStatus::Queued | TaskStatus::Held) {
6527 result.unwrap();
6528 expected["urgent"] = urgent.into();
6529 } else {
6530 let error = result.unwrap_err().to_string();
6531 assert!(error.contains(status.as_str()), "{error}");
6532 assert!(error.contains("queued or held"), "{error}");
6533 }
6534 assert_eq!(serde_json::to_value(&t).unwrap(), expected);
6535 }
6536 }
6537 }
6538
6539 #[test]
6540 fn immediate_only_changes_queued_or_held_and_preserves_settings() {
6541 for status in [
6542 TaskStatus::Queued,
6543 TaskStatus::Held,
6544 TaskStatus::Running,
6545 TaskStatus::Done,
6546 TaskStatus::Failed,
6547 TaskStatus::Blocked,
6548 TaskStatus::Parked,
6549 ] {
6550 let mut t = task("immediate settings");
6551 t.status = status;
6552 t.attempts = 2;
6553 t.hold_reason = Some("waiting".into());
6554 t.priority = 7;
6555 t.interrupt = true;
6556 t.urgent = true;
6557 let before = serde_json::to_value(&t).unwrap();
6558 for immediate in [true, true, false, false] {
6559 let result = t.set_immediate(immediate);
6560 let mut expected = before.clone();
6561 if matches!(status, TaskStatus::Queued | TaskStatus::Held) {
6562 result.unwrap();
6563 expected["immediate"] = immediate.into();
6564 } else {
6565 let error = result.unwrap_err().to_string();
6566 assert!(error.contains(status.as_str()), "{error}");
6567 assert!(error.contains("queued or held"), "{error}");
6568 }
6569 assert_eq!(serde_json::to_value(&t).unwrap(), expected);
6570 assert!(t.urgent, "changing immediate must preserve saved urgent");
6571 }
6572 }
6573 }
6574
6575 #[test]
6576 fn a_task_recorded_without_an_immediate_field_still_reads_as_not_immediate() {
6577 let (_dir, q) = queue();
6578 let path = q.path_of("20260101-000000-imm0");
6579 std::fs::create_dir_all(q.root()).unwrap();
6580 std::fs::write(
6581 &path,
6582 serde_json::json!({
6583 "schema": SCHEMA,
6584 "id": "20260101-000000-imm0",
6585 "title": "from before immediate existed",
6586 "instruction": "from before immediate existed",
6587 "repo": ".",
6588 "source": { "kind": "human" },
6589 "status": "queued",
6590 "urgent": true,
6591 "created_at": Timestamp::now().to_string(),
6592 "updated_at": Timestamp::now().to_string(),
6593 })
6594 .to_string(),
6595 )
6596 .unwrap();
6597
6598 let task = q.get("20260101-000000-imm0").expect("must still read");
6599 assert!(!task.immediate);
6600 assert!(task.urgent);
6601 }
6602
6603 #[test]
6604 fn immediate_reuses_urgent_isolation_and_explicit_cache_wins() {
6605 let mut cfg = crate::config::Config::default();
6606 cfg.verify.e2e = vec!["CARGO_TARGET_DIR=/tmp/shared-target cargo test".into()];
6607 let mut t = task("immediate cache");
6608
6609 t.set_immediate(true).unwrap();
6610 assert_eq!(
6611 t.build_cache_override(&cfg),
6612 Some((BuildCache::Isolated, "immediate"))
6613 );
6614
6615 t.set_urgent(true).unwrap();
6617 assert_eq!(
6618 t.build_cache_override(&cfg),
6619 Some((BuildCache::Isolated, "immediate"))
6620 );
6621
6622 t.change_build_cache(Some(BuildCache::Shared)).unwrap();
6624 assert_eq!(
6625 t.build_cache_override(&cfg),
6626 Some((BuildCache::Shared, "task-override"))
6627 );
6628
6629 t.change_build_cache(None).unwrap();
6631 assert_eq!(
6632 t.build_cache_override(&cfg),
6633 Some((BuildCache::Isolated, "immediate"))
6634 );
6635 t.set_immediate(false).unwrap();
6636 assert_eq!(
6637 t.build_cache_override(&cfg),
6638 Some((BuildCache::Isolated, "urgent"))
6639 );
6640
6641 t.set_immediate(true).unwrap();
6643 cfg.verify.e2e = vec!["CARGO_TARGET_DIR=/tmp/shared-target cargo test | tee log".into()];
6644 assert_eq!(t.build_cache_override(&cfg), None);
6645 }
6646
6647 #[test]
6648 fn priority_can_be_changed_while_queued_but_not_while_running() {
6649 let mut t = task("reprioritise me");
6650 t.set_priority(5).unwrap();
6651 assert_eq!(t.priority, 5);
6652
6653 t.start("run-1".to_owned());
6654 let err = t.set_priority(9).unwrap_err().to_string();
6655 assert!(err.contains("running"), "{err}");
6656 assert_eq!(t.priority, 5, "the rejected write must not partially apply");
6657 }
6658
6659 #[test]
6660 fn interrupt_can_be_marked_while_queued_but_not_while_running() {
6661 let mut t = task("interrupt me");
6662 assert!(!t.interrupt, "off unless asked, same as any other task");
6663
6664 t.set_interrupt(true).unwrap();
6665 assert!(t.interrupt);
6666
6667 t.start("run-1".to_owned());
6668 assert!(
6669 !t.interrupt,
6670 "the mark is one-shot: dispatching the task fulfils it, \
6671 whatever the run that follows ends up doing"
6672 );
6673 let err = t.set_interrupt(true).unwrap_err().to_string();
6674 assert!(err.contains("running"), "{err}");
6675 t.set_interrupt(false).unwrap();
6678 assert!(!t.interrupt);
6679 }
6680
6681 #[test]
6685 fn a_failed_run_does_not_leave_the_task_still_marked_to_interrupt() {
6686 let mut t = task("interrupt me");
6687 t.set_interrupt(true).unwrap();
6688 t.start("run-1".to_owned());
6689 t.fail("mock failure", 5);
6690 assert_eq!(t.status, TaskStatus::Failed);
6691 assert!(
6692 !t.interrupt,
6693 "one attempt already spent the mark; a retry is an ordinary \
6694 requeue, not a fresh interrupt request"
6695 );
6696 }
6697
6698 #[test]
6699 fn changing_priority_moves_a_task_ahead_in_the_real_queue_order() {
6700 let (_dir, q) = queue();
6701 let mut a = task("first filed");
6702 let mut b = task("second filed");
6703 a.id = "20260101-000001-aaaa".to_owned();
6704 b.id = "20260101-000002-bbbb".to_owned();
6705 q.put(&mut a).unwrap();
6706 q.put(&mut b).unwrap();
6707
6708 assert_eq!(
6709 q.next_runnable().unwrap().id,
6710 a.id,
6711 "with equal priority the older task goes first, so a burst of \
6712 new work cannot starve it"
6713 );
6714 assert_eq!(
6715 q.list()[0].id,
6716 b.id,
6717 "but the list an operator reads is newest first, the same as \
6718 before priority existed - a's turn to run does not make it the \
6719 newest task"
6720 );
6721
6722 let mut a = q.get(&a.id).unwrap();
6723 a.set_priority(10).unwrap();
6724 q.put(&mut a).unwrap();
6725
6726 assert_eq!(
6727 q.next_runnable().unwrap().id,
6728 a.id,
6729 "a raised priority must be reflected the moment it is saved"
6730 );
6731 assert_eq!(
6735 q.list()[0].id,
6736 a.id,
6737 "the raised task must sort first in the list an operator reads, \
6738 not only in next_runnable's own ordering"
6739 );
6740 }
6741
6742 #[test]
6743 fn editing_replaces_title_and_instruction_but_keeps_identity_and_history() {
6744 let mut t = Task::new(
6745 "old title".to_owned(),
6746 "old instruction".to_owned(),
6747 PathBuf::from("/repo"),
6748 Source::Agent {
6749 run: "20260101-000000-beef".to_owned(),
6750 node: "implement".to_owned(),
6751 },
6752 );
6753 let id = t.id.clone();
6754 let created_at = t.created_at;
6755 t.runs.push("20260101-000000-beef".to_owned());
6756
6757 t.edit("new title".to_owned(), "new instruction".to_owned())
6758 .unwrap();
6759
6760 assert_eq!(t.title, "new title");
6761 assert_eq!(t.instruction, "new instruction");
6762 assert_eq!(t.id, id, "editing must not mint a new id");
6763 assert_eq!(t.created_at, created_at);
6764 assert_eq!(
6765 t.source,
6766 Source::Agent {
6767 run: "20260101-000000-beef".to_owned(),
6768 node: "implement".to_owned(),
6769 },
6770 "editing must not turn agent attribution into human"
6771 );
6772 assert_eq!(t.runs, ["20260101-000000-beef"]);
6773 }
6774
6775 #[test]
6776 fn editing_is_refused_once_a_task_is_running_or_finished() {
6777 let mut running = task("in flight");
6778 running.start("run-1".to_owned());
6779 let err = running
6780 .edit("x".to_owned(), "y".to_owned())
6781 .unwrap_err()
6782 .to_string();
6783 assert!(err.contains("running"), "{err}");
6784
6785 let mut done = task("finished");
6786 done.succeed(completion(&done));
6787 let err = done
6788 .edit("x".to_owned(), "y".to_owned())
6789 .unwrap_err()
6790 .to_string();
6791 assert!(err.contains("done"), "{err}");
6792
6793 let mut queued = task("waiting");
6795 queued.edit("x".to_owned(), "y".to_owned()).unwrap();
6796 let mut held = task("parked");
6797 held.hold_machine(None);
6798 held.edit("x".to_owned(), "y".to_owned()).unwrap();
6799 }
6800
6801 #[test]
6802 fn a_task_recorded_without_a_hold_reason_still_reads_as_none() {
6803 let (_dir, q) = queue();
6804 let path = q.path_of("20260101-000000-aaaa");
6805 std::fs::create_dir_all(q.root()).unwrap();
6806 std::fs::write(
6807 &path,
6808 serde_json::json!({
6809 "schema": SCHEMA,
6810 "id": "20260101-000000-aaaa",
6811 "title": "from before hold reasons existed",
6812 "instruction": "from before hold reasons existed",
6813 "repo": ".",
6814 "source": { "kind": "human" },
6815 "status": "held",
6816 "created_at": Timestamp::now().to_string(),
6817 "updated_at": Timestamp::now().to_string(),
6818 })
6819 .to_string(),
6820 )
6821 .unwrap();
6822
6823 let task = q.get("20260101-000000-aaaa").expect("must still read");
6824 assert!(task.hold_reason.is_none());
6825 assert!(task.operator_held());
6826 }
6827
6828 #[test]
6829 fn a_legacy_reasoned_hold_defaults_to_operator_protection() {
6830 let (_dir, q) = queue();
6831 let path = q.path_of("20260101-000000-bbbb");
6832 std::fs::create_dir_all(q.root()).unwrap();
6833 std::fs::write(
6834 &path,
6835 serde_json::json!({
6836 "schema": 2,
6837 "id": "20260101-000000-bbbb",
6838 "title": "old manual recovery",
6839 "instruction": "old manual recovery",
6840 "repo": ".",
6841 "source": { "kind": "human" },
6842 "status": "held",
6843 "hold_reason": "active manual recovery run20260912-224242-daf5",
6844 "created_at": Timestamp::now().to_string(),
6845 "updated_at": Timestamp::now().to_string(),
6846 })
6847 .to_string(),
6848 )
6849 .unwrap();
6850
6851 let task = q.get("20260101-000000-bbbb").expect("must still read");
6852 assert_eq!(task.hold_source, None);
6853 assert!(task.operator_held());
6854 }
6855
6856 #[test]
6857 fn a_task_recorded_without_a_diagnostic_still_reads_as_none() {
6858 let (_dir, q) = queue();
6859 let path = q.path_of("20260101-000000-aaaa");
6860 std::fs::create_dir_all(q.root()).unwrap();
6861 std::fs::write(
6862 &path,
6863 serde_json::json!({
6864 "schema": SCHEMA,
6865 "id": "20260101-000000-aaaa",
6866 "title": "from before diagnostics existed",
6867 "instruction": "from before diagnostics existed",
6868 "repo": ".",
6869 "source": { "kind": "human" },
6870 "status": "held",
6871 "created_at": Timestamp::now().to_string(),
6872 "updated_at": Timestamp::now().to_string(),
6873 })
6874 .to_string(),
6875 )
6876 .unwrap();
6877
6878 let task = q.get("20260101-000000-aaaa").expect("must still read");
6879 assert!(task.diagnostic.is_none());
6880 }
6881
6882 #[test]
6883 fn a_schema_1_task_with_no_blocking_fields_still_reads() {
6884 let (_dir, q) = queue();
6888 let path = q.path_of("20260101-000000-aaaa");
6889 std::fs::create_dir_all(q.root()).unwrap();
6890 std::fs::write(
6891 &path,
6892 serde_json::json!({
6893 "schema": 1,
6894 "id": "20260101-000000-aaaa",
6895 "title": "from before blocking existed",
6896 "instruction": "from before blocking existed",
6897 "repo": ".",
6898 "source": { "kind": "human" },
6899 "status": "queued",
6900 "created_at": Timestamp::now().to_string(),
6901 "updated_at": Timestamp::now().to_string(),
6902 })
6903 .to_string(),
6904 )
6905 .unwrap();
6906
6907 let task = q.get("20260101-000000-aaaa").expect("must still read");
6908 assert!(task.blocked_by.is_empty());
6909 assert!(task.block_reason.is_none());
6910 assert!(task.answers.is_empty());
6911 assert!(task.review_branch.is_none());
6912 }
6913
6914 #[test]
6915 fn releasing_or_finishing_a_task_clears_its_stale_diagnostic() {
6916 let mut held = task("diagnosed");
6921 held.start("run-1".to_owned());
6922 held.fail("gate red", 1);
6923 held.diagnostic = Some("cargo test failed: ...".to_owned());
6924 assert_eq!(held.status, TaskStatus::Held);
6925
6926 held.release();
6927 assert!(held.diagnostic.is_none());
6928
6929 held.diagnostic = Some("cargo test failed: ...".to_owned());
6930 held.succeed(completion(&held));
6931 assert!(held.diagnostic.is_none());
6932 }
6933
6934 #[test]
6935 fn failing_a_task_always_clears_whatever_diagnostic_it_carried() {
6936 let mut t = task("retried");
6937 t.start("run-1".to_owned());
6938 t.diagnostic = Some("stale evidence from a previous hold".to_owned());
6939 t.fail("unrelated config error", 5);
6940 assert_eq!(t.status, TaskStatus::Failed);
6941 assert!(
6942 t.diagnostic.is_none(),
6943 "fail() must not let an old diagnostic outlive the run that produced it"
6944 );
6945 }
6946
6947 #[test]
6948 fn a_claim_is_exclusive_and_releases_on_drop() {
6949 let (_dir, q) = queue();
6950 let mut t = task("contended");
6951 q.put(&mut t).unwrap();
6952
6953 let held = q.claim(&t.id).unwrap();
6954 assert!(
6955 q.claim(&t.id).is_err(),
6956 "two daemons must not drive one task into two runs"
6957 );
6958 drop(held);
6959 assert!(q.claim(&t.id).is_ok(), "a released claim is reclaimable");
6960 }
6961
6962 #[test]
6963 fn a_round_trip_survives_disk() {
6964 let (_dir, q) = queue();
6965 let mut t = Task::new(
6966 "titled".to_owned(),
6967 "body".to_owned(),
6968 PathBuf::from("/repo"),
6969 Source::Agent {
6970 run: "20260101-000000-beef".to_owned(),
6971 node: "implement".to_owned(),
6972 },
6973 );
6974 t.priority = 3;
6975 q.put(&mut t).unwrap();
6976
6977 let back = q.get(&t.id).unwrap();
6978 assert_eq!(back.id, t.id);
6979 assert_eq!(back.priority, 3);
6980 assert_eq!(back.source.label(), "implement@beef");
6981 assert_eq!(q.get(t.short()).unwrap().id, t.id);
6983 }
6984
6985 #[test]
6986 fn an_unreadable_task_does_not_take_the_queue_down() {
6987 let (_dir, q) = queue();
6988 let mut t = task("fine");
6989 q.put(&mut t).unwrap();
6990 std::fs::write(q.root().join("broken.json"), "{ not json").unwrap();
6991
6992 let listed = q.list();
6993 assert_eq!(listed.len(), 1, "the readable task still lists");
6994 assert_eq!(listed[0].id, t.id);
6995 }
6996
6997 #[test]
6998 fn a_task_recorded_without_a_solo_field_still_reads_as_not_solo() {
6999 let (_dir, q) = queue();
7000 let path = q.path_of("20260101-000000-aaaa");
7001 std::fs::create_dir_all(q.root()).unwrap();
7002 std::fs::write(
7003 &path,
7004 serde_json::json!({
7005 "schema": SCHEMA,
7006 "id": "20260101-000000-aaaa",
7007 "title": "from before solo existed",
7008 "instruction": "from before solo existed",
7009 "repo": ".",
7010 "source": { "kind": "human" },
7011 "status": "queued",
7012 "created_at": Timestamp::now().to_string(),
7013 "updated_at": Timestamp::now().to_string(),
7014 })
7015 .to_string(),
7016 )
7017 .unwrap();
7018
7019 let task = q.get("20260101-000000-aaaa").expect("must still read");
7020 assert!(!task.solo, "a queue file with no `solo` field means false");
7021 }
7022
7023 #[test]
7024 fn a_task_recorded_without_an_urgent_field_still_reads_as_not_urgent() {
7025 let (_dir, q) = queue();
7026 let path = q.path_of("20260101-000000-bbbb");
7027 std::fs::create_dir_all(q.root()).unwrap();
7028 std::fs::write(
7029 &path,
7030 serde_json::json!({
7031 "schema": SCHEMA,
7032 "id": "20260101-000000-bbbb",
7033 "title": "from before urgent existed",
7034 "instruction": "from before urgent existed",
7035 "repo": ".",
7036 "source": { "kind": "human" },
7037 "status": "queued",
7038 "created_at": Timestamp::now().to_string(),
7039 "updated_at": Timestamp::now().to_string(),
7040 })
7041 .to_string(),
7042 )
7043 .unwrap();
7044
7045 let task = q.get("20260101-000000-bbbb").expect("must still read");
7046 assert!(
7047 !task.urgent,
7048 "a queue file with no `urgent` field means false, same as `solo`"
7049 );
7050 }
7051
7052 #[test]
7053 fn a_task_from_a_future_schema_is_refused_rather_than_guessed_at() {
7054 let (_dir, q) = queue();
7055 let mut t = task("from the future");
7056 q.put(&mut t).unwrap();
7057 let path = q.path_of(&t.id);
7058 let body = std::fs::read_to_string(&path)
7059 .unwrap()
7060 .replace(&format!("\"schema\": {SCHEMA}"), "\"schema\": 99");
7061 std::fs::write(&path, body).unwrap();
7062
7063 let err = q.get(&t.id).unwrap_err().to_string();
7064 assert!(err.contains("schema 99"), "{err}");
7065 }
7066
7067 #[test]
7068 fn revision_moves_when_the_queue_changes() {
7069 let (_dir, q) = queue();
7070 assert_eq!(q.revision(), 0, "an empty queue has no revision");
7071 let mut t = task("first");
7072 q.put(&mut t).unwrap();
7073 assert!(q.revision() > 0, "a written task moves the revision");
7074 }
7075
7076 #[test]
7077 fn revision_moves_when_deleting_an_older_task() {
7078 let (dir, q) = queue();
7079 let questions = Questions::at(dir.path().join("questions"));
7080 let mut t1 = task("older");
7081 q.put(&mut t1).unwrap();
7082 std::thread::sleep(std::time::Duration::from_millis(10));
7084 let mut t2 = task("newer");
7085 q.put(&mut t2).unwrap();
7086
7087 let rev_before = q.revision();
7088 q.remove(&t1.id, false, &questions).unwrap();
7089 let rev_after = q.revision();
7090
7091 assert_ne!(
7092 rev_before, rev_after,
7093 "deleting an older task must change the revision so other clients see the deletion"
7094 );
7095 }
7096
7097 #[test]
7098 fn removing_a_task_takes_it_out_of_the_listing() {
7099 let (dir, q) = queue();
7100 let questions = Questions::at(dir.path().join("questions"));
7101 let mut t = task("delete me");
7102 q.put(&mut t).unwrap();
7103 let removed = q.remove(t.short(), false, &questions).unwrap();
7104 assert_eq!(removed.id, t.id, "a prefix resolves before deleting");
7105 assert!(removed.released.is_empty() && removed.still_blocked.is_empty());
7106 assert!(q.list().is_empty());
7107 assert!(
7108 q.remove(&t.id, false, &questions).is_err(),
7109 "removing twice is an error"
7110 );
7111 }
7112
7113 #[test]
7114 fn removing_a_task_takes_its_stale_lock_with_it() {
7115 let (dir, q) = queue();
7116 let questions = Questions::at(dir.path().join("questions"));
7117 let mut t = task("interrupted");
7118 q.put(&mut t).unwrap();
7119
7120 let claim = q.claim(&t.id).unwrap();
7123 std::mem::forget(claim);
7124 assert!(
7125 q.claim(&t.id).is_err(),
7126 "the orphaned lock is what makes the task look claimed"
7127 );
7128
7129 let err = q.remove(&t.id, true, &questions).unwrap_err().to_string();
7131 assert!(err.contains("live daemon"), "{err}");
7132 assert!(q.get(&t.id).is_ok(), "a refused delete keeps the task");
7133
7134 q.remove(&t.id, false, &questions).unwrap();
7136 assert!(q.list().is_empty());
7137 let mut again = task("interrupted");
7138 again.id = t.id.clone();
7139 q.put(&mut again).unwrap();
7140 assert!(
7141 q.claim(&t.id).is_ok(),
7142 "a task that comes back must be claimable, which a left-behind lock would prevent"
7143 );
7144 }
7145
7146 fn notices_of(dir: &Path) -> Vec<crate::notices::Notice> {
7147 crate::notices::Notices::at(dir.join("notifications")).list()
7148 }
7149
7150 #[test]
7151 fn removing_a_sole_dependency_releases_the_dependent_without_a_hold() {
7152 let (dir, q) = queue();
7153 let questions = Questions::at(dir.path().join("questions"));
7154 let mut dep = task("dependency");
7155 q.put(&mut dep).unwrap();
7156 let mut blocked = task("waiting");
7157 blocked.block(vec![dep.id.clone()], Some("waits".to_owned()));
7158 q.put(&mut blocked).unwrap();
7159
7160 let removed = q.remove(&dep.id, false, &questions).unwrap();
7161 assert_eq!(removed.released, [blocked.id.clone()]);
7162 assert!(removed.still_blocked.is_empty());
7163
7164 let after = q.get(&blocked.id).unwrap();
7165 assert_eq!(after.status, TaskStatus::Queued);
7166 assert!(after.blocked_by.is_empty());
7167 assert!(after.block_reason.is_none());
7168 let notes = notices_of(dir.path());
7169 assert_eq!(notes.len(), 1, "{notes:?}");
7170 assert_eq!(notes[0].severity, crate::notices::Severity::Info);
7171 assert_eq!(
7172 notes[0].link,
7173 Some(crate::notices::Link::Task {
7174 id: blocked.id.clone(),
7175 })
7176 );
7177 }
7178
7179 #[test]
7180 fn removing_one_of_two_dependencies_keeps_the_other() {
7181 let (dir, q) = queue();
7182 let questions = Questions::at(dir.path().join("questions"));
7183 let mut dep = task("dependency");
7184 q.put(&mut dep).unwrap();
7185 let mut other = task("other");
7186 q.put(&mut other).unwrap();
7187 let mut blocked = task("waiting");
7188 blocked.block(
7189 vec![dep.id.clone(), other.id.clone()],
7190 Some("waits on both".to_owned()),
7191 );
7192 q.put(&mut blocked).unwrap();
7193
7194 let removed = q.remove(&dep.id, false, &questions).unwrap();
7195 assert!(removed.released.is_empty());
7196 assert_eq!(removed.still_blocked, [blocked.id.clone()]);
7197
7198 let after = q.get(&blocked.id).unwrap();
7199 assert_eq!(after.status, TaskStatus::Blocked);
7200 assert_eq!(after.blocked_by, [other.id.clone()]);
7201 assert!(missing_blockers(&q, &questions, &after.blocked_by).is_empty());
7204 }
7205
7206 #[test]
7207 fn a_dependency_deleted_before_its_dependents_were_rewritten_is_released_later() {
7208 let (dir, q) = queue();
7209 let questions = Questions::at(dir.path().join("questions"));
7210 let mut dep = task("dependency");
7211 q.put(&mut dep).unwrap();
7212 let mut blocked = task("waiting");
7213 blocked.block(vec![dep.id.clone()], None);
7214 q.put(&mut blocked).unwrap();
7215
7216 let claim = q.claim(&blocked.id).unwrap();
7218 let removed = q.remove(&dep.id, false, &questions).unwrap();
7219 assert!(removed.released.is_empty());
7220 drop(claim);
7221
7222 let mut task = q.get(&blocked.id).unwrap();
7223 assert_eq!(task.status, TaskStatus::Blocked);
7224 assert!(missing_blockers(&q, &questions, &task.blocked_by).is_empty());
7225 assert_eq!(
7226 q.apply_deleted_blockers(&mut task, &questions),
7227 [dep.id.clone()]
7228 );
7229 assert_eq!(task.status, TaskStatus::Queued);
7230 }
7231
7232 #[test]
7233 fn dependency_resolution_short_deleted_reference_releases_only_its_waiters() {
7234 let (dir, q) = queue();
7235 let questions = Questions::at(dir.path().join("questions"));
7236 let mut dep = task("dependency");
7237 dep.id = "20261013-193611-ca5b".into();
7238 q.put(&mut dep).unwrap();
7239 let mut waiting = task("waiting");
7240 waiting.block(vec!["ca5b".into()], None);
7241 q.put(&mut waiting).unwrap();
7242 q.remove(&dep.id, false, &questions).unwrap();
7243 assert_eq!(q.get(&waiting.id).unwrap().status, TaskStatus::Queued);
7244 assert_eq!(
7245 dependency(&q, &questions, "ca5b"),
7246 Dependency::Deleted(dep.id)
7247 );
7248 }
7249
7250 #[test]
7251 fn dependency_resolution_preserves_cross_store_ambiguity_and_exact_ids() {
7252 let (dir, queue) = queue();
7253 let questions = Questions::at(dir.path().join("questions"));
7254 let mut dep = task("dependency");
7255 dep.id = "20261013-193611-ca5b".into();
7256 queue.put(&mut dep).unwrap();
7257 std::fs::create_dir_all(questions.root()).unwrap();
7258 let question_id = "20261014-193611-ca5b";
7259 std::fs::write(questions.path_of(question_id), "unreadable question").unwrap();
7260 assert_eq!(questions.resolve_id("ca5b").unwrap(), question_id);
7261 assert_eq!(
7262 dependency(&queue, &questions, "ca5b"),
7263 Dependency::Ambiguous
7264 );
7265 assert_eq!(
7266 dependency(&queue, &questions, &dep.id),
7267 Dependency::Task(dep.id)
7268 );
7269 assert_eq!(
7270 dependency(&queue, &questions, question_id),
7271 Dependency::Question(question_id.into())
7272 );
7273 assert_eq!(
7274 dependency(&queue, &questions, "missing"),
7275 Dependency::Missing
7276 );
7277 }
7278
7279 #[test]
7280 fn dependency_resolution_directory_errors_are_unknown_not_missing() {
7281 let dir = tempfile::tempdir().unwrap();
7282 let q = Queue::at(dir.path().join("not-a-directory"));
7283 std::fs::write(q.root(), "file").unwrap();
7284 let questions = Questions::at(dir.path().join("questions"));
7285 assert_eq!(dependency(&q, &questions, "ca5b"), Dependency::Unknown);
7286 assert!(missing_blockers(&q, &questions, &["ca5b".into()]).is_empty());
7287 }
7288
7289 #[test]
7290 fn a_dependency_without_a_tombstone_is_still_missing() {
7291 let (dir, q) = queue();
7292 let questions = Questions::at(dir.path().join("questions"));
7293 let mut dep = task("dependency");
7294 q.put(&mut dep).unwrap();
7295 std::fs::remove_file(q.path_of(&dep.id)).unwrap();
7296 assert_eq!(
7297 missing_blockers(&q, &questions, std::slice::from_ref(&dep.id)),
7298 [dep.id.clone()]
7299 );
7300 assert!(deleted_blockers(&q, &questions, std::slice::from_ref(&dep.id)).is_empty());
7301 }
7302
7303 #[test]
7304 fn a_held_dependent_is_left_alone_by_a_dependency_deletion() {
7305 let mut t = task("held");
7306 t.hold_machine(Some("because".to_owned()));
7307 t.blocked_by = vec!["gone".to_owned()];
7308 assert!(!t.dependency_deleted("gone"));
7309 assert_eq!(t.status, TaskStatus::Held);
7310 }
7311
7312 #[test]
7313 fn a_failed_record_removal_takes_the_tombstone_back() {
7314 let (_dir, q) = queue();
7315 let mut t = task("stays");
7316 q.put(&mut t).unwrap();
7317 q.write_tombstone(&t.id).unwrap();
7318 let err = q.remove_record_with_attachments(&t.id, |_| Err(std::io::Error::other("nope")));
7319 assert!(err.is_err());
7320 assert!(!q.was_deleted(&t.id));
7323 }
7324
7325 fn source_file(dir: &Path, name: &str, body: &str) -> PathBuf {
7326 let p = dir.join(name);
7327 std::fs::write(&p, body).unwrap();
7328 p
7329 }
7330
7331 #[test]
7332 fn an_attachment_copy_survives_deleting_its_source() {
7333 let (dir, q) = queue();
7334 let src = source_file(dir.path(), "shot.png", "pixels");
7335 let mut t = task("with a picture");
7336 let names = q.attach(&mut t, std::slice::from_ref(&src)).unwrap();
7337 q.put(&mut t).unwrap();
7338 std::fs::remove_file(&src).unwrap();
7339 assert_eq!(names, ["shot.png"]);
7340 let loaded = q.get(&t.id).unwrap();
7341 let paths = q.attachment_paths(&loaded);
7342 assert_eq!(paths.len(), 1);
7343 assert_eq!(std::fs::read_to_string(&paths[0]).unwrap(), "pixels");
7344 }
7345
7346 #[test]
7347 fn attachment_names_that_could_traverse_or_are_odd_are_refused() {
7348 let (dir, q) = queue();
7349 let mut t = task("bad names");
7350 for name in ["a..b.png", ".hidden", "with space.png", "-x.png"] {
7351 let src = source_file(dir.path(), name, "x");
7352 assert!(
7353 q.attach(&mut t, &[src]).is_err(),
7354 "`{name}` must be refused"
7355 );
7356 }
7357 assert!(!crate::ask::valid_asset_name("C:foo.png"));
7361 #[cfg(not(windows))]
7362 {
7363 let src = source_file(dir.path(), "C:foo.png", "x");
7364 assert!(q.attach(&mut t, &[src]).is_err());
7365 }
7366 let long = format!("{}.png", "a".repeat(70));
7367 let src = source_file(dir.path(), &long, "x");
7368 assert!(q.attach(&mut t, &[src]).is_err());
7369 assert!(t.attachments.is_empty());
7370 assert!(!q.attachments_dir(&t.id).exists());
7371 }
7372
7373 #[test]
7374 fn a_taken_attachment_name_is_numbered_not_overwritten() {
7375 let (dir, q) = queue();
7376 let a = source_file(dir.path(), "shot.png", "one");
7377 let sub = dir.path().join("other");
7378 std::fs::create_dir_all(&sub).unwrap();
7379 let b = source_file(&sub, "shot.png", "two");
7380 let mut t = task("collision");
7381 q.attach(&mut t, &[a]).unwrap();
7382 q.attach(&mut t, &[b]).unwrap();
7383 assert_eq!(t.attachments, ["shot.png", "shot-2.png"]);
7384 let paths = q.attachment_paths(&t);
7385 assert_eq!(std::fs::read_to_string(&paths[0]).unwrap(), "one");
7386 assert_eq!(std::fs::read_to_string(&paths[1]).unwrap(), "two");
7387 }
7388
7389 #[test]
7390 fn a_renumbered_name_stays_inside_the_length_bound() {
7391 let (dir, q) = queue();
7392 let name = format!("{}.png", "a".repeat(60));
7393 assert_eq!(name.len(), 64);
7394 let a = source_file(dir.path(), &name, "one");
7395 let sub = dir.path().join("other");
7396 std::fs::create_dir_all(&sub).unwrap();
7397 let b = source_file(&sub, &name, "two");
7398 let mut t = task("long");
7399 q.attach(&mut t, &[a, b]).unwrap();
7400 assert_eq!(t.attachments.len(), 2);
7401 assert!(
7402 t.attachments
7403 .iter()
7404 .all(|n| crate::ask::valid_asset_name(n))
7405 );
7406 assert!(t.attachments[1].ends_with("-2.png"));
7407 }
7408
7409 #[test]
7410 fn a_failed_attach_keeps_existing_attachments_and_leaves_no_partial_copy() {
7411 let (dir, q) = queue();
7412 let good = source_file(dir.path(), "good.png", "ok");
7413 let mut t = task("partial");
7414 q.attach(&mut t, &[good]).unwrap();
7415 let more = source_file(dir.path(), "more.png", "ok");
7416 let missing = dir.path().join("missing.png");
7417 assert!(q.attach(&mut t, &[more, missing]).is_err());
7418 assert_eq!(t.attachments, ["good.png"]);
7419 let on_disk: Vec<_> = std::fs::read_dir(q.attachments_dir(&t.id))
7420 .unwrap()
7421 .flatten()
7422 .collect();
7423 assert_eq!(on_disk.len(), 1);
7424 }
7425
7426 fn block_put(q: &Queue, t: &Task) -> PathBuf {
7428 let tmp = q.path_of(&t.id).with_extension("json.tmp");
7429 std::fs::create_dir_all(&tmp).unwrap();
7430 tmp
7431 }
7432
7433 #[test]
7434 fn a_failed_put_leaves_no_new_attachment_directory() {
7435 let (dir, q) = queue();
7436 let mut t = task("fresh");
7437 let tmp = block_put(&q, &t);
7438 let src = source_file(dir.path(), "shot.png", "x");
7439 assert!(q.attach_and_put(&mut t, &[src]).is_err());
7440 assert!(t.attachments.is_empty());
7441 assert!(!q.attachments_dir(&t.id).exists());
7442 assert!(!q.path_of(&t.id).exists());
7443 std::fs::remove_dir(tmp).unwrap();
7444 }
7445
7446 #[test]
7447 fn a_failed_put_removes_only_the_copy_it_just_made() {
7448 let (dir, q) = queue();
7449 let mut t = task("edited");
7450 let first = source_file(dir.path(), "first.png", "1");
7451 q.attach_and_put(&mut t, &[first]).unwrap();
7452 block_put(&q, &t);
7453 let second = source_file(dir.path(), "second.png", "2");
7454 assert!(q.attach_and_put(&mut t, &[second]).is_err());
7455 assert_eq!(t.attachments, ["first.png"]);
7456 let on_disk: Vec<_> = std::fs::read_dir(q.attachments_dir(&t.id))
7457 .unwrap()
7458 .flatten()
7459 .map(|e| e.file_name().to_string_lossy().into_owned())
7460 .collect();
7461 assert_eq!(on_disk, ["first.png"]);
7462 assert_eq!(q.get(&t.id).unwrap().attachments, ["first.png"]);
7463 }
7464
7465 #[test]
7466 fn a_leftover_removing_directory_is_swept_by_the_next_removal() {
7467 let (dir, q) = queue();
7468 let questions = Questions::at(dir.path().join("questions"));
7469 let gone = task("gone");
7470 let mut other = task("other");
7471 let mut live = task("live");
7472 q.put(&mut other).unwrap();
7473 q.put(&mut live).unwrap();
7474 let orphan = q.root.join(format!("{}.attachments.removing", gone.id));
7477 std::fs::create_dir_all(&orphan).unwrap();
7478 std::fs::write(orphan.join("shot.png"), "x").unwrap();
7479 let busy = q.root.join(format!("{}.attachments.removing", live.id));
7482 std::fs::create_dir_all(&busy).unwrap();
7483
7484 q.remove(&other.id, false, &questions).unwrap();
7485 assert!(!orphan.exists(), "an orphan is swept");
7486 assert!(busy.exists(), "a removal in progress is left alone");
7487 }
7488
7489 #[test]
7490 fn a_blocked_aside_rename_fails_the_removal_and_loses_nothing() {
7491 let (dir, q) = queue();
7492 let questions = Questions::at(dir.path().join("questions"));
7493 let mut t = task("stuck");
7494 let src = source_file(dir.path(), "shot.png", "x");
7495 q.attach_and_put(&mut t, &[src]).unwrap();
7496 let aside = q.root.join(format!("{}.attachments.removing", t.id));
7499 std::fs::create_dir_all(&aside).unwrap();
7500 std::fs::write(aside.join("old.png"), "o").unwrap();
7501 assert!(q.remove(&t.id, false, &questions).is_err());
7502 assert!(q.path_of(&t.id).exists());
7503 assert!(q.attachments_dir(&t.id).join("shot.png").is_file());
7504 }
7505
7506 #[test]
7507 fn a_failed_record_removal_puts_the_attachments_back() {
7508 let (dir, q) = queue();
7509 let mut t = task("rollback");
7510 let src = source_file(dir.path(), "shot.png", "x");
7511 q.attach_and_put(&mut t, &[src]).unwrap();
7512 let err = q
7513 .remove_record_with_attachments(&t.id, |_| {
7514 Err(std::io::Error::other("injected failure"))
7515 })
7516 .unwrap_err();
7517 assert!(format!("{err:#}").contains("injected failure"));
7518 assert!(q.path_of(&t.id).exists());
7519 assert!(q.attachments_dir(&t.id).join("shot.png").is_file());
7520 assert!(
7521 !q.root
7522 .join(format!("{}.attachments.removing", t.id))
7523 .exists()
7524 );
7525 }
7526
7527 #[test]
7528 fn editing_a_task_keeps_its_attachments() {
7529 let (dir, q) = queue();
7530 let src = source_file(dir.path(), "shot.png", "x");
7531 let mut t = task("editable");
7532 q.attach(&mut t, &[src]).unwrap();
7533 t.edit("new".to_owned(), "new text".to_owned()).unwrap();
7534 q.put(&mut t).unwrap();
7535 assert_eq!(q.get(&t.id).unwrap().attachments, ["shot.png"]);
7536 }
7537
7538 #[test]
7539 fn removing_a_task_deletes_its_attachments() {
7540 let (dir, q) = queue();
7541 let questions = Questions::at(dir.path().join("questions"));
7542 let src = source_file(dir.path(), "shot.png", "x");
7543 let mut t = task("doomed");
7544 q.attach(&mut t, &[src]).unwrap();
7545 q.put(&mut t).unwrap();
7546 assert!(q.attachments_dir(&t.id).is_dir());
7547 q.remove(&t.id, false, &questions).unwrap();
7548 assert!(!q.attachments_dir(&t.id).exists());
7549 assert!(q.list().is_empty());
7550 }
7551
7552 #[test]
7553 fn a_task_written_before_attachments_still_reads() {
7554 let (_dir, q) = queue();
7555 let mut t = task("old");
7556 q.put(&mut t).unwrap();
7557 let path = q.path_of(&t.id);
7558 let mut v: serde_json::Value =
7559 serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
7560 v.as_object_mut().unwrap().remove("attachments");
7561 std::fs::write(&path, v.to_string()).unwrap();
7562 assert!(q.get(&t.id).unwrap().attachments.is_empty());
7563 }
7564
7565 #[test]
7566 fn attachment_paths_are_absolute_even_when_the_root_is_relative() {
7567 let q = Queue::at(PathBuf::from("relative-queue"));
7568 let mut t = task("rel");
7569 t.attachments.push("shot.png".to_owned());
7570 let paths = q.attachment_paths(&t);
7571 assert!(paths[0].is_absolute(), "{}", paths[0].display());
7572 assert!(paths[0].ends_with(format!("{}.attachments/shot.png", t.id)));
7573 }
7574
7575 fn upgrade_parked(id: &str, started: &str) -> Task {
7576 let mut t = task(id);
7577 t.id = id.into();
7578 t.start(format!("run-{id}"));
7579 t.park("upgrade");
7580 t.record_pass_at(
7581 &format!("run-{id}"),
7582 0,
7583 Some(started.parse().unwrap()),
7584 1,
7585 Some(crate::run::ParkCause::Upgrade {
7586 from: "old".into(),
7587 to: None,
7588 }),
7589 );
7590 t
7591 }
7592
7593 #[test]
7594 fn upgrade_resume_order_follows_dispatch_claim_not_graph_start() {
7595 let stamp = |id: &str, dispatched: &str, started: &str| {
7597 let mut t = task(id);
7598 t.id = id.into();
7599 t.start(format!("run-{id}"));
7600 t.park("upgrade");
7601 t.dispatched_at = Some(dispatched.parse().unwrap());
7602 t.record_pass_at(
7603 &format!("run-{id}"),
7604 0,
7605 Some(started.parse().unwrap()),
7606 1,
7607 Some(crate::run::ParkCause::Upgrade {
7608 from: "old".into(),
7609 to: None,
7610 }),
7611 );
7612 t
7613 };
7614 let a = stamp("a", "2026-10-22T00:00:01Z", "2026-10-22T00:00:09Z");
7615 let b = stamp("b", "2026-10-22T00:00:02Z", "2026-10-22T00:00:03Z");
7616 assert!(dispatch_order(&a, &b).is_lt());
7617 }
7618
7619 #[test]
7620 fn upgrade_resume_order_survives_queue_reload_and_reversed_settlement() {
7621 let (_dir, q) = queue();
7622 let mut later = upgrade_parked("later", "2026-10-22T00:00:02Z");
7623 let mut earlier = upgrade_parked("earlier", "2026-10-22T00:00:01Z");
7624 earlier.priority = -10;
7625 let mut fresh = task("fresh");
7626 fresh.id = "newer".into();
7627 fresh.priority = 100;
7628 for t in [&mut fresh, &mut later, &mut earlier] {
7629 q.put(t).unwrap();
7630 }
7631 let reloaded = Queue::at(q.root().to_owned());
7632 let mut tasks = reloaded.list();
7633 tasks.sort_unstable_by(dispatch_order);
7634 assert_eq!(
7635 tasks.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
7636 vec!["earlier", "later", "newer"]
7637 );
7638 assert_eq!(reloaded.next_runnable().unwrap().id, "earlier");
7639 assert_eq!(reloaded.get("earlier").unwrap().attempts, 0);
7640 }
7641
7642 #[test]
7643 fn upgrade_resume_legacy_order_uses_settlement_and_id() {
7644 let mut a = upgrade_parked("a", "2026-10-22T00:00:02Z");
7645 let mut b = upgrade_parked("b", "2026-10-22T00:00:01Z");
7646 for t in [&mut a, &mut b] {
7647 let mut value = serde_json::to_value(&*t).unwrap();
7648 value["passes"][0]
7649 .as_object_mut()
7650 .unwrap()
7651 .remove("started_at");
7652 *t = serde_json::from_value(value).unwrap();
7653 }
7654 assert!(dispatch_order(&a, &b).is_lt());
7655 b.passes[0].settled_at = a.passes[0].settled_at;
7656 assert!(dispatch_order(&a, &b).is_lt());
7657 }
7658
7659 #[test]
7660 fn upgrade_resume_key_excludes_other_parks_and_explicit_task_changes() {
7661 let original = upgrade_parked("a", "2026-10-22T00:00:01Z");
7662 assert!(original.upgrade_resume_key().is_some());
7663 for cause in [
7664 crate::run::ParkCause::Operator,
7665 crate::run::ParkCause::Question,
7666 crate::run::ParkCause::Interrupt {
7667 reason: "interrupt".into(),
7668 },
7669 crate::run::ParkCause::Unspecified,
7670 ] {
7671 let mut t = original.clone();
7672 t.passes[0].parked = Some(cause);
7673 assert!(t.upgrade_resume_key().is_none());
7674 let mut fresh = task("fresh");
7675 fresh.priority = 1;
7676 assert!(dispatch_order(&fresh, &t).is_lt());
7677 }
7678 let mut t = original.clone();
7679 t.release();
7680 assert!(t.upgrade_resume_key().is_none());
7681 t.edit("edited".into(), "new instruction".into()).unwrap();
7682 assert!(t.upgrade_resume_key().is_none());
7683 let mut t = original.clone();
7684 t.requeue();
7685 t.status = TaskStatus::Parked;
7686 assert!(t.upgrade_resume_key().is_none());
7687 let mut t = original.clone();
7688 t.start("different-run".into());
7689 t.park("no upgrade");
7690 assert!(t.upgrade_resume_key().is_none());
7691 }
7692
7693 #[test]
7694 fn explicitly_resumed_older_run_becomes_current_without_duplicate_history() {
7695 let dir = tempfile::tempdir().unwrap();
7696 let q = Queue::at(dir.path().join("queue"));
7697 let mut t = task("resume");
7698 t.start("A".into());
7699 t.record_pass("A", 0, 1, None);
7700 t.start("B".into());
7701 q.put(&mut t).unwrap();
7702 assert_eq!(t.runs, vec!["A", "B"]);
7703 t.start("A".into());
7704 t.record_pass("A", 1, 3, None);
7705 q.put(&mut t).unwrap();
7706 let saved = q.get(&t.id).unwrap();
7707 assert_eq!(saved.runs, vec!["B", "A"]);
7708 assert_eq!(saved.runs.last().map(String::as_str), Some("A"));
7709 assert_eq!(saved.attempts, 3);
7710 assert_eq!(saved.passes.len(), 2);
7711 assert_eq!(saved.passes[0].run, "A");
7712 assert_eq!(saved.passes[1].run, "A");
7713 }
7714
7715 #[test]
7716 fn repeated_start_records_one_run_and_separate_passes() {
7717 let mut t = task("resume");
7718 t.start("same-run".into());
7719 t.record_pass("same-run", 0, 1, None);
7720 t.start("same-run".into());
7721 t.record_pass("same-run", 1, 2, None);
7722 assert_eq!(t.runs, vec!["same-run"]);
7723 assert_eq!(t.attempts, 2);
7724 assert_eq!(t.passes.len(), 2);
7725 }
7726
7727 #[test]
7728 fn link_run_adds_a_run_once_and_touches_nothing_else() {
7729 let dir = tempfile::tempdir().unwrap();
7730 let queue = Queue::at(dir.path().join("queue"));
7731 let mut t = Task::new(
7732 "t".to_owned(),
7733 "do it".to_owned(),
7734 PathBuf::from("."),
7735 Source::Human,
7736 );
7737 queue.put(&mut t).unwrap();
7738 let before = queue.get(&t.id).unwrap();
7739
7740 let linked = queue.link_run(&t.id[..4], "20260930-092817-ec34").unwrap();
7741 assert_eq!(linked.runs, vec!["20260930-092817-ec34".to_owned()]);
7742 assert_eq!(linked.status, before.status);
7743 assert_eq!(linked.attempts, before.attempts);
7744 assert_eq!(linked.interrupt, before.interrupt);
7745
7746 let again = queue.link_run(&t.id, "20260930-092817-ec34").unwrap();
7747 assert_eq!(again.runs.len(), 1, "linking twice must not duplicate");
7748 assert_eq!(queue.get(&t.id).unwrap().runs.len(), 1);
7749 assert!(queue.link_run("no-such-task", "r").is_err());
7750 }
7751
7752 #[test]
7753 fn put_keeps_a_run_linked_after_the_writer_took_its_snapshot() {
7754 let dir = tempfile::tempdir().unwrap();
7755 let queue = Queue::at(dir.path().join("queue"));
7756 let mut t = Task::new(
7757 "t".to_owned(),
7758 "do it".to_owned(),
7759 PathBuf::from("."),
7760 Source::Human,
7761 );
7762 queue.put(&mut t).unwrap();
7763 let mut snapshot = queue.get(&t.id).unwrap();
7765 queue.link_run(&t.id, "20260930-092817-ec34").unwrap();
7766
7767 snapshot.start("20260930-000000-aaaa".to_owned());
7768 queue.put(&mut snapshot).unwrap();
7769
7770 let stored = queue.get(&t.id).unwrap();
7771 assert!(stored.runs.contains(&"20260930-092817-ec34".to_owned()));
7772 assert!(stored.runs.contains(&"20260930-000000-aaaa".to_owned()));
7773 assert_eq!(stored.attempts, 1);
7774 }
7775
7776 #[test]
7777 fn concurrent_links_and_daemon_saves_lose_nothing() {
7778 let dir = tempfile::tempdir().unwrap();
7779 let queue = Queue::at(dir.path().join("queue"));
7780 let mut t = Task::new(
7781 "t".to_owned(),
7782 "do it".to_owned(),
7783 PathBuf::from("."),
7784 Source::Human,
7785 );
7786 queue.put(&mut t).unwrap();
7787 let id = t.id.clone();
7788
7789 let linkers: Vec<_> = (0..4)
7790 .map(|n| {
7791 let (queue, id) = (queue.clone(), id.clone());
7792 std::thread::spawn(move || {
7793 for k in 0..10 {
7794 queue
7795 .link_run(&id, &format!("20260930-00000{n}-l{k:03}"))
7796 .unwrap();
7797 }
7798 })
7799 })
7800 .collect();
7801 let mut mine = queue.get(&id).unwrap();
7804 for k in 0..10 {
7805 mine.start(format!("20260930-000009-d{k:03}"));
7806 queue.put(&mut mine).unwrap();
7807 }
7808 for l in linkers {
7809 l.join().unwrap();
7810 }
7811
7812 let stored = queue.get(&id).unwrap();
7813 assert_eq!(stored.runs.len(), 50, "{:?}", stored.runs);
7814 assert_eq!(
7815 stored.attempts, 10,
7816 "linking never rewinds the daemon's work"
7817 );
7818 }
7819
7820 fn age_lock(path: &Path) {
7821 let f = std::fs::OpenOptions::new().write(true).open(path).unwrap();
7822 f.set_modified(std::time::SystemTime::now() - std::time::Duration::from_secs(60))
7823 .unwrap();
7824 }
7825
7826 #[test]
7827 fn concurrent_stale_takeover_yields_one_holder() {
7828 use std::sync::atomic::{AtomicUsize, Ordering};
7829 use std::sync::{Arc, Barrier};
7830 for _ in 0..5 {
7831 let dir = tempfile::tempdir().unwrap();
7832 let q = Queue::at(dir.path().to_path_buf());
7833 let lock = dir.path().join("t.write-lock");
7834 std::fs::write(&lock, "dead-0000").unwrap();
7835 age_lock(&lock);
7836 let n = 6;
7837 let barrier = Arc::new(Barrier::new(n));
7838 let (now, max) = (Arc::new(AtomicUsize::new(0)), Arc::new(AtomicUsize::new(0)));
7839 let handles: Vec<_> = (0..n)
7840 .map(|_| {
7841 let (q, b, now, max) = (q.clone(), barrier.clone(), now.clone(), max.clone());
7842 std::thread::spawn(move || {
7843 b.wait();
7844 let g = q.lock_task("t").unwrap();
7845 let held = now.fetch_add(1, Ordering::SeqCst) + 1;
7846 max.fetch_max(held, Ordering::SeqCst);
7847 std::thread::sleep(std::time::Duration::from_millis(20));
7848 now.fetch_sub(1, Ordering::SeqCst);
7849 drop(g);
7850 })
7851 })
7852 .collect();
7853 for h in handles {
7854 h.join().unwrap();
7855 }
7856 assert_eq!(max.load(Ordering::SeqCst), 1);
7857 assert!(!lock.exists());
7858 }
7859 }
7860
7861 #[test]
7862 fn dropping_a_replaced_lock_leaves_the_new_holders_token() {
7863 let dir = tempfile::tempdir().unwrap();
7864 let q = Queue::at(dir.path().to_path_buf());
7865 let lock = dir.path().join("t.write-lock");
7866 let a = q.lock_task("t").unwrap();
7867 let replacement = owner_token();
7870 std::fs::write(&lock, &replacement).unwrap();
7871 drop(a);
7872 assert_eq!(std::fs::read_to_string(&lock).unwrap(), replacement);
7873 }
7874
7875 #[test]
7876 fn aged_live_task_lock_excludes_updates_until_retirement_releases_it() {
7877 let dir = tempfile::tempdir().unwrap();
7878 let q = Queue::at(dir.path().to_path_buf());
7879 let held = q.lock_task("t").unwrap();
7880 let path = dir.path().join("t.write-lock");
7881 age_lock(&path);
7882 assert!(!break_stale(&path, &held.token));
7883 let (started_tx, started_rx) = std::sync::mpsc::channel();
7884 let (acquired_tx, acquired_rx) = std::sync::mpsc::channel();
7885 let updater = std::thread::spawn(move || {
7886 started_tx.send(()).unwrap();
7887 let _write = q.lock_task("t").unwrap();
7888 acquired_tx.send(()).unwrap();
7889 });
7890 started_rx.recv().unwrap();
7891 assert!(
7892 acquired_rx
7893 .recv_timeout(std::time::Duration::from_millis(100))
7894 .is_err()
7895 );
7896 assert_eq!(std::fs::read_to_string(&path).unwrap(), held.token);
7897 drop(held);
7898 acquired_rx
7899 .recv_timeout(std::time::Duration::from_secs(2))
7900 .unwrap();
7901 updater.join().unwrap();
7902 assert!(!path.exists());
7903 }
7904
7905 #[test]
7906 fn break_stale_leaves_a_lock_that_replaced_the_one_judged() {
7907 let dir = tempfile::tempdir().unwrap();
7908 let lock = dir.path().join("t.write-lock");
7909 std::fs::write(&lock, "new-token").unwrap();
7910 assert!(!break_stale(&lock, "old-token"));
7911 assert_eq!(std::fs::read_to_string(&lock).unwrap(), "new-token");
7912 assert!(!break_stale(&lock, "new-token"));
7914 assert!(lock.exists());
7915 age_lock(&lock);
7916 assert!(break_stale(&lock, "new-token"));
7917 assert!(!lock.exists());
7918 }
7919
7920 #[test]
7921 fn a_stale_break_marker_is_recovered_and_a_fresh_one_is_respected() {
7922 let dir = tempfile::tempdir().unwrap();
7923 let lock = dir.path().join("t.write-lock");
7924 std::fs::write(&lock, "dead-1").unwrap();
7925 age_lock(&lock);
7926 let marker = break_marker(&lock, "dead-1");
7927 std::fs::write(&marker, "crashed-remover").unwrap();
7928 assert!(!break_stale(&lock, "dead-1"));
7930 assert!(lock.exists());
7931 age_lock(&marker);
7933 assert!(break_stale(&lock, "dead-1"));
7934 assert!(!lock.exists());
7935 assert!(!marker.exists());
7936 }
7937
7938 fn chat_task() -> Task {
7939 Task::new(
7940 "t".to_owned(),
7941 "do t".to_owned(),
7942 PathBuf::from("."),
7943 Source::Agent {
7944 run: "20260902-000000-beef".to_owned(),
7945 node: CHAT_NODE.to_owned(),
7946 },
7947 )
7948 }
7949
7950 #[test]
7951 fn a_blocked_hold_keeps_its_anchor_but_a_new_run_starts_a_new_hold() {
7952 let mut t = chat_task();
7953 t.hold_machine(Some("waiting".into()));
7954 let old: Timestamp = "2020-01-01T00:00:00Z".parse().unwrap();
7955 t.held_at = Some(old);
7956 t.block(vec!["decision".into()], None);
7957 t.hold_machine(Some("same waiting decision".into()));
7958 assert_eq!(t.held_at, Some(old));
7959 t.start("real-new-run".into());
7960 t.fail("new failure", 1);
7961 assert_ne!(
7962 t.held_at,
7963 Some(old),
7964 "old answers cannot approve a new hold"
7965 );
7966 }
7967
7968 #[test]
7969 fn legacy_delivery_survives_upgrade_and_a_no_progress_run_link() {
7970 let (_dir, queue) = queue();
7971 let mut t = chat_task();
7972 t.start("old-run".into());
7973 t.hold_machine(Some("operator is considering recovery".into()));
7974 t.chat_notice = Some(ChatNotice {
7975 key: format!("held#{}", t.held_at.unwrap()),
7976 at: Timestamp::now(),
7977 outcome: ChatNoticeOutcome::Posted,
7978 });
7979 let mut raw = serde_json::to_value(&t).unwrap();
7980 raw.as_object_mut().unwrap().remove("chat_notices");
7981 raw.as_object_mut().unwrap().remove("hold_notice_cause");
7982 std::fs::create_dir_all(queue.path_of(&t.id).parent().unwrap()).unwrap();
7983 std::fs::write(queue.path_of(&t.id), serde_json::to_string(&raw).unwrap()).unwrap();
7984 assert_eq!(queue.get(&t.id).unwrap().chat_notice_due(), None);
7985 queue
7986 .modify(&t.id, |task| {
7987 task.requeue();
7988 task.link_run("unprepared-run");
7989 task.startup_notice_cause("startup-source");
7990 task.fail("same unresolved preflight", 0);
7991 true
7992 })
7993 .unwrap();
7994 assert_eq!(queue.get(&t.id).unwrap().chat_notice_due(), None);
7995 queue
7996 .modify(&t.id, |task| {
7997 task.succeed(completion(task));
7998 true
7999 })
8000 .unwrap();
8001 assert!(
8002 queue
8003 .get(&t.id)
8004 .unwrap()
8005 .chat_notice_due()
8006 .unwrap()
8007 .starts_with("done:")
8008 );
8009 }
8010
8011 #[test]
8012 fn a_dependency_wait_does_not_change_when_released_and_blocked_again() {
8013 let mut t = chat_task();
8014 t.block(vec!["a".into(), "b".into()], Some("waiting".into()));
8015 let key = t.chat_notice_key().unwrap();
8016 t.chat_notices.push(key);
8017 t.release();
8018 t.block(
8019 vec!["b".into(), "a".into(), "a".into()],
8020 Some("still waiting on prerequisites".into()),
8021 );
8022 assert_eq!(t.chat_notice_due(), None);
8023 t.block(
8024 vec!["new-question".into()],
8025 Some("different decision".into()),
8026 );
8027 assert!(t.chat_notice_due().is_some());
8028 }
8029
8030 #[test]
8031 fn running_startup_failures_preserve_stage_and_report_distinct_blockers() {
8032 let mut t = chat_task();
8033 t.start("existing-run".into());
8034 t.fail("implementation failed", 1);
8035 let failed = t.chat_notice_key().unwrap();
8036 t.chat_notices.push(failed.clone());
8037 t.release_operator("test", None);
8038 t.start("existing-run".into());
8039 t.fail_startup("startup-source", "same unresolved recovery source", 1);
8040 assert_eq!(
8041 t.chat_notice_due(),
8042 None,
8043 "no-progress recovery stays quiet"
8044 );
8045 t.release_operator("test", None);
8046 t.start("existing-run".into());
8047 t.fail_startup("startup-attachments", "attachment missing", 1);
8048 let attachments = t.chat_notice_due().expect("new attachment blocker");
8049 assert_ne!(attachments, failed);
8050 assert_eq!(
8051 t.hold_notice_cause.as_ref().unwrap().stage,
8052 "startup-attachments"
8053 );
8054 t.chat_notices.push(attachments);
8055 t.release_operator("test", None);
8056 t.start("existing-run".into());
8057 t.fail_startup(
8058 "startup-attachments",
8059 "same missing attachment, reworded",
8060 1,
8061 );
8062 assert_eq!(
8063 t.chat_notice_due(),
8064 None,
8065 "same stage after attempt counter reset"
8066 );
8067 t.release_operator("test", None);
8068 t.start("existing-run".into());
8069 t.fail_startup("startup-config", "different preflight stage", 1);
8070 assert!(t.chat_notice_due().is_some());
8071 assert_eq!(
8072 t.hold_notice_cause.as_ref().unwrap().stage,
8073 "startup-config"
8074 );
8075 }
8076
8077 #[test]
8078 fn structured_causes_preserve_no_progress_retries_and_report_new_passes() {
8079 let mut t = chat_task();
8080 t.hold_machine(Some("startup source missing".into()));
8081 t.startup_notice_cause("startup-source");
8082 let first = t.chat_notice_key().unwrap();
8083 t.chat_notices.push(first.clone());
8084 t.release_operator("test", None);
8085 t.startup_notice_cause("startup-source");
8086 t.hold_machine(Some("same source cannot be read".into()));
8087 assert_eq!(t.chat_notice_due(), None);
8088 t.startup_notice_cause("startup-config");
8089 assert!(t.chat_notice_due().is_some(), "different startup stage");
8090 t.notice_cause("failed", Some("existing-run"), Some(0));
8091 let run_failure = t.chat_notice_key().unwrap();
8092 t.chat_notices.push(run_failure.clone());
8093 t.release_operator("test", None);
8094 t.startup_notice_cause("startup-source");
8095 t.hold_machine(Some("no new work happened".into()));
8096 assert_eq!(t.chat_notice_due(), None);
8097 t.notice_cause("failed", Some("existing-run"), Some(1));
8098 assert!(t.chat_notice_due().is_some(), "a real resumed pass failed");
8099 assert_ne!(t.chat_notice_key().unwrap(), run_failure);
8100 }
8101
8102 #[test]
8103 fn legacy_hold_baseline_does_not_replay_or_hide_new_failures_and_completion() {
8104 let mut t = chat_task();
8105 t.hold_machine(Some("still waiting".into()));
8106 t.chat_notice = Some(ChatNotice {
8107 key: "held#2026-10-14T00:00:00Z".into(),
8108 at: Timestamp::now(),
8109 outcome: ChatNoticeOutcome::Posted,
8110 });
8111 assert_eq!(t.chat_notice_due(), None, "old hold baseline");
8112 t.import_chat_notice();
8113 t.notice_cause("failed", Some("new-run"), Some(0));
8114 assert!(t.chat_notice_due().is_some(), "new producer evidence");
8115 t.succeed(completion(&t));
8116 assert!(t.chat_notice_due().unwrap().starts_with("done:"));
8117 }
8118
8119 #[test]
8120 fn a_chat_notice_is_due_only_for_a_final_state_and_only_once() {
8121 let mut t = chat_task();
8122 assert_eq!(t.chat_notice_due(), None, "queued");
8123 t.start("r1".to_owned());
8124 assert_eq!(t.chat_notice_due(), None, "running");
8125 t.fail("boom", 3);
8126 assert_eq!(t.status, TaskStatus::Failed);
8127 assert_eq!(t.chat_notice_due(), None, "a retried failure is not final");
8128 t.start("r2".to_owned());
8129 t.park("upgrade");
8130 assert_eq!(t.chat_notice_due(), None, "parked");
8131 t.fail("boom", 1);
8132 assert_eq!(t.status, TaskStatus::Held);
8133 let key = t
8134 .chat_notice_due()
8135 .expect("held on the last attempt is final");
8136 t.chat_notice = Some(ChatNotice {
8137 key,
8138 at: Timestamp::now(),
8139 outcome: ChatNoticeOutcome::Posted,
8140 });
8141 assert_eq!(t.chat_notice_due(), None, "same hold, no second notice");
8142 t.release();
8143 assert_eq!(t.chat_notice_due(), None, "requeued after a release");
8144 t.start("r3".to_owned());
8145 t.succeed(completion(&t));
8146 assert!(t.chat_notice_due().is_some(), "done is a new final state");
8147 }
8148
8149 #[test]
8150 fn legacy_completion_receipts_do_not_suppress_new_occurrences() {
8151 for key in ["done", "done#0", "done#1", "done#12"] {
8152 let mut t = chat_task();
8153 t.status = TaskStatus::Done;
8154 t.chat_notice = Some(ChatNotice {
8155 key: key.to_owned(),
8156 at: Timestamp::now(),
8157 outcome: ChatNoticeOutcome::Posted,
8158 });
8159 assert_eq!(t.chat_notice_key().as_deref(), Some("done"));
8160 assert_eq!(t.chat_notice_due(), None, "legacy recorded key: {key}");
8161 let mut context = completion(&t);
8162 context.reason = Some("inspect again".into());
8163 t.reopen(context).unwrap();
8164 t.start("r2".to_owned());
8165 t.succeed(completion(&t));
8166 assert!(t.chat_notice_key().unwrap().starts_with("done:"));
8167 assert!(
8168 t.chat_notice_due().is_some(),
8169 "new occurrence, old receipt: {key}"
8170 );
8171 }
8172 }
8173
8174 #[test]
8175 fn a_release_without_progress_keeps_the_unresolved_notice_cause() {
8176 let mut t = chat_task();
8177 t.hold_manual(Some("wait".to_owned()));
8178 let first = t.chat_notice_due().expect("held");
8179 t.chat_notice = Some(ChatNotice {
8180 key: first.clone(),
8181 at: Timestamp::now(),
8182 outcome: ChatNoticeOutcome::Posted,
8183 });
8184 t.hold_manual(Some("still waiting".to_owned()));
8185 assert_eq!(t.chat_notice_due(), None, "a re-hold keeps its start");
8186 t.release();
8187 std::thread::sleep(std::time::Duration::from_millis(5));
8188 t.hold_manual(None);
8189 assert_eq!(t.chat_notice_due(), None, "no progress, same cause");
8190 }
8191
8192 fn human_key(t: &Task) -> Option<String> {
8193 t.chat_notice_key().filter(|k| k.starts_with("done:"))
8194 }
8195
8196 #[test]
8197 fn a_chat_notice_needs_a_chat_source_and_a_current_schema() {
8198 let mut human = task("h");
8199 human.succeed(completion(&human));
8200 assert!(
8201 human
8202 .chat_notice_due()
8203 .is_some_and(|k| k.starts_with("done:")),
8204 "a completion this build recorded reaches the linked task chat"
8205 );
8206 human.completion_history[0].schema = COMPLETION_REPORT_SCHEMA - 1;
8207 assert_eq!(
8208 human.chat_notice_due(),
8209 None,
8210 "an older completion stays quiet"
8211 );
8212 let mut held_human = task("hh");
8213 held_human.hold_manual(None);
8214 assert_eq!(
8215 held_human.chat_notice_due(),
8216 None,
8217 "only completion is reported"
8218 );
8219 let mut inherited = task("i");
8221 inherited.origin_chat = Some("20260902-000000-beef".to_owned());
8222 inherited.succeed(completion(&inherited));
8223 assert_eq!(
8224 inherited.chat_notice_due(),
8225 human_key(&inherited),
8226 "reported as a human-filed completion, not as a chat's own task"
8227 );
8228 assert_eq!(inherited.filed_by_chat(), None);
8229 let mut old = chat_task();
8230 old.schema = 12;
8231 old.status = TaskStatus::Done;
8232 assert_eq!(old.chat_notice_due(), None, "history is not replayed");
8233 let mut live = chat_task();
8234 live.schema = 12;
8235 live.start("r1".to_owned());
8236 live.succeed(completion(&live));
8237 assert!(live.chat_notice_due().is_some(), "started by this build");
8238 let mut held = chat_task();
8239 held.schema = 12;
8240 held.hold_machine(Some("config".to_owned()));
8241 assert!(held.chat_notice_due().is_some(), "held before any start");
8242 }
8243
8244 #[test]
8245 fn a_stale_snapshot_does_not_rewind_a_recorded_chat_notice() {
8246 let tmp = tempfile::tempdir().expect("tempdir");
8247 let q = Queue::at(tmp.path().join("queue"));
8248 let mut t = chat_task();
8249 t.succeed(completion(&t));
8250 q.put(&mut t).expect("put");
8251 let mut stale = q.get(&t.id).expect("get");
8252 let key = t.chat_notice_due().expect("due");
8253 q.modify(&t.id, |x| {
8254 x.chat_notice = Some(ChatNotice {
8255 key: key.clone(),
8256 at: Timestamp::now(),
8257 outcome: ChatNoticeOutcome::Posted,
8258 });
8259 true
8260 })
8261 .expect("modify");
8262 q.put(&mut stale).expect("stale put");
8263 assert_eq!(q.get(&t.id).expect("get").chat_notice_due(), None);
8264 }
8265
8266 #[test]
8267 fn empty_sources_are_omitted_so_older_builds_still_read_the_task() {
8268 let mut t = task("plain");
8271 let value = serde_json::to_value(&t).unwrap();
8272 assert!(value.get("sources").is_none(), "{value}");
8273 t.sources.pick_commits.push(crate::refs::Input {
8274 token: "abc1234".into(),
8275 sha: "a".repeat(40),
8276 provenance: crate::refs::Provenance::ExplicitCli,
8277 });
8278 let value = serde_json::to_value(&t).unwrap();
8279 assert_eq!(value["sources"]["pick_commits"][0]["sha"], "a".repeat(40));
8280 let restored: Task = serde_json::from_value(value).unwrap();
8281 assert_eq!(restored.sources, t.sources);
8282 }
8283
8284 fn queue_with_ids(dir: &Path, ids: &[&str]) -> Queue {
8286 let ids: Vec<String> = ids.iter().map(|s| (*s).to_owned()).collect();
8287 let n = std::sync::atomic::AtomicUsize::new(0);
8288 Queue::at(dir.join("queue")).with_id_source(move || {
8289 let i = n.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
8290 ids.get(i)
8291 .cloned()
8292 .unwrap_or_else(|| format!("20260101-000000-f{i:03x}"))
8293 })
8294 }
8295
8296 const TAKEN: &str = "20260101-000000-aaaa";
8297
8298 #[test]
8299 fn a_new_task_never_merges_into_a_record_with_its_candidate_id() {
8300 let dir = tempfile::tempdir().unwrap();
8301 let q = queue_with_ids(dir.path(), &[TAKEN, TAKEN]);
8302 let mut first = task("first");
8303 first.start("run-1".into());
8304 first.succeed(completion(&first));
8305 q.put(&mut first).unwrap();
8306 assert_eq!(first.id, TAKEN);
8307 let stored_before = q.get(&first.id).unwrap();
8308 assert!(!stored_before.runs.is_empty());
8309
8310 let mut second = task("second");
8311 q.put(&mut second).unwrap();
8312
8313 assert_ne!(second.id, first.id);
8314 assert!(second.runs.is_empty());
8315 assert!(second.passes.is_empty());
8316 assert!(second.chat_notices.is_empty());
8317 assert!(second.chat_notice.is_none());
8318 assert_eq!(second.chat_notice_due(), task("fresh").chat_notice_due());
8319 let a = q.get(&first.id).unwrap();
8320 let b = q.get(&second.id).unwrap();
8321 assert_eq!(a.title, "first");
8322 assert_eq!(a.runs, stored_before.runs);
8323 assert_eq!(a.passes, stored_before.passes);
8324 assert_eq!(a.chat_notices, stored_before.chat_notices);
8325 assert_eq!(a.chat_notice, stored_before.chat_notice);
8326 assert_eq!(a.chat_notice_due(), stored_before.chat_notice_due());
8327 assert_eq!(b.title, "second");
8328 assert!(b.runs.is_empty());
8329 assert!(b.passes.is_empty());
8330 assert!(b.chat_notice.is_none());
8331
8332 let mut again = q.get(&second.id).unwrap();
8334 again.title = "second, edited".into();
8335 q.put(&mut again).unwrap();
8336 assert_eq!(q.get(&second.id).unwrap().title, "second, edited");
8337 assert_eq!(q.list().len(), 2);
8338 }
8339
8340 #[test]
8341 fn a_new_task_skips_an_id_with_an_orphaned_claim_or_attachments() {
8342 let dir = tempfile::tempdir().unwrap();
8343 let q = queue_with_ids(dir.path(), &["orphan-lock", "orphan-dir", "free"]);
8344 std::fs::create_dir_all(q.root()).unwrap();
8345 std::fs::write(q.root().join("orphan-lock.lock"), "x").unwrap();
8346 std::fs::create_dir_all(q.attachments_dir("orphan-dir")).unwrap();
8347 let mut t = task("t");
8348 q.put(&mut t).unwrap();
8349 assert_eq!(t.id, "free");
8350 }
8351
8352 #[test]
8353 fn a_claimed_new_task_holds_the_claim_on_the_reserved_id() {
8354 let dir = tempfile::tempdir().unwrap();
8355 let q = queue_with_ids(dir.path(), &[TAKEN, TAKEN]);
8356 let mut first = task("first");
8357 q.put(&mut first).unwrap();
8358 let mut second = task("second");
8359 let claim = q.file_claimed(&mut second).unwrap();
8360 assert_ne!(second.id, first.id);
8361 assert!(q.claim(&second.id).is_err());
8362 assert!(q.claim(&first.id).is_ok(), "the first task was not claimed");
8363 drop(claim);
8364 }
8365
8366 #[test]
8367 fn an_attached_new_task_skips_a_taken_id() {
8368 let dir = tempfile::tempdir().unwrap();
8369 let q = queue_with_ids(dir.path(), &[TAKEN, TAKEN]);
8370 let mut first = task("first");
8371 q.put(&mut first).unwrap();
8372 let src = source_file(dir.path(), "shot.png", "x");
8373 let mut second = task("second");
8374 q.attach_and_put(&mut second, &[src]).unwrap();
8375 assert_ne!(second.id, first.id);
8376 assert!(!q.attachments_dir(&first.id).exists());
8377 assert_eq!(q.attachment_paths(&second).len(), 1);
8378 assert!(q.attachment_paths(&second)[0].is_file());
8379 }
8380
8381 #[test]
8382 fn attaching_before_putting_a_new_task_reserves_the_id() {
8383 let dir = tempfile::tempdir().unwrap();
8384 let q = queue_with_ids(dir.path(), &[TAKEN, TAKEN]);
8385 let mut first = task("first");
8386 q.put(&mut first).unwrap();
8387 let src = source_file(dir.path(), "shot.png", "x");
8388 let mut second = task("second");
8389 q.attach(&mut second, &[src]).unwrap();
8390 assert_ne!(second.id, first.id);
8391 assert!(q.attachments_dir(&second.id).is_dir());
8392 q.put(&mut second).unwrap();
8393 assert_eq!(q.get(&second.id).unwrap().attachments.len(), 1);
8394 assert_eq!(q.get(&first.id).unwrap().title, "first");
8395 assert!(q.get(&first.id).unwrap().attachments.is_empty());
8396 }
8397
8398 #[test]
8399 fn create_new_keeps_its_already_exists_meaning() {
8400 let dir = tempfile::tempdir().unwrap();
8401 let q = Queue::at(dir.path().join("queue"));
8402 let mut a = task("a");
8403 a.id = "fixed-id".into();
8404 assert!(q.create_new(&mut a).unwrap());
8405 let mut b = task("b");
8406 b.id = "fixed-id".into();
8407 assert!(!q.create_new(&mut b).unwrap());
8408 assert_eq!(q.get("fixed-id").unwrap().title, "a");
8409 }
8410
8411 #[test]
8412 fn filing_gives_up_when_no_id_is_ever_free() {
8413 let dir = tempfile::tempdir().unwrap();
8414 let q = Queue::at(dir.path().join("queue")).with_id_source(|| TAKEN.to_owned());
8415 let mut first = task("first");
8416 q.put(&mut first).unwrap();
8417 let mut second = task("second");
8418 assert!(q.put(&mut second).is_err());
8419 assert_eq!(q.get(&first.id).unwrap().title, "first");
8420 }
8421}