1use std::collections::HashMap;
34use std::num::NonZeroUsize;
35use std::path::{Path, PathBuf};
36
37use anyhow::{Context, Result, bail};
38use jiff::Timestamp;
39use serde::{Deserialize, Serialize};
40
41use crate::ask::Questions;
42
43pub const SCHEMA: u32 = 18;
130
131#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
133#[serde(rename_all = "lowercase")]
134pub enum HoldSource {
135 Manual,
137 Machine,
139}
140
141impl HoldSource {
142 pub fn label(self) -> &'static str {
144 match self {
145 Self::Manual => "manual",
146 Self::Machine => "machine",
147 }
148 }
149}
150
151#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
154#[serde(tag = "kind", rename_all = "lowercase")]
155pub enum Source {
156 Human,
158 Agent {
161 run: String,
163 node: String,
165 },
166 Issue {
168 number: u64,
170 repo: String,
172 },
173}
174
175pub const CHAT_NODE: &str = "chat";
178
179impl Source {
180 pub fn label(&self) -> String {
182 match self {
183 Self::Human => "human".to_owned(),
184 Self::Agent { run, node } => format!("{node}@{}", short(run)),
185 Self::Issue { number, .. } => format!("issue #{number}"),
186 }
187 }
188}
189
190#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
192#[serde(rename_all = "lowercase")]
193pub enum TaskStatus {
194 Queued,
196 Running,
198 Done,
200 Failed,
202 Held,
204 Blocked,
208 Parked,
213}
214
215impl TaskStatus {
216 pub fn runnable(self) -> bool {
218 matches!(self, Self::Queued | Self::Failed | Self::Parked)
219 }
220
221 pub fn as_str(self) -> &'static str {
223 match self {
224 Self::Queued => "queued",
225 Self::Running => "running",
226 Self::Done => "done",
227 Self::Failed => "failed",
228 Self::Held => "held",
229 Self::Blocked => "blocked",
230 Self::Parked => "parked",
231 }
232 }
233}
234
235#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
238pub struct TaskCounts {
239 pub queued: usize,
241 pub running: usize,
243 pub done: usize,
245 pub failed: usize,
247 pub held: usize,
249 pub blocked: usize,
251 pub parked: usize,
253}
254
255impl TaskCounts {
256 pub fn of(tasks: &[Task]) -> Self {
260 let mut counts = Self::default();
261 for t in tasks {
262 match t.status {
263 TaskStatus::Queued => counts.queued += 1,
264 TaskStatus::Running => counts.running += 1,
265 TaskStatus::Done => counts.done += 1,
266 TaskStatus::Failed => counts.failed += 1,
267 TaskStatus::Held => counts.held += 1,
268 TaskStatus::Blocked => counts.blocked += 1,
269 TaskStatus::Parked => counts.parked += 1,
270 }
271 }
272 counts
273 }
274}
275
276#[derive(Debug, Clone, Serialize, Deserialize)]
278#[serde(deny_unknown_fields)]
279pub struct Task {
280 pub schema: u32,
282 pub id: String,
284 pub title: String,
286 pub instruction: String,
288 pub repo: PathBuf,
290 pub source: Source,
292 #[serde(default)]
294 pub priority: i32,
295 #[serde(default)]
306 pub solo: bool,
307 pub status: TaskStatus,
309 #[serde(default)]
311 pub attempts: usize,
312 #[serde(default)]
314 pub attempt_limit: Option<NonZeroUsize>,
315 #[serde(default)]
318 pub runs: Vec<String>,
319 #[serde(default)]
321 pub last_error: Option<String>,
322 #[serde(default)]
335 pub hold_reason: Option<String>,
336 #[serde(default)]
339 pub hold_source: Option<HoldSource>,
340 #[serde(default)]
352 pub diagnostic: Option<String>,
353 #[serde(default)]
363 pub blocked_by: Vec<String>,
364 #[serde(default)]
367 pub block_reason: Option<String>,
368 #[serde(default)]
381 pub blocked_from: Option<TaskStatus>,
382 #[serde(default)]
393 pub answers: Vec<AnsweredQuestion>,
394 #[serde(default)]
400 pub triage_applied: Vec<String>,
401 #[serde(default)]
407 pub actions_applied: Vec<String>,
408 #[serde(default)]
413 pub resume_override: Option<OperatorResume>,
414 #[serde(default)]
417 pub resumption: Option<Resumption>,
418 #[serde(default)]
420 pub resumption_history: Vec<Resumption>,
421 #[serde(default)]
423 pub operator_decided_at: Option<Timestamp>,
424 #[serde(default)]
436 pub review_branch: Option<String>,
437 #[serde(default)]
439 pub review_instruction: Option<String>,
440 #[serde(default)]
442 pub pr_recovery: Option<crate::pr_recovery::Selection>,
443 #[serde(default)]
446 pub fresh_start: bool,
447 #[serde(default)]
458 pub interrupt: bool,
459 #[serde(default)]
482 pub urgent: bool,
483 #[serde(default)]
489 pub attachments: Vec<String>,
490 #[serde(default)]
494 pub followup: Option<FollowUp>,
495 #[serde(default)]
501 pub origin_chat: Option<String>,
502 #[serde(default)]
509 pub overrides: Option<RunOverrides>,
510 #[serde(default)]
517 pub review_of: Option<String>,
518 #[serde(default)]
523 pub held_at: Option<Timestamp>,
524 #[serde(default)]
528 pub park_reason: Option<String>,
529 #[serde(default)]
532 pub chat_notice: Option<ChatNotice>,
533 #[serde(default)]
538 pub passes: Vec<TaskPass>,
539 pub created_at: Timestamp,
541 pub updated_at: Timestamp,
543}
544
545pub(crate) fn is_done_notice_key(key: &str) -> bool {
547 key == "done"
548 || key
549 .strip_prefix("done#")
550 .is_some_and(|count| !count.is_empty() && count.bytes().all(|b| b.is_ascii_digit()))
551}
552
553#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
555#[serde(rename_all = "snake_case")]
556pub enum PassCost {
557 Spent,
559 Refunded,
561}
562
563#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
565pub struct TaskPass {
566 pub run: String,
568 pub pass_index: usize,
570 pub cost: PassCost,
572 pub attempts_after: usize,
574 pub settled_at: Timestamp,
576 #[serde(default)]
578 pub parked: Option<crate::run::ParkCause>,
579}
580
581#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
583#[serde(rename_all = "lowercase")]
584pub enum ChatNoticeOutcome {
585 Posted,
587 Skipped,
589}
590
591#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
593pub struct ChatNotice {
594 pub key: String,
596 pub at: Timestamp,
598 pub outcome: ChatNoticeOutcome,
600}
601
602#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
604pub struct RunOverrides {
605 #[serde(default)]
608 pub inherit_daemon_options: bool,
609 #[serde(default)]
611 pub merge: Option<String>,
612 #[serde(default)]
614 pub candidates: Option<usize>,
615 #[serde(default)]
617 pub judges: Option<usize>,
618 #[serde(default)]
620 pub reviewers: Option<usize>,
621 #[serde(default)]
623 pub review_rounds: Option<usize>,
624 #[serde(default)]
626 pub seed: Option<u64>,
627 #[serde(default)]
629 pub config: Option<PathBuf>,
630}
631
632impl RunOverrides {
633 pub fn merge_over(&mut self, other: &RunOverrides) {
635 macro_rules! take {
636 ($($f:ident),*) => {$(
637 if other.$f.is_some() {
638 self.$f.clone_from(&other.$f);
639 }
640 )*};
641 }
642 take!(
643 merge,
644 candidates,
645 judges,
646 reviewers,
647 review_rounds,
648 seed,
649 config
650 );
651 }
652
653 pub fn apply(&self, config: &mut crate::config::Config) {
655 if let Some(n) = self.candidates {
656 config.graph.implementers = n;
657 }
658 if let Some(n) = self.judges {
659 config.graph.judges = n;
660 }
661 if let Some(n) = self.reviewers {
662 config.graph.reviewers = n;
663 }
664 if let Some(n) = self.review_rounds {
665 config.graph.review_rounds = n;
666 }
667 if let Some(m) = &self.merge
668 && let Ok(mode) = crate::daemon::merge_mode(m)
669 {
670 config.merge.mode = mode;
671 }
672 if let Some(s) = self.seed {
673 config.blind.seed = Some(s);
674 }
675 }
676}
677
678#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
680pub struct FollowUp {
681 pub run: String,
683 #[serde(default)]
685 pub origin_task: Option<String>,
686 pub pr: String,
688 pub findings: Vec<String>,
690 pub generation: u32,
693}
694
695#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
697pub struct Resumption {
698 pub generation: u64,
700 pub source: String,
702 pub question_id: Option<String>,
704 pub at: Timestamp,
706 pub instruction: String,
708 pub answers_through: usize,
710 pub runs_through: usize,
713 pub cleared_reason: Option<String>,
715 #[serde(default)]
717 pub blocking_evidence: Vec<String>,
718}
719
720#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
723pub struct OperatorResume {
724 pub question_id: String,
726 pub at: Timestamp,
728 #[serde(default)]
731 pub conductor_rehold: Option<String>,
732 #[serde(default)]
735 pub forced: bool,
736 #[serde(default)]
743 pub pinned_run: Option<String>,
744}
745
746#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
749pub struct AnsweredQuestion {
750 pub question: String,
752 pub answer: String,
754}
755
756impl Task {
757 pub fn new(title: String, instruction: String, repo: PathBuf, source: Source) -> Self {
759 let now = Timestamp::now();
760 let origin_chat = match &source {
761 Source::Agent { run, node } if node == CHAT_NODE => Some(run.clone()),
762 _ => None,
763 };
764 Self {
765 schema: SCHEMA,
766 id: new_id(),
767 title,
768 instruction,
769 repo,
770 source,
771 priority: 0,
772 solo: false,
773 status: TaskStatus::Queued,
774 attempts: 0,
775 attempt_limit: None,
776 runs: Vec::new(),
777 last_error: None,
778 hold_reason: None,
779 hold_source: None,
780 diagnostic: None,
781 blocked_by: Vec::new(),
782 block_reason: None,
783 blocked_from: None,
784 answers: Vec::new(),
785 triage_applied: Vec::new(),
786 actions_applied: Vec::new(),
787 resume_override: None,
788 resumption: None,
789 resumption_history: Vec::new(),
790 operator_decided_at: None,
791 review_branch: None,
792 review_instruction: None,
793 pr_recovery: None,
794 fresh_start: false,
795 interrupt: false,
796 urgent: false,
797 attachments: Vec::new(),
798 followup: None,
799 origin_chat,
800 overrides: None,
801 review_of: None,
802 held_at: None,
803 park_reason: None,
804 chat_notice: None,
805 passes: Vec::new(),
806 created_at: now,
807 updated_at: now,
808 }
809 }
810
811 pub fn chat_talk(&self) -> Option<&str> {
814 if let Some(id) = &self.origin_chat {
815 return Some(id);
816 }
817 match &self.source {
818 Source::Agent { run, node } if node == CHAT_NODE => Some(run),
819 _ => None,
820 }
821 }
822
823 pub fn filed_by_chat(&self) -> Option<&str> {
827 match &self.source {
828 Source::Agent { run, node } if node == CHAT_NODE => Some(run),
829 _ => None,
830 }
831 }
832
833 pub fn chat_notice_key(&self) -> Option<String> {
839 match self.status {
840 TaskStatus::Done => Some("done".to_owned()),
841 TaskStatus::Held => Some(format!(
842 "held#{}",
843 self.held_at.map(|t| t.to_string()).unwrap_or_default()
844 )),
845 TaskStatus::Blocked => Some(format!(
846 "blocked#{}#{}",
847 self.blocked_by.join(","),
848 self.block_reason.as_deref().unwrap_or_default()
849 )),
850 _ => None,
851 }
852 }
853
854 pub fn chat_notice_due(&self) -> Option<String> {
858 self.filed_by_chat()?;
859 if self.schema < 13 {
860 return None;
861 }
862 let key = self.chat_notice_key()?;
863 match &self.chat_notice {
864 Some(n) if n.key == key || (key == "done" && is_done_notice_key(&n.key)) => None,
865 _ => Some(key),
866 }
867 }
868
869 pub fn short(&self) -> &str {
871 short(&self.id)
872 }
873
874 pub fn mark_triage_applied(&mut self, question_id: &str) {
876 if !self.triage_applied(question_id) {
877 self.triage_applied.push(question_id.to_owned());
878 }
879 }
880
881 pub fn action_applied(&self, question_id: &str) -> bool {
884 self.actions_applied.iter().any(|id| id == question_id)
885 }
886
887 pub fn mark_action_applied(&mut self, question_id: &str) {
889 if !self.action_applied(question_id) {
890 self.actions_applied.push(question_id.to_owned());
891 }
892 }
893
894 pub fn triage_applied(&self, question_id: &str) -> bool {
896 self.triage_applied.iter().any(|id| id == question_id)
897 }
898
899 pub fn start(&mut self, run: String) {
912 self.stamp_schema();
913 self.status = TaskStatus::Running;
914 self.attempts += 1;
915 self.runs.retain(|id| id != &run);
916 self.runs.push(run);
917 self.last_error = None;
918 self.park_reason = None;
919 self.fresh_start = false;
920 self.interrupt = false;
921 self.resume_override = None;
923 }
924
925 pub fn link_run(&mut self, run: &str) -> bool {
930 if self.runs.iter().any(|r| r == run) {
931 return false;
932 }
933 self.runs.push(run.to_owned());
934 true
935 }
936
937 pub fn succeed(&mut self) {
947 self.stamp_schema();
948 self.status = TaskStatus::Done;
949 self.resume_override = None;
950 self.last_error = None;
951 self.park_reason = None;
952 self.hold_reason = None;
953 self.hold_source = None;
954 self.diagnostic = None;
955 self.blocked_by.clear();
956 self.block_reason = None;
957 self.blocked_from = None;
958 }
959
960 pub fn already_landed(&mut self, note: impl Into<String>) {
968 self.succeed();
969 self.attempts = self.attempts.saturating_sub(1);
970 self.last_error = Some(note.into());
971 }
972
973 pub fn superseded_attempts(&self, last_run_succeeded: bool) -> &[String] {
1003 if self.status != TaskStatus::Done || !last_run_succeeded || self.runs.len() < 2 {
1004 return &[];
1005 }
1006 &self.runs[..self.runs.len() - 1]
1007 }
1008
1009 pub fn successor_of(&self, run: &str) -> Option<&String> {
1017 let pos = self.runs.iter().rposition(|r| r == run)?;
1018 self.runs.get(pos + 1)
1019 }
1020
1021 pub fn earlier_attempts(&self) -> &[String] {
1028 &self.runs
1029 }
1030
1031 fn stamp_schema(&mut self) {
1038 self.schema = self.schema.max(SCHEMA);
1039 }
1040
1041 fn note_held(&mut self) {
1042 self.stamp_schema();
1043 if self.status != TaskStatus::Held || self.held_at.is_none() {
1044 self.held_at = Some(Timestamp::now());
1045 }
1046 }
1047
1048 pub fn fail(&mut self, why: impl Into<String>, max_attempts: usize) {
1064 let why = why.into();
1065 self.diagnostic = None;
1066 self.park_reason = None;
1067 self.status = if self.attempts >= self.effective_attempt_limit(max_attempts) {
1068 self.note_held();
1069 self.hold_source = Some(HoldSource::Machine);
1070 self.hold_reason = Some(why.clone());
1071 TaskStatus::Held
1072 } else {
1073 TaskStatus::Failed
1074 };
1075 self.last_error = Some(why);
1076 }
1077
1078 pub fn stall(&mut self, why: impl Into<String>) {
1088 self.last_error = Some(why.into());
1089 self.diagnostic = None;
1090 self.attempts = self.attempts.saturating_sub(1);
1091 self.status = TaskStatus::Failed;
1092 }
1093
1094 pub fn park(&mut self, why: impl Into<String>) {
1100 self.diagnostic = None;
1101 self.attempts = self.attempts.saturating_sub(1);
1102 self.status = TaskStatus::Parked;
1103 self.park_reason = Some(why.into());
1104 self.schema = self.schema.max(SCHEMA);
1107 }
1108
1109 pub fn record_pass(
1112 &mut self,
1113 run: &str,
1114 pass_index: usize,
1115 attempts_before: usize,
1116 parked: Option<crate::run::ParkCause>,
1117 ) {
1118 if self
1119 .passes
1120 .iter()
1121 .any(|p| p.run == run && p.pass_index == pass_index)
1122 {
1123 return;
1124 }
1125 let cost = if self.attempts < attempts_before {
1126 PassCost::Refunded
1127 } else {
1128 PassCost::Spent
1129 };
1130 self.passes.push(TaskPass {
1131 run: run.to_owned(),
1132 pass_index,
1133 cost,
1134 attempts_after: self.attempts,
1135 settled_at: Timestamp::now(),
1136 parked,
1137 });
1138 self.schema = self.schema.max(SCHEMA);
1139 }
1140
1141 pub fn operator_held(&self) -> bool {
1147 self.status == TaskStatus::Held && !matches!(self.hold_source, Some(HoldSource::Machine))
1148 }
1149
1150 pub fn hold_manual(&mut self, reason: Option<String>) {
1160 self.operator_decided_at = Some(Timestamp::now());
1162 self.hold_unrequested_retry(reason);
1163 }
1164
1165 pub(crate) fn hold_unrequested_retry(&mut self, reason: Option<String>) {
1168 self.park_reason = None;
1169 self.note_held();
1170 self.status = TaskStatus::Held;
1171 if reason.is_some() {
1172 self.hold_reason = reason;
1173 }
1174 self.hold_source = Some(HoldSource::Manual);
1175 self.blocked_by.clear();
1176 self.block_reason = None;
1177 self.blocked_from = None;
1178 }
1179
1180 pub fn hold_machine(&mut self, reason: Option<String>) {
1185 self.park_reason = None;
1186 self.note_held();
1187 self.status = TaskStatus::Held;
1188 if reason.is_some() {
1189 self.hold_reason = reason;
1190 }
1191 self.hold_source = Some(HoldSource::Machine);
1192 self.blocked_by.clear();
1193 self.block_reason = None;
1194 self.blocked_from = None;
1195 }
1196
1197 pub fn block(&mut self, blocked_by: Vec<String>, reason: Option<String>) {
1207 self.stamp_schema();
1208 if self.status != TaskStatus::Blocked {
1209 self.blocked_from = Some(self.status);
1210 }
1211 self.status = TaskStatus::Blocked;
1212 self.blocked_by = blocked_by;
1213 self.block_reason = reason;
1214 }
1215
1216 pub fn unblock(&mut self, resolved_id: &str) {
1239 if self.status != TaskStatus::Blocked {
1240 return;
1241 }
1242 self.blocked_by.retain(|id| id != resolved_id);
1243 self.restore_if_unblocked();
1244 }
1245
1246 pub fn dependency_deleted(&mut self, deleted_id: &str) -> bool {
1257 if self.status != TaskStatus::Blocked || !self.blocked_by.iter().any(|b| b == deleted_id) {
1258 return false;
1259 }
1260 self.blocked_by.retain(|id| id != deleted_id);
1261 self.restore_if_unblocked();
1262 true
1263 }
1264
1265 fn restore_if_unblocked(&mut self) {
1269 if self.blocked_by.is_empty() {
1270 self.status = match self.blocked_from {
1271 Some(TaskStatus::Running) => TaskStatus::Queued,
1272 Some(other) => other,
1273 None if self.hold_reason.is_some() || self.hold_source.is_some() => {
1274 TaskStatus::Held
1275 }
1276 None => TaskStatus::Queued,
1277 };
1278 self.block_reason = None;
1279 self.blocked_from = None;
1280 }
1281 }
1282
1283 pub fn record_answer(&mut self, question: String, answer: String) {
1288 self.answers.push(AnsweredQuestion { question, answer });
1289 }
1290
1291 pub fn request_review(&mut self, branch: String) {
1295 self.release();
1296 self.review_branch = Some(branch);
1297 self.review_instruction = Some(self.instruction.clone());
1298 }
1299
1300 pub fn requeue(&mut self) {
1303 self.release();
1304 self.review_branch = None;
1306 self.review_instruction = None;
1307 self.fresh_start = true;
1308 }
1309
1310 pub fn hold_for_handover(&mut self, branch: Option<String>, reason: String) {
1319 if branch.is_some() {
1320 self.review_branch = branch;
1321 self.review_instruction = Some(self.instruction.clone());
1322 }
1323 self.hold_machine(Some(reason));
1324 }
1325
1326 pub fn set_urgent(&mut self, urgent: bool) -> Result<()> {
1328 if !matches!(self.status, TaskStatus::Queued | TaskStatus::Held) {
1329 bail!(
1330 "task {} is {}; urgent can only change while queued or held; \
1331 wait for the active attempt to finish and requeue or hold the task first",
1332 self.short(),
1333 self.status.as_str()
1334 );
1335 }
1336 self.urgent = urgent;
1337 Ok(())
1338 }
1339
1340 pub fn set_priority(&mut self, priority: i32) -> Result<()> {
1349 if self.status == TaskStatus::Running {
1350 bail!(
1351 "task {} is running; its priority cannot be changed until \
1352 this attempt finishes",
1353 self.short()
1354 );
1355 }
1356 self.priority = priority;
1357 Ok(())
1358 }
1359
1360 pub fn set_interrupt(&mut self, interrupt: bool) -> Result<()> {
1375 if interrupt && !self.status.runnable() {
1376 bail!(
1377 "task {} is {}; only a queued or failed task can be marked \
1378 to interrupt",
1379 self.short(),
1380 self.status.as_str()
1381 );
1382 }
1383 self.interrupt = interrupt;
1384 Ok(())
1385 }
1386
1387 pub fn effective_attempt_limit(&self, daemon_limit: usize) -> usize {
1389 self.attempt_limit.map_or(daemon_limit, NonZeroUsize::get)
1390 }
1391
1392 pub fn change_attempt_limit(&mut self, limit: Option<NonZeroUsize>) -> Result<()> {
1395 if !matches!(self.status, TaskStatus::Queued | TaskStatus::Held) {
1396 bail!("only queued or held tasks can change the attempt limit");
1397 }
1398 self.stamp_schema();
1399 self.attempt_limit = limit;
1400 Ok(())
1401 }
1402
1403 pub fn implementers(&self) -> Option<usize> {
1405 if self.solo {
1406 Some(1)
1407 } else {
1408 self.overrides.as_ref().and_then(|o| o.candidates)
1409 }
1410 }
1411
1412 pub fn change_implementers(&mut self, count: u8) -> Result<()> {
1415 self.check_implementers_editable()?;
1416 let explicit = self.overrides.as_ref().and_then(|o| o.config.as_deref());
1417 let (mut config, _) = crate::config::Config::discover(&self.repo, explicit)?;
1418 if let Some(o) = &self.overrides {
1419 o.apply(&mut config);
1420 }
1421 self.set_implementers(count, &config)
1422 }
1423
1424 fn check_implementers_editable(&self) -> Result<()> {
1425 if !matches!(self.status, TaskStatus::Queued | TaskStatus::Held) {
1426 bail!(
1427 "task {} is {}; only queued or held tasks can change implementers",
1428 self.short(),
1429 self.status.as_str()
1430 );
1431 }
1432 Ok(())
1433 }
1434
1435 pub fn set_implementers(&mut self, count: u8, config: &crate::config::Config) -> Result<()> {
1437 self.check_implementers_editable()?;
1438 crate::talk::check_implementers(count, config).map_err(anyhow::Error::msg)?;
1439 self.stamp_schema();
1440 self.solo = count == 1;
1441 let mut overrides = self.overrides.clone().unwrap_or_else(|| RunOverrides {
1442 inherit_daemon_options: true,
1443 ..Default::default()
1444 });
1445 overrides.candidates = (count > 1).then_some(usize::from(count));
1446 let mut settings = overrides.clone();
1447 settings.inherit_daemon_options = false;
1448 self.overrides = if overrides.inherit_daemon_options && settings == RunOverrides::default()
1450 {
1451 None
1452 } else {
1453 Some(overrides)
1454 };
1455 Ok(())
1456 }
1457
1458 pub fn edit(&mut self, title: String, instruction: String) -> Result<()> {
1470 if !matches!(self.status, TaskStatus::Queued | TaskStatus::Held) {
1471 bail!(
1472 "task {} is {}; only a queued or held task's instruction can \
1473 be edited",
1474 self.short(),
1475 self.status.as_str()
1476 );
1477 }
1478 if self.review_branch.is_some() && self.review_instruction.is_none() {
1481 self.review_instruction = Some(self.instruction.clone());
1482 }
1483 if self.instruction != instruction {
1484 self.resume_override = None;
1487 }
1488 self.title = title;
1489 self.instruction = instruction;
1490 Ok(())
1491 }
1492
1493 pub fn handed_off(&mut self, why: impl Into<String>) {
1513 let why = why.into();
1514 self.diagnostic = None;
1515 self.note_held();
1516 self.status = TaskStatus::Held;
1517 self.hold_source = Some(HoldSource::Machine);
1518 self.hold_reason = Some(why.clone());
1519 self.last_error = Some(why);
1520 }
1521
1522 pub fn release_operator(&mut self, source: &str, question_id: Option<&str>) {
1524 if self
1525 .resumption
1526 .as_ref()
1527 .is_some_and(|r| r.instruction != self.instruction)
1528 {
1529 self.resume_override = None;
1532 }
1533 let approval = Resumption {
1534 generation: self.resumption.as_ref().map_or(1, |r| r.generation + 1),
1535 source: source.to_owned(),
1536 question_id: question_id.map(str::to_owned),
1537 at: Timestamp::now(),
1538 instruction: self.instruction.clone(),
1539 answers_through: self.answers.len(),
1540 runs_through: self.runs.len(),
1541 blocking_evidence: Vec::new(),
1542 cleared_reason: self
1543 .hold_reason
1544 .clone()
1545 .or_else(|| self.block_reason.clone()),
1546 };
1547 self.release();
1548 self.operator_decided_at = Some(approval.at);
1549 if let Some(previous) = self.resumption.replace(approval) {
1550 self.resumption_history.push(previous);
1551 }
1552 }
1553
1554 pub fn release(&mut self) {
1558 let refused_handover = self.status == TaskStatus::Held
1559 && self.hold_source == Some(HoldSource::Machine)
1560 && self.review_branch.is_some()
1561 && self
1562 .review_instruction
1563 .as_ref()
1564 .is_none_or(|i| *i == self.instruction);
1565 self.status = TaskStatus::Queued;
1566 self.held_at = None;
1567 self.attempts = 0;
1568 self.last_error = None;
1569 self.park_reason = None;
1570 self.hold_reason = None;
1573 self.hold_source = None;
1574 self.diagnostic = None;
1575 self.blocked_by.clear();
1580 self.block_reason = None;
1581 self.blocked_from = None;
1582 if !refused_handover {
1586 self.review_branch = None;
1587 self.review_instruction = None;
1588 }
1589 self.fresh_start = false;
1590 }
1591}
1592
1593fn copy_new(dir: &Path, src: &Path, name: &str) -> Result<(String, PathBuf)> {
1597 use std::io::ErrorKind;
1598 let (stem, ext) = match name.rfind('.') {
1599 Some(i) if i > 0 => (&name[..i], &name[i..]),
1600 _ => (name, ""),
1601 };
1602 for n in 1u32.. {
1603 let candidate = if n == 1 {
1604 name.to_owned()
1605 } else {
1606 let suffix = format!("-{n}");
1607 let room = 64usize.saturating_sub(suffix.len() + ext.len());
1608 let stem: String = stem.chars().take(room).collect();
1609 format!("{stem}{suffix}{ext}")
1610 };
1611 if !crate::ask::valid_asset_name(&candidate) {
1612 bail!("no valid attachment name is left for `{name}`");
1613 }
1614 let path = dir.join(&candidate);
1615 match std::fs::OpenOptions::new()
1616 .write(true)
1617 .create_new(true)
1618 .open(&path)
1619 {
1620 Ok(mut out) => {
1621 let copied = std::fs::File::open(src)
1622 .and_then(|mut input| std::io::copy(&mut input, &mut out));
1623 if let Err(e) = copied {
1624 drop(out);
1625 let _ = std::fs::remove_file(&path);
1626 return Err(e).with_context(|| format!("copy {}", src.display()));
1627 }
1628 return Ok((candidate, path));
1629 }
1630 Err(e) if e.kind() == ErrorKind::AlreadyExists => continue,
1631 Err(e) => return Err(e).with_context(|| format!("create {}", path.display())),
1632 }
1633 }
1634 unreachable!("the counter never runs out")
1635}
1636
1637const TASK_LOCK_STALE: std::time::Duration = std::time::Duration::from_secs(10);
1640
1641struct TaskLock {
1644 path: PathBuf,
1645 token: String,
1646}
1647
1648fn owner_token() -> String {
1651 static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1652 let n = COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1653 let mut r = crate::rng::SplitMix64::new(crate::rng::entropy() ^ n.rotate_left(32));
1654 format!("{}-{:016x}", std::process::id(), r.next_u64())
1655}
1656
1657fn break_marker(path: &Path, token: &str) -> PathBuf {
1660 let mut h: u64 = 0xcbf29ce484222325;
1661 for b in token.bytes() {
1662 h ^= u64::from(b);
1663 h = h.wrapping_mul(0x100000001b3);
1664 }
1665 let mut name = path.as_os_str().to_owned();
1666 name.push(format!(".break-{h:016x}"));
1667 PathBuf::from(name)
1668}
1669
1670fn older_than_stale(path: &Path) -> bool {
1671 std::fs::metadata(path)
1672 .and_then(|m| m.modified())
1673 .ok()
1674 .and_then(|t| t.elapsed().ok())
1675 .is_some_and(|age| age > TASK_LOCK_STALE)
1676}
1677
1678const MAX_MARKER_DEPTH: u8 = 3;
1682
1683fn take_marker(path: &Path, token: &str, depth: u8) -> Option<(PathBuf, String)> {
1689 use std::io::Write;
1690 let marker = break_marker(path, token);
1691 for _ in 0..2 {
1692 match std::fs::OpenOptions::new()
1693 .write(true)
1694 .create_new(true)
1695 .open(&marker)
1696 {
1697 Ok(mut f) => {
1698 let mine = owner_token();
1699 if f.write_all(mine.as_bytes()).is_err() {
1700 drop(f);
1701 let _ = std::fs::remove_file(&marker);
1702 return None;
1703 }
1704 return Some((marker, mine));
1705 }
1706 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
1707 let judged = std::fs::read_to_string(&marker).ok();
1708 match judged.filter(|_| older_than_stale(&marker)) {
1709 Some(judged) if depth < MAX_MARKER_DEPTH => {
1710 remove_lock_if(&marker, &judged, true, depth + 1)?;
1711 }
1712 _ => return None,
1713 }
1714 }
1715 Err(_) => return None,
1716 }
1717 }
1718 None
1719}
1720
1721fn remove_lock_if(path: &Path, token: &str, require_stale: bool, depth: u8) -> Option<bool> {
1726 let (marker, mine) = take_marker(path, token, depth)?;
1727 let still = std::fs::read_to_string(path).is_ok_and(|c| c == token)
1728 && (!require_stale || older_than_stale(path));
1729 if still {
1730 let _ = std::fs::remove_file(path);
1731 }
1732 if depth >= MAX_MARKER_DEPTH {
1734 if std::fs::read_to_string(&marker).is_ok_and(|c| c == mine) {
1735 let _ = std::fs::remove_file(&marker);
1736 }
1737 } else {
1738 let _ = remove_lock_if(&marker, &mine, false, depth + 1);
1739 }
1740 Some(still)
1741}
1742
1743fn break_stale(path: &Path, judged: &str) -> bool {
1746 remove_lock_if(path, judged, true, 0).unwrap_or(false)
1747}
1748
1749impl Drop for TaskLock {
1750 fn drop(&mut self) {
1751 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2);
1752 loop {
1753 match remove_lock_if(&self.path, &self.token, false, 0) {
1754 Some(_) => return,
1755 None if std::time::Instant::now() > deadline => return,
1756 None => std::thread::sleep(std::time::Duration::from_millis(5)),
1757 }
1758 }
1759 }
1760}
1761
1762#[derive(Debug, Clone)]
1764pub struct Queue {
1765 root: PathBuf,
1766}
1767
1768impl Queue {
1769 pub fn open() -> Self {
1771 Self::at(crate::run::home().join("queue"))
1772 }
1773
1774 pub fn at(root: PathBuf) -> Self {
1777 Self { root }
1778 }
1779
1780 pub fn root(&self) -> &Path {
1782 &self.root
1783 }
1784
1785 pub fn path_of(&self, id: &str) -> PathBuf {
1787 self.root.join(format!("{id}.json"))
1788 }
1789
1790 pub fn attachments_dir(&self, id: &str) -> PathBuf {
1793 self.root.join(format!("{id}.attachments"))
1794 }
1795
1796 pub fn attach(&self, task: &mut Task, sources: &[PathBuf]) -> Result<Vec<String>> {
1807 let mut wanted = Vec::new();
1808 for src in sources {
1809 let name = src
1810 .file_name()
1811 .and_then(|n| n.to_str())
1812 .with_context(|| format!("`{}` has no usable file name", src.display()))?;
1813 if !crate::ask::valid_asset_name(name) {
1814 bail!(
1815 "attachment name `{name}` must match ^[A-Za-z0-9][A-Za-z0-9._-]{{0,63}}$ \
1816 with no `..`; rename the file and try again"
1817 );
1818 }
1819 if !src.is_file() {
1820 bail!("attachment `{}` is not a file", src.display());
1821 }
1822 wanted.push((src, name));
1823 }
1824 let dir = self.attachments_dir(&task.id);
1825 let existed = dir.is_dir();
1826 std::fs::create_dir_all(&dir).with_context(|| format!("create {}", dir.display()))?;
1827 let mut created: Vec<PathBuf> = Vec::new();
1828 let mut names = Vec::new();
1829 let mut copy_all = || -> Result<()> {
1830 for (src, name) in &wanted {
1831 let (stored, path) = copy_new(&dir, src, name)?;
1832 created.push(path);
1833 names.push(stored);
1834 }
1835 Ok(())
1836 };
1837 if let Err(e) = copy_all() {
1838 for path in &created {
1839 let _ = std::fs::remove_file(path);
1840 }
1841 if !existed {
1842 let _ = std::fs::remove_dir(&dir);
1843 }
1844 return Err(e);
1845 }
1846 task.attachments.extend(names.iter().cloned());
1847 Ok(names)
1848 }
1849
1850 pub fn attach_and_put(&self, task: &mut Task, sources: &[PathBuf]) -> Result<Vec<String>> {
1861 let dir = self.attachments_dir(&task.id);
1862 let existed = dir.is_dir();
1863 let before = task.attachments.len();
1864 let names = self.attach(task, sources)?;
1865 if let Err(e) = self.put(task) {
1866 for name in &names {
1867 let _ = std::fs::remove_file(dir.join(name));
1868 }
1869 if !existed {
1870 let _ = std::fs::remove_dir(&dir);
1871 }
1872 task.attachments.truncate(before);
1873 return Err(e);
1874 }
1875 Ok(names)
1876 }
1877
1878 pub fn attachment_paths(&self, task: &Task) -> Vec<PathBuf> {
1882 let dir = self.attachments_dir(&task.id);
1883 task.attachments
1884 .iter()
1885 .map(|n| {
1886 let p = dir.join(n);
1887 std::path::absolute(&p).unwrap_or(p)
1888 })
1889 .collect()
1890 }
1891
1892 pub fn put(&self, task: &mut Task) -> Result<()> {
1901 let _lock = self.lock_task(&task.id)?;
1902 self.put_unlocked(task)
1903 }
1904
1905 pub fn create_new(&self, task: &mut Task) -> Result<bool> {
1910 let _lock = self.lock_task(&task.id)?;
1911 if self.path_of(&task.id).exists() {
1912 return Ok(false);
1913 }
1914 self.put_unlocked(task)?;
1915 Ok(true)
1916 }
1917
1918 fn put_unlocked(&self, task: &mut Task) -> Result<()> {
1920 if let Ok(stored) = read_path(&self.path_of(&task.id)) {
1921 for run in stored.runs {
1922 if !task.runs.contains(&run) {
1923 task.runs.push(run);
1924 }
1925 }
1926 for p in stored.passes {
1927 if !task
1928 .passes
1929 .iter()
1930 .any(|q| q.run == p.run && q.pass_index == p.pass_index)
1931 {
1932 task.passes.push(p);
1933 }
1934 }
1935 if let Some(n) = stored.chat_notice
1938 && task.chat_notice.as_ref().is_none_or(|mine| mine.at < n.at)
1939 {
1940 task.chat_notice = Some(n);
1941 }
1942 }
1943 task.updated_at = Timestamp::now();
1944 std::fs::create_dir_all(&self.root)
1945 .with_context(|| format!("create {}", self.root.display()))?;
1946 let body = serde_json::to_string_pretty(task).context("serialize task")?;
1947 let path = self.path_of(&task.id);
1948 let tmp = path.with_extension("json.tmp");
1949 std::fs::write(&tmp, &body).with_context(|| format!("write {}", tmp.display()))?;
1950 std::fs::rename(&tmp, &path).with_context(|| format!("replace {}", path.display()))?;
1951 if let (Some(notice), Some(home)) = (
1956 crate::notices::task_held(task),
1957 self.root.parent().filter(|p| !p.as_os_str().is_empty()),
1958 ) {
1959 crate::notices::raise_in(home, notice);
1960 }
1961 Ok(())
1962 }
1963
1964 pub fn modify(&self, id: &str, f: impl FnOnce(&mut Task) -> bool) -> Result<bool> {
1969 let id = self.resolve_id(id)?;
1970 let _lock = self.lock_task(&id)?;
1971 let mut task = self.get(&id)?;
1972 if !f(&mut task) {
1973 return Ok(false);
1974 }
1975 self.put_unlocked(&mut task)?;
1976 Ok(true)
1977 }
1978
1979 pub fn link_run(&self, id: &str, run: &str) -> Result<Task> {
1984 let id = self.resolve_id(id)?;
1985 let _lock = self.lock_task(&id)?;
1988 let mut task = self.get(&id)?;
1989 if task.link_run(run) {
1990 self.put_unlocked(&mut task)?;
1991 }
1992 Ok(task)
1993 }
1994
1995 fn lock_task(&self, id: &str) -> Result<TaskLock> {
2003 std::fs::create_dir_all(&self.root)
2004 .with_context(|| format!("create {}", self.root.display()))?;
2005 let path = self.root.join(format!("{id}.write-lock"));
2006 let started = std::time::Instant::now();
2007 loop {
2008 match std::fs::OpenOptions::new()
2009 .write(true)
2010 .create_new(true)
2011 .open(&path)
2012 {
2013 Ok(mut file) => {
2014 use std::io::Write;
2015 let token = owner_token();
2016 if let Err(e) = file.write_all(token.as_bytes()) {
2017 drop(file);
2018 let _ = std::fs::remove_file(&path);
2019 return Err(e).with_context(|| format!("lock {}", path.display()));
2020 }
2021 return Ok(TaskLock { path, token });
2022 }
2023 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
2024 let judged = std::fs::read_to_string(&path).ok();
2027 let broken = judged
2028 .filter(|_| older_than_stale(&path))
2029 .is_some_and(|judged| break_stale(&path, &judged));
2030 if !broken {
2034 if started.elapsed() > TASK_LOCK_STALE {
2035 bail!("could not lock task {id}");
2036 }
2037 std::thread::sleep(std::time::Duration::from_millis(15));
2038 }
2039 }
2040 Err(e)
2044 if e.kind() == std::io::ErrorKind::PermissionDenied
2045 && started.elapsed() <= TASK_LOCK_STALE =>
2046 {
2047 std::thread::sleep(std::time::Duration::from_millis(15));
2048 }
2049 Err(e) => return Err(e).with_context(|| format!("lock {}", path.display())),
2050 }
2051 }
2052 }
2053
2054 pub fn get(&self, id: &str) -> Result<Task> {
2056 let resolved = self.resolve_id(id)?;
2057 read_path(&self.path_of(&resolved))
2058 }
2059
2060 pub fn remove(&self, id: &str, in_flight: bool, questions: &Questions) -> Result<Removal> {
2092 let _ = questions;
2093 let resolved = self.resolve_id(id)?;
2094 if in_flight {
2095 bail!("task {resolved} is being run by a live daemon right now");
2096 }
2097 self.write_tombstone(&resolved)?;
2098 if let Err(e) = self.remove_record_with_attachments(&resolved, |p| std::fs::remove_file(p))
2099 {
2100 if self.path_of(&resolved).exists() {
2104 let _ = std::fs::remove_file(self.tombstone_path(&resolved));
2105 }
2106 return Err(e);
2107 }
2108 let (released, still_blocked) = self.release_dependents_of(&resolved);
2109 Ok(Removal {
2110 id: resolved,
2111 released,
2112 still_blocked,
2113 })
2114 }
2115
2116 fn tombstone_path(&self, id: &str) -> PathBuf {
2119 self.root.join(format!("{id}.removed"))
2120 }
2121
2122 fn write_tombstone(&self, id: &str) -> Result<()> {
2123 let path = self.tombstone_path(id);
2124 let tmp = self.root.join(format!("{id}.removed.tmp"));
2125 std::fs::write(&tmp, b"")
2126 .and_then(|()| std::fs::rename(&tmp, &path))
2127 .with_context(|| format!("write {}", path.display()))
2128 }
2129
2130 fn was_deleted(&self, id: &str) -> bool {
2134 self.tombstone_path(id).is_file() && !self.path_of(id).exists()
2135 }
2136
2137 pub fn apply_deleted_blockers(&self, task: &mut Task) -> Vec<String> {
2141 let deleted = deleted_blockers(self, &task.blocked_by);
2142 deleted
2143 .into_iter()
2144 .filter(|id| task.dependency_deleted(id))
2145 .collect()
2146 }
2147
2148 pub fn note_dependency_deleted(&self, dependent: &Task, deleted: &str) {
2152 let Some(home) = self.root.parent().filter(|p| !p.as_os_str().is_empty()) else {
2153 return;
2154 };
2155 let ja = crate::lang::is_japanese(&crate::lang::of_repo(&dependent.repo));
2156 let waiting = dependent.status == TaskStatus::Blocked;
2157 let message = match (ja, waiting) {
2158 (true, false) => format!(
2159 "タスク {} は、待っていた {} が削除されたため待機を解除し、元の状態に戻しました",
2160 dependent.short(),
2161 short(deleted)
2162 ),
2163 (true, true) => format!(
2164 "タスク {} は、待っていた {} が削除されたため、残りの依存を待っています",
2165 dependent.short(),
2166 short(deleted)
2167 ),
2168 (false, false) => format!(
2169 "Task {} stopped waiting on {} because it was deleted, and returned to its previous state",
2170 dependent.short(),
2171 short(deleted)
2172 ),
2173 (false, true) => format!(
2174 "Task {} stopped waiting on {} because it was deleted, and is still waiting on its other dependencies",
2175 dependent.short(),
2176 short(deleted)
2177 ),
2178 };
2179 crate::notices::raise_in(
2180 home,
2181 crate::notices::Notice::info(
2182 &format!("unblocked:{}:{}", dependent.id, deleted),
2183 message,
2184 )
2185 .link(crate::notices::Link::Task {
2186 id: dependent.id.clone(),
2187 }),
2188 );
2189 }
2190
2191 fn release_dependents_of(&self, dependency: &str) -> (Vec<String>, Vec<String>) {
2196 let (mut released, mut still_blocked) = (Vec::new(), Vec::new());
2197 for listed in self.list() {
2198 if listed.status != TaskStatus::Blocked
2199 || !listed.blocked_by.iter().any(|b| b == dependency)
2200 {
2201 continue;
2202 }
2203 let Ok(_claim) = self.claim(&listed.id) else {
2204 continue;
2205 };
2206 let Ok(mut task) = self.get(&listed.id) else {
2207 continue;
2208 };
2209 if !task.dependency_deleted(dependency) {
2210 continue;
2211 }
2212 if self.put(&mut task).is_err() {
2213 continue;
2214 }
2215 self.note_dependency_deleted(&task, dependency);
2216 if task.status == TaskStatus::Blocked {
2217 still_blocked.push(task.id.clone());
2218 } else {
2219 released.push(task.id.clone());
2220 }
2221 }
2222 (released, still_blocked)
2223 }
2224
2225 fn remove_record_with_attachments(
2229 &self,
2230 resolved: &str,
2231 remove_record: impl FnOnce(&Path) -> std::io::Result<()>,
2232 ) -> Result<()> {
2233 self.sweep_removed_attachments();
2240 let attachments = self.attachments_dir(resolved);
2241 let aside = self.root.join(format!("{resolved}.attachments.removing"));
2242 let moved = match std::fs::rename(&attachments, &aside) {
2243 Ok(()) => true,
2244 Err(e) if e.kind() == std::io::ErrorKind::NotFound => false,
2245 Err(e) => {
2246 return Err(e).with_context(|| format!("remove {}", attachments.display()));
2247 }
2248 };
2249 let path = self.path_of(resolved);
2250 if let Err(e) = remove_record(&path) {
2251 if moved {
2252 let _ = std::fs::rename(&aside, &attachments);
2253 }
2254 return Err(e).with_context(|| format!("remove {}", path.display()));
2255 }
2256 if moved {
2257 if let Err(e) = std::fs::remove_dir_all(&aside) {
2258 tracing::warn!("leftover attachments {}: {e}", aside.display());
2259 }
2260 }
2261 let lock = self.lock_path(resolved);
2262 if let Err(e) = std::fs::remove_file(&lock) {
2263 if e.kind() != std::io::ErrorKind::NotFound {
2264 return Err(e).with_context(|| format!("remove {}", lock.display()));
2265 }
2266 }
2267 Ok(())
2268 }
2269
2270 fn sweep_removed_attachments(&self) {
2276 let Ok(entries) = std::fs::read_dir(&self.root) else {
2277 return;
2278 };
2279 for entry in entries.flatten() {
2280 let name = entry.file_name();
2281 let name = name.to_string_lossy();
2282 let Some(id) = name.strip_suffix(".attachments.removing") else {
2283 continue;
2284 };
2285 if !self.path_of(id).exists() {
2288 if let Err(e) = std::fs::remove_dir_all(entry.path()) {
2289 tracing::warn!("leftover attachments {}: {e}", entry.path().display());
2290 }
2291 }
2292 }
2293 self.sweep_tombstones();
2294 }
2295
2296 fn sweep_tombstones(&self) {
2305 let Ok(entries) = std::fs::read_dir(&self.root) else {
2306 return;
2307 };
2308 let tasks = self.list();
2309 for entry in entries.flatten() {
2310 let name = entry.file_name();
2311 let name = name.to_string_lossy();
2312 let Some(id) = name.strip_suffix(".removed") else {
2313 continue;
2314 };
2315 if self.path_of(id).exists()
2316 || tasks.iter().any(|t| t.blocked_by.iter().any(|b| b == id))
2317 {
2318 continue;
2319 }
2320 let old = entry
2321 .metadata()
2322 .and_then(|m| m.modified())
2323 .ok()
2324 .and_then(|m| m.elapsed().ok())
2325 .is_some_and(|age| age >= TOMBSTONE_GRACE);
2326 if old {
2327 let _ = std::fs::remove_file(entry.path());
2328 }
2329 }
2330 }
2331
2332 fn lock_path(&self, id: &str) -> PathBuf {
2335 self.root.join(format!("{id}.lock"))
2336 }
2337
2338 pub fn list(&self) -> Vec<Task> {
2351 let mut tasks: Vec<Task> = std::fs::read_dir(&self.root)
2352 .into_iter()
2353 .flatten()
2354 .flatten()
2355 .map(|e| e.path())
2356 .filter(|p| p.extension().is_some_and(|x| x == "json"))
2357 .filter_map(|p| read_path(&p).ok())
2358 .collect();
2359 tasks.sort_unstable_by(|a, b| b.priority.cmp(&a.priority).then_with(|| b.id.cmp(&a.id)));
2360 tasks
2361 }
2362
2363 pub fn superseded(&self) -> HashMap<String, String> {
2376 let mut by = HashMap::new();
2377 for task in self.list() {
2378 for earlier in &task.runs {
2379 if let Some(later) = task.successor_of(earlier) {
2380 by.insert(earlier.clone(), later.clone());
2381 }
2382 }
2383 }
2384 by
2385 }
2386
2387 pub fn superseded_by(&self, run: &str) -> Option<String> {
2395 for task in self.list() {
2396 if task.runs.iter().any(|r| r == run) {
2397 return task.successor_of(run).cloned();
2398 }
2399 }
2400 None
2401 }
2402
2403 pub fn latest_attempt(&self, run: &str) -> Option<String> {
2414 for task in self.list() {
2415 if task.runs.iter().any(|r| r == run) {
2416 return task.runs.last().filter(|last| **last != run).cloned();
2417 }
2418 }
2419 None
2420 }
2421
2422 pub fn next_runnable(&self) -> Option<Task> {
2427 let mut runnable: Vec<Task> = self
2428 .list()
2429 .into_iter()
2430 .filter(|t| t.status.runnable())
2431 .collect();
2432 runnable.sort_unstable_by(|a, b| b.priority.cmp(&a.priority).then(a.id.cmp(&b.id)));
2433 runnable.into_iter().next()
2434 }
2435
2436 pub fn claim(&self, id: &str) -> Result<Claim> {
2443 std::fs::create_dir_all(&self.root)
2444 .with_context(|| format!("create {}", self.root.display()))?;
2445 let path = self.lock_path(id);
2446 match std::fs::OpenOptions::new()
2447 .write(true)
2448 .create_new(true)
2449 .open(&path)
2450 {
2451 Ok(mut f) => {
2452 use std::io::Write as _;
2453 let _ = writeln!(f, "{}", std::process::id());
2455 Ok(Claim { path })
2456 }
2457 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
2458 bail!("task {id} is already claimed ({} exists)", path.display())
2459 }
2460 Err(e) => Err(e).with_context(|| format!("lock {}", path.display())),
2461 }
2462 }
2463
2464 pub fn resolve_id(&self, prefix: &str) -> Result<String> {
2466 if self.path_of(prefix).is_file() {
2467 return Ok(prefix.to_owned());
2468 }
2469 let hits: Vec<String> = self
2470 .list()
2471 .into_iter()
2472 .map(|t| t.id)
2473 .filter(|id| id.starts_with(prefix) || id.ends_with(prefix))
2474 .collect();
2475 match hits.len() {
2476 1 => Ok(hits.into_iter().next().expect("exactly one hit")),
2477 0 => bail!("no task matches `{prefix}`"),
2478 _ => bail!(
2479 "`{prefix}` matches {} tasks: {}",
2480 hits.len(),
2481 hits.join(", ")
2482 ),
2483 }
2484 }
2485
2486 pub fn revision(&self) -> u64 {
2493 self.revision_excluding(&std::collections::BTreeSet::new())
2494 }
2495
2496 pub fn revision_excluding(&self, skip: &std::collections::BTreeSet<String>) -> u64 {
2499 use std::hash::{Hash as _, Hasher as _};
2500
2501 let mut entries: Vec<(String, u64)> = std::fs::read_dir(&self.root)
2502 .into_iter()
2503 .flatten()
2504 .flatten()
2505 .filter(|e| e.path().extension().is_some_and(|ext| ext == "json"))
2506 .filter(|e| {
2507 let path = e.path();
2508 !path
2509 .file_stem()
2510 .is_some_and(|stem| skip.contains(stem.to_string_lossy().as_ref()))
2511 })
2512 .filter_map(|e| {
2513 let name = e.file_name().to_string_lossy().into_owned();
2514 let mtime = e
2515 .metadata()
2516 .ok()?
2517 .modified()
2518 .ok()?
2519 .duration_since(std::time::UNIX_EPOCH)
2520 .ok()?
2521 .as_millis() as u64;
2522 Some((name, mtime))
2523 })
2524 .collect();
2525
2526 if entries.is_empty() {
2527 return 0;
2528 }
2529
2530 entries.sort_unstable();
2531 let mut hasher = std::hash::DefaultHasher::new();
2532 for (name, mtime) in &entries {
2533 name.hash(&mut hasher);
2534 mtime.hash(&mut hasher);
2535 }
2536 let h = hasher.finish();
2537 if h == 0 { 1 } else { h }
2538 }
2539}
2540
2541const TOMBSTONE_GRACE: std::time::Duration = std::time::Duration::from_secs(3600);
2544
2545#[derive(Debug, Clone)]
2547pub struct Removal {
2548 pub id: String,
2550 pub released: Vec<String>,
2554 pub still_blocked: Vec<String>,
2557}
2558
2559#[derive(Debug)]
2561pub struct Claim {
2562 path: PathBuf,
2563}
2564
2565impl Drop for Claim {
2566 fn drop(&mut self) {
2567 let _ = std::fs::remove_file(&self.path);
2568 }
2569}
2570
2571pub fn title_from(instruction: &str, max: usize) -> String {
2574 let Some(line) = first_line(instruction) else {
2575 return "(empty task)".to_owned();
2576 };
2577 if line.chars().count() <= max {
2578 return line.to_owned();
2579 }
2580 let head: String = line.chars().take(max.saturating_sub(1)).collect();
2581 format!("{head}…")
2582}
2583
2584pub(crate) fn first_line(instruction: &str) -> Option<&str> {
2590 let line = instruction
2591 .lines()
2592 .map(str::trim)
2593 .find(|l| !l.is_empty())?
2594 .trim_start_matches(['#', '-', '*', '>', ' '])
2595 .trim();
2596 (!line.is_empty()).then_some(line)
2597}
2598
2599fn read_path(path: &Path) -> Result<Task> {
2600 let body = std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;
2601 let task: Task =
2602 serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))?;
2603 if task.schema > SCHEMA {
2609 bail!(
2610 "task {} was written by a different magi (schema {}, this build \
2611 speaks {SCHEMA})",
2612 task.id,
2613 task.schema
2614 );
2615 }
2616 Ok(task)
2617}
2618
2619pub fn missing_blockers(
2633 queue: &Queue,
2634 questions: &Questions,
2635 blocked_by: &[String],
2636) -> Vec<String> {
2637 blocked_by
2638 .iter()
2639 .filter(|id| {
2640 !queue.path_of(id).is_file()
2641 && !questions.path_of(id).is_file()
2642 && !queue.was_deleted(id)
2643 })
2644 .cloned()
2645 .collect()
2646}
2647
2648pub fn deleted_blockers(queue: &Queue, blocked_by: &[String]) -> Vec<String> {
2653 blocked_by
2654 .iter()
2655 .filter(|id| queue.was_deleted(id))
2656 .cloned()
2657 .collect()
2658}
2659
2660pub fn missing_blocker_hold_reason(blocked_by: &[String], missing: &[String]) -> String {
2672 missing_blocker_hold_reason_in(blocked_by, missing, "en")
2673}
2674
2675pub fn missing_blocker_hold_reason_in(
2677 blocked_by: &[String],
2678 missing: &[String],
2679 language: &str,
2680) -> String {
2681 if crate::lang::is_japanese(language) {
2682 format!(
2683 "{} を待っていましたが、{} はディスク上に存在しません - `magi task triage` を参照",
2684 blocked_by.join(", "),
2685 missing.join(", "),
2686 )
2687 } else {
2688 format!(
2689 "blocked on {} but {} no longer exist(s) on disk - see `magi task triage`",
2690 blocked_by.join(", "),
2691 missing.join(", "),
2692 )
2693 }
2694}
2695
2696pub fn short(id: &str) -> &str {
2698 id.split('-').next_back().unwrap_or(id)
2699}
2700
2701fn new_id() -> String {
2702 let stamp = jiff::Zoned::now().strftime("%Y%m%d-%H%M%S");
2703 let seed = crate::rng::entropy();
2704 format!("{stamp}-{:04x}", (seed ^ (seed >> 32)) & 0xffff)
2705}
2706
2707#[cfg(test)]
2708mod tests {
2709 #[test]
2710 fn explicit_resumption_is_not_invented_for_legacy_or_automatic_release() {
2711 let t = Task::new(
2712 "retry".into(),
2713 "do it".into(),
2714 PathBuf::from("."),
2715 Source::Human,
2716 );
2717 let mut value = serde_json::to_value(&t).unwrap();
2718 for field in ["resumption", "resumption_history", "operator_decided_at"] {
2719 value.as_object_mut().unwrap().remove(field);
2720 }
2721 value["schema"] = serde_json::json!(15);
2722 let mut legacy: Task = serde_json::from_value(value).unwrap();
2723 legacy.hold_machine(Some("automatic retry".into()));
2724 legacy.release();
2725 assert!(legacy.resumption.is_none());
2726 assert!(legacy.resumption_history.is_empty());
2727 assert!(legacy.operator_decided_at.is_none());
2728 legacy.release_operator("cli", None);
2729 legacy.start("run".into());
2730 let reloaded: Task =
2731 serde_json::from_str(&serde_json::to_string(&legacy).unwrap()).unwrap();
2732 assert!(reloaded.resume_override.is_none());
2733 assert_eq!(reloaded.resumption.as_ref().unwrap().generation, 1);
2734 }
2735
2736 #[test]
2737 fn merge_over_lets_the_later_choice_win_and_keeps_the_rest() {
2738 let mut base = RunOverrides {
2739 merge: Some("pr".to_owned()),
2740 candidates: Some(3),
2741 ..RunOverrides::default()
2742 };
2743 base.merge_over(&RunOverrides {
2744 merge: Some("none".to_owned()),
2745 seed: Some(7),
2746 ..RunOverrides::default()
2747 });
2748 assert_eq!(base.merge.as_deref(), Some("none"));
2749 assert_eq!(base.candidates, Some(3));
2750 assert_eq!(base.seed, Some(7));
2751 }
2752
2753 #[test]
2754 fn an_already_landed_task_is_done_with_its_attempt_refunded() {
2755 let mut t = task("relanded");
2756 t.attempts = 1;
2757 t.status = TaskStatus::Running;
2758 t.already_landed("already in main as 0e368de");
2759 assert_eq!(t.status, TaskStatus::Done);
2760 assert_eq!(t.attempts, 0);
2761 assert!(t.hold_reason.is_none());
2762 assert_eq!(t.last_error.as_deref(), Some("already in main as 0e368de"));
2763 }
2764
2765 #[test]
2766 fn missing_blocker_reason_follows_the_language() {
2767 let b = vec!["a".to_owned()];
2768 let en = missing_blocker_hold_reason_in(&b, &b, "en");
2769 assert_eq!(en, missing_blocker_hold_reason(&b, &b));
2770 assert!(en.starts_with("blocked on a"));
2771 assert!(missing_blocker_hold_reason_in(&b, &b, "ja").contains("存在しません"));
2772 assert_eq!(missing_blocker_hold_reason_in(&b, &b, "de"), en);
2773 }
2774
2775 use super::*;
2776
2777 #[test]
2778 fn triage_applied_survives_release_and_old_records_read_as_empty() {
2779 let mut t = Task::new(
2780 "t".to_owned(),
2781 "i".to_owned(),
2782 PathBuf::from("r"),
2783 Source::Human,
2784 );
2785 t.mark_triage_applied("q1");
2786 t.mark_triage_applied("q1");
2787 t.hold_machine(Some("x".to_owned()));
2788 t.release();
2789 assert_eq!(t.triage_applied, ["q1"]);
2790 assert!(t.triage_applied("q1") && !t.triage_applied("q2"));
2791
2792 let mut v = serde_json::to_value(&t).unwrap();
2793 v.as_object_mut().unwrap().remove("triage_applied");
2794 let old: Task = serde_json::from_value(v).unwrap();
2795 assert!(old.triage_applied.is_empty());
2796 }
2797
2798 #[test]
2799 fn task_counts_of_empty_is_all_zero() {
2800 assert_eq!(TaskCounts::of(&[]), TaskCounts::default());
2801 }
2802
2803 #[test]
2804 fn task_counts_of_tallies_every_status() {
2805 let mut queued = Task::new(
2806 "q".to_owned(),
2807 "i".to_owned(),
2808 PathBuf::from("."),
2809 Source::Human,
2810 );
2811 queued.status = TaskStatus::Queued;
2812 let mut running = queued.clone();
2813 running.status = TaskStatus::Running;
2814 let mut done = queued.clone();
2815 done.status = TaskStatus::Done;
2816 let mut failed = queued.clone();
2817 failed.status = TaskStatus::Failed;
2818 let mut held = queued.clone();
2819 held.status = TaskStatus::Held;
2820 let mut blocked = queued.clone();
2821 blocked.status = TaskStatus::Blocked;
2822
2823 let mut parked = queued.clone();
2824 parked.status = TaskStatus::Parked;
2825
2826 let counts = TaskCounts::of(&[
2827 queued,
2828 running,
2829 done.clone(),
2830 done,
2831 failed,
2832 held,
2833 blocked,
2834 parked,
2835 ]);
2836 assert_eq!(
2837 counts,
2838 TaskCounts {
2839 queued: 1,
2840 running: 1,
2841 done: 2,
2842 failed: 1,
2843 held: 1,
2844 blocked: 1,
2845 parked: 1,
2846 }
2847 );
2848 }
2849
2850 #[test]
2851 fn task_implementers_persist_normalized_without_losing_history() {
2852 let (_dir, q) = queue();
2853 let mut t = task("keep me");
2854 t.hold_manual(Some("waiting".into()));
2855 t.runs.push("earlier-run".into());
2856 t.attachments.push("reference.txt".into());
2857 let cfg: crate::config::Config =
2858 toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
2859 .unwrap();
2860 q.put(&mut t).unwrap();
2861 let original = serde_json::to_value(&t).unwrap();
2862 for n in [2, 1, 2] {
2863 t.set_implementers(n, &cfg).unwrap();
2864 q.put(&mut t).unwrap();
2865 t = q.get(&t.id).unwrap();
2866 assert_eq!(t.implementers(), Some(usize::from(n)));
2867 assert_eq!(t.solo, n == 1);
2868 if n == 1 {
2869 assert!(t.overrides.is_none());
2870 }
2871 let mut actual = serde_json::to_value(&t).unwrap();
2872 for field in ["solo", "overrides", "updated_at"] {
2873 actual[field] = original[field].clone();
2874 }
2875 assert_eq!(actual, original);
2876 }
2877 t.overrides.as_mut().unwrap().judges = Some(2);
2878 t.set_implementers(1, &cfg).unwrap();
2879 assert_eq!(t.overrides.as_ref().unwrap().judges, Some(2));
2880 assert_eq!(t.overrides.as_ref().unwrap().candidates, None);
2881 }
2882
2883 #[test]
2884 fn task_implementers_old_records_keep_inheritance_until_changed() {
2885 let mut value = serde_json::to_value(task("old task")).unwrap();
2886 value.as_object_mut().unwrap().remove("solo");
2887 value.as_object_mut().unwrap().remove("overrides");
2888 let mut old: Task = serde_json::from_value(value).unwrap();
2889 assert_eq!(old.implementers(), None);
2890 old.set_implementers(1, &crate::config::Config::default())
2891 .unwrap();
2892 assert!(old.solo);
2893 assert!(old.overrides.is_none());
2894 }
2895
2896 #[test]
2897 fn task_implementers_reject_invalid_counts_and_states() {
2898 let cfg = crate::config::Config::default();
2899 let mut t = task("unchanged");
2900 for n in [0, 4, 255] {
2901 assert!(t.set_implementers(n, &cfg).is_err());
2902 }
2903 for status in [
2904 TaskStatus::Running,
2905 TaskStatus::Done,
2906 TaskStatus::Failed,
2907 TaskStatus::Blocked,
2908 TaskStatus::Parked,
2909 ] {
2910 t.status = status;
2911 let before = serde_json::to_value(&t).unwrap();
2912 assert!(t.set_implementers(1, &cfg).is_err());
2913 assert_eq!(serde_json::to_value(&t).unwrap(), before);
2914 }
2915 }
2916
2917 fn queue() -> (tempfile::TempDir, Queue) {
2920 let dir = tempfile::tempdir().unwrap();
2921 let q = Queue::at(dir.path().join("queue"));
2922 (dir, q)
2923 }
2924
2925 #[test]
2926 fn putting_a_machine_held_task_files_a_notification_beside_the_queue() {
2927 let dir = tempfile::tempdir().unwrap();
2928 let q = Queue::at(dir.path().join("queue"));
2929 let mut t = task("held");
2930 q.put(&mut t).unwrap();
2931 assert_eq!(
2932 crate::notices::Notices::at(dir.path().join("notifications"))
2933 .list()
2934 .len(),
2935 0
2936 );
2937 t.hold_machine(Some("out of attempts".to_owned()));
2938 q.put(&mut t).unwrap();
2939 let listed = crate::notices::Notices::at(dir.path().join("notifications")).list();
2940 assert_eq!(listed.len(), 1);
2941 assert!(listed[0].message.contains("out of attempts"));
2942 }
2943
2944 fn task(title: &str) -> Task {
2945 Task::new(
2946 title.to_owned(),
2947 format!("do {title}"),
2948 PathBuf::from("."),
2949 Source::Human,
2950 )
2951 }
2952
2953 #[test]
2954 fn attempt_limit_inherits_old_records_and_controls_failure() {
2955 let mut t = task("budget");
2956 let mut old = serde_json::to_value(&t).unwrap();
2957 old.as_object_mut().unwrap().remove("attempt_limit");
2958 old["schema"] = serde_json::json!(15);
2959 let legacy: Task = serde_json::from_value(old).unwrap();
2960 assert_eq!(legacy.attempt_limit, None);
2961 assert_eq!(legacy.effective_attempt_limit(2), 2);
2962 t.attempts = 2;
2963 t.change_attempt_limit(NonZeroUsize::new(3)).unwrap();
2964 t.fail("retry", 1);
2965 assert_eq!(t.status, TaskStatus::Failed);
2966 t.attempts = 3;
2967 t.fail("stop", 10);
2968 assert_eq!(t.status, TaskStatus::Held);
2969 t.change_attempt_limit(None).unwrap();
2970 assert_eq!(t.status, TaskStatus::Held);
2971 assert_eq!(t.attempts, 3);
2972 t.fail("inherit", 4);
2973 assert_eq!(t.status, TaskStatus::Failed);
2974 for status in [
2975 TaskStatus::Running,
2976 TaskStatus::Done,
2977 TaskStatus::Failed,
2978 TaskStatus::Blocked,
2979 TaskStatus::Parked,
2980 ] {
2981 t.status = status;
2982 assert!(t.change_attempt_limit(NonZeroUsize::new(1)).is_err());
2983 assert_eq!(t.attempt_limit, None);
2984 }
2985 }
2986
2987 #[test]
2988 fn earlier_attempts_is_every_recorded_run_and_agrees_with_the_display() {
2989 let mut t = task("retried");
2990 assert!(
2991 t.earlier_attempts().is_empty(),
2992 "a first attempt takes nothing over"
2993 );
2994 t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned()];
2995 assert_eq!(t.earlier_attempts(), ["aaaa", "bbbb"]);
2996 assert_eq!(t.successor_of("aaaa"), Some(&"bbbb".to_owned()));
2998 assert_eq!(t.successor_of("bbbb"), None);
2999 assert_eq!(t.successor_of("zzzz"), None);
3000 }
3001
3002 #[test]
3003 fn resumed_runs_are_superseded_only_after_their_last_occurrence() {
3004 let (_dir, q) = queue();
3005 let mut t = task("resumed");
3006 for (runs, successor) in [
3007 (vec!["aaaa", "aaaa"], None),
3008 (vec!["aaaa", "bbbb", "aaaa"], None),
3009 (vec!["aaaa", "aaaa", "bbbb"], Some("bbbb")),
3010 (vec!["aaaa", "bbbb", "aaaa", "cccc"], Some("cccc")),
3011 ] {
3012 t.runs = runs.into_iter().map(str::to_owned).collect();
3013 q.put(&mut t).unwrap();
3014
3015 assert_eq!(t.successor_of("aaaa").map(String::as_str), successor);
3016 assert_eq!(q.superseded_by("aaaa").as_deref(), successor);
3017 assert_eq!(q.superseded().get("aaaa").map(String::as_str), successor);
3018 }
3019 }
3020
3021 #[test]
3022 fn superseded_by_names_the_next_attempt_and_none_for_the_last() {
3023 let (_dir, q) = queue();
3024 let mut t = task("retried");
3025 t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned(), "cccc".to_owned()];
3026 q.put(&mut t).unwrap();
3027
3028 assert_eq!(q.superseded_by("aaaa"), Some("bbbb".to_owned()));
3029 assert_eq!(q.superseded_by("bbbb"), Some("cccc".to_owned()));
3030 assert_eq!(
3031 q.superseded_by("cccc"),
3032 None,
3033 "the latest attempt replaces nothing"
3034 );
3035 assert_eq!(
3036 q.superseded_by("never-heard-of-it"),
3037 None,
3038 "a run belonging to no task on this queue is not superseded"
3039 );
3040
3041 let mut by = HashMap::new();
3042 by.insert("aaaa".to_owned(), "bbbb".to_owned());
3043 by.insert("bbbb".to_owned(), "cccc".to_owned());
3044 assert_eq!(
3045 q.superseded(),
3046 by,
3047 "the whole-map and single-run forms must agree"
3048 );
3049 }
3050
3051 #[test]
3052 fn superseded_attempts_is_empty_until_the_task_is_done() {
3053 let mut t = task("retried");
3054 t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned()];
3055 t.status = TaskStatus::Failed;
3056 assert_eq!(
3057 t.superseded_attempts(true),
3058 &[] as &[String],
3059 "a task still retrying has no attempt yet that a later one made moot"
3060 );
3061
3062 t.status = TaskStatus::Running;
3063 assert_eq!(t.superseded_attempts(true), &[] as &[String]);
3064 }
3065
3066 #[test]
3067 fn superseded_attempts_names_every_run_before_the_one_that_succeeded() {
3068 let mut t = task("retried");
3069 t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned(), "cccc".to_owned()];
3070 t.status = TaskStatus::Done;
3071 assert_eq!(
3072 t.superseded_attempts(true),
3073 &["aaaa".to_owned(), "bbbb".to_owned()],
3074 "cccc is the attempt whose success made the task done, and stays out"
3075 );
3076 }
3077
3078 #[test]
3079 fn superseded_attempts_is_empty_for_a_done_task_with_only_one_attempt() {
3080 let mut t = task("first try landed");
3081 t.runs = vec!["aaaa".to_owned()];
3082 t.status = TaskStatus::Done;
3083 assert_eq!(t.superseded_attempts(true), &[] as &[String]);
3084 }
3085
3086 #[test]
3087 fn superseded_attempts_is_empty_when_the_last_run_never_actually_succeeded() {
3088 let mut t = task("closed by hand after a manual merge");
3095 t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned()];
3096 t.status = TaskStatus::Done;
3097 assert_eq!(
3098 t.superseded_attempts(false),
3099 &[] as &[String],
3100 "nothing here is provably why the task is done, so nothing is superseded"
3101 );
3102 }
3103
3104 #[test]
3105 fn latest_attempt_names_the_chain_s_current_head_not_just_the_next_one() {
3106 let (_dir, q) = queue();
3107 let mut t = task("retried twice");
3108 t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned(), "cccc".to_owned()];
3109 q.put(&mut t).unwrap();
3110
3111 assert_eq!(
3112 q.latest_attempt("aaaa"),
3113 Some("cccc".to_owned()),
3114 "an old attempt points straight at the chain's current head, not the \
3115 next attempt in the middle of it"
3116 );
3117 assert_eq!(q.latest_attempt("bbbb"), Some("cccc".to_owned()));
3118 assert_eq!(
3119 q.latest_attempt("cccc"),
3120 None,
3121 "the latest attempt is not superseded by anything"
3122 );
3123 assert_eq!(
3124 q.latest_attempt("never-heard-of-it"),
3125 None,
3126 "a run belonging to no task on this queue is not superseded"
3127 );
3128 }
3129
3130 #[test]
3131 fn a_markdown_heading_is_the_title_not_decoration() {
3132 assert_eq!(
3137 title_from("# Rework the config loader\n\nIt re-reads it.\n", 40),
3138 "Rework the config loader"
3139 );
3140 assert_eq!(title_from("- fix the thing", 40), "fix the thing");
3141 assert_eq!(title_from("> quoted task", 40), "quoted task");
3142 assert_eq!(title_from(" \n\n", 40), "(empty task)");
3144 assert_eq!(title_from("###\n", 40), "(empty task)");
3145 }
3146
3147 #[test]
3148 fn a_long_title_is_elided_by_characters_not_bytes() {
3149 let long = "課題".repeat(30);
3151 let title = title_from(&long, 10);
3152 assert_eq!(title.chars().count(), 10);
3153 assert!(title.ends_with('…'));
3154 }
3155
3156 #[test]
3157 fn priority_wins_and_ties_break_oldest_first() {
3158 let (_dir, q) = queue();
3159 let mut a = task("first");
3160 let mut b = task("second");
3161 let mut c = task("urgent");
3162 a.id = "20260101-000001-aaaa".to_owned();
3164 b.id = "20260101-000002-bbbb".to_owned();
3165 c.id = "20260101-000003-cccc".to_owned();
3166 c.priority = 5;
3167 for t in [&mut a, &mut b, &mut c] {
3168 q.put(t).unwrap();
3169 }
3170
3171 assert_eq!(q.next_runnable().unwrap().id, c.id);
3173 c.hold_machine(None);
3174 q.put(&mut c).unwrap();
3175 assert_eq!(q.next_runnable().unwrap().id, a.id);
3177 assert_eq!(q.list().len(), 3, "b is still waiting its turn");
3178 }
3179
3180 #[test]
3181 fn a_blocked_task_never_starves_another_runnable_one() {
3182 let (_dir, q) = queue();
3183 let mut blocked = task("blocked");
3184 blocked.block(vec!["something".to_owned()], None);
3185 q.put(&mut blocked).unwrap();
3186
3187 let mut runnable = task("free to go");
3188 q.put(&mut runnable).unwrap();
3189
3190 let next = q.next_runnable().expect("a runnable task is still offered");
3191 assert_eq!(next.id, runnable.id);
3192 }
3193
3194 #[test]
3195 fn a_held_task_is_never_offered_to_the_loop() {
3196 let (_dir, q) = queue();
3197 let mut t = task("held");
3198 q.put(&mut t).unwrap();
3199 assert!(q.next_runnable().is_some());
3200
3201 t.hold_machine(None);
3202 q.put(&mut t).unwrap();
3203 assert!(
3204 q.next_runnable().is_none(),
3205 "a held task must wait for a human"
3206 );
3207
3208 t.status = TaskStatus::Failed;
3210 q.put(&mut t).unwrap();
3211 assert!(q.next_runnable().is_some());
3212 }
3213
3214 #[test]
3215 fn attempts_are_capped_and_then_the_task_is_held() {
3216 let mut t = task("doomed");
3217
3218 t.start("run-1".to_owned());
3219 t.fail("gate red", 2);
3220 assert_eq!(t.status, TaskStatus::Failed, "one attempt of two: retry");
3221
3222 t.start("run-2".to_owned());
3223 t.fail("gate red", 2);
3224 assert_eq!(
3225 t.status,
3226 TaskStatus::Held,
3227 "out of attempts: stop spending money on it"
3228 );
3229 assert_eq!(t.runs, ["run-1", "run-2"]);
3230 assert_eq!(t.last_error.as_deref(), Some("gate red"));
3231 assert_eq!(
3232 t.hold_reason.as_deref(),
3233 Some("gate red"),
3234 "the hold must say why, not leave hold_reason null next to a \
3235 populated last_error"
3236 );
3237 }
3238
3239 #[test]
3240 fn handing_off_a_task_records_a_hold_reason_too() {
3241 let mut t = task("left a pull request");
3242 t.start("run-1".to_owned());
3243 t.handed_off("run ended with a pull request open [run run-1]");
3244 assert_eq!(t.status, TaskStatus::Held);
3245 assert_eq!(t.hold_source, Some(HoldSource::Machine));
3246 assert_eq!(
3247 t.hold_reason.as_deref(),
3248 Some("run ended with a pull request open [run run-1]")
3249 );
3250 assert_eq!(t.hold_reason, t.last_error);
3251 }
3252
3253 #[test]
3254 fn a_quota_stall_is_refunded_so_the_backlog_survives_the_night() {
3255 let mut t = task("stalled by quota");
3256
3257 t.start("run-1".to_owned());
3258 assert_eq!(t.attempts, 1);
3259 t.stall("judge-1, judge-2 out of quota");
3260 assert_eq!(
3261 t.attempts, 0,
3262 "a closed quota window must not spend the task's retry budget"
3263 );
3264 assert_eq!(t.status, TaskStatus::Failed, "the loop should retry it");
3265 assert_eq!(
3266 t.last_error.as_deref(),
3267 Some("judge-1, judge-2 out of quota")
3268 );
3269
3270 for _ in 0..20 {
3273 t.start("run-n".to_owned());
3274 t.stall("still out of quota");
3275 }
3276 t.start("run-real".to_owned());
3277 t.fail("gate red", 2);
3278 assert_eq!(
3279 t.status,
3280 TaskStatus::Failed,
3281 "the first attempt that was really judged is attempt one"
3282 );
3283 }
3284
3285 #[test]
3286 fn releasing_a_held_task_gives_it_a_real_second_chance() {
3287 let mut t = task("retry me");
3288 t.start("run-1".to_owned());
3289 t.fail("gate red", 1);
3290 assert_eq!(t.status, TaskStatus::Held);
3291
3292 t.release();
3293 assert_eq!(t.status, TaskStatus::Queued);
3294 assert_eq!(t.attempts, 0);
3297 assert!(t.last_error.is_none());
3298 assert_eq!(
3299 t.runs.len(),
3300 1,
3301 "history is kept: attempts reset, evidence does not"
3302 );
3303 }
3304
3305 #[test]
3306 fn a_hold_reason_survives_and_a_release_clears_it() {
3307 let mut t = task("waiting on something else");
3308 t.hold_manual(Some(
3309 "waiting for 20260101-000000-aaaa to land first".to_owned(),
3310 ));
3311 assert_eq!(t.status, TaskStatus::Held);
3312 assert_eq!(
3313 t.hold_reason.as_deref(),
3314 Some("waiting for 20260101-000000-aaaa to land first")
3315 );
3316
3317 t.hold_manual(None);
3319 assert_eq!(
3320 t.hold_reason.as_deref(),
3321 Some("waiting for 20260101-000000-aaaa to land first"),
3322 "a bare re-hold keeps whatever a human already wrote down"
3323 );
3324
3325 let mut plain = task("no reason given");
3327 plain.hold_manual(None);
3328 assert_eq!(plain.status, TaskStatus::Held);
3329 assert!(plain.hold_reason.is_none());
3330
3331 t.release();
3332 assert_eq!(t.status, TaskStatus::Queued);
3333 assert!(
3334 t.hold_reason.is_none(),
3335 "a stale reason must not greet the next person who holds this task"
3336 );
3337 }
3338
3339 #[test]
3340 fn closing_a_held_task_as_done_clears_its_hold_reason_too() {
3341 let mut t = task("landed by hand while held");
3346 t.hold_manual(Some("waiting on 3ed9".to_owned()));
3347 assert_eq!(t.hold_reason.as_deref(), Some("waiting on 3ed9"));
3348
3349 t.succeed();
3350 assert_eq!(t.status, TaskStatus::Done);
3351 assert!(
3352 t.hold_reason.is_none(),
3353 "a done task cannot still be waiting on something"
3354 );
3355 }
3356
3357 #[test]
3358 fn holding_or_closing_a_blocked_task_clears_its_dependency_too() {
3359 let mut held = task("held straight out of blocked");
3366 held.block(
3367 vec!["20260101-000000-dead".to_owned()],
3368 Some("waiting on the migration script".to_owned()),
3369 );
3370 assert_eq!(held.status, TaskStatus::Blocked);
3371
3372 held.hold_manual(None);
3373 assert_eq!(held.status, TaskStatus::Held);
3374 assert!(
3375 held.blocked_by.is_empty(),
3376 "hold overrides the wait, same as release"
3377 );
3378 assert!(held.block_reason.is_none());
3379
3380 let mut done = task("closed straight out of blocked");
3381 done.block(
3382 vec!["20260101-000000-dead".to_owned()],
3383 Some("waiting on the migration script".to_owned()),
3384 );
3385 done.succeed();
3386 assert_eq!(done.status, TaskStatus::Done);
3387 assert!(
3388 done.blocked_by.is_empty(),
3389 "a done task cannot still be waiting on a dependency"
3390 );
3391 assert!(done.block_reason.is_none());
3392 }
3393
3394 #[test]
3395 fn a_blocked_task_is_never_offered_to_the_loop() {
3396 let mut t = task("blocked");
3397 assert!(t.status.runnable());
3398 t.block(
3399 vec!["dep-id".to_owned()],
3400 Some("waits on dep-id".to_owned()),
3401 );
3402 assert_eq!(t.status, TaskStatus::Blocked);
3403 assert!(!t.status.runnable());
3404 assert_eq!(TaskStatus::Blocked.as_str(), "blocked");
3405 }
3406
3407 #[test]
3408 fn unblocking_the_last_dependency_returns_the_task_to_queued() {
3409 let mut t = task("blocked on two");
3410 t.block(
3411 vec!["a".to_owned(), "b".to_owned()],
3412 Some("waits on a and b".to_owned()),
3413 );
3414
3415 t.unblock("a");
3416 assert_eq!(t.status, TaskStatus::Blocked, "b is still outstanding");
3417 assert_eq!(t.blocked_by, ["b"]);
3418
3419 t.unblock("b");
3420 assert_eq!(t.status, TaskStatus::Queued);
3421 assert!(t.blocked_by.is_empty());
3422 assert!(t.block_reason.is_none());
3423 }
3424
3425 #[test]
3426 fn unblocking_an_id_on_a_task_that_is_not_blocked_is_a_no_op() {
3427 let mut t = task("never blocked");
3428 t.unblock("whatever");
3429 assert_eq!(t.status, TaskStatus::Queued);
3430 }
3431
3432 #[test]
3433 fn a_held_task_blocked_on_a_question_returns_to_held_not_queued() {
3434 let mut t = task("held, then asked about");
3439 t.hold_machine(Some("out of attempts".to_owned()));
3440 assert_eq!(t.status, TaskStatus::Held);
3441
3442 t.block(vec!["q1".to_owned()], Some("what now?".to_owned()));
3443 assert_eq!(t.status, TaskStatus::Blocked);
3444
3445 t.record_answer("what now?".to_owned(), "leave it held".to_owned());
3446 t.unblock("q1");
3447 assert_eq!(t.status, TaskStatus::Held, "must restore, not requeue");
3448 assert_eq!(t.hold_reason.as_deref(), Some("out of attempts"));
3449 assert_eq!(t.hold_source, Some(HoldSource::Machine));
3450 assert!(t.blocked_from.is_none(), "consumed once restored");
3451 }
3452
3453 #[test]
3454 fn a_manually_held_task_blocked_on_a_question_returns_to_held() {
3455 let mut t = task("manually held, then asked about");
3456 t.hold_manual(Some("waiting on a dependency".to_owned()));
3457
3458 t.block(vec!["q1".to_owned()], None);
3459 t.unblock("q1");
3460
3461 assert_eq!(t.status, TaskStatus::Held);
3462 assert_eq!(t.hold_source, Some(HoldSource::Manual));
3463 }
3464
3465 #[test]
3466 fn re_blocking_an_already_blocked_task_keeps_the_original_blocked_from() {
3467 let mut t = task("held, blocked twice");
3471 t.hold_machine(None);
3472 t.block(vec!["q1".to_owned()], Some("first".to_owned()));
3473 t.block(
3474 vec!["q1".to_owned(), "q2".to_owned()],
3475 Some("second".to_owned()),
3476 );
3477
3478 t.unblock("q1");
3479 assert_eq!(t.status, TaskStatus::Blocked, "q2 still outstanding");
3480 t.unblock("q2");
3481 assert_eq!(t.status, TaskStatus::Held);
3482 }
3483
3484 #[test]
3485 fn unblocking_a_task_blocked_while_running_lands_on_queued_not_running() {
3486 let mut t = task("blocked mid-run");
3490 t.start("run-1".to_owned());
3491 assert_eq!(t.status, TaskStatus::Running);
3492
3493 t.block(vec!["q1".to_owned()], None);
3494 t.unblock("q1");
3495 assert_eq!(t.status, TaskStatus::Queued);
3496 }
3497
3498 #[test]
3499 fn a_pre_schema_4_blocked_record_with_hold_evidence_restores_to_held() {
3500 let mut t = task("legacy record, held before it was blocked");
3506 t.hold_source = Some(HoldSource::Machine);
3507 t.hold_reason = Some("legacy hold reason".to_owned());
3508 t.status = TaskStatus::Blocked;
3509 t.blocked_by = vec!["q1".to_owned()];
3510 t.blocked_from = None;
3511
3512 t.unblock("q1");
3513 assert_eq!(t.status, TaskStatus::Held);
3514 }
3515
3516 #[test]
3517 fn a_pre_schema_4_blocked_record_with_no_hold_evidence_restores_to_queued() {
3518 let mut t = task("legacy record, ordinary dependency block");
3519 t.status = TaskStatus::Blocked;
3520 t.blocked_by = vec!["dep".to_owned()];
3521 t.blocked_from = None;
3522
3523 t.unblock("dep");
3524 assert_eq!(t.status, TaskStatus::Queued);
3525 }
3526
3527 #[test]
3528 fn answering_a_question_is_recorded_and_survives_a_release() {
3529 let mut t = task("asked something");
3530 t.block(vec!["q1".to_owned()], Some("which backend?".to_owned()));
3531 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
3532 t.unblock("q1");
3533 assert_eq!(t.status, TaskStatus::Queued);
3534 assert_eq!(t.answers.len(), 1);
3535 assert_eq!(t.answers[0].answer, "SQLite");
3536
3537 t.release();
3541 assert_eq!(t.answers.len(), 1, "the answer is not lost on release");
3542 }
3543
3544 #[test]
3545 fn resumption_review_branch_requires_unchanged_authored_criteria() {
3546 for source in ["cli", "web"] {
3547 let mut t = task("review old candidate");
3548 t.request_review("candidate-A".into());
3549 t.hold_for_handover(Some("candidate-A".into()), "handover refused".into());
3550 let mut unchanged = t.clone();
3551 unchanged.release_operator(source, None);
3552 assert_eq!(unchanged.review_branch.as_deref(), Some("candidate-A"));
3553 t.edit(
3554 "review approved head".into(),
3555 "Reuse measured PR head B; fix Clippy; review".into(),
3556 )
3557 .unwrap();
3558 t.release_operator(source, None);
3559 assert!(t.review_branch.is_none());
3560 assert!(t.review_instruction.is_none());
3561 let mut legacy = unchanged;
3563 legacy.review_instruction = None;
3564 legacy.hold_for_handover(None, "still checked out".into());
3565 legacy
3566 .edit("new plan".into(), "Reuse measured PR head B".into())
3567 .unwrap();
3568 legacy.release_operator(source, None);
3569 assert!(legacy.review_branch.is_none());
3570 }
3571 }
3572
3573 #[test]
3574 fn a_refused_handover_keeps_the_review_branch_across_release() {
3575 let mut t = task("refused takeover");
3576 t.start("run-1".to_owned());
3577 t.hold_for_handover(Some("magi/eba2/A".to_owned()), "checked out".to_owned());
3578 assert_eq!(t.status, TaskStatus::Held);
3579 assert_eq!(t.attempts, 1);
3580 t.release();
3581 assert_eq!(t.status, TaskStatus::Queued);
3582 assert_eq!(t.attempts, 0);
3583 assert_eq!(t.review_branch.as_deref(), Some("magi/eba2/A"));
3584
3585 t.hold_for_handover(None, "again".to_owned());
3587 t.requeue();
3588 assert!(t.review_branch.is_none());
3589
3590 let mut m = task("manual");
3592 m.review_branch = Some("magi/x/A".to_owned());
3593 m.hold_manual(None);
3594 m.release();
3595 assert!(m.review_branch.is_none());
3596 }
3597
3598 #[test]
3599 fn requesting_review_requeues_the_task_and_remembers_the_branch() {
3600 let mut t = task("blocked run with a surviving branch");
3601 t.start("run-1".to_owned());
3602 t.fail("blocked with major findings", 5);
3603 assert_eq!(t.status, TaskStatus::Failed);
3604
3605 t.request_review("magi/eba2/A".to_owned());
3606 assert_eq!(t.status, TaskStatus::Queued);
3607 assert_eq!(t.attempts, 0);
3608 assert_eq!(t.review_branch.as_deref(), Some("magi/eba2/A"));
3609
3610 t.release();
3612 assert!(t.review_branch.is_none());
3613 }
3614
3615 #[test]
3616 fn conductor_requeue_but_not_an_ordinary_release_forces_a_fresh_start() {
3617 let mut t = task("retry");
3618 t.start("run-1".to_owned());
3619 t.requeue();
3620 assert!(t.fresh_start);
3621
3622 t.release();
3623 assert!(!t.fresh_start);
3624 }
3625
3626 #[test]
3627 fn urgent_only_changes_queued_or_held_and_preserves_settings() {
3628 for status in [
3629 TaskStatus::Queued,
3630 TaskStatus::Held,
3631 TaskStatus::Running,
3632 TaskStatus::Done,
3633 TaskStatus::Failed,
3634 TaskStatus::Blocked,
3635 TaskStatus::Parked,
3636 ] {
3637 let mut t = task("urgent settings");
3638 t.status = status;
3639 t.attempts = 2;
3640 t.hold_reason = Some("waiting".into());
3641 t.priority = 7;
3642 t.interrupt = true;
3643 let before = serde_json::to_value(&t).unwrap();
3644 for urgent in [true, true, false, false] {
3645 let result = t.set_urgent(urgent);
3646 let mut expected = before.clone();
3647 if matches!(status, TaskStatus::Queued | TaskStatus::Held) {
3648 result.unwrap();
3649 expected["urgent"] = urgent.into();
3650 } else {
3651 let error = result.unwrap_err().to_string();
3652 assert!(error.contains(status.as_str()), "{error}");
3653 assert!(error.contains("queued or held"), "{error}");
3654 }
3655 assert_eq!(serde_json::to_value(&t).unwrap(), expected);
3656 }
3657 }
3658 }
3659
3660 #[test]
3661 fn priority_can_be_changed_while_queued_but_not_while_running() {
3662 let mut t = task("reprioritise me");
3663 t.set_priority(5).unwrap();
3664 assert_eq!(t.priority, 5);
3665
3666 t.start("run-1".to_owned());
3667 let err = t.set_priority(9).unwrap_err().to_string();
3668 assert!(err.contains("running"), "{err}");
3669 assert_eq!(t.priority, 5, "the rejected write must not partially apply");
3670 }
3671
3672 #[test]
3673 fn interrupt_can_be_marked_while_queued_but_not_while_running() {
3674 let mut t = task("interrupt me");
3675 assert!(!t.interrupt, "off unless asked, same as any other task");
3676
3677 t.set_interrupt(true).unwrap();
3678 assert!(t.interrupt);
3679
3680 t.start("run-1".to_owned());
3681 assert!(
3682 !t.interrupt,
3683 "the mark is one-shot: dispatching the task fulfils it, \
3684 whatever the run that follows ends up doing"
3685 );
3686 let err = t.set_interrupt(true).unwrap_err().to_string();
3687 assert!(err.contains("running"), "{err}");
3688 t.set_interrupt(false).unwrap();
3691 assert!(!t.interrupt);
3692 }
3693
3694 #[test]
3698 fn a_failed_run_does_not_leave_the_task_still_marked_to_interrupt() {
3699 let mut t = task("interrupt me");
3700 t.set_interrupt(true).unwrap();
3701 t.start("run-1".to_owned());
3702 t.fail("mock failure", 5);
3703 assert_eq!(t.status, TaskStatus::Failed);
3704 assert!(
3705 !t.interrupt,
3706 "one attempt already spent the mark; a retry is an ordinary \
3707 requeue, not a fresh interrupt request"
3708 );
3709 }
3710
3711 #[test]
3712 fn changing_priority_moves_a_task_ahead_in_the_real_queue_order() {
3713 let (_dir, q) = queue();
3714 let mut a = task("first filed");
3715 let mut b = task("second filed");
3716 a.id = "20260101-000001-aaaa".to_owned();
3717 b.id = "20260101-000002-bbbb".to_owned();
3718 q.put(&mut a).unwrap();
3719 q.put(&mut b).unwrap();
3720
3721 assert_eq!(
3722 q.next_runnable().unwrap().id,
3723 a.id,
3724 "with equal priority the older task goes first, so a burst of \
3725 new work cannot starve it"
3726 );
3727 assert_eq!(
3728 q.list()[0].id,
3729 b.id,
3730 "but the list an operator reads is newest first, the same as \
3731 before priority existed - a's turn to run does not make it the \
3732 newest task"
3733 );
3734
3735 let mut a = q.get(&a.id).unwrap();
3736 a.set_priority(10).unwrap();
3737 q.put(&mut a).unwrap();
3738
3739 assert_eq!(
3740 q.next_runnable().unwrap().id,
3741 a.id,
3742 "a raised priority must be reflected the moment it is saved"
3743 );
3744 assert_eq!(
3748 q.list()[0].id,
3749 a.id,
3750 "the raised task must sort first in the list an operator reads, \
3751 not only in next_runnable's own ordering"
3752 );
3753 }
3754
3755 #[test]
3756 fn editing_replaces_title_and_instruction_but_keeps_identity_and_history() {
3757 let mut t = Task::new(
3758 "old title".to_owned(),
3759 "old instruction".to_owned(),
3760 PathBuf::from("/repo"),
3761 Source::Agent {
3762 run: "20260101-000000-beef".to_owned(),
3763 node: "implement".to_owned(),
3764 },
3765 );
3766 let id = t.id.clone();
3767 let created_at = t.created_at;
3768 t.runs.push("20260101-000000-beef".to_owned());
3769
3770 t.edit("new title".to_owned(), "new instruction".to_owned())
3771 .unwrap();
3772
3773 assert_eq!(t.title, "new title");
3774 assert_eq!(t.instruction, "new instruction");
3775 assert_eq!(t.id, id, "editing must not mint a new id");
3776 assert_eq!(t.created_at, created_at);
3777 assert_eq!(
3778 t.source,
3779 Source::Agent {
3780 run: "20260101-000000-beef".to_owned(),
3781 node: "implement".to_owned(),
3782 },
3783 "editing must not turn agent attribution into human"
3784 );
3785 assert_eq!(t.runs, ["20260101-000000-beef"]);
3786 }
3787
3788 #[test]
3789 fn editing_is_refused_once_a_task_is_running_or_finished() {
3790 let mut running = task("in flight");
3791 running.start("run-1".to_owned());
3792 let err = running
3793 .edit("x".to_owned(), "y".to_owned())
3794 .unwrap_err()
3795 .to_string();
3796 assert!(err.contains("running"), "{err}");
3797
3798 let mut done = task("finished");
3799 done.succeed();
3800 let err = done
3801 .edit("x".to_owned(), "y".to_owned())
3802 .unwrap_err()
3803 .to_string();
3804 assert!(err.contains("done"), "{err}");
3805
3806 let mut queued = task("waiting");
3808 queued.edit("x".to_owned(), "y".to_owned()).unwrap();
3809 let mut held = task("parked");
3810 held.hold_machine(None);
3811 held.edit("x".to_owned(), "y".to_owned()).unwrap();
3812 }
3813
3814 #[test]
3815 fn a_task_recorded_without_a_hold_reason_still_reads_as_none() {
3816 let (_dir, q) = queue();
3817 let path = q.path_of("20260101-000000-aaaa");
3818 std::fs::create_dir_all(q.root()).unwrap();
3819 std::fs::write(
3820 &path,
3821 serde_json::json!({
3822 "schema": SCHEMA,
3823 "id": "20260101-000000-aaaa",
3824 "title": "from before hold reasons existed",
3825 "instruction": "from before hold reasons existed",
3826 "repo": ".",
3827 "source": { "kind": "human" },
3828 "status": "held",
3829 "created_at": Timestamp::now().to_string(),
3830 "updated_at": Timestamp::now().to_string(),
3831 })
3832 .to_string(),
3833 )
3834 .unwrap();
3835
3836 let task = q.get("20260101-000000-aaaa").expect("must still read");
3837 assert!(task.hold_reason.is_none());
3838 assert!(task.operator_held());
3839 }
3840
3841 #[test]
3842 fn a_legacy_reasoned_hold_defaults_to_operator_protection() {
3843 let (_dir, q) = queue();
3844 let path = q.path_of("20260101-000000-bbbb");
3845 std::fs::create_dir_all(q.root()).unwrap();
3846 std::fs::write(
3847 &path,
3848 serde_json::json!({
3849 "schema": 2,
3850 "id": "20260101-000000-bbbb",
3851 "title": "old manual recovery",
3852 "instruction": "old manual recovery",
3853 "repo": ".",
3854 "source": { "kind": "human" },
3855 "status": "held",
3856 "hold_reason": "active manual recovery run20260912-224242-daf5",
3857 "created_at": Timestamp::now().to_string(),
3858 "updated_at": Timestamp::now().to_string(),
3859 })
3860 .to_string(),
3861 )
3862 .unwrap();
3863
3864 let task = q.get("20260101-000000-bbbb").expect("must still read");
3865 assert_eq!(task.hold_source, None);
3866 assert!(task.operator_held());
3867 }
3868
3869 #[test]
3870 fn a_task_recorded_without_a_diagnostic_still_reads_as_none() {
3871 let (_dir, q) = queue();
3872 let path = q.path_of("20260101-000000-aaaa");
3873 std::fs::create_dir_all(q.root()).unwrap();
3874 std::fs::write(
3875 &path,
3876 serde_json::json!({
3877 "schema": SCHEMA,
3878 "id": "20260101-000000-aaaa",
3879 "title": "from before diagnostics existed",
3880 "instruction": "from before diagnostics existed",
3881 "repo": ".",
3882 "source": { "kind": "human" },
3883 "status": "held",
3884 "created_at": Timestamp::now().to_string(),
3885 "updated_at": Timestamp::now().to_string(),
3886 })
3887 .to_string(),
3888 )
3889 .unwrap();
3890
3891 let task = q.get("20260101-000000-aaaa").expect("must still read");
3892 assert!(task.diagnostic.is_none());
3893 }
3894
3895 #[test]
3896 fn a_schema_1_task_with_no_blocking_fields_still_reads() {
3897 let (_dir, q) = queue();
3901 let path = q.path_of("20260101-000000-aaaa");
3902 std::fs::create_dir_all(q.root()).unwrap();
3903 std::fs::write(
3904 &path,
3905 serde_json::json!({
3906 "schema": 1,
3907 "id": "20260101-000000-aaaa",
3908 "title": "from before blocking existed",
3909 "instruction": "from before blocking existed",
3910 "repo": ".",
3911 "source": { "kind": "human" },
3912 "status": "queued",
3913 "created_at": Timestamp::now().to_string(),
3914 "updated_at": Timestamp::now().to_string(),
3915 })
3916 .to_string(),
3917 )
3918 .unwrap();
3919
3920 let task = q.get("20260101-000000-aaaa").expect("must still read");
3921 assert!(task.blocked_by.is_empty());
3922 assert!(task.block_reason.is_none());
3923 assert!(task.answers.is_empty());
3924 assert!(task.review_branch.is_none());
3925 }
3926
3927 #[test]
3928 fn releasing_or_finishing_a_task_clears_its_stale_diagnostic() {
3929 let mut held = task("diagnosed");
3934 held.start("run-1".to_owned());
3935 held.fail("gate red", 1);
3936 held.diagnostic = Some("cargo test failed: ...".to_owned());
3937 assert_eq!(held.status, TaskStatus::Held);
3938
3939 held.release();
3940 assert!(held.diagnostic.is_none());
3941
3942 held.diagnostic = Some("cargo test failed: ...".to_owned());
3943 held.succeed();
3944 assert!(held.diagnostic.is_none());
3945 }
3946
3947 #[test]
3948 fn failing_a_task_always_clears_whatever_diagnostic_it_carried() {
3949 let mut t = task("retried");
3950 t.start("run-1".to_owned());
3951 t.diagnostic = Some("stale evidence from a previous hold".to_owned());
3952 t.fail("unrelated config error", 5);
3953 assert_eq!(t.status, TaskStatus::Failed);
3954 assert!(
3955 t.diagnostic.is_none(),
3956 "fail() must not let an old diagnostic outlive the run that produced it"
3957 );
3958 }
3959
3960 #[test]
3961 fn a_claim_is_exclusive_and_releases_on_drop() {
3962 let (_dir, q) = queue();
3963 let mut t = task("contended");
3964 q.put(&mut t).unwrap();
3965
3966 let held = q.claim(&t.id).unwrap();
3967 assert!(
3968 q.claim(&t.id).is_err(),
3969 "two daemons must not drive one task into two runs"
3970 );
3971 drop(held);
3972 assert!(q.claim(&t.id).is_ok(), "a released claim is reclaimable");
3973 }
3974
3975 #[test]
3976 fn a_round_trip_survives_disk() {
3977 let (_dir, q) = queue();
3978 let mut t = Task::new(
3979 "titled".to_owned(),
3980 "body".to_owned(),
3981 PathBuf::from("/repo"),
3982 Source::Agent {
3983 run: "20260101-000000-beef".to_owned(),
3984 node: "implement".to_owned(),
3985 },
3986 );
3987 t.priority = 3;
3988 q.put(&mut t).unwrap();
3989
3990 let back = q.get(&t.id).unwrap();
3991 assert_eq!(back.id, t.id);
3992 assert_eq!(back.priority, 3);
3993 assert_eq!(back.source.label(), "implement@beef");
3994 assert_eq!(q.get(t.short()).unwrap().id, t.id);
3996 }
3997
3998 #[test]
3999 fn an_unreadable_task_does_not_take_the_queue_down() {
4000 let (_dir, q) = queue();
4001 let mut t = task("fine");
4002 q.put(&mut t).unwrap();
4003 std::fs::write(q.root().join("broken.json"), "{ not json").unwrap();
4004
4005 let listed = q.list();
4006 assert_eq!(listed.len(), 1, "the readable task still lists");
4007 assert_eq!(listed[0].id, t.id);
4008 }
4009
4010 #[test]
4011 fn a_task_recorded_without_a_solo_field_still_reads_as_not_solo() {
4012 let (_dir, q) = queue();
4013 let path = q.path_of("20260101-000000-aaaa");
4014 std::fs::create_dir_all(q.root()).unwrap();
4015 std::fs::write(
4016 &path,
4017 serde_json::json!({
4018 "schema": SCHEMA,
4019 "id": "20260101-000000-aaaa",
4020 "title": "from before solo existed",
4021 "instruction": "from before solo existed",
4022 "repo": ".",
4023 "source": { "kind": "human" },
4024 "status": "queued",
4025 "created_at": Timestamp::now().to_string(),
4026 "updated_at": Timestamp::now().to_string(),
4027 })
4028 .to_string(),
4029 )
4030 .unwrap();
4031
4032 let task = q.get("20260101-000000-aaaa").expect("must still read");
4033 assert!(!task.solo, "a queue file with no `solo` field means false");
4034 }
4035
4036 #[test]
4037 fn a_task_recorded_without_an_urgent_field_still_reads_as_not_urgent() {
4038 let (_dir, q) = queue();
4039 let path = q.path_of("20260101-000000-bbbb");
4040 std::fs::create_dir_all(q.root()).unwrap();
4041 std::fs::write(
4042 &path,
4043 serde_json::json!({
4044 "schema": SCHEMA,
4045 "id": "20260101-000000-bbbb",
4046 "title": "from before urgent existed",
4047 "instruction": "from before urgent existed",
4048 "repo": ".",
4049 "source": { "kind": "human" },
4050 "status": "queued",
4051 "created_at": Timestamp::now().to_string(),
4052 "updated_at": Timestamp::now().to_string(),
4053 })
4054 .to_string(),
4055 )
4056 .unwrap();
4057
4058 let task = q.get("20260101-000000-bbbb").expect("must still read");
4059 assert!(
4060 !task.urgent,
4061 "a queue file with no `urgent` field means false, same as `solo`"
4062 );
4063 }
4064
4065 #[test]
4066 fn a_task_from_a_future_schema_is_refused_rather_than_guessed_at() {
4067 let (_dir, q) = queue();
4068 let mut t = task("from the future");
4069 q.put(&mut t).unwrap();
4070 let path = q.path_of(&t.id);
4071 let body = std::fs::read_to_string(&path)
4072 .unwrap()
4073 .replace(&format!("\"schema\": {SCHEMA}"), "\"schema\": 99");
4074 std::fs::write(&path, body).unwrap();
4075
4076 let err = q.get(&t.id).unwrap_err().to_string();
4077 assert!(err.contains("schema 99"), "{err}");
4078 }
4079
4080 #[test]
4081 fn revision_moves_when_the_queue_changes() {
4082 let (_dir, q) = queue();
4083 assert_eq!(q.revision(), 0, "an empty queue has no revision");
4084 let mut t = task("first");
4085 q.put(&mut t).unwrap();
4086 assert!(q.revision() > 0, "a written task moves the revision");
4087 }
4088
4089 #[test]
4090 fn revision_moves_when_deleting_an_older_task() {
4091 let (dir, q) = queue();
4092 let questions = Questions::at(dir.path().join("questions"));
4093 let mut t1 = task("older");
4094 q.put(&mut t1).unwrap();
4095 std::thread::sleep(std::time::Duration::from_millis(10));
4097 let mut t2 = task("newer");
4098 q.put(&mut t2).unwrap();
4099
4100 let rev_before = q.revision();
4101 q.remove(&t1.id, false, &questions).unwrap();
4102 let rev_after = q.revision();
4103
4104 assert_ne!(
4105 rev_before, rev_after,
4106 "deleting an older task must change the revision so other clients see the deletion"
4107 );
4108 }
4109
4110 #[test]
4111 fn removing_a_task_takes_it_out_of_the_listing() {
4112 let (dir, q) = queue();
4113 let questions = Questions::at(dir.path().join("questions"));
4114 let mut t = task("delete me");
4115 q.put(&mut t).unwrap();
4116 let removed = q.remove(t.short(), false, &questions).unwrap();
4117 assert_eq!(removed.id, t.id, "a prefix resolves before deleting");
4118 assert!(removed.released.is_empty() && removed.still_blocked.is_empty());
4119 assert!(q.list().is_empty());
4120 assert!(
4121 q.remove(&t.id, false, &questions).is_err(),
4122 "removing twice is an error"
4123 );
4124 }
4125
4126 #[test]
4127 fn removing_a_task_takes_its_stale_lock_with_it() {
4128 let (dir, q) = queue();
4129 let questions = Questions::at(dir.path().join("questions"));
4130 let mut t = task("interrupted");
4131 q.put(&mut t).unwrap();
4132
4133 let claim = q.claim(&t.id).unwrap();
4136 std::mem::forget(claim);
4137 assert!(
4138 q.claim(&t.id).is_err(),
4139 "the orphaned lock is what makes the task look claimed"
4140 );
4141
4142 let err = q.remove(&t.id, true, &questions).unwrap_err().to_string();
4144 assert!(err.contains("live daemon"), "{err}");
4145 assert!(q.get(&t.id).is_ok(), "a refused delete keeps the task");
4146
4147 q.remove(&t.id, false, &questions).unwrap();
4149 assert!(q.list().is_empty());
4150 let mut again = task("interrupted");
4151 again.id = t.id.clone();
4152 q.put(&mut again).unwrap();
4153 assert!(
4154 q.claim(&t.id).is_ok(),
4155 "a task that comes back must be claimable, which a left-behind lock would prevent"
4156 );
4157 }
4158
4159 fn notices_of(dir: &Path) -> Vec<crate::notices::Notice> {
4160 crate::notices::Notices::at(dir.join("notifications")).list()
4161 }
4162
4163 #[test]
4164 fn removing_a_sole_dependency_releases_the_dependent_without_a_hold() {
4165 let (dir, q) = queue();
4166 let questions = Questions::at(dir.path().join("questions"));
4167 let mut dep = task("dependency");
4168 q.put(&mut dep).unwrap();
4169 let mut blocked = task("waiting");
4170 blocked.block(vec![dep.id.clone()], Some("waits".to_owned()));
4171 q.put(&mut blocked).unwrap();
4172
4173 let removed = q.remove(&dep.id, false, &questions).unwrap();
4174 assert_eq!(removed.released, [blocked.id.clone()]);
4175 assert!(removed.still_blocked.is_empty());
4176
4177 let after = q.get(&blocked.id).unwrap();
4178 assert_eq!(after.status, TaskStatus::Queued);
4179 assert!(after.blocked_by.is_empty());
4180 assert!(after.block_reason.is_none());
4181 let notes = notices_of(dir.path());
4182 assert_eq!(notes.len(), 1, "{notes:?}");
4183 assert_eq!(notes[0].severity, crate::notices::Severity::Info);
4184 assert_eq!(
4185 notes[0].link,
4186 Some(crate::notices::Link::Task {
4187 id: blocked.id.clone(),
4188 })
4189 );
4190 }
4191
4192 #[test]
4193 fn removing_one_of_two_dependencies_keeps_the_other() {
4194 let (dir, q) = queue();
4195 let questions = Questions::at(dir.path().join("questions"));
4196 let mut dep = task("dependency");
4197 q.put(&mut dep).unwrap();
4198 let mut other = task("other");
4199 q.put(&mut other).unwrap();
4200 let mut blocked = task("waiting");
4201 blocked.block(
4202 vec![dep.id.clone(), other.id.clone()],
4203 Some("waits on both".to_owned()),
4204 );
4205 q.put(&mut blocked).unwrap();
4206
4207 let removed = q.remove(&dep.id, false, &questions).unwrap();
4208 assert!(removed.released.is_empty());
4209 assert_eq!(removed.still_blocked, [blocked.id.clone()]);
4210
4211 let after = q.get(&blocked.id).unwrap();
4212 assert_eq!(after.status, TaskStatus::Blocked);
4213 assert_eq!(after.blocked_by, [other.id.clone()]);
4214 assert!(missing_blockers(&q, &questions, &after.blocked_by).is_empty());
4217 }
4218
4219 #[test]
4220 fn a_dependency_deleted_before_its_dependents_were_rewritten_is_released_later() {
4221 let (dir, q) = queue();
4222 let questions = Questions::at(dir.path().join("questions"));
4223 let mut dep = task("dependency");
4224 q.put(&mut dep).unwrap();
4225 let mut blocked = task("waiting");
4226 blocked.block(vec![dep.id.clone()], None);
4227 q.put(&mut blocked).unwrap();
4228
4229 let claim = q.claim(&blocked.id).unwrap();
4231 let removed = q.remove(&dep.id, false, &questions).unwrap();
4232 assert!(removed.released.is_empty());
4233 drop(claim);
4234
4235 let mut task = q.get(&blocked.id).unwrap();
4236 assert_eq!(task.status, TaskStatus::Blocked);
4237 assert!(missing_blockers(&q, &questions, &task.blocked_by).is_empty());
4238 assert_eq!(q.apply_deleted_blockers(&mut task), [dep.id.clone()]);
4239 assert_eq!(task.status, TaskStatus::Queued);
4240 }
4241
4242 #[test]
4243 fn a_dependency_without_a_tombstone_is_still_missing() {
4244 let (dir, q) = queue();
4245 let questions = Questions::at(dir.path().join("questions"));
4246 let mut dep = task("dependency");
4247 q.put(&mut dep).unwrap();
4248 std::fs::remove_file(q.path_of(&dep.id)).unwrap();
4249 assert_eq!(
4250 missing_blockers(&q, &questions, std::slice::from_ref(&dep.id)),
4251 [dep.id.clone()]
4252 );
4253 assert!(deleted_blockers(&q, std::slice::from_ref(&dep.id)).is_empty());
4254 }
4255
4256 #[test]
4257 fn a_held_dependent_is_left_alone_by_a_dependency_deletion() {
4258 let mut t = task("held");
4259 t.hold_machine(Some("because".to_owned()));
4260 t.blocked_by = vec!["gone".to_owned()];
4261 assert!(!t.dependency_deleted("gone"));
4262 assert_eq!(t.status, TaskStatus::Held);
4263 }
4264
4265 #[test]
4266 fn a_failed_record_removal_takes_the_tombstone_back() {
4267 let (_dir, q) = queue();
4268 let mut t = task("stays");
4269 q.put(&mut t).unwrap();
4270 q.write_tombstone(&t.id).unwrap();
4271 let err = q.remove_record_with_attachments(&t.id, |_| Err(std::io::Error::other("nope")));
4272 assert!(err.is_err());
4273 assert!(!q.was_deleted(&t.id));
4276 }
4277
4278 fn source_file(dir: &Path, name: &str, body: &str) -> PathBuf {
4279 let p = dir.join(name);
4280 std::fs::write(&p, body).unwrap();
4281 p
4282 }
4283
4284 #[test]
4285 fn an_attachment_copy_survives_deleting_its_source() {
4286 let (dir, q) = queue();
4287 let src = source_file(dir.path(), "shot.png", "pixels");
4288 let mut t = task("with a picture");
4289 let names = q.attach(&mut t, std::slice::from_ref(&src)).unwrap();
4290 q.put(&mut t).unwrap();
4291 std::fs::remove_file(&src).unwrap();
4292 assert_eq!(names, ["shot.png"]);
4293 let loaded = q.get(&t.id).unwrap();
4294 let paths = q.attachment_paths(&loaded);
4295 assert_eq!(paths.len(), 1);
4296 assert_eq!(std::fs::read_to_string(&paths[0]).unwrap(), "pixels");
4297 }
4298
4299 #[test]
4300 fn attachment_names_that_could_traverse_or_are_odd_are_refused() {
4301 let (dir, q) = queue();
4302 let mut t = task("bad names");
4303 for name in ["a..b.png", ".hidden", "with space.png", "-x.png"] {
4304 let src = source_file(dir.path(), name, "x");
4305 assert!(
4306 q.attach(&mut t, &[src]).is_err(),
4307 "`{name}` must be refused"
4308 );
4309 }
4310 assert!(!crate::ask::valid_asset_name("C:foo.png"));
4314 #[cfg(not(windows))]
4315 {
4316 let src = source_file(dir.path(), "C:foo.png", "x");
4317 assert!(q.attach(&mut t, &[src]).is_err());
4318 }
4319 let long = format!("{}.png", "a".repeat(70));
4320 let src = source_file(dir.path(), &long, "x");
4321 assert!(q.attach(&mut t, &[src]).is_err());
4322 assert!(t.attachments.is_empty());
4323 assert!(!q.attachments_dir(&t.id).exists());
4324 }
4325
4326 #[test]
4327 fn a_taken_attachment_name_is_numbered_not_overwritten() {
4328 let (dir, q) = queue();
4329 let a = source_file(dir.path(), "shot.png", "one");
4330 let sub = dir.path().join("other");
4331 std::fs::create_dir_all(&sub).unwrap();
4332 let b = source_file(&sub, "shot.png", "two");
4333 let mut t = task("collision");
4334 q.attach(&mut t, &[a]).unwrap();
4335 q.attach(&mut t, &[b]).unwrap();
4336 assert_eq!(t.attachments, ["shot.png", "shot-2.png"]);
4337 let paths = q.attachment_paths(&t);
4338 assert_eq!(std::fs::read_to_string(&paths[0]).unwrap(), "one");
4339 assert_eq!(std::fs::read_to_string(&paths[1]).unwrap(), "two");
4340 }
4341
4342 #[test]
4343 fn a_renumbered_name_stays_inside_the_length_bound() {
4344 let (dir, q) = queue();
4345 let name = format!("{}.png", "a".repeat(60));
4346 assert_eq!(name.len(), 64);
4347 let a = source_file(dir.path(), &name, "one");
4348 let sub = dir.path().join("other");
4349 std::fs::create_dir_all(&sub).unwrap();
4350 let b = source_file(&sub, &name, "two");
4351 let mut t = task("long");
4352 q.attach(&mut t, &[a, b]).unwrap();
4353 assert_eq!(t.attachments.len(), 2);
4354 assert!(
4355 t.attachments
4356 .iter()
4357 .all(|n| crate::ask::valid_asset_name(n))
4358 );
4359 assert!(t.attachments[1].ends_with("-2.png"));
4360 }
4361
4362 #[test]
4363 fn a_failed_attach_keeps_existing_attachments_and_leaves_no_partial_copy() {
4364 let (dir, q) = queue();
4365 let good = source_file(dir.path(), "good.png", "ok");
4366 let mut t = task("partial");
4367 q.attach(&mut t, &[good]).unwrap();
4368 let more = source_file(dir.path(), "more.png", "ok");
4369 let missing = dir.path().join("missing.png");
4370 assert!(q.attach(&mut t, &[more, missing]).is_err());
4371 assert_eq!(t.attachments, ["good.png"]);
4372 let on_disk: Vec<_> = std::fs::read_dir(q.attachments_dir(&t.id))
4373 .unwrap()
4374 .flatten()
4375 .collect();
4376 assert_eq!(on_disk.len(), 1);
4377 }
4378
4379 fn block_put(q: &Queue, t: &Task) -> PathBuf {
4381 let tmp = q.path_of(&t.id).with_extension("json.tmp");
4382 std::fs::create_dir_all(&tmp).unwrap();
4383 tmp
4384 }
4385
4386 #[test]
4387 fn a_failed_put_leaves_no_new_attachment_directory() {
4388 let (dir, q) = queue();
4389 let mut t = task("fresh");
4390 let tmp = block_put(&q, &t);
4391 let src = source_file(dir.path(), "shot.png", "x");
4392 assert!(q.attach_and_put(&mut t, &[src]).is_err());
4393 assert!(t.attachments.is_empty());
4394 assert!(!q.attachments_dir(&t.id).exists());
4395 assert!(!q.path_of(&t.id).exists());
4396 std::fs::remove_dir(tmp).unwrap();
4397 }
4398
4399 #[test]
4400 fn a_failed_put_removes_only_the_copy_it_just_made() {
4401 let (dir, q) = queue();
4402 let mut t = task("edited");
4403 let first = source_file(dir.path(), "first.png", "1");
4404 q.attach_and_put(&mut t, &[first]).unwrap();
4405 block_put(&q, &t);
4406 let second = source_file(dir.path(), "second.png", "2");
4407 assert!(q.attach_and_put(&mut t, &[second]).is_err());
4408 assert_eq!(t.attachments, ["first.png"]);
4409 let on_disk: Vec<_> = std::fs::read_dir(q.attachments_dir(&t.id))
4410 .unwrap()
4411 .flatten()
4412 .map(|e| e.file_name().to_string_lossy().into_owned())
4413 .collect();
4414 assert_eq!(on_disk, ["first.png"]);
4415 assert_eq!(q.get(&t.id).unwrap().attachments, ["first.png"]);
4416 }
4417
4418 #[test]
4419 fn a_leftover_removing_directory_is_swept_by_the_next_removal() {
4420 let (dir, q) = queue();
4421 let questions = Questions::at(dir.path().join("questions"));
4422 let gone = task("gone");
4423 let mut other = task("other");
4424 let mut live = task("live");
4425 q.put(&mut other).unwrap();
4426 q.put(&mut live).unwrap();
4427 let orphan = q.root.join(format!("{}.attachments.removing", gone.id));
4430 std::fs::create_dir_all(&orphan).unwrap();
4431 std::fs::write(orphan.join("shot.png"), "x").unwrap();
4432 let busy = q.root.join(format!("{}.attachments.removing", live.id));
4435 std::fs::create_dir_all(&busy).unwrap();
4436
4437 q.remove(&other.id, false, &questions).unwrap();
4438 assert!(!orphan.exists(), "an orphan is swept");
4439 assert!(busy.exists(), "a removal in progress is left alone");
4440 }
4441
4442 #[test]
4443 fn a_blocked_aside_rename_fails_the_removal_and_loses_nothing() {
4444 let (dir, q) = queue();
4445 let questions = Questions::at(dir.path().join("questions"));
4446 let mut t = task("stuck");
4447 let src = source_file(dir.path(), "shot.png", "x");
4448 q.attach_and_put(&mut t, &[src]).unwrap();
4449 let aside = q.root.join(format!("{}.attachments.removing", t.id));
4452 std::fs::create_dir_all(&aside).unwrap();
4453 std::fs::write(aside.join("old.png"), "o").unwrap();
4454 assert!(q.remove(&t.id, false, &questions).is_err());
4455 assert!(q.path_of(&t.id).exists());
4456 assert!(q.attachments_dir(&t.id).join("shot.png").is_file());
4457 }
4458
4459 #[test]
4460 fn a_failed_record_removal_puts_the_attachments_back() {
4461 let (dir, q) = queue();
4462 let mut t = task("rollback");
4463 let src = source_file(dir.path(), "shot.png", "x");
4464 q.attach_and_put(&mut t, &[src]).unwrap();
4465 let err = q
4466 .remove_record_with_attachments(&t.id, |_| {
4467 Err(std::io::Error::other("injected failure"))
4468 })
4469 .unwrap_err();
4470 assert!(format!("{err:#}").contains("injected failure"));
4471 assert!(q.path_of(&t.id).exists());
4472 assert!(q.attachments_dir(&t.id).join("shot.png").is_file());
4473 assert!(
4474 !q.root
4475 .join(format!("{}.attachments.removing", t.id))
4476 .exists()
4477 );
4478 }
4479
4480 #[test]
4481 fn editing_a_task_keeps_its_attachments() {
4482 let (dir, q) = queue();
4483 let src = source_file(dir.path(), "shot.png", "x");
4484 let mut t = task("editable");
4485 q.attach(&mut t, &[src]).unwrap();
4486 t.edit("new".to_owned(), "new text".to_owned()).unwrap();
4487 q.put(&mut t).unwrap();
4488 assert_eq!(q.get(&t.id).unwrap().attachments, ["shot.png"]);
4489 }
4490
4491 #[test]
4492 fn removing_a_task_deletes_its_attachments() {
4493 let (dir, q) = queue();
4494 let questions = Questions::at(dir.path().join("questions"));
4495 let src = source_file(dir.path(), "shot.png", "x");
4496 let mut t = task("doomed");
4497 q.attach(&mut t, &[src]).unwrap();
4498 q.put(&mut t).unwrap();
4499 assert!(q.attachments_dir(&t.id).is_dir());
4500 q.remove(&t.id, false, &questions).unwrap();
4501 assert!(!q.attachments_dir(&t.id).exists());
4502 assert!(q.list().is_empty());
4503 }
4504
4505 #[test]
4506 fn a_task_written_before_attachments_still_reads() {
4507 let (_dir, q) = queue();
4508 let mut t = task("old");
4509 q.put(&mut t).unwrap();
4510 let path = q.path_of(&t.id);
4511 let mut v: serde_json::Value =
4512 serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
4513 v.as_object_mut().unwrap().remove("attachments");
4514 std::fs::write(&path, v.to_string()).unwrap();
4515 assert!(q.get(&t.id).unwrap().attachments.is_empty());
4516 }
4517
4518 #[test]
4519 fn attachment_paths_are_absolute_even_when_the_root_is_relative() {
4520 let q = Queue::at(PathBuf::from("relative-queue"));
4521 let mut t = task("rel");
4522 t.attachments.push("shot.png".to_owned());
4523 let paths = q.attachment_paths(&t);
4524 assert!(paths[0].is_absolute(), "{}", paths[0].display());
4525 assert!(paths[0].ends_with(format!("{}.attachments/shot.png", t.id)));
4526 }
4527
4528 #[test]
4529 fn explicitly_resumed_older_run_becomes_current_without_duplicate_history() {
4530 let dir = tempfile::tempdir().unwrap();
4531 let q = Queue::at(dir.path().join("queue"));
4532 let mut t = task("resume");
4533 t.start("A".into());
4534 t.record_pass("A", 0, 1, None);
4535 t.start("B".into());
4536 q.put(&mut t).unwrap();
4537 assert_eq!(t.runs, vec!["A", "B"]);
4538 t.start("A".into());
4539 t.record_pass("A", 1, 3, None);
4540 q.put(&mut t).unwrap();
4541 let saved = q.get(&t.id).unwrap();
4542 assert_eq!(saved.runs, vec!["B", "A"]);
4543 assert_eq!(saved.runs.last().map(String::as_str), Some("A"));
4544 assert_eq!(saved.attempts, 3);
4545 assert_eq!(saved.passes.len(), 2);
4546 assert_eq!(saved.passes[0].run, "A");
4547 assert_eq!(saved.passes[1].run, "A");
4548 }
4549
4550 #[test]
4551 fn repeated_start_records_one_run_and_separate_passes() {
4552 let mut t = task("resume");
4553 t.start("same-run".into());
4554 t.record_pass("same-run", 0, 1, None);
4555 t.start("same-run".into());
4556 t.record_pass("same-run", 1, 2, None);
4557 assert_eq!(t.runs, vec!["same-run"]);
4558 assert_eq!(t.attempts, 2);
4559 assert_eq!(t.passes.len(), 2);
4560 }
4561
4562 #[test]
4563 fn link_run_adds_a_run_once_and_touches_nothing_else() {
4564 let dir = tempfile::tempdir().unwrap();
4565 let queue = Queue::at(dir.path().join("queue"));
4566 let mut t = Task::new(
4567 "t".to_owned(),
4568 "do it".to_owned(),
4569 PathBuf::from("."),
4570 Source::Human,
4571 );
4572 queue.put(&mut t).unwrap();
4573 let before = queue.get(&t.id).unwrap();
4574
4575 let linked = queue.link_run(&t.id[..4], "20260930-092817-ec34").unwrap();
4576 assert_eq!(linked.runs, vec!["20260930-092817-ec34".to_owned()]);
4577 assert_eq!(linked.status, before.status);
4578 assert_eq!(linked.attempts, before.attempts);
4579 assert_eq!(linked.interrupt, before.interrupt);
4580
4581 let again = queue.link_run(&t.id, "20260930-092817-ec34").unwrap();
4582 assert_eq!(again.runs.len(), 1, "linking twice must not duplicate");
4583 assert_eq!(queue.get(&t.id).unwrap().runs.len(), 1);
4584 assert!(queue.link_run("no-such-task", "r").is_err());
4585 }
4586
4587 #[test]
4588 fn put_keeps_a_run_linked_after_the_writer_took_its_snapshot() {
4589 let dir = tempfile::tempdir().unwrap();
4590 let queue = Queue::at(dir.path().join("queue"));
4591 let mut t = Task::new(
4592 "t".to_owned(),
4593 "do it".to_owned(),
4594 PathBuf::from("."),
4595 Source::Human,
4596 );
4597 queue.put(&mut t).unwrap();
4598 let mut snapshot = queue.get(&t.id).unwrap();
4600 queue.link_run(&t.id, "20260930-092817-ec34").unwrap();
4601
4602 snapshot.start("20260930-000000-aaaa".to_owned());
4603 queue.put(&mut snapshot).unwrap();
4604
4605 let stored = queue.get(&t.id).unwrap();
4606 assert!(stored.runs.contains(&"20260930-092817-ec34".to_owned()));
4607 assert!(stored.runs.contains(&"20260930-000000-aaaa".to_owned()));
4608 assert_eq!(stored.attempts, 1);
4609 }
4610
4611 #[test]
4612 fn concurrent_links_and_daemon_saves_lose_nothing() {
4613 let dir = tempfile::tempdir().unwrap();
4614 let queue = Queue::at(dir.path().join("queue"));
4615 let mut t = Task::new(
4616 "t".to_owned(),
4617 "do it".to_owned(),
4618 PathBuf::from("."),
4619 Source::Human,
4620 );
4621 queue.put(&mut t).unwrap();
4622 let id = t.id.clone();
4623
4624 let linkers: Vec<_> = (0..4)
4625 .map(|n| {
4626 let (queue, id) = (queue.clone(), id.clone());
4627 std::thread::spawn(move || {
4628 for k in 0..10 {
4629 queue
4630 .link_run(&id, &format!("20260930-00000{n}-l{k:03}"))
4631 .unwrap();
4632 }
4633 })
4634 })
4635 .collect();
4636 let mut mine = queue.get(&id).unwrap();
4639 for k in 0..10 {
4640 mine.start(format!("20260930-000009-d{k:03}"));
4641 queue.put(&mut mine).unwrap();
4642 }
4643 for l in linkers {
4644 l.join().unwrap();
4645 }
4646
4647 let stored = queue.get(&id).unwrap();
4648 assert_eq!(stored.runs.len(), 50, "{:?}", stored.runs);
4649 assert_eq!(
4650 stored.attempts, 10,
4651 "linking never rewinds the daemon's work"
4652 );
4653 }
4654
4655 fn age_lock(path: &Path) {
4656 let f = std::fs::OpenOptions::new().write(true).open(path).unwrap();
4657 f.set_modified(std::time::SystemTime::now() - std::time::Duration::from_secs(60))
4658 .unwrap();
4659 }
4660
4661 #[test]
4662 fn concurrent_stale_takeover_yields_one_holder() {
4663 use std::sync::atomic::{AtomicUsize, Ordering};
4664 use std::sync::{Arc, Barrier};
4665 for _ in 0..5 {
4666 let dir = tempfile::tempdir().unwrap();
4667 let q = Queue::at(dir.path().to_path_buf());
4668 let lock = dir.path().join("t.write-lock");
4669 std::fs::write(&lock, "dead-0000").unwrap();
4670 age_lock(&lock);
4671 let n = 6;
4672 let barrier = Arc::new(Barrier::new(n));
4673 let (now, max) = (Arc::new(AtomicUsize::new(0)), Arc::new(AtomicUsize::new(0)));
4674 let handles: Vec<_> = (0..n)
4675 .map(|_| {
4676 let (q, b, now, max) = (q.clone(), barrier.clone(), now.clone(), max.clone());
4677 std::thread::spawn(move || {
4678 b.wait();
4679 let g = q.lock_task("t").unwrap();
4680 let held = now.fetch_add(1, Ordering::SeqCst) + 1;
4681 max.fetch_max(held, Ordering::SeqCst);
4682 std::thread::sleep(std::time::Duration::from_millis(20));
4683 now.fetch_sub(1, Ordering::SeqCst);
4684 drop(g);
4685 })
4686 })
4687 .collect();
4688 for h in handles {
4689 h.join().unwrap();
4690 }
4691 assert_eq!(max.load(Ordering::SeqCst), 1);
4692 assert!(!lock.exists());
4693 }
4694 }
4695
4696 #[test]
4697 fn dropping_a_stolen_lock_leaves_the_new_holders_lock() {
4698 let dir = tempfile::tempdir().unwrap();
4699 let q = Queue::at(dir.path().to_path_buf());
4700 let lock = dir.path().join("t.write-lock");
4701 let a = q.lock_task("t").unwrap();
4702 age_lock(&lock);
4703 let b = q.lock_task("t").unwrap();
4704 assert_ne!(a.token, b.token);
4705 drop(a);
4706 assert_eq!(std::fs::read_to_string(&lock).unwrap(), b.token);
4707 drop(b);
4708 assert!(!lock.exists());
4709 }
4710
4711 #[test]
4712 fn break_stale_leaves_a_lock_that_replaced_the_one_judged() {
4713 let dir = tempfile::tempdir().unwrap();
4714 let lock = dir.path().join("t.write-lock");
4715 std::fs::write(&lock, "new-token").unwrap();
4716 assert!(!break_stale(&lock, "old-token"));
4717 assert_eq!(std::fs::read_to_string(&lock).unwrap(), "new-token");
4718 assert!(!break_stale(&lock, "new-token"));
4720 assert!(lock.exists());
4721 age_lock(&lock);
4722 assert!(break_stale(&lock, "new-token"));
4723 assert!(!lock.exists());
4724 }
4725
4726 #[test]
4727 fn a_stale_break_marker_is_recovered_and_a_fresh_one_is_respected() {
4728 let dir = tempfile::tempdir().unwrap();
4729 let lock = dir.path().join("t.write-lock");
4730 std::fs::write(&lock, "dead-1").unwrap();
4731 age_lock(&lock);
4732 let marker = break_marker(&lock, "dead-1");
4733 std::fs::write(&marker, "crashed-remover").unwrap();
4734 assert!(!break_stale(&lock, "dead-1"));
4736 assert!(lock.exists());
4737 age_lock(&marker);
4739 assert!(break_stale(&lock, "dead-1"));
4740 assert!(!lock.exists());
4741 assert!(!marker.exists());
4742 }
4743
4744 fn chat_task() -> Task {
4745 Task::new(
4746 "t".to_owned(),
4747 "do t".to_owned(),
4748 PathBuf::from("."),
4749 Source::Agent {
4750 run: "20260902-000000-beef".to_owned(),
4751 node: CHAT_NODE.to_owned(),
4752 },
4753 )
4754 }
4755
4756 #[test]
4757 fn a_chat_notice_is_due_only_for_a_final_state_and_only_once() {
4758 let mut t = chat_task();
4759 assert_eq!(t.chat_notice_due(), None, "queued");
4760 t.start("r1".to_owned());
4761 assert_eq!(t.chat_notice_due(), None, "running");
4762 t.fail("boom", 3);
4763 assert_eq!(t.status, TaskStatus::Failed);
4764 assert_eq!(t.chat_notice_due(), None, "a retried failure is not final");
4765 t.start("r2".to_owned());
4766 t.park("upgrade");
4767 assert_eq!(t.chat_notice_due(), None, "parked");
4768 t.fail("boom", 1);
4769 assert_eq!(t.status, TaskStatus::Held);
4770 let key = t
4771 .chat_notice_due()
4772 .expect("held on the last attempt is final");
4773 t.chat_notice = Some(ChatNotice {
4774 key,
4775 at: Timestamp::now(),
4776 outcome: ChatNoticeOutcome::Posted,
4777 });
4778 assert_eq!(t.chat_notice_due(), None, "same hold, no second notice");
4779 t.release();
4780 assert_eq!(t.chat_notice_due(), None, "requeued after a release");
4781 t.start("r3".to_owned());
4782 t.succeed();
4783 assert!(t.chat_notice_due().is_some(), "done is a new final state");
4784 }
4785
4786 #[test]
4787 fn completed_chat_notices_keep_current_and_legacy_keys_after_requeue() {
4788 for key in ["done", "done#0", "done#1", "done#12"] {
4789 let mut t = chat_task();
4790 t.start("r1".to_owned());
4791 t.succeed();
4792 t.chat_notice = Some(ChatNotice {
4793 key: key.to_owned(),
4794 at: Timestamp::now(),
4795 outcome: ChatNoticeOutcome::Posted,
4796 });
4797 t.requeue();
4798 t.start("r2".to_owned());
4799 t.succeed();
4800 assert_eq!(t.chat_notice_key().as_deref(), Some("done"));
4801 assert_eq!(t.chat_notice_due(), None, "recorded key: {key}");
4802 }
4803 }
4804
4805 #[test]
4806 fn a_new_hold_after_a_release_is_a_new_cause() {
4807 let mut t = chat_task();
4808 t.hold_manual(Some("wait".to_owned()));
4809 let first = t.chat_notice_due().expect("held");
4810 t.chat_notice = Some(ChatNotice {
4811 key: first.clone(),
4812 at: Timestamp::now(),
4813 outcome: ChatNoticeOutcome::Posted,
4814 });
4815 t.hold_manual(Some("still waiting".to_owned()));
4816 assert_eq!(t.chat_notice_due(), None, "a re-hold keeps its start");
4817 t.release();
4818 std::thread::sleep(std::time::Duration::from_millis(5));
4819 t.hold_manual(None);
4820 let second = t.chat_notice_due().expect("a fresh hold");
4821 assert_ne!(first, second);
4822 }
4823
4824 #[test]
4825 fn a_chat_notice_needs_a_chat_source_and_a_current_schema() {
4826 let mut human = task("h");
4827 human.succeed();
4828 assert_eq!(human.chat_notice_due(), None);
4829 let mut inherited = task("i");
4831 inherited.origin_chat = Some("20260902-000000-beef".to_owned());
4832 inherited.succeed();
4833 assert_eq!(inherited.chat_notice_due(), None);
4834 let mut old = chat_task();
4835 old.schema = 12;
4836 old.status = TaskStatus::Done;
4837 assert_eq!(old.chat_notice_due(), None, "history is not replayed");
4838 let mut live = chat_task();
4839 live.schema = 12;
4840 live.start("r1".to_owned());
4841 live.succeed();
4842 assert!(live.chat_notice_due().is_some(), "started by this build");
4843 let mut held = chat_task();
4844 held.schema = 12;
4845 held.hold_machine(Some("config".to_owned()));
4846 assert!(held.chat_notice_due().is_some(), "held before any start");
4847 }
4848
4849 #[test]
4850 fn a_stale_snapshot_does_not_rewind_a_recorded_chat_notice() {
4851 let tmp = tempfile::tempdir().expect("tempdir");
4852 let q = Queue::at(tmp.path().join("queue"));
4853 let mut t = chat_task();
4854 t.succeed();
4855 q.put(&mut t).expect("put");
4856 let mut stale = q.get(&t.id).expect("get");
4857 let key = t.chat_notice_due().expect("due");
4858 q.modify(&t.id, |x| {
4859 x.chat_notice = Some(ChatNotice {
4860 key: key.clone(),
4861 at: Timestamp::now(),
4862 outcome: ChatNoticeOutcome::Posted,
4863 });
4864 true
4865 })
4866 .expect("modify");
4867 q.put(&mut stale).expect("stale put");
4868 assert_eq!(q.get(&t.id).expect("get").chat_notice_due(), None);
4869 }
4870}