agentleFS
zircotezircote/git-notes-memory/CLAUDE.md

git-notes-memory

CLAUDE.md4 starsChanged 12 months agoMITArchived repositoryView on GitHub

git-notes-memory is a Python library and Claude Code plugin that provides git-native, semantically-searchable memory storage. Memories are stored as git notes with YAML front matter and indexed in SQLite with sqlite-vec for vector similarity search. The codebase uses a singleton service factory pattern with lazy initialization: Services are exposed through factory functions (get_*_service()) that return singleton instances. Internal modules use get_default_service() naming. Memories are stored under refs/notes/mem/{namespace} where namespace is one of: inception, elicitation, research, decisions, progress, blockers, reviews, learnings,…

The file

We split this CLAUDE.md into the rules it gives an agent

9 rules. About 0 are common, 4 are distinctive, and 5 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈4

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 5

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    All models are immutable (@dataclass(frozen=True)):

    line 159
  2. Very specific:

    Use LSP goToDefinition before modifying unfamiliar functions, classes, or modules

    line 263
  3. Very specific:

    Use LSP findReferences before refactoring any symbol to understand full impact

    line 264
  4. Very specific:

    Use LSP documentSymbol to get file structure overview before major edits

    line 265
  5. Distinctive:

    Prefer LSP navigation over grep—it resolves through imports and re-exports

    line 266
  6. Distinctive:

    After each edit, check hook output for lint/type errors

    line 270
  7. Very specific:

    Run make quality before committing

    line 272
  8. Distinctive:

    If hooks report errors, fix them before proceeding to the next task

    line 282
  9. Distinctive:

    Use hook output to guide fixes, not guesswork

    line 284

≈ “Common” is an estimate: at least 1 in 5 of the 12,729 CLAUDE.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
CLAUDE.md

CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

Project Overview

git-notes-memory is a Python library and Claude Code plugin that provides git-native, semantically-searchable memory storage. Memories are stored as git notes with YAML front matter and indexed in SQLite with sqlite-vec for vector similarity search.

Development Commands

# Install with dev dependencies
uv sync

# Run all tests
make test

# Run tests with coverage (80% minimum required)
make coverage

# Run a specific test file
uv run pytest tests/test_capture.py -v

# Run a single test
uv run pytest tests/test_capture.py::TestCaptureService::test_capture_basic -v

# Skip slow tests
uv run pytest -m "not slow"

# Run all quality checks (format, lint, typecheck, security, tests)
make quality

# Individual quality checks
make format     # Auto-fix formatting
make lint       # Ruff linting
make typecheck  # mypy strict mode
make security   # bandit security scan

# Version management
make version    # Show current version
make bump       # Bump patch version (0.3.1 → 0.3.2)
make bump-minor # Bump minor version (0.3.1 → 0.4.0)
make bump-major # Bump major version (0.3.1 → 1.0.0)
make bump-dry   # Preview version bump changes

Architecture

Service Layer Pattern

The codebase uses a singleton service factory pattern with lazy initialization:

__init__.py          # Lazy imports via __getattr__ to avoid loading embedding model at import
    └── get_capture_service()  → CaptureService
    └── get_recall_service()   → RecallService
    └── get_sync_service()     → SyncService

Services are exposed through factory functions (get_*_service()) that return singleton instances. Internal modules use get_default_service() naming.

Core Data Flow

Capture:
  CaptureService.capture()
      → validate (namespace, summary ≤100 chars, content ≤100KB)
      → serialize_note() (YAML front matter + body)
      → GitOps.append_note() (atomic append to refs/notes/mem/{namespace})
      → EmbeddingService.embed() (sentence-transformers, graceful degradation)
      → IndexService.insert() (SQLite + sqlite-vec)

Recall:
  RecallService.search()
      → EmbeddingService.embed(query)
      → IndexService.search_vector() (KNN via sqlite-vec)
      → Memory objects with distance scores

Git Notes Storage

Memories are stored under refs/notes/mem/{namespace} where namespace is one of: inception, elicitation, research, decisions, progress, blockers, reviews, learnings, retrospective, patterns

Each note has YAML front matter:

---
type: decisions
timestamp: 2024-01-15T10:30:00Z
summary: Use PostgreSQL for persistence
spec: my-project
tags: [database, architecture]
---
## Context
...

Key Modules

ModuleResponsibility
capture.pyMemory capture with file locking (fcntl) for concurrency
recall.pySearch and retrieval with progressive hydration
index.pySQLite + sqlite-vec for metadata and vector search
embedding.pySentence-transformer embeddings (all-MiniLM-L6-v2)
git_ops.pyGit notes operations with security validation
note_parser.pyYAML front matter parsing/serialization
models.pyFrozen dataclasses for all domain objects
sync.pyIndex synchronization with git notes
security/Secrets filtering and PII protection subsystem

