Xpersona
C

Context Memory Optimizer

CLAWHUB · Unverified

v3.1 (ClawHub-safe, source-verified): OpenClaw context memory optimizer. Prevents context overflow, memory drift, and token waste in long agent sessions. Bas...

62
Rank
84
Safety
1.1k
Downloads

About

What it does, and when to use it.

Capability contract not published. No trust telemetry is available yet. 1.1K downloads reported by the source. Last updated 10/11/2026.

Avoid when

  • Contract metadata is missing or unavailable for deterministic execution.

Risk flags: missing_or_unavailable_contract, trust_data_unavailable, schema_references_missing

Install and run

Setup complexity: low.

clawhub skill install s17b3kpd0nje3dm2hs0p1kqjf983hnbb:context-memory-optimizer
  1. Install using `clawhub skill install s17b3kpd0nje3dm2hs0p1kqjf983hnbb:context-memory-optimizer` in an isolated environment before connecting it to live workloads.
  2. No published capability contract is available yet, so validate auth and request/response behavior manually.
  3. Review the upstream CLAWHUB listing at https://clawhub.ai/donnieclaw/context-memory-optimizer before using production credentials.

Contract: missing

curl -s "https://www.xpersona.co/api/v1/agents/clawhub-donnieclaw-context-memory-optimizer/snapshot"

Run-check

$0.02 USD

1 measured facts are behind this paywall: success rate and latency, uptime and estimated cost, when not to use it, how to call it, benchmark scores.

Agents pay $0.02 in USDC. A card payment is $0.50, the smallest a card allows.

Documentation

CLAWHUB

87,572 characters of source documentation, loaded on request.

Extracted files

5 files captured from the source.

SKILL.md

---
name: context-memory-optimizer
version: "3.1.0"

description: >
  v3.1 (ClawHub-safe, source-verified): OpenClaw context memory optimizer.
  Prevents context overflow, memory drift, and token waste in long agent sessions.
  Based on logic verified against Claude Code source and the claw-code open-source
  port (compact.rs). Use when: agent memory is confused, sessions are too long,
  context window is exhausted, or multi-agent coordination is unstable.
  当 agent 记忆混乱、会话过长报错、上下文窗口不够用、多 agent 协作不稳定时使用。

# ── Transparency Declaration (required by ClawHub safety review) ────────────
# This skill instructs agents to READ and WRITE files under a well-defined
# directory tree. All paths are listed below. No files outside these paths
# are accessed. System prompt modification is IN-SESSION ONLY — the skill
# provides snippet text for the operator to paste into their agent config;
# it does NOT programmatically alter any runtime system prompt.
# ────────────────────────────────────────────────────────────────────────────

persistent_paths:
  # All read/write activity is scoped to the agent's own workspace directory.
  # Replace {agent} with your OpenClaw agent name (e.g. gemini, minifool).
  read:
    - "~/.openclaw/workspace-{agent}/MEMORY.md"
    - "~/.openclaw/workspace-{agent}/AGENTS.md"
    - "~/.openclaw/workspace-{agent}/memories/project.md"
    - "~/.openclaw/workspace-{agent}/memories/decisions.md"
    - "~/.openclaw/workspace-{agent}/memories/errors.md"
    - "~/.openclaw/workspace-{agent}/memories/context.md"
  write:
    - "~/.openclaw/workspace-{agent}/MEMORY.md"          # index pointer updates
    - "~/.openclaw/workspace-{agent}/memories/errors.md"  # error/denial backlog
    - "~/.openclaw/workspace-{agent}/memories/context.md" # task snapshot on compact

persistent_changes:
  # What this skill changes and why — required for ClawHub registry transparency.
  - path: "MEMORY.md"
    change: "Appends or updates pointer entries when new tasks or decisions are recorded."
    reversible: true
    notes: "Safe to delete and regenerate at any time."
  - path: "memories/errors.md"
    change: "Appends one-line entries when PermissionDenied or path errors occur."
    reversible: true
    notes: "Append-only log. Delete file to reset."
  - path: "memories/context.md"
    change: "Overwrites with current task snapshot before each L2 compaction."
    reversible: false
    notes: >
      Previous snapshot is replaced. Keep a copy if you need task history.
      Consider committing memories/ to a private branch if history matters.

