Repository avatar
AI Tools
v1.3.1
active

somnia

io.github.Cliping2077/somnia

Local-first long-term memory for AI coding agents; consolidates while idle. Scoped, quote-verified.

Documentation

Somnia

Somnia is long-term memory for AI coding agents such as Claude Code, Codex, and Gemini CLI. It keeps memories in a folder on your computer, ties each consolidated memory to a quote from the conversation it came from, and lets you review, share, or remove them in a local journal. "Sleep" is only a name: it means consolidating memories while the agent is idle (10 minutes by default). Somnia is not a sleep-health app. While the agent is idle, supported clients show a small sleeping indicator in their own interface, and typing wakes it at once.

简体中文 · ✦ Interactive 3D Dream Galaxy

Animated Somnia sleep indicators across DeepSeek Harness, Claude, Codex, Gemini, and Universal

Quick Start

Requires Node.js 22+. One command detects the AI clients on your computer, lists the files it would change, and asks before it installs anything:

npx github:Cliping2077/somnia install

First 5 minutes

  1. Install. Run the command above, choose your client, read the file list, and confirm. Then restart the client.
  2. Use it. Work as usual. Ask your agent to remember something, for example "remember that this project uses pnpm, not npm", and later ask what it remembers about the project. The agent reads and writes memories through Somnia's memory tool.
  3. Look at it. Run npx github:Cliping2077/somnia ui to open the Dream Journal on your computer. It shows each memory with its scope and, for consolidated memories, the quote it came from. You can pin, share with other clients, or remove memories, select several at once, and restore earlier snapshots.
  4. Know what leaves your computer. By default nothing does, except with DeepSeek Harness, which uses the model you picked there. Consolidating idle conversations automatically needs a model that you turn on yourself. See Privacy and data flow.
Other install options (one client, plugin marketplaces, MCP config, ZIP downloads)

Install directly for a specific client (claude, codex, gemini, dsh, cursor, windsurf):

npx github:Cliping2077/somnia install --host claude --hooks
gemini extensions install https://github.com/Cliping2077/somnia

Claude Code plugin marketplace:

/plugin marketplace add Cliping2077/somnia
/plugin install somnia@somnia-marketplace

Any MCP client that runs local stdio servers, from npm (@cliping2077/somnia):

{ "mcpServers": { "somnia": { "command": "npx", "args": ["-y", "@cliping2077/somnia"] } } }
  • DeepSeek Harness standalone bundle: Download somnia-dsh-v1.3.0.zip, extract it, and select the dsh-memory folder in Plugins → Install local bundle (DSH guide).
  • Offline multi-client ZIP: Download somnia-multi-client-v1.3.0.zip (includes Windows install-windows.cmd, macOS install-macos.command, Linux install.sh, and Chrome/Edge packages/web-sleep extension).
  • Dream Journal Web UI: npx github:Cliping2077/somnia ui (add --lang zh-CN for Chinese).

Privacy and data flow

  • Memories, episodes, snapshots, and reports are plain files under ~/.somnia/memory (or the folder you pass with --dir). Somnia has no server of its own.
  • By default no model is called, so nothing is sent anywhere. The installer prints this notice, the MCP server prints one on stderr when a model is enabled, and the Dream Journal shows which case applies at the top of the page.
  • A model is used only if you turn one on. --provider env (for somnia mcp and somnia ui) sends selected conversation excerpts and your existing memories to the provider behind the API key in your environment (SOMNIA_API_KEY, DEEPSEEK_API_KEY, OPENAI_API_KEY, ANTHROPIC_API_KEY, or GEMINI_API_KEY). --sampling asks your MCP client's own model instead.
  • DeepSeek Harness is different. Its adapter consolidates with the model you selected in Harness. If that is a remote provider, selected excerpts and memory entries are sent to it.
  • Common secrets, emails, and card numbers are redacted before anything is stored, but the filter is best-effort. Treat the store and its archives as sensitive.

Legacy v1.2 DeepSeek Harness Migration

If you used Somnia v1.2 in DeepSeek Harness, close Harness and preview or apply migration before adding other clients:

node bin/somnia.mjs migrate-dsh
node bin/somnia.mjs migrate-dsh --apply

Use node bin/somnia.mjs migrate-dsh --rollback to restore before writing new entries.

LoCoMo pilot with the DeepSeek API

This exploratory run used the Gemini-prepared Somnia v1.2.0 pre-release candidate. The consolidation prompt included examples that overlapped with the benchmark questions and was used only in the Somnia arm. The archived runner could also accept a fallback window after another window succeeded. These results are unsuitable for comparative accuracy claims about Somnia or the corrected candidate.

Context supplied to deepseek-flashQA exact matchStemmed Token F1Mean QA tokens / questionMean end-to-end tokens / question
No memory0/12 (0.0%)0.00004949
Append-only full transcript4/12 (33.3%)0.508125,39925,399
Somnia pre-release candidate (consolidated memory + retrieved excerpts)5/12 (41.7%)0.47531,5669,246

