Skip to content

feat: tag-based filtering and management commands - #69

Merged
ajianaz merged 1 commit into
developfrom
feat/tag-filtering-management
May 29, 2026
Merged

ajianaz merged 1 commit into
developfrom
feat/tag-filtering-management

Conversation

@ajianaz

@ajianaz ajianaz commented May 29, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #42

Changes

New Type

  • TagInfo { name: String, count: usize } in memory/types.rs

Store Methods (memory/store.rs)

  • tags_with_counts() — aggregate all tags with usage counts
  • rename_tag(old, new) — rename a tag across all matching memories
  • delete_tag(tag) — remove a tag from all matching memories

Uteke Wrappers (lib.rs)

  • tags_with_counts(), rename_tag(), delete_tag() delegate to store

CLI (main.rs)

  • uteke tags list [--by-count] — list tags alphabetically or by count
  • uteke tags rename <old> <new> — rename tag across memories
  • uteke tags delete <tag> [--confirm] — delete tag (requires --confirm)

Tests

  • test_tags_with_counts — verifies count aggregation
  • test_rename_tag — verifies tag rename propagates
  • test_delete_tag — verifies tag removal from memories

All checks pass: cargo check, clippy, test (18/18), fmt.

Summary by CodeRabbit

  • New Features
    • Added tag management commands including list (with sort-by-count option), rename, and delete operations.
    • Tags now display usage counts in human-readable format.
    • Tag deletion requires explicit --confirm flag for safety.
    • Support for both JSON and human-readable output formats across tag operations.

Review Change Stack

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
@coderabbitai

coderabbitai Bot commented May 29, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

This PR introduces comprehensive tag management to uteke by adding a Tags CLI subcommand with list, rename, and delete operations. The implementation spans a new TagInfo type, Store-level tag analytics and mutations (rename/delete via JSON manipulation), public Uteke API wrappers, and CLI command handling with human-readable output and confirmation gates.

Changes

Tag Management Feature

Layer / File(s) Summary
Tag Info data contract
crates/uteke-core/src/memory/types.rs
TagInfo struct with name and count fields represents tag metadata for analytics output.
Store tag operations and tests
crates/uteke-core/src/memory/store.rs
tags_with_counts() lists unique tags with per-tag memory counts; rename_tag() parses and updates JSON arrays across matching memories; delete_tag() filters tags from JSON arrays. Tests verify tag counting, rename correctness, and deletion of tags from arrays.
Public Uteke API wrappers
crates/uteke-core/src/lib.rs
Three public methods delegate to Store operations and return tag counts or operation results. Re-export formatting adjusted for readability.
CLI Tags subcommand and handler
crates/uteke-cli/src/main.rs
Tags subcommand with list (optional count-based sort), rename (old/new names), and delete (with --confirm gate). Lists tags with human-readable or JSON output, renames with success messages, and deletes only when confirmed.

Sequence Diagram

sequenceDiagram
  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
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~30 minutes

Poem

🐰 Tags now bloom in uteke's garden,
Listed, renamed, and gently deleted,
JSON arrays dance through memories,
As CLI whispers commands anew—
Organization hops forward! 🌱

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Linked Issues check ❓ Inconclusive The PR implements tag management operations (list, rename, delete) from issue #42, but does not implement tag-aware filtering for recall/search or per-memory tag operations that are also listed in the issue objectives. Clarify whether partial implementation of #42 is intentional or if additional tag-aware search/recall filtering and per-memory tag operations are planned in follow-up PRs.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title 'feat: tag-based filtering and management commands' accurately describes the main changes: new CLI commands for tag listing, renaming, and deletion with supporting library APIs.
Out of Scope Changes check ✅ Passed All code changes are directly related to implementing global tag management commands (list, rename, delete) and supporting library APIs as specified in the linked issue requirements.
Docstring Coverage ✅ Passed Docstring coverage is 94.12% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/tag-filtering-management

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

📥 Commits

Reviewing files that changed from the base of the PR and between b92a7b1 and 849cf67.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (4)
  • crates/uteke-cli/src/main.rs
  • crates/uteke-core/src/lib.rs
  • crates/uteke-core/src/memory/store.rs
  • crates/uteke-core/src/memory/types.rs

Comment on lines +748 to +763
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()
);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

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.

Comment on lines +392 to +417
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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

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.

Comment on lines +422 to +508
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)
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

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.

Comment on lines +448 to +456
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()))?;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

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.

Suggested change
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.

@ajianaz
ajianaz merged commit aecc1ed into develop May 29, 2026
6 checks passed
@ajianaz
ajianaz deleted the feat/tag-filtering-management branch May 30, 2026 04:55
ajianaz added a commit that referenced this pull request Aug 13, 2026
feat: tag-based filtering and management commands
ajianaz added a commit that referenced this pull request Aug 13, 2026
- Add --tags option to CLI search command (comma-separated)
- Update Uteke::search() to accept tags_filter parameter
- Filter search results by tags, matching recall behavior
- Addresses CodeRabbit feedback on PR #69 (partial #42 implementation)

See: #42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat: tag-based filtering and management

1 participant