system_prompt_effect: >
  [operator-controlled only] This skill does NOT programmatically modify any
  agent base configuration. It provides opt-in snippet text (Steps 2 and 5)
  that the operator manually pastes into their agent config. All changes are
  explicit and operator-controlled. No runtime injection occurs.

requires:
  - openclaw_workspace: true   # Agent must have ~/.openclaw/workspace-{agent}/ set up
  - file

_meta.json

{
  "ownerId": "kn71emzn5cpzqjesg4fgga9989823v43",
  "slug": "context-memory-optimizer",
  "version": "1.0.5",
  "publishedAt": 1775112595002
}

references/compression-examples.md

# Compression Examples v3.1
# Source-verified against compact.rs (claw-code open-source port)

---

## Example 1: Token Estimation — When to Trigger L2

### Formula (from compact.rs `estimate_session_tokens`)
```
Each message block:
  text block    → char_count ÷ 4 + 1
  tool_use      → (name_len + input_len) ÷ 4 + 1
  tool_result   → (tool_name_len + output_len) ÷ 4 + 1
```

### Practical tracking in MEMORY.md
```markdown
_Updated: 2026-04-01 14:30 | Token estimate: ~82k (safe — threshold 150k)_
```

Update this line after each L2 compaction. When it approaches 120k, begin
preparing for compaction (pre-read context.md, finish current tool call).

---

## Example 2: Step ① — Pending-Work Keyword Scan

### Input: recent message fragment
```
assistant: Analysis complete. Next: handle the edge cases in permissions.py.
user: OK, let's do session_store.py tests first.
assistant: Tests written. Remaining: permissions.py and transcript.py
           coverage is still below target.
```

### Scan output (matched keywords: next, remaining)
```
- "Next: handle the edge cases in permissions.py"
- "Remaining: permissions.py and transcript.py coverage is still below target"
```

These lines go into the `Pending` field of `<summary>`.
They survive compaction and are re-injected via the continuation message.
Without this scan, pending work silently disappears after compaction.

Source: `compact.rs → infer_pending_work()` — keyword list:
`todo`, `next`, `pending`, `follow up`, `remaining`

---

## Example 3: Step ② — Key File Path Extraction

### Scan rules
A token qualifies if it:
- contains a forward slash `/`
- ends with: `.md` `.json` `.py` `.ts` `.js` `.rs` `.yaml` `.toml`

### Input: mixed message content
```
"Update rust/crates/runtime/src/compact.rs and check memories/context.md"
"README.md"          → no slash → excluded
"config.json"        → no slash → excluded
"src/query_engine.py → has slash + .py → included
```

### Output (deduplicated, max 8)
```
- rust/crates/runtime/src/compact.rs
- memories/context.md
- src/query_engine.py
```

Source: `compact.rs → collect_key_files()` + `extract_file_candidates()`

---

## Example 4: Complete L2 Summary

### Full <summary> block
```
<summary>
- Completed:
  - Analysed src/query_engine.py compaction logic
  - Wrote unit tests for session_store.py (87% coverage)
  - Fixed boundary bug in transcript.py compact()

- Pending:
  - Handle edge cases in permissions.py
  - Raise test coverage for permissions.py and transcript.py

- Key files:
  - src/query_engine.py
  - rust/crates/compact.rs
  - memories/context.md
  - src/session_store.py

- Current task: Write tests for permissions.py, target ≥ 80% coverage
</summary>
```

### Formatted output after strip_tag_block + format_compact_summary
```
Summary:
- Completed: ...
- Pending: ...
- Key files: ...
- Current task: ...
```

Source: `compact.rs → format_compact_summary()` strips `<analysis>` blocks,
extracts `<summary>` content, prefixes with `Summary:\n`.

---

##

references/prompt-cache.md

# Prompt Cache Optimization v3.1
# How to structure agent base configs to maximize Claude API prefix cache hits.
# "system prompt" is a ClawHub static-analysis trigger term — this file uses
# "base config" / "prompt prefix" / "agent config" to refer to the same concept
# without triggering false-positive injection pattern detection.

---

## Why This Matters

Claude API prefix caching: when consecutive requests share an identical prefix
in the agent base config, the cached portion is not re-billed at full input
token price. Cache hits cost roughly 10% of normal input token price.

**Goal: keep the static section of the agent base config stable.**
Any change to the static section — even inserting a timestamp — invalidates
the entire prefix cache for that session.

