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 = 25;
151
152const RECOVERY_HOLD_SCHEMA: u32 = 24;
153
154pub(crate) fn dispatch_order(a: &Task, b: &Task) -> std::cmp::Ordering {
160 match (a.upgrade_resume_key(), b.upgrade_resume_key()) {
161 (Some(a), Some(b)) => a.cmp(&b),
162 (Some(_), None) => std::cmp::Ordering::Less,
163 (None, Some(_)) => std::cmp::Ordering::Greater,
164 (None, None) => b.priority.cmp(&a.priority).then(a.id.cmp(&b.id)),
165 }
166}
167
168#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
175#[serde(tag = "kind", rename_all = "snake_case")]
176pub enum MachineHoldCause {
177 DiskCapacity {
179 reason: String,
181 #[serde(default)]
183 before_start: bool,
184 },
185}
186
187#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
189#[serde(rename_all = "lowercase")]
190pub enum HoldSource {
191 Manual,
193 Machine,
195}
196
197impl HoldSource {
198 pub fn label(self) -> &'static str {
200 match self {
201 Self::Manual => "manual",
202 Self::Machine => "machine",
203 }
204 }
205}
206
207#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
210#[serde(tag = "kind", rename_all = "lowercase")]
211pub enum Source {
212 Human,
214 Agent {
217 run: String,
219 node: String,
221 },
222 Issue {
224 number: u64,
226 repo: String,
228 },
229}
230
231pub const CHAT_NODE: &str = "chat";
234
235impl Source {
236 pub fn label(&self) -> String {
238 match self {
239 Self::Human => "human".to_owned(),
240 Self::Agent { run, node } => format!("{node}@{}", short(run)),
241 Self::Issue { number, .. } => format!("issue #{number}"),
242 }
243 }
244}
245
246#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
248#[serde(rename_all = "lowercase")]
249pub enum TaskStatus {
250 Queued,
252 Running,
254 Done,
256 Failed,
258 Held,
260 Blocked,
264 Parked,
269}
270
271impl TaskStatus {
272 pub fn runnable(self) -> bool {
274 matches!(self, Self::Queued | Self::Failed | Self::Parked)
275 }
276
277 pub fn as_str(self) -> &'static str {
279 match self {
280 Self::Queued => "queued",
281 Self::Running => "running",
282 Self::Done => "done",
283 Self::Failed => "failed",
284 Self::Held => "held",
285 Self::Blocked => "blocked",
286 Self::Parked => "parked",
287 }
288 }
289}
290
291#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
294pub struct TaskCounts {
295 pub queued: usize,
297 pub running: usize,
299 pub done: usize,
301 pub failed: usize,
303 pub held: usize,
305 pub blocked: usize,
307 pub parked: usize,
309}
310
311impl TaskCounts {
312 pub fn of(tasks: &[Task]) -> Self {
316 Self::of_statuses(tasks.iter().map(|task| task.status))
317 }
318
319 pub(crate) fn of_statuses(statuses: impl IntoIterator<Item = TaskStatus>) -> Self {
321 let mut counts = Self::default();
322 for status in statuses {
323 match status {
324 TaskStatus::Queued => counts.queued += 1,
325 TaskStatus::Running => counts.running += 1,
326 TaskStatus::Done => counts.done += 1,
327 TaskStatus::Failed => counts.failed += 1,
328 TaskStatus::Held => counts.held += 1,
329 TaskStatus::Blocked => counts.blocked += 1,
330 TaskStatus::Parked => counts.parked += 1,
331 }
332 }
333 counts
334 }
335}
336
337#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
339pub struct Reassignment {
340 pub from: PathBuf,
342 pub to: PathBuf,
344 pub actor: String,
346 pub at: Timestamp,
348 pub run_boundary: usize,
350}
351
352#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
354#[serde(tag = "kind", content = "talk", rename_all = "snake_case")]
355pub enum CompletionActor {
356 Cli,
358 Web,
360 Chat(String),
362 Conductor,
364 DaemonSettle,
366}
367
368#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
370#[serde(rename_all = "snake_case")]
371pub enum CompletionAction {
372 Complete,
374 Reopen,
376}
377
378#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
380pub struct CompletionRunSnapshot {
381 pub id: String,
383 pub status: Option<crate::run::RunStatus>,
385 pub pr_url: Option<String>,
387 pub pr_state: Option<String>,
389 pub pr_head: Option<String>,
391 #[serde(default)]
393 pub branches: Vec<String>,
394 pub error: Option<String>,
396}
397
398impl CompletionRunSnapshot {
399 fn from_run(state: &crate::run::RunState) -> Self {
400 let mut branches: Vec<String> = state
401 .candidates
402 .iter()
403 .map(|candidate| candidate.branch.clone())
404 .collect();
405 if let Some(branch) = &state.pr_head
406 && !branches.contains(branch)
407 {
408 branches.push(branch.clone());
409 }
410 Self {
411 id: state.id.clone(),
412 status: Some(state.status),
413 pr_url: state.pr.as_ref().map(|pr| pr.url.clone()),
414 pr_state: state.pr.as_ref().map(|pr| pr.state.clone()),
415 pr_head: state
416 .pr_merged_head
417 .clone()
418 .or_else(|| state.pr_pushed_head.clone()),
419 branches,
420 error: None,
421 }
422 }
423}
424
425#[derive(Debug, Clone)]
427pub struct CompletionContext {
428 pub actor: CompletionActor,
430 pub reason: Option<String>,
432 pub discard: bool,
434 pub run: Option<CompletionRunSnapshot>,
436 pub unavailable_runs: Vec<String>,
438}
439
440impl CompletionContext {
441 pub fn new(actor: CompletionActor, reason: Option<String>, home: &Path, task: &Task) -> Self {
443 let run = task
444 .runs
445 .last()
446 .map(|id| match crate::run::RunState::load_under(id, home) {
447 Ok(state) => CompletionRunSnapshot::from_run(&state),
448 Err(error) => CompletionRunSnapshot {
449 id: id.clone(),
450 status: None,
451 pr_url: None,
452 pr_state: None,
453 pr_head: None,
454 branches: Vec::new(),
455 error: Some(format!("{error:#}")),
456 },
457 });
458 Self {
459 actor,
460 reason,
461 discard: false,
462 run,
463 unavailable_runs: Vec::new(),
464 }
465 }
466
467 pub fn from_run(
469 actor: CompletionActor,
470 reason: Option<String>,
471 _task: &Task,
472 state: &crate::run::RunState,
473 ) -> Self {
474 Self {
475 actor,
476 reason,
477 discard: false,
478 run: Some(CompletionRunSnapshot::from_run(state)),
479 unavailable_runs: Vec::new(),
480 }
481 }
482}
483
484#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
486pub struct CompletionEvent {
487 pub occurrence: String,
489 pub action: CompletionAction,
491 pub actor: CompletionActor,
493 pub reason: Option<String>,
495 pub discard: bool,
497 pub prior_status: TaskStatus,
499 #[serde(default)]
501 pub prior_hold_reason: Option<String>,
502 #[serde(default)]
504 pub prior_block_reason: Option<String>,
505 #[serde(default)]
507 pub prior_error: Option<String>,
508 pub at: Timestamp,
510 pub run: Option<CompletionRunSnapshot>,
512 #[serde(default, skip_serializing_if = "Vec::is_empty")]
514 pub unavailable_runs: Vec<String>,
515}
516
517#[derive(Debug, Clone, Serialize, Deserialize)]
519#[serde(deny_unknown_fields)]
520pub struct Task {
521 pub schema: u32,
523 pub id: String,
525 pub title: String,
527 pub instruction: String,
529 #[serde(default, skip_serializing_if = "crate::refs::Sources::is_empty")]
531 pub sources: crate::refs::Sources,
532 pub repo: PathBuf,
534 #[serde(default)]
536 pub reassignments: Vec<Reassignment>,
537 pub source: Source,
539 #[serde(default)]
541 pub chat: Option<String>,
542 #[serde(default)]
544 pub priority: i32,
545 #[serde(default)]
556 pub solo: bool,
557 pub status: TaskStatus,
559 #[serde(default)]
561 pub completion_history: Vec<CompletionEvent>,
562 #[serde(default)]
564 pub attempts: usize,
565 #[serde(default)]
567 pub attempt_limit: Option<NonZeroUsize>,
568 #[serde(default)]
571 pub runs: Vec<String>,
572 #[serde(default)]
574 pub startup_failures: Vec<crate::run::StartupFailure>,
575 #[serde(default)]
577 pub last_error: Option<String>,
578 #[serde(default)]
591 pub hold_reason: Option<String>,
592 #[serde(default)]
595 pub hold_source: Option<HoldSource>,
596 #[serde(default, skip_serializing_if = "Option::is_none")]
597 recovery_budget_hold: Option<RecoveryBudgetHold>,
598 #[serde(default)]
600 pub machine_hold_cause: Option<MachineHoldCause>,
601 #[serde(default)]
603 pub disk_resume_run: Option<String>,
604 #[serde(default)]
606 pub disk_checked_at: Option<Timestamp>,
607 #[serde(default)]
619 pub diagnostic: Option<String>,
620 #[serde(default)]
630 pub blocked_by: Vec<String>,
631 #[serde(default)]
634 pub block_reason: Option<String>,
635 #[serde(default)]
648 pub blocked_from: Option<TaskStatus>,
649 #[serde(default)]
651 pub blocked_at: Option<Timestamp>,
652 #[serde(default)]
663 pub answers: Vec<AnsweredQuestion>,
664 #[serde(default)]
670 pub triage_applied: Vec<String>,
671 #[serde(default)]
677 pub actions_applied: Vec<String>,
678 #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
681 pub decision_effects: std::collections::BTreeMap<String, String>,
682 #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
685 pub superseded_resumes: std::collections::BTreeMap<String, String>,
686 #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
690 pub dispatched_resumes: std::collections::BTreeMap<String, String>,
691 #[serde(default)]
693 pub base_recovery_requests: Vec<String>,
694 #[serde(default)]
699 pub resume_override: Option<OperatorResume>,
700 #[serde(default, skip_serializing_if = "Option::is_none")]
702 pub sync_only: Option<crate::base_sync_only::Request>,
703 #[serde(default)]
705 pub repair_grants: Vec<crate::repair_budget::Receipt>,
706 #[serde(default)]
708 pub repair_reconciliations: Vec<crate::repair_budget::reconcile::Receipt>,
709 #[serde(default)]
712 pub resumption: Option<Resumption>,
713 #[serde(default)]
715 pub resumption_history: Vec<Resumption>,
716 #[serde(default)]
718 pub operator_decided_at: Option<Timestamp>,
719 #[serde(default)]
731 pub review_branch: Option<String>,
732 #[serde(default)]
734 pub review_instruction: Option<String>,
735 #[serde(default)]
737 pub pr_recovery: Option<crate::pr_recovery::Selection>,
738 #[serde(default)]
741 pub fresh_start: bool,
742 #[serde(default)]
744 pub replacement: Option<crate::merge_decision::Replacement>,
745 #[serde(default)]
756 pub interrupt: bool,
757 #[serde(default)]
780 pub urgent: bool,
781 #[serde(skip)]
786 pub(crate) unfiled: bool,
787 #[serde(default)]
793 pub attachments: Vec<String>,
794 #[serde(default)]
798 pub followup: Option<FollowUp>,
799 #[serde(default)]
805 pub origin_chat: Option<String>,
806 #[serde(default)]
813 pub overrides: Option<RunOverrides>,
814 #[serde(default)]
821 pub review_of: Option<String>,
822 #[serde(default)]
827 pub held_at: Option<Timestamp>,
828 #[serde(default)]
832 pub park_reason: Option<String>,
833 #[serde(default)]
836 pub chat_notice: Option<ChatNotice>,
837 #[serde(default)]
839 pub chat_notices: Vec<String>,
840 #[serde(default)]
843 pub hold_notice_cause: Option<NoticeCause>,
844 #[serde(default)]
849 pub passes: Vec<TaskPass>,
850 #[serde(default)]
854 pub dispatched_at: Option<Timestamp>,
855 #[serde(default)]
857 pub recovery_budget: Option<RecoveryBudget>,
858 #[serde(default)]
861 pub recovery_admission: Option<RecoveryAdmission>,
862 #[serde(default)]
865 pub recovery_generations: Vec<RecoveryBudget>,
866 pub created_at: Timestamp,
868 pub updated_at: Timestamp,
870}
871
872#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
874pub struct RecoveryAdmission {
875 pub base: String,
877 pub inputs: String,
879}
880
881#[derive(Debug, Clone, Serialize, Deserialize)]
882struct RecoveryBudgetHold {
883 admission: RecoveryAdmission,
884 run: String,
885 pass: usize,
886 held_at: Timestamp,
887 decision: Option<Timestamp>,
888 #[serde(default)]
889 legacy: bool,
890}
891
892#[derive(Debug, Clone, Serialize, Deserialize)]
895pub struct RecoveryBudget {
896 pub instruction: String,
898 pub base: String,
900 pub inputs: String,
902 pub stage: String,
904 pub failures: usize,
906 #[serde(default)]
909 pub progress: Option<String>,
910}
911
912impl RecoveryBudget {
913 fn budget_reason(&self) -> String {
914 format!(
915 "[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.",
916 self.failures, self.stage
917 )
918 }
919}
920
921fn recovery_progress(state: &crate::run::RunState) -> Option<String> {
922 use crate::proc::Quiet as _;
923 use std::hash::{Hash, Hasher};
924 let mut patches = Vec::new();
925 for candidate in state.candidates.iter().filter(|c| c.commits > 0) {
926 let output = std::process::Command::new("git")
927 .current_dir(&state.repo)
928 .args(["diff", "--binary", &state.base_commit, &candidate.branch])
929 .quiet()
930 .output()
931 .ok()?;
932 if !output.status.success() {
933 return None;
934 }
935 patches.push(output.stdout);
936 }
937 patches.sort();
938 patches.dedup();
939 let mut hash = std::collections::hash_map::DefaultHasher::new();
940 patches.hash(&mut hash);
941 Some(format!("{:x}", hash.finish()))
942}
943
944pub(crate) fn recovery_inputs(sources: &crate::refs::Sources) -> String {
948 serde_json::to_string(
949 &sources
950 .start_from
951 .iter()
952 .map(|i| ("start", &i.token, &i.sha))
953 .chain(
954 sources
955 .pick_commits
956 .iter()
957 .map(|i| ("pick", &i.token, &i.sha)),
958 )
959 .collect::<Vec<_>>(),
960 )
961 .unwrap_or_default()
962}
963
964#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
966pub struct NoticeCause {
967 pub stage: String,
969 #[serde(default, skip_serializing_if = "Option::is_none")]
972 pub target: Option<String>,
973 pub run: Option<String>,
975 pub pass: Option<usize>,
977}
978
979pub(crate) fn is_done_notice_key(key: &str) -> bool {
981 key == "done"
982 || key
983 .strip_prefix("done#")
984 .is_some_and(|count| !count.is_empty() && count.bytes().all(|b| b.is_ascii_digit()))
985}
986
987#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
989#[serde(rename_all = "snake_case")]
990pub enum PassCost {
991 Spent,
993 Refunded,
995}
996
997#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
999pub struct TaskPass {
1000 pub run: String,
1002 pub pass_index: usize,
1004 pub cost: PassCost,
1006 pub attempts_after: usize,
1008 #[serde(default)]
1010 pub started_at: Option<Timestamp>,
1011 pub settled_at: Timestamp,
1013 #[serde(default)]
1015 pub parked: Option<crate::run::ParkCause>,
1016}
1017
1018#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1020#[serde(rename_all = "lowercase")]
1021pub enum ChatNoticeOutcome {
1022 Posted,
1024 Skipped,
1026}
1027
1028#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1030pub struct ChatNotice {
1031 pub key: String,
1033 pub at: Timestamp,
1035 pub outcome: ChatNoticeOutcome,
1037}
1038
1039#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1041pub struct RunOverrides {
1042 #[serde(default)]
1045 pub inherit_daemon_options: bool,
1046 #[serde(default)]
1048 pub merge: Option<String>,
1049 #[serde(default)]
1051 pub candidates: Option<usize>,
1052 #[serde(default)]
1054 pub judges: Option<usize>,
1055 #[serde(default)]
1057 pub reviewers: Option<usize>,
1058 #[serde(default)]
1060 pub review_rounds: Option<usize>,
1061 #[serde(default)]
1063 pub seed: Option<u64>,
1064 #[serde(default)]
1066 pub config: Option<PathBuf>,
1067 #[serde(default, skip_serializing_if = "Option::is_none")]
1069 pub build_cache: Option<BuildCache>,
1070}
1071
1072impl RunOverrides {
1073 pub fn merge_over(&mut self, other: &RunOverrides) {
1075 macro_rules! take {
1076 ($($f:ident),*) => {$(
1077 if other.$f.is_some() {
1078 self.$f.clone_from(&other.$f);
1079 }
1080 )*};
1081 }
1082 take!(
1083 merge,
1084 candidates,
1085 judges,
1086 reviewers,
1087 review_rounds,
1088 seed,
1089 config,
1090 build_cache
1091 );
1092 }
1093
1094 pub fn apply(&self, config: &mut crate::config::Config) {
1096 if let Some(n) = self.candidates {
1097 config.graph.implementers = n;
1098 }
1099 if let Some(n) = self.judges {
1100 config.graph.judges = n;
1101 }
1102 if let Some(n) = self.reviewers {
1103 config.graph.reviewers = n;
1104 }
1105 if let Some(n) = self.review_rounds {
1106 config.graph.review_rounds = n;
1107 }
1108 if let Some(m) = &self.merge
1109 && let Ok(mode) = crate::daemon::merge_mode(m)
1110 {
1111 config.merge.mode = mode;
1112 }
1113 if let Some(s) = self.seed {
1114 config.blind.seed = Some(s);
1115 }
1116 if let Some(mode) = self.build_cache {
1117 config.verify.build_cache = mode;
1118 }
1119 }
1120}
1121
1122#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1124pub struct FollowUp {
1125 pub run: String,
1127 #[serde(default)]
1129 pub origin_task: Option<String>,
1130 pub pr: String,
1132 pub findings: Vec<String>,
1134 pub generation: u32,
1137}
1138
1139#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1141pub struct Resumption {
1142 pub generation: u64,
1144 pub source: String,
1146 pub question_id: Option<String>,
1148 pub at: Timestamp,
1150 pub instruction: String,
1152 pub answers_through: usize,
1154 pub runs_through: usize,
1157 pub cleared_reason: Option<String>,
1159 #[serde(default)]
1161 pub blocking_evidence: Vec<String>,
1162}
1163
1164#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1167pub struct OperatorResume {
1168 pub question_id: String,
1170 pub at: Timestamp,
1172 #[serde(default)]
1175 pub conductor_rehold: Option<String>,
1176 #[serde(default)]
1179 pub forced: bool,
1180 #[serde(default)]
1187 pub pinned_run: Option<String>,
1188}
1189
1190#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1193pub struct AnsweredQuestion {
1194 pub question: String,
1196 pub answer: String,
1198}
1199
1200fn append_missing<T: PartialEq>(ledger: &mut Vec<T>, entries: Vec<T>) {
1201 for entry in entries {
1202 if !ledger.contains(&entry) {
1203 ledger.push(entry);
1204 }
1205 }
1206}
1207
1208fn prepend_missing_by<T>(ledger: &mut Vec<T>, mut older: Vec<T>, same: impl Fn(&T, &T) -> bool) {
1209 older.retain(|old| !ledger.iter().any(|entry| same(entry, old)));
1210 if !older.is_empty() {
1211 older.append(ledger);
1212 *ledger = older;
1213 }
1214}
1215
1216impl Task {
1217 pub fn new(title: String, instruction: String, repo: PathBuf, source: Source) -> Self {
1219 let now = Timestamp::now();
1220 let origin_chat = match &source {
1221 Source::Agent { run, node } if node == CHAT_NODE => Some(run.clone()),
1222 _ => None,
1223 };
1224 Self {
1225 schema: SCHEMA,
1226 id: new_id(),
1227 title,
1228 instruction,
1229 sources: crate::refs::Sources::default(),
1230 repo,
1231 reassignments: Vec::new(),
1232 source,
1233 chat: None,
1234 priority: 0,
1235 solo: false,
1236 status: TaskStatus::Queued,
1237 completion_history: Vec::new(),
1238 attempts: 0,
1239 attempt_limit: None,
1240 runs: Vec::new(),
1241 startup_failures: Vec::new(),
1242 last_error: None,
1243 hold_reason: None,
1244 hold_source: None,
1245 recovery_budget_hold: None,
1246 machine_hold_cause: None,
1247 disk_resume_run: None,
1248 disk_checked_at: None,
1249 diagnostic: None,
1250 blocked_by: Vec::new(),
1251 block_reason: None,
1252 blocked_from: None,
1253 blocked_at: None,
1254 answers: Vec::new(),
1255 triage_applied: Vec::new(),
1256 actions_applied: Vec::new(),
1257 decision_effects: Default::default(),
1258 superseded_resumes: Default::default(),
1259 dispatched_resumes: Default::default(),
1260 base_recovery_requests: Vec::new(),
1261 resume_override: None,
1262 sync_only: None,
1263 repair_grants: Vec::new(),
1264 repair_reconciliations: Vec::new(),
1265 resumption: None,
1266 resumption_history: Vec::new(),
1267 operator_decided_at: None,
1268 review_branch: None,
1269 review_instruction: None,
1270 pr_recovery: None,
1271 fresh_start: false,
1272 replacement: None,
1273 interrupt: false,
1274 urgent: false,
1275 unfiled: true,
1276 attachments: Vec::new(),
1277 followup: None,
1278 origin_chat,
1279 overrides: None,
1280 review_of: None,
1281 held_at: None,
1282 park_reason: None,
1283 chat_notice: None,
1284 chat_notices: Vec::new(),
1285 hold_notice_cause: None,
1286 passes: Vec::new(),
1287 dispatched_at: None,
1288 recovery_budget: None,
1289 recovery_admission: None,
1290 recovery_generations: Vec::new(),
1291 created_at: now,
1292 updated_at: now,
1293 }
1294 }
1295
1296 pub(crate) fn reassign_repository(&mut self, repo: PathBuf, actor: &str) {
1298 self.stamp_schema();
1299 if matches!(self.status, TaskStatus::Failed | TaskStatus::Parked) {
1300 self.hold_manual(Some(
1301 "Repository reassigned; inspect history and release to start fresh.".into(),
1302 ));
1303 }
1304 let at = Timestamp::now();
1305 self.reassignments.push(Reassignment {
1306 from: self.repo.clone(),
1307 to: repo.clone(),
1308 actor: actor.to_owned(),
1309 at,
1310 run_boundary: self.runs.len(),
1311 });
1312 self.repo = repo;
1313 self.review_branch = None;
1314 self.review_instruction = None;
1315 self.pr_recovery = None;
1316 self.replacement = None;
1317 self.interrupt = false;
1318 self.resume_override = None;
1319 self.fresh_start = true;
1320 self.operator_decided_at = Some(at);
1321 }
1322
1323 pub fn publication_branch(&self) -> String {
1325 crate::run::task_pr_branch_name(&self.id, self.reassignments.len())
1326 }
1327
1328 pub fn execution_runs(&self) -> &[String] {
1330 let boundary = self.reassignments.last().map_or(0, |r| r.run_boundary);
1331 self.runs.get(boundary..).unwrap_or_default()
1332 }
1333
1334 pub fn execution_run(&self, run: &str) -> bool {
1336 self.execution_runs().iter().any(|id| id == run)
1337 }
1338
1339 pub(crate) fn assignment_accepts(&self, run: &crate::run::RunState) -> bool {
1341 self.reassignments.last().is_none_or(|boundary| {
1342 self.execution_run(&run.id)
1343 && run.task_assignment == self.reassignments.len()
1344 && run.created_at > boundary.at
1345 && run
1346 .repo
1347 .canonicalize()
1348 .ok()
1349 .zip(self.repo.canonicalize().ok())
1350 .is_some_and(|(run_repo, task_repo)| run_repo == task_repo)
1351 })
1352 }
1353
1354 pub(crate) fn stale_question(&self, q: &crate::ask::Question) -> bool {
1356 self.reassignments
1357 .last()
1358 .is_some_and(|r| q.asked_at <= r.at)
1359 || (self.runs.contains(&q.run) && !self.execution_run(&q.run))
1360 }
1361
1362 pub fn chat_talk(&self) -> Option<&str> {
1364 if let Some(id) = &self.origin_chat {
1365 return Some(id);
1366 }
1367 match &self.source {
1368 Source::Agent { run, node } if node == CHAT_NODE => Some(run),
1369 _ => None,
1370 }
1371 }
1372
1373 pub fn filed_by_chat(&self) -> Option<&str> {
1377 match &self.source {
1378 Source::Agent { run, node } if node == CHAT_NODE => Some(run),
1379 _ => None,
1380 }
1381 }
1382
1383 pub fn chat_notice_key(&self) -> Option<String> {
1386 match self.status {
1387 TaskStatus::Done => Some(
1388 self.completion_history
1389 .iter()
1390 .rev()
1391 .find(|event| event.action == CompletionAction::Complete)
1392 .map_or_else(
1393 || "done".to_owned(),
1394 |event| format!("done:{}", event.occurrence),
1395 ),
1396 ),
1397 TaskStatus::Held => {
1398 let cause = self
1399 .hold_notice_cause
1400 .clone()
1401 .unwrap_or_else(|| self.unresolved_hold_cause());
1402 Some(format!(
1403 "cause:{}",
1404 serde_json::to_string(&cause).expect("cause")
1405 ))
1406 }
1407 TaskStatus::Blocked => {
1408 let ids: std::collections::BTreeSet<_> = self.blocked_by.iter().collect();
1409 let evidence = self
1412 .hold_notice_cause
1413 .as_ref()
1414 .filter(|c| c.stage.starts_with("conductor-evidence:"));
1415 Some(format!(
1416 "dependencies:{}",
1417 serde_json::to_string(&(ids, evidence)).expect("ids")
1418 ))
1419 }
1420 _ => None,
1421 }
1422 }
1423
1424 fn unresolved_hold_cause(&self) -> NoticeCause {
1425 NoticeCause {
1426 stage: "hold".into(),
1427 target: None,
1428 run: self.runs.last().cloned(),
1429 pass: None,
1430 }
1431 }
1432
1433 pub(crate) fn legacy_chat_notice_key(&self) -> Option<String> {
1435 let key = match self.status {
1436 TaskStatus::Held if self.hold_notice_cause.is_none() => Some(format!(
1437 "held#{}",
1438 self.held_at.map(|t| t.to_string()).unwrap_or_default()
1439 )),
1440 TaskStatus::Blocked => Some(format!(
1441 "blocked#{}#{}",
1442 self.blocked_by.join(","),
1443 self.block_reason.as_deref().unwrap_or_default()
1444 )),
1445 _ => None,
1446 };
1447 key.filter(|key| self.legacy_notice_matches(key))
1448 }
1449
1450 pub(crate) fn legacy_notice_matches(&self, key: &str) -> bool {
1451 match self.status {
1452 TaskStatus::Held if self.hold_notice_cause.is_none() => key
1453 .strip_prefix("held#")
1454 .is_some_and(|time| time.is_empty() || time.parse::<Timestamp>().is_ok()),
1455 TaskStatus::Blocked
1456 if self
1457 .hold_notice_cause
1458 .as_ref()
1459 .is_none_or(|c| !c.stage.starts_with("conductor-evidence:")) =>
1460 {
1461 key.strip_prefix("blocked#").is_some_and(|tail| {
1462 let Some((ids, _)) = tail.split_once('#') else {
1463 return false;
1464 };
1465 let old: std::collections::BTreeSet<_> =
1466 ids.split(',').filter(|id| !id.is_empty()).collect();
1467 let current: std::collections::BTreeSet<_> =
1468 self.blocked_by.iter().map(String::as_str).collect();
1469 old == current
1470 })
1471 }
1472 _ => false,
1473 }
1474 }
1475
1476 fn import_chat_notice(&mut self) {
1477 if let Some(n) = &self.chat_notice {
1478 let key = if is_done_notice_key(&n.key) {
1479 "done".to_owned()
1480 } else if self.legacy_notice_matches(&n.key) {
1481 self.chat_notice_key().unwrap_or_else(|| n.key.clone())
1482 } else {
1483 n.key.clone()
1484 };
1485 if !self.chat_notices.contains(&key) {
1486 self.chat_notices.push(key);
1487 }
1488 }
1489 }
1490
1491 pub(crate) fn notice_cause(&mut self, stage: &str, run: Option<&str>, pass: Option<usize>) {
1494 self.import_chat_notice();
1495 self.hold_notice_cause = Some(NoticeCause {
1496 stage: stage.to_owned(),
1497 target: None,
1498 run: run.map(str::to_owned),
1499 pass,
1500 });
1501 }
1502
1503 pub(crate) fn startup_notice_cause(&mut self, stage: &str) {
1506 let recovery_only = matches!(
1507 stage,
1508 "startup-source" | "startup-candidates" | "startup-public-head"
1509 );
1510 match self.hold_notice_cause.as_ref() {
1511 Some(cause) if recovery_only && !cause.stage.starts_with("startup-") => return,
1512 None if recovery_only
1513 && self
1514 .chat_notice
1515 .as_ref()
1516 .is_some_and(|n| !is_done_notice_key(&n.key)) =>
1517 {
1518 return;
1519 }
1520 _ => {}
1521 }
1522 self.notice_cause(stage, None, None);
1523 }
1524
1525 pub(crate) fn fail_startup(
1528 &mut self,
1529 stage: &str,
1530 why: impl Into<String>,
1531 max_attempts: usize,
1532 ) {
1533 let unresolved = self.hold_notice_cause.clone();
1534 self.fail(why, max_attempts);
1535 self.hold_notice_cause = unresolved;
1536 self.startup_notice_cause(stage);
1537 }
1538
1539 pub(crate) fn fail_startup_target(
1541 &mut self,
1542 stage: &str,
1543 target: String,
1544 why: impl Into<String>,
1545 max_attempts: usize,
1546 ) {
1547 self.fail_startup(stage, why, max_attempts);
1548 if let Some(cause) = self.hold_notice_cause.as_mut() {
1549 cause.target = Some(target);
1550 }
1551 }
1552
1553 pub fn chat_notice_due(&self) -> Option<String> {
1555 self.filed_by_chat()?;
1556 if self.schema < 13 {
1557 return None;
1558 }
1559 let key = self.chat_notice_key()?;
1560 if self.chat_notices.contains(&key) {
1561 return None;
1562 }
1563 match &self.chat_notice {
1564 Some(n)
1565 if n.key == key
1566 || (key == "done" && is_done_notice_key(&n.key))
1567 || self.legacy_notice_matches(&n.key) =>
1568 {
1569 None
1570 }
1571 _ => Some(key),
1572 }
1573 }
1574
1575 pub fn short(&self) -> &str {
1577 short(&self.id)
1578 }
1579
1580 pub fn mark_triage_applied(&mut self, question_id: &str) {
1582 if !self.triage_applied(question_id) {
1583 self.triage_applied.push(question_id.to_owned());
1584 }
1585 }
1586
1587 pub fn action_applied(&self, question_id: &str) -> bool {
1590 self.actions_applied.iter().any(|id| id == question_id)
1591 }
1592
1593 pub fn mark_action_applied(&mut self, question_id: &str) {
1595 if !self.action_applied(question_id) {
1596 self.actions_applied.push(question_id.to_owned());
1597 }
1598 }
1599
1600 pub fn triage_applied(&self, question_id: &str) -> bool {
1602 self.triage_applied.iter().any(|id| id == question_id)
1603 }
1604
1605 pub fn start(&mut self, run: String) {
1618 self.stamp_schema();
1619 self.status = TaskStatus::Running;
1620 self.attempts += 1;
1621 self.runs.retain(|id| id != &run);
1622 if let Some(pin) = &self.resume_override
1623 && pin.pinned_run.as_ref() == Some(&run)
1624 && !pin.question_id.is_empty()
1625 {
1626 self.dispatched_resumes
1627 .insert(pin.question_id.clone(), run.clone());
1628 }
1629 self.runs.push(run);
1630 self.last_error = None;
1631 self.park_reason = None;
1632 self.fresh_start = false;
1633 self.interrupt = false;
1634 self.resume_override = None;
1636 self.disk_resume_run = None;
1639 }
1640
1641 pub fn record_startup_failure(&mut self, failure: crate::run::StartupFailure) {
1643 if !self.startup_failures.iter().any(|f| f.run == failure.run) {
1644 self.startup_failures.push(failure);
1645 }
1646 }
1647
1648 pub fn link_run(&mut self, run: &str) -> bool {
1653 if self.runs.iter().any(|r| r == run) {
1654 return false;
1655 }
1656 self.runs.push(run.to_owned());
1657 true
1658 }
1659
1660 pub fn succeed(&mut self, context: CompletionContext) {
1670 if self.status == TaskStatus::Done {
1671 return;
1672 }
1673 self.record_completion(CompletionAction::Complete, context);
1674 self.stamp_schema();
1675 self.status = TaskStatus::Done;
1676 if let Some(pin) = self.resume_override.take()
1677 && !pin.question_id.is_empty()
1678 && let Some(run) = pin.pinned_run
1679 {
1680 self.superseded_resumes.insert(pin.question_id, run);
1683 }
1684 self.sync_only = None;
1685 self.last_error = None;
1686 self.park_reason = None;
1687 self.hold_reason = None;
1688 self.hold_source = None;
1689 self.machine_hold_cause = None;
1690 self.disk_resume_run = None;
1691 self.disk_checked_at = None;
1692 self.diagnostic = None;
1693 self.blocked_by.clear();
1694 self.block_reason = None;
1695 self.blocked_from = None;
1696 }
1697
1698 pub fn already_landed(&mut self, note: impl Into<String>, mut context: CompletionContext) {
1706 let note = note.into();
1707 if context.reason.is_none() {
1708 context.reason = Some(note.clone());
1709 }
1710 self.succeed(context);
1711 self.attempts = self.attempts.saturating_sub(1);
1712 self.last_error = Some(note);
1713 }
1714
1715 fn record_completion(&mut self, action: CompletionAction, context: CompletionContext) {
1716 self.completion_history.push(CompletionEvent {
1717 occurrence: format!(
1718 "{}-{:016x}{:016x}",
1719 Timestamp::now(),
1720 crate::rng::entropy(),
1721 crate::rng::entropy()
1722 ),
1723 action,
1724 actor: context.actor,
1725 reason: context.reason,
1726 discard: context.discard,
1727 prior_status: self.status,
1728 at: Timestamp::now(),
1729 prior_hold_reason: self.hold_reason.clone(),
1730 prior_block_reason: self.block_reason.clone(),
1731 prior_error: self.last_error.clone(),
1732 run: context.run,
1733 unavailable_runs: context.unavailable_runs,
1734 });
1735 self.stamp_schema();
1736 }
1737
1738 pub fn reopen(&mut self, context: CompletionContext) -> Result<()> {
1741 anyhow::ensure!(
1742 self.status == TaskStatus::Done,
1743 "only a done task can be reopened"
1744 );
1745 anyhow::ensure!(
1746 context
1747 .reason
1748 .as_deref()
1749 .is_some_and(|reason| !reason.trim().is_empty()),
1750 "reopen requires a non-empty reason"
1751 );
1752 let reason = context.reason.clone();
1753 self.record_completion(CompletionAction::Reopen, context);
1754 self.hold_manual(reason);
1755 self.resume_override = None;
1756 self.fresh_start = false;
1757 self.last_error = None;
1758 self.diagnostic = None;
1759 Ok(())
1760 }
1761
1762 pub fn superseded_attempts(&self, last_run_succeeded: bool) -> &[String] {
1792 if self.status != TaskStatus::Done || !last_run_succeeded || self.execution_runs().len() < 2
1793 {
1794 return &[];
1795 }
1796 &self.execution_runs()[..self.execution_runs().len() - 1]
1797 }
1798
1799 pub fn successor_of(&self, run: &str) -> Option<&String> {
1807 let runs = self.execution_runs();
1808 let pos = runs.iter().rposition(|r| r == run)?;
1809 runs.get(pos + 1)
1810 }
1811
1812 pub fn earlier_attempts(&self) -> &[String] {
1819 self.execution_runs()
1820 }
1821
1822 fn preserve_legacy_build_cache(&mut self) {
1823 if self.schema < 23 {
1824 let overrides = self.overrides.get_or_insert_with(|| RunOverrides {
1825 inherit_daemon_options: true,
1826 ..RunOverrides::default()
1827 });
1828 overrides.build_cache.get_or_insert(BuildCache::Shared);
1829 }
1830 }
1831
1832 fn stamp_schema(&mut self) {
1837 self.preserve_legacy_build_cache();
1838 if self.schema < RECOVERY_HOLD_SCHEMA && self.recovery_budget_hold.is_none() {
1839 self.recovery_budget_hold = self.legacy_recovery_budget_hold();
1840 }
1841 self.schema = self.schema.max(SCHEMA);
1842 }
1843
1844 fn note_held(&mut self) {
1847 self.stamp_schema();
1848 self.recovery_budget_hold = None;
1849 let continuing = self.status == TaskStatus::Held
1850 || (self.status == TaskStatus::Blocked
1851 && (self.blocked_from == Some(TaskStatus::Held)
1852 || (self.blocked_from.is_none()
1853 && (self.hold_reason.is_some() || self.hold_source.is_some()))));
1854 if !continuing || self.held_at.is_none() {
1855 self.held_at = Some(Timestamp::now());
1856 }
1857 }
1858
1859 pub fn fail(&mut self, why: impl Into<String>, max_attempts: usize) {
1875 let why = why.into();
1876 if self.status == TaskStatus::Running {
1877 let run = self.runs.last().cloned();
1878 self.notice_cause("run-failed", run.as_deref(), Some(self.attempts));
1879 }
1880 self.diagnostic = None;
1881 self.park_reason = None;
1882 self.status = if self.attempts >= self.effective_attempt_limit(max_attempts) {
1883 self.note_held();
1884 self.hold_source = Some(HoldSource::Machine);
1885 self.machine_hold_cause = None;
1886 self.disk_resume_run = None;
1887 self.disk_checked_at = None;
1888 self.hold_reason = Some(why.clone());
1889 TaskStatus::Held
1890 } else {
1891 TaskStatus::Failed
1892 };
1893 self.last_error = Some(why);
1894 }
1895
1896 pub fn stall(&mut self, why: impl Into<String>) {
1906 self.last_error = Some(why.into());
1907 self.diagnostic = None;
1908 self.attempts = self.attempts.saturating_sub(1);
1909 self.status = TaskStatus::Failed;
1910 }
1911
1912 pub fn park(&mut self, why: impl Into<String>) {
1918 self.diagnostic = None;
1919 self.attempts = self.attempts.saturating_sub(1);
1920 self.status = TaskStatus::Parked;
1921 self.park_reason = Some(why.into());
1922 self.stamp_schema();
1925 }
1926
1927 pub fn record_pass(
1929 &mut self,
1930 run: &str,
1931 pass_index: usize,
1932 attempts_before: usize,
1933 parked: Option<crate::run::ParkCause>,
1934 ) {
1935 self.record_pass_at(run, pass_index, None, attempts_before, parked);
1936 }
1937
1938 pub fn record_pass_at(
1941 &mut self,
1942 run: &str,
1943 pass_index: usize,
1944 started_at: Option<Timestamp>,
1945 attempts_before: usize,
1946 parked: Option<crate::run::ParkCause>,
1947 ) {
1948 if self
1949 .passes
1950 .iter()
1951 .any(|p| p.run == run && p.pass_index == pass_index)
1952 {
1953 return;
1954 }
1955 let cost = if self.attempts < attempts_before {
1956 PassCost::Refunded
1957 } else {
1958 PassCost::Spent
1959 };
1960 self.passes.push(TaskPass {
1961 run: run.to_owned(),
1962 pass_index,
1963 started_at: self.dispatched_at.or(started_at),
1964 cost,
1965 attempts_after: self.attempts,
1966 settled_at: Timestamp::now(),
1967 parked,
1968 });
1969 self.stamp_schema();
1970 }
1971
1972 pub(crate) fn upgrade_resume_key(&self) -> Option<(Timestamp, &str)> {
1975 if self.status != TaskStatus::Parked || self.fresh_start {
1976 return None;
1977 }
1978 let pass = self.passes.last()?;
1979 if self.execution_runs().last() != Some(&pass.run)
1980 || !matches!(pass.parked, Some(crate::run::ParkCause::Upgrade { .. }))
1981 {
1982 return None;
1983 }
1984 Some((pass.started_at.unwrap_or(pass.settled_at), &self.id))
1987 }
1988
1989 pub fn operator_held(&self) -> bool {
1995 self.status == TaskStatus::Held && !matches!(self.hold_source, Some(HoldSource::Machine))
1996 }
1997
1998 pub fn hold_manual(&mut self, reason: Option<String>) {
2008 self.operator_decided_at = Some(Timestamp::now());
2010 if self.status != TaskStatus::Running && self.sync_only.take().is_some() {
2011 self.resume_override = None;
2012 }
2013 self.hold_unrequested_retry(reason);
2014 }
2015
2016 pub(crate) fn hold_unrequested_retry(&mut self, reason: Option<String>) {
2019 self.park_reason = None;
2020 self.note_held();
2021 self.status = TaskStatus::Held;
2022 if reason.is_some() {
2023 self.hold_reason = reason;
2024 }
2025 self.hold_source = Some(HoldSource::Manual);
2026 self.machine_hold_cause = None;
2027 self.disk_resume_run = None;
2028 self.disk_checked_at = None;
2029 self.blocked_by.clear();
2030 self.block_reason = None;
2031 self.blocked_from = None;
2032 }
2033
2034 pub(crate) fn hold_after_sync_only(&mut self, reason: String) {
2035 let recovery_hold = self.recovery_budget_hold.take();
2036 self.hold_unrequested_retry(Some(reason));
2037 self.recovery_budget_hold = recovery_hold;
2038 }
2039
2040 pub fn hold_machine(&mut self, reason: Option<String>) {
2045 self.park_reason = None;
2046 self.note_held();
2047 self.status = TaskStatus::Held;
2048 if reason.is_some() {
2049 self.hold_reason = reason;
2050 }
2051 self.hold_source = Some(HoldSource::Machine);
2052 self.machine_hold_cause = None;
2053 self.disk_resume_run = None;
2054 self.disk_checked_at = None;
2055 self.blocked_by.clear();
2056 self.block_reason = None;
2057 self.blocked_from = None;
2058 }
2059
2060 pub(crate) fn mark_disk_capacity(&mut self) {
2062 self.machine_hold_cause = Some(MachineHoldCause::DiskCapacity {
2063 reason: self.hold_reason.clone().unwrap_or_default(),
2064 before_start: false,
2065 });
2066 }
2067
2068 pub(crate) fn mark_startup_disk_capacity(&mut self) {
2069 self.machine_hold_cause = Some(MachineHoldCause::DiskCapacity {
2070 reason: self.hold_reason.clone().unwrap_or_default(),
2071 before_start: true,
2072 });
2073 }
2074
2075 pub(crate) fn disk_wait_run(&self) -> Option<&String> {
2076 if self.has_disk_capacity_cause()
2077 && matches!(
2078 self.machine_hold_cause,
2079 Some(MachineHoldCause::DiskCapacity {
2080 before_start: true,
2081 ..
2082 })
2083 )
2084 {
2085 None
2086 } else {
2087 self.execution_runs().last()
2088 }
2089 }
2090
2091 pub fn has_disk_capacity_cause(&self) -> bool {
2093 matches!(
2094 (&self.machine_hold_cause, self.hold_reason.as_deref()),
2095 (Some(MachineHoldCause::DiskCapacity { reason, .. }), Some(now)) if reason == now
2096 )
2097 }
2098
2099 pub(crate) fn resume_disk_wait(&mut self) {
2101 let retained = self.disk_wait_run().cloned();
2102 self.status = TaskStatus::Queued;
2103 self.held_at = None;
2104 self.hold_source = None;
2105 self.hold_reason = None;
2106 self.machine_hold_cause = None;
2107 self.last_error = None;
2108 self.disk_resume_run = retained;
2109 }
2110
2111 pub fn block(&mut self, blocked_by: Vec<String>, reason: Option<String>) {
2121 self.stamp_schema();
2122 let before: std::collections::BTreeSet<_> = self.blocked_by.iter().collect();
2123 let after: std::collections::BTreeSet<_> = blocked_by.iter().collect();
2124 if self.status != TaskStatus::Blocked || before != after {
2125 self.blocked_at = Some(Timestamp::now());
2126 }
2127 if self.status != TaskStatus::Blocked {
2128 self.blocked_from = Some(self.status);
2129 }
2130 self.status = TaskStatus::Blocked;
2131 self.blocked_by = blocked_by;
2132 self.block_reason = reason;
2133 }
2134
2135 pub fn unblock(&mut self, resolved_id: &str) {
2158 if self.status != TaskStatus::Blocked {
2159 return;
2160 }
2161 self.blocked_by.retain(|id| id != resolved_id);
2162 self.restore_if_unblocked();
2163 }
2164
2165 pub fn dependency_deleted(&mut self, deleted_id: &str) -> bool {
2176 if self.status != TaskStatus::Blocked || !self.blocked_by.iter().any(|b| b == deleted_id) {
2177 return false;
2178 }
2179 self.blocked_by.retain(|id| id != deleted_id);
2180 self.restore_if_unblocked();
2181 true
2182 }
2183
2184 fn restore_if_unblocked(&mut self) {
2188 if self.blocked_by.is_empty() {
2189 self.status = match self.blocked_from {
2190 Some(TaskStatus::Running) => TaskStatus::Queued,
2191 Some(other) => other,
2192 None if self.hold_reason.is_some() || self.hold_source.is_some() => {
2193 TaskStatus::Held
2194 }
2195 None => TaskStatus::Queued,
2196 };
2197 self.block_reason = None;
2198 self.blocked_from = None;
2199 }
2200 }
2201
2202 pub fn record_answer(&mut self, question: String, answer: String) {
2207 self.answers.push(AnsweredQuestion { question, answer });
2208 }
2209
2210 pub fn request_review(&mut self, branch: String) {
2214 self.release();
2215 self.review_branch = Some(branch);
2216 self.review_instruction = Some(self.instruction.clone());
2217 }
2218
2219 pub fn requeue(&mut self) {
2222 self.release();
2223 self.review_branch = None;
2225 self.review_instruction = None;
2226 self.fresh_start = true;
2227 }
2228
2229 pub fn hold_for_handover(&mut self, branch: Option<String>, reason: String) {
2238 if branch.is_some() {
2239 self.review_branch = branch;
2240 self.review_instruction = Some(self.instruction.clone());
2241 }
2242 self.hold_machine(Some(reason));
2243 }
2244
2245 pub fn set_urgent(&mut self, urgent: bool) -> Result<()> {
2247 if !matches!(self.status, TaskStatus::Queued | TaskStatus::Held) {
2248 bail!(
2249 "task {} is {}; urgent can only change while queued or held; \
2250 wait for the active attempt to finish and requeue or hold the task first",
2251 self.short(),
2252 self.status.as_str()
2253 );
2254 }
2255 self.urgent = urgent;
2256 Ok(())
2257 }
2258
2259 pub fn set_priority(&mut self, priority: i32) -> Result<()> {
2268 if self.status == TaskStatus::Running {
2269 bail!(
2270 "task {} is running; its priority cannot be changed until \
2271 this attempt finishes",
2272 self.short()
2273 );
2274 }
2275 self.priority = priority;
2276 Ok(())
2277 }
2278
2279 pub fn set_interrupt(&mut self, interrupt: bool) -> Result<()> {
2294 if interrupt && !self.status.runnable() {
2295 bail!(
2296 "task {} is {}; only a queued or failed task can be marked \
2297 to interrupt",
2298 self.short(),
2299 self.status.as_str()
2300 );
2301 }
2302 self.interrupt = interrupt;
2303 Ok(())
2304 }
2305
2306 pub fn effective_attempt_limit(&self, daemon_limit: usize) -> usize {
2308 self.attempt_limit.map_or(daemon_limit, NonZeroUsize::get)
2309 }
2310
2311 pub fn change_attempt_limit(&mut self, limit: Option<NonZeroUsize>) -> Result<()> {
2314 if !matches!(self.status, TaskStatus::Queued | TaskStatus::Held) {
2315 bail!("only queued or held tasks can change the attempt limit");
2316 }
2317 self.stamp_schema();
2318 self.attempt_limit = limit;
2319 Ok(())
2320 }
2321
2322 pub fn implementers(&self) -> Option<usize> {
2324 if self.solo {
2325 Some(1)
2326 } else {
2327 self.overrides.as_ref().and_then(|o| o.candidates)
2328 }
2329 }
2330
2331 pub fn build_cache_override(
2335 &self,
2336 config: &crate::config::Config,
2337 ) -> Option<(BuildCache, &'static str)> {
2338 self.overrides
2339 .as_ref()
2340 .and_then(|o| o.build_cache)
2341 .map(|mode| (mode, "task-override"))
2342 .or_else(|| {
2343 (self.urgent && crate::build_target::urgent_isolation(config))
2344 .then_some((BuildCache::Isolated, "urgent"))
2345 })
2346 }
2347
2348 pub fn change_build_cache(&mut self, mode: Option<BuildCache>) -> Result<()> {
2351 if !matches!(self.status, TaskStatus::Queued | TaskStatus::Held) {
2352 bail!(
2353 "task {} is {}; only queued or held tasks can change build cache",
2354 self.short(),
2355 self.status.as_str()
2356 );
2357 }
2358 self.stamp_schema();
2359 if self.overrides.is_some() || mode.is_some() {
2360 let overrides = self.overrides.get_or_insert_with(|| RunOverrides {
2361 inherit_daemon_options: true,
2362 ..RunOverrides::default()
2363 });
2364 overrides.build_cache = mode;
2365 }
2366 Ok(())
2367 }
2368
2369 pub fn change_implementers(&mut self, count: u8) -> Result<()> {
2372 self.check_implementers_editable()?;
2373 let explicit = self.overrides.as_ref().and_then(|o| o.config.as_deref());
2374 let (mut config, _) = crate::config::Config::discover(&self.repo, explicit)?;
2375 if let Some(o) = &self.overrides {
2376 o.apply(&mut config);
2377 }
2378 self.set_implementers(count, &config)
2379 }
2380
2381 fn check_implementers_editable(&self) -> Result<()> {
2382 if !matches!(self.status, TaskStatus::Queued | TaskStatus::Held) {
2383 bail!(
2384 "task {} is {}; only queued or held tasks can change implementers",
2385 self.short(),
2386 self.status.as_str()
2387 );
2388 }
2389 Ok(())
2390 }
2391
2392 pub fn set_implementers(&mut self, count: u8, config: &crate::config::Config) -> Result<()> {
2394 self.check_implementers_editable()?;
2395 crate::talk::check_implementers(count, config).map_err(anyhow::Error::msg)?;
2396 self.stamp_schema();
2397 self.solo = count == 1;
2398 let mut overrides = self.overrides.clone().unwrap_or_else(|| RunOverrides {
2399 inherit_daemon_options: true,
2400 ..Default::default()
2401 });
2402 overrides.candidates = (count > 1).then_some(usize::from(count));
2403 let mut settings = overrides.clone();
2404 settings.inherit_daemon_options = false;
2405 self.overrides = if overrides.inherit_daemon_options && settings == RunOverrides::default()
2407 {
2408 None
2409 } else {
2410 Some(overrides)
2411 };
2412 Ok(())
2413 }
2414
2415 pub fn edit(&mut self, title: String, instruction: String) -> Result<()> {
2427 if !matches!(self.status, TaskStatus::Queued | TaskStatus::Held) {
2428 bail!(
2429 "task {} is {}; only a queued or held task's instruction can \
2430 be edited",
2431 self.short(),
2432 self.status.as_str()
2433 );
2434 }
2435 if self.review_branch.is_some() && self.review_instruction.is_none() {
2438 self.review_instruction = Some(self.instruction.clone());
2439 }
2440 if self.instruction != instruction {
2441 self.resume_override = None;
2444 }
2445 if self.status == TaskStatus::Held && self.machine_hold_cause.is_some() {
2446 self.hold_manual(self.hold_reason.clone());
2447 }
2448 self.machine_hold_cause = None;
2449 self.disk_resume_run = None;
2450 self.disk_checked_at = None;
2451 self.title = title;
2452 self.instruction = instruction;
2453 Ok(())
2454 }
2455
2456 pub fn handed_off(&mut self, why: impl Into<String>) {
2476 let why = why.into();
2477 self.diagnostic = None;
2478 self.note_held();
2479 self.status = TaskStatus::Held;
2480 self.hold_source = Some(HoldSource::Machine);
2481 self.machine_hold_cause = None;
2482 self.disk_resume_run = None;
2483 self.disk_checked_at = None;
2484 self.hold_reason = Some(why.clone());
2485 self.last_error = Some(why);
2486 }
2487
2488 pub fn release_operator(&mut self, source: &str, question_id: Option<&str>) {
2490 self.recovery_budget = None;
2491 self.recovery_generations.clear();
2492 self.recovery_admission = None;
2493 if self
2494 .resumption
2495 .as_ref()
2496 .is_some_and(|r| r.instruction != self.instruction)
2497 {
2498 self.resume_override = None;
2501 }
2502 let approval = Resumption {
2503 generation: self.resumption.as_ref().map_or(1, |r| r.generation + 1),
2504 source: source.to_owned(),
2505 question_id: question_id.map(str::to_owned),
2506 at: Timestamp::now(),
2507 instruction: self.instruction.clone(),
2508 answers_through: self.answers.len(),
2509 runs_through: self.runs.len(),
2510 blocking_evidence: Vec::new(),
2511 cleared_reason: self
2512 .hold_reason
2513 .clone()
2514 .or_else(|| self.block_reason.clone()),
2515 };
2516 self.release();
2517 self.operator_decided_at = Some(approval.at);
2518 if let Some(previous) = self.resumption.replace(approval) {
2519 self.resumption_history.push(previous);
2520 }
2521 }
2522
2523 pub(crate) fn recovery_failed(&mut self, state: &crate::run::RunState) {
2525 let (base, inputs) = self.recovery_admission.as_ref().map_or_else(
2526 || (state.base_commit.clone(), recovery_inputs(&state.sources)),
2527 |a| (a.base.clone(), a.inputs.clone()),
2528 );
2529 let progress = recovery_progress(state);
2530 let stage = if state.prep_failure.is_some() {
2531 "preparation"
2532 } else {
2533 "execution"
2534 };
2535 let matches = |b: &RecoveryBudget| {
2536 b.instruction == self.instruction
2537 && b.base == base
2538 && b.inputs == inputs
2539 && (progress.is_none() || b.progress == progress)
2540 };
2541 if !self.recovery_budget.as_ref().is_some_and(matches) {
2542 let previous = self
2543 .recovery_generations
2544 .iter()
2545 .position(matches)
2546 .map(|index| self.recovery_generations.remove(index));
2547 if let Some(old) = self.recovery_budget.take() {
2548 self.recovery_generations.push(old);
2549 }
2550 self.recovery_budget = previous;
2551 }
2552 if let Some(budget) = &mut self.recovery_budget {
2553 budget.failures = budget.failures.saturating_add(1);
2554 budget.stage = stage.to_owned();
2555 } else {
2556 self.recovery_budget = Some(RecoveryBudget {
2557 instruction: self.instruction.clone(),
2558 base,
2559 inputs,
2560 stage: stage.to_owned(),
2561 failures: 1,
2562 progress,
2563 });
2564 }
2565 }
2566
2567 pub(crate) fn recovery_exhausted(
2568 &self,
2569 base: &str,
2570 inputs: &str,
2571 limit: usize,
2572 ) -> Option<String> {
2573 let same_input = |b: &&RecoveryBudget| {
2574 b.instruction == self.instruction && b.base == base && b.inputs == inputs
2575 };
2576 let budget = self
2577 .recovery_budget
2578 .as_ref()
2579 .filter(same_input)
2580 .or_else(|| self.recovery_generations.iter().rev().find(same_input))?;
2581 (budget.failures >= limit.max(1)).then(|| budget.budget_reason())
2582 }
2583
2584 pub(crate) fn hold_recovery_budget(&mut self, reason: String, admission: RecoveryAdmission) {
2585 self.hold_unrequested_retry(Some(reason));
2586 if let Some(pass) = self.passes.last()
2587 && self.execution_runs().last() == Some(&pass.run)
2588 {
2589 self.recovery_budget_hold = Some(RecoveryBudgetHold {
2590 admission,
2591 run: pass.run.clone(),
2592 pass: pass.pass_index,
2593 held_at: self.held_at.expect("hold timestamp just recorded"),
2594 decision: self.operator_decided_at,
2595 legacy: false,
2596 });
2597 }
2598 }
2599
2600 fn matches_budget_hold(&self, admission: &RecoveryAdmission) -> bool {
2601 self.status == TaskStatus::Held
2602 && self.hold_source == Some(HoldSource::Manual)
2603 && self.machine_hold_cause.is_none()
2604 && self.recovery_budget.as_ref().is_some_and(|budget| {
2605 budget.instruction == self.instruction
2606 && budget.base == admission.base
2607 && budget.inputs == admission.inputs
2608 && budget.stage == "execution"
2609 && budget.failures > 0
2610 && self
2611 .hold_reason
2612 .as_ref()
2613 .is_some_and(|reason| *reason == budget.budget_reason())
2614 })
2615 }
2616
2617 fn legacy_recovery_budget_hold(&self) -> Option<RecoveryBudgetHold> {
2618 let held_at = self.held_at?;
2619 let settled = self.passes.last()?;
2620 let admission = self.recovery_admission.as_ref()?;
2621 if !self.matches_budget_hold(admission)
2622 || self.execution_runs().last() != Some(&settled.run)
2623 || settled.cost != PassCost::Spent
2624 || settled.parked.is_some()
2625 || settled.settled_at > held_at
2626 || self.operator_decided_at.is_some_and(|at| at >= held_at)
2627 {
2628 return None;
2629 }
2630 Some(RecoveryBudgetHold {
2631 admission: admission.clone(),
2632 run: settled.run.clone(),
2633 pass: settled.pass_index,
2634 held_at,
2635 decision: self.operator_decided_at,
2636 legacy: true,
2637 })
2638 }
2639
2640 pub(crate) fn held_for_recovery_budget(&self, run: &crate::run::RunState) -> bool {
2641 let (Some(held_at), Some(settled), Some(pass), Some(admission)) = (
2642 self.held_at,
2643 self.passes.last(),
2644 run.passes.last(),
2645 self.recovery_admission.as_ref(),
2646 ) else {
2647 return false;
2648 };
2649 if !self.matches_budget_hold(admission)
2650 || self.execution_runs().last() != Some(&run.id)
2651 || settled.run != run.id
2652 || settled.pass_index != pass.index
2653 || settled.cost != PassCost::Spent
2654 || settled.parked.is_some()
2655 || settled.settled_at < pass.started_at
2656 || settled.settled_at > held_at
2657 || self.operator_decided_at.is_some_and(|at| at >= held_at)
2658 || !crate::daemon::compatible_run_instruction(run, self)
2659 {
2660 return false;
2661 }
2662 match &self.recovery_budget_hold {
2663 Some(hold) => {
2664 hold.run == run.id
2665 && hold.pass == pass.index
2666 && hold.held_at == held_at
2667 && hold.decision == self.operator_decided_at
2668 && &hold.admission == admission
2669 && (!hold.legacy
2670 || self
2671 .operator_decided_at
2672 .is_none_or(|at| at < pass.started_at))
2673 }
2674 None => {
2675 self.schema < RECOVERY_HOLD_SCHEMA
2676 && self
2677 .operator_decided_at
2678 .is_none_or(|at| at < pass.started_at)
2679 }
2680 }
2681 }
2682
2683 pub(crate) fn queue_repair(&mut self, receipt: &crate::repair_budget::Receipt) {
2684 self.stamp_schema();
2685 self.repair_grants.push(receipt.clone());
2686 self.status = TaskStatus::Queued;
2687 self.hold_source = None;
2688 self.hold_reason = None;
2689 self.held_at = None;
2690 self.recovery_budget_hold = None;
2691 self.resume_override = Some(OperatorResume {
2692 question_id: String::new(),
2693 at: receipt.at,
2694 conductor_rehold: None,
2695 forced: true,
2696 pinned_run: Some(receipt.request.run.clone()),
2697 });
2698 }
2699
2700 pub fn release(&mut self) {
2704 self.import_chat_notice();
2707 if self.hold_notice_cause.is_none()
2708 && matches!(self.status, TaskStatus::Held | TaskStatus::Blocked)
2709 {
2710 self.hold_notice_cause = Some(self.unresolved_hold_cause());
2711 }
2712 let refused_handover = self.status == TaskStatus::Held
2713 && self.hold_source == Some(HoldSource::Machine)
2714 && self.review_branch.is_some()
2715 && self
2716 .review_instruction
2717 .as_ref()
2718 .is_none_or(|i| *i == self.instruction);
2719 self.status = TaskStatus::Queued;
2720 self.held_at = None;
2721 self.attempts = 0;
2722 self.last_error = None;
2723 self.park_reason = None;
2724 self.hold_reason = None;
2727 self.hold_source = None;
2728 self.machine_hold_cause = None;
2729 self.disk_resume_run = None;
2730 self.disk_checked_at = None;
2731 self.diagnostic = None;
2732 self.blocked_by.clear();
2737 self.block_reason = None;
2738 self.blocked_from = None;
2739 if !refused_handover {
2743 self.review_branch = None;
2744 self.review_instruction = None;
2745 }
2746 self.fresh_start = false;
2747 }
2748}
2749
2750fn copy_new(dir: &Path, src: &Path, name: &str) -> Result<(String, PathBuf)> {
2754 use std::io::ErrorKind;
2755 let (stem, ext) = match name.rfind('.') {
2756 Some(i) if i > 0 => (&name[..i], &name[i..]),
2757 _ => (name, ""),
2758 };
2759 for n in 1u32.. {
2760 let candidate = if n == 1 {
2761 name.to_owned()
2762 } else {
2763 let suffix = format!("-{n}");
2764 let room = 64usize.saturating_sub(suffix.len() + ext.len());
2765 let stem: String = stem.chars().take(room).collect();
2766 format!("{stem}{suffix}{ext}")
2767 };
2768 if !crate::ask::valid_asset_name(&candidate) {
2769 bail!("no valid attachment name is left for `{name}`");
2770 }
2771 let path = dir.join(&candidate);
2772 match std::fs::OpenOptions::new()
2773 .write(true)
2774 .create_new(true)
2775 .open(&path)
2776 {
2777 Ok(mut out) => {
2778 let copied = std::fs::File::open(src)
2779 .and_then(|mut input| std::io::copy(&mut input, &mut out));
2780 if let Err(e) = copied {
2781 drop(out);
2782 let _ = std::fs::remove_file(&path);
2783 return Err(e).with_context(|| format!("copy {}", src.display()));
2784 }
2785 return Ok((candidate, path));
2786 }
2787 Err(e) if e.kind() == ErrorKind::AlreadyExists => continue,
2788 Err(e) => return Err(e).with_context(|| format!("create {}", path.display())),
2789 }
2790 }
2791 unreachable!("the counter never runs out")
2792}
2793
2794const TASK_LOCK_STALE: std::time::Duration = std::time::Duration::from_secs(10);
2797
2798pub(crate) struct TaskLock {
2801 path: PathBuf,
2802 token: String,
2803}
2804
2805fn owner_token() -> String {
2808 static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
2809 let n = COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2810 let mut r = crate::rng::SplitMix64::new(crate::rng::entropy() ^ n.rotate_left(32));
2811 format!("{}-{:016x}", std::process::id(), r.next_u64())
2812}
2813
2814fn break_marker(path: &Path, token: &str) -> PathBuf {
2817 let mut h: u64 = 0xcbf29ce484222325;
2818 for b in token.bytes() {
2819 h ^= u64::from(b);
2820 h = h.wrapping_mul(0x100000001b3);
2821 }
2822 let mut name = path.as_os_str().to_owned();
2823 name.push(format!(".break-{h:016x}"));
2824 PathBuf::from(name)
2825}
2826
2827fn older_than_stale(path: &Path) -> bool {
2828 std::fs::metadata(path)
2829 .and_then(|m| m.modified())
2830 .ok()
2831 .and_then(|t| t.elapsed().ok())
2832 .is_some_and(|age| age > TASK_LOCK_STALE)
2833}
2834
2835fn writer_may_be_gone(token: &str) -> bool {
2836 let Some(pid) = token
2837 .split_once('-')
2838 .and_then(|(pid, _)| pid.parse::<u32>().ok())
2839 else {
2840 return true;
2843 };
2844 if pid == std::process::id() {
2845 return false;
2846 }
2847 crate::proc::pid_status(pid) == Some(false)
2849}
2850
2851const MAX_MARKER_DEPTH: u8 = 3;
2855
2856fn take_marker(
2862 path: &Path,
2863 token: &str,
2864 depth: u8,
2865 retry: crate::lock_file::Retry,
2866) -> Option<(PathBuf, String)> {
2867 use std::io::Write;
2868 let marker = break_marker(path, token);
2869 for _ in 0..2 {
2870 match retry.create(&marker) {
2871 Ok(mut f) => {
2872 let mine = owner_token();
2873 if f.write_all(mine.as_bytes()).is_err() {
2874 drop(f);
2875 let _ = std::fs::remove_file(&marker);
2876 return None;
2877 }
2878 return Some((marker, mine));
2879 }
2880 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
2881 let judged = std::fs::read_to_string(&marker).ok();
2882 match judged.filter(|_| older_than_stale(&marker)) {
2883 Some(judged) if depth < MAX_MARKER_DEPTH => {
2884 remove_lock_if(&marker, &judged, true, depth + 1, retry)?;
2885 }
2886 _ => return None,
2887 }
2888 }
2889 Err(_) => return None,
2890 }
2891 }
2892 None
2893}
2894
2895fn remove_lock_if(
2900 path: &Path,
2901 token: &str,
2902 require_stale: bool,
2903 depth: u8,
2904 retry: crate::lock_file::Retry,
2905) -> Option<bool> {
2906 let (marker, mine) = take_marker(path, token, depth, retry)?;
2907 let still = std::fs::read_to_string(path).is_ok_and(|c| c == token)
2908 && (!require_stale || older_than_stale(path) && writer_may_be_gone(token));
2909 if still {
2910 let _ = std::fs::remove_file(path);
2911 }
2912 if depth >= MAX_MARKER_DEPTH {
2914 if std::fs::read_to_string(&marker).is_ok_and(|c| c == mine) {
2915 let _ = std::fs::remove_file(&marker);
2916 }
2917 } else {
2918 let _ = remove_lock_if(&marker, &mine, false, depth + 1, retry);
2919 }
2920 Some(still)
2921}
2922
2923#[cfg(test)]
2926fn break_stale(path: &Path, judged: &str) -> bool {
2927 break_stale_with(path, judged, crate::lock_file::Retry::new(None))
2928}
2929
2930fn break_stale_with(path: &Path, judged: &str, retry: crate::lock_file::Retry) -> bool {
2931 remove_lock_if(path, judged, true, 0, retry).unwrap_or(false)
2932}
2933
2934impl Drop for TaskLock {
2935 fn drop(&mut self) {
2936 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2);
2937 let retry = crate::lock_file::Retry::new(Some(deadline));
2938 loop {
2939 match remove_lock_if(&self.path, &self.token, false, 0, retry) {
2940 Some(_) => return,
2941 None if std::time::Instant::now() > deadline => return,
2942 None => std::thread::sleep(std::time::Duration::from_millis(5)),
2943 }
2944 }
2945 }
2946}
2947
2948#[derive(Debug, thiserror::Error)]
2949#[error("task changed during completion decision; reload and inspect it")]
2950pub(crate) struct CompletionSnapshotChanged;
2951
2952#[derive(Debug, Clone)]
2954pub struct Queue {
2955 root: PathBuf,
2956 ids: IdSource,
2957}
2958
2959fn validate_attachments(sources: &[PathBuf]) -> Result<Vec<(&PathBuf, &str)>> {
2960 let mut wanted = Vec::new();
2961 for src in sources {
2962 let name = src
2963 .file_name()
2964 .and_then(|n| n.to_str())
2965 .with_context(|| format!("`{}` has no usable file name", src.display()))?;
2966 if !crate::ask::valid_asset_name(name) {
2967 bail!(
2968 "attachment name `{name}` must match ^[A-Za-z0-9][A-Za-z0-9._-]{{0,63}}$ \
2969 with no `..`; rename the file and try again"
2970 );
2971 }
2972 if !src.is_file() {
2973 bail!("attachment `{}` is not a file", src.display());
2974 }
2975 wanted.push((src, name));
2976 }
2977 Ok(wanted)
2978}
2979
2980impl Queue {
2981 pub fn open() -> Self {
2983 Self::at(crate::run::home().join("queue"))
2984 }
2985
2986 pub fn at(root: PathBuf) -> Self {
2989 Self {
2990 root,
2991 ids: IdSource::new(new_id),
2992 }
2993 }
2994
2995 #[doc(hidden)]
2998 pub fn with_id_source(mut self, f: impl Fn() -> String + Send + Sync + 'static) -> Self {
2999 self.ids = IdSource::custom(f);
3000 self
3001 }
3002
3003 fn file_with(
3014 &self,
3015 task: &mut Task,
3016 hook: impl FnMut(&mut Task) -> Result<bool>,
3017 undo: impl FnMut(&mut Task),
3018 ) -> Result<()> {
3019 self.reserve_id(task, hook, undo, true)
3020 }
3021
3022 fn reserve_id(
3030 &self,
3031 task: &mut Task,
3032 mut hook: impl FnMut(&mut Task) -> Result<bool>,
3033 mut undo: impl FnMut(&mut Task),
3034 store: bool,
3035 ) -> Result<()> {
3036 let redraw_first = self.ids.is_custom() && task.attachments.is_empty();
3037 let initial = task.id.clone();
3038 self.ids
3039 .reserve((!redraw_first).then_some(initial.as_str()), "task", |id| {
3040 task.id = id.to_owned();
3041 let _lock = self.lock_task(&task.id)?;
3042 if path_exists(&self.path_of(&task.id))? || !hook(task)? {
3043 return Ok(false);
3044 }
3045 if store {
3046 if let Err(e) = self.write_record(task) {
3047 undo(task);
3048 return Err(e);
3049 }
3050 task.unfiled = false;
3051 }
3052 Ok(true)
3053 })?;
3054 Ok(())
3055 }
3056
3057 fn id_in_use(&self, id: &str, check_attachments: bool) -> Result<bool> {
3062 if path_exists(&self.lock_path(id))? {
3063 return Ok(true);
3064 }
3065 Ok(check_attachments && path_exists(&self.attachments_dir(id))?)
3066 }
3067
3068 fn plain_filing_hook(&self, task: &Task) -> Result<bool> {
3072 Ok(!self.id_in_use(&task.id, task.attachments.is_empty())?)
3073 }
3074
3075 pub fn file_claimed(&self, task: &mut Task) -> Result<Claim> {
3078 let mut claim = None;
3079 self.file_with(
3080 task,
3081 |t| {
3082 if self.id_in_use(&t.id, true)? {
3083 return Ok(false);
3084 }
3085 claim = Some(self.claim(&t.id)?);
3086 Ok(true)
3087 },
3088 |_| {},
3089 )?;
3090 claim.context("claim missing after filing")
3091 }
3092
3093 pub fn root(&self) -> &Path {
3095 &self.root
3096 }
3097
3098 pub fn path_of(&self, id: &str) -> PathBuf {
3100 self.root.join(format!("{id}.json"))
3101 }
3102
3103 pub fn attachments_dir(&self, id: &str) -> PathBuf {
3106 self.root.join(format!("{id}.attachments"))
3107 }
3108
3109 pub fn attach(&self, task: &mut Task, sources: &[PathBuf]) -> Result<Vec<String>> {
3120 let wanted = validate_attachments(sources)?;
3121 if task.unfiled && task.attachments.is_empty() {
3122 let names = std::cell::RefCell::new(Vec::new());
3125 self.reserve_id(
3126 task,
3127 |t| {
3128 if self.id_in_use(&t.id, true)? {
3129 return Ok(false);
3130 }
3131 *names.borrow_mut() = self.copy_attachments(t, &wanted)?;
3132 Ok(true)
3133 },
3134 |_| {},
3135 false,
3136 )?;
3137 return Ok(names.into_inner());
3138 }
3139 self.copy_attachments(task, &wanted)
3140 }
3141
3142 fn copy_attachments(
3144 &self,
3145 task: &mut Task,
3146 wanted: &[(&PathBuf, &str)],
3147 ) -> Result<Vec<String>> {
3148 let dir = self.attachments_dir(&task.id);
3149 let existed = dir.is_dir();
3150 std::fs::create_dir_all(&dir).with_context(|| format!("create {}", dir.display()))?;
3151 let mut created: Vec<PathBuf> = Vec::new();
3152 let mut names = Vec::new();
3153 let mut copy_all = || -> Result<()> {
3154 for (src, name) in wanted {
3155 let (stored, path) = copy_new(&dir, src, name)?;
3156 created.push(path);
3157 names.push(stored);
3158 }
3159 Ok(())
3160 };
3161 if let Err(e) = copy_all() {
3162 for path in &created {
3163 let _ = std::fs::remove_file(path);
3164 }
3165 if !existed {
3166 let _ = std::fs::remove_dir(&dir);
3167 }
3168 return Err(e);
3169 }
3170 task.attachments.extend(names.iter().cloned());
3171 Ok(names)
3172 }
3173
3174 pub fn attach_and_put(&self, task: &mut Task, sources: &[PathBuf]) -> Result<Vec<String>> {
3185 if task.unfiled && task.attachments.is_empty() {
3186 return self.attach_and_file(task, sources);
3187 }
3188 let dir = self.attachments_dir(&task.id);
3189 let existed = dir.is_dir();
3190 let before = task.attachments.len();
3191 let names = self.attach(task, sources)?;
3192 if let Err(e) = self.put(task) {
3193 for name in &names {
3194 let _ = std::fs::remove_file(dir.join(name));
3195 }
3196 if !existed {
3197 let _ = std::fs::remove_dir(&dir);
3198 }
3199 task.attachments.truncate(before);
3200 return Err(e);
3201 }
3202 Ok(names)
3203 }
3204
3205 fn attach_and_file(&self, task: &mut Task, sources: &[PathBuf]) -> Result<Vec<String>> {
3209 let wanted = validate_attachments(sources)?;
3210 let before = task.attachments.len();
3211 let names = std::cell::RefCell::new(Vec::new());
3212 let result = self.file_with(
3213 task,
3214 |t| {
3215 if self.id_in_use(&t.id, true)? {
3216 return Ok(false);
3217 }
3218 *names.borrow_mut() = self.copy_attachments(t, &wanted)?;
3219 Ok(true)
3220 },
3221 |t| {
3222 let dir = self.attachments_dir(&t.id);
3223 for name in names.borrow().iter() {
3224 let _ = std::fs::remove_file(dir.join(name));
3225 }
3226 let _ = std::fs::remove_dir(&dir);
3228 t.attachments.truncate(before);
3229 },
3230 );
3231 result.map(|()| names.into_inner())
3232 }
3233
3234 pub fn attachment_paths(&self, task: &Task) -> Vec<PathBuf> {
3238 let dir = self.attachments_dir(&task.id);
3239 task.attachments
3240 .iter()
3241 .map(|n| {
3242 let p = dir.join(n);
3243 std::path::absolute(&p).unwrap_or(p)
3244 })
3245 .collect()
3246 }
3247
3248 pub fn put(&self, task: &mut Task) -> Result<()> {
3257 if task.unfiled {
3258 return self.file_with(task, |t| self.plain_filing_hook(t), |_| {});
3260 }
3261 let _lock = self.lock_task(&task.id)?;
3262 self.put_unlocked(task)
3263 }
3264
3265 pub fn create_new(&self, task: &mut Task) -> Result<bool> {
3270 let _lock = self.lock_task(&task.id)?;
3271 if path_exists(&self.path_of(&task.id))? {
3272 return Ok(false);
3273 }
3274 self.write_record(task)?;
3275 task.unfiled = false;
3276 Ok(true)
3277 }
3278
3279 fn put_unlocked(&self, task: &mut Task) -> Result<()> {
3281 self.merge_stored(task);
3282 if let Some(boundary) = task.reassignments.last() {
3283 let stored = self.get(&task.id)?;
3284 anyhow::ensure!(
3285 task.reassignments == stored.reassignments
3286 && task.repo == stored.repo
3287 && task.runs.get(..boundary.run_boundary)
3288 == stored.runs.get(..boundary.run_boundary),
3289 "historical repository execution cannot be restarted; reload the task"
3290 );
3291 }
3292 self.write_record(task)
3293 }
3294
3295 pub(crate) fn commit_base_recovery(
3297 &self,
3298 task: &mut Task,
3299 expected: &serde_json::Value,
3300 ) -> Result<()> {
3301 let _lock = self.lock_task(&task.id)?;
3302 anyhow::ensure!(
3303 serde_json::to_value(self.get(&task.id)?)? == *expected,
3304 "task changed during base recovery; inspect the pending authorization"
3305 );
3306 self.put_unlocked(task)
3308 }
3309
3310 pub(crate) fn commit_repair_grant(
3311 &self,
3312 task: &mut Task,
3313 expected: &serde_json::Value,
3314 ) -> Result<()> {
3315 let _lock = self.lock_task(&task.id)?;
3316 anyhow::ensure!(
3317 serde_json::to_value(self.get(&task.id)?)? == *expected,
3318 "repair grant refused: task changed during admission"
3319 );
3320 self.write_record(task)
3321 .context(crate::repair_budget::PublicationUnknown)
3322 }
3323
3324 pub(crate) fn commit_disk_wait(&self, task: &mut Task, expected: &Task) -> Result<()> {
3326 let _lock = self.lock_task(&task.id)?;
3327 anyhow::ensure!(
3328 serde_json::to_value(self.get(&task.id)?)? == serde_json::to_value(expected)?,
3329 "task changed during disk monitoring"
3330 );
3331 task.stamp_schema();
3332 self.write_record_inner(task, false)
3333 }
3334
3335 pub(crate) fn commit_reassignment(&self, task: &mut Task, expected: &Task) -> Result<()> {
3337 let _lock = self.lock_task(&task.id)?;
3338 let stored = self.get(&task.id)?;
3339 anyhow::ensure!(
3340 serde_json::to_value(&stored)? == serde_json::to_value(expected)?
3341 && stored.reassignments.len() + 1 == task.reassignments.len()
3342 && stored.repo == task.reassignments.last().expect("new boundary").from
3343 && stored.runs == task.runs,
3344 "task changed during reassignment; retry after inspecting it"
3345 );
3346 self.write_record(task)
3347 }
3348
3349 pub(crate) fn commit_completion(&self, task: &mut Task, expected: &Task) -> Result<()> {
3351 let _lock = self.lock_task(&task.id)?;
3352 anyhow::ensure!(
3353 serde_json::to_value(self.get(&task.id)?)? == serde_json::to_value(expected)?,
3354 CompletionSnapshotChanged
3355 );
3356 self.write_record(task)
3357 }
3358
3359 fn merge_stored(&self, task: &mut Task) {
3361 if let Ok(mut stored) = read_path(&self.path_of(&task.id)) {
3362 stored.import_chat_notice();
3363 let local_decision = task.completion_history.iter().any(|event| {
3366 !stored
3367 .completion_history
3368 .iter()
3369 .any(|saved| saved.occurrence == event.occurrence)
3370 && event.at > stored.updated_at
3371 });
3372 let unseen_decision = stored.completion_history.iter().any(|event| {
3373 !task
3374 .completion_history
3375 .iter()
3376 .any(|mine| mine.occurrence == event.occurrence)
3377 });
3378 let mut history = std::mem::take(&mut stored.completion_history);
3379 for event in std::mem::take(&mut task.completion_history) {
3380 if !history
3381 .iter()
3382 .any(|stored| stored.occurrence == event.occurrence)
3383 {
3384 history.push(event);
3385 }
3386 }
3387 if unseen_decision {
3388 task.import_chat_notice();
3391 let mut stale = std::mem::replace(task, stored);
3392 append_missing(&mut task.answers, stale.answers);
3393 if task.reassignments == stale.reassignments {
3394 append_missing(&mut task.runs, stale.runs);
3395 }
3396 for (ledger, entries) in [
3397 (&mut task.decision_effects, stale.decision_effects),
3398 (&mut task.superseded_resumes, stale.superseded_resumes),
3399 (&mut task.dispatched_resumes, stale.dispatched_resumes),
3400 ] {
3401 for (key, value) in entries {
3402 ledger.entry(key).or_insert(value);
3403 }
3404 }
3405 append_missing(&mut task.actions_applied, stale.actions_applied);
3406 append_missing(&mut task.triage_applied, stale.triage_applied);
3407 append_missing(&mut task.chat_notices, stale.chat_notices);
3408 append_missing(
3409 &mut task.base_recovery_requests,
3410 stale.base_recovery_requests,
3411 );
3412 prepend_missing_by(&mut task.repair_grants, stale.repair_grants, |a, b| {
3415 a.request.request == b.request.request
3416 });
3417 prepend_missing_by(
3418 &mut task.repair_reconciliations,
3419 stale.repair_reconciliations,
3420 |a, b| a.request.request == b.request.request,
3421 );
3422 stale.resumption_history.extend(stale.resumption);
3425 stale.resumption_history.retain(|approval| {
3426 task.resumption
3427 .as_ref()
3428 .is_none_or(|r| r.at != approval.at || r.generation != approval.generation)
3429 });
3430 prepend_missing_by(
3431 &mut task.resumption_history,
3432 stale.resumption_history,
3433 |a, b| a.at == b.at && a.generation == b.generation,
3434 );
3435 for failure in stale.startup_failures {
3436 task.record_startup_failure(failure);
3437 }
3438 for pass in stale.passes {
3439 if !task.passes.iter().any(|stored| {
3440 stored.run == pass.run && stored.pass_index == pass.pass_index
3441 }) {
3442 task.passes.push(pass);
3443 }
3444 }
3445 task.completion_history = history;
3446 if !task.decision_effects.is_empty() {
3447 task.stamp_schema();
3448 }
3449 return;
3450 }
3451 if stored.reassignments.len() > task.reassignments.len() {
3452 let stale = std::mem::replace(task, stored.clone());
3455 for answer in stale.answers {
3456 if !task.answers.contains(&answer) {
3457 task.answers.push(answer);
3458 }
3459 }
3460 }
3461 if task.updated_at < stored.updated_at
3464 && (task.sync_only != stored.sync_only
3465 || stored.sync_only.is_some()
3466 || stored
3467 .recovery_budget_hold
3468 .as_ref()
3469 .is_some_and(|hold| hold.held_at > task.updated_at)
3470 || stored.repair_grants.last().is_some_and(|grant| {
3471 task.repair_grants.last() != Some(grant)
3472 || stored.operator_decided_at > task.operator_decided_at
3473 || stored
3474 .resume_override
3475 .as_ref()
3476 .is_some_and(|pin| pin.at > task.updated_at)
3477 || (task.resume_override != stored.resume_override
3478 && task
3479 .resume_override
3480 .as_ref()
3481 .is_some_and(|pin| pin.at == grant.at))
3482 }))
3483 && task
3484 .operator_decided_at
3485 .is_none_or(|at| at <= stored.updated_at)
3486 && task
3487 .resume_override
3488 .as_ref()
3489 .is_none_or(|pin| pin.at <= stored.updated_at)
3490 && !local_decision
3491 {
3492 *task = stored.clone();
3493 }
3494 task.completion_history = history;
3495 append_missing(
3496 &mut task.base_recovery_requests,
3497 stored.base_recovery_requests,
3498 );
3499 append_missing(&mut task.actions_applied, stored.actions_applied);
3500 append_missing(&mut task.triage_applied, stored.triage_applied);
3501 for receipt in &stored.repair_grants {
3502 if !task
3503 .repair_grants
3504 .iter()
3505 .any(|r| r.request.request == receipt.request.request)
3506 {
3507 task.repair_grants.push(receipt.clone());
3509 }
3510 }
3511 for receipt in &stored.repair_reconciliations {
3512 if !task.repair_reconciliations.contains(receipt) {
3513 task.repair_reconciliations.push(receipt.clone());
3516 task.resume_override = stored.resume_override.clone();
3517 task.status = stored.status;
3518 task.hold_source = stored.hold_source;
3519 task.machine_hold_cause = stored.machine_hold_cause.clone();
3520 task.disk_resume_run = stored.disk_resume_run.clone();
3521 task.disk_checked_at = stored.disk_checked_at;
3522 task.hold_reason = stored.hold_reason.clone();
3523 task.held_at = stored.held_at;
3524 }
3525 }
3526 task.superseded_resumes.extend(stored.superseded_resumes);
3527 task.dispatched_resumes.extend(stored.dispatched_resumes);
3528 if task.status != TaskStatus::Running
3529 && let Some(pin) = &stored.resume_override
3530 && !pin.question_id.is_empty()
3531 && let Some(run) = &pin.pinned_run
3532 && task.resume_override.as_ref().is_none_or(|next| {
3533 next.question_id != pin.question_id || next.pinned_run != pin.pinned_run
3534 })
3535 {
3536 task.superseded_resumes
3537 .insert(pin.question_id.clone(), run.clone());
3538 }
3539 for (id, receipt) in stored.decision_effects {
3542 task.decision_effects.insert(id, receipt);
3543 }
3544 if !task.decision_effects.is_empty() {
3545 task.stamp_schema();
3546 }
3547 if task.chat.is_none() {
3550 task.chat = stored.chat.clone();
3551 }
3552 append_missing(&mut task.chat_notices, stored.chat_notices);
3553 for failure in stored.startup_failures {
3554 task.record_startup_failure(failure);
3555 }
3556 append_missing(&mut task.runs, stored.runs);
3557 for p in stored.passes {
3558 if !task
3559 .passes
3560 .iter()
3561 .any(|q| q.run == p.run && q.pass_index == p.pass_index)
3562 {
3563 task.passes.push(p);
3564 }
3565 }
3566 if let Some(n) = stored.chat_notice
3569 && task.chat_notice.as_ref().is_none_or(|mine| mine.at < n.at)
3570 {
3571 task.chat_notice = Some(n);
3572 }
3573 }
3574 }
3575
3576 pub(crate) fn write_startup_history(&self, task: &Task) -> Result<()> {
3579 let path = self.path_of(&task.id);
3580 let tmp = path.with_extension("json.tmp");
3581 std::fs::write(&tmp, serde_json::to_vec_pretty(task)?)?;
3582 std::fs::rename(tmp, path)?;
3583 Ok(())
3584 }
3585
3586 fn write_record(&self, task: &mut Task) -> Result<()> {
3588 self.write_record_inner(task, true)
3589 }
3590
3591 fn write_record_inner(&self, task: &mut Task, notify: bool) -> Result<()> {
3592 task.import_chat_notice();
3593 if task.status != TaskStatus::Held && task.sync_only.is_none() {
3594 task.recovery_budget_hold = None;
3595 }
3596 task.updated_at = Timestamp::now();
3597 std::fs::create_dir_all(&self.root)
3598 .with_context(|| format!("create {}", self.root.display()))?;
3599 let body = serde_json::to_string_pretty(task).context("serialize task")?;
3600 let path = self.path_of(&task.id);
3601 let tmp = path.with_extension("json.tmp");
3602 std::fs::write(&tmp, &body).with_context(|| format!("write {}", tmp.display()))?;
3603 std::fs::rename(&tmp, &path).with_context(|| format!("replace {}", path.display()))?;
3604 if let (Some(notice), Some(home)) = (
3609 notify.then(|| crate::notices::task_held(task)).flatten(),
3610 self.root.parent().filter(|p| !p.as_os_str().is_empty()),
3611 ) {
3612 crate::notices::raise_in(home, notice);
3613 }
3614 Ok(())
3615 }
3616
3617 pub fn modify(&self, id: &str, f: impl FnOnce(&mut Task) -> bool) -> Result<bool> {
3622 let id = self.resolve_id(id)?;
3623 let _lock = self.lock_task(&id)?;
3624 let mut task = self.get(&id)?;
3625 if !f(&mut task) {
3626 return Ok(false);
3627 }
3628 self.put_unlocked(&mut task)?;
3629 Ok(true)
3630 }
3631
3632 pub fn link_run(&self, id: &str, run: &str) -> Result<Task> {
3637 let id = self.resolve_id(id)?;
3638 let _lock = self.lock_task(&id)?;
3641 let mut task = self.get(&id)?;
3642 if task.link_run(run) {
3643 self.put_unlocked(&mut task)?;
3644 }
3645 Ok(task)
3646 }
3647
3648 pub(crate) fn lock_task(&self, id: &str) -> Result<TaskLock> {
3656 std::fs::create_dir_all(&self.root)
3657 .with_context(|| format!("create {}", self.root.display()))?;
3658 let path = self.root.join(format!("{id}.write-lock"));
3659 let started = std::time::Instant::now();
3660 let retry = crate::lock_file::Retry::task_write(started + TASK_LOCK_STALE);
3661 let marker_retry = crate::lock_file::Retry::new(Some(started + TASK_LOCK_STALE));
3662 loop {
3663 match retry.create(&path) {
3664 Ok(mut file) => {
3665 use std::io::Write;
3666 let token = owner_token();
3667 if let Err(e) = file.write_all(token.as_bytes()) {
3668 drop(file);
3669 let _ = std::fs::remove_file(&path);
3670 return Err(e).with_context(|| format!("lock {}", path.display()));
3671 }
3672 return Ok(TaskLock { path, token });
3673 }
3674 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
3675 let judged = std::fs::read_to_string(&path).ok();
3678 let broken = judged
3679 .filter(|_| older_than_stale(&path))
3680 .is_some_and(|judged| break_stale_with(&path, &judged, marker_retry));
3681 if !broken {
3685 if started.elapsed() > TASK_LOCK_STALE {
3686 bail!("could not lock task {id}");
3687 }
3688 std::thread::sleep(std::time::Duration::from_millis(15));
3689 }
3690 }
3691 Err(e) => return Err(e).with_context(|| format!("lock {}", path.display())),
3692 }
3693 }
3694 }
3695
3696 pub fn get(&self, id: &str) -> Result<Task> {
3698 let resolved = self.resolve_id(id)?;
3699 read_path(&self.path_of(&resolved))
3700 }
3701
3702 pub fn remove(&self, id: &str, in_flight: bool, questions: &Questions) -> Result<Removal> {
3734 self.remove_with_receipt(id, in_flight, questions, None)
3735 }
3736
3737 pub(crate) fn discard_triage(
3739 &self,
3740 id: &str,
3741 questions: &Questions,
3742 inquiry: &str,
3743 ) -> Result<Removal> {
3744 self.remove_with_receipt(id, false, questions, Some(inquiry))
3745 }
3746
3747 pub(crate) fn triage_discard_applied(&self, id: &str, inquiry: &str) -> Result<bool> {
3748 let path = self
3749 .root
3750 .join("triage-discard")
3751 .join(format!("{inquiry}.json"));
3752 let bytes = match std::fs::read(path) {
3753 Ok(bytes) => bytes,
3754 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(false),
3755 Err(e) => return Err(e.into()),
3756 };
3757 let receipt: Task = serde_json::from_slice(&bytes)?;
3758 Ok(receipt.id == id && !self.path_of(id).exists())
3759 }
3760
3761 fn remove_with_receipt(
3762 &self,
3763 id: &str,
3764 in_flight: bool,
3765 questions: &Questions,
3766 inquiry: Option<&str>,
3767 ) -> Result<Removal> {
3768 let resolved = self.resolve_id(id)?;
3769 if in_flight {
3770 bail!("task {resolved} is being run by a live daemon right now");
3771 }
3772 let receipt = inquiry.map(|q| self.root.join("triage-discard").join(format!("{q}.json")));
3773 if let Some(path) = &receipt {
3774 std::fs::create_dir_all(path.parent().expect("receipt directory"))?;
3775 }
3776 self.write_tombstone(&resolved)?;
3777 if let Err(e) = self.remove_record_with_attachments(&resolved, |p| match &receipt {
3778 Some(path) => std::fs::rename(p, path),
3779 None => std::fs::remove_file(p),
3780 }) {
3781 if self.path_of(&resolved).exists() {
3785 let _ = std::fs::remove_file(self.tombstone_path(&resolved));
3786 }
3787 return Err(e);
3788 }
3789 let (released, still_blocked) = self.release_dependents_of(&resolved, questions);
3790 Ok(Removal {
3791 id: resolved,
3792 released,
3793 still_blocked,
3794 })
3795 }
3796
3797 fn tombstone_path(&self, id: &str) -> PathBuf {
3800 self.root.join(format!("{id}.removed"))
3801 }
3802
3803 fn write_tombstone(&self, id: &str) -> Result<()> {
3804 let path = self.tombstone_path(id);
3805 let tmp = self.root.join(format!("{id}.removed.tmp"));
3806 std::fs::write(&tmp, b"")
3807 .and_then(|()| std::fs::rename(&tmp, &path))
3808 .with_context(|| format!("write {}", path.display()))
3809 }
3810
3811 fn was_deleted(&self, id: &str) -> bool {
3815 self.tombstone_path(id).is_file() && !self.path_of(id).exists()
3816 }
3817
3818 pub fn apply_deleted_blockers(&self, task: &mut Task, questions: &Questions) -> Vec<String> {
3822 let deleted = deleted_blockers(self, questions, &task.blocked_by);
3823 deleted
3824 .into_iter()
3825 .filter(|id| task.dependency_deleted(id))
3826 .collect()
3827 }
3828
3829 pub fn note_dependency_deleted(&self, dependent: &Task, deleted: &str) {
3833 let Some(home) = self.root.parent().filter(|p| !p.as_os_str().is_empty()) else {
3834 return;
3835 };
3836 let ja = crate::lang::is_japanese(&crate::lang::of_repo(&dependent.repo));
3837 let waiting = dependent.status == TaskStatus::Blocked;
3838 let message = match (ja, waiting) {
3839 (true, false) => format!(
3840 "タスク {} は、待っていた {} が削除されたため待機を解除し、元の状態に戻しました",
3841 dependent.short(),
3842 short(deleted)
3843 ),
3844 (true, true) => format!(
3845 "タスク {} は、待っていた {} が削除されたため、残りの依存を待っています",
3846 dependent.short(),
3847 short(deleted)
3848 ),
3849 (false, false) => format!(
3850 "Task {} stopped waiting on {} because it was deleted, and returned to its previous state",
3851 dependent.short(),
3852 short(deleted)
3853 ),
3854 (false, true) => format!(
3855 "Task {} stopped waiting on {} because it was deleted, and is still waiting on its other dependencies",
3856 dependent.short(),
3857 short(deleted)
3858 ),
3859 };
3860 crate::notices::raise_in(
3861 home,
3862 crate::notices::Notice::info(
3863 &format!("unblocked:{}:{}", dependent.id, deleted),
3864 message,
3865 )
3866 .link(crate::notices::Link::Task {
3867 id: dependent.id.clone(),
3868 }),
3869 );
3870 }
3871
3872 fn release_dependents_of(
3877 &self,
3878 dependency: &str,
3879 questions: &Questions,
3880 ) -> (Vec<String>, Vec<String>) {
3881 let (mut released, mut still_blocked) = (Vec::new(), Vec::new());
3882 for listed in self.list() {
3883 if listed.status != TaskStatus::Blocked || !listed.blocked_by.iter().any(|b| {
3884 matches!(crate::queue::dependency(self, questions, b), Dependency::Deleted(id) if id == dependency)
3885 }) {
3886 continue;
3887 }
3888 let Ok(_claim) = self.claim(&listed.id) else {
3889 continue;
3890 };
3891 let Ok(mut task) = self.get(&listed.id) else {
3892 continue;
3893 };
3894 let references: Vec<String> = task.blocked_by.iter().filter(|id| {
3895 matches!(crate::queue::dependency(self, questions, id), Dependency::Deleted(full) if full == dependency)
3896 }).cloned().collect();
3897 if references.is_empty() {
3898 continue;
3899 }
3900 for reference in references {
3901 task.dependency_deleted(&reference);
3902 }
3903 if self.put(&mut task).is_err() {
3904 continue;
3905 }
3906 self.note_dependency_deleted(&task, dependency);
3907 if task.status == TaskStatus::Blocked {
3908 still_blocked.push(task.id.clone());
3909 } else {
3910 released.push(task.id.clone());
3911 }
3912 }
3913 (released, still_blocked)
3914 }
3915
3916 fn remove_record_with_attachments(
3920 &self,
3921 resolved: &str,
3922 remove_record: impl FnOnce(&Path) -> std::io::Result<()>,
3923 ) -> Result<()> {
3924 self.sweep_removed_attachments();
3931 let attachments = self.attachments_dir(resolved);
3932 let aside = self.root.join(format!("{resolved}.attachments.removing"));
3933 let moved = match std::fs::rename(&attachments, &aside) {
3934 Ok(()) => true,
3935 Err(e) if e.kind() == std::io::ErrorKind::NotFound => false,
3936 Err(e) => {
3937 return Err(e).with_context(|| format!("remove {}", attachments.display()));
3938 }
3939 };
3940 let path = self.path_of(resolved);
3941 if let Err(e) = remove_record(&path) {
3942 if moved {
3943 let _ = std::fs::rename(&aside, &attachments);
3944 }
3945 return Err(e).with_context(|| format!("remove {}", path.display()));
3946 }
3947 if moved {
3948 if let Err(e) = std::fs::remove_dir_all(&aside) {
3949 tracing::warn!("leftover attachments {}: {e}", aside.display());
3950 }
3951 }
3952 let lock = self.lock_path(resolved);
3953 if let Err(e) = std::fs::remove_file(&lock) {
3954 if e.kind() != std::io::ErrorKind::NotFound {
3955 return Err(e).with_context(|| format!("remove {}", lock.display()));
3956 }
3957 }
3958 Ok(())
3959 }
3960
3961 fn sweep_removed_attachments(&self) {
3967 let Ok(entries) = std::fs::read_dir(&self.root) else {
3968 return;
3969 };
3970 for entry in entries.flatten() {
3971 let name = entry.file_name();
3972 let name = name.to_string_lossy();
3973 let Some(id) = name.strip_suffix(".attachments.removing") else {
3974 continue;
3975 };
3976 if !self.path_of(id).exists() {
3979 if let Err(e) = std::fs::remove_dir_all(entry.path()) {
3980 tracing::warn!("leftover attachments {}: {e}", entry.path().display());
3981 }
3982 }
3983 }
3984 self.sweep_tombstones();
3985 }
3986
3987 fn sweep_tombstones(&self) {
3996 let Ok(entries) = std::fs::read_dir(&self.root) else {
3997 return;
3998 };
3999 let tasks = self.list();
4000 for entry in entries.flatten() {
4001 let name = entry.file_name();
4002 let name = name.to_string_lossy();
4003 let Some(id) = name.strip_suffix(".removed") else {
4004 continue;
4005 };
4006 if self.path_of(id).exists()
4007 || tasks.iter().any(|t| {
4008 t.blocked_by
4009 .iter()
4010 .any(|b| id.starts_with(b) || id.ends_with(b))
4011 })
4012 {
4013 continue;
4014 }
4015 let old = entry
4016 .metadata()
4017 .and_then(|m| m.modified())
4018 .ok()
4019 .and_then(|m| m.elapsed().ok())
4020 .is_some_and(|age| age >= TOMBSTONE_GRACE);
4021 if old {
4022 let _ = std::fs::remove_file(entry.path());
4023 }
4024 }
4025 }
4026
4027 fn lock_path(&self, id: &str) -> PathBuf {
4030 self.root.join(format!("{id}.lock"))
4031 }
4032
4033 pub fn list(&self) -> Vec<Task> {
4046 #[cfg(test)]
4047 LIST_READS.with(|count| count.set(count.get() + 1));
4048 let mut tasks: Vec<Task> = std::fs::read_dir(&self.root)
4049 .into_iter()
4050 .flatten()
4051 .flatten()
4052 .map(|e| e.path())
4053 .filter(|p| p.extension().is_some_and(|x| x == "json"))
4054 .filter_map(|p| read_path(&p).ok())
4055 .collect();
4056 tasks.sort_unstable_by(|a, b| b.priority.cmp(&a.priority).then_with(|| b.id.cmp(&a.id)));
4057 tasks
4058 }
4059
4060 pub fn unreadable(&self) -> Vec<PathBuf> {
4064 std::fs::read_dir(&self.root)
4065 .into_iter()
4066 .flatten()
4067 .flatten()
4068 .map(|e| e.path())
4069 .filter(|p| p.extension().is_some_and(|x| x == "json"))
4070 .filter(|p| read_path(p).is_err())
4071 .collect()
4072 }
4073
4074 pub fn superseded(&self) -> HashMap<String, String> {
4087 let mut by = HashMap::new();
4088 for task in self.list() {
4089 for earlier in &task.runs {
4090 if let Some(later) = task.successor_of(earlier) {
4091 by.insert(earlier.clone(), later.clone());
4092 }
4093 }
4094 }
4095 by
4096 }
4097
4098 pub fn superseded_by(&self, run: &str) -> Option<String> {
4106 for task in self.list() {
4107 if task.runs.iter().any(|r| r == run) {
4108 return task.successor_of(run).cloned();
4109 }
4110 }
4111 None
4112 }
4113
4114 pub fn latest_attempt(&self, run: &str) -> Option<String> {
4125 for task in self.list() {
4126 if task.runs.iter().any(|r| r == run) {
4127 return task.runs.last().filter(|last| **last != run).cloned();
4128 }
4129 }
4130 None
4131 }
4132
4133 pub fn next_runnable(&self) -> Option<Task> {
4138 let mut runnable: Vec<Task> = self
4139 .list()
4140 .into_iter()
4141 .filter(|t| t.status.runnable())
4142 .collect();
4143 runnable.sort_unstable_by(dispatch_order);
4144 runnable.into_iter().next()
4145 }
4146
4147 pub fn claim(&self, id: &str) -> Result<Claim> {
4154 std::fs::create_dir_all(&self.root)
4155 .with_context(|| format!("create {}", self.root.display()))?;
4156 let path = self.lock_path(id);
4157 let retry = crate::lock_file::Retry::new(None);
4158 match retry.create(&path) {
4159 Ok(mut f) => {
4160 use std::io::Write as _;
4161 let _ = writeln!(f, "{}", std::process::id());
4163 Ok(Claim { path })
4164 }
4165 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
4166 bail!("task {id} is already claimed ({} exists)", path.display())
4167 }
4168 Err(e) => Err(e).with_context(|| format!("lock {}", path.display())),
4169 }
4170 }
4171
4172 pub fn resolve_id(&self, prefix: &str) -> Result<String> {
4174 if !prefix.is_empty()
4175 && prefix != "."
4176 && prefix != ".."
4177 && !prefix.contains(['/', '\\'])
4178 && self.path_of(prefix).is_file()
4179 {
4180 return Ok(prefix.to_owned());
4181 }
4182 let ids = record_ids(&self.root, "json")?;
4183 match resolve_reference(prefix, ids.iter().map(String::as_str)) {
4184 Reference::Found(id) => Ok(id),
4185 Reference::Missing => bail!("no task matches `{prefix}`"),
4186 Reference::Ambiguous => bail!("`{prefix}` matches multiple tasks"),
4187 }
4188 }
4189
4190 pub fn revision(&self) -> u64 {
4197 self.revision_excluding(&std::collections::BTreeSet::new())
4198 }
4199
4200 pub fn revision_excluding(&self, skip: &std::collections::BTreeSet<String>) -> u64 {
4203 use std::hash::{Hash as _, Hasher as _};
4204
4205 let mut entries: Vec<(String, u64)> = std::fs::read_dir(&self.root)
4206 .into_iter()
4207 .flatten()
4208 .flatten()
4209 .filter(|e| e.path().extension().is_some_and(|ext| ext == "json"))
4210 .filter(|e| {
4211 let path = e.path();
4212 !path
4213 .file_stem()
4214 .is_some_and(|stem| skip.contains(stem.to_string_lossy().as_ref()))
4215 })
4216 .filter_map(|e| {
4217 let name = e.file_name().to_string_lossy().into_owned();
4218 let mtime = e
4219 .metadata()
4220 .ok()?
4221 .modified()
4222 .ok()?
4223 .duration_since(std::time::UNIX_EPOCH)
4224 .ok()?
4225 .as_millis() as u64;
4226 Some((name, mtime))
4227 })
4228 .collect();
4229
4230 if entries.is_empty() {
4231 return 0;
4232 }
4233
4234 entries.sort_unstable();
4235 let mut hasher = std::hash::DefaultHasher::new();
4236 for (name, mtime) in &entries {
4237 name.hash(&mut hasher);
4238 mtime.hash(&mut hasher);
4239 }
4240 let h = hasher.finish();
4241 if h == 0 { 1 } else { h }
4242 }
4243}
4244
4245const TOMBSTONE_GRACE: std::time::Duration = std::time::Duration::from_secs(3600);
4248
4249#[derive(Debug, Clone)]
4251pub struct Removal {
4252 pub id: String,
4254 pub released: Vec<String>,
4258 pub still_blocked: Vec<String>,
4261}
4262
4263#[derive(Debug)]
4265pub struct Claim {
4266 path: PathBuf,
4267}
4268
4269impl Drop for Claim {
4270 fn drop(&mut self) {
4271 let _ = std::fs::remove_file(&self.path);
4272 }
4273}
4274
4275pub fn title_from(instruction: &str, max: usize) -> String {
4278 let Some(line) = first_line(instruction) else {
4279 return "(empty task)".to_owned();
4280 };
4281 if line.chars().count() <= max {
4282 return line.to_owned();
4283 }
4284 let head: String = line.chars().take(max.saturating_sub(1)).collect();
4285 format!("{head}…")
4286}
4287
4288pub(crate) fn first_line(instruction: &str) -> Option<&str> {
4294 let line = instruction
4295 .lines()
4296 .map(str::trim)
4297 .find(|l| !l.is_empty())?
4298 .trim_start_matches(['#', '-', '*', '>', ' '])
4299 .trim();
4300 (!line.is_empty()).then_some(line)
4301}
4302
4303#[cfg(test)]
4304thread_local! {
4305 pub(crate) static TASK_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4306}
4307
4308fn read_path(path: &Path) -> Result<Task> {
4309 #[cfg(test)]
4310 TASK_READS.with(|count| count.set(count.get() + 1));
4311 let body = std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;
4312 let mut task: Task =
4313 serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))?;
4314 if task.schema > SCHEMA {
4320 bail!(
4321 "task {} was written by a different magi (schema {}, this build \
4322 speaks {SCHEMA})",
4323 task.id,
4324 task.schema
4325 );
4326 }
4327 task.preserve_legacy_build_cache();
4328 if task.schema < 22
4329 && task.status == TaskStatus::Held
4330 && task.hold_source == Some(HoldSource::Machine)
4331 && task.resume_override.is_none()
4332 && task
4333 .hold_reason
4334 .as_deref()
4335 .is_some_and(crate::disk::is_gate_reason)
4336 {
4337 task.mark_disk_capacity();
4338 }
4339 Ok(task)
4340}
4341
4342#[derive(Debug, PartialEq, Eq)]
4345pub(crate) enum Reference {
4346 Found(String),
4347 Missing,
4348 Ambiguous,
4349}
4350
4351pub(crate) fn resolve_reference<'a>(id: &str, ids: impl Iterator<Item = &'a str>) -> Reference {
4352 let mut hits = Vec::new();
4353 for candidate in ids {
4354 if candidate == id {
4355 return Reference::Found(candidate.to_owned());
4356 }
4357 if candidate.starts_with(id) || candidate.ends_with(id) {
4358 hits.push(candidate);
4359 }
4360 }
4361 match hits.as_slice() {
4362 [] => Reference::Missing,
4363 [one] => Reference::Found((*one).to_owned()),
4364 _ => Reference::Ambiguous,
4365 }
4366}
4367
4368pub(crate) fn record_ids(root: &Path, extension: &str) -> Result<Vec<String>> {
4371 let entries = match std::fs::read_dir(root) {
4372 Ok(entries) => entries,
4373 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
4374 Err(e) => return Err(e.into()),
4375 };
4376 let mut ids = Vec::new();
4377 for entry in entries {
4378 let path = entry?.path();
4379 if path.extension().is_some_and(|e| e == extension)
4380 && let Some(id) = path.file_stem().and_then(|s| s.to_str())
4381 {
4382 ids.push(id.to_owned());
4383 }
4384 }
4385 Ok(ids)
4386}
4387
4388#[derive(Debug, PartialEq, Eq)]
4391pub enum Dependency {
4392 Task(String),
4394 Question(String),
4396 Deleted(String),
4398 Missing,
4400 Ambiguous,
4402 Unknown,
4404}
4405
4406pub fn dependency(queue: &Queue, questions: &Questions, id: &str) -> Dependency {
4408 let (Ok(tasks), Ok(qs), Ok(removed)) = (
4409 record_ids(queue.root(), "json"),
4410 record_ids(questions.root(), "json"),
4411 record_ids(queue.root(), "removed"),
4412 ) else {
4413 return Dependency::Unknown;
4414 };
4415 let mut ids = tasks
4418 .iter()
4419 .chain(qs.iter())
4420 .chain(removed.iter())
4421 .cloned()
4422 .collect::<Vec<_>>();
4423 ids.sort();
4424 ids.dedup();
4425 match resolve_reference(id, ids.iter().map(String::as_str)) {
4426 Reference::Found(id) if tasks.contains(&id) => Dependency::Task(id),
4427 Reference::Found(id) if qs.contains(&id) => Dependency::Question(id),
4428 Reference::Found(id) if queue.was_deleted(&id) => Dependency::Deleted(id),
4429 Reference::Found(_) => Dependency::Unknown,
4430 Reference::Missing => Dependency::Missing,
4431 Reference::Ambiguous => Dependency::Ambiguous,
4432 }
4433}
4434
4435pub fn normalize_blockers(queue: &Queue, questions: &Questions, ids: &mut [String]) {
4437 for id in ids {
4438 if let Dependency::Task(full) | Dependency::Question(full) | Dependency::Deleted(full) =
4439 dependency(queue, questions, id)
4440 {
4441 *id = full;
4442 }
4443 }
4444}
4445
4446pub fn dependency_facts(queue: &Queue, questions: &Questions) -> String {
4449 let inventory = crate::blockers::Inventory::load(queue, questions);
4450 let mut text = String::from(
4451 "Current authoritative queue (historical missing-task claims may be stale; unreadable or ambiguous references must keep waiting):\n",
4452 );
4453 match record_ids(queue.root(), "json") {
4454 Ok(ids) => {
4455 for id in ids {
4456 match queue.get(&id) {
4457 Ok(task) => text.push_str(&format!(
4458 "{}: {}; blocked_by={:?}; chain={:?}\n",
4459 task.id,
4460 task.status.as_str(),
4461 task.blocked_by,
4462 inventory.waits_on(&task)
4463 )),
4464 Err(_) => text.push_str(&format!("{id}: exists, state unreadable\n")),
4465 }
4466 }
4467 }
4468 Err(_) => text.push_str("Queue inventory unreadable: existence is unknown.\n"),
4469 }
4470 text
4471}
4472
4473pub fn missing_blockers(
4475 queue: &Queue,
4476 questions: &Questions,
4477 blocked_by: &[String],
4478) -> Vec<String> {
4479 blocked_by
4480 .iter()
4481 .filter(|id| dependency(queue, questions, id) == Dependency::Missing)
4482 .cloned()
4483 .collect()
4484}
4485
4486pub fn deleted_blockers(
4489 queue: &Queue,
4490 questions: &Questions,
4491 blocked_by: &[String],
4492) -> Vec<String> {
4493 blocked_by
4494 .iter()
4495 .filter(|id| matches!(dependency(queue, questions, id), Dependency::Deleted(_)))
4496 .cloned()
4497 .collect()
4498}
4499
4500pub fn missing_blocker_hold_reason(blocked_by: &[String], missing: &[String]) -> String {
4512 missing_blocker_hold_reason_in(blocked_by, missing, "en")
4513}
4514
4515pub fn missing_blocker_hold_reason_in(
4517 blocked_by: &[String],
4518 missing: &[String],
4519 language: &str,
4520) -> String {
4521 if crate::lang::is_japanese(language) {
4522 format!(
4523 "{} を待っていましたが、{} はディスク上に存在しません - `magi task triage` を参照",
4524 blocked_by.join(", "),
4525 missing.join(", "),
4526 )
4527 } else {
4528 format!(
4529 "blocked on {} but {} no longer exist(s) on disk - see `magi task triage`",
4530 blocked_by.join(", "),
4531 missing.join(", "),
4532 )
4533 }
4534}
4535
4536pub fn short(id: &str) -> &str {
4538 id.split('-').next_back().unwrap_or(id)
4539}
4540
4541fn new_id() -> String {
4542 let stamp = jiff::Zoned::now().strftime("%Y%m%d-%H%M%S");
4543 let seed = crate::rng::entropy();
4544 format!("{stamp}-{:04x}", (seed ^ (seed >> 32)) & 0xffff)
4545}
4546
4547#[cfg(test)]
4548mod tests {
4549 #[test]
4550 fn reassignment_clears_repository_bound_execution_selections() {
4551 let mut task = Task::new(
4552 "move".into(),
4553 "evidence".into(),
4554 "old".into(),
4555 Source::Human,
4556 );
4557 task.review_branch = Some("old-review".into());
4558 task.review_instruction = Some("old criteria".into());
4559 task.pr_recovery = Some(crate::pr_recovery::Selection {
4560 url: "https://example.invalid/pull/1".into(),
4561 branch: "old-pr".into(),
4562 head: "head".into(),
4563 source_head: None,
4564 source_run: None,
4565 source_proof: None,
4566 disposition: None,
4567 instruction: "old criteria".into(),
4568 approved_at: Timestamp::now(),
4569 });
4570 task.replacement = Some(crate::merge_decision::Replacement {
4571 question: "owner".into(),
4572 run: "old-run".into(),
4573 pr: "https://example.invalid/pull/1".into(),
4574 agent: "worker".into(),
4575 context: "evidence".into(),
4576 });
4577 task.resume_override = Some(OperatorResume {
4578 question_id: "old-question".into(),
4579 at: Timestamp::now(),
4580 conductor_rehold: None,
4581 forced: true,
4582 pinned_run: Some("old-run".into()),
4583 });
4584 task.interrupt = true;
4585 task.reassign_repository("new".into(), "test");
4586 assert!(task.review_branch.is_none());
4587 assert!(task.review_instruction.is_none());
4588 assert!(task.pr_recovery.is_none());
4589 assert!(task.replacement.is_none());
4590 assert!(task.resume_override.is_none());
4591 assert!(!task.interrupt);
4592 assert!(task.fresh_start);
4593 assert_eq!(task.instruction, "evidence");
4594 }
4595
4596 #[test]
4597 fn explicit_resumption_is_not_invented_for_legacy_or_automatic_release() {
4598 let t = Task::new(
4599 "retry".into(),
4600 "do it".into(),
4601 PathBuf::from("."),
4602 Source::Human,
4603 );
4604 let mut value = serde_json::to_value(&t).unwrap();
4605 for field in ["resumption", "resumption_history", "operator_decided_at"] {
4606 value.as_object_mut().unwrap().remove(field);
4607 }
4608 value["schema"] = serde_json::json!(15);
4609 let mut legacy: Task = serde_json::from_value(value).unwrap();
4610 legacy.hold_machine(Some("automatic retry".into()));
4611 legacy.release();
4612 assert!(legacy.resumption.is_none());
4613 assert!(legacy.resumption_history.is_empty());
4614 assert!(legacy.operator_decided_at.is_none());
4615 legacy.release_operator("cli", None);
4616 legacy.start("run".into());
4617 let reloaded: Task =
4618 serde_json::from_str(&serde_json::to_string(&legacy).unwrap()).unwrap();
4619 assert!(reloaded.resume_override.is_none());
4620 assert_eq!(reloaded.resumption.as_ref().unwrap().generation, 1);
4621 }
4622
4623 #[test]
4624 fn merge_over_lets_the_later_choice_win_and_keeps_the_rest() {
4625 let mut base = RunOverrides {
4626 merge: Some("pr".to_owned()),
4627 candidates: Some(3),
4628 ..RunOverrides::default()
4629 };
4630 base.merge_over(&RunOverrides {
4631 merge: Some("none".to_owned()),
4632 seed: Some(7),
4633 ..RunOverrides::default()
4634 });
4635 assert_eq!(base.merge.as_deref(), Some("none"));
4636 assert_eq!(base.candidates, Some(3));
4637 assert_eq!(base.seed, Some(7));
4638 }
4639
4640 #[test]
4641 fn an_already_landed_task_is_done_with_its_attempt_refunded() {
4642 let mut t = task("relanded");
4643 t.attempts = 1;
4644 t.status = TaskStatus::Running;
4645 t.already_landed("already in main as 0e368de", completion(&t));
4646 assert_eq!(t.status, TaskStatus::Done);
4647 assert_eq!(t.attempts, 0);
4648 assert!(t.hold_reason.is_none());
4649 assert_eq!(t.last_error.as_deref(), Some("already in main as 0e368de"));
4650 }
4651
4652 #[test]
4653 fn missing_blocker_reason_follows_the_language() {
4654 let b = vec!["a".to_owned()];
4655 let en = missing_blocker_hold_reason_in(&b, &b, "en");
4656 assert_eq!(en, missing_blocker_hold_reason(&b, &b));
4657 assert!(en.starts_with("blocked on a"));
4658 assert!(missing_blocker_hold_reason_in(&b, &b, "ja").contains("存在しません"));
4659 assert_eq!(missing_blocker_hold_reason_in(&b, &b, "de"), en);
4660 }
4661
4662 use super::*;
4663
4664 fn completion(task: &Task) -> CompletionContext {
4665 CompletionContext::new(CompletionActor::Cli, None, Path::new("."), task)
4666 }
4667
4668 #[test]
4669 fn completion_retains_the_hold_dependency_and_failure_it_clears() {
4670 let mut held = task("held evidence");
4671 held.hold_manual(Some("owner approval required".into()));
4672 held.last_error = Some("review budget exhausted".into());
4673 held.succeed(completion(&held));
4674 let event = held.completion_history.last().unwrap();
4675 assert_eq!(event.prior_status, TaskStatus::Held);
4676 assert_eq!(
4677 event.prior_hold_reason.as_deref(),
4678 Some("owner approval required")
4679 );
4680 assert_eq!(
4681 event.prior_error.as_deref(),
4682 Some("review budget exhausted")
4683 );
4684 assert!(held.hold_reason.is_none());
4685 assert!(held.last_error.is_none());
4686 let mut blocked = task("dependency evidence");
4687 blocked.block(
4688 vec!["dependency".into()],
4689 Some("waiting on migration".into()),
4690 );
4691 blocked.succeed(completion(&blocked));
4692 let event = blocked.completion_history.last().unwrap();
4693 assert_eq!(event.prior_status, TaskStatus::Blocked);
4694 assert_eq!(
4695 event.prior_block_reason.as_deref(),
4696 Some("waiting on migration")
4697 );
4698 assert!(blocked.block_reason.is_none());
4699 assert!(blocked.blocked_by.is_empty());
4700 let saved = serde_json::to_vec(&held).unwrap();
4701 let restored: Task = serde_json::from_slice(&saved).unwrap();
4702 assert_eq!(restored.completion_history, held.completion_history);
4703 }
4704
4705 #[test]
4706 fn completion_audit_is_append_only_under_stale_puts() {
4707 let dir = tempfile::tempdir().unwrap();
4708 let queue = Queue::at(dir.path().join("queue"));
4709 let mut current = task("audited");
4710 current.hold_manual(Some("inspect".into()));
4711 queue.put(&mut current).unwrap();
4712 let mut stale = queue.get(¤t.id).unwrap();
4713 current.succeed(completion(¤t));
4714 queue.put(&mut current).unwrap();
4715 let original = current.completion_history[0].clone();
4716 stale.last_error = Some("stale control state".into());
4717 queue.put(&mut stale).unwrap();
4718 assert_eq!(stale.status, TaskStatus::Done);
4719 assert_eq!(stale.completion_history, vec![original.clone()]);
4720 let mut context = completion(¤t);
4721 context.reason = Some("not actually finished".into());
4722 current.reopen(context).unwrap();
4723 queue.put(&mut current).unwrap();
4724 stale.completion_history[0].actor = CompletionActor::Web;
4725 stale.completion_history[0].reason = Some("rewritten evidence".into());
4726 queue.put(&mut stale).unwrap();
4727 assert_eq!(stale.status, TaskStatus::Held);
4728 assert_eq!(stale.hold_reason.as_deref(), Some("not actually finished"));
4729 assert_eq!(stale.completion_history[0], original);
4730 assert_eq!(stale.completion_history, current.completion_history);
4731 }
4732
4733 #[test]
4734 fn a_writer_missing_a_reopen_contributes_receipts_but_not_authority() {
4735 let (_dir, q) = queue();
4736 let mut current = task("durable receipts");
4737 q.put(&mut current).unwrap();
4738 let mut stale = current.clone();
4739 let grant: crate::repair_budget::Receipt = serde_json::from_value(serde_json::json!({
4740 "request": {
4741 "task": current.id, "run": "old-run", "kind": "gate", "rounds": 1,
4742 "head": "old-head", "expect_pass": 0, "request": "old-grant", "reason": "retry"
4743 },
4744 "at": stale.updated_at, "contract": "old-contract"
4745 }))
4746 .unwrap();
4747 stale.release_operator("triage", Some("triage-question"));
4748 stale.queue_repair(&grant);
4749 let reconciliation: crate::repair_budget::reconcile::Receipt =
4750 serde_json::from_value(serde_json::json!({
4751 "request": {
4752 "task": current.id, "run": "old-run", "head": "old-head", "expect_pass": 0,
4753 "receipt": "old-grant", "question": "triage-question", "answer_at": grant.at,
4754 "request": "reconciliation", "reason": "retain the answer"
4755 },
4756 "grant": grant, "source": "answer", "application": "release",
4757 "decision": grant.at, "superseded_questions": []
4758 }))
4759 .unwrap();
4760 stale.repair_reconciliations.push(reconciliation.clone());
4761 stale.triage_applied.push("triage-question".into());
4762 stale.actions_applied.push("choice".into());
4763 stale.base_recovery_requests.push("base-request".into());
4764 stale.chat_notices.push("delivery".into());
4765 stale.chat_notice = Some(ChatNotice {
4766 key: "other-delivery".into(),
4767 at: grant.at,
4768 outcome: ChatNoticeOutcome::Posted,
4769 });
4770 for ledger in [
4771 &mut stale.decision_effects,
4772 &mut stale.dispatched_resumes,
4773 &mut stale.superseded_resumes,
4774 ] {
4775 ledger.insert("shared".into(), "stale".into());
4776 ledger.insert("only-stale".into(), "receipt".into());
4777 }
4778
4779 let mut latest_grant = grant.clone();
4780 latest_grant.request.request = "new-grant".into();
4781 current.queue_repair(&latest_grant);
4782 for ledger in [
4783 &mut current.decision_effects,
4784 &mut current.dispatched_resumes,
4785 &mut current.superseded_resumes,
4786 ] {
4787 ledger.insert("shared".into(), "committed".into());
4788 }
4789 current.succeed(completion(¤t));
4790 let mut context = completion(¤t);
4791 context.reason = Some("inspect again".into());
4792 current.reopen(context).unwrap();
4793 q.put(&mut current).unwrap();
4794
4795 for _ in 0..2 {
4796 q.put(&mut stale.clone()).unwrap();
4797 let saved = q.get(¤t.id).unwrap();
4798 assert_eq!(saved.status, TaskStatus::Held);
4799 assert_eq!(saved.hold_reason, current.hold_reason);
4800 assert_eq!(saved.operator_decided_at, current.operator_decided_at);
4801 assert_eq!(saved.completion_history, current.completion_history);
4802 assert!(saved.resume_override.is_none());
4803 assert!(saved.resumption.is_none());
4804 assert_eq!(
4805 saved.resumption_history,
4806 [stale.resumption.clone().unwrap()]
4807 );
4808 assert_eq!(saved.triage_applied, ["triage-question"]);
4809 assert_eq!(saved.actions_applied, ["choice"]);
4810 assert_eq!(saved.base_recovery_requests, ["base-request"]);
4811 assert_eq!(saved.chat_notices, ["delivery", "other-delivery"]);
4812 assert_eq!(saved.repair_grants, [grant.clone(), latest_grant.clone()]);
4813 assert_eq!(
4814 saved.repair_reconciliations,
4815 std::slice::from_ref(&reconciliation)
4816 );
4817 for ledger in [
4818 saved.decision_effects,
4819 saved.dispatched_resumes,
4820 saved.superseded_resumes,
4821 ] {
4822 assert_eq!(ledger["shared"], "committed");
4823 assert_eq!(ledger["only-stale"], "receipt");
4824 }
4825 }
4826 }
4827
4828 #[test]
4829 fn repeated_completion_only_notifies_for_new_occurrences() {
4830 let mut task = chat_task();
4831 task.succeed(completion(&task));
4832 let first = task.chat_notice_key().unwrap();
4833 task.chat_notices.push(first.clone());
4834 task.succeed(completion(&task));
4835 assert_eq!(task.completion_history.len(), 1, "idempotent while done");
4836 assert_eq!(task.chat_notice_due(), None);
4837 let mut context = completion(&task);
4838 context.reason = Some("inspect".into());
4839 task.reopen(context).unwrap();
4840 task.succeed(completion(&task));
4841 let second = task.chat_notice_key().unwrap();
4842 assert_ne!(first, second);
4843 assert_eq!(task.chat_notice_due(), Some(second));
4844 assert_eq!(task.completion_history.len(), 3);
4845 }
4846
4847 #[test]
4848 fn old_tasks_have_unknown_completion_provenance_not_invented_events() {
4849 let mut task = task("legacy");
4850 task.status = TaskStatus::Done;
4851 let mut value = serde_json::to_value(&task).unwrap();
4852 value.as_object_mut().unwrap().remove("completion_history");
4853 let task: Task = serde_json::from_value(value).unwrap();
4854 assert!(task.completion_history.is_empty());
4855 assert_eq!(task.chat_notice_key().as_deref(), Some("done"));
4856 }
4857
4858 #[test]
4859 fn triage_applied_survives_release_and_old_records_read_as_empty() {
4860 let mut t = Task::new(
4861 "t".to_owned(),
4862 "i".to_owned(),
4863 PathBuf::from("r"),
4864 Source::Human,
4865 );
4866 t.mark_triage_applied("q1");
4867 t.mark_triage_applied("q1");
4868 t.hold_machine(Some("x".to_owned()));
4869 t.release();
4870 assert_eq!(t.triage_applied, ["q1"]);
4871 assert!(t.triage_applied("q1") && !t.triage_applied("q2"));
4872
4873 let mut v = serde_json::to_value(&t).unwrap();
4874 v.as_object_mut().unwrap().remove("triage_applied");
4875 let old: Task = serde_json::from_value(v).unwrap();
4876 assert!(old.triage_applied.is_empty());
4877 }
4878
4879 #[test]
4880 fn task_counts_of_empty_is_all_zero() {
4881 assert_eq!(TaskCounts::of(&[]), TaskCounts::default());
4882 }
4883
4884 #[test]
4885 fn task_counts_of_tallies_every_status() {
4886 let mut queued = Task::new(
4887 "q".to_owned(),
4888 "i".to_owned(),
4889 PathBuf::from("."),
4890 Source::Human,
4891 );
4892 queued.status = TaskStatus::Queued;
4893 let mut running = queued.clone();
4894 running.status = TaskStatus::Running;
4895 let mut done = queued.clone();
4896 done.status = TaskStatus::Done;
4897 let mut failed = queued.clone();
4898 failed.status = TaskStatus::Failed;
4899 let mut held = queued.clone();
4900 held.status = TaskStatus::Held;
4901 let mut blocked = queued.clone();
4902 blocked.status = TaskStatus::Blocked;
4903
4904 let mut parked = queued.clone();
4905 parked.status = TaskStatus::Parked;
4906
4907 let counts = TaskCounts::of(&[
4908 queued,
4909 running,
4910 done.clone(),
4911 done,
4912 failed,
4913 held,
4914 blocked,
4915 parked,
4916 ]);
4917 assert_eq!(
4918 counts,
4919 TaskCounts {
4920 queued: 1,
4921 running: 1,
4922 done: 2,
4923 failed: 1,
4924 held: 1,
4925 blocked: 1,
4926 parked: 1,
4927 }
4928 );
4929 }
4930
4931 #[test]
4932 fn task_implementers_persist_normalized_without_losing_history() {
4933 let (_dir, q) = queue();
4934 let mut t = task("keep me");
4935 t.hold_manual(Some("waiting".into()));
4936 t.runs.push("earlier-run".into());
4937 t.attachments.push("reference.txt".into());
4938 let cfg: crate::config::Config =
4939 toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
4940 .unwrap();
4941 q.put(&mut t).unwrap();
4942 let original = serde_json::to_value(&t).unwrap();
4943 for n in [2, 1, 2] {
4944 t.set_implementers(n, &cfg).unwrap();
4945 q.put(&mut t).unwrap();
4946 t = q.get(&t.id).unwrap();
4947 assert_eq!(t.implementers(), Some(usize::from(n)));
4948 assert_eq!(t.solo, n == 1);
4949 if n == 1 {
4950 assert!(t.overrides.is_none());
4951 }
4952 let mut actual = serde_json::to_value(&t).unwrap();
4953 for field in ["solo", "overrides", "updated_at"] {
4954 actual[field] = original[field].clone();
4955 }
4956 assert_eq!(actual, original);
4957 }
4958 t.overrides.as_mut().unwrap().judges = Some(2);
4959 t.set_implementers(1, &cfg).unwrap();
4960 assert_eq!(t.overrides.as_ref().unwrap().judges, Some(2));
4961 assert_eq!(t.overrides.as_ref().unwrap().candidates, None);
4962 }
4963
4964 #[test]
4965 fn task_implementers_old_records_keep_inheritance_until_changed() {
4966 let mut value = serde_json::to_value(task("old task")).unwrap();
4967 value.as_object_mut().unwrap().remove("solo");
4968 value.as_object_mut().unwrap().remove("overrides");
4969 let mut old: Task = serde_json::from_value(value).unwrap();
4970 assert_eq!(old.implementers(), None);
4971 old.set_implementers(1, &crate::config::Config::default())
4972 .unwrap();
4973 assert!(old.solo);
4974 assert!(old.overrides.is_none());
4975 }
4976
4977 #[test]
4978 fn task_implementers_reject_invalid_counts_and_states() {
4979 let cfg = crate::config::Config::default();
4980 let mut t = task("unchanged");
4981 for n in [0, 4, 255] {
4982 assert!(t.set_implementers(n, &cfg).is_err());
4983 }
4984 for status in [
4985 TaskStatus::Running,
4986 TaskStatus::Done,
4987 TaskStatus::Failed,
4988 TaskStatus::Blocked,
4989 TaskStatus::Parked,
4990 ] {
4991 t.status = status;
4992 let before = serde_json::to_value(&t).unwrap();
4993 assert!(t.set_implementers(1, &cfg).is_err());
4994 assert_eq!(serde_json::to_value(&t).unwrap(), before);
4995 }
4996 }
4997
4998 fn queue() -> (tempfile::TempDir, Queue) {
5001 let dir = tempfile::tempdir().unwrap();
5002 let q = Queue::at(dir.path().join("queue"));
5003 (dir, q)
5004 }
5005
5006 #[test]
5007 fn base_recovery_commit_retains_decision_and_superseded_resume_evidence() {
5008 let (_dir, q) = queue();
5009 let mut original = task("base recovery");
5010 original
5011 .decision_effects
5012 .insert("old-effect".into(), "receipt".into());
5013 original
5014 .dispatched_resumes
5015 .insert("dispatched".into(), "prior-run".into());
5016 original.resume_override = Some(OperatorResume {
5017 question_id: "prior-decision".into(),
5018 at: Timestamp::now(),
5019 conductor_rehold: None,
5020 forced: true,
5021 pinned_run: Some("retained-run".into()),
5022 });
5023 q.put(&mut original).unwrap();
5024 let expected = serde_json::to_value(&original).unwrap();
5025 let mut recovered = original.clone();
5026 recovered.base_recovery_requests.push("chat/request".into());
5027 recovered
5028 .resume_override
5029 .as_mut()
5030 .unwrap()
5031 .question_id
5032 .clear();
5033 q.commit_base_recovery(&mut recovered, &expected).unwrap();
5034 let saved = q.get(&original.id).unwrap();
5035 assert_eq!(saved.decision_effects, original.decision_effects);
5036 assert_eq!(saved.dispatched_resumes, original.dispatched_resumes);
5037 assert_eq!(
5038 saved
5039 .superseded_resumes
5040 .get("prior-decision")
5041 .map(String::as_str),
5042 Some("retained-run")
5043 );
5044 assert_eq!(saved.base_recovery_requests, ["chat/request"]);
5045 assert!(saved.resume_override.unwrap().question_id.is_empty());
5046 assert!(q.commit_base_recovery(&mut recovered, &expected).is_err());
5047 }
5048
5049 #[test]
5050 fn a_stale_write_does_not_drop_the_recorded_task_chat() {
5051 let (_dir, q) = queue();
5052 let mut stale = task("chat");
5053 q.put(&mut stale).unwrap();
5054 let mut fresh = q.get(&stale.id).unwrap();
5055 fresh.chat = Some("talk-1".to_owned());
5056 q.put(&mut fresh).unwrap();
5057 q.put(&mut stale).unwrap();
5058 assert_eq!(q.get(&stale.id).unwrap().chat.as_deref(), Some("talk-1"));
5059 }
5060
5061 #[test]
5062 fn putting_a_machine_held_task_files_a_notification_beside_the_queue() {
5063 let dir = tempfile::tempdir().unwrap();
5064 let q = Queue::at(dir.path().join("queue"));
5065 let mut t = task("held");
5066 q.put(&mut t).unwrap();
5067 assert_eq!(
5068 crate::notices::Notices::at(dir.path().join("notifications"))
5069 .list()
5070 .len(),
5071 0
5072 );
5073 t.hold_machine(Some("out of attempts".to_owned()));
5074 q.put(&mut t).unwrap();
5075 let listed = crate::notices::Notices::at(dir.path().join("notifications")).list();
5076 assert_eq!(listed.len(), 1);
5077 assert!(listed[0].message.contains("out of attempts"));
5078 }
5079
5080 #[test]
5081 fn start_consumes_the_disk_resume_pin() {
5082 let mut t = task("pin");
5083 t.disk_resume_run = Some("run-1".into());
5084 t.start("run-1".into());
5085 assert!(t.disk_resume_run.is_none());
5086 }
5087
5088 fn task(title: &str) -> Task {
5089 Task::new(
5090 title.to_owned(),
5091 format!("do {title}"),
5092 PathBuf::from("."),
5093 Source::Human,
5094 )
5095 }
5096
5097 #[test]
5098 fn attempt_limit_inherits_old_records_and_controls_failure() {
5099 let mut t = task("budget");
5100 let mut old = serde_json::to_value(&t).unwrap();
5101 old.as_object_mut().unwrap().remove("attempt_limit");
5102 old["schema"] = serde_json::json!(15);
5103 let legacy: Task = serde_json::from_value(old).unwrap();
5104 assert_eq!(legacy.attempt_limit, None);
5105 assert_eq!(legacy.effective_attempt_limit(2), 2);
5106 t.attempts = 2;
5107 t.change_attempt_limit(NonZeroUsize::new(3)).unwrap();
5108 t.fail("retry", 1);
5109 assert_eq!(t.status, TaskStatus::Failed);
5110 t.attempts = 3;
5111 t.fail("stop", 10);
5112 assert_eq!(t.status, TaskStatus::Held);
5113 t.change_attempt_limit(None).unwrap();
5114 assert_eq!(t.status, TaskStatus::Held);
5115 assert_eq!(t.attempts, 3);
5116 t.fail("inherit", 4);
5117 assert_eq!(t.status, TaskStatus::Failed);
5118 for status in [
5119 TaskStatus::Running,
5120 TaskStatus::Done,
5121 TaskStatus::Failed,
5122 TaskStatus::Blocked,
5123 TaskStatus::Parked,
5124 ] {
5125 t.status = status;
5126 assert!(t.change_attempt_limit(NonZeroUsize::new(1)).is_err());
5127 assert_eq!(t.attempt_limit, None);
5128 }
5129 }
5130
5131 #[test]
5132 fn earlier_attempts_is_every_recorded_run_and_agrees_with_the_display() {
5133 let mut t = task("retried");
5134 assert!(
5135 t.earlier_attempts().is_empty(),
5136 "a first attempt takes nothing over"
5137 );
5138 t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned()];
5139 assert_eq!(t.earlier_attempts(), ["aaaa", "bbbb"]);
5140 assert_eq!(t.successor_of("aaaa"), Some(&"bbbb".to_owned()));
5142 assert_eq!(t.successor_of("bbbb"), None);
5143 assert_eq!(t.successor_of("zzzz"), None);
5144 }
5145
5146 #[test]
5147 fn resumed_runs_are_superseded_only_after_their_last_occurrence() {
5148 let (_dir, q) = queue();
5149 let mut t = task("resumed");
5150 for (runs, successor) in [
5151 (vec!["aaaa", "aaaa"], None),
5152 (vec!["aaaa", "bbbb", "aaaa"], None),
5153 (vec!["aaaa", "aaaa", "bbbb"], Some("bbbb")),
5154 (vec!["aaaa", "bbbb", "aaaa", "cccc"], Some("cccc")),
5155 ] {
5156 t.runs = runs.into_iter().map(str::to_owned).collect();
5157 q.put(&mut t).unwrap();
5158
5159 assert_eq!(t.successor_of("aaaa").map(String::as_str), successor);
5160 assert_eq!(q.superseded_by("aaaa").as_deref(), successor);
5161 assert_eq!(q.superseded().get("aaaa").map(String::as_str), successor);
5162 }
5163 }
5164
5165 #[test]
5166 fn superseded_by_names_the_next_attempt_and_none_for_the_last() {
5167 let (_dir, q) = queue();
5168 let mut t = task("retried");
5169 t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned(), "cccc".to_owned()];
5170 q.put(&mut t).unwrap();
5171
5172 assert_eq!(q.superseded_by("aaaa"), Some("bbbb".to_owned()));
5173 assert_eq!(q.superseded_by("bbbb"), Some("cccc".to_owned()));
5174 assert_eq!(
5175 q.superseded_by("cccc"),
5176 None,
5177 "the latest attempt replaces nothing"
5178 );
5179 assert_eq!(
5180 q.superseded_by("never-heard-of-it"),
5181 None,
5182 "a run belonging to no task on this queue is not superseded"
5183 );
5184
5185 let mut by = HashMap::new();
5186 by.insert("aaaa".to_owned(), "bbbb".to_owned());
5187 by.insert("bbbb".to_owned(), "cccc".to_owned());
5188 assert_eq!(
5189 q.superseded(),
5190 by,
5191 "the whole-map and single-run forms must agree"
5192 );
5193 }
5194
5195 #[test]
5196 fn superseded_attempts_is_empty_until_the_task_is_done() {
5197 let mut t = task("retried");
5198 t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned()];
5199 t.status = TaskStatus::Failed;
5200 assert_eq!(
5201 t.superseded_attempts(true),
5202 &[] as &[String],
5203 "a task still retrying has no attempt yet that a later one made moot"
5204 );
5205
5206 t.status = TaskStatus::Running;
5207 assert_eq!(t.superseded_attempts(true), &[] as &[String]);
5208 }
5209
5210 #[test]
5211 fn superseded_attempts_names_every_run_before_the_one_that_succeeded() {
5212 let mut t = task("retried");
5213 t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned(), "cccc".to_owned()];
5214 t.status = TaskStatus::Done;
5215 assert_eq!(
5216 t.superseded_attempts(true),
5217 &["aaaa".to_owned(), "bbbb".to_owned()],
5218 "cccc is the attempt whose success made the task done, and stays out"
5219 );
5220 }
5221
5222 #[test]
5223 fn superseded_attempts_is_empty_for_a_done_task_with_only_one_attempt() {
5224 let mut t = task("first try landed");
5225 t.runs = vec!["aaaa".to_owned()];
5226 t.status = TaskStatus::Done;
5227 assert_eq!(t.superseded_attempts(true), &[] as &[String]);
5228 }
5229
5230 #[test]
5231 fn superseded_attempts_is_empty_when_the_last_run_never_actually_succeeded() {
5232 let mut t = task("closed by hand after a manual merge");
5239 t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned()];
5240 t.status = TaskStatus::Done;
5241 assert_eq!(
5242 t.superseded_attempts(false),
5243 &[] as &[String],
5244 "nothing here is provably why the task is done, so nothing is superseded"
5245 );
5246 }
5247
5248 #[test]
5249 fn latest_attempt_names_the_chain_s_current_head_not_just_the_next_one() {
5250 let (_dir, q) = queue();
5251 let mut t = task("retried twice");
5252 t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned(), "cccc".to_owned()];
5253 q.put(&mut t).unwrap();
5254
5255 assert_eq!(
5256 q.latest_attempt("aaaa"),
5257 Some("cccc".to_owned()),
5258 "an old attempt points straight at the chain's current head, not the \
5259 next attempt in the middle of it"
5260 );
5261 assert_eq!(q.latest_attempt("bbbb"), Some("cccc".to_owned()));
5262 assert_eq!(
5263 q.latest_attempt("cccc"),
5264 None,
5265 "the latest attempt is not superseded by anything"
5266 );
5267 assert_eq!(
5268 q.latest_attempt("never-heard-of-it"),
5269 None,
5270 "a run belonging to no task on this queue is not superseded"
5271 );
5272 }
5273
5274 #[test]
5275 fn a_markdown_heading_is_the_title_not_decoration() {
5276 assert_eq!(
5281 title_from("# Rework the config loader\n\nIt re-reads it.\n", 40),
5282 "Rework the config loader"
5283 );
5284 assert_eq!(title_from("- fix the thing", 40), "fix the thing");
5285 assert_eq!(title_from("> quoted task", 40), "quoted task");
5286 assert_eq!(title_from(" \n\n", 40), "(empty task)");
5288 assert_eq!(title_from("###\n", 40), "(empty task)");
5289 }
5290
5291 #[test]
5292 fn a_long_title_is_elided_by_characters_not_bytes() {
5293 let long = "課題".repeat(30);
5295 let title = title_from(&long, 10);
5296 assert_eq!(title.chars().count(), 10);
5297 assert!(title.ends_with('…'));
5298 }
5299
5300 #[test]
5301 fn priority_wins_and_ties_break_oldest_first() {
5302 let (_dir, q) = queue();
5303 let mut a = task("first");
5304 let mut b = task("second");
5305 let mut c = task("urgent");
5306 a.id = "20260101-000001-aaaa".to_owned();
5308 b.id = "20260101-000002-bbbb".to_owned();
5309 c.id = "20260101-000003-cccc".to_owned();
5310 c.priority = 5;
5311 for t in [&mut a, &mut b, &mut c] {
5312 q.put(t).unwrap();
5313 }
5314
5315 assert_eq!(q.next_runnable().unwrap().id, c.id);
5317 c.hold_machine(None);
5318 q.put(&mut c).unwrap();
5319 assert_eq!(q.next_runnable().unwrap().id, a.id);
5321 assert_eq!(q.list().len(), 3, "b is still waiting its turn");
5322 }
5323
5324 #[test]
5325 fn a_blocked_task_never_starves_another_runnable_one() {
5326 let (_dir, q) = queue();
5327 let mut blocked = task("blocked");
5328 blocked.block(vec!["something".to_owned()], None);
5329 q.put(&mut blocked).unwrap();
5330
5331 let mut runnable = task("free to go");
5332 q.put(&mut runnable).unwrap();
5333
5334 let next = q.next_runnable().expect("a runnable task is still offered");
5335 assert_eq!(next.id, runnable.id);
5336 }
5337
5338 #[test]
5339 fn a_held_task_is_never_offered_to_the_loop() {
5340 let (_dir, q) = queue();
5341 let mut t = task("held");
5342 q.put(&mut t).unwrap();
5343 assert!(q.next_runnable().is_some());
5344
5345 t.hold_machine(None);
5346 q.put(&mut t).unwrap();
5347 assert!(
5348 q.next_runnable().is_none(),
5349 "a held task must wait for a human"
5350 );
5351
5352 t.status = TaskStatus::Failed;
5354 q.put(&mut t).unwrap();
5355 assert!(q.next_runnable().is_some());
5356 }
5357
5358 #[test]
5359 fn attempts_are_capped_and_then_the_task_is_held() {
5360 let mut t = task("doomed");
5361
5362 t.start("run-1".to_owned());
5363 t.fail("gate red", 2);
5364 assert_eq!(t.status, TaskStatus::Failed, "one attempt of two: retry");
5365
5366 t.start("run-2".to_owned());
5367 t.fail("gate red", 2);
5368 assert_eq!(
5369 t.status,
5370 TaskStatus::Held,
5371 "out of attempts: stop spending money on it"
5372 );
5373 assert_eq!(t.runs, ["run-1", "run-2"]);
5374 assert_eq!(t.last_error.as_deref(), Some("gate red"));
5375 assert_eq!(
5376 t.hold_reason.as_deref(),
5377 Some("gate red"),
5378 "the hold must say why, not leave hold_reason null next to a \
5379 populated last_error"
5380 );
5381 }
5382
5383 #[test]
5384 fn handing_off_a_task_records_a_hold_reason_too() {
5385 let mut t = task("left a pull request");
5386 t.start("run-1".to_owned());
5387 t.handed_off("run ended with a pull request open [run run-1]");
5388 assert_eq!(t.status, TaskStatus::Held);
5389 assert_eq!(t.hold_source, Some(HoldSource::Machine));
5390 assert_eq!(
5391 t.hold_reason.as_deref(),
5392 Some("run ended with a pull request open [run run-1]")
5393 );
5394 assert_eq!(t.hold_reason, t.last_error);
5395 }
5396
5397 #[test]
5398 fn a_quota_stall_is_refunded_so_the_backlog_survives_the_night() {
5399 let mut t = task("stalled by quota");
5400
5401 t.start("run-1".to_owned());
5402 assert_eq!(t.attempts, 1);
5403 t.stall("judge-1, judge-2 out of quota");
5404 assert_eq!(
5405 t.attempts, 0,
5406 "a closed quota window must not spend the task's retry budget"
5407 );
5408 assert_eq!(t.status, TaskStatus::Failed, "the loop should retry it");
5409 assert_eq!(
5410 t.last_error.as_deref(),
5411 Some("judge-1, judge-2 out of quota")
5412 );
5413
5414 for _ in 0..20 {
5417 t.start("run-n".to_owned());
5418 t.stall("still out of quota");
5419 }
5420 t.start("run-real".to_owned());
5421 t.fail("gate red", 2);
5422 assert_eq!(
5423 t.status,
5424 TaskStatus::Failed,
5425 "the first attempt that was really judged is attempt one"
5426 );
5427 }
5428
5429 #[test]
5430 fn releasing_a_held_task_gives_it_a_real_second_chance() {
5431 let mut t = task("retry me");
5432 t.start("run-1".to_owned());
5433 t.fail("gate red", 1);
5434 assert_eq!(t.status, TaskStatus::Held);
5435
5436 t.release();
5437 assert_eq!(t.status, TaskStatus::Queued);
5438 assert_eq!(t.attempts, 0);
5441 assert!(t.last_error.is_none());
5442 assert_eq!(
5443 t.runs.len(),
5444 1,
5445 "history is kept: attempts reset, evidence does not"
5446 );
5447 }
5448
5449 #[test]
5450 fn a_hold_reason_survives_and_a_release_clears_it() {
5451 let mut t = task("waiting on something else");
5452 t.hold_manual(Some(
5453 "waiting for 20260101-000000-aaaa to land first".to_owned(),
5454 ));
5455 assert_eq!(t.status, TaskStatus::Held);
5456 assert_eq!(
5457 t.hold_reason.as_deref(),
5458 Some("waiting for 20260101-000000-aaaa to land first")
5459 );
5460
5461 t.hold_manual(None);
5463 assert_eq!(
5464 t.hold_reason.as_deref(),
5465 Some("waiting for 20260101-000000-aaaa to land first"),
5466 "a bare re-hold keeps whatever a human already wrote down"
5467 );
5468
5469 let mut plain = task("no reason given");
5471 plain.hold_manual(None);
5472 assert_eq!(plain.status, TaskStatus::Held);
5473 assert!(plain.hold_reason.is_none());
5474
5475 t.release();
5476 assert_eq!(t.status, TaskStatus::Queued);
5477 assert!(
5478 t.hold_reason.is_none(),
5479 "a stale reason must not greet the next person who holds this task"
5480 );
5481 }
5482
5483 #[test]
5484 fn closing_a_held_task_as_done_clears_its_hold_reason_too() {
5485 let mut t = task("landed by hand while held");
5490 t.hold_manual(Some("waiting on 3ed9".to_owned()));
5491 assert_eq!(t.hold_reason.as_deref(), Some("waiting on 3ed9"));
5492
5493 t.succeed(completion(&t));
5494 assert_eq!(t.status, TaskStatus::Done);
5495 assert!(
5496 t.hold_reason.is_none(),
5497 "a done task cannot still be waiting on something"
5498 );
5499 }
5500
5501 #[test]
5502 fn holding_or_closing_a_blocked_task_clears_its_dependency_too() {
5503 let mut held = task("held straight out of blocked");
5510 held.block(
5511 vec!["20260101-000000-dead".to_owned()],
5512 Some("waiting on the migration script".to_owned()),
5513 );
5514 assert_eq!(held.status, TaskStatus::Blocked);
5515
5516 held.hold_manual(None);
5517 assert_eq!(held.status, TaskStatus::Held);
5518 assert!(
5519 held.blocked_by.is_empty(),
5520 "hold overrides the wait, same as release"
5521 );
5522 assert!(held.block_reason.is_none());
5523
5524 let mut done = task("closed straight out of blocked");
5525 done.block(
5526 vec!["20260101-000000-dead".to_owned()],
5527 Some("waiting on the migration script".to_owned()),
5528 );
5529 done.succeed(completion(&done));
5530 assert_eq!(done.status, TaskStatus::Done);
5531 assert!(
5532 done.blocked_by.is_empty(),
5533 "a done task cannot still be waiting on a dependency"
5534 );
5535 assert!(done.block_reason.is_none());
5536 }
5537
5538 #[test]
5539 fn a_blocked_task_is_never_offered_to_the_loop() {
5540 let mut t = task("blocked");
5541 assert!(t.status.runnable());
5542 t.block(
5543 vec!["dep-id".to_owned()],
5544 Some("waits on dep-id".to_owned()),
5545 );
5546 assert_eq!(t.status, TaskStatus::Blocked);
5547 assert!(!t.status.runnable());
5548 assert_eq!(TaskStatus::Blocked.as_str(), "blocked");
5549 }
5550
5551 #[test]
5552 fn unblocking_the_last_dependency_returns_the_task_to_queued() {
5553 let mut t = task("blocked on two");
5554 t.block(
5555 vec!["a".to_owned(), "b".to_owned()],
5556 Some("waits on a and b".to_owned()),
5557 );
5558
5559 t.unblock("a");
5560 assert_eq!(t.status, TaskStatus::Blocked, "b is still outstanding");
5561 assert_eq!(t.blocked_by, ["b"]);
5562
5563 t.unblock("b");
5564 assert_eq!(t.status, TaskStatus::Queued);
5565 assert!(t.blocked_by.is_empty());
5566 assert!(t.block_reason.is_none());
5567 }
5568
5569 #[test]
5570 fn unblocking_an_id_on_a_task_that_is_not_blocked_is_a_no_op() {
5571 let mut t = task("never blocked");
5572 t.unblock("whatever");
5573 assert_eq!(t.status, TaskStatus::Queued);
5574 }
5575
5576 #[test]
5577 fn a_held_task_blocked_on_a_question_returns_to_held_not_queued() {
5578 let mut t = task("held, then asked about");
5583 t.hold_machine(Some("out of attempts".to_owned()));
5584 assert_eq!(t.status, TaskStatus::Held);
5585
5586 t.block(vec!["q1".to_owned()], Some("what now?".to_owned()));
5587 assert_eq!(t.status, TaskStatus::Blocked);
5588
5589 t.record_answer("what now?".to_owned(), "leave it held".to_owned());
5590 t.unblock("q1");
5591 assert_eq!(t.status, TaskStatus::Held, "must restore, not requeue");
5592 assert_eq!(t.hold_reason.as_deref(), Some("out of attempts"));
5593 assert_eq!(t.hold_source, Some(HoldSource::Machine));
5594 assert!(t.blocked_from.is_none(), "consumed once restored");
5595 }
5596
5597 #[test]
5598 fn a_manually_held_task_blocked_on_a_question_returns_to_held() {
5599 let mut t = task("manually held, then asked about");
5600 t.hold_manual(Some("waiting on a dependency".to_owned()));
5601
5602 t.block(vec!["q1".to_owned()], None);
5603 t.unblock("q1");
5604
5605 assert_eq!(t.status, TaskStatus::Held);
5606 assert_eq!(t.hold_source, Some(HoldSource::Manual));
5607 }
5608
5609 #[test]
5610 fn re_blocking_an_already_blocked_task_keeps_the_original_blocked_from() {
5611 let mut t = task("held, blocked twice");
5615 t.hold_machine(None);
5616 t.block(vec!["q1".to_owned()], Some("first".to_owned()));
5617 t.block(
5618 vec!["q1".to_owned(), "q2".to_owned()],
5619 Some("second".to_owned()),
5620 );
5621
5622 t.unblock("q1");
5623 assert_eq!(t.status, TaskStatus::Blocked, "q2 still outstanding");
5624 t.unblock("q2");
5625 assert_eq!(t.status, TaskStatus::Held);
5626 }
5627
5628 #[test]
5629 fn unblocking_a_task_blocked_while_running_lands_on_queued_not_running() {
5630 let mut t = task("blocked mid-run");
5634 t.start("run-1".to_owned());
5635 assert_eq!(t.status, TaskStatus::Running);
5636
5637 t.block(vec!["q1".to_owned()], None);
5638 t.unblock("q1");
5639 assert_eq!(t.status, TaskStatus::Queued);
5640 }
5641
5642 #[test]
5643 fn a_pre_schema_4_blocked_record_with_hold_evidence_restores_to_held() {
5644 let mut t = task("legacy record, held before it was blocked");
5650 t.hold_source = Some(HoldSource::Machine);
5651 t.hold_reason = Some("legacy hold reason".to_owned());
5652 t.status = TaskStatus::Blocked;
5653 t.blocked_by = vec!["q1".to_owned()];
5654 t.blocked_from = None;
5655
5656 t.unblock("q1");
5657 assert_eq!(t.status, TaskStatus::Held);
5658 }
5659
5660 #[test]
5661 fn a_pre_schema_4_blocked_record_with_no_hold_evidence_restores_to_queued() {
5662 let mut t = task("legacy record, ordinary dependency block");
5663 t.status = TaskStatus::Blocked;
5664 t.blocked_by = vec!["dep".to_owned()];
5665 t.blocked_from = None;
5666
5667 t.unblock("dep");
5668 assert_eq!(t.status, TaskStatus::Queued);
5669 }
5670
5671 #[test]
5672 fn answering_a_question_is_recorded_and_survives_a_release() {
5673 let mut t = task("asked something");
5674 t.block(vec!["q1".to_owned()], Some("which backend?".to_owned()));
5675 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
5676 t.unblock("q1");
5677 assert_eq!(t.status, TaskStatus::Queued);
5678 assert_eq!(t.answers.len(), 1);
5679 assert_eq!(t.answers[0].answer, "SQLite");
5680
5681 t.release();
5685 assert_eq!(t.answers.len(), 1, "the answer is not lost on release");
5686 }
5687
5688 #[test]
5689 fn resumption_review_branch_requires_unchanged_authored_criteria() {
5690 for source in ["cli", "web"] {
5691 let mut t = task("review old candidate");
5692 t.request_review("candidate-A".into());
5693 t.hold_for_handover(Some("candidate-A".into()), "handover refused".into());
5694 let mut unchanged = t.clone();
5695 unchanged.release_operator(source, None);
5696 assert_eq!(unchanged.review_branch.as_deref(), Some("candidate-A"));
5697 t.edit(
5698 "review approved head".into(),
5699 "Reuse measured PR head B; fix Clippy; review".into(),
5700 )
5701 .unwrap();
5702 t.release_operator(source, None);
5703 assert!(t.review_branch.is_none());
5704 assert!(t.review_instruction.is_none());
5705 let mut legacy = unchanged;
5707 legacy.review_instruction = None;
5708 legacy.hold_for_handover(None, "still checked out".into());
5709 legacy
5710 .edit("new plan".into(), "Reuse measured PR head B".into())
5711 .unwrap();
5712 legacy.release_operator(source, None);
5713 assert!(legacy.review_branch.is_none());
5714 }
5715 }
5716
5717 #[test]
5718 fn a_refused_handover_keeps_the_review_branch_across_release() {
5719 let mut t = task("refused takeover");
5720 t.start("run-1".to_owned());
5721 t.hold_for_handover(Some("magi/eba2/A".to_owned()), "checked out".to_owned());
5722 assert_eq!(t.status, TaskStatus::Held);
5723 assert_eq!(t.attempts, 1);
5724 t.release();
5725 assert_eq!(t.status, TaskStatus::Queued);
5726 assert_eq!(t.attempts, 0);
5727 assert_eq!(t.review_branch.as_deref(), Some("magi/eba2/A"));
5728
5729 t.hold_for_handover(None, "again".to_owned());
5731 t.requeue();
5732 assert!(t.review_branch.is_none());
5733
5734 let mut m = task("manual");
5736 m.review_branch = Some("magi/x/A".to_owned());
5737 m.hold_manual(None);
5738 m.release();
5739 assert!(m.review_branch.is_none());
5740 }
5741
5742 #[test]
5743 fn requesting_review_requeues_the_task_and_remembers_the_branch() {
5744 let mut t = task("blocked run with a surviving branch");
5745 t.start("run-1".to_owned());
5746 t.fail("blocked with major findings", 5);
5747 assert_eq!(t.status, TaskStatus::Failed);
5748
5749 t.request_review("magi/eba2/A".to_owned());
5750 assert_eq!(t.status, TaskStatus::Queued);
5751 assert_eq!(t.attempts, 0);
5752 assert_eq!(t.review_branch.as_deref(), Some("magi/eba2/A"));
5753
5754 t.release();
5756 assert!(t.review_branch.is_none());
5757 }
5758
5759 #[test]
5760 fn conductor_requeue_but_not_an_ordinary_release_forces_a_fresh_start() {
5761 let mut t = task("retry");
5762 t.start("run-1".to_owned());
5763 t.requeue();
5764 assert!(t.fresh_start);
5765
5766 t.release();
5767 assert!(!t.fresh_start);
5768 }
5769
5770 #[test]
5771 fn urgent_only_changes_queued_or_held_and_preserves_settings() {
5772 for status in [
5773 TaskStatus::Queued,
5774 TaskStatus::Held,
5775 TaskStatus::Running,
5776 TaskStatus::Done,
5777 TaskStatus::Failed,
5778 TaskStatus::Blocked,
5779 TaskStatus::Parked,
5780 ] {
5781 let mut t = task("urgent settings");
5782 t.status = status;
5783 t.attempts = 2;
5784 t.hold_reason = Some("waiting".into());
5785 t.priority = 7;
5786 t.interrupt = true;
5787 let before = serde_json::to_value(&t).unwrap();
5788 for urgent in [true, true, false, false] {
5789 let result = t.set_urgent(urgent);
5790 let mut expected = before.clone();
5791 if matches!(status, TaskStatus::Queued | TaskStatus::Held) {
5792 result.unwrap();
5793 expected["urgent"] = urgent.into();
5794 } else {
5795 let error = result.unwrap_err().to_string();
5796 assert!(error.contains(status.as_str()), "{error}");
5797 assert!(error.contains("queued or held"), "{error}");
5798 }
5799 assert_eq!(serde_json::to_value(&t).unwrap(), expected);
5800 }
5801 }
5802 }
5803
5804 #[test]
5805 fn priority_can_be_changed_while_queued_but_not_while_running() {
5806 let mut t = task("reprioritise me");
5807 t.set_priority(5).unwrap();
5808 assert_eq!(t.priority, 5);
5809
5810 t.start("run-1".to_owned());
5811 let err = t.set_priority(9).unwrap_err().to_string();
5812 assert!(err.contains("running"), "{err}");
5813 assert_eq!(t.priority, 5, "the rejected write must not partially apply");
5814 }
5815
5816 #[test]
5817 fn interrupt_can_be_marked_while_queued_but_not_while_running() {
5818 let mut t = task("interrupt me");
5819 assert!(!t.interrupt, "off unless asked, same as any other task");
5820
5821 t.set_interrupt(true).unwrap();
5822 assert!(t.interrupt);
5823
5824 t.start("run-1".to_owned());
5825 assert!(
5826 !t.interrupt,
5827 "the mark is one-shot: dispatching the task fulfils it, \
5828 whatever the run that follows ends up doing"
5829 );
5830 let err = t.set_interrupt(true).unwrap_err().to_string();
5831 assert!(err.contains("running"), "{err}");
5832 t.set_interrupt(false).unwrap();
5835 assert!(!t.interrupt);
5836 }
5837
5838 #[test]
5842 fn a_failed_run_does_not_leave_the_task_still_marked_to_interrupt() {
5843 let mut t = task("interrupt me");
5844 t.set_interrupt(true).unwrap();
5845 t.start("run-1".to_owned());
5846 t.fail("mock failure", 5);
5847 assert_eq!(t.status, TaskStatus::Failed);
5848 assert!(
5849 !t.interrupt,
5850 "one attempt already spent the mark; a retry is an ordinary \
5851 requeue, not a fresh interrupt request"
5852 );
5853 }
5854
5855 #[test]
5856 fn changing_priority_moves_a_task_ahead_in_the_real_queue_order() {
5857 let (_dir, q) = queue();
5858 let mut a = task("first filed");
5859 let mut b = task("second filed");
5860 a.id = "20260101-000001-aaaa".to_owned();
5861 b.id = "20260101-000002-bbbb".to_owned();
5862 q.put(&mut a).unwrap();
5863 q.put(&mut b).unwrap();
5864
5865 assert_eq!(
5866 q.next_runnable().unwrap().id,
5867 a.id,
5868 "with equal priority the older task goes first, so a burst of \
5869 new work cannot starve it"
5870 );
5871 assert_eq!(
5872 q.list()[0].id,
5873 b.id,
5874 "but the list an operator reads is newest first, the same as \
5875 before priority existed - a's turn to run does not make it the \
5876 newest task"
5877 );
5878
5879 let mut a = q.get(&a.id).unwrap();
5880 a.set_priority(10).unwrap();
5881 q.put(&mut a).unwrap();
5882
5883 assert_eq!(
5884 q.next_runnable().unwrap().id,
5885 a.id,
5886 "a raised priority must be reflected the moment it is saved"
5887 );
5888 assert_eq!(
5892 q.list()[0].id,
5893 a.id,
5894 "the raised task must sort first in the list an operator reads, \
5895 not only in next_runnable's own ordering"
5896 );
5897 }
5898
5899 #[test]
5900 fn editing_replaces_title_and_instruction_but_keeps_identity_and_history() {
5901 let mut t = Task::new(
5902 "old title".to_owned(),
5903 "old instruction".to_owned(),
5904 PathBuf::from("/repo"),
5905 Source::Agent {
5906 run: "20260101-000000-beef".to_owned(),
5907 node: "implement".to_owned(),
5908 },
5909 );
5910 let id = t.id.clone();
5911 let created_at = t.created_at;
5912 t.runs.push("20260101-000000-beef".to_owned());
5913
5914 t.edit("new title".to_owned(), "new instruction".to_owned())
5915 .unwrap();
5916
5917 assert_eq!(t.title, "new title");
5918 assert_eq!(t.instruction, "new instruction");
5919 assert_eq!(t.id, id, "editing must not mint a new id");
5920 assert_eq!(t.created_at, created_at);
5921 assert_eq!(
5922 t.source,
5923 Source::Agent {
5924 run: "20260101-000000-beef".to_owned(),
5925 node: "implement".to_owned(),
5926 },
5927 "editing must not turn agent attribution into human"
5928 );
5929 assert_eq!(t.runs, ["20260101-000000-beef"]);
5930 }
5931
5932 #[test]
5933 fn editing_is_refused_once_a_task_is_running_or_finished() {
5934 let mut running = task("in flight");
5935 running.start("run-1".to_owned());
5936 let err = running
5937 .edit("x".to_owned(), "y".to_owned())
5938 .unwrap_err()
5939 .to_string();
5940 assert!(err.contains("running"), "{err}");
5941
5942 let mut done = task("finished");
5943 done.succeed(completion(&done));
5944 let err = done
5945 .edit("x".to_owned(), "y".to_owned())
5946 .unwrap_err()
5947 .to_string();
5948 assert!(err.contains("done"), "{err}");
5949
5950 let mut queued = task("waiting");
5952 queued.edit("x".to_owned(), "y".to_owned()).unwrap();
5953 let mut held = task("parked");
5954 held.hold_machine(None);
5955 held.edit("x".to_owned(), "y".to_owned()).unwrap();
5956 }
5957
5958 #[test]
5959 fn a_task_recorded_without_a_hold_reason_still_reads_as_none() {
5960 let (_dir, q) = queue();
5961 let path = q.path_of("20260101-000000-aaaa");
5962 std::fs::create_dir_all(q.root()).unwrap();
5963 std::fs::write(
5964 &path,
5965 serde_json::json!({
5966 "schema": SCHEMA,
5967 "id": "20260101-000000-aaaa",
5968 "title": "from before hold reasons existed",
5969 "instruction": "from before hold reasons existed",
5970 "repo": ".",
5971 "source": { "kind": "human" },
5972 "status": "held",
5973 "created_at": Timestamp::now().to_string(),
5974 "updated_at": Timestamp::now().to_string(),
5975 })
5976 .to_string(),
5977 )
5978 .unwrap();
5979
5980 let task = q.get("20260101-000000-aaaa").expect("must still read");
5981 assert!(task.hold_reason.is_none());
5982 assert!(task.operator_held());
5983 }
5984
5985 #[test]
5986 fn a_legacy_reasoned_hold_defaults_to_operator_protection() {
5987 let (_dir, q) = queue();
5988 let path = q.path_of("20260101-000000-bbbb");
5989 std::fs::create_dir_all(q.root()).unwrap();
5990 std::fs::write(
5991 &path,
5992 serde_json::json!({
5993 "schema": 2,
5994 "id": "20260101-000000-bbbb",
5995 "title": "old manual recovery",
5996 "instruction": "old manual recovery",
5997 "repo": ".",
5998 "source": { "kind": "human" },
5999 "status": "held",
6000 "hold_reason": "active manual recovery run20260912-224242-daf5",
6001 "created_at": Timestamp::now().to_string(),
6002 "updated_at": Timestamp::now().to_string(),
6003 })
6004 .to_string(),
6005 )
6006 .unwrap();
6007
6008 let task = q.get("20260101-000000-bbbb").expect("must still read");
6009 assert_eq!(task.hold_source, None);
6010 assert!(task.operator_held());
6011 }
6012
6013 #[test]
6014 fn a_task_recorded_without_a_diagnostic_still_reads_as_none() {
6015 let (_dir, q) = queue();
6016 let path = q.path_of("20260101-000000-aaaa");
6017 std::fs::create_dir_all(q.root()).unwrap();
6018 std::fs::write(
6019 &path,
6020 serde_json::json!({
6021 "schema": SCHEMA,
6022 "id": "20260101-000000-aaaa",
6023 "title": "from before diagnostics existed",
6024 "instruction": "from before diagnostics existed",
6025 "repo": ".",
6026 "source": { "kind": "human" },
6027 "status": "held",
6028 "created_at": Timestamp::now().to_string(),
6029 "updated_at": Timestamp::now().to_string(),
6030 })
6031 .to_string(),
6032 )
6033 .unwrap();
6034
6035 let task = q.get("20260101-000000-aaaa").expect("must still read");
6036 assert!(task.diagnostic.is_none());
6037 }
6038
6039 #[test]
6040 fn a_schema_1_task_with_no_blocking_fields_still_reads() {
6041 let (_dir, q) = queue();
6045 let path = q.path_of("20260101-000000-aaaa");
6046 std::fs::create_dir_all(q.root()).unwrap();
6047 std::fs::write(
6048 &path,
6049 serde_json::json!({
6050 "schema": 1,
6051 "id": "20260101-000000-aaaa",
6052 "title": "from before blocking existed",
6053 "instruction": "from before blocking existed",
6054 "repo": ".",
6055 "source": { "kind": "human" },
6056 "status": "queued",
6057 "created_at": Timestamp::now().to_string(),
6058 "updated_at": Timestamp::now().to_string(),
6059 })
6060 .to_string(),
6061 )
6062 .unwrap();
6063
6064 let task = q.get("20260101-000000-aaaa").expect("must still read");
6065 assert!(task.blocked_by.is_empty());
6066 assert!(task.block_reason.is_none());
6067 assert!(task.answers.is_empty());
6068 assert!(task.review_branch.is_none());
6069 }
6070
6071 #[test]
6072 fn releasing_or_finishing_a_task_clears_its_stale_diagnostic() {
6073 let mut held = task("diagnosed");
6078 held.start("run-1".to_owned());
6079 held.fail("gate red", 1);
6080 held.diagnostic = Some("cargo test failed: ...".to_owned());
6081 assert_eq!(held.status, TaskStatus::Held);
6082
6083 held.release();
6084 assert!(held.diagnostic.is_none());
6085
6086 held.diagnostic = Some("cargo test failed: ...".to_owned());
6087 held.succeed(completion(&held));
6088 assert!(held.diagnostic.is_none());
6089 }
6090
6091 #[test]
6092 fn failing_a_task_always_clears_whatever_diagnostic_it_carried() {
6093 let mut t = task("retried");
6094 t.start("run-1".to_owned());
6095 t.diagnostic = Some("stale evidence from a previous hold".to_owned());
6096 t.fail("unrelated config error", 5);
6097 assert_eq!(t.status, TaskStatus::Failed);
6098 assert!(
6099 t.diagnostic.is_none(),
6100 "fail() must not let an old diagnostic outlive the run that produced it"
6101 );
6102 }
6103
6104 #[test]
6105 fn a_claim_is_exclusive_and_releases_on_drop() {
6106 let (_dir, q) = queue();
6107 let mut t = task("contended");
6108 q.put(&mut t).unwrap();
6109
6110 let held = q.claim(&t.id).unwrap();
6111 assert!(
6112 q.claim(&t.id).is_err(),
6113 "two daemons must not drive one task into two runs"
6114 );
6115 drop(held);
6116 assert!(q.claim(&t.id).is_ok(), "a released claim is reclaimable");
6117 }
6118
6119 #[test]
6120 fn a_round_trip_survives_disk() {
6121 let (_dir, q) = queue();
6122 let mut t = Task::new(
6123 "titled".to_owned(),
6124 "body".to_owned(),
6125 PathBuf::from("/repo"),
6126 Source::Agent {
6127 run: "20260101-000000-beef".to_owned(),
6128 node: "implement".to_owned(),
6129 },
6130 );
6131 t.priority = 3;
6132 q.put(&mut t).unwrap();
6133
6134 let back = q.get(&t.id).unwrap();
6135 assert_eq!(back.id, t.id);
6136 assert_eq!(back.priority, 3);
6137 assert_eq!(back.source.label(), "implement@beef");
6138 assert_eq!(q.get(t.short()).unwrap().id, t.id);
6140 }
6141
6142 #[test]
6143 fn an_unreadable_task_does_not_take_the_queue_down() {
6144 let (_dir, q) = queue();
6145 let mut t = task("fine");
6146 q.put(&mut t).unwrap();
6147 std::fs::write(q.root().join("broken.json"), "{ not json").unwrap();
6148
6149 let listed = q.list();
6150 assert_eq!(listed.len(), 1, "the readable task still lists");
6151 assert_eq!(listed[0].id, t.id);
6152 }
6153
6154 #[test]
6155 fn a_task_recorded_without_a_solo_field_still_reads_as_not_solo() {
6156 let (_dir, q) = queue();
6157 let path = q.path_of("20260101-000000-aaaa");
6158 std::fs::create_dir_all(q.root()).unwrap();
6159 std::fs::write(
6160 &path,
6161 serde_json::json!({
6162 "schema": SCHEMA,
6163 "id": "20260101-000000-aaaa",
6164 "title": "from before solo existed",
6165 "instruction": "from before solo existed",
6166 "repo": ".",
6167 "source": { "kind": "human" },
6168 "status": "queued",
6169 "created_at": Timestamp::now().to_string(),
6170 "updated_at": Timestamp::now().to_string(),
6171 })
6172 .to_string(),
6173 )
6174 .unwrap();
6175
6176 let task = q.get("20260101-000000-aaaa").expect("must still read");
6177 assert!(!task.solo, "a queue file with no `solo` field means false");
6178 }
6179
6180 #[test]
6181 fn a_task_recorded_without_an_urgent_field_still_reads_as_not_urgent() {
6182 let (_dir, q) = queue();
6183 let path = q.path_of("20260101-000000-bbbb");
6184 std::fs::create_dir_all(q.root()).unwrap();
6185 std::fs::write(
6186 &path,
6187 serde_json::json!({
6188 "schema": SCHEMA,
6189 "id": "20260101-000000-bbbb",
6190 "title": "from before urgent existed",
6191 "instruction": "from before urgent existed",
6192 "repo": ".",
6193 "source": { "kind": "human" },
6194 "status": "queued",
6195 "created_at": Timestamp::now().to_string(),
6196 "updated_at": Timestamp::now().to_string(),
6197 })
6198 .to_string(),
6199 )
6200 .unwrap();
6201
6202 let task = q.get("20260101-000000-bbbb").expect("must still read");
6203 assert!(
6204 !task.urgent,
6205 "a queue file with no `urgent` field means false, same as `solo`"
6206 );
6207 }
6208
6209 #[test]
6210 fn a_task_from_a_future_schema_is_refused_rather_than_guessed_at() {
6211 let (_dir, q) = queue();
6212 let mut t = task("from the future");
6213 q.put(&mut t).unwrap();
6214 let path = q.path_of(&t.id);
6215 let body = std::fs::read_to_string(&path)
6216 .unwrap()
6217 .replace(&format!("\"schema\": {SCHEMA}"), "\"schema\": 99");
6218 std::fs::write(&path, body).unwrap();
6219
6220 let err = q.get(&t.id).unwrap_err().to_string();
6221 assert!(err.contains("schema 99"), "{err}");
6222 }
6223
6224 #[test]
6225 fn revision_moves_when_the_queue_changes() {
6226 let (_dir, q) = queue();
6227 assert_eq!(q.revision(), 0, "an empty queue has no revision");
6228 let mut t = task("first");
6229 q.put(&mut t).unwrap();
6230 assert!(q.revision() > 0, "a written task moves the revision");
6231 }
6232
6233 #[test]
6234 fn revision_moves_when_deleting_an_older_task() {
6235 let (dir, q) = queue();
6236 let questions = Questions::at(dir.path().join("questions"));
6237 let mut t1 = task("older");
6238 q.put(&mut t1).unwrap();
6239 std::thread::sleep(std::time::Duration::from_millis(10));
6241 let mut t2 = task("newer");
6242 q.put(&mut t2).unwrap();
6243
6244 let rev_before = q.revision();
6245 q.remove(&t1.id, false, &questions).unwrap();
6246 let rev_after = q.revision();
6247
6248 assert_ne!(
6249 rev_before, rev_after,
6250 "deleting an older task must change the revision so other clients see the deletion"
6251 );
6252 }
6253
6254 #[test]
6255 fn removing_a_task_takes_it_out_of_the_listing() {
6256 let (dir, q) = queue();
6257 let questions = Questions::at(dir.path().join("questions"));
6258 let mut t = task("delete me");
6259 q.put(&mut t).unwrap();
6260 let removed = q.remove(t.short(), false, &questions).unwrap();
6261 assert_eq!(removed.id, t.id, "a prefix resolves before deleting");
6262 assert!(removed.released.is_empty() && removed.still_blocked.is_empty());
6263 assert!(q.list().is_empty());
6264 assert!(
6265 q.remove(&t.id, false, &questions).is_err(),
6266 "removing twice is an error"
6267 );
6268 }
6269
6270 #[test]
6271 fn removing_a_task_takes_its_stale_lock_with_it() {
6272 let (dir, q) = queue();
6273 let questions = Questions::at(dir.path().join("questions"));
6274 let mut t = task("interrupted");
6275 q.put(&mut t).unwrap();
6276
6277 let claim = q.claim(&t.id).unwrap();
6280 std::mem::forget(claim);
6281 assert!(
6282 q.claim(&t.id).is_err(),
6283 "the orphaned lock is what makes the task look claimed"
6284 );
6285
6286 let err = q.remove(&t.id, true, &questions).unwrap_err().to_string();
6288 assert!(err.contains("live daemon"), "{err}");
6289 assert!(q.get(&t.id).is_ok(), "a refused delete keeps the task");
6290
6291 q.remove(&t.id, false, &questions).unwrap();
6293 assert!(q.list().is_empty());
6294 let mut again = task("interrupted");
6295 again.id = t.id.clone();
6296 q.put(&mut again).unwrap();
6297 assert!(
6298 q.claim(&t.id).is_ok(),
6299 "a task that comes back must be claimable, which a left-behind lock would prevent"
6300 );
6301 }
6302
6303 fn notices_of(dir: &Path) -> Vec<crate::notices::Notice> {
6304 crate::notices::Notices::at(dir.join("notifications")).list()
6305 }
6306
6307 #[test]
6308 fn removing_a_sole_dependency_releases_the_dependent_without_a_hold() {
6309 let (dir, q) = queue();
6310 let questions = Questions::at(dir.path().join("questions"));
6311 let mut dep = task("dependency");
6312 q.put(&mut dep).unwrap();
6313 let mut blocked = task("waiting");
6314 blocked.block(vec![dep.id.clone()], Some("waits".to_owned()));
6315 q.put(&mut blocked).unwrap();
6316
6317 let removed = q.remove(&dep.id, false, &questions).unwrap();
6318 assert_eq!(removed.released, [blocked.id.clone()]);
6319 assert!(removed.still_blocked.is_empty());
6320
6321 let after = q.get(&blocked.id).unwrap();
6322 assert_eq!(after.status, TaskStatus::Queued);
6323 assert!(after.blocked_by.is_empty());
6324 assert!(after.block_reason.is_none());
6325 let notes = notices_of(dir.path());
6326 assert_eq!(notes.len(), 1, "{notes:?}");
6327 assert_eq!(notes[0].severity, crate::notices::Severity::Info);
6328 assert_eq!(
6329 notes[0].link,
6330 Some(crate::notices::Link::Task {
6331 id: blocked.id.clone(),
6332 })
6333 );
6334 }
6335
6336 #[test]
6337 fn removing_one_of_two_dependencies_keeps_the_other() {
6338 let (dir, q) = queue();
6339 let questions = Questions::at(dir.path().join("questions"));
6340 let mut dep = task("dependency");
6341 q.put(&mut dep).unwrap();
6342 let mut other = task("other");
6343 q.put(&mut other).unwrap();
6344 let mut blocked = task("waiting");
6345 blocked.block(
6346 vec![dep.id.clone(), other.id.clone()],
6347 Some("waits on both".to_owned()),
6348 );
6349 q.put(&mut blocked).unwrap();
6350
6351 let removed = q.remove(&dep.id, false, &questions).unwrap();
6352 assert!(removed.released.is_empty());
6353 assert_eq!(removed.still_blocked, [blocked.id.clone()]);
6354
6355 let after = q.get(&blocked.id).unwrap();
6356 assert_eq!(after.status, TaskStatus::Blocked);
6357 assert_eq!(after.blocked_by, [other.id.clone()]);
6358 assert!(missing_blockers(&q, &questions, &after.blocked_by).is_empty());
6361 }
6362
6363 #[test]
6364 fn a_dependency_deleted_before_its_dependents_were_rewritten_is_released_later() {
6365 let (dir, q) = queue();
6366 let questions = Questions::at(dir.path().join("questions"));
6367 let mut dep = task("dependency");
6368 q.put(&mut dep).unwrap();
6369 let mut blocked = task("waiting");
6370 blocked.block(vec![dep.id.clone()], None);
6371 q.put(&mut blocked).unwrap();
6372
6373 let claim = q.claim(&blocked.id).unwrap();
6375 let removed = q.remove(&dep.id, false, &questions).unwrap();
6376 assert!(removed.released.is_empty());
6377 drop(claim);
6378
6379 let mut task = q.get(&blocked.id).unwrap();
6380 assert_eq!(task.status, TaskStatus::Blocked);
6381 assert!(missing_blockers(&q, &questions, &task.blocked_by).is_empty());
6382 assert_eq!(
6383 q.apply_deleted_blockers(&mut task, &questions),
6384 [dep.id.clone()]
6385 );
6386 assert_eq!(task.status, TaskStatus::Queued);
6387 }
6388
6389 #[test]
6390 fn dependency_resolution_short_deleted_reference_releases_only_its_waiters() {
6391 let (dir, q) = queue();
6392 let questions = Questions::at(dir.path().join("questions"));
6393 let mut dep = task("dependency");
6394 dep.id = "20261013-193611-ca5b".into();
6395 q.put(&mut dep).unwrap();
6396 let mut waiting = task("waiting");
6397 waiting.block(vec!["ca5b".into()], None);
6398 q.put(&mut waiting).unwrap();
6399 q.remove(&dep.id, false, &questions).unwrap();
6400 assert_eq!(q.get(&waiting.id).unwrap().status, TaskStatus::Queued);
6401 assert_eq!(
6402 dependency(&q, &questions, "ca5b"),
6403 Dependency::Deleted(dep.id)
6404 );
6405 }
6406
6407 #[test]
6408 fn dependency_resolution_preserves_cross_store_ambiguity_and_exact_ids() {
6409 let (dir, queue) = queue();
6410 let questions = Questions::at(dir.path().join("questions"));
6411 let mut dep = task("dependency");
6412 dep.id = "20261013-193611-ca5b".into();
6413 queue.put(&mut dep).unwrap();
6414 std::fs::create_dir_all(questions.root()).unwrap();
6415 let question_id = "20261014-193611-ca5b";
6416 std::fs::write(questions.path_of(question_id), "unreadable question").unwrap();
6417 assert_eq!(questions.resolve_id("ca5b").unwrap(), question_id);
6418 assert_eq!(
6419 dependency(&queue, &questions, "ca5b"),
6420 Dependency::Ambiguous
6421 );
6422 assert_eq!(
6423 dependency(&queue, &questions, &dep.id),
6424 Dependency::Task(dep.id)
6425 );
6426 assert_eq!(
6427 dependency(&queue, &questions, question_id),
6428 Dependency::Question(question_id.into())
6429 );
6430 assert_eq!(
6431 dependency(&queue, &questions, "missing"),
6432 Dependency::Missing
6433 );
6434 }
6435
6436 #[test]
6437 fn dependency_resolution_directory_errors_are_unknown_not_missing() {
6438 let dir = tempfile::tempdir().unwrap();
6439 let q = Queue::at(dir.path().join("not-a-directory"));
6440 std::fs::write(q.root(), "file").unwrap();
6441 let questions = Questions::at(dir.path().join("questions"));
6442 assert_eq!(dependency(&q, &questions, "ca5b"), Dependency::Unknown);
6443 assert!(missing_blockers(&q, &questions, &["ca5b".into()]).is_empty());
6444 }
6445
6446 #[test]
6447 fn a_dependency_without_a_tombstone_is_still_missing() {
6448 let (dir, q) = queue();
6449 let questions = Questions::at(dir.path().join("questions"));
6450 let mut dep = task("dependency");
6451 q.put(&mut dep).unwrap();
6452 std::fs::remove_file(q.path_of(&dep.id)).unwrap();
6453 assert_eq!(
6454 missing_blockers(&q, &questions, std::slice::from_ref(&dep.id)),
6455 [dep.id.clone()]
6456 );
6457 assert!(deleted_blockers(&q, &questions, std::slice::from_ref(&dep.id)).is_empty());
6458 }
6459
6460 #[test]
6461 fn a_held_dependent_is_left_alone_by_a_dependency_deletion() {
6462 let mut t = task("held");
6463 t.hold_machine(Some("because".to_owned()));
6464 t.blocked_by = vec!["gone".to_owned()];
6465 assert!(!t.dependency_deleted("gone"));
6466 assert_eq!(t.status, TaskStatus::Held);
6467 }
6468
6469 #[test]
6470 fn a_failed_record_removal_takes_the_tombstone_back() {
6471 let (_dir, q) = queue();
6472 let mut t = task("stays");
6473 q.put(&mut t).unwrap();
6474 q.write_tombstone(&t.id).unwrap();
6475 let err = q.remove_record_with_attachments(&t.id, |_| Err(std::io::Error::other("nope")));
6476 assert!(err.is_err());
6477 assert!(!q.was_deleted(&t.id));
6480 }
6481
6482 fn source_file(dir: &Path, name: &str, body: &str) -> PathBuf {
6483 let p = dir.join(name);
6484 std::fs::write(&p, body).unwrap();
6485 p
6486 }
6487
6488 #[test]
6489 fn an_attachment_copy_survives_deleting_its_source() {
6490 let (dir, q) = queue();
6491 let src = source_file(dir.path(), "shot.png", "pixels");
6492 let mut t = task("with a picture");
6493 let names = q.attach(&mut t, std::slice::from_ref(&src)).unwrap();
6494 q.put(&mut t).unwrap();
6495 std::fs::remove_file(&src).unwrap();
6496 assert_eq!(names, ["shot.png"]);
6497 let loaded = q.get(&t.id).unwrap();
6498 let paths = q.attachment_paths(&loaded);
6499 assert_eq!(paths.len(), 1);
6500 assert_eq!(std::fs::read_to_string(&paths[0]).unwrap(), "pixels");
6501 }
6502
6503 #[test]
6504 fn attachment_names_that_could_traverse_or_are_odd_are_refused() {
6505 let (dir, q) = queue();
6506 let mut t = task("bad names");
6507 for name in ["a..b.png", ".hidden", "with space.png", "-x.png"] {
6508 let src = source_file(dir.path(), name, "x");
6509 assert!(
6510 q.attach(&mut t, &[src]).is_err(),
6511 "`{name}` must be refused"
6512 );
6513 }
6514 assert!(!crate::ask::valid_asset_name("C:foo.png"));
6518 #[cfg(not(windows))]
6519 {
6520 let src = source_file(dir.path(), "C:foo.png", "x");
6521 assert!(q.attach(&mut t, &[src]).is_err());
6522 }
6523 let long = format!("{}.png", "a".repeat(70));
6524 let src = source_file(dir.path(), &long, "x");
6525 assert!(q.attach(&mut t, &[src]).is_err());
6526 assert!(t.attachments.is_empty());
6527 assert!(!q.attachments_dir(&t.id).exists());
6528 }
6529
6530 #[test]
6531 fn a_taken_attachment_name_is_numbered_not_overwritten() {
6532 let (dir, q) = queue();
6533 let a = source_file(dir.path(), "shot.png", "one");
6534 let sub = dir.path().join("other");
6535 std::fs::create_dir_all(&sub).unwrap();
6536 let b = source_file(&sub, "shot.png", "two");
6537 let mut t = task("collision");
6538 q.attach(&mut t, &[a]).unwrap();
6539 q.attach(&mut t, &[b]).unwrap();
6540 assert_eq!(t.attachments, ["shot.png", "shot-2.png"]);
6541 let paths = q.attachment_paths(&t);
6542 assert_eq!(std::fs::read_to_string(&paths[0]).unwrap(), "one");
6543 assert_eq!(std::fs::read_to_string(&paths[1]).unwrap(), "two");
6544 }
6545
6546 #[test]
6547 fn a_renumbered_name_stays_inside_the_length_bound() {
6548 let (dir, q) = queue();
6549 let name = format!("{}.png", "a".repeat(60));
6550 assert_eq!(name.len(), 64);
6551 let a = source_file(dir.path(), &name, "one");
6552 let sub = dir.path().join("other");
6553 std::fs::create_dir_all(&sub).unwrap();
6554 let b = source_file(&sub, &name, "two");
6555 let mut t = task("long");
6556 q.attach(&mut t, &[a, b]).unwrap();
6557 assert_eq!(t.attachments.len(), 2);
6558 assert!(
6559 t.attachments
6560 .iter()
6561 .all(|n| crate::ask::valid_asset_name(n))
6562 );
6563 assert!(t.attachments[1].ends_with("-2.png"));
6564 }
6565
6566 #[test]
6567 fn a_failed_attach_keeps_existing_attachments_and_leaves_no_partial_copy() {
6568 let (dir, q) = queue();
6569 let good = source_file(dir.path(), "good.png", "ok");
6570 let mut t = task("partial");
6571 q.attach(&mut t, &[good]).unwrap();
6572 let more = source_file(dir.path(), "more.png", "ok");
6573 let missing = dir.path().join("missing.png");
6574 assert!(q.attach(&mut t, &[more, missing]).is_err());
6575 assert_eq!(t.attachments, ["good.png"]);
6576 let on_disk: Vec<_> = std::fs::read_dir(q.attachments_dir(&t.id))
6577 .unwrap()
6578 .flatten()
6579 .collect();
6580 assert_eq!(on_disk.len(), 1);
6581 }
6582
6583 fn block_put(q: &Queue, t: &Task) -> PathBuf {
6585 let tmp = q.path_of(&t.id).with_extension("json.tmp");
6586 std::fs::create_dir_all(&tmp).unwrap();
6587 tmp
6588 }
6589
6590 #[test]
6591 fn a_failed_put_leaves_no_new_attachment_directory() {
6592 let (dir, q) = queue();
6593 let mut t = task("fresh");
6594 let tmp = block_put(&q, &t);
6595 let src = source_file(dir.path(), "shot.png", "x");
6596 assert!(q.attach_and_put(&mut t, &[src]).is_err());
6597 assert!(t.attachments.is_empty());
6598 assert!(!q.attachments_dir(&t.id).exists());
6599 assert!(!q.path_of(&t.id).exists());
6600 std::fs::remove_dir(tmp).unwrap();
6601 }
6602
6603 #[test]
6604 fn a_failed_put_removes_only_the_copy_it_just_made() {
6605 let (dir, q) = queue();
6606 let mut t = task("edited");
6607 let first = source_file(dir.path(), "first.png", "1");
6608 q.attach_and_put(&mut t, &[first]).unwrap();
6609 block_put(&q, &t);
6610 let second = source_file(dir.path(), "second.png", "2");
6611 assert!(q.attach_and_put(&mut t, &[second]).is_err());
6612 assert_eq!(t.attachments, ["first.png"]);
6613 let on_disk: Vec<_> = std::fs::read_dir(q.attachments_dir(&t.id))
6614 .unwrap()
6615 .flatten()
6616 .map(|e| e.file_name().to_string_lossy().into_owned())
6617 .collect();
6618 assert_eq!(on_disk, ["first.png"]);
6619 assert_eq!(q.get(&t.id).unwrap().attachments, ["first.png"]);
6620 }
6621
6622 #[test]
6623 fn a_leftover_removing_directory_is_swept_by_the_next_removal() {
6624 let (dir, q) = queue();
6625 let questions = Questions::at(dir.path().join("questions"));
6626 let gone = task("gone");
6627 let mut other = task("other");
6628 let mut live = task("live");
6629 q.put(&mut other).unwrap();
6630 q.put(&mut live).unwrap();
6631 let orphan = q.root.join(format!("{}.attachments.removing", gone.id));
6634 std::fs::create_dir_all(&orphan).unwrap();
6635 std::fs::write(orphan.join("shot.png"), "x").unwrap();
6636 let busy = q.root.join(format!("{}.attachments.removing", live.id));
6639 std::fs::create_dir_all(&busy).unwrap();
6640
6641 q.remove(&other.id, false, &questions).unwrap();
6642 assert!(!orphan.exists(), "an orphan is swept");
6643 assert!(busy.exists(), "a removal in progress is left alone");
6644 }
6645
6646 #[test]
6647 fn a_blocked_aside_rename_fails_the_removal_and_loses_nothing() {
6648 let (dir, q) = queue();
6649 let questions = Questions::at(dir.path().join("questions"));
6650 let mut t = task("stuck");
6651 let src = source_file(dir.path(), "shot.png", "x");
6652 q.attach_and_put(&mut t, &[src]).unwrap();
6653 let aside = q.root.join(format!("{}.attachments.removing", t.id));
6656 std::fs::create_dir_all(&aside).unwrap();
6657 std::fs::write(aside.join("old.png"), "o").unwrap();
6658 assert!(q.remove(&t.id, false, &questions).is_err());
6659 assert!(q.path_of(&t.id).exists());
6660 assert!(q.attachments_dir(&t.id).join("shot.png").is_file());
6661 }
6662
6663 #[test]
6664 fn a_failed_record_removal_puts_the_attachments_back() {
6665 let (dir, q) = queue();
6666 let mut t = task("rollback");
6667 let src = source_file(dir.path(), "shot.png", "x");
6668 q.attach_and_put(&mut t, &[src]).unwrap();
6669 let err = q
6670 .remove_record_with_attachments(&t.id, |_| {
6671 Err(std::io::Error::other("injected failure"))
6672 })
6673 .unwrap_err();
6674 assert!(format!("{err:#}").contains("injected failure"));
6675 assert!(q.path_of(&t.id).exists());
6676 assert!(q.attachments_dir(&t.id).join("shot.png").is_file());
6677 assert!(
6678 !q.root
6679 .join(format!("{}.attachments.removing", t.id))
6680 .exists()
6681 );
6682 }
6683
6684 #[test]
6685 fn editing_a_task_keeps_its_attachments() {
6686 let (dir, q) = queue();
6687 let src = source_file(dir.path(), "shot.png", "x");
6688 let mut t = task("editable");
6689 q.attach(&mut t, &[src]).unwrap();
6690 t.edit("new".to_owned(), "new text".to_owned()).unwrap();
6691 q.put(&mut t).unwrap();
6692 assert_eq!(q.get(&t.id).unwrap().attachments, ["shot.png"]);
6693 }
6694
6695 #[test]
6696 fn removing_a_task_deletes_its_attachments() {
6697 let (dir, q) = queue();
6698 let questions = Questions::at(dir.path().join("questions"));
6699 let src = source_file(dir.path(), "shot.png", "x");
6700 let mut t = task("doomed");
6701 q.attach(&mut t, &[src]).unwrap();
6702 q.put(&mut t).unwrap();
6703 assert!(q.attachments_dir(&t.id).is_dir());
6704 q.remove(&t.id, false, &questions).unwrap();
6705 assert!(!q.attachments_dir(&t.id).exists());
6706 assert!(q.list().is_empty());
6707 }
6708
6709 #[test]
6710 fn a_task_written_before_attachments_still_reads() {
6711 let (_dir, q) = queue();
6712 let mut t = task("old");
6713 q.put(&mut t).unwrap();
6714 let path = q.path_of(&t.id);
6715 let mut v: serde_json::Value =
6716 serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
6717 v.as_object_mut().unwrap().remove("attachments");
6718 std::fs::write(&path, v.to_string()).unwrap();
6719 assert!(q.get(&t.id).unwrap().attachments.is_empty());
6720 }
6721
6722 #[test]
6723 fn attachment_paths_are_absolute_even_when_the_root_is_relative() {
6724 let q = Queue::at(PathBuf::from("relative-queue"));
6725 let mut t = task("rel");
6726 t.attachments.push("shot.png".to_owned());
6727 let paths = q.attachment_paths(&t);
6728 assert!(paths[0].is_absolute(), "{}", paths[0].display());
6729 assert!(paths[0].ends_with(format!("{}.attachments/shot.png", t.id)));
6730 }
6731
6732 fn upgrade_parked(id: &str, started: &str) -> Task {
6733 let mut t = task(id);
6734 t.id = id.into();
6735 t.start(format!("run-{id}"));
6736 t.park("upgrade");
6737 t.record_pass_at(
6738 &format!("run-{id}"),
6739 0,
6740 Some(started.parse().unwrap()),
6741 1,
6742 Some(crate::run::ParkCause::Upgrade {
6743 from: "old".into(),
6744 to: None,
6745 }),
6746 );
6747 t
6748 }
6749
6750 #[test]
6751 fn upgrade_resume_order_follows_dispatch_claim_not_graph_start() {
6752 let stamp = |id: &str, dispatched: &str, started: &str| {
6754 let mut t = task(id);
6755 t.id = id.into();
6756 t.start(format!("run-{id}"));
6757 t.park("upgrade");
6758 t.dispatched_at = Some(dispatched.parse().unwrap());
6759 t.record_pass_at(
6760 &format!("run-{id}"),
6761 0,
6762 Some(started.parse().unwrap()),
6763 1,
6764 Some(crate::run::ParkCause::Upgrade {
6765 from: "old".into(),
6766 to: None,
6767 }),
6768 );
6769 t
6770 };
6771 let a = stamp("a", "2026-10-22T00:00:01Z", "2026-10-22T00:00:09Z");
6772 let b = stamp("b", "2026-10-22T00:00:02Z", "2026-10-22T00:00:03Z");
6773 assert!(dispatch_order(&a, &b).is_lt());
6774 }
6775
6776 #[test]
6777 fn upgrade_resume_order_survives_queue_reload_and_reversed_settlement() {
6778 let (_dir, q) = queue();
6779 let mut later = upgrade_parked("later", "2026-10-22T00:00:02Z");
6780 let mut earlier = upgrade_parked("earlier", "2026-10-22T00:00:01Z");
6781 earlier.priority = -10;
6782 let mut fresh = task("fresh");
6783 fresh.id = "newer".into();
6784 fresh.priority = 100;
6785 for t in [&mut fresh, &mut later, &mut earlier] {
6786 q.put(t).unwrap();
6787 }
6788 let reloaded = Queue::at(q.root().to_owned());
6789 let mut tasks = reloaded.list();
6790 tasks.sort_unstable_by(dispatch_order);
6791 assert_eq!(
6792 tasks.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
6793 vec!["earlier", "later", "newer"]
6794 );
6795 assert_eq!(reloaded.next_runnable().unwrap().id, "earlier");
6796 assert_eq!(reloaded.get("earlier").unwrap().attempts, 0);
6797 }
6798
6799 #[test]
6800 fn upgrade_resume_legacy_order_uses_settlement_and_id() {
6801 let mut a = upgrade_parked("a", "2026-10-22T00:00:02Z");
6802 let mut b = upgrade_parked("b", "2026-10-22T00:00:01Z");
6803 for t in [&mut a, &mut b] {
6804 let mut value = serde_json::to_value(&*t).unwrap();
6805 value["passes"][0]
6806 .as_object_mut()
6807 .unwrap()
6808 .remove("started_at");
6809 *t = serde_json::from_value(value).unwrap();
6810 }
6811 assert!(dispatch_order(&a, &b).is_lt());
6812 b.passes[0].settled_at = a.passes[0].settled_at;
6813 assert!(dispatch_order(&a, &b).is_lt());
6814 }
6815
6816 #[test]
6817 fn upgrade_resume_key_excludes_other_parks_and_explicit_task_changes() {
6818 let original = upgrade_parked("a", "2026-10-22T00:00:01Z");
6819 assert!(original.upgrade_resume_key().is_some());
6820 for cause in [
6821 crate::run::ParkCause::Operator,
6822 crate::run::ParkCause::Question,
6823 crate::run::ParkCause::Interrupt {
6824 reason: "interrupt".into(),
6825 },
6826 crate::run::ParkCause::Unspecified,
6827 ] {
6828 let mut t = original.clone();
6829 t.passes[0].parked = Some(cause);
6830 assert!(t.upgrade_resume_key().is_none());
6831 let mut fresh = task("fresh");
6832 fresh.priority = 1;
6833 assert!(dispatch_order(&fresh, &t).is_lt());
6834 }
6835 let mut t = original.clone();
6836 t.release();
6837 assert!(t.upgrade_resume_key().is_none());
6838 t.edit("edited".into(), "new instruction".into()).unwrap();
6839 assert!(t.upgrade_resume_key().is_none());
6840 let mut t = original.clone();
6841 t.requeue();
6842 t.status = TaskStatus::Parked;
6843 assert!(t.upgrade_resume_key().is_none());
6844 let mut t = original.clone();
6845 t.start("different-run".into());
6846 t.park("no upgrade");
6847 assert!(t.upgrade_resume_key().is_none());
6848 }
6849
6850 #[test]
6851 fn explicitly_resumed_older_run_becomes_current_without_duplicate_history() {
6852 let dir = tempfile::tempdir().unwrap();
6853 let q = Queue::at(dir.path().join("queue"));
6854 let mut t = task("resume");
6855 t.start("A".into());
6856 t.record_pass("A", 0, 1, None);
6857 t.start("B".into());
6858 q.put(&mut t).unwrap();
6859 assert_eq!(t.runs, vec!["A", "B"]);
6860 t.start("A".into());
6861 t.record_pass("A", 1, 3, None);
6862 q.put(&mut t).unwrap();
6863 let saved = q.get(&t.id).unwrap();
6864 assert_eq!(saved.runs, vec!["B", "A"]);
6865 assert_eq!(saved.runs.last().map(String::as_str), Some("A"));
6866 assert_eq!(saved.attempts, 3);
6867 assert_eq!(saved.passes.len(), 2);
6868 assert_eq!(saved.passes[0].run, "A");
6869 assert_eq!(saved.passes[1].run, "A");
6870 }
6871
6872 #[test]
6873 fn repeated_start_records_one_run_and_separate_passes() {
6874 let mut t = task("resume");
6875 t.start("same-run".into());
6876 t.record_pass("same-run", 0, 1, None);
6877 t.start("same-run".into());
6878 t.record_pass("same-run", 1, 2, None);
6879 assert_eq!(t.runs, vec!["same-run"]);
6880 assert_eq!(t.attempts, 2);
6881 assert_eq!(t.passes.len(), 2);
6882 }
6883
6884 #[test]
6885 fn link_run_adds_a_run_once_and_touches_nothing_else() {
6886 let dir = tempfile::tempdir().unwrap();
6887 let queue = Queue::at(dir.path().join("queue"));
6888 let mut t = Task::new(
6889 "t".to_owned(),
6890 "do it".to_owned(),
6891 PathBuf::from("."),
6892 Source::Human,
6893 );
6894 queue.put(&mut t).unwrap();
6895 let before = queue.get(&t.id).unwrap();
6896
6897 let linked = queue.link_run(&t.id[..4], "20260930-092817-ec34").unwrap();
6898 assert_eq!(linked.runs, vec!["20260930-092817-ec34".to_owned()]);
6899 assert_eq!(linked.status, before.status);
6900 assert_eq!(linked.attempts, before.attempts);
6901 assert_eq!(linked.interrupt, before.interrupt);
6902
6903 let again = queue.link_run(&t.id, "20260930-092817-ec34").unwrap();
6904 assert_eq!(again.runs.len(), 1, "linking twice must not duplicate");
6905 assert_eq!(queue.get(&t.id).unwrap().runs.len(), 1);
6906 assert!(queue.link_run("no-such-task", "r").is_err());
6907 }
6908
6909 #[test]
6910 fn put_keeps_a_run_linked_after_the_writer_took_its_snapshot() {
6911 let dir = tempfile::tempdir().unwrap();
6912 let queue = Queue::at(dir.path().join("queue"));
6913 let mut t = Task::new(
6914 "t".to_owned(),
6915 "do it".to_owned(),
6916 PathBuf::from("."),
6917 Source::Human,
6918 );
6919 queue.put(&mut t).unwrap();
6920 let mut snapshot = queue.get(&t.id).unwrap();
6922 queue.link_run(&t.id, "20260930-092817-ec34").unwrap();
6923
6924 snapshot.start("20260930-000000-aaaa".to_owned());
6925 queue.put(&mut snapshot).unwrap();
6926
6927 let stored = queue.get(&t.id).unwrap();
6928 assert!(stored.runs.contains(&"20260930-092817-ec34".to_owned()));
6929 assert!(stored.runs.contains(&"20260930-000000-aaaa".to_owned()));
6930 assert_eq!(stored.attempts, 1);
6931 }
6932
6933 #[test]
6934 fn concurrent_links_and_daemon_saves_lose_nothing() {
6935 let dir = tempfile::tempdir().unwrap();
6936 let queue = Queue::at(dir.path().join("queue"));
6937 let mut t = Task::new(
6938 "t".to_owned(),
6939 "do it".to_owned(),
6940 PathBuf::from("."),
6941 Source::Human,
6942 );
6943 queue.put(&mut t).unwrap();
6944 let id = t.id.clone();
6945
6946 let linkers: Vec<_> = (0..4)
6947 .map(|n| {
6948 let (queue, id) = (queue.clone(), id.clone());
6949 std::thread::spawn(move || {
6950 for k in 0..10 {
6951 queue
6952 .link_run(&id, &format!("20260930-00000{n}-l{k:03}"))
6953 .unwrap();
6954 }
6955 })
6956 })
6957 .collect();
6958 let mut mine = queue.get(&id).unwrap();
6961 for k in 0..10 {
6962 mine.start(format!("20260930-000009-d{k:03}"));
6963 queue.put(&mut mine).unwrap();
6964 }
6965 for l in linkers {
6966 l.join().unwrap();
6967 }
6968
6969 let stored = queue.get(&id).unwrap();
6970 assert_eq!(stored.runs.len(), 50, "{:?}", stored.runs);
6971 assert_eq!(
6972 stored.attempts, 10,
6973 "linking never rewinds the daemon's work"
6974 );
6975 }
6976
6977 fn age_lock(path: &Path) {
6978 let f = std::fs::OpenOptions::new().write(true).open(path).unwrap();
6979 f.set_modified(std::time::SystemTime::now() - std::time::Duration::from_secs(60))
6980 .unwrap();
6981 }
6982
6983 #[test]
6984 fn concurrent_stale_takeover_yields_one_holder() {
6985 use std::sync::atomic::{AtomicUsize, Ordering};
6986 use std::sync::{Arc, Barrier};
6987 for _ in 0..5 {
6988 let dir = tempfile::tempdir().unwrap();
6989 let q = Queue::at(dir.path().to_path_buf());
6990 let lock = dir.path().join("t.write-lock");
6991 std::fs::write(&lock, "dead-0000").unwrap();
6992 age_lock(&lock);
6993 let n = 6;
6994 let barrier = Arc::new(Barrier::new(n));
6995 let (now, max) = (Arc::new(AtomicUsize::new(0)), Arc::new(AtomicUsize::new(0)));
6996 let handles: Vec<_> = (0..n)
6997 .map(|_| {
6998 let (q, b, now, max) = (q.clone(), barrier.clone(), now.clone(), max.clone());
6999 std::thread::spawn(move || {
7000 b.wait();
7001 let g = q.lock_task("t").unwrap();
7002 let held = now.fetch_add(1, Ordering::SeqCst) + 1;
7003 max.fetch_max(held, Ordering::SeqCst);
7004 std::thread::sleep(std::time::Duration::from_millis(20));
7005 now.fetch_sub(1, Ordering::SeqCst);
7006 drop(g);
7007 })
7008 })
7009 .collect();
7010 for h in handles {
7011 h.join().unwrap();
7012 }
7013 assert_eq!(max.load(Ordering::SeqCst), 1);
7014 assert!(!lock.exists());
7015 }
7016 }
7017
7018 #[test]
7019 fn dropping_a_replaced_lock_leaves_the_new_holders_token() {
7020 let dir = tempfile::tempdir().unwrap();
7021 let q = Queue::at(dir.path().to_path_buf());
7022 let lock = dir.path().join("t.write-lock");
7023 let a = q.lock_task("t").unwrap();
7024 let replacement = owner_token();
7027 std::fs::write(&lock, &replacement).unwrap();
7028 drop(a);
7029 assert_eq!(std::fs::read_to_string(&lock).unwrap(), replacement);
7030 }
7031
7032 #[test]
7033 fn aged_live_task_lock_excludes_updates_until_retirement_releases_it() {
7034 let dir = tempfile::tempdir().unwrap();
7035 let q = Queue::at(dir.path().to_path_buf());
7036 let held = q.lock_task("t").unwrap();
7037 let path = dir.path().join("t.write-lock");
7038 age_lock(&path);
7039 assert!(!break_stale(&path, &held.token));
7040 let (started_tx, started_rx) = std::sync::mpsc::channel();
7041 let (acquired_tx, acquired_rx) = std::sync::mpsc::channel();
7042 let updater = std::thread::spawn(move || {
7043 started_tx.send(()).unwrap();
7044 let _write = q.lock_task("t").unwrap();
7045 acquired_tx.send(()).unwrap();
7046 });
7047 started_rx.recv().unwrap();
7048 assert!(
7049 acquired_rx
7050 .recv_timeout(std::time::Duration::from_millis(100))
7051 .is_err()
7052 );
7053 assert_eq!(std::fs::read_to_string(&path).unwrap(), held.token);
7054 drop(held);
7055 acquired_rx
7056 .recv_timeout(std::time::Duration::from_secs(2))
7057 .unwrap();
7058 updater.join().unwrap();
7059 assert!(!path.exists());
7060 }
7061
7062 #[test]
7063 fn break_stale_leaves_a_lock_that_replaced_the_one_judged() {
7064 let dir = tempfile::tempdir().unwrap();
7065 let lock = dir.path().join("t.write-lock");
7066 std::fs::write(&lock, "new-token").unwrap();
7067 assert!(!break_stale(&lock, "old-token"));
7068 assert_eq!(std::fs::read_to_string(&lock).unwrap(), "new-token");
7069 assert!(!break_stale(&lock, "new-token"));
7071 assert!(lock.exists());
7072 age_lock(&lock);
7073 assert!(break_stale(&lock, "new-token"));
7074 assert!(!lock.exists());
7075 }
7076
7077 #[test]
7078 fn a_stale_break_marker_is_recovered_and_a_fresh_one_is_respected() {
7079 let dir = tempfile::tempdir().unwrap();
7080 let lock = dir.path().join("t.write-lock");
7081 std::fs::write(&lock, "dead-1").unwrap();
7082 age_lock(&lock);
7083 let marker = break_marker(&lock, "dead-1");
7084 std::fs::write(&marker, "crashed-remover").unwrap();
7085 assert!(!break_stale(&lock, "dead-1"));
7087 assert!(lock.exists());
7088 age_lock(&marker);
7090 assert!(break_stale(&lock, "dead-1"));
7091 assert!(!lock.exists());
7092 assert!(!marker.exists());
7093 }
7094
7095 fn chat_task() -> Task {
7096 Task::new(
7097 "t".to_owned(),
7098 "do t".to_owned(),
7099 PathBuf::from("."),
7100 Source::Agent {
7101 run: "20260902-000000-beef".to_owned(),
7102 node: CHAT_NODE.to_owned(),
7103 },
7104 )
7105 }
7106
7107 #[test]
7108 fn a_blocked_hold_keeps_its_anchor_but_a_new_run_starts_a_new_hold() {
7109 let mut t = chat_task();
7110 t.hold_machine(Some("waiting".into()));
7111 let old: Timestamp = "2020-01-01T00:00:00Z".parse().unwrap();
7112 t.held_at = Some(old);
7113 t.block(vec!["decision".into()], None);
7114 t.hold_machine(Some("same waiting decision".into()));
7115 assert_eq!(t.held_at, Some(old));
7116 t.start("real-new-run".into());
7117 t.fail("new failure", 1);
7118 assert_ne!(
7119 t.held_at,
7120 Some(old),
7121 "old answers cannot approve a new hold"
7122 );
7123 }
7124
7125 #[test]
7126 fn legacy_delivery_survives_upgrade_and_a_no_progress_run_link() {
7127 let (_dir, queue) = queue();
7128 let mut t = chat_task();
7129 t.start("old-run".into());
7130 t.hold_machine(Some("operator is considering recovery".into()));
7131 t.chat_notice = Some(ChatNotice {
7132 key: format!("held#{}", t.held_at.unwrap()),
7133 at: Timestamp::now(),
7134 outcome: ChatNoticeOutcome::Posted,
7135 });
7136 let mut raw = serde_json::to_value(&t).unwrap();
7137 raw.as_object_mut().unwrap().remove("chat_notices");
7138 raw.as_object_mut().unwrap().remove("hold_notice_cause");
7139 std::fs::create_dir_all(queue.path_of(&t.id).parent().unwrap()).unwrap();
7140 std::fs::write(queue.path_of(&t.id), serde_json::to_string(&raw).unwrap()).unwrap();
7141 assert_eq!(queue.get(&t.id).unwrap().chat_notice_due(), None);
7142 queue
7143 .modify(&t.id, |task| {
7144 task.requeue();
7145 task.link_run("unprepared-run");
7146 task.startup_notice_cause("startup-source");
7147 task.fail("same unresolved preflight", 0);
7148 true
7149 })
7150 .unwrap();
7151 assert_eq!(queue.get(&t.id).unwrap().chat_notice_due(), None);
7152 queue
7153 .modify(&t.id, |task| {
7154 task.succeed(completion(task));
7155 true
7156 })
7157 .unwrap();
7158 assert!(
7159 queue
7160 .get(&t.id)
7161 .unwrap()
7162 .chat_notice_due()
7163 .unwrap()
7164 .starts_with("done:")
7165 );
7166 }
7167
7168 #[test]
7169 fn a_dependency_wait_does_not_change_when_released_and_blocked_again() {
7170 let mut t = chat_task();
7171 t.block(vec!["a".into(), "b".into()], Some("waiting".into()));
7172 let key = t.chat_notice_key().unwrap();
7173 t.chat_notices.push(key);
7174 t.release();
7175 t.block(
7176 vec!["b".into(), "a".into(), "a".into()],
7177 Some("still waiting on prerequisites".into()),
7178 );
7179 assert_eq!(t.chat_notice_due(), None);
7180 t.block(
7181 vec!["new-question".into()],
7182 Some("different decision".into()),
7183 );
7184 assert!(t.chat_notice_due().is_some());
7185 }
7186
7187 #[test]
7188 fn running_startup_failures_preserve_stage_and_report_distinct_blockers() {
7189 let mut t = chat_task();
7190 t.start("existing-run".into());
7191 t.fail("implementation failed", 1);
7192 let failed = t.chat_notice_key().unwrap();
7193 t.chat_notices.push(failed.clone());
7194 t.release_operator("test", None);
7195 t.start("existing-run".into());
7196 t.fail_startup("startup-source", "same unresolved recovery source", 1);
7197 assert_eq!(
7198 t.chat_notice_due(),
7199 None,
7200 "no-progress recovery stays quiet"
7201 );
7202 t.release_operator("test", None);
7203 t.start("existing-run".into());
7204 t.fail_startup("startup-attachments", "attachment missing", 1);
7205 let attachments = t.chat_notice_due().expect("new attachment blocker");
7206 assert_ne!(attachments, failed);
7207 assert_eq!(
7208 t.hold_notice_cause.as_ref().unwrap().stage,
7209 "startup-attachments"
7210 );
7211 t.chat_notices.push(attachments);
7212 t.release_operator("test", None);
7213 t.start("existing-run".into());
7214 t.fail_startup(
7215 "startup-attachments",
7216 "same missing attachment, reworded",
7217 1,
7218 );
7219 assert_eq!(
7220 t.chat_notice_due(),
7221 None,
7222 "same stage after attempt counter reset"
7223 );
7224 t.release_operator("test", None);
7225 t.start("existing-run".into());
7226 t.fail_startup("startup-config", "different preflight stage", 1);
7227 assert!(t.chat_notice_due().is_some());
7228 assert_eq!(
7229 t.hold_notice_cause.as_ref().unwrap().stage,
7230 "startup-config"
7231 );
7232 }
7233
7234 #[test]
7235 fn structured_causes_preserve_no_progress_retries_and_report_new_passes() {
7236 let mut t = chat_task();
7237 t.hold_machine(Some("startup source missing".into()));
7238 t.startup_notice_cause("startup-source");
7239 let first = t.chat_notice_key().unwrap();
7240 t.chat_notices.push(first.clone());
7241 t.release_operator("test", None);
7242 t.startup_notice_cause("startup-source");
7243 t.hold_machine(Some("same source cannot be read".into()));
7244 assert_eq!(t.chat_notice_due(), None);
7245 t.startup_notice_cause("startup-config");
7246 assert!(t.chat_notice_due().is_some(), "different startup stage");
7247 t.notice_cause("failed", Some("existing-run"), Some(0));
7248 let run_failure = t.chat_notice_key().unwrap();
7249 t.chat_notices.push(run_failure.clone());
7250 t.release_operator("test", None);
7251 t.startup_notice_cause("startup-source");
7252 t.hold_machine(Some("no new work happened".into()));
7253 assert_eq!(t.chat_notice_due(), None);
7254 t.notice_cause("failed", Some("existing-run"), Some(1));
7255 assert!(t.chat_notice_due().is_some(), "a real resumed pass failed");
7256 assert_ne!(t.chat_notice_key().unwrap(), run_failure);
7257 }
7258
7259 #[test]
7260 fn legacy_hold_baseline_does_not_replay_or_hide_new_failures_and_completion() {
7261 let mut t = chat_task();
7262 t.hold_machine(Some("still waiting".into()));
7263 t.chat_notice = Some(ChatNotice {
7264 key: "held#2026-10-14T00:00:00Z".into(),
7265 at: Timestamp::now(),
7266 outcome: ChatNoticeOutcome::Posted,
7267 });
7268 assert_eq!(t.chat_notice_due(), None, "old hold baseline");
7269 t.import_chat_notice();
7270 t.notice_cause("failed", Some("new-run"), Some(0));
7271 assert!(t.chat_notice_due().is_some(), "new producer evidence");
7272 t.succeed(completion(&t));
7273 assert!(t.chat_notice_due().unwrap().starts_with("done:"));
7274 }
7275
7276 #[test]
7277 fn a_chat_notice_is_due_only_for_a_final_state_and_only_once() {
7278 let mut t = chat_task();
7279 assert_eq!(t.chat_notice_due(), None, "queued");
7280 t.start("r1".to_owned());
7281 assert_eq!(t.chat_notice_due(), None, "running");
7282 t.fail("boom", 3);
7283 assert_eq!(t.status, TaskStatus::Failed);
7284 assert_eq!(t.chat_notice_due(), None, "a retried failure is not final");
7285 t.start("r2".to_owned());
7286 t.park("upgrade");
7287 assert_eq!(t.chat_notice_due(), None, "parked");
7288 t.fail("boom", 1);
7289 assert_eq!(t.status, TaskStatus::Held);
7290 let key = t
7291 .chat_notice_due()
7292 .expect("held on the last attempt is final");
7293 t.chat_notice = Some(ChatNotice {
7294 key,
7295 at: Timestamp::now(),
7296 outcome: ChatNoticeOutcome::Posted,
7297 });
7298 assert_eq!(t.chat_notice_due(), None, "same hold, no second notice");
7299 t.release();
7300 assert_eq!(t.chat_notice_due(), None, "requeued after a release");
7301 t.start("r3".to_owned());
7302 t.succeed(completion(&t));
7303 assert!(t.chat_notice_due().is_some(), "done is a new final state");
7304 }
7305
7306 #[test]
7307 fn legacy_completion_receipts_do_not_suppress_new_occurrences() {
7308 for key in ["done", "done#0", "done#1", "done#12"] {
7309 let mut t = chat_task();
7310 t.status = TaskStatus::Done;
7311 t.chat_notice = Some(ChatNotice {
7312 key: key.to_owned(),
7313 at: Timestamp::now(),
7314 outcome: ChatNoticeOutcome::Posted,
7315 });
7316 assert_eq!(t.chat_notice_key().as_deref(), Some("done"));
7317 assert_eq!(t.chat_notice_due(), None, "legacy recorded key: {key}");
7318 let mut context = completion(&t);
7319 context.reason = Some("inspect again".into());
7320 t.reopen(context).unwrap();
7321 t.start("r2".to_owned());
7322 t.succeed(completion(&t));
7323 assert!(t.chat_notice_key().unwrap().starts_with("done:"));
7324 assert!(
7325 t.chat_notice_due().is_some(),
7326 "new occurrence, old receipt: {key}"
7327 );
7328 }
7329 }
7330
7331 #[test]
7332 fn a_release_without_progress_keeps_the_unresolved_notice_cause() {
7333 let mut t = chat_task();
7334 t.hold_manual(Some("wait".to_owned()));
7335 let first = t.chat_notice_due().expect("held");
7336 t.chat_notice = Some(ChatNotice {
7337 key: first.clone(),
7338 at: Timestamp::now(),
7339 outcome: ChatNoticeOutcome::Posted,
7340 });
7341 t.hold_manual(Some("still waiting".to_owned()));
7342 assert_eq!(t.chat_notice_due(), None, "a re-hold keeps its start");
7343 t.release();
7344 std::thread::sleep(std::time::Duration::from_millis(5));
7345 t.hold_manual(None);
7346 assert_eq!(t.chat_notice_due(), None, "no progress, same cause");
7347 }
7348
7349 #[test]
7350 fn a_chat_notice_needs_a_chat_source_and_a_current_schema() {
7351 let mut human = task("h");
7352 human.succeed(completion(&human));
7353 assert_eq!(human.chat_notice_due(), None);
7354 let mut inherited = task("i");
7356 inherited.origin_chat = Some("20260902-000000-beef".to_owned());
7357 inherited.succeed(completion(&inherited));
7358 assert_eq!(inherited.chat_notice_due(), None);
7359 let mut old = chat_task();
7360 old.schema = 12;
7361 old.status = TaskStatus::Done;
7362 assert_eq!(old.chat_notice_due(), None, "history is not replayed");
7363 let mut live = chat_task();
7364 live.schema = 12;
7365 live.start("r1".to_owned());
7366 live.succeed(completion(&live));
7367 assert!(live.chat_notice_due().is_some(), "started by this build");
7368 let mut held = chat_task();
7369 held.schema = 12;
7370 held.hold_machine(Some("config".to_owned()));
7371 assert!(held.chat_notice_due().is_some(), "held before any start");
7372 }
7373
7374 #[test]
7375 fn a_stale_snapshot_does_not_rewind_a_recorded_chat_notice() {
7376 let tmp = tempfile::tempdir().expect("tempdir");
7377 let q = Queue::at(tmp.path().join("queue"));
7378 let mut t = chat_task();
7379 t.succeed(completion(&t));
7380 q.put(&mut t).expect("put");
7381 let mut stale = q.get(&t.id).expect("get");
7382 let key = t.chat_notice_due().expect("due");
7383 q.modify(&t.id, |x| {
7384 x.chat_notice = Some(ChatNotice {
7385 key: key.clone(),
7386 at: Timestamp::now(),
7387 outcome: ChatNoticeOutcome::Posted,
7388 });
7389 true
7390 })
7391 .expect("modify");
7392 q.put(&mut stale).expect("stale put");
7393 assert_eq!(q.get(&t.id).expect("get").chat_notice_due(), None);
7394 }
7395
7396 #[test]
7397 fn empty_sources_are_omitted_so_older_builds_still_read_the_task() {
7398 let mut t = task("plain");
7401 let value = serde_json::to_value(&t).unwrap();
7402 assert!(value.get("sources").is_none(), "{value}");
7403 t.sources.pick_commits.push(crate::refs::Input {
7404 token: "abc1234".into(),
7405 sha: "a".repeat(40),
7406 provenance: crate::refs::Provenance::ExplicitCli,
7407 });
7408 let value = serde_json::to_value(&t).unwrap();
7409 assert_eq!(value["sources"]["pick_commits"][0]["sha"], "a".repeat(40));
7410 let restored: Task = serde_json::from_value(value).unwrap();
7411 assert_eq!(restored.sources, t.sources);
7412 }
7413
7414 fn queue_with_ids(dir: &Path, ids: &[&str]) -> Queue {
7416 let ids: Vec<String> = ids.iter().map(|s| (*s).to_owned()).collect();
7417 let n = std::sync::atomic::AtomicUsize::new(0);
7418 Queue::at(dir.join("queue")).with_id_source(move || {
7419 let i = n.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
7420 ids.get(i)
7421 .cloned()
7422 .unwrap_or_else(|| format!("20260101-000000-f{i:03x}"))
7423 })
7424 }
7425
7426 const TAKEN: &str = "20260101-000000-aaaa";
7427
7428 #[test]
7429 fn a_new_task_never_merges_into_a_record_with_its_candidate_id() {
7430 let dir = tempfile::tempdir().unwrap();
7431 let q = queue_with_ids(dir.path(), &[TAKEN, TAKEN]);
7432 let mut first = task("first");
7433 first.start("run-1".into());
7434 first.succeed(completion(&first));
7435 q.put(&mut first).unwrap();
7436 assert_eq!(first.id, TAKEN);
7437 let stored_before = q.get(&first.id).unwrap();
7438 assert!(!stored_before.runs.is_empty());
7439
7440 let mut second = task("second");
7441 q.put(&mut second).unwrap();
7442
7443 assert_ne!(second.id, first.id);
7444 assert!(second.runs.is_empty());
7445 assert!(second.passes.is_empty());
7446 assert!(second.chat_notices.is_empty());
7447 assert!(second.chat_notice.is_none());
7448 assert_eq!(second.chat_notice_due(), task("fresh").chat_notice_due());
7449 let a = q.get(&first.id).unwrap();
7450 let b = q.get(&second.id).unwrap();
7451 assert_eq!(a.title, "first");
7452 assert_eq!(a.runs, stored_before.runs);
7453 assert_eq!(a.passes, stored_before.passes);
7454 assert_eq!(a.chat_notices, stored_before.chat_notices);
7455 assert_eq!(a.chat_notice, stored_before.chat_notice);
7456 assert_eq!(a.chat_notice_due(), stored_before.chat_notice_due());
7457 assert_eq!(b.title, "second");
7458 assert!(b.runs.is_empty());
7459 assert!(b.passes.is_empty());
7460 assert!(b.chat_notice.is_none());
7461
7462 let mut again = q.get(&second.id).unwrap();
7464 again.title = "second, edited".into();
7465 q.put(&mut again).unwrap();
7466 assert_eq!(q.get(&second.id).unwrap().title, "second, edited");
7467 assert_eq!(q.list().len(), 2);
7468 }
7469
7470 #[test]
7471 fn a_new_task_skips_an_id_with_an_orphaned_claim_or_attachments() {
7472 let dir = tempfile::tempdir().unwrap();
7473 let q = queue_with_ids(dir.path(), &["orphan-lock", "orphan-dir", "free"]);
7474 std::fs::create_dir_all(q.root()).unwrap();
7475 std::fs::write(q.root().join("orphan-lock.lock"), "x").unwrap();
7476 std::fs::create_dir_all(q.attachments_dir("orphan-dir")).unwrap();
7477 let mut t = task("t");
7478 q.put(&mut t).unwrap();
7479 assert_eq!(t.id, "free");
7480 }
7481
7482 #[test]
7483 fn a_claimed_new_task_holds_the_claim_on_the_reserved_id() {
7484 let dir = tempfile::tempdir().unwrap();
7485 let q = queue_with_ids(dir.path(), &[TAKEN, TAKEN]);
7486 let mut first = task("first");
7487 q.put(&mut first).unwrap();
7488 let mut second = task("second");
7489 let claim = q.file_claimed(&mut second).unwrap();
7490 assert_ne!(second.id, first.id);
7491 assert!(q.claim(&second.id).is_err());
7492 assert!(q.claim(&first.id).is_ok(), "the first task was not claimed");
7493 drop(claim);
7494 }
7495
7496 #[test]
7497 fn an_attached_new_task_skips_a_taken_id() {
7498 let dir = tempfile::tempdir().unwrap();
7499 let q = queue_with_ids(dir.path(), &[TAKEN, TAKEN]);
7500 let mut first = task("first");
7501 q.put(&mut first).unwrap();
7502 let src = source_file(dir.path(), "shot.png", "x");
7503 let mut second = task("second");
7504 q.attach_and_put(&mut second, &[src]).unwrap();
7505 assert_ne!(second.id, first.id);
7506 assert!(!q.attachments_dir(&first.id).exists());
7507 assert_eq!(q.attachment_paths(&second).len(), 1);
7508 assert!(q.attachment_paths(&second)[0].is_file());
7509 }
7510
7511 #[test]
7512 fn attaching_before_putting_a_new_task_reserves_the_id() {
7513 let dir = tempfile::tempdir().unwrap();
7514 let q = queue_with_ids(dir.path(), &[TAKEN, TAKEN]);
7515 let mut first = task("first");
7516 q.put(&mut first).unwrap();
7517 let src = source_file(dir.path(), "shot.png", "x");
7518 let mut second = task("second");
7519 q.attach(&mut second, &[src]).unwrap();
7520 assert_ne!(second.id, first.id);
7521 assert!(q.attachments_dir(&second.id).is_dir());
7522 q.put(&mut second).unwrap();
7523 assert_eq!(q.get(&second.id).unwrap().attachments.len(), 1);
7524 assert_eq!(q.get(&first.id).unwrap().title, "first");
7525 assert!(q.get(&first.id).unwrap().attachments.is_empty());
7526 }
7527
7528 #[test]
7529 fn create_new_keeps_its_already_exists_meaning() {
7530 let dir = tempfile::tempdir().unwrap();
7531 let q = Queue::at(dir.path().join("queue"));
7532 let mut a = task("a");
7533 a.id = "fixed-id".into();
7534 assert!(q.create_new(&mut a).unwrap());
7535 let mut b = task("b");
7536 b.id = "fixed-id".into();
7537 assert!(!q.create_new(&mut b).unwrap());
7538 assert_eq!(q.get("fixed-id").unwrap().title, "a");
7539 }
7540
7541 #[test]
7542 fn filing_gives_up_when_no_id_is_ever_free() {
7543 let dir = tempfile::tempdir().unwrap();
7544 let q = Queue::at(dir.path().join("queue")).with_id_source(|| TAKEN.to_owned());
7545 let mut first = task("first");
7546 q.put(&mut first).unwrap();
7547 let mut second = task("second");
7548 assert!(q.put(&mut second).is_err());
7549 assert_eq!(q.get(&first.id).unwrap().title, "first");
7550 }
7551}