1use std::{
6 fs::{File, OpenOptions},
7 path::{Path, PathBuf},
8 time::{Duration, Instant},
9};
10
11use anyhow::{Context, Result, ensure};
12use jiff::Timestamp;
13use serde::{Deserialize, Serialize};
14
15use crate::{
16 queue::Queue,
17 talk::{self, Talks},
18};
19
20#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
22#[serde(deny_unknown_fields)]
23pub struct Inquiry {
24 pub schema: u32,
26 pub id: String,
28 pub task: String,
30 pub run: Option<String>,
32 pub repo: PathBuf,
34 pub source: String,
36 #[serde(default, skip_serializing_if = "Option::is_none")]
38 pub occurrence: Option<String>,
39 pub text: String,
41 pub display: String,
43 pub key: String,
45 pub evidence: Option<String>,
47 pub created_at: Timestamp,
49 pub delivered_to: Option<String>,
51 #[serde(default, skip_serializing_if = "Option::is_none")]
53 pub decision: Option<crate::task_decision::Decision>,
54 #[serde(default, skip_serializing_if = "Option::is_none")]
56 pub delivery_error: Option<String>,
57 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
59 pub archived: bool,
60}
61
62#[derive(Clone, Copy, PartialEq, Eq)]
64pub(crate) enum HistoryResolution {
65 Applied,
66 Retired,
67}
68
69#[derive(Debug, Clone)]
71pub struct Outbox {
72 root: PathBuf,
73}
74
75pub(crate) struct ExecutionClaim {
78 _file: File,
80}
81
82#[cfg(unix)]
83impl Drop for ExecutionClaim {
84 fn drop(&mut self) {
85 use std::os::fd::AsRawFd;
86 unsafe { libc::flock(self._file.as_raw_fd(), libc::LOCK_UN) };
89 }
90}
91
92fn valid_id(id: &str) -> bool {
93 !id.is_empty()
94 && id.len() <= 160
95 && id
96 .bytes()
97 .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_'))
98}
99
100fn id_for(task: &str, kind: &str, generation: &str) -> String {
102 use sha2::{Digest, Sha256};
103 let bytes = serde_json::to_vec(&("task-inquiry-v3", task, kind, generation))
104 .expect("string tuple serialization cannot fail");
105 let digest: String = Sha256::digest(bytes)
106 .iter()
107 .map(|byte| format!("{byte:02x}"))
108 .collect();
109 format!("task-v3-{digest}")
110}
111
112fn same_repository(left: &Path, right: &Path) -> bool {
113 left == right
114 || std::fs::canonicalize(left)
115 .ok()
116 .zip(std::fs::canonicalize(right).ok())
117 .is_some_and(|(left, right)| left == right)
118}
119
120impl Outbox {
121 pub fn at(home: &Path) -> Self {
123 Self {
124 root: home.join("notifications").join("task-inquiries"),
125 }
126 }
127
128 fn path(&self, id: &str) -> Result<PathBuf> {
129 ensure!(valid_id(id), "invalid inquiry id");
130 Ok(self.root.join(format!("{id}.json")))
131 }
132
133 fn lock(&self, id: &str) -> Result<File> {
134 self.path(id)?;
135 std::fs::create_dir_all(&self.root)?;
136 let file = OpenOptions::new()
137 .read(true)
138 .write(true)
139 .create(true)
140 .truncate(false)
141 .open(self.root.join(format!("{id}.lock")))?;
142 let deadline = Instant::now() + Duration::from_secs(20);
143 loop {
144 match crate::pr_head::try_lock_file(&file) {
145 Ok(()) => return Ok(file),
146 Err(error)
147 if error.kind() == std::io::ErrorKind::WouldBlock
148 || error.raw_os_error() == Some(33) =>
149 {
150 ensure!(Instant::now() < deadline, "inquiry {id} is busy");
151 std::thread::sleep(Duration::from_millis(10));
152 }
153 Err(error) => return Err(error.into()),
154 }
155 }
156 }
157
158 pub(crate) fn execution_claim(&self, id: &str) -> Result<ExecutionClaim> {
162 self.path(id)?;
163 std::fs::create_dir_all(&self.root)?;
164 let file = OpenOptions::new()
165 .read(true)
166 .write(true)
167 .create(true)
168 .truncate(false)
169 .open(self.root.join(format!("{id}.execution.lock")))?;
170 crate::pr_head::try_lock_file(&file)
171 .with_context(|| format!("effect consumer for inquiry {id} is busy"))?;
172 Ok(ExecutionClaim { _file: file })
173 }
174
175 fn save(&self, inquiry: &Inquiry) -> Result<()> {
176 let path = self.path(&inquiry.id)?;
177 let temporary = path.with_extension("json.tmp");
178 std::fs::write(&temporary, serde_json::to_vec_pretty(inquiry)?)?;
179 std::fs::rename(temporary, path)?;
180 Ok(())
181 }
182
183 pub fn file(
186 &self,
187 task: &crate::queue::Task,
188 run: Option<String>,
189 source: String,
190 summary: &str,
191 detail: &str,
192 ) -> Result<Inquiry> {
193 let content = serde_json::to_string(&(summary, detail))?;
194 let occurrence = format!("content:{}", id_for(&task.id, &source, &content));
195 self.file_for_occurrence(task, run, source, &occurrence, summary, detail)
196 }
197
198 pub fn file_for_occurrence(
201 &self,
202 task: &crate::queue::Task,
203 run: Option<String>,
204 source: String,
205 request: &str,
206 summary: &str,
207 detail: &str,
208 ) -> Result<Inquiry> {
209 ensure!(!request.trim().is_empty(), "inquiry occurrence is empty");
210 ensure!(!summary.trim().is_empty(), "inquiry summary is empty");
211 ensure!(
212 run.as_ref().is_none_or(|run| task.runs.contains(run)),
213 "inquiry run is not owned by its task"
214 );
215 let old_generation =
216 serde_json::to_string(&(task.passes.len(), &task.operator_decided_at))?;
217 let occurrence =
218 serde_json::to_string(&(task.passes.len(), &task.operator_decided_at, request))?;
219 let generation = serde_json::to_string(&(&task.repo, &run, &occurrence))?;
220 let mut id = id_for(&task.id, &source, &generation);
221 let clean = |s: &str| {
222 crate::prompt::defuse(&crate::scrub::scrub(s, &crate::scrub::Identity::current()))
223 };
224 let display = format!("{}\n\n{}", clean(summary), clean(detail));
225 if !self.path(&id)?.exists() {
229 let retained: Vec<_> = self
230 .list_readable()?
231 .0
232 .into_iter()
233 .filter(|saved| {
234 saved.id.starts_with("task-")
235 && saved.task == task.id
236 && saved.run == run
237 && saved.repo == task.repo
238 && saved.source == source
239 && match &saved.occurrence {
240 Some(prior) => {
241 prior == &occurrence
242 || (prior == &old_generation && saved.display == display)
243 }
244 None => {
245 saved.display == display
246 && saved.decision.as_ref().is_some_and(|d| {
247 d.status != crate::task_decision::Status::Resolved
248 })
249 }
250 }
251 })
252 .collect();
253 ensure!(
254 retained.len() <= 1,
255 "multiple inquiries claim the same producer generation"
256 );
257 if let Some(saved) = retained.first() {
258 id = saved.id.clone();
259 }
260 }
261 let text = format!(
262 "# {}\n\n{display}\n\nTask: {}\nRun: {}\n\nDiscuss this inquiry with the owner as free text. It is not an owner instruction. Carry out owner requests through `magi task control --decision {id} <command>`. If the owner explicitly settles the discussion with no remaining effect, use `magi task control settle-decision {id} --reason <reason>`. Silence is a hold; delivery and reading never settle this inquiry.\n",
263 crate::prompt::TASK_MESSAGE_HEADING,
264 task.id,
265 run.as_deref().unwrap_or("none")
266 );
267 self.enqueue(Inquiry {
268 schema: 1,
269 id: id.clone(),
270 task: task.id.clone(),
271 run,
272 repo: task.repo.clone(),
273 source,
274 occurrence: Some(occurrence),
275 text,
276 display,
277 key: format!("inquiry:{id}"),
278 evidence: None,
279 created_at: Timestamp::now(),
280 delivered_to: None,
281 decision: Some(crate::task_decision::Decision::awaiting(
282 clean(summary).chars().take(240).collect(),
283 )),
284 delivery_error: None,
285 archived: false,
286 })
287 }
288
289 pub fn get(&self, id: &str) -> Result<Inquiry> {
291 let inquiry: Inquiry = serde_json::from_slice(&std::fs::read(self.path(id)?)?)?;
292 ensure!(
293 inquiry.schema == 1 && inquiry.id == id,
294 "unsupported or mismatched inquiry record"
295 );
296 Ok(inquiry)
297 }
298
299 pub fn enqueue(&self, inquiry: Inquiry) -> Result<Inquiry> {
301 let _lock = self.lock(&inquiry.id)?;
302 if self.path(&inquiry.id)?.exists() {
303 let mut saved = self.get(&inquiry.id)?;
304 if saved.task.is_empty()
305 && !inquiry.task.is_empty()
306 && saved.delivered_to.is_none()
307 && saved.source == inquiry.source
308 && saved.decision.as_ref().is_some_and(|d| d.request.is_none())
309 {
310 saved.task = inquiry.task.clone();
311 saved.run = inquiry.run.clone();
312 saved.repo = inquiry.repo.clone();
313 saved.text = inquiry.text.clone();
314 saved.display = inquiry.display.clone();
315 saved.evidence = inquiry.evidence.clone();
316 saved.delivery_error = None;
317 self.save(&saved)?;
318 }
319 ensure!(
320 saved.task == inquiry.task
321 && saved.run == inquiry.run
322 && saved.repo == inquiry.repo
323 && saved.source == inquiry.source
324 && saved.key == inquiry.key,
325 "inquiry identity was reused for a different target"
326 );
327 if let Some(occurrence) = &inquiry.occurrence {
330 let retained_generation = saved.occurrence.as_ref().is_some_and(|prior| {
331 let prior = serde_json::from_str::<Vec<serde_json::Value>>(prior);
332 let next = serde_json::from_str::<Vec<serde_json::Value>>(occurrence);
333 matches!((prior, next), (Ok(prior), Ok(next)) if prior.len() == 2 && next.len() == 3 && prior == next[..2] && saved.display == inquiry.display)
334 });
335 ensure!(
336 saved
337 .occurrence
338 .as_ref()
339 .is_none_or(|prior| prior == occurrence)
340 || retained_generation,
341 "inquiry identity was reused across occurrence generations"
342 );
343 if saved.occurrence.is_none() || retained_generation {
344 saved.occurrence = Some(occurrence.clone());
345 self.save(&saved)?;
346 }
347 }
348 if saved.decision.is_none() && inquiry.decision.is_some() {
349 saved.archived = inquiry.archived;
350 if !inquiry.archived {
351 saved.text = inquiry.text;
352 saved.display = inquiry.display;
353 }
354 saved.decision = inquiry.decision;
355 self.save(&saved)?;
356 }
357 return Ok(saved);
358 }
359 ensure!(
360 inquiry.schema == 1 && inquiry.delivered_to.is_none(),
361 "new inquiries cannot carry delivery receipts"
362 );
363 ensure!(!inquiry.text.trim().is_empty(), "inquiry text is empty");
364 self.save(&inquiry)?;
365 Ok(inquiry)
366 }
367
368 pub(crate) fn reclassify_history(
371 &self,
372 incoming: Inquiry,
373 resolution: HistoryResolution,
374 ) -> Result<()> {
375 let _execution = self.execution_claim(&incoming.id)?;
376 let _lock = self.lock(&incoming.id)?;
377 let mut saved = match self.get(&incoming.id) {
378 Ok(saved) => saved,
379 Err(error)
380 if error
381 .downcast_ref::<std::io::Error>()
382 .is_some_and(|e| e.kind() == std::io::ErrorKind::NotFound) =>
383 {
384 return self.save(&incoming);
385 }
386 Err(error) => return Err(error),
387 };
388 ensure!(
389 saved.source == incoming.source && saved.key == incoming.key,
390 "history correction source identity changed"
391 );
392 if saved.decision.as_ref().is_some_and(|d| {
393 d.request.is_some() || d.status == crate::task_decision::Status::Resolved
394 }) {
395 return Ok(());
396 }
397 ensure!(
398 saved.task.is_empty()
399 || incoming.task.is_empty()
400 || (saved.task == incoming.task
401 && saved.repo == incoming.repo
402 && saved.run == incoming.run),
403 "history correction ownership changed; reconcile the original owner"
404 );
405 if saved.task.is_empty() && !incoming.task.is_empty() && saved.delivered_to.is_none() {
406 saved.task = incoming.task.clone();
407 saved.run = incoming.run.clone();
408 saved.repo = incoming.repo.clone();
409 }
410 saved.archived = incoming.archived;
413 match (&mut saved.decision, incoming.decision) {
414 (Some(saved), Some(next)) => {
415 if next.status == crate::task_decision::Status::Resolved {
416 let evidence = next
417 .history
418 .last()
419 .context("completed history has no receipt")?;
420 if resolution == HistoryResolution::Retired {
421 saved.retire(&evidence.evidence)?;
422 } else {
423 saved.applied(&evidence.evidence)?;
424 }
425 } else if let Some(error) = next.error {
426 saved.fail(&error)?;
427 }
428 }
429 (decision @ None, next) => *decision = next,
430 _ => {}
431 }
432 saved.delivery_error = incoming.delivery_error;
433 self.save(&saved)
434 }
435
436 pub fn deliver(&self, queue: &Queue, talks: &Talks, id: &str) -> Result<String> {
439 let _lock = self.lock(id)?;
440 let mut inquiry = self.get(id)?;
441 ensure!(
442 !inquiry.archived,
443 "passive inquiry history is not a delivery"
444 );
445 let (_, mut chat) =
446 crate::task_chat::destination_checked(queue, talks, &inquiry.task, |task| {
447 ensure!(
448 same_repository(&task.repo, &inquiry.repo),
449 "inquiry repository no longer matches its task"
450 );
451 ensure!(
452 inquiry
453 .run
454 .as_ref()
455 .is_none_or(|run| task.runs.contains(run)),
456 "inquiry run is not owned by its task"
457 );
458 Ok(())
459 })?;
460 if let Some(delivered) = &inquiry.delivered_to {
461 ensure!(
462 delivered == &chat.id,
463 "delivered inquiry changed conversations"
464 );
465 if chat.notified.iter().any(|key| key == &inquiry.key) {
466 return Ok(delivered.clone());
467 }
468 }
471 talk::queue_semantic_notice(
472 &mut chat,
473 talks,
474 &inquiry.text,
475 &inquiry.key,
476 &|_| false,
477 (
478 None,
479 Some(
480 inquiry
481 .evidence
482 .clone()
483 .unwrap_or_else(|| format!("task-inquiry:{}", inquiry.id)),
484 ),
485 ),
486 crate::prompt::NoticeDisplay {
487 inquiry: Some(inquiry.id.clone()),
488 facts: inquiry.display.clone(),
489 output: None,
490 task: Some(inquiry.task.clone()),
491 run: inquiry.run.clone(),
492 },
493 )?;
494 inquiry.delivered_to = Some(chat.id.clone());
495 inquiry.delivery_error = None;
496 self.save(&inquiry)?;
497 Ok(chat.id)
498 }
499
500 fn records(&self) -> Result<Vec<Result<Inquiry>>> {
501 let entries = match std::fs::read_dir(&self.root) {
502 Ok(entries) => entries,
503 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
504 Err(error) => return Err(error.into()),
505 };
506 let mut paths = Vec::new();
507 for entry in entries {
508 let path = entry?.path();
509 if path
510 .extension()
511 .is_some_and(|extension| extension == "json")
512 {
513 paths.push(path);
514 }
515 }
516 paths.sort();
517 Ok(paths
518 .into_iter()
519 .map(|path| {
520 let id = path
521 .file_stem()
522 .and_then(|stem| stem.to_str())
523 .context("invalid inquiry filename")?;
524 self.get(id).with_context(|| format!("read inquiry {id}"))
525 })
526 .collect())
527 }
528
529 pub fn list(&self) -> Result<Vec<Inquiry>> {
531 self.records()?.into_iter().collect()
532 }
533
534 pub fn list_readable(&self) -> Result<(Vec<Inquiry>, usize)> {
537 let mut items = Vec::new();
538 let mut unreadable = 0;
539 for record in self.records()? {
540 match record {
541 Ok(inquiry) => items.push(inquiry),
542 Err(error) => {
543 tracing::warn!("task inquiry record is unreadable: {error:#}");
544 unreadable += 1;
545 }
546 }
547 }
548 Ok((items, unreadable))
549 }
550
551 pub fn update_decision(
554 &self,
555 id: &str,
556 change: impl FnOnce(&mut crate::task_decision::Decision) -> Result<bool>,
557 ) -> Result<()> {
558 let _lock = self.lock(id)?;
559 let mut inquiry = self.get(id)?;
560 let decision = inquiry
561 .decision
562 .as_mut()
563 .context("inquiry is informational")?;
564 if change(decision)? {
565 self.save(&inquiry)?;
566 }
567 Ok(())
568 }
569
570 pub fn settle(
577 &self,
578 id: &str,
579 chat: &str,
580 reason: &str,
581 replacement: Option<&str>,
582 ) -> Result<()> {
583 ensure!(!reason.trim().is_empty(), "settlement reason is empty");
584 let _execution = self.execution_claim(id)?;
585 let mut ids = vec![id];
586 if let Some(replacement) = replacement {
587 ensure!(replacement != id, "decision cannot supersede itself");
588 ids.push(replacement);
589 }
590 ids.sort_unstable();
591 let _locks: Vec<_> = ids
594 .into_iter()
595 .map(|id| self.lock(id))
596 .collect::<Result<_>>()?;
597 let mut current = self.get(id)?;
598 ensure!(
599 current.delivered_to.as_deref() == Some(chat)
600 || (current.task.is_empty()
601 && current.delivered_to.is_none()
602 && replacement.is_none()),
603 "decision belongs to another chat"
604 );
605 let reason = if let Some(replacement) = replacement {
606 ensure!(replacement != id, "decision cannot supersede itself");
607 let next = self.get(replacement)?;
608 ensure!(
609 next.task == current.task
610 && next.repo == current.repo
611 && next.delivered_to == current.delivered_to
612 && next
613 .decision
614 .as_ref()
615 .is_some_and(|d| d.status != crate::task_decision::Status::Resolved),
616 "replacement must be an active decision in the same task chat"
617 );
618 format!("superseded by {replacement}: {reason}")
619 } else {
620 format!("owner settled; no further effect remains: {reason}")
621 };
622 let decision = current
623 .decision
624 .as_mut()
625 .context("inquiry is informational")?;
626 let changed = if decision
627 .request
628 .as_deref()
629 .is_some_and(|r| r.starts_with("decision: "))
630 {
631 decision.settle_legacy(&format!(
632 "owner confirmed no remaining legacy effect: {reason}"
633 ))?
634 } else {
635 decision.settle(&reason)?
636 };
637 if changed {
638 self.save(¤t)?;
639 }
640 Ok(())
641 }
642
643 pub fn pending(&self) -> Result<Vec<Inquiry>> {
645 Ok(self
646 .records()?
647 .into_iter()
648 .collect::<Result<Vec<_>>>()?
649 .into_iter()
650 .filter(|inquiry| {
651 inquiry.delivered_to.is_none()
652 && !inquiry.archived
653 && inquiry.decision.as_ref().is_none_or(|decision| {
654 decision.status != crate::task_decision::Status::Resolved
655 })
656 })
657 .collect())
658 }
659
660 pub fn sweep(&self, queue: &Queue, talks: &Talks) -> Result<()> {
662 let home = self
663 .root
664 .parent()
665 .and_then(Path::parent)
666 .context("inquiry store has no home")?;
667 let deferred = crate::task_chat::migration_pending(home);
668 let mut failed = None;
669 for record in self.records()? {
670 let inquiry = match record {
671 Ok(inquiry) => inquiry,
672 Err(error) => {
673 tracing::warn!("task inquiry record is unreadable: {error:#}");
674 failed.get_or_insert(error);
675 continue;
676 }
677 };
678 if inquiry.key.starts_with("question:")
679 && deferred
680 .as_ref()
681 .map_or(true, |ids| ids.contains(&inquiry.id))
682 {
683 continue;
684 }
685 if inquiry.archived
686 || inquiry
687 .decision
688 .as_ref()
689 .is_some_and(|d| d.status == crate::task_decision::Status::Resolved)
690 || inquiry.task.is_empty()
691 {
692 continue;
693 }
694 if inquiry
695 .delivered_to
696 .as_ref()
697 .is_some_and(|id| talks.path_of(id).exists())
698 {
699 continue;
700 }
701 if let Err(error) = self.deliver(queue, talks, &inquiry.id) {
702 if let Ok(_lock) = self.lock(&inquiry.id)
703 && let Ok(mut current) = self.get(&inquiry.id)
704 {
705 let message = format!("{error:#}");
706 if current.delivery_error.as_ref() != Some(&message) {
707 current.delivery_error = Some(message);
708 if let Err(error) = self.save(¤t) {
709 tracing::warn!("cannot persist inquiry delivery failure: {error:#}");
710 }
711 }
712 }
713 tracing::warn!("inquiry {} delivery failed: {error:#}", inquiry.id);
714 failed.get_or_insert(error);
715 }
716 }
717 failed.map_or(Ok(()), Err)
718 }
719}
720
721#[cfg(test)]
722mod tests {
723 use super::*;
724
725 #[cfg(unix)]
726 #[test]
727 fn execution_claim_releases_while_an_inherited_descriptor_remains_open() {
728 let home = tempfile::tempdir().unwrap();
729 let outbox = Outbox::at(home.path());
730 let claim = outbox.execution_claim("legacy-inquiry").unwrap();
731 let inherited = claim._file.try_clone().unwrap();
733 assert!(outbox.execution_claim("legacy-inquiry").is_err());
734 drop(claim);
735 let next = outbox.execution_claim("legacy-inquiry").unwrap();
736 drop(inherited);
737 assert!(outbox.execution_claim("legacy-inquiry").is_err());
738 drop(next);
739 assert!(outbox.execution_claim("legacy-inquiry").is_ok());
740 }
741 use crate::{
742 queue::{Source, Task},
743 task_decision::Status,
744 };
745
746 fn task() -> Task {
747 Task::new(
748 "work".into(),
749 "work".into(),
750 PathBuf::from("/repo"),
751 Source::Human,
752 )
753 }
754
755 #[test]
756 fn identity_uses_task_kind_and_generation_with_unambiguous_boundaries() {
757 assert_eq!(id_for("t", "k", "g"), id_for("t", "k", "g"));
758 assert_ne!(id_for("t", "k", "g"), id_for("u", "k", "g"));
759 assert_ne!(id_for("t", "k", "g"), id_for("t", "l", "g"));
760 assert_ne!(id_for("t", "k", "g"), id_for("t", "k", "h"));
761 assert_ne!(id_for("ab", "c", "d"), id_for("a", "bc", "d"));
762 }
763
764 #[test]
765 fn rewording_after_restart_preserves_content_receipts_and_all_decision_states() {
766 let dir = tempfile::tempdir().unwrap();
767 let mut task = task();
768 task.runs = vec!["run-a".into(), "run-b".into()];
769 let outbox = Outbox::at(dir.path());
770 let first = outbox
771 .file_for_occurrence(
772 &task,
773 Some("run-a".into()),
774 "implement".into(),
775 "first-inquiry",
776 "Original",
777 "Original detail",
778 )
779 .unwrap();
780 for status in [
781 Status::AwaitingOwner,
782 Status::Queued,
783 Status::InProgress,
784 Status::RetryNeeded,
785 Status::Resolved,
786 ] {
787 let mut saved = outbox.get(&first.id).unwrap();
788 saved.delivered_to = Some("chat-a".into());
789 let decision = saved.decision.as_mut().unwrap();
790 decision.status = status;
791 decision.request =
792 (status != Status::AwaitingOwner).then(|| "durable owner request".into());
793 decision.error = (status == Status::RetryNeeded).then(|| "uncertain effect".into());
794 outbox.save(&saved).unwrap();
795 let replay = Outbox::at(dir.path())
796 .file_for_occurrence(
797 &task,
798 Some("run-a".into()),
799 "implement".into(),
800 "first-inquiry",
801 "Reworded",
802 "Changed detail",
803 )
804 .unwrap();
805 assert_eq!(replay, saved);
806 }
807 let other_kind = outbox
808 .file_for_occurrence(
809 &task,
810 Some("run-a".into()),
811 "review".into(),
812 "first-inquiry",
813 "Original",
814 "Original detail",
815 )
816 .unwrap();
817 let other_run = outbox
818 .file_for_occurrence(
819 &task,
820 Some("run-b".into()),
821 "implement".into(),
822 "first-inquiry",
823 "Original",
824 "Original detail",
825 )
826 .unwrap();
827 assert_ne!(first.id, other_kind.id);
828 assert_ne!(first.id, other_run.id);
829 task.hold_manual(Some("new owner generation".into()));
830 let next = outbox
831 .file_for_occurrence(
832 &task,
833 Some("run-a".into()),
834 "implement".into(),
835 "first-inquiry",
836 "Original",
837 "Original detail",
838 )
839 .unwrap();
840 assert_ne!(first.id, next.id);
841 assert_eq!(next.decision.unwrap().status, Status::AwaitingOwner);
842 assert_eq!(outbox.list().unwrap().len(), 4);
843 }
844
845 #[test]
846 fn retained_content_ids_keep_links_and_lifecycle_when_reworded() {
847 let dir = tempfile::tempdir().unwrap();
848 let task = task();
849 let outbox = Outbox::at(dir.path());
850 let mut retained = outbox
851 .file_for_occurrence(
852 &task,
853 None,
854 "implement".into(),
855 "first-inquiry",
856 "Original",
857 "Original detail",
858 )
859 .unwrap();
860 std::fs::remove_file(outbox.path(&retained.id).unwrap()).unwrap();
861 retained.id = "task-retained-content-hash".into();
863 retained.key = format!("inquiry:{}", retained.id);
864 retained.delivered_to = Some("retained-chat".into());
865 retained
866 .decision
867 .as_mut()
868 .unwrap()
869 .settle("owner settled this occurrence")
870 .unwrap();
871 outbox.save(&retained).unwrap();
872 let replay = Outbox::at(dir.path())
873 .file_for_occurrence(
874 &task,
875 None,
876 "implement".into(),
877 "first-inquiry",
878 "Reworded",
879 "Changed detail",
880 )
881 .unwrap();
882 assert_eq!(replay, retained);
883 assert_eq!(outbox.list().unwrap().len(), 1);
884 }
885}