Hooks Subsystem

The hooks/ module provides Claude Code hook handlers:

HandlerHook EventPurpose
session_start_handler.pySessionStartInjects memory context and response guidance
user_prompt_handler.pyUserPromptSubmitDetects capture markers ([decision], [learned], etc.)
post_tool_use_handler.pyPostToolUseSurfaces related memories after file operations
pre_compact_handler.pyPreCompactAuto-captures content before context compaction
stop_handler.pyStopSession analysis and index sync

Supporting modules:

  • context_builder.py - Builds XML memory context with token budgeting
  • guidance_builder.py - Loads response guidance templates from templates/
  • signal_detector.py - Pattern matching for capture markers
  • config_loader.py - Environment-based hook configuration
  • namespace_styles.py - ANSI colors and emojis for namespace display

Security Subsystem

The security/ module provides secrets filtering and PII protection:

ModuleResponsibility
config.pyEnvironment-based configuration for filtering behavior
detector.pyDetectSecretsAdapter wrapping detect-secrets library
pii.pyPIIDetector for SSN, credit cards, phone numbers
redactor.pyRedactor applies strategies (redact/mask/block/warn)
allowlist.pyAllowlistManager for false positive management
service.pySecretsFilteringService orchestrating the pipeline
audit.pyAuditLogger for compliance logging (SOC2/GDPR)
models.pySecretDetection, FilterResult, FilterAction types

Filtering Strategies:

  • REDACT: Replace with [REDACTED:type]
  • MASK: Show partial content abc...xyz
  • BLOCK: Raise BlockedContentError
  • WARN: Log but pass through unchanged

Detection Flow:

Content → PIIDetector → DetectSecretsAdapter → Deduplicate → AllowlistCheck → Redactor → FilterResult

Models

All models are immutable (@dataclass(frozen=True)):

  • Memory - Core entity with id format {namespace}:{commit_sha}:{index}
  • MemoryResult - Memory + distance score from vector search
  • CaptureResult - Operation result with success/warning status
  • HydrationLevel - SUMMARY → FULL → FILES progressive loading

Claude Code Plugin Integration

The plugin.json and hooks in hooks/ directory define the plugin:

  • Commands: /memory:capture, /memory:recall, /memory:search, /memory:sync, /memory:status
  • Secrets Commands: /memory:scan-secrets, /memory:secrets-allowlist, /memory:test-secret, /memory:audit-log
  • Hooks: SessionStart, UserPromptSubmit, PostToolUse, PreCompact, Stop
  • Skills: memory-recall for semantic search

Code Conventions

  • Python 3.11+ with full type annotations (mypy strict)
  • Google-style docstrings
  • Frozen dataclasses for all models (immutability)
  • Tuple over list for immutable collections in models
  • Factory functions expose services; internal modules use get_default_service()
  • Graceful degradation: embedding failures don't block capture

Testing

The test suite uses pytest with automatic singleton reset via conftest.py. Each test gets isolated service instances to prevent cross-test pollution.

# Tests automatically reset singletons via autouse fixture
# For manual isolation, use tmp_path and monkeypatch:
@pytest.fixture
def capture_service(tmp_path, monkeypatch):
    monkeypatch.setenv("MEMORY_PLUGIN_DATA_DIR", str(tmp_path))
    return get_capture_service(repo_path=tmp_path)

Environment Variables

Core Configuration

VariableDescriptionDefault
MEMORY_PLUGIN_DATA_DIRData/index directory~/.local/share/memory-plugin/
MEMORY_PLUGIN_GIT_NAMESPACEGit notes ref prefixrefs/notes/mem
MEMORY_PLUGIN_EMBEDDING_MODELEmbedding modelall-MiniLM-L6-v2

Hook Configuration

VariableDescriptionDefault
HOOK_ENABLEDMaster switch for all hookstrue
HOOK_SESSION_START_ENABLEDEnable SessionStart context injectiontrue
HOOK_SESSION_START_FETCH_REMOTEFetch notes from remote on session startfalse
HOOK_USER_PROMPT_ENABLEDEnable capture marker detectionfalse
HOOK_POST_TOOL_USE_ENABLEDEnable file-contextual memory injectiontrue
HOOK_PRE_COMPACT_ENABLEDEnable auto-capture before compactiontrue
HOOK_STOP_ENABLEDEnable Stop hook processingtrue
HOOK_STOP_PUSH_REMOTEPush notes to remote on session stopfalse
HOOK_DEBUGEnable debug logging to stderrfalse
HOOK_SESSION_START_INCLUDE_GUIDANCEInclude response guidance templatestrue
HOOK_SESSION_START_GUIDANCE_DETAILGuidance level: minimal/standard/detailedstandard

