Skip to content

v2.0.0: Security, Author Protection & First-Time UX - #1

Merged
varun369 merged 1 commit into
mainfrom
v2.0.0-release
Feb 5, 2026
Merged

varun369 merged 1 commit into
mainfrom
v2.0.0-release

Conversation

@varun369

@varun369 varun369 commented Feb 5, 2026 •

Copy link
Copy Markdown
Member

Summary

Major release with security hardening, author protection, and improved first-time user experience.

Security Fixes

  • API server binds to localhost only (127.0.0.1) instead of 0.0.0.0
  • Path traversal protection in profile management
  • Input validation with size limits (1MB content, 10KB summary)
  • Graph build limits (5000 memories max) to prevent resource exhaustion

Author Protection

  • Copyright headers added to all Python files
  • System metadata watermarks in database schema
  • Footer attribution in UI
  • README author section with GitHub links

First-Time UX

  • New setup_validator.py for comprehensive installation validation
  • Database auto-initialization with full V2 schema
  • Table existence checks before graph operations
  • Clear error messages with fix instructions
  • Branded install.sh with dependency checking

Documentation

  • README updated with feature comparison table vs competitors
  • Quick start commands and usage examples
  • Optional dependency installation guide

Test plan

  • Input validation tests pass
  • Profile security tests pass (path traversal blocked)
  • Setup validator runs successfully
  • API server binds to localhost only
  • Watermarks present in all Python files
  • UI footer shows author attribution
  • README has feature comparison table
  • docs/plans folder NOT included (gitignored)

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Added comprehensive setup validation tool to verify system requirements and database initialization.
  • Bug Fixes

    • Enhanced input validation for memory content, summaries, and tags to prevent invalid data entry.
    • Added memory processing limits to prevent performance degradation with large datasets.
  • Security

    • API server now binds to localhost only by default, reducing network exposure.
    • Implemented path traversal protection for profile management.
  • Documentation

    • Updated README with feature comparison table and improved project attribution.
    • Enhanced installation script with Python version validation and better setup guidance.
  • Chores

    • Added project licensing headers and metadata across modules.

…ovements

Security fixes:
- API server binds to localhost only (127.0.0.1) instead of 0.0.0.0
- Path traversal protection in profile management
- Input validation with size limits (1MB content, 10KB summary, 50 char tags, 20 max tags)
- Graph build limits (5000 memories max) to prevent resource exhaustion

Author protection:
- Copyright headers added to all Python files
- System metadata watermarks in database schema
- Footer attribution in UI
- README author section with GitHub links

First-time UX:
- New setup_validator.py for comprehensive installation validation
- Database auto-initialization with full V2 schema
- Table existence checks before graph operations
- Clear error messages with fix instructions
- Branded install.sh with dependency checking

Documentation:
- README updated with feature comparison table vs competitors
- Quick start commands and usage examples
- Optional dependency installation guide

Co-Authored-By: Claude Opus 4.5 <[email protected]>
@coderabbitai

coderabbitai Bot commented Feb 5, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

This pull request adds license headers to multiple files, enhances security through input validation and network binding changes, introduces a comprehensive setup validator script, significantly improves the installation workflow with better diagnostics, and updates README documentation with feature comparisons and author information.

Changes

Cohort / File(s) Summary
License and Metadata Headers
create_demo_db.py, src/memory-reset.py, src/memory_compression.py, src/migrate_v1_to_v2.py, src/pattern_learner.py, src/tree_manager.py, test_demo.py, verify_demo.py
Added module-level license headers and metadata docstrings without functional changes.
Security and Input Validation
api_server.py, src/memory-profiles.py, src/memory_store_v2.py
Hardened network exposure by binding FastAPI to localhost; added strict validation for profile names (path traversal protection) and memory content (size/tag limits) with enforced constraints.
Graph Processing and Limits
src/graph_engine.py
Introduced MAX_MEMORIES_FOR_GRAPH constant and comprehensive pre-flight validation checks (table existence, memory count thresholds) with structured error returns to prevent O(n²) explosions.
Setup and Validation Infrastructure
src/setup_validator.py
New comprehensive validation script with Python version checking, dependency verification (core and optional), directory structure validation, and database initialization with schema creation.
Installation Workflow
install.sh
Major refactor: added ASCII banners, Python 3.8+ validation, directory creation, conditional hooks/CLI/API installation, improved config handling, database initialization fallback, and expanded usage guidance.
Documentation
.gitignore, README.md, ui/index.html
Added docs/plans/ to gitignore; updated README with modern badges, Feature Comparison table, expanded author section, and GitHub links; added footer credit to UI.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Poem

🐰 With headers in place and validations so tight,
We've locked down the paths and the network's now right,
A validator watches from start to the end,
Installation now speaks in voices that blend,
Security fences keep wanderers out—hop hop! 🔐

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the three main focus areas of this PR: security hardening, author protection, and first-time UX improvements for v2.0.0.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

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

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch v2.0.0-release

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.

