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