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 LLM backend that actually
94    /// ran the re-embedding of the edited body. `"claude" | "codex" | "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(
103    args: EditArgs,
104    llm_backend: crate::cli::LlmBackendChoice,
105    embedding_backend: crate::cli::EmbeddingBackendChoice,
106) -> Result<(), AppError> {
107    use crate::constants::*;
108
109    let inicio = std::time::Instant::now();
110    tracing::debug!(target: "edit", name = ?args.name_positional.as_deref().or(args.name.as_deref()), "updating memory");
111    // Resolve name from positional or --name flag; both are optional, at least one is required.
112    let name = args.name_positional.or(args.name).ok_or_else(|| {
113        AppError::Validation(crate::i18n::validation::name_required_positional_or_flag())
114    })?;
115    let namespace = crate::namespace::resolve_namespace(args.namespace.as_deref())?;
116
117    let paths = AppPaths::resolve(args.db.as_deref())?;
118    crate::storage::connection::ensure_db_ready(&paths)?;
119    let mut conn = open_rw(&paths.db)?;
120
121    let (memory_id, current_updated_at, _current_version) =
122        memories::find_by_name(&conn, &namespace, &name)?
123            .ok_or_else(|| AppError::NotFound(errors_msg::memory_not_found(&name, &namespace)))?;
124
125    if let Some(expected) = args.expected_updated_at {
126        if expected != current_updated_at {
127            return Err(AppError::Conflict(errors_msg::optimistic_lock_conflict(
128                expected,
129                current_updated_at,
130            )));
131        }
132    }
133
134    let mut raw_body: Option<String> = None;
135    if args.body.is_some() || args.body_file.is_some() || args.body_stdin {
136        let b = if let Some(b) = args.body {
137            b
138        } else if let Some(path) = &args.body_file {
139            let file_size = std::fs::metadata(path).map_err(AppError::Io)?.len();
140            if file_size > MAX_MEMORY_BODY_LEN as u64 {
141                return Err(AppError::BodyTooLarge {
142                    bytes: file_size,
143                    limit: MAX_MEMORY_BODY_LEN as u64,
144                });
145            }
146            std::fs::read_to_string(path).map_err(AppError::Io)?
147        } else {
148            crate::stdin_helper::read_stdin_with_timeout(60)?
149        };
150        // v1.1.2 (Gap 2): boundary validation of BOTH payload ceilings —
151        // bytes (BodyTooLarge) and estimated tokens (TooManyTokens), exit 6.
152        crate::memory_guard::check_embedding_input_size(&b)?;
153        raw_body = Some(b);
154    }
155
156    if let Some(ref desc) = args.description {
157        if desc.len() > MAX_MEMORY_DESCRIPTION_LEN {
158            return Err(AppError::Validation(
159                crate::i18n::validation::description_exceeds(MAX_MEMORY_DESCRIPTION_LEN),
160            ));
161        }
162    }
163
164    let row = memories::read_by_name(&conn, &namespace, &name)?
165        .ok_or_else(|| AppError::Internal(anyhow::anyhow!("memory row not found after check")))?;
166
167    let body_changed = raw_body.is_some();
168    let new_body = raw_body.unwrap_or(row.body.clone());
169    let new_description = args.description.unwrap_or(row.description.clone());
170    let new_hash = blake3::hash(new_body.as_bytes()).to_hex().to_string();
171    // Skip re-embedding when body content is identical to the stored version.
172    let body_changed = body_changed && new_hash != row.body_hash;
173    let memory_type = args
174        .memory_type
175        .map(|t| t.as_str().to_string())
176        .unwrap_or_else(|| row.memory_type.clone());
177    let type_changed = memory_type != row.memory_type;
178    let metadata = row.metadata.clone();
179
180    let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
181
182    let affected = if let Some(ts) = args.expected_updated_at {
183        tx.execute(
184            "UPDATE memories SET description=?2, body=?3, body_hash=?4, type=?5
185             WHERE id=?1 AND updated_at=?6 AND deleted_at IS NULL",
186            rusqlite::params![
187                memory_id,
188                new_description,
189                new_body,
190                new_hash,
191                memory_type,
192                ts
193            ],
194        )?
195    } else {
196        tx.execute(
197            "UPDATE memories SET description=?2, body=?3, body_hash=?4, type=?5
198             WHERE id=?1 AND deleted_at IS NULL",
199            rusqlite::params![memory_id, new_description, new_body, new_hash, memory_type],
200        )?
201    };
202
203    if affected == 0 {
204        return Err(AppError::Conflict(
205            "optimistic lock conflict: memory was modified by another process".to_string(),
206        ));
207    }
208
209    // v1.0.84 (ADR-0042): backend discriminator for the JSON envelope.
210    // Populated only when re-embedding actually ran; stays None for
211    // description-only or metadata-only edits.
212    let mut backend_invoked: Option<&'static str> = None;
213
214    if body_changed || type_changed || args.force_reembed {
215        output::emit_progress_i18n(
216            "Re-computing embedding for edited body...",
217            crate::i18n::validation::runtime_pt::edit_recomputing_embedding(),
218        );
219        // v1.0.82 (GAP-003): forward --llm-backend to embed_with_fallback.
220        // v1.0.84 (ADR-0042): tuple (Vec<f32>, LlmBackendKind) — extrai o
221        // backend that actually ran — populate `backend_invoked`.
222        let skip_embed = crate::embedder::should_skip_embedding_on_failure();
223        let embedding: Option<(Vec<f32>, &'static str)> =
224            match crate::embedder::embed_passage_with_embedding_choice(
225                &paths.models,
226                &new_body,
227                embedding_backend,
228                llm_backend,
229            ) {
230                Ok((emb, kind)) => Some((emb, kind.as_str())),
231                // v1.1.2 (Gap 2): typed payload rejections are permanent and
232                // must not be swallowed by --skip-embedding-on-failure.
233                Err(
234                    e @ (AppError::Validation(_)
235                    | AppError::BodyTooLarge { .. }
236                    | AppError::TooManyTokens { .. }),
237                ) => return Err(e),
238                Err(e) if skip_embed => {
239                    tracing::warn!(error = %e, "edit: embedding failed; --skip-embedding-on-failure active, persisting without embedding");
240                    None
241                }
242                Err(e) => return Err(e),
243            };
244        if let Some((ref emb, kind)) = embedding {
245            backend_invoked = Some(kind);
246            let snippet: String = new_body.chars().take(300).collect();
247            memories::upsert_vec(
248                &tx,
249                memory_id,
250                &namespace,
251                &memory_type,
252                emb,
253                &name,
254                &snippet,
255            )?;
256        }
257    }
258
259    let next_v = versions::next_version(&tx, memory_id)?;
260
261    versions::insert_version(
262        &tx,
263        memory_id,
264        next_v,
265        &name,
266        &memory_type,
267        &new_description,
268        &new_body,
269        &metadata,
270        None,
271        "edit",
272    )?;
273
274    memories::sync_fts_after_update(
275        &tx,
276        memory_id,
277        &row.name,
278        &row.description,
279        &row.body,
280        &row.name,
281        &new_description,
282        &new_body,
283    )?;
284
285    tx.commit()?;
286
287    conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE);")?;
288
289    output::emit_json(&EditResponse {
290        memory_id,
291        name,
292        action: "updated".to_string(),
293        version: next_v,
294        elapsed_ms: inicio.elapsed().as_millis() as u64,
295        backend_invoked,
296    })?;
297
298    Ok(())
299}
300
301#[cfg(test)]
302mod tests {
303    use super::*;
304
305    #[derive(clap::Parser)]
306    struct TestCli {
307        #[command(flatten)]
308        args: EditArgs,
309    }
310
311    #[test]
312    fn type_flag_is_a_visible_alias_of_memory_type() {
313        // G47: COOKBOOK, README and llms.txt promise `edit --type`; the flag
314        // was only reachable as --memory-type, breaking the documented CLI.
315        use clap::Parser;
316        let cli = TestCli::try_parse_from(["edit", "--name", "m", "--type", "decision"])
317            .expect("--type must parse as an alias of --memory-type");
318        assert!(cli.args.memory_type.is_some());
319        let cli = TestCli::try_parse_from(["edit", "--name", "m", "--memory-type", "decision"])
320            .expect("--memory-type must keep working");
321        assert!(cli.args.memory_type.is_some());
322    }
323
324    #[test]
325    fn edit_response_serializes_all_fields() {
326        let resp = EditResponse {
327            memory_id: 42,
328            name: "my-memory".to_string(),
329            action: "updated".to_string(),
330            version: 3,
331            elapsed_ms: 7,
332            backend_invoked: None,
333        };
334        let json = serde_json::to_value(&resp).expect("serialization failed");
335        assert_eq!(json["memory_id"], 42i64);
336        assert_eq!(json["name"], "my-memory");
337        assert_eq!(json["action"], "updated");
338        assert_eq!(json["version"], 3i64);
339        assert!(json["elapsed_ms"].is_number());
340    }
341
342    #[test]
343    fn edit_response_action_contains_updated() {
344        let resp = EditResponse {
345            memory_id: 1,
346            name: "n".to_string(),
347            action: "updated".to_string(),
348            version: 1,
349            elapsed_ms: 0,
350            backend_invoked: None,
351        };
352        assert_eq!(
353            resp.action, "updated",
354            "action must be 'updated' for successful edits"
355        );
356    }
357
358    #[test]
359    fn edit_body_exceeds_limit_returns_error() {
360        let limit = crate::constants::MAX_MEMORY_BODY_LEN;
361        let large_body: String = "a".repeat(limit + 1);
362        assert!(
363            large_body.len() > limit,
364            "body above limit must have length > MAX_MEMORY_BODY_LEN"
365        );
366    }
367
368    #[test]
369    fn edit_description_exceeds_limit_returns_error() {
370        let limit = crate::constants::MAX_MEMORY_DESCRIPTION_LEN;
371        let large_desc: String = "d".repeat(limit + 1);
372        assert!(
373            large_desc.len() > limit,
374            "description above limit must have length > MAX_MEMORY_DESCRIPTION_LEN"
375        );
376    }
377}