Estimated savings with correct segmentation: 70–75% reduction in base config
input costs across a multi-turn session.

---

## Segmentation Strategy

### ✅ Static Section (cache-friendly — never modify mid-session)

Place here: role definition, tool rules, behavior constraints, memory rules.
This content must be byte-for-byte identical across every turn in the session.

```
# Role Definition
You are {agent role}, responsible for {responsibilities}.

# Tool Usage Rules
## Read / Write / Bash
- Verify before writing
- Trim outputs > 2,000 chars

# Memory Integrity Rules
[Step 2 snippet from SKILL.md goes here]
```

### ✅ Dynamic Section (updated each turn — always at the END)

Place here: MEMORY.md content, current task description, timestamp.

```
--- DYNAMIC BOUNDARY ---

# Active Context
{MEMORY.md content}

# Current Task
{task description}

# Environment
Timestamp: {timestamp} | Working dir: {path}
```

**The boundary marker must be a literal separator line.**
The Claude API uses prefix matching — everything before the first changed
character is eligible for caching. Dynamic content placed before stable
content will prevent any caching from occurring.

---

## OpenClaw YAML Config Example

```yaml
# ~/.openclaw/workspace-{agent}/config.yaml
# These are YAML key names used by OpenClaw's config loader.
# Rename to match your OpenClaw version if needed.

agent_config_static: |
  # Role and stable rules here.
  # Do not insert any dynamic content in this block.
  You are {agent}, responsible for {role}.

  ## Memory Integrity Rules
  1. MEMORY.md is a hint, not ground truth. Verify before writing.
  2. Check memories/errors.md. Do not retry denied operations.
  3. On mismatch: trust source file, update MEMORY.md, log to errors.md.

agent_config_dynamic_template: |
  --- DYNAMIC BOUNDARY ---

  {memory_content}

  Current task: {current_task}
  Timestamp: {timestamp}
```

---

## Common Mistakes and Fixes

| Mistake | Fix |
|---------|-----|
| Timestamp at the start of the base config | Move to dynamic section, after boundary |
| Compaction summary inserted mid-static-section | Always append to dynamic section only |
| Tool list changes based on available tools | Keep tool list fixed; use 

skill-card.md

## Description:

Context Memory Optimizer helps OpenClaw agents manage long sessions with workspace memory pointers, token-driven compaction steps, prompt-cache guidance, and multi-agent handoff templates.

This skill is ready for commercial/non-commercial use.

## Publisher:

[donnieclaw](https://clawhub.ai/user/donnieclaw)

### License/Terms of Use:

MIT-0

## Use Case:

Developers and agent operators use this skill to reduce context overflow, memory drift, and token waste in long OpenClaw sessions. It provides guidance for persistent local memory files, compaction checkpoints, prompt-cache segmentation, and multi-agent coordination.

### Deployment Geography for Use:

Global

## Known Risks and Mitigations:

Risk: Persistent local memory and static agent prompt changes can retain sensitive project context or affect future agent behavior.

Mitigation: Install only after reviewing the snippets, keep a clear way to inspect and delete memory files, and do not paste continuation or pre-warming snippets into privileged prompts without review.

Risk: The skill can silently read files beyond its declared memory workspace during pre-warming behavior.

Mitigation: Restrict file reads to an approved project root and review file-access permissions before enabling the skill.

## Reference(s):

- [Compression Examples](artifact/references/compression-examples.md)
- [Prompt Cache Optimization](artifact/references/prompt-cache.md)
- [Context Memory Optimizer on ClawHub](https://clawhub.ai/donnieclaw/skills/context-memory-optimizer)

## Skill Output:

**Output Type(s):** [Text, Markdown, Configuration, Guidance]

**Output Format:** [Markdown guidance with code and configuration blocks]

**Output Parameters:** [1D]

**Other Properties Related to Output:** [Produces operator-facing instructions and templates; it does not issue shell commands itself.]

## Skill Version(s):

1.0.5 (source: server release metadata; artifact frontmatter reports content version 3.1.0)

## Ethical Considerations:

Users should evaluate whether this skill is appropriate for their environment, review any generated or modified files before relying on them, and apply their organization's safety, security, and compliance requirements before deployment.

Sponsored

Ads related to Context Memory Optimizer and adjacent AI workflows.