Skip to main content

sqlite_graphrag/commands/
restore.rs

1//! Handler for the `restore` CLI subcommand.
2
3use crate::errors::AppError;
4use crate::i18n::errors_msg;
5use crate::output;
6use crate::output::JsonOutputFormat;
7use crate::paths::AppPaths;
8use crate::storage::connection::open_rw;
9use crate::storage::memories;
10use crate::storage::versions;
11use rusqlite::params;
12use rusqlite::OptionalExtension;
13use serde::Serialize;
14
15#[derive(clap::Args)]
16#[command(after_long_help = "EXAMPLES:\n  \
17    # Restore the latest non-`restore` version of a memory\n  \
18    sqlite-graphrag restore --name onboarding\n\n  \
19    # Restore a specific version\n  \
20    sqlite-graphrag restore --name onboarding --version 3\n\n  \
21    # Restore within a specific namespace\n  \
22    sqlite-graphrag restore --name onboarding --namespace my-project")]
23pub struct RestoreArgs {
24    /// Memory name as a positional argument. Alternative to `--name`.
25    #[arg(
26        value_name = "NAME",
27        conflicts_with = "name",
28        help = "Memory name to restore; alternative to --name"
29    )]
30    pub name_positional: Option<String>,
31    /// Memory name to restore (must exist, including soft-deleted/forgotten).
32    #[arg(long)]
33    pub name: Option<String>,
34    /// Version to restore. When omitted, defaults to the latest non-`restore` version
35    /// from `memory_versions`. This makes the forget+restore workflow work without
36    /// requiring the user to discover the version first.
37    #[arg(long)]
38    pub version: Option<i64>,
39    #[arg(
40        long,
41        help = "Namespace (env: SQLITE_GRAPHRAG_NAMESPACE, default: global)"
42    )]
43    pub namespace: Option<String>,
44    /// Optimistic locking: reject if the current updated_at does not match (exit 3).
45    #[arg(
46        long,
47        value_name = "EPOCH_OR_RFC3339",
48        value_parser = crate::parsers::parse_expected_updated_at,
49        long_help = "Optimistic lock: reject if updated_at does not match. \
50Accepts Unix epoch (e.g. 1700000000) or RFC 3339 (e.g. 2026-04-19T12:00:00Z)."
51    )]
52    pub expected_updated_at: Option<i64>,
53    /// Output format.
54    #[arg(long, value_enum, default_value_t = JsonOutputFormat::Json)]
55    pub format: JsonOutputFormat,
56    #[arg(long, hide = true, help = "No-op; JSON is always emitted on stdout")]
57    pub json: bool,
58    #[arg(long, env = "SQLITE_GRAPHRAG_DB_PATH")]
59    pub db: Option<String>,
60}
61
62#[derive(Serialize)]
63struct RestoreResponse {
64    /// Always `"restored"` — signals the completed action to shell callers and LLM agents.
65    action: String,
66    memory_id: i64,
67    name: String,
68    version: i64,
69    restored_from: i64,
70    /// Total execution time in milliseconds from handler start to serialisation.
71    elapsed_ms: u64,
72}
73
74pub fn run(args: RestoreArgs) -> Result<(), AppError> {
75    let start = std::time::Instant::now();
76    let _ = args.format;
77    tracing::debug!(target: "restore", name = ?args.name_positional.as_deref().or(args.name.as_deref()), version = ?args.version, "restoring version");
78    let name = args
79        .name_positional
80        .as_deref()
81        .or(args.name.as_deref())
82        .ok_or_else(|| {
83            AppError::Validation(
84                "name required: pass as positional argument or via --name".to_string(),
85            )
86        })?
87        .to_string();
88    let namespace = crate::namespace::resolve_namespace(args.namespace.as_deref())?;
89    let paths = AppPaths::resolve(args.db.as_deref())?;
90    let mut conn = open_rw(&paths.db)?;
91
92    // PRD line 1118: query WITHOUT a deleted_at filter — restore must work on soft-deleted memories
93    let result: Option<(i64, i64)> = conn
94        .query_row(
95            "SELECT id, updated_at FROM memories WHERE namespace = ?1 AND name = ?2",
96            params![namespace, name],
97            |r| Ok((r.get(0)?, r.get(1)?)),
98        )
99        .optional()?;
100    let (memory_id, current_updated_at) = result
101        .ok_or_else(|| AppError::NotFound(errors_msg::memory_not_found(&name, &namespace)))?;
102
103    if let Some(expected) = args.expected_updated_at {
104        if expected != current_updated_at {
105            return Err(AppError::Conflict(errors_msg::optimistic_lock_conflict(
106                expected,
107                current_updated_at,
108            )));
109        }
110    }
111
112    // v1.0.22 P0: resolve optional `--version`. When absent, uses the highest version
113    // whose `change_reason` is not 'restore' (recovers the real state, not meta-restore).
114    // Lets the forget+restore workflow function without manually reading memory_versions.
115    let target_version: i64 = match args.version {
116        Some(v) => v,
117        None => {
118            let last: Option<i64> = conn
119                .query_row(
120                    "SELECT MAX(version) FROM memory_versions
121                     WHERE memory_id = ?1 AND change_reason != 'restore'",
122                    params![memory_id],
123                    |r| r.get(0),
124                )
125                .optional()?
126                .flatten();
127            let v = last.ok_or_else(|| {
128                AppError::NotFound(errors_msg::memory_not_found(&name, &namespace))
129            })?;
130            tracing::info!(target: "restore",
131                "restore --version omitted; using latest non-restore version: {}",
132                v
133            );
134            v
135        }
136    };
137
138    let version_row: (String, String, String, String, String) = {
139        let mut stmt = conn.prepare_cached(
140            "SELECT name, type, description, body, metadata
141             FROM memory_versions
142             WHERE memory_id = ?1 AND version = ?2",
143        )?;
144
145        stmt.query_row(params![memory_id, target_version], |r| {
146            Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?))
147        })
148        .map_err(|_| AppError::NotFound(errors_msg::version_not_found(target_version, &name)))?
149    };
150
151    let (_old_name, old_type, old_description, old_body, old_metadata) = version_row;
152
153    // Read current FTS-indexed values before the UPDATE so sync_fts_after_update
154    // can issue the correct DELETE command for the external-content FTS5 table.
155    let (cur_name, cur_desc, cur_body): (String, String, String) = conn.query_row(
156        "SELECT name, description, body FROM memories WHERE id = ?1",
157        params![memory_id],
158        |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
159    )?;
160
161    // v1.0.21 P1-D: re-embed restored body to keep `vec_memories` synchronized
162    // with `memories`. Without this, semantic queries used the post-forget version
163    // vector, causing inconsistent recall (vec_memories=2 vs memories=3 after forget+restore).
164    output::emit_progress_i18n(
165        "Re-computing embedding for restored memory...",
166        crate::i18n::validation::runtime_pt::restore_recomputing_embedding(),
167    );
168    let embedding = crate::daemon::embed_passage_or_local(&paths.models, &old_body)?;
169    let snippet: String = old_body.chars().take(300).collect();
170
171    let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
172
173    // deleted_at = NULL reactivates soft-deleted memories; no deleted_at filter in the WHERE
174    let affected = if let Some(ts) = args.expected_updated_at {
175        tx.execute(
176            "UPDATE memories SET type=?2, description=?3, body=?4, body_hash=?5, deleted_at=NULL
177             WHERE id=?1 AND updated_at=?6",
178            rusqlite::params![
179                memory_id,
180                old_type,
181                old_description,
182                old_body,
183                blake3::hash(old_body.as_bytes()).to_hex().to_string(),
184                ts
185            ],
186        )?
187    } else {
188        tx.execute(
189            "UPDATE memories SET type=?2, description=?3, body=?4, body_hash=?5, deleted_at=NULL
190             WHERE id=?1",
191            rusqlite::params![
192                memory_id,
193                old_type,
194                old_description,
195                old_body,
196                blake3::hash(old_body.as_bytes()).to_hex().to_string()
197            ],
198        )?
199    };
200
201    if affected == 0 {
202        return Err(AppError::Conflict(errors_msg::concurrent_process_conflict()));
203    }
204
205    let next_v = versions::next_version(&tx, memory_id)?;
206
207    versions::insert_version(
208        &tx,
209        memory_id,
210        next_v,
211        &cur_name,
212        &old_type,
213        &old_description,
214        &old_body,
215        &old_metadata,
216        None,
217        "restore",
218    )?;
219
220    memories::upsert_vec(
221        &tx, memory_id, &namespace, &old_type, &embedding, &cur_name, &snippet,
222    )?;
223
224    memories::sync_fts_after_update(
225        &tx,
226        memory_id,
227        &cur_name,
228        &cur_desc,
229        &cur_body,
230        &cur_name,
231        &old_description,
232        &old_body,
233    )?;
234
235    tx.commit()?;
236
237    conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE);")?;
238
239    output::emit_json(&RestoreResponse {
240        action: "restored".to_string(),
241        memory_id,
242        name: cur_name.clone(),
243        version: next_v,
244        restored_from: target_version,
245        elapsed_ms: start.elapsed().as_millis() as u64,
246    })?;
247
248    Ok(())
249}
250
251#[cfg(test)]
252mod tests {
253    use crate::errors::AppError;
254
255    #[test]
256    fn optimistic_lock_conflict_returns_exit_3() {
257        let err = AppError::Conflict(
258            "optimistic lock conflict: expected updated_at=50, but current is 99".to_string(),
259        );
260        assert_eq!(err.exit_code(), 3);
261        assert!(err.to_string().contains("conflict"));
262    }
263
264    #[test]
265    fn restore_response_includes_action_field() {
266        let resp = super::RestoreResponse {
267            action: "restored".to_string(),
268            memory_id: 1,
269            name: "test-mem".to_string(),
270            version: 3,
271            restored_from: 2,
272            elapsed_ms: 42,
273        };
274        let json = serde_json::to_value(&resp).expect("serialization failed");
275        assert_eq!(json["action"], "restored");
276        assert_eq!(json["memory_id"], 1);
277        assert_eq!(json["version"], 3);
278        assert_eq!(json["restored_from"], 2);
279    }
280}