sqlite_graphrag/commands/
edit.rs1use 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 #[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 #[arg(long)]
31 pub name: Option<String>,
32 #[arg(long, conflicts_with_all = ["body_file", "body_stdin"])]
34 pub body: Option<String>,
35 #[arg(long, conflicts_with_all = ["body", "body_stdin"])]
37 pub body_file: Option<std::path::PathBuf>,
38 #[arg(long, conflicts_with_all = ["body", "body_file"])]
40 pub body_stdin: bool,
41 #[arg(long)]
43 pub description: Option<String>,
44 #[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 #[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 #[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 elapsed_ms: u64,
91}
92
93pub fn run(args: EditArgs, llm_backend: crate::cli::LlmBackendChoice) -> Result<(), AppError> {
94 use crate::constants::*;
95
96 let inicio = std::time::Instant::now();
97 tracing::debug!(target: "edit", name = ?args.name_positional.as_deref().or(args.name.as_deref()), "updating memory");
98 let name = args.name_positional.or(args.name).ok_or_else(|| {
100 AppError::Validation("name required: pass as positional argument or via --name".to_string())
101 })?;
102 let namespace = crate::namespace::resolve_namespace(args.namespace.as_deref())?;
103
104 let paths = AppPaths::resolve(args.db.as_deref())?;
105 crate::storage::connection::ensure_db_ready(&paths)?;
106 let mut conn = open_rw(&paths.db)?;
107
108 let (memory_id, current_updated_at, _current_version) =
109 memories::find_by_name(&conn, &namespace, &name)?
110 .ok_or_else(|| AppError::NotFound(errors_msg::memory_not_found(&name, &namespace)))?;
111
112 if let Some(expected) = args.expected_updated_at {
113 if expected != current_updated_at {
114 return Err(AppError::Conflict(errors_msg::optimistic_lock_conflict(
115 expected,
116 current_updated_at,
117 )));
118 }
119 }
120
121 let mut raw_body: Option<String> = None;
122 if args.body.is_some() || args.body_file.is_some() || args.body_stdin {
123 let b = if let Some(b) = args.body {
124 b
125 } else if let Some(path) = &args.body_file {
126 let file_size = std::fs::metadata(path).map_err(AppError::Io)?.len();
127 if file_size > MAX_MEMORY_BODY_LEN as u64 {
128 return Err(AppError::LimitExceeded(
129 crate::i18n::validation::body_exceeds(MAX_MEMORY_BODY_LEN),
130 ));
131 }
132 std::fs::read_to_string(path).map_err(AppError::Io)?
133 } else {
134 crate::stdin_helper::read_stdin_with_timeout(60)?
135 };
136 if b.len() > MAX_MEMORY_BODY_LEN {
137 return Err(AppError::LimitExceeded(
138 crate::i18n::validation::body_exceeds(MAX_MEMORY_BODY_LEN),
139 ));
140 }
141 raw_body = Some(b);
142 }
143
144 if let Some(ref desc) = args.description {
145 if desc.len() > MAX_MEMORY_DESCRIPTION_LEN {
146 return Err(AppError::Validation(
147 crate::i18n::validation::description_exceeds(MAX_MEMORY_DESCRIPTION_LEN),
148 ));
149 }
150 }
151
152 let row = memories::read_by_name(&conn, &namespace, &name)?
153 .ok_or_else(|| AppError::Internal(anyhow::anyhow!("memory row not found after check")))?;
154
155 let body_changed = raw_body.is_some();
156 let new_body = raw_body.unwrap_or(row.body.clone());
157 let new_description = args.description.unwrap_or(row.description.clone());
158 let new_hash = blake3::hash(new_body.as_bytes()).to_hex().to_string();
159 let body_changed = body_changed && new_hash != row.body_hash;
161 let memory_type = args
162 .memory_type
163 .map(|t| t.as_str().to_string())
164 .unwrap_or_else(|| row.memory_type.clone());
165 let type_changed = memory_type != row.memory_type;
166 let metadata = row.metadata.clone();
167
168 let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
169
170 let affected = if let Some(ts) = args.expected_updated_at {
171 tx.execute(
172 "UPDATE memories SET description=?2, body=?3, body_hash=?4, type=?5
173 WHERE id=?1 AND updated_at=?6 AND deleted_at IS NULL",
174 rusqlite::params![
175 memory_id,
176 new_description,
177 new_body,
178 new_hash,
179 memory_type,
180 ts
181 ],
182 )?
183 } else {
184 tx.execute(
185 "UPDATE memories SET description=?2, body=?3, body_hash=?4, type=?5
186 WHERE id=?1 AND deleted_at IS NULL",
187 rusqlite::params![memory_id, new_description, new_body, new_hash, memory_type],
188 )?
189 };
190
191 if affected == 0 {
192 return Err(AppError::Conflict(
193 "optimistic lock conflict: memory was modified by another process".to_string(),
194 ));
195 }
196
197 if body_changed || type_changed || args.force_reembed {
198 output::emit_progress_i18n(
199 "Re-computing embedding for edited body...",
200 crate::i18n::validation::runtime_pt::edit_recomputing_embedding(),
201 );
202 let embedding = crate::embedder::embed_passage_with_choice(
204 &paths.models,
205 &new_body,
206 Some(llm_backend),
207 )?;
208 let snippet: String = new_body.chars().take(300).collect();
209 memories::upsert_vec(
210 &tx,
211 memory_id,
212 &namespace,
213 &memory_type,
214 &embedding,
215 &name,
216 &snippet,
217 )?;
218 }
219
220 let next_v = versions::next_version(&tx, memory_id)?;
221
222 versions::insert_version(
223 &tx,
224 memory_id,
225 next_v,
226 &name,
227 &memory_type,
228 &new_description,
229 &new_body,
230 &metadata,
231 None,
232 "edit",
233 )?;
234
235 memories::sync_fts_after_update(
236 &tx,
237 memory_id,
238 &row.name,
239 &row.description,
240 &row.body,
241 &row.name,
242 &new_description,
243 &new_body,
244 )?;
245
246 tx.commit()?;
247
248 conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE);")?;
249
250 output::emit_json(&EditResponse {
251 memory_id,
252 name,
253 action: "updated".to_string(),
254 version: next_v,
255 elapsed_ms: inicio.elapsed().as_millis() as u64,
256 })?;
257
258 Ok(())
259}
260
261#[cfg(test)]
262mod tests {
263 use super::*;
264
265 #[derive(clap::Parser)]
266 struct TestCli {
267 #[command(flatten)]
268 args: EditArgs,
269 }
270
271 #[test]
272 fn type_flag_is_a_visible_alias_of_memory_type() {
273 use clap::Parser;
276 let cli = TestCli::try_parse_from(["edit", "--name", "m", "--type", "decision"])
277 .expect("--type must parse as an alias of --memory-type");
278 assert!(cli.args.memory_type.is_some());
279 let cli = TestCli::try_parse_from(["edit", "--name", "m", "--memory-type", "decision"])
280 .expect("--memory-type must keep working");
281 assert!(cli.args.memory_type.is_some());
282 }
283
284 #[test]
285 fn edit_response_serializes_all_fields() {
286 let resp = EditResponse {
287 memory_id: 42,
288 name: "my-memory".to_string(),
289 action: "updated".to_string(),
290 version: 3,
291 elapsed_ms: 7,
292 };
293 let json = serde_json::to_value(&resp).expect("serialization failed");
294 assert_eq!(json["memory_id"], 42i64);
295 assert_eq!(json["name"], "my-memory");
296 assert_eq!(json["action"], "updated");
297 assert_eq!(json["version"], 3i64);
298 assert!(json["elapsed_ms"].is_number());
299 }
300
301 #[test]
302 fn edit_response_action_contains_updated() {
303 let resp = EditResponse {
304 memory_id: 1,
305 name: "n".to_string(),
306 action: "updated".to_string(),
307 version: 1,
308 elapsed_ms: 0,
309 };
310 assert_eq!(
311 resp.action, "updated",
312 "action must be 'updated' for successful edits"
313 );
314 }
315
316 #[test]
317 fn edit_body_exceeds_limit_returns_error() {
318 let limit = crate::constants::MAX_MEMORY_BODY_LEN;
319 let large_body: String = "a".repeat(limit + 1);
320 assert!(
321 large_body.len() > limit,
322 "body above limit must have length > MAX_MEMORY_BODY_LEN"
323 );
324 }
325
326 #[test]
327 fn edit_description_exceeds_limit_returns_error() {
328 let limit = crate::constants::MAX_MEMORY_DESCRIPTION_LEN;
329 let large_desc: String = "d".repeat(limit + 1);
330 assert!(
331 large_desc.len() > limit,
332 "description above limit must have length > MAX_MEMORY_DESCRIPTION_LEN"
333 );
334 }
335}