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/// Why a passive compatibility import no longer needs a decision.
63#[derive(Clone, Copy, PartialEq, Eq)]
64pub(crate) enum HistoryResolution {
65    Applied,
66    Retired,
67}
68
69/// File-backed outbox under the existing notifications write grant.
70#[derive(Debug, Clone)]
71pub struct Outbox {
72    root: PathBuf,
73}
74
75/// Release the execution fence even if a concurrent fork still retains a
76/// descriptor for the same open file description.
77pub(crate) struct ExecutionClaim {
78    // Closing the retained file releases the lock on platforms without flock.
79    _file: File,
80}
81
82#[cfg(unix)]
83impl Drop for ExecutionClaim {
84    fn drop(&mut self) {
85        use std::os::fd::AsRawFd;
86        // SAFETY: this guard owns the live descriptor; LOCK_UN releases only
87        // this open file description's flock.
88        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
100/// Stable identity for one producer-assigned occurrence.
101fn 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    /// Open an outbox beneath an explicit state home.
122    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    /// Shared with legacy consumers: acquire before reading an executable reply
159    /// and retain through its effect and receipt. Nonblocking so a settlement
160    /// cannot wait for (and then hide) an operation currently in flight.
161    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    /// File one content-distinct inquiry. An unchanged producer replay retains
184    /// its receipt; independent inquiries need distinct occurrence identifiers.
185    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    /// File or replay an explicit producer occurrence independently of prose.
199    /// Use a new key for each separate inquiry, including identical wording.
200    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        // Adopt retained content-derived IDs without rewriting transcript links
226        // or effect receipts. Unknown generations can only carry forward active,
227        // unchanged intent; known generations also retain resolved history.
228        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    /// Read one delivery without consulting legacy question records.
290    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    /// Persist before delivery. Retries retain the original input and receipt.
300    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            // The original prose and decision lifecycle survive a producer replay.
328            // Identity is ownership plus occurrence, never the rephrased body.
329            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    /// Correct only passive compatibility imports, under delivery and execution
369    /// fences. Accepted requests, explicit outcomes and delivered prose survive.
370    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        // Never replace a conversation already delivered. Updating lifecycle
411        // visibility does not acknowledge or redeliver its prose.
412        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    /// Deliver under a per-inquiry lease, releasing the task lock before any
437    /// conversation operation. The transcript key repairs a lost final receipt.
438    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            // The saved conversation was removed/recreated after delivery.
469            // Restore the same inquiry key; no owner request is reconstructed.
470        }
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                None,
486            ),
487            crate::prompt::NoticeDisplay {
488                inquiry: Some(inquiry.id.clone()),
489                facts: inquiry.display.clone(),
490                output: None,
491                task: Some(inquiry.task.clone()),
492                run: inquiry.run.clone(),
493            },
494        )?;
495        inquiry.delivered_to = Some(chat.id.clone());
496        inquiry.delivery_error = None;
497        self.save(&inquiry)?;
498        Ok(chat.id)
499    }
500
501    fn records(&self) -> Result<Vec<Result<Inquiry>>> {
502        let entries = match std::fs::read_dir(&self.root) {
503            Ok(entries) => entries,
504            Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
505            Err(error) => return Err(error.into()),
506        };
507        let mut paths = Vec::new();
508        for entry in entries {
509            let path = entry?.path();
510            if path
511                .extension()
512                .is_some_and(|extension| extension == "json")
513            {
514                paths.push(path);
515            }
516        }
517        paths.sort();
518        Ok(paths
519            .into_iter()
520            .map(|path| {
521                let id = path
522                    .file_stem()
523                    .and_then(|stem| stem.to_str())
524                    .context("invalid inquiry filename")?;
525                self.get(id).with_context(|| format!("read inquiry {id}"))
526            })
527            .collect())
528    }
529
530    /// Read all durable inquiries, including completed decision history.
531    pub fn list(&self) -> Result<Vec<Inquiry>> {
532        self.records()?.into_iter().collect()
533    }
534
535    /// 一覧表示用の同一走査で、正常な記録と読めない記録の件数を返す。
536    /// 実行系の厳密な list / pending のエラー処理は変更しない。
537    pub fn list_readable(&self) -> Result<(Vec<Inquiry>, usize)> {
538        let mut items = Vec::new();
539        let mut unreadable = 0;
540        for record in self.records()? {
541            match record {
542                Ok(inquiry) => items.push(inquiry),
543                Err(error) => {
544                    tracing::warn!("task inquiry record is unreadable: {error:#}");
545                    unreadable += 1;
546                }
547            }
548        }
549        Ok((items, unreadable))
550    }
551
552    /// Change only the decision lifecycle under the same lease as delivery.
553    /// Returning false avoids rewriting a receipt on every scheduler lap.
554    pub fn update_decision(
555        &self,
556        id: &str,
557        change: impl FnOnce(&mut crate::task_decision::Decision) -> Result<bool>,
558    ) -> Result<()> {
559        let _lock = self.lock(id)?;
560        let mut inquiry = self.get(id)?;
561        let decision = inquiry
562            .decision
563            .as_mut()
564            .context("inquiry is informational")?;
565        if change(decision)? {
566            self.save(&inquiry)?;
567        }
568        Ok(())
569    }
570
571    /// Explicit settlement belongs to the owning task chat. Replacement must
572    /// already exist and have the same task/repository; it executes nothing.
573    /// Undelivered ownerless imports may be settled from any authorized chat
574    /// without assigning that chat or inventing a task association. Accepted
575    /// legacy choices support explicit owner confirmation of no remaining
576    /// effect; native command uncertainty still requires its receipt.
577    pub fn settle(
578        &self,
579        id: &str,
580        chat: &str,
581        reason: &str,
582        replacement: Option<&str>,
583    ) -> Result<()> {
584        ensure!(!reason.trim().is_empty(), "settlement reason is empty");
585        let _execution = self.execution_claim(id)?;
586        let mut ids = vec![id];
587        if let Some(replacement) = replacement {
588            ensure!(replacement != id, "decision cannot supersede itself");
589            ids.push(replacement);
590        }
591        ids.sort_unstable();
592        // Hold both records in a fixed order. Reciprocal supersessions cannot
593        // both observe an active replacement and erase the last pending intent.
594        let _locks: Vec<_> = ids
595            .into_iter()
596            .map(|id| self.lock(id))
597            .collect::<Result<_>>()?;
598        let mut current = self.get(id)?;
599        ensure!(
600            current.delivered_to.as_deref() == Some(chat)
601                || (current.task.is_empty()
602                    && current.delivered_to.is_none()
603                    && replacement.is_none()),
604            "decision belongs to another chat"
605        );
606        let reason = if let Some(replacement) = replacement {
607            ensure!(replacement != id, "decision cannot supersede itself");
608            let next = self.get(replacement)?;
609            ensure!(
610                next.task == current.task
611                    && next.repo == current.repo
612                    && next.delivered_to == current.delivered_to
613                    && next
614                        .decision
615                        .as_ref()
616                        .is_some_and(|d| d.status != crate::task_decision::Status::Resolved),
617                "replacement must be an active decision in the same task chat"
618            );
619            format!("superseded by {replacement}: {reason}")
620        } else {
621            format!("owner settled; no further effect remains: {reason}")
622        };
623        let decision = current
624            .decision
625            .as_mut()
626            .context("inquiry is informational")?;
627        let changed = if decision
628            .request
629            .as_deref()
630            .is_some_and(|r| r.starts_with("decision: "))
631        {
632            decision.settle_legacy(&format!(
633                "owner confirmed no remaining legacy effect: {reason}"
634            ))?
635        } else {
636            decision.settle(&reason)?
637        };
638        if changed {
639            self.save(&current)?;
640        }
641        Ok(())
642    }
643
644    /// Read pending deliveries. Corrupt records are errors, never silently skipped.
645    pub fn pending(&self) -> Result<Vec<Inquiry>> {
646        Ok(self
647            .records()?
648            .into_iter()
649            .collect::<Result<Vec<_>>>()?
650            .into_iter()
651            .filter(|inquiry| {
652                inquiry.delivered_to.is_none()
653                    && !inquiry.archived
654                    && inquiry.decision.as_ref().is_none_or(|decision| {
655                        decision.status != crate::task_decision::Status::Resolved
656                    })
657            })
658            .collect())
659    }
660
661    /// Resume durable deliveries after a scheduler restart without starting agents.
662    pub fn sweep(&self, queue: &Queue, talks: &Talks) -> Result<()> {
663        let home = self
664            .root
665            .parent()
666            .and_then(Path::parent)
667            .context("inquiry store has no home")?;
668        let deferred = crate::task_chat::migration_pending(home);
669        let mut failed = None;
670        for record in self.records()? {
671            let inquiry = match record {
672                Ok(inquiry) => inquiry,
673                Err(error) => {
674                    tracing::warn!("task inquiry record is unreadable: {error:#}");
675                    failed.get_or_insert(error);
676                    continue;
677                }
678            };
679            if inquiry.key.starts_with("question:")
680                && deferred
681                    .as_ref()
682                    .map_or(true, |ids| ids.contains(&inquiry.id))
683            {
684                continue;
685            }
686            if inquiry.archived
687                || inquiry
688                    .decision
689                    .as_ref()
690                    .is_some_and(|d| d.status == crate::task_decision::Status::Resolved)
691                || inquiry.task.is_empty()
692            {
693                continue;
694            }
695            if inquiry
696                .delivered_to
697                .as_ref()
698                .is_some_and(|id| talks.path_of(id).exists())
699            {
700                continue;
701            }
702            if let Err(error) = self.deliver(queue, talks, &inquiry.id) {
703                if let Ok(_lock) = self.lock(&inquiry.id)
704                    && let Ok(mut current) = self.get(&inquiry.id)
705                {
706                    let message = format!("{error:#}");
707                    if current.delivery_error.as_ref() != Some(&message) {
708                        current.delivery_error = Some(message);
709                        if let Err(error) = self.save(&current) {
710                            tracing::warn!("cannot persist inquiry delivery failure: {error:#}");
711                        }
712                    }
713                }
714                tracing::warn!("inquiry {} delivery failed: {error:#}", inquiry.id);
715                failed.get_or_insert(error);
716            }
717        }
718        failed.map_or(Ok(()), Err)
719    }
720}
721
722#[cfg(test)]
723mod tests {
724    use super::*;
725
726    #[cfg(unix)]
727    #[test]
728    fn execution_claim_releases_while_an_inherited_descriptor_remains_open() {
729        let home = tempfile::tempdir().unwrap();
730        let outbox = Outbox::at(home.path());
731        let claim = outbox.execution_claim("legacy-inquiry").unwrap();
732        // A fork shares this open file description until exec closes it.
733        let inherited = claim._file.try_clone().unwrap();
734        assert!(outbox.execution_claim("legacy-inquiry").is_err());
735        drop(claim);
736        let next = outbox.execution_claim("legacy-inquiry").unwrap();
737        drop(inherited);
738        assert!(outbox.execution_claim("legacy-inquiry").is_err());
739        drop(next);
740        assert!(outbox.execution_claim("legacy-inquiry").is_ok());
741    }
742    use crate::{
743        queue::{Source, Task},
744        task_decision::Status,
745    };
746
747    fn task() -> Task {
748        Task::new(
749            "work".into(),
750            "work".into(),
751            PathBuf::from("/repo"),
752            Source::Human,
753        )
754    }
755
756    #[test]
757    fn identity_uses_task_kind_and_generation_with_unambiguous_boundaries() {
758        assert_eq!(id_for("t", "k", "g"), id_for("t", "k", "g"));
759        assert_ne!(id_for("t", "k", "g"), id_for("u", "k", "g"));
760        assert_ne!(id_for("t", "k", "g"), id_for("t", "l", "g"));
761        assert_ne!(id_for("t", "k", "g"), id_for("t", "k", "h"));
762        assert_ne!(id_for("ab", "c", "d"), id_for("a", "bc", "d"));
763    }
764
765    #[test]
766    fn rewording_after_restart_preserves_content_receipts_and_all_decision_states() {
767        let dir = tempfile::tempdir().unwrap();
768        let mut task = task();
769        task.runs = vec!["run-a".into(), "run-b".into()];
770        let outbox = Outbox::at(dir.path());
771        let first = outbox
772            .file_for_occurrence(
773                &task,
774                Some("run-a".into()),
775                "implement".into(),
776                "first-inquiry",
777                "Original",
778                "Original detail",
779            )
780            .unwrap();
781        for status in [
782            Status::AwaitingOwner,
783            Status::Queued,
784            Status::InProgress,
785            Status::RetryNeeded,
786            Status::Resolved,
787        ] {
788            let mut saved = outbox.get(&first.id).unwrap();
789            saved.delivered_to = Some("chat-a".into());
790            let decision = saved.decision.as_mut().unwrap();
791            decision.status = status;
792            decision.request =
793                (status != Status::AwaitingOwner).then(|| "durable owner request".into());
794            decision.error = (status == Status::RetryNeeded).then(|| "uncertain effect".into());
795            outbox.save(&saved).unwrap();
796            let replay = Outbox::at(dir.path())
797                .file_for_occurrence(
798                    &task,
799                    Some("run-a".into()),
800                    "implement".into(),
801                    "first-inquiry",
802                    "Reworded",
803                    "Changed detail",
804                )
805                .unwrap();
806            assert_eq!(replay, saved);
807        }
808        let other_kind = outbox
809            .file_for_occurrence(
810                &task,
811                Some("run-a".into()),
812                "review".into(),
813                "first-inquiry",
814                "Original",
815                "Original detail",
816            )
817            .unwrap();
818        let other_run = outbox
819            .file_for_occurrence(
820                &task,
821                Some("run-b".into()),
822                "implement".into(),
823                "first-inquiry",
824                "Original",
825                "Original detail",
826            )
827            .unwrap();
828        assert_ne!(first.id, other_kind.id);
829        assert_ne!(first.id, other_run.id);
830        task.hold_manual(Some("new owner generation".into()));
831        let next = outbox
832            .file_for_occurrence(
833                &task,
834                Some("run-a".into()),
835                "implement".into(),
836                "first-inquiry",
837                "Original",
838                "Original detail",
839            )
840            .unwrap();
841        assert_ne!(first.id, next.id);
842        assert_eq!(next.decision.unwrap().status, Status::AwaitingOwner);
843        assert_eq!(outbox.list().unwrap().len(), 4);
844    }
845
846    #[test]
847    fn retained_content_ids_keep_links_and_lifecycle_when_reworded() {
848        let dir = tempfile::tempdir().unwrap();
849        let task = task();
850        let outbox = Outbox::at(dir.path());
851        let mut retained = outbox
852            .file_for_occurrence(
853                &task,
854                None,
855                "implement".into(),
856                "first-inquiry",
857                "Original",
858                "Original detail",
859            )
860            .unwrap();
861        std::fs::remove_file(outbox.path(&retained.id).unwrap()).unwrap();
862        // Both retained native formats used this namespace and content hashes.
863        retained.id = "task-retained-content-hash".into();
864        retained.key = format!("inquiry:{}", retained.id);
865        retained.delivered_to = Some("retained-chat".into());
866        retained
867            .decision
868            .as_mut()
869            .unwrap()
870            .settle("owner settled this occurrence")
871            .unwrap();
872        outbox.save(&retained).unwrap();
873        let replay = Outbox::at(dir.path())
874            .file_for_occurrence(
875                &task,
876                None,
877                "implement".into(),
878                "first-inquiry",
879                "Reworded",
880                "Changed detail",
881            )
882            .unwrap();
883        assert_eq!(replay, retained);
884        assert_eq!(outbox.list().unwrap().len(), 1);
885    }
886}