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