The pilot covered 12 questions across three conversations. Of the 45 requests, nine were consolidation calls. Including those calls, the candidate used 63.6% fewer tokens than the full-transcript arm in this run. Candidate aggregate report

The earlier v1.0.5 pilot used the same question selection with one consolidation call per conversation. Its Somnia arm averaged 2,004 end-to-end tokens per question, compared with 9,246 for the three-window candidate run. v1.0.5 aggregate report

After fetching LoCoMo, node eval/deepseek-pilot.mjs estimates the request budget offline. With DEEPSEEK_API_KEY set, node eval/deepseek-pilot.mjs --run --max-usd 0.60 starts a new paid pilot with the corrected runner. The command aborts if a consolidation window falls back and prints aggregates by default.

Offline LoCoMo evidence retrieval

node eval/fetch-datasets.mjs prints the download instructions for the pinned LoCoMo corpus. After downloading it, run node eval/locomo-evidence.mjs to compare recent turns, standalone BM25, and Somnia episode recall on the same questions. Each ranking gets up to 10 excerpts and 2,000 UTF-8 bytes. The evaluator checks exact annotated turn IDs. It scored 1,527 questions with verifiable evidence across 10 conversations.

Ranking in the candidate checkoutAt least one gold turnAll gold turnsMean context bytes
Recent turns17/1,52714/1,5271,599
Standalone BM251,079/1,527881/1,5271,725
Somnia episode recall1,163/1,527966/1,5271,754

With the same limits, Somnia episode recall in the earlier checkout hit at least one gold turn on 930 questions and all gold turns on 763. The tokenizer changed for both standalone BM25 and Somnia episode recall, so this check measures the combined changes in retrieval. Candidate report · Historical report

What a nap does (Sleep-Time Compute)

  1. Surprise-Gated & Stratified Replay — strips timestamp headers before scoring salience, preserves turns across all sessions without early-window truncation, and gates background idle consolidation via token-containment surprise (surpriseOf, inspired by Google Titans & Zhang arXiv:2605.12978) so trivial chatter or already-stored facts spend zero LLM tokens.
  2. Sleep-Time Precomputation & Consolidation — converts relative dates ("yesterday", "4 years ago") into explicit calendar dates, synthesizes same-entity multi-episode facts, precomputes search cues (synonyms, hypernyms, aliases) for zero-embedding recall, distills feedback guardrails & procedures, and verifies verbatim source quotes.
  3. Dream Rehearsal Gate, Downscale & Freshness — runs deterministic Pre- vs. Post-Dream synthetic rehearsal (rehearseConsolidation, inspired by Google Research SLEEP arXiv:2606.03979 & Anthropic Dreams) to seed omitted quote anchors into cues and revert destructive UPDATE operations that erase concrete facts without a change cue; unused entries fade via Ebbinghaus retention, and dynamic entries older than 24h carry [verified YYYY-MM-DD] stamps.
  4. Archive & Cross-Agent Rule Sync — rotates restorable snapshots and writes human-readable MEMORY.md mirrors. From the project directory, explicitly sync the project's rules into AGENTS.md or CLAUDE.md with node bin/somnia.mjs sync-rules --scope my-project --out AGENTS.md.

The DeepSeek Harness adapter runs consolidation in the background and can interrupt it when a new task starts. Pending episodes remain available for later attempts.

day  ──►  episodes.jsonl        (fast, 30-day replay window, never injected)
             │
        nap  ▼
        replay → consolidate → downscale → archive
             │              │
             ▼              ▼
        memory.json     snapshots/ + dream-report.md
        (slow, injected, foreground / background)

DeepSeek Harness adapter

In DSH's Plugins page, install the local bundle from this repository's packages/dsh-memory directory. Verify that its memory plugin is enabled. Memory lives in ~/.dsh/memory/:

FilePurpose
episodes.jsonlredacted recent episodes (30-day replay window, capped at 5,000 during consolidation)
memory.jsonlong-term entries available for session context
snapshots/restorable history of memory changes
dreams/YYYY-MM-DD.mdhuman-readable dream report
dream-journal.jsoncurrent or most recent consolidation phase

The memory tool includes these actions:

memory save | search | list | hide | show | forget
memory dream | wash | state | config | snapshots | restore

Why not just append?

Append-only memory rots. Entries duplicate, contradict each other, keep stale plans alive, and never forget. Every conversation makes the store a little worse.

Somnia stores the scope and source of a memory so you can see where it applies and what prompted it. The design notes document the related projects and published designs that informed it.

Design principles

  • Task first. A user message always outranks a dream.
  • Record scope. A one-off instruction can stay in the notes for its task.
  • Keep a review trail. Sources, reports, and restore let you inspect memory changes and recover earlier entries.
  • Keep the store on disk. When DSH uses a remote provider for consolidation, selected excerpts and memory entries go to that provider.
  • Redact common sensitive patterns. The filter covers common credentials, emails, and card numbers. Treat the store and its archives as sensitive.

