惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

腾讯CDC
Engineering at Meta
Engineering at Meta
Last Week in AI
Last Week in AI
V
Visual Studio Blog
Stack Overflow Blog
Stack Overflow Blog
A
About on SuperTechFans
博客园 - 司徒正美
D
DataBreaches.Net
有赞技术团队
有赞技术团队
T
The Blog of Author Tim Ferriss
MyScale Blog
MyScale Blog
I
InfoQ
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
月光博客
月光博客
Google DeepMind News
Google DeepMind News
Recent Announcements
Recent Announcements
小众软件
小众软件
G
Google Developers Blog
博客园 - 【当耐特】
U
Unit 42
美团技术团队
B
Blog
D
Docker
Blog — PlanetScale
Blog — PlanetScale

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Claude Code Was Getting Dumber. Semantic Memory Fixed It.
Kunal Jaiswa · 2026-04-23 · via DEV Community

I use Claude Code as my primary development tool. It manages a home automation stack spread across five machines — camera monitors, WhatsApp agents, LLM inference pipelines, job scrapers, diet trackers. Over two months, the codebase grew to 30+ services with their own ports, configs, credentials, and war stories.

To keep Claude informed, I maintained documentation in .md files. camera_monitor.md. dgx_inference.md. openclaw_agents.md. One file per system, each containing architecture decisions, port numbers, credentials, known bugs, and fix history.

It worked great at 5 files. At 30, Claude started losing the plot.

The Problem With Files

Claude Code reads CLAUDE.md at session start. I added rules there: "read camera_monitor.md before touching the camera system." "Check dgx_inference.md for port mappings." Reasonable instructions.

But Claude's context window is finite. Each .md file averaged 200-400 lines. Loading 10 of them for a cross-system task consumed 3,000-4,000 tokens before Claude wrote a single line of code. And it had to decide which files to read — sometimes guessing wrong, reading 5 files before finding the answer in the 6th.

The symptoms were subtle:

  • Claude would re-explore code I'd already documented
  • It would suggest ports that were already in use
  • It would miss dependencies between services ("that endpoint moved to the Dell server last week")
  • It would launch Explore agents to grep the codebase for answers that existed in a .md file it hadn't loaded

Each session started with a tax: Claude burning context on orientation instead of doing work. The more documentation I wrote, the worse it got. A classic information retrieval problem disguised as a context window problem.

What RAG Doesn't Solve

The obvious answer is "just use RAG." Embed the docs, retrieve the relevant chunks, inject them into context. Every AI wrapper does this.

But RAG over documentation files has a specific failure mode: your retrieval unit is the wrong size. A .md file is either too big (wastes context with irrelevant sections) or you chunk it and lose the structural relationships between sections. The camera monitor doc has 15 sections — contour detection constants, RTSP URLs, the KV cache leak fix, the PyAV deadlock bug. A chunk retriever might return the RTSP URLs when you asked about the deadlock, because they share keywords like "camera" and "connection."

What I actually needed was a memory system — not document retrieval, but a knowledge base where each entry is a self-contained fact with metadata, and search is semantic, not keyword.

The Memory Server

I built a 767-line Python server that gives Claude six MCP tools: memory_search, memory_save, memory_list, memory_update, memory_delete, memory_stats.

Claude Code ──MCP/SSE──▶ memory_server.py (port 8042)
                              │
                              ├── sentence-transformers (all-MiniLM-L6-v2)
                              │     └── 384-dim embeddings, runs on CPU
                              │
                              ├── TurboQuant (4-bit vector compression)
                              │     └── in-memory index, persisted to disk
                              │
                              └── MySQL
                                    └── content, tags, category, agent_id, timestamps

Enter fullscreen mode Exit fullscreen mode

Each memory is a self-contained knowledge unit — a bug fix, a port mapping, an architecture decision, a credential, a "never do this" lesson. Not a document chunk. A fact.

The server exposes both MCP (for Claude Code) and REST (for other agents). Search is cosine similarity on MiniLM-L6-v2 embeddings, compressed to 4-bit with TurboQuant for a smaller memory footprint. Metadata lives in MySQL for filtering by category, tags, and agent.

The Memory-First Rule

The server alone isn't enough. Claude needs to be told to use it. In CLAUDE.md:

### MANDATORY: Memory-First Rule
**BEFORE reading any files, exploring code, or launching agents
— ALWAYS use `memory_search` first.**

