π δΈζη | English
AgentMemory is a compilation-free, lightweight, and universal persistent memory system (Universal Agent Memory - UAM). It allows multiple developer agents (such as Claude Code, OpenCode, ChatGPT desktop (Codex runtime), Antigravity CLI, and Grok) to share, record, and query context observations and decisions across different workspaces.
- Cross-Agent Memory Sharing: Shares historical session facts, architectural decisions, and bug-fixing notes across different development assistants.
- Compilation-Free & Lightweight: Built with a pure JavaScript in-memory Feature Hashing Vectorizer and WebAssembly SQLite (
node-sqlite3-wasm), bypassing complex C++ native compiler dependencies (node-gyp). - Hybrid Search: Combines SQLite FTS5 BM25 keyword matching with Cosine Similarity vector retrieval for highly relevant results.
- Background Summarization: Uses the DeepSeek Flash API to summarize session tool logs asynchronously in the background.
- Daily Memory Digests: Runs a daily per-project synthesis job that filters low-signal observations, writes compact fact/decision/action digests, and feeds recent digests into startup context.
- Secure Global Config: Stores API keys and settings globally (
~/.agentmem/.env) to keep codebase repositories clean and credentials safe. - Loopback Admin Console: Exposes a local-only
/adminpage for inspecting the database, filtering observations, and toggling global memory read/write gates at runtime. - Persistent Runtime Policy: Persists
readEnabledandwriteEnabledflags in SQLite so runtime gating survives worker restarts.
graph TD
subgraph Clients [Developer Assistants]
CC[Claude Code]
OC[OpenCode]
CX["ChatGPT desktop<br/>(Codex runtime)"]
AG[Antigravity CLI]
GK[Grok]
end
subgraph AgentMemory Core [AgentMemory System]
CLI[Global CLI Wrapper]
Worker[Background HTTP Worker Port 38888]
MCP[Stdio MCP Server]
DB[(WASM SQLite + FTS5)]
end
CC -- Stdio MCP / Hooks --> MCP
OC -- Stdio MCP / ESM Plugin --> MCP
CX -- Stdio MCP --> MCP
AG -- Stdio MCP --> MCP
GK -- Stdio MCP / Hooks --> MCP
CC -- Post-Tool Event --> Worker
OC -- Post-Tool Event --> Worker
GK -- Lifecycle Events --> Worker
Worker -- Async Summarization --> LLM[DeepSeek Flash API]
Worker -- Write Obs --> DB
MCP -- Query / Write --> DB
- Node.js (v18+)
Clone the repository and build the distribution files:
git clone https://github.com/KuanChen01/AgentMemory.git
cd AgentMemory
npm install
npm run buildLink the executable globally to register the agentmem CLI:
npm linkSet up your global configuration file in your user home directory:
File Path: ~/.agentmem/.env (Create parent directory .agentmem if it doesn't exist)
# General LLM credentials (supports OpenAI, DeepSeek, Mimo, Ark, local Ollama, etc.)
AGENTMEM_LLM_API_KEY=your_api_key_here
AGENTMEM_LLM_API_URL=https://api.deepseek.com/v1
AGENTMEM_LLM_MODEL=deepseek-chat
# Optional: Set to true if your proxy platform doesn't support JSON Mode parameters
AGENTMEM_LLM_DISABLE_JSON_MODE=false
# Optional: Custom JSON headers required by your proxy pools or gateway (e.g. Volcengine Ark)
# AGENTMEM_LLM_HEADERS={"X-Custom-Auth":"value"}
# Local service port
AGENTMEM_PORT=38888Run the installer to automatically configure settings for Claude Code, OpenCode, ChatGPT desktop (Codex runtime), Antigravity, and Grok:
agentmem installIf you want the command to fail whenever any one of the five agents cannot be configured, use:
agentmem install --strictThe installer is now backup-first and merge-first:
- It stores install state in
~/.agentmem/install-state.json - It keeps pristine baselines under
~/.agentmem/backups/when available - It merges only AgentMemory-owned hooks / MCP entries instead of replacing whole hook arrays
To remove AgentMemory from the current machine without deleting the repo checkout, use:
agentmem uninstall --strictAdd --purge-all if you also want to remove the retained install-state and backup artifacts after cleanup.
For a second Windows machine, use the dedicated bootstrap entry instead of repeating the setup manually:
.\bootstrap-second-machine.cmdDetailed Chinese walkthrough: docs/Second Machine Bootstrap Guide.zh.md
Run these commands globally from any directory:
- Start Worker:
agentmem start(launches the memory worker service; keep the terminal open while it is running) - Stop Worker:
agentmem stop(sends a graceful shutdown trigger to the local worker) - Check Status:
agentmem status(verifies if the port38888is active) - Print Version:
agentmem version - Run Setup:
agentmem install(updates Claude Code, OpenCode, Codex, Antigravity, and Grok settings) - Strict Setup:
agentmem install --strict(fails if any one of the five agents cannot be configured) - Uninstall Local Integration:
agentmem uninstall --strict(removes AgentMemory-managed hooks, MCP entries, plugin artifacts,.env, and database files from the current machine) - Purge Local Install State:
agentmem uninstall --strict --purge-all(also removes retained backup and install-state artifacts) - Second-Machine Bootstrap:
agentmem bootstrap-win --strictorbootstrap-second-machine.cmd - Release Manifest:
agentmem release-manifest --json(prints the machine-readable release policy and current version) - Release Plan:
npm run release:plan -- --next patch|minor|major(prints the manual release checklist for the next version) - Release Bump:
npm run release:bump -- --next patch|minor|major(updates the root package version metadata before a release commit)
For a same-shape second Windows machine, the recommended path is:
git clone https://github.com/KuanChen01/AgentMemory.git
cd AgentMemory
.\bootstrap-second-machine.cmdThe bootstrap script runs npm install, npm run build, creates or validates %USERPROFILE%\.agentmem\.env, runs npm link, configures all five agents, probes or starts the worker, and opens /admin.
If %USERPROFILE%\.agentmem\.env is missing, bootstrap writes a blank scaffold and stops with an actionable error. Fill the AGENTMEM_LLM_* values, then rerun the command.
AgentMemory now treats product releases as a first-class maintainer workflow:
- Official releases are published from
masteronly. - Versioning is strict
SemVerwith tags shaped likev1.2.3. - The current v1 distribution channel is GitHub Release + default source archives.
- Release metadata is exposed through the CLI (
agentmem release-manifest) and/admin/api/overview, and/admin/api/release-checknow compares the current checkout against the latest published GitHub Release.
Detailed maintainer workflow: docs/Release Process.md
After the worker is running, open:
http://127.0.0.1:38888/admin
The admin console is intentionally restricted to loopback clients. It is not exposed to non-local network addresses.
Windows local control now has two entrypoints:
npm run workbenchstart-workbench.cmd
npm run workbench keeps the direct one-click flow: build the repo, probe http://127.0.0.1:38888/admin/api/overview, reuse or start the worker, and open /admin.
start-workbench.cmd is now the interactive control entrypoint. With no arguments it probes the current status first, then shows a one-shot menu for Start, Stop, Restart, Status, Open Admin, and Exit. With arguments it supports:
start-workbench.cmd start|stop|restart|status|open-admin|menustart-workbench.cmd start --no-openstart-workbench.cmd restart --port 38889 --no-open
The page provides:
- Runtime for global
readEnabled/writeEnabledcontrol, project inventory, daily digest status / manual run / scheduler settings, workbench posture, and a read-only GitHub Release update check with manual upgrade guidance - Procedural Skills for reviewing digest
skill_candidates, promoting them to draft, flipping lifecycle status, recording success/failure/rejected/skipped feedback, inspecting feedback history, evidence, lifecycle, recommendation signals, and the latest automatic post-task review artifacts next to task-level query validation - LLM Settings for switching
AGENTMEM_LLM_MODEL, updating the OpenAI-compatible API base URL, preserving or replacing the API key, and running a live connection test - Project Context for the current
ProjectContextView, recent daily digests, rendered startup text, bounded context package metrics, temporal slice diagnostics, and policy decision trace - State Lab for explicit structured state reads and writes
- Search Diagnostics for raw hybrid search scores (
hybrid_score,fts_score,vector_score) and low-signal title visibility - Observation Ledger for filterable observation browsing and detailed drill-down
AgentMemory now separates memory into explicit layers:
- Observations remain the append-only historical ledger used for hybrid search and detailed recall.
- State facts store explicit current or historical truth with
effective_at,recorded_at, andsuperseded_at. - Daily digests store scheduled or manually triggered per-project summaries with fact, decision, command, open-question, and next-action lists. Digest output is not auto-promoted into state facts.
- Procedural skills are now first-class, reviewable memory objects with draft/enabled/disabled/retired states plus success/failure feedback logs.
The policy brain is now explicit instead of being scattered across hooks and ad-hoc call sites:
memory-policy.tscentralizes read decisions, low-signal ledger writes, and draft promotion gates for procedural skill candidates.memory-orchestrator.tsis the shared Stage 2 read orchestrator used by worker startup context, MCPget_project_context, and task-level query resolution.memory-query.tsis the task-oriented resolution path that now reuses the shared orchestrator to decide which layers to read, when to consult procedural memory, and how to attach bounded context, temporal diagnostics, and decision trace output.
New interfaces in this first cut:
GET /context?project_path=&limit=&as_of=returns aProjectContextViewobject instead of a raw observation array.GET /state?project_path=&entity_type=&entity_key=&fact_key=&as_of=reads current or historical structured state.POST /stateexplicitly writes a structured state fact.POST /memory/queryreturns the policy decision, layered context, matching observations, matching procedural skills, a bounded context package, temporal slice diagnostics, and a decision trace for a task query.POST /searchandPOST /admin/api/searchnow accept optionalas_offiltering for historical replay.- MCP tools:
get_project_context,query_memory,get_memory_state,set_memory_state,list_procedural_skills,promote_skill_candidate,set_procedural_skill_status,record_procedural_skill_feedback
ProjectContextView combines:
as_offor time-sliced reconstructioncurrent_statedaily_digestsfrom recent successful daily summaries, trimmed for startup useprocedural_skillsfrom enabled or draft first-class procedural memory, enriched with feedback summary/history, lifecycle signal, and recommendation state when relevantsummary_blocksbuilt from curated recent observations with low-signal titles filtered out and duplicate titles collapsedrecent_observationsas a slim startup-oriented metadata list (id,title,created_at,agent_id) without full narratives or embeddingssliding_windowas the compatibility alias for the Stage 2 bounded context packagebounded_contextas the host-facing bounded recent-context package with layer budgets, trimming order, rendered package text, and host responsibilitiestemporal_diagnosticsfor per-layeras_of/ latest slice behaviordecision_tracefor why the policy and recommendation path produced the current packagememory_layersfor explicit metadata/profile/recent-summary/ledger/procedural/window separationgenerated_at
Structured state is still explicit-write only in this phase. Observations, hook logs, and LLM summaries do not automatically promote themselves into the state layer. Procedural skill candidates also remain reviewable before promotion: they can be promoted into draft skills, but they are never auto-enabled.
The workbench also exposes loopback-only admin APIs for the UI:
GET /admin/api/context?project_path=&limit=returns:view: rawProjectContextViewrendered: the same text block produced byrenderProjectContextView(view)metrics:payloadBytes,summaryCount,lowSignalCount,duplicateTitleCount,proceduralSkillCount,slidingWindowEntryCount,boundedContextBudget,boundedContextCharsUsed,boundedContextTrimmedEntries,temporalDiagnosticLayerCount,decisionTraceStepCount
GET /admin/api/state?project_path=&entity_type=&entity_key=&fact_key=&as_of=reads structured state for the workbenchPOST /admin/api/stateexplicitly writes a structured state fact from the workbenchPOST /admin/api/searchreturns raw hybrid search diagnostics for the current project without changing the ranking algorithm, and accepts optionalas_ofPOST /admin/api/memory/queryexposes the policy-driven task resolution path used to assemble layered memory context, bounded context packaging, temporal diagnostics, and decision trace outputGET /admin/api/skills?project_path=&status=&as_of=&limit=lists current procedural skills with feedback history, evidence summary, lifecycle signal, and recommendation metadataGET /admin/api/post-task-reviews?project_path=&limit=lists automatic post-task review artifacts generated from the real observation write path, including matched skills, recommendation states, bounded context, temporal diagnostics, and decision trace dataPOST /admin/api/skills/promote-candidateexplicitly promotes a digestskill_candidateinto a draft procedural skillPOST /admin/api/skills/statusflips a procedural skill betweendraft,enabled,disabled, andretiredPOST /admin/api/skills/feedbackrecords success/failure/rejected/skipped feedback for a procedural skillGET /admin/api/digests?project_path=&limit=returns recent saved daily memory digests for a projectPOST /admin/api/digests/runmanually runs the daily memory digest job for a selected project and optionallocal_dateGET /admin/api/digest-schedulerreturns the persisted daily digest scheduler config and current runtime statusPOST /admin/api/digest-schedulersaves schedulerenabled,schedule_time,time_zone, andlookback_days, then applies the new timer to the running workerGET /admin/api/release-checkcompares the current checkout against the latest published GitHub Release and returns manual upgrade guidance for either git checkouts or source archivesGET /admin/api/llm-configreturns a sanitized LLM config snapshot without exposing the full API keyPOST /admin/api/llm-configpersists model, API URL, JSON-mode, headers, and optional API key changes to~/.agentmem/.envand updates the running worker processPOST /admin/api/llm-testsends a small OpenAI-compatiblechat/completionsrequest with the current form values and returns pass/fail diagnostics
readEnabled=falseblocks memory restoration and explicit read APIs:- HTTP:
/context,/search,/state,/memory/query - MCP:
get_project_context,query_memory,search_memory,memory_timeline,get_memory_details,get_memory_state,list_procedural_skills - Session-start hooks stop printing restored memory into the agent session
- HTTP:
writeEnabled=falseblocks new memory creation:- HTTP:
/tools,/sessions,/sessions/close,/state,/admin/api/skills/* - MCP:
record_memory,set_memory_state,promote_skill_candidate,set_procedural_skill_status,record_procedural_skill_feedback - Post-tool hooks stop producing new observations
- HTTP:
Both flags are stored in SQLite app_settings, so the selected policy survives worker restarts.
Daily digest reads use the same read gate as startup context, and manual digest runs use the same write gate as observation and state writes. Scheduler settings are persisted in SQLite app_settings; the legacy AGENTMEM_DAILY_DIGEST_DISABLED=true environment flag only seeds the default value before a scheduler setting is saved.
- Use
npm run workbenchfor the old one-click launch, or usestart-workbench.cmdfor interactiveStart / Stop / Restart / Status / Open Admincontrol - Open
http://127.0.0.1:38888/admin - Use the
Read MemoryandWrite Memoryswitches to change runtime policy - Use the Runtime release card to compare the current checkout with the latest GitHub Release and choose the recommended manual upgrade path
- Use Runtime daily digest controls to inspect the latest per-project digest, manually run one for a selected local date, or change the automatic scheduler's enabled state, run time, time zone, and catch-up window
- Use
Procedural Skillsto review digest candidates, promote the reusable ones to draft, flipenabled/disabled/retired, record operator feedback, inspect automatic post-task reviews, and run a validation query that shows matched skill titles plus the currentrollout_stage - Use
LLM Settingsto switch models or endpoints, save the env-file change, and test the connection before the next summary job - Use
Project Context,State Lab, andSearch Diagnosticsto inspect startup context quality, structured state, and current hybrid ranking behavior - Use
Observation Ledgerto drill into the raw observation history when needed - Use
agentmem statusto confirm the worker is still reachable, andagentmem stopwhen finished
agentmem install now writes both the mcp.agentmem block and the generated bridge plugin %USERPROFILE%/.config/opencode/plugins/agentmem-plugin.mjs. The resulting config shape is:
Claude Code uses two different files:
~/.claude.jsonfor global stdio MCP servers~/.claude/settings.jsonfor hooks and other session settings
~/.claude.json
{
"mcpServers": {
"agentmem": {
"type": "stdio",
"command": "node",
"args": ["path/to/AgentMemory/dist/servers/mcp-server.js"],
"env": {}
}
}
}~/.claude/settings.json
{
"hooks": {
"SessionStart": [
{
"matcher": ".*",
"hooks": [{ "type": "command", "command": "node \"path/to/AgentMemory/dist/hooks/claude-session-start.js\"" }]
}
],
"PostToolUse": [
{
"matcher": ".*",
"hooks": [{ "type": "command", "command": "node \"path/to/AgentMemory/dist/hooks/claude-post-tool.js\"" }]
}
]
}
}The desktop app is currently branded ChatGPT, while its Codex runtime continues to use ~/.codex. Expose the MCP server in config.toml, and register lifecycle hooks in hooks.json; keep the codex-* hook file names unchanged.
~/.codex/config.toml
[features]
hooks = true
[mcp_servers.agentmem]
command = "node"
args = [ "path/to/AgentMemory/dist/servers/mcp-server.js" ]~/.codex/hooks.json
{
"hooks": {
"SessionStart": [
{
"matcher": ".*",
"hooks": [{ "type": "command", "command": "node \"path/to/AgentMemory/dist/hooks/codex-session-start.js\"" }]
}
],
"PostToolUse": [
{
"matcher": ".*",
"hooks": [{ "type": "command", "command": "node \"path/to/AgentMemory/dist/hooks/codex-post-tool.js\"" }]
}
]
}
}agentmem install now also updates the active Antigravity MCP registry. It checks Antigravity's direct registries first (%USERPROFILE%\.gemini\antigravity-cli\mcp_config.json, then antigravity-ide, antigravity, and .gemini\config\mcp_config.json) before falling back to Gemini-compatible plugin registries under %USERPROFILE%\.gemini\config\plugins\*\mcp_config.json. If your machine keeps that registry somewhere else, pass:
agentmem install --strict --antigravity-config "C:\\path\\to\\mcp_config.json"Generic shape:
{
"mcpServers": {
"agentmem": {
"command": "node",
"args": ["path/to/AgentMemory/dist/servers/mcp-server.js"],
"env": { "AGENTMEM_AGENT_ID": "antigravity" },
"disabled": false
}
}
}The installer also creates and activates an Antigravity plugin under %USERPROFILE%\.agentmem\antigravity-plugins\agentmem. Its PreInvocation, PostToolUse, and Stop hooks automatically inject ProjectContextView, record tool work as canonical antigravity, and close the session. The MCP registry receives AGENTMEM_AGENT_ID=antigravity, so explicit record_memory calls that omit agent_id no longer fall back to mcp-client. %USERPROFILE%\.agentmem\AGENTMEM_ANTIGRAVITY.md remains as a readable compatibility copy of the plugin rule.
Preferred Antigravity workflow:
- Read the current workspace root
obsiguide.md; if it is missing butobsiguide.template.mdexists, bootstrap and initializeobsiguide.mdfrom verified repo evidence before feature work. - Let the
PreInvocationhook inject startup context automatically. Useget_project_context,search_memory, ormemory_timelineonly for explicit drill-down, then verify relevant results against repo evidence andobsiguide.md. - Before writing to
E:\Kuan\Vault, check current repo evidence,obsiguide.md, and existing vault notes. Do not paste raw AgentMemory summaries or session recaps into the vault. - Normal tool work is recorded automatically by
PostToolUse, andStopcloses the session. Use explicitrecord_memory(agent_id="antigravity")only for a deliberate milestone entry. - If you need more detail after startup, use
memory_timeline,search_memory, and thenget_memory_detailsfor drill-down.
This gives Antigravity the same automatic read/write lifecycle as the other hook-backed agents.
agentmem install registers the stdio MCP server with AGENTMEM_AGENT_ID=grok, creates a managed global ~/.grok/AGENTS.md Vault rule file, creates a default ~/.grok/agents/agentmem.md profile, and writes global lifecycle hooks to ~/.grok/hooks/agentmem.json.
[agent]
name = "agentmem"
[compat.claude]
hooks = false
[mcp_servers.agentmem]
command = "node"
args = [ "path/to/AgentMemory/dist/servers/mcp-server.js" ]
env = { AGENTMEM_AGENT_ID = "grok" }The managed global AGENTS.md is loaded by every Grok profile and contains the obsiguide.md bootstrap, AgentMemory/Vault boundary, evidence priority, durable-note, and reporting workflow. The default profile enables AGENTS.md loading, then makes get_project_context its first memory read. Grok's passive hooks cannot inject stdout into the model, so the profile owns startup recovery while SessionStart, PostToolUse, PostToolUseFailure, Stop, and SessionEnd hooks register sessions, record tool work, and close sessions. The installer disables Grok's Claude-hook compatibility only: this prevents the existing Claude post-tool hook from mislabeling Grok activity as claudecode; Claude skills and MCP compatibility remain enabled.
Use this when validating a live local installation:
- Precheck: worker starts,
/adminloads, and the current observation count is readable read on / write on: previous memory is restored and a new observation can be recordedread off / write on: restored memory disappears, explicit read tools return disabled messages, but new writes still succeedread on / write off: memory can still be read, but new writes no longer increase the observation count- Restore defaults: turn both toggles back on and verify the persisted policy survives a worker restart
If a smoke check fails, fix only issues directly related to /admin, runtime policy gating, or the current agent integration path, then re-run npm run build and the affected tests/*.test.cjs.
Apache-2.0 License
{ "mcp": { "agentmem": { "type": "local", "command": ["node", "path/to/AgentMemory/dist/servers/mcp-server.js"], "enabled": true } }, "plugin": [ "file:///C:/Users/YourUsername/.config/opencode/plugins/agentmem-plugin.mjs" ] }