W ai4rent.net
← Reference architecture Memory loop

Memory that improves the agent — without quietly poisoning it.

A three-layer memory system: readable workspace files, a fast local hybrid index and a shared global brain. The additions that matter are provenance, incremental sync and an evaluation gate on everything that claims to be an improvement.

TL;DR — Keep the three layers. Make writes transactional and attributable. Retrieve with BM25 + vectors. Evaluate every strategy and retrieval-weight change on a holdout set. Never let an agent’s own score be the only evidence that it got better.
Three-layer memory architecture Sources flow through ingestion and trust into the shared Postgres brain, then sync to workspace Markdown and a local SQLite hybrid index. Retrieval fuses BM25 and vectors with RRF. Feedback, consolidation and decay feed back into the brain. WRITE PATH Sources web · Discord · agents Ingest + validate dedupe · scan · trust label Shared brain · PostgreSQL knowledge · lessons · strategies Incremental sync watermark · event-driven Workspace Markdown · agent context Local index · SQLite FTS5 + vec0 · cached Quarantine unverified · conflicting local index reject / review READ PATH Agent query task context BM25 / FTS exact terms · IDs Vector semantic recall RRF fusion k=60 · evaluated α Rerank + gate freshness · trust context to agent LEARN PATH Retrieval feedback rank · usefulness · outcome Evaluation gate golden set · holdout Strategy / α update canary · rollback Consolidate / decay lessons · importance α / retrieval trusted lessons Trust is a field, not a feeling. source hash · author · trust level · ACL · expiry · evidence hash
The write path is governed; the read path is hybrid; the learn path is evaluated before it changes behaviour.

The three layers

Each layer has a different job. Do not collapse them into one database.

01

Workspace memory

~/.openclaw/workspace-{agent}/memory/

Human-readable Markdown, materialised from the shared brain. This is the agent’s context window: knowledge digest, peer knowledge, strategies, reflections and lessons.

Markdownper agentreviewable
02

Local hybrid index

~/.openclaw/memory/{agent}.sqlite

Fast, offline retrieval with FTS5 for exact terms and a vector table for semantic recall. Embeds once and caches by content hash.

SQLiteFTS5 + vec0no network
03

Shared global brain

PostgreSQL · schema: agency

Durable, cross-agent knowledge: knowledge, lessons, strategies, reflections, scores, competency and retrieval feedback. The source of truth for learning.

pgvectortsvector7 tables
Add a control plane. Ingestion, consolidation, decay, evolution and transfer are jobs, not tables. Put them behind a queue with locks, retries and audit logs.

The memory loop

A write is not finished when it is stored. It is finished when it is attributable, retrievable and evaluated.

1
Ingest

Research or task output becomes a candidate record with source, author and timestamp.

2
Validate

Deduplicate, classify and score trust. Unverified content goes to quarantine.

3
Persist

Write to PostgreSQL with embedding + tsvector; keep the event log.

4
Sync

Incremental materialisation to workspace Markdown, then reindex only changed chunks.

5
Retrieve

Local or global hybrid search: BM25 + vector, fused with RRF.

6
Learn

Log results and feedback; consolidate lessons; evaluate before any strategy or α change.

Hybrid retrieval

BM25 catches exact identifiers, error codes and names that embeddings blur. Vectors catch conceptual matches. Fuse both; do not choose one.

Fusion

score = (1 - α) / (k + rank_bm25)
      + α     / (k + rank_vector)

k = 60
α = 0.5 initially, clamped [0.2, 0.8]
α is per agent and changes only after
an offline evaluation gate.

When to use which index

  • Local SQLite — current task context, private workspace, offline.
  • Global PostgreSQL — peer knowledge, durable lessons, cross-agent strategies.
  • Both — merge candidates, then rerank with a small model or deterministic rules.
Do not tune α from clicks alone. “Was helpful” is sparse and biased. Use a labelled query set, measure recall@k and answer quality, and ship α changes as canaries.

Schema that supports trust

The original seven tables are a good base. Add provenance and trust to every knowledge record.

TablePurpose
agency.knowledgeDurable facts and research with embeddings and full-text index.
agency.lessonsTrigger → action lessons extracted from incidents and reviews.
agency.strategy_registryVersioned strategy prompts, scores, parent/child lineage.
agency.reflectionsPost-task analysis and proposed rewrites.
agency.score_ledgerImmutable score events — not a mutable average.
agency.agent_competencyPer-agent, per-skill tier and evidence.
agency.retrieval_feedbackQuery, result, rank and usefulness — the evaluation signal.
-- minimum trust fields
source_url, source_hash, author_agent, created_at,
trust_level: raw | verified | trusted,
trust_reason, expires_at, acl_scope

Consolidation, decay and forgetting

Decay keeps memory lean, but forgetting must be deliberate and auditable.

ClassDefaultRule
PermanentIdentity, soul, core memoryNever auto-archive; human pin only.
Short-termDaily logs14 days, importance-weighted; archived, not deleted.
Long-termReports, audits, digests90 days, then summary retained.

Importance multiplies the effective age, but keep a hard retention floor and an archive. A production incident at 2× importance should not become immortal by accident.

Strategy evolution with a brake

UCB selection and reflection are useful. They are not evidence on their own.

1
Register
2
Select
3
Execute
4
Score
5
Reflect
6
Evolve

What to measure

MetricQuestion it answers
Recall@kAre the right memories retrieved for a known query set?
Precision / noiseHow much irrelevant context enters the window?
StalenessMedian age of retrieved memory; drift from source.
Poison rateQuarantined or rejected records per 1,000 ingests.
Strategy deltaWin rate of a new strategy versus its parent on a holdout set.
Cost / queryEmbedding, vector and rerank cost per successful retrieval.

Failure modes

FailureCauseFix
Stale memorySix-hour full sync; no watermarkEvent-driven updates + reconciliation; surface freshness.
Poisoned knowledgeAny agent can ingest web/Discord textProvenance, trust level, quarantine, injection checks.
Runaway evolutionSelf-scored strategies; no holdoutOffline evaluation gate, canary, minimum sample, rollback.
Index driftSQLite rebuilt from changed filesContent hashes, incremental index, embedding version.
Privacy leakShared brain across agentsACL by agent/tenant, PII scan, retention policy.
Full reference PDF memory + workflow Next: task workflow →