Skip to content
Back to skills

Slm Cache

ASecurity

KV cache for repeated reads — call slm_cache_get(key) first; on a miss do the expensive operation then slm_cache_set(key, value, ttl_seconds) to store it; on a hit use the returned value directly; always fail-open (hit:false on any error, never raises); saves tokens when the same file, query result, or tool output is read more than once in a session.

  • 293 stars
  • 0 votes
  • 0 copies
  • 2 views
  • Added September 5, 2026
ai-agentspythonshellbashapi

Works with

  • cli
  • api
  • mcp

Security analysis

A100/100

Scanned December 3, 2026

npx -y skills add varun369/SuperLocalMemoryV2 --skill slm-cache --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Slm Cache?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Slm Cache
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/varun369-slm-cache/badge)](https://www.skillsdirectory.com/skills/varun369-slm-cache)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: slm-cache
description: KV cache for repeated reads — call slm_cache_get(key) first; on a miss do the expensive operation then slm_cache_set(key, value, ttl_seconds) to store it; on a hit use the returned value directly; always fail-open (hit:false on any error, never raises); saves tokens when the same file, query result, or tool output is read more than once in a session.
when_to_use: "cache file, avoid re-reading, repeated read, cache result, cache tool output, save re-read, reuse across session, cache check, cache hit, cache miss"
allowed-tools: slm_cache_set, slm_cache_get, Bash(slm:*)
---

# slm-cache — KV Cache for Repeated Reads (Surface B)

## Purpose

When the same file, query result, or expensive tool output is needed more than once in a session, fetching it again wastes tokens and time. `slm_cache_set` stores a result under a stable key; `slm_cache_get` retrieves it on subsequent calls. The cache is agent-scoped (automatically namespaced by tenant/agent ID), TTL-bounded, and fail-open.

This is an agent-routed cache — it caches results the agent explicitly routes through SLM. It cannot cache Claude conversation turns.

## Tool: slm_cache_set

```
slm_cache_set(
    key:          str,          # required — cache key (max 512 chars)
    value:        str,          # required — value to store (max 1 MB)
    ttl_seconds:  int = 86400,  # time-to-live in seconds (default 24 h)
    source_path:  str | None = None,   # optional abs file path for automatic mtime freshness guard
    semantic_key: str | None = None,   # optional prose query text for semantic fallback (never file/code)
) -> dict
```

### Return dict

| Key | Type | Meaning |
|-----|------|---------|
| `ok` | bool | `True` on success; `False` on validation error or internal error |
| `stored` | bool | `True` when the value was written to the cache |
| `file_guarded` | bool | `True` when `(mtime_ns, size)` freshness verification and edit-time `file:<path>` invalidation are active |
| `semantic_indexed` | bool | `True` when the non-code entry was also indexed for scoped semantic L2 fallback |
| `note` | str \| None | Error detail or `None` on success |

Keys are SHA-256-hashed internally per agent so they do not collide across agents. The raw key string you supply is the only handle you need. The namespace is the calling agent (`SLM_AGENT_ID`, or the `/mcp/<agent>` path), not the memory profile, so switching profiles does not give you a fresh cache. A caller on another computer gets its own namespace, keyed by its access key, and can never see a local agent's entries.

**Zero stale-code guarantee (v4.2.35):** Any key starting with `file:/abs/path` (or passing `source_path`) automatically snapshots `(mtime_ns, size)` and registers a `file:<realpath>` tag. When any IDE edits or writes that file, SLM's `post_tool_outcome` hook evicts the cached entry in `<1ms`; even if the file changed outside the IDE, `slm_cache_get` verifies `os.stat` and auto-evicts before returning a clean miss.

## Tool: slm_cache_get

```
slm_cache_get(
    key:               str,          # required — same key used in slm_cache_set
    source_path:       str | None = None,   # optional file path hint (disables semantic fallback)
    semantic_fallback: bool | None = None,  # True forces semantic check on non-code keys; None follows config
    min_similarity:    float = 0.92,        # cosine similarity floor (clamped >= 0.92)
) -> dict
```

### Return dict

| Key | Type | Meaning |
|-----|------|---------|
| `ok` | bool | `True` on clean execution (including miss); `False` on internal error |
| `hit` | bool | `True` when the key exists, is fresh on disk, and has not expired |
| `value` | str \| None | The stored value on a hit; `None` on miss |
| `cache_tier` | str | `"exact"` or `"semantic"` (present on hits; `"semantic"` is strictly blocked for `file:`/`code:` keys) |
| `stale_evicted` | bool | `True` when an outdated file-backed entry was detected and auto-evicted |
| `note` | str \| None | Error detail or `None` |

`value` is the string you stored. A miss returns `{"ok": true, "hit": false, "value": null, "note": null}`. `ok: false` means something went wrong internally but the miss behaviour is the same — treat both as a cache miss and proceed with the real fetch.

## Standard Pattern: Cache-Aside

Always check the cache first, then fill on miss:

```python
# 1. Check cache
cached = await slm_cache_get(key="file:/absolute/path/to/config.json")

if cached["hit"]:
    content = cached["value"]
else:
    # 2. Expensive operation (file read, search, API call)
    content = read_file("/absolute/path/to/config.json")

    # 3. Store for the rest of the session
    await slm_cache_set(
        key="file:/absolute/path/to/config.json",
        value=content,
        ttl_seconds=3600,   # 1 h — adjust to data volatility
    )

# 4. Use content
```

## Key Naming Convention

Use a stable, human-readable prefix so keys are recognisable in stats and won't collide accidentally:

| Content type | Suggested prefix | Example |
|---|---|---|
| File read | `file:` | `file:/repo/src/config.py` |
| Search result | `search:` | `search:recall:session_init_context` |
| Tool output | `tool:` | `tool:build_code_graph:/repo` |
| External fetch | `url:` | `url:https://api.example.com/v1/data` |

Key length cap: 512 characters. Keys longer than that are rejected (`ok: false`).

## When Caching Pays Off

**Cache when:**
- You will read the same file more than once in a session.
- A search or recall result is reused across multiple reasoning steps.
- An expensive MCP tool call (graph build, semantic search) produces output that is stable for the session duration.

**Do NOT cache:**
- Volatile data (live API responses that change minute-to-minute, current timestamps, streaming output).
- Secrets, credentials, tokens, or `ccr_id` values (CCR already handles its own storage).
- Data that must be fresh for correctness — a stale cache is worse than a cache miss.
- Intermediate scratchpad text you will discard.

## Fail-Open Guarantee

Neither tool raises an exception. On any internal error:

- `slm_cache_get` returns `{"ok": false, "hit": false, "value": null, ...}` — treat as a miss and proceed with the real fetch.
- `slm_cache_set` returns `{"ok": false, "stored": false, ...}` — log the note if useful, but continue; the value is still available in memory this step.

Never block a task on a cache failure.

## TTL Guidance

| Data type | Suggested TTL |
|---|---|
| Static config / generated file | 86400 s (24 h — the default) |
| Session-specific tool output | 3600 s (1 h) |
| Rapidly changing API data | Do not cache, or 60–300 s |

Set `ttl_seconds` to match how long the data remains valid. After expiry `slm_cache_get` returns a miss automatically.

## Secondary CLI (fallback when MCP is unavailable)

Prefer the MCP tools above. If you must use the command line:

```bash
slm cache status [--json] [--tenant default]
slm cache clear [--json] [--tenant default]
slm cache invalidate --tag <tag> [--json] [--tenant default]
slm cache ttl --set <seconds> [--semantic <seconds>] [--json] [--tenant default]
slm cache semantic on|off [--json] [--tenant default]
slm cache keepalive 3h|6h|9h|off|status [--upstream-ping] [--json]
```

`slm cache keepalive 3h|6h|9h` keeps active L2 cache entries warm across an unbroken 3-hour, 6-hour, or 9-hour work session (at zero extra API cost) and auto-expires cleanly when the window ends. Pass `--upstream-ping` only when routing Anthropic API traffic through `slm proxy` and you also want minimal 1-token server-side prompt-cache refresh pings during pauses.

These subcommands control daemon-level cache settings and bulk removal. They do not read or write individual entries — use the MCP tools for that. Entries written by `slm_cache_set` carry the tag `mcp-kv`, so `slm cache invalidate --tag mcp-kv` removes them, and `slm cache clear` deletes every entry for the tenant.

---

## Related skills

- `slm-compress` — for large content reduction; cache and compress work together
- `slm-status` — view `cache_kv_hits`/`cache_kv_misses` counters (daemon-persisted totals) from `slm_optimize_stats`

---

SuperLocalMemory v4.2.35 · Qualixar · AGPL-3.0-or-later

<!-- slm:no-mcp-cli:start -->
## When SLM's MCP tools are not in your tool list

Some hosts block local MCP servers by policy, and many agents, bots and agent frameworks never had them. SuperLocalMemory works the same from any shell, so this skill still applies:

- Run `slm status --json` first. Never report "SLM unavailable" only because an MCP tool is missing.
- Every MCP tool this skill names runs as `slm tool <name> --json '{...}'`, with the same arguments, checks and results: a successful call prints exactly what the MCP tool returns, and a failed one prints `"success": false` with `error.code` and `error.message`. `slm tool describe <name>` shows one tool's arguments; `slm tool list` lists the tools available right now (pictures and documents appear once they are turned on, `slm media status`).
- Every other `slm` command answers in one JSON document on stdout: add `--json` after it, put `slm --json` before it, or set `SLM_JSON=1` in the environment. `slm mcp`, `slm session` and `slm session-context` ignore `SLM_JSON` so servers and hooks keep working; give them `--json` directly. Read `success` first; a failure carries `error.code` and `error.message`. Exit code 0 means success, 1 that the command ran and failed (`error.exit_code` keeps a more specific code), 2 that it could not run, 130 that it was interrupted. Under JSON a command never asks a question: one that needs a confirmation answers `confirmation_required` and names the flag. `slm gdpr export` streams its document over several lines.
- Shortcuts for everyday work: `slm recall "<question>" --json` and `slm remember "<text>" --json`. `slm help --json` lists every command with its options.

The slm-cli skill has the full command reference.
<!-- slm:no-mcp-cli:end -->

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in ai-agents →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.