- Plugins that let Claude Code, Cursor, Codex, and other harnesses remember your project. Opens the Claude Code guide.
+ Start with Claude Code, then choose the individual guide for Cursor, Codex, Kimi Code, OpenCode, OpenClaw, Pi Agent, DeepSeek Harness, or Antigravity.
diff --git a/docs/llms.txt b/docs/llms.txt
index ae45ad462..f13e2fc07 100644
--- a/docs/llms.txt
+++ b/docs/llms.txt
@@ -171,6 +171,7 @@ If the user is on a pre-current major (Python < 2, TS < 3, or a Platform call st
- [Introduction](https://docs.mem0.ai/introduction) [Both]: Use when the user wants a one-page overview of how memory fits between the LLM and the app.
- [Vibe Code with Mem0](https://docs.mem0.ai/vibecoding) [Both]: Use when the user is in Claude Code, Cursor, or Windsurf and wants memory wired into their editor.
- [Platform Overview](https://docs.mem0.ai/platform/overview) [Platform]: Use when the user picks the managed product - 4-line integration, hosted API, dashboard.
+- [Mem0 Copilot](https://docs.mem0.ai/platform/copilot) [Platform]: Use when inspecting project memories, reviewing configuration changes, or testing extraction in the dashboard.
- [Sign up as an agent](https://docs.mem0.ai/platform/agent-signup) [Platform]: Use when an AI agent needs to mint a Mem0 API key autonomously - four commands, no email or dashboard, human claims ownership later.
- [Platform vs Open Source](https://docs.mem0.ai/platform/platform-vs-oss) [Both]: Use when the user is deciding between managed and self-hosted.
- [Platform Quickstart](https://docs.mem0.ai/platform/quickstart) [Platform]: Use for the first Platform integration - API key plus `MemoryClient.add/search`.
@@ -185,7 +186,6 @@ If the user is on a pre-current major (Python < 2, TS < 3, or a Platform call st
## Core Concepts
- [How Mem0 Works](https://docs.mem0.ai/core-concepts/how-it-works) [Both]: Use when explaining the end-to-end pipeline: extraction (ADD-only distillation), storage across vector/entity/history stores, and multi-signal retrieval.
-- [Memory Types](https://docs.mem0.ai/core-concepts/memory-types) [Both]: Use when checking which `memory_type` values actually work: `procedural_memory` is implemented, `semantic_memory` and `episodic_memory` are defined in the enum but rejected by validation.
- [Memory Operations - Add](https://docs.mem0.ai/core-concepts/memory-operations/add) [Both]: Use when explaining how `add()` extracts facts, resolves conflicts, and writes to both stores.
- [Memory Operations - Search](https://docs.mem0.ai/core-concepts/memory-operations/search) [Both]: Use when explaining how queries are processed and ranked.
- [Memory Operations - Update](https://docs.mem0.ai/core-concepts/memory-operations/update) [Both]: Use when memories need to be edited in place or reconciled against new info.
@@ -197,6 +197,7 @@ If the user is on a pre-current major (Python < 2, TS < 3, or a Platform call st
### Features - Essential
- [V2 Memory Filters](https://docs.mem0.ai/platform/features/v2-memory-filters) [Platform]: Use when compound filters (AND/OR on metadata, entity, time) are needed at search.
- [Entity-Scoped Memory](https://docs.mem0.ai/platform/features/entity-scoped-memory) [Platform]: Use when partitioning memories by user, agent, app, or run.
+- [Profiles](https://docs.mem0.ai/platform/features/user-profiles) [Platform]: Use when a structured always-current summary of a user is needed in one read, instead of searching their memories.
- [Graph Memory](https://docs.mem0.ai/platform/features/graph-memory) [Platform]: Use when connecting facts across memories through shared entities for entity-centric or multi-hop questions.
- [Async Client](https://docs.mem0.ai/platform/features/async-client) [Platform]: Use when the app issues many concurrent Mem0 calls and needs non-blocking I/O.
- [Multimodal Support](https://docs.mem0.ai/platform/features/multimodal-support) [Platform]: Use when storing images or PDFs as memory input.
@@ -208,6 +209,7 @@ If the user is on a pre-current major (Python < 2, TS < 3, or a Platform call st
- [Custom Instructions](https://docs.mem0.ai/platform/features/custom-instructions) [Platform]: Use when tailoring what Mem0 extracts and stores on Platform.
- [Memory Decay](https://docs.mem0.ai/platform/features/memory-decay) [Platform]: Use when search results should boost recently-reinforced memories and dampen stale ones. Opt in per project; applies at search time and never filters candidates out.
- [Dream](https://docs.mem0.ai/platform/features/dream) [Platform]: Use when long-lived user memory should stay coherent on its own - synthesizing recurring patterns, superseding outdated facts, and merging duplicates in the background. Synthesis is opt-in (Pro+); Supersede and Merge are always on.
+- [Bring Your Own Key (BYOK)](https://docs.mem0.ai/platform/features/byok) [Platform]: Use when connecting your own OpenAI, Anthropic, OpenRouter or Azure OpenAI key so memories are created on your model - setup, key-check errors, failed adds, rate limits and choosing a model.
- [Advanced Memory Operations](https://docs.mem0.ai/platform/advanced-memory-operations) [Platform]: Use when basic CRUD is not enough - batch ops, complex filters, workflows.
### Features - Data Management
@@ -223,6 +225,7 @@ If the user is on a pre-current major (Python < 2, TS < 3, or a Platform call st
### Support & Migration
- [FAQs](https://docs.mem0.ai/platform/faqs) [Platform]: Use when answering common Platform questions.
+- [Pricing FAQ](https://docs.mem0.ai/platform/pricing) [Platform]: Use when a user asks how the October 26, 2026 pricing change affects their plan - existing Starter, Growth and Pro plans, free plan limits and the 30-day period, connecting their own LLM key, Vercel accounts and usage-based billing.
- [Contribute to Platform](https://docs.mem0.ai/platform/contribute) [Platform]: Use when a user wants to contribute to Platform docs or code.
- [OSS to Platform Migration](https://docs.mem0.ai/migration/oss-to-platform) [Both]: Use when moving from self-hosted to managed.
- [OSS v2 to v3 Migration](https://docs.mem0.ai/migration/oss-v2-to-v3) [OSS]: Use when upgrading a self-hosted deployment across major versions.
@@ -255,24 +258,25 @@ If the user is on a pre-current major (Python < 2, TS < 3, or a Platform call st
- [Agno](https://docs.mem0.ai/integrations/agno) [Platform]: Use when the user is on Agno.
- [Camel AI](https://docs.mem0.ai/integrations/camel-ai) [Both]: Use when the user is on Camel AI.
- [ChatDev](https://docs.mem0.ai/integrations/chatdev) [Platform]: Use when the user is on ChatDev.
-- [Hermes](https://docs.mem0.ai/integrations/hermes) [Both]: Use when the user is on Hermes.
-- [Pi Agent](https://docs.mem0.ai/integrations/pi-agent) [Platform]: Use when adding persistent memory to Pi Agent with the Mem0 plugin.
-- [DeepSeek Harness](https://docs.mem0.ai/integrations/deepseek-plugin) [Platform]: Use when adding persistent memory to the DeepSeek Harness (Cordis) agent via the Mem0 plugin.
+- [Hermes](https://docs.mem0.ai/integrations/hermes) [Both]: Use when installing or configuring the standalone Hermes memory plugin, or migrating from the bundled Mem0 provider.
+- [Pi Agent](https://docs.mem0.ai/integrations/pi-agent) [Platform]: Use when adding automatic capture, prompt recall, scoped memory, and six memory commands to Pi Agent.
+- [DeepSeek Harness](https://docs.mem0.ai/integrations/deepseek-plugin) [Platform]: Use when adding automatic recall, completed-turn capture, and native search/add tools to DeepSeek Harness.
- [OpenAI Agents SDK](https://docs.mem0.ai/integrations/openai-agents-sdk) [Platform]: Use when the user is on the OpenAI Agents SDK.
- [Google AI ADK](https://docs.mem0.ai/integrations/google-ai-adk) [Platform]: Use when the user is on Google's Agent Development Kit.
- [Mastra](https://docs.mem0.ai/integrations/mastra) [Platform]: Use when the user is on Mastra (TypeScript).
-- [OpenClaw](https://docs.mem0.ai/integrations/openclaw) [Both]: Use when wiring Mem0 into Claude Code or editors via OpenClaw.
+- [OpenClaw](https://docs.mem0.ai/integrations/openclaw) [Both]: Use when adding persistent memory to OpenClaw agents with Mem0 Platform or a self-hosted backend.
- [Vercel AI SDK](https://docs.mem0.ai/integrations/vercel-ai-sdk) [Both]: Use when the user is on the Vercel AI SDK.
- [Vercel](https://docs.mem0.ai/integrations/vercel) [Platform]: Use when deploying on Vercel and installing Mem0 from the Vercel Marketplace.
- [Strands Agents](https://docs.mem0.ai/integrations/strands) [Both]: Use when the user is on AWS Strands and wants a native MemoryStore.
### AI Coding Tools
-- [Claude Code](https://docs.mem0.ai/integrations/claude-code) [Both]: Use when wiring memory into Claude Code.
+- [Claude Code](https://docs.mem0.ai/integrations/claude-code) [Platform]: Use when wiring memory into Claude Code.
- [Claude.ai](https://docs.mem0.ai/integrations/claude-ai) [Platform]: Use when connecting Mem0 to Claude.ai (the hosted web app) via a custom remote MCP connector, or when Claude's native memory seems to be crowding out mem0 tool calls.
-- [Cursor](https://docs.mem0.ai/integrations/cursor) [Platform]: Use when wiring memory into Cursor.
-- [Codex](https://docs.mem0.ai/integrations/codex) [Platform]: Use when wiring memory into Codex / other editor assistants.
-- [OpenCode](https://docs.mem0.ai/integrations/opencode) [Platform]: Use when wiring memory into OpenCode.
-- [Antigravity](https://docs.mem0.ai/integrations/antigravity) [Platform]: Use when wiring memory into Google Antigravity.
+- [Cursor](https://docs.mem0.ai/integrations/cursor) [Platform]: Use when adding lifecycle capture, explicit memory recall, and six memory skills to Cursor.
+- [Codex](https://docs.mem0.ai/integrations/codex) [Platform]: Use when adding automatic capture and recall, six memory skills, and a search tool to OpenAI Codex.
+- [Kimi Code](https://docs.mem0.ai/integrations/kimi) [Platform]: Use when adding persistent project memory to Kimi Code through its native plugin lifecycle.
+- [OpenCode](https://docs.mem0.ai/integrations/opencode) [Platform]: Use when adding ten native SDK memory tools, automatic context, seven skills, and project scoping to OpenCode.
+- [Antigravity](https://docs.mem0.ai/integrations/antigravity) [Platform]: Use when adding lifecycle capture, explicit recall, and six memory skills to Google Antigravity.
### Voice & Real-time
- [LiveKit](https://docs.mem0.ai/integrations/livekit) [Platform]: Use when building real-time voice/video with memory.
@@ -324,6 +328,7 @@ If the user is on a pre-current major (Python < 2, TS < 3, or a Platform call st
- [Healthcare Google ADK](https://docs.mem0.ai/cookbooks/integrations/healthcare-google-adk) [Platform]: Use when the domain is medical and the framework is Google ADK.
- [AWS Bedrock](https://docs.mem0.ai/cookbooks/integrations/aws-bedrock) [OSS]: Use when deploying with AWS managed model services.
- [Tavily Search](https://docs.mem0.ai/cookbooks/integrations/tavily-search) [Platform]: Use when the agent layers web search on memory.
+- [Company Brain (Mem0 Platform + Supabase)](https://docs.mem0.ai/cookbooks/integrations/supabase) [Platform]: Use to build a shared org brain on Mem0 Platform with Supabase as system of record and the MCP server as the access layer (with a new-hire onboarding demo).
### Framework Examples
- [LlamaIndex React](https://docs.mem0.ai/cookbooks/frameworks/llamaindex-react) [Both]: Use when building a React UI with LlamaIndex and memory.
@@ -361,6 +366,11 @@ All API Reference docs describe Mem0 Platform REST endpoints (requires API key).
### Entities
- [Get Users](https://docs.mem0.ai/api-reference/entities/get-users) [Platform]: Use when listing users, agents, or apps known to a project.
- [Delete User](https://docs.mem0.ai/api-reference/entities/delete-user) [Platform]: Use when removing an entity and all its memories.
+- [Get Profile](https://docs.mem0.ai/api-reference/profiles/get-profile) [Platform]: Use when reading a user's structured profile and branching on its generation status.
+- [Get Profile Settings](https://docs.mem0.ai/api-reference/profiles/get-profile-settings) [Platform]: Use when checking the project's profile schema, instructions, or enabled flag.
+- [Update Profile Settings](https://docs.mem0.ai/api-reference/profiles/update-profile-settings) [Platform]: Use when defining or changing the JSON Schema that shapes profiles for a project.
+- [Generate Profiles](https://docs.mem0.ai/api-reference/profiles/generate-profiles) [Platform]: Use when building profiles now: a sample of ten, or one entity.
+- [Get Generation Job](https://docs.mem0.ai/api-reference/profiles/get-profile-job) [Platform]: Use when checking how far a generation has got, and whether it finished.
### Organizations
- [Create Organization](https://docs.mem0.ai/api-reference/organization/create-org) [Platform]: Use when setting up a new org.
@@ -417,22 +427,25 @@ Each subdirectory is a Claude Code Skill (`SKILL.md` + supporting assets). Load
Source: https://github.com/mem0ai/mem0/tree/main/integrations/claude-code-plugin
-The `integrations/claude-code-plugin/` directory is the Claude Code plugin (v0.3.0, installs as `mem0@mem0-plugins`). It captures evidence locally through lifecycle hooks, extracts memories in a detached background worker, and exposes a single local MCP tool, `search_memories`, plus six `/mem0:*` skills and the `mem0:sidekick` agent. Pure-stdlib Python, nothing to install.
+The self-contained Claude Code plugin lives in `integrations/claude-code-plugin/` (v0.3.1, installs as `mem0@mem0-plugins`). It captures evidence locally through lifecycle hooks, extracts memories in a detached background worker, and exposes a single local MCP tool, `search_memories`, plus six `/mem0:*` skills and `mem0:sidekick`, available only in Claude Code. Pure-stdlib Python, nothing to install.
-### Editor Plugin (shared glue)
+### Coding-Agent Plugin Sources
-Source: https://github.com/mem0ai/mem0/tree/main/integrations/mem0-plugin
+Source: https://github.com/mem0ai/mem0/tree/main/integrations/agent-plugin-core
-The `integrations/mem0-plugin/` directory provides MCP server connection, lifecycle hooks, and skill bundling for Cursor, Codex, Kimi, Antigravity, and OpenCode. It exposes 9 MCP tools: `add_memory`, `search_memories`, `get_memories`, `get_memory`, `update_memory`, `delete_memory`, `delete_all_memories`, `delete_entities`, `list_entities`. Claude Code moved to `integrations/claude-code-plugin/` in v0.3.0; do not run both at the same time.
+The `integrations/agent-plugin-core/` directory is the single source for shared Python and TypeScript memory behavior. Native plugins live in their own sibling directories, while `integrations/mem0-agent-plugin/` is the single portable Agent Plugins v1 package. Sidekick is available only in Claude Code. The portable package provides search and skills but no automatic capture; its remember skill cannot save a new memory on its own. Shared Python search accepts optional `run_id` for session-specific recall in every scope. TypeScript integrations reuse the core's lifecycle, formatting, identity, scoping, and telemetry utilities while keeping their public packages and native host APIs unchanged.
Editor-specific setup docs (already listed above under `## Integrations > AI Coding Tools`):
-- `integrations/claude-code` [Both]
+- `integrations/claude-code` [Platform]
- `integrations/cursor` [Platform]
- `integrations/codex` [Platform]
+- `integrations/kimi` [Platform]
- `integrations/opencode` [Platform]
- `integrations/antigravity` [Platform]
- `integrations/openclaw` [Both]
+- `integrations/pi-agent` [Platform]
+- `integrations/deepseek-plugin` [Platform]
### MCP Endpoints
diff --git a/docs/migration/platform-v2-to-v3.mdx b/docs/migration/platform-v2-to-v3.mdx
index 8cc9690da..8a16dde57 100644
--- a/docs/migration/platform-v2-to-v3.mdx
+++ b/docs/migration/platform-v2-to-v3.mdx
@@ -136,8 +136,8 @@ curl -X POST 'https://api.mem0.ai/v3/memories/?page=1&page_size=50' \
| Parameter | V1/V2 | V3 | Notes |
|---|---|---|---|
| `top_k` | Supported | Supported (1-1000, default 10) | No change |
-| `threshold` | Default: none | Default: `0.1` | Pass `0.0` to disable |
-| `rerank` | Default: `true` | Default: `false` | Pass `true` to enable (adds latency) |
+| `threshold` | Default: `0.3` (v2) | Default: `0.1` | Pass `0.3` to keep the v2 cutoff, or `0.0` to disable |
+| `rerank` | Default: `false` | Default: `false` | No change. Pass `true` to enable (adds latency) |
| Entity IDs in `search` / `get_all` | Top-level | Inside `filters` dict | Top-level raises 400 |
### Response Format
@@ -265,10 +265,10 @@ If your application previously read graph relations from the API response (`rela
- The default `threshold` is now `0.1` (previously no threshold). If your application was relying on unfiltered results, explicitly pass `threshold=0.0` in your search calls to preserve the old behavior. In most cases, the new default is better: it filters out low-relevance noise.
+ The default `threshold` is now `0.1` (it was `0.3` on v2), so lower-scoring matches that v2 hid can now appear. Scores are computed differently in v3, so retune against representative queries. To keep a stricter cutoff, pass an explicit `threshold` in your search calls, or pass `threshold=0.0` to disable filtering.
- Reranking is now `false` by default. If your application depended on reranked results, add `rerank=True` to your search calls. Note that reranking adds latency (~200-400ms) but can improve ordering quality for complex queries.
+ Reranking is `false` by default, the same as on v2. If your application depends on reranked results, pass `rerank=True` to your search calls. Note that reranking adds latency (~200-400ms) but can improve ordering quality for complex queries.
The top-level `score` field continues to work as before. It is now a combined multi-signal score (semantic + keyword + entity) rather than pure cosine similarity, so the absolute numbers will differ. Relative ranking remains comparable: if you have threshold-based filtering in your app, retune on a representative query set.
diff --git a/docs/open-source/features/custom-instructions.mdx b/docs/open-source/features/custom-instructions.mdx
index 06a3acd10..b6d40f39f 100644
--- a/docs/open-source/features/custom-instructions.mdx
+++ b/docs/open-source/features/custom-instructions.mdx
@@ -1,7 +1,6 @@
---
-title: Custom Instructions
-seo:
- title: "Open Source Custom Instructions - Mem0"
+title: "Open Source Custom Instructions"
+sidebarTitle: "Custom Instructions"
description: Tailor fact extraction so Mem0 stores only the details you care about.
icon: "wand-magic-sparkles"
---
diff --git a/docs/open-source/features/multimodal-support.mdx b/docs/open-source/features/multimodal-support.mdx
index 7fb9f335b..b1697cced 100644
--- a/docs/open-source/features/multimodal-support.mdx
+++ b/docs/open-source/features/multimodal-support.mdx
@@ -1,7 +1,6 @@
---
-title: Multimodal Support
-seo:
- title: "Open Source Multimodal Support - Mem0"
+title: "Open Source Multimodal Support"
+sidebarTitle: "Multimodal Support"
description: Capture and recall memories from both text and images.
icon: "image"
---
diff --git a/docs/open-source/features/overview.mdx b/docs/open-source/features/overview.mdx
index 8e8379bd8..59c01f5f6 100644
--- a/docs/open-source/features/overview.mdx
+++ b/docs/open-source/features/overview.mdx
@@ -1,7 +1,6 @@
---
-title: "Overview"
-seo:
- title: "Open Source Features Overview - Mem0"
+title: "Open Source Features Overview"
+sidebarTitle: "Overview"
description: "Self-hosting features that extend Mem0 beyond basic memory storage"
icon: "list"
---
diff --git a/docs/open-source/features/rest-api.mdx b/docs/open-source/features/rest-api.mdx
index b798d242d..4a877907c 100644
--- a/docs/open-source/features/rest-api.mdx
+++ b/docs/open-source/features/rest-api.mdx
@@ -56,7 +56,7 @@ The Mem0 REST API server exposes every OSS memory operation over HTTP. Run it al
make bootstrap # starts Compose, creates an admin, issues the first API key
```
- Or to start the stack only and finish setup via the browser wizard at http://localhost:3000:
+ Or to start the stack only and finish setup via the browser wizard at `http://localhost:3000`:
```bash
cd server
diff --git a/docs/open-source/overview.mdx b/docs/open-source/overview.mdx
index 667172c08..0adb15003 100644
--- a/docs/open-source/overview.mdx
+++ b/docs/open-source/overview.mdx
@@ -1,7 +1,6 @@
---
-title: "Overview"
-seo:
- title: "Mem0 Open Source Overview"
+title: "Open Source Overview"
+sidebarTitle: "Overview"
description: "Self-host Mem0 with full control over your infrastructure and data"
icon: "house"
---
diff --git a/docs/openapi.json b/docs/openapi.json
index af215596f..f27449514 100644
--- a/docs/openapi.json
+++ b/docs/openapi.json
@@ -8070,6 +8070,480 @@
}
}
}
+ },
+ "/v2/entities/{entity_type}/{entity_id}/profile/": {
+ "get": {
+ "tags": [
+ "profiles"
+ ],
+ "operationId": "profiles_read",
+ "summary": "Get an entity's profile",
+ "description": "Return the memory profile for one user.\n\nGeneration is asynchronous, so a known entity that has no profile yet is a normal 200 carrying a `status`. A 404 means only that no such entity exists.",
+ "parameters": [
+ {
+ "name": "entity_type",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "enum": [
+ "user"
+ ]
+ },
+ "description": "The kind of entity that carries the profile."
+ },
+ {
+ "name": "entity_id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string"
+ },
+ "description": "The entity's id, as supplied when the memory was added."
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "The profile envelope.",
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "object",
+ "properties": {
+ "profile": {
+ "type": "object",
+ "additionalProperties": true,
+ "description": "The generated profile, shaped by the project's schema. Empty unless status is succeeded."
+ },
+ "status": {
+ "type": "string",
+ "enum": [
+ "succeeded",
+ "pending",
+ "failed",
+ "not_enabled",
+ "insufficient_data"
+ ],
+ "description": "Generation state. Branch on this rather than on an empty profile."
+ },
+ "entity_type": {
+ "type": "string",
+ "enum": [
+ "user"
+ ]
+ },
+ "entity_id": {
+ "type": "string"
+ },
+ "updated_at": {
+ "type": "string",
+ "format": "date-time",
+ "nullable": true
+ },
+ "generation_count": {
+ "type": "integer"
+ }
+ }
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "Unsupported entity type."
+ },
+ "404": {
+ "description": "No such entity in this project."
+ }
+ }
+ }
+ },
+ "/v2/profiles/settings/": {
+ "get": {
+ "tags": [
+ "profiles"
+ ],
+ "operationId": "profiles_settings_read",
+ "summary": "Get profile settings",
+ "description": "Return the profile settings for the project the API key is scoped to.",
+ "responses": {
+ "200": {
+ "description": "Current settings.",
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "object",
+ "properties": {
+ "enabled": {
+ "type": "boolean",
+ "description": "Whether profile generation runs for this project. Project-wide."
+ },
+ "entities": {
+ "type": "object",
+ "description": "Settings for user profiles, under `user`.",
+ "properties": {
+ "user": {
+ "type": "object",
+ "properties": {
+ "schema": {
+ "type": "object",
+ "additionalProperties": true,
+ "nullable": true,
+ "description": "JSON Schema describing the profile. Every property needs a description."
+ },
+ "custom_instructions": {
+ "type": "string",
+ "nullable": true,
+ "description": "Extra guidance for the extraction step."
+ }
+ }
+ }
+ }
+ },
+ "capabilities": {
+ "type": "object",
+ "properties": {
+ "jobs": {
+ "type": "boolean"
+ },
+ "estimates": {
+ "type": "boolean"
+ },
+ "samples": {
+ "type": "boolean"
+ },
+ "full_rebuild": {
+ "type": "boolean",
+ "description": "Whether a project-wide rebuild (regenerate/backfill) is available. Currently false."
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "post": {
+ "tags": [
+ "profiles"
+ ],
+ "operationId": "profiles_settings_update",
+ "summary": "Update profile settings",
+ "description": "Update the project's profile settings. Only the fields present in the body are written, so one setting can change without re-sending the others.",
+ "requestBody": {
+ "required": true,
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "object",
+ "description": "Only the fields present are written. `schema` and `custom_instructions` nest under `entities.user`; a flat body is rejected.",
+ "properties": {
+ "enabled": {
+ "type": "boolean",
+ "description": "Whether profile generation runs for this project. Project-wide."
+ },
+ "entities": {
+ "type": "object",
+ "description": "Settings for user profiles, under `user`.",
+ "properties": {
+ "user": {
+ "type": "object",
+ "properties": {
+ "schema": {
+ "type": "object",
+ "additionalProperties": true,
+ "nullable": true,
+ "description": "JSON Schema describing the profile. Every property needs a description. Send null to clear it."
+ },
+ "custom_instructions": {
+ "type": "string",
+ "nullable": true,
+ "description": "Extra guidance for the extraction step. Send null to clear it."
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "responses": {
+ "200": {
+ "description": "Settings as stored after the update.",
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "object",
+ "properties": {
+ "enabled": {
+ "type": "boolean",
+ "description": "Whether profile generation runs for this project. Project-wide."
+ },
+ "entities": {
+ "type": "object",
+ "description": "Settings for user profiles, under `user`.",
+ "properties": {
+ "user": {
+ "type": "object",
+ "properties": {
+ "schema": {
+ "type": "object",
+ "additionalProperties": true,
+ "nullable": true,
+ "description": "JSON Schema describing the profile. Every property needs a description."
+ },
+ "custom_instructions": {
+ "type": "string",
+ "nullable": true,
+ "description": "Extra guidance for the extraction step."
+ }
+ }
+ }
+ }
+ },
+ "capabilities": {
+ "type": "object",
+ "properties": {
+ "jobs": {
+ "type": "boolean"
+ },
+ "estimates": {
+ "type": "boolean"
+ },
+ "samples": {
+ "type": "boolean"
+ },
+ "full_rebuild": {
+ "type": "boolean",
+ "description": "Whether a project-wide rebuild (regenerate/backfill) is available. Currently false."
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "The schema is not a valid profile schema."
+ }
+ }
+ }
+ },
+ "/v2/profiles/jobs/": {
+ "post": {
+ "tags": [
+ "profiles"
+ ],
+ "operationId": "profiles_create_job",
+ "summary": "Generate profiles",
+ "description": "Start one generation. `operation` says what to build:\n\n- `sample` โ up to 10 real entities, so a schema can be judged before it is used widely. These are real profiles: they are saved to those entities and count toward usage.\n- `trigger` โ one entity, named by `entity_id`.\n\nSend an `Idempotency-Key` header. Replaying the same key returns the same job instead of charging twice. Poll `status_url` from the response until the status is terminal.",
+ "parameters": [
+ {
+ "in": "header",
+ "name": "Idempotency-Key",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "minLength": 8,
+ "maxLength": 128
+ },
+ "description": "Makes a retry safe: the same key returns the same job."
+ }
+ ],
+ "requestBody": {
+ "required": true,
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "object",
+ "required": [
+ "operation",
+ "entity_type"
+ ],
+ "properties": {
+ "operation": {
+ "type": "string",
+ "enum": [
+ "sample",
+ "trigger"
+ ],
+ "description": "What to generate. Optional only when `entity_id` is set, which means `trigger`."
+ },
+ "entity_type": {
+ "type": "string",
+ "enum": [
+ "user"
+ ]
+ },
+ "entity_id": {
+ "type": "string",
+ "description": "One entity, for `trigger`."
+ },
+ "limit": {
+ "type": "integer",
+ "minimum": 1,
+ "maximum": 10,
+ "description": "How many entities to sample."
+ }
+ }
+ }
+ }
+ }
+ },
+ "responses": {
+ "202": {
+ "description": "Job accepted.",
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "object",
+ "properties": {
+ "job_id": {
+ "type": "string"
+ },
+ "status": {
+ "type": "string"
+ },
+ "status_url": {
+ "type": "string",
+ "description": "Poll this. Building the path yourself breaks on a route change."
+ },
+ "operation": {
+ "type": "string"
+ },
+ "entity_type": {
+ "type": "string"
+ },
+ "entity_count_reserved": {
+ "type": "integer",
+ "description": "Entities reserved against usage for this job."
+ },
+ "event_id": {
+ "type": "string",
+ "nullable": true
+ },
+ "replayed": {
+ "type": "boolean",
+ "description": "True when an Idempotency-Key returned an existing job."
+ },
+ "sampled": {
+ "type": "integer",
+ "description": "`sample` only."
+ },
+ "entity_ids": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "description": "`sample` only: the entity ids picked. Read each with `GET /v2/entities/user/{entity_id}/profile/`."
+ }
+ }
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "Unknown or missing `operation`, or profiles are not configured."
+ },
+ "402": {
+ "description": "Payment required."
+ },
+ "409": {
+ "description": "A job is already running, or the Idempotency-Key was used for a different request. Branch on `error.code`."
+ },
+ "429": {
+ "description": "Cooldown. `retry_after_seconds` sits inside `error`."
+ },
+ "503": {
+ "description": "`jobs_unavailable` โ generation is switched off for this project."
+ }
+ }
+ }
+ },
+ "/v2/profiles/jobs/{job_id}/": {
+ "get": {
+ "tags": [
+ "profiles"
+ ],
+ "operationId": "profiles_get_job",
+ "summary": "Read a generation job",
+ "description": "The job nests under `job`. `total` is null until `enumeration_complete`, and `completed` is `succeeded + failed + skipped`.",
+ "parameters": [
+ {
+ "in": "path",
+ "name": "job_id",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "The job.",
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "object",
+ "properties": {
+ "job": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string"
+ },
+ "operation": {
+ "type": "string"
+ },
+ "entity_type": {
+ "type": "string"
+ },
+ "status": {
+ "type": "string",
+ "enum": [
+ "QUEUED",
+ "RUNNING",
+ "SUCCEEDED",
+ "PARTIALLY_SUCCEEDED",
+ "FAILED",
+ "CANCELLED"
+ ]
+ },
+ "total": {
+ "type": "integer",
+ "nullable": true
+ },
+ "enumeration_complete": {
+ "type": "boolean"
+ },
+ "completed": {
+ "type": "integer"
+ },
+ "succeeded": {
+ "type": "integer"
+ },
+ "failed": {
+ "type": "integer"
+ },
+ "skipped": {
+ "type": "integer"
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "No such job in this project."
+ }
+ }
+ }
}
},
"components": {
@@ -8988,4 +9462,4 @@
}
},
"x-original-swagger-version": "2.0"
-}
\ No newline at end of file
+}
diff --git a/docs/platform/cli.mdx b/docs/platform/cli.mdx
index 21d48d29e..e34f0aa59 100644
--- a/docs/platform/cli.mdx
+++ b/docs/platform/cli.mdx
@@ -1,7 +1,6 @@
---
-title: CLI
-seo:
- title: "Mem0 CLI for Terminal Memory Management"
+title: "CLI for Terminal Memory Management"
+sidebarTitle: "CLI"
description: "Manage memories from your terminal, for both humans and AI agents."
icon: "terminal"
iconType: "solid"
diff --git a/docs/platform/copilot.mdx b/docs/platform/copilot.mdx
new file mode 100644
index 000000000..3d218ff84
--- /dev/null
+++ b/docs/platform/copilot.mdx
@@ -0,0 +1,194 @@
+---
+title: "Mem0 Copilot"
+description: "Inspect project memories, review configuration changes, and test extraction from the Mem0 dashboard."
+icon: "message"
+---
+
+Copilot is an AI assistant in the [Mem0 dashboard](https://app.mem0.ai/dashboard/copilot). Ask it to inspect stored memories, suggest extraction rules and categories, change project settings, or explain the platform SDKs and APIs.
+
+You describe the task in chat. Copilot uses tools to read project data or propose changes. In **Review changes** mode, you approve each change before it runs.
+
+## Start with your project
+
+1. Sign in to the dashboard and select the organization and project you want to work on.
+2. Open **Copilot** in the sidebar.
+3. Select **Review changes** below the message box.
+4. Ask: โShow my current project settings and explain what each one does.โ
+5. Expand an activity card, such as **Read project config**, to see its **Input** and **Result**. Check these results when reviewing an answer or confirming a change.
+
+You can ask about settings or SDK usage with an empty project. Suggestions based on stored data need enough project history to analyze.
+
+## Inspect stored memories
+
+Start with a project overview, then narrow the question:
+
+| Prompt | What to inspect |
+| --- | --- |
+| โSummarize what this project has stored and how it is categorized.โ | The memories and category patterns Copilot reads. Check which records support its summary. |
+| โAnalyze the memories for user alice.โ | Facts stored for `alice`, their categories, and unwanted information. To investigate a missing fact, also provide the original input. |
+| โSearch alice's memories for dietary preferences.โ | Memories relevant to the query within that user's scope. |
+
+Copilot can list memories across the project. Searching by meaning needs a specific User, Agent, App, or Run ID. Select one in **Scope** or name it in your prompt.
+
+Memory lists are paginated, and suggestions use samples. Check the activity results to see which records were read. Ask for more pages when you need to inspect the rest.
+
+### Choose the memory scope
+
+Open **Scope** below the message box. Select an existing ID or type one and choose it.
+
+| Control | Identifies |
+| --- | --- |
+| **User** | The end user whose memories you want to inspect, such as `alice`. |
+| **Agent** | An AI agent associated with the memories. |
+| **App** | An application associated with the memories. |
+| **Run** | A particular execution or session associated with the memories. |
+
+A field set to **any** adds no filter for that entity type. **Clear scope** removes the selections. Scope gives Copilot default IDs to use; you can request a different entity in a message. Check the activity's **Input** to confirm which IDs it used. Adding a test memory requires a **User** ID, even when another entity is selected.
+
+
+ Scope selects memories, not separate settings. Categories, extraction instructions, memory depth, and multilingual settings apply to the selected project. Category and extraction suggestions also analyze project data, regardless of the selected entity.
+
+
+See [Entity-scoped memory](/platform/features/entity-scoped-memory) for how these IDs organize memories in your application.
+
+## Review and apply changes
+
+The mode control below the message box determines when changes run:
+
+- **Review changes**: Copilot pauses before changing project configuration or adding a test memory. Read the proposal and choose whether to apply it.
+- **Auto-apply**: Copilot can change settings and add test memories without asking for approval. Check the selected project and scope before using it.
+
+Ask Copilot to show the current settings before requesting an update. In the approval card, review every listed field. Approving the card applies the whole proposal, including fields you did not edit.
+
+| Action | Effect |
+| --- | --- |
+| **Apply change** | Approve the proposed write. Inspect the subsequent result to confirm it succeeded. |
+| **Edit** | When offered, edit extraction instructions or category names and descriptions. Choose **Apply with edits** to submit your revision. |
+| **Discard edits** | Return to the original proposal without applying it. |
+| **Decline** | Reject this proposal without applying it. |
+| **Ask for something else** | Enter feedback and choose **Send**. This declines the current proposal and sends your feedback as a new message. Review the next proposal before applying it. |
+
+Not every field has an inline editor. If a proposal includes both extraction instructions and categories, only the instructions get an editor. The editor cannot apply blank instructions or an empty category list. Use **Ask for something else** to change other fields or request separate proposals.
+
+
+ A generated prompt profile contains separate prompts for extraction and summaries. If your project uses one, saving extraction instructions through Copilot deactivates it. Review the replacement rules and test the affected behavior before using them in production.
+
+
+## What Copilot cannot do
+
+Copilot cannot perform these actions, even in **Auto-apply** mode:
+
+- Create or delete API keys.
+- Directly edit or delete existing memories.
+- Export project data.
+- Invite or remove organization or project members, or change their roles and permissions.
+- Create or delete organizations or projects.
+- Change billing details or subscription plans.
+
+Use the dashboard or the relevant platform API for these tasks. Copilot can explain the steps or point you to documentation, but it cannot carry out the actions.
+
+Copilot supports the managed Mem0 platform. It does not help configure or use the [self-hosted open-source library](/open-source/overview).
+
+## Example 1: Stop storing small talk, then test extraction
+
+This walkthrough uses a project where you have noticed greetings or small talk in stored memories. Use a development project when trying configuration changes, since a test user does not isolate project settings.
+
+
+
+ Select the project, set **User** to `alice`, and ask:
+
+ > Analyze the memories for user alice.
+
+ Inspect the returned memories. Identify examples of small talk you want to exclude and useful facts you still want to keep.
+
+
+ With **Review changes** selected, ask:
+
+ > Update my extraction instructions to ignore greetings and small talk. Keep the existing rules for durable user preferences.
+
+ Check for a **Read project config** activity before reviewing the update. If it is missing, ask Copilot to read the current instructions first. If analysis reports insufficient data, ask it to use the rule you provided. You can also set the rule directly through [Custom instructions](/platform/features/custom-instructions).
+
+
+ Review the full replacement text. Keep existing rules your application needs. For this test, the relevant rules could look like:
+
+ ```text
+ Remember the following:
+
+ * The user's dietary preferences and food restrictions.
+
+ Don't remember the following:
+
+ * Greetings and small talk.
+ ```
+
+ Use **Edit** to adjust the wording, or **Ask for something else** to request a revision.
+
+ Choose **Apply change** or **Apply with edits**, then inspect the result to confirm the instructions were saved.
+
+
+ Choose a new **User** ID for this test, such as `copilot-extraction-test-01`, and clear any other entity selections. Ask:
+
+ > Add this as a user message for copilot-extraction-test-01: โHi! How's your day? I prefer vegetarian meals and avoid peanuts.โ
+
+ Review the test-memory proposal and choose **Apply change**.
+
+
+ Adding a test memory writes to the selected project. It is not a dry run. Use a dedicated test user so you can find and remove the test data afterward.
+
+
+
+ Expand **Add test memory** and inspect **Result**. A `PENDING` status means extraction is still running. Use the returned `event_id` with the [Get Event API](/api-reference/events/get-event) to check progress. Wait for `SUCCEEDED` before evaluating the output. If the event is `FAILED`, inspect its details before retrying.
+
+ Then ask:
+
+ > List all memories for user copilot-extraction-test-01. Then search that user's memories for dietary preferences.
+
+ Check that the memories retain the vegetarian preference and peanut restriction, and exclude the greeting. Inspect the full list as well as search results: a relevant search can hide unwanted small-talk records.
+
+ If the output is wrong, describe the mismatch and review another instruction change. Use a new test user for the next attempt so earlier memories do not affect the result. Remove test data afterward through the dashboard or [memory deletion API](/api-reference/memory/delete-memories).
+
+
+
+Test with new inputs after changing settings. Updating configuration is not a cleanup operation for existing memories. See [Custom instructions](/platform/features/custom-instructions) for guidance on writing extraction rules.
+
+## Example 2: Suggest categories and extraction instructions
+
+These workflows sample the selected project's data. Generating a suggestion does not update settings by itself. Copilot can then propose applying it, which follows the selected review mode. Use **Review changes** to inspect suggestions before they are saved.
+
+| Workflow | Data used | Example prompt |
+| --- | --- | --- |
+| Custom categories | Stored memories, excluding deleted memories. | โSuggest custom categories from this project's memories.โ |
+| Extraction instructions | Successful requests to add conversation data, including requests that produced no memories. | โCompare recent add requests with the extracted memories and suggest better extraction instructions.โ |
+
+Category suggestions identify recurring themes. Review the names, descriptions, and examples. Applying a category list replaces the project's previous list; it does not add to it or re-tag existing memories. See [Custom categories](/platform/features/custom-categories) for project and per-call behavior.
+
+Extraction suggestions compare conversation inputs with what was extracted. One add request can produce several memories or none, so the number of add requests is different from the number of stored memories. Keep your application's existing requirements when reviewing the proposal.
+
+Both workflows require enough project data. If a suggestion fails because there is too little data, check the activity's **Result** for the current and required counts. You can still inspect memories, ask SDK/API questions, or provide your own rules instead of requesting a data-based suggestion.
+
+## Example 3: Adjust detail and language
+
+Ask Copilot to read the current settings, then request the change you need:
+
+- **Memory depth** controls the level of detail: **Less**, **Medium**, or **More detailed**. Try โShow my current memory depth, then propose More detailed memories.โ For deciding *which facts* to retain, use extraction instructions.
+- **Multilingual** behavior preserves the user's original language. Try โEnable multilingual behavior so memories preserve the language of the input.โ Test it with a new conversation in the language your application uses.
+
+Both are project settings. Review the proposed values and test a fresh input after applying them. See [Organization and project settings](/api-reference/organizations-projects) for configuration through the API.
+
+## Example 4: Ask SDK and API questions
+
+Include your language and the task, for example:
+
+> Show me how to search memories for user alice with the managed Mem0 Python SDK. Link the documentation you used.
+
+Copilot can look up the official platform documentation. Check the **Browse mem0 docs** and **Read docs page** activities and open the cited pages. If an answer has no sources, ask for them before using the example. The [Platform quickstart](/platform/quickstart) covers adding and searching memories in code.
+
+## Resume a conversation and check message limits
+
+Use **History** to reopen your 50 most recently active chats for the selected project. Chats belong to the person who created them; other project members cannot open them. Use **New chat** to start a separate conversation, or **Delete chat** in history to remove one. Deleting a chat does not undo settings changes or remove test memories.
+
+Message allowances depend on the organization's plan and are shared across its projects and members. They reset at the start of each calendar month in UTC.
+
+For plans with a limit, a usage notice appears once 80% of the allowance is used. Below that point, no counter is shown. At the limit, new messages are disabled until the allowance resets or the plan is upgraded. Follow the notice's upgrade link to review plan options.
+
+Sending feedback through **Ask for something else** counts as a new message. Approving or declining a saved proposal without feedback does not use another message. Test additions and searches also use the platform APIs and remain subject to their normal quotas.
diff --git a/docs/platform/features/async-client.mdx b/docs/platform/features/async-client.mdx
index 6effd9995..964fb1ce5 100644
--- a/docs/platform/features/async-client.mdx
+++ b/docs/platform/features/async-client.mdx
@@ -124,7 +124,7 @@ await client.deleteAll({ userId: "alice" });
- At least one filter (`user_id`, `agent_id`, `app_id`, or `run_id`) is required: calling `delete_all` with no filters raises an error to prevent accidental data loss. You can pass `"*"` as a value to delete all memories for a given entity type (e.g., `user_id="*"` removes memories for every user). A full project wipe requires all four filters set to `"*"`. When multiple entity filters are combined on a single `delete_all` call, only one is currently guaranteed to be honored; scope each call to a single entity id to be safe.
+ At least one filter (`user_id`, `agent_id`, `app_id`, or `run_id`) is required: calling `delete_all` with no filters raises an error to prevent accidental data loss. You can pass `"*"` as a value to delete all memories for a given entity type (e.g., `user_id="*"` removes memories for every user). A full project wipe requires all four filters set to `"*"`. When multiple entity filters are combined on a single `delete_all` call, only one is currently guaranteed to be honored; scope each call to a single entity id to be safe. Entity IDs are top-level arguments, not `filters`, and an empty or whitespace-only ID raises an error instead of matching every memory.
### History
diff --git a/docs/platform/features/byok.mdx b/docs/platform/features/byok.mdx
new file mode 100644
index 000000000..6a57c6cd8
--- /dev/null
+++ b/docs/platform/features/byok.mdx
@@ -0,0 +1,126 @@
+---
+title: "Bring Your Own Key (BYOK)"
+sidebarTitle: "BYOK"
+description: "Run memory creation on your own LLM provider and model, billed to your own API key."
+---
+
+## Overview
+
+With Bring Your Own Key (BYOK), Mem0 runs the LLM calls that turn your messages into memories on a model you choose, using your own API key. Mem0 sends your message text to that provider under your account, and your provider bills you directly. If your key stops working, Mem0 doesn't switch to its own key. The add fails and shows why. Embeddings, search and reranking still run on Mem0.
+
+## Where to find it
+
+BYOK is set per organization, in **Settings โ BYOK** in the [Mem0 dashboard](https://app.mem0.ai/dashboard/settings?tab=org-llm). Only organization owners see this tab. One key covers every project in the organization.
+
+
+ Organizations created through the Vercel Marketplace are managed from Vercel and can't use BYOK.
+
+
+## Supported providers
+
+| Provider | What you need | Model |
+|---|---|---|
+| OpenAI | An OpenAI API key | Pick from the list or enter any OpenAI model ID. GPT-6 Luna is recommended for best value. |
+| Anthropic | An Anthropic API key | Pick from the list or enter any Claude model ID. Claude Haiku 5.5 is recommended for best value. |
+| OpenRouter | An OpenRouter API key | Pick from the list or enter any OpenRouter model ID, such as `deepseek/deepseek-v4.1-flash`. DeepSeek V4.1 Flash is recommended for best value. |
+| Azure OpenAI | An API key and your endpoint URL | Your deployment name |
+
+For Azure OpenAI, use your resource's endpoint from the Azure portal, such as `https://your-resource.openai.azure.com/`.
+
+## Set up BYOK
+
+
+
+Go to **Settings โ BYOK** in the dashboard.
+
+
+Pick OpenAI, Anthropic, OpenRouter or Azure OpenAI from the **Provider** list.
+
+
+The **Model** list shows the models we tested, with a **Recommended** tag on our pick for that provider. Under the model, the tab shows its estimated cost per 1,000 adds on your provider account.
+
+To use a model that isn't in the list, choose **Other model ID** and type the model ID exactly as your provider names it. For Azure OpenAI, type your deployment name in **Deployment / Model**.
+
+
+Paste your key into **API key**. For Azure OpenAI, also fill in **Endpoint URL**.
+
+
+Click **Save key**. Mem0 sends a short test request to your provider with your key and model, then saves them. When the test passes, the top of the tab shows your provider and model, such as **Running on OpenAI ยท gpt-6-luna**.
+
+
+
+Mem0 encrypts your key and never shows it again. To change only the model, pick the new model and leave **API key** empty to keep the saved key. To stop using BYOK, click **Remove key**. New adds then run on Mem0's default model, within your plan's limits.
+
+## Errors and rate limits
+
+### When you save a key
+
+If the test request finds one of these problems, Mem0 doesn't save the key:
+
+| Message | What to check |
+|---|---|
+| The provider rejected the API key. Double-check the key and try again. | The key is wrong, revoked, or from a different provider. |
+| The provider couldn't find that model or deployment. Double-check the Model name and try again. | The model ID is misspelled, your account can't use that model, or the Azure deployment doesn't exist on that resource. |
+| Could not reach the endpoint. Double-check the Endpoint URL and try again. | The Azure OpenAI **Endpoint URL** is misspelled, doesn't exist, or isn't reachable. |
+| The Endpoint URL responded unexpectedly (HTTP โฆ). Double-check the Endpoint URL and try again. | The Azure OpenAI **Endpoint URL** doesn't point to an Azure OpenAI resource. |
+| Could not reach the provider. Try again in a moment. | Mem0 couldn't connect to your provider. This is usually brief. |
+| The provider responded unexpectedly (HTTP โฆ). Try again in a moment. | Your provider returned an error Mem0 didn't expect. |
+
+Some problems don't stop the save, because they can be fixed on your provider's side without changing anything in Mem0. In that case Mem0 saves the key and shows a warning at the top of the tab that names your provider. For example, with an OpenAI key:
+
+- **No credit:** "Key saved, but OpenAI says this account has no credit. Adds will fail until you add credit with OpenAI."
+- **Rate limited:** "Key saved, but OpenAI is rate limiting requests right now. Adds may fail until the limit resets."
+
+After you add credit or the limit resets, click **Check again** to run the test again on the saved key.
+
+### When an add fails
+
+Adds run in the background. Each add returns an `event_id`, and you can follow it with [Get Event](/api-reference/events/get-event). When an add fails for one of the reasons below, the event ends as `FAILED` and its `error` field says why:
+
+```json
+{
+ "id": "6f1d3a2e-8c4b-4f6a-9d2e-1b7c5a9e0f42",
+ "event_type": "ADD",
+ "status": "FAILED",
+ "error": "The configured LLM provider account is out of quota or credits."
+}
+```
+
+| `error` | What to do |
+|---|---|
+| The configured LLM provider rejected the API credentials. | Save a valid key in **Settings โ BYOK**. |
+| The configured LLM provider account is out of quota or credits. | Add credit with your provider. |
+| The configured LLM model or deployment was not found. | Pick a model your account can use, or fix the Azure deployment name. |
+| The configured LLM provider returned a response that could not be parsed. | Switch to a model from the **Model** list. This model replied in a format Mem0 couldn't read. |
+| The configured LLM credentials could not be read. Please re-save your provider settings. | Save your key again in **Settings โ BYOK**. |
+| Input exceeds the model's context window. | Send shorter messages, or pick a model with a larger context window. |
+
+In the dashboard, open the failed add on the **Requests** page to see the same reason. Mem0 doesn't retry these adds, so send them again after you fix the cause.
+
+### Rate limits and temporary errors
+
+When your provider rate limits a request, times out or returns a server error, Mem0 retries it automatically, so the add can take longer to finish. If this happens often, raise the rate limits on your provider account.
+
+## Choose a model
+
+Three things decide which model fits:
+
+- **Accuracy:** how well the memories a model writes answer questions later.
+- **Cost:** what your provider charges for the calls behind one add.
+- **Latency:** how long it takes from sending an add until its memories show up in search.
+
+We measured these on [LoCoMo](https://github.com/snap-research/locomo), a public benchmark of long conversations, for a limited set of popular models. Your own data can give different results. Based on what we measured, these are our picks: **Best value** balances accuracy and price, **Best under \$1** is the most accurate model under \$1 per 1,000 add requests, and **Best quality** has the highest accuracy.
+
+
+
+
+
+
+The latency above is for adds, which run asynchronously: the add call returns an event ID right away, and the memories become searchable once processing finishes. Search doesn't use your model, and its server-side latency is about 270 ms at p50 and 640 ms at p95.
+
+
+Accuracy against cost for every model we tested. The green line marks the best accuracy available at each price, the gold area holds the models under $2 per 1,000 add requests, and the gray dashed line is Mem0's default model, at 92.5%.
+
+
+
+
diff --git a/docs/platform/features/custom-instructions.mdx b/docs/platform/features/custom-instructions.mdx
index 923c8f5dc..9acd741f2 100644
--- a/docs/platform/features/custom-instructions.mdx
+++ b/docs/platform/features/custom-instructions.mdx
@@ -1,7 +1,6 @@
---
-title: Custom Instructions
-seo:
- title: "Platform Custom Instructions - Mem0"
+title: "Platform Custom Instructions"
+sidebarTitle: "Custom Instructions"
description: 'Control how Mem0 extracts and stores memories using natural language guidelines'
---
@@ -154,7 +153,7 @@ Both fields are also accepted per request, overriding the project setting for th
```python Python
client.add(
messages,
- filters={"agent_id": "support-agent"},
+ agent_id="support-agent",
agent_custom_instructions="Only remember which tools errored and why.",
)
```
diff --git a/docs/platform/features/multimodal-support.mdx b/docs/platform/features/multimodal-support.mdx
index 4c450ea37..3de9e0177 100644
--- a/docs/platform/features/multimodal-support.mdx
+++ b/docs/platform/features/multimodal-support.mdx
@@ -1,7 +1,6 @@
---
-title: Multimodal Support
-seo:
- title: "Platform Multimodal Support - Mem0"
+title: "Platform Multimodal Support"
+sidebarTitle: "Multimodal Support"
description: Integrate images and documents into your interactions with Mem0
---
diff --git a/docs/platform/features/user-profiles.mdx b/docs/platform/features/user-profiles.mdx
new file mode 100644
index 000000000..1e99f59ea
--- /dev/null
+++ b/docs/platform/features/user-profiles.mdx
@@ -0,0 +1,359 @@
+---
+title: Profiles
+description: "Build a structured, always-current summary of each user from their memories, shaped by a JSON Schema you define."
+---
+
+# Profiles
+
+Memories are individual facts. A profile is the summary of all of them for one entity: a single structured object, shaped by a JSON Schema you define, that Mem0 keeps current as new memories arrive.
+
+Search answers "what did this user say about X". A profile answers "who is this user", in one read, with no query to write.
+
+
+ **Use profiles whenโฆ**
+ - You want to personalize a first response, before the user says anything in this session.
+ - You need a compact object to drop into a prompt instead of a list of memories.
+ - You want the same fields for every user, so your code can rely on their shape.
+
+
+
+ User Profiles are in **beta** and available on request. To enable them for your
+ organization, contact [support@mem0.ai](mailto:support@mem0.ai).
+
+
+## How it works
+
+1. You define a **schema**: the fields a profile should contain, each with a description.
+2. Mem0 builds each entity's profile from their memories, and rebuilds it as new memories arrive.
+3. You read the profile whenever you need it.
+
+Generation is **asynchronous**. A profile is not ready the instant an entity's first memory lands, so a read tells you where it is with a `status` rather than failing.
+
+## Define the schema
+
+The schema is JSON Schema. Every property needs a `description` โ that is what tells the model how to fill the field, so a vague description gives a vague profile.
+
+
+```python Python
+from mem0 import MemoryClient
+
+client = MemoryClient()
+
+client.update_profile_settings(
+ enabled=True,
+ schema={
+ "type": "object",
+ "properties": {
+ "communication_style": {
+ "type": "string",
+ "description": "How the user prefers to be addressed: terse, detailed, formal, casual",
+ },
+ "expertise_areas": {
+ "type": "array",
+ "items": {"type": "string"},
+ "description": "Subjects the user demonstrates working knowledge of",
+ },
+ "current_goals": {
+ "type": "array",
+ "items": {"type": "string"},
+ "description": "What the user is actively trying to accomplish",
+ },
+ },
+ },
+ custom_instructions="Prefer durable traits over one-off remarks.",
+)
+```
+
+```typescript TypeScript
+import MemoryClient from "mem0ai";
+
+const client = new MemoryClient({ apiKey: "your-api-key" });
+
+await client.updateProfileSettings({
+ enabled: true,
+ schema: {
+ type: "object",
+ properties: {
+ communication_style: {
+ type: "string",
+ description:
+ "How the user prefers to be addressed: terse, detailed, formal, casual",
+ },
+ expertise_areas: {
+ type: "array",
+ items: { type: "string" },
+ description: "Subjects the user demonstrates working knowledge of",
+ },
+ current_goals: {
+ type: "array",
+ items: { type: "string" },
+ description: "What the user is actively trying to accomplish",
+ },
+ },
+ },
+ customInstructions: "Prefer durable traits over one-off remarks.",
+});
+```
+
+
+
+ Your schema's property names reach the API exactly as you write them. The SDKs do not rewrite them, so a profile always comes back with the field names you chose.
+
+
+Only the fields you pass are written. To turn the feature off without touching your schema, send `enabled` alone.
+
+## Read a profile
+
+
+```python Python
+result = client.get_profile("alice")
+
+if result["status"] == "succeeded":
+ print(result["profile"])
+else:
+ print("not ready:", result["status"])
+```
+
+```typescript TypeScript
+const result = await client.getProfile({ entityId: "alice" });
+
+if (result.status === "succeeded") {
+ console.log(result.profile);
+} else {
+ console.log("not ready:", result.status);
+}
+```
+
+
+A response looks like this:
+
+```json
+{
+ "profile": {
+ "communication_style": "terse",
+ "expertise_areas": ["distributed systems", "postgres"],
+ "current_goals": ["cut p99 latency", "migrate off the legacy queue"]
+ },
+ "status": "succeeded",
+ "entity_type": "user",
+ "entity_id": "alice",
+ "updated_at": "2026-02-08T10:30:00Z",
+ "generation_count": 3
+}
+```
+
+`generation_count` is how many times this profile has been (re)generated โ `0` before the first generation completes.
+
+### Always branch on `status`
+
+`profile` is empty unless `status` is `succeeded`. Check the status rather than the emptiness of the object, so a profile that is merely still building is not mistaken for a user you know nothing about.
+
+| `status` | Meaning | What to do |
+|---|---|---|
+| `succeeded` | Profile is built and current | Use it |
+| `pending` | Generation is queued or running | Read again shortly |
+| `insufficient_data` | Not enough memories to say anything yet | Fall back to defaults |
+| `not_enabled` | Profiles are off for this project | Enable them in settings |
+| `failed` | The last generation did not complete | Retry, or trigger a new one |
+
+A `404` means only that no such entity exists in your project.
+
+## Generate a profile on demand
+
+Profiles are built once an entity has accumulated enough messages, so a brand-new user has none during their first few interactions. Trigger one directly to close that gap:
+
+
+```python Python
+client.generate_profile("alice")
+```
+
+```typescript TypeScript
+await client.generateProfile({ entityId: "alice" });
+```
+
+
+The call returns as soon as the work is queued. Poll the read endpoint and branch on `status`.
+
+## Test a schema before applying it
+
+A schema that reads well can still produce disappointing profiles. Sample a few real entities and inspect the output before committing to it.
+
+Sampling is asynchronous: the call returns a job as soon as it is queued. Poll `status_url` until the job is terminal, then read each sampled entity's profile:
+
+
+```python Python
+import time
+
+job = client.sample_profiles(limit=5)
+
+# Poll until the sample job reaches a terminal state (job status is UPPERCASE).
+TERMINAL = {"SUCCEEDED", "PARTIALLY_SUCCEEDED", "FAILED", "CANCELLED"}
+deadline = time.time() + 120
+while True:
+ status = client.get_profile_job(job["status_url"])["job"]
+ if status["status"] in TERMINAL:
+ break
+ if time.time() > deadline:
+ raise TimeoutError("Sample job did not finish in time")
+ time.sleep(3)
+
+print(status["status"], status["succeeded"], "of", status["total"])
+
+# The create response lists the sampled entities; read each one's saved profile.
+for entity_id in job.get("entity_ids", []):
+ print(client.get_profile(entity_id))
+```
+
+```typescript TypeScript
+const job = await client.sampleProfiles({ limit: 5 });
+
+// Poll until the sample job reaches a terminal state (job status is UPPERCASE).
+const TERMINAL = ["SUCCEEDED", "PARTIALLY_SUCCEEDED", "FAILED", "CANCELLED"];
+const deadline = Date.now() + 120_000;
+let status;
+while (true) {
+ status = (await client.getProfileJob(job.statusUrl)).job;
+ if (TERMINAL.includes(status.status)) break;
+ if (Date.now() > deadline)
+ throw new Error("Sample job did not finish in time");
+ await new Promise((resolve) => setTimeout(resolve, 3000));
+}
+
+console.log(status.status, status.succeeded, "of", status.total);
+
+// The create response lists the sampled entities; read each one's saved profile.
+for (const entityId of job.entityIds ?? []) {
+ console.log(await client.getProfile({ entityId }));
+}
+```
+
+
+These are real generations. The profiles are saved to those entities and count toward your usage, so sampling is not wasted work and not a free dry run. A sample covers up to 10 entities and cannot be repeated immediately.
+
+## Apply a new schema to existing entities
+
+A new schema shapes the next generation. Profiles that already exist keep their values until their entity is generated again.
+
+Each entity picks the new schema up as it sends more memories, and you can generate one now with `generate_profile`.
+
+
+Rebuilding every profile in a project at once is not available yet. Refresh profiles one entity at a time with `generate_profile`, or let each one update on its own as its entity sends more memories.
+
+
+## When profiles update
+
+You never call an "update profile" endpoint โ Mem0 keeps each profile current for you. Two things drive it:
+
+- **Automatically, as memories accumulate.** Mem0 refreshes an entity's profile after roughly every **10 messages** it receives, folding the new memories into the existing profile. There is no schedule to wait for and no extra call to make: the same `add` you already do keeps the profile moving.
+- **On demand.** Call `generate_profile` to build or refresh a profile immediately โ useful for a brand-new entity that has not yet crossed the automatic threshold.
+
+Generation is **asynchronous and incremental**. A refresh runs in the background a short while after its trigger, so a read taken immediately after an `add` may still show the previous profile (or `pending`). Branch on `status` rather than assuming the latest memory is already reflected.
+
+
+ Updates are **incremental**, not a full rebuild each time โ Mem0 merges what it newly learns into the stored profile and keeps the fields your schema still defines. After a schema change, existing profiles pick it up as their entities send more memories, or when you call `generate_profile` โ see [Apply a new schema to existing entities](#apply-a-new-schema-to-existing-entities).
+
+
+## Use a profile in a prompt
+
+The point of the structure is that it drops straight into a prompt:
+
+```python
+result = client.get_profile(user_id)
+
+if result["status"] == "succeeded":
+ profile = result["profile"]
+ system_prompt = f"""You are helping {user_id}.
+Communication style: {profile.get("communication_style", "unknown")}
+Areas of expertise: {", ".join(profile.get("expertise_areas", []))}
+Current goals: {", ".join(profile.get("current_goals", []))}
+
+Match their style and do not explain what they already know."""
+else:
+ system_prompt = "You are a helpful assistant."
+```
+
+## Writing a schema that works
+
+- **Describe every field.** The description is the instruction; without it the model guesses.
+- **Prefer durable traits.** "Prefers dark mode" ages well; "is annoyed today" does not.
+- **Keep it small.** Ten focused fields beat forty speculative ones, and cost less to generate.
+- **Say what the field is not.** A description that rules out the near-miss interpretation is worth more than one that only states the obvious.
+- **Sample before you commit.** It is the only way to see what your descriptions actually produce.
+
+
+ A schema has a size budget of roughly **10,000 tokens** of serialized JSON โ the whole schema is sent to the model on every generation, so a handful of verbose fields can cost more than many terse ones. Oversized schemas are rejected on save.
+
+
+## Availability
+
+The feature is in beta and enabled per organization on request โ see the note at the top of this page.
+
+Once it is on, an entity gets a profile when two more things hold:
+
+- profiles are **enabled** with a schema for the project (see [Define the schema](#define-the-schema)), and
+- the memory is scoped to an entity โ a `user_id`.
+
+On a project where profiles are turned off, a read returns `status: not_enabled` rather than an error, so you can call it unconditionally and branch on the status.
+
+## Settings reference
+
+| Argument | Type | Description |
+|---|---|---|
+| `enabled` | boolean | Whether profile generation runs for the project |
+| `schema` | object | JSON Schema describing the profile. Every property needs a `description` |
+| `custom_instructions` | string | Extra guidance applied during extraction |
+
+`enabled` is project-wide. `schema` and `custom_instructions` apply to user
+profiles, so the stored settings nest them under `entities`:
+
+```json
+{
+ "enabled": true,
+ "entities": {
+ "user": {
+ "schema": { "type": "object", "properties": { "...": {} } },
+ "custom_instructions": "Prefer durable traits over one-off remarks."
+ }
+ },
+ "capabilities": { "full_rebuild": false }
+}
+```
+
+That is what a read returns and what a write accepts. The SDKs take the fields
+flat and nest them for you, so a schema you write with
+`update_profile_settings` comes back unchanged from `get_profile_settings`.
+
+
+ Profile settings are per project. An API key is scoped to one project, so profiles never cross a project boundary.
+
+
+## FAQ
+
+**Do I need to change my `add` or `search` calls to use profiles?**
+No. Profiles are built from the memories you already add. You define a schema once and read the profile when you need it โ your ingestion and retrieval code is unchanged.
+
+**Why is `profile` empty even though the entity has memories?**
+Generation is asynchronous and needs enough to work with. Branch on `status`: `pending` means it is still building, and `insufficient_data` means there are not yet enough memories to fill the schema. Read again shortly, or call `generate_profile` to build one now.
+
+**Is sampling free?**
+No. `sample_profiles` runs real generations against real memories and **keeps** the profiles it produces, so it counts toward your usage like any other generation. It exists to check a schema on a few entities before you commit to it โ not as a zero-cost dry run.
+
+**Does changing the schema rewrite existing profiles?**
+No. A schema change applies to the next generation. An existing profile keeps its values until its entity is generated again, which happens as that entity sends more memories, or when you call `generate_profile` for it.
+
+**What happens to a field I remove from the schema?**
+It stops being maintained. On an entity's next generation, fields your schema no longer defines are pruned from the stored profile โ so keep a field in the schema for as long as you want its value kept.
+
+**How current is a profile?**
+It refreshes automatically as memories accumulate (about every 10 messages for an entity), plus any on-demand `generate_profile` calls. Because refreshes run in the background, expect a short delay after the triggering `add` rather than an instant update.
+
+## Related
+
+
+
+ How users, agents, apps and runs partition memories.
+
+
+ Steer what Mem0 extracts in the first place.
+
+
diff --git a/docs/platform/overview.mdx b/docs/platform/overview.mdx
index 35933c511..9bc34aea9 100644
--- a/docs/platform/overview.mdx
+++ b/docs/platform/overview.mdx
@@ -1,7 +1,6 @@
---
-title: "Overview"
-seo:
- title: "Mem0 Platform Overview"
+title: "Platform Overview"
+sidebarTitle: "Overview"
description: "Managed memory layer for AI agents, production-ready in minutes"
icon: "cloud"
---
@@ -51,8 +50,8 @@ For the full pipeline, see [How Mem0 works](/core-concepts/how-it-works).
Get an API key and save your first memory.
-
- How user, agent, app, and run memory differ.
+
+ Organize memories by user, agent, app, and run.
The core memory operations, end to end.
diff --git a/docs/platform/platform-vs-oss.mdx b/docs/platform/platform-vs-oss.mdx
index 92bcc27b4..8a79ab351 100644
--- a/docs/platform/platform-vs-oss.mdx
+++ b/docs/platform/platform-vs-oss.mdx
@@ -39,7 +39,7 @@ The core memory loop is identical on both: `add`, `search`, `get`, `get_all`, `u
- **Entity scoping** by `user_id`, `agent_id`, and `run_id`
- **Filter grouping**: both accept `AND`/`OR`/`NOT` wrappers, both implicitly AND a flat multi-key filter like `{"user_id": "alice", "agent_id": "a1"}`, and both accept `*` as a wildcard value. Which fields you may filter on, and which operators each field accepts, differ (see below)
- **Entity-aware ranking**: both extract entities from memory text and use shared entities to boost related results at search time
-- **Multimodal input**, **memory expiration** (`expiration_date`), **reranking**, **procedural memory** (Python), and **custom extraction instructions** (`custom_instructions`)
+- **Multimodal input**, **memory expiration** (`expiration_date`), **reranking**, and **custom extraction instructions** (`custom_instructions`)
- Python and JavaScript SDKs, plus a REST API (self-hosted via `server/`, or hosted)
## What's actually different
diff --git a/docs/platform/pricing.mdx b/docs/platform/pricing.mdx
new file mode 100644
index 000000000..5d27d8252
--- /dev/null
+++ b/docs/platform/pricing.mdx
@@ -0,0 +1,96 @@
+---
+title: "Pricing FAQ"
+sidebarTitle: "Pricing"
+description: "Frequently asked questions about Mem0's plans, limits and using your own LLM key."
+icon: "credit-card"
+---
+
+## Existing paid plans
+
+
+
+ Nothing. Your price, limits, extra usage and billing date stay the same, and you can still turn extra usage on or off from your dashboard. These plans are no longer sold to new accounts.
+
+
+ Plan changes now go through our team. If you need higher limits or more features, [talk to us](https://app.mem0.ai/enterprise?ref=docs) and we'll set up a custom plan. If you cancel, your account moves to the free plan, any extra usage up to then is billed on your last invoice, and the old plan can't be restarted.
+
+
+
+## Free plan
+
+
+
+ For your first 30 days, Mem0 pays for the model calls, with limits of 10,000 adds and 1,000 retrievals a month. After that, connect your own LLM key to keep adding memories, and your limits go up to 50,000 adds and 10,000 retrievals a month at no charge from Mem0. You can connect a key at any time, including during your first 30 days.
+
+
+ If you signed up before October 26, 2026, you have until November 25, 2026. Otherwise, your 30 days start on the day you sign up.
+
+
+ Your memories stay, and searches keep working up to 1,000 a month. New adds return an error until you connect a key.
+
+
+ Calls past the limit return an error until your limits reset next month.
+
+
+ Yes. We email the organization owner at 50%, 80% and 100% of each monthly limit, and of your usage-based billing cap.
+
+
+
+## Your own LLM key
+
+
+
+ Adding a memory runs language model calls that extract and organize it. With your key, those calls bill to your provider account. That is how we keep the free plan free at higher limits.
+
+
+ It depends on the model. Our recommended models cost about \$3.55 to \$5.34 per 1,000 adds: GPT-6 Luna on OpenAI, Claude Haiku 5.5 on Anthropic and DeepSeek V4.1 Flash on OpenRouter. The [BYOK guide](/platform/features/byok#choose-a-model) compares accuracy and cost across every model we tested.
+
+
+ OpenAI, Anthropic, Azure OpenAI and OpenRouter.
+
+
+ Yes. The text you add is sent to your provider under your account and its terms. Mem0 stores your key encrypted, never shows it again after you save it, and you can remove it at any time.
+
+
+ Organization owners, in **Settings โ BYOK**. One key covers every project in the organization.
+
+
+ Adds fail with a reason you can see in the dashboard, and we email the organization owner, at most once a day. Mem0 doesn't switch to its own key, so send the failed adds again once the key works. Searches keep working.
+
+
+ Your limits go back to the ones without a key, and usage-based billing stops until you connect a key again. Anything you used before removing it is still billed on your next invoice.
+
+
+
+## Vercel
+
+
+
+ Nothing changes. Your plan is billed through Vercel. Organizations created through the Vercel Marketplace are managed from Vercel and can't use BYOK.
+
+
+
+## Need more
+
+
+
+ Once you've connected your own key, you can turn on usage-based billing from your dashboard and set a monthly spending cap. For SSO, an SLA or a contract, [talk to us](https://app.mem0.ai/enterprise?ref=docs).
+
+
+ You pay only for adds and retrievals above your free limits, billed once a month. The rate is shown when you turn it on, and those extra calls stop when you reach your monthly cap.
+
+
+ Yes, at any time from your dashboard. If you turn it off, you're still billed for what you used before.
+
+
+
+## Learn more
+
+
+
+ Connect your provider key, pick a model and fix failed adds.
+
+
+ Accuracy, cost and latency for every model we tested.
+
+
diff --git a/docs/templates/api_reference_template.mdx b/docs/templates/api_reference_template.mdx
index d04412863..67a83d556 100644
--- a/docs/templates/api_reference_template.mdx
+++ b/docs/templates/api_reference_template.mdx
@@ -4,7 +4,7 @@ description: "Standard layout for documenting Mem0 API endpoints."
icon: "code"
---
-# Api Reference Template
+# API Reference Template
API reference pages document a single endpoint contract. Present metadata, request/response examples, and recovery guidance without narrative detours.
diff --git a/docs/templates/feature_guide_template.mdx b/docs/templates/feature_guide_template.mdx
index fc502f88b..7582f3a47 100644
--- a/docs/templates/feature_guide_template.mdx
+++ b/docs/templates/feature_guide_template.mdx
@@ -124,7 +124,7 @@ Walk through a real request/response. Include sample payloads and highlight nota
{/* DEBUG: verify CTA targets */}
-
+
Understand how Mem0 ranks memories under the hood.
diff --git a/docs/templates/parameters_reference_template.mdx b/docs/templates/parameters_reference_template.mdx
index f86cb7745..b31d1b442 100644
--- a/docs/templates/parameters_reference_template.mdx
+++ b/docs/templates/parameters_reference_template.mdx
@@ -38,7 +38,6 @@ client.memories.add(
user_id: str,
memory: str,
metadata: Optional[dict] = None,
- memory_type: Literal["session", "long_term"] = "session",
)
```
@@ -47,13 +46,13 @@ await mem0.memories.add({
userId: string;
memory: string;
metadata?: Record;
- memoryType?: "session" | "long_term";
});
```
- Defaults to session memories. Override `memory_type` for long-term storage.
+ [Describe defaults supported by this operation and SDK. Do not infer a
+ memory type or retention policy from a scoping identifier.]
@@ -67,7 +66,6 @@ await mem0.memories.add({
| `user_id` | string | Yes | Unique identifier for the end user. | Must match follow-up operations. |
| `memory` | string | Yes | Content to persist. | Managed & OSS. Markdown allowed. |
| `metadata` | object | No | Key-value pairs for filters. | OSS stores as JSONB; limit to 2KB. |
-| `memory_type` | string | No | Retention bucket | Platform supports `shared`. |
Set `ttl_seconds` when you need memories to expire automatically (OSS only).
diff --git a/docs/vibecoding.mdx b/docs/vibecoding.mdx
index 50eb08e04..a5bf80016 100644
--- a/docs/vibecoding.mdx
+++ b/docs/vibecoding.mdx
@@ -96,8 +96,8 @@ time. Storage: vector embeddings.
**Architecture Overview:**
- Memory is scoped by user_id, agent_id, or run_id
- Core operations: add, search, update, delete
-- Memory types: factual (preferences, facts), episodic (past interactions),
- semantic (concept relationships), working (session state)
+- Store preferences, facts, and past interactions; use run_id to scope a
+ session. Platform does not expose a memory_type selector.
- Integration pattern: retrieve relevant memories โ generate response โ store
new memories
diff --git a/examples/mem0-demo/package.json b/examples/mem0-demo/package.json
index ec5b7c61c..32366bb8b 100644
--- a/examples/mem0-demo/package.json
+++ b/examples/mem0-demo/package.json
@@ -28,7 +28,7 @@
"clsx": "^2.1.1",
"js-cookie": "^3.0.6",
"lucide-react": "^0.477.0",
- "next": "15.5.21",
+ "next": "15.5.28",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"react-markdown": "^10.0.1",
diff --git a/examples/misc/movie_recommendation_grok3.py b/examples/misc/movie_recommendation_grok3.py
index bb4edbc42..abd383a47 100644
--- a/examples/misc/movie_recommendation_grok3.py
+++ b/examples/misc/movie_recommendation_grok3.py
@@ -45,11 +45,11 @@ grok_client = OpenAI(
def recommend_movie_with_memory(user_id: str, user_query: str):
# Retrieve prior memory about movies
- past_memories = memory.search("movie preferences", user_id=user_id)
+ past_memories = memory.search("movie preferences", filters={"user_id": user_id})
prompt = user_query
- if past_memories:
- prompt += f"\nPreviously, the user mentioned: {past_memories}"
+ if past_memories["results"]:
+ prompt += f"\nPreviously, the user mentioned: {[m['memory'] for m in past_memories['results']]}"
# Generate movie recommendation using Grok 3
response = grok_client.chat.completions.create(model="grok-3-beta", messages=[{"role": "user", "content": prompt}])
diff --git a/examples/misc/strands_agent_aws_elasticache_neptune.py b/examples/misc/strands_agent_aws_elasticache_neptune.py
index 01fde8614..37f1a2fb8 100644
--- a/examples/misc/strands_agent_aws_elasticache_neptune.py
+++ b/examples/misc/strands_agent_aws_elasticache_neptune.py
@@ -198,7 +198,7 @@ def search_memory_tool(query: str, user_id: str = "user") -> str:
Relevant vector memories found or message if none found
"""
try:
- results = m.search(query, user_id=user_id)
+ results = m.search(query, filters={"user_id": user_id})
if isinstance(results, dict) and 'results' in results:
memory_list = results['results']
@@ -245,7 +245,7 @@ def search_graph_memory_tool(query: str, user_id: str = "user") -> str:
"""
try:
graph_query = f"relationships connections {query}"
- results = m.search(graph_query, user_id=user_id)
+ results = m.search(graph_query, filters={"user_id": user_id})
if isinstance(results, dict) and 'results' in results:
memory_list = results['results']
@@ -290,7 +290,7 @@ def get_all_memories_tool(user_id: str = "user") -> str:
All memories for the user or message if none found
"""
try:
- all_memories = m.get_all(user_id=user_id)
+ all_memories = m.get_all(filters={"user_id": user_id})
if isinstance(all_memories, dict) and 'results' in all_memories:
memory_list = all_memories['results']
diff --git a/examples/misc/vllm_example.py b/examples/misc/vllm_example.py
index 635cb550e..610edd2b7 100644
--- a/examples/misc/vllm_example.py
+++ b/examples/misc/vllm_example.py
@@ -107,16 +107,16 @@ def main():
for query in search_queries:
print(f"\nQuery: {query}")
- memories = memory.search(query=query, user_id="user_123")
+ memories = memory.search(query=query, filters={"user_id": "user_123"})
- for memory_item in memories:
+ for memory_item in memories["results"]:
print(f" - {memory_item['memory']}")
print("\n--> Getting all memories for user...")
- all_memories = memory.get_all(user_id="user_123")
- print(f"Total memories stored: {len(all_memories)}")
+ all_memories = memory.get_all(filters={"user_id": "user_123"})
+ print(f"Total memories stored: {len(all_memories['results'])}")
- for memory_item in all_memories:
+ for memory_item in all_memories["results"]:
print(f" - {memory_item['memory']}")
print("\n--> vLLM integration demo completed successfully!")
diff --git a/examples/notebooks/user-profiles.ipynb b/examples/notebooks/user-profiles.ipynb
new file mode 100644
index 000000000..72ef7580d
--- /dev/null
+++ b/examples/notebooks/user-profiles.ipynb
@@ -0,0 +1,764 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# User Profiles โ live demo\n",
+ "\n",
+ "A **profile** is a structured JSON document about ONE user, filled by an LLM from that\n",
+ "user's memories, shaped by a JSON Schema you supply.\n",
+ "\n",
+ "Search answers *\"what did this user say about X\"*. A profile answers *\"who is this\n",
+ "user\"*, in one read, with no query to write โ and it is available on the first turn of a\n",
+ "session, before the user has said anything.\n",
+ "\n",
+ "**What this notebook does:** feed a user 12 conversation turns, watch a profile get\n",
+ "generated from them, add 6 more turns that contradict the first set, and watch the\n",
+ "profile rewrite itself. Then it shows every way the API says no.\n",
+ "\n",
+ "**You need:** an API key, and a project on the **Pro plan or higher**. Never commit one.\n",
+ "\n",
+ "> Set `MEM0_API_KEY`, and `MEM0_API_HOST` if you are pointing at a sandbox rather than\n",
+ "> production. The cells below read both from the environment.\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "> **Use a disposable project.** This notebook overwrites the project's profile settings\n",
+ "> (enabled, schema, custom instructions). The last cell restores the values saved at the\n",
+ "> start, but only if you reach it: if a cell fails midway, the project keeps the demo\n",
+ "> schema until you run the cleanup cell or reset it yourself. Do not point it at a\n",
+ "> project other people or production traffic depend on.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# This notebook drives the SDK from this worktree, not the published mem0ai:\n",
+ "# the profile fixes below are not released yet.\n",
+ "%pip install -q -e ../..\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": "import json\nimport os\nimport time\nimport uuid\n\nimport mem0\nfrom mem0 import MemoryClient\n\nAPI_KEY = os.environ.get(\"MEM0_API_KEY\")\nif not API_KEY:\n import getpass\n\n API_KEY = getpass.getpass(\"API key: \")\n\nclient = MemoryClient(api_key=API_KEY, host=os.environ.get(\"MEM0_API_HOST\") or None)\n\n# Fresh id each run, so nothing below is stale from a previous pass.\nUSER_ID = f\"demo_{uuid.uuid4().hex[:8]}\"\n\n# Snapshot the project's profile settings up front. This notebook overwrites the\n# shared project schema/instructions/enabled below; the cleanup cell restores this.\nORIGINAL_SETTINGS = client.get_profile_settings()\n\nprint(\"sdk :\", mem0.__file__) # must be this worktree\nprint(\"host :\", client.host)\nprint(\"demo user:\", USER_ID)"
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 1. Define the schema\n",
+ "\n",
+ "The schema is handed to the model as a **tool definition**, and each field's\n",
+ "`description` is the only instruction the model gets about what belongs there. An\n",
+ "undescribed field is a field the model guesses at.\n",
+ "\n",
+ "Rules worth knowing:\n",
+ "\n",
+ "- root `type: object` with a **non-empty** `properties` โ an empty one is refused, because\n",
+ " it would bill you to extract nothing\n",
+ "- the root keys `_profile_config_version` and `entities` are **reserved** and rejected:\n",
+ " they name the storage envelope, so a schema using them could not be read back\n",
+ " unambiguously\n",
+ "- keep it small. The whole schema is sent to the model on every generation\n",
+ "\n",
+ "Descriptions are **not** enforced on write in this build โ a property without one is\n",
+ "accepted and then quietly underfilled at generation time. Section F1 demonstrates it.\n",
+ "Treat descriptions as your job, not the validator's.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "SCHEMA = {\n",
+ " \"type\": \"object\",\n",
+ " \"properties\": {\n",
+ " \"occupation\": {\n",
+ " \"type\": \"string\",\n",
+ " \"description\": \"The person's current job title, in one short phrase.\",\n",
+ " },\n",
+ " \"location\": {\n",
+ " \"type\": \"string\",\n",
+ " \"description\": \"The city or region the person currently lives in.\",\n",
+ " },\n",
+ " \"interests\": {\n",
+ " \"type\": \"array\",\n",
+ " \"items\": {\"type\": \"string\"},\n",
+ " \"description\": \"Hobbies and topics they return to, as short lowercase tags.\",\n",
+ " },\n",
+ " \"dietary_restrictions\": {\n",
+ " \"type\": \"array\",\n",
+ " \"items\": {\"type\": \"string\"},\n",
+ " \"description\": \"Foods the person avoids, and why, if they said.\",\n",
+ " },\n",
+ " \"communication_style\": {\n",
+ " \"type\": \"string\",\n",
+ " \"enum\": [\"concise\", \"detailed\", \"casual\", \"formal\"],\n",
+ " \"description\": \"How this person prefers to be answered.\",\n",
+ " },\n",
+ " \"expertise_level\": {\n",
+ " \"type\": \"string\",\n",
+ " \"enum\": [\"beginner\", \"intermediate\", \"advanced\"],\n",
+ " \"description\": \"Their technical depth, judged from how they discuss their work.\",\n",
+ " },\n",
+ " },\n",
+ "}\n",
+ "\n",
+ "settings = client.update_profile_settings(\n",
+ " enabled=True,\n",
+ " schema=SCHEMA,\n",
+ " custom_instructions=(\n",
+ " \"Prefer facts the person stated outright over anything inferred. \"\n",
+ " \"Leave a field empty rather than guessing.\"\n",
+ " ),\n",
+ ")\n",
+ "\n",
+ "# Sorted, because JSONB storage does not preserve the key order you sent.\n",
+ "# Compare a stored schema by SET, never by string or by key order.\n",
+ "stored = settings[\"entities\"][\"user\"][\"schema\"]\n",
+ "print(\"schema fields:\", sorted(stored[\"properties\"]))\n",
+ "print(\"enabled :\", settings[\"enabled\"])\n",
+ "print(\"capabilities :\", settings[\"capabilities\"])\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "`enabled` is project-wide; `schema` and `custom_instructions` apply to user profiles\n",
+ "and are stored under `entities`. The SDK takes them flat and nests them for you, so what\n",
+ "you write comes back unchanged from `get_profile_settings()`.\n",
+ "\n",
+ "Only the arguments you pass are written. To turn the feature off without touching your\n",
+ "schema, send `enabled` alone.\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 2. The turns\n",
+ "\n",
+ "Twelve conversation turns for one user. Nothing about `add()` changes โ profiles are a\n",
+ "side effect of the normal pipeline.\n",
+ "\n",
+ "Twelve, not five, because generation fires when an entity crosses a **10-message\n",
+ "boundary**. Below that it waits for a flush window measured in hours, and this notebook\n",
+ "would sit there.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "TURNS = [\n",
+ " (\"user\", \"Hey โ I just moved to Berlin for a new job.\"),\n",
+ " (\"assistant\", \"Congratulations! What's the new role?\"),\n",
+ " (\"user\", \"Senior data engineer at a logistics company. Mostly Spark and Airflow.\"),\n",
+ " (\"assistant\", \"Nice stack. How are you finding the pipelines there?\"),\n",
+ " (\"user\", \"Honestly the DAGs are a mess. I've been rewriting the partitioning to cut shuffle.\"),\n",
+ " (\"assistant\", \"That usually pays off fast. Anything blocking you?\"),\n",
+ " (\"user\", \"Just time. Keep it short when you answer me, I skim everything.\"),\n",
+ " (\"assistant\", \"Understood โ short answers from here.\"),\n",
+ " (\"user\", \"Outside work I climb most weekends, and I'm learning German.\"),\n",
+ " (\"assistant\", \"Bouldering or ropes?\"),\n",
+ " (\"user\", \"Bouldering. Also โ I'm vegetarian, so skip meat in any recipe suggestions.\"),\n",
+ " (\"assistant\", \"Noted, vegetarian only.\"),\n",
+ "]\n",
+ "\n",
+ "response = client.add(\n",
+ " [{\"role\": r, \"content\": c} for r, c in TURNS],\n",
+ " user_id=USER_ID,\n",
+ ")\n",
+ "print(json.dumps(response, indent=2)[:300])\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The add is **async** โ it returns an `event_id` and the memories do not exist yet. Poll\n",
+ "`GET /v1/event/{event_id}/` until it is `SUCCEEDED` or `FAILED`; that, not a sleep, is how\n",
+ "you know the add finished. Then let the extracted memories settle.\n",
+ "\n",
+ "Under load this can take a minute or more, so the cell says plainly whether it ran out of\n",
+ "time rather than printing `0 memories` as though that were the answer.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "event_id = response[\"event_id\"]\n",
+ "deadline = time.time() + 300\n",
+ "\n",
+ "# 1. The add itself. Terminal status, not a sleep.\n",
+ "event_status = None\n",
+ "while time.time() < deadline:\n",
+ " event_status = client.client.get(f\"/v1/event/{event_id}/\").json().get(\"status\")\n",
+ " if event_status in (\"SUCCEEDED\", \"FAILED\"):\n",
+ " break\n",
+ " print(f\" add {event_status}\")\n",
+ " time.sleep(5)\n",
+ "print(f\"add finished: {event_status}\")\n",
+ "# Stop here unless the add SUCCEEDED. A failed or unfinished add would otherwise let the\n",
+ "# generation below bill for a profile built without these memories.\n",
+ "if event_status != \"SUCCEEDED\":\n",
+ " raise RuntimeError(f\"add did not succeed (status={event_status}); not generating a profile\")\n",
+ "\n",
+ "# 2. Extraction lands in batches, so the FIRST non-empty page is not the whole set.\n",
+ "# Wait for the count to stop growing instead of breaking on the first result.\n",
+ "memories, stable = [], 0\n",
+ "while time.time() < deadline:\n",
+ " page = client.get_all(filters={\"user_id\": USER_ID}, page_size=50)\n",
+ " found = page.get(\"results\", []) if isinstance(page, dict) else page\n",
+ " stable = stable + 1 if found and len(found) == len(memories) else 0\n",
+ " memories = found\n",
+ " if stable >= 2: # two identical polls in a row\n",
+ " break\n",
+ " print(f\" ... {len(memories)} so far\")\n",
+ " time.sleep(5)\n",
+ "\n",
+ "if memories:\n",
+ " print(f\"\\n{len(memories)} memories extracted:\\n\")\n",
+ " for m in memories:\n",
+ " print(\" \\u2022\", m.get(\"memory\"))\n",
+ "else:\n",
+ " # Say so. Reporting '0 memories' as a result hides a busy or broken environment\n",
+ " # and makes the profile below look like it came from nothing.\n",
+ " print(\"\\nNO memories yet โ extraction is still catching up, or the ingestion\")\n",
+ " print(\"worker is down. Everything below will report insufficient_data.\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 3. Read the profile\n",
+ "\n",
+ "Crossing the 10-message boundary should already have queued a generation. Read first โ\n",
+ "and note that a known user with no profile yet is a **200 with a status**, not a 404. That\n",
+ "distinction is the whole point of the envelope.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "envelope = client.get_profile(USER_ID)\n",
+ "print(json.dumps(envelope, indent=2))\n",
+ "\n",
+ "print(\"\\nstatus vocabulary:\")\n",
+ "print(\" succeeded terminal โ a generation ran AND the profile has content\")\n",
+ "print(\" pending queued or running\")\n",
+ "print(\" failed terminal โ the last generation did not complete\")\n",
+ "print(\" not_enabled feature off, or plan below Pro\")\n",
+ "print(\" insufficient_data no content to show: no row yet, queued, or a\")\n",
+ "print(\" generation that legitimately found nothing\")\n",
+ "print()\n",
+ "print(\"`succeeded` is decided by the profile BODY, not by generation_count: an\")\n",
+ "print(\"empty extraction still increments the counter, so counting generations\")\n",
+ "print(\"reports 'done' for a profile with nothing in it.\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Force it, rather than waiting\n",
+ "\n",
+ "`generate_profile()` closes the bootstrapping gap: without it a new user has no profile\n",
+ "until their tenth message. One entity, a few seconds.\n",
+ "\n",
+ "Each call sends a new `Idempotency-Key` unless you pass one, and a new key starts a new job.\n",
+ "To retry a dropped request safely, generate the key yourself and pass the same\n",
+ "`idempotency_key` on every attempt: the server then returns the original job instead of\n",
+ "billing a second one.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "TERMINAL = {\"succeeded\", \"failed\", \"not_enabled\"}\n",
+ "\n",
+ "\n",
+ "def wait_for_profile(entity_id, timeout=300, interval=5, since=None):\n",
+ " \"\"\"Poll until terminal.\n",
+ "\n",
+ " `since` waits for a generation_count ABOVE that value, which is how you wait\n",
+ " for an UPDATE rather than accepting the profile you already had.\n",
+ "\n",
+ " `insufficient_data` is NOT terminal by itself โ it also covers 'queued', so\n",
+ " poll through it and give up on the timeout instead.\n",
+ " \"\"\"\n",
+ " deadline = time.time() + timeout\n",
+ " body = None\n",
+ " while time.time() < deadline:\n",
+ " body = client.get_profile(entity_id)\n",
+ " status = (body.get(\"status\") or \"\").lower()\n",
+ " count = body.get(\"generation_count\") or 0\n",
+ " fresh = count > since if since is not None else True\n",
+ " if status == \"succeeded\" and fresh:\n",
+ " return body\n",
+ " if status in (\"failed\", \"not_enabled\"):\n",
+ " raise RuntimeError(f\"generation stopped: {status}\")\n",
+ " print(f\" ... {status} (generation_count={count})\")\n",
+ " time.sleep(interval)\n",
+ " raise TimeoutError(f\"not ready in {timeout}s: {body}\")\n",
+ "\n",
+ "\n",
+ "print(json.dumps(client.generate_profile(USER_ID), indent=2))\n",
+ "print(\"\\npolling...\")\n",
+ "\n",
+ "try:\n",
+ " body = wait_for_profile(USER_ID)\n",
+ " print(\"\\n=== PROFILE ===\")\n",
+ " print(json.dumps(body[\"profile\"], indent=2))\n",
+ " print(f\"\\nstatus={body['status']} generations={body['generation_count']} updated={body['updated_at']}\")\n",
+ "except TimeoutError as e:\n",
+ " # Say so plainly and let the rest of the notebook skip, rather than raising\n",
+ " # a NameError in every cell below and burying the real cause.\n",
+ " body = None\n",
+ " print(f\"\\nNO PROFILE: {e}\")\n",
+ " print(\"Generation never finished. Usually the ingestion worker is down, or\")\n",
+ " print(\"this project has no memories for the user yet.\")\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# The model must not invent fields outside your schema โ the forced tool call is\n",
+ "# what makes that structural rather than a request.\n",
+ "if body is None:\n",
+ " print(\"skipped โ no profile was generated above\")\n",
+ "else:\n",
+ " extra = set(body[\"profile\"]) - set(SCHEMA[\"properties\"])\n",
+ " print(\"fields outside the schema:\", extra or \"none\")\n",
+ "\n",
+ " # A forced JSON-Schema response makes the model emit SOMETHING for every property,\n",
+ " # so 'I found nothing' arrives as a type default: 0, \"\", [].\n",
+ " filled = {k: v for k, v in body[\"profile\"].items() if v not in (None, \"\", [], {}, 0)}\n",
+ " print(f\"genuinely populated: {len(filled)}/{len(SCHEMA['properties'])} -> {list(filled)}\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 4. Now watch it update\n",
+ "\n",
+ "Six more turns that contradict and extend what we already know: a promotion, a move, a\n",
+ "dropped hobby. A profile is a living document, not an append-only log โ the model gets the\n",
+ "memories and rewrites the whole thing.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "if body is None:\n",
+ " print(\"skipped โ no profile was generated above\")\n",
+ "else:\n",
+ " before = body[\"generation_count\"]\n",
+ "\n",
+ " MORE_TURNS = [\n",
+ " (\"user\", \"Update โ I got promoted to staff engineer last week.\"),\n",
+ " (\"assistant\", \"Congratulations. Same team?\"),\n",
+ " (\"user\", \"Same company, but I'm relocating to Munich for it.\"),\n",
+ " (\"assistant\", \"Big move. How do you feel about it?\"),\n",
+ " (\"user\", \"Good. I've stopped climbing though โ knee injury. Picked up cycling instead.\"),\n",
+ " (\"assistant\", \"Sorry about the knee. Cycling's kinder on it.\"),\n",
+ " ]\n",
+ "\n",
+ " followup = client.add(\n",
+ " [{\"role\": r, \"content\": c} for r, c in MORE_TURNS],\n",
+ " user_id=USER_ID,\n",
+ " )\n",
+ "\n",
+ " # Wait for the add to land before triggering: a generation queued before the new\n",
+ " # memories exist rewrites the profile from the OLD ones and looks like a no-op.\n",
+ " deadline = time.time() + 300\n",
+ " status = None\n",
+ " while time.time() < deadline:\n",
+ " status = client.client.get(f\"/v1/event/{followup['event_id']}/\").json().get(\"status\")\n",
+ " if status in (\"SUCCEEDED\", \"FAILED\"):\n",
+ " break\n",
+ " time.sleep(5)\n",
+ " print(\"follow-up add:\", status)\n",
+ " # Generating after a FAILED or unfinished add bills for a profile built from the OLD\n",
+ " # memories only, so stop instead.\n",
+ " if status != \"SUCCEEDED\":\n",
+ " raise RuntimeError(f\"follow-up add did not succeed (status={status}); not regenerating\")\n",
+ " time.sleep(15) # let extraction settle\n",
+ "\n",
+ " print(json.dumps(client.generate_profile(USER_ID), indent=2))\n",
+ " print(f\"\\npolling for a NEW generation (count must exceed {before})...\")\n",
+ " updated = wait_for_profile(USER_ID, since=before)\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "if body is None:\n",
+ " print(\"skipped โ no profile was generated above\")\n",
+ "else:\n",
+ " print(f\"{'field':<22} {'before':<34} after\")\n",
+ " print(\"-\" * 92)\n",
+ " for field in SCHEMA[\"properties\"]:\n",
+ " b = json.dumps(body[\"profile\"].get(field))\n",
+ " a = json.dumps(updated[\"profile\"].get(field))\n",
+ " mark = \" \" if a == b else \"->\"\n",
+ " print(f\"{mark} {field:<20} {b[:32]:<34} {a[:32]}\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 5. Use it in a prompt\n",
+ "\n",
+ "The point of the structure is that it drops straight into a prompt โ no list of memories\n",
+ "to summarize, no query to write.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def build_system_prompt(entity_id):\n",
+ " result = client.get_profile(entity_id)\n",
+ " if result[\"status\"] != \"succeeded\":\n",
+ " # Branch on status, never on an empty profile: a user whose profile is\n",
+ " # still building is not a user you know nothing about.\n",
+ " return \"You are a helpful assistant.\"\n",
+ "\n",
+ " p = result[\"profile\"]\n",
+ " return f\"\"\"You are helping {entity_id}.\n",
+ "Occupation: {p.get(\"occupation\", \"unknown\")}\n",
+ "Location: {p.get(\"location\", \"unknown\")}\n",
+ "Interests: {\", \".join(p.get(\"interests\", [])) or \"unknown\"}\n",
+ "Dietary restrictions: {\", \".join(p.get(\"dietary_restrictions\", [])) or \"none stated\"}\n",
+ "Preferred style: {p.get(\"communication_style\", \"unknown\")}\n",
+ "\n",
+ "Match their style and do not explain what they already know.\"\"\"\n",
+ "\n",
+ "\n",
+ "print(build_system_prompt(USER_ID))\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 6. Judge a schema before committing to it\n",
+ "\n",
+ "`sample_profiles()` runs your schema against up to 10 **real** users that have memories.\n",
+ "\n",
+ "These are real generations and the results are **kept** โ a dry run would cost exactly the\n",
+ "same and leave those users no better off. It is not a free preview.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# 202, not 200: the sample generations are queued, not finished.\n",
+ "#\n",
+ "# A 409 `already_running` means a sample from an earlier run is still going.\n",
+ "# That is the cooldown working, not an error โ reuse that job rather than\n",
+ "# failing the notebook.\n",
+ "try:\n",
+ " job = client.sample_profiles(limit=3)\n",
+ " print(json.dumps(job, indent=2)[:400])\n",
+ " print(\"\\nsampled\", job.get(\"sampled\"), \"entities:\", job.get(\"entity_ids\"))\n",
+ "except Exception as e:\n",
+ " detail = str(e)\n",
+ " print(\"sample refused:\", detail[:200])\n",
+ " running = json.loads(detail).get(\"error\", {}).get(\"job_id\") if detail.startswith(\"{\") else None\n",
+ " job = {\"job_id\": running, \"status_url\": f\"/v2/profiles/jobs/{running}/\"} if running else None\n",
+ " print(\"reusing the running job:\", running)\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Poll `status_url` to see how the job went. `total` is `null` until enumeration finishes,\n",
+ "so format it defensively rather than assuming a number.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": "JOB_TERMINAL = {\"SUCCEEDED\", \"PARTIALLY_SUCCEEDED\", \"FAILED\", \"CANCELLED\"}\n\n\ndef wait_for_job(job_response, timeout=300, interval=5):\n \"\"\"Poll a generation job. Prefer status_url over a bare job id, so a route\n change needs no client update. Raise on timeout so an unfinished job is never\n mistaken for a finished one.\"\"\"\n handle = job_response.get(\"status_url\") or job_response[\"job_id\"]\n deadline = time.time() + timeout\n status = None\n while time.time() < deadline:\n status = client.get_profile_job(handle)[\"job\"]\n total = status.get(\"total\")\n print(\n f\" {status['status']} \"\n f\"completed={status.get('completed', 0)}/{total if total is not None else '?'} \"\n f\"succeeded={status.get('succeeded', 0)} \"\n f\"failed={status.get('failed', 0)} \"\n f\"skipped={status.get('skipped', 0)}\"\n )\n if str(status.get(\"status\", \"\")).upper() in JOB_TERMINAL:\n return status\n time.sleep(interval)\n raise TimeoutError(\n f\"job not terminal in {timeout}s (last status: {status.get('status') if status else 'none'})\"\n )\n\n\nif job is None:\n print(\"no sample job to poll\")\nelse:\n final = wait_for_job(job)\n\n print(\"\\n--- what the sample produced ---\")\n for entity_id in job.get(\"entity_ids\", []):\n got = client.get_profile(entity_id)\n print(f\"\\n{entity_id} [{got['status']}]\")\n print(\" \", json.dumps(got[\"profile\"])[:220])"
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 7. Apply a new schema to existing users\n",
+ "\n",
+ "A new schema shapes the **next** generation. Profiles that already exist keep their values\n",
+ "until their user is generated again โ which happens as that user sends more memories, or\n",
+ "when you call `generate_profile()` for them.\n",
+ "\n",
+ "A field you **remove** stops being maintained: on the next generation, fields your schema\n",
+ "no longer defines are pruned. Keep a field for as long as you want its value kept."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "# Failure scenarios\n",
+ "\n",
+ "Everything above is the path that works. These are the ways it says no, and what each one\n",
+ "means. Run this section last: F3 deliberately leaves the project switched off for a moment.\n",
+ "\n",
+ "> **About the `HTTP error occurred:` lines below.** The SDK logs every 4xx at\n",
+ "> ERROR level before raising, so they appear even for the failures these cells\n",
+ "> deliberately catch. Read the line printed *after* each one โ that is the cell's\n",
+ "> own verdict. Nothing here is unhandled.\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## F1. Schemas that get rejected\n",
+ "\n",
+ "Rejections happen on **write**, where you can see and fix them โ not silently at\n",
+ "generation time, where you would only notice as an empty profile weeks later.\n",
+ "\n",
+ "The last case matters for storage: the user schema lives in one JSONB column alongside\n",
+ "the envelope that separates it, so a schema using the envelope's own reserved keys could\n",
+ "not be read back unambiguously. It is refused rather than stored.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "BAD_SCHEMAS = [\n",
+ " ({\"type\": \"object\", \"properties\": {}}, \"empty โ bills you to extract nothing\"),\n",
+ " ({\"type\": \"array\", \"items\": {\"type\": \"string\"}}, \"root must be an object\"),\n",
+ " (\n",
+ " {\n",
+ " \"type\": \"object\",\n",
+ " \"properties\": {\"tone\": {\"type\": \"string\", \"description\": \"Preferred tone.\"}},\n",
+ " # At the schema ROOT, which is where the envelope's own keys live.\n",
+ " \"_profile_config_version\": 1,\n",
+ " \"entities\": {\"user\": {}},\n",
+ " },\n",
+ " \"reserved settings keys at the schema root\",\n",
+ " ),\n",
+ "]\n",
+ "\n",
+ "for bad, why in BAD_SCHEMAS:\n",
+ " try:\n",
+ " client.update_profile_settings(schema=bad)\n",
+ " print(f\"ACCEPTED (unexpected): {why}\")\n",
+ " except Exception as e:\n",
+ " print(f\"rejected [{why}]:\\n {str(e)[:160]}\\n\")\n",
+ "\n",
+ "# NOT rejected: a property with no description. The validator allows it and the\n",
+ "# model then has nothing to go on, so the field comes back empty. Descriptions are\n",
+ "# your job, not the validator's.\n",
+ "try:\n",
+ " client.update_profile_settings(schema={\"type\": \"object\", \"properties\": {\"x\": {\"type\": \"string\"}}})\n",
+ " print(\"accepted [no description on 'x'] <- the trap: valid to store, useless to generate\")\n",
+ "finally:\n",
+ " client.update_profile_settings(schema=SCHEMA) # put the good one back\n",
+ "\n",
+ "restored = client.get_profile_settings()[\"entities\"][\"user\"][\"schema\"]\n",
+ "assert set(restored[\"properties\"]) == set(SCHEMA[\"properties\"])\n",
+ "print(\"\\nschema restored:\", sorted(restored[\"properties\"]))\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## F2. A user that does not exist\n",
+ "\n",
+ "404 means only \"no such user\". A known user with no profile yet is a 200 carrying\n",
+ "`insufficient_data`, so an ordinary empty state never looks like an error.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from mem0.exceptions import MemoryNotFoundError\n",
+ "\n",
+ "try:\n",
+ " client.get_profile(\"user_who_never_existed\")\n",
+ " print(\"ACCEPTED (unexpected)\")\n",
+ "except MemoryNotFoundError as e:\n",
+ " print(\"404 as intended:\", str(e)[:120])\n",
+ "\n",
+ "# ...versus a real user who simply has no profile row yet.\n",
+ "fresh = f\"demo_never_profiled_{uuid.uuid4().hex[:6]}\"\n",
+ "client.add([{\"role\": \"user\", \"content\": \"One passing remark.\"}], user_id=fresh)\n",
+ "time.sleep(5)\n",
+ "print(\"known but unprofiled:\", client.get_profile(fresh)[\"status\"])\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## F3. Profiles turned off\n",
+ "\n",
+ "`enabled` is the one project-wide switch. Every generation path then refuses.\n",
+ "\n",
+ "Nothing is deleted. Your schema and every profile you already built are kept, so turning\n",
+ "it back on resumes rather than restarts.\n",
+ "\n",
+ "Note what a read does **not** do โ a profile that already exists keeps reporting\n",
+ "`succeeded` and keeps returning its content. `not_enabled` is only what you get for a user\n",
+ "with no profile yet. Turning the feature off stops new work; it does not hide what has\n",
+ "already been built.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "client.update_profile_settings(enabled=False)\n",
+ "\n",
+ "print(\"read (demo user) :\", client.get_profile(USER_ID)[\"status\"])\n",
+ "print(\"read (never profiled) :\", client.get_profile(fresh)[\"status\"])\n",
+ "try:\n",
+ " client.generate_profile(USER_ID)\n",
+ " print(\"trigger: ACCEPTED (unexpected)\")\n",
+ "except Exception as e:\n",
+ " print(\"trigger:\", str(e)[:160])\n",
+ "\n",
+ "back = client.update_profile_settings(enabled=True) # put it back\n",
+ "print(\"\\nrestored:\", back[\"enabled\"])\n",
+ "print(\"schema survived:\", bool(back[\"entities\"][\"user\"][\"schema\"]))\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 7. Cleanup\n",
+ "\n",
+ "Removes the demo users. The profile row cascades with the entity.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": "# Restore the project's profile settings to the start-of-run snapshot in `finally`, so a\n# failed delete still leaves a shared project as we found it. Passing the original values\n# (including None) clears anything this notebook set: the SDK treats an explicit None as\n# \"clear\" and an omitted argument as \"unchanged\".\ntry:\n # `fresh` only exists if the error-handling section ran.\n for entity_id in (USER_ID, globals().get(\"fresh\")):\n if entity_id is None:\n continue\n r = client.client.delete(f\"/v2/entities/user/{entity_id}/\")\n print(entity_id, \"->\", r.status_code)\nfinally:\n _user = ORIGINAL_SETTINGS.get(\"entities\", {}).get(\"user\", {})\n client.update_profile_settings(\n enabled=ORIGINAL_SETTINGS.get(\"enabled\", False),\n schema=_user.get(\"schema\"),\n custom_instructions=_user.get(\"custom_instructions\"),\n )\n print(\"profile settings restored to the pre-notebook snapshot\")"
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Cheat sheet\n",
+ "\n",
+ "| Want | Call | Cost |\n",
+ "| --- | --- | --- |\n",
+ "| configure | `update_profile_settings(...)` | free |\n",
+ "| read | `get_profile(user_id)` | free |\n",
+ "| one user now | `generate_profile(user_id)` | 1 LLM call |\n",
+ "| try a schema | `sample_profiles(limit=n)` | โค10 real generations, kept |\n",
+ "| poll a job | `get_profile_job(status_url)` | free |\n",
+ "\n",
+ "**Settings apply to user profiles.** The stored shape is:\n",
+ "\n",
+ "```json\n",
+ "{\"enabled\": true,\n",
+ " \"entities\": {\"user\": {\"schema\": {...}, \"custom_instructions\": \"...\"}},\n",
+ " \"capabilities\": {\"full_rebuild\": false}}\n",
+ "```\n",
+ "\n",
+ "The SDK takes these flat and nests them for you. Only the fields you pass are written;\n",
+ "`enabled` is the one project-wide switch.\n",
+ "\n",
+ "**Left alone, generation fires** on a 10-message boundary, or after a flush window\n",
+ "measured in hours. `generate_profile()` is how you skip the wait for one user.\n",
+ "\n",
+ "**Three traps:**\n",
+ "\n",
+ "1. `insufficient_data` is not a terminal verdict โ it also covers \"queued\", so poll\n",
+ " through it and give up on a timeout instead.\n",
+ "2. `succeeded` is decided by the profile **body**, not `generation_count`. An empty\n",
+ " extraction still increments the counter.\n",
+ "3. A forced JSON-Schema response emits something for every property, so \"nothing found\"\n",
+ " arrives as a type default โ `\"\"`, `[]`, `0` โ not as a missing key.\n"
+ ]
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3 (ipykernel)",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.12.4"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 4
+}
\ No newline at end of file
diff --git a/integrations/AGENTS.md b/integrations/AGENTS.md
index 6083dcf6a..e7814523f 100644
--- a/integrations/AGENTS.md
+++ b/integrations/AGENTS.md
@@ -1,21 +1,23 @@
# Integrations (`integrations/`)
-Agent and editor integrations. Each subdirectory is self-contained: its own `package.json`, lockfile, build, and tests. **There is no shared toolchain.** Check the table before running anything.
+Agent and editor integrations. Most packages are self-contained; coding-agent plugins share the code in `agent-plugin-core/`. Check the table before running anything.
| Directory | Package | Build | Lint | Test |
|-----------|---------|-------|------|------|
| `vercel-ai-sdk/` | `@mem0/vercel-ai-provider` | tsup (CJS+ESM) | ESLint + Prettier | jest + vitest (edge/node) |
| `openclaw/` | `@mem0/openclaw-mem0` | tsup (ESM) | none | vitest |
-| `claude-code-plugin/` | Claude Code plugin, installs as `mem0@mem0-plugins` (v0.3.0) | none | ruff | pytest |
-| `mem0-plugin/` | Cursor / Codex / Kimi / Antigravity / OpenCode plugin (legacy โ Claude Code moved to `claude-code-plugin/`) | none | none | pytest |
-| `mem0-plugin/.opencode-plugin/` | `@mem0/opencode-plugin` | Bun | none | tsc type-check |
+| `hermes-plugin-mem0/` | Standalone Hermes memory provider | none | ruff + isort | pytest (host-stubbed offline); live CLI/Desktop validation |
+| `agent-plugin-core/` | Shared Python/TypeScript behavior, skill templates, builds, and conformance | Python build script | ruff + tsc | pytest + node:test |
+| `mem0-agent-plugin/` | One portable Agent Plugins v1 package | Python | ruff | shared conformance |
+| `claude-code-plugin/`, `cursor-plugin/`, `codex-plugin/`, `kimi-plugin/`, `antigravity-plugin/` | Self-contained native plugins generated from the shared Python core | Python | ruff | pytest |
+| `opencode-plugin/` | `@mem0/opencode-plugin` (Bun/TypeScript) | tsup (via Bun) | tsc | bun test |
| `pi-agent-plugin/` | `@mem0/pi-agent-plugin` | tsup | none | vitest |
| `deepseek-plugin/` | `@mem0/deepseek-plugin` | tsup (ESM) | none | vitest |
| `n8n-nodes-mem0/` | `@mem0/n8n-nodes-mem0` | tsc | ESLint (n8n-nodes-base) | none |
| `zapier-mem0/` | `@mem0/zapier` | tsc | none | offline unit tests + `zapier validate` |
| `mem0-strands/` | `mem0-strands` (PyPI) | hatch | Ruff + mypy | pytest |
-pnpm everywhere except `.opencode-plugin/` (Bun) and `mem0-strands/` (Python: pip / hatch). Never npm, never yarn.
+pnpm for TypeScript packages except `opencode-plugin/` (Bun). `mem0-strands/` uses Python/pip/hatch. Never npm or yarn.
## Commands
@@ -41,20 +43,63 @@ Run the type check after every TypeScript change: `pnpm run typecheck` or `tsc -
## What each one is
- **`vercel-ai-sdk/`** wraps the Vercel AI SDK through a `createMem0` provider. Integrations for AI-SDK repos go through this wrapper, not raw `MemoryClient`.
-- **`claude-code-plugin/`** is the Claude Code plugin (v0.3.0, installs as `mem0@mem0-plugins`): local evidence capture via lifecycle hooks, background memory extraction to the Mem0 Platform, a local `search_memories` MCP tool, six `/mem0:*` skills, and the `mem0:sidekick` agent. Pure-stdlib Python โ no dependencies to install. Its `core/` + `adapters/claude/` split marks engine vs. harness glue; future per-harness plugins start by copying `core/` and keeping the contract tests verbatim (see its `docs/CONTRACT.md`).
-- **`mem0-plugin/`** connects Cursor, Codex, Kimi, Antigravity, and OpenCode to the MCP server at `mcp.mem0.ai` and installs lifecycle hooks for automatic memory capture. Exposes 9 MCP tools: `add_memory`, `search_memories`, `get_memories`, `get_memory`, `update_memory`, `delete_memory`, `delete_all_memories`, `delete_entities`, `list_entities`. The Claude Code plugin moved to [`claude-code-plugin/`](claude-code-plugin/) in v0.3.0 (installs as `mem0@mem0-plugins`); do not run both at the same time.
+- **`agent-plugin-core/`** owns the shared Python memory runtime, TypeScript lifecycle utilities, skill templates, builds, and conformance runner. Claude Code is the behavioral source of truth. Native manifests and adapters live in sibling plugin directories; do not hand-edit their generated `core/` or `skills/` trees. Build and validation details are in [`agent-plugin-core/README.md`](agent-plugin-core/README.md).
+- **`opencode-plugin/`** is a Bun/TypeScript plugin for OpenCode (`@mem0/opencode-plugin` on npm). It registers Mem0 memory tools as an OpenCode plugin with its own skills and telemetry.
- **`openclaw/`**, **`pi-agent-plugin/`**, **`deepseek-plugin/`** are editor and agent plugins with the same shape. `deepseek-plugin/` registers Mem0 search/add tools as a native DeepSeek Harness (Cordis) plugin.
- **`n8n-nodes-mem0/`** is an n8n community node: add, search, get, update, delete.
- **`zapier-mem0/`** is a Zapier Platform CLI app: add, search, get, delete. It deploys to Zapier, not npm, so it is **not** in the release router. Deploy it with `gh workflow run zapier-mem0-cd.yml --ref main` (needs the `ZAPIER_DEPLOY_KEY` secret).
- **`mem0-strands/`** is a native Strands `MemoryStore` (Python, published to PyPI as `mem0-strands`). It plugs into the Strands `MemoryManager` for automatic recall and server-side extraction, over the hosted Mem0 platform or self-hosted Mem0 OSS. The package lives under `mem0-strands/python/`.
+## Surface attribution
+
+Every integration tells the Mem0 platform which surface it is. Three headers,
+and the rules on them are what keep one layer from erasing another:
+
+| Header | Carries | Rule |
+|--------|---------|------|
+| `X-Mem0-Source` | one canonical source value | **set-once** โ write only if absent |
+| `X-Application` | the host app it runs inside | **set-once** โ write only if absent |
+| `X-Mem0-Client` | `name/version`, outermost first | **append-only** โ add yourself, never replace |
+
+Set-once means check-then-set, never assignment. An integration that wraps the
+SDK is the outermost layer and sets the source; the SDK underneath defers to it.
+Assignment is exactly how every agent plugin came to be indistinguishable from
+every other one at the platform.
+
+How to declare it from an integration, in order of preference:
+
+1. Send the headers yourself, if you make the HTTP call directly.
+2. Pass `source` in the call options, if you go through an SDK.
+3. Set `MEM0_SOURCE` / `MEM0_APPLICATION` / `MEM0_CLIENT_STACK` in the
+ environment before constructing the client. The SDKs read these and defer to
+ anything already present.
+
+Append-only applies where a stack can actually form: an SDK handed a client that
+already carries `X-Mem0-Client` appends itself rather than replacing. An SDK
+constructed with no outer context simply reports itself, which is correct โ it
+is the outermost layer in that process.
+
+The backend recognizes a fixed list of source values and buckets everything else
+into `OTHERS`. A new value has to land in the platform's `EventSource` enum, so
+do not invent one without that change going in too.
+
+`X-Application` is allowlisted the same way, and this one has a rule of its own:
+**omit the header when you do not know the host.** A value outside the allowlist
+is discarded server-side, so guessing produces an event that claims an
+attribution we do not actually have. The portable bundle is the case that
+matters. It runs in whatever editor a user drops it into, so its build leaves
+`PLATFORM_APPLICATION` empty and `memory_core` sends no header at all, while the
+native bundles each name the host they were generated for. If you add a build
+target, decide which of those two it is.
+
## Adding an integration
-1. Create `integrations//` and build it there, self-contained.
+1. For a native coding-agent host, add `integrations/-plugin/` with `plugin-build.json`, its manifest, and a thin adapter, then generate its shared runtime. Portable clients use the single `mem0-agent-plugin/` package. Independent TypeScript integrations stay self-contained and import shared lifecycle behavior from `agent-plugin-core/typescript/`.
2. If it publishes to a registry, set `repository.directory: "integrations/"` in `package.json` so npm provenance links to the right subdirectory.
3. Add `.github/workflows/-checks.yml` and `-cd.yml`. Use `integrations/` in the `paths:` trigger, `working-directory`, and `cache-dependency-path`. Register the release tag prefix in the `case` block in `release.yml`, keeping the bare `v*` arm last.
**Workflow filenames are load-bearing:** npm OIDC trusted publishing is pinned to repository plus workflow filename. Renaming one breaks publishing.
4. Register the CI workflow in `ci-gate.yml`: a path filter under the `changes` job, a call job, and an entry in the gate job's `needs` list.
-5. If it is a Claude Code or editor marketplace plugin, register its path in all five `marketplace.json` files: root, `.claude-plugin/`, `.cursor-plugin/`, `.codex-plugin/`, and `.agents/plugins/`.
+5. If it is a Claude Code or editor marketplace plugin, register the generated native bundle path in the applicable marketplace files. Preserve the existing public plugin name.
6. Document it under `docs/integrations/` and add the page to `docs/docs.json` and `docs/llms.txt`.
7. Add rows to the table above and to the CI/CD tables in [`../.github/AGENTS.md`](../.github/AGENTS.md).
+8. Send the three headers in [Surface attribution](#surface-attribution), and land the matching `EventSource` value on the platform in the same week. Until it exists, your traffic reports as `OTHERS`.
diff --git a/integrations/agent-plugin-core/README.md b/integrations/agent-plugin-core/README.md
new file mode 100644
index 000000000..dab9a88b7
--- /dev/null
+++ b/integrations/agent-plugin-core/README.md
@@ -0,0 +1,126 @@
+# Mem0 agent plugin core
+
+This directory is the single source of shared memory behavior for Mem0 coding-agent plugins. Installable plugins remain ordinary sibling directories under `integrations/`.
+
+## Architecture
+
+```text
+integrations/
+โโโ agent-plugin-core/ # Shared source; never installed as a plugin
+โ โโโ python/ # Claude-derived capture, recall, MCP, scoping, and telemetry
+โ โโโ typescript/ # Shared lifecycle, search prompts, formatting, identity, scoping, and telemetry
+โ โโโ skills/ # The only source for the six generated memory skills
+โ โโโ build/ # Bundle builder, schemas, and validation
+โ โโโ conformance/ # One offline/live verification entry point
+โ โโโ tests/
+โโโ mem0-agent-plugin/ # One portable Agent Plugins v1 package
+โโโ claude-code-plugin/ # Native Claude package and adapter
+โโโ cursor-plugin/ # Native Cursor package and adapter
+โโโ codex-plugin/ # Native Codex package and adapter
+โโโ kimi-plugin/ # Native Kimi package and adapter
+โโโ antigravity-plugin/ # Native Antigravity package and adapter
+```
+
+Each native directory owns only its manifest, native hooks or adapter, tests, and `plugin-build.json`. Its `core/` and `skills/` directories are generated from this module. They are committed because clients install a self-contained plugin directory and the Agent Plugins specification forbids package files from resolving outside the plugin root.
+
+Sidekick belongs only to Claude Code. Its agent definition is in `claude-code-plugin/agents/sidekick.md`; its hooks are in `claude-code-plugin/adapters/claude/hook.py`. Other plugins must not register Sidekick. The shared core handles memory and native subagent tracking for Claude Code and Codex.
+
+TypeScript integrations (`openclaw`, `opencode-plugin`, `pi-agent-plugin`, and `deepseek-plugin`) import `typescript/src/` at build time. Their package builders include the shared implementation in their normal output; they do not carry checked-in copies.
+
+## Shared memory behavior
+
+The six Python packages use the same `search_memories` MCP tool and six skill templates. Native hooks collect conversations and flush them to Mem0 in the background. The portable package uses the Agent Plugins v1 layout so compatible hosts can load its MCP server and skills. It has no lifecycle hooks or flush worker; its bundled `remember` skill assumes automatic capture and cannot save a memory on its own.
+
+Python search accepts `query`, `top_k`, `category`, `scope`, and optional `run_id`:
+
+| Scope | Memories searched |
+| --- | --- |
+| `repo` (default) | Shared repository memories and your personal memories in that repository |
+| `dir` | Shared memories from the current directory and its children, plus your personal repository memories |
+| `mine` | Your personal memories in that repository |
+
+`run_id` filters any scope to memories saved in a known coding-agent session. Omit it for recall across sessions; it does not attribute the search request to the current session. Native Python extraction writes include the session's `run_id`.
+
+New Git repository writes use a hashed remote identity for shared `agent_id`. Search and explicit shared-memory deletion include both that ID and the legacy unhashed ID under the same `app_id`. Legacy memories remain accessible, but their original ambiguity between matching owner/repository names on different Git hosts remains.
+
+Captured prompts and responses preserve their full text after secret redaction. Python extraction splits oversized input across requests without dropping message text. The session-end worker flushes the conversation already collected by hooks without adding the final answer again. Search queries, retrieved context, and tool evidence have separate limits.
+
+TypeScript hosts reuse redaction, lifecycle utilities, and the search prompts in `typescript/src/prompts.ts`, which a test keeps identical to the Python core. They retain their own tools, scopes, and capture events. They do not inherit the Python `repo`/`dir`/`mine` contract or its background batching. OpenCode captures selected user prompts; Pi and DeepSeek capture completed conversation turns; OpenClaw selects recent messages and earlier summaries, then filters noise. Removing message-length truncation does not turn these integrations into complete transcript archives.
+
+For installation, follow the host guides: [Claude Code](../../docs/integrations/claude-code.mdx), [Cursor](../../docs/integrations/cursor.mdx), [Codex](../../docs/integrations/codex.mdx), [Kimi](../../docs/integrations/kimi.mdx), and [Antigravity](../../docs/integrations/antigravity.mdx).
+
+## Build and verify
+
+From the repository root:
+
+```bash
+python3.11 -m venv /tmp/mem0-agent-plugins
+/tmp/mem0-agent-plugins/bin/pip install \
+ -r integrations/agent-plugin-core/requirements-dev.txt
+
+for host in claude-code cursor codex kimi antigravity; do
+ /tmp/mem0-agent-plugins/bin/python \
+ integrations/agent-plugin-core/build/build.py "$host" \
+ --kind native --check
+done
+
+/tmp/mem0-agent-plugins/bin/python \
+ integrations/agent-plugin-core/build/build.py mem0-agent-plugin \
+ --kind portable --check
+```
+
+Use `--sync` instead of `--check` after changing `python/` or `skills/`. This only replaces generated `core/` and `skills/` content; it does not change manifests, adapters, tests, or the Claude sidekick.
+
+Run every offline Python and TypeScript check and write one machine-readable report:
+
+```bash
+/tmp/mem0-agent-plugins/bin/python \
+ integrations/agent-plugin-core/conformance/run.py \
+ --install \
+ --report /tmp/mem0-plugin-conformance.json
+```
+
+For every TypeScript integration, this also builds the publishable package, verifies its required entry files, and rejects compiled artifacts that still import monorepo source. This keeps published plugins self-contained without committing their `dist/` directories.
+
+The offline suite does not contact Mem0 Platform. An explicit disposable key enables the inherited live scoping suite:
+
+```bash
+export MEM0_API_KEY="m0-disposable-test-key"
+/tmp/mem0-agent-plugins/bin/python \
+ integrations/agent-plugin-core/conformance/run.py \
+ --group live-platform --live \
+ --report /tmp/mem0-plugin-live-conformance.json
+```
+
+Do not put a real key in source files, command history shared with others, or pull-request configuration.
+
+## Add a plugin
+
+For another native Python host:
+
+1. Add `integrations/-plugin/` with its native manifest and the smallest adapter that translates host events.
+2. Add `plugin-build.json` declaring the plugin-root variable and runtime files.
+3. Add one adapter contract test.
+4. Register the host in `build/build.py` and `conformance/run.py`.
+5. Run `--sync`, `--check`, and the conformance command above.
+
+Keep capture, recall, memory scoping, redaction, skill text, and telemetry in this shared module. Host directories should contain only behavior required by their native SDK.
+
+For a TypeScript host, import the shared lifecycle modules directly and keep only native SDK registration in the integration. Do not advertise capture or compaction behavior unless the host exposes the necessary lifecycle seam. Sidekick is limited to Claude Code.
+
+## Host capture capabilities
+
+| Host | Conversation capture | Tool outcomes | Subagent context and correlation |
+| --- | --- | --- | --- |
+| Claude Code | Incremental active transcript branch | Native success/failure hooks | Parent context; native agent ID |
+| Cursor | Prompt and response hooks; duplicate responses suppressed | Native success/failure hooks | No plugin subagent hooks or agent declaration |
+| Codex | Native prompt and final-response fields | Structured failure indicators when present; otherwise unknown | Parent context; native agent ID |
+| Kimi | Prompt hooks and completed v2 wire output | Native success/failure hooks | No plugin subagent hooks or agent declaration |
+| Antigravity | Incremental completed transcript messages, including later prompts | Native tool errors | No plugin subagent hooks or agent declaration |
+| Portable v1 | Explicit memory skills | No native lifecycle hooks | No native subagent declaration |
+
+Python status uses `subagent_runs` and `last_subagent`. Legacy SQLite names and event handling keep existing records and running workers compatible.
+
+An uncorrelated subagent completion is kept as its own record; the plugin never guesses which overlapping run completed. Codex's documented hook fields already match the shared input contract, so no speculative field aliases or unsupported failure event are registered.
+
+Offline conformance exercises the adapters and MCP servers with native-shaped payloads and builds each distributable package. It does not establish that every installed editor or Harness version loads the plugin correctly; those checks require smoke tests in the actual hosts.
diff --git a/integrations/agent-plugin-core/build/__init__.py b/integrations/agent-plugin-core/build/__init__.py
new file mode 100644
index 000000000..81c68c34c
--- /dev/null
+++ b/integrations/agent-plugin-core/build/__init__.py
@@ -0,0 +1 @@
+"""Build and validate self-contained Mem0 agent plugins."""
diff --git a/integrations/agent-plugin-core/build/build.py b/integrations/agent-plugin-core/build/build.py
new file mode 100644
index 000000000..3059b9b1f
--- /dev/null
+++ b/integrations/agent-plugin-core/build/build.py
@@ -0,0 +1,290 @@
+#!/usr/bin/env python3
+from __future__ import annotations
+
+import argparse
+import json
+import re
+import shutil
+import tempfile
+from collections.abc import Mapping
+from pathlib import Path
+
+try:
+ from .validate import validate_bundle
+except ImportError:
+ from validate import validate_bundle
+
+CORE_ROOT = Path(__file__).resolve().parents[1]
+REPOSITORY_ROOT = CORE_ROOT.parents[1]
+INTEGRATIONS_ROOT = REPOSITORY_ROOT / "integrations"
+SHARED_SKILLS = CORE_ROOT / "skills"
+PORTABLE_PLUGIN = "mem0-agent-plugin"
+NATIVE_PLUGINS = {
+ "claude-code": INTEGRATIONS_ROOT / "claude-code-plugin",
+ "cursor": INTEGRATIONS_ROOT / "cursor-plugin",
+ "codex": INTEGRATIONS_ROOT / "codex-plugin",
+ "kimi": INTEGRATIONS_ROOT / "kimi-plugin",
+ "antigravity": INTEGRATIONS_ROOT / "antigravity-plugin",
+}
+PROTECTED_OUTPUTS = {
+ REPOSITORY_ROOT,
+ INTEGRATIONS_ROOT,
+ CORE_ROOT,
+ INTEGRATIONS_ROOT / PORTABLE_PLUGIN,
+ *NATIVE_PLUGINS.values(),
+}
+TEMPLATE_TOKEN = re.compile(r"{{([A-Z_]+)}}")
+TEMPLATE_TOKENS = {
+ "PLUGIN_ROOT",
+ "PLUGIN_DATA",
+ "PLUGIN_DATA_ARG",
+ "COMMAND_PREFIX",
+ "HARNESS_ID",
+ "HARNESS_NAME",
+}
+
+
+def render_template(source: str, values: Mapping[str, str]) -> str:
+ def replace(match: re.Match[str]) -> str:
+ token = match.group(1)
+ if token not in TEMPLATE_TOKENS or token not in values:
+ raise ValueError(f"unknown or unresolved template token: {token}")
+ return values[token]
+
+ rendered = TEMPLATE_TOKEN.sub(replace, source)
+ if "{{" in rendered or "}}" in rendered:
+ raise ValueError("unresolved template token")
+ return rendered
+
+
+def replace_output(staged: Path, output: Path) -> Path:
+ """Replace one explicit build output without touching its siblings."""
+ if not staged.is_dir():
+ raise ValueError(f"staged directory does not exist: {staged}")
+
+ resolved_output = output.resolve()
+ if resolved_output in {path.resolve() for path in PROTECTED_OUTPUTS}:
+ raise ValueError(f"refusing protected output path: {output}")
+ if output.exists() and not output.is_dir():
+ raise ValueError(f"output path is not a directory: {output}")
+
+ output.parent.mkdir(parents=True, exist_ok=True)
+ temporary = Path(tempfile.mkdtemp(prefix=f".{output.name}-", dir=output.parent))
+ try:
+ shutil.copytree(staged, temporary, dirs_exist_ok=True)
+ if output.exists():
+ shutil.rmtree(output)
+ temporary.replace(output)
+ finally:
+ if temporary.exists():
+ shutil.rmtree(temporary)
+ return output
+
+
+def _render_harness_id(host: str, *, portable: bool = False) -> str:
+ """Emit core/_harness_id.py for one host.
+
+ Carries both vocabularies from a single definition: the PostHog `source` tag
+ and the platform's X-Mem0-Source / X-Application pair. Keeping them together
+ is what stops the two from drifting into separate vocabularies for the same
+ thing.
+
+ The portable bundle runs in whatever editor a user drops it into, so it does
+ not know its host and must not guess one. HARNESS_ID stays "coding-agent",
+ which is true and useful for grouping in PostHog, but PLATFORM_APPLICATION is
+ left empty: X-Application names a real host app, is checked against an
+ allowlist server-side, and a value that is always discarded is worse than no
+ value -- it reads like an attribution we have and do not.
+ """
+ tag = host.upper().replace("-", "_") + "_PLUGIN"
+ application = "" if portable else host
+ return (
+ '"""Generated by integrations/agent-plugin-core/build/build.py. Do not edit."""\n'
+ "\n"
+ f'HARNESS_ID = "{host}"\n'
+ f'SOURCE_TAG = "{tag}"\n'
+ "\n"
+ "# Platform-side vocabulary (mem0_event.source + X-Application). The whole\n"
+ "# plugin family is one source; which editor it runs in is the application.\n"
+ "# An empty application means the host is unknown, and memory_core omits\n"
+ "# the header entirely rather than sending a placeholder.\n"
+ 'PLATFORM_SOURCE = "MEM0_PLUGIN"\n'
+ f'PLATFORM_APPLICATION = "{application}"\n'
+ )
+
+
+def _bundle_python(
+ staged: Path,
+ host: str,
+ plugin_root: str,
+ *,
+ plugin_data: str = "",
+ portable: bool = False,
+) -> None:
+ core = staged / "core"
+ core.mkdir()
+ for source in sorted((CORE_ROOT / "python").glob("*.py")):
+ if portable and source.name in {"flush_worker.py", "hook_runner.py"}:
+ continue
+ shutil.copy2(source, core / source.name)
+
+ # Generated per host so identity does not depend on an entrypoint remembering
+ # to call telemetry.init(). mcp_server.py and the detached telemetry.py sender
+ # never did, which is how MCP searches reported harness=generic and every
+ # batch they drained was labelled MEM0_PLUGIN regardless of the real host.
+ (core / "_harness_id.py").write_text(_render_harness_id(host, portable=portable), encoding="utf-8")
+
+ values = {
+ "PLUGIN_ROOT": plugin_root,
+ "PLUGIN_DATA": "${PLUGIN_DATA}",
+ "PLUGIN_DATA_ARG": f'--plugin-data-dir "{plugin_data}"' if plugin_data else "",
+ "COMMAND_PREFIX": "mem0",
+ "HARNESS_ID": host,
+ "HARNESS_NAME": host.replace("-", " ").title(),
+ }
+ for source in sorted(SHARED_SKILLS.glob("*/SKILL.md.tmpl")):
+ target = staged / "skills" / source.parent.name / "SKILL.md"
+ target.parent.mkdir(parents=True)
+ rendered = render_template(source.read_text(encoding="utf-8"), values)
+ if portable:
+ rendered = "\n".join(
+ line
+ for line in rendered.splitlines()
+ if not line.startswith(("argument-hint:", "disable-model-invocation:"))
+ ) + "\n"
+ target.write_text(rendered, encoding="utf-8")
+
+
+def _build_portable(staged: Path) -> None:
+ source = INTEGRATIONS_ROOT / PORTABLE_PLUGIN
+ _copy_declared_files(staged, source, {"plugin.json": "plugin.json", "mcp.json": "mcp.json"})
+ _bundle_python(staged, "coding-agent", "${PLUGIN_ROOT}", portable=True)
+
+
+def _copy_declared_files(staged: Path, source_root: Path, files: object) -> None:
+ if not isinstance(files, dict):
+ raise ValueError("native files must be an object")
+ source_root = source_root.resolve()
+ staged_root = staged.resolve()
+ for source_name, target_name in files.items():
+ if not isinstance(source_name, str) or not isinstance(target_name, str):
+ raise ValueError("native file paths must be strings")
+ source = (source_root / source_name).resolve()
+ target = (staged / target_name).resolve()
+ if not source.is_relative_to(source_root) or not target.is_relative_to(staged_root):
+ raise ValueError("native file paths must stay inside their roots")
+ if not source.is_file():
+ raise ValueError(f"native source file does not exist: {source_name}")
+ target.parent.mkdir(parents=True, exist_ok=True)
+ shutil.copy2(source, target)
+
+
+def _build_native(host: str, source_root: Path, staged: Path, descriptor: dict) -> None:
+ native = descriptor.get("native")
+ if not isinstance(native, dict) or not isinstance(native.get("pluginRoot"), str):
+ raise ValueError(f"native build is not declared for {host}")
+ _bundle_python(
+ staged,
+ host,
+ native["pluginRoot"],
+ plugin_data=str(native.get("pluginData") or ""),
+ )
+ _copy_declared_files(staged, source_root, native.get("files", {}))
+
+
+def build(host: str, kind: str, output: Path) -> Path:
+ if kind not in {"portable", "native"}:
+ raise ValueError(f"unknown bundle kind: {kind}")
+ if kind == "portable":
+ if host != PORTABLE_PLUGIN:
+ raise ValueError(f"the portable bundle is {PORTABLE_PLUGIN}")
+ source_root = INTEGRATIONS_ROOT / PORTABLE_PLUGIN
+ descriptor = None
+ else:
+ source_root = NATIVE_PLUGINS.get(host)
+ if source_root is None:
+ raise ValueError(f"unknown host: {host}")
+ descriptor_path = source_root / "plugin-build.json"
+ descriptor = json.loads(descriptor_path.read_text(encoding="utf-8"))
+ with tempfile.TemporaryDirectory(prefix=f"mem0-{host}-{kind}-") as temporary:
+ staged = Path(temporary) / "bundle"
+ staged.mkdir()
+ if kind == "portable":
+ _build_portable(staged)
+ else:
+ assert descriptor is not None
+ _build_native(host, source_root, staged, descriptor)
+ errors = validate_bundle(staged, kind)
+ if errors:
+ raise ValueError("invalid bundle:\n" + "\n".join(errors))
+ return replace_output(staged, output)
+
+
+def installable_root(host: str, kind: str) -> Path:
+ if kind == "portable" and host == PORTABLE_PLUGIN:
+ return INTEGRATIONS_ROOT / PORTABLE_PLUGIN
+ if kind == "native" and host in NATIVE_PLUGINS:
+ return NATIVE_PLUGINS[host]
+ raise ValueError(f"unknown {kind} plugin: {host}")
+
+
+def bundle_drift(host: str, kind: str) -> list[str]:
+ target = installable_root(host, kind)
+ with tempfile.TemporaryDirectory(prefix=f"mem0-check-{host}-") as temporary:
+ generated = build(host, kind, Path(temporary) / "bundle")
+ errors: list[str] = []
+ for directory in ("core", "skills"):
+ expected = {
+ path.relative_to(generated)
+ for path in (generated / directory).rglob("*")
+ if path.is_file()
+ }
+ actual = {
+ path.relative_to(target)
+ for path in (target / directory).rglob("*")
+ if path.is_file() and "__pycache__" not in path.parts and path.suffix != ".pyc"
+ }
+ errors.extend(f"missing generated file: {path}" for path in sorted(expected - actual))
+ errors.extend(f"stale generated file: {path}" for path in sorted(actual - expected))
+ for source in sorted(path for path in generated.rglob("*") if path.is_file()):
+ relative = source.relative_to(generated)
+ installed = target / relative
+ if not installed.is_file() or source.read_bytes() != installed.read_bytes():
+ errors.append(f"generated file differs: {relative}")
+ return errors
+
+
+def sync_generated(host: str, kind: str) -> Path:
+ target = installable_root(host, kind)
+ with tempfile.TemporaryDirectory(prefix=f"mem0-sync-{host}-") as temporary:
+ generated = build(host, kind, Path(temporary) / "bundle")
+ for directory in ("core", "skills"):
+ replace_output(generated / directory, target / directory)
+ return target
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description="Build a self-contained Mem0 agent plugin")
+ parser.add_argument("host")
+ parser.add_argument("--kind", choices=("portable", "native"), required=True)
+ action = parser.add_mutually_exclusive_group(required=True)
+ action.add_argument("--output", type=Path)
+ action.add_argument("--check", action="store_true")
+ action.add_argument("--sync", action="store_true")
+ args = parser.parse_args()
+ if args.check:
+ errors = bundle_drift(args.host, args.kind)
+ if errors:
+ print("\n".join(errors))
+ return 1
+ print(f"Current {args.kind} bundle: {installable_root(args.host, args.kind)}")
+ elif args.sync:
+ print(sync_generated(args.host, args.kind))
+ else:
+ assert args.output is not None
+ print(build(args.host, args.kind, args.output))
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/integrations/agent-plugin-core/build/schemas/mcp.schema.json b/integrations/agent-plugin-core/build/schemas/mcp.schema.json
new file mode 100644
index 000000000..1c0626056
--- /dev/null
+++ b/integrations/agent-plugin-core/build/schemas/mcp.schema.json
@@ -0,0 +1,89 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "$id": "https://agent-plugins.org/schemas/1.0.0/mcp.schema.json",
+ "title": "Agent Plugins MCP Configuration",
+ "description": "Machine-readable schema for mcp.json in Agent Plugins 1.0.0. The Agent Plugins specification defines additional semantic and operational requirements.",
+ "type": "object",
+ "properties": {
+ "$schema": {
+ "const": "https://agent-plugins.org/schemas/1.0.0/mcp.schema.json",
+ "description": "Canonical identifier of the MCP configuration schema for the Agent Plugins version targeted by this document."
+ },
+ "mcpServers": {
+ "type": "object",
+ "additionalProperties": { "$ref": "#/$defs/server" }
+ }
+ },
+ "required": ["$schema", "mcpServers"],
+ "additionalProperties": false,
+ "$defs": {
+ "server": {
+ "title": "MCP server",
+ "oneOf": [
+ { "$ref": "#/$defs/stdioServer" },
+ { "$ref": "#/$defs/streamableHttpServer" },
+ { "$ref": "#/$defs/sseServer" }
+ ]
+ },
+ "stdioServer": {
+ "title": "stdio MCP server",
+ "type": "object",
+ "properties": {
+ "type": { "const": "stdio" },
+ "command": {
+ "type": "string",
+ "minLength": 1,
+ "description": "Executable token. Resolution rules are defined by the Agent Plugins specification."
+ },
+ "args": { "type": "array", "items": { "type": "string" } },
+ "env": {
+ "type": "object",
+ "propertyNames": { "not": { "enum": ["PLUGIN_ROOT", "PLUGIN_DATA"] } },
+ "additionalProperties": { "type": "string" }
+ },
+ "cwd": {
+ "type": "string",
+ "pattern": "^(?:\\./|\\$\\{PLUGIN_ROOT\\}(?:/|$)|\\$\\{PLUGIN_DATA\\}(?:/|$))",
+ "description": "Plugin-relative, PLUGIN_ROOT-rooted, or PLUGIN_DATA-rooted working directory. Filesystem containment is validated separately."
+ }
+ },
+ "required": ["type", "command"],
+ "additionalProperties": false
+ },
+ "streamableHttpServer": {
+ "title": "Streamable HTTP MCP server",
+ "type": "object",
+ "properties": {
+ "type": { "const": "streamable-http" },
+ "url": {
+ "type": "string",
+ "minLength": 1,
+ "description": "MCP endpoint URL. URL semantics are defined by the Agent Plugins specification."
+ },
+ "headers": { "$ref": "#/$defs/headers" }
+ },
+ "required": ["type", "url"],
+ "additionalProperties": false
+ },
+ "sseServer": {
+ "title": "Legacy HTTP+SSE MCP server",
+ "type": "object",
+ "properties": {
+ "type": { "const": "sse" },
+ "url": {
+ "type": "string",
+ "minLength": 1,
+ "description": "MCP endpoint URL. URL semantics are defined by the Agent Plugins specification."
+ },
+ "headers": { "$ref": "#/$defs/headers" }
+ },
+ "required": ["type", "url"],
+ "additionalProperties": false
+ },
+ "headers": {
+ "title": "HTTP headers",
+ "type": "object",
+ "additionalProperties": { "type": "string" }
+ }
+ }
+}
diff --git a/integrations/agent-plugin-core/build/schemas/plugin.schema.json b/integrations/agent-plugin-core/build/schemas/plugin.schema.json
new file mode 100644
index 000000000..fc3155c35
--- /dev/null
+++ b/integrations/agent-plugin-core/build/schemas/plugin.schema.json
@@ -0,0 +1,45 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "$id": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json",
+ "title": "Agent Plugins Manifest",
+ "description": "Machine-readable schema for plugin.json in Agent Plugins 1.0.0. The Agent Plugins specification defines additional semantic and operational requirements.",
+ "type": "object",
+ "properties": {
+ "$schema": {
+ "const": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json",
+ "description": "Canonical identifier of the plugin manifest schema for the Agent Plugins version targeted by this document."
+ },
+ "name": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 64,
+ "pattern": "^(?!.*(?:--|\\.\\.))[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$",
+ "description": "Human-readable plugin name."
+ },
+ "version": { "type": "string" },
+ "description": { "type": "string" },
+ "author": {
+ "type": "object",
+ "properties": {
+ "name": { "type": "string" },
+ "email": { "type": "string" },
+ "url": { "type": "string" }
+ },
+ "additionalProperties": false
+ },
+ "homepage": { "type": "string" },
+ "repository": { "type": "string" },
+ "license": { "type": "string" },
+ "keywords": {
+ "type": "array",
+ "items": { "type": "string" }
+ },
+ "extensions": {
+ "type": "object",
+ "description": "Client-specific manifest data keyed by reverse-domain extension namespace. Agent Plugins assigns no semantics to namespace object contents.",
+ "additionalProperties": { "type": "object" }
+ }
+ },
+ "required": ["$schema", "name"],
+ "additionalProperties": false
+}
diff --git a/integrations/agent-plugin-core/build/validate.py b/integrations/agent-plugin-core/build/validate.py
new file mode 100644
index 000000000..fea164e16
--- /dev/null
+++ b/integrations/agent-plugin-core/build/validate.py
@@ -0,0 +1,76 @@
+#!/usr/bin/env python3
+from __future__ import annotations
+
+import argparse
+import json
+import sys
+from pathlib import Path
+
+from jsonschema import Draft202012Validator
+from skills_ref import validate as validate_skill
+
+SCHEMAS = Path(__file__).resolve().parent / "schemas"
+
+
+def _schema_errors(path: Path, schema_name: str) -> list[str]:
+ if not path.is_file():
+ return [f"{path.name}: file is required"]
+
+ try:
+ value = json.loads(path.read_text(encoding="utf-8"))
+ except (OSError, json.JSONDecodeError) as error:
+ return [f"{path.name}: {error}"]
+
+ schema = json.loads((SCHEMAS / schema_name).read_text(encoding="utf-8"))
+ errors = Draft202012Validator(schema).iter_errors(value)
+ return [
+ f"{path.name}{''.join(f'.{part}' for part in error.absolute_path)}: {error.message}"
+ for error in sorted(errors, key=lambda item: tuple(str(part) for part in item.absolute_path))
+ ]
+
+
+def validate_bundle(root: Path, kind: str) -> list[str]:
+ errors: list[str] = []
+ if not root.is_dir():
+ return [f"{root}: directory is required"]
+
+ for path in sorted(root.rglob("*")):
+ if path.is_symlink():
+ errors.append(f"{path.relative_to(root)}: symlinks are not allowed in release bundles")
+
+ if kind == "portable":
+ errors.extend(_schema_errors(root / "plugin.json", "plugin.schema.json"))
+ if (root / "mcp.json").exists():
+ errors.extend(_schema_errors(root / "mcp.json", "mcp.schema.json"))
+ skills = root / "skills"
+ if skills.is_dir():
+ for skill in sorted(path for path in skills.iterdir() if path.is_dir()):
+ errors.extend(f"skills/{skill.name}: {error}" for error in validate_skill(skill))
+ elif kind == "native":
+ for path in sorted(root.rglob("*.json")):
+ relative = path.relative_to(root)
+ try:
+ json.loads(path.read_text(encoding="utf-8"))
+ except (OSError, json.JSONDecodeError) as error:
+ errors.append(f"{relative}: {error}")
+ return sorted(errors)
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description="Validate a generated Mem0 plugin bundle")
+ parser.add_argument("root", type=Path)
+ parser.add_argument("--kind", choices=("portable", "native"), required=True)
+ args = parser.parse_args()
+
+ errors = validate_bundle(args.root, args.kind)
+ if errors:
+ for error in errors:
+ print(error, file=sys.stderr)
+ return 1
+
+ print(f"Validated {args.kind} bundle: {args.root}")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/integrations/agent-plugin-core/conformance/artifacts.py b/integrations/agent-plugin-core/conformance/artifacts.py
new file mode 100644
index 000000000..a7aa6efa7
--- /dev/null
+++ b/integrations/agent-plugin-core/conformance/artifacts.py
@@ -0,0 +1,58 @@
+#!/usr/bin/env python3
+"""Verify that a built TypeScript plugin is self-contained and publishable."""
+
+from __future__ import annotations
+
+import argparse
+import re
+import time
+from pathlib import Path
+from typing import Any
+
+
+CORE_ROOT = Path(__file__).resolve().parents[1]
+INTEGRATIONS_ROOT = CORE_ROOT.parent
+TYPESCRIPT_ARTIFACTS = {
+ "openclaw": (INTEGRATIONS_ROOT / "openclaw", ("dist/index.js", "dist/index.d.ts")),
+ "opencode": (INTEGRATIONS_ROOT / "opencode-plugin", ("dist/index.js", "index.d.ts")),
+ "pi-agent": (
+ INTEGRATIONS_ROOT / "pi-agent-plugin",
+ ("dist/index.js", "dist/index.d.ts", "dist/entry.js", "dist/entry.d.ts"),
+ ),
+ "deepseek": (INTEGRATIONS_ROOT / "deepseek-plugin", ("dist/index.js", "dist/index.d.ts")),
+}
+MONOREPO_IMPORT = re.compile(
+ r"(?:from\s+|import\s*\(|require\s*\()\s*['\"][^'\"]*agent-plugin-core"
+)
+
+
+def verify_artifact(group: str, package: Path, required: tuple[str, ...]) -> dict[str, Any]:
+ started = time.monotonic()
+ errors = [f"missing package artifact: {name}" for name in required if not (package / name).is_file()]
+ dist = package / "dist"
+ for pattern in ("*.js", "*.mjs", "*.cjs", "*.d.ts"):
+ for artifact in dist.rglob(pattern) if dist.is_dir() else ():
+ if MONOREPO_IMPORT.search(artifact.read_text(encoding="utf-8")):
+ errors.append(f"monorepo source import in package artifact: {artifact.relative_to(package)}")
+ return {
+ "name": f"{group}-artifact",
+ "group": group,
+ "status": "failed" if errors else "passed",
+ "duration_seconds": round(time.monotonic() - started, 3),
+ **({"output": "\n".join(errors)} if errors else {}),
+ }
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("group", choices=tuple(TYPESCRIPT_ARTIFACTS))
+ args = parser.parse_args()
+ package, required = TYPESCRIPT_ARTIFACTS[args.group]
+ result = verify_artifact(args.group, package, required)
+ if result.get("output"):
+ print(result["output"])
+ return 0 if result["status"] == "passed" else 1
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/integrations/agent-plugin-core/conformance/run.py b/integrations/agent-plugin-core/conformance/run.py
new file mode 100644
index 000000000..86f7de10f
--- /dev/null
+++ b/integrations/agent-plugin-core/conformance/run.py
@@ -0,0 +1,320 @@
+#!/usr/bin/env python3
+"""Run every coding-agent plugin check and emit one conformance report."""
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import subprocess
+import sys
+import tempfile
+import time
+from pathlib import Path
+from typing import Any
+
+
+CORE_ROOT = Path(__file__).resolve().parents[1]
+REPOSITORY_ROOT = CORE_ROOT.parents[1]
+PYTHON_HOSTS = ("claude-code", "cursor", "codex", "kimi", "antigravity")
+GROUPS = (
+ "python-bundles",
+ "python-tests",
+ "typescript-core",
+ "openclaw",
+ "opencode",
+ "pi-agent",
+ "deepseek",
+)
+LIVE_GROUP = "live-platform"
+
+sys.path.insert(0, str(CORE_ROOT))
+sys.path.insert(0, str(CORE_ROOT / "python"))
+from memory_core import redact # noqa: E402
+from build.build import build # noqa: E402
+from conformance.artifacts import TYPESCRIPT_ARTIFACTS, verify_artifact as _typescript_artifact_check # noqa: E402
+
+
+def _package_directories() -> dict[str, Path]:
+ return {
+ "typescript-core": CORE_ROOT / "typescript",
+ "openclaw": REPOSITORY_ROOT / "integrations" / "openclaw",
+ "opencode": REPOSITORY_ROOT / "integrations" / "opencode-plugin",
+ "pi-agent": REPOSITORY_ROOT / "integrations" / "pi-agent-plugin",
+ "deepseek": REPOSITORY_ROOT / "integrations" / "deepseek-plugin",
+ }
+
+
+def _runtime_commands() -> dict[str, list[list[str]]]:
+ return {
+ "python-tests": [
+ [
+ sys.executable,
+ "-m",
+ "pytest",
+ "integrations/agent-plugin-core/tests",
+ "integrations/claude-code-plugin/tests",
+ "integrations/cursor-plugin/tests",
+ "integrations/codex-plugin/tests",
+ "integrations/kimi-plugin/tests",
+ "integrations/antigravity-plugin/tests",
+ "-q",
+ "--ignore=integrations/agent-plugin-core/tests/test_conformance.py",
+ "--ignore=integrations/claude-code-plugin/tests/integration",
+ ]
+ ],
+ "typescript-core": [["pnpm", "test"], ["pnpm", "typecheck"]],
+ "openclaw": [
+ ["pnpm", "test"],
+ ["pnpm", "exec", "tsc", "--noEmit"],
+ ["pnpm", "build"],
+ ],
+ "opencode": [
+ ["bun", "test"],
+ ["bun", "run", "type-check"],
+ ["bun", "run", "build"],
+ ],
+ "pi-agent": [
+ ["pnpm", "test"],
+ ["pnpm", "typecheck"],
+ ["pnpm", "build"],
+ ],
+ "deepseek": [
+ ["pnpm", "test"],
+ ["pnpm", "typecheck"],
+ ["pnpm", "build"],
+ ],
+ LIVE_GROUP: [
+ [
+ sys.executable,
+ "-m",
+ "pytest",
+ "integrations/claude-code-plugin/tests/integration",
+ "-q",
+ ]
+ ],
+ }
+
+
+def _planned_checks(groups: set[str]) -> list[dict[str, Any]]:
+ checks: list[dict[str, Any]] = []
+ if "python-bundles" in groups:
+ checks.append(
+ {
+ "name": "python-bundles",
+ "group": "python-bundles",
+ "status": "planned",
+ "hosts": list(PYTHON_HOSTS),
+ "kinds": {"native": list(PYTHON_HOSTS), "portable": ["mem0-agent-plugin"]},
+ }
+ )
+ for group, commands in _runtime_commands().items():
+ if group not in groups:
+ continue
+ for index, command in enumerate(commands, start=1):
+ checks.append(
+ {
+ "name": f"{group}-{index}",
+ "group": group,
+ "status": "planned",
+ "command": command,
+ }
+ )
+ if group in TYPESCRIPT_ARTIFACTS:
+ _, required = TYPESCRIPT_ARTIFACTS[group]
+ checks.append(
+ {
+ "name": f"{group}-artifact",
+ "group": group,
+ "status": "planned",
+ "required": list(required),
+ }
+ )
+ return checks
+
+
+def _command_check(
+ name: str,
+ group: str,
+ command: list[str],
+ *,
+ cwd: Path,
+ environment_overrides: dict[str, str] | None = None,
+) -> dict[str, Any]:
+ started = time.monotonic()
+ environment = dict(os.environ)
+ environment.update(environment_overrides or {})
+ safe_command = [redact(part) for part in command]
+ try:
+ result = subprocess.run(
+ command,
+ cwd=cwd,
+ env=environment,
+ text=True,
+ capture_output=True,
+ check=False,
+ )
+ output = redact((result.stdout + result.stderr).strip())
+ return {
+ "name": name,
+ "group": group,
+ "status": "passed" if result.returncode == 0 else "failed",
+ "duration_seconds": round(time.monotonic() - started, 3),
+ "command": safe_command,
+ "exit_code": result.returncode,
+ **({"output": output[-8_000:]} if output else {}),
+ }
+ except OSError as exc:
+ return {
+ "name": name,
+ "group": group,
+ "status": "failed",
+ "duration_seconds": round(time.monotonic() - started, 3),
+ "command": safe_command,
+ "exit_code": None,
+ "output": redact(str(exc)),
+ }
+
+
+def _bundle_checks(artifacts_dir: Path) -> list[dict[str, Any]]:
+ checks: list[dict[str, Any]] = []
+ plugins = [(host, "native") for host in PYTHON_HOSTS] + [("mem0-agent-plugin", "portable")]
+ for host, kind in plugins:
+ started = time.monotonic()
+ try:
+ output = artifacts_dir / host
+ build(host, kind, output)
+ status, error = "passed", ""
+ except Exception as exc:
+ status, error = "failed", f"{type(exc).__name__}: {exc}"
+ checks.append(
+ {
+ "name": f"{host}-{kind}",
+ "group": "python-bundles",
+ "host": host,
+ "kind": kind,
+ "status": status,
+ "duration_seconds": round(time.monotonic() - started, 3),
+ **({"output": error} if error else {}),
+ }
+ )
+ return checks
+
+
+def _install_checks(groups: set[str]) -> list[dict[str, Any]]:
+ checks: list[dict[str, Any]] = []
+ for group, package in _package_directories().items():
+ if group not in groups:
+ continue
+ command = (
+ ["bun", "install", "--frozen-lockfile"]
+ if group == "opencode"
+ else ["pnpm", "install", "--frozen-lockfile"]
+ )
+ checks.append(
+ _command_check(
+ f"{group}-install",
+ group,
+ command,
+ cwd=package,
+ environment_overrides={"CI": "true"},
+ )
+ )
+ return checks
+
+
+def _runtime_checks(groups: set[str]) -> list[dict[str, Any]]:
+ checks: list[dict[str, Any]] = []
+ directories = {
+ **_package_directories(),
+ "python-tests": REPOSITORY_ROOT,
+ LIVE_GROUP: REPOSITORY_ROOT,
+ }
+ for group, commands in _runtime_commands().items():
+ if group not in groups:
+ continue
+ for index, command in enumerate(commands, start=1):
+ checks.append(
+ _command_check(
+ f"{group}-{index}",
+ group,
+ command,
+ cwd=directories[group],
+ )
+ )
+ if group in TYPESCRIPT_ARTIFACTS:
+ _, required = TYPESCRIPT_ARTIFACTS[group]
+ checks.append(
+ _typescript_artifact_check(
+ group,
+ directories[group],
+ required,
+ )
+ )
+ return checks
+
+
+def _print_report(report: dict[str, Any]) -> None:
+ for check in report["checks"]:
+ marker = {"passed": "PASS", "failed": "FAIL", "planned": "PLAN"}[check["status"]]
+ duration = f" ({check['duration_seconds']:.3f}s)" if "duration_seconds" in check else ""
+ print(f"{marker:4} {check['name']}{duration}")
+ if check["status"] == "failed" and check.get("output"):
+ print(check["output"])
+ print(f"\nConformance: {report['status']} ({len(report['checks'])} checks)")
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--group", action="append", choices=("all", *GROUPS, LIVE_GROUP), default=[])
+ parser.add_argument("--list", action="store_true", help="Print the checks without running them")
+ parser.add_argument("--install", action="store_true", help="Install TypeScript dependencies first")
+ parser.add_argument("--live", action="store_true", help="Run the opt-in tests against Mem0 Platform")
+ parser.add_argument("--artifacts-dir", type=Path)
+ parser.add_argument("--report", type=Path)
+ args = parser.parse_args()
+
+ selected = set(GROUPS if not args.group or "all" in args.group else args.group)
+ if args.live:
+ selected.add(LIVE_GROUP)
+ if args.list:
+ report = {"status": "planned", "checks": _planned_checks(selected)}
+ if args.report:
+ args.report.parent.mkdir(parents=True, exist_ok=True)
+ args.report.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")
+ _print_report(report)
+ return 0
+ if LIVE_GROUP in selected and not os.environ.get("MEM0_API_KEY"):
+ parser.error("MEM0_API_KEY is required for --live")
+
+ temporary = None
+ if args.artifacts_dir:
+ artifacts_dir = args.artifacts_dir.resolve()
+ artifacts_dir.mkdir(parents=True, exist_ok=True)
+ else:
+ temporary = tempfile.TemporaryDirectory(prefix="mem0-plugin-conformance-")
+ artifacts_dir = Path(temporary.name)
+
+ checks: list[dict[str, Any]] = []
+ try:
+ if args.install:
+ checks.extend(_install_checks(selected))
+ if "python-bundles" in selected:
+ checks.extend(_bundle_checks(artifacts_dir))
+ checks.extend(_runtime_checks(selected))
+ report = {
+ "status": "passed" if all(check["status"] == "passed" for check in checks) else "failed",
+ "checks": checks,
+ }
+ if args.report:
+ args.report.parent.mkdir(parents=True, exist_ok=True)
+ args.report.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")
+ _print_report(report)
+ return 0 if report["status"] == "passed" else 1
+ finally:
+ if temporary is not None:
+ temporary.cleanup()
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/integrations/agent-plugin-core/python/flush_worker.py b/integrations/agent-plugin-core/python/flush_worker.py
new file mode 100644
index 000000000..6f7b9ecb2
--- /dev/null
+++ b/integrations/agent-plugin-core/python/flush_worker.py
@@ -0,0 +1,100 @@
+#!/usr/bin/env python3
+"""Detached remote checkpoint worker.
+
+Claude Code may cancel SessionEnd hooks as a print-mode process exits. The hook
+therefore persists its input first and launches this process in a new session.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import sys
+import time
+from pathlib import Path
+
+import telemetry
+from memory_core import (
+ EvidenceStore,
+ checkpoint_session,
+ configure_harness,
+ touch_handoff_heartbeat,
+)
+
+
+def main() -> int:
+ if len(sys.argv) != 2:
+ return 2
+ handoff_path = Path(sys.argv[1])
+ os.environ["MEM0_CODE_HANDOFF_PATH"] = str(handoff_path)
+ harness = os.environ.get("MEM0_PLUGIN_HARNESS")
+ if harness:
+ source_tag = os.environ.get("MEM0_PLUGIN_SOURCE_TAG", "")
+ configure_harness(
+ harness,
+ env_prefix=os.environ.get("MEM0_PLUGIN_ENV_PREFIX", ""),
+ data_dir_name=os.environ.get("MEM0_PLUGIN_DATA_DIR_NAME", ""),
+ source_tag=source_tag,
+ )
+ telemetry.init(harness=harness, source_tag=source_tag.upper())
+ completed = False
+ try:
+ payload = json.loads(handoff_path.read_text(encoding="utf-8"))
+ delay = float(payload.get("delay_seconds") or 0)
+ if delay > 0:
+ payload.pop("delay_seconds", None)
+ temporary = handoff_path.with_suffix(f".{os.getpid()}.tmp")
+ try:
+ temporary.write_text(json.dumps(payload), encoding="utf-8")
+ temporary.replace(handoff_path)
+ finally:
+ temporary.unlink(missing_ok=True)
+ time.sleep(delay)
+ if not handoff_path.exists():
+ return 0
+ hook_input = payload.get("hook_input") or {}
+ reason = str(payload.get("reason") or "checkpoint")
+ wait_for_inflight = bool(payload.get("wait_for_inflight"))
+ store = EvidenceStore()
+ try:
+ if wait_for_inflight:
+ session_id = str(
+ hook_input.get("session_id") or "unknown-session"
+ )
+ repo = store.repo_for_session(session_id, hook_input.get("cwd"))
+ deadline = time.monotonic() + float(
+ os.environ.get("MEM0_CODE_EXTRACTION_WAIT_SECONDS", "120")
+ )
+ while (
+ store.has_inflight_flush(repo.identity, session_id)
+ and time.monotonic() < deadline
+ ):
+ touch_handoff_heartbeat()
+ time.sleep(0.25)
+ # Hooks capture the conversation before handoff; the worker only flushes it.
+ result = checkpoint_session(store, hook_input, reason)
+ print(json.dumps(result, sort_keys=True), flush=True)
+ completed = result.get("status") in {
+ "semantic-succeeded",
+ "explicitly-stored",
+ "nothing-to-flush",
+ }
+ finally:
+ store.close()
+ return 0
+ finally:
+ telemetry.flush()
+ if completed:
+ try:
+ handoff_path.unlink()
+ except OSError:
+ pass
+ elif handoff_path.suffix == ".running":
+ try:
+ handoff_path.replace(handoff_path.with_suffix(".json"))
+ except OSError:
+ pass
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/integrations/agent-plugin-core/python/hook_runner.py b/integrations/agent-plugin-core/python/hook_runner.py
new file mode 100644
index 000000000..b3d8a3210
--- /dev/null
+++ b/integrations/agent-plugin-core/python/hook_runner.py
@@ -0,0 +1,388 @@
+"""Shared hook orchestration for all Mem0 agent plugins."""
+
+from __future__ import annotations
+
+import argparse
+import hashlib
+import json
+import os
+import subprocess
+import sys
+import time
+import uuid
+from pathlib import Path
+
+import telemetry
+from memory_core import (
+ EvidenceStore,
+ _session_id,
+ api_key,
+ bounded,
+ cache_plugin_api_key,
+ checkpoint_session,
+ clear_stale_api_key_cache,
+ configure_harness,
+ data_dir,
+ detached_process_kwargs,
+ format_context,
+ harness_config,
+ record_session_start,
+ record_tool,
+ record_user_prompt,
+ redact,
+ search_memories,
+)
+
+STALE_RUNNING_SECONDS = 300
+PENDING_EXPIRY_SECONDS = 7 * 24 * 60 * 60
+PENDING_LAUNCH_LIMIT = 5
+DEFAULT_IDLE_FLUSH_SECONDS = 300
+
+_core_dir: Path = Path(__file__).resolve().parent
+
+
+def read_hook_input() -> dict:
+ try:
+ value = json.load(sys.stdin)
+ return value if isinstance(value, dict) else {}
+ except (json.JSONDecodeError, OSError):
+ return {}
+
+
+def default_record_stop(store: EvidenceStore, hook_input: dict):
+ """Record the assistant's response without transcript parsing."""
+ session_id = _session_id(hook_input)
+ repo = store.repo_for_session(session_id, hook_input.get("cwd"))
+ message = redact(hook_input.get("last_assistant_message", "")).strip()
+ if message:
+ store.record_assistant_response(repo, session_id, message)
+ return repo, session_id
+
+
+def first_prompt_memory_output(store: EvidenceStore, hook_input: dict) -> dict:
+ """Search once before the agent handles the first prompt in a session."""
+ repo, session_id, prompt, is_first_prompt = record_user_prompt(store, hook_input)
+ if not is_first_prompt:
+ return {}
+ try:
+ minimum_query_chars = int(os.environ.get("MEM0_CODE_MIN_QUERY_CHARS", "20"))
+ except ValueError:
+ minimum_query_chars = 20
+ if len(prompt.strip()) < max(minimum_query_chars, 1):
+ return {}
+ result = search_memories(
+ store, repo, session_id, bounded(prompt, 6000),
+ top_k=5, operation="first-prompt-search", timeout=2,
+ )
+ if not result.memories:
+ return {}
+ context = format_context(
+ result.memories,
+ "Mem0 found these relevant memories from earlier work in this repository:",
+ )
+ telemetry.record(
+ "context_injected",
+ repo=repo, session_id=session_id, trigger="first-prompt",
+ memory_count=len(result.memories), context_chars=len(context),
+ prompt_chars=len(prompt),
+ )
+ return {
+ "hookSpecificOutput": {
+ "hookEventName": "UserPromptSubmit",
+ "additionalContext": context,
+ },
+ }
+
+
+def _launch_handoff(handoff_path: Path) -> bool:
+ running_path = handoff_path.with_suffix(".running")
+ try:
+ handoff_path.replace(running_path)
+ except OSError:
+ return False
+ worker = _core_dir / "flush_worker.py"
+ log_path = data_dir() / "flush-worker.log"
+ log_handle = open(log_path, "a", encoding="utf-8")
+ harness = harness_config()
+ child_env = os.environ.copy()
+ child_env.update(
+ {
+ "MEM0_CODE_DATA_DIR": str(data_dir()),
+ "MEM0_PLUGIN_HARNESS": harness["name"],
+ "MEM0_PLUGIN_ENV_PREFIX": harness["env_prefix"],
+ "MEM0_PLUGIN_DATA_DIR_NAME": harness["data_dir_name"],
+ "MEM0_PLUGIN_SOURCE_TAG": harness["source_tag"],
+ }
+ )
+ try:
+ subprocess.Popen(
+ [sys.executable, str(worker), str(running_path)],
+ stdin=subprocess.DEVNULL,
+ stdout=log_handle, stderr=log_handle,
+ close_fds=True,
+ env=child_env,
+ **detached_process_kwargs(),
+ )
+ finally:
+ log_handle.close()
+ return True
+
+
+def recover_pending_handoffs() -> int:
+ pending_dir = data_dir() / "pending"
+ pending_dir.mkdir(parents=True, exist_ok=True)
+ now = time.time()
+ for running in pending_dir.glob("*.running"):
+ try:
+ if now - running.stat().st_mtime > STALE_RUNNING_SECONDS:
+ running.replace(running.with_suffix(".json"))
+ except OSError:
+ continue
+ recoverable = []
+ for handoff in pending_dir.glob("*.json"):
+ try:
+ age = now - handoff.stat().st_mtime
+ except OSError:
+ continue
+ if age > PENDING_EXPIRY_SECONDS:
+ handoff.unlink(missing_ok=True)
+ continue
+ recoverable.append((age, handoff))
+ recoverable.sort(key=lambda item: item[0], reverse=True)
+ launched = 0
+ for _, handoff in recoverable[:PENDING_LAUNCH_LIMIT]:
+ launched += int(_launch_handoff(handoff))
+ return launched
+
+
+def refresh_pending_handoffs() -> None:
+ pending_dir = data_dir() / "pending"
+ if not pending_dir.is_dir():
+ return
+ for pattern in ("*.json", "*.running"):
+ for handoff in pending_dir.glob(pattern):
+ try:
+ os.utime(handoff)
+ except OSError:
+ continue
+
+
+def hand_off_flush(
+ hook_input: dict, reason: str, *, wait_for_inflight: bool = False,
+) -> None:
+ pending_dir = data_dir() / "pending"
+ pending_dir.mkdir(parents=True, exist_ok=True)
+ material = (
+ f"{hook_input.get('cwd', '')}\0{hook_input.get('session_id', '')}\0{reason}"
+ )
+ digest = hashlib.sha256(material.encode()).hexdigest()[:24]
+ handoff_path = pending_dir / f"{digest}-{uuid.uuid4().hex[:8]}.json"
+ temporary_path = handoff_path.with_suffix(".tmp")
+ temporary_path.write_text(
+ json.dumps({
+ "hook_input": hook_input,
+ "reason": reason,
+ "wait_for_inflight": wait_for_inflight,
+ }),
+ encoding="utf-8",
+ )
+ temporary_path.replace(handoff_path)
+ _launch_handoff(handoff_path)
+
+
+def automatic_flush_enabled() -> bool:
+ return os.environ.get("MEM0_CODE_AUTO_FLUSH", "true").lower() in {
+ "1", "true", "yes", "on",
+ }
+
+
+def schedule_periodic_checkpoint(
+ store: EvidenceStore, hook_input: dict, repo, session_id: str,
+) -> bool:
+ if (
+ not automatic_flush_enabled()
+ or not api_key()
+ or not store.checkpoint_due(repo.identity, session_id)
+ ):
+ return False
+ if store.prepare_flush(repo, session_id, "periodic") is None:
+ return False
+ hand_off_flush(hook_input, "periodic")
+ return True
+
+
+def _idle_flush_seconds() -> int:
+ try:
+ return max(
+ int(os.environ.get("MEM0_CODE_IDLE_FLUSH_SECONDS", str(DEFAULT_IDLE_FLUSH_SECONDS))),
+ 0,
+ )
+ except ValueError:
+ return DEFAULT_IDLE_FLUSH_SECONDS
+
+
+def schedule_idle_flush(
+ store: EvidenceStore, hook_input: dict, repo, session_id: str,
+) -> bool:
+ delay = _idle_flush_seconds()
+ if delay <= 0 or not automatic_flush_enabled() or not api_key():
+ return False
+ if store.has_inflight_flush(repo.identity, session_id):
+ return False
+ if not store.has_unflushed_events(repo.identity, session_id):
+ return False
+ pending_dir = data_dir() / "pending"
+ pending_dir.mkdir(parents=True, exist_ok=True)
+ material = f"idle\0{hook_input.get('cwd', '')}\0{hook_input.get('session_id', '')}"
+ digest = hashlib.sha256(material.encode()).hexdigest()[:24]
+ for old in pending_dir.glob(f"idle-{digest}*"):
+ old.unlink(missing_ok=True)
+ handoff_path = pending_dir / f"idle-{digest}-{uuid.uuid4().hex[:8]}.json"
+ temporary_path = handoff_path.with_suffix(".tmp")
+ temporary_path.write_text(
+ json.dumps({
+ "hook_input": hook_input,
+ "reason": "idle",
+ "delay_seconds": delay,
+ }),
+ encoding="utf-8",
+ )
+ temporary_path.replace(handoff_path)
+ _launch_handoff(handoff_path)
+ return True
+
+
+def log_failure(exc: Exception) -> None:
+ try:
+ log_path = data_dir() / "plugin-errors.log"
+ with log_path.open("a", encoding="utf-8") as handle:
+ handle.write(f"{time.time():.3f} {type(exc).__name__}: {exc}\n")
+ except OSError:
+ pass
+
+
+def run(
+ *,
+ record_stop_fn=None,
+ extra_actions: dict | None = None,
+ data_dir_env: str = "MEM0_PLUGIN_DATA_DIR",
+ automatic_flush_reasons: set | None = None,
+) -> int:
+ if record_stop_fn is None:
+ record_stop_fn = default_record_stop
+ if automatic_flush_reasons is None:
+ automatic_flush_reasons = {"session-end"}
+
+ base_actions = ["session-start", "user-prompt", "post-tool", "stop", "flush"]
+ all_actions = base_actions + list((extra_actions or {}).keys())
+
+ parser = argparse.ArgumentParser()
+ parser.add_argument("action", choices=all_actions)
+ parser.add_argument("--reason", default="manual")
+ parser.add_argument("--plugin-data-dir", default="")
+ parser.add_argument("--harness", default="")
+ args = parser.parse_args()
+
+ if args.harness:
+ configure_harness(args.harness)
+ telemetry.init(harness=args.harness)
+
+ if args.plugin_data_dir:
+ os.environ[data_dir_env] = args.plugin_data_dir
+
+ # Snapshot BEFORE anything writes to the data dir: cache_plugin_api_key
+ # writes `api-key` and EvidenceStore creates `evidence.sqlite3`, so asking
+ # after them always saw content and every fresh install reported an upgrade.
+ data_dir_was_empty = telemetry.data_dir_was_empty()
+
+ cache_plugin_api_key()
+ if args.action == "session-start":
+ clear_stale_api_key_cache()
+
+ hook_input = read_hook_input()
+ store = EvidenceStore()
+ try:
+ if store.is_paused():
+ if args.action == "session-start":
+ refresh_pending_handoffs()
+ telemetry.record("session_start", paused=True)
+ telemetry.spawn_flush()
+ return 0
+
+ if args.action == "session-start":
+ # Claims the marker atomically and says which event to record, so a
+ # second session starting alongside this one cannot record it too.
+ first_event = telemetry.claim_install(was_empty=data_dir_was_empty)
+ if first_event == "install":
+ telemetry.record("install")
+ elif first_event == "upgrade":
+ # First run after a build that never wrote the marker; the
+ # predecessor version was never recorded anywhere.
+ telemetry.record("upgrade", from_version="pre-0.3")
+ else:
+ previous = telemetry.claim_version_change()
+ if previous:
+ telemetry.record("upgrade", from_version=previous)
+ recovered = recover_pending_handoffs()
+ record_session_start(store, hook_input)
+ if recovered:
+ telemetry.record("handoff_recovered", count=recovered)
+ telemetry.spawn_flush()
+ elif args.action == "user-prompt":
+ output = first_prompt_memory_output(store, hook_input)
+ if output:
+ print(json.dumps(output))
+ elif args.action == "post-tool":
+ record_tool(store, hook_input)
+ elif args.action == "stop":
+ repo, session_id = record_stop_fn(store, hook_input)
+ if not schedule_periodic_checkpoint(store, hook_input, repo, session_id):
+ schedule_idle_flush(store, hook_input, repo, session_id)
+ elif args.action == "flush":
+ automatic = args.reason in automatic_flush_reasons
+ if automatic and not automatic_flush_enabled():
+ return 0
+ if args.reason == "session-end":
+ record_stop_fn(store, hook_input)
+ if os.environ.get("MEM0_CODE_SYNC_FLUSH") == "1":
+ print(json.dumps(checkpoint_session(store, hook_input, args.reason)))
+ else:
+ session_id = str(hook_input.get("session_id") or "unknown-session")
+ repo = store.repo_for_session(session_id, hook_input.get("cwd"))
+ already_running = store.has_inflight_flush(repo.identity, session_id)
+ if already_running and args.reason == "session-end":
+ hand_off_flush(hook_input, args.reason, wait_for_inflight=True)
+ elif not already_running and store.prepare_flush(
+ repo, session_id, args.reason,
+ ) is not None:
+ hand_off_flush(hook_input, args.reason)
+ elif extra_actions and args.action in extra_actions:
+ result = extra_actions[args.action](store, hook_input)
+ if result:
+ print(json.dumps(result))
+ finally:
+ store.close()
+ return 0
+
+
+def entry_point(
+ *,
+ record_stop_fn=None,
+ extra_actions: dict | None = None,
+ data_dir_env: str = "MEM0_PLUGIN_DATA_DIR",
+ automatic_flush_reasons: set | None = None,
+) -> None:
+ try:
+ raise SystemExit(run(
+ record_stop_fn=record_stop_fn,
+ extra_actions=extra_actions,
+ data_dir_env=data_dir_env,
+ automatic_flush_reasons=automatic_flush_reasons,
+ ))
+ except Exception as exc:
+ log_failure(exc)
+ raise SystemExit(0)
+
+
+if __name__ == "__main__":
+ entry_point()
diff --git a/integrations/agent-plugin-core/python/mcp_server.py b/integrations/agent-plugin-core/python/mcp_server.py
new file mode 100644
index 000000000..a0b73cb79
--- /dev/null
+++ b/integrations/agent-plugin-core/python/mcp_server.py
@@ -0,0 +1,240 @@
+#!/usr/bin/env python3
+"""Expose Mem0's memory search as one local coding-agent tool."""
+
+from __future__ import annotations
+
+import json
+import os
+import sys
+from typing import Any
+
+import telemetry
+from memory_core import (
+ CODING_MEMORY_CATEGORY_NAMES,
+ PLUGIN_VERSION,
+ SEARCH_SCOPES,
+ format_search_result,
+ resolve_repo,
+ search_memories,
+)
+
+PROTOCOL_VERSION = "2024-11-05"
+TOOL_NAME = "search_memories"
+TOOL_DESCRIPTION = (
+ "Search memories from earlier work in this repository. Use it before "
+ "repeating investigation or when earlier decisions, fixes, commands, or "
+ "results may help."
+)
+TOOL_SCHEMA = {
+ "type": "object",
+ "properties": {
+ "query": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 2000,
+ "description": "A direct question about earlier work in this repository.",
+ },
+ "top_k": {
+ "type": "integer",
+ "minimum": 1,
+ "maximum": 20,
+ "description": "Maximum memories to return. Uses Mem0's configured default when omitted.",
+ },
+ "category": {
+ "type": "string",
+ "enum": list(CODING_MEMORY_CATEGORY_NAMES),
+ "description": "Optional memory category. Omit to search every category.",
+ },
+ "scope": {
+ "type": "string",
+ "enum": list(SEARCH_SCOPES),
+ "description": (
+ "Which memories to search. 'repo' (default) is the whole repository's "
+ "shared memory plus your own preferences, 'dir' narrows the shared "
+ "part to the current directory, 'mine' is your preferences alone."
+ ),
+ },
+ "run_id": {
+ "type": "string",
+ "minLength": 1,
+ "description": (
+ "Optional coding-agent session ID. With any scope, restricts results to memories "
+ "saved in that session. Omit to recall memories across sessions."
+ ),
+ },
+ },
+ "required": ["query"],
+ "additionalProperties": False,
+}
+
+
+class ToolInputError(ValueError):
+ pass
+
+
+def _validate_arguments(
+ arguments: Any,
+) -> tuple[str, int | None, str | None, str | None, str | None]:
+ if not isinstance(arguments, dict):
+ raise ToolInputError("Search arguments must be an object.")
+
+ unknown = set(arguments) - {"query", "top_k", "category", "scope", "run_id"}
+ if unknown:
+ raise ToolInputError(f"Unknown search argument: {sorted(unknown)[0]}")
+
+ query = arguments.get("query")
+ if not isinstance(query, str) or not query.strip():
+ raise ToolInputError("query must be a non-empty string.")
+ query = query.strip()
+ if len(query) > 2000:
+ raise ToolInputError("query must be at most 2,000 characters.")
+
+ top_k = arguments.get("top_k")
+ if top_k is not None and (
+ isinstance(top_k, bool) or not isinstance(top_k, int) or not 1 <= top_k <= 20
+ ):
+ raise ToolInputError("top_k must be an integer from 1 to 20.")
+
+ category = arguments.get("category")
+ if category is not None and category not in CODING_MEMORY_CATEGORY_NAMES:
+ raise ToolInputError("category must be one of Mem0's supported categories.")
+
+ scope = arguments.get("scope")
+ if scope is not None and scope not in SEARCH_SCOPES:
+ raise ToolInputError(f"scope must be one of {list(SEARCH_SCOPES)}.")
+
+ run_id = arguments.get("run_id")
+ if run_id is not None:
+ if not isinstance(run_id, str) or not run_id.strip():
+ raise ToolInputError("run_id must be a non-empty string.")
+ run_id = run_id.strip()
+
+ return query, top_k, category, scope, run_id
+
+
+def call_search_memories(arguments: Any, cwd: str | None = None) -> str:
+ query, top_k, category, scope, run_id = _validate_arguments(arguments)
+ repo = resolve_repo(cwd or os.environ.get("CLAUDE_PROJECT_DIR") or os.getcwd())
+ result = search_memories(
+ None,
+ repo,
+ None,
+ query,
+ top_k=top_k,
+ category=category,
+ scope=scope,
+ run_id=run_id,
+ operation="mcp-search",
+ )
+ return format_search_result(result)
+
+
+def _workspace_cwd(params: dict[str, Any]) -> str | None:
+ meta = params.get("_meta")
+ if not isinstance(meta, dict):
+ return None
+ metadata = meta.get("x-codex-turn-metadata")
+ if not isinstance(metadata, dict):
+ return None
+ workspaces = metadata.get("workspaces") or {}
+ if isinstance(workspaces, dict):
+ return next((path for path in workspaces if isinstance(path, str) and path), None)
+ return None
+
+
+def _tool_response(text: str, *, is_error: bool = False) -> dict[str, Any]:
+ return {
+ "content": [{"type": "text", "text": text}],
+ "isError": is_error,
+ }
+
+
+def handle_request(message: Any) -> dict[str, Any] | None:
+ if not isinstance(message, dict):
+ return None
+ request_id = message.get("id")
+ method = message.get("method")
+
+ if method == "notifications/initialized":
+ return None
+ if method == "initialize":
+ requested = (message.get("params") or {}).get("protocolVersion")
+ return {
+ "jsonrpc": "2.0",
+ "id": request_id,
+ "result": {
+ "protocolVersion": requested or PROTOCOL_VERSION,
+ "capabilities": {"tools": {"listChanged": False}},
+ "serverInfo": {"name": "mem0", "version": PLUGIN_VERSION},
+ },
+ }
+ if method == "ping":
+ return {"jsonrpc": "2.0", "id": request_id, "result": {}}
+ if method == "tools/list":
+ return {
+ "jsonrpc": "2.0",
+ "id": request_id,
+ "result": {
+ "tools": [
+ {
+ "name": TOOL_NAME,
+ "description": TOOL_DESCRIPTION,
+ "inputSchema": TOOL_SCHEMA,
+ "annotations": {
+ "readOnlyHint": True,
+ "idempotentHint": True,
+ "openWorldHint": True,
+ },
+ }
+ ]
+ },
+ }
+ if method == "tools/call":
+ params = message.get("params") or {}
+ if params.get("name") != TOOL_NAME:
+ result = _tool_response("Unknown Mem0 tool.", is_error=True)
+ else:
+ try:
+ result = _tool_response(
+ call_search_memories(params.get("arguments"), _workspace_cwd(params))
+ )
+ except ToolInputError as exc:
+ result = _tool_response(str(exc), is_error=True)
+ except Exception:
+ result = _tool_response("Memory search failed.", is_error=True)
+ return {"jsonrpc": "2.0", "id": request_id, "result": result}
+ if request_id is None:
+ return None
+ return {
+ "jsonrpc": "2.0",
+ "id": request_id,
+ "error": {"code": -32601, "message": "Method not found"},
+ }
+
+
+def main() -> int:
+ for raw_line in sys.stdin:
+ try:
+ message = json.loads(raw_line)
+ response = handle_request(message)
+ except json.JSONDecodeError:
+ response = {
+ "jsonrpc": "2.0",
+ "id": None,
+ "error": {"code": -32700, "message": "Parse error"},
+ }
+ except Exception:
+ response = {
+ "jsonrpc": "2.0",
+ "id": None,
+ "error": {"code": -32603, "message": "Internal error"},
+ }
+ if response is not None:
+ sys.stdout.write(json.dumps(response, separators=(",", ":")) + "\n")
+ sys.stdout.flush()
+ telemetry.spawn_flush()
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/integrations/agent-plugin-core/python/memory_cli.py b/integrations/agent-plugin-core/python/memory_cli.py
new file mode 100644
index 000000000..76d2ee871
--- /dev/null
+++ b/integrations/agent-plugin-core/python/memory_cli.py
@@ -0,0 +1,154 @@
+#!/usr/bin/env python3
+"""Mem0 diagnostics and user controls."""
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+
+import telemetry
+from memory_core import (
+ EvidenceStore,
+ api_key,
+ configure_harness,
+ data_dir,
+ doctor,
+ forget_remote_repo,
+ resolve_repo,
+ user_id,
+)
+
+
+def _print_status(value: dict) -> None:
+ last = value.get("last_operation") or {}
+ print(f"Mem0: {'paused' if value['paused'] else 'active'}")
+ print(f"Repository: {value['repo_id']}")
+ print(f"Local data: {value['data_dir']}")
+ print(f"API key: {'configured' if value['api_key_configured'] else 'missing'}")
+ print(
+ "Saved on this computer: "
+ f"{value['events']} session details, {value['flushes']} memory updates"
+ )
+ print(
+ f"Used in this repository: {value['retrievals']} memories returned, "
+ f"{value['subagent_runs']} subagent runs"
+ )
+ if last:
+ item_label = ""
+ if last["operation"] in {"flush", "flush-retry"}:
+ item_label = f", {last['item_count']} memories"
+ operation = (
+ "memory update"
+ if last["operation"] in {"flush", "flush-retry"}
+ else last["operation"].replace("-", " ")
+ )
+ print(
+ f"Last {operation}: "
+ f"{'succeeded' if last['success'] else 'failed'} "
+ f"({last['duration_ms']:.1f} ms{item_label})"
+ )
+ subagent = value.get("last_subagent") or {}
+ if subagent:
+ state = "finished" if subagent.get("stopped_at") else "started"
+ print(
+ "Last subagent: "
+ f"{state}, received {subagent['context_chars']} characters of memory, "
+ f"agent {subagent['agent_id']}"
+ )
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--plugin-data-dir", default="")
+ parser.add_argument("--harness", default="")
+ subparsers = parser.add_subparsers(dest="command", required=True)
+
+ status = subparsers.add_parser("status")
+ status.add_argument("--json", action="store_true")
+
+ doctor_parser = subparsers.add_parser("doctor")
+ doctor_parser.add_argument("--json", action="store_true")
+
+ subparsers.add_parser("pause")
+ subparsers.add_parser("resume")
+
+ forget = subparsers.add_parser("forget")
+ forget.add_argument("--remote", action="store_true")
+ forget.add_argument("--yes", action="store_true")
+ forget.add_argument("--include-project-memory", action="store_true")
+
+ args = parser.parse_args()
+ if args.harness:
+ source_tag = f"{args.harness.replace('-', '_')}_plugin"
+ configure_harness(args.harness, source_tag=source_tag)
+ telemetry.init(harness=args.harness, source_tag=source_tag.upper())
+ if args.plugin_data_dir:
+ os.environ["MEM0_CODE_DATA_DIR"] = args.plugin_data_dir
+ store = EvidenceStore()
+ try:
+ repo = resolve_repo(os.getcwd())
+ telemetry.record("control", repo=repo, action=args.command)
+ if args.command == "status":
+ result = {
+ **store.status(repo.identity),
+ "repo_id": repo.identity,
+ "app_id": repo.app_id,
+ "project_id": repo.project_id,
+ "directory": repo.directory,
+ "user_id": user_id(),
+ "data_dir": str(data_dir()),
+ "api_key_configured": bool(api_key()),
+ }
+ if args.json:
+ print(json.dumps(result, indent=2, default=str))
+ else:
+ _print_status(result)
+ elif args.command == "doctor":
+ result = doctor(os.getcwd())
+ if args.json:
+ print(json.dumps(result, indent=2, default=str))
+ else:
+ for name, check in result["checks"].items():
+ print(
+ f"{'PASS' if check['ok'] else 'FAIL'} {name}: {check['detail']}"
+ )
+ return 0 if result["ok"] else 1
+ elif args.command == "pause":
+ store.set_setting("paused", "true")
+ print("Mem0 stopped saving and searching memories.")
+ elif args.command == "resume":
+ store.set_setting("paused", "false")
+ print("Mem0 resumed saving and searching memories.")
+ elif args.command == "forget":
+ if not args.yes:
+ print(
+ "Refusing to delete data without --yes. Add --remote to also "
+ "delete this user/repository scope from Mem0."
+ )
+ return 2
+ remote_result = (
+ forget_remote_repo(
+ repo, include_project_memory=args.include_project_memory
+ )
+ if args.remote
+ else None
+ )
+ local_result = store.forget_local_repo(repo.identity)
+ print(
+ json.dumps(
+ {"local": local_result, "remote": remote_result},
+ indent=2,
+ default=str,
+ )
+ )
+ if remote_result and remote_result.get("status") == "error":
+ return 1
+ finally:
+ store.close()
+ telemetry.spawn_flush()
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/integrations/agent-plugin-core/python/memory_core.py b/integrations/agent-plugin-core/python/memory_core.py
new file mode 100644
index 000000000..9b420a063
--- /dev/null
+++ b/integrations/agent-plugin-core/python/memory_core.py
@@ -0,0 +1,2676 @@
+#!/usr/bin/env python3
+"""Shared core for Mem0 agent plugins.
+
+Hooks record small session details locally. When the agent compacts or ends the
+session, Mem0 sends the useful parts to the platform so it can create memories.
+The agent can search those memories during later work in the repository.
+"""
+
+from __future__ import annotations
+
+import functools
+import hashlib
+import json
+import math
+import os
+import re
+import sqlite3
+import subprocess
+import sys
+import time
+import urllib.error
+import urllib.parse
+import urllib.request
+from dataclasses import dataclass
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Any, Iterable
+
+import telemetry
+
+DEFAULT_API_URL = "https://api.mem0.ai"
+PLUGIN_VERSION = "0.3.3"
+
+_harness_name: str = "generic"
+_harness_env_prefix: str = "MEM0_PLUGIN"
+_harness_data_dir_name: str = "mem0-plugin"
+_harness_source_tag: str = "mem0_plugin"
+
+
+def configure_harness(
+ name: str,
+ env_prefix: str = "",
+ data_dir_name: str = "",
+ source_tag: str = "",
+) -> None:
+ global _harness_name, _harness_env_prefix, _harness_data_dir_name, _harness_source_tag
+ _harness_name = name
+ _harness_env_prefix = env_prefix or f"MEM0_{name.upper().replace('-', '_')}"
+ _harness_data_dir_name = data_dir_name or f"{name}-plugin"
+ _harness_source_tag = source_tag or f"{name.replace('-', '_')}_plugin"
+
+
+def harness_config() -> dict[str, str]:
+ return {
+ "name": _harness_name,
+ "env_prefix": _harness_env_prefix,
+ "data_dir_name": _harness_data_dir_name,
+ "source_tag": _harness_source_tag,
+ }
+
+
+MAX_COMMAND_CHARS = 2000
+MAX_RESULT_CHARS = 2500
+MAX_EPISODE_CHARS = 12000
+CHECKPOINT_EXCHANGES = 5
+CHECKPOINT_MESSAGES = 10
+CHECKPOINT_SOURCE_CHARS = 40000
+DEFAULT_MAX_CONTEXT_CHARS = 4000
+MAX_EXTRACTION_INPUT_TOKENS = 24000
+MAX_FLUSH_ATTEMPTS = 5
+FORGET_PAGE_SIZE = 100
+FORGET_MAX_PAGES = 50
+
+PROJECT_MEMORY_INSTRUCTIONS = """Save concise repository facts that will help with future coding work.
+
+A completed change should produce one memory explaining the resulting behavior, where it is implemented when useful, and any important constraints or reasoning. Exploration or accepted decisions may produce separate memories only when they are independently useful.
+
+Use the coding agent's final response for conclusions about current repository behavior. Do not save proposed or recommended changes unless the user accepted them or the coding agent completed them. Treat subagent responses as supporting repository evidence, not as decisions.
+
+Write about the repository, not the user, assistant, session, or task. Do not include test results, documentation updates, release notes, or temporary state.
+
+If nothing useful was established, return no memories."""
+
+PERSONAL_MEMORY_INSTRUCTIONS = """Save concise facts about the user that will help in any repository: preferred tools, package managers, languages, coding style, review and communication preferences, and anything the user explicitly asked to be remembered about themselves.
+
+Write in the third person about the user, not about the repository, the assistant, the session, or the task. Do not save repository facts, project decisions, commands, or what was built.
+
+Never save that the user has no preferences or that nothing was learned. If nothing was learned about the user, return no memories."""
+
+CODING_MEMORY_CATEGORIES = [
+ {
+ "project_knowledge": (
+ "What the project is and how its code, APIs, data, files, and "
+ "components work."
+ )
+ },
+ {
+ "decisions_and_constraints": (
+ "Why an approach was chosen, what must remain true, and rules future "
+ "work must follow."
+ )
+ },
+ {
+ "workflows": (
+ "How to run, test, debug, deploy, configure, or otherwise work on the "
+ "project."
+ )
+ },
+ {
+ "problems_and_fixes": (
+ "Bugs, failures, known pitfalls, their causes, and how to fix or avoid "
+ "them."
+ )
+ },
+ {
+ "results": (
+ "Outcomes and measurements from tests, benchmarks, experiments, or "
+ "investigations."
+ )
+ },
+]
+CODING_MEMORY_CATEGORY_NAMES = tuple(
+ category_name
+ for category in CODING_MEMORY_CATEGORIES
+ for category_name in category
+)
+
+TEST_COMMAND_RE = re.compile(
+ r"(?:^|\s)(?:pytest|py\.test|jest|vitest|go\s+test|cargo\s+test|"
+ r"npm\s+(?:run\s+)?test|pnpm\s+(?:run\s+)?test|yarn\s+test|"
+ r"mvn\s+test|gradle\s+test|make\s+test)(?:\s|$)",
+ re.IGNORECASE,
+)
+BUILD_COMMAND_RE = re.compile(
+ r"(?:^|\s)(?:npm|pnpm|yarn)\s+(?:run\s+)?build(?:\s|$)|"
+ r"(?:^|\s)(?:cargo|go|mvn|gradle|make)\s+build(?:\s|$)",
+ re.IGNORECASE,
+)
+
+SECRET_PATTERNS = [
+ re.compile(r"(?i)(authorization\s*[:=]\s*(?:bearer|token)\s+)[^\s\"']+"),
+ re.compile(
+ r"(?i)((?:api[_-]?key|secret[_-]?access[_-]?key|session[_-]?token)\s*[:=]\s*)[^\s\"']+"
+ ),
+ re.compile(
+ r"(?i)((?:access[_-]?token|refresh[_-]?token|password|credential)"
+ r"\s*[:=]\s*)[^\s&\"']+"
+ ),
+ re.compile(r"\b(?:sk|m0|mem0_sk|psk)-[A-Za-z0-9_\-]{12,}\b"),
+ re.compile(r"\b(?:ASIA|AKIA)[A-Z0-9]{12,}\b"),
+ re.compile(r"\b(?:ghp_|github_pat_|xox[baprs]-)[A-Za-z0-9_\-]{12,}\b"),
+ re.compile(
+ r"-----BEGIN [^-]*PRIVATE KEY-----.*?-----END [^-]*PRIVATE KEY-----",
+ re.DOTALL,
+ ),
+ re.compile(
+ r'(?i)("(?:api[_-]?key|password|secret(?:[_-]?access[_-]?key)?'
+ r'|(?:access|refresh|session)[_-]?token|token|authorization|credential'
+ r')"\s*:\s*")(?:\\.|[^"\\])*'
+ ),
+]
+
+
+def utc_now() -> str:
+ return datetime.now(timezone.utc).isoformat()
+
+
+def redact(value: Any) -> str:
+ text = (
+ value
+ if isinstance(value, str)
+ else json.dumps(value, ensure_ascii=False, default=str)
+ )
+ for pattern in SECRET_PATTERNS:
+ if pattern.groups:
+ text = pattern.sub(r"\1[REDACTED]", text)
+ else:
+ text = pattern.sub("[REDACTED]", text)
+ return text
+
+
+def bounded(value: Any, limit: int) -> str:
+ text = redact(value).strip()
+ if len(text) <= limit:
+ return text
+ return text[:limit] + f"\n...[truncated {len(text) - limit} chars]"
+
+
+def _git(cwd: str, *args: str) -> str:
+ try:
+ result = subprocess.run(
+ ["git", "-C", cwd, *args],
+ check=False,
+ capture_output=True,
+ text=True,
+ timeout=0.5,
+ )
+ except (OSError, subprocess.TimeoutExpired):
+ return ""
+ return result.stdout.strip() if result.returncode == 0 else ""
+
+
+def _normalize_remote(remote: str) -> str:
+ remote = remote.strip()
+ if remote.startswith("git@") and ":" in remote:
+ host_path = remote[4:].replace(":", "/", 1)
+ remote = f"https://{host_path}"
+ if remote.endswith(".git"):
+ remote = remote[:-4]
+ if "://" in remote:
+ parsed = urllib.parse.urlsplit(remote)
+ hostname = parsed.hostname or ""
+ if parsed.port:
+ hostname = f"{hostname}:{parsed.port}"
+ remote = urllib.parse.urlunsplit(
+ (parsed.scheme, hostname, parsed.path, parsed.query, parsed.fragment)
+ )
+ return remote.rstrip("/")
+
+
+_WILDCARD_SCOPE = re.compile(r"^\*+$")
+
+
+def _scope_value(raw: str | None) -> str:
+ """Reject wildcards as identities: they are filter syntax and would widen the scope."""
+ value = (raw or "").strip()
+ return "" if _WILDCARD_SCOPE.match(value) else value
+
+
+SEARCH_SCOPES = ("repo", "dir", "mine")
+DEFAULT_SEARCH_SCOPE = "repo"
+
+def directory_app_id(repo: RepoContext) -> str:
+ """The app_id of the directory this session runs in: the repository at the root, repository/path below it."""
+ return f"{repo.app_id}/{repo.directory}" if repo.directory else repo.app_id
+
+
+def directory_chain(repo: RepoContext) -> list[str]:
+ """Every directory a memory belongs to, from the top-level folder down to the one it was written in."""
+ parts = repo.directory.split("/") if repo.directory else []
+ return ["/".join(parts[: index + 1]) for index in range(len(parts))]
+
+
+def _shared_project_ids(repo: RepoContext) -> list[str]:
+ """Current and pre-upgrade namespaces, shared by recall and explicit deletion."""
+ if not repo.identity.startswith("local:") and repo.project_id != repo.app_id:
+ return [repo.project_id, repo.app_id]
+ return [repo.project_id]
+
+
+def _search_filters(user: str, repo: RepoContext, scope: str) -> dict[str, Any]:
+ """Build the scope filter: app_id scopes to the repo, then union shared and personal lanes."""
+ app_scope = {"app_id": repo.app_id}
+ mine = {"AND": [{"user_id": user}, app_scope]}
+ if scope == "mine":
+ return mine
+ projects = [{"AND": [{"agent_id": project_id}, app_scope]} for project_id in _shared_project_ids(repo)]
+ shared: dict[str, Any] = projects[0] if len(projects) == 1 else {"OR": projects}
+ if scope == "dir" and repo.directory:
+ shared = {"AND": [shared, {"metadata": {"dirs": {"contains": repo.directory}}}]}
+ return {"OR": [shared, mine]}
+
+
+def search_scope() -> str:
+ configured = (
+ _plugin_option("search_scope", "MEM0_CODE_SEARCH_SCOPE") or ""
+ ).strip().lower()
+ return configured if configured in SEARCH_SCOPES else DEFAULT_SEARCH_SCOPE
+
+
+def resolve_search_scope(scope: str | None) -> str:
+ value = (scope or search_scope()).strip().lower()
+ if value not in SEARCH_SCOPES:
+ raise ValueError(f"Unknown search scope: {value}")
+ return value
+
+
+def _legacy_project_map(cwd: str, root: str, raw_remote: str) -> str:
+ """Return the project name used by the previous Claude Code plugin."""
+ try:
+ data = json.loads((Path.home() / ".mem0" / "project_map.json").read_text())
+ except (OSError, json.JSONDecodeError):
+ return ""
+ if not isinstance(data, dict):
+ return ""
+
+ keys = list(dict.fromkeys([cwd, root, os.path.realpath(cwd), os.path.realpath(root)]))
+ if raw_remote:
+ keys.append(f"remote:{hashlib.sha256(raw_remote.encode()).hexdigest()[:16]}")
+ for key in keys:
+ value = data.get(key)
+ if isinstance(value, str) and value.strip():
+ return value.strip()
+ return ""
+
+
+def _legacy_project_id(cwd: str, root: str, raw_remote: str, identity: str) -> str:
+ """Use the repository namespace created by the previous Mem0 plugin."""
+ configured = _scope_value(os.environ.get("MEM0_PROJECT_ID"))
+ if configured:
+ return configured
+
+ mapped = _scope_value(_legacy_project_map(cwd, root, raw_remote))
+ if mapped:
+ return mapped
+
+ remote = raw_remote or ("" if identity.startswith("local:") else identity)
+ remote = remote.strip().removesuffix(".git")
+ for prefix in ("https://", "http://", "ssh://", "git://"):
+ if remote.startswith(prefix):
+ remote = remote[len(prefix) :]
+ break
+ else:
+ remote = re.sub(r"^git@", "", remote)
+ parts = [part for part in remote.replace(":", "/", 1).split("/") if part]
+ if len(parts) >= 2:
+ return f"{parts[-2]}-{parts[-1]}".replace("/", "-").replace(":", "-")
+ if parts:
+ return parts[-1].replace("/", "-").replace(":", "-")
+ return os.path.basename(root or cwd) or "unknown"
+
+
+@dataclass(frozen=True)
+class RepoContext:
+ cwd: str
+ root: str
+ identity: str
+ app_id: str
+ branch: str
+ head_sha: str
+ project_id: str = ""
+ directory: str = ""
+
+
+def _project_id(root: str, identity: str, app_id: str) -> str:
+ """The shared namespace: includes a host hash so repos with the same owner/name on different hosts stay apart."""
+ if not identity.startswith("local:"):
+ return f"{app_id}-{hashlib.sha256(identity.encode()).hexdigest()[:10]}"
+ return f"local-{app_id}-{hashlib.sha256(root.encode()).hexdigest()[:10]}"
+
+
+def _relative_directory(cwd: str, root: str) -> str:
+ relative = os.path.relpath(cwd, root)
+ return "" if relative == "." or relative.startswith("..") else relative.replace(os.sep, "/")
+
+
+@dataclass(frozen=True)
+class MemorySearchResult:
+ succeeded: bool
+ matched_count: int
+ already_shown_count: int
+ memories: list[dict[str, Any]]
+
+
+@functools.lru_cache(maxsize=64)
+def _resolve_repo_cached(cwd: str) -> RepoContext:
+ given_cwd = cwd
+ cwd = os.path.realpath(cwd)
+ given_root = _git(cwd, "rev-parse", "--show-toplevel") or given_cwd
+ root = os.path.realpath(given_root)
+ raw_remote = _git(root, "config", "--get", "remote.origin.url")
+ remote = _normalize_remote(raw_remote)
+ identity = remote or f"local:{root}"
+ app_id = _legacy_project_id(given_cwd, given_root, raw_remote, identity)
+ return RepoContext(
+ cwd=cwd,
+ root=root,
+ identity=identity,
+ app_id=app_id,
+ branch=_git(root, "branch", "--show-current") or "detached",
+ head_sha=_git(root, "rev-parse", "HEAD"),
+ project_id=_project_id(root, identity, app_id),
+ directory=_relative_directory(cwd, root),
+ )
+
+
+def resolve_repo(cwd: str | None) -> RepoContext:
+ return _resolve_repo_cached(os.path.abspath(cwd or os.getcwd()))
+
+
+def api_key() -> str:
+ configured = (
+ os.environ.get("MEM0_API_KEY")
+ or os.environ.get("PLUGIN_OPTION_API_KEY")
+ or os.environ.get("CLAUDE_PLUGIN_OPTION_API_KEY")
+ or os.environ.get("CLAUDE_PLUGIN_OPTION_MEM0_API_KEY")
+ or ""
+ ).strip()
+ if configured:
+ return configured
+ try:
+ return (data_dir() / "api-key").read_text(encoding="utf-8").strip()
+ except OSError:
+ return ""
+
+
+def cache_plugin_api_key() -> bool:
+ """Bridge host's hook-only sensitive config into plugin-owned storage."""
+ configured = (
+ os.environ.get("PLUGIN_OPTION_API_KEY")
+ or os.environ.get("CLAUDE_PLUGIN_OPTION_API_KEY")
+ or os.environ.get("CLAUDE_PLUGIN_OPTION_MEM0_API_KEY")
+ or ""
+ ).strip()
+ if not configured:
+ return False
+
+ directory = data_dir()
+ directory.mkdir(parents=True, exist_ok=True)
+ path = directory / "api-key"
+ temporary = directory / f"api-key.{os.getpid()}.tmp"
+ descriptor = os.open(
+ temporary,
+ os.O_WRONLY | os.O_CREAT | os.O_TRUNC,
+ 0o600,
+ )
+ try:
+ with os.fdopen(descriptor, "w", encoding="utf-8") as handle:
+ handle.write(configured)
+ os.replace(temporary, path)
+ os.chmod(path, 0o600)
+ finally:
+ try:
+ temporary.unlink()
+ except FileNotFoundError:
+ pass
+ return True
+
+
+def clear_stale_api_key_cache() -> bool:
+ """Drop the cached key file once every configured key source is gone."""
+ configured = (
+ os.environ.get("MEM0_API_KEY")
+ or os.environ.get("PLUGIN_OPTION_API_KEY")
+ or os.environ.get("CLAUDE_PLUGIN_OPTION_API_KEY")
+ or os.environ.get("CLAUDE_PLUGIN_OPTION_MEM0_API_KEY")
+ or ""
+ ).strip()
+ if configured:
+ return False
+ path = data_dir() / "api-key"
+ if not path.exists():
+ return False
+ try:
+ path.unlink()
+ except OSError:
+ return False
+ return True
+
+
+def detached_process_kwargs(platform: str | None = None) -> dict:
+ """Keep a spawned worker alive after the coding agent exits, on POSIX and Windows."""
+ if (platform or sys.platform) == "win32":
+ return {
+ "creationflags": subprocess.DETACHED_PROCESS
+ | subprocess.CREATE_NEW_PROCESS_GROUP
+ }
+ return {"start_new_session": True}
+
+
+def _plugin_option(name: str, fallback: str = "") -> str:
+ return (
+ os.environ.get(f"PLUGIN_OPTION_{name.upper()}")
+ or os.environ.get(f"CLAUDE_PLUGIN_OPTION_{name.upper()}")
+ or os.environ.get(fallback)
+ or ""
+ ).strip()
+
+
+def user_id() -> str:
+ return (
+ _scope_value(_plugin_option("user_id", "MEM0_CODE_USER_ID"))
+ or _scope_value(os.environ.get("MEM0_USER_ID"))
+ or _scope_value(os.environ.get("MEM0_RESOLVED_USER_ID"))
+ or _scope_value(os.environ.get("USER"))
+ or _scope_value(os.environ.get("USERNAME"))
+ or "default"
+ )
+
+
+def data_dir() -> Path:
+ configured = (
+ os.environ.get("MEM0_CODE_DATA_DIR")
+ or os.environ.get("MEM0_PLUGIN_DATA_DIR")
+ or os.environ.get("PLUGIN_DATA")
+ or os.environ.get("CLAUDE_PLUGIN_DATA")
+ )
+ return (
+ Path(configured).expanduser() if configured else Path.home() / ".mem0" / _harness_data_dir_name
+ )
+
+
+def _bool_option(name: str, fallback: str, default: bool = False) -> bool:
+ value = _plugin_option(name, fallback)
+ if not value:
+ return default
+ return value.lower() in {"1", "true", "yes", "on"}
+
+
+def _int_option(name: str, fallback: str, default: int) -> int:
+ value = _plugin_option(name, fallback)
+ try:
+ return int(value) if value else default
+ except ValueError:
+ return default
+
+
+
+def _checkpoint_message(event: dict[str, Any]) -> str:
+ kind = event.get("kind")
+ payload = event.get("payload") or {}
+ if kind == "user_prompt":
+ return redact(payload.get("text", "")).strip()
+ if kind == "assistant_stop":
+ transcript_messages = payload.get("transcript_messages") or []
+ if isinstance(transcript_messages, list):
+ text = "\n".join(
+ str(message.get("content") or "")
+ for message in transcript_messages
+ if isinstance(message, dict) and message.get("content")
+ )
+ if text:
+ return text
+ return redact(payload.get("text", "")).strip()
+ if kind in {"subagent_stop", "sidekick_stop"}:
+ return redact(payload.get("final_message", "")).strip()
+ return ""
+
+
+def checkpoint_stats(events: list[dict[str, Any]]) -> tuple[int, int, int]:
+ """Return completed exchanges, messages, and source characters."""
+ completed = sum(event.get("kind") == "assistant_stop" for event in events)
+ contents = [content for event in events if (content := _checkpoint_message(event))]
+ return completed, len(contents), sum(len(content) for content in contents)
+
+
+def select_checkpoint_events(
+ events: list[dict[str, Any]], *, force: bool
+) -> list[dict[str, Any]]:
+ """Select one ordered extraction block without splitting an exchange."""
+ for index, event in enumerate(events):
+ if event.get("kind") != "assistant_stop":
+ continue
+ candidate = events[: index + 1]
+ completed, messages, source_chars = checkpoint_stats(candidate)
+ if (
+ completed >= CHECKPOINT_EXCHANGES
+ or messages >= CHECKPOINT_MESSAGES
+ or source_chars >= CHECKPOINT_SOURCE_CHARS
+ ):
+ return candidate
+ return events if force else []
+
+
+class EvidenceStore:
+ def __init__(self, path: Path | None = None):
+ directory = data_dir() if path is None else path.parent
+ directory.mkdir(parents=True, exist_ok=True)
+ self.path = path or directory / "evidence.sqlite3"
+ try:
+ self._open()
+ except sqlite3.DatabaseError:
+ self._quarantine()
+ self._open()
+
+ def _open(self) -> None:
+ self.conn = sqlite3.connect(self.path, timeout=10)
+ self.conn.row_factory = sqlite3.Row
+ try:
+ self.conn.execute("PRAGMA journal_mode=WAL")
+ self.conn.execute("PRAGMA busy_timeout=10000")
+ self._migrate()
+ except sqlite3.DatabaseError:
+ self.conn.close()
+ raise
+
+ def _quarantine(self) -> None:
+ """Move an unreadable database aside so capture restarts cleanly."""
+ stamp = int(time.time())
+ for suffix in ("", "-wal", "-shm"):
+ source = Path(f"{self.path}{suffix}")
+ try:
+ source.replace(f"{self.path}.corrupt-{stamp}{suffix}")
+ except FileNotFoundError:
+ continue
+ except OSError:
+ try:
+ source.unlink()
+ except OSError:
+ pass
+ telemetry.record("db_quarantined")
+
+ def close(self) -> None:
+ self.conn.close()
+
+ def _migrate(self) -> None:
+ # Keep the legacy table name so existing databases and in-flight workers remain compatible.
+ self.conn.executescript(
+ """
+ CREATE TABLE IF NOT EXISTS events (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ repo_id TEXT NOT NULL,
+ app_id TEXT NOT NULL,
+ session_id TEXT NOT NULL,
+ created_at TEXT NOT NULL,
+ kind TEXT NOT NULL,
+ payload_json TEXT NOT NULL,
+ flush_id TEXT
+ );
+ CREATE INDEX IF NOT EXISTS events_session_idx
+ ON events(repo_id, session_id, flush_id, id);
+
+ CREATE TABLE IF NOT EXISTS session_scopes (
+ session_id TEXT PRIMARY KEY,
+ repo_id TEXT NOT NULL,
+ app_id TEXT NOT NULL,
+ root TEXT NOT NULL,
+ branch TEXT NOT NULL,
+ head_sha TEXT NOT NULL,
+ created_at TEXT NOT NULL,
+ directory TEXT NOT NULL DEFAULT ''
+ );
+
+ CREATE TABLE IF NOT EXISTS flushes (
+ packet_id TEXT PRIMARY KEY,
+ repo_id TEXT NOT NULL,
+ app_id TEXT NOT NULL,
+ session_id TEXT NOT NULL,
+ reason TEXT NOT NULL,
+ event_start INTEGER NOT NULL,
+ event_end INTEGER NOT NULL,
+ status TEXT NOT NULL,
+ episode_event_id TEXT,
+ semantic_event_id TEXT,
+ error TEXT,
+ attempts INTEGER NOT NULL DEFAULT 0,
+ created_at TEXT NOT NULL,
+ updated_at TEXT NOT NULL
+ );
+
+ CREATE TABLE IF NOT EXISTS retrievals (
+ session_id TEXT NOT NULL,
+ repo_id TEXT NOT NULL,
+ memory_id TEXT NOT NULL,
+ injected_at TEXT NOT NULL,
+ rank INTEGER,
+ score REAL,
+ memory_text TEXT,
+ context_chars INTEGER NOT NULL DEFAULT 0,
+ PRIMARY KEY(session_id, repo_id, memory_id)
+ );
+
+ CREATE TABLE IF NOT EXISTS operations (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ created_at TEXT NOT NULL,
+ repo_id TEXT NOT NULL,
+ session_id TEXT NOT NULL,
+ operation TEXT NOT NULL,
+ duration_ms REAL NOT NULL,
+ success INTEGER NOT NULL,
+ item_count INTEGER NOT NULL DEFAULT 0,
+ request_chars INTEGER NOT NULL DEFAULT 0,
+ response_chars INTEGER NOT NULL DEFAULT 0,
+ error TEXT
+ );
+
+ CREATE TABLE IF NOT EXISTS sidekick_runs (
+ repo_id TEXT NOT NULL,
+ session_id TEXT NOT NULL,
+ agent_id TEXT NOT NULL,
+ agent_type TEXT NOT NULL,
+ started_at TEXT NOT NULL,
+ stopped_at TEXT,
+ transcript_path TEXT,
+ context_chars INTEGER NOT NULL DEFAULT 0,
+ final_message TEXT,
+ PRIMARY KEY(repo_id, session_id, agent_id)
+ );
+ CREATE INDEX IF NOT EXISTS sidekick_runs_repo_idx
+ ON sidekick_runs(repo_id, started_at);
+
+ CREATE TABLE IF NOT EXISTS settings (
+ key TEXT PRIMARY KEY,
+ value TEXT NOT NULL,
+ updated_at TEXT NOT NULL
+ );
+
+ """
+ )
+ # Remove the pre-0.1.1 snapshot implementation.
+ self.conn.executescript(
+ """
+ DROP TABLE IF EXISTS sidekick_calls;
+ DROP TABLE IF EXISTS sidekick_snapshots;
+ DROP TABLE IF EXISTS sidekick_state;
+ DROP TABLE IF EXISTS sidekick_packets;
+ """
+ )
+ self._ensure_column("retrievals", "rank", "INTEGER")
+ self._ensure_column("retrievals", "score", "REAL")
+ self._ensure_column("retrievals", "memory_text", "TEXT")
+ self._ensure_column("retrievals", "context_chars", "INTEGER NOT NULL DEFAULT 0")
+ self._ensure_column("flushes", "attempts", "INTEGER NOT NULL DEFAULT 0")
+ self._ensure_column("session_scopes", "directory", "TEXT NOT NULL DEFAULT ''")
+ self.conn.commit()
+
+ def _ensure_column(self, table: str, column: str, declaration: str) -> None:
+ columns = {
+ str(row["name"])
+ for row in self.conn.execute(f"PRAGMA table_info({table})").fetchall()
+ }
+ if column not in columns:
+ self.conn.execute(f"ALTER TABLE {table} ADD COLUMN {column} {declaration}")
+
+ def record_event(
+ self,
+ repo: RepoContext,
+ session_id: str,
+ kind: str,
+ payload: dict[str, Any],
+ ) -> int:
+ cursor = self.conn.execute(
+ """INSERT INTO events
+ (repo_id, app_id, session_id, created_at, kind, payload_json)
+ VALUES (?, ?, ?, ?, ?, ?)""",
+ (
+ repo.identity,
+ repo.app_id,
+ session_id,
+ utc_now(),
+ kind,
+ json.dumps(payload, ensure_ascii=False, sort_keys=True),
+ ),
+ )
+ self.conn.commit()
+ return int(cursor.lastrowid)
+
+ def record_assistant_response(self, repo: RepoContext, session_id: str, message: str) -> None:
+ """Ignore repeated response hooks until another prompt or a different answer arrives."""
+ with self.conn:
+ # Serialize the check and insert across concurrent Stop and SessionEnd hooks.
+ self.conn.execute("BEGIN IMMEDIATE")
+ previous = self.conn.execute(
+ """SELECT kind, payload_json FROM events
+ WHERE repo_id = ? AND session_id = ? AND kind IN ('user_prompt', 'assistant_stop')
+ ORDER BY id DESC LIMIT 1""",
+ (repo.identity, session_id),
+ ).fetchone()
+ if (
+ previous is not None
+ and previous["kind"] == "assistant_stop"
+ and json.loads(previous["payload_json"]).get("text") == message
+ ):
+ return
+ self.record_event(repo, session_id, "assistant_stop", {"text": message})
+
+ def repo_for_session(self, session_id: str, cwd: str | None) -> RepoContext:
+ """Keep one project scope for every hook in a coding-agent session."""
+ current = resolve_repo(cwd)
+ if session_id == "unknown-session":
+ return current
+
+ with self.conn:
+ self.conn.execute(
+ """INSERT OR IGNORE INTO session_scopes
+ (session_id, repo_id, app_id, root, branch, head_sha, created_at, directory)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)""",
+ (
+ session_id,
+ current.identity,
+ current.app_id,
+ current.root,
+ current.branch,
+ current.head_sha,
+ utc_now(),
+ current.directory,
+ ),
+ )
+ scope = self.conn.execute(
+ "SELECT * FROM session_scopes WHERE session_id = ?", (session_id,)
+ ).fetchone()
+ same_git_repo = (
+ current.identity == scope["repo_id"] and bool(current.head_sha)
+ )
+ pinned = current if same_git_repo else resolve_repo(str(scope["root"]))
+ return RepoContext(
+ cwd=current.cwd,
+ root=pinned.root,
+ identity=str(scope["repo_id"]),
+ app_id=str(scope["app_id"]),
+ branch=pinned.branch,
+ head_sha=pinned.head_sha,
+ project_id=pinned.project_id,
+ directory=str(scope["directory"] or ""),
+ )
+
+ def prepare_flush(
+ self, repo: RepoContext, session_id: str, reason: str
+ ) -> tuple[str, list[dict[str, Any]]] | None:
+ with self.conn:
+ self.conn.execute("BEGIN IMMEDIATE")
+ existing = self.conn.execute(
+ """SELECT * FROM flushes
+ WHERE repo_id = ? AND session_id = ?
+ AND status NOT IN ('semantic-succeeded', 'explicitly-stored', 'gave-up')
+ ORDER BY created_at LIMIT 1""",
+ (repo.identity, session_id),
+ ).fetchone()
+ if existing and int(existing["attempts"] or 0) >= MAX_FLUSH_ATTEMPTS:
+ self.conn.execute(
+ "UPDATE flushes SET status = 'gave-up', updated_at = ? WHERE packet_id = ?",
+ (utc_now(), existing["packet_id"]),
+ )
+ telemetry.record(
+ "flush",
+ repo=repo,
+ session_id=session_id,
+ reason=reason,
+ status="gave-up",
+ success=False,
+ attempts=int(existing["attempts"] or 0),
+ )
+ existing = None
+ if existing:
+ if reason != "periodic" and existing["reason"] == "periodic":
+ self.conn.execute(
+ "UPDATE flushes SET reason = ?, updated_at = ? WHERE packet_id = ?",
+ (reason, utc_now(), existing["packet_id"]),
+ )
+ existing_rows = self.conn.execute(
+ "SELECT * FROM events WHERE flush_id = ? ORDER BY id",
+ (existing["packet_id"],),
+ ).fetchall()
+ if existing_rows:
+ return str(existing["packet_id"]), [
+ {
+ "id": row["id"],
+ "created_at": row["created_at"],
+ "kind": row["kind"],
+ "payload": json.loads(row["payload_json"]),
+ }
+ for row in existing_rows
+ ]
+
+ rows = self.conn.execute(
+ """SELECT * FROM events
+ WHERE repo_id = ? AND session_id = ? AND flush_id IS NULL
+ ORDER BY id""",
+ (repo.identity, session_id),
+ ).fetchall()
+ if not rows:
+ return None
+
+ events = [
+ {
+ "id": row["id"],
+ "created_at": row["created_at"],
+ "kind": row["kind"],
+ "payload": json.loads(row["payload_json"]),
+ }
+ for row in rows
+ ]
+ events = select_checkpoint_events(events, force=reason != "periodic")
+ if not events:
+ return None
+ event_start, event_end = events[0]["id"], events[-1]["id"]
+ packet_material = f"{repo.identity}\0{session_id}\0{event_start}\0{event_end}"
+ packet_id = hashlib.sha256(packet_material.encode()).hexdigest()[:32]
+ now = utc_now()
+
+ self.conn.execute(
+ """INSERT OR IGNORE INTO flushes
+ (packet_id, repo_id, app_id, session_id, reason, event_start,
+ event_end, status, created_at, updated_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, 'prepared', ?, ?)""",
+ (
+ packet_id,
+ repo.identity,
+ repo.app_id,
+ session_id,
+ reason,
+ event_start,
+ event_end,
+ now,
+ now,
+ ),
+ )
+ event_ids = [event["id"] for event in events]
+ placeholders = ", ".join("?" for _ in event_ids)
+ self.conn.execute(
+ f"UPDATE events SET flush_id = ? "
+ f"WHERE id IN ({placeholders}) AND flush_id IS NULL",
+ (packet_id, *event_ids),
+ )
+ return packet_id, events
+
+ def checkpoint_due(self, repo_id: str, session_id: str) -> bool:
+ if self.has_inflight_flush(repo_id, session_id):
+ return False
+ rows = self.conn.execute(
+ """SELECT * FROM events
+ WHERE repo_id = ? AND session_id = ? AND flush_id IS NULL
+ ORDER BY id""",
+ (repo_id, session_id),
+ ).fetchall()
+ events = [
+ {
+ "id": row["id"],
+ "created_at": row["created_at"],
+ "kind": row["kind"],
+ "payload": json.loads(row["payload_json"]),
+ }
+ for row in rows
+ ]
+ return bool(select_checkpoint_events(events, force=False))
+
+ def has_inflight_flush(self, repo_id: str, session_id: str) -> bool:
+ return (
+ self.conn.execute(
+ """SELECT 1 FROM flushes
+ WHERE repo_id = ? AND session_id = ?
+ AND status IN ('prepared', 'semantic-queued')
+ LIMIT 1""",
+ (repo_id, session_id),
+ ).fetchone()
+ is not None
+ )
+
+ def flush_record(self, packet_id: str) -> dict[str, Any] | None:
+ row = self.conn.execute(
+ "SELECT * FROM flushes WHERE packet_id = ?", (packet_id,)
+ ).fetchone()
+ return dict(row) if row else None
+
+ def has_unflushed_events(self, repo_id: str, session_id: str) -> bool:
+ return (
+ self.conn.execute(
+ """SELECT 1 FROM events
+ WHERE repo_id = ? AND session_id = ? AND flush_id IS NULL
+ LIMIT 1""",
+ (repo_id, session_id),
+ ).fetchone()
+ is not None
+ )
+
+ def unflushed_starts_with_session_start(
+ self, repo_id: str, session_id: str
+ ) -> bool:
+ row = self.conn.execute(
+ """SELECT kind FROM events
+ WHERE repo_id = ? AND session_id = ? AND flush_id IS NULL
+ ORDER BY id LIMIT 1""",
+ (repo_id, session_id),
+ ).fetchone()
+ return bool(row and row["kind"] == "session_start")
+
+ def update_flush(self, packet_id: str, **fields: Any) -> None:
+ allowed = {"status", "episode_event_id", "semantic_event_id", "error"}
+ updates = {key: value for key, value in fields.items() if key in allowed}
+ updates["updated_at"] = utc_now()
+ clause = ", ".join(f"{key} = ?" for key in updates)
+ failed = str(fields.get("status", "")) in {
+ "error",
+ "semantic-failed",
+ "semantic-timeout",
+ "semantic-missing",
+ }
+ if failed:
+ clause += ", attempts = attempts + 1"
+ with self.conn:
+ self.conn.execute(
+ f"UPDATE flushes SET {clause} WHERE packet_id = ?",
+ [*updates.values(), packet_id],
+ )
+
+ def unseen(
+ self, session_id: str, repo_id: str, memories: Iterable[dict[str, Any]]
+ ) -> list[dict[str, Any]]:
+ seen = {
+ row["memory_id"]
+ for row in self.conn.execute(
+ "SELECT memory_id FROM retrievals WHERE session_id = ? AND repo_id = ?",
+ (session_id, repo_id),
+ )
+ }
+ return [memory for memory in memories if str(memory.get("id", "")) not in seen]
+
+ def mark_injected(
+ self, session_id: str, repo_id: str, memories: Iterable[dict[str, Any]]
+ ) -> None:
+ now = utc_now()
+ with self.conn:
+ for rank, memory in enumerate(memories, start=1):
+ memory_id = str(memory.get("id", ""))
+ if memory_id:
+ memory_text = bounded(
+ memory.get("memory") or memory.get("text") or "",
+ 4000,
+ )
+ try:
+ score = float(memory["score"])
+ except (KeyError, TypeError, ValueError):
+ score = None
+ self.conn.execute(
+ """INSERT OR IGNORE INTO retrievals
+ (session_id, repo_id, memory_id, injected_at, rank,
+ score, memory_text, context_chars)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)""",
+ (
+ session_id,
+ repo_id,
+ memory_id,
+ now,
+ rank,
+ score,
+ memory_text,
+ len(memory_text),
+ ),
+ )
+
+ def injected_memories(
+ self, session_id: str, repo_id: str
+ ) -> list[dict[str, Any]]:
+ """Return the exact memories already supplied to the main conversation."""
+ rows = self.conn.execute(
+ """SELECT memory_id, rank, score, memory_text
+ FROM retrievals
+ WHERE session_id = ? AND repo_id = ?
+ ORDER BY COALESCE(rank, 2147483647), injected_at, memory_id""",
+ (session_id, repo_id),
+ ).fetchall()
+ return [
+ {
+ "id": row["memory_id"],
+ "memory": row["memory_text"],
+ "score": row["score"],
+ }
+ for row in rows
+ if row["memory_text"]
+ ]
+
+ def start_subagent(
+ self,
+ repo: RepoContext,
+ session_id: str,
+ agent_id: str,
+ agent_type: str,
+ context_chars: int,
+ ) -> bool:
+ """Record one native subagent instance and whether context was first sent."""
+ with self.conn:
+ cursor = self.conn.execute(
+ """INSERT OR IGNORE INTO sidekick_runs
+ (repo_id, session_id, agent_id, agent_type, started_at,
+ context_chars)
+ VALUES (?, ?, ?, ?, ?, ?)""",
+ (
+ repo.identity,
+ session_id,
+ agent_id,
+ agent_type,
+ utc_now(),
+ context_chars,
+ ),
+ )
+ return int(cursor.rowcount) > 0
+
+ def stop_subagent(
+ self,
+ repo: RepoContext,
+ session_id: str,
+ agent_id: str,
+ agent_type: str,
+ transcript_path: str,
+ final_message: str,
+ ) -> str:
+ now = utc_now()
+ self.conn.execute("BEGIN IMMEDIATE")
+ try:
+ if not agent_id:
+ rows = self.conn.execute(
+ """SELECT agent_id FROM sidekick_runs
+ WHERE repo_id = ? AND session_id = ? AND agent_type = ? AND stopped_at IS NULL
+ LIMIT 2""",
+ (repo.identity, session_id, agent_type),
+ ).fetchall()
+ # Without a host ID, overlapping runs cannot be correlated reliably.
+ agent_id = rows[0]["agent_id"] if len(rows) == 1 else f"unknown-agent-{time.time_ns()}"
+ self.conn.execute(
+ """INSERT INTO sidekick_runs
+ (repo_id, session_id, agent_id, agent_type, started_at,
+ stopped_at, transcript_path, final_message)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
+ ON CONFLICT(repo_id, session_id, agent_id) DO UPDATE SET
+ stopped_at = excluded.stopped_at,
+ transcript_path = excluded.transcript_path,
+ final_message = excluded.final_message""",
+ (
+ repo.identity,
+ session_id,
+ agent_id,
+ agent_type,
+ now,
+ now,
+ bounded(transcript_path, 2000),
+ redact(final_message).strip(),
+ ),
+ )
+ self.conn.commit()
+ except Exception:
+ self.conn.rollback()
+ raise
+ return agent_id
+
+ def operation(
+ self,
+ repo: RepoContext,
+ session_id: str,
+ operation: str,
+ duration_ms: float,
+ success: bool,
+ *,
+ item_count: int = 0,
+ request_chars: int = 0,
+ response_chars: int = 0,
+ error: str = "",
+ ) -> None:
+ with self.conn:
+ self.conn.execute(
+ """INSERT INTO operations
+ (created_at, repo_id, session_id, operation, duration_ms,
+ success, item_count, request_chars, response_chars, error)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
+ (
+ utc_now(),
+ repo.identity,
+ session_id,
+ operation,
+ duration_ms,
+ int(success),
+ item_count,
+ request_chars,
+ response_chars,
+ bounded(error, 1000),
+ ),
+ )
+
+ def has_operation(self, repo_id: str, session_id: str, operation: str) -> bool:
+ row = self.conn.execute(
+ """SELECT 1 FROM operations
+ WHERE repo_id = ? AND session_id = ? AND operation = ?
+ LIMIT 1""",
+ (repo_id, session_id, operation),
+ ).fetchone()
+ return row is not None
+
+ def has_event(self, repo_id: str, session_id: str, kind: str) -> bool:
+ row = self.conn.execute(
+ """SELECT 1 FROM events
+ WHERE repo_id = ? AND session_id = ? AND kind = ?
+ LIMIT 1""",
+ (repo_id, session_id, kind),
+ ).fetchone()
+ return row is not None
+
+ def latest_event_payload(
+ self, repo_id: str, session_id: str, kind: str
+ ) -> dict[str, Any]:
+ row = self.conn.execute(
+ """SELECT payload_json FROM events
+ WHERE repo_id = ? AND session_id = ? AND kind = ?
+ ORDER BY id DESC LIMIT 1""",
+ (repo_id, session_id, kind),
+ ).fetchone()
+ if not row:
+ return {}
+ try:
+ payload = json.loads(row["payload_json"])
+ except json.JSONDecodeError:
+ return {}
+ return payload if isinstance(payload, dict) else {}
+
+ def setting(self, key: str, default: str = "") -> str:
+ row = self.conn.execute(
+ "SELECT value FROM settings WHERE key = ?", (key,)
+ ).fetchone()
+ return str(row["value"]) if row else default
+
+ def set_setting(self, key: str, value: str) -> None:
+ with self.conn:
+ self.conn.execute(
+ """INSERT INTO settings(key, value, updated_at)
+ VALUES (?, ?, ?)
+ ON CONFLICT(key) DO UPDATE SET
+ value = excluded.value,
+ updated_at = excluded.updated_at""",
+ (key, value, utc_now()),
+ )
+
+ def is_paused(self) -> bool:
+ return self.setting("paused", "false").lower() in {
+ "1",
+ "true",
+ "yes",
+ "on",
+ }
+
+ def forget_local_repo(self, repo_id: str) -> dict[str, int]:
+ tables = {
+ "events": "repo_id",
+ "session_scopes": "repo_id",
+ "flushes": "repo_id",
+ "retrievals": "repo_id",
+ "operations": "repo_id",
+ "sidekick_runs": "repo_id",
+ }
+ removed: dict[str, int] = {}
+ with self.conn:
+ for table, column in tables.items():
+ cursor = self.conn.execute(
+ f"DELETE FROM {table} WHERE {column} = ?", (repo_id,)
+ )
+ removed["subagent_runs" if table == "sidekick_runs" else table] = max(int(cursor.rowcount), 0)
+ return removed
+
+ def status(self, repo_id: str) -> dict[str, Any]:
+ def count(table: str) -> int:
+ return int(
+ self.conn.execute(
+ f"SELECT COUNT(*) FROM {table} WHERE repo_id = ?", (repo_id,)
+ ).fetchone()[0]
+ )
+
+ last_operation = self.conn.execute(
+ """SELECT created_at, operation, duration_ms, success, item_count, error
+ FROM operations WHERE repo_id = ? ORDER BY id DESC LIMIT 1""",
+ (repo_id,),
+ ).fetchone()
+ last_subagent = self.conn.execute(
+ """SELECT session_id, agent_id, agent_type, started_at, stopped_at,
+ context_chars
+ FROM sidekick_runs WHERE repo_id = ?
+ ORDER BY started_at DESC LIMIT 1""",
+ (repo_id,),
+ ).fetchone()
+ return {
+ "paused": self.is_paused(),
+ "events": count("events"),
+ "flushes": count("flushes"),
+ "retrievals": count("retrievals"),
+ "subagent_runs": count("sidekick_runs"),
+ "last_operation": dict(last_operation) if last_operation else None,
+ "last_subagent": dict(last_subagent) if last_subagent else None,
+ }
+
+
+def _session_id(hook_input: dict[str, Any]) -> str:
+ return str(hook_input.get("session_id") or "unknown-session")
+
+
+def record_session_start(store: EvidenceStore, hook_input: dict[str, Any]) -> None:
+ session_id = _session_id(hook_input)
+ repo = store.repo_for_session(session_id, hook_input.get("cwd"))
+ store.record_event(
+ repo,
+ session_id,
+ "session_start",
+ {
+ "source": hook_input.get("source", "startup"),
+ "model": bounded(hook_input.get("model", ""), 200),
+ "branch": repo.branch,
+ "head_sha": repo.head_sha,
+ },
+ )
+ telemetry.record(
+ "session_start",
+ repo=repo,
+ session_id=session_id,
+ trigger=bounded(str(hook_input.get("source", "startup")), 60),
+ model=bounded(hook_input.get("model", ""), 200),
+ api_key_configured=bool(api_key()),
+ is_git_repo=not repo.identity.startswith("local:"),
+ )
+
+
+def record_user_prompt(
+ store: EvidenceStore, hook_input: dict[str, Any]
+) -> tuple[RepoContext, str, str, bool]:
+ session_id = _session_id(hook_input)
+ repo = store.repo_for_session(session_id, hook_input.get("cwd"))
+ prompt = redact(hook_input.get("prompt", "")).strip()
+ is_first_prompt = not store.has_event(repo.identity, session_id, "user_prompt")
+ store.record_event(repo, session_id, "user_prompt", {"text": prompt})
+ return repo, session_id, prompt, is_first_prompt
+
+
+def _tool_result_preview(response: Any) -> str:
+ if isinstance(response, dict):
+ selected = {}
+ for key in (
+ "stdout",
+ "stderr",
+ "output",
+ "content",
+ "error",
+ "filePath",
+ "success",
+ "interrupted",
+ ):
+ if key in response:
+ selected[key] = response[key]
+ response = selected or {"keys": sorted(response.keys())[:20]}
+ return bounded(response, MAX_RESULT_CHARS)
+
+
+def tool_payload(hook_input: dict[str, Any], *, failed: bool | None = False) -> dict[str, Any]:
+ name = str(hook_input.get("tool_name") or "unknown")
+ tool_input = hook_input.get("tool_input") or {}
+ if not isinstance(tool_input, dict):
+ tool_input = {}
+ payload: dict[str, Any] = {
+ "tool": name,
+ "failed": failed,
+ "duration_ms": hook_input.get("duration_ms"),
+ "agent_role": "subagent" if hook_input.get("agent_id") else "main",
+ }
+ if hook_input.get("agent_id"):
+ payload["agent_id"] = bounded(hook_input["agent_id"], 200)
+ if hook_input.get("agent_type"):
+ payload["agent_type"] = bounded(hook_input["agent_type"], 200)
+
+ if name in {"Read", "Write", "Edit", "MultiEdit", "NotebookEdit"}:
+ path = tool_input.get("file_path") or tool_input.get("notebook_path")
+ if path:
+ payload["path"] = bounded(path, 1000)
+ if name in {"Write", "Edit", "MultiEdit", "NotebookEdit"}:
+ payload["mutation_chars"] = sum(
+ len(str(tool_input.get(key, "")))
+ for key in ("content", "new_string", "new_source", "edits")
+ )
+ elif name == "Bash" or "command" in tool_input:
+ command = bounded(tool_input.get("command", ""), MAX_COMMAND_CHARS)
+ payload["command"] = command
+ payload["command_kind"] = (
+ "test"
+ if TEST_COMMAND_RE.search(command)
+ else "build"
+ if BUILD_COMMAND_RE.search(command)
+ else "shell"
+ )
+ response = (
+ hook_input.get("error") if failed else hook_input.get("tool_response")
+ )
+ payload["result_preview"] = _tool_result_preview(response)
+ elif name in {"Grep", "Glob", "WebSearch", "WebFetch"}:
+ for key in ("pattern", "path", "query", "url"):
+ if tool_input.get(key):
+ payload[key] = bounded(tool_input[key], 1000)
+ else:
+ payload["input_keys"] = sorted(tool_input.keys())[:20]
+ if failed:
+ payload["error"] = bounded(hook_input.get("error", ""), MAX_RESULT_CHARS)
+
+ if failed and "error" not in payload:
+ payload["error"] = bounded(hook_input.get("error", ""), MAX_RESULT_CHARS)
+ return payload
+
+
+def record_tool(
+ store: EvidenceStore, hook_input: dict[str, Any], *, failed: bool | None = False
+) -> None:
+ session_id = _session_id(hook_input)
+ repo = store.repo_for_session(session_id, hook_input.get("cwd"))
+ payload = tool_payload(hook_input, failed=failed)
+ if payload.get("path"):
+ payload["repo_path"] = _repo_relative_path(repo, str(payload["path"]))
+ store.record_event(
+ repo,
+ session_id,
+ "tool_failure" if failed else "tool_result",
+ payload,
+ )
+
+
+def record_subagent_start(
+ store: EvidenceStore, hook_input: dict[str, Any]
+) -> str:
+ """Record a native subagent and reuse the main turn's retrieved memories."""
+ session_id = _session_id(hook_input)
+ repo = store.repo_for_session(session_id, hook_input.get("cwd"))
+ agent_id = bounded(hook_input.get("agent_id", "unknown-agent"), 200)
+ agent_type = bounded(hook_input.get("agent_type", "unknown-agent"), 200)
+ context = combine_context(
+ format_context(store.injected_memories(session_id, repo.identity))
+ )
+ first_start = store.start_subagent(
+ repo, session_id, agent_id, agent_type, len(context)
+ )
+ store.record_event(
+ repo,
+ session_id,
+ "subagent_start",
+ {
+ "agent_id": agent_id,
+ "agent_type": agent_type,
+ "context_chars": len(context) if first_start else 0,
+ "repo_root": bounded(repo.root, 2000),
+ },
+ )
+ telemetry.record(
+ "subagent",
+ repo=repo,
+ session_id=session_id,
+ phase="start",
+ first_start=first_start,
+ context_chars=len(context) if first_start else 0,
+ )
+ return context if first_start else ""
+
+
+def record_subagent_stop(store: EvidenceStore, hook_input: dict[str, Any]) -> None:
+ session_id = _session_id(hook_input)
+ repo = store.repo_for_session(session_id, hook_input.get("cwd"))
+ agent_type = bounded(hook_input.get("agent_type", "unknown-agent"), 200)
+ agent_id = bounded(hook_input.get("agent_id", ""), 200)
+ final_message = redact(hook_input.get("last_assistant_message", "")).strip()
+ transcript_path = bounded(hook_input.get("agent_transcript_path", ""), 2000)
+ agent_id = store.stop_subagent(
+ repo,
+ session_id,
+ agent_id,
+ agent_type,
+ transcript_path,
+ final_message,
+ )
+ store.record_event(
+ repo,
+ session_id,
+ "subagent_stop",
+ {
+ "agent_id": agent_id,
+ "agent_type": agent_type,
+ "transcript_path": transcript_path,
+ "final_message": final_message,
+ },
+ )
+ telemetry.record(
+ "subagent",
+ repo=repo,
+ session_id=session_id,
+ phase="stop",
+ has_transcript=bool(transcript_path),
+ message_chars=len(final_message),
+ )
+
+
+def _ordered_unique(values: Iterable[str]) -> list[str]:
+ seen: set[str] = set()
+ result = []
+ for value in values:
+ if value and value not in seen:
+ seen.add(value)
+ result.append(value)
+ return result
+
+
+def _repo_relative_path(repo: RepoContext, value: str) -> str:
+ value = str(value or "").strip()
+ if not value:
+ return ""
+ try:
+ path = Path(value)
+ if path.is_absolute():
+ try:
+ return path.resolve().relative_to(Path(repo.root).resolve()).as_posix()
+ except ValueError:
+ return ""
+ except (OSError, ValueError):
+ pass
+ return bounded(value, 1000)
+
+
+def _render_command_lines(commands: list[dict[str, str]]) -> list[str]:
+ lines = []
+ for command in commands:
+ line = f"- [{command['status']}/{command['kind']}] {command['command']}"
+ if command["result"]:
+ line += f" โ {bounded(command['result'], 500).replace(chr(10), ' ')}"
+ lines.append(line)
+ return lines
+
+
+def build_episode(
+ repo: RepoContext,
+ session_id: str,
+ packet_id: str,
+ events: list[dict[str, Any]],
+ *,
+ canonical_task: str = "",
+ task_outcome: str = "",
+) -> tuple[str, dict[str, Any]]:
+ prompts = [
+ redact(e["payload"].get("text", "")).strip()
+ for e in events
+ if e["kind"] == "user_prompt" and e["payload"].get("text")
+ ]
+ assistant_conclusions = [
+ redact(e["payload"].get("text", "")).strip()
+ for e in events
+ if e["kind"] == "assistant_stop" and e["payload"].get("text")
+ ]
+ subagent_outcomes = [
+ redact(e["payload"].get("final_message", "")).strip()
+ for e in events
+ if e["kind"] in {"subagent_stop", "sidekick_stop"} and e["payload"].get("final_message")
+ ]
+ tools = [
+ e["payload"] for e in events if e["kind"] in {"tool_result", "tool_failure"}
+ and e["payload"].get("agent_role", "main") == "main"
+ ]
+ read_paths = _ordered_unique(
+ _repo_relative_path(repo, str(t.get("repo_path") or t.get("path", "")))
+ for t in tools
+ if t.get("tool") == "Read"
+ )
+ modified_paths = _ordered_unique(
+ _repo_relative_path(repo, str(t.get("repo_path") or t.get("path", "")))
+ for t in tools
+ if t.get("tool") in {"Write", "Edit", "MultiEdit", "NotebookEdit"}
+ )
+ searches = [
+ {key: t[key] for key in ("tool", "pattern", "path", "query", "url") if key in t}
+ for t in tools
+ if t.get("tool") in {"Grep", "Glob", "WebSearch", "WebFetch"}
+ ]
+ commands = [
+ {
+ "command": t.get("command", ""),
+ "kind": t.get("command_kind", "shell"),
+ "status": "unknown" if t.get("failed", False) is None else "failed" if t.get("failed") else "succeeded",
+ "result": t.get("result_preview", ""),
+ }
+ for t in tools
+ if t.get("command")
+ ]
+
+ task = bounded(canonical_task or (prompts[0] if prompts else ""), 4000)
+ conclusion = redact(assistant_conclusions[-1] if assistant_conclusions else "").strip()
+ outcome = bounded(task_outcome, 2000)
+
+ extraction_messages: list[dict[str, str]] = []
+ pending_user_messages: list[dict[str, str]] = []
+ if task and not prompts:
+ pending_user_messages.append({"role": "user", "content": task})
+ for event in events:
+ if event["kind"] == "user_prompt" and event["payload"].get("text"):
+ pending_user_messages.append(
+ {
+ "role": "user",
+ "content": redact(event["payload"].get("text", "")).strip(),
+ }
+ )
+ elif event["kind"] == "assistant_stop":
+ transcript_messages = event["payload"].get("transcript_messages") or []
+ if isinstance(transcript_messages, list) and transcript_messages:
+ transcript_users = {
+ redact(message.get("content") or "").strip()
+ for message in transcript_messages
+ if isinstance(message, dict) and message.get("role") == "user"
+ }
+ extraction_messages.extend(
+ message
+ for message in pending_user_messages
+ if message["content"].strip() not in transcript_users
+ )
+ extraction_messages.extend(
+ {
+ "role": str(message.get("role") or ""),
+ "content": redact(message.get("content") or "").strip(),
+ }
+ for message in transcript_messages
+ if isinstance(message, dict)
+ and message.get("role") in {"user", "assistant"}
+ and message.get("content")
+ )
+ else:
+ extraction_messages.extend(pending_user_messages)
+ if event["payload"].get("text"):
+ extraction_messages.append(
+ {
+ "role": "assistant",
+ "content": redact(event["payload"].get("text", "")).strip(),
+ }
+ )
+ pending_user_messages = []
+ elif event["kind"] in {"subagent_stop", "sidekick_stop"}:
+ pass
+ extraction_messages.extend(pending_user_messages)
+
+ structured = {
+ "packet_id": packet_id,
+ "repo": repo.identity,
+ "app_id": repo.app_id,
+ "session_id": session_id,
+ "branch": repo.branch,
+ "head_sha": repo.head_sha,
+ "task": task,
+ "task_outcome": outcome,
+ "assistant_conclusion": conclusion,
+ "user_messages": prompts,
+ "assistant_outcomes": assistant_conclusions,
+ "subagent_outcomes": subagent_outcomes,
+ "extraction_messages": extraction_messages,
+ "files_read": read_paths[:50],
+ "files_modified": modified_paths[:50],
+ "searches": searches[-30:],
+ "commands": commands[-30:],
+ }
+ lines = ["Coding-session episode"]
+ if task:
+ lines.extend(["", "Task:", task])
+ if modified_paths:
+ lines.extend(
+ ["", "Files modified:", *[f"- {path}" for path in modified_paths[:50]]]
+ )
+ if read_paths:
+ lines.extend(["", "Files read:", *[f"- {path}" for path in read_paths[:50]]])
+ if commands:
+ lines.append("")
+ lines.append("Observed commands:")
+ lines.extend(_render_command_lines(commands[-30:]))
+ if searches:
+ lines.extend(
+ [
+ "",
+ "Observed searches:",
+ *[
+ f"- {json.dumps(item, ensure_ascii=False, sort_keys=True)}"
+ for item in searches[-20:]
+ ],
+ ]
+ )
+ if conclusion:
+ lines.extend(["", "Agent conclusion:", conclusion])
+ if outcome:
+ lines.extend(["", "Task outcome:", outcome])
+ lines.extend(
+ [
+ "",
+ f"Provenance: repo={repo.identity}; branch={repo.branch}; head={repo.head_sha}; packet={packet_id}",
+ ]
+ )
+ content = "\n".join(lines)
+ return bounded(content, MAX_EPISODE_CHARS), structured
+
+
+def build_semantic_evidence(structured: dict[str, Any]) -> str:
+ """Format changed paths for memory extraction.
+
+ Test and build results remain in the local evidence store for diagnostics,
+ but are not useful repository knowledge by default and should not steer
+ memory extraction toward transient verification details.
+ """
+ modified_paths = [
+ bounded(path, 500) for path in structured.get("files_modified", [])[:20]
+ ]
+ commands = structured.get("commands") or []
+ if not any(command.get("status") == "failed" for command in commands):
+ commands = []
+
+ if not modified_paths and not commands:
+ return ""
+
+ lines = ["Additional repository details from this session"]
+ if modified_paths:
+ lines.extend(
+ [
+ "",
+ "Changed paths:",
+ *[f"- {path}" for path in modified_paths],
+ ]
+ )
+ if commands:
+ lines.extend(["", "Commands run in this session:", *_render_command_lines(commands)])
+ return bounded("\n".join(lines), 8000)
+
+
+def build_extraction_messages(structured: dict[str, Any]) -> list[dict[str, str]]:
+ """Build the session messages sent to Mem0 for memory extraction."""
+ evidence = build_semantic_evidence(structured)
+ messages = [
+ {"role": message["role"], "content": redact(message["content"]).strip()}
+ for message in structured.get("extraction_messages", [])
+ if message.get("role") in {"user", "assistant"} and message.get("content")
+ ]
+ if evidence:
+ for message in reversed(messages):
+ if message["role"] == "assistant":
+ message["content"] = f"{message['content']}\n\n{evidence}"
+ break
+ else:
+ messages.append({"role": "assistant", "content": evidence})
+
+ return messages
+
+
+def _estimated_tokens(value: str) -> int:
+ """Conservatively estimate tokens without adding a tokenizer dependency."""
+ ascii_chars = sum(ord(char) < 128 for char in value)
+ return math.ceil((ascii_chars * 0.4) + (len(value) - ascii_chars))
+
+
+def _message_tokens(messages: list[dict[str, str]]) -> int:
+ return _estimated_tokens(json.dumps(messages, ensure_ascii=False))
+
+
+def _is_agent_assignment(message: dict[str, str]) -> bool:
+ return message.get("role") == "assistant" and message.get(
+ "content", ""
+ ).startswith("Subagent assignment (")
+
+
+def _is_agent_response(message: dict[str, str]) -> bool:
+ return message.get("role") == "assistant" and message.get(
+ "content", ""
+ ).startswith("Subagent response (")
+
+
+def extraction_message_batches(
+ messages: list[dict[str, str]],
+ *,
+ max_tokens: int = MAX_EXTRACTION_INPUT_TOKENS,
+) -> list[list[dict[str, str]]]:
+ """Keep exchanges together when possible; split oversized messages to enforce the request budget."""
+ if not messages or _message_tokens(messages) <= max_tokens:
+ return [messages]
+
+ exchanges: list[list[dict[str, str]]] = []
+ exchange: list[dict[str, str]] = []
+ for message in messages:
+ if message.get("role") == "user" and exchange:
+ exchanges.append(exchange)
+ exchange = []
+ exchange.append(message)
+ if exchange:
+ exchanges.append(exchange)
+
+ units: list[list[dict[str, str]]] = []
+ for exchange in exchanges:
+ if _message_tokens(exchange) <= max_tokens:
+ units.append(exchange)
+ continue
+ index = 0
+ while index < len(exchange):
+ message = exchange[index]
+ if (
+ _is_agent_assignment(message)
+ and index + 1 < len(exchange)
+ and _is_agent_response(exchange[index + 1])
+ ):
+ units.append(exchange[index : index + 2])
+ index += 2
+ else:
+ units.append([message])
+ index += 1
+
+ bounded_units: list[list[dict[str, str]]] = []
+ for unit in units:
+ if _message_tokens(unit) <= max_tokens:
+ bounded_units.append(unit)
+ continue
+ for message in unit:
+ remaining = message["content"]
+ while remaining:
+ low, high = 0, len(remaining)
+ while low < high:
+ middle = (low + high + 1) // 2
+ if _message_tokens([{**message, "content": remaining[:middle]}]) <= max_tokens:
+ low = middle
+ else:
+ high = middle - 1
+ if low == 0:
+ raise ValueError("Extraction token budget cannot fit a message")
+ bounded_units.append([{**message, "content": remaining[:low]}])
+ remaining = remaining[low:]
+
+ batches: list[list[dict[str, str]]] = []
+ batch: list[dict[str, str]] = []
+ for unit in bounded_units:
+ candidate = [*batch, *unit]
+ if batch and _message_tokens(candidate) > max_tokens:
+ batches.append(batch)
+ batch = list(unit)
+ else:
+ batch = candidate
+ if batch:
+ batches.append(batch)
+ return batches
+
+
+# Platform surface attribution. Read from the generated per-host module so a new
+# entrypoint is correct without remembering to configure anything.
+try: # pragma: no cover - absent only in the un-built shared source tree
+ from _harness_id import PLATFORM_APPLICATION as _PLATFORM_APPLICATION
+ from _harness_id import PLATFORM_SOURCE as _PLATFORM_SOURCE
+except ImportError:
+ _PLATFORM_SOURCE = "MEM0_PLUGIN"
+ _PLATFORM_APPLICATION = ""
+
+
+def platform_headers(key: str) -> dict[str, str]:
+ """Auth plus the three surface-identity headers.
+
+ X-Mem0-Source and X-Application are set-once by contract: this is the
+ outermost layer, so it sets them, and nothing below may overwrite them.
+ X-Mem0-Client is append-only โ anything downstream adds itself to the tail.
+ """
+ headers = {
+ "Authorization": f"Token {key}",
+ "Content-Type": "application/json",
+ "X-Mem0-Source": _PLATFORM_SOURCE,
+ "X-Mem0-Client": f"mem0-plugin/{PLUGIN_VERSION}",
+ }
+ if _PLATFORM_APPLICATION:
+ headers["X-Application"] = _PLATFORM_APPLICATION
+ return headers
+
+
+def _request_json(
+ url: str, key: str, payload: dict[str, Any], timeout: float
+) -> tuple[dict[str, Any] | list[Any], int, int]:
+ raw = json.dumps(payload, ensure_ascii=False).encode()
+ request = urllib.request.Request(
+ url,
+ data=raw,
+ headers=platform_headers(key),
+ method="POST",
+ )
+ with urllib.request.urlopen(request, timeout=timeout) as response:
+ response_raw = response.read()
+ parsed = json.loads(response_raw or b"{}")
+ return parsed, len(raw), len(response_raw)
+
+
+def _request_json_with_network_retry(
+ url: str, key: str, payload: dict[str, Any], timeout: float
+) -> tuple[dict[str, Any] | list[Any], int, int]:
+ """Retry one transient connection failure without retrying API responses."""
+ try:
+ return _request_json(url, key, payload, timeout)
+ except urllib.error.HTTPError:
+ raise
+ except (urllib.error.URLError, TimeoutError, OSError):
+ time.sleep(0.25)
+ return _request_json(url, key, payload, timeout)
+
+
+def _get_json(
+ url: str, key: str, timeout: float
+) -> tuple[dict[str, Any] | list[Any], int]:
+ request = urllib.request.Request(
+ url,
+ headers=platform_headers(key),
+ method="GET",
+ )
+ with urllib.request.urlopen(request, timeout=timeout) as response:
+ response_raw = response.read()
+ return json.loads(response_raw or b"{}"), len(response_raw)
+
+
+def _event_id(response: dict[str, Any] | list[Any]) -> str:
+ return str(response.get("event_id", "")) if isinstance(response, dict) else ""
+
+
+def _stored_event_ids(value: Any) -> list[str]:
+ raw = str(value or "")
+ if not raw.startswith("["):
+ return []
+ try:
+ parsed = json.loads(raw)
+ except json.JSONDecodeError:
+ return []
+ return [str(item or "") for item in parsed] if isinstance(parsed, list) else []
+
+
+def _result_count(response: dict[str, Any] | list[Any]) -> int:
+ if isinstance(response, dict):
+ results = response.get("results")
+ return len(results) if isinstance(results, list) else 0
+ return len(response) if isinstance(response, list) else 0
+
+
+def touch_handoff_heartbeat() -> None:
+ """Mark the worker's handoff file alive so recovery does not relaunch it."""
+ path = os.environ.get("MEM0_CODE_HANDOFF_PATH", "")
+ if not path:
+ return
+ try:
+ os.utime(path)
+ except OSError:
+ pass
+
+
+def _wait_for_event(api_url: str, key: str, event_id: str) -> tuple[str, int, int]:
+ """Wait for extraction to finish before a later task can search the store."""
+ if not event_id:
+ return "MISSING", 0, 0
+ wait_seconds = float(os.environ.get("MEM0_CODE_EXTRACTION_WAIT_SECONDS", "120"))
+ poll_seconds = max(float(os.environ.get("MEM0_CODE_EVENT_POLL_SECONDS", "1")), 0.1)
+ deadline = time.monotonic() + wait_seconds
+ response_chars = 0
+ while time.monotonic() < deadline:
+ touch_handoff_heartbeat()
+ try:
+ response, size = _get_json(
+ f"{api_url}/v1/event/{event_id}/",
+ key,
+ min(10, poll_seconds + 5),
+ )
+ except urllib.error.HTTPError as exc:
+ if exc.code not in {408, 429} and exc.code < 500:
+ raise
+ time.sleep(poll_seconds)
+ continue
+ except (urllib.error.URLError, TimeoutError, OSError):
+ # The extraction job is durable server-side. A transient polling
+ # failure must not discard a job that may still complete normally.
+ time.sleep(poll_seconds)
+ continue
+ response_chars += size
+ status = (
+ str(response.get("status", "UNKNOWN"))
+ if isinstance(response, dict)
+ else "UNKNOWN"
+ )
+ if status in {"SUCCEEDED", "FAILED"}:
+ return status, response_chars, _result_count(response)
+ time.sleep(poll_seconds)
+ return "TIMEOUT", response_chars, 0
+
+
+def _record_flush(
+ repo: RepoContext,
+ session_id: str,
+ reason: str,
+ status: str,
+ elapsed: float,
+ **extra: Any,
+) -> None:
+ telemetry.record(
+ "flush",
+ repo=repo,
+ session_id=session_id,
+ reason=reason,
+ status=status,
+ success=status in {"semantic-succeeded", "nothing-to-flush"},
+ duration_ms=round(elapsed, 2),
+ **extra,
+ )
+
+
+def flush_session(
+ store: EvidenceStore, hook_input: dict[str, Any], reason: str
+) -> dict[str, Any]:
+ key = api_key()
+ if not key:
+ telemetry.record("flush", reason=reason, status="local-only", success=False)
+ return {"status": "local-only", "reason": "no-api-key"}
+
+ session_id = _session_id(hook_input)
+ if session_id == "unknown-session":
+ telemetry.record("flush", reason=reason, status="no-session-id", success=False)
+ return {"status": "error", "reason": "no-session-id"}
+ repo = store.repo_for_session(session_id, hook_input.get("cwd"))
+ prepared = store.prepare_flush(repo, session_id, reason)
+ if prepared is None:
+ return {"status": "nothing-to-flush"}
+ packet_id, events = prepared
+ existing_flush = store.flush_record(packet_id) or {}
+
+ _, structured = build_episode(
+ repo,
+ session_id,
+ packet_id,
+ events,
+ canonical_task=bounded(hook_input.get("task", ""), 4000),
+ task_outcome=bounded(hook_input.get("task_outcome", ""), 2000),
+ )
+
+ metadata = {"source": _harness_source_tag}
+ if repo.branch and repo.branch not in {"detached", "unknown"}:
+ metadata["branch"] = repo.branch
+ if repo.head_sha:
+ metadata["git_sha"] = repo.head_sha
+ api_url = os.environ.get("MEM0_API_URL", DEFAULT_API_URL).rstrip("/")
+ add_url = f"{api_url}/v3/memories/add/"
+
+ write_user = _scope_value(user_id())
+ write_project = _scope_value(repo.project_id)
+ if not write_user or not _scope_value(repo.app_id) or not write_project:
+ telemetry.record("flush", reason=reason, status="unscoped", success=False)
+ return {"status": "error", "reason": "wildcard-scope"}
+
+ body = {
+ "agent_id": write_project,
+ "user_id": write_user,
+ "app_id": repo.app_id,
+ "run_id": session_id,
+ # Top level, not metadata: the backend reads `source` from the body or
+ # the query string, never from metadata, which is where this used to
+ # sit. The X-Mem0-Source header is also read, but only from the
+ # platform release that ships alongside this change, so the body value
+ # is what makes attribution work on both. The harness tag stays in
+ # metadata as hook provenance.
+ "source": _PLATFORM_SOURCE,
+ "metadata": {**metadata, "author": write_user, "dirs": directory_chain(repo)},
+ "agent_custom_instructions": PROJECT_MEMORY_INSTRUCTIONS,
+ "custom_instructions": PERSONAL_MEMORY_INSTRUCTIONS,
+ "custom_categories": CODING_MEMORY_CATEGORIES,
+ "infer": True,
+ }
+
+ started = time.perf_counter()
+ try:
+ stored_events = _stored_event_ids(existing_flush.get("semantic_event_id"))
+ existing_event = (
+ "" if stored_events else str(existing_flush.get("semantic_event_id") or "")
+ )
+ if existing_event:
+ existing_status, existing_resp, existing_items = _wait_for_event(
+ api_url, key, existing_event
+ )
+ if existing_status == "SUCCEEDED":
+ elapsed = (time.perf_counter() - started) * 1000
+ store.update_flush(
+ packet_id,
+ status="semantic-succeeded",
+ semantic_event_id=existing_event,
+ error="",
+ )
+ store.operation(
+ repo,
+ session_id,
+ "flush-retry",
+ elapsed,
+ True,
+ item_count=existing_items,
+ response_chars=existing_resp,
+ )
+ _record_flush(
+ repo,
+ session_id,
+ reason,
+ "semantic-succeeded",
+ elapsed,
+ memory_count=existing_items,
+ resumed=True,
+ )
+ effective_reason = str(
+ (store.flush_record(packet_id) or {}).get("reason") or reason
+ )
+ if (
+ store.has_unflushed_events(repo.identity, session_id)
+ and not store.unflushed_starts_with_session_start(
+ repo.identity, session_id
+ )
+ and (
+ effective_reason != "periodic"
+ or store.checkpoint_due(repo.identity, session_id)
+ )
+ ):
+ return flush_session(store, hook_input, effective_reason)
+ return {
+ "status": "semantic-succeeded",
+ "packet_id": packet_id,
+ "semantic_event_id": existing_event,
+ "semantic_status": existing_status,
+ "memory_count": existing_items,
+ "duration_ms": round(elapsed, 2),
+ "resumed": True,
+ }
+ if existing_status == "TIMEOUT":
+ elapsed = (time.perf_counter() - started) * 1000
+ error = "semantic extraction event timed out"
+ store.update_flush(packet_id, status="semantic-timeout", error=error)
+ store.operation(
+ repo,
+ session_id,
+ "flush-retry",
+ elapsed,
+ False,
+ response_chars=existing_resp,
+ error=error,
+ )
+ _record_flush(
+ repo,
+ session_id,
+ reason,
+ "semantic-timeout",
+ elapsed,
+ resumed=True,
+ error_kind="timeout",
+ )
+ return {
+ "status": "semantic-timeout",
+ "packet_id": packet_id,
+ "semantic_event_id": existing_event,
+ "duration_ms": round(elapsed, 2),
+ "resumed": True,
+ }
+
+ message_batches = [
+ batch
+ for batch in extraction_message_batches(
+ build_extraction_messages(structured)
+ )
+ if batch
+ ]
+ batches = [(body, messages) for messages in message_batches]
+ if not batches:
+ store.update_flush(packet_id, status="semantic-succeeded", error="")
+ return {"status": "nothing-to-flush", "packet_id": packet_id}
+ operation_name = "flush-retry" if stored_events else "flush"
+ semantic_events = stored_events[: len(batches)]
+ semantic_events += [""] * (len(batches) - len(semantic_events))
+ semantic_req = 0
+ semantic_resp = 0
+ for index, (body, messages) in enumerate(batches):
+ if semantic_events[index]:
+ continue
+ semantic_response, request_chars, response_chars = _request_json(
+ add_url,
+ key,
+ {**body, "messages": messages},
+ 15,
+ )
+ semantic_events[index] = _event_id(semantic_response)
+ semantic_req += request_chars
+ semantic_resp += response_chars
+ store.update_flush(
+ packet_id,
+ status="semantic-queued",
+ semantic_event_id=json.dumps(semantic_events),
+ )
+
+ semantic_event = semantic_events[-1]
+ semantic_status = "SUCCEEDED"
+ event_resp = 0
+ semantic_items = 0
+ failed_event = semantic_event
+ for index, queued_event in enumerate(semantic_events):
+ status, response_chars, item_count = _wait_for_event(
+ api_url, key, queued_event
+ )
+ event_resp += response_chars
+ semantic_items += item_count
+ if status != "SUCCEEDED":
+ semantic_status = status
+ failed_event = queued_event
+ if status in {"FAILED", "MISSING"}:
+ semantic_events[index] = ""
+ store.update_flush(
+ packet_id, semantic_event_id=json.dumps(semantic_events)
+ )
+ break
+ if semantic_status != "SUCCEEDED":
+ elapsed = (time.perf_counter() - started) * 1000
+ error = f"semantic extraction event {semantic_status.lower()}"
+ store.update_flush(
+ packet_id, status=f"semantic-{semantic_status.lower()}", error=error
+ )
+ store.operation(
+ repo,
+ session_id,
+ operation_name,
+ elapsed,
+ False,
+ item_count=semantic_items,
+ request_chars=semantic_req,
+ response_chars=semantic_resp + event_resp,
+ error=error,
+ )
+ _record_flush(
+ repo,
+ session_id,
+ reason,
+ f"semantic-{semantic_status.lower()}",
+ elapsed,
+ memory_count=semantic_items,
+ batch_count=len(batches),
+ error_kind=telemetry.error_kind(error),
+ )
+ return {
+ "status": f"semantic-{semantic_status.lower()}",
+ "packet_id": packet_id,
+ "semantic_event_id": failed_event,
+ "memory_count": semantic_items,
+ "duration_ms": round(elapsed, 2),
+ }
+
+ elapsed = (time.perf_counter() - started) * 1000
+ store.update_flush(
+ packet_id,
+ status="semantic-succeeded",
+ semantic_event_id=json.dumps(semantic_events),
+ error="",
+ )
+ store.operation(
+ repo,
+ session_id,
+ operation_name,
+ elapsed,
+ True,
+ item_count=semantic_items,
+ request_chars=semantic_req,
+ response_chars=semantic_resp + event_resp,
+ )
+ _record_flush(
+ repo,
+ session_id,
+ reason,
+ "semantic-succeeded",
+ elapsed,
+ memory_count=semantic_items,
+ batch_count=len(batches),
+ request_chars=semantic_req,
+ )
+ effective_reason = str(
+ (store.flush_record(packet_id) or {}).get("reason") or reason
+ )
+ if (
+ store.has_unflushed_events(repo.identity, session_id)
+ and not store.unflushed_starts_with_session_start(
+ repo.identity, session_id
+ )
+ and (
+ effective_reason != "periodic"
+ or store.checkpoint_due(repo.identity, session_id)
+ )
+ ):
+ return flush_session(store, hook_input, effective_reason)
+ return {
+ "status": "semantic-succeeded",
+ "packet_id": packet_id,
+ "semantic_event_id": semantic_event,
+ "semantic_status": semantic_status,
+ "memory_count": semantic_items,
+ "duration_ms": round(elapsed, 2),
+ }
+ except Exception as exc: # hooks must fail open
+ elapsed = (time.perf_counter() - started) * 1000
+ error = bounded(str(exc), 1000)
+ store.update_flush(packet_id, status="error", error=error)
+ store.operation(repo, session_id, "flush", elapsed, False, error=error)
+ _record_flush(
+ repo,
+ session_id,
+ reason,
+ "error",
+ elapsed,
+ error_kind=telemetry.error_kind(exc),
+ )
+ return {"status": "error", "packet_id": packet_id, "error": error}
+
+
+def checkpoint_session(
+ store: EvidenceStore, hook_input: dict[str, Any], reason: str
+) -> dict[str, Any]:
+ """Run remote extraction at a durable boundary."""
+ return flush_session(store, hook_input, reason)
+
+
+
+def search_memories(
+ store: EvidenceStore | None,
+ repo: RepoContext,
+ session_id: str | None,
+ query: str,
+ *,
+ top_k: int | None = None,
+ category: str | None = None,
+ scope: str | None = None,
+ run_id: str | None = None,
+ operation: str = "search",
+ timeout: float = 5,
+) -> MemorySearchResult:
+ key = api_key()
+ if not key or not query.strip():
+ return MemorySearchResult(False, 0, 0, [])
+ search_once = os.environ.get(
+ "MEM0_CODE_SEARCH_ONCE_PER_SESSION", "false"
+ ).lower() in {
+ "1",
+ "true",
+ "yes",
+ "on",
+ }
+ track_session = store is not None and bool(session_id)
+ if (
+ search_once
+ and track_session
+ and store.has_operation(repo.identity, session_id, "search")
+ ):
+ return MemorySearchResult(False, 0, 0, [])
+
+ result_limit = min(
+ max(
+ top_k
+ if top_k is not None
+ else _int_option("top_k", "MEM0_CODE_TOP_K", 3),
+ 1,
+ ),
+ 20,
+ )
+ if category is not None and category not in CODING_MEMORY_CATEGORY_NAMES:
+ raise ValueError(f"Unknown memory category: {category}")
+ user, project = _scope_value(user_id()), _scope_value(repo.project_id)
+ if not user or not project or not _scope_value(repo.app_id):
+ return MemorySearchResult(False, 0, 0, [])
+ filters = _search_filters(user, repo, resolve_search_scope(scope))
+ if category:
+ filters = {"AND": [filters, {"categories": {"contains": category}}]}
+ if run_id:
+ filters = {"AND": [filters, {"run_id": run_id}]}
+ payload = {
+ "query": query,
+ "app_id": repo.app_id,
+ "filters": filters,
+ "top_k": result_limit,
+ "rerank": False,
+ "latest_only": True,
+ }
+ url = (
+ os.environ.get("MEM0_API_URL", DEFAULT_API_URL).rstrip("/")
+ + "/v3/memories/search/"
+ )
+ started = time.perf_counter()
+ try:
+ response, request_chars, response_chars = _request_json_with_network_retry(
+ url, key, payload, timeout
+ )
+ memories = (
+ response if isinstance(response, list) else response.get("results", [])
+ )
+ memories = [
+ memory
+ for memory in memories
+ if isinstance(memory, dict)
+ and (memory.get("metadata") or {}).get("record_kind") != "task_episode"
+ ][:result_limit]
+ if track_session:
+ returned_memories = store.unseen(session_id, repo.identity, memories)
+ store.mark_injected(session_id, repo.identity, returned_memories)
+ already_shown_count = len(memories) - len(returned_memories)
+ else:
+ returned_memories = memories
+ already_shown_count = 0
+ elapsed = (time.perf_counter() - started) * 1000
+ if track_session:
+ store.operation(
+ repo,
+ session_id,
+ operation,
+ elapsed,
+ True,
+ item_count=len(returned_memories),
+ request_chars=request_chars,
+ response_chars=response_chars,
+ )
+ telemetry.record(
+ "search",
+ repo=repo,
+ session_id=session_id,
+ trigger=operation,
+ success=True,
+ duration_ms=round(elapsed, 2),
+ matched_count=len(memories),
+ returned_count=len(returned_memories),
+ already_shown_count=already_shown_count,
+ top_k=result_limit,
+ has_category=bool(category),
+ )
+ return MemorySearchResult(
+ succeeded=True,
+ matched_count=len(memories),
+ already_shown_count=already_shown_count,
+ memories=returned_memories,
+ )
+ except Exception as exc:
+ elapsed = (time.perf_counter() - started) * 1000
+ if track_session:
+ store.operation(repo, session_id, operation, elapsed, False, error=str(exc))
+ telemetry.record(
+ "search",
+ repo=repo,
+ session_id=session_id,
+ trigger=operation,
+ success=False,
+ duration_ms=round(elapsed, 2),
+ top_k=result_limit,
+ has_category=bool(category),
+ error_kind=telemetry.error_kind(exc),
+ )
+ return MemorySearchResult(False, 0, 0, [])
+
+
+def format_context(
+ memories: list[dict[str, Any]],
+ heading: str = "Relevant repository memories:",
+) -> str:
+ if not memories:
+ return ""
+ limit = min(
+ max(
+ _int_option(
+ "max_context_chars",
+ "MEM0_CODE_MAX_CONTEXT_CHARS",
+ DEFAULT_MAX_CONTEXT_CHARS,
+ ),
+ 1000,
+ ),
+ 10000,
+ )
+ lines = [heading] if heading else []
+ for memory in memories:
+ text = re.sub(
+ r"\s+",
+ " ",
+ redact(memory.get("memory") or memory.get("text") or ""),
+ )
+ text = text.strip()
+ if not text:
+ continue
+ branch = str((memory.get("metadata") or {}).get("branch") or "").strip()
+ branch_label = (
+ f" [learnt on branch {branch}]"
+ if branch.casefold() not in {"", "main", "master", "unknown", "detached"}
+ else ""
+ )
+ number = len(lines) if heading else len(lines) + 1
+ entry = f"{number}. {text}{branch_label}"
+ candidate = "\n".join([*lines, entry])
+ if len(candidate) <= limit:
+ lines.append(entry)
+ continue
+ if not lines or (heading and len(lines) == 1):
+ prefix = f"{number}. "
+ suffix = f"โฆ{branch_label}"
+ available = (
+ limit
+ - len("\n".join(lines))
+ - (1 if lines else 0)
+ - len(prefix)
+ - len(suffix)
+ )
+ if available > 0:
+ lines.append(prefix + text[:available].rstrip() + suffix)
+ break
+ minimum_lines = 2 if heading else 1
+ return "\n".join(lines) if len(lines) >= minimum_lines else ""
+
+
+def format_search_result(result: MemorySearchResult) -> str:
+ """Return only the text the coding agent needs from an explicit memory search."""
+ if not result.succeeded:
+ return "Memory search failed."
+ if result.memories:
+ rendered = format_context(result.memories, heading="")
+ if rendered:
+ return rendered
+ return "No matching memories found."
+
+
+def combine_context(*contexts: str) -> str:
+ """Combine memory sources under one hard budget without repeated lines."""
+ seen: set[str] = set()
+ lines: list[str] = []
+ for context in contexts:
+ for line in str(context or "").splitlines():
+ normalized = re.sub(r"\s+", " ", line).strip().casefold()
+ if not normalized or normalized in seen:
+ continue
+ seen.add(normalized)
+ lines.append(line.rstrip())
+ limit = min(
+ max(
+ _int_option(
+ "max_context_chars",
+ "MEM0_CODE_MAX_CONTEXT_CHARS",
+ DEFAULT_MAX_CONTEXT_CHARS,
+ ),
+ 1000,
+ ),
+ 10000,
+ )
+ return bounded("\n".join(lines), limit) if lines else ""
+
+
+def _scoped_memory_ids(
+ api_url: str, key: str, user: str, repo: RepoContext, include_project: bool
+) -> list[str]:
+ """List this user's memory ids for this repository, plus the shared project memory when asked."""
+ ids: list[str] = []
+ seen: set[str] = set()
+ prefix = repo.app_id
+ _collect_memory_ids(
+ api_url, key, {"user_id": user}, ids, seen,
+ app_id_prefix=prefix,
+ )
+ if include_project:
+ for project_id in _shared_project_ids(repo):
+ _collect_memory_ids(
+ api_url, key, {"agent_id": project_id}, ids, seen,
+ app_id_prefix=prefix,
+ )
+ return ids
+
+
+def _collect_memory_ids(
+ api_url: str,
+ key: str,
+ filters: dict[str, Any],
+ ids: list[str],
+ seen: set[str],
+ *,
+ app_id_prefix: str = "",
+) -> None:
+ """Page through one list filter; the list endpoint returns nothing for an OR whose user branch has no memories."""
+ payload = {"filters": filters}
+ for page in range(1, FORGET_MAX_PAGES + 1):
+ parsed, _, _ = _request_json(
+ f"{api_url}/v2/memories/?page={page}&page_size={FORGET_PAGE_SIZE}",
+ key,
+ payload,
+ 15,
+ )
+ items = parsed.get("results") if isinstance(parsed, dict) else parsed
+ if not isinstance(items, list) or not items:
+ break
+ for item in items:
+ if not isinstance(item, dict):
+ continue
+ memory_id = str(item.get("id", ""))
+ if not memory_id or memory_id in seen:
+ continue
+ if app_id_prefix:
+ item_app_id = str(item.get("app_id") or "")
+ if item_app_id != app_id_prefix and not item_app_id.startswith(app_id_prefix + "/"):
+ continue
+ seen.add(memory_id)
+ ids.append(memory_id)
+ if len(items) < FORGET_PAGE_SIZE:
+ break
+
+
+def _delete_memory(api_url: str, key: str, memory_id: str) -> bool:
+ request = urllib.request.Request(
+ f"{api_url}/v1/memories/{urllib.parse.quote(memory_id)}/",
+ headers=platform_headers(key),
+ method="DELETE",
+ )
+ try:
+ with urllib.request.urlopen(request, timeout=15):
+ return True
+ except Exception:
+ return False
+
+
+def forget_remote_repo(
+ repo: RepoContext, *, include_project_memory: bool = False
+) -> dict[str, Any]:
+ """Delete this user's memories for this repository; project memory is shared, so only on request."""
+ key = api_key()
+ if not key:
+ telemetry.record("forget", repo=repo, success=False, error_kind="no-api-key")
+ return {"status": "error", "error": "Mem0 API key is not configured"}
+ user = _scope_value(user_id())
+ if not user or not _scope_value(repo.app_id) or not _scope_value(repo.project_id):
+ telemetry.record("forget", repo=repo, success=False, error_kind="unscoped")
+ return {
+ "status": "error",
+ "error": "Refusing to forget: the user or repository scope is a wildcard",
+ }
+ api_url = os.environ.get("MEM0_API_URL", DEFAULT_API_URL).rstrip("/")
+ try:
+ memory_ids = _scoped_memory_ids(api_url, key, user, repo, include_project_memory)
+ except Exception as exc:
+ telemetry.record(
+ "forget", repo=repo, success=False, error_kind=telemetry.error_kind(exc)
+ )
+ return {"status": "error", "error": bounded(str(exc), 1000)}
+ deleted = sum(_delete_memory(api_url, key, memory_id) for memory_id in memory_ids)
+ failed = len(memory_ids) - deleted
+ telemetry.record("forget", repo=repo, success=not failed, item_count=deleted)
+ if failed:
+ return {
+ "status": "partial",
+ "deleted": deleted,
+ "failed": failed,
+ "error": f"{failed} of {len(memory_ids)} memories could not be deleted",
+ }
+ return {"status": "deleted", "deleted": deleted}
+
+
+def _doctor_mem0_authentication(repo: RepoContext) -> dict[str, Any]:
+ """Verify the configured key with one read-only, repository-scoped search."""
+ key = api_key()
+ if not key:
+ return {"ok": False, "detail": "API key missing"}
+ payload = {
+ "query": "Mem0 authentication check",
+ "filters": {
+ "AND": [
+ {"user_id": user_id()},
+ {"app_id": repo.app_id},
+ ]
+ },
+ "top_k": 1,
+ "threshold": 1.0,
+ "rerank": False,
+ }
+ url = os.environ.get("MEM0_API_URL", DEFAULT_API_URL).rstrip("/")
+ started = time.perf_counter()
+ try:
+ _request_json(f"{url}/v3/memories/search/", key, payload, 5)
+ except Exception as exc:
+ return {"ok": False, "detail": bounded(str(exc), 300)}
+ elapsed = (time.perf_counter() - started) * 1000
+ return {"ok": True, "detail": f"connected ({elapsed:.0f} ms)"}
+
+
+def _doctor_user_id() -> dict[str, Any]:
+ """Flag a configured user ID the plugin refuses, since the silent fallback surprises people."""
+ configured = _plugin_option("user_id", "MEM0_CODE_USER_ID") or os.environ.get(
+ "MEM0_USER_ID", ""
+ )
+ if configured and not _scope_value(configured):
+ return {
+ "ok": False,
+ "detail": f"configured user_id {configured!r} is a wildcard; using {user_id()!r}",
+ }
+ return {"ok": True, "detail": user_id()}
+
+
+def doctor(cwd: str | None = None) -> dict[str, Any]:
+ repo = resolve_repo(cwd)
+ directory = data_dir()
+ directory.mkdir(parents=True, exist_ok=True)
+ checks: dict[str, dict[str, Any]] = {
+ "python": {
+ "ok": tuple(sys.version_info[:2]) >= (3, 10),
+ "detail": f"{sys.version_info.major}.{sys.version_info.minor}",
+ },
+ "data_directory": {
+ "ok": os.access(directory, os.W_OK),
+ "detail": str(directory),
+ },
+ "mem0_api_key": {
+ "ok": bool(api_key()),
+ "detail": "configured" if api_key() else "missing",
+ },
+ "repository": {
+ "ok": bool(repo.identity),
+ "detail": repo.identity,
+ },
+ "user_id": _doctor_user_id(),
+ "mem0_authentication": _doctor_mem0_authentication(repo),
+ }
+ return {
+ "ok": all(bool(value["ok"]) for value in checks.values()),
+ "plugin_version": PLUGIN_VERSION,
+ "repo_id": repo.identity,
+ "app_id": repo.app_id,
+ "user_id": user_id(),
+ "checks": checks,
+ }
diff --git a/integrations/agent-plugin-core/python/telemetry.py b/integrations/agent-plugin-core/python/telemetry.py
new file mode 100644
index 000000000..c1fc0084c
--- /dev/null
+++ b/integrations/agent-plugin-core/python/telemetry.py
@@ -0,0 +1,1013 @@
+#!/usr/bin/env python3
+"""Usage telemetry for Mem0 agent plugins.
+
+Events are linked to your Mem0 account email when an API key is configured, and
+to a random per-machine id otherwise. Not anonymous โ the Python SDK and CLI
+attribute the same way.
+
+Hooks run on a 3-6 second budget and fire on every tool call, so recording never
+touches the network: `record` appends one JSON line to a local spool and returns.
+A detached `python3 telemetry.py` drains the spool in one batched PostHog request,
+started once per session and again from the flush worker that is already detached.
+
+Pure stdlib, matching the rest of the plugin. Opt out with MEM0_TELEMETRY=false.
+
+Never sends prompts, memory text, queries, file paths, repository names, or API
+keys: only event names, durations, counts, coarse outcomes, and repo/session
+identifiers hashed with a random per-install salt.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import os
+import platform
+import subprocess
+import sys
+import time
+import urllib.error
+import urllib.request
+import uuid
+from pathlib import Path
+from typing import Any
+
+import memory_core
+
+# Seeded from the per-host module the build generates into core/. Two processes
+# in this pipeline never call init() โ mcp_server.py, and the detached
+# `python3 telemetry.py` sender that spawn_flush() starts โ so a module default
+# was what every one of their events got labelled with.
+try: # pragma: no cover - absent only in the un-built shared source tree
+ from _harness_id import HARNESS_ID as _DEFAULT_HARNESS
+ from _harness_id import PLATFORM_APPLICATION as _PLATFORM_APPLICATION
+ from _harness_id import PLATFORM_SOURCE as _PLATFORM_SOURCE
+ from _harness_id import SOURCE_TAG as _DEFAULT_SOURCE_TAG
+except ImportError:
+ _DEFAULT_HARNESS = "generic"
+ _DEFAULT_SOURCE_TAG = "MEM0_PLUGIN"
+ _PLATFORM_SOURCE = "MEM0_PLUGIN"
+ _PLATFORM_APPLICATION = ""
+
+_salt_cache: str = ""
+_harness: str = _DEFAULT_HARNESS
+_source_tag: str = _DEFAULT_SOURCE_TAG
+_PRIVATE_KEYS = {
+ "apikey",
+ "authorization",
+ "password",
+ "query",
+ "secret",
+ "prompt",
+ "token",
+ "text",
+ "memory",
+ "message",
+ "error",
+ "path",
+ "cwd",
+ "userid",
+ "agentid",
+ "runid",
+ "repoid",
+ "repositoryid",
+ "projectid",
+ "appid",
+ "filters",
+}
+
+
+def init(harness: str = "", source_tag: str = "") -> None:
+ """Override the generated identity. Optional โ core/_harness_id.py is the default.
+
+ The fallback shape matches memory_core.configure_harness's (``_PLUGIN``).
+ It used to be ``MEM0__PLUGIN`` here and ``_plugin`` there, which
+ meant one plugin could emit three different source values depending on which
+ process happened to send the batch.
+ """
+ global _harness, _source_tag
+ _harness = harness or _DEFAULT_HARNESS
+ _source_tag = source_tag or (
+ f"{_harness.upper().replace('-', '_')}_PLUGIN" if harness else _DEFAULT_SOURCE_TAG
+ )
+
+POSTHOG_API_KEY = "phc_hgJkUVJFYtmaJqrvf6CYN67TIQ8yhXAkWzUn9AMU4yX"
+POSTHOG_CAPTURE_URL = "https://us.i.posthog.com/i/v0/e/"
+POSTHOG_BATCH_URL = "https://us.i.posthog.com/batch/"
+EVENT_PREFIX = "code"
+SPOOL_LIMIT_BYTES = 256 * 1024
+BATCH_SIZE = 100
+SEND_TIMEOUT = 5
+CLAIM_STALE_SECONDS = 120
+CLAIM_EXPIRY_SECONDS = 7 * 24 * 60 * 60
+# A batch is only discarded once it has genuinely been retried this many times.
+MAX_CLAIM_ATTEMPTS = 3
+# Parked claims drained per run, after the live spool. Bounded so a long backlog
+# cannot turn one flush into an unbounded send loop.
+MAX_PARKED_PER_RUN = 3
+# Added to the wait before a released claim becomes reclaimable, per attempt
+# already spent. Releasing straight to "reclaimable now" let two senders burn the
+# whole budget within seconds of one another on a single momentary failure, and
+# discard a batch a retry a minute later would have delivered.
+RETRY_COOLDOWN_SECONDS = 60
+
+
+def is_enabled() -> bool:
+ """Whether telemetry is switched on for this process."""
+ return os.environ.get("MEM0_TELEMETRY", "true").strip().lower() not in {
+ "false",
+ "0",
+ "no",
+ "off",
+ }
+
+
+def _digest(value: str, length: int = 16) -> str:
+ """Unsalted digest. Only for values that are already secrets (API keys)."""
+ return hashlib.sha256(value.encode("utf-8")).hexdigest()[:length]
+
+
+def _salt_path() -> Path:
+ return memory_core.data_dir() / "telemetry-salt"
+
+
+def _install_salt() -> str:
+ """Random per-install salt, created once and memoized for the process.
+
+ Deliberately its own file, claimed with O_CREAT|O_EXCL, rather than a key in
+ the identity file. Three reasons, all of which produced wrong data when this
+ lived in the identity dict:
+
+ - Hooks are short-lived separate processes firing on every tool call, and
+ people run more than one agent window. A read-modify-write would let each
+ process mint its own salt, so one repository would hash several ways in the
+ window before a writer won.
+ - resolve_distinct_id holds a copy of the identity dict across a network call
+ to /v1/ping/, so whichever write landed second erased the other's key โ
+ losing either the salt (repo_hash changes mid-stream) or the email (a
+ second $identify, splitting the person).
+ - Touching the identity file from record() would create it, and is_first_run
+ keys off that file, so recording an event would silently suppress the
+ install event.
+
+ Published atomically, and there is deliberately no derived fallback. Creating
+ the file with O_CREAT|O_EXCL and then writing into it leaves a window where
+ the file exists and is empty, and a concurrent hook that reads it in that
+ window gets nothing. Falling back to a digest of the path would hand that
+ process a salt an attacker can compute, memoized for its whole run, which is
+ the privacy control this function exists to provide silently turning itself
+ off under load. The salt is written to a private temp file first and linked
+ into place, so the name either does not exist or already has the full value.
+
+ Returns "" when it genuinely cannot persist. Callers omit the hash entirely
+ rather than emit an unsalted one.
+ """
+ global _salt_cache
+ if _salt_cache:
+ return _salt_cache
+
+ path = _salt_path()
+ # Read before writing. Hooks are separate processes firing on every tool
+ # call, so all but the first find the salt already published; going straight
+ # to create-fsync-link-unlink meant every one of them paid an fsync to
+ # discover that, on a path whose whole promise is appending a line and
+ # returning.
+ try:
+ _salt_cache = path.read_text(encoding="utf-8").strip()
+ if _salt_cache:
+ return _salt_cache
+ except OSError:
+ pass
+
+ temporary = path.with_name(f"{path.name}.{os.getpid()}.tmp")
+ try:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ handle = os.open(temporary, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
+ with os.fdopen(handle, "w", encoding="utf-8") as stream:
+ stream.write(uuid.uuid4().hex)
+ stream.flush()
+ os.fsync(stream.fileno())
+ try:
+ # Atomic claim: fails if another process already published one.
+ # os.link rather than replace, which would clobber theirs.
+ os.link(temporary, path)
+ except FileExistsError:
+ pass
+ except OSError:
+ # No hardlinks here (some network mounts, some container volumes).
+ # Claim the name directly instead. That reopens the empty-file
+ # window, but the window is now benign: a reader that lands in it
+ # gets "" and omits the hash for that process rather than caching a
+ # guessable one. Losing the hashes on every run of an entire
+ # filesystem is the worse failure.
+ try:
+ fallback = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
+ with os.fdopen(fallback, "w", encoding="utf-8") as stream:
+ stream.write(temporary.read_text(encoding="utf-8"))
+ except OSError:
+ pass
+ except OSError:
+ pass
+ finally:
+ try:
+ temporary.unlink()
+ except OSError:
+ pass
+
+ try:
+ _salt_cache = path.read_text(encoding="utf-8").strip()
+ except OSError:
+ _salt_cache = ""
+ return _salt_cache
+
+
+def _scoped_digest(value: str, length: int = 16) -> str:
+ """Salted digest for values drawn from a guessable space.
+
+ repo.identity is a git remote URL, or ``local:`` when there is
+ no remote โ which normally contains the account username. Sixteen unsalted
+ hex characters over that input space is enumerable, so this is not a
+ privacy control without the salt. Salting per install keeps every
+ within-account join the analytics actually use and gives up only
+ cross-machine joins on the same repository, which nothing computes.
+
+ Returns "" when there is no salt, so record() omits the property. An
+ unsalted digest over this input space is close to plaintext, and emitting one
+ under a name that implies it is hashed is worse than sending nothing.
+ """
+ if not value:
+ return ""
+ salt = _install_salt()
+ if not salt:
+ return ""
+ return hashlib.sha256(f"{salt}:{value}".encode("utf-8")).hexdigest()[:length]
+
+
+def _safe_value(value: Any) -> Any:
+ if isinstance(value, str):
+ return memory_core.redact(value)
+ if isinstance(value, dict):
+ return {
+ key: _safe_value(item)
+ for key, item in value.items()
+ if "".join(character for character in str(key).lower() if character.isalnum())
+ not in _PRIVATE_KEYS
+ }
+ if isinstance(value, (list, tuple)):
+ return [_safe_value(item) for item in value]
+ if value is None or isinstance(value, (bool, int, float)):
+ return value
+ return memory_core.redact(value)
+
+
+def _spool_path() -> Path:
+ return memory_core.data_dir() / "telemetry.jsonl"
+
+
+def _identity_path() -> Path:
+ return memory_core.data_dir() / "telemetry-identity.json"
+
+
+def _read_identity() -> dict[str, str]:
+ try:
+ value = json.loads(_identity_path().read_text(encoding="utf-8"))
+ except (OSError, json.JSONDecodeError):
+ return {}
+ return value if isinstance(value, dict) else {}
+
+
+def _write_identity(identity: dict[str, str]) -> None:
+ path = _identity_path()
+ temporary = path.with_suffix(f".{os.getpid()}.tmp")
+ try:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ temporary.write_text(json.dumps(identity), encoding="utf-8")
+ temporary.replace(path)
+ except OSError:
+ try:
+ temporary.unlink()
+ except OSError:
+ pass
+
+
+def anonymous_id(identity: dict[str, str] | None = None) -> str:
+ """Per-machine anonymous identifier, created and persisted on first use."""
+ identity = _read_identity() if identity is None else identity
+ existing = identity.get("anonymous_id")
+ if existing:
+ return existing
+ created = f"code-anon-{uuid.uuid4().hex}"
+ identity["anonymous_id"] = created
+ _write_identity(identity)
+ return created
+
+
+def _rotate_anonymous_id(identity: dict[str, str]) -> str:
+ """Mint a fresh anonymous id because the account context is gone.
+
+ The previous id may already have been merged into a person profile by an
+ $identify, and that merge is permanent. Reusing it after a logout or a key
+ change attributes everything that follows to the account that just went
+ away, which is the same misattribution the key fingerprint exists to stop,
+ only arriving through the anonymous path instead.
+
+ `aliased` is cleared with it: the new id has never been merged, so it is
+ eligible to be aliased into whatever account comes next.
+ """
+ created = f"code-anon-{uuid.uuid4().hex}"
+ identity["anonymous_id"] = created
+ identity.pop("aliased", None)
+ _write_identity(identity)
+ return created
+
+
+def _install_state_path() -> Path:
+ return memory_core.data_dir() / "install-state.json"
+
+
+def is_first_run() -> bool:
+ """Whether install has never been recorded on this machine.
+
+ Deliberately NOT the identity file. That file is only written by a
+ successful flush, so an offline or firewalled user recorded code.install on
+ every single session, forever โ and every 0.2.x user recorded one on their
+ first 0.3.x session because 0.2.x never wrote it at all.
+ """
+ return not _install_state_path().exists()
+
+
+def data_dir_was_empty() -> bool:
+ """Whether the data directory is untouched. Call BEFORE anything writes to it.
+
+ hook_runner reaches claim_install() only after cache_plugin_api_key() has
+ written `api-key` and EvidenceStore() has created `evidence.sqlite3`, so
+ asking at claim time always saw content and every fresh install reported an
+ upgrade. The caller snapshots this at the top of the run instead.
+ """
+ return not _data_dir_has_content()
+
+
+def claim_install(was_empty: bool | None = None) -> str | None:
+ """Claim the one install/upgrade record for this machine, atomically.
+
+ Returns the event to record ("install" or "upgrade"), or None if another
+ session already claimed it. O_CREAT|O_EXCL so two sessions starting together
+ cannot both win.
+
+ `was_empty` must come from data_dir_was_empty() called before this process
+ wrote anything. Omitting it falls back to checking now, which is only
+ correct for a caller that has touched nothing.
+ """
+ if not is_enabled():
+ # Never consume the one-shot claim while the user is opted out, or they
+ # would silently lose their install event if they later opt in.
+ return None
+
+ path = _install_state_path()
+ upgrading = not (data_dir_was_empty() if was_empty is None else was_empty)
+ try:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ handle = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
+ except FileExistsError:
+ return None
+ except OSError:
+ return None
+ try:
+ with os.fdopen(handle, "w", encoding="utf-8") as stream:
+ json.dump(
+ {
+ "plugin_version": memory_core.PLUGIN_VERSION,
+ "installed_at": memory_core.utc_now(),
+ "upgraded": upgrading,
+ },
+ stream,
+ )
+ # Durable before this returns. The O_EXCL open is what makes the
+ # claim exclusive, so it cannot be replaced by a temp-and-rename
+ # without losing that, which leaves the content as the thing to make
+ # safe. A kill between the open and this fsync used to leave a marker
+ # that exists but parses to nothing: is_first_run reads it as claimed
+ # and claim_version_change cannot read a version out of it.
+ stream.flush()
+ os.fsync(stream.fileno())
+ except OSError:
+ pass
+ return "upgrade" if upgrading else "install"
+
+
+def _data_dir_has_content() -> bool:
+ """Whether anything predates this session in the plugin data directory."""
+ try:
+ for entry in memory_core.data_dir().iterdir():
+ if entry.name != "install-state.json":
+ return True
+ except OSError:
+ pass
+ return False
+
+
+def _repair_install_state(path: Path) -> None:
+ """Rewrite an unparseable marker so version tracking can resume."""
+ try:
+ temporary = path.with_suffix(f".{os.getpid()}.tmp")
+ temporary.write_text(
+ json.dumps({"plugin_version": memory_core.PLUGIN_VERSION, "repaired_at": memory_core.utc_now()}),
+ encoding="utf-8",
+ )
+ temporary.replace(path)
+ except OSError:
+ pass
+
+
+def claim_version_change() -> str | None:
+ """Return the previously recorded version if it differs, updating the marker.
+
+ Only meaningful once the marker exists โ the first transition into 0.3.x has
+ no recorded predecessor and reports "pre-0.3" instead. Claiming by rewriting
+ the marker means the next session sees no change and records nothing.
+ """
+ path = _install_state_path()
+ try:
+ state = json.loads(path.read_text(encoding="utf-8"))
+ except OSError:
+ return None
+ except json.JSONDecodeError:
+ # A crash between O_EXCL and the write leaves an empty marker. Left
+ # alone it disables every future upgrade event on this machine, because
+ # claim_install sees the file and this function cannot parse it.
+ state = None
+ if not isinstance(state, dict):
+ _repair_install_state(path)
+ return None
+ previous = str(state.get("plugin_version") or "")
+ if not previous or previous == memory_core.PLUGIN_VERSION:
+ return None
+ # Claim the transition with an exclusive sentinel before rewriting the
+ # marker. A plain read-modify-write let every concurrently starting session
+ # observe the old version and each record its own upgrade โ and the first
+ # session after a version bump is exactly when several agent windows restart
+ # together.
+ sentinel = path.with_name(f"upgraded-{memory_core.PLUGIN_VERSION}")
+ try:
+ os.close(os.open(sentinel, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600))
+ except FileExistsError:
+ return None
+ except OSError:
+ return None
+
+ state["plugin_version"] = memory_core.PLUGIN_VERSION
+ state["upgraded_at"] = memory_core.utc_now()
+ temporary = path.with_suffix(f".{os.getpid()}.tmp")
+ try:
+ temporary.write_text(json.dumps(state), encoding="utf-8")
+ temporary.replace(path)
+ except OSError:
+ # Release the claim. The marker still records the old version, so
+ # without this the sentinel makes claim_version_change return early on
+ # every later run and this version's upgrade is never recorded again.
+ for leftover in (sentinel, temporary):
+ try:
+ leftover.unlink()
+ except OSError:
+ pass
+ return None
+ return previous
+
+
+def record(
+ event: str,
+ *,
+ repo: Any = None,
+ session_id: str | None = None,
+ **properties: Any,
+) -> None:
+ """Append one event to the local spool. Never blocks and never raises."""
+ if not is_enabled():
+ return
+ try:
+ spool = _spool_path()
+ try:
+ if spool.stat().st_size > SPOOL_LIMIT_BYTES:
+ return
+ except OSError:
+ pass
+ properties = _safe_value(properties)
+ # Stamped in the RECORDING process, beside harness. `source` used to be
+ # read in the sending process from a module global, so whichever process
+ # drained the spool named every event in it. flush() spreads per-event
+ # properties last, so this now wins over any sender's default.
+ properties.update(
+ harness=_harness,
+ source=_source_tag,
+ plugin_version=memory_core.PLUGIN_VERSION,
+ os=sys.platform,
+ python_version=platform.python_version(),
+ )
+ # Assigned only when the digest is real. _scoped_digest returns "" when
+ # the salt could not be persisted, and an empty property is worse than an
+ # absent one: it survives the None filter below and reads as a value.
+ if repo is not None:
+ repo_hash = _scoped_digest(getattr(repo, "identity", ""))
+ if repo_hash:
+ properties["repo_hash"] = repo_hash
+ if session_id:
+ session_hash = _scoped_digest(session_id)
+ if session_hash:
+ properties["session_hash"] = session_hash
+ line = json.dumps(
+ {
+ "event": f"{EVENT_PREFIX}.{event}",
+ "uuid": str(uuid.uuid4()),
+ "timestamp": memory_core.utc_now(),
+ "properties": {
+ key: value for key, value in properties.items() if value is not None
+ },
+ },
+ separators=(",", ":"),
+ default=str,
+ )
+ spool.parent.mkdir(parents=True, exist_ok=True)
+ with spool.open("a", encoding="utf-8") as handle:
+ handle.write(line + "\n")
+ except Exception:
+ pass
+
+
+def error_kind(exc: BaseException | str) -> str:
+ """Coarse, content-free label for a failure, safe to send."""
+ text = exc if isinstance(exc, str) else f"{type(exc).__name__}: {exc}"
+ lowered = text.lower()
+ if "timed out" in lowered or "timeout" in lowered:
+ return "timeout"
+ if "401" in lowered or "403" in lowered or "unauthor" in lowered or "forbidden" in lowered:
+ return "auth"
+ if "429" in lowered or "rate limit" in lowered:
+ return "rate-limited"
+ if any(code in lowered for code in ("500", "502", "503", "504")):
+ return "server-error"
+ if "400" in lowered or "422" in lowered:
+ return "bad-request"
+ if isinstance(exc, str):
+ return "other"
+ if isinstance(exc, urllib.error.URLError):
+ return "network"
+ return type(exc).__name__
+
+
+def spawn_flush() -> bool:
+ """Start the detached sender that drains the spool."""
+ if not is_enabled():
+ return False
+ try:
+ if not _spool_path().exists() and not any(
+ memory_core.data_dir().glob("telemetry-*.sending")
+ ):
+ return False
+ subprocess.Popen(
+ [sys.executable, str(Path(__file__).resolve())],
+ stdin=subprocess.DEVNULL,
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL,
+ close_fds=True,
+ **memory_core.detached_process_kwargs(),
+ )
+ return True
+ except Exception:
+ return False
+
+
+def _claim_name(attempt: int = 0) -> str:
+ """Claim filename. The attempt count rides in the name so the 7-day expiry
+ only ever discards a batch that was actually retried and failed."""
+ return f"telemetry-{os.getpid()}-{uuid.uuid4().hex[:8]}-a{attempt}.sending"
+
+
+def _claim_attempt(claim: Path) -> int:
+ """Attempts recorded in a claim filename; 0 for the pre-attempt-count shape.
+
+ Anchored on field position, not on a leading "a": the legacy shape is
+ ``telemetry--.sending`` and a hex id such as ``a1234567`` would
+ otherwise parse as attempt 1234567 and be discarded unsent on the first
+ flush after an upgrade.
+ """
+ stem = claim.name[: -len(".sending")] if claim.name.endswith(".sending") else claim.name
+ parts = stem.split("-")
+ if len(parts) != 4:
+ return 0
+ tail = parts[3]
+ if tail.startswith("a") and tail[1:].isdigit():
+ return int(tail[1:])
+ return 0
+
+
+def _touch(path: Path) -> None:
+ """Refresh mtime so a claim's age measures time since it was claimed.
+
+ ``Path.replace`` is ``os.rename``, which preserves mtime โ so a claim created
+ after a quiet minute inherited the spool's last-write time and looked
+ abandoned the instant it was made. A second sender would then take it over
+ while the first was still posting, and both would deliver the batch.
+ """
+ try:
+ os.utime(path, None)
+ except OSError:
+ pass
+
+
+def _claim_spool() -> Path | None:
+ """Rename the spool aside so exactly one sender owns each batch."""
+ directory = memory_core.data_dir()
+ claim = directory / _claim_name()
+ spool = _spool_path()
+ try:
+ spool.replace(claim)
+ _touch(claim)
+ return claim
+ except OSError:
+ pass
+ return _claim_parked(directory)
+
+
+def _sweep_debris(directory: Path) -> None:
+ """Remove files nothing else will ever pick up again.
+
+ *.partial is a temp file orphaned by a crash between write and rename.
+ *.corrupt is a batch quarantined for undecodable content. No glob in this
+ module matches either, so without this they accumulate on disk for the life
+ of the install.
+
+ Quarantined batches are kept far longer than debris: they are the only
+ evidence left of events that could not be delivered, and someone diagnosing
+ a report of missing telemetry has to be able to find one.
+ """
+ now = time.time()
+ for debris in directory.glob("telemetry-*.partial"):
+ try:
+ if now - debris.stat().st_mtime > CLAIM_STALE_SECONDS:
+ debris.unlink()
+ except OSError:
+ continue
+ for quarantined in directory.glob("telemetry-*.corrupt"):
+ try:
+ if now - quarantined.stat().st_mtime > CLAIM_EXPIRY_SECONDS:
+ quarantined.unlink()
+ except OSError:
+ continue
+ # The same reasoning covers *.tmp. _write_identity and _install_salt both
+ # create one and unlink it in a finally, which a SIGKILL skips, and no glob
+ # in this module matches the leftovers either.
+ for temporary in directory.glob("telemetry-*.tmp"):
+ try:
+ if now - temporary.stat().st_mtime > CLAIM_STALE_SECONDS:
+ temporary.unlink()
+ except OSError:
+ continue
+
+
+def _claim_parked(directory: Path) -> Path | None:
+ """Take the oldest abandoned claim, if any lease has actually expired.
+
+ Kept separate from the live spool so flush() can drain both in one run.
+ Previously parked batches were only reachable when no spool existed at all,
+ and because sessions keep recording there usually was one โ so a batch
+ parked by a failed send waited until the 7-day expiry deleted it unsent,
+ even though its own presence is what started the sender.
+ """
+ now = time.time()
+ for orphan in sorted(directory.glob("telemetry-*.sending"), key=_safe_mtime):
+ try:
+ age = now - orphan.stat().st_mtime
+ except OSError:
+ continue
+ if age < CLAIM_STALE_SECONDS:
+ # Someone else holds a live lease on it. This check has to come
+ # first. Claiming a file bumps its attempt count and refreshes its
+ # mtime, so a sender that has just taken the final attempt looks
+ # exhausted to everyone else while it is actively draining. Judging
+ # exhaustion before liveness let a second sender unlink a batch out
+ # from under its owner, losing every event in it.
+ continue
+ # Attempts, not age. Every re-claim touches the mtime and every release
+ # backdates it by a fixed amount, so age is pinned near the stale
+ # threshold and never reaches the expiry. Age stays only as a backstop
+ # for files that never carried an attempt marker.
+ if _claim_attempt(orphan) >= MAX_CLAIM_ATTEMPTS or age > CLAIM_EXPIRY_SECONDS:
+ try:
+ orphan.unlink()
+ except OSError:
+ pass
+ continue
+ claim = orphan.parent / _claim_name(_claim_attempt(orphan) + 1)
+ try:
+ orphan.replace(claim)
+ _touch(claim)
+ return claim
+ except OSError:
+ continue
+ return None
+
+
+def _safe_mtime(path: Path) -> float:
+ try:
+ return path.stat().st_mtime
+ except OSError:
+ return 0.0
+
+
+def _rewrite_claim(claim: Path, remaining: list[dict[str, Any]]) -> bool:
+ """Persist the unsent remainder, atomically, and refresh the lease.
+
+ Called after every successful batch. Two jobs: a retry resumes where the
+ send stopped instead of re-posting from the top, and the rewrite doubles as
+ the lease heartbeat, so a slow sender does not have its claim stolen
+ mid-flight. Interval is one batch, well inside CLAIM_STALE_SECONDS.
+ """
+ if not remaining:
+ try:
+ claim.unlink()
+ except OSError:
+ pass
+ return True
+ temporary = claim.with_suffix(f".{os.getpid()}.partial")
+ try:
+ payload = "".join(json.dumps(event, separators=(",", ":"), default=str) + "\n" for event in remaining)
+ # fsync before the rename: without it the rename can land while the
+ # bytes have not, and the claim comes back empty or truncated after a
+ # crash. _drain then reads zero events and unlinks it.
+ with open(temporary, "w", encoding="utf-8") as handle:
+ handle.write(payload)
+ handle.flush()
+ os.fsync(handle.fileno())
+ temporary.replace(claim)
+ _touch(claim)
+ return True
+ except OSError:
+ try:
+ temporary.unlink()
+ except OSError:
+ pass
+ return False
+
+
+def _release_claim(claim: Path, remaining: list[dict[str, Any]]) -> None:
+ """Persist the remainder and drop the lease, because this sender has given up.
+
+ Distinct from the per-batch heartbeat: heartbeating on the way out would
+ make an abandoned batch look actively owned for a further
+ CLAIM_STALE_SECONDS, delaying the retry for no reason. Ageing it past the
+ threshold lets the next flush pick it up immediately, while the attempt
+ count in the filename still bounds how many times that can happen.
+ """
+ if not _rewrite_claim(claim, remaining):
+ return
+ try:
+ # Backdate past the stale threshold so the next flush can pick it up,
+ # minus a cooldown that grows with the attempts already spent. Clamped so
+ # the mtime never lands in the future, which would read as a live lease.
+ cooldown = min(_claim_attempt(claim) * RETRY_COOLDOWN_SECONDS, CLAIM_STALE_SECONDS)
+ released = time.time() - CLAIM_STALE_SECONDS - 1 + cooldown
+ os.utime(claim, (released, released))
+ except OSError:
+ pass
+
+
+def _resolve_email(key: str) -> str:
+ """Trade the API key for the account email so events join other Mem0 surfaces."""
+ url = os.environ.get("MEM0_API_URL", memory_core.DEFAULT_API_URL).rstrip("/") + "/v1/ping/"
+ request = urllib.request.Request(
+ url, headers={"Authorization": f"Token {key}", "Content-Type": "application/json"}
+ )
+ try:
+ with urllib.request.urlopen(request, timeout=SEND_TIMEOUT) as response:
+ payload = json.loads(response.read().decode("utf-8"))
+ except Exception:
+ return ""
+ email = payload.get("user_email") if isinstance(payload, dict) else ""
+ return email if isinstance(email, str) else ""
+
+
+def _post(payload: dict[str, Any], url: str) -> bool:
+ request = urllib.request.Request(
+ url,
+ data=json.dumps(payload, default=str).encode("utf-8"),
+ headers={"Content-Type": "application/json"},
+ )
+ try:
+ with urllib.request.urlopen(request, timeout=SEND_TIMEOUT):
+ return True
+ except Exception:
+ return False
+
+
+def resolve_distinct_id() -> tuple[str, str]:
+ """Return the PostHog distinct id and the anonymous id it replaced, if any.
+
+ The second value becomes a PostHog $identify alias. It is ONLY ever an
+ anonymous id: aliasing one account email to another merges two real person
+ profiles and cannot be undone, so a key that now belongs to a different
+ account re-resolves with no alias.
+ """
+ identity = _read_identity()
+ key = memory_core.api_key()
+ fingerprint = _digest(key) if key else ""
+ email = identity.get("email", "")
+
+ if email and fingerprint:
+ recorded = identity.get("key_fingerprint", "")
+ if recorded == fingerprint:
+ return email, ""
+ if not recorded:
+ # Rows written before fingerprints existed. Verify rather than
+ # adopt: a key changed before the upgrade would otherwise bind the
+ # new key to the previous account's email, permanently, and the
+ # fingerprint would then agree with itself forever after.
+ verified = _resolve_email(key)
+ if not verified:
+ # Offline, firewalled, or the API is down. Keep the previous
+ # behaviour and retry on the next flush rather than dropping a
+ # real account attribution. Safe because the same network that
+ # failed /v1/ping/ is about to fail the PostHog POST, so nothing
+ # is delivered under the unverified identity in the meantime.
+ return email, ""
+ identity["email"] = verified
+ identity["key_fingerprint"] = fingerprint
+ _write_identity(identity)
+ return verified, ""
+
+ if not key:
+ # No key to verify the account with; do not keep attributing to it.
+ if email:
+ identity.pop("email", None)
+ identity.pop("key_fingerprint", None)
+ return _rotate_anonymous_id(identity), ""
+ return anonymous_id(identity), ""
+
+ resolved = _resolve_email(key)
+ if not resolved:
+ # The key changed and will not resolve (revoked, offline, API down).
+ # Reaching here with an email means the recorded fingerprint disagreed,
+ # so the key really did change. Drop the account and rotate: the stored
+ # anonymous id may already be merged into that account's person, and
+ # reusing it would keep the events on the profile we are trying to
+ # leave.
+ if email:
+ identity.pop("email", None)
+ identity.pop("key_fingerprint", None)
+ return _rotate_anonymous_id(identity), ""
+ return anonymous_id(identity), ""
+
+ # Alias only when going anonymous -> email for the first time. Once an anon
+ # id has been merged into an account it must never be offered again: an
+ # alias naming an already-identified id is what could link two real people.
+ previous = "" if (email or identity.get("aliased")) else identity.get("anonymous_id", "")
+ if previous:
+ identity["aliased"] = True
+ identity["email"] = resolved
+ identity["key_fingerprint"] = fingerprint
+ _write_identity(identity)
+ return resolved, previous
+
+
+def flush() -> int:
+ """Drain the live spool, then any parked claims, and return events sent."""
+ if not is_enabled():
+ return 0
+ sent, delivered = _drain(_claim_spool())
+ if not delivered:
+ # The network is failing. Retrying other batches now would only burn
+ # their attempt budget against the same broken connection.
+ return sent
+
+ # Parked batches used to starve behind the live spool indefinitely. Bounded
+ # per run so a long backlog cannot turn one flush into an unbounded loop.
+ directory = memory_core.data_dir()
+ _sweep_debris(directory)
+ for _ in range(MAX_PARKED_PER_RUN):
+ parked = _claim_parked(directory)
+ if parked is None:
+ break
+ count, delivered = _drain(parked)
+ sent += count
+ if not delivered:
+ break
+ return sent
+
+
+def _drain(claim: Path | None) -> tuple[int, bool]:
+ """Post one claimed batch file, recording progress after every batch.
+
+ Returns (events sent, whether everything was delivered).
+ """
+ if claim is None:
+ return 0, True
+ try:
+ lines = claim.read_text(encoding="utf-8").splitlines()
+ except ValueError:
+ # UnicodeDecodeError from a torn write: the content is unrecoverable, so
+ # quarantine rather than retry. flush() runs from a bare `finally:` in
+ # flush_worker, so raising here also skips the handoff cleanup, and an
+ # undecodable file would otherwise be re-read on every flush forever.
+ # Reported as delivered because there is nothing left to deliver and the
+ # rest of the run should continue.
+ try:
+ claim.replace(claim.with_suffix(".corrupt"))
+ except OSError:
+ try:
+ claim.unlink()
+ except OSError:
+ pass
+ return 0, True
+ except OSError:
+ # Could not read it, which is not the same as having nothing to send.
+ # The file is left exactly where it is: a vanished or briefly unreadable
+ # claim is retryable, and quarantining it here would discard events over
+ # a transient filesystem error. Reported as undelivered so the run stops
+ # instead of counting a batch nothing was posted from as delivered.
+ return 0, False
+ events = []
+ for line in lines:
+ try:
+ value = json.loads(line)
+ except json.JSONDecodeError:
+ continue
+ if isinstance(value, dict) and value.get("event"):
+ events.append(value)
+ if not events:
+ # Only delete when the file really is empty. A non-empty file that
+ # parses to nothing is a torn write, and its contents are the unsent
+ # remainder โ deleting it is the data loss this PR exists to prevent.
+ try:
+ empty = claim.stat().st_size == 0
+ except OSError:
+ empty = True
+ try:
+ claim.replace(claim.with_suffix(".corrupt")) if not empty else claim.unlink()
+ except OSError:
+ pass
+ return 0, True
+
+ distinct_id, aliased_anonymous_id = resolve_distinct_id()
+ if aliased_anonymous_id:
+ _post(
+ {
+ "api_key": POSTHOG_API_KEY,
+ "event": "$identify",
+ "distinct_id": distinct_id,
+ "properties": {
+ "$anon_distinct_id": aliased_anonymous_id,
+ "$lib": "posthog-python",
+ },
+ },
+ POSTHOG_CAPTURE_URL,
+ )
+
+ sent = 0
+ for start in range(0, len(events), BATCH_SIZE):
+ chunk = events[start : start + BATCH_SIZE]
+ batch = [
+ {
+ "event": event["event"],
+ "distinct_id": distinct_id,
+ # Carried through from record() so a resend can be collapsed.
+ "uuid": event.get("uuid"),
+ "timestamp": event.get("timestamp"),
+ "properties": {
+ # Fallback only: events recorded by a build before source
+ # moved into record() have none of their own.
+ "source": _source_tag,
+ "language": "python",
+ "$process_person_profile": False,
+ "$lib": "posthog-python",
+ **(event.get("properties") or {}),
+ },
+ }
+ for event in chunk
+ ]
+ if not _post({"api_key": POSTHOG_API_KEY, "batch": batch}, POSTHOG_BATCH_URL):
+ # Keep only what has not been delivered, and release the lease.
+ # Previously the whole file was kept and the retry re-posted every
+ # batch, including the ones that had already arrived.
+ _release_claim(claim, events[start:])
+ return sent, False
+ sent += len(chunk)
+ # Record progress and refresh the lease after each successful batch, so
+ # a crash repeats at most one batch instead of the entire file. If the
+ # rewrite fails the claim still holds delivered events, so stop rather
+ # than carry on as though progress were recorded โ continuing is how the
+ # duplicate delivery this PR fixes would come back.
+ if not _rewrite_claim(claim, events[start + len(chunk) :]):
+ _release_claim(claim, events[start + len(chunk) :])
+ return sent, False
+ return sent, True
+
+
+def main() -> int:
+ flush()
+ return 0
+
+
+if __name__ == "__main__":
+ try:
+ raise SystemExit(main())
+ except Exception:
+ raise SystemExit(0)
diff --git a/integrations/agent-plugin-core/requirements-dev.txt b/integrations/agent-plugin-core/requirements-dev.txt
new file mode 100644
index 000000000..1fbe37b8d
--- /dev/null
+++ b/integrations/agent-plugin-core/requirements-dev.txt
@@ -0,0 +1,3 @@
+jsonschema>=4.23,<5
+pytest>=8,<10
+skills-ref==0.1.1
diff --git a/integrations/agent-plugin-core/skills/forget/SKILL.md.tmpl b/integrations/agent-plugin-core/skills/forget/SKILL.md.tmpl
new file mode 100644
index 000000000..1b16a6c79
--- /dev/null
+++ b/integrations/agent-plugin-core/skills/forget/SKILL.md.tmpl
@@ -0,0 +1,26 @@
+---
+name: forget
+description: Delete the Mem0 memories stored for this repository and this user. Use when the user asks to forget, clear, wipe, or delete memories.
+disable-model-invocation: true
+---
+
+# Forget this repository's memories
+
+This permanently deletes remote memories. Before running anything, tell the
+user exactly what will be deleted: their own memories for this repository
+only. The repository's project memory is shared by everyone who works in it,
+so it stays unless the user explicitly asks to delete that too.
+
+After the user confirms, run:
+
+```bash
+python3 "{{PLUGIN_ROOT}}/core/memory_cli.py" --harness "{{HARNESS_ID}}" {{PLUGIN_DATA_ARG}} forget --remote --yes
+```
+
+If the user also asked to delete the repository's shared project memory, add
+`--include-project-memory` and say that this removes it for every teammate.
+
+Report what the command output says was deleted. If the user only wants local
+data cleared (evidence log, pending queue), run the same command without
+`--remote`. Never pass `--yes` before the user has confirmed in this
+conversation.
diff --git a/integrations/agent-plugin-core/skills/pause/SKILL.md.tmpl b/integrations/agent-plugin-core/skills/pause/SKILL.md.tmpl
new file mode 100644
index 000000000..569305ec7
--- /dev/null
+++ b/integrations/agent-plugin-core/skills/pause/SKILL.md.tmpl
@@ -0,0 +1,20 @@
+---
+name: pause
+description: Pause Mem0 memory capture on this machine. Use when the user wants to stop memories being recorded, for example for private work or experiments.
+disable-model-invocation: true
+---
+
+# Pause memory capture
+
+To pause (hooks stop capturing and sending session content; a minimal
+telemetry ping still fires at session start, under your Mem0 account email,
+unless `MEM0_TELEMETRY=false`):
+
+```bash
+python3 "{{PLUGIN_ROOT}}/core/memory_cli.py" --harness "{{HARNESS_ID}}" {{PLUGIN_DATA_ARG}} pause
+```
+
+Confirm the new state back to the user, and remind them that already-created
+memories still exist and remain searchable. Pending unsent packets are held
+while paused, not expired, and are delivered after resuming. To turn capture
+back on, use `/mem0:resume`.
diff --git a/integrations/agent-plugin-core/skills/remember/SKILL.md.tmpl b/integrations/agent-plugin-core/skills/remember/SKILL.md.tmpl
new file mode 100644
index 000000000..7be5fc9be
--- /dev/null
+++ b/integrations/agent-plugin-core/skills/remember/SKILL.md.tmpl
@@ -0,0 +1,21 @@
+---
+name: remember
+description: Acknowledge a "remember this" request and make sure it is captured well. Use when the user explicitly asks to remember, note, or save something for future sessions.
+disable-model-invocation: true
+---
+
+# Remember something for future sessions
+
+Mem0 creates memories from the session automatically โ there is no separate
+write command. When the user asks to remember something:
+
+1. Restate the fact clearly and completely in your reply, in one or two
+ sentences, including any names, values, or paths it depends on. Your visible
+ reply is what memory extraction reads, so a precise restatement is what gets
+ remembered.
+2. Tell the user it will be saved with this session's memories when the session
+ ends or compacts, and that it will surface in future sessions in this
+ repository (they can check later with /mem0:search).
+
+Do not invent a storage confirmation or a memory ID โ creation happens in the
+background after the session.
diff --git a/integrations/agent-plugin-core/skills/resume/SKILL.md.tmpl b/integrations/agent-plugin-core/skills/resume/SKILL.md.tmpl
new file mode 100644
index 000000000..b8a4d5f01
--- /dev/null
+++ b/integrations/agent-plugin-core/skills/resume/SKILL.md.tmpl
@@ -0,0 +1,19 @@
+---
+name: resume
+description: Resume Mem0 memory capture after it was paused with /mem0:pause.
+disable-model-invocation: true
+---
+
+# Resume memory capture
+
+Resume memory capture for this machine.
+
+Run:
+
+```bash
+python3 "{{PLUGIN_ROOT}}/core/memory_cli.py" --harness "{{HARNESS_ID}}" {{PLUGIN_DATA_ARG}} resume
+```
+
+Confirm to the user that capture is active again. New sessions record evidence and
+create memories as normal; nothing that happened while paused is retroactively
+captured.
diff --git a/integrations/agent-plugin-core/skills/search/SKILL.md.tmpl b/integrations/agent-plugin-core/skills/search/SKILL.md.tmpl
new file mode 100644
index 000000000..6c4fdd03c
--- /dev/null
+++ b/integrations/agent-plugin-core/skills/search/SKILL.md.tmpl
@@ -0,0 +1,26 @@
+---
+name: search
+description: Search memories from earlier {{HARNESS_NAME}} sessions in this repository. Use it when earlier work may already explain the code, error, decision, or command you need, so you can avoid repeating file reads, searches, or experiments.
+argument-hint: "[question] [--top-k number] [--category category-name] [--scope repo|dir|mine] [--run-id session-id]"
+disable-model-invocation: true
+---
+
+# Search memories
+
+Call `search_memories` with the user's question. Treat `--top-k`, `--category`,
+`--scope`, and `--run-id` as tool arguments instead of including them in the
+query.
+
+Omit `top_k` to use Mem0's configured default. Omit `category` to search every
+category. Omit `scope` to use the configured default, normally `repo`: this
+repository's shared memory, which everyone who works in it contributes to,
+plus your own preferences.
+
+Pass `scope` when the question needs something else: `dir` to narrow the
+shared memory to the directory you are working in (a package inside a
+monorepo), `mine` for your own preferences alone.
+
+Pass `run_id` with any scope to retrieve memories saved in a specific coding-agent
+session. Omit `run_id` to search across sessions. It filters the memories returned;
+it does not identify the session making the search request. Use a known session ID,
+never invent one. Return the tool's result directly.
diff --git a/integrations/agent-plugin-core/skills/status/SKILL.md.tmpl b/integrations/agent-plugin-core/skills/status/SKILL.md.tmpl
new file mode 100644
index 000000000..c1ac9e8f9
--- /dev/null
+++ b/integrations/agent-plugin-core/skills/status/SKILL.md.tmpl
@@ -0,0 +1,23 @@
+---
+name: status
+description: Show whether Mem0 memory is working in this repository, covering configuration, capture state, pending flushes, and whether the Mem0 API key is valid. Use when the user asks whether memory is on, why a memory is missing, or anything looks broken.
+disable-model-invocation: false
+---
+
+# Memory status
+
+Run both commands and report the combined result in plain language:
+
+```bash
+python3 "{{PLUGIN_ROOT}}/core/memory_cli.py" --harness "{{HARNESS_ID}}" {{PLUGIN_DATA_ARG}} status --json
+python3 "{{PLUGIN_ROOT}}/core/memory_cli.py" --harness "{{HARNESS_ID}}" {{PLUGIN_DATA_ARG}} doctor
+```
+
+Summarize, using only fields the JSON actually reports: whether capture is
+active or paused, the user ID and repository scope (`repo_id`), whether an
+API key is configured, the event/flush/retrieval counts (`flushes` is the
+number of completed flushes, not a pending count), and the doctor check
+results. If doctor reports an authentication failure (401 / invalid key), say
+clearly that the Mem0 API key is invalid or expired and that memories are NOT
+being created. Never report an auth failure as "no memories found". Suggest
+reinstalling with `--config api_key=...` in that case.
diff --git a/integrations/agent-plugin-core/tests/test_build.py b/integrations/agent-plugin-core/tests/test_build.py
new file mode 100644
index 000000000..23295cc38
--- /dev/null
+++ b/integrations/agent-plugin-core/tests/test_build.py
@@ -0,0 +1,167 @@
+from __future__ import annotations
+
+import json
+import sys
+from pathlib import Path
+
+import pytest
+
+ROOT = Path(__file__).resolve().parents[1]
+REPOSITORY_ROOT = ROOT.parents[1]
+sys.path.insert(0, str(ROOT))
+
+from build.build import ( # noqa: E402
+ build,
+ bundle_drift,
+ render_template,
+ replace_output,
+)
+from build.validate import validate_bundle # noqa: E402
+
+
+def test_render_rejects_unknown_or_unresolved_tokens() -> None:
+ with pytest.raises(ValueError, match="UNKNOWN"):
+ render_template("run {{UNKNOWN}}", {})
+
+
+def test_build_replaces_only_the_requested_output(tmp_path: Path) -> None:
+ staged = tmp_path / "staged"
+ staged.mkdir()
+ (staged / "plugin.json").write_text("{}", encoding="utf-8")
+ output = tmp_path / "output"
+ output.mkdir()
+ (output / "stale.py").write_text("stale", encoding="utf-8")
+ sibling = tmp_path / "keep.txt"
+ sibling.write_text("keep", encoding="utf-8")
+
+ replace_output(staged, output)
+
+ assert not (output / "stale.py").exists()
+ assert (output / "plugin.json").exists()
+ assert sibling.read_text(encoding="utf-8") == "keep"
+
+
+def test_build_cannot_replace_an_installable_source_directory(tmp_path: Path) -> None:
+ staged = tmp_path / "staged"
+ staged.mkdir()
+
+ with pytest.raises(ValueError, match="protected output path"):
+ replace_output(staged, REPOSITORY_ROOT / "integrations" / "claude-code-plugin")
+
+
+def test_portable_bundle_is_conformant_and_self_contained(tmp_path: Path) -> None:
+ root = build("mem0-agent-plugin", "portable", tmp_path / "mem0-agent-plugin")
+
+ assert validate_bundle(root, "portable") == []
+ assert json.loads((root / "plugin.json").read_text(encoding="utf-8"))["$schema"] == (
+ "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json"
+ )
+ server = json.loads((root / "mcp.json").read_text(encoding="utf-8"))["mcpServers"]["mem0"]
+ assert server["type"] == "stdio"
+ assert server["args"] == ["${PLUGIN_ROOT}/core/mcp_server.py"]
+ assert "env" not in server
+ assert not (root / "core" / "hook_runner.py").exists()
+ assert not (root / "core" / "flush_worker.py").exists()
+ assert not (root / "agents").exists()
+ for skill in (root / "skills").glob("*/SKILL.md"):
+ frontmatter = skill.read_text(encoding="utf-8").split("---", 2)[1]
+ keys = {line.split(":", 1)[0] for line in frontmatter.splitlines() if ":" in line}
+ assert keys <= {"name", "description", "license", "compatibility", "metadata", "allowed-tools"}
+ assert not any(path.is_symlink() for path in root.rglob("*"))
+
+
+def _harness_identity(root: Path) -> dict[str, str]:
+ """Read the generated core/_harness_id.py without importing it."""
+ values: dict[str, str] = {}
+ for line in (root / "core" / "_harness_id.py").read_text(encoding="utf-8").splitlines():
+ if "=" in line and not line.lstrip().startswith("#"):
+ name, _, raw = line.partition("=")
+ values[name.strip()] = raw.strip().strip('"')
+ return values
+
+
+def test_the_portable_bundle_declares_no_host_application(tmp_path: Path) -> None:
+ """It runs in whatever editor a user drops it into, so it cannot know the host.
+
+ X-Application is allowlisted server-side. A guessed value is silently dropped
+ there, which is the worst outcome: the wire says we know the host and the
+ stored event says we do not.
+ """
+ identity = _harness_identity(build("mem0-agent-plugin", "portable", tmp_path / "portable"))
+
+ assert identity["PLATFORM_APPLICATION"] == ""
+ # The PostHog-side label is still useful for grouping and stays populated.
+ assert identity["HARNESS_ID"] == "coding-agent"
+ assert identity["PLATFORM_SOURCE"] == "MEM0_PLUGIN"
+
+
+@pytest.mark.parametrize("host", ["claude-code", "cursor", "codex", "kimi", "antigravity"])
+def test_a_native_bundle_names_the_host_it_was_built_for(host: str, tmp_path: Path) -> None:
+ identity = _harness_identity(build(host, "native", tmp_path / host))
+
+ assert identity["PLATFORM_APPLICATION"] == host
+
+
+@pytest.mark.parametrize("host", ["claude-code", "cursor", "codex", "kimi", "antigravity"])
+def test_native_bundle_is_self_contained(host: str, tmp_path: Path) -> None:
+ root = build(host, "native", tmp_path / host)
+
+ assert (root / "core" / "memory_core.py").is_file()
+ assert (root / "skills" / "remember" / "SKILL.md").is_file()
+ assert not any(path.is_symlink() for path in root.rglob("*"))
+
+
+@pytest.mark.parametrize("host", ["claude-code", "cursor", "codex", "kimi", "antigravity"])
+def test_only_claude_bundles_sidekick(host: str, tmp_path: Path) -> None:
+ root = build(host, "native", tmp_path / host)
+ if host == "claude-code":
+ agent = (root / "agents" / "sidekick.md").read_text()
+ assert "model: sonnet" in agent
+ assert "isolation: worktree" in agent
+ else:
+ assert not (root / "agents").exists()
+ for path in root.rglob("*.json"):
+ assert "sidekick" not in path.read_text().lower()
+
+
+@pytest.mark.parametrize("host", ["claude-code", "cursor", "codex", "kimi", "antigravity"])
+def test_native_control_skills_select_the_host_store(host: str, tmp_path: Path) -> None:
+ root = build(host, "native", tmp_path / host)
+ status = (root / "skills" / "status" / "SKILL.md").read_text(encoding="utf-8")
+
+ assert f'--harness "{host}"' in status
+ if host == "claude-code":
+ assert '--plugin-data-dir "${CLAUDE_PLUGIN_DATA}"' in status
+ elif host == "codex":
+ assert '--plugin-data-dir "${PLUGIN_DATA}"' in status
+
+
+@pytest.mark.parametrize(
+ ("host", "kind"),
+ [
+ ("mem0-agent-plugin", "portable"),
+ ("claude-code", "native"),
+ ("cursor", "native"),
+ ("codex", "native"),
+ ("kimi", "native"),
+ ("antigravity", "native"),
+ ],
+)
+def test_installable_plugin_directories_are_current(host: str, kind: str) -> None:
+ assert bundle_drift(host, kind) == []
+
+
+def test_marketplaces_keep_public_names_and_reference_real_plugins() -> None:
+ marketplace = json.loads((REPOSITORY_ROOT / "marketplace.json").read_text(encoding="utf-8"))
+ sources = {plugin["name"]: plugin["source"] for plugin in marketplace["plugins"]}
+
+ assert sources == {"mem0": "./integrations/claude-code-plugin"}
+ for source in sources.values():
+ assert (REPOSITORY_ROOT / source).exists()
+
+ codex_marketplace = json.loads(
+ (REPOSITORY_ROOT / ".agents" / "plugins" / "marketplace.json").read_text(encoding="utf-8")
+ )
+ assert [plugin["name"] for plugin in codex_marketplace["plugins"]] == ["mem0"]
+ codex = codex_marketplace["plugins"][0]
+ assert codex["source"]["path"] == "./integrations/codex-plugin"
diff --git a/integrations/agent-plugin-core/tests/test_conformance.py b/integrations/agent-plugin-core/tests/test_conformance.py
new file mode 100644
index 000000000..53c7fb826
--- /dev/null
+++ b/integrations/agent-plugin-core/tests/test_conformance.py
@@ -0,0 +1,190 @@
+from __future__ import annotations
+
+import json
+import os
+import subprocess
+import sys
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+from conformance import run as conformance_run # noqa: E402
+from conformance.run import _command_check # noqa: E402
+
+
+PLUGIN_ROOT = Path(__file__).resolve().parents[1]
+RUNNER = PLUGIN_ROOT / "conformance" / "run.py"
+PYTHON_HOSTS = {"claude-code", "cursor", "codex", "kimi", "antigravity"}
+
+
+def test_python_bundle_conformance_builds_every_host(tmp_path: Path) -> None:
+ report = tmp_path / "report.json"
+ artifacts = tmp_path / "artifacts"
+
+ result = subprocess.run(
+ [
+ sys.executable,
+ str(RUNNER),
+ "--group",
+ "python-bundles",
+ "--artifacts-dir",
+ str(artifacts),
+ "--report",
+ str(report),
+ ],
+ cwd=PLUGIN_ROOT.parents[1],
+ text=True,
+ capture_output=True,
+ check=False,
+ )
+
+ assert result.returncode == 0, result.stdout + result.stderr
+ payload = json.loads(report.read_text(encoding="utf-8"))
+ assert payload["status"] == "passed"
+ assert {
+ entry["host"]
+ for entry in payload["checks"]
+ if entry["kind"] == "native"
+ } == PYTHON_HOSTS
+ assert {
+ entry["host"]
+ for entry in payload["checks"]
+ if entry["kind"] == "portable"
+ } == {"mem0-agent-plugin"}
+ for host in PYTHON_HOSTS:
+ assert (artifacts / host).is_dir()
+ assert (artifacts / "mem0-agent-plugin").is_dir()
+
+
+def test_conformance_plan_covers_every_runtime(tmp_path: Path) -> None:
+ report = tmp_path / "plan.json"
+
+ result = subprocess.run(
+ [sys.executable, str(RUNNER), "--list", "--report", str(report)],
+ cwd=PLUGIN_ROOT.parents[1],
+ text=True,
+ capture_output=True,
+ check=False,
+ )
+
+ assert result.returncode == 0, result.stdout + result.stderr
+ payload = json.loads(report.read_text(encoding="utf-8"))
+ assert {entry["group"] for entry in payload["checks"]} == {
+ "python-bundles",
+ "python-tests",
+ "typescript-core",
+ "openclaw",
+ "opencode",
+ "pi-agent",
+ "deepseek",
+ }
+ assert all(entry["status"] == "planned" for entry in payload["checks"])
+ assert {
+ entry["group"]
+ for entry in payload["checks"]
+ if entry["name"].endswith("-artifact")
+ } == {"openclaw", "opencode", "pi-agent", "deepseek"}
+
+
+def test_typescript_artifact_check_rejects_monorepo_imports(tmp_path: Path) -> None:
+ dist = tmp_path / "dist"
+ dist.mkdir()
+ (dist / "index.js").write_text(
+ 'import { createMemoryLifecycle } from "../../agent-plugin-core/typescript/src/lifecycle.ts";\n',
+ encoding="utf-8",
+ )
+
+ artifact_check = getattr(conformance_run, "_typescript_artifact_check", None)
+ assert artifact_check is not None, "TypeScript package artifacts are not checked"
+ result = artifact_check("example", tmp_path, ("dist/index.js",))
+
+ assert result["status"] == "failed"
+ assert "monorepo source import" in result["output"]
+
+
+def test_live_conformance_requires_an_explicit_mem0_key(tmp_path: Path) -> None:
+ environment = dict(os.environ)
+ environment.pop("MEM0_API_KEY", None)
+
+ result = subprocess.run(
+ [sys.executable, str(RUNNER), "--live", "--report", str(tmp_path / "report.json")],
+ cwd=PLUGIN_ROOT.parents[1],
+ env=environment,
+ text=True,
+ capture_output=True,
+ check=False,
+ )
+
+ assert result.returncode == 2
+ assert "MEM0_API_KEY is required for --live" in result.stderr
+
+
+def test_live_conformance_reports_platform_failure_without_crashing(tmp_path: Path) -> None:
+ report = tmp_path / "report.json"
+ environment = {
+ **os.environ,
+ "MEM0_API_KEY": "m0-intentionally-invalid",
+ "MEM0_API_URL": "http://127.0.0.1:1",
+ }
+
+ result = subprocess.run(
+ [
+ sys.executable,
+ str(RUNNER),
+ "--group",
+ "live-platform",
+ "--live",
+ "--report",
+ str(report),
+ ],
+ cwd=PLUGIN_ROOT.parents[1],
+ env=environment,
+ text=True,
+ capture_output=True,
+ check=False,
+ )
+
+ assert result.returncode == 1
+ payload = json.loads(report.read_text(encoding="utf-8"))
+ assert payload["status"] == "failed"
+ assert payload["checks"][0]["group"] == "live-platform"
+
+
+def test_runtime_checks_preserve_the_callers_telemetry_setting(tmp_path: Path, monkeypatch) -> None:
+ monkeypatch.delenv("MEM0_TELEMETRY", raising=False)
+
+ result = _command_check(
+ "environment",
+ "test",
+ [sys.executable, "-c", "import os; print(os.environ.get('MEM0_TELEMETRY', 'unset'))"],
+ cwd=tmp_path,
+ )
+
+ assert result["status"] == "passed"
+ assert result["output"] == "unset"
+
+
+def test_command_check_can_force_non_interactive_installs(tmp_path: Path) -> None:
+ result = _command_check(
+ "environment",
+ "test",
+ [sys.executable, "-c", "import os; print(os.environ['CI'])"],
+ cwd=tmp_path,
+ environment_overrides={"CI": "true"},
+ )
+
+ assert result["status"] == "passed"
+ assert result["output"] == "true"
+
+
+def test_conformance_report_redacts_command_output(tmp_path: Path) -> None:
+ secret = "sk-eval-12345678901234567890"
+
+ result = _command_check(
+ "redaction",
+ "test",
+ [sys.executable, "-c", f"print('failure: {secret}')"],
+ cwd=tmp_path,
+ )
+
+ assert secret not in json.dumps(result)
+ assert "[REDACTED]" in result["output"]
diff --git a/integrations/agent-plugin-core/tests/test_spool_delivery.py b/integrations/agent-plugin-core/tests/test_spool_delivery.py
new file mode 100644
index 000000000..accd631a6
--- /dev/null
+++ b/integrations/agent-plugin-core/tests/test_spool_delivery.py
@@ -0,0 +1,446 @@
+"""Delivery semantics of the telemetry spool: no duplicates, no starvation.
+
+These run against a built host's core in-process (not a subprocess) because they
+need to inject failures into ``_post``. The identity tests next door cover the
+uninitialised-process case that needs a real interpreter.
+"""
+
+from __future__ import annotations
+
+import importlib
+import json
+import os
+import sys
+import time
+from pathlib import Path
+
+import pytest
+
+CORE_ROOT = Path(__file__).resolve().parents[1]
+REPOSITORY_ROOT = CORE_ROOT.parents[1]
+HOST_CORE = REPOSITORY_ROOT / "integrations" / "claude-code-plugin" / "core"
+
+pytestmark = pytest.mark.skipif(not HOST_CORE.exists(), reason="claude-code-plugin is not built")
+
+
+@pytest.fixture()
+def telemetry(tmp_path, monkeypatch):
+ # CI runs this directory and claude-code-plugin/tests in ONE pytest process,
+ # and that suite's conftest sets MEM0_TELEMETRY=false at import, process-wide.
+ # Without this the whole file silently no-ops: record() returns early and
+ # every assertion sees an empty spool. Do not rely on ambient env.
+ monkeypatch.setenv("MEM0_TELEMETRY", "true")
+ monkeypatch.setenv("MEM0_CODE_DATA_DIR", str(tmp_path / "data"))
+ monkeypatch.syspath_prepend(str(HOST_CORE))
+
+ # Save and RESTORE rather than delete. claude-code-plugin/tests/conftest.py
+ # imports memory_core once at collection and calls configure_harness() on it;
+ # dropping the module left a later re-import with default harness config, so
+ # tests in that suite failed depending on collection order.
+ names = ("telemetry", "memory_core", "_harness_id")
+ saved = {name: sys.modules.get(name) for name in names}
+ for name in names:
+ sys.modules.pop(name, None)
+
+ module = importlib.import_module("telemetry")
+ monkeypatch.setattr(module, "resolve_distinct_id", lambda: ("tester@example.com", ""))
+ try:
+ yield module
+ finally:
+ for name in names:
+ sys.modules.pop(name, None)
+ if saved[name] is not None:
+ sys.modules[name] = saved[name]
+
+
+def _delivered(payloads):
+ return [event for payload in payloads if "batch" in payload for event in payload["batch"]]
+
+
+def test_a_partial_failure_does_not_redeliver_what_already_arrived(telemetry):
+ """Defect 2a: flush kept the whole claim on failure and retried from the top.
+
+ 150 events across two batches, the second failing, previously delivered 250.
+ """
+ for index in range(150):
+ telemetry.record("search", index=index)
+
+ sent: list[dict] = []
+ calls = {"n": 0}
+
+ def flaky(payload, url):
+ calls["n"] += 1
+ if calls["n"] == 2: # second batch fails
+ return False
+ sent.append(payload)
+ return True
+
+ telemetry._post = flaky
+ telemetry.flush()
+
+ telemetry._post = lambda payload, url: sent.append(payload) or True
+ telemetry.flush()
+
+ events = _delivered(sent)
+ assert len(events) == 150
+ assert len({event["uuid"] for event in events}) == 150
+
+
+def test_a_fresh_claim_is_not_immediately_stealable(telemetry):
+ """Defect 2b: rename preserves mtime, so a claim inherited the spool's age.
+
+ With the last write older than the stale threshold, a claim made now looked
+ abandoned the instant it existed and a second sender took it over.
+ """
+ telemetry.record("search")
+ spool = telemetry._spool_path()
+ old = time.time() - (telemetry.CLAIM_STALE_SECONDS + 60)
+ os.utime(spool, (old, old))
+
+ first = telemetry._claim_spool()
+ assert first is not None
+
+ # A second sender starting right now must find nothing to take.
+ assert telemetry._claim_parked(first.parent) is None
+
+
+def test_a_live_final_attempt_is_not_deleted_by_another_sender(telemetry):
+ """Review finding: exhaustion was judged before liveness, so owners lost batches.
+
+ Claiming a parked file bumps its attempt count and refreshes its mtime. Once
+ the count reaches the budget, the owner draining it looked exhausted to every
+ other sender, which unlinked the file out from under it. Everything in that
+ batch was gone, which is precisely the loss this PR exists to stop.
+ """
+ telemetry.record("search", reason="owned-by-the-first-sender")
+ spool = telemetry._spool_path()
+ stale = time.time() - (telemetry.CLAIM_STALE_SECONDS + 60)
+ os.utime(spool, (stale, stale))
+
+ claim = telemetry._claim_spool()
+ assert claim is not None
+
+ # Walk it to the final attempt, ageing it each round so it can be re-claimed.
+ # _claim_spool hands back a0 and _release_claim keeps the name, so it takes
+ # one full round per attempt to reach the budget.
+ for _ in range(telemetry.MAX_CLAIM_ATTEMPTS):
+ # Carry the marker through each rewrite so the final assertion proves the
+ # events survived, not merely that some file with the right name did.
+ telemetry._release_claim(claim, [{"event": "code.search", "uuid": "owned-by-the-first-sender"}])
+ parked = sorted(claim.parent.glob("telemetry-*.sending"))
+ assert parked, "the batch was dropped while still inside its budget"
+ os.utime(parked[0], (stale, stale))
+ claim = telemetry._claim_parked(claim.parent)
+ assert claim is not None
+
+ assert telemetry._claim_attempt(claim) >= telemetry.MAX_CLAIM_ATTEMPTS
+ assert claim.exists()
+
+ # The owner is draining it right now: fresh mtime, live lease.
+ second_sender = telemetry._claim_parked(claim.parent)
+
+ assert second_sender is None, "a second sender took a batch under a live lease"
+ assert claim.exists(), "a second sender deleted a batch its owner was draining"
+ assert "owned-by-the-first-sender" in claim.read_text(encoding="utf-8")
+
+
+def test_an_exhausted_batch_is_still_discarded_once_its_lease_lapses(telemetry):
+ """The liveness check must defer the cleanup, not cancel it.
+
+ Guards the obvious over-correction: skipping live claims is only safe if an
+ abandoned one at the same attempt count is still reaped on a later run.
+ """
+ telemetry.record("search")
+ spool = telemetry._spool_path()
+ stale = time.time() - (telemetry.CLAIM_STALE_SECONDS + 60)
+ os.utime(spool, (stale, stale))
+
+ claim = telemetry._claim_spool()
+ assert claim is not None
+ exhausted = claim.parent / telemetry._claim_name(telemetry.MAX_CLAIM_ATTEMPTS)
+ claim.replace(exhausted)
+ os.utime(exhausted, (stale, stale))
+
+ assert telemetry._claim_parked(exhausted.parent) is None
+ assert not exhausted.exists(), "an abandoned exhausted batch was left behind forever"
+
+
+def test_a_parked_batch_is_drained_behind_the_live_spool(telemetry):
+ """Defect 6: parked claims were only reachable when no spool existed.
+
+ Because sessions keep recording there usually was one, so a batch parked by
+ a failed send waited until the 7-day expiry deleted it unsent โ even though
+ its own presence is what starts the sender.
+ """
+ telemetry.record("parked")
+ telemetry._post = lambda payload, url: False
+ telemetry.flush()
+
+ parked = list(telemetry.memory_core.data_dir().glob("telemetry-*.sending"))
+ assert len(parked) == 1
+ old = time.time() - (telemetry.CLAIM_STALE_SECONDS + 60)
+ os.utime(parked[0], (old, old))
+
+ telemetry.record("fresh")
+ sent: list[dict] = []
+ telemetry._post = lambda payload, url: sent.append(payload) or True
+ telemetry.flush()
+
+ names = {event["event"] for event in _delivered(sent)}
+ assert names == {"code.parked", "code.fresh"}
+
+
+def test_a_batch_is_retried_until_the_budget_is_spent_not_discarded(telemetry):
+ """Expiry discards what failed repeatedly, not what merely sat for a while.
+
+ The budget is the attempt count, because age cannot be one: every re-claim
+ touches the mtime and every release backdates it, so age never accumulates.
+ """
+ telemetry.record("parked")
+ telemetry._post = lambda payload, url: False
+ telemetry.flush()
+
+ parked = list(telemetry.memory_core.data_dir().glob("telemetry-*.sending"))
+ assert len(parked) == 1
+ assert telemetry._claim_attempt(parked[0]) < telemetry.MAX_CLAIM_ATTEMPTS
+
+ sent: list[dict] = []
+ telemetry._post = lambda payload, url: sent.append(payload) or True
+ telemetry.flush()
+
+ assert [event["event"] for event in _delivered(sent)] == ["code.parked"]
+
+
+def test_progress_is_recorded_after_every_batch(telemetry):
+ """A crash repeats at most one batch, not the whole file."""
+ for index in range(250):
+ telemetry.record("search", index=index)
+
+ calls = {"n": 0}
+
+ def die_after_two(payload, url):
+ calls["n"] += 1
+ if calls["n"] > 2:
+ return False
+ return True
+
+ telemetry._post = die_after_two
+ telemetry.flush()
+
+ parked = list(telemetry.memory_core.data_dir().glob("telemetry-*.sending"))
+ assert len(parked) == 1
+ remaining = parked[0].read_text(encoding="utf-8").strip().splitlines()
+ # Two batches of 100 landed; only the last 50 should still be pending.
+ assert len(remaining) == 50
+ assert json.loads(remaining[0])["properties"]["index"] == 200
+
+
+def test_the_heartbeat_actually_refreshes_the_lease(telemetry):
+ """The claim rewrite doubles as the lease heartbeat.
+
+ Previously asserted `SEND_TIMEOUT * 4 < CLAIM_STALE_SECONDS`, which compares
+ two constants and executes none of the code under test. Drive the real
+ rewrite and watch the mtime move instead.
+ """
+ for index in range(150):
+ telemetry.record("search", index=index)
+ claim = telemetry._claim_spool()
+ assert claim is not None
+
+ stale = time.time() - (telemetry.CLAIM_STALE_SECONDS + 60)
+ os.utime(claim, (stale, stale))
+ assert time.time() - claim.stat().st_mtime > telemetry.CLAIM_STALE_SECONDS
+
+ telemetry._rewrite_claim(claim, [{"event": "code.x", "properties": {}}])
+ assert time.time() - claim.stat().st_mtime < telemetry.CLAIM_STALE_SECONDS
+
+
+def test_an_undeliverable_batch_is_eventually_given_up_on(telemetry):
+ """Expiry has to be reachable from a state the state machine can produce.
+
+ It was not: every re-claim touched the mtime and every release backdated it
+ by a fixed amount, so age hovered near the stale threshold and the 7-day
+ expiry never fired. An undeliverable batch lived on disk forever, and
+ spawn_flush saw it and started a sender on every hook.
+ """
+ telemetry.record("doomed")
+ telemetry._post = lambda payload, url: False
+
+ directory = telemetry.memory_core.data_dir()
+ for _ in range(telemetry.MAX_CLAIM_ATTEMPTS + 3):
+ telemetry.flush()
+ # Attempts now carry a cooldown, so a released claim is not instantly
+ # reclaimable. Age it to stand in for the wall time a real retry waits;
+ # without this the loop spins inside one cooldown and proves nothing.
+ for parked in directory.glob("telemetry-*.sending"):
+ stale = time.time() - (telemetry.CLAIM_STALE_SECONDS + 60)
+ os.utime(parked, (stale, stale))
+
+ leftover = list(directory.glob("telemetry-*.sending"))
+ assert leftover == [], f"batch never given up on: {[p.name for p in leftover]}"
+
+
+def test_a_batch_that_cannot_be_read_is_not_counted_as_delivered(telemetry):
+ """Review finding: a read failure reported 'everything delivered'.
+
+ Nothing was posted, so calling it delivered lets flush() carry on to other
+ claims as though this batch had arrived, and hides the failure from the one
+ signal that says the run went badly. It also must not quarantine: a briefly
+ unreadable file is retryable, and moving it to .corrupt discards the events
+ over a transient filesystem error, because nothing ever re-globs .corrupt.
+ """
+ telemetry.record("search")
+ spool = telemetry._spool_path()
+ stale = time.time() - (telemetry.CLAIM_STALE_SECONDS + 60)
+ os.utime(spool, (stale, stale))
+ claim = telemetry._claim_spool()
+ assert claim is not None
+
+ original = Path.read_text
+
+ def unreadable(self, *args, **kwargs):
+ if self == claim:
+ raise OSError(5, "I/O error")
+ return original(self, *args, **kwargs)
+
+ Path.read_text = unreadable
+ try:
+ sent, delivered = telemetry._drain(claim)
+ finally:
+ Path.read_text = original
+
+ assert sent == 0
+ assert delivered is False, "an unread batch was reported as delivered"
+ assert claim.exists(), "a transient read error discarded the batch"
+ assert not list(claim.parent.glob("*.corrupt")), "quarantined over a transient error"
+
+
+def test_undecodable_content_is_still_quarantined_and_the_run_continues(telemetry):
+ """The other half: genuinely unrecoverable content must not block the run.
+
+ Guards the over-correction. If every read problem returned undelivered, one
+ torn file would stop every later claim on every flush, forever.
+ """
+ telemetry.record("search")
+ spool = telemetry._spool_path()
+ stale = time.time() - (telemetry.CLAIM_STALE_SECONDS + 60)
+ os.utime(spool, (stale, stale))
+ claim = telemetry._claim_spool()
+ assert claim is not None
+ claim.write_bytes(b"\xff\xfe torn \x00 write")
+
+ sent, delivered = telemetry._drain(claim)
+
+ assert (sent, delivered) == (0, True)
+ assert not claim.exists()
+ assert list(claim.parent.glob("*.corrupt")), "unrecoverable content was not quarantined"
+
+
+def test_retries_are_spread_over_real_time_not_burned_at_once(telemetry):
+ """Review finding: releasing straight to reclaimable spent the budget instantly.
+
+ Two senders hitting one momentary failure could walk a batch from attempt 0
+ to the limit within seconds and discard it, when a retry a minute later would
+ have delivered. Each release now has to age past a cooldown that grows with
+ the attempts already spent.
+ """
+ telemetry.record("doomed")
+ telemetry._post = lambda payload, url: False
+
+ directory = telemetry.memory_core.data_dir()
+ telemetry.flush()
+
+ parked = list(directory.glob("telemetry-*.sending"))
+ assert parked, "the batch was discarded on its first failure"
+ assert telemetry._claim_attempt(parked[0]) == 0
+
+ # Second sender, immediately: the cooldown has not elapsed, so it must not
+ # be able to spend another attempt.
+ telemetry.flush()
+ still = list(directory.glob("telemetry-*.sending"))
+ assert len(still) == 1
+ assert telemetry._claim_attempt(still[0]) <= 1, "burned attempts without waiting"
+
+
+def test_a_legacy_claim_filename_is_not_mistaken_for_a_huge_attempt_count(telemetry):
+ """The old shape is telemetry--.sending, and hex can start with 'a'."""
+ assert telemetry._claim_attempt(Path("telemetry-999-deadbeef.sending")) == 0
+ assert telemetry._claim_attempt(Path("telemetry-999-a1234567.sending")) == 0
+ assert telemetry._claim_attempt(Path("telemetry-999-deadbeef-a2.sending")) == 2
+
+
+def test_a_torn_claim_is_quarantined_not_deleted(telemetry):
+ """A non-empty file that parses to nothing is the remainder, not garbage."""
+ telemetry.record("search")
+ claim = telemetry._claim_spool()
+ claim.write_bytes(b"\xff\xfe not utf-8 at all")
+ stale = time.time() - (telemetry.CLAIM_STALE_SECONDS + 60)
+ os.utime(claim, (stale, stale))
+
+ sent = telemetry.flush()
+
+ assert sent == 0
+ assert not claim.exists()
+ quarantined = list(telemetry.memory_core.data_dir().glob("*.corrupt"))
+ assert len(quarantined) == 1, "torn claim was destroyed instead of kept"
+
+
+def test_a_failed_rewrite_stops_instead_of_redelivering(telemetry):
+ """Ignoring the rewrite result reintroduced the duplicates this PR fixes."""
+ for index in range(250):
+ telemetry.record("search", index=index)
+
+ telemetry._rewrite_claim = lambda claim, remaining: False
+ delivered = []
+ telemetry._post = lambda payload, url: delivered.extend(payload.get("batch", [])) or True
+
+ telemetry.flush()
+ assert len(delivered) == 100, f"kept going after a failed rewrite: {len(delivered)}"
+
+
+def test_partial_files_are_swept(telemetry):
+ """Nothing else globs *.partial, so a crash mid-rename orphans one forever."""
+ data_dir = telemetry.memory_core.data_dir()
+ data_dir.mkdir(parents=True, exist_ok=True)
+ debris = data_dir / "telemetry-1-abc-a0.1.partial"
+ debris.write_text("x", encoding="utf-8")
+ old = time.time() - (telemetry.CLAIM_STALE_SECONDS + 60)
+ os.utime(debris, (old, old))
+
+ telemetry.flush()
+ assert not debris.exists()
+
+
+def test_quarantined_batches_are_eventually_collected(telemetry):
+ """Nothing re-globs .corrupt, so without a sweep they live on disk forever.
+
+ Kept much longer than .partial debris on purpose: a quarantined batch is the
+ only remaining evidence of events that could not be delivered.
+ """
+ directory = telemetry.memory_core.data_dir()
+ directory.mkdir(parents=True, exist_ok=True)
+ fresh = directory / "telemetry-1-aaaaaaaa-a0.corrupt"
+ old = directory / "telemetry-2-bbbbbbbb-a0.corrupt"
+ for path in (fresh, old):
+ path.write_text("torn", encoding="utf-8")
+ expired = time.time() - (telemetry.CLAIM_EXPIRY_SECONDS + 60)
+ os.utime(old, (expired, expired))
+
+ telemetry._sweep_debris(directory)
+
+ assert fresh.exists(), "a recent quarantine was discarded before anyone could look at it"
+ assert not old.exists(), "an expired quarantine was left on disk forever"
+
+
+def test_temp_files_orphaned_by_a_kill_are_collected(telemetry):
+ """_write_identity and _install_salt unlink in a finally, which SIGKILL skips."""
+ directory = telemetry.memory_core.data_dir()
+ directory.mkdir(parents=True, exist_ok=True)
+ orphan = directory / "telemetry-salt.999.tmp"
+ orphan.write_text("abandoned", encoding="utf-8")
+ stale = time.time() - (telemetry.CLAIM_STALE_SECONDS + 60)
+ os.utime(orphan, (stale, stale))
+
+ telemetry._sweep_debris(directory)
+
+ assert not orphan.exists(), "a killed process left a temp file on disk forever"
diff --git a/integrations/agent-plugin-core/tests/test_subagents.py b/integrations/agent-plugin-core/tests/test_subagents.py
new file mode 100644
index 000000000..f91b3e091
--- /dev/null
+++ b/integrations/agent-plugin-core/tests/test_subagents.py
@@ -0,0 +1,102 @@
+"""Exercise bundled subagent hooks as separate host processes, without Mem0 calls."""
+
+import json
+import os
+import sqlite3
+import subprocess
+import sys
+from pathlib import Path
+
+import pytest
+
+ROOT = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(ROOT / "python"))
+
+from memory_core import EvidenceStore, RepoContext, checkpoint_stats # noqa: E402
+
+
+def test_generic_tracking_preserves_legacy_runs_and_can_finish_them(tmp_path):
+ database = tmp_path / "evidence.sqlite3"
+ with sqlite3.connect(database) as connection:
+ connection.executescript("""
+ CREATE TABLE sidekick_runs (
+ repo_id TEXT NOT NULL, session_id TEXT NOT NULL,
+ agent_id TEXT NOT NULL, agent_type TEXT NOT NULL,
+ started_at TEXT NOT NULL, stopped_at TEXT, transcript_path TEXT,
+ context_chars INTEGER NOT NULL DEFAULT 0, final_message TEXT,
+ PRIMARY KEY(repo_id, session_id, agent_id)
+ );
+ INSERT INTO sidekick_runs VALUES
+ ('repo', 'session', 'worker', 'default', '2026-09-10', NULL, NULL, 123, NULL);
+ """)
+ for _ in range(2):
+ store = EvidenceStore(database)
+ try:
+ assert store.status("repo")["subagent_runs"] == 1
+ row = store.conn.execute("SELECT * FROM sidekick_runs").fetchone()
+ assert row["agent_id"] == "worker"
+ assert row["context_chars"] == 123
+ repo = RepoContext(str(tmp_path), str(tmp_path), "repo", "app", "main", "")
+ store.stop_subagent(repo, "session", "worker", "default", "", "Completed after upgrade.")
+ assert store.status("repo")["last_subagent"]["stopped_at"]
+ assert store.conn.execute("SELECT final_message FROM sidekick_runs").fetchone()[0] == (
+ "Completed after upgrade."
+ )
+ finally:
+ store.close()
+ assert checkpoint_stats([{"kind": "sidekick_stop", "payload": {"final_message": "Legacy result."}}]) == (0, 1, 14)
+
+
+@pytest.mark.parametrize("host", ["claude-code", "codex"])
+def test_subagent_hooks_preserve_parent_scope_and_correlate_completion(tmp_path, host):
+ parent = tmp_path / "parent"
+ child = tmp_path / "child-worktree"
+ parent.mkdir()
+ child.mkdir()
+ database = tmp_path / "data" / "evidence.sqlite3"
+ store = EvidenceStore(database)
+ repo = store.repo_for_session("parent-session", str(parent))
+ store.mark_injected("parent-session", repo.identity, [{"id": "one", "memory": "Parent memory marker."}])
+ store.mark_injected("other-session", repo.identity, [{"id": "two", "memory": "Foreign memory marker."}])
+ store.close()
+
+ plugin = ROOT.parent / f"{host}-plugin"
+ adapter = plugin / ("adapters/claude/hook.py" if host == "claude-code" else "hooks/adapter.py")
+ start, stop = "sidekick-start", "sidekick-stop"
+ payload = {"session_id": "parent-session", "cwd": str(child), "agent_id": "worker", "agent_type": "default"}
+ response_key = "last_assistant_message"
+ if host == "codex":
+ start, stop = "subagent-start", "subagent-stop"
+
+ env = {key: value for key, value in os.environ.items() if not key.startswith(("MEM0_", "CLAUDE_PLUGIN_"))}
+ env.update(MEM0_CODE_DATA_DIR=str(database.parent), MEM0_TELEMETRY="false", MEM0_API_URL="http://127.0.0.1:1")
+
+ def invoke(event, body):
+ result = subprocess.run(
+ [sys.executable, str(adapter), event],
+ input=json.dumps({**body, "hook_event_name": event}),
+ text=True,
+ capture_output=True,
+ env=env,
+ timeout=15,
+ check=True,
+ )
+ return result.stdout
+
+ output = invoke(start, payload)
+ context = json.loads(output)["hookSpecificOutput"]["additionalContext"]
+ assert "Parent memory marker." in context
+ assert "Foreign memory marker." not in output
+ assert "Parent memory marker." not in invoke(start, payload)
+ invoke(stop, {**payload, response_key: "Finished the delegated task."})
+
+ store = EvidenceStore(database)
+ runs = store.conn.execute("SELECT * FROM sidekick_runs").fetchall()
+ store.close()
+ assert len(runs) == 1
+ assert (runs[0]["repo_id"], runs[0]["session_id"], runs[0]["agent_id"]) == (
+ repo.identity, "parent-session", "worker"
+ )
+ assert runs[0]["stopped_at"]
+ assert runs[0]["final_message"] == "Finished the delegated task."
+ assert runs[0]["context_chars"] > 0
diff --git a/integrations/agent-plugin-core/tests/test_uninitialised_identity.py b/integrations/agent-plugin-core/tests/test_uninitialised_identity.py
new file mode 100644
index 000000000..74a31fa5c
--- /dev/null
+++ b/integrations/agent-plugin-core/tests/test_uninitialised_identity.py
@@ -0,0 +1,274 @@
+"""Core telemetry behaviour with NO telemetry.init(), in a real subprocess.
+
+Why this file exists
+--------------------
+``telemetry.py`` lives in ``agent-plugin-core/python/`` but its only tests lived
+under ``claude-code-plugin/tests/``, behind a ``conftest.py`` that calls
+``configure_harness()`` and ``telemetry.init()`` at import. Core behaviour was
+therefore only ever exercised inside an already-configured module.
+
+Two processes in the real pipeline never call ``init()``:
+
+- ``mcp_server.py``, which records every manual search;
+- the detached ``python3 telemetry.py`` sender that ``spawn_flush()`` starts at
+ session start, after every skill command, and when the MCP server exits.
+
+Both fell back to module defaults, so MCP searches reported ``harness=generic``
+and everything that sender delivered was labelled ``MEM0_PLUGIN`` regardless of
+which of the six plugins produced it. The suite stayed green throughout.
+
+These tests run in a fresh interpreter with no conftest, against a built host
+bundle, which is the only arrangement that can catch that class of bug.
+"""
+
+from __future__ import annotations
+
+import json
+import subprocess
+import sys
+import tempfile
+from pathlib import Path
+
+import pytest
+
+CORE_ROOT = Path(__file__).resolve().parents[1]
+REPOSITORY_ROOT = CORE_ROOT.parents[1]
+HOSTS = {
+ "claude-code": ("claude-code-plugin", "CLAUDE_CODE_PLUGIN"),
+ "cursor": ("cursor-plugin", "CURSOR_PLUGIN"),
+ "codex": ("codex-plugin", "CODEX_PLUGIN"),
+ "kimi": ("kimi-plugin", "KIMI_PLUGIN"),
+ "antigravity": ("antigravity-plugin", "ANTIGRAVITY_PLUGIN"),
+ # Portable: no flush_worker and no hook_runner, so its ONLY sender is the
+ # uninitialised telemetry.py. A native-only test passes here vacuously.
+ "coding-agent": ("mem0-agent-plugin", "CODING_AGENT_PLUGIN"),
+}
+
+
+def _core_dir(directory: str) -> Path:
+ return REPOSITORY_ROOT / "integrations" / directory / "core"
+
+
+def _run(core: Path, data_dir: Path, body: str) -> str:
+ """Execute `body` in a fresh interpreter with only the host's core on sys.path."""
+ script = f"import sys; sys.path.insert(0, {str(core)!r})\n{body}"
+ result = subprocess.run(
+ [sys.executable, "-c", script],
+ capture_output=True,
+ text=True,
+ env={
+ "MEM0_CODE_DATA_DIR": str(data_dir),
+ "PATH": "/usr/bin:/bin",
+ "HOME": str(data_dir),
+ },
+ )
+ assert result.returncode == 0, result.stderr
+ return result.stdout.strip()
+
+
+@pytest.mark.parametrize("harness,spec", sorted(HOSTS.items()))
+def test_identity_resolves_without_init(harness, spec):
+ """Every built host knows what it is with no configuration call at all."""
+ directory, source_tag = spec
+ core = _core_dir(directory)
+ if not core.exists():
+ pytest.skip(f"{directory} is not built in this tree")
+
+ with tempfile.TemporaryDirectory() as tmp:
+ out = _run(
+ core,
+ Path(tmp),
+ "import telemetry; print(telemetry._harness, telemetry._source_tag)",
+ )
+ assert out == f"{harness} {source_tag}"
+
+
+def test_mcp_server_records_the_real_harness():
+ """mcp_server imports telemetry and never initialises it (server.py has no init).
+
+ Its recorded events used to carry harness=generic for every plugin.
+ """
+ core = _core_dir("claude-code-plugin")
+ if not core.exists():
+ pytest.skip("claude-code-plugin is not built in this tree")
+
+ with tempfile.TemporaryDirectory() as tmp:
+ data_dir = Path(tmp)
+ _run(
+ core,
+ data_dir,
+ "import mcp_server, telemetry; telemetry.record('search', trigger='mcp-search')",
+ )
+ spooled = (data_dir / "telemetry.jsonl").read_text(encoding="utf-8").strip()
+
+ event = json.loads(spooled)
+ assert event["properties"]["harness"] == "claude-code"
+ assert event["properties"]["source"] == "CLAUDE_CODE_PLUGIN"
+
+
+def test_the_detached_sender_does_not_relabel_events():
+ """`python3 telemetry.py` is the sender spawn_flush() starts, and never inits.
+
+ source is stamped at record time now, so which process sends is irrelevant.
+ """
+ core = _core_dir("claude-code-plugin")
+ if not core.exists():
+ pytest.skip("claude-code-plugin is not built in this tree")
+
+ with tempfile.TemporaryDirectory() as tmp:
+ data_dir = Path(tmp)
+ _run(core, data_dir, "import telemetry; telemetry.record('search')")
+
+ captured = data_dir / "captured.json"
+ # Drain with a fresh, unconfigured interpreter, capturing the payload
+ # instead of posting it.
+ _run(
+ core,
+ data_dir,
+ "import json, telemetry\n"
+ "sent = []\n"
+ "telemetry._post = lambda payload, url: sent.append(payload) or True\n"
+ "telemetry.flush()\n"
+ f"open({str(captured)!r}, 'w').write(json.dumps(sent))",
+ )
+ payloads = json.loads(captured.read_text(encoding="utf-8"))
+
+ batches = [p for p in payloads if "batch" in p]
+ assert batches, "nothing was sent"
+ properties = batches[0]["batch"][0]["properties"]
+ assert properties["source"] == "CLAUDE_CODE_PLUGIN"
+ assert properties["harness"] == "claude-code"
+
+
+def test_every_event_carries_a_uuid_for_dedupe():
+ core = _core_dir("claude-code-plugin")
+ if not core.exists():
+ pytest.skip("claude-code-plugin is not built in this tree")
+
+ with tempfile.TemporaryDirectory() as tmp:
+ data_dir = Path(tmp)
+ _run(core, data_dir, "import telemetry; telemetry.record('search'); telemetry.record('flush')")
+ lines = (data_dir / "telemetry.jsonl").read_text(encoding="utf-8").strip().splitlines()
+
+ ids = [json.loads(line)["uuid"] for line in lines]
+ assert len(ids) == 2
+ assert len(set(ids)) == 2
+
+
+def test_source_tag_defaults_agree_between_the_two_modules():
+ """configure_harness and telemetry.init must derive the same tag.
+
+ They disagreed: `_plugin` in one and `MEM0__PLUGIN` in the other,
+ so one plugin could emit three different source values depending on which
+ process sent the batch.
+ """
+ core = _core_dir("claude-code-plugin")
+ if not core.exists():
+ pytest.skip("claude-code-plugin is not built in this tree")
+
+ with tempfile.TemporaryDirectory() as tmp:
+ out = _run(
+ core,
+ Path(tmp),
+ "import memory_core, telemetry\n"
+ "memory_core.configure_harness('kimi')\n"
+ "telemetry.init(harness='kimi')\n"
+ "print(memory_core.harness_config()['source_tag'].upper(), telemetry._source_tag)",
+ )
+ left, right = out.split()
+ assert left == right == "KIMI_PLUGIN"
+
+
+def test_the_plugin_declares_its_surface_in_the_body_and_the_headers():
+ """Body and headers both, because only the body works on every backend."""
+ core = _core_dir("claude-code-plugin")
+ if not core.exists():
+ pytest.skip("claude-code-plugin is not built in this tree")
+
+ with tempfile.TemporaryDirectory() as tmp:
+ out = _run(
+ core,
+ Path(tmp),
+ "import json, memory_core\n"
+ "h = memory_core.platform_headers('k')\n"
+ "print(json.dumps({'source': h.get('X-Mem0-Source'),"
+ " 'app': h.get('X-Application'),"
+ " 'client': h.get('X-Mem0-Client'),"
+ " 'auth': h.get('Authorization'),"
+ " 'ctype': h.get('Content-Type')}))",
+ )
+ headers = json.loads(out)
+ assert headers["source"] == "MEM0_PLUGIN"
+ assert headers["app"] == "claude-code"
+ assert headers["client"].startswith("mem0-plugin/")
+ # The transport headers the three call sites relied on must survive.
+ assert headers["auth"] == "Token k"
+ assert headers["ctype"] == "application/json"
+
+
+def _session_start(core: Path, data_dir: Path) -> list[str]:
+ """Drive the real hook_runner session-start path and return lifecycle events."""
+ recorded = "\n".join(
+ [
+ "import io, json, sys",
+ f"sys.path.insert(0, {str(core)!r})",
+ "import telemetry, hook_runner",
+ "seen = []",
+ "telemetry.record = lambda event, **kw: seen.append(event) or None",
+ "telemetry.spawn_flush = lambda: False",
+ # run() reads sys.argv through argparse; it takes no positional args.
+ "sys.argv = ['hook_runner', 'session-start']",
+ "sys.stdin = io.StringIO('{}')",
+ "hook_runner.run()",
+ "print(json.dumps([e for e in seen if e in ('install', 'upgrade')]))",
+ ]
+ )
+ import json as _json
+
+ return _json.loads(_run(core, data_dir, recorded) or "[]")
+
+
+def test_a_fresh_install_reports_install_not_upgrade():
+ """The decision must survive the writes hook_runner does before asking.
+
+ claim_install() is reached only after cache_plugin_api_key() has written
+ `api-key` and EvidenceStore() has created `evidence.sqlite3`. Asking "is the
+ data dir empty" at that point always saw content, so code.install could
+ never fire and every new user was counted as an upgrade.
+ """
+ core = _core_dir("claude-code-plugin")
+ if not core.exists():
+ pytest.skip("claude-code-plugin is not built in this tree")
+
+ with tempfile.TemporaryDirectory() as tmp:
+ data_dir = Path(tmp) / "data"
+ assert _session_start(core, data_dir) == ["install"]
+
+
+def test_the_lifecycle_event_fires_exactly_once():
+ core = _core_dir("claude-code-plugin")
+ if not core.exists():
+ pytest.skip("claude-code-plugin is not built in this tree")
+
+ with tempfile.TemporaryDirectory() as tmp:
+ data_dir = Path(tmp) / "data"
+ first = _session_start(core, data_dir)
+ second = _session_start(core, data_dir)
+ third = _session_start(core, data_dir)
+
+ assert first == ["install"]
+ assert second == []
+ assert third == []
+
+
+def test_an_existing_data_dir_reports_upgrade():
+ core = _core_dir("claude-code-plugin")
+ if not core.exists():
+ pytest.skip("claude-code-plugin is not built in this tree")
+
+ with tempfile.TemporaryDirectory() as tmp:
+ data_dir = Path(tmp) / "data"
+ data_dir.mkdir(parents=True)
+ # A 0.2.x leftover: the data dir survives the upgrade.
+ (data_dir / "requirements.txt").write_text("mem0ai\n", encoding="utf-8")
+ assert _session_start(core, data_dir) == ["upgrade"]
diff --git a/integrations/agent-plugin-core/tests/test_validate.py b/integrations/agent-plugin-core/tests/test_validate.py
new file mode 100644
index 000000000..79df69f54
--- /dev/null
+++ b/integrations/agent-plugin-core/tests/test_validate.py
@@ -0,0 +1,115 @@
+from __future__ import annotations
+
+import json
+import subprocess
+import sys
+from pathlib import Path
+
+
+ROOT = Path(__file__).resolve().parents[1]
+VALIDATE = ROOT / "build" / "validate.py"
+PLUGIN_SCHEMA = "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json"
+
+
+def run_validator(bundle: Path) -> subprocess.CompletedProcess[str]:
+ return subprocess.run(
+ [sys.executable, str(VALIDATE), str(bundle), "--kind", "portable"],
+ capture_output=True,
+ check=False,
+ text=True,
+ )
+
+
+def write_manifest(bundle: Path, schema: str = PLUGIN_SCHEMA) -> None:
+ bundle.mkdir(parents=True, exist_ok=True)
+ (bundle / "plugin.json").write_text(
+ json.dumps({"$schema": schema, "name": "mem0"}),
+ encoding="utf-8",
+ )
+
+
+def test_rejects_wrong_agent_plugin_schema(tmp_path: Path) -> None:
+ bundle = tmp_path / "plugin"
+ write_manifest(bundle, "https://agent-plugins.org/v1.0.0/plugin.schema.json")
+
+ result = run_validator(bundle)
+
+ assert result.returncode == 1
+ assert result.stderr == (
+ "plugin.json.$schema: "
+ "'https://agent-plugins.org/schemas/1.0.0/plugin.schema.json' was expected\n"
+ )
+
+
+def test_rejects_symlink_outside_bundle(tmp_path: Path) -> None:
+ bundle = tmp_path / "plugin"
+ write_manifest(bundle)
+ outside = tmp_path / "outside"
+ outside.mkdir()
+ (bundle / "skills").symlink_to(outside, target_is_directory=True)
+
+ result = run_validator(bundle)
+
+ assert result.returncode == 1
+ assert result.stderr == "skills: symlinks are not allowed in release bundles\n"
+
+
+def test_accepts_minimal_portable_bundle(tmp_path: Path) -> None:
+ bundle = tmp_path / "plugin"
+ write_manifest(bundle)
+
+ result = run_validator(bundle)
+
+ assert result.returncode == 0
+ assert result.stdout == f"Validated portable bundle: {bundle}\n"
+ assert result.stderr == ""
+
+
+def test_rejects_nonconformant_agent_skill(tmp_path: Path) -> None:
+ bundle = tmp_path / "plugin"
+ write_manifest(bundle)
+ skill = bundle / "skills" / "Bad_Name"
+ skill.mkdir(parents=True)
+ (skill / "SKILL.md").write_text(
+ "---\nname: Bad_Name\ndescription: invalid\nunknown: true\n---\n",
+ encoding="utf-8",
+ )
+
+ result = run_validator(bundle)
+
+ assert result.returncode == 1
+ assert "skills/Bad_Name" in result.stderr
+
+
+def run_native_validator(bundle: Path) -> subprocess.CompletedProcess[str]:
+ return subprocess.run(
+ [sys.executable, str(VALIDATE), str(bundle), "--kind", "native"],
+ capture_output=True,
+ check=False,
+ text=True,
+ )
+
+
+def test_native_bundle_rejects_malformed_json(tmp_path: Path) -> None:
+ bundle = tmp_path / "plugin"
+ bundle.mkdir(parents=True)
+ (bundle / "plugin.json").write_text("{bad json", encoding="utf-8")
+
+ result = run_native_validator(bundle)
+
+ assert result.returncode == 1
+ assert "plugin.json" in result.stderr
+
+
+def test_native_bundle_accepts_valid_json(tmp_path: Path) -> None:
+ bundle = tmp_path / "plugin"
+ bundle.mkdir(parents=True)
+ (bundle / "plugin.json").write_text('{"name": "mem0"}', encoding="utf-8")
+ hooks = bundle / "hooks"
+ hooks.mkdir()
+ (hooks / "hooks.json").write_text('{"version": 1}', encoding="utf-8")
+
+ result = run_native_validator(bundle)
+
+ assert result.returncode == 0
+ assert "native" in result.stdout
diff --git a/integrations/agent-plugin-core/typescript/package.json b/integrations/agent-plugin-core/typescript/package.json
new file mode 100644
index 000000000..b9794e88a
--- /dev/null
+++ b/integrations/agent-plugin-core/typescript/package.json
@@ -0,0 +1,14 @@
+{
+ "name": "@mem0/agent-plugin-core",
+ "version": "0.0.0",
+ "private": true,
+ "type": "module",
+ "scripts": {
+ "test": "node --test tests/*.test.ts",
+ "typecheck": "tsc --noEmit"
+ },
+ "devDependencies": {
+ "@types/node": "^22.15.0",
+ "typescript": "^5.6.0"
+ }
+}
diff --git a/integrations/agent-plugin-core/typescript/pnpm-lock.yaml b/integrations/agent-plugin-core/typescript/pnpm-lock.yaml
new file mode 100644
index 000000000..65e364ea3
--- /dev/null
+++ b/integrations/agent-plugin-core/typescript/pnpm-lock.yaml
@@ -0,0 +1,39 @@
+lockfileVersion: '9.0'
+
+settings:
+ autoInstallPeers: true
+ excludeLinksFromLockfile: false
+
+importers:
+
+ .:
+ devDependencies:
+ '@types/node':
+ specifier: ^22.15.0
+ version: 22.20.1
+ typescript:
+ specifier: ^5.6.0
+ version: 5.9.3
+
+packages:
+
+ '@types/node@22.20.1':
+ resolution: {integrity: sha512-EANqOCF9QFyra+4pfxUcX9STKJpCLjMbObVzljIJomAWSnuSIEAvyzEU53GaajbXJEgdh0iEcPL+DGvpUd4k1Q==}
+
+ typescript@5.9.3:
+ resolution: {integrity: sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==}
+ engines: {node: '>=14.17'}
+ hasBin: true
+
+ undici-types@6.21.0:
+ resolution: {integrity: sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==}
+
+snapshots:
+
+ '@types/node@22.20.1':
+ dependencies:
+ undici-types: 6.21.0
+
+ typescript@5.9.3: {}
+
+ undici-types@6.21.0: {}
diff --git a/integrations/agent-plugin-core/typescript/src/formatting.ts b/integrations/agent-plugin-core/typescript/src/formatting.ts
new file mode 100644
index 000000000..8f569cd94
--- /dev/null
+++ b/integrations/agent-plugin-core/typescript/src/formatting.ts
@@ -0,0 +1,70 @@
+export interface MemoryLike {
+ id: string;
+ memory?: string;
+ categories?: string[];
+ createdAt?: Date | string;
+}
+
+export const MAX_OUTPUT_LINES = 200;
+export const MAX_OUTPUT_CHARS = 50_000;
+export const MAX_OUTPUT_BYTES = MAX_OUTPUT_CHARS;
+
+export function formatAge(date: Date | string): string {
+ const minutes = Math.floor((Date.now() - new Date(date).getTime()) / 60_000);
+ if (minutes < 60) return `${minutes}m ago`;
+ const hours = Math.floor(minutes / 60);
+ return hours < 24 ? `${hours}h ago` : `${Math.floor(hours / 24)}d ago`;
+}
+
+export function formatMemoryCompact(memory: MemoryLike): string {
+ const category = memory.categories?.[0] ?? "uncategorized";
+ const age = memory.createdAt ? ` (${formatAge(memory.createdAt)})` : "";
+ return `[${category}] ${memory.memory ?? "(empty)"}${age} [mem0:${memory.id}]`;
+}
+
+export function formatMemoryList(memories: MemoryLike[]): string {
+ return memories.length
+ ? memories.map((memory, index) => `${index + 1}. ${formatMemoryCompact(memory)}`).join("\n")
+ : "No memories found.";
+}
+
+export function formatAddResult(result: unknown): string {
+ const items: MemoryLike[] = Array.isArray(result)
+ ? result
+ : ((result as { results?: MemoryLike[] } | null)?.results ?? (result ? [result as MemoryLike] : []));
+ const pending = items.find((item) => (item as { status?: string }).status === "PENDING") as
+ | { eventId?: string; event_id?: string }
+ | undefined;
+ if (pending) {
+ const id = pending.eventId ?? pending.event_id;
+ return `Memory queued for background extraction${id ? ` (event ${id})` : ""}; it will be searchable shortly.`;
+ }
+ if (!items.length) return "Memory stored.";
+ return `Stored ${items.length} ${items.length === 1 ? "memory" : "memories"}:\n${formatMemoryList(items)}`;
+}
+
+export function groupByCategory(memories: MemoryLike[]): Map {
+ const groups = new Map();
+ for (const memory of memories) {
+ const category = memory.categories?.[0] ?? "uncategorized";
+ groups.set(category, [...(groups.get(category) ?? []), memory]);
+ }
+ return groups;
+}
+
+export function truncateOutput(
+ text: string,
+ maxChars = MAX_OUTPUT_CHARS,
+ maxLines = MAX_OUTPUT_LINES,
+): string {
+ const lines = text.split("\n");
+ if (lines.length <= maxLines && text.length <= maxChars) return text;
+ const kept = lines.slice(0, maxLines);
+ let result = kept.join("\n");
+ const charCapped = result.length > maxChars;
+ if (charCapped) result = result.slice(0, maxChars);
+ const reasons = [];
+ if (kept.length < lines.length) reasons.push(`showing ${kept.length} of ${lines.length} lines`);
+ if (charCapped) reasons.push(`cut at ${Math.floor(maxChars / 1000)}KB`);
+ return `${result}\n\n[Output truncated: ${reasons.join(", ")}]`;
+}
diff --git a/integrations/agent-plugin-core/typescript/src/identity.ts b/integrations/agent-plugin-core/typescript/src/identity.ts
new file mode 100644
index 000000000..6fffdee93
--- /dev/null
+++ b/integrations/agent-plugin-core/typescript/src/identity.ts
@@ -0,0 +1,33 @@
+export interface EntityParams {
+ userId?: string;
+ agentId?: string;
+ runId?: string;
+}
+
+const clean = (value: string | undefined): string | undefined => value?.trim() || undefined;
+
+export function entitySearchFilters(
+ params: EntityParams,
+ defaultUserId: string,
+): Record {
+ const filters: Record = { user_id: clean(params.userId) ?? defaultUserId };
+ const agentId = clean(params.agentId);
+ const runId = clean(params.runId);
+ if (agentId) filters.agent_id = agentId;
+ if (runId) filters.run_id = runId;
+ return filters;
+}
+
+export function entityAddParams(params: EntityParams, defaultUserId: string): Record {
+ const values: Record = { userId: clean(params.userId) ?? defaultUserId };
+ const agentId = clean(params.agentId);
+ const runId = clean(params.runId);
+ if (agentId) values.agentId = agentId;
+ if (runId) values.runId = runId;
+ return values;
+}
+
+export function parseProjectFromRemote(remote: string): string | null {
+ const match = remote.trim().match(/[:/]([^/:]+)\/([^/:]+?)(?:\.git)?\/?$/);
+ return match ? `${match[1]}-${match[2]}` : null;
+}
diff --git a/integrations/agent-plugin-core/typescript/src/lifecycle.ts b/integrations/agent-plugin-core/typescript/src/lifecycle.ts
new file mode 100644
index 000000000..738ccc1c7
--- /dev/null
+++ b/integrations/agent-plugin-core/typescript/src/lifecycle.ts
@@ -0,0 +1,180 @@
+import type { MemoryLike } from "./formatting.ts";
+import { formatMemoryCompact } from "./formatting.ts";
+import { RECALL_HEADING } from "./prompts.ts";
+
+const MAX_RECALL_QUERY_CHARS = 6_000;
+export const DEFAULT_MAX_CONTEXT_CHARS = 4_000;
+
+const SECRET_PATTERNS: Array<[RegExp, string]> = [
+ [/(authorization\s*[:=]\s*(?:bearer|token)\s+)[^\s"']+/gi, "$1[REDACTED]"],
+ [
+ /((?:api[_-]?key|secret[_-]?access[_-]?key|session[_-]?token)\s*[:=]\s*)[^\s"']+/gi,
+ "$1[REDACTED]",
+ ],
+ [
+ /((?:access[_-]?token|refresh[_-]?token|password|credential)\s*[:=]\s*)[^\s&"']+/gi,
+ "$1[REDACTED]",
+ ],
+ [/\b(?:sk|m0|mem0_sk|psk)-[A-Za-z0-9_-]{12,}\b/g, "[REDACTED]"],
+ [/\b(?:ASIA|AKIA)[A-Z0-9]{12,}\b/g, "[REDACTED]"],
+ [/\b(?:ghp_|github_pat_|xox[baprs]-)[A-Za-z0-9_-]{12,}\b/g, "[REDACTED]"],
+ [/-----BEGIN [^-]*PRIVATE KEY-----[\s\S]*?-----END [^-]*PRIVATE KEY-----/g, "[REDACTED]"],
+];
+
+export function redactSecrets(value: unknown): string {
+ let text =
+ typeof value === "string"
+ ? value
+ : (JSON.stringify(value, null, 0) ?? String(value));
+ for (const [pattern, replacement] of SECRET_PATTERNS) text = text.replace(pattern, replacement);
+ return text;
+}
+
+export function boundedText(value: unknown, limit: number): string {
+ const text = redactSecrets(value).trim();
+ return text.length <= limit ? text : `${text.slice(0, limit)}\n...[truncated ${text.length - limit} chars]`;
+}
+
+interface MessageLike {
+ role: string;
+ content?: unknown;
+}
+
+function extractText(content: unknown): string | null {
+ if (typeof content === "string") return content;
+ if (!Array.isArray(content)) return null;
+ const text = content
+ .filter(
+ (block): block is { type: "text"; text: string } =>
+ typeof block === "object" &&
+ block !== null &&
+ (block as { type?: unknown }).type === "text" &&
+ typeof (block as { text?: unknown }).text === "string",
+ )
+ .map((block) => block.text)
+ .join("\n");
+ return text || null;
+}
+
+export function extractConversation(
+ messages: MessageLike[],
+): Array<{ role: "user" | "assistant"; content: string }> {
+ const conversation: Array<{ role: "user" | "assistant"; content: string }> = [];
+ for (const message of messages) {
+ if (message.role !== "user" && message.role !== "assistant") continue;
+ const text = extractText(message.content);
+ if (!text) continue;
+ const content = redactSecrets(text).trim();
+ if (content) conversation.push({ role: message.role, content });
+ }
+ return conversation;
+}
+
+interface RecallOptions {
+ heading?: string;
+ maxChars?: number;
+ seenIds?: Set;
+ timeoutMs?: number;
+}
+
+interface MemoryLifecycleOptions {
+ recallHeading?: string;
+ maxContextChars?: number;
+ recallTimeoutMs?: number;
+}
+
+/** Shared lifecycle policy. Host adapters only translate native events into these operations. */
+class MemoryLifecycle {
+ readonly #seenMemoryIds = new Set();
+ readonly #options: MemoryLifecycleOptions;
+
+ constructor(options: MemoryLifecycleOptions = {}) {
+ this.#options = options;
+ }
+
+ beginSession(): void {
+ this.#seenMemoryIds.clear();
+ }
+
+ prepareConversation(
+ messages: MessageLike[],
+ ): Array<{ role: "user" | "assistant"; content: string }> {
+ return extractConversation(messages);
+ }
+
+ prepareUserText(value: unknown): string {
+ return redactSecrets(value).trim();
+ }
+
+ recall(
+ prompt: string,
+ enabled: boolean,
+ search: (query: string) => Promise<{ results?: unknown[] }>,
+ ): Promise {
+ return buildRecallContext(prompt, enabled, search, {
+ heading: this.#options.recallHeading,
+ maxChars: this.#options.maxContextChars,
+ seenIds: this.#seenMemoryIds,
+ timeoutMs: this.#options.recallTimeoutMs,
+ });
+ }
+}
+
+export function createMemoryLifecycle(
+ options: MemoryLifecycleOptions = {},
+): MemoryLifecycle {
+ return new MemoryLifecycle(options);
+}
+
+export async function buildRecallContext(
+ prompt: string,
+ enabled: boolean,
+ search: (query: string) => Promise<{ results?: unknown[] }>,
+ options: RecallOptions = {},
+): Promise {
+ if (!enabled) return "";
+ const query = boundedText(prompt, MAX_RECALL_QUERY_CHARS);
+ if (!query) return "";
+
+ try {
+ let timer: ReturnType | undefined;
+ let response: { results?: unknown[] } | null;
+ try {
+ const timeout = new Promise((resolve) => {
+ timer = setTimeout(() => resolve(null), options.timeoutMs ?? 2_000);
+ });
+ response = await Promise.race([search(query), timeout]);
+ } finally {
+ if (timer) clearTimeout(timer);
+ }
+ if (!response) return "";
+ const memories = (response.results ?? []) as MemoryLike[];
+ const unseen = memories.filter((memory) => !options.seenIds?.has(memory.id));
+ if (!unseen.length) return "";
+
+ const prefix = `\n${options.heading ?? RECALL_HEADING}\n`;
+ const suffix = "\n";
+ const maxChars = options.maxChars ?? DEFAULT_MAX_CONTEXT_CHARS;
+ const lines: string[] = [];
+ for (const memory of unseen) {
+ const line = `${lines.length + 1}. ${redactSecrets(formatMemoryCompact(memory))
+ .replace(/\s+/g, " ")
+ .trim()}`;
+ const candidate = prefix + [...lines, line].join("\n") + suffix;
+ if (candidate.length > maxChars) {
+ if (!lines.length) {
+ const available = maxChars - prefix.length - suffix.length;
+ if (available > 1) lines.push(`${line.slice(0, available - 1).trimEnd()}โฆ`);
+ }
+ break;
+ }
+ lines.push(line);
+ options.seenIds?.add(memory.id);
+ }
+ if (!lines.length) return "";
+ if (unseen[0] && !options.seenIds?.has(unseen[0].id)) options.seenIds?.add(unseen[0].id);
+ return prefix + lines.join("\n") + suffix;
+ } catch {
+ return "";
+ }
+}
diff --git a/integrations/agent-plugin-core/typescript/src/prompts.ts b/integrations/agent-plugin-core/typescript/src/prompts.ts
new file mode 100644
index 000000000..cb4d4e07b
--- /dev/null
+++ b/integrations/agent-plugin-core/typescript/src/prompts.ts
@@ -0,0 +1,10 @@
+export const SEARCH_WHEN =
+ "before repeating investigation or when earlier decisions, fixes, commands, or results may help";
+
+export const SEARCH_TOOL_DESCRIPTION = `Search memories from earlier work in this repository. Use it ${SEARCH_WHEN}.`;
+export const SEARCH_QUERY_DESCRIPTION = "A direct question about earlier work in this repository.";
+export const RECALL_HEADING = "Mem0 found these relevant memories from earlier work in this repository:";
+
+export const USER_SEARCH_TOOL_DESCRIPTION = `Search memories from earlier work. Use it ${SEARCH_WHEN}.`;
+export const USER_SEARCH_QUERY_DESCRIPTION = "A direct question about earlier work.";
+export const USER_RECALL_HEADING = "Mem0 found these relevant memories from earlier work:";
diff --git a/integrations/agent-plugin-core/typescript/src/scoping.ts b/integrations/agent-plugin-core/typescript/src/scoping.ts
new file mode 100644
index 000000000..055ef2222
--- /dev/null
+++ b/integrations/agent-plugin-core/typescript/src/scoping.ts
@@ -0,0 +1,50 @@
+export type Scope = "project" | "session" | "global";
+
+export interface ScopeContext {
+ userId: string;
+ appId: string;
+ runId: string;
+}
+
+export function normalizeScope(value: unknown): Scope {
+ return value === "session" || value === "global" ? value : "project";
+}
+
+export function resolveToolScope(requested: Scope | undefined, configured: Scope): Scope {
+ const scope = requested ?? configured;
+ if (scope === "global" && configured !== "global") {
+ throw new Error("Select global scope in the plugin settings or /mem0-scope command first.");
+ }
+ return scope;
+}
+
+function validateContext(scope: Scope, context: ScopeContext): void {
+ const keys: (keyof ScopeContext)[] = ["userId"];
+ if (scope !== "global") keys.push("appId");
+ if (scope === "session") keys.push("runId");
+ for (const key of keys) {
+ if (!context[key]?.trim() || /^\*+$/.test(context[key].trim())) {
+ throw new Error(`Invalid memory scope ${key}`);
+ }
+ }
+}
+
+export function scopeSearchFilters(scope: Scope, context: ScopeContext): Record {
+ validateContext(scope, context);
+ if (scope === "session") {
+ return { user_id: context.userId, app_id: context.appId, run_id: context.runId };
+ }
+ return scope === "global"
+ ? { user_id: context.userId }
+ : { user_id: context.userId, app_id: context.appId };
+}
+
+export function scopeAddParams(scope: Scope, context: ScopeContext): Record {
+ validateContext(scope, context);
+ if (scope === "session") {
+ return { userId: context.userId, appId: context.appId, runId: context.runId };
+ }
+ return scope === "global"
+ ? { userId: context.userId }
+ : { userId: context.userId, appId: context.appId };
+}
diff --git a/integrations/agent-plugin-core/typescript/src/telemetry.ts b/integrations/agent-plugin-core/typescript/src/telemetry.ts
new file mode 100644
index 000000000..2b6c5286e
--- /dev/null
+++ b/integrations/agent-plugin-core/typescript/src/telemetry.ts
@@ -0,0 +1,247 @@
+import { randomUUID } from "node:crypto";
+
+import { redactSecrets } from "./lifecycle.ts";
+
+const POSTHOG_API_KEY = "phc_hgJkUVJFYtmaJqrvf6CYN67TIQ8yhXAkWzUn9AMU4yX";
+const POSTHOG_BATCH_URL = "https://us.i.posthog.com/batch/";
+const OFF_VALUES = new Set(["false", "0", "no", "off"]);
+const PRIVATE_KEYS = new Set([
+ "apikey",
+ "authorization",
+ "password",
+ "query",
+ "secret",
+ "prompt",
+ "token",
+ "text",
+ "memory",
+ "message",
+ "error",
+ "path",
+ "cwd",
+ "userid",
+ "agentid",
+ "runid",
+ "repoid",
+ "repositoryid",
+ "projectid",
+ "appid",
+ "filters",
+]);
+
+export interface TelemetryConfig {
+ host: string;
+ source: string;
+ version: string;
+ distinctId: string | (() => string | undefined);
+ delivery?: (batch: Record[]) => void | Promise;
+ flushThreshold?: number;
+ flushIntervalMs?: number;
+ maxQueueSize?: number;
+ commonProperties?: Record;
+ eventName?: (event: string) => string;
+ enabled?: () => boolean;
+}
+
+export function isTelemetryEnabled(): boolean {
+ const value = process.env.MEM0_TELEMETRY;
+ return value === undefined || !OFF_VALUES.has(value.toLowerCase());
+}
+
+function safeValue(value: unknown): unknown {
+ if (typeof value === "string") return redactSecrets(value);
+ if (Array.isArray(value)) return value.map(safeValue);
+ if (value && typeof value === "object") {
+ return Object.fromEntries(
+ Object.entries(value)
+ .filter(([key]) => !PRIVATE_KEYS.has(key.toLowerCase().replace(/[^a-z]/g, "")))
+ .map(([key, nested]) => [key, safeValue(nested)]),
+ );
+ }
+ return value;
+}
+
+function safeProperties(properties: Record): Record {
+ return safeValue(properties) as Record;
+}
+
+export function errorKind(error: unknown): string {
+ const text = (error instanceof Error ? error.message : String(error)).toLowerCase();
+ if (text.includes("timeout") || text.includes("aborted")) return "timeout";
+ if (text.includes("401") || text.includes("403") || text.includes("unauthor")) return "auth";
+ if (text.includes("429") || text.includes("rate limit")) return "rate-limited";
+ if (/50[0234]/.test(text)) return "server-error";
+ if (text.includes("400") || text.includes("422")) return "bad-request";
+ if (text.includes("fetch failed") || text.includes("enotfound")) return "network";
+ return error instanceof Error ? error.constructor.name : "other";
+}
+
+// Delivery is retried in memory, not spooled to disk, and that is a decision
+// rather than an omission. The Python core spools because its hooks are separate
+// processes that fire per tool call and exit immediately, so nothing survives
+// without a file. These plugins are loaded into a host that lives for a whole
+// session, so re-queueing covers the same transient failures without the claim
+// and lease machinery a correct cross-process spool needs. What that leaves
+// uncovered is narrow: a session that both starts and ends with no connectivity.
+const RETRY_BACKOFF_CEILING_MS = 60_000;
+// Consecutive failed flushes before the queue is dropped. Deliberately NOT the
+// same thing as Python's budget, which rides in the claim filename and so
+// follows one batch: this counter lives in the closure and counts the outage,
+// not the payload. Events captured between attempts join the same queue and go
+// with it. Per-batch accounting would need an attempt count on every event, and
+// the queue is already bounded, so the simpler rule is the one in force here.
+// Without any bound a payload the server will never accept is retried for the
+// whole session and, now that the backlog is preferred over new events, holds
+// the queue against everything behind it.
+const MAX_DELIVERY_ATTEMPTS = 5;
+
+export function createTelemetry(config: TelemetryConfig) {
+ let queue: Record[] = [];
+ let timer: ReturnType | undefined;
+ let consecutiveFailures = 0;
+ let retryNotBefore = 0;
+ let exitFlushAttempted = false;
+ let flushing = false;
+ const flushThreshold = config.flushThreshold ?? 10;
+ const maxQueueSize = config.maxQueueSize ?? 100;
+
+ const deliver = config.delivery ?? (async (batch: Record[]) => {
+ const response = await fetch(POSTHOG_BATCH_URL, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ api_key: POSTHOG_API_KEY, batch }),
+ signal: AbortSignal.timeout(3_000),
+ });
+ // fetch only rejects on a network-level failure. Without this check a 500,
+ // a 503 or a 429 resolved normally and the batch was counted as delivered
+ // and dropped, which is the likelier outage than a refused connection.
+ // Any non-2xx is retried, matching the Python core: the backoff and the
+ // queue bound contain a payload that will never be accepted, because the
+ // re-queued batch sits at the front and is the first thing evicted.
+ if (!response.ok) throw new Error(`posthog responded ${response.status}`);
+ });
+
+ async function flush(force = false): Promise {
+ // One at a time. Two overlapping flushes each detach the queue and each
+ // prepend their own batch back on failure, so the later batch lands in front
+ // of the earlier one and the truncation then drops the OLDER events first,
+ // inverting the priority the failure path exists to establish. A second
+ // caller returns immediately; the queue waits for the next flush.
+ if (flushing) return;
+ if (!queue.length) return;
+ // `force` skips the cooldown. beforeExit is the last chance this process
+ // gets, and gating it on the same backoff meant that after any failure the
+ // exit flush did nothing and the queue died with the process, which is the
+ // loss this whole mechanism exists to prevent.
+ if (!force && Date.now() < retryNotBefore) return;
+ const batch = queue;
+ queue = [];
+ flushing = true;
+ try {
+ await deliver(batch);
+ consecutiveFailures = 0;
+ retryNotBefore = 0;
+ } catch {
+ // Put it back. Detaching the batch and swallowing the error deleted the
+ // events outright, so any blip silently dropped telemetry with nothing
+ // recording that it had happened. Every event carries a uuid, so a retry
+ // that duplicates one PostHog already accepted is collapsed there.
+ //
+ consecutiveFailures += 1;
+ if (consecutiveFailures >= MAX_DELIVERY_ATTEMPTS) {
+ // Give up on the queue so a failing outage cannot hold it for the
+ // session. This drops whatever is queued now, which includes events
+ // captured during the outage, not only the batch that kept failing.
+ consecutiveFailures = 0;
+ retryNotBefore = 0;
+ return;
+ }
+ // Keep the FRONT on overflow, so the batch being retried survives and a
+ // new event is what gets dropped. Matches the Python core, where record()
+ // refuses new events once the spool is full rather than evicting the
+ // backlog. Keeping the newest would throw away exactly the events this
+ // retry exists to save.
+ queue = [...batch, ...queue].slice(0, maxQueueSize);
+ retryNotBefore = Date.now() + Math.min(2 ** consecutiveFailures * 1_000, RETRY_BACKOFF_CEILING_MS);
+ } finally {
+ flushing = false;
+ }
+ }
+
+ function beforeExit(): void {
+ // Once, and only once. Node re-emits beforeExit whenever the handler
+ // schedules more async work, so an unconditional forced flush looped until
+ // the attempt budget was spent: five attempts against a 3s delivery timeout
+ // is fifteen seconds added to the shutdown of whatever editor or CLI is
+ // hosting this. The backoff used to end that loop after one attempt, and
+ // removing it for the forced path removed the only thing bounding it.
+ if (exitFlushAttempted) return;
+ exitFlushAttempted = true;
+ void flush(true);
+ }
+
+ function build(event: string, properties: Record = {}): Record | null {
+ if (!(config.enabled?.() ?? isTelemetryEnabled())) return null;
+ try {
+ const distinctId = typeof config.distinctId === "function" ? config.distinctId() : config.distinctId;
+ if (!distinctId) return null;
+ return {
+ event: config.eventName?.(event) ?? event,
+ distinct_id: distinctId,
+ // Stamped once, at capture. This is what makes retrying safe: a batch
+ // re-sent after a failure carries the same ids, so PostHog collapses
+ // anything it already accepted instead of counting it twice.
+ uuid: randomUUID(),
+ // Capture time, not ingestion time. Events now sit through backoff and
+ // across a whole outage, so without this PostHog records them whenever
+ // delivery happened to succeed. It also matters for the uuid dedupe
+ // above, whose key includes the event date.
+ timestamp: new Date().toISOString(),
+ properties: {
+ ...safeProperties(properties),
+ ...safeProperties(config.commonProperties ?? {}),
+ host: config.host,
+ source: config.source,
+ language: "node",
+ plugin_version: config.version,
+ node_version: process.version,
+ os: process.platform,
+ $process_person_profile: false,
+ $lib: "posthog-node",
+ },
+ };
+ } catch {
+ return null;
+ }
+ }
+
+ function capture(event: string, properties: Record = {}): void {
+ try {
+ const payload = build(event, properties);
+ if (!payload) return;
+ // Full means drop this event, not evict the backlog. Same rule as the
+ // failure path above and as Python's record().
+ if (queue.length >= maxQueueSize) return;
+ queue.push(payload);
+ if (!timer) {
+ timer = setInterval(() => void flush(), config.flushIntervalMs ?? 5_000);
+ timer.unref?.();
+ process.on("beforeExit", beforeExit);
+ }
+ if (queue.length >= flushThreshold) void flush();
+ } catch {
+ // Telemetry must never affect plugin behavior.
+ }
+ }
+
+ function resetForTesting(): void {
+ queue = [];
+ consecutiveFailures = 0;
+ retryNotBefore = 0;
+ if (timer) clearInterval(timer);
+ timer = undefined;
+ process.off("beforeExit", beforeExit);
+ }
+
+ return { build, capture, flush, resetForTesting, queueForTesting: () => queue };
+}
diff --git a/integrations/agent-plugin-core/typescript/tests/formatting.test.ts b/integrations/agent-plugin-core/typescript/tests/formatting.test.ts
new file mode 100644
index 000000000..d96a2cf2c
--- /dev/null
+++ b/integrations/agent-plugin-core/typescript/tests/formatting.test.ts
@@ -0,0 +1,39 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import {
+ MAX_OUTPUT_CHARS,
+ MAX_OUTPUT_LINES,
+ formatAddResult,
+ formatAge,
+ formatMemoryCompact,
+ formatMemoryList,
+ truncateOutput,
+} from "../src/formatting.ts";
+
+test("memory formatting preserves the existing compact host output", () => {
+ const now = Date.now();
+ assert.equal(formatAge(new Date(now - 30 * 60_000)), "30m ago");
+ assert.match(
+ formatMemoryCompact({ id: "abc", memory: "Dark mode", categories: ["preference"] }),
+ /^\[preference\] Dark mode \[mem0:abc\]$/,
+ );
+ assert.equal(formatMemoryList([]), "No memories found.");
+ assert.match(formatMemoryList([{ id: "1", memory: "A" }, { id: "2", memory: "B" }]), /^1\..*\n2\./);
+});
+
+test("write formatting handles pending, stored, and empty results", () => {
+ assert.equal(
+ formatAddResult({ eventId: "evt-9", status: "PENDING" }),
+ "Memory queued for background extraction (event evt-9); it will be searchable shortly.",
+ );
+ assert.match(formatAddResult([{ id: "1" }, { id: "2" }]), /^Stored 2 memories:/);
+ assert.equal(formatAddResult([]), "Memory stored.");
+});
+
+test("output truncation preserves small output and bounds large output", () => {
+ assert.equal(truncateOutput("a\nb"), "a\nb");
+ const many = Array.from({ length: MAX_OUTPUT_LINES + 1 }, (_, index) => `line ${index}`).join("\n");
+ assert.match(truncateOutput(many), /showing 200 of 201 lines/);
+ assert.match(truncateOutput("x".repeat(MAX_OUTPUT_CHARS + 1)), /cut at 50KB/);
+});
diff --git a/integrations/agent-plugin-core/typescript/tests/identity.test.ts b/integrations/agent-plugin-core/typescript/tests/identity.test.ts
new file mode 100644
index 000000000..c789f766f
--- /dev/null
+++ b/integrations/agent-plugin-core/typescript/tests/identity.test.ts
@@ -0,0 +1,18 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { entityAddParams, entitySearchFilters, parseProjectFromRemote } from "../src/identity.ts";
+
+test("parses common git remote forms", () => {
+ assert.equal(parseProjectFromRemote("git@github.com-work:mem0ai/mem0.git"), "mem0ai-mem0");
+ assert.equal(parseProjectFromRemote("https://github.com/mem0ai/mem0/"), "mem0ai-mem0");
+ assert.equal(parseProjectFromRemote("not-a-remote"), null);
+ assert.equal(parseProjectFromRemote(""), null);
+});
+
+test("entity filters trim overrides and preserve API casing", () => {
+ const params = { userId: " alice ", agentId: " agent ", runId: " " };
+ assert.deepEqual(entitySearchFilters(params, "default"), { user_id: "alice", agent_id: "agent" });
+ assert.deepEqual(entityAddParams(params, "default"), { userId: "alice", agentId: "agent" });
+ assert.deepEqual(entitySearchFilters({ userId: " " }, "default"), { user_id: "default" });
+});
diff --git a/integrations/agent-plugin-core/typescript/tests/lifecycle.test.ts b/integrations/agent-plugin-core/typescript/tests/lifecycle.test.ts
new file mode 100644
index 000000000..7e1776eae
--- /dev/null
+++ b/integrations/agent-plugin-core/typescript/tests/lifecycle.test.ts
@@ -0,0 +1,120 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import {
+ boundedText,
+ buildRecallContext,
+ createMemoryLifecycle,
+ extractConversation,
+ redactSecrets,
+} from "../src/lifecycle.ts";
+
+test("one lifecycle owns recall state and resets it for a new session", async () => {
+ const lifecycle = createMemoryLifecycle({ recallTimeoutMs: 50 });
+ const search = async () => ({ results: [{ id: "m1", memory: "Use pnpm" }] });
+
+ assert.match(await lifecycle.recall("package manager", true, search), /Use pnpm/);
+ assert.equal(await lifecycle.recall("package manager", true, search), "");
+
+ lifecycle.beginSession();
+ assert.match(await lifecycle.recall("package manager", true, search), /Use pnpm/);
+});
+
+test("one lifecycle owns capture preparation", () => {
+ const lifecycle = createMemoryLifecycle();
+
+ assert.deepEqual(
+ lifecycle.prepareConversation([
+ { role: "user", content: "password=secret-value" },
+ { role: "assistant", content: "Configured it" },
+ ]),
+ [
+ { role: "user", content: "password=[REDACTED]" },
+ { role: "assistant", content: "Configured it" },
+ ],
+ );
+});
+
+test("capture preserves long prompts and responses while redacting secrets", () => {
+ const lifecycle = createMemoryLifecycle();
+ const prompt = "Repository question. ".repeat(2000) + "Final requirement. api_key=hidden-user-secret";
+ const answer = "Repository answer. ".repeat(4000) + "Final detail. password=hidden-agent-secret";
+ assert.deepEqual(lifecycle.prepareConversation([
+ { role: "user", content: prompt },
+ { role: "assistant", content: [{ type: "text", text: answer }] },
+ ]), [
+ { role: "user", content: redactSecrets(prompt) },
+ { role: "assistant", content: redactSecrets(answer) },
+ ]);
+ assert.equal(lifecycle.prepareUserText(prompt), redactSecrets(prompt));
+});
+
+test("redacts Claude-equivalent credentials before content leaves the host", () => {
+ const privateKey = "-----BEGIN PRIVATE KEY-----\nsecret\n-----END PRIVATE KEY-----";
+ const input = [
+ "Authorization: Bearer top-secret-token",
+ "api_key=super-secret-value",
+ "password=hunter2",
+ "ghp_abcdefghijklmnopqrstuvwxyz123456",
+ privateKey,
+ ].join("\n");
+
+ const output = redactSecrets(input);
+ assert.equal(output.includes("top-secret-token"), false);
+ assert.equal(output.includes("super-secret-value"), false);
+ assert.equal(output.includes("hunter2"), false);
+ assert.equal(output.includes("ghp_"), false);
+ assert.equal(output.includes("secret\n-----END"), false);
+ assert.match(output, /\[REDACTED\]/);
+});
+
+test("bounds redacted content and reports the omitted character count", () => {
+ assert.equal(boundedText(" abc ", 10), "abc");
+ assert.equal(boundedText("abcdefgh", 5), "abcde\n...[truncated 3 chars]");
+});
+
+test("normalizes and sanitizes user/assistant conversation content", () => {
+ const messages = [
+ { role: "system", content: "ignored" },
+ { role: "user", content: [{ type: "text", text: "token=m0-abcdefghijklmnop" }] },
+ { role: "assistant", content: [{ type: "tool_use" }, { type: "text", text: "done" }] },
+ ];
+
+ assert.deepEqual(extractConversation(messages), [
+ { role: "user", content: "token=[REDACTED]" },
+ { role: "assistant", content: "done" },
+ ]);
+});
+
+test("recall is bounded, fail-open, and de-duplicates already injected memories", async () => {
+ const seen = new Set(["old"]);
+ const search = async () => ({
+ results: [
+ { id: "old", memory: "already shown" },
+ { id: "new", memory: `api_key=hidden ${"x".repeat(100)}` },
+ ],
+ });
+
+ const output = await buildRecallContext("what changed?", true, search, {
+ maxChars: 240,
+ seenIds: seen,
+ });
+ assert.equal(output.includes("already shown"), false);
+ assert.equal(output.includes("hidden"), false);
+ assert.ok(output.length <= 240);
+ assert.equal(seen.has("new"), true);
+ assert.equal(
+ await buildRecallContext("what changed?", true, async () => {
+ throw new Error("offline");
+ }),
+ "",
+ );
+});
+
+test("recall times out without blocking the host turn", async () => {
+ const never = () => new Promise<{ results?: unknown[] }>(() => {});
+ const started = Date.now();
+
+ assert.equal(await buildRecallContext("hello", true, never, { timeoutMs: 5 }), "");
+ assert.ok(Date.now() - started < 100);
+});
diff --git a/integrations/agent-plugin-core/typescript/tests/prompts.test.ts b/integrations/agent-plugin-core/typescript/tests/prompts.test.ts
new file mode 100644
index 000000000..3090c1d51
--- /dev/null
+++ b/integrations/agent-plugin-core/typescript/tests/prompts.test.ts
@@ -0,0 +1,31 @@
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import test from "node:test";
+
+import { buildRecallContext } from "../src/lifecycle.ts";
+import {
+ RECALL_HEADING,
+ SEARCH_QUERY_DESCRIPTION,
+ SEARCH_TOOL_DESCRIPTION,
+ USER_RECALL_HEADING,
+} from "../src/prompts.ts";
+
+const pythonSource = (name: string) =>
+ readFileSync(new URL(`../../python/${name}`, import.meta.url), "utf8").replace(/"\s*\n\s*"/g, "");
+
+test("search prompts match the Python core", () => {
+ assert.ok(pythonSource("mcp_server.py").includes(SEARCH_TOOL_DESCRIPTION));
+ assert.ok(pythonSource("mcp_server.py").includes(SEARCH_QUERY_DESCRIPTION));
+ assert.ok(pythonSource("hook_runner.py").includes(RECALL_HEADING));
+});
+
+test("recall context uses the repository heading unless the host overrides it", async () => {
+ const search = async () => ({ results: [{ id: "m1", memory: "Use pnpm" }] });
+
+ assert.ok((await buildRecallContext("package manager", true, search)).includes(RECALL_HEADING));
+ assert.ok(
+ (await buildRecallContext("package manager", true, search, { heading: USER_RECALL_HEADING })).includes(
+ USER_RECALL_HEADING,
+ ),
+ );
+});
diff --git a/integrations/agent-plugin-core/typescript/tests/scoping.test.ts b/integrations/agent-plugin-core/typescript/tests/scoping.test.ts
new file mode 100644
index 000000000..266457649
--- /dev/null
+++ b/integrations/agent-plugin-core/typescript/tests/scoping.test.ts
@@ -0,0 +1,44 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { normalizeScope, resolveToolScope, scopeAddParams, scopeSearchFilters } from "../src/scoping.ts";
+
+const context = { userId: "u", appId: "app", runId: "run" };
+
+test("normalizes unknown scope to project", () => {
+ assert.equal(normalizeScope("session"), "session");
+ assert.equal(normalizeScope("global"), "global");
+ assert.equal(normalizeScope("invalid"), "project");
+});
+
+test("resolves project, session, and global search filters", () => {
+ assert.deepEqual(scopeSearchFilters("project", context), { user_id: "u", app_id: "app" });
+ assert.deepEqual(scopeSearchFilters("session", context), { user_id: "u", app_id: "app", run_id: "run" });
+ assert.deepEqual(scopeSearchFilters("global", context), { user_id: "u" });
+});
+
+test("resolves camel-case add params", () => {
+ assert.deepEqual(scopeAddParams("project", context), { userId: "u", appId: "app" });
+ assert.deepEqual(scopeAddParams("session", context), { userId: "u", appId: "app", runId: "run" });
+ assert.deepEqual(scopeAddParams("global", context), { userId: "u" });
+});
+
+test("rejects empty and wildcard identities before building filters or writes", () => {
+ for (const invalid of ["", " ", "*", "***"]) {
+ for (const scope of ["project", "session"] as const) {
+ for (const resolve of [scopeSearchFilters, scopeAddParams]) {
+ assert.throws(() => resolve(scope, { ...context, appId: invalid }), /appId/);
+ assert.throws(() => resolve(scope, { ...context, userId: invalid }), /userId/);
+ }
+ }
+ assert.throws(() => scopeSearchFilters("session", { ...context, runId: invalid }), /runId/);
+ }
+});
+
+
+test("tools cannot enable global scope without a user-configured global default", () => {
+ assert.throws(() => resolveToolScope("global", "project"), /Select global/);
+ assert.throws(() => resolveToolScope("global", "session"), /Select global/);
+ assert.equal(resolveToolScope("global", "global"), "global");
+ assert.equal(resolveToolScope("session", "project"), "session");
+});
diff --git a/integrations/agent-plugin-core/typescript/tests/telemetry.test.ts b/integrations/agent-plugin-core/typescript/tests/telemetry.test.ts
new file mode 100644
index 000000000..cf9671682
--- /dev/null
+++ b/integrations/agent-plugin-core/typescript/tests/telemetry.test.ts
@@ -0,0 +1,371 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { createTelemetry, errorKind } from "../src/telemetry.ts";
+
+test("telemetry preserves host names and strips sensitive properties", async () => {
+ const delivered: Record[][] = [];
+ const telemetry = createTelemetry({
+ host: "deepseek",
+ source: "DEEPSEEK_HARNESS",
+ version: "1.2.3",
+ distinctId: "person",
+ delivery: async (batch) => {
+ delivered.push(batch);
+ },
+ });
+
+ telemetry.capture("deepseek.tool.search_memory", {
+ success: true,
+ query: "secret",
+ apiKey: "key",
+ cwd: "/private/repo",
+ repo_id: "raw-repo",
+ query_chars: 6,
+ });
+ await telemetry.flush();
+ telemetry.resetForTesting();
+
+ const event = delivered[0][0] as { event: string; properties: Record };
+ assert.equal(event.event, "deepseek.tool.search_memory");
+ assert.deepEqual(event.properties, {
+ success: true,
+ query_chars: 6,
+ host: "deepseek",
+ source: "DEEPSEEK_HARNESS",
+ language: "node",
+ plugin_version: "1.2.3",
+ node_version: process.version,
+ os: process.platform,
+ $process_person_profile: false,
+ $lib: "posthog-node",
+ });
+});
+
+test("all false-like opt-out values suppress events", async () => {
+ const original = process.env.MEM0_TELEMETRY;
+ try {
+ for (const value of ["false", "0", "no", "OFF"]) {
+ process.env.MEM0_TELEMETRY = value;
+ let delivered = false;
+ const telemetry = createTelemetry({
+ host: "pi",
+ source: "PI_AGENT_PLUGIN",
+ version: "1",
+ distinctId: "person",
+ delivery: async () => {
+ delivered = true;
+ },
+ });
+ telemetry.capture("pi.test");
+ await telemetry.flush();
+ telemetry.resetForTesting();
+ assert.equal(delivered, false);
+ }
+ } finally {
+ if (original === undefined) delete process.env.MEM0_TELEMETRY;
+ else process.env.MEM0_TELEMETRY = original;
+ }
+});
+
+test("telemetry redacts secrets nested inside allowed properties", () => {
+ const secret = "sk-eval-12345678901234567890";
+ const telemetry = createTelemetry({
+ host: "pi",
+ source: "PI_AGENT_PLUGIN",
+ version: "1",
+ distinctId: "person",
+ });
+
+ const event = telemetry.build("pi.test", {
+ note: `failure contained ${secret}`,
+ details: { authorization: `Bearer ${secret}`, count: 2 },
+ });
+ telemetry.resetForTesting();
+
+ const serialized = JSON.stringify(event);
+ assert.equal(serialized.includes(secret), false);
+ assert.equal(serialized.includes("[REDACTED]"), true);
+ assert.equal((event?.properties as { details: { count: number } }).details.count, 2);
+});
+
+for (const key of ["password", "token", "secret", "authorization"]) {
+ test(`telemetry removes ${key} from nested list elements`, () => {
+ const secret = "sk-eval-12345678901234567890";
+ const telemetry = createTelemetry({
+ host: "pi",
+ source: "PI_AGENT_PLUGIN",
+ version: "1",
+ distinctId: "person",
+ });
+
+ const event = telemetry.build("pi.test", {
+ details: [
+ { [key]: "plain-value", count: 2 },
+ { nested: { [key.toUpperCase()]: "plain-value", ok: true } },
+ [`failure contained ${secret}`],
+ ],
+ });
+ telemetry.resetForTesting();
+
+ assert.deepEqual((event?.properties as { details: unknown[] }).details, [
+ { count: 2 },
+ { nested: { ok: true } },
+ ["failure contained [REDACTED]"],
+ ]);
+ });
+}
+
+test("error classification does not expose messages", () => {
+ assert.equal(errorKind(new Error("429 secret query")), "rate-limited");
+ assert.equal(errorKind(new Error("401 key")), "auth");
+ assert.equal(errorKind(new Error("request timeout")), "timeout");
+ assert.equal(errorKind(new Error("fetch failed")), "network");
+});
+
+test("a failed delivery keeps the batch instead of deleting it", async () => {
+ // The defect: the queue was detached before the await and the error swallowed,
+ // so one blip destroyed the events with nothing recording that it happened.
+ const attempts: Record[][] = [];
+ let failNext = true;
+ const telemetry = createTelemetry({
+ host: "h", source: "S", version: "1", distinctId: "d",
+ flushThreshold: 1000,
+ delivery: async (batch) => {
+ attempts.push(batch);
+ if (failNext) throw new Error("network down");
+ },
+ });
+
+ telemetry.capture("one");
+ telemetry.capture("two");
+ await telemetry.flush();
+
+ assert.equal(attempts.length, 1);
+ assert.equal(telemetry.queueForTesting().length, 2, "events were dropped on failure");
+
+ failNext = false;
+ // Backoff is in force, so wait it out the way wall time would.
+ await new Promise((resolve) => setTimeout(resolve, 2_100));
+ await telemetry.flush();
+
+ assert.equal(attempts.length, 2, "never retried");
+ assert.equal(telemetry.queueForTesting().length, 0);
+ telemetry.resetForTesting();
+});
+
+test("a retried event carries the same uuid so PostHog can collapse it", async () => {
+ const attempts: Record[][] = [];
+ let failNext = true;
+ const telemetry = createTelemetry({
+ host: "h", source: "S", version: "1", distinctId: "d",
+ flushThreshold: 1000,
+ delivery: async (batch) => {
+ attempts.push(batch);
+ if (failNext) throw new Error("network down");
+ },
+ });
+
+ telemetry.capture("once");
+ await telemetry.flush();
+ failNext = false;
+ await new Promise((resolve) => setTimeout(resolve, 2_100));
+ await telemetry.flush();
+
+ assert.equal(attempts.length, 2);
+ const first = attempts[0][0].uuid;
+ assert.ok(first, "events carry no uuid, so a retry would double count");
+ assert.equal(attempts[1][0].uuid, first, "retry minted a new uuid");
+ telemetry.resetForTesting();
+});
+
+test("repeated failures back off instead of retrying every flush", async () => {
+ let calls = 0;
+ const telemetry = createTelemetry({
+ host: "h", source: "S", version: "1", distinctId: "d",
+ flushThreshold: 1000,
+ delivery: async () => { calls += 1; throw new Error("blocked"); },
+ });
+
+ telemetry.capture("one");
+ await telemetry.flush();
+ await telemetry.flush();
+ await telemetry.flush();
+
+ assert.equal(calls, 1, "a blocked host was hammered on every flush");
+ assert.equal(telemetry.queueForTesting().length, 1, "the event was lost while backing off");
+ telemetry.resetForTesting();
+});
+
+test("a full queue drops the new event and keeps the batch being retried", async () => {
+ // Python's record() refuses new events once the spool is full rather than
+ // evicting the backlog. Keeping the newest here would throw away exactly the
+ // events the retry exists to save.
+ const telemetry = createTelemetry({
+ host: "h", source: "S", version: "1", distinctId: "d",
+ flushThreshold: 1000, maxQueueSize: 3,
+ delivery: async () => { throw new Error("down"); },
+ });
+
+ // Fill past the cap BEFORE the flush, so the re-queue actually has to truncate.
+ // Capturing only two left the queue empty at re-queue time and the slice on the
+ // failure path never ran, which is the half that decides the direction.
+ telemetry.capture("a");
+ telemetry.capture("b");
+ telemetry.capture("c");
+ await telemetry.flush();
+ telemetry.capture("d");
+ telemetry.capture("e");
+
+ const events = telemetry.queueForTesting().map((e) => (e as any).event);
+ assert.equal(events.length, 3, "queue grew past maxQueueSize");
+ assert.deepEqual(events, ["a", "b", "c"], "the retried batch was evicted instead of the new events");
+ telemetry.resetForTesting();
+});
+
+test("the exit-time flush ignores the backoff", async () => {
+ // beforeExit is the last chance the process gets. Gating it on the same
+ // cooldown meant that after any failure it did nothing and the queue died.
+ let attempts = 0;
+ let failing = true;
+ const telemetry = createTelemetry({
+ host: "h", source: "S", version: "1", distinctId: "d", flushThreshold: 1000,
+ delivery: async () => { attempts += 1; if (failing) throw new Error("down"); },
+ });
+
+ telemetry.capture("a");
+ await telemetry.flush();
+ assert.equal(attempts, 1);
+
+ failing = false;
+ await telemetry.flush();
+ assert.equal(attempts, 1, "the backoff should still hold for an ordinary flush");
+
+ await telemetry.flush(true);
+ assert.equal(attempts, 2, "the exit flush was suppressed by the backoff");
+ assert.equal(telemetry.queueForTesting().length, 0);
+ telemetry.resetForTesting();
+});
+
+test("every event carries a capture-time timestamp", async () => {
+ const sent: Record[][] = [];
+ const telemetry = createTelemetry({
+ host: "h", source: "S", version: "1", distinctId: "d", flushThreshold: 1000,
+ delivery: async (batch) => { sent.push(batch); },
+ });
+
+ telemetry.capture("a");
+ const capturedAt = Date.now();
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ await telemetry.flush();
+
+ const stamped = sent[0][0].timestamp as string;
+ assert.ok(stamped, "no timestamp, so PostHog would record delivery time");
+ assert.ok(Math.abs(Date.parse(stamped) - capturedAt) < 1_000, "not capture time");
+ telemetry.resetForTesting();
+});
+
+test("a batch the server will never accept is eventually given up on", async () => {
+ let attempts = 0;
+ const telemetry = createTelemetry({
+ host: "h", source: "S", version: "1", distinctId: "d", flushThreshold: 1000,
+ delivery: async () => { attempts += 1; throw new Error("permanently bad"); },
+ });
+
+ telemetry.capture("doomed");
+ for (let i = 0; i < 8; i += 1) await telemetry.flush(true);
+
+ assert.ok(attempts <= 6, `retried ${attempts} times with no cap`);
+ assert.equal(telemetry.queueForTesting().length, 0, "a doomed batch held the queue forever");
+ telemetry.resetForTesting();
+});
+
+test("an HTTP error response is a failure, not a delivery", async () => {
+ // fetch only rejects on a network-level failure, so a 500 used to resolve
+ // normally and the batch was dropped as delivered. Exercises the real default
+ // delivery path rather than an injected one, which is where this hid.
+ const realFetch = globalThis.fetch;
+ let calls = 0;
+ globalThis.fetch = (async () => {
+ calls += 1;
+ return new Response("upstream is unwell", { status: 503 });
+ }) as typeof fetch;
+
+ const telemetry = createTelemetry({
+ host: "h", source: "S", version: "1", distinctId: "d", flushThreshold: 1000,
+ });
+ try {
+ telemetry.capture("during.outage");
+ await telemetry.flush();
+
+ assert.equal(calls, 1, "never reached the network");
+ assert.equal(telemetry.queueForTesting().length, 1, "a 503 was counted as delivered");
+ } finally {
+ globalThis.fetch = realFetch;
+ telemetry.resetForTesting();
+ }
+});
+
+test("a 2xx is a delivery", async () => {
+ const realFetch = globalThis.fetch;
+ globalThis.fetch = (async () => new Response("ok", { status: 200 })) as typeof fetch;
+
+ const telemetry = createTelemetry({
+ host: "h", source: "S", version: "1", distinctId: "d", flushThreshold: 1000,
+ });
+ try {
+ telemetry.capture("fine");
+ await telemetry.flush();
+ assert.equal(telemetry.queueForTesting().length, 0, "a good response did not clear the queue");
+ } finally {
+ globalThis.fetch = realFetch;
+ telemetry.resetForTesting();
+ }
+});
+
+test("the exit flush is attempted once, not until the budget is spent", async () => {
+ // Node re-emits beforeExit whenever the handler schedules async work, so an
+ // unconditional forced flush looped until MAX_DELIVERY_ATTEMPTS. Against the
+ // real 3s delivery timeout that is fifteen seconds added to a host's shutdown.
+ let attempts = 0;
+ const telemetry = createTelemetry({
+ host: "h", source: "S", version: "1", distinctId: "d", flushThreshold: 1000,
+ delivery: async () => { attempts += 1; throw new Error("down"); },
+ });
+
+ telemetry.capture("a");
+ const handlers = process.listeners("beforeExit");
+ const ours = handlers[handlers.length - 1] as () => void;
+ ours();
+ ours();
+ ours();
+ await new Promise((resolve) => setTimeout(resolve, 20));
+
+ assert.equal(attempts, 1, `exit flush ran ${attempts} times`);
+ telemetry.resetForTesting();
+});
+
+test("overlapping flushes do not reorder the backlog behind newer events", async () => {
+ // Each flush detaches the queue and prepends its own batch back on failure, so
+ // two in flight at once put the LATER batch in front of the earlier one. The
+ // truncation then drops the older events first, inverting the priority the
+ // failure path exists to establish.
+ let release: (() => void)[] = [];
+ const telemetry = createTelemetry({
+ host: "h", source: "S", version: "1", distinctId: "d", flushThreshold: 1000,
+ delivery: () => new Promise((_resolve, reject) => { release.push(() => reject(new Error("down"))); }),
+ });
+
+ telemetry.capture("first");
+ const a = telemetry.flush();
+ telemetry.capture("second");
+ const b = telemetry.flush();
+
+ release.forEach((fn) => fn());
+ await Promise.all([a, b]);
+
+ const events = telemetry.queueForTesting().map((e) => (e as any).event);
+ assert.equal(release.length, 1, "a second delivery started while one was in flight");
+ assert.deepEqual(events, ["first", "second"], `backlog reordered: ${events.join(",")}`);
+ telemetry.resetForTesting();
+});
diff --git a/integrations/agent-plugin-core/typescript/tsconfig.json b/integrations/agent-plugin-core/typescript/tsconfig.json
new file mode 100644
index 000000000..5abe9f948
--- /dev/null
+++ b/integrations/agent-plugin-core/typescript/tsconfig.json
@@ -0,0 +1,12 @@
+{
+ "compilerOptions": {
+ "target": "ES2022",
+ "module": "ES2022",
+ "moduleResolution": "bundler",
+ "strict": true,
+ "types": ["node"],
+ "allowImportingTsExtensions": true,
+ "noEmit": true
+ },
+ "include": ["src", "tests"]
+}
diff --git a/integrations/antigravity-plugin/core/_harness_id.py b/integrations/antigravity-plugin/core/_harness_id.py
new file mode 100644
index 000000000..18b7f68ec
--- /dev/null
+++ b/integrations/antigravity-plugin/core/_harness_id.py
@@ -0,0 +1,11 @@
+"""Generated by integrations/agent-plugin-core/build/build.py. Do not edit."""
+
+HARNESS_ID = "antigravity"
+SOURCE_TAG = "ANTIGRAVITY_PLUGIN"
+
+# Platform-side vocabulary (mem0_event.source + X-Application). The whole
+# plugin family is one source; which editor it runs in is the application.
+# An empty application means the host is unknown, and memory_core omits
+# the header entirely rather than sending a placeholder.
+PLATFORM_SOURCE = "MEM0_PLUGIN"
+PLATFORM_APPLICATION = "antigravity"
diff --git a/integrations/antigravity-plugin/core/flush_worker.py b/integrations/antigravity-plugin/core/flush_worker.py
new file mode 100644
index 000000000..6f7b9ecb2
--- /dev/null
+++ b/integrations/antigravity-plugin/core/flush_worker.py
@@ -0,0 +1,100 @@
+#!/usr/bin/env python3
+"""Detached remote checkpoint worker.
+
+Claude Code may cancel SessionEnd hooks as a print-mode process exits. The hook
+therefore persists its input first and launches this process in a new session.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import sys
+import time
+from pathlib import Path
+
+import telemetry
+from memory_core import (
+ EvidenceStore,
+ checkpoint_session,
+ configure_harness,
+ touch_handoff_heartbeat,
+)
+
+
+def main() -> int:
+ if len(sys.argv) != 2:
+ return 2
+ handoff_path = Path(sys.argv[1])
+ os.environ["MEM0_CODE_HANDOFF_PATH"] = str(handoff_path)
+ harness = os.environ.get("MEM0_PLUGIN_HARNESS")
+ if harness:
+ source_tag = os.environ.get("MEM0_PLUGIN_SOURCE_TAG", "")
+ configure_harness(
+ harness,
+ env_prefix=os.environ.get("MEM0_PLUGIN_ENV_PREFIX", ""),
+ data_dir_name=os.environ.get("MEM0_PLUGIN_DATA_DIR_NAME", ""),
+ source_tag=source_tag,
+ )
+ telemetry.init(harness=harness, source_tag=source_tag.upper())
+ completed = False
+ try:
+ payload = json.loads(handoff_path.read_text(encoding="utf-8"))
+ delay = float(payload.get("delay_seconds") or 0)
+ if delay > 0:
+ payload.pop("delay_seconds", None)
+ temporary = handoff_path.with_suffix(f".{os.getpid()}.tmp")
+ try:
+ temporary.write_text(json.dumps(payload), encoding="utf-8")
+ temporary.replace(handoff_path)
+ finally:
+ temporary.unlink(missing_ok=True)
+ time.sleep(delay)
+ if not handoff_path.exists():
+ return 0
+ hook_input = payload.get("hook_input") or {}
+ reason = str(payload.get("reason") or "checkpoint")
+ wait_for_inflight = bool(payload.get("wait_for_inflight"))
+ store = EvidenceStore()
+ try:
+ if wait_for_inflight:
+ session_id = str(
+ hook_input.get("session_id") or "unknown-session"
+ )
+ repo = store.repo_for_session(session_id, hook_input.get("cwd"))
+ deadline = time.monotonic() + float(
+ os.environ.get("MEM0_CODE_EXTRACTION_WAIT_SECONDS", "120")
+ )
+ while (
+ store.has_inflight_flush(repo.identity, session_id)
+ and time.monotonic() < deadline
+ ):
+ touch_handoff_heartbeat()
+ time.sleep(0.25)
+ # Hooks capture the conversation before handoff; the worker only flushes it.
+ result = checkpoint_session(store, hook_input, reason)
+ print(json.dumps(result, sort_keys=True), flush=True)
+ completed = result.get("status") in {
+ "semantic-succeeded",
+ "explicitly-stored",
+ "nothing-to-flush",
+ }
+ finally:
+ store.close()
+ return 0
+ finally:
+ telemetry.flush()
+ if completed:
+ try:
+ handoff_path.unlink()
+ except OSError:
+ pass
+ elif handoff_path.suffix == ".running":
+ try:
+ handoff_path.replace(handoff_path.with_suffix(".json"))
+ except OSError:
+ pass
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/integrations/antigravity-plugin/core/hook_runner.py b/integrations/antigravity-plugin/core/hook_runner.py
new file mode 100644
index 000000000..b3d8a3210
--- /dev/null
+++ b/integrations/antigravity-plugin/core/hook_runner.py
@@ -0,0 +1,388 @@
+"""Shared hook orchestration for all Mem0 agent plugins."""
+
+from __future__ import annotations
+
+import argparse
+import hashlib
+import json
+import os
+import subprocess
+import sys
+import time
+import uuid
+from pathlib import Path
+
+import telemetry
+from memory_core import (
+ EvidenceStore,
+ _session_id,
+ api_key,
+ bounded,
+ cache_plugin_api_key,
+ checkpoint_session,
+ clear_stale_api_key_cache,
+ configure_harness,
+ data_dir,
+ detached_process_kwargs,
+ format_context,
+ harness_config,
+ record_session_start,
+ record_tool,
+ record_user_prompt,
+ redact,
+ search_memories,
+)
+
+STALE_RUNNING_SECONDS = 300
+PENDING_EXPIRY_SECONDS = 7 * 24 * 60 * 60
+PENDING_LAUNCH_LIMIT = 5
+DEFAULT_IDLE_FLUSH_SECONDS = 300
+
+_core_dir: Path = Path(__file__).resolve().parent
+
+
+def read_hook_input() -> dict:
+ try:
+ value = json.load(sys.stdin)
+ return value if isinstance(value, dict) else {}
+ except (json.JSONDecodeError, OSError):
+ return {}
+
+
+def default_record_stop(store: EvidenceStore, hook_input: dict):
+ """Record the assistant's response without transcript parsing."""
+ session_id = _session_id(hook_input)
+ repo = store.repo_for_session(session_id, hook_input.get("cwd"))
+ message = redact(hook_input.get("last_assistant_message", "")).strip()
+ if message:
+ store.record_assistant_response(repo, session_id, message)
+ return repo, session_id
+
+
+def first_prompt_memory_output(store: EvidenceStore, hook_input: dict) -> dict:
+ """Search once before the agent handles the first prompt in a session."""
+ repo, session_id, prompt, is_first_prompt = record_user_prompt(store, hook_input)
+ if not is_first_prompt:
+ return {}
+ try:
+ minimum_query_chars = int(os.environ.get("MEM0_CODE_MIN_QUERY_CHARS", "20"))
+ except ValueError:
+ minimum_query_chars = 20
+ if len(prompt.strip()) < max(minimum_query_chars, 1):
+ return {}
+ result = search_memories(
+ store, repo, session_id, bounded(prompt, 6000),
+ top_k=5, operation="first-prompt-search", timeout=2,
+ )
+ if not result.memories:
+ return {}
+ context = format_context(
+ result.memories,
+ "Mem0 found these relevant memories from earlier work in this repository:",
+ )
+ telemetry.record(
+ "context_injected",
+ repo=repo, session_id=session_id, trigger="first-prompt",
+ memory_count=len(result.memories), context_chars=len(context),
+ prompt_chars=len(prompt),
+ )
+ return {
+ "hookSpecificOutput": {
+ "hookEventName": "UserPromptSubmit",
+ "additionalContext": context,
+ },
+ }
+
+
+def _launch_handoff(handoff_path: Path) -> bool:
+ running_path = handoff_path.with_suffix(".running")
+ try:
+ handoff_path.replace(running_path)
+ except OSError:
+ return False
+ worker = _core_dir / "flush_worker.py"
+ log_path = data_dir() / "flush-worker.log"
+ log_handle = open(log_path, "a", encoding="utf-8")
+ harness = harness_config()
+ child_env = os.environ.copy()
+ child_env.update(
+ {
+ "MEM0_CODE_DATA_DIR": str(data_dir()),
+ "MEM0_PLUGIN_HARNESS": harness["name"],
+ "MEM0_PLUGIN_ENV_PREFIX": harness["env_prefix"],
+ "MEM0_PLUGIN_DATA_DIR_NAME": harness["data_dir_name"],
+ "MEM0_PLUGIN_SOURCE_TAG": harness["source_tag"],
+ }
+ )
+ try:
+ subprocess.Popen(
+ [sys.executable, str(worker), str(running_path)],
+ stdin=subprocess.DEVNULL,
+ stdout=log_handle, stderr=log_handle,
+ close_fds=True,
+ env=child_env,
+ **detached_process_kwargs(),
+ )
+ finally:
+ log_handle.close()
+ return True
+
+
+def recover_pending_handoffs() -> int:
+ pending_dir = data_dir() / "pending"
+ pending_dir.mkdir(parents=True, exist_ok=True)
+ now = time.time()
+ for running in pending_dir.glob("*.running"):
+ try:
+ if now - running.stat().st_mtime > STALE_RUNNING_SECONDS:
+ running.replace(running.with_suffix(".json"))
+ except OSError:
+ continue
+ recoverable = []
+ for handoff in pending_dir.glob("*.json"):
+ try:
+ age = now - handoff.stat().st_mtime
+ except OSError:
+ continue
+ if age > PENDING_EXPIRY_SECONDS:
+ handoff.unlink(missing_ok=True)
+ continue
+ recoverable.append((age, handoff))
+ recoverable.sort(key=lambda item: item[0], reverse=True)
+ launched = 0
+ for _, handoff in recoverable[:PENDING_LAUNCH_LIMIT]:
+ launched += int(_launch_handoff(handoff))
+ return launched
+
+
+def refresh_pending_handoffs() -> None:
+ pending_dir = data_dir() / "pending"
+ if not pending_dir.is_dir():
+ return
+ for pattern in ("*.json", "*.running"):
+ for handoff in pending_dir.glob(pattern):
+ try:
+ os.utime(handoff)
+ except OSError:
+ continue
+
+
+def hand_off_flush(
+ hook_input: dict, reason: str, *, wait_for_inflight: bool = False,
+) -> None:
+ pending_dir = data_dir() / "pending"
+ pending_dir.mkdir(parents=True, exist_ok=True)
+ material = (
+ f"{hook_input.get('cwd', '')}\0{hook_input.get('session_id', '')}\0{reason}"
+ )
+ digest = hashlib.sha256(material.encode()).hexdigest()[:24]
+ handoff_path = pending_dir / f"{digest}-{uuid.uuid4().hex[:8]}.json"
+ temporary_path = handoff_path.with_suffix(".tmp")
+ temporary_path.write_text(
+ json.dumps({
+ "hook_input": hook_input,
+ "reason": reason,
+ "wait_for_inflight": wait_for_inflight,
+ }),
+ encoding="utf-8",
+ )
+ temporary_path.replace(handoff_path)
+ _launch_handoff(handoff_path)
+
+
+def automatic_flush_enabled() -> bool:
+ return os.environ.get("MEM0_CODE_AUTO_FLUSH", "true").lower() in {
+ "1", "true", "yes", "on",
+ }
+
+
+def schedule_periodic_checkpoint(
+ store: EvidenceStore, hook_input: dict, repo, session_id: str,
+) -> bool:
+ if (
+ not automatic_flush_enabled()
+ or not api_key()
+ or not store.checkpoint_due(repo.identity, session_id)
+ ):
+ return False
+ if store.prepare_flush(repo, session_id, "periodic") is None:
+ return False
+ hand_off_flush(hook_input, "periodic")
+ return True
+
+
+def _idle_flush_seconds() -> int:
+ try:
+ return max(
+ int(os.environ.get("MEM0_CODE_IDLE_FLUSH_SECONDS", str(DEFAULT_IDLE_FLUSH_SECONDS))),
+ 0,
+ )
+ except ValueError:
+ return DEFAULT_IDLE_FLUSH_SECONDS
+
+
+def schedule_idle_flush(
+ store: EvidenceStore, hook_input: dict, repo, session_id: str,
+) -> bool:
+ delay = _idle_flush_seconds()
+ if delay <= 0 or not automatic_flush_enabled() or not api_key():
+ return False
+ if store.has_inflight_flush(repo.identity, session_id):
+ return False
+ if not store.has_unflushed_events(repo.identity, session_id):
+ return False
+ pending_dir = data_dir() / "pending"
+ pending_dir.mkdir(parents=True, exist_ok=True)
+ material = f"idle\0{hook_input.get('cwd', '')}\0{hook_input.get('session_id', '')}"
+ digest = hashlib.sha256(material.encode()).hexdigest()[:24]
+ for old in pending_dir.glob(f"idle-{digest}*"):
+ old.unlink(missing_ok=True)
+ handoff_path = pending_dir / f"idle-{digest}-{uuid.uuid4().hex[:8]}.json"
+ temporary_path = handoff_path.with_suffix(".tmp")
+ temporary_path.write_text(
+ json.dumps({
+ "hook_input": hook_input,
+ "reason": "idle",
+ "delay_seconds": delay,
+ }),
+ encoding="utf-8",
+ )
+ temporary_path.replace(handoff_path)
+ _launch_handoff(handoff_path)
+ return True
+
+
+def log_failure(exc: Exception) -> None:
+ try:
+ log_path = data_dir() / "plugin-errors.log"
+ with log_path.open("a", encoding="utf-8") as handle:
+ handle.write(f"{time.time():.3f} {type(exc).__name__}: {exc}\n")
+ except OSError:
+ pass
+
+
+def run(
+ *,
+ record_stop_fn=None,
+ extra_actions: dict | None = None,
+ data_dir_env: str = "MEM0_PLUGIN_DATA_DIR",
+ automatic_flush_reasons: set | None = None,
+) -> int:
+ if record_stop_fn is None:
+ record_stop_fn = default_record_stop
+ if automatic_flush_reasons is None:
+ automatic_flush_reasons = {"session-end"}
+
+ base_actions = ["session-start", "user-prompt", "post-tool", "stop", "flush"]
+ all_actions = base_actions + list((extra_actions or {}).keys())
+
+ parser = argparse.ArgumentParser()
+ parser.add_argument("action", choices=all_actions)
+ parser.add_argument("--reason", default="manual")
+ parser.add_argument("--plugin-data-dir", default="")
+ parser.add_argument("--harness", default="")
+ args = parser.parse_args()
+
+ if args.harness:
+ configure_harness(args.harness)
+ telemetry.init(harness=args.harness)
+
+ if args.plugin_data_dir:
+ os.environ[data_dir_env] = args.plugin_data_dir
+
+ # Snapshot BEFORE anything writes to the data dir: cache_plugin_api_key
+ # writes `api-key` and EvidenceStore creates `evidence.sqlite3`, so asking
+ # after them always saw content and every fresh install reported an upgrade.
+ data_dir_was_empty = telemetry.data_dir_was_empty()
+
+ cache_plugin_api_key()
+ if args.action == "session-start":
+ clear_stale_api_key_cache()
+
+ hook_input = read_hook_input()
+ store = EvidenceStore()
+ try:
+ if store.is_paused():
+ if args.action == "session-start":
+ refresh_pending_handoffs()
+ telemetry.record("session_start", paused=True)
+ telemetry.spawn_flush()
+ return 0
+
+ if args.action == "session-start":
+ # Claims the marker atomically and says which event to record, so a
+ # second session starting alongside this one cannot record it too.
+ first_event = telemetry.claim_install(was_empty=data_dir_was_empty)
+ if first_event == "install":
+ telemetry.record("install")
+ elif first_event == "upgrade":
+ # First run after a build that never wrote the marker; the
+ # predecessor version was never recorded anywhere.
+ telemetry.record("upgrade", from_version="pre-0.3")
+ else:
+ previous = telemetry.claim_version_change()
+ if previous:
+ telemetry.record("upgrade", from_version=previous)
+ recovered = recover_pending_handoffs()
+ record_session_start(store, hook_input)
+ if recovered:
+ telemetry.record("handoff_recovered", count=recovered)
+ telemetry.spawn_flush()
+ elif args.action == "user-prompt":
+ output = first_prompt_memory_output(store, hook_input)
+ if output:
+ print(json.dumps(output))
+ elif args.action == "post-tool":
+ record_tool(store, hook_input)
+ elif args.action == "stop":
+ repo, session_id = record_stop_fn(store, hook_input)
+ if not schedule_periodic_checkpoint(store, hook_input, repo, session_id):
+ schedule_idle_flush(store, hook_input, repo, session_id)
+ elif args.action == "flush":
+ automatic = args.reason in automatic_flush_reasons
+ if automatic and not automatic_flush_enabled():
+ return 0
+ if args.reason == "session-end":
+ record_stop_fn(store, hook_input)
+ if os.environ.get("MEM0_CODE_SYNC_FLUSH") == "1":
+ print(json.dumps(checkpoint_session(store, hook_input, args.reason)))
+ else:
+ session_id = str(hook_input.get("session_id") or "unknown-session")
+ repo = store.repo_for_session(session_id, hook_input.get("cwd"))
+ already_running = store.has_inflight_flush(repo.identity, session_id)
+ if already_running and args.reason == "session-end":
+ hand_off_flush(hook_input, args.reason, wait_for_inflight=True)
+ elif not already_running and store.prepare_flush(
+ repo, session_id, args.reason,
+ ) is not None:
+ hand_off_flush(hook_input, args.reason)
+ elif extra_actions and args.action in extra_actions:
+ result = extra_actions[args.action](store, hook_input)
+ if result:
+ print(json.dumps(result))
+ finally:
+ store.close()
+ return 0
+
+
+def entry_point(
+ *,
+ record_stop_fn=None,
+ extra_actions: dict | None = None,
+ data_dir_env: str = "MEM0_PLUGIN_DATA_DIR",
+ automatic_flush_reasons: set | None = None,
+) -> None:
+ try:
+ raise SystemExit(run(
+ record_stop_fn=record_stop_fn,
+ extra_actions=extra_actions,
+ data_dir_env=data_dir_env,
+ automatic_flush_reasons=automatic_flush_reasons,
+ ))
+ except Exception as exc:
+ log_failure(exc)
+ raise SystemExit(0)
+
+
+if __name__ == "__main__":
+ entry_point()
diff --git a/integrations/antigravity-plugin/core/mcp_server.py b/integrations/antigravity-plugin/core/mcp_server.py
new file mode 100644
index 000000000..a0b73cb79
--- /dev/null
+++ b/integrations/antigravity-plugin/core/mcp_server.py
@@ -0,0 +1,240 @@
+#!/usr/bin/env python3
+"""Expose Mem0's memory search as one local coding-agent tool."""
+
+from __future__ import annotations
+
+import json
+import os
+import sys
+from typing import Any
+
+import telemetry
+from memory_core import (
+ CODING_MEMORY_CATEGORY_NAMES,
+ PLUGIN_VERSION,
+ SEARCH_SCOPES,
+ format_search_result,
+ resolve_repo,
+ search_memories,
+)
+
+PROTOCOL_VERSION = "2024-11-05"
+TOOL_NAME = "search_memories"
+TOOL_DESCRIPTION = (
+ "Search memories from earlier work in this repository. Use it before "
+ "repeating investigation or when earlier decisions, fixes, commands, or "
+ "results may help."
+)
+TOOL_SCHEMA = {
+ "type": "object",
+ "properties": {
+ "query": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 2000,
+ "description": "A direct question about earlier work in this repository.",
+ },
+ "top_k": {
+ "type": "integer",
+ "minimum": 1,
+ "maximum": 20,
+ "description": "Maximum memories to return. Uses Mem0's configured default when omitted.",
+ },
+ "category": {
+ "type": "string",
+ "enum": list(CODING_MEMORY_CATEGORY_NAMES),
+ "description": "Optional memory category. Omit to search every category.",
+ },
+ "scope": {
+ "type": "string",
+ "enum": list(SEARCH_SCOPES),
+ "description": (
+ "Which memories to search. 'repo' (default) is the whole repository's "
+ "shared memory plus your own preferences, 'dir' narrows the shared "
+ "part to the current directory, 'mine' is your preferences alone."
+ ),
+ },
+ "run_id": {
+ "type": "string",
+ "minLength": 1,
+ "description": (
+ "Optional coding-agent session ID. With any scope, restricts results to memories "
+ "saved in that session. Omit to recall memories across sessions."
+ ),
+ },
+ },
+ "required": ["query"],
+ "additionalProperties": False,
+}
+
+
+class ToolInputError(ValueError):
+ pass
+
+
+def _validate_arguments(
+ arguments: Any,
+) -> tuple[str, int | None, str | None, str | None, str | None]:
+ if not isinstance(arguments, dict):
+ raise ToolInputError("Search arguments must be an object.")
+
+ unknown = set(arguments) - {"query", "top_k", "category", "scope", "run_id"}
+ if unknown:
+ raise ToolInputError(f"Unknown search argument: {sorted(unknown)[0]}")
+
+ query = arguments.get("query")
+ if not isinstance(query, str) or not query.strip():
+ raise ToolInputError("query must be a non-empty string.")
+ query = query.strip()
+ if len(query) > 2000:
+ raise ToolInputError("query must be at most 2,000 characters.")
+
+ top_k = arguments.get("top_k")
+ if top_k is not None and (
+ isinstance(top_k, bool) or not isinstance(top_k, int) or not 1 <= top_k <= 20
+ ):
+ raise ToolInputError("top_k must be an integer from 1 to 20.")
+
+ category = arguments.get("category")
+ if category is not None and category not in CODING_MEMORY_CATEGORY_NAMES:
+ raise ToolInputError("category must be one of Mem0's supported categories.")
+
+ scope = arguments.get("scope")
+ if scope is not None and scope not in SEARCH_SCOPES:
+ raise ToolInputError(f"scope must be one of {list(SEARCH_SCOPES)}.")
+
+ run_id = arguments.get("run_id")
+ if run_id is not None:
+ if not isinstance(run_id, str) or not run_id.strip():
+ raise ToolInputError("run_id must be a non-empty string.")
+ run_id = run_id.strip()
+
+ return query, top_k, category, scope, run_id
+
+
+def call_search_memories(arguments: Any, cwd: str | None = None) -> str:
+ query, top_k, category, scope, run_id = _validate_arguments(arguments)
+ repo = resolve_repo(cwd or os.environ.get("CLAUDE_PROJECT_DIR") or os.getcwd())
+ result = search_memories(
+ None,
+ repo,
+ None,
+ query,
+ top_k=top_k,
+ category=category,
+ scope=scope,
+ run_id=run_id,
+ operation="mcp-search",
+ )
+ return format_search_result(result)
+
+
+def _workspace_cwd(params: dict[str, Any]) -> str | None:
+ meta = params.get("_meta")
+ if not isinstance(meta, dict):
+ return None
+ metadata = meta.get("x-codex-turn-metadata")
+ if not isinstance(metadata, dict):
+ return None
+ workspaces = metadata.get("workspaces") or {}
+ if isinstance(workspaces, dict):
+ return next((path for path in workspaces if isinstance(path, str) and path), None)
+ return None
+
+
+def _tool_response(text: str, *, is_error: bool = False) -> dict[str, Any]:
+ return {
+ "content": [{"type": "text", "text": text}],
+ "isError": is_error,
+ }
+
+
+def handle_request(message: Any) -> dict[str, Any] | None:
+ if not isinstance(message, dict):
+ return None
+ request_id = message.get("id")
+ method = message.get("method")
+
+ if method == "notifications/initialized":
+ return None
+ if method == "initialize":
+ requested = (message.get("params") or {}).get("protocolVersion")
+ return {
+ "jsonrpc": "2.0",
+ "id": request_id,
+ "result": {
+ "protocolVersion": requested or PROTOCOL_VERSION,
+ "capabilities": {"tools": {"listChanged": False}},
+ "serverInfo": {"name": "mem0", "version": PLUGIN_VERSION},
+ },
+ }
+ if method == "ping":
+ return {"jsonrpc": "2.0", "id": request_id, "result": {}}
+ if method == "tools/list":
+ return {
+ "jsonrpc": "2.0",
+ "id": request_id,
+ "result": {
+ "tools": [
+ {
+ "name": TOOL_NAME,
+ "description": TOOL_DESCRIPTION,
+ "inputSchema": TOOL_SCHEMA,
+ "annotations": {
+ "readOnlyHint": True,
+ "idempotentHint": True,
+ "openWorldHint": True,
+ },
+ }
+ ]
+ },
+ }
+ if method == "tools/call":
+ params = message.get("params") or {}
+ if params.get("name") != TOOL_NAME:
+ result = _tool_response("Unknown Mem0 tool.", is_error=True)
+ else:
+ try:
+ result = _tool_response(
+ call_search_memories(params.get("arguments"), _workspace_cwd(params))
+ )
+ except ToolInputError as exc:
+ result = _tool_response(str(exc), is_error=True)
+ except Exception:
+ result = _tool_response("Memory search failed.", is_error=True)
+ return {"jsonrpc": "2.0", "id": request_id, "result": result}
+ if request_id is None:
+ return None
+ return {
+ "jsonrpc": "2.0",
+ "id": request_id,
+ "error": {"code": -32601, "message": "Method not found"},
+ }
+
+
+def main() -> int:
+ for raw_line in sys.stdin:
+ try:
+ message = json.loads(raw_line)
+ response = handle_request(message)
+ except json.JSONDecodeError:
+ response = {
+ "jsonrpc": "2.0",
+ "id": None,
+ "error": {"code": -32700, "message": "Parse error"},
+ }
+ except Exception:
+ response = {
+ "jsonrpc": "2.0",
+ "id": None,
+ "error": {"code": -32603, "message": "Internal error"},
+ }
+ if response is not None:
+ sys.stdout.write(json.dumps(response, separators=(",", ":")) + "\n")
+ sys.stdout.flush()
+ telemetry.spawn_flush()
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/integrations/antigravity-plugin/core/memory_cli.py b/integrations/antigravity-plugin/core/memory_cli.py
new file mode 100644
index 000000000..76d2ee871
--- /dev/null
+++ b/integrations/antigravity-plugin/core/memory_cli.py
@@ -0,0 +1,154 @@
+#!/usr/bin/env python3
+"""Mem0 diagnostics and user controls."""
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+
+import telemetry
+from memory_core import (
+ EvidenceStore,
+ api_key,
+ configure_harness,
+ data_dir,
+ doctor,
+ forget_remote_repo,
+ resolve_repo,
+ user_id,
+)
+
+
+def _print_status(value: dict) -> None:
+ last = value.get("last_operation") or {}
+ print(f"Mem0: {'paused' if value['paused'] else 'active'}")
+ print(f"Repository: {value['repo_id']}")
+ print(f"Local data: {value['data_dir']}")
+ print(f"API key: {'configured' if value['api_key_configured'] else 'missing'}")
+ print(
+ "Saved on this computer: "
+ f"{value['events']} session details, {value['flushes']} memory updates"
+ )
+ print(
+ f"Used in this repository: {value['retrievals']} memories returned, "
+ f"{value['subagent_runs']} subagent runs"
+ )
+ if last:
+ item_label = ""
+ if last["operation"] in {"flush", "flush-retry"}:
+ item_label = f", {last['item_count']} memories"
+ operation = (
+ "memory update"
+ if last["operation"] in {"flush", "flush-retry"}
+ else last["operation"].replace("-", " ")
+ )
+ print(
+ f"Last {operation}: "
+ f"{'succeeded' if last['success'] else 'failed'} "
+ f"({last['duration_ms']:.1f} ms{item_label})"
+ )
+ subagent = value.get("last_subagent") or {}
+ if subagent:
+ state = "finished" if subagent.get("stopped_at") else "started"
+ print(
+ "Last subagent: "
+ f"{state}, received {subagent['context_chars']} characters of memory, "
+ f"agent {subagent['agent_id']}"
+ )
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--plugin-data-dir", default="")
+ parser.add_argument("--harness", default="")
+ subparsers = parser.add_subparsers(dest="command", required=True)
+
+ status = subparsers.add_parser("status")
+ status.add_argument("--json", action="store_true")
+
+ doctor_parser = subparsers.add_parser("doctor")
+ doctor_parser.add_argument("--json", action="store_true")
+
+ subparsers.add_parser("pause")
+ subparsers.add_parser("resume")
+
+ forget = subparsers.add_parser("forget")
+ forget.add_argument("--remote", action="store_true")
+ forget.add_argument("--yes", action="store_true")
+ forget.add_argument("--include-project-memory", action="store_true")
+
+ args = parser.parse_args()
+ if args.harness:
+ source_tag = f"{args.harness.replace('-', '_')}_plugin"
+ configure_harness(args.harness, source_tag=source_tag)
+ telemetry.init(harness=args.harness, source_tag=source_tag.upper())
+ if args.plugin_data_dir:
+ os.environ["MEM0_CODE_DATA_DIR"] = args.plugin_data_dir
+ store = EvidenceStore()
+ try:
+ repo = resolve_repo(os.getcwd())
+ telemetry.record("control", repo=repo, action=args.command)
+ if args.command == "status":
+ result = {
+ **store.status(repo.identity),
+ "repo_id": repo.identity,
+ "app_id": repo.app_id,
+ "project_id": repo.project_id,
+ "directory": repo.directory,
+ "user_id": user_id(),
+ "data_dir": str(data_dir()),
+ "api_key_configured": bool(api_key()),
+ }
+ if args.json:
+ print(json.dumps(result, indent=2, default=str))
+ else:
+ _print_status(result)
+ elif args.command == "doctor":
+ result = doctor(os.getcwd())
+ if args.json:
+ print(json.dumps(result, indent=2, default=str))
+ else:
+ for name, check in result["checks"].items():
+ print(
+ f"{'PASS' if check['ok'] else 'FAIL'} {name}: {check['detail']}"
+ )
+ return 0 if result["ok"] else 1
+ elif args.command == "pause":
+ store.set_setting("paused", "true")
+ print("Mem0 stopped saving and searching memories.")
+ elif args.command == "resume":
+ store.set_setting("paused", "false")
+ print("Mem0 resumed saving and searching memories.")
+ elif args.command == "forget":
+ if not args.yes:
+ print(
+ "Refusing to delete data without --yes. Add --remote to also "
+ "delete this user/repository scope from Mem0."
+ )
+ return 2
+ remote_result = (
+ forget_remote_repo(
+ repo, include_project_memory=args.include_project_memory
+ )
+ if args.remote
+ else None
+ )
+ local_result = store.forget_local_repo(repo.identity)
+ print(
+ json.dumps(
+ {"local": local_result, "remote": remote_result},
+ indent=2,
+ default=str,
+ )
+ )
+ if remote_result and remote_result.get("status") == "error":
+ return 1
+ finally:
+ store.close()
+ telemetry.spawn_flush()
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/integrations/antigravity-plugin/core/memory_core.py b/integrations/antigravity-plugin/core/memory_core.py
new file mode 100644
index 000000000..9b420a063
--- /dev/null
+++ b/integrations/antigravity-plugin/core/memory_core.py
@@ -0,0 +1,2676 @@
+#!/usr/bin/env python3
+"""Shared core for Mem0 agent plugins.
+
+Hooks record small session details locally. When the agent compacts or ends the
+session, Mem0 sends the useful parts to the platform so it can create memories.
+The agent can search those memories during later work in the repository.
+"""
+
+from __future__ import annotations
+
+import functools
+import hashlib
+import json
+import math
+import os
+import re
+import sqlite3
+import subprocess
+import sys
+import time
+import urllib.error
+import urllib.parse
+import urllib.request
+from dataclasses import dataclass
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Any, Iterable
+
+import telemetry
+
+DEFAULT_API_URL = "https://api.mem0.ai"
+PLUGIN_VERSION = "0.3.3"
+
+_harness_name: str = "generic"
+_harness_env_prefix: str = "MEM0_PLUGIN"
+_harness_data_dir_name: str = "mem0-plugin"
+_harness_source_tag: str = "mem0_plugin"
+
+
+def configure_harness(
+ name: str,
+ env_prefix: str = "",
+ data_dir_name: str = "",
+ source_tag: str = "",
+) -> None:
+ global _harness_name, _harness_env_prefix, _harness_data_dir_name, _harness_source_tag
+ _harness_name = name
+ _harness_env_prefix = env_prefix or f"MEM0_{name.upper().replace('-', '_')}"
+ _harness_data_dir_name = data_dir_name or f"{name}-plugin"
+ _harness_source_tag = source_tag or f"{name.replace('-', '_')}_plugin"
+
+
+def harness_config() -> dict[str, str]:
+ return {
+ "name": _harness_name,
+ "env_prefix": _harness_env_prefix,
+ "data_dir_name": _harness_data_dir_name,
+ "source_tag": _harness_source_tag,
+ }
+
+
+MAX_COMMAND_CHARS = 2000
+MAX_RESULT_CHARS = 2500
+MAX_EPISODE_CHARS = 12000
+CHECKPOINT_EXCHANGES = 5
+CHECKPOINT_MESSAGES = 10
+CHECKPOINT_SOURCE_CHARS = 40000
+DEFAULT_MAX_CONTEXT_CHARS = 4000
+MAX_EXTRACTION_INPUT_TOKENS = 24000
+MAX_FLUSH_ATTEMPTS = 5
+FORGET_PAGE_SIZE = 100
+FORGET_MAX_PAGES = 50
+
+PROJECT_MEMORY_INSTRUCTIONS = """Save concise repository facts that will help with future coding work.
+
+A completed change should produce one memory explaining the resulting behavior, where it is implemented when useful, and any important constraints or reasoning. Exploration or accepted decisions may produce separate memories only when they are independently useful.
+
+Use the coding agent's final response for conclusions about current repository behavior. Do not save proposed or recommended changes unless the user accepted them or the coding agent completed them. Treat subagent responses as supporting repository evidence, not as decisions.
+
+Write about the repository, not the user, assistant, session, or task. Do not include test results, documentation updates, release notes, or temporary state.
+
+If nothing useful was established, return no memories."""
+
+PERSONAL_MEMORY_INSTRUCTIONS = """Save concise facts about the user that will help in any repository: preferred tools, package managers, languages, coding style, review and communication preferences, and anything the user explicitly asked to be remembered about themselves.
+
+Write in the third person about the user, not about the repository, the assistant, the session, or the task. Do not save repository facts, project decisions, commands, or what was built.
+
+Never save that the user has no preferences or that nothing was learned. If nothing was learned about the user, return no memories."""
+
+CODING_MEMORY_CATEGORIES = [
+ {
+ "project_knowledge": (
+ "What the project is and how its code, APIs, data, files, and "
+ "components work."
+ )
+ },
+ {
+ "decisions_and_constraints": (
+ "Why an approach was chosen, what must remain true, and rules future "
+ "work must follow."
+ )
+ },
+ {
+ "workflows": (
+ "How to run, test, debug, deploy, configure, or otherwise work on the "
+ "project."
+ )
+ },
+ {
+ "problems_and_fixes": (
+ "Bugs, failures, known pitfalls, their causes, and how to fix or avoid "
+ "them."
+ )
+ },
+ {
+ "results": (
+ "Outcomes and measurements from tests, benchmarks, experiments, or "
+ "investigations."
+ )
+ },
+]
+CODING_MEMORY_CATEGORY_NAMES = tuple(
+ category_name
+ for category in CODING_MEMORY_CATEGORIES
+ for category_name in category
+)
+
+TEST_COMMAND_RE = re.compile(
+ r"(?:^|\s)(?:pytest|py\.test|jest|vitest|go\s+test|cargo\s+test|"
+ r"npm\s+(?:run\s+)?test|pnpm\s+(?:run\s+)?test|yarn\s+test|"
+ r"mvn\s+test|gradle\s+test|make\s+test)(?:\s|$)",
+ re.IGNORECASE,
+)
+BUILD_COMMAND_RE = re.compile(
+ r"(?:^|\s)(?:npm|pnpm|yarn)\s+(?:run\s+)?build(?:\s|$)|"
+ r"(?:^|\s)(?:cargo|go|mvn|gradle|make)\s+build(?:\s|$)",
+ re.IGNORECASE,
+)
+
+SECRET_PATTERNS = [
+ re.compile(r"(?i)(authorization\s*[:=]\s*(?:bearer|token)\s+)[^\s\"']+"),
+ re.compile(
+ r"(?i)((?:api[_-]?key|secret[_-]?access[_-]?key|session[_-]?token)\s*[:=]\s*)[^\s\"']+"
+ ),
+ re.compile(
+ r"(?i)((?:access[_-]?token|refresh[_-]?token|password|credential)"
+ r"\s*[:=]\s*)[^\s&\"']+"
+ ),
+ re.compile(r"\b(?:sk|m0|mem0_sk|psk)-[A-Za-z0-9_\-]{12,}\b"),
+ re.compile(r"\b(?:ASIA|AKIA)[A-Z0-9]{12,}\b"),
+ re.compile(r"\b(?:ghp_|github_pat_|xox[baprs]-)[A-Za-z0-9_\-]{12,}\b"),
+ re.compile(
+ r"-----BEGIN [^-]*PRIVATE KEY-----.*?-----END [^-]*PRIVATE KEY-----",
+ re.DOTALL,
+ ),
+ re.compile(
+ r'(?i)("(?:api[_-]?key|password|secret(?:[_-]?access[_-]?key)?'
+ r'|(?:access|refresh|session)[_-]?token|token|authorization|credential'
+ r')"\s*:\s*")(?:\\.|[^"\\])*'
+ ),
+]
+
+
+def utc_now() -> str:
+ return datetime.now(timezone.utc).isoformat()
+
+
+def redact(value: Any) -> str:
+ text = (
+ value
+ if isinstance(value, str)
+ else json.dumps(value, ensure_ascii=False, default=str)
+ )
+ for pattern in SECRET_PATTERNS:
+ if pattern.groups:
+ text = pattern.sub(r"\1[REDACTED]", text)
+ else:
+ text = pattern.sub("[REDACTED]", text)
+ return text
+
+
+def bounded(value: Any, limit: int) -> str:
+ text = redact(value).strip()
+ if len(text) <= limit:
+ return text
+ return text[:limit] + f"\n...[truncated {len(text) - limit} chars]"
+
+
+def _git(cwd: str, *args: str) -> str:
+ try:
+ result = subprocess.run(
+ ["git", "-C", cwd, *args],
+ check=False,
+ capture_output=True,
+ text=True,
+ timeout=0.5,
+ )
+ except (OSError, subprocess.TimeoutExpired):
+ return ""
+ return result.stdout.strip() if result.returncode == 0 else ""
+
+
+def _normalize_remote(remote: str) -> str:
+ remote = remote.strip()
+ if remote.startswith("git@") and ":" in remote:
+ host_path = remote[4:].replace(":", "/", 1)
+ remote = f"https://{host_path}"
+ if remote.endswith(".git"):
+ remote = remote[:-4]
+ if "://" in remote:
+ parsed = urllib.parse.urlsplit(remote)
+ hostname = parsed.hostname or ""
+ if parsed.port:
+ hostname = f"{hostname}:{parsed.port}"
+ remote = urllib.parse.urlunsplit(
+ (parsed.scheme, hostname, parsed.path, parsed.query, parsed.fragment)
+ )
+ return remote.rstrip("/")
+
+
+_WILDCARD_SCOPE = re.compile(r"^\*+$")
+
+
+def _scope_value(raw: str | None) -> str:
+ """Reject wildcards as identities: they are filter syntax and would widen the scope."""
+ value = (raw or "").strip()
+ return "" if _WILDCARD_SCOPE.match(value) else value
+
+
+SEARCH_SCOPES = ("repo", "dir", "mine")
+DEFAULT_SEARCH_SCOPE = "repo"
+
+def directory_app_id(repo: RepoContext) -> str:
+ """The app_id of the directory this session runs in: the repository at the root, repository/path below it."""
+ return f"{repo.app_id}/{repo.directory}" if repo.directory else repo.app_id
+
+
+def directory_chain(repo: RepoContext) -> list[str]:
+ """Every directory a memory belongs to, from the top-level folder down to the one it was written in."""
+ parts = repo.directory.split("/") if repo.directory else []
+ return ["/".join(parts[: index + 1]) for index in range(len(parts))]
+
+
+def _shared_project_ids(repo: RepoContext) -> list[str]:
+ """Current and pre-upgrade namespaces, shared by recall and explicit deletion."""
+ if not repo.identity.startswith("local:") and repo.project_id != repo.app_id:
+ return [repo.project_id, repo.app_id]
+ return [repo.project_id]
+
+
+def _search_filters(user: str, repo: RepoContext, scope: str) -> dict[str, Any]:
+ """Build the scope filter: app_id scopes to the repo, then union shared and personal lanes."""
+ app_scope = {"app_id": repo.app_id}
+ mine = {"AND": [{"user_id": user}, app_scope]}
+ if scope == "mine":
+ return mine
+ projects = [{"AND": [{"agent_id": project_id}, app_scope]} for project_id in _shared_project_ids(repo)]
+ shared: dict[str, Any] = projects[0] if len(projects) == 1 else {"OR": projects}
+ if scope == "dir" and repo.directory:
+ shared = {"AND": [shared, {"metadata": {"dirs": {"contains": repo.directory}}}]}
+ return {"OR": [shared, mine]}
+
+
+def search_scope() -> str:
+ configured = (
+ _plugin_option("search_scope", "MEM0_CODE_SEARCH_SCOPE") or ""
+ ).strip().lower()
+ return configured if configured in SEARCH_SCOPES else DEFAULT_SEARCH_SCOPE
+
+
+def resolve_search_scope(scope: str | None) -> str:
+ value = (scope or search_scope()).strip().lower()
+ if value not in SEARCH_SCOPES:
+ raise ValueError(f"Unknown search scope: {value}")
+ return value
+
+
+def _legacy_project_map(cwd: str, root: str, raw_remote: str) -> str:
+ """Return the project name used by the previous Claude Code plugin."""
+ try:
+ data = json.loads((Path.home() / ".mem0" / "project_map.json").read_text())
+ except (OSError, json.JSONDecodeError):
+ return ""
+ if not isinstance(data, dict):
+ return ""
+
+ keys = list(dict.fromkeys([cwd, root, os.path.realpath(cwd), os.path.realpath(root)]))
+ if raw_remote:
+ keys.append(f"remote:{hashlib.sha256(raw_remote.encode()).hexdigest()[:16]}")
+ for key in keys:
+ value = data.get(key)
+ if isinstance(value, str) and value.strip():
+ return value.strip()
+ return ""
+
+
+def _legacy_project_id(cwd: str, root: str, raw_remote: str, identity: str) -> str:
+ """Use the repository namespace created by the previous Mem0 plugin."""
+ configured = _scope_value(os.environ.get("MEM0_PROJECT_ID"))
+ if configured:
+ return configured
+
+ mapped = _scope_value(_legacy_project_map(cwd, root, raw_remote))
+ if mapped:
+ return mapped
+
+ remote = raw_remote or ("" if identity.startswith("local:") else identity)
+ remote = remote.strip().removesuffix(".git")
+ for prefix in ("https://", "http://", "ssh://", "git://"):
+ if remote.startswith(prefix):
+ remote = remote[len(prefix) :]
+ break
+ else:
+ remote = re.sub(r"^git@", "", remote)
+ parts = [part for part in remote.replace(":", "/", 1).split("/") if part]
+ if len(parts) >= 2:
+ return f"{parts[-2]}-{parts[-1]}".replace("/", "-").replace(":", "-")
+ if parts:
+ return parts[-1].replace("/", "-").replace(":", "-")
+ return os.path.basename(root or cwd) or "unknown"
+
+
+@dataclass(frozen=True)
+class RepoContext:
+ cwd: str
+ root: str
+ identity: str
+ app_id: str
+ branch: str
+ head_sha: str
+ project_id: str = ""
+ directory: str = ""
+
+
+def _project_id(root: str, identity: str, app_id: str) -> str:
+ """The shared namespace: includes a host hash so repos with the same owner/name on different hosts stay apart."""
+ if not identity.startswith("local:"):
+ return f"{app_id}-{hashlib.sha256(identity.encode()).hexdigest()[:10]}"
+ return f"local-{app_id}-{hashlib.sha256(root.encode()).hexdigest()[:10]}"
+
+
+def _relative_directory(cwd: str, root: str) -> str:
+ relative = os.path.relpath(cwd, root)
+ return "" if relative == "." or relative.startswith("..") else relative.replace(os.sep, "/")
+
+
+@dataclass(frozen=True)
+class MemorySearchResult:
+ succeeded: bool
+ matched_count: int
+ already_shown_count: int
+ memories: list[dict[str, Any]]
+
+
+@functools.lru_cache(maxsize=64)
+def _resolve_repo_cached(cwd: str) -> RepoContext:
+ given_cwd = cwd
+ cwd = os.path.realpath(cwd)
+ given_root = _git(cwd, "rev-parse", "--show-toplevel") or given_cwd
+ root = os.path.realpath(given_root)
+ raw_remote = _git(root, "config", "--get", "remote.origin.url")
+ remote = _normalize_remote(raw_remote)
+ identity = remote or f"local:{root}"
+ app_id = _legacy_project_id(given_cwd, given_root, raw_remote, identity)
+ return RepoContext(
+ cwd=cwd,
+ root=root,
+ identity=identity,
+ app_id=app_id,
+ branch=_git(root, "branch", "--show-current") or "detached",
+ head_sha=_git(root, "rev-parse", "HEAD"),
+ project_id=_project_id(root, identity, app_id),
+ directory=_relative_directory(cwd, root),
+ )
+
+
+def resolve_repo(cwd: str | None) -> RepoContext:
+ return _resolve_repo_cached(os.path.abspath(cwd or os.getcwd()))
+
+
+def api_key() -> str:
+ configured = (
+ os.environ.get("MEM0_API_KEY")
+ or os.environ.get("PLUGIN_OPTION_API_KEY")
+ or os.environ.get("CLAUDE_PLUGIN_OPTION_API_KEY")
+ or os.environ.get("CLAUDE_PLUGIN_OPTION_MEM0_API_KEY")
+ or ""
+ ).strip()
+ if configured:
+ return configured
+ try:
+ return (data_dir() / "api-key").read_text(encoding="utf-8").strip()
+ except OSError:
+ return ""
+
+
+def cache_plugin_api_key() -> bool:
+ """Bridge host's hook-only sensitive config into plugin-owned storage."""
+ configured = (
+ os.environ.get("PLUGIN_OPTION_API_KEY")
+ or os.environ.get("CLAUDE_PLUGIN_OPTION_API_KEY")
+ or os.environ.get("CLAUDE_PLUGIN_OPTION_MEM0_API_KEY")
+ or ""
+ ).strip()
+ if not configured:
+ return False
+
+ directory = data_dir()
+ directory.mkdir(parents=True, exist_ok=True)
+ path = directory / "api-key"
+ temporary = directory / f"api-key.{os.getpid()}.tmp"
+ descriptor = os.open(
+ temporary,
+ os.O_WRONLY | os.O_CREAT | os.O_TRUNC,
+ 0o600,
+ )
+ try:
+ with os.fdopen(descriptor, "w", encoding="utf-8") as handle:
+ handle.write(configured)
+ os.replace(temporary, path)
+ os.chmod(path, 0o600)
+ finally:
+ try:
+ temporary.unlink()
+ except FileNotFoundError:
+ pass
+ return True
+
+
+def clear_stale_api_key_cache() -> bool:
+ """Drop the cached key file once every configured key source is gone."""
+ configured = (
+ os.environ.get("MEM0_API_KEY")
+ or os.environ.get("PLUGIN_OPTION_API_KEY")
+ or os.environ.get("CLAUDE_PLUGIN_OPTION_API_KEY")
+ or os.environ.get("CLAUDE_PLUGIN_OPTION_MEM0_API_KEY")
+ or ""
+ ).strip()
+ if configured:
+ return False
+ path = data_dir() / "api-key"
+ if not path.exists():
+ return False
+ try:
+ path.unlink()
+ except OSError:
+ return False
+ return True
+
+
+def detached_process_kwargs(platform: str | None = None) -> dict:
+ """Keep a spawned worker alive after the coding agent exits, on POSIX and Windows."""
+ if (platform or sys.platform) == "win32":
+ return {
+ "creationflags": subprocess.DETACHED_PROCESS
+ | subprocess.CREATE_NEW_PROCESS_GROUP
+ }
+ return {"start_new_session": True}
+
+
+def _plugin_option(name: str, fallback: str = "") -> str:
+ return (
+ os.environ.get(f"PLUGIN_OPTION_{name.upper()}")
+ or os.environ.get(f"CLAUDE_PLUGIN_OPTION_{name.upper()}")
+ or os.environ.get(fallback)
+ or ""
+ ).strip()
+
+
+def user_id() -> str:
+ return (
+ _scope_value(_plugin_option("user_id", "MEM0_CODE_USER_ID"))
+ or _scope_value(os.environ.get("MEM0_USER_ID"))
+ or _scope_value(os.environ.get("MEM0_RESOLVED_USER_ID"))
+ or _scope_value(os.environ.get("USER"))
+ or _scope_value(os.environ.get("USERNAME"))
+ or "default"
+ )
+
+
+def data_dir() -> Path:
+ configured = (
+ os.environ.get("MEM0_CODE_DATA_DIR")
+ or os.environ.get("MEM0_PLUGIN_DATA_DIR")
+ or os.environ.get("PLUGIN_DATA")
+ or os.environ.get("CLAUDE_PLUGIN_DATA")
+ )
+ return (
+ Path(configured).expanduser() if configured else Path.home() / ".mem0" / _harness_data_dir_name
+ )
+
+
+def _bool_option(name: str, fallback: str, default: bool = False) -> bool:
+ value = _plugin_option(name, fallback)
+ if not value:
+ return default
+ return value.lower() in {"1", "true", "yes", "on"}
+
+
+def _int_option(name: str, fallback: str, default: int) -> int:
+ value = _plugin_option(name, fallback)
+ try:
+ return int(value) if value else default
+ except ValueError:
+ return default
+
+
+
+def _checkpoint_message(event: dict[str, Any]) -> str:
+ kind = event.get("kind")
+ payload = event.get("payload") or {}
+ if kind == "user_prompt":
+ return redact(payload.get("text", "")).strip()
+ if kind == "assistant_stop":
+ transcript_messages = payload.get("transcript_messages") or []
+ if isinstance(transcript_messages, list):
+ text = "\n".join(
+ str(message.get("content") or "")
+ for message in transcript_messages
+ if isinstance(message, dict) and message.get("content")
+ )
+ if text:
+ return text
+ return redact(payload.get("text", "")).strip()
+ if kind in {"subagent_stop", "sidekick_stop"}:
+ return redact(payload.get("final_message", "")).strip()
+ return ""
+
+
+def checkpoint_stats(events: list[dict[str, Any]]) -> tuple[int, int, int]:
+ """Return completed exchanges, messages, and source characters."""
+ completed = sum(event.get("kind") == "assistant_stop" for event in events)
+ contents = [content for event in events if (content := _checkpoint_message(event))]
+ return completed, len(contents), sum(len(content) for content in contents)
+
+
+def select_checkpoint_events(
+ events: list[dict[str, Any]], *, force: bool
+) -> list[dict[str, Any]]:
+ """Select one ordered extraction block without splitting an exchange."""
+ for index, event in enumerate(events):
+ if event.get("kind") != "assistant_stop":
+ continue
+ candidate = events[: index + 1]
+ completed, messages, source_chars = checkpoint_stats(candidate)
+ if (
+ completed >= CHECKPOINT_EXCHANGES
+ or messages >= CHECKPOINT_MESSAGES
+ or source_chars >= CHECKPOINT_SOURCE_CHARS
+ ):
+ return candidate
+ return events if force else []
+
+
+class EvidenceStore:
+ def __init__(self, path: Path | None = None):
+ directory = data_dir() if path is None else path.parent
+ directory.mkdir(parents=True, exist_ok=True)
+ self.path = path or directory / "evidence.sqlite3"
+ try:
+ self._open()
+ except sqlite3.DatabaseError:
+ self._quarantine()
+ self._open()
+
+ def _open(self) -> None:
+ self.conn = sqlite3.connect(self.path, timeout=10)
+ self.conn.row_factory = sqlite3.Row
+ try:
+ self.conn.execute("PRAGMA journal_mode=WAL")
+ self.conn.execute("PRAGMA busy_timeout=10000")
+ self._migrate()
+ except sqlite3.DatabaseError:
+ self.conn.close()
+ raise
+
+ def _quarantine(self) -> None:
+ """Move an unreadable database aside so capture restarts cleanly."""
+ stamp = int(time.time())
+ for suffix in ("", "-wal", "-shm"):
+ source = Path(f"{self.path}{suffix}")
+ try:
+ source.replace(f"{self.path}.corrupt-{stamp}{suffix}")
+ except FileNotFoundError:
+ continue
+ except OSError:
+ try:
+ source.unlink()
+ except OSError:
+ pass
+ telemetry.record("db_quarantined")
+
+ def close(self) -> None:
+ self.conn.close()
+
+ def _migrate(self) -> None:
+ # Keep the legacy table name so existing databases and in-flight workers remain compatible.
+ self.conn.executescript(
+ """
+ CREATE TABLE IF NOT EXISTS events (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ repo_id TEXT NOT NULL,
+ app_id TEXT NOT NULL,
+ session_id TEXT NOT NULL,
+ created_at TEXT NOT NULL,
+ kind TEXT NOT NULL,
+ payload_json TEXT NOT NULL,
+ flush_id TEXT
+ );
+ CREATE INDEX IF NOT EXISTS events_session_idx
+ ON events(repo_id, session_id, flush_id, id);
+
+ CREATE TABLE IF NOT EXISTS session_scopes (
+ session_id TEXT PRIMARY KEY,
+ repo_id TEXT NOT NULL,
+ app_id TEXT NOT NULL,
+ root TEXT NOT NULL,
+ branch TEXT NOT NULL,
+ head_sha TEXT NOT NULL,
+ created_at TEXT NOT NULL,
+ directory TEXT NOT NULL DEFAULT ''
+ );
+
+ CREATE TABLE IF NOT EXISTS flushes (
+ packet_id TEXT PRIMARY KEY,
+ repo_id TEXT NOT NULL,
+ app_id TEXT NOT NULL,
+ session_id TEXT NOT NULL,
+ reason TEXT NOT NULL,
+ event_start INTEGER NOT NULL,
+ event_end INTEGER NOT NULL,
+ status TEXT NOT NULL,
+ episode_event_id TEXT,
+ semantic_event_id TEXT,
+ error TEXT,
+ attempts INTEGER NOT NULL DEFAULT 0,
+ created_at TEXT NOT NULL,
+ updated_at TEXT NOT NULL
+ );
+
+ CREATE TABLE IF NOT EXISTS retrievals (
+ session_id TEXT NOT NULL,
+ repo_id TEXT NOT NULL,
+ memory_id TEXT NOT NULL,
+ injected_at TEXT NOT NULL,
+ rank INTEGER,
+ score REAL,
+ memory_text TEXT,
+ context_chars INTEGER NOT NULL DEFAULT 0,
+ PRIMARY KEY(session_id, repo_id, memory_id)
+ );
+
+ CREATE TABLE IF NOT EXISTS operations (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ created_at TEXT NOT NULL,
+ repo_id TEXT NOT NULL,
+ session_id TEXT NOT NULL,
+ operation TEXT NOT NULL,
+ duration_ms REAL NOT NULL,
+ success INTEGER NOT NULL,
+ item_count INTEGER NOT NULL DEFAULT 0,
+ request_chars INTEGER NOT NULL DEFAULT 0,
+ response_chars INTEGER NOT NULL DEFAULT 0,
+ error TEXT
+ );
+
+ CREATE TABLE IF NOT EXISTS sidekick_runs (
+ repo_id TEXT NOT NULL,
+ session_id TEXT NOT NULL,
+ agent_id TEXT NOT NULL,
+ agent_type TEXT NOT NULL,
+ started_at TEXT NOT NULL,
+ stopped_at TEXT,
+ transcript_path TEXT,
+ context_chars INTEGER NOT NULL DEFAULT 0,
+ final_message TEXT,
+ PRIMARY KEY(repo_id, session_id, agent_id)
+ );
+ CREATE INDEX IF NOT EXISTS sidekick_runs_repo_idx
+ ON sidekick_runs(repo_id, started_at);
+
+ CREATE TABLE IF NOT EXISTS settings (
+ key TEXT PRIMARY KEY,
+ value TEXT NOT NULL,
+ updated_at TEXT NOT NULL
+ );
+
+ """
+ )
+ # Remove the pre-0.1.1 snapshot implementation.
+ self.conn.executescript(
+ """
+ DROP TABLE IF EXISTS sidekick_calls;
+ DROP TABLE IF EXISTS sidekick_snapshots;
+ DROP TABLE IF EXISTS sidekick_state;
+ DROP TABLE IF EXISTS sidekick_packets;
+ """
+ )
+ self._ensure_column("retrievals", "rank", "INTEGER")
+ self._ensure_column("retrievals", "score", "REAL")
+ self._ensure_column("retrievals", "memory_text", "TEXT")
+ self._ensure_column("retrievals", "context_chars", "INTEGER NOT NULL DEFAULT 0")
+ self._ensure_column("flushes", "attempts", "INTEGER NOT NULL DEFAULT 0")
+ self._ensure_column("session_scopes", "directory", "TEXT NOT NULL DEFAULT ''")
+ self.conn.commit()
+
+ def _ensure_column(self, table: str, column: str, declaration: str) -> None:
+ columns = {
+ str(row["name"])
+ for row in self.conn.execute(f"PRAGMA table_info({table})").fetchall()
+ }
+ if column not in columns:
+ self.conn.execute(f"ALTER TABLE {table} ADD COLUMN {column} {declaration}")
+
+ def record_event(
+ self,
+ repo: RepoContext,
+ session_id: str,
+ kind: str,
+ payload: dict[str, Any],
+ ) -> int:
+ cursor = self.conn.execute(
+ """INSERT INTO events
+ (repo_id, app_id, session_id, created_at, kind, payload_json)
+ VALUES (?, ?, ?, ?, ?, ?)""",
+ (
+ repo.identity,
+ repo.app_id,
+ session_id,
+ utc_now(),
+ kind,
+ json.dumps(payload, ensure_ascii=False, sort_keys=True),
+ ),
+ )
+ self.conn.commit()
+ return int(cursor.lastrowid)
+
+ def record_assistant_response(self, repo: RepoContext, session_id: str, message: str) -> None:
+ """Ignore repeated response hooks until another prompt or a different answer arrives."""
+ with self.conn:
+ # Serialize the check and insert across concurrent Stop and SessionEnd hooks.
+ self.conn.execute("BEGIN IMMEDIATE")
+ previous = self.conn.execute(
+ """SELECT kind, payload_json FROM events
+ WHERE repo_id = ? AND session_id = ? AND kind IN ('user_prompt', 'assistant_stop')
+ ORDER BY id DESC LIMIT 1""",
+ (repo.identity, session_id),
+ ).fetchone()
+ if (
+ previous is not None
+ and previous["kind"] == "assistant_stop"
+ and json.loads(previous["payload_json"]).get("text") == message
+ ):
+ return
+ self.record_event(repo, session_id, "assistant_stop", {"text": message})
+
+ def repo_for_session(self, session_id: str, cwd: str | None) -> RepoContext:
+ """Keep one project scope for every hook in a coding-agent session."""
+ current = resolve_repo(cwd)
+ if session_id == "unknown-session":
+ return current
+
+ with self.conn:
+ self.conn.execute(
+ """INSERT OR IGNORE INTO session_scopes
+ (session_id, repo_id, app_id, root, branch, head_sha, created_at, directory)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)""",
+ (
+ session_id,
+ current.identity,
+ current.app_id,
+ current.root,
+ current.branch,
+ current.head_sha,
+ utc_now(),
+ current.directory,
+ ),
+ )
+ scope = self.conn.execute(
+ "SELECT * FROM session_scopes WHERE session_id = ?", (session_id,)
+ ).fetchone()
+ same_git_repo = (
+ current.identity == scope["repo_id"] and bool(current.head_sha)
+ )
+ pinned = current if same_git_repo else resolve_repo(str(scope["root"]))
+ return RepoContext(
+ cwd=current.cwd,
+ root=pinned.root,
+ identity=str(scope["repo_id"]),
+ app_id=str(scope["app_id"]),
+ branch=pinned.branch,
+ head_sha=pinned.head_sha,
+ project_id=pinned.project_id,
+ directory=str(scope["directory"] or ""),
+ )
+
+ def prepare_flush(
+ self, repo: RepoContext, session_id: str, reason: str
+ ) -> tuple[str, list[dict[str, Any]]] | None:
+ with self.conn:
+ self.conn.execute("BEGIN IMMEDIATE")
+ existing = self.conn.execute(
+ """SELECT * FROM flushes
+ WHERE repo_id = ? AND session_id = ?
+ AND status NOT IN ('semantic-succeeded', 'explicitly-stored', 'gave-up')
+ ORDER BY created_at LIMIT 1""",
+ (repo.identity, session_id),
+ ).fetchone()
+ if existing and int(existing["attempts"] or 0) >= MAX_FLUSH_ATTEMPTS:
+ self.conn.execute(
+ "UPDATE flushes SET status = 'gave-up', updated_at = ? WHERE packet_id = ?",
+ (utc_now(), existing["packet_id"]),
+ )
+ telemetry.record(
+ "flush",
+ repo=repo,
+ session_id=session_id,
+ reason=reason,
+ status="gave-up",
+ success=False,
+ attempts=int(existing["attempts"] or 0),
+ )
+ existing = None
+ if existing:
+ if reason != "periodic" and existing["reason"] == "periodic":
+ self.conn.execute(
+ "UPDATE flushes SET reason = ?, updated_at = ? WHERE packet_id = ?",
+ (reason, utc_now(), existing["packet_id"]),
+ )
+ existing_rows = self.conn.execute(
+ "SELECT * FROM events WHERE flush_id = ? ORDER BY id",
+ (existing["packet_id"],),
+ ).fetchall()
+ if existing_rows:
+ return str(existing["packet_id"]), [
+ {
+ "id": row["id"],
+ "created_at": row["created_at"],
+ "kind": row["kind"],
+ "payload": json.loads(row["payload_json"]),
+ }
+ for row in existing_rows
+ ]
+
+ rows = self.conn.execute(
+ """SELECT * FROM events
+ WHERE repo_id = ? AND session_id = ? AND flush_id IS NULL
+ ORDER BY id""",
+ (repo.identity, session_id),
+ ).fetchall()
+ if not rows:
+ return None
+
+ events = [
+ {
+ "id": row["id"],
+ "created_at": row["created_at"],
+ "kind": row["kind"],
+ "payload": json.loads(row["payload_json"]),
+ }
+ for row in rows
+ ]
+ events = select_checkpoint_events(events, force=reason != "periodic")
+ if not events:
+ return None
+ event_start, event_end = events[0]["id"], events[-1]["id"]
+ packet_material = f"{repo.identity}\0{session_id}\0{event_start}\0{event_end}"
+ packet_id = hashlib.sha256(packet_material.encode()).hexdigest()[:32]
+ now = utc_now()
+
+ self.conn.execute(
+ """INSERT OR IGNORE INTO flushes
+ (packet_id, repo_id, app_id, session_id, reason, event_start,
+ event_end, status, created_at, updated_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, 'prepared', ?, ?)""",
+ (
+ packet_id,
+ repo.identity,
+ repo.app_id,
+ session_id,
+ reason,
+ event_start,
+ event_end,
+ now,
+ now,
+ ),
+ )
+ event_ids = [event["id"] for event in events]
+ placeholders = ", ".join("?" for _ in event_ids)
+ self.conn.execute(
+ f"UPDATE events SET flush_id = ? "
+ f"WHERE id IN ({placeholders}) AND flush_id IS NULL",
+ (packet_id, *event_ids),
+ )
+ return packet_id, events
+
+ def checkpoint_due(self, repo_id: str, session_id: str) -> bool:
+ if self.has_inflight_flush(repo_id, session_id):
+ return False
+ rows = self.conn.execute(
+ """SELECT * FROM events
+ WHERE repo_id = ? AND session_id = ? AND flush_id IS NULL
+ ORDER BY id""",
+ (repo_id, session_id),
+ ).fetchall()
+ events = [
+ {
+ "id": row["id"],
+ "created_at": row["created_at"],
+ "kind": row["kind"],
+ "payload": json.loads(row["payload_json"]),
+ }
+ for row in rows
+ ]
+ return bool(select_checkpoint_events(events, force=False))
+
+ def has_inflight_flush(self, repo_id: str, session_id: str) -> bool:
+ return (
+ self.conn.execute(
+ """SELECT 1 FROM flushes
+ WHERE repo_id = ? AND session_id = ?
+ AND status IN ('prepared', 'semantic-queued')
+ LIMIT 1""",
+ (repo_id, session_id),
+ ).fetchone()
+ is not None
+ )
+
+ def flush_record(self, packet_id: str) -> dict[str, Any] | None:
+ row = self.conn.execute(
+ "SELECT * FROM flushes WHERE packet_id = ?", (packet_id,)
+ ).fetchone()
+ return dict(row) if row else None
+
+ def has_unflushed_events(self, repo_id: str, session_id: str) -> bool:
+ return (
+ self.conn.execute(
+ """SELECT 1 FROM events
+ WHERE repo_id = ? AND session_id = ? AND flush_id IS NULL
+ LIMIT 1""",
+ (repo_id, session_id),
+ ).fetchone()
+ is not None
+ )
+
+ def unflushed_starts_with_session_start(
+ self, repo_id: str, session_id: str
+ ) -> bool:
+ row = self.conn.execute(
+ """SELECT kind FROM events
+ WHERE repo_id = ? AND session_id = ? AND flush_id IS NULL
+ ORDER BY id LIMIT 1""",
+ (repo_id, session_id),
+ ).fetchone()
+ return bool(row and row["kind"] == "session_start")
+
+ def update_flush(self, packet_id: str, **fields: Any) -> None:
+ allowed = {"status", "episode_event_id", "semantic_event_id", "error"}
+ updates = {key: value for key, value in fields.items() if key in allowed}
+ updates["updated_at"] = utc_now()
+ clause = ", ".join(f"{key} = ?" for key in updates)
+ failed = str(fields.get("status", "")) in {
+ "error",
+ "semantic-failed",
+ "semantic-timeout",
+ "semantic-missing",
+ }
+ if failed:
+ clause += ", attempts = attempts + 1"
+ with self.conn:
+ self.conn.execute(
+ f"UPDATE flushes SET {clause} WHERE packet_id = ?",
+ [*updates.values(), packet_id],
+ )
+
+ def unseen(
+ self, session_id: str, repo_id: str, memories: Iterable[dict[str, Any]]
+ ) -> list[dict[str, Any]]:
+ seen = {
+ row["memory_id"]
+ for row in self.conn.execute(
+ "SELECT memory_id FROM retrievals WHERE session_id = ? AND repo_id = ?",
+ (session_id, repo_id),
+ )
+ }
+ return [memory for memory in memories if str(memory.get("id", "")) not in seen]
+
+ def mark_injected(
+ self, session_id: str, repo_id: str, memories: Iterable[dict[str, Any]]
+ ) -> None:
+ now = utc_now()
+ with self.conn:
+ for rank, memory in enumerate(memories, start=1):
+ memory_id = str(memory.get("id", ""))
+ if memory_id:
+ memory_text = bounded(
+ memory.get("memory") or memory.get("text") or "",
+ 4000,
+ )
+ try:
+ score = float(memory["score"])
+ except (KeyError, TypeError, ValueError):
+ score = None
+ self.conn.execute(
+ """INSERT OR IGNORE INTO retrievals
+ (session_id, repo_id, memory_id, injected_at, rank,
+ score, memory_text, context_chars)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)""",
+ (
+ session_id,
+ repo_id,
+ memory_id,
+ now,
+ rank,
+ score,
+ memory_text,
+ len(memory_text),
+ ),
+ )
+
+ def injected_memories(
+ self, session_id: str, repo_id: str
+ ) -> list[dict[str, Any]]:
+ """Return the exact memories already supplied to the main conversation."""
+ rows = self.conn.execute(
+ """SELECT memory_id, rank, score, memory_text
+ FROM retrievals
+ WHERE session_id = ? AND repo_id = ?
+ ORDER BY COALESCE(rank, 2147483647), injected_at, memory_id""",
+ (session_id, repo_id),
+ ).fetchall()
+ return [
+ {
+ "id": row["memory_id"],
+ "memory": row["memory_text"],
+ "score": row["score"],
+ }
+ for row in rows
+ if row["memory_text"]
+ ]
+
+ def start_subagent(
+ self,
+ repo: RepoContext,
+ session_id: str,
+ agent_id: str,
+ agent_type: str,
+ context_chars: int,
+ ) -> bool:
+ """Record one native subagent instance and whether context was first sent."""
+ with self.conn:
+ cursor = self.conn.execute(
+ """INSERT OR IGNORE INTO sidekick_runs
+ (repo_id, session_id, agent_id, agent_type, started_at,
+ context_chars)
+ VALUES (?, ?, ?, ?, ?, ?)""",
+ (
+ repo.identity,
+ session_id,
+ agent_id,
+ agent_type,
+ utc_now(),
+ context_chars,
+ ),
+ )
+ return int(cursor.rowcount) > 0
+
+ def stop_subagent(
+ self,
+ repo: RepoContext,
+ session_id: str,
+ agent_id: str,
+ agent_type: str,
+ transcript_path: str,
+ final_message: str,
+ ) -> str:
+ now = utc_now()
+ self.conn.execute("BEGIN IMMEDIATE")
+ try:
+ if not agent_id:
+ rows = self.conn.execute(
+ """SELECT agent_id FROM sidekick_runs
+ WHERE repo_id = ? AND session_id = ? AND agent_type = ? AND stopped_at IS NULL
+ LIMIT 2""",
+ (repo.identity, session_id, agent_type),
+ ).fetchall()
+ # Without a host ID, overlapping runs cannot be correlated reliably.
+ agent_id = rows[0]["agent_id"] if len(rows) == 1 else f"unknown-agent-{time.time_ns()}"
+ self.conn.execute(
+ """INSERT INTO sidekick_runs
+ (repo_id, session_id, agent_id, agent_type, started_at,
+ stopped_at, transcript_path, final_message)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
+ ON CONFLICT(repo_id, session_id, agent_id) DO UPDATE SET
+ stopped_at = excluded.stopped_at,
+ transcript_path = excluded.transcript_path,
+ final_message = excluded.final_message""",
+ (
+ repo.identity,
+ session_id,
+ agent_id,
+ agent_type,
+ now,
+ now,
+ bounded(transcript_path, 2000),
+ redact(final_message).strip(),
+ ),
+ )
+ self.conn.commit()
+ except Exception:
+ self.conn.rollback()
+ raise
+ return agent_id
+
+ def operation(
+ self,
+ repo: RepoContext,
+ session_id: str,
+ operation: str,
+ duration_ms: float,
+ success: bool,
+ *,
+ item_count: int = 0,
+ request_chars: int = 0,
+ response_chars: int = 0,
+ error: str = "",
+ ) -> None:
+ with self.conn:
+ self.conn.execute(
+ """INSERT INTO operations
+ (created_at, repo_id, session_id, operation, duration_ms,
+ success, item_count, request_chars, response_chars, error)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
+ (
+ utc_now(),
+ repo.identity,
+ session_id,
+ operation,
+ duration_ms,
+ int(success),
+ item_count,
+ request_chars,
+ response_chars,
+ bounded(error, 1000),
+ ),
+ )
+
+ def has_operation(self, repo_id: str, session_id: str, operation: str) -> bool:
+ row = self.conn.execute(
+ """SELECT 1 FROM operations
+ WHERE repo_id = ? AND session_id = ? AND operation = ?
+ LIMIT 1""",
+ (repo_id, session_id, operation),
+ ).fetchone()
+ return row is not None
+
+ def has_event(self, repo_id: str, session_id: str, kind: str) -> bool:
+ row = self.conn.execute(
+ """SELECT 1 FROM events
+ WHERE repo_id = ? AND session_id = ? AND kind = ?
+ LIMIT 1""",
+ (repo_id, session_id, kind),
+ ).fetchone()
+ return row is not None
+
+ def latest_event_payload(
+ self, repo_id: str, session_id: str, kind: str
+ ) -> dict[str, Any]:
+ row = self.conn.execute(
+ """SELECT payload_json FROM events
+ WHERE repo_id = ? AND session_id = ? AND kind = ?
+ ORDER BY id DESC LIMIT 1""",
+ (repo_id, session_id, kind),
+ ).fetchone()
+ if not row:
+ return {}
+ try:
+ payload = json.loads(row["payload_json"])
+ except json.JSONDecodeError:
+ return {}
+ return payload if isinstance(payload, dict) else {}
+
+ def setting(self, key: str, default: str = "") -> str:
+ row = self.conn.execute(
+ "SELECT value FROM settings WHERE key = ?", (key,)
+ ).fetchone()
+ return str(row["value"]) if row else default
+
+ def set_setting(self, key: str, value: str) -> None:
+ with self.conn:
+ self.conn.execute(
+ """INSERT INTO settings(key, value, updated_at)
+ VALUES (?, ?, ?)
+ ON CONFLICT(key) DO UPDATE SET
+ value = excluded.value,
+ updated_at = excluded.updated_at""",
+ (key, value, utc_now()),
+ )
+
+ def is_paused(self) -> bool:
+ return self.setting("paused", "false").lower() in {
+ "1",
+ "true",
+ "yes",
+ "on",
+ }
+
+ def forget_local_repo(self, repo_id: str) -> dict[str, int]:
+ tables = {
+ "events": "repo_id",
+ "session_scopes": "repo_id",
+ "flushes": "repo_id",
+ "retrievals": "repo_id",
+ "operations": "repo_id",
+ "sidekick_runs": "repo_id",
+ }
+ removed: dict[str, int] = {}
+ with self.conn:
+ for table, column in tables.items():
+ cursor = self.conn.execute(
+ f"DELETE FROM {table} WHERE {column} = ?", (repo_id,)
+ )
+ removed["subagent_runs" if table == "sidekick_runs" else table] = max(int(cursor.rowcount), 0)
+ return removed
+
+ def status(self, repo_id: str) -> dict[str, Any]:
+ def count(table: str) -> int:
+ return int(
+ self.conn.execute(
+ f"SELECT COUNT(*) FROM {table} WHERE repo_id = ?", (repo_id,)
+ ).fetchone()[0]
+ )
+
+ last_operation = self.conn.execute(
+ """SELECT created_at, operation, duration_ms, success, item_count, error
+ FROM operations WHERE repo_id = ? ORDER BY id DESC LIMIT 1""",
+ (repo_id,),
+ ).fetchone()
+ last_subagent = self.conn.execute(
+ """SELECT session_id, agent_id, agent_type, started_at, stopped_at,
+ context_chars
+ FROM sidekick_runs WHERE repo_id = ?
+ ORDER BY started_at DESC LIMIT 1""",
+ (repo_id,),
+ ).fetchone()
+ return {
+ "paused": self.is_paused(),
+ "events": count("events"),
+ "flushes": count("flushes"),
+ "retrievals": count("retrievals"),
+ "subagent_runs": count("sidekick_runs"),
+ "last_operation": dict(last_operation) if last_operation else None,
+ "last_subagent": dict(last_subagent) if last_subagent else None,
+ }
+
+
+def _session_id(hook_input: dict[str, Any]) -> str:
+ return str(hook_input.get("session_id") or "unknown-session")
+
+
+def record_session_start(store: EvidenceStore, hook_input: dict[str, Any]) -> None:
+ session_id = _session_id(hook_input)
+ repo = store.repo_for_session(session_id, hook_input.get("cwd"))
+ store.record_event(
+ repo,
+ session_id,
+ "session_start",
+ {
+ "source": hook_input.get("source", "startup"),
+ "model": bounded(hook_input.get("model", ""), 200),
+ "branch": repo.branch,
+ "head_sha": repo.head_sha,
+ },
+ )
+ telemetry.record(
+ "session_start",
+ repo=repo,
+ session_id=session_id,
+ trigger=bounded(str(hook_input.get("source", "startup")), 60),
+ model=bounded(hook_input.get("model", ""), 200),
+ api_key_configured=bool(api_key()),
+ is_git_repo=not repo.identity.startswith("local:"),
+ )
+
+
+def record_user_prompt(
+ store: EvidenceStore, hook_input: dict[str, Any]
+) -> tuple[RepoContext, str, str, bool]:
+ session_id = _session_id(hook_input)
+ repo = store.repo_for_session(session_id, hook_input.get("cwd"))
+ prompt = redact(hook_input.get("prompt", "")).strip()
+ is_first_prompt = not store.has_event(repo.identity, session_id, "user_prompt")
+ store.record_event(repo, session_id, "user_prompt", {"text": prompt})
+ return repo, session_id, prompt, is_first_prompt
+
+
+def _tool_result_preview(response: Any) -> str:
+ if isinstance(response, dict):
+ selected = {}
+ for key in (
+ "stdout",
+ "stderr",
+ "output",
+ "content",
+ "error",
+ "filePath",
+ "success",
+ "interrupted",
+ ):
+ if key in response:
+ selected[key] = response[key]
+ response = selected or {"keys": sorted(response.keys())[:20]}
+ return bounded(response, MAX_RESULT_CHARS)
+
+
+def tool_payload(hook_input: dict[str, Any], *, failed: bool | None = False) -> dict[str, Any]:
+ name = str(hook_input.get("tool_name") or "unknown")
+ tool_input = hook_input.get("tool_input") or {}
+ if not isinstance(tool_input, dict):
+ tool_input = {}
+ payload: dict[str, Any] = {
+ "tool": name,
+ "failed": failed,
+ "duration_ms": hook_input.get("duration_ms"),
+ "agent_role": "subagent" if hook_input.get("agent_id") else "main",
+ }
+ if hook_input.get("agent_id"):
+ payload["agent_id"] = bounded(hook_input["agent_id"], 200)
+ if hook_input.get("agent_type"):
+ payload["agent_type"] = bounded(hook_input["agent_type"], 200)
+
+ if name in {"Read", "Write", "Edit", "MultiEdit", "NotebookEdit"}:
+ path = tool_input.get("file_path") or tool_input.get("notebook_path")
+ if path:
+ payload["path"] = bounded(path, 1000)
+ if name in {"Write", "Edit", "MultiEdit", "NotebookEdit"}:
+ payload["mutation_chars"] = sum(
+ len(str(tool_input.get(key, "")))
+ for key in ("content", "new_string", "new_source", "edits")
+ )
+ elif name == "Bash" or "command" in tool_input:
+ command = bounded(tool_input.get("command", ""), MAX_COMMAND_CHARS)
+ payload["command"] = command
+ payload["command_kind"] = (
+ "test"
+ if TEST_COMMAND_RE.search(command)
+ else "build"
+ if BUILD_COMMAND_RE.search(command)
+ else "shell"
+ )
+ response = (
+ hook_input.get("error") if failed else hook_input.get("tool_response")
+ )
+ payload["result_preview"] = _tool_result_preview(response)
+ elif name in {"Grep", "Glob", "WebSearch", "WebFetch"}:
+ for key in ("pattern", "path", "query", "url"):
+ if tool_input.get(key):
+ payload[key] = bounded(tool_input[key], 1000)
+ else:
+ payload["input_keys"] = sorted(tool_input.keys())[:20]
+ if failed:
+ payload["error"] = bounded(hook_input.get("error", ""), MAX_RESULT_CHARS)
+
+ if failed and "error" not in payload:
+ payload["error"] = bounded(hook_input.get("error", ""), MAX_RESULT_CHARS)
+ return payload
+
+
+def record_tool(
+ store: EvidenceStore, hook_input: dict[str, Any], *, failed: bool | None = False
+) -> None:
+ session_id = _session_id(hook_input)
+ repo = store.repo_for_session(session_id, hook_input.get("cwd"))
+ payload = tool_payload(hook_input, failed=failed)
+ if payload.get("path"):
+ payload["repo_path"] = _repo_relative_path(repo, str(payload["path"]))
+ store.record_event(
+ repo,
+ session_id,
+ "tool_failure" if failed else "tool_result",
+ payload,
+ )
+
+
+def record_subagent_start(
+ store: EvidenceStore, hook_input: dict[str, Any]
+) -> str:
+ """Record a native subagent and reuse the main turn's retrieved memories."""
+ session_id = _session_id(hook_input)
+ repo = store.repo_for_session(session_id, hook_input.get("cwd"))
+ agent_id = bounded(hook_input.get("agent_id", "unknown-agent"), 200)
+ agent_type = bounded(hook_input.get("agent_type", "unknown-agent"), 200)
+ context = combine_context(
+ format_context(store.injected_memories(session_id, repo.identity))
+ )
+ first_start = store.start_subagent(
+ repo, session_id, agent_id, agent_type, len(context)
+ )
+ store.record_event(
+ repo,
+ session_id,
+ "subagent_start",
+ {
+ "agent_id": agent_id,
+ "agent_type": agent_type,
+ "context_chars": len(context) if first_start else 0,
+ "repo_root": bounded(repo.root, 2000),
+ },
+ )
+ telemetry.record(
+ "subagent",
+ repo=repo,
+ session_id=session_id,
+ phase="start",
+ first_start=first_start,
+ context_chars=len(context) if first_start else 0,
+ )
+ return context if first_start else ""
+
+
+def record_subagent_stop(store: EvidenceStore, hook_input: dict[str, Any]) -> None:
+ session_id = _session_id(hook_input)
+ repo = store.repo_for_session(session_id, hook_input.get("cwd"))
+ agent_type = bounded(hook_input.get("agent_type", "unknown-agent"), 200)
+ agent_id = bounded(hook_input.get("agent_id", ""), 200)
+ final_message = redact(hook_input.get("last_assistant_message", "")).strip()
+ transcript_path = bounded(hook_input.get("agent_transcript_path", ""), 2000)
+ agent_id = store.stop_subagent(
+ repo,
+ session_id,
+ agent_id,
+ agent_type,
+ transcript_path,
+ final_message,
+ )
+ store.record_event(
+ repo,
+ session_id,
+ "subagent_stop",
+ {
+ "agent_id": agent_id,
+ "agent_type": agent_type,
+ "transcript_path": transcript_path,
+ "final_message": final_message,
+ },
+ )
+ telemetry.record(
+ "subagent",
+ repo=repo,
+ session_id=session_id,
+ phase="stop",
+ has_transcript=bool(transcript_path),
+ message_chars=len(final_message),
+ )
+
+
+def _ordered_unique(values: Iterable[str]) -> list[str]:
+ seen: set[str] = set()
+ result = []
+ for value in values:
+ if value and value not in seen:
+ seen.add(value)
+ result.append(value)
+ return result
+
+
+def _repo_relative_path(repo: RepoContext, value: str) -> str:
+ value = str(value or "").strip()
+ if not value:
+ return ""
+ try:
+ path = Path(value)
+ if path.is_absolute():
+ try:
+ return path.resolve().relative_to(Path(repo.root).resolve()).as_posix()
+ except ValueError:
+ return ""
+ except (OSError, ValueError):
+ pass
+ return bounded(value, 1000)
+
+
+def _render_command_lines(commands: list[dict[str, str]]) -> list[str]:
+ lines = []
+ for command in commands:
+ line = f"- [{command['status']}/{command['kind']}] {command['command']}"
+ if command["result"]:
+ line += f" โ {bounded(command['result'], 500).replace(chr(10), ' ')}"
+ lines.append(line)
+ return lines
+
+
+def build_episode(
+ repo: RepoContext,
+ session_id: str,
+ packet_id: str,
+ events: list[dict[str, Any]],
+ *,
+ canonical_task: str = "",
+ task_outcome: str = "",
+) -> tuple[str, dict[str, Any]]:
+ prompts = [
+ redact(e["payload"].get("text", "")).strip()
+ for e in events
+ if e["kind"] == "user_prompt" and e["payload"].get("text")
+ ]
+ assistant_conclusions = [
+ redact(e["payload"].get("text", "")).strip()
+ for e in events
+ if e["kind"] == "assistant_stop" and e["payload"].get("text")
+ ]
+ subagent_outcomes = [
+ redact(e["payload"].get("final_message", "")).strip()
+ for e in events
+ if e["kind"] in {"subagent_stop", "sidekick_stop"} and e["payload"].get("final_message")
+ ]
+ tools = [
+ e["payload"] for e in events if e["kind"] in {"tool_result", "tool_failure"}
+ and e["payload"].get("agent_role", "main") == "main"
+ ]
+ read_paths = _ordered_unique(
+ _repo_relative_path(repo, str(t.get("repo_path") or t.get("path", "")))
+ for t in tools
+ if t.get("tool") == "Read"
+ )
+ modified_paths = _ordered_unique(
+ _repo_relative_path(repo, str(t.get("repo_path") or t.get("path", "")))
+ for t in tools
+ if t.get("tool") in {"Write", "Edit", "MultiEdit", "NotebookEdit"}
+ )
+ searches = [
+ {key: t[key] for key in ("tool", "pattern", "path", "query", "url") if key in t}
+ for t in tools
+ if t.get("tool") in {"Grep", "Glob", "WebSearch", "WebFetch"}
+ ]
+ commands = [
+ {
+ "command": t.get("command", ""),
+ "kind": t.get("command_kind", "shell"),
+ "status": "unknown" if t.get("failed", False) is None else "failed" if t.get("failed") else "succeeded",
+ "result": t.get("result_preview", ""),
+ }
+ for t in tools
+ if t.get("command")
+ ]
+
+ task = bounded(canonical_task or (prompts[0] if prompts else ""), 4000)
+ conclusion = redact(assistant_conclusions[-1] if assistant_conclusions else "").strip()
+ outcome = bounded(task_outcome, 2000)
+
+ extraction_messages: list[dict[str, str]] = []
+ pending_user_messages: list[dict[str, str]] = []
+ if task and not prompts:
+ pending_user_messages.append({"role": "user", "content": task})
+ for event in events:
+ if event["kind"] == "user_prompt" and event["payload"].get("text"):
+ pending_user_messages.append(
+ {
+ "role": "user",
+ "content": redact(event["payload"].get("text", "")).strip(),
+ }
+ )
+ elif event["kind"] == "assistant_stop":
+ transcript_messages = event["payload"].get("transcript_messages") or []
+ if isinstance(transcript_messages, list) and transcript_messages:
+ transcript_users = {
+ redact(message.get("content") or "").strip()
+ for message in transcript_messages
+ if isinstance(message, dict) and message.get("role") == "user"
+ }
+ extraction_messages.extend(
+ message
+ for message in pending_user_messages
+ if message["content"].strip() not in transcript_users
+ )
+ extraction_messages.extend(
+ {
+ "role": str(message.get("role") or ""),
+ "content": redact(message.get("content") or "").strip(),
+ }
+ for message in transcript_messages
+ if isinstance(message, dict)
+ and message.get("role") in {"user", "assistant"}
+ and message.get("content")
+ )
+ else:
+ extraction_messages.extend(pending_user_messages)
+ if event["payload"].get("text"):
+ extraction_messages.append(
+ {
+ "role": "assistant",
+ "content": redact(event["payload"].get("text", "")).strip(),
+ }
+ )
+ pending_user_messages = []
+ elif event["kind"] in {"subagent_stop", "sidekick_stop"}:
+ pass
+ extraction_messages.extend(pending_user_messages)
+
+ structured = {
+ "packet_id": packet_id,
+ "repo": repo.identity,
+ "app_id": repo.app_id,
+ "session_id": session_id,
+ "branch": repo.branch,
+ "head_sha": repo.head_sha,
+ "task": task,
+ "task_outcome": outcome,
+ "assistant_conclusion": conclusion,
+ "user_messages": prompts,
+ "assistant_outcomes": assistant_conclusions,
+ "subagent_outcomes": subagent_outcomes,
+ "extraction_messages": extraction_messages,
+ "files_read": read_paths[:50],
+ "files_modified": modified_paths[:50],
+ "searches": searches[-30:],
+ "commands": commands[-30:],
+ }
+ lines = ["Coding-session episode"]
+ if task:
+ lines.extend(["", "Task:", task])
+ if modified_paths:
+ lines.extend(
+ ["", "Files modified:", *[f"- {path}" for path in modified_paths[:50]]]
+ )
+ if read_paths:
+ lines.extend(["", "Files read:", *[f"- {path}" for path in read_paths[:50]]])
+ if commands:
+ lines.append("")
+ lines.append("Observed commands:")
+ lines.extend(_render_command_lines(commands[-30:]))
+ if searches:
+ lines.extend(
+ [
+ "",
+ "Observed searches:",
+ *[
+ f"- {json.dumps(item, ensure_ascii=False, sort_keys=True)}"
+ for item in searches[-20:]
+ ],
+ ]
+ )
+ if conclusion:
+ lines.extend(["", "Agent conclusion:", conclusion])
+ if outcome:
+ lines.extend(["", "Task outcome:", outcome])
+ lines.extend(
+ [
+ "",
+ f"Provenance: repo={repo.identity}; branch={repo.branch}; head={repo.head_sha}; packet={packet_id}",
+ ]
+ )
+ content = "\n".join(lines)
+ return bounded(content, MAX_EPISODE_CHARS), structured
+
+
+def build_semantic_evidence(structured: dict[str, Any]) -> str:
+ """Format changed paths for memory extraction.
+
+ Test and build results remain in the local evidence store for diagnostics,
+ but are not useful repository knowledge by default and should not steer
+ memory extraction toward transient verification details.
+ """
+ modified_paths = [
+ bounded(path, 500) for path in structured.get("files_modified", [])[:20]
+ ]
+ commands = structured.get("commands") or []
+ if not any(command.get("status") == "failed" for command in commands):
+ commands = []
+
+ if not modified_paths and not commands:
+ return ""
+
+ lines = ["Additional repository details from this session"]
+ if modified_paths:
+ lines.extend(
+ [
+ "",
+ "Changed paths:",
+ *[f"- {path}" for path in modified_paths],
+ ]
+ )
+ if commands:
+ lines.extend(["", "Commands run in this session:", *_render_command_lines(commands)])
+ return bounded("\n".join(lines), 8000)
+
+
+def build_extraction_messages(structured: dict[str, Any]) -> list[dict[str, str]]:
+ """Build the session messages sent to Mem0 for memory extraction."""
+ evidence = build_semantic_evidence(structured)
+ messages = [
+ {"role": message["role"], "content": redact(message["content"]).strip()}
+ for message in structured.get("extraction_messages", [])
+ if message.get("role") in {"user", "assistant"} and message.get("content")
+ ]
+ if evidence:
+ for message in reversed(messages):
+ if message["role"] == "assistant":
+ message["content"] = f"{message['content']}\n\n{evidence}"
+ break
+ else:
+ messages.append({"role": "assistant", "content": evidence})
+
+ return messages
+
+
+def _estimated_tokens(value: str) -> int:
+ """Conservatively estimate tokens without adding a tokenizer dependency."""
+ ascii_chars = sum(ord(char) < 128 for char in value)
+ return math.ceil((ascii_chars * 0.4) + (len(value) - ascii_chars))
+
+
+def _message_tokens(messages: list[dict[str, str]]) -> int:
+ return _estimated_tokens(json.dumps(messages, ensure_ascii=False))
+
+
+def _is_agent_assignment(message: dict[str, str]) -> bool:
+ return message.get("role") == "assistant" and message.get(
+ "content", ""
+ ).startswith("Subagent assignment (")
+
+
+def _is_agent_response(message: dict[str, str]) -> bool:
+ return message.get("role") == "assistant" and message.get(
+ "content", ""
+ ).startswith("Subagent response (")
+
+
+def extraction_message_batches(
+ messages: list[dict[str, str]],
+ *,
+ max_tokens: int = MAX_EXTRACTION_INPUT_TOKENS,
+) -> list[list[dict[str, str]]]:
+ """Keep exchanges together when possible; split oversized messages to enforce the request budget."""
+ if not messages or _message_tokens(messages) <= max_tokens:
+ return [messages]
+
+ exchanges: list[list[dict[str, str]]] = []
+ exchange: list[dict[str, str]] = []
+ for message in messages:
+ if message.get("role") == "user" and exchange:
+ exchanges.append(exchange)
+ exchange = []
+ exchange.append(message)
+ if exchange:
+ exchanges.append(exchange)
+
+ units: list[list[dict[str, str]]] = []
+ for exchange in exchanges:
+ if _message_tokens(exchange) <= max_tokens:
+ units.append(exchange)
+ continue
+ index = 0
+ while index < len(exchange):
+ message = exchange[index]
+ if (
+ _is_agent_assignment(message)
+ and index + 1 < len(exchange)
+ and _is_agent_response(exchange[index + 1])
+ ):
+ units.append(exchange[index : index + 2])
+ index += 2
+ else:
+ units.append([message])
+ index += 1
+
+ bounded_units: list[list[dict[str, str]]] = []
+ for unit in units:
+ if _message_tokens(unit) <= max_tokens:
+ bounded_units.append(unit)
+ continue
+ for message in unit:
+ remaining = message["content"]
+ while remaining:
+ low, high = 0, len(remaining)
+ while low < high:
+ middle = (low + high + 1) // 2
+ if _message_tokens([{**message, "content": remaining[:middle]}]) <= max_tokens:
+ low = middle
+ else:
+ high = middle - 1
+ if low == 0:
+ raise ValueError("Extraction token budget cannot fit a message")
+ bounded_units.append([{**message, "content": remaining[:low]}])
+ remaining = remaining[low:]
+
+ batches: list[list[dict[str, str]]] = []
+ batch: list[dict[str, str]] = []
+ for unit in bounded_units:
+ candidate = [*batch, *unit]
+ if batch and _message_tokens(candidate) > max_tokens:
+ batches.append(batch)
+ batch = list(unit)
+ else:
+ batch = candidate
+ if batch:
+ batches.append(batch)
+ return batches
+
+
+# Platform surface attribution. Read from the generated per-host module so a new
+# entrypoint is correct without remembering to configure anything.
+try: # pragma: no cover - absent only in the un-built shared source tree
+ from _harness_id import PLATFORM_APPLICATION as _PLATFORM_APPLICATION
+ from _harness_id import PLATFORM_SOURCE as _PLATFORM_SOURCE
+except ImportError:
+ _PLATFORM_SOURCE = "MEM0_PLUGIN"
+ _PLATFORM_APPLICATION = ""
+
+
+def platform_headers(key: str) -> dict[str, str]:
+ """Auth plus the three surface-identity headers.
+
+ X-Mem0-Source and X-Application are set-once by contract: this is the
+ outermost layer, so it sets them, and nothing below may overwrite them.
+ X-Mem0-Client is append-only โ anything downstream adds itself to the tail.
+ """
+ headers = {
+ "Authorization": f"Token {key}",
+ "Content-Type": "application/json",
+ "X-Mem0-Source": _PLATFORM_SOURCE,
+ "X-Mem0-Client": f"mem0-plugin/{PLUGIN_VERSION}",
+ }
+ if _PLATFORM_APPLICATION:
+ headers["X-Application"] = _PLATFORM_APPLICATION
+ return headers
+
+
+def _request_json(
+ url: str, key: str, payload: dict[str, Any], timeout: float
+) -> tuple[dict[str, Any] | list[Any], int, int]:
+ raw = json.dumps(payload, ensure_ascii=False).encode()
+ request = urllib.request.Request(
+ url,
+ data=raw,
+ headers=platform_headers(key),
+ method="POST",
+ )
+ with urllib.request.urlopen(request, timeout=timeout) as response:
+ response_raw = response.read()
+ parsed = json.loads(response_raw or b"{}")
+ return parsed, len(raw), len(response_raw)
+
+
+def _request_json_with_network_retry(
+ url: str, key: str, payload: dict[str, Any], timeout: float
+) -> tuple[dict[str, Any] | list[Any], int, int]:
+ """Retry one transient connection failure without retrying API responses."""
+ try:
+ return _request_json(url, key, payload, timeout)
+ except urllib.error.HTTPError:
+ raise
+ except (urllib.error.URLError, TimeoutError, OSError):
+ time.sleep(0.25)
+ return _request_json(url, key, payload, timeout)
+
+
+def _get_json(
+ url: str, key: str, timeout: float
+) -> tuple[dict[str, Any] | list[Any], int]:
+ request = urllib.request.Request(
+ url,
+ headers=platform_headers(key),
+ method="GET",
+ )
+ with urllib.request.urlopen(request, timeout=timeout) as response:
+ response_raw = response.read()
+ return json.loads(response_raw or b"{}"), len(response_raw)
+
+
+def _event_id(response: dict[str, Any] | list[Any]) -> str:
+ return str(response.get("event_id", "")) if isinstance(response, dict) else ""
+
+
+def _stored_event_ids(value: Any) -> list[str]:
+ raw = str(value or "")
+ if not raw.startswith("["):
+ return []
+ try:
+ parsed = json.loads(raw)
+ except json.JSONDecodeError:
+ return []
+ return [str(item or "") for item in parsed] if isinstance(parsed, list) else []
+
+
+def _result_count(response: dict[str, Any] | list[Any]) -> int:
+ if isinstance(response, dict):
+ results = response.get("results")
+ return len(results) if isinstance(results, list) else 0
+ return len(response) if isinstance(response, list) else 0
+
+
+def touch_handoff_heartbeat() -> None:
+ """Mark the worker's handoff file alive so recovery does not relaunch it."""
+ path = os.environ.get("MEM0_CODE_HANDOFF_PATH", "")
+ if not path:
+ return
+ try:
+ os.utime(path)
+ except OSError:
+ pass
+
+
+def _wait_for_event(api_url: str, key: str, event_id: str) -> tuple[str, int, int]:
+ """Wait for extraction to finish before a later task can search the store."""
+ if not event_id:
+ return "MISSING", 0, 0
+ wait_seconds = float(os.environ.get("MEM0_CODE_EXTRACTION_WAIT_SECONDS", "120"))
+ poll_seconds = max(float(os.environ.get("MEM0_CODE_EVENT_POLL_SECONDS", "1")), 0.1)
+ deadline = time.monotonic() + wait_seconds
+ response_chars = 0
+ while time.monotonic() < deadline:
+ touch_handoff_heartbeat()
+ try:
+ response, size = _get_json(
+ f"{api_url}/v1/event/{event_id}/",
+ key,
+ min(10, poll_seconds + 5),
+ )
+ except urllib.error.HTTPError as exc:
+ if exc.code not in {408, 429} and exc.code < 500:
+ raise
+ time.sleep(poll_seconds)
+ continue
+ except (urllib.error.URLError, TimeoutError, OSError):
+ # The extraction job is durable server-side. A transient polling
+ # failure must not discard a job that may still complete normally.
+ time.sleep(poll_seconds)
+ continue
+ response_chars += size
+ status = (
+ str(response.get("status", "UNKNOWN"))
+ if isinstance(response, dict)
+ else "UNKNOWN"
+ )
+ if status in {"SUCCEEDED", "FAILED"}:
+ return status, response_chars, _result_count(response)
+ time.sleep(poll_seconds)
+ return "TIMEOUT", response_chars, 0
+
+
+def _record_flush(
+ repo: RepoContext,
+ session_id: str,
+ reason: str,
+ status: str,
+ elapsed: float,
+ **extra: Any,
+) -> None:
+ telemetry.record(
+ "flush",
+ repo=repo,
+ session_id=session_id,
+ reason=reason,
+ status=status,
+ success=status in {"semantic-succeeded", "nothing-to-flush"},
+ duration_ms=round(elapsed, 2),
+ **extra,
+ )
+
+
+def flush_session(
+ store: EvidenceStore, hook_input: dict[str, Any], reason: str
+) -> dict[str, Any]:
+ key = api_key()
+ if not key:
+ telemetry.record("flush", reason=reason, status="local-only", success=False)
+ return {"status": "local-only", "reason": "no-api-key"}
+
+ session_id = _session_id(hook_input)
+ if session_id == "unknown-session":
+ telemetry.record("flush", reason=reason, status="no-session-id", success=False)
+ return {"status": "error", "reason": "no-session-id"}
+ repo = store.repo_for_session(session_id, hook_input.get("cwd"))
+ prepared = store.prepare_flush(repo, session_id, reason)
+ if prepared is None:
+ return {"status": "nothing-to-flush"}
+ packet_id, events = prepared
+ existing_flush = store.flush_record(packet_id) or {}
+
+ _, structured = build_episode(
+ repo,
+ session_id,
+ packet_id,
+ events,
+ canonical_task=bounded(hook_input.get("task", ""), 4000),
+ task_outcome=bounded(hook_input.get("task_outcome", ""), 2000),
+ )
+
+ metadata = {"source": _harness_source_tag}
+ if repo.branch and repo.branch not in {"detached", "unknown"}:
+ metadata["branch"] = repo.branch
+ if repo.head_sha:
+ metadata["git_sha"] = repo.head_sha
+ api_url = os.environ.get("MEM0_API_URL", DEFAULT_API_URL).rstrip("/")
+ add_url = f"{api_url}/v3/memories/add/"
+
+ write_user = _scope_value(user_id())
+ write_project = _scope_value(repo.project_id)
+ if not write_user or not _scope_value(repo.app_id) or not write_project:
+ telemetry.record("flush", reason=reason, status="unscoped", success=False)
+ return {"status": "error", "reason": "wildcard-scope"}
+
+ body = {
+ "agent_id": write_project,
+ "user_id": write_user,
+ "app_id": repo.app_id,
+ "run_id": session_id,
+ # Top level, not metadata: the backend reads `source` from the body or
+ # the query string, never from metadata, which is where this used to
+ # sit. The X-Mem0-Source header is also read, but only from the
+ # platform release that ships alongside this change, so the body value
+ # is what makes attribution work on both. The harness tag stays in
+ # metadata as hook provenance.
+ "source": _PLATFORM_SOURCE,
+ "metadata": {**metadata, "author": write_user, "dirs": directory_chain(repo)},
+ "agent_custom_instructions": PROJECT_MEMORY_INSTRUCTIONS,
+ "custom_instructions": PERSONAL_MEMORY_INSTRUCTIONS,
+ "custom_categories": CODING_MEMORY_CATEGORIES,
+ "infer": True,
+ }
+
+ started = time.perf_counter()
+ try:
+ stored_events = _stored_event_ids(existing_flush.get("semantic_event_id"))
+ existing_event = (
+ "" if stored_events else str(existing_flush.get("semantic_event_id") or "")
+ )
+ if existing_event:
+ existing_status, existing_resp, existing_items = _wait_for_event(
+ api_url, key, existing_event
+ )
+ if existing_status == "SUCCEEDED":
+ elapsed = (time.perf_counter() - started) * 1000
+ store.update_flush(
+ packet_id,
+ status="semantic-succeeded",
+ semantic_event_id=existing_event,
+ error="",
+ )
+ store.operation(
+ repo,
+ session_id,
+ "flush-retry",
+ elapsed,
+ True,
+ item_count=existing_items,
+ response_chars=existing_resp,
+ )
+ _record_flush(
+ repo,
+ session_id,
+ reason,
+ "semantic-succeeded",
+ elapsed,
+ memory_count=existing_items,
+ resumed=True,
+ )
+ effective_reason = str(
+ (store.flush_record(packet_id) or {}).get("reason") or reason
+ )
+ if (
+ store.has_unflushed_events(repo.identity, session_id)
+ and not store.unflushed_starts_with_session_start(
+ repo.identity, session_id
+ )
+ and (
+ effective_reason != "periodic"
+ or store.checkpoint_due(repo.identity, session_id)
+ )
+ ):
+ return flush_session(store, hook_input, effective_reason)
+ return {
+ "status": "semantic-succeeded",
+ "packet_id": packet_id,
+ "semantic_event_id": existing_event,
+ "semantic_status": existing_status,
+ "memory_count": existing_items,
+ "duration_ms": round(elapsed, 2),
+ "resumed": True,
+ }
+ if existing_status == "TIMEOUT":
+ elapsed = (time.perf_counter() - started) * 1000
+ error = "semantic extraction event timed out"
+ store.update_flush(packet_id, status="semantic-timeout", error=error)
+ store.operation(
+ repo,
+ session_id,
+ "flush-retry",
+ elapsed,
+ False,
+ response_chars=existing_resp,
+ error=error,
+ )
+ _record_flush(
+ repo,
+ session_id,
+ reason,
+ "semantic-timeout",
+ elapsed,
+ resumed=True,
+ error_kind="timeout",
+ )
+ return {
+ "status": "semantic-timeout",
+ "packet_id": packet_id,
+ "semantic_event_id": existing_event,
+ "duration_ms": round(elapsed, 2),
+ "resumed": True,
+ }
+
+ message_batches = [
+ batch
+ for batch in extraction_message_batches(
+ build_extraction_messages(structured)
+ )
+ if batch
+ ]
+ batches = [(body, messages) for messages in message_batches]
+ if not batches:
+ store.update_flush(packet_id, status="semantic-succeeded", error="")
+ return {"status": "nothing-to-flush", "packet_id": packet_id}
+ operation_name = "flush-retry" if stored_events else "flush"
+ semantic_events = stored_events[: len(batches)]
+ semantic_events += [""] * (len(batches) - len(semantic_events))
+ semantic_req = 0
+ semantic_resp = 0
+ for index, (body, messages) in enumerate(batches):
+ if semantic_events[index]:
+ continue
+ semantic_response, request_chars, response_chars = _request_json(
+ add_url,
+ key,
+ {**body, "messages": messages},
+ 15,
+ )
+ semantic_events[index] = _event_id(semantic_response)
+ semantic_req += request_chars
+ semantic_resp += response_chars
+ store.update_flush(
+ packet_id,
+ status="semantic-queued",
+ semantic_event_id=json.dumps(semantic_events),
+ )
+
+ semantic_event = semantic_events[-1]
+ semantic_status = "SUCCEEDED"
+ event_resp = 0
+ semantic_items = 0
+ failed_event = semantic_event
+ for index, queued_event in enumerate(semantic_events):
+ status, response_chars, item_count = _wait_for_event(
+ api_url, key, queued_event
+ )
+ event_resp += response_chars
+ semantic_items += item_count
+ if status != "SUCCEEDED":
+ semantic_status = status
+ failed_event = queued_event
+ if status in {"FAILED", "MISSING"}:
+ semantic_events[index] = ""
+ store.update_flush(
+ packet_id, semantic_event_id=json.dumps(semantic_events)
+ )
+ break
+ if semantic_status != "SUCCEEDED":
+ elapsed = (time.perf_counter() - started) * 1000
+ error = f"semantic extraction event {semantic_status.lower()}"
+ store.update_flush(
+ packet_id, status=f"semantic-{semantic_status.lower()}", error=error
+ )
+ store.operation(
+ repo,
+ session_id,
+ operation_name,
+ elapsed,
+ False,
+ item_count=semantic_items,
+ request_chars=semantic_req,
+ response_chars=semantic_resp + event_resp,
+ error=error,
+ )
+ _record_flush(
+ repo,
+ session_id,
+ reason,
+ f"semantic-{semantic_status.lower()}",
+ elapsed,
+ memory_count=semantic_items,
+ batch_count=len(batches),
+ error_kind=telemetry.error_kind(error),
+ )
+ return {
+ "status": f"semantic-{semantic_status.lower()}",
+ "packet_id": packet_id,
+ "semantic_event_id": failed_event,
+ "memory_count": semantic_items,
+ "duration_ms": round(elapsed, 2),
+ }
+
+ elapsed = (time.perf_counter() - started) * 1000
+ store.update_flush(
+ packet_id,
+ status="semantic-succeeded",
+ semantic_event_id=json.dumps(semantic_events),
+ error="",
+ )
+ store.operation(
+ repo,
+ session_id,
+ operation_name,
+ elapsed,
+ True,
+ item_count=semantic_items,
+ request_chars=semantic_req,
+ response_chars=semantic_resp + event_resp,
+ )
+ _record_flush(
+ repo,
+ session_id,
+ reason,
+ "semantic-succeeded",
+ elapsed,
+ memory_count=semantic_items,
+ batch_count=len(batches),
+ request_chars=semantic_req,
+ )
+ effective_reason = str(
+ (store.flush_record(packet_id) or {}).get("reason") or reason
+ )
+ if (
+ store.has_unflushed_events(repo.identity, session_id)
+ and not store.unflushed_starts_with_session_start(
+ repo.identity, session_id
+ )
+ and (
+ effective_reason != "periodic"
+ or store.checkpoint_due(repo.identity, session_id)
+ )
+ ):
+ return flush_session(store, hook_input, effective_reason)
+ return {
+ "status": "semantic-succeeded",
+ "packet_id": packet_id,
+ "semantic_event_id": semantic_event,
+ "semantic_status": semantic_status,
+ "memory_count": semantic_items,
+ "duration_ms": round(elapsed, 2),
+ }
+ except Exception as exc: # hooks must fail open
+ elapsed = (time.perf_counter() - started) * 1000
+ error = bounded(str(exc), 1000)
+ store.update_flush(packet_id, status="error", error=error)
+ store.operation(repo, session_id, "flush", elapsed, False, error=error)
+ _record_flush(
+ repo,
+ session_id,
+ reason,
+ "error",
+ elapsed,
+ error_kind=telemetry.error_kind(exc),
+ )
+ return {"status": "error", "packet_id": packet_id, "error": error}
+
+
+def checkpoint_session(
+ store: EvidenceStore, hook_input: dict[str, Any], reason: str
+) -> dict[str, Any]:
+ """Run remote extraction at a durable boundary."""
+ return flush_session(store, hook_input, reason)
+
+
+
+def search_memories(
+ store: EvidenceStore | None,
+ repo: RepoContext,
+ session_id: str | None,
+ query: str,
+ *,
+ top_k: int | None = None,
+ category: str | None = None,
+ scope: str | None = None,
+ run_id: str | None = None,
+ operation: str = "search",
+ timeout: float = 5,
+) -> MemorySearchResult:
+ key = api_key()
+ if not key or not query.strip():
+ return MemorySearchResult(False, 0, 0, [])
+ search_once = os.environ.get(
+ "MEM0_CODE_SEARCH_ONCE_PER_SESSION", "false"
+ ).lower() in {
+ "1",
+ "true",
+ "yes",
+ "on",
+ }
+ track_session = store is not None and bool(session_id)
+ if (
+ search_once
+ and track_session
+ and store.has_operation(repo.identity, session_id, "search")
+ ):
+ return MemorySearchResult(False, 0, 0, [])
+
+ result_limit = min(
+ max(
+ top_k
+ if top_k is not None
+ else _int_option("top_k", "MEM0_CODE_TOP_K", 3),
+ 1,
+ ),
+ 20,
+ )
+ if category is not None and category not in CODING_MEMORY_CATEGORY_NAMES:
+ raise ValueError(f"Unknown memory category: {category}")
+ user, project = _scope_value(user_id()), _scope_value(repo.project_id)
+ if not user or not project or not _scope_value(repo.app_id):
+ return MemorySearchResult(False, 0, 0, [])
+ filters = _search_filters(user, repo, resolve_search_scope(scope))
+ if category:
+ filters = {"AND": [filters, {"categories": {"contains": category}}]}
+ if run_id:
+ filters = {"AND": [filters, {"run_id": run_id}]}
+ payload = {
+ "query": query,
+ "app_id": repo.app_id,
+ "filters": filters,
+ "top_k": result_limit,
+ "rerank": False,
+ "latest_only": True,
+ }
+ url = (
+ os.environ.get("MEM0_API_URL", DEFAULT_API_URL).rstrip("/")
+ + "/v3/memories/search/"
+ )
+ started = time.perf_counter()
+ try:
+ response, request_chars, response_chars = _request_json_with_network_retry(
+ url, key, payload, timeout
+ )
+ memories = (
+ response if isinstance(response, list) else response.get("results", [])
+ )
+ memories = [
+ memory
+ for memory in memories
+ if isinstance(memory, dict)
+ and (memory.get("metadata") or {}).get("record_kind") != "task_episode"
+ ][:result_limit]
+ if track_session:
+ returned_memories = store.unseen(session_id, repo.identity, memories)
+ store.mark_injected(session_id, repo.identity, returned_memories)
+ already_shown_count = len(memories) - len(returned_memories)
+ else:
+ returned_memories = memories
+ already_shown_count = 0
+ elapsed = (time.perf_counter() - started) * 1000
+ if track_session:
+ store.operation(
+ repo,
+ session_id,
+ operation,
+ elapsed,
+ True,
+ item_count=len(returned_memories),
+ request_chars=request_chars,
+ response_chars=response_chars,
+ )
+ telemetry.record(
+ "search",
+ repo=repo,
+ session_id=session_id,
+ trigger=operation,
+ success=True,
+ duration_ms=round(elapsed, 2),
+ matched_count=len(memories),
+ returned_count=len(returned_memories),
+ already_shown_count=already_shown_count,
+ top_k=result_limit,
+ has_category=bool(category),
+ )
+ return MemorySearchResult(
+ succeeded=True,
+ matched_count=len(memories),
+ already_shown_count=already_shown_count,
+ memories=returned_memories,
+ )
+ except Exception as exc:
+ elapsed = (time.perf_counter() - started) * 1000
+ if track_session:
+ store.operation(repo, session_id, operation, elapsed, False, error=str(exc))
+ telemetry.record(
+ "search",
+ repo=repo,
+ session_id=session_id,
+ trigger=operation,
+ success=False,
+ duration_ms=round(elapsed, 2),
+ top_k=result_limit,
+ has_category=bool(category),
+ error_kind=telemetry.error_kind(exc),
+ )
+ return MemorySearchResult(False, 0, 0, [])
+
+
+def format_context(
+ memories: list[dict[str, Any]],
+ heading: str = "Relevant repository memories:",
+) -> str:
+ if not memories:
+ return ""
+ limit = min(
+ max(
+ _int_option(
+ "max_context_chars",
+ "MEM0_CODE_MAX_CONTEXT_CHARS",
+ DEFAULT_MAX_CONTEXT_CHARS,
+ ),
+ 1000,
+ ),
+ 10000,
+ )
+ lines = [heading] if heading else []
+ for memory in memories:
+ text = re.sub(
+ r"\s+",
+ " ",
+ redact(memory.get("memory") or memory.get("text") or ""),
+ )
+ text = text.strip()
+ if not text:
+ continue
+ branch = str((memory.get("metadata") or {}).get("branch") or "").strip()
+ branch_label = (
+ f" [learnt on branch {branch}]"
+ if branch.casefold() not in {"", "main", "master", "unknown", "detached"}
+ else ""
+ )
+ number = len(lines) if heading else len(lines) + 1
+ entry = f"{number}. {text}{branch_label}"
+ candidate = "\n".join([*lines, entry])
+ if len(candidate) <= limit:
+ lines.append(entry)
+ continue
+ if not lines or (heading and len(lines) == 1):
+ prefix = f"{number}. "
+ suffix = f"โฆ{branch_label}"
+ available = (
+ limit
+ - len("\n".join(lines))
+ - (1 if lines else 0)
+ - len(prefix)
+ - len(suffix)
+ )
+ if available > 0:
+ lines.append(prefix + text[:available].rstrip() + suffix)
+ break
+ minimum_lines = 2 if heading else 1
+ return "\n".join(lines) if len(lines) >= minimum_lines else ""
+
+
+def format_search_result(result: MemorySearchResult) -> str:
+ """Return only the text the coding agent needs from an explicit memory search."""
+ if not result.succeeded:
+ return "Memory search failed."
+ if result.memories:
+ rendered = format_context(result.memories, heading="")
+ if rendered:
+ return rendered
+ return "No matching memories found."
+
+
+def combine_context(*contexts: str) -> str:
+ """Combine memory sources under one hard budget without repeated lines."""
+ seen: set[str] = set()
+ lines: list[str] = []
+ for context in contexts:
+ for line in str(context or "").splitlines():
+ normalized = re.sub(r"\s+", " ", line).strip().casefold()
+ if not normalized or normalized in seen:
+ continue
+ seen.add(normalized)
+ lines.append(line.rstrip())
+ limit = min(
+ max(
+ _int_option(
+ "max_context_chars",
+ "MEM0_CODE_MAX_CONTEXT_CHARS",
+ DEFAULT_MAX_CONTEXT_CHARS,
+ ),
+ 1000,
+ ),
+ 10000,
+ )
+ return bounded("\n".join(lines), limit) if lines else ""
+
+
+def _scoped_memory_ids(
+ api_url: str, key: str, user: str, repo: RepoContext, include_project: bool
+) -> list[str]:
+ """List this user's memory ids for this repository, plus the shared project memory when asked."""
+ ids: list[str] = []
+ seen: set[str] = set()
+ prefix = repo.app_id
+ _collect_memory_ids(
+ api_url, key, {"user_id": user}, ids, seen,
+ app_id_prefix=prefix,
+ )
+ if include_project:
+ for project_id in _shared_project_ids(repo):
+ _collect_memory_ids(
+ api_url, key, {"agent_id": project_id}, ids, seen,
+ app_id_prefix=prefix,
+ )
+ return ids
+
+
+def _collect_memory_ids(
+ api_url: str,
+ key: str,
+ filters: dict[str, Any],
+ ids: list[str],
+ seen: set[str],
+ *,
+ app_id_prefix: str = "",
+) -> None:
+ """Page through one list filter; the list endpoint returns nothing for an OR whose user branch has no memories."""
+ payload = {"filters": filters}
+ for page in range(1, FORGET_MAX_PAGES + 1):
+ parsed, _, _ = _request_json(
+ f"{api_url}/v2/memories/?page={page}&page_size={FORGET_PAGE_SIZE}",
+ key,
+ payload,
+ 15,
+ )
+ items = parsed.get("results") if isinstance(parsed, dict) else parsed
+ if not isinstance(items, list) or not items:
+ break
+ for item in items:
+ if not isinstance(item, dict):
+ continue
+ memory_id = str(item.get("id", ""))
+ if not memory_id or memory_id in seen:
+ continue
+ if app_id_prefix:
+ item_app_id = str(item.get("app_id") or "")
+ if item_app_id != app_id_prefix and not item_app_id.startswith(app_id_prefix + "/"):
+ continue
+ seen.add(memory_id)
+ ids.append(memory_id)
+ if len(items) < FORGET_PAGE_SIZE:
+ break
+
+
+def _delete_memory(api_url: str, key: str, memory_id: str) -> bool:
+ request = urllib.request.Request(
+ f"{api_url}/v1/memories/{urllib.parse.quote(memory_id)}/",
+ headers=platform_headers(key),
+ method="DELETE",
+ )
+ try:
+ with urllib.request.urlopen(request, timeout=15):
+ return True
+ except Exception:
+ return False
+
+
+def forget_remote_repo(
+ repo: RepoContext, *, include_project_memory: bool = False
+) -> dict[str, Any]:
+ """Delete this user's memories for this repository; project memory is shared, so only on request."""
+ key = api_key()
+ if not key:
+ telemetry.record("forget", repo=repo, success=False, error_kind="no-api-key")
+ return {"status": "error", "error": "Mem0 API key is not configured"}
+ user = _scope_value(user_id())
+ if not user or not _scope_value(repo.app_id) or not _scope_value(repo.project_id):
+ telemetry.record("forget", repo=repo, success=False, error_kind="unscoped")
+ return {
+ "status": "error",
+ "error": "Refusing to forget: the user or repository scope is a wildcard",
+ }
+ api_url = os.environ.get("MEM0_API_URL", DEFAULT_API_URL).rstrip("/")
+ try:
+ memory_ids = _scoped_memory_ids(api_url, key, user, repo, include_project_memory)
+ except Exception as exc:
+ telemetry.record(
+ "forget", repo=repo, success=False, error_kind=telemetry.error_kind(exc)
+ )
+ return {"status": "error", "error": bounded(str(exc), 1000)}
+ deleted = sum(_delete_memory(api_url, key, memory_id) for memory_id in memory_ids)
+ failed = len(memory_ids) - deleted
+ telemetry.record("forget", repo=repo, success=not failed, item_count=deleted)
+ if failed:
+ return {
+ "status": "partial",
+ "deleted": deleted,
+ "failed": failed,
+ "error": f"{failed} of {len(memory_ids)} memories could not be deleted",
+ }
+ return {"status": "deleted", "deleted": deleted}
+
+
+def _doctor_mem0_authentication(repo: RepoContext) -> dict[str, Any]:
+ """Verify the configured key with one read-only, repository-scoped search."""
+ key = api_key()
+ if not key:
+ return {"ok": False, "detail": "API key missing"}
+ payload = {
+ "query": "Mem0 authentication check",
+ "filters": {
+ "AND": [
+ {"user_id": user_id()},
+ {"app_id": repo.app_id},
+ ]
+ },
+ "top_k": 1,
+ "threshold": 1.0,
+ "rerank": False,
+ }
+ url = os.environ.get("MEM0_API_URL", DEFAULT_API_URL).rstrip("/")
+ started = time.perf_counter()
+ try:
+ _request_json(f"{url}/v3/memories/search/", key, payload, 5)
+ except Exception as exc:
+ return {"ok": False, "detail": bounded(str(exc), 300)}
+ elapsed = (time.perf_counter() - started) * 1000
+ return {"ok": True, "detail": f"connected ({elapsed:.0f} ms)"}
+
+
+def _doctor_user_id() -> dict[str, Any]:
+ """Flag a configured user ID the plugin refuses, since the silent fallback surprises people."""
+ configured = _plugin_option("user_id", "MEM0_CODE_USER_ID") or os.environ.get(
+ "MEM0_USER_ID", ""
+ )
+ if configured and not _scope_value(configured):
+ return {
+ "ok": False,
+ "detail": f"configured user_id {configured!r} is a wildcard; using {user_id()!r}",
+ }
+ return {"ok": True, "detail": user_id()}
+
+
+def doctor(cwd: str | None = None) -> dict[str, Any]:
+ repo = resolve_repo(cwd)
+ directory = data_dir()
+ directory.mkdir(parents=True, exist_ok=True)
+ checks: dict[str, dict[str, Any]] = {
+ "python": {
+ "ok": tuple(sys.version_info[:2]) >= (3, 10),
+ "detail": f"{sys.version_info.major}.{sys.version_info.minor}",
+ },
+ "data_directory": {
+ "ok": os.access(directory, os.W_OK),
+ "detail": str(directory),
+ },
+ "mem0_api_key": {
+ "ok": bool(api_key()),
+ "detail": "configured" if api_key() else "missing",
+ },
+ "repository": {
+ "ok": bool(repo.identity),
+ "detail": repo.identity,
+ },
+ "user_id": _doctor_user_id(),
+ "mem0_authentication": _doctor_mem0_authentication(repo),
+ }
+ return {
+ "ok": all(bool(value["ok"]) for value in checks.values()),
+ "plugin_version": PLUGIN_VERSION,
+ "repo_id": repo.identity,
+ "app_id": repo.app_id,
+ "user_id": user_id(),
+ "checks": checks,
+ }
diff --git a/integrations/antigravity-plugin/core/telemetry.py b/integrations/antigravity-plugin/core/telemetry.py
new file mode 100644
index 000000000..c1fc0084c
--- /dev/null
+++ b/integrations/antigravity-plugin/core/telemetry.py
@@ -0,0 +1,1013 @@
+#!/usr/bin/env python3
+"""Usage telemetry for Mem0 agent plugins.
+
+Events are linked to your Mem0 account email when an API key is configured, and
+to a random per-machine id otherwise. Not anonymous โ the Python SDK and CLI
+attribute the same way.
+
+Hooks run on a 3-6 second budget and fire on every tool call, so recording never
+touches the network: `record` appends one JSON line to a local spool and returns.
+A detached `python3 telemetry.py` drains the spool in one batched PostHog request,
+started once per session and again from the flush worker that is already detached.
+
+Pure stdlib, matching the rest of the plugin. Opt out with MEM0_TELEMETRY=false.
+
+Never sends prompts, memory text, queries, file paths, repository names, or API
+keys: only event names, durations, counts, coarse outcomes, and repo/session
+identifiers hashed with a random per-install salt.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import os
+import platform
+import subprocess
+import sys
+import time
+import urllib.error
+import urllib.request
+import uuid
+from pathlib import Path
+from typing import Any
+
+import memory_core
+
+# Seeded from the per-host module the build generates into core/. Two processes
+# in this pipeline never call init() โ mcp_server.py, and the detached
+# `python3 telemetry.py` sender that spawn_flush() starts โ so a module default
+# was what every one of their events got labelled with.
+try: # pragma: no cover - absent only in the un-built shared source tree
+ from _harness_id import HARNESS_ID as _DEFAULT_HARNESS
+ from _harness_id import PLATFORM_APPLICATION as _PLATFORM_APPLICATION
+ from _harness_id import PLATFORM_SOURCE as _PLATFORM_SOURCE
+ from _harness_id import SOURCE_TAG as _DEFAULT_SOURCE_TAG
+except ImportError:
+ _DEFAULT_HARNESS = "generic"
+ _DEFAULT_SOURCE_TAG = "MEM0_PLUGIN"
+ _PLATFORM_SOURCE = "MEM0_PLUGIN"
+ _PLATFORM_APPLICATION = ""
+
+_salt_cache: str = ""
+_harness: str = _DEFAULT_HARNESS
+_source_tag: str = _DEFAULT_SOURCE_TAG
+_PRIVATE_KEYS = {
+ "apikey",
+ "authorization",
+ "password",
+ "query",
+ "secret",
+ "prompt",
+ "token",
+ "text",
+ "memory",
+ "message",
+ "error",
+ "path",
+ "cwd",
+ "userid",
+ "agentid",
+ "runid",
+ "repoid",
+ "repositoryid",
+ "projectid",
+ "appid",
+ "filters",
+}
+
+
+def init(harness: str = "", source_tag: str = "") -> None:
+ """Override the generated identity. Optional โ core/_harness_id.py is the default.
+
+ The fallback shape matches memory_core.configure_harness's (``_PLUGIN``).
+ It used to be ``MEM0__PLUGIN`` here and ``_plugin`` there, which
+ meant one plugin could emit three different source values depending on which
+ process happened to send the batch.
+ """
+ global _harness, _source_tag
+ _harness = harness or _DEFAULT_HARNESS
+ _source_tag = source_tag or (
+ f"{_harness.upper().replace('-', '_')}_PLUGIN" if harness else _DEFAULT_SOURCE_TAG
+ )
+
+POSTHOG_API_KEY = "phc_hgJkUVJFYtmaJqrvf6CYN67TIQ8yhXAkWzUn9AMU4yX"
+POSTHOG_CAPTURE_URL = "https://us.i.posthog.com/i/v0/e/"
+POSTHOG_BATCH_URL = "https://us.i.posthog.com/batch/"
+EVENT_PREFIX = "code"
+SPOOL_LIMIT_BYTES = 256 * 1024
+BATCH_SIZE = 100
+SEND_TIMEOUT = 5
+CLAIM_STALE_SECONDS = 120
+CLAIM_EXPIRY_SECONDS = 7 * 24 * 60 * 60
+# A batch is only discarded once it has genuinely been retried this many times.
+MAX_CLAIM_ATTEMPTS = 3
+# Parked claims drained per run, after the live spool. Bounded so a long backlog
+# cannot turn one flush into an unbounded send loop.
+MAX_PARKED_PER_RUN = 3
+# Added to the wait before a released claim becomes reclaimable, per attempt
+# already spent. Releasing straight to "reclaimable now" let two senders burn the
+# whole budget within seconds of one another on a single momentary failure, and
+# discard a batch a retry a minute later would have delivered.
+RETRY_COOLDOWN_SECONDS = 60
+
+
+def is_enabled() -> bool:
+ """Whether telemetry is switched on for this process."""
+ return os.environ.get("MEM0_TELEMETRY", "true").strip().lower() not in {
+ "false",
+ "0",
+ "no",
+ "off",
+ }
+
+
+def _digest(value: str, length: int = 16) -> str:
+ """Unsalted digest. Only for values that are already secrets (API keys)."""
+ return hashlib.sha256(value.encode("utf-8")).hexdigest()[:length]
+
+
+def _salt_path() -> Path:
+ return memory_core.data_dir() / "telemetry-salt"
+
+
+def _install_salt() -> str:
+ """Random per-install salt, created once and memoized for the process.
+
+ Deliberately its own file, claimed with O_CREAT|O_EXCL, rather than a key in
+ the identity file. Three reasons, all of which produced wrong data when this
+ lived in the identity dict:
+
+ - Hooks are short-lived separate processes firing on every tool call, and
+ people run more than one agent window. A read-modify-write would let each
+ process mint its own salt, so one repository would hash several ways in the
+ window before a writer won.
+ - resolve_distinct_id holds a copy of the identity dict across a network call
+ to /v1/ping/, so whichever write landed second erased the other's key โ
+ losing either the salt (repo_hash changes mid-stream) or the email (a
+ second $identify, splitting the person).
+ - Touching the identity file from record() would create it, and is_first_run
+ keys off that file, so recording an event would silently suppress the
+ install event.
+
+ Published atomically, and there is deliberately no derived fallback. Creating
+ the file with O_CREAT|O_EXCL and then writing into it leaves a window where
+ the file exists and is empty, and a concurrent hook that reads it in that
+ window gets nothing. Falling back to a digest of the path would hand that
+ process a salt an attacker can compute, memoized for its whole run, which is
+ the privacy control this function exists to provide silently turning itself
+ off under load. The salt is written to a private temp file first and linked
+ into place, so the name either does not exist or already has the full value.
+
+ Returns "" when it genuinely cannot persist. Callers omit the hash entirely
+ rather than emit an unsalted one.
+ """
+ global _salt_cache
+ if _salt_cache:
+ return _salt_cache
+
+ path = _salt_path()
+ # Read before writing. Hooks are separate processes firing on every tool
+ # call, so all but the first find the salt already published; going straight
+ # to create-fsync-link-unlink meant every one of them paid an fsync to
+ # discover that, on a path whose whole promise is appending a line and
+ # returning.
+ try:
+ _salt_cache = path.read_text(encoding="utf-8").strip()
+ if _salt_cache:
+ return _salt_cache
+ except OSError:
+ pass
+
+ temporary = path.with_name(f"{path.name}.{os.getpid()}.tmp")
+ try:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ handle = os.open(temporary, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
+ with os.fdopen(handle, "w", encoding="utf-8") as stream:
+ stream.write(uuid.uuid4().hex)
+ stream.flush()
+ os.fsync(stream.fileno())
+ try:
+ # Atomic claim: fails if another process already published one.
+ # os.link rather than replace, which would clobber theirs.
+ os.link(temporary, path)
+ except FileExistsError:
+ pass
+ except OSError:
+ # No hardlinks here (some network mounts, some container volumes).
+ # Claim the name directly instead. That reopens the empty-file
+ # window, but the window is now benign: a reader that lands in it
+ # gets "" and omits the hash for that process rather than caching a
+ # guessable one. Losing the hashes on every run of an entire
+ # filesystem is the worse failure.
+ try:
+ fallback = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
+ with os.fdopen(fallback, "w", encoding="utf-8") as stream:
+ stream.write(temporary.read_text(encoding="utf-8"))
+ except OSError:
+ pass
+ except OSError:
+ pass
+ finally:
+ try:
+ temporary.unlink()
+ except OSError:
+ pass
+
+ try:
+ _salt_cache = path.read_text(encoding="utf-8").strip()
+ except OSError:
+ _salt_cache = ""
+ return _salt_cache
+
+
+def _scoped_digest(value: str, length: int = 16) -> str:
+ """Salted digest for values drawn from a guessable space.
+
+ repo.identity is a git remote URL, or ``local:`` when there is
+ no remote โ which normally contains the account username. Sixteen unsalted
+ hex characters over that input space is enumerable, so this is not a
+ privacy control without the salt. Salting per install keeps every
+ within-account join the analytics actually use and gives up only
+ cross-machine joins on the same repository, which nothing computes.
+
+ Returns "" when there is no salt, so record() omits the property. An
+ unsalted digest over this input space is close to plaintext, and emitting one
+ under a name that implies it is hashed is worse than sending nothing.
+ """
+ if not value:
+ return ""
+ salt = _install_salt()
+ if not salt:
+ return ""
+ return hashlib.sha256(f"{salt}:{value}".encode("utf-8")).hexdigest()[:length]
+
+
+def _safe_value(value: Any) -> Any:
+ if isinstance(value, str):
+ return memory_core.redact(value)
+ if isinstance(value, dict):
+ return {
+ key: _safe_value(item)
+ for key, item in value.items()
+ if "".join(character for character in str(key).lower() if character.isalnum())
+ not in _PRIVATE_KEYS
+ }
+ if isinstance(value, (list, tuple)):
+ return [_safe_value(item) for item in value]
+ if value is None or isinstance(value, (bool, int, float)):
+ return value
+ return memory_core.redact(value)
+
+
+def _spool_path() -> Path:
+ return memory_core.data_dir() / "telemetry.jsonl"
+
+
+def _identity_path() -> Path:
+ return memory_core.data_dir() / "telemetry-identity.json"
+
+
+def _read_identity() -> dict[str, str]:
+ try:
+ value = json.loads(_identity_path().read_text(encoding="utf-8"))
+ except (OSError, json.JSONDecodeError):
+ return {}
+ return value if isinstance(value, dict) else {}
+
+
+def _write_identity(identity: dict[str, str]) -> None:
+ path = _identity_path()
+ temporary = path.with_suffix(f".{os.getpid()}.tmp")
+ try:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ temporary.write_text(json.dumps(identity), encoding="utf-8")
+ temporary.replace(path)
+ except OSError:
+ try:
+ temporary.unlink()
+ except OSError:
+ pass
+
+
+def anonymous_id(identity: dict[str, str] | None = None) -> str:
+ """Per-machine anonymous identifier, created and persisted on first use."""
+ identity = _read_identity() if identity is None else identity
+ existing = identity.get("anonymous_id")
+ if existing:
+ return existing
+ created = f"code-anon-{uuid.uuid4().hex}"
+ identity["anonymous_id"] = created
+ _write_identity(identity)
+ return created
+
+
+def _rotate_anonymous_id(identity: dict[str, str]) -> str:
+ """Mint a fresh anonymous id because the account context is gone.
+
+ The previous id may already have been merged into a person profile by an
+ $identify, and that merge is permanent. Reusing it after a logout or a key
+ change attributes everything that follows to the account that just went
+ away, which is the same misattribution the key fingerprint exists to stop,
+ only arriving through the anonymous path instead.
+
+ `aliased` is cleared with it: the new id has never been merged, so it is
+ eligible to be aliased into whatever account comes next.
+ """
+ created = f"code-anon-{uuid.uuid4().hex}"
+ identity["anonymous_id"] = created
+ identity.pop("aliased", None)
+ _write_identity(identity)
+ return created
+
+
+def _install_state_path() -> Path:
+ return memory_core.data_dir() / "install-state.json"
+
+
+def is_first_run() -> bool:
+ """Whether install has never been recorded on this machine.
+
+ Deliberately NOT the identity file. That file is only written by a
+ successful flush, so an offline or firewalled user recorded code.install on
+ every single session, forever โ and every 0.2.x user recorded one on their
+ first 0.3.x session because 0.2.x never wrote it at all.
+ """
+ return not _install_state_path().exists()
+
+
+def data_dir_was_empty() -> bool:
+ """Whether the data directory is untouched. Call BEFORE anything writes to it.
+
+ hook_runner reaches claim_install() only after cache_plugin_api_key() has
+ written `api-key` and EvidenceStore() has created `evidence.sqlite3`, so
+ asking at claim time always saw content and every fresh install reported an
+ upgrade. The caller snapshots this at the top of the run instead.
+ """
+ return not _data_dir_has_content()
+
+
+def claim_install(was_empty: bool | None = None) -> str | None:
+ """Claim the one install/upgrade record for this machine, atomically.
+
+ Returns the event to record ("install" or "upgrade"), or None if another
+ session already claimed it. O_CREAT|O_EXCL so two sessions starting together
+ cannot both win.
+
+ `was_empty` must come from data_dir_was_empty() called before this process
+ wrote anything. Omitting it falls back to checking now, which is only
+ correct for a caller that has touched nothing.
+ """
+ if not is_enabled():
+ # Never consume the one-shot claim while the user is opted out, or they
+ # would silently lose their install event if they later opt in.
+ return None
+
+ path = _install_state_path()
+ upgrading = not (data_dir_was_empty() if was_empty is None else was_empty)
+ try:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ handle = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
+ except FileExistsError:
+ return None
+ except OSError:
+ return None
+ try:
+ with os.fdopen(handle, "w", encoding="utf-8") as stream:
+ json.dump(
+ {
+ "plugin_version": memory_core.PLUGIN_VERSION,
+ "installed_at": memory_core.utc_now(),
+ "upgraded": upgrading,
+ },
+ stream,
+ )
+ # Durable before this returns. The O_EXCL open is what makes the
+ # claim exclusive, so it cannot be replaced by a temp-and-rename
+ # without losing that, which leaves the content as the thing to make
+ # safe. A kill between the open and this fsync used to leave a marker
+ # that exists but parses to nothing: is_first_run reads it as claimed
+ # and claim_version_change cannot read a version out of it.
+ stream.flush()
+ os.fsync(stream.fileno())
+ except OSError:
+ pass
+ return "upgrade" if upgrading else "install"
+
+
+def _data_dir_has_content() -> bool:
+ """Whether anything predates this session in the plugin data directory."""
+ try:
+ for entry in memory_core.data_dir().iterdir():
+ if entry.name != "install-state.json":
+ return True
+ except OSError:
+ pass
+ return False
+
+
+def _repair_install_state(path: Path) -> None:
+ """Rewrite an unparseable marker so version tracking can resume."""
+ try:
+ temporary = path.with_suffix(f".{os.getpid()}.tmp")
+ temporary.write_text(
+ json.dumps({"plugin_version": memory_core.PLUGIN_VERSION, "repaired_at": memory_core.utc_now()}),
+ encoding="utf-8",
+ )
+ temporary.replace(path)
+ except OSError:
+ pass
+
+
+def claim_version_change() -> str | None:
+ """Return the previously recorded version if it differs, updating the marker.
+
+ Only meaningful once the marker exists โ the first transition into 0.3.x has
+ no recorded predecessor and reports "pre-0.3" instead. Claiming by rewriting
+ the marker means the next session sees no change and records nothing.
+ """
+ path = _install_state_path()
+ try:
+ state = json.loads(path.read_text(encoding="utf-8"))
+ except OSError:
+ return None
+ except json.JSONDecodeError:
+ # A crash between O_EXCL and the write leaves an empty marker. Left
+ # alone it disables every future upgrade event on this machine, because
+ # claim_install sees the file and this function cannot parse it.
+ state = None
+ if not isinstance(state, dict):
+ _repair_install_state(path)
+ return None
+ previous = str(state.get("plugin_version") or "")
+ if not previous or previous == memory_core.PLUGIN_VERSION:
+ return None
+ # Claim the transition with an exclusive sentinel before rewriting the
+ # marker. A plain read-modify-write let every concurrently starting session
+ # observe the old version and each record its own upgrade โ and the first
+ # session after a version bump is exactly when several agent windows restart
+ # together.
+ sentinel = path.with_name(f"upgraded-{memory_core.PLUGIN_VERSION}")
+ try:
+ os.close(os.open(sentinel, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600))
+ except FileExistsError:
+ return None
+ except OSError:
+ return None
+
+ state["plugin_version"] = memory_core.PLUGIN_VERSION
+ state["upgraded_at"] = memory_core.utc_now()
+ temporary = path.with_suffix(f".{os.getpid()}.tmp")
+ try:
+ temporary.write_text(json.dumps(state), encoding="utf-8")
+ temporary.replace(path)
+ except OSError:
+ # Release the claim. The marker still records the old version, so
+ # without this the sentinel makes claim_version_change return early on
+ # every later run and this version's upgrade is never recorded again.
+ for leftover in (sentinel, temporary):
+ try:
+ leftover.unlink()
+ except OSError:
+ pass
+ return None
+ return previous
+
+
+def record(
+ event: str,
+ *,
+ repo: Any = None,
+ session_id: str | None = None,
+ **properties: Any,
+) -> None:
+ """Append one event to the local spool. Never blocks and never raises."""
+ if not is_enabled():
+ return
+ try:
+ spool = _spool_path()
+ try:
+ if spool.stat().st_size > SPOOL_LIMIT_BYTES:
+ return
+ except OSError:
+ pass
+ properties = _safe_value(properties)
+ # Stamped in the RECORDING process, beside harness. `source` used to be
+ # read in the sending process from a module global, so whichever process
+ # drained the spool named every event in it. flush() spreads per-event
+ # properties last, so this now wins over any sender's default.
+ properties.update(
+ harness=_harness,
+ source=_source_tag,
+ plugin_version=memory_core.PLUGIN_VERSION,
+ os=sys.platform,
+ python_version=platform.python_version(),
+ )
+ # Assigned only when the digest is real. _scoped_digest returns "" when
+ # the salt could not be persisted, and an empty property is worse than an
+ # absent one: it survives the None filter below and reads as a value.
+ if repo is not None:
+ repo_hash = _scoped_digest(getattr(repo, "identity", ""))
+ if repo_hash:
+ properties["repo_hash"] = repo_hash
+ if session_id:
+ session_hash = _scoped_digest(session_id)
+ if session_hash:
+ properties["session_hash"] = session_hash
+ line = json.dumps(
+ {
+ "event": f"{EVENT_PREFIX}.{event}",
+ "uuid": str(uuid.uuid4()),
+ "timestamp": memory_core.utc_now(),
+ "properties": {
+ key: value for key, value in properties.items() if value is not None
+ },
+ },
+ separators=(",", ":"),
+ default=str,
+ )
+ spool.parent.mkdir(parents=True, exist_ok=True)
+ with spool.open("a", encoding="utf-8") as handle:
+ handle.write(line + "\n")
+ except Exception:
+ pass
+
+
+def error_kind(exc: BaseException | str) -> str:
+ """Coarse, content-free label for a failure, safe to send."""
+ text = exc if isinstance(exc, str) else f"{type(exc).__name__}: {exc}"
+ lowered = text.lower()
+ if "timed out" in lowered or "timeout" in lowered:
+ return "timeout"
+ if "401" in lowered or "403" in lowered or "unauthor" in lowered or "forbidden" in lowered:
+ return "auth"
+ if "429" in lowered or "rate limit" in lowered:
+ return "rate-limited"
+ if any(code in lowered for code in ("500", "502", "503", "504")):
+ return "server-error"
+ if "400" in lowered or "422" in lowered:
+ return "bad-request"
+ if isinstance(exc, str):
+ return "other"
+ if isinstance(exc, urllib.error.URLError):
+ return "network"
+ return type(exc).__name__
+
+
+def spawn_flush() -> bool:
+ """Start the detached sender that drains the spool."""
+ if not is_enabled():
+ return False
+ try:
+ if not _spool_path().exists() and not any(
+ memory_core.data_dir().glob("telemetry-*.sending")
+ ):
+ return False
+ subprocess.Popen(
+ [sys.executable, str(Path(__file__).resolve())],
+ stdin=subprocess.DEVNULL,
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL,
+ close_fds=True,
+ **memory_core.detached_process_kwargs(),
+ )
+ return True
+ except Exception:
+ return False
+
+
+def _claim_name(attempt: int = 0) -> str:
+ """Claim filename. The attempt count rides in the name so the 7-day expiry
+ only ever discards a batch that was actually retried and failed."""
+ return f"telemetry-{os.getpid()}-{uuid.uuid4().hex[:8]}-a{attempt}.sending"
+
+
+def _claim_attempt(claim: Path) -> int:
+ """Attempts recorded in a claim filename; 0 for the pre-attempt-count shape.
+
+ Anchored on field position, not on a leading "a": the legacy shape is
+ ``telemetry--.sending`` and a hex id such as ``a1234567`` would
+ otherwise parse as attempt 1234567 and be discarded unsent on the first
+ flush after an upgrade.
+ """
+ stem = claim.name[: -len(".sending")] if claim.name.endswith(".sending") else claim.name
+ parts = stem.split("-")
+ if len(parts) != 4:
+ return 0
+ tail = parts[3]
+ if tail.startswith("a") and tail[1:].isdigit():
+ return int(tail[1:])
+ return 0
+
+
+def _touch(path: Path) -> None:
+ """Refresh mtime so a claim's age measures time since it was claimed.
+
+ ``Path.replace`` is ``os.rename``, which preserves mtime โ so a claim created
+ after a quiet minute inherited the spool's last-write time and looked
+ abandoned the instant it was made. A second sender would then take it over
+ while the first was still posting, and both would deliver the batch.
+ """
+ try:
+ os.utime(path, None)
+ except OSError:
+ pass
+
+
+def _claim_spool() -> Path | None:
+ """Rename the spool aside so exactly one sender owns each batch."""
+ directory = memory_core.data_dir()
+ claim = directory / _claim_name()
+ spool = _spool_path()
+ try:
+ spool.replace(claim)
+ _touch(claim)
+ return claim
+ except OSError:
+ pass
+ return _claim_parked(directory)
+
+
+def _sweep_debris(directory: Path) -> None:
+ """Remove files nothing else will ever pick up again.
+
+ *.partial is a temp file orphaned by a crash between write and rename.
+ *.corrupt is a batch quarantined for undecodable content. No glob in this
+ module matches either, so without this they accumulate on disk for the life
+ of the install.
+
+ Quarantined batches are kept far longer than debris: they are the only
+ evidence left of events that could not be delivered, and someone diagnosing
+ a report of missing telemetry has to be able to find one.
+ """
+ now = time.time()
+ for debris in directory.glob("telemetry-*.partial"):
+ try:
+ if now - debris.stat().st_mtime > CLAIM_STALE_SECONDS:
+ debris.unlink()
+ except OSError:
+ continue
+ for quarantined in directory.glob("telemetry-*.corrupt"):
+ try:
+ if now - quarantined.stat().st_mtime > CLAIM_EXPIRY_SECONDS:
+ quarantined.unlink()
+ except OSError:
+ continue
+ # The same reasoning covers *.tmp. _write_identity and _install_salt both
+ # create one and unlink it in a finally, which a SIGKILL skips, and no glob
+ # in this module matches the leftovers either.
+ for temporary in directory.glob("telemetry-*.tmp"):
+ try:
+ if now - temporary.stat().st_mtime > CLAIM_STALE_SECONDS:
+ temporary.unlink()
+ except OSError:
+ continue
+
+
+def _claim_parked(directory: Path) -> Path | None:
+ """Take the oldest abandoned claim, if any lease has actually expired.
+
+ Kept separate from the live spool so flush() can drain both in one run.
+ Previously parked batches were only reachable when no spool existed at all,
+ and because sessions keep recording there usually was one โ so a batch
+ parked by a failed send waited until the 7-day expiry deleted it unsent,
+ even though its own presence is what started the sender.
+ """
+ now = time.time()
+ for orphan in sorted(directory.glob("telemetry-*.sending"), key=_safe_mtime):
+ try:
+ age = now - orphan.stat().st_mtime
+ except OSError:
+ continue
+ if age < CLAIM_STALE_SECONDS:
+ # Someone else holds a live lease on it. This check has to come
+ # first. Claiming a file bumps its attempt count and refreshes its
+ # mtime, so a sender that has just taken the final attempt looks
+ # exhausted to everyone else while it is actively draining. Judging
+ # exhaustion before liveness let a second sender unlink a batch out
+ # from under its owner, losing every event in it.
+ continue
+ # Attempts, not age. Every re-claim touches the mtime and every release
+ # backdates it by a fixed amount, so age is pinned near the stale
+ # threshold and never reaches the expiry. Age stays only as a backstop
+ # for files that never carried an attempt marker.
+ if _claim_attempt(orphan) >= MAX_CLAIM_ATTEMPTS or age > CLAIM_EXPIRY_SECONDS:
+ try:
+ orphan.unlink()
+ except OSError:
+ pass
+ continue
+ claim = orphan.parent / _claim_name(_claim_attempt(orphan) + 1)
+ try:
+ orphan.replace(claim)
+ _touch(claim)
+ return claim
+ except OSError:
+ continue
+ return None
+
+
+def _safe_mtime(path: Path) -> float:
+ try:
+ return path.stat().st_mtime
+ except OSError:
+ return 0.0
+
+
+def _rewrite_claim(claim: Path, remaining: list[dict[str, Any]]) -> bool:
+ """Persist the unsent remainder, atomically, and refresh the lease.
+
+ Called after every successful batch. Two jobs: a retry resumes where the
+ send stopped instead of re-posting from the top, and the rewrite doubles as
+ the lease heartbeat, so a slow sender does not have its claim stolen
+ mid-flight. Interval is one batch, well inside CLAIM_STALE_SECONDS.
+ """
+ if not remaining:
+ try:
+ claim.unlink()
+ except OSError:
+ pass
+ return True
+ temporary = claim.with_suffix(f".{os.getpid()}.partial")
+ try:
+ payload = "".join(json.dumps(event, separators=(",", ":"), default=str) + "\n" for event in remaining)
+ # fsync before the rename: without it the rename can land while the
+ # bytes have not, and the claim comes back empty or truncated after a
+ # crash. _drain then reads zero events and unlinks it.
+ with open(temporary, "w", encoding="utf-8") as handle:
+ handle.write(payload)
+ handle.flush()
+ os.fsync(handle.fileno())
+ temporary.replace(claim)
+ _touch(claim)
+ return True
+ except OSError:
+ try:
+ temporary.unlink()
+ except OSError:
+ pass
+ return False
+
+
+def _release_claim(claim: Path, remaining: list[dict[str, Any]]) -> None:
+ """Persist the remainder and drop the lease, because this sender has given up.
+
+ Distinct from the per-batch heartbeat: heartbeating on the way out would
+ make an abandoned batch look actively owned for a further
+ CLAIM_STALE_SECONDS, delaying the retry for no reason. Ageing it past the
+ threshold lets the next flush pick it up immediately, while the attempt
+ count in the filename still bounds how many times that can happen.
+ """
+ if not _rewrite_claim(claim, remaining):
+ return
+ try:
+ # Backdate past the stale threshold so the next flush can pick it up,
+ # minus a cooldown that grows with the attempts already spent. Clamped so
+ # the mtime never lands in the future, which would read as a live lease.
+ cooldown = min(_claim_attempt(claim) * RETRY_COOLDOWN_SECONDS, CLAIM_STALE_SECONDS)
+ released = time.time() - CLAIM_STALE_SECONDS - 1 + cooldown
+ os.utime(claim, (released, released))
+ except OSError:
+ pass
+
+
+def _resolve_email(key: str) -> str:
+ """Trade the API key for the account email so events join other Mem0 surfaces."""
+ url = os.environ.get("MEM0_API_URL", memory_core.DEFAULT_API_URL).rstrip("/") + "/v1/ping/"
+ request = urllib.request.Request(
+ url, headers={"Authorization": f"Token {key}", "Content-Type": "application/json"}
+ )
+ try:
+ with urllib.request.urlopen(request, timeout=SEND_TIMEOUT) as response:
+ payload = json.loads(response.read().decode("utf-8"))
+ except Exception:
+ return ""
+ email = payload.get("user_email") if isinstance(payload, dict) else ""
+ return email if isinstance(email, str) else ""
+
+
+def _post(payload: dict[str, Any], url: str) -> bool:
+ request = urllib.request.Request(
+ url,
+ data=json.dumps(payload, default=str).encode("utf-8"),
+ headers={"Content-Type": "application/json"},
+ )
+ try:
+ with urllib.request.urlopen(request, timeout=SEND_TIMEOUT):
+ return True
+ except Exception:
+ return False
+
+
+def resolve_distinct_id() -> tuple[str, str]:
+ """Return the PostHog distinct id and the anonymous id it replaced, if any.
+
+ The second value becomes a PostHog $identify alias. It is ONLY ever an
+ anonymous id: aliasing one account email to another merges two real person
+ profiles and cannot be undone, so a key that now belongs to a different
+ account re-resolves with no alias.
+ """
+ identity = _read_identity()
+ key = memory_core.api_key()
+ fingerprint = _digest(key) if key else ""
+ email = identity.get("email", "")
+
+ if email and fingerprint:
+ recorded = identity.get("key_fingerprint", "")
+ if recorded == fingerprint:
+ return email, ""
+ if not recorded:
+ # Rows written before fingerprints existed. Verify rather than
+ # adopt: a key changed before the upgrade would otherwise bind the
+ # new key to the previous account's email, permanently, and the
+ # fingerprint would then agree with itself forever after.
+ verified = _resolve_email(key)
+ if not verified:
+ # Offline, firewalled, or the API is down. Keep the previous
+ # behaviour and retry on the next flush rather than dropping a
+ # real account attribution. Safe because the same network that
+ # failed /v1/ping/ is about to fail the PostHog POST, so nothing
+ # is delivered under the unverified identity in the meantime.
+ return email, ""
+ identity["email"] = verified
+ identity["key_fingerprint"] = fingerprint
+ _write_identity(identity)
+ return verified, ""
+
+ if not key:
+ # No key to verify the account with; do not keep attributing to it.
+ if email:
+ identity.pop("email", None)
+ identity.pop("key_fingerprint", None)
+ return _rotate_anonymous_id(identity), ""
+ return anonymous_id(identity), ""
+
+ resolved = _resolve_email(key)
+ if not resolved:
+ # The key changed and will not resolve (revoked, offline, API down).
+ # Reaching here with an email means the recorded fingerprint disagreed,
+ # so the key really did change. Drop the account and rotate: the stored
+ # anonymous id may already be merged into that account's person, and
+ # reusing it would keep the events on the profile we are trying to
+ # leave.
+ if email:
+ identity.pop("email", None)
+ identity.pop("key_fingerprint", None)
+ return _rotate_anonymous_id(identity), ""
+ return anonymous_id(identity), ""
+
+ # Alias only when going anonymous -> email for the first time. Once an anon
+ # id has been merged into an account it must never be offered again: an
+ # alias naming an already-identified id is what could link two real people.
+ previous = "" if (email or identity.get("aliased")) else identity.get("anonymous_id", "")
+ if previous:
+ identity["aliased"] = True
+ identity["email"] = resolved
+ identity["key_fingerprint"] = fingerprint
+ _write_identity(identity)
+ return resolved, previous
+
+
+def flush() -> int:
+ """Drain the live spool, then any parked claims, and return events sent."""
+ if not is_enabled():
+ return 0
+ sent, delivered = _drain(_claim_spool())
+ if not delivered:
+ # The network is failing. Retrying other batches now would only burn
+ # their attempt budget against the same broken connection.
+ return sent
+
+ # Parked batches used to starve behind the live spool indefinitely. Bounded
+ # per run so a long backlog cannot turn one flush into an unbounded loop.
+ directory = memory_core.data_dir()
+ _sweep_debris(directory)
+ for _ in range(MAX_PARKED_PER_RUN):
+ parked = _claim_parked(directory)
+ if parked is None:
+ break
+ count, delivered = _drain(parked)
+ sent += count
+ if not delivered:
+ break
+ return sent
+
+
+def _drain(claim: Path | None) -> tuple[int, bool]:
+ """Post one claimed batch file, recording progress after every batch.
+
+ Returns (events sent, whether everything was delivered).
+ """
+ if claim is None:
+ return 0, True
+ try:
+ lines = claim.read_text(encoding="utf-8").splitlines()
+ except ValueError:
+ # UnicodeDecodeError from a torn write: the content is unrecoverable, so
+ # quarantine rather than retry. flush() runs from a bare `finally:` in
+ # flush_worker, so raising here also skips the handoff cleanup, and an
+ # undecodable file would otherwise be re-read on every flush forever.
+ # Reported as delivered because there is nothing left to deliver and the
+ # rest of the run should continue.
+ try:
+ claim.replace(claim.with_suffix(".corrupt"))
+ except OSError:
+ try:
+ claim.unlink()
+ except OSError:
+ pass
+ return 0, True
+ except OSError:
+ # Could not read it, which is not the same as having nothing to send.
+ # The file is left exactly where it is: a vanished or briefly unreadable
+ # claim is retryable, and quarantining it here would discard events over
+ # a transient filesystem error. Reported as undelivered so the run stops
+ # instead of counting a batch nothing was posted from as delivered.
+ return 0, False
+ events = []
+ for line in lines:
+ try:
+ value = json.loads(line)
+ except json.JSONDecodeError:
+ continue
+ if isinstance(value, dict) and value.get("event"):
+ events.append(value)
+ if not events:
+ # Only delete when the file really is empty. A non-empty file that
+ # parses to nothing is a torn write, and its contents are the unsent
+ # remainder โ deleting it is the data loss this PR exists to prevent.
+ try:
+ empty = claim.stat().st_size == 0
+ except OSError:
+ empty = True
+ try:
+ claim.replace(claim.with_suffix(".corrupt")) if not empty else claim.unlink()
+ except OSError:
+ pass
+ return 0, True
+
+ distinct_id, aliased_anonymous_id = resolve_distinct_id()
+ if aliased_anonymous_id:
+ _post(
+ {
+ "api_key": POSTHOG_API_KEY,
+ "event": "$identify",
+ "distinct_id": distinct_id,
+ "properties": {
+ "$anon_distinct_id": aliased_anonymous_id,
+ "$lib": "posthog-python",
+ },
+ },
+ POSTHOG_CAPTURE_URL,
+ )
+
+ sent = 0
+ for start in range(0, len(events), BATCH_SIZE):
+ chunk = events[start : start + BATCH_SIZE]
+ batch = [
+ {
+ "event": event["event"],
+ "distinct_id": distinct_id,
+ # Carried through from record() so a resend can be collapsed.
+ "uuid": event.get("uuid"),
+ "timestamp": event.get("timestamp"),
+ "properties": {
+ # Fallback only: events recorded by a build before source
+ # moved into record() have none of their own.
+ "source": _source_tag,
+ "language": "python",
+ "$process_person_profile": False,
+ "$lib": "posthog-python",
+ **(event.get("properties") or {}),
+ },
+ }
+ for event in chunk
+ ]
+ if not _post({"api_key": POSTHOG_API_KEY, "batch": batch}, POSTHOG_BATCH_URL):
+ # Keep only what has not been delivered, and release the lease.
+ # Previously the whole file was kept and the retry re-posted every
+ # batch, including the ones that had already arrived.
+ _release_claim(claim, events[start:])
+ return sent, False
+ sent += len(chunk)
+ # Record progress and refresh the lease after each successful batch, so
+ # a crash repeats at most one batch instead of the entire file. If the
+ # rewrite fails the claim still holds delivered events, so stop rather
+ # than carry on as though progress were recorded โ continuing is how the
+ # duplicate delivery this PR fixes would come back.
+ if not _rewrite_claim(claim, events[start + len(chunk) :]):
+ _release_claim(claim, events[start + len(chunk) :])
+ return sent, False
+ return sent, True
+
+
+def main() -> int:
+ flush()
+ return 0
+
+
+if __name__ == "__main__":
+ try:
+ raise SystemExit(main())
+ except Exception:
+ raise SystemExit(0)
diff --git a/integrations/antigravity-plugin/hooks.json b/integrations/antigravity-plugin/hooks.json
new file mode 100644
index 000000000..bc2b06f5f
--- /dev/null
+++ b/integrations/antigravity-plugin/hooks.json
@@ -0,0 +1,18 @@
+{
+ "mem0": {
+ "PreInvocation": [
+ { "type": "command", "command": "python3 ./hooks/adapter.py PreInvocation", "timeout": 5 }
+ ],
+ "PostToolUse": [
+ {
+ "matcher": "*",
+ "hooks": [
+ { "type": "command", "command": "python3 ./hooks/adapter.py PostToolUse", "timeout": 3 }
+ ]
+ }
+ ],
+ "Stop": [
+ { "type": "command", "command": "python3 ./hooks/adapter.py Stop", "timeout": 5 }
+ ]
+ }
+}
diff --git a/integrations/antigravity-plugin/hooks/adapter.py b/integrations/antigravity-plugin/hooks/adapter.py
new file mode 100644
index 000000000..8c20e269b
--- /dev/null
+++ b/integrations/antigravity-plugin/hooks/adapter.py
@@ -0,0 +1,163 @@
+#!/usr/bin/env python3
+"""Translate Antigravity hooks into the shared Mem0 runtime."""
+
+from __future__ import annotations
+
+import contextlib
+import io
+import json
+import os
+import re
+import sys
+from pathlib import Path
+
+HERE = Path(__file__).resolve()
+BUNDLED_CORE = HERE.parent.parent / "core"
+CORE = BUNDLED_CORE if BUNDLED_CORE.is_dir() else HERE.parents[2] / "core" / "python"
+sys.path.insert(0, str(CORE))
+
+import hook_runner # noqa: E402
+import telemetry # noqa: E402
+from memory_core import ( # noqa: E402
+ configure_harness,
+ record_tool,
+ redact,
+)
+
+
+def _read_transcript(path: str) -> list[dict[str, str]]:
+ messages = []
+ try:
+ with open(path, encoding="utf-8") as transcript:
+ for line in transcript:
+ try:
+ step = json.loads(line)
+ except json.JSONDecodeError:
+ continue
+ content = step.get("content")
+ if not isinstance(content, str) or step.get("status") != "DONE":
+ continue
+ if step.get("type") == "USER_INPUT":
+ match = re.search(r"\s*(.*?)\s*", content, re.DOTALL)
+ messages.append({"role": "user", "content": redact(match.group(1) if match else content).strip()})
+ elif step.get("source") == "MODEL" and step.get("type") == "PLANNER_RESPONSE":
+ messages.append({"role": "assistant", "content": redact(content).strip()})
+ except (OSError, TypeError):
+ pass
+ return messages
+
+
+def _transcript_messages(path: str) -> tuple[str, str]:
+ messages = _read_transcript(path)
+ return tuple(next((m["content"] for m in reversed(messages) if m["role"] == role), "")
+ for role in ("user", "assistant"))
+
+
+def _record_stop(store, payload):
+ session_id = str(payload.get("session_id") or "unknown-session")
+ repo = store.repo_for_session(session_id, payload.get("cwd"))
+ path = str(payload.get("transcript_path") or "")
+ messages = _read_transcript(path)
+ if not messages:
+ return hook_runner.default_record_stop(store, payload)
+ with store.conn:
+ store.conn.execute("BEGIN IMMEDIATE")
+ previous = store.latest_event_payload(repo.identity, session_id, "assistant_stop")
+ offset = previous.get("transcript_count", 0) if previous.get("transcript_path") == path else 0
+ if not isinstance(offset, int) or not 0 <= offset <= len(messages):
+ offset = 0
+ if messages[offset:]:
+ store.record_event(repo, session_id, "assistant_stop", {
+ "transcript_messages": messages[offset:],
+ "transcript_count": len(messages),
+ "transcript_path": path,
+ })
+ return repo, session_id
+
+
+def normalize(payload: dict) -> dict:
+ value = dict(payload)
+ value.setdefault("session_id", value.get("conversationId", ""))
+ workspaces = value.get("workspacePaths") or []
+ cwd = workspaces[0] if workspaces else os.environ.get("MEM0_CWD", "").strip()
+ if cwd:
+ value.setdefault("cwd", cwd)
+ value.setdefault("transcript_path", value.get("transcriptPath", ""))
+ prompt, assistant = _transcript_messages(value["transcript_path"])
+ if prompt:
+ value.setdefault("prompt", prompt)
+ if assistant:
+ value.setdefault("last_assistant_message", assistant)
+ tool_call = value.get("toolCall") or {}
+ if isinstance(tool_call, dict):
+ value.setdefault("tool_name", tool_call.get("name", ""))
+ value.setdefault("tool_input", tool_call.get("args", {}))
+ if value.get("error"):
+ value.setdefault("tool_response", value["error"])
+ return value
+
+
+def _record_failure(store, payload):
+ return record_tool(store, payload, failed=True)
+
+
+def _run_shared(arguments: list[str], payload: dict) -> tuple[int, str]:
+ sys.argv = [sys.argv[0], *arguments]
+ sys.stdin = io.StringIO(json.dumps(payload))
+ output = io.StringIO()
+ with contextlib.redirect_stdout(output):
+ result = hook_runner.run(
+ record_stop_fn=_record_stop,
+ extra_actions={"post-tool-failure": _record_failure},
+ automatic_flush_reasons={"session-end"},
+ )
+ return result, output.getvalue()
+
+
+def main() -> int:
+ if len(sys.argv) != 2 or sys.argv[1] not in {"PreInvocation", "PostToolUse", "Stop"}:
+ return 2
+ event = sys.argv[1]
+ try:
+ raw = json.load(sys.stdin)
+ except (json.JSONDecodeError, OSError):
+ raw = {}
+ payload = normalize(raw if isinstance(raw, dict) else {})
+ if not payload.get("cwd"):
+ output = {"injectSteps": []} if event == "PreInvocation" else {}
+ if event == "Stop":
+ output = {"decision": "allow"}
+ print(json.dumps(output))
+ return 0
+ configure_harness("antigravity", data_dir_name="antigravity-plugin", source_tag="antigravity_plugin")
+ telemetry.init(harness="antigravity", source_tag="ANTIGRAVITY_PLUGIN")
+ if event == "PreInvocation":
+ if payload.get("invocationNum") != 0:
+ print(json.dumps({"injectSteps": []}))
+ return 0
+ _run_shared(["session-start"], payload)
+ result, output = _run_shared(["user-prompt"], payload)
+ context = ""
+ for line in output.splitlines():
+ try:
+ context = json.loads(line)["hookSpecificOutput"]["additionalContext"]
+ except (json.JSONDecodeError, KeyError, TypeError):
+ continue
+ print(json.dumps({"injectSteps": [{"ephemeralMessage": context}] if context else []}))
+ return result
+ action = {
+ "PostToolUse": ["post-tool-failure" if payload.get("error") else "post-tool"],
+ "Stop": ["flush", "--reason", "session-end"],
+ }[event]
+ result, _ = _run_shared(action, payload)
+ print(json.dumps({"decision": "allow"} if event == "Stop" else {}))
+ return result
+
+
+if __name__ == "__main__":
+ try:
+ raise SystemExit(main())
+ except Exception as exc:
+ hook_runner.log_failure(exc)
+ print("{}")
+ raise SystemExit(0) from None
diff --git a/integrations/antigravity-plugin/mcp_config.json b/integrations/antigravity-plugin/mcp_config.json
new file mode 100644
index 000000000..cc9f44de1
--- /dev/null
+++ b/integrations/antigravity-plugin/mcp_config.json
@@ -0,0 +1,8 @@
+{
+ "mcpServers": {
+ "mem0": {
+ "command": "python3",
+ "args": ["./core/mcp_server.py"]
+ }
+ }
+}
diff --git a/integrations/antigravity-plugin/plugin-build.json b/integrations/antigravity-plugin/plugin-build.json
new file mode 100644
index 000000000..5a9112025
--- /dev/null
+++ b/integrations/antigravity-plugin/plugin-build.json
@@ -0,0 +1,14 @@
+{
+ "id": "mem0",
+ "version": "0.3.3",
+ "homepage": "https://docs.mem0.ai/integrations/antigravity",
+ "native": {
+ "pluginRoot": "${ANTIGRAVITY_PLUGIN_ROOT}",
+ "files": {
+ "plugin.json": "plugin.json",
+ "hooks.json": "hooks.json",
+ "mcp_config.json": "mcp_config.json",
+ "hooks/adapter.py": "hooks/adapter.py"
+ }
+ }
+}
diff --git a/integrations/antigravity-plugin/plugin.json b/integrations/antigravity-plugin/plugin.json
new file mode 100644
index 000000000..32490cc76
--- /dev/null
+++ b/integrations/antigravity-plugin/plugin.json
@@ -0,0 +1,5 @@
+{
+ "$schema": "https://antigravity.google/schemas/v1/plugin.json",
+ "name": "mem0",
+ "description": "Cross-session memory and token savings for coding agents."
+}
diff --git a/integrations/antigravity-plugin/skills/forget/SKILL.md b/integrations/antigravity-plugin/skills/forget/SKILL.md
new file mode 100644
index 000000000..a0c4cbe5c
--- /dev/null
+++ b/integrations/antigravity-plugin/skills/forget/SKILL.md
@@ -0,0 +1,26 @@
+---
+name: forget
+description: Delete the Mem0 memories stored for this repository and this user. Use when the user asks to forget, clear, wipe, or delete memories.
+disable-model-invocation: true
+---
+
+# Forget this repository's memories
+
+This permanently deletes remote memories. Before running anything, tell the
+user exactly what will be deleted: their own memories for this repository
+only. The repository's project memory is shared by everyone who works in it,
+so it stays unless the user explicitly asks to delete that too.
+
+After the user confirms, run:
+
+```bash
+python3 "${ANTIGRAVITY_PLUGIN_ROOT}/core/memory_cli.py" --harness "antigravity" forget --remote --yes
+```
+
+If the user also asked to delete the repository's shared project memory, add
+`--include-project-memory` and say that this removes it for every teammate.
+
+Report what the command output says was deleted. If the user only wants local
+data cleared (evidence log, pending queue), run the same command without
+`--remote`. Never pass `--yes` before the user has confirmed in this
+conversation.
diff --git a/integrations/antigravity-plugin/skills/pause/SKILL.md b/integrations/antigravity-plugin/skills/pause/SKILL.md
new file mode 100644
index 000000000..77b4146b6
--- /dev/null
+++ b/integrations/antigravity-plugin/skills/pause/SKILL.md
@@ -0,0 +1,20 @@
+---
+name: pause
+description: Pause Mem0 memory capture on this machine. Use when the user wants to stop memories being recorded, for example for private work or experiments.
+disable-model-invocation: true
+---
+
+# Pause memory capture
+
+To pause (hooks stop capturing and sending session content; a minimal
+telemetry ping still fires at session start, under your Mem0 account email,
+unless `MEM0_TELEMETRY=false`):
+
+```bash
+python3 "${ANTIGRAVITY_PLUGIN_ROOT}/core/memory_cli.py" --harness "antigravity" pause
+```
+
+Confirm the new state back to the user, and remind them that already-created
+memories still exist and remain searchable. Pending unsent packets are held
+while paused, not expired, and are delivered after resuming. To turn capture
+back on, use `/mem0:resume`.
diff --git a/integrations/antigravity-plugin/skills/remember/SKILL.md b/integrations/antigravity-plugin/skills/remember/SKILL.md
new file mode 100644
index 000000000..7be5fc9be
--- /dev/null
+++ b/integrations/antigravity-plugin/skills/remember/SKILL.md
@@ -0,0 +1,21 @@
+---
+name: remember
+description: Acknowledge a "remember this" request and make sure it is captured well. Use when the user explicitly asks to remember, note, or save something for future sessions.
+disable-model-invocation: true
+---
+
+# Remember something for future sessions
+
+Mem0 creates memories from the session automatically โ there is no separate
+write command. When the user asks to remember something:
+
+1. Restate the fact clearly and completely in your reply, in one or two
+ sentences, including any names, values, or paths it depends on. Your visible
+ reply is what memory extraction reads, so a precise restatement is what gets
+ remembered.
+2. Tell the user it will be saved with this session's memories when the session
+ ends or compacts, and that it will surface in future sessions in this
+ repository (they can check later with /mem0:search).
+
+Do not invent a storage confirmation or a memory ID โ creation happens in the
+background after the session.
diff --git a/integrations/antigravity-plugin/skills/resume/SKILL.md b/integrations/antigravity-plugin/skills/resume/SKILL.md
new file mode 100644
index 000000000..52a88a38d
--- /dev/null
+++ b/integrations/antigravity-plugin/skills/resume/SKILL.md
@@ -0,0 +1,19 @@
+---
+name: resume
+description: Resume Mem0 memory capture after it was paused with /mem0:pause.
+disable-model-invocation: true
+---
+
+# Resume memory capture
+
+Resume memory capture for this machine.
+
+Run:
+
+```bash
+python3 "${ANTIGRAVITY_PLUGIN_ROOT}/core/memory_cli.py" --harness "antigravity" resume
+```
+
+Confirm to the user that capture is active again. New sessions record evidence and
+create memories as normal; nothing that happened while paused is retroactively
+captured.
diff --git a/integrations/antigravity-plugin/skills/search/SKILL.md b/integrations/antigravity-plugin/skills/search/SKILL.md
new file mode 100644
index 000000000..530a70a86
--- /dev/null
+++ b/integrations/antigravity-plugin/skills/search/SKILL.md
@@ -0,0 +1,26 @@
+---
+name: search
+description: Search memories from earlier Antigravity sessions in this repository. Use it when earlier work may already explain the code, error, decision, or command you need, so you can avoid repeating file reads, searches, or experiments.
+argument-hint: "[question] [--top-k number] [--category category-name] [--scope repo|dir|mine] [--run-id session-id]"
+disable-model-invocation: true
+---
+
+# Search memories
+
+Call `search_memories` with the user's question. Treat `--top-k`, `--category`,
+`--scope`, and `--run-id` as tool arguments instead of including them in the
+query.
+
+Omit `top_k` to use Mem0's configured default. Omit `category` to search every
+category. Omit `scope` to use the configured default, normally `repo`: this
+repository's shared memory, which everyone who works in it contributes to,
+plus your own preferences.
+
+Pass `scope` when the question needs something else: `dir` to narrow the
+shared memory to the directory you are working in (a package inside a
+monorepo), `mine` for your own preferences alone.
+
+Pass `run_id` with any scope to retrieve memories saved in a specific coding-agent
+session. Omit `run_id` to search across sessions. It filters the memories returned;
+it does not identify the session making the search request. Use a known session ID,
+never invent one. Return the tool's result directly.
diff --git a/integrations/antigravity-plugin/skills/status/SKILL.md b/integrations/antigravity-plugin/skills/status/SKILL.md
new file mode 100644
index 000000000..d417e4a40
--- /dev/null
+++ b/integrations/antigravity-plugin/skills/status/SKILL.md
@@ -0,0 +1,23 @@
+---
+name: status
+description: Show whether Mem0 memory is working in this repository, covering configuration, capture state, pending flushes, and whether the Mem0 API key is valid. Use when the user asks whether memory is on, why a memory is missing, or anything looks broken.
+disable-model-invocation: false
+---
+
+# Memory status
+
+Run both commands and report the combined result in plain language:
+
+```bash
+python3 "${ANTIGRAVITY_PLUGIN_ROOT}/core/memory_cli.py" --harness "antigravity" status --json
+python3 "${ANTIGRAVITY_PLUGIN_ROOT}/core/memory_cli.py" --harness "antigravity" doctor
+```
+
+Summarize, using only fields the JSON actually reports: whether capture is
+active or paused, the user ID and repository scope (`repo_id`), whether an
+API key is configured, the event/flush/retrieval counts (`flushes` is the
+number of completed flushes, not a pending count), and the doctor check
+results. If doctor reports an authentication failure (401 / invalid key), say
+clearly that the Mem0 API key is invalid or expired and that memories are NOT
+being created. Never report an auth failure as "no memories found". Suggest
+reinstalling with `--config api_key=...` in that case.
diff --git a/integrations/antigravity-plugin/tests/test_antigravity.py b/integrations/antigravity-plugin/tests/test_antigravity.py
new file mode 100644
index 000000000..6c73fbeb2
--- /dev/null
+++ b/integrations/antigravity-plugin/tests/test_antigravity.py
@@ -0,0 +1,140 @@
+from __future__ import annotations
+
+import importlib.util
+import io
+import json
+import sys
+from pathlib import Path
+
+HOST = Path(__file__).resolve().parents[1]
+CORE_ROOT = HOST.parent / "agent-plugin-core"
+sys.path.insert(0, str(CORE_ROOT))
+
+from build.build import build # noqa: E402
+
+SPEC = importlib.util.spec_from_file_location("antigravity_adapter", HOST / "hooks" / "adapter.py")
+assert SPEC and SPEC.loader
+adapter = importlib.util.module_from_spec(SPEC)
+SPEC.loader.exec_module(adapter)
+
+
+def test_normalizes_antigravity_camel_case_payload(tmp_path: Path) -> None:
+ transcript = tmp_path / "transcript.jsonl"
+ transcript.write_text(
+ "\n".join(
+ [
+ json.dumps(
+ {
+ "source": "USER_EXPLICIT",
+ "type": "USER_INPUT",
+ "status": "DONE",
+ "content": "\nremember the parser\n",
+ }
+ ),
+ json.dumps(
+ {
+ "source": "MODEL",
+ "type": "PLANNER_RESPONSE",
+ "status": "DONE",
+ "content": "The parser is fixed.",
+ }
+ ),
+ ]
+ ),
+ encoding="utf-8",
+ )
+ value = adapter.normalize(
+ {
+ "conversationId": "conversation-1",
+ "workspacePaths": ["/repo"],
+ "transcriptPath": str(transcript),
+ "toolCall": {"name": "run_command", "args": {"CommandLine": "pytest"}},
+ "error": "failed",
+ }
+ )
+
+ assert value["session_id"] == "conversation-1"
+ assert value["cwd"] == "/repo"
+ assert value["transcript_path"] == str(transcript)
+ assert value["prompt"] == "remember the parser"
+ assert value["last_assistant_message"] == "The parser is fixed."
+ assert value["tool_name"] == "run_command"
+ assert value["tool_input"] == {"CommandLine": "pytest"}
+ assert value["tool_response"] == "failed"
+
+
+def test_uses_explicit_cwd_when_antigravity_omits_workspaces(monkeypatch) -> None:
+ monkeypatch.setenv("MEM0_CWD", "/repo")
+
+ value = adapter.normalize({"workspacePaths": []})
+
+ assert value["cwd"] == "/repo"
+
+
+def test_skips_capture_when_workspace_is_unknown(monkeypatch, capsys) -> None:
+ monkeypatch.delenv("MEM0_CWD", raising=False)
+
+ def run_shared(*_):
+ raise AssertionError("shared runtime should not run")
+
+ monkeypatch.setattr(adapter, "_run_shared", run_shared)
+ monkeypatch.setattr(sys, "argv", ["adapter.py", "PostToolUse"])
+ monkeypatch.setattr(sys, "stdin", io.StringIO('{"workspacePaths": []}'))
+
+ assert adapter.main() == 0
+ assert json.loads(capsys.readouterr().out) == {}
+
+
+def test_pre_invocation_translates_shared_recall_to_ephemeral_message(monkeypatch, capsys) -> None:
+ calls = []
+
+ def run_shared(arguments, payload):
+ calls.append(arguments)
+ if arguments == ["user-prompt"]:
+ return 0, json.dumps(
+ {"hookSpecificOutput": {"additionalContext": "Earlier repository context."}}
+ )
+ return 0, ""
+
+ monkeypatch.setattr(adapter, "_run_shared", run_shared)
+ monkeypatch.setattr(sys, "argv", ["adapter.py", "PreInvocation"])
+ monkeypatch.setattr(sys, "stdin", io.StringIO('{"invocationNum": 0, "workspacePaths": ["/repo"]}'))
+
+ assert adapter.main() == 0
+ assert calls == [["session-start"], ["user-prompt"]]
+ assert json.loads(capsys.readouterr().out) == {
+ "injectSteps": [{"ephemeralMessage": "Earlier repository context."}]
+ }
+
+
+def test_native_antigravity_bundle_uses_supported_events(tmp_path: Path) -> None:
+ root = build("antigravity", "native", tmp_path / "antigravity")
+
+ manifest = json.loads((root / "plugin.json").read_text(encoding="utf-8"))
+ hooks = json.loads((root / "hooks.json").read_text(encoding="utf-8"))["mem0"]
+ assert manifest["$schema"] == "https://antigravity.google/schemas/v1/plugin.json"
+ assert set(hooks) == {"PreInvocation", "PostToolUse", "Stop"}
+ assert (root / "mcp_config.json").is_file()
+ assert not (root / "agents").exists()
+ assert not any(path.is_symlink() for path in root.rglob("*"))
+
+
+def test_stop_captures_later_prompts_once(tmp_path):
+ transcript = tmp_path / "transcript.jsonl"
+ store = adapter.hook_runner.EvidenceStore(tmp_path / "evidence.sqlite3")
+ payload = {"session_id": "s1", "cwd": str(tmp_path), "transcript_path": str(transcript)}
+ turns = []
+ try:
+ for prompt, answer in [("First question", "First answer"), ("Next question", "Next answer")]:
+ turns.extend([
+ {"type": "USER_INPUT", "status": "DONE", "content": prompt},
+ {"type": "PLANNER_RESPONSE", "source": "MODEL", "status": "DONE", "content": answer},
+ ])
+ transcript.write_text(''.join(json.dumps(row) + '\n' for row in turns))
+ adapter._record_stop(store, payload)
+ adapter._record_stop(store, payload)
+ rows = store.conn.execute("SELECT payload_json FROM events WHERE kind = 'assistant_stop' ORDER BY id").fetchall()
+ messages = [message for row in rows for message in json.loads(row[0])["transcript_messages"]]
+ assert [m["content"] for m in messages] == ["First question", "First answer", "Next question", "Next answer"]
+ finally:
+ store.close()
diff --git a/integrations/claude-code-plugin/.claude-plugin/plugin.json b/integrations/claude-code-plugin/.claude-plugin/plugin.json
index 3fd2ceb02..8182b49dc 100644
--- a/integrations/claude-code-plugin/.claude-plugin/plugin.json
+++ b/integrations/claude-code-plugin/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "mem0",
- "version": "0.3.0",
+ "version": "0.3.3",
"description": "Cross-session memory and token savings for coding agents.",
"author": {
"name": "Mem0"
diff --git a/integrations/claude-code-plugin/.gitignore b/integrations/claude-code-plugin/.gitignore
deleted file mode 100644
index 7f1a2fd19..000000000
--- a/integrations/claude-code-plugin/.gitignore
+++ /dev/null
@@ -1,11 +0,0 @@
-__pycache__/
-*.py[cod]
-.pytest_cache/
-.ruff_cache/
-.venv/
-*.sqlite3
-*.sqlite3-shm
-*.sqlite3-wal
-flush-worker.log
-plugin-errors.log
-pending/
diff --git a/integrations/claude-code-plugin/README.md b/integrations/claude-code-plugin/README.md
index 87c535502..b58f54c79 100644
--- a/integrations/claude-code-plugin/README.md
+++ b/integrations/claude-code-plugin/README.md
@@ -4,6 +4,8 @@ Persistent cross-session memory for Claude Code, plus a Sonnet sidekick agent fo
Claude Code forgets everything between sessions. This plugin fixes that: hooks capture session details locally, a background worker turns them into Mem0 memories, and Claude automatically gets the relevant ones back at the start of later sessions.
+Current bundle version: `0.3.1`.
+
## Prerequisites
- Python 3.10+ and Git.
@@ -34,30 +36,35 @@ To remove:
claude plugin uninstall mem0@mem0-plugins
```
-For local development, load the current checkout directly:
+For local development, verify and load the self-contained plugin directory:
```bash
-claude --plugin-dir .
+python3 integrations/agent-plugin-core/build/build.py claude-code --kind native --check
+claude --plugin-dir integrations/claude-code-plugin
```
## How it works
### Memory
-1. **Capture.** Hooks save the main agent's activity locally: user messages, Claude's answers, changed file paths, and short test/build results. No model calls, no blocking. Sidekick output is excluded.
+1. **Capture.** Hooks save the main agent's activity locally: user messages, Claude's answers, changed file paths, and short test/build results. Capture does not call a model. Sidekick assignments and completed responses are recorded separately as supporting evidence.
-2. **Flush.** After every five completed exchanges, a detached background worker sends that batch to Mem0. Large exchanges flush sooner. Ending or compacting the session flushes anything remaining. If idle, an auto-flush runs after five minutes (configurable with `MEM0_CODE_IDLE_FLUSH_SECONDS`). The worker survives Claude Code exiting.
+2. **Flush.** After every five completed exchanges, a detached background worker sends that batch to Mem0. Large exchanges flush sooner. Ending or compacting the session flushes anything remaining. The session-end worker sends the conversation already collected by hooks without recording the final answer again. If idle, an auto-flush runs after five minutes (configurable with `MEM0_CODE_IDLE_FLUSH_SECONDS`). The worker survives Claude Code exiting.
-3. **Extract.** Each flush sends a single `add` call with `agent_id` (the project identity), `user_id` (you), `app_id` (the repository), and `run_id` (the session). Mem0 classifies each extracted memory as either:
+3. **Extract.** Each flush sends one or more `add` calls with `agent_id` (the project identity), `user_id` (you), `app_id` (the repository), and `run_id` (the session). Mem0 classifies each extracted memory as either:
- **Shared project memory** (`agent_id`): one namespace per repo, scoped by `app_id`. Stores conventions, decisions, constraints, working commands, and failed commands with their fixes. Everyone on the repo reads and writes the same pool. Never carries a `user_id`. Directory information is stored in metadata for directory-scoped searches.
- **Personal memory** (`user_id`): your preferred tools, style, habits, and anything you asked to be remembered. Scoped to the repo by `app_id`. Private to you.
-4. **Recall.** On the next session's first prompt, the plugin searches automatically and supplies up to five relevant memories. No model is called to write the query.
+4. **Recall.** On the next session's first prompt, if it has at least 20 characters, the plugin searches automatically and supplies up to five relevant memories. No model is called to write the query.
+
+Captured prompts and responses retain their full text after secret redaction. Oversized extraction input is split across requests without discarding message text. Search results and tool evidence still have separate size limits.
After that first search, Claude can call `search_memories` with a specific question, and you can run `/mem0:search` yourself. Explicit searches return up to 3 results by default (configurable to 20), capped at 4,000 characters.
### Sonnet sidekick agent
+Sidekick is available only in this plugin. The shared core handles memory and subagent tracking.
+
`mem0:sidekick` is a Sonnet coding agent that runs in a separate Git worktree. It can investigate, implement, test, debug, or review something instead of the main (Opus/Fable) session doing the same work, reducing cost when the main agent doesn't need to repeat it.
The main agent reviews the result. Corrections go back to the same sidekick so it keeps what it learned. Changes stay in the sidekick's worktree until the main agent reviews and copies them over.
@@ -87,7 +94,7 @@ By default the worktree branches from the repo's default branch. Set `worktree.b
| Command | What it does |
| --- | --- |
-| `/mem0:search` | Search memories from earlier sessions. Accepts `--top-k `, `--category `, and `--scope `. |
+| `/mem0:search` | Search memories from earlier sessions. Accepts `--top-k `, `--category `, `--scope `, and `--run-id `. |
| `/mem0:status` | Check config, capture state, pending flushes, and API key validity. |
| `/mem0:forget` | Delete your memories for this repo (shared project memory stays unless you pass `--include-project-memory`). |
| `/mem0:pause` | Pause memory capture. |
@@ -104,7 +111,11 @@ Categories for `--category`: `project_knowledge`, `decisions_and_constraints`, `
| `dir` | Project memory from the current directory (and children), plus your preferences |
| `mine` | Your personal preferences only |
-Set the default with the `search_scope` setting or `MEM0_CODE_SEARCH_SCOPE`. Pass `--run-id ` to see only what one specific session recorded.
+Set the default with the `search_scope` setting or `MEM0_CODE_SEARCH_SCOPE`. Pass optional `run_id` to `search_memories` (or `--run-id` to `/mem0:search`) with any scope to search memories saved in that session. Omit it to search across sessions. This filters the returned memories; it does not identify the session making the request. Use a known session ID.
+
+New Git repository memories use a hash of the remote identity in `agent_id`. Searches also include the previous unhashed ID under the same repository `app_id`, so shared memories remain available after upgrading. Older IDs retain their original limitation: matching owner/repository names on different Git hosts share that legacy namespace. Local folders keep their path-based namespaces.
+
+Explicit shared-memory deletion with `--include-project-memory` covers both repository IDs. Default deletion preserves shared memories.
## Settings
@@ -125,13 +136,23 @@ Local data lives in `${CLAUDE_PLUGIN_DATA}`:
- `pending/`: sessions waiting to be sent to Mem0 (retried after interruption)
- `flush-worker.log`: whether memory creation succeeded
- `plugin-errors.log`: hook errors (no credentials)
-- `telemetry.jsonl` / `telemetry-identity.json`: anonymous usage events
+- `telemetry.jsonl` / `telemetry-identity.json`: usage events and the id they are sent under
+- `telemetry-salt`: random per-install salt for the repo and session hashes
+- `install-state.json`: records that install has been counted once on this machine
-Mem0 receives each block of user messages, Claude's answers, the sidekick's answer, and changed file paths. Complete files and general tool output stay on your machine. Values that look like credentials are redacted before anything is sent.
+Mem0 receives captured user messages, Claude's answers, sidekick assignments and completed responses, and changed file paths. When a failed command is recorded, extraction can also include bounded command details and results. Complete files and general tool output stay on your machine. Values that look like credentials are redacted before anything is sent.
## Telemetry
-Anonymous usage events (which hook ran, timing, result counts, failure types) so Mem0 can identify what's used and what's breaking. Repo and session IDs are hashed before leaving your machine. Prompts, memory text, file paths, tool output, and API keys are never sent.
+Usage events (which hook ran, timing, result counts, failure types) so Mem0 can identify what's used and what's breaking.
+
+**These events are not anonymous.** When an API key is configured โ which installing the plugin requires โ events are sent under your Mem0 account email, the same way the Python SDK and the CLI attribute theirs. Without a key they are sent under a random per-machine id.
+
+What each event carries: the event name, the plugin version, the harness it ran in, your OS and Python version, and per-event properties describing what happened โ timings, counts, coarse outcome and failure labels, and which model was configured. Repository and session identifiers are hashed with a random salt generated on your machine, so they cannot be linked back to a repository name or path.
+
+Rather than restate a list that drifts, the exact set is enforced in code: `telemetry.record` filters every property through a denylist of sensitive keys and redacts credential-shaped values. See `_PRIVATE_KEYS` in `core/telemetry.py`.
+
+Prompts, memory text, queries, file paths, repository names, and API keys are never sent.
Turn it off:
@@ -181,10 +202,10 @@ Breaking update. Memories carry over, most local config does not.
## Development checks
-Run from `integrations/claude-code-plugin/`:
+Run from the repository root:
```bash
-python3 -m pytest tests -q
-python3 -m ruff check .
-claude plugin validate --strict .
+python3 -m pytest integrations/claude-code-plugin/tests -q --ignore=integrations/claude-code-plugin/tests/integration
+python3 -m ruff check integrations/agent-plugin-core/python integrations/claude-code-plugin
+claude plugin validate --strict integrations/claude-code-plugin
```
diff --git a/integrations/claude-code-plugin/adapters/claude/hook.py b/integrations/claude-code-plugin/adapters/claude/hook.py
index 1fcab1177..f38d959b2 100644
--- a/integrations/claude-code-plugin/adapters/claude/hook.py
+++ b/integrations/claude-code-plugin/adapters/claude/hook.py
@@ -3,367 +3,52 @@
from __future__ import annotations
-import argparse
-import hashlib
-import json
-import os
-import subprocess
import sys
-import time
-import uuid
from pathlib import Path
-sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "core"))
+_here = Path(__file__).resolve()
+_bundled_core = _here.parents[2] / "core"
+_core_dir = _bundled_core if (_bundled_core / "memory_core.py").is_file() else _bundled_core / "python"
+sys.path.insert(0, str(_core_dir))
+sys.path.insert(0, str(_here.parent))
-import telemetry
-from memory_core import (
- EvidenceStore,
- api_key,
- cache_plugin_api_key,
- checkpoint_session,
- clear_stale_api_key_cache,
- data_dir,
- detached_process_kwargs,
- format_context,
- record_session_start,
- record_sidekick_start,
- record_sidekick_stop,
- record_stop,
+import hook_runner # noqa: E402
+import telemetry # noqa: E402
+from memory_core import ( # noqa: E402
+ configure_harness,
+ record_subagent_start,
+ record_subagent_stop,
record_tool,
- record_user_prompt,
- search_memories,
)
+from transcript import record_stop # noqa: E402
+
+configure_harness("claude-code", data_dir_name="claude-code-plugin", source_tag="claude_code_plugin")
+telemetry.init(harness="claude-code", source_tag="CLAUDE_CODE_PLUGIN")
-STALE_RUNNING_SECONDS = 300
-PENDING_EXPIRY_SECONDS = 7 * 24 * 60 * 60
-PENDING_LAUNCH_LIMIT = 5
+def _sidekick_start(store, hook_input):
+ context = record_subagent_start(store, {"agent_type": "mem0:sidekick", **hook_input})
+ if context:
+ return {
+ "hookSpecificOutput": {
+ "hookEventName": "SubagentStart",
+ "additionalContext": context,
+ },
+ }
-def read_hook_input() -> dict:
- try:
- value = json.load(sys.stdin)
- return value if isinstance(value, dict) else {}
- except (json.JSONDecodeError, OSError):
- return {}
-
-
-def first_prompt_memory_output(store: EvidenceStore, hook_input: dict) -> dict:
- """Search once before Claude handles the first prompt in a session."""
- repo, session_id, prompt, is_first_prompt = record_user_prompt(store, hook_input)
- if not is_first_prompt:
- return {}
- try:
- minimum_query_chars = int(os.environ.get("MEM0_CODE_MIN_QUERY_CHARS", "20"))
- except ValueError:
- minimum_query_chars = 20
- if len(prompt.strip()) < max(minimum_query_chars, 1):
- return {}
- result = search_memories(
- store,
- repo,
- session_id,
- prompt,
- top_k=5,
- operation="first-prompt-search",
- timeout=2,
- )
- if not result.memories:
- return {}
- context = format_context(
- result.memories,
- "Mem0 found these relevant memories from earlier work in this repository:",
- )
- telemetry.record(
- "context_injected",
- repo=repo,
- session_id=session_id,
- trigger="first-prompt",
- memory_count=len(result.memories),
- context_chars=len(context),
- prompt_chars=len(prompt),
- )
- return {
- "hookSpecificOutput": {
- "hookEventName": "UserPromptSubmit",
- "additionalContext": context,
- },
- }
-
-
-def _launch_handoff(handoff_path: Path) -> bool:
- running_path = handoff_path.with_suffix(".running")
- try:
- handoff_path.replace(running_path)
- except OSError:
- return False
- worker = Path(__file__).resolve().parents[2] / "core" / "flush_worker.py"
- log_path = data_dir() / "flush-worker.log"
- log_handle = open(log_path, "a", encoding="utf-8")
- try:
- subprocess.Popen(
- [sys.executable, str(worker), str(running_path)],
- stdin=subprocess.DEVNULL,
- stdout=log_handle,
- stderr=log_handle,
- close_fds=True,
- **detached_process_kwargs(),
- )
- finally:
- log_handle.close()
- return True
-
-
-def recover_pending_handoffs() -> int:
- pending_dir = data_dir() / "pending"
- pending_dir.mkdir(parents=True, exist_ok=True)
- now = time.time()
- for running in pending_dir.glob("*.running"):
- try:
- if now - running.stat().st_mtime > STALE_RUNNING_SECONDS:
- running.replace(running.with_suffix(".json"))
- except OSError:
- continue
- recoverable = []
- for handoff in pending_dir.glob("*.json"):
- try:
- age = now - handoff.stat().st_mtime
- except OSError:
- continue
- if age > PENDING_EXPIRY_SECONDS:
- handoff.unlink(missing_ok=True)
- continue
- recoverable.append((age, handoff))
- recoverable.sort(key=lambda item: item[0], reverse=True)
- launched = 0
- for _, handoff in recoverable[:PENDING_LAUNCH_LIMIT]:
- launched += int(_launch_handoff(handoff))
- return launched
-
-
-def refresh_pending_handoffs() -> None:
- """Hold unsent packets while paused instead of letting them expire."""
- pending_dir = data_dir() / "pending"
- if not pending_dir.is_dir():
- return
- for pattern in ("*.json", "*.running"):
- for handoff in pending_dir.glob(pattern):
- try:
- os.utime(handoff)
- except OSError:
- continue
-
-
-def hand_off_flush(
- hook_input: dict, reason: str, *, wait_for_inflight: bool = False
-) -> None:
- """Persist hook input and detach delivery from Claude's shutdown lifecycle."""
- pending_dir = data_dir() / "pending"
- pending_dir.mkdir(parents=True, exist_ok=True)
- material = (
- f"{hook_input.get('cwd', '')}\0{hook_input.get('session_id', '')}\0{reason}"
- )
- digest = hashlib.sha256(material.encode()).hexdigest()[:24]
- handoff_path = pending_dir / f"{digest}-{uuid.uuid4().hex[:8]}.json"
- temporary_path = handoff_path.with_suffix(".tmp")
- temporary_path.write_text(
- json.dumps(
- {
- "hook_input": hook_input,
- "reason": reason,
- "wait_for_inflight": wait_for_inflight,
- }
- ),
- encoding="utf-8",
- )
- temporary_path.replace(handoff_path)
- _launch_handoff(handoff_path)
-
-
-def automatic_flush_enabled() -> bool:
- return os.environ.get("MEM0_CODE_AUTO_FLUSH", "true").lower() in {
- "1",
- "true",
- "yes",
- "on",
- }
-
-
-def schedule_periodic_checkpoint(
- store: EvidenceStore,
- hook_input: dict,
- repo,
- session_id: str,
-) -> bool:
- """Start one background extraction when a complete block is ready."""
- if (
- not automatic_flush_enabled()
- or not api_key()
- or not store.checkpoint_due(repo.identity, session_id)
- ):
- return False
- if store.prepare_flush(repo, session_id, "periodic") is None:
- return False
- hand_off_flush(hook_input, "periodic")
- return True
-
-
-DEFAULT_IDLE_FLUSH_SECONDS = 300
-
-
-def _idle_flush_seconds() -> int:
- try:
- return max(
- int(os.environ.get("MEM0_CODE_IDLE_FLUSH_SECONDS", str(DEFAULT_IDLE_FLUSH_SECONDS))),
- 0,
- )
- except ValueError:
- return DEFAULT_IDLE_FLUSH_SECONDS
-
-
-def schedule_idle_flush(
- store: EvidenceStore,
- hook_input: dict,
- repo,
- session_id: str,
-) -> bool:
- """Launch a delayed background flush for sessions that may never end."""
- delay = _idle_flush_seconds()
- if delay <= 0 or not automatic_flush_enabled() or not api_key():
- return False
- if store.has_inflight_flush(repo.identity, session_id):
- return False
- if not store.has_unflushed_events(repo.identity, session_id):
- return False
- pending_dir = data_dir() / "pending"
- pending_dir.mkdir(parents=True, exist_ok=True)
- material = f"idle\0{hook_input.get('cwd', '')}\0{hook_input.get('session_id', '')}"
- digest = hashlib.sha256(material.encode()).hexdigest()[:24]
- for old in pending_dir.glob(f"idle-{digest}*"):
- old.unlink(missing_ok=True)
- handoff_path = pending_dir / f"idle-{digest}-{uuid.uuid4().hex[:8]}.json"
- temporary_path = handoff_path.with_suffix(".tmp")
- temporary_path.write_text(
- json.dumps({
- "hook_input": hook_input,
- "reason": "idle",
- "delay_seconds": delay,
- }),
- encoding="utf-8",
- )
- temporary_path.replace(handoff_path)
- _launch_handoff(handoff_path)
- return True
-
-
-def log_failure(exc: Exception) -> None:
- try:
- log_path = data_dir() / "plugin-errors.log"
- with log_path.open("a", encoding="utf-8") as handle:
- handle.write(f"{time.time():.3f} {type(exc).__name__}: {exc}\n")
- except OSError:
- pass
-
-
-def main() -> int:
- parser = argparse.ArgumentParser()
- parser.add_argument(
- "action",
- choices=[
- "session-start",
- "user-prompt",
- "post-tool",
- "post-tool-failure",
- "sidekick-start",
- "sidekick-stop",
- "stop",
- "flush",
- ],
- )
- parser.add_argument("--reason", default="manual")
- parser.add_argument("--plugin-data-dir", default="")
- args = parser.parse_args()
- if args.plugin_data_dir:
- os.environ["MEM0_CODE_DATA_DIR"] = args.plugin_data_dir
- cache_plugin_api_key()
- if args.action == "session-start":
- clear_stale_api_key_cache()
- hook_input = read_hook_input()
- store = EvidenceStore()
- try:
- if store.is_paused():
- if args.action == "session-start":
- refresh_pending_handoffs()
- telemetry.record("session_start", paused=True)
- telemetry.spawn_flush()
- return 0
- if args.action == "session-start":
- if telemetry.is_first_run():
- telemetry.record("install")
- recovered = recover_pending_handoffs()
- record_session_start(store, hook_input)
- if recovered:
- telemetry.record("handoff_recovered", count=recovered)
- telemetry.spawn_flush()
- elif args.action == "user-prompt":
- output = first_prompt_memory_output(store, hook_input)
- if output:
- print(json.dumps(output))
- elif args.action == "post-tool":
- record_tool(store, hook_input)
- elif args.action == "post-tool-failure":
- record_tool(store, hook_input, failed=True)
- elif args.action == "sidekick-start":
- context = record_sidekick_start(store, hook_input)
- if context:
- print(
- json.dumps(
- {
- "hookSpecificOutput": {
- "hookEventName": "SubagentStart",
- "additionalContext": context,
- }
- }
- )
- )
- elif args.action == "sidekick-stop":
- record_sidekick_stop(store, hook_input)
- elif args.action == "stop":
- repo, session_id = record_stop(store, hook_input)
- if not schedule_periodic_checkpoint(store, hook_input, repo, session_id):
- schedule_idle_flush(store, hook_input, repo, session_id)
- elif args.action == "flush":
- automatic = args.reason in {"session-end", "pre-compact"}
- if automatic and not automatic_flush_enabled():
- return 0
- if args.reason == "session-end":
- # In print mode, SessionEnd can arrive before the Stop hook has
- # recorded Claude's final response. Read any remaining visible
- # transcript messages before preparing the final extraction.
- record_stop(store, hook_input)
- if os.environ.get("MEM0_CODE_SYNC_FLUSH") == "1":
- print(json.dumps(checkpoint_session(store, hook_input, args.reason)))
- else:
- session_id = str(hook_input.get("session_id") or "unknown-session")
- repo = store.repo_for_session(session_id, hook_input.get("cwd"))
- already_running = store.has_inflight_flush(repo.identity, session_id)
- if already_running and args.reason == "session-end":
- hand_off_flush(
- hook_input, args.reason, wait_for_inflight=True
- )
- elif not already_running and store.prepare_flush(
- repo, session_id, args.reason
- ) is not None:
- hand_off_flush(hook_input, args.reason)
- finally:
- store.close()
- return 0
+def _sidekick_stop(store, hook_input):
+ record_subagent_stop(store, {"agent_type": "mem0:sidekick", **hook_input})
if __name__ == "__main__":
- try:
- raise SystemExit(main())
- except Exception as exc:
- # Memory must never prevent the coding agent from continuing.
- log_failure(exc)
- raise SystemExit(0)
+ hook_runner.entry_point(
+ record_stop_fn=record_stop,
+ extra_actions={
+ "post-tool-failure": lambda s, h: record_tool(s, h, failed=True),
+ "sidekick-start": _sidekick_start,
+ "sidekick-stop": _sidekick_stop,
+ },
+ data_dir_env="MEM0_CODE_DATA_DIR",
+ automatic_flush_reasons={"session-end", "pre-compact"},
+ )
diff --git a/integrations/claude-code-plugin/adapters/claude/transcript.py b/integrations/claude-code-plugin/adapters/claude/transcript.py
new file mode 100644
index 000000000..1d55ccb96
--- /dev/null
+++ b/integrations/claude-code-plugin/adapters/claude/transcript.py
@@ -0,0 +1,362 @@
+"""Claude Code transcript parsing for Mem0 memory extraction."""
+
+from __future__ import annotations
+
+import html
+import json
+import re
+import sys
+from pathlib import Path
+from typing import Any
+
+_here = Path(__file__).resolve()
+sys.path.insert(0, str(_here.parents[2] / "core" / "python"))
+
+from memory_core import ( # noqa: E402
+ EvidenceStore,
+ RepoContext,
+ _session_id,
+ redact,
+)
+
+
+def _message_content_text(content: Any) -> str:
+ """Return visible text from one Claude transcript message."""
+ if isinstance(content, str):
+ return redact(content).strip()
+ if not isinstance(content, list):
+ return ""
+ parts = []
+ for block in content:
+ if not isinstance(block, dict) or block.get("type") != "text":
+ continue
+ text = redact(block.get("text", "")).strip()
+ if text:
+ parts.append(text)
+ return "\n\n".join(parts)
+
+
+def _transcript_rows(
+ path: str, offset: int = 0
+) -> tuple[list[dict[str, Any]], int, bool]:
+ """Parse transcript rows from a byte offset, returning rows, end offset, and whether the offset was honored."""
+ if not path:
+ return [], 0, False
+ rows = []
+ try:
+ resolved = Path(path).expanduser()
+ if not 0 <= offset <= resolved.stat().st_size:
+ offset = 0
+ end = offset
+ with resolved.open("rb") as handle:
+ handle.seek(offset)
+ for line in handle:
+ if not line.endswith(b"\n"):
+ break
+ end += len(line)
+ try:
+ row = json.loads(line.decode("utf-8", errors="replace"))
+ except json.JSONDecodeError:
+ continue
+ if isinstance(row, dict) and row.get("uuid"):
+ rows.append(row)
+ except OSError:
+ return [], offset, False
+ return rows, end, offset > 0
+
+
+def _active_transcript_chain(
+ rows: list[dict[str, Any]], session_id: str
+) -> list[dict[str, Any]]:
+ """Follow the current Claude conversation branch from its latest record."""
+ by_uuid = {str(row["uuid"]): row for row in rows if row.get("uuid")}
+ leaf = next(
+ (
+ row
+ for row in reversed(rows)
+ if not row.get("isSidechain")
+ and str(row.get("sessionId") or "") == session_id
+ ),
+ None,
+ )
+ if leaf is None:
+ return []
+
+ chain = []
+ seen = set()
+ current = leaf
+ while current is not None:
+ uuid = str(current.get("uuid") or "")
+ if not uuid or uuid in seen:
+ break
+ seen.add(uuid)
+ chain.append(current)
+ current = by_uuid.get(str(current.get("parentUuid") or ""))
+ chain.reverse()
+ return chain
+
+
+def _human_prompt_text(row: dict[str, Any]) -> str:
+ if row.get("type") != "user":
+ return ""
+ origin = row.get("origin") or {}
+ if isinstance(origin, dict) and origin.get("kind") not in {None, "human"}:
+ return ""
+ message = row.get("message") or {}
+ content = message.get("content") if isinstance(message, dict) else None
+ if not isinstance(content, str):
+ return ""
+ text = redact(content).strip()
+ if text.startswith(""):
+ text = text.removeprefix("").strip()
+ ignored_prefixes = (
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ )
+ return "" if text.startswith(ignored_prefixes) else text
+
+
+def _xml_value(text: str, tag: str) -> str:
+ match = re.search(fr"<{tag}>(.*?){tag}>", text, re.DOTALL)
+ return html.unescape(match.group(1).strip()) if match else ""
+
+
+def _agent_assignment(tool_input: dict[str, Any]) -> str:
+ prompt = redact(tool_input.get("prompt", "")).strip()
+ if not prompt:
+ return ""
+ agent_type = redact(tool_input.get("subagent_type", "agent")).strip() or "agent"
+ description = redact(tool_input.get("description", "")).strip()
+ heading = f"Subagent assignment ({agent_type}"
+ if description:
+ heading += f": {description}"
+ return f"{heading}):\n{prompt}"
+
+
+def _agent_response(tool_input: dict[str, Any], result: str) -> str:
+ result = redact(result).strip()
+ if not result or result.startswith("Async agent launched successfully."):
+ return ""
+ agent_type = redact(tool_input.get("subagent_type", "agent")).strip() or "agent"
+ description = redact(tool_input.get("description", "")).strip()
+ heading = f"Subagent response ({agent_type}"
+ if description:
+ heading += f": {description}"
+ return f"{heading}):\n{result}"
+
+
+def _tool_result_text(block: dict[str, Any]) -> str:
+ return _message_content_text(block.get("content"))
+
+
+def transcript_extraction_messages(
+ transcript_path: str,
+ session_id: str,
+ *,
+ previous_leaf_uuid: str = "",
+ prompt_hint: str = "",
+ fallback_assistant_message: str = "",
+ label_final_response: bool = False,
+ start_offset: int = 0,
+) -> tuple[list[dict[str, str]], str, int]:
+ """Read the meaningful part of the current Claude exchange."""
+ rows, end_offset, resumed = _transcript_rows(transcript_path, start_offset)
+ chain = _active_transcript_chain(rows, session_id)
+ if not chain:
+ if resumed:
+ return [], previous_leaf_uuid, end_offset
+ fallback = redact(fallback_assistant_message).strip()
+ return (
+ ([{"role": "assistant", "content": f"Main Claude response:\n{fallback}"}]
+ if fallback
+ else []),
+ "",
+ end_offset,
+ )
+
+ leaf_uuid = str(chain[-1].get("uuid") or "")
+ if previous_leaf_uuid and leaf_uuid == previous_leaf_uuid:
+ return [], leaf_uuid, end_offset
+ start = 0
+ if previous_leaf_uuid:
+ for index, row in enumerate(chain):
+ if str(row.get("uuid") or "") == previous_leaf_uuid:
+ start = index + 1
+ break
+ else:
+ previous_leaf_uuid = ""
+ if not previous_leaf_uuid and not resumed:
+ prompt_hint = redact(prompt_hint).strip()
+ candidates = [
+ index
+ for index, row in enumerate(chain)
+ if _human_prompt_text(row)
+ and (
+ not prompt_hint
+ or _human_prompt_text(row) == prompt_hint
+ )
+ ]
+ task_notifications = [
+ index
+ for index, row in enumerate(chain)
+ if isinstance((row.get("message") or {}).get("content"), str)
+ and (row.get("message") or {})["content"].startswith("")
+ ]
+ if candidates:
+ start = candidates[-1]
+ elif task_notifications:
+ start = task_notifications[-1]
+
+ tool_uses: dict[str, tuple[str, dict[str, Any]]] = {}
+ for row in chain:
+ message = row.get("message") or {}
+ content = message.get("content") if isinstance(message, dict) else None
+ if not isinstance(content, list):
+ continue
+ for block in content:
+ if not isinstance(block, dict) or block.get("type") != "tool_use":
+ continue
+ tool_id = str(block.get("id") or "")
+ tool_input = block.get("input") or {}
+ if tool_id and isinstance(tool_input, dict):
+ tool_uses[tool_id] = (str(block.get("name") or ""), tool_input)
+
+ output: list[dict[str, str]] = []
+
+ def append(role: str, content: str) -> None:
+ content = redact(content).strip()
+ if content:
+ output.append({"role": role, "content": content})
+
+ for row in chain[start:]:
+ message = row.get("message") or {}
+ if not isinstance(message, dict):
+ continue
+ role = str(message.get("role") or "")
+ content = message.get("content")
+
+ if role == "user" and isinstance(content, str):
+ if content.startswith(""):
+ if _xml_value(content, "status") != "completed":
+ continue
+ tool_id = _xml_value(content, "tool-use-id")
+ tool = tool_uses.get(tool_id)
+ result = _xml_value(content, "result")
+ if tool and tool[0] == "Agent" and result:
+ assignment = _agent_assignment(tool[1])
+ response = _agent_response(tool[1], result)
+ append("assistant", assignment)
+ append("assistant", response)
+ continue
+ human = _human_prompt_text(row)
+ if human:
+ append("user", human)
+ continue
+
+ if not isinstance(content, list):
+ continue
+ for block in content:
+ if not isinstance(block, dict):
+ continue
+ block_type = block.get("type")
+ if role == "assistant" and block_type == "text":
+ append("assistant", str(block.get("text") or ""))
+ continue
+ if role != "user" or block_type != "tool_result":
+ continue
+
+ tool_id = str(block.get("tool_use_id") or "")
+ tool = tool_uses.get(tool_id)
+ if not tool:
+ continue
+ name, tool_input = tool
+ result = _tool_result_text(block)
+ failed = bool(block.get("is_error"))
+ if name == "Agent" and not failed:
+ response = _agent_response(tool_input, result)
+ if response:
+ append("assistant", _agent_assignment(tool_input))
+ append("assistant", response)
+ elif name == "AskUserQuestion" and result and not failed:
+ append("user", f"User answers to Claude's questions:\n{result}")
+ elif name == "ExitPlanMode" and not failed:
+ plan = redact(tool_input.get("plan", "")).strip()
+ if plan:
+ append("assistant", f"Approved implementation plan:\n{plan}")
+
+ fallback = redact(fallback_assistant_message).strip()
+ if fallback:
+ labeled = f"Main Claude response:\n{fallback}"
+ for message in reversed(output):
+ if message["role"] == "assistant" and message["content"] == fallback:
+ message["content"] = labeled
+ break
+ else:
+ append("assistant", labeled)
+ elif label_final_response:
+ last_message = chain[-1].get("message") or {}
+ last_content = (
+ last_message.get("content") if isinstance(last_message, dict) else None
+ )
+ final_parts = [
+ redact(block.get("text", "")).strip()
+ for block in (last_content if isinstance(last_content, list) else [])
+ if isinstance(block, dict)
+ and block.get("type") == "text"
+ and redact(block.get("text", "")).strip()
+ ]
+ for start in range(len(output) - len(final_parts), -1, -1):
+ candidate = output[start : start + len(final_parts)]
+ if final_parts and [item["content"] for item in candidate] == final_parts:
+ candidate[0]["content"] = (
+ f"Main Claude response:\n{candidate[0]['content']}"
+ )
+ break
+ return output, leaf_uuid, end_offset
+
+
+def record_stop(
+ store: EvidenceStore, hook_input: dict[str, Any]
+) -> tuple[RepoContext, str]:
+ session_id = _session_id(hook_input)
+ repo = store.repo_for_session(session_id, hook_input.get("cwd"))
+ message = redact(hook_input.get("last_assistant_message", "")).strip()
+ previous_stop = store.latest_event_payload(
+ repo.identity, session_id, "assistant_stop"
+ )
+ latest_prompt = store.latest_event_payload(repo.identity, session_id, "user_prompt")
+ transcript_path = str(hook_input.get("transcript_path") or "")
+ previous_offset = previous_stop.get("transcript_offset")
+ start_offset = (
+ previous_offset
+ if isinstance(previous_offset, int)
+ and str(previous_stop.get("transcript_path") or "") == transcript_path
+ else 0
+ )
+ transcript_messages, leaf_uuid, end_offset = transcript_extraction_messages(
+ transcript_path,
+ session_id,
+ previous_leaf_uuid=str(previous_stop.get("transcript_leaf_uuid") or ""),
+ prompt_hint=str(latest_prompt.get("text") or ""),
+ fallback_assistant_message=message,
+ label_final_response=True,
+ start_offset=start_offset,
+ )
+ if transcript_messages:
+ payload: dict[str, Any] = {
+ "text": message,
+ "transcript_messages": transcript_messages,
+ }
+ if leaf_uuid:
+ payload["transcript_leaf_uuid"] = leaf_uuid
+ if transcript_path:
+ payload["transcript_path"] = transcript_path
+ payload["transcript_offset"] = end_offset
+ store.record_event(
+ repo, session_id, "assistant_stop", payload
+ )
+ return repo, session_id
diff --git a/integrations/claude-code-plugin/agents/sidekick.md b/integrations/claude-code-plugin/agents/sidekick.md
index d0552c0c3..8f719327a 100644
--- a/integrations/claude-code-plugin/agents/sidekick.md
+++ b/integrations/claude-code-plugin/agents/sidekick.md
@@ -12,11 +12,8 @@ You are Mem0's Sonnet coding agent. Complete the work the main agent gives you.
Work in the separate Git worktree Claude Code created for you. Return a tested
result that the main agent can review without doing the same work again.
-ALWAYS call `search_memories` before answering anything that could depend on
-prior context (the user's preferences, facts about this codebase, history,
-people, projects, or earlier decisions). Do not rely on the chat window or
-assume you know enough from the current conversation. Search with a focused
-question before investigating the repository.
+When memories from earlier sessions could help, call `search_memories` with a
+focused question before searching the repository again.
Inspect the relevant code and repository rules. Reproduce the problem when that
helps. Decide the implementation details, edit files when asked, and test the
diff --git a/integrations/claude-code-plugin/core/_harness_id.py b/integrations/claude-code-plugin/core/_harness_id.py
new file mode 100644
index 000000000..9c4949408
--- /dev/null
+++ b/integrations/claude-code-plugin/core/_harness_id.py
@@ -0,0 +1,11 @@
+"""Generated by integrations/agent-plugin-core/build/build.py. Do not edit."""
+
+HARNESS_ID = "claude-code"
+SOURCE_TAG = "CLAUDE_CODE_PLUGIN"
+
+# Platform-side vocabulary (mem0_event.source + X-Application). The whole
+# plugin family is one source; which editor it runs in is the application.
+# An empty application means the host is unknown, and memory_core omits
+# the header entirely rather than sending a placeholder.
+PLATFORM_SOURCE = "MEM0_PLUGIN"
+PLATFORM_APPLICATION = "claude-code"
diff --git a/integrations/claude-code-plugin/core/flush_worker.py b/integrations/claude-code-plugin/core/flush_worker.py
index c60fa82a5..6f7b9ecb2 100644
--- a/integrations/claude-code-plugin/core/flush_worker.py
+++ b/integrations/claude-code-plugin/core/flush_worker.py
@@ -17,7 +17,7 @@ import telemetry
from memory_core import (
EvidenceStore,
checkpoint_session,
- record_stop,
+ configure_harness,
touch_handoff_heartbeat,
)
@@ -27,15 +27,28 @@ def main() -> int:
return 2
handoff_path = Path(sys.argv[1])
os.environ["MEM0_CODE_HANDOFF_PATH"] = str(handoff_path)
+ harness = os.environ.get("MEM0_PLUGIN_HARNESS")
+ if harness:
+ source_tag = os.environ.get("MEM0_PLUGIN_SOURCE_TAG", "")
+ configure_harness(
+ harness,
+ env_prefix=os.environ.get("MEM0_PLUGIN_ENV_PREFIX", ""),
+ data_dir_name=os.environ.get("MEM0_PLUGIN_DATA_DIR_NAME", ""),
+ source_tag=source_tag,
+ )
+ telemetry.init(harness=harness, source_tag=source_tag.upper())
completed = False
try:
payload = json.loads(handoff_path.read_text(encoding="utf-8"))
delay = float(payload.get("delay_seconds") or 0)
if delay > 0:
payload.pop("delay_seconds", None)
- handoff_path.write_text(
- json.dumps(payload), encoding="utf-8"
- )
+ temporary = handoff_path.with_suffix(f".{os.getpid()}.tmp")
+ try:
+ temporary.write_text(json.dumps(payload), encoding="utf-8")
+ temporary.replace(handoff_path)
+ finally:
+ temporary.unlink(missing_ok=True)
time.sleep(delay)
if not handoff_path.exists():
return 0
@@ -58,8 +71,7 @@ def main() -> int:
):
touch_handoff_heartbeat()
time.sleep(0.25)
- if reason == "session-end":
- record_stop(store, hook_input)
+ # Hooks capture the conversation before handoff; the worker only flushes it.
result = checkpoint_session(store, hook_input, reason)
print(json.dumps(result, sort_keys=True), flush=True)
completed = result.get("status") in {
diff --git a/integrations/claude-code-plugin/core/hook_runner.py b/integrations/claude-code-plugin/core/hook_runner.py
new file mode 100644
index 000000000..b3d8a3210
--- /dev/null
+++ b/integrations/claude-code-plugin/core/hook_runner.py
@@ -0,0 +1,388 @@
+"""Shared hook orchestration for all Mem0 agent plugins."""
+
+from __future__ import annotations
+
+import argparse
+import hashlib
+import json
+import os
+import subprocess
+import sys
+import time
+import uuid
+from pathlib import Path
+
+import telemetry
+from memory_core import (
+ EvidenceStore,
+ _session_id,
+ api_key,
+ bounded,
+ cache_plugin_api_key,
+ checkpoint_session,
+ clear_stale_api_key_cache,
+ configure_harness,
+ data_dir,
+ detached_process_kwargs,
+ format_context,
+ harness_config,
+ record_session_start,
+ record_tool,
+ record_user_prompt,
+ redact,
+ search_memories,
+)
+
+STALE_RUNNING_SECONDS = 300
+PENDING_EXPIRY_SECONDS = 7 * 24 * 60 * 60
+PENDING_LAUNCH_LIMIT = 5
+DEFAULT_IDLE_FLUSH_SECONDS = 300
+
+_core_dir: Path = Path(__file__).resolve().parent
+
+
+def read_hook_input() -> dict:
+ try:
+ value = json.load(sys.stdin)
+ return value if isinstance(value, dict) else {}
+ except (json.JSONDecodeError, OSError):
+ return {}
+
+
+def default_record_stop(store: EvidenceStore, hook_input: dict):
+ """Record the assistant's response without transcript parsing."""
+ session_id = _session_id(hook_input)
+ repo = store.repo_for_session(session_id, hook_input.get("cwd"))
+ message = redact(hook_input.get("last_assistant_message", "")).strip()
+ if message:
+ store.record_assistant_response(repo, session_id, message)
+ return repo, session_id
+
+
+def first_prompt_memory_output(store: EvidenceStore, hook_input: dict) -> dict:
+ """Search once before the agent handles the first prompt in a session."""
+ repo, session_id, prompt, is_first_prompt = record_user_prompt(store, hook_input)
+ if not is_first_prompt:
+ return {}
+ try:
+ minimum_query_chars = int(os.environ.get("MEM0_CODE_MIN_QUERY_CHARS", "20"))
+ except ValueError:
+ minimum_query_chars = 20
+ if len(prompt.strip()) < max(minimum_query_chars, 1):
+ return {}
+ result = search_memories(
+ store, repo, session_id, bounded(prompt, 6000),
+ top_k=5, operation="first-prompt-search", timeout=2,
+ )
+ if not result.memories:
+ return {}
+ context = format_context(
+ result.memories,
+ "Mem0 found these relevant memories from earlier work in this repository:",
+ )
+ telemetry.record(
+ "context_injected",
+ repo=repo, session_id=session_id, trigger="first-prompt",
+ memory_count=len(result.memories), context_chars=len(context),
+ prompt_chars=len(prompt),
+ )
+ return {
+ "hookSpecificOutput": {
+ "hookEventName": "UserPromptSubmit",
+ "additionalContext": context,
+ },
+ }
+
+
+def _launch_handoff(handoff_path: Path) -> bool:
+ running_path = handoff_path.with_suffix(".running")
+ try:
+ handoff_path.replace(running_path)
+ except OSError:
+ return False
+ worker = _core_dir / "flush_worker.py"
+ log_path = data_dir() / "flush-worker.log"
+ log_handle = open(log_path, "a", encoding="utf-8")
+ harness = harness_config()
+ child_env = os.environ.copy()
+ child_env.update(
+ {
+ "MEM0_CODE_DATA_DIR": str(data_dir()),
+ "MEM0_PLUGIN_HARNESS": harness["name"],
+ "MEM0_PLUGIN_ENV_PREFIX": harness["env_prefix"],
+ "MEM0_PLUGIN_DATA_DIR_NAME": harness["data_dir_name"],
+ "MEM0_PLUGIN_SOURCE_TAG": harness["source_tag"],
+ }
+ )
+ try:
+ subprocess.Popen(
+ [sys.executable, str(worker), str(running_path)],
+ stdin=subprocess.DEVNULL,
+ stdout=log_handle, stderr=log_handle,
+ close_fds=True,
+ env=child_env,
+ **detached_process_kwargs(),
+ )
+ finally:
+ log_handle.close()
+ return True
+
+
+def recover_pending_handoffs() -> int:
+ pending_dir = data_dir() / "pending"
+ pending_dir.mkdir(parents=True, exist_ok=True)
+ now = time.time()
+ for running in pending_dir.glob("*.running"):
+ try:
+ if now - running.stat().st_mtime > STALE_RUNNING_SECONDS:
+ running.replace(running.with_suffix(".json"))
+ except OSError:
+ continue
+ recoverable = []
+ for handoff in pending_dir.glob("*.json"):
+ try:
+ age = now - handoff.stat().st_mtime
+ except OSError:
+ continue
+ if age > PENDING_EXPIRY_SECONDS:
+ handoff.unlink(missing_ok=True)
+ continue
+ recoverable.append((age, handoff))
+ recoverable.sort(key=lambda item: item[0], reverse=True)
+ launched = 0
+ for _, handoff in recoverable[:PENDING_LAUNCH_LIMIT]:
+ launched += int(_launch_handoff(handoff))
+ return launched
+
+
+def refresh_pending_handoffs() -> None:
+ pending_dir = data_dir() / "pending"
+ if not pending_dir.is_dir():
+ return
+ for pattern in ("*.json", "*.running"):
+ for handoff in pending_dir.glob(pattern):
+ try:
+ os.utime(handoff)
+ except OSError:
+ continue
+
+
+def hand_off_flush(
+ hook_input: dict, reason: str, *, wait_for_inflight: bool = False,
+) -> None:
+ pending_dir = data_dir() / "pending"
+ pending_dir.mkdir(parents=True, exist_ok=True)
+ material = (
+ f"{hook_input.get('cwd', '')}\0{hook_input.get('session_id', '')}\0{reason}"
+ )
+ digest = hashlib.sha256(material.encode()).hexdigest()[:24]
+ handoff_path = pending_dir / f"{digest}-{uuid.uuid4().hex[:8]}.json"
+ temporary_path = handoff_path.with_suffix(".tmp")
+ temporary_path.write_text(
+ json.dumps({
+ "hook_input": hook_input,
+ "reason": reason,
+ "wait_for_inflight": wait_for_inflight,
+ }),
+ encoding="utf-8",
+ )
+ temporary_path.replace(handoff_path)
+ _launch_handoff(handoff_path)
+
+
+def automatic_flush_enabled() -> bool:
+ return os.environ.get("MEM0_CODE_AUTO_FLUSH", "true").lower() in {
+ "1", "true", "yes", "on",
+ }
+
+
+def schedule_periodic_checkpoint(
+ store: EvidenceStore, hook_input: dict, repo, session_id: str,
+) -> bool:
+ if (
+ not automatic_flush_enabled()
+ or not api_key()
+ or not store.checkpoint_due(repo.identity, session_id)
+ ):
+ return False
+ if store.prepare_flush(repo, session_id, "periodic") is None:
+ return False
+ hand_off_flush(hook_input, "periodic")
+ return True
+
+
+def _idle_flush_seconds() -> int:
+ try:
+ return max(
+ int(os.environ.get("MEM0_CODE_IDLE_FLUSH_SECONDS", str(DEFAULT_IDLE_FLUSH_SECONDS))),
+ 0,
+ )
+ except ValueError:
+ return DEFAULT_IDLE_FLUSH_SECONDS
+
+
+def schedule_idle_flush(
+ store: EvidenceStore, hook_input: dict, repo, session_id: str,
+) -> bool:
+ delay = _idle_flush_seconds()
+ if delay <= 0 or not automatic_flush_enabled() or not api_key():
+ return False
+ if store.has_inflight_flush(repo.identity, session_id):
+ return False
+ if not store.has_unflushed_events(repo.identity, session_id):
+ return False
+ pending_dir = data_dir() / "pending"
+ pending_dir.mkdir(parents=True, exist_ok=True)
+ material = f"idle\0{hook_input.get('cwd', '')}\0{hook_input.get('session_id', '')}"
+ digest = hashlib.sha256(material.encode()).hexdigest()[:24]
+ for old in pending_dir.glob(f"idle-{digest}*"):
+ old.unlink(missing_ok=True)
+ handoff_path = pending_dir / f"idle-{digest}-{uuid.uuid4().hex[:8]}.json"
+ temporary_path = handoff_path.with_suffix(".tmp")
+ temporary_path.write_text(
+ json.dumps({
+ "hook_input": hook_input,
+ "reason": "idle",
+ "delay_seconds": delay,
+ }),
+ encoding="utf-8",
+ )
+ temporary_path.replace(handoff_path)
+ _launch_handoff(handoff_path)
+ return True
+
+
+def log_failure(exc: Exception) -> None:
+ try:
+ log_path = data_dir() / "plugin-errors.log"
+ with log_path.open("a", encoding="utf-8") as handle:
+ handle.write(f"{time.time():.3f} {type(exc).__name__}: {exc}\n")
+ except OSError:
+ pass
+
+
+def run(
+ *,
+ record_stop_fn=None,
+ extra_actions: dict | None = None,
+ data_dir_env: str = "MEM0_PLUGIN_DATA_DIR",
+ automatic_flush_reasons: set | None = None,
+) -> int:
+ if record_stop_fn is None:
+ record_stop_fn = default_record_stop
+ if automatic_flush_reasons is None:
+ automatic_flush_reasons = {"session-end"}
+
+ base_actions = ["session-start", "user-prompt", "post-tool", "stop", "flush"]
+ all_actions = base_actions + list((extra_actions or {}).keys())
+
+ parser = argparse.ArgumentParser()
+ parser.add_argument("action", choices=all_actions)
+ parser.add_argument("--reason", default="manual")
+ parser.add_argument("--plugin-data-dir", default="")
+ parser.add_argument("--harness", default="")
+ args = parser.parse_args()
+
+ if args.harness:
+ configure_harness(args.harness)
+ telemetry.init(harness=args.harness)
+
+ if args.plugin_data_dir:
+ os.environ[data_dir_env] = args.plugin_data_dir
+
+ # Snapshot BEFORE anything writes to the data dir: cache_plugin_api_key
+ # writes `api-key` and EvidenceStore creates `evidence.sqlite3`, so asking
+ # after them always saw content and every fresh install reported an upgrade.
+ data_dir_was_empty = telemetry.data_dir_was_empty()
+
+ cache_plugin_api_key()
+ if args.action == "session-start":
+ clear_stale_api_key_cache()
+
+ hook_input = read_hook_input()
+ store = EvidenceStore()
+ try:
+ if store.is_paused():
+ if args.action == "session-start":
+ refresh_pending_handoffs()
+ telemetry.record("session_start", paused=True)
+ telemetry.spawn_flush()
+ return 0
+
+ if args.action == "session-start":
+ # Claims the marker atomically and says which event to record, so a
+ # second session starting alongside this one cannot record it too.
+ first_event = telemetry.claim_install(was_empty=data_dir_was_empty)
+ if first_event == "install":
+ telemetry.record("install")
+ elif first_event == "upgrade":
+ # First run after a build that never wrote the marker; the
+ # predecessor version was never recorded anywhere.
+ telemetry.record("upgrade", from_version="pre-0.3")
+ else:
+ previous = telemetry.claim_version_change()
+ if previous:
+ telemetry.record("upgrade", from_version=previous)
+ recovered = recover_pending_handoffs()
+ record_session_start(store, hook_input)
+ if recovered:
+ telemetry.record("handoff_recovered", count=recovered)
+ telemetry.spawn_flush()
+ elif args.action == "user-prompt":
+ output = first_prompt_memory_output(store, hook_input)
+ if output:
+ print(json.dumps(output))
+ elif args.action == "post-tool":
+ record_tool(store, hook_input)
+ elif args.action == "stop":
+ repo, session_id = record_stop_fn(store, hook_input)
+ if not schedule_periodic_checkpoint(store, hook_input, repo, session_id):
+ schedule_idle_flush(store, hook_input, repo, session_id)
+ elif args.action == "flush":
+ automatic = args.reason in automatic_flush_reasons
+ if automatic and not automatic_flush_enabled():
+ return 0
+ if args.reason == "session-end":
+ record_stop_fn(store, hook_input)
+ if os.environ.get("MEM0_CODE_SYNC_FLUSH") == "1":
+ print(json.dumps(checkpoint_session(store, hook_input, args.reason)))
+ else:
+ session_id = str(hook_input.get("session_id") or "unknown-session")
+ repo = store.repo_for_session(session_id, hook_input.get("cwd"))
+ already_running = store.has_inflight_flush(repo.identity, session_id)
+ if already_running and args.reason == "session-end":
+ hand_off_flush(hook_input, args.reason, wait_for_inflight=True)
+ elif not already_running and store.prepare_flush(
+ repo, session_id, args.reason,
+ ) is not None:
+ hand_off_flush(hook_input, args.reason)
+ elif extra_actions and args.action in extra_actions:
+ result = extra_actions[args.action](store, hook_input)
+ if result:
+ print(json.dumps(result))
+ finally:
+ store.close()
+ return 0
+
+
+def entry_point(
+ *,
+ record_stop_fn=None,
+ extra_actions: dict | None = None,
+ data_dir_env: str = "MEM0_PLUGIN_DATA_DIR",
+ automatic_flush_reasons: set | None = None,
+) -> None:
+ try:
+ raise SystemExit(run(
+ record_stop_fn=record_stop_fn,
+ extra_actions=extra_actions,
+ data_dir_env=data_dir_env,
+ automatic_flush_reasons=automatic_flush_reasons,
+ ))
+ except Exception as exc:
+ log_failure(exc)
+ raise SystemExit(0)
+
+
+if __name__ == "__main__":
+ entry_point()
diff --git a/integrations/claude-code-plugin/core/mcp_server.py b/integrations/claude-code-plugin/core/mcp_server.py
index 2a9a37c07..a0b73cb79 100644
--- a/integrations/claude-code-plugin/core/mcp_server.py
+++ b/integrations/claude-code-plugin/core/mcp_server.py
@@ -1,5 +1,5 @@
#!/usr/bin/env python3
-"""Expose Mem0's memory search as one local Claude Code tool."""
+"""Expose Mem0's memory search as one local coding-agent tool."""
from __future__ import annotations
@@ -11,27 +11,19 @@ from typing import Any
import telemetry
from memory_core import (
CODING_MEMORY_CATEGORY_NAMES,
+ PLUGIN_VERSION,
+ SEARCH_SCOPES,
format_search_result,
resolve_repo,
- SEARCH_SCOPES,
search_memories,
)
-
PROTOCOL_VERSION = "2024-11-05"
TOOL_NAME = "search_memories"
TOOL_DESCRIPTION = (
- "Search memories from earlier work in this repository. ALWAYS call this "
- "tool before answering anything that could depend on prior context: the "
- "user's preferences, facts about this codebase, history, people, projects, "
- "or earlier decisions. Do not rely on the chat window alone. The "
- "repository's memory is shared by everyone who works in it and includes "
- "what it took to run, test, or build here, so search before assuming an "
- "invocation works. The scope argument changes what is searched: 'repo' "
- "(default) is the whole repository's shared memory plus your own "
- "preferences, 'dir' narrows the shared part to the directory you are "
- "working in, and 'mine' is your preferences alone. Pass run_id to look "
- "at one earlier Claude Code session only."
+ "Search memories from earlier work in this repository. Use it before "
+ "repeating investigation or when earlier decisions, fixes, commands, or "
+ "results may help."
)
TOOL_SCHEMA = {
"type": "object",
@@ -65,8 +57,10 @@ TOOL_SCHEMA = {
"run_id": {
"type": "string",
"minLength": 1,
- "maxLength": 200,
- "description": "Optional Claude Code session ID. Restricts the search to memories written from that session.",
+ "description": (
+ "Optional coding-agent session ID. With any scope, restricts results to memories "
+ "saved in that session. Omit to recall memories across sessions."
+ ),
},
},
"required": ["query"],
@@ -110,16 +104,17 @@ def _validate_arguments(
raise ToolInputError(f"scope must be one of {list(SEARCH_SCOPES)}.")
run_id = arguments.get("run_id")
- if run_id is not None and (
- not isinstance(run_id, str) or not run_id.strip() or len(run_id) > 200
- ):
- raise ToolInputError("run_id must be a non-empty string of at most 200 characters.")
+ if run_id is not None:
+ if not isinstance(run_id, str) or not run_id.strip():
+ raise ToolInputError("run_id must be a non-empty string.")
+ run_id = run_id.strip()
+
return query, top_k, category, scope, run_id
-def call_search_memories(arguments: Any) -> str:
+def call_search_memories(arguments: Any, cwd: str | None = None) -> str:
query, top_k, category, scope, run_id = _validate_arguments(arguments)
- repo = resolve_repo(os.environ.get("CLAUDE_PROJECT_DIR") or os.getcwd())
+ repo = resolve_repo(cwd or os.environ.get("CLAUDE_PROJECT_DIR") or os.getcwd())
result = search_memories(
None,
repo,
@@ -134,6 +129,19 @@ def call_search_memories(arguments: Any) -> str:
return format_search_result(result)
+def _workspace_cwd(params: dict[str, Any]) -> str | None:
+ meta = params.get("_meta")
+ if not isinstance(meta, dict):
+ return None
+ metadata = meta.get("x-codex-turn-metadata")
+ if not isinstance(metadata, dict):
+ return None
+ workspaces = metadata.get("workspaces") or {}
+ if isinstance(workspaces, dict):
+ return next((path for path in workspaces if isinstance(path, str) and path), None)
+ return None
+
+
def _tool_response(text: str, *, is_error: bool = False) -> dict[str, Any]:
return {
"content": [{"type": "text", "text": text}],
@@ -157,7 +165,7 @@ def handle_request(message: Any) -> dict[str, Any] | None:
"result": {
"protocolVersion": requested or PROTOCOL_VERSION,
"capabilities": {"tools": {"listChanged": False}},
- "serverInfo": {"name": "mem0", "version": "0.3.0"},
+ "serverInfo": {"name": "mem0", "version": PLUGIN_VERSION},
},
}
if method == "ping":
@@ -187,7 +195,9 @@ def handle_request(message: Any) -> dict[str, Any] | None:
result = _tool_response("Unknown Mem0 tool.", is_error=True)
else:
try:
- result = _tool_response(call_search_memories(params.get("arguments")))
+ result = _tool_response(
+ call_search_memories(params.get("arguments"), _workspace_cwd(params))
+ )
except ToolInputError as exc:
result = _tool_response(str(exc), is_error=True)
except Exception:
diff --git a/integrations/claude-code-plugin/core/memory_cli.py b/integrations/claude-code-plugin/core/memory_cli.py
index eb1b595b9..76d2ee871 100644
--- a/integrations/claude-code-plugin/core/memory_cli.py
+++ b/integrations/claude-code-plugin/core/memory_cli.py
@@ -11,6 +11,7 @@ import telemetry
from memory_core import (
EvidenceStore,
api_key,
+ configure_harness,
data_dir,
doctor,
forget_remote_repo,
@@ -31,7 +32,7 @@ def _print_status(value: dict) -> None:
)
print(
f"Used in this repository: {value['retrievals']} memories returned, "
- f"{value['sidekick_runs']} sidekick runs"
+ f"{value['subagent_runs']} subagent runs"
)
if last:
item_label = ""
@@ -47,19 +48,20 @@ def _print_status(value: dict) -> None:
f"{'succeeded' if last['success'] else 'failed'} "
f"({last['duration_ms']:.1f} ms{item_label})"
)
- sidekick = value.get("last_sidekick") or {}
- if sidekick:
- state = "finished" if sidekick.get("stopped_at") else "started"
+ subagent = value.get("last_subagent") or {}
+ if subagent:
+ state = "finished" if subagent.get("stopped_at") else "started"
print(
- "Last sidekick: "
- f"{state}, received {sidekick['context_chars']} characters of memory, "
- f"agent {sidekick['agent_id']}"
+ "Last subagent: "
+ f"{state}, received {subagent['context_chars']} characters of memory, "
+ f"agent {subagent['agent_id']}"
)
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("--plugin-data-dir", default="")
+ parser.add_argument("--harness", default="")
subparsers = parser.add_subparsers(dest="command", required=True)
status = subparsers.add_parser("status")
@@ -77,6 +79,10 @@ def main() -> int:
forget.add_argument("--include-project-memory", action="store_true")
args = parser.parse_args()
+ if args.harness:
+ source_tag = f"{args.harness.replace('-', '_')}_plugin"
+ configure_harness(args.harness, source_tag=source_tag)
+ telemetry.init(harness=args.harness, source_tag=source_tag.upper())
if args.plugin_data_dir:
os.environ["MEM0_CODE_DATA_DIR"] = args.plugin_data_dir
store = EvidenceStore()
diff --git a/integrations/claude-code-plugin/core/memory_core.py b/integrations/claude-code-plugin/core/memory_core.py
index b9d9267b7..9b420a063 100644
--- a/integrations/claude-code-plugin/core/memory_core.py
+++ b/integrations/claude-code-plugin/core/memory_core.py
@@ -1,16 +1,15 @@
#!/usr/bin/env python3
-"""Save useful coding memories and search them in later Claude Code sessions.
+"""Shared core for Mem0 agent plugins.
-Hooks record small session details locally. When Claude compacts or ends the
-session, Mem0 sends the useful parts of the session to Mem0 so it can create
-memories. Claude can search those memories during later work in the repository.
+Hooks record small session details locally. When the agent compacts or ends the
+session, Mem0 sends the useful parts to the platform so it can create memories.
+The agent can search those memories during later work in the repository.
"""
from __future__ import annotations
import functools
import hashlib
-import html
import json
import math
import os
@@ -20,20 +19,46 @@ import subprocess
import sys
import time
import urllib.error
-import urllib.request
import urllib.parse
+import urllib.request
from dataclasses import dataclass
-from datetime import timezone, datetime
+from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Iterable
import telemetry
-
DEFAULT_API_URL = "https://api.mem0.ai"
-PLUGIN_VERSION = "0.3.0"
-MAX_PROMPT_CHARS = 6000
-MAX_ASSISTANT_CHARS = 6000
+PLUGIN_VERSION = "0.3.3"
+
+_harness_name: str = "generic"
+_harness_env_prefix: str = "MEM0_PLUGIN"
+_harness_data_dir_name: str = "mem0-plugin"
+_harness_source_tag: str = "mem0_plugin"
+
+
+def configure_harness(
+ name: str,
+ env_prefix: str = "",
+ data_dir_name: str = "",
+ source_tag: str = "",
+) -> None:
+ global _harness_name, _harness_env_prefix, _harness_data_dir_name, _harness_source_tag
+ _harness_name = name
+ _harness_env_prefix = env_prefix or f"MEM0_{name.upper().replace('-', '_')}"
+ _harness_data_dir_name = data_dir_name or f"{name}-plugin"
+ _harness_source_tag = source_tag or f"{name.replace('-', '_')}_plugin"
+
+
+def harness_config() -> dict[str, str]:
+ return {
+ "name": _harness_name,
+ "env_prefix": _harness_env_prefix,
+ "data_dir_name": _harness_data_dir_name,
+ "source_tag": _harness_source_tag,
+ }
+
+
MAX_COMMAND_CHARS = 2000
MAX_RESULT_CHARS = 2500
MAX_EPISODE_CHARS = 12000
@@ -46,15 +71,13 @@ MAX_FLUSH_ATTEMPTS = 5
FORGET_PAGE_SIZE = 100
FORGET_MAX_PAGES = 50
-PROJECT_MEMORY_INSTRUCTIONS = """Save concise repository facts that will help anyone with future coding work in this repository.
+PROJECT_MEMORY_INSTRUCTIONS = """Save concise repository facts that will help with future coding work.
A completed change should produce one memory explaining the resulting behavior, where it is implemented when useful, and any important constraints or reasoning. Exploration or accepted decisions may produce separate memories only when they are independently useful.
-A command that failed and was then made to work should produce one memory naming the failing invocation, the error it returned, and the invocation that succeeded. Do not save one-off errors caused by an edit still in progress, transient network failures, or anything a rerun would fix on its own.
+Use the coding agent's final response for conclusions about current repository behavior. Do not save proposed or recommended changes unless the user accepted them or the coding agent completed them. Treat subagent responses as supporting repository evidence, not as decisions.
-Use Claude's final response for conclusions about current repository behavior. Do not save proposed or recommended changes unless the user accepted them or Claude completed them. Treat subagent responses as supporting repository evidence, not as decisions.
-
-Write about the repository, not the user, assistant, session, or task. Do not save personal preferences. Do not save a memory that only states which repository, branch, or directory the session worked in. Do not include test results, documentation updates, release notes, or temporary state.
+Write about the repository, not the user, assistant, session, or task. Do not include test results, documentation updates, release notes, or temporary state.
If nothing useful was established, return no memories."""
@@ -130,6 +153,11 @@ SECRET_PATTERNS = [
r"-----BEGIN [^-]*PRIVATE KEY-----.*?-----END [^-]*PRIVATE KEY-----",
re.DOTALL,
),
+ re.compile(
+ r'(?i)("(?:api[_-]?key|password|secret(?:[_-]?access[_-]?key)?'
+ r'|(?:access|refresh|session)[_-]?token|token|authorization|credential'
+ r')"\s*:\s*")(?:\\.|[^"\\])*'
+ ),
]
@@ -213,13 +241,21 @@ def directory_chain(repo: RepoContext) -> list[str]:
return ["/".join(parts[: index + 1]) for index in range(len(parts))]
+def _shared_project_ids(repo: RepoContext) -> list[str]:
+ """Current and pre-upgrade namespaces, shared by recall and explicit deletion."""
+ if not repo.identity.startswith("local:") and repo.project_id != repo.app_id:
+ return [repo.project_id, repo.app_id]
+ return [repo.project_id]
+
+
def _search_filters(user: str, repo: RepoContext, scope: str) -> dict[str, Any]:
"""Build the scope filter: app_id scopes to the repo, then union shared and personal lanes."""
app_scope = {"app_id": repo.app_id}
mine = {"AND": [{"user_id": user}, app_scope]}
if scope == "mine":
return mine
- shared: dict[str, Any] = {"AND": [{"agent_id": repo.project_id}, app_scope]}
+ projects = [{"AND": [{"agent_id": project_id}, app_scope]} for project_id in _shared_project_ids(repo)]
+ shared: dict[str, Any] = projects[0] if len(projects) == 1 else {"OR": projects}
if scope == "dir" and repo.directory:
shared = {"AND": [shared, {"metadata": {"dirs": {"contains": repo.directory}}}]}
return {"OR": [shared, mine]}
@@ -297,9 +333,9 @@ class RepoContext:
def _project_id(root: str, identity: str, app_id: str) -> str:
- """The shared namespace: the repository, or a folder path hashed so same-named folders stay apart."""
+ """The shared namespace: includes a host hash so repos with the same owner/name on different hosts stay apart."""
if not identity.startswith("local:"):
- return app_id
+ return f"{app_id}-{hashlib.sha256(identity.encode()).hexdigest()[:10]}"
return f"local-{app_id}-{hashlib.sha256(root.encode()).hexdigest()[:10]}"
@@ -345,8 +381,8 @@ def resolve_repo(cwd: str | None) -> RepoContext:
def api_key() -> str:
configured = (
os.environ.get("MEM0_API_KEY")
+ or os.environ.get("PLUGIN_OPTION_API_KEY")
or os.environ.get("CLAUDE_PLUGIN_OPTION_API_KEY")
- # Compatibility with the pre-marketplace development harness.
or os.environ.get("CLAUDE_PLUGIN_OPTION_MEM0_API_KEY")
or ""
).strip()
@@ -359,9 +395,10 @@ def api_key() -> str:
def cache_plugin_api_key() -> bool:
- """Bridge Claude's hook-only sensitive config into plugin-owned storage."""
+ """Bridge host's hook-only sensitive config into plugin-owned storage."""
configured = (
- os.environ.get("CLAUDE_PLUGIN_OPTION_API_KEY")
+ os.environ.get("PLUGIN_OPTION_API_KEY")
+ or os.environ.get("CLAUDE_PLUGIN_OPTION_API_KEY")
or os.environ.get("CLAUDE_PLUGIN_OPTION_MEM0_API_KEY")
or ""
).strip()
@@ -394,6 +431,7 @@ def clear_stale_api_key_cache() -> bool:
"""Drop the cached key file once every configured key source is gone."""
configured = (
os.environ.get("MEM0_API_KEY")
+ or os.environ.get("PLUGIN_OPTION_API_KEY")
or os.environ.get("CLAUDE_PLUGIN_OPTION_API_KEY")
or os.environ.get("CLAUDE_PLUGIN_OPTION_MEM0_API_KEY")
or ""
@@ -411,7 +449,7 @@ def clear_stale_api_key_cache() -> bool:
def detached_process_kwargs(platform: str | None = None) -> dict:
- """Keep a spawned worker alive after Claude Code exits, on POSIX and Windows."""
+ """Keep a spawned worker alive after the coding agent exits, on POSIX and Windows."""
if (platform or sys.platform) == "win32":
return {
"creationflags": subprocess.DETACHED_PROCESS
@@ -422,7 +460,8 @@ def detached_process_kwargs(platform: str | None = None) -> dict:
def _plugin_option(name: str, fallback: str = "") -> str:
return (
- os.environ.get(f"CLAUDE_PLUGIN_OPTION_{name.upper()}")
+ os.environ.get(f"PLUGIN_OPTION_{name.upper()}")
+ or os.environ.get(f"CLAUDE_PLUGIN_OPTION_{name.upper()}")
or os.environ.get(fallback)
or ""
).strip()
@@ -440,11 +479,14 @@ def user_id() -> str:
def data_dir() -> Path:
- configured = os.environ.get("MEM0_CODE_DATA_DIR") or os.environ.get(
- "CLAUDE_PLUGIN_DATA"
+ configured = (
+ os.environ.get("MEM0_CODE_DATA_DIR")
+ or os.environ.get("MEM0_PLUGIN_DATA_DIR")
+ or os.environ.get("PLUGIN_DATA")
+ or os.environ.get("CLAUDE_PLUGIN_DATA")
)
return (
- Path(configured).expanduser() if configured else Path.home() / ".mem0" / "claude-code-plugin"
+ Path(configured).expanduser() if configured else Path.home() / ".mem0" / _harness_data_dir_name
)
@@ -464,316 +506,11 @@ def _int_option(name: str, fallback: str, default: int) -> int:
-def _message_content_text(content: Any) -> str:
- """Return visible text from one Claude transcript message."""
- if isinstance(content, str):
- return redact(content).strip()
- if not isinstance(content, list):
- return ""
- parts = []
- for block in content:
- if not isinstance(block, dict) or block.get("type") != "text":
- continue
- text = redact(block.get("text", "")).strip()
- if text:
- parts.append(text)
- return "\n\n".join(parts)
-
-
-def _transcript_rows(
- path: str, offset: int = 0
-) -> tuple[list[dict[str, Any]], int, bool]:
- """Parse transcript rows from a byte offset, returning rows, end offset, and whether the offset was honored."""
- if not path:
- return [], 0, False
- rows = []
- try:
- resolved = Path(path).expanduser()
- if not 0 <= offset <= resolved.stat().st_size:
- offset = 0
- end = offset
- with resolved.open("rb") as handle:
- handle.seek(offset)
- for line in handle:
- if not line.endswith(b"\n"):
- break
- end += len(line)
- try:
- row = json.loads(line.decode("utf-8", errors="replace"))
- except json.JSONDecodeError:
- continue
- if isinstance(row, dict) and row.get("uuid"):
- rows.append(row)
- except OSError:
- return [], offset, False
- return rows, end, offset > 0
-
-
-def _active_transcript_chain(
- rows: list[dict[str, Any]], session_id: str
-) -> list[dict[str, Any]]:
- """Follow the current Claude conversation branch from its latest record."""
- by_uuid = {str(row["uuid"]): row for row in rows if row.get("uuid")}
- leaf = next(
- (
- row
- for row in reversed(rows)
- if not row.get("isSidechain")
- and str(row.get("sessionId") or "") == session_id
- ),
- None,
- )
- if leaf is None:
- return []
-
- chain = []
- seen = set()
- current = leaf
- while current is not None:
- uuid = str(current.get("uuid") or "")
- if not uuid or uuid in seen:
- break
- seen.add(uuid)
- chain.append(current)
- current = by_uuid.get(str(current.get("parentUuid") or ""))
- chain.reverse()
- return chain
-
-
-def _human_prompt_text(row: dict[str, Any]) -> str:
- if row.get("type") != "user":
- return ""
- origin = row.get("origin") or {}
- if isinstance(origin, dict) and origin.get("kind") not in {None, "human"}:
- return ""
- message = row.get("message") or {}
- content = message.get("content") if isinstance(message, dict) else None
- if not isinstance(content, str):
- return ""
- text = redact(content).strip()
- if text.startswith(""):
- text = text.removeprefix("").strip()
- ignored_prefixes = (
- "",
- "",
- "",
- "",
- "",
- "",
- )
- return "" if text.startswith(ignored_prefixes) else text
-
-
-def _xml_value(text: str, tag: str) -> str:
- match = re.search(fr"<{tag}>(.*?){tag}>", text, re.DOTALL)
- return html.unescape(match.group(1).strip()) if match else ""
-
-
-def _agent_assignment(tool_input: dict[str, Any]) -> str:
- prompt = redact(tool_input.get("prompt", "")).strip()
- if not prompt:
- return ""
- agent_type = redact(tool_input.get("subagent_type", "agent")).strip() or "agent"
- description = redact(tool_input.get("description", "")).strip()
- heading = f"Subagent assignment ({agent_type}"
- if description:
- heading += f": {description}"
- return f"{heading}):\n{prompt}"
-
-
-def _agent_response(tool_input: dict[str, Any], result: str) -> str:
- result = redact(result).strip()
- if not result or result.startswith("Async agent launched successfully."):
- return ""
- agent_type = redact(tool_input.get("subagent_type", "agent")).strip() or "agent"
- description = redact(tool_input.get("description", "")).strip()
- heading = f"Subagent response ({agent_type}"
- if description:
- heading += f": {description}"
- return f"{heading}):\n{result}"
-
-
-def _tool_result_text(block: dict[str, Any]) -> str:
- return _message_content_text(block.get("content"))
-
-
-def transcript_extraction_messages(
- transcript_path: str,
- session_id: str,
- *,
- previous_leaf_uuid: str = "",
- prompt_hint: str = "",
- fallback_assistant_message: str = "",
- label_final_response: bool = False,
- start_offset: int = 0,
-) -> tuple[list[dict[str, str]], str, int]:
- """Read the meaningful part of the current Claude exchange.
-
- The returned messages contain human prompts, visible Claude text, accepted
- plans, answers collected through AskUserQuestion, and completed native
- subagent assignments and responses. Raw tool output and hidden reasoning
- are deliberately excluded.
- """
- rows, end_offset, resumed = _transcript_rows(transcript_path, start_offset)
- chain = _active_transcript_chain(rows, session_id)
- if not chain:
- if resumed:
- return [], previous_leaf_uuid, end_offset
- fallback = redact(fallback_assistant_message).strip()
- return (
- ([{"role": "assistant", "content": f"Main Claude response:\n{fallback}"}]
- if fallback
- else []),
- "",
- end_offset,
- )
-
- leaf_uuid = str(chain[-1].get("uuid") or "")
- if previous_leaf_uuid and leaf_uuid == previous_leaf_uuid:
- return [], leaf_uuid, end_offset
- start = 0
- if previous_leaf_uuid:
- for index, row in enumerate(chain):
- if str(row.get("uuid") or "") == previous_leaf_uuid:
- start = index + 1
- break
- else:
- previous_leaf_uuid = ""
- if not previous_leaf_uuid and not resumed:
- prompt_hint = redact(prompt_hint).strip()
- candidates = [
- index
- for index, row in enumerate(chain)
- if _human_prompt_text(row)
- and (
- not prompt_hint
- or _human_prompt_text(row) == prompt_hint
- )
- ]
- task_notifications = [
- index
- for index, row in enumerate(chain)
- if isinstance((row.get("message") or {}).get("content"), str)
- and (row.get("message") or {})["content"].startswith("")
- ]
- if candidates:
- start = candidates[-1]
- elif task_notifications:
- start = task_notifications[-1]
-
- tool_uses: dict[str, tuple[str, dict[str, Any]]] = {}
- for row in chain:
- message = row.get("message") or {}
- content = message.get("content") if isinstance(message, dict) else None
- if not isinstance(content, list):
- continue
- for block in content:
- if not isinstance(block, dict) or block.get("type") != "tool_use":
- continue
- tool_id = str(block.get("id") or "")
- tool_input = block.get("input") or {}
- if tool_id and isinstance(tool_input, dict):
- tool_uses[tool_id] = (str(block.get("name") or ""), tool_input)
-
- output: list[dict[str, str]] = []
-
- def append(role: str, content: str) -> None:
- content = redact(content).strip()
- if content:
- output.append({"role": role, "content": content})
-
- for row in chain[start:]:
- message = row.get("message") or {}
- if not isinstance(message, dict):
- continue
- role = str(message.get("role") or "")
- content = message.get("content")
-
- if role == "user" and isinstance(content, str):
- if content.startswith(""):
- if _xml_value(content, "status") != "completed":
- continue
- tool_id = _xml_value(content, "tool-use-id")
- tool = tool_uses.get(tool_id)
- result = _xml_value(content, "result")
- if tool and tool[0] == "Agent" and result:
- assignment = _agent_assignment(tool[1])
- response = _agent_response(tool[1], result)
- append("assistant", assignment)
- append("assistant", response)
- continue
- human = _human_prompt_text(row)
- if human:
- append("user", human)
- continue
-
- if not isinstance(content, list):
- continue
- for block in content:
- if not isinstance(block, dict):
- continue
- block_type = block.get("type")
- if role == "assistant" and block_type == "text":
- append("assistant", str(block.get("text") or ""))
- continue
- if role != "user" or block_type != "tool_result":
- continue
-
- tool_id = str(block.get("tool_use_id") or "")
- tool = tool_uses.get(tool_id)
- if not tool:
- continue
- name, tool_input = tool
- result = _tool_result_text(block)
- failed = bool(block.get("is_error"))
- if name == "Agent" and not failed:
- response = _agent_response(tool_input, result)
- if response:
- append("assistant", _agent_assignment(tool_input))
- append("assistant", response)
- elif name == "AskUserQuestion" and result and not failed:
- append("user", f"User answers to Claude's questions:\n{result}")
- elif name == "ExitPlanMode" and not failed:
- plan = redact(tool_input.get("plan", "")).strip()
- if plan:
- append("assistant", f"Approved implementation plan:\n{plan}")
-
- fallback = redact(fallback_assistant_message).strip()
- if fallback:
- labeled = f"Main Claude response:\n{fallback}"
- for message in reversed(output):
- if message["role"] == "assistant" and message["content"] == fallback:
- message["content"] = labeled
- break
- else:
- append("assistant", labeled)
- elif label_final_response:
- last_message = chain[-1].get("message") or {}
- last_content = (
- last_message.get("content") if isinstance(last_message, dict) else None
- )
- final_parts = [
- redact(block.get("text", "")).strip()
- for block in (last_content if isinstance(last_content, list) else [])
- if isinstance(block, dict)
- and block.get("type") == "text"
- and redact(block.get("text", "")).strip()
- ]
- for start in range(len(output) - len(final_parts), -1, -1):
- candidate = output[start : start + len(final_parts)]
- if final_parts and [item["content"] for item in candidate] == final_parts:
- candidate[0]["content"] = (
- f"Main Claude response:\n{candidate[0]['content']}"
- )
- break
- return output, leaf_uuid, end_offset
-
-
def _checkpoint_message(event: dict[str, Any]) -> str:
kind = event.get("kind")
payload = event.get("payload") or {}
if kind == "user_prompt":
- return bounded(payload.get("text", ""), MAX_PROMPT_CHARS)
+ return redact(payload.get("text", "")).strip()
if kind == "assistant_stop":
transcript_messages = payload.get("transcript_messages") or []
if isinstance(transcript_messages, list):
@@ -784,9 +521,9 @@ def _checkpoint_message(event: dict[str, Any]) -> str:
)
if text:
return text
- return bounded(payload.get("text", ""), MAX_ASSISTANT_CHARS)
- if kind == "sidekick_stop":
- return bounded(payload.get("final_message", ""), MAX_ASSISTANT_CHARS)
+ return redact(payload.get("text", "")).strip()
+ if kind in {"subagent_stop", "sidekick_stop"}:
+ return redact(payload.get("final_message", "")).strip()
return ""
@@ -857,6 +594,7 @@ class EvidenceStore:
self.conn.close()
def _migrate(self) -> None:
+ # Keep the legacy table name so existing databases and in-flight workers remain compatible.
self.conn.executescript(
"""
CREATE TABLE IF NOT EXISTS events (
@@ -949,8 +687,7 @@ class EvidenceStore:
"""
)
- # Remove the pre-0.1.1 no-tools snapshot implementation. The real coding
- # sidekick is a native Claude Code agent and stores no state in this DB.
+ # Remove the pre-0.1.1 snapshot implementation.
self.conn.executescript(
"""
DROP TABLE IF EXISTS sidekick_calls;
@@ -998,8 +735,27 @@ class EvidenceStore:
self.conn.commit()
return int(cursor.lastrowid)
+ def record_assistant_response(self, repo: RepoContext, session_id: str, message: str) -> None:
+ """Ignore repeated response hooks until another prompt or a different answer arrives."""
+ with self.conn:
+ # Serialize the check and insert across concurrent Stop and SessionEnd hooks.
+ self.conn.execute("BEGIN IMMEDIATE")
+ previous = self.conn.execute(
+ """SELECT kind, payload_json FROM events
+ WHERE repo_id = ? AND session_id = ? AND kind IN ('user_prompt', 'assistant_stop')
+ ORDER BY id DESC LIMIT 1""",
+ (repo.identity, session_id),
+ ).fetchone()
+ if (
+ previous is not None
+ and previous["kind"] == "assistant_stop"
+ and json.loads(previous["payload_json"]).get("text") == message
+ ):
+ return
+ self.record_event(repo, session_id, "assistant_stop", {"text": message})
+
def repo_for_session(self, session_id: str, cwd: str | None) -> RepoContext:
- """Keep one project scope for every hook in a Claude Code session."""
+ """Keep one project scope for every hook in a coding-agent session."""
current = resolve_repo(cwd)
if session_id == "unknown-session":
return current
@@ -1041,78 +797,77 @@ class EvidenceStore:
def prepare_flush(
self, repo: RepoContext, session_id: str, reason: str
) -> tuple[str, list[dict[str, Any]]] | None:
- existing = self.conn.execute(
- """SELECT * FROM flushes
- WHERE repo_id = ? AND session_id = ?
- AND status NOT IN ('semantic-succeeded', 'explicitly-stored', 'gave-up')
- ORDER BY created_at LIMIT 1""",
- (repo.identity, session_id),
- ).fetchone()
- if existing and int(existing["attempts"] or 0) >= MAX_FLUSH_ATTEMPTS:
- with self.conn:
+ with self.conn:
+ self.conn.execute("BEGIN IMMEDIATE")
+ existing = self.conn.execute(
+ """SELECT * FROM flushes
+ WHERE repo_id = ? AND session_id = ?
+ AND status NOT IN ('semantic-succeeded', 'explicitly-stored', 'gave-up')
+ ORDER BY created_at LIMIT 1""",
+ (repo.identity, session_id),
+ ).fetchone()
+ if existing and int(existing["attempts"] or 0) >= MAX_FLUSH_ATTEMPTS:
self.conn.execute(
"UPDATE flushes SET status = 'gave-up', updated_at = ? WHERE packet_id = ?",
(utc_now(), existing["packet_id"]),
)
- telemetry.record(
- "flush",
- repo=repo,
- session_id=session_id,
- reason=reason,
- status="gave-up",
- success=False,
- attempts=int(existing["attempts"] or 0),
- )
- existing = None
- if existing:
- if reason != "periodic" and existing["reason"] == "periodic":
- with self.conn:
+ telemetry.record(
+ "flush",
+ repo=repo,
+ session_id=session_id,
+ reason=reason,
+ status="gave-up",
+ success=False,
+ attempts=int(existing["attempts"] or 0),
+ )
+ existing = None
+ if existing:
+ if reason != "periodic" and existing["reason"] == "periodic":
self.conn.execute(
"UPDATE flushes SET reason = ?, updated_at = ? WHERE packet_id = ?",
(reason, utc_now(), existing["packet_id"]),
)
- existing_rows = self.conn.execute(
- "SELECT * FROM events WHERE flush_id = ? ORDER BY id",
- (existing["packet_id"],),
+ existing_rows = self.conn.execute(
+ "SELECT * FROM events WHERE flush_id = ? ORDER BY id",
+ (existing["packet_id"],),
+ ).fetchall()
+ if existing_rows:
+ return str(existing["packet_id"]), [
+ {
+ "id": row["id"],
+ "created_at": row["created_at"],
+ "kind": row["kind"],
+ "payload": json.loads(row["payload_json"]),
+ }
+ for row in existing_rows
+ ]
+
+ rows = self.conn.execute(
+ """SELECT * FROM events
+ WHERE repo_id = ? AND session_id = ? AND flush_id IS NULL
+ ORDER BY id""",
+ (repo.identity, session_id),
).fetchall()
- if existing_rows:
- return str(existing["packet_id"]), [
- {
- "id": row["id"],
- "created_at": row["created_at"],
- "kind": row["kind"],
- "payload": json.loads(row["payload_json"]),
- }
- for row in existing_rows
- ]
+ if not rows:
+ return None
- rows = self.conn.execute(
- """SELECT * FROM events
- WHERE repo_id = ? AND session_id = ? AND flush_id IS NULL
- ORDER BY id""",
- (repo.identity, session_id),
- ).fetchall()
- if not rows:
- return None
+ events = [
+ {
+ "id": row["id"],
+ "created_at": row["created_at"],
+ "kind": row["kind"],
+ "payload": json.loads(row["payload_json"]),
+ }
+ for row in rows
+ ]
+ events = select_checkpoint_events(events, force=reason != "periodic")
+ if not events:
+ return None
+ event_start, event_end = events[0]["id"], events[-1]["id"]
+ packet_material = f"{repo.identity}\0{session_id}\0{event_start}\0{event_end}"
+ packet_id = hashlib.sha256(packet_material.encode()).hexdigest()[:32]
+ now = utc_now()
- events = [
- {
- "id": row["id"],
- "created_at": row["created_at"],
- "kind": row["kind"],
- "payload": json.loads(row["payload_json"]),
- }
- for row in rows
- ]
- events = select_checkpoint_events(events, force=reason != "periodic")
- if not events:
- return None
- event_start, event_end = events[0]["id"], events[-1]["id"]
- packet_material = f"{repo.identity}\0{session_id}\0{event_start}\0{event_end}"
- packet_id = hashlib.sha256(packet_material.encode()).hexdigest()[:32]
- now = utc_now()
-
- with self.conn:
self.conn.execute(
"""INSERT OR IGNORE INTO flushes
(packet_id, repo_id, app_id, session_id, reason, event_start,
@@ -1137,7 +892,7 @@ class EvidenceStore:
f"WHERE id IN ({placeholders}) AND flush_id IS NULL",
(packet_id, *event_ids),
)
- return packet_id, events
+ return packet_id, events
def checkpoint_due(self, repo_id: str, session_id: str) -> bool:
if self.has_inflight_flush(repo_id, session_id):
@@ -1284,7 +1039,7 @@ class EvidenceStore:
if row["memory_text"]
]
- def start_sidekick(
+ def start_subagent(
self,
repo: RepoContext,
session_id: str,
@@ -1292,7 +1047,7 @@ class EvidenceStore:
agent_type: str,
context_chars: int,
) -> bool:
- """Record one native sidekick instance and whether context was first sent."""
+ """Record one native subagent instance and whether context was first sent."""
with self.conn:
cursor = self.conn.execute(
"""INSERT OR IGNORE INTO sidekick_runs
@@ -1310,7 +1065,7 @@ class EvidenceStore:
)
return int(cursor.rowcount) > 0
- def stop_sidekick(
+ def stop_subagent(
self,
repo: RepoContext,
session_id: str,
@@ -1318,9 +1073,19 @@ class EvidenceStore:
agent_type: str,
transcript_path: str,
final_message: str,
- ) -> None:
+ ) -> str:
now = utc_now()
- with self.conn:
+ self.conn.execute("BEGIN IMMEDIATE")
+ try:
+ if not agent_id:
+ rows = self.conn.execute(
+ """SELECT agent_id FROM sidekick_runs
+ WHERE repo_id = ? AND session_id = ? AND agent_type = ? AND stopped_at IS NULL
+ LIMIT 2""",
+ (repo.identity, session_id, agent_type),
+ ).fetchall()
+ # Without a host ID, overlapping runs cannot be correlated reliably.
+ agent_id = rows[0]["agent_id"] if len(rows) == 1 else f"unknown-agent-{time.time_ns()}"
self.conn.execute(
"""INSERT INTO sidekick_runs
(repo_id, session_id, agent_id, agent_type, started_at,
@@ -1338,9 +1103,14 @@ class EvidenceStore:
now,
now,
bounded(transcript_path, 2000),
- bounded(final_message, MAX_ASSISTANT_CHARS),
+ redact(final_message).strip(),
),
)
+ self.conn.commit()
+ except Exception:
+ self.conn.rollback()
+ raise
+ return agent_id
def operation(
self,
@@ -1450,7 +1220,7 @@ class EvidenceStore:
cursor = self.conn.execute(
f"DELETE FROM {table} WHERE {column} = ?", (repo_id,)
)
- removed[table] = max(int(cursor.rowcount), 0)
+ removed["subagent_runs" if table == "sidekick_runs" else table] = max(int(cursor.rowcount), 0)
return removed
def status(self, repo_id: str) -> dict[str, Any]:
@@ -1466,7 +1236,7 @@ class EvidenceStore:
FROM operations WHERE repo_id = ? ORDER BY id DESC LIMIT 1""",
(repo_id,),
).fetchone()
- last_sidekick = self.conn.execute(
+ last_subagent = self.conn.execute(
"""SELECT session_id, agent_id, agent_type, started_at, stopped_at,
context_chars
FROM sidekick_runs WHERE repo_id = ?
@@ -1478,9 +1248,9 @@ class EvidenceStore:
"events": count("events"),
"flushes": count("flushes"),
"retrievals": count("retrievals"),
- "sidekick_runs": count("sidekick_runs"),
+ "subagent_runs": count("sidekick_runs"),
"last_operation": dict(last_operation) if last_operation else None,
- "last_sidekick": dict(last_sidekick) if last_sidekick else None,
+ "last_subagent": dict(last_subagent) if last_subagent else None,
}
@@ -1518,7 +1288,7 @@ def record_user_prompt(
) -> tuple[RepoContext, str, str, bool]:
session_id = _session_id(hook_input)
repo = store.repo_for_session(session_id, hook_input.get("cwd"))
- prompt = bounded(hook_input.get("prompt", ""), MAX_PROMPT_CHARS)
+ prompt = redact(hook_input.get("prompt", "")).strip()
is_first_prompt = not store.has_event(repo.identity, session_id, "user_prompt")
store.record_event(repo, session_id, "user_prompt", {"text": prompt})
return repo, session_id, prompt, is_first_prompt
@@ -1543,7 +1313,7 @@ def _tool_result_preview(response: Any) -> str:
return bounded(response, MAX_RESULT_CHARS)
-def tool_payload(hook_input: dict[str, Any], *, failed: bool = False) -> dict[str, Any]:
+def tool_payload(hook_input: dict[str, Any], *, failed: bool | None = False) -> dict[str, Any]:
name = str(hook_input.get("tool_name") or "unknown")
tool_input = hook_input.get("tool_input") or {}
if not isinstance(tool_input, dict):
@@ -1552,7 +1322,7 @@ def tool_payload(hook_input: dict[str, Any], *, failed: bool = False) -> dict[st
"tool": name,
"failed": failed,
"duration_ms": hook_input.get("duration_ms"),
- "agent_role": "sidekick" if hook_input.get("agent_id") else "main",
+ "agent_role": "subagent" if hook_input.get("agent_id") else "main",
}
if hook_input.get("agent_id"):
payload["agent_id"] = bounded(hook_input["agent_id"], 200)
@@ -1597,7 +1367,7 @@ def tool_payload(hook_input: dict[str, Any], *, failed: bool = False) -> dict[st
def record_tool(
- store: EvidenceStore, hook_input: dict[str, Any], *, failed: bool = False
+ store: EvidenceStore, hook_input: dict[str, Any], *, failed: bool | None = False
) -> None:
session_id = _session_id(hook_input)
repo = store.repo_for_session(session_id, hook_input.get("cwd"))
@@ -1612,76 +1382,33 @@ def record_tool(
)
-def record_stop(
- store: EvidenceStore, hook_input: dict[str, Any]
-) -> tuple[RepoContext, str]:
- session_id = _session_id(hook_input)
- repo = store.repo_for_session(session_id, hook_input.get("cwd"))
- message = bounded(hook_input.get("last_assistant_message", ""), MAX_ASSISTANT_CHARS)
- previous_stop = store.latest_event_payload(
- repo.identity, session_id, "assistant_stop"
- )
- latest_prompt = store.latest_event_payload(repo.identity, session_id, "user_prompt")
- transcript_path = str(hook_input.get("transcript_path") or "")
- previous_offset = previous_stop.get("transcript_offset")
- start_offset = (
- previous_offset
- if isinstance(previous_offset, int)
- and str(previous_stop.get("transcript_path") or "") == transcript_path
- else 0
- )
- transcript_messages, leaf_uuid, end_offset = transcript_extraction_messages(
- transcript_path,
- session_id,
- previous_leaf_uuid=str(previous_stop.get("transcript_leaf_uuid") or ""),
- prompt_hint=str(latest_prompt.get("text") or ""),
- fallback_assistant_message=message,
- label_final_response=True,
- start_offset=start_offset,
- )
- if transcript_messages:
- payload: dict[str, Any] = {
- "text": message,
- "transcript_messages": transcript_messages,
- }
- if leaf_uuid:
- payload["transcript_leaf_uuid"] = leaf_uuid
- if transcript_path:
- payload["transcript_path"] = transcript_path
- payload["transcript_offset"] = end_offset
- store.record_event(
- repo, session_id, "assistant_stop", payload
- )
- return repo, session_id
-
-
-def record_sidekick_start(
+def record_subagent_start(
store: EvidenceStore, hook_input: dict[str, Any]
) -> str:
- """Record a native sidekick and reuse the main turn's retrieved memories."""
+ """Record a native subagent and reuse the main turn's retrieved memories."""
session_id = _session_id(hook_input)
repo = store.repo_for_session(session_id, hook_input.get("cwd"))
agent_id = bounded(hook_input.get("agent_id", "unknown-agent"), 200)
- agent_type = bounded(hook_input.get("agent_type", "mem0:sidekick"), 200)
+ agent_type = bounded(hook_input.get("agent_type", "unknown-agent"), 200)
context = combine_context(
format_context(store.injected_memories(session_id, repo.identity))
)
- first_start = store.start_sidekick(
+ first_start = store.start_subagent(
repo, session_id, agent_id, agent_type, len(context)
)
store.record_event(
repo,
session_id,
- "sidekick_start",
+ "subagent_start",
{
"agent_id": agent_id,
"agent_type": agent_type,
"context_chars": len(context) if first_start else 0,
- "worktree_root": bounded(repo.root, 2000),
+ "repo_root": bounded(repo.root, 2000),
},
)
telemetry.record(
- "sidekick",
+ "subagent",
repo=repo,
session_id=session_id,
phase="start",
@@ -1691,16 +1418,14 @@ def record_sidekick_start(
return context if first_start else ""
-def record_sidekick_stop(store: EvidenceStore, hook_input: dict[str, Any]) -> None:
+def record_subagent_stop(store: EvidenceStore, hook_input: dict[str, Any]) -> None:
session_id = _session_id(hook_input)
repo = store.repo_for_session(session_id, hook_input.get("cwd"))
- agent_id = bounded(hook_input.get("agent_id", "unknown-agent"), 200)
- agent_type = bounded(hook_input.get("agent_type", "mem0:sidekick"), 200)
- final_message = bounded(
- hook_input.get("last_assistant_message", ""), MAX_ASSISTANT_CHARS
- )
+ agent_type = bounded(hook_input.get("agent_type", "unknown-agent"), 200)
+ agent_id = bounded(hook_input.get("agent_id", ""), 200)
+ final_message = redact(hook_input.get("last_assistant_message", "")).strip()
transcript_path = bounded(hook_input.get("agent_transcript_path", ""), 2000)
- store.stop_sidekick(
+ agent_id = store.stop_subagent(
repo,
session_id,
agent_id,
@@ -1711,7 +1436,7 @@ def record_sidekick_stop(store: EvidenceStore, hook_input: dict[str, Any]) -> No
store.record_event(
repo,
session_id,
- "sidekick_stop",
+ "subagent_stop",
{
"agent_id": agent_id,
"agent_type": agent_type,
@@ -1720,7 +1445,7 @@ def record_sidekick_stop(store: EvidenceStore, hook_input: dict[str, Any]) -> No
},
)
telemetry.record(
- "sidekick",
+ "subagent",
repo=repo,
session_id=session_id,
phase="stop",
@@ -1775,19 +1500,19 @@ def build_episode(
task_outcome: str = "",
) -> tuple[str, dict[str, Any]]:
prompts = [
- bounded(e["payload"].get("text", ""), MAX_PROMPT_CHARS)
+ redact(e["payload"].get("text", "")).strip()
for e in events
if e["kind"] == "user_prompt" and e["payload"].get("text")
]
assistant_conclusions = [
- bounded(e["payload"].get("text", ""), MAX_ASSISTANT_CHARS)
+ redact(e["payload"].get("text", "")).strip()
for e in events
if e["kind"] == "assistant_stop" and e["payload"].get("text")
]
- sidekick_outcomes = [
- bounded(e["payload"].get("final_message", ""), MAX_ASSISTANT_CHARS)
+ subagent_outcomes = [
+ redact(e["payload"].get("final_message", "")).strip()
for e in events
- if e["kind"] == "sidekick_stop" and e["payload"].get("final_message")
+ if e["kind"] in {"subagent_stop", "sidekick_stop"} and e["payload"].get("final_message")
]
tools = [
e["payload"] for e in events if e["kind"] in {"tool_result", "tool_failure"}
@@ -1812,7 +1537,7 @@ def build_episode(
{
"command": t.get("command", ""),
"kind": t.get("command_kind", "shell"),
- "status": "failed" if t.get("failed") else "succeeded",
+ "status": "unknown" if t.get("failed", False) is None else "failed" if t.get("failed") else "succeeded",
"result": t.get("result_preview", ""),
}
for t in tools
@@ -1820,10 +1545,7 @@ def build_episode(
]
task = bounded(canonical_task or (prompts[0] if prompts else ""), 4000)
- conclusion = bounded(
- assistant_conclusions[-1] if assistant_conclusions else "",
- MAX_ASSISTANT_CHARS,
- )
+ conclusion = redact(assistant_conclusions[-1] if assistant_conclusions else "").strip()
outcome = bounded(task_outcome, 2000)
extraction_messages: list[dict[str, str]] = []
@@ -1835,16 +1557,14 @@ def build_episode(
pending_user_messages.append(
{
"role": "user",
- "content": bounded(
- event["payload"].get("text", ""), MAX_PROMPT_CHARS
- ),
+ "content": redact(event["payload"].get("text", "")).strip(),
}
)
elif event["kind"] == "assistant_stop":
transcript_messages = event["payload"].get("transcript_messages") or []
if isinstance(transcript_messages, list) and transcript_messages:
transcript_users = {
- str(message.get("content") or "").strip()
+ redact(message.get("content") or "").strip()
for message in transcript_messages
if isinstance(message, dict) and message.get("role") == "user"
}
@@ -1856,7 +1576,7 @@ def build_episode(
extraction_messages.extend(
{
"role": str(message.get("role") or ""),
- "content": str(message.get("content") or ""),
+ "content": redact(message.get("content") or "").strip(),
}
for message in transcript_messages
if isinstance(message, dict)
@@ -1869,14 +1589,11 @@ def build_episode(
extraction_messages.append(
{
"role": "assistant",
- "content": bounded(
- event["payload"].get("text", ""),
- MAX_ASSISTANT_CHARS,
- ),
+ "content": redact(event["payload"].get("text", "")).strip(),
}
)
pending_user_messages = []
- elif event["kind"] == "sidekick_stop":
+ elif event["kind"] in {"subagent_stop", "sidekick_stop"}:
pass
extraction_messages.extend(pending_user_messages)
@@ -1892,7 +1609,7 @@ def build_episode(
"assistant_conclusion": conclusion,
"user_messages": prompts,
"assistant_outcomes": assistant_conclusions,
- "sidekick_outcomes": sidekick_outcomes,
+ "subagent_outcomes": subagent_outcomes,
"extraction_messages": extraction_messages,
"files_read": read_paths[:50],
"files_modified": modified_paths[:50],
@@ -1972,7 +1689,7 @@ def build_extraction_messages(structured: dict[str, Any]) -> list[dict[str, str]
"""Build the session messages sent to Mem0 for memory extraction."""
evidence = build_semantic_evidence(structured)
messages = [
- {"role": message["role"], "content": message["content"]}
+ {"role": message["role"], "content": redact(message["content"]).strip()}
for message in structured.get("extraction_messages", [])
if message.get("role") in {"user", "assistant"} and message.get("content")
]
@@ -2014,7 +1731,7 @@ def extraction_message_batches(
*,
max_tokens: int = MAX_EXTRACTION_INPUT_TOKENS,
) -> list[list[dict[str, str]]]:
- """Split large extraction input without cutting messages or agent pairs."""
+ """Keep exchanges together when possible; split oversized messages to enforce the request budget."""
if not messages or _message_tokens(messages) <= max_tokens:
return [messages]
@@ -2047,9 +1764,29 @@ def extraction_message_batches(
units.append([message])
index += 1
+ bounded_units: list[list[dict[str, str]]] = []
+ for unit in units:
+ if _message_tokens(unit) <= max_tokens:
+ bounded_units.append(unit)
+ continue
+ for message in unit:
+ remaining = message["content"]
+ while remaining:
+ low, high = 0, len(remaining)
+ while low < high:
+ middle = (low + high + 1) // 2
+ if _message_tokens([{**message, "content": remaining[:middle]}]) <= max_tokens:
+ low = middle
+ else:
+ high = middle - 1
+ if low == 0:
+ raise ValueError("Extraction token budget cannot fit a message")
+ bounded_units.append([{**message, "content": remaining[:low]}])
+ remaining = remaining[low:]
+
batches: list[list[dict[str, str]]] = []
batch: list[dict[str, str]] = []
- for unit in units:
+ for unit in bounded_units:
candidate = [*batch, *unit]
if batch and _message_tokens(candidate) > max_tokens:
batches.append(batch)
@@ -2061,6 +1798,34 @@ def extraction_message_batches(
return batches
+# Platform surface attribution. Read from the generated per-host module so a new
+# entrypoint is correct without remembering to configure anything.
+try: # pragma: no cover - absent only in the un-built shared source tree
+ from _harness_id import PLATFORM_APPLICATION as _PLATFORM_APPLICATION
+ from _harness_id import PLATFORM_SOURCE as _PLATFORM_SOURCE
+except ImportError:
+ _PLATFORM_SOURCE = "MEM0_PLUGIN"
+ _PLATFORM_APPLICATION = ""
+
+
+def platform_headers(key: str) -> dict[str, str]:
+ """Auth plus the three surface-identity headers.
+
+ X-Mem0-Source and X-Application are set-once by contract: this is the
+ outermost layer, so it sets them, and nothing below may overwrite them.
+ X-Mem0-Client is append-only โ anything downstream adds itself to the tail.
+ """
+ headers = {
+ "Authorization": f"Token {key}",
+ "Content-Type": "application/json",
+ "X-Mem0-Source": _PLATFORM_SOURCE,
+ "X-Mem0-Client": f"mem0-plugin/{PLUGIN_VERSION}",
+ }
+ if _PLATFORM_APPLICATION:
+ headers["X-Application"] = _PLATFORM_APPLICATION
+ return headers
+
+
def _request_json(
url: str, key: str, payload: dict[str, Any], timeout: float
) -> tuple[dict[str, Any] | list[Any], int, int]:
@@ -2068,7 +1833,7 @@ def _request_json(
request = urllib.request.Request(
url,
data=raw,
- headers={"Authorization": f"Token {key}", "Content-Type": "application/json"},
+ headers=platform_headers(key),
method="POST",
)
with urllib.request.urlopen(request, timeout=timeout) as response:
@@ -2095,7 +1860,7 @@ def _get_json(
) -> tuple[dict[str, Any] | list[Any], int]:
request = urllib.request.Request(
url,
- headers={"Authorization": f"Token {key}", "Content-Type": "application/json"},
+ headers=platform_headers(key),
method="GET",
)
with urllib.request.urlopen(request, timeout=timeout) as response:
@@ -2152,6 +1917,11 @@ def _wait_for_event(api_url: str, key: str, event_id: str) -> tuple[str, int, in
key,
min(10, poll_seconds + 5),
)
+ except urllib.error.HTTPError as exc:
+ if exc.code not in {408, 429} and exc.code < 500:
+ raise
+ time.sleep(poll_seconds)
+ continue
except (urllib.error.URLError, TimeoutError, OSError):
# The extraction job is durable server-side. A transient polling
# failure must not discard a job that may still complete normally.
@@ -2217,7 +1987,7 @@ def flush_session(
task_outcome=bounded(hook_input.get("task_outcome", ""), 2000),
)
- metadata = {"source": "claude_code_plugin"}
+ metadata = {"source": _harness_source_tag}
if repo.branch and repo.branch not in {"detached", "unknown"}:
metadata["branch"] = repo.branch
if repo.head_sha:
@@ -2236,6 +2006,13 @@ def flush_session(
"user_id": write_user,
"app_id": repo.app_id,
"run_id": session_id,
+ # Top level, not metadata: the backend reads `source` from the body or
+ # the query string, never from metadata, which is where this used to
+ # sit. The X-Mem0-Source header is also read, but only from the
+ # platform release that ships alongside this change, so the body value
+ # is what makes attribution work on both. The harness tag stays in
+ # metadata as hook provenance.
+ "source": _PLATFORM_SOURCE,
"metadata": {**metadata, "author": write_user, "dirs": directory_chain(repo)},
"agent_custom_instructions": PROJECT_MEMORY_INSTRUCTIONS,
"custom_instructions": PERSONAL_MEMORY_INSTRUCTIONS,
@@ -2684,7 +2461,7 @@ def format_context(
def format_search_result(result: MemorySearchResult) -> str:
- """Return only the text Claude needs from an explicit memory search."""
+ """Return only the text the coding agent needs from an explicit memory search."""
if not result.succeeded:
return "Memory search failed."
if result.memories:
@@ -2731,7 +2508,11 @@ def _scoped_memory_ids(
app_id_prefix=prefix,
)
if include_project:
- _collect_memory_ids(api_url, key, {"agent_id": repo.project_id}, ids, seen)
+ for project_id in _shared_project_ids(repo):
+ _collect_memory_ids(
+ api_url, key, {"agent_id": project_id}, ids, seen,
+ app_id_prefix=prefix,
+ )
return ids
@@ -2775,7 +2556,7 @@ def _collect_memory_ids(
def _delete_memory(api_url: str, key: str, memory_id: str) -> bool:
request = urllib.request.Request(
f"{api_url}/v1/memories/{urllib.parse.quote(memory_id)}/",
- headers={"Authorization": f"Token {key}", "Content-Type": "application/json"},
+ headers=platform_headers(key),
method="DELETE",
)
try:
diff --git a/integrations/claude-code-plugin/core/telemetry.py b/integrations/claude-code-plugin/core/telemetry.py
index 2b704a339..c1fc0084c 100644
--- a/integrations/claude-code-plugin/core/telemetry.py
+++ b/integrations/claude-code-plugin/core/telemetry.py
@@ -1,5 +1,9 @@
#!/usr/bin/env python3
-"""Anonymous usage telemetry for the Mem0 Claude Code plugin.
+"""Usage telemetry for Mem0 agent plugins.
+
+Events are linked to your Mem0 account email when an API key is configured, and
+to a random per-machine id otherwise. Not anonymous โ the Python SDK and CLI
+attribute the same way.
Hooks run on a 3-6 second budget and fire on every tool call, so recording never
touches the network: `record` appends one JSON line to a local spool and returns.
@@ -9,7 +13,8 @@ started once per session and again from the flush worker that is already detache
Pure stdlib, matching the rest of the plugin. Opt out with MEM0_TELEMETRY=false.
Never sends prompts, memory text, queries, file paths, repository names, or API
-keys: only event names, durations, counts, coarse outcomes, and salted hashes.
+keys: only event names, durations, counts, coarse outcomes, and repo/session
+identifiers hashed with a random per-install salt.
"""
from __future__ import annotations
@@ -29,6 +34,63 @@ from typing import Any
import memory_core
+# Seeded from the per-host module the build generates into core/. Two processes
+# in this pipeline never call init() โ mcp_server.py, and the detached
+# `python3 telemetry.py` sender that spawn_flush() starts โ so a module default
+# was what every one of their events got labelled with.
+try: # pragma: no cover - absent only in the un-built shared source tree
+ from _harness_id import HARNESS_ID as _DEFAULT_HARNESS
+ from _harness_id import PLATFORM_APPLICATION as _PLATFORM_APPLICATION
+ from _harness_id import PLATFORM_SOURCE as _PLATFORM_SOURCE
+ from _harness_id import SOURCE_TAG as _DEFAULT_SOURCE_TAG
+except ImportError:
+ _DEFAULT_HARNESS = "generic"
+ _DEFAULT_SOURCE_TAG = "MEM0_PLUGIN"
+ _PLATFORM_SOURCE = "MEM0_PLUGIN"
+ _PLATFORM_APPLICATION = ""
+
+_salt_cache: str = ""
+_harness: str = _DEFAULT_HARNESS
+_source_tag: str = _DEFAULT_SOURCE_TAG
+_PRIVATE_KEYS = {
+ "apikey",
+ "authorization",
+ "password",
+ "query",
+ "secret",
+ "prompt",
+ "token",
+ "text",
+ "memory",
+ "message",
+ "error",
+ "path",
+ "cwd",
+ "userid",
+ "agentid",
+ "runid",
+ "repoid",
+ "repositoryid",
+ "projectid",
+ "appid",
+ "filters",
+}
+
+
+def init(harness: str = "", source_tag: str = "") -> None:
+ """Override the generated identity. Optional โ core/_harness_id.py is the default.
+
+ The fallback shape matches memory_core.configure_harness's (``_PLUGIN``).
+ It used to be ``MEM0__PLUGIN`` here and ``_plugin`` there, which
+ meant one plugin could emit three different source values depending on which
+ process happened to send the batch.
+ """
+ global _harness, _source_tag
+ _harness = harness or _DEFAULT_HARNESS
+ _source_tag = source_tag or (
+ f"{_harness.upper().replace('-', '_')}_PLUGIN" if harness else _DEFAULT_SOURCE_TAG
+ )
+
POSTHOG_API_KEY = "phc_hgJkUVJFYtmaJqrvf6CYN67TIQ8yhXAkWzUn9AMU4yX"
POSTHOG_CAPTURE_URL = "https://us.i.posthog.com/i/v0/e/"
POSTHOG_BATCH_URL = "https://us.i.posthog.com/batch/"
@@ -38,6 +100,16 @@ BATCH_SIZE = 100
SEND_TIMEOUT = 5
CLAIM_STALE_SECONDS = 120
CLAIM_EXPIRY_SECONDS = 7 * 24 * 60 * 60
+# A batch is only discarded once it has genuinely been retried this many times.
+MAX_CLAIM_ATTEMPTS = 3
+# Parked claims drained per run, after the live spool. Bounded so a long backlog
+# cannot turn one flush into an unbounded send loop.
+MAX_PARKED_PER_RUN = 3
+# Added to the wait before a released claim becomes reclaimable, per attempt
+# already spent. Releasing straight to "reclaimable now" let two senders burn the
+# whole budget within seconds of one another on a single momentary failure, and
+# discard a batch a retry a minute later would have delivered.
+RETRY_COOLDOWN_SECONDS = 60
def is_enabled() -> bool:
@@ -51,9 +123,143 @@ def is_enabled() -> bool:
def _digest(value: str, length: int = 16) -> str:
+ """Unsalted digest. Only for values that are already secrets (API keys)."""
return hashlib.sha256(value.encode("utf-8")).hexdigest()[:length]
+def _salt_path() -> Path:
+ return memory_core.data_dir() / "telemetry-salt"
+
+
+def _install_salt() -> str:
+ """Random per-install salt, created once and memoized for the process.
+
+ Deliberately its own file, claimed with O_CREAT|O_EXCL, rather than a key in
+ the identity file. Three reasons, all of which produced wrong data when this
+ lived in the identity dict:
+
+ - Hooks are short-lived separate processes firing on every tool call, and
+ people run more than one agent window. A read-modify-write would let each
+ process mint its own salt, so one repository would hash several ways in the
+ window before a writer won.
+ - resolve_distinct_id holds a copy of the identity dict across a network call
+ to /v1/ping/, so whichever write landed second erased the other's key โ
+ losing either the salt (repo_hash changes mid-stream) or the email (a
+ second $identify, splitting the person).
+ - Touching the identity file from record() would create it, and is_first_run
+ keys off that file, so recording an event would silently suppress the
+ install event.
+
+ Published atomically, and there is deliberately no derived fallback. Creating
+ the file with O_CREAT|O_EXCL and then writing into it leaves a window where
+ the file exists and is empty, and a concurrent hook that reads it in that
+ window gets nothing. Falling back to a digest of the path would hand that
+ process a salt an attacker can compute, memoized for its whole run, which is
+ the privacy control this function exists to provide silently turning itself
+ off under load. The salt is written to a private temp file first and linked
+ into place, so the name either does not exist or already has the full value.
+
+ Returns "" when it genuinely cannot persist. Callers omit the hash entirely
+ rather than emit an unsalted one.
+ """
+ global _salt_cache
+ if _salt_cache:
+ return _salt_cache
+
+ path = _salt_path()
+ # Read before writing. Hooks are separate processes firing on every tool
+ # call, so all but the first find the salt already published; going straight
+ # to create-fsync-link-unlink meant every one of them paid an fsync to
+ # discover that, on a path whose whole promise is appending a line and
+ # returning.
+ try:
+ _salt_cache = path.read_text(encoding="utf-8").strip()
+ if _salt_cache:
+ return _salt_cache
+ except OSError:
+ pass
+
+ temporary = path.with_name(f"{path.name}.{os.getpid()}.tmp")
+ try:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ handle = os.open(temporary, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
+ with os.fdopen(handle, "w", encoding="utf-8") as stream:
+ stream.write(uuid.uuid4().hex)
+ stream.flush()
+ os.fsync(stream.fileno())
+ try:
+ # Atomic claim: fails if another process already published one.
+ # os.link rather than replace, which would clobber theirs.
+ os.link(temporary, path)
+ except FileExistsError:
+ pass
+ except OSError:
+ # No hardlinks here (some network mounts, some container volumes).
+ # Claim the name directly instead. That reopens the empty-file
+ # window, but the window is now benign: a reader that lands in it
+ # gets "" and omits the hash for that process rather than caching a
+ # guessable one. Losing the hashes on every run of an entire
+ # filesystem is the worse failure.
+ try:
+ fallback = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
+ with os.fdopen(fallback, "w", encoding="utf-8") as stream:
+ stream.write(temporary.read_text(encoding="utf-8"))
+ except OSError:
+ pass
+ except OSError:
+ pass
+ finally:
+ try:
+ temporary.unlink()
+ except OSError:
+ pass
+
+ try:
+ _salt_cache = path.read_text(encoding="utf-8").strip()
+ except OSError:
+ _salt_cache = ""
+ return _salt_cache
+
+
+def _scoped_digest(value: str, length: int = 16) -> str:
+ """Salted digest for values drawn from a guessable space.
+
+ repo.identity is a git remote URL, or ``local:`` when there is
+ no remote โ which normally contains the account username. Sixteen unsalted
+ hex characters over that input space is enumerable, so this is not a
+ privacy control without the salt. Salting per install keeps every
+ within-account join the analytics actually use and gives up only
+ cross-machine joins on the same repository, which nothing computes.
+
+ Returns "" when there is no salt, so record() omits the property. An
+ unsalted digest over this input space is close to plaintext, and emitting one
+ under a name that implies it is hashed is worse than sending nothing.
+ """
+ if not value:
+ return ""
+ salt = _install_salt()
+ if not salt:
+ return ""
+ return hashlib.sha256(f"{salt}:{value}".encode("utf-8")).hexdigest()[:length]
+
+
+def _safe_value(value: Any) -> Any:
+ if isinstance(value, str):
+ return memory_core.redact(value)
+ if isinstance(value, dict):
+ return {
+ key: _safe_value(item)
+ for key, item in value.items()
+ if "".join(character for character in str(key).lower() if character.isalnum())
+ not in _PRIVATE_KEYS
+ }
+ if isinstance(value, (list, tuple)):
+ return [_safe_value(item) for item in value]
+ if value is None or isinstance(value, (bool, int, float)):
+ return value
+ return memory_core.redact(value)
+
+
def _spool_path() -> Path:
return memory_core.data_dir() / "telemetry.jsonl"
@@ -96,9 +302,176 @@ def anonymous_id(identity: dict[str, str] | None = None) -> str:
return created
+def _rotate_anonymous_id(identity: dict[str, str]) -> str:
+ """Mint a fresh anonymous id because the account context is gone.
+
+ The previous id may already have been merged into a person profile by an
+ $identify, and that merge is permanent. Reusing it after a logout or a key
+ change attributes everything that follows to the account that just went
+ away, which is the same misattribution the key fingerprint exists to stop,
+ only arriving through the anonymous path instead.
+
+ `aliased` is cleared with it: the new id has never been merged, so it is
+ eligible to be aliased into whatever account comes next.
+ """
+ created = f"code-anon-{uuid.uuid4().hex}"
+ identity["anonymous_id"] = created
+ identity.pop("aliased", None)
+ _write_identity(identity)
+ return created
+
+
+def _install_state_path() -> Path:
+ return memory_core.data_dir() / "install-state.json"
+
+
def is_first_run() -> bool:
- """Whether this machine has never recorded a plugin event before."""
- return not _identity_path().exists()
+ """Whether install has never been recorded on this machine.
+
+ Deliberately NOT the identity file. That file is only written by a
+ successful flush, so an offline or firewalled user recorded code.install on
+ every single session, forever โ and every 0.2.x user recorded one on their
+ first 0.3.x session because 0.2.x never wrote it at all.
+ """
+ return not _install_state_path().exists()
+
+
+def data_dir_was_empty() -> bool:
+ """Whether the data directory is untouched. Call BEFORE anything writes to it.
+
+ hook_runner reaches claim_install() only after cache_plugin_api_key() has
+ written `api-key` and EvidenceStore() has created `evidence.sqlite3`, so
+ asking at claim time always saw content and every fresh install reported an
+ upgrade. The caller snapshots this at the top of the run instead.
+ """
+ return not _data_dir_has_content()
+
+
+def claim_install(was_empty: bool | None = None) -> str | None:
+ """Claim the one install/upgrade record for this machine, atomically.
+
+ Returns the event to record ("install" or "upgrade"), or None if another
+ session already claimed it. O_CREAT|O_EXCL so two sessions starting together
+ cannot both win.
+
+ `was_empty` must come from data_dir_was_empty() called before this process
+ wrote anything. Omitting it falls back to checking now, which is only
+ correct for a caller that has touched nothing.
+ """
+ if not is_enabled():
+ # Never consume the one-shot claim while the user is opted out, or they
+ # would silently lose their install event if they later opt in.
+ return None
+
+ path = _install_state_path()
+ upgrading = not (data_dir_was_empty() if was_empty is None else was_empty)
+ try:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ handle = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
+ except FileExistsError:
+ return None
+ except OSError:
+ return None
+ try:
+ with os.fdopen(handle, "w", encoding="utf-8") as stream:
+ json.dump(
+ {
+ "plugin_version": memory_core.PLUGIN_VERSION,
+ "installed_at": memory_core.utc_now(),
+ "upgraded": upgrading,
+ },
+ stream,
+ )
+ # Durable before this returns. The O_EXCL open is what makes the
+ # claim exclusive, so it cannot be replaced by a temp-and-rename
+ # without losing that, which leaves the content as the thing to make
+ # safe. A kill between the open and this fsync used to leave a marker
+ # that exists but parses to nothing: is_first_run reads it as claimed
+ # and claim_version_change cannot read a version out of it.
+ stream.flush()
+ os.fsync(stream.fileno())
+ except OSError:
+ pass
+ return "upgrade" if upgrading else "install"
+
+
+def _data_dir_has_content() -> bool:
+ """Whether anything predates this session in the plugin data directory."""
+ try:
+ for entry in memory_core.data_dir().iterdir():
+ if entry.name != "install-state.json":
+ return True
+ except OSError:
+ pass
+ return False
+
+
+def _repair_install_state(path: Path) -> None:
+ """Rewrite an unparseable marker so version tracking can resume."""
+ try:
+ temporary = path.with_suffix(f".{os.getpid()}.tmp")
+ temporary.write_text(
+ json.dumps({"plugin_version": memory_core.PLUGIN_VERSION, "repaired_at": memory_core.utc_now()}),
+ encoding="utf-8",
+ )
+ temporary.replace(path)
+ except OSError:
+ pass
+
+
+def claim_version_change() -> str | None:
+ """Return the previously recorded version if it differs, updating the marker.
+
+ Only meaningful once the marker exists โ the first transition into 0.3.x has
+ no recorded predecessor and reports "pre-0.3" instead. Claiming by rewriting
+ the marker means the next session sees no change and records nothing.
+ """
+ path = _install_state_path()
+ try:
+ state = json.loads(path.read_text(encoding="utf-8"))
+ except OSError:
+ return None
+ except json.JSONDecodeError:
+ # A crash between O_EXCL and the write leaves an empty marker. Left
+ # alone it disables every future upgrade event on this machine, because
+ # claim_install sees the file and this function cannot parse it.
+ state = None
+ if not isinstance(state, dict):
+ _repair_install_state(path)
+ return None
+ previous = str(state.get("plugin_version") or "")
+ if not previous or previous == memory_core.PLUGIN_VERSION:
+ return None
+ # Claim the transition with an exclusive sentinel before rewriting the
+ # marker. A plain read-modify-write let every concurrently starting session
+ # observe the old version and each record its own upgrade โ and the first
+ # session after a version bump is exactly when several agent windows restart
+ # together.
+ sentinel = path.with_name(f"upgraded-{memory_core.PLUGIN_VERSION}")
+ try:
+ os.close(os.open(sentinel, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600))
+ except FileExistsError:
+ return None
+ except OSError:
+ return None
+
+ state["plugin_version"] = memory_core.PLUGIN_VERSION
+ state["upgraded_at"] = memory_core.utc_now()
+ temporary = path.with_suffix(f".{os.getpid()}.tmp")
+ try:
+ temporary.write_text(json.dumps(state), encoding="utf-8")
+ temporary.replace(path)
+ except OSError:
+ # Release the claim. The marker still records the old version, so
+ # without this the sentinel makes claim_version_change return early on
+ # every later run and this version's upgrade is never recorded again.
+ for leftover in (sentinel, temporary):
+ try:
+ leftover.unlink()
+ except OSError:
+ pass
+ return None
+ return previous
def record(
@@ -118,19 +491,33 @@ def record(
return
except OSError:
pass
+ properties = _safe_value(properties)
+ # Stamped in the RECORDING process, beside harness. `source` used to be
+ # read in the sending process from a module global, so whichever process
+ # drained the spool named every event in it. flush() spreads per-event
+ # properties last, so this now wins over any sender's default.
properties.update(
- harness="claude-code",
+ harness=_harness,
+ source=_source_tag,
plugin_version=memory_core.PLUGIN_VERSION,
os=sys.platform,
python_version=platform.python_version(),
)
+ # Assigned only when the digest is real. _scoped_digest returns "" when
+ # the salt could not be persisted, and an empty property is worse than an
+ # absent one: it survives the None filter below and reads as a value.
if repo is not None:
- properties["repo_hash"] = _digest(getattr(repo, "identity", ""))
+ repo_hash = _scoped_digest(getattr(repo, "identity", ""))
+ if repo_hash:
+ properties["repo_hash"] = repo_hash
if session_id:
- properties["session_hash"] = _digest(session_id)
+ session_hash = _scoped_digest(session_id)
+ if session_hash:
+ properties["session_hash"] = session_hash
line = json.dumps(
{
"event": f"{EVENT_PREFIX}.{event}",
+ "uuid": str(uuid.uuid4()),
"timestamp": memory_core.utc_now(),
"properties": {
key: value for key, value in properties.items() if value is not None
@@ -189,38 +576,201 @@ def spawn_flush() -> bool:
return False
+def _claim_name(attempt: int = 0) -> str:
+ """Claim filename. The attempt count rides in the name so the 7-day expiry
+ only ever discards a batch that was actually retried and failed."""
+ return f"telemetry-{os.getpid()}-{uuid.uuid4().hex[:8]}-a{attempt}.sending"
+
+
+def _claim_attempt(claim: Path) -> int:
+ """Attempts recorded in a claim filename; 0 for the pre-attempt-count shape.
+
+ Anchored on field position, not on a leading "a": the legacy shape is
+ ``telemetry--.sending`` and a hex id such as ``a1234567`` would
+ otherwise parse as attempt 1234567 and be discarded unsent on the first
+ flush after an upgrade.
+ """
+ stem = claim.name[: -len(".sending")] if claim.name.endswith(".sending") else claim.name
+ parts = stem.split("-")
+ if len(parts) != 4:
+ return 0
+ tail = parts[3]
+ if tail.startswith("a") and tail[1:].isdigit():
+ return int(tail[1:])
+ return 0
+
+
+def _touch(path: Path) -> None:
+ """Refresh mtime so a claim's age measures time since it was claimed.
+
+ ``Path.replace`` is ``os.rename``, which preserves mtime โ so a claim created
+ after a quiet minute inherited the spool's last-write time and looked
+ abandoned the instant it was made. A second sender would then take it over
+ while the first was still posting, and both would deliver the batch.
+ """
+ try:
+ os.utime(path, None)
+ except OSError:
+ pass
+
+
def _claim_spool() -> Path | None:
"""Rename the spool aside so exactly one sender owns each batch."""
directory = memory_core.data_dir()
- claim = directory / f"telemetry-{os.getpid()}-{uuid.uuid4().hex[:8]}.sending"
+ claim = directory / _claim_name()
spool = _spool_path()
try:
spool.replace(claim)
+ _touch(claim)
return claim
except OSError:
pass
+ return _claim_parked(directory)
+
+
+def _sweep_debris(directory: Path) -> None:
+ """Remove files nothing else will ever pick up again.
+
+ *.partial is a temp file orphaned by a crash between write and rename.
+ *.corrupt is a batch quarantined for undecodable content. No glob in this
+ module matches either, so without this they accumulate on disk for the life
+ of the install.
+
+ Quarantined batches are kept far longer than debris: they are the only
+ evidence left of events that could not be delivered, and someone diagnosing
+ a report of missing telemetry has to be able to find one.
+ """
now = time.time()
- for orphan in sorted(directory.glob("telemetry-*.sending")):
+ for debris in directory.glob("telemetry-*.partial"):
+ try:
+ if now - debris.stat().st_mtime > CLAIM_STALE_SECONDS:
+ debris.unlink()
+ except OSError:
+ continue
+ for quarantined in directory.glob("telemetry-*.corrupt"):
+ try:
+ if now - quarantined.stat().st_mtime > CLAIM_EXPIRY_SECONDS:
+ quarantined.unlink()
+ except OSError:
+ continue
+ # The same reasoning covers *.tmp. _write_identity and _install_salt both
+ # create one and unlink it in a finally, which a SIGKILL skips, and no glob
+ # in this module matches the leftovers either.
+ for temporary in directory.glob("telemetry-*.tmp"):
+ try:
+ if now - temporary.stat().st_mtime > CLAIM_STALE_SECONDS:
+ temporary.unlink()
+ except OSError:
+ continue
+
+
+def _claim_parked(directory: Path) -> Path | None:
+ """Take the oldest abandoned claim, if any lease has actually expired.
+
+ Kept separate from the live spool so flush() can drain both in one run.
+ Previously parked batches were only reachable when no spool existed at all,
+ and because sessions keep recording there usually was one โ so a batch
+ parked by a failed send waited until the 7-day expiry deleted it unsent,
+ even though its own presence is what started the sender.
+ """
+ now = time.time()
+ for orphan in sorted(directory.glob("telemetry-*.sending"), key=_safe_mtime):
try:
age = now - orphan.stat().st_mtime
except OSError:
continue
- if age > CLAIM_EXPIRY_SECONDS:
+ if age < CLAIM_STALE_SECONDS:
+ # Someone else holds a live lease on it. This check has to come
+ # first. Claiming a file bumps its attempt count and refreshes its
+ # mtime, so a sender that has just taken the final attempt looks
+ # exhausted to everyone else while it is actively draining. Judging
+ # exhaustion before liveness let a second sender unlink a batch out
+ # from under its owner, losing every event in it.
+ continue
+ # Attempts, not age. Every re-claim touches the mtime and every release
+ # backdates it by a fixed amount, so age is pinned near the stale
+ # threshold and never reaches the expiry. Age stays only as a backstop
+ # for files that never carried an attempt marker.
+ if _claim_attempt(orphan) >= MAX_CLAIM_ATTEMPTS or age > CLAIM_EXPIRY_SECONDS:
try:
orphan.unlink()
except OSError:
pass
continue
- if age < CLAIM_STALE_SECONDS:
- continue
+ claim = orphan.parent / _claim_name(_claim_attempt(orphan) + 1)
try:
orphan.replace(claim)
+ _touch(claim)
return claim
except OSError:
continue
return None
+def _safe_mtime(path: Path) -> float:
+ try:
+ return path.stat().st_mtime
+ except OSError:
+ return 0.0
+
+
+def _rewrite_claim(claim: Path, remaining: list[dict[str, Any]]) -> bool:
+ """Persist the unsent remainder, atomically, and refresh the lease.
+
+ Called after every successful batch. Two jobs: a retry resumes where the
+ send stopped instead of re-posting from the top, and the rewrite doubles as
+ the lease heartbeat, so a slow sender does not have its claim stolen
+ mid-flight. Interval is one batch, well inside CLAIM_STALE_SECONDS.
+ """
+ if not remaining:
+ try:
+ claim.unlink()
+ except OSError:
+ pass
+ return True
+ temporary = claim.with_suffix(f".{os.getpid()}.partial")
+ try:
+ payload = "".join(json.dumps(event, separators=(",", ":"), default=str) + "\n" for event in remaining)
+ # fsync before the rename: without it the rename can land while the
+ # bytes have not, and the claim comes back empty or truncated after a
+ # crash. _drain then reads zero events and unlinks it.
+ with open(temporary, "w", encoding="utf-8") as handle:
+ handle.write(payload)
+ handle.flush()
+ os.fsync(handle.fileno())
+ temporary.replace(claim)
+ _touch(claim)
+ return True
+ except OSError:
+ try:
+ temporary.unlink()
+ except OSError:
+ pass
+ return False
+
+
+def _release_claim(claim: Path, remaining: list[dict[str, Any]]) -> None:
+ """Persist the remainder and drop the lease, because this sender has given up.
+
+ Distinct from the per-batch heartbeat: heartbeating on the way out would
+ make an abandoned batch look actively owned for a further
+ CLAIM_STALE_SECONDS, delaying the retry for no reason. Ageing it past the
+ threshold lets the next flush pick it up immediately, while the attempt
+ count in the filename still bounds how many times that can happen.
+ """
+ if not _rewrite_claim(claim, remaining):
+ return
+ try:
+ # Backdate past the stale threshold so the next flush can pick it up,
+ # minus a cooldown that grows with the attempts already spent. Clamped so
+ # the mtime never lands in the future, which would read as a live lease.
+ cooldown = min(_claim_attempt(claim) * RETRY_COOLDOWN_SECONDS, CLAIM_STALE_SECONDS)
+ released = time.time() - CLAIM_STALE_SECONDS - 1 + cooldown
+ os.utime(claim, (released, released))
+ except OSError:
+ pass
+
+
def _resolve_email(key: str) -> str:
"""Trade the API key for the account email so events join other Mem0 surfaces."""
url = os.environ.get("MEM0_API_URL", memory_core.DEFAULT_API_URL).rstrip("/") + "/v1/ping/"
@@ -250,34 +800,130 @@ def _post(payload: dict[str, Any], url: str) -> bool:
def resolve_distinct_id() -> tuple[str, str]:
- """Return the PostHog distinct id and the anonymous id it replaced, if any."""
+ """Return the PostHog distinct id and the anonymous id it replaced, if any.
+
+ The second value becomes a PostHog $identify alias. It is ONLY ever an
+ anonymous id: aliasing one account email to another merges two real person
+ profiles and cannot be undone, so a key that now belongs to a different
+ account re-resolves with no alias.
+ """
identity = _read_identity()
- email = identity.get("email", "")
- if email:
- return email, ""
key = memory_core.api_key()
+ fingerprint = _digest(key) if key else ""
+ email = identity.get("email", "")
+
+ if email and fingerprint:
+ recorded = identity.get("key_fingerprint", "")
+ if recorded == fingerprint:
+ return email, ""
+ if not recorded:
+ # Rows written before fingerprints existed. Verify rather than
+ # adopt: a key changed before the upgrade would otherwise bind the
+ # new key to the previous account's email, permanently, and the
+ # fingerprint would then agree with itself forever after.
+ verified = _resolve_email(key)
+ if not verified:
+ # Offline, firewalled, or the API is down. Keep the previous
+ # behaviour and retry on the next flush rather than dropping a
+ # real account attribution. Safe because the same network that
+ # failed /v1/ping/ is about to fail the PostHog POST, so nothing
+ # is delivered under the unverified identity in the meantime.
+ return email, ""
+ identity["email"] = verified
+ identity["key_fingerprint"] = fingerprint
+ _write_identity(identity)
+ return verified, ""
+
if not key:
+ # No key to verify the account with; do not keep attributing to it.
+ if email:
+ identity.pop("email", None)
+ identity.pop("key_fingerprint", None)
+ return _rotate_anonymous_id(identity), ""
return anonymous_id(identity), ""
- email = _resolve_email(key)
- if not email:
+
+ resolved = _resolve_email(key)
+ if not resolved:
+ # The key changed and will not resolve (revoked, offline, API down).
+ # Reaching here with an email means the recorded fingerprint disagreed,
+ # so the key really did change. Drop the account and rotate: the stored
+ # anonymous id may already be merged into that account's person, and
+ # reusing it would keep the events on the profile we are trying to
+ # leave.
+ if email:
+ identity.pop("email", None)
+ identity.pop("key_fingerprint", None)
+ return _rotate_anonymous_id(identity), ""
return anonymous_id(identity), ""
- previous = identity.get("anonymous_id", "")
- identity["email"] = email
+
+ # Alias only when going anonymous -> email for the first time. Once an anon
+ # id has been merged into an account it must never be offered again: an
+ # alias naming an already-identified id is what could link two real people.
+ previous = "" if (email or identity.get("aliased")) else identity.get("anonymous_id", "")
+ if previous:
+ identity["aliased"] = True
+ identity["email"] = resolved
+ identity["key_fingerprint"] = fingerprint
_write_identity(identity)
- return email, previous
+ return resolved, previous
def flush() -> int:
- """Drain claimed spools to PostHog and return the number of events sent."""
+ """Drain the live spool, then any parked claims, and return events sent."""
if not is_enabled():
return 0
- claim = _claim_spool()
+ sent, delivered = _drain(_claim_spool())
+ if not delivered:
+ # The network is failing. Retrying other batches now would only burn
+ # their attempt budget against the same broken connection.
+ return sent
+
+ # Parked batches used to starve behind the live spool indefinitely. Bounded
+ # per run so a long backlog cannot turn one flush into an unbounded loop.
+ directory = memory_core.data_dir()
+ _sweep_debris(directory)
+ for _ in range(MAX_PARKED_PER_RUN):
+ parked = _claim_parked(directory)
+ if parked is None:
+ break
+ count, delivered = _drain(parked)
+ sent += count
+ if not delivered:
+ break
+ return sent
+
+
+def _drain(claim: Path | None) -> tuple[int, bool]:
+ """Post one claimed batch file, recording progress after every batch.
+
+ Returns (events sent, whether everything was delivered).
+ """
if claim is None:
- return 0
+ return 0, True
try:
lines = claim.read_text(encoding="utf-8").splitlines()
+ except ValueError:
+ # UnicodeDecodeError from a torn write: the content is unrecoverable, so
+ # quarantine rather than retry. flush() runs from a bare `finally:` in
+ # flush_worker, so raising here also skips the handoff cleanup, and an
+ # undecodable file would otherwise be re-read on every flush forever.
+ # Reported as delivered because there is nothing left to deliver and the
+ # rest of the run should continue.
+ try:
+ claim.replace(claim.with_suffix(".corrupt"))
+ except OSError:
+ try:
+ claim.unlink()
+ except OSError:
+ pass
+ return 0, True
except OSError:
- return 0
+ # Could not read it, which is not the same as having nothing to send.
+ # The file is left exactly where it is: a vanished or briefly unreadable
+ # claim is retryable, and quarantining it here would discard events over
+ # a transient filesystem error. Reported as undelivered so the run stops
+ # instead of counting a batch nothing was posted from as delivered.
+ return 0, False
events = []
for line in lines:
try:
@@ -287,11 +933,18 @@ def flush() -> int:
if isinstance(value, dict) and value.get("event"):
events.append(value)
if not events:
+ # Only delete when the file really is empty. A non-empty file that
+ # parses to nothing is a torn write, and its contents are the unsent
+ # remainder โ deleting it is the data loss this PR exists to prevent.
try:
- claim.unlink()
+ empty = claim.stat().st_size == 0
+ except OSError:
+ empty = True
+ try:
+ claim.replace(claim.with_suffix(".corrupt")) if not empty else claim.unlink()
except OSError:
pass
- return 0
+ return 0, True
distinct_id, aliased_anonymous_id = resolve_distinct_id()
if aliased_anonymous_id:
@@ -310,29 +963,42 @@ def flush() -> int:
sent = 0
for start in range(0, len(events), BATCH_SIZE):
+ chunk = events[start : start + BATCH_SIZE]
batch = [
{
"event": event["event"],
"distinct_id": distinct_id,
+ # Carried through from record() so a resend can be collapsed.
+ "uuid": event.get("uuid"),
"timestamp": event.get("timestamp"),
"properties": {
- "source": "CLAUDE_CODE_PLUGIN",
+ # Fallback only: events recorded by a build before source
+ # moved into record() have none of their own.
+ "source": _source_tag,
"language": "python",
"$process_person_profile": False,
"$lib": "posthog-python",
**(event.get("properties") or {}),
},
}
- for event in events[start : start + BATCH_SIZE]
+ for event in chunk
]
if not _post({"api_key": POSTHOG_API_KEY, "batch": batch}, POSTHOG_BATCH_URL):
- return sent
- sent += len(batch)
- try:
- claim.unlink()
- except OSError:
- pass
- return sent
+ # Keep only what has not been delivered, and release the lease.
+ # Previously the whole file was kept and the retry re-posted every
+ # batch, including the ones that had already arrived.
+ _release_claim(claim, events[start:])
+ return sent, False
+ sent += len(chunk)
+ # Record progress and refresh the lease after each successful batch, so
+ # a crash repeats at most one batch instead of the entire file. If the
+ # rewrite fails the claim still holds delivered events, so stop rather
+ # than carry on as though progress were recorded โ continuing is how the
+ # duplicate delivery this PR fixes would come back.
+ if not _rewrite_claim(claim, events[start + len(chunk) :]):
+ _release_claim(claim, events[start + len(chunk) :])
+ return sent, False
+ return sent, True
def main() -> int:
diff --git a/integrations/claude-code-plugin/plugin-build.json b/integrations/claude-code-plugin/plugin-build.json
new file mode 100644
index 000000000..d62d653c3
--- /dev/null
+++ b/integrations/claude-code-plugin/plugin-build.json
@@ -0,0 +1,17 @@
+{
+ "id": "mem0",
+ "version": "0.3.3",
+ "homepage": "https://docs.mem0.ai/integrations/claude-code",
+ "native": {
+ "pluginRoot": "${CLAUDE_PLUGIN_ROOT}",
+ "pluginData": "${CLAUDE_PLUGIN_DATA}",
+ "files": {
+ ".claude-plugin/plugin.json": ".claude-plugin/plugin.json",
+ ".mcp.json": ".mcp.json",
+ "hooks/hooks.json": "hooks/hooks.json",
+ "adapters/claude/hook.py": "adapters/claude/hook.py",
+ "adapters/claude/transcript.py": "adapters/claude/transcript.py",
+ "agents/sidekick.md": "agents/sidekick.md"
+ }
+ }
+}
diff --git a/integrations/claude-code-plugin/skills/forget/SKILL.md b/integrations/claude-code-plugin/skills/forget/SKILL.md
index c61219cc6..7cf25a38e 100644
--- a/integrations/claude-code-plugin/skills/forget/SKILL.md
+++ b/integrations/claude-code-plugin/skills/forget/SKILL.md
@@ -14,7 +14,7 @@ so it stays unless the user explicitly asks to delete that too.
After the user confirms, run:
```bash
-python3 "${CLAUDE_PLUGIN_ROOT}/core/memory_cli.py" forget --remote --yes
+python3 "${CLAUDE_PLUGIN_ROOT}/core/memory_cli.py" --harness "claude-code" --plugin-data-dir "${CLAUDE_PLUGIN_DATA}" forget --remote --yes
```
If the user also asked to delete the repository's shared project memory, add
diff --git a/integrations/claude-code-plugin/skills/pause/SKILL.md b/integrations/claude-code-plugin/skills/pause/SKILL.md
index 6492ccc43..ce69d13d2 100644
--- a/integrations/claude-code-plugin/skills/pause/SKILL.md
+++ b/integrations/claude-code-plugin/skills/pause/SKILL.md
@@ -7,11 +7,11 @@ disable-model-invocation: true
# Pause memory capture
To pause (hooks stop capturing and sending session content; a minimal
-anonymous telemetry ping still fires at session start unless
-`MEM0_TELEMETRY=false`):
+telemetry ping still fires at session start, under your Mem0 account email,
+unless `MEM0_TELEMETRY=false`):
```bash
-python3 "${CLAUDE_PLUGIN_ROOT}/core/memory_cli.py" pause
+python3 "${CLAUDE_PLUGIN_ROOT}/core/memory_cli.py" --harness "claude-code" --plugin-data-dir "${CLAUDE_PLUGIN_DATA}" pause
```
Confirm the new state back to the user, and remind them that already-created
diff --git a/integrations/claude-code-plugin/skills/resume/SKILL.md b/integrations/claude-code-plugin/skills/resume/SKILL.md
index f4877fc9f..61082fb42 100644
--- a/integrations/claude-code-plugin/skills/resume/SKILL.md
+++ b/integrations/claude-code-plugin/skills/resume/SKILL.md
@@ -11,7 +11,7 @@ Resume memory capture for this machine.
Run:
```bash
-python3 "${CLAUDE_PLUGIN_ROOT}/core/memory_cli.py" resume
+python3 "${CLAUDE_PLUGIN_ROOT}/core/memory_cli.py" --harness "claude-code" --plugin-data-dir "${CLAUDE_PLUGIN_DATA}" resume
```
Confirm to the user that capture is active again. New sessions record evidence and
diff --git a/integrations/claude-code-plugin/skills/search/SKILL.md b/integrations/claude-code-plugin/skills/search/SKILL.md
index ad5c958bb..f7289b91d 100644
--- a/integrations/claude-code-plugin/skills/search/SKILL.md
+++ b/integrations/claude-code-plugin/skills/search/SKILL.md
@@ -12,15 +12,15 @@ Call `search_memories` with the user's question. Treat `--top-k`, `--category`,
query.
Omit `top_k` to use Mem0's configured default. Omit `category` to search every
-category; a category is a best-effort label Mem0 assigned when it saved the
-memory, so if a category search misses, repeat it without the category. Omit
-`scope` to use the configured default, normally `repo`: this repository's
-shared memory, which everyone who works in it contributes to, plus your own
-preferences.
+category. Omit `scope` to use the configured default, normally `repo`: this
+repository's shared memory, which everyone who works in it contributes to,
+plus your own preferences.
Pass `scope` when the question needs something else: `dir` to narrow the
shared memory to the directory you are working in (a package inside a
-monorepo), `mine` for your own preferences alone. Pass `run_id` with a Claude
-Code session ID to look at what one earlier session recorded, for example to
-pick up where a compacted or closed session left off. Return the tool's result
-directly.
+monorepo), `mine` for your own preferences alone.
+
+Pass `run_id` with any scope to retrieve memories saved in a specific coding-agent
+session. Omit `run_id` to search across sessions. It filters the memories returned;
+it does not identify the session making the search request. Use a known session ID,
+never invent one. Return the tool's result directly.
diff --git a/integrations/claude-code-plugin/skills/status/SKILL.md b/integrations/claude-code-plugin/skills/status/SKILL.md
index ef572549c..ed5e49b3f 100644
--- a/integrations/claude-code-plugin/skills/status/SKILL.md
+++ b/integrations/claude-code-plugin/skills/status/SKILL.md
@@ -9,8 +9,8 @@ disable-model-invocation: false
Run both commands and report the combined result in plain language:
```bash
-python3 "${CLAUDE_PLUGIN_ROOT}/core/memory_cli.py" status --json
-python3 "${CLAUDE_PLUGIN_ROOT}/core/memory_cli.py" doctor
+python3 "${CLAUDE_PLUGIN_ROOT}/core/memory_cli.py" --harness "claude-code" --plugin-data-dir "${CLAUDE_PLUGIN_DATA}" status --json
+python3 "${CLAUDE_PLUGIN_ROOT}/core/memory_cli.py" --harness "claude-code" --plugin-data-dir "${CLAUDE_PLUGIN_DATA}" doctor
```
Summarize, using only fields the JSON actually reports: whether capture is
diff --git a/integrations/claude-code-plugin/tests/conftest.py b/integrations/claude-code-plugin/tests/conftest.py
index 85245a5ee..a5b795951 100644
--- a/integrations/claude-code-plugin/tests/conftest.py
+++ b/integrations/claude-code-plugin/tests/conftest.py
@@ -1,7 +1,20 @@
-"""Keep the test suite from sending usage telemetry to the live PostHog project."""
+"""Configure harness identity and disable live telemetry for the test suite."""
from __future__ import annotations
import os
+import sys
+from pathlib import Path
os.environ["MEM0_TELEMETRY"] = "false"
+
+HOST_ROOT = Path(__file__).resolve().parents[1]
+_core = HOST_ROOT / "core"
+sys.path.insert(0, str(_core))
+
+import hook_runner # noqa: E402,F401
+from memory_core import configure_harness # noqa: E402
+import telemetry # noqa: E402
+
+configure_harness("claude-code", data_dir_name="claude-code-plugin", source_tag="claude_code_plugin")
+telemetry.init(harness="claude-code", source_tag="CLAUDE_CODE_PLUGIN")
diff --git a/integrations/claude-code-plugin/tests/integration/test_live_scoping.py b/integrations/claude-code-plugin/tests/integration/test_live_scoping.py
index da223f5c8..90542868f 100644
--- a/integrations/claude-code-plugin/tests/integration/test_live_scoping.py
+++ b/integrations/claude-code-plugin/tests/integration/test_live_scoping.py
@@ -13,10 +13,11 @@ from pathlib import Path
import pytest
PLUGIN_ROOT = Path(__file__).resolve().parents[2]
-sys.path.insert(0, str(PLUGIN_ROOT / "core"))
-sys.path.insert(0, str(PLUGIN_ROOT / "adapters" / "claude"))
+_core_dir = PLUGIN_ROOT / "core"
+sys.path.insert(0, str(_core_dir))
+sys.path.insert(0, str(PLUGIN_ROOT))
-import hook # noqa: E402
+import hook_runner # noqa: E402
import memory_core # noqa: E402
pytestmark = pytest.mark.skipif(
@@ -177,15 +178,17 @@ def test_shared_project_memory_reaches_a_teammate_who_never_wrote(ns):
def test_repo_scope_spans_every_subdirectory(ns):
found = ns.search("erin", ns.root, "how many times are Stripe webhooks retried", scope="repo")
assert "stripe" in _text(found)
- app_ids = {m.get("app_id") for m in found}
- assert any(app.endswith("/services/billing") for app in app_ids)
+ assert any("services/billing" in (memory.get("metadata") or {}).get("dirs", []) for memory in found)
def test_dir_scope_narrows_shared_memory_to_the_directory(ns):
billing = ns.root / "services" / "billing"
found = ns.search("erin", billing, "how do I run the tests here", scope="dir")
assert "billing-test" in _text(found)
- assert {m.get("app_id") for m in found if m.get("agent_id")} == {memory_core.directory_app_id(memory_core.resolve_repo(str(billing)))}
+ shared = [memory for memory in found if memory.get("agent_id")]
+ assert shared
+ assert {memory.get("app_id") for memory in shared} == {memory_core.resolve_repo(str(billing)).app_id}
+ assert all("services/billing" in (memory.get("metadata") or {}).get("dirs", []) for memory in shared)
web = ns.root / "apps" / "web"
elsewhere = ns.search("erin", web, "Stripe webhook retries exponential backoff", scope="dir", tries=1)
@@ -232,7 +235,7 @@ def test_a_pending_packet_is_recovered_and_delivered_by_the_worker(ns):
stale.write_text(json.dumps({"hook_input": {"session_id": sid, "cwd": str(ns.root)}, "reason": "session-end"}))
os.utime(stale, (time.time() - 3600, time.time() - 3600))
- assert hook.recover_pending_handoffs() == 1
+ assert hook_runner.recover_pending_handoffs() == 1
deadline = time.time() + 240
while time.time() < deadline and list(pending.iterdir()):
time.sleep(3)
diff --git a/integrations/claude-code-plugin/tests/test_claude_build.py b/integrations/claude-code-plugin/tests/test_claude_build.py
new file mode 100644
index 000000000..46ccfb206
--- /dev/null
+++ b/integrations/claude-code-plugin/tests/test_claude_build.py
@@ -0,0 +1,35 @@
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+
+HOST = Path(__file__).resolve().parents[1]
+CORE_ROOT = HOST.parent / "agent-plugin-core"
+sys.path.insert(0, str(CORE_ROOT))
+
+from build.build import SHARED_SKILLS, build, render_template # noqa: E402
+
+
+def test_native_claude_bundle_preserves_working_contract(tmp_path: Path) -> None:
+ root = build("claude-code", "native", tmp_path / "claude-code")
+
+ assert (root / ".claude-plugin" / "plugin.json").read_bytes() == (
+ HOST / ".claude-plugin" / "plugin.json"
+ ).read_bytes()
+ assert (root / ".mcp.json").read_bytes() == (HOST / ".mcp.json").read_bytes()
+ assert (root / "hooks" / "hooks.json").read_bytes() == (HOST / "hooks" / "hooks.json").read_bytes()
+ assert (root / "agents" / "sidekick.md").read_bytes() == (HOST / "agents" / "sidekick.md").read_bytes()
+ values = {
+ "PLUGIN_ROOT": "${CLAUDE_PLUGIN_ROOT}",
+ "PLUGIN_DATA": "${PLUGIN_DATA}",
+ "PLUGIN_DATA_ARG": '--plugin-data-dir "${CLAUDE_PLUGIN_DATA}"',
+ "COMMAND_PREFIX": "mem0",
+ "HARNESS_ID": "claude-code",
+ "HARNESS_NAME": "Claude Code",
+ }
+ for skill in SHARED_SKILLS.glob("*/SKILL.md.tmpl"):
+ rendered = render_template(skill.read_text(encoding="utf-8"), values)
+ assert (root / "skills" / skill.parent.name / "SKILL.md").read_text(encoding="utf-8") == rendered
+ assert (root / "adapters" / "claude" / "hook.py").is_file()
+ assert (root / "core" / "mcp_server.py").is_file()
+ assert not any(path.is_symlink() for path in root.rglob("*"))
diff --git a/integrations/claude-code-plugin/tests/test_memory_core.py b/integrations/claude-code-plugin/tests/test_memory_core.py
index 23bf72f8a..b6b1c28f9 100644
--- a/integrations/claude-code-plugin/tests/test_memory_core.py
+++ b/integrations/claude-code-plugin/tests/test_memory_core.py
@@ -2,6 +2,7 @@ from __future__ import annotations
import json
import os
+import re
import sqlite3
import subprocess
import sys
@@ -11,16 +12,18 @@ from unittest.mock import patch
import pytest
-
-PLUGIN_ROOT = Path(__file__).resolve().parents[1]
-CORE = PLUGIN_ROOT / "core"
-ADAPTER = PLUGIN_ROOT / "adapters" / "claude"
+HOST_ROOT = Path(__file__).resolve().parents[1]
+REPOSITORY_ROOT = HOST_ROOT.parents[1]
+PLUGIN_ROOT = HOST_ROOT
+CORE = HOST_ROOT / "core"
+ADAPTER = HOST_ROOT / "adapters" / "claude" / "hook.py"
sys.path.insert(0, str(CORE))
-sys.path.insert(0, str(ADAPTER))
+sys.path.insert(0, str(ADAPTER.parent))
-import memory_core # noqa: E402
-import memory_cli # noqa: E402
import mcp_server # noqa: E402
+import memory_cli # noqa: E402
+import memory_core # noqa: E402
+import transcript as transcript_mod # noqa: E402
@pytest.fixture
@@ -54,6 +57,14 @@ def repo() -> memory_core.RepoContext:
)
+def test_portable_plugin_uses_standard_data_directory(tmp_path, monkeypatch):
+ monkeypatch.delenv("MEM0_CODE_DATA_DIR", raising=False)
+ monkeypatch.delenv("CLAUDE_PLUGIN_DATA", raising=False)
+ monkeypatch.setenv("PLUGIN_DATA", str(tmp_path))
+
+ assert memory_core.data_dir() == tmp_path
+
+
def _write_transcript(path: Path, session_id: str, entries: list[dict]) -> None:
parent = None
rows = []
@@ -235,7 +246,7 @@ def test_transcript_extraction_keeps_meaningful_messages_and_excludes_raw_tools(
],
)
- messages, leaf, _ = memory_core.transcript_extraction_messages(
+ messages, leaf, _ = transcript_mod.transcript_extraction_messages(
str(transcript), "s1"
)
serialized = json.dumps(messages)
@@ -335,7 +346,7 @@ def test_transcript_extraction_pairs_background_agent_notification(tmp_path):
],
)
- messages, _, _ = memory_core.transcript_extraction_messages(
+ messages, _, _ = transcript_mod.transcript_extraction_messages(
str(transcript), "s1", previous_leaf_uuid="launch-result"
)
serialized = json.dumps(messages)
@@ -388,7 +399,7 @@ def test_transcript_extraction_omits_claude_ui_messages_but_keeps_attachments(
],
)
- messages, _, _ = memory_core.transcript_extraction_messages(
+ messages, _, _ = transcript_mod.transcript_extraction_messages(
str(transcript), "s1", prompt_hint="The attached issue says repository scope is wrong."
)
serialized = json.dumps(messages)
@@ -487,7 +498,7 @@ def test_transcript_extraction_uses_active_branch_and_omits_rejected_plan(tmp_pa
"".join(json.dumps(row) + "\n" for row in rows), encoding="utf-8"
)
- messages, leaf, _ = memory_core.transcript_extraction_messages(
+ messages, leaf, _ = transcript_mod.transcript_extraction_messages(
str(transcript), "s1"
)
serialized = json.dumps(messages)
@@ -525,7 +536,7 @@ def test_record_stop_processes_only_new_transcript_entries(
store,
{"session_id": "s1", "cwd": "/tmp/repo", "prompt": "Inspect the parser."},
)
- memory_core.record_stop(
+ transcript_mod.record_stop(
store,
{
"session_id": "s1",
@@ -562,7 +573,7 @@ def test_record_stop_processes_only_new_transcript_entries(
"prompt": "Where is that implemented?",
},
)
- memory_core.record_stop(
+ transcript_mod.record_stop(
store,
{
"session_id": "s1",
@@ -591,7 +602,7 @@ def test_record_stop_processes_only_new_transcript_entries(
]
-def test_extraction_messages_keep_long_content():
+def test_extraction_messages_preserve_long_content():
long_response = "repository detail " * 4000
structured = {
"extraction_messages": [
@@ -605,10 +616,47 @@ def test_extraction_messages_keep_long_content():
assert messages == [
{"role": "user", "content": "Explain the repository."},
- {"role": "assistant", "content": long_response},
+ {"role": "assistant", "content": long_response.strip()},
]
+@pytest.mark.parametrize("capture", ["hook", "transcript"])
+def test_long_conversation_reaches_extraction_without_truncation(isolated_env, monkeypatch, capture):
+ import hook_runner
+
+ monkeypatch.setenv("MEM0_API_KEY", "test-key")
+ monkeypatch.setattr(memory_core, "resolve_repo", lambda cwd: repo())
+ prompt = "Repository question. " * 2000 + "Final user requirement. api_key=hidden-user-secret"
+ answer = "Repository answer. " * 4000 + "Final implementation detail. password=hidden-agent-secret"
+ payload = {"session_id": "s1", "cwd": "/tmp/repo", "prompt": prompt, "last_assistant_message": answer}
+ store = memory_core.EvidenceStore()
+ memory_core.record_user_prompt(store, payload)
+ if capture == "transcript":
+ transcript = isolated_env / "long-session.jsonl"
+ _write_transcript(transcript, "s1", [
+ {"type": "user", "message": {"role": "user", "content": prompt}},
+ {"type": "assistant", "message": {"role": "assistant", "content": answer}},
+ ])
+ transcript_mod.record_stop(store, {**payload, "transcript_path": str(transcript)})
+ else:
+ hook_runner.default_record_stop(store, payload)
+
+ with (
+ patch.object(memory_core, "_request_json", return_value=({"event_id": "extraction"}, 200, 20)) as request,
+ patch.object(memory_core, "_wait_for_event", return_value=("SUCCEEDED", 20, 1)),
+ ):
+ assert memory_core.flush_session(store, payload, "session-end")["status"] == "semantic-succeeded"
+
+ batches = [call.args[2]["messages"] for call in request.call_args_list]
+ assert len(batches) > 1
+ assert all(memory_core._message_tokens(batch) <= memory_core.MAX_EXTRACTION_INPUT_TOKENS for batch in batches)
+ for role, text in (("user", prompt), ("assistant", answer)):
+ actual = "".join(message["content"] for batch in batches for message in batch if message["role"] == role)
+ prefix = "Main Claude response:\n" if capture == "transcript" and role == "assistant" else ""
+ assert actual == prefix + memory_core.redact(text)
+ store.close()
+
+
def test_upgrade_removes_legacy_snapshot_tables(isolated_env):
database = Path(os.environ["MEM0_CODE_DATA_DIR"]) / "evidence.sqlite3"
database.parent.mkdir(parents=True, exist_ok=True)
@@ -756,7 +804,7 @@ def test_tool_capture_identifies_main_and_sidekick_roles():
)
assert main["agent_role"] == "main"
- assert sidekick["agent_role"] == "sidekick"
+ assert sidekick["agent_role"] == "subagent"
assert sidekick["agent_id"] == "agent-123"
assert sidekick["agent_type"] == "mem0:sidekick"
@@ -863,6 +911,20 @@ def test_common_tokens_and_private_keys_are_redacted():
assert "private-material" not in value
+def test_json_shaped_secrets_are_redacted():
+ value = memory_core.redact('{"apiKey": "sk-secret-12345", "name": "test"}')
+ assert "sk-secret-12345" not in value
+ assert "[REDACTED]" in value
+ assert '"name": "test"' in value
+
+ value = memory_core.redact('{"password": "hunter2", "count": 1}')
+ assert "hunter2" not in value
+
+ value = memory_core.redact('{"secret_access_key": "ABCDEFGHIJ1234567890", "region": "us-east-1"}')
+ assert "ABCDEFGHIJ1234567890" not in value
+ assert '"region": "us-east-1"' in value
+
+
def test_remote_identity_removes_embedded_credentials():
normalized = memory_core._normalize_remote(
"https://secret-token@github.com/example/repo.git"
@@ -896,6 +958,49 @@ def test_repo_scope_matches_the_previous_plugin_mapping(
assert resolved.app_id == "customer-platform"
+def test_different_git_hosts_produce_different_project_ids():
+ github = memory_core._project_id("/tmp/repo", "https://github.com/acme/api", "acme-api")
+ gitlab = memory_core._project_id("/tmp/repo", "https://gitlab.internal/acme/api", "acme-api")
+
+ assert github != gitlab
+ assert github.startswith("acme-api-")
+ assert gitlab.startswith("acme-api-")
+
+
+@pytest.mark.parametrize("scope", ["repo", "dir", "mine"])
+def test_upgraded_repo_search_retrieves_legacy_and_current_shared_memories(isolated_env, monkeypatch, scope):
+ from dataclasses import replace
+
+ monkeypatch.setenv("MEM0_API_KEY", "test-key")
+ project = replace(repo(), project_id=memory_core._project_id(repo().root, repo().identity, repo().app_id))
+ records = [
+ {"id": "legacy", "agent_id": project.app_id, "app_id": project.app_id},
+ {"id": "current", "agent_id": project.project_id, "app_id": project.app_id},
+ {"id": "personal", "user_id": "test-user", "app_id": project.app_id},
+ {"id": "teammate", "user_id": "someone-else", "app_id": project.app_id},
+ {"id": "other-app", "agent_id": project.app_id, "app_id": "another-repo"},
+ {"id": "other-host", "agent_id": "code-example-other-host", "app_id": project.app_id},
+ ]
+
+ def matches(record, filters):
+ for key, value in filters.items():
+ if key == "AND":
+ return all(matches(record, child) for child in value)
+ if key == "OR":
+ return any(matches(record, child) for child in value)
+ if record.get(key) != value:
+ return False
+ return True
+
+ def search(url, key, payload, timeout):
+ return {"results": [record for record in records if matches(record, payload["filters"])]}, 0, 0
+
+ monkeypatch.setattr(memory_core, "_request_json_with_network_retry", search)
+ result = memory_core.search_memories(None, project, None, "prior work", scope=scope)
+ expected = {"personal"} if scope == "mine" else {"legacy", "current", "personal"}
+ assert {memory["id"] for memory in result.memories} == expected
+
+
def test_non_git_session_keeps_starting_project_scope_after_nested_commands(
isolated_env,
):
@@ -1061,32 +1166,32 @@ def test_forced_checkpoint_sends_an_incomplete_remainder(isolated_env):
def test_stop_schedules_one_background_checkpoint_when_block_is_ready(
isolated_env,
):
- import hook
+ import hook_runner
store = memory_core.EvidenceStore()
for number in range(1, 5):
_record_exchange(store, number)
with (
- patch.object(hook, "api_key", return_value="m0-test-key"),
- patch.object(hook, "hand_off_flush") as handoff,
+ patch.object(hook_runner, "api_key", return_value="m0-test-key"),
+ patch.object(hook_runner, "hand_off_flush") as handoff,
):
assert (
- hook.schedule_periodic_checkpoint(
+ hook_runner.schedule_periodic_checkpoint(
store, {"session_id": "s1", "cwd": "/tmp/repo"}, repo(), "s1"
)
is False
)
_record_exchange(store, 5)
assert (
- hook.schedule_periodic_checkpoint(
+ hook_runner.schedule_periodic_checkpoint(
store, {"session_id": "s1", "cwd": "/tmp/repo"}, repo(), "s1"
)
is True
)
_record_exchange(store, 6)
assert (
- hook.schedule_periodic_checkpoint(
+ hook_runner.schedule_periodic_checkpoint(
store, {"session_id": "s1", "cwd": "/tmp/repo"}, repo(), "s1"
)
is False
@@ -1100,64 +1205,64 @@ def test_stop_schedules_one_background_checkpoint_when_block_is_ready(
def test_stop_schedules_idle_flush_when_periodic_not_due(isolated_env):
- import hook
+ import hook_runner
store = memory_core.EvidenceStore()
_record_exchange(store, 1)
hook_input = {"session_id": "s1", "cwd": "/tmp/repo"}
with (
- patch.object(hook, "api_key", return_value="m0-test-key"),
- patch.object(hook, "_launch_handoff", return_value=True) as launch,
+ patch.object(hook_runner, "api_key", return_value="m0-test-key"),
+ patch.object(hook_runner, "_launch_handoff", return_value=True) as launch,
):
- assert not hook.schedule_periodic_checkpoint(store, hook_input, repo(), "s1")
- assert hook.schedule_idle_flush(store, hook_input, repo(), "s1")
+ assert not hook_runner.schedule_periodic_checkpoint(store, hook_input, repo(), "s1")
+ assert hook_runner.schedule_idle_flush(store, hook_input, repo(), "s1")
payload = json.loads(launch.call_args.args[0].read_text(encoding="utf-8"))
assert payload["reason"] == "idle"
- assert payload["delay_seconds"] == hook.DEFAULT_IDLE_FLUSH_SECONDS
+ assert payload["delay_seconds"] == hook_runner.DEFAULT_IDLE_FLUSH_SECONDS
store.close()
def test_idle_flush_skipped_when_inflight_flush_exists(isolated_env):
- import hook
+ import hook_runner
store = memory_core.EvidenceStore()
for number in range(1, 6):
_record_exchange(store, number)
hook_input = {"session_id": "s1", "cwd": "/tmp/repo"}
- with patch.object(hook, "api_key", return_value="m0-test-key"):
+ with patch.object(hook_runner, "api_key", return_value="m0-test-key"):
store.prepare_flush(repo(), "s1", "periodic")
- assert not hook.schedule_idle_flush(store, hook_input, repo(), "s1")
+ assert not hook_runner.schedule_idle_flush(store, hook_input, repo(), "s1")
store.close()
def test_idle_flush_skipped_when_no_unflushed_events(isolated_env):
- import hook
+ import hook_runner
store = memory_core.EvidenceStore()
hook_input = {"session_id": "s1", "cwd": "/tmp/repo"}
- with patch.object(hook, "api_key", return_value="m0-test-key"):
- assert not hook.schedule_idle_flush(store, hook_input, repo(), "s1")
+ with patch.object(hook_runner, "api_key", return_value="m0-test-key"):
+ assert not hook_runner.schedule_idle_flush(store, hook_input, repo(), "s1")
store.close()
def test_idle_flush_skipped_when_disabled(isolated_env, monkeypatch):
- import hook
+ import hook_runner
store = memory_core.EvidenceStore()
_record_exchange(store, 1)
monkeypatch.setenv("MEM0_CODE_IDLE_FLUSH_SECONDS", "0")
hook_input = {"session_id": "s1", "cwd": "/tmp/repo"}
- with patch.object(hook, "api_key", return_value="m0-test-key"):
- assert not hook.schedule_idle_flush(store, hook_input, repo(), "s1")
+ with patch.object(hook_runner, "api_key", return_value="m0-test-key"):
+ assert not hook_runner.schedule_idle_flush(store, hook_input, repo(), "s1")
store.close()
def test_stop_hook_falls_through_to_idle_flush(isolated_env, monkeypatch):
- import hook
+ import hook_runner
store = memory_core.EvidenceStore()
_record_exchange(store, 1)
@@ -1166,7 +1271,7 @@ def test_stop_hook_falls_through_to_idle_flush(isolated_env, monkeypatch):
periodic_called = []
idle_called = []
- original_periodic = hook.schedule_periodic_checkpoint
+ original_periodic = hook_runner.schedule_periodic_checkpoint
def mock_periodic(*a, **kw):
result = original_periodic(*a, **kw)
@@ -1178,14 +1283,17 @@ def test_stop_hook_falls_through_to_idle_flush(isolated_env, monkeypatch):
return True
with (
- patch.object(hook, "api_key", return_value="m0-test-key"),
- patch.object(hook, "schedule_periodic_checkpoint", side_effect=mock_periodic),
- patch.object(hook, "schedule_idle_flush", side_effect=mock_idle),
- patch.object(hook, "record_stop", return_value=(repo(), "s1")),
+ patch.object(hook_runner, "api_key", return_value="m0-test-key"),
+ patch.object(hook_runner, "schedule_periodic_checkpoint", side_effect=mock_periodic),
+ patch.object(hook_runner, "schedule_idle_flush", side_effect=mock_idle),
):
monkeypatch.setattr("sys.stdin", __import__("io").StringIO(json.dumps(hook_input)))
monkeypatch.setattr("sys.argv", ["hook.py", "stop"])
- hook.main()
+ hook_runner.run(
+ record_stop_fn=lambda s, h: (repo(), "s1"),
+ data_dir_env="MEM0_CODE_DATA_DIR",
+ automatic_flush_reasons={"session-end", "pre-compact"},
+ )
assert periodic_called == [False]
assert idle_called == [True]
@@ -1228,6 +1336,136 @@ def test_flush_worker_sleeps_for_delay_seconds(isolated_env, monkeypatch):
assert "delay_seconds" not in rewritten_content
+def test_session_end_worker_does_not_repeat_captured_final_response(isolated_env, monkeypatch):
+ import flush_worker
+
+ monkeypatch.setenv("MEM0_API_KEY", "test-key")
+ monkeypatch.setattr(memory_core, "resolve_repo", lambda cwd: repo())
+ store = memory_core.EvidenceStore()
+ for index in range(5):
+ store.record_event(repo(), "s1", "user_prompt", {"text": f"Earlier prompt {index}"})
+ store.record_event(repo(), "s1", "assistant_stop", {"text": f"Earlier answer {index}"})
+ first_packet, _ = store.prepare_flush(repo(), "s1", "periodic")
+ store.update_flush(first_packet, status="semantic-queued", semantic_event_id="earlier-extraction")
+
+ prompt = "How does the serializer handle dates?"
+ answer = "The serializer preserves timezone-naive dates."
+ transcript = isolated_env / "session.jsonl"
+ _write_transcript(transcript, "s1", [
+ {"type": "user", "message": {"role": "user", "content": prompt}},
+ {"type": "assistant", "message": {"role": "assistant", "content": answer}},
+ ])
+ hook_input = {
+ "session_id": "s1", "cwd": "/tmp/repo",
+ "transcript_path": str(transcript), "last_assistant_message": answer,
+ }
+ memory_core.record_user_prompt(store, {**hook_input, "prompt": prompt})
+ transcript_mod.record_stop(store, hook_input)
+ # SessionEnd captures again before handing off, using the same transcript cursor.
+ transcript_mod.record_stop(store, hook_input)
+ handoff = isolated_env / "session-end.running"
+ handoff.write_text(json.dumps({
+ "hook_input": hook_input, "reason": "session-end", "wait_for_inflight": True,
+ }))
+ monkeypatch.setattr(sys, "argv", ["flush_worker.py", str(handoff)])
+ monkeypatch.setenv("MEM0_CODE_HANDOFF_PATH", str(handoff))
+ monkeypatch.setattr(flush_worker.time, "sleep", lambda seconds: store.update_flush(
+ first_packet, status="semantic-succeeded",
+ ))
+ with (
+ patch.object(memory_core, "_request_json", return_value=({"event_id": "final-extraction"}, 200, 20)) as request,
+ patch.object(memory_core, "_wait_for_event", return_value=("SUCCEEDED", 20, 1)),
+ ):
+ assert flush_worker.main() == 0
+
+ assert request.call_count == 1
+ messages = request.call_args.args[2]["messages"]
+ assert sum(prompt in message["content"] for message in messages) == 1
+ assert sum(answer in message["content"] for message in messages) == 1
+ assert not handoff.exists()
+ store.close()
+
+
+def test_default_stop_records_each_exchange_once_across_repeated_hooks(isolated_env, monkeypatch):
+ import hook_runner
+
+ monkeypatch.setattr(memory_core, "resolve_repo", lambda cwd: repo())
+ store = memory_core.EvidenceStore()
+ hook_input = {"session_id": "s1", "cwd": "/tmp/repo", "last_assistant_message": "The parser uses UTC."}
+ for _ in range(2):
+ memory_core.record_user_prompt(store, {**hook_input, "prompt": "What timezone does the parser use?"})
+ hook_runner.default_record_stop(store, hook_input)
+ # A tool notification and a flush must not make a repeated Stop look like a new answer.
+ store.record_event(repo(), "s1", "tool_result", {"tool": "Read"})
+ packet, _ = store.prepare_flush(repo(), "s1", "session-end")
+ store.update_flush(packet, status="semantic-succeeded")
+ hook_runner.default_record_stop(store, hook_input)
+
+ responses = store.conn.execute("SELECT payload_json FROM events WHERE kind = 'assistant_stop'").fetchall()
+ assert [json.loads(row[0])["text"] for row in responses] == ["The parser uses UTC."] * 2
+ assert not store.has_unflushed_events(repo().identity, "s1")
+ store.close()
+
+
+def test_concurrent_response_hooks_record_one_answer(isolated_env):
+ from concurrent.futures import ThreadPoolExecutor
+ from threading import Barrier
+
+ store = memory_core.EvidenceStore()
+ store.record_event(repo(), "s1", "user_prompt", {"text": "Inspect the parser."})
+ ready = Barrier(2)
+
+ def capture():
+ connection = memory_core.EvidenceStore(store.path)
+ try:
+ ready.wait(timeout=5)
+ connection.record_assistant_response(repo(), "s1", "The parser uses UTC.")
+ finally:
+ connection.close()
+
+ with ThreadPoolExecutor(max_workers=2) as workers:
+ list(workers.map(lambda _: capture(), range(2)))
+ assert store.conn.execute("SELECT COUNT(*) FROM events WHERE kind = 'assistant_stop'").fetchone()[0] == 1
+ store.record_assistant_response(repo(), "s1", "The serializer also uses UTC.")
+ store.record_assistant_response(repo(), "s2", "The parser uses UTC.")
+ assert store.conn.execute("SELECT COUNT(*) FROM events WHERE kind = 'assistant_stop'").fetchone()[0] == 3
+ store.close()
+
+
+def test_flush_worker_restores_harness_identity_from_child_environment(isolated_env, monkeypatch):
+ import flush_worker
+
+ handoff_path = Path(os.environ["MEM0_CODE_DATA_DIR"]) / "pending" / "kimi.running"
+ handoff_path.parent.mkdir(parents=True, exist_ok=True)
+ handoff_path.write_text(
+ json.dumps({"hook_input": {"session_id": "s1", "cwd": "/tmp/repo"}}),
+ encoding="utf-8",
+ )
+ monkeypatch.setenv("MEM0_PLUGIN_HARNESS", "kimi")
+ monkeypatch.setenv("MEM0_PLUGIN_ENV_PREFIX", "MEM0_KIMI")
+ monkeypatch.setenv("MEM0_PLUGIN_DATA_DIR_NAME", "kimi-plugin")
+ monkeypatch.setenv("MEM0_PLUGIN_SOURCE_TAG", "kimi_plugin")
+ monkeypatch.setattr("sys.argv", ["flush_worker.py", str(handoff_path)])
+
+ with (
+ patch.object(flush_worker, "configure_harness", wraps=memory_core.configure_harness) as configure,
+ patch.object(flush_worker.telemetry, "init") as telemetry_init,
+ patch.object(flush_worker, "checkpoint_session", return_value={"status": "nothing-to-flush"}),
+ ):
+ flush_worker.main()
+
+ configure.assert_called_once_with(
+ "kimi",
+ env_prefix="MEM0_KIMI",
+ data_dir_name="kimi-plugin",
+ source_tag="kimi_plugin",
+ )
+ telemetry_init.assert_called_once_with(harness="kimi", source_tag="KIMI_PLUGIN")
+ memory_core.configure_harness(
+ "claude-code", data_dir_name="claude-code-plugin", source_tag="claude_code_plugin"
+ )
+
+
def test_launch_handoff_resolves_flush_worker_under_core(isolated_env):
"""hook.py lives in adapters/claude/; flush_worker.py lives in core/.
@@ -1235,7 +1473,7 @@ def test_launch_handoff_resolves_flush_worker_under_core(isolated_env):
sibling of hook.py, or every background flush launches against a
nonexistent path.
"""
- import hook
+ import hook_runner
data_dir_path = Path(os.environ["MEM0_CODE_DATA_DIR"])
pending_dir = data_dir_path / "pending"
@@ -1243,13 +1481,18 @@ def test_launch_handoff_resolves_flush_worker_under_core(isolated_env):
handoff_path = pending_dir / "test-handoff.json"
handoff_path.write_text("{}", encoding="utf-8")
- with patch.object(hook.subprocess, "Popen") as popen:
- assert hook._launch_handoff(handoff_path) is True
+ with patch.object(hook_runner.subprocess, "Popen") as popen:
+ assert hook_runner._launch_handoff(handoff_path) is True
launched_args = popen.call_args.args[0]
worker_path = Path(launched_args[1])
assert worker_path == CORE / "flush_worker.py"
assert worker_path.is_file()
+ child_env = popen.call_args.kwargs["env"]
+ assert child_env["MEM0_PLUGIN_HARNESS"] == "claude-code"
+ assert child_env["MEM0_PLUGIN_DATA_DIR_NAME"] == "claude-code-plugin"
+ assert child_env["MEM0_PLUGIN_SOURCE_TAG"] == "claude_code_plugin"
+ assert child_env["MEM0_CODE_DATA_DIR"] == os.environ["MEM0_CODE_DATA_DIR"]
def test_flush_worker_detaches_on_windows_as_well_as_posix(monkeypatch):
@@ -1258,30 +1501,30 @@ def test_flush_worker_detaches_on_windows_as_well_as_posix(monkeypatch):
Without a creationflags fallback the worker stays attached to Claude's
console on Windows and background extraction can die with the session.
"""
- import hook
+ import hook_runner
- assert hook.detached_process_kwargs("darwin") == {"start_new_session": True}
- assert hook.detached_process_kwargs("linux") == {"start_new_session": True}
+ assert hook_runner.detached_process_kwargs("darwin") == {"start_new_session": True}
+ assert hook_runner.detached_process_kwargs("linux") == {"start_new_session": True}
monkeypatch.setattr(subprocess, "DETACHED_PROCESS", 0x00000008, raising=False)
monkeypatch.setattr(
subprocess, "CREATE_NEW_PROCESS_GROUP", 0x00000200, raising=False
)
- windows_kwargs = hook.detached_process_kwargs("win32")
+ windows_kwargs = hook_runner.detached_process_kwargs("win32")
assert windows_kwargs == {"creationflags": 0x00000208}
assert "start_new_session" not in windows_kwargs
def test_launch_handoff_always_requests_detachment(isolated_env):
- import hook
+ import hook_runner
pending_dir = Path(os.environ["MEM0_CODE_DATA_DIR"]) / "pending"
pending_dir.mkdir(parents=True, exist_ok=True)
handoff_path = pending_dir / "detach-handoff.json"
handoff_path.write_text("{}", encoding="utf-8")
- with patch.object(hook.subprocess, "Popen") as popen:
- assert hook._launch_handoff(handoff_path) is True
+ with patch.object(hook_runner.subprocess, "Popen") as popen:
+ assert hook_runner._launch_handoff(handoff_path) is True
assert popen.call_args.kwargs["start_new_session"] is True
@@ -1294,23 +1537,23 @@ def test_pending_recovery_is_capped_and_leaves_the_rest_for_next_session(
Each worker can block for MEM0_CODE_EXTRACTION_WAIT_SECONDS, so an
uncapped launch is a thundering herd at session start.
"""
- import hook
+ import hook_runner
pending_dir = Path(os.environ["MEM0_CODE_DATA_DIR"]) / "pending"
pending_dir.mkdir(parents=True, exist_ok=True)
- for number in range(hook.PENDING_LAUNCH_LIMIT + 3):
+ for number in range(hook_runner.PENDING_LAUNCH_LIMIT + 3):
(pending_dir / f"packet-{number}.json").write_text("{}", encoding="utf-8")
- with patch.object(hook.subprocess, "Popen"):
- launched = hook.recover_pending_handoffs()
+ with patch.object(hook_runner.subprocess, "Popen"):
+ launched = hook_runner.recover_pending_handoffs()
- assert launched == hook.PENDING_LAUNCH_LIMIT
- assert len(list(pending_dir.glob("*.running"))) == hook.PENDING_LAUNCH_LIMIT
+ assert launched == hook_runner.PENDING_LAUNCH_LIMIT
+ assert len(list(pending_dir.glob("*.running"))) == hook_runner.PENDING_LAUNCH_LIMIT
assert len(list(pending_dir.glob("*.json"))) == 3
def test_pending_recovery_drops_packets_past_the_expiry_window(isolated_env):
- import hook
+ import hook_runner
pending_dir = Path(os.environ["MEM0_CODE_DATA_DIR"]) / "pending"
pending_dir.mkdir(parents=True, exist_ok=True)
@@ -1319,11 +1562,11 @@ def test_pending_recovery_drops_packets_past_the_expiry_window(isolated_env):
fresh = pending_dir / "fresh.json"
fresh.write_text("{}", encoding="utf-8")
- stale_time = time.time() - hook.PENDING_EXPIRY_SECONDS - 60
+ stale_time = time.time() - hook_runner.PENDING_EXPIRY_SECONDS - 60
os.utime(expired, (stale_time, stale_time))
- with patch.object(hook.subprocess, "Popen"):
- launched = hook.recover_pending_handoffs()
+ with patch.object(hook_runner.subprocess, "Popen"):
+ launched = hook_runner.recover_pending_handoffs()
assert launched == 1
assert not expired.exists()
@@ -1423,7 +1666,7 @@ def test_checkpoint_queues_only_prod_extraction_with_canonical_evidence(
store.record_event(
repo(),
"s1",
- "sidekick_stop",
+ "subagent_stop",
{
"agent_id": "agent-1",
"agent_type": "mem0:sidekick",
@@ -2061,11 +2304,11 @@ def test_format_context_labels_memories_from_non_main_branches():
def test_sidekick_instructions_reject_unrequested_related_changes():
- prompt = (Path(__file__).parents[1] / "agents" / "sidekick.md").read_text()
+ prompt = (PLUGIN_ROOT / "agents" / "sidekick.md").read_text()
normalized = " ".join(prompt.split())
assert "Skill" in prompt.split("---", 2)[1]
- assert "ALWAYS call `search_memories` before answering anything" in normalized
- assert "Do not rely on the chat window" in normalized
+ assert "call `search_memories` with a" in normalized
+ assert "focused question before searching the repository again" in normalized
assert "Complete only the work the main agent assigned" in normalized
assert "Do not make related improvements" in normalized
assert "report them separately" in normalized
@@ -2095,9 +2338,9 @@ def test_sidekick_reuses_parent_memory_once_and_records_lifecycle(
}
with patch.object(memory_core, "resolve_repo", return_value=repo()):
- first = memory_core.record_sidekick_start(store, start_input)
- repeated = memory_core.record_sidekick_start(store, start_input)
- memory_core.record_sidekick_stop(
+ first = memory_core.record_subagent_start(store, start_input)
+ repeated = memory_core.record_subagent_start(store, start_input)
+ memory_core.record_subagent_stop(
store,
{
**start_input,
@@ -2117,10 +2360,40 @@ def test_sidekick_reuses_parent_memory_once_and_records_lifecycle(
row[0]
for row in store.conn.execute("SELECT kind FROM events ORDER BY id").fetchall()
]
- assert events == ["sidekick_start", "sidekick_start", "sidekick_stop"]
+ assert events == ["subagent_start", "subagent_start", "subagent_stop"]
store.close()
+def test_subagent_stop_without_agent_id_closes_latest_matching_run(isolated_env):
+ store = memory_core.EvidenceStore()
+ start_input = {
+ "session_id": "s1",
+ "cwd": "/tmp/repo",
+ "agent_id": "agent-123",
+ "agent_type": "sidekick",
+ }
+
+ with patch.object(memory_core, "resolve_repo", return_value=repo()):
+ memory_core.record_subagent_start(store, start_input)
+ memory_core.record_subagent_stop(
+ store,
+ {
+ "session_id": "s1",
+ "cwd": "/tmp/repo",
+ "agent_type": "sidekick",
+ "last_assistant_message": "Done.",
+ },
+ )
+
+ rows = store.conn.execute("SELECT agent_id, stopped_at, final_message FROM sidekick_runs").fetchall()
+ store.close()
+
+ assert len(rows) == 1
+ assert rows[0]["agent_id"] == "agent-123"
+ assert rows[0]["stopped_at"]
+ assert rows[0]["final_message"] == "Done."
+
+
def test_search_once_per_session_avoids_repeated_remote_searches(
isolated_env, monkeypatch
):
@@ -2325,7 +2598,8 @@ def test_mcp_tool_contract_is_small_and_read_only():
"query",
"top_k",
"category",
- "scope", "run_id",
+ "scope",
+ "run_id",
}
assert tool["inputSchema"]["required"] == ["query"]
assert tool["inputSchema"]["properties"]["top_k"]["minimum"] == 1
@@ -2335,6 +2609,8 @@ def test_mcp_tool_contract_is_small_and_read_only():
)
assert tool["annotations"]["readOnlyHint"] is True
assert tool["annotations"]["idempotentHint"] is True
+ assert "Claude" not in tool["description"]
+ assert "Claude" not in memory_core.PROJECT_MEMORY_INSTRUCTIONS
def test_plugin_mcp_config_starts_the_local_server():
@@ -2430,6 +2706,51 @@ def test_mcp_tool_is_session_independent_and_returns_plain_memories(
assert "project_knowledge" not in rendered
+@pytest.mark.parametrize("scope", ["repo", "dir", "mine"])
+def test_mcp_search_passes_run_id_for_every_scope(isolated_env, monkeypatch, scope):
+ from dataclasses import replace
+
+ monkeypatch.setenv("MEM0_API_KEY", "test-key")
+ project = replace(repo(), directory="src", project_id="code-example-hash")
+ monkeypatch.setattr(mcp_server, "resolve_repo", lambda cwd: project)
+ with patch.object(
+ memory_core, "_request_json_with_network_retry", return_value=({"results": []}, 0, 0)
+ ) as request:
+ mcp_server.call_search_memories({"query": "parser", "scope": scope})
+ across_sessions = request.call_args.args[2]["filters"]
+ mcp_server.call_search_memories({"query": "parser", "scope": scope, "run_id": "session-42"})
+ assert request.call_args.args[2]["filters"] == {"AND": [across_sessions, {"run_id": "session-42"}]}
+
+
+def test_mcp_tool_uses_codex_workspace_metadata(isolated_env):
+ result = memory_core.MemorySearchResult(
+ succeeded=True, matched_count=0, already_shown_count=0, memories=[]
+ )
+ request = {
+ "jsonrpc": "2.0",
+ "id": 2,
+ "method": "tools/call",
+ "params": {
+ "name": "search_memories",
+ "arguments": {"query": "parser"},
+ "_meta": {
+ "x-codex-turn-metadata": {
+ "workspaces": {"/tmp/active-repository": {"has_changes": False}}
+ }
+ },
+ },
+ }
+
+ with (
+ patch.object(mcp_server, "resolve_repo", return_value=repo()) as resolve,
+ patch.object(mcp_server, "search_memories", return_value=result),
+ ):
+ response = mcp_server.handle_request(request)
+
+ resolve.assert_called_once_with("/tmp/active-repository")
+ assert response["result"]["isError"] is False
+
+
@pytest.mark.parametrize(
"arguments, message",
[
@@ -2438,7 +2759,8 @@ def test_mcp_tool_is_session_independent_and_returns_plain_memories(
({"query": "parser", "top_k": True}, "1 to 20"),
({"query": "parser", "category": "other"}, "supported categories"),
({"query": "parser", "threshold": 0.5}, "Unknown search argument"),
- ({"query": "parser", "run_id": ""}, "run_id must be"),
+ ({"query": "parser", "run_id": " "}, "run_id must be a non-empty string"),
+ ({"query": "parser", "run_id": 42}, "run_id must be a non-empty string"),
],
)
def test_mcp_tool_rejects_invalid_arguments(arguments, message):
@@ -2447,7 +2769,7 @@ def test_mcp_tool_rejects_invalid_arguments(arguments, message):
def test_search_skill_describes_memory_as_optional_starting_knowledge():
- prompt = (Path(__file__).parents[1] / "skills" / "search" / "SKILL.md").read_text()
+ prompt = (PLUGIN_ROOT / "skills" / "search" / "SKILL.md").read_text()
normalized = " ".join(prompt.split())
assert "earlier work may already explain" in normalized
@@ -2455,6 +2777,9 @@ def test_search_skill_describes_memory_as_optional_starting_knowledge():
assert "Call `search_memories` with the user's question" in normalized
assert "Return the tool's result directly" in normalized
assert "Run the search before repository exploration" not in normalized
+ assert "run_id" in normalized
+ assert "--run-id" in normalized
+ assert "Omit `run_id` to search across sessions" in normalized
def test_control_skills_exposed():
@@ -2493,7 +2818,7 @@ def test_pause_skill_points_to_dedicated_resume_command():
def test_resume_skill_runs_cli_and_is_a_dedicated_command():
text = (PLUGIN_ROOT / "skills" / "resume" / "SKILL.md").read_text()
assert "disable-model-invocation: true" in text
- assert 'core/memory_cli.py" resume' in text
+ assert '--harness "claude-code" --plugin-data-dir "${CLAUDE_PLUGIN_DATA}" resume' in text
def test_remember_skill_acknowledges_without_write_api():
@@ -2512,14 +2837,14 @@ def test_status_output_explains_memory_activity_in_plain_language(capsys):
"events": 8,
"flushes": 2,
"retrievals": 3,
- "sidekick_runs": 1,
+ "subagent_runs": 1,
"last_operation": {
"operation": "flush",
"success": 1,
"duration_ms": 123.4,
"item_count": 2,
},
- "last_sidekick": {
+ "last_subagent": {
"stopped_at": "now",
"context_chars": 240,
"agent_id": "agent-1",
@@ -2529,9 +2854,9 @@ def test_status_output_explains_memory_activity_in_plain_language(capsys):
output = capsys.readouterr().out
assert "Saved on this computer: 8 session details, 2 memory updates" in output
- assert "3 memories returned, 1 sidekick runs" in output
+ assert "3 memories returned, 1 subagent runs" in output
assert "Last memory update: succeeded" in output
- assert "Last sidekick: finished, received 240 characters of memory" in output
+ assert "Last subagent: finished, received 240 characters of memory" in output
assert "checkpoint" not in output.lower()
assert "injected" not in output.lower()
@@ -2591,7 +2916,7 @@ def _run_hook(
env.pop("CLAUDE_PLUGIN_OPTION_API_KEY", None)
env.pop("CLAUDE_PLUGIN_OPTION_MEM0_API_KEY", None)
return subprocess.run(
- [sys.executable, str(ADAPTER / "hook.py"), action, *extra],
+ [sys.executable, str(ADAPTER), action, *extra],
input=json.dumps(payload),
text=True,
capture_output=True,
@@ -2774,7 +3099,7 @@ def test_first_user_prompt_searches_verbatim_and_returns_five_memories(
for index in range(1, 7)
]
- import hook
+ import hook_runner
with (
patch.object(memory_core, "resolve_repo", return_value=repo()),
@@ -2784,7 +3109,7 @@ def test_first_user_prompt_searches_verbatim_and_returns_five_memories(
return_value=({"results": results}, 200, 600),
) as request,
):
- output = hook.first_prompt_memory_output(
+ output = hook_runner.first_prompt_memory_output(
store,
{"session_id": "s1", "cwd": "/tmp/repo", "prompt": prompt},
)
@@ -2814,7 +3139,7 @@ def test_later_user_prompts_do_not_search_automatically(isolated_env, monkeypatc
monkeypatch.setenv("MEM0_API_KEY", "m0-test-key")
store = memory_core.EvidenceStore()
- import hook
+ import hook_runner
with (
patch.object(memory_core, "resolve_repo", return_value=repo()),
@@ -2824,7 +3149,7 @@ def test_later_user_prompts_do_not_search_automatically(isolated_env, monkeypatc
return_value=({"results": []}, 100, 20),
) as request,
):
- first = hook.first_prompt_memory_output(
+ first = hook_runner.first_prompt_memory_output(
store,
{
"session_id": "s1",
@@ -2832,7 +3157,7 @@ def test_later_user_prompts_do_not_search_automatically(isolated_env, monkeypatc
"prompt": "Where is ODS date formatting implemented?",
},
)
- second = hook.first_prompt_memory_output(
+ second = hook_runner.first_prompt_memory_output(
store,
{
"session_id": "s1",
@@ -2853,7 +3178,7 @@ def test_manual_search_remains_available_after_automatic_search(
monkeypatch.setenv("MEM0_API_KEY", "m0-test-key")
store = memory_core.EvidenceStore()
- import hook
+ import hook_runner
with (
patch.object(memory_core, "resolve_repo", return_value=repo()),
@@ -2878,7 +3203,7 @@ def test_manual_search_remains_available_after_automatic_search(
],
) as request,
):
- hook.first_prompt_memory_output(
+ hook_runner.first_prompt_memory_output(
store,
{
"session_id": "s1",
@@ -2912,7 +3237,7 @@ def test_first_prompt_is_silent_when_all_matches_were_already_provided(
}
store.mark_injected("s1", repo().identity, [existing])
- import hook
+ import hook_runner
with (
patch.object(memory_core, "resolve_repo", return_value=repo()),
@@ -2922,7 +3247,7 @@ def test_first_prompt_is_silent_when_all_matches_were_already_provided(
return_value=({"results": [existing]}, 100, 100),
),
):
- output = hook.first_prompt_memory_output(
+ output = hook_runner.first_prompt_memory_output(
store,
{
"session_id": "s1",
@@ -2943,7 +3268,7 @@ def test_user_prompt_search_failure_still_records_evidence_and_emits_no_context(
env["MEM0_API_KEY"] = "m0-test-key"
env["MEM0_API_URL"] = "http://127.0.0.1:1"
result = subprocess.run(
- [sys.executable, str(ADAPTER / "hook.py"), "user-prompt"],
+ [sys.executable, str(ADAPTER), "user-prompt"],
input=json.dumps(
{
"session_id": "s1",
@@ -3027,7 +3352,7 @@ def test_plugin_entrypoints_share_explicit_claude_data_dir(tmp_path, monkeypatch
sidekick = subprocess.run(
[
sys.executable,
- str(ADAPTER / "hook.py"),
+ str(ADAPTER),
"sidekick-start",
"--plugin-data-dir",
str(canonical_data),
@@ -3067,7 +3392,7 @@ def test_plugin_entrypoints_share_explicit_claude_data_dir(tmp_path, monkeypatch
status_payload = json.loads(status.stdout)
assert status_payload["data_dir"] == str(canonical_data)
assert status_payload["retrievals"] == 1
- assert status_payload["sidekick_runs"] == 1
+ assert status_payload["subagent_runs"] == 1
assert not (conflicting_data / "evidence.sqlite3").exists()
@@ -3102,7 +3427,7 @@ def test_automatic_flush_can_be_disabled_for_external_harnesses(isolated_env):
env["MEM0_API_KEY"] = "m0-test-key"
start = subprocess.run(
- [sys.executable, str(ADAPTER / "hook.py"), "user-prompt"],
+ [sys.executable, str(ADAPTER), "user-prompt"],
input=json.dumps(
{"session_id": "s1", "cwd": cwd, "prompt": "Inspect parser behavior."}
),
@@ -3112,7 +3437,7 @@ def test_automatic_flush_can_be_disabled_for_external_harnesses(isolated_env):
check=False,
)
flushed = subprocess.run(
- [sys.executable, str(ADAPTER / "hook.py"), "flush", "--reason", "session-end"],
+ [sys.executable, str(ADAPTER), "flush", "--reason", "session-end"],
input=json.dumps({"session_id": "s1", "cwd": cwd}),
text=True,
capture_output=True,
@@ -3136,12 +3461,34 @@ def test_automatic_flush_can_be_disabled_for_external_harnesses(isolated_env):
def test_version_is_single_sourced():
manifest = json.loads((PLUGIN_ROOT / ".claude-plugin" / "plugin.json").read_text())
assert manifest["name"] == "mem0"
- assert manifest["version"] == memory_core.PLUGIN_VERSION == "0.3.0"
- root = PLUGIN_ROOT.parents[1]
+ # Compared against PLUGIN_VERSION, never a literal. A hardcoded version here
+ # was one more place to edit on every release, inside the test asserting the
+ # version is single-sourced, and it caught nothing that the agreement checks
+ # below do not: fifteen places set to the same wrong value would still pass.
+ assert re.fullmatch(r"\d+\.\d+\.\d+", memory_core.PLUGIN_VERSION), memory_core.PLUGIN_VERSION
+ assert manifest["version"] == memory_core.PLUGIN_VERSION
+ root = REPOSITORY_ROOT
for mp in (root / "marketplace.json", root / ".claude-plugin" / "marketplace.json"):
entry = next(p for p in json.loads(mp.read_text())["plugins"] if p["name"] == "mem0")
assert entry["version"] == memory_core.PLUGIN_VERSION
assert entry["source"] == "./integrations/claude-code-plugin"
+ manifests = {
+ "cursor": ".cursor-plugin/plugin.json",
+ "codex": ".codex-plugin/plugin.json",
+ "kimi": "kimi.plugin.json",
+ "mem0-agent": "plugin.json",
+ }
+ for host, filename in manifests.items():
+ manifest = json.loads((root / "integrations" / f"{host}-plugin" / filename).read_text())
+ assert manifest["version"] == memory_core.PLUGIN_VERSION
+ for host in ("claude-code", "cursor", "codex", "kimi", "antigravity"):
+ descriptor = json.loads((root / "integrations" / f"{host}-plugin" / "plugin-build.json").read_text())
+ assert descriptor["version"] == memory_core.PLUGIN_VERSION
+ for directory in (".cursor-plugin", ".kimi-plugin"):
+ marketplace = json.loads((root / directory / "marketplace.json").read_text())
+ assert marketplace["plugins"][0]["version"] == memory_core.PLUGIN_VERSION
+ response = mcp_server.handle_request({"jsonrpc": "2.0", "id": 1, "method": "initialize"})
+ assert response["result"]["serverInfo"]["version"] == memory_core.PLUGIN_VERSION
def test_user_id_falls_back_to_the_windows_account_name(monkeypatch):
@@ -3183,7 +3530,7 @@ def test_transcript_rows_resume_from_a_byte_offset(tmp_path):
],
)
- rows, end, resumed = memory_core._transcript_rows(str(transcript))
+ rows, end, resumed = transcript_mod._transcript_rows(str(transcript))
assert [row["uuid"] for row in rows] == ["entry-1", "entry-2"]
assert end == transcript.stat().st_size
assert resumed is False
@@ -3201,12 +3548,12 @@ def test_transcript_rows_resume_from_a_byte_offset(tmp_path):
handle.write(json.dumps(third_row) + "\n")
handle.write('{"uuid": "partial-row"')
- rows, end, resumed = memory_core._transcript_rows(str(transcript), first_size)
+ rows, end, resumed = transcript_mod._transcript_rows(str(transcript), first_size)
assert [row["uuid"] for row in rows] == ["entry-3"]
assert resumed is True
assert end < transcript.stat().st_size
- rows, _, resumed = memory_core._transcript_rows(
+ rows, _, resumed = transcript_mod._transcript_rows(
str(transcript), transcript.stat().st_size + 100
)
assert [row["uuid"] for row in rows] == ["entry-1", "entry-2", "entry-3"]
@@ -3235,7 +3582,7 @@ def test_record_stop_reads_the_transcript_from_the_stored_offset(
store = memory_core.EvidenceStore()
with patch.object(memory_core, "resolve_repo", return_value=repo()):
- memory_core.record_stop(
+ transcript_mod.record_stop(
store,
{
"session_id": "s1",
@@ -3270,7 +3617,7 @@ def test_record_stop_reads_the_transcript_from_the_stored_offset(
},
]
_write_transcript(transcript, "s1", second_entries)
- original_rows = memory_core._transcript_rows
+ original_rows = transcript_mod._transcript_rows
offsets = []
def spying_rows(path, offset=0):
@@ -3279,9 +3626,9 @@ def test_record_stop_reads_the_transcript_from_the_stored_offset(
with (
patch.object(memory_core, "resolve_repo", return_value=repo()),
- patch.object(memory_core, "_transcript_rows", side_effect=spying_rows),
+ patch.object(transcript_mod, "_transcript_rows", side_effect=spying_rows),
):
- memory_core.record_stop(
+ transcript_mod.record_stop(
store,
{
"session_id": "s1",
@@ -3355,7 +3702,7 @@ def test_event_poll_touches_the_worker_heartbeat(isolated_env, monkeypatch, tmp_
def test_paused_session_start_keeps_pending_packets_fresh(isolated_env):
- import hook
+ import hook_runner
pending_dir = Path(os.environ["MEM0_CODE_DATA_DIR"]) / "pending"
pending_dir.mkdir(parents=True, exist_ok=True)
@@ -3363,11 +3710,11 @@ def test_paused_session_start_keeps_pending_packets_fresh(isolated_env):
held.write_text("{}", encoding="utf-8")
claimed = pending_dir / "claimed.running"
claimed.write_text("{}", encoding="utf-8")
- stale_time = time.time() - hook.PENDING_EXPIRY_SECONDS - 60
+ stale_time = time.time() - hook_runner.PENDING_EXPIRY_SECONDS - 60
for path in (held, claimed):
os.utime(path, (stale_time, stale_time))
- hook.refresh_pending_handoffs()
+ hook_runner.refresh_pending_handoffs()
assert held.stat().st_mtime > time.time() - 60
assert claimed.stat().st_mtime > time.time() - 60
@@ -3635,7 +3982,7 @@ def test_forget_only_touches_shared_project_memory_when_asked(monkeypatch, isola
repo = memory_core.RepoContext(
cwd="/x", root="/x", identity="x", app_id="repo-a", branch="main", head_sha="abc", project_id="repo-a"
)
- listed = [({"results": []}, 0, 0), ({"results": [{"id": "shared-1"}]}, 0, 0)]
+ listed = [({"results": []}, 0, 0), ({"results": [{"id": "shared-1", "app_id": "repo-a"}]}, 0, 0)]
with patch.object(memory_core, "_request_json", side_effect=listed) as request:
with patch.object(memory_core, "_delete_memory", return_value=True):
result = memory_core.forget_remote_repo(repo, include_project_memory=True)
@@ -3647,6 +3994,36 @@ def test_forget_only_touches_shared_project_memory_when_asked(monkeypatch, isola
assert result == {"status": "deleted", "deleted": 1}
+@pytest.mark.parametrize("include_project", [False, True])
+def test_forget_includes_legacy_shared_memories_only_when_requested(monkeypatch, isolated_env, include_project):
+ from dataclasses import replace
+
+ monkeypatch.setenv("MEM0_API_KEY", "test-key")
+ project = replace(repo(), project_id="code-example-hash")
+ listed = {
+ "test-user": [{"id": "personal", "app_id": project.app_id}],
+ project.project_id: [{"id": "current", "app_id": project.app_id}],
+ project.app_id: [
+ {"id": "legacy", "app_id": project.app_id},
+ {"id": "other-app", "app_id": "another-repo"},
+ ],
+ }
+
+ def request(url, key, payload, timeout):
+ identity = next(iter(payload["filters"].values()))
+ return {"results": listed[identity]}, 0, 0
+
+ with (
+ patch.object(memory_core, "_request_json", side_effect=request),
+ patch.object(memory_core, "_delete_memory", return_value=True) as delete,
+ ):
+ result = memory_core.forget_remote_repo(project, include_project_memory=include_project)
+
+ expected = {"personal", "current", "legacy"} if include_project else {"personal"}
+ assert {call.args[2] for call in delete.call_args_list} == expected
+ assert result == {"status": "deleted", "deleted": len(expected)}
+
+
def test_forget_reports_partial_failures(monkeypatch, isolated_env):
monkeypatch.setenv("MEM0_API_KEY", "test-key")
repo = memory_core.RepoContext(
@@ -3956,7 +4333,7 @@ def test_flush_sends_unified_body_with_both_agent_and_user_id(isolated_env, monk
assert sent_body["run_id"] == "s1"
assert "lane" not in sent_body["metadata"]
assert "Save concise repository facts" in sent_body["agent_custom_instructions"]
- assert "invocation that succeeded" in sent_body["agent_custom_instructions"]
+ assert "Write about the repository, not the user" in sent_body["agent_custom_instructions"]
assert "Do not save repository facts" in sent_body["custom_instructions"]
assert sent_body["custom_categories"] == memory_core.CODING_MEMORY_CATEGORIES
store.close()
@@ -4025,7 +4402,8 @@ def test_same_named_folders_at_different_paths_get_different_namespaces():
b = memory_core._project_id("/home/raj/marketing", "local:/home/raj/marketing", "marketing")
assert a != b
assert a.startswith("local-marketing-") and b.startswith("local-marketing-")
- assert memory_core._project_id("/x", "https://github.com/acme/api", "acme-api") == "acme-api"
+ remote_id = memory_core._project_id("/x", "https://github.com/acme/api", "acme-api")
+ assert remote_id.startswith("acme-api-") and remote_id != "acme-api"
def test_relative_directory_is_empty_at_the_root_and_posix_below():
@@ -4171,3 +4549,88 @@ def test_every_write_carries_the_session_run_id(isolated_env, monkeypatch):
assert len(bodies) == 1
assert bodies[0]["run_id"] == "s1"
store.close()
+
+
+def test_shared_transcripts_redact_without_truncating_before_extraction():
+ secret = '"password": "plain-private-value" '
+ prompt = secret + 'x' * 20000
+ answer = secret + '็' * 40000
+ events = [
+ {"kind": "user_prompt", "payload": {"text": prompt}},
+ {"kind": "assistant_stop", "payload": {"transcript_messages": [
+ {"role": "user", "content": prompt},
+ {"role": "assistant", "content": answer},
+ ]}},
+ ]
+ _, structured = memory_core.build_episode(repo(), "s1", "packet", events)
+ messages = memory_core.build_extraction_messages(structured)
+ assert [message["role"] for message in messages] == ["user", "assistant"]
+ assert "plain-private-value" not in json.dumps(structured)
+ assert [message["content"] for message in messages] == [memory_core.redact(prompt), memory_core.redact(answer)]
+
+
+@pytest.mark.parametrize("status", [400, 401, 403, 404, 422])
+def test_event_polling_fails_fast_on_permanent_http_errors(status):
+ error = memory_core.urllib.error.HTTPError("https://example.test", status, "rejected", {}, None)
+ with patch.object(memory_core, "_get_json", side_effect=error), patch.object(memory_core.time, "sleep") as sleep:
+ with pytest.raises(memory_core.urllib.error.HTTPError):
+ memory_core._wait_for_event("https://example.test", "test-key", "event")
+ sleep.assert_not_called()
+
+
+def test_prepare_flush_locks_before_reading_events(isolated_env):
+ store = memory_core.EvidenceStore()
+ store.record_event(repo(), "s1", "user_prompt", {"text": "Explain this."})
+ statements = []
+ store.conn.set_trace_callback(statements.append)
+ store.prepare_flush(repo(), "s1", "session-end")
+ assert statements[0] == "BEGIN IMMEDIATE"
+ assert not store.conn.in_transaction
+ store.close()
+
+
+def test_extraction_batches_bound_individual_messages_without_losing_text():
+ content = '็\\"\n' * 1000
+ messages = [{"role": "assistant", "content": content}]
+ batches = memory_core.extraction_message_batches(messages, max_tokens=200)
+ assert all(memory_core._message_tokens(batch) <= 200 for batch in batches)
+ assert ''.join(message['content'] for batch in batches for message in batch) == content
+
+
+def test_overlapping_subagent_stop_without_id_does_not_guess(isolated_env):
+ store = memory_core.EvidenceStore()
+ store.start_subagent(repo(), "s1", "first", "sidekick", 0)
+ store.start_subagent(repo(), "s1", "second", "sidekick", 0)
+ stopped = store.stop_subagent(repo(), "s1", "", "sidekick", "", "Uncorrelated response")
+ assert stopped not in {"first", "second"}
+ rows = store.conn.execute("SELECT agent_id, stopped_at, final_message FROM sidekick_runs").fetchall()
+ assert all(row["stopped_at"] is None for row in rows if row["agent_id"] in {"first", "second"})
+ assert next(row for row in rows if row["agent_id"] == stopped)["final_message"] == "Uncorrelated response"
+ store.close()
+
+
+def test_delayed_handoff_survives_failed_atomic_rewrite(isolated_env, monkeypatch):
+ import flush_worker
+
+ path = isolated_env / "checkpoint.running"
+ original = {"delay_seconds": 10, "hook_input": {"session_id": "s1"}}
+ path.write_text(json.dumps(original))
+ monkeypatch.setattr(sys, "argv", ["flush_worker.py", str(path)])
+ replace = Path.replace
+
+ def fail_temporary(source, target):
+ if source.suffix == ".tmp":
+ raise OSError("simulated disk failure")
+ return replace(source, target)
+
+ with patch.object(Path, "replace", fail_temporary), patch.object(flush_worker, "checkpoint_session") as checkpoint:
+ with pytest.raises(OSError, match="simulated disk failure"):
+ flush_worker.main()
+ assert json.loads(path.with_suffix(".json").read_text()) == original
+ assert not list(isolated_env.glob("*.tmp"))
+ checkpoint.assert_not_called()
+
+
+def test_json_secret_redaction_handles_escaped_quotes():
+ value = json.dumps({"password": 'prefix"private suffix'})
+ assert json.loads(memory_core.redact(value)) == {"password": "[REDACTED]"}
diff --git a/integrations/claude-code-plugin/tests/test_telemetry.py b/integrations/claude-code-plugin/tests/test_telemetry.py
index a36980426..73bf8f121 100644
--- a/integrations/claude-code-plugin/tests/test_telemetry.py
+++ b/integrations/claude-code-plugin/tests/test_telemetry.py
@@ -1,15 +1,15 @@
from __future__ import annotations
import json
+import os
import sys
from pathlib import Path
from unittest.mock import patch
import pytest
-
-PLUGIN_ROOT = Path(__file__).resolve().parents[1]
-CORE = PLUGIN_ROOT / "core"
+HOST_ROOT = Path(__file__).resolve().parents[1]
+CORE = HOST_ROOT / "core"
sys.path.insert(0, str(CORE))
import memory_core # noqa: E402
@@ -77,6 +77,46 @@ def test_record_hashes_identifiers_and_keeps_no_content(isolated_env):
assert "session-abcdef" not in serialized
+def test_record_rejects_sensitive_properties_at_the_shared_boundary(isolated_env):
+ secret = "sk-eval-12345678901234567890"
+ telemetry.record(
+ "search",
+ prompt=f"remember {secret}",
+ query=secret,
+ api_key=secret,
+ user_id="private-user",
+ note=f"failure contained {secret}",
+ memory_count=2,
+ )
+
+ (event,) = spool_lines()
+ assert event["properties"]["memory_count"] == 2
+ serialized = json.dumps(event)
+ assert secret not in serialized
+ assert "private-user" not in serialized
+ assert not {"prompt", "query", "api_key", "user_id"} & event["properties"].keys()
+
+
+@pytest.mark.parametrize("key", ["password", "token", "secret", "authorization"])
+def test_record_removes_sensitive_keys_from_nested_lists(isolated_env, key):
+ secret = "sk-eval-12345678901234567890"
+ telemetry.record(
+ "search",
+ details=[
+ {key: "plain-value", "count": 2},
+ {"nested": {key.upper(): "plain-value", "ok": True}},
+ [f"failure contained {secret}"],
+ ],
+ )
+
+ (event,) = spool_lines()
+ assert event["properties"]["details"] == [
+ {"count": 2},
+ {"nested": {"ok": True}},
+ ["failure contained [REDACTED]"],
+ ]
+
+
def test_record_stops_appending_past_the_spool_cap(isolated_env):
spool = memory_core.data_dir() / "telemetry.jsonl"
spool.parent.mkdir(parents=True, exist_ok=True)
@@ -159,9 +199,11 @@ def test_a_stale_claim_is_reclaimed(isolated_env, monkeypatch):
telemetry.record("search")
orphan = telemetry._claim_spool()
assert orphan is not None
- monkeypatch.setattr(
- telemetry.time, "time", lambda: orphan.stat().st_mtime + telemetry.CLAIM_STALE_SECONDS + 1
- )
+ # Frozen rather than re-stat'd per call: flush() drains the live spool and
+ # then looks for parked claims in the same run, so by the second look this
+ # file no longer exists.
+ stale_now = orphan.stat().st_mtime + telemetry.CLAIM_STALE_SECONDS + 1
+ monkeypatch.setattr(telemetry.time, "time", lambda: stale_now)
with patch.object(telemetry, "_post", lambda payload, url: True):
assert telemetry.flush() == 1
@@ -171,9 +213,13 @@ def test_an_expired_claim_is_dropped(isolated_env, monkeypatch):
telemetry.record("search")
orphan = telemetry._claim_spool()
assert orphan is not None
- monkeypatch.setattr(
- telemetry.time, "time", lambda: orphan.stat().st_mtime + telemetry.CLAIM_EXPIRY_SECONDS + 1
- )
+ expired_now = orphan.stat().st_mtime + telemetry.CLAIM_EXPIRY_SECONDS + 1
+ monkeypatch.setattr(telemetry.time, "time", lambda: expired_now)
+ # Expiry now only discards a batch that was genuinely retried and failed,
+ # so age alone is not enough โ age it past the attempt budget too.
+ retried = orphan.parent / orphan.name.replace("-a0.", f"-a{telemetry.MAX_CLAIM_ATTEMPTS}.")
+ orphan.replace(retried)
+ os.utime(retried, (expired_now, expired_now - telemetry.CLAIM_EXPIRY_SECONDS - 1))
assert telemetry._claim_spool() is None
assert not list(memory_core.data_dir().glob("telemetry-*.sending"))
@@ -219,12 +265,150 @@ def test_an_unresolvable_key_falls_back_to_the_anonymous_id(isolated_env, monkey
assert telemetry.resolve_distinct_id()[0].startswith("code-anon-")
-def test_is_first_run_flips_after_the_first_identity_write(isolated_env):
+def test_logging_out_does_not_leave_events_on_the_previous_account(isolated_env, monkeypatch):
+ """Review finding: clearing the email kept an id already merged into a person.
+
+ The anonymous id is offered to PostHog as $anon_distinct_id on first sign-in,
+ and that merge is permanent. Keeping it after the key goes away means every
+ later anonymous event lands on the account that just left.
+ """
+ # Run anonymously first, which is the only way an id exists to be merged.
+ merged = telemetry.anonymous_id()
+
+ monkeypatch.setenv("MEM0_API_KEY", "key-for-account-a")
+ with patch.object(telemetry, "_resolve_email", lambda key: "a@example.com"):
+ identified, alias = telemetry.resolve_distinct_id()
+ assert identified == "a@example.com"
+ assert alias == merged, "the anonymous id was merged into this account"
+
+ monkeypatch.delenv("MEM0_API_KEY", raising=False)
+ after_logout, logout_alias = telemetry.resolve_distinct_id()
+
+ assert after_logout.startswith("code-anon-")
+ assert after_logout != merged, "reused an id already merged into the previous account"
+ assert logout_alias == ""
+ assert "aliased" not in telemetry._read_identity(), "rotated id must be aliasable again"
+
+
+def test_a_changed_key_that_will_not_resolve_rotates_the_anonymous_id(isolated_env, monkeypatch):
+ """Same leak by the other route: fingerprint disagrees and the lookup fails."""
+ merged = telemetry.anonymous_id()
+ monkeypatch.setenv("MEM0_API_KEY", "key-for-account-a")
+ with patch.object(telemetry, "_resolve_email", lambda key: "a@example.com"):
+ telemetry.resolve_distinct_id()
+
+ monkeypatch.setenv("MEM0_API_KEY", "key-for-account-b")
+ with patch.object(telemetry, "_resolve_email", lambda key: ""):
+ after, alias = telemetry.resolve_distinct_id()
+
+ assert after.startswith("code-anon-")
+ assert after != merged
+ assert alias == ""
+ assert "email" not in telemetry._read_identity()
+
+
+def test_a_legacy_cached_email_is_verified_before_the_key_is_bound(isolated_env, monkeypatch):
+ """Review finding: a key changed before upgrading bound the wrong account.
+
+ Rows written before fingerprints existed carry an email and no fingerprint.
+ Adopting the current key without checking pinned that key to the previous
+ account's email, and every run after that agreed with itself.
+ """
+ telemetry._write_identity({"email": "old@example.com", "anonymous_id": "code-anon-seed"})
+ monkeypatch.setenv("MEM0_API_KEY", "key-for-account-b")
+
+ with patch.object(telemetry, "_resolve_email", lambda key: "new@example.com"):
+ resolved, alias = telemetry.resolve_distinct_id()
+
+ assert resolved == "new@example.com"
+ assert alias == "", "email to email must never alias; it merges two real people"
+ stored = telemetry._read_identity()
+ assert stored["email"] == "new@example.com"
+ assert stored["key_fingerprint"] == telemetry._digest("key-for-account-b")
+
+
+def test_a_legacy_row_keeps_working_when_the_account_cannot_be_checked(isolated_env, monkeypatch):
+ """Firewalled users must not lose attribution, and must not bind unverified.
+
+ The same network that fails /v1/ping/ fails the PostHog POST, so nothing is
+ delivered under the unverified identity while this holds.
+ """
+ telemetry._write_identity({"email": "old@example.com"})
+ monkeypatch.setenv("MEM0_API_KEY", "key-for-account-b")
+
+ with patch.object(telemetry, "_resolve_email", lambda key: ""):
+ resolved, _ = telemetry.resolve_distinct_id()
+
+ assert resolved == "old@example.com"
+ assert "key_fingerprint" not in telemetry._read_identity(), "bound an unverified key"
+
+
+def test_a_failed_upgrade_claim_can_be_retried(isolated_env, monkeypatch):
+ """Review finding: a failed rewrite left the sentinel and suppressed forever.
+
+ claim_version_change returns early on FileExistsError, and the marker still
+ holds the old version, so the upgrade for that version was never recorded
+ again on that machine.
+ """
+ telemetry.claim_install()
+ state_path = memory_core.data_dir() / "install-state.json"
+ state = json.loads(state_path.read_text())
+ state["plugin_version"] = "0.0.1-old"
+ state_path.write_text(json.dumps(state), encoding="utf-8")
+
+ real_replace = Path.replace
+
+ def failing_replace(self, target):
+ raise OSError("disk full")
+
+ monkeypatch.setattr(Path, "replace", failing_replace)
+ assert telemetry.claim_version_change() is None
+
+ monkeypatch.setattr(Path, "replace", real_replace)
+ assert telemetry.claim_version_change() == "0.0.1-old", "sentinel suppressed the retry"
+
+
+def test_first_run_is_not_flipped_by_writing_the_identity_file(isolated_env):
+ """The identity file is written by a successful flush, not by recording.
+
+ Keying first-run off it meant an offline user recorded code.install on every
+ session forever, and every 0.2.x user recorded one on their first 0.3.x run.
+ """
assert telemetry.is_first_run()
telemetry.anonymous_id()
+ assert telemetry.is_first_run()
+
+
+def test_claiming_install_ends_first_run(isolated_env):
+ assert telemetry.claim_install() == "install"
assert not telemetry.is_first_run()
+def test_install_can_only_be_claimed_once(isolated_env):
+ """Two sessions starting together must not both record an install."""
+ assert telemetry.claim_install() == "install"
+ assert telemetry.claim_install() is None
+
+
+def test_a_populated_data_dir_reads_as_an_upgrade(isolated_env):
+ """A fresh install has an empty data directory; anything else predates it."""
+ data_dir = memory_core.data_dir()
+ data_dir.mkdir(parents=True, exist_ok=True)
+ (data_dir / "requirements.txt").write_text("mem0ai\n", encoding="utf-8")
+ assert telemetry.claim_install() == "upgrade"
+
+
+def test_a_version_change_is_claimed_once(isolated_env):
+ telemetry.claim_install()
+ state_path = memory_core.data_dir() / "install-state.json"
+ state = json.loads(state_path.read_text())
+ state["plugin_version"] = "0.0.1-old"
+ state_path.write_text(json.dumps(state), encoding="utf-8")
+
+ assert telemetry.claim_version_change() == "0.0.1-old"
+ assert telemetry.claim_version_change() is None
+
+
def test_spawn_flush_does_nothing_without_a_spool(isolated_env):
with patch.object(telemetry.subprocess, "Popen") as popen:
assert telemetry.spawn_flush() is False
@@ -234,3 +418,114 @@ def test_spawn_flush_does_nothing_without_a_spool(isolated_env):
with patch.object(telemetry.subprocess, "Popen") as popen:
assert telemetry.spawn_flush() is True
popen.assert_called_once()
+
+
+def test_salt_is_stable_across_processes(isolated_env):
+ """Hooks are separate short-lived processes; one repo must hash one way.
+
+ An unlocked read-modify-write let each process mint its own salt, so a
+ repository hashed several ways in the window before one writer won.
+ """
+ import subprocess as sp
+
+ core = str(Path(__file__).resolve().parents[1] / "core")
+ script = (
+ f"import sys; sys.path.insert(0, {core!r})\n"
+ "import telemetry\n"
+ "print(telemetry._install_salt())"
+ )
+ env = {**os.environ, "MEM0_CODE_DATA_DIR": str(memory_core.data_dir())}
+ salts = {
+ sp.run([sys.executable, "-c", script], capture_output=True, text=True, env=env).stdout.strip()
+ for _ in range(4)
+ }
+ assert len(salts) == 1, f"one repo hashed {len(salts)} ways: {salts}"
+
+
+def test_salt_does_not_touch_the_identity_file(isolated_env):
+ """The identity file is is_first_run's marker and the sender's email store.
+
+ Writing the salt into it would create it from record(), suppressing the
+ install event, and would race resolve_distinct_id, which holds a stale copy
+ of that dict across a network call.
+ """
+ telemetry._install_salt()
+ assert not telemetry._identity_path().exists()
+
+
+def test_no_salt_means_no_hash_rather_than_an_unsalted_one(isolated_env, monkeypatch):
+ """A read-only data dir drops the property; it must not emit a weak digest.
+
+ The previous fallback was a digest of the salt file's own path, which an
+ attacker can compute, memoized for the whole process. A property named
+ repo_hash carrying an effectively unsalted digest is worse than no property:
+ it reads as protected and is not.
+ """
+ telemetry._salt_cache = ""
+ monkeypatch.setattr(telemetry.os, "open", lambda *a, **k: (_ for _ in ()).throw(OSError("read-only")))
+
+ assert telemetry._install_salt() == ""
+ assert telemetry._scoped_digest("git@github.com:acme/secret.git") == ""
+
+
+def test_a_half_written_salt_is_never_visible_to_another_process(isolated_env, monkeypatch):
+ """The window this closes: file created, value not yet written.
+
+ O_CREAT|O_EXCL then write leaves the name present and empty in between. A
+ hook reading it there used to get "", fall back to the path digest and cache
+ that for its whole run, so the same repo hashed two ways depending on timing.
+ Publishing by link means the name either does not exist or is complete.
+ """
+ telemetry._salt_cache = ""
+ salt_path = telemetry._salt_path()
+ observed = []
+
+ real_link = telemetry.os.link
+
+ def observing_link(source, target):
+ # Stand where the racing reader stands: after the temp file is written,
+ # before the real name exists.
+ observed.append(salt_path.exists())
+ return real_link(source, target)
+
+ monkeypatch.setattr(telemetry.os, "link", observing_link)
+ salt = telemetry._install_salt()
+
+ assert observed == [False], "the salt name existed before it held a value"
+ assert len(salt) == 32
+ assert salt_path.read_text(encoding="utf-8").strip() == salt
+
+
+def test_a_filesystem_without_hardlinks_still_gets_a_salt(isolated_env, monkeypatch):
+ """Publishing by link must not become a silent loss of the hashes.
+
+ Some network mounts and container volumes reject os.link. Returning ""
+ there would drop repo_hash and session_hash on every run for that whole
+ cohort, which is a bigger loss than the narrow race the link closes.
+ """
+ telemetry._salt_cache = ""
+ monkeypatch.setattr(
+ telemetry.os, "link", lambda src, dst: (_ for _ in ()).throw(OSError(38, "not implemented"))
+ )
+
+ salt = telemetry._install_salt()
+
+ assert len(salt) == 32, "no salt on a filesystem without hardlinks"
+ assert telemetry._salt_path().read_text(encoding="utf-8").strip() == salt
+ assert telemetry._scoped_digest("git@github.com:acme/x.git") != ""
+ assert not list(telemetry._salt_path().parent.glob("telemetry-salt.*.tmp"))
+
+
+def test_a_concurrent_writer_does_not_clobber_the_published_salt(isolated_env):
+ """Second process to finish must adopt the first one's salt, not replace it.
+
+ os.link rather than os.replace is what makes losing the race harmless.
+ """
+ telemetry._salt_cache = ""
+ first = telemetry._install_salt()
+
+ telemetry._salt_cache = ""
+ second = telemetry._install_salt()
+
+ assert second == first
+ assert not list(telemetry._salt_path().parent.glob("telemetry-salt.*.tmp")), "temp file left behind"
diff --git a/integrations/codex-plugin/.codex-plugin/plugin.json b/integrations/codex-plugin/.codex-plugin/plugin.json
new file mode 100644
index 000000000..e91eca25a
--- /dev/null
+++ b/integrations/codex-plugin/.codex-plugin/plugin.json
@@ -0,0 +1,13 @@
+{
+ "name": "mem0",
+ "version": "0.3.3",
+ "description": "Cross-session memory and token savings for coding agents.",
+ "author": { "name": "Mem0", "email": "support@mem0.ai" },
+ "homepage": "https://docs.mem0.ai/integrations/codex",
+ "repository": "https://github.com/mem0ai/mem0",
+ "license": "Apache-2.0",
+ "keywords": ["memory", "coding-agents", "continual-learning", "token-efficiency"],
+ "skills": "./skills/",
+ "hooks": "./hooks/hooks.json",
+ "mcpServers": "./.mcp.json"
+}
diff --git a/integrations/codex-plugin/.mcp.json b/integrations/codex-plugin/.mcp.json
new file mode 100644
index 000000000..00daa05bd
--- /dev/null
+++ b/integrations/codex-plugin/.mcp.json
@@ -0,0 +1,19 @@
+{
+ "mcpServers": {
+ "mem0": {
+ "type": "stdio",
+ "command": "python3",
+ "args": ["./core/mcp_server.py"],
+ "cwd": ".",
+ "env_vars": [
+ "MEM0_API_KEY",
+ "MEM0_API_URL",
+ "MEM0_CODE_USER_ID",
+ "MEM0_USER_ID",
+ "MEM0_RESOLVED_USER_ID",
+ "MEM0_PROJECT_ID",
+ "MEM0_TELEMETRY"
+ ]
+ }
+ }
+}
diff --git a/integrations/codex-plugin/core/_harness_id.py b/integrations/codex-plugin/core/_harness_id.py
new file mode 100644
index 000000000..47938ee08
--- /dev/null
+++ b/integrations/codex-plugin/core/_harness_id.py
@@ -0,0 +1,11 @@
+"""Generated by integrations/agent-plugin-core/build/build.py. Do not edit."""
+
+HARNESS_ID = "codex"
+SOURCE_TAG = "CODEX_PLUGIN"
+
+# Platform-side vocabulary (mem0_event.source + X-Application). The whole
+# plugin family is one source; which editor it runs in is the application.
+# An empty application means the host is unknown, and memory_core omits
+# the header entirely rather than sending a placeholder.
+PLATFORM_SOURCE = "MEM0_PLUGIN"
+PLATFORM_APPLICATION = "codex"
diff --git a/integrations/codex-plugin/core/flush_worker.py b/integrations/codex-plugin/core/flush_worker.py
new file mode 100644
index 000000000..6f7b9ecb2
--- /dev/null
+++ b/integrations/codex-plugin/core/flush_worker.py
@@ -0,0 +1,100 @@
+#!/usr/bin/env python3
+"""Detached remote checkpoint worker.
+
+Claude Code may cancel SessionEnd hooks as a print-mode process exits. The hook
+therefore persists its input first and launches this process in a new session.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import sys
+import time
+from pathlib import Path
+
+import telemetry
+from memory_core import (
+ EvidenceStore,
+ checkpoint_session,
+ configure_harness,
+ touch_handoff_heartbeat,
+)
+
+
+def main() -> int:
+ if len(sys.argv) != 2:
+ return 2
+ handoff_path = Path(sys.argv[1])
+ os.environ["MEM0_CODE_HANDOFF_PATH"] = str(handoff_path)
+ harness = os.environ.get("MEM0_PLUGIN_HARNESS")
+ if harness:
+ source_tag = os.environ.get("MEM0_PLUGIN_SOURCE_TAG", "")
+ configure_harness(
+ harness,
+ env_prefix=os.environ.get("MEM0_PLUGIN_ENV_PREFIX", ""),
+ data_dir_name=os.environ.get("MEM0_PLUGIN_DATA_DIR_NAME", ""),
+ source_tag=source_tag,
+ )
+ telemetry.init(harness=harness, source_tag=source_tag.upper())
+ completed = False
+ try:
+ payload = json.loads(handoff_path.read_text(encoding="utf-8"))
+ delay = float(payload.get("delay_seconds") or 0)
+ if delay > 0:
+ payload.pop("delay_seconds", None)
+ temporary = handoff_path.with_suffix(f".{os.getpid()}.tmp")
+ try:
+ temporary.write_text(json.dumps(payload), encoding="utf-8")
+ temporary.replace(handoff_path)
+ finally:
+ temporary.unlink(missing_ok=True)
+ time.sleep(delay)
+ if not handoff_path.exists():
+ return 0
+ hook_input = payload.get("hook_input") or {}
+ reason = str(payload.get("reason") or "checkpoint")
+ wait_for_inflight = bool(payload.get("wait_for_inflight"))
+ store = EvidenceStore()
+ try:
+ if wait_for_inflight:
+ session_id = str(
+ hook_input.get("session_id") or "unknown-session"
+ )
+ repo = store.repo_for_session(session_id, hook_input.get("cwd"))
+ deadline = time.monotonic() + float(
+ os.environ.get("MEM0_CODE_EXTRACTION_WAIT_SECONDS", "120")
+ )
+ while (
+ store.has_inflight_flush(repo.identity, session_id)
+ and time.monotonic() < deadline
+ ):
+ touch_handoff_heartbeat()
+ time.sleep(0.25)
+ # Hooks capture the conversation before handoff; the worker only flushes it.
+ result = checkpoint_session(store, hook_input, reason)
+ print(json.dumps(result, sort_keys=True), flush=True)
+ completed = result.get("status") in {
+ "semantic-succeeded",
+ "explicitly-stored",
+ "nothing-to-flush",
+ }
+ finally:
+ store.close()
+ return 0
+ finally:
+ telemetry.flush()
+ if completed:
+ try:
+ handoff_path.unlink()
+ except OSError:
+ pass
+ elif handoff_path.suffix == ".running":
+ try:
+ handoff_path.replace(handoff_path.with_suffix(".json"))
+ except OSError:
+ pass
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/integrations/codex-plugin/core/hook_runner.py b/integrations/codex-plugin/core/hook_runner.py
new file mode 100644
index 000000000..b3d8a3210
--- /dev/null
+++ b/integrations/codex-plugin/core/hook_runner.py
@@ -0,0 +1,388 @@
+"""Shared hook orchestration for all Mem0 agent plugins."""
+
+from __future__ import annotations
+
+import argparse
+import hashlib
+import json
+import os
+import subprocess
+import sys
+import time
+import uuid
+from pathlib import Path
+
+import telemetry
+from memory_core import (
+ EvidenceStore,
+ _session_id,
+ api_key,
+ bounded,
+ cache_plugin_api_key,
+ checkpoint_session,
+ clear_stale_api_key_cache,
+ configure_harness,
+ data_dir,
+ detached_process_kwargs,
+ format_context,
+ harness_config,
+ record_session_start,
+ record_tool,
+ record_user_prompt,
+ redact,
+ search_memories,
+)
+
+STALE_RUNNING_SECONDS = 300
+PENDING_EXPIRY_SECONDS = 7 * 24 * 60 * 60
+PENDING_LAUNCH_LIMIT = 5
+DEFAULT_IDLE_FLUSH_SECONDS = 300
+
+_core_dir: Path = Path(__file__).resolve().parent
+
+
+def read_hook_input() -> dict:
+ try:
+ value = json.load(sys.stdin)
+ return value if isinstance(value, dict) else {}
+ except (json.JSONDecodeError, OSError):
+ return {}
+
+
+def default_record_stop(store: EvidenceStore, hook_input: dict):
+ """Record the assistant's response without transcript parsing."""
+ session_id = _session_id(hook_input)
+ repo = store.repo_for_session(session_id, hook_input.get("cwd"))
+ message = redact(hook_input.get("last_assistant_message", "")).strip()
+ if message:
+ store.record_assistant_response(repo, session_id, message)
+ return repo, session_id
+
+
+def first_prompt_memory_output(store: EvidenceStore, hook_input: dict) -> dict:
+ """Search once before the agent handles the first prompt in a session."""
+ repo, session_id, prompt, is_first_prompt = record_user_prompt(store, hook_input)
+ if not is_first_prompt:
+ return {}
+ try:
+ minimum_query_chars = int(os.environ.get("MEM0_CODE_MIN_QUERY_CHARS", "20"))
+ except ValueError:
+ minimum_query_chars = 20
+ if len(prompt.strip()) < max(minimum_query_chars, 1):
+ return {}
+ result = search_memories(
+ store, repo, session_id, bounded(prompt, 6000),
+ top_k=5, operation="first-prompt-search", timeout=2,
+ )
+ if not result.memories:
+ return {}
+ context = format_context(
+ result.memories,
+ "Mem0 found these relevant memories from earlier work in this repository:",
+ )
+ telemetry.record(
+ "context_injected",
+ repo=repo, session_id=session_id, trigger="first-prompt",
+ memory_count=len(result.memories), context_chars=len(context),
+ prompt_chars=len(prompt),
+ )
+ return {
+ "hookSpecificOutput": {
+ "hookEventName": "UserPromptSubmit",
+ "additionalContext": context,
+ },
+ }
+
+
+def _launch_handoff(handoff_path: Path) -> bool:
+ running_path = handoff_path.with_suffix(".running")
+ try:
+ handoff_path.replace(running_path)
+ except OSError:
+ return False
+ worker = _core_dir / "flush_worker.py"
+ log_path = data_dir() / "flush-worker.log"
+ log_handle = open(log_path, "a", encoding="utf-8")
+ harness = harness_config()
+ child_env = os.environ.copy()
+ child_env.update(
+ {
+ "MEM0_CODE_DATA_DIR": str(data_dir()),
+ "MEM0_PLUGIN_HARNESS": harness["name"],
+ "MEM0_PLUGIN_ENV_PREFIX": harness["env_prefix"],
+ "MEM0_PLUGIN_DATA_DIR_NAME": harness["data_dir_name"],
+ "MEM0_PLUGIN_SOURCE_TAG": harness["source_tag"],
+ }
+ )
+ try:
+ subprocess.Popen(
+ [sys.executable, str(worker), str(running_path)],
+ stdin=subprocess.DEVNULL,
+ stdout=log_handle, stderr=log_handle,
+ close_fds=True,
+ env=child_env,
+ **detached_process_kwargs(),
+ )
+ finally:
+ log_handle.close()
+ return True
+
+
+def recover_pending_handoffs() -> int:
+ pending_dir = data_dir() / "pending"
+ pending_dir.mkdir(parents=True, exist_ok=True)
+ now = time.time()
+ for running in pending_dir.glob("*.running"):
+ try:
+ if now - running.stat().st_mtime > STALE_RUNNING_SECONDS:
+ running.replace(running.with_suffix(".json"))
+ except OSError:
+ continue
+ recoverable = []
+ for handoff in pending_dir.glob("*.json"):
+ try:
+ age = now - handoff.stat().st_mtime
+ except OSError:
+ continue
+ if age > PENDING_EXPIRY_SECONDS:
+ handoff.unlink(missing_ok=True)
+ continue
+ recoverable.append((age, handoff))
+ recoverable.sort(key=lambda item: item[0], reverse=True)
+ launched = 0
+ for _, handoff in recoverable[:PENDING_LAUNCH_LIMIT]:
+ launched += int(_launch_handoff(handoff))
+ return launched
+
+
+def refresh_pending_handoffs() -> None:
+ pending_dir = data_dir() / "pending"
+ if not pending_dir.is_dir():
+ return
+ for pattern in ("*.json", "*.running"):
+ for handoff in pending_dir.glob(pattern):
+ try:
+ os.utime(handoff)
+ except OSError:
+ continue
+
+
+def hand_off_flush(
+ hook_input: dict, reason: str, *, wait_for_inflight: bool = False,
+) -> None:
+ pending_dir = data_dir() / "pending"
+ pending_dir.mkdir(parents=True, exist_ok=True)
+ material = (
+ f"{hook_input.get('cwd', '')}\0{hook_input.get('session_id', '')}\0{reason}"
+ )
+ digest = hashlib.sha256(material.encode()).hexdigest()[:24]
+ handoff_path = pending_dir / f"{digest}-{uuid.uuid4().hex[:8]}.json"
+ temporary_path = handoff_path.with_suffix(".tmp")
+ temporary_path.write_text(
+ json.dumps({
+ "hook_input": hook_input,
+ "reason": reason,
+ "wait_for_inflight": wait_for_inflight,
+ }),
+ encoding="utf-8",
+ )
+ temporary_path.replace(handoff_path)
+ _launch_handoff(handoff_path)
+
+
+def automatic_flush_enabled() -> bool:
+ return os.environ.get("MEM0_CODE_AUTO_FLUSH", "true").lower() in {
+ "1", "true", "yes", "on",
+ }
+
+
+def schedule_periodic_checkpoint(
+ store: EvidenceStore, hook_input: dict, repo, session_id: str,
+) -> bool:
+ if (
+ not automatic_flush_enabled()
+ or not api_key()
+ or not store.checkpoint_due(repo.identity, session_id)
+ ):
+ return False
+ if store.prepare_flush(repo, session_id, "periodic") is None:
+ return False
+ hand_off_flush(hook_input, "periodic")
+ return True
+
+
+def _idle_flush_seconds() -> int:
+ try:
+ return max(
+ int(os.environ.get("MEM0_CODE_IDLE_FLUSH_SECONDS", str(DEFAULT_IDLE_FLUSH_SECONDS))),
+ 0,
+ )
+ except ValueError:
+ return DEFAULT_IDLE_FLUSH_SECONDS
+
+
+def schedule_idle_flush(
+ store: EvidenceStore, hook_input: dict, repo, session_id: str,
+) -> bool:
+ delay = _idle_flush_seconds()
+ if delay <= 0 or not automatic_flush_enabled() or not api_key():
+ return False
+ if store.has_inflight_flush(repo.identity, session_id):
+ return False
+ if not store.has_unflushed_events(repo.identity, session_id):
+ return False
+ pending_dir = data_dir() / "pending"
+ pending_dir.mkdir(parents=True, exist_ok=True)
+ material = f"idle\0{hook_input.get('cwd', '')}\0{hook_input.get('session_id', '')}"
+ digest = hashlib.sha256(material.encode()).hexdigest()[:24]
+ for old in pending_dir.glob(f"idle-{digest}*"):
+ old.unlink(missing_ok=True)
+ handoff_path = pending_dir / f"idle-{digest}-{uuid.uuid4().hex[:8]}.json"
+ temporary_path = handoff_path.with_suffix(".tmp")
+ temporary_path.write_text(
+ json.dumps({
+ "hook_input": hook_input,
+ "reason": "idle",
+ "delay_seconds": delay,
+ }),
+ encoding="utf-8",
+ )
+ temporary_path.replace(handoff_path)
+ _launch_handoff(handoff_path)
+ return True
+
+
+def log_failure(exc: Exception) -> None:
+ try:
+ log_path = data_dir() / "plugin-errors.log"
+ with log_path.open("a", encoding="utf-8") as handle:
+ handle.write(f"{time.time():.3f} {type(exc).__name__}: {exc}\n")
+ except OSError:
+ pass
+
+
+def run(
+ *,
+ record_stop_fn=None,
+ extra_actions: dict | None = None,
+ data_dir_env: str = "MEM0_PLUGIN_DATA_DIR",
+ automatic_flush_reasons: set | None = None,
+) -> int:
+ if record_stop_fn is None:
+ record_stop_fn = default_record_stop
+ if automatic_flush_reasons is None:
+ automatic_flush_reasons = {"session-end"}
+
+ base_actions = ["session-start", "user-prompt", "post-tool", "stop", "flush"]
+ all_actions = base_actions + list((extra_actions or {}).keys())
+
+ parser = argparse.ArgumentParser()
+ parser.add_argument("action", choices=all_actions)
+ parser.add_argument("--reason", default="manual")
+ parser.add_argument("--plugin-data-dir", default="")
+ parser.add_argument("--harness", default="")
+ args = parser.parse_args()
+
+ if args.harness:
+ configure_harness(args.harness)
+ telemetry.init(harness=args.harness)
+
+ if args.plugin_data_dir:
+ os.environ[data_dir_env] = args.plugin_data_dir
+
+ # Snapshot BEFORE anything writes to the data dir: cache_plugin_api_key
+ # writes `api-key` and EvidenceStore creates `evidence.sqlite3`, so asking
+ # after them always saw content and every fresh install reported an upgrade.
+ data_dir_was_empty = telemetry.data_dir_was_empty()
+
+ cache_plugin_api_key()
+ if args.action == "session-start":
+ clear_stale_api_key_cache()
+
+ hook_input = read_hook_input()
+ store = EvidenceStore()
+ try:
+ if store.is_paused():
+ if args.action == "session-start":
+ refresh_pending_handoffs()
+ telemetry.record("session_start", paused=True)
+ telemetry.spawn_flush()
+ return 0
+
+ if args.action == "session-start":
+ # Claims the marker atomically and says which event to record, so a
+ # second session starting alongside this one cannot record it too.
+ first_event = telemetry.claim_install(was_empty=data_dir_was_empty)
+ if first_event == "install":
+ telemetry.record("install")
+ elif first_event == "upgrade":
+ # First run after a build that never wrote the marker; the
+ # predecessor version was never recorded anywhere.
+ telemetry.record("upgrade", from_version="pre-0.3")
+ else:
+ previous = telemetry.claim_version_change()
+ if previous:
+ telemetry.record("upgrade", from_version=previous)
+ recovered = recover_pending_handoffs()
+ record_session_start(store, hook_input)
+ if recovered:
+ telemetry.record("handoff_recovered", count=recovered)
+ telemetry.spawn_flush()
+ elif args.action == "user-prompt":
+ output = first_prompt_memory_output(store, hook_input)
+ if output:
+ print(json.dumps(output))
+ elif args.action == "post-tool":
+ record_tool(store, hook_input)
+ elif args.action == "stop":
+ repo, session_id = record_stop_fn(store, hook_input)
+ if not schedule_periodic_checkpoint(store, hook_input, repo, session_id):
+ schedule_idle_flush(store, hook_input, repo, session_id)
+ elif args.action == "flush":
+ automatic = args.reason in automatic_flush_reasons
+ if automatic and not automatic_flush_enabled():
+ return 0
+ if args.reason == "session-end":
+ record_stop_fn(store, hook_input)
+ if os.environ.get("MEM0_CODE_SYNC_FLUSH") == "1":
+ print(json.dumps(checkpoint_session(store, hook_input, args.reason)))
+ else:
+ session_id = str(hook_input.get("session_id") or "unknown-session")
+ repo = store.repo_for_session(session_id, hook_input.get("cwd"))
+ already_running = store.has_inflight_flush(repo.identity, session_id)
+ if already_running and args.reason == "session-end":
+ hand_off_flush(hook_input, args.reason, wait_for_inflight=True)
+ elif not already_running and store.prepare_flush(
+ repo, session_id, args.reason,
+ ) is not None:
+ hand_off_flush(hook_input, args.reason)
+ elif extra_actions and args.action in extra_actions:
+ result = extra_actions[args.action](store, hook_input)
+ if result:
+ print(json.dumps(result))
+ finally:
+ store.close()
+ return 0
+
+
+def entry_point(
+ *,
+ record_stop_fn=None,
+ extra_actions: dict | None = None,
+ data_dir_env: str = "MEM0_PLUGIN_DATA_DIR",
+ automatic_flush_reasons: set | None = None,
+) -> None:
+ try:
+ raise SystemExit(run(
+ record_stop_fn=record_stop_fn,
+ extra_actions=extra_actions,
+ data_dir_env=data_dir_env,
+ automatic_flush_reasons=automatic_flush_reasons,
+ ))
+ except Exception as exc:
+ log_failure(exc)
+ raise SystemExit(0)
+
+
+if __name__ == "__main__":
+ entry_point()
diff --git a/integrations/codex-plugin/core/mcp_server.py b/integrations/codex-plugin/core/mcp_server.py
new file mode 100644
index 000000000..a0b73cb79
--- /dev/null
+++ b/integrations/codex-plugin/core/mcp_server.py
@@ -0,0 +1,240 @@
+#!/usr/bin/env python3
+"""Expose Mem0's memory search as one local coding-agent tool."""
+
+from __future__ import annotations
+
+import json
+import os
+import sys
+from typing import Any
+
+import telemetry
+from memory_core import (
+ CODING_MEMORY_CATEGORY_NAMES,
+ PLUGIN_VERSION,
+ SEARCH_SCOPES,
+ format_search_result,
+ resolve_repo,
+ search_memories,
+)
+
+PROTOCOL_VERSION = "2024-11-05"
+TOOL_NAME = "search_memories"
+TOOL_DESCRIPTION = (
+ "Search memories from earlier work in this repository. Use it before "
+ "repeating investigation or when earlier decisions, fixes, commands, or "
+ "results may help."
+)
+TOOL_SCHEMA = {
+ "type": "object",
+ "properties": {
+ "query": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 2000,
+ "description": "A direct question about earlier work in this repository.",
+ },
+ "top_k": {
+ "type": "integer",
+ "minimum": 1,
+ "maximum": 20,
+ "description": "Maximum memories to return. Uses Mem0's configured default when omitted.",
+ },
+ "category": {
+ "type": "string",
+ "enum": list(CODING_MEMORY_CATEGORY_NAMES),
+ "description": "Optional memory category. Omit to search every category.",
+ },
+ "scope": {
+ "type": "string",
+ "enum": list(SEARCH_SCOPES),
+ "description": (
+ "Which memories to search. 'repo' (default) is the whole repository's "
+ "shared memory plus your own preferences, 'dir' narrows the shared "
+ "part to the current directory, 'mine' is your preferences alone."
+ ),
+ },
+ "run_id": {
+ "type": "string",
+ "minLength": 1,
+ "description": (
+ "Optional coding-agent session ID. With any scope, restricts results to memories "
+ "saved in that session. Omit to recall memories across sessions."
+ ),
+ },
+ },
+ "required": ["query"],
+ "additionalProperties": False,
+}
+
+
+class ToolInputError(ValueError):
+ pass
+
+
+def _validate_arguments(
+ arguments: Any,
+) -> tuple[str, int | None, str | None, str | None, str | None]:
+ if not isinstance(arguments, dict):
+ raise ToolInputError("Search arguments must be an object.")
+
+ unknown = set(arguments) - {"query", "top_k", "category", "scope", "run_id"}
+ if unknown:
+ raise ToolInputError(f"Unknown search argument: {sorted(unknown)[0]}")
+
+ query = arguments.get("query")
+ if not isinstance(query, str) or not query.strip():
+ raise ToolInputError("query must be a non-empty string.")
+ query = query.strip()
+ if len(query) > 2000:
+ raise ToolInputError("query must be at most 2,000 characters.")
+
+ top_k = arguments.get("top_k")
+ if top_k is not None and (
+ isinstance(top_k, bool) or not isinstance(top_k, int) or not 1 <= top_k <= 20
+ ):
+ raise ToolInputError("top_k must be an integer from 1 to 20.")
+
+ category = arguments.get("category")
+ if category is not None and category not in CODING_MEMORY_CATEGORY_NAMES:
+ raise ToolInputError("category must be one of Mem0's supported categories.")
+
+ scope = arguments.get("scope")
+ if scope is not None and scope not in SEARCH_SCOPES:
+ raise ToolInputError(f"scope must be one of {list(SEARCH_SCOPES)}.")
+
+ run_id = arguments.get("run_id")
+ if run_id is not None:
+ if not isinstance(run_id, str) or not run_id.strip():
+ raise ToolInputError("run_id must be a non-empty string.")
+ run_id = run_id.strip()
+
+ return query, top_k, category, scope, run_id
+
+
+def call_search_memories(arguments: Any, cwd: str | None = None) -> str:
+ query, top_k, category, scope, run_id = _validate_arguments(arguments)
+ repo = resolve_repo(cwd or os.environ.get("CLAUDE_PROJECT_DIR") or os.getcwd())
+ result = search_memories(
+ None,
+ repo,
+ None,
+ query,
+ top_k=top_k,
+ category=category,
+ scope=scope,
+ run_id=run_id,
+ operation="mcp-search",
+ )
+ return format_search_result(result)
+
+
+def _workspace_cwd(params: dict[str, Any]) -> str | None:
+ meta = params.get("_meta")
+ if not isinstance(meta, dict):
+ return None
+ metadata = meta.get("x-codex-turn-metadata")
+ if not isinstance(metadata, dict):
+ return None
+ workspaces = metadata.get("workspaces") or {}
+ if isinstance(workspaces, dict):
+ return next((path for path in workspaces if isinstance(path, str) and path), None)
+ return None
+
+
+def _tool_response(text: str, *, is_error: bool = False) -> dict[str, Any]:
+ return {
+ "content": [{"type": "text", "text": text}],
+ "isError": is_error,
+ }
+
+
+def handle_request(message: Any) -> dict[str, Any] | None:
+ if not isinstance(message, dict):
+ return None
+ request_id = message.get("id")
+ method = message.get("method")
+
+ if method == "notifications/initialized":
+ return None
+ if method == "initialize":
+ requested = (message.get("params") or {}).get("protocolVersion")
+ return {
+ "jsonrpc": "2.0",
+ "id": request_id,
+ "result": {
+ "protocolVersion": requested or PROTOCOL_VERSION,
+ "capabilities": {"tools": {"listChanged": False}},
+ "serverInfo": {"name": "mem0", "version": PLUGIN_VERSION},
+ },
+ }
+ if method == "ping":
+ return {"jsonrpc": "2.0", "id": request_id, "result": {}}
+ if method == "tools/list":
+ return {
+ "jsonrpc": "2.0",
+ "id": request_id,
+ "result": {
+ "tools": [
+ {
+ "name": TOOL_NAME,
+ "description": TOOL_DESCRIPTION,
+ "inputSchema": TOOL_SCHEMA,
+ "annotations": {
+ "readOnlyHint": True,
+ "idempotentHint": True,
+ "openWorldHint": True,
+ },
+ }
+ ]
+ },
+ }
+ if method == "tools/call":
+ params = message.get("params") or {}
+ if params.get("name") != TOOL_NAME:
+ result = _tool_response("Unknown Mem0 tool.", is_error=True)
+ else:
+ try:
+ result = _tool_response(
+ call_search_memories(params.get("arguments"), _workspace_cwd(params))
+ )
+ except ToolInputError as exc:
+ result = _tool_response(str(exc), is_error=True)
+ except Exception:
+ result = _tool_response("Memory search failed.", is_error=True)
+ return {"jsonrpc": "2.0", "id": request_id, "result": result}
+ if request_id is None:
+ return None
+ return {
+ "jsonrpc": "2.0",
+ "id": request_id,
+ "error": {"code": -32601, "message": "Method not found"},
+ }
+
+
+def main() -> int:
+ for raw_line in sys.stdin:
+ try:
+ message = json.loads(raw_line)
+ response = handle_request(message)
+ except json.JSONDecodeError:
+ response = {
+ "jsonrpc": "2.0",
+ "id": None,
+ "error": {"code": -32700, "message": "Parse error"},
+ }
+ except Exception:
+ response = {
+ "jsonrpc": "2.0",
+ "id": None,
+ "error": {"code": -32603, "message": "Internal error"},
+ }
+ if response is not None:
+ sys.stdout.write(json.dumps(response, separators=(",", ":")) + "\n")
+ sys.stdout.flush()
+ telemetry.spawn_flush()
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/integrations/codex-plugin/core/memory_cli.py b/integrations/codex-plugin/core/memory_cli.py
new file mode 100644
index 000000000..76d2ee871
--- /dev/null
+++ b/integrations/codex-plugin/core/memory_cli.py
@@ -0,0 +1,154 @@
+#!/usr/bin/env python3
+"""Mem0 diagnostics and user controls."""
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+
+import telemetry
+from memory_core import (
+ EvidenceStore,
+ api_key,
+ configure_harness,
+ data_dir,
+ doctor,
+ forget_remote_repo,
+ resolve_repo,
+ user_id,
+)
+
+
+def _print_status(value: dict) -> None:
+ last = value.get("last_operation") or {}
+ print(f"Mem0: {'paused' if value['paused'] else 'active'}")
+ print(f"Repository: {value['repo_id']}")
+ print(f"Local data: {value['data_dir']}")
+ print(f"API key: {'configured' if value['api_key_configured'] else 'missing'}")
+ print(
+ "Saved on this computer: "
+ f"{value['events']} session details, {value['flushes']} memory updates"
+ )
+ print(
+ f"Used in this repository: {value['retrievals']} memories returned, "
+ f"{value['subagent_runs']} subagent runs"
+ )
+ if last:
+ item_label = ""
+ if last["operation"] in {"flush", "flush-retry"}:
+ item_label = f", {last['item_count']} memories"
+ operation = (
+ "memory update"
+ if last["operation"] in {"flush", "flush-retry"}
+ else last["operation"].replace("-", " ")
+ )
+ print(
+ f"Last {operation}: "
+ f"{'succeeded' if last['success'] else 'failed'} "
+ f"({last['duration_ms']:.1f} ms{item_label})"
+ )
+ subagent = value.get("last_subagent") or {}
+ if subagent:
+ state = "finished" if subagent.get("stopped_at") else "started"
+ print(
+ "Last subagent: "
+ f"{state}, received {subagent['context_chars']} characters of memory, "
+ f"agent {subagent['agent_id']}"
+ )
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--plugin-data-dir", default="")
+ parser.add_argument("--harness", default="")
+ subparsers = parser.add_subparsers(dest="command", required=True)
+
+ status = subparsers.add_parser("status")
+ status.add_argument("--json", action="store_true")
+
+ doctor_parser = subparsers.add_parser("doctor")
+ doctor_parser.add_argument("--json", action="store_true")
+
+ subparsers.add_parser("pause")
+ subparsers.add_parser("resume")
+
+ forget = subparsers.add_parser("forget")
+ forget.add_argument("--remote", action="store_true")
+ forget.add_argument("--yes", action="store_true")
+ forget.add_argument("--include-project-memory", action="store_true")
+
+ args = parser.parse_args()
+ if args.harness:
+ source_tag = f"{args.harness.replace('-', '_')}_plugin"
+ configure_harness(args.harness, source_tag=source_tag)
+ telemetry.init(harness=args.harness, source_tag=source_tag.upper())
+ if args.plugin_data_dir:
+ os.environ["MEM0_CODE_DATA_DIR"] = args.plugin_data_dir
+ store = EvidenceStore()
+ try:
+ repo = resolve_repo(os.getcwd())
+ telemetry.record("control", repo=repo, action=args.command)
+ if args.command == "status":
+ result = {
+ **store.status(repo.identity),
+ "repo_id": repo.identity,
+ "app_id": repo.app_id,
+ "project_id": repo.project_id,
+ "directory": repo.directory,
+ "user_id": user_id(),
+ "data_dir": str(data_dir()),
+ "api_key_configured": bool(api_key()),
+ }
+ if args.json:
+ print(json.dumps(result, indent=2, default=str))
+ else:
+ _print_status(result)
+ elif args.command == "doctor":
+ result = doctor(os.getcwd())
+ if args.json:
+ print(json.dumps(result, indent=2, default=str))
+ else:
+ for name, check in result["checks"].items():
+ print(
+ f"{'PASS' if check['ok'] else 'FAIL'} {name}: {check['detail']}"
+ )
+ return 0 if result["ok"] else 1
+ elif args.command == "pause":
+ store.set_setting("paused", "true")
+ print("Mem0 stopped saving and searching memories.")
+ elif args.command == "resume":
+ store.set_setting("paused", "false")
+ print("Mem0 resumed saving and searching memories.")
+ elif args.command == "forget":
+ if not args.yes:
+ print(
+ "Refusing to delete data without --yes. Add --remote to also "
+ "delete this user/repository scope from Mem0."
+ )
+ return 2
+ remote_result = (
+ forget_remote_repo(
+ repo, include_project_memory=args.include_project_memory
+ )
+ if args.remote
+ else None
+ )
+ local_result = store.forget_local_repo(repo.identity)
+ print(
+ json.dumps(
+ {"local": local_result, "remote": remote_result},
+ indent=2,
+ default=str,
+ )
+ )
+ if remote_result and remote_result.get("status") == "error":
+ return 1
+ finally:
+ store.close()
+ telemetry.spawn_flush()
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/integrations/codex-plugin/core/memory_core.py b/integrations/codex-plugin/core/memory_core.py
new file mode 100644
index 000000000..9b420a063
--- /dev/null
+++ b/integrations/codex-plugin/core/memory_core.py
@@ -0,0 +1,2676 @@
+#!/usr/bin/env python3
+"""Shared core for Mem0 agent plugins.
+
+Hooks record small session details locally. When the agent compacts or ends the
+session, Mem0 sends the useful parts to the platform so it can create memories.
+The agent can search those memories during later work in the repository.
+"""
+
+from __future__ import annotations
+
+import functools
+import hashlib
+import json
+import math
+import os
+import re
+import sqlite3
+import subprocess
+import sys
+import time
+import urllib.error
+import urllib.parse
+import urllib.request
+from dataclasses import dataclass
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Any, Iterable
+
+import telemetry
+
+DEFAULT_API_URL = "https://api.mem0.ai"
+PLUGIN_VERSION = "0.3.3"
+
+_harness_name: str = "generic"
+_harness_env_prefix: str = "MEM0_PLUGIN"
+_harness_data_dir_name: str = "mem0-plugin"
+_harness_source_tag: str = "mem0_plugin"
+
+
+def configure_harness(
+ name: str,
+ env_prefix: str = "",
+ data_dir_name: str = "",
+ source_tag: str = "",
+) -> None:
+ global _harness_name, _harness_env_prefix, _harness_data_dir_name, _harness_source_tag
+ _harness_name = name
+ _harness_env_prefix = env_prefix or f"MEM0_{name.upper().replace('-', '_')}"
+ _harness_data_dir_name = data_dir_name or f"{name}-plugin"
+ _harness_source_tag = source_tag or f"{name.replace('-', '_')}_plugin"
+
+
+def harness_config() -> dict[str, str]:
+ return {
+ "name": _harness_name,
+ "env_prefix": _harness_env_prefix,
+ "data_dir_name": _harness_data_dir_name,
+ "source_tag": _harness_source_tag,
+ }
+
+
+MAX_COMMAND_CHARS = 2000
+MAX_RESULT_CHARS = 2500
+MAX_EPISODE_CHARS = 12000
+CHECKPOINT_EXCHANGES = 5
+CHECKPOINT_MESSAGES = 10
+CHECKPOINT_SOURCE_CHARS = 40000
+DEFAULT_MAX_CONTEXT_CHARS = 4000
+MAX_EXTRACTION_INPUT_TOKENS = 24000
+MAX_FLUSH_ATTEMPTS = 5
+FORGET_PAGE_SIZE = 100
+FORGET_MAX_PAGES = 50
+
+PROJECT_MEMORY_INSTRUCTIONS = """Save concise repository facts that will help with future coding work.
+
+A completed change should produce one memory explaining the resulting behavior, where it is implemented when useful, and any important constraints or reasoning. Exploration or accepted decisions may produce separate memories only when they are independently useful.
+
+Use the coding agent's final response for conclusions about current repository behavior. Do not save proposed or recommended changes unless the user accepted them or the coding agent completed them. Treat subagent responses as supporting repository evidence, not as decisions.
+
+Write about the repository, not the user, assistant, session, or task. Do not include test results, documentation updates, release notes, or temporary state.
+
+If nothing useful was established, return no memories."""
+
+PERSONAL_MEMORY_INSTRUCTIONS = """Save concise facts about the user that will help in any repository: preferred tools, package managers, languages, coding style, review and communication preferences, and anything the user explicitly asked to be remembered about themselves.
+
+Write in the third person about the user, not about the repository, the assistant, the session, or the task. Do not save repository facts, project decisions, commands, or what was built.
+
+Never save that the user has no preferences or that nothing was learned. If nothing was learned about the user, return no memories."""
+
+CODING_MEMORY_CATEGORIES = [
+ {
+ "project_knowledge": (
+ "What the project is and how its code, APIs, data, files, and "
+ "components work."
+ )
+ },
+ {
+ "decisions_and_constraints": (
+ "Why an approach was chosen, what must remain true, and rules future "
+ "work must follow."
+ )
+ },
+ {
+ "workflows": (
+ "How to run, test, debug, deploy, configure, or otherwise work on the "
+ "project."
+ )
+ },
+ {
+ "problems_and_fixes": (
+ "Bugs, failures, known pitfalls, their causes, and how to fix or avoid "
+ "them."
+ )
+ },
+ {
+ "results": (
+ "Outcomes and measurements from tests, benchmarks, experiments, or "
+ "investigations."
+ )
+ },
+]
+CODING_MEMORY_CATEGORY_NAMES = tuple(
+ category_name
+ for category in CODING_MEMORY_CATEGORIES
+ for category_name in category
+)
+
+TEST_COMMAND_RE = re.compile(
+ r"(?:^|\s)(?:pytest|py\.test|jest|vitest|go\s+test|cargo\s+test|"
+ r"npm\s+(?:run\s+)?test|pnpm\s+(?:run\s+)?test|yarn\s+test|"
+ r"mvn\s+test|gradle\s+test|make\s+test)(?:\s|$)",
+ re.IGNORECASE,
+)
+BUILD_COMMAND_RE = re.compile(
+ r"(?:^|\s)(?:npm|pnpm|yarn)\s+(?:run\s+)?build(?:\s|$)|"
+ r"(?:^|\s)(?:cargo|go|mvn|gradle|make)\s+build(?:\s|$)",
+ re.IGNORECASE,
+)
+
+SECRET_PATTERNS = [
+ re.compile(r"(?i)(authorization\s*[:=]\s*(?:bearer|token)\s+)[^\s\"']+"),
+ re.compile(
+ r"(?i)((?:api[_-]?key|secret[_-]?access[_-]?key|session[_-]?token)\s*[:=]\s*)[^\s\"']+"
+ ),
+ re.compile(
+ r"(?i)((?:access[_-]?token|refresh[_-]?token|password|credential)"
+ r"\s*[:=]\s*)[^\s&\"']+"
+ ),
+ re.compile(r"\b(?:sk|m0|mem0_sk|psk)-[A-Za-z0-9_\-]{12,}\b"),
+ re.compile(r"\b(?:ASIA|AKIA)[A-Z0-9]{12,}\b"),
+ re.compile(r"\b(?:ghp_|github_pat_|xox[baprs]-)[A-Za-z0-9_\-]{12,}\b"),
+ re.compile(
+ r"-----BEGIN [^-]*PRIVATE KEY-----.*?-----END [^-]*PRIVATE KEY-----",
+ re.DOTALL,
+ ),
+ re.compile(
+ r'(?i)("(?:api[_-]?key|password|secret(?:[_-]?access[_-]?key)?'
+ r'|(?:access|refresh|session)[_-]?token|token|authorization|credential'
+ r')"\s*:\s*")(?:\\.|[^"\\])*'
+ ),
+]
+
+
+def utc_now() -> str:
+ return datetime.now(timezone.utc).isoformat()
+
+
+def redact(value: Any) -> str:
+ text = (
+ value
+ if isinstance(value, str)
+ else json.dumps(value, ensure_ascii=False, default=str)
+ )
+ for pattern in SECRET_PATTERNS:
+ if pattern.groups:
+ text = pattern.sub(r"\1[REDACTED]", text)
+ else:
+ text = pattern.sub("[REDACTED]", text)
+ return text
+
+
+def bounded(value: Any, limit: int) -> str:
+ text = redact(value).strip()
+ if len(text) <= limit:
+ return text
+ return text[:limit] + f"\n...[truncated {len(text) - limit} chars]"
+
+
+def _git(cwd: str, *args: str) -> str:
+ try:
+ result = subprocess.run(
+ ["git", "-C", cwd, *args],
+ check=False,
+ capture_output=True,
+ text=True,
+ timeout=0.5,
+ )
+ except (OSError, subprocess.TimeoutExpired):
+ return ""
+ return result.stdout.strip() if result.returncode == 0 else ""
+
+
+def _normalize_remote(remote: str) -> str:
+ remote = remote.strip()
+ if remote.startswith("git@") and ":" in remote:
+ host_path = remote[4:].replace(":", "/", 1)
+ remote = f"https://{host_path}"
+ if remote.endswith(".git"):
+ remote = remote[:-4]
+ if "://" in remote:
+ parsed = urllib.parse.urlsplit(remote)
+ hostname = parsed.hostname or ""
+ if parsed.port:
+ hostname = f"{hostname}:{parsed.port}"
+ remote = urllib.parse.urlunsplit(
+ (parsed.scheme, hostname, parsed.path, parsed.query, parsed.fragment)
+ )
+ return remote.rstrip("/")
+
+
+_WILDCARD_SCOPE = re.compile(r"^\*+$")
+
+
+def _scope_value(raw: str | None) -> str:
+ """Reject wildcards as identities: they are filter syntax and would widen the scope."""
+ value = (raw or "").strip()
+ return "" if _WILDCARD_SCOPE.match(value) else value
+
+
+SEARCH_SCOPES = ("repo", "dir", "mine")
+DEFAULT_SEARCH_SCOPE = "repo"
+
+def directory_app_id(repo: RepoContext) -> str:
+ """The app_id of the directory this session runs in: the repository at the root, repository/path below it."""
+ return f"{repo.app_id}/{repo.directory}" if repo.directory else repo.app_id
+
+
+def directory_chain(repo: RepoContext) -> list[str]:
+ """Every directory a memory belongs to, from the top-level folder down to the one it was written in."""
+ parts = repo.directory.split("/") if repo.directory else []
+ return ["/".join(parts[: index + 1]) for index in range(len(parts))]
+
+
+def _shared_project_ids(repo: RepoContext) -> list[str]:
+ """Current and pre-upgrade namespaces, shared by recall and explicit deletion."""
+ if not repo.identity.startswith("local:") and repo.project_id != repo.app_id:
+ return [repo.project_id, repo.app_id]
+ return [repo.project_id]
+
+
+def _search_filters(user: str, repo: RepoContext, scope: str) -> dict[str, Any]:
+ """Build the scope filter: app_id scopes to the repo, then union shared and personal lanes."""
+ app_scope = {"app_id": repo.app_id}
+ mine = {"AND": [{"user_id": user}, app_scope]}
+ if scope == "mine":
+ return mine
+ projects = [{"AND": [{"agent_id": project_id}, app_scope]} for project_id in _shared_project_ids(repo)]
+ shared: dict[str, Any] = projects[0] if len(projects) == 1 else {"OR": projects}
+ if scope == "dir" and repo.directory:
+ shared = {"AND": [shared, {"metadata": {"dirs": {"contains": repo.directory}}}]}
+ return {"OR": [shared, mine]}
+
+
+def search_scope() -> str:
+ configured = (
+ _plugin_option("search_scope", "MEM0_CODE_SEARCH_SCOPE") or ""
+ ).strip().lower()
+ return configured if configured in SEARCH_SCOPES else DEFAULT_SEARCH_SCOPE
+
+
+def resolve_search_scope(scope: str | None) -> str:
+ value = (scope or search_scope()).strip().lower()
+ if value not in SEARCH_SCOPES:
+ raise ValueError(f"Unknown search scope: {value}")
+ return value
+
+
+def _legacy_project_map(cwd: str, root: str, raw_remote: str) -> str:
+ """Return the project name used by the previous Claude Code plugin."""
+ try:
+ data = json.loads((Path.home() / ".mem0" / "project_map.json").read_text())
+ except (OSError, json.JSONDecodeError):
+ return ""
+ if not isinstance(data, dict):
+ return ""
+
+ keys = list(dict.fromkeys([cwd, root, os.path.realpath(cwd), os.path.realpath(root)]))
+ if raw_remote:
+ keys.append(f"remote:{hashlib.sha256(raw_remote.encode()).hexdigest()[:16]}")
+ for key in keys:
+ value = data.get(key)
+ if isinstance(value, str) and value.strip():
+ return value.strip()
+ return ""
+
+
+def _legacy_project_id(cwd: str, root: str, raw_remote: str, identity: str) -> str:
+ """Use the repository namespace created by the previous Mem0 plugin."""
+ configured = _scope_value(os.environ.get("MEM0_PROJECT_ID"))
+ if configured:
+ return configured
+
+ mapped = _scope_value(_legacy_project_map(cwd, root, raw_remote))
+ if mapped:
+ return mapped
+
+ remote = raw_remote or ("" if identity.startswith("local:") else identity)
+ remote = remote.strip().removesuffix(".git")
+ for prefix in ("https://", "http://", "ssh://", "git://"):
+ if remote.startswith(prefix):
+ remote = remote[len(prefix) :]
+ break
+ else:
+ remote = re.sub(r"^git@", "", remote)
+ parts = [part for part in remote.replace(":", "/", 1).split("/") if part]
+ if len(parts) >= 2:
+ return f"{parts[-2]}-{parts[-1]}".replace("/", "-").replace(":", "-")
+ if parts:
+ return parts[-1].replace("/", "-").replace(":", "-")
+ return os.path.basename(root or cwd) or "unknown"
+
+
+@dataclass(frozen=True)
+class RepoContext:
+ cwd: str
+ root: str
+ identity: str
+ app_id: str
+ branch: str
+ head_sha: str
+ project_id: str = ""
+ directory: str = ""
+
+
+def _project_id(root: str, identity: str, app_id: str) -> str:
+ """The shared namespace: includes a host hash so repos with the same owner/name on different hosts stay apart."""
+ if not identity.startswith("local:"):
+ return f"{app_id}-{hashlib.sha256(identity.encode()).hexdigest()[:10]}"
+ return f"local-{app_id}-{hashlib.sha256(root.encode()).hexdigest()[:10]}"
+
+
+def _relative_directory(cwd: str, root: str) -> str:
+ relative = os.path.relpath(cwd, root)
+ return "" if relative == "." or relative.startswith("..") else relative.replace(os.sep, "/")
+
+
+@dataclass(frozen=True)
+class MemorySearchResult:
+ succeeded: bool
+ matched_count: int
+ already_shown_count: int
+ memories: list[dict[str, Any]]
+
+
+@functools.lru_cache(maxsize=64)
+def _resolve_repo_cached(cwd: str) -> RepoContext:
+ given_cwd = cwd
+ cwd = os.path.realpath(cwd)
+ given_root = _git(cwd, "rev-parse", "--show-toplevel") or given_cwd
+ root = os.path.realpath(given_root)
+ raw_remote = _git(root, "config", "--get", "remote.origin.url")
+ remote = _normalize_remote(raw_remote)
+ identity = remote or f"local:{root}"
+ app_id = _legacy_project_id(given_cwd, given_root, raw_remote, identity)
+ return RepoContext(
+ cwd=cwd,
+ root=root,
+ identity=identity,
+ app_id=app_id,
+ branch=_git(root, "branch", "--show-current") or "detached",
+ head_sha=_git(root, "rev-parse", "HEAD"),
+ project_id=_project_id(root, identity, app_id),
+ directory=_relative_directory(cwd, root),
+ )
+
+
+def resolve_repo(cwd: str | None) -> RepoContext:
+ return _resolve_repo_cached(os.path.abspath(cwd or os.getcwd()))
+
+
+def api_key() -> str:
+ configured = (
+ os.environ.get("MEM0_API_KEY")
+ or os.environ.get("PLUGIN_OPTION_API_KEY")
+ or os.environ.get("CLAUDE_PLUGIN_OPTION_API_KEY")
+ or os.environ.get("CLAUDE_PLUGIN_OPTION_MEM0_API_KEY")
+ or ""
+ ).strip()
+ if configured:
+ return configured
+ try:
+ return (data_dir() / "api-key").read_text(encoding="utf-8").strip()
+ except OSError:
+ return ""
+
+
+def cache_plugin_api_key() -> bool:
+ """Bridge host's hook-only sensitive config into plugin-owned storage."""
+ configured = (
+ os.environ.get("PLUGIN_OPTION_API_KEY")
+ or os.environ.get("CLAUDE_PLUGIN_OPTION_API_KEY")
+ or os.environ.get("CLAUDE_PLUGIN_OPTION_MEM0_API_KEY")
+ or ""
+ ).strip()
+ if not configured:
+ return False
+
+ directory = data_dir()
+ directory.mkdir(parents=True, exist_ok=True)
+ path = directory / "api-key"
+ temporary = directory / f"api-key.{os.getpid()}.tmp"
+ descriptor = os.open(
+ temporary,
+ os.O_WRONLY | os.O_CREAT | os.O_TRUNC,
+ 0o600,
+ )
+ try:
+ with os.fdopen(descriptor, "w", encoding="utf-8") as handle:
+ handle.write(configured)
+ os.replace(temporary, path)
+ os.chmod(path, 0o600)
+ finally:
+ try:
+ temporary.unlink()
+ except FileNotFoundError:
+ pass
+ return True
+
+
+def clear_stale_api_key_cache() -> bool:
+ """Drop the cached key file once every configured key source is gone."""
+ configured = (
+ os.environ.get("MEM0_API_KEY")
+ or os.environ.get("PLUGIN_OPTION_API_KEY")
+ or os.environ.get("CLAUDE_PLUGIN_OPTION_API_KEY")
+ or os.environ.get("CLAUDE_PLUGIN_OPTION_MEM0_API_KEY")
+ or ""
+ ).strip()
+ if configured:
+ return False
+ path = data_dir() / "api-key"
+ if not path.exists():
+ return False
+ try:
+ path.unlink()
+ except OSError:
+ return False
+ return True
+
+
+def detached_process_kwargs(platform: str | None = None) -> dict:
+ """Keep a spawned worker alive after the coding agent exits, on POSIX and Windows."""
+ if (platform or sys.platform) == "win32":
+ return {
+ "creationflags": subprocess.DETACHED_PROCESS
+ | subprocess.CREATE_NEW_PROCESS_GROUP
+ }
+ return {"start_new_session": True}
+
+
+def _plugin_option(name: str, fallback: str = "") -> str:
+ return (
+ os.environ.get(f"PLUGIN_OPTION_{name.upper()}")
+ or os.environ.get(f"CLAUDE_PLUGIN_OPTION_{name.upper()}")
+ or os.environ.get(fallback)
+ or ""
+ ).strip()
+
+
+def user_id() -> str:
+ return (
+ _scope_value(_plugin_option("user_id", "MEM0_CODE_USER_ID"))
+ or _scope_value(os.environ.get("MEM0_USER_ID"))
+ or _scope_value(os.environ.get("MEM0_RESOLVED_USER_ID"))
+ or _scope_value(os.environ.get("USER"))
+ or _scope_value(os.environ.get("USERNAME"))
+ or "default"
+ )
+
+
+def data_dir() -> Path:
+ configured = (
+ os.environ.get("MEM0_CODE_DATA_DIR")
+ or os.environ.get("MEM0_PLUGIN_DATA_DIR")
+ or os.environ.get("PLUGIN_DATA")
+ or os.environ.get("CLAUDE_PLUGIN_DATA")
+ )
+ return (
+ Path(configured).expanduser() if configured else Path.home() / ".mem0" / _harness_data_dir_name
+ )
+
+
+def _bool_option(name: str, fallback: str, default: bool = False) -> bool:
+ value = _plugin_option(name, fallback)
+ if not value:
+ return default
+ return value.lower() in {"1", "true", "yes", "on"}
+
+
+def _int_option(name: str, fallback: str, default: int) -> int:
+ value = _plugin_option(name, fallback)
+ try:
+ return int(value) if value else default
+ except ValueError:
+ return default
+
+
+
+def _checkpoint_message(event: dict[str, Any]) -> str:
+ kind = event.get("kind")
+ payload = event.get("payload") or {}
+ if kind == "user_prompt":
+ return redact(payload.get("text", "")).strip()
+ if kind == "assistant_stop":
+ transcript_messages = payload.get("transcript_messages") or []
+ if isinstance(transcript_messages, list):
+ text = "\n".join(
+ str(message.get("content") or "")
+ for message in transcript_messages
+ if isinstance(message, dict) and message.get("content")
+ )
+ if text:
+ return text
+ return redact(payload.get("text", "")).strip()
+ if kind in {"subagent_stop", "sidekick_stop"}:
+ return redact(payload.get("final_message", "")).strip()
+ return ""
+
+
+def checkpoint_stats(events: list[dict[str, Any]]) -> tuple[int, int, int]:
+ """Return completed exchanges, messages, and source characters."""
+ completed = sum(event.get("kind") == "assistant_stop" for event in events)
+ contents = [content for event in events if (content := _checkpoint_message(event))]
+ return completed, len(contents), sum(len(content) for content in contents)
+
+
+def select_checkpoint_events(
+ events: list[dict[str, Any]], *, force: bool
+) -> list[dict[str, Any]]:
+ """Select one ordered extraction block without splitting an exchange."""
+ for index, event in enumerate(events):
+ if event.get("kind") != "assistant_stop":
+ continue
+ candidate = events[: index + 1]
+ completed, messages, source_chars = checkpoint_stats(candidate)
+ if (
+ completed >= CHECKPOINT_EXCHANGES
+ or messages >= CHECKPOINT_MESSAGES
+ or source_chars >= CHECKPOINT_SOURCE_CHARS
+ ):
+ return candidate
+ return events if force else []
+
+
+class EvidenceStore:
+ def __init__(self, path: Path | None = None):
+ directory = data_dir() if path is None else path.parent
+ directory.mkdir(parents=True, exist_ok=True)
+ self.path = path or directory / "evidence.sqlite3"
+ try:
+ self._open()
+ except sqlite3.DatabaseError:
+ self._quarantine()
+ self._open()
+
+ def _open(self) -> None:
+ self.conn = sqlite3.connect(self.path, timeout=10)
+ self.conn.row_factory = sqlite3.Row
+ try:
+ self.conn.execute("PRAGMA journal_mode=WAL")
+ self.conn.execute("PRAGMA busy_timeout=10000")
+ self._migrate()
+ except sqlite3.DatabaseError:
+ self.conn.close()
+ raise
+
+ def _quarantine(self) -> None:
+ """Move an unreadable database aside so capture restarts cleanly."""
+ stamp = int(time.time())
+ for suffix in ("", "-wal", "-shm"):
+ source = Path(f"{self.path}{suffix}")
+ try:
+ source.replace(f"{self.path}.corrupt-{stamp}{suffix}")
+ except FileNotFoundError:
+ continue
+ except OSError:
+ try:
+ source.unlink()
+ except OSError:
+ pass
+ telemetry.record("db_quarantined")
+
+ def close(self) -> None:
+ self.conn.close()
+
+ def _migrate(self) -> None:
+ # Keep the legacy table name so existing databases and in-flight workers remain compatible.
+ self.conn.executescript(
+ """
+ CREATE TABLE IF NOT EXISTS events (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ repo_id TEXT NOT NULL,
+ app_id TEXT NOT NULL,
+ session_id TEXT NOT NULL,
+ created_at TEXT NOT NULL,
+ kind TEXT NOT NULL,
+ payload_json TEXT NOT NULL,
+ flush_id TEXT
+ );
+ CREATE INDEX IF NOT EXISTS events_session_idx
+ ON events(repo_id, session_id, flush_id, id);
+
+ CREATE TABLE IF NOT EXISTS session_scopes (
+ session_id TEXT PRIMARY KEY,
+ repo_id TEXT NOT NULL,
+ app_id TEXT NOT NULL,
+ root TEXT NOT NULL,
+ branch TEXT NOT NULL,
+ head_sha TEXT NOT NULL,
+ created_at TEXT NOT NULL,
+ directory TEXT NOT NULL DEFAULT ''
+ );
+
+ CREATE TABLE IF NOT EXISTS flushes (
+ packet_id TEXT PRIMARY KEY,
+ repo_id TEXT NOT NULL,
+ app_id TEXT NOT NULL,
+ session_id TEXT NOT NULL,
+ reason TEXT NOT NULL,
+ event_start INTEGER NOT NULL,
+ event_end INTEGER NOT NULL,
+ status TEXT NOT NULL,
+ episode_event_id TEXT,
+ semantic_event_id TEXT,
+ error TEXT,
+ attempts INTEGER NOT NULL DEFAULT 0,
+ created_at TEXT NOT NULL,
+ updated_at TEXT NOT NULL
+ );
+
+ CREATE TABLE IF NOT EXISTS retrievals (
+ session_id TEXT NOT NULL,
+ repo_id TEXT NOT NULL,
+ memory_id TEXT NOT NULL,
+ injected_at TEXT NOT NULL,
+ rank INTEGER,
+ score REAL,
+ memory_text TEXT,
+ context_chars INTEGER NOT NULL DEFAULT 0,
+ PRIMARY KEY(session_id, repo_id, memory_id)
+ );
+
+ CREATE TABLE IF NOT EXISTS operations (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ created_at TEXT NOT NULL,
+ repo_id TEXT NOT NULL,
+ session_id TEXT NOT NULL,
+ operation TEXT NOT NULL,
+ duration_ms REAL NOT NULL,
+ success INTEGER NOT NULL,
+ item_count INTEGER NOT NULL DEFAULT 0,
+ request_chars INTEGER NOT NULL DEFAULT 0,
+ response_chars INTEGER NOT NULL DEFAULT 0,
+ error TEXT
+ );
+
+ CREATE TABLE IF NOT EXISTS sidekick_runs (
+ repo_id TEXT NOT NULL,
+ session_id TEXT NOT NULL,
+ agent_id TEXT NOT NULL,
+ agent_type TEXT NOT NULL,
+ started_at TEXT NOT NULL,
+ stopped_at TEXT,
+ transcript_path TEXT,
+ context_chars INTEGER NOT NULL DEFAULT 0,
+ final_message TEXT,
+ PRIMARY KEY(repo_id, session_id, agent_id)
+ );
+ CREATE INDEX IF NOT EXISTS sidekick_runs_repo_idx
+ ON sidekick_runs(repo_id, started_at);
+
+ CREATE TABLE IF NOT EXISTS settings (
+ key TEXT PRIMARY KEY,
+ value TEXT NOT NULL,
+ updated_at TEXT NOT NULL
+ );
+
+ """
+ )
+ # Remove the pre-0.1.1 snapshot implementation.
+ self.conn.executescript(
+ """
+ DROP TABLE IF EXISTS sidekick_calls;
+ DROP TABLE IF EXISTS sidekick_snapshots;
+ DROP TABLE IF EXISTS sidekick_state;
+ DROP TABLE IF EXISTS sidekick_packets;
+ """
+ )
+ self._ensure_column("retrievals", "rank", "INTEGER")
+ self._ensure_column("retrievals", "score", "REAL")
+ self._ensure_column("retrievals", "memory_text", "TEXT")
+ self._ensure_column("retrievals", "context_chars", "INTEGER NOT NULL DEFAULT 0")
+ self._ensure_column("flushes", "attempts", "INTEGER NOT NULL DEFAULT 0")
+ self._ensure_column("session_scopes", "directory", "TEXT NOT NULL DEFAULT ''")
+ self.conn.commit()
+
+ def _ensure_column(self, table: str, column: str, declaration: str) -> None:
+ columns = {
+ str(row["name"])
+ for row in self.conn.execute(f"PRAGMA table_info({table})").fetchall()
+ }
+ if column not in columns:
+ self.conn.execute(f"ALTER TABLE {table} ADD COLUMN {column} {declaration}")
+
+ def record_event(
+ self,
+ repo: RepoContext,
+ session_id: str,
+ kind: str,
+ payload: dict[str, Any],
+ ) -> int:
+ cursor = self.conn.execute(
+ """INSERT INTO events
+ (repo_id, app_id, session_id, created_at, kind, payload_json)
+ VALUES (?, ?, ?, ?, ?, ?)""",
+ (
+ repo.identity,
+ repo.app_id,
+ session_id,
+ utc_now(),
+ kind,
+ json.dumps(payload, ensure_ascii=False, sort_keys=True),
+ ),
+ )
+ self.conn.commit()
+ return int(cursor.lastrowid)
+
+ def record_assistant_response(self, repo: RepoContext, session_id: str, message: str) -> None:
+ """Ignore repeated response hooks until another prompt or a different answer arrives."""
+ with self.conn:
+ # Serialize the check and insert across concurrent Stop and SessionEnd hooks.
+ self.conn.execute("BEGIN IMMEDIATE")
+ previous = self.conn.execute(
+ """SELECT kind, payload_json FROM events
+ WHERE repo_id = ? AND session_id = ? AND kind IN ('user_prompt', 'assistant_stop')
+ ORDER BY id DESC LIMIT 1""",
+ (repo.identity, session_id),
+ ).fetchone()
+ if (
+ previous is not None
+ and previous["kind"] == "assistant_stop"
+ and json.loads(previous["payload_json"]).get("text") == message
+ ):
+ return
+ self.record_event(repo, session_id, "assistant_stop", {"text": message})
+
+ def repo_for_session(self, session_id: str, cwd: str | None) -> RepoContext:
+ """Keep one project scope for every hook in a coding-agent session."""
+ current = resolve_repo(cwd)
+ if session_id == "unknown-session":
+ return current
+
+ with self.conn:
+ self.conn.execute(
+ """INSERT OR IGNORE INTO session_scopes
+ (session_id, repo_id, app_id, root, branch, head_sha, created_at, directory)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)""",
+ (
+ session_id,
+ current.identity,
+ current.app_id,
+ current.root,
+ current.branch,
+ current.head_sha,
+ utc_now(),
+ current.directory,
+ ),
+ )
+ scope = self.conn.execute(
+ "SELECT * FROM session_scopes WHERE session_id = ?", (session_id,)
+ ).fetchone()
+ same_git_repo = (
+ current.identity == scope["repo_id"] and bool(current.head_sha)
+ )
+ pinned = current if same_git_repo else resolve_repo(str(scope["root"]))
+ return RepoContext(
+ cwd=current.cwd,
+ root=pinned.root,
+ identity=str(scope["repo_id"]),
+ app_id=str(scope["app_id"]),
+ branch=pinned.branch,
+ head_sha=pinned.head_sha,
+ project_id=pinned.project_id,
+ directory=str(scope["directory"] or ""),
+ )
+
+ def prepare_flush(
+ self, repo: RepoContext, session_id: str, reason: str
+ ) -> tuple[str, list[dict[str, Any]]] | None:
+ with self.conn:
+ self.conn.execute("BEGIN IMMEDIATE")
+ existing = self.conn.execute(
+ """SELECT * FROM flushes
+ WHERE repo_id = ? AND session_id = ?
+ AND status NOT IN ('semantic-succeeded', 'explicitly-stored', 'gave-up')
+ ORDER BY created_at LIMIT 1""",
+ (repo.identity, session_id),
+ ).fetchone()
+ if existing and int(existing["attempts"] or 0) >= MAX_FLUSH_ATTEMPTS:
+ self.conn.execute(
+ "UPDATE flushes SET status = 'gave-up', updated_at = ? WHERE packet_id = ?",
+ (utc_now(), existing["packet_id"]),
+ )
+ telemetry.record(
+ "flush",
+ repo=repo,
+ session_id=session_id,
+ reason=reason,
+ status="gave-up",
+ success=False,
+ attempts=int(existing["attempts"] or 0),
+ )
+ existing = None
+ if existing:
+ if reason != "periodic" and existing["reason"] == "periodic":
+ self.conn.execute(
+ "UPDATE flushes SET reason = ?, updated_at = ? WHERE packet_id = ?",
+ (reason, utc_now(), existing["packet_id"]),
+ )
+ existing_rows = self.conn.execute(
+ "SELECT * FROM events WHERE flush_id = ? ORDER BY id",
+ (existing["packet_id"],),
+ ).fetchall()
+ if existing_rows:
+ return str(existing["packet_id"]), [
+ {
+ "id": row["id"],
+ "created_at": row["created_at"],
+ "kind": row["kind"],
+ "payload": json.loads(row["payload_json"]),
+ }
+ for row in existing_rows
+ ]
+
+ rows = self.conn.execute(
+ """SELECT * FROM events
+ WHERE repo_id = ? AND session_id = ? AND flush_id IS NULL
+ ORDER BY id""",
+ (repo.identity, session_id),
+ ).fetchall()
+ if not rows:
+ return None
+
+ events = [
+ {
+ "id": row["id"],
+ "created_at": row["created_at"],
+ "kind": row["kind"],
+ "payload": json.loads(row["payload_json"]),
+ }
+ for row in rows
+ ]
+ events = select_checkpoint_events(events, force=reason != "periodic")
+ if not events:
+ return None
+ event_start, event_end = events[0]["id"], events[-1]["id"]
+ packet_material = f"{repo.identity}\0{session_id}\0{event_start}\0{event_end}"
+ packet_id = hashlib.sha256(packet_material.encode()).hexdigest()[:32]
+ now = utc_now()
+
+ self.conn.execute(
+ """INSERT OR IGNORE INTO flushes
+ (packet_id, repo_id, app_id, session_id, reason, event_start,
+ event_end, status, created_at, updated_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, 'prepared', ?, ?)""",
+ (
+ packet_id,
+ repo.identity,
+ repo.app_id,
+ session_id,
+ reason,
+ event_start,
+ event_end,
+ now,
+ now,
+ ),
+ )
+ event_ids = [event["id"] for event in events]
+ placeholders = ", ".join("?" for _ in event_ids)
+ self.conn.execute(
+ f"UPDATE events SET flush_id = ? "
+ f"WHERE id IN ({placeholders}) AND flush_id IS NULL",
+ (packet_id, *event_ids),
+ )
+ return packet_id, events
+
+ def checkpoint_due(self, repo_id: str, session_id: str) -> bool:
+ if self.has_inflight_flush(repo_id, session_id):
+ return False
+ rows = self.conn.execute(
+ """SELECT * FROM events
+ WHERE repo_id = ? AND session_id = ? AND flush_id IS NULL
+ ORDER BY id""",
+ (repo_id, session_id),
+ ).fetchall()
+ events = [
+ {
+ "id": row["id"],
+ "created_at": row["created_at"],
+ "kind": row["kind"],
+ "payload": json.loads(row["payload_json"]),
+ }
+ for row in rows
+ ]
+ return bool(select_checkpoint_events(events, force=False))
+
+ def has_inflight_flush(self, repo_id: str, session_id: str) -> bool:
+ return (
+ self.conn.execute(
+ """SELECT 1 FROM flushes
+ WHERE repo_id = ? AND session_id = ?
+ AND status IN ('prepared', 'semantic-queued')
+ LIMIT 1""",
+ (repo_id, session_id),
+ ).fetchone()
+ is not None
+ )
+
+ def flush_record(self, packet_id: str) -> dict[str, Any] | None:
+ row = self.conn.execute(
+ "SELECT * FROM flushes WHERE packet_id = ?", (packet_id,)
+ ).fetchone()
+ return dict(row) if row else None
+
+ def has_unflushed_events(self, repo_id: str, session_id: str) -> bool:
+ return (
+ self.conn.execute(
+ """SELECT 1 FROM events
+ WHERE repo_id = ? AND session_id = ? AND flush_id IS NULL
+ LIMIT 1""",
+ (repo_id, session_id),
+ ).fetchone()
+ is not None
+ )
+
+ def unflushed_starts_with_session_start(
+ self, repo_id: str, session_id: str
+ ) -> bool:
+ row = self.conn.execute(
+ """SELECT kind FROM events
+ WHERE repo_id = ? AND session_id = ? AND flush_id IS NULL
+ ORDER BY id LIMIT 1""",
+ (repo_id, session_id),
+ ).fetchone()
+ return bool(row and row["kind"] == "session_start")
+
+ def update_flush(self, packet_id: str, **fields: Any) -> None:
+ allowed = {"status", "episode_event_id", "semantic_event_id", "error"}
+ updates = {key: value for key, value in fields.items() if key in allowed}
+ updates["updated_at"] = utc_now()
+ clause = ", ".join(f"{key} = ?" for key in updates)
+ failed = str(fields.get("status", "")) in {
+ "error",
+ "semantic-failed",
+ "semantic-timeout",
+ "semantic-missing",
+ }
+ if failed:
+ clause += ", attempts = attempts + 1"
+ with self.conn:
+ self.conn.execute(
+ f"UPDATE flushes SET {clause} WHERE packet_id = ?",
+ [*updates.values(), packet_id],
+ )
+
+ def unseen(
+ self, session_id: str, repo_id: str, memories: Iterable[dict[str, Any]]
+ ) -> list[dict[str, Any]]:
+ seen = {
+ row["memory_id"]
+ for row in self.conn.execute(
+ "SELECT memory_id FROM retrievals WHERE session_id = ? AND repo_id = ?",
+ (session_id, repo_id),
+ )
+ }
+ return [memory for memory in memories if str(memory.get("id", "")) not in seen]
+
+ def mark_injected(
+ self, session_id: str, repo_id: str, memories: Iterable[dict[str, Any]]
+ ) -> None:
+ now = utc_now()
+ with self.conn:
+ for rank, memory in enumerate(memories, start=1):
+ memory_id = str(memory.get("id", ""))
+ if memory_id:
+ memory_text = bounded(
+ memory.get("memory") or memory.get("text") or "",
+ 4000,
+ )
+ try:
+ score = float(memory["score"])
+ except (KeyError, TypeError, ValueError):
+ score = None
+ self.conn.execute(
+ """INSERT OR IGNORE INTO retrievals
+ (session_id, repo_id, memory_id, injected_at, rank,
+ score, memory_text, context_chars)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)""",
+ (
+ session_id,
+ repo_id,
+ memory_id,
+ now,
+ rank,
+ score,
+ memory_text,
+ len(memory_text),
+ ),
+ )
+
+ def injected_memories(
+ self, session_id: str, repo_id: str
+ ) -> list[dict[str, Any]]:
+ """Return the exact memories already supplied to the main conversation."""
+ rows = self.conn.execute(
+ """SELECT memory_id, rank, score, memory_text
+ FROM retrievals
+ WHERE session_id = ? AND repo_id = ?
+ ORDER BY COALESCE(rank, 2147483647), injected_at, memory_id""",
+ (session_id, repo_id),
+ ).fetchall()
+ return [
+ {
+ "id": row["memory_id"],
+ "memory": row["memory_text"],
+ "score": row["score"],
+ }
+ for row in rows
+ if row["memory_text"]
+ ]
+
+ def start_subagent(
+ self,
+ repo: RepoContext,
+ session_id: str,
+ agent_id: str,
+ agent_type: str,
+ context_chars: int,
+ ) -> bool:
+ """Record one native subagent instance and whether context was first sent."""
+ with self.conn:
+ cursor = self.conn.execute(
+ """INSERT OR IGNORE INTO sidekick_runs
+ (repo_id, session_id, agent_id, agent_type, started_at,
+ context_chars)
+ VALUES (?, ?, ?, ?, ?, ?)""",
+ (
+ repo.identity,
+ session_id,
+ agent_id,
+ agent_type,
+ utc_now(),
+ context_chars,
+ ),
+ )
+ return int(cursor.rowcount) > 0
+
+ def stop_subagent(
+ self,
+ repo: RepoContext,
+ session_id: str,
+ agent_id: str,
+ agent_type: str,
+ transcript_path: str,
+ final_message: str,
+ ) -> str:
+ now = utc_now()
+ self.conn.execute("BEGIN IMMEDIATE")
+ try:
+ if not agent_id:
+ rows = self.conn.execute(
+ """SELECT agent_id FROM sidekick_runs
+ WHERE repo_id = ? AND session_id = ? AND agent_type = ? AND stopped_at IS NULL
+ LIMIT 2""",
+ (repo.identity, session_id, agent_type),
+ ).fetchall()
+ # Without a host ID, overlapping runs cannot be correlated reliably.
+ agent_id = rows[0]["agent_id"] if len(rows) == 1 else f"unknown-agent-{time.time_ns()}"
+ self.conn.execute(
+ """INSERT INTO sidekick_runs
+ (repo_id, session_id, agent_id, agent_type, started_at,
+ stopped_at, transcript_path, final_message)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
+ ON CONFLICT(repo_id, session_id, agent_id) DO UPDATE SET
+ stopped_at = excluded.stopped_at,
+ transcript_path = excluded.transcript_path,
+ final_message = excluded.final_message""",
+ (
+ repo.identity,
+ session_id,
+ agent_id,
+ agent_type,
+ now,
+ now,
+ bounded(transcript_path, 2000),
+ redact(final_message).strip(),
+ ),
+ )
+ self.conn.commit()
+ except Exception:
+ self.conn.rollback()
+ raise
+ return agent_id
+
+ def operation(
+ self,
+ repo: RepoContext,
+ session_id: str,
+ operation: str,
+ duration_ms: float,
+ success: bool,
+ *,
+ item_count: int = 0,
+ request_chars: int = 0,
+ response_chars: int = 0,
+ error: str = "",
+ ) -> None:
+ with self.conn:
+ self.conn.execute(
+ """INSERT INTO operations
+ (created_at, repo_id, session_id, operation, duration_ms,
+ success, item_count, request_chars, response_chars, error)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
+ (
+ utc_now(),
+ repo.identity,
+ session_id,
+ operation,
+ duration_ms,
+ int(success),
+ item_count,
+ request_chars,
+ response_chars,
+ bounded(error, 1000),
+ ),
+ )
+
+ def has_operation(self, repo_id: str, session_id: str, operation: str) -> bool:
+ row = self.conn.execute(
+ """SELECT 1 FROM operations
+ WHERE repo_id = ? AND session_id = ? AND operation = ?
+ LIMIT 1""",
+ (repo_id, session_id, operation),
+ ).fetchone()
+ return row is not None
+
+ def has_event(self, repo_id: str, session_id: str, kind: str) -> bool:
+ row = self.conn.execute(
+ """SELECT 1 FROM events
+ WHERE repo_id = ? AND session_id = ? AND kind = ?
+ LIMIT 1""",
+ (repo_id, session_id, kind),
+ ).fetchone()
+ return row is not None
+
+ def latest_event_payload(
+ self, repo_id: str, session_id: str, kind: str
+ ) -> dict[str, Any]:
+ row = self.conn.execute(
+ """SELECT payload_json FROM events
+ WHERE repo_id = ? AND session_id = ? AND kind = ?
+ ORDER BY id DESC LIMIT 1""",
+ (repo_id, session_id, kind),
+ ).fetchone()
+ if not row:
+ return {}
+ try:
+ payload = json.loads(row["payload_json"])
+ except json.JSONDecodeError:
+ return {}
+ return payload if isinstance(payload, dict) else {}
+
+ def setting(self, key: str, default: str = "") -> str:
+ row = self.conn.execute(
+ "SELECT value FROM settings WHERE key = ?", (key,)
+ ).fetchone()
+ return str(row["value"]) if row else default
+
+ def set_setting(self, key: str, value: str) -> None:
+ with self.conn:
+ self.conn.execute(
+ """INSERT INTO settings(key, value, updated_at)
+ VALUES (?, ?, ?)
+ ON CONFLICT(key) DO UPDATE SET
+ value = excluded.value,
+ updated_at = excluded.updated_at""",
+ (key, value, utc_now()),
+ )
+
+ def is_paused(self) -> bool:
+ return self.setting("paused", "false").lower() in {
+ "1",
+ "true",
+ "yes",
+ "on",
+ }
+
+ def forget_local_repo(self, repo_id: str) -> dict[str, int]:
+ tables = {
+ "events": "repo_id",
+ "session_scopes": "repo_id",
+ "flushes": "repo_id",
+ "retrievals": "repo_id",
+ "operations": "repo_id",
+ "sidekick_runs": "repo_id",
+ }
+ removed: dict[str, int] = {}
+ with self.conn:
+ for table, column in tables.items():
+ cursor = self.conn.execute(
+ f"DELETE FROM {table} WHERE {column} = ?", (repo_id,)
+ )
+ removed["subagent_runs" if table == "sidekick_runs" else table] = max(int(cursor.rowcount), 0)
+ return removed
+
+ def status(self, repo_id: str) -> dict[str, Any]:
+ def count(table: str) -> int:
+ return int(
+ self.conn.execute(
+ f"SELECT COUNT(*) FROM {table} WHERE repo_id = ?", (repo_id,)
+ ).fetchone()[0]
+ )
+
+ last_operation = self.conn.execute(
+ """SELECT created_at, operation, duration_ms, success, item_count, error
+ FROM operations WHERE repo_id = ? ORDER BY id DESC LIMIT 1""",
+ (repo_id,),
+ ).fetchone()
+ last_subagent = self.conn.execute(
+ """SELECT session_id, agent_id, agent_type, started_at, stopped_at,
+ context_chars
+ FROM sidekick_runs WHERE repo_id = ?
+ ORDER BY started_at DESC LIMIT 1""",
+ (repo_id,),
+ ).fetchone()
+ return {
+ "paused": self.is_paused(),
+ "events": count("events"),
+ "flushes": count("flushes"),
+ "retrievals": count("retrievals"),
+ "subagent_runs": count("sidekick_runs"),
+ "last_operation": dict(last_operation) if last_operation else None,
+ "last_subagent": dict(last_subagent) if last_subagent else None,
+ }
+
+
+def _session_id(hook_input: dict[str, Any]) -> str:
+ return str(hook_input.get("session_id") or "unknown-session")
+
+
+def record_session_start(store: EvidenceStore, hook_input: dict[str, Any]) -> None:
+ session_id = _session_id(hook_input)
+ repo = store.repo_for_session(session_id, hook_input.get("cwd"))
+ store.record_event(
+ repo,
+ session_id,
+ "session_start",
+ {
+ "source": hook_input.get("source", "startup"),
+ "model": bounded(hook_input.get("model", ""), 200),
+ "branch": repo.branch,
+ "head_sha": repo.head_sha,
+ },
+ )
+ telemetry.record(
+ "session_start",
+ repo=repo,
+ session_id=session_id,
+ trigger=bounded(str(hook_input.get("source", "startup")), 60),
+ model=bounded(hook_input.get("model", ""), 200),
+ api_key_configured=bool(api_key()),
+ is_git_repo=not repo.identity.startswith("local:"),
+ )
+
+
+def record_user_prompt(
+ store: EvidenceStore, hook_input: dict[str, Any]
+) -> tuple[RepoContext, str, str, bool]:
+ session_id = _session_id(hook_input)
+ repo = store.repo_for_session(session_id, hook_input.get("cwd"))
+ prompt = redact(hook_input.get("prompt", "")).strip()
+ is_first_prompt = not store.has_event(repo.identity, session_id, "user_prompt")
+ store.record_event(repo, session_id, "user_prompt", {"text": prompt})
+ return repo, session_id, prompt, is_first_prompt
+
+
+def _tool_result_preview(response: Any) -> str:
+ if isinstance(response, dict):
+ selected = {}
+ for key in (
+ "stdout",
+ "stderr",
+ "output",
+ "content",
+ "error",
+ "filePath",
+ "success",
+ "interrupted",
+ ):
+ if key in response:
+ selected[key] = response[key]
+ response = selected or {"keys": sorted(response.keys())[:20]}
+ return bounded(response, MAX_RESULT_CHARS)
+
+
+def tool_payload(hook_input: dict[str, Any], *, failed: bool | None = False) -> dict[str, Any]:
+ name = str(hook_input.get("tool_name") or "unknown")
+ tool_input = hook_input.get("tool_input") or {}
+ if not isinstance(tool_input, dict):
+ tool_input = {}
+ payload: dict[str, Any] = {
+ "tool": name,
+ "failed": failed,
+ "duration_ms": hook_input.get("duration_ms"),
+ "agent_role": "subagent" if hook_input.get("agent_id") else "main",
+ }
+ if hook_input.get("agent_id"):
+ payload["agent_id"] = bounded(hook_input["agent_id"], 200)
+ if hook_input.get("agent_type"):
+ payload["agent_type"] = bounded(hook_input["agent_type"], 200)
+
+ if name in {"Read", "Write", "Edit", "MultiEdit", "NotebookEdit"}:
+ path = tool_input.get("file_path") or tool_input.get("notebook_path")
+ if path:
+ payload["path"] = bounded(path, 1000)
+ if name in {"Write", "Edit", "MultiEdit", "NotebookEdit"}:
+ payload["mutation_chars"] = sum(
+ len(str(tool_input.get(key, "")))
+ for key in ("content", "new_string", "new_source", "edits")
+ )
+ elif name == "Bash" or "command" in tool_input:
+ command = bounded(tool_input.get("command", ""), MAX_COMMAND_CHARS)
+ payload["command"] = command
+ payload["command_kind"] = (
+ "test"
+ if TEST_COMMAND_RE.search(command)
+ else "build"
+ if BUILD_COMMAND_RE.search(command)
+ else "shell"
+ )
+ response = (
+ hook_input.get("error") if failed else hook_input.get("tool_response")
+ )
+ payload["result_preview"] = _tool_result_preview(response)
+ elif name in {"Grep", "Glob", "WebSearch", "WebFetch"}:
+ for key in ("pattern", "path", "query", "url"):
+ if tool_input.get(key):
+ payload[key] = bounded(tool_input[key], 1000)
+ else:
+ payload["input_keys"] = sorted(tool_input.keys())[:20]
+ if failed:
+ payload["error"] = bounded(hook_input.get("error", ""), MAX_RESULT_CHARS)
+
+ if failed and "error" not in payload:
+ payload["error"] = bounded(hook_input.get("error", ""), MAX_RESULT_CHARS)
+ return payload
+
+
+def record_tool(
+ store: EvidenceStore, hook_input: dict[str, Any], *, failed: bool | None = False
+) -> None:
+ session_id = _session_id(hook_input)
+ repo = store.repo_for_session(session_id, hook_input.get("cwd"))
+ payload = tool_payload(hook_input, failed=failed)
+ if payload.get("path"):
+ payload["repo_path"] = _repo_relative_path(repo, str(payload["path"]))
+ store.record_event(
+ repo,
+ session_id,
+ "tool_failure" if failed else "tool_result",
+ payload,
+ )
+
+
+def record_subagent_start(
+ store: EvidenceStore, hook_input: dict[str, Any]
+) -> str:
+ """Record a native subagent and reuse the main turn's retrieved memories."""
+ session_id = _session_id(hook_input)
+ repo = store.repo_for_session(session_id, hook_input.get("cwd"))
+ agent_id = bounded(hook_input.get("agent_id", "unknown-agent"), 200)
+ agent_type = bounded(hook_input.get("agent_type", "unknown-agent"), 200)
+ context = combine_context(
+ format_context(store.injected_memories(session_id, repo.identity))
+ )
+ first_start = store.start_subagent(
+ repo, session_id, agent_id, agent_type, len(context)
+ )
+ store.record_event(
+ repo,
+ session_id,
+ "subagent_start",
+ {
+ "agent_id": agent_id,
+ "agent_type": agent_type,
+ "context_chars": len(context) if first_start else 0,
+ "repo_root": bounded(repo.root, 2000),
+ },
+ )
+ telemetry.record(
+ "subagent",
+ repo=repo,
+ session_id=session_id,
+ phase="start",
+ first_start=first_start,
+ context_chars=len(context) if first_start else 0,
+ )
+ return context if first_start else ""
+
+
+def record_subagent_stop(store: EvidenceStore, hook_input: dict[str, Any]) -> None:
+ session_id = _session_id(hook_input)
+ repo = store.repo_for_session(session_id, hook_input.get("cwd"))
+ agent_type = bounded(hook_input.get("agent_type", "unknown-agent"), 200)
+ agent_id = bounded(hook_input.get("agent_id", ""), 200)
+ final_message = redact(hook_input.get("last_assistant_message", "")).strip()
+ transcript_path = bounded(hook_input.get("agent_transcript_path", ""), 2000)
+ agent_id = store.stop_subagent(
+ repo,
+ session_id,
+ agent_id,
+ agent_type,
+ transcript_path,
+ final_message,
+ )
+ store.record_event(
+ repo,
+ session_id,
+ "subagent_stop",
+ {
+ "agent_id": agent_id,
+ "agent_type": agent_type,
+ "transcript_path": transcript_path,
+ "final_message": final_message,
+ },
+ )
+ telemetry.record(
+ "subagent",
+ repo=repo,
+ session_id=session_id,
+ phase="stop",
+ has_transcript=bool(transcript_path),
+ message_chars=len(final_message),
+ )
+
+
+def _ordered_unique(values: Iterable[str]) -> list[str]:
+ seen: set[str] = set()
+ result = []
+ for value in values:
+ if value and value not in seen:
+ seen.add(value)
+ result.append(value)
+ return result
+
+
+def _repo_relative_path(repo: RepoContext, value: str) -> str:
+ value = str(value or "").strip()
+ if not value:
+ return ""
+ try:
+ path = Path(value)
+ if path.is_absolute():
+ try:
+ return path.resolve().relative_to(Path(repo.root).resolve()).as_posix()
+ except ValueError:
+ return ""
+ except (OSError, ValueError):
+ pass
+ return bounded(value, 1000)
+
+
+def _render_command_lines(commands: list[dict[str, str]]) -> list[str]:
+ lines = []
+ for command in commands:
+ line = f"- [{command['status']}/{command['kind']}] {command['command']}"
+ if command["result"]:
+ line += f" โ {bounded(command['result'], 500).replace(chr(10), ' ')}"
+ lines.append(line)
+ return lines
+
+
+def build_episode(
+ repo: RepoContext,
+ session_id: str,
+ packet_id: str,
+ events: list[dict[str, Any]],
+ *,
+ canonical_task: str = "",
+ task_outcome: str = "",
+) -> tuple[str, dict[str, Any]]:
+ prompts = [
+ redact(e["payload"].get("text", "")).strip()
+ for e in events
+ if e["kind"] == "user_prompt" and e["payload"].get("text")
+ ]
+ assistant_conclusions = [
+ redact(e["payload"].get("text", "")).strip()
+ for e in events
+ if e["kind"] == "assistant_stop" and e["payload"].get("text")
+ ]
+ subagent_outcomes = [
+ redact(e["payload"].get("final_message", "")).strip()
+ for e in events
+ if e["kind"] in {"subagent_stop", "sidekick_stop"} and e["payload"].get("final_message")
+ ]
+ tools = [
+ e["payload"] for e in events if e["kind"] in {"tool_result", "tool_failure"}
+ and e["payload"].get("agent_role", "main") == "main"
+ ]
+ read_paths = _ordered_unique(
+ _repo_relative_path(repo, str(t.get("repo_path") or t.get("path", "")))
+ for t in tools
+ if t.get("tool") == "Read"
+ )
+ modified_paths = _ordered_unique(
+ _repo_relative_path(repo, str(t.get("repo_path") or t.get("path", "")))
+ for t in tools
+ if t.get("tool") in {"Write", "Edit", "MultiEdit", "NotebookEdit"}
+ )
+ searches = [
+ {key: t[key] for key in ("tool", "pattern", "path", "query", "url") if key in t}
+ for t in tools
+ if t.get("tool") in {"Grep", "Glob", "WebSearch", "WebFetch"}
+ ]
+ commands = [
+ {
+ "command": t.get("command", ""),
+ "kind": t.get("command_kind", "shell"),
+ "status": "unknown" if t.get("failed", False) is None else "failed" if t.get("failed") else "succeeded",
+ "result": t.get("result_preview", ""),
+ }
+ for t in tools
+ if t.get("command")
+ ]
+
+ task = bounded(canonical_task or (prompts[0] if prompts else ""), 4000)
+ conclusion = redact(assistant_conclusions[-1] if assistant_conclusions else "").strip()
+ outcome = bounded(task_outcome, 2000)
+
+ extraction_messages: list[dict[str, str]] = []
+ pending_user_messages: list[dict[str, str]] = []
+ if task and not prompts:
+ pending_user_messages.append({"role": "user", "content": task})
+ for event in events:
+ if event["kind"] == "user_prompt" and event["payload"].get("text"):
+ pending_user_messages.append(
+ {
+ "role": "user",
+ "content": redact(event["payload"].get("text", "")).strip(),
+ }
+ )
+ elif event["kind"] == "assistant_stop":
+ transcript_messages = event["payload"].get("transcript_messages") or []
+ if isinstance(transcript_messages, list) and transcript_messages:
+ transcript_users = {
+ redact(message.get("content") or "").strip()
+ for message in transcript_messages
+ if isinstance(message, dict) and message.get("role") == "user"
+ }
+ extraction_messages.extend(
+ message
+ for message in pending_user_messages
+ if message["content"].strip() not in transcript_users
+ )
+ extraction_messages.extend(
+ {
+ "role": str(message.get("role") or ""),
+ "content": redact(message.get("content") or "").strip(),
+ }
+ for message in transcript_messages
+ if isinstance(message, dict)
+ and message.get("role") in {"user", "assistant"}
+ and message.get("content")
+ )
+ else:
+ extraction_messages.extend(pending_user_messages)
+ if event["payload"].get("text"):
+ extraction_messages.append(
+ {
+ "role": "assistant",
+ "content": redact(event["payload"].get("text", "")).strip(),
+ }
+ )
+ pending_user_messages = []
+ elif event["kind"] in {"subagent_stop", "sidekick_stop"}:
+ pass
+ extraction_messages.extend(pending_user_messages)
+
+ structured = {
+ "packet_id": packet_id,
+ "repo": repo.identity,
+ "app_id": repo.app_id,
+ "session_id": session_id,
+ "branch": repo.branch,
+ "head_sha": repo.head_sha,
+ "task": task,
+ "task_outcome": outcome,
+ "assistant_conclusion": conclusion,
+ "user_messages": prompts,
+ "assistant_outcomes": assistant_conclusions,
+ "subagent_outcomes": subagent_outcomes,
+ "extraction_messages": extraction_messages,
+ "files_read": read_paths[:50],
+ "files_modified": modified_paths[:50],
+ "searches": searches[-30:],
+ "commands": commands[-30:],
+ }
+ lines = ["Coding-session episode"]
+ if task:
+ lines.extend(["", "Task:", task])
+ if modified_paths:
+ lines.extend(
+ ["", "Files modified:", *[f"- {path}" for path in modified_paths[:50]]]
+ )
+ if read_paths:
+ lines.extend(["", "Files read:", *[f"- {path}" for path in read_paths[:50]]])
+ if commands:
+ lines.append("")
+ lines.append("Observed commands:")
+ lines.extend(_render_command_lines(commands[-30:]))
+ if searches:
+ lines.extend(
+ [
+ "",
+ "Observed searches:",
+ *[
+ f"- {json.dumps(item, ensure_ascii=False, sort_keys=True)}"
+ for item in searches[-20:]
+ ],
+ ]
+ )
+ if conclusion:
+ lines.extend(["", "Agent conclusion:", conclusion])
+ if outcome:
+ lines.extend(["", "Task outcome:", outcome])
+ lines.extend(
+ [
+ "",
+ f"Provenance: repo={repo.identity}; branch={repo.branch}; head={repo.head_sha}; packet={packet_id}",
+ ]
+ )
+ content = "\n".join(lines)
+ return bounded(content, MAX_EPISODE_CHARS), structured
+
+
+def build_semantic_evidence(structured: dict[str, Any]) -> str:
+ """Format changed paths for memory extraction.
+
+ Test and build results remain in the local evidence store for diagnostics,
+ but are not useful repository knowledge by default and should not steer
+ memory extraction toward transient verification details.
+ """
+ modified_paths = [
+ bounded(path, 500) for path in structured.get("files_modified", [])[:20]
+ ]
+ commands = structured.get("commands") or []
+ if not any(command.get("status") == "failed" for command in commands):
+ commands = []
+
+ if not modified_paths and not commands:
+ return ""
+
+ lines = ["Additional repository details from this session"]
+ if modified_paths:
+ lines.extend(
+ [
+ "",
+ "Changed paths:",
+ *[f"- {path}" for path in modified_paths],
+ ]
+ )
+ if commands:
+ lines.extend(["", "Commands run in this session:", *_render_command_lines(commands)])
+ return bounded("\n".join(lines), 8000)
+
+
+def build_extraction_messages(structured: dict[str, Any]) -> list[dict[str, str]]:
+ """Build the session messages sent to Mem0 for memory extraction."""
+ evidence = build_semantic_evidence(structured)
+ messages = [
+ {"role": message["role"], "content": redact(message["content"]).strip()}
+ for message in structured.get("extraction_messages", [])
+ if message.get("role") in {"user", "assistant"} and message.get("content")
+ ]
+ if evidence:
+ for message in reversed(messages):
+ if message["role"] == "assistant":
+ message["content"] = f"{message['content']}\n\n{evidence}"
+ break
+ else:
+ messages.append({"role": "assistant", "content": evidence})
+
+ return messages
+
+
+def _estimated_tokens(value: str) -> int:
+ """Conservatively estimate tokens without adding a tokenizer dependency."""
+ ascii_chars = sum(ord(char) < 128 for char in value)
+ return math.ceil((ascii_chars * 0.4) + (len(value) - ascii_chars))
+
+
+def _message_tokens(messages: list[dict[str, str]]) -> int:
+ return _estimated_tokens(json.dumps(messages, ensure_ascii=False))
+
+
+def _is_agent_assignment(message: dict[str, str]) -> bool:
+ return message.get("role") == "assistant" and message.get(
+ "content", ""
+ ).startswith("Subagent assignment (")
+
+
+def _is_agent_response(message: dict[str, str]) -> bool:
+ return message.get("role") == "assistant" and message.get(
+ "content", ""
+ ).startswith("Subagent response (")
+
+
+def extraction_message_batches(
+ messages: list[dict[str, str]],
+ *,
+ max_tokens: int = MAX_EXTRACTION_INPUT_TOKENS,
+) -> list[list[dict[str, str]]]:
+ """Keep exchanges together when possible; split oversized messages to enforce the request budget."""
+ if not messages or _message_tokens(messages) <= max_tokens:
+ return [messages]
+
+ exchanges: list[list[dict[str, str]]] = []
+ exchange: list[dict[str, str]] = []
+ for message in messages:
+ if message.get("role") == "user" and exchange:
+ exchanges.append(exchange)
+ exchange = []
+ exchange.append(message)
+ if exchange:
+ exchanges.append(exchange)
+
+ units: list[list[dict[str, str]]] = []
+ for exchange in exchanges:
+ if _message_tokens(exchange) <= max_tokens:
+ units.append(exchange)
+ continue
+ index = 0
+ while index < len(exchange):
+ message = exchange[index]
+ if (
+ _is_agent_assignment(message)
+ and index + 1 < len(exchange)
+ and _is_agent_response(exchange[index + 1])
+ ):
+ units.append(exchange[index : index + 2])
+ index += 2
+ else:
+ units.append([message])
+ index += 1
+
+ bounded_units: list[list[dict[str, str]]] = []
+ for unit in units:
+ if _message_tokens(unit) <= max_tokens:
+ bounded_units.append(unit)
+ continue
+ for message in unit:
+ remaining = message["content"]
+ while remaining:
+ low, high = 0, len(remaining)
+ while low < high:
+ middle = (low + high + 1) // 2
+ if _message_tokens([{**message, "content": remaining[:middle]}]) <= max_tokens:
+ low = middle
+ else:
+ high = middle - 1
+ if low == 0:
+ raise ValueError("Extraction token budget cannot fit a message")
+ bounded_units.append([{**message, "content": remaining[:low]}])
+ remaining = remaining[low:]
+
+ batches: list[list[dict[str, str]]] = []
+ batch: list[dict[str, str]] = []
+ for unit in bounded_units:
+ candidate = [*batch, *unit]
+ if batch and _message_tokens(candidate) > max_tokens:
+ batches.append(batch)
+ batch = list(unit)
+ else:
+ batch = candidate
+ if batch:
+ batches.append(batch)
+ return batches
+
+
+# Platform surface attribution. Read from the generated per-host module so a new
+# entrypoint is correct without remembering to configure anything.
+try: # pragma: no cover - absent only in the un-built shared source tree
+ from _harness_id import PLATFORM_APPLICATION as _PLATFORM_APPLICATION
+ from _harness_id import PLATFORM_SOURCE as _PLATFORM_SOURCE
+except ImportError:
+ _PLATFORM_SOURCE = "MEM0_PLUGIN"
+ _PLATFORM_APPLICATION = ""
+
+
+def platform_headers(key: str) -> dict[str, str]:
+ """Auth plus the three surface-identity headers.
+
+ X-Mem0-Source and X-Application are set-once by contract: this is the
+ outermost layer, so it sets them, and nothing below may overwrite them.
+ X-Mem0-Client is append-only โ anything downstream adds itself to the tail.
+ """
+ headers = {
+ "Authorization": f"Token {key}",
+ "Content-Type": "application/json",
+ "X-Mem0-Source": _PLATFORM_SOURCE,
+ "X-Mem0-Client": f"mem0-plugin/{PLUGIN_VERSION}",
+ }
+ if _PLATFORM_APPLICATION:
+ headers["X-Application"] = _PLATFORM_APPLICATION
+ return headers
+
+
+def _request_json(
+ url: str, key: str, payload: dict[str, Any], timeout: float
+) -> tuple[dict[str, Any] | list[Any], int, int]:
+ raw = json.dumps(payload, ensure_ascii=False).encode()
+ request = urllib.request.Request(
+ url,
+ data=raw,
+ headers=platform_headers(key),
+ method="POST",
+ )
+ with urllib.request.urlopen(request, timeout=timeout) as response:
+ response_raw = response.read()
+ parsed = json.loads(response_raw or b"{}")
+ return parsed, len(raw), len(response_raw)
+
+
+def _request_json_with_network_retry(
+ url: str, key: str, payload: dict[str, Any], timeout: float
+) -> tuple[dict[str, Any] | list[Any], int, int]:
+ """Retry one transient connection failure without retrying API responses."""
+ try:
+ return _request_json(url, key, payload, timeout)
+ except urllib.error.HTTPError:
+ raise
+ except (urllib.error.URLError, TimeoutError, OSError):
+ time.sleep(0.25)
+ return _request_json(url, key, payload, timeout)
+
+
+def _get_json(
+ url: str, key: str, timeout: float
+) -> tuple[dict[str, Any] | list[Any], int]:
+ request = urllib.request.Request(
+ url,
+ headers=platform_headers(key),
+ method="GET",
+ )
+ with urllib.request.urlopen(request, timeout=timeout) as response:
+ response_raw = response.read()
+ return json.loads(response_raw or b"{}"), len(response_raw)
+
+
+def _event_id(response: dict[str, Any] | list[Any]) -> str:
+ return str(response.get("event_id", "")) if isinstance(response, dict) else ""
+
+
+def _stored_event_ids(value: Any) -> list[str]:
+ raw = str(value or "")
+ if not raw.startswith("["):
+ return []
+ try:
+ parsed = json.loads(raw)
+ except json.JSONDecodeError:
+ return []
+ return [str(item or "") for item in parsed] if isinstance(parsed, list) else []
+
+
+def _result_count(response: dict[str, Any] | list[Any]) -> int:
+ if isinstance(response, dict):
+ results = response.get("results")
+ return len(results) if isinstance(results, list) else 0
+ return len(response) if isinstance(response, list) else 0
+
+
+def touch_handoff_heartbeat() -> None:
+ """Mark the worker's handoff file alive so recovery does not relaunch it."""
+ path = os.environ.get("MEM0_CODE_HANDOFF_PATH", "")
+ if not path:
+ return
+ try:
+ os.utime(path)
+ except OSError:
+ pass
+
+
+def _wait_for_event(api_url: str, key: str, event_id: str) -> tuple[str, int, int]:
+ """Wait for extraction to finish before a later task can search the store."""
+ if not event_id:
+ return "MISSING", 0, 0
+ wait_seconds = float(os.environ.get("MEM0_CODE_EXTRACTION_WAIT_SECONDS", "120"))
+ poll_seconds = max(float(os.environ.get("MEM0_CODE_EVENT_POLL_SECONDS", "1")), 0.1)
+ deadline = time.monotonic() + wait_seconds
+ response_chars = 0
+ while time.monotonic() < deadline:
+ touch_handoff_heartbeat()
+ try:
+ response, size = _get_json(
+ f"{api_url}/v1/event/{event_id}/",
+ key,
+ min(10, poll_seconds + 5),
+ )
+ except urllib.error.HTTPError as exc:
+ if exc.code not in {408, 429} and exc.code < 500:
+ raise
+ time.sleep(poll_seconds)
+ continue
+ except (urllib.error.URLError, TimeoutError, OSError):
+ # The extraction job is durable server-side. A transient polling
+ # failure must not discard a job that may still complete normally.
+ time.sleep(poll_seconds)
+ continue
+ response_chars += size
+ status = (
+ str(response.get("status", "UNKNOWN"))
+ if isinstance(response, dict)
+ else "UNKNOWN"
+ )
+ if status in {"SUCCEEDED", "FAILED"}:
+ return status, response_chars, _result_count(response)
+ time.sleep(poll_seconds)
+ return "TIMEOUT", response_chars, 0
+
+
+def _record_flush(
+ repo: RepoContext,
+ session_id: str,
+ reason: str,
+ status: str,
+ elapsed: float,
+ **extra: Any,
+) -> None:
+ telemetry.record(
+ "flush",
+ repo=repo,
+ session_id=session_id,
+ reason=reason,
+ status=status,
+ success=status in {"semantic-succeeded", "nothing-to-flush"},
+ duration_ms=round(elapsed, 2),
+ **extra,
+ )
+
+
+def flush_session(
+ store: EvidenceStore, hook_input: dict[str, Any], reason: str
+) -> dict[str, Any]:
+ key = api_key()
+ if not key:
+ telemetry.record("flush", reason=reason, status="local-only", success=False)
+ return {"status": "local-only", "reason": "no-api-key"}
+
+ session_id = _session_id(hook_input)
+ if session_id == "unknown-session":
+ telemetry.record("flush", reason=reason, status="no-session-id", success=False)
+ return {"status": "error", "reason": "no-session-id"}
+ repo = store.repo_for_session(session_id, hook_input.get("cwd"))
+ prepared = store.prepare_flush(repo, session_id, reason)
+ if prepared is None:
+ return {"status": "nothing-to-flush"}
+ packet_id, events = prepared
+ existing_flush = store.flush_record(packet_id) or {}
+
+ _, structured = build_episode(
+ repo,
+ session_id,
+ packet_id,
+ events,
+ canonical_task=bounded(hook_input.get("task", ""), 4000),
+ task_outcome=bounded(hook_input.get("task_outcome", ""), 2000),
+ )
+
+ metadata = {"source": _harness_source_tag}
+ if repo.branch and repo.branch not in {"detached", "unknown"}:
+ metadata["branch"] = repo.branch
+ if repo.head_sha:
+ metadata["git_sha"] = repo.head_sha
+ api_url = os.environ.get("MEM0_API_URL", DEFAULT_API_URL).rstrip("/")
+ add_url = f"{api_url}/v3/memories/add/"
+
+ write_user = _scope_value(user_id())
+ write_project = _scope_value(repo.project_id)
+ if not write_user or not _scope_value(repo.app_id) or not write_project:
+ telemetry.record("flush", reason=reason, status="unscoped", success=False)
+ return {"status": "error", "reason": "wildcard-scope"}
+
+ body = {
+ "agent_id": write_project,
+ "user_id": write_user,
+ "app_id": repo.app_id,
+ "run_id": session_id,
+ # Top level, not metadata: the backend reads `source` from the body or
+ # the query string, never from metadata, which is where this used to
+ # sit. The X-Mem0-Source header is also read, but only from the
+ # platform release that ships alongside this change, so the body value
+ # is what makes attribution work on both. The harness tag stays in
+ # metadata as hook provenance.
+ "source": _PLATFORM_SOURCE,
+ "metadata": {**metadata, "author": write_user, "dirs": directory_chain(repo)},
+ "agent_custom_instructions": PROJECT_MEMORY_INSTRUCTIONS,
+ "custom_instructions": PERSONAL_MEMORY_INSTRUCTIONS,
+ "custom_categories": CODING_MEMORY_CATEGORIES,
+ "infer": True,
+ }
+
+ started = time.perf_counter()
+ try:
+ stored_events = _stored_event_ids(existing_flush.get("semantic_event_id"))
+ existing_event = (
+ "" if stored_events else str(existing_flush.get("semantic_event_id") or "")
+ )
+ if existing_event:
+ existing_status, existing_resp, existing_items = _wait_for_event(
+ api_url, key, existing_event
+ )
+ if existing_status == "SUCCEEDED":
+ elapsed = (time.perf_counter() - started) * 1000
+ store.update_flush(
+ packet_id,
+ status="semantic-succeeded",
+ semantic_event_id=existing_event,
+ error="",
+ )
+ store.operation(
+ repo,
+ session_id,
+ "flush-retry",
+ elapsed,
+ True,
+ item_count=existing_items,
+ response_chars=existing_resp,
+ )
+ _record_flush(
+ repo,
+ session_id,
+ reason,
+ "semantic-succeeded",
+ elapsed,
+ memory_count=existing_items,
+ resumed=True,
+ )
+ effective_reason = str(
+ (store.flush_record(packet_id) or {}).get("reason") or reason
+ )
+ if (
+ store.has_unflushed_events(repo.identity, session_id)
+ and not store.unflushed_starts_with_session_start(
+ repo.identity, session_id
+ )
+ and (
+ effective_reason != "periodic"
+ or store.checkpoint_due(repo.identity, session_id)
+ )
+ ):
+ return flush_session(store, hook_input, effective_reason)
+ return {
+ "status": "semantic-succeeded",
+ "packet_id": packet_id,
+ "semantic_event_id": existing_event,
+ "semantic_status": existing_status,
+ "memory_count": existing_items,
+ "duration_ms": round(elapsed, 2),
+ "resumed": True,
+ }
+ if existing_status == "TIMEOUT":
+ elapsed = (time.perf_counter() - started) * 1000
+ error = "semantic extraction event timed out"
+ store.update_flush(packet_id, status="semantic-timeout", error=error)
+ store.operation(
+ repo,
+ session_id,
+ "flush-retry",
+ elapsed,
+ False,
+ response_chars=existing_resp,
+ error=error,
+ )
+ _record_flush(
+ repo,
+ session_id,
+ reason,
+ "semantic-timeout",
+ elapsed,
+ resumed=True,
+ error_kind="timeout",
+ )
+ return {
+ "status": "semantic-timeout",
+ "packet_id": packet_id,
+ "semantic_event_id": existing_event,
+ "duration_ms": round(elapsed, 2),
+ "resumed": True,
+ }
+
+ message_batches = [
+ batch
+ for batch in extraction_message_batches(
+ build_extraction_messages(structured)
+ )
+ if batch
+ ]
+ batches = [(body, messages) for messages in message_batches]
+ if not batches:
+ store.update_flush(packet_id, status="semantic-succeeded", error="")
+ return {"status": "nothing-to-flush", "packet_id": packet_id}
+ operation_name = "flush-retry" if stored_events else "flush"
+ semantic_events = stored_events[: len(batches)]
+ semantic_events += [""] * (len(batches) - len(semantic_events))
+ semantic_req = 0
+ semantic_resp = 0
+ for index, (body, messages) in enumerate(batches):
+ if semantic_events[index]:
+ continue
+ semantic_response, request_chars, response_chars = _request_json(
+ add_url,
+ key,
+ {**body, "messages": messages},
+ 15,
+ )
+ semantic_events[index] = _event_id(semantic_response)
+ semantic_req += request_chars
+ semantic_resp += response_chars
+ store.update_flush(
+ packet_id,
+ status="semantic-queued",
+ semantic_event_id=json.dumps(semantic_events),
+ )
+
+ semantic_event = semantic_events[-1]
+ semantic_status = "SUCCEEDED"
+ event_resp = 0
+ semantic_items = 0
+ failed_event = semantic_event
+ for index, queued_event in enumerate(semantic_events):
+ status, response_chars, item_count = _wait_for_event(
+ api_url, key, queued_event
+ )
+ event_resp += response_chars
+ semantic_items += item_count
+ if status != "SUCCEEDED":
+ semantic_status = status
+ failed_event = queued_event
+ if status in {"FAILED", "MISSING"}:
+ semantic_events[index] = ""
+ store.update_flush(
+ packet_id, semantic_event_id=json.dumps(semantic_events)
+ )
+ break
+ if semantic_status != "SUCCEEDED":
+ elapsed = (time.perf_counter() - started) * 1000
+ error = f"semantic extraction event {semantic_status.lower()}"
+ store.update_flush(
+ packet_id, status=f"semantic-{semantic_status.lower()}", error=error
+ )
+ store.operation(
+ repo,
+ session_id,
+ operation_name,
+ elapsed,
+ False,
+ item_count=semantic_items,
+ request_chars=semantic_req,
+ response_chars=semantic_resp + event_resp,
+ error=error,
+ )
+ _record_flush(
+ repo,
+ session_id,
+ reason,
+ f"semantic-{semantic_status.lower()}",
+ elapsed,
+ memory_count=semantic_items,
+ batch_count=len(batches),
+ error_kind=telemetry.error_kind(error),
+ )
+ return {
+ "status": f"semantic-{semantic_status.lower()}",
+ "packet_id": packet_id,
+ "semantic_event_id": failed_event,
+ "memory_count": semantic_items,
+ "duration_ms": round(elapsed, 2),
+ }
+
+ elapsed = (time.perf_counter() - started) * 1000
+ store.update_flush(
+ packet_id,
+ status="semantic-succeeded",
+ semantic_event_id=json.dumps(semantic_events),
+ error="",
+ )
+ store.operation(
+ repo,
+ session_id,
+ operation_name,
+ elapsed,
+ True,
+ item_count=semantic_items,
+ request_chars=semantic_req,
+ response_chars=semantic_resp + event_resp,
+ )
+ _record_flush(
+ repo,
+ session_id,
+ reason,
+ "semantic-succeeded",
+ elapsed,
+ memory_count=semantic_items,
+ batch_count=len(batches),
+ request_chars=semantic_req,
+ )
+ effective_reason = str(
+ (store.flush_record(packet_id) or {}).get("reason") or reason
+ )
+ if (
+ store.has_unflushed_events(repo.identity, session_id)
+ and not store.unflushed_starts_with_session_start(
+ repo.identity, session_id
+ )
+ and (
+ effective_reason != "periodic"
+ or store.checkpoint_due(repo.identity, session_id)
+ )
+ ):
+ return flush_session(store, hook_input, effective_reason)
+ return {
+ "status": "semantic-succeeded",
+ "packet_id": packet_id,
+ "semantic_event_id": semantic_event,
+ "semantic_status": semantic_status,
+ "memory_count": semantic_items,
+ "duration_ms": round(elapsed, 2),
+ }
+ except Exception as exc: # hooks must fail open
+ elapsed = (time.perf_counter() - started) * 1000
+ error = bounded(str(exc), 1000)
+ store.update_flush(packet_id, status="error", error=error)
+ store.operation(repo, session_id, "flush", elapsed, False, error=error)
+ _record_flush(
+ repo,
+ session_id,
+ reason,
+ "error",
+ elapsed,
+ error_kind=telemetry.error_kind(exc),
+ )
+ return {"status": "error", "packet_id": packet_id, "error": error}
+
+
+def checkpoint_session(
+ store: EvidenceStore, hook_input: dict[str, Any], reason: str
+) -> dict[str, Any]:
+ """Run remote extraction at a durable boundary."""
+ return flush_session(store, hook_input, reason)
+
+
+
+def search_memories(
+ store: EvidenceStore | None,
+ repo: RepoContext,
+ session_id: str | None,
+ query: str,
+ *,
+ top_k: int | None = None,
+ category: str | None = None,
+ scope: str | None = None,
+ run_id: str | None = None,
+ operation: str = "search",
+ timeout: float = 5,
+) -> MemorySearchResult:
+ key = api_key()
+ if not key or not query.strip():
+ return MemorySearchResult(False, 0, 0, [])
+ search_once = os.environ.get(
+ "MEM0_CODE_SEARCH_ONCE_PER_SESSION", "false"
+ ).lower() in {
+ "1",
+ "true",
+ "yes",
+ "on",
+ }
+ track_session = store is not None and bool(session_id)
+ if (
+ search_once
+ and track_session
+ and store.has_operation(repo.identity, session_id, "search")
+ ):
+ return MemorySearchResult(False, 0, 0, [])
+
+ result_limit = min(
+ max(
+ top_k
+ if top_k is not None
+ else _int_option("top_k", "MEM0_CODE_TOP_K", 3),
+ 1,
+ ),
+ 20,
+ )
+ if category is not None and category not in CODING_MEMORY_CATEGORY_NAMES:
+ raise ValueError(f"Unknown memory category: {category}")
+ user, project = _scope_value(user_id()), _scope_value(repo.project_id)
+ if not user or not project or not _scope_value(repo.app_id):
+ return MemorySearchResult(False, 0, 0, [])
+ filters = _search_filters(user, repo, resolve_search_scope(scope))
+ if category:
+ filters = {"AND": [filters, {"categories": {"contains": category}}]}
+ if run_id:
+ filters = {"AND": [filters, {"run_id": run_id}]}
+ payload = {
+ "query": query,
+ "app_id": repo.app_id,
+ "filters": filters,
+ "top_k": result_limit,
+ "rerank": False,
+ "latest_only": True,
+ }
+ url = (
+ os.environ.get("MEM0_API_URL", DEFAULT_API_URL).rstrip("/")
+ + "/v3/memories/search/"
+ )
+ started = time.perf_counter()
+ try:
+ response, request_chars, response_chars = _request_json_with_network_retry(
+ url, key, payload, timeout
+ )
+ memories = (
+ response if isinstance(response, list) else response.get("results", [])
+ )
+ memories = [
+ memory
+ for memory in memories
+ if isinstance(memory, dict)
+ and (memory.get("metadata") or {}).get("record_kind") != "task_episode"
+ ][:result_limit]
+ if track_session:
+ returned_memories = store.unseen(session_id, repo.identity, memories)
+ store.mark_injected(session_id, repo.identity, returned_memories)
+ already_shown_count = len(memories) - len(returned_memories)
+ else:
+ returned_memories = memories
+ already_shown_count = 0
+ elapsed = (time.perf_counter() - started) * 1000
+ if track_session:
+ store.operation(
+ repo,
+ session_id,
+ operation,
+ elapsed,
+ True,
+ item_count=len(returned_memories),
+ request_chars=request_chars,
+ response_chars=response_chars,
+ )
+ telemetry.record(
+ "search",
+ repo=repo,
+ session_id=session_id,
+ trigger=operation,
+ success=True,
+ duration_ms=round(elapsed, 2),
+ matched_count=len(memories),
+ returned_count=len(returned_memories),
+ already_shown_count=already_shown_count,
+ top_k=result_limit,
+ has_category=bool(category),
+ )
+ return MemorySearchResult(
+ succeeded=True,
+ matched_count=len(memories),
+ already_shown_count=already_shown_count,
+ memories=returned_memories,
+ )
+ except Exception as exc:
+ elapsed = (time.perf_counter() - started) * 1000
+ if track_session:
+ store.operation(repo, session_id, operation, elapsed, False, error=str(exc))
+ telemetry.record(
+ "search",
+ repo=repo,
+ session_id=session_id,
+ trigger=operation,
+ success=False,
+ duration_ms=round(elapsed, 2),
+ top_k=result_limit,
+ has_category=bool(category),
+ error_kind=telemetry.error_kind(exc),
+ )
+ return MemorySearchResult(False, 0, 0, [])
+
+
+def format_context(
+ memories: list[dict[str, Any]],
+ heading: str = "Relevant repository memories:",
+) -> str:
+ if not memories:
+ return ""
+ limit = min(
+ max(
+ _int_option(
+ "max_context_chars",
+ "MEM0_CODE_MAX_CONTEXT_CHARS",
+ DEFAULT_MAX_CONTEXT_CHARS,
+ ),
+ 1000,
+ ),
+ 10000,
+ )
+ lines = [heading] if heading else []
+ for memory in memories:
+ text = re.sub(
+ r"\s+",
+ " ",
+ redact(memory.get("memory") or memory.get("text") or ""),
+ )
+ text = text.strip()
+ if not text:
+ continue
+ branch = str((memory.get("metadata") or {}).get("branch") or "").strip()
+ branch_label = (
+ f" [learnt on branch {branch}]"
+ if branch.casefold() not in {"", "main", "master", "unknown", "detached"}
+ else ""
+ )
+ number = len(lines) if heading else len(lines) + 1
+ entry = f"{number}. {text}{branch_label}"
+ candidate = "\n".join([*lines, entry])
+ if len(candidate) <= limit:
+ lines.append(entry)
+ continue
+ if not lines or (heading and len(lines) == 1):
+ prefix = f"{number}. "
+ suffix = f"โฆ{branch_label}"
+ available = (
+ limit
+ - len("\n".join(lines))
+ - (1 if lines else 0)
+ - len(prefix)
+ - len(suffix)
+ )
+ if available > 0:
+ lines.append(prefix + text[:available].rstrip() + suffix)
+ break
+ minimum_lines = 2 if heading else 1
+ return "\n".join(lines) if len(lines) >= minimum_lines else ""
+
+
+def format_search_result(result: MemorySearchResult) -> str:
+ """Return only the text the coding agent needs from an explicit memory search."""
+ if not result.succeeded:
+ return "Memory search failed."
+ if result.memories:
+ rendered = format_context(result.memories, heading="")
+ if rendered:
+ return rendered
+ return "No matching memories found."
+
+
+def combine_context(*contexts: str) -> str:
+ """Combine memory sources under one hard budget without repeated lines."""
+ seen: set[str] = set()
+ lines: list[str] = []
+ for context in contexts:
+ for line in str(context or "").splitlines():
+ normalized = re.sub(r"\s+", " ", line).strip().casefold()
+ if not normalized or normalized in seen:
+ continue
+ seen.add(normalized)
+ lines.append(line.rstrip())
+ limit = min(
+ max(
+ _int_option(
+ "max_context_chars",
+ "MEM0_CODE_MAX_CONTEXT_CHARS",
+ DEFAULT_MAX_CONTEXT_CHARS,
+ ),
+ 1000,
+ ),
+ 10000,
+ )
+ return bounded("\n".join(lines), limit) if lines else ""
+
+
+def _scoped_memory_ids(
+ api_url: str, key: str, user: str, repo: RepoContext, include_project: bool
+) -> list[str]:
+ """List this user's memory ids for this repository, plus the shared project memory when asked."""
+ ids: list[str] = []
+ seen: set[str] = set()
+ prefix = repo.app_id
+ _collect_memory_ids(
+ api_url, key, {"user_id": user}, ids, seen,
+ app_id_prefix=prefix,
+ )
+ if include_project:
+ for project_id in _shared_project_ids(repo):
+ _collect_memory_ids(
+ api_url, key, {"agent_id": project_id}, ids, seen,
+ app_id_prefix=prefix,
+ )
+ return ids
+
+
+def _collect_memory_ids(
+ api_url: str,
+ key: str,
+ filters: dict[str, Any],
+ ids: list[str],
+ seen: set[str],
+ *,
+ app_id_prefix: str = "",
+) -> None:
+ """Page through one list filter; the list endpoint returns nothing for an OR whose user branch has no memories."""
+ payload = {"filters": filters}
+ for page in range(1, FORGET_MAX_PAGES + 1):
+ parsed, _, _ = _request_json(
+ f"{api_url}/v2/memories/?page={page}&page_size={FORGET_PAGE_SIZE}",
+ key,
+ payload,
+ 15,
+ )
+ items = parsed.get("results") if isinstance(parsed, dict) else parsed
+ if not isinstance(items, list) or not items:
+ break
+ for item in items:
+ if not isinstance(item, dict):
+ continue
+ memory_id = str(item.get("id", ""))
+ if not memory_id or memory_id in seen:
+ continue
+ if app_id_prefix:
+ item_app_id = str(item.get("app_id") or "")
+ if item_app_id != app_id_prefix and not item_app_id.startswith(app_id_prefix + "/"):
+ continue
+ seen.add(memory_id)
+ ids.append(memory_id)
+ if len(items) < FORGET_PAGE_SIZE:
+ break
+
+
+def _delete_memory(api_url: str, key: str, memory_id: str) -> bool:
+ request = urllib.request.Request(
+ f"{api_url}/v1/memories/{urllib.parse.quote(memory_id)}/",
+ headers=platform_headers(key),
+ method="DELETE",
+ )
+ try:
+ with urllib.request.urlopen(request, timeout=15):
+ return True
+ except Exception:
+ return False
+
+
+def forget_remote_repo(
+ repo: RepoContext, *, include_project_memory: bool = False
+) -> dict[str, Any]:
+ """Delete this user's memories for this repository; project memory is shared, so only on request."""
+ key = api_key()
+ if not key:
+ telemetry.record("forget", repo=repo, success=False, error_kind="no-api-key")
+ return {"status": "error", "error": "Mem0 API key is not configured"}
+ user = _scope_value(user_id())
+ if not user or not _scope_value(repo.app_id) or not _scope_value(repo.project_id):
+ telemetry.record("forget", repo=repo, success=False, error_kind="unscoped")
+ return {
+ "status": "error",
+ "error": "Refusing to forget: the user or repository scope is a wildcard",
+ }
+ api_url = os.environ.get("MEM0_API_URL", DEFAULT_API_URL).rstrip("/")
+ try:
+ memory_ids = _scoped_memory_ids(api_url, key, user, repo, include_project_memory)
+ except Exception as exc:
+ telemetry.record(
+ "forget", repo=repo, success=False, error_kind=telemetry.error_kind(exc)
+ )
+ return {"status": "error", "error": bounded(str(exc), 1000)}
+ deleted = sum(_delete_memory(api_url, key, memory_id) for memory_id in memory_ids)
+ failed = len(memory_ids) - deleted
+ telemetry.record("forget", repo=repo, success=not failed, item_count=deleted)
+ if failed:
+ return {
+ "status": "partial",
+ "deleted": deleted,
+ "failed": failed,
+ "error": f"{failed} of {len(memory_ids)} memories could not be deleted",
+ }
+ return {"status": "deleted", "deleted": deleted}
+
+
+def _doctor_mem0_authentication(repo: RepoContext) -> dict[str, Any]:
+ """Verify the configured key with one read-only, repository-scoped search."""
+ key = api_key()
+ if not key:
+ return {"ok": False, "detail": "API key missing"}
+ payload = {
+ "query": "Mem0 authentication check",
+ "filters": {
+ "AND": [
+ {"user_id": user_id()},
+ {"app_id": repo.app_id},
+ ]
+ },
+ "top_k": 1,
+ "threshold": 1.0,
+ "rerank": False,
+ }
+ url = os.environ.get("MEM0_API_URL", DEFAULT_API_URL).rstrip("/")
+ started = time.perf_counter()
+ try:
+ _request_json(f"{url}/v3/memories/search/", key, payload, 5)
+ except Exception as exc:
+ return {"ok": False, "detail": bounded(str(exc), 300)}
+ elapsed = (time.perf_counter() - started) * 1000
+ return {"ok": True, "detail": f"connected ({elapsed:.0f} ms)"}
+
+
+def _doctor_user_id() -> dict[str, Any]:
+ """Flag a configured user ID the plugin refuses, since the silent fallback surprises people."""
+ configured = _plugin_option("user_id", "MEM0_CODE_USER_ID") or os.environ.get(
+ "MEM0_USER_ID", ""
+ )
+ if configured and not _scope_value(configured):
+ return {
+ "ok": False,
+ "detail": f"configured user_id {configured!r} is a wildcard; using {user_id()!r}",
+ }
+ return {"ok": True, "detail": user_id()}
+
+
+def doctor(cwd: str | None = None) -> dict[str, Any]:
+ repo = resolve_repo(cwd)
+ directory = data_dir()
+ directory.mkdir(parents=True, exist_ok=True)
+ checks: dict[str, dict[str, Any]] = {
+ "python": {
+ "ok": tuple(sys.version_info[:2]) >= (3, 10),
+ "detail": f"{sys.version_info.major}.{sys.version_info.minor}",
+ },
+ "data_directory": {
+ "ok": os.access(directory, os.W_OK),
+ "detail": str(directory),
+ },
+ "mem0_api_key": {
+ "ok": bool(api_key()),
+ "detail": "configured" if api_key() else "missing",
+ },
+ "repository": {
+ "ok": bool(repo.identity),
+ "detail": repo.identity,
+ },
+ "user_id": _doctor_user_id(),
+ "mem0_authentication": _doctor_mem0_authentication(repo),
+ }
+ return {
+ "ok": all(bool(value["ok"]) for value in checks.values()),
+ "plugin_version": PLUGIN_VERSION,
+ "repo_id": repo.identity,
+ "app_id": repo.app_id,
+ "user_id": user_id(),
+ "checks": checks,
+ }
diff --git a/integrations/codex-plugin/core/telemetry.py b/integrations/codex-plugin/core/telemetry.py
new file mode 100644
index 000000000..c1fc0084c
--- /dev/null
+++ b/integrations/codex-plugin/core/telemetry.py
@@ -0,0 +1,1013 @@
+#!/usr/bin/env python3
+"""Usage telemetry for Mem0 agent plugins.
+
+Events are linked to your Mem0 account email when an API key is configured, and
+to a random per-machine id otherwise. Not anonymous โ the Python SDK and CLI
+attribute the same way.
+
+Hooks run on a 3-6 second budget and fire on every tool call, so recording never
+touches the network: `record` appends one JSON line to a local spool and returns.
+A detached `python3 telemetry.py` drains the spool in one batched PostHog request,
+started once per session and again from the flush worker that is already detached.
+
+Pure stdlib, matching the rest of the plugin. Opt out with MEM0_TELEMETRY=false.
+
+Never sends prompts, memory text, queries, file paths, repository names, or API
+keys: only event names, durations, counts, coarse outcomes, and repo/session
+identifiers hashed with a random per-install salt.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import os
+import platform
+import subprocess
+import sys
+import time
+import urllib.error
+import urllib.request
+import uuid
+from pathlib import Path
+from typing import Any
+
+import memory_core
+
+# Seeded from the per-host module the build generates into core/. Two processes
+# in this pipeline never call init() โ mcp_server.py, and the detached
+# `python3 telemetry.py` sender that spawn_flush() starts โ so a module default
+# was what every one of their events got labelled with.
+try: # pragma: no cover - absent only in the un-built shared source tree
+ from _harness_id import HARNESS_ID as _DEFAULT_HARNESS
+ from _harness_id import PLATFORM_APPLICATION as _PLATFORM_APPLICATION
+ from _harness_id import PLATFORM_SOURCE as _PLATFORM_SOURCE
+ from _harness_id import SOURCE_TAG as _DEFAULT_SOURCE_TAG
+except ImportError:
+ _DEFAULT_HARNESS = "generic"
+ _DEFAULT_SOURCE_TAG = "MEM0_PLUGIN"
+ _PLATFORM_SOURCE = "MEM0_PLUGIN"
+ _PLATFORM_APPLICATION = ""
+
+_salt_cache: str = ""
+_harness: str = _DEFAULT_HARNESS
+_source_tag: str = _DEFAULT_SOURCE_TAG
+_PRIVATE_KEYS = {
+ "apikey",
+ "authorization",
+ "password",
+ "query",
+ "secret",
+ "prompt",
+ "token",
+ "text",
+ "memory",
+ "message",
+ "error",
+ "path",
+ "cwd",
+ "userid",
+ "agentid",
+ "runid",
+ "repoid",
+ "repositoryid",
+ "projectid",
+ "appid",
+ "filters",
+}
+
+
+def init(harness: str = "", source_tag: str = "") -> None:
+ """Override the generated identity. Optional โ core/_harness_id.py is the default.
+
+ The fallback shape matches memory_core.configure_harness's (``_PLUGIN``).
+ It used to be ``MEM0__PLUGIN`` here and ``_plugin`` there, which
+ meant one plugin could emit three different source values depending on which
+ process happened to send the batch.
+ """
+ global _harness, _source_tag
+ _harness = harness or _DEFAULT_HARNESS
+ _source_tag = source_tag or (
+ f"{_harness.upper().replace('-', '_')}_PLUGIN" if harness else _DEFAULT_SOURCE_TAG
+ )
+
+POSTHOG_API_KEY = "phc_hgJkUVJFYtmaJqrvf6CYN67TIQ8yhXAkWzUn9AMU4yX"
+POSTHOG_CAPTURE_URL = "https://us.i.posthog.com/i/v0/e/"
+POSTHOG_BATCH_URL = "https://us.i.posthog.com/batch/"
+EVENT_PREFIX = "code"
+SPOOL_LIMIT_BYTES = 256 * 1024
+BATCH_SIZE = 100
+SEND_TIMEOUT = 5
+CLAIM_STALE_SECONDS = 120
+CLAIM_EXPIRY_SECONDS = 7 * 24 * 60 * 60
+# A batch is only discarded once it has genuinely been retried this many times.
+MAX_CLAIM_ATTEMPTS = 3
+# Parked claims drained per run, after the live spool. Bounded so a long backlog
+# cannot turn one flush into an unbounded send loop.
+MAX_PARKED_PER_RUN = 3
+# Added to the wait before a released claim becomes reclaimable, per attempt
+# already spent. Releasing straight to "reclaimable now" let two senders burn the
+# whole budget within seconds of one another on a single momentary failure, and
+# discard a batch a retry a minute later would have delivered.
+RETRY_COOLDOWN_SECONDS = 60
+
+
+def is_enabled() -> bool:
+ """Whether telemetry is switched on for this process."""
+ return os.environ.get("MEM0_TELEMETRY", "true").strip().lower() not in {
+ "false",
+ "0",
+ "no",
+ "off",
+ }
+
+
+def _digest(value: str, length: int = 16) -> str:
+ """Unsalted digest. Only for values that are already secrets (API keys)."""
+ return hashlib.sha256(value.encode("utf-8")).hexdigest()[:length]
+
+
+def _salt_path() -> Path:
+ return memory_core.data_dir() / "telemetry-salt"
+
+
+def _install_salt() -> str:
+ """Random per-install salt, created once and memoized for the process.
+
+ Deliberately its own file, claimed with O_CREAT|O_EXCL, rather than a key in
+ the identity file. Three reasons, all of which produced wrong data when this
+ lived in the identity dict:
+
+ - Hooks are short-lived separate processes firing on every tool call, and
+ people run more than one agent window. A read-modify-write would let each
+ process mint its own salt, so one repository would hash several ways in the
+ window before a writer won.
+ - resolve_distinct_id holds a copy of the identity dict across a network call
+ to /v1/ping/, so whichever write landed second erased the other's key โ
+ losing either the salt (repo_hash changes mid-stream) or the email (a
+ second $identify, splitting the person).
+ - Touching the identity file from record() would create it, and is_first_run
+ keys off that file, so recording an event would silently suppress the
+ install event.
+
+ Published atomically, and there is deliberately no derived fallback. Creating
+ the file with O_CREAT|O_EXCL and then writing into it leaves a window where
+ the file exists and is empty, and a concurrent hook that reads it in that
+ window gets nothing. Falling back to a digest of the path would hand that
+ process a salt an attacker can compute, memoized for its whole run, which is
+ the privacy control this function exists to provide silently turning itself
+ off under load. The salt is written to a private temp file first and linked
+ into place, so the name either does not exist or already has the full value.
+
+ Returns "" when it genuinely cannot persist. Callers omit the hash entirely
+ rather than emit an unsalted one.
+ """
+ global _salt_cache
+ if _salt_cache:
+ return _salt_cache
+
+ path = _salt_path()
+ # Read before writing. Hooks are separate processes firing on every tool
+ # call, so all but the first find the salt already published; going straight
+ # to create-fsync-link-unlink meant every one of them paid an fsync to
+ # discover that, on a path whose whole promise is appending a line and
+ # returning.
+ try:
+ _salt_cache = path.read_text(encoding="utf-8").strip()
+ if _salt_cache:
+ return _salt_cache
+ except OSError:
+ pass
+
+ temporary = path.with_name(f"{path.name}.{os.getpid()}.tmp")
+ try:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ handle = os.open(temporary, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
+ with os.fdopen(handle, "w", encoding="utf-8") as stream:
+ stream.write(uuid.uuid4().hex)
+ stream.flush()
+ os.fsync(stream.fileno())
+ try:
+ # Atomic claim: fails if another process already published one.
+ # os.link rather than replace, which would clobber theirs.
+ os.link(temporary, path)
+ except FileExistsError:
+ pass
+ except OSError:
+ # No hardlinks here (some network mounts, some container volumes).
+ # Claim the name directly instead. That reopens the empty-file
+ # window, but the window is now benign: a reader that lands in it
+ # gets "" and omits the hash for that process rather than caching a
+ # guessable one. Losing the hashes on every run of an entire
+ # filesystem is the worse failure.
+ try:
+ fallback = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
+ with os.fdopen(fallback, "w", encoding="utf-8") as stream:
+ stream.write(temporary.read_text(encoding="utf-8"))
+ except OSError:
+ pass
+ except OSError:
+ pass
+ finally:
+ try:
+ temporary.unlink()
+ except OSError:
+ pass
+
+ try:
+ _salt_cache = path.read_text(encoding="utf-8").strip()
+ except OSError:
+ _salt_cache = ""
+ return _salt_cache
+
+
+def _scoped_digest(value: str, length: int = 16) -> str:
+ """Salted digest for values drawn from a guessable space.
+
+ repo.identity is a git remote URL, or ``local:`` when there is
+ no remote โ which normally contains the account username. Sixteen unsalted
+ hex characters over that input space is enumerable, so this is not a
+ privacy control without the salt. Salting per install keeps every
+ within-account join the analytics actually use and gives up only
+ cross-machine joins on the same repository, which nothing computes.
+
+ Returns "" when there is no salt, so record() omits the property. An
+ unsalted digest over this input space is close to plaintext, and emitting one
+ under a name that implies it is hashed is worse than sending nothing.
+ """
+ if not value:
+ return ""
+ salt = _install_salt()
+ if not salt:
+ return ""
+ return hashlib.sha256(f"{salt}:{value}".encode("utf-8")).hexdigest()[:length]
+
+
+def _safe_value(value: Any) -> Any:
+ if isinstance(value, str):
+ return memory_core.redact(value)
+ if isinstance(value, dict):
+ return {
+ key: _safe_value(item)
+ for key, item in value.items()
+ if "".join(character for character in str(key).lower() if character.isalnum())
+ not in _PRIVATE_KEYS
+ }
+ if isinstance(value, (list, tuple)):
+ return [_safe_value(item) for item in value]
+ if value is None or isinstance(value, (bool, int, float)):
+ return value
+ return memory_core.redact(value)
+
+
+def _spool_path() -> Path:
+ return memory_core.data_dir() / "telemetry.jsonl"
+
+
+def _identity_path() -> Path:
+ return memory_core.data_dir() / "telemetry-identity.json"
+
+
+def _read_identity() -> dict[str, str]:
+ try:
+ value = json.loads(_identity_path().read_text(encoding="utf-8"))
+ except (OSError, json.JSONDecodeError):
+ return {}
+ return value if isinstance(value, dict) else {}
+
+
+def _write_identity(identity: dict[str, str]) -> None:
+ path = _identity_path()
+ temporary = path.with_suffix(f".{os.getpid()}.tmp")
+ try:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ temporary.write_text(json.dumps(identity), encoding="utf-8")
+ temporary.replace(path)
+ except OSError:
+ try:
+ temporary.unlink()
+ except OSError:
+ pass
+
+
+def anonymous_id(identity: dict[str, str] | None = None) -> str:
+ """Per-machine anonymous identifier, created and persisted on first use."""
+ identity = _read_identity() if identity is None else identity
+ existing = identity.get("anonymous_id")
+ if existing:
+ return existing
+ created = f"code-anon-{uuid.uuid4().hex}"
+ identity["anonymous_id"] = created
+ _write_identity(identity)
+ return created
+
+
+def _rotate_anonymous_id(identity: dict[str, str]) -> str:
+ """Mint a fresh anonymous id because the account context is gone.
+
+ The previous id may already have been merged into a person profile by an
+ $identify, and that merge is permanent. Reusing it after a logout or a key
+ change attributes everything that follows to the account that just went
+ away, which is the same misattribution the key fingerprint exists to stop,
+ only arriving through the anonymous path instead.
+
+ `aliased` is cleared with it: the new id has never been merged, so it is
+ eligible to be aliased into whatever account comes next.
+ """
+ created = f"code-anon-{uuid.uuid4().hex}"
+ identity["anonymous_id"] = created
+ identity.pop("aliased", None)
+ _write_identity(identity)
+ return created
+
+
+def _install_state_path() -> Path:
+ return memory_core.data_dir() / "install-state.json"
+
+
+def is_first_run() -> bool:
+ """Whether install has never been recorded on this machine.
+
+ Deliberately NOT the identity file. That file is only written by a
+ successful flush, so an offline or firewalled user recorded code.install on
+ every single session, forever โ and every 0.2.x user recorded one on their
+ first 0.3.x session because 0.2.x never wrote it at all.
+ """
+ return not _install_state_path().exists()
+
+
+def data_dir_was_empty() -> bool:
+ """Whether the data directory is untouched. Call BEFORE anything writes to it.
+
+ hook_runner reaches claim_install() only after cache_plugin_api_key() has
+ written `api-key` and EvidenceStore() has created `evidence.sqlite3`, so
+ asking at claim time always saw content and every fresh install reported an
+ upgrade. The caller snapshots this at the top of the run instead.
+ """
+ return not _data_dir_has_content()
+
+
+def claim_install(was_empty: bool | None = None) -> str | None:
+ """Claim the one install/upgrade record for this machine, atomically.
+
+ Returns the event to record ("install" or "upgrade"), or None if another
+ session already claimed it. O_CREAT|O_EXCL so two sessions starting together
+ cannot both win.
+
+ `was_empty` must come from data_dir_was_empty() called before this process
+ wrote anything. Omitting it falls back to checking now, which is only
+ correct for a caller that has touched nothing.
+ """
+ if not is_enabled():
+ # Never consume the one-shot claim while the user is opted out, or they
+ # would silently lose their install event if they later opt in.
+ return None
+
+ path = _install_state_path()
+ upgrading = not (data_dir_was_empty() if was_empty is None else was_empty)
+ try:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ handle = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
+ except FileExistsError:
+ return None
+ except OSError:
+ return None
+ try:
+ with os.fdopen(handle, "w", encoding="utf-8") as stream:
+ json.dump(
+ {
+ "plugin_version": memory_core.PLUGIN_VERSION,
+ "installed_at": memory_core.utc_now(),
+ "upgraded": upgrading,
+ },
+ stream,
+ )
+ # Durable before this returns. The O_EXCL open is what makes the
+ # claim exclusive, so it cannot be replaced by a temp-and-rename
+ # without losing that, which leaves the content as the thing to make
+ # safe. A kill between the open and this fsync used to leave a marker
+ # that exists but parses to nothing: is_first_run reads it as claimed
+ # and claim_version_change cannot read a version out of it.
+ stream.flush()
+ os.fsync(stream.fileno())
+ except OSError:
+ pass
+ return "upgrade" if upgrading else "install"
+
+
+def _data_dir_has_content() -> bool:
+ """Whether anything predates this session in the plugin data directory."""
+ try:
+ for entry in memory_core.data_dir().iterdir():
+ if entry.name != "install-state.json":
+ return True
+ except OSError:
+ pass
+ return False
+
+
+def _repair_install_state(path: Path) -> None:
+ """Rewrite an unparseable marker so version tracking can resume."""
+ try:
+ temporary = path.with_suffix(f".{os.getpid()}.tmp")
+ temporary.write_text(
+ json.dumps({"plugin_version": memory_core.PLUGIN_VERSION, "repaired_at": memory_core.utc_now()}),
+ encoding="utf-8",
+ )
+ temporary.replace(path)
+ except OSError:
+ pass
+
+
+def claim_version_change() -> str | None:
+ """Return the previously recorded version if it differs, updating the marker.
+
+ Only meaningful once the marker exists โ the first transition into 0.3.x has
+ no recorded predecessor and reports "pre-0.3" instead. Claiming by rewriting
+ the marker means the next session sees no change and records nothing.
+ """
+ path = _install_state_path()
+ try:
+ state = json.loads(path.read_text(encoding="utf-8"))
+ except OSError:
+ return None
+ except json.JSONDecodeError:
+ # A crash between O_EXCL and the write leaves an empty marker. Left
+ # alone it disables every future upgrade event on this machine, because
+ # claim_install sees the file and this function cannot parse it.
+ state = None
+ if not isinstance(state, dict):
+ _repair_install_state(path)
+ return None
+ previous = str(state.get("plugin_version") or "")
+ if not previous or previous == memory_core.PLUGIN_VERSION:
+ return None
+ # Claim the transition with an exclusive sentinel before rewriting the
+ # marker. A plain read-modify-write let every concurrently starting session
+ # observe the old version and each record its own upgrade โ and the first
+ # session after a version bump is exactly when several agent windows restart
+ # together.
+ sentinel = path.with_name(f"upgraded-{memory_core.PLUGIN_VERSION}")
+ try:
+ os.close(os.open(sentinel, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600))
+ except FileExistsError:
+ return None
+ except OSError:
+ return None
+
+ state["plugin_version"] = memory_core.PLUGIN_VERSION
+ state["upgraded_at"] = memory_core.utc_now()
+ temporary = path.with_suffix(f".{os.getpid()}.tmp")
+ try:
+ temporary.write_text(json.dumps(state), encoding="utf-8")
+ temporary.replace(path)
+ except OSError:
+ # Release the claim. The marker still records the old version, so
+ # without this the sentinel makes claim_version_change return early on
+ # every later run and this version's upgrade is never recorded again.
+ for leftover in (sentinel, temporary):
+ try:
+ leftover.unlink()
+ except OSError:
+ pass
+ return None
+ return previous
+
+
+def record(
+ event: str,
+ *,
+ repo: Any = None,
+ session_id: str | None = None,
+ **properties: Any,
+) -> None:
+ """Append one event to the local spool. Never blocks and never raises."""
+ if not is_enabled():
+ return
+ try:
+ spool = _spool_path()
+ try:
+ if spool.stat().st_size > SPOOL_LIMIT_BYTES:
+ return
+ except OSError:
+ pass
+ properties = _safe_value(properties)
+ # Stamped in the RECORDING process, beside harness. `source` used to be
+ # read in the sending process from a module global, so whichever process
+ # drained the spool named every event in it. flush() spreads per-event
+ # properties last, so this now wins over any sender's default.
+ properties.update(
+ harness=_harness,
+ source=_source_tag,
+ plugin_version=memory_core.PLUGIN_VERSION,
+ os=sys.platform,
+ python_version=platform.python_version(),
+ )
+ # Assigned only when the digest is real. _scoped_digest returns "" when
+ # the salt could not be persisted, and an empty property is worse than an
+ # absent one: it survives the None filter below and reads as a value.
+ if repo is not None:
+ repo_hash = _scoped_digest(getattr(repo, "identity", ""))
+ if repo_hash:
+ properties["repo_hash"] = repo_hash
+ if session_id:
+ session_hash = _scoped_digest(session_id)
+ if session_hash:
+ properties["session_hash"] = session_hash
+ line = json.dumps(
+ {
+ "event": f"{EVENT_PREFIX}.{event}",
+ "uuid": str(uuid.uuid4()),
+ "timestamp": memory_core.utc_now(),
+ "properties": {
+ key: value for key, value in properties.items() if value is not None
+ },
+ },
+ separators=(",", ":"),
+ default=str,
+ )
+ spool.parent.mkdir(parents=True, exist_ok=True)
+ with spool.open("a", encoding="utf-8") as handle:
+ handle.write(line + "\n")
+ except Exception:
+ pass
+
+
+def error_kind(exc: BaseException | str) -> str:
+ """Coarse, content-free label for a failure, safe to send."""
+ text = exc if isinstance(exc, str) else f"{type(exc).__name__}: {exc}"
+ lowered = text.lower()
+ if "timed out" in lowered or "timeout" in lowered:
+ return "timeout"
+ if "401" in lowered or "403" in lowered or "unauthor" in lowered or "forbidden" in lowered:
+ return "auth"
+ if "429" in lowered or "rate limit" in lowered:
+ return "rate-limited"
+ if any(code in lowered for code in ("500", "502", "503", "504")):
+ return "server-error"
+ if "400" in lowered or "422" in lowered:
+ return "bad-request"
+ if isinstance(exc, str):
+ return "other"
+ if isinstance(exc, urllib.error.URLError):
+ return "network"
+ return type(exc).__name__
+
+
+def spawn_flush() -> bool:
+ """Start the detached sender that drains the spool."""
+ if not is_enabled():
+ return False
+ try:
+ if not _spool_path().exists() and not any(
+ memory_core.data_dir().glob("telemetry-*.sending")
+ ):
+ return False
+ subprocess.Popen(
+ [sys.executable, str(Path(__file__).resolve())],
+ stdin=subprocess.DEVNULL,
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL,
+ close_fds=True,
+ **memory_core.detached_process_kwargs(),
+ )
+ return True
+ except Exception:
+ return False
+
+
+def _claim_name(attempt: int = 0) -> str:
+ """Claim filename. The attempt count rides in the name so the 7-day expiry
+ only ever discards a batch that was actually retried and failed."""
+ return f"telemetry-{os.getpid()}-{uuid.uuid4().hex[:8]}-a{attempt}.sending"
+
+
+def _claim_attempt(claim: Path) -> int:
+ """Attempts recorded in a claim filename; 0 for the pre-attempt-count shape.
+
+ Anchored on field position, not on a leading "a": the legacy shape is
+ ``telemetry--.sending`` and a hex id such as ``a1234567`` would
+ otherwise parse as attempt 1234567 and be discarded unsent on the first
+ flush after an upgrade.
+ """
+ stem = claim.name[: -len(".sending")] if claim.name.endswith(".sending") else claim.name
+ parts = stem.split("-")
+ if len(parts) != 4:
+ return 0
+ tail = parts[3]
+ if tail.startswith("a") and tail[1:].isdigit():
+ return int(tail[1:])
+ return 0
+
+
+def _touch(path: Path) -> None:
+ """Refresh mtime so a claim's age measures time since it was claimed.
+
+ ``Path.replace`` is ``os.rename``, which preserves mtime โ so a claim created
+ after a quiet minute inherited the spool's last-write time and looked
+ abandoned the instant it was made. A second sender would then take it over
+ while the first was still posting, and both would deliver the batch.
+ """
+ try:
+ os.utime(path, None)
+ except OSError:
+ pass
+
+
+def _claim_spool() -> Path | None:
+ """Rename the spool aside so exactly one sender owns each batch."""
+ directory = memory_core.data_dir()
+ claim = directory / _claim_name()
+ spool = _spool_path()
+ try:
+ spool.replace(claim)
+ _touch(claim)
+ return claim
+ except OSError:
+ pass
+ return _claim_parked(directory)
+
+
+def _sweep_debris(directory: Path) -> None:
+ """Remove files nothing else will ever pick up again.
+
+ *.partial is a temp file orphaned by a crash between write and rename.
+ *.corrupt is a batch quarantined for undecodable content. No glob in this
+ module matches either, so without this they accumulate on disk for the life
+ of the install.
+
+ Quarantined batches are kept far longer than debris: they are the only
+ evidence left of events that could not be delivered, and someone diagnosing
+ a report of missing telemetry has to be able to find one.
+ """
+ now = time.time()
+ for debris in directory.glob("telemetry-*.partial"):
+ try:
+ if now - debris.stat().st_mtime > CLAIM_STALE_SECONDS:
+ debris.unlink()
+ except OSError:
+ continue
+ for quarantined in directory.glob("telemetry-*.corrupt"):
+ try:
+ if now - quarantined.stat().st_mtime > CLAIM_EXPIRY_SECONDS:
+ quarantined.unlink()
+ except OSError:
+ continue
+ # The same reasoning covers *.tmp. _write_identity and _install_salt both
+ # create one and unlink it in a finally, which a SIGKILL skips, and no glob
+ # in this module matches the leftovers either.
+ for temporary in directory.glob("telemetry-*.tmp"):
+ try:
+ if now - temporary.stat().st_mtime > CLAIM_STALE_SECONDS:
+ temporary.unlink()
+ except OSError:
+ continue
+
+
+def _claim_parked(directory: Path) -> Path | None:
+ """Take the oldest abandoned claim, if any lease has actually expired.
+
+ Kept separate from the live spool so flush() can drain both in one run.
+ Previously parked batches were only reachable when no spool existed at all,
+ and because sessions keep recording there usually was one โ so a batch
+ parked by a failed send waited until the 7-day expiry deleted it unsent,
+ even though its own presence is what started the sender.
+ """
+ now = time.time()
+ for orphan in sorted(directory.glob("telemetry-*.sending"), key=_safe_mtime):
+ try:
+ age = now - orphan.stat().st_mtime
+ except OSError:
+ continue
+ if age < CLAIM_STALE_SECONDS:
+ # Someone else holds a live lease on it. This check has to come
+ # first. Claiming a file bumps its attempt count and refreshes its
+ # mtime, so a sender that has just taken the final attempt looks
+ # exhausted to everyone else while it is actively draining. Judging
+ # exhaustion before liveness let a second sender unlink a batch out
+ # from under its owner, losing every event in it.
+ continue
+ # Attempts, not age. Every re-claim touches the mtime and every release
+ # backdates it by a fixed amount, so age is pinned near the stale
+ # threshold and never reaches the expiry. Age stays only as a backstop
+ # for files that never carried an attempt marker.
+ if _claim_attempt(orphan) >= MAX_CLAIM_ATTEMPTS or age > CLAIM_EXPIRY_SECONDS:
+ try:
+ orphan.unlink()
+ except OSError:
+ pass
+ continue
+ claim = orphan.parent / _claim_name(_claim_attempt(orphan) + 1)
+ try:
+ orphan.replace(claim)
+ _touch(claim)
+ return claim
+ except OSError:
+ continue
+ return None
+
+
+def _safe_mtime(path: Path) -> float:
+ try:
+ return path.stat().st_mtime
+ except OSError:
+ return 0.0
+
+
+def _rewrite_claim(claim: Path, remaining: list[dict[str, Any]]) -> bool:
+ """Persist the unsent remainder, atomically, and refresh the lease.
+
+ Called after every successful batch. Two jobs: a retry resumes where the
+ send stopped instead of re-posting from the top, and the rewrite doubles as
+ the lease heartbeat, so a slow sender does not have its claim stolen
+ mid-flight. Interval is one batch, well inside CLAIM_STALE_SECONDS.
+ """
+ if not remaining:
+ try:
+ claim.unlink()
+ except OSError:
+ pass
+ return True
+ temporary = claim.with_suffix(f".{os.getpid()}.partial")
+ try:
+ payload = "".join(json.dumps(event, separators=(",", ":"), default=str) + "\n" for event in remaining)
+ # fsync before the rename: without it the rename can land while the
+ # bytes have not, and the claim comes back empty or truncated after a
+ # crash. _drain then reads zero events and unlinks it.
+ with open(temporary, "w", encoding="utf-8") as handle:
+ handle.write(payload)
+ handle.flush()
+ os.fsync(handle.fileno())
+ temporary.replace(claim)
+ _touch(claim)
+ return True
+ except OSError:
+ try:
+ temporary.unlink()
+ except OSError:
+ pass
+ return False
+
+
+def _release_claim(claim: Path, remaining: list[dict[str, Any]]) -> None:
+ """Persist the remainder and drop the lease, because this sender has given up.
+
+ Distinct from the per-batch heartbeat: heartbeating on the way out would
+ make an abandoned batch look actively owned for a further
+ CLAIM_STALE_SECONDS, delaying the retry for no reason. Ageing it past the
+ threshold lets the next flush pick it up immediately, while the attempt
+ count in the filename still bounds how many times that can happen.
+ """
+ if not _rewrite_claim(claim, remaining):
+ return
+ try:
+ # Backdate past the stale threshold so the next flush can pick it up,
+ # minus a cooldown that grows with the attempts already spent. Clamped so
+ # the mtime never lands in the future, which would read as a live lease.
+ cooldown = min(_claim_attempt(claim) * RETRY_COOLDOWN_SECONDS, CLAIM_STALE_SECONDS)
+ released = time.time() - CLAIM_STALE_SECONDS - 1 + cooldown
+ os.utime(claim, (released, released))
+ except OSError:
+ pass
+
+
+def _resolve_email(key: str) -> str:
+ """Trade the API key for the account email so events join other Mem0 surfaces."""
+ url = os.environ.get("MEM0_API_URL", memory_core.DEFAULT_API_URL).rstrip("/") + "/v1/ping/"
+ request = urllib.request.Request(
+ url, headers={"Authorization": f"Token {key}", "Content-Type": "application/json"}
+ )
+ try:
+ with urllib.request.urlopen(request, timeout=SEND_TIMEOUT) as response:
+ payload = json.loads(response.read().decode("utf-8"))
+ except Exception:
+ return ""
+ email = payload.get("user_email") if isinstance(payload, dict) else ""
+ return email if isinstance(email, str) else ""
+
+
+def _post(payload: dict[str, Any], url: str) -> bool:
+ request = urllib.request.Request(
+ url,
+ data=json.dumps(payload, default=str).encode("utf-8"),
+ headers={"Content-Type": "application/json"},
+ )
+ try:
+ with urllib.request.urlopen(request, timeout=SEND_TIMEOUT):
+ return True
+ except Exception:
+ return False
+
+
+def resolve_distinct_id() -> tuple[str, str]:
+ """Return the PostHog distinct id and the anonymous id it replaced, if any.
+
+ The second value becomes a PostHog $identify alias. It is ONLY ever an
+ anonymous id: aliasing one account email to another merges two real person
+ profiles and cannot be undone, so a key that now belongs to a different
+ account re-resolves with no alias.
+ """
+ identity = _read_identity()
+ key = memory_core.api_key()
+ fingerprint = _digest(key) if key else ""
+ email = identity.get("email", "")
+
+ if email and fingerprint:
+ recorded = identity.get("key_fingerprint", "")
+ if recorded == fingerprint:
+ return email, ""
+ if not recorded:
+ # Rows written before fingerprints existed. Verify rather than
+ # adopt: a key changed before the upgrade would otherwise bind the
+ # new key to the previous account's email, permanently, and the
+ # fingerprint would then agree with itself forever after.
+ verified = _resolve_email(key)
+ if not verified:
+ # Offline, firewalled, or the API is down. Keep the previous
+ # behaviour and retry on the next flush rather than dropping a
+ # real account attribution. Safe because the same network that
+ # failed /v1/ping/ is about to fail the PostHog POST, so nothing
+ # is delivered under the unverified identity in the meantime.
+ return email, ""
+ identity["email"] = verified
+ identity["key_fingerprint"] = fingerprint
+ _write_identity(identity)
+ return verified, ""
+
+ if not key:
+ # No key to verify the account with; do not keep attributing to it.
+ if email:
+ identity.pop("email", None)
+ identity.pop("key_fingerprint", None)
+ return _rotate_anonymous_id(identity), ""
+ return anonymous_id(identity), ""
+
+ resolved = _resolve_email(key)
+ if not resolved:
+ # The key changed and will not resolve (revoked, offline, API down).
+ # Reaching here with an email means the recorded fingerprint disagreed,
+ # so the key really did change. Drop the account and rotate: the stored
+ # anonymous id may already be merged into that account's person, and
+ # reusing it would keep the events on the profile we are trying to
+ # leave.
+ if email:
+ identity.pop("email", None)
+ identity.pop("key_fingerprint", None)
+ return _rotate_anonymous_id(identity), ""
+ return anonymous_id(identity), ""
+
+ # Alias only when going anonymous -> email for the first time. Once an anon
+ # id has been merged into an account it must never be offered again: an
+ # alias naming an already-identified id is what could link two real people.
+ previous = "" if (email or identity.get("aliased")) else identity.get("anonymous_id", "")
+ if previous:
+ identity["aliased"] = True
+ identity["email"] = resolved
+ identity["key_fingerprint"] = fingerprint
+ _write_identity(identity)
+ return resolved, previous
+
+
+def flush() -> int:
+ """Drain the live spool, then any parked claims, and return events sent."""
+ if not is_enabled():
+ return 0
+ sent, delivered = _drain(_claim_spool())
+ if not delivered:
+ # The network is failing. Retrying other batches now would only burn
+ # their attempt budget against the same broken connection.
+ return sent
+
+ # Parked batches used to starve behind the live spool indefinitely. Bounded
+ # per run so a long backlog cannot turn one flush into an unbounded loop.
+ directory = memory_core.data_dir()
+ _sweep_debris(directory)
+ for _ in range(MAX_PARKED_PER_RUN):
+ parked = _claim_parked(directory)
+ if parked is None:
+ break
+ count, delivered = _drain(parked)
+ sent += count
+ if not delivered:
+ break
+ return sent
+
+
+def _drain(claim: Path | None) -> tuple[int, bool]:
+ """Post one claimed batch file, recording progress after every batch.
+
+ Returns (events sent, whether everything was delivered).
+ """
+ if claim is None:
+ return 0, True
+ try:
+ lines = claim.read_text(encoding="utf-8").splitlines()
+ except ValueError:
+ # UnicodeDecodeError from a torn write: the content is unrecoverable, so
+ # quarantine rather than retry. flush() runs from a bare `finally:` in
+ # flush_worker, so raising here also skips the handoff cleanup, and an
+ # undecodable file would otherwise be re-read on every flush forever.
+ # Reported as delivered because there is nothing left to deliver and the
+ # rest of the run should continue.
+ try:
+ claim.replace(claim.with_suffix(".corrupt"))
+ except OSError:
+ try:
+ claim.unlink()
+ except OSError:
+ pass
+ return 0, True
+ except OSError:
+ # Could not read it, which is not the same as having nothing to send.
+ # The file is left exactly where it is: a vanished or briefly unreadable
+ # claim is retryable, and quarantining it here would discard events over
+ # a transient filesystem error. Reported as undelivered so the run stops
+ # instead of counting a batch nothing was posted from as delivered.
+ return 0, False
+ events = []
+ for line in lines:
+ try:
+ value = json.loads(line)
+ except json.JSONDecodeError:
+ continue
+ if isinstance(value, dict) and value.get("event"):
+ events.append(value)
+ if not events:
+ # Only delete when the file really is empty. A non-empty file that
+ # parses to nothing is a torn write, and its contents are the unsent
+ # remainder โ deleting it is the data loss this PR exists to prevent.
+ try:
+ empty = claim.stat().st_size == 0
+ except OSError:
+ empty = True
+ try:
+ claim.replace(claim.with_suffix(".corrupt")) if not empty else claim.unlink()
+ except OSError:
+ pass
+ return 0, True
+
+ distinct_id, aliased_anonymous_id = resolve_distinct_id()
+ if aliased_anonymous_id:
+ _post(
+ {
+ "api_key": POSTHOG_API_KEY,
+ "event": "$identify",
+ "distinct_id": distinct_id,
+ "properties": {
+ "$anon_distinct_id": aliased_anonymous_id,
+ "$lib": "posthog-python",
+ },
+ },
+ POSTHOG_CAPTURE_URL,
+ )
+
+ sent = 0
+ for start in range(0, len(events), BATCH_SIZE):
+ chunk = events[start : start + BATCH_SIZE]
+ batch = [
+ {
+ "event": event["event"],
+ "distinct_id": distinct_id,
+ # Carried through from record() so a resend can be collapsed.
+ "uuid": event.get("uuid"),
+ "timestamp": event.get("timestamp"),
+ "properties": {
+ # Fallback only: events recorded by a build before source
+ # moved into record() have none of their own.
+ "source": _source_tag,
+ "language": "python",
+ "$process_person_profile": False,
+ "$lib": "posthog-python",
+ **(event.get("properties") or {}),
+ },
+ }
+ for event in chunk
+ ]
+ if not _post({"api_key": POSTHOG_API_KEY, "batch": batch}, POSTHOG_BATCH_URL):
+ # Keep only what has not been delivered, and release the lease.
+ # Previously the whole file was kept and the retry re-posted every
+ # batch, including the ones that had already arrived.
+ _release_claim(claim, events[start:])
+ return sent, False
+ sent += len(chunk)
+ # Record progress and refresh the lease after each successful batch, so
+ # a crash repeats at most one batch instead of the entire file. If the
+ # rewrite fails the claim still holds delivered events, so stop rather
+ # than carry on as though progress were recorded โ continuing is how the
+ # duplicate delivery this PR fixes would come back.
+ if not _rewrite_claim(claim, events[start + len(chunk) :]):
+ _release_claim(claim, events[start + len(chunk) :])
+ return sent, False
+ return sent, True
+
+
+def main() -> int:
+ flush()
+ return 0
+
+
+if __name__ == "__main__":
+ try:
+ raise SystemExit(main())
+ except Exception:
+ raise SystemExit(0)
diff --git a/integrations/codex-plugin/hooks/adapter.py b/integrations/codex-plugin/hooks/adapter.py
new file mode 100644
index 000000000..2032c6496
--- /dev/null
+++ b/integrations/codex-plugin/hooks/adapter.py
@@ -0,0 +1,64 @@
+#!/usr/bin/env python3
+"""Run Codex hooks through the shared Mem0 runtime."""
+
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+
+HERE = Path(__file__).resolve()
+BUNDLED_CORE = HERE.parent.parent / "core"
+CORE = BUNDLED_CORE if BUNDLED_CORE.is_dir() else HERE.parents[2] / "core" / "python"
+sys.path.insert(0, str(CORE))
+
+import hook_runner # noqa: E402
+import telemetry # noqa: E402
+from memory_core import ( # noqa: E402
+ configure_harness,
+ record_subagent_start,
+ record_subagent_stop,
+ record_tool,
+)
+
+configure_harness("codex", data_dir_name="codex-plugin", source_tag="codex_plugin")
+telemetry.init(harness="codex", source_tag="CODEX_PLUGIN")
+
+
+def _subagent_start(store, hook_input):
+ context = record_subagent_start(store, hook_input)
+ if context:
+ return {
+ "hookSpecificOutput": {
+ "hookEventName": "SubagentStart",
+ "additionalContext": context,
+ }
+ }
+
+
+def _subagent_stop(store, hook_input):
+ record_subagent_stop(store, hook_input)
+
+
+def _post_tool(store, payload):
+ response = payload.get("tool_response")
+ failed = None
+ if isinstance(response, dict):
+ exit_code = response.get("exit_code")
+ if isinstance(exit_code, int) and not isinstance(exit_code, bool):
+ failed = exit_code != 0
+ elif isinstance(response.get("isError"), bool):
+ failed = response["isError"]
+ elif isinstance(response.get("success"), bool):
+ failed = not response["success"]
+ if failed:
+ payload = {**payload, "error": response}
+ record_tool(store, payload, failed=failed)
+
+
+if __name__ == "__main__":
+ if len(sys.argv) > 1 and sys.argv[1] == "post-tool":
+ sys.argv[1] = "codex-post-tool"
+ hook_runner.entry_point(
+ extra_actions={"subagent-start": _subagent_start, "subagent-stop": _subagent_stop, "codex-post-tool": _post_tool},
+ automatic_flush_reasons={"session-end", "pre-compact"},
+ )
diff --git a/integrations/codex-plugin/hooks/hooks.json b/integrations/codex-plugin/hooks/hooks.json
new file mode 100644
index 000000000..1941c3e8f
--- /dev/null
+++ b/integrations/codex-plugin/hooks/hooks.json
@@ -0,0 +1,63 @@
+{
+ "description": "Create memories from coding sessions and recall them in later work.",
+ "hooks": {
+ "SessionStart": [
+ {
+ "matcher": "startup|resume|clear|compact",
+ "hooks": [
+ { "type": "command", "command": "python3 \"${PLUGIN_ROOT}/hooks/adapter.py\" session-start --plugin-data-dir \"${PLUGIN_DATA}\"", "timeout": 3 }
+ ]
+ }
+ ],
+ "UserPromptSubmit": [
+ {
+ "hooks": [
+ { "type": "command", "command": "python3 \"${PLUGIN_ROOT}/hooks/adapter.py\" user-prompt --plugin-data-dir \"${PLUGIN_DATA}\"", "timeout": 3 }
+ ]
+ }
+ ],
+ "PostToolUse": [
+ {
+ "matcher": ".*",
+ "hooks": [
+ { "type": "command", "command": "python3 \"${PLUGIN_ROOT}/hooks/adapter.py\" post-tool --plugin-data-dir \"${PLUGIN_DATA}\"", "timeout": 3 }
+ ]
+ }
+ ],
+ "SubagentStart": [
+ {
+ "hooks": [
+ { "type": "command", "command": "python3 \"${PLUGIN_ROOT}/hooks/adapter.py\" subagent-start --plugin-data-dir \"${PLUGIN_DATA}\"", "timeout": 3 }
+ ]
+ }
+ ],
+ "SubagentStop": [
+ {
+ "hooks": [
+ { "type": "command", "command": "python3 \"${PLUGIN_ROOT}/hooks/adapter.py\" subagent-stop --plugin-data-dir \"${PLUGIN_DATA}\"", "timeout": 3 }
+ ]
+ }
+ ],
+ "Stop": [
+ {
+ "hooks": [
+ { "type": "command", "command": "python3 \"${PLUGIN_ROOT}/hooks/adapter.py\" stop --plugin-data-dir \"${PLUGIN_DATA}\"", "timeout": 3 }
+ ]
+ }
+ ],
+ "PreCompact": [
+ {
+ "hooks": [
+ { "type": "command", "command": "python3 \"${PLUGIN_ROOT}/hooks/adapter.py\" flush --reason pre-compact --plugin-data-dir \"${PLUGIN_DATA}\"", "timeout": 3 }
+ ]
+ }
+ ],
+ "SessionEnd": [
+ {
+ "hooks": [
+ { "type": "command", "command": "python3 \"${PLUGIN_ROOT}/hooks/adapter.py\" flush --reason session-end --plugin-data-dir \"${PLUGIN_DATA}\"", "timeout": 3 }
+ ]
+ }
+ ]
+ }
+}
diff --git a/integrations/codex-plugin/plugin-build.json b/integrations/codex-plugin/plugin-build.json
new file mode 100644
index 000000000..a354c31f5
--- /dev/null
+++ b/integrations/codex-plugin/plugin-build.json
@@ -0,0 +1,15 @@
+{
+ "id": "mem0",
+ "version": "0.3.3",
+ "homepage": "https://docs.mem0.ai/integrations/codex",
+ "native": {
+ "pluginRoot": "${PLUGIN_ROOT}",
+ "pluginData": "${PLUGIN_DATA}",
+ "files": {
+ ".codex-plugin/plugin.json": ".codex-plugin/plugin.json",
+ "hooks/hooks.json": "hooks/hooks.json",
+ "hooks/adapter.py": "hooks/adapter.py",
+ ".mcp.json": ".mcp.json"
+ }
+ }
+}
diff --git a/integrations/codex-plugin/skills/forget/SKILL.md b/integrations/codex-plugin/skills/forget/SKILL.md
new file mode 100644
index 000000000..09b285cac
--- /dev/null
+++ b/integrations/codex-plugin/skills/forget/SKILL.md
@@ -0,0 +1,26 @@
+---
+name: forget
+description: Delete the Mem0 memories stored for this repository and this user. Use when the user asks to forget, clear, wipe, or delete memories.
+disable-model-invocation: true
+---
+
+# Forget this repository's memories
+
+This permanently deletes remote memories. Before running anything, tell the
+user exactly what will be deleted: their own memories for this repository
+only. The repository's project memory is shared by everyone who works in it,
+so it stays unless the user explicitly asks to delete that too.
+
+After the user confirms, run:
+
+```bash
+python3 "${PLUGIN_ROOT}/core/memory_cli.py" --harness "codex" --plugin-data-dir "${PLUGIN_DATA}" forget --remote --yes
+```
+
+If the user also asked to delete the repository's shared project memory, add
+`--include-project-memory` and say that this removes it for every teammate.
+
+Report what the command output says was deleted. If the user only wants local
+data cleared (evidence log, pending queue), run the same command without
+`--remote`. Never pass `--yes` before the user has confirmed in this
+conversation.
diff --git a/integrations/codex-plugin/skills/pause/SKILL.md b/integrations/codex-plugin/skills/pause/SKILL.md
new file mode 100644
index 000000000..c8f8ddd5f
--- /dev/null
+++ b/integrations/codex-plugin/skills/pause/SKILL.md
@@ -0,0 +1,20 @@
+---
+name: pause
+description: Pause Mem0 memory capture on this machine. Use when the user wants to stop memories being recorded, for example for private work or experiments.
+disable-model-invocation: true
+---
+
+# Pause memory capture
+
+To pause (hooks stop capturing and sending session content; a minimal
+telemetry ping still fires at session start, under your Mem0 account email,
+unless `MEM0_TELEMETRY=false`):
+
+```bash
+python3 "${PLUGIN_ROOT}/core/memory_cli.py" --harness "codex" --plugin-data-dir "${PLUGIN_DATA}" pause
+```
+
+Confirm the new state back to the user, and remind them that already-created
+memories still exist and remain searchable. Pending unsent packets are held
+while paused, not expired, and are delivered after resuming. To turn capture
+back on, use `/mem0:resume`.
diff --git a/integrations/codex-plugin/skills/remember/SKILL.md b/integrations/codex-plugin/skills/remember/SKILL.md
new file mode 100644
index 000000000..7be5fc9be
--- /dev/null
+++ b/integrations/codex-plugin/skills/remember/SKILL.md
@@ -0,0 +1,21 @@
+---
+name: remember
+description: Acknowledge a "remember this" request and make sure it is captured well. Use when the user explicitly asks to remember, note, or save something for future sessions.
+disable-model-invocation: true
+---
+
+# Remember something for future sessions
+
+Mem0 creates memories from the session automatically โ there is no separate
+write command. When the user asks to remember something:
+
+1. Restate the fact clearly and completely in your reply, in one or two
+ sentences, including any names, values, or paths it depends on. Your visible
+ reply is what memory extraction reads, so a precise restatement is what gets
+ remembered.
+2. Tell the user it will be saved with this session's memories when the session
+ ends or compacts, and that it will surface in future sessions in this
+ repository (they can check later with /mem0:search).
+
+Do not invent a storage confirmation or a memory ID โ creation happens in the
+background after the session.
diff --git a/integrations/codex-plugin/skills/resume/SKILL.md b/integrations/codex-plugin/skills/resume/SKILL.md
new file mode 100644
index 000000000..59a097585
--- /dev/null
+++ b/integrations/codex-plugin/skills/resume/SKILL.md
@@ -0,0 +1,19 @@
+---
+name: resume
+description: Resume Mem0 memory capture after it was paused with /mem0:pause.
+disable-model-invocation: true
+---
+
+# Resume memory capture
+
+Resume memory capture for this machine.
+
+Run:
+
+```bash
+python3 "${PLUGIN_ROOT}/core/memory_cli.py" --harness "codex" --plugin-data-dir "${PLUGIN_DATA}" resume
+```
+
+Confirm to the user that capture is active again. New sessions record evidence and
+create memories as normal; nothing that happened while paused is retroactively
+captured.
diff --git a/integrations/codex-plugin/skills/search/SKILL.md b/integrations/codex-plugin/skills/search/SKILL.md
new file mode 100644
index 000000000..90f435008
--- /dev/null
+++ b/integrations/codex-plugin/skills/search/SKILL.md
@@ -0,0 +1,26 @@
+---
+name: search
+description: Search memories from earlier Codex sessions in this repository. Use it when earlier work may already explain the code, error, decision, or command you need, so you can avoid repeating file reads, searches, or experiments.
+argument-hint: "[question] [--top-k number] [--category category-name] [--scope repo|dir|mine] [--run-id session-id]"
+disable-model-invocation: true
+---
+
+# Search memories
+
+Call `search_memories` with the user's question. Treat `--top-k`, `--category`,
+`--scope`, and `--run-id` as tool arguments instead of including them in the
+query.
+
+Omit `top_k` to use Mem0's configured default. Omit `category` to search every
+category. Omit `scope` to use the configured default, normally `repo`: this
+repository's shared memory, which everyone who works in it contributes to,
+plus your own preferences.
+
+Pass `scope` when the question needs something else: `dir` to narrow the
+shared memory to the directory you are working in (a package inside a
+monorepo), `mine` for your own preferences alone.
+
+Pass `run_id` with any scope to retrieve memories saved in a specific coding-agent
+session. Omit `run_id` to search across sessions. It filters the memories returned;
+it does not identify the session making the search request. Use a known session ID,
+never invent one. Return the tool's result directly.
diff --git a/integrations/codex-plugin/skills/status/SKILL.md b/integrations/codex-plugin/skills/status/SKILL.md
new file mode 100644
index 000000000..4f67cc829
--- /dev/null
+++ b/integrations/codex-plugin/skills/status/SKILL.md
@@ -0,0 +1,23 @@
+---
+name: status
+description: Show whether Mem0 memory is working in this repository, covering configuration, capture state, pending flushes, and whether the Mem0 API key is valid. Use when the user asks whether memory is on, why a memory is missing, or anything looks broken.
+disable-model-invocation: false
+---
+
+# Memory status
+
+Run both commands and report the combined result in plain language:
+
+```bash
+python3 "${PLUGIN_ROOT}/core/memory_cli.py" --harness "codex" --plugin-data-dir "${PLUGIN_DATA}" status --json
+python3 "${PLUGIN_ROOT}/core/memory_cli.py" --harness "codex" --plugin-data-dir "${PLUGIN_DATA}" doctor
+```
+
+Summarize, using only fields the JSON actually reports: whether capture is
+active or paused, the user ID and repository scope (`repo_id`), whether an
+API key is configured, the event/flush/retrieval counts (`flushes` is the
+number of completed flushes, not a pending count), and the doctor check
+results. If doctor reports an authentication failure (401 / invalid key), say
+clearly that the Mem0 API key is invalid or expired and that memories are NOT
+being created. Never report an auth failure as "no memories found". Suggest
+reinstalling with `--config api_key=...` in that case.
diff --git a/integrations/codex-plugin/tests/test_codex.py b/integrations/codex-plugin/tests/test_codex.py
new file mode 100644
index 000000000..dc5cce8fc
--- /dev/null
+++ b/integrations/codex-plugin/tests/test_codex.py
@@ -0,0 +1,107 @@
+from __future__ import annotations
+
+import json
+import sqlite3
+import subprocess
+import sys
+from pathlib import Path
+
+HOST = Path(__file__).resolve().parents[1]
+CORE_ROOT = HOST.parent / "agent-plugin-core"
+sys.path.insert(0, str(CORE_ROOT))
+
+from build.build import build # noqa: E402
+
+
+def test_codex_hooks_use_native_events_and_plugin_paths() -> None:
+ hooks = json.loads((HOST / "hooks" / "hooks.json").read_text(encoding="utf-8"))["hooks"]
+
+ assert set(hooks) == {
+ "SessionStart",
+ "UserPromptSubmit",
+ "PostToolUse",
+ "SubagentStart",
+ "SubagentStop",
+ "Stop",
+ "PreCompact",
+ "SessionEnd",
+ }
+ commands = [hook["command"] for groups in hooks.values() for group in groups for hook in group["hooks"]]
+ assert "matcher" not in hooks["SubagentStart"][0]
+ assert "matcher" not in hooks["SubagentStop"][0]
+ assert all("${PLUGIN_ROOT}/hooks/adapter.py" in command for command in commands)
+ assert any("flush --reason pre-compact" in command for command in commands)
+ assert any("flush --reason session-end" in command for command in commands)
+ assert all(hook.get("timeout", 0) <= 3 for groups in hooks.values() for group in groups for hook in group["hooks"])
+
+
+def test_codex_subagent_records_lifecycle(tmp_path: Path) -> None:
+ adapter = HOST / "hooks" / "adapter.py"
+ payload = {
+ "session_id": "session-1",
+ "cwd": str(tmp_path),
+ "agent_id": "agent-1",
+ "agent_type": "default",
+ }
+
+ for action, extra in (
+ ("subagent-start", {}),
+ ("subagent-stop", {"last_assistant_message": "SUBAGENT_OK"}),
+ ):
+ result = subprocess.run(
+ [sys.executable, str(adapter), action, "--plugin-data-dir", str(tmp_path / "data")],
+ input=json.dumps({**payload, **extra}),
+ text=True,
+ capture_output=True,
+ check=False,
+ )
+ assert result.returncode == 0, result.stderr
+
+ with sqlite3.connect(tmp_path / "data" / "evidence.sqlite3") as connection:
+ row = connection.execute(
+ "SELECT agent_id, stopped_at, final_message FROM sidekick_runs"
+ ).fetchone()
+
+ assert row is not None
+ assert row[0] == "agent-1"
+ assert row[1]
+ assert row[2] == "SUBAGENT_OK"
+
+
+def test_codex_mcp_uses_host_relative_paths() -> None:
+ manifest = json.loads((HOST / ".codex-plugin" / "plugin.json").read_text(encoding="utf-8"))
+ assert manifest["mcpServers"] == "./.mcp.json"
+
+ server = json.loads((HOST / ".mcp.json").read_text(encoding="utf-8"))["mcpServers"]["mem0"]
+ assert server["command"] == "python3"
+ assert server["args"] == ["./core/mcp_server.py"]
+ assert server["cwd"] == "."
+ assert set(server["env_vars"]) >= {"MEM0_API_KEY", "MEM0_CODE_USER_ID"}
+ assert "PLUGIN_ROOT" not in json.dumps(server)
+
+
+def test_native_codex_bundle_is_self_contained(tmp_path: Path) -> None:
+ root = build("codex", "native", tmp_path / "codex")
+
+ manifest = json.loads((root / ".codex-plugin" / "plugin.json").read_text(encoding="utf-8"))
+ assert manifest["hooks"] == "./hooks/hooks.json"
+ assert manifest["skills"] == "./skills/"
+ assert (root / "hooks" / "adapter.py").is_file()
+ assert (root / "core" / "mcp_server.py").is_file()
+ assert (root / ".mcp.json").is_file()
+ assert not (root / "agents").exists()
+ assert not any(path.is_symlink() for path in root.rglob("*"))
+
+
+def test_codex_post_tool_keeps_failures_and_unknown_outcomes(tmp_path):
+ for response, failed in [("raw command output", None), ({"exit_code": 1, "stderr": "failed"}, True), ({"isError": False}, False)]:
+ result = subprocess.run(
+ [sys.executable, str(HOST / "hooks" / "adapter.py"), "post-tool", "--plugin-data-dir", str(tmp_path / "data")],
+ input=json.dumps({"session_id": "s1", "cwd": str(tmp_path), "tool_name": "Bash",
+ "tool_input": {"command": "test command"}, "tool_response": response}),
+ text=True, capture_output=True, check=False,
+ )
+ assert result.returncode == 0, result.stderr
+ with sqlite3.connect(tmp_path / "data" / "evidence.sqlite3") as connection:
+ row = connection.execute("SELECT payload_json FROM events ORDER BY id DESC LIMIT 1").fetchone()
+ assert json.loads(row[0])["failed"] is failed
diff --git a/integrations/cursor-plugin/.cursor-plugin/plugin.json b/integrations/cursor-plugin/.cursor-plugin/plugin.json
new file mode 100644
index 000000000..7c2304f29
--- /dev/null
+++ b/integrations/cursor-plugin/.cursor-plugin/plugin.json
@@ -0,0 +1,24 @@
+{
+ "name": "mem0",
+ "version": "0.3.3",
+ "description": "Cross-session memory and token savings for coding agents.",
+ "author": { "name": "Mem0", "email": "support@mem0.ai" },
+ "homepage": "https://docs.mem0.ai/integrations/cursor",
+ "repository": "https://github.com/mem0ai/mem0",
+ "license": "Apache-2.0",
+ "keywords": ["memory", "coding-agents", "continual-learning", "token-efficiency"],
+ "skills": "./skills/",
+ "hooks": "./hooks/hooks.json",
+ "mcpServers": "./mcp.json",
+ "variables": {
+ "type": "object",
+ "properties": {
+ "api_key": { "type": "string", "title": "Mem0 API Key", "description": "Mem0 Platform API key used to create and search memories." },
+ "user_id": { "type": "string", "title": "Memory user ID", "description": "Optional stable ID shared across machines.", "default": "" },
+ "top_k": { "type": "number", "title": "Manual search results", "default": 3, "minimum": 1, "maximum": 20 },
+ "max_context_chars": { "type": "number", "title": "Maximum retrieved context", "default": 4000, "minimum": 1000, "maximum": 10000 },
+ "search_scope": { "type": "string", "title": "Default search scope", "default": "repo", "enum": ["repo", "dir", "mine"] }
+ },
+ "required": ["api_key"]
+ }
+}
diff --git a/integrations/cursor-plugin/core/_harness_id.py b/integrations/cursor-plugin/core/_harness_id.py
new file mode 100644
index 000000000..0e20bf1ff
--- /dev/null
+++ b/integrations/cursor-plugin/core/_harness_id.py
@@ -0,0 +1,11 @@
+"""Generated by integrations/agent-plugin-core/build/build.py. Do not edit."""
+
+HARNESS_ID = "cursor"
+SOURCE_TAG = "CURSOR_PLUGIN"
+
+# Platform-side vocabulary (mem0_event.source + X-Application). The whole
+# plugin family is one source; which editor it runs in is the application.
+# An empty application means the host is unknown, and memory_core omits
+# the header entirely rather than sending a placeholder.
+PLATFORM_SOURCE = "MEM0_PLUGIN"
+PLATFORM_APPLICATION = "cursor"
diff --git a/integrations/cursor-plugin/core/flush_worker.py b/integrations/cursor-plugin/core/flush_worker.py
new file mode 100644
index 000000000..6f7b9ecb2
--- /dev/null
+++ b/integrations/cursor-plugin/core/flush_worker.py
@@ -0,0 +1,100 @@
+#!/usr/bin/env python3
+"""Detached remote checkpoint worker.
+
+Claude Code may cancel SessionEnd hooks as a print-mode process exits. The hook
+therefore persists its input first and launches this process in a new session.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import sys
+import time
+from pathlib import Path
+
+import telemetry
+from memory_core import (
+ EvidenceStore,
+ checkpoint_session,
+ configure_harness,
+ touch_handoff_heartbeat,
+)
+
+
+def main() -> int:
+ if len(sys.argv) != 2:
+ return 2
+ handoff_path = Path(sys.argv[1])
+ os.environ["MEM0_CODE_HANDOFF_PATH"] = str(handoff_path)
+ harness = os.environ.get("MEM0_PLUGIN_HARNESS")
+ if harness:
+ source_tag = os.environ.get("MEM0_PLUGIN_SOURCE_TAG", "")
+ configure_harness(
+ harness,
+ env_prefix=os.environ.get("MEM0_PLUGIN_ENV_PREFIX", ""),
+ data_dir_name=os.environ.get("MEM0_PLUGIN_DATA_DIR_NAME", ""),
+ source_tag=source_tag,
+ )
+ telemetry.init(harness=harness, source_tag=source_tag.upper())
+ completed = False
+ try:
+ payload = json.loads(handoff_path.read_text(encoding="utf-8"))
+ delay = float(payload.get("delay_seconds") or 0)
+ if delay > 0:
+ payload.pop("delay_seconds", None)
+ temporary = handoff_path.with_suffix(f".{os.getpid()}.tmp")
+ try:
+ temporary.write_text(json.dumps(payload), encoding="utf-8")
+ temporary.replace(handoff_path)
+ finally:
+ temporary.unlink(missing_ok=True)
+ time.sleep(delay)
+ if not handoff_path.exists():
+ return 0
+ hook_input = payload.get("hook_input") or {}
+ reason = str(payload.get("reason") or "checkpoint")
+ wait_for_inflight = bool(payload.get("wait_for_inflight"))
+ store = EvidenceStore()
+ try:
+ if wait_for_inflight:
+ session_id = str(
+ hook_input.get("session_id") or "unknown-session"
+ )
+ repo = store.repo_for_session(session_id, hook_input.get("cwd"))
+ deadline = time.monotonic() + float(
+ os.environ.get("MEM0_CODE_EXTRACTION_WAIT_SECONDS", "120")
+ )
+ while (
+ store.has_inflight_flush(repo.identity, session_id)
+ and time.monotonic() < deadline
+ ):
+ touch_handoff_heartbeat()
+ time.sleep(0.25)
+ # Hooks capture the conversation before handoff; the worker only flushes it.
+ result = checkpoint_session(store, hook_input, reason)
+ print(json.dumps(result, sort_keys=True), flush=True)
+ completed = result.get("status") in {
+ "semantic-succeeded",
+ "explicitly-stored",
+ "nothing-to-flush",
+ }
+ finally:
+ store.close()
+ return 0
+ finally:
+ telemetry.flush()
+ if completed:
+ try:
+ handoff_path.unlink()
+ except OSError:
+ pass
+ elif handoff_path.suffix == ".running":
+ try:
+ handoff_path.replace(handoff_path.with_suffix(".json"))
+ except OSError:
+ pass
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/integrations/cursor-plugin/core/hook_runner.py b/integrations/cursor-plugin/core/hook_runner.py
new file mode 100644
index 000000000..b3d8a3210
--- /dev/null
+++ b/integrations/cursor-plugin/core/hook_runner.py
@@ -0,0 +1,388 @@
+"""Shared hook orchestration for all Mem0 agent plugins."""
+
+from __future__ import annotations
+
+import argparse
+import hashlib
+import json
+import os
+import subprocess
+import sys
+import time
+import uuid
+from pathlib import Path
+
+import telemetry
+from memory_core import (
+ EvidenceStore,
+ _session_id,
+ api_key,
+ bounded,
+ cache_plugin_api_key,
+ checkpoint_session,
+ clear_stale_api_key_cache,
+ configure_harness,
+ data_dir,
+ detached_process_kwargs,
+ format_context,
+ harness_config,
+ record_session_start,
+ record_tool,
+ record_user_prompt,
+ redact,
+ search_memories,
+)
+
+STALE_RUNNING_SECONDS = 300
+PENDING_EXPIRY_SECONDS = 7 * 24 * 60 * 60
+PENDING_LAUNCH_LIMIT = 5
+DEFAULT_IDLE_FLUSH_SECONDS = 300
+
+_core_dir: Path = Path(__file__).resolve().parent
+
+
+def read_hook_input() -> dict:
+ try:
+ value = json.load(sys.stdin)
+ return value if isinstance(value, dict) else {}
+ except (json.JSONDecodeError, OSError):
+ return {}
+
+
+def default_record_stop(store: EvidenceStore, hook_input: dict):
+ """Record the assistant's response without transcript parsing."""
+ session_id = _session_id(hook_input)
+ repo = store.repo_for_session(session_id, hook_input.get("cwd"))
+ message = redact(hook_input.get("last_assistant_message", "")).strip()
+ if message:
+ store.record_assistant_response(repo, session_id, message)
+ return repo, session_id
+
+
+def first_prompt_memory_output(store: EvidenceStore, hook_input: dict) -> dict:
+ """Search once before the agent handles the first prompt in a session."""
+ repo, session_id, prompt, is_first_prompt = record_user_prompt(store, hook_input)
+ if not is_first_prompt:
+ return {}
+ try:
+ minimum_query_chars = int(os.environ.get("MEM0_CODE_MIN_QUERY_CHARS", "20"))
+ except ValueError:
+ minimum_query_chars = 20
+ if len(prompt.strip()) < max(minimum_query_chars, 1):
+ return {}
+ result = search_memories(
+ store, repo, session_id, bounded(prompt, 6000),
+ top_k=5, operation="first-prompt-search", timeout=2,
+ )
+ if not result.memories:
+ return {}
+ context = format_context(
+ result.memories,
+ "Mem0 found these relevant memories from earlier work in this repository:",
+ )
+ telemetry.record(
+ "context_injected",
+ repo=repo, session_id=session_id, trigger="first-prompt",
+ memory_count=len(result.memories), context_chars=len(context),
+ prompt_chars=len(prompt),
+ )
+ return {
+ "hookSpecificOutput": {
+ "hookEventName": "UserPromptSubmit",
+ "additionalContext": context,
+ },
+ }
+
+
+def _launch_handoff(handoff_path: Path) -> bool:
+ running_path = handoff_path.with_suffix(".running")
+ try:
+ handoff_path.replace(running_path)
+ except OSError:
+ return False
+ worker = _core_dir / "flush_worker.py"
+ log_path = data_dir() / "flush-worker.log"
+ log_handle = open(log_path, "a", encoding="utf-8")
+ harness = harness_config()
+ child_env = os.environ.copy()
+ child_env.update(
+ {
+ "MEM0_CODE_DATA_DIR": str(data_dir()),
+ "MEM0_PLUGIN_HARNESS": harness["name"],
+ "MEM0_PLUGIN_ENV_PREFIX": harness["env_prefix"],
+ "MEM0_PLUGIN_DATA_DIR_NAME": harness["data_dir_name"],
+ "MEM0_PLUGIN_SOURCE_TAG": harness["source_tag"],
+ }
+ )
+ try:
+ subprocess.Popen(
+ [sys.executable, str(worker), str(running_path)],
+ stdin=subprocess.DEVNULL,
+ stdout=log_handle, stderr=log_handle,
+ close_fds=True,
+ env=child_env,
+ **detached_process_kwargs(),
+ )
+ finally:
+ log_handle.close()
+ return True
+
+
+def recover_pending_handoffs() -> int:
+ pending_dir = data_dir() / "pending"
+ pending_dir.mkdir(parents=True, exist_ok=True)
+ now = time.time()
+ for running in pending_dir.glob("*.running"):
+ try:
+ if now - running.stat().st_mtime > STALE_RUNNING_SECONDS:
+ running.replace(running.with_suffix(".json"))
+ except OSError:
+ continue
+ recoverable = []
+ for handoff in pending_dir.glob("*.json"):
+ try:
+ age = now - handoff.stat().st_mtime
+ except OSError:
+ continue
+ if age > PENDING_EXPIRY_SECONDS:
+ handoff.unlink(missing_ok=True)
+ continue
+ recoverable.append((age, handoff))
+ recoverable.sort(key=lambda item: item[0], reverse=True)
+ launched = 0
+ for _, handoff in recoverable[:PENDING_LAUNCH_LIMIT]:
+ launched += int(_launch_handoff(handoff))
+ return launched
+
+
+def refresh_pending_handoffs() -> None:
+ pending_dir = data_dir() / "pending"
+ if not pending_dir.is_dir():
+ return
+ for pattern in ("*.json", "*.running"):
+ for handoff in pending_dir.glob(pattern):
+ try:
+ os.utime(handoff)
+ except OSError:
+ continue
+
+
+def hand_off_flush(
+ hook_input: dict, reason: str, *, wait_for_inflight: bool = False,
+) -> None:
+ pending_dir = data_dir() / "pending"
+ pending_dir.mkdir(parents=True, exist_ok=True)
+ material = (
+ f"{hook_input.get('cwd', '')}\0{hook_input.get('session_id', '')}\0{reason}"
+ )
+ digest = hashlib.sha256(material.encode()).hexdigest()[:24]
+ handoff_path = pending_dir / f"{digest}-{uuid.uuid4().hex[:8]}.json"
+ temporary_path = handoff_path.with_suffix(".tmp")
+ temporary_path.write_text(
+ json.dumps({
+ "hook_input": hook_input,
+ "reason": reason,
+ "wait_for_inflight": wait_for_inflight,
+ }),
+ encoding="utf-8",
+ )
+ temporary_path.replace(handoff_path)
+ _launch_handoff(handoff_path)
+
+
+def automatic_flush_enabled() -> bool:
+ return os.environ.get("MEM0_CODE_AUTO_FLUSH", "true").lower() in {
+ "1", "true", "yes", "on",
+ }
+
+
+def schedule_periodic_checkpoint(
+ store: EvidenceStore, hook_input: dict, repo, session_id: str,
+) -> bool:
+ if (
+ not automatic_flush_enabled()
+ or not api_key()
+ or not store.checkpoint_due(repo.identity, session_id)
+ ):
+ return False
+ if store.prepare_flush(repo, session_id, "periodic") is None:
+ return False
+ hand_off_flush(hook_input, "periodic")
+ return True
+
+
+def _idle_flush_seconds() -> int:
+ try:
+ return max(
+ int(os.environ.get("MEM0_CODE_IDLE_FLUSH_SECONDS", str(DEFAULT_IDLE_FLUSH_SECONDS))),
+ 0,
+ )
+ except ValueError:
+ return DEFAULT_IDLE_FLUSH_SECONDS
+
+
+def schedule_idle_flush(
+ store: EvidenceStore, hook_input: dict, repo, session_id: str,
+) -> bool:
+ delay = _idle_flush_seconds()
+ if delay <= 0 or not automatic_flush_enabled() or not api_key():
+ return False
+ if store.has_inflight_flush(repo.identity, session_id):
+ return False
+ if not store.has_unflushed_events(repo.identity, session_id):
+ return False
+ pending_dir = data_dir() / "pending"
+ pending_dir.mkdir(parents=True, exist_ok=True)
+ material = f"idle\0{hook_input.get('cwd', '')}\0{hook_input.get('session_id', '')}"
+ digest = hashlib.sha256(material.encode()).hexdigest()[:24]
+ for old in pending_dir.glob(f"idle-{digest}*"):
+ old.unlink(missing_ok=True)
+ handoff_path = pending_dir / f"idle-{digest}-{uuid.uuid4().hex[:8]}.json"
+ temporary_path = handoff_path.with_suffix(".tmp")
+ temporary_path.write_text(
+ json.dumps({
+ "hook_input": hook_input,
+ "reason": "idle",
+ "delay_seconds": delay,
+ }),
+ encoding="utf-8",
+ )
+ temporary_path.replace(handoff_path)
+ _launch_handoff(handoff_path)
+ return True
+
+
+def log_failure(exc: Exception) -> None:
+ try:
+ log_path = data_dir() / "plugin-errors.log"
+ with log_path.open("a", encoding="utf-8") as handle:
+ handle.write(f"{time.time():.3f} {type(exc).__name__}: {exc}\n")
+ except OSError:
+ pass
+
+
+def run(
+ *,
+ record_stop_fn=None,
+ extra_actions: dict | None = None,
+ data_dir_env: str = "MEM0_PLUGIN_DATA_DIR",
+ automatic_flush_reasons: set | None = None,
+) -> int:
+ if record_stop_fn is None:
+ record_stop_fn = default_record_stop
+ if automatic_flush_reasons is None:
+ automatic_flush_reasons = {"session-end"}
+
+ base_actions = ["session-start", "user-prompt", "post-tool", "stop", "flush"]
+ all_actions = base_actions + list((extra_actions or {}).keys())
+
+ parser = argparse.ArgumentParser()
+ parser.add_argument("action", choices=all_actions)
+ parser.add_argument("--reason", default="manual")
+ parser.add_argument("--plugin-data-dir", default="")
+ parser.add_argument("--harness", default="")
+ args = parser.parse_args()
+
+ if args.harness:
+ configure_harness(args.harness)
+ telemetry.init(harness=args.harness)
+
+ if args.plugin_data_dir:
+ os.environ[data_dir_env] = args.plugin_data_dir
+
+ # Snapshot BEFORE anything writes to the data dir: cache_plugin_api_key
+ # writes `api-key` and EvidenceStore creates `evidence.sqlite3`, so asking
+ # after them always saw content and every fresh install reported an upgrade.
+ data_dir_was_empty = telemetry.data_dir_was_empty()
+
+ cache_plugin_api_key()
+ if args.action == "session-start":
+ clear_stale_api_key_cache()
+
+ hook_input = read_hook_input()
+ store = EvidenceStore()
+ try:
+ if store.is_paused():
+ if args.action == "session-start":
+ refresh_pending_handoffs()
+ telemetry.record("session_start", paused=True)
+ telemetry.spawn_flush()
+ return 0
+
+ if args.action == "session-start":
+ # Claims the marker atomically and says which event to record, so a
+ # second session starting alongside this one cannot record it too.
+ first_event = telemetry.claim_install(was_empty=data_dir_was_empty)
+ if first_event == "install":
+ telemetry.record("install")
+ elif first_event == "upgrade":
+ # First run after a build that never wrote the marker; the
+ # predecessor version was never recorded anywhere.
+ telemetry.record("upgrade", from_version="pre-0.3")
+ else:
+ previous = telemetry.claim_version_change()
+ if previous:
+ telemetry.record("upgrade", from_version=previous)
+ recovered = recover_pending_handoffs()
+ record_session_start(store, hook_input)
+ if recovered:
+ telemetry.record("handoff_recovered", count=recovered)
+ telemetry.spawn_flush()
+ elif args.action == "user-prompt":
+ output = first_prompt_memory_output(store, hook_input)
+ if output:
+ print(json.dumps(output))
+ elif args.action == "post-tool":
+ record_tool(store, hook_input)
+ elif args.action == "stop":
+ repo, session_id = record_stop_fn(store, hook_input)
+ if not schedule_periodic_checkpoint(store, hook_input, repo, session_id):
+ schedule_idle_flush(store, hook_input, repo, session_id)
+ elif args.action == "flush":
+ automatic = args.reason in automatic_flush_reasons
+ if automatic and not automatic_flush_enabled():
+ return 0
+ if args.reason == "session-end":
+ record_stop_fn(store, hook_input)
+ if os.environ.get("MEM0_CODE_SYNC_FLUSH") == "1":
+ print(json.dumps(checkpoint_session(store, hook_input, args.reason)))
+ else:
+ session_id = str(hook_input.get("session_id") or "unknown-session")
+ repo = store.repo_for_session(session_id, hook_input.get("cwd"))
+ already_running = store.has_inflight_flush(repo.identity, session_id)
+ if already_running and args.reason == "session-end":
+ hand_off_flush(hook_input, args.reason, wait_for_inflight=True)
+ elif not already_running and store.prepare_flush(
+ repo, session_id, args.reason,
+ ) is not None:
+ hand_off_flush(hook_input, args.reason)
+ elif extra_actions and args.action in extra_actions:
+ result = extra_actions[args.action](store, hook_input)
+ if result:
+ print(json.dumps(result))
+ finally:
+ store.close()
+ return 0
+
+
+def entry_point(
+ *,
+ record_stop_fn=None,
+ extra_actions: dict | None = None,
+ data_dir_env: str = "MEM0_PLUGIN_DATA_DIR",
+ automatic_flush_reasons: set | None = None,
+) -> None:
+ try:
+ raise SystemExit(run(
+ record_stop_fn=record_stop_fn,
+ extra_actions=extra_actions,
+ data_dir_env=data_dir_env,
+ automatic_flush_reasons=automatic_flush_reasons,
+ ))
+ except Exception as exc:
+ log_failure(exc)
+ raise SystemExit(0)
+
+
+if __name__ == "__main__":
+ entry_point()
diff --git a/integrations/cursor-plugin/core/mcp_server.py b/integrations/cursor-plugin/core/mcp_server.py
new file mode 100644
index 000000000..a0b73cb79
--- /dev/null
+++ b/integrations/cursor-plugin/core/mcp_server.py
@@ -0,0 +1,240 @@
+#!/usr/bin/env python3
+"""Expose Mem0's memory search as one local coding-agent tool."""
+
+from __future__ import annotations
+
+import json
+import os
+import sys
+from typing import Any
+
+import telemetry
+from memory_core import (
+ CODING_MEMORY_CATEGORY_NAMES,
+ PLUGIN_VERSION,
+ SEARCH_SCOPES,
+ format_search_result,
+ resolve_repo,
+ search_memories,
+)
+
+PROTOCOL_VERSION = "2024-11-05"
+TOOL_NAME = "search_memories"
+TOOL_DESCRIPTION = (
+ "Search memories from earlier work in this repository. Use it before "
+ "repeating investigation or when earlier decisions, fixes, commands, or "
+ "results may help."
+)
+TOOL_SCHEMA = {
+ "type": "object",
+ "properties": {
+ "query": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 2000,
+ "description": "A direct question about earlier work in this repository.",
+ },
+ "top_k": {
+ "type": "integer",
+ "minimum": 1,
+ "maximum": 20,
+ "description": "Maximum memories to return. Uses Mem0's configured default when omitted.",
+ },
+ "category": {
+ "type": "string",
+ "enum": list(CODING_MEMORY_CATEGORY_NAMES),
+ "description": "Optional memory category. Omit to search every category.",
+ },
+ "scope": {
+ "type": "string",
+ "enum": list(SEARCH_SCOPES),
+ "description": (
+ "Which memories to search. 'repo' (default) is the whole repository's "
+ "shared memory plus your own preferences, 'dir' narrows the shared "
+ "part to the current directory, 'mine' is your preferences alone."
+ ),
+ },
+ "run_id": {
+ "type": "string",
+ "minLength": 1,
+ "description": (
+ "Optional coding-agent session ID. With any scope, restricts results to memories "
+ "saved in that session. Omit to recall memories across sessions."
+ ),
+ },
+ },
+ "required": ["query"],
+ "additionalProperties": False,
+}
+
+
+class ToolInputError(ValueError):
+ pass
+
+
+def _validate_arguments(
+ arguments: Any,
+) -> tuple[str, int | None, str | None, str | None, str | None]:
+ if not isinstance(arguments, dict):
+ raise ToolInputError("Search arguments must be an object.")
+
+ unknown = set(arguments) - {"query", "top_k", "category", "scope", "run_id"}
+ if unknown:
+ raise ToolInputError(f"Unknown search argument: {sorted(unknown)[0]}")
+
+ query = arguments.get("query")
+ if not isinstance(query, str) or not query.strip():
+ raise ToolInputError("query must be a non-empty string.")
+ query = query.strip()
+ if len(query) > 2000:
+ raise ToolInputError("query must be at most 2,000 characters.")
+
+ top_k = arguments.get("top_k")
+ if top_k is not None and (
+ isinstance(top_k, bool) or not isinstance(top_k, int) or not 1 <= top_k <= 20
+ ):
+ raise ToolInputError("top_k must be an integer from 1 to 20.")
+
+ category = arguments.get("category")
+ if category is not None and category not in CODING_MEMORY_CATEGORY_NAMES:
+ raise ToolInputError("category must be one of Mem0's supported categories.")
+
+ scope = arguments.get("scope")
+ if scope is not None and scope not in SEARCH_SCOPES:
+ raise ToolInputError(f"scope must be one of {list(SEARCH_SCOPES)}.")
+
+ run_id = arguments.get("run_id")
+ if run_id is not None:
+ if not isinstance(run_id, str) or not run_id.strip():
+ raise ToolInputError("run_id must be a non-empty string.")
+ run_id = run_id.strip()
+
+ return query, top_k, category, scope, run_id
+
+
+def call_search_memories(arguments: Any, cwd: str | None = None) -> str:
+ query, top_k, category, scope, run_id = _validate_arguments(arguments)
+ repo = resolve_repo(cwd or os.environ.get("CLAUDE_PROJECT_DIR") or os.getcwd())
+ result = search_memories(
+ None,
+ repo,
+ None,
+ query,
+ top_k=top_k,
+ category=category,
+ scope=scope,
+ run_id=run_id,
+ operation="mcp-search",
+ )
+ return format_search_result(result)
+
+
+def _workspace_cwd(params: dict[str, Any]) -> str | None:
+ meta = params.get("_meta")
+ if not isinstance(meta, dict):
+ return None
+ metadata = meta.get("x-codex-turn-metadata")
+ if not isinstance(metadata, dict):
+ return None
+ workspaces = metadata.get("workspaces") or {}
+ if isinstance(workspaces, dict):
+ return next((path for path in workspaces if isinstance(path, str) and path), None)
+ return None
+
+
+def _tool_response(text: str, *, is_error: bool = False) -> dict[str, Any]:
+ return {
+ "content": [{"type": "text", "text": text}],
+ "isError": is_error,
+ }
+
+
+def handle_request(message: Any) -> dict[str, Any] | None:
+ if not isinstance(message, dict):
+ return None
+ request_id = message.get("id")
+ method = message.get("method")
+
+ if method == "notifications/initialized":
+ return None
+ if method == "initialize":
+ requested = (message.get("params") or {}).get("protocolVersion")
+ return {
+ "jsonrpc": "2.0",
+ "id": request_id,
+ "result": {
+ "protocolVersion": requested or PROTOCOL_VERSION,
+ "capabilities": {"tools": {"listChanged": False}},
+ "serverInfo": {"name": "mem0", "version": PLUGIN_VERSION},
+ },
+ }
+ if method == "ping":
+ return {"jsonrpc": "2.0", "id": request_id, "result": {}}
+ if method == "tools/list":
+ return {
+ "jsonrpc": "2.0",
+ "id": request_id,
+ "result": {
+ "tools": [
+ {
+ "name": TOOL_NAME,
+ "description": TOOL_DESCRIPTION,
+ "inputSchema": TOOL_SCHEMA,
+ "annotations": {
+ "readOnlyHint": True,
+ "idempotentHint": True,
+ "openWorldHint": True,
+ },
+ }
+ ]
+ },
+ }
+ if method == "tools/call":
+ params = message.get("params") or {}
+ if params.get("name") != TOOL_NAME:
+ result = _tool_response("Unknown Mem0 tool.", is_error=True)
+ else:
+ try:
+ result = _tool_response(
+ call_search_memories(params.get("arguments"), _workspace_cwd(params))
+ )
+ except ToolInputError as exc:
+ result = _tool_response(str(exc), is_error=True)
+ except Exception:
+ result = _tool_response("Memory search failed.", is_error=True)
+ return {"jsonrpc": "2.0", "id": request_id, "result": result}
+ if request_id is None:
+ return None
+ return {
+ "jsonrpc": "2.0",
+ "id": request_id,
+ "error": {"code": -32601, "message": "Method not found"},
+ }
+
+
+def main() -> int:
+ for raw_line in sys.stdin:
+ try:
+ message = json.loads(raw_line)
+ response = handle_request(message)
+ except json.JSONDecodeError:
+ response = {
+ "jsonrpc": "2.0",
+ "id": None,
+ "error": {"code": -32700, "message": "Parse error"},
+ }
+ except Exception:
+ response = {
+ "jsonrpc": "2.0",
+ "id": None,
+ "error": {"code": -32603, "message": "Internal error"},
+ }
+ if response is not None:
+ sys.stdout.write(json.dumps(response, separators=(",", ":")) + "\n")
+ sys.stdout.flush()
+ telemetry.spawn_flush()
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/integrations/cursor-plugin/core/memory_cli.py b/integrations/cursor-plugin/core/memory_cli.py
new file mode 100644
index 000000000..76d2ee871
--- /dev/null
+++ b/integrations/cursor-plugin/core/memory_cli.py
@@ -0,0 +1,154 @@
+#!/usr/bin/env python3
+"""Mem0 diagnostics and user controls."""
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+
+import telemetry
+from memory_core import (
+ EvidenceStore,
+ api_key,
+ configure_harness,
+ data_dir,
+ doctor,
+ forget_remote_repo,
+ resolve_repo,
+ user_id,
+)
+
+
+def _print_status(value: dict) -> None:
+ last = value.get("last_operation") or {}
+ print(f"Mem0: {'paused' if value['paused'] else 'active'}")
+ print(f"Repository: {value['repo_id']}")
+ print(f"Local data: {value['data_dir']}")
+ print(f"API key: {'configured' if value['api_key_configured'] else 'missing'}")
+ print(
+ "Saved on this computer: "
+ f"{value['events']} session details, {value['flushes']} memory updates"
+ )
+ print(
+ f"Used in this repository: {value['retrievals']} memories returned, "
+ f"{value['subagent_runs']} subagent runs"
+ )
+ if last:
+ item_label = ""
+ if last["operation"] in {"flush", "flush-retry"}:
+ item_label = f", {last['item_count']} memories"
+ operation = (
+ "memory update"
+ if last["operation"] in {"flush", "flush-retry"}
+ else last["operation"].replace("-", " ")
+ )
+ print(
+ f"Last {operation}: "
+ f"{'succeeded' if last['success'] else 'failed'} "
+ f"({last['duration_ms']:.1f} ms{item_label})"
+ )
+ subagent = value.get("last_subagent") or {}
+ if subagent:
+ state = "finished" if subagent.get("stopped_at") else "started"
+ print(
+ "Last subagent: "
+ f"{state}, received {subagent['context_chars']} characters of memory, "
+ f"agent {subagent['agent_id']}"
+ )
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--plugin-data-dir", default="")
+ parser.add_argument("--harness", default="")
+ subparsers = parser.add_subparsers(dest="command", required=True)
+
+ status = subparsers.add_parser("status")
+ status.add_argument("--json", action="store_true")
+
+ doctor_parser = subparsers.add_parser("doctor")
+ doctor_parser.add_argument("--json", action="store_true")
+
+ subparsers.add_parser("pause")
+ subparsers.add_parser("resume")
+
+ forget = subparsers.add_parser("forget")
+ forget.add_argument("--remote", action="store_true")
+ forget.add_argument("--yes", action="store_true")
+ forget.add_argument("--include-project-memory", action="store_true")
+
+ args = parser.parse_args()
+ if args.harness:
+ source_tag = f"{args.harness.replace('-', '_')}_plugin"
+ configure_harness(args.harness, source_tag=source_tag)
+ telemetry.init(harness=args.harness, source_tag=source_tag.upper())
+ if args.plugin_data_dir:
+ os.environ["MEM0_CODE_DATA_DIR"] = args.plugin_data_dir
+ store = EvidenceStore()
+ try:
+ repo = resolve_repo(os.getcwd())
+ telemetry.record("control", repo=repo, action=args.command)
+ if args.command == "status":
+ result = {
+ **store.status(repo.identity),
+ "repo_id": repo.identity,
+ "app_id": repo.app_id,
+ "project_id": repo.project_id,
+ "directory": repo.directory,
+ "user_id": user_id(),
+ "data_dir": str(data_dir()),
+ "api_key_configured": bool(api_key()),
+ }
+ if args.json:
+ print(json.dumps(result, indent=2, default=str))
+ else:
+ _print_status(result)
+ elif args.command == "doctor":
+ result = doctor(os.getcwd())
+ if args.json:
+ print(json.dumps(result, indent=2, default=str))
+ else:
+ for name, check in result["checks"].items():
+ print(
+ f"{'PASS' if check['ok'] else 'FAIL'} {name}: {check['detail']}"
+ )
+ return 0 if result["ok"] else 1
+ elif args.command == "pause":
+ store.set_setting("paused", "true")
+ print("Mem0 stopped saving and searching memories.")
+ elif args.command == "resume":
+ store.set_setting("paused", "false")
+ print("Mem0 resumed saving and searching memories.")
+ elif args.command == "forget":
+ if not args.yes:
+ print(
+ "Refusing to delete data without --yes. Add --remote to also "
+ "delete this user/repository scope from Mem0."
+ )
+ return 2
+ remote_result = (
+ forget_remote_repo(
+ repo, include_project_memory=args.include_project_memory
+ )
+ if args.remote
+ else None
+ )
+ local_result = store.forget_local_repo(repo.identity)
+ print(
+ json.dumps(
+ {"local": local_result, "remote": remote_result},
+ indent=2,
+ default=str,
+ )
+ )
+ if remote_result and remote_result.get("status") == "error":
+ return 1
+ finally:
+ store.close()
+ telemetry.spawn_flush()
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/integrations/cursor-plugin/core/memory_core.py b/integrations/cursor-plugin/core/memory_core.py
new file mode 100644
index 000000000..9b420a063
--- /dev/null
+++ b/integrations/cursor-plugin/core/memory_core.py
@@ -0,0 +1,2676 @@
+#!/usr/bin/env python3
+"""Shared core for Mem0 agent plugins.
+
+Hooks record small session details locally. When the agent compacts or ends the
+session, Mem0 sends the useful parts to the platform so it can create memories.
+The agent can search those memories during later work in the repository.
+"""
+
+from __future__ import annotations
+
+import functools
+import hashlib
+import json
+import math
+import os
+import re
+import sqlite3
+import subprocess
+import sys
+import time
+import urllib.error
+import urllib.parse
+import urllib.request
+from dataclasses import dataclass
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Any, Iterable
+
+import telemetry
+
+DEFAULT_API_URL = "https://api.mem0.ai"
+PLUGIN_VERSION = "0.3.3"
+
+_harness_name: str = "generic"
+_harness_env_prefix: str = "MEM0_PLUGIN"
+_harness_data_dir_name: str = "mem0-plugin"
+_harness_source_tag: str = "mem0_plugin"
+
+
+def configure_harness(
+ name: str,
+ env_prefix: str = "",
+ data_dir_name: str = "",
+ source_tag: str = "",
+) -> None:
+ global _harness_name, _harness_env_prefix, _harness_data_dir_name, _harness_source_tag
+ _harness_name = name
+ _harness_env_prefix = env_prefix or f"MEM0_{name.upper().replace('-', '_')}"
+ _harness_data_dir_name = data_dir_name or f"{name}-plugin"
+ _harness_source_tag = source_tag or f"{name.replace('-', '_')}_plugin"
+
+
+def harness_config() -> dict[str, str]:
+ return {
+ "name": _harness_name,
+ "env_prefix": _harness_env_prefix,
+ "data_dir_name": _harness_data_dir_name,
+ "source_tag": _harness_source_tag,
+ }
+
+
+MAX_COMMAND_CHARS = 2000
+MAX_RESULT_CHARS = 2500
+MAX_EPISODE_CHARS = 12000
+CHECKPOINT_EXCHANGES = 5
+CHECKPOINT_MESSAGES = 10
+CHECKPOINT_SOURCE_CHARS = 40000
+DEFAULT_MAX_CONTEXT_CHARS = 4000
+MAX_EXTRACTION_INPUT_TOKENS = 24000
+MAX_FLUSH_ATTEMPTS = 5
+FORGET_PAGE_SIZE = 100
+FORGET_MAX_PAGES = 50
+
+PROJECT_MEMORY_INSTRUCTIONS = """Save concise repository facts that will help with future coding work.
+
+A completed change should produce one memory explaining the resulting behavior, where it is implemented when useful, and any important constraints or reasoning. Exploration or accepted decisions may produce separate memories only when they are independently useful.
+
+Use the coding agent's final response for conclusions about current repository behavior. Do not save proposed or recommended changes unless the user accepted them or the coding agent completed them. Treat subagent responses as supporting repository evidence, not as decisions.
+
+Write about the repository, not the user, assistant, session, or task. Do not include test results, documentation updates, release notes, or temporary state.
+
+If nothing useful was established, return no memories."""
+
+PERSONAL_MEMORY_INSTRUCTIONS = """Save concise facts about the user that will help in any repository: preferred tools, package managers, languages, coding style, review and communication preferences, and anything the user explicitly asked to be remembered about themselves.
+
+Write in the third person about the user, not about the repository, the assistant, the session, or the task. Do not save repository facts, project decisions, commands, or what was built.
+
+Never save that the user has no preferences or that nothing was learned. If nothing was learned about the user, return no memories."""
+
+CODING_MEMORY_CATEGORIES = [
+ {
+ "project_knowledge": (
+ "What the project is and how its code, APIs, data, files, and "
+ "components work."
+ )
+ },
+ {
+ "decisions_and_constraints": (
+ "Why an approach was chosen, what must remain true, and rules future "
+ "work must follow."
+ )
+ },
+ {
+ "workflows": (
+ "How to run, test, debug, deploy, configure, or otherwise work on the "
+ "project."
+ )
+ },
+ {
+ "problems_and_fixes": (
+ "Bugs, failures, known pitfalls, their causes, and how to fix or avoid "
+ "them."
+ )
+ },
+ {
+ "results": (
+ "Outcomes and measurements from tests, benchmarks, experiments, or "
+ "investigations."
+ )
+ },
+]
+CODING_MEMORY_CATEGORY_NAMES = tuple(
+ category_name
+ for category in CODING_MEMORY_CATEGORIES
+ for category_name in category
+)
+
+TEST_COMMAND_RE = re.compile(
+ r"(?:^|\s)(?:pytest|py\.test|jest|vitest|go\s+test|cargo\s+test|"
+ r"npm\s+(?:run\s+)?test|pnpm\s+(?:run\s+)?test|yarn\s+test|"
+ r"mvn\s+test|gradle\s+test|make\s+test)(?:\s|$)",
+ re.IGNORECASE,
+)
+BUILD_COMMAND_RE = re.compile(
+ r"(?:^|\s)(?:npm|pnpm|yarn)\s+(?:run\s+)?build(?:\s|$)|"
+ r"(?:^|\s)(?:cargo|go|mvn|gradle|make)\s+build(?:\s|$)",
+ re.IGNORECASE,
+)
+
+SECRET_PATTERNS = [
+ re.compile(r"(?i)(authorization\s*[:=]\s*(?:bearer|token)\s+)[^\s\"']+"),
+ re.compile(
+ r"(?i)((?:api[_-]?key|secret[_-]?access[_-]?key|session[_-]?token)\s*[:=]\s*)[^\s\"']+"
+ ),
+ re.compile(
+ r"(?i)((?:access[_-]?token|refresh[_-]?token|password|credential)"
+ r"\s*[:=]\s*)[^\s&\"']+"
+ ),
+ re.compile(r"\b(?:sk|m0|mem0_sk|psk)-[A-Za-z0-9_\-]{12,}\b"),
+ re.compile(r"\b(?:ASIA|AKIA)[A-Z0-9]{12,}\b"),
+ re.compile(r"\b(?:ghp_|github_pat_|xox[baprs]-)[A-Za-z0-9_\-]{12,}\b"),
+ re.compile(
+ r"-----BEGIN [^-]*PRIVATE KEY-----.*?-----END [^-]*PRIVATE KEY-----",
+ re.DOTALL,
+ ),
+ re.compile(
+ r'(?i)("(?:api[_-]?key|password|secret(?:[_-]?access[_-]?key)?'
+ r'|(?:access|refresh|session)[_-]?token|token|authorization|credential'
+ r')"\s*:\s*")(?:\\.|[^"\\])*'
+ ),
+]
+
+
+def utc_now() -> str:
+ return datetime.now(timezone.utc).isoformat()
+
+
+def redact(value: Any) -> str:
+ text = (
+ value
+ if isinstance(value, str)
+ else json.dumps(value, ensure_ascii=False, default=str)
+ )
+ for pattern in SECRET_PATTERNS:
+ if pattern.groups:
+ text = pattern.sub(r"\1[REDACTED]", text)
+ else:
+ text = pattern.sub("[REDACTED]", text)
+ return text
+
+
+def bounded(value: Any, limit: int) -> str:
+ text = redact(value).strip()
+ if len(text) <= limit:
+ return text
+ return text[:limit] + f"\n...[truncated {len(text) - limit} chars]"
+
+
+def _git(cwd: str, *args: str) -> str:
+ try:
+ result = subprocess.run(
+ ["git", "-C", cwd, *args],
+ check=False,
+ capture_output=True,
+ text=True,
+ timeout=0.5,
+ )
+ except (OSError, subprocess.TimeoutExpired):
+ return ""
+ return result.stdout.strip() if result.returncode == 0 else ""
+
+
+def _normalize_remote(remote: str) -> str:
+ remote = remote.strip()
+ if remote.startswith("git@") and ":" in remote:
+ host_path = remote[4:].replace(":", "/", 1)
+ remote = f"https://{host_path}"
+ if remote.endswith(".git"):
+ remote = remote[:-4]
+ if "://" in remote:
+ parsed = urllib.parse.urlsplit(remote)
+ hostname = parsed.hostname or ""
+ if parsed.port:
+ hostname = f"{hostname}:{parsed.port}"
+ remote = urllib.parse.urlunsplit(
+ (parsed.scheme, hostname, parsed.path, parsed.query, parsed.fragment)
+ )
+ return remote.rstrip("/")
+
+
+_WILDCARD_SCOPE = re.compile(r"^\*+$")
+
+
+def _scope_value(raw: str | None) -> str:
+ """Reject wildcards as identities: they are filter syntax and would widen the scope."""
+ value = (raw or "").strip()
+ return "" if _WILDCARD_SCOPE.match(value) else value
+
+
+SEARCH_SCOPES = ("repo", "dir", "mine")
+DEFAULT_SEARCH_SCOPE = "repo"
+
+def directory_app_id(repo: RepoContext) -> str:
+ """The app_id of the directory this session runs in: the repository at the root, repository/path below it."""
+ return f"{repo.app_id}/{repo.directory}" if repo.directory else repo.app_id
+
+
+def directory_chain(repo: RepoContext) -> list[str]:
+ """Every directory a memory belongs to, from the top-level folder down to the one it was written in."""
+ parts = repo.directory.split("/") if repo.directory else []
+ return ["/".join(parts[: index + 1]) for index in range(len(parts))]
+
+
+def _shared_project_ids(repo: RepoContext) -> list[str]:
+ """Current and pre-upgrade namespaces, shared by recall and explicit deletion."""
+ if not repo.identity.startswith("local:") and repo.project_id != repo.app_id:
+ return [repo.project_id, repo.app_id]
+ return [repo.project_id]
+
+
+def _search_filters(user: str, repo: RepoContext, scope: str) -> dict[str, Any]:
+ """Build the scope filter: app_id scopes to the repo, then union shared and personal lanes."""
+ app_scope = {"app_id": repo.app_id}
+ mine = {"AND": [{"user_id": user}, app_scope]}
+ if scope == "mine":
+ return mine
+ projects = [{"AND": [{"agent_id": project_id}, app_scope]} for project_id in _shared_project_ids(repo)]
+ shared: dict[str, Any] = projects[0] if len(projects) == 1 else {"OR": projects}
+ if scope == "dir" and repo.directory:
+ shared = {"AND": [shared, {"metadata": {"dirs": {"contains": repo.directory}}}]}
+ return {"OR": [shared, mine]}
+
+
+def search_scope() -> str:
+ configured = (
+ _plugin_option("search_scope", "MEM0_CODE_SEARCH_SCOPE") or ""
+ ).strip().lower()
+ return configured if configured in SEARCH_SCOPES else DEFAULT_SEARCH_SCOPE
+
+
+def resolve_search_scope(scope: str | None) -> str:
+ value = (scope or search_scope()).strip().lower()
+ if value not in SEARCH_SCOPES:
+ raise ValueError(f"Unknown search scope: {value}")
+ return value
+
+
+def _legacy_project_map(cwd: str, root: str, raw_remote: str) -> str:
+ """Return the project name used by the previous Claude Code plugin."""
+ try:
+ data = json.loads((Path.home() / ".mem0" / "project_map.json").read_text())
+ except (OSError, json.JSONDecodeError):
+ return ""
+ if not isinstance(data, dict):
+ return ""
+
+ keys = list(dict.fromkeys([cwd, root, os.path.realpath(cwd), os.path.realpath(root)]))
+ if raw_remote:
+ keys.append(f"remote:{hashlib.sha256(raw_remote.encode()).hexdigest()[:16]}")
+ for key in keys:
+ value = data.get(key)
+ if isinstance(value, str) and value.strip():
+ return value.strip()
+ return ""
+
+
+def _legacy_project_id(cwd: str, root: str, raw_remote: str, identity: str) -> str:
+ """Use the repository namespace created by the previous Mem0 plugin."""
+ configured = _scope_value(os.environ.get("MEM0_PROJECT_ID"))
+ if configured:
+ return configured
+
+ mapped = _scope_value(_legacy_project_map(cwd, root, raw_remote))
+ if mapped:
+ return mapped
+
+ remote = raw_remote or ("" if identity.startswith("local:") else identity)
+ remote = remote.strip().removesuffix(".git")
+ for prefix in ("https://", "http://", "ssh://", "git://"):
+ if remote.startswith(prefix):
+ remote = remote[len(prefix) :]
+ break
+ else:
+ remote = re.sub(r"^git@", "", remote)
+ parts = [part for part in remote.replace(":", "/", 1).split("/") if part]
+ if len(parts) >= 2:
+ return f"{parts[-2]}-{parts[-1]}".replace("/", "-").replace(":", "-")
+ if parts:
+ return parts[-1].replace("/", "-").replace(":", "-")
+ return os.path.basename(root or cwd) or "unknown"
+
+
+@dataclass(frozen=True)
+class RepoContext:
+ cwd: str
+ root: str
+ identity: str
+ app_id: str
+ branch: str
+ head_sha: str
+ project_id: str = ""
+ directory: str = ""
+
+
+def _project_id(root: str, identity: str, app_id: str) -> str:
+ """The shared namespace: includes a host hash so repos with the same owner/name on different hosts stay apart."""
+ if not identity.startswith("local:"):
+ return f"{app_id}-{hashlib.sha256(identity.encode()).hexdigest()[:10]}"
+ return f"local-{app_id}-{hashlib.sha256(root.encode()).hexdigest()[:10]}"
+
+
+def _relative_directory(cwd: str, root: str) -> str:
+ relative = os.path.relpath(cwd, root)
+ return "" if relative == "." or relative.startswith("..") else relative.replace(os.sep, "/")
+
+
+@dataclass(frozen=True)
+class MemorySearchResult:
+ succeeded: bool
+ matched_count: int
+ already_shown_count: int
+ memories: list[dict[str, Any]]
+
+
+@functools.lru_cache(maxsize=64)
+def _resolve_repo_cached(cwd: str) -> RepoContext:
+ given_cwd = cwd
+ cwd = os.path.realpath(cwd)
+ given_root = _git(cwd, "rev-parse", "--show-toplevel") or given_cwd
+ root = os.path.realpath(given_root)
+ raw_remote = _git(root, "config", "--get", "remote.origin.url")
+ remote = _normalize_remote(raw_remote)
+ identity = remote or f"local:{root}"
+ app_id = _legacy_project_id(given_cwd, given_root, raw_remote, identity)
+ return RepoContext(
+ cwd=cwd,
+ root=root,
+ identity=identity,
+ app_id=app_id,
+ branch=_git(root, "branch", "--show-current") or "detached",
+ head_sha=_git(root, "rev-parse", "HEAD"),
+ project_id=_project_id(root, identity, app_id),
+ directory=_relative_directory(cwd, root),
+ )
+
+
+def resolve_repo(cwd: str | None) -> RepoContext:
+ return _resolve_repo_cached(os.path.abspath(cwd or os.getcwd()))
+
+
+def api_key() -> str:
+ configured = (
+ os.environ.get("MEM0_API_KEY")
+ or os.environ.get("PLUGIN_OPTION_API_KEY")
+ or os.environ.get("CLAUDE_PLUGIN_OPTION_API_KEY")
+ or os.environ.get("CLAUDE_PLUGIN_OPTION_MEM0_API_KEY")
+ or ""
+ ).strip()
+ if configured:
+ return configured
+ try:
+ return (data_dir() / "api-key").read_text(encoding="utf-8").strip()
+ except OSError:
+ return ""
+
+
+def cache_plugin_api_key() -> bool:
+ """Bridge host's hook-only sensitive config into plugin-owned storage."""
+ configured = (
+ os.environ.get("PLUGIN_OPTION_API_KEY")
+ or os.environ.get("CLAUDE_PLUGIN_OPTION_API_KEY")
+ or os.environ.get("CLAUDE_PLUGIN_OPTION_MEM0_API_KEY")
+ or ""
+ ).strip()
+ if not configured:
+ return False
+
+ directory = data_dir()
+ directory.mkdir(parents=True, exist_ok=True)
+ path = directory / "api-key"
+ temporary = directory / f"api-key.{os.getpid()}.tmp"
+ descriptor = os.open(
+ temporary,
+ os.O_WRONLY | os.O_CREAT | os.O_TRUNC,
+ 0o600,
+ )
+ try:
+ with os.fdopen(descriptor, "w", encoding="utf-8") as handle:
+ handle.write(configured)
+ os.replace(temporary, path)
+ os.chmod(path, 0o600)
+ finally:
+ try:
+ temporary.unlink()
+ except FileNotFoundError:
+ pass
+ return True
+
+
+def clear_stale_api_key_cache() -> bool:
+ """Drop the cached key file once every configured key source is gone."""
+ configured = (
+ os.environ.get("MEM0_API_KEY")
+ or os.environ.get("PLUGIN_OPTION_API_KEY")
+ or os.environ.get("CLAUDE_PLUGIN_OPTION_API_KEY")
+ or os.environ.get("CLAUDE_PLUGIN_OPTION_MEM0_API_KEY")
+ or ""
+ ).strip()
+ if configured:
+ return False
+ path = data_dir() / "api-key"
+ if not path.exists():
+ return False
+ try:
+ path.unlink()
+ except OSError:
+ return False
+ return True
+
+
+def detached_process_kwargs(platform: str | None = None) -> dict:
+ """Keep a spawned worker alive after the coding agent exits, on POSIX and Windows."""
+ if (platform or sys.platform) == "win32":
+ return {
+ "creationflags": subprocess.DETACHED_PROCESS
+ | subprocess.CREATE_NEW_PROCESS_GROUP
+ }
+ return {"start_new_session": True}
+
+
+def _plugin_option(name: str, fallback: str = "") -> str:
+ return (
+ os.environ.get(f"PLUGIN_OPTION_{name.upper()}")
+ or os.environ.get(f"CLAUDE_PLUGIN_OPTION_{name.upper()}")
+ or os.environ.get(fallback)
+ or ""
+ ).strip()
+
+
+def user_id() -> str:
+ return (
+ _scope_value(_plugin_option("user_id", "MEM0_CODE_USER_ID"))
+ or _scope_value(os.environ.get("MEM0_USER_ID"))
+ or _scope_value(os.environ.get("MEM0_RESOLVED_USER_ID"))
+ or _scope_value(os.environ.get("USER"))
+ or _scope_value(os.environ.get("USERNAME"))
+ or "default"
+ )
+
+
+def data_dir() -> Path:
+ configured = (
+ os.environ.get("MEM0_CODE_DATA_DIR")
+ or os.environ.get("MEM0_PLUGIN_DATA_DIR")
+ or os.environ.get("PLUGIN_DATA")
+ or os.environ.get("CLAUDE_PLUGIN_DATA")
+ )
+ return (
+ Path(configured).expanduser() if configured else Path.home() / ".mem0" / _harness_data_dir_name
+ )
+
+
+def _bool_option(name: str, fallback: str, default: bool = False) -> bool:
+ value = _plugin_option(name, fallback)
+ if not value:
+ return default
+ return value.lower() in {"1", "true", "yes", "on"}
+
+
+def _int_option(name: str, fallback: str, default: int) -> int:
+ value = _plugin_option(name, fallback)
+ try:
+ return int(value) if value else default
+ except ValueError:
+ return default
+
+
+
+def _checkpoint_message(event: dict[str, Any]) -> str:
+ kind = event.get("kind")
+ payload = event.get("payload") or {}
+ if kind == "user_prompt":
+ return redact(payload.get("text", "")).strip()
+ if kind == "assistant_stop":
+ transcript_messages = payload.get("transcript_messages") or []
+ if isinstance(transcript_messages, list):
+ text = "\n".join(
+ str(message.get("content") or "")
+ for message in transcript_messages
+ if isinstance(message, dict) and message.get("content")
+ )
+ if text:
+ return text
+ return redact(payload.get("text", "")).strip()
+ if kind in {"subagent_stop", "sidekick_stop"}:
+ return redact(payload.get("final_message", "")).strip()
+ return ""
+
+
+def checkpoint_stats(events: list[dict[str, Any]]) -> tuple[int, int, int]:
+ """Return completed exchanges, messages, and source characters."""
+ completed = sum(event.get("kind") == "assistant_stop" for event in events)
+ contents = [content for event in events if (content := _checkpoint_message(event))]
+ return completed, len(contents), sum(len(content) for content in contents)
+
+
+def select_checkpoint_events(
+ events: list[dict[str, Any]], *, force: bool
+) -> list[dict[str, Any]]:
+ """Select one ordered extraction block without splitting an exchange."""
+ for index, event in enumerate(events):
+ if event.get("kind") != "assistant_stop":
+ continue
+ candidate = events[: index + 1]
+ completed, messages, source_chars = checkpoint_stats(candidate)
+ if (
+ completed >= CHECKPOINT_EXCHANGES
+ or messages >= CHECKPOINT_MESSAGES
+ or source_chars >= CHECKPOINT_SOURCE_CHARS
+ ):
+ return candidate
+ return events if force else []
+
+
+class EvidenceStore:
+ def __init__(self, path: Path | None = None):
+ directory = data_dir() if path is None else path.parent
+ directory.mkdir(parents=True, exist_ok=True)
+ self.path = path or directory / "evidence.sqlite3"
+ try:
+ self._open()
+ except sqlite3.DatabaseError:
+ self._quarantine()
+ self._open()
+
+ def _open(self) -> None:
+ self.conn = sqlite3.connect(self.path, timeout=10)
+ self.conn.row_factory = sqlite3.Row
+ try:
+ self.conn.execute("PRAGMA journal_mode=WAL")
+ self.conn.execute("PRAGMA busy_timeout=10000")
+ self._migrate()
+ except sqlite3.DatabaseError:
+ self.conn.close()
+ raise
+
+ def _quarantine(self) -> None:
+ """Move an unreadable database aside so capture restarts cleanly."""
+ stamp = int(time.time())
+ for suffix in ("", "-wal", "-shm"):
+ source = Path(f"{self.path}{suffix}")
+ try:
+ source.replace(f"{self.path}.corrupt-{stamp}{suffix}")
+ except FileNotFoundError:
+ continue
+ except OSError:
+ try:
+ source.unlink()
+ except OSError:
+ pass
+ telemetry.record("db_quarantined")
+
+ def close(self) -> None:
+ self.conn.close()
+
+ def _migrate(self) -> None:
+ # Keep the legacy table name so existing databases and in-flight workers remain compatible.
+ self.conn.executescript(
+ """
+ CREATE TABLE IF NOT EXISTS events (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ repo_id TEXT NOT NULL,
+ app_id TEXT NOT NULL,
+ session_id TEXT NOT NULL,
+ created_at TEXT NOT NULL,
+ kind TEXT NOT NULL,
+ payload_json TEXT NOT NULL,
+ flush_id TEXT
+ );
+ CREATE INDEX IF NOT EXISTS events_session_idx
+ ON events(repo_id, session_id, flush_id, id);
+
+ CREATE TABLE IF NOT EXISTS session_scopes (
+ session_id TEXT PRIMARY KEY,
+ repo_id TEXT NOT NULL,
+ app_id TEXT NOT NULL,
+ root TEXT NOT NULL,
+ branch TEXT NOT NULL,
+ head_sha TEXT NOT NULL,
+ created_at TEXT NOT NULL,
+ directory TEXT NOT NULL DEFAULT ''
+ );
+
+ CREATE TABLE IF NOT EXISTS flushes (
+ packet_id TEXT PRIMARY KEY,
+ repo_id TEXT NOT NULL,
+ app_id TEXT NOT NULL,
+ session_id TEXT NOT NULL,
+ reason TEXT NOT NULL,
+ event_start INTEGER NOT NULL,
+ event_end INTEGER NOT NULL,
+ status TEXT NOT NULL,
+ episode_event_id TEXT,
+ semantic_event_id TEXT,
+ error TEXT,
+ attempts INTEGER NOT NULL DEFAULT 0,
+ created_at TEXT NOT NULL,
+ updated_at TEXT NOT NULL
+ );
+
+ CREATE TABLE IF NOT EXISTS retrievals (
+ session_id TEXT NOT NULL,
+ repo_id TEXT NOT NULL,
+ memory_id TEXT NOT NULL,
+ injected_at TEXT NOT NULL,
+ rank INTEGER,
+ score REAL,
+ memory_text TEXT,
+ context_chars INTEGER NOT NULL DEFAULT 0,
+ PRIMARY KEY(session_id, repo_id, memory_id)
+ );
+
+ CREATE TABLE IF NOT EXISTS operations (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ created_at TEXT NOT NULL,
+ repo_id TEXT NOT NULL,
+ session_id TEXT NOT NULL,
+ operation TEXT NOT NULL,
+ duration_ms REAL NOT NULL,
+ success INTEGER NOT NULL,
+ item_count INTEGER NOT NULL DEFAULT 0,
+ request_chars INTEGER NOT NULL DEFAULT 0,
+ response_chars INTEGER NOT NULL DEFAULT 0,
+ error TEXT
+ );
+
+ CREATE TABLE IF NOT EXISTS sidekick_runs (
+ repo_id TEXT NOT NULL,
+ session_id TEXT NOT NULL,
+ agent_id TEXT NOT NULL,
+ agent_type TEXT NOT NULL,
+ started_at TEXT NOT NULL,
+ stopped_at TEXT,
+ transcript_path TEXT,
+ context_chars INTEGER NOT NULL DEFAULT 0,
+ final_message TEXT,
+ PRIMARY KEY(repo_id, session_id, agent_id)
+ );
+ CREATE INDEX IF NOT EXISTS sidekick_runs_repo_idx
+ ON sidekick_runs(repo_id, started_at);
+
+ CREATE TABLE IF NOT EXISTS settings (
+ key TEXT PRIMARY KEY,
+ value TEXT NOT NULL,
+ updated_at TEXT NOT NULL
+ );
+
+ """
+ )
+ # Remove the pre-0.1.1 snapshot implementation.
+ self.conn.executescript(
+ """
+ DROP TABLE IF EXISTS sidekick_calls;
+ DROP TABLE IF EXISTS sidekick_snapshots;
+ DROP TABLE IF EXISTS sidekick_state;
+ DROP TABLE IF EXISTS sidekick_packets;
+ """
+ )
+ self._ensure_column("retrievals", "rank", "INTEGER")
+ self._ensure_column("retrievals", "score", "REAL")
+ self._ensure_column("retrievals", "memory_text", "TEXT")
+ self._ensure_column("retrievals", "context_chars", "INTEGER NOT NULL DEFAULT 0")
+ self._ensure_column("flushes", "attempts", "INTEGER NOT NULL DEFAULT 0")
+ self._ensure_column("session_scopes", "directory", "TEXT NOT NULL DEFAULT ''")
+ self.conn.commit()
+
+ def _ensure_column(self, table: str, column: str, declaration: str) -> None:
+ columns = {
+ str(row["name"])
+ for row in self.conn.execute(f"PRAGMA table_info({table})").fetchall()
+ }
+ if column not in columns:
+ self.conn.execute(f"ALTER TABLE {table} ADD COLUMN {column} {declaration}")
+
+ def record_event(
+ self,
+ repo: RepoContext,
+ session_id: str,
+ kind: str,
+ payload: dict[str, Any],
+ ) -> int:
+ cursor = self.conn.execute(
+ """INSERT INTO events
+ (repo_id, app_id, session_id, created_at, kind, payload_json)
+ VALUES (?, ?, ?, ?, ?, ?)""",
+ (
+ repo.identity,
+ repo.app_id,
+ session_id,
+ utc_now(),
+ kind,
+ json.dumps(payload, ensure_ascii=False, sort_keys=True),
+ ),
+ )
+ self.conn.commit()
+ return int(cursor.lastrowid)
+
+ def record_assistant_response(self, repo: RepoContext, session_id: str, message: str) -> None:
+ """Ignore repeated response hooks until another prompt or a different answer arrives."""
+ with self.conn:
+ # Serialize the check and insert across concurrent Stop and SessionEnd hooks.
+ self.conn.execute("BEGIN IMMEDIATE")
+ previous = self.conn.execute(
+ """SELECT kind, payload_json FROM events
+ WHERE repo_id = ? AND session_id = ? AND kind IN ('user_prompt', 'assistant_stop')
+ ORDER BY id DESC LIMIT 1""",
+ (repo.identity, session_id),
+ ).fetchone()
+ if (
+ previous is not None
+ and previous["kind"] == "assistant_stop"
+ and json.loads(previous["payload_json"]).get("text") == message
+ ):
+ return
+ self.record_event(repo, session_id, "assistant_stop", {"text": message})
+
+ def repo_for_session(self, session_id: str, cwd: str | None) -> RepoContext:
+ """Keep one project scope for every hook in a coding-agent session."""
+ current = resolve_repo(cwd)
+ if session_id == "unknown-session":
+ return current
+
+ with self.conn:
+ self.conn.execute(
+ """INSERT OR IGNORE INTO session_scopes
+ (session_id, repo_id, app_id, root, branch, head_sha, created_at, directory)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)""",
+ (
+ session_id,
+ current.identity,
+ current.app_id,
+ current.root,
+ current.branch,
+ current.head_sha,
+ utc_now(),
+ current.directory,
+ ),
+ )
+ scope = self.conn.execute(
+ "SELECT * FROM session_scopes WHERE session_id = ?", (session_id,)
+ ).fetchone()
+ same_git_repo = (
+ current.identity == scope["repo_id"] and bool(current.head_sha)
+ )
+ pinned = current if same_git_repo else resolve_repo(str(scope["root"]))
+ return RepoContext(
+ cwd=current.cwd,
+ root=pinned.root,
+ identity=str(scope["repo_id"]),
+ app_id=str(scope["app_id"]),
+ branch=pinned.branch,
+ head_sha=pinned.head_sha,
+ project_id=pinned.project_id,
+ directory=str(scope["directory"] or ""),
+ )
+
+ def prepare_flush(
+ self, repo: RepoContext, session_id: str, reason: str
+ ) -> tuple[str, list[dict[str, Any]]] | None:
+ with self.conn:
+ self.conn.execute("BEGIN IMMEDIATE")
+ existing = self.conn.execute(
+ """SELECT * FROM flushes
+ WHERE repo_id = ? AND session_id = ?
+ AND status NOT IN ('semantic-succeeded', 'explicitly-stored', 'gave-up')
+ ORDER BY created_at LIMIT 1""",
+ (repo.identity, session_id),
+ ).fetchone()
+ if existing and int(existing["attempts"] or 0) >= MAX_FLUSH_ATTEMPTS:
+ self.conn.execute(
+ "UPDATE flushes SET status = 'gave-up', updated_at = ? WHERE packet_id = ?",
+ (utc_now(), existing["packet_id"]),
+ )
+ telemetry.record(
+ "flush",
+ repo=repo,
+ session_id=session_id,
+ reason=reason,
+ status="gave-up",
+ success=False,
+ attempts=int(existing["attempts"] or 0),
+ )
+ existing = None
+ if existing:
+ if reason != "periodic" and existing["reason"] == "periodic":
+ self.conn.execute(
+ "UPDATE flushes SET reason = ?, updated_at = ? WHERE packet_id = ?",
+ (reason, utc_now(), existing["packet_id"]),
+ )
+ existing_rows = self.conn.execute(
+ "SELECT * FROM events WHERE flush_id = ? ORDER BY id",
+ (existing["packet_id"],),
+ ).fetchall()
+ if existing_rows:
+ return str(existing["packet_id"]), [
+ {
+ "id": row["id"],
+ "created_at": row["created_at"],
+ "kind": row["kind"],
+ "payload": json.loads(row["payload_json"]),
+ }
+ for row in existing_rows
+ ]
+
+ rows = self.conn.execute(
+ """SELECT * FROM events
+ WHERE repo_id = ? AND session_id = ? AND flush_id IS NULL
+ ORDER BY id""",
+ (repo.identity, session_id),
+ ).fetchall()
+ if not rows:
+ return None
+
+ events = [
+ {
+ "id": row["id"],
+ "created_at": row["created_at"],
+ "kind": row["kind"],
+ "payload": json.loads(row["payload_json"]),
+ }
+ for row in rows
+ ]
+ events = select_checkpoint_events(events, force=reason != "periodic")
+ if not events:
+ return None
+ event_start, event_end = events[0]["id"], events[-1]["id"]
+ packet_material = f"{repo.identity}\0{session_id}\0{event_start}\0{event_end}"
+ packet_id = hashlib.sha256(packet_material.encode()).hexdigest()[:32]
+ now = utc_now()
+
+ self.conn.execute(
+ """INSERT OR IGNORE INTO flushes
+ (packet_id, repo_id, app_id, session_id, reason, event_start,
+ event_end, status, created_at, updated_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, 'prepared', ?, ?)""",
+ (
+ packet_id,
+ repo.identity,
+ repo.app_id,
+ session_id,
+ reason,
+ event_start,
+ event_end,
+ now,
+ now,
+ ),
+ )
+ event_ids = [event["id"] for event in events]
+ placeholders = ", ".join("?" for _ in event_ids)
+ self.conn.execute(
+ f"UPDATE events SET flush_id = ? "
+ f"WHERE id IN ({placeholders}) AND flush_id IS NULL",
+ (packet_id, *event_ids),
+ )
+ return packet_id, events
+
+ def checkpoint_due(self, repo_id: str, session_id: str) -> bool:
+ if self.has_inflight_flush(repo_id, session_id):
+ return False
+ rows = self.conn.execute(
+ """SELECT * FROM events
+ WHERE repo_id = ? AND session_id = ? AND flush_id IS NULL
+ ORDER BY id""",
+ (repo_id, session_id),
+ ).fetchall()
+ events = [
+ {
+ "id": row["id"],
+ "created_at": row["created_at"],
+ "kind": row["kind"],
+ "payload": json.loads(row["payload_json"]),
+ }
+ for row in rows
+ ]
+ return bool(select_checkpoint_events(events, force=False))
+
+ def has_inflight_flush(self, repo_id: str, session_id: str) -> bool:
+ return (
+ self.conn.execute(
+ """SELECT 1 FROM flushes
+ WHERE repo_id = ? AND session_id = ?
+ AND status IN ('prepared', 'semantic-queued')
+ LIMIT 1""",
+ (repo_id, session_id),
+ ).fetchone()
+ is not None
+ )
+
+ def flush_record(self, packet_id: str) -> dict[str, Any] | None:
+ row = self.conn.execute(
+ "SELECT * FROM flushes WHERE packet_id = ?", (packet_id,)
+ ).fetchone()
+ return dict(row) if row else None
+
+ def has_unflushed_events(self, repo_id: str, session_id: str) -> bool:
+ return (
+ self.conn.execute(
+ """SELECT 1 FROM events
+ WHERE repo_id = ? AND session_id = ? AND flush_id IS NULL
+ LIMIT 1""",
+ (repo_id, session_id),
+ ).fetchone()
+ is not None
+ )
+
+ def unflushed_starts_with_session_start(
+ self, repo_id: str, session_id: str
+ ) -> bool:
+ row = self.conn.execute(
+ """SELECT kind FROM events
+ WHERE repo_id = ? AND session_id = ? AND flush_id IS NULL
+ ORDER BY id LIMIT 1""",
+ (repo_id, session_id),
+ ).fetchone()
+ return bool(row and row["kind"] == "session_start")
+
+ def update_flush(self, packet_id: str, **fields: Any) -> None:
+ allowed = {"status", "episode_event_id", "semantic_event_id", "error"}
+ updates = {key: value for key, value in fields.items() if key in allowed}
+ updates["updated_at"] = utc_now()
+ clause = ", ".join(f"{key} = ?" for key in updates)
+ failed = str(fields.get("status", "")) in {
+ "error",
+ "semantic-failed",
+ "semantic-timeout",
+ "semantic-missing",
+ }
+ if failed:
+ clause += ", attempts = attempts + 1"
+ with self.conn:
+ self.conn.execute(
+ f"UPDATE flushes SET {clause} WHERE packet_id = ?",
+ [*updates.values(), packet_id],
+ )
+
+ def unseen(
+ self, session_id: str, repo_id: str, memories: Iterable[dict[str, Any]]
+ ) -> list[dict[str, Any]]:
+ seen = {
+ row["memory_id"]
+ for row in self.conn.execute(
+ "SELECT memory_id FROM retrievals WHERE session_id = ? AND repo_id = ?",
+ (session_id, repo_id),
+ )
+ }
+ return [memory for memory in memories if str(memory.get("id", "")) not in seen]
+
+ def mark_injected(
+ self, session_id: str, repo_id: str, memories: Iterable[dict[str, Any]]
+ ) -> None:
+ now = utc_now()
+ with self.conn:
+ for rank, memory in enumerate(memories, start=1):
+ memory_id = str(memory.get("id", ""))
+ if memory_id:
+ memory_text = bounded(
+ memory.get("memory") or memory.get("text") or "",
+ 4000,
+ )
+ try:
+ score = float(memory["score"])
+ except (KeyError, TypeError, ValueError):
+ score = None
+ self.conn.execute(
+ """INSERT OR IGNORE INTO retrievals
+ (session_id, repo_id, memory_id, injected_at, rank,
+ score, memory_text, context_chars)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)""",
+ (
+ session_id,
+ repo_id,
+ memory_id,
+ now,
+ rank,
+ score,
+ memory_text,
+ len(memory_text),
+ ),
+ )
+
+ def injected_memories(
+ self, session_id: str, repo_id: str
+ ) -> list[dict[str, Any]]:
+ """Return the exact memories already supplied to the main conversation."""
+ rows = self.conn.execute(
+ """SELECT memory_id, rank, score, memory_text
+ FROM retrievals
+ WHERE session_id = ? AND repo_id = ?
+ ORDER BY COALESCE(rank, 2147483647), injected_at, memory_id""",
+ (session_id, repo_id),
+ ).fetchall()
+ return [
+ {
+ "id": row["memory_id"],
+ "memory": row["memory_text"],
+ "score": row["score"],
+ }
+ for row in rows
+ if row["memory_text"]
+ ]
+
+ def start_subagent(
+ self,
+ repo: RepoContext,
+ session_id: str,
+ agent_id: str,
+ agent_type: str,
+ context_chars: int,
+ ) -> bool:
+ """Record one native subagent instance and whether context was first sent."""
+ with self.conn:
+ cursor = self.conn.execute(
+ """INSERT OR IGNORE INTO sidekick_runs
+ (repo_id, session_id, agent_id, agent_type, started_at,
+ context_chars)
+ VALUES (?, ?, ?, ?, ?, ?)""",
+ (
+ repo.identity,
+ session_id,
+ agent_id,
+ agent_type,
+ utc_now(),
+ context_chars,
+ ),
+ )
+ return int(cursor.rowcount) > 0
+
+ def stop_subagent(
+ self,
+ repo: RepoContext,
+ session_id: str,
+ agent_id: str,
+ agent_type: str,
+ transcript_path: str,
+ final_message: str,
+ ) -> str:
+ now = utc_now()
+ self.conn.execute("BEGIN IMMEDIATE")
+ try:
+ if not agent_id:
+ rows = self.conn.execute(
+ """SELECT agent_id FROM sidekick_runs
+ WHERE repo_id = ? AND session_id = ? AND agent_type = ? AND stopped_at IS NULL
+ LIMIT 2""",
+ (repo.identity, session_id, agent_type),
+ ).fetchall()
+ # Without a host ID, overlapping runs cannot be correlated reliably.
+ agent_id = rows[0]["agent_id"] if len(rows) == 1 else f"unknown-agent-{time.time_ns()}"
+ self.conn.execute(
+ """INSERT INTO sidekick_runs
+ (repo_id, session_id, agent_id, agent_type, started_at,
+ stopped_at, transcript_path, final_message)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
+ ON CONFLICT(repo_id, session_id, agent_id) DO UPDATE SET
+ stopped_at = excluded.stopped_at,
+ transcript_path = excluded.transcript_path,
+ final_message = excluded.final_message""",
+ (
+ repo.identity,
+ session_id,
+ agent_id,
+ agent_type,
+ now,
+ now,
+ bounded(transcript_path, 2000),
+ redact(final_message).strip(),
+ ),
+ )
+ self.conn.commit()
+ except Exception:
+ self.conn.rollback()
+ raise
+ return agent_id
+
+ def operation(
+ self,
+ repo: RepoContext,
+ session_id: str,
+ operation: str,
+ duration_ms: float,
+ success: bool,
+ *,
+ item_count: int = 0,
+ request_chars: int = 0,
+ response_chars: int = 0,
+ error: str = "",
+ ) -> None:
+ with self.conn:
+ self.conn.execute(
+ """INSERT INTO operations
+ (created_at, repo_id, session_id, operation, duration_ms,
+ success, item_count, request_chars, response_chars, error)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
+ (
+ utc_now(),
+ repo.identity,
+ session_id,
+ operation,
+ duration_ms,
+ int(success),
+ item_count,
+ request_chars,
+ response_chars,
+ bounded(error, 1000),
+ ),
+ )
+
+ def has_operation(self, repo_id: str, session_id: str, operation: str) -> bool:
+ row = self.conn.execute(
+ """SELECT 1 FROM operations
+ WHERE repo_id = ? AND session_id = ? AND operation = ?
+ LIMIT 1""",
+ (repo_id, session_id, operation),
+ ).fetchone()
+ return row is not None
+
+ def has_event(self, repo_id: str, session_id: str, kind: str) -> bool:
+ row = self.conn.execute(
+ """SELECT 1 FROM events
+ WHERE repo_id = ? AND session_id = ? AND kind = ?
+ LIMIT 1""",
+ (repo_id, session_id, kind),
+ ).fetchone()
+ return row is not None
+
+ def latest_event_payload(
+ self, repo_id: str, session_id: str, kind: str
+ ) -> dict[str, Any]:
+ row = self.conn.execute(
+ """SELECT payload_json FROM events
+ WHERE repo_id = ? AND session_id = ? AND kind = ?
+ ORDER BY id DESC LIMIT 1""",
+ (repo_id, session_id, kind),
+ ).fetchone()
+ if not row:
+ return {}
+ try:
+ payload = json.loads(row["payload_json"])
+ except json.JSONDecodeError:
+ return {}
+ return payload if isinstance(payload, dict) else {}
+
+ def setting(self, key: str, default: str = "") -> str:
+ row = self.conn.execute(
+ "SELECT value FROM settings WHERE key = ?", (key,)
+ ).fetchone()
+ return str(row["value"]) if row else default
+
+ def set_setting(self, key: str, value: str) -> None:
+ with self.conn:
+ self.conn.execute(
+ """INSERT INTO settings(key, value, updated_at)
+ VALUES (?, ?, ?)
+ ON CONFLICT(key) DO UPDATE SET
+ value = excluded.value,
+ updated_at = excluded.updated_at""",
+ (key, value, utc_now()),
+ )
+
+ def is_paused(self) -> bool:
+ return self.setting("paused", "false").lower() in {
+ "1",
+ "true",
+ "yes",
+ "on",
+ }
+
+ def forget_local_repo(self, repo_id: str) -> dict[str, int]:
+ tables = {
+ "events": "repo_id",
+ "session_scopes": "repo_id",
+ "flushes": "repo_id",
+ "retrievals": "repo_id",
+ "operations": "repo_id",
+ "sidekick_runs": "repo_id",
+ }
+ removed: dict[str, int] = {}
+ with self.conn:
+ for table, column in tables.items():
+ cursor = self.conn.execute(
+ f"DELETE FROM {table} WHERE {column} = ?", (repo_id,)
+ )
+ removed["subagent_runs" if table == "sidekick_runs" else table] = max(int(cursor.rowcount), 0)
+ return removed
+
+ def status(self, repo_id: str) -> dict[str, Any]:
+ def count(table: str) -> int:
+ return int(
+ self.conn.execute(
+ f"SELECT COUNT(*) FROM {table} WHERE repo_id = ?", (repo_id,)
+ ).fetchone()[0]
+ )
+
+ last_operation = self.conn.execute(
+ """SELECT created_at, operation, duration_ms, success, item_count, error
+ FROM operations WHERE repo_id = ? ORDER BY id DESC LIMIT 1""",
+ (repo_id,),
+ ).fetchone()
+ last_subagent = self.conn.execute(
+ """SELECT session_id, agent_id, agent_type, started_at, stopped_at,
+ context_chars
+ FROM sidekick_runs WHERE repo_id = ?
+ ORDER BY started_at DESC LIMIT 1""",
+ (repo_id,),
+ ).fetchone()
+ return {
+ "paused": self.is_paused(),
+ "events": count("events"),
+ "flushes": count("flushes"),
+ "retrievals": count("retrievals"),
+ "subagent_runs": count("sidekick_runs"),
+ "last_operation": dict(last_operation) if last_operation else None,
+ "last_subagent": dict(last_subagent) if last_subagent else None,
+ }
+
+
+def _session_id(hook_input: dict[str, Any]) -> str:
+ return str(hook_input.get("session_id") or "unknown-session")
+
+
+def record_session_start(store: EvidenceStore, hook_input: dict[str, Any]) -> None:
+ session_id = _session_id(hook_input)
+ repo = store.repo_for_session(session_id, hook_input.get("cwd"))
+ store.record_event(
+ repo,
+ session_id,
+ "session_start",
+ {
+ "source": hook_input.get("source", "startup"),
+ "model": bounded(hook_input.get("model", ""), 200),
+ "branch": repo.branch,
+ "head_sha": repo.head_sha,
+ },
+ )
+ telemetry.record(
+ "session_start",
+ repo=repo,
+ session_id=session_id,
+ trigger=bounded(str(hook_input.get("source", "startup")), 60),
+ model=bounded(hook_input.get("model", ""), 200),
+ api_key_configured=bool(api_key()),
+ is_git_repo=not repo.identity.startswith("local:"),
+ )
+
+
+def record_user_prompt(
+ store: EvidenceStore, hook_input: dict[str, Any]
+) -> tuple[RepoContext, str, str, bool]:
+ session_id = _session_id(hook_input)
+ repo = store.repo_for_session(session_id, hook_input.get("cwd"))
+ prompt = redact(hook_input.get("prompt", "")).strip()
+ is_first_prompt = not store.has_event(repo.identity, session_id, "user_prompt")
+ store.record_event(repo, session_id, "user_prompt", {"text": prompt})
+ return repo, session_id, prompt, is_first_prompt
+
+
+def _tool_result_preview(response: Any) -> str:
+ if isinstance(response, dict):
+ selected = {}
+ for key in (
+ "stdout",
+ "stderr",
+ "output",
+ "content",
+ "error",
+ "filePath",
+ "success",
+ "interrupted",
+ ):
+ if key in response:
+ selected[key] = response[key]
+ response = selected or {"keys": sorted(response.keys())[:20]}
+ return bounded(response, MAX_RESULT_CHARS)
+
+
+def tool_payload(hook_input: dict[str, Any], *, failed: bool | None = False) -> dict[str, Any]:
+ name = str(hook_input.get("tool_name") or "unknown")
+ tool_input = hook_input.get("tool_input") or {}
+ if not isinstance(tool_input, dict):
+ tool_input = {}
+ payload: dict[str, Any] = {
+ "tool": name,
+ "failed": failed,
+ "duration_ms": hook_input.get("duration_ms"),
+ "agent_role": "subagent" if hook_input.get("agent_id") else "main",
+ }
+ if hook_input.get("agent_id"):
+ payload["agent_id"] = bounded(hook_input["agent_id"], 200)
+ if hook_input.get("agent_type"):
+ payload["agent_type"] = bounded(hook_input["agent_type"], 200)
+
+ if name in {"Read", "Write", "Edit", "MultiEdit", "NotebookEdit"}:
+ path = tool_input.get("file_path") or tool_input.get("notebook_path")
+ if path:
+ payload["path"] = bounded(path, 1000)
+ if name in {"Write", "Edit", "MultiEdit", "NotebookEdit"}:
+ payload["mutation_chars"] = sum(
+ len(str(tool_input.get(key, "")))
+ for key in ("content", "new_string", "new_source", "edits")
+ )
+ elif name == "Bash" or "command" in tool_input:
+ command = bounded(tool_input.get("command", ""), MAX_COMMAND_CHARS)
+ payload["command"] = command
+ payload["command_kind"] = (
+ "test"
+ if TEST_COMMAND_RE.search(command)
+ else "build"
+ if BUILD_COMMAND_RE.search(command)
+ else "shell"
+ )
+ response = (
+ hook_input.get("error") if failed else hook_input.get("tool_response")
+ )
+ payload["result_preview"] = _tool_result_preview(response)
+ elif name in {"Grep", "Glob", "WebSearch", "WebFetch"}:
+ for key in ("pattern", "path", "query", "url"):
+ if tool_input.get(key):
+ payload[key] = bounded(tool_input[key], 1000)
+ else:
+ payload["input_keys"] = sorted(tool_input.keys())[:20]
+ if failed:
+ payload["error"] = bounded(hook_input.get("error", ""), MAX_RESULT_CHARS)
+
+ if failed and "error" not in payload:
+ payload["error"] = bounded(hook_input.get("error", ""), MAX_RESULT_CHARS)
+ return payload
+
+
+def record_tool(
+ store: EvidenceStore, hook_input: dict[str, Any], *, failed: bool | None = False
+) -> None:
+ session_id = _session_id(hook_input)
+ repo = store.repo_for_session(session_id, hook_input.get("cwd"))
+ payload = tool_payload(hook_input, failed=failed)
+ if payload.get("path"):
+ payload["repo_path"] = _repo_relative_path(repo, str(payload["path"]))
+ store.record_event(
+ repo,
+ session_id,
+ "tool_failure" if failed else "tool_result",
+ payload,
+ )
+
+
+def record_subagent_start(
+ store: EvidenceStore, hook_input: dict[str, Any]
+) -> str:
+ """Record a native subagent and reuse the main turn's retrieved memories."""
+ session_id = _session_id(hook_input)
+ repo = store.repo_for_session(session_id, hook_input.get("cwd"))
+ agent_id = bounded(hook_input.get("agent_id", "unknown-agent"), 200)
+ agent_type = bounded(hook_input.get("agent_type", "unknown-agent"), 200)
+ context = combine_context(
+ format_context(store.injected_memories(session_id, repo.identity))
+ )
+ first_start = store.start_subagent(
+ repo, session_id, agent_id, agent_type, len(context)
+ )
+ store.record_event(
+ repo,
+ session_id,
+ "subagent_start",
+ {
+ "agent_id": agent_id,
+ "agent_type": agent_type,
+ "context_chars": len(context) if first_start else 0,
+ "repo_root": bounded(repo.root, 2000),
+ },
+ )
+ telemetry.record(
+ "subagent",
+ repo=repo,
+ session_id=session_id,
+ phase="start",
+ first_start=first_start,
+ context_chars=len(context) if first_start else 0,
+ )
+ return context if first_start else ""
+
+
+def record_subagent_stop(store: EvidenceStore, hook_input: dict[str, Any]) -> None:
+ session_id = _session_id(hook_input)
+ repo = store.repo_for_session(session_id, hook_input.get("cwd"))
+ agent_type = bounded(hook_input.get("agent_type", "unknown-agent"), 200)
+ agent_id = bounded(hook_input.get("agent_id", ""), 200)
+ final_message = redact(hook_input.get("last_assistant_message", "")).strip()
+ transcript_path = bounded(hook_input.get("agent_transcript_path", ""), 2000)
+ agent_id = store.stop_subagent(
+ repo,
+ session_id,
+ agent_id,
+ agent_type,
+ transcript_path,
+ final_message,
+ )
+ store.record_event(
+ repo,
+ session_id,
+ "subagent_stop",
+ {
+ "agent_id": agent_id,
+ "agent_type": agent_type,
+ "transcript_path": transcript_path,
+ "final_message": final_message,
+ },
+ )
+ telemetry.record(
+ "subagent",
+ repo=repo,
+ session_id=session_id,
+ phase="stop",
+ has_transcript=bool(transcript_path),
+ message_chars=len(final_message),
+ )
+
+
+def _ordered_unique(values: Iterable[str]) -> list[str]:
+ seen: set[str] = set()
+ result = []
+ for value in values:
+ if value and value not in seen:
+ seen.add(value)
+ result.append(value)
+ return result
+
+
+def _repo_relative_path(repo: RepoContext, value: str) -> str:
+ value = str(value or "").strip()
+ if not value:
+ return ""
+ try:
+ path = Path(value)
+ if path.is_absolute():
+ try:
+ return path.resolve().relative_to(Path(repo.root).resolve()).as_posix()
+ except ValueError:
+ return ""
+ except (OSError, ValueError):
+ pass
+ return bounded(value, 1000)
+
+
+def _render_command_lines(commands: list[dict[str, str]]) -> list[str]:
+ lines = []
+ for command in commands:
+ line = f"- [{command['status']}/{command['kind']}] {command['command']}"
+ if command["result"]:
+ line += f" โ {bounded(command['result'], 500).replace(chr(10), ' ')}"
+ lines.append(line)
+ return lines
+
+
+def build_episode(
+ repo: RepoContext,
+ session_id: str,
+ packet_id: str,
+ events: list[dict[str, Any]],
+ *,
+ canonical_task: str = "",
+ task_outcome: str = "",
+) -> tuple[str, dict[str, Any]]:
+ prompts = [
+ redact(e["payload"].get("text", "")).strip()
+ for e in events
+ if e["kind"] == "user_prompt" and e["payload"].get("text")
+ ]
+ assistant_conclusions = [
+ redact(e["payload"].get("text", "")).strip()
+ for e in events
+ if e["kind"] == "assistant_stop" and e["payload"].get("text")
+ ]
+ subagent_outcomes = [
+ redact(e["payload"].get("final_message", "")).strip()
+ for e in events
+ if e["kind"] in {"subagent_stop", "sidekick_stop"} and e["payload"].get("final_message")
+ ]
+ tools = [
+ e["payload"] for e in events if e["kind"] in {"tool_result", "tool_failure"}
+ and e["payload"].get("agent_role", "main") == "main"
+ ]
+ read_paths = _ordered_unique(
+ _repo_relative_path(repo, str(t.get("repo_path") or t.get("path", "")))
+ for t in tools
+ if t.get("tool") == "Read"
+ )
+ modified_paths = _ordered_unique(
+ _repo_relative_path(repo, str(t.get("repo_path") or t.get("path", "")))
+ for t in tools
+ if t.get("tool") in {"Write", "Edit", "MultiEdit", "NotebookEdit"}
+ )
+ searches = [
+ {key: t[key] for key in ("tool", "pattern", "path", "query", "url") if key in t}
+ for t in tools
+ if t.get("tool") in {"Grep", "Glob", "WebSearch", "WebFetch"}
+ ]
+ commands = [
+ {
+ "command": t.get("command", ""),
+ "kind": t.get("command_kind", "shell"),
+ "status": "unknown" if t.get("failed", False) is None else "failed" if t.get("failed") else "succeeded",
+ "result": t.get("result_preview", ""),
+ }
+ for t in tools
+ if t.get("command")
+ ]
+
+ task = bounded(canonical_task or (prompts[0] if prompts else ""), 4000)
+ conclusion = redact(assistant_conclusions[-1] if assistant_conclusions else "").strip()
+ outcome = bounded(task_outcome, 2000)
+
+ extraction_messages: list[dict[str, str]] = []
+ pending_user_messages: list[dict[str, str]] = []
+ if task and not prompts:
+ pending_user_messages.append({"role": "user", "content": task})
+ for event in events:
+ if event["kind"] == "user_prompt" and event["payload"].get("text"):
+ pending_user_messages.append(
+ {
+ "role": "user",
+ "content": redact(event["payload"].get("text", "")).strip(),
+ }
+ )
+ elif event["kind"] == "assistant_stop":
+ transcript_messages = event["payload"].get("transcript_messages") or []
+ if isinstance(transcript_messages, list) and transcript_messages:
+ transcript_users = {
+ redact(message.get("content") or "").strip()
+ for message in transcript_messages
+ if isinstance(message, dict) and message.get("role") == "user"
+ }
+ extraction_messages.extend(
+ message
+ for message in pending_user_messages
+ if message["content"].strip() not in transcript_users
+ )
+ extraction_messages.extend(
+ {
+ "role": str(message.get("role") or ""),
+ "content": redact(message.get("content") or "").strip(),
+ }
+ for message in transcript_messages
+ if isinstance(message, dict)
+ and message.get("role") in {"user", "assistant"}
+ and message.get("content")
+ )
+ else:
+ extraction_messages.extend(pending_user_messages)
+ if event["payload"].get("text"):
+ extraction_messages.append(
+ {
+ "role": "assistant",
+ "content": redact(event["payload"].get("text", "")).strip(),
+ }
+ )
+ pending_user_messages = []
+ elif event["kind"] in {"subagent_stop", "sidekick_stop"}:
+ pass
+ extraction_messages.extend(pending_user_messages)
+
+ structured = {
+ "packet_id": packet_id,
+ "repo": repo.identity,
+ "app_id": repo.app_id,
+ "session_id": session_id,
+ "branch": repo.branch,
+ "head_sha": repo.head_sha,
+ "task": task,
+ "task_outcome": outcome,
+ "assistant_conclusion": conclusion,
+ "user_messages": prompts,
+ "assistant_outcomes": assistant_conclusions,
+ "subagent_outcomes": subagent_outcomes,
+ "extraction_messages": extraction_messages,
+ "files_read": read_paths[:50],
+ "files_modified": modified_paths[:50],
+ "searches": searches[-30:],
+ "commands": commands[-30:],
+ }
+ lines = ["Coding-session episode"]
+ if task:
+ lines.extend(["", "Task:", task])
+ if modified_paths:
+ lines.extend(
+ ["", "Files modified:", *[f"- {path}" for path in modified_paths[:50]]]
+ )
+ if read_paths:
+ lines.extend(["", "Files read:", *[f"- {path}" for path in read_paths[:50]]])
+ if commands:
+ lines.append("")
+ lines.append("Observed commands:")
+ lines.extend(_render_command_lines(commands[-30:]))
+ if searches:
+ lines.extend(
+ [
+ "",
+ "Observed searches:",
+ *[
+ f"- {json.dumps(item, ensure_ascii=False, sort_keys=True)}"
+ for item in searches[-20:]
+ ],
+ ]
+ )
+ if conclusion:
+ lines.extend(["", "Agent conclusion:", conclusion])
+ if outcome:
+ lines.extend(["", "Task outcome:", outcome])
+ lines.extend(
+ [
+ "",
+ f"Provenance: repo={repo.identity}; branch={repo.branch}; head={repo.head_sha}; packet={packet_id}",
+ ]
+ )
+ content = "\n".join(lines)
+ return bounded(content, MAX_EPISODE_CHARS), structured
+
+
+def build_semantic_evidence(structured: dict[str, Any]) -> str:
+ """Format changed paths for memory extraction.
+
+ Test and build results remain in the local evidence store for diagnostics,
+ but are not useful repository knowledge by default and should not steer
+ memory extraction toward transient verification details.
+ """
+ modified_paths = [
+ bounded(path, 500) for path in structured.get("files_modified", [])[:20]
+ ]
+ commands = structured.get("commands") or []
+ if not any(command.get("status") == "failed" for command in commands):
+ commands = []
+
+ if not modified_paths and not commands:
+ return ""
+
+ lines = ["Additional repository details from this session"]
+ if modified_paths:
+ lines.extend(
+ [
+ "",
+ "Changed paths:",
+ *[f"- {path}" for path in modified_paths],
+ ]
+ )
+ if commands:
+ lines.extend(["", "Commands run in this session:", *_render_command_lines(commands)])
+ return bounded("\n".join(lines), 8000)
+
+
+def build_extraction_messages(structured: dict[str, Any]) -> list[dict[str, str]]:
+ """Build the session messages sent to Mem0 for memory extraction."""
+ evidence = build_semantic_evidence(structured)
+ messages = [
+ {"role": message["role"], "content": redact(message["content"]).strip()}
+ for message in structured.get("extraction_messages", [])
+ if message.get("role") in {"user", "assistant"} and message.get("content")
+ ]
+ if evidence:
+ for message in reversed(messages):
+ if message["role"] == "assistant":
+ message["content"] = f"{message['content']}\n\n{evidence}"
+ break
+ else:
+ messages.append({"role": "assistant", "content": evidence})
+
+ return messages
+
+
+def _estimated_tokens(value: str) -> int:
+ """Conservatively estimate tokens without adding a tokenizer dependency."""
+ ascii_chars = sum(ord(char) < 128 for char in value)
+ return math.ceil((ascii_chars * 0.4) + (len(value) - ascii_chars))
+
+
+def _message_tokens(messages: list[dict[str, str]]) -> int:
+ return _estimated_tokens(json.dumps(messages, ensure_ascii=False))
+
+
+def _is_agent_assignment(message: dict[str, str]) -> bool:
+ return message.get("role") == "assistant" and message.get(
+ "content", ""
+ ).startswith("Subagent assignment (")
+
+
+def _is_agent_response(message: dict[str, str]) -> bool:
+ return message.get("role") == "assistant" and message.get(
+ "content", ""
+ ).startswith("Subagent response (")
+
+
+def extraction_message_batches(
+ messages: list[dict[str, str]],
+ *,
+ max_tokens: int = MAX_EXTRACTION_INPUT_TOKENS,
+) -> list[list[dict[str, str]]]:
+ """Keep exchanges together when possible; split oversized messages to enforce the request budget."""
+ if not messages or _message_tokens(messages) <= max_tokens:
+ return [messages]
+
+ exchanges: list[list[dict[str, str]]] = []
+ exchange: list[dict[str, str]] = []
+ for message in messages:
+ if message.get("role") == "user" and exchange:
+ exchanges.append(exchange)
+ exchange = []
+ exchange.append(message)
+ if exchange:
+ exchanges.append(exchange)
+
+ units: list[list[dict[str, str]]] = []
+ for exchange in exchanges:
+ if _message_tokens(exchange) <= max_tokens:
+ units.append(exchange)
+ continue
+ index = 0
+ while index < len(exchange):
+ message = exchange[index]
+ if (
+ _is_agent_assignment(message)
+ and index + 1 < len(exchange)
+ and _is_agent_response(exchange[index + 1])
+ ):
+ units.append(exchange[index : index + 2])
+ index += 2
+ else:
+ units.append([message])
+ index += 1
+
+ bounded_units: list[list[dict[str, str]]] = []
+ for unit in units:
+ if _message_tokens(unit) <= max_tokens:
+ bounded_units.append(unit)
+ continue
+ for message in unit:
+ remaining = message["content"]
+ while remaining:
+ low, high = 0, len(remaining)
+ while low < high:
+ middle = (low + high + 1) // 2
+ if _message_tokens([{**message, "content": remaining[:middle]}]) <= max_tokens:
+ low = middle
+ else:
+ high = middle - 1
+ if low == 0:
+ raise ValueError("Extraction token budget cannot fit a message")
+ bounded_units.append([{**message, "content": remaining[:low]}])
+ remaining = remaining[low:]
+
+ batches: list[list[dict[str, str]]] = []
+ batch: list[dict[str, str]] = []
+ for unit in bounded_units:
+ candidate = [*batch, *unit]
+ if batch and _message_tokens(candidate) > max_tokens:
+ batches.append(batch)
+ batch = list(unit)
+ else:
+ batch = candidate
+ if batch:
+ batches.append(batch)
+ return batches
+
+
+# Platform surface attribution. Read from the generated per-host module so a new
+# entrypoint is correct without remembering to configure anything.
+try: # pragma: no cover - absent only in the un-built shared source tree
+ from _harness_id import PLATFORM_APPLICATION as _PLATFORM_APPLICATION
+ from _harness_id import PLATFORM_SOURCE as _PLATFORM_SOURCE
+except ImportError:
+ _PLATFORM_SOURCE = "MEM0_PLUGIN"
+ _PLATFORM_APPLICATION = ""
+
+
+def platform_headers(key: str) -> dict[str, str]:
+ """Auth plus the three surface-identity headers.
+
+ X-Mem0-Source and X-Application are set-once by contract: this is the
+ outermost layer, so it sets them, and nothing below may overwrite them.
+ X-Mem0-Client is append-only โ anything downstream adds itself to the tail.
+ """
+ headers = {
+ "Authorization": f"Token {key}",
+ "Content-Type": "application/json",
+ "X-Mem0-Source": _PLATFORM_SOURCE,
+ "X-Mem0-Client": f"mem0-plugin/{PLUGIN_VERSION}",
+ }
+ if _PLATFORM_APPLICATION:
+ headers["X-Application"] = _PLATFORM_APPLICATION
+ return headers
+
+
+def _request_json(
+ url: str, key: str, payload: dict[str, Any], timeout: float
+) -> tuple[dict[str, Any] | list[Any], int, int]:
+ raw = json.dumps(payload, ensure_ascii=False).encode()
+ request = urllib.request.Request(
+ url,
+ data=raw,
+ headers=platform_headers(key),
+ method="POST",
+ )
+ with urllib.request.urlopen(request, timeout=timeout) as response:
+ response_raw = response.read()
+ parsed = json.loads(response_raw or b"{}")
+ return parsed, len(raw), len(response_raw)
+
+
+def _request_json_with_network_retry(
+ url: str, key: str, payload: dict[str, Any], timeout: float
+) -> tuple[dict[str, Any] | list[Any], int, int]:
+ """Retry one transient connection failure without retrying API responses."""
+ try:
+ return _request_json(url, key, payload, timeout)
+ except urllib.error.HTTPError:
+ raise
+ except (urllib.error.URLError, TimeoutError, OSError):
+ time.sleep(0.25)
+ return _request_json(url, key, payload, timeout)
+
+
+def _get_json(
+ url: str, key: str, timeout: float
+) -> tuple[dict[str, Any] | list[Any], int]:
+ request = urllib.request.Request(
+ url,
+ headers=platform_headers(key),
+ method="GET",
+ )
+ with urllib.request.urlopen(request, timeout=timeout) as response:
+ response_raw = response.read()
+ return json.loads(response_raw or b"{}"), len(response_raw)
+
+
+def _event_id(response: dict[str, Any] | list[Any]) -> str:
+ return str(response.get("event_id", "")) if isinstance(response, dict) else ""
+
+
+def _stored_event_ids(value: Any) -> list[str]:
+ raw = str(value or "")
+ if not raw.startswith("["):
+ return []
+ try:
+ parsed = json.loads(raw)
+ except json.JSONDecodeError:
+ return []
+ return [str(item or "") for item in parsed] if isinstance(parsed, list) else []
+
+
+def _result_count(response: dict[str, Any] | list[Any]) -> int:
+ if isinstance(response, dict):
+ results = response.get("results")
+ return len(results) if isinstance(results, list) else 0
+ return len(response) if isinstance(response, list) else 0
+
+
+def touch_handoff_heartbeat() -> None:
+ """Mark the worker's handoff file alive so recovery does not relaunch it."""
+ path = os.environ.get("MEM0_CODE_HANDOFF_PATH", "")
+ if not path:
+ return
+ try:
+ os.utime(path)
+ except OSError:
+ pass
+
+
+def _wait_for_event(api_url: str, key: str, event_id: str) -> tuple[str, int, int]:
+ """Wait for extraction to finish before a later task can search the store."""
+ if not event_id:
+ return "MISSING", 0, 0
+ wait_seconds = float(os.environ.get("MEM0_CODE_EXTRACTION_WAIT_SECONDS", "120"))
+ poll_seconds = max(float(os.environ.get("MEM0_CODE_EVENT_POLL_SECONDS", "1")), 0.1)
+ deadline = time.monotonic() + wait_seconds
+ response_chars = 0
+ while time.monotonic() < deadline:
+ touch_handoff_heartbeat()
+ try:
+ response, size = _get_json(
+ f"{api_url}/v1/event/{event_id}/",
+ key,
+ min(10, poll_seconds + 5),
+ )
+ except urllib.error.HTTPError as exc:
+ if exc.code not in {408, 429} and exc.code < 500:
+ raise
+ time.sleep(poll_seconds)
+ continue
+ except (urllib.error.URLError, TimeoutError, OSError):
+ # The extraction job is durable server-side. A transient polling
+ # failure must not discard a job that may still complete normally.
+ time.sleep(poll_seconds)
+ continue
+ response_chars += size
+ status = (
+ str(response.get("status", "UNKNOWN"))
+ if isinstance(response, dict)
+ else "UNKNOWN"
+ )
+ if status in {"SUCCEEDED", "FAILED"}:
+ return status, response_chars, _result_count(response)
+ time.sleep(poll_seconds)
+ return "TIMEOUT", response_chars, 0
+
+
+def _record_flush(
+ repo: RepoContext,
+ session_id: str,
+ reason: str,
+ status: str,
+ elapsed: float,
+ **extra: Any,
+) -> None:
+ telemetry.record(
+ "flush",
+ repo=repo,
+ session_id=session_id,
+ reason=reason,
+ status=status,
+ success=status in {"semantic-succeeded", "nothing-to-flush"},
+ duration_ms=round(elapsed, 2),
+ **extra,
+ )
+
+
+def flush_session(
+ store: EvidenceStore, hook_input: dict[str, Any], reason: str
+) -> dict[str, Any]:
+ key = api_key()
+ if not key:
+ telemetry.record("flush", reason=reason, status="local-only", success=False)
+ return {"status": "local-only", "reason": "no-api-key"}
+
+ session_id = _session_id(hook_input)
+ if session_id == "unknown-session":
+ telemetry.record("flush", reason=reason, status="no-session-id", success=False)
+ return {"status": "error", "reason": "no-session-id"}
+ repo = store.repo_for_session(session_id, hook_input.get("cwd"))
+ prepared = store.prepare_flush(repo, session_id, reason)
+ if prepared is None:
+ return {"status": "nothing-to-flush"}
+ packet_id, events = prepared
+ existing_flush = store.flush_record(packet_id) or {}
+
+ _, structured = build_episode(
+ repo,
+ session_id,
+ packet_id,
+ events,
+ canonical_task=bounded(hook_input.get("task", ""), 4000),
+ task_outcome=bounded(hook_input.get("task_outcome", ""), 2000),
+ )
+
+ metadata = {"source": _harness_source_tag}
+ if repo.branch and repo.branch not in {"detached", "unknown"}:
+ metadata["branch"] = repo.branch
+ if repo.head_sha:
+ metadata["git_sha"] = repo.head_sha
+ api_url = os.environ.get("MEM0_API_URL", DEFAULT_API_URL).rstrip("/")
+ add_url = f"{api_url}/v3/memories/add/"
+
+ write_user = _scope_value(user_id())
+ write_project = _scope_value(repo.project_id)
+ if not write_user or not _scope_value(repo.app_id) or not write_project:
+ telemetry.record("flush", reason=reason, status="unscoped", success=False)
+ return {"status": "error", "reason": "wildcard-scope"}
+
+ body = {
+ "agent_id": write_project,
+ "user_id": write_user,
+ "app_id": repo.app_id,
+ "run_id": session_id,
+ # Top level, not metadata: the backend reads `source` from the body or
+ # the query string, never from metadata, which is where this used to
+ # sit. The X-Mem0-Source header is also read, but only from the
+ # platform release that ships alongside this change, so the body value
+ # is what makes attribution work on both. The harness tag stays in
+ # metadata as hook provenance.
+ "source": _PLATFORM_SOURCE,
+ "metadata": {**metadata, "author": write_user, "dirs": directory_chain(repo)},
+ "agent_custom_instructions": PROJECT_MEMORY_INSTRUCTIONS,
+ "custom_instructions": PERSONAL_MEMORY_INSTRUCTIONS,
+ "custom_categories": CODING_MEMORY_CATEGORIES,
+ "infer": True,
+ }
+
+ started = time.perf_counter()
+ try:
+ stored_events = _stored_event_ids(existing_flush.get("semantic_event_id"))
+ existing_event = (
+ "" if stored_events else str(existing_flush.get("semantic_event_id") or "")
+ )
+ if existing_event:
+ existing_status, existing_resp, existing_items = _wait_for_event(
+ api_url, key, existing_event
+ )
+ if existing_status == "SUCCEEDED":
+ elapsed = (time.perf_counter() - started) * 1000
+ store.update_flush(
+ packet_id,
+ status="semantic-succeeded",
+ semantic_event_id=existing_event,
+ error="",
+ )
+ store.operation(
+ repo,
+ session_id,
+ "flush-retry",
+ elapsed,
+ True,
+ item_count=existing_items,
+ response_chars=existing_resp,
+ )
+ _record_flush(
+ repo,
+ session_id,
+ reason,
+ "semantic-succeeded",
+ elapsed,
+ memory_count=existing_items,
+ resumed=True,
+ )
+ effective_reason = str(
+ (store.flush_record(packet_id) or {}).get("reason") or reason
+ )
+ if (
+ store.has_unflushed_events(repo.identity, session_id)
+ and not store.unflushed_starts_with_session_start(
+ repo.identity, session_id
+ )
+ and (
+ effective_reason != "periodic"
+ or store.checkpoint_due(repo.identity, session_id)
+ )
+ ):
+ return flush_session(store, hook_input, effective_reason)
+ return {
+ "status": "semantic-succeeded",
+ "packet_id": packet_id,
+ "semantic_event_id": existing_event,
+ "semantic_status": existing_status,
+ "memory_count": existing_items,
+ "duration_ms": round(elapsed, 2),
+ "resumed": True,
+ }
+ if existing_status == "TIMEOUT":
+ elapsed = (time.perf_counter() - started) * 1000
+ error = "semantic extraction event timed out"
+ store.update_flush(packet_id, status="semantic-timeout", error=error)
+ store.operation(
+ repo,
+ session_id,
+ "flush-retry",
+ elapsed,
+ False,
+ response_chars=existing_resp,
+ error=error,
+ )
+ _record_flush(
+ repo,
+ session_id,
+ reason,
+ "semantic-timeout",
+ elapsed,
+ resumed=True,
+ error_kind="timeout",
+ )
+ return {
+ "status": "semantic-timeout",
+ "packet_id": packet_id,
+ "semantic_event_id": existing_event,
+ "duration_ms": round(elapsed, 2),
+ "resumed": True,
+ }
+
+ message_batches = [
+ batch
+ for batch in extraction_message_batches(
+ build_extraction_messages(structured)
+ )
+ if batch
+ ]
+ batches = [(body, messages) for messages in message_batches]
+ if not batches:
+ store.update_flush(packet_id, status="semantic-succeeded", error="")
+ return {"status": "nothing-to-flush", "packet_id": packet_id}
+ operation_name = "flush-retry" if stored_events else "flush"
+ semantic_events = stored_events[: len(batches)]
+ semantic_events += [""] * (len(batches) - len(semantic_events))
+ semantic_req = 0
+ semantic_resp = 0
+ for index, (body, messages) in enumerate(batches):
+ if semantic_events[index]:
+ continue
+ semantic_response, request_chars, response_chars = _request_json(
+ add_url,
+ key,
+ {**body, "messages": messages},
+ 15,
+ )
+ semantic_events[index] = _event_id(semantic_response)
+ semantic_req += request_chars
+ semantic_resp += response_chars
+ store.update_flush(
+ packet_id,
+ status="semantic-queued",
+ semantic_event_id=json.dumps(semantic_events),
+ )
+
+ semantic_event = semantic_events[-1]
+ semantic_status = "SUCCEEDED"
+ event_resp = 0
+ semantic_items = 0
+ failed_event = semantic_event
+ for index, queued_event in enumerate(semantic_events):
+ status, response_chars, item_count = _wait_for_event(
+ api_url, key, queued_event
+ )
+ event_resp += response_chars
+ semantic_items += item_count
+ if status != "SUCCEEDED":
+ semantic_status = status
+ failed_event = queued_event
+ if status in {"FAILED", "MISSING"}:
+ semantic_events[index] = ""
+ store.update_flush(
+ packet_id, semantic_event_id=json.dumps(semantic_events)
+ )
+ break
+ if semantic_status != "SUCCEEDED":
+ elapsed = (time.perf_counter() - started) * 1000
+ error = f"semantic extraction event {semantic_status.lower()}"
+ store.update_flush(
+ packet_id, status=f"semantic-{semantic_status.lower()}", error=error
+ )
+ store.operation(
+ repo,
+ session_id,
+ operation_name,
+ elapsed,
+ False,
+ item_count=semantic_items,
+ request_chars=semantic_req,
+ response_chars=semantic_resp + event_resp,
+ error=error,
+ )
+ _record_flush(
+ repo,
+ session_id,
+ reason,
+ f"semantic-{semantic_status.lower()}",
+ elapsed,
+ memory_count=semantic_items,
+ batch_count=len(batches),
+ error_kind=telemetry.error_kind(error),
+ )
+ return {
+ "status": f"semantic-{semantic_status.lower()}",
+ "packet_id": packet_id,
+ "semantic_event_id": failed_event,
+ "memory_count": semantic_items,
+ "duration_ms": round(elapsed, 2),
+ }
+
+ elapsed = (time.perf_counter() - started) * 1000
+ store.update_flush(
+ packet_id,
+ status="semantic-succeeded",
+ semantic_event_id=json.dumps(semantic_events),
+ error="",
+ )
+ store.operation(
+ repo,
+ session_id,
+ operation_name,
+ elapsed,
+ True,
+ item_count=semantic_items,
+ request_chars=semantic_req,
+ response_chars=semantic_resp + event_resp,
+ )
+ _record_flush(
+ repo,
+ session_id,
+ reason,
+ "semantic-succeeded",
+ elapsed,
+ memory_count=semantic_items,
+ batch_count=len(batches),
+ request_chars=semantic_req,
+ )
+ effective_reason = str(
+ (store.flush_record(packet_id) or {}).get("reason") or reason
+ )
+ if (
+ store.has_unflushed_events(repo.identity, session_id)
+ and not store.unflushed_starts_with_session_start(
+ repo.identity, session_id
+ )
+ and (
+ effective_reason != "periodic"
+ or store.checkpoint_due(repo.identity, session_id)
+ )
+ ):
+ return flush_session(store, hook_input, effective_reason)
+ return {
+ "status": "semantic-succeeded",
+ "packet_id": packet_id,
+ "semantic_event_id": semantic_event,
+ "semantic_status": semantic_status,
+ "memory_count": semantic_items,
+ "duration_ms": round(elapsed, 2),
+ }
+ except Exception as exc: # hooks must fail open
+ elapsed = (time.perf_counter() - started) * 1000
+ error = bounded(str(exc), 1000)
+ store.update_flush(packet_id, status="error", error=error)
+ store.operation(repo, session_id, "flush", elapsed, False, error=error)
+ _record_flush(
+ repo,
+ session_id,
+ reason,
+ "error",
+ elapsed,
+ error_kind=telemetry.error_kind(exc),
+ )
+ return {"status": "error", "packet_id": packet_id, "error": error}
+
+
+def checkpoint_session(
+ store: EvidenceStore, hook_input: dict[str, Any], reason: str
+) -> dict[str, Any]:
+ """Run remote extraction at a durable boundary."""
+ return flush_session(store, hook_input, reason)
+
+
+
+def search_memories(
+ store: EvidenceStore | None,
+ repo: RepoContext,
+ session_id: str | None,
+ query: str,
+ *,
+ top_k: int | None = None,
+ category: str | None = None,
+ scope: str | None = None,
+ run_id: str | None = None,
+ operation: str = "search",
+ timeout: float = 5,
+) -> MemorySearchResult:
+ key = api_key()
+ if not key or not query.strip():
+ return MemorySearchResult(False, 0, 0, [])
+ search_once = os.environ.get(
+ "MEM0_CODE_SEARCH_ONCE_PER_SESSION", "false"
+ ).lower() in {
+ "1",
+ "true",
+ "yes",
+ "on",
+ }
+ track_session = store is not None and bool(session_id)
+ if (
+ search_once
+ and track_session
+ and store.has_operation(repo.identity, session_id, "search")
+ ):
+ return MemorySearchResult(False, 0, 0, [])
+
+ result_limit = min(
+ max(
+ top_k
+ if top_k is not None
+ else _int_option("top_k", "MEM0_CODE_TOP_K", 3),
+ 1,
+ ),
+ 20,
+ )
+ if category is not None and category not in CODING_MEMORY_CATEGORY_NAMES:
+ raise ValueError(f"Unknown memory category: {category}")
+ user, project = _scope_value(user_id()), _scope_value(repo.project_id)
+ if not user or not project or not _scope_value(repo.app_id):
+ return MemorySearchResult(False, 0, 0, [])
+ filters = _search_filters(user, repo, resolve_search_scope(scope))
+ if category:
+ filters = {"AND": [filters, {"categories": {"contains": category}}]}
+ if run_id:
+ filters = {"AND": [filters, {"run_id": run_id}]}
+ payload = {
+ "query": query,
+ "app_id": repo.app_id,
+ "filters": filters,
+ "top_k": result_limit,
+ "rerank": False,
+ "latest_only": True,
+ }
+ url = (
+ os.environ.get("MEM0_API_URL", DEFAULT_API_URL).rstrip("/")
+ + "/v3/memories/search/"
+ )
+ started = time.perf_counter()
+ try:
+ response, request_chars, response_chars = _request_json_with_network_retry(
+ url, key, payload, timeout
+ )
+ memories = (
+ response if isinstance(response, list) else response.get("results", [])
+ )
+ memories = [
+ memory
+ for memory in memories
+ if isinstance(memory, dict)
+ and (memory.get("metadata") or {}).get("record_kind") != "task_episode"
+ ][:result_limit]
+ if track_session:
+ returned_memories = store.unseen(session_id, repo.identity, memories)
+ store.mark_injected(session_id, repo.identity, returned_memories)
+ already_shown_count = len(memories) - len(returned_memories)
+ else:
+ returned_memories = memories
+ already_shown_count = 0
+ elapsed = (time.perf_counter() - started) * 1000
+ if track_session:
+ store.operation(
+ repo,
+ session_id,
+ operation,
+ elapsed,
+ True,
+ item_count=len(returned_memories),
+ request_chars=request_chars,
+ response_chars=response_chars,
+ )
+ telemetry.record(
+ "search",
+ repo=repo,
+ session_id=session_id,
+ trigger=operation,
+ success=True,
+ duration_ms=round(elapsed, 2),
+ matched_count=len(memories),
+ returned_count=len(returned_memories),
+ already_shown_count=already_shown_count,
+ top_k=result_limit,
+ has_category=bool(category),
+ )
+ return MemorySearchResult(
+ succeeded=True,
+ matched_count=len(memories),
+ already_shown_count=already_shown_count,
+ memories=returned_memories,
+ )
+ except Exception as exc:
+ elapsed = (time.perf_counter() - started) * 1000
+ if track_session:
+ store.operation(repo, session_id, operation, elapsed, False, error=str(exc))
+ telemetry.record(
+ "search",
+ repo=repo,
+ session_id=session_id,
+ trigger=operation,
+ success=False,
+ duration_ms=round(elapsed, 2),
+ top_k=result_limit,
+ has_category=bool(category),
+ error_kind=telemetry.error_kind(exc),
+ )
+ return MemorySearchResult(False, 0, 0, [])
+
+
+def format_context(
+ memories: list[dict[str, Any]],
+ heading: str = "Relevant repository memories:",
+) -> str:
+ if not memories:
+ return ""
+ limit = min(
+ max(
+ _int_option(
+ "max_context_chars",
+ "MEM0_CODE_MAX_CONTEXT_CHARS",
+ DEFAULT_MAX_CONTEXT_CHARS,
+ ),
+ 1000,
+ ),
+ 10000,
+ )
+ lines = [heading] if heading else []
+ for memory in memories:
+ text = re.sub(
+ r"\s+",
+ " ",
+ redact(memory.get("memory") or memory.get("text") or ""),
+ )
+ text = text.strip()
+ if not text:
+ continue
+ branch = str((memory.get("metadata") or {}).get("branch") or "").strip()
+ branch_label = (
+ f" [learnt on branch {branch}]"
+ if branch.casefold() not in {"", "main", "master", "unknown", "detached"}
+ else ""
+ )
+ number = len(lines) if heading else len(lines) + 1
+ entry = f"{number}. {text}{branch_label}"
+ candidate = "\n".join([*lines, entry])
+ if len(candidate) <= limit:
+ lines.append(entry)
+ continue
+ if not lines or (heading and len(lines) == 1):
+ prefix = f"{number}. "
+ suffix = f"โฆ{branch_label}"
+ available = (
+ limit
+ - len("\n".join(lines))
+ - (1 if lines else 0)
+ - len(prefix)
+ - len(suffix)
+ )
+ if available > 0:
+ lines.append(prefix + text[:available].rstrip() + suffix)
+ break
+ minimum_lines = 2 if heading else 1
+ return "\n".join(lines) if len(lines) >= minimum_lines else ""
+
+
+def format_search_result(result: MemorySearchResult) -> str:
+ """Return only the text the coding agent needs from an explicit memory search."""
+ if not result.succeeded:
+ return "Memory search failed."
+ if result.memories:
+ rendered = format_context(result.memories, heading="")
+ if rendered:
+ return rendered
+ return "No matching memories found."
+
+
+def combine_context(*contexts: str) -> str:
+ """Combine memory sources under one hard budget without repeated lines."""
+ seen: set[str] = set()
+ lines: list[str] = []
+ for context in contexts:
+ for line in str(context or "").splitlines():
+ normalized = re.sub(r"\s+", " ", line).strip().casefold()
+ if not normalized or normalized in seen:
+ continue
+ seen.add(normalized)
+ lines.append(line.rstrip())
+ limit = min(
+ max(
+ _int_option(
+ "max_context_chars",
+ "MEM0_CODE_MAX_CONTEXT_CHARS",
+ DEFAULT_MAX_CONTEXT_CHARS,
+ ),
+ 1000,
+ ),
+ 10000,
+ )
+ return bounded("\n".join(lines), limit) if lines else ""
+
+
+def _scoped_memory_ids(
+ api_url: str, key: str, user: str, repo: RepoContext, include_project: bool
+) -> list[str]:
+ """List this user's memory ids for this repository, plus the shared project memory when asked."""
+ ids: list[str] = []
+ seen: set[str] = set()
+ prefix = repo.app_id
+ _collect_memory_ids(
+ api_url, key, {"user_id": user}, ids, seen,
+ app_id_prefix=prefix,
+ )
+ if include_project:
+ for project_id in _shared_project_ids(repo):
+ _collect_memory_ids(
+ api_url, key, {"agent_id": project_id}, ids, seen,
+ app_id_prefix=prefix,
+ )
+ return ids
+
+
+def _collect_memory_ids(
+ api_url: str,
+ key: str,
+ filters: dict[str, Any],
+ ids: list[str],
+ seen: set[str],
+ *,
+ app_id_prefix: str = "",
+) -> None:
+ """Page through one list filter; the list endpoint returns nothing for an OR whose user branch has no memories."""
+ payload = {"filters": filters}
+ for page in range(1, FORGET_MAX_PAGES + 1):
+ parsed, _, _ = _request_json(
+ f"{api_url}/v2/memories/?page={page}&page_size={FORGET_PAGE_SIZE}",
+ key,
+ payload,
+ 15,
+ )
+ items = parsed.get("results") if isinstance(parsed, dict) else parsed
+ if not isinstance(items, list) or not items:
+ break
+ for item in items:
+ if not isinstance(item, dict):
+ continue
+ memory_id = str(item.get("id", ""))
+ if not memory_id or memory_id in seen:
+ continue
+ if app_id_prefix:
+ item_app_id = str(item.get("app_id") or "")
+ if item_app_id != app_id_prefix and not item_app_id.startswith(app_id_prefix + "/"):
+ continue
+ seen.add(memory_id)
+ ids.append(memory_id)
+ if len(items) < FORGET_PAGE_SIZE:
+ break
+
+
+def _delete_memory(api_url: str, key: str, memory_id: str) -> bool:
+ request = urllib.request.Request(
+ f"{api_url}/v1/memories/{urllib.parse.quote(memory_id)}/",
+ headers=platform_headers(key),
+ method="DELETE",
+ )
+ try:
+ with urllib.request.urlopen(request, timeout=15):
+ return True
+ except Exception:
+ return False
+
+
+def forget_remote_repo(
+ repo: RepoContext, *, include_project_memory: bool = False
+) -> dict[str, Any]:
+ """Delete this user's memories for this repository; project memory is shared, so only on request."""
+ key = api_key()
+ if not key:
+ telemetry.record("forget", repo=repo, success=False, error_kind="no-api-key")
+ return {"status": "error", "error": "Mem0 API key is not configured"}
+ user = _scope_value(user_id())
+ if not user or not _scope_value(repo.app_id) or not _scope_value(repo.project_id):
+ telemetry.record("forget", repo=repo, success=False, error_kind="unscoped")
+ return {
+ "status": "error",
+ "error": "Refusing to forget: the user or repository scope is a wildcard",
+ }
+ api_url = os.environ.get("MEM0_API_URL", DEFAULT_API_URL).rstrip("/")
+ try:
+ memory_ids = _scoped_memory_ids(api_url, key, user, repo, include_project_memory)
+ except Exception as exc:
+ telemetry.record(
+ "forget", repo=repo, success=False, error_kind=telemetry.error_kind(exc)
+ )
+ return {"status": "error", "error": bounded(str(exc), 1000)}
+ deleted = sum(_delete_memory(api_url, key, memory_id) for memory_id in memory_ids)
+ failed = len(memory_ids) - deleted
+ telemetry.record("forget", repo=repo, success=not failed, item_count=deleted)
+ if failed:
+ return {
+ "status": "partial",
+ "deleted": deleted,
+ "failed": failed,
+ "error": f"{failed} of {len(memory_ids)} memories could not be deleted",
+ }
+ return {"status": "deleted", "deleted": deleted}
+
+
+def _doctor_mem0_authentication(repo: RepoContext) -> dict[str, Any]:
+ """Verify the configured key with one read-only, repository-scoped search."""
+ key = api_key()
+ if not key:
+ return {"ok": False, "detail": "API key missing"}
+ payload = {
+ "query": "Mem0 authentication check",
+ "filters": {
+ "AND": [
+ {"user_id": user_id()},
+ {"app_id": repo.app_id},
+ ]
+ },
+ "top_k": 1,
+ "threshold": 1.0,
+ "rerank": False,
+ }
+ url = os.environ.get("MEM0_API_URL", DEFAULT_API_URL).rstrip("/")
+ started = time.perf_counter()
+ try:
+ _request_json(f"{url}/v3/memories/search/", key, payload, 5)
+ except Exception as exc:
+ return {"ok": False, "detail": bounded(str(exc), 300)}
+ elapsed = (time.perf_counter() - started) * 1000
+ return {"ok": True, "detail": f"connected ({elapsed:.0f} ms)"}
+
+
+def _doctor_user_id() -> dict[str, Any]:
+ """Flag a configured user ID the plugin refuses, since the silent fallback surprises people."""
+ configured = _plugin_option("user_id", "MEM0_CODE_USER_ID") or os.environ.get(
+ "MEM0_USER_ID", ""
+ )
+ if configured and not _scope_value(configured):
+ return {
+ "ok": False,
+ "detail": f"configured user_id {configured!r} is a wildcard; using {user_id()!r}",
+ }
+ return {"ok": True, "detail": user_id()}
+
+
+def doctor(cwd: str | None = None) -> dict[str, Any]:
+ repo = resolve_repo(cwd)
+ directory = data_dir()
+ directory.mkdir(parents=True, exist_ok=True)
+ checks: dict[str, dict[str, Any]] = {
+ "python": {
+ "ok": tuple(sys.version_info[:2]) >= (3, 10),
+ "detail": f"{sys.version_info.major}.{sys.version_info.minor}",
+ },
+ "data_directory": {
+ "ok": os.access(directory, os.W_OK),
+ "detail": str(directory),
+ },
+ "mem0_api_key": {
+ "ok": bool(api_key()),
+ "detail": "configured" if api_key() else "missing",
+ },
+ "repository": {
+ "ok": bool(repo.identity),
+ "detail": repo.identity,
+ },
+ "user_id": _doctor_user_id(),
+ "mem0_authentication": _doctor_mem0_authentication(repo),
+ }
+ return {
+ "ok": all(bool(value["ok"]) for value in checks.values()),
+ "plugin_version": PLUGIN_VERSION,
+ "repo_id": repo.identity,
+ "app_id": repo.app_id,
+ "user_id": user_id(),
+ "checks": checks,
+ }
diff --git a/integrations/cursor-plugin/core/telemetry.py b/integrations/cursor-plugin/core/telemetry.py
new file mode 100644
index 000000000..c1fc0084c
--- /dev/null
+++ b/integrations/cursor-plugin/core/telemetry.py
@@ -0,0 +1,1013 @@
+#!/usr/bin/env python3
+"""Usage telemetry for Mem0 agent plugins.
+
+Events are linked to your Mem0 account email when an API key is configured, and
+to a random per-machine id otherwise. Not anonymous โ the Python SDK and CLI
+attribute the same way.
+
+Hooks run on a 3-6 second budget and fire on every tool call, so recording never
+touches the network: `record` appends one JSON line to a local spool and returns.
+A detached `python3 telemetry.py` drains the spool in one batched PostHog request,
+started once per session and again from the flush worker that is already detached.
+
+Pure stdlib, matching the rest of the plugin. Opt out with MEM0_TELEMETRY=false.
+
+Never sends prompts, memory text, queries, file paths, repository names, or API
+keys: only event names, durations, counts, coarse outcomes, and repo/session
+identifiers hashed with a random per-install salt.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import os
+import platform
+import subprocess
+import sys
+import time
+import urllib.error
+import urllib.request
+import uuid
+from pathlib import Path
+from typing import Any
+
+import memory_core
+
+# Seeded from the per-host module the build generates into core/. Two processes
+# in this pipeline never call init() โ mcp_server.py, and the detached
+# `python3 telemetry.py` sender that spawn_flush() starts โ so a module default
+# was what every one of their events got labelled with.
+try: # pragma: no cover - absent only in the un-built shared source tree
+ from _harness_id import HARNESS_ID as _DEFAULT_HARNESS
+ from _harness_id import PLATFORM_APPLICATION as _PLATFORM_APPLICATION
+ from _harness_id import PLATFORM_SOURCE as _PLATFORM_SOURCE
+ from _harness_id import SOURCE_TAG as _DEFAULT_SOURCE_TAG
+except ImportError:
+ _DEFAULT_HARNESS = "generic"
+ _DEFAULT_SOURCE_TAG = "MEM0_PLUGIN"
+ _PLATFORM_SOURCE = "MEM0_PLUGIN"
+ _PLATFORM_APPLICATION = ""
+
+_salt_cache: str = ""
+_harness: str = _DEFAULT_HARNESS
+_source_tag: str = _DEFAULT_SOURCE_TAG
+_PRIVATE_KEYS = {
+ "apikey",
+ "authorization",
+ "password",
+ "query",
+ "secret",
+ "prompt",
+ "token",
+ "text",
+ "memory",
+ "message",
+ "error",
+ "path",
+ "cwd",
+ "userid",
+ "agentid",
+ "runid",
+ "repoid",
+ "repositoryid",
+ "projectid",
+ "appid",
+ "filters",
+}
+
+
+def init(harness: str = "", source_tag: str = "") -> None:
+ """Override the generated identity. Optional โ core/_harness_id.py is the default.
+
+ The fallback shape matches memory_core.configure_harness's (``_PLUGIN``).
+ It used to be ``MEM0__PLUGIN`` here and ``_plugin`` there, which
+ meant one plugin could emit three different source values depending on which
+ process happened to send the batch.
+ """
+ global _harness, _source_tag
+ _harness = harness or _DEFAULT_HARNESS
+ _source_tag = source_tag or (
+ f"{_harness.upper().replace('-', '_')}_PLUGIN" if harness else _DEFAULT_SOURCE_TAG
+ )
+
+POSTHOG_API_KEY = "phc_hgJkUVJFYtmaJqrvf6CYN67TIQ8yhXAkWzUn9AMU4yX"
+POSTHOG_CAPTURE_URL = "https://us.i.posthog.com/i/v0/e/"
+POSTHOG_BATCH_URL = "https://us.i.posthog.com/batch/"
+EVENT_PREFIX = "code"
+SPOOL_LIMIT_BYTES = 256 * 1024
+BATCH_SIZE = 100
+SEND_TIMEOUT = 5
+CLAIM_STALE_SECONDS = 120
+CLAIM_EXPIRY_SECONDS = 7 * 24 * 60 * 60
+# A batch is only discarded once it has genuinely been retried this many times.
+MAX_CLAIM_ATTEMPTS = 3
+# Parked claims drained per run, after the live spool. Bounded so a long backlog
+# cannot turn one flush into an unbounded send loop.
+MAX_PARKED_PER_RUN = 3
+# Added to the wait before a released claim becomes reclaimable, per attempt
+# already spent. Releasing straight to "reclaimable now" let two senders burn the
+# whole budget within seconds of one another on a single momentary failure, and
+# discard a batch a retry a minute later would have delivered.
+RETRY_COOLDOWN_SECONDS = 60
+
+
+def is_enabled() -> bool:
+ """Whether telemetry is switched on for this process."""
+ return os.environ.get("MEM0_TELEMETRY", "true").strip().lower() not in {
+ "false",
+ "0",
+ "no",
+ "off",
+ }
+
+
+def _digest(value: str, length: int = 16) -> str:
+ """Unsalted digest. Only for values that are already secrets (API keys)."""
+ return hashlib.sha256(value.encode("utf-8")).hexdigest()[:length]
+
+
+def _salt_path() -> Path:
+ return memory_core.data_dir() / "telemetry-salt"
+
+
+def _install_salt() -> str:
+ """Random per-install salt, created once and memoized for the process.
+
+ Deliberately its own file, claimed with O_CREAT|O_EXCL, rather than a key in
+ the identity file. Three reasons, all of which produced wrong data when this
+ lived in the identity dict:
+
+ - Hooks are short-lived separate processes firing on every tool call, and
+ people run more than one agent window. A read-modify-write would let each
+ process mint its own salt, so one repository would hash several ways in the
+ window before a writer won.
+ - resolve_distinct_id holds a copy of the identity dict across a network call
+ to /v1/ping/, so whichever write landed second erased the other's key โ
+ losing either the salt (repo_hash changes mid-stream) or the email (a
+ second $identify, splitting the person).
+ - Touching the identity file from record() would create it, and is_first_run
+ keys off that file, so recording an event would silently suppress the
+ install event.
+
+ Published atomically, and there is deliberately no derived fallback. Creating
+ the file with O_CREAT|O_EXCL and then writing into it leaves a window where
+ the file exists and is empty, and a concurrent hook that reads it in that
+ window gets nothing. Falling back to a digest of the path would hand that
+ process a salt an attacker can compute, memoized for its whole run, which is
+ the privacy control this function exists to provide silently turning itself
+ off under load. The salt is written to a private temp file first and linked
+ into place, so the name either does not exist or already has the full value.
+
+ Returns "" when it genuinely cannot persist. Callers omit the hash entirely
+ rather than emit an unsalted one.
+ """
+ global _salt_cache
+ if _salt_cache:
+ return _salt_cache
+
+ path = _salt_path()
+ # Read before writing. Hooks are separate processes firing on every tool
+ # call, so all but the first find the salt already published; going straight
+ # to create-fsync-link-unlink meant every one of them paid an fsync to
+ # discover that, on a path whose whole promise is appending a line and
+ # returning.
+ try:
+ _salt_cache = path.read_text(encoding="utf-8").strip()
+ if _salt_cache:
+ return _salt_cache
+ except OSError:
+ pass
+
+ temporary = path.with_name(f"{path.name}.{os.getpid()}.tmp")
+ try:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ handle = os.open(temporary, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
+ with os.fdopen(handle, "w", encoding="utf-8") as stream:
+ stream.write(uuid.uuid4().hex)
+ stream.flush()
+ os.fsync(stream.fileno())
+ try:
+ # Atomic claim: fails if another process already published one.
+ # os.link rather than replace, which would clobber theirs.
+ os.link(temporary, path)
+ except FileExistsError:
+ pass
+ except OSError:
+ # No hardlinks here (some network mounts, some container volumes).
+ # Claim the name directly instead. That reopens the empty-file
+ # window, but the window is now benign: a reader that lands in it
+ # gets "" and omits the hash for that process rather than caching a
+ # guessable one. Losing the hashes on every run of an entire
+ # filesystem is the worse failure.
+ try:
+ fallback = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
+ with os.fdopen(fallback, "w", encoding="utf-8") as stream:
+ stream.write(temporary.read_text(encoding="utf-8"))
+ except OSError:
+ pass
+ except OSError:
+ pass
+ finally:
+ try:
+ temporary.unlink()
+ except OSError:
+ pass
+
+ try:
+ _salt_cache = path.read_text(encoding="utf-8").strip()
+ except OSError:
+ _salt_cache = ""
+ return _salt_cache
+
+
+def _scoped_digest(value: str, length: int = 16) -> str:
+ """Salted digest for values drawn from a guessable space.
+
+ repo.identity is a git remote URL, or ``local:`` when there is
+ no remote โ which normally contains the account username. Sixteen unsalted
+ hex characters over that input space is enumerable, so this is not a
+ privacy control without the salt. Salting per install keeps every
+ within-account join the analytics actually use and gives up only
+ cross-machine joins on the same repository, which nothing computes.
+
+ Returns "" when there is no salt, so record() omits the property. An
+ unsalted digest over this input space is close to plaintext, and emitting one
+ under a name that implies it is hashed is worse than sending nothing.
+ """
+ if not value:
+ return ""
+ salt = _install_salt()
+ if not salt:
+ return ""
+ return hashlib.sha256(f"{salt}:{value}".encode("utf-8")).hexdigest()[:length]
+
+
+def _safe_value(value: Any) -> Any:
+ if isinstance(value, str):
+ return memory_core.redact(value)
+ if isinstance(value, dict):
+ return {
+ key: _safe_value(item)
+ for key, item in value.items()
+ if "".join(character for character in str(key).lower() if character.isalnum())
+ not in _PRIVATE_KEYS
+ }
+ if isinstance(value, (list, tuple)):
+ return [_safe_value(item) for item in value]
+ if value is None or isinstance(value, (bool, int, float)):
+ return value
+ return memory_core.redact(value)
+
+
+def _spool_path() -> Path:
+ return memory_core.data_dir() / "telemetry.jsonl"
+
+
+def _identity_path() -> Path:
+ return memory_core.data_dir() / "telemetry-identity.json"
+
+
+def _read_identity() -> dict[str, str]:
+ try:
+ value = json.loads(_identity_path().read_text(encoding="utf-8"))
+ except (OSError, json.JSONDecodeError):
+ return {}
+ return value if isinstance(value, dict) else {}
+
+
+def _write_identity(identity: dict[str, str]) -> None:
+ path = _identity_path()
+ temporary = path.with_suffix(f".{os.getpid()}.tmp")
+ try:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ temporary.write_text(json.dumps(identity), encoding="utf-8")
+ temporary.replace(path)
+ except OSError:
+ try:
+ temporary.unlink()
+ except OSError:
+ pass
+
+
+def anonymous_id(identity: dict[str, str] | None = None) -> str:
+ """Per-machine anonymous identifier, created and persisted on first use."""
+ identity = _read_identity() if identity is None else identity
+ existing = identity.get("anonymous_id")
+ if existing:
+ return existing
+ created = f"code-anon-{uuid.uuid4().hex}"
+ identity["anonymous_id"] = created
+ _write_identity(identity)
+ return created
+
+
+def _rotate_anonymous_id(identity: dict[str, str]) -> str:
+ """Mint a fresh anonymous id because the account context is gone.
+
+ The previous id may already have been merged into a person profile by an
+ $identify, and that merge is permanent. Reusing it after a logout or a key
+ change attributes everything that follows to the account that just went
+ away, which is the same misattribution the key fingerprint exists to stop,
+ only arriving through the anonymous path instead.
+
+ `aliased` is cleared with it: the new id has never been merged, so it is
+ eligible to be aliased into whatever account comes next.
+ """
+ created = f"code-anon-{uuid.uuid4().hex}"
+ identity["anonymous_id"] = created
+ identity.pop("aliased", None)
+ _write_identity(identity)
+ return created
+
+
+def _install_state_path() -> Path:
+ return memory_core.data_dir() / "install-state.json"
+
+
+def is_first_run() -> bool:
+ """Whether install has never been recorded on this machine.
+
+ Deliberately NOT the identity file. That file is only written by a
+ successful flush, so an offline or firewalled user recorded code.install on
+ every single session, forever โ and every 0.2.x user recorded one on their
+ first 0.3.x session because 0.2.x never wrote it at all.
+ """
+ return not _install_state_path().exists()
+
+
+def data_dir_was_empty() -> bool:
+ """Whether the data directory is untouched. Call BEFORE anything writes to it.
+
+ hook_runner reaches claim_install() only after cache_plugin_api_key() has
+ written `api-key` and EvidenceStore() has created `evidence.sqlite3`, so
+ asking at claim time always saw content and every fresh install reported an
+ upgrade. The caller snapshots this at the top of the run instead.
+ """
+ return not _data_dir_has_content()
+
+
+def claim_install(was_empty: bool | None = None) -> str | None:
+ """Claim the one install/upgrade record for this machine, atomically.
+
+ Returns the event to record ("install" or "upgrade"), or None if another
+ session already claimed it. O_CREAT|O_EXCL so two sessions starting together
+ cannot both win.
+
+ `was_empty` must come from data_dir_was_empty() called before this process
+ wrote anything. Omitting it falls back to checking now, which is only
+ correct for a caller that has touched nothing.
+ """
+ if not is_enabled():
+ # Never consume the one-shot claim while the user is opted out, or they
+ # would silently lose their install event if they later opt in.
+ return None
+
+ path = _install_state_path()
+ upgrading = not (data_dir_was_empty() if was_empty is None else was_empty)
+ try:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ handle = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
+ except FileExistsError:
+ return None
+ except OSError:
+ return None
+ try:
+ with os.fdopen(handle, "w", encoding="utf-8") as stream:
+ json.dump(
+ {
+ "plugin_version": memory_core.PLUGIN_VERSION,
+ "installed_at": memory_core.utc_now(),
+ "upgraded": upgrading,
+ },
+ stream,
+ )
+ # Durable before this returns. The O_EXCL open is what makes the
+ # claim exclusive, so it cannot be replaced by a temp-and-rename
+ # without losing that, which leaves the content as the thing to make
+ # safe. A kill between the open and this fsync used to leave a marker
+ # that exists but parses to nothing: is_first_run reads it as claimed
+ # and claim_version_change cannot read a version out of it.
+ stream.flush()
+ os.fsync(stream.fileno())
+ except OSError:
+ pass
+ return "upgrade" if upgrading else "install"
+
+
+def _data_dir_has_content() -> bool:
+ """Whether anything predates this session in the plugin data directory."""
+ try:
+ for entry in memory_core.data_dir().iterdir():
+ if entry.name != "install-state.json":
+ return True
+ except OSError:
+ pass
+ return False
+
+
+def _repair_install_state(path: Path) -> None:
+ """Rewrite an unparseable marker so version tracking can resume."""
+ try:
+ temporary = path.with_suffix(f".{os.getpid()}.tmp")
+ temporary.write_text(
+ json.dumps({"plugin_version": memory_core.PLUGIN_VERSION, "repaired_at": memory_core.utc_now()}),
+ encoding="utf-8",
+ )
+ temporary.replace(path)
+ except OSError:
+ pass
+
+
+def claim_version_change() -> str | None:
+ """Return the previously recorded version if it differs, updating the marker.
+
+ Only meaningful once the marker exists โ the first transition into 0.3.x has
+ no recorded predecessor and reports "pre-0.3" instead. Claiming by rewriting
+ the marker means the next session sees no change and records nothing.
+ """
+ path = _install_state_path()
+ try:
+ state = json.loads(path.read_text(encoding="utf-8"))
+ except OSError:
+ return None
+ except json.JSONDecodeError:
+ # A crash between O_EXCL and the write leaves an empty marker. Left
+ # alone it disables every future upgrade event on this machine, because
+ # claim_install sees the file and this function cannot parse it.
+ state = None
+ if not isinstance(state, dict):
+ _repair_install_state(path)
+ return None
+ previous = str(state.get("plugin_version") or "")
+ if not previous or previous == memory_core.PLUGIN_VERSION:
+ return None
+ # Claim the transition with an exclusive sentinel before rewriting the
+ # marker. A plain read-modify-write let every concurrently starting session
+ # observe the old version and each record its own upgrade โ and the first
+ # session after a version bump is exactly when several agent windows restart
+ # together.
+ sentinel = path.with_name(f"upgraded-{memory_core.PLUGIN_VERSION}")
+ try:
+ os.close(os.open(sentinel, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600))
+ except FileExistsError:
+ return None
+ except OSError:
+ return None
+
+ state["plugin_version"] = memory_core.PLUGIN_VERSION
+ state["upgraded_at"] = memory_core.utc_now()
+ temporary = path.with_suffix(f".{os.getpid()}.tmp")
+ try:
+ temporary.write_text(json.dumps(state), encoding="utf-8")
+ temporary.replace(path)
+ except OSError:
+ # Release the claim. The marker still records the old version, so
+ # without this the sentinel makes claim_version_change return early on
+ # every later run and this version's upgrade is never recorded again.
+ for leftover in (sentinel, temporary):
+ try:
+ leftover.unlink()
+ except OSError:
+ pass
+ return None
+ return previous
+
+
+def record(
+ event: str,
+ *,
+ repo: Any = None,
+ session_id: str | None = None,
+ **properties: Any,
+) -> None:
+ """Append one event to the local spool. Never blocks and never raises."""
+ if not is_enabled():
+ return
+ try:
+ spool = _spool_path()
+ try:
+ if spool.stat().st_size > SPOOL_LIMIT_BYTES:
+ return
+ except OSError:
+ pass
+ properties = _safe_value(properties)
+ # Stamped in the RECORDING process, beside harness. `source` used to be
+ # read in the sending process from a module global, so whichever process
+ # drained the spool named every event in it. flush() spreads per-event
+ # properties last, so this now wins over any sender's default.
+ properties.update(
+ harness=_harness,
+ source=_source_tag,
+ plugin_version=memory_core.PLUGIN_VERSION,
+ os=sys.platform,
+ python_version=platform.python_version(),
+ )
+ # Assigned only when the digest is real. _scoped_digest returns "" when
+ # the salt could not be persisted, and an empty property is worse than an
+ # absent one: it survives the None filter below and reads as a value.
+ if repo is not None:
+ repo_hash = _scoped_digest(getattr(repo, "identity", ""))
+ if repo_hash:
+ properties["repo_hash"] = repo_hash
+ if session_id:
+ session_hash = _scoped_digest(session_id)
+ if session_hash:
+ properties["session_hash"] = session_hash
+ line = json.dumps(
+ {
+ "event": f"{EVENT_PREFIX}.{event}",
+ "uuid": str(uuid.uuid4()),
+ "timestamp": memory_core.utc_now(),
+ "properties": {
+ key: value for key, value in properties.items() if value is not None
+ },
+ },
+ separators=(",", ":"),
+ default=str,
+ )
+ spool.parent.mkdir(parents=True, exist_ok=True)
+ with spool.open("a", encoding="utf-8") as handle:
+ handle.write(line + "\n")
+ except Exception:
+ pass
+
+
+def error_kind(exc: BaseException | str) -> str:
+ """Coarse, content-free label for a failure, safe to send."""
+ text = exc if isinstance(exc, str) else f"{type(exc).__name__}: {exc}"
+ lowered = text.lower()
+ if "timed out" in lowered or "timeout" in lowered:
+ return "timeout"
+ if "401" in lowered or "403" in lowered or "unauthor" in lowered or "forbidden" in lowered:
+ return "auth"
+ if "429" in lowered or "rate limit" in lowered:
+ return "rate-limited"
+ if any(code in lowered for code in ("500", "502", "503", "504")):
+ return "server-error"
+ if "400" in lowered or "422" in lowered:
+ return "bad-request"
+ if isinstance(exc, str):
+ return "other"
+ if isinstance(exc, urllib.error.URLError):
+ return "network"
+ return type(exc).__name__
+
+
+def spawn_flush() -> bool:
+ """Start the detached sender that drains the spool."""
+ if not is_enabled():
+ return False
+ try:
+ if not _spool_path().exists() and not any(
+ memory_core.data_dir().glob("telemetry-*.sending")
+ ):
+ return False
+ subprocess.Popen(
+ [sys.executable, str(Path(__file__).resolve())],
+ stdin=subprocess.DEVNULL,
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL,
+ close_fds=True,
+ **memory_core.detached_process_kwargs(),
+ )
+ return True
+ except Exception:
+ return False
+
+
+def _claim_name(attempt: int = 0) -> str:
+ """Claim filename. The attempt count rides in the name so the 7-day expiry
+ only ever discards a batch that was actually retried and failed."""
+ return f"telemetry-{os.getpid()}-{uuid.uuid4().hex[:8]}-a{attempt}.sending"
+
+
+def _claim_attempt(claim: Path) -> int:
+ """Attempts recorded in a claim filename; 0 for the pre-attempt-count shape.
+
+ Anchored on field position, not on a leading "a": the legacy shape is
+ ``telemetry--.sending`` and a hex id such as ``a1234567`` would
+ otherwise parse as attempt 1234567 and be discarded unsent on the first
+ flush after an upgrade.
+ """
+ stem = claim.name[: -len(".sending")] if claim.name.endswith(".sending") else claim.name
+ parts = stem.split("-")
+ if len(parts) != 4:
+ return 0
+ tail = parts[3]
+ if tail.startswith("a") and tail[1:].isdigit():
+ return int(tail[1:])
+ return 0
+
+
+def _touch(path: Path) -> None:
+ """Refresh mtime so a claim's age measures time since it was claimed.
+
+ ``Path.replace`` is ``os.rename``, which preserves mtime โ so a claim created
+ after a quiet minute inherited the spool's last-write time and looked
+ abandoned the instant it was made. A second sender would then take it over
+ while the first was still posting, and both would deliver the batch.
+ """
+ try:
+ os.utime(path, None)
+ except OSError:
+ pass
+
+
+def _claim_spool() -> Path | None:
+ """Rename the spool aside so exactly one sender owns each batch."""
+ directory = memory_core.data_dir()
+ claim = directory / _claim_name()
+ spool = _spool_path()
+ try:
+ spool.replace(claim)
+ _touch(claim)
+ return claim
+ except OSError:
+ pass
+ return _claim_parked(directory)
+
+
+def _sweep_debris(directory: Path) -> None:
+ """Remove files nothing else will ever pick up again.
+
+ *.partial is a temp file orphaned by a crash between write and rename.
+ *.corrupt is a batch quarantined for undecodable content. No glob in this
+ module matches either, so without this they accumulate on disk for the life
+ of the install.
+
+ Quarantined batches are kept far longer than debris: they are the only
+ evidence left of events that could not be delivered, and someone diagnosing
+ a report of missing telemetry has to be able to find one.
+ """
+ now = time.time()
+ for debris in directory.glob("telemetry-*.partial"):
+ try:
+ if now - debris.stat().st_mtime > CLAIM_STALE_SECONDS:
+ debris.unlink()
+ except OSError:
+ continue
+ for quarantined in directory.glob("telemetry-*.corrupt"):
+ try:
+ if now - quarantined.stat().st_mtime > CLAIM_EXPIRY_SECONDS:
+ quarantined.unlink()
+ except OSError:
+ continue
+ # The same reasoning covers *.tmp. _write_identity and _install_salt both
+ # create one and unlink it in a finally, which a SIGKILL skips, and no glob
+ # in this module matches the leftovers either.
+ for temporary in directory.glob("telemetry-*.tmp"):
+ try:
+ if now - temporary.stat().st_mtime > CLAIM_STALE_SECONDS:
+ temporary.unlink()
+ except OSError:
+ continue
+
+
+def _claim_parked(directory: Path) -> Path | None:
+ """Take the oldest abandoned claim, if any lease has actually expired.
+
+ Kept separate from the live spool so flush() can drain both in one run.
+ Previously parked batches were only reachable when no spool existed at all,
+ and because sessions keep recording there usually was one โ so a batch
+ parked by a failed send waited until the 7-day expiry deleted it unsent,
+ even though its own presence is what started the sender.
+ """
+ now = time.time()
+ for orphan in sorted(directory.glob("telemetry-*.sending"), key=_safe_mtime):
+ try:
+ age = now - orphan.stat().st_mtime
+ except OSError:
+ continue
+ if age < CLAIM_STALE_SECONDS:
+ # Someone else holds a live lease on it. This check has to come
+ # first. Claiming a file bumps its attempt count and refreshes its
+ # mtime, so a sender that has just taken the final attempt looks
+ # exhausted to everyone else while it is actively draining. Judging
+ # exhaustion before liveness let a second sender unlink a batch out
+ # from under its owner, losing every event in it.
+ continue
+ # Attempts, not age. Every re-claim touches the mtime and every release
+ # backdates it by a fixed amount, so age is pinned near the stale
+ # threshold and never reaches the expiry. Age stays only as a backstop
+ # for files that never carried an attempt marker.
+ if _claim_attempt(orphan) >= MAX_CLAIM_ATTEMPTS or age > CLAIM_EXPIRY_SECONDS:
+ try:
+ orphan.unlink()
+ except OSError:
+ pass
+ continue
+ claim = orphan.parent / _claim_name(_claim_attempt(orphan) + 1)
+ try:
+ orphan.replace(claim)
+ _touch(claim)
+ return claim
+ except OSError:
+ continue
+ return None
+
+
+def _safe_mtime(path: Path) -> float:
+ try:
+ return path.stat().st_mtime
+ except OSError:
+ return 0.0
+
+
+def _rewrite_claim(claim: Path, remaining: list[dict[str, Any]]) -> bool:
+ """Persist the unsent remainder, atomically, and refresh the lease.
+
+ Called after every successful batch. Two jobs: a retry resumes where the
+ send stopped instead of re-posting from the top, and the rewrite doubles as
+ the lease heartbeat, so a slow sender does not have its claim stolen
+ mid-flight. Interval is one batch, well inside CLAIM_STALE_SECONDS.
+ """
+ if not remaining:
+ try:
+ claim.unlink()
+ except OSError:
+ pass
+ return True
+ temporary = claim.with_suffix(f".{os.getpid()}.partial")
+ try:
+ payload = "".join(json.dumps(event, separators=(",", ":"), default=str) + "\n" for event in remaining)
+ # fsync before the rename: without it the rename can land while the
+ # bytes have not, and the claim comes back empty or truncated after a
+ # crash. _drain then reads zero events and unlinks it.
+ with open(temporary, "w", encoding="utf-8") as handle:
+ handle.write(payload)
+ handle.flush()
+ os.fsync(handle.fileno())
+ temporary.replace(claim)
+ _touch(claim)
+ return True
+ except OSError:
+ try:
+ temporary.unlink()
+ except OSError:
+ pass
+ return False
+
+
+def _release_claim(claim: Path, remaining: list[dict[str, Any]]) -> None:
+ """Persist the remainder and drop the lease, because this sender has given up.
+
+ Distinct from the per-batch heartbeat: heartbeating on the way out would
+ make an abandoned batch look actively owned for a further
+ CLAIM_STALE_SECONDS, delaying the retry for no reason. Ageing it past the
+ threshold lets the next flush pick it up immediately, while the attempt
+ count in the filename still bounds how many times that can happen.
+ """
+ if not _rewrite_claim(claim, remaining):
+ return
+ try:
+ # Backdate past the stale threshold so the next flush can pick it up,
+ # minus a cooldown that grows with the attempts already spent. Clamped so
+ # the mtime never lands in the future, which would read as a live lease.
+ cooldown = min(_claim_attempt(claim) * RETRY_COOLDOWN_SECONDS, CLAIM_STALE_SECONDS)
+ released = time.time() - CLAIM_STALE_SECONDS - 1 + cooldown
+ os.utime(claim, (released, released))
+ except OSError:
+ pass
+
+
+def _resolve_email(key: str) -> str:
+ """Trade the API key for the account email so events join other Mem0 surfaces."""
+ url = os.environ.get("MEM0_API_URL", memory_core.DEFAULT_API_URL).rstrip("/") + "/v1/ping/"
+ request = urllib.request.Request(
+ url, headers={"Authorization": f"Token {key}", "Content-Type": "application/json"}
+ )
+ try:
+ with urllib.request.urlopen(request, timeout=SEND_TIMEOUT) as response:
+ payload = json.loads(response.read().decode("utf-8"))
+ except Exception:
+ return ""
+ email = payload.get("user_email") if isinstance(payload, dict) else ""
+ return email if isinstance(email, str) else ""
+
+
+def _post(payload: dict[str, Any], url: str) -> bool:
+ request = urllib.request.Request(
+ url,
+ data=json.dumps(payload, default=str).encode("utf-8"),
+ headers={"Content-Type": "application/json"},
+ )
+ try:
+ with urllib.request.urlopen(request, timeout=SEND_TIMEOUT):
+ return True
+ except Exception:
+ return False
+
+
+def resolve_distinct_id() -> tuple[str, str]:
+ """Return the PostHog distinct id and the anonymous id it replaced, if any.
+
+ The second value becomes a PostHog $identify alias. It is ONLY ever an
+ anonymous id: aliasing one account email to another merges two real person
+ profiles and cannot be undone, so a key that now belongs to a different
+ account re-resolves with no alias.
+ """
+ identity = _read_identity()
+ key = memory_core.api_key()
+ fingerprint = _digest(key) if key else ""
+ email = identity.get("email", "")
+
+ if email and fingerprint:
+ recorded = identity.get("key_fingerprint", "")
+ if recorded == fingerprint:
+ return email, ""
+ if not recorded:
+ # Rows written before fingerprints existed. Verify rather than
+ # adopt: a key changed before the upgrade would otherwise bind the
+ # new key to the previous account's email, permanently, and the
+ # fingerprint would then agree with itself forever after.
+ verified = _resolve_email(key)
+ if not verified:
+ # Offline, firewalled, or the API is down. Keep the previous
+ # behaviour and retry on the next flush rather than dropping a
+ # real account attribution. Safe because the same network that
+ # failed /v1/ping/ is about to fail the PostHog POST, so nothing
+ # is delivered under the unverified identity in the meantime.
+ return email, ""
+ identity["email"] = verified
+ identity["key_fingerprint"] = fingerprint
+ _write_identity(identity)
+ return verified, ""
+
+ if not key:
+ # No key to verify the account with; do not keep attributing to it.
+ if email:
+ identity.pop("email", None)
+ identity.pop("key_fingerprint", None)
+ return _rotate_anonymous_id(identity), ""
+ return anonymous_id(identity), ""
+
+ resolved = _resolve_email(key)
+ if not resolved:
+ # The key changed and will not resolve (revoked, offline, API down).
+ # Reaching here with an email means the recorded fingerprint disagreed,
+ # so the key really did change. Drop the account and rotate: the stored
+ # anonymous id may already be merged into that account's person, and
+ # reusing it would keep the events on the profile we are trying to
+ # leave.
+ if email:
+ identity.pop("email", None)
+ identity.pop("key_fingerprint", None)
+ return _rotate_anonymous_id(identity), ""
+ return anonymous_id(identity), ""
+
+ # Alias only when going anonymous -> email for the first time. Once an anon
+ # id has been merged into an account it must never be offered again: an
+ # alias naming an already-identified id is what could link two real people.
+ previous = "" if (email or identity.get("aliased")) else identity.get("anonymous_id", "")
+ if previous:
+ identity["aliased"] = True
+ identity["email"] = resolved
+ identity["key_fingerprint"] = fingerprint
+ _write_identity(identity)
+ return resolved, previous
+
+
+def flush() -> int:
+ """Drain the live spool, then any parked claims, and return events sent."""
+ if not is_enabled():
+ return 0
+ sent, delivered = _drain(_claim_spool())
+ if not delivered:
+ # The network is failing. Retrying other batches now would only burn
+ # their attempt budget against the same broken connection.
+ return sent
+
+ # Parked batches used to starve behind the live spool indefinitely. Bounded
+ # per run so a long backlog cannot turn one flush into an unbounded loop.
+ directory = memory_core.data_dir()
+ _sweep_debris(directory)
+ for _ in range(MAX_PARKED_PER_RUN):
+ parked = _claim_parked(directory)
+ if parked is None:
+ break
+ count, delivered = _drain(parked)
+ sent += count
+ if not delivered:
+ break
+ return sent
+
+
+def _drain(claim: Path | None) -> tuple[int, bool]:
+ """Post one claimed batch file, recording progress after every batch.
+
+ Returns (events sent, whether everything was delivered).
+ """
+ if claim is None:
+ return 0, True
+ try:
+ lines = claim.read_text(encoding="utf-8").splitlines()
+ except ValueError:
+ # UnicodeDecodeError from a torn write: the content is unrecoverable, so
+ # quarantine rather than retry. flush() runs from a bare `finally:` in
+ # flush_worker, so raising here also skips the handoff cleanup, and an
+ # undecodable file would otherwise be re-read on every flush forever.
+ # Reported as delivered because there is nothing left to deliver and the
+ # rest of the run should continue.
+ try:
+ claim.replace(claim.with_suffix(".corrupt"))
+ except OSError:
+ try:
+ claim.unlink()
+ except OSError:
+ pass
+ return 0, True
+ except OSError:
+ # Could not read it, which is not the same as having nothing to send.
+ # The file is left exactly where it is: a vanished or briefly unreadable
+ # claim is retryable, and quarantining it here would discard events over
+ # a transient filesystem error. Reported as undelivered so the run stops
+ # instead of counting a batch nothing was posted from as delivered.
+ return 0, False
+ events = []
+ for line in lines:
+ try:
+ value = json.loads(line)
+ except json.JSONDecodeError:
+ continue
+ if isinstance(value, dict) and value.get("event"):
+ events.append(value)
+ if not events:
+ # Only delete when the file really is empty. A non-empty file that
+ # parses to nothing is a torn write, and its contents are the unsent
+ # remainder โ deleting it is the data loss this PR exists to prevent.
+ try:
+ empty = claim.stat().st_size == 0
+ except OSError:
+ empty = True
+ try:
+ claim.replace(claim.with_suffix(".corrupt")) if not empty else claim.unlink()
+ except OSError:
+ pass
+ return 0, True
+
+ distinct_id, aliased_anonymous_id = resolve_distinct_id()
+ if aliased_anonymous_id:
+ _post(
+ {
+ "api_key": POSTHOG_API_KEY,
+ "event": "$identify",
+ "distinct_id": distinct_id,
+ "properties": {
+ "$anon_distinct_id": aliased_anonymous_id,
+ "$lib": "posthog-python",
+ },
+ },
+ POSTHOG_CAPTURE_URL,
+ )
+
+ sent = 0
+ for start in range(0, len(events), BATCH_SIZE):
+ chunk = events[start : start + BATCH_SIZE]
+ batch = [
+ {
+ "event": event["event"],
+ "distinct_id": distinct_id,
+ # Carried through from record() so a resend can be collapsed.
+ "uuid": event.get("uuid"),
+ "timestamp": event.get("timestamp"),
+ "properties": {
+ # Fallback only: events recorded by a build before source
+ # moved into record() have none of their own.
+ "source": _source_tag,
+ "language": "python",
+ "$process_person_profile": False,
+ "$lib": "posthog-python",
+ **(event.get("properties") or {}),
+ },
+ }
+ for event in chunk
+ ]
+ if not _post({"api_key": POSTHOG_API_KEY, "batch": batch}, POSTHOG_BATCH_URL):
+ # Keep only what has not been delivered, and release the lease.
+ # Previously the whole file was kept and the retry re-posted every
+ # batch, including the ones that had already arrived.
+ _release_claim(claim, events[start:])
+ return sent, False
+ sent += len(chunk)
+ # Record progress and refresh the lease after each successful batch, so
+ # a crash repeats at most one batch instead of the entire file. If the
+ # rewrite fails the claim still holds delivered events, so stop rather
+ # than carry on as though progress were recorded โ continuing is how the
+ # duplicate delivery this PR fixes would come back.
+ if not _rewrite_claim(claim, events[start + len(chunk) :]):
+ _release_claim(claim, events[start + len(chunk) :])
+ return sent, False
+ return sent, True
+
+
+def main() -> int:
+ flush()
+ return 0
+
+
+if __name__ == "__main__":
+ try:
+ raise SystemExit(main())
+ except Exception:
+ raise SystemExit(0)
diff --git a/integrations/cursor-plugin/hooks/adapter.py b/integrations/cursor-plugin/hooks/adapter.py
new file mode 100644
index 000000000..ba82f4eab
--- /dev/null
+++ b/integrations/cursor-plugin/hooks/adapter.py
@@ -0,0 +1,111 @@
+#!/usr/bin/env python3
+"""Translate Cursor's native hooks into the shared Mem0 runtime."""
+
+from __future__ import annotations
+
+import contextlib
+import io
+import json
+import os
+import sys
+from pathlib import Path
+
+HERE = Path(__file__).resolve()
+BUNDLED_CORE = HERE.parent.parent / "core"
+CORE = BUNDLED_CORE if BUNDLED_CORE.is_dir() else HERE.parents[2] / "core" / "python"
+sys.path.insert(0, str(CORE))
+
+import hook_runner # noqa: E402
+import telemetry # noqa: E402
+from memory_core import ( # noqa: E402
+ configure_harness,
+ record_tool,
+)
+
+EVENTS = {
+ "sessionStart": "session-start",
+ "beforeSubmitPrompt": "user-prompt",
+ "postToolUse": "post-tool",
+ "postToolUseFailure": "post-tool-failure",
+ "afterAgentResponse": "assistant-stop",
+ "stop": "stop",
+ "sessionEnd": "session-end",
+ "preCompact": "pre-compact",
+}
+
+
+def normalize(payload: dict, event: str) -> dict:
+ value = dict(payload)
+ value.setdefault("session_id", value.get("conversation_id") or value.get("parent_conversation_id", ""))
+ roots = value.get("workspace_roots") or []
+ if roots:
+ value.setdefault("cwd", roots[0])
+ if "tool_output" in value:
+ value.setdefault("tool_response", value["tool_output"])
+ if "error_message" in value:
+ value.setdefault("tool_response", value["error_message"])
+ if "text" in value:
+ value.setdefault("last_assistant_message", value["text"])
+ if "summary" in value:
+ value.setdefault("last_assistant_message", value["summary"])
+ return {"action": EVENTS[event], "payload": value}
+
+
+def _record_failure(store, payload):
+ return record_tool(store, payload, failed=True)
+
+
+def _record_response(store, payload):
+ hook_runner.default_record_stop(store, payload)
+
+
+def main() -> int:
+ if len(sys.argv) != 2 or sys.argv[1] not in EVENTS:
+ return 2
+ event = sys.argv[1]
+ try:
+ raw = json.load(sys.stdin)
+ except (json.JSONDecodeError, OSError):
+ raw = {}
+ normalized = normalize(raw if isinstance(raw, dict) else {}, event)
+ action = normalized["action"]
+ arguments = {
+ "session-end": ["flush", "--reason", "session-end"],
+ "pre-compact": ["flush", "--reason", "pre-compact"],
+ }.get(action, [action])
+ sys.argv = [sys.argv[0], *arguments]
+ sys.stdin = io.StringIO(json.dumps(normalized["payload"]))
+
+ configure_harness("cursor", data_dir_name="cursor-plugin", source_tag="cursor_plugin")
+ telemetry.init(harness="cursor", source_tag="CURSOR_PLUGIN")
+ with contextlib.redirect_stdout(io.StringIO()):
+ result = hook_runner.run(
+ extra_actions={
+ "post-tool-failure": _record_failure,
+ "assistant-stop": _record_response,
+ },
+ automatic_flush_reasons={"session-end", "pre-compact"},
+ )
+ if event == "sessionStart":
+ environment = {
+ key: value
+ for key in (
+ "PLUGIN_OPTION_API_KEY",
+ "PLUGIN_OPTION_USER_ID",
+ "PLUGIN_OPTION_TOP_K",
+ "PLUGIN_OPTION_MAX_CONTEXT_CHARS",
+ "PLUGIN_OPTION_SEARCH_SCOPE",
+ )
+ if (value := os.environ.get(key))
+ }
+ if environment:
+ print(json.dumps({"env": environment}))
+ return result
+
+
+if __name__ == "__main__":
+ try:
+ raise SystemExit(main())
+ except Exception as exc:
+ hook_runner.log_failure(exc)
+ raise SystemExit(0) from None
diff --git a/integrations/cursor-plugin/hooks/hooks.json b/integrations/cursor-plugin/hooks/hooks.json
new file mode 100644
index 000000000..dcd1d7c5d
--- /dev/null
+++ b/integrations/cursor-plugin/hooks/hooks.json
@@ -0,0 +1,13 @@
+{
+ "version": 1,
+ "hooks": {
+ "sessionStart": [{ "command": "PLUGIN_OPTION_API_KEY=\"${api_key}\" PLUGIN_OPTION_USER_ID=\"${user_id}\" PLUGIN_OPTION_TOP_K=\"${top_k}\" PLUGIN_OPTION_MAX_CONTEXT_CHARS=\"${max_context_chars}\" PLUGIN_OPTION_SEARCH_SCOPE=\"${search_scope}\" python3 \"${CURSOR_PLUGIN_ROOT}/hooks/adapter.py\" sessionStart", "timeout": 5 }],
+ "beforeSubmitPrompt": [{ "command": "python3 \"${CURSOR_PLUGIN_ROOT}/hooks/adapter.py\" beforeSubmitPrompt", "timeout": 6 }],
+ "postToolUse": [{ "command": "python3 \"${CURSOR_PLUGIN_ROOT}/hooks/adapter.py\" postToolUse", "timeout": 3 }],
+ "postToolUseFailure": [{ "command": "python3 \"${CURSOR_PLUGIN_ROOT}/hooks/adapter.py\" postToolUseFailure", "timeout": 3 }],
+ "afterAgentResponse": [{ "command": "python3 \"${CURSOR_PLUGIN_ROOT}/hooks/adapter.py\" afterAgentResponse", "timeout": 3 }],
+ "stop": [{ "command": "python3 \"${CURSOR_PLUGIN_ROOT}/hooks/adapter.py\" stop", "timeout": 3 }],
+ "preCompact": [{ "command": "python3 \"${CURSOR_PLUGIN_ROOT}/hooks/adapter.py\" preCompact", "timeout": 5 }],
+ "sessionEnd": [{ "command": "python3 \"${CURSOR_PLUGIN_ROOT}/hooks/adapter.py\" sessionEnd", "timeout": 5 }]
+ }
+}
diff --git a/integrations/cursor-plugin/mcp.json b/integrations/cursor-plugin/mcp.json
new file mode 100644
index 000000000..b17c1186c
--- /dev/null
+++ b/integrations/cursor-plugin/mcp.json
@@ -0,0 +1,18 @@
+{
+ "mcpServers": {
+ "mem0": {
+ "type": "stdio",
+ "command": "python3",
+ "args": [
+ "${CURSOR_PLUGIN_ROOT}/core/mcp_server.py"
+ ],
+ "env": {
+ "PLUGIN_OPTION_API_KEY": "${api_key}",
+ "PLUGIN_OPTION_USER_ID": "${user_id}",
+ "PLUGIN_OPTION_TOP_K": "${top_k}",
+ "PLUGIN_OPTION_MAX_CONTEXT_CHARS": "${max_context_chars}",
+ "PLUGIN_OPTION_SEARCH_SCOPE": "${search_scope}"
+ }
+ }
+ }
+}
diff --git a/integrations/cursor-plugin/plugin-build.json b/integrations/cursor-plugin/plugin-build.json
new file mode 100644
index 000000000..5320fb7f9
--- /dev/null
+++ b/integrations/cursor-plugin/plugin-build.json
@@ -0,0 +1,14 @@
+{
+ "id": "mem0",
+ "version": "0.3.3",
+ "homepage": "https://docs.mem0.ai/integrations/cursor",
+ "native": {
+ "pluginRoot": "${CURSOR_PLUGIN_ROOT}",
+ "files": {
+ ".cursor-plugin/plugin.json": ".cursor-plugin/plugin.json",
+ "hooks/hooks.json": "hooks/hooks.json",
+ "hooks/adapter.py": "hooks/adapter.py",
+ "mcp.json": "mcp.json"
+ }
+ }
+}
diff --git a/integrations/cursor-plugin/skills/forget/SKILL.md b/integrations/cursor-plugin/skills/forget/SKILL.md
new file mode 100644
index 000000000..c3af4d3df
--- /dev/null
+++ b/integrations/cursor-plugin/skills/forget/SKILL.md
@@ -0,0 +1,26 @@
+---
+name: forget
+description: Delete the Mem0 memories stored for this repository and this user. Use when the user asks to forget, clear, wipe, or delete memories.
+disable-model-invocation: true
+---
+
+# Forget this repository's memories
+
+This permanently deletes remote memories. Before running anything, tell the
+user exactly what will be deleted: their own memories for this repository
+only. The repository's project memory is shared by everyone who works in it,
+so it stays unless the user explicitly asks to delete that too.
+
+After the user confirms, run:
+
+```bash
+python3 "${CURSOR_PLUGIN_ROOT}/core/memory_cli.py" --harness "cursor" forget --remote --yes
+```
+
+If the user also asked to delete the repository's shared project memory, add
+`--include-project-memory` and say that this removes it for every teammate.
+
+Report what the command output says was deleted. If the user only wants local
+data cleared (evidence log, pending queue), run the same command without
+`--remote`. Never pass `--yes` before the user has confirmed in this
+conversation.
diff --git a/integrations/cursor-plugin/skills/pause/SKILL.md b/integrations/cursor-plugin/skills/pause/SKILL.md
new file mode 100644
index 000000000..17384c368
--- /dev/null
+++ b/integrations/cursor-plugin/skills/pause/SKILL.md
@@ -0,0 +1,20 @@
+---
+name: pause
+description: Pause Mem0 memory capture on this machine. Use when the user wants to stop memories being recorded, for example for private work or experiments.
+disable-model-invocation: true
+---
+
+# Pause memory capture
+
+To pause (hooks stop capturing and sending session content; a minimal
+telemetry ping still fires at session start, under your Mem0 account email,
+unless `MEM0_TELEMETRY=false`):
+
+```bash
+python3 "${CURSOR_PLUGIN_ROOT}/core/memory_cli.py" --harness "cursor" pause
+```
+
+Confirm the new state back to the user, and remind them that already-created
+memories still exist and remain searchable. Pending unsent packets are held
+while paused, not expired, and are delivered after resuming. To turn capture
+back on, use `/mem0:resume`.
diff --git a/integrations/cursor-plugin/skills/remember/SKILL.md b/integrations/cursor-plugin/skills/remember/SKILL.md
new file mode 100644
index 000000000..7be5fc9be
--- /dev/null
+++ b/integrations/cursor-plugin/skills/remember/SKILL.md
@@ -0,0 +1,21 @@
+---
+name: remember
+description: Acknowledge a "remember this" request and make sure it is captured well. Use when the user explicitly asks to remember, note, or save something for future sessions.
+disable-model-invocation: true
+---
+
+# Remember something for future sessions
+
+Mem0 creates memories from the session automatically โ there is no separate
+write command. When the user asks to remember something:
+
+1. Restate the fact clearly and completely in your reply, in one or two
+ sentences, including any names, values, or paths it depends on. Your visible
+ reply is what memory extraction reads, so a precise restatement is what gets
+ remembered.
+2. Tell the user it will be saved with this session's memories when the session
+ ends or compacts, and that it will surface in future sessions in this
+ repository (they can check later with /mem0:search).
+
+Do not invent a storage confirmation or a memory ID โ creation happens in the
+background after the session.
diff --git a/integrations/cursor-plugin/skills/resume/SKILL.md b/integrations/cursor-plugin/skills/resume/SKILL.md
new file mode 100644
index 000000000..d45bd545d
--- /dev/null
+++ b/integrations/cursor-plugin/skills/resume/SKILL.md
@@ -0,0 +1,19 @@
+---
+name: resume
+description: Resume Mem0 memory capture after it was paused with /mem0:pause.
+disable-model-invocation: true
+---
+
+# Resume memory capture
+
+Resume memory capture for this machine.
+
+Run:
+
+```bash
+python3 "${CURSOR_PLUGIN_ROOT}/core/memory_cli.py" --harness "cursor" resume
+```
+
+Confirm to the user that capture is active again. New sessions record evidence and
+create memories as normal; nothing that happened while paused is retroactively
+captured.
diff --git a/integrations/cursor-plugin/skills/search/SKILL.md b/integrations/cursor-plugin/skills/search/SKILL.md
new file mode 100644
index 000000000..2e3bde6a7
--- /dev/null
+++ b/integrations/cursor-plugin/skills/search/SKILL.md
@@ -0,0 +1,26 @@
+---
+name: search
+description: Search memories from earlier Cursor sessions in this repository. Use it when earlier work may already explain the code, error, decision, or command you need, so you can avoid repeating file reads, searches, or experiments.
+argument-hint: "[question] [--top-k number] [--category category-name] [--scope repo|dir|mine] [--run-id session-id]"
+disable-model-invocation: true
+---
+
+# Search memories
+
+Call `search_memories` with the user's question. Treat `--top-k`, `--category`,
+`--scope`, and `--run-id` as tool arguments instead of including them in the
+query.
+
+Omit `top_k` to use Mem0's configured default. Omit `category` to search every
+category. Omit `scope` to use the configured default, normally `repo`: this
+repository's shared memory, which everyone who works in it contributes to,
+plus your own preferences.
+
+Pass `scope` when the question needs something else: `dir` to narrow the
+shared memory to the directory you are working in (a package inside a
+monorepo), `mine` for your own preferences alone.
+
+Pass `run_id` with any scope to retrieve memories saved in a specific coding-agent
+session. Omit `run_id` to search across sessions. It filters the memories returned;
+it does not identify the session making the search request. Use a known session ID,
+never invent one. Return the tool's result directly.
diff --git a/integrations/cursor-plugin/skills/status/SKILL.md b/integrations/cursor-plugin/skills/status/SKILL.md
new file mode 100644
index 000000000..23ad94e33
--- /dev/null
+++ b/integrations/cursor-plugin/skills/status/SKILL.md
@@ -0,0 +1,23 @@
+---
+name: status
+description: Show whether Mem0 memory is working in this repository, covering configuration, capture state, pending flushes, and whether the Mem0 API key is valid. Use when the user asks whether memory is on, why a memory is missing, or anything looks broken.
+disable-model-invocation: false
+---
+
+# Memory status
+
+Run both commands and report the combined result in plain language:
+
+```bash
+python3 "${CURSOR_PLUGIN_ROOT}/core/memory_cli.py" --harness "cursor" status --json
+python3 "${CURSOR_PLUGIN_ROOT}/core/memory_cli.py" --harness "cursor" doctor
+```
+
+Summarize, using only fields the JSON actually reports: whether capture is
+active or paused, the user ID and repository scope (`repo_id`), whether an
+API key is configured, the event/flush/retrieval counts (`flushes` is the
+number of completed flushes, not a pending count), and the doctor check
+results. If doctor reports an authentication failure (401 / invalid key), say
+clearly that the Mem0 API key is invalid or expired and that memories are NOT
+being created. Never report an auth failure as "no memories found". Suggest
+reinstalling with `--config api_key=...` in that case.
diff --git a/integrations/cursor-plugin/tests/test_adapter.py b/integrations/cursor-plugin/tests/test_adapter.py
new file mode 100644
index 000000000..7db6f81c3
--- /dev/null
+++ b/integrations/cursor-plugin/tests/test_adapter.py
@@ -0,0 +1,81 @@
+from __future__ import annotations
+
+import importlib.util
+import json
+import sys
+from pathlib import Path
+
+import pytest
+
+HOST = Path(__file__).resolve().parents[1]
+CORE_ROOT = HOST.parent / "agent-plugin-core"
+sys.path.insert(0, str(CORE_ROOT))
+from build.build import build # noqa: E402
+
+SPEC = importlib.util.spec_from_file_location("cursor_adapter", HOST / "hooks" / "adapter.py")
+assert SPEC and SPEC.loader
+adapter = importlib.util.module_from_spec(SPEC)
+SPEC.loader.exec_module(adapter)
+
+
+@pytest.mark.parametrize(
+ ("event", "action"),
+ [
+ ("sessionStart", "session-start"),
+ ("beforeSubmitPrompt", "user-prompt"),
+ ("postToolUse", "post-tool"),
+ ("postToolUseFailure", "post-tool-failure"),
+ ("afterAgentResponse", "assistant-stop"),
+ ("stop", "stop"),
+ ("sessionEnd", "session-end"),
+ ("preCompact", "pre-compact"),
+ ],
+)
+def test_normalizes_cursor_events(event: str, action: str) -> None:
+ normalized = adapter.normalize(
+ {
+ "conversation_id": "conversation-1",
+ "workspace_roots": ["/worktree"],
+ "tool_output": "done",
+ "text": "assistant response",
+ },
+ event,
+ )
+
+ assert normalized["action"] == action
+ assert normalized["payload"]["session_id"] == "conversation-1"
+ assert normalized["payload"]["cwd"] == "/worktree"
+ assert normalized["payload"]["tool_response"] == "done"
+ assert normalized["payload"]["last_assistant_message"] == "assistant response"
+
+
+def test_after_agent_response_does_not_return_internal_context(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(adapter.hook_runner, "default_record_stop", lambda store, payload: (object(), "session"))
+
+ assert adapter._record_response(object(), {}) is None
+
+
+def test_cursor_hooks_use_native_flat_entries() -> None:
+ hooks = json.loads((HOST / "hooks" / "hooks.json").read_text(encoding="utf-8"))
+
+ assert hooks["version"] == 1
+ assert not {"subagentStart", "subagentStop"} & hooks["hooks"].keys()
+ assert set(hooks["hooks"]) >= {
+ "sessionStart",
+ "beforeSubmitPrompt",
+ "postToolUse",
+ "stop",
+ "sessionEnd",
+ }
+ assert all("hooks" not in entry for entries in hooks["hooks"].values() for entry in entries)
+
+
+def test_native_cursor_bundle_is_self_contained(tmp_path: Path) -> None:
+ root = build("cursor", "native", tmp_path / "cursor")
+
+ manifest = json.loads((root / ".cursor-plugin" / "plugin.json").read_text(encoding="utf-8"))
+ assert manifest["hooks"] == "./hooks/hooks.json"
+ assert "agents" not in manifest
+ assert (root / "hooks" / "adapter.py").is_file()
+ assert not (root / "agents").exists()
+ assert not any(path.is_symlink() for path in root.rglob("*"))
diff --git a/integrations/deepseek-plugin/README.md b/integrations/deepseek-plugin/README.md
index 088835d08..d5cb3345a 100644
--- a/integrations/deepseek-plugin/README.md
+++ b/integrations/deepseek-plugin/README.md
@@ -2,46 +2,68 @@
[Mem0](https://mem0.ai) long-term memory as a native [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness) (Cordis) plugin.
-It gives a Harness agent two memory tools backed by the Mem0 SDK, so recall and writes persist across sessions:
+It gives a Harness agent automatic long-term memory plus two explicit memory tools backed by the Mem0 SDK:
-| Tool | Does |
+| Capability | Does |
|---|---|
+| Auto-recall | Searches Mem0 for the latest human prompt and adds unseen results to the model context |
+| Auto-capture | Stores the human/assistant messages from each completed turn |
| `search_memory` | Recall facts from Mem0 relevant to a query |
| `add_memory` | Store a fact in Mem0 for future sessions |
-Unlike the local/file-based memory plugins in the ecosystem, Mem0 is a managed backend: server-side extraction, semantic dedup and conflict resolution, and the same memory bank reusable across Harness, Claude Code, Codex, and other agents.
+Unlike the local/file-based memory plugins in the ecosystem, Mem0 is a managed backend: server-side extraction, semantic dedup and conflict resolution, and memories that other agents can retrieve when their user and entity filters match.
+
+Current package version: `0.3.0`.
+
+Sidekick is available only in the [Claude Code plugin](../claude-code-plugin/README.md#sonnet-sidekick-agent).
## How it works
-A Cordis plugin is a module exporting `apply(ctx, config)`. This one declares `inject = ['tools']` so it waits for the harness tool registry, then registers the two tools via `ctx.tools.register(defineTool(...))`. When the plugin unmounts, the tools are removed automatically (Cordis revertible effects).
+A Cordis plugin is a module exporting `apply(ctx, config)`. This one waits for the Harness tool and system-prompt services, then uses the native extension points:
+
+- `system-prompt/assemble` recalls memory before a model request.
+- `session/event` captures only completed turns from the durable event stream.
+- `ctx.tools.register(...)` exposes explicit search and add tools.
+
+Completed human and assistant text is preserved after secret redaction, without the former 6,000-character per-message cutoff. Recall queries and displayed tool results retain separate size limits. These behaviors use [agent-plugin-core](../agent-plugin-core/README.md); this integration keeps its native tools and user-based scoping.
+
+Cordis owns listener and tool cleanup when the plugin unmounts. Every automatic path is fail-open: a memory API failure does not block the agent.
```
[ mem0ai SDK ] <-- managed memory, owned by Mem0
|
-[ deepseek-plugin: apply(ctx) -> ctx.tools.register(...) ] <-- this package
+[ deepseek-plugin: prompt + session listeners, memory tools ] <-- this package
|
[ DeepSeek Harness ] <-- the agent, loaded via cordis.yml
```
## Try it locally
-1. Build the plugin:
+1. Build and pack the plugin:
```sh
cd integrations/deepseek-plugin
- pnpm install
+ pnpm install --frozen-lockfile
pnpm build
+ mkdir -p /tmp/mem0-deepseek-plugin
+ pnpm pack --pack-destination /tmp/mem0-deepseek-plugin
```
2. Set your Mem0 key:
```sh
export MEM0_API_KEY=...
```
-3. Point Harness at it. Copy `cordis.example.yml`, set the absolute path to `dist/index.js` and your `userId`, then:
+3. Install it into a disposable Harness profile:
```sh
- pnpm dsh web --patch ./integrations/deepseek-plugin/cordis.example.yml
+ DSH_HOME=/tmp/mem0-dsh-dev pnpm dlx @deepseek-ai/dsh@0.1.1-rc.2 \
+ plugin --profile headless add /tmp/mem0-deepseek-plugin/mem0-deepseek-plugin-0.3.0.tgz
```
-4. Open http://127.0.0.1:3080 and ask the agent to remember something, then recall it in a later turn.
+4. Copy `cordis.example.yml`, set its installed package path and your `userId`, then run Harness with the same profile:
+ ```sh
+ DSH_HOME=/tmp/mem0-dsh-dev pnpm dlx @deepseek-ai/dsh@0.1.1-rc.2 \
+ web --patch ./integrations/deepseek-plugin/cordis.example.yml
+ ```
+5. Open http://127.0.0.1:3080 and ask the agent to remember something, then recall it in a later turn.
-For a Mem0 Platform on-prem or dedicated deployment, point `config.host` at that base URL (defaults to `api.mem0.ai`). `host` is a Platform base-URL override โ it is not a switch to self-hosted Mem0 OSS, whose server exposes a different API surface.
+For a Mem0 Platform on-prem or dedicated deployment, point `config.host` at that base URL (defaults to `api.mem0.ai`). `host` overrides the Platform base URL. It does not support the self-hosted Mem0 OSS API.
## Configuration
@@ -49,14 +71,25 @@ For a Mem0 Platform on-prem or dedicated deployment, point `config.host` at that
|---|---|---|---|
| `apiKey` | no | `$MEM0_API_KEY` | Mem0 platform API key |
| `userId` | yes | | Entity that owns the memories |
+| `allowUserOverride` | no | `false` | Permit model-selected access to a different user only in a trusted multi-user deployment |
| `host` | no | `api.mem0.ai` | Platform base URL (on-prem / dedicated) |
+| `autoRecall` | no | `true` | Recall relevant memory before model requests |
+| `autoCapture` | no | `true` | Store completed human/assistant turns |
+
+## Memory scope
+
+Automatic capture and recall use the configured `userId` across sessions. Automatic writes do not attach a repository ID or `runId`.
+
+Both `search_memory` and `add_memory` accept optional `agentId` and `runId`. On search, these narrow the returned memories; on add, they attach those identities to the stored memory. Pass a known `runId` to search memories explicitly saved with that session ID. This does not include automatically captured user-only memories or identify the session making the request.
+
+Per-call `userId` overrides are rejected unless the operator enables `allowUserOverride: true`. Automatic recall and capture always use the configured user.
## Telemetry
-Writes are tagged `source="DEEPSEEK_HARNESS"` so Mem0's backend can attribute usage to this integration. For it to surface by name (rather than bucketing into `OTHERS`), `DEEPSEEK_HARNESS` must be present in the backend's `KNOWN_EVENT_SOURCES` allowlist, a one-line platform change matching the existing `ZAPIER` / `STRANDS` sources.
+Writes are tagged `source="DEEPSEEK_HARNESS"`. That value has to exist in the backend's `EventSource` enum for usage to surface by name; until it does, these writes read as `OTHERS`. It is added by [mem0ai/platform#3602](https://github.com/mem0ai/platform/pull/3602), which has to ship before this claim is true.
-The plugin also sends anonymous usage events (which tool ran, duration, result counts, coarse failure kind) so Mem0 can tell how the plugin is used and where it breaks. Queries, memory text, and entity ids are never sent. Turn it off with `MEM0_TELEMETRY=false`.
+The plugin also sends usage events (which tool ran, duration, result counts, coarse failure kind) so Mem0 can tell how the plugin is used and where it breaks. These are **not anonymous**: when an API key is configured they are sent under your Mem0 account email, the same way the SDK attributes its own. Queries, memory text, and entity ids are never sent. Turn it off with `MEM0_TELEMETRY=false`.
## Status
-Developer preview. Tracks the DeepSeek Harness v0.1 plugin API (`@deepseek-ai/cordis`, `@deepseek-ai/dsh-tools`), which is young and moving; pin versions once it stabilizes. Auto-capture (store turns without an explicit tool call) and auto-recall (inject memory into the prompt at assembly) are planned once the harness session/assembly event API is confirmed.
+Developer preview. Tracks the DeepSeek Harness v0.1 plugin API, which is young and moving. Harness capability packages are peer dependencies supplied by the host; this package pins matching release-candidate versions for local typechecking and tests.
diff --git a/integrations/deepseek-plugin/cordis.example.yml b/integrations/deepseek-plugin/cordis.example.yml
index 7a0ac3bb9..5ed84b162 100644
--- a/integrations/deepseek-plugin/cordis.example.yml
+++ b/integrations/deepseek-plugin/cordis.example.yml
@@ -1,19 +1,17 @@
# Example DeepSeek Harness config that loads deepseek-plugin alongside the built-in
# tools plugin. Load with:
#
-# pnpm dsh web --patch ./integrations/deepseek-plugin/cordis.example.yml
+# DSH_HOME=/tmp/mem0-dsh-dev pnpm dlx @deepseek-ai/dsh@0.1.1-rc.2 \
+# web --patch ./integrations/deepseek-plugin/cordis.example.yml
#
-# The tools plugin (and its system-prompt dependency) must be present, because
-# the memory tools contribute schemas the system prompt renders.
-
-- name: "@deepseek-ai/dsh-system-prompt"
-- name: "@deepseek-ai/dsh-tools"
- insert:
- id: mem0
- # Absolute path to the built plugin (run `pnpm build` first), or point
- # at src/index.ts when running through tsx during development.
- name: "/absolute/path/to/mem0/integrations/deepseek-plugin/dist/index.js"
+ # Install the packed plugin into this disposable profile first; loading
+ # raw dist bypasses Harness's peer dependency installation.
+ name: "/tmp/mem0-dsh-dev/profiles/headless/node_modules/@mem0/deepseek-plugin/dist/index.js"
config:
# apiKey is read from the MEM0_API_KEY env var when omitted here.
userId: "your-user-id"
+ # autoRecall: true # optional; enabled by default
+ # autoCapture: true # optional; enabled by default
# host: "https://your-onprem.mem0.ai" # optional: Platform on-prem / dedicated base URL
diff --git a/integrations/deepseek-plugin/package.json b/integrations/deepseek-plugin/package.json
index b64e4a4e7..3de2d4f13 100644
--- a/integrations/deepseek-plugin/package.json
+++ b/integrations/deepseek-plugin/package.json
@@ -1,6 +1,6 @@
{
"name": "@mem0/deepseek-plugin",
- "version": "0.1.1",
+ "version": "0.3.2",
"description": "Mem0 long-term memory as a native DeepSeek Harness (Cordis) plugin.",
"type": "module",
"license": "Apache-2.0",
@@ -31,7 +31,6 @@
},
"files": [
"dist",
- "src",
"README.md",
"LICENSE"
],
@@ -46,14 +45,27 @@
},
"peerDependencies": {
"@deepseek-ai/cordis": "*",
+ "@deepseek-ai/dsh-agent": "*",
+ "@deepseek-ai/dsh-session": "*",
+ "@deepseek-ai/dsh-system-prompt": "*",
"@deepseek-ai/dsh-tools": "*"
},
"devDependencies": {
"@deepseek-ai/cordis": "4.0.1",
- "@deepseek-ai/dsh-tools": "0.0.1-rc.1",
+ "@deepseek-ai/dsh-agent": "0.1.1-rc.2",
+ "@deepseek-ai/dsh-session": "0.1.1-rc.2",
+ "@deepseek-ai/dsh-system-prompt": "0.1.1-rc.2",
+ "@deepseek-ai/dsh-tools": "0.1.1-rc.2",
"@types/node": "^22.15.0",
"tsup": "^8.5.0",
"typescript": "^5.6.0",
"vitest": "^4.1.7"
+ },
+ "pnpm": {
+ "overrides": {
+ "axios@<1.20.0": ">=1.20.0 <2.0.0",
+ "follow-redirects@<1.16.2": ">=1.16.2 <2.0.0",
+ "vite@>=8.2.0 <8.2.4": ">=8.2.4 <9.0.0"
+ }
}
}
diff --git a/integrations/deepseek-plugin/pnpm-lock.yaml b/integrations/deepseek-plugin/pnpm-lock.yaml
index 26bc065c8..e56466e4a 100644
--- a/integrations/deepseek-plugin/pnpm-lock.yaml
+++ b/integrations/deepseek-plugin/pnpm-lock.yaml
@@ -4,6 +4,11 @@ settings:
autoInstallPeers: false
excludeLinksFromLockfile: false
+overrides:
+ axios@<1.20.0: '>=1.20.0 <2.0.0'
+ follow-redirects@<1.16.2: '>=1.16.2 <2.0.0'
+ vite@>=8.2.0 <8.2.4: '>=8.2.4 <9.0.0'
+
importers:
.:
@@ -15,15 +20,24 @@ importers:
'@deepseek-ai/cordis':
specifier: 4.0.1
version: 4.0.1
+ '@deepseek-ai/dsh-agent':
+ specifier: 0.1.1-rc.2
+ version: 0.1.1-rc.2(@deepseek-ai/cordis@4.0.1)(@deepseek-ai/dsh-session@0.1.1-rc.2(@deepseek-ai/cordis@4.0.1))(@deepseek-ai/dsh-system-prompt@0.1.1-rc.2(@deepseek-ai/cordis@4.0.1))
+ '@deepseek-ai/dsh-session':
+ specifier: 0.1.1-rc.2
+ version: 0.1.1-rc.2(@deepseek-ai/cordis@4.0.1)
+ '@deepseek-ai/dsh-system-prompt':
+ specifier: 0.1.1-rc.2
+ version: 0.1.1-rc.2(@deepseek-ai/cordis@4.0.1)
'@deepseek-ai/dsh-tools':
- specifier: 0.0.1-rc.1
- version: 0.0.1-rc.1(@deepseek-ai/cordis@4.0.1)
+ specifier: 0.1.1-rc.2
+ version: 0.1.1-rc.2(@deepseek-ai/cordis@4.0.1)(@deepseek-ai/dsh-agent@0.1.1-rc.2(@deepseek-ai/cordis@4.0.1)(@deepseek-ai/dsh-session@0.1.1-rc.2(@deepseek-ai/cordis@4.0.1))(@deepseek-ai/dsh-system-prompt@0.1.1-rc.2(@deepseek-ai/cordis@4.0.1)))(@deepseek-ai/dsh-session@0.1.1-rc.2(@deepseek-ai/cordis@4.0.1))(@deepseek-ai/dsh-system-prompt@0.1.1-rc.2(@deepseek-ai/cordis@4.0.1))
'@types/node':
specifier: ^22.15.0
version: 22.20.1
tsup:
specifier: ^8.5.0
- version: 8.5.1(postcss@8.5.26)(typescript@5.9.3)
+ version: 8.5.1(postcss@8.5.32)(typescript@5.9.3)
typescript:
specifier: ^5.6.0
version: 5.9.3
@@ -48,18 +62,47 @@ packages:
'@deepseek-ai/cosmokit@1.8.2':
resolution: {integrity: sha512-muBOKtSrUKU5m/xpq8ZXWL6hQ/jgd4PhU2PqH97bcxIiLEJfNwZOGQEx4t/aS/GgxRAR+ra9pMHPMtTHU4sqqA==}
- '@deepseek-ai/dsh-tools@0.0.1-rc.1':
- resolution: {integrity: sha512-mrtq+UXc6UVidrGo4GM8RAH0Gqc4iFOmtPeQAz59Phhjl3EmzkFI0Mo6dQlHQamrc2J9jppPtGtUzW9qHmwxDQ==}
+ '@deepseek-ai/dsh-agent@0.1.1-rc.2':
+ resolution: {integrity: sha512-cC7lnJe7JgPFcreNXxcxLMxQd78LnpVO9ZXROjZsGRQN1zGH6i/DduI892F1am85IfzzO+XTxMwwUHmfwamb0g==}
peerDependencies:
- '@deepseek-ai/cordis': ^4.0.1-rc.1
- '@deepseek-ai/dsh-agent': ^0.0.1-rc.1
- '@deepseek-ai/dsh-code-runtime': ^0.0.1-rc.1
- '@deepseek-ai/dsh-invariants': ^0.0.1-rc.1
- '@deepseek-ai/dsh-llm': ^0.0.1-rc.1
- '@deepseek-ai/dsh-scope': ^0.0.1-rc.1
- '@deepseek-ai/dsh-session': ^0.0.1-rc.1
- '@deepseek-ai/dsh-system-prompt': ^0.0.1-rc.1
- '@deepseek-ai/dsh-user-approval': ^0.0.1-rc.1
+ '@deepseek-ai/cordis': ^4.0.1
+ '@deepseek-ai/dsh-invariants': ^0.1.1-rc.2
+ '@deepseek-ai/dsh-llm': ^0.1.1-rc.2
+ '@deepseek-ai/dsh-scope': ^0.1.1-rc.2
+ '@deepseek-ai/dsh-session': ^0.1.1-rc.2
+ '@deepseek-ai/dsh-system-prompt': ^0.1.1-rc.2
+ '@deepseek-ai/dsh-typert-protocol': ^0.1.1-rc.2
+
+ '@deepseek-ai/dsh-session@0.1.1-rc.2':
+ resolution: {integrity: sha512-4/cv6X9HPhm47eyRhCu/WZwzrtJKegk5J+0xaxcZ9i8S0smdxP57tqy8a0jkSshLQn7BzMFxneQrlYExrLrDhQ==}
+ peerDependencies:
+ '@deepseek-ai/cordis': ^4.0.1
+ '@deepseek-ai/dsh-brand': ^0.1.1-rc.2
+ '@deepseek-ai/dsh-invariants': ^0.1.1-rc.2
+ '@deepseek-ai/dsh-llm': ^0.1.1-rc.2
+ '@deepseek-ai/dsh-scope': ^0.1.1-rc.2
+ '@deepseek-ai/dsh-typert-protocol': ^0.1.1-rc.2
+
+ '@deepseek-ai/dsh-system-prompt@0.1.1-rc.2':
+ resolution: {integrity: sha512-on4hjAlYI5uX9q7Sf95YkMMBVe6heywtA/H50ksrIMUub8U2B98hO9iQpHhjwIO1F1vu+5pLcPvRr6yUGGmtXQ==}
+ peerDependencies:
+ '@deepseek-ai/cordis': ^4.0.1
+ '@deepseek-ai/dsh-invariants': ^0.1.1-rc.2
+ '@deepseek-ai/dsh-llm': ^0.1.1-rc.2
+ '@deepseek-ai/dsh-scope': ^0.1.1-rc.2
+
+ '@deepseek-ai/dsh-tools@0.1.1-rc.2':
+ resolution: {integrity: sha512-0GGL4D55MwYDepzZMOI3L0ycu5b2qr96GL0Y7snwhAnpK2Di61rbX3fJE+PB3ZrovGX0csIRdt9n3iJZDVtDrw==}
+ peerDependencies:
+ '@deepseek-ai/cordis': ^4.0.1
+ '@deepseek-ai/dsh-agent': ^0.1.1-rc.2
+ '@deepseek-ai/dsh-code-runtime': ^0.1.1-rc.2
+ '@deepseek-ai/dsh-invariants': ^0.1.1-rc.2
+ '@deepseek-ai/dsh-llm': ^0.1.1-rc.2
+ '@deepseek-ai/dsh-scope': ^0.1.1-rc.2
+ '@deepseek-ai/dsh-session': ^0.1.1-rc.2
+ '@deepseek-ai/dsh-system-prompt': ^0.1.1-rc.2
+ '@deepseek-ai/dsh-user-approval': ^0.1.1-rc.2
'@deepseek-ai/schemastery@3.18.1':
resolution: {integrity: sha512-Qn0FCSwCQnpnj6SB31I6i2sIKgKWnkbJM8O0EU91Gv2UsYVvtZTl6IA0sCwk2e2MZf5S8w5hpq9QkeVvK9qwxg==}
@@ -239,95 +282,95 @@ packages:
cpu: [x64]
os: [linux]
- '@oxc-project/types@0.146.0':
- resolution: {integrity: sha512-XC0QsnnhVe7sLIWmYmdPw7x5P0h4W8vUU3Nv1ySgWXtvCz8NizoAEpGXA0sOYoJQV2Rl13LgURAHQ5cI5ILCSA==}
+ '@oxc-project/types@0.156.0':
+ resolution: {integrity: sha512-1Duyg48TdJNdyhEB8Xn1L36bT9Pv6GUtlKjHxOys8xkaF/rQq3XJE+bAurSK/AgIz5mGFsb77cn9Pb20+WCScw==}
- '@rolldown/binding-android-arm-eabi@1.2.5':
- resolution: {integrity: sha512-DLe/i+l8ynIBY7XEQ191TeZvCoowIGa18R+dIV30GW7DiOtp74i/xX8hs8GUjW5ARV7VZuie3d6AumSmCwbeRA==}
+ '@rolldown/binding-android-arm-eabi@1.2.16':
+ resolution: {integrity: sha512-ia3DwAs0OsMGS7+IConptSiyk9pEXkOx/AbJ2n/lAGxH3QkWQus1t8d7gnAT38FCU2sQu8lUbeR6AiZFv4JxaA==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm]
os: [android]
- '@rolldown/binding-android-arm64@1.2.5':
- resolution: {integrity: sha512-zXcwKlQApYAOELHd8PwKDFkagYF9Wy4e0RJ+0qnzl9Pjnpj75TEG8ufv40p2J7kCEfwZAsNiuzRIyNNMWT38ig==}
+ '@rolldown/binding-android-arm64@1.2.16':
+ resolution: {integrity: sha512-kx5wBiMB6E7TEvpl2B9gjLU004BkvEm2Dr941BFjx/SontPwSzNuQUIoVKxHHoSjpFIfHMmcguyLOtyn0hObRg==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [android]
- '@rolldown/binding-darwin-arm64@1.2.5':
- resolution: {integrity: sha512-dK4QakI42nzWgJT5sm4y4y/O//D4OxM75/cH28RLV+nzIN9AY+YsbuUVrUTjlLjXR6vpyxFbSsbmNuJ6BP9sww==}
+ '@rolldown/binding-darwin-arm64@1.2.16':
+ resolution: {integrity: sha512-qslZrXnKJU4cUpjoAmtAo/KQM9e2IRMlmpig6Zpwj+8KWxW8v+nkAf9216Bsek9lOC1jvg2yCjygCFo2f83msQ==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [darwin]
- '@rolldown/binding-darwin-x64@1.2.5':
- resolution: {integrity: sha512-fqSALaUu1Wjd1nK2uW2kJDWdLCc8lx1IcY+MTY26Aurfdx19anlzhqXOgCFbBFQnlFDTn4TC1/7Nz4Bl2mLP3A==}
+ '@rolldown/binding-darwin-x64@1.2.16':
+ resolution: {integrity: sha512-FdF+y48ND13eAyM2mQn+85kvAqNlvRWROy2rhgA463X/0Gv4vGtazZtfaF1mRBLscYvtOlh4QnLjOWiFzX69OQ==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [darwin]
- '@rolldown/binding-freebsd-x64@1.2.5':
- resolution: {integrity: sha512-/vCnNxlkxs9tKxNDcyWUePpJ/PgTzxIaVhoM5SmG8UV+GR/IcPam4VYxi7GIMo7PSDuNqlJqvprqii9NqqVCMw==}
+ '@rolldown/binding-freebsd-x64@1.2.16':
+ resolution: {integrity: sha512-ddjqFM5e95AgLbUPtKIS7V1KTVlA0RUgCVr5mn+/IEhsdy3pr+Vuj/HZ7nlMN2FyxIwUktOH1LEPIQXO1v9y1Q==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [freebsd]
- '@rolldown/binding-linux-arm-gnueabihf@1.2.5':
- resolution: {integrity: sha512-abk0NLA519LxRCszmbE0jYKuQ9YPocOXTiOXOo6Yr+YAT95VH+PtqYAjOJvGKt3viEd/x4qzabAlwd5bHOOARg==}
+ '@rolldown/binding-linux-arm-gnueabihf@1.2.16':
+ resolution: {integrity: sha512-tHdKWbFkFBI687iim3LIyIvyL7j66VvQYkDPss5Stn/qyE2tWkR1YD0dXmXPFKKqT/o5ZEJVsaRsWS2meQwGOA==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm]
os: [linux]
- '@rolldown/binding-linux-arm64-gnu@1.2.5':
- resolution: {integrity: sha512-Y7eALiJ8lr0M2HH103Js+g7V34wf6snlpZLAsHI90uLhr3PVlNsbFVAXJC9d/V6BnPyKtpSwI+NcB/RLxsQxuA==}
+ '@rolldown/binding-linux-arm64-gnu@1.2.16':
+ resolution: {integrity: sha512-FJiLGAblPBMlBEdbOqw6kW6QcXDWAf/oJu7gYs9ZJZwmg+K+/zjFLxPTIY9izJUzxzc24FHvmseyA0IvJSl17w==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
- '@rolldown/binding-linux-arm64-musl@1.2.5':
- resolution: {integrity: sha512-xMvZgnbZg4YVnR/AX2b3oOPDTFYJvUVaJg5FedA/LuvexAtXibZQej4cnTkw3rjsJ/ggUROB64TdtETiim+FYA==}
+ '@rolldown/binding-linux-arm64-musl@1.2.16':
+ resolution: {integrity: sha512-hrJpblMsrQ58U9veWpbXzkhV5zStunds6HWLprqq1qauvgBr1E6P+24kLj6lSLI9vjRn/RYpjprhkHQPKGWpNg==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
- '@rolldown/binding-linux-ppc64-gnu@1.2.5':
- resolution: {integrity: sha512-GRjeqTUDHTo5GwntsLaAMcBahG3nlpjftXWZLN73HiYQlhwEowvarFgQnRnQZtIp4keXX7quXFbG38uPZBa2EA==}
+ '@rolldown/binding-linux-ppc64-gnu@1.2.16':
+ resolution: {integrity: sha512-qJd/dC6j6CwLG9/s/RP2nb1RZ0GIgj7Ioj7x/SYa3RzjVrlzrmH0fhIOpfvqQDeIsdP0loi+kHaMhJzY1PBIaA==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [ppc64]
os: [linux]
- '@rolldown/binding-linux-s390x-gnu@1.2.5':
- resolution: {integrity: sha512-vLNTR45F2Uwc8AufkNXPmB4VliaXs+FvcheEogIzOXzO4l+LzieXF5A/TWxLy5HtqpsRCHUfd0lPVrrdgXdLHQ==}
+ '@rolldown/binding-linux-s390x-gnu@1.2.16':
+ resolution: {integrity: sha512-Vx7Xg5uUJuNcujJjI70OICaH0EYj80BtOLZTSN7uOYg8QOLlyKnaG0IW7Fn/J0IpJsaKzmDKMhOQv1JBM9m9vg==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [s390x]
os: [linux]
- '@rolldown/binding-linux-x64-gnu@1.2.5':
- resolution: {integrity: sha512-Mgj59/HTuYeK9Gz2MA+mBWKnHsAgkBSec15ZMb1st3oIfFbX7gCjOae7GydHhzcyQi9Z/7M1QuN9bR3oFqF0jQ==}
+ '@rolldown/binding-linux-x64-gnu@1.2.16':
+ resolution: {integrity: sha512-TNKhgE3uJTsTzatUSSYt0Kgo+Oa2uSlSjz4r1aEIea7HX6ULBym4fAlYUhG1i6pjNf2njfCUAfKwr6C3E9Xg1w==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
- '@rolldown/binding-linux-x64-musl@1.2.5':
- resolution: {integrity: sha512-mY8AP0/ichsbhAxGnLa3d3+MwV0EfgrPND2bplI3Ym8T6R2pJ0N87bvrKVwNXmdy3jnr6eQBecdqx/HMknBmpA==}
+ '@rolldown/binding-linux-x64-musl@1.2.16':
+ resolution: {integrity: sha512-7chXdpjXZ8qG0+mIxECN3cT9kvhZ3/oZhMX6Pp876P7CDrIy8nJswva6Mq357JR7eYXfuskwZxMeV1SzoZdHrA==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
- '@rolldown/binding-openharmony-arm64@1.2.5':
- resolution: {integrity: sha512-8SLssA2oweAxyRgDp789ACfRb/3P+zNRJpzZxSizxF9m8NUDQ4+3xjo8ttjhVGGw6Qxb70oZiEtIjaKikCO7Yw==}
+ '@rolldown/binding-openharmony-arm64@1.2.16':
+ resolution: {integrity: sha512-Kwjt+7uNTJK5/MDkGWGVO2KQPnj8yAV75dMpfwyHZrJSXWHrniOB0aUEWlVYf3H1hOqFLIStLdM5QXq6bnKmOQ==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [openharmony]
- '@rolldown/binding-win32-arm64-msvc@1.2.5':
- resolution: {integrity: sha512-vGbruD5zquhoc8D9SViXgN2FBJtNdTyQ4DtG+SWiEGlJiAzoKcZ2xp+xuXCffhubVdt0NJlTZqkeRuERy7g8Cw==}
+ '@rolldown/binding-win32-arm64-msvc@1.2.16':
+ resolution: {integrity: sha512-/LH6WfjDRXXJz/p5xl4TmU+jpcnwcxbKEQBW/GZE0JHfN0lGIyTtsUEGaQ/q/GikkGJ2yLKe6pwm7AnEWO8pdw==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [win32]
- '@rolldown/binding-win32-x64-msvc@1.2.5':
- resolution: {integrity: sha512-e/SXpgISz+IoqVcSSI0rx/d/he8zqLex+/rCWpnHpmVfmPIUjag9H6P7zotf0gJHwPUhQxZ/mF8tr6acebT9yw==}
+ '@rolldown/binding-win32-x64-msvc@1.2.16':
+ resolution: {integrity: sha512-1lv1KvX0Z871zfk7vw+dnXMMnHNyDwMzWG8Kv3HxDXMOhzCX4SHc7HK319fInP0i+0p9D8brkfzL7pJOaGl+tw==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [win32]
@@ -488,7 +531,7 @@ packages:
resolution: {integrity: sha512-2XJVD55d1o5AZous5CCGKS74g/riOj9odEt2bQpCVZeblHyHdnMeFl4jl0XjU21stf4mbjUkew2eXQZt65g5CQ==}
peerDependencies:
msw: ^2.4.9
- vite: ^6.0.0 || ^7.0.0 || ^8.0.0
+ vite: '>=8.2.4 <9.0.0'
peerDependenciesMeta:
msw:
optional: true
@@ -537,8 +580,8 @@ packages:
asynckit@0.4.0:
resolution: {integrity: sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==}
- axios@1.19.0:
- resolution: {integrity: sha512-ht/iuYZXEjFxLH/Hkezgd7m6JKlHHXEUSneaDz8uZe1Gj5QZtCnpyDsckvAiEnT89OEbCLmnte4R4sn7P0EKFw==}
+ axios@1.20.0:
+ resolution: {integrity: sha512-r8aOh8j9cGKpgQAqpzrUHnSIc6a59Y3Xf/cv8sy1DrHCkZHzQGEuoq1tARk6qSyDdtQGSDgpb9kFlruzPvrgwg==}
bundle-require@5.1.0:
resolution: {integrity: sha512-3WrrOuZiyaaZPWiEt4G3+IffISVC9HYlWueJEBWED4ZH4aIAC2PnkdnuRrR94M+w6yGWn4AglWtJtBI8YqvgoA==}
@@ -648,8 +691,8 @@ packages:
fix-dts-default-cjs-exports@1.0.1:
resolution: {integrity: sha512-pVIECanWFC61Hzl2+oOCtoJ3F17kglZC/6N94eRWycFgBH35hHx0Li604ZIzhseh97mf2p0cv7vVrOZGoqhlEg==}
- follow-redirects@1.16.0:
- resolution: {integrity: sha512-y5rN/uOsadFT/JfYwhxRS5R7Qce+g3zG97+JrtFZlC9klX/W5hD7iiLzScI4nZqUS7DNUdhPgw4xI8W2LuXlUw==}
+ follow-redirects@1.16.2:
+ resolution: {integrity: sha512-/kVP2U8z596Ia0gwFrwyIeo74ta5aVmSeU1FfAUMAmcEP5EP7zydmag3SLiN64NaRKef3lxsq7i/g7ltJQDGow==}
engines: {node: '>=4.0'}
peerDependencies:
debug: '*'
@@ -934,8 +977,8 @@ packages:
mz@2.7.0:
resolution: {integrity: sha512-z81GNO7nnYMEhrGh9LeymoE4+Yr0Wn5McHIZMK5cfQCl+NDX08sCZgUc9/6MHni9IWuFLm1Z3HTCXu2z9fN62Q==}
- nanoid@3.3.18:
- resolution: {integrity: sha512-DTg4MJbGMWkfi6VZFdNt2/caMbQy4Ou+Op/hJQvGEWcnVfoA1QA+xzRKAzw9jD6+GVOOeYr/mIcuDSdug6F6+w==}
+ nanoid@3.3.20:
+ resolution: {integrity: sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==}
engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1}
hasBin: true
@@ -983,6 +1026,10 @@ packages:
resolution: {integrity: sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A==}
engines: {node: '>=12'}
+ picomatch@4.0.7:
+ resolution: {integrity: sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==}
+ engines: {node: '>=12'}
+
pirates@4.0.7:
resolution: {integrity: sha512-TfySrs/5nm8fQJDcBDuUng3VOUKsd7S+zqvbOTiGXHfxX4wK31ard+hoNuvkicM/2YFzlpDgABOevKSsB4G/FA==}
engines: {node: '>= 6'}
@@ -1008,8 +1055,8 @@ packages:
yaml:
optional: true
- postcss@8.5.26:
- resolution: {integrity: sha512-u82N74LFzG8ca+dD8puPnplTXoGH4fTPpVGuIbt36G3qvNlkvfD0lEAZSxaly3KX8TS/L1A1gsCEmvKmBcVbkQ==}
+ postcss@8.5.32:
+ resolution: {integrity: sha512-LJlKCCAUFKOuZxipUdYw1NzIITEsPcgyOG9LkvRJvuKj/bRzbuRY0ARXvL0pWGpsZvn8jku+LMep2eU0seHp8g==}
engines: {node: ^10 || ^12 || >=14}
proxy-from-env@2.1.0:
@@ -1024,8 +1071,8 @@ packages:
resolution: {integrity: sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==}
engines: {node: '>=8'}
- rolldown@1.2.5:
- resolution: {integrity: sha512-VD2IE5PUG4Oj8zz2VGykiYd5wbnjdIiSsNQb8Qu5B+noEp+A78mu2iVvpp27g8es14Tk9rofNs5Tku9iQCS4fA==}
+ rolldown@1.2.16:
+ resolution: {integrity: sha512-bWvlMpFKiTfDKfnK7FC2MPgPeWCf/Kpwsq49ApdW+FQaBZb6O6dZ4MAPbPUjp7hYQrw/RobqCzn64BRrQecGHw==}
engines: {node: ^20.19.0 || >=22.12.0}
hasBin: true
@@ -1037,8 +1084,8 @@ packages:
siginfo@2.0.0:
resolution: {integrity: sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==}
- source-map-js@1.2.1:
- resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==}
+ source-map-js@1.2.2:
+ resolution: {integrity: sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==}
engines: {node: '>=0.10.0'}
source-map@0.7.6:
@@ -1128,13 +1175,13 @@ packages:
resolution: {integrity: sha512-vIYxrBCC/N/K+Js3qSN88go7kIfNPssr/hHCesKCQNAjmgvYS2oqr69kIufEG+O4+PfezOH4EbIeHCfFov8ZgQ==}
hasBin: true
- vite@8.2.2:
- resolution: {integrity: sha512-cFKLV/PRgAUlIRm5WjMjJ86jrftzpqcgH+Us+DS8mI3CDNiH30Whrz8uHL3+MOLPAgqbMBAqWdAHAphOAM+z/Q==}
+ vite@8.3.6:
+ resolution: {integrity: sha512-UI7dK29NnS54Fk+mmo7o+jI6U8Fp7hDl+X5Q1k45WH+d4dSlbLVUETGQ+hfkNgvLQGyoElPj837nZyv4MBc0VA==}
engines: {node: ^20.19.0 || >=22.12.0}
hasBin: true
peerDependencies:
'@types/node': ^20.19.0 || >=22.12.0
- '@vitejs/devtools': ^0.4.0 || ^0.5.0
+ '@vitejs/devtools': ^0.7.1 || ^0.8.0
esbuild: ^0.27.0 || ^0.28.0
jiti: '>=1.21.0'
less: ^4.0.0
@@ -1238,9 +1285,27 @@ snapshots:
'@deepseek-ai/cosmokit@1.8.2': {}
- '@deepseek-ai/dsh-tools@0.0.1-rc.1(@deepseek-ai/cordis@4.0.1)':
+ '@deepseek-ai/dsh-agent@0.1.1-rc.2(@deepseek-ai/cordis@4.0.1)(@deepseek-ai/dsh-session@0.1.1-rc.2(@deepseek-ai/cordis@4.0.1))(@deepseek-ai/dsh-system-prompt@0.1.1-rc.2(@deepseek-ai/cordis@4.0.1))':
dependencies:
'@deepseek-ai/cordis': 4.0.1
+ '@deepseek-ai/dsh-session': 0.1.1-rc.2(@deepseek-ai/cordis@4.0.1)
+ '@deepseek-ai/dsh-system-prompt': 0.1.1-rc.2(@deepseek-ai/cordis@4.0.1)
+
+ '@deepseek-ai/dsh-session@0.1.1-rc.2(@deepseek-ai/cordis@4.0.1)':
+ dependencies:
+ '@deepseek-ai/cordis': 4.0.1
+
+ '@deepseek-ai/dsh-system-prompt@0.1.1-rc.2(@deepseek-ai/cordis@4.0.1)':
+ dependencies:
+ '@deepseek-ai/cordis': 4.0.1
+ '@deepseek-ai/schemastery': 3.18.1
+
+ '@deepseek-ai/dsh-tools@0.1.1-rc.2(@deepseek-ai/cordis@4.0.1)(@deepseek-ai/dsh-agent@0.1.1-rc.2(@deepseek-ai/cordis@4.0.1)(@deepseek-ai/dsh-session@0.1.1-rc.2(@deepseek-ai/cordis@4.0.1))(@deepseek-ai/dsh-system-prompt@0.1.1-rc.2(@deepseek-ai/cordis@4.0.1)))(@deepseek-ai/dsh-session@0.1.1-rc.2(@deepseek-ai/cordis@4.0.1))(@deepseek-ai/dsh-system-prompt@0.1.1-rc.2(@deepseek-ai/cordis@4.0.1))':
+ dependencies:
+ '@deepseek-ai/cordis': 4.0.1
+ '@deepseek-ai/dsh-agent': 0.1.1-rc.2(@deepseek-ai/cordis@4.0.1)(@deepseek-ai/dsh-session@0.1.1-rc.2(@deepseek-ai/cordis@4.0.1))(@deepseek-ai/dsh-system-prompt@0.1.1-rc.2(@deepseek-ai/cordis@4.0.1))
+ '@deepseek-ai/dsh-session': 0.1.1-rc.2(@deepseek-ai/cordis@4.0.1)
+ '@deepseek-ai/dsh-system-prompt': 0.1.1-rc.2(@deepseek-ai/cordis@4.0.1)
'@deepseek-ai/schemastery': 3.18.1
'@deepseek-ai/schemastery@3.18.1':
@@ -1343,51 +1408,51 @@ snapshots:
'@napi-rs/lzma-linux-x64-gnu@1.5.1':
optional: true
- '@oxc-project/types@0.146.0': {}
+ '@oxc-project/types@0.156.0': {}
- '@rolldown/binding-android-arm-eabi@1.2.5':
+ '@rolldown/binding-android-arm-eabi@1.2.16':
optional: true
- '@rolldown/binding-android-arm64@1.2.5':
+ '@rolldown/binding-android-arm64@1.2.16':
optional: true
- '@rolldown/binding-darwin-arm64@1.2.5':
+ '@rolldown/binding-darwin-arm64@1.2.16':
optional: true
- '@rolldown/binding-darwin-x64@1.2.5':
+ '@rolldown/binding-darwin-x64@1.2.16':
optional: true
- '@rolldown/binding-freebsd-x64@1.2.5':
+ '@rolldown/binding-freebsd-x64@1.2.16':
optional: true
- '@rolldown/binding-linux-arm-gnueabihf@1.2.5':
+ '@rolldown/binding-linux-arm-gnueabihf@1.2.16':
optional: true
- '@rolldown/binding-linux-arm64-gnu@1.2.5':
+ '@rolldown/binding-linux-arm64-gnu@1.2.16':
optional: true
- '@rolldown/binding-linux-arm64-musl@1.2.5':
+ '@rolldown/binding-linux-arm64-musl@1.2.16':
optional: true
- '@rolldown/binding-linux-ppc64-gnu@1.2.5':
+ '@rolldown/binding-linux-ppc64-gnu@1.2.16':
optional: true
- '@rolldown/binding-linux-s390x-gnu@1.2.5':
+ '@rolldown/binding-linux-s390x-gnu@1.2.16':
optional: true
- '@rolldown/binding-linux-x64-gnu@1.2.5':
+ '@rolldown/binding-linux-x64-gnu@1.2.16':
optional: true
- '@rolldown/binding-linux-x64-musl@1.2.5':
+ '@rolldown/binding-linux-x64-musl@1.2.16':
optional: true
- '@rolldown/binding-openharmony-arm64@1.2.5':
+ '@rolldown/binding-openharmony-arm64@1.2.16':
optional: true
- '@rolldown/binding-win32-arm64-msvc@1.2.5':
+ '@rolldown/binding-win32-arm64-msvc@1.2.16':
optional: true
- '@rolldown/binding-win32-x64-msvc@1.2.5':
+ '@rolldown/binding-win32-x64-msvc@1.2.16':
optional: true
'@rolldown/pluginutils@1.0.1': {}
@@ -1500,13 +1565,13 @@ snapshots:
chai: 6.2.2
tinyrainbow: 3.1.1
- '@vitest/mocker@4.1.11(vite@8.2.2(@types/node@22.20.1)(esbuild@0.27.7))':
+ '@vitest/mocker@4.1.11(vite@8.3.6(@types/node@22.20.1)(esbuild@0.27.7))':
dependencies:
'@vitest/spy': 4.1.11
estree-walker: 3.0.3
magic-string: 0.30.21
optionalDependencies:
- vite: 8.2.2(@types/node@22.20.1)(esbuild@0.27.7)
+ vite: 8.3.6(@types/node@22.20.1)(esbuild@0.27.7)
'@vitest/pretty-format@4.1.11':
dependencies:
@@ -1554,9 +1619,9 @@ snapshots:
asynckit@0.4.0: {}
- axios@1.19.0:
+ axios@1.20.0:
dependencies:
- follow-redirects: 1.16.0
+ follow-redirects: 1.16.2
form-data: 4.0.6
https-proxy-agent: 5.0.1
proxy-from-env: 2.1.0
@@ -1672,7 +1737,7 @@ snapshots:
mlly: 1.8.2
rollup: 4.62.5
- follow-redirects@1.16.0: {}
+ follow-redirects@1.16.2: {}
form-data-encoder@1.7.2: {}
@@ -1800,7 +1865,7 @@ snapshots:
mem0ai@3.1.6:
dependencies:
- axios: 1.19.0
+ axios: 1.20.0
openai: 4.104.0(zod@3.25.76)
uuid: 11.1.1
zod: 3.25.76
@@ -1831,7 +1896,7 @@ snapshots:
object-assign: 4.1.1
thenify-all: 1.6.0
- nanoid@3.3.18: {}
+ nanoid@3.3.20: {}
node-domexception@1.0.0: {}
@@ -1863,6 +1928,8 @@ snapshots:
picomatch@4.0.5: {}
+ picomatch@4.0.7: {}
+
pirates@4.0.7: {}
pkg-types@1.3.1:
@@ -1871,17 +1938,17 @@ snapshots:
mlly: 1.8.2
pathe: 2.0.3
- postcss-load-config@6.0.1(postcss@8.5.26):
+ postcss-load-config@6.0.1(postcss@8.5.32):
dependencies:
lilconfig: 3.1.3
optionalDependencies:
- postcss: 8.5.26
+ postcss: 8.5.32
- postcss@8.5.26:
+ postcss@8.5.32:
dependencies:
- nanoid: 3.3.18
+ nanoid: 3.3.20
picocolors: 1.1.1
- source-map-js: 1.2.1
+ source-map-js: 1.2.2
proxy-from-env@2.1.0: {}
@@ -1889,26 +1956,26 @@ snapshots:
resolve-from@5.0.0: {}
- rolldown@1.2.5:
+ rolldown@1.2.16:
dependencies:
- '@oxc-project/types': 0.146.0
+ '@oxc-project/types': 0.156.0
'@rolldown/pluginutils': 1.0.1
optionalDependencies:
- '@rolldown/binding-android-arm-eabi': 1.2.5
- '@rolldown/binding-android-arm64': 1.2.5
- '@rolldown/binding-darwin-arm64': 1.2.5
- '@rolldown/binding-darwin-x64': 1.2.5
- '@rolldown/binding-freebsd-x64': 1.2.5
- '@rolldown/binding-linux-arm-gnueabihf': 1.2.5
- '@rolldown/binding-linux-arm64-gnu': 1.2.5
- '@rolldown/binding-linux-arm64-musl': 1.2.5
- '@rolldown/binding-linux-ppc64-gnu': 1.2.5
- '@rolldown/binding-linux-s390x-gnu': 1.2.5
- '@rolldown/binding-linux-x64-gnu': 1.2.5
- '@rolldown/binding-linux-x64-musl': 1.2.5
- '@rolldown/binding-openharmony-arm64': 1.2.5
- '@rolldown/binding-win32-arm64-msvc': 1.2.5
- '@rolldown/binding-win32-x64-msvc': 1.2.5
+ '@rolldown/binding-android-arm-eabi': 1.2.16
+ '@rolldown/binding-android-arm64': 1.2.16
+ '@rolldown/binding-darwin-arm64': 1.2.16
+ '@rolldown/binding-darwin-x64': 1.2.16
+ '@rolldown/binding-freebsd-x64': 1.2.16
+ '@rolldown/binding-linux-arm-gnueabihf': 1.2.16
+ '@rolldown/binding-linux-arm64-gnu': 1.2.16
+ '@rolldown/binding-linux-arm64-musl': 1.2.16
+ '@rolldown/binding-linux-ppc64-gnu': 1.2.16
+ '@rolldown/binding-linux-s390x-gnu': 1.2.16
+ '@rolldown/binding-linux-x64-gnu': 1.2.16
+ '@rolldown/binding-linux-x64-musl': 1.2.16
+ '@rolldown/binding-openharmony-arm64': 1.2.16
+ '@rolldown/binding-win32-arm64-msvc': 1.2.16
+ '@rolldown/binding-win32-x64-msvc': 1.2.16
rollup@4.62.5:
dependencies:
@@ -1944,7 +2011,7 @@ snapshots:
siginfo@2.0.0: {}
- source-map-js@1.2.1: {}
+ source-map-js@1.2.2: {}
source-map@0.7.6: {}
@@ -1989,7 +2056,7 @@ snapshots:
ts-interface-checker@0.1.13: {}
- tsup@8.5.1(postcss@8.5.26)(typescript@5.9.3):
+ tsup@8.5.1(postcss@8.5.32)(typescript@5.9.3):
dependencies:
bundle-require: 5.1.0(esbuild@0.27.7)
cac: 6.7.14
@@ -2000,7 +2067,7 @@ snapshots:
fix-dts-default-cjs-exports: 1.0.1
joycon: 3.1.1
picocolors: 1.1.1
- postcss-load-config: 6.0.1(postcss@8.5.26)
+ postcss-load-config: 6.0.1(postcss@8.5.32)
resolve-from: 5.0.0
rollup: 4.62.5
source-map: 0.7.6
@@ -2009,7 +2076,7 @@ snapshots:
tinyglobby: 0.2.17
tree-kill: 1.2.2
optionalDependencies:
- postcss: 8.5.26
+ postcss: 8.5.32
typescript: 5.9.3
transitivePeerDependencies:
- jiti
@@ -2027,12 +2094,12 @@ snapshots:
uuid@11.1.1: {}
- vite@8.2.2(@types/node@22.20.1)(esbuild@0.27.7):
+ vite@8.3.6(@types/node@22.20.1)(esbuild@0.27.7):
dependencies:
lightningcss: 1.33.0
- picomatch: 4.0.5
- postcss: 8.5.26
- rolldown: 1.2.5
+ picomatch: 4.0.7
+ postcss: 8.5.32
+ rolldown: 1.2.16
tinyglobby: 0.2.17
optionalDependencies:
'@types/node': 22.20.1
@@ -2042,7 +2109,7 @@ snapshots:
vitest@4.1.11(@types/node@22.20.1)(esbuild@0.27.7):
dependencies:
'@vitest/expect': 4.1.11
- '@vitest/mocker': 4.1.11(vite@8.2.2(@types/node@22.20.1)(esbuild@0.27.7))
+ '@vitest/mocker': 4.1.11(vite@8.3.6(@types/node@22.20.1)(esbuild@0.27.7))
'@vitest/pretty-format': 4.1.11
'@vitest/runner': 4.1.11
'@vitest/snapshot': 4.1.11
@@ -2059,7 +2126,7 @@ snapshots:
tinyexec: 1.3.0
tinyglobby: 0.2.17
tinyrainbow: 3.1.1
- vite: 8.2.2(@types/node@22.20.1)(esbuild@0.27.7)
+ vite: 8.3.6(@types/node@22.20.1)(esbuild@0.27.7)
why-is-node-running: 2.3.0
optionalDependencies:
'@types/node': 22.20.1
diff --git a/integrations/deepseek-plugin/src/formatting.ts b/integrations/deepseek-plugin/src/formatting.ts
index 63296a185..79bb6283f 100644
--- a/integrations/deepseek-plugin/src/formatting.ts
+++ b/integrations/deepseek-plugin/src/formatting.ts
@@ -1,69 +1,7 @@
-/**
- * Compact, token-cheap rendering of Mem0 results for the model context.
- *
- * Mirrors the format used by the sibling Mem0 plugins
- * (integrations/pi-agent-plugin/src/memory/formatting.ts) so a memory reads the
- * same way across every harness: `[category] text (age) [mem0:id]`. Dumping the
- * raw search envelope instead would spend most of the tokens on JSON scaffolding.
- */
-
-export interface MemoryLike {
- id: string;
- memory?: string;
- categories?: string[];
- createdAt?: Date | string;
-}
-
-export function formatAge(date: Date | string): string {
- const d = typeof date === "string" ? new Date(date) : date;
- const ms = Date.now() - d.getTime();
- const minutes = Math.floor(ms / 60_000);
- if (minutes < 60) return `${minutes}m ago`;
- const hours = Math.floor(minutes / 60);
- if (hours < 24) return `${hours}h ago`;
- const days = Math.floor(hours / 24);
- return `${days}d ago`;
-}
-
-export function formatMemoryCompact(mem: MemoryLike): string {
- const cat = mem.categories?.[0] ?? "uncategorized";
- const age = mem.createdAt ? ` (${formatAge(mem.createdAt)})` : "";
- return `[${cat}] ${mem.memory ?? "(empty)"}${age} [mem0:${mem.id}]`;
-}
-
-export function formatMemoryList(memories: MemoryLike[]): string {
- if (memories.length === 0) return "No memories found.";
- return memories
- .map((m, i) => `${i + 1}. ${formatMemoryCompact(m)}`)
- .join("\n");
-}
-
-/**
- * One-line confirmation for a write.
- *
- * `client.add` hits the async `/v3/memories/add/` endpoint, which returns
- * `{ event_id, status: "PENDING" }` โ extraction runs server-side *after* the
- * call returns, so the extracted memories are not in this response. Report the
- * write as queued in that case; only render a list when the backend actually
- * returns memories (older / OSS shapes).
- */
-export function formatAddResult(result: unknown): string {
- const items: MemoryLike[] = Array.isArray(result)
- ? (result as MemoryLike[])
- : ((result as { results?: MemoryLike[] } | null)?.results ??
- (result ? [result as MemoryLike] : []));
-
- const pending = items.find(
- (r) => (r as { status?: string }).status === "PENDING",
- ) as { eventId?: string; event_id?: string } | undefined;
- if (pending) {
- // The SDK camel-cases response keys (event_id -> eventId); accept either.
- const id = pending.eventId ?? pending.event_id;
- const evt = id ? ` (event ${id})` : "";
- return `Memory queued for background extraction${evt}; it will be searchable shortly.`;
- }
-
- if (items.length === 0) return "Memory stored.";
- const noun = items.length === 1 ? "memory" : "memories";
- return `Stored ${items.length} ${noun}:\n${formatMemoryList(items)}`;
-}
+export {
+ formatAddResult,
+ formatAge,
+ formatMemoryCompact,
+ formatMemoryList,
+} from "../../agent-plugin-core/typescript/src/formatting.ts";
+export type { MemoryLike } from "../../agent-plugin-core/typescript/src/formatting.ts";
diff --git a/integrations/deepseek-plugin/src/index.ts b/integrations/deepseek-plugin/src/index.ts
index 6cb9bef12..c5eb64390 100644
--- a/integrations/deepseek-plugin/src/index.ts
+++ b/integrations/deepseek-plugin/src/index.ts
@@ -6,37 +6,63 @@
* - `add_memory` stores a fact for future sessions
*
* A plugin is a Cordis module that exports `apply(ctx, config)`. Declaring
- * `inject = ['tools']` holds the plugin until the harness tool registry exists;
+ * `inject = ['tools', 'systemPrompt']` holds the plugin until the harness services exist;
* tools registered via `ctx.tools.register(...)` are auto-unregistered when the
* plugin unmounts (Cordis revertible effects).
*/
import type { Context } from "@deepseek-ai/cordis";
+import type {} from "@deepseek-ai/dsh-agent";
+import type { PromptAssembly } from "@deepseek-ai/dsh-system-prompt";
+import type {} from "@deepseek-ai/dsh-session";
import { defineTool } from "@deepseek-ai/dsh-tools";
import { MemoryClient } from "mem0ai";
import { formatMemoryList, formatAddResult } from "./formatting.ts";
import { truncateOutput } from "./output.ts";
import { resolveSearchFilters, resolveAddParams } from "./scoping.ts";
import { captureEvent, errorKind } from "./telemetry.ts";
+import { createMemoryLifecycle } from "../../agent-plugin-core/typescript/src/lifecycle.ts";
+import {
+ USER_RECALL_HEADING,
+ USER_SEARCH_QUERY_DESCRIPTION,
+ USER_SEARCH_TOOL_DESCRIPTION,
+} from "../../agent-plugin-core/typescript/src/prompts.ts";
export const name = "mem0";
-export const inject = ["tools"];
+export const inject = ["tools", "systemPrompt"];
// Tags writes so Mem0's backend attributes them to this integration in
-// telemetry. The backend keeps recognized values via its KNOWN_EVENT_SOURCES
-// allowlist; unknown values bucket into "OTHERS", so "DEEPSEEK_HARNESS" must be
-// added to that allowlist for usage to surface by name (a one-line backend PR,
-// same pattern as the ZAPIER / STRANDS sources).
+// telemetry. Values outside the backend's KNOWN_EVENT_SOURCES allowlist bucket
+// into "OTHERS"; this one is added by mem0ai/platform#3602 and reads as OTHERS
+// until that ships.
const SOURCE = "DEEPSEEK_HARNESS";
const DEFAULT_SEARCH_LIMIT = 10;
+const AUTO_RECALL_LIMIT = 5;
+
+interface HarnessMessage {
+ role: string;
+ content?: unknown;
+ source?: { kind?: string };
+}
+
+interface SessionState {
+ lifecycle: ReturnType;
+ messages: HarnessMessage[];
+}
export interface Config {
/** Mem0 API key. Defaults to the MEM0_API_KEY env var. */
apiKey?: string;
/** Default entity that owns the memories (Mem0 user scope). */
userId: string;
+ /** Explicitly allow model-selected cross-user access. Defaults to false. */
+ allowUserOverride?: boolean;
/** Optional Mem0 Platform base-URL override (on-prem / dedicated); defaults to api.mem0.ai. Not a switch to self-hosted OSS. */
host?: string;
+ /** Recall relevant memory before each model request. Defaults to true. */
+ autoRecall?: boolean;
+ /** Store completed turns automatically. Defaults to true. */
+ autoCapture?: boolean;
}
// Both tools return a single text string; the render is identical, so lift it
@@ -55,7 +81,7 @@ const scopeParams = {
userId: {
type: "string",
description:
- "Entity that owns the memory. Defaults to the plugin's configured userId; set this only to read or write another user's memories.",
+ "Entity that owns the memory. Defaults to the plugin's configured userId; cross-user overrides require allowUserOverride in plugin configuration.",
},
agentId: {
type: "string",
@@ -72,8 +98,8 @@ export function apply(ctx: Context, config: Config): void {
if (!apiKey) {
throw new Error("deepseek-plugin: set config.apiKey or the MEM0_API_KEY env var");
}
- const userId = config.userId;
- if (!userId) {
+ const userId = config.userId?.trim();
+ if (!userId || /^\*+$/.test(userId)) {
throw new Error("deepseek-plugin: config.userId is required");
}
@@ -81,18 +107,104 @@ export function apply(ctx: Context, config: Config): void {
apiKey,
...(config.host ? { host: config.host } : {}),
});
+ const toolLifecycle = createMemoryLifecycle();
+ const sessionStates = new WeakMap