Tools
Memory Inject
OpenClaw plugin that auto-injects recent memory files into new sessions via session_start + before_prompt_build hooks. Multi-agent, fail-open, MIT.
Install
npm install &&
Configuration Example
{
"plugins": {
"memory-inject": {
"enabled": true,
"memoryDir": "memory",
"daysToLoad": 3,
"maxFiles": 6,
"maxTokens": 8000,
"filenamePattern": "^\\d{4}-\\d{2}-\\d{2}(-.+)?\\.md$",
"excludeAgents": ["sensitive-agent"],
"contextLabel": "Memory context (auto-injected)"
}
}
}
README
# openclaw-memory-inject
Auto-inject recent memory files into new sessions so OpenClaw agents maintain
continuity across Discord threads and `/new` resets.
## What it does
OpenClaw's built-in `startupContext` feature only fires when a user explicitly
types `/new` or `/reset` with an empty message. It does **not** fire when a new
session is created through a Discord thread — which is how many agents receive
most of their conversations. This means agents lose all memory continuity on
every new thread.
**memory-inject** closes that gap. It watches for new sessions via the
`session_start` hook, then injects your most recent `memory/*.md` files into
the system prompt on the first turn via the `before_prompt_build` hook. The
result: every agent — regardless of how its session was created — starts with a
fresh snapshot of recent memory.
The plugin is designed to be lightweight and defensive. It reads a small,
bounded set of files from disk once per session and caches the decision
in-process so it never re-reads or re-injects on subsequent turns. If the
memory directory is missing or full of unreadable files, the plugin silently
backs off — it never blocks an agent turn.
## How it works
memory-inject registers two hooks with the OpenClaw runtime:
1. **`session_start`** — When a session begins, the plugin records the session
key in an in-memory `SessionCache`. This is the trigger: every new session
gets marked as eligible for injection.
2. **`before_prompt_build`** — On the first turn of a marked session, the
plugin scans the agent's `memory/` directory, selects recent files matching
the configured pattern, reads them, and returns a `prependContext` block.
After injection, the cache is updated so no further injections happen for
that session.
The two-hook strategy is necessary because `session_start` tells us a session
is new, but only `before_prompt_build` can actually modify the prompt. By
bridging them with an in-process cache, we get exactly-once injection per
session.
## Features
- **Multi-agent** — Automatically detects each agent's workspace directory and
loads that agent's memory files independently
- **Fail-open** — Never blocks an agent turn; all disk errors are swallowed
and logged
- **Configurable** — 8 settings control what gets injected, how much, and for
which agents
- **Filename regex matching** — Default pattern matches `YYYY-MM-DD.md` and
`YYYY-MM-DD-slug.md`; override with any valid regex
- **Token-budget truncation** — Soft cap on total injected content, estimated
as `chars / 4`; oldest files are dropped first
- **mtime-based sorting** — Files are sorted newest-first by modification time
- **Zero runtime dependencies** — Only `node:*` built-in modules; `devDependencies`
are TypeScript and the test runner
- **MIT licensed**
## Installation
Requires OpenClaw 2026.6+ (the version where `session_start` and
`before_prompt_build` hooks became available).
### From GitHub (stable)
```bash
openclaw plugins install dannyge/openclaw-memory-inject
```
### From a local clone (development)
```bash
git clone https://github.com/dannyge/openclaw-memory-inject.git
cd openclaw-memory-inject
npm install && npm run build
openclaw plugins install --link /path/to/openclaw-memory-inject
```
Using `--link` tells OpenClaw to load the plugin directly from your local clone
so you can iterate without reinstalling. Edits to `src/` plus `npm run build`
are picked up on the next gateway restart.
### Verify the install
After installation, confirm the plugin is registered:
```bash
openclaw plugins list | grep -i memory-inject
```
Expected output:
```
| Memory Inject | memory-inject | openclaw | enabled | ~/Projects/openclaw-memory-inject/dist/index.js | 0.1.0 |
```
The plugin loads its hooks at gateway startup, so **a restart is required**
for a fresh install. Continue with
[Verifying after install](#verifying-after-install) for the end-to-end
verification workflow.
## Configuration
All settings go under the plugin's config key in your OpenClaw gateway config.
The plugin is fully functional with zero configuration — every field has a
sensible default.
| Key | Type | Default | Description |
|-----|------|---------|-------------|
| `enabled` | `boolean` | `true` | Master switch. Set to `false` to disable injection without unloading the plugin. |
| `memoryDir` | `string` | `"memory"` | Directory relative to the agent's workspace directory. |
| `daysToLoad` | `number` | `2` | How many recent days of memory files to consider (1–365). Default 2 = today + yesterday. |
| `maxFiles` | `number` | `4` | Maximum files to inject per session (1–100). Newest files by mtime are kept. |
| `maxTokens` | `number` | `4000` | Soft token cap on total injected content (100–128000). Oldest files are dropped first when exceeded. |
| `filenamePattern` | `string` | `"^\\d{4}-\\d{2}-\\d{2}(-.+)?\\.md$"` | ECMAScript regex matched against file basenames. |
| `excludeAgents` | `string[]` | `[]` | Agent IDs that should never receive injection (e.g. sensitive workloads). |
| `contextLabel` | `string` | `"Recent memory (auto-injected by memory-inject plugin)"` | Header line for the injected context block. Set to `""` to omit. |
Example JSON configuration:
```json
{
"plugins": {
"memory-inject": {
"enabled": true,
"memoryDir": "memory",
"daysToLoad": 3,
"maxFiles": 6,
"maxTokens": 8000,
"filenamePattern": "^\\d{4}-\\d{2}-\\d{2}(-.+)?\\.md$",
"excludeAgents": ["sensitive-agent"],
"contextLabel": "Memory context (auto-injected)"
}
}
}
```
The authoritative source for config field names and defaults is
`openclaw.plugin.json` → `configSchema`.
## Usage examples
### Minimal — use all defaults
No config needed. The plugin loads with defaults: scans `memory/` in each
agent's workspace, matches `YYYY-MM-DD.md` and `YYYY-MM-DD-slug.md`, loads up
to 4 files from the last 2 days, capped at ~4000 tokens.
### Advanced — wider window, more files
```json
{
"plugins": {
"memory-inject": {
"daysToLoad": 7,
"maxFiles": 10,
"maxTokens": 16000
}
}
}
```
Load up to 10 memory files from the past week, with a 16000-token budget.
### Exclude specific agents
```json
{
"plugins": {
"memory-inject": {
"excludeAgents": ["kbadmin", "sensitive"]
}
}
}
```
Agents `kbadmin` and `sensitive` won't receive any memory injection, while all
other agents use the default configuration.
### Custom filename pattern
```json
{
"plugins": {
"memory-inject": {
"filenamePattern": "^session-\\d{8}(-.+)?\\.md$"
}
}
}
```
Match files like `session-20260623.md` or `session-20260623-debugging.md`
instead of the default date-based pattern.
## How memory files are matched
By default, the plugin looks for files matching the regular expression
`^\d{4}-\d{2}-\d{2}(-.+)?\.md$`. This catches:
- `2026-06-23.md`
- `2026-06-23-debug-session.md`
- `2026-06-22.md`
It scans `<workspaceDir>/memory/` (the directory is configurable via
`memoryDir`). Files are sorted by modification time, newest first. The
`daysToLoad` window is based on the local system clock — files older than
`now - (daysToLoad * 24h)` are excluded before the `maxFiles` and `maxTokens`
limits apply.
Logical dates are parsed from the `YYYY-MM-DD` prefix in each filename and
included in the injected context block as annotations.
## Multi-agent behavior
The plugin auto-detects `ctx.workspaceDir` from the OpenClaw runtime context,
which means it reads the correct `memory/` directory for whichever agent is
handling the current turn. No per-agent configuration is needed.
Configuration is global — all agents share the same settings unless you use
`excludeAgents` to opt specific agents out entirely. This is intentional:
memory-inject is designed to be a set-and-forget plugin that works uniformly
across your agent fleet.
## Performance and token cost
- **Disk reads**: At most `maxFiles` file reads per session (default: 4), each
capped at the remaining token budget × 4 characters (hard ceiling 512 KB per
file). All reads happen once, on the first turn of a new session.
- **Token estimation**: Content size is estimated as `totalChars / 4`. This is
a conservative approximation that works well for English-heavy prose and
reasonably for CJK-mixed content.
- **Injection frequency**: Exactly once per session. The `SessionCache`
prevents re-injection on subsequent turns within the same session.
- **Memory overhead**: A small in-process map of session keys (one entry per
active session). Entries are garbage-collected when sessions end.
## Verifying after install
The most reliable way to confirm the plugin works end-to-end is to look at
the gateway log for the `[memory-inject]` injection message. The plugin
prints exactly one line per successful injection.
### 1. Make sure your workspace has matching memory files
The plugin scans `<workspaceDir>/<memoryDir>/` for files matching
`filenamePattern` (default `^\d{4}-\d{2}-\d{2}(-.+)?\.md$`). For a quick
test on agent `ops`, create one or two files:
```bash
cd ~/.openclaw/agents/ops/workspace/memory
NOW=$(date +%Y-%m-%d)
YDAY=$(date -v-1d +%Y-%m-%d)
echo "# Test memory" > ${NOW}.md
echo "# Yesterday note" > ${YDAY}.md
```
The `memory/` directory is **per-agent** (each of your agents has its own
under `~/.openclaw/agents/<agentId>/workspace/memory/`). Pick whichever
agent you can easily trigger a new session on — usually the one you talk
to most.
### 2. Trigger a fresh session
A "fresh session" is anything that has not seen this session before. Easy
triggers:
- Send a message to a Discord thread where the agent has never replied
(a brand-new thread works for every agent)
- Issue `/new` or `/reset` in the agent's main session
- Restart the gateway (cache resets, every active session is treated as new)
Cron jobs are also valid triggers — they create isolated sessions.
### 3. Check the gateway log
Tail the ga
... (truncated)
tools
Comments
Sign in to leave a comment