โ† All skills
Tencent SkillHub ยท Developer Tools

Self-improving Agent Memory Upgrade (SurrealDB)

A comprehensive knowledge graph memory system with semantic search, episodic memory, working memory, automatic context injection, and per-agent isolation.

skill openclawclawhub Free
0 Downloads
0 Stars
0 Installs
0 Score
High Signal

A comprehensive knowledge graph memory system with semantic search, episodic memory, working memory, automatic context injection, and per-agent isolation.

โฌ‡ 0 downloads โ˜… 0 stars Unverified but indexed

Install for OpenClaw

Quick setup
  1. Download the package from Yavira.
  2. Extract the archive and review SKILL.md first.
  3. Import or place the package into your OpenClaw setup.

Requirements

Target platform
OpenClaw
Install method
Manual import
Extraction
Extract archive
Prerequisites
OpenClaw
Primary doc
SKILL.md

Package facts

Download mode
Yavira redirect
Package format
ZIP package
Source platform
Tencent SkillHub
What's included
SECURITY.md, SKILL.md, CHANGELOG.md, README.md, skill.json, INSTRUCTIONS.md

Validation

  • Use the Yavira download entry.
  • Review SKILL.md after the package is downloaded.
  • Confirm the extracted package contains the expected setup assets.

Install with your agent

Agent handoff

Hand the extracted package to your coding agent with a concrete install brief instead of figuring it out manually.

  1. Download the package from Yavira.
  2. Extract it into a folder your agent can access.
  3. Paste one of the prompts below and point your agent at the extracted folder.
New install

I downloaded a skill package from Yavira. Read SKILL.md from the extracted folder and install it by following the included instructions. Then review README.md for any prerequisites, environment setup, or post-install checks. Tell me what you changed and call out any manual steps you could not complete.

Upgrade existing

I downloaded an updated skill package from Yavira. Read SKILL.md from the extracted folder, compare it with my current installation, and upgrade it while preserving any custom configuration unless the package docs explicitly say otherwise. Then review README.md for any prerequisites, environment setup, or post-install checks. Summarize what changed and any follow-up checks I should run.

Trust & source

Release facts

Source
Tencent SkillHub
Verification
Indexed source record
Version
2.2.3

Documentation

ClawHub primary doc Primary doc: SKILL.md 36 sections Open source page

SurrealDB Knowledge Graph Memory v2.2

A comprehensive knowledge graph memory system with semantic search, episodic memory, working memory, automatic context injection, and per-agent isolation โ€” enabling every agent to become a continuously self-improving AI.

Description

Use this skill for: Semantic Memory โ€” Store and retrieve facts with confidence-weighted vector search Episodic Memory โ€” Record task histories and learn from past experiences Working Memory โ€” Track active task state with crash recovery Auto-Injection โ€” Automatically inject relevant context into agent prompts Outcome Calibration โ€” Facts gain/lose confidence based on task outcomes Self-Improvement โ€” Scheduled extraction and relation discovery make every agent smarter over time Triggers: "remember this", "store fact", "what do you know about", "memory search", "find similar tasks", "learn from history" Security: This skill reads workspace memory files and sends their content to OpenAI for extraction. It registers two background cron jobs and (optionally) patches OpenClaw source files. All behaviors are opt-in or documented. See SECURITY.md for the full breakdown before enabling. Required: OPENAI_API_KEY, surreal binary, python3 โ‰ฅ3.10

๐Ÿ”„ Self-Improving Agent Loop

This is the core concept: every agent equipped with this skill improves itself automatically, with no manual intervention required. Two scheduled cron jobs โ€” knowledge extraction and relationship correlation โ€” run on a fixed schedule and continuously grow the knowledge graph. Combined with auto-injection, the agent gets progressively smarter with each conversation.

The Cycle

