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 {
71    // Closing the retained file releases the lock on platforms without flock.
72    _file: File,
73}
74
75#[cfg(unix)]
76impl Drop for ExecutionClaim {
77    fn drop(&mut self) {
78        use std::os::fd::AsRawFd;
79        // SAFETY: this guard owns the live descriptor; LOCK_UN releases only
80        // this open file description's flock.
81        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
93/// Stable identity for one producer-assigned occurrence.
94fn 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    /// Open an outbox beneath an explicit state home.
115    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    /// Shared with legacy consumers: acquire before reading an executable reply
152    /// and retain through its effect and receipt. Nonblocking so a settlement
153    /// cannot wait for (and then hide) an operation currently in flight.
154    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    /// File one content-distinct inquiry. An unchanged producer replay retains
177    /// its receipt; independent inquiries need distinct occurrence identifiers.
178    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    /// File or replay an explicit producer occurrence independently of prose.
192    /// Use a new key for each separate inquiry, including identical wording.
193    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        // Adopt retained content-derived IDs without rewriting transcript links
219        // or effect receipts. Unknown generations can only carry forward active,
220        // unchanged intent; known generations also retain resolved history.
221        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    /// Read one delivery without consulting legacy question records.
283    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    /// Persist before delivery. Retries retain the original input and receipt.
293    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            // The original prose and decision lifecycle survive a producer replay.
321            // Identity is ownership plus occurrence, never the rephrased body.
322            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    /// Deliver under a per-inquiry lease, releasing the task lock before any
362    /// conversation operation. The transcript key repairs a lost final receipt.
363    pub fn deliver(&self, queue: &Queue, talks: &Talks, id: &str) -> Result<String> {
364        let _lock = self.lock(id)?;
365        let mut inquiry = self.get(id)?;
366        ensure!(
367            !inquiry.archived,
368            "passive inquiry history is not a delivery"
369        );
370        let (_, mut chat) =
371            crate::task_chat::destination_checked(queue, talks, &inquiry.task, |task| {
372                ensure!(
373                    same_repository(&task.repo, &inquiry.repo),
374                    "inquiry repository no longer matches its task"
375                );
376                ensure!(
377                    inquiry
378                        .run
379                        .as_ref()
380                        .is_none_or(|run| task.runs.contains(run)),
381                    "inquiry run is not owned by its task"
382                );
383                Ok(())
384            })?;
385        if let Some(delivered) = &inquiry.delivered_to {
386            ensure!(
387                delivered == &chat.id,
388                "delivered inquiry changed conversations"
389            );
390            if chat.notified.iter().any(|key| key == &inquiry.key) {
391                return Ok(delivered.clone());
392            }
393            // The saved conversation was removed/recreated after delivery.
394            // Restore the same inquiry key; no owner request is reconstructed.
395        }
396        talk::queue_semantic_notice(
397            &mut chat,
398            talks,
399            &inquiry.text,
400            &inquiry.key,
401            &|_| false,
402            (
403                None,
404                Some(
405                    inquiry
406                        .evidence
407                        .clone()
408                        .unwrap_or_else(|| format!("task-inquiry:{}", inquiry.id)),
409                ),
410            ),
411            crate::prompt::NoticeDisplay {
412                inquiry: Some(inquiry.id.clone()),
413                facts: inquiry.display.clone(),
414                output: None,
415                task: Some(inquiry.task.clone()),
416                run: inquiry.run.clone(),
417            },
418        )?;
419        inquiry.delivered_to = Some(chat.id.clone());
420        inquiry.delivery_error = None;
421        self.save(&inquiry)?;
422        Ok(chat.id)
423    }
424
425    fn records(&self) -> Result<Vec<Result<Inquiry>>> {
426        let entries = match std::fs::read_dir(&self.root) {
427            Ok(entries) => entries,
428            Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
429            Err(error) => return Err(error.into()),
430        };
431        let mut paths = Vec::new();
432        for entry in entries {
433            let path = entry?.path();
434            if path
435                .extension()
436                .is_some_and(|extension| extension == "json")
437            {
438                paths.push(path);
439            }
440        }
441        paths.sort();
442        Ok(paths
443            .into_iter()
444            .map(|path| {
445                let id = path
446                    .file_stem()
447                    .and_then(|stem| stem.to_str())
448                    .context("invalid inquiry filename")?;
449                self.get(id).with_context(|| format!("read inquiry {id}"))
450            })
451            .collect())
452    }
453
454    /// Stop compatibility/history delivery without manufacturing resolution.
455    pub(crate) fn suspend_delivery(&self, id: &str, reason: &str) -> Result<()> {
456        let _lock = self.lock(id)?;
457        let mut record = self.get(id)?;
458        if !record.archived || record.delivery_error.as_deref() != Some(reason) {
459            record.archived = true;
460            record.delivery_error = Some(reason.to_owned());
461            self.save(&record)?;
462        }
463        Ok(())
464    }
465
466    /// Read all durable inquiries, including completed decision history.
467    pub fn list(&self) -> Result<Vec<Inquiry>> {
468        self.records()?.into_iter().collect()
469    }
470
471    /// 一覧表示用の同一走査で、正常な記録と読めない記録の件数を返す。
472    /// 実行系の厳密な list / pending のエラー処理は変更しない。
473    pub fn list_readable(&self) -> Result<(Vec<Inquiry>, usize)> {
474        let mut items = Vec::new();
475        let mut unreadable = 0;
476        for record in self.records()? {
477            match record {
478                Ok(inquiry) => items.push(inquiry),
479                Err(error) => {
480                    tracing::warn!("task inquiry record is unreadable: {error:#}");
481                    unreadable += 1;
482                }
483            }
484        }
485        Ok((items, unreadable))
486    }
487
488    /// Change only the decision lifecycle under the same lease as delivery.
489    /// Returning false avoids rewriting a receipt on every scheduler lap.
490    pub fn update_decision(
491        &self,
492        id: &str,
493        change: impl FnOnce(&mut crate::task_decision::Decision) -> Result<bool>,
494    ) -> Result<()> {
495        let _lock = self.lock(id)?;
496        let mut inquiry = self.get(id)?;
497        let decision = inquiry
498            .decision
499            .as_mut()
500            .context("inquiry is informational")?;
501        if change(decision)? {
502            self.save(&inquiry)?;
503        }
504        Ok(())
505    }
506
507    /// Explicit settlement belongs to the owning task chat. Replacement must
508    /// already exist and have the same task/repository; it executes nothing.
509    /// Undelivered ownerless imports may be settled from any authorized chat
510    /// without assigning that chat or inventing a task association. Accepted
511    /// legacy choices support explicit owner confirmation of no remaining
512    /// effect; native command uncertainty still requires its receipt.
513    pub fn settle(
514        &self,
515        id: &str,
516        chat: &str,
517        reason: &str,
518        replacement: Option<&str>,
519    ) -> Result<()> {
520        ensure!(!reason.trim().is_empty(), "settlement reason is empty");
521        let _execution = self.execution_claim(id)?;
522        let mut ids = vec![id];
523        if let Some(replacement) = replacement {
524            ensure!(replacement != id, "decision cannot supersede itself");
525            ids.push(replacement);
526        }
527        ids.sort_unstable();
528        // Hold both records in a fixed order. Reciprocal supersessions cannot
529        // both observe an active replacement and erase the last pending intent.
530        let _locks: Vec<_> = ids
531            .into_iter()
532            .map(|id| self.lock(id))
533            .collect::<Result<_>>()?;
534        let mut current = self.get(id)?;
535        ensure!(
536            current.delivered_to.as_deref() == Some(chat)
537                || (current.task.is_empty()
538                    && current.delivered_to.is_none()
539                    && replacement.is_none()),
540            "decision belongs to another chat"
541        );
542        let reason = if let Some(replacement) = replacement {
543            ensure!(replacement != id, "decision cannot supersede itself");
544            let next = self.get(replacement)?;
545            ensure!(
546                next.task == current.task
547                    && next.repo == current.repo
548                    && next.delivered_to == current.delivered_to
549                    && next
550                        .decision
551                        .as_ref()
552                        .is_some_and(|d| d.status != crate::task_decision::Status::Resolved),
553                "replacement must be an active decision in the same task chat"
554            );
555            format!("superseded by {replacement}: {reason}")
556        } else {
557            format!("owner settled; no further effect remains: {reason}")
558        };
559        let decision = current
560            .decision
561            .as_mut()
562            .context("inquiry is informational")?;
563        let changed = if decision
564            .request
565            .as_deref()
566            .is_some_and(|r| r.starts_with("decision: "))
567        {
568            decision.settle_legacy(&format!(
569                "owner confirmed no remaining legacy effect: {reason}"
570            ))?
571        } else {
572            decision.settle(&reason)?
573        };
574        if changed {
575            self.save(&current)?;
576        }
577        Ok(())
578    }
579
580    /// Read pending deliveries. Corrupt records are errors, never silently skipped.
581    pub fn pending(&self) -> Result<Vec<Inquiry>> {
582        Ok(self
583            .records()?
584            .into_iter()
585            .collect::<Result<Vec<_>>>()?
586            .into_iter()
587            .filter(|inquiry| {
588                inquiry.delivered_to.is_none()
589                    && !inquiry.archived
590                    && inquiry.decision.as_ref().is_none_or(|decision| {
591                        decision.status != crate::task_decision::Status::Resolved
592                    })
593            })
594            .collect())
595    }
596
597    /// Resume durable deliveries after a scheduler restart without starting agents.
598    pub fn sweep(&self, queue: &Queue, talks: &Talks) -> Result<()> {
599        let home = self
600            .root
601            .parent()
602            .and_then(Path::parent)
603            .context("inquiry store has no home")?;
604        let deferred = crate::task_chat::migration_pending(home);
605        let mut failed = None;
606        for record in self.records()? {
607            let inquiry = match record {
608                Ok(inquiry) => inquiry,
609                Err(error) => {
610                    tracing::warn!("task inquiry record is unreadable: {error:#}");
611                    failed.get_or_insert(error);
612                    continue;
613                }
614            };
615            if inquiry.key.starts_with("question:")
616                && deferred
617                    .as_ref()
618                    .map_or(true, |ids| ids.contains(&inquiry.id))
619            {
620                continue;
621            }
622            if inquiry.archived
623                || inquiry
624                    .decision
625                    .as_ref()
626                    .is_some_and(|d| d.status == crate::task_decision::Status::Resolved)
627                || inquiry.task.is_empty()
628            {
629                continue;
630            }
631            if inquiry
632                .delivered_to
633                .as_ref()
634                .is_some_and(|id| talks.path_of(id).exists())
635            {
636                continue;
637            }
638            if let Err(error) = self.deliver(queue, talks, &inquiry.id) {
639                if let Ok(_lock) = self.lock(&inquiry.id)
640                    && let Ok(mut current) = self.get(&inquiry.id)
641                {
642                    let message = format!("{error:#}");
643                    if current.delivery_error.as_ref() != Some(&message) {
644                        current.delivery_error = Some(message);
645                        if let Err(error) = self.save(&current) {
646                            tracing::warn!("cannot persist inquiry delivery failure: {error:#}");
647                        }
648                    }
649                }
650                tracing::warn!("inquiry {} delivery failed: {error:#}", inquiry.id);
651                failed.get_or_insert(error);
652            }
653        }
654        failed.map_or(Ok(()), Err)
655    }
656}
657
658#[cfg(test)]
659mod tests {
660    use super::*;
661
662    #[cfg(unix)]
663    #[test]
664    fn execution_claim_releases_while_an_inherited_descriptor_remains_open() {
665        let home = tempfile::tempdir().unwrap();
666        let outbox = Outbox::at(home.path());
667        let claim = outbox.execution_claim("legacy-inquiry").unwrap();
668        // A fork shares this open file description until exec closes it.
669        let inherited = claim._file.try_clone().unwrap();
670        assert!(outbox.execution_claim("legacy-inquiry").is_err());
671        drop(claim);
672        let next = outbox.execution_claim("legacy-inquiry").unwrap();
673        drop(inherited);
674        assert!(outbox.execution_claim("legacy-inquiry").is_err());
675        drop(next);
676        assert!(outbox.execution_claim("legacy-inquiry").is_ok());
677    }
678    use crate::{
679        queue::{Source, Task},
680        task_decision::Status,
681    };
682
683    fn task() -> Task {
684        Task::new(
685            "work".into(),
686            "work".into(),
687            PathBuf::from("/repo"),
688            Source::Human,
689        )
690    }
691
692    #[test]
693    fn identity_uses_task_kind_and_generation_with_unambiguous_boundaries() {
694        assert_eq!(id_for("t", "k", "g"), id_for("t", "k", "g"));
695        assert_ne!(id_for("t", "k", "g"), id_for("u", "k", "g"));
696        assert_ne!(id_for("t", "k", "g"), id_for("t", "l", "g"));
697        assert_ne!(id_for("t", "k", "g"), id_for("t", "k", "h"));
698        assert_ne!(id_for("ab", "c", "d"), id_for("a", "bc", "d"));
699    }
700
701    #[test]
702    fn rewording_after_restart_preserves_content_receipts_and_all_decision_states() {
703        let dir = tempfile::tempdir().unwrap();
704        let mut task = task();
705        task.runs = vec!["run-a".into(), "run-b".into()];
706        let outbox = Outbox::at(dir.path());
707        let first = outbox
708            .file_for_occurrence(
709                &task,
710                Some("run-a".into()),
711                "implement".into(),
712                "first-inquiry",
713                "Original",
714                "Original detail",
715            )
716            .unwrap();
717        for status in [
718            Status::AwaitingOwner,
719            Status::Queued,
720            Status::InProgress,
721            Status::RetryNeeded,
722            Status::Resolved,
723        ] {
724            let mut saved = outbox.get(&first.id).unwrap();
725            saved.delivered_to = Some("chat-a".into());
726            let decision = saved.decision.as_mut().unwrap();
727            decision.status = status;
728            decision.request =
729                (status != Status::AwaitingOwner).then(|| "durable owner request".into());
730            decision.error = (status == Status::RetryNeeded).then(|| "uncertain effect".into());
731            outbox.save(&saved).unwrap();
732            let replay = Outbox::at(dir.path())
733                .file_for_occurrence(
734                    &task,
735                    Some("run-a".into()),
736                    "implement".into(),
737                    "first-inquiry",
738                    "Reworded",
739                    "Changed detail",
740                )
741                .unwrap();
742            assert_eq!(replay, saved);
743        }
744        let other_kind = outbox
745            .file_for_occurrence(
746                &task,
747                Some("run-a".into()),
748                "review".into(),
749                "first-inquiry",
750                "Original",
751                "Original detail",
752            )
753            .unwrap();
754        let other_run = outbox
755            .file_for_occurrence(
756                &task,
757                Some("run-b".into()),
758                "implement".into(),
759                "first-inquiry",
760                "Original",
761                "Original detail",
762            )
763            .unwrap();
764        assert_ne!(first.id, other_kind.id);
765        assert_ne!(first.id, other_run.id);
766        task.hold_manual(Some("new owner generation".into()));
767        let next = outbox
768            .file_for_occurrence(
769                &task,
770                Some("run-a".into()),
771                "implement".into(),
772                "first-inquiry",
773                "Original",
774                "Original detail",
775            )
776            .unwrap();
777        assert_ne!(first.id, next.id);
778        assert_eq!(next.decision.unwrap().status, Status::AwaitingOwner);
779        assert_eq!(outbox.list().unwrap().len(), 4);
780    }
781
782    #[test]
783    fn retained_content_ids_keep_links_and_lifecycle_when_reworded() {
784        let dir = tempfile::tempdir().unwrap();
785        let task = task();
786        let outbox = Outbox::at(dir.path());
787        let mut retained = outbox
788            .file_for_occurrence(
789                &task,
790                None,
791                "implement".into(),
792                "first-inquiry",
793                "Original",
794                "Original detail",
795            )
796            .unwrap();
797        std::fs::remove_file(outbox.path(&retained.id).unwrap()).unwrap();
798        // Both retained native formats used this namespace and content hashes.
799        retained.id = "task-retained-content-hash".into();
800        retained.key = format!("inquiry:{}", retained.id);
801        retained.delivered_to = Some("retained-chat".into());
802        retained
803            .decision
804            .as_mut()
805            .unwrap()
806            .settle("owner settled this occurrence")
807            .unwrap();
808        outbox.save(&retained).unwrap();
809        let replay = Outbox::at(dir.path())
810            .file_for_occurrence(
811                &task,
812                None,
813                "implement".into(),
814                "first-inquiry",
815                "Reworded",
816                "Changed detail",
817            )
818            .unwrap();
819        assert_eq!(replay, retained);
820        assert_eq!(outbox.list().unwrap().len(), 1);
821    }
822}