@varun369
varun369 merged commit 1c27b84 into main Feb 5, 2026
@varun369
varun369 deleted the v2.0.0-release branch February 5, 2026 12:47

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

🤖 Fix all issues with AI agents
In `@install.sh`:
- Around line 92-139: The fallback database schema in the inline Python block
diverges from the runtime schema used by GraphEngine: update the CREATE TABLE
statements for graph_edges and graph_clusters to match the columns GraphEngine
expects (e.g., use weight or similarity_score instead of similarity, and
name/member_count or the exact column names GraphEngine inserts) or replace this
fallback with a call to the canonical initializer used at runtime (e.g., the
same setup_validator.py logic) so both paths produce identical columns and avoid
“no such column” errors when GraphEngine inserts.

In `@src/graph_engine.py`:
- Around line 492-495: The docstring still claims the function raises ValueError
but the implementation returns a failure dict when the memory count exceeds
5000; update the docstring in this function to remove the "Raises: ValueError"
section and instead document the actual behavior (i.e., on too many memories
(>5000) it returns a dict like {"success": False, "error": "<message>"} or
similar), including the condition (">5000") and the return structure;
alternatively, if you prefer to keep the docstring as-is, change the code path
that currently returns the failure dict to raise ValueError instead — choose one
approach and make the docstring and the implementation (the branch handling the
memory limit) consistent.

In `@src/memory-profiles.py`:
- Around line 100-101: The reserved-name check incorrectly blocks the legitimate
'default' profile; in the validation that currently tests profile_name in ['.',
'..', 'default'] (in the profile name validation function in
src/memory-profiles.py), remove 'default' from the blocked list so only '.' and
'..' are rejected (e.g., change to ['.', '..']); ensure any callers like
switch_profile or _save_current_to_profile continue to accept 'default' and no
other logic treats 'default' as reserved.

In `@src/setup_validator.py`:
- Around line 408-412: The call to check_database() returns three values but the
third, missing_tables, is unused which causes lint warnings; update the call in
src/setup_validator.py (the block where check_database() is invoked) to either
ignore the third return by assigning it to a prefixed name like _missing_tables
or drop the third value from the assignment (e.g., db_ok, db_msg =
check_database() if check_database supports that), and keep the existing print
of Database using db_ok and db_msg unchanged.
- Around line 20-22: The environment variable name used when constructing
MEMORY_DIR is misspelled as 'SUPERLOCALEMORY_DIR', preventing overrides; update
the os.environ key to the correct 'SUPERLOCALMEMORY_DIR' in the MEMORY_DIR
assignment (the line defining MEMORY_DIR that uses os.environ.get), leaving the
fallback to Path.home() / ".claude-memory" and DB_PATH = MEMORY_DIR /
"memory.db" unchanged.
- Around line 241-266: The CREATE TABLE statements for graph_edges and
graph_clusters use column names (e.g., similarity, cluster_name, memory_count)
that don’t match GraphEngine’s insert schema (it writes weight or
similarity_score, name, member_count); update the CREATE TABLE to use the exact
column names GraphEngine expects (for graph_edges add/rename to weight and/or
similarity_score and keep foreign keys/UNIQUE, for graph_clusters rename
cluster_name->name and memory_count->member_count or add those columns as
aliases with the same defaults) so DB initialization matches GraphEngine inserts
and prevents write errors.
🧹 Nitpick comments (2)
ui/index.html (1)

286-289: Consider moving inline styles to the existing CSS block.

The footer uses inline styles that could be extracted to the existing <style> block (lines 13-115) for better maintainability and consistency with the rest of the page.

♻️ Optional refactor to extract inline styles

Add to the <style> block:

footer {
    text-align: center;
    padding: 20px;
    margin-top: 40px;
    border-top: 1px solid `#333`;
    color: `#888`;
}

footer a {
    color: `#4fc3f7`;
}

Then simplify the footer markup:

-    <footer style="text-align: center; padding: 20px; margin-top: 40px; border-top: 1px solid `#333`; color: `#888`;">
-        <p>SuperLocalMemory V2 by <a href="https://github.com/varun369" style="color: `#4fc3f7`;">Varun Pratap Bhardwaj</a></p>
-        <p><a href="https://github.com/varun369/SuperLocalMemoryV2" style="color: `#4fc3f7`;">GitHub Repository</a> | MIT License</p>
+    <footer>
+        <p>SuperLocalMemory V2 by <a href="https://github.com/varun369">Varun Pratap Bhardwaj</a></p>
+        <p><a href="https://github.com/varun369/SuperLocalMemoryV2">GitHub Repository</a> | MIT License</p>
     </footer>