[Agent Conversation] โ†“ stores important facts via knowledge_store_sync [Memory Files] โ† agent writes to MEMORY.md / daily memory/*.md files โ†“ every 6 hours โ€” extraction cron fires [Entity + Fact Extraction] โ† LLM reads files, extracts structured facts + entities โ†“ facts stored with embeddings + agent_id tag [Knowledge Graph] โ† SurrealDB: facts, entities, mentions โ†“ daily at 3 AM โ€” relation discovery cron fires [Relationship Correlation] โ† AI finds semantic links between facts โ†“ relates_to edges created between connected facts [Richer Knowledge Graph] โ† facts are no longer isolated; they form a web โ†“ on every new message โ€” auto-injection reads the graph [Context Window] โ† relevant facts + relations + episodes injected automatically โ†“ [Better Responses] โ† agent uses accumulated knowledge to respond more accurately โ†‘ new insights written back to memory files โ†’ cycle repeats

What Each Scheduled Job Does

Job 1 โ€” Knowledge Extraction (every 6 hours) Script: scripts/extract-knowledge.py extract Reads MEMORY.md and all memory/YYYY-MM-DD.md files in the workspace Uses an LLM (GPT-4) to extract structured facts, entities, and key concepts Hashes file content to skip unchanged files โ€” only processes diffs Stores each fact with: A vector embedding (OpenAI text-embedding-3-small) for semantic search A confidence score (defaults to 0.9) An agent_id tag so facts stay isolated to the right agent source metadata pointing back to the originating file Result: raw conversational knowledge becomes searchable, structured memory Job 2 โ€” Relationship Correlation (daily at 3 AM) Script: scripts/extract-knowledge.py discover-relations Queries the graph for facts that have no relationships yet ("isolated facts") Batches them and asks an LLM to identify semantic connections between them Creates relates_to edges in SurrealDB linking related facts Result: isolated facts become a connected knowledge web โ€” the agent can now traverse relationships, not just keyword-match Over time, the graph evolves from a flat list into a rich semantic network Job 3 โ€” Deduplication (daily at 4 AM) Script: scripts/extract-knowledge.py dedupe --threshold 0.92 Compares all facts using vector similarity (cosine distance) Facts above the threshold (92% similar) are flagged as duplicates Keeps the higher-confidence fact, removes the duplicate Prevents extraction from creating bloat over time Result: a clean, non-redundant knowledge base Job 4 โ€” Reconciliation (weekly, Sundays at 5 AM) Script: scripts/extract-knowledge.py reconcile --verbose Applies time-based confidence decay to aging facts Prunes facts that have decayed below minimum confidence Cleans orphaned entities with no linked facts Consolidates near-duplicate entities Result: the knowledge graph stays healthy, relevant, and pruned of stale information

Why This Makes Agents Self-Improving

When auto-injection is enabled, every new conversation starts with the most relevant slice of the accumulated knowledge graph. As the agent: Has conversations โ†’ writes insights to memory files Extraction job fires โ†’ converts those insights into structured facts Relation job fires โ†’ connects those facts to existing knowledge Next conversation โ†’ auto-injection pulls in richer, more connected context ...the agent effectively gets smarter with every cycle. It learns from its own outputs, grounds future responses in its accumulated history, and avoids repeating mistakes (via episodic memory and outcome calibration).

OpenClaw Cron Jobs (Required)

The skill requires 5 cron jobs for full self-improving operation. All run as isolated background sessions with no delivery: Job NameScheduleWhat it runsMemory Knowledge ExtractionEvery 6 hours (0 */6 * * *)extract-knowledge.py extract โ€” extracts facts from memory filesMemory Relation DiscoveryDaily at 3 AM (0 3 * * *)extract-knowledge.py discover-relations โ€” AI-powered relationship findingMemory DeduplicationDaily at 4 AM (0 4 * * *)extract-knowledge.py dedupe --threshold 0.92 โ€” removes duplicate/near-duplicate factsMemory ReconciliationWeekly Sun 5 AM (0 5 * * 0)extract-knowledge.py reconcile --verbose โ€” prunes stale facts, applies confidence decay, cleans orphans All jobs use sessionTarget: "isolated" with delivery: none. They run in fully isolated background sessions and never fire into the main agent session. A bottom-right corner toast notification appears in the Control UI when each job starts and completes. Setup commands (run after installation): # 1. Knowledge Extraction โ€” every 6 hours openclaw cron add \ --name "Memory Knowledge Extraction" \ --cron "0 */6 * * *" \ --agent main --session isolated --no-deliver \ --timeout-seconds 300 \ --message "Run memory knowledge extraction. Execute: cd SKILL_DIR && source .venv/bin/activate && python3 scripts/extract-knowledge.py extract" # 2. Relation Discovery โ€” daily at 3 AM openclaw cron add \ --name "Memory Relation Discovery" \ --cron "0 3 * * *" --exact \ --agent main --session isolated --no-deliver \ --timeout-seconds 300 \ --message "Run memory relation discovery. Execute: cd SKILL_DIR && source .venv/bin/activate && python3 scripts/extract-knowledge.py discover-relations" # 3. Deduplication โ€” daily at 4 AM openclaw cron add \ --name "Memory Deduplication" \ --cron "0 4 * * *" --exact \ --agent main --session isolated --no-deliver \ --timeout-seconds 120 \ --message "Run knowledge graph deduplication. Execute: cd SKILL_DIR && source .venv/bin/activate && python3 scripts/extract-knowledge.py dedupe --threshold 0.92" # 4. Reconciliation โ€” weekly on Sundays at 5 AM openclaw cron add \ --name "Memory Reconciliation" \ --cron "0 5 * * 0" --exact \ --agent main --session isolated --no-deliver \ --timeout-seconds 180 \ --message "Run knowledge graph reconciliation. Execute: cd SKILL_DIR && source .venv/bin/activate && python3 scripts/extract-knowledge.py reconcile --verbose" Replace SKILL_DIR with your actual skill path. To check job status: openclaw cron list

