Skip to main content

magi/
task_inquiry.rs

1//! Durable task-owned free-text deliveries, independent of decision execution.
2//!
3//! A delivery receipt means only that the conversation accepted a report. It
4//! never records an owner request or authorizes a task, publication or merge.
5use 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/// Free-text input owed to a task's conversation.
21#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
22#[serde(deny_unknown_fields)]
23pub struct Inquiry {
24    /// Durable format version.
25    pub schema: u32,
26    /// Stable producer-assigned delivery identity.
27    pub id: String,
28    /// Exact owning task; prefixes are never resolved on delivery.
29    pub task: String,
30    /// Execution the inquiry concerns, if any.
31    pub run: Option<String>,
32    /// Repository captured when the inquiry was filed.
33    pub repo: PathBuf,
34    /// Producing graph node or service.
35    pub source: String,
36    /// Producer occurrence generation. Older saved inquiries may not have one.
37    #[serde(default, skip_serializing_if = "Option::is_none")]
38    pub occurrence: Option<String>,
39    /// Complete free-text agent input, with no executable choices.
40    pub text: String,
41    /// User-visible report facts.
42    pub display: String,
43    /// Source delivery key, retained across a transport migration.
44    pub key: String,
45    /// Existing automatic-notice evidence identity.
46    pub evidence: Option<String>,
47    /// When the inquiry was filed.
48    pub created_at: Timestamp,
49    /// Conversation that durably accepted it. This is not an action receipt.
50    pub delivered_to: Option<String>,
51    /// Owner decision lifecycle; absent for informational deliveries.
52    #[serde(default, skip_serializing_if = "Option::is_none")]
53    pub decision: Option<crate::task_decision::Decision>,
54    /// Delivery failures never count as a decision or action outcome.
55    #[serde(default, skip_serializing_if = "Option::is_none")]
56    pub delivery_error: Option<String>,
57    /// Passive imported history; never submitted to a chat worker.
58    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
59    pub archived: bool,
60}
61
62/// File-backed outbox under the existing notifications write grant.
63#[derive(Debug, Clone)]
64pub struct Outbox {
65    root: PathBuf,
66}
67
68/// Release the execution fence even if a concurrent fork still retains a
69/// descriptor for the same open file description.
70pub(crate) struct ExecutionClaim(File);
71
72#[cfg(unix)]
73impl Drop for ExecutionClaim {
74    fn drop(&mut self) {
75        use std::os::fd::AsRawFd;
76        // SAFETY: this guard owns the live descriptor; LOCK_UN releases only
77        // this open file description's flock.
78        unsafe { libc::flock(self.0.as_raw_fd(), libc::LOCK_UN) };
79    }
80}
81
82fn valid_id(id: &str) -> bool {
83    !id.is_empty()
84        && id.len() <= 160
85        && id
86            .bytes()
87            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_'))
88}
89
90/// Stable identity for one producer-assigned occurrence.
91fn id_for(task: &str, kind: &str, generation: &str) -> String {
92    use sha2::{Digest, Sha256};
93    let bytes = serde_json::to_vec(&("task-inquiry-v3", task, kind, generation))
94        .expect("string tuple serialization cannot fail");
95    let digest: String = Sha256::digest(bytes)
96        .iter()
97        .map(|byte| format!("{byte:02x}"))
98        .collect();
99    format!("task-v3-{digest}")
100}
101
102fn same_repository(left: &Path, right: &Path) -> bool {
103    left == right
104        || std::fs::canonicalize(left)
105            .ok()
106            .zip(std::fs::canonicalize(right).ok())
107            .is_some_and(|(left, right)| left == right)
108}
109
110impl Outbox {
111    /// Open an outbox beneath an explicit state home.
112    pub fn at(home: &Path) -> Self {
113        Self {
114            root: home.join("notifications").join("task-inquiries"),
115        }
116    }
117
118    fn path(&self, id: &str) -> Result<PathBuf> {
119        ensure!(valid_id(id), "invalid inquiry id");
120        Ok(self.root.join(format!("{id}.json")))
121    }
122
123    fn lock(&self, id: &str) -> Result<File> {
124        self.path(id)?;
125        std::fs::create_dir_all(&self.root)?;
126        let file = OpenOptions::new()
127            .read(true)
128            .write(true)
129            .create(true)
130            .truncate(false)
131            .open(self.root.join(format!("{id}.lock")))?;
132        let deadline = Instant::now() + Duration::from_secs(20);
133        loop {
134            match crate::pr_head::try_lock_file(&file) {
135                Ok(()) => return Ok(file),
136                Err(error)
137                    if error.kind() == std::io::ErrorKind::WouldBlock
138                        || error.raw_os_error() == Some(33) =>
139                {
140                    ensure!(Instant::now() < deadline, "inquiry {id} is busy");
141                    std::thread::sleep(Duration::from_millis(10));
142                }
143                Err(error) => return Err(error.into()),
144            }
145        }
146    }
147
148    /// Shared with legacy consumers: acquire before reading an executable reply
149    /// and retain through its effect and receipt. Nonblocking so a settlement
150    /// cannot wait for (and then hide) an operation currently in flight.
151    pub(crate) fn execution_claim(&self, id: &str) -> Result<ExecutionClaim> {
152        self.path(id)?;
153        std::fs::create_dir_all(&self.root)?;
154        let file = OpenOptions::new()
155            .read(true)
156            .write(true)
157            .create(true)
158            .truncate(false)
159            .open(self.root.join(format!("{id}.execution.lock")))?;
160        crate::pr_head::try_lock_file(&file)
161            .with_context(|| format!("effect consumer for inquiry {id} is busy"))?;
162        Ok(ExecutionClaim(file))
163    }
164
165    fn save(&self, inquiry: &Inquiry) -> Result<()> {
166        let path = self.path(&inquiry.id)?;
167        let temporary = path.with_extension("json.tmp");
168        std::fs::write(&temporary, serde_json::to_vec_pretty(inquiry)?)?;
169        std::fs::rename(temporary, path)?;
170        Ok(())
171    }
172
173    /// File one content-distinct inquiry. An unchanged producer replay retains
174    /// its receipt; independent inquiries need distinct occurrence identifiers.
175    pub fn file(
176        &self,
177        task: &crate::queue::Task,
178        run: Option<String>,
179        source: String,
180        summary: &str,
181        detail: &str,
182    ) -> Result<Inquiry> {
183        let content = serde_json::to_string(&(summary, detail))?;
184        let occurrence = format!("content:{}", id_for(&task.id, &source, &content));
185        self.file_for_occurrence(task, run, source, &occurrence, summary, detail)
186    }
187
188    /// File or replay an explicit producer occurrence independently of prose.
189    /// Use a new key for each separate inquiry, including identical wording.
190    pub fn file_for_occurrence(
191        &self,
192        task: &crate::queue::Task,
193        run: Option<String>,
194        source: String,
195        request: &str,
196        summary: &str,
197        detail: &str,
198    ) -> Result<Inquiry> {
199        ensure!(!request.trim().is_empty(), "inquiry occurrence is empty");
200        ensure!(!summary.trim().is_empty(), "inquiry summary is empty");
201        ensure!(
202            run.as_ref().is_none_or(|run| task.runs.contains(run)),
203            "inquiry run is not owned by its task"
204        );
205        let old_generation =
206            serde_json::to_string(&(task.passes.len(), &task.operator_decided_at))?;
207        let occurrence =
208            serde_json::to_string(&(task.passes.len(), &task.operator_decided_at, request))?;
209        let generation = serde_json::to_string(&(&task.repo, &run, &occurrence))?;
210        let mut id = id_for(&task.id, &source, &generation);
211        let clean = |s: &str| {
212            crate::prompt::defuse(&crate::scrub::scrub(s, &crate::scrub::Identity::current()))
213        };
214        let display = format!("{}\n\n{}", clean(summary), clean(detail));
215        // Adopt retained content-derived IDs without rewriting transcript links
216        // or effect receipts. Unknown generations can only carry forward active,
217        // unchanged intent; known generations also retain resolved history.
218        if !self.path(&id)?.exists() {
219            let retained: Vec<_> = self
220                .list_readable()?
221                .0
222                .into_iter()
223                .filter(|saved| {
224                    saved.id.starts_with("task-")
225                        && saved.task == task.id
226                        && saved.run == run
227                        && saved.repo == task.repo
228                        && saved.source == source
229                        && match &saved.occurrence {
230                            Some(prior) => {
231                                prior == &occurrence
232                                    || (prior == &old_generation && saved.display == display)
233                            }
234                            None => {
235                                saved.display == display
236                                    && saved.decision.as_ref().is_some_and(|d| {
237                                        d.status != crate::task_decision::Status::Resolved
238                                    })
239                            }
240                        }
241                })
242                .collect();
243            ensure!(
244                retained.len() <= 1,
245                "multiple inquiries claim the same producer generation"
246            );
247            if let Some(saved) = retained.first() {
248                id = saved.id.clone();
249            }
250        }
251        let text = format!(
252            "# {}\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",
253            crate::prompt::TASK_MESSAGE_HEADING,
254            task.id,
255            run.as_deref().unwrap_or("none")
256        );
257        self.enqueue(Inquiry {
258            schema: 1,
259            id: id.clone(),
260            task: task.id.clone(),
261            run,
262            repo: task.repo.clone(),
263            source,
264            occurrence: Some(occurrence),
265            text,
266            display,
267            key: format!("inquiry:{id}"),
268            evidence: None,
269            created_at: Timestamp::now(),
270            delivered_to: None,
271            decision: Some(crate::task_decision::Decision::awaiting(
272                clean(summary).chars().take(240).collect(),
273            )),
274            delivery_error: None,
275            archived: false,
276        })
277    }
278
279    /// Read one delivery without consulting legacy question records.
280    pub fn get(&self, id: &str) -> Result<Inquiry> {
281        let inquiry: Inquiry = serde_json::from_slice(&std::fs::read(self.path(id)?)?)?;
282        ensure!(
283            inquiry.schema == 1 && inquiry.id == id,
284            "unsupported or mismatched inquiry record"
285        );
286        Ok(inquiry)
287    }
288
289    /// Persist before delivery. Retries retain the original input and receipt.
290    pub fn enqueue(&self, inquiry: Inquiry) -> Result<Inquiry> {
291        let _lock = self.lock(&inquiry.id)?;
292        if self.path(&inquiry.id)?.exists() {
293            let mut saved = self.get(&inquiry.id)?;
294            if saved.task.is_empty()
295                && !inquiry.task.is_empty()
296                && saved.delivered_to.is_none()
297                && saved.source == inquiry.source
298                && saved.decision.as_ref().is_some_and(|d| d.request.is_none())
299            {
300                saved.task = inquiry.task.clone();
301                saved.run = inquiry.run.clone();
302                saved.repo = inquiry.repo.clone();
303                saved.text = inquiry.text.clone();
304                saved.display = inquiry.display.clone();
305                saved.evidence = inquiry.evidence.clone();
306                saved.delivery_error = None;
307                self.save(&saved)?;
308            }
309            ensure!(
310                saved.task == inquiry.task
311                    && saved.run == inquiry.run
312                    && saved.repo == inquiry.repo
313                    && saved.source == inquiry.source
314                    && saved.key == inquiry.key,
315                "inquiry identity was reused for a different target"
316            );
317            // The original prose and decision lifecycle survive a producer replay.
318            // Identity is ownership plus occurrence, never the rephrased body.
319            if let Some(occurrence) = &inquiry.occurrence {
320                let retained_generation = saved.occurrence.as_ref().is_some_and(|prior| {
321                    let prior = serde_json::from_str::<Vec<serde_json::Value>>(prior);
322                    let next = serde_json::from_str::<Vec<serde_json::Value>>(occurrence);
323                    matches!((prior, next), (Ok(prior), Ok(next)) if prior.len() == 2 && next.len() == 3 && prior == next[..2] && saved.display == inquiry.display)
324                });
325                ensure!(
326                    saved
327                        .occurrence
328                        .as_ref()
329                        .is_none_or(|prior| prior == occurrence)
330                        || retained_generation,
331                    "inquiry identity was reused across occurrence generations"
332                );
333                if saved.occurrence.is_none() || retained_generation {
334                    saved.occurrence = Some(occurrence.clone());
335                    self.save(&saved)?;
336                }
337            }
338            if saved.decision.is_none() && inquiry.decision.is_some() {
339                saved.archived = inquiry.archived;
340                if !inquiry.archived {
341                    saved.text = inquiry.text;
342                    saved.display = inquiry.display;
343                }
344                saved.decision = inquiry.decision;
345                self.save(&saved)?;
346            }
347            return Ok(saved);
348        }
349        ensure!(
350            inquiry.schema == 1 && inquiry.delivered_to.is_none(),
351            "new inquiries cannot carry delivery receipts"
352        );
353        ensure!(!inquiry.text.trim().is_empty(), "inquiry text is empty");
354        self.save(&inquiry)?;
355        Ok(inquiry)
356    }
357
358    /// Deliver under a per-inquiry lease, releasing the task lock before any
359    /// conversation operation. The transcript key repairs a lost final receipt.
360    pub fn deliver(&self, queue: &Queue, talks: &Talks, id: &str) -> Result<String> {
361        let _lock = self.lock(id)?;
362        let mut inquiry = self.get(id)?;
363        ensure!(
364            !inquiry.archived,
365            "passive inquiry history is not a delivery"
366        );
367        let (_, mut chat) =
368            crate::task_chat::destination_checked(queue, talks, &inquiry.task, |task| {
369                ensure!(
370                    same_repository(&task.repo, &inquiry.repo),
371                    "inquiry repository no longer matches its task"
372                );
373                ensure!(
374                    inquiry
375                        .run
376                        .as_ref()
377                        .is_none_or(|run| task.runs.contains(run)),
378                    "inquiry run is not owned by its task"
379                );
380                Ok(())
381            })?;
382        if let Some(delivered) = &inquiry.delivered_to {
383            ensure!(
384                delivered == &chat.id,
385                "delivered inquiry changed conversations"
386            );
387            if chat.notified.iter().any(|key| key == &inquiry.key) {
388                return Ok(delivered.clone());
389            }
390            // The saved conversation was removed/recreated after delivery.
391            // Restore the same inquiry key; no owner request is reconstructed.
392        }
393        talk::queue_semantic_notice(
394            &mut chat,
395            talks,
396            &inquiry.text,
397            &inquiry.key,
398            &|_| false,
399            (
400                None,
401                Some(
402                    inquiry
403                        .evidence
404                        .clone()
405                        .unwrap_or_else(|| format!("task-inquiry:{}", inquiry.id)),
406                ),
407            ),
408            crate::prompt::NoticeDisplay {
409                inquiry: Some(inquiry.id.clone()),
410                facts: inquiry.display.clone(),
411                output: None,
412                task: Some(inquiry.task.clone()),
413                run: inquiry.run.clone(),
414            },
415        )?;
416        inquiry.delivered_to = Some(chat.id.clone());
417        inquiry.delivery_error = None;
418        self.save(&inquiry)?;
419        Ok(chat.id)
420    }
421
422    fn records(&self) -> Result<Vec<Result<Inquiry>>> {
423        let entries = match std::fs::read_dir(&self.root) {
424            Ok(entries) => entries,
425            Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
426            Err(error) => return Err(error.into()),
427        };
428        let mut paths = Vec::new();
429        for entry in entries {
430            let path = entry?.path();
431            if path
432                .extension()
433                .is_some_and(|extension| extension == "json")
434            {
435                paths.push(path);
436            }
437        }
438        paths.sort();
439        Ok(paths
440            .into_iter()
441            .map(|path| {
442                let id = path
443                    .file_stem()
444                    .and_then(|stem| stem.to_str())
445                    .context("invalid inquiry filename")?;
446                self.get(id).with_context(|| format!("read inquiry {id}"))
447            })
448            .collect())
449    }
450
451    /// Stop compatibility/history delivery without manufacturing resolution.
452    pub(crate) fn suspend_delivery(&self, id: &str, reason: &str) -> Result<()> {
453        let _lock = self.lock(id)?;
454        let mut record = self.get(id)?;
455        if !record.archived || record.delivery_error.as_deref() != Some(reason) {
456            record.archived = true;
457            record.delivery_error = Some(reason.to_owned());
458            self.save(&record)?;
459        }
460        Ok(())
461    }
462
463    /// Read all durable inquiries, including completed decision history.
464    pub fn list(&self) -> Result<Vec<Inquiry>> {
465        self.records()?.into_iter().collect()
466    }
467
468    /// 一覧表示用の同一走査で、正常な記録と読めない記録の件数を返す。
469    /// 実行系の厳密な list / pending のエラー処理は変更しない。
470    pub fn list_readable(&self) -> Result<(Vec<Inquiry>, usize)> {
471        let mut items = Vec::new();
472        let mut unreadable = 0;
473        for record in self.records()? {
474            match record {
475                Ok(inquiry) => items.push(inquiry),
476                Err(error) => {
477                    tracing::warn!("task inquiry record is unreadable: {error:#}");
478                    unreadable += 1;
479                }
480            }
481        }
482        Ok((items, unreadable))
483    }
484
485    /// Change only the decision lifecycle under the same lease as delivery.
486    /// Returning false avoids rewriting a receipt on every scheduler lap.
487    pub fn update_decision(
488        &self,
489        id: &str,
490        change: impl FnOnce(&mut crate::task_decision::Decision) -> Result<bool>,
491    ) -> Result<()> {
492        let _lock = self.lock(id)?;
493        let mut inquiry = self.get(id)?;
494        let decision = inquiry
495            .decision
496            .as_mut()
497            .context("inquiry is informational")?;
498        if change(decision)? {
499            self.save(&inquiry)?;
500        }
501        Ok(())
502    }
503
504    /// Explicit settlement belongs to the owning task chat. Replacement must
505    /// already exist and have the same task/repository; it executes nothing.
506    /// Undelivered ownerless imports may be settled from any authorized chat
507    /// without assigning that chat or inventing a task association. Accepted
508    /// legacy choices support explicit owner confirmation of no remaining
509    /// effect; native command uncertainty still requires its receipt.
510    pub fn settle(
511        &self,
512        id: &str,
513        chat: &str,
514        reason: &str,
515        replacement: Option<&str>,
516    ) -> Result<()> {
517        ensure!(!reason.trim().is_empty(), "settlement reason is empty");
518        let _execution = self.execution_claim(id)?;
519        let mut ids = vec![id];
520        if let Some(replacement) = replacement {
521            ensure!(replacement != id, "decision cannot supersede itself");
522            ids.push(replacement);
523        }
524        ids.sort_unstable();
525        // Hold both records in a fixed order. Reciprocal supersessions cannot
526        // both observe an active replacement and erase the last pending intent.
527        let _locks: Vec<_> = ids
528            .into_iter()
529            .map(|id| self.lock(id))
530            .collect::<Result<_>>()?;
531        let mut current = self.get(id)?;
532        ensure!(
533            current.delivered_to.as_deref() == Some(chat)
534                || (current.task.is_empty()
535                    && current.delivered_to.is_none()
536                    && replacement.is_none()),
537            "decision belongs to another chat"
538        );
539        let reason = if let Some(replacement) = replacement {
540            ensure!(replacement != id, "decision cannot supersede itself");
541            let next = self.get(replacement)?;
542            ensure!(
543                next.task == current.task
544                    && next.repo == current.repo
545                    && next.delivered_to == current.delivered_to
546                    && next
547                        .decision
548                        .as_ref()
549                        .is_some_and(|d| d.status != crate::task_decision::Status::Resolved),
550                "replacement must be an active decision in the same task chat"
551            );
552            format!("superseded by {replacement}: {reason}")
553        } else {
554            format!("owner settled; no further effect remains: {reason}")
555        };
556        let decision = current
557            .decision
558            .as_mut()
559            .context("inquiry is informational")?;
560        let changed = if decision
561            .request
562            .as_deref()
563            .is_some_and(|r| r.starts_with("decision: "))
564        {
565            decision.settle_legacy(&format!(
566                "owner confirmed no remaining legacy effect: {reason}"
567            ))?
568        } else {
569            decision.settle(&reason)?
570        };
571        if changed {
572            self.save(&current)?;
573        }
574        Ok(())
575    }
576
577    /// Read pending deliveries. Corrupt records are errors, never silently skipped.
578    pub fn pending(&self) -> Result<Vec<Inquiry>> {
579        Ok(self
580            .records()?
581            .into_iter()
582            .collect::<Result<Vec<_>>>()?
583            .into_iter()
584            .filter(|inquiry| {
585                inquiry.delivered_to.is_none()
586                    && !inquiry.archived
587                    && inquiry.decision.as_ref().is_none_or(|decision| {
588                        decision.status != crate::task_decision::Status::Resolved
589                    })
590            })
591            .collect())
592    }
593
594    /// Resume durable deliveries after a scheduler restart without starting agents.
595    pub fn sweep(&self, queue: &Queue, talks: &Talks) -> Result<()> {
596        let home = self
597            .root
598            .parent()
599            .and_then(Path::parent)
600            .context("inquiry store has no home")?;
601        let deferred = crate::task_chat::migration_pending(home);
602        let mut failed = None;
603        for record in self.records()? {
604            let inquiry = match record {
605                Ok(inquiry) => inquiry,
606                Err(error) => {
607                    tracing::warn!("task inquiry record is unreadable: {error:#}");
608                    failed.get_or_insert(error);
609                    continue;
610                }
611            };
612            if inquiry.key.starts_with("question:")
613                && deferred
614                    .as_ref()
615                    .map_or(true, |ids| ids.contains(&inquiry.id))
616            {
617                continue;
618            }
619            if inquiry.archived
620                || inquiry
621                    .decision
622                    .as_ref()
623                    .is_some_and(|d| d.status == crate::task_decision::Status::Resolved)
624                || inquiry.task.is_empty()
625            {
626                continue;
627            }
628            if inquiry
629                .delivered_to
630                .as_ref()
631                .is_some_and(|id| talks.path_of(id).exists())
632            {
633                continue;
634            }
635            if let Err(error) = self.deliver(queue, talks, &inquiry.id) {
636                if let Ok(_lock) = self.lock(&inquiry.id)
637                    && let Ok(mut current) = self.get(&inquiry.id)
638                {
639                    let message = format!("{error:#}");
640                    if current.delivery_error.as_ref() != Some(&message) {
641                        current.delivery_error = Some(message);
642                        if let Err(error) = self.save(&current) {
643                            tracing::warn!("cannot persist inquiry delivery failure: {error:#}");
644                        }
645                    }
646                }
647                tracing::warn!("inquiry {} delivery failed: {error:#}", inquiry.id);
648                failed.get_or_insert(error);
649            }
650        }
651        failed.map_or(Ok(()), Err)
652    }
653}
654
655#[cfg(test)]
656mod tests {
657    use super::*;
658
659    #[cfg(unix)]
660    #[test]
661    fn execution_claim_releases_while_an_inherited_descriptor_remains_open() {
662        let home = tempfile::tempdir().unwrap();
663        let outbox = Outbox::at(home.path());
664        let claim = outbox.execution_claim("legacy-inquiry").unwrap();
665        // A fork shares this open file description until exec closes it.
666        let inherited = claim.0.try_clone().unwrap();
667        assert!(outbox.execution_claim("legacy-inquiry").is_err());
668        drop(claim);
669        let next = outbox.execution_claim("legacy-inquiry").unwrap();
670        drop(inherited);
671        assert!(outbox.execution_claim("legacy-inquiry").is_err());
672        drop(next);
673        assert!(outbox.execution_claim("legacy-inquiry").is_ok());
674    }
675    use crate::{
676        queue::{Source, Task},
677        task_decision::Status,
678    };
679
680    fn task() -> Task {
681        Task::new(
682            "work".into(),
683            "work".into(),
684            PathBuf::from("/repo"),
685            Source::Human,
686        )
687    }
688
689    #[test]
690    fn identity_uses_task_kind_and_generation_with_unambiguous_boundaries() {
691        assert_eq!(id_for("t", "k", "g"), id_for("t", "k", "g"));
692        assert_ne!(id_for("t", "k", "g"), id_for("u", "k", "g"));
693        assert_ne!(id_for("t", "k", "g"), id_for("t", "l", "g"));
694        assert_ne!(id_for("t", "k", "g"), id_for("t", "k", "h"));
695        assert_ne!(id_for("ab", "c", "d"), id_for("a", "bc", "d"));
696    }
697
698    #[test]
699    fn rewording_after_restart_preserves_content_receipts_and_all_decision_states() {
700        let dir = tempfile::tempdir().unwrap();
701        let mut task = task();
702        task.runs = vec!["run-a".into(), "run-b".into()];
703        let outbox = Outbox::at(dir.path());
704        let first = outbox
705            .file_for_occurrence(
706                &task,
707                Some("run-a".into()),
708                "implement".into(),
709                "first-inquiry",
710                "Original",
711                "Original detail",
712            )
713            .unwrap();
714        for status in [
715            Status::AwaitingOwner,
716            Status::Queued,
717            Status::InProgress,
718            Status::RetryNeeded,
719            Status::Resolved,
720        ] {
721            let mut saved = outbox.get(&first.id).unwrap();
722            saved.delivered_to = Some("chat-a".into());
723            let decision = saved.decision.as_mut().unwrap();
724            decision.status = status;
725            decision.request =
726                (status != Status::AwaitingOwner).then(|| "durable owner request".into());
727            decision.error = (status == Status::RetryNeeded).then(|| "uncertain effect".into());
728            outbox.save(&saved).unwrap();
729            let replay = Outbox::at(dir.path())
730                .file_for_occurrence(
731                    &task,
732                    Some("run-a".into()),
733                    "implement".into(),
734                    "first-inquiry",
735                    "Reworded",
736                    "Changed detail",
737                )
738                .unwrap();
739            assert_eq!(replay, saved);
740        }
741        let other_kind = outbox
742            .file_for_occurrence(
743                &task,
744                Some("run-a".into()),
745                "review".into(),
746                "first-inquiry",
747                "Original",
748                "Original detail",
749            )
750            .unwrap();
751        let other_run = outbox
752            .file_for_occurrence(
753                &task,
754                Some("run-b".into()),
755                "implement".into(),
756                "first-inquiry",
757                "Original",
758                "Original detail",
759            )
760            .unwrap();
761        assert_ne!(first.id, other_kind.id);
762        assert_ne!(first.id, other_run.id);
763        task.hold_manual(Some("new owner generation".into()));
764        let next = outbox
765            .file_for_occurrence(
766                &task,
767                Some("run-a".into()),
768                "implement".into(),
769                "first-inquiry",
770                "Original",
771                "Original detail",
772            )
773            .unwrap();
774        assert_ne!(first.id, next.id);
775        assert_eq!(next.decision.unwrap().status, Status::AwaitingOwner);
776        assert_eq!(outbox.list().unwrap().len(), 4);
777    }
778
779    #[test]
780    fn retained_content_ids_keep_links_and_lifecycle_when_reworded() {
781        let dir = tempfile::tempdir().unwrap();
782        let task = task();
783        let outbox = Outbox::at(dir.path());
784        let mut retained = outbox
785            .file_for_occurrence(
786                &task,
787                None,
788                "implement".into(),
789                "first-inquiry",
790                "Original",
791                "Original detail",
792            )
793            .unwrap();
794        std::fs::remove_file(outbox.path(&retained.id).unwrap()).unwrap();
795        // Both retained native formats used this namespace and content hashes.
796        retained.id = "task-retained-content-hash".into();
797        retained.key = format!("inquiry:{}", retained.id);
798        retained.delivered_to = Some("retained-chat".into());
799        retained
800            .decision
801            .as_mut()
802            .unwrap()
803            .settle("owner settled this occurrence")
804            .unwrap();
805        outbox.save(&retained).unwrap();
806        let replay = Outbox::at(dir.path())
807            .file_for_occurrence(
808                &task,
809                None,
810                "implement".into(),
811                "first-inquiry",
812                "Reworded",
813                "Changed detail",
814            )
815            .unwrap();
816        assert_eq!(replay, retained);
817        assert_eq!(outbox.list().unwrap().len(), 1);
818    }
819}