remnic
Open-source memory and context for user-aware agents: scoped memory, provenance, retrieval quality, correction, boundaries, evals, and MCP/HTTP access.
Safety scan
A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.
Check it deeper on your machine
It has changed since its scan on 11 Nov 2026.
As a Claude Code plugin, install it and then ask Claude Code:
/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/joshuaswarren/remnic with scanskillsafety
Or from a terminal, clone it and run it:
git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/joshuaswarren/remnic'
It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.
Badge for your README
Markdown
[](/listings/joshuaswarren--remnic)HTML
<a href="/listings/joshuaswarren--remnic"><img src="/api/listings/joshuaswarren--remnic/badge.svg" alt="findsafeskills safety rating" /></a>Install
Install instructions from the README
As written by the repo's author. findsafeskills has not verified these steps.
The fastest judge path uses the committed synthetic mission and requires no dependency install, model call, account, or credential:
git clone https://github.com/joshuaswarren/remnic.git cd remnic node scripts/relay/judge-package.mjs serve
Open the printed loopback URL, compare the current and stale beliefs, open the X-Ray, review and approve the proposed correction, and follow the fresh agent through the passing payment test. Verify the same evidence from the terminal:
node scripts/relay/judge-package.mjs verify node scripts/verify-relay-judge-package.mjs
- **Judge package:** Linux with procfs and Node.js 22.12 or newer; Linux x64 is independently clean-room verified. - **Mission Control:** Chrome/Chromium 151 verified at desktop and mobile sizes, including keyboard-only and reduced-motion flows. - **Live isolated mission runner:** Linux x64 with Codex CLI 0.144.4 or newer and the repository development dependencies. This is not required for the judge experience. - **macOS and Windows:** use the submission video/gallery or run the verifier in a supported Linux environment. The executable verifier fails closed where equivalent filesystem-safety primitives are unavailable.
Remnic's core memory engine, integrations, and benchmark framework predate Build Week. The [submission ledger](HACKATHON.md) separates that foundation from the new Relay work. See the [judge guide](docs/remnic-relay/JUDGE-GUIDE.md) and [claim ledger](docs/remnic-relay/CLAIMS.md) for the complete evidence.
What was scanned
The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.
.claude-plugin/marketplace.json · Manifest · 20 lines
View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)
This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.
- {
- "name": "remnic",
- "owner": {
- "name": "Remnic"
- },
- "metadata": {
- "description": "Remnic — local-first AI memory for Claude Code: automatic recall, observation, and cross-agent knowledge sharing.",
- "version": "1.0.0"
- },
- "plugins": [
- {
- "name": "remnic",
- "source": "./packages/plugin-claude-code",
- "description": "Persistent long-term memory for Claude Code — wires SessionStart/UserPromptSubmit/PostToolUse hooks, MCP tools, memory skills, and the memory-review agent into a running Remnic daemon.",
- "homepage": "https://github.com/joshuaswarren/remnic",
- "category": "productivity",
- "keywords": ["memory", "recall", "observe", "mcp", "engram", "remnic"]
- }
- ]
- }
README.md · README · 580 lines
View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)
This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.
- # Remnic
- [](https://www.npmjs.com/package/@remnic/cli)
- [](LICENSE)
- [](https://github.com/sponsors/joshuaswarren)
- Open-source, local-first memory and context for AI agents. One memory store, every agent.
- Website: **[remnic.ai](https://remnic.ai)** - guide library, comparisons, benchmarks, and changelog.
- ## The projects
- Part of the Omarchy on Apple Silicon ecosystem:
- - [omarchy-mlx](https://github.com/joshuaswarren/omarchy-mlx) — MLX on the Apple GPU under Linux, and Core ML models on the Neural Engine.
- - [omarchy-ane](https://github.com/joshuaswarren/omarchy-ane) — Linux driver for the Apple Neural Engine: DRM kernel modules and libane.
- - [mil-hwx-compiler](https://github.com/joshuaswarren/mil-hwx-compiler) — compiles Core ML MIL into ANE programs on Linux (M1/M2 targets).
- - [metal2vk](https://github.com/joshuaswarren/metal2vk) — translates Metal compute kernels to Vulkan SPIR-V with open tools.
- - [mesa-1](https://github.com/joshuaswarren/mesa-1) — Mesa fork carrying the Honeykrisp Vulkan driver work for Apple silicon.
- - [omarchy-cluster](https://github.com/joshuaswarren/omarchy-cluster) — one local model split across Macs on macOS and Omarchy Linux.
- - [omarchy-apple-dev](https://github.com/joshuaswarren/omarchy-apple-dev) — build and ship iOS apps from Omarchy Linux, no Xcode or Mac.
- - [omarchy-egpu](https://github.com/joshuaswarren/omarchy-egpu) — eGPU setup, diagnostics and measured local-inference results on Omarchy Linux.
- - [ane-linux-experiments](https://github.com/joshuaswarren/ane-linux-experiments) — Neural Engine on Linux: verified primitives, receipt-backed macOS parity.
- - [coreglass](https://github.com/joshuaswarren/coreglass) — profiler that shows where local inference loses speed on Apple Silicon Linux.
- - [omarchy-inference-fleet](https://github.com/joshuaswarren/omarchy-inference-fleet) — reproducible, pinned single-node MLX inference baselines.
- - Platform upstream: [omarchy-mac](https://github.com/omacom/omarchy-mac) — Omarchy on Apple Silicon Macs.
- <!-- end The projects -->
- - **Your files, your machine.** Memory records are plain markdown files with YAML frontmatter on your disk. Remnic also keeps local JSON and SQLite state; it does not require an external database service. `cat`, `grep`, edit, and version-control your memory files with the tools you already use.
- - **One memory across every tool.** OpenClaw, Claude Code, Codex CLI, Cursor, ChatGPT (developer mode), Hermes, Replit, Pi, omp, Factory Droid, and any MCP client read and write the same store. Tell one agent a preference; every agent knows it.
- - **Automatic extraction and recall.** Remnic watches conversations, distills durable knowledge, and injects the right context back when it is needed.
- - **Sharp retrieval.** Hybrid search (BM25 + vector + reranking) over rebuildable indexes, with graph recall, memory-worth scoring, and per-result provenance you can inspect.
- - **MIT licensed.** Free, open, and built to be forked.
- <!-- BEGIN BUILD FOR GOOD 2026 HIGHLIGHT -->
- ## Build for Good 2026: What Helps Me
- **Explain what helps once. Share only what you choose. Stop sharing at any time.**
- What Helps Me is a private support passport built on Remnic. It turns selected
- memories into short first-person cards. The owner reviews every word before a
- helper can see it.
- No OpenAI API key is required. Manual cards need no model. Draft and question
- calls use the owner's existing Remnic route, including an OpenClaw gateway or a
- local model.
- [Watch the narrated 102-second product story](docs/hackathons/assets/what-helps-me/demo.webm)
- or read the [full Build for Good entry](docs/hackathons/build-for-good-2026.md).
- The walkthrough always shows a **Synthetic replay** banner. It is not live-call
- proof. The separate live runner exercises the real standalone server and model
- flow. Its receipt validator checks internal consistency, not independent proof.
- ### What we built
- - An owner workspace for selecting exact memories, drafting cards, editing each
- draft, and approving each card.
- - Exact-version share links that last from five minutes through seven days.
- - A helper view that shows approved cards only and cites the card behind each
- grounded answer.
- - Immediate **Stop sharing** controls. Every helper request checks durable grant
- state again.
- - A provider-neutral model path. It uses Remnic's existing OpenClaw gateway,
- local, compatible remote, and optional direct OpenAI routes.
- - A strict live run record for draft, approval, sharing, question, revocation,
- and the final locked read. It stores no private text, secrets, or raw model IDs.
- The framing comes from [NHS England's health and care passport guidance](https://www.england.nhs.uk/long-read/health-and-care-passports-implementation-guidance/).
- The NHS guidance says the person owns the passport, chooses its contents, and
- chooses who sees it. What Helps Me applies those rules to a broader
- self-advocacy tool. It is not a medical record, care plan, IEP, diagnosis tool,
- or emergency guide.
- ### Who it helps
- What Helps Me is for people who often need to explain how others can support
- them. It also helps trusted helpers act on clear, current guidance without
- seeing the person's full memory store.
- ### How it will be used
- 1. The owner selects one to 20 notes.
- 2. The owner checks a clear consent box or writes a card by hand.
- 3. The configured model drafts up to eight cards.
- 4. The owner edits and approves each card.
- 5. The owner shares exact card versions for a set time.
- 6. The helper reads the guide or asks a grounded question.
- 7. The owner selects **Stop sharing** to lock the link.
- The model is the scribe. The person is the author.
- ### How Codex helped
- Codex traced Remnic's existing memory, model, HTTP, MCP, and browser contracts.
- It then built the feature as a seven-layer PR stack. Codex also wrote adversarial
- tests, checked WCAG states at four widths, and built the privacy-safe live run
- record. The owner approval and revocation rules remain deterministic core
- code. A model cannot bypass them.
- ### How to run the project
- Run the no-key synthetic walkthrough in about five minutes:
- ```bash
- git clone https://github.com/joshuaswarren/remnic.git
- cd remnic
- pnpm install --frozen-lockfile
- pnpm exec playwright install chromium
- npm run demo:support-passport:replay
- ```
- Open the printed loopback URL. The replay uses synthetic data and labels itself
- on every screen.
- Run the standalone live flow with a local, direct, or compatible model route:
- ```bash
- npm run demo:support-passport:live -- \
- --config ./remnic.config.json \
- --output ./tmp/support-passport-demo
- npm run demo:support-passport:validate-receipt -- \
- --receipt ./tmp/support-passport-demo/receipt.json
- ```
- The validator checks the self-reported receipt schema and hash consistency. It
- does not convert that receipt into independent attestation.
- For an existing OpenClaw install, keep the current gateway providers and model
- auth. Enable the feature, owner HTTP bridge, and gateway route in
- `openclaw.json`:
- ```jsonc
- {
- "plugins": {
- "entries": {
- "openclaw-remnic": {
- "config": {
- "modelSource": "gateway",
- "openaiApiKey": false,
- "supportPassport": { "enabled": true },
- "agentAccessHttp": {
- "enabled": true,
- "host": "127.0.0.1",
- "port": 4318,
- "authToken": "${OPENCLAW_REMNIC_ACCESS_TOKEN}",
- "principal": "passport-owner"
- }
- }
- }
- }
- }
- }
- ```
- Set `OPENCLAW_REMNIC_ACCESS_TOKEN` to a private local bearer token. This token
- protects the browser bridge. It is not a model provider key. Open
- `/remnic/ui/what-helps-me/` on the configured Remnic HTTP origin. Remnic uses
- the OpenClaw gateway model chain and its existing provider auth.
- The standalone live runner does not boot an OpenClaw host. Use the real browser
- flow above to exercise an existing OpenClaw gateway setup. No OpenAI API key is
- required. Manual cards and sharing need no model. Draft and question requests
- return `503 provider_unavailable` when no model route is configured.
- <!-- END BUILD FOR GOOD 2026 HIGHLIGHT -->
- <!-- BEGIN OPENAI BUILD WEEK 2026 HIGHLIGHT — temporary submission section -->
- ## OpenAI Build Week 2026: Remnic Relay
- **Correct once. Every agent learns.**
- Remnic is shared memory for AI agents. **Remnic Relay** is the human-governed
- correction loop we built for OpenAI Build Week: it exposes the stale belief
- behind an agent failure, shows where that belief came from, puts the proposed
- replacement behind human approval, and proves a brand-new agent learned the
- approved correction from Remnic.
- The demonstration follows an online-payment failure. One Codex agent reads the
- current rule while another confidently applies an older retry rule. Relay opens
- an evidence X-Ray connecting the recalled memory to the failing test, presents
- a before-and-after memory diff for approval, preserves the old belief as
- superseded, and then starts a fresh agent with no handoff. The mission is only
- complete when that agent recalls the replacement and turns the same payment
- test green.
- ### What we built during Build Week
- - a versioned contract for conflicts, evidence, corrections, lineage, and
- fresh-agent verification;
- - a human-gated correction engine with append-only supersession;
- - Mission Control views for conflict inspection, evidence X-Ray, approval,
- propagation, and the final mission receipt;
- - an isolated four-role Codex mission runner using only a cleared synthetic
- Remnic instance; and
- - a dependency-free judge package that binds the recorded agent run, product
- UI, synthetic fixture, and verification receipt into one reproducible story.
- ### How Codex and GPT-5.6 were used
- Codex collaborated across the new extension: contract modeling, correction
- engine, Mission Control, isolated runner, adversarial tests, evidence sealing,
- and judge packaging. GPT-5.6 also powers the demonstrated product workflow
- itself through four isolated Codex roles: Scout reads the accepted rule, a
- Builder acts on stale memory, a correction agent proposes the replacement, and
- a fresh Builder proves the approved memory propagated without an agent
- handoff. Agents propose; a human approves; the test proves the result.
- ### Install, supported platforms, and testing
- The fastest judge path uses the committed synthetic mission and requires no
- dependency install, model call, account, or credential:
- ```bash
- git clone https://github.com/joshuaswarren/remnic.git
- cd remnic
- node scripts/relay/judge-package.mjs serve
- ```
- Open the printed loopback URL, compare the current and stale beliefs, open the
- X-Ray, review and approve the proposed correction, and follow the fresh agent
- through the passing payment test. Verify the same evidence from the terminal:
- ```bash
- node scripts/relay/judge-package.mjs verify
- node scripts/verify-relay-judge-package.mjs
- ```
- - **Judge package:** Linux with procfs and Node.js 22.12 or newer; Linux x64 is
- independently clean-room verified.
- - **Mission Control:** Chrome/Chromium 151 verified at desktop and mobile
- sizes, including keyboard-only and reduced-motion flows.
- - **Live isolated mission runner:** Linux x64 with Codex CLI 0.144.4 or newer
- and the repository development dependencies. This is not required for the
- judge experience.
- - **macOS and Windows:** use the submission video/gallery or run the verifier
- in a supported Linux environment. The executable verifier fails closed where
- equivalent filesystem-safety primitives are unavailable.
- Remnic's core memory engine, integrations, and benchmark framework predate
- Build Week. The [submission ledger](HACKATHON.md) separates that foundation
- from the new Relay work. See the [judge guide](docs/remnic-relay/JUDGE-GUIDE.md)
- and [claim ledger](docs/remnic-relay/CLAIMS.md) for the complete evidence.
- <!-- END OPENAI BUILD WEEK 2026 HIGHLIGHT -->
- ## Why Remnic
- Most agents do not fail because they lack another prompt. They fail because they do not understand the user, the project, the boundaries, or what "good" means in context. Every session starts from zero: the agent forgets your name, your projects, the decisions you already made, and the bugs you already debugged. You re-explain the same context over and over, and the agent still repeats the same mistakes.
- There is a useful split in AI memory between **memory backends** (extract facts, store vectors, retrieve relevant ones) and **context substrates** (human-readable context that accumulates and compounds across sessions). Most tools pick one camp. Remnic does both:
- - **The files are the source of truth.** The hybrid search index is downstream of your markdown, fully rebuildable from disk, never authoritative itself.
- - **Recall stays sharp.** Three retrieval tiers, opt-in graph traversal, memory-worth scoring that filters low-value facts before they reach the model, and temporal supersession that keeps stale facts out.
- - **It compounds.** Background consolidation merges duplicates, promotes recurring themes, and snapshots page versions on every overwrite. The longer you use it, the better it gets, and you can always read exactly what it knows.
- | Without Remnic | With Remnic |
- |---|---|
- | Re-explain who you are and what you are working on | The agent recalls your identity, projects, and preferences automatically |
- | Repeat context for every task | Entity knowledge surfaces people, projects, tools, and relationships on demand |
- | Lose debugging and research context between sessions | Past root causes, dead ends, and findings are recalled, so work is not repeated |
- | Manually restate preferences every session | Preferences persist across sessions, agents, and projects |
- | A context-switching tax when you resume work | Session-start recall brings you back up to speed |
- | Built-in agent memory that does not scale | Hybrid search, lifecycle management, namespaces, and governance |
- | Third-party memory services that cost money and hold your data | Local memory files, with model and integration routes you control |
- ## How Remnic compares
- Most alternatives trade away at least one of local-first storage, a free license, or multi-host support; Remnic combines all three in one package.
- | Option | Hosting | Price | Agent coverage | Storage |
- |---|---|---|---|---|
- | Remnic | Local-first | Free (MIT) | Native plugins for Claude Code, Codex CLI, Pi, OpenClaw, Hermes, plus any MCP client | Markdown + YAML, rebuildable index |
- | mem0 | Cloud / self-host | Freemium | SDK / API | Vectors / database |
- | Letta (MemGPT) | Cloud / self-host | Freemium | API | Database-backed |
- | Zep (Graphiti) | Cloud / self-host | Freemium | SDK / API | Graph database |
- | Supermemory | Cloud | Paid | API | Hosting handled by the service |
- | MemPalace | Local | Free | Single host | Local |
- | ChatGPT memory | Cloud | Bundled | Single tool | Opaque |
- Hosting and price labels mirror the canonical matrix at [remnic.ai/compare](https://remnic.ai/compare), which also carries the per-competitor teardowns. Importers for mem0, Supermemory, ChatGPT, Claude, and Gemini: [remnic.ai/import](https://remnic.ai/import).
- ## Quick start
- ### Prerequisites
- - [Node.js](https://nodejs.org/) 22.12 or newer.
- - A model provider for extraction (an OpenAI API key, the OpenClaw gateway model chain, or a [local LLM](docs/guides/local-llm.md)). Retrieval-only mode needs none of these.
- - Optional but recommended: [QMD](https://github.com/tobi/qmd) for the highest-quality hybrid search. Without it, Remnic falls back to embedding search and then recency-ordered reads.
- ### Any agent (standalone)
- Install the CLI, start the daemon, and verify it is running.
- ```bash
- npm install -g @remnic/cli # installs `remnic` (plus the legacy `engram` forwarder)
- remnic init # write remnic.config.json
- export OPENAI_API_KEY=sk-... # extraction provider (or route to a local LLM)
- export REMNIC_AUTH_TOKEN=$(openssl rand -hex 32)
- remnic daemon start # start the background server
- remnic status # confirm it is running
- remnic query "hello" --explain # test a query with the tier breakdown
- ```
- `remnic query --explain` prints which retrieval tier produced each result and why, so you can watch the memory pipeline work on your very first query. Run `remnic doctor` any time to check your setup, then connect a tool from the table below. Full five-minute walkthrough: [docs/guides/quickstart.md](docs/guides/quickstart.md).
- ### OpenClaw (native plugin)
- OpenClaw gets the deepest integration: a memory-slot plugin that recalls every session and observes every response.
- ```bash
- openclaw plugins install clawhub:@remnic/plugin-openclaw # install the plugin
- remnic openclaw install # wire the memory slot in openclaw.json
- launchctl kickstart -k gui/$(id -u)/ai.openclaw.gateway # restart the OpenClaw gateway (macOS)
- remnic doctor # verify every check passes
- ```
- `remnic openclaw install` writes `plugins.entries["openclaw-remnic"]` and sets `plugins.slots.memory = "openclaw-remnic"` in `~/.openclaw/openclaw.json`. Without the slot, OpenClaw skips plugin registration and no hooks fire, so `remnic doctor` checks the slot explicitly and points you at the fix. After the restart, confirm the plugin is live:
- ```bash
- grep "gateway_start fired" ~/.openclaw/logs/gateway.log
- ```
- A matching line means Remnic is active and hooks are firing. (The `[engram]` log prefix remains during the v1.x compatibility window.)
- Prefer to let the agent do it? Tell any OpenClaw agent: *"Install the @remnic/plugin-openclaw plugin and configure it as my memory system."* It runs the install, updates `openclaw.json`, and restarts the gateway for you. Comprehensive install and first-run guide, including QMD setup: [docs/getting-started.md](docs/getting-started.md).
- ## Works with your tools
- One store, many front doors. Each integration reads and writes the same memory on your machine, so a preference you state in one tool is available in all of them.
- | Tool | Integration | Recall / observe | Docs |
- |------|-------------|------------------|------|
- | OpenClaw | Native memory-slot plugin | Every session / every response | [docs/plugins/openclaw.md](docs/plugins/openclaw.md) |
- | Claude Code | Native hooks + MCP | Every prompt / every tool use | [docs/plugins/claude-code.md](docs/plugins/claude-code.md) |
- | Codex CLI | Native hooks + MCP + memory extension | Every prompt / every tool use | [docs/plugins/codex.md](docs/plugins/codex.md) |
- | ChatGPT (developer mode) | MCP + OAuth 2.1 on your own server | On demand | [docs/integration/chatgpt.md](docs/integration/chatgpt.md) |
- | Cursor | Generic MCP client | On demand | [docs/integration/connector-setup.md](docs/integration/connector-setup.md) |
- | Hermes | Python `MemoryProvider` | Every LLM call / every turn | [docs/plugins/hermes.md](docs/plugins/hermes.md) |
- | Replit | MCP | On demand | [docs/plugins/replit.md](docs/plugins/replit.md) |
- | Pi Coding Agent | Native extension + MCP + compaction | Every turn / every turn | [docs/integration/pi.md](docs/integration/pi.md) |
- | Oh My Pi (omp) | Native extension + MCP | Every turn / every turn | [docs/integration/omp.md](docs/integration/omp.md) |
- | Factory Droid | HTTP MCP + bearer auth | On demand | [docs/integration/droid.md](docs/integration/droid.md) |
- | Any MCP client | HTTP or stdio MCP | On demand | [docs/integration/connector-setup.md](docs/integration/connector-setup.md) |
- Once the daemon is running, register each tool with a single command:
- ```bash
- remnic connectors install codex-cli # token + connector state + memory extension
- remnic connectors install claude-code # token + connector state
- remnic connectors install pi # token + connector state
- remnic connectors install omp # token + connector state
- remnic connectors install replit # token + connector state
- remnic connectors install droid # token + connector state + ~/.factory/mcp.json
- ```
- Each install mints a host-specific auth token and records Remnic-side connector state; for some hosts (such as Codex CLI) it also materializes the memory extension. How much of the host itself gets configured varies — Claude Code and Hermes, for example, need a few manual wiring steps documented in their plugin guides. See the [connector setup guide](docs/integration/connector-setup.md) for every tool, exactly what its install automates, its config snippet, and multi-tenant setups.
- Over MCP, Remnic exposes a rich tool surface beyond store and recall: entity lookup, memory correction, temporal recall, X-ray provenance, daily briefing, work-board, and continuity tools among them. Hosted clients call these directly, and the standalone HTTP endpoint (`remnic daemon start` or `@remnic/server`) serves the same tools. See the [HTTP + MCP API reference](docs/api.md).
- ## How it works
- Remnic runs a continuous three-phase loop around every agent conversation:
- ```
- Recall -> Before a conversation, inject the relevant memories into context
- Buffer -> After each turn, accumulate content until a trigger fires
- Extract -> Periodically, distill structured memories with an LLM and write them to disk
- ```
- - **Recall** ranks your stored memories against the incoming context and injects a budgeted slice back into the prompt. Extraction and rerank can run through the OpenClaw gateway model chain, OpenAI (Responses API), or a local LLM. See [docs/guides/cost-control.md](docs/guides/cost-control.md).
- - **Buffer** accumulates conversation turns until a size or time trigger fires, so extraction runs on meaningful spans rather than on every message.
- - **Extract** distills durable knowledge, runs it through an importance judge, and writes accepted memories to disk. The search index is then rebuilt from those files.
- ```mermaid
- flowchart LR
- A[Agent session] -->|recall| B[Memory store<br/>markdown + YAML]
- A -->|buffer turns| C[Extraction]
- C -->|write memories| B
- B -->|index| D[Hybrid search<br/>BM25 + vector + rerank]
- D -->|rank + explain| A
- ```
- Each memory is a portable markdown file with YAML frontmatter, so it stays git-friendly and readable with no database required:
- ```yaml
- ---
- id: decision-1738789200000-a1b2
- category: decision
- confidence: 0.92
- tags: ["architecture", "search"]
- ---
- Use the port/adapter pattern for search backends so alternative engines
- can replace the default index without changing core logic.
- ```
- Categories include `fact`, `decision`, `preference`, `correction`, `relationship`, `principle`, `commitment`, `skill`, and `rule`. Files are organized on disk under your configured memory directory:
- ```
- <memoryDir>/
- facts/ extracted facts, decisions, preferences, corrections, ...
- entities/ people, projects, tools, and their relationships
- profile.md the accumulated user profile
- ```
- The search index lives separately and is rebuildable from these files at any time. The full storage model and retrieval flow are in [docs/architecture/overview.md](docs/architecture/overview.md).
- ## Feature highlights
- **Core memory.** LLM extraction that separates durable knowledge from conversational noise, entity tracking for people, projects, tools, and relationships, a full write/consolidate/expire lifecycle, and importance gating that drops low-value facts before they are ever stored. See [docs/architecture/memory-lifecycle.md](docs/architecture/memory-lifecycle.md).
- **Search.** Six pluggable backends behind one interface: QMD, [Orama](https://oramasearch.com/), LanceDB, Meilisearch, a remote adapter, and a no-op. QMD is the default and highest-quality option, combining BM25, vector, and reranking. Any backend is rebuildable from your markdown at any time. See [docs/search-backends.md](docs/search-backends.md).
- **Memory OS.** [Namespaces](docs/namespaces.md) for multi-agent and multi-tenant isolation (opt-in via `namespacesEnabled`, default `false`), hot/cold [tiering](docs/retention-policy.md) driven by a value-score model, background consolidation via the ["dreams" surface](docs/dreams.md), opt-in [graph reasoning](docs/architecture/graph-reasoning.md) with Personalized PageRank, and transparent AES-256-GCM [at-rest encryption](docs/encryption.md) (opt-in via `secureStoreEnabled`, default `false`).
- **Lossless Context Management.** Archive full session transcripts and recall them losslessly through the daemon recall envelope, for when a summary is not enough. Opt-in via `lcmEnabled`, default `false`. See [docs/guides/lossless-context-management.md](docs/guides/lossless-context-management.md).
- **Trust and boundaries.** Scoped memory, provenance on every fact, correction handling, and boundary principles that decide when an agent should ask instead of act. See [docs/user-aware-agents.md](docs/user-aware-agents.md).
- **Import your memory.** Seven optional importers pull existing memory from the tools you already use. The base CLI never bundles them; install only what you need, and every run supports `--dry-run` for a zero-write preview.
- | Source | Package | Adapter |
- |--------|---------|---------|
- | ChatGPT | `@remnic/import-chatgpt` | `remnic import --adapter chatgpt` |
- | Claude | `@remnic/import-claude` | `remnic import --adapter claude` |
- | Gemini | `@remnic/import-gemini` | `remnic import --adapter gemini` |
- | mem0 | `@remnic/import-mem0` | `remnic import --adapter mem0` |
- | Supermemory | `@remnic/import-supermemory` | `remnic import --adapter supermemory` |
- | WeClone | `@remnic/import-weclone` | `openclaw engram bulk-import --source weclone` |
- | lossless-claw | `@remnic/import-lossless-claw` | `remnic import-lossless-claw` |
- See [docs/importers.md](docs/importers.md) for input formats, provenance metadata, and the full privacy breakdown.
- **Open Knowledge Format (OKF).** The memory directory doubles as an OKF v0.1 knowledge bundle: every memory file ships an inert `type` field next to Remnic's canonical `category`, so OKF-aware consumers can read your store without a converter. `category` stays authoritative — `type` is interop metadata and never overrides it on parse. These commands inspect, repair, and export the bundle:
- | Command | What it does |
- |---------|--------------|
- | `remnic okf lint` | Report files missing frontmatter or `type`; exit 1 when findings remain (`--json` for machine output) |
- | `remnic okf sweep` | Backfill missing `type` values from `category` without bumping `updated` (opt-in via `okf.sweepEnabled`) |
- | `remnic export okf --out <dir>` | Export a portable OKF v0.1 knowledge bundle (plaintext interchange; not a capsule) |
- Config gates, lint finding codes, and the full category-to-type mapping: [docs/okf.md](docs/okf.md).
- **Live connectors: Google Drive and Notion.** Beyond one-time imports, Remnic can *continuously* sync external sources into memory. The Google Drive and Notion connectors poll for changed documents on a schedule and ingest them incrementally — connect once (`remnic connectors run google-drive` / `remnic connectors run notion` for a manual sync, `remnic connectors status` to inspect), and your docs stay searchable alongside everything else your agents know. Gmail and GitHub connectors run on the hosted scheduler as well. Setup, OAuth, and polling details: [docs/live-connectors.md](docs/live-connectors.md).
- **Wearables.** Three optional connectors ingest AI-wearable recordings, clean and speaker-label the transcripts, apply your personal corrections, store searchable per-day transcript files, and create memories under strict per-source trust gates: `@remnic/connector-limitless` (Limitless Pendant), `@remnic/connector-bee` (Bee bracelet), and `@remnic/connector-omi` (Omi necklace). See [docs/wearables.md](docs/wearables.md).
- **Glass-box tooling.** [Recall X-ray](docs/xray.md) shows which retrieval tier produced each result and why, the [daily briefing](docs/guides/daily-briefing.md) surfaces active entities and open commitments, and the [operator console](docs/console.md) gives live engine introspection with trace record and replay.
- **Benchmarks.** Memory quality is measured, not asserted. [MemCorrect](docs/benchmarks/memcorrect.md) checks whether a backend recalls the right fact, accepts a correction, and stops serving the stale one. The [full benchmark suite](docs/benchmarks.md) covers the rest, with reproducible artifacts and leaderboard safety.
- **More capabilities.** A few of the deeper features, each with its own guide:
- - [Procedural memory](docs/procedural-memory.md) — multi-step runbooks captured from your work (on by default outside the `conservative` preset).
- - [Temporal recall](docs/temporal-recall.md) — `valid_at` / `invalid_at` fact lifecycle and an `as_of` recall filter.
- - [Pattern reinforcement](docs/pattern-reinforcement.md) — cross-session pattern detection with a recall boost for reinforced primitives.
- - [Shared context](docs/shared-context.md) — cross-agent shared intelligence for multi-agent teams.
- - [Coding-agent memory](docs/coding-agent.md) — repo conventions, review behavior, and ask-before rules for coding tools.
- ## Privacy and your data
- Memory records live in your configured directory. Local-first storage does not make every model or integration local-only.
- - Remnic stores memories as Markdown, alongside local indexes and other state. You can inspect, back up, and version-control the files.
- - Model calls follow your configuration. The local LLM route is **fail-open by default**; the `local-llm-heavy` preset does not disable cloud fallback.
- - For local-only use, check model routing, fallback, embeddings, reranking, briefing follow-ups, search backends, and connected clients separately. The [accessibility and privacy guide](ACCESSIBILITY.md#local-only-use-and-privacy) explains the limits and current verification status.
- - Hosted clients process memories they receive through Remnic's tools. Connectors, remote services, and deliberate sharing add their own data flows.
- - **Keep user data out of git.** Paths that contain memory content (`facts/`, `entities/`, `profile.md`) should never be committed. Enable [at-rest encryption](docs/encryption.md) if the disk itself is untrusted.
- ## Architecture
- Remnic is a [pnpm](https://pnpm.io/) monorepo of **25+ published packages**. The engine is host-agnostic; every integration is a thin adapter over it, so standalone Remnic is always first-class and adapter work follows each host's upstream SDK rather than recreating host behavior inside Remnic.
- ```text
- @remnic/core
- (extraction, storage, search,
- graph, trust, consolidation)
- |
- +-------------------+-------------------+
- | | |
- @remnic/cli @remnic/server plugins
- (remnic bin) (HTTP + MCP) openclaw, claude-code,
- codex, pi, hermes
- |
- a la carte add-ons
- import-* (7 importers) + connector-*
- (3 wearable sources)
- ```
- - **Engine:** `@remnic/core` (the framework-agnostic memory engine), `@remnic/cli` (the standalone `remnic` binary), and `@remnic/server` (HTTP + MCP server).
- - **Plugins:** native adapters for OpenClaw, Claude Code, Codex, and Pi, plus Hermes shipped as `remnic-hermes` on PyPI.
- - **A la carte:** seven `@remnic/import-*` importers and three `@remnic/connector-*` wearable connectors, installed only when you need them.
- - **Benchmarks:** `@remnic/bench` provides the published suites and CI regression gates.
- The complete package map, dependency graph, and publish order are in [docs/architecture/monorepo-structure.md](docs/architecture/monorepo-structure.md).
- ## Configuration
- `remnic init` writes `./remnic.config.json` with separate `remnic` and `server` blocks.
- The generated file references `OPENAI_API_KEY` and `REMNIC_AUTH_TOKEN`; configure those
- variables or replace the provider and auth settings for your setup. Four optional
- `memoryOsPreset` values seed defaults before explicit settings override them:
- - `conservative` keeps the footprint small and disables reranking, graph features, and procedural memory.
- - `balanced` is a general-purpose preset, selected explicitly by `remnic init`.
- - `research-max` enables graph and experimental learning features, but not every optional subsystem.
- - `local-llm-heavy` — tuned for local-model extraction and rerank.
- Without `memoryOsPreset`, the parser uses individual setting defaults rather than
- applying `balanced`. Extraction routing (`gateway`, OpenAI, or a local LLM), recall
- budget, search backend, lifecycle, namespaces, and encryption are all configurable.
- See [docs/config-reference.md](docs/config-reference.md) for config keys, defaults,
- and operator guidance.
- ## Self-hosting and operators
- Running Remnic for a team or across machines? `remnic daemon start` hands off to launchd or systemd when a service is installed, and `@remnic/server` exposes the same memory over HTTP + MCP for remote agents. Namespaces isolate tenants, and the standalone server supports multi-tenant, multi-harness setups.
- - [Standalone server guide](docs/guides/standalone-server.md) — multi-tenant setup and connecting multiple harnesses.
- - [Deployment topologies](docs/integration/deployment-topologies.md) — localhost, LAN, remote, and containerized layouts.
- - [Operations](docs/operations.md) — backups, exports, hourly summaries, and logs.
- ## Documentation
- The complete, organized docs hub lives at **[docs/README.md](docs/README.md)**. Starting points by journey:
- - **Start here:** [Quickstart](docs/guides/quickstart.md) - [Getting started](docs/getting-started.md) - [CLI reference](docs/cli.md)
- - [Accessibility](ACCESSIBILITY.md) covers helpful features, privacy controls, testing limits, and feedback.
- - [How I use Remnic every day](docs/DAILY-USE.md) is a 30-day log of retained memories with recent recall timing, the command behind each number, and what is not measured.
- - [Community numbers](docs/COMMUNITY-NUMBERS.md) counts stars, forks, and contributors, with the source and date behind each figure.
- - **Connect your tools:** [Connector setup](docs/integration/connector-setup.md) - [ChatGPT](docs/integration/chatgpt.md) - [Plugins index](docs/plugins/README.md) - [Deployment topologies](docs/integration/deployment-topologies.md)
- - **Configure:** [Config reference](docs/config-reference.md) - [Search backends](docs/search-backends.md) - [Local LLM](docs/guides/local-llm.md) - [Cost control](docs/guides/cost-control.md)
- - **Operate:** [Operations](docs/operations.md) - [Retention policy](docs/retention-policy.md) - [Import / export](docs/import-export.md) - [Standalone server](docs/guides/standalone-server.md)
- - **Internals:** [Architecture overview](docs/architecture/overview.md) - [Retrieval pipeline](docs/architecture/retrieval-pipeline.md) - [Memory lifecycle](docs/architecture/memory-lifecycle.md) - [HTTP + MCP API](docs/api.md)
- The website publishes the [guide library](https://remnic.ai/guides) (what is AI agent memory, MCP memory servers, Claude Code memory), the [comparison pages](https://remnic.ai/compare), the [benchmarks report](https://remnic.ai/benchmarks), and the [changelog](https://remnic.ai/changelog).
- ## FAQ
- **Do I need OpenClaw?** No. Remnic runs standalone through `@remnic/cli` and connects to any tool over MCP or HTTP. OpenClaw simply gets the deepest native integration.
- **Does it work offline or without an API key?** Local file retrieval can work without a model provider. Extraction needs a model. A [local LLM](docs/guides/local-llm.md) can serve it, but fallback and other configured routes need separate checks before claiming local-only operation.
- **Where is my data?** Memory records live under your configured memory directory. Models, search services, hosted clients, connectors, and sharing can send data elsewhere. See [Privacy and your data](#privacy-and-your-data).
- **How much does it cost?** The software is MIT and free. Your only cost is your chosen extraction provider, which is zero when you use a local LLM.
- **Do I need QMD?** No, but it gives the best search. Without it, Remnic falls back to embedding search and then recency-ordered reads.
- **Can multiple agents share one memory?** Yes. Every connected tool reads and writes the same store, and [namespaces](docs/namespaces.md) isolate tenants when you want separation.
- **Is it production-ready?** Remnic is extensively tested with CI regression gates and a published benchmark suite. See [docs/benchmarks.md](docs/benchmarks.md) for the evidence.
- **I was using Engram.** Everything still works. See [Engram to Remnic](#engram-to-remnic) below for the migration path.
- ## Engram to Remnic
- Engram is now Remnic. Canonical packages live under the `@remnic/*` scope, and OpenClaw installs use [`@remnic/plugin-openclaw`](https://www.npmjs.com/package/@remnic/plugin-openclaw). The legacy `engram` CLI name, the `openclaw engram` command namespace, and the `/engram/v1/...` HTTP paths remain available as a compatibility surface during the rename window. Migrating an existing install? Run `remnic openclaw migrate-engram --yes`, which backs up the legacy extension, installs the new plugin, preserves your `memoryDir`, and switches the memory slot. Full steps: [Engram to Remnic migration guide](docs/guides/openclaw-engram-to-remnic.md).
- Read [Accessibility](ACCESSIBILITY.md) for useful features, privacy limits, and the local-model checks marked Measured or Not measured.
- - [Feature roadmap (GitHub Project)](https://github.com/users/joshuaswarren/projects/1) — current priority order, blockers, and next work.
- - [Issues](https://github.com/joshuaswarren/remnic/issues) — report a bug or request a feature.
- - [Contributing](CONTRIBUTING.md) — how to build Remnic and open a pull request.
- - [Contributors](CONTRIBUTORS.md) — every outside contributor and what they built.
- ## Support
- Every bit of support helps keep Remnic alive and free. If you are able, [sponsor on GitHub](https://github.com/sponsors/joshuaswarren) or send a Lightning donation to `joshuaswarren@strike.me` to directly fund continued development and new integrations.
- [](https://github.com/sponsors/joshuaswarren)
- If financial support is not an option, you can still make a big difference: [star the repo](https://github.com/joshuaswarren/remnic), share it, or recommend it to a colleague. Word of mouth is how most people find Remnic.
- ## Contributing
- Contributions from humans and AI-assisted contributors are welcome. Start with [CONTRIBUTING.md](CONTRIBUTING.md) for setup, the preflight gate, and PR expectations. Deeper references: [docs/development/contributing.md](docs/development/contributing.md) and [docs/CONVENTIONS.md](docs/CONVENTIONS.md).
- ## License
- [MIT](LICENSE)
packages/plugin-claude-code/hooks/bin/remnic-cc-hook.test.cjs · Bundled script · 1,021 lines · 2 findings marked
- "use strict";
- // Integration tests for the unified Claude Code hook runner (issue #1518).
- // Each test spawns the real remnic-cc-hook.cjs against a mock Remnic HTTP
- // server, with an isolated HOME/XDG_STATE_HOME, and asserts both the emitted
- // hook JSON and the cursor/observe side effects. These tests cover the
- // cross-platform failure classes called out in #1518:
- // - shell-metacharacter session ids are rejected (no shell injection vector)
- // - short prompts skipped, no-token skipped, dead-daemon guidance
- // - cursor retention on failed final flush (no data loss)
- // - payload via stdin (not env) so large edits do not E2BIG on Windows
- // - hooks.json uses exec form (command + args) so Windows works without
- // Git Bash and shell metacharacters in the plugin root cannot inject
- const assert = require("node:assert/strict");
- const test = require("node:test");
- const http = require("node:http");
- const fs = require("node:fs");
- const os = require("node:os");
- const path = require("node:path");
- const { spawn } = require("node:child_process");
- const RUNNER = path.join(__dirname, "remnic-cc-hook.cjs");
- // Shared runner source (issue #2483): implementation-detail assertions read
- // the core, while behavioral tests spawn the wrapper entry (RUNNER).
- const CORE = path.join(__dirname, "remnic-hook-core.cjs");
- function startServer(handler) {
- const calls = [];
- const server = http.createServer((req, res) => {
- let body = "";
- req.on("data", (c) => (body += c));
- req.on("end", () => {
- let parsed = null;
- try {
- parsed = body ? JSON.parse(body) : null;
- } catch {
- parsed = body;
- }
- calls.push({ method: req.method, url: req.url, body: parsed });
- handler(req, res, parsed);
- });
- });
- return new Promise((resolve) => {
- server.listen(0, "127.0.0.1", () => {
- resolve({ server, port: server.address().port, calls });
- });
- });
- }
- function mkHome() {
- const dir = fs.mkdtempSync(path.join(os.tmpdir(), "remnic-cc-test-"));
- return dir;
- }
- // Async spawn (NOT spawnSync) so the in-process mock HTTP server's event loop
- // stays free to answer the runner's requests while it runs.
- function runHook(event, input, { port, home, env = {} } = {}) {
- return new Promise((resolve) => {
- const child = spawn(process.execPath, [RUNNER, event], {
- env: {
- ...process.env,
- HOME: home,
- USERPROFILE: home,
- XDG_STATE_HOME: path.join(home, "state"),
- REMNIC_HOST: "127.0.0.1",
- REMNIC_PORT: String(port),
- // Default to an env token unless a test overrides it. Every env name
- // resolveToken() consults is pinned here — including the canonical
- // REMNIC_AUTH_TOKEN / ENGRAM_AUTH_TOKEN pair — so a value inherited
- // from the parent shell (a developer or CI runner that authenticates
- // a local daemon) cannot leak through `...process.env` and make the
- // no-token path take a token (#1518 test isolation). Tests that want
- // a specific name set it through `env.extra`, which is spread last.
- OPENCLAW_REMNIC_ACCESS_TOKEN: env.token === null ? "" : env.token || "test-token",
- OPENCLAW_ENGRAM_ACCESS_TOKEN: "",
- REMNIC_AUTH_TOKEN: "",
- ENGRAM_AUTH_TOKEN: "",
- // Internal worker-propagation channel, not a user credential. Pinned
- // so an inherited value cannot reach the detached observe worker.
- REMNIC_HOOK_TOKEN: "",
- // Clear daemon URL env so a developer shell with REMNIC_DAEMON_URL
- // set can't route tests away from the mock server (the shared core
- // honors it since issue #2483). Tests that WANT a daemon URL
- // override it via env.extra (which spreads last).
- REMNIC_DAEMON_URL: "",
- ENGRAM_DAEMON_URL: "",
- ...env.extra,
- },
- stdio: ["pipe", "pipe", "pipe"],
- });
- let stdout = "";
- let stderr = "";
- child.stdout.on("data", (d) => (stdout += d));
- child.stderr.on("data", (d) => (stderr += d));
- child.on("close", () => {
- let json = null;
- try {
- json = JSON.parse(stdout.trim().split("\n").filter(Boolean).pop());
- } catch {
- /* leave null */
- }
- resolve({ stdout, stderr, json });
- });
- child.stdin.end(typeof input === "string" ? input : JSON.stringify(input));
- });
- }
- function transcript(home, messages) {
- const file = path.join(home, "transcript.jsonl");
- const lines = messages.map((m) => JSON.stringify({ type: m.role, message: { role: m.role, content: m.content } }));
- fs.writeFileSync(file, lines.join("\n") + "\n");
- return file;
- }
- function cursorPath(home, sessionId) {
- return path.join(home, "state", "remnic", "hooks", `remnic-cursor-${sessionId}`);
- }
- // ── session-start ──────────────────────────────────────────────────────────
- test("session-start: healthy server returns recall context with codingContext cleared outside a repo", async () => {
- const home = mkHome();
- const { server, port, calls } = await startServer((req, res) => {
- if (req.url === "/engram/v1/live") return res.writeHead(200).end("ok");
- if (req.url === "/engram/v1/recall") {
- return res.writeHead(200, { "Content-Type": "application/json" }).end(
- JSON.stringify({ context: "remembered preferences", count: 3, mode: "auto" }),
- );
- }
- res.writeHead(404).end();
- });
- try {
- const { json } = await runHook("session-start", { session_id: "s1", cwd: home }, { port, home });
- assert.equal(json.continue, true);
- assert.match(json.hookSpecificOutput.additionalContext, /Remnic Memory Recall — 3 memories/);
- assert.match(json.hookSpecificOutput.additionalContext, /remembered preferences/);
- const recall = calls.find((c) => c.url === "/engram/v1/recall");
- assert.ok(recall, "recall was called");
- assert.equal(recall.body.mode, "auto");
- assert.equal(recall.body.topK, 12);
- // claude-code client id header
- assert.equal(recall.method, "POST");
- // Outside a git repo, codingContext is explicitly null (clears stale routing).
- assert.ok("codingContext" in recall.body);
- assert.equal(recall.body.codingContext, null);
- } finally {
- server.close();
- fs.rmSync(home, { recursive: true, force: true });
- }
- });
- test("session-start: health probe carries the bearer token (auth-gated daemons)", async () => {
- const home = mkHome();
- let healthAuth = "unset";
- const { server, port } = await startServer((req, res) => {
- if (req.url === "/engram/v1/live") {
- healthAuth = req.headers.authorization || null;
- return res.writeHead(200).end("ok");
- }
- if (req.url === "/engram/v1/recall") {
- return res
- .writeHead(200, { "Content-Type": "application/json" })
- .end(JSON.stringify({ context: "ctx", count: 1, mode: "auto" }));
- }
- res.writeHead(404).end();
- });
- try {
- await runHook("session-start", { session_id: "s1", cwd: home }, { port, home });
- // Without this header an auth-gated daemon 401s the probe and the hook
- // reports "daemon not running", silently skipping recall/observe.
- assert.equal(healthAuth, "Bearer test-token");
- } finally {
- server.close();
- fs.rmSync(home, { recursive: true, force: true });
- }
- });
- test("session-start: hung diagnostic /health does not stall the live probe (#3257)", async () => {
- const home = mkHome();
- const { server, port, calls } = await startServer((req, res) => {
- // The expensive diagnostic route never answers; only /live is healthy.
- if (req.url === "/engram/v1/health") return;
- if (req.url === "/engram/v1/live") return res.writeHead(200).end("ok");
- if (req.url === "/engram/v1/recall") {
- return res.writeHead(200, { "Content-Type": "application/json" }).end(
- JSON.stringify({ context: "live recall", count: 1, mode: "auto" }),
- );
- }
- res.writeHead(404).end();
- });
- try {
- const { json } = await runHook("session-start", { session_id: "s1", cwd: home }, { port, home });
- assert.equal(json.continue, true);
- assert.match(json.hookSpecificOutput.additionalContext, /live recall/);
- assert.ok(calls.some((c) => c.url === "/engram/v1/recall"), "recall reached the daemon");
- } finally {
- server.close();
- fs.rmSync(home, { recursive: true, force: true });
- }
- });
- test("session-start: 404 live falls back to legacy health within one budget", async () => {
- const home = mkHome();
- const { server, port, calls } = await startServer((req, res) => {
- if (req.url === "/engram/v1/live") return res.writeHead(404).end();
- if (req.url === "/engram/v1/health") return res.writeHead(200).end("ok");
- if (req.url === "/engram/v1/recall") {
- return res.writeHead(200, { "Content-Type": "application/json" }).end(
- JSON.stringify({ context: "legacy recall", count: 1, mode: "auto" }),
- );
- }
- res.writeHead(404).end();
- });
- try {
- const { json } = await runHook("session-start", { session_id: "s1", cwd: home }, { port, home });
- assert.equal(json.continue, true);
- assert.match(json.hookSpecificOutput.additionalContext, /legacy recall/);
- const probeUrls = calls.filter((c) => c.url === "/engram/v1/live" || c.url === "/engram/v1/health").map((c) => c.url);
- assert.deepEqual(probeUrls, ["/engram/v1/live", "/engram/v1/health"]);
- } finally {
- server.close();
- fs.rmSync(home, { recursive: true, force: true });
- }
- });
- test("session-start: 503 live is a final answer with no legacy retry", async () => {
- const home = mkHome();
- const { server, port, calls } = await startServer((req, res) => {
- if (req.url === "/engram/v1/live") return res.writeHead(503).end();
- // A 503 must NOT be re-probed on the legacy route, even when it would pass.
- if (req.url === "/engram/v1/health") return res.writeHead(200).end("ok");
- if (req.url === "/engram/v1/recall") {
- return res.writeHead(200, { "Content-Type": "application/json" }).end(
- JSON.stringify({ context: "ctx", count: 1, mode: "auto" }),
- );
- }
- res.writeHead(404).end();
- });
- try {
- const { json } = await runHook("session-start", { session_id: "s1", cwd: home }, { port, home });
- assert.match(json.hookSpecificOutput.additionalContext, /daemon not running/);
- assert.ok(!calls.some((c) => c.url === "/engram/v1/recall"), "recall is skipped");
- assert.deepEqual(
- calls.filter((c) => c.url.startsWith("/engram/v1/")).map((c) => c.url),
- ["/engram/v1/live", "/engram/v1/live"],
- );
- } finally {
- server.close();
- fs.rmSync(home, { recursive: true, force: true });
- }
- });
- test("session-start: REMNIC_DAEMON_URL routes recall to the remote base URL (#2483)", async () => {
- const home = mkHome();
- const { server, port, calls } = await startServer((req, res) => {
- if (req.url === "/engram/v1/live") return res.writeHead(200).end("ok");
- if (req.url === "/engram/v1/recall") {
- return res.writeHead(200, { "Content-Type": "application/json" }).end(
- JSON.stringify({ context: "remote recall", count: 1, mode: "auto" }),
- );
- }
- res.writeHead(404).end();
- });
- try {
- // A full REMNIC_DAEMON_URL must take precedence over the (wrong) PORT —
- // the same remote/central-daemon contract the Codex runner has had since
- // #1571. Issue #2483: the Claude Code hook inherits it via the shared
- // core, so a Claude Code host can also reach a remote daemon over
- // Tailscale/LAN/VPN (plain or TLS).
- const { json } = await runHook(
- "session-start",
- { session_id: "remote-1", cwd: home },
- {
- port: 1, // deliberately unused; daemon URL wins
- home,
- env: { extra: { REMNIC_DAEMON_URL: `http://127.0.0.1:${port}` } },
- },
- );
- assert.equal(json.continue, true);
- assert.match(json.hookSpecificOutput.additionalContext, /remote recall/);
- assert.ok(
- calls.some((c) => c.url === "/engram/v1/recall"),
- "recall reached the REMNIC_DAEMON_URL host",
- );
- } finally {
- server.close();
- fs.rmSync(home, { recursive: true, force: true });
- }
- });
- test("recall body targets REMNIC_NAMESPACE when set, and omits namespace when unset", async () => {
- const mk = () =>
- startServer((req, res) => {
- if (req.url === "/engram/v1/live") return res.writeHead(200).end("ok");
- if (req.url === "/engram/v1/recall") {
- return res
- .writeHead(200, { "Content-Type": "application/json" })
- .end(JSON.stringify({ context: "ctx", count: 1, mode: "auto" }));
- }
- res.writeHead(404).end();
- });
- // set → namespace travels in the request body (REST reads it from the body,
- // not a header; the "claude-code" client id otherwise resolves to the
- // adapter's own empty namespace and recall returns nothing).
- {
- const home = mkHome();
- const { server, port, calls } = await mk();
- try {
- await runHook(
- "session-start",
- { session_id: "s1", cwd: home },
- { port, home, env: { extra: { REMNIC_NAMESPACE: "team-shared" } } },
- );
- const recall = calls.find((c) => c.url === "/engram/v1/recall");
- assert.ok(recall, "recall was called");
- assert.equal(recall.body.namespace, "team-shared");
- } finally {
- server.close();
- fs.rmSync(home, { recursive: true, force: true });
- }
- }
- // unset → opt-in no-op, no namespace field (behaviour unchanged for existing users).
- // Explicitly clear both env vars so a value inherited from the developer's
- // shell (`...process.env`) can't leak in and make this path look "set".
- {
- const home = mkHome();
- const { server, port, calls } = await mk();
- try {
- await runHook(
- "session-start",
- { session_id: "s1", cwd: home },
- { port, home, env: { extra: { REMNIC_NAMESPACE: "", ENGRAM_NAMESPACE: "" } } },
- );
- const recall = calls.find((c) => c.url === "/engram/v1/recall");
- assert.ok(recall, "recall was called");
- assert.equal("namespace" in recall.body, false);
- } finally {
- server.close();
- fs.rmSync(home, { recursive: true, force: true });
- }
- }
- });
- test("namespace targeting: ENGRAM_NAMESPACE fallback (recall) and observe body both honor it", async () => {
- // ENGRAM_NAMESPACE is the fallback when REMNIC_NAMESPACE is unset → recall body carries it.
- {
- const home = mkHome();
- const { server, port, calls } = await startServer((req, res) => {
- if (req.url === "/engram/v1/live") return res.writeHead(200).end("ok");
- if (req.url === "/engram/v1/recall") {
- return res
- .writeHead(200, { "Content-Type": "application/json" })
- .end(JSON.stringify({ context: "ctx", count: 1, mode: "auto" }));
- }
- res.writeHead(404).end();
- });
- try {
- await runHook(
- "session-start",
- { session_id: "s1", cwd: home },
- { port, home, env: { extra: { REMNIC_NAMESPACE: "", ENGRAM_NAMESPACE: "legacy-ns" } } },
- );
- const recall = calls.find((c) => c.url === "/engram/v1/recall");
- assert.ok(recall, "recall was called");
- assert.equal(recall.body.namespace, "legacy-ns");
- } finally {
- server.close();
- fs.rmSync(home, { recursive: true, force: true });
- }
- }
- // observe uses the same httpPost path, so its body carries the namespace too.
- {
- const home = mkHome();
- const { server, port, calls } = await startServer((req, res) => res.writeHead(200).end("{}"));
- try {
- const tpath = transcript(home, [
- { role: "user", content: "first" },
- { role: "assistant", content: "second" },
- ]);
- await runHook(
- "__observe-worker__",
- JSON.stringify({ session_id: "sObsNs", transcript_path: tpath }),
- { port, home, env: { extra: { REMNIC_NAMESPACE: "team-shared", ENGRAM_NAMESPACE: "" } } },
- );
- const observe = calls.find((c) => c.url === "/engram/v1/observe");
- assert.ok(observe, "observe was called");
- assert.equal(observe.body.namespace, "team-shared");
- } finally {
- server.close();
- fs.rmSync(home, { recursive: true, force: true });
- }
- }
- });
- test("session-start: falls back to minimal mode when full recall fails", async () => {
- const home = mkHome();
- let recallHits = 0;
- const { server, port, calls } = await startServer((req, res) => {
- if (req.url === "/engram/v1/live") return res.writeHead(200).end("ok");
- if (req.url === "/engram/v1/recall") {
- recallHits += 1;
- if (recallHits === 1) return res.writeHead(500).end("boom");
- return res.writeHead(200).end(JSON.stringify({ context: "fallback ctx", count: 1, mode: "minimal" }));
- }
- res.writeHead(404).end();
- });
- try {
- const { json } = await runHook("session-start", { session_id: "s1", cwd: home }, { port, home });
- assert.match(json.hookSpecificOutput.additionalContext, /minimal mode/);
- const recalls = calls.filter((c) => c.url === "/engram/v1/recall");
- assert.equal(recalls.length, 2);
- assert.equal(recalls[1].body.mode, "minimal");
- assert.equal(recalls[1].body.topK, 8);
- } finally {
- server.close();
- fs.rmSync(home, { recursive: true, force: true });
- }
- });
- test("session-start: no token → claude-code install hint, no recall call", async () => {
- const home = mkHome();
- const { server, port, calls } = await startServer((req, res) => {
- if (req.url === "/engram/v1/live") return res.writeHead(200).end("ok");
- res.writeHead(200).end("{}");
- });
- try {
- const { json } = await runHook("session-start", { session_id: "s1", cwd: home }, { port, home, env: { token: null } });
- assert.match(json.hookSpecificOutput.additionalContext, /no auth token/);
- assert.match(json.hookSpecificOutput.additionalContext, /claude-code/);
- assert.equal(calls.filter((c) => c.url === "/engram/v1/recall").length, 0);
- } finally {
- server.close();
- fs.rmSync(home, { recursive: true, force: true });
- }
- });
- test("session-start: dead daemon → distinct daemon-not-running message", async () => {
- const home = mkHome();
- // Use a port with no listener to simulate a dead daemon.
- const dead = await startServer(() => {});
- const port = dead.port;
- dead.server.close();
- await new Promise((r) => setTimeout(r, 50));
- const { json } = await runHook("session-start", { session_id: "s1", cwd: home }, { port, home });
- assert.match(json.hookSpecificOutput.additionalContext, /daemon not running/);
- fs.rmSync(home, { recursive: true, force: true });
- });
- // ── user-prompt-recall ─────────────────────────────────────────────────────
- test("user-prompt-recall: short prompt is skipped with bare continue", async () => {
- const home = mkHome();
- const { server, port, calls } = await startServer((req, res) => res.writeHead(200).end("{}"));
- try {
- const { json } = await runHook("user-prompt-recall", { session_id: "s1", prompt: "hi there" }, { port, home });
- assert.deepEqual(json, { continue: true });
- assert.equal(calls.length, 0);
- } finally {
- server.close();
- fs.rmSync(home, { recursive: true, force: true });
- }
- });
- test("user-prompt-recall: no token → bare continue, no banner, no call", async () => {
- const home = mkHome();
- const { server, port, calls } = await startServer((req, res) => res.writeHead(200).end("{}"));
- try {
- const { json } = await runHook(
- "user-prompt-recall",
- { session_id: "s1", prompt: "this is a sufficiently long prompt" },
- { port, home, env: { token: null } },
- );
- assert.deepEqual(json, { continue: true });
- assert.equal(calls.length, 0);
- } finally {
- server.close();
- fs.rmSync(home, { recursive: true, force: true });
- }
- });
- test("user-prompt-recall: long prompt injects <remnic-memory> context", async () => {
- const home = mkHome();
- const { server, port, calls } = await startServer((req, res) => {
- if (req.url === "/engram/v1/recall") {
- return res.writeHead(200).end(JSON.stringify({ context: "rel ctx", count: 2 }));
- }
- res.writeHead(404).end();
- });
- try {
- const { json } = await runHook(
- "user-prompt-recall",
- { session_id: "s1", prompt: "please recall the deployment decisions we made" },
- { port, home },
- );
- assert.match(json.hookSpecificOutput.additionalContext, /<remnic-memory count="2">/);
- assert.equal(calls[0].body.mode, "minimal");
- } finally {
- server.close();
- fs.rmSync(home, { recursive: true, force: true });
- }
- });
- // ── post-tool-observe ──────────────────────────────────────────────────────
- test("observe worker: advances cursor only after a successful observe", async () => {
- const home = mkHome();
- const { server, port, calls } = await startServer((req, res) => res.writeHead(200).end("{}"));
- try {
- const tpath = transcript(home, [
- { role: "user", content: "first" },
- { role: "assistant", content: "second" },
- ]);
- await runHook(
- "__observe-worker__",
- JSON.stringify({ session_id: "sObs", transcript_path: tpath }),
- { port, home },
- );
- const observe = calls.find((c) => c.url === "/engram/v1/observe");
- assert.ok(observe, "observe was called");
- assert.equal(observe.body.messages.length, 2);
- assert.equal(fs.readFileSync(cursorPath(home, "sObs"), "utf8").trim(), "2");
- } finally {
- server.close();
- fs.rmSync(home, { recursive: true, force: true });
- }
- });
- test("observe worker: does NOT advance the cursor when observe fails", async () => {
- const home = mkHome();
- const { server, port } = await startServer((req, res) => {
- if (req.url === "/engram/v1/observe") return res.writeHead(500).end("boom");
- res.writeHead(200).end("{}");
- });
- try {
- const tpath = transcript(home, [{ role: "user", content: "only" }]);
- await runHook(
- "__observe-worker__",
- JSON.stringify({ session_id: "sFail", transcript_path: tpath }),
- { port, home },
- );
- assert.equal(fs.existsSync(cursorPath(home, "sFail")), false, "cursor must not be written on failure");
- } finally {
- server.close();
- fs.rmSync(home, { recursive: true, force: true });
- }
- });
- test("observe worker: shell-metacharacter session id is rejected (no injection vector)", async () => {
- // A session id containing shell metacharacters must NOT reach the observe
- // endpoint or the cursor filesystem path. The runner validates the id
- // charset so a malicious payload field can never become a path traversal
- // or a shell argument even if a future caller regresses to shell=true.
- const home = mkHome();
- const { server, port, calls } = await startServer((req, res) => res.writeHead(200).end("{}"));
- try {
- const tpath = transcript(home, [{ role: "user", content: "x" }]);
- await runHook(
- "__observe-worker__",
- JSON.stringify({ session_id: "s; rm -rf /", transcript_path: tpath }),
- Note: Quoted as data in code: Runs `rm -rf` against a root or home-directory path
- Line 563 on GitHub
- { port, home },
- );
- assert.equal(calls.filter((c) => c.url === "/engram/v1/observe").length, 0, "no observe for invalid session id");
- assert.equal(
- fs.existsSync(cursorPath(home, "s; rm -rf /")),
- Note: Quoted as data in code: Runs `rm -rf` against a root or home-directory path
- Line 568 on GitHub
- false,
- "no cursor file written for invalid session id",
- );
- } finally {
- server.close();
- fs.rmSync(home, { recursive: true, force: true });
- }
- });
- test("post-tool-observe: foreground emits continue immediately", async () => {
- const home = mkHome();
- const { server, port } = await startServer((req, res) => res.writeHead(200).end("{}"));
- try {
- const tpath = transcript(home, [{ role: "user", content: "x" }]);
- const { json } = await runHook("post-tool-observe", { session_id: "sPt", transcript_path: tpath }, { port, home });
- assert.deepEqual(json, { continue: true });
- } finally {
- server.close();
- fs.rmSync(home, { recursive: true, force: true });
- }
- });
- test("post-tool-observe: worker payload travels via STDIN, not the environment", async () => {
- // Windows caps the environment block at ~32 KB. Large PostToolUse payloads
- // (big file edits) would E2BIG; the worker reads stdin instead. We assert
- // the source rather than running an E2BIG payload because reproducing the
- // limit cross-platform is impractical.
- const src = fs.readFileSync(CORE, "utf8");
- assert.doesNotMatch(
- src,
- /REMNIC_HOOK_INPUT:\s*rawInput/,
- "foreground hook must NOT propagate the payload via env (E2BIG on Windows)",
- );
- assert.match(
- src,
- /child\.stdin\.end\(rawInput\)/,
- "foreground hook must write the payload to the worker's stdin",
- );
- });
- test("unknown event fails open with continue", async () => {
- const home = mkHome();
- const { server, port } = await startServer((req, res) => res.writeHead(200).end("{}"));
- try {
- const { json } = await runHook("bogus-event", {}, { port, home });
- assert.deepEqual(json, { continue: true });
- } finally {
- server.close();
- fs.rmSync(home, { recursive: true, force: true });
- }
- });
- // ── session-end ────────────────────────────────────────────────────────────
- test("session-end: retains the cursor when the final flush fails (no data loss)", async () => {
- const home = mkHome();
- const { server, port } = await startServer((req, res) => {
- if (req.url === "/engram/v1/observe") return res.writeHead(503).end("down");
- res.writeHead(200).end("{}");
- });
- try {
- const tpath = transcript(home, [{ role: "user", content: "pending tail" }]);
- fs.mkdirSync(path.join(home, "state", "remnic", "hooks"), { recursive: true });
- fs.writeFileSync(cursorPath(home, "sEnd"), "0\n");
- const { json } = await runHook("session-end", { session_id: "sEnd", transcript_path: tpath }, { port, home });
- assert.equal(json.continue, true);
- // Cursor must be RETAINED for retry — the regression this fixes.
- assert.equal(fs.existsSync(cursorPath(home, "sEnd")), true, "cursor retained after failed flush");
- assert.equal(fs.readFileSync(cursorPath(home, "sEnd"), "utf8").trim(), "0");
- } finally {
- server.close();
- fs.rmSync(home, { recursive: true, force: true });
- }
- });
- test("session-end: removes the cursor after a successful final flush", async () => {
- const home = mkHome();
- const { server, port, calls } = await startServer((req, res) => res.writeHead(200).end("{}"));
- try {
- const tpath = transcript(home, [{ role: "user", content: "pending tail" }]);
- fs.mkdirSync(path.join(home, "state", "remnic", "hooks"), { recursive: true });
- fs.writeFileSync(cursorPath(home, "sEnd2"), "0\n");
- await runHook("session-end", { session_id: "sEnd2", transcript_path: tpath }, { port, home });
- assert.ok(calls.find((c) => c.url === "/engram/v1/observe"), "final flush observed");
- assert.equal(fs.existsSync(cursorPath(home, "sEnd2")), false, "cursor cleared after successful flush");
- } finally {
- server.close();
- fs.rmSync(home, { recursive: true, force: true });
- }
- });
- test("session-end: skips final flush via a symlinked cursor (state hardening)", async () => {
- const home = mkHome();
- const { server, port, calls } = await startServer((req, res) => res.writeHead(200).end("{}"));
- try {
- const stateDir = path.join(home, "state", "remnic", "hooks");
- fs.mkdirSync(stateDir, { recursive: true, mode: 0o700 });
- const cursor = cursorPath(home, "sUnsafe");
- const symTarget = path.join(home, "target.txt");
- fs.writeFileSync(symTarget, "unchanged\n");
- fs.symlinkSync(symTarget, cursor);
- const tpath = transcript(home, [{ role: "user", content: "would-be-pending" }]);
- await runHook("session-end", { session_id: "sUnsafe", transcript_path: tpath }, { port, home });
- assert.equal(calls.filter((c) => c.url === "/engram/v1/observe").length, 0);
- assert.equal(fs.readFileSync(symTarget, "utf8"), "unchanged\n");
- } finally {
- server.close();
- fs.rmSync(home, { recursive: true, force: true });
- }
- });
- // ── token resolution ───────────────────────────────────────────────────────
- test("token resolution: claude-code connector wins over openclaw in tokens.json", async () => {
- const home = mkHome();
- fs.mkdirSync(path.join(home, ".remnic"), { recursive: true });
- fs.writeFileSync(
- path.join(home, ".remnic", "tokens.json"),
- JSON.stringify({
- tokens: [
- { connector: "openclaw", token: "openclaw-tok" },
- { connector: "claude-code", token: "cc-tok" },
- ],
- }),
- );
- const { server, port, calls } = await startServer((req, res) => {
- if (req.url === "/engram/v1/live") return res.writeHead(200).end("ok");
- if (req.url === "/engram/v1/recall") return res.writeHead(200).end("{}");
- res.writeHead(200).end("{}");
- });
- try {
- // No env token — must come from tokens.json.
- await runHook(
- "session-start",
- { session_id: "sTok", cwd: home },
- { port, home, env: { token: null } },
- );
- const recall = calls.find((c) => c.url === "/engram/v1/recall");
- assert.ok(recall, "recall was called using the tokens.json credential");
- } finally {
- server.close();
- fs.rmSync(home, { recursive: true, force: true });
- }
- });
- test("token resolution: legacy ~/.engram/tokens.json is the read fallback", async () => {
- const home = mkHome();
- fs.mkdirSync(path.join(home, ".engram"), { recursive: true });
- fs.writeFileSync(
- path.join(home, ".engram", "tokens.json"),
- JSON.stringify({ tokens: [{ connector: "openclaw", token: "legacy-tok" }] }),
- );
- const { server, port, calls } = await startServer((req, res) => {
- if (req.url === "/engram/v1/live") return res.writeHead(200).end("ok");
- if (req.url === "/engram/v1/recall") return res.writeHead(200).end("{}");
- res.writeHead(200).end("{}");
- });
- try {
- await runHook(
- "session-start",
- { session_id: "sLeg", cwd: home },
- { port, home, env: { token: null } },
- );
- const recall = calls.find((c) => c.url === "/engram/v1/recall");
- assert.ok(recall, "recall was called using the legacy engram token store");
- } finally {
- server.close();
- fs.rmSync(home, { recursive: true, force: true });
- }
- });
- // The documented standalone-server setup (docs/guides/standalone-server.md,
- // README) authenticates the daemon with REMNIC_AUTH_TOKEN and never mints a
- // connector token, so nothing lands in ~/.remnic/tokens.json and none of the
- // OPENCLAW_* names are set. Before the canonical pair was added to
- // resolveToken(), that shape sent an unauthenticated health probe, took a 401,
- // and reported "daemon not running" — silently skipping recall and observe.
- function authEnvServer() {
- const seen = { health: "unset", recall: "unset" };
- return startServer((req, res) => {
- if (req.url === "/engram/v1/live") {
- seen.health = req.headers.authorization || null;
- return res.writeHead(200).end("ok");
- }
- if (req.url === "/engram/v1/recall") {
- seen.recall = req.headers.authorization || null;
- return res
- .writeHead(200, { "Content-Type": "application/json" })
- .end(JSON.stringify({ context: "ctx", count: 1, mode: "auto" }));
- }
- res.writeHead(404).end();
- }).then((started) => ({ ...started, seen }));
- }
- for (const name of ["REMNIC_AUTH_TOKEN", "ENGRAM_AUTH_TOKEN"]) {
- test(`token resolution: ${name} authenticates health and recall (no token store)`, async () => {
- const home = mkHome();
- const { server, port, seen } = await authEnvServer();
- try {
- const res = await runHook(
- "session-start",
- { session_id: "sEnv", cwd: home },
- { port, home, env: { token: null, extra: { [name]: "operator-secret" } } },
- );
- assert.equal(seen.health, "Bearer operator-secret");
- assert.equal(seen.recall, "Bearer operator-secret");
- assert.doesNotMatch(
- res.json.hookSpecificOutput.additionalContext,
- /daemon not running/,
- "an authenticated daemon must not be reported as down",
- );
- } finally {
- server.close();
- fs.rmSync(home, { recursive: true, force: true });
- }
- });
- }
- test("token resolution: OPENCLAW_REMNIC_ACCESS_TOKEN outranks REMNIC_AUTH_TOKEN", async () => {
- const home = mkHome();
- const { server, port, seen } = await authEnvServer();
- try {
- await runHook(
- "session-start",
- { session_id: "sPrec", cwd: home },
- { port, home, env: { token: "connector-tok", extra: { REMNIC_AUTH_TOKEN: "operator-secret" } } },
- );
- // Both are current names; the connector-scoped one stays first, so an
- // install that already worked keeps its existing credential.
- assert.equal(seen.health, "Bearer connector-tok");
- } finally {
- server.close();
- fs.rmSync(home, { recursive: true, force: true });
- }
- });
- test("token resolution: REMNIC_AUTH_TOKEN outranks the legacy OPENCLAW_ENGRAM_ACCESS_TOKEN", async () => {
- const home = mkHome();
- const { server, port, seen } = await authEnvServer();
- try {
- await runHook(
- "session-start",
- { session_id: "sLegacyPrec", cwd: home },
- {
- port,
- home,
- env: {
- token: null,
- extra: {
- OPENCLAW_ENGRAM_ACCESS_TOKEN: "stale-legacy-tok",
- REMNIC_AUTH_TOKEN: "operator-secret",
- },
- },
- },
- );
- // Primary-before-legacy (AGENTS.md §9). A migrated deployment often still
- // exports the pre-rename alias; if that stale value outranked the token
- // the daemon actually runs with, the probe would 401 and land back on
- // "daemon not running".
- assert.equal(seen.health, "Bearer operator-secret");
- } finally {
- server.close();
- fs.rmSync(home, { recursive: true, force: true });
- }
- });
- test("token resolution: tokens.json still outranks REMNIC_AUTH_TOKEN", async () => {
- const home = mkHome();
- fs.mkdirSync(path.join(home, ".remnic"), { recursive: true });
- fs.writeFileSync(
- path.join(home, ".remnic", "tokens.json"),
- JSON.stringify({ tokens: [{ connector: "claude-code", token: "cc-tok" }] }),
- );
- const { server, port, seen } = await authEnvServer();
- try {
- await runHook(
- "session-start",
- { session_id: "sStore", cwd: home },
- { port, home, env: { token: null, extra: { REMNIC_AUTH_TOKEN: "operator-secret" } } },
- );
- assert.equal(seen.health, "Bearer cc-tok");
- } finally {
- server.close();
- fs.rmSync(home, { recursive: true, force: true });
- }
- });
- // ── hooks.json Windows parity ─────────────────────────────────────────────
- test("hooks.json: every event uses cross-platform exec form with ${CLAUDE_PLUGIN_ROOT} (#1518)", () => {
- const cfg = JSON.parse(
- fs.readFileSync(path.join(__dirname, "..", "hooks.json"), "utf8"),
- );
- const eventToHookName = (event) => {
- switch (event) {
- case "SessionStart": return "session-start";
- case "PostToolUse": return "post-tool-observe";
- case "UserPromptSubmit": return "user-prompt-recall";
- default: throw new Error(`unexpected event ${event}`);
- }
- };
- for (const event of ["SessionStart", "PostToolUse", "UserPromptSubmit"]) {
- const matchers = cfg.hooks[event] || [];
- for (const matcher of matchers) {
- for (const hook of matcher.hooks) {
- // Claude Code hooks do not support `commandWindows` (that field is
- // specific to the Codex plugin loader). The documented cross-
- // platform shape is exec form: `command: "node"` with an `args`
- // vector pointing at the runner. `node.exe` is a real binary on
- // Windows, so the same entry works on every platform without a
- // shell, without Git Bash, and without `.sh`/`.ps1` dispatch.
- // Each `args` element is passed verbatim (no shell tokenization),
- // so a plugin root containing spaces or metacharacters such as `$`
- // or backticks cannot be re-interpreted by a shell.
- assert.equal(
- hook.command,
- "node",
- `${event}.command must be the bare executable "node" (exec form)`,
- );
- assert.ok(
- Array.isArray(hook.args) && hook.args.length >= 2,
- `${event} must declare an args vector [runner, event-name]`,
- );
- assert.ok(
- typeof hook.args[0] === "string" &&
- hook.args[0].startsWith("${CLAUDE_PLUGIN_ROOT}/hooks/bin/remnic-cc-hook.cjs"),
- `${event}.args[0] must point at the bundled runner via \${CLAUDE_PLUGIN_ROOT}, got: ${hook.args && hook.args[0]}`,
- );
- assert.equal(hook.args[1], eventToHookName(event),
- `${event}.args[1] must be the hook event name`);
- // The shell-form fields must NOT be present: no `commandWindows`
- // (unsupported by Claude Code), and `command` must not be a shell
- // string that would let a shell re-tokenize the plugin root.
- assert.ok(
- hook.commandWindows === undefined,
- `${event} must not declare commandWindows (Claude Code ignores it; exec form is the cross-platform path)`,
- );
- }
- }
- }
- });
- test("plugin.json: manifest conforms to the Claude Code plugin schema (author is an object)", () => {
- const manifest = JSON.parse(
- fs.readFileSync(path.join(__dirname, "..", "..", ".claude-plugin", "plugin.json"), "utf8"),
- );
- // Claude Code's plugin-manifest validator rejects a string `author`
- // ("Invalid input: expected object, received string"), which blocks
- // installing this plugin from a Claude Code marketplace. `author` must be an
- // object carrying at least a `name`.
- assert.equal(typeof manifest.author, "object", "author must be an object, not a string");
- assert.ok(manifest.author !== null && !Array.isArray(manifest.author), "author must be a plain object");
- assert.equal(typeof manifest.author.name, "string", "author.name must be a string");
- assert.ok(manifest.author.name.length > 0, "author.name must be non-empty");
- // Sanity-check the other required identity fields while we're here.
- assert.equal(typeof manifest.name, "string", "name must be a string");
- assert.equal(typeof manifest.version, "string", "version must be a string");
- });
- test("runner source: payload fields never reach a shell — spawn uses fixed argv (#1518 guard shell interpolation)", () => {
- const src = fs.readFileSync(CORE, "utf8");
- // Every spawn/spawnSync must use a fixed literal argument array, never a
- // string command, so a payload value (session id, cwd, transcript path,
- // prompt, tool name) cannot achieve command injection.
- assert.doesNotMatch(
- src,
- /spawn(Sync)?\(\s*`/m,
- "spawn/spawnSync must never take a template-literal command (shell injection risk)",
- );
- assert.doesNotMatch(
- src,
- /execFileSync\(\s*`|exec\(\s*`/m,
- "exec/execFileSync must never take a template-literal command",
- );
- // Confirm the daemon-start + migration loops pre-check PATH with onPath()
- // (.cmd/.exe-aware) so the remnic→engram fallthrough happens, and launch
- // through a shell on Windows so `.cmd` npm shims actually run.
- const onPathHits = (src.match(/onPath\(bin\)/g) || []).length;
- assert.ok(onPathHits >= 2, "both migration and daemon-start loops must PATH-gate with onPath()");
- assert.match(
- src,
- /shell:\s*process\.platform === "win32"/,
- "CLI launches must use a shell on Windows so .cmd shims run",
- );
- });
- test("runner source: stdin is the single payload source — no env-var override", () => {
- const src = fs.readFileSync(CORE, "utf8");
- assert.doesNotMatch(
- src,
- /process\.env\.REMNIC_HOOK_INPUT/,
- "readStdin must not consult REMNIC_HOOK_INPUT (env-leak override risk)",
- );
- });
- test("runner source: path inputs are type-validated before use (#1518 validate path types)", () => {
- const src = fs.readFileSync(CORE, "utf8");
- // cwd / transcript_path are coerced via `input.X || ""` so an unexpected
- // non-string payload field (number, object, array) cannot reach fs / git
- // and throw an opaque error or, worse, be coerced by Node to a path.
- assert.match(src, /const cwd = input\.cwd \|\| ""/, "cwd must be defaulted to empty string");
- assert.match(
- src,
- /const transcriptPath = input\.transcript_path \|\| ""/,
- "transcript_path must be defaulted to empty string",
- );
- });
- test("token resolution: REMNIC_AUTH_TOKEN outranks ENGRAM_AUTH_TOKEN when both are set", async () => {
- const home = mkHome();
- const { server, port, seen } = await authEnvServer();
- try {
- await runHook(
- "session-start",
- { session_id: "sBothCanonical", cwd: home },
- {
- port,
- home,
- env: {
- token: null,
- extra: { REMNIC_AUTH_TOKEN: "current-tok", ENGRAM_AUTH_TOKEN: "legacy-tok" },
- },
- },
- );
- assert.equal(seen.health, "Bearer current-tok");
- assert.equal(seen.recall, "Bearer current-tok");
- } finally {
- server.close();
- fs.rmSync(home, { recursive: true, force: true });
- }
- });
- test("health probe uses the same bearer as the operation it gates", async () => {
- const home = mkHome();
- const { server, port, seen } = await authEnvServer();
- try {
- // REMNIC_HOOK_TOKEN is the detached observe worker's internal propagation
- // channel; the foreground handlers never read it. If the probe consulted
- // it, an inherited value would authenticate health with one bearer while
- // recall sent another — a false "healthy" followed by a 401, or the
- // reverse. Probe and operation must carry one snapshot.
- await runHook(
- "session-start",
- { session_id: "sSnapshot", cwd: home },
- { port, home, env: { extra: { REMNIC_HOOK_TOKEN: "inherited-worker-tok" } } },
- );
- assert.equal(seen.health, "Bearer test-token");
- assert.equal(seen.recall, seen.health);
- } finally {
- server.close();
- fs.rmSync(home, { recursive: true, force: true });
- }
- });
Ratings and comments
Sign in to rate this skill.
Sign inFree to use. If it’s helped, pass it on.