Skip to main content

sqlite_graphrag/commands/
history.rs

1//! Handler for the `history` CLI subcommand.
2
3use crate::errors::AppError;
4use crate::i18n::errors_msg;
5use crate::output;
6use crate::paths::AppPaths;
7use crate::storage::connection::open_ro;
8use rusqlite::params;
9use rusqlite::OptionalExtension;
10use serde::Serialize;
11
12#[derive(clap::Args)]
13#[command(after_long_help = "EXAMPLES:\n  \
14    # List all versions of a memory (positional form)\n  \
15    sqlite-graphrag history onboarding\n\n  \
16    # List versions using the named flag form\n  \
17    sqlite-graphrag history --name onboarding\n\n  \
18    # Omit body content to reduce response size\n  \
19    sqlite-graphrag history onboarding --no-body\n\n  \
20    # Include character-level change summary between versions\n  \
21    sqlite-graphrag history onboarding --diff\n\n\
22DIFF OUTPUT:\n  \
23    When --diff is active, each version (except the first) includes a `changes`\n  \
24    object with `added_chars` and `removed_chars` — the character count difference\n  \
25    between that version and its predecessor.")]
26/// History args.
27pub struct HistoryArgs {
28    /// Memory name as a positional argument. Alternative to `--name`.
29    #[arg(
30        value_name = "NAME",
31        conflicts_with = "name",
32        help = "Memory name whose version history to return; alternative to --name"
33    )]
34    pub name_positional: Option<String>,
35    /// Memory name whose version history will be returned. Includes soft-deleted memories
36    /// so that `restore --version <V>` workflow remains discoverable after `forget`.
37    #[arg(long)]
38    pub name: Option<String>,
39    #[arg(
40        long,
41        help = "Namespace (flag / XDG namespace.default / global)"
42    )]
43    /// Namespace scope.
44    pub namespace: Option<String>,
45    /// Omit body content from each version to reduce response size.
46    #[arg(
47        long,
48        default_value_t = false,
49        help = "Omit body content from response"
50    )]
51    pub no_body: bool,
52    /// Include character-level change summary between consecutive versions.
53    #[arg(
54        long,
55        default_value_t = false,
56        help = "Include character-level change summary between consecutive versions"
57    )]
58    pub diff: bool,
59    /// Emit machine-readable JSON on stdout.
60    #[arg(long, hide = true, help = "No-op; JSON is always emitted on stdout")]
61    pub json: bool,
62    /// Path to graphrag.sqlite. Overrides the XDG `db.path` setting.
63    #[arg(
64        long,
65                help = "Path to graphrag.sqlite"
66    )]
67    pub db: Option<String>,
68}
69
70/// Character-level change summary between two consecutive versions.
71#[derive(Serialize)]
72struct VersionChanges {
73    added_chars: usize,
74    removed_chars: usize,
75}
76
77#[derive(Serialize)]
78struct HistoryVersion {
79    version: i64,
80    name: String,
81    #[serde(rename = "type")]
82    memory_type: String,
83    description: String,
84    #[serde(skip_serializing_if = "Option::is_none")]
85    body: Option<String>,
86    metadata: serde_json::Value,
87    /// Past-tense action label derived from `change_reason`; always populated
88    /// so consumers do not see `null` for the documented `action` contract
89    /// (M-A6 fix in v1.0.40). Known mappings: `create→created`, `edit→edited`,
90    /// `rename→renamed`, `restore→restored`, `merge→merged`, `forget→forgotten`.
91    /// Unknown verbs are passed through unchanged.
92    action: String,
93    change_reason: String,
94    changed_by: Option<String>,
95    created_at: i64,
96    created_at_iso: String,
97    #[serde(skip_serializing_if = "Option::is_none")]
98    pub changes: Option<VersionChanges>,
99}
100
101/// Maps the raw `change_reason` stored in `memory_versions` to the past-tense
102/// `action` exposed in the JSON contract. Centralized so future call sites
103/// (e.g. `read --include-history`) reuse the same mapping.
104fn change_reason_to_action(reason: &str) -> String {
105    match reason {
106        "create" => "created",
107        "edit" => "edited",
108        "update" => "updated",
109        "rename" => "renamed",
110        "restore" => "restored",
111        "merge" => "merged",
112        "forget" => "forgotten",
113        other => other,
114    }
115    .to_string()
116}
117
118#[derive(Serialize)]
119struct HistoryResponse {
120    name: String,
121    namespace: String,
122    /// True when the memory is currently soft-deleted (forgotten).
123    /// Allows the user to discover the version for `restore` even after `forget`.
124    deleted: bool,
125    versions: Vec<HistoryVersion>,
126    /// Total execution time in milliseconds from handler start to serialisation.
127    elapsed_ms: u64,
128}
129
130/// Run.
131pub fn run(args: HistoryArgs) -> Result<(), AppError> {
132    let start = std::time::Instant::now();
133    // Resolve name from positional or --name flag; both are optional, at least one is required.
134    let name = args.name_positional.or(args.name).ok_or_else(|| {
135        AppError::Validation(crate::i18n::validation::name_required_positional_or_flag())
136    })?;
137    let namespace = crate::namespace::resolve_namespace(args.namespace.as_deref())?;
138    let paths = AppPaths::resolve(args.db.as_deref())?;
139    crate::storage::connection::ensure_db_ready(&paths)?;
140    let conn = open_ro(&paths.db)?;
141
142    // v1.0.22 P0: direct query WITHOUT deleted_at filter — history MUST return versions
143    // of forgotten memories so the user can discover the version to use in `restore`.
144    // The old find_by_name filtered deleted_at IS NULL and was a dead-end in the forget+restore workflow.
145    let row: Option<(i64, Option<i64>)> = conn
146        .query_row(
147            "SELECT id, deleted_at FROM memories WHERE namespace = ?1 AND name = ?2",
148            params![namespace, name],
149            |r| Ok((r.get(0)?, r.get(1)?)),
150        )
151        .optional()?;
152    let (memory_id, deleted_at) =
153        row.ok_or_else(|| AppError::NotFound(errors_msg::memory_not_found(&name, &namespace)))?;
154    let deleted = deleted_at.is_some();
155
156    let mut stmt = conn.prepare_cached(
157        "SELECT version, name, type, description, body, metadata,
158                change_reason, changed_by, created_at
159         FROM memory_versions
160         WHERE memory_id = ?1
161         ORDER BY version ASC",
162    )?;
163
164    let no_body = args.no_body;
165    let want_diff = args.diff;
166    let mut versions = stmt
167        .query_map(params![memory_id], |r| {
168            let created_at: i64 = r.get(8)?;
169            let created_at_iso = crate::tz::epoch_to_iso(created_at);
170            let body_str: String = r.get(4)?;
171            let metadata_str: String = r.get(5)?;
172            let metadata_value: serde_json::Value = serde_json::from_str(&metadata_str)
173                .unwrap_or(serde_json::Value::Object(serde_json::Map::new()));
174            let change_reason: String = r.get(6)?;
175            let action = change_reason_to_action(&change_reason);
176            Ok(HistoryVersion {
177                version: r.get(0)?,
178                name: r.get(1)?,
179                memory_type: r.get(2)?,
180                description: r.get(3)?,
181                body: if no_body { None } else { Some(body_str) },
182                metadata: metadata_value,
183                action,
184                change_reason,
185                changed_by: r.get(7)?,
186                created_at,
187                created_at_iso,
188                changes: None,
189            })
190        })?
191        .collect::<Result<Vec<_>, _>>()?;
192
193    if want_diff && !versions.is_empty() {
194        let body_lens: Vec<usize> = versions
195            .iter()
196            .map(|v| v.body.as_deref().map_or(0, str::len))
197            .collect();
198
199        versions[0].changes = Some(VersionChanges {
200            added_chars: body_lens[0],
201            removed_chars: 0,
202        });
203
204        for i in 1..versions.len() {
205            let old_len = body_lens[i - 1];
206            let new_len = body_lens[i];
207            versions[i].changes = Some(VersionChanges {
208                added_chars: new_len.saturating_sub(old_len),
209                removed_chars: old_len.saturating_sub(new_len),
210            });
211        }
212    }
213
214    output::emit_json(&HistoryResponse {
215        name,
216        namespace,
217        deleted,
218        versions,
219        elapsed_ms: start.elapsed().as_millis() as u64,
220    })?;
221
222    Ok(())
223}
224
225#[cfg(test)]
226mod tests {
227    use super::{change_reason_to_action, VersionChanges};
228
229    // Bug M-A6: action is always populated and maps known reasons to past tense.
230    #[test]
231    fn version_changes_serializes_correctly() {
232        let changes = VersionChanges {
233            added_chars: 10,
234            removed_chars: 3,
235        };
236        let json = serde_json::to_value(&changes).expect("serialization failed");
237        assert_eq!(json["added_chars"], 10u64);
238        assert_eq!(json["removed_chars"], 3u64);
239    }
240
241    #[test]
242    fn added_chars_saturating_sub_no_underflow() {
243        // new body shorter than old — added_chars must be 0, not wrapping
244        let old_len: usize = 100;
245        let new_len: usize = 40;
246        let added = new_len.saturating_sub(old_len);
247        let removed = old_len.saturating_sub(new_len);
248        assert_eq!(added, 0);
249        assert_eq!(removed, 60);
250    }
251
252    #[test]
253    fn removed_chars_saturating_sub_no_underflow() {
254        // new body longer than old — removed_chars must be 0
255        let old_len: usize = 20;
256        let new_len: usize = 80;
257        let added = new_len.saturating_sub(old_len);
258        let removed = old_len.saturating_sub(new_len);
259        assert_eq!(added, 60);
260        assert_eq!(removed, 0);
261    }
262
263    #[test]
264    fn change_reason_create_maps_to_created() {
265        assert_eq!(change_reason_to_action("create"), "created");
266    }
267
268    #[test]
269    fn change_reason_edit_maps_to_edited() {
270        assert_eq!(change_reason_to_action("edit"), "edited");
271    }
272
273    #[test]
274    fn change_reason_rename_maps_to_renamed() {
275        assert_eq!(change_reason_to_action("rename"), "renamed");
276    }
277
278    #[test]
279    fn change_reason_restore_maps_to_restored() {
280        assert_eq!(change_reason_to_action("restore"), "restored");
281    }
282
283    #[test]
284    fn change_reason_merge_maps_to_merged() {
285        assert_eq!(change_reason_to_action("merge"), "merged");
286    }
287
288    #[test]
289    fn change_reason_forget_maps_to_forgotten() {
290        assert_eq!(change_reason_to_action("forget"), "forgotten");
291    }
292
293    #[test]
294    fn change_reason_unknown_passes_through() {
295        assert_eq!(change_reason_to_action("custom-action"), "custom-action");
296    }
297
298    #[test]
299    fn epoch_zero_yields_valid_iso() {
300        // v1.0.68 (test fix): timezone-agnostic — parse the ISO and compare
301        // the instant with the Unix epoch.  The previous starts_with check
302        // leaked the SQLITE_GRAPHRAG_DISPLAY_TZ env var from sibling tests
303        // and failed on hosts whose default display timezone is not UTC.
304        let iso = crate::tz::epoch_to_iso(0);
305        let parsed = chrono::DateTime::parse_from_rfc3339(&iso)
306            .unwrap_or_else(|e| panic!("expected RFC3339, got `{iso}`: {e}"));
307        assert_eq!(
308            parsed.timestamp(),
309            chrono::DateTime::UNIX_EPOCH.timestamp(),
310            "epoch 0 must map to the Unix epoch instant, got: {iso}"
311        );
312    }
313
314    #[test]
315    fn typical_epoch_yields_iso_rfc3339() {
316        let iso = crate::tz::epoch_to_iso(1_745_000_000);
317        assert!(!iso.is_empty(), "created_at_iso must not be empty");
318        assert!(iso.contains('T'), "created_at_iso must contain T separator");
319        // With UTC the offset is +00:00; verifies general format without relying on the global tz
320        assert!(
321            iso.contains('+') || iso.contains('-'),
322            "must contain offset sign, got: {iso}"
323        );
324    }
325
326    #[test]
327    fn invalid_epoch_returns_fallback() {
328        let iso = crate::tz::epoch_to_iso(i64::MIN);
329        assert!(
330            !iso.is_empty(),
331            "invalid epoch must return non-empty fallback"
332        );
333    }
334}