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

推荐订阅源

B
Blog
V
Vulnerabilities – Threatpost
Apple Machine Learning Research
Apple Machine Learning Research
V
V2EX
博客园 - 叶小钗
阮一峰的网络日志
阮一峰的网络日志
人人都是产品经理
人人都是产品经理
Latest news
Latest news
博客园 - 三生石上(FineUI控件)
美团技术团队
aimingoo的专栏
aimingoo的专栏
Google Online Security Blog
Google Online Security Blog
Security Archives - TechRepublic
Security Archives - TechRepublic
T
Threatpost
Y
Y Combinator Blog
T
Tailwind CSS Blog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
A
Arctic Wolf
C
Cyber Attacks, Cyber Crime and Cyber Security
小众软件
小众软件
Recent Commits to openclaw:main
Recent Commits to openclaw:main
T
Tenable Blog
W
WeLiveSecurity
L
LINUX DO - 热门话题
D
Docker
Cyberwarzone
Cyberwarzone
量子位
A
About on SuperTechFans
The Last Watchdog
The Last Watchdog
雷峰网
雷峰网
C
CERT Recently Published Vulnerability Notes
P
Palo Alto Networks Blog
The Hacker News
The Hacker News
Blog — PlanetScale
Blog — PlanetScale
P
Proofpoint News Feed
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
F
Full Disclosure
The Cloudflare Blog
T
The Blog of Author Tim Ferriss
T
The Exploit Database - CXSecurity.com
Engineering at Meta
Engineering at Meta
O
OpenAI News
Hacker News - Newest:
Hacker News - Newest: "LLM"
Scott Helme
Scott Helme
IT之家
IT之家
S
Secure Thoughts
MongoDB | Blog
MongoDB | Blog
L
Lohrmann on Cybersecurity
博客园 - 司徒正美
Google DeepMind News
Google DeepMind News

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 Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Your AI Agent is Stuck in a Loop. Here's the Memory Layer That Breaks It and Saves You Money
Enrique B. · 2026-05-19 · via DEV Community

Every time you open a new chat in Cursor, VS Code, Antigravity and even Claude Desktop, you paste your codebase back in. Or you let the IDE do it automatically, same result. You're burning context tokens on files the agent already "knew" ten minutes ago in a different window. The agent re-reads my_models.py, your_script.js, their_script.ts, index.html and the three service files it touched yesterday, just to orient itself before answering your actual question.

That's not a context window problem. It's a memory architecture problem. There's no persistence layer between sessions or IDEs. The fix isn't a bigger context window; it's not sending the same data twice.

In a real test session with Copilot, after three exchanges with four unnecessary re-queries, zerikai_memory's tool results accounted for just 1.6% of a 128K context window. A raw file-chunk retrieval setup doing the same work would burn ~40% of that window before you got to your actual question. On the DeepSeek side, locking the project brief as a fixed system prefix means every query hits the KV cache at $0.0028/M tokens instead of $0.14/M, a 50x cost reduction on the largest token block per call.

That's the exact problem zerikai_memory was built to solve. (Open source)


Hi, I'm Enrique, an AI software engineer with over 30 years of tech experience. I built zerikai_memory after diagnosing a structural bottleneck in my own workflows: context loss between sessions, redundant re-injection across IDEs, and rising per-query costs that compound with every sloppy retrieval. The rising cost of AI IDE subscriptions made the economics impossible to ignore, but the underlying architecture problem was already there. zerikai_memory is the engineering response to that diagnosis, built for developers who want precision and cost control.


What It Actually Does

Indexing workflow

zerikai_memory is a local MCP server. Any IDE that supports the Model Context Protocol (Cursor, pi, Antigravity, Copilot, and even Claude Desktop) can connect to it. When you run scan_workspace, it walks your project using tree-sitter to parse source files into individual code entities: Functions, Classes, Methods, HTML components.

Each entity gets its own embedding in a local ChromaDB collection, along with structured metadata: Language, Return type, Parent class, Line numbers, Param count, Decorators, Docstring presence.

That last part matters. Most RAG setups (including the ones built into commercial IDEs) chunk files by token count or line count, which means a function might get split across two chunks, or buried under 500 lines of imports. This is a corner being cut at your expense: you pay for the tokens, the agent gets noise. zerikai_memory treats each function as the atomic unit instead. extract_entities in code_indexer.py returns a list of CodeEntity objects, one per parsed symbol: clean signal, no noise.

When your agent queries memory, along with the raw answer, it gets inline source citations back:

Sources: `extract_entities` #code_indexer.py:184 (0.35)
`_extract_js_function` #code_indexer.py:595 (0.81)
`_extract_js_like` #code_indexer.py:543 (0.89)
`CodeEntity` #code_indexer.py:156 (0.83)
`_extract_html` #code_indexer.py:907 (0.84)

