Skip to content

feat: v0.0.8 — Stability & Architecture - #160

Merged
ajianaz merged 7 commits into
developfrom
feature/v0.0.8
Jun 4, 2026
Merged

ajianaz merged 7 commits into
developfrom
feature/v0.0.8

Conversation

@ajianaz

@ajianaz ajianaz commented Jun 3, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Major overhaul: god module split, input validation, schema versioning, error handling, Python wrapper.

Closes

Also

Tests

  • 116 pass (up from 96 in v0.0.7)
  • 0 warnings in release build

Files

  • 21 files changed: +3667 / -2405

Co-Authored-By: codecoradev [email protected]

Summary by CodeRabbit

Release Notes

  • New Features

    • Added memory consolidation to find and merge similar memories based on configurable similarity thresholds.
    • Introduced namespace management for isolated memory contexts.
    • Added comprehensive diagnostics: health checks, consistency verification, and automatic index repair.
    • Implemented memory aging and TTL-based cleanup for automatic lifecycle management.
    • Added import/export in JSONL format.
    • Expanded CLI with agent integration setup (Pi, Claude, Cursor).
    • Added checksum verification command.
  • Performance & Infrastructure

    • Added benchmark tool to measure performance across memory scales.
    • Optimized production builds with compiler settings.
    • Implemented server-mode request routing and payload validation.
  • Documentation

    • Updated project version and added design philosophy section.
    • Expanded server mode documentation with endpoint table.
    • Added performance benchmarking section with methodology and scaling notes.
    • Revised roadmap with demand-gated framing.

@coderabbitai

coderabbitai Bot commented Jun 3, 2026 •

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@ajianaz, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 25 minutes and 40 seconds. Learn how PR review limits work.

Your organization has run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: ea689b0f-6b76-47b7-9ef0-4cf89c805b5a

📥 Commits

Reviewing files that changed from the base of the PR and between 3565358 and 9a8d847.

📒 Files selected for processing (8)
  • CHANGELOG.md
  • Cargo.toml
  • crates/uteke-cli/src/commands.rs
  • crates/uteke-core/src/consolidate.rs
  • crates/uteke-core/src/error.rs
  • crates/uteke-core/src/import_export.rs
  • crates/uteke-core/src/maintenance.rs
  • crates/uteke-core/src/memory/store.rs
📝 Walkthrough

Walkthrough

This PR performs a comprehensive refactoring of the Uteke memory system library and CLI tooling. It introduces a new error handling system with sanitization, modularizes the core library by extracting operations into submodules, implements maintenance and consolidation workflows, redesigns CLI dispatch across separate modules, expands the Python wrapper with namespace support and full API coverage, and updates documentation with performance benchmarks.

Changes

Uteke System Refactoring and API Expansion

Layer / File(s) Summary
Error system and diagnostic types
crates/uteke-core/src/error.rs, crates/uteke-core/src/types.rs
Error enum with db/embed/lock constructors that sanitize underlying errors and emit warnings; diagnostic report types (DoctorStatus, DoctorCheck, DoctorReport, VerifyReport, RepairReport) for health/consistency operations.
Library entrypoint refactoring
crates/uteke-core/src/lib.rs
Reshapes lib.rs as module entrypoint with submodule declarations and re-exports; adds MAX_*_LENGTH validation constants and validate_input function; introduces TierConfig for configurable memory tiering; extends Uteke with open_with_embedder and open_with_tier constructors; removes large impl Uteke block (moved to submodules).
Embedding engine and vector index error mapping
crates/uteke-core/src/embed/engine.rs, crates/uteke-core/src/memory/vector.rs
Updates EmbeddingEngine and VectorIndex error handling to use new Error::embed constructors for model loading, tensor operations, index persistence, and HTTP downloads.
Core memory operations
crates/uteke-core/src/operations.rs
Implements remember, recall, search, forget, bulk delete variants, list, get, namespace/tag management methods; embeds queries, searches vectors, applies namespace/tag filtering, manages access tracking and tier-based scoring.
Store persistence and schema versioning
crates/uteke-core/src/memory/store.rs
Adds CURRENT_SCHEMA_VERSION and migration infrastructure; refactors all CRUD/query operations to use standardized Error::db mapping; updates JSON deserialization with corruption warnings and fallback defaults; extends schema with access-tracking and deprecation columns.
Memory consolidation and maintenance
crates/uteke-core/src/consolidate.rs, crates/uteke-core/src/maintenance.rs
Implements consolidation (check_contradiction, remember_with_contradiction, find_duplicates, consolidate) and maintenance operations (doctor, verify, repair, stats, aging_preview, aging_cleanup, prune, shutdown) with health reporting and aging tier management.
JSONL import and export
crates/uteke-core/src/import_export.rs
Implements export (memory snapshots without embeddings) and import (re-embeds, validates, writes vector index first then store with rollback) with namespace support.
CLI output formatting
crates/uteke-cli/src/output.rs
Centralizes JSON and human-readable formatters for all command types (memories, tags, stats, health/consistency reports, aging status) with empty-state handling, byte scaling, and content truncation.
CLI main refactoring and dispatch
crates/uteke-cli/src/main.rs, crates/uteke-cli/src/commands.rs
Refactors main.rs to declare and delegate to commands, init, output modules; adds VerifyChecksums command; delegates Init to init::run_init_command; implements comprehensive run_command dispatcher for all subcommands with namespace resolution, confirmation gating, dry-run output, and optional server HTTP routing.
Agent initialization
crates/uteke-cli/src/init.rs
Implements agent-specific init workflows for pi (creates .agents/skills/uteke-memory with SKILL.md), claude (writes UTEKE.md with conditional CLAUDE.md reference), and cursor (creates .cursor/rules/uteke.mdc) with JSON or human-readable output.
Performance benchmarking
Cargo.toml, crates/uteke-cli/Cargo.toml, crates/uteke-cli/src/bench.rs
Adds [profile.bench] optimization settings (opt-level = 3, lto = true); implements memory-bench binary measuring operation performance (remember, recall, search, list, consolidate, bulk_forget_all) across dataset sizes with per-operation timing metrics.
Server payload validation
crates/uteke-server/src/main.rs
Adds Content-Length header validation for POST requests; rejects payloads exceeding MAX_PAYLOAD_SIZE with HTTP 413 JSON error response.
Python wrapper expansion
examples/python_hermes.py
Extends UtekeMemory with optional namespace parameter across all API methods; adds comprehensive public methods for consolidation, pruning, namespace management, tag operations, memory aging, diagnostics, and import/export; updates smoke test for namespace isolation validation.
Documentation and roadmap
README.md
Updates version badge to v0.0.7; adds Design Philosophy section; expands Server Mode with API endpoint table; introduces Performance section with benchmarks and scaling notes; updates roadmap with demand-gated framing (v0.0.8, Phases A/B/C).

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • ajianaz/uteke#30: Directly related—implements health-check/repair functionality (Uteke::doctor, verify, repair) with the same maintenance module and output/command dispatch wiring.
  • ajianaz/uteke#22: Overlaps on JSONL export/import portability end-to-end (core Uteke import/export logic and CLI command wiring).
  • ajianaz/uteke#91: Overlaps at CLI server-routing/local dispatcher logic (is_server_running/run_via_server/run_command and related command handling branches).

🐰 In modular harmony we stand,
Each layer now in its rightful land,
Errors flow with clarity and care,
CLI commands everywhere!
A refactor grand, with tests in hand—
Uteke's future truly planned! ✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title clearly summarizes the main change: a major v0.0.8 release focused on stability and architecture improvements through code reorganization, input validation, error handling, and expanded features.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/v0.0.8

Warning

Review ran into problems

🔥 Problems

Stopped waiting for pipeline failures after 30000ms. One of your pipelines takes longer than our 30000ms fetch window to run, so review may not consider pipeline-failure results for inline comments if any failures occurred after the fetch window. Increase the timeout if you want to wait longer or run a @coderabbit review after the pipeline has finished.


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.

@github-actions

github-actions Bot commented Jun 3, 2026 •

Copy link
Copy Markdown

🔍 Cora AI Code Review

⚠️ Review could not complete. Cora produced an empty result. Check the workflow logs for errors.


Review powered by cora-cli · BYOK · MIT

@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: 2

Note

Due to the large number of review comments, Critical severity comments were prioritized as inline comments.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (5)
crates/uteke-core/src/lib.rs (1)

181-185: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Derive the index filename from the database filename.

Every on-disk store in the same directory currently maps to the same uteke_index.usearch path. Opening foo.sqlite and bar.sqlite side by side will make them share and overwrite one vector index.