Review without the UI

node bin/somnia.mjs state
node bin/somnia.mjs list --status foreground
node bin/somnia.mjs search "间距"
node bin/somnia.mjs snapshots
node bin/somnia.mjs restore 2026-11-17T...
node bin/somnia.mjs report
node bin/somnia.mjs sync-rules --scope my-project --out AGENTS.md

Point the CLI at the store used by the adapter to audit a dream, hide an entry, or roll back a snapshot without opening the app. npm test runs the core, mock DSH host, publication safety, and end-to-end memory tests offline.

Development and release verification

The held-out pilot instructions include an offline request estimate and a matched-context comparison protocol for plain BM25, Somnia retrieval, and Somnia with consolidation.

Use Node.js 22 or newer. Set git config core.hooksPath .githooks in the checkout to validate staged Git objects and the complete outbound commit range. New or changed media and other binary files require a separate privacy review. Run node scripts/verify-release.mjs to verify all five package archives (@somnia/core, dsh-plugin-sleep-memory, @cliping2077/somnia, claude-plugin-sleep-memory, gemini-plugin-sleep-memory) locally. The GitHub verification workflow starts only when dispatched and does not publish packages automatically.

The DSH plugin installs as a plain directory, so packages/dsh-memory carries its own copy of the core files (core.js, consolidate.js, file-memory.js). packages/core/src is the source of truth: edit it there, then run npm run sync-core. npm test fails if the copies drift.

Why "sleep"?

Somnia is long-term memory for AI coding agents. "Sleep" refers to consolidating while the agent is idle, by analogy with replay and consolidation during sleep. It is not a sleep-health app. In Somnia, a dream is a background round of selecting episodes, applying memory updates, and writing a report you can review.

Other agents

@somnia/core provides the host-independent memory engine. It takes a storage directory and a generate() function. @cliping2077/somnia exposes memory tools to compatible local clients. The DeepSeek Harness adapter connects the core to the Harness lifecycle and interface.

To port, implement the six hooks in docs/porting.md and reuse packages/core/src/somnia.js. The DSH adapter in packages/dsh-memory/index.js is the reference implementation.

Current design and how to verify it

The engine applies ADD / UPDATE / DELETE / NOOP operations. An added entry needs a scope object and traceable evidence. Somnia can demote a one-off decision to notes and can mark an older claim as superseded when a newer claim concerns the same subject and scope. See the design and attribution notes.

The machine store is memory.json; it is mirrored to a Claude-style memory/MEMORY.md index plus one markdown file per entry. Editing a file is authoritative — the next load takes the file over the JSON.

Run the verification suites (no dataset download needed):

node packages/core/test/units.mjs
node packages/dsh-memory/test-adapter.mjs
node eval/adoption-eval.mjs
node eval/integration-eval.mjs
node eval/file-sync-eval.mjs
node eval/fetch-datasets.mjs   # tells you how to fetch LoCoMo / LongMemEval-S

The evaluation scripts measure behaviors such as retrieval, source validation and restoration. Long-running conversations and the effect of memory on final answers still need broader evaluation.

What has been tested, and known limitations

Tested

  • npm test runs the offline suite: the core engine, the host adapters, the installer, the Dream Journal server, and publication safety.
  • npm run eval runs reproducible checks on bundled synthetic conversations (eval/fixtures/synthetic-conversations.json). A scripted stand-in plays the model, including deliberately wrong answers, so the checks cover Somnia's own safeguards: quote verification, conflict handling, isolation between clients and workspaces, and a local consolidation keeping each memory's origin client. It prints PASS or FAIL per check and exits with an error if one fails. It does not call a real model or measure answer quality.
  • The LoCoMo pilot and evidence-retrieval runs above are archived explorations with the caveats stated there.

Known limitations

  • The pilot data is small (12 questions), and its consolidation prompt included examples that overlap the benchmark questions, so prompt leakage is possible. It cannot support claims that Somnia answers more accurately than another approach.
  • Answer quality over long projects and long conversations has not been validated.
  • Conflict handling is checked on scripted cases. How real models handle contradictory or ambiguous statements has not been validated.
  • A wrong memory can be carried into later sessions, and into other clients if you share it. Quotes, scopes, the journal, host isolation, and snapshots help you catch and undo this, but their effectiveness at scale has not been validated.
  • A verified quote shows that the words appear in the conversation. It does not show that the memory's interpretation of them is right.
  • Redaction is pattern-based and can miss unusual secrets.
  • What gets remembered depends on the model you choose for consolidation.

License & Ownership

Copyright © 2026 @Cliping2077. Core sleep-consolidation engine (packages/core, lib, bin) is licensed under MPL-2.0; thin host adapters are licensed under MIT. See LICENSE and TRADEMARK.md.

NPM
@cliping2077/somnia
Install Command
npm install @cliping2077/somnia