{"id":"09e2401e-ab2e-4780-a2e6-6681e8ffdded","entityType":"agent","slug":"clawhub-jlacroix82-memory-router","name":"Memory Router","canonicalUrl":"https://www.xpersona.co/agent/clawhub-jlacroix82-memory-router","canonicalPath":"/agent/clawhub-jlacroix82-memory-router","generatedAt":"2026-10-09T20:52:32.087Z","source":"CLAWHUB","claimStatus":"UNCLAIMED","verificationTier":"NONE","summary":{"evidence":{"source":"editorial-content","verified":true,"confidence":"high","updatedAt":"2026-10-09T16:44:14.157Z","emptyReason":null},"description":"OpenClaw skill that auto-tiers bloated MEMORY.md, generates smart per-session manifests, and routes only what matters — 70-85% context reduction with zero de... Skill: Memory Router Owner: jlacroix82 Summary: OpenClaw skill that auto-tiers bloated MEMORY.md, generates smart per-session manifests, and routes only what matters — 70-85% context reduction with zero de... Tags: latest:2.4.3 Version history: v2.4.3 | 2026-07-21T18:51:29.200Z | auto **2.4.3 Changelog** - Added prominent safety and warning sections to SKILL.md: clarifies destructive operations, confirmation flags, a","descriptionLabel":"Technical summary","evidenceSummary":"Capability contract not published. No trust telemetry is available yet. 2.3K downloads reported by the source. Last updated 10/9/2026.","installCommand":"clawhub skill install s175p518b8g47fx6r9zyvs95ks876t4t:memory-router","sourceUrl":"https://clawhub.ai/jlacroix82/memory-router","homepage":"https://clawhub.ai/jlacroix82/skills/memory-router","primaryLinks":[{"label":"View on ClawHub","url":"https://clawhub.ai/jlacroix82/memory-router","kind":"source"},{"label":"Homepage","url":"https://clawhub.ai/jlacroix82/skills/memory-router","kind":"homepage"}],"safetyScore":84,"overallRank":62,"popularityScore":67,"trustScore":null,"claimedByName":null,"isOwner":false,"seoDescription":"OpenClaw skill that auto-tiers bloated MEMORY.md, generates smart per-session manifests, and routes only what matters — 70-85% context reduction with zero de..."},"coverage":{"evidence":{"source":"public-profile","verified":false,"confidence":"medium","updatedAt":"2026-10-09T16:44:14.157Z","emptyReason":null},"protocols":[{"protocol":"OPENCLEW","label":"OpenClaw","status":"self-declared","notes":"Declared in the public agent profile."}],"capabilities":[],"verifiedCount":0,"selfDeclaredCount":1,"capabilityMatrix":{"rows":[{"key":"OPENCLEW","type":"protocol","support":"unknown","confidenceSource":"profile","notes":"Listed on profile"}],"flattenedTokens":"protocol:OPENCLEW|unknown|profile"}},"adoption":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"medium","updatedAt":"2026-10-09T16:44:14.157Z","emptyReason":null},"stars":null,"forks":null,"downloads":2281,"packageName":null,"latestVersion":"2.4.3","tractionLabel":"2.3K downloads"},"release":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"medium","updatedAt":"2026-10-09T16:44:14.157Z","emptyReason":null},"lastUpdatedAt":"2026-10-09T16:44:14.157Z","lastCrawledAt":"2026-10-09T16:44:14.157Z","lastIndexedAt":null,"nextCrawlAt":"2026-10-10T16:44:14.157Z","lastVerifiedAt":null,"highlights":[{"version":"2.4.3","createdAt":"2026-07-21T18:51:29.200Z","changelog":"**2.4.3 Changelog** - Added prominent safety and warning sections to SKILL.md: clarifies destructive operations, confirmation flags, and filesystem requirements. - Improved SKILL.md documentation for commands that modify or delete files, including `--tier`, `--restore`, and `--cleanup`. - Removed the outdated skill-card.md file.","fileCount":8,"zipByteSize":29296},{"version":"2.4.2","createdAt":"2026-07-20T01:57:34.195Z","changelog":"Clean security scan (0 findings). Added clawhub.yaml for publish tracking.","fileCount":8,"zipByteSize":28915},{"version":"2.4.1","createdAt":"2026-06-14T02:22:09.796Z","changelog":"Security hardening: path validation, atomic writes, safer backup restore delimiter. Updated safety table for unattended command classification.","fileCount":7,"zipByteSize":28774},{"version":"2.4.0","createdAt":"2026-06-13T03:36:44.082Z","changelog":"Fix: --confirm safety check before backup creation; updated README with accurate Safe vs Unsafe command table and retention policy clarification","fileCount":7,"zipByteSize":28536},{"version":"2.3.0","createdAt":"2026-06-12T21:28:54.701Z","changelog":"**memory-router 2.3.0** - Improved output and feedback messages in tiering dry runs (clarifies when no files are modified). - Updated usage documentation in SKILL.md, INSTALL.md, and README.md to reflect clearer command options and outputs. - Removed legacy documentation file `skill-card.md`. - Minor refinements to command-line feedback, especially for dry-run and confirmation flows.","fileCount":7,"zipByteSize":27984},{"version":"2.2.2","createdAt":"2026-06-12T19:54:03.915Z","changelog":"Security audit fixes: restore mode now extracts only original content (fixes corruption bug), --confirm flag required for --tier, safety documentation updated to warn against auto-running --tier/--restore during heartbeats","fileCount":7,"zipByteSize":26454},{"version":"2.2.1","createdAt":"2026-06-12T15:24:47.708Z","changelog":"Bug fix: corrected 'tiling' typo in threshold message","fileCount":7,"zipByteSize":25471},{"version":"1.0.4","createdAt":"2026-06-05T15:36:26.730Z","changelog":"Security audit fixes: (1) Strip backup metadata header during restore to prevent document corruption, (2) Added persistent-state warnings throughout docs, (3) Added --dry-run support for restore, (4) Strengthened overwrite warnings","fileCount":7,"zipByteSize":26934}]},"execution":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No published capability contract is available yet."},"installCommand":"clawhub skill install s175p518b8g47fx6r9zyvs95ks876t4t:memory-router","setupComplexity":"low","setupSteps":["Setup complexity is classified as HIGH. You must provision dedicated cloud infrastructure or an isolated VM. Do not run this directly on your local workstation.","Final validation: Expose the agent to a mock request payload inside a sandbox and trace the network egress before allowing access to real customer data."],"contract":{"contractStatus":"missing","authModes":[],"requires":[],"forbidden":[],"supportsMcp":false,"supportsA2a":false,"supportsStreaming":false,"inputSchemaRef":null,"outputSchemaRef":null,"dataRegion":null,"contractUpdatedAt":null,"sourceUpdatedAt":null,"freshnessSeconds":null},"invocationGuide":{"preferredApi":{"snapshotUrl":"https://www.xpersona.co/api/v1/agents/clawhub-jlacroix82-memory-router/snapshot","contractUrl":"https://www.xpersona.co/api/v1/agents/clawhub-jlacroix82-memory-router/contract","trustUrl":"https://www.xpersona.co/api/v1/agents/clawhub-jlacroix82-memory-router/trust"},"curlExamples":["curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-jlacroix82-memory-router/snapshot\"","curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-jlacroix82-memory-router/contract\"","curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-jlacroix82-memory-router/trust\""],"jsonRequestTemplate":{"query":"summarize this repo","constraints":{"maxLatencyMs":2000,"protocolPreference":["OPENCLEW"]}},"jsonResponseTemplate":{"ok":true,"result":{"summary":"...","confidence":0.9},"meta":{"source":"CLAWHUB","generatedAt":"2026-10-09T20:52:32.083Z"}},"retryPolicy":{"maxAttempts":3,"backoffMs":[500,1500,3500],"retryableConditions":["HTTP_429","HTTP_503","NETWORK_TIMEOUT"]}},"endpoints":{"dossierUrl":"https://www.xpersona.co/api/v1/agents/clawhub-jlacroix82-memory-router/dossier","snapshotUrl":"https://www.xpersona.co/api/v1/agents/clawhub-jlacroix82-memory-router/snapshot","contractUrl":"https://www.xpersona.co/api/v1/agents/clawhub-jlacroix82-memory-router/contract","trustUrl":"https://www.xpersona.co/api/v1/agents/clawhub-jlacroix82-memory-router/trust"}},"reliability":{"evidence":{"source":"runtime-metrics","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No trust, reliability, or runtime telemetry is available."},"trust":{"status":"unavailable","handshakeStatus":"UNKNOWN","verificationFreshnessHours":null,"reputationScore":null,"p95LatencyMs":null,"successRate30d":null,"fallbackRate":null,"attempts30d":null,"trustUpdatedAt":null,"trustConfidence":"unknown","sourceUpdatedAt":null,"freshnessSeconds":null},"decisionGuardrails":{"doNotUseIf":["Contract metadata is missing or unavailable for deterministic execution."],"safeUseWhen":[],"riskFlags":["missing_or_unavailable_contract","trust_data_unavailable","schema_references_missing"],"operationalConfidence":"low"},"executionMetrics":{"observedLatencyMsP50":null,"observedLatencyMsP95":null,"estimatedCostUsd":null,"uptime30d":null,"rateLimitRpm":null,"rateLimitBurst":null,"lastVerifiedAt":null,"verificationSource":null},"runtimeMetrics":{"successRate":null,"avgLatencyMs":null,"avgCostUsd":null,"hallucinationRate":null,"retryRate":null,"disputeRate":null,"p50Latency":null,"p95Latency":null,"lastUpdated":null}},"benchmarks":{"evidence":{"source":"no-benchmark-data","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No benchmark suites or observed failure patterns are available."},"suites":[],"failurePatterns":[]},"artifacts":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"high","updatedAt":"2026-10-09T16:44:14.157Z","emptyReason":null},"readme":"Skill: Memory Router\n\nOwner: jlacroix82\n\nSummary: OpenClaw skill that auto-tiers bloated MEMORY.md, generates smart per-session manifests, and routes only what matters — 70-85% context reduction with zero de...\n\nTags: latest:2.4.3\n\nVersion history:\n\nv2.4.3 | 2026-07-21T18:51:29.200Z | auto\n\n**2.4.3 Changelog**\n\n- Added prominent safety and warning sections to SKILL.md: clarifies destructive operations, confirmation flags, and filesystem requirements.\n- Improved SKILL.md documentation for commands that modify or delete files, including `--tier`, `--restore`, and `--cleanup`.\n- Removed the outdated skill-card.md file.\n\nv2.4.2 | 2026-07-20T01:57:34.195Z | user\n\nClean security scan (0 findings). Added clawhub.yaml for publish tracking.\n\nv2.4.1 | 2026-06-14T02:22:09.796Z | user\n\nSecurity hardening: path validation, atomic writes, safer backup restore delimiter. Updated safety table for unattended command classification.\n\nv2.4.0 | 2026-06-13T03:36:44.082Z | user\n\nFix: --confirm safety check before backup creation; updated README with accurate Safe vs Unsafe command table and retention policy clarification\n\nv2.3.0 | 2026-06-12T21:28:54.701Z | auto\n\n**memory-router 2.3.0**\n\n- Improved output and feedback messages in tiering dry runs (clarifies when no files are modified).\n- Updated usage documentation in SKILL.md, INSTALL.md, and README.md to reflect clearer command options and outputs.\n- Removed legacy documentation file `skill-card.md`.\n- Minor refinements to command-line feedback, especially for dry-run and confirmation flows.\n\nv2.2.2 | 2026-06-12T19:54:03.915Z | user\n\nSecurity audit fixes: restore mode now extracts only original content (fixes corruption bug), --confirm flag required for --tier, safety documentation updated to warn against auto-running --tier/--restore during heartbeats\n\nv2.2.1 | 2026-06-12T15:24:47.708Z | user\n\nBug fix: corrected 'tiling' typo in threshold message\n\nv1.0.4 | 2026-06-05T15:36:26.730Z | user\n\nSecurity audit fixes: (1) Strip backup metadata header during restore to prevent document corruption, (2) Added persistent-state warnings throughout docs, (3) Added --dry-run support for restore, (4) Strengthened overwrite warnings\n\nv2.2.0 | 2026-06-04T03:32:51.255Z | user\n\nFix WAL injection vulnerability (append path used unsanitized variables), require --force flag for destructive restore operation\n\nv2.1.0 | 2026-05-23T15:08:32.060Z | user\n\nSafety overhaul: pre-tier backups before any tier operation, --dry-run preview mode, --restore from backup, minCoreLines/minCoreChars safety thresholds to prevent data loss\n\nv1.0.3 | 2026-05-22T04:17:29.774Z | user\n\nUpdated SKILL.md with full punchy intro, architecture diagram, and comprehensive documentation.\n\nv1.0.2 | 2026-05-22T04:17:01.110Z | user\n\nUpdated SKILL.md with full punchy intro, architecture diagram, and comprehensive documentation.\n\nv1.0.1 | 2026-05-22T04:16:24.623Z | user\n\nUpdated SKILL.md with full documentation, architecture diagram, and compelling intro — matches README.md content.\n\nv1.0.0 | 2026-05-22T03:33:18.619Z | user\n\nInitial release — intelligent memory routing with auto-tiering, manifest generation, entity-aware search, token budgeting, and WAL protocol. Zero external dependencies.\n\nArchive index:\n\nArchive v2.4.3: 8 files, 29296 bytes\n\nFiles: _meta.json (132b), clawhub.yaml (330b), config.json (778b), INSTALL.md (5310b), memory-router.js (41394b), README.md (18132b), skill-card.md (2560b), SKILL.md (19930b)\n\nFile v2.4.3:SKILL.md\n\n# MemoryRouter ⚡\n\n**Never lose context. Never forget decisions. Never repeat mistakes.**\n\nThe memory problem is the single biggest reason agents feel dumb over time. Not the models. Not the prompts. **Memory management.**\n\nMemoryRouter fixes it with one tool, zero dependencies, zero setup.\n\n## The Problem — In 30 Seconds\n\nAgent memory files grow unbounded. After a week, you've got thousands of lines across dozens of files. Every session loads **everything** — even when the user asks \"what's the weather?\"\n\nThat's tokens burned on irrelevant memories, every interaction, forever.\n\nThen compaction kicks in and details vanish.\n\n**The bottleneck isn't the model. It's what the model gets to see.**\n\n## Why Memory Fails\n\n| Failure Mode | Cause | Fix |\n|-------------|-------|-----|\n| Forgets everything | Loads irrelevant files, context window fills up | Smart manifest — load only what matters |\n| Repeats mistakes | Lessons not captured or loaded | Entity index + audit for conflicts |\n| Repeats work | No session state persistence | WAL protocol — write state before responding |\n| Slow responses | Loads 50+ files when only 3 matter | Token budgeting — cap context window |\n| Duplicates everywhere | No automated cleanup | `--audit` finds high-similarity pairs |\n\n## The Architecture\n\n```\n┌──────────────────────────────────────────────────────┐\n│              MEMORYROUTER ⚡                          │\n├──────────────────────────────────────────────────────┤\n│                                                      │\n│  ┌──────────────┐    ┌──────────────┐               │\n│  │  AUTO-TIER   │    │  MANIFEST    │               │\n│  │  MEMORY.md   │ →  │  GENERATOR   │               │\n│  │              │    │              │               │\n│  │ Core (always │    │ Required:    │               │\n│  │ loaded)      │    │ MEMORY.md    │               │\n│  │ + Archive    │    │ Recent logs  │               │\n│  │ (on demand)  │    │ Boosted:     │               │\n│  └──────────────┘    │ entity files │               │\n│                      └──────┬───────┘               │\n│                             │                        │\n│              ┌──────────────▼──────────────┐         │\n│              │  ENTITY RESOLUTION          │         │\n│              │  \"alice\" → preferences.md,         │         │\n│              │  notes.md, decisions.md│         │\n│              └──────────────┬──────────────┘         │\n│                             │                        │\n│              ┌──────────────▼──────────────┐         │\n│              │  TOKEN BUDGET FILTER        │         │\n│              │  20K budget → 7 files       │         │\n│              │  100K budget → 16 files     │         │\n│              └──────────────┬──────────────┘         │\n│                             │                        │\n│              ┌──────────────▼──────────────┐         │\n│              │  AGENT LOADS ONLY WHAT      │         │\n│              │  MATTERS → 70-85% REDUCTION │         │\n│              └─────────────────────────────┘         │\n└──────────────────────────────────────────────────────┘\n```\n\n## ⚠️ Important Warnings\n\n### Automatic File Modification\nMemoryRouter automatically modifies MEMORY.md and archive files under `memory/` during `--tier`, `--audit`, and `--restore` operations. These changes are not reversible unless you have a backup. Always run `--dry-run` first to preview changes.\n\n### Destructive Flags Requiring Confirmation\n- `--tier` rewrites MEMORY.md permanently\n- `--restore` overwrites MEMORY.md with backup content\n- `--cleanup` with auto-remove can delete archived entries\n- These operations require explicit `--confirm` / `--force` flags and will refuse to run without them\n\n### Filesystem Access\nMemoryRouter reads and writes `memory/` files and directories. Ensure proper filesystem permissions and avoid running in untrusted shared directories.\n\n## Quick Start\n\n### Fix a bloated MEMORY.md (requires confirmation)\n\n```bash\nnode skills/memory-router/memory-router.js --tier --confirm\n```\n\n**Output:**\n```\n[memory-router] MEMORY.md: 7809 lines, 309254 chars\n[memory-router] ✅ Pre-tier backup: memory/backups/MEMORY-backup-2026-05-23-1234567890.md (7809 lines saved)\n[memory-router] Tiered: 202 core sections, 1002 archived\n[memory-router] MEMORY.md reduced from 7809 lines to 2222 lines\n```\n\n### Preview tiering without making changes\n\n```bash\nnode skills/memory-router/memory-router.js --tier --dry-run\n```\n\n**Output:**\n```\n[memory-router] MEMORY.md: 7809 lines, 309254 chars\n[memory-router] ── DRY RUN ──\n[memory-router] Would archive: memory/active/MEMORY-archive-2026-05-23.md\n[memory-router] Would reduce MEMORY.md from 7809 lines to ~2222 lines\n[memory-router] Core sections: 202, Archive sections: 1002\n[memory-router] ✅ No files were modified.\n```\n\n### Restore MEMORY.md from latest backup\n\n```bash\nnode skills/memory-router/memory-router.js --restore --force\n```\n\n⚠️ **Destructive** — overwrites MEMORY.md. Requires `--force` flag. Extracts only the original content from the backup (metadata headers are stripped). Always creates a backup of the current MEMORY.md before overwriting.\n\n### Generate a smart manifest in one command\n\n```bash\nnode skills/memory-router/memory-router.js --compact\n```\n\nCreates `memory/memory-manifest.json` — the agent's shopping list of what to load.\n\n### With entity boosting\n\n```bash\nnode skills/memory-router/memory-router.js --compact --query \"alice\"\n```\n\nFiles linked to \"alice\" get priority. No AI, no embeddings — just fast entity resolution.\n\n### With a token budget\n\n```bash\nnode skills/memory-router/memory-router.js --compact --budget 20000\n```\n\nOnly loads files that fit within 20K tokens. Tight budgets load core only. Generous budgets load archive on demand.\n\n### Other commands\n\n```bash\nnode skills/memory-router/memory-router.js --audit      # Find duplicates & conflicts\nnode skills/memory-router/memory-router.js --status      # Health overview\nnode skills/memory-router/memory-router.js --entity add alice person preferences.md\n```\n\n## How It Works\n\n### The Core Insight\n\n**Memory management is the bottleneck, not model capability.** Every agent system hits the same wall — context window fills up, everything loads, irrelevant memories dilute the signal.\n\nMemoryRouter takes a **routing** approach rather than a **compression** approach:\n\n1. **Auto-tiering** splits MEMORY.md into core sections (identity, preferences, boundaries — always loaded) and archive sections (everything else, loaded on demand)\n2. **Manifest generation** creates a per-session file list: which files to load, which to skip, which to boost\n3. **Entity-aware boosting** links people, projects, and systems to files — search for \"alice\" → load preferences.md first\n4. **Token budgeting** caps how many files load based on available context window\n\n### The Flow\n\n```\nUser query → --compact --query \"alice\"\n              ↓\n         Manifest generated\n              ↓\n         Load required files (MEMORY.md, recent daily logs)\n              ↓\n         Boost entity-matched files (preferences.md, notes.md)\n              ↓\n         Agent loads only what matters → 70-85% context reduction\n```\n\n## The 4 Engines\n\n### ⚡ Engine 1: Auto-Tier (`--tier`)\n\nWhen MEMORY.md exceeds configurable thresholds (default: 500 lines or 25KB), splits into:\n- **Core file** — Identity, preferences, relationships, projects, patterns, boundaries\n- **Archive files** — Everything else, stored with timestamps in `memory/active/`\n\n**Safety features (v2):**\n- **Pre-tier backup** — Every `--tier` creates a full backup in `memory/backups/` before modifying MEMORY.md\n- **`--dry-run`** — Preview what tiering would do without making changes\n- **`--confirm`** — Required for destructive writes (no auto-tier without explicit confirmation)\n- **Minimum core size** — Aborts if core sections would fall below `minCoreLines`/`minCoreChars` thresholds\n- **`--restore --force`** — Restore MEMORY.md from the latest backup (requires `--force` flag)\n\nSections are classified by header keywords (identity, preferences, etc.) or by content heuristics.\n\n### 📋 Engine 2: Manifest Generator (`--compact`)\n\nCreates `memory/memory-manifest.json` with a file list:\n\n```json\n{\n  \"generated\": \"2026-05-21\",\n  \"files\": [\n    { \"path\": \"MEMORY.md\", \"tier\": \"core\", \"required\": true, \"size\": 50346 },\n    { \"path\": \"memory/2026-05-21.md\", \"tier\": \"recent\", \"required\": true, \"size\": 2034 },\n    { \"path\": \"self-improving/memory.md\", \"tier\": \"domain\", \"required\": false, \"size\": 670 }\n  ]\n}\n```\n\n**Options:**\n| Flag | Description |\n|------|-------------|\n| `--query \"text\"` | Entity-aware boosting — files linked to matching entities get priority |\n| `--budget N` | Token budget — only loads files that fit within N tokens |\n\n### 🔍 Engine 3: Audit Scanner (`--audit`)\n\nScans all memory files for:\n- **High-similarity pairs** — Files with >70% text overlap (potential duplicates)\n- **Revision keywords** — \"revised\", \"updated\", \"changed\", \"no longer\", \"actually\", \"correction\" (facts that may have been superseded)\n\nOutput: `memory/memory-audit-report.md`\n\n### 🏥 Engine 4: Health Monitor (`--status`)\n\nQuick snapshot of MEMORY.md line/char counts, file counts per directory, archive count, manifest status, entity index size, and WAL state.\n\n## Additional Tools\n\n### Entity Index (`--entity`)\n\n| Command | Description |\n|---------|-------------|\n| `--entity add <name> <type> <files...>` | Add entity (e.g., `alice person preferences.md`) |\n| `--entity list` | List all entities |\n| `--entity search <query>` | Search entities (direct and fuzzy match) |\n\n### WAL Protocol (`--wal`)\n\n| Command | Description |\n|---------|-------------|\n| `--wal init` | Initialize SESSION-STATE.md with template |\n| `--wal get` | Show current session state |\n| `--wal update <section> --content \"<text>\"` | Update a section |\n\n## Configuration\n\nEdit `config.json` to customize behavior:\n\n```json\n{\n  \"thresholds\": {\n    \"memoryMdMaxLines\": 500,\n    \"memoryMdMaxChars\": 25000,\n    \"tierArchiveMinAgeDays\": 3,\n    \"auditMaxFiles\": 50\n  },\n  \"tiering\": {\n    \"archiveDir\": \"memory/active\",\n    \"retentionDays\": 90,\n    \"keepInMemory\": [\n      \"identity\", \"preferences\", \"relationships\",\n      \"projects\", \"patterns\", \"boundaries\", \"key_facts\"\n    ]\n  },\n  \"manifest\": {\n    \"generateOnTier\": true,\n    \"manifestPath\": \"memory/memory-manifest.json\"\n  },\n  \"audit\": {\n    \"reportPath\": \"memory/memory-audit-report.md\",\n    \"duplicateThreshold\": 0.7,\n    \"conflictKeywords\": [\n      \"revised\", \"updated\", \"changed\", \"no longer\",\n      \"actually\", \"correction\", \"mistake\"\n    ]\n  }\n}\n```\n\n| Setting | Default | Description |\n|---------|---------|-------------|\n| `memoryMdMaxLines` | 500 | Auto-tier trigger (lines) |\n| `memoryMdMaxChars` | 25000 | Auto-tier trigger (characters) |\n| `tierArchiveMinAgeDays` | 3 | Minimum age before archiving |\n| `retentionDays` | 90 | ⚠️ Archive retention period. Files older than this are candidates for deletion (irreversible). Set to 365+ until confident. |\n| `keepInMemory` | see above | Headers/keywords that stay in core |\n| `generateOnTier` | true | Auto-generate manifest after tiering |\n| `duplicateThreshold` | 0.7 | Similarity score to flag as duplicate |\n| `conflictKeywords` | see above | Words that signal fact revision |\n| `backupDir` | `memory/backups` | Directory for pre-tier backups |\n| `minCoreLines` | 20 | Abort if core sections below this |\n| `minCoreChars` | 1000 | Abort if core chars below this |\n\n## Agent Memory Loading Protocol\n\nWhen the agent wakes up, use the manifest instead of loading all memory files:\n\n1. Read `memory/memory-manifest.json`\n2. Load all `required: true` files\n3. For `required: false` files, use `memory_search` to check relevance\n4. Load only the top 3-5 most relevant optional files\n\n**Result: 70–85% context reduction — load what matters, skip the rest.**\n\n## Heartbeat Integration\n\nAdd to your `HEARTBEAT.md`:\n\n```markdown\n### ⚡ MemoryRouter (SAFE commands only)\n\n- Run `node skills/memory-router/memory-router.js --compact` to update manifest ✅ safe\n- Run `node skills/memory-router/memory-router.js --audit` to check for issues ✅ safe\n- Run `node skills/memory-router/memory-router.js --status` for health overview ✅ safe\n- ⚠️ Do NOT auto-run `--tier` or `--restore` during heartbeats\n- `--tier --dry-run` is side-effect free (no files created)\n- For tiering: run `--tier --dry-run` manually, review output, then `--tier --confirm`\n```\n\n## Performance\n\n| Metric | Result |\n|--------|--------|\n| Tiering speed (8K lines) | 25ms |\n| Tiering speed (15K lines) | 30ms |\n| Token reduction | **96%** (7,809 → 222 lines) |\n| File count reduction | **53 → 15 files** |\n| Memory footprint | ~2MB (Node.js runtime) |\n\n## Comparison\n\n| Approach | Tokens Saved | Setup Effort | Maintenance | Privacy |\n|----------|-------------|-------------|-------------|---------|\n| Raw file injection | 0% | None | Manual | ✅ |\n| **MemoryRouter** | **70–85%** | **None** | **Automated** | **✅** |\n| Obsidian vault | 40–60% | High | Medium | ⚠️ Cloud |\n| Vector DB (ChromaDB) | 70–85% | Very High | High | ✅ |\n| mem0 | 70–85% | High | Medium | ⚠️ Cloud |\n\n**MemoryRouter gives you the best token savings of the vector DB approach with zero setup effort.**\n\n## Entity Naming\n\nPick one canonical name per entity and reuse it consistently:\n\n- Use full descriptive names: \"machine learning\" not \"ML\", \"JavaScript\" not \"JS\"\n- Same string after lowercasing = same entity. Different strings = different entities\n- Call `--entity search` periodically to verify your index\n\nExamples:\n```bash\n# ✅ Good — consistent, descriptive\nnode memory-router.js --entity add alice person preferences.md\nnode memory-router.js --entity add openclaw system AGENTS.md\n\n# ❌ Bad — inconsistent, ambiguous\nnode memory-router.js --entity add alice person preferences.md\nnode memory-router.js --entity add Alice person notes.md\nnode memory-router.js --entity add JS person docs.md\n```\n\n## Manifest Format\n\nThe manifest JSON tells the agent which files to load:\n\n```json\n{\n  \"generated\": \"2026-05-21\",\n  \"version\": 2,\n  \"query\": \"memory management\",\n  \"budget\": 20000,\n  \"files\": [\n    {\n      \"path\": \"MEMORY.md\",\n      \"tier\": \"core\",\n      \"required\": true,\n      \"size\": 50346\n    },\n    {\n      \"path\": \"memory/2026-05-21.md\",\n      \"tier\": \"recent\",\n      \"ageDays\": 0,\n      \"required\": true,\n      \"size\": 2034\n    },\n    {\n      \"path\": \"self-improving/memory.md\",\n      \"tier\": \"domain\",\n      \"required\": false,\n      \"size\": 670\n    }\n  ]\n}\n```\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `tier` | string | `core`, `recent`, `domain`, or `archive` |\n| `required` | bool | Always load this file |\n| `size` | int | File size in bytes |\n| `boosted` | bool | Entity match — higher priority |\n| `entityMatch` | string | Entity name that matched |\n| `load` | bool | Included under budget mode |\n| `budgetUsed` | int | Total tokens loaded (budget mode) |\n| `budgetEfficiency` | string | Percentage remaining (budget mode) |\n\n## Troubleshooting\n\n| Problem | Fix |\n|---------|-----|\n| \"No MEMORY.md found\" | Create one: `echo \"# MEMORY.md\" > MEMORY.md` |\n| \"Memory directory not found\" | Create it: `mkdir -p memory` |\n| Tiering not working | Check thresholds — if under 500 lines and 25KB, nothing happens (by design) |\n| Manifest shows wrong files | Run `--compact` again — it regenerates fresh each time |\n| Entity search returns nothing | Add entities first: `--entity add <name> <type> <files...>` |\n| Budget too small | Core files always load. Budget only controls optional files. |\n\n## ⚠️ SAFETY — READ BEFORE USING\n\n### Destructive Operations\n\n`--tier` and `--restore` **permanently modify user memory files**.\n\n- `--tier` rewrites MEMORY.md, moving sections to archive files\n- `--restore` overwrites MEMORY.md with backup content\n- Both require **explicit confirmation** (`--confirm` / `--force`) — they will refuse to run without it\n- Always run `--tier --dry-run` first to preview what will change\n- Pre-tier backups are created only when actually tiering (not in dry-run mode)\n\n### Archive Retention — Data Loss Risk\n\nThe `retentionDays` config (default: 90) marks archived files as **candidates for deletion** after that period. This is **irreversible** — once deleted, archived memory sections cannot be recovered.\n\n**Before enabling retention:**\n1. Back up your entire `memory/` directory\n2. Set `retentionDays` to a large value (365+) until you're confident\n3. Monitor what gets deleted before reducing the value\n\n### Safe vs Unsafe Commands\n\n| Command | Safe in automation? | Modifies files? |\n|---------|-------------------|------------------|\n| `--compact` | ✅ Yes | Writes `memory-manifest.json` (generated output) |\n| `--audit` | ✅ Yes | Writes `memory-audit-report.md` (generated report) |\n| `--status` | ✅ Yes | No file writes |\n| `--entity add` | ⚠️ Yes — but writes entity index | Yes (persists entity → file mapping) |\n| `--entity list/search` | ✅ Yes | No file writes |\n| `--wal init` | ⚠️ Yes — but creates SESSION-STATE.md | Yes (creates new file) |\n| `--wal get` | ✅ Yes | No file writes |\n| `--wal update` | ⚠️ Yes — but modifies SESSION-STATE.md | Yes (updates session state) |\n| `--tier --dry-run` | ✅ Yes | No file writes (side-effect free) |\n| `--tier --confirm` | ❌ No — rewrites MEMORY.md + creates backup | Yes |\n| `--restore --force` | ❌ No — overwrites MEMORY.md | Yes |\n\n**`--compact`, `--audit`, `--status`, `--entity list/search`, `--wal get`, and `--tier --dry-run` are safe for unattended/heartbeat use.**\n\n**`--entity add`, `--wal init`, and `--wal update` write persistent files — review before automating.**\n\n**`--tier --confirm` and `--restore --force` are destructive — never automate.**\n\n## Security\n\nBuilt with defense-in-depth:\n\n- **Path validation** — rejects file paths outside workspace root\n- **Regex escaping** — prevents injection in WAL section names\n- **Symlink protection** — refuses to read/write symlinks\n- **Size limits** — 10MB max file size\n- **Entity name validation** — alphanumeric + hyphens/underscores only\n- **Content sanitization** — prevents header injection in WAL updates\n- **Audit keyword validation** — rejects regex metacharacters in conflict keywords\n\n## Design Principles\n\n1. **Safe by default** — Destructive operations require explicit flags (`--confirm`, `--force`)\n2. **No external dependencies** — Pure Node.js, no npm packages\n3. **Configurable** — Thresholds, keywords, retention policies\n4. **Transparent** — Generates reports, nothing is silently deleted\n5. **Reversible** — Archives use dated filenames, original content preserved\n6. **Privacy-first** — All local, no cloud APIs\n\nFile v2.4.3:README.md\n\n# MemoryRouter ⚡\n\n**Never lose context. Never forget decisions. Never repeat mistakes.**\n\nThe memory problem is the single biggest reason agents feel dumb over time. Not the models. Not the prompts. **Memory management.**\n\nMemoryRouter fixes it with one tool, zero dependencies, zero setup.\n\n## The Problem — In 30 Seconds\n\nAgent memory files grow unbounded. After a week, you've got thousands of lines across dozens of files. Every session loads **everything** — even when the user asks \"what's the weather?\"\n\nThat's tokens burned on irrelevant memories, every interaction, forever.\n\nThen compaction kicks in and details vanish.\n\n**The bottleneck isn't the model. It's what the model gets to see.**\n\n## Why Memory Fails\n\n| Failure Mode | Cause | Fix |\n|-------------|-------|-----|\n| Forgets everything | Loads irrelevant files, context window fills up | Smart manifest — load only what matters |\n| Repeats mistakes | Lessons not captured or loaded | Entity index + audit for conflicts |\n| Repeats work | No session state persistence | WAL protocol — write state before responding |\n| Slow responses | Loads 50+ files when only 3 matter | Token budgeting — cap context window |\n| Duplicates everywhere | No automated cleanup | `--audit` finds high-similarity pairs |\n\n## The Architecture\n\n```\n┌──────────────────────────────────────────────────────┐\n│              MEMORYROUTER ⚡                          │\n├──────────────────────────────────────────────────────┤\n│                                                      │\n│  ┌──────────────┐    ┌──────────────┐               │\n│  │  AUTO-TIER   │    │  MANIFEST    │               │\n│  │  MEMORY.md   │ →  │  GENERATOR   │               │\n│  │              │    │              │               │\n│  │ Core (always │    │ Required:    │               │\n│  │ loaded)      │    │ MEMORY.md    │               │\n│  │ + Archive    │    │ Recent logs  │               │\n│  │ (on demand)  │    │ Boosted:     │               │\n│  └──────────────┘    │ entity files │               │\n│                      └──────┬───────┘               │\n│                             │                        │\n│              ┌──────────────▼──────────────┐         │\n│              │  ENTITY RESOLUTION          │         │\n│              │  \"alice\" → preferences.md,         │         │\n│              │  notes.md, decisions.md│         │\n│              └──────────────┬──────────────┘         │\n│                             │                        │\n│              ┌──────────────▼──────────────┐         │\n│              │  TOKEN BUDGET FILTER        │         │\n│              │  20K budget → 7 files       │         │\n│              │  100K budget → 16 files     │         │\n│              └──────────────┬──────────────┘         │\n│                             │                        │\n│              ┌──────────────▼──────────────┐         │\n│              │  AGENT LOADS ONLY WHAT      │         │\n│              │  MATTERS → 70-85% REDUCTION │         │\n│              └─────────────────────────────┘         │\n└──────────────────────────────────────────────────────┘\n```\n\n## Quick Start\n\n### ⚠️ Safety First\n\n**Before using `--tier` or `--restore`:**\n\n1. **Back up your memory files** — `cp -r memory/ memory-backup-$(date +%Y%m%d)/`\n2. **Run `--tier --dry-run` first** — review what it will do\n3. **Only then** run `--tier --confirm` if the output looks correct\n\n`--tier` and `--restore` **permanently modify** user memory files. There is no undo.\n\n### Fix a bloated MEMORY.md in one command (requires --confirm)\n\n```bash\nnode skills/memory-router/memory-router.js --tier --confirm\n```\n\n**Output:**\n```\n[memory-router] MEMORY.md: 7809 lines, 309254 chars\n[memory-router] Tiered: 202 core sections, 1002 archived\n[memory-router] MEMORY.md reduced from 7809 lines to 2222 lines\n```\n\n### Generate a smart manifest in one command\n\n```bash\nnode skills/memory-router/memory-router.js --compact\n```\n\nCreates `memory/memory-manifest.json` — the agent's shopping list of what to load.\n\n### With entity boosting\n\n```bash\nnode skills/memory-router/memory-router.js --compact --query \"alice\"\n```\n\nFiles linked to \"alice\" get priority. No AI, no embeddings — just fast entity resolution.\n\n### With a token budget\n\n```bash\nnode skills/memory-router/memory-router.js --compact --budget 20000\n```\n\nOnly loads files that fit within 20K tokens. Tight budgets load core only. Generous budgets load archive on demand.\n\n### Other commands\n\n```bash\nnode skills/memory-router/memory-router.js --audit      # Find duplicates & conflicts\nnode skills/memory-router/memory-router.js --status      # Health overview\nnode skills/memory-router/memory-router.js --entity add alice person preferences.md\n```\n\n## How It Works\n\n### The Core Insight\n\n**Memory management is the bottleneck, not model capability.** Every agent system hits the same wall — context window fills up, everything loads, irrelevant memories dilute the signal.\n\nMemoryRouter takes a **routing** approach rather than a **compression** approach:\n\n1. **Auto-tiering** splits MEMORY.md into core sections (identity, preferences, boundaries — always loaded) and archive sections (everything else, loaded on demand)\n2. **Manifest generation** creates a per-session file list: which files to load, which to skip, which to boost\n3. **Entity-aware boosting** links people, projects, and systems to files — search for \"alice\" → load preferences.md first\n4. **Token budgeting** caps how many files load based on available context window\n\n### The Flow\n\n```\nUser query → --compact --query \"alice\"\n              ↓\n         Manifest generated\n              ↓\n         Load required files (MEMORY.md, recent daily logs)\n              ↓\n         Boost entity-matched files (preferences.md, notes.md)\n              ↓\n         Agent loads only what matters → 70-85% context reduction\n```\n\n## The 4 Engines\n\n### ⚡ Engine 1: Auto-Tier (`--tier`)\n\nWhen MEMORY.md exceeds configurable thresholds (default: 500 lines or 25KB), splits into:\n- **Core file** — Identity, preferences, relationships, projects, patterns, boundaries\n- **Archive files** — Everything else, stored with timestamps in `memory/active/`\n\nSections are classified by header keywords (identity, preferences, etc.) or by content heuristics.\n\n### 📋 Engine 2: Manifest Generator (`--compact`)\n\nCreates `memory/memory-manifest.json` with a file list:\n\n```json\n{\n  \"generated\": \"2026-05-21\",\n  \"files\": [\n    { \"path\": \"MEMORY.md\", \"tier\": \"core\", \"required\": true, \"size\": 50346 },\n    { \"path\": \"memory/2026-05-21.md\", \"tier\": \"recent\", \"required\": true, \"size\": 2034 },\n    { \"path\": \"self-improving/memory.md\", \"tier\": \"domain\", \"required\": false, \"size\": 670 }\n  ]\n}\n```\n\n**Options:**\n| Flag | Description |\n|------|-------------|\n| `--query \"text\"` | Entity-aware boosting — files linked to matching entities get priority |\n| `--budget N` | Token budget — only loads files that fit within N tokens |\n\n### 🔍 Engine 3: Audit Scanner (`--audit`)\n\nScans all memory files for:\n- **High-similarity pairs** — Files with >70% text overlap (potential duplicates)\n- **Revision keywords** — \"revised\", \"updated\", \"changed\", \"no longer\", \"actually\", \"correction\" (facts that may have been superseded)\n\nOutput: `memory/memory-audit-report.md`\n\n### 🏥 Engine 4: Health Monitor (`--status`)\n\nQuick snapshot of MEMORY.md line/char counts, file counts per directory, archive count, manifest status, entity index size, and WAL state.\n\n## Additional Tools\n\n### Entity Index (`--entity`)\n\n| Command | Description |\n|---------|-------------|\n| `--entity add <name> <type> <files...>` | Add entity (e.g., `alice person preferences.md`) |\n| `--entity list` | List all entities |\n| `--entity search <query>` | Search entities (direct and fuzzy match) |\n\n### WAL Protocol (`--wal`)\n\n| Command | Description |\n|---------|-------------|\n| `--wal init` | Initialize SESSION-STATE.md with template |\n| `--wal get` | Show current session state |\n| `--wal update <section> --content \"<text>\"` | Update a section |\n\n## Configuration\n\nEdit `config.json` to customize behavior:\n\n```json\n{\n  \"thresholds\": {\n    \"memoryMdMaxLines\": 500,\n    \"memoryMdMaxChars\": 25000,\n    \"tierArchiveMinAgeDays\": 3,\n    \"auditMaxFiles\": 50\n  },\n  \"tiering\": {\n    \"archiveDir\": \"memory/active\",\n    \"retentionDays\": 90,\n    \"keepInMemory\": [\n      \"identity\", \"preferences\", \"relationships\",\n      \"projects\", \"patterns\", \"boundaries\", \"key_facts\"\n    ]\n  },\n  \"manifest\": {\n    \"generateOnTier\": true,\n    \"manifestPath\": \"memory/memory-manifest.json\"\n  },\n  \"audit\": {\n    \"reportPath\": \"memory/memory-audit-report.md\",\n    \"duplicateThreshold\": 0.7,\n    \"conflictKeywords\": [\n      \"revised\", \"updated\", \"changed\", \"no longer\",\n      \"actually\", \"correction\", \"mistake\"\n    ]\n  }\n}\n```\n\n| Setting | Default | Description |\n|---------|---------|-------------|\n| `memoryMdMaxLines` | 500 | Auto-tier trigger (lines) |\n| `memoryMdMaxChars` | 25000 | Auto-tier trigger (characters) |\n| `tierArchiveMinAgeDays` | 3 | Minimum age before archiving |\n| `retentionDays` | 90 | Archive retention period |\n| `keepInMemory` | see above | Headers/keywords that stay in core |\n| `generateOnTier` | true | Auto-generate manifest after tiering |\n| `duplicateThreshold` | 0.7 | Similarity score to flag as duplicate |\n| `conflictKeywords` | see above | Words that signal fact revision |\n\n## Agent Memory Loading Protocol\n\nWhen the agent wakes up, use the manifest instead of loading all memory files:\n\n1. Read `memory/memory-manifest.json`\n2. Load all `required: true` files\n3. For `required: false` files, use `memory_search` to check relevance\n4. Load only the top 3-5 most relevant optional files\n\n**Result: 70–85% context reduction — load what matters, skip the rest.**\n\n## Heartbeat Integration\n\nAdd to your `HEARTBEAT.md`:\n\n```markdown\n### ⚡ MemoryRouter (SAFE commands only)\n\n- Run `node skills/memory-router/memory-router.js --compact` to update manifest ✅ safe\n- Run `node skills/memory-router/memory-router.js --audit` to check for issues ✅ safe\n- Run `node skills/memory-router/memory-router.js --status` for health overview ✅ safe\n- ⚠️ Do NOT auto-run `--tier --confirm` or `--restore --force` during heartbeats\n- `--tier --dry-run` is side-effect free (no file writes)\n- For tiering: run `--tier --dry-run` manually, review output, then `--tier --confirm`\n```\n\n## Performance\n\n| Metric | Result |\n|--------|--------|\n| Tiering speed (8K lines) | 25ms |\n| Tiering speed (15K lines) | 30ms |\n| Token reduction | **96%** (7,809 → 222 lines) |\n| File count reduction | **53 → 15 files** |\n| Memory footprint | ~2MB (Node.js runtime) |\n\n## Comparison\n\n| Approach | Tokens Saved | Setup Effort | Maintenance | Privacy |\n|----------|-------------|-------------|-------------|---------|\n| Raw file injection | 0% | None | Manual | ✅ |\n| **MemoryRouter** | **70–85%** | **None** | **Automated** | **✅** |\n| Obsidian vault | 40–60% | High | Medium | ⚠️ Cloud |\n| Vector DB (ChromaDB) | 70–85% | Very High | High | ✅ |\n| mem0 | 70–85% | High | Medium | ⚠️ Cloud |\n\n**MemoryRouter gives you the best token savings of the vector DB approach with zero setup effort.**\n\n## Entity Naming\n\nPick one canonical name per entity and reuse it consistently:\n\n- Use full descriptive names: \"machine learning\" not \"ML\", \"JavaScript\" not \"JS\"\n- Same string after lowercasing = same entity. Different strings = different entities\n- Call `--entity search` periodically to verify your index\n\nExamples:\n```bash\n# ✅ Good — consistent, descriptive\nnode memory-router.js --entity add alice person preferences.md\nnode memory-router.js --entity add openclaw system AGENTS.md\n\n# ❌ Bad — inconsistent, ambiguous\nnode memory-router.js --entity add alice person preferences.md\nnode memory-router.js --entity add Alice person notes.md\nnode memory-router.js --entity add JS person docs.md\n```\n\n## Manifest Format\n\nThe manifest JSON tells the agent which files to load:\n\n```json\n{\n  \"generated\": \"2026-05-21\",\n  \"version\": 2,\n  \"query\": \"memory management\",\n  \"budget\": 20000,\n  \"files\": [\n    {\n      \"path\": \"MEMORY.md\",\n      \"tier\": \"core\",\n      \"required\": true,\n      \"size\": 50346\n    },\n    {\n      \"path\": \"memory/2026-05-21.md\",\n      \"tier\": \"recent\",\n      \"ageDays\": 0,\n      \"required\": true,\n      \"size\": 2034\n    },\n    {\n      \"path\": \"self-improving/memory.md\",\n      \"tier\": \"domain\",\n      \"required\": false,\n      \"size\": 670\n    }\n  ]\n}\n```\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `tier` | string | `core`, `recent`, `domain`, or `archive` |\n| `required` | bool | Always load this file |\n| `size` | int | File size in bytes |\n| `boosted` | bool | Entity match — higher priority |\n| `entityMatch` | string | Entity name that matched |\n| `load` | bool | Included under budget mode |\n| `budgetUsed` | int | Total tokens loaded (budget mode) |\n| `budgetEfficiency` | string | Percentage remaining (budget mode) |\n\n## Troubleshooting\n\n| Problem | Fix |\n|---------|-----|\n| \"No MEMORY.md found\" | Create one: `echo \"# MEMORY.md\" > MEMORY.md` |\n| \"Memory directory not found\" | Create it: `mkdir -p memory` |\n| Tiering not working | Check thresholds — if under 500 lines and 25KB, nothing happens (by design) |\n| Manifest shows wrong files | Run `--compact` again — it regenerates fresh each time |\n| Entity search returns nothing | Add entities first: `--entity add <name> <type> <files...>` |\n| Budget too small | Core files always load. Budget only controls optional files. |\n\n## ⚠️ SAFETY — READ BEFORE USING\n\n### Destructive Operations\n\n`--tier` and `--restore` **permanently modify user memory files**.\n\n- `--tier` rewrites MEMORY.md, moving sections to archive files\n- `--restore` overwrites MEMORY.md with backup content\n- Both require **explicit confirmation** (`--confirm` / `--force`) — they will refuse to run without it\n- Always run `--tier --dry-run` first to preview what will change\n- Pre-tier backups are created before any tiering operation\n\n### Archive Retention — Data Loss Risk\n\nThe `retentionDays` config (default: 90) marks archived files as **candidates for deletion** after that period. This is **irreversible** — once deleted, archived memory sections cannot be recovered.\n\n**Note:** This is the one case where files are deleted. All other operations are non-destructive by default. The earlier claim that \"nothing is silently deleted\" applies only to operations that do not have retention enabled.\n\n**Before enabling retention:**\n1. Back up your entire `memory/` directory\n2. Set `retentionDays` to a large value (365+) until you're confident\n3. Monitor what gets deleted before reducing the value\n\n### Safe vs Unsafe Commands\n\n| Command | Safe in automation? | Modifies files? |\n|---------|-------------------|------------------|\n| `--compact` | ✅ Yes | Writes `memory-manifest.json` (generated output) |\n| `--audit` | ✅ Yes | Writes `memory-audit-report.md` (generated report) |\n| `--status` | ✅ Yes | No file writes |\n| `--entity add` | ⚠️ Yes — but writes entity index | Yes (persists entity → file mapping) |\n| `--entity list/search` | ✅ Yes | No file writes |\n| `--wal init` | ⚠️ Yes — but creates SESSION-STATE.md | Yes (creates new file) |\n| `--wal get` | ✅ Yes | No file writes |\n| `--wal update` | ⚠️ Yes — but modifies SESSION-STATE.md | Yes (updates session state) |\n| `--tier --dry-run` | ✅ Yes | No file writes (side-effect free) |\n| `--tier --confirm` | ❌ No — rewrites MEMORY.md + creates backup | Yes |\n| `--restore --force` | ❌ No — overwrites MEMORY.md | Yes |\n\n**`--compact`, `--audit`, `--status`, `--entity list/search`, `--wal get`, and `--tier --dry-run` are safe for unattended/heartbeat use.**\n\n**`--entity add`, `--wal init`, and `--wal update` write persistent files — review before automating.**\n\n**`--tier --confirm` and `--restore --force` are destructive — never automate.**\n\n## Security\n\nBuilt with defense-in-depth:\n\n- **Path validation** — rejects file paths outside workspace root\n- **Regex escaping** — prevents injection in WAL section names\n- **Symlink protection** — refuses to read/write symlinks\n- **Size limits** — 10MB max file size\n- **Entity name validation** — alphanumeric + hyphens/underscores only\n- **Content sanitization** — prevents header injection in WAL updates\n- **Audit keyword validation** — rejects regex metacharacters in conflict keywords\n\n## Design Principles\n\n1. **Safe by default** — Destructive operations require explicit flags (`--confirm`, `--force`)\n2. **No external dependencies** — Pure Node.js, no npm packages\n3. **Configurable** — Thresholds, keywords, retention policies\n4. **Transparent** — Generates reports; however, retention policy (when enabled) deletes archived files after `retentionDays` — this is intentional but irreversible\n5. **Reversible** — Pre-tier backups preserve original MEMORY.md; restored via `--restore --force`\n6. **Privacy-first** — All local, no cloud APIs\n\nFile v2.4.3:_meta.json\n\n{\n  \"ownerId\": \"kn7b6eyf5vc7khg5fr63pjm8xd82qvw5\",\n  \"slug\": \"memory-router\",\n  \"version\": \"2.4.3\",\n  \"publishedAt\": 1784659889200\n}\n\nFile v2.4.3:INSTALL.md\n\n# MemoryRouter — Installation Guide\n\n## Prerequisites\n\n- OpenClaw installed and running\n- Node.js 18+ (built-in `fs` and `path` — no npm packages needed)\n- A `MEMORY.md` file in your workspace (can be empty initially)\n\n## Quick Install (1 minute)\n\n```bash\n# 1. Create the skill directory\nmkdir -p ~/.openclaw/workspace/skills/memory-router\n\n# 2. Copy the skill files\n# Place these files from this package into the directory above:\n#   - memory-router.js   (core engine)\n#   - config.json          (thresholds and options)\n#   - SKILL.md             (skill definition)\n#   - README.md            (this guide)\n\n# 3. Make executable\nchmod +x ~/.openclaw/workspace/skills/memory-router/memory-router.js\n\n# 4. Test it works\nnode ~/.openclaw/workspace/skills/memory-router/memory-router.js --status\n```\n\nExpected output:\n```\n=== MemoryRouter Status ===\n\nMEMORY.md: X lines, Y KB ✅ OK\nmemory/: 0 files, 0.0 KB total\nself-improving/: 0 files\nproactivity/: 0 files\narchives: 0 files\nmanifest: not generated\nentity index: 0 entities\nWAL: not initialized\n```\n\n## Configuration\n\nEdit `config.json` to customize behavior:\n\n```json\n{\n  \"thresholds\": {\n    \"memoryMdMaxLines\": 500,\n    \"memoryMdMaxChars\": 25000,\n    \"tierArchiveMinAgeDays\": 3,\n    \"auditMaxFiles\": 50\n  },\n  \"tiering\": {\n    \"archiveDir\": \"memory/active\",\n    \"retentionDays\": 90,\n    \"keepInMemory\": [\n      \"identity\", \"preferences\", \"relationships\",\n      \"projects\", \"patterns\", \"boundaries\", \"key_facts\"\n    ]\n  },\n  \"manifest\": {\n    \"generateOnTier\": true,\n    \"manifestPath\": \"memory/memory-manifest.json\"\n  },\n  \"audit\": {\n    \"reportPath\": \"memory/memory-audit-report.md\",\n    \"duplicateThreshold\": 0.7,\n    \"conflictKeywords\": [\n      \"revised\", \"updated\", \"changed\", \"no longer\",\n      \"actually\", \"correction\", \"mistake\"\n    ]\n  }\n}\n```\n\n### Key settings explained\n\n| Setting | Default | What it does |\n|---------|---------|-------------|\n| `memoryMdMaxLines` | 500 | Auto-tier triggers when MEMORY.md exceeds this line count |\n| `memoryMdMaxChars` | 25000 | Same, but by character count (whichever threshold is hit first) |\n| `tierArchiveMinAgeDays` | 3 | Sections must be this old before archiving |\n| `retentionDays` | 90 | ⚠️ Archived files older than this are **candidates for deletion**. Irreversible. Set to 365+ until confident. |\n| `keepInMemory` | see above | Headers/keywords that always stay in the core MEMORY.md |\n| `generateOnTier` | true | Auto-generate manifest after tiering |\n| `duplicateThreshold` | 0.7 | Similarity score (>70%) to flag as potential duplicate |\n\n## Heartbeat Integration\n\nAdd this to your `HEARTBEAT.md` under scheduled tasks:\n\n```markdown\n### 🔧 MemoryRouter (SAFE commands only)\n\n- Run `node skills/memory-router/memory-router.js --compact` to update manifest ✅ safe\n- Run `node skills/memory-router/memory-router.js --audit` to check for issues ✅ safe\n- Run `node skills/memory-router/memory-router.js --status` for health overview ✅ safe\n- ⚠️ Do NOT auto-run `--tier` during heartbeats — it permanently rewrites MEMORY.md\n- `--tier --dry-run` is side-effect free (no files created or modified)\n- For tiering: run `--tier --dry-run` manually, review output, then `--tier --confirm`\n- Check `memory/memory-audit-report.md` for any flagged conflicts\n```\n\n**Important:** `--tier` permanently rewrites MEMORY.md. Only run it manually with `--confirm` after reviewing `--dry-run` output.\n\n## Agent Memory Loading Protocol\n\nWhen your agent wakes up, use the manifest instead of loading all memory files:\n\n1. Read `memory/memory-manifest.json`\n2. Load all `required: true` files\n3. For `required: false` files, use `memory_search` to check relevance\n4. Load only the top 3-5 most relevant optional files\n\nThis gives you **70-85% context reduction** — load what matters, skip the rest.\n\n## Commands Reference\n\n| Command | What it does |\n|---------|-------------|\n| `--tier` | Auto-tier MEMORY.md (split core + archive) |\n| `--compact` | Generate per-session manifest |\n| `--compact --query \"text\"` | Query-aware manifest with entity boosting |\n| `--compact --budget N` | Manifest filtered to N tokens |\n| `--audit` | Scan for duplicates/conflicts |\n| `--status` | Show memory health overview |\n| `--entity add <name> <type> <files...>` | Add entity to index |\n| `--entity list` | List all entities |\n| `--entity search <query>` | Search entities |\n| `--wal init` | Initialize WAL (session state) |\n| `--wal get` | Show current WAL state |\n| `--wal update <section> --content \"<text>\"` | Update WAL section |\n\n## Troubleshooting\n\n### \"No MEMORY.md found\"\n\nCreate one:\n```bash\necho \"# MEMORY.md - Long-Term Memory\" > ~/.openclaw/workspace/MEMORY.md\n```\n\n### \"Memory directory not found\"\n\nCreate it:\n```bash\nmkdir -p ~/.openclaw/workspace/memory\n```\n\n### Tiering not working\n\nCheck your thresholds in `config.json`. If MEMORY.md is under 500 lines and 25KB, nothing happens — that's by design.\n\n### Manifest shows wrong file count\n\nRun `--compact` again. The manifest is regenerated fresh each time.\n\n### Entity search returns nothing\n\nAdd entities first:\n```bash\nnode memory-router.js --entity add james person USER.md IDENTITY.md\n```\n\n## Custom Workspace Path\n\nIf you want to use a different workspace:\n\n```bash\nMM_WORKSPACE=/path/to/your/workspace node memory-router.js --status\n```\n\nFile v2.4.3:skill-card.md\n\n## Description:\n\nMemory Router helps agents manage local memory files by generating focused manifests, tiering oversized MEMORY.md content, auditing duplicate or conflicting entries, and maintaining entity and session-state indexes.\n\nThis skill is ready for commercial/non-commercial use.\n\n## Publisher:\n\n[jlacroix82](https://clawhub.ai/user/jlacroix82)\n\n### License/Terms of Use:\n\nMIT-0\n\n## Use Case:\n\nDevelopers and agent operators use Memory Router to reduce memory context bloat, route only relevant memory files into a session, and inspect local memory health before loading or rewriting memory state.\n\n### Deployment Geography for Use:\n\nGlobal\n\n## Known Risks and Mitigations:\n\nRisk: Tiering, restore, cleanup, entity, and WAL commands can modify or overwrite local memory files.\n\nMitigation: Use a backed-up workspace, run status or dry-run commands first, and reserve --tier --confirm and --restore --force for reviewed manual execution.\n\nRisk: Custom workspace or path settings can increase the chance of operating on the wrong files.\n\nMitigation: Avoid absolute paths or .. components in custom path settings and confirm the workspace before running commands that write files.\n\nRisk: The security verdict is suspicious because destructive restore and tiering guarantees may be weaker than the documentation suggests.\n\nMitigation: Treat the skill as an assisted local memory tool, review generated manifests and audit reports, and do not rely on its backups as the only recovery mechanism.\n\n## Reference(s):\n\n- [ClawHub skill page](https://clawhub.ai/jlacroix82/skills/memory-router)\n- [README](artifact/README.md)\n- [Installation Guide](artifact/INSTALL.md)\n- [Skill definition](artifact/SKILL.md)\n\n## Skill Output:\n\n**Output Type(s):** [text, markdown, code, shell commands, configuration, guidance]\n\n**Output Format:** [Markdown guidance with shell commands, JSON configuration examples, generated JSON manifests, text status output, and Markdown audit reports]\n\n**Output Parameters:** [1D]\n\n**Other Properties Related to Output:** [Local filesystem outputs may include memory/memory-manifest.json, memory/memory-audit-report.md, archive files, backups, entity indexes, and SESSION-STATE.md depending on the command.]\n\n## Skill Version(s):\n\n2.4.3 (source: server release evidence)\n\n## Ethical Considerations:\n\nUsers 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.\n\nFile v2.4.3:config.json\n\n{\n  \"thresholds\": {\n    \"memoryMdMaxLines\": 500,\n    \"memoryMdMaxChars\": 25000,\n    \"tierArchiveMinAgeDays\": 3,\n    \"auditMaxFiles\": 50\n  },\n  \"tiering\": {\n    \"archiveDir\": \"memory/active\",\n    \"backupDir\": \"memory/backups\",\n    \"retentionDays\": 90,\n    \"minCoreLines\": 20,\n    \"minCoreChars\": 1000,\n    \"keepInMemory\": [\n      \"identity\",\n      \"preferences\",\n      \"relationships\",\n      \"projects\",\n      \"patterns\",\n      \"boundaries\",\n      \"key_facts\"\n    ]\n  },\n  \"manifest\": {\n    \"generateOnTier\": true,\n    \"manifestPath\": \"memory/memory-manifest.json\"\n  },\n  \"audit\": {\n    \"reportPath\": \"memory/memory-audit-report.md\",\n    \"duplicateThreshold\": 0.7,\n    \"conflictKeywords\": [\"revised\", \"updated\", \"changed\", \"no longer\", \"actually\", \"correction\", \"mistake\"]\n  }\n}\n\nFile v2.4.3:clawhub.yaml\n\nslug: memory-router\nname: Memory Router\nowner: jlacroix82\ndescription: Intelligent memory file management with manifest generation, auditing, entity indexing, and tiering\nversion: 2.4.2\ntype: skill\nauthor: OpenClaw\nlicense: MIT\nkeywords:\n  - memory\n  - indexing\n  - routing\n  - agent\n  - manifest\nentry: SKILL.md\ndependencies: []\n\nArchive v2.4.2: 8 files, 28915 bytes\n\nFiles: _meta.json (132b), clawhub.yaml (330b), config.json (778b), INSTALL.md (5310b), memory-router.js (41394b), README.md (18132b), skill-card.md (2293b), SKILL.md (19145b)\n\nFile v2.4.2:SKILL.md\n\n# MemoryRouter ⚡\n\n**Never lose context. Never forget decisions. Never repeat mistakes.**\n\nThe memory problem is the single biggest reason agents feel dumb over time. Not the models. Not the prompts. **Memory management.**\n\nMemoryRouter fixes it with one tool, zero dependencies, zero setup.\n\n## The Problem — In 30 Seconds\n\nAgent memory files grow unbounded. After a week, you've got thousands of lines across dozens of files. Every session loads **everything** — even when the user asks \"what's the weather?\"\n\nThat's tokens burned on irrelevant memories, every interaction, forever.\n\nThen compaction kicks in and details vanish.\n\n**The bottleneck isn't the model. It's what the model gets to see.**\n\n## Why Memory Fails\n\n| Failure Mode | Cause | Fix |\n|-------------|-------|-----|\n| Forgets everything | Loads irrelevant files, context window fills up | Smart manifest — load only what matters |\n| Repeats mistakes | Lessons not captured or loaded | Entity index + audit for conflicts |\n| Repeats work | No session state persistence | WAL protocol — write state before responding |\n| Slow responses | Loads 50+ files when only 3 matter | Token budgeting — cap context window |\n| Duplicates everywhere | No automated cleanup | `--audit` finds high-similarity pairs |\n\n## The Architecture\n\n```\n┌──────────────────────────────────────────────────────┐\n│              MEMORYROUTER ⚡                          │\n├──────────────────────────────────────────────────────┤\n│                                                      │\n│  ┌──────────────┐    ┌──────────────┐               │\n│  │  AUTO-TIER   │    │  MANIFEST    │               │\n│  │  MEMORY.md   │ →  │  GENERATOR   │               │\n│  │              │    │              │               │\n│  │ Core (always │    │ Required:    │               │\n│  │ loaded)      │    │ MEMORY.md    │               │\n│  │ + Archive    │    │ Recent logs  │               │\n│  │ (on demand)  │    │ Boosted:     │               │\n│  └──────────────┘    │ entity files │               │\n│                      └──────┬───────┘               │\n│                             │                        │\n│              ┌──────────────▼──────────────┐         │\n│              │  ENTITY RESOLUTION          │         │\n│              │  \"alice\" → preferences.md,         │         │\n│              │  notes.md, decisions.md│         │\n│              └──────────────┬──────────────┘         │\n│                             │                        │\n│              ┌──────────────▼──────────────┐         │\n│              │  TOKEN BUDGET FILTER        │         │\n│              │  20K budget → 7 files       │         │\n│              │  100K budget → 16 files     │         │\n│              └──────────────┬──────────────┘         │\n│                             │                        │\n│              ┌──────────────▼──────────────┐         │\n│              │  AGENT LOADS ONLY WHAT      │         │\n│              │  MATTERS → 70-85% REDUCTION │         │\n│              └─────────────────────────────┘         │\n└──────────────────────────────────────────────────────┘\n```\n\n## Quick Start\n\n### Fix a bloated MEMORY.md (requires confirmation)\n\n```bash\nnode skills/memory-router/memory-router.js --tier --confirm\n```\n\n**Output:**\n```\n[memory-router] MEMORY.md: 7809 lines, 309254 chars\n[memory-router] ✅ Pre-tier backup: memory/backups/MEMORY-backup-2026-05-23-1234567890.md (7809 lines saved)\n[memory-router] Tiered: 202 core sections, 1002 archived\n[memory-router] MEMORY.md reduced from 7809 lines to 2222 lines\n```\n\n### Preview tiering without making changes\n\n```bash\nnode skills/memory-router/memory-router.js --tier --dry-run\n```\n\n**Output:**\n```\n[memory-router] MEMORY.md: 7809 lines, 309254 chars\n[memory-router] ── DRY RUN ──\n[memory-router] Would archive: memory/active/MEMORY-archive-2026-05-23.md\n[memory-router] Would reduce MEMORY.md from 7809 lines to ~2222 lines\n[memory-router] Core sections: 202, Archive sections: 1002\n[memory-router] ✅ No files were modified.\n```\n\n### Restore MEMORY.md from latest backup\n\n```bash\nnode skills/memory-router/memory-router.js --restore --force\n```\n\n⚠️ **Destructive** — overwrites MEMORY.md. Requires `--force` flag. Extracts only the original content from the backup (metadata headers are stripped). Always creates a backup of the current MEMORY.md before overwriting.\n\n### Generate a smart manifest in one command\n\n```bash\nnode skills/memory-router/memory-router.js --compact\n```\n\nCreates `memory/memory-manifest.json` — the agent's shopping list of what to load.\n\n### With entity boosting\n\n```bash\nnode skills/memory-router/memory-router.js --compact --query \"alice\"\n```\n\nFiles linked to \"alice\" get priority. No AI, no embeddings — just fast entity resolution.\n\n### With a token budget\n\n```bash\nnode skills/memory-router/memory-router.js --compact --budget 20000\n```\n\nOnly loads files that fit within 20K tokens. Tight budgets load core only. Generous budgets load archive on demand.\n\n### Other commands\n\n```bash\nnode skills/memory-router/memory-router.js --audit      # Find duplicates & conflicts\nnode skills/memory-router/memory-router.js --status      # Health overview\nnode skills/memory-router/memory-router.js --entity add alice person preferences.md\n```\n\n## How It Works\n\n### The Core Insight\n\n**Memory management is the bottleneck, not model capability.** Every agent system hits the same wall — context window fills up, everything loads, irrelevant memories dilute the signal.\n\nMemoryRouter takes a **routing** approach rather than a **compression** approach:\n\n1. **Auto-tiering** splits MEMORY.md into core sections (identity, preferences, boundaries — always loaded) and archive sections (everything else, loaded on demand)\n2. **Manifest generation** creates a per-session file list: which files to load, which to skip, which to boost\n3. **Entity-aware boosting** links people, projects, and systems to files — search for \"alice\" → load preferences.md first\n4. **Token budgeting** caps how many files load based on available context window\n\n### The Flow\n\n```\nUser query → --compact --query \"alice\"\n              ↓\n         Manifest generated\n              ↓\n         Load required files (MEMORY.md, recent daily logs)\n              ↓\n         Boost entity-matched files (preferences.md, notes.md)\n              ↓\n         Agent loads only what matters → 70-85% context reduction\n```\n\n## The 4 Engines\n\n### ⚡ Engine 1: Auto-Tier (`--tier`)\n\nWhen MEMORY.md exceeds configurable thresholds (default: 500 lines or 25KB), splits into:\n- **Core file** — Identity, preferences, relationships, projects, patterns, boundaries\n- **Archive files** — Everything else, stored with timestamps in `memory/active/`\n\n**Safety features (v2):**\n- **Pre-tier backup** — Every `--tier` creates a full backup in `memory/backups/` before modifying MEMORY.md\n- **`--dry-run`** — Preview what tiering would do without making changes\n- **`--confirm`** — Required for destructive writes (no auto-tier without explicit confirmation)\n- **Minimum core size** — Aborts if core sections would fall below `minCoreLines`/`minCoreChars` thresholds\n- **`--restore --force`** — Restore MEMORY.md from the latest backup (requires `--force` flag)\n\nSections are classified by header keywords (identity, preferences, etc.) or by content heuristics.\n\n### 📋 Engine 2: Manifest Generator (`--compact`)\n\nCreates `memory/memory-manifest.json` with a file list:\n\n```json\n{\n  \"generated\": \"2026-05-21\",\n  \"files\": [\n    { \"path\": \"MEMORY.md\", \"tier\": \"core\", \"required\": true, \"size\": 50346 },\n    { \"path\": \"memory/2026-05-21.md\", \"tier\": \"recent\", \"required\": true, \"size\": 2034 },\n    { \"path\": \"self-improving/memory.md\", \"tier\": \"domain\", \"required\": false, \"size\": 670 }\n  ]\n}\n```\n\n**Options:**\n| Flag | Description |\n|------|-------------|\n| `--query \"text\"` | Entity-aware boosting — files linked to matching entities get priority |\n| `--budget N` | Token budget — only loads files that fit within N tokens |\n\n### 🔍 Engine 3: Audit Scanner (`--audit`)\n\nScans all memory files for:\n- **High-similarity pairs** — Files with >70% text overlap (potential duplicates)\n- **Revision keywords** — \"revised\", \"updated\", \"changed\", \"no longer\", \"actually\", \"correction\" (facts that may have been superseded)\n\nOutput: `memory/memory-audit-report.md`\n\n### 🏥 Engine 4: Health Monitor (`--status`)\n\nQuick snapshot of MEMORY.md line/char counts, file counts per directory, archive count, manifest status, entity index size, and WAL state.\n\n## Additional Tools\n\n### Entity Index (`--entity`)\n\n| Command | Description |\n|---------|-------------|\n| `--entity add <name> <type> <files...>` | Add entity (e.g., `alice person preferences.md`) |\n| `--entity list` | List all entities |\n| `--entity search <query>` | Search entities (direct and fuzzy match) |\n\n### WAL Protocol (`--wal`)\n\n| Command | Description |\n|---------|-------------|\n| `--wal init` | Initialize SESSION-STATE.md with template |\n| `--wal get` | Show current session state |\n| `--wal update <section> --content \"<text>\"` | Update a section |\n\n## Configuration\n\nEdit `config.json` to customize behavior:\n\n```json\n{\n  \"thresholds\": {\n    \"memoryMdMaxLines\": 500,\n    \"memoryMdMaxChars\": 25000,\n    \"tierArchiveMinAgeDays\": 3,\n    \"auditMaxFiles\": 50\n  },\n  \"tiering\": {\n    \"archiveDir\": \"memory/active\",\n    \"retentionDays\": 90,\n    \"keepInMemory\": [\n      \"identity\", \"preferences\", \"relationships\",\n      \"projects\", \"patterns\", \"boundaries\", \"key_facts\"\n    ]\n  },\n  \"manifest\": {\n    \"generateOnTier\": true,\n    \"manifestPath\": \"memory/memory-manifest.json\"\n  },\n  \"audit\": {\n    \"reportPath\": \"memory/memory-audit-report.md\",\n    \"duplicateThreshold\": 0.7,\n    \"conflictKeywords\": [\n      \"revised\", \"updated\", \"changed\", \"no longer\",\n      \"actually\", \"correction\", \"mistake\"\n    ]\n  }\n}\n```\n\n| Setting | Default | Description |\n|---------|---------|-------------|\n| `memoryMdMaxLines` | 500 | Auto-tier trigger (lines) |\n| `memoryMdMaxChars` | 25000 | Auto-tier trigger (characters) |\n| `tierArchiveMinAgeDays` | 3 | Minimum age before archiving |\n| `retentionDays` | 90 | ⚠️ Archive retention period. Files older than this are candidates for deletion (irreversible). Set to 365+ until confident. |\n| `keepInMemory` | see above | Headers/keywords that stay in core |\n| `generateOnTier` | true | Auto-generate manifest after tiering |\n| `duplicateThreshold` | 0.7 | Similarity score to flag as duplicate |\n| `conflictKeywords` | see above | Words that signal fact revision |\n| `backupDir` | `memory/backups` | Directory for pre-tier backups |\n| `minCoreLines` | 20 | Abort if core sections below this |\n| `minCoreChars` | 1000 | Abort if core chars below this |\n\n## Agent Memory Loading Protocol\n\nWhen the agent wakes up, use the manifest instead of loading all memory files:\n\n1. Read `memory/memory-manifest.json`\n2. Load all `required: true` files\n3. For `required: false` files, use `memory_search` to check relevance\n4. Load only the top 3-5 most relevant optional files\n\n**Result: 70–85% context reduction — load what matters, skip the rest.**\n\n## Heartbeat Integration\n\nAdd to your `HEARTBEAT.md`:\n\n```markdown\n### ⚡ MemoryRouter (SAFE commands only)\n\n- Run `node skills/memory-router/memory-router.js --compact` to update manifest ✅ safe\n- Run `node skills/memory-router/memory-router.js --audit` to check for issues ✅ safe\n- Run `node skills/memory-router/memory-router.js --status` for health overview ✅ safe\n- ⚠️ Do NOT auto-run `--tier` or `--restore` during heartbeats\n- `--tier --dry-run` is side-effect free (no files created)\n- For tiering: run `--tier --dry-run` manually, review output, then `--tier --confirm`\n```\n\n## Performance\n\n| Metric | Result |\n|--------|--------|\n| Tiering speed (8K lines) | 25ms |\n| Tiering speed (15K lines) | 30ms |\n| Token reduction | **96%** (7,809 → 222 lines) |\n| File count reduction | **53 → 15 files** |\n| Memory footprint | ~2MB (Node.js runtime) |\n\n## Comparison\n\n| Approach | Tokens Saved | Setup Effort | Maintenance | Privacy |\n|----------|-------------|-------------|-------------|---------|\n| Raw file injection | 0% | None | Manual | ✅ |\n| **MemoryRouter** | **70–85%** | **None** | **Automated** | **✅** |\n| Obsidian vault | 40–60% | High | Medium | ⚠️ Cloud |\n| Vector DB (ChromaDB) | 70–85% | Very High | High | ✅ |\n| mem0 | 70–85% | High | Medium | ⚠️ Cloud |\n\n**MemoryRouter gives you the best token savings of the vector DB approach with zero setup effort.**\n\n## Entity Naming\n\nPick one canonical name per entity and reuse it consistently:\n\n- Use full descriptive names: \"machine learning\" not \"ML\", \"JavaScript\" not \"JS\"\n- Same string after lowercasing = same entity. Different strings = different entities\n- Call `--entity search` periodically to verify your index\n\nExamples:\n```bash\n# ✅ Good — consistent, descriptive\nnode memory-router.js --entity add alice person preferences.md\nnode memory-router.js --entity add openclaw system AGENTS.md\n\n# ❌ Bad — inconsistent, ambiguous\nnode memory-router.js --entity add alice person preferences.md\nnode memory-router.js --entity add Alice person notes.md\nnode memory-router.js --entity add JS person docs.md\n```\n\n## Manifest Format\n\nThe manifest JSON tells the agent which files to load:\n\n```json\n{\n  \"generated\": \"2026-05-21\",\n  \"version\": 2,\n  \"query\": \"memory management\",\n  \"budget\": 20000,\n  \"files\": [\n    {\n      \"path\": \"MEMORY.md\",\n      \"tier\": \"core\",\n      \"required\": true,\n      \"size\": 50346\n    },\n    {\n      \"path\": \"memory/2026-05-21.md\",\n      \"tier\": \"recent\",\n      \"ageDays\": 0,\n      \"required\": true,\n      \"size\": 2034\n    },\n    {\n      \"path\": \"self-improving/memory.md\",\n      \"tier\": \"domain\",\n      \"required\": false,\n      \"size\": 670\n    }\n  ]\n}\n```\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `tier` | string | `core`, `recent`, `domain`, or `archive` |\n| `required` | bool | Always load this file |\n| `size` | int | File size in bytes |\n| `boosted` | bool | Entity match — higher priority |\n| `entityMatch` | string | Entity name that matched |\n| `load` | bool | Included under budget mode |\n| `budgetUsed` | int | Total tokens loaded (budget mode) |\n| `budgetEfficiency` | string | Percentage remaining (budget mode) |\n\n## Troubleshooting\n\n| Problem | Fix |\n|---------|-----|\n| \"No MEMORY.md found\" | Create one: `echo \"# MEMORY.md\" > MEMORY.md` |\n| \"Memory directory not found\" | Create it: `mkdir -p memory` |\n| Tiering not working | Check thresholds — if under 500 lines and 25KB, nothing happens (by design) |\n| Manifest shows wrong files | Run `--compact` again — it regenerates fresh each time |\n| Entity search returns nothing | Add entities first: `--entity add <name> <type> <files...>` |\n| Budget too small | Core files always load. Budget only controls optional files. |\n\n## ⚠️ SAFETY — READ BEFORE USING\n\n### Destructive Operations\n\n`--tier` and `--restore` **permanently modify user memory files**.\n\n- `--tier` rewrites MEMORY.md, moving sections to archive files\n- `--restore` overwrites MEMORY.md with backup content\n- Both require **explicit confirmation** (`--confirm` / `--force`) — they will refuse to run without it\n- Always run `--tier --dry-run` first to preview what will change\n- Pre-tier backups are created only when actually tiering (not in dry-run mode)\n\n### Archive Retention — Data Loss Risk\n\nThe `retentionDays` config (default: 90) marks archived files as **candidates for deletion** after that period. This is **irreversible** — once deleted, archived memory sections cannot be recovered.\n\n**Before enabling retention:**\n1. Back up your entire `memory/` directory\n2. Set `retentionDays` to a large value (365+) until you're confident\n3. Monitor what gets deleted before reducing the value\n\n### Safe vs Unsafe Commands\n\n| Command | Safe in automation? | Modifies files? |\n|---------|-------------------|------------------|\n| `--compact` | ✅ Yes | Writes `memory-manifest.json` (generated output) |\n| `--audit` | ✅ Yes | Writes `memory-audit-report.md` (generated report) |\n| `--status` | ✅ Yes | No file writes |\n| `--entity add` | ⚠️ Yes — but writes entity index | Yes (persists entity → file mapping) |\n| `--entity list/search` | ✅ Yes | No file writes |\n| `--wal init` | ⚠️ Yes — but creates SESSION-STATE.md | Yes (creates new file) |\n| `--wal get` | ✅ Yes | No file writes |\n| `--wal update` | ⚠️ Yes — but modifies SESSION-STATE.md | Yes (updates session state) |\n| `--tier --dry-run` | ✅ Yes | No file writes (side-effect free) |\n| `--tier --confirm` | ❌ No — rewrites MEMORY.md + creates backup | Yes |\n| `--restore --force` | ❌ No — overwrites MEMORY.md | Yes |\n\n**`--compact`, `--audit`, `--status`, `--entity list/search`, `--wal get`, and `--tier --dry-run` are safe for unattended/heartbeat use.**\n\n**`--entity add`, `--wal init`, and `--wal update` write persistent files — review before automating.**\n\n**`--tier --confirm` and `--restore --force` are destructive — never automate.**\n\n## Security\n\nBuilt with defense-in-depth:\n\n- **Path validation** — rejects file paths outside workspace root\n- **Regex escaping** — prevents injection in WAL section names\n- **Symlink protection** — refuses to read/write symlinks\n- **Size limits** — 10MB max file size\n- **Entity name validation** — alphanumeric + hyphens/underscores only\n- **Content sanitization** — prevents header injection in WAL updates\n- **Audit keyword validation** — rejects regex metacharacters in conflict keywords\n\n## Design Principles\n\n1. **Safe by default** — Destructive operations require explicit flags (`--confirm`, `--force`)\n2. **No external dependencies** — Pure Node.js, no npm packages\n3. **Configurable** — Thresholds, keywords, retention policies\n4. **Transparent** — Generates reports, nothing is silently deleted\n5. **Reversible** — Archives use dated filenames, original content preserved\n6. **Privacy-first** — All local, no cloud APIs\n\nFile v2.4.2:README.md\n\n# MemoryRouter ⚡\n\n**Never lose context. Never forget decisions. Never repeat mistakes.**\n\nThe memory problem is the single biggest reason agents feel dumb over time. Not the models. Not the prompts. **Memory management.**\n\nMemoryRouter fixes it with one tool, zero dependencies, zero setup.\n\n## The Problem — In 30 Seconds\n\nAgent memory files grow unbounded. After a week, you've got thousands of lines across dozens of files. Every session loads **everything** — even when the user asks \"what's the weather?\"\n\nThat's tokens burned on irrelevant memories, every interaction, forever.\n\nThen compaction kicks in and details vanish.\n\n**The bottleneck isn't the model. It's what the model gets to see.**\n\n## Why Memory Fails\n\n| Failure Mode | Cause | Fix |\n|-------------|-------|-----|\n| Forgets everything | Loads irrelevant files, context window fills up | Smart manifest — load only what matters |\n| Repeats mistakes | Lessons not captured or loaded | Entity index + audit for conflicts |\n| Repeats work | No session state persistence | WAL protocol — write state before responding |\n| Slow responses | Loads 50+ files when only 3 matter | Token budgeting — cap context window |\n| Duplicates everywhere | No automated cleanup | `--audit` finds high-similarity pairs |\n\n## The Architecture\n\n```\n┌──────────────────────────────────────────────────────┐\n│              MEMORYROUTER ⚡                          │\n├──────────────────────────────────────────────────────┤\n│                                                      │\n│  ┌──────────────┐    ┌──────────────┐               │\n│  │  AUTO-TIER   │    │  MANIFEST    │               │\n│  │  MEMORY.md   │ →  │  GENERATOR   │               │\n│  │              │    │              │               │\n│  │ Core (always │    │ Required:    │               │\n│  │ loaded)      │    │ MEMORY.md    │               │\n│  │ + Archive    │    │ Recent logs  │               │\n│  │ (on demand)  │    │ Boosted:     │               │\n│  └──────────────┘    │ entity files │               │\n│                      └──────┬───────┘               │\n│                             │                        │\n│              ┌──────────────▼──────────────┐         │\n│              │  ENTITY RESOLUTION          │         │\n│              │  \"alice\" → preferences.md,         │         │\n│              │  notes.md, decisions.md│         │\n│              └──────────────┬──────────────┘         │\n│                             │                        │\n│              ┌──────────────▼──────────────┐         │\n│              │  TOKEN BUDGET FILTER        │         │\n│              │  20K budget → 7 files       │         │\n│              │  100K budget → 16 files     │         │\n│              └──────────────┬──────────────┘         │\n│                             │                        │\n│              ┌──────────────▼──────────────┐         │\n│              │  AGENT LOADS ONLY WHAT      │         │\n│              │  MATTERS → 70-85% REDUCTION │         │\n│              └─────────────────────────────┘         │\n└──────────────────────────────────────────────────────┘\n```\n\n## Quick Start\n\n### ⚠️ Safety First\n\n**Before using `--tier` or `--restore`:**\n\n1. **Back up your memory files** — `cp -r memory/ memory-backup-$(date +%Y%m%d)/`\n2. **Run `--tier --dry-run` first** — review what it will do\n3. **Only then** run `--tier --confirm` if the output looks correct\n\n`--tier` and `--restore` **permanently modify** user memory files. There is no undo.\n\n### Fix a bloated MEMORY.md in one command (requires --confirm)\n\n```bash\nnode skills/memory-router/memory-router.js --tier --confirm\n```\n\n**Output:**\n```\n[memory-router] MEMORY.md: 7809 lines, 309254 chars\n[memory-router] Tiered: 202 core sections, 1002 archived\n[memory-router] MEMORY.md reduced from 7809 lines to 2222 lines\n```\n\n### Generate a smart manifest in one command\n\n```bash\nnode skills/memory-router/memory-router.js --compact\n```\n\nCreates `memory/memory-manifest.json` — the agent's shopping list of what to load.\n\n### With entity boosting\n\n```bash\nnode skills/memory-router/memory-router.js --compact --query \"alice\"\n```\n\nFiles linked to \"alice\" get priority. No AI, no embeddings — just fast entity resolution.\n\n### With a token budget\n\n```bash\nnode skills/memory-router/memory-router.js --compact --budget 20000\n```\n\nOnly loads files that fit within 20K tokens. Tight budgets load core only. Generous budgets load archive on demand.\n\n### Other commands\n\n```bash\nnode skills/memory-router/memory-router.js --audit      # Find duplicates & conflicts\nnode skills/memory-router/memory-router.js --status      # Health overview\nnode skills/memory-router/memory-router.js --entity add alice person preferences.md\n```\n\n## How It Works\n\n### The Core Insight\n\n**Memory management is the bottleneck, not model capability.** Every agent system hits the same wall — context window fills up, everything loads, irrelevant memories dilute the signal.\n\nMemoryRouter takes a **routing** approach rather than a **compression** approach:\n\n1. **Auto-tiering** splits MEMORY.md into core sections (identity, preferences, boundaries — always loaded) and archive sections (everything else, loaded on demand)\n2. **Manifest generation** creates a per-session file list: which files to load, which to skip, which to boost\n3. **Entity-aware boosting** links people, projects, and systems to files — search for \"alice\" → load preferences.md first\n4. **Token budgeting** caps how many files load based on available context window\n\n### The Flow\n\n```\nUser query → --compact --query \"alice\"\n              ↓\n         Manifest generated\n              ↓\n         Load required files (MEMORY.md, recent daily logs)\n              ↓\n         Boost entity-matched files (preferences.md, notes.md)\n              ↓\n         Agent loads only what matters → 70-85% context reduction\n```\n\n## The 4 Engines\n\n### ⚡ Engine 1: Auto-Tier (`--tier`)\n\nWhen MEMORY.md exceeds configurable thresholds (default: 500 lines or 25KB), splits into:\n- **Core file** — Identity, preferences, relationships, projects, patterns, boundaries\n- **Archive files** — Everything else, stored with timestamps in `memory/active/`\n\nSections are classified by header keywords (identity, preferences, etc.) or by content heuristics.\n\n### 📋 Engine 2: Manifest Generator (`--compact`)\n\nCreates `memory/memory-manifest.json` with a file list:\n\n```json\n{\n  \"generated\": \"2026-05-21\",\n  \"files\": [\n    { \"path\": \"MEMORY.md\", \"tier\": \"core\", \"required\": true, \"size\": 50346 },\n    { \"path\": \"memory/2026-05-21.md\", \"tier\": \"recent\", \"required\": true, \"size\": 2034 },\n    { \"path\": \"self-improving/memory.md\", \"tier\": \"domain\", \"required\": false, \"size\": 670 }\n  ]\n}\n```\n\n**Options:**\n| Flag | Description |\n|------|-------------|\n| `--query \"text\"` | Entity-aware boosting — files linked to matching entities get priority |\n| `--budget N` | Token budget — only loads files that fit within N tokens |\n\n### 🔍 Engine 3: Audit Scanner (`--audit`)\n\nScans all memory files for:\n- **High-similarity pairs** — Files with >70% text overlap (potential duplicates)\n- **Revision keywords** — \"revised\", \"updated\", \"changed\", \"no longer\", \"actually\", \"correction\" (facts that may have been superseded)\n\nOutput: `memory/memory-audit-report.md`\n\n### 🏥 Engine 4: Health Monitor (`--status`)\n\nQuick snapshot of MEMORY.md line/char counts, file counts per directory, archive count, manifest status, entity index size, and WAL state.\n\n## Additional Tools\n\n### Entity Index (`--entity`)\n\n| Command | Description |\n|---------|-------------|\n| `--entity add <name> <type> <files...>` | Add entity (e.g., `alice person preferences.md`) |\n| `--entity list` | List all entities |\n| `--entity search <query>` | Search entities (direct and fuzzy match) |\n\n### WAL Protocol (`--wal`)\n\n| Command | Description |\n|---------|-------------|\n| `--wal init` | Initialize SESSION-STATE.md with template |\n| `--wal get` | Show current session state |\n| `--wal update <section> --content \"<text>\"` | Update a section |\n\n## Configuration\n\nEdit `config.json` to customize behavior:\n\n```json\n{\n  \"thresholds\": {\n    \"memoryMdMaxLines\": 500,\n    \"memoryMdMaxChars\": 25000,\n    \"tierArchiveMinAgeDays\": 3,\n    \"auditMaxFiles\": 50\n  },\n  \"tiering\": {\n    \"archiveDir\": \"memory/active\",\n    \"retentionDays\": 90,\n    \"keepInMemory\": [\n      \"identity\", \"preferences\", \"relationships\",\n      \"projects\", \"patterns\", \"boundaries\", \"key_facts\"\n    ]\n  },\n  \"manifest\": {\n    \"generateOnTier\": true,\n    \"manifestPath\": \"memory/memory-manifest.json\"\n  },\n  \"audit\": {\n    \"reportPath\": \"memory/memory-audit-report.md\",\n    \"duplicateThreshold\": 0.7,\n    \"conflictKeywords\": [\n      \"revised\", \"updated\", \"changed\", \"no longer\",\n      \"actually\", \"correction\", \"mistake\"\n    ]\n  }\n}\n```\n\n| Setting | Default | Description |\n|---------|---------|-------------|\n| `memoryMdMaxLines` | 500 | Auto-tier trigger (lines) |\n| `memoryMdMaxChars` | 25000 | Auto-tier trigger (characters) |\n| `tierArchiveMinAgeDays` | 3 | Minimum age before archiving |\n| `retentionDays` | 90 | Archive retention period |\n| `keepInMemory` | see above | Headers/keywords that stay in core |\n| `generateOnTier` | true | Auto-generate manifest after tiering |\n| `duplicateThreshold` | 0.7 | Similarity score to flag as duplicate |\n| `conflictKeywords` | see above | Words that signal fact revision |\n\n## Agent Memory Loading Protocol\n\nWhen the agent wakes up, use the manifest instead of loading all memory files:\n\n1. Read `memory/memory-manifest.json`\n2. Load all `required: true` files\n3. For `required: false` files, use `memory_search` to check relevance\n4. Load only the top 3-5 most relevant optional files\n\n**Result: 70–85% context reduction — load what matters, skip the rest.**\n\n## Heartbeat Integration\n\nAdd to your `HEARTBEAT.md`:\n\n```markdown\n### ⚡ MemoryRouter (SAFE commands only)\n\n- Run `node skills/memory-router/memory-router.js --compact` to update manifest ✅ safe\n- Run `node skills/memory-router/memory-router.js --audit` to check for issues ✅ safe\n- Run `node skills/memory-router/memory-router.js --status` for health overview ✅ safe\n- ⚠️ Do NOT auto-run `--tier --confirm` or `--restore --force` during heartbeats\n- `--tier --dry-run` is side-effect free (no file writes)\n- For tiering: run `--tier --dry-run` manually, review output, then `--tier --confirm`\n```\n\n## Performance\n\n| Metric | Result |\n|--------|--------|\n| Tiering speed (8K lines) | 25ms |\n| Tiering speed (15K lines) | 30ms |\n| Token reduction | **96%** (7,809 → 222 lines) |\n| File count reduction | **53 → 15 files** |\n| Memory footprint | ~2MB (Node.js runtime) |\n\n## Comparison\n\n| Approach | Tokens Saved | Setup Effort | Maintenance | Privacy |\n|----------|-------------|-------------|-------------|---------|\n| Raw file injection | 0% | None | Manual | ✅ |\n| **MemoryRouter** | **70–85%** | **None** | **Automated** | **✅** |\n| Obsidian vault | 40–60% | High | Medium | ⚠️ Cloud |\n| Vector DB (ChromaDB) | 70–85% | Very High | High | ✅ |\n| mem0 | 70–85% | High | Medium | ⚠️ Cloud |\n\n**MemoryRouter gives you the best token savings of the vector DB approach with zero setup effort.**\n\n## Entity Naming\n\nPick one canonical name per entity and reuse it consistently:\n\n- Use full descriptive names: \"machine learning\" not \"ML\", \"JavaScript\" not \"JS\"\n- Same string after lowercasing = same entity. Different strings = different entities\n- Call `--entity search` periodically to verify your index\n\nExamples:\n```bash\n# ✅ Good — consistent, descriptive\nnode memory-router.js --entity add alice person preferences.md\nnode memory-router.js --entity add openclaw system AGENTS.md\n\n# ❌ Bad — inconsistent, ambiguous\nnode memory-router.js --entity add alice person preferences.md\nnode memory-router.js --entity add Alice person notes.md\nnode memory-router.js --entity add JS person docs.md\n```\n\n## Manifest Format\n\nThe manifest JSON tells the agent which files to load:\n\n```json\n{\n  \"generated\": \"2026-05-21\",\n  \"version\": 2,\n  \"query\": \"memory management\",\n  \"budget\": 20000,\n  \"files\": [\n    {\n      \"path\": \"MEMORY.md\",\n      \"tier\": \"core\",\n      \"required\": true,\n      \"size\": 50346\n    },\n    {\n      \"path\": \"memory/2026-05-21.md\",\n      \"tier\": \"recent\",\n      \"ageDays\": 0,\n      \"required\": true,\n      \"size\": 2034\n    },\n    {\n      \"path\": \"self-improving/memory.md\",\n      \"tier\": \"domain\",\n      \"required\": false,\n      \"size\": 670\n    }\n  ]\n}\n```\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `tier` | string | `core`, `recent`, `domain`, or `archive` |\n| `required` | bool | Always load this file |\n| `size` | int | File size in bytes |\n| `boosted` | bool | Entity match — higher priority |\n| `entityMatch` | string | Entity name that matched |\n| `load` | bool | Included under budget mode |\n| `budgetUsed` | int | Total tokens loaded (budget mode) |\n| `budgetEfficiency` | string | Percentage remaining (budget mode) |\n\n## Troubleshooting\n\n| Problem | Fix |\n|---------|-----|\n| \"No MEMORY.md found\" | Create one: `echo \"# MEMORY.md\" > MEMORY.md` |\n| \"Memory directory not found\" | Create it: `mkdir -p memory` |\n| Tiering not working | Check thresholds — if under 500 lines and 25KB, nothing happens (by design) |\n| Manifest shows wrong files | Run `--compact` again — it regenerates fresh each time |\n| Entity search returns nothing | Add entities first: `--entity add <name> <type> <files...>` |\n| Budget too small | Core files always load. Budget only controls optional files. |\n\n## ⚠️ SAFETY — READ BEFORE USING\n\n### Destructive Operations\n\n`--tier` and `--restore` **permanently modify user memory files**.\n\n- `--tier` rewrites MEMORY.md, moving sections to archive files\n- `--restore` overwrites MEMORY.md with backup content\n- Both require **explicit confirmation** (`--confirm` / `--force`) — they will refuse to run without it\n- Always run `--tier --dry-run` first to preview what will change\n- Pre-tier backups are created before any tiering operation\n\n### Archive Retention — Data Loss Risk\n\nThe `retentionDays` config (default: 90) marks archived files as **candidates for deletion** after that period. This is **irreversible** — once deleted, archived memory sections cannot be recovered.\n\n**Note:** This is the one case where files are deleted. All other operations are non-destructive by default. The earlier claim that \"nothing is silently deleted\" applies only to operations that do not have retention enabled.\n\n**Before enabling retention:**\n1. Back up your entire `memory/` directory\n2. Set `retentionDays` to a large value (365+) until you're confident\n3. Monitor what gets deleted before reducing the value\n\n### Safe vs Unsafe Commands\n\n| Command | Safe in automation? | Modifies files? |\n|---------|-------------------|------------------|\n| `--compact` | ✅ Yes | Writes `memory-manifest.json` (generated output) |\n| `--audit` | ✅ Yes | Writes `memory-audit-report.md` (generated report) |\n| `--status` | ✅ Yes | No file writes |\n| `--entity add` | ⚠️ Yes — but writes entity index | Yes (persists entity → file mapping) |\n| `--entity list/search` | ✅ Yes | No file writes |\n| `--wal init` | ⚠️ Yes — but creates SESSION-STATE.md | Yes (creates new file) |\n| `--wal get` | ✅ Yes | No file writes |\n| `--wal update` | ⚠️ Yes — but modifies SESSION-STATE.md | Yes (updates session state) |\n| `--tier --dry-run` | ✅ Yes | No file writes (side-effect free) |\n| `--tier --confirm` | ❌ No — rewrites MEMORY.md + creates backup | Yes |\n| `--restore --force` | ❌ No — overwrites MEMORY.md | Yes |\n\n**`--compact`, `--audit`, `--status`, `--entity list/search`, `--wal get`, and `--tier --dry-run` are safe for unattended/heartbeat use.**\n\n**`--entity add`, `--wal init`, and `--wal update` write persistent files — review before automating.**\n\n**`--tier --confirm` and `--restore --force` are destructive — never automate.**\n\n## Security\n\nBuilt with defense-in-depth:\n\n- **Path validation** — rejects file paths outside workspace root\n- **Regex escaping** — prevents injection in WAL section names\n- **Symlink protection** — refuses to read/write symlinks\n- **Size limits** — 10MB max file size\n- **Entity name validation** — alphanumeric + hyphens/underscores only\n- **Content sanitization** — prevents header injection in WAL updates\n- **Audit keyword validation** — rejects regex metacharacters in conflict keywords\n\n## Design Principles\n\n1. **Safe by default** — Destructive operations require explicit flags (`--confirm`, `--force`)\n2. **No external dependencies** — Pure Node.js, no npm packages\n3. **Configurable** — Thresholds, keywords, retention policies\n4. **Transparent** — Generates reports; however, retention policy (when enabled) deletes archived files after `retentionDays` — this is intentional but irreversible\n5. **Reversible** — Pre-tier backups preserve original MEMORY.md; restored via `--restore --force`\n6. **Privacy-first** — All local, no cloud APIs\n\nFile v2.4.2:_meta.json\n\n{\n  \"ownerId\": \"kn7b6eyf5vc7khg5fr63pjm8xd82qvw5\",\n  \"slug\": \"memory-router\",\n  \"version\": \"2.4.2\",\n  \"publishedAt\": 1784512654195\n}\n\nFile v2.4.2:INSTALL.md\n\n# MemoryRouter — Installation Guide\n\n## Prerequisites\n\n- OpenClaw installed and running\n- Node.js 18+ (built-in `fs` and `path` — no npm packages needed)\n- A `MEMORY.md` file in your workspace (can be empty initially)\n\n## Quick Install (1 minute)\n\n```bash\n# 1. Create the skill directory\nmkdir -p ~/.openclaw/workspace/skills/memory-router\n\n# 2. Copy the skill files\n# Place these files from this package into the directory above:\n#   - memory-router.js   (core engine)\n#   - config.json          (thresholds and options)\n#   - SKILL.md             (skill definition)\n#   - README.md            (this guide)\n\n# 3. Make executable\nchmod +x ~/.openclaw/workspace/skills/memory-router/memory-router.js\n\n# 4. Test it works\nnode ~/.openclaw/workspace/skills/memory-router/memory-router.js --status\n```\n\nExpected output:\n```\n=== MemoryRouter Status ===\n\nMEMORY.md: X lines, Y KB ✅ OK\nmemory/: 0 files, 0.0 KB total\nself-improving/: 0 files\nproactivity/: 0 files\narchives: 0 files\nmanifest: not generated\nentity index: 0 entities\nWAL: not initialized\n```\n\n## Configuration\n\nEdit `config.json` to customize behavior:\n\n```json\n{\n  \"thresholds\": {\n    \"memoryMdMaxLines\": 500,\n    \"memoryMdMaxChars\": 25000,\n    \"tierArchiveMinAgeDays\": 3,\n    \"auditMaxFiles\": 50\n  },\n  \"tiering\": {\n    \"archiveDir\": \"memory/active\",\n    \"retentionDays\": 90,\n    \"keepInMemory\": [\n      \"identity\", \"preferences\", \"relationships\",\n      \"projects\", \"patterns\", \"boundaries\", \"key_facts\"\n    ]\n  },\n  \"manifest\": {\n    \"generateOnTier\": true,\n    \"manifestPath\": \"memory/memory-manifest.json\"\n  },\n  \"audit\": {\n    \"reportPath\": \"memory/memory-audit-report.md\",\n    \"duplicateThreshold\": 0.7,\n    \"conflictKeywords\": [\n      \"revised\", \"updated\", \"changed\", \"no longer\",\n      \"actually\", \"correction\", \"mistake\"\n    ]\n  }\n}\n```\n\n### Key settings explained\n\n| Setting | Default | What it does |\n|---------|---------|-------------|\n| `memoryMdMaxLines` | 500 | Auto-tier triggers when MEMORY.md exceeds this line count |\n| `memoryMdMaxChars` | 25000 | Same, but by character count (whichever threshold is hit first) |\n| `tierArchiveMinAgeDays` | 3 | Sections must be this old before archiving |\n| `retentionDays` | 90 | ⚠️ Archived files older than this are **candidates for deletion**. Irreversible. Set to 365+ until confident. |\n| `keepInMemory` | see above | Headers/keywords that always stay in the core MEMORY.md |\n| `generateOnTier` | true | Auto-generate manifest after tiering |\n| `duplicateThreshold` | 0.7 | Similarity score (>70%) to flag as potential duplicate |\n\n## Heartbeat Integration\n\nAdd this to your `HEARTBEAT.md` under scheduled tasks:\n\n```markdown\n### 🔧 MemoryRouter (SAFE commands only)\n\n- Run `node skills/memory-router/memory-router.js --compact` to update manifest ✅ safe\n- Run `node skills/memory-router/memory-router.js --audit` to check for issues ✅ safe\n- Run `node skills/memory-router/memory-router.js --status` for health overview ✅ safe\n- ⚠️ Do NOT auto-run `--tier` during heartbeats — it permanently rewrites MEMORY.md\n- `--tier --dry-run` is side-effect free (no files created or modified)\n- For tiering: run `--tier --dry-run` manually, review output, then `--tier --confirm`\n- Check `memory/memory-audit-report.md` for any flagged conflicts\n```\n\n**Important:** `--tier` permanently rewrites MEMORY.md. Only run it manually with `--confirm` after reviewing `--dry-run` output.\n\n## Agent Memory Loading Protocol\n\nWhen your agent wakes up, use the manifest instead of loading all memory files:\n\n1. Read `memory/memory-manifest.json`\n2. Load all `required: true` files\n3. For `required: false` files, use `memory_search` to check relevance\n4. Load only the top 3-5 most relevant optional files\n\nThis gives you **70-85% context reduction** — load what matters, skip the rest.\n\n## Commands Reference\n\n| Command | What it does |\n|---------|-------------|\n| `--tier` | Auto-tier MEMORY.md (split core + archive) |\n| `--compact` | Generate per-session manifest |\n| `--compact --query \"text\"` | Query-aware manifest with entity boosting |\n| `--compact --budget N` | Manifest filtered to N tokens |\n| `--audit` | Scan for duplicates/conflicts |\n| `--status` | Show memory health overview |\n| `--entity add <name> <type> <files...>` | Add entity to index |\n| `--entity list` | List all entities |\n| `--entity search <query>` | Search entities |\n| `--wal init` | Initialize WAL (session state) |\n| `--wal get` | Show current WAL state |\n| `--wal update <section> --content \"<text>\"` | Update WAL section |\n\n## Troubleshooting\n\n### \"No MEMORY.md found\"\n\nCreate one:\n```bash\necho \"# MEMORY.md - Long-Term Memory\" > ~/.openclaw/workspace/MEMORY.md\n```\n\n### \"Memory directory not found\"\n\nCreate it:\n```bash\nmkdir -p ~/.openclaw/workspace/memory\n```\n\n### Tiering not working\n\nCheck your thresholds in `config.json`. If MEMORY.md is under 500 lines and 25KB, nothing happens — that's by design.\n\n### Manifest shows wrong file count\n\nRun `--compact` again. The manifest is regenerated fresh each time.\n\n### Entity search returns nothing\n\nAdd entities first:\n```bash\nnode memory-router.js --entity add james person USER.md IDENTITY.md\n```\n\n## Custom Workspace Path\n\nIf you want to use a different workspace:\n\n```bash\nMM_WORKSPACE=/path/to/your/workspace node memory-router.js --status\n```\n\nFile v2.4.2:skill-card.md\n\n## Description: <br>\nMemory Router manages local agent memory by tiering large MEMORY.md files, generating per-session manifests, auditing duplicates, indexing entities, and maintaining session state. <br>\n\nThis skill is ready for commercial/non-commercial use. <br>\n\n## Publisher: <br>\n[jlacroix82](https://clawhub.ai/user/jlacroix82) <br>\n\n### License/Terms of Use: <br>\nMIT-0 <br>\n\n\n## Use Case: <br>\nDevelopers and agent users use this skill to reduce memory-context load, route only relevant memory files into a session, and maintain local memory hygiene without external services. <br>\n\n### Deployment Geography for Use: <br>\nGlobal <br>\n\n## Known Risks and Mitigations: <br>\nRisk: Tiering and restore commands can permanently rewrite local memory files. <br>\nMitigation: Run --tier --dry-run first, keep backups of memory/, and do not automate --tier --confirm or --restore --force. <br>\nRisk: Archive retention can lead to irreversible loss of archived memory sections. <br>\nMitigation: Use a conservative retentionDays value, back up memory/ before enabling retention, and monitor deleted candidates before lowering the retention window. <br>\nRisk: Session-state output may contain sensitive working memory. <br>\nMitigation: Treat --wal get output as sensitive and avoid sharing or logging it outside the trusted workspace. <br>\n\n\n## Reference(s): <br>\n- [ClawHub skill listing](https://clawhub.ai/jlacroix82/skills/memory-router) <br>\n- [README.md](README.md) <br>\n- [INSTALL.md](INSTALL.md) <br>\n\n\n## Skill Output: <br>\n**Output Type(s):** [text, markdown, json, shell commands, configuration, guidance] <br>\n**Output Format:** [CLI text plus generated JSON and Markdown files] <br>\n**Output Parameters:** [1D] <br>\n**Other Properties Related to Output:** [Can write memory/memory-manifest.json, memory/memory-audit-report.md, entity index data, SESSION-STATE.md, backups, and modified MEMORY.md files depending on the command.] <br>\n\n## Skill Version(s): <br>\n2.4.2 (source: server release metadata) <br>\n\n## Ethical Considerations: <br>\nUsers 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. <br>\n\nFile v2.4.2:config.json\n\n{\n  \"thresholds\": {\n    \"memoryMdMaxLines\": 500,\n    \"memoryMdMaxChars\": 25000,\n    \"tierArchiveMinAgeDays\": 3,\n    \"auditMaxFiles\": 50\n  },\n  \"tiering\": {\n    \"archiveDir\": \"memory/active\",\n    \"backupDir\": \"memory/backups\",\n    \"retentionDays\": 90,\n    \"minCoreLines\": 20,\n    \"minCoreChars\": 1000,\n    \"keepInMemory\": [\n      \"identity\",\n      \"preferences\",\n      \"relationships\",\n      \"projects\",\n      \"patterns\",\n      \"boundaries\",\n      \"key_facts\"\n    ]\n  },\n  \"manifest\": {\n    \"generateOnTier\": true,\n    \"manifestPath\": \"memory/memory-manifest.json\"\n  },\n  \"audit\": {\n    \"reportPath\": \"memory/memory-audit-report.md\",\n    \"duplicateThreshold\": 0.7,\n    \"conflictKeywords\": [\"revised\", \"updated\", \"changed\", \"no longer\", \"actually\", \"correction\", \"mistake\"]\n  }\n}\n\nFile v2.4.2:clawhub.yaml\n\nslug: memory-router\nname: Memory Router\nowner: jlacroix82\ndescription: Intelligent memory file management with manifest generation, auditing, entity indexing, and tiering\nversion: 2.4.2\ntype: skill\nauthor: OpenClaw\nlicense: MIT\nkeywords:\n  - memory\n  - indexing\n  - routing\n  - agent\n  - manifest\nentry: SKILL.md\ndependencies: []\n\nArchive v2.4.1: 7 files, 28774 bytes\n\nFiles: _meta.json (132b), config.json (778b), INSTALL.md (5310b), memory-router.js (41394b), README.md (18132b), skill-card.md (2911b), SKILL.md (19145b)\n\nFile v2.4.1:SKILL.md\n\n# MemoryRouter ⚡\n\n**Never lose context. Never forget decisions. Never repeat mistakes.**\n\nThe memory problem is the single biggest reason agents feel dumb over time. Not the models. Not the prompts. **Memory management.**\n\nMemoryRouter fixes it with one tool, zero dependencies, zero setup.\n\n## The Problem — In 30 Seconds\n\nAgent memory files grow unbounded. After a week, you've got thousands of lines across dozens of files. Every session loads **everything** — even when the user asks \"what's the weather?\"\n\nThat's tokens burned on irrelevant memories, every interaction, forever.\n\nThen compaction kicks in and details vanish.\n\n**The bottleneck isn't the model. It's what the model gets to see.**\n\n## Why Memory Fails\n\n| Failure Mode | Cause | Fix |\n|-------------|-------|-----|\n| Forgets everything | Loads irrelevant files, context window fills up | Smart manifest — load only what matters |\n| Repeats mistakes | Lessons not captured or loaded | Entity index + audit for conflicts |\n| Repeats work | No session state persistence | WAL protocol — write state before responding |\n| Slow responses | Loads 50+ files when only 3 matter | Token budgeting — cap context window |\n| Duplicates everywhere | No automated cleanup | `--audit` finds high-similarity pairs |\n\n## The Architecture\n\n```\n┌──────────────────────────────────────────────────────┐\n│              MEMORYROUTER ⚡                          │\n├──────────────────────────────────────────────────────┤\n│                                                      │\n│  ┌──────────────┐    ┌──────────────┐               │\n│  │  AUTO-TIER   │    │  MANIFEST    │               │\n│  │  MEMORY.md   │ →  │  GENERATOR   │               │\n│  │              │    │              │               │\n│  │ Core (always │    │ Required:    │               │\n│  │ loaded)      │    │ MEMORY.md    │               │\n│  │ + Archive    │    │ Recent logs  │               │\n│  │ (on demand)  │    │ Boosted:     │               │\n│  └──────────────┘    │ entity files │               │\n│                      └──────┬───────┘               │\n│                             │                        │\n│              ┌──────────────▼──────────────┐         │\n│              │  ENTITY RESOLUTION          │         │\n│              │  \"alice\" → preferences.md,         │         │\n│              │  notes.md, decisions.md│         │\n│              └──────────────┬──────────────┘         │\n│                             │                        │\n│              ┌──────────────▼──────────────┐         │\n│              │  TOKEN BUDGET FILTER        │         │\n│              │  20K budget → 7 files       │         │\n│              │  100K budget → 16 files     │         │\n│              └──────────────┬──────────────┘         │\n│                             │                        │\n│              ┌──────────────▼──────────────┐         │\n│              │  AGENT LOADS ONLY WHAT      │         │\n│              │  MATTERS → 70-85% REDUCTION │         │\n│              └─────────────────────────────┘         │\n└──────────────────────────────────────────────────────┘\n```\n\n## Quick Start\n\n### Fix a bloated MEMORY.md (requires confirmation)\n\n```bash\nnode skills/memory-router/memory-router.js --tier --confirm\n```\n\n**Output:**\n```\n[memory-router] MEMORY.md: 7809 lines, 309254 chars\n[memory-router] ✅ Pre-tier backup: memory/backups/MEMORY-backup-2026-05-23-1234567890.md (7809 lines saved)\n[memory-router] Tiered: 202 core sections, 1002 archived\n[memory-router] MEMORY.md reduced from 7809 lines to 2222 lines\n```\n\n### Preview tiering without making changes\n\n```bash\nnode skills/memory-router/memory-router.js --tier --dry-run\n```\n\n**Output:**\n```\n[memory-router] MEMORY.md: 7809 lines, 309254 chars\n[memory-router] ── DRY RUN ──\n[memory-router] Would archive: memory/active/MEMORY-archive-2026-05-23.md\n[memory-router] Would reduce MEMORY.md from 7809 lines to ~2222 lines\n[memory-router] Core sections: 202, Archive sections: 1002\n[memory-router] ✅ No files were modified.\n```\n\n### Restore MEMORY.md from latest backup\n\n```bash\nnode skills/memory-router/memory-router.js --restore --force\n```\n\n⚠️ **Destructive** — overwrites MEMORY.md. Requires `--force` flag. Extracts only the original content from the backup (metadata headers are stripped). Always creates a backup of the current MEMORY.md before overwriting.\n\n### Generate a smart manifest in one command\n\n```bash\nnode skills/memory-router/memory-router.js --compact\n```\n\nCreates `memory/memory-manifest.json` — the agent's shopping list of what to load.\n\n### With entity boosting\n\n```bash\nnode skills/memory-router/memory-router.js --compact --query \"alice\"\n```\n\nFiles linked to \"alice\" get priority. No AI, no embeddings — just fast entity resolution.\n\n### With a token budget\n\n```bash\nnode skills/memory-router/memory-router.js --compact --budget 20000\n```\n\nOnly loads files that fit within 20K tokens. Tight budgets load core only. Generous budgets load archive on demand.\n\n### Other commands\n\n```bash\nnode skills/memory-router/memory-router.js --audit      # Find duplicates & conflicts\nnode skills/memory-router/memory-router.js --status      # Health overview\nnode skills/memory-router/memory-router.js --entity add alice person preferences.md\n```\n\n## How It Works\n\n### The Core Insight\n\n**Memory management is the bottleneck, not model capability.** Every agent system hits the same wall — context window fills up, everything loads, irrelevant memories dilute the signal.\n\nMemoryRouter takes a **routing** approach rather than a **compression** approach:\n\n1. **Auto-tiering** splits MEMORY.md into core sections (identity, preferences, boundaries — always loaded) and archive sections (everything else, loaded on demand)\n2. **Manifest generation** creates a per-session file list: which files to load, which to skip, which to boost\n3. **Entity-aware boosting** links people, projects, and systems to files — search for \"alice\" → load preferences.md first\n4. **Token budgeting** caps how many files load based on available context window\n\n### The Flow\n\n```\nUser query → --compact --query \"alice\"\n              ↓\n         Manifest generated\n              ↓\n         Load required files (MEMORY.md, recent daily logs)\n              ↓\n         Boost entity-matched files (preferences.md, notes.md)\n              ↓\n         Agent loads only what matters → 70-85% context reduction\n```\n\n## The 4 Engines\n\n### ⚡ Engine 1: Auto-Tier (`--tier`)\n\nWhen MEMORY.md exceeds configurable thresholds (default: 500 lines or 25KB), splits into:\n- **Core file** — Identity, preferences, relationships, projects, patterns, boundaries\n- **Archive files** — Everything else, stored with timestamps in `memory/active/`\n\n**Safety features (v2):**\n- **Pre-tier backup** — Every `--tier` creates a full backup in `memory/backups/` before modifying MEMORY.md\n- **`--dry-run`** — Preview what tiering would do without making changes\n- **`--confirm`** — Required for destructive writes (no auto-tier without explicit confirmation)\n- **Minimum core size** — Aborts if core sections would fall below `minCoreLines`/`minCoreChars` thresholds\n- **`--restore --force`** — Restore MEMORY.md from the latest backup (requires `--force` flag)\n\nSections are classified by header keywords (identity, preferences, etc.) or by content heuristics.\n\n### 📋 Engine 2: Manifest Generator (`--compact`)\n\nCreates `memory/memory-manifest.json` with a file list:\n\n```json\n{\n  \"generated\": \"2026-05-21\",\n  \"files\": [\n    { \"path\": \"MEMORY.md\", \"tier\": \"core\", \"required\": true, \"size\": 50346 },\n    { \"path\": \"memory/2026-05-21.md\", \"tier\": \"recent\", \"required\": true, \"size\": 2034 },\n    { \"path\": \"self-improving/memory.md\", \"tier\": \"domain\", \"required\": false, \"size\": 670 }\n  ]\n}\n```\n\n**Options:**\n| Flag | Description |\n|------|-------------|\n| `--query \"text\"` | Entity-aware boosting — files linked to matching entities get priority |\n| `--budget N` | Token budget — only loads files that fit within N tokens |\n\n### 🔍 Engine 3: Audit Scanner (`--audit`)\n\nScans all memory files for:\n- **High-similarity pairs** — Files with >70% text overlap (potential duplicates)\n- **Revision keywords** — \"revised\", \"updated\", \"changed\", \"no longer\", \"actually\", \"correction\" (facts that may have been superseded)\n\nOutput: `memory/memory-audit-report.md`\n\n### 🏥 Engine 4: Health Monitor (`--status`)\n\nQuick snapshot of MEMORY.md line/char counts, file counts per directory, archive count, manifest status, entity index size, and WAL state.\n\n## Additional Tools\n\n### Entity Index (`--entity`)\n\n| Command | Description |\n|---------|-------------|\n| `--entity add <name> <type> <files...>` | Add entity (e.g., `alice person preferences.md`) |\n| `--entity list` | List all entities |\n| `--entity search <query>` | Search entities (direct and fuzzy match) |\n\n### WAL Protocol (`--wal`)\n\n| Command | Description |\n|---------|-------------|\n| `--wal init` | Initialize SESSION-STATE.md with template |\n| `--wal get` | Show current session state |\n| `--wal update <section> --content \"<text>\"` | Update a section |\n\n## Configuration\n\nEdit `config.json` to customize behavior:\n\n```json\n{\n  \"thresholds\": {\n    \"memoryMdMaxLines\": 500,\n    \"memoryMdMaxChars\": 25000,\n    \"tierArchiveMinAgeDays\": 3,\n    \"auditMaxFiles\": 50\n  },\n  \"tiering\": {\n    \"archiveDir\": \"memory/active\",\n    \"retentionDays\": 90,\n    \"keepInMemory\": [\n      \"identity\", \"preferences\", \"relationships\",\n      \"projects\", \"patterns\", \"boundaries\", \"key_facts\"\n    ]\n  },\n  \"manifest\": {\n    \"generateOnTier\": true,\n    \"manifestPath\": \"memory/memory-manifest.json\"\n  },\n  \"audit\": {\n    \"reportPath\": \"memory/memory-audit-report.md\",\n    \"duplicateThreshold\": 0.7,\n    \"conflictKeywords\": [\n      \"revised\", \"updated\", \"changed\", \"no longer\",\n      \"actually\", \"correction\", \"mistake\"\n    ]\n  }\n}\n```\n\n| Setting | Default | Description |\n|---------|---------|-------------|\n| `memoryMdMaxLines` | 500 | Auto-tier trigger (lines) |\n| `memoryMdMaxChars` | 25000 | Auto-tier trigger (characters) |\n| `tierArchiveMinAgeDays` | 3 | Minimum age before archiving |\n| `retentionDays` | 90 | ⚠️ Archive retention period. Files older than this are candidates for deletion (irreversible). Set to 365+ until confident. |\n| `keepInMemory` | see above | Headers/keywords that stay in core |\n| `generateOnTier` | true | Auto-generate manifest after tiering |\n| `duplicateThreshold` | 0.7 | Similarity score to flag as duplicate |\n| `conflictKeywords` | see above | Words that signal fact revision |\n| `backupDir` | `memory/backups` | Directory for pre-tier backups |\n| `minCoreLines` | 20 | Abort if core sections below this |\n| `minCoreChars` | 1000 | Abort if core chars below this |\n\n## Agent Memory Loading Protocol\n\nWhen the agent wakes up, use the manifest instead of loading all memory files:\n\n1. Read `memory/memory-manifest.json`\n2. Load all `required: true` files\n3. For `required: false` files, use `memory_search` to check relevance\n4. Load only the top 3-5 most relevant optional files\n\n**Result: 70–85% context reduction — load what matters, skip the rest.**\n\n## Heartbeat Integration\n\nAdd to your `HEARTBEAT.md`:\n\n```markdown\n### ⚡ MemoryRouter (SAFE commands only)\n\n- Run `node skills/memory-router/memory-router.js --compact` to update manifest ✅ safe\n- Run `node skills/memory-router/memory-router.js --audit` to check for issues ✅ safe\n- Run `node skills/memory-router/memory-router.js --status` for health overview ✅ safe\n- ⚠️ Do NOT auto-run `--tier` or `--restore` during heartbeats\n- `--tier --dry-run` is side-effect free (no files created)\n- For tiering: run `--tier --dry-run` manually, review output, then `--tier --confirm`\n```\n\n## Performance\n\n| Metric | Result |\n|--------|--------|\n| Tiering speed (8K lines) | 25ms |\n| Tiering speed (15K lines) | 30ms |\n| Token reduction | **96%** (7,809 → 222 lines) |\n| File count reduction | **53 → 15 files** |\n| Memory footprint | ~2MB (Node.js runtime) |\n\n## Comparison\n\n| Approach | Tokens Saved | Setup Effort | Maintenance | Privacy |\n|----------|-------------|-------------|-------------|---------|\n| Raw file injection | 0% | None | Manual | ✅ |\n| **MemoryRouter** | **70–85%** | **None** | **Automated** | **✅** |\n| Obsidian vault | 40–60% | High | Medium | ⚠️ Cloud |\n| Vector DB (ChromaDB) | 70–85% | Very High | High | ✅ |\n| mem0 | 70–85% | High | Medium | ⚠️ Cloud |\n\n**MemoryRouter gives you the best token savings of the vector DB approach with zero setup effort.**\n\n## Entity Naming\n\nPick one canonical name per entity and reuse it consistently:\n\n- Use full descriptive names: \"machine learning\" not \"ML\", \"JavaScript\" not \"JS\"\n- Same string after lowercasing = same entity. Different strings = different entities\n- Call `--entity search` periodically to verify your index\n\nExamples:\n```bash\n# ✅ Good — consistent, descriptive\nnode memory-router.js --entity add alice person preferences.md\nnode memory-router.js --entity add openclaw system AGENTS.md\n\n# ❌ Bad — inconsistent, ambiguous\nnode memory-router.js --entity add alice person preferences.md\nnode memory-router.js --entity add Alice person notes.md\nnode memory-router.js --entity add JS person docs.md\n```\n\n## Manifest Format\n\nThe manifest JSON tells the agent which files to load:\n\n```json\n{\n  \"generated\": \"2026-05-21\",\n  \"version\": 2,\n  \"query\": \"memory management\",\n  \"budget\": 20000,\n  \"files\": [\n    {\n      \"path\": \"MEMORY.md\",\n      \"tier\": \"core\",\n      \"required\": true,\n      \"size\": 50346\n    },\n    {\n      \"path\": \"memory/2026-05-21.md\",\n      \"tier\": \"recent\",\n      \"ageDays\": 0,\n      \"required\": true,\n      \"size\": 2034\n    },\n    {\n      \"path\": \"self-improving/memory.md\",\n      \"tier\": \"domain\",\n      \"required\": false,\n      \"size\": 670\n    }\n  ]\n}\n```\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `tier` | string | `core`, `recent`, `domain`, or `archive` |\n| `required` | bool | Always load this file |\n| `size` | int | File size in bytes |\n| `boosted` | bool | Entity match — higher priority |\n| `entityMatch` | string | Entity name that matched |\n| `load` | bool | Included under budget mode |\n| `budgetUsed` | int | Total tokens loaded (budget mode) |\n| `budgetEfficiency` | string | Percentage remaining (budget mode) |\n\n## Troubleshooting\n\n| Problem | Fix |\n|---------|-----|\n| \"No MEMORY.md found\" | Create one: `echo \"# MEMORY.md\" > MEMORY.md` |\n| \"Memory directory not found\" | Create it: `mkdir -p memory` |\n| Tiering not working | Check thresholds — if under 500 lines and 25KB, nothing happens (by design) |\n| Manifest shows wrong files | Run `--compact` again — it regenerates fresh each time |\n| Entity search returns nothing | Add entities first: `--entity add <name> <type> <files...>` |\n| Budget too small | Core files always load. Budget only controls optional files. |\n\n## ⚠️ SAFETY — READ BEFORE USING\n\n### Destructive Operations\n\n`--tier` and `--restore` **permanently modify user memory files**.\n\n- `--tier` rewrites MEMORY.md, moving sections to archive files\n- `--restore` overwrites MEMORY.md with backup content\n- Both require **explicit confirmation** (`--confirm` / `--force`) — they will refuse to run without it\n- Always run `--tier --dry-run` first to preview what will change\n- Pre-tier backups are created only when actually tiering (not in dry-run mode)\n\n### Archive Retention — Data Loss Risk\n\nThe `retentionDays` config (default: 90) marks archived files as **candidates for deletion** after that period. This is **irreversible** — once deleted, archived memory sections cannot be recovered.\n\n**Before enabling retention:**\n1. Back up your entire `memory/` directory\n2. Set `retentionDays` to a large value (365+) until you're confident\n3. Monitor what gets deleted before reducing the value\n\n### Safe vs Unsafe Commands\n\n| Command | Safe in automation? | Modifies files? |\n|---------|-------------------|------------------|\n| `--compact` | ✅ Yes | Writes `memory-manifest.json` (generated output) |\n| `--audit` | ✅ Yes | Writes `memory-audit-report.md` (generated report) |\n| `--status` | ✅ Yes | No file writes |\n| `--entity add` | ⚠️ Yes — but writes entity index | Yes (persists entity → file mapping) |\n| `--entity list/search` | ✅ Yes | No file writes |\n| `--wal init` | ⚠️ Yes — but creates SESSION-STATE.md | Yes (creates new file) |\n| `--wal get` | ✅ Yes | No file writes |\n| `--wal update` | ⚠️ Yes — but modifies SESSION-STATE.md | Yes (updates session state) |\n| `--tier --dry-run` | ✅ Yes | No file writes (side-effect free) |\n| `--tier --confirm` | ❌ No — rewrites MEMORY.md + creates backup | Yes |\n| `--restore --force` | ❌ No — overwrites MEMORY.md | Yes |\n\n**`--compact`, `--audit`, `--status`, `--entity list/search`, `--wal get`, and `--tier --dry-run` are safe for unattended/heartbeat use.**\n\n**`--entity add`, `--wal init`, and `--wal update` write persistent files — review before automating.**\n\n**`--tier --confirm` and `--restore --force` are destructive — never automate.**\n\n## Security\n\nBuilt with defense-in-depth:\n\n- **Path validation** — rejects file paths outside workspace root\n- **Regex escaping** — prevents injection in WAL section names\n- **Symlink protection** — refuses to read/write symlinks\n- **Size limits** — 10MB max file size\n- **Entity name validation** — alphanumeric + hyphens/underscores only\n- **Content sanitization** — prevents header injection in WAL updates\n- **Audit keyword validation** — rejects regex metacharacters in conflict keywords\n\n## Design Principles\n\n1. **Safe by default** — Destructive operations require explicit flags (`--confirm`, `--force`)\n2. **No external dependencies** — Pure Node.js, no npm packages\n3. **Configurable** — Thresholds, keywords, retention policies\n4. **Transparent** — Generates reports, nothing is silently deleted\n5. **Reversible** — Archives use dated filenames, original content preserved\n6. **Privacy-first** — All local, no cloud APIs\n\nFile v2.4.1:README.md\n\n# MemoryRouter ⚡\n\n**Never lose context. Never forget decisions. Never repeat mistakes.**\n\nThe memory problem is the single biggest reason agents feel dumb over time. Not the models. Not the prompts. **Memory management.**\n\nMemoryRouter fixes it with one tool, zero dependencies, zero setup.\n\n## The Problem — In 30 Seconds\n\nAgent memory files grow unbounded. After a week, you've got thousands of lines across dozens of files. Every session loads **everything** — even when the user asks \"what's the weather?\"\n\nThat's tokens burned on irrelevant memories, every interaction, forever.\n\nThen compaction kicks in and details vanish.\n\n**The bottleneck isn't the model. It's what the model gets to see.**\n\n## Why Memory Fails\n\n| Failure Mode | Cause | Fix |\n|-------------|-------|-----|\n| Forgets everything | Loads irrelevant files, context window fills up | Smart manifest — load only what matters |\n| Repeats mistakes | Lessons not captured or loaded | Entity index + audit for conflicts |\n| Repeats work | No session state persistence | WAL protocol — write state before responding |\n| Slow responses | Loads 50+ files when only 3 matter | Token budgeting — cap context window |\n| Duplicates everywhere | No automated cleanup | `--audit` finds high-similarity pairs |\n\n## The Architecture\n\n```\n┌──────────────────────────────────────────────────────┐\n│              MEMORYROUTER ⚡                          │\n├──────────────────────────────────────────────────────┤\n│                                                      │\n│  ┌──────────────┐    ┌──────────────┐               │\n│  │  AUTO-TIER   │    │  MANIFEST    │               │\n│  │  MEMORY.md   │ →  │  GENERATOR   │               │\n│  │              │    │              │               │\n│  │ Core (always │    │ Required:    │               │\n│  │ loaded)      │    │ MEMORY.md    │               │\n│  │ + Archive    │    │ Recent logs  │               │\n│  │ (on demand)  │    │ Boosted:     │               │\n│  └──────────────┘    │ entity files │               │\n│                      └──────┬───────┘               │\n│                             │                        │\n│              ┌──────────────▼──────────────┐         │\n│              │  ENTITY RESOLUTION          │         │\n│              │  \"alice\" → preferences.md,         │         │\n│              │  notes.md, decisions.md│         │\n│              └──────────────┬──────────────┘         │\n│                             │                        │\n│              ┌──────────────▼──────────────┐         │\n│              │  TOKEN BUDGET FILTER        │         │\n│              │  20K budget → 7 files       │         │\n│              │  100K budget → 16 files     │         │\n│              └──────────────┬──────────────┘         │\n│                             │                        │\n│              ┌──────────────▼──────────────┐         │\n│              │  AGENT LOADS ONLY WHAT      │         │\n│              │  MATTERS → 70-85% REDUCTION │         │\n│              └─────────────────────────────┘         │\n└──────────────────────────────────────────────────────┘\n```\n\n## Quick Start\n\n### ⚠️ Safety First\n\n**Before using `--tier` or `--restore`:**\n\n1. **Back up your memory files** — `cp -r memory/ memory-backup-$(date +%Y%m%d)/`\n2. **Run `--tier --dry-run` first** — review what it will do\n3. **Only then** run `--tier --confirm` if the output looks correct\n\n`--tier` and `--restore` **permanently modify** user memory files. There is no undo.\n\n### Fix a bloated MEMORY.md in one command (requires --confirm)\n\n```bash\nnode skills/memory-router/memory-router.js --tier --confirm\n```\n\n**Output:**\n```\n[memory-router] MEMORY.md: 7809 lines, 309254 chars\n[memory-router] Tiered: 202 core sections, 1002 archived\n[memory-router] MEMORY.md reduced from 7809 lines to 2222 lines\n```\n\n### Generate a smart manifest in one command\n\n```bash\nnode skills/memory-router/memory-router.js --compact\n```\n\nCreates `memory/memory-manifest.json` — the agent's shopping list of what to load.\n\n### With entity boosting\n\n```bash\nnode skills/memory-router/memory-router.js --compact --query \"alice\"\n```\n\nFiles linked to \"alice\" get priority. No AI, no embeddings — just fast entity resolution.\n\n### With a token budget\n\n```bash\nnode skills/memory-router/memory-router.js --compact --budget 20000\n```\n\nOnly loads files that fit within 20K tokens. Tight budgets load core only. Generous budgets load archive on demand.\n\n### Other commands\n\n```bash\nnode skills/memory-router/memory-router.js --audit      # Find duplicates & conflicts\nnode skills/memory-router/memory-router.js --status      # Health overview\nnode skills/memory-router/memory-router.js --entity add alice person preferences.md\n```\n\n## How It Works\n\n### The Core Insight\n\n**Memory management is the bottleneck, not model capability.** Every agent system hits the same wall — context window fills up, everything loads, irrelevant memories dilute the signal.\n\nMemoryRouter takes a **routing** approach rather than a **compression** approach:\n\n1. **Auto-tiering** splits MEMORY.md into core sections (identity, preferences, boundaries — always loaded) and archive sections (everything else, loaded on demand)\n2. **Manifest generation** creates a per-session file list: which files to load, which to skip, which to boost\n3. **Entity-aware boosting** links people, projects, and systems to files — search for \"alice\" → load preferences.md first\n4. **Token budgeting** caps how many files load based on available context window\n\n### The Flow\n\n```\nUser query → --compact --query \"alice\"\n              ↓\n         Manifest generated\n              ↓\n         Load required files (MEMORY.md, recent daily logs)\n              ↓\n         Boost entity-matched files (preferences.md, notes.md)\n              ↓\n         Agent loads only what matters → 70-85% context reduction\n```\n\n## The 4 Engines\n\n### ⚡ Engine 1: Auto-Tier (`--tier`)\n\nWhen MEMORY.md exceeds configurable thresholds (default: 500 lines or 25KB), splits into:\n- **Core file** — Identity, preferences, relationships, projects, patterns, boundaries\n- **Archive files** — Everything else, stored with timestamps in `memory/active/`\n\nSections are classified by header keywords (identity, preferences, etc.) or by content heuristics.\n\n### 📋 Engine 2: Manifest Generator (`--compact`)\n\nCreates `memory/memory-manifest.json` with a file list:\n\n```json\n{\n  \"generated\": \"2026-05-21\",\n  \"files\": [\n    { \"path\": \"MEMORY.md\", \"tier\": \"core\", \"required\": true, \"size\": 50346 },\n    { \"path\": \"memory/2026-05-21.md\", \"tier\": \"recent\", \"required\": true, \"size\": 2034 },\n    { \"path\": \"self-improving/memory.md\", \"tier\": \"domain\", \"required\": false, \"size\": 670 }\n  ]\n}\n```\n\n**Options:**\n| Flag | Description |\n|------|-------------|\n| `--query \"text\"` | Entity-aware boosting — files linked to matching entities get priority |\n| `--budget N` | Token budget — only loads files that fit within N tokens |\n\n### 🔍 Engine 3: Audit Scanner (`--audit`)\n\nScans all memory files for:\n- **High-similarity pairs** — Files with >70% text overlap (potential duplicates)\n- **Revision keywords** — \"revised\", \"updated\", \"changed\", \"no longer\", \"actually\", \"correction\" (facts that may have been superseded)\n\nOutput: `memory/memory-audit-report.md`\n\n### 🏥 Engine 4: Health Monitor (`--status`)\n\nQuick snapshot of MEMORY.md line/char counts, file counts per directory, archive count, manifest status, entity index size, and WAL state.\n\n## Additional Tools\n\n### Entity Index (`--entity`)\n\n| Command | Description |\n|---------|-------------|\n| `--entity add <name> <type> <files...>` | Add entity (e.g., `alice person preferences.md`) |\n| `--entity list` | List all entities |\n| `--entity search <query>` | Search entities (direct and fuzzy match) |\n\n### WAL Protocol (`--wal`)\n\n| Command | Description |\n|---------|-------------|\n| `--wal init` | Initialize SESSION-STATE.md with template |\n| `--wal get` | Show current session state |\n| `--wal update <section> --content \"<text>\"` | Update a section |\n\n## Configuration\n\nEdit `config.json` to customize behavior:\n\n```json\n{\n  \"thresholds\": {\n    \"memoryMdMaxLines\": 500,\n    \"memoryMdMaxChars\": 25000,\n    \"tierArchiveMinAgeDays\": 3,\n    \"auditMaxFiles\": 50\n  },\n  \"tiering\": {\n    \"archiveDir\": \"memory/active\",\n    \"retentionDays\": 90,\n    \"keepInMemory\": [\n      \"identity\", \"preferences\", \"relationships\",\n      \"projects\", \"patterns\", \"boundaries\", \"key_facts\"\n    ]\n  },\n  \"manifest\": {\n    \"generateOnTier\": true,\n    \"manifestPath\": \"memory/memory-manifest.json\"\n  },\n  \"audit\": {\n    \"reportPath\": \"memory/memory-audit-report.md\",\n    \"duplicateThreshold\": 0.7,\n    \"conflictKeywords\": [\n      \"revised\", \"updated\", \"changed\", \"no longer\",\n      \"actually\", \"correction\", \"mistake\"\n    ]\n  }\n}\n```\n\n| Setting | Default | Description |\n|---------|---------|-------------|\n| `memoryMdMaxLines` | 500 | Auto-tier trigger (lines) |\n| `memoryMdMaxChars` | 25000 | Auto-tier trigger (characters) |\n| `tierArchiveMinAgeDays` | 3 | Minimum age before archiving |\n| `retentionDays` | 90 | Archive retention period |\n| `keepInMemory` | see above | Headers/keywords that stay in core |\n| `generateOnTier` | true | Auto-generate manifest after tiering |\n| `duplicateThreshold` | 0.7 | Similarity score to flag as duplicate |\n| `conflictKeywords` | see above | Words that signal fact revision |\n\n## Agent Memory Loading Protocol\n\nWhen the agent wakes up, use the manifest instead of loading all memory files:\n\n1. Read `memory/memory-manifest.json`\n2. Load all `required: true` files\n3. For `required: false` files, use `memory_search` to check relevance\n4. Load only the top 3-5 most relevant optional files\n\n**Result: 70–85% context reduction — load what matters, skip the rest.**\n\n## Heartbeat Integration\n\nAdd to your `HEARTBEAT.md`:\n\n```markdown\n### ⚡ MemoryRouter (SAFE commands only)\n\n- Run `node skills/memory-router/memory-router.js --compact` to update manifest ✅ safe\n- Run `node skills/memory-router/memory-router.js --audit` to check for issues ✅ safe\n- Run `node skills/memory-router/memory-router.js --status` for health overview ✅ safe\n- ⚠️ Do NOT auto-run `--tier --confirm` or `--restore --force` during heartbeats\n- `--tier --dry-run` is side-effect free (no file writes)\n- For tiering: run `--tier --dry-run` manually, review output, then `--tier --confirm`\n```\n\n## Performance\n\n| Metric | Result |\n|--------|--------|\n| Tiering speed (8K lines) | 25ms |\n| Tiering speed (15K lines) | 30ms |\n| Token reduction | **96%** (7,809 → 222 lines) |\n| File count reduction | **53 → 15 files** |\n| Memory footprint | ~2MB (Node.js runtime) |\n\n## Comparison\n\n| Approach | Tokens Saved | Setup Effort | Maintenance | Privacy |\n|----------|-------------|-------------|-------------|---------|\n| Raw file injection | 0% | None | Manual | ✅ |\n| **MemoryRouter** | **70–85%** | **None** | **Automated** | **✅** |\n| Obsidian vault | 40–60% | High | Medium | ⚠️ Cloud |\n| Vector DB (ChromaDB) | 70–85% | Very High | High | ✅ |\n| mem0 | 70–85% | High | Medium | ⚠️ Cloud |\n\n**MemoryRouter gives you the best token savings of the vector DB approach with zero setup effort.**\n\n## Entity Naming\n\nPick one canonical name per entity and reuse it consistently:\n\n- Use full descriptive names: \"machine learning\" not \"ML\", \"JavaScript\" not \"JS\"\n- Same string after lowercasing = same entity. Different strings = different entities\n- Call `--entity search` periodically to verify your index\n\nExamples:\n```bash\n# ✅ Good — consistent, descriptive\nnode memory-router.js --entity add alice person preferences.md\nnode memory-router.js --entity add openclaw system AGENTS.md\n\n# ❌ Bad — inconsistent, ambiguous\nnode memory-router.js --entity add alice person preferences.md\nnode memory-router.js --entity add Alice person notes.md\nnode memory-router.js --entity add JS person docs.md\n```\n\n## Manifest Format\n\nThe manifest JSON tells the agent which files to load:\n\n```json\n{\n  \"generated\": \"2026-05-21\",\n  \"version\": 2,\n  \"query\": \"memory management\",\n  \"budget\": 20000,\n  \"files\": [\n    {\n      \"path\": \"MEMORY.md\",\n      \"tier\": \"core\",\n      \"required\": true,\n      \"size\": 50346\n    },\n    {\n      \"path\": \"memory/2026-05-21.md\",\n      \"tier\": \"recent\",\n      \"ageDays\": 0,\n      \"required\": true,\n      \"size\": 2034\n    },\n    {\n      \"path\": \"self-improving/memory.md\",\n      \"tier\": \"domain\",\n      \"required\": false,\n      \"size\": 670\n    }\n  ]\n}\n```\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `tier` | string | `core`, `recent`, `domain`, or `archive` |\n| `required` | bool | Always load this file |\n| `size` | int | File size in bytes |\n| `boosted` | bool | Entity match — higher priority |\n| `entityMatch` | string | Entity name that matched |\n| `load` | bool | Included under budget mode |\n| `budgetUsed` | int | Total tokens loaded (budget mode) |\n| `budgetEfficiency` | string | Percentage remaining (budget mode) |\n\n## Troubleshooting\n\n| Problem | Fix |\n|---------|-----|\n| \"No MEMORY.md found\" | Create one: `echo \"# MEMORY.md\" > MEMORY.md` |\n| \"Memory directory not found\" | Create it: `mkdir -p memory` |\n| Tiering not working | Check thresholds — if under 500 lines and 25KB, nothing happens (by design) |\n| Manifest shows wrong files | Run `--compact` again — it regenerates fresh each time |\n| Entity search returns nothing | Add entities first: `--entity add <name> <type> <files...>` |\n| Budget too small | Core files always load. Budget only controls optional files. |\n\n## ⚠️ SAFETY — READ BEFORE USING\n\n### Destructive Operations\n\n`--tier` and `--restore` **permanently modify user memory files**.\n\n- `--tier` rewrites MEMORY.md, moving sections to archive files\n- `--restore` overwrites MEMORY.md with backup content\n- Both require **explicit confirmation** (`--confirm` / `--force`) — they will refuse to run without it\n- Always run `--tier --dry-run` first to preview what will change\n- Pre-tier backups are created before any tiering operation\n\n### Archive Retention — Data Loss Risk\n\nThe `retentionDays` config (default: 90) marks archived files as **candidates for deletion** after that period. This is **irreversible** — once deleted, archived memory sections cannot be recovered.\n\n**Note:** This is the one case where files are deleted. All other operations are non-destructive by default. The earlier claim that \"nothing is silently deleted\" applies only to operations that do not have retention enabled.\n\n**Before enabling retention:**\n1. Back up your entire `memory/` directory\n2. Set `retentionDays` to a large value (365+) until you're confident\n3. Monitor what gets deleted before reducing the value\n\n### Safe vs Unsafe Commands\n\n| Command | Safe in automation? | Modifies files? |\n|---------|-------------------|------------------|\n| `--compact` | ✅ Yes | Writes `memory-manifest.json` (generated output) |\n| `--audit` | ✅ Yes | Writes `memory-audit-report.md` (generated report) |\n| `--status` | ✅ Yes | No file writes |\n| `--entity add` | ⚠️ Yes — but writes entity index | Yes (persists entity → file mapping) |\n| `--entity list/search` | ✅ Yes | No file writes |\n| `--wal init` | ⚠️ Yes — but creates SESSION-STATE.md | Yes (creates new file) |\n| `--wal get` | ✅ Yes | No file writes |\n| `--wal update` | ⚠️ Yes — but modifies SESSION-STATE.md | Yes (updates session state) |\n| `--tier --dry-run` | ✅ Yes | No file writes (side-effect free) |\n| `--tier --confirm` | ❌ No — rewrites MEMORY.md + creates backup | Yes |\n| `--restore --force` | ❌ No — overwrites MEMORY.md | Yes |\n\n**`--compact`, `--audit`, `--status`, `--entity list/search`, `--wal get`, and `--tier --dry-run` are safe for unattended/heartbeat use.**\n\n**`--entity add`, `--wal init`, and `--wal update` write persistent files — review before automating.**\n\n**`--tier --confirm` and `--restore --force` are destructive — never automate.**\n\n## Security\n\nBuilt with defense-in-depth:\n\n- **Path validation** — rejects file paths outside workspace root\n- **Regex escaping** — prevents injection in WAL section names\n- **Symlink protection** — refuses to read/write symlinks\n- **Size limits** — 10MB max file size\n- **Entity name validation** — alphanumeric + hyphens/underscores only\n- **Content sanitization** — prevents header injection in WAL updates\n- **Audit keyword validation** — rejects regex metacharacters in conflict keywords\n\n## Design Principles\n\n1. **Safe by default** — Destructive operations require explicit flags (`--confirm`, `--force`)\n2. **No external dependencies** — Pure Node.js, no npm packages\n3. **Configurable** — Thresholds, keywords, retention policies\n4. **Transparent** — Generates reports; however, retention policy (when enabled) deletes archived files after `retentionDays` — this is intentional but irreversible\n5. **Reversible** — Pre-tier backups preserve original MEMORY.md; restored via `--restore --force`\n6. **Privacy-first** — All local, no cloud APIs\n\nFile v2.4.1:_meta.json\n\n{\n  \"ownerId\": \"kn7b6eyf5vc7khg5fr63pjm8xd82qvw5\",\n  \"slug\": \"memory-router\",\n  \"version\": \"2.4.1\",\n  \"publishedAt\": 1781403729796\n}\n\nFile v2.4.1:INSTALL.md\n\n# MemoryRouter — Installation Guide\n\n## Prerequisites\n\n- OpenClaw installed and running\n- Node.js 18+ (built-in `fs` and `path` — no npm packages needed)\n- A `MEMORY.md` file in your workspace (can be empty initially)\n\n## Quick Install (1 minute)\n\n```bash\n# 1. Create the skill directory\nmkdir -p ~/.openclaw/workspace/skills/memory-router\n\n# 2. Copy the skill files\n# Place these files from this package into the directory above:\n#   - memory-router.js   (core engine)\n#   - config.json          (thresholds and options)\n#   - SKILL.md             (skill definition)\n#   - README.md            (this guide)\n\n# 3. Make executable\nchmod +x ~/.openclaw/workspace/skills/memory-router/memory-router.js\n\n# 4. Test it works\nnode ~/.openclaw/workspace/skills/memory-router/memory-router.js --status\n```\n\nExpected output:\n```\n=== MemoryRouter Status ===\n\nMEMORY.md: X lines, Y KB ✅ OK\nmemory/: 0 files, 0.0 KB total\nself-improving/: 0 files\nproactivity/: 0 files\narchives: 0 files\nmanifest: not generated\nentity index: 0 entities\nWAL: not initialized\n```\n\n## Configuration\n\nEdit `config.json` to customize behavior:\n\n```json\n{\n  \"thresholds\": {\n    \"memoryMdMaxLines\": 500,\n    \"memoryMdMaxChars\": 25000,\n    \"tierArchiveMinAgeDays\": 3,\n    \"auditMaxFiles\": 50\n  },\n  \"tiering\": {\n    \"archiveDir\": \"memory/active\",\n    \"retentionDays\": 90,\n    \"keepInMemory\": [\n      \"identity\", \"preferences\", \"relationships\",\n      \"projects\", \"patterns\", \"boundaries\", \"key_facts\"\n    ]\n  },\n  \"manifest\": {\n    \"generateOnTier\": true,\n    \"manifestPath\": \"memory/memory-manifest.json\"\n  },\n  \"audit\": {\n    \"reportPath\": \"memory/memory-audit-report.md\",\n    \"duplicateThreshold\": 0.7,\n    \"conflictKeywords\": [\n      \"revised\", \"updated\", \"changed\", \"no longer\",\n      \"actually\", \"correction\", \"mistake\"\n    ]\n  }\n}\n```\n\n### Key settings explained\n\n| Setting | Default | What it does |\n|---------|---------|-------------|\n| `memoryMdMaxLines` | 500 | Auto-tier triggers when MEMORY.md exceeds this line count |\n| `memoryMdMaxChars` | 25000 | Same, but by character count (whichever threshold is hit first) |\n| `tierArchiveMinAgeDays` | 3 | Sections must be this old before archiving |\n| `retentionDays` | 90 | ⚠️ Archived files older than this are **candidates for deletion**. Irreversible. Set to 365+ until confident. |\n| `keepInMemory` | see above | Headers/keywords that always stay in the core MEMORY.md |\n| `generateOnTier` | true | Auto-generate manifest after tiering |\n| `duplicateThreshold` | 0.7 | Similarity score (>70%) to flag as potential duplicate |\n\n## Heartbeat Integration\n\nAdd this to your `HEARTBEAT.md` under scheduled tasks:\n\n```markdown\n### 🔧 MemoryRouter (SAFE commands only)\n\n- Run `node skills/memory-router/memory-router.js --compact` to update manifest ✅ safe\n- Run `node skills/memory-router/memory-router.js --audit` to check for issues ✅ safe\n- Run `node skills/memory-router/memory-router.js --status` for health overview ✅ safe\n- ⚠️ Do NOT auto-run `--tier` during heartbeats — it permanently rewrites MEMORY.md\n- `--tier --dry-run` is side-effect free (no files created or modified)\n- For tiering: run `--tier --dry-run` manually, review output, then `--tier --confirm`\n- Check `memory/memory-audit-report.md` for any flagged conflicts\n```\n\n**Important:** `--tier` permanently rewrites MEMORY.md. Only run it manually with `--confirm` after reviewing `--dry-run` output.\n\n## Agent Memory Loading Protocol\n\nWhen your agent wakes up, use the manifest instead of loading all memory files:\n\n1. Read `memory/memory-manifest.json`\n2. Load all `required: true` files\n3. For `required: false` files, use `memory_search` to check relevance\n4. Load only the top 3-5 most relevant optional files\n\nThis gives you **70-85% context reduction** — load what matters, skip the rest.\n\n## Commands Reference\n\n| Command | What it does |\n|---------|-------------|\n| `--tier` | Auto-tier MEMORY.md (split core + archive) |\n| `--compact` | Generate per-session manifest |\n| `--compact --query \"text\"` | Query-aware manifest with entity boosting |\n| `--compact --budget N` | Manifest filtered to N tokens |\n| `--audit` | Scan for duplicates/conflicts |\n| `--status` | Show memory health overview |\n| `--entity add <name> <type> <files...>` | Add entity to index |\n| `--entity list` | List all entities |\n| `--entity search <query>` | Search entities |\n| `--wal init` | Initialize WAL (session state) |\n| `--wal get` | Show current WAL state |\n| `--wal update <section> --content \"<text>\"` | Update WAL section |\n\n## Troubleshooting\n\n### \"No MEMORY.md found\"\n\nCreate one:\n```bash\necho \"# MEMORY.md - Long-Term Memory\" > ~/.openclaw/workspace/MEMORY.md\n```\n\n### \"Memory directory not found\"\n\nCreate it:\n```bash\nmkdir -p ~/.openclaw/workspace/memory\n```\n\n### Tiering not working\n\nCheck your thresholds in `config.json`. If MEMORY.md is under 500 lines and 25KB, nothing happens — that's by design.\n\n### Manifest shows wrong file count\n\nRun `--compact` again. The manifest is regenerated fresh each time.\n\n### Entity search returns nothing\n\nAdd entities first:\n```bash\nnode memory-router.js --entity add james person USER.md IDENTITY.md\n```\n\n## Custom Workspace Path\n\nIf you want to use a different workspace:\n\n```bash\nMM_WORKSPACE=/path/to/your/workspace node memory-router.js --status\n```\n\nFile v2.4.1:skill-card.md\n\n## Description: <br>\nMemory Router helps OpenClaw agents manage local memory by tiering bloated MEMORY.md files, generating query-aware manifests, auditing duplicate or conflicting memories, and maintaining session state. <br>\n\nThis skill is ready for commercial/non-commercial use. <br>\n\n## Publisher: <br>\n[jlacroix82](https://clawhub.ai/user/jlacroix82) <br>\n\n### License/Terms of Use: <br>\nMIT-0 <br>\n\n\n## Use Case: <br>\nDevelopers and agent operators use this skill to keep long-running OpenClaw memory stores concise, searchable, and relevant across sessions. It is intended for local workflows that need memory manifests, audits, entity indexing, and controlled MEMORY.md tiering. <br>\n\n### Deployment Geography for Use: <br>\nGlobal <br>\n\n## Known Risks and Mitigations: <br>\nRisk: The skill reads and modifies local memory files as part of its normal purpose. <br>\nMitigation: Install only for workflows that intentionally delegate local memory-file management, and keep separate backups of MEMORY.md and memory/ before write operations. <br>\nRisk: Tiering and restore operations can rewrite or overwrite MEMORY.md. <br>\nMitigation: Run --tier --dry-run first, review the proposed changes, then use --tier --confirm only when ready; do not place --tier --confirm or --restore --force in unattended automation. <br>\nRisk: Archive retention settings can lead to irreversible deletion of archived memory sections. <br>\nMitigation: Use conservative retention settings, back up the full memory directory, and monitor archived files before reducing retention periods. <br>\nRisk: Persistent helper commands such as entity updates and WAL updates write local state files. <br>\nMitigation: Review these commands before automating them, and reserve unattended runs for commands documented as safe such as --compact, --audit, --status, entity list/search, WAL get, and --tier --dry-run. <br>\n\n\n## Reference(s): <br>\n- [Memory Router on ClawHub](https://clawhub.ai/jlacroix82/memory-router) <br>\n- [README.md](artifact/README.md) <br>\n- [INSTALL.md](artifact/INSTALL.md) <br>\n\n\n## Skill Output: <br>\n**Output Type(s):** [text, markdown, code, shell commands, configuration, guidance] <br>\n**Output Format:** [Markdown guidance, shell commands, JSON manifests, and Markdown reports] <br>\n**Output Parameters:** [1D] <br>\n**Other Properties Related to Output:** [Produces local files such as memory/memory-manifest.json, memory/memory-audit-report.md, entity indexes, session state, backups, archives, and updated MEMORY.md content depending on the command used.] <br>\n\n## Skill Version(s): <br>\n2.4.1 (source: server release evidence) <br>\n\n## Ethical Considerations: <br>\nUsers 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. <br>\n\nFile v2.4.1:config.json\n\n{\n  \"thresholds\": {\n    \"memoryMdMaxLines\": 500,\n    \"memoryMdMaxChars\": 25000,\n    \"tierArchiveMinAgeDays\": 3,\n    \"auditMaxFiles\": 50\n  },\n  \"tiering\": {\n    \"archiveDir\": \"memory/active\",\n    \"backupDir\": \"memory/backups\",\n    \"retentionDays\": 90,\n    \"minCoreLines\": 20,\n    \"minCoreChars\": 1000,\n    \"keepInMemory\": [\n      \"identity\",\n      \"preferences\",\n      \"relationships\",\n      \"projects\",\n      \"patterns\",\n      \"boundaries\",\n      \"key_facts\"\n    ]\n  },\n  \"manifest\": {\n    \"generateOnTier\": true,\n    \"manifestPath\": \"memory/memory-manifest.json\"\n  },\n  \"audit\": {\n    \"reportPath\": \"memory/memory-audit-report.md\",\n    \"duplicateThreshold\": 0.7,\n    \"conflictKeywords\": [\"revised\", \"updated\", \"changed\", \"no longer\", \"actually\", \"correction\", \"mistake\"]\n  }\n}\n\nArchive v2.4.0: 7 files, 28536 bytes\n\nFiles: _meta.json (132b), config.json (778b), INSTALL.md (5310b), memory-router.js (41245b), README.md (18132b), skill-card.md (2771b), SKILL.md (18556b)\n\nFile v2.4.0:SKILL.md\n\n# MemoryRouter ⚡\n\n**Never lose context. Never forget decisions. Never repeat mistakes.**\n\nThe memory problem is the single biggest reason agents feel dumb over time. Not the models. Not the prompts. **Memory management.**\n\nMemoryRouter fixes it with one tool, zero dependencies, zero setup.\n\n## The Problem — In 30 Seconds\n\nAgent memory files grow unbounded. After a week, you've got thousands of lines across dozens of files. Every session loads **everything** — even when the user asks \"what's the weather?\"\n\nThat's tokens burned on irrelevant memories, every interaction, forever.\n\nThen compaction kicks in and details vanish.\n\n**The bottleneck isn't the model. It's what the model gets to see.**\n\n## Why Memory Fails\n\n| Failure Mode | Cause | Fix |\n|-------------|-------|-----|\n| Forgets everything | Loads irrelevant files, context window fills up | Smart manifest — load only what matters |\n| Repeats mistakes | Lessons not captured or loaded | Entity index + audit for conflicts |\n| Repeats work | No session state persistence | WAL protocol — write state before responding |\n| Slow responses | Loads 50+ files when only 3 matter | Token budgeting — cap context window |\n| Duplicates everywhere | No automated cleanup | `--audit` finds high-similarity pairs |\n\n## The Architecture\n\n```\n┌──────────────────────────────────────────────────────┐\n│              MEMORYROUTER ⚡                          │\n├──────────────────────────────────────────────────────┤\n│                                                      │\n│  ┌──────────────┐    ┌──────────────┐               │\n│  │  AUTO-TIER   │    │  MANIFEST    │               │\n│  │  MEMORY.md   │ →  │  GENERATOR   │               │\n│  │              │    │              │               │\n│  │ Core (always │    │ Required:    │               │\n│  │ loaded)      │    │ MEMORY.md    │               │\n│  │ + Archive    │    │ Recent logs  │               │\n│  │ (on demand)  │    │ Boosted:     │               │\n│  └──────────────┘    │ entity files │               │\n│                      └──────┬───────┘               │\n│                             │                        │\n│              ┌──────────────▼──────────────┐         │\n│              │  ENTITY RESOLUTION          │         │\n│              │  \"alice\" → preferences.md,         │         │\n│              │  notes.md, decisions.md│         │\n│              └──────────────┬──────────────┘         │\n│                             │                        │\n│              ┌──────────────▼──────────────┐         │\n│              │  TOKEN BUDGET FILTER        │         │\n│              │  20K budget → 7 files       │         │\n│              │  100K budget → 16 files     │         │\n│              └──────────────┬──────────────┘         │\n│                             │                        │\n│              ┌──────────────▼──────────────┐         │\n│              │  AGENT LOADS ONLY WHAT      │         │\n│              │  MATTERS → 70-85% REDUCTION │         │\n│              └─────────────────────────────┘         │\n└──────────────────────────────────────────────────────┘\n```\n\n## Quick Start\n\n### Fix a bloated MEMORY.md (requires confirmation)\n\n```bash\nnode skills/memory-router/memory-router.js --tier --confirm\n```\n\n**Output:**\n```\n[memory-router] MEMORY.md: 7809 lines, 309254 chars\n[memory-router] ✅ Pre-tier backup: memory/backups/MEMORY-backup-2026-05-23-1234567890.md (7809 lines saved)\n[memory-router] Tiered: 202 core sections, 1002 archived\n[memory-router] MEMORY.md reduced from 7809 lines to 2222 lines\n```\n\n### Preview tiering without making changes\n\n```bash\nnode skills/memory-router/memory-router.js --tier --dry-run\n```\n\n**Output:**\n```\n[memory-router] MEMORY.md: 7809 lines, 309254 chars\n[memory-router] ── DRY RUN ──\n[memory-router] Would archive: memory/active/MEMORY-archive-2026-05-23.md\n[memory-router] Would reduce MEMORY.md from 7809 lines to ~2222 lines\n[memory-router] Core sections: 202, Archive sections: 1002\n[memory-router] ✅ No files were modified.\n```\n\n### Restore MEMORY.md from latest backup\n\n```bash\nnode skills/memory-router/memory-router.js --restore --force\n```\n\n⚠️ **Destructive** — overwrites MEMORY.md. Requires `--force` flag. Extracts only the original content from the backup (metadata headers are stripped). Always creates a backup of the current MEMORY.md before overwriting.\n\n### Generate a smart manifest in one command\n\n```bash\nnode skills/memory-router/memory-router.js --compact\n```\n\nCreates `memory/memory-manifest.json` — the agent's shopping list of what to load.\n\n### With entity boosting\n\n```bash\nnode skills/memory-router/memory-router.js --compact --query \"alice\"\n```\n\nFiles linked to \"alice\" get priority. No AI, no embeddings — just fast entity resolution.\n\n### With a token budget\n\n```bash\nnode skills/memory-router/memory-router.js --compact --budget 20000\n```\n\nOnly loads files that fit within 20K tokens. Tight budgets load core only. Generous budgets load archive on demand.\n\n### Other commands\n\n```bash\nnode skills/memory-router/memory-router.js --audit      # Find duplicates & conflicts\nnode skills/memory-router/memory-router.js --status      # Health overview\nnode skills/memory-router/memory-router.js --entity add alice person preferences.md\n```\n\n## How It Works\n\n### The Core Insight\n\n**Memory management is the bottleneck, not model capability.** Every agent system hits the same wall — context window fills up, everything loads, irrelevant memories dilute the signal.\n\nMemoryRouter takes a **routing** approach rather than a **compression** approach:\n\n1. **Auto-tiering** splits MEMORY.md into core sections (identity, preferences, boundaries — always loaded) and archive sections (everything else, loaded on demand)\n2. **Manifest generation** creates a per-session file list: which files to load, which to skip, which to boost\n3. **Entity-aware boosting** links people, projects, and systems to files — search for \"alice\" → load preferences.md first\n4. **Token budgeting** caps how many files load based on available context window\n\n### The Flow\n\n```\nUser query → --compact --query \"alice\"\n              ↓\n         Manifest generated\n              ↓\n         Load required files (MEMORY.md, recent daily logs)\n              ↓\n         Boost entity-matched files (preferences.md, notes.md)\n              ↓\n         Agent loads only what matters → 70-85% context reduction\n```\n\n## The 4 Engines\n\n### ⚡ Engine 1: Auto-Tier (`--tier`)\n\nWhen MEMORY.md exceeds configurable thresholds (default: 500 lines or 25KB), splits into:\n- **Core file** — Identity, preferences, relationships, projects, patterns, boundaries\n- **Archive files** — Everything else, stored with timestamps in `memory/active/`\n\n**Safety features (v2):**\n- **Pre-tier backup** — Every `--tier` creates a full backup in `memory/backups/` before modifying MEMORY.md\n- **`--dry-run`** — Preview what tiering would do without making changes\n- **`--confirm`** — Required for destructive writes (no auto-tier without explicit confirmation)\n- **Minimum core size** — Aborts if core sections would fall below `minCoreLines`/`minCoreChars` thresholds\n- **`--restore --force`** — Restore MEMORY.md from the latest backup (requires `--force` flag)\n\nSections are classified by header keywords (identity, preferences, etc.) or by content heuristics.\n\n### 📋 Engine 2: Manifest Generator (`--compact`)\n\nCreates `memory/memory-manifest.json` with a file list:\n\n```json\n{\n  \"generated\": \"2026-05-21\",\n  \"files\": [\n    { \"path\": \"MEMORY.md\", \"tier\": \"core\", \"required\": true, \"size\": 50346 },\n    { \"path\": \"memory/2026-05-21.md\", \"tier\": \"recent\", \"required\": true, \"size\": 2034 },\n    { \"path\": \"self-improving/memory.md\", \"tier\": \"domain\", \"required\": false, \"size\": 670 }\n  ]\n}\n```\n\n**Options:**\n| Flag | Description |\n|------|-------------|\n| `--query \"text\"` | Entity-aware boosting — files linked to matching entities get priority |\n| `--budget N` | Token budget — only loads files that fit within N tokens |\n\n### 🔍 Engine 3: Audit Scanner (`--audit`)\n\nScans all memory files for:\n- **High-similari\n\nArchive v2.3.0: 7 files, 27984 bytes\n\nFiles: _meta.json (132b), config.json (778b), INSTALL.md (5310b), memory-router.js (40402b), README.md (17155b), skill-card.md (2872b), SKILL.md (18556b)\n\nArchive v2.2.2: 7 files, 26454 bytes\n\nFiles: _meta.json (132b), config.json (778b), INSTALL.md (4836b), memory-router.js (40423b), README.md (15505b), skill-card.md (2367b), SKILL.md (17285b)\n\nArchive v2.2.1: 7 files, 25471 bytes\n\nFiles: _meta.json (132b), config.json (778b), INSTALL.md (4836b), memory-router.js (39403b), README.md (14969b), skill-card.md (2135b), SKILL.md (16420b)\n\nArchive v1.0.4: 7 files, 26934 bytes\n\nFiles: config.json (778b), INSTALL.md (4836b), memory-router.js (41802b), README.md (17174b), skill-card.md (2430b), SKILL.md (16670b), _meta.json (132b)\n\nArchive v2.2.0: 7 files, 25588 bytes\n\nFiles: config.json (778b), INSTALL.md (4836b), memory-router.js (39402b), README.md (14969b), skill-card.md (2438b), SKILL.md (16420b), _meta.json (132b)\n\nArchive v2.1.0: 7 files, 25503 bytes\n\nFiles: config.json (778b), INSTALL.md (4836b), memory-router.js (39307b), README.md (14969b), skill-card.md (2266b), SKILL.md (16420b), _meta.json (132b)","readmeExcerpt":"Skill: Memory Router Owner: jlacroix82 Summary: OpenClaw skill that auto-tiers bloated MEMORY.md, generates smart per-session manifests, and routes only what matters — 70-85% context reduction with zero de... Tags: latest:2.4.3 Version history: v2.4.3 | 2026-07-21T18:51:29.200Z | auto **2.4.3 Changelog** - Added prominent safety and warning sections to SKILL.md: clarifies destructive operations, confirmation flags, a","codeSnippets":[],"executableExamples":[{"language":"text","snippet":"┌──────────────────────────────────────────────────────┐\n│              MEMORYROUTER ⚡                          │\n├──────────────────────────────────────────────────────┤\n│                                                      │\n│  ┌──────────────┐    ┌──────────────┐               │\n│  │  AUTO-TIER   │    │  MANIFEST    │               │\n│  │  MEMORY.md   │ →  │  GENERATOR   │               │\n│  │              │    │              │               │\n│  │ Core (always │    │ Required:    │               │\n│  │ loaded)      │    │ MEMORY.md    │               │\n│  │ + Archive    │    │ Recent logs  │               │\n│  │ (on demand)  │    │ Boosted:     │               │\n│  └──────────────┘    │ entity files │               │\n│                      └──────┬───────┘               │\n│                             │                        │\n│              ┌──────────────▼──────────────┐         │\n│              │  ENTITY RESOLUTION          │         │\n│              │  \"alice\" → preferences.md,         │         │\n│              │  notes.md, decisions.md│         │\n│              └──────────────┬──────────────┘         │\n│                             │                        │\n│              ┌──────────────▼──────────────┐         │\n│              │  TOKEN BUDGET FILTER        │         │\n│              │  20K budget → 7 files       │         │\n│              │  100K budget → 16 files     │         │\n│              └──────────────┬──────────────┘         │\n│                             │                        │\n│              ┌──────────────▼──────────────┐         │\n│              │  AGENT LOADS ONLY WHAT      │         │\n│              │  MATTERS → 70-85% REDUCTION │         │\n│              └─────────────────────────────┘         │\n└──────────────────────────────────────────────────────┘"},{"language":"bash","snippet":"node skills/memory-router/memory-router.js --tier --confirm"},{"language":"text","snippet":"[memory-router] MEMORY.md: 7809 lines, 309254 chars\n[memory-router] ✅ Pre-tier backup: memory/backups/MEMORY-backup-2026-05-23-1234567890.md (7809 lines saved)\n[memory-router] Tiered: 202 core sections, 1002 archived\n[memory-router] MEMORY.md reduced from 7809 lines to 2222 lines"},{"language":"bash","snippet":"node skills/memory-router/memory-router.js --tier --dry-run"},{"language":"text","snippet":"[memory-router] MEMORY.md: 7809 lines, 309254 chars\n[memory-router] ── DRY RUN ──\n[memory-router] Would archive: memory/active/MEMORY-archive-2026-05-23.md\n[memory-router] Would reduce MEMORY.md from 7809 lines to ~2222 lines\n[memory-router] Core sections: 202, Archive sections: 1002\n[memory-router] ✅ No files were modified."},{"language":"bash","snippet":"node skills/memory-router/memory-router.js --restore --force"}],"parameters":null,"dependencies":[],"permissions":[],"extractedFiles":[{"path":"SKILL.md","content":"# MemoryRouter ⚡\n\n**Never lose context. Never forget decisions. Never repeat mistakes.**\n\nThe memory problem is the single biggest reason agents feel dumb over time. Not the models. Not the prompts. **Memory management.**\n\nMemoryRouter fixes it with one tool, zero dependencies, zero setup.\n\n## The Problem — In 30 Seconds\n\nAgent memory files grow unbounded. After a week, you've got thousands of lines across dozens of files. Every session loads **everything** — even when the user asks \"what's the weather?\"\n\nThat's tokens burned on irrelevant memories, every interaction, forever.\n\nThen compaction kicks in and details vanish.\n\n**The bottleneck isn't the model. It's what the model gets to see.**\n\n## Why Memory Fails\n\n| Failure Mode | Cause | Fix |\n|-------------|-------|-----|\n| Forgets everything | Loads irrelevant files, context window fills up | Smart manifest — load only what matters |\n| Repeats mistakes | Lessons not captured or loaded | Entity index + audit for conflicts |\n| Repeats work | No session state persistence | WAL protocol — write state before responding |\n| Slow responses | Loads 50+ files when only 3 matter | Token budgeting — cap context window |\n| Duplicates everywhere | No automated cleanup | `--audit` finds high-similarity pairs |\n\n## The Architecture\n\n```\n┌──────────────────────────────────────────────────────┐\n│              MEMORYROUTER ⚡                          │\n├──────────────────────────────────────────────────────┤\n│                                                      │\n│  ┌──────────────┐    ┌──────────────┐               │\n│  │  AUTO-TIER   │    │  MANIFEST    │               │\n│  │  MEMORY.md   │ →  │  GENERATOR   │               │\n│  │              │    │              │               │\n│  │ Core (always │    │ Required:    │               │\n│  │ loaded)      │    │ MEMORY.md    │               │\n│  │ + Archive    │    │ Recent logs  │               │\n│  │ (on demand)  │    │ Boosted:     │               │\n│  └──────────────┘    │ entity files │               │\n│                      └──────┬───────┘               │\n│                             │                        │\n│              ┌──────────────▼──────────────┐         │\n│              │  ENTITY RESOLUTION          │         │\n│              │  \"alice\" → preferences.md,         │         │\n│              │  notes.md, decisions.md│         │\n│              └──────────────┬──────────────┘         │\n│                             │                        │\n│              ┌──────────────▼──────────────┐         │\n│              │  TOKEN BUDGET FILTER        │         │\n│              │  20K budget → 7 files       │         │\n│              │  100K budget → 16 files     │         │\n│              └──────────────┬──────────────┘         │\n│                             │                        │\n│              ┌──────────────▼──────────────┐         │\n│              │  AGENT LOADS ONLY WHAT      │         │\n│              │  MATTERS → 70-85% REDUCTION │         │\n│   "},{"path":"README.md","content":"# MemoryRouter ⚡\n\n**Never lose context. Never forget decisions. Never repeat mistakes.**\n\nThe memory problem is the single biggest reason agents feel dumb over time. Not the models. Not the prompts. **Memory management.**\n\nMemoryRouter fixes it with one tool, zero dependencies, zero setup.\n\n## The Problem — In 30 Seconds\n\nAgent memory files grow unbounded. After a week, you've got thousands of lines across dozens of files. Every session loads **everything** — even when the user asks \"what's the weather?\"\n\nThat's tokens burned on irrelevant memories, every interaction, forever.\n\nThen compaction kicks in and details vanish.\n\n**The bottleneck isn't the model. It's what the model gets to see.**\n\n## Why Memory Fails\n\n| Failure Mode | Cause | Fix |\n|-------------|-------|-----|\n| Forgets everything | Loads irrelevant files, context window fills up | Smart manifest — load only what matters |\n| Repeats mistakes | Lessons not captured or loaded | Entity index + audit for conflicts |\n| Repeats work | No session state persistence | WAL protocol — write state before responding |\n| Slow responses | Loads 50+ files when only 3 matter | Token budgeting — cap context window |\n| Duplicates everywhere | No automated cleanup | `--audit` finds high-similarity pairs |\n\n## The Architecture\n\n```\n┌──────────────────────────────────────────────────────┐\n│              MEMORYROUTER ⚡                          │\n├──────────────────────────────────────────────────────┤\n│                                                      │\n│  ┌──────────────┐    ┌──────────────┐               │\n│  │  AUTO-TIER   │    │  MANIFEST    │               │\n│  │  MEMORY.md   │ →  │  GENERATOR   │               │\n│  │              │    │              │               │\n│  │ Core (always │    │ Required:    │               │\n│  │ loaded)      │    │ MEMORY.md    │               │\n│  │ + Archive    │    │ Recent logs  │               │\n│  │ (on demand)  │    │ Boosted:     │               │\n│  └──────────────┘    │ entity files │               │\n│                      └──────┬───────┘               │\n│                             │                        │\n│              ┌──────────────▼──────────────┐         │\n│              │  ENTITY RESOLUTION          │         │\n│              │  \"alice\" → preferences.md,         │         │\n│              │  notes.md, decisions.md│         │\n│              └──────────────┬──────────────┘         │\n│                             │                        │\n│              ┌──────────────▼──────────────┐         │\n│              │  TOKEN BUDGET FILTER        │         │\n│              │  20K budget → 7 files       │         │\n│              │  100K budget → 16 files     │         │\n│              └──────────────┬──────────────┘         │\n│                             │                        │\n│              ┌──────────────▼──────────────┐         │\n│              │  AGENT LOADS ONLY WHAT      │         │\n│              │  MATTERS → 70-85% REDUCTION │         │\n│   "},{"path":"_meta.json","content":"{\n  \"ownerId\": \"kn7b6eyf5vc7khg5fr63pjm8xd82qvw5\",\n  \"slug\": \"memory-router\",\n  \"version\": \"2.4.3\",\n  \"publishedAt\": 1784659889200\n}"},{"path":"INSTALL.md","content":"# MemoryRouter — Installation Guide\n\n## Prerequisites\n\n- OpenClaw installed and running\n- Node.js 18+ (built-in `fs` and `path` — no npm packages needed)\n- A `MEMORY.md` file in your workspace (can be empty initially)\n\n## Quick Install (1 minute)\n\n```bash\n# 1. Create the skill directory\nmkdir -p ~/.openclaw/workspace/skills/memory-router\n\n# 2. Copy the skill files\n# Place these files from this package into the directory above:\n#   - memory-router.js   (core engine)\n#   - config.json          (thresholds and options)\n#   - SKILL.md             (skill definition)\n#   - README.md            (this guide)\n\n# 3. Make executable\nchmod +x ~/.openclaw/workspace/skills/memory-router/memory-router.js\n\n# 4. Test it works\nnode ~/.openclaw/workspace/skills/memory-router/memory-router.js --status\n```\n\nExpected output:\n```\n=== MemoryRouter Status ===\n\nMEMORY.md: X lines, Y KB ✅ OK\nmemory/: 0 files, 0.0 KB total\nself-improving/: 0 files\nproactivity/: 0 files\narchives: 0 files\nmanifest: not generated\nentity index: 0 entities\nWAL: not initialized\n```\n\n## Configuration\n\nEdit `config.json` to customize behavior:\n\n```json\n{\n  \"thresholds\": {\n    \"memoryMdMaxLines\": 500,\n    \"memoryMdMaxChars\": 25000,\n    \"tierArchiveMinAgeDays\": 3,\n    \"auditMaxFiles\": 50\n  },\n  \"tiering\": {\n    \"archiveDir\": \"memory/active\",\n    \"retentionDays\": 90,\n    \"keepInMemory\": [\n      \"identity\", \"preferences\", \"relationships\",\n      \"projects\", \"patterns\", \"boundaries\", \"key_facts\"\n    ]\n  },\n  \"manifest\": {\n    \"generateOnTier\": true,\n    \"manifestPath\": \"memory/memory-manifest.json\"\n  },\n  \"audit\": {\n    \"reportPath\": \"memory/memory-audit-report.md\",\n    \"duplicateThreshold\": 0.7,\n    \"conflictKeywords\": [\n      \"revised\", \"updated\", \"changed\", \"no longer\",\n      \"actually\", \"correction\", \"mistake\"\n    ]\n  }\n}\n```\n\n### Key settings explained\n\n| Setting | Default | What it does |\n|---------|---------|-------------|\n| `memoryMdMaxLines` | 500 | Auto-tier triggers when MEMORY.md exceeds this line count |\n| `memoryMdMaxChars` | 25000 | Same, but by character count (whichever threshold is hit first) |\n| `tierArchiveMinAgeDays` | 3 | Sections must be this old before archiving |\n| `retentionDays` | 90 | ⚠️ Archived files older than this are **candidates for deletion**. Irreversible. Set to 365+ until confident. |\n| `keepInMemory` | see above | Headers/keywords that always stay in the core MEMORY.md |\n| `generateOnTier` | true | Auto-generate manifest after tiering |\n| `duplicateThreshold` | 0.7 | Similarity score (>70%) to flag as potential duplicate |\n\n## Heartbeat Integration\n\nAdd this to your `HEARTBEAT.md` under scheduled tasks:\n\n```markdown\n### 🔧 MemoryRouter (SAFE commands only)\n\n- Run `node skills/memory-router/memory-router.js --compact` to update manifest ✅ safe\n- Run `node skills/memory-router/memory-router.js --audit` to check for issues ✅ safe\n- Run `node skills/memory-router/memory-router.js --status` for health overview ✅ safe\n- ⚠️ Do NOT auto-run `--tier` during heartbeats — it p"},{"path":"skill-card.md","content":"## Description:\n\nMemory Router helps agents manage local memory files by generating focused manifests, tiering oversized MEMORY.md content, auditing duplicate or conflicting entries, and maintaining entity and session-state indexes.\n\nThis skill is ready for commercial/non-commercial use.\n\n## Publisher:\n\n[jlacroix82](https://clawhub.ai/user/jlacroix82)\n\n### License/Terms of Use:\n\nMIT-0\n\n## Use Case:\n\nDevelopers and agent operators use Memory Router to reduce memory context bloat, route only relevant memory files into a session, and inspect local memory health before loading or rewriting memory state.\n\n### Deployment Geography for Use:\n\nGlobal\n\n## Known Risks and Mitigations:\n\nRisk: Tiering, restore, cleanup, entity, and WAL commands can modify or overwrite local memory files.\n\nMitigation: Use a backed-up workspace, run status or dry-run commands first, and reserve --tier --confirm and --restore --force for reviewed manual execution.\n\nRisk: Custom workspace or path settings can increase the chance of operating on the wrong files.\n\nMitigation: Avoid absolute paths or .. components in custom path settings and confirm the workspace before running commands that write files.\n\nRisk: The security verdict is suspicious because destructive restore and tiering guarantees may be weaker than the documentation suggests.\n\nMitigation: Treat the skill as an assisted local memory tool, review generated manifests and audit reports, and do not rely on its backups as the only recovery mechanism.\n\n## Reference(s):\n\n- [ClawHub skill page](https://clawhub.ai/jlacroix82/skills/memory-router)\n- [README](artifact/README.md)\n- [Installation Guide](artifact/INSTALL.md)\n- [Skill definition](artifact/SKILL.md)\n\n## Skill Output:\n\n**Output Type(s):** [text, markdown, code, shell commands, configuration, guidance]\n\n**Output Format:** [Markdown guidance with shell commands, JSON configuration examples, generated JSON manifests, text status output, and Markdown audit reports]\n\n**Output Parameters:** [1D]\n\n**Other Properties Related to Output:** [Local filesystem outputs may include memory/memory-manifest.json, memory/memory-audit-report.md, archive files, backups, entity indexes, and SESSION-STATE.md depending on the command.]\n\n## Skill Version(s):\n\n2.4.3 (source: server release evidence)\n\n## Ethical Considerations:\n\nUsers 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."}],"languages":[],"docsSourceLabel":"CLAWHUB","editorialOverview":"OpenClaw skill that auto-tiers bloated MEMORY.md, generates smart per-session manifests, and routes only what matters — 70-85% context reduction with zero de... Skill: Memory Router Owner: jlacroix82 Summary: OpenClaw skill that auto-tiers bloated MEMORY.md, generates smart per-session manifests, and routes only what matters — 70-85% context reduction with zero de... Tags: latest:2.4.3 Version history: v2.4.3 | 2026-07-21T18:51:29.200Z | auto **2.4.3 Changelog** - Added prominent safety and warning sections to SKILL.md: clarifies destructive operations, confirmation flags, a","editorialQuality":{"score":100,"threshold":65,"status":"ready","wordCount":1349,"uniquenessScore":54,"reasons":[]}},"media":{"evidence":{"source":"no-media","verified":false,"confidence":"low","updatedAt":"2026-10-09T16:44:14.157Z","emptyReason":"No screenshots, media assets, or demo links are available."},"primaryImageUrl":null,"mediaAssetCount":0,"assets":[],"demoUrl":null},"ownerResources":{"evidence":{"source":"unclaimed","verified":false,"confidence":"low","updatedAt":"2026-10-09T16:44:14.157Z","emptyReason":"This page has not been claimed by the agent owner."},"hasCustomPage":false,"customPageUpdatedAt":null,"customLinks":[],"structuredLinks":{"docsUrl":null,"demoUrl":null,"supportUrl":null,"pricingUrl":null,"statusUrl":null},"customPage":null},"relatedAgents":{"evidence":{"source":"protocol-neighbors","verified":false,"confidence":"medium","updatedAt":"2026-10-09T20:52:32.087Z","emptyReason":null},"items":[{"id":"8ebccd8e-3863-4187-8355-c3f14e1f9edf","entityType":"agent","canonicalPath":"/agent/iofficeai-aionui","slug":"iofficeai-aionui","name":"AionUi","description":"Free, local, open-source 24/7 Cowork app and OpenClaw for Gemini CLI, Claude Code, Codex, OpenCode, Qwen Code, Goose CLI, Auggie, and more | 🌟 Star if you like it!","url":"https://github.com/iOfficeAI/AionUi","homepage":"https://www.aionui.com","source":"GITHUB_REPOS","protocols":["MCP","OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-10-09T19:11:12.944Z","createdAt":"2026-02-25T03:38:16.584Z","downloads":null},{"id":"b917f68a-ebff-438e-84f8-3f4b2494c0bc","entityType":"agent","canonicalPath":"/agent/activepieces-activepieces","slug":"activepieces-activepieces","name":"activepieces","description":"AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents","url":"https://github.com/activepieces/activepieces","homepage":"https://www.activepieces.com","source":"GITHUB_REPOS","protocols":["OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-04-15T02:22:12.426Z","createdAt":"2026-02-25T03:38:12.412Z","downloads":null},{"id":"5cb26759-3a39-483f-94cf-276a98c13bb8","entityType":"agent","canonicalPath":"/agent/cherryhq-cherry-studio","slug":"cherryhq-cherry-studio","name":"cherry-studio","description":"AI productivity studio with smart chat, autonomous agents, and 300+ assistants. Unified access to frontier LLMs","url":"https://github.com/CherryHQ/cherry-studio","homepage":"https://cherry-ai.com","source":"GITHUB_REPOS","protocols":["MCP","OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-04-11T14:38:40.986Z","createdAt":"2026-02-25T03:38:19.379Z","downloads":null},{"id":"6f6582d0-5d76-4f0f-b81d-86520247950b","entityType":"agent","canonicalPath":"/agent/copilotkit-copilotkit","slug":"copilotkit-copilotkit","name":"CopilotKit","description":"The Frontend for Agents & Generative UI. React + Angular","url":"https://github.com/CopilotKit/CopilotKit","homepage":"https://docs.copilotkit.ai","source":"GITHUB_REPOS","protocols":["OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-03-25T09:50:57.846Z","createdAt":"2026-02-25T03:39:14.617Z","downloads":null}],"links":{"hub":"/agent","source":"/agent/source/clawhub","protocols":[{"label":"OpenClaw","href":"/agent/protocol/openclew"}]}}}