💡 Proposed fix
-        let index_path = store.path().map(|p| {
-            let dir = p.parent().unwrap_or(Path::new("."));
-            dir.join("uteke_index.usearch")
-        });
+        let index_path = store.path().map(|p| {
+            let dir = p.parent().unwrap_or(Path::new("."));
+            let stem = p.file_stem().and_then(|s| s.to_str()).unwrap_or("uteke");
+            dir.join(format!("{stem}.usearch"))
+        });
🤖 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/lib.rs` around lines 181 - 185, The current index_path
closure always returns "uteke_index.usearch" so different DB files share one
index; update the closure used when computing index_path (the code around
store.path() and the index_path variable in lib.rs) to derive the index filename
from the database filename (use Path::file_stem() or file_name() on the Path p)
and join that with a suffix like "_uteke_index.usearch" (falling back to a
sensible default if file_stem/file_name is None) so each DB (e.g., foo.sqlite ->
foo_uteke_index.usearch) gets its own index file.
examples/python_hermes.py (2)

22-22: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

consolidate()'s return annotation doesn't match its own contract.

The docstring says non-dry_run returns a summary dict, but the signature promises a list. That makes the new typed API lie to callers.

Suggested fix
-from typing import Any, Dict, List, Optional
+from typing import Any, Dict, List, Optional, Union
@@
-    ) -> List[Dict[str, Any]]:
+    ) -> Union[List[Dict[str, Any]], Dict[str, Any]]:

Also applies to: 290-312

🤖 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 `@examples/python_hermes.py` at line 22, The consolidate() function's return
type annotation contradicts its docstring/contract (it currently types as
List[...] but when dry_run is False it actually returns a summary dict); update
the typing to match the real behavior either by adding proper typing.overload
signatures (one overload for dry_run=True -> List[str] and one for dry_run=False
-> Dict[str, Any]) or by changing the single return annotation to
Union[List[str], Dict[str, Any]] (and import Union/overload as needed); apply
the same change for the other consolidate implementation/occurrence referenced
around lines 290-312 so both signatures match the documented contract.

97-105: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Stop echoing raw CLI arguments in wrapper exceptions.

These messages can include full memory content, queries, tags, and import/export paths, which undoes the sanitized-error work in this PR and can leak user data into logs.

Suggested fix
         except subprocess.CalledProcessError as exc:
             stderr = exc.stderr.strip() if exc.stderr else ""
             raise UtekeError(
-                f"uteke {' '.join(args)} failed: {stderr}",
+                f"uteke command failed: {stderr}",
                 returncode=exc.returncode,
             ) from exc
         except subprocess.TimeoutExpired as exc:
             raise UtekeError(
-                f"uteke {' '.join(args)} timed out after 30s"
+                "uteke command timed out after 30s"
             ) from exc
🤖 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 `@examples/python_hermes.py` around lines 97 - 105, The exception handlers that
raise UtekeError currently interpolate the raw args list (args) into the error
message (in the subprocess.CalledProcessError and subprocess.TimeoutExpired
handlers), which can leak sensitive data; change those messages to avoid echoing
raw CLI arguments—use a generic command identifier (e.g., "uteke") and optional
metadata like returncode or a sanitized stderr snippet instead of f" {'
'.join(args)}". Update the CalledProcessError branch to include exc.returncode
and a trimmed/sanitized stderr variable (do not include args), and update the
TimeoutExpired branch to remove args from the timed-out message and optionally
include the timeout value or process id if needed; keep the exception type
raising UtekeError in both places and preserve exception chaining (from exc).
crates/uteke-core/src/embed/engine.rs (1)

37-45: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Write downloaded model files atomically.

Lines 37-45 treat mere file existence as a complete cache hit, but Lines 156-157 write straight to the final path. If the process is interrupted during the write, the next startup will skip the download and keep failing on the partial model until the cache is manually cleaned. Download to a temp file and rename only after the write succeeds.

Also applies to: 156-157

🤖 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/embed/engine.rs` around lines 37 - 45, The current
download logic treats existence of model_path, model_data_path, and
tokenizer_path as complete but writes directly to those final paths (see
download_hf_file usage), which can leave partial files on interrupt; update the
download process to write to a temporary file in the same directory (e.g.,
model_path.with_extension("tmp") or using a secure temp mechanism), ensure the
full content is flushed and closed, then atomically rename/move the temp file to
the final path (using std::fs::rename or equivalent) for model_path,
model_data_path, and tokenizer_path; also ensure errors during download/delete
of the temp file are handled so partial files won't be treated as cache hits on
next startup (apply same change for the code around the current write at the
later write site referenced).
crates/uteke-core/src/memory/store.rs (1)

530-539: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Compare timestamps as datetimes, not raw TEXT.

These queries compare RFC3339 strings written by to_rfc3339() against datetime('now', ...), which uses a different text format. SQLite will do lexicographic comparison here, so aging and TTL pruning can misclassify rows. Wrap the stored columns with datetime(...) (or store numeric epochs) everywhere this pattern appears.

Possible fix
- AND created_at < datetime('now', '-' || ?2 || ' days')
+ AND datetime(created_at) < datetime('now', '-' || ?2 || ' days')

- AND (last_accessed IS NULL OR last_accessed < datetime('now', '-' || ?4 || ' days'))
+ AND (last_accessed IS NULL OR datetime(last_accessed) < datetime('now', '-' || ?4 || ' days'))

- AND datetime(updated_at) < datetime('now', '-' || ?2 || ' days')
+ AND datetime(updated_at) < datetime('now', '-' || ?2 || ' days')

Also applies to: 571-577, 880-885

