Skip to main content

paper/core/
answer.rs

1//! Extractive answering.
2//!
3//! Paper never invents text: an answer is always a verbatim quote from a local
4//! document plus the citation that proves it. Generative polish is an optional,
5//! separate step and is never required for a correct answer.
6
7use crate::core::search::{Confidence, Hit};
8use serde::Serialize;
9
10#[derive(Debug, Clone, Serialize)]
11pub struct Citation {
12    pub source_id: i64,
13    pub path: String,
14    pub page: i64,
15    pub line_start: i64,
16    pub line_end: i64,
17    /// Format-specific anchor, when the source has one.
18    #[serde(skip_serializing_if = "Option::is_none")]
19    pub anchor: Option<String>,
20    /// Heading path the quoted passage sits under.
21    #[serde(skip_serializing_if = "Option::is_none")]
22    pub section: Option<String>,
23    /// `path [anchor]:line_start-line_end`, or `path:line_start-line_end`.
24    pub reference: String,
25}
26
27#[derive(Debug, Clone, Serialize)]
28pub struct Answer {
29    pub question: String,
30    /// Verbatim extract supporting the answer.
31    pub text: String,
32    pub citations: Vec<Citation>,
33    /// True when nothing relevant was found locally.
34    pub not_found: bool,
35    /// Set when a generative engine rewrote the extract. Empty for local answers.
36    pub engine: String,
37}
38
39impl Citation {
40    pub fn from_hit(hit: &Hit) -> Self {
41        let mut reference = hit.path.clone();
42        if let Some(anchor) = &hit.anchor {
43            reference.push_str(&format!(" [{anchor}]"));
44        }
45        if hit.line_start > 0 {
46            reference.push_str(&format!(":{}-{}", hit.line_start, hit.line_end));
47        } else if hit.page > 0 {
48            reference.push_str(&format!(":p.{}", hit.page));
49        }
50        Self {
51            source_id: hit.source_id,
52            path: hit.path.clone(),
53            page: hit.page,
54            line_start: hit.line_start,
55            line_end: hit.line_end,
56            anchor: hit.anchor.clone(),
57            section: hit.section.clone(),
58            reference,
59        }
60    }
61}
62
63impl Answer {
64    /// Build an answer from ranked hits.
65    ///
66    /// Hits whose evidence is [`Confidence::Low`] are treated as no answer at
67    /// all: a plausible-looking quote from a weak match is worse than saying
68    /// "not found", because it makes the user trust a wrong citation.
69    pub fn from_hits(question: &str, hits: &[Hit]) -> Self {
70        let supported: Vec<&Hit> = hits
71            .iter()
72            .filter(|hit| !matches!(hit.confidence, Confidence::Low))
73            .collect();
74        match supported.first() {
75            None => Self {
76                question: question.to_string(),
77                text: String::new(),
78                citations: vec![],
79                not_found: true,
80                engine: "local".to_string(),
81            },
82            Some(top) => Self {
83                question: question.to_string(),
84                text: top.snippet.clone(),
85                citations: supported
86                    .iter()
87                    .take(3)
88                    .map(|h| Citation::from_hit(h))
89                    .collect(),
90                not_found: false,
91                engine: "local".to_string(),
92            },
93        }
94    }
95
96    /// Human-readable rendering used by the CLI.
97    pub fn render(&self) -> String {
98        if self.not_found {
99            return "No matching document found in the local index.".to_string();
100        }
101        let mut out = self.text.clone();
102        out.push_str("\n\nSources:\n");
103        for citation in &self.citations {
104            out.push_str(&format!("  - {}\n", citation.reference));
105        }
106        out
107    }
108}