Adding Cron Jobs for a New Agent

When spawning a new agent that should self-improve, register its own extraction job: # OpenClaw cron add (via Koda) โ€” example for a 'scout-monitor' agent # Schedule: every 6h, extract facts tagged to scout-monitor python3 scripts/extract-knowledge.py extract --agent-id scout-monitor The --agent-id flag ensures extracted facts are isolated to that agent's pool and don't pollute the main agent's knowledge. Each agent self-improves independently while still reading shared scope='global' facts.

Features (v2.2)

FeatureDescriptionSemantic FactsVector-indexed facts with confidence scoringEpisodic MemoryTask histories with decisions, problems, solutions, learningsWorking MemoryYAML-based task state that survives crashesOutcome CalibrationFacts used in successful tasks gain confidenceAuto-InjectionRelevant facts/episodes injected into prompts automaticallyEntity ExtractionAutomatic entity linking and relationship discoveryConfidence DecayStale facts naturally decay over timeAgent IsolationEach agent has its own scoped memory pool; scope='global' facts are shared across all agentsSelf-Improving LoopScheduled extraction + relation discovery automatically grow the graph

Agent Isolation (v2.2)

Each agent in OpenClaw has its own scoped memory pool. Facts are tagged with agent_id on write; all read queries filter to (agent_id = $agent_id OR scope = 'global').

How it works

Agent A (main) Agent B (scout-monitor) โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚ 391 factsโ”‚ โ”‚ 0 factsโ”‚ โ† isolated pools โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ†‘ โ†‘ โ””โ”€โ”€โ”€โ”€ scope='global' โ”€โ”€โ”€โ”€โ”€โ”˜ โ† shared facts visible to both

Storing facts

All knowledge_store / knowledge_store_sync calls accept agent_id: # Stored to scout-monitor's pool only mcporter call surrealdb-memory.knowledge_store \ content="API is healthy at /ping" \ agent_id='scout-monitor' # Stored globally (visible to all agents) mcporter call surrealdb-memory.knowledge_store \ content="Project uses Python 3.12" \ agent_id='main' scope='global'

Auto-injection (agent-aware)

With references/enhanced-loop-hook-agent-isolation.md applied to src/agents/enhanced-loop-hook.ts, the enhanced loop automatically extracts the agent ID from the session key and passes it to memory_inject. No manual configuration needed โ€” each agent's auto-injection is silently scoped to its own facts.

Extraction (agent-aware)

Pass --agent-id to extract-knowledge.py so cron-extracted facts are correctly tagged: python3 scripts/extract-knowledge.py extract --agent-id scout-monitor Default is "main". Update cron jobs accordingly for non-main agents.

Backward compatibility

Existing facts without an explicit agent_id are treated as owned by "main". Nothing is lost on upgrade to v2.2.

Dashboard UI

The Memory tab in the Control dashboard provides a two-column layout:

Left Column: Dashboard

๐Ÿ“Š Statistics โ€” Live counts of facts, entities, relations, and archived items Confidence Bar โ€” Visual display of average confidence score Sources Breakdown โ€” Facts grouped by source file ๐Ÿฅ System Health โ€” Status of SurrealDB, schema, and Python dependencies ๐Ÿ”— DB Studio โ€” Quick link to SurrealDB's web interface

Right Column: Operations

๐Ÿ“ฅ Knowledge Extraction Extract Changes โ€” Incrementally extract facts from modified files Find Relations โ€” Discover semantic relationships between existing facts Full Sync โ€” Complete extraction + relation discovery Progress bar with real-time status updates ๐Ÿ”ง Maintenance Apply Decay โ€” Reduce confidence of stale facts Prune Stale โ€” Archive facts below threshold Full Sweep โ€” Complete maintenance cycle ๐Ÿ’ก Tips โ€” Quick reference for operations When the system needs setup, an Installation section appears with manual controls.

