Skip to main content

sqlite_graphrag/commands/
edit.rs

1//! Handler for the `edit` CLI subcommand.
2
3use crate::errors::AppError;
4use crate::i18n::errors_msg;
5use crate::output;
6use crate::paths::AppPaths;
7use crate::storage::connection::open_rw;
8use crate::storage::{memories, versions};
9use serde::Serialize;
10
11#[derive(clap::Args)]
12#[command(after_long_help = "EXAMPLES:\n  \
13    # Edit body inline\n  \
14    sqlite-graphrag edit onboarding --body \"updated content\"\n\n  \
15    # Edit body from a file\n  \
16    sqlite-graphrag edit onboarding --body-file ./updated.md\n\n  \
17    # Edit body from stdin (pipe)\n  \
18    cat updated.md | sqlite-graphrag edit onboarding --body-stdin\n\n  \
19    # Update only the description\n  \
20    sqlite-graphrag edit onboarding --description \"new short description\"")]
21/// Edit args.
22pub struct EditArgs {
23    /// Memory name as a positional argument. Alternative to `--name`.
24    #[arg(
25        value_name = "NAME",
26        conflicts_with = "name",
27        help = "Memory name to edit; alternative to --name"
28    )]
29    pub name_positional: Option<String>,
30    /// Memory name to edit. Soft-deleted memories are not editable; use `restore` first.
31    #[arg(long)]
32    pub name: Option<String>,
33    /// New inline body content. Mutually exclusive with --body-file and --body-stdin.
34    #[arg(long, conflicts_with_all = ["body_file", "body_stdin"])]
35    pub body: Option<String>,
36    /// Read new body from a file. Mutually exclusive with --body and --body-stdin.
37    #[arg(long, conflicts_with_all = ["body", "body_stdin"])]
38    pub body_file: Option<std::path::PathBuf>,
39    /// Read new body from stdin until EOF. Mutually exclusive with --body and --body-file.
40    #[arg(long, conflicts_with_all = ["body", "body_file"])]
41    pub body_stdin: bool,
42    /// New description (≤500 chars) replacing the existing one.
43    #[arg(long)]
44    pub description: Option<String>,
45    /// Change the memory type (e.g. note, skill, decision).
46    #[arg(long, value_enum, visible_alias = "type", help = "Change memory type")]
47    pub memory_type: Option<crate::cli::MemoryType>,
48    #[arg(
49        long,
50        value_name = "EPOCH_OR_RFC3339",
51        value_parser = crate::parsers::parse_expected_updated_at,
52        long_help = "Optimistic lock: reject if updated_at does not match. \
53Accepts Unix epoch (e.g. 1700000000) or RFC 3339 (e.g. 2026-04-19T12:00:00Z)."
54    )]
55    /// Expected updated at.
56    pub expected_updated_at: Option<i64>,
57    #[arg(long, help = "Namespace (flag / XDG namespace.default / global)")]
58    /// Namespace scope.
59    pub namespace: Option<String>,
60    /// Emit machine-readable JSON on stdout.
61    #[arg(long, hide = true, help = "No-op; JSON is always emitted on stdout")]
62    pub json: bool,
63    /// Path to the SQLite database file.
64    #[arg(long)]
65    pub db: Option<String>,
66    /// G42/S9 (v1.0.79): regenerate the embedding even when the body is
67    /// unchanged. This is the supported way to re-embed a memory (the
68    /// pre-v1.0.79 docs suggested `edit --description "<same>"`, which
69    /// is a no-op and never re-embeds).
70    #[arg(
71        long,
72        default_value_t = false,
73        help = "Regenerate the embedding even when the body is unchanged (G42/S9)"
74    )]
75    pub force_reembed: bool,
76    /// G42/S3 (v1.0.79): maximum simultaneous LLM embedding subprocesses.
77    /// Only relevant for future multi-item edit paths; a single-body edit
78    /// performs one LLM call regardless.
79    #[arg(long, default_value_t = 4, value_name = "N",
80          value_parser = clap::value_parser!(u64).range(1..=32),
81          help = "Maximum simultaneous LLM embedding subprocesses (default: 4, clamp [1,32])")]
82    pub llm_parallelism: u64,
83}
84
85#[derive(Serialize)]
86struct EditResponse {
87    memory_id: i64,
88    name: String,
89    action: String,
90    version: i64,
91    /// Total execution time in milliseconds from handler start to serialisation.
92    elapsed_ms: u64,
93    /// v1.0.84 (ADR-0042): discriminator of the embedding backend that actually
94    /// ran the re-embedding of the edited body. `"openrouter" | "none"`.
95    /// Absent on the wire when `None` (kept for happy-path envelope cleanliness,
96    /// or when the body did not change and re-embedding was not invoked).
97    #[serde(skip_serializing_if = "Option::is_none")]
98    backend_invoked: Option<&'static str>,
99}
100
101/// Run.
102pub fn run(args: EditArgs, backends: crate::cli::BackendChoice) -> Result<(), AppError> {
103    use crate::constants::*;
104
105    let started = std::time::Instant::now();
106    tracing::debug!(target: "edit", name = ?args.name_positional.as_deref().or(args.name.as_deref()), "updating memory");
107    // Resolve name from positional or --name flag; both are optional, at least one is required.
108    let name = args.name_positional.or(args.name).ok_or_else(|| {
109        AppError::Validation(crate::i18n::validation::name_required_positional_or_flag())
110    })?;
111    let namespace = crate::namespace::resolve_namespace(args.namespace.as_deref())?;
112
113    let paths = AppPaths::resolve(args.db.as_deref())?;
114    crate::storage::connection::ensure_db_ready(&paths)?;
115    let mut conn = open_rw(&paths.db)?;
116
117    let (memory_id, current_updated_at, _current_version) =
118        memories::find_by_name(&conn, &namespace, &name)?
119            .ok_or_else(|| AppError::NotFound(errors_msg::memory_not_found(&name, &namespace)))?;
120
121    if let Some(expected) = args.expected_updated_at {
122        if expected != current_updated_at {
123            return Err(AppError::Conflict(errors_msg::optimistic_lock_conflict(
124                expected,
125                current_updated_at,
126            )));
127        }
128    }
129
130    let mut raw_body: Option<String> = None;
131    if args.body.is_some() || args.body_file.is_some() || args.body_stdin {
132        let b = if let Some(b) = args.body {
133            b
134        } else if let Some(path) = &args.body_file {
135            let file_size = std::fs::metadata(path).map_err(AppError::Io)?.len();
136            if file_size > MAX_MEMORY_BODY_LEN as u64 {
137                return Err(AppError::BodyTooLarge {
138                    bytes: file_size,
139                    limit: MAX_MEMORY_BODY_LEN as u64,
140                });
141            }
142            std::fs::read_to_string(path).map_err(AppError::Io)?
143        } else {
144            crate::stdin_helper::read_stdin()?
145        };
146        // v1.1.2 (Gap 2): boundary validation of BOTH payload ceilings —
147        // bytes (BodyTooLarge) and estimated tokens (TooManyTokens), exit 6.
148        crate::memory_guard::check_embedding_input_size(&b)?;
149        raw_body = Some(b);
150    }
151
152    if let Some(ref desc) = args.description {
153        if desc.len() > MAX_MEMORY_DESCRIPTION_LEN {
154            return Err(AppError::Validation(
155                crate::i18n::validation::description_exceeds(MAX_MEMORY_DESCRIPTION_LEN),
156            ));
157        }
158    }
159
160    let row = memories::read_by_name(&conn, &namespace, &name)?
161        .ok_or_else(|| AppError::Internal(anyhow::anyhow!("memory row not found after check")))?;
162
163    let body_changed = raw_body.is_some();
164    let new_body = raw_body.unwrap_or(row.body.clone());
165    let new_description = args.description.unwrap_or(row.description.clone());
166    let new_hash = blake3::hash(new_body.as_bytes()).to_hex().to_string();
167    // Skip re-embedding when body content is identical to the stored version.
168    let body_changed = body_changed && new_hash != row.body_hash;
169    let memory_type = args
170        .memory_type
171        .map(|t| t.as_str().to_string())
172        .unwrap_or_else(|| row.memory_type.clone());
173    let type_changed = memory_type != row.memory_type;
174    let metadata = row.metadata.clone();
175
176    let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
177
178    let affected = if let Some(ts) = args.expected_updated_at {
179        tx.execute(
180            "UPDATE memories SET description=?2, body=?3, body_hash=?4, type=?5
181             WHERE id=?1 AND updated_at=?6 AND deleted_at IS NULL",
182            rusqlite::params![
183                memory_id,
184                new_description,
185                new_body,
186                new_hash,
187                memory_type,
188                ts
189            ],
190        )?
191    } else {
192        tx.execute(
193            "UPDATE memories SET description=?2, body=?3, body_hash=?4, type=?5
194             WHERE id=?1 AND deleted_at IS NULL",
195            rusqlite::params![memory_id, new_description, new_body, new_hash, memory_type],
196        )?
197    };
198
199    if affected == 0 {
200        return Err(AppError::Conflict(
201            "optimistic lock conflict: memory was modified by another process".to_string(),
202        ));
203    }
204
205    // v1.0.84 (ADR-0042): backend discriminator for the JSON envelope.
206    // Populated only when re-embedding actually ran; stays None for
207    // description-only or metadata-only edits.
208    let mut backend_invoked: Option<&'static str> = None;
209
210    if body_changed || type_changed || args.force_reembed {
211        output::emit_progress_i18n(
212            "Re-computing embedding for edited body...",
213            crate::i18n::validation::runtime_pt::edit_recomputing_embedding(),
214        );
215        // v1.0.82 (GAP-003): forward --llm-backend to embed_with_fallback.
216        // v1.0.84 (ADR-0042): tuple (Vec<f32>, LlmBackendKind) — extrai o
217        // backend that actually ran — populate `backend_invoked`.
218        let skip_embed = crate::embedder::should_skip_embedding_on_failure();
219        let embedding: Option<(Vec<f32>, &'static str)> =
220            match crate::embedder::embed_passage_with_embedding_choice(
221                &paths.models,
222                &new_body,
223                backends,
224            ) {
225                Ok((emb, kind)) => Some((emb, kind.as_str())),
226                // v1.1.2 (Gap 2): typed payload rejections are permanent and
227                // must not be swallowed by --skip-embedding-on-failure.
228                Err(
229                    e @ (AppError::Validation(_)
230                    | AppError::BodyTooLarge { .. }
231                    | AppError::TooManyTokens { .. }),
232                ) => return Err(e),
233                Err(e) if skip_embed => {
234                    tracing::warn!(error = %e, "edit: embedding failed; --skip-embedding-on-failure active, persisting without embedding");
235                    None
236                }
237                Err(e) => return Err(e),
238            };
239        if let Some((ref emb, kind)) = embedding {
240            backend_invoked = Some(kind);
241            let snippet: String = new_body.chars().take(300).collect();
242            memories::upsert_vec(
243                &tx,
244                memory_id,
245                &namespace,
246                &memory_type,
247                emb,
248                &name,
249                &snippet,
250            )?;
251        }
252    }
253
254    let next_v = versions::next_version(&tx, memory_id)?;
255
256    versions::insert_version(
257        &tx,
258        memory_id,
259        next_v,
260        &name,
261        &memory_type,
262        &new_description,
263        &new_body,
264        &metadata,
265        None,
266        "edit",
267    )?;
268
269    memories::sync_fts_after_update(
270        &tx,
271        memory_id,
272        &row.name,
273        &row.description,
274        &row.body,
275        &row.name,
276        &new_description,
277        &new_body,
278    )?;
279
280    tx.commit()?;
281
282    conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE);")?;
283
284    output::emit_json(&EditResponse {
285        memory_id,
286        name,
287        action: "updated".to_string(),
288        version: next_v,
289        elapsed_ms: started.elapsed().as_millis() as u64,
290        backend_invoked,
291    })?;
292
293    Ok(())
294}
295
296#[cfg(test)]
297mod tests {
298    use super::*;
299
300    #[derive(clap::Parser)]
301    struct TestCli {
302        #[command(flatten)]
303        args: EditArgs,
304    }
305
306    #[test]
307    fn type_flag_is_a_visible_alias_of_memory_type() {
308        // G47: COOKBOOK, README and llms.txt promise `edit --type`; the flag
309        // was only reachable as --memory-type, breaking the documented CLI.
310        use clap::Parser;
311        let cli = TestCli::try_parse_from(["edit", "--name", "m", "--type", "decision"])
312            .expect("--type must parse as an alias of --memory-type");
313        assert!(cli.args.memory_type.is_some());
314        let cli = TestCli::try_parse_from(["edit", "--name", "m", "--memory-type", "decision"])
315            .expect("--memory-type must keep working");
316        assert!(cli.args.memory_type.is_some());
317    }
318
319    #[test]
320    fn edit_response_serializes_all_fields() {
321        let resp = EditResponse {
322            memory_id: 42,
323            name: "my-memory".to_string(),
324            action: "updated".to_string(),
325            version: 3,
326            elapsed_ms: 7,
327            backend_invoked: None,
328        };
329        let json = serde_json::to_value(&resp).expect("serialization failed");
330        assert_eq!(json["memory_id"], 42i64);
331        assert_eq!(json["name"], "my-memory");
332        assert_eq!(json["action"], "updated");
333        assert_eq!(json["version"], 3i64);
334        assert!(json["elapsed_ms"].is_number());
335    }
336
337    #[test]
338    fn edit_response_action_contains_updated() {
339        let resp = EditResponse {
340            memory_id: 1,
341            name: "n".to_string(),
342            action: "updated".to_string(),
343            version: 1,
344            elapsed_ms: 0,
345            backend_invoked: None,
346        };
347        assert_eq!(
348            resp.action, "updated",
349            "action must be 'updated' for successful edits"
350        );
351    }
352
353    #[test]
354    fn edit_body_exceeds_limit_returns_error() {
355        let limit = crate::constants::MAX_MEMORY_BODY_LEN;
356        let large_body: String = "a".repeat(limit + 1);
357        assert!(
358            large_body.len() > limit,
359            "body above limit must have length > MAX_MEMORY_BODY_LEN"
360        );
361    }
362
363    #[test]
364    fn edit_description_exceeds_limit_returns_error() {
365        let limit = crate::constants::MAX_MEMORY_DESCRIPTION_LEN;
366        let large_desc: String = "d".repeat(limit + 1);
367        assert!(
368            large_desc.len() > limit,
369            "description above limit must have length > MAX_MEMORY_DESCRIPTION_LEN"
370        );
371    }
372}