Skip to main content

ai_memory/cli/
update.rs

1// Copyright 2026 AlphaOne LLC
2// SPDX-License-Identifier: Apache-2.0
3
4//! `cmd_update` migration. See `cli::store` for the design pattern.
5
6use crate::cli::CliOutput;
7use crate::{db, validate};
8use anyhow::Result;
9use clap::Args;
10use std::path::Path;
11
12#[derive(Args)]
13pub struct UpdateArgs {
14    pub id: String,
15    #[arg(long, short = 'T', allow_hyphen_values = true)]
16    pub title: Option<String>,
17    #[arg(long, short, allow_hyphen_values = true)]
18    pub content: Option<String>,
19    #[arg(long, short)]
20    pub tier: Option<String>,
21    #[arg(long, short)]
22    pub namespace: Option<String>,
23    #[arg(long)]
24    pub tags: Option<String>,
25    #[arg(long, short)]
26    pub priority: Option<i32>,
27    #[arg(long)]
28    pub confidence: Option<f64>,
29    /// Expiry timestamp (RFC3339), or empty string to clear
30    #[arg(long)]
31    pub expires_at: Option<String>,
32}
33
34/// `update` handler.
35pub fn run(
36    db_path: &Path,
37    args: &UpdateArgs,
38    json_out: bool,
39    out: &mut CliOutput<'_>,
40) -> Result<()> {
41    use crate::models::Tier;
42    validate::validate_id(&args.id)?;
43    let conn = db::open(db_path)?;
44    let resolved_id = if db::get(&conn, &args.id)?.is_some() {
45        args.id.clone()
46    } else if let Some(mem) = db::get_by_prefix(&conn, &args.id)? {
47        mem.id
48    } else {
49        writeln!(out.stderr, "not found: {}", args.id)?;
50        std::process::exit(1);
51    };
52    let tier = args.tier.as_deref().and_then(Tier::from_str);
53    let tags: Option<Vec<String>> = args.tags.as_ref().map(|t| {
54        t.split(',')
55            .map(|s| s.trim().to_string())
56            .filter(|s| !s.is_empty())
57            .collect()
58    });
59    if let Some(ref t) = args.title {
60        validate::validate_title(t)?;
61    }
62    if let Some(ref c) = args.content {
63        validate::validate_content(c)?;
64    }
65    if let Some(ref ns) = args.namespace {
66        validate::validate_namespace(ns)?;
67    }
68    if let Some(ref tags) = tags {
69        validate::validate_tags(tags)?;
70    }
71    if let Some(p) = args.priority {
72        validate::validate_priority(p)?;
73    }
74    if let Some(c) = args.confidence {
75        validate::validate_confidence(c)?;
76    }
77    if let Some(ref ts) = args.expires_at
78        && !ts.is_empty()
79    {
80        validate::validate_expires_at_format(ts)?;
81    }
82    let (found, _content_changed) = db::update(
83        &conn,
84        &resolved_id,
85        args.title.as_deref(),
86        args.content.as_deref(),
87        tier.as_ref(),
88        args.namespace.as_deref(),
89        tags.as_ref(),
90        args.priority,
91        args.confidence,
92        args.expires_at.as_deref(),
93        None,
94    )?;
95    if !found {
96        writeln!(out.stderr, "not found: {}", args.id)?;
97        std::process::exit(1);
98    }
99    if let Some(mem) = db::get(&conn, &resolved_id)? {
100        if json_out {
101            writeln!(out.stdout, "{}", serde_json::to_string(&mem)?)?;
102        } else {
103            writeln!(out.stdout, "updated: {} [{}]", mem.id, mem.title)?;
104        }
105    }
106    Ok(())
107}
108
109#[cfg(test)]
110mod tests {
111    use super::*;
112    use crate::cli::test_utils::{TestEnv, seed_memory};
113
114    fn empty_args(id: &str) -> UpdateArgs {
115        UpdateArgs {
116            id: id.to_string(),
117            title: None,
118            content: None,
119            tier: None,
120            namespace: None,
121            tags: None,
122            priority: None,
123            confidence: None,
124            expires_at: None,
125        }
126    }
127
128    #[test]
129    fn test_update_happy_path() {
130        let mut env = TestEnv::fresh();
131        let db = env.db_path.clone();
132        let id = seed_memory(&db, "ns", "old-title", "old content");
133        let mut args = empty_args(&id);
134        args.title = Some("new-title".to_string());
135        args.content = Some("new content".to_string());
136        {
137            let mut out = env.output();
138            run(&db, &args, false, &mut out).unwrap();
139        }
140        assert!(env.stdout_str().contains("updated:"));
141        assert!(env.stdout_str().contains("new-title"));
142    }
143
144    #[test]
145    fn test_update_by_prefix_id() {
146        let mut env = TestEnv::fresh();
147        let db = env.db_path.clone();
148        let id = seed_memory(&db, "ns", "title-a", "content-a");
149        // Use an 8-char prefix (UUIDs are 36 chars).
150        let prefix = &id[..8];
151        let mut args = empty_args(prefix);
152        args.title = Some("renamed".to_string());
153        {
154            let mut out = env.output();
155            run(&db, &args, false, &mut out).unwrap();
156        }
157        assert!(env.stdout_str().contains("renamed"));
158    }
159
160    // Skip nonexistent-id-exits-nonzero test directly: process::exit
161    // tears down the test runner. Exit-path coverage handled in the
162    // integration suite that spawns the binary.
163
164    #[test]
165    fn test_update_partial_only_title() {
166        let mut env = TestEnv::fresh();
167        let db = env.db_path.clone();
168        let id = seed_memory(&db, "ns", "orig-title", "orig content");
169        let mut args = empty_args(&id);
170        args.title = Some("title-only-change".to_string());
171        {
172            let mut out = env.output();
173            run(&db, &args, true, &mut out).unwrap();
174        }
175        let v: serde_json::Value = serde_json::from_str(env.stdout_str().trim()).unwrap();
176        assert_eq!(v["title"].as_str().unwrap(), "title-only-change");
177        assert_eq!(v["content"].as_str().unwrap(), "orig content");
178    }
179
180    #[test]
181    fn test_update_partial_only_content() {
182        let mut env = TestEnv::fresh();
183        let db = env.db_path.clone();
184        let id = seed_memory(&db, "ns", "kept-title", "old-content");
185        let mut args = empty_args(&id);
186        args.content = Some("new content body".to_string());
187        {
188            let mut out = env.output();
189            run(&db, &args, true, &mut out).unwrap();
190        }
191        let v: serde_json::Value = serde_json::from_str(env.stdout_str().trim()).unwrap();
192        assert_eq!(v["title"].as_str().unwrap(), "kept-title");
193        assert_eq!(v["content"].as_str().unwrap(), "new content body");
194    }
195
196    #[test]
197    fn test_update_clear_expires_at_with_empty_string() {
198        let mut env = TestEnv::fresh();
199        let db = env.db_path.clone();
200        let id = seed_memory(&db, "ns", "tt", "cc");
201        let mut args = empty_args(&id);
202        args.expires_at = Some(String::new());
203        {
204            let mut out = env.output();
205            // Empty-string skips the format-validate branch and is
206            // forwarded as a clear-expiry directive to db::update.
207            run(&db, &args, false, &mut out).unwrap();
208        }
209        assert!(env.stdout_str().contains("updated:"));
210    }
211
212    #[test]
213    fn test_update_invalid_priority_validation_error() {
214        let mut env = TestEnv::fresh();
215        let db = env.db_path.clone();
216        let id = seed_memory(&db, "ns", "tt", "cc");
217        let mut args = empty_args(&id);
218        args.priority = Some(99);
219        let mut out = env.output();
220        let res = run(&db, &args, false, &mut out);
221        assert!(res.is_err());
222    }
223}