src/setup_validator.py (1)

130-155: Narrow the bare except to sqlite3.Error when reading memory count.
Catching everything masks unexpected errors. Since this code executes SQL operations on a sqlite3 connection, use except sqlite3.Error: instead.

♻️ Suggested refactor
-        try:
-            cursor.execute("SELECT COUNT(*) FROM memories")
-            memory_count = cursor.fetchone()[0]
-        except:
-            memory_count = 0
+        try:
+            cursor.execute("SELECT COUNT(*) FROM memories")
+            memory_count = cursor.fetchone()[0]
+        except sqlite3.Error:
+            memory_count = 0

Comment thread install.sh
Comment on lines +92 to +139
# Initialize database
echo ""
echo "Initializing database..."
if python3 "${INSTALL_DIR}/setup_validator.py" --init > /dev/null 2>&1; then
echo "✓ Database initialized"
else
# Fallback: create basic tables
python3 -c "
import sqlite3
from pathlib import Path
db_path = Path.home() / '.claude-memory' / 'memory.db'
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
cursor.execute('''CREATE TABLE IF NOT EXISTS memories (
id INTEGER PRIMARY KEY AUTOINCREMENT,
content TEXT NOT NULL,
summary TEXT,
project_path TEXT,
project_name TEXT,
tags TEXT DEFAULT '[]',
category TEXT,
parent_id INTEGER,
tree_path TEXT DEFAULT '/',
depth INTEGER DEFAULT 0,
memory_type TEXT DEFAULT 'session',
importance INTEGER DEFAULT 5,
content_hash TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
last_accessed TIMESTAMP,
access_count INTEGER DEFAULT 0,
compressed_at TIMESTAMP,
tier INTEGER DEFAULT 1,
cluster_id INTEGER
)''')
cursor.execute('CREATE TABLE IF NOT EXISTS graph_nodes (id INTEGER PRIMARY KEY, memory_id INTEGER UNIQUE, entities TEXT DEFAULT \"[]\", embedding_vector BLOB, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)')
cursor.execute('CREATE TABLE IF NOT EXISTS graph_edges (id INTEGER PRIMARY KEY, source_memory_id INTEGER, target_memory_id INTEGER, similarity REAL, relationship_type TEXT, shared_entities TEXT DEFAULT \"[]\", created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)')
cursor.execute('CREATE TABLE IF NOT EXISTS graph_clusters (id INTEGER PRIMARY KEY, cluster_name TEXT, description TEXT, memory_count INTEGER DEFAULT 0, avg_importance REAL DEFAULT 5.0, top_entities TEXT DEFAULT \"[]\", created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)')
cursor.execute('CREATE TABLE IF NOT EXISTS identity_patterns (id INTEGER PRIMARY KEY, pattern_type TEXT, pattern_key TEXT, pattern_value TEXT, confidence REAL DEFAULT 0.0, frequency INTEGER DEFAULT 1, last_seen TIMESTAMP DEFAULT CURRENT_TIMESTAMP, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)')
cursor.execute('CREATE TABLE IF NOT EXISTS pattern_examples (id INTEGER PRIMARY KEY, pattern_id INTEGER, memory_id INTEGER, context TEXT, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)')
cursor.execute('CREATE TABLE IF NOT EXISTS memory_tree (id INTEGER PRIMARY KEY, node_type TEXT, name TEXT, parent_id INTEGER, tree_path TEXT DEFAULT \"/\", depth INTEGER DEFAULT 0, memory_count INTEGER DEFAULT 0, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)')
cursor.execute('CREATE TABLE IF NOT EXISTS memory_archive (id INTEGER PRIMARY KEY, original_memory_id INTEGER, compressed_content TEXT, compression_type TEXT DEFAULT \"tier2\", original_size INTEGER, compressed_size INTEGER, archived_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)')
cursor.execute('CREATE TABLE IF NOT EXISTS system_metadata (key TEXT PRIMARY KEY, value TEXT NOT NULL)')
cursor.execute(\"INSERT OR REPLACE INTO system_metadata (key, value) VALUES ('product', 'SuperLocalMemory V2'), ('author', 'Varun Pratap Bhardwaj'), ('repository', 'https://github.com/varun369/SuperLocalMemoryV2'), ('license', 'MIT'), ('schema_version', '2.0.0')\")
conn.commit()
conn.close()
print('Database ready')
" && echo "✓ Database initialized (fallback)"
fi

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 | 🔴 Critical

Fallback DB schema diverges from runtime schema.
The inline fallback creates graph_edges/graph_clusters columns that don’t match what GraphEngine inserts (e.g., weight/similarity_score, name/member_count). If this path runs, graph builds will fail with “no such column” errors. Align the SQL with the runtime schema (or reuse the canonical initializer).

🛠️ Suggested alignment inside the fallback SQL
-cursor.execute('CREATE TABLE IF NOT EXISTS graph_edges (id INTEGER PRIMARY KEY, source_memory_id INTEGER, target_memory_id INTEGER, similarity REAL, relationship_type TEXT, shared_entities TEXT DEFAULT \"[]\", created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)')
+cursor.execute('CREATE TABLE IF NOT EXISTS graph_edges (id INTEGER PRIMARY KEY, source_memory_id INTEGER NOT NULL, target_memory_id INTEGER NOT NULL, relationship_type TEXT, weight REAL DEFAULT 1.0, shared_entities TEXT DEFAULT \"[]\", similarity_score REAL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, UNIQUE(source_memory_id, target_memory_id))')

-cursor.execute('CREATE TABLE IF NOT EXISTS graph_clusters (id INTEGER PRIMARY KEY, cluster_name TEXT, description TEXT, memory_count INTEGER DEFAULT 0, avg_importance REAL DEFAULT 5.0, top_entities TEXT DEFAULT \"[]\", created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)')
+cursor.execute('CREATE TABLE IF NOT EXISTS graph_clusters (id INTEGER PRIMARY KEY, name TEXT NOT NULL, description TEXT, member_count INTEGER DEFAULT 0, avg_importance REAL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)')
📝 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
# Initialize database
echo ""
echo "Initializing database..."
if python3 "${INSTALL_DIR}/setup_validator.py" --init > /dev/null 2>&1; then
echo "✓ Database initialized"
else
# Fallback: create basic tables
python3 -c "
import sqlite3
from pathlib import Path
db_path = Path.home() / '.claude-memory' / 'memory.db'
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
cursor.execute('''CREATE TABLE IF NOT EXISTS memories (
id INTEGER PRIMARY KEY AUTOINCREMENT,
content TEXT NOT NULL,
summary TEXT,
project_path TEXT,
project_name TEXT,
tags TEXT DEFAULT '[]',
category TEXT,
parent_id INTEGER,
tree_path TEXT DEFAULT '/',
depth INTEGER DEFAULT 0,
memory_type TEXT DEFAULT 'session',
importance INTEGER DEFAULT 5,
content_hash TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
last_accessed TIMESTAMP,
access_count INTEGER DEFAULT 0,
compressed_at TIMESTAMP,
tier INTEGER DEFAULT 1,
cluster_id INTEGER
)''')
cursor.execute('CREATE TABLE IF NOT EXISTS graph_nodes (id INTEGER PRIMARY KEY, memory_id INTEGER UNIQUE, entities TEXT DEFAULT \"[]\", embedding_vector BLOB, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)')
cursor.execute('CREATE TABLE IF NOT EXISTS graph_edges (id INTEGER PRIMARY KEY, source_memory_id INTEGER, target_memory_id INTEGER, similarity REAL, relationship_type TEXT, shared_entities TEXT DEFAULT \"[]\", created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)')
cursor.execute('CREATE TABLE IF NOT EXISTS graph_clusters (id INTEGER PRIMARY KEY, cluster_name TEXT, description TEXT, memory_count INTEGER DEFAULT 0, avg_importance REAL DEFAULT 5.0, top_entities TEXT DEFAULT \"[]\", created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)')
cursor.execute('CREATE TABLE IF NOT EXISTS identity_patterns (id INTEGER PRIMARY KEY, pattern_type TEXT, pattern_key TEXT, pattern_value TEXT, confidence REAL DEFAULT 0.0, frequency INTEGER DEFAULT 1, last_seen TIMESTAMP DEFAULT CURRENT_TIMESTAMP, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)')
cursor.execute('CREATE TABLE IF NOT EXISTS pattern_examples (id INTEGER PRIMARY KEY, pattern_id INTEGER, memory_id INTEGER, context TEXT, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)')
cursor.execute('CREATE TABLE IF NOT EXISTS memory_tree (id INTEGER PRIMARY KEY, node_type TEXT, name TEXT, parent_id INTEGER, tree_path TEXT DEFAULT \"/\", depth INTEGER DEFAULT 0, memory_count INTEGER DEFAULT 0, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)')
cursor.execute('CREATE TABLE IF NOT EXISTS memory_archive (id INTEGER PRIMARY KEY, original_memory_id INTEGER, compressed_content TEXT, compression_type TEXT DEFAULT \"tier2\", original_size INTEGER, compressed_size INTEGER, archived_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)')
cursor.execute('CREATE TABLE IF NOT EXISTS system_metadata (key TEXT PRIMARY KEY, value TEXT NOT NULL)')
cursor.execute(\"INSERT OR REPLACE INTO system_metadata (key, value) VALUES ('product', 'SuperLocalMemory V2'), ('author', 'Varun Pratap Bhardwaj'), ('repository', 'https://github.com/varun369/SuperLocalMemoryV2'), ('license', 'MIT'), ('schema_version', '2.0.0')\")
conn.commit()
conn.close()
print('Database ready')
" && echo "✓ Database initialized (fallback)"
fi
# Initialize database
echo ""
echo "Initializing database..."
if python3 "${INSTALL_DIR}/setup_validator.py" --init > /dev/null 2>&1; then
echo "✓ Database initialized"
else
# Fallback: create basic tables
python3 -c "
import sqlite3
from pathlib import Path
db_path = Path.home() / '.claude-memory' / 'memory.db'
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
cursor.execute('''CREATE TABLE IF NOT EXISTS memories (
id INTEGER PRIMARY KEY AUTOINCREMENT,
content TEXT NOT NULL,
summary TEXT,
project_path TEXT,
project_name TEXT,
tags TEXT DEFAULT '[]',
category TEXT,
parent_id INTEGER,
tree_path TEXT DEFAULT '/',
depth INTEGER DEFAULT 0,
memory_type TEXT DEFAULT 'session',
importance INTEGER DEFAULT 5,
content_hash TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
last_accessed TIMESTAMP,
access_count INTEGER DEFAULT 0,
compressed_at TIMESTAMP,
tier INTEGER DEFAULT 1,
cluster_id INTEGER
)''')
cursor.execute('CREATE TABLE IF NOT EXISTS graph_nodes (id INTEGER PRIMARY KEY, memory_id INTEGER UNIQUE, entities TEXT DEFAULT "[]", embedding_vector BLOB, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)')
cursor.execute('CREATE TABLE IF NOT EXISTS graph_edges (id INTEGER PRIMARY KEY, source_memory_id INTEGER NOT NULL, target_memory_id INTEGER NOT NULL, relationship_type TEXT, weight REAL DEFAULT 1.0, shared_entities TEXT DEFAULT "[]", similarity_score REAL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, UNIQUE(source_memory_id, target_memory_id))')
cursor.execute('CREATE TABLE IF NOT EXISTS graph_clusters (id INTEGER PRIMARY KEY, name TEXT NOT NULL, description TEXT, member_count INTEGER DEFAULT 0, avg_importance REAL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)')
cursor.execute('CREATE TABLE IF NOT EXISTS identity_patterns (id INTEGER PRIMARY KEY, pattern_type TEXT, pattern_key TEXT, pattern_value TEXT, confidence REAL DEFAULT 0.0, frequency INTEGER DEFAULT 1, last_seen TIMESTAMP DEFAULT CURRENT_TIMESTAMP, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)')
cursor.execute('CREATE TABLE IF NOT EXISTS pattern_examples (id INTEGER PRIMARY KEY, pattern_id INTEGER, memory_id INTEGER, context TEXT, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)')
cursor.execute('CREATE TABLE IF NOT EXISTS memory_tree (id INTEGER PRIMARY KEY, node_type TEXT, name TEXT, parent_id INTEGER, tree_path TEXT DEFAULT "/", depth INTEGER DEFAULT 0, memory_count INTEGER DEFAULT 0, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)')
cursor.execute('CREATE TABLE IF NOT EXISTS memory_archive (id INTEGER PRIMARY KEY, original_memory_id INTEGER, compressed_content TEXT, compression_type TEXT DEFAULT "tier2", original_size INTEGER, compressed_size INTEGER, archived_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)')
cursor.execute('CREATE TABLE IF NOT EXISTS system_metadata (key TEXT PRIMARY KEY, value TEXT NOT NULL)')
cursor.execute("INSERT OR REPLACE INTO system_metadata (key, value) VALUES ('product', 'SuperLocalMemory V2'), ('author', 'Varun Pratap Bhardwaj'), ('repository', 'https://github.com/varun369/SuperLocalMemoryV2'), ('license', 'MIT'), ('schema_version', '2.0.0')")
conn.commit()
conn.close()
print('Database ready')
" && echo "✓ Database initialized (fallback)"
fi
🤖 Prompt for AI Agents
In `@install.sh` around lines 92 - 139, The fallback database schema in the inline
Python block diverges from the runtime schema used by GraphEngine: update the
CREATE TABLE statements for graph_edges and graph_clusters to match the columns
GraphEngine expects (e.g., use weight or similarity_score instead of similarity,
and name/member_count or the exact column names GraphEngine inserts) or replace
this fallback with a call to the canonical initializer used at runtime (e.g.,
the same setup_validator.py logic) so both paths produce identical columns and
avoid “no such column” errors when GraphEngine inserts.

Comment thread src/graph_engine.py
Comment on lines +492 to 495

Raises:
ValueError: If too many memories (>5000) for safe processing
"""

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

Docstring no longer matches behavior.
The function now returns a failure dict when over the limit, but the docstring still claims it raises ValueError. Update the docstring or raise the exception.

✏️ Suggested docstring tweak
-        Raises:
-            ValueError: If too many memories (>5000) for safe processing
+        Notes:
+            Returns a failure dict when memory count exceeds MAX_MEMORIES_FOR_GRAPH.
📝 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
Raises:
ValueError: If too many memories (>5000) for safe processing
"""
Notes:
Returns a failure dict when memory count exceeds MAX_MEMORIES_FOR_GRAPH.
"""
🤖 Prompt for AI Agents
In `@src/graph_engine.py` around lines 492 - 495, The docstring still claims the
function raises ValueError but the implementation returns a failure dict when
the memory count exceeds 5000; update the docstring in this function to remove
the "Raises: ValueError" section and instead document the actual behavior (i.e.,
on too many memories (>5000) it returns a dict like {"success": False, "error":
"<message>"} or similar), including the condition (">5000") and the return
structure; alternatively, if you prefer to keep the docstring as-is, change the
code path that currently returns the failure dict to raise ValueError instead —
choose one approach and make the docstring and the implementation (the branch
handling the memory limit) consistent.

Comment thread src/memory-profiles.py
Comment on lines +100 to +101
if profile_name in ['.', '..', 'default']:
raise ValueError(f"Reserved profile name: {profile_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 | 🔴 Critical

Critical: Blocking 'default' breaks the profile system.

The reserved names check includes 'default', but default is the standard profile used throughout this codebase. This will cause ValueError when:

  • Switching to the default profile (switch_profile('default'))
  • Saving current state to default profile (_save_current_to_profile('default'))
  • Loading the default profile

The . and .. checks are correct for path traversal prevention, but default should be allowed.

🐛 Proposed fix
-        if profile_name in ['.', '..', 'default']:
-            raise ValueError(f"Reserved profile name: {profile_name}")
+        if profile_name in ['.', '..']:
+            raise ValueError(f"Reserved profile name: {profile_name}")
📝 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
if profile_name in ['.', '..', 'default']:
raise ValueError(f"Reserved profile name: {profile_name}")
if profile_name in ['.', '..']:
raise ValueError(f"Reserved profile name: {profile_name}")
🧰 Tools
🪛 Ruff (0.14.14)

[warning] 101-101: Avoid specifying long messages outside the exception class

(TRY003)

🤖 Prompt for AI Agents
In `@src/memory-profiles.py` around lines 100 - 101, The reserved-name check
incorrectly blocks the legitimate 'default' profile; in the validation that
currently tests profile_name in ['.', '..', 'default'] (in the profile name
validation function in src/memory-profiles.py), remove 'default' from the
blocked list so only '.' and '..' are rejected (e.g., change to ['.', '..']);
ensure any callers like switch_profile or _save_current_to_profile continue to
accept 'default' and no other logic treats 'default' as reserved.

Comment thread src/setup_validator.py
Comment on lines +20 to +22
# Configuration
MEMORY_DIR = Path(os.environ.get('SUPERLOCALEMORY_DIR', str(Path.home() / ".claude-memory")))
DB_PATH = MEMORY_DIR / "memory.db"

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

Env var override typo blocks custom memory dir.
SUPERLOCALEMORY_DIR is missing an “M”. Users setting SUPERLOCALMEMORY_DIR won’t be honored.

✏️ Fix the environment variable name
-MEMORY_DIR = Path(os.environ.get('SUPERLOCALEMORY_DIR', str(Path.home() / ".claude-memory")))
+MEMORY_DIR = Path(os.environ.get('SUPERLOCALMEMORY_DIR', str(Path.home() / ".claude-memory")))
📝 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
# Configuration
MEMORY_DIR = Path(os.environ.get('SUPERLOCALEMORY_DIR', str(Path.home() / ".claude-memory")))
DB_PATH = MEMORY_DIR / "memory.db"
# Configuration
MEMORY_DIR = Path(os.environ.get('SUPERLOCALMEMORY_DIR', str(Path.home() / ".claude-memory")))
DB_PATH = MEMORY_DIR / "memory.db"
🤖 Prompt for AI Agents
In `@src/setup_validator.py` around lines 20 - 22, The environment variable name
used when constructing MEMORY_DIR is misspelled as 'SUPERLOCALEMORY_DIR',
preventing overrides; update the os.environ key to the correct
'SUPERLOCALMEMORY_DIR' in the MEMORY_DIR assignment (the line defining
MEMORY_DIR that uses os.environ.get), leaving the fallback to Path.home() /
".claude-memory" and DB_PATH = MEMORY_DIR / "memory.db" unchanged.

Comment thread src/setup_validator.py
Comment on lines +241 to +266
cursor.execute('''
CREATE TABLE IF NOT EXISTS graph_edges (
id INTEGER PRIMARY KEY AUTOINCREMENT,
source_memory_id INTEGER NOT NULL,
target_memory_id INTEGER NOT NULL,
similarity REAL NOT NULL,
relationship_type TEXT,
shared_entities TEXT DEFAULT '[]',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (source_memory_id) REFERENCES memories(id),
FOREIGN KEY (target_memory_id) REFERENCES memories(id),
UNIQUE(source_memory_id, target_memory_id)
)
''')

cursor.execute('''
CREATE TABLE IF NOT EXISTS graph_clusters (
id INTEGER PRIMARY KEY AUTOINCREMENT,
cluster_name TEXT,
description TEXT,
memory_count INTEGER DEFAULT 0,
avg_importance REAL DEFAULT 5.0,
top_entities TEXT DEFAULT '[]',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
''')

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 | 🔴 Critical

Graph schema doesn’t match GraphEngine inserts.
graph_edges and graph_clusters columns here differ from what GraphEngine inserts (weight/similarity_score, name/member_count). Databases initialized via this path will fail during graph writes. Align the schema with GraphEngine.

🛠️ Suggested schema alignment
-                similarity REAL NOT NULL,
-                relationship_type TEXT,
-                shared_entities TEXT DEFAULT '[]',
-                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+                relationship_type TEXT,
+                weight REAL DEFAULT 1.0,
+                shared_entities TEXT DEFAULT '[]',
+                similarity_score REAL,
+                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,

-                cluster_name TEXT,
-                description TEXT,
-                memory_count INTEGER DEFAULT 0,
-                avg_importance REAL DEFAULT 5.0,
-                top_entities TEXT DEFAULT '[]',
-                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
+                name TEXT NOT NULL,
+                description TEXT,
+                member_count INTEGER DEFAULT 0,
+                avg_importance REAL,
+                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+                updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
📝 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
cursor.execute('''
CREATE TABLE IF NOT EXISTS graph_edges (
id INTEGER PRIMARY KEY AUTOINCREMENT,
source_memory_id INTEGER NOT NULL,
target_memory_id INTEGER NOT NULL,
similarity REAL NOT NULL,
relationship_type TEXT,
shared_entities TEXT DEFAULT '[]',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (source_memory_id) REFERENCES memories(id),
FOREIGN KEY (target_memory_id) REFERENCES memories(id),
UNIQUE(source_memory_id, target_memory_id)
)
''')
cursor.execute('''
CREATE TABLE IF NOT EXISTS graph_clusters (
id INTEGER PRIMARY KEY AUTOINCREMENT,
cluster_name TEXT,
description TEXT,
memory_count INTEGER DEFAULT 0,
avg_importance REAL DEFAULT 5.0,
top_entities TEXT DEFAULT '[]',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
''')
cursor.execute('''
CREATE TABLE IF NOT EXISTS graph_edges (
id INTEGER PRIMARY KEY AUTOINCREMENT,
source_memory_id INTEGER NOT NULL,
target_memory_id INTEGER NOT NULL,
relationship_type TEXT,
weight REAL DEFAULT 1.0,
shared_entities TEXT DEFAULT '[]',
similarity_score REAL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (source_memory_id) REFERENCES memories(id),
FOREIGN KEY (target_memory_id) REFERENCES memories(id),
UNIQUE(source_memory_id, target_memory_id)
)
''')
cursor.execute('''
CREATE TABLE IF NOT EXISTS graph_clusters (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
description TEXT,
member_count INTEGER DEFAULT 0,
avg_importance REAL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
''')
🤖 Prompt for AI Agents
In `@src/setup_validator.py` around lines 241 - 266, The CREATE TABLE statements
for graph_edges and graph_clusters use column names (e.g., similarity,
cluster_name, memory_count) that don’t match GraphEngine’s insert schema (it
writes weight or similarity_score, name, member_count); update the CREATE TABLE
to use the exact column names GraphEngine expects (for graph_edges add/rename to
weight and/or similarity_score and keep foreign keys/UNIQUE, for graph_clusters
rename cluster_name->name and memory_count->member_count or add those columns as
aliases with the same defaults) so DB initialization matches GraphEngine inserts
and prevents write errors.

Comment thread src/setup_validator.py
Comment on lines +408 to +412
# Check database
print("Checking database...")
db_ok, db_msg, missing_tables = check_database()
print(f" {'✓' if db_ok else '○'} Database: {db_msg}")

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

Unused missing_tables variable triggers lint noise.
Prefix it or drop it since it’s not used.

♻️ Minimal fix
-    db_ok, db_msg, missing_tables = check_database()
+    db_ok, db_msg, _missing_tables = check_database()
📝 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
# Check database
print("Checking database...")
db_ok, db_msg, missing_tables = check_database()
print(f" {'✓' if db_ok else '○'} Database: {db_msg}")
# Check database
print("Checking database...")
db_ok, db_msg, _missing_tables = check_database()
print(f" {'✓' if db_ok else '○'} Database: {db_msg}")
🧰 Tools
🪛 Ruff (0.14.14)

[warning] 410-410: Unpacked variable missing_tables is never used

Prefix it with an underscore or any other dummy variable pattern

(RUF059)

🤖 Prompt for AI Agents
In `@src/setup_validator.py` around lines 408 - 412, The call to check_database()
returns three values but the third, missing_tables, is unused which causes lint
warnings; update the call in src/setup_validator.py (the block where
check_database() is invoked) to either ignore the third return by assigning it
to a prefixed name like _missing_tables or drop the third value from the
assignment (e.g., db_ok, db_msg = check_database() if check_database supports
that), and keep the existing print of Database using db_ok and db_msg unchanged.

varun369 added a commit that referenced this pull request May 31, 2026
CRITICAL fixes:
- Delete 238 garbage/template-leak facts from DB (polluting recall #1)
- Store quality gate rejects low-quality content before DB insert
- engine config access: getattr chain (was AttributeError in core_memory tool)

HIGH fixes:
- Process 97 pending memories stuck in pending.db
- Mode switching: accept uppercase A/B/C in argparse (already lowered)

SCORE NORMALIZATION:
- Final sigmoid in run_recall catches ranking pipeline re-scores
- All recall responses now score in [0,1]

BENCHMARK RESULTS (all 3 surfaces, mode A=B):
- MCP: 0.9s, Dashboard: 0.8s, CLI: 1.4s (via daemon)
- 6 channels contributing on every surface
- Scores normalized [0,1], injection 4K budget with core block

Co-Authored-By: Claude Opus 4.8 <[email protected]>
varun369 added a commit that referenced this pull request May 31, 2026
…ll (v3.5.5)

Closes the remember→recall window. engine.store_fast() does a synchronous
verbatim insert (memory + atomic_fact, FTS5 auto-populated) + single ~22ms
embedding, so a stored memory is recallable at rank #1 within ~240ms across
MCP/CLI/Dashboard. Slow enrichment (LLM extraction, graph) stays async.
Materializer enriches the verbatim fact in place. MCP remember routes through
daemon write-through with pending.db offline fallback.

Verified: store 0.24s → recall rank #1 (0.881) zero-wait. Suite 4,489 passed.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
varun369 added a commit that referenced this pull request Jun 18, 2026
…3.6.14

Stage-8 audit findings #1/#2/#3 (HIGH, memory-perf). The semantic-cache layer
held three unbounded/broken in-memory structures that grow for the daemon's
lifetime — directly violating the bounded-memory / no-leak requirement for the
recall/remember lifeline.

- semantic.py VCacheSemantic._index: add per-tenant LRU cap
  (semantic_max_index_entries, default 10000) inside the existing _index_lock;
  oldest-evicted, lossless (DB remains source of truth via vec_search fallback).
- boundary_store.py _cache: OrderedDict LRU capped at 50000; move_to_end on
  read/write hit, popitem(last=False) on overflow; load_all() returns OrderedDict
  so the semantic.py warm-start reassignment preserves LRU semantics.
- centroid_store.py rebuild_from_db: fix 2-tuple unpack of get_all_vectors()'s
  3-tuple return (entry_id, blob, context_fp) — the ValueError was caught
  fail-open, silently disabling the SAFE-CACHE adversarial defense on every
  warm-start with vectors present.

Independently validated by Opus; full suite 5918 passed / 0 failed.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
varun369 pushed a commit that referenced this pull request Oct 11, 2026
PR-245 recheck #1: deterministic manager-query interleavings expose foreign unload and stop commands; five regressions fail on the current removal order.

Co-Authored-By: Codex Sol 6.1 <[email protected]>
varun369 pushed a commit that referenced this pull request Oct 11, 2026
PR-245 recheck #1: pin definition identity and byte digest before OS mutation, revalidate the effective job before each destructive command, and abort on concurrent replacement. Serialize discovery through publication across all roots of the same user. Remove the unchecked macOS install unload and bind Windows orphan cleanup and deletion to the verified handle.

The exact reviewer race and cross-platform interleavings are now GREEN; service/caller modules pass 119 tests, registry/stdio modules 24, and Windows API contract mocks 3. Native Windows execution remains a platform validation follow-up.

Co-Authored-By: Codex Sol 6.1 <[email protected]>
neoneye pushed a commit to agent-memory-atlas-archive/qualixar--superlocalmemory that referenced this pull request Oct 13, 2026
Reject directory and leaf links, bind records to the canonical root, and use pinned directories with exclusive atomic record and reconnect publication. Regressions reproduce PR-245 qualixar#1 and directory-swap races without signaling real processes.

Co-Authored-By: Codex Sol 6.1 <[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