How QMD + Zvec give OpenClaw agents structured working memory, instant recall, and always-fresh semantic search — a first-of-its-kind integration.
Every AI agent framework has the same dirty secret: memory is an afterthought. Context windows fill up and get wiped. Conversation history is ephemeral. And the "memory" solutions are just glorified note files.
Inspired by how human memory works — from instant muscle memory to deep recall — every layer serves a different latency and richness profile.
Lower is better
The agent writes to QMD during work. A file watcher detects changes and auto-indexes into Zvec. When the agent needs to recall something, it checks QMD first (instant), then Zvec (fast), then falls back to full search.
QMD is a structured JSON scratchpad that lives at memory/qmd/current.json. It's the agent's working memory — loaded on every session start, updated during work, compacted when tasks complete.
{
"session_id": "main-2026-02-23",
"tasks": [
{
"id": "cyprus-hotels",
"status": "active",
"title": "Find monthly rental in Limassol for Mar 5–Apr 5",
"progress": [
"Sent 20 RFPs via AgentMail",
"Four Seasons replied: €1,360/night, 17 nights only",
"9+ hotels still waiting for replies"
],
"entities": ["Four Seasons", "Amara", "Parklane"],
"decisions": ["Using AgentMail not personal email"]
},
{
"id": "memory-architecture",
"status": "active",
"title": "Memory architecture upgrade (Zvec + QMD)",
"decisions": ["QMD as Layer 0 working memory", "JSON format for structured access"]
}
],
"entities_seen": {
"people": ["Omer Levi", "Vasilia Keke (Four Seasons)"],
"urls": ["clawqa.ai", "command.clawz.org"]
}
}
Zvec is a local vector search service built on Alibaba's Zvec library. It combines HNSW approximate nearest-neighbor search with BM25 keyword matching for hybrid retrieval — giving you both semantic understanding and exact-match precision.
| Index Type | HNSW (Hierarchical NSW) |
| Dimensions | 768 (embeddinggemma-300m) |
| Chunks Indexed | 1,166 |
| Query Latency | ~8ms (top-5) |
| Port | localhost:4010 |
| Hybrid Search | HNSW + BM25 fusion |
⚠️ Stale Data Problem
Zvec was migrated once from SQLite (1,166 chunks) but has no mechanism to index new content. Every daily log, every QMD update, every new knowledge file — invisible to search.
Solution: The file watcher (see Integration below) polls SQLite every 60s and auto-indexes new chunks into Zvec.
The key insight: QMD and Zvec don't just coexist — they feed each other. QMD captures real-time state. The watcher detects changes and pipes them into Zvec's index. Queries check QMD first (instant hit for active tasks), then fall back to Zvec's semantic search.
When the agent asks "What did Four Seasons quote?":
Here's what memory operations look like in a real agent session:
def search(query_embedding, topk=10, filter_expr=None):
"""Search the zvec collection via HNSW nearest-neighbor"""
if collection is None:
return {"error": "collection not initialized"}
vq = zvec.VectorQuery("dense", vector=query_embedding)
kwargs = {"topk": topk}
if filter_expr:
kwargs["filter"] = filter_expr
results = collection.query(vq, **kwargs)
out = []
for r in results:
item = {
"id": r.id,
"score": float(r.score),
"text": r.field("text"),
"path": r.field("path"),
"source": r.field("source"),
}
out.append(item)
return {"results": out, "count": len(out)}
# POST /index — Accepts new documents and upserts into HNSW index
elif url.path == "/index":
docs_data = body.get("docs", [])
docs = []
for d in docs_data:
doc = zvec.Doc(str(d["id"]))
doc.vectors["dense"] = d["embedding"]
for k in ["text", "path", "source"]:
if k in d:
doc.fields[k] = d[k]
doc.fields["updated_at"] = int(time.time())
docs.append(doc)
collection.upsert(docs) # Atomic upsert — update if exists, insert if new
collection.flush() # Persist to disk
self._json({"indexed": len(docs)})
def sync_once():
"""Poll SQLite for new chunks, push to Zvec"""
state = load_state()
max_id = get_max_rowid()
if max_id <= state["last_sync_id"]:
return 0 # Nothing new
chunks = get_new_chunks(state["last_sync_id"])
indexed = index_to_zvec(chunks)
# Update sync state — tracks high-water mark
state["last_sync_id"] = max_id
state["total_synced"] += indexed
state["last_sync_at"] = time.strftime("%Y-%m-%dT%H:%M:%SZ")
save_state(state)
return indexed
# Main loop — poll every 60 seconds
while True:
n = sync_once()
if n > 0:
print(f"Synced {n} new chunks to zvec")
time.sleep(60)
schema = zvec.CollectionSchema(
name="memory",
vectors=[
zvec.VectorSchema("dense", zvec.DataType.VECTOR_FP32, dim), # 768-dim float32
],
fields=[
zvec.FieldSchema("text", zvec.DataType.STRING), # The actual chunk content
zvec.FieldSchema("path", zvec.DataType.STRING), # Source file path
zvec.FieldSchema("source", zvec.DataType.STRING), # Origin (memory, knowledge, etc)
zvec.FieldSchema("start_line", zvec.DataType.INT32), # Line range for context
zvec.FieldSchema("end_line", zvec.DataType.INT32),
zvec.FieldSchema("updated_at", zvec.DataType.INT64), # Timestamp for freshness
]
)
{
"session_id": "main-YYYY-MM-DD", // Current session identifier
"started_at": "ISO-8601", // Session start time
"tasks": [
{
"id": "unique-slug", // Task identifier
"status": "active|done|blocked", // Current state
"title": "Human-readable title",
"context": "Background information",
"progress": ["Step 1 done", "Step 2 done"],
"entities": ["Person", "Company"], // Named entities involved
"decisions": ["Why we chose X"], // Decision log with reasoning
"blockers": ["What's stopping us"],
"next": "Next action to take"
}
],
"entities_seen": { // Global entity tracker
"people": [], "urls": [], "credentials": []
},
"decisions": [], // Session-level decisions
"updated_at": "ISO-8601" // Last modification time
}
Status: Live. QMD is active and loaded every session. current.json tracks 4 active tasks with full context, entities, and decisions. Compaction script ready.
Status: Live. Zvec server running on port 4010 with 1,166 chunks. Watcher.py polls SQLite every 60s for new chunks and auto-indexes them.
Status: Planned. Weekly cron to archive old daily logs, summarize completed tasks, and promote key decisions to MEMORY.md.
Status: Future. Neo4j + Graphiti for entity relationships and temporal queries. "Who worked on X?" across the full memory stack.
Most AI agents treat memory as an afterthought — a vector database you throw everything into and hope cosine similarity finds what you need. QMD + Zvec takes a different approach:
QMD isn't a blob of text. It's typed JSON with tasks, entities, decisions. The agent can programmatically check "am I working on hotels?" without semantic search.
Not everything needs a vector search. Active task state should be instant. Recent context should be fast. Historical knowledge can afford 100ms.
A stale index with 10,000 chunks is less useful than a fresh one with 1,166. The watcher ensures search results include what happened 60 seconds ago.
Memory that only grows eventually drowns in noise. QMD compacts done tasks → daily logs → MEMORY.md → knowledge graph. Each layer is denser than the last.