Prerequisites

SurrealDB installed and running: # Install (one-time) ./scripts/install.sh # Start server surreal start --bind 127.0.0.1:8000 --user root --pass root file:~/.openclaw/memory/knowledge.db Python dependencies (use the skill's venv): cd /path/to/surrealdb-memory python3 -m venv .venv source .venv/bin/activate pip install surrealdb openai pyyaml OpenAI API key for embeddings (set in OpenClaw config or environment) mcporter configured with this skill's MCP server

MCP Server Setup

Add to your config/mcporter.json: { "servers": { "surrealdb-memory": { "command": ["python3", "/path/to/surrealdb-memory/scripts/mcp-server-v2.py"], "env": { "OPENAI_API_KEY": "${OPENAI_API_KEY}", "SURREAL_URL": "http://localhost:8000", "SURREAL_USER": "root", "SURREAL_PASS": "root" } } } }

Core Tools

ToolDescriptionknowledge_searchSemantic search for factsknowledge_recallGet a fact with full context (relations, entities)knowledge_storeStore a new factknowledge_statsGet database statistics

v2 Tools

ToolDescriptionknowledge_store_syncStore with importance routing (high importance = immediate write)episode_searchFind similar past tasksepisode_learningsGet actionable learnings from historyepisode_storeRecord a completed task episodeworking_memory_statusGet current task statecontext_aware_searchSearch with task context boostingmemory_injectIntelligent context injection for prompts

memory_inject Tool

The memory_inject tool returns formatted context ready for prompt injection: # Scoped to a specific agent (returns only that agent's facts + global facts) mcporter call surrealdb-memory.memory_inject \ query="user message" \ max_facts:7 \ max_episodes:3 \ confidence_threshold:0.9 \ include_relations:true \ agent_id='scout-monitor' Output: ## Semantic Memory (Relevant Facts) ๐Ÿ“Œ [60% relevant, 100% confidence] Relevant fact here... ## Related Entities โ€ข Entity Name (type) ## Episodic Memory (Past Experiences) โœ… Task: Previous task goal [similarity] โ†’ Key learning from that task

Auto-Injection (Enhanced Loop Integration)

When enabled, memory is automatically injected into every agent turn: Enable in Mode UI: Open Control dashboard โ†’ Mode tab Scroll to "๐Ÿง  Memory & Knowledge Graph" section Toggle "Auto-Inject Context" Configure limits (max facts, max episodes, confidence threshold) How it works: On each user message, memory_inject is called automatically Relevant facts are searched based on the user's query If average fact confidence < threshold, episodic memories are included Formatted context is injected into the agent's system prompt v2.2: With references/enhanced-loop-hook-agent-isolation.md applied, the active agent's ID is automatically extracted from the session key and passed as agent_id โ€” each agent's injection is silently scoped to its own facts Configuration (in Mode settings): SettingDefaultDescriptionAuto-Inject ContextOffMaster toggleMax Facts7Maximum semantic facts to injectMax Episodes3Maximum episodic memoriesConfidence Threshold90%Include episodes when below thisInclude RelationsOnInclude entity relationships

CLI Commands

# Activate venv source .venv/bin/activate # Store a fact python scripts/memory-cli.py store "Important fact" --confidence 0.9 # Search python scripts/memory-cli.py search "query" # Get stats python scripts/knowledge-tool.py stats # Run maintenance python scripts/memory-cli.py maintain # Extract from files (incremental) python scripts/extract-knowledge.py extract # Extract for a specific agent python scripts/extract-knowledge.py extract --agent-id scout-monitor # Force full extraction (all files, not just changed) python scripts/extract-knowledge.py extract --full # Discover semantic relationships python scripts/extract-knowledge.py discover-relations

Tables

fact โ€” Semantic facts with embeddings and confidence entity โ€” Extracted entities (people, places, concepts) relates_to โ€” Relationships between facts mentions โ€” Fact-to-entity links episode โ€” Task histories with outcomes working_memory โ€” Active task snapshots

Key Fields (fact)

content โ€” The fact text embedding โ€” Vector for semantic search confidence โ€” Base confidence (0-1) success_count / failure_count โ€” Outcome tracking scope โ€” global, client, or agent agent_id โ€” Which agent owns this fact (v2.2)

