Repository navigation
feat: tag-based filtering and management commands - #69
Conversation
Add tag management commands: list with counts, rename, delete. - Add TagInfo type with name and count fields - Add store methods: tags_with_counts(), rename_tag(), delete_tag() - Add Uteke wrapper methods for tag operations - Add CLI Tags subcommand with List, Rename, Delete variants - Delete requires --confirm flag for safety - Add unit tests for all new store methods Closes #42
📝 WalkthroughWalkthroughThis PR introduces comprehensive tag management to uteke by adding a Tags CLI subcommand with list, rename, and delete operations. The implementation spans a new ChangesTag Management Feature
Sequence DiagramsequenceDiagram
participant CLI as CLI Handler
participant Uteke as Uteke API
participant Store as Store
CLI->>Uteke: tags_with_counts()
Uteke->>Store: tags_with_counts(namespace)
Store-->>Uteke: TagInfo list
Uteke-->>CLI: TagInfo list
CLI->>CLI: Sort by count or name
CLI->>CLI: Format output
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~30 minutes Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 inconclusive)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 4
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@crates/uteke-cli/src/main.rs`:
- Around line 748-763: The branch that runs when !confirm currently prints
human-readable lines then returns Err, which breaks --json output; update the
block that inspects tags from uteke.tags_with_counts(ns) and the match on info
(using variables confirm, tags, tag, info) to detect the CLI's JSON flag (the
existing --json boolean/flag) and, if JSON is requested, emit a single JSON-safe
object (e.g. containing error/message, tag name, and count) instead of the two
println! calls, and then return the error (or a JSON-formatted error) so no
human-readable lines are printed to stdout when --json is set. Ensure the
non-JSON behavior stays unchanged for interactive output.
In `@crates/uteke-core/src/memory/store.rs`:
- Around line 392-417: tags_with_counts calls unique_tags with namespace=None
but count_tag currently treats None as DEFAULT_NAMESPACE causing wrong zero
counts; update count_tag (or replace with count_tag_for_namespace) so it accepts
namespace: Option<&str> and, when namespace is None, runs a query without the
"namespace = ?" predicate (i.e. use "SELECT COUNT(*) FROM memories WHERE tags
LIKE ?") and when namespace is Some(ns) use the existing "namespace = ? AND tags
LIKE ?" query; ensure the pattern building (format!("%\"{tag}\"%")) and error
mapping to Error::Database remain unchanged so tags_with_counts returns correct
counts for all namespaces.
- Around line 422-508: The rename_tag and delete_tag functions currently treat
namespace=None as DEFAULT_NAMESPACE, which restricts mutations to the default
namespace; change both to interpret None as "no namespace filter" by building
two query branches: when namespace.is_some() prepare SQL "SELECT id, tags FROM
memories WHERE namespace = ?1 AND tags LIKE ?2" and call query_map with params
[ns, pattern], otherwise prepare SQL "SELECT id, tags FROM memories WHERE tags
LIKE ?1" and call query_map with only [pattern]; apply the same conditional
logic for the UPDATE statements if you need to include namespace in the WHERE
clause (use "UPDATE ... WHERE id = ?3" for global and "UPDATE ... WHERE
namespace = ?3 AND id = ?4" if keeping namespace filtering), and remove the
unwrap_or(DEFAULT_NAMESPACE) usage in rename_tag/delete_tag so None truly means
unfiltered/global.
- Around line 448-456: The rename loop can leave duplicates when replacing old
with new (e.g., ["rust","systems"] -> ["systems","systems"]); after the in-place
replacement (the for t in &mut tags { ... } block that sets changed = true and
before calling serde_json::to_string for new_tags_json), deduplicate the tags
vector so duplicate strings are removed while preserving first-seen order;
implement this by tracking seen values (e.g., a HashSet) and retaining only the
first occurrence (or alternatively sort+dedup if order does not matter), then
serialize the deduped tags and return Error::Database on serde failures as
before; remember to import std::collections::HashSet if you use it and reference
the tags, old, new, changed, and new_tags_json symbols in your change.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 6f8c0a18-5488-46cb-a43d-122a2611e358
⛔ Files ignored due to path filters (1)
Cargo.lockis excluded by!**/*.lock
📒 Files selected for processing (4)
crates/uteke-cli/src/main.rscrates/uteke-core/src/lib.rscrates/uteke-core/src/memory/store.rscrates/uteke-core/src/memory/types.rs
| if !confirm { | ||
| // Check if tag exists and show count | ||
| let tags = uteke | ||
| .tags_with_counts(ns) | ||
| .map_err(|e| format!("Failed to list tags: {e}"))?; | ||
| let info = tags.iter().find(|t| t.name == *tag); | ||
| match info { | ||
| Some(info) => { | ||
| println!( | ||
| "Tag '{}' is used by {} memory(ies).", | ||
| info.name, info.count | ||
| ); | ||
| println!("Use --confirm to proceed with deletion."); | ||
| return Err( | ||
| "Tag deletion not confirmed. Use --confirm flag.".to_string() | ||
| ); |
There was a problem hiding this comment.
Keep the confirmation failure JSON-safe under --json.
When --json is set, this branch still prints human-readable lines before returning an error. That makes uteke tags delete ... --json produce non-JSON stdout on a predictable failure path, which will break scripted callers.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@crates/uteke-cli/src/main.rs` around lines 748 - 763, The branch that runs
when !confirm currently prints human-readable lines then returns Err, which
breaks --json output; update the block that inspects tags from
uteke.tags_with_counts(ns) and the match on info (using variables confirm, tags,
tag, info) to detect the CLI's JSON flag (the existing --json boolean/flag) and,
if JSON is requested, emit a single JSON-safe object (e.g. containing
error/message, tag name, and count) instead of the two println! calls, and then
return the error (or a JSON-formatted error) so no human-readable lines are
printed to stdout when --json is set. Ensure the non-JSON behavior stays
unchanged for interactive output.
| pub fn tags_with_counts(&self, namespace: Option<&str>) -> Result<Vec<TagInfo>, Error> { | ||
| let tags = self.unique_tags(namespace)?; | ||
| let mut result = Vec::new(); | ||
| for tag in &tags { | ||
| let count = self.count_tag(tag, namespace)?; | ||
| result.push(TagInfo { | ||
| name: tag.clone(), | ||
| count, | ||
| }); | ||
| } | ||
| Ok(result) | ||
| } | ||
|
|
||
| /// Count how many memories use a specific tag. | ||
| fn count_tag(&self, tag: &str, namespace: Option<&str>) -> Result<usize, Error> { | ||
| let ns = namespace.unwrap_or(crate::memory::types::DEFAULT_NAMESPACE); | ||
| let pattern = format!("%\"{tag}\"%"); | ||
| let count: usize = self | ||
| .conn | ||
| .query_row( | ||
| "SELECT COUNT(*) FROM memories WHERE namespace = ?1 AND tags LIKE ?2", | ||
| rusqlite::params![ns, pattern], | ||
| |row| row.get(0), | ||
| ) | ||
| .map_err(|e| Error::Database(e.to_string()))?; | ||
| Ok(count) |
There was a problem hiding this comment.
Preserve None as “all namespaces” when counting tags.
tags_with_counts(None) currently calls unique_tags(None) across all namespaces, then count_tag(None) collapses back to DEFAULT_NAMESPACE. That can return tags from other namespaces with a 0 count, and it makes the API behavior inconsistent with the existing count/load_all semantics.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@crates/uteke-core/src/memory/store.rs` around lines 392 - 417,
tags_with_counts calls unique_tags with namespace=None but count_tag currently
treats None as DEFAULT_NAMESPACE causing wrong zero counts; update count_tag (or
replace with count_tag_for_namespace) so it accepts namespace: Option<&str> and,
when namespace is None, runs a query without the "namespace = ?" predicate (i.e.
use "SELECT COUNT(*) FROM memories WHERE tags LIKE ?") and when namespace is
Some(ns) use the existing "namespace = ? AND tags LIKE ?" query; ensure the
pattern building (format!("%\"{tag}\"%")) and error mapping to Error::Database
remain unchanged so tags_with_counts returns correct counts for all namespaces.
| pub fn rename_tag( | ||
| &self, | ||
| old: &str, | ||
| new: &str, | ||
| namespace: Option<&str>, | ||
| ) -> Result<usize, Error> { | ||
| let ns = namespace.unwrap_or(crate::memory::types::DEFAULT_NAMESPACE); | ||
| let pattern = format!("%\"{old}\"%"); | ||
| let sql = "SELECT id, tags FROM memories WHERE namespace = ?1 AND tags LIKE ?2"; | ||
| let mut stmt = self | ||
| .conn | ||
| .prepare(sql) | ||
| .map_err(|e| Error::Database(e.to_string()))?; | ||
|
|
||
| let rows: Vec<(String, String)> = stmt | ||
| .query_map(rusqlite::params![ns, pattern], |row| { | ||
| Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?)) | ||
| }) | ||
| .map_err(|e| Error::Database(e.to_string()))? | ||
| .filter_map(|r| r.ok()) | ||
| .collect(); | ||
|
|
||
| let mut updated = 0; | ||
| for (id, tags_str) in &rows { | ||
| let mut tags: Vec<String> = serde_json::from_str(tags_str).unwrap_or_default(); | ||
| let mut changed = false; | ||
| for t in &mut tags { | ||
| if t == old { | ||
| *t = new.to_string(); | ||
| changed = true; | ||
| } | ||
| } | ||
| if changed { | ||
| let new_tags_json = | ||
| serde_json::to_string(&tags).map_err(|e| Error::Database(e.to_string()))?; | ||
| let now = chrono::Utc::now().to_rfc3339(); | ||
| self.conn | ||
| .execute( | ||
| "UPDATE memories SET tags = ?1, updated_at = ?2 WHERE id = ?3", | ||
| rusqlite::params![new_tags_json, now, id], | ||
| ) | ||
| .map_err(|e| Error::Database(e.to_string()))?; | ||
| updated += 1; | ||
| } | ||
| } | ||
| Ok(updated) | ||
| } | ||
|
|
||
| /// Delete a tag from all memories (optionally filtered by namespace). | ||
| /// Returns the number of memories updated. | ||
| pub fn delete_tag(&self, tag: &str, namespace: Option<&str>) -> Result<usize, Error> { | ||
| let ns = namespace.unwrap_or(crate::memory::types::DEFAULT_NAMESPACE); | ||
| let pattern = format!("%\"{tag}\"%"); | ||
| let sql = "SELECT id, tags FROM memories WHERE namespace = ?1 AND tags LIKE ?2"; | ||
| let mut stmt = self | ||
| .conn | ||
| .prepare(sql) | ||
| .map_err(|e| Error::Database(e.to_string()))?; | ||
|
|
||
| let rows: Vec<(String, String)> = stmt | ||
| .query_map(rusqlite::params![ns, pattern], |row| { | ||
| Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?)) | ||
| }) | ||
| .map_err(|e| Error::Database(e.to_string()))? | ||
| .filter_map(|r| r.ok()) | ||
| .collect(); | ||
|
|
||
| let mut updated = 0; | ||
| for (id, tags_str) in &rows { | ||
| let mut tags: Vec<String> = serde_json::from_str(tags_str).unwrap_or_default(); | ||
| let before_len = tags.len(); | ||
| tags.retain(|t| t != tag); | ||
| if tags.len() != before_len { | ||
| let new_tags_json = | ||
| serde_json::to_string(&tags).map_err(|e| Error::Database(e.to_string()))?; | ||
| let now = chrono::Utc::now().to_rfc3339(); | ||
| self.conn | ||
| .execute( | ||
| "UPDATE memories SET tags = ?1, updated_at = ?2 WHERE id = ?3", | ||
| rusqlite::params![new_tags_json, now, id], | ||
| ) | ||
| .map_err(|e| Error::Database(e.to_string()))?; | ||
| updated += 1; | ||
| } | ||
| } | ||
| Ok(updated) | ||
| } |
There was a problem hiding this comment.
Don’t force global tag mutations into the default namespace.
Both mutation paths turn None into DEFAULT_NAMESPACE, so rename_tag(..., None) and delete_tag(..., None) only touch the default namespace. That prevents the advertised unfiltered/global behavior and makes uteke tags rename/delete miss non-default memories unless the caller loops namespaces manually.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@crates/uteke-core/src/memory/store.rs` around lines 422 - 508, The rename_tag
and delete_tag functions currently treat namespace=None as DEFAULT_NAMESPACE,
which restricts mutations to the default namespace; change both to interpret
None as "no namespace filter" by building two query branches: when
namespace.is_some() prepare SQL "SELECT id, tags FROM memories WHERE namespace =
?1 AND tags LIKE ?2" and call query_map with params [ns, pattern], otherwise
prepare SQL "SELECT id, tags FROM memories WHERE tags LIKE ?1" and call
query_map with only [pattern]; apply the same conditional logic for the UPDATE
statements if you need to include namespace in the WHERE clause (use "UPDATE ...
WHERE id = ?3" for global and "UPDATE ... WHERE namespace = ?3 AND id = ?4" if
keeping namespace filtering), and remove the unwrap_or(DEFAULT_NAMESPACE) usage
in rename_tag/delete_tag so None truly means unfiltered/global.
| for t in &mut tags { | ||
| if t == old { | ||
| *t = new.to_string(); | ||
| changed = true; | ||
| } | ||
| } | ||
| if changed { | ||
| let new_tags_json = | ||
| serde_json::to_string(&tags).map_err(|e| Error::Database(e.to_string()))?; |
There was a problem hiding this comment.
Deduplicate when renaming into an existing tag.
If a memory already has new, this rewrite leaves duplicate tags behind instead of merging them. For example, renaming rust -> systems on ["rust", "systems"] serializes ["systems", "systems"].
Possible fix
for t in &mut tags {
if t == old {
*t = new.to_string();
changed = true;
}
}
if changed {
+ tags.dedup();
let new_tags_json =
serde_json::to_string(&tags).map_err(|e| Error::Database(e.to_string()))?;📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| for t in &mut tags { | |
| if t == old { | |
| *t = new.to_string(); | |
| changed = true; | |
| } | |
| } | |
| if changed { | |
| let new_tags_json = | |
| serde_json::to_string(&tags).map_err(|e| Error::Database(e.to_string()))?; | |
| for t in &mut tags { | |
| if t == old { | |
| *t = new.to_string(); | |
| changed = true; | |
| } | |
| } | |
| if changed { | |
| tags.dedup(); | |
| let new_tags_json = | |
| serde_json::to_string(&tags).map_err(|e| Error::Database(e.to_string()))?; |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@crates/uteke-core/src/memory/store.rs` around lines 448 - 456, The rename
loop can leave duplicates when replacing old with new (e.g., ["rust","systems"]
-> ["systems","systems"]); after the in-place replacement (the for t in &mut
tags { ... } block that sets changed = true and before calling
serde_json::to_string for new_tags_json), deduplicate the tags vector so
duplicate strings are removed while preserving first-seen order; implement this
by tracking seen values (e.g., a HashSet) and retaining only the first
occurrence (or alternatively sort+dedup if order does not matter), then
serialize the deduped tags and return Error::Database on serde failures as
before; remember to import std::collections::HashSet if you use it and reference
the tags, old, new, changed, and new_tags_json symbols in your change.
feat: tag-based filtering and management commands
Closes #42
Changes
New Type
TagInfo { name: String, count: usize }inmemory/types.rsStore Methods (
memory/store.rs)tags_with_counts()— aggregate all tags with usage countsrename_tag(old, new)— rename a tag across all matching memoriesdelete_tag(tag)— remove a tag from all matching memoriesUteke Wrappers (
lib.rs)tags_with_counts(),rename_tag(),delete_tag()delegate to storeCLI (
main.rs)uteke tags list [--by-count]— list tags alphabetically or by countuteke tags rename <old> <new>— rename tag across memoriesuteke tags delete <tag> [--confirm]— delete tag (requires --confirm)Tests
test_tags_with_counts— verifies count aggregationtest_rename_tag— verifies tag rename propagatestest_delete_tag— verifies tag removal from memoriesAll checks pass: cargo check, clippy, test (18/18), fmt.
Summary by CodeRabbit
--confirmflag for safety.