(raw answer synthesized from those sources)

Enter fullscreen mode Exit fullscreen mode

The IDE agent doesn't hunt for the function; the citations give it the exact file, line number, and L2 distance score. #code_indexer.py:184 is plain text that renders in every IDE and is clickable in VS Code Copilot, so you can jump straight to the source too. No additional search, no extra API call.


The Indexing Cost Is Zero

tree-sitter is a deterministic local parser. It runs entirely on your machine, no API calls, no LLM involvement. Parsing and embedding your codebase costs $0.00.

The only thing that costs money is the project brief: a 9-section structured summary (Overview, Technical Stack, Core Architecture, Primary Conventions, Purpose, Key Files, Data Flow, Development & Testing, Future Roadmap). That brief is generated once after the first scan using either the DeepSeek API or Ollama. With DeepSeek, it's a few cents. With Ollama, it's free. After that, the brief is locked and cached.

Why lock it? Because the brief is the fixed prefix of every system message sent to DeepSeek. DeepSeek's KV cache means identical prefixes are stored server-side after the first call, so subsequent queries hit the cache at $0.0028/M tokens instead of \$0.14/M tokens. That's a 50× cost reduction on the largest token block per query. Intentionally keeping the brief stable is what makes that discount work consistently.

If you update the Architecture or implement a large feature, you can regenerate the brief by asking the MCP server to update_brief.


Auto-Routing: Paying Only for What Needs It

Not every query deserves a cloud LLM. A lookup like "where is process_data defined?" is a short, specific question that Ollama handles fine locally. An architectural question like "explain how the query routing pipeline decides between DeepSeek v4-flash and v4-pro" is a 20-word query touching design decisions, and that earns the cloud call.

The routing logic in _should_use_cloud() runs a 4-step priority chain on every incoming query:

  1. Explicit override: use_cloud=True or use_cloud=False passed directly; short-circuits everything else.
  2. Architectural keyword escalation: if the query contains design/architecture terms (configured in config.py), route to DeepSeek.
  3. Length escalation: queries of 40 words or more route to DeepSeek.
  4. Default fallback: fall back to whatever MEMORY_MODE is set to in .env (local, cloud, or hybrid).

Within the DeepSeek path, _select_model picks between v4-flash and v4-pro based on query complexity. Short cloud queries get the cheaper model; heavier ones get the capable one. You're not paying v4-pro rates for a function lookup.

Tip: start in cloud mode (DeepSeek API), then you can try hybrid and then local (Ollama).


Lexical Re-ranking: Fixing the Semantic Similarity False Positive Problem

Lexical re-ranking

Semantic similarity alone has a well-known failure mode: a generic function that describes the same concept as your query can outscore the specific function you actually want. A file summary mentioning "parsing" might beat parse_entities() in cosine space if the embeddings aren't tight.

zerikai_memory adds a re-ranking pass on top of ChromaDB's semantic results. After distance filtering removes weak matches, survivors are re-scored by weighted keyword overlap in entity names and docstrings:

score = (1 / distance) + (keyword_hits × LEXICAL_RERANK_WEIGHT)

Enter fullscreen mode Exit fullscreen mode

A function named extract_entities will outrank a vague file-level summary that happened to embed close to the query. No results are dropped; it's a pure reorder. The weight is configurable via ENABLE_LEXICAL_RERANK in .env. It's off by default; turn it on if you're seeing generic summaries crowding out specific function hits.

The reranking test in the inline citations example above shows it working:

  • VS Code Query:
{
  "workspace": "zerikai_memory",
  "user_query": "extract function for parsing code entities from source files. Show me the Sources table."
}

Enter fullscreen mode Exit fullscreen mode

Agent chat window screen grab

Returns extract_entities at distance 0.35 as the top hit, with the JS and HTML extractors behind it. Notably, _extract_markdown didn't appear despite sharing vocabulary, which is exactly the false positive problem the re-ranker exists to solve.


Context Window Impact