Key Fields (episode)

goal โ€” What was attempted outcome โ€” success, failure, abandoned decisions โ€” Key decisions made problems โ€” Problems encountered (structured) solutions โ€” Solutions applied (structured) key_learnings โ€” Extracted lessons

Confidence Scoring

  • Effective confidence is calculated from:
  • Base confidence (0.0โ€“1.0)
  • + Inherited boost from supporting facts
  • + Entity boost from well-established entities
  • + Outcome adjustment based on success/failure history
  • Contradiction drain from conflicting facts
  • Time decay (configurable, ~5% per month)

Automated โ€” OpenClaw Cron (as deployed)

The self-improving loop runs via 4 registered OpenClaw cron jobs: Every 6h โ†’ extract-knowledge.py extract (extract facts from memory files) Daily 3 AM โ†’ extract-knowledge.py discover-relations (find relationships between facts) Daily 4 AM โ†’ extract-knowledge.py dedupe (remove duplicate facts) Weekly Sun โ†’ extract-knowledge.py reconcile (prune stale, decay, clean orphans) See the "OpenClaw Cron Jobs (Required)" section above for setup commands. To verify they're active: openclaw cron list To manually trigger any job: cd SKILL_DIR && source .venv/bin/activate python3 scripts/extract-knowledge.py extract python3 scripts/extract-knowledge.py discover-relations python3 scripts/extract-knowledge.py dedupe --threshold 0.92 python3 scripts/extract-knowledge.py reconcile --verbose

Manual (UI)

Use the Maintenance section in the Memory tab: Apply Decay โ€” Reduce confidence of stale facts Prune Stale โ€” Archive facts below 0.3 confidence Full Sweep โ€” Run complete maintenance cycle

Scripts

FilePurposemcp-server-v2.pyMCP server with all 11 toolsmcp-server.pyLegacy v1 MCP serverepisodes.pyEpisodic memory moduleworking_memory.pyWorking memory modulememory-cli.pyCLI for manual operationsextract-knowledge.pyBulk extraction from files (supports --agent-id)knowledge-tools.pyHigher-level extractionschema-v2.sqlv2 database schemamigrate-v2.pyMigration script

Integration

FilePurposeopenclaw-integration/gateway/memory.tsGateway server methodsopenclaw-integration/ui/memory-view.tsMemory dashboard UIopenclaw-integration/ui/memory-controller.tsUI controller

Troubleshooting

"Connection refused" โ†’ Start SurrealDB: surreal start --bind 127.0.0.1:8000 --user root --pass root file:~/.openclaw/memory/knowledge.db "No MCP servers configured" โ†’ Ensure mcporter is run from a directory containing config/mcporter.json with the surrealdb-memory server defined Memory injection returning null โ†’ Check that OPENAI_API_KEY is set in the environment โ†’ Verify SurrealDB is running and schema is initialized Empty search results โ†’ Run extraction from the UI or via CLI: python3 scripts/extract-knowledge.py extract "No facts to analyze" on relation discovery โ†’ This is normal if all facts are already related โ€” the graph is well-connected. Run extraction first if the graph is empty. Progress bar not updating โ†’ Ensure the gateway has been restarted after UI updates โ†’ Check browser console for polling errors Facts from wrong agent appearing โ†’ Check that agent_id is being passed correctly to all store/search calls โ†’ Verify references/enhanced-loop-hook-agent-isolation.md is applied for auto-injection scoping

Migration from v1 / v2.1

# Apply v2 schema (additive, won't delete existing data) ./scripts/migrate-v2.sh # Or manually: source .venv/bin/activate python scripts/migrate-v2.py All existing facts without an agent_id are treated as owned by "main" โ€” backward compatible.

Stats

Check your knowledge graph via UI (Dashboard section) or CLI: mcporter call surrealdb-memory.knowledge_stats Example output: { "facts": 379, "entities": 485, "relations": 106, "episodes": 3, "avg_confidence": 0.99 } v2.2 โ€” Agent isolation, self-improving loop, cron-based extraction & relationship correlation

Category context

Code helpers, APIs, CLIs, browser automation, testing, and developer operations.

Source: Tencent SkillHub

Largest current source with strong distribution and engagement signals.

Package contents

Included in package
5 Docs1 Config
  • SKILL.md Primary doc
  • CHANGELOG.md Docs
  • INSTRUCTIONS.md Docs
  • README.md Docs
  • SECURITY.md Docs
  • skill.json Config