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