🤖 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 530 - 539, The SQL is
comparing stored RFC3339 TEXT values lexicographically against datetime('now',
...) which is incorrect; update the WHERE clauses in the queries built in this
file (the sql string used for pruning in the function that prepares the "SELECT
... FROM memories" query and the other noted queries) to convert stored
timestamp columns using datetime(...), e.g. use datetime(created_at) and
datetime(last_accessed) (and datetime(valid_from)/datetime(valid_until where
used) ) on the left-hand side so comparisons use actual datetimes, or
alternatively switch to storing numeric epochs and compare those; apply the same
change to the other similar queries in this file that filter by created_at,
last_accessed, valid_from, or valid_until.
🟠 Major comments (24)
crates/uteke-cli/src/init.rs-16-23 (1)

16-23: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

run_init rejects documented agent values (copilot, codex).

run_init currently errors for agents that the CLI contract advertises (see crates/uteke-cli/src/main.rs Lines 162-167). This creates a user-facing command contract break.

Suggested fix (align runtime behavior with declared CLI contract)
 pub(crate) fn run_init(agent: &str, json: bool) -> Result<(), String> {
     match agent {
         "pi" => init_pi(json),
         "claude" => init_claude(json),
         "cursor" => init_cursor(json),
+        "copilot" => init_claude(json),
+        "codex" => init_claude(json),
         _ => Err(format!(
-            "Unknown agent: {agent}. Supported: pi, claude, cursor"
+            "Unknown agent: {agent}. Supported: pi, claude, cursor, copilot, codex"
         )),
     }
 }
🤖 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/init.rs` around lines 16 - 23, run_init currently
rejects documented agents like "copilot" and "codex" because the match in
run_init only handles "pi", "claude", and "cursor"; update that match to include
arms for the documented aliases by adding "copilot" and "codex" arms. Map
"copilot" and "codex" to the appropriate initializer functions (e.g., add
"copilot" => init_pi(...) and/or "codex" => init_cursor(...) as the CLI contract
expects) so run_init accepts the documented values while keeping init_pi,
init_claude, and init_cursor unchanged.
crates/uteke-server/src/main.rs-466-469 (1)

466-469: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Fix double-encoded error payload in 413 response.

At Line 468, error_response is given a JSON string instead of a plain message, so clients get {"error":"{\"error\":\"Payload too large\"}"} instead of {"error":"Payload too large"}.

Suggested fix
-                    let response = error_response(
-                        413,
-                        serde_json::json!({"error": "Payload too large"}).to_string(),
-                    );
+                    let response = error_response(413, "Payload too large");
🤖 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-server/src/main.rs` around lines 466 - 469, The 413 response is
double-encoding the JSON because error_response is being passed a JSON string;
change the call to pass the JSON value (or a plain message) instead of
serde_json::json!(...).to_string() so error_response receives the raw
value/message; locate the call to error_response in main.rs (the 413 branch) and
remove the .to_string() (or construct the payload as a non-string) so the
resulting client payload is {"error":"Payload too large"} rather than a nested
JSON string.
crates/uteke-server/src/main.rs-459-475 (1)

459-475: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Enforce payload limit even when Content-Length is missing or malformed.

The current guard is header-dependent only. If Content-Length is absent/invalid, the request still reaches read_body (Line 124) which does an unbounded read_to_string, so oversized bodies can still consume memory.

Suggested fix (header check + bounded body read)
-fn read_body<T: serde::de::DeserializeOwned>(reader: &mut dyn IoRead) -> Result<T, String> {
+fn read_body<T: serde::de::DeserializeOwned>(
+    reader: &mut dyn IoRead,
+    max_bytes: usize,
+) -> Result<T, String> {
     let mut body = String::new();
-    reader
+    reader
+        .take((max_bytes as u64) + 1)
         .read_to_string(&mut body)
         .map_err(|e| format!("Failed to read body: {e}"))?;
+    if body.len() > max_bytes {
+        return Err("Payload too large".to_string());
+    }
     serde_json::from_str(&body).map_err(|e| format!("Invalid JSON: {e}"))
 }

And update call sites, e.g.:

-(&Method::Post, "/remember") => match read_body::<RememberRequest>(body) {
+(&Method::Post, "/remember") => match read_body::<RememberRequest>(body, uteke_core::MAX_PAYLOAD_SIZE) {
🤖 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-server/src/main.rs` around lines 459 - 475, The POST
payload-size check currently only uses Content-Length and lets requests with
missing/invalid headers reach read_body (which does unbounded read), so change
handling for Method::Post to enforce the limit regardless: when Content-Length
is missing/invalid, perform a bounded read of the request body using a reader
limited to uteke_core::MAX_PAYLOAD_SIZE + 1 bytes (e.g., via Read::take) and
reject with error_response(413, ...) if more than MAX_PAYLOAD_SIZE bytes are
read; also update the read_body call sites (and any helpers named read_body) to
accept/perform a bounded read so no unbounded read_to_string path remains.
crates/uteke-cli/src/bench.rs-100-155 (1)

100-155: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Fail fast on benchmark operation errors instead of discarding Results.

Line 102, Line 115, Line 129, Line 142, Line 148, and Line 154 currently swallow failures, so reported timings can be invalid while appearing successful.

Suggested fix
-        for (content, tags) in &memories {
+        for (content, tags) in &memories {
             let tags_ref: Vec<&str> = tags.iter().map(|s| s.as_str()).collect();
-            let _ = uteke.remember(content, &tags_ref, None, Some("bench"));
+            uteke
+                .remember(content, &tags_ref, None, Some("bench"))
+                .expect("benchmark insert failed");
         }
@@
         let recall_start = Instant::now();
         for query in RECALL_QUERIES {
-            let _ = black_box(uteke.recall(query, 5, None, Some("bench")));
+            black_box(
+                uteke
+                    .recall(query, 5, None, Some("bench"))
+                    .expect("benchmark recall failed"),
+            );
         }
@@
         let search_start = Instant::now();
         for query in RECALL_QUERIES {
-            let _ = black_box(uteke.search(query, 5, None, Some("bench")));
+            black_box(
+                uteke
+                    .search(query, 5, None, Some("bench"))
+                    .expect("benchmark search failed"),
+            );
         }
@@
-        let _ = black_box(uteke.list(None, size, 0, Some("bench")));
+        black_box(
+            uteke
+                .list(None, size, 0, Some("bench"))
+                .expect("benchmark list failed"),
+        );
@@
-        let _ = black_box(uteke.consolidate(Some("bench"), 0.90, false));
+        black_box(
+            uteke
+                .consolidate(Some("bench"), 0.90, false)
+                .expect("benchmark consolidate failed"),
+        );
@@
-        let _ = black_box(uteke.bulk_forget_all(Some("bench")));
+        black_box(
+            uteke
+                .bulk_forget_all(Some("bench"))
+                .expect("benchmark forget_all failed"),
+        );
🤖 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/bench.rs` around lines 100 - 155, The benchmark
currently swallows Results from multiple Uteke calls (uteke.remember,
uteke.recall, uteke.search, uteke.list, uteke.consolidate,
uteke.bulk_forget_all) which can hide failures and corrupt timings; modify the
benchmark to fail fast by handling each Result instead of discarding it—either
propagate errors by changing the benchmark function signature to return Result
and using the ? operator on each call, or call .expect("bench: <operation>
failed")/unwrap with a clear message for each operation (remember, recall,
search, list, consolidate, bulk_forget_all) so any error aborts immediately and
timing reflects only successful runs.
crates/uteke-core/src/maintenance.rs-117-124 (1)

117-124: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Propagate index.save() failures from mutating maintenance commands.

repair(), aging_cleanup(), and prune() all return success even if the rebuilt/cleaned index was never persisted. After restart, the DB and on-disk index can diverge again while the command has already reported success.

Possible fix
-            index.save().ok();
+            index.save()?;

Also applies to: 218-227, 258-267

🤖 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/maintenance.rs` around lines 117 - 124, The repair(),
aging_cleanup(), and prune() paths currently call index.save().ok(), swallowing
persistence errors; change them to propagate failures so callers see when the
on-disk index wasn't written. Replace the index.save().ok() calls inside the
mutex block (the code that calls index.build(...) and index.save()) with proper
error handling that returns Err on save failure (e.g., map the save error into
the function's Error type and use ? or propagate it), ensuring the functions
return an error instead of success when index.save() fails.
crates/uteke-core/src/import_export.rs-11-20 (1)

11-20: ⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift

The public export/import format drops namespace information.

ExportEntry does not carry a namespace, but import() assigns every record to namespace.unwrap_or(DEFAULT_NAMESPACE). That means export(None) followed by import(None) flattens all namespaces into one and breaks isolation for library callers, even though this API advertises cross-namespace export.

Also applies to: 69-83

🤖 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/import_export.rs` around lines 11 - 20, The
export/import flow currently drops namespace info because ExportEntry lacks a
namespace field and import() assigns namespace.unwrap_or(DEFAULT_NAMESPACE),
causing all records to be imported into a single namespace; to fix, add a
namespace: Option<String> (or String) to ExportEntry, populate it in export()
from each memory's namespace (where memories come from store.load_all / the
memory struct), and update import() to use the exported entry's namespace when
present (falling back to the function-level namespace parameter or
DEFAULT_NAMESPACE only for legacy entries without a namespace). Update related
serialization/deserialization and tests to ensure namespace is preserved across
export/import for ExportEntry, export(), and import().
crates/uteke-core/src/consolidate.rs-31-31 (1)

31-31: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Don't turn store read failures into “no contradiction.”

if let Ok(Some(memory)) = self.store.get_by_id(id) suppresses Err(_) and silently continues. A transient DB failure here becomes a false negative, so remember_with_contradiction() can insert conflicting data instead of surfacing the failure.

🤖 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/consolidate.rs` at line 31, The current use of `if let
Ok(Some(memory)) = self.store.get_by_id(id)` in `consolidate.rs` swallows
`Err(_)` from `self.store.get_by_id` and treats transient read failures as “no
contradiction”; change this to explicitly handle the `Result` from
`self.store.get_by_id(id)`—i.e., match on `Ok(Some(_))`, `Ok(None)`, and
`Err(e)`—and on `Err(e)` propagate or return the error from
`remember_with_contradiction()` (or the surrounding function) instead of
continuing, so database read failures surface instead of being treated as absent
memory. Ensure you update any return types or use `?` where appropriate so
`remember_with_contradiction()` correctly returns the underlying storage error.
crates/uteke-core/src/maintenance.rs-42-58 (1)

42-58: ⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift

Count equality is not a real consistency check.

Both doctor() and verify() mark the index healthy when the counts match, but that still misses orphaned IDs or wrong vectors. A stale index with the same cardinality will be reported as consistent, which is a false positive for the very command users rely on before skipping repair.

Also applies to: 82-96

🤖 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/maintenance.rs` around lines 42 - 58, The current check
in doctor() (and similarly in verify()) only compares db_count vs index_count
(db_count, index_count) which yields false positives; instead implement an
actual ID-level consistency check: fetch the set/list of document IDs from the
DB and the set of IDs from the index (the code paths around the "Index
consistency" DoctorCheck creation), compute missing-in-index and
orphaned-in-index sets, and update the DoctorCheck (name "Index consistency",
status DoctorStatus::Ok/Error, detail) to report mismatches (e.g., counts plus
examples or counts of missing/orphaned IDs and advice to run `uteke repair`) so
equality without matching IDs is not treated as Ok.
crates/uteke-core/src/consolidate.rs-183-208 (1)

183-208: ⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift

Pick the survivor by timestamp, not by pair order.

consolidate() always deletes pair.id_a, but find_duplicates() only preserves iteration order; it never proves that id_a is the older record. That makes the “keeps newer, removes older” contract incorrect and can delete the newer memory.

🤖 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/consolidate.rs` around lines 183 - 208, consolidate
currently deletes pair.id_a unconditionally which can remove the newer memory;
change logic in consolidate (around iterating pairs and using pair.id_a /
pair.id_b) to pick the survivor by comparing timestamps rather than pair order:
for each pair, load or use the timestamp fields for id_a and id_b (e.g.,
pair.timestamp_a / pair.timestamp_b or fetch the two records from the store) to
determine which is newer, mark the older id for delete and the newer id as kept,
update already_removed, removed_ids, and kept_ids accordingly, and call
store.delete on the older id (not always id_a); ensure errors still map to
Error::db("consolidate delete", e).
crates/uteke-core/src/consolidate.rs-48-53 (1)

48-53: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Avoid logging raw memory content in contradiction detection.

These snippets come from user-authored memories and can contain secrets or PII. Logging the IDs and similarity is enough for diagnostics without copying content into the log stream.

🤖 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/consolidate.rs` around lines 48 - 53, The log currently
prints raw user memory text via memory.content and content; replace that with
non-sensitive identifiers and the similarity score. Update the tracing::info
call that references similarity, memory.content and content to log similarity
plus memory.id (or memory.key/stable identifier) and the candidate's id (e.g.,
candidate_id or other identifier available where content is used) instead of
including the actual content strings; if no identifier exists, derive and log a
non-reversible fingerprint (hash) of the content rather than the raw text.
crates/uteke-core/src/import_export.rs-46-65 (1)

46-65: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Reuse validate_input() for imported records.

This path only rejects empty content, so whitespace-only content, oversized content, too many tags, and overlong tags all bypass the limits enforced by the normal write path in crates/uteke-core/src/lib.rs. Import should apply the same validation contract before embedding.

Possible fix
-            if entry.content.is_empty() {
+            if crate::validate_input(&entry.content, &entry.tags).is_err() {
                 skipped += 1;
                 continue;
             }
🤖 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/import_export.rs` around lines 46 - 65, Import path
currently only rejects empty content; before re-embedding each ExportEntry call
the existing validate_input(...) used by the write path (the validate_input
function in crate utek-core/src/lib.rs) with the imported entry's content and
tags to enforce whitespace, size, tag count and tag length limits; if
validate_input returns an error, increment skipped and continue (same behavior
as other validation failures) and only proceed to lock self.embedder and call
embed(...) when validate_input succeeds.
examples/python_hermes.py-240-245 (1)

240-245: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Only collapse the actual not-found case into None / False.

Catching every UtekeError here hides timeouts, invalid namespaces, JSON parse failures, and other CLI errors as ordinary misses. That turns real operational failures into silent data-path behavior.

Also applies to: 261-270

🤖 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 `@examples/python_hermes.py` around lines 240 - 245, The current broad except
UtekeError swallows all CLI failures; change the handler in the method that
calls self._run(self._ns_args(namespace) + ["get", memory_id]) so it only
returns None for a genuine "not found" condition (e.g., inspect the caught
UtekeError's error code/message or a specific subclass like NotFoundError) and
re-raise any other UtekeError (timeouts, invalid namespace, JSON parse issues).
Apply the same selective handling to the similar block around lines 261-270;
reference the symbols UtekeError, _run, _ns_args and _parse_json when locating
and fixing the handlers.
examples/python_hermes.py-52-59 (1)

52-59: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Make the subprocess timeout configurable before exposing long-running commands.

A fixed 30s limit is likely to break valid import_from, repair, doctor, and first-run model-loading flows on larger stores. The expanded wrapper needs a caller-tunable timeout instead of a hard stop baked into _run.

Suggested fix
     def __init__(
         self,
         store_path: str = "~/.uteke",
         namespace: Optional[str] = None,
+        timeout_seconds: int = 30,
     ) -> None:
         self.store_path = os.path.expanduser(store_path)
         self._namespace = namespace
         self._uteke_bin = os.environ.get("UTEKE_BIN", "uteke")
+        self._timeout_seconds = timeout_seconds
@@
             result = subprocess.run(
                 cmd,
                 capture_output=True,
                 text=True,
                 check=True,
-                timeout=30,
+                timeout=self._timeout_seconds,
             )
@@
         except subprocess.TimeoutExpired as exc:
             raise UtekeError(
-                "uteke command timed out after 30s"
+                f"uteke command timed out after {self._timeout_seconds}s"
             ) from exc

Also applies to: 90-105

🤖 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 `@examples/python_hermes.py` around lines 52 - 59, The class currently
hardcodes a 30s subprocess timeout which will break long-running flows; add a
configurable timeout in __init__ (e.g. parameter name subprocess_timeout or
timeout with default value) and store it on the instance
(self._subprocess_timeout or self._timeout), then update the internal runner
method _run to use that instance timeout (and accept an optional per-call
timeout override) instead of the fixed 30s; ensure callers like import_from,
repair, doctor and any first-run model-loading paths call _run without assuming
30s so they inherit the configurable timeout.
examples/python_hermes.py-347-353 (1)

347-353: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Keep the wrapper's default namespace in sync with namespace_switch().

Right now this updates the CLI config but not self._namespace, so instances created with an explicit namespace keep issuing commands against the old namespace after a switch.

Suggested fix
     def namespace_switch(self, name: str) -> None:
         """Set the default namespace in the Uteke config.
@@
         """
         self._run(["namespace", "switch", name])
+        self._namespace = name
🤖 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 `@examples/python_hermes.py` around lines 347 - 353, The namespace_switch
method updates the CLI config but doesn't update the wrapper's in-memory
default, so change namespace_switch (in the class where self._namespace exists)
to set self._namespace = name after the successful self._run(["namespace",
"switch", name]) call so the wrapper and new instances use the switched
namespace; ensure this assignment happens only when the command completes
without raising.
crates/uteke-cli/src/commands.rs-26-28 (1)

26-28: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Use the same namespace resolution on the server path as the local path.

run_command() uses resolve_namespace(cli, config), but the server path falls back straight to "default". That means UTEKE_NAMESPACE and config.store.namespace are silently ignored whenever server routing is enabled, so the same command can hit different namespaces depending on transport.

🤖 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/commands.rs` around lines 26 - 28, run_via_server
currently hardcodes the namespace to "default" and bypasses the same resolution
used by run_command; update run_via_server to accept the configuration (or
otherwise access the same Config used by run_command) and call
resolve_namespace(cli, config) to determine ns instead of using
cli.namespace.as_deref().unwrap_or("default"), ensuring it uses UTEKE_NAMESPACE
and config.store.namespace the same way run_command does. Adjust the function
signature and call sites accordingly so run_via_server and run_command resolve
namespaces identically.
crates/uteke-cli/src/commands.rs-17-22 (1)

17-22: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Treat only successful /health responses as “server running”.

This currently returns true for any HTTP response, including 404/500, so main() can route the CLI to a broken or unrelated service on that port. Check response.status().is_success() before declaring the server available.

🤖 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/commands.rs` around lines 17 - 22, is_server_running
currently treats any HTTP response as success; change it to only return true
when the GET to "{url}/health" both succeeds and returns an HTTP success status.
In the map/closure for Client::build, call send() and then check
response.status().is_success() (e.g., map send() result to
response.status().is_success()), returning false on any error—so the final chain
should only produce true for a successful send with
response.status().is_success(). Ensure the function still unwraps the build
error to false (as it does now).
crates/uteke-cli/src/commands.rs-207-209 (2)

207-209: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Stop logging raw memory content and search queries at INFO.

main.rs now persists INFO logs to ~/.uteke/uteke.log by default, so these statements write remembered content and recall/search queries to disk even without --verbose. That is a privacy/compliance regression for a memory store that may contain secrets or PII.

Also applies to: 260-260, 278-278

🤖 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/commands.rs` around lines 207 - 209, The code is logging
raw memory content and search queries at INFO (tracing::info! calls that include
the `content`, `type`, and `detect_contradiction` variables), which persists
sensitive data to disk; change these log sites to not emit raw content at INFO —
either downgrade to tracing::debug! or remove the `content`/query payload from
the message and log only non-sensitive metadata (e.g., `type` and
`detect_contradiction`), and apply this change for the same logging statements
around the earlier mentioned instances (the tracing::info! at the shown diff and
the similar calls at the other locations). Ensure no raw `content` or query
strings are written to INFO-level logs.

207-209: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

The local non-contradiction path drops --type entirely.

remember --type ... is only forwarded when detect_contradiction is enabled. In the normal local path you pass None, while the server path includes "type" in its request body, so behavior changes depending on execution mode.

Also applies to: 246-248

🤖 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/commands.rs` around lines 207 - 209, The local path for
the remember command drops the "--type" value when detect_contradiction is
false, causing behavior to differ from the server path; update the local
handling so the "type" value is forwarded (not set to None) regardless of
detect_contradiction. Locate the code around the tracing::info! that logs
"Remembering: {content} (type: {type}, contradiction: {detect_contradiction})"
and ensure the same "type" field included in the server request body is also
included in the local request/struct construction (apply the same change at the
other occurrence around lines 246-248), preserving the variable name type and
passing it through to the local remember logic.
crates/uteke-cli/src/commands.rs-141-184 (1)

141-184: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Unsupported forget --cold/--all variants should fall back locally, not hard-fail in server mode.

This match arm claims Commands::Forget is server-supported, but only implements id and --tag. When the server is enabled, uteke forget --cold / --all now exits with Provide an ID... instead of hitting the working local implementation.

crates/uteke-cli/src/commands.rs-773-785 (1)

773-785: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Parse CHECKSUMS.txt entries strictly and check sha256sum exit status.

find(|l| l.contains(binary_filename)) can match the wrong artifact (uteke vs uteke-server), and a failed sha256sum invocation is treated like a mismatch based on empty stdout. Parse the filename field exactly and reject non-zero command exits before comparing hashes.

🤖 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/commands.rs` around lines 773 - 785, The checksum lookup
and verification need to be made strict: instead of find(|l|
l.contains(binary_filename)), parse each line of checksums into fields (e.g.,
split_whitespace) and match the filename field exactly against binary_filename
so you don't confuse names like "uteke" vs "uteke-server"; extract the
expected_hash from the hash field of that parsed line. Also check the Command
output status (output.status.success()) and return an error if sha256sum exited
non-zero before reading stdout; only then parse stdout to get actual_hash and
compare to expected_hash (return a clear error if the expected entry is missing,
the command fails, or hashes mismatch). Use the variables shown (checksums,
expected_line/expected_hash, binary_filename, binary, actual_hash) to locate and
update the logic.
crates/uteke-cli/src/commands.rs-48-53 (1)

48-53: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Handle non-2xx server responses before decoding success payloads.

These branches call resp.json() directly, so validation/server errors get surfaced as parse failures or even as bogus success output instead of the actual server error. Gate on error_for_status() first, then decode either the success schema or the server's error body.

Also applies to: 69-75, 91-97, 113-119, 128-134, 149-157, 164-173

🤖 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/commands.rs` around lines 48 - 53, The code calls
resp.json() directly after sending requests (e.g., the block that does
client.post(...).json(&body).send() and stores into resp), which hides non-2xx
server responses as parse errors; change each such flow to first check
resp.error_for_status() (or resp.status().is_success()) and only then decode the
success payload with resp.json(); if error_for_status returns Err, read the
response body (resp.text() or resp.json() into serde_json::Value) and return a
formatted error including that body so server error details surface. Apply the
same fix to every occurrence that currently calls resp.json() directly (the
other resp handling blocks in this file).
crates/uteke-core/src/memory/store.rs-770-781 (1)

770-781: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Make bulk deletes atomic before handing control back to the vector layer.

These methods collect IDs and then delete rows one-by-one outside a transaction. If one DELETE fails midway, some rows are already gone from SQLite but the error aborts before operations.rs receives the deleted ID list, so the vector index never removes those entries and the two stores drift apart. Wrap the select+delete sequence in a transaction and only return after commit.

Also applies to: 794-805, 813-824

🤖 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 770 - 781, The
select-then-delete sequence is non-atomic: collect ids into ids and then call
self.conn.execute in a loop; wrap the SELECT and the DELETE loop in a single
SQLite transaction so either all deletes succeed or none are committed. Use
rusqlite's Transaction (e.g., let tx = self.conn.transaction()?) and run the
prepare/query_map against tx, collect ids, perform the DELETEs via tx.execute,
then tx.commit() before returning; apply the same pattern to the other similar
blocks at the ranges referenced (the blocks around the ids collection and DELETE
loop at lines ~794-805 and ~813-824) so the select+delete is atomic and errors
roll back automatically.
crates/uteke-core/src/operations.rs-172-189 (1)

172-189: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Push tag filtering down before applying limit.

search_content(query, namespace, limit) caps the SQL result set first, then Lines 176-184 discard rows that miss tags_filter. If the first limit text matches don't have the requested tag, this returns too few results even when later matches do exist. Move the tag predicate into Store::search_content or over-fetch until limit tagged rows survive.

🤖 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/operations.rs` around lines 172 - 189, The results are
being limited by self.store.search_content(query, namespace, limit) before
applying tags_filter, which can drop matching tagged rows; update the flow so
tagged filtering happens before the limit by either (preferred) extending
Store::search_content to accept an optional tags_filter parameter and apply the
tag predicate inside Store::search_content (i.e. modify the
Store::search_content signature and SQL/logic to filter by tags), or
(alternative) over-fetch by calling self.store.search_content with a higher
limit (e.g., limit * N or limit + buffer), apply the tags_filter in the existing
iterator, then truncate the collected SearchResult vec to the requested limit;
refer to self.store.search_content, tags_filter, SearchResult and
Store::search_content when making the change.
crates/uteke-core/src/embed/engine.rs-140-143 (1)

140-143: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Configure explicit timeouts (and make model writes atomic) for HF model downloads.

The current download uses a blocking client with no explicit timeout settings:

let response = reqwest::blocking::Client::new()
    .get(&url)
    .send()
    .map_err(|e| Error::embed("download model file", e))?;

Since download_hf_file() also writes directly to local_path via std::fs::write, an interrupted write can leave a partial/corrupt file that future startups will skip because they only check Path::exists().

  • Set explicit connect/read/total timeouts on the reqwest::blocking::Client (rather than relying on defaults).
  • Download to a temporary file and rename atomically into local_path after success.
🤖 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/embed/engine.rs` around lines 140 - 143, The
download_hf_file logic must use a reqwest blocking client with explicit timeouts
and perform atomic writes: replace Client::new() with a Client built via
reqwest::blocking::Client::builder() and set connect_timeout and an overall
timeout (Duration values you choose) before build(), then use that client to
send the request; write the response body to a temporary file (e.g., local_path
with a ".tmp" suffix or a tempfile) and only after the write completes and is
flushed/closed, atomically rename (std::fs::rename) the temp file into
local_path so partial downloads cannot leave corrupt files; update error
handling around the client build, send, file write, and rename in
download_hf_file to map_err with Error::embed as before.
🟡 Minor comments (4)
README.md-157-165 (1)

157-165: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Correct /forget API contract wording for namespace deletion.

The server route does not support namespace-only deletion; it supports ?id= or ?tag= (with optional namespace when deleting by tag). Current wording can mislead API users.

Suggested fix
-| `/forget` | DELETE | Delete by id, tag, or namespace |
+| `/forget` | DELETE | Delete by id (`?id=`) or by tag (`?tag=` with optional `&namespace=`) |
🤖 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 `@README.md` around lines 157 - 165, Update the README entry for the `/forget`
endpoint to accurately reflect the server contract: state that `/forget`
supports deletion by `?id=` or by `?tag=` (and when deleting by tag you may
optionally provide `namespace=`), and explicitly note that namespace-only
deletion is not supported; modify the table row for `/forget` to replace "Delete
by id, tag, or namespace" with a precise phrasing like "Delete by id (`?id=`) or
by tag (`?tag=`) — optional `namespace=` allowed with tag; namespace-only
deletion not supported" so users of the `GET /forget` route understand the exact
query parameters.
crates/uteke-cli/src/init.rs-142-143 (1)

142-143: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Claude success message is inaccurate when no reference was inserted.

At Line 142, existence of CLAUDE.md is treated as “reference added,” but Lines 126-130 only add it conditionally. This can report a write that never happened.

Suggested fix (track whether insertion occurred)
-    if claude_md.exists() {
+    let mut reference_added = false;
+    if claude_md.exists() {
         let existing = std::fs::read_to_string(&claude_md)
             .map_err(|e| format!("Failed to read CLAUDE.md: {e}"))?;
         if !existing.contains("UTEKE.md") {
             let updated = format!("{existing}\n\n## Uteke Memory\n\nSee [UTEKE.md](UTEKE.md) for uteke memory commands.\n");
             std::fs::write(&claude_md, updated)
                 .map_err(|e| format!("Failed to update CLAUDE.md: {e}"))?;
+            reference_added = true;
         }
     }
@@
-        if claude_md.exists() {
-            println!("  Reference added to CLAUDE.md");
+        if claude_md.exists() && reference_added {
+            println!("  Reference added to CLAUDE.md");
+        } else if claude_md.exists() {
+            println!("  CLAUDE.md already references UTEKE.md");
         } else {
             println!("  Tip: Create CLAUDE.md and add a reference to UTEKE.md");
         }
🤖 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/init.rs` around lines 142 - 143, The success message
incorrectly assumes a reference was inserted whenever claude_md.exists() is
true; instead track whether an insertion actually occurred (e.g., introduce a
boolean like claude_inserted or claude_written) at the point where you perform
the conditional write (the code around the existing insertion logic that
checks/creates CLAUDE.md), set that flag to true only when you write/insert, and
change the println! that currently checks claude_md.exists() to check the new
flag (e.g., if claude_inserted { println!("  Reference added to CLAUDE.md"); }).
Ensure the flag is initialized false and only flipped on successful write so the
message accurately reflects the operation.
crates/uteke-cli/src/bench.rs-23-27 (1)

23-27: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Handle temp directory setup failures explicitly.

Line 25 and Line 26 ignore filesystem errors, which can mask root causes and make size runs fail ambiguously.

Suggested fix
 fn bench_dir() -> PathBuf {
     let dir = std::env::temp_dir().join("uteke-bench");
-    let _ = std::fs::remove_dir_all(&dir);
-    let _ = std::fs::create_dir_all(&dir);
+    if dir.exists() {
+        std::fs::remove_dir_all(&dir).expect("failed to clean benchmark directory");
+    }
+    std::fs::create_dir_all(&dir).expect("failed to create benchmark directory");
     dir
 }
🤖 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/bench.rs` around lines 23 - 27, The bench_dir function
currently swallows IO errors from std::fs::remove_dir_all and
std::fs::create_dir_all; change it to surface failures by returning a
Result<PathBuf, std::io::Error> (or propagate using ?), and call
remove_dir_all(&dir)? and create_dir_all(&dir)? (or use expect with a clear
message) so errors are not ignored. Update any callers of bench_dir to handle
the Result if you choose to return one; keep the function name bench_dir and
preserve the use of std::env::temp_dir for locating the directory.
crates/uteke-core/src/lib.rs-44-48 (1)

44-48: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Fix “characters” validation to avoid UTF-8 byte counting (validate_input)

  • validate_input uses content.len() and t.len() (UTF-8 byte length) while MAX_CONTENT_LENGTH/MAX_TAG_LENGTH and the error messages label the limits as “chars”; multibyte input will be rejected too early.
💡 Proposed fix
-    if content.len() > MAX_CONTENT_LENGTH {
+    let content_chars = content.chars().count();
+    if content_chars > MAX_CONTENT_LENGTH {
         return Err(Error::Validation(format!(
             "Content too long: {} chars (max {})",
-            content.len(),
+            content_chars,
             MAX_CONTENT_LENGTH
         )));
     }
@@
     for tag in tags {
         let t = tag.as_ref();
         if t.is_empty() {
             return Err(Error::Validation("Tags must not be empty".into()));
         }
-        if t.len() > MAX_TAG_LENGTH {
+        let tag_chars = t.chars().count();
+        if tag_chars > MAX_TAG_LENGTH {
             return Err(Error::Validation(format!(
                 "Tag too long: {} chars (max {})",
-                t.len(),
+                tag_chars,
                 MAX_TAG_LENGTH
             )));
         }
     }
🤖 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/lib.rs` around lines 44 - 48, validate_input currently
compares UTF-8 byte lengths (content.len(), t.len()) against
MAX_CONTENT_LENGTH/MAX_TAG_LENGTH and reports "chars", which mislabels multibyte
input; change the checks and the values used in the error message to use
character counts (e.g. content.chars().count() and t.chars().count()) instead of
byte lengths, update the error messages to print those character counts, and
ensure the comparisons in the validate_input function reference these char
counts when enforcing MAX_CONTENT_LENGTH and MAX_TAG_LENGTH.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: a1ded6b4-8013-4568-93dc-8f2555307951

📥 Commits

Reviewing files that changed from the base of the PR and between 707e819 and c2695ae.

📒 Files selected for processing (21)
  • .github/workflows/release.yml
  • Cargo.toml
  • README.md
  • crates/uteke-cli/Cargo.toml
  • crates/uteke-cli/src/bench.rs
  • crates/uteke-cli/src/commands.rs
  • crates/uteke-cli/src/init.rs
  • crates/uteke-cli/src/main.rs
  • crates/uteke-cli/src/output.rs
  • crates/uteke-core/src/consolidate.rs
  • crates/uteke-core/src/embed/engine.rs
  • crates/uteke-core/src/error.rs
  • crates/uteke-core/src/import_export.rs
  • crates/uteke-core/src/lib.rs
  • crates/uteke-core/src/maintenance.rs
  • crates/uteke-core/src/memory/store.rs
  • crates/uteke-core/src/memory/vector.rs
  • crates/uteke-core/src/operations.rs
  • crates/uteke-core/src/types.rs
  • crates/uteke-server/src/main.rs
  • examples/python_hermes.py

Comment thread .github/workflows/release.yml Resolved
Comment thread crates/uteke-core/src/consolidate.rs Resolved
CTO Hermes and others added 2 commits June 4, 2026 13:38
Closes #130 #131 #132 #134 #138 #139 #144 #137

Architecture:
- Split lib.rs (1471→352) and main.rs (1538→422) into focused modules
- Core: operations, maintenance, consolidate, error, types, import_export
- CLI: commands, init, output, bench

Validation (#132):
- Max content 10K chars, max 20 tags, max server payload 1MB

Binary integrity (#134):
- SHA256 checksums in release artifacts (CHECKSUMS.txt)
- verify-checksums subcommand

Schema versioning (#138):
- schema_version table + migration framework

Reliability (#139):
- Fix deadlock in check_contradiction (mutex re-acquire)

Error handling (#144):
- Error enum rewrite with sanitized user-friendly messages
- ~90 call sites migrated from raw rusqlite/usearch/ONNX errors
- Lock errors now include operation context
- 7 new unit tests for sanitization

Python wrapper (#137):
- 7→21 methods covering all CLI commands
- Namespace support on all methods
- Full type hints + Google-style docstrings

Benchmark (#49):
- memory-bench binary for library-level timing

README:
- Badge v0.0.7, Design Philosophy section
- Performance section with actual benchmark data
- Removed knowledge graph from roadmap

Tests: 116 pass (+20 from v0.0.7)

Co-Authored-By: codecoradev <[email protected]>
CTO Hermes added 2 commits June 4, 2026 14:19
- check_contradiction: now read-only, no mutation during check
- Deprecation happens AFTER new memory is persisted (prevents data loss)
- Version bump 0.0.7 → 0.0.8
- CHANGELOG v0.0.8 entry

Fixes CodeRabbit review on consolidate.rs rollback path
Rust 1.96 clippy enforces io::Error::other() over
io::Error::new(ErrorKind::Other, ...)

@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: 8

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
crates/uteke-core/src/lib.rs (2)

181-189: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Derive the vector index filename from the DB filename.

Line 184 hard-codes one index file per directory, so foo.sqlite and bar.sqlite in the same folder will load and mutate the same uteke_index.usearch. That breaks store isolation because all remember/search operations now share one HNSW index while SQLite remains split by database.

Proposed fix
         let index_path = store.path().map(|p| {
-            let dir = p.parent().unwrap_or(Path::new("."));
-            dir.join("uteke_index.usearch")
+            p.with_extension("usearch")
         });
🤖 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/lib.rs` around lines 181 - 189, The code currently
computes index_path from the DB directory only, causing different DB files in
the same folder to share one index; change index_path generation to derive the
index filename from the DB filename (use the DB file stem or name and
append/replace with a unique index suffix) so each SQLite DB gets its own index
file; update the closure that builds index_path (the map on store.path()) to
obtain the DB file stem via store.path().map(|p| { let stem = p.file_stem()... }
) and join that stem with a per-db index name before passing the resulting path
to VectorIndex::load_or_create (keep fallback to VectorIndex::new when
index_path is None), leaving VectorIndex::load_or_create and
EmbeddingEngine::dims() usage unchanged.

329-333: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Restore UTEKE_HOME instead of clobbering process state.

Line 330 mutates a process-global env var and Line 333 always removes it, so this test can race with parallel tests and also destroys any preexisting UTEKE_HOME. Please capture the prior value and restore it under a test-local guard, or run this test serially.

🤖 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/lib.rs` around lines 329 - 333, The test
test_uteke_home_with_env mutates the process-global UTEKE_HOME and
unconditionally removes it, which can clobber concurrent tests; capture the
prior value with std::env::var_os("UTEKE_HOME") before setting the env, then
after the assertion restore it (if Some(v) set_var("UTEKE_HOME", v) else
remove_var("UTEKE_HOME")). Update the test body in test_uteke_home_with_env to
save the old value, set the env, run the assertion, and finally restore the
original value so process state is preserved.
examples/python_hermes.py (1)

76-107: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

UtekeError now leaks memory content and file paths in failure messages.

_run() formats the public exception with ' '.join(args), so failures on remember(...), search(...), import_from(...), etc. echo raw memory text and local paths into agent logs. That undercuts the sanitized-error work in the core crate; surface only the subcommand name here and keep full args out of user-facing errors.

🤖 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 `@examples/python_hermes.py` around lines 76 - 107, The _run method builds
UtekeError messages by joining full args which can leak memory content and file
paths; change the error formatting inside the subprocess exception handlers so
you only surface the subcommand name (use args[0] or similar) instead of '
'.join(args), and include only sanitized details (e.g., stripped stderr or a
generic message) in the UtekeError for both CalledProcessError and
TimeoutExpired; update the messages created in the except blocks that raise
UtekeError (refer to _run, UtekeError, subprocess.run and self._uteke_bin) so no
raw argument payloads or paths are included in user-facing errors.
🧹 Nitpick comments (1)
examples/python_hermes.py (1)

628-641: ⚡ Quick win

The smoke test doesn't actually prove cross-namespace isolation.

After inserting via mem_ns, the script never re-checks the original mem view. A regression that writes into both namespaces can still pass this test.

Suggested assertion
         stats_ns = mem_ns.stats()
         print(f"Namespace stats: {stats_ns['total_memories']} memories")
+        default_stats = mem.stats()
+        assert default_stats["total_memories"] == 0, (
+            "default namespace should stay empty after namespaced insert"
+        )
 
         ok_ns = mem_ns.forget(mid_ns)
🤖 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 `@examples/python_hermes.py` around lines 628 - 641, The current smoke test
using UtekeMemory (mem_ns.remember -> mid_ns) only checks namespace-local
recall/stats/forget but never verifies the original mem instance is unaffected;
update the test to assert cross-namespace isolation by calling
mem.recall("namespace") and mem.stats() after the mem_ns.remember operation and
asserting that mem does not contain mid_ns (e.g., recall length unchanged and
stats['total_memories'] unchanged), and ensure mem.forget(mid_ns) is False or
leaves mem unchanged to catch regressions where writes leak across namespaces;
reference UtekeMemory.remember, UtekeMemory.recall, UtekeMemory.stats,
UtekeMemory.forget, mem_ns, mem, and mid_ns when making this change.
🤖 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-core/src/import_export.rs`:
- Around line 12-20: The export logic (export/ExportEntry) drops each memory's
namespace when mapping memories from self.store.load_all, causing import() to
collapse everything into namespace.unwrap_or(DEFAULT_NAMESPACE); fix by adding a
namespace field to ExportEntry and populate it from m.namespace in the export
mapping (the block building ExportEntry), then update import() to prefer the
exported entry.namespace when present and only fall back to the provided
namespace argument or DEFAULT_NAMESPACE for older exports; ensure import handles
missing namespace for backward compatibility.
- Around line 47-85: The import path currently only checks
entry.content.is_empty() and skips other validations enforced by remember() (max
content length ~10K, max tags, non-whitespace content), so extract or call the
shared validation used by remember()/server (e.g., the remember validation
routine) before re-embedding: validate entry.content length, trim/ensure
non-whitespace, validate tags count/format and any other limits, and
return/skips + increment skipped on failure; perform this validation right after
deserializing ExportEntry (before calling self.embedder.lock()/.embed()) so
invalid rows are not embedded or persisted and behavior matches
remember()/server. Ensure you reference ExportEntry, Memory, and the
embedder.lock()/embed() call when making the change.

In `@crates/uteke-core/src/lib.rs`:
- Around line 44-48: The validation currently uses str::len() (byte length) for
checks like comparing content.len() against MAX_CONTENT_LENGTH (and similar
checks for tags), which incorrectly rejects multibyte characters; update those
checks to use character counts (e.g. content.chars().count()) instead of .len(),
apply the same change to tag/name length checks, and make the error message
values reflect the character counts so the reported "chars" numbers match the
validation logic (references: uses of content.len() and tag.len() in the
validation code and constants like MAX_CONTENT_LENGTH).

In `@examples/python_hermes.py`:
- Around line 226-245: The get method currently catches all UtekeError and
returns None, hiding real failures; change the except block to only swallow the
specific "not found" case and re-raise other errors: after calling
self._run(...) wrap in try/except UtekeError as e, detect the not-found
condition (e.g. inspect e.code or e.message for the CLI's "not found" sentinel
or add a small helper like _is_not_found_error(e)), return None only when that
check is true, otherwise raise; apply the same change to the other method
referenced at 247-270 so only genuine not-found responses are converted to
None/False and all other UtekeError instances propagate.
- Around line 347-353: The namespace_switch method performs the CLI call but
doesn't update the wrapper's stored namespace, leaving self._namespace stale;
after successfully running self._run(["namespace", "switch", name]) in
namespace_switch, set self._namespace = name (or handle normalization if other
code expects a specific format) so subsequent commands that reference
self._namespace use the new value; locate the namespace_switch method and update
it to assign the new name to the instance field after the successful call.

In `@README.md`:
- Line 374: The README's roadmap entry "v0.0.8 (next)" conflicts with the PR's
objectives and the version badge; either update the roadmap to reflect that this
PR is the release (change the string "v0.0.8 (next)" to "v0.0.8 (current
release)" and add a new "v0.0.9 (next)" entry) or, if the release is still
forthcoming, keep "v0.0.8 (next)" but align the PR title/objectives and the
version badge so they indicate a pre-release state; locate and update the
"v0.0.8 (next)" roadmap string and the version badge text to make the README and
PR consistent.
- Line 245: Update the search speedup value in the README table row that
currently reads "| **Search (avg/query)** | 3,158ms | 9ms | **367x** |" to the
correct value: compute 3158 / 9 = 350.89 and replace "**367x**" with "**351x**"
(rounded). Ensure the table cell string is updated exactly to "| **Search
(avg/query)** | 3,158ms | 9ms | **351x** |".

---

Outside diff comments:
In `@crates/uteke-core/src/lib.rs`:
- Around line 181-189: The code currently computes index_path from the DB
directory only, causing different DB files in the same folder to share one
index; change index_path generation to derive the index filename from the DB
filename (use the DB file stem or name and append/replace with a unique index
suffix) so each SQLite DB gets its own index file; update the closure that
builds index_path (the map on store.path()) to obtain the DB file stem via
store.path().map(|p| { let stem = p.file_stem()... } ) and join that stem with a
per-db index name before passing the resulting path to
VectorIndex::load_or_create (keep fallback to VectorIndex::new when index_path
is None), leaving VectorIndex::load_or_create and EmbeddingEngine::dims() usage
unchanged.
- Around line 329-333: The test test_uteke_home_with_env mutates the
process-global UTEKE_HOME and unconditionally removes it, which can clobber
concurrent tests; capture the prior value with std::env::var_os("UTEKE_HOME")
before setting the env, then after the assertion restore it (if Some(v)
set_var("UTEKE_HOME", v) else remove_var("UTEKE_HOME")). Update the test body in
test_uteke_home_with_env to save the old value, set the env, run the assertion,
and finally restore the original value so process state is preserved.

In `@examples/python_hermes.py`:
- Around line 76-107: The _run method builds UtekeError messages by joining full
args which can leak memory content and file paths; change the error formatting
inside the subprocess exception handlers so you only surface the subcommand name
(use args[0] or similar) instead of ' '.join(args), and include only sanitized
details (e.g., stripped stderr or a generic message) in the UtekeError for both
CalledProcessError and TimeoutExpired; update the messages created in the except
blocks that raise UtekeError (refer to _run, UtekeError, subprocess.run and
self._uteke_bin) so no raw argument payloads or paths are included in
user-facing errors.

---

Nitpick comments:
In `@examples/python_hermes.py`:
- Around line 628-641: The current smoke test using UtekeMemory (mem_ns.remember
-> mid_ns) only checks namespace-local recall/stats/forget but never verifies
the original mem instance is unaffected; update the test to assert
cross-namespace isolation by calling mem.recall("namespace") and mem.stats()
after the mem_ns.remember operation and asserting that mem does not contain
mid_ns (e.g., recall length unchanged and stats['total_memories'] unchanged),
and ensure mem.forget(mid_ns) is False or leaves mem unchanged to catch
regressions where writes leak across namespaces; reference UtekeMemory.remember,
UtekeMemory.recall, UtekeMemory.stats, UtekeMemory.forget, mem_ns, mem, and
mid_ns when making this 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: e67c24dd-1d67-4bfb-8444-0203d8972710

📥 Commits

Reviewing files that changed from the base of the PR and between c2695ae and 3565358.

📒 Files selected for processing (20)
  • Cargo.toml
  • README.md
  • crates/uteke-cli/Cargo.toml
  • crates/uteke-cli/src/bench.rs
  • crates/uteke-cli/src/commands.rs
  • crates/uteke-cli/src/init.rs
  • crates/uteke-cli/src/main.rs
  • crates/uteke-cli/src/output.rs
  • crates/uteke-core/src/consolidate.rs
  • crates/uteke-core/src/embed/engine.rs
  • crates/uteke-core/src/error.rs
  • crates/uteke-core/src/import_export.rs
  • crates/uteke-core/src/lib.rs
  • crates/uteke-core/src/maintenance.rs
  • crates/uteke-core/src/memory/store.rs
  • crates/uteke-core/src/memory/vector.rs
  • crates/uteke-core/src/operations.rs
  • crates/uteke-core/src/types.rs
  • crates/uteke-server/src/main.rs
  • examples/python_hermes.py
✅ Files skipped from review due to trivial changes (1)
  • crates/uteke-cli/Cargo.toml
🚧 Files skipped from review as they are similar to previous changes (15)
  • crates/uteke-server/src/main.rs
  • Cargo.toml
  • crates/uteke-core/src/memory/vector.rs
  • crates/uteke-core/src/embed/engine.rs
  • crates/uteke-core/src/types.rs
  • crates/uteke-cli/src/bench.rs
  • crates/uteke-core/src/consolidate.rs
  • crates/uteke-cli/src/init.rs
  • crates/uteke-cli/src/commands.rs
  • crates/uteke-core/src/error.rs
  • crates/uteke-cli/src/output.rs
  • crates/uteke-core/src/maintenance.rs
  • crates/uteke-core/src/operations.rs
  • crates/uteke-cli/src/main.rs
  • crates/uteke-core/src/memory/store.rs

Comment on lines +12 to +20
let memories = self.store.load_all(namespace)?;
let entries: Vec<ExportEntry> = memories
.into_iter()
.map(|m| ExportEntry {
content: m.content,
tags: m.tags,
metadata: m.metadata,
created_at: m.created_at,
})

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 | 🏗️ Heavy lift

Full-store export/import currently drops namespace isolation.

export(None) can emit memories from multiple namespaces, but ExportEntry omits m.namespace and import() rewrites every row into namespace.unwrap_or(DEFAULT_NAMESPACE). A round-trip of the whole store therefore collapses everything into one namespace.

Also applies to: 70-78

🤖 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/import_export.rs` around lines 12 - 20, The export
logic (export/ExportEntry) drops each memory's namespace when mapping memories
from self.store.load_all, causing import() to collapse everything into
namespace.unwrap_or(DEFAULT_NAMESPACE); fix by adding a namespace field to
ExportEntry and populate it from m.namespace in the export mapping (the block
building ExportEntry), then update import() to prefer the exported
entry.namespace when present and only fall back to the provided namespace
argument or DEFAULT_NAMESPACE for older exports; ensure import handles missing
namespace for backward compatibility.

Comment on lines +47 to +85
let entry: ExportEntry = match serde_json::from_str(line) {
Ok(e) => e,
Err(_) => {
skipped += 1;
continue;
}
};

if entry.content.is_empty() {
skipped += 1;
continue;
}

// Re-embed the content
let embedding = self
.embedder
.lock()
.map_err(|_| Error::lock("embedder lock during import"))?
.embed(&entry.content)?;

let id = uuid::Uuid::new_v4().to_string();
let now = chrono::Utc::now();

let memory = Memory {
id: id.clone(),
content: entry.content,
embedding: embedding.clone(),
tags: entry.tags,
metadata: entry.metadata,
created_at: entry.created_at,
updated_at: now,
namespace: namespace.unwrap_or(DEFAULT_NAMESPACE).to_string(),
access_count: 0,
last_accessed: None,
deprecated: false,
valid_from: Some(entry.created_at),
valid_until: None,
memory_type: "fact".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

Reuse the shared input validation before embedding/importing.

This path only rejects entry.content.is_empty(), so JSONL imports can still persist records that violate the new v0.0.8 limits (>10K content, too many tags, whitespace-only content, etc.) that remember() and the server now reject. That creates data the rest of the API won't accept and burns embedding work on invalid rows.

🤖 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/import_export.rs` around lines 47 - 85, The import path
currently only checks entry.content.is_empty() and skips other validations
enforced by remember() (max content length ~10K, max tags, non-whitespace
content), so extract or call the shared validation used by remember()/server
(e.g., the remember validation routine) before re-embedding: validate
entry.content length, trim/ensure non-whitespace, validate tags count/format and
any other limits, and return/skips + increment skipped on failure; perform this
validation right after deserializing ExportEntry (before calling
self.embedder.lock()/.embed()) so invalid rows are not embedded or persisted and
behavior matches remember()/server. Ensure you reference ExportEntry, Memory,
and the embedder.lock()/embed() call when making the change.

Comment on lines +87 to +116
// Write-ahead: vector index first (can be rolled back), then SQLite.
{
let mut index = self
.index
.lock()
.map_err(|_| Error::lock("index lock during import"))?;
index.insert(&id, &embedding);
// Don't save per-item — we'll persist once after the full import.
}

if let Err(e) = self.store.insert(&memory) {
// Rollback: remove from vector index
let mut index = self
.index
.lock()
.map_err(|_| Error::lock("index lock during import rollback"))?;
index.remove(&id);
return Err(e);
}

imported += 1;
}

// Persist vector index after import completes
if imported > 0 {
let mut index = self
.index
.lock()
.map_err(|_| Error::lock("index lock during import save"))?;
index.save()?;

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 | 🏗️ Heavy lift

import() is not crash-safe across SQLite and the persisted vector index.

Earlier rows are committed to SQLite before the index is durably saved. If any later store.insert() fails, or if the final index.save() fails, import() returns with rows already in the DB but missing from the persisted index, so they disappear from recall/search after restart until a repair runs. This needs a real rollback boundary for the successfully inserted rows, not just rollback of the current vector entry.

Comment on lines +44 to +48
if content.len() > MAX_CONTENT_LENGTH {
return Err(Error::Validation(format!(
"Content too long: {} chars (max {})",
content.len(),
MAX_CONTENT_LENGTH

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

Use character counts here, not byte counts.

Line 44 and Line 63 use str::len(), but this API documents character limits. Multibyte input will hit the limit early, so valid non-ASCII content/tags get rejected under the advertised 10K/50-character caps.

Proposed fix
 pub fn validate_input(content: &str, tags: &[impl AsRef<str>]) -> Result<(), Error> {
     if content.trim().is_empty() {
         return Err(Error::Validation("Content must not be empty".into()));
     }
-    if content.len() > MAX_CONTENT_LENGTH {
+    let content_len = content.chars().count();
+    if content_len > MAX_CONTENT_LENGTH {
         return Err(Error::Validation(format!(
             "Content too long: {} chars (max {})",
-            content.len(),
+            content_len,
             MAX_CONTENT_LENGTH
         )));
     }
@@
     for tag in tags {
         let t = tag.as_ref();
         if t.is_empty() {
             return Err(Error::Validation("Tags must not be empty".into()));
         }
-        if t.len() > MAX_TAG_LENGTH {
+        let tag_len = t.chars().count();
+        if tag_len > MAX_TAG_LENGTH {
             return Err(Error::Validation(format!(
                 "Tag too long: {} chars (max {})",
-                t.len(),
+                tag_len,
                 MAX_TAG_LENGTH
             )));
         }
     }

Also applies to: 63-67

🤖 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/lib.rs` around lines 44 - 48, The validation currently
uses str::len() (byte length) for checks like comparing content.len() against
MAX_CONTENT_LENGTH (and similar checks for tags), which incorrectly rejects
multibyte characters; update those checks to use character counts (e.g.
content.chars().count()) instead of .len(), apply the same change to tag/name
length checks, and make the error message values reflect the character counts so
the reported "chars" numbers match the validation logic (references: uses of
content.len() and tag.len() in the validation code and constants like
MAX_CONTENT_LENGTH).

Comment thread examples/python_hermes.py
Comment on lines +226 to 245
def get(
self,
memory_id: str,
namespace: Optional[str] = None,
) -> Optional[Dict[str, Any]]:
"""Get a single memory by ID.

Args:
memory_id: UUID of the memory.
namespace: Namespace override.

Returns:
Memory dict, or ``None`` if not found.
"""
try:
return self._parse_json(self._run(["get", memory_id]))
return self._parse_json(
self._run(self._ns_args(namespace) + ["get", memory_id])
)
except UtekeError:
return None

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 collapse every CLI failure into None/False.

Both methods catch any UtekeError, so timeouts, malformed JSON, permission problems, and other CLI failures become indistinguishable from a legitimate "not found". That makes real outages invisible to callers. Only translate the specific miss/not-found case; re-raise everything else.

Also applies to: 247-270

🧰 Tools
🪛 Ruff (0.15.15)

[warning] 242-242: Consider [*self._ns_args(namespace), "get", memory_id] instead of concatenation

Replace with [*self._ns_args(namespace), "get", memory_id]

(RUF005)

🤖 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 `@examples/python_hermes.py` around lines 226 - 245, The get method currently
catches all UtekeError and returns None, hiding real failures; change the except
block to only swallow the specific "not found" case and re-raise other errors:
after calling self._run(...) wrap in try/except UtekeError as e, detect the
not-found condition (e.g. inspect e.code or e.message for the CLI's "not found"
sentinel or add a small helper like _is_not_found_error(e)), return None only
when that check is true, otherwise raise; apply the same change to the other
method referenced at 247-270 so only genuine not-found responses are converted
to None/False and all other UtekeError instances propagate.

Comment thread examples/python_hermes.py
Comment on lines +347 to +353
def namespace_switch(self, name: str) -> None:
"""Set the default namespace in the Uteke config.

Args:
name: Namespace name to set as default.
"""
self._run(["namespace", "switch", name])

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

namespace_switch() leaves the wrapper pinned to the old namespace.

If this instance was created with a default namespace, subsequent calls still prepend the stale --namespace value because self._namespace is never updated after a successful switch.

Suggested fix
     def namespace_switch(self, name: str) -> None:
         """Set the default namespace in the Uteke config.
@@
         Args:
             name: Namespace name to set as default.
         """
         self._run(["namespace", "switch", name])
+        self._namespace = name
🤖 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 `@examples/python_hermes.py` around lines 347 - 353, The namespace_switch
method performs the CLI call but doesn't update the wrapper's stored namespace,
leaving self._namespace stale; after successfully running
self._run(["namespace", "switch", name]) in namespace_switch, set
self._namespace = name (or handle normalization if other code expects a specific
format) so subsequent commands that reference self._namespace use the new value;
locate the namespace_switch method and update it to assign the new name to the
instance field after the successful call.

Comment thread README.md
| **Insert 100** | ~316s (0.3/s) | 7.7s (13/s) | **41x** |
| **Insert 1,000** | ~53 min (0.3/s) | 84s (12/s) | **38x** |
| **Recall (avg/query)** | 3,158ms | 42ms | **75x** |
| **Search (avg/query)** | 3,158ms | 9ms | **367x** |

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 | 🟡 Minor | ⚡ Quick win

Correct the search speedup calculation.

The speedup is calculated as 3,158ms / 9ms = 350.89x, which rounds to 351x, not 367x. The current value overstates the performance improvement by ~4.5%.

🔢 Proposed fix
-| **Search (avg/query)** | 3,158ms | 9ms | **367x** |
+| **Search (avg/query)** | 3,158ms | 9ms | **351x** |
📝 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
| **Search (avg/query)** | 3,158ms | 9ms | **367x** |
| **Search (avg/query)** | 3,158ms | 9ms | **351x** |
🤖 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 `@README.md` at line 245, Update the search speedup value in the README table
row that currently reads "| **Search (avg/query)** | 3,158ms | 9ms | **367x** |"
to the correct value: compute 3158 / 9 = 350.89 and replace "**367x**" with
"**351x**" (rounded). Ensure the table cell string is updated exactly to "|
**Search (avg/query)** | 3,158ms | 9ms | **351x** |".

Comment thread README.md
**Phase A (100+ stars):** Better embeddings, import from external sources, Hermes plugin, benchmark
**Phase B (500+ stars):** Python SDK (PyO3), Node.js SDK, editor integrations
**Phase C (1000+ stars):** Team features, cloud sync (opt-in), knowledge graph
**v0.0.8 (next):** Input validation, binary checksums, codebase modularization, benchmark

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 | 🟡 Minor | ⚡ Quick win

Clarify v0.0.8 roadmap label.

The roadmap lists "v0.0.8 (next)" with features (input validation, checksums, modularization, benchmark) that are delivered in this PR according to the PR objectives. This creates ambiguity:

  • If this PR IS the v0.0.8 release, consider labeling it "v0.0.8 (current release)" and adding a new "v0.0.9 (next)" entry.
  • If v0.0.8 is still upcoming, the "(next)" label is correct but conflicts with the PR title and objectives stating this is the v0.0.8 release.

This is related to the version badge concern on line 11. Both suggest the README may be showing the state before the version bump.

📋 Suggested clarification

If this PR completes the v0.0.8 release, consider:

-**v0.0.8 (next):** Input validation, binary checksums, codebase modularization, benchmark
+**v0.0.8 (current release):** Input validation, binary checksums, codebase modularization, benchmark
+**v0.0.9 (next):** TBD — see Phase A milestones
📝 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
**v0.0.8 (next):** Input validation, binary checksums, codebase modularization, benchmark
**v0.0.8 (current release):** Input validation, binary checksums, codebase modularization, benchmark
**v0.0.9 (next):** TBD — see Phase A milestones
🤖 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 `@README.md` at line 374, The README's roadmap entry "v0.0.8 (next)" conflicts
with the PR's objectives and the version badge; either update the roadmap to
reflect that this PR is the release (change the string "v0.0.8 (next)" to
"v0.0.8 (current release)" and add a new "v0.0.9 (next)" entry) or, if the
release is still forthcoming, keep "v0.0.8 (next)" but align the PR
title/objectives and the version badge so they indicate a pre-release state;
locate and update the "v0.0.8 (next)" roadmap string and the version badge text
to make the README and PR consistent.

CTO Hermes added 3 commits June 4, 2026 14:32
Placeholder match for future schema migrations — single binding
is intentional, allow clippy lint
- read_to_string(checksums_file) — remove needless &
- .arg(binary) — remove needless &
- .into() — remove useless conversion
import_export.rs and maintenance.rs tests used explicit crate:: paths,
making super::* unused.
@ajianaz
ajianaz merged commit 89fc139 into develop Jun 4, 2026
7 checks passed
@ajianaz
ajianaz deleted the feature/v0.0.8 branch June 6, 2026 06:57
ajianaz added a commit that referenced this pull request Aug 13, 2026
* feat: v0.0.8 stability & architecture overhaul

Closes #130 #131 #132 #134 #138 #139 #144 #137

Architecture:
- Split lib.rs (1471→352) and main.rs (1538→422) into focused modules
- Core: operations, maintenance, consolidate, error, types, import_export
- CLI: commands, init, output, bench

Validation (#132):
- Max content 10K chars, max 20 tags, max server payload 1MB

Binary integrity (#134):
- SHA256 checksums in release artifacts (CHECKSUMS.txt)
- verify-checksums subcommand

Schema versioning (#138):
- schema_version table + migration framework

Reliability (#139):
- Fix deadlock in check_contradiction (mutex re-acquire)

Error handling (#144):
- Error enum rewrite with sanitized user-friendly messages
- ~90 call sites migrated from raw rusqlite/usearch/ONNX errors
- Lock errors now include operation context
- 7 new unit tests for sanitization

Python wrapper (#137):
- 7→21 methods covering all CLI commands
- Namespace support on all methods
- Full type hints + Google-style docstrings

Benchmark (#49):
- memory-bench binary for library-level timing

README:
- Badge v0.0.7, Design Philosophy section
- Performance section with actual benchmark data
- Removed knowledge graph from roadmap

Tests: 116 pass (+20 from v0.0.7)

Co-Authored-By: codecoradev <[email protected]>

* style: cargo fmt — fix CI format check

* fix: safe contradiction deprecation + v0.0.8 version bump

- check_contradiction: now read-only, no mutation during check
- Deprecation happens AFTER new memory is persisted (prevents data loss)
- Version bump 0.0.7 → 0.0.8
- CHANGELOG v0.0.8 entry

Fixes CodeRabbit review on consolidate.rs rollback path

* fix: use io::Error::other() — clippy io_other_error lint

Rust 1.96 clippy enforces io::Error::other() over
io::Error::new(ErrorKind::Other, ...)

* fix: suppress clippy match_single_binding in migration match

Placeholder match for future schema migrations — single binding
is intentional, allow clippy lint

* fix: clippy needless_borrows + useless_conversion in commands.rs

- read_to_string(checksums_file) — remove needless &
- .arg(binary) — remove needless &
- .into() — remove useless conversion

* fix: remove unused super::* imports — clippy unused_imports

import_export.rs and maintenance.rs tests used explicit crate:: paths,
making super::* unused.

---------

Co-authored-by: CTO Hermes <[email protected]>
Co-authored-by: codecoradev <[email protected]>
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.

1 participant