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(
45 long,
46 value_name = "EPOCH_OR_RFC3339",
47 value_parser = crate::parsers::parse_expected_updated_at,
48 long_help = "Optimistic lock: reject if updated_at does not match. \
49Accepts Unix epoch (e.g. 1700000000) or RFC 3339 (e.g. 2026-04-19T12:00:00Z)."
50 )]
51 pub expected_updated_at: Option<i64>,
52 #[arg(
53 long,
54 help = "Namespace (env: SQLITE_GRAPHRAG_NAMESPACE, default: global)"
55 )]
56 pub namespace: Option<String>,
57 #[arg(long, hide = true, help = "No-op; JSON is always emitted on stdout")]
58 pub json: bool,
59 #[arg(long, env = "SQLITE_GRAPHRAG_DB_PATH")]
60 pub db: Option<String>,
61}
62
63#[derive(Serialize)]
64struct EditResponse {
65 memory_id: i64,
66 name: String,
67 action: String,
68 version: i64,
69 elapsed_ms: u64,
71}
72
73pub fn run(args: EditArgs) -> Result<(), AppError> {
74 use crate::constants::*;
75
76 let inicio = std::time::Instant::now();
77 let name = args.name_positional.or(args.name).ok_or_else(|| {
79 AppError::Validation("name required: pass as positional argument or via --name".to_string())
80 })?;
81 let namespace = crate::namespace::resolve_namespace(args.namespace.as_deref())?;
82
83 let paths = AppPaths::resolve(args.db.as_deref())?;
84 crate::storage::connection::ensure_db_ready(&paths)?;
85 let mut conn = open_rw(&paths.db)?;
86
87 let (memory_id, current_updated_at, _current_version) =
88 memories::find_by_name(&conn, &namespace, &name)?
89 .ok_or_else(|| AppError::NotFound(errors_msg::memory_not_found(&name, &namespace)))?;
90
91 if let Some(expected) = args.expected_updated_at {
92 if expected != current_updated_at {
93 return Err(AppError::Conflict(errors_msg::optimistic_lock_conflict(
94 expected,
95 current_updated_at,
96 )));
97 }
98 }
99
100 let mut raw_body: Option<String> = None;
101 if args.body.is_some() || args.body_file.is_some() || args.body_stdin {
102 let b = if let Some(b) = args.body {
103 b
104 } else if let Some(path) = &args.body_file {
105 std::fs::read_to_string(path).map_err(AppError::Io)?
106 } else {
107 crate::stdin_helper::read_stdin_with_timeout(60)?
108 };
109 if b.len() > MAX_MEMORY_BODY_LEN {
110 return Err(AppError::LimitExceeded(
111 crate::i18n::validation::body_exceeds(MAX_MEMORY_BODY_LEN),
112 ));
113 }
114 raw_body = Some(b);
115 }
116
117 if let Some(ref desc) = args.description {
118 if desc.len() > MAX_MEMORY_DESCRIPTION_LEN {
119 return Err(AppError::Validation(
120 crate::i18n::validation::description_exceeds(MAX_MEMORY_DESCRIPTION_LEN),
121 ));
122 }
123 }
124
125 let row = memories::read_by_name(&conn, &namespace, &name)?
126 .ok_or_else(|| AppError::Internal(anyhow::anyhow!("memory row not found after check")))?;
127
128 let body_changed = raw_body.is_some();
129 let new_body = raw_body.unwrap_or(row.body.clone());
130 let new_description = args.description.unwrap_or(row.description.clone());
131 let new_hash = blake3::hash(new_body.as_bytes()).to_hex().to_string();
132 let memory_type = row.memory_type.clone();
133 let metadata = row.metadata.clone();
134
135 let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
136
137 let affected = if let Some(ts) = args.expected_updated_at {
138 tx.execute(
139 "UPDATE memories SET description=?2, body=?3, body_hash=?4
140 WHERE id=?1 AND updated_at=?5 AND deleted_at IS NULL",
141 rusqlite::params![memory_id, new_description, new_body, new_hash, ts],
142 )?
143 } else {
144 tx.execute(
145 "UPDATE memories SET description=?2, body=?3, body_hash=?4
146 WHERE id=?1 AND deleted_at IS NULL",
147 rusqlite::params![memory_id, new_description, new_body, new_hash],
148 )?
149 };
150
151 if affected == 0 {
152 return Err(AppError::Conflict(
153 "optimistic lock conflict: memory was modified by another process".to_string(),
154 ));
155 }
156
157 if body_changed {
158 output::emit_progress_i18n(
159 "Re-computing embedding for edited body...",
160 crate::i18n::validation::runtime_pt::edit_recomputing_embedding(),
161 );
162 let embedding = crate::daemon::embed_passage_or_local(&paths.models, &new_body)?;
163 let snippet: String = new_body.chars().take(300).collect();
164 memories::upsert_vec(
165 &tx,
166 memory_id,
167 &namespace,
168 &memory_type,
169 &embedding,
170 &name,
171 &snippet,
172 )?;
173 }
174
175 let next_v = versions::next_version(&tx, memory_id)?;
176
177 versions::insert_version(
178 &tx,
179 memory_id,
180 next_v,
181 &name,
182 &memory_type,
183 &new_description,
184 &new_body,
185 &metadata,
186 None,
187 "edit",
188 )?;
189
190 memories::sync_fts_after_update(
191 &tx,
192 memory_id,
193 &row.name,
194 &row.description,
195 &row.body,
196 &row.name,
197 &new_description,
198 &new_body,
199 )?;
200
201 tx.commit()?;
202
203 conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE);")?;
204
205 output::emit_json(&EditResponse {
206 memory_id,
207 name,
208 action: "updated".to_string(),
209 version: next_v,
210 elapsed_ms: inicio.elapsed().as_millis() as u64,
211 })?;
212
213 Ok(())
214}
215
216#[cfg(test)]
217mod tests {
218 use super::*;
219
220 #[test]
221 fn edit_response_serializes_all_fields() {
222 let resp = EditResponse {
223 memory_id: 42,
224 name: "my-memory".to_string(),
225 action: "updated".to_string(),
226 version: 3,
227 elapsed_ms: 7,
228 };
229 let json = serde_json::to_value(&resp).expect("serialization failed");
230 assert_eq!(json["memory_id"], 42i64);
231 assert_eq!(json["name"], "my-memory");
232 assert_eq!(json["action"], "updated");
233 assert_eq!(json["version"], 3i64);
234 assert!(json["elapsed_ms"].is_number());
235 }
236
237 #[test]
238 fn edit_response_action_contains_updated() {
239 let resp = EditResponse {
240 memory_id: 1,
241 name: "n".to_string(),
242 action: "updated".to_string(),
243 version: 1,
244 elapsed_ms: 0,
245 };
246 assert_eq!(
247 resp.action, "updated",
248 "action must be 'updated' for successful edits"
249 );
250 }
251
252 #[test]
253 fn edit_body_exceeds_limit_returns_error() {
254 let limit = crate::constants::MAX_MEMORY_BODY_LEN;
255 let large_body: String = "a".repeat(limit + 1);
256 assert!(
257 large_body.len() > limit,
258 "body above limit must have length > MAX_MEMORY_BODY_LEN"
259 );
260 }
261
262 #[test]
263 fn edit_description_exceeds_limit_returns_error() {
264 let limit = crate::constants::MAX_MEMORY_DESCRIPTION_LEN;
265 let large_desc: String = "d".repeat(limit + 1);
266 assert!(
267 large_desc.len() > limit,
268 "description above limit must have length > MAX_MEMORY_DESCRIPTION_LEN"
269 );
270 }
271}