← Back to Plugins
Tools

PostClaw

ChristopherLittle51 By ChristopherLittle51 👁 425 views ▲ 0 votes

PostgreSQL-backed Persistent Memory System Plugin for OpenClaw.

GitHub

Install

npm install
npm

Configuration Example

{
  "plugins": {
    "load": { "paths": ["/absolute/path/to/PostClaw"] },
    "slots": { "memory": "postclaw" },
    "entries": {
      "postclaw": { "enabled": true }
    }
  }
}

README

# PostClaw โ€” PostgreSQL Memory Plugin for OpenClaw

<p align="center">
<img src="https://github.com/user-attachments/assets/2a7798c6-e711-40fa-bcf2-7416180651cc" 
        alt="PostClaw Logo - Postmodern Artwork of a giant lobster interspersed with technology and classical designs." 
        width="800" 
        height="600" 
        style="display: block; margin: 0 auto" />
</p>

**PostClaw** replaces OpenClaw's default memory system with a PostgreSQL backend powered by `pgvector`. It provides semantic search, episodic memory, knowledge graph linking, dynamic persona injection, and autonomous memory management for multi-agent swarms.

---

## Table of Contents

- [Features](#features)
- [Prerequisites](#prerequisites)
- [Quick Start](#quick-start)
- [Installation](#installation)
- [Database Setup](#database-setup)
- [Configuration](#configuration)
- [Plugin Hooks](#plugin-hooks)
- [Agent Tools](#agent-tools)
- [CLI Commands](#cli-commands)
- [Background Services](#background-services)
- [Database Schema](#database-schema)
- [Row-Level Security](#row-level-security)
- [Persona Bootstrap](#persona-bootstrap)
- [Sleep Cycle](#sleep-cycle)
- [Testing](#testing)
- [Troubleshooting](#troubleshooting)

---

## Features

| Feature | Description |
|---------|-------------|
| **Semantic Memory (RAG)** | Stores memories as vector embeddings in PostgreSQL via `pgvector` for contextual retrieval |
| **Episodic Memory** | Automatically logs user prompts and tool calls as short-term memory events |
| **Knowledge Graph** | Links related memories with typed, directed edges for graph-augmented retrieval |
| **Dynamic Persona Injection** | Injects agent-specific persona rules and RAG context into every prompt |
| **Duplicate Detection** | Identifies and merges near-duplicate memories during background maintenance |
| **Multi-Agent Isolation** | Row-Level Security (RLS) ensures agents can only read/write their own data |
| **Autonomous Management** | Agents silently store, update, link, and search memories without user prompts |

---

## Prerequisites

1. **OpenClaw** โ€” installed and configured
2. **PostgreSQL** (v14+) โ€” installed and running. The `pgvector` extension is installed automatically by the setup command.
3. **Node.js** (v18+) and **npm**
4. **Embedding Provider** โ€” LM Studio, Ollama, or any OpenAI-compatible endpoint serving an embedding model (e.g. `nomic-embed-text-v2-moe`)

---

## Quick Start

```bash
# 1. Install the plugin
openclaw plugins install @postclaw/postclaw        # from npm
# OR from a local path:
openclaw plugins install /path/to/PostClaw

# 2. Set up the database (creates DB, user, schema, everything)
openclaw postclaw setup

# 3. Restart the gateway
openclaw restart
```

Done. PostClaw will automatically:
- Connect to the database using the credential it just generated
- Start injecting RAG context and persona rules into every prompt
- Begin logging episodic memory after each agent turn
- Run the sleep cycle in the background every 6 hours

---

## Installation

### From npm (recommended)

```bash
openclaw plugins install @postclaw/postclaw
```

### From local path

```bash
# Copy into ~/.openclaw/extensions/postclaw/
openclaw plugins install /path/to/PostClaw

# Or link for development (live edits, no copy)
openclaw plugins install -l /path/to/PostClaw
```

### Manual

```bash
git clone <repository-url> PostClaw
cd PostClaw
npm install
npm run build
```

Then add to `~/.openclaw/openclaw.json`:

```json
{
  "plugins": {
    "load": { "paths": ["/absolute/path/to/PostClaw"] },
    "slots": { "memory": "postclaw" },
    "entries": {
      "postclaw": { "enabled": true }
    }
  }
}
```

---

## Database Setup

### Automated Setup

```bash
openclaw postclaw setup [options]
```

This command:
1. Connects to PostgreSQL as a superuser
2. Creates the `memorydb` database (if it doesn't exist)
3. Installs the `vector` and `pgcrypto` extensions
4. Creates the `openclaw` app user with a **random password**
5. Creates the `system_admin` role with RLS bypass
6. Builds all tables, triggers, indices, and RLS policies
7. Auto-updates `~/.openclaw/openclaw.json` with the connection string

#### Options

| Flag | Default | Description |
|------|---------|-------------|
| `--admin-url <url>` | `postgres://localhost/postgres` | Superuser connection string |
| `--db-name <name>` | `memorydb` | Database name |
| `--db-user <user>` | `openclaw` | App user name |
| `--db-password <pass>` | *auto-generated* | App user password |
| `--skip-config` | `false` | Don't auto-update `openclaw.json` |

#### Examples

```bash
# Local PostgreSQL with default peer auth
openclaw postclaw setup

# Remote / password-protected PostgreSQL
openclaw postclaw setup --admin-url postgres://postgres:[email protected]:5432/postgres

# Custom database and user names
openclaw postclaw setup --db-name myagent_memory --db-user myagent --db-password hunter2
```

#### Output

```
๐Ÿฆ PostClaw Database Setup

  โœ…  Connected to Postgres as superuser
  โœ…  Created database 'memorydb'
  โœ…  Created user 'openclaw'
  โœ…  Created role 'system_admin'
  โœ…  Schema created (6 tables, 14 indices, 18 RLS policies)
  โœ…  Granted permissions

โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”
  Database:     memorydb
  App User:     openclaw
  App Password: kR9x!mQ2vL8nP4wZ
  Admin User:   system_admin
  Admin Pass:   bN7yT3xK1mR5sW9e

  Connection:   postgres://openclaw:kR9x!mQ2vL8nP4wZ@localhost:5432/memorydb

  โœ… openclaw.json updated with dbUrl
โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”

  Save these credentials! They won't be shown again.
```

The setup is **fully idempotent** โ€” safe to re-run without errors.

---

## Configuration

All configuration lives in `~/.openclaw/openclaw.json`:

```json
{
  "plugins": {
    "slots": {
      "memory": "postclaw"
    },
    "entries": {
      "postclaw": {
        "enabled": true,
        "config": {
          "dbUrl": "postgres://openclaw:PASSWORD@localhost:5432/memorydb",
          "sleepIntervalHours": 6
        }
      }
    }
  },
  "agents": {
    "defaults": {
      "memorySearch": {
        "provider": "openai",
        "remote": {
          "baseUrl": "http://127.0.0.1:1234/v1/",
          "apiKey": "lm-studio"
        },
        "model": "text-embedding-nomic-embed-text-v2-moe"
      }
    }
  }
}
```

### Config Properties

| Key | Type | Default | Description |
|-----|------|---------|-------------|
| `dbUrl` | `string` | โ€” | PostgreSQL connection string (**required**) |
| `adminDbUrl` | `string` | โ€” | Superuser connection (only used by `postclaw setup`) |
| `sleepIntervalHours` | `number` | `6` | Hours between background sleep cycles. Set to `0` to disable. |

The `POSTCLAW_DB_URL` environment variable is also supported as a fallback for `dbUrl`.

---

## Plugin Hooks

PostClaw registers three hooks with the OpenClaw lifecycle:

### 1. `message_received` (void)

**When:** Every inbound message before agent processing begins.

**What it does:** Caches the raw message text so the next `before_prompt_build` has the real user text (not the system-modified version).

### 2. `before_prompt_build` (modifying)

**When:** Before the LLM prompt is assembled for each agent turn.

**What it does:**

1. **Prunes the system prompt** โ€” strips OpenClaw's default bloat (Tooling rules, Documentation, Project Context markdown)
2. **Injects memory architecture rules** โ€” teaches the agent how to use its memory tools
3. **Fetches persona context** โ€” pulls `agent_persona` rules from Postgres (core rules always, situational rules ranked by embedding similarity)
4. **Runs RAG search** โ€” performs a vector similarity search on `memory_semantic` + traverses `entity_edges` for linked memories
5. **Loads dynamic tools** โ€” fetches tool schemas from `context_environment` ranked by embedding similarity
6. **Injects everything** โ€” returns the modified system prompt and prepended RAG context

**Returns:** `{ systemPrompt, prependContext, tools }`

### 3. `agent_end` (void)

**When:** After the agent completes a turn (response generated).

**What it does:**

1. **Logs user prompt** as an episodic memory event (with embedding)
2. **Logs each tool call** the agent made as a separate episodic event
3. Skips heartbeat/cron runs to avoid noise

---

## Agent Tools

PostClaw registers 5 native tools that the agent can invoke autonomously:

### `memory_search`

Search the semantic memory database by natural language query.

```
memory_search({ query: "user's preferred programming language" })
โ†’ { results: "[ID: abc...] (92.3%) - The user prefers TypeScript..." }
```

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `query` | `string` | โœ… | Natural language search query |
| `max_results` | `number` | โ€” | Max results to return (default: 5) |

### `memory_store`

Store a new semantic memory fact with embedding.

```
memory_store({
  content: "The user's server runs Ubuntu 22.04 on a Hetzner VPS",
  scope: "private",
  category: "infrastructure",
  tier: "permanent",
  confidence: 0.95
})
โ†’ { id: "550e8400-...", status: "stored" }
```

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `content` | `string` | โœ… | The fact to store |
| `scope` | `"private" \| "shared" \| "global"` | โ€” | Visibility (default: `private`) |
| `category` | `string` | โ€” | Semantic category label |
| `volatility` | `"low" \| "medium" \| "high"` | โ€” | How likely to change |
| `tier` | `"volatile" \| "session" \| "daily" \| "stable" \| "permanent"` | โ€” | Retention tier |
| `confidence` | `number` | โ€” | 0.0โ€“1.0 confidence score |
| `metadata` | `object` | โ€” | Arbitrary JSON metadata |

### `memory_update`

Supersede an existing memory with a corrected fact. Archives the old memory and links the new one.

```
memory_update({
  old_memory_id: "550e8400-...",
  new_fact: "The user's server now runs Ubuntu 24.04",
  tier: "permanent"
})
โ†’ { newId: "7c9e6679-...", status: "updated" }
```



... (truncated)
tools

Comments

Sign in to leave a comment

Loading comments...