Entity-level indexing matters most when the agent is sloppy. In a test session with Copilot, after three back-and-forth exchanges (including four re-queries it didn't need), the context window sat at 17.1K of 128K tokens, just 13%. The tool results from Zerikai accounted for 1.6% of that total.

If zerikai returned raw file chunks instead of individual entities, a single retrieval might pull 500 lines of a file to find one function. Twelve retrievals across three turns could burn north of 40% of the window before you even got to your actual work.

Entity-level (zerikai, tested) Raw file chunks (estimated)
Tool results after 3 turns, 4 calls 1.6% of window (~2K tokens) ~40% of window (~50K tokens)
Space left for actual work ~111K tokens ~28K tokens
Agent re-queries Negligible cost Amplifies the burn

When the agent re-queries four times because it summarized too aggressively, entity-level indexing means it burned 800 tokens, not 50,000. The real cost of a bad agent layer is multiplied by how much data each retrieval returns (one of the reasons I migrated to pi.dev, but that's another write-up).

Small retrievals save you twice: they stretch your IDE's token quota and they shrink your DeepSeek bill. Pay for the brief once. Query your own code for free.


How Agents Display Source Citations

zerikai memory returns the full #file:line (distance) in every response. But each agent publisher decides how much of it to surface. The same query, same tool, four different agents:

  • Example: "Sources: _truncate_for_brief #main.py:401 (0.62)"
Agent Calls Failed Showed L2 Notes
Antigravity (Gemini) 1 0 Yes Re-rendered inline text as a table
Claude Desktop 1 0 Yes Showed full citation in body
Copilot 5 0 No Re-queried 4x, hid distance from user until asked
Pi (inside workspace) 1 0 Yes One clean call when in the project path

The data is always there in context; the agent uses #file:line (distance) for reasoning regardless.

Ask: "show me the full sources with distances" and it surfaces the complete line. What you see is filtered by your agent's display layer, not by zerikai memory.


Workspace Isolation and .memignore

Every project gets its own ChromaDB sub-collection, its own SQLite records, and its own brief file. Queries for project_a don't pull from project_b. Workspaces are identified by normalized filesystem path with deterministic UUIDs, so the same project opened from different IDE windows or different paths resolves to the same memory store.

Before any file hits the indexer, .memignore filters it out. It works identically to .gitignore: glob patterns, # comments, blank lines ignored. node_modules/, .git/, venv/, compiled output: configure it once per workspace, it's enforced on every scan.

Scans are idempotent. Re-scanning the same file overwrites its existing records using deterministic hashing. Stale entries (files deleted or added to .memignore since the last scan) are automatically purged. Run scan_workspace as often as you want; no duplicates accumulate, no ghost records from renamed files.

Be discriminative with the files and folders added to .memignore. We tend to save test/ or research/, and other dated resources, which add unnecessary noise to the ChromaDB index. Add those types of folders and files to .memignore to ignore them during the scan.


Local Mode: Zero Cost, No Data Leaves Your Machine

If you're working on a private codebase or just don't want to touch a cloud API, set MEMORY_MODE=local in .env and point zerikai_memory at a running Ollama instance. Everything runs locally: parsing, embedding, retrieval, and synthesis. The inline citations still work. The project brief still generates. Auto-routing routes everything to Ollama. Token tracking still logs usage (it just logs zero cost).

This makes the local mode genuinely useful for confidential projects, not just a fallback. The main trade-off versus DeepSeek is synthesis quality on complex architectural queries, as Ollama models are capable but won't match v4-pro on multi-hop reasoning about your codebase design.


What It Doesn't Do

Worth being explicit: zerikai_memory doesn't replace your IDE's built-in context management for the file you're actively editing. It's additive; what it eliminates is the need to re-inject project-wide context at the start of every new session. It also doesn't currently support all languages tree-sitter handles; Python, JS/TS, HTML, CSS, and Markdown are covered, and others are on the roadmap.

The project brief is intentionally locked after the first scan. If your architecture changes significantly, you need to trigger update_brief via the MCP server. That's a manual step, and it's a deliberate trade-off for KV cache stability over automatic freshness.


Stack

  • Python: MCP server, query routing, brief synthesis
  • ChromaDB: local vector store (file-based, stored in .brain/vector_db/)
  • zerikai.db: SQLite workspace registry and token tracking (stored in .brain/zerikai.db)
  • tree-sitter: deterministic local code parser, zero API cost
  • DeepSeek: cloud LLM (v4-flash and v4-pro), with KV cache optimization
  • Ollama: local LLM for zero-cost operation

Getting Started: Index zerikai_memory itself as your first workspace. It's the fastest way to see how entity-level indexing, lexical re-ranking, and inline citations actually work before applying them to your own projects. If your language isn't supported yet, search PyPI for tree-sitter-<language> to find the grammar bindings, then use the MCP server itself to guide you through adding it to code_indexer.py. Rescan, and you're ready to index your other workspaces with the newly added language.

The repo is on GitHub: zerikai_memory

If you're running agent workflows across multiple IDEs or projects, the context re-injection overhead adds up. zerikai_memory cuts that out at the root.

The more interesting problems turned out to be elsewhere: getting traceable, line-precise source citations out of a retrieval layer so agents stop guessing and start pointing, and getting lexical re-ranking to prevent semantically close but functionally irrelevant results from crowding out the right answer.

Have you thought about the impact of traceable sources in your own agent workflows? Have you hit the false-positive problem in semantic memory search? Drop your setup and approach below.

Thank you

Enrique Bruzual