Secrets Filtering Configuration

VariableDescriptionDefault
SECRETS_FILTER_ENABLEDEnable/disable secrets filteringtrue
SECRETS_FILTER_STRATEGYDefault strategy: redact, mask, block, warnredact
SECRETS_FILTER_ENTROPY_ENABLEDEnable entropy-based detectiontrue
SECRETS_FILTER_PII_ENABLEDEnable PII detection (SSN, credit cards, phones)true
SECRETS_FILTER_AUDIT_ENABLEDEnable audit loggingtrue
SECRETS_FILTER_AUDIT_DIRAudit log directory~/.local/share/memory-plugin/audit/

Remote Sync (Team Collaboration)

For team environments where multiple developers share memories:

# Enable automatic sync with remote (opt-in)
export HOOK_SESSION_START_FETCH_REMOTE=true  # Fetch from remote on session start
export HOOK_STOP_PUSH_REMOTE=true            # Push to remote on session stop

With these enabled, memories are automatically synchronized with the origin repository:

  • Session start: Fetches and merges remote notes using cat_sort_uniq strategy
  • Session stop: Pushes local notes to remote

Manual sync is always available via /memory:sync --remote.

Code Intelligence (LSP)

LSP hooks are configured in .claude/hooks.json for immediate feedback on Python edits.

Installed Hooks

HookTriggerAction
format-on-editPostToolUse (Write/Edit)Runs ruff format on changed files
lint-check-on-editPostToolUse (Write/Edit)Runs ruff check on changed files
typecheck-on-editPostToolUse (Write/Edit)Runs mypy on changed files
pre-commit-quality-gatePreToolUse (git commit)Runs full make quality before commit

Navigation & Understanding

  • Use LSP goToDefinition before modifying unfamiliar functions, classes, or modules
  • Use LSP findReferences before refactoring any symbol to understand full impact
  • Use LSP documentSymbol to get file structure overview before major edits
  • Prefer LSP navigation over grep—it resolves through imports and re-exports

Verification Workflow

  1. After each edit, check hook output for lint/type errors
  2. Fix errors immediately before proceeding
  3. Run make quality before committing

Pre-Edit Checklist

  • Navigate to definition to understand implementation
  • Find all references to assess change impact
  • Review type annotations via hover before modifying function signatures

Error Handling

  • If hooks report errors, fix them before proceeding to the next task
  • Type errors are blocking in this project (mypy strict mode)
  • Use hook output to guide fixes, not guesswork

Completed Spec Projects

  • docs/spec/completed/2025-12-25-observability-instrumentation/ - Observability Instrumentation
    • Completed: 2025-12-26
    • Outcome: success
    • GitHub Issue: #10
    • Features: Metrics collection, distributed tracing, structured logging, CLI commands (/metrics, /traces, /health)
    • Deliverables: 115+ tests, 4 phases completed (6 total, 2 optional skipped), 20 tasks, 11 ADRs
    • Note: Phases 5-6 (OpenTelemetry, Docker stack) skipped as optional Tier 3 enhancements
    • Key docs: REQUIREMENTS.md, ARCHITECTURE.md, IMPLEMENTATION_PLAN.md, DECISIONS.md, PROGRESS.md
  • docs/spec/completed/2025-12-25-secrets-filtering/ - Secrets Filtering and Sensitive Data Protection
    • Completed: 2025-12-25
    • Outcome: success
    • GitHub Issue: #12
    • Features: detect-secrets integration, custom PII detection (SSN, credit cards with Luhn, phones), 4 filtering strategies (REDACT/MASK/BLOCK/WARN), SOC2/GDPR audit logging
    • Deliverables: security/ module (7 components), 4 slash commands, 524 tests with 87%+ coverage
    • Key docs: REQUIREMENTS.md, ARCHITECTURE.md, IMPLEMENTATION_PLAN.md, DECISIONS.md, RETROSPECTIVE.md
  • docs/spec/completed/2025-12-25-fix-git-notes-fetch-refspec/ - Fix Git Notes Fetch Refspec
    • Completed: 2025-12-25
    • Outcome: success
    • GitHub Issue: #18
    • Features: Remote tracking refs pattern, idempotent migration, hook-based auto-sync, proper fetch→merge→push workflow
    • Deliverables: 26 tests, 5 phases, 20 tasks, 7 ADRs, complete documentation (2,648 lines)
    • Key docs: REQUIREMENTS.md, ARCHITECTURE.md, IMPLEMENTATION_PLAN.md, DECISIONS.md, RETROSPECTIVE.md

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.