**Order of operations for ANY question:**
1. `memory_search` with relevant keywords
2. Only if memory has no results → then read files/explore code
3. If memory server is down → fall back to local .md files

**DO NOT:** Launch Explore agents, read source files, or grep
the codebase as a first step. Memory has it.

Enter fullscreen mode Exit fullscreen mode

This single rule changed everything. Instead of reading 5 files to find a port number, Claude runs one semantic search and gets a scored result in <100ms. The context window stays clean for actual work.

What Went Into Memory

I wrote an import script that parsed every .md documentation file, split them by ## headers into self-contained sections, and bulk-loaded them as individual memories. 30 files became 200+ memories, each tagged with source file and category.

Some examples of what a single memory entry looks like:

  • "DGX Spark Ollama runs on port 11434, WebSocket proxy on 8765, adapter on 8091. Request flow: gate_monitor → adapter HTTP → WebSocket → proxy → Ollama."
  • "KV Cache Leak Fix: Ollama allocates full KV cache based on model's context_length field. Fix: create derived Modelfile with PARAMETER num_ctx 4096."
  • "Cross-thread RTSP kill bug: analysis_loop calling container.close() from wrong thread → PyAV deadlock at 300% CPU. Fix: threading.Event, rtsp_loop checks between frames."

Each one is a complete thought. No "see section 3.2 of camera_monitor.md." No dependency on having read the parent document. Claude searches "camera monitor RTSP bug" and gets exactly the fix history — nothing more, nothing less.

Per-Agent Isolation

The server enforces agent isolation. Every API call requires an agent parameter — claude, skippy, jot, hermes. Each agent only sees its own memories. agent="global" bypasses filtering for debugging.

if agent != "global":
    sql += " AND agent_id = %s"
    params.append(agent)

Enter fullscreen mode Exit fullscreen mode

This matters because I run multiple AI agents with different roles. Claude Code manages infrastructure. Skippy handled WhatsApp conversations. Each needs different knowledge, and neither should see the other's private data. One memory server, multiple isolated namespaces.

The Before and After

Before (file-based):

  1. Claude reads CLAUDE.md (200 lines)
  2. Claude decides which .md files might be relevant
  3. Claude reads 3-5 files (600-2000 lines)
  4. Claude sometimes reads the wrong files, backtracks
  5. Claude finally has enough context, starts working
  6. Context window: 2,000-4,000 tokens consumed on orientation

After (memory-first):

  1. Claude reads CLAUDE.md (200 lines, includes memory-first rule)
  2. Claude calls memory_search("camera monitor RTSP port") → 3 results, 50 lines
  3. Claude has the answer, starts working
  4. Context window: ~250 tokens consumed on orientation

The difference isn't just speed. It's accuracy. Memory search returns scored results ranked by semantic similarity. File reading returns entire documents and hopes Claude finds the relevant paragraph. Memory search at 0.4+ similarity threshold almost always returns the right answer. File reading sometimes returns the right file but the wrong section.

What I'd Change

Score tuning matters. I started with min_score: 0.3 which returned too many tangential results. Bumping to 0.4 cut noise significantly. Your threshold depends on your embedding model and memory granularity.

Memory hygiene is real work. Memories go stale. Ports change, services get decommissioned, bugs get fixed. You need to memory_update old entries or they'll mislead future sessions. I treat it like documentation — when I change a service, I update both the code and the memory.

The import granularity is critical. Too coarse (full documents) and you're back to RAG's chunking problem. Too fine (individual config values) and you lose relationships. ## header sections turned out to be the right unit for my documentation style — each section is typically one concept with enough context to stand alone.

The Stack

memory_server.py         — 767 lines, Python (Starlette + uvicorn)
sentence-transformers    — all-MiniLM-L6-v2, 384-dim embeddings
turboquant-vectors       — 4-bit vector compression + cosine search
MySQL                    — metadata, tags, categories, agent ownership
MCP SSE transport        — Claude Code native tool integration
REST API                 — /api/search, /api/save, /api/health (for other agents)
Dell R740 (Ubuntu)       — always-on server, port 8042

Enter fullscreen mode Exit fullscreen mode

202 memories. 6 tools. One rule in CLAUDE.md. Claude went from spending its first 30 seconds reading the wrong files to spending 100ms finding the right answer.

The irony isn't lost on me: I built an AI memory system to make a different AI smarter. But that's the actual state of the art — AI systems that get better not from bigger models, but from better access to the right information at the right time.