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