From 8d3bbe5157c369ff599d90b6bb91d2c59bf11d99 Mon Sep 17 00:00:00 2001
From: "mintlify[bot]" <109931778+mintlify[bot]@users.noreply.github.com>
Date: Tue, 15 Sep 2026 13:54:01 +0000
Subject: [PATCH 01/54] docs: shorten hermes integration description to meet
SEO length
---
docs/integrations/hermes.mdx | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/docs/integrations/hermes.mdx b/docs/integrations/hermes.mdx
index dce08e63f..8ad3384c6 100644
--- a/docs/integrations/hermes.mdx
+++ b/docs/integrations/hermes.mdx
@@ -1,6 +1,6 @@
---
title: Hermes Agent
-description: "Add long-term memory to Hermes agents with Mem0: managed Platform, a self-hosted server, or fully local OSS — with current-turn recall and background fact extraction."
+description: "Add long-term memory to Hermes agents with Mem0 using the managed Platform, a self-hosted server, or fully local OSS."
---
Add long-term memory to [Hermes Agent](https://github.com/NousResearch/hermes-agent), a self-improving AI agent CLI by Nous Research. Hermes has a pluggable memory system, and Mem0 is one of the supported providers. Once enabled, Mem0 learns facts from your conversations and surfaces relevant ones for the current question, without slowing down the chat.
From b51f7692f002d4f8719dd5c0f23d4d129003757d Mon Sep 17 00:00:00 2001
From: PowderXu <126909591+PowderXu@users.noreply.github.com>
Date: Tue, 15 Sep 2026 10:11:46 -0400
Subject: [PATCH 02/54] docs(upstash): correct the default collection namespace
(#7287)
---
docs/components/vectordbs/dbs/upstash-vector.mdx | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/docs/components/vectordbs/dbs/upstash-vector.mdx b/docs/components/vectordbs/dbs/upstash-vector.mdx
index 1858516f8..90fa49397 100644
--- a/docs/components/vectordbs/dbs/upstash-vector.mdx
+++ b/docs/components/vectordbs/dbs/upstash-vector.mdx
@@ -102,7 +102,7 @@ Here are the parameters available for configuring Upstash Vector:
| `url` | URL for the Upstash Vector index | `None` |
| `token` | Token for the Upstash Vector index | `None` |
| `client` | An `upstash_vector.Index` instance | `None` |
-| `collection_name` | The default namespace used | `""` |
+| `collection_name` | The default namespace used | `"mem0"` |
| `enable_embeddings` | Whether to use Upstash embeddings | `False` |
From 0df3e4b87df20785f0741370c75e44428796193e Mon Sep 17 00:00:00 2001
From: Paurush Mittal <137642194+paurushmittal@users.noreply.github.com>
Date: Wed, 16 Sep 2026 17:14:33 +0530
Subject: [PATCH 03/54] fix(docs): correct rendered titles and remaining SEO
links (#7344)
---
docs/api-reference.mdx | 5 ++---
docs/api-reference/memory/delete-memory.mdx | 5 ++---
docs/api-reference/memory/update-memory.mdx | 5 ++---
docs/api-reference/organization/add-org-member.mdx | 5 ++---
docs/api-reference/organization/get-org-members.mdx | 5 ++---
docs/api-reference/project/add-project-member.mdx | 5 ++---
docs/api-reference/project/get-project-members.mdx | 5 ++---
docs/components/embedders/config.mdx | 5 ++---
docs/components/embedders/models/aws-bedrock.mdx | 5 ++---
docs/components/embedders/models/azure-openai.mdx | 5 ++---
docs/components/embedders/models/google-ai.mdx | 5 ++---
docs/components/embedders/models/langchain.mdx | 5 ++---
docs/components/embedders/models/lmstudio.mdx | 5 ++---
docs/components/embedders/models/ollama.mdx | 5 ++---
docs/components/embedders/models/openai.mdx | 5 ++---
docs/components/embedders/models/together.mdx | 5 ++---
docs/components/embedders/overview.mdx | 5 ++---
docs/components/llms/config.mdx | 5 ++---
docs/components/llms/models/aws-bedrock.mdx | 5 ++---
docs/components/llms/models/azure-openai.mdx | 5 ++---
docs/components/llms/models/deepseek.mdx | 2 +-
docs/components/llms/models/google-ai.mdx | 5 ++---
docs/components/llms/models/langchain.mdx | 5 ++---
docs/components/llms/models/lmstudio.mdx | 7 +++----
docs/components/llms/models/minimax.mdx | 2 +-
docs/components/llms/models/ollama.mdx | 5 ++---
docs/components/llms/models/openai.mdx | 5 ++---
docs/components/llms/models/together.mdx | 5 ++---
docs/components/llms/models/xAI.mdx | 5 ++---
docs/components/llms/overview.mdx | 5 ++---
docs/components/rerankers/overview.mdx | 5 ++---
docs/components/vectordbs/config.mdx | 5 ++---
docs/components/vectordbs/dbs/langchain.mdx | 5 ++---
docs/components/vectordbs/overview.mdx | 5 ++---
docs/cookbooks/overview.mdx | 5 ++---
docs/core-concepts/memory-operations/delete.mdx | 5 ++---
docs/core-concepts/memory-operations/update.mdx | 5 ++---
docs/integrations.mdx | 5 ++---
docs/integrations/aws-bedrock.mdx | 5 ++---
docs/integrations/codex.mdx | 2 +-
docs/integrations/flowise.mdx | 2 +-
docs/integrations/langchain.mdx | 5 ++---
docs/integrations/n8n.mdx | 5 ++---
docs/open-source/features/custom-instructions.mdx | 5 ++---
docs/open-source/features/multimodal-support.mdx | 5 ++---
docs/open-source/features/overview.mdx | 5 ++---
docs/open-source/features/rest-api.mdx | 2 +-
docs/open-source/overview.mdx | 5 ++---
docs/platform/cli.mdx | 5 ++---
docs/platform/features/custom-instructions.mdx | 5 ++---
docs/platform/features/multimodal-support.mdx | 5 ++---
docs/platform/overview.mdx | 5 ++---
52 files changed, 100 insertions(+), 147 deletions(-)
diff --git a/docs/api-reference.mdx b/docs/api-reference.mdx
index 1aac9708e..2477bf313 100644
--- a/docs/api-reference.mdx
+++ b/docs/api-reference.mdx
@@ -1,7 +1,6 @@
---
-title: "Overview"
-seo:
- title: "API Reference Overview - Mem0"
+title: "API Reference Overview"
+sidebarTitle: "Overview"
icon: "terminal"
iconType: "solid"
description: "REST APIs for memory management, search, and entity operations"
diff --git a/docs/api-reference/memory/delete-memory.mdx b/docs/api-reference/memory/delete-memory.mdx
index 1ff61da9e..87084b005 100644
--- a/docs/api-reference/memory/delete-memory.mdx
+++ b/docs/api-reference/memory/delete-memory.mdx
@@ -1,7 +1,6 @@
---
-title: 'Delete Memory'
-seo:
- title: "Delete Memory API Endpoint - Mem0"
+title: "Delete Memory API Endpoint"
+sidebarTitle: "Delete Memory"
description: "Delete a single memory by its unique memory ID from the Mem0 platform using the DELETE endpoint."
openapi: delete /v1/memories/{memory_id}/
---
\ No newline at end of file
diff --git a/docs/api-reference/memory/update-memory.mdx b/docs/api-reference/memory/update-memory.mdx
index 4818be587..a8a53a2e0 100644
--- a/docs/api-reference/memory/update-memory.mdx
+++ b/docs/api-reference/memory/update-memory.mdx
@@ -1,7 +1,6 @@
---
-title: 'Update Memory'
-seo:
- title: "Update Memory API Endpoint - Mem0"
+title: "Update Memory API Endpoint"
+sidebarTitle: "Update Memory"
description: "Update the content, metadata, timestamp, or expiration date of a single memory by its unique ID using the PUT endpoint."
openapi: put /v1/memories/{memory_id}/
---
diff --git a/docs/api-reference/organization/add-org-member.mdx b/docs/api-reference/organization/add-org-member.mdx
index 2b0f00f4f..35237ffb6 100644
--- a/docs/api-reference/organization/add-org-member.mdx
+++ b/docs/api-reference/organization/add-org-member.mdx
@@ -1,7 +1,6 @@
---
-title: 'Add Member'
-seo:
- title: "Add Organization Member API Endpoint - Mem0"
+title: "Add Organization Member API Endpoint"
+sidebarTitle: "Add Member"
description: "Add a new member to an organization with a specified role such as READER or OWNER access level."
openapi: post /api/v1/orgs/organizations/{org_id}/members/
---
diff --git a/docs/api-reference/organization/get-org-members.mdx b/docs/api-reference/organization/get-org-members.mdx
index b1a401195..333859d4c 100644
--- a/docs/api-reference/organization/get-org-members.mdx
+++ b/docs/api-reference/organization/get-org-members.mdx
@@ -1,7 +1,6 @@
---
-title: 'Get Members'
-seo:
- title: "Get Organization Members API Endpoint - Mem0"
+title: "Get Organization Members API Endpoint"
+sidebarTitle: "Get Members"
description: "Retrieve a list of all members belonging to a specific organization on the Mem0 platform."
openapi: get /api/v1/orgs/organizations/{org_id}/members/
---
\ No newline at end of file
diff --git a/docs/api-reference/project/add-project-member.mdx b/docs/api-reference/project/add-project-member.mdx
index f3e78c7f1..d1338f1b6 100644
--- a/docs/api-reference/project/add-project-member.mdx
+++ b/docs/api-reference/project/add-project-member.mdx
@@ -1,7 +1,6 @@
---
-title: 'Add Member'
-seo:
- title: "Add Project Member API Endpoint - Mem0"
+title: "Add Project Member API Endpoint"
+sidebarTitle: "Add Member"
description: "Add a new member to a project with a specified role such as READER or OWNER access level."
openapi: post /api/v1/orgs/organizations/{org_id}/projects/{project_id}/members/
---
diff --git a/docs/api-reference/project/get-project-members.mdx b/docs/api-reference/project/get-project-members.mdx
index 722aafeba..35a4d5eb8 100644
--- a/docs/api-reference/project/get-project-members.mdx
+++ b/docs/api-reference/project/get-project-members.mdx
@@ -1,7 +1,6 @@
---
-title: 'Get Members'
-seo:
- title: "Get Project Members API Endpoint - Mem0"
+title: "Get Project Members API Endpoint"
+sidebarTitle: "Get Members"
description: "Retrieve a list of all members belonging to a specific project on the Mem0 platform."
openapi: get /api/v1/orgs/organizations/{org_id}/projects/{project_id}/members/
---
\ No newline at end of file
diff --git a/docs/components/embedders/config.mdx b/docs/components/embedders/config.mdx
index dd107fc04..577db6353 100644
--- a/docs/components/embedders/config.mdx
+++ b/docs/components/embedders/config.mdx
@@ -1,7 +1,6 @@
---
-title: Configurations
-seo:
- title: "Embedder Configuration Reference - Mem0"
+title: "Embedder Configuration Reference"
+sidebarTitle: "Configurations"
description: "Reference for embedder configuration options in Mem0, including provider selection and model settings."
---
diff --git a/docs/components/embedders/models/aws-bedrock.mdx b/docs/components/embedders/models/aws-bedrock.mdx
index d831a5aad..2528a79fe 100644
--- a/docs/components/embedders/models/aws-bedrock.mdx
+++ b/docs/components/embedders/models/aws-bedrock.mdx
@@ -1,7 +1,6 @@
---
-title: AWS Bedrock
-seo:
- title: "AWS Bedrock as Embedding Provider - Mem0"
+title: "AWS Bedrock as Embedding Provider"
+sidebarTitle: "AWS Bedrock"
description: "Configure AWS Bedrock as an embedding provider in Mem0 with IAM credentials and boto3 authentication."
---
diff --git a/docs/components/embedders/models/azure-openai.mdx b/docs/components/embedders/models/azure-openai.mdx
index 1b0e7cb9c..eb1086444 100644
--- a/docs/components/embedders/models/azure-openai.mdx
+++ b/docs/components/embedders/models/azure-openai.mdx
@@ -1,7 +1,6 @@
---
-title: Azure OpenAI
-seo:
- title: "Azure OpenAI as Embedding Provider - Mem0"
+title: "Azure OpenAI as Embedding Provider"
+sidebarTitle: "Azure OpenAI"
description: "Configure Azure OpenAI as an embedding provider in Mem0 with API key, deployment, and endpoint settings."
---
diff --git a/docs/components/embedders/models/google-ai.mdx b/docs/components/embedders/models/google-ai.mdx
index c9a67bf1c..726dd83e0 100644
--- a/docs/components/embedders/models/google-ai.mdx
+++ b/docs/components/embedders/models/google-ai.mdx
@@ -1,7 +1,6 @@
---
-title: Google AI
-seo:
- title: "Google AI as Embedding Provider - Mem0"
+title: "Google AI as Embedding Provider"
+sidebarTitle: "Google AI"
description: "Configure Google AI as an embedding provider in Mem0 using Gemini models and the GOOGLE_API_KEY variable."
---
diff --git a/docs/components/embedders/models/langchain.mdx b/docs/components/embedders/models/langchain.mdx
index 05908c295..e72ab32e7 100644
--- a/docs/components/embedders/models/langchain.mdx
+++ b/docs/components/embedders/models/langchain.mdx
@@ -1,7 +1,6 @@
---
-title: LangChain
-seo:
- title: "LangChain as Embedding Provider - Mem0"
+title: "LangChain as Embedding Provider"
+sidebarTitle: "LangChain"
description: "Use LangChain as an embedding provider in Mem0 to access a wide range of models through a unified interface."
---
diff --git a/docs/components/embedders/models/lmstudio.mdx b/docs/components/embedders/models/lmstudio.mdx
index 8fe656be0..5ab13b08e 100644
--- a/docs/components/embedders/models/lmstudio.mdx
+++ b/docs/components/embedders/models/lmstudio.mdx
@@ -1,7 +1,6 @@
---
-title: "LM Studio"
-seo:
- title: "LM Studio as Embedding Provider - Mem0"
+title: "LM Studio as Embedding Provider"
+sidebarTitle: "LM Studio"
description: "Configure LM Studio as an embedding provider in Mem0 for local embedding generation with models like nomic-embed-text."
---
You can use embedding models from LM Studio to run Mem0 locally.
diff --git a/docs/components/embedders/models/ollama.mdx b/docs/components/embedders/models/ollama.mdx
index cc3f65e78..e4345b727 100644
--- a/docs/components/embedders/models/ollama.mdx
+++ b/docs/components/embedders/models/ollama.mdx
@@ -1,7 +1,6 @@
---
-title: "Ollama"
-seo:
- title: "Ollama as Embedding Provider - Mem0"
+title: "Ollama as Embedding Provider"
+sidebarTitle: "Ollama"
description: "Configure Ollama as an embedding provider in Mem0 to generate embeddings locally using open-source models."
---
You can use embedding models from Ollama to run Mem0 locally.
diff --git a/docs/components/embedders/models/openai.mdx b/docs/components/embedders/models/openai.mdx
index 376ffb87d..4acf136aa 100644
--- a/docs/components/embedders/models/openai.mdx
+++ b/docs/components/embedders/models/openai.mdx
@@ -1,7 +1,6 @@
---
-title: OpenAI
-seo:
- title: "OpenAI as Embedding Provider - Mem0"
+title: "OpenAI as Embedding Provider"
+sidebarTitle: "OpenAI"
description: "Configure OpenAI as an embedding provider in Mem0 using models like text-embedding-3-large for vector generation."
---
diff --git a/docs/components/embedders/models/together.mdx b/docs/components/embedders/models/together.mdx
index 1cc4329c1..75f44227e 100644
--- a/docs/components/embedders/models/together.mdx
+++ b/docs/components/embedders/models/together.mdx
@@ -1,7 +1,6 @@
---
-title: Together
-seo:
- title: "Together AI as Embedding Provider - Mem0"
+title: "Together AI as Embedding Provider"
+sidebarTitle: "Together"
description: "Configure Together AI as an embedding provider in Mem0 with support for 1024-dimensional embedding models."
---
diff --git a/docs/components/embedders/overview.mdx b/docs/components/embedders/overview.mdx
index e8cffd476..28f649091 100644
--- a/docs/components/embedders/overview.mdx
+++ b/docs/components/embedders/overview.mdx
@@ -1,7 +1,6 @@
---
-title: Overview
-seo:
- title: "Embedding Providers Overview - Mem0"
+title: "Embedding Providers Overview"
+sidebarTitle: Overview
description: "Overview of all supported embedding model providers in Mem0, including OpenAI, Azure, Ollama, and more."
---
diff --git a/docs/components/llms/config.mdx b/docs/components/llms/config.mdx
index 5482376dc..5c67c876a 100644
--- a/docs/components/llms/config.mdx
+++ b/docs/components/llms/config.mdx
@@ -1,7 +1,6 @@
---
-title: Configurations
-seo:
- title: "LLM Configuration Reference - Mem0"
+title: "LLM Configuration Reference"
+sidebarTitle: "Configurations"
description: "Reference for LLM configuration options in Mem0 for Python and TypeScript, including value precedence rules."
---
diff --git a/docs/components/llms/models/aws-bedrock.mdx b/docs/components/llms/models/aws-bedrock.mdx
index e75971391..f6f940024 100644
--- a/docs/components/llms/models/aws-bedrock.mdx
+++ b/docs/components/llms/models/aws-bedrock.mdx
@@ -1,7 +1,6 @@
---
-title: AWS Bedrock
-seo:
- title: "AWS Bedrock as LLM Provider - Mem0"
+title: "AWS Bedrock as LLM Provider"
+sidebarTitle: "AWS Bedrock"
description: "Configure AWS Bedrock as an LLM provider in Mem0 with IAM authentication and Claude model support."
---
diff --git a/docs/components/llms/models/azure-openai.mdx b/docs/components/llms/models/azure-openai.mdx
index 550ff0fce..a81d3ec5f 100644
--- a/docs/components/llms/models/azure-openai.mdx
+++ b/docs/components/llms/models/azure-openai.mdx
@@ -1,7 +1,6 @@
---
-title: Azure OpenAI
-seo:
- title: "Azure OpenAI as LLM Provider - Mem0"
+title: "Azure OpenAI as LLM Provider"
+sidebarTitle: "Azure OpenAI"
description: "Configure Azure OpenAI as an LLM provider in Mem0 with Azure Identity authentication and deployment settings."
---
diff --git a/docs/components/llms/models/deepseek.mdx b/docs/components/llms/models/deepseek.mdx
index ef178382a..6d9ccdb0f 100644
--- a/docs/components/llms/models/deepseek.mdx
+++ b/docs/components/llms/models/deepseek.mdx
@@ -3,7 +3,7 @@ title: DeepSeek
description: "Configure DeepSeek as an LLM provider in Mem0 with API key setup and optional custom endpoint configuration."
---
-To use DeepSeek LLM models, you have to set the `DEEPSEEK_API_KEY` environment variable. You can also optionally set `DEEPSEEK_API_BASE` if you need to use a different API endpoint (defaults to "https://api.deepseek.com").
+To use DeepSeek LLM models, you have to set the `DEEPSEEK_API_KEY` environment variable. You can also optionally set `DEEPSEEK_API_BASE` if you need to use a different API endpoint (defaults to `https://api.deepseek.com`).
## Usage
diff --git a/docs/components/llms/models/google-ai.mdx b/docs/components/llms/models/google-ai.mdx
index ba5e50d07..5cb7a576e 100644
--- a/docs/components/llms/models/google-ai.mdx
+++ b/docs/components/llms/models/google-ai.mdx
@@ -1,7 +1,6 @@
---
-title: Google AI
-seo:
- title: "Google AI as LLM Provider - Mem0"
+title: "Google AI as LLM Provider"
+sidebarTitle: "Google AI"
description: "Configure Google Gemini as an LLM provider in Mem0 using the google.genai SDK and GOOGLE_API_KEY variable."
---
diff --git a/docs/components/llms/models/langchain.mdx b/docs/components/llms/models/langchain.mdx
index b7676ece2..2bace4cb9 100644
--- a/docs/components/llms/models/langchain.mdx
+++ b/docs/components/llms/models/langchain.mdx
@@ -1,7 +1,6 @@
---
-title: LangChain
-seo:
- title: "LangChain as LLM Provider - Mem0"
+title: "LangChain as LLM Provider"
+sidebarTitle: "LangChain"
description: "Use LangChain as an LLM provider in Mem0 to integrate with various chat models through a unified interface."
---
diff --git a/docs/components/llms/models/lmstudio.mdx b/docs/components/llms/models/lmstudio.mdx
index 727ede319..192fe64e2 100644
--- a/docs/components/llms/models/lmstudio.mdx
+++ b/docs/components/llms/models/lmstudio.mdx
@@ -1,7 +1,6 @@
---
-title: LM Studio
-seo:
- title: "LM Studio as LLM Provider - Mem0"
+title: "LM Studio as LLM Provider"
+sidebarTitle: "LM Studio"
description: "Configure LM Studio as an LLM provider in Mem0 for running local language models via an OpenAI-compatible API."
---
@@ -78,7 +77,7 @@ m.add(messages, user_id="alice123", metadata={"category": "movies"})
To use LM Studio, you need to:
1. Download and install [LM Studio](https://lmstudio.ai/)
2. Start a local server from the "Server" tab
- 3. Set the appropriate `lmstudio_base_url` in your configuration (default is usually http://localhost:1234/v1)
+ 3. Set the appropriate `lmstudio_base_url` in your configuration (default is usually `http://localhost:1234/v1`)
## Config
diff --git a/docs/components/llms/models/minimax.mdx b/docs/components/llms/models/minimax.mdx
index d885324e3..3d5cf36ac 100644
--- a/docs/components/llms/models/minimax.mdx
+++ b/docs/components/llms/models/minimax.mdx
@@ -3,7 +3,7 @@ title: MiniMax
description: "Configure MiniMax as an LLM provider in Mem0 with API key setup and optional custom endpoint configuration."
---
-To use MiniMax LLM models, you have to set the `MINIMAX_API_KEY` environment variable. You can also optionally set `MINIMAX_API_BASE` if you need to use a different API endpoint (defaults to "https://api.minimax.io/v1").
+To use MiniMax LLM models, you have to set the `MINIMAX_API_KEY` environment variable. You can also optionally set `MINIMAX_API_BASE` if you need to use a different API endpoint (defaults to `https://api.minimax.io/v1`).
## Usage
diff --git a/docs/components/llms/models/ollama.mdx b/docs/components/llms/models/ollama.mdx
index 2d6133575..7aef3d948 100644
--- a/docs/components/llms/models/ollama.mdx
+++ b/docs/components/llms/models/ollama.mdx
@@ -1,7 +1,6 @@
---
-title: Ollama
-seo:
- title: "Ollama as LLM Provider - Mem0"
+title: "Ollama as LLM Provider"
+sidebarTitle: "Ollama"
description: "Configure Ollama as an LLM provider in Mem0 for running local language models with tool-calling support."
---
diff --git a/docs/components/llms/models/openai.mdx b/docs/components/llms/models/openai.mdx
index 5fe67ffb0..12e709b1f 100644
--- a/docs/components/llms/models/openai.mdx
+++ b/docs/components/llms/models/openai.mdx
@@ -1,7 +1,6 @@
---
-title: OpenAI
-seo:
- title: "OpenAI as LLM Provider - Mem0"
+title: "OpenAI as LLM Provider"
+sidebarTitle: "OpenAI"
description: "Configure OpenAI as an LLM provider in Mem0 with support for GPT models and Openrouter compatibility."
---
diff --git a/docs/components/llms/models/together.mdx b/docs/components/llms/models/together.mdx
index 314564e61..d80b0592f 100644
--- a/docs/components/llms/models/together.mdx
+++ b/docs/components/llms/models/together.mdx
@@ -1,7 +1,6 @@
---
-title: Together
-seo:
- title: "Together AI as LLM Provider - Mem0"
+title: "Together AI as LLM Provider"
+sidebarTitle: "Together"
description: "Configure Together AI as an LLM provider in Mem0 with API key setup and optional custom endpoint configuration."
---
diff --git a/docs/components/llms/models/xAI.mdx b/docs/components/llms/models/xAI.mdx
index 3c4ff4edc..59d41444a 100644
--- a/docs/components/llms/models/xAI.mdx
+++ b/docs/components/llms/models/xAI.mdx
@@ -1,7 +1,6 @@
---
-title: xAI
-seo:
- title: "xAI Grok as LLM Provider - Mem0"
+title: "xAI Grok as LLM Provider"
+sidebarTitle: "xAI"
description: "Configure xAI Grok models as an LLM provider in Mem0 with API key setup and usage examples."
---
diff --git a/docs/components/llms/overview.mdx b/docs/components/llms/overview.mdx
index e500f58cc..99755a9d1 100644
--- a/docs/components/llms/overview.mdx
+++ b/docs/components/llms/overview.mdx
@@ -1,7 +1,6 @@
---
-title: Overview
-seo:
- title: "LLM Providers Overview - Mem0"
+title: "LLM Providers Overview"
+sidebarTitle: Overview
description: "Overview of all supported LLM providers in Mem0, including OpenAI, Anthropic, Groq, Ollama, and more."
---
diff --git a/docs/components/rerankers/overview.mdx b/docs/components/rerankers/overview.mdx
index 8ec18c4e7..b5cfde3a9 100644
--- a/docs/components/rerankers/overview.mdx
+++ b/docs/components/rerankers/overview.mdx
@@ -1,7 +1,6 @@
---
-title: Overview
-seo:
- title: "Reranker Providers Overview - Mem0"
+title: "Reranker Providers Overview"
+sidebarTitle: "Overview"
description: 'Pick the right reranker path to boost Mem0 search relevance.'
---
diff --git a/docs/components/vectordbs/config.mdx b/docs/components/vectordbs/config.mdx
index 2fcd6fa7a..d48dc1672 100644
--- a/docs/components/vectordbs/config.mdx
+++ b/docs/components/vectordbs/config.mdx
@@ -1,7 +1,6 @@
---
-title: Configurations
-seo:
- title: "Vector Store Configuration Reference - Mem0"
+title: "Vector Store Configuration Reference"
+sidebarTitle: "Configurations"
description: "Reference for vector database configuration options in Mem0, including provider selection and connection settings."
---
diff --git a/docs/components/vectordbs/dbs/langchain.mdx b/docs/components/vectordbs/dbs/langchain.mdx
index 0ff348466..10cbee109 100644
--- a/docs/components/vectordbs/dbs/langchain.mdx
+++ b/docs/components/vectordbs/dbs/langchain.mdx
@@ -1,7 +1,6 @@
---
-title: LangChain
-seo:
- title: "LangChain as Vector Store Provider - Mem0"
+title: "LangChain as Vector Store Provider"
+sidebarTitle: "LangChain"
description: "Use LangChain as a unified vector store provider in Mem0 to access multiple vector databases through one interface."
---
diff --git a/docs/components/vectordbs/overview.mdx b/docs/components/vectordbs/overview.mdx
index 2d7085d61..21f979c95 100644
--- a/docs/components/vectordbs/overview.mdx
+++ b/docs/components/vectordbs/overview.mdx
@@ -1,7 +1,6 @@
---
-title: Overview
-seo:
- title: "Vector Store Providers Overview - Mem0"
+title: "Vector Store Providers Overview"
+sidebarTitle: "Overview"
description: "Overview of all supported vector databases in Mem0, including Qdrant, Chroma, PGVector, Pinecone, Oracle, and more."
---
diff --git a/docs/cookbooks/overview.mdx b/docs/cookbooks/overview.mdx
index df98e590c..c8434e771 100644
--- a/docs/cookbooks/overview.mdx
+++ b/docs/cookbooks/overview.mdx
@@ -1,7 +1,6 @@
---
-title: Overview
-seo:
- title: "Cookbooks and Tutorials - Mem0"
+title: "Cookbooks and Tutorials"
+sidebarTitle: "Overview"
description: "Browse cookbook examples and tutorials for building AI applications with Mem0, from companion chatbots to AI agents."
---
diff --git a/docs/core-concepts/memory-operations/delete.mdx b/docs/core-concepts/memory-operations/delete.mdx
index 694546f8e..eb8f4c8c9 100644
--- a/docs/core-concepts/memory-operations/delete.mdx
+++ b/docs/core-concepts/memory-operations/delete.mdx
@@ -1,7 +1,6 @@
---
-title: Delete Memory
-seo:
- title: "Delete Memory Operation - Mem0"
+title: "Delete Memory Operation"
+sidebarTitle: "Delete Memory"
description: Remove memories from Mem0 either individually, in bulk, or via filters.
icon: "trash"
iconType: "solid"
diff --git a/docs/core-concepts/memory-operations/update.mdx b/docs/core-concepts/memory-operations/update.mdx
index b53af5559..b1e190b47 100644
--- a/docs/core-concepts/memory-operations/update.mdx
+++ b/docs/core-concepts/memory-operations/update.mdx
@@ -1,7 +1,6 @@
---
-title: Update Memory
-seo:
- title: "Update Memory Operation - Mem0"
+title: "Update Memory Operation"
+sidebarTitle: "Update Memory"
description: Modify an existing memory by updating its content or metadata.
icon: "pen-to-square"
iconType: "solid"
diff --git a/docs/integrations.mdx b/docs/integrations.mdx
index 138e6cffe..a912afcad 100644
--- a/docs/integrations.mdx
+++ b/docs/integrations.mdx
@@ -1,7 +1,6 @@
---
-title: Overview
-seo:
- title: "Integrations Overview - Mem0"
+title: "Integrations Overview"
+sidebarTitle: "Overview"
description: "Overview of Mem0 integrations with popular AI frameworks and tools for persistent memory and context management."
---
diff --git a/docs/integrations/aws-bedrock.mdx b/docs/integrations/aws-bedrock.mdx
index 55c757f16..069893fc6 100644
--- a/docs/integrations/aws-bedrock.mdx
+++ b/docs/integrations/aws-bedrock.mdx
@@ -1,7 +1,6 @@
---
-title: AWS Bedrock
-seo:
- title: "AWS Bedrock Integration with Mem0"
+title: "AWS Bedrock Integration"
+sidebarTitle: "AWS Bedrock"
description: "Use Mem0 with AWS Bedrock and OpenSearch Service for cloud-native persistent semantic memory storage."
---
diff --git a/docs/integrations/codex.mdx b/docs/integrations/codex.mdx
index d0ad0735f..a91f4f8f0 100644
--- a/docs/integrations/codex.mdx
+++ b/docs/integrations/codex.mdx
@@ -3,7 +3,7 @@ title: Codex
description: "Add persistent memory to OpenAI Codex with automatic capture, automatic recall, a search tool, and six memory skills."
---
-Add persistent memory to [**OpenAI Codex**](https://openai.com/index/codex/) with the Mem0 plugin. Codex forgets everything between tasks. This plugin fixes that by connecting to Mem0's cloud memory layer via MCP, automatically capturing learnings at key lifecycle points, and retrieving relevant context on the first prompt of a session. Codex can use the search tool for recall later in the session.
+Add persistent memory to [**OpenAI Codex**](https://openai.com/codex/) with the Mem0 plugin. Codex forgets everything between tasks. This plugin fixes that by connecting to Mem0's cloud memory layer via MCP, automatically capturing learnings at key lifecycle points, and retrieving relevant context on the first prompt of a session. Codex can use the search tool for recall later in the session.
Current plugin version: `0.3.1`.
diff --git a/docs/integrations/flowise.mdx b/docs/integrations/flowise.mdx
index 790a470fb..56649eb7b 100644
--- a/docs/integrations/flowise.mdx
+++ b/docs/integrations/flowise.mdx
@@ -23,7 +23,7 @@ npm install -g flowise
npx flowise start
```
-2. Access to the Flowise UI at http://localhost:3000
+2. Access to the Flowise UI at `http://localhost:3000`
3. Basic familiarity with [Flowise's LLM orchestration](https://flowiseai.com/#features) concepts
## Setup and Configuration
diff --git a/docs/integrations/langchain.mdx b/docs/integrations/langchain.mdx
index 2f8d1a7a9..ae8e41ef3 100644
--- a/docs/integrations/langchain.mdx
+++ b/docs/integrations/langchain.mdx
@@ -1,7 +1,6 @@
---
-title: Langchain
-seo:
- title: "LangChain Integration with Mem0"
+title: "LangChain Integration"
+sidebarTitle: "Langchain"
description: "Build personalized AI agents using LangChain for conversation flow and Mem0 for long-term memory retention."
---
diff --git a/docs/integrations/n8n.mdx b/docs/integrations/n8n.mdx
index b9d345d6b..f53358b77 100644
--- a/docs/integrations/n8n.mdx
+++ b/docs/integrations/n8n.mdx
@@ -1,7 +1,6 @@
---
-title: n8n
-seo:
- title: "n8n Integration with Mem0"
+title: "n8n Integration"
+sidebarTitle: "n8n"
description: "Add long-term memory to n8n workflows and AI Agents with the Mem0 community node, no code required."
---
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/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/features/custom-instructions.mdx b/docs/platform/features/custom-instructions.mdx
index 923c8f5dc..8b5b1f35e 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'
---
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/overview.mdx b/docs/platform/overview.mdx
index 35933c511..ddb5ff405 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"
---
From f5220ff8d4236f2369a19b554f76a47059deb2b6 Mon Sep 17 00:00:00 2001
From: ANIRUDDHA ADAK
Date: Thu, 17 Sep 2026 19:23:45 +0530
Subject: [PATCH 04/54] fix(security): bump next to 15.5.24, patches
GHSA-p293-qw3h-jr36 (#7320)
---
examples/mem0-demo/package.json | 2 +-
server/dashboard/package.json | 2 +-
server/dashboard/pnpm-lock.yaml | 84 ++++++++++++++++-----------------
3 files changed, 44 insertions(+), 44 deletions(-)
diff --git a/examples/mem0-demo/package.json b/examples/mem0-demo/package.json
index ec5b7c61c..ef1f8d20a 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.24",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"react-markdown": "^10.0.1",
diff --git a/server/dashboard/package.json b/server/dashboard/package.json
index 7d1b86432..d2ce90831 100644
--- a/server/dashboard/package.json
+++ b/server/dashboard/package.json
@@ -45,7 +45,7 @@
"framer-motion": "^12.23.12",
"lodash": "^4.18.1",
"lucide-react": "^0.542.0",
- "next": "15.5.21",
+ "next": "15.5.24",
"next-themes": "^0.4.4",
"react": "^19.0.0",
"react-copy-to-clipboard": "^5.1.0",
diff --git a/server/dashboard/pnpm-lock.yaml b/server/dashboard/pnpm-lock.yaml
index acbd0b7eb..1fe88f38f 100644
--- a/server/dashboard/pnpm-lock.yaml
+++ b/server/dashboard/pnpm-lock.yaml
@@ -122,8 +122,8 @@ importers:
specifier: ^0.542.0
version: 0.542.0(react@19.2.7)
next:
- specifier: 15.5.21
- version: 15.5.21(@types/node@22.5.4)(react-dom@19.2.7(react@19.2.7))(react@19.2.7)
+ specifier: 15.5.24
+ version: 15.5.24(@types/node@22.5.4)(react-dom@19.2.7(react@19.2.7))(react@19.2.7)
next-themes:
specifier: ^0.4.4
version: 0.4.6(react-dom@19.2.7(react@19.2.7))(react@19.2.7)
@@ -476,60 +476,60 @@ packages:
'@emnapi/core': ^1.7.1
'@emnapi/runtime': ^1.7.1
- '@next/env@15.5.21':
- resolution: {integrity: sha512-hjJI/GfrjWHgNguRIBzItjRRu0m3Nrz17GhxsjuHfjIvg9hyg3239REd2dpI+bpMTFuVrVprHzEQ19m++cDtbw==}
+ '@next/env@15.5.24':
+ resolution: {integrity: sha512-mBDF7T0XKZjs9SpUAl0buizVO+O02ULjOvWX8o/AZo/5AGw/UAS1Zzcylmd4pqbftzmKQi+L/nB4jgBYKEAl5Q==}
'@next/eslint-plugin-next@15.5.18':
resolution: {integrity: sha512-w4MYq8M26a8PNrfto0JosLf5/3ssln1rsyP96g2DkC8uFVymStM5DLSz5ElxxrPRg2XnTMnFo3kREFlhYvxhWw==}
- '@next/swc-darwin-arm64@15.5.21':
- resolution: {integrity: sha512-ZfjqPEdi6TRC/fWx7UDbwb1fbVgyh2uD5tVTRKIDZDlYM+UNuE/LafDG2fwuAoZilADpABh46OY/F5qf9JjqLQ==}
+ '@next/swc-darwin-arm64@15.5.24':
+ resolution: {integrity: sha512-AGdNLvxZNY6eR2iSnV+6wUa8CiHTMr4F7g3uHH7fT4ICIJBE00R9u4tzN/Vuwsw0cOi8MTD2HJcTCb6siMH88Q==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [darwin]
- '@next/swc-darwin-x64@15.5.21':
- resolution: {integrity: sha512-TlCf1NpxgQLzTrexuev75xwmNCJMd1/qkJpTVP1GRRcih93hlIBn1P72hkh8T0gnRFr6BmWksQtbyG3jT6jnww==}
+ '@next/swc-darwin-x64@15.5.24':
+ resolution: {integrity: sha512-9HrQajBMmGcrrrvDfRimiCrbAPh3E6uHJmwBovYr6Yrmi9p9PZqI876BrXX280wICh3o2XwUlp4blkB0NNBqFg==}
engines: {node: '>= 10'}
cpu: [x64]
os: [darwin]
- '@next/swc-linux-arm64-gnu@15.5.21':
- resolution: {integrity: sha512-LXRsq1p+HvHSi7ygwNcSEEcK0zuo5jS75ZlqFHtOH+LF7qntXAJVJxah+1Pi/GyBm7EpkwU7m4EgbvIKrMqm9A==}
+ '@next/swc-linux-arm64-gnu@15.5.24':
+ resolution: {integrity: sha512-rl9LSfE75si0WT3cDgdUC1XYCKS+TgxC+/IjitmeycrAG18X/plIP1/vy8dd/HPycYcIvE688PD7FuvEAiEAew==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [linux]
libc: [glibc]
- '@next/swc-linux-arm64-musl@15.5.21':
- resolution: {integrity: sha512-hyGixhFxpDKjqoev6l4KlcRBlt9AXWrGhDZwmwg49sMJM5tnKQPSi+SEj9+e5n+l/bthRGZUdh59GKIs6lQPRw==}
+ '@next/swc-linux-arm64-musl@15.5.24':
+ resolution: {integrity: sha512-TlNAnpsjxSF3aAUtqnfmtXXf8m9sIDBlmF3c7bTAlnshUYu2U0OxN2uf5d0gcFwqHVEdivJNBcCaqNOwPGNimw==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [linux]
libc: [musl]
- '@next/swc-linux-x64-gnu@15.5.21':
- resolution: {integrity: sha512-qfE+YfOba6S2+13e8qn1/UozDVNZ2clBlrs8UtDoax4s8ediu6sq93z66OEHUYlb69Tffh5JTNkgtsAKiSuugg==}
+ '@next/swc-linux-x64-gnu@15.5.24':
+ resolution: {integrity: sha512-7dwtlhr0SLndqTG1z9ncRkbJswDZiKWlxzFyXDvJ2RDZRDRHp8zyMJ4D9UH/FgnQeXxxB6gZy2pMcIUoNKQ4pA==}
engines: {node: '>= 10'}
cpu: [x64]
os: [linux]
libc: [glibc]
- '@next/swc-linux-x64-musl@15.5.21':
- resolution: {integrity: sha512-BXLGG+EvIwp/Rrgl6HY8sqvD6BOUOIRz8/naDbeLNX7mlA5H2XRcL6MW/0IGnJISfj5BA9gNhFyJj5yOoiIDJQ==}
+ '@next/swc-linux-x64-musl@15.5.24':
+ resolution: {integrity: sha512-kGZxM+WhkYs0276lFrMkj7PRtXT3Btp6cwvfSO/cCVLxJJttB5Ccnl2niaCgUja8HgSbEVnMHpg3FJWoOJ9e/g==}
engines: {node: '>= 10'}
cpu: [x64]
os: [linux]
libc: [musl]
- '@next/swc-win32-arm64-msvc@15.5.21':
- resolution: {integrity: sha512-tNGNOlT0Wn7E4IMsSnufjXN/l2L2/AGdLLpa2vzS89SYCBuihgLn3ngLsIrvndAnWo9nAkus+4gZHTI/Ijx9HA==}
+ '@next/swc-win32-arm64-msvc@15.5.24':
+ resolution: {integrity: sha512-jBDDkZ/qKAqkWivWDMkJSXUzbzV0QKRBKJjEHUAvSB97Hzw7NLzJ6yV56Lts/wjir7s4P31GYgpbS6ZL+hasAA==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [win32]
- '@next/swc-win32-x64-msvc@15.5.21':
- resolution: {integrity: sha512-DmIdWmC9p4rdNIiQqo8ap0+Cnj6kKtTZnuSCxoYydSc8sgpDgAg9wFhxplunak9imLV0pTvc5WVCOHwm5eHLtQ==}
+ '@next/swc-win32-x64-msvc@15.5.24':
+ resolution: {integrity: sha512-JqtwjvvorjacQ0spgjmUJoxySoYgPwdT1sFdQ0/zmW4iMlP2hjYlCoJIyS7o6Epb4Fug8eco3HXFoBDUCDeH7Q==}
engines: {node: '>= 10'}
cpu: [x64]
os: [win32]
@@ -2417,8 +2417,8 @@ packages:
react: ^16.8 || ^17 || ^18 || ^19 || ^19.0.0-rc
react-dom: ^16.8 || ^17 || ^18 || ^19 || ^19.0.0-rc
- next@15.5.21:
- resolution: {integrity: sha512-/TsdBtkWLhkl+NVL3Uqws2UphNd6IPzOtzSk1fHaf+0P7GQKLZDUytyhns/Ykbzdy9+YRjwG7ONvrHaaTDdFqQ==}
+ next@15.5.24:
+ resolution: {integrity: sha512-Y+xn8EQCoC3ZbsFPyzE+tE8XOdrWeUdUF7NeXbmg9DsgAxl5UYxlsrvgVESHTyTGigoTa1bCUrxn70F5bqt0Gw==}
engines: {node: ^18.18.0 || ^19.8.0 || >= 20.0.0}
hasBin: true
peerDependencies:
@@ -3343,34 +3343,34 @@ snapshots:
'@tybys/wasm-util': 0.10.2
optional: true
- '@next/env@15.5.21': {}
+ '@next/env@15.5.24': {}
'@next/eslint-plugin-next@15.5.18':
dependencies:
fast-glob: 3.3.1
- '@next/swc-darwin-arm64@15.5.21':
+ '@next/swc-darwin-arm64@15.5.24':
optional: true
- '@next/swc-darwin-x64@15.5.21':
+ '@next/swc-darwin-x64@15.5.24':
optional: true
- '@next/swc-linux-arm64-gnu@15.5.21':
+ '@next/swc-linux-arm64-gnu@15.5.24':
optional: true
- '@next/swc-linux-arm64-musl@15.5.21':
+ '@next/swc-linux-arm64-musl@15.5.24':
optional: true
- '@next/swc-linux-x64-gnu@15.5.21':
+ '@next/swc-linux-x64-gnu@15.5.24':
optional: true
- '@next/swc-linux-x64-musl@15.5.21':
+ '@next/swc-linux-x64-musl@15.5.24':
optional: true
- '@next/swc-win32-arm64-msvc@15.5.21':
+ '@next/swc-win32-arm64-msvc@15.5.24':
optional: true
- '@next/swc-win32-x64-msvc@15.5.21':
+ '@next/swc-win32-x64-msvc@15.5.24':
optional: true
'@nodelib/fs.scandir@2.1.5':
@@ -5421,24 +5421,24 @@ snapshots:
react: 19.2.7
react-dom: 19.2.7(react@19.2.7)
- next@15.5.21(@types/node@22.5.4)(react-dom@19.2.7(react@19.2.7))(react@19.2.7):
+ next@15.5.24(@types/node@22.5.4)(react-dom@19.2.7(react@19.2.7))(react@19.2.7):
dependencies:
- '@next/env': 15.5.21
+ '@next/env': 15.5.24
'@swc/helpers': 0.5.15
- caniuse-lite: 1.0.30001797
+ caniuse-lite: 1.0.30001810
postcss: 8.5.23
react: 19.2.7
react-dom: 19.2.7(react@19.2.7)
styled-jsx: 5.1.6(react@19.2.7)
optionalDependencies:
- '@next/swc-darwin-arm64': 15.5.21
- '@next/swc-darwin-x64': 15.5.21
- '@next/swc-linux-arm64-gnu': 15.5.21
- '@next/swc-linux-arm64-musl': 15.5.21
- '@next/swc-linux-x64-gnu': 15.5.21
- '@next/swc-linux-x64-musl': 15.5.21
- '@next/swc-win32-arm64-msvc': 15.5.21
- '@next/swc-win32-x64-msvc': 15.5.21
+ '@next/swc-darwin-arm64': 15.5.24
+ '@next/swc-darwin-x64': 15.5.24
+ '@next/swc-linux-arm64-gnu': 15.5.24
+ '@next/swc-linux-arm64-musl': 15.5.24
+ '@next/swc-linux-x64-gnu': 15.5.24
+ '@next/swc-linux-x64-musl': 15.5.24
+ '@next/swc-win32-arm64-msvc': 15.5.24
+ '@next/swc-win32-x64-msvc': 15.5.24
sharp: 0.35.3(@types/node@22.5.4)
transitivePeerDependencies:
- '@babel/core'
From f135cb994979170401d4e62d37fd043ed01ac5f8 Mon Sep 17 00:00:00 2001
From: "mintlify[bot]" <109931778+mintlify[bot]@users.noreply.github.com>
Date: Thu, 17 Sep 2026 19:32:03 +0530
Subject: [PATCH 05/54] SEO & metadata audit: shorten hermes description
(#7359)
Co-authored-by: mintlify[bot] <109931778+mintlify[bot]@users.noreply.github.com>
---
docs/integrations/hermes.mdx | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/docs/integrations/hermes.mdx b/docs/integrations/hermes.mdx
index dce08e63f..26de7221c 100644
--- a/docs/integrations/hermes.mdx
+++ b/docs/integrations/hermes.mdx
@@ -1,6 +1,6 @@
---
title: Hermes Agent
-description: "Add long-term memory to Hermes agents with Mem0: managed Platform, a self-hosted server, or fully local OSS — with current-turn recall and background fact extraction."
+description: "Add long-term memory to Hermes agents using Mem0 Platform, a self-hosted server, or local OSS mode with background fact extraction."
---
Add long-term memory to [Hermes Agent](https://github.com/NousResearch/hermes-agent), a self-improving AI agent CLI by Nous Research. Hermes has a pluggable memory system, and Mem0 is one of the supported providers. Once enabled, Mem0 learns facts from your conversations and surfaces relevant ones for the current question, without slowing down the chat.
From 84bf468176f0c5e82493bb95aec5484eb2d92bc1 Mon Sep 17 00:00:00 2001
From: Kartik
Date: Fri, 18 Sep 2026 06:54:04 +0530
Subject: [PATCH 06/54] docs: add practical Mem0 Copilot guide (MEM-6344)
(#7337)
---
docs/docs.json | 1 +
docs/llms.txt | 1 +
docs/platform/copilot.mdx | 194 ++++++++++++++++++++++++++++++++++++++
3 files changed, 196 insertions(+)
create mode 100644 docs/platform/copilot.mdx
diff --git a/docs/docs.json b/docs/docs.json
index c1c4887d2..4ca51fa24 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -41,6 +41,7 @@
"pages": [
"platform/quickstart",
"platform/overview",
+ "platform/copilot",
"platform/agent-signup",
"vibecoding",
"platform/cli",
diff --git a/docs/llms.txt b/docs/llms.txt
index 65e13de8f..686835a0e 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`.
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.
From e4e0307ae6c13dfa0b11d77c8b66936e524aede1 Mon Sep 17 00:00:00 2001
From: Saket Aryan
Date: Fri, 18 Sep 2026 13:23:05 +0530
Subject: [PATCH 07/54] fix(plugins): say what telemetry actually sends, and
salt the hashes (#7322)
---
docs/integrations/claude-code.mdx | 30 ++++
docs/integrations/deepseek-plugin.mdx | 2 +-
docs/integrations/openclaw.mdx | 4 +-
.../agent-plugin-core/python/telemetry.py | 138 +++++++++++++++++-
.../skills/pause/SKILL.md.tmpl | 4 +-
.../antigravity-plugin/core/telemetry.py | 138 +++++++++++++++++-
.../antigravity-plugin/skills/pause/SKILL.md | 4 +-
integrations/claude-code-plugin/README.md | 14 +-
.../claude-code-plugin/core/telemetry.py | 138 +++++++++++++++++-
.../claude-code-plugin/skills/pause/SKILL.md | 4 +-
.../tests/test_telemetry.py | 112 ++++++++++++++
integrations/codex-plugin/core/telemetry.py | 138 +++++++++++++++++-
.../codex-plugin/skills/pause/SKILL.md | 4 +-
integrations/cursor-plugin/core/telemetry.py | 138 +++++++++++++++++-
.../cursor-plugin/skills/pause/SKILL.md | 4 +-
integrations/deepseek-plugin/README.md | 4 +-
integrations/deepseek-plugin/src/index.ts | 6 +-
integrations/kimi-plugin/core/telemetry.py | 138 +++++++++++++++++-
.../kimi-plugin/skills/pause/SKILL.md | 4 +-
.../mem0-agent-plugin/core/telemetry.py | 138 +++++++++++++++++-
.../mem0-agent-plugin/skills/pause/SKILL.md | 4 +-
integrations/mem0-strands/README.md | 8 +-
integrations/zapier-mem0/README.md | 2 +-
23 files changed, 1120 insertions(+), 56 deletions(-)
diff --git a/docs/integrations/claude-code.mdx b/docs/integrations/claude-code.mdx
index 0b8e5a328..4277bb90e 100644
--- a/docs/integrations/claude-code.mdx
+++ b/docs/integrations/claude-code.mdx
@@ -172,6 +172,36 @@ claude plugin update mem0@mem0-plugins --scope user
| Sidekick won't start | Must be in a Git repo. Check that your Claude Code version supports plugin agents and worktrees. |
| Remove the plugin | `claude plugin uninstall mem0@mem0-plugins` |
+## Telemetry
+
+The plugin sends usage events (which hook ran, timing, result counts, failure
+types) so Mem0 can see what's used and what's breaking.
+
+These events are **not anonymous**. When an API key is configured, which
+installing the plugin requires, they 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.
+
+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.
+
+The exact set is enforced in code rather than by this list: every property is
+filtered through a denylist of sensitive keys and credential-shaped values are
+redacted before anything is sent.
+
+Prompts, memory text, queries, file paths, repository names, and API keys are
+never sent.
+
+Turn it off:
+
+```bash
+export MEM0_TELEMETRY=false
+```
+
Detailed MCP configuration for all clients
diff --git a/docs/integrations/deepseek-plugin.mdx b/docs/integrations/deepseek-plugin.mdx
index 16b8badaf..0242496e1 100644
--- a/docs/integrations/deepseek-plugin.mdx
+++ b/docs/integrations/deepseek-plugin.mdx
@@ -114,7 +114,7 @@ Both tools also accept optional per-call `userId`, `agentId`, and `runId` params
## Telemetry
-Writes are tagged `source="DEEPSEEK_HARNESS"` so Mem0 can attribute usage to this integration. Anonymous usage events include operation names, durations, result counts, and coarse failure kinds. Queries, memory text, entity IDs, and API keys are never included. Set `MEM0_TELEMETRY=false` to opt out.
+Writes are tagged `source="DEEPSEEK_HARNESS"` so Mem0 can attribute usage to this integration. Usage events include operation names, durations, result counts, and coarse failure kinds. They 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, entity IDs, and API keys are never included. Set `MEM0_TELEMETRY=false` to opt out.
This plugin is a developer preview and tracks the evolving DeepSeek Harness plugin API.
diff --git a/docs/integrations/openclaw.mdx b/docs/integrations/openclaw.mdx
index a9642d444..fd7d449d9 100644
--- a/docs/integrations/openclaw.mdx
+++ b/docs/integrations/openclaw.mdx
@@ -481,7 +481,9 @@ Plugin config is stored in `~/.openclaw/openclaw.json` with file permissions `0o
### Telemetry
-Anonymous usage telemetry (PostHog) is enabled by default to help improve the plugin. No conversation content or memory values are included, only event counts (recall, capture, tool usage, CLI commands).
+Usage telemetry (PostHog) is enabled by default to help improve the plugin. No conversation content or memory values are included, only event counts (recall, capture, tool usage, CLI commands).
+
+These events are **not anonymous**. OpenClaw does not send your account email the way the SDK does, but it does send an unsalted SHA-256 hash of it, falling back to a hash of the API key and then to a random per-machine id. Mem0 holds the email the hash is derived from, so the hash identifies your account rather than concealing it. The first run that resolves an account also emits a PostHog `$identify`, which permanently merges any earlier random id into that identity.
To opt out, set the environment variable:
diff --git a/integrations/agent-plugin-core/python/telemetry.py b/integrations/agent-plugin-core/python/telemetry.py
index 249595475..132de5b0c 100644
--- a/integrations/agent-plugin-core/python/telemetry.py
+++ b/integrations/agent-plugin-core/python/telemetry.py
@@ -1,5 +1,9 @@
#!/usr/bin/env python3
-"""Anonymous usage telemetry for Mem0 agent plugins.
+"""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,7 @@ from typing import Any
import memory_core
+_salt_cache: str = ""
_harness: str = "generic"
_source_tag: str = "MEM0_PLUGIN"
_PRIVATE_KEYS = {
@@ -83,9 +89,126 @@ 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)
@@ -174,10 +297,17 @@ def record(
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}",
diff --git a/integrations/agent-plugin-core/skills/pause/SKILL.md.tmpl b/integrations/agent-plugin-core/skills/pause/SKILL.md.tmpl
index 9cc720c7a..569305ec7 100644
--- a/integrations/agent-plugin-core/skills/pause/SKILL.md.tmpl
+++ b/integrations/agent-plugin-core/skills/pause/SKILL.md.tmpl
@@ -7,8 +7,8 @@ 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 "{{PLUGIN_ROOT}}/core/memory_cli.py" --harness "{{HARNESS_ID}}" {{PLUGIN_DATA_ARG}} pause
diff --git a/integrations/antigravity-plugin/core/telemetry.py b/integrations/antigravity-plugin/core/telemetry.py
index 249595475..132de5b0c 100644
--- a/integrations/antigravity-plugin/core/telemetry.py
+++ b/integrations/antigravity-plugin/core/telemetry.py
@@ -1,5 +1,9 @@
#!/usr/bin/env python3
-"""Anonymous usage telemetry for Mem0 agent plugins.
+"""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,7 @@ from typing import Any
import memory_core
+_salt_cache: str = ""
_harness: str = "generic"
_source_tag: str = "MEM0_PLUGIN"
_PRIVATE_KEYS = {
@@ -83,9 +89,126 @@ 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)
@@ -174,10 +297,17 @@ def record(
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}",
diff --git a/integrations/antigravity-plugin/skills/pause/SKILL.md b/integrations/antigravity-plugin/skills/pause/SKILL.md
index e88f7d315..77b4146b6 100644
--- a/integrations/antigravity-plugin/skills/pause/SKILL.md
+++ b/integrations/antigravity-plugin/skills/pause/SKILL.md
@@ -7,8 +7,8 @@ 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 "${ANTIGRAVITY_PLUGIN_ROOT}/core/memory_cli.py" --harness "antigravity" pause
diff --git a/integrations/claude-code-plugin/README.md b/integrations/claude-code-plugin/README.md
index 130460b17..b58f54c79 100644
--- a/integrations/claude-code-plugin/README.md
+++ b/integrations/claude-code-plugin/README.md
@@ -136,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 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:
diff --git a/integrations/claude-code-plugin/core/telemetry.py b/integrations/claude-code-plugin/core/telemetry.py
index 249595475..132de5b0c 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 Mem0 agent plugins.
+"""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,7 @@ from typing import Any
import memory_core
+_salt_cache: str = ""
_harness: str = "generic"
_source_tag: str = "MEM0_PLUGIN"
_PRIVATE_KEYS = {
@@ -83,9 +89,126 @@ 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)
@@ -174,10 +297,17 @@ def record(
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}",
diff --git a/integrations/claude-code-plugin/skills/pause/SKILL.md b/integrations/claude-code-plugin/skills/pause/SKILL.md
index 5aef04f39..ce69d13d2 100644
--- a/integrations/claude-code-plugin/skills/pause/SKILL.md
+++ b/integrations/claude-code-plugin/skills/pause/SKILL.md
@@ -7,8 +7,8 @@ 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" --harness "claude-code" --plugin-data-dir "${CLAUDE_PLUGIN_DATA}" pause
diff --git a/integrations/claude-code-plugin/tests/test_telemetry.py b/integrations/claude-code-plugin/tests/test_telemetry.py
index 0ae280b19..6029fa98a 100644
--- a/integrations/claude-code-plugin/tests/test_telemetry.py
+++ b/integrations/claude-code-plugin/tests/test_telemetry.py
@@ -1,6 +1,7 @@
from __future__ import annotations
import json
+import os
import sys
from pathlib import Path
from unittest.mock import patch
@@ -273,3 +274,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/core/telemetry.py b/integrations/codex-plugin/core/telemetry.py
index 249595475..132de5b0c 100644
--- a/integrations/codex-plugin/core/telemetry.py
+++ b/integrations/codex-plugin/core/telemetry.py
@@ -1,5 +1,9 @@
#!/usr/bin/env python3
-"""Anonymous usage telemetry for Mem0 agent plugins.
+"""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,7 @@ from typing import Any
import memory_core
+_salt_cache: str = ""
_harness: str = "generic"
_source_tag: str = "MEM0_PLUGIN"
_PRIVATE_KEYS = {
@@ -83,9 +89,126 @@ 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)
@@ -174,10 +297,17 @@ def record(
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}",
diff --git a/integrations/codex-plugin/skills/pause/SKILL.md b/integrations/codex-plugin/skills/pause/SKILL.md
index d8a52f47b..c8f8ddd5f 100644
--- a/integrations/codex-plugin/skills/pause/SKILL.md
+++ b/integrations/codex-plugin/skills/pause/SKILL.md
@@ -7,8 +7,8 @@ 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 "${PLUGIN_ROOT}/core/memory_cli.py" --harness "codex" --plugin-data-dir "${PLUGIN_DATA}" pause
diff --git a/integrations/cursor-plugin/core/telemetry.py b/integrations/cursor-plugin/core/telemetry.py
index 249595475..132de5b0c 100644
--- a/integrations/cursor-plugin/core/telemetry.py
+++ b/integrations/cursor-plugin/core/telemetry.py
@@ -1,5 +1,9 @@
#!/usr/bin/env python3
-"""Anonymous usage telemetry for Mem0 agent plugins.
+"""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,7 @@ from typing import Any
import memory_core
+_salt_cache: str = ""
_harness: str = "generic"
_source_tag: str = "MEM0_PLUGIN"
_PRIVATE_KEYS = {
@@ -83,9 +89,126 @@ 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)
@@ -174,10 +297,17 @@ def record(
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}",
diff --git a/integrations/cursor-plugin/skills/pause/SKILL.md b/integrations/cursor-plugin/skills/pause/SKILL.md
index 634385145..17384c368 100644
--- a/integrations/cursor-plugin/skills/pause/SKILL.md
+++ b/integrations/cursor-plugin/skills/pause/SKILL.md
@@ -7,8 +7,8 @@ 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 "${CURSOR_PLUGIN_ROOT}/core/memory_cli.py" --harness "cursor" pause
diff --git a/integrations/deepseek-plugin/README.md b/integrations/deepseek-plugin/README.md
index 93e5f563f..d5cb3345a 100644
--- a/integrations/deepseek-plugin/README.md
+++ b/integrations/deepseek-plugin/README.md
@@ -86,9 +86,9 @@ Per-call `userId` overrides are rejected unless the operator enables `allowUserO
## 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
diff --git a/integrations/deepseek-plugin/src/index.ts b/integrations/deepseek-plugin/src/index.ts
index bea70c02c..2d24b498a 100644
--- a/integrations/deepseek-plugin/src/index.ts
+++ b/integrations/deepseek-plugin/src/index.ts
@@ -26,10 +26,8 @@ export const name = "mem0";
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. The backend's KNOWN_EVENT_SOURCES allowlist recognizes this value;
+// anything outside it buckets into "OTHERS".
const SOURCE = "DEEPSEEK_HARNESS";
const DEFAULT_SEARCH_LIMIT = 10;
diff --git a/integrations/kimi-plugin/core/telemetry.py b/integrations/kimi-plugin/core/telemetry.py
index 249595475..132de5b0c 100644
--- a/integrations/kimi-plugin/core/telemetry.py
+++ b/integrations/kimi-plugin/core/telemetry.py
@@ -1,5 +1,9 @@
#!/usr/bin/env python3
-"""Anonymous usage telemetry for Mem0 agent plugins.
+"""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,7 @@ from typing import Any
import memory_core
+_salt_cache: str = ""
_harness: str = "generic"
_source_tag: str = "MEM0_PLUGIN"
_PRIVATE_KEYS = {
@@ -83,9 +89,126 @@ 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)
@@ -174,10 +297,17 @@ def record(
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}",
diff --git a/integrations/kimi-plugin/skills/pause/SKILL.md b/integrations/kimi-plugin/skills/pause/SKILL.md
index 9f217a468..8f93e3bf7 100644
--- a/integrations/kimi-plugin/skills/pause/SKILL.md
+++ b/integrations/kimi-plugin/skills/pause/SKILL.md
@@ -7,8 +7,8 @@ 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 "${KIMI_PLUGIN_ROOT}/core/memory_cli.py" --harness "kimi" pause
diff --git a/integrations/mem0-agent-plugin/core/telemetry.py b/integrations/mem0-agent-plugin/core/telemetry.py
index 249595475..132de5b0c 100644
--- a/integrations/mem0-agent-plugin/core/telemetry.py
+++ b/integrations/mem0-agent-plugin/core/telemetry.py
@@ -1,5 +1,9 @@
#!/usr/bin/env python3
-"""Anonymous usage telemetry for Mem0 agent plugins.
+"""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,7 @@ from typing import Any
import memory_core
+_salt_cache: str = ""
_harness: str = "generic"
_source_tag: str = "MEM0_PLUGIN"
_PRIVATE_KEYS = {
@@ -83,9 +89,126 @@ 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)
@@ -174,10 +297,17 @@ def record(
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}",
diff --git a/integrations/mem0-agent-plugin/skills/pause/SKILL.md b/integrations/mem0-agent-plugin/skills/pause/SKILL.md
index c6316dd0b..a87d6c3ee 100644
--- a/integrations/mem0-agent-plugin/skills/pause/SKILL.md
+++ b/integrations/mem0-agent-plugin/skills/pause/SKILL.md
@@ -6,8 +6,8 @@ description: Pause Mem0 memory capture on this machine. Use when the user wants
# 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 "${PLUGIN_ROOT}/core/memory_cli.py" --harness "coding-agent" pause
diff --git a/integrations/mem0-strands/README.md b/integrations/mem0-strands/README.md
index f45d98e44..8ea4ecacc 100644
--- a/integrations/mem0-strands/README.md
+++ b/integrations/mem0-strands/README.md
@@ -79,9 +79,11 @@ the tool share one Mem0 backend and namespace.
## Telemetry
-The store sends anonymous usage events (store configuration, operation, duration,
-result counts, coarse failure kind) over the Mem0 SDK's existing telemetry client,
-tagged `source="STRANDS"`. Queries, memory text, message content, entity ids, and
+The store sends usage events (store configuration, operation, duration, result
+counts, coarse failure kind) over the Mem0 SDK's existing telemetry client,
+tagged `source="STRANDS"`. 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, message content, entity ids, and
metadata are never sent. Turn it off with `MEM0_TELEMETRY=false`.
## Development
diff --git a/integrations/zapier-mem0/README.md b/integrations/zapier-mem0/README.md
index 7b3f5ed0f..dab21d3f3 100644
--- a/integrations/zapier-mem0/README.md
+++ b/integrations/zapier-mem0/README.md
@@ -32,7 +32,7 @@ pnpm test:unit # offline unit tests (mocked, no network)
MEM0_API_KEY=m0-... pnpm test # unit + live E2E against api.mem0.ai
```
-Anonymous usage telemetry is sent to Mem0; opt out with `MEM0_TELEMETRY=false`.
+This app sends no telemetry of its own. Its API requests carry `source: "ZAPIER"` so Mem0 can see aggregate usage of the integration.
To deploy (maintainers): `pnpm build && zapier push`.
From 012cd32c3a5a8d1cbd3eccc3f71a62fa29e9ff26 Mon Sep 17 00:00:00 2001
From: Saket Aryan
Date: Fri, 18 Sep 2026 13:42:34 +0530
Subject: [PATCH 08/54] fix(plugins): report the plugin that produced the
event, not the one that sent it (#7323)
---
integrations/agent-plugin-core/build/build.py | 28 +++
.../agent-plugin-core/python/telemetry.py | 42 +++-
.../tests/test_uninitialised_identity.py | 179 ++++++++++++++++++
.../antigravity-plugin/core/_harness_id.py | 9 +
.../antigravity-plugin/core/telemetry.py | 42 +++-
.../claude-code-plugin/core/_harness_id.py | 9 +
.../claude-code-plugin/core/telemetry.py | 42 +++-
integrations/codex-plugin/core/_harness_id.py | 9 +
integrations/codex-plugin/core/telemetry.py | 42 +++-
.../cursor-plugin/core/_harness_id.py | 9 +
integrations/cursor-plugin/core/telemetry.py | 42 +++-
integrations/kimi-plugin/core/_harness_id.py | 9 +
integrations/kimi-plugin/core/telemetry.py | 42 +++-
.../mem0-agent-plugin/core/_harness_id.py | 9 +
.../mem0-agent-plugin/core/telemetry.py | 42 +++-
15 files changed, 520 insertions(+), 35 deletions(-)
create mode 100644 integrations/agent-plugin-core/tests/test_uninitialised_identity.py
create mode 100644 integrations/antigravity-plugin/core/_harness_id.py
create mode 100644 integrations/claude-code-plugin/core/_harness_id.py
create mode 100644 integrations/codex-plugin/core/_harness_id.py
create mode 100644 integrations/cursor-plugin/core/_harness_id.py
create mode 100644 integrations/kimi-plugin/core/_harness_id.py
create mode 100644 integrations/mem0-agent-plugin/core/_harness_id.py
diff --git a/integrations/agent-plugin-core/build/build.py b/integrations/agent-plugin-core/build/build.py
index 7a72e5c51..e675efb02 100644
--- a/integrations/agent-plugin-core/build/build.py
+++ b/integrations/agent-plugin-core/build/build.py
@@ -81,6 +81,28 @@ def replace_output(staged: Path, output: Path) -> Path:
return output
+def _render_harness_id(host: str) -> 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.
+ """
+ tag = host.upper().replace("-", "_") + "_PLUGIN"
+ 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"
+ 'PLATFORM_SOURCE = "MEM0_PLUGIN"\n'
+ f'PLATFORM_APPLICATION = "{host}"\n'
+ )
+
+
def _bundle_python(
staged: Path,
host: str,
@@ -96,6 +118,12 @@ def _bundle_python(
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), encoding="utf-8")
+
values = {
"PLUGIN_ROOT": plugin_root,
"PLUGIN_DATA": "${PLUGIN_DATA}",
diff --git a/integrations/agent-plugin-core/python/telemetry.py b/integrations/agent-plugin-core/python/telemetry.py
index 132de5b0c..6d7aeecae 100644
--- a/integrations/agent-plugin-core/python/telemetry.py
+++ b/integrations/agent-plugin-core/python/telemetry.py
@@ -34,9 +34,24 @@ 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 = "generic"
-_source_tag: str = "MEM0_PLUGIN"
+_harness: str = _DEFAULT_HARNESS
+_source_tag: str = _DEFAULT_SOURCE_TAG
_PRIVATE_KEYS = {
"apikey",
"authorization",
@@ -62,10 +77,19 @@ _PRIVATE_KEYS = {
}
-def init(harness: str = "generic", source_tag: str = "") -> None:
+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
- _source_tag = source_tag or f"MEM0_{harness.upper().replace('-', '_')}_PLUGIN"
+ _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/"
@@ -291,8 +315,13 @@ def record(
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(),
@@ -311,6 +340,7 @@ def record(
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
@@ -496,6 +526,8 @@ def flush() -> int:
"distinct_id": distinct_id,
"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,
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..14f911bee
--- /dev/null
+++ b/integrations/agent-plugin-core/tests/test_uninitialised_identity.py
@@ -0,0 +1,179 @@
+"""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"
diff --git a/integrations/antigravity-plugin/core/_harness_id.py b/integrations/antigravity-plugin/core/_harness_id.py
new file mode 100644
index 000000000..2c8a515f4
--- /dev/null
+++ b/integrations/antigravity-plugin/core/_harness_id.py
@@ -0,0 +1,9 @@
+"""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.
+PLATFORM_SOURCE = "MEM0_PLUGIN"
+PLATFORM_APPLICATION = "antigravity"
diff --git a/integrations/antigravity-plugin/core/telemetry.py b/integrations/antigravity-plugin/core/telemetry.py
index 132de5b0c..6d7aeecae 100644
--- a/integrations/antigravity-plugin/core/telemetry.py
+++ b/integrations/antigravity-plugin/core/telemetry.py
@@ -34,9 +34,24 @@ 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 = "generic"
-_source_tag: str = "MEM0_PLUGIN"
+_harness: str = _DEFAULT_HARNESS
+_source_tag: str = _DEFAULT_SOURCE_TAG
_PRIVATE_KEYS = {
"apikey",
"authorization",
@@ -62,10 +77,19 @@ _PRIVATE_KEYS = {
}
-def init(harness: str = "generic", source_tag: str = "") -> None:
+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
- _source_tag = source_tag or f"MEM0_{harness.upper().replace('-', '_')}_PLUGIN"
+ _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/"
@@ -291,8 +315,13 @@ def record(
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(),
@@ -311,6 +340,7 @@ def record(
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
@@ -496,6 +526,8 @@ def flush() -> int:
"distinct_id": distinct_id,
"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,
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..6c3e1ce15
--- /dev/null
+++ b/integrations/claude-code-plugin/core/_harness_id.py
@@ -0,0 +1,9 @@
+"""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.
+PLATFORM_SOURCE = "MEM0_PLUGIN"
+PLATFORM_APPLICATION = "claude-code"
diff --git a/integrations/claude-code-plugin/core/telemetry.py b/integrations/claude-code-plugin/core/telemetry.py
index 132de5b0c..6d7aeecae 100644
--- a/integrations/claude-code-plugin/core/telemetry.py
+++ b/integrations/claude-code-plugin/core/telemetry.py
@@ -34,9 +34,24 @@ 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 = "generic"
-_source_tag: str = "MEM0_PLUGIN"
+_harness: str = _DEFAULT_HARNESS
+_source_tag: str = _DEFAULT_SOURCE_TAG
_PRIVATE_KEYS = {
"apikey",
"authorization",
@@ -62,10 +77,19 @@ _PRIVATE_KEYS = {
}
-def init(harness: str = "generic", source_tag: str = "") -> None:
+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
- _source_tag = source_tag or f"MEM0_{harness.upper().replace('-', '_')}_PLUGIN"
+ _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/"
@@ -291,8 +315,13 @@ def record(
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(),
@@ -311,6 +340,7 @@ def record(
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
@@ -496,6 +526,8 @@ def flush() -> int:
"distinct_id": distinct_id,
"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,
diff --git a/integrations/codex-plugin/core/_harness_id.py b/integrations/codex-plugin/core/_harness_id.py
new file mode 100644
index 000000000..152313a21
--- /dev/null
+++ b/integrations/codex-plugin/core/_harness_id.py
@@ -0,0 +1,9 @@
+"""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.
+PLATFORM_SOURCE = "MEM0_PLUGIN"
+PLATFORM_APPLICATION = "codex"
diff --git a/integrations/codex-plugin/core/telemetry.py b/integrations/codex-plugin/core/telemetry.py
index 132de5b0c..6d7aeecae 100644
--- a/integrations/codex-plugin/core/telemetry.py
+++ b/integrations/codex-plugin/core/telemetry.py
@@ -34,9 +34,24 @@ 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 = "generic"
-_source_tag: str = "MEM0_PLUGIN"
+_harness: str = _DEFAULT_HARNESS
+_source_tag: str = _DEFAULT_SOURCE_TAG
_PRIVATE_KEYS = {
"apikey",
"authorization",
@@ -62,10 +77,19 @@ _PRIVATE_KEYS = {
}
-def init(harness: str = "generic", source_tag: str = "") -> None:
+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
- _source_tag = source_tag or f"MEM0_{harness.upper().replace('-', '_')}_PLUGIN"
+ _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/"
@@ -291,8 +315,13 @@ def record(
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(),
@@ -311,6 +340,7 @@ def record(
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
@@ -496,6 +526,8 @@ def flush() -> int:
"distinct_id": distinct_id,
"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,
diff --git a/integrations/cursor-plugin/core/_harness_id.py b/integrations/cursor-plugin/core/_harness_id.py
new file mode 100644
index 000000000..40241a7f4
--- /dev/null
+++ b/integrations/cursor-plugin/core/_harness_id.py
@@ -0,0 +1,9 @@
+"""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.
+PLATFORM_SOURCE = "MEM0_PLUGIN"
+PLATFORM_APPLICATION = "cursor"
diff --git a/integrations/cursor-plugin/core/telemetry.py b/integrations/cursor-plugin/core/telemetry.py
index 132de5b0c..6d7aeecae 100644
--- a/integrations/cursor-plugin/core/telemetry.py
+++ b/integrations/cursor-plugin/core/telemetry.py
@@ -34,9 +34,24 @@ 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 = "generic"
-_source_tag: str = "MEM0_PLUGIN"
+_harness: str = _DEFAULT_HARNESS
+_source_tag: str = _DEFAULT_SOURCE_TAG
_PRIVATE_KEYS = {
"apikey",
"authorization",
@@ -62,10 +77,19 @@ _PRIVATE_KEYS = {
}
-def init(harness: str = "generic", source_tag: str = "") -> None:
+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
- _source_tag = source_tag or f"MEM0_{harness.upper().replace('-', '_')}_PLUGIN"
+ _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/"
@@ -291,8 +315,13 @@ def record(
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(),
@@ -311,6 +340,7 @@ def record(
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
@@ -496,6 +526,8 @@ def flush() -> int:
"distinct_id": distinct_id,
"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,
diff --git a/integrations/kimi-plugin/core/_harness_id.py b/integrations/kimi-plugin/core/_harness_id.py
new file mode 100644
index 000000000..aa17750b1
--- /dev/null
+++ b/integrations/kimi-plugin/core/_harness_id.py
@@ -0,0 +1,9 @@
+"""Generated by integrations/agent-plugin-core/build/build.py. Do not edit."""
+
+HARNESS_ID = "kimi"
+SOURCE_TAG = "KIMI_PLUGIN"
+
+# Platform-side vocabulary (mem0_event.source + X-Application). The whole
+# plugin family is one source; which editor it runs in is the application.
+PLATFORM_SOURCE = "MEM0_PLUGIN"
+PLATFORM_APPLICATION = "kimi"
diff --git a/integrations/kimi-plugin/core/telemetry.py b/integrations/kimi-plugin/core/telemetry.py
index 132de5b0c..6d7aeecae 100644
--- a/integrations/kimi-plugin/core/telemetry.py
+++ b/integrations/kimi-plugin/core/telemetry.py
@@ -34,9 +34,24 @@ 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 = "generic"
-_source_tag: str = "MEM0_PLUGIN"
+_harness: str = _DEFAULT_HARNESS
+_source_tag: str = _DEFAULT_SOURCE_TAG
_PRIVATE_KEYS = {
"apikey",
"authorization",
@@ -62,10 +77,19 @@ _PRIVATE_KEYS = {
}
-def init(harness: str = "generic", source_tag: str = "") -> None:
+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
- _source_tag = source_tag or f"MEM0_{harness.upper().replace('-', '_')}_PLUGIN"
+ _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/"
@@ -291,8 +315,13 @@ def record(
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(),
@@ -311,6 +340,7 @@ def record(
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
@@ -496,6 +526,8 @@ def flush() -> int:
"distinct_id": distinct_id,
"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,
diff --git a/integrations/mem0-agent-plugin/core/_harness_id.py b/integrations/mem0-agent-plugin/core/_harness_id.py
new file mode 100644
index 000000000..b0836d6de
--- /dev/null
+++ b/integrations/mem0-agent-plugin/core/_harness_id.py
@@ -0,0 +1,9 @@
+"""Generated by integrations/agent-plugin-core/build/build.py. Do not edit."""
+
+HARNESS_ID = "coding-agent"
+SOURCE_TAG = "CODING_AGENT_PLUGIN"
+
+# Platform-side vocabulary (mem0_event.source + X-Application). The whole
+# plugin family is one source; which editor it runs in is the application.
+PLATFORM_SOURCE = "MEM0_PLUGIN"
+PLATFORM_APPLICATION = "coding-agent"
diff --git a/integrations/mem0-agent-plugin/core/telemetry.py b/integrations/mem0-agent-plugin/core/telemetry.py
index 132de5b0c..6d7aeecae 100644
--- a/integrations/mem0-agent-plugin/core/telemetry.py
+++ b/integrations/mem0-agent-plugin/core/telemetry.py
@@ -34,9 +34,24 @@ 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 = "generic"
-_source_tag: str = "MEM0_PLUGIN"
+_harness: str = _DEFAULT_HARNESS
+_source_tag: str = _DEFAULT_SOURCE_TAG
_PRIVATE_KEYS = {
"apikey",
"authorization",
@@ -62,10 +77,19 @@ _PRIVATE_KEYS = {
}
-def init(harness: str = "generic", source_tag: str = "") -> None:
+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
- _source_tag = source_tag or f"MEM0_{harness.upper().replace('-', '_')}_PLUGIN"
+ _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/"
@@ -291,8 +315,13 @@ def record(
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(),
@@ -311,6 +340,7 @@ def record(
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
@@ -496,6 +526,8 @@ def flush() -> int:
"distinct_id": distinct_id,
"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,
From 33629990956ca6336501deea2e9cd625e5fe09af Mon Sep 17 00:00:00 2001
From: Saket Aryan
Date: Fri, 18 Sep 2026 13:43:33 +0530
Subject: [PATCH 09/54] fix(plugins): stop delivering telemetry events twice,
and stop losing parked ones (#7324)
---
.../agent-plugin-core/python/telemetry.py | 274 ++++++++++-
.../tests/test_spool_delivery.py | 446 ++++++++++++++++++
.../antigravity-plugin/core/telemetry.py | 274 ++++++++++-
.../claude-code-plugin/core/telemetry.py | 274 ++++++++++-
.../tests/test_telemetry.py | 18 +-
integrations/codex-plugin/core/telemetry.py | 274 ++++++++++-
integrations/cursor-plugin/core/telemetry.py | 274 ++++++++++-
integrations/kimi-plugin/core/telemetry.py | 274 ++++++++++-
.../mem0-agent-plugin/core/telemetry.py | 274 ++++++++++-
9 files changed, 2243 insertions(+), 139 deletions(-)
create mode 100644 integrations/agent-plugin-core/tests/test_spool_delivery.py
diff --git a/integrations/agent-plugin-core/python/telemetry.py b/integrations/agent-plugin-core/python/telemetry.py
index 6d7aeecae..a4375f002 100644
--- a/integrations/agent-plugin-core/python/telemetry.py
+++ b/integrations/agent-plugin-core/python/telemetry.py
@@ -100,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:
@@ -399,38 +409,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/"
@@ -478,16 +651,61 @@ def resolve_distinct_id() -> tuple[str, str]:
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:
@@ -497,11 +715,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:
@@ -520,10 +745,13 @@ 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": {
# Fallback only: events recorded by a build before source
@@ -535,16 +763,24 @@ def flush() -> int:
**(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/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/antigravity-plugin/core/telemetry.py b/integrations/antigravity-plugin/core/telemetry.py
index 6d7aeecae..a4375f002 100644
--- a/integrations/antigravity-plugin/core/telemetry.py
+++ b/integrations/antigravity-plugin/core/telemetry.py
@@ -100,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:
@@ -399,38 +409,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/"
@@ -478,16 +651,61 @@ def resolve_distinct_id() -> tuple[str, str]:
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:
@@ -497,11 +715,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:
@@ -520,10 +745,13 @@ 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": {
# Fallback only: events recorded by a build before source
@@ -535,16 +763,24 @@ def flush() -> int:
**(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/core/telemetry.py b/integrations/claude-code-plugin/core/telemetry.py
index 6d7aeecae..a4375f002 100644
--- a/integrations/claude-code-plugin/core/telemetry.py
+++ b/integrations/claude-code-plugin/core/telemetry.py
@@ -100,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:
@@ -399,38 +409,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/"
@@ -478,16 +651,61 @@ def resolve_distinct_id() -> tuple[str, str]:
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:
@@ -497,11 +715,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:
@@ -520,10 +745,13 @@ 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": {
# Fallback only: events recorded by a build before source
@@ -535,16 +763,24 @@ def flush() -> int:
**(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/tests/test_telemetry.py b/integrations/claude-code-plugin/tests/test_telemetry.py
index 6029fa98a..de0db10c6 100644
--- a/integrations/claude-code-plugin/tests/test_telemetry.py
+++ b/integrations/claude-code-plugin/tests/test_telemetry.py
@@ -199,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
@@ -211,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"))
diff --git a/integrations/codex-plugin/core/telemetry.py b/integrations/codex-plugin/core/telemetry.py
index 6d7aeecae..a4375f002 100644
--- a/integrations/codex-plugin/core/telemetry.py
+++ b/integrations/codex-plugin/core/telemetry.py
@@ -100,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:
@@ -399,38 +409,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/"
@@ -478,16 +651,61 @@ def resolve_distinct_id() -> tuple[str, str]:
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:
@@ -497,11 +715,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:
@@ -520,10 +745,13 @@ 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": {
# Fallback only: events recorded by a build before source
@@ -535,16 +763,24 @@ def flush() -> int:
**(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/cursor-plugin/core/telemetry.py b/integrations/cursor-plugin/core/telemetry.py
index 6d7aeecae..a4375f002 100644
--- a/integrations/cursor-plugin/core/telemetry.py
+++ b/integrations/cursor-plugin/core/telemetry.py
@@ -100,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:
@@ -399,38 +409,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/"
@@ -478,16 +651,61 @@ def resolve_distinct_id() -> tuple[str, str]:
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:
@@ -497,11 +715,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:
@@ -520,10 +745,13 @@ 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": {
# Fallback only: events recorded by a build before source
@@ -535,16 +763,24 @@ def flush() -> int:
**(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/kimi-plugin/core/telemetry.py b/integrations/kimi-plugin/core/telemetry.py
index 6d7aeecae..a4375f002 100644
--- a/integrations/kimi-plugin/core/telemetry.py
+++ b/integrations/kimi-plugin/core/telemetry.py
@@ -100,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:
@@ -399,38 +409,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/"
@@ -478,16 +651,61 @@ def resolve_distinct_id() -> tuple[str, str]:
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:
@@ -497,11 +715,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:
@@ -520,10 +745,13 @@ 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": {
# Fallback only: events recorded by a build before source
@@ -535,16 +763,24 @@ def flush() -> int:
**(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/mem0-agent-plugin/core/telemetry.py b/integrations/mem0-agent-plugin/core/telemetry.py
index 6d7aeecae..a4375f002 100644
--- a/integrations/mem0-agent-plugin/core/telemetry.py
+++ b/integrations/mem0-agent-plugin/core/telemetry.py
@@ -100,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:
@@ -399,38 +409,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/"
@@ -478,16 +651,61 @@ def resolve_distinct_id() -> tuple[str, str]:
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:
@@ -497,11 +715,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:
@@ -520,10 +745,13 @@ 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": {
# Fallback only: events recorded by a build before source
@@ -535,16 +763,24 @@ def flush() -> int:
**(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:
From 4e38b057fd110c201bd372ab5e1620e81c67a4ed Mon Sep 17 00:00:00 2001
From: Saket Aryan
Date: Fri, 18 Sep 2026 13:46:25 +0530
Subject: [PATCH 10/54] fix(plugins): count installs once, and re-resolve the
email when the key changes (#7325)
---
.../agent-plugin-core/python/hook_runner.py | 18 +-
.../agent-plugin-core/python/telemetry.py | 240 +++++++++++++++++-
.../tests/test_uninitialised_identity.py | 68 +++++
.../antigravity-plugin/core/hook_runner.py | 18 +-
.../antigravity-plugin/core/telemetry.py | 240 +++++++++++++++++-
.../claude-code-plugin/core/hook_runner.py | 18 +-
.../claude-code-plugin/core/telemetry.py | 240 +++++++++++++++++-
.../tests/test_telemetry.py | 140 +++++++++-
integrations/codex-plugin/core/hook_runner.py | 18 +-
integrations/codex-plugin/core/telemetry.py | 240 +++++++++++++++++-
.../cursor-plugin/core/hook_runner.py | 18 +-
integrations/cursor-plugin/core/telemetry.py | 240 +++++++++++++++++-
integrations/kimi-plugin/core/hook_runner.py | 18 +-
integrations/kimi-plugin/core/telemetry.py | 240 +++++++++++++++++-
.../mem0-agent-plugin/core/telemetry.py | 240 +++++++++++++++++-
15 files changed, 1912 insertions(+), 84 deletions(-)
diff --git a/integrations/agent-plugin-core/python/hook_runner.py b/integrations/agent-plugin-core/python/hook_runner.py
index 2a2adb557..b3d8a3210 100644
--- a/integrations/agent-plugin-core/python/hook_runner.py
+++ b/integrations/agent-plugin-core/python/hook_runner.py
@@ -290,6 +290,11 @@ def run(
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()
@@ -305,8 +310,19 @@ def run(
return 0
if args.action == "session-start":
- if telemetry.is_first_run():
+ # 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:
diff --git a/integrations/agent-plugin-core/python/telemetry.py b/integrations/agent-plugin-core/python/telemetry.py
index a4375f002..c1fc0084c 100644
--- a/integrations/agent-plugin-core/python/telemetry.py
+++ b/integrations/agent-plugin-core/python/telemetry.py
@@ -302,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(
@@ -633,21 +800,72 @@ 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:
diff --git a/integrations/agent-plugin-core/tests/test_uninitialised_identity.py b/integrations/agent-plugin-core/tests/test_uninitialised_identity.py
index 14f911bee..7d48dbcc3 100644
--- a/integrations/agent-plugin-core/tests/test_uninitialised_identity.py
+++ b/integrations/agent-plugin-core/tests/test_uninitialised_identity.py
@@ -177,3 +177,71 @@ def test_source_tag_defaults_agree_between_the_two_modules():
)
left, right = out.split()
assert left == right == "KIMI_PLUGIN"
+
+
+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/antigravity-plugin/core/hook_runner.py b/integrations/antigravity-plugin/core/hook_runner.py
index 2a2adb557..b3d8a3210 100644
--- a/integrations/antigravity-plugin/core/hook_runner.py
+++ b/integrations/antigravity-plugin/core/hook_runner.py
@@ -290,6 +290,11 @@ def run(
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()
@@ -305,8 +310,19 @@ def run(
return 0
if args.action == "session-start":
- if telemetry.is_first_run():
+ # 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:
diff --git a/integrations/antigravity-plugin/core/telemetry.py b/integrations/antigravity-plugin/core/telemetry.py
index a4375f002..c1fc0084c 100644
--- a/integrations/antigravity-plugin/core/telemetry.py
+++ b/integrations/antigravity-plugin/core/telemetry.py
@@ -302,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(
@@ -633,21 +800,72 @@ 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:
diff --git a/integrations/claude-code-plugin/core/hook_runner.py b/integrations/claude-code-plugin/core/hook_runner.py
index 2a2adb557..b3d8a3210 100644
--- a/integrations/claude-code-plugin/core/hook_runner.py
+++ b/integrations/claude-code-plugin/core/hook_runner.py
@@ -290,6 +290,11 @@ def run(
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()
@@ -305,8 +310,19 @@ def run(
return 0
if args.action == "session-start":
- if telemetry.is_first_run():
+ # 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:
diff --git a/integrations/claude-code-plugin/core/telemetry.py b/integrations/claude-code-plugin/core/telemetry.py
index a4375f002..c1fc0084c 100644
--- a/integrations/claude-code-plugin/core/telemetry.py
+++ b/integrations/claude-code-plugin/core/telemetry.py
@@ -302,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(
@@ -633,21 +800,72 @@ 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:
diff --git a/integrations/claude-code-plugin/tests/test_telemetry.py b/integrations/claude-code-plugin/tests/test_telemetry.py
index de0db10c6..73bf8f121 100644
--- a/integrations/claude-code-plugin/tests/test_telemetry.py
+++ b/integrations/claude-code-plugin/tests/test_telemetry.py
@@ -265,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
diff --git a/integrations/codex-plugin/core/hook_runner.py b/integrations/codex-plugin/core/hook_runner.py
index 2a2adb557..b3d8a3210 100644
--- a/integrations/codex-plugin/core/hook_runner.py
+++ b/integrations/codex-plugin/core/hook_runner.py
@@ -290,6 +290,11 @@ def run(
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()
@@ -305,8 +310,19 @@ def run(
return 0
if args.action == "session-start":
- if telemetry.is_first_run():
+ # 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:
diff --git a/integrations/codex-plugin/core/telemetry.py b/integrations/codex-plugin/core/telemetry.py
index a4375f002..c1fc0084c 100644
--- a/integrations/codex-plugin/core/telemetry.py
+++ b/integrations/codex-plugin/core/telemetry.py
@@ -302,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(
@@ -633,21 +800,72 @@ 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:
diff --git a/integrations/cursor-plugin/core/hook_runner.py b/integrations/cursor-plugin/core/hook_runner.py
index 2a2adb557..b3d8a3210 100644
--- a/integrations/cursor-plugin/core/hook_runner.py
+++ b/integrations/cursor-plugin/core/hook_runner.py
@@ -290,6 +290,11 @@ def run(
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()
@@ -305,8 +310,19 @@ def run(
return 0
if args.action == "session-start":
- if telemetry.is_first_run():
+ # 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:
diff --git a/integrations/cursor-plugin/core/telemetry.py b/integrations/cursor-plugin/core/telemetry.py
index a4375f002..c1fc0084c 100644
--- a/integrations/cursor-plugin/core/telemetry.py
+++ b/integrations/cursor-plugin/core/telemetry.py
@@ -302,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(
@@ -633,21 +800,72 @@ 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:
diff --git a/integrations/kimi-plugin/core/hook_runner.py b/integrations/kimi-plugin/core/hook_runner.py
index 2a2adb557..b3d8a3210 100644
--- a/integrations/kimi-plugin/core/hook_runner.py
+++ b/integrations/kimi-plugin/core/hook_runner.py
@@ -290,6 +290,11 @@ def run(
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()
@@ -305,8 +310,19 @@ def run(
return 0
if args.action == "session-start":
- if telemetry.is_first_run():
+ # 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:
diff --git a/integrations/kimi-plugin/core/telemetry.py b/integrations/kimi-plugin/core/telemetry.py
index a4375f002..c1fc0084c 100644
--- a/integrations/kimi-plugin/core/telemetry.py
+++ b/integrations/kimi-plugin/core/telemetry.py
@@ -302,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(
@@ -633,21 +800,72 @@ 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:
diff --git a/integrations/mem0-agent-plugin/core/telemetry.py b/integrations/mem0-agent-plugin/core/telemetry.py
index a4375f002..c1fc0084c 100644
--- a/integrations/mem0-agent-plugin/core/telemetry.py
+++ b/integrations/mem0-agent-plugin/core/telemetry.py
@@ -302,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(
@@ -633,21 +800,72 @@ 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:
From 1a5c7ad28c67ae04381998eb69d829fd1de55de9 Mon Sep 17 00:00:00 2001
From: Saket Aryan
Date: Fri, 18 Sep 2026 14:13:11 +0530
Subject: [PATCH 11/54] feat(integrations): declare which surface each client
is, and its version (#7326)
---
cli/node/src/backend/platform.ts | 3 +-
cli/python/src/mem0_cli/backend/platform.py | 3 +-
integrations/AGENTS.md | 43 +++++++
integrations/agent-plugin-core/build/build.py | 16 ++-
.../agent-plugin-core/python/memory_core.py | 41 +++++-
.../agent-plugin-core/tests/test_build.py | 32 +++++
.../tests/test_uninitialised_identity.py | 27 ++++
.../antigravity-plugin/core/_harness_id.py | 2 +
.../antigravity-plugin/core/memory_core.py | 41 +++++-
.../claude-code-plugin/core/_harness_id.py | 2 +
.../claude-code-plugin/core/memory_core.py | 41 +++++-
integrations/codex-plugin/core/_harness_id.py | 2 +
integrations/codex-plugin/core/memory_core.py | 41 +++++-
.../cursor-plugin/core/_harness_id.py | 2 +
.../cursor-plugin/core/memory_core.py | 41 +++++-
integrations/deepseek-plugin/src/index.ts | 5 +-
integrations/kimi-plugin/core/_harness_id.py | 2 +
integrations/kimi-plugin/core/memory_core.py | 41 +++++-
.../mem0-agent-plugin/core/_harness_id.py | 4 +-
.../mem0-agent-plugin/core/memory_core.py | 41 +++++-
.../pi-agent-plugin/src/attribution.test.ts | 80 ++++++++++++
.../pi-agent-plugin/src/attribution.ts | 65 ++++++++++
integrations/pi-agent-plugin/src/commands.ts | 16 ++-
integrations/pi-agent-plugin/src/entry.ts | 6 +
integrations/vercel-ai-sdk/src/mem0-utils.ts | 19 ++-
integrations/vercel-ai-sdk/tsconfig.json | 1 +
integrations/vercel-ai-sdk/tsup.config.ts | 7 ++
mem0-ts/src/client/mem0.ts | 61 +++++++++
mem0-ts/src/client/mem0.types.ts | 3 +
mem0/client/main.py | 118 ++++++++++++++----
tests/test_client_surface_headers.py | 63 ++++++++++
31 files changed, 812 insertions(+), 57 deletions(-)
create mode 100644 integrations/pi-agent-plugin/src/attribution.test.ts
create mode 100644 integrations/pi-agent-plugin/src/attribution.ts
create mode 100644 tests/test_client_surface_headers.py
diff --git a/cli/node/src/backend/platform.ts b/cli/node/src/backend/platform.ts
index 705a3d470..65a4b6228 100644
--- a/cli/node/src/backend/platform.ts
+++ b/cli/node/src/backend/platform.ts
@@ -31,7 +31,8 @@ export class PlatformBackend implements Backend {
this.headers = {
Authorization: `Token ${config.apiKey}`,
"Content-Type": "application/json",
- "X-Mem0-Source": "cli",
+ "X-Mem0-Source": "CLI",
+ "X-Mem0-Client": `mem0-cli-node/${CLI_VERSION}`,
"X-Mem0-Client-Language": "node",
"X-Mem0-Client-Version": CLI_VERSION,
};
diff --git a/cli/python/src/mem0_cli/backend/platform.py b/cli/python/src/mem0_cli/backend/platform.py
index 1d153da9c..a9ce60df1 100644
--- a/cli/python/src/mem0_cli/backend/platform.py
+++ b/cli/python/src/mem0_cli/backend/platform.py
@@ -27,7 +27,8 @@ class PlatformBackend(Backend):
headers={
"Authorization": f"Token {config.api_key}",
"Content-Type": "application/json",
- "X-Mem0-Source": "cli",
+ "X-Mem0-Source": "CLI",
+ "X-Mem0-Client": f"mem0-cli-python/{__version__}",
"X-Mem0-Client-Language": "python",
"X-Mem0-Client-Version": __version__,
},
diff --git a/integrations/AGENTS.md b/integrations/AGENTS.md
index c129dd48b..221c8206f 100644
--- a/integrations/AGENTS.md
+++ b/integrations/AGENTS.md
@@ -49,6 +49,48 @@ Run the type check after every TypeScript change: `pnpm run typecheck` or `tsc -
- **`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. 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/`.
@@ -59,3 +101,4 @@ Run the type check after every TypeScript change: `pnpm run typecheck` or `tsc -
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/build/build.py b/integrations/agent-plugin-core/build/build.py
index e675efb02..3059b9b1f 100644
--- a/integrations/agent-plugin-core/build/build.py
+++ b/integrations/agent-plugin-core/build/build.py
@@ -81,15 +81,23 @@ def replace_output(staged: Path, output: Path) -> Path:
return output
-def _render_harness_id(host: str) -> str:
+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"
@@ -98,8 +106,10 @@ def _render_harness_id(host: str) -> str:
"\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 = "{host}"\n'
+ f'PLATFORM_APPLICATION = "{application}"\n'
)
@@ -122,7 +132,7 @@ def _bundle_python(
# 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), encoding="utf-8")
+ (core / "_harness_id.py").write_text(_render_harness_id(host, portable=portable), encoding="utf-8")
values = {
"PLUGIN_ROOT": plugin_root,
diff --git a/integrations/agent-plugin-core/python/memory_core.py b/integrations/agent-plugin-core/python/memory_core.py
index 77d7a2b80..d350e76d2 100644
--- a/integrations/agent-plugin-core/python/memory_core.py
+++ b/integrations/agent-plugin-core/python/memory_core.py
@@ -1800,6 +1800,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]:
@@ -1807,7 +1835,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:
@@ -1834,7 +1862,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:
@@ -1980,6 +2008,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,
@@ -2523,7 +2558,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/agent-plugin-core/tests/test_build.py b/integrations/agent-plugin-core/tests/test_build.py
index 54b5e5c6a..23295cc38 100644
--- a/integrations/agent-plugin-core/tests/test_build.py
+++ b/integrations/agent-plugin-core/tests/test_build.py
@@ -70,6 +70,38 @@ def test_portable_bundle_is_conformant_and_self_contained(tmp_path: Path) -> Non
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)
diff --git a/integrations/agent-plugin-core/tests/test_uninitialised_identity.py b/integrations/agent-plugin-core/tests/test_uninitialised_identity.py
index 7d48dbcc3..74a31fa5c 100644
--- a/integrations/agent-plugin-core/tests/test_uninitialised_identity.py
+++ b/integrations/agent-plugin-core/tests/test_uninitialised_identity.py
@@ -179,6 +179,33 @@ def test_source_tag_defaults_agree_between_the_two_modules():
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(
diff --git a/integrations/antigravity-plugin/core/_harness_id.py b/integrations/antigravity-plugin/core/_harness_id.py
index 2c8a515f4..18b7f68ec 100644
--- a/integrations/antigravity-plugin/core/_harness_id.py
+++ b/integrations/antigravity-plugin/core/_harness_id.py
@@ -5,5 +5,7 @@ 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/memory_core.py b/integrations/antigravity-plugin/core/memory_core.py
index 77d7a2b80..d350e76d2 100644
--- a/integrations/antigravity-plugin/core/memory_core.py
+++ b/integrations/antigravity-plugin/core/memory_core.py
@@ -1800,6 +1800,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]:
@@ -1807,7 +1835,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:
@@ -1834,7 +1862,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:
@@ -1980,6 +2008,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,
@@ -2523,7 +2558,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/_harness_id.py b/integrations/claude-code-plugin/core/_harness_id.py
index 6c3e1ce15..9c4949408 100644
--- a/integrations/claude-code-plugin/core/_harness_id.py
+++ b/integrations/claude-code-plugin/core/_harness_id.py
@@ -5,5 +5,7 @@ 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/memory_core.py b/integrations/claude-code-plugin/core/memory_core.py
index 77d7a2b80..d350e76d2 100644
--- a/integrations/claude-code-plugin/core/memory_core.py
+++ b/integrations/claude-code-plugin/core/memory_core.py
@@ -1800,6 +1800,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]:
@@ -1807,7 +1835,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:
@@ -1834,7 +1862,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:
@@ -1980,6 +2008,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,
@@ -2523,7 +2558,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/codex-plugin/core/_harness_id.py b/integrations/codex-plugin/core/_harness_id.py
index 152313a21..47938ee08 100644
--- a/integrations/codex-plugin/core/_harness_id.py
+++ b/integrations/codex-plugin/core/_harness_id.py
@@ -5,5 +5,7 @@ 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/memory_core.py b/integrations/codex-plugin/core/memory_core.py
index 77d7a2b80..d350e76d2 100644
--- a/integrations/codex-plugin/core/memory_core.py
+++ b/integrations/codex-plugin/core/memory_core.py
@@ -1800,6 +1800,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]:
@@ -1807,7 +1835,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:
@@ -1834,7 +1862,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:
@@ -1980,6 +2008,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,
@@ -2523,7 +2558,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/cursor-plugin/core/_harness_id.py b/integrations/cursor-plugin/core/_harness_id.py
index 40241a7f4..0e20bf1ff 100644
--- a/integrations/cursor-plugin/core/_harness_id.py
+++ b/integrations/cursor-plugin/core/_harness_id.py
@@ -5,5 +5,7 @@ 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/memory_core.py b/integrations/cursor-plugin/core/memory_core.py
index 77d7a2b80..d350e76d2 100644
--- a/integrations/cursor-plugin/core/memory_core.py
+++ b/integrations/cursor-plugin/core/memory_core.py
@@ -1800,6 +1800,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]:
@@ -1807,7 +1835,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:
@@ -1834,7 +1862,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:
@@ -1980,6 +2008,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,
@@ -2523,7 +2558,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/deepseek-plugin/src/index.ts b/integrations/deepseek-plugin/src/index.ts
index 2d24b498a..3ac86f4b0 100644
--- a/integrations/deepseek-plugin/src/index.ts
+++ b/integrations/deepseek-plugin/src/index.ts
@@ -26,8 +26,9 @@ export const name = "mem0";
export const inject = ["tools", "systemPrompt"];
// Tags writes so Mem0's backend attributes them to this integration in
-// telemetry. The backend's KNOWN_EVENT_SOURCES allowlist recognizes this value;
-// anything outside it buckets into "OTHERS".
+// 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;
diff --git a/integrations/kimi-plugin/core/_harness_id.py b/integrations/kimi-plugin/core/_harness_id.py
index aa17750b1..83ab061ef 100644
--- a/integrations/kimi-plugin/core/_harness_id.py
+++ b/integrations/kimi-plugin/core/_harness_id.py
@@ -5,5 +5,7 @@ SOURCE_TAG = "KIMI_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 = "kimi"
diff --git a/integrations/kimi-plugin/core/memory_core.py b/integrations/kimi-plugin/core/memory_core.py
index 77d7a2b80..d350e76d2 100644
--- a/integrations/kimi-plugin/core/memory_core.py
+++ b/integrations/kimi-plugin/core/memory_core.py
@@ -1800,6 +1800,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]:
@@ -1807,7 +1835,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:
@@ -1834,7 +1862,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:
@@ -1980,6 +2008,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,
@@ -2523,7 +2558,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/mem0-agent-plugin/core/_harness_id.py b/integrations/mem0-agent-plugin/core/_harness_id.py
index b0836d6de..3efd000f8 100644
--- a/integrations/mem0-agent-plugin/core/_harness_id.py
+++ b/integrations/mem0-agent-plugin/core/_harness_id.py
@@ -5,5 +5,7 @@ SOURCE_TAG = "CODING_AGENT_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 = "coding-agent"
+PLATFORM_APPLICATION = ""
diff --git a/integrations/mem0-agent-plugin/core/memory_core.py b/integrations/mem0-agent-plugin/core/memory_core.py
index 77d7a2b80..d350e76d2 100644
--- a/integrations/mem0-agent-plugin/core/memory_core.py
+++ b/integrations/mem0-agent-plugin/core/memory_core.py
@@ -1800,6 +1800,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]:
@@ -1807,7 +1835,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:
@@ -1834,7 +1862,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:
@@ -1980,6 +2008,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,
@@ -2523,7 +2558,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/pi-agent-plugin/src/attribution.test.ts b/integrations/pi-agent-plugin/src/attribution.test.ts
new file mode 100644
index 000000000..f90d28da3
--- /dev/null
+++ b/integrations/pi-agent-plugin/src/attribution.test.ts
@@ -0,0 +1,80 @@
+import { describe, expect, it } from "vitest";
+import { applySurfaceHeaders, PLATFORM_APPLICATION, PLATFORM_SOURCE } from "./attribution.ts";
+
+function client(headers: Record = {}) {
+ return { headers: { Authorization: "Token k", ...headers } } as never;
+}
+
+describe("applySurfaceHeaders", () => {
+ it("stamps the shared client so every path is attributed, not just commands", () => {
+ const mem0 = client();
+ applySurfaceHeaders(mem0);
+ const headers = (mem0 as unknown as { headers: Record }).headers;
+
+ expect(headers["X-Mem0-Source"]).toBe(PLATFORM_SOURCE);
+ expect(headers["X-Application"]).toBe(PLATFORM_APPLICATION);
+ expect(headers["X-Mem0-Client"]).toMatch(/^mem0-pi-agent\//);
+ expect(headers.Authorization).toBe("Token k");
+ });
+
+ it("defers to a surface an outer wrapper already declared", () => {
+ const mem0 = client({ "X-Mem0-Source": "OPENCLAW", "X-Application": "vscode" });
+ applySurfaceHeaders(mem0);
+ const headers = (mem0 as unknown as { headers: Record }).headers;
+
+ expect(headers["X-Mem0-Source"]).toBe("OPENCLAW");
+ expect(headers["X-Application"]).toBe("vscode");
+ });
+
+ it("appends to the client stack rather than replacing it", () => {
+ const mem0 = client({ "X-Mem0-Client": "openclaw/2.1.0" });
+ applySurfaceHeaders(mem0);
+ const headers = (mem0 as unknown as { headers: Record }).headers;
+
+ expect(headers["X-Mem0-Client"]).toMatch(/^openclaw\/2\.1\.0, mem0-pi-agent\//);
+ });
+
+ it("treats a blank header as absent", () => {
+ const mem0 = client({ "X-Mem0-Source": " " });
+ applySurfaceHeaders(mem0);
+ const headers = (mem0 as unknown as { headers: Record }).headers;
+
+ expect(headers["X-Mem0-Source"]).toBe(PLATFORM_SOURCE);
+ });
+
+ it("bounds the stack so a long chain cannot grow the header without limit", () => {
+ const mem0 = client({ "X-Mem0-Client": "a/1, b/1, c/1, d/1, e/1" });
+ applySurfaceHeaders(mem0);
+ const headers = (mem0 as unknown as { headers: Record }).headers;
+
+ expect(headers["X-Mem0-Client"].split(",").length).toBeLessThanOrEqual(4);
+ expect(headers["X-Mem0-Client"].length).toBeLessThanOrEqual(200);
+ });
+});
+
+describe("client stack bounding", () => {
+ it("keeps our own entry when the caller already filled the stack", () => {
+ // The defect: pushing then trimming to four dropped exactly the entry this
+ // function exists to add, so we vanished from our own stack.
+ const mem0 = client({ "X-Mem0-Client": "a/1, b/2, c/3, d/4" });
+ applySurfaceHeaders(mem0);
+ const stack = (mem0 as unknown as { headers: Record }).headers["X-Mem0-Client"];
+
+ expect(stack).toMatch(/mem0-pi-agent\//);
+ expect(stack.split(",").length).toBeLessThanOrEqual(4);
+ });
+
+ it("drops whole entries at the character cap, never a fragment", () => {
+ const long = `${"n".repeat(90)}/1.0, ${"m".repeat(90)}/1.0, ${"o".repeat(90)}/1.0`;
+ const mem0 = client({ "X-Mem0-Client": long });
+ applySurfaceHeaders(mem0);
+ const stack = (mem0 as unknown as { headers: Record }).headers["X-Mem0-Client"];
+
+ expect(stack.length).toBeLessThanOrEqual(200);
+ expect(stack.endsWith("/0.0.0") || /mem0-pi-agent\/[\w.\-]+$/.test(stack)).toBe(true);
+ // Every surviving entry is whole: name/version, no severed tail.
+ for (const entry of stack.split(",")) {
+ expect(entry.trim()).toMatch(/^[^/]+\/[^/]+$/);
+ }
+ });
+});
diff --git a/integrations/pi-agent-plugin/src/attribution.ts b/integrations/pi-agent-plugin/src/attribution.ts
new file mode 100644
index 000000000..2cbc9a73e
--- /dev/null
+++ b/integrations/pi-agent-plugin/src/attribution.ts
@@ -0,0 +1,65 @@
+import type MemoryClient from "mem0ai";
+import * as fs from "node:fs";
+
+/** Surface identity for this plugin, as the platform's EventSource knows it. */
+export const PLATFORM_SOURCE = "PI_AGENT";
+
+/** Host app the plugin runs inside. Allowlisted server-side. */
+export const PLATFORM_APPLICATION = "pi";
+
+const PLUGIN_VERSION = (() => {
+ try {
+ return JSON.parse(
+ fs.readFileSync(new URL("../package.json", import.meta.url), "utf-8"),
+ ).version as string;
+ } catch {
+ return "unknown";
+ }
+})();
+
+const MAX_STACK_ENTRIES = 4;
+const MAX_STACK_CHARS = 200;
+
+/**
+ * Append our own entry and bound the result, dropping WHOLE entries.
+ *
+ * Neither cap cuts characters: slicing the joined string severs an identifier
+ * and leaves a fragment the platform parses as a real client name. And the
+ * reserved slot is ours, since it is the only entry this layer can vouch for.
+ */
+function boundedStack(callerEntries: string[], own: string): string {
+ const kept: string[] = [];
+ let budget = MAX_STACK_CHARS - own.length;
+ for (const entry of callerEntries.slice(0, MAX_STACK_ENTRIES - 1)) {
+ const cost = entry.length + ", ".length;
+ if (cost > budget) break;
+ budget -= cost;
+ kept.push(entry);
+ }
+ return [...kept, own].join(", ");
+}
+
+/**
+ * Stamp surface identity onto the shared client, once, at construction.
+ *
+ * Tagging individual call sites was not enough: automatic recall, capture, the
+ * memory tools and deletion all go through this same client, so everything
+ * except the explicit slash commands reached the platform as generic SDK
+ * traffic. Every request method in the SDK sends `this.headers`, so setting
+ * them here covers all of them.
+ *
+ * X-Mem0-Source and X-Application are set-once, so a wrapper that already named
+ * a surface keeps it. X-Mem0-Client is append-only, so the platform sees the
+ * whole chain rather than only the last speaker.
+ */
+export function applySurfaceHeaders(client: MemoryClient): void {
+ const headers = client.headers as Record;
+ if (!headers["X-Mem0-Source"]?.trim()) headers["X-Mem0-Source"] = PLATFORM_SOURCE;
+ if (!headers["X-Application"]?.trim()) headers["X-Application"] = PLATFORM_APPLICATION;
+
+ const existing = (headers["X-Mem0-Client"] ?? "")
+ .split(",")
+ .map((part) => part.trim())
+ .filter(Boolean);
+ headers["X-Mem0-Client"] = boundedStack(existing, `mem0-pi-agent/${PLUGIN_VERSION}`);
+}
diff --git a/integrations/pi-agent-plugin/src/commands.ts b/integrations/pi-agent-plugin/src/commands.ts
index 9379bed9a..e969478a1 100644
--- a/integrations/pi-agent-plugin/src/commands.ts
+++ b/integrations/pi-agent-plugin/src/commands.ts
@@ -1,3 +1,4 @@
+import type { SearchMemoryOptions } from "mem0ai";
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
import type MemoryClient from "mem0ai";
import type { Mem0Config, ScopeContext, Scope } from "./types.ts";
@@ -5,6 +6,12 @@ import { DEFAULT_CUSTOM_CATEGORIES } from "./types.ts";
import { resolveSearchFilters, resolveAddParams } from "./memory/scoping.ts";
import { formatMemoryList, formatMemoryCompact, groupByCategory } from "./memory/formatting.ts";
import { captureCommandEvent } from "./telemetry.ts";
+import { PLATFORM_SOURCE } from "./attribution.ts";
+
+// Wire identity is set once on the shared client in entry.ts, which covers
+// every path including recall, capture, tools and deletion. It stays in the
+// body of the two calls below as well: body `source` is what the backend reads
+// when the header is absent.
const SEARCH_TOP_K = 10;
@@ -29,7 +36,12 @@ export function registerCommands(
threshold: config.searchThreshold,
topK: SEARCH_TOP_K,
rerank: true,
- });
+ source: PLATFORM_SOURCE,
+ // Widened by exactly this one property. `source` reaches the wire via the
+ // SDK's camelToSnakeKeys spread, but it is absent from SearchMemoryOptions
+ // in the published mem0ai types. A blanket `as never` would also disable
+ // checking of filters, threshold, topK and rerank above.
+ } as SearchMemoryOptions & { source: string });
return result.results ?? [];
};
@@ -45,7 +57,7 @@ export function registerCommands(
const addParams = resolveAddParams(config.defaultScope, getScopeCtx());
const result = await mem0.add(
[{ role: "user", content: text }],
- { ...addParams, customCategories: DEFAULT_CUSTOM_CATEGORIES, infer: false },
+ { ...addParams, customCategories: DEFAULT_CUSTOM_CATEGORIES, infer: false, source: PLATFORM_SOURCE },
);
captureCommandEvent("mem0-remember", {}, telemetryCtx);
diff --git a/integrations/pi-agent-plugin/src/entry.ts b/integrations/pi-agent-plugin/src/entry.ts
index d49d78ad0..256c05aa4 100644
--- a/integrations/pi-agent-plugin/src/entry.ts
+++ b/integrations/pi-agent-plugin/src/entry.ts
@@ -10,6 +10,7 @@ import { captureEvent } from "./telemetry.ts";
import * as os from "node:os";
import type { ScopeContext } from "./types.ts";
import { createMemoryLifecycle } from "../../agent-plugin-core/typescript/src/lifecycle.ts";
+import { applySurfaceHeaders } from "./attribution.ts";
export { buildRecallContext } from "../../agent-plugin-core/typescript/src/lifecycle.ts";
@@ -29,6 +30,11 @@ export default function mem0Extension(pi: ExtensionAPI): void {
}
const mem0 = new MemoryClient({ apiKey: config.apiKey });
+ // Every path below shares this client: automatic recall, capture, the memory
+ // tools and deletion as well as the slash commands. Attribution belongs here
+ // rather than on individual calls, or everything except the commands reports
+ // as generic SDK traffic.
+ applySurfaceHeaders(mem0);
const scopeCtx: ScopeContext = {
userId: resolveUserId(config.userId),
diff --git a/integrations/vercel-ai-sdk/src/mem0-utils.ts b/integrations/vercel-ai-sdk/src/mem0-utils.ts
index 55d485cbc..b7a041939 100644
--- a/integrations/vercel-ai-sdk/src/mem0-utils.ts
+++ b/integrations/vercel-ai-sdk/src/mem0-utils.ts
@@ -1,3 +1,10 @@
+declare const __MEM0_PROVIDER_VERSION__: string | undefined;
+
+// Replaced at build time by tsup `define`. The fallback only applies when the
+// source is run unbundled, such as in tests.
+const PROVIDER_VERSION =
+ typeof __MEM0_PROVIDER_VERSION__ !== "undefined" ? __MEM0_PROVIDER_VERSION__ : "dev";
+
import { LanguageModelV3Prompt } from '@ai-sdk/provider';
import { Mem0ConfigSettings } from './mem0-types';
import { loadApiKey } from '@ai-sdk/provider-utils';
@@ -277,7 +284,11 @@ const searchInternalMemories = async (query: string, config?: Mem0ConfigSettings
method: 'POST',
headers: {
Authorization: `Token ${apiKey}`,
- 'Content-Type': 'application/json'
+ 'Content-Type': 'application/json',
+ // Surface attribution. Set-once by contract: this wrapper is the
+ // outermost layer on these raw fetch calls.
+ 'X-Mem0-Source': 'VERCEL_AI_SDK',
+ 'X-Mem0-Client': `mem0-vercel-ai-provider/${PROVIDER_VERSION}`
},
body: JSON.stringify(body),
};
@@ -331,7 +342,11 @@ const updateMemories = async (messages: Array, config?: Mem0ConfigSetti
method: 'POST',
headers: {
Authorization: `Token ${apiKey}`,
- 'Content-Type': 'application/json'
+ 'Content-Type': 'application/json',
+ // Surface attribution. Set-once by contract: this wrapper is the
+ // outermost layer on these raw fetch calls.
+ 'X-Mem0-Source': 'VERCEL_AI_SDK',
+ 'X-Mem0-Client': `mem0-vercel-ai-provider/${PROVIDER_VERSION}`
},
body: JSON.stringify(body),
};
diff --git a/integrations/vercel-ai-sdk/tsconfig.json b/integrations/vercel-ai-sdk/tsconfig.json
index b05d5db02..e40350730 100644
--- a/integrations/vercel-ai-sdk/tsconfig.json
+++ b/integrations/vercel-ai-sdk/tsconfig.json
@@ -12,6 +12,7 @@
"noUnusedLocals": false,
"noUnusedParameters": false,
"preserveWatchOutput": true,
+ "resolveJsonModule": true,
"skipLibCheck": true,
"strict": true,
"types": ["@types/node", "jest"],
diff --git a/integrations/vercel-ai-sdk/tsup.config.ts b/integrations/vercel-ai-sdk/tsup.config.ts
index 2c8f74a6d..ff2d298c0 100644
--- a/integrations/vercel-ai-sdk/tsup.config.ts
+++ b/integrations/vercel-ai-sdk/tsup.config.ts
@@ -1,4 +1,5 @@
import { defineConfig } from 'tsup'
+import pkg from './package.json'
export default defineConfig([
{
@@ -6,5 +7,11 @@ export default defineConfig([
entry: ['src/index.ts'],
format: ['cjs', 'esm'],
sourcemap: true,
+ // Injected rather than written in the source. A hardcoded literal matches
+ // package.json on the day it is written and misreports the client version
+ // from the next release bump onwards. Same mechanism as mem0-ts.
+ define: {
+ __MEM0_PROVIDER_VERSION__: JSON.stringify(pkg.version),
+ },
},
])
\ No newline at end of file
diff --git a/mem0-ts/src/client/mem0.ts b/mem0-ts/src/client/mem0.ts
index ff259f2fe..33e03f0c2 100644
--- a/mem0-ts/src/client/mem0.ts
+++ b/mem0-ts/src/client/mem0.ts
@@ -95,6 +95,66 @@ interface ClientIdentity {
const IDENTITY_CACHE_MAX_DEFAULT = 50;
const identityByCredentials = new Map>();
+declare const __MEM0_SDK_VERSION__: string | undefined;
+
+// Injected by tsup (see mem0-ts/tsup.config.ts `define`), the same mechanism
+// telemetry.ts already uses. A hardcoded literal goes stale at the next release
+// bump and then misreports the client version forever.
+const SDK_VERSION =
+ typeof __MEM0_SDK_VERSION__ !== "undefined" ? __MEM0_SDK_VERSION__ : "dev";
+
+const MAX_STACK_ENTRIES = 4;
+const MAX_STACK_CHARS = 200;
+
+/**
+ * Append our own entry and bound the result, dropping WHOLE entries.
+ *
+ * Neither cap cuts characters: slicing the joined string severs an identifier
+ * and leaves a fragment the platform parses as a real client name. And the
+ * reserved slot is ours. Pushing first and then trimming to four dropped exactly
+ * the entry this exists to add whenever a caller already sent four, so we
+ * vanished from our own stack while every caller claim survived.
+ */
+function boundedStack(callerEntries: string[], own: string): string {
+ const kept: string[] = [];
+ let budget = MAX_STACK_CHARS - own.length;
+ for (const entry of callerEntries.slice(0, MAX_STACK_ENTRIES - 1)) {
+ const cost = entry.length + ", ".length;
+ if (cost > budget) break;
+ budget -= cost;
+ kept.push(entry);
+ }
+ return [...kept, own].join(", ");
+}
+
+/**
+ * Surface-identity headers.
+ *
+ * X-Mem0-Source and X-Application are SET-ONCE by contract: whichever layer is
+ * outermost sets them and nothing below overwrites, so a plugin wrapping this
+ * SDK keeps its own identity. X-Mem0-Client is APPEND-ONLY - every layer adds
+ * itself, so the platform sees the whole stack and not just the last speaker.
+ */
+function surfaceHeaders(): Record {
+ const env: Record =
+ typeof process !== "undefined" && process.env ? process.env : {};
+ const existing = (env.MEM0_CLIENT_STACK ?? "").trim();
+ const entries = existing
+ ? existing
+ .split(",")
+ .map((part) => part.trim())
+ .filter(Boolean)
+ : [];
+ const headers: Record = {
+ "X-Mem0-Client": boundedStack(entries, `mem0-js/${SDK_VERSION}`),
+ };
+ const source = (env.MEM0_SOURCE ?? "").trim();
+ if (source) headers["X-Mem0-Source"] = source;
+ const application = (env.MEM0_APPLICATION ?? "").trim();
+ if (application) headers["X-Application"] = application;
+ return headers;
+}
+
export default class MemoryClient {
apiKey: string;
host: string;
@@ -129,6 +189,7 @@ export default class MemoryClient {
this.headers = {
Authorization: `Token ${this.apiKey}`,
"Content-Type": "application/json",
+ ...surfaceHeaders(),
};
this.client = axios.create({
diff --git a/mem0-ts/src/client/mem0.types.ts b/mem0-ts/src/client/mem0.types.ts
index c230441e0..cbe541321 100644
--- a/mem0-ts/src/client/mem0.types.ts
+++ b/mem0-ts/src/client/mem0.types.ts
@@ -30,6 +30,9 @@ export interface SearchMemoryOptions {
showExpired?: boolean;
referenceDate?: string | number;
keywordSearch?: boolean;
+ /** Surface that produced the call, e.g. "OPENCLAW". Must be a value the
+ * backend's EventSource enum knows, or it buckets into OTHERS. */
+ source?: string;
}
export interface GetAllMemoryOptions {
diff --git a/mem0/client/main.py b/mem0/client/main.py
index a52986dcd..3a82d9e5a 100644
--- a/mem0/client/main.py
+++ b/mem0/client/main.py
@@ -79,6 +79,95 @@ def _maybe_alias_anon_to_email(user_email):
logger.debug("Failed to alias anon telemetry to %r: %s", user_email, e)
+def _sdk_version() -> str:
+ """Resolved here rather than imported from the package root, which would cycle."""
+ try:
+ import importlib.metadata
+
+ return importlib.metadata.version("mem0ai")
+ except Exception:
+ return "unknown"
+
+
+def _apply_client_headers(client: Any, api_key: str, user_id: str) -> None:
+ """Merge our headers into a caller-supplied client without erasing theirs.
+
+ A wrapper may hand us a client already carrying its own X-Mem0-Source or a
+ partial X-Mem0-Client stack. Blanket update() replaced both, which is the
+ opposite of the set-once / append-only contract: the outermost layer is the
+ one whose identity should survive.
+ """
+ existing = client.headers
+ mine = _client_headers(api_key, user_id)
+
+ outer_stack = existing.get("X-Mem0-Client")
+ if outer_stack:
+ entries = [part.strip() for part in str(outer_stack).split(",") if part.strip()]
+ mine["X-Mem0-Client"] = _bounded_stack(entries, f"mem0-python/{_sdk_version()}")
+
+ for name, value in mine.items():
+ if name in ("X-Mem0-Source", "X-Application") and existing.get(name):
+ continue
+ existing[name] = value
+
+
+MAX_STACK_ENTRIES = 4
+MAX_STACK_CHARS = 200
+
+
+def _bounded_stack(caller_entries, own: str) -> str:
+ """Append our own entry and bound the result, dropping WHOLE entries.
+
+ Two rules, and the second is the one that was wrong. Neither cap cuts
+ characters: a blunt slice severs an identifier and leaves a fragment that
+ parses as a real client name. And the reserved slot is OURS. Appending first
+ and then trimming to four dropped exactly the entry this function exists to
+ add, every time a caller already sent four, so the SDK vanished from its own
+ stack while the caller's claims all survived.
+ """
+ kept = []
+ budget = MAX_STACK_CHARS - len(own)
+ for entry in list(caller_entries)[: MAX_STACK_ENTRIES - 1]:
+ cost = len(entry) + len(", ")
+ if cost > budget:
+ break
+ budget -= cost
+ kept.append(entry)
+ return ", ".join(kept + [own])
+
+
+def _client_headers(api_key: str, user_id: str) -> Dict[str, str]:
+ """Auth plus surface-identity headers.
+
+ X-Mem0-Source and X-Application are SET-ONCE by contract: whichever layer is
+ outermost sets them, and nothing below overwrites. A plugin or harness that
+ wraps this SDK therefore keeps its own identity — it declares via MEM0_SOURCE
+ / MEM0_APPLICATION and the SDK defers.
+
+ X-Mem0-Client is APPEND-ONLY: every layer adds itself, so the platform sees
+ the whole stack rather than only whoever spoke last.
+ """
+ headers = {
+ "Authorization": f"Token {api_key}",
+ "Mem0-User-ID": user_id,
+ "X-Mem0-Client": _client_stack(),
+ }
+ source = os.getenv("MEM0_SOURCE", "").strip()
+ if source:
+ headers["X-Mem0-Source"] = source
+ application = os.getenv("MEM0_APPLICATION", "").strip()
+ if application:
+ headers["X-Application"] = application
+ return headers
+
+
+def _client_stack() -> str:
+ """This SDK appended to any stack an outer layer already declared."""
+ existing = os.getenv("MEM0_CLIENT_STACK", "").strip()
+ entries = [part.strip() for part in existing.split(",") if part.strip()] if existing else []
+ return _bounded_stack(entries, f"mem0-python/{_sdk_version()}")
+
+
class MemoryClient:
"""Client for interacting with the Mem0 API.
@@ -129,19 +218,11 @@ class MemoryClient:
self.client = client
# Ensure the client has the correct base_url and headers
self.client.base_url = httpx.URL(self.host)
- self.client.headers.update(
- {
- "Authorization": f"Token {self.api_key}",
- "Mem0-User-ID": self.user_id,
- }
- )
+ _apply_client_headers(self.client, self.api_key, self.user_id)
else:
self.client = httpx.Client(
base_url=self.host,
- headers={
- "Authorization": f"Token {self.api_key}",
- "Mem0-User-ID": self.user_id,
- },
+ headers=_client_headers(self.api_key, self.user_id),
timeout=300,
)
self.user_email = self._validate_api_key()
@@ -1018,19 +1099,11 @@ class AsyncMemoryClient:
self.async_client = client
# Ensure the client has the correct base_url and headers
self.async_client.base_url = httpx.URL(self.host)
- self.async_client.headers.update(
- {
- "Authorization": f"Token {self.api_key}",
- "Mem0-User-ID": self.user_id,
- }
- )
+ _apply_client_headers(self.async_client, self.api_key, self.user_id)
else:
self.async_client = httpx.AsyncClient(
base_url=self.host,
- headers={
- "Authorization": f"Token {self.api_key}",
- "Mem0-User-ID": self.user_id,
- },
+ headers=_client_headers(self.api_key, self.user_id),
timeout=300,
)
@@ -1053,10 +1126,7 @@ class AsyncMemoryClient:
params = self._prepare_params()
response = requests.get(
f"{self.host}/v1/ping/",
- headers={
- "Authorization": f"Token {self.api_key}",
- "Mem0-User-ID": self.user_id,
- },
+ headers=_client_headers(self.api_key, self.user_id),
params=params,
)
response.raise_for_status()
diff --git a/tests/test_client_surface_headers.py b/tests/test_client_surface_headers.py
new file mode 100644
index 000000000..51d09d306
--- /dev/null
+++ b/tests/test_client_surface_headers.py
@@ -0,0 +1,63 @@
+"""Surface-identity headers, and that a client can be constructed at all.
+
+The construction test exists because it was not there: a signature change to
+_bounded_stack missed the _client_stack call site, every MemoryClient(...) raised
+TypeError, and the whole suite stayed green because nothing built one.
+"""
+
+import os
+from unittest.mock import patch
+
+from mem0.client.main import _bounded_stack, _client_headers, _client_stack
+
+
+def test_a_client_can_be_constructed():
+ from mem0 import MemoryClient
+
+ # _validate_api_key normally populates org/project from the API response;
+ # stubbing it leaves them None, which a later accessor rejects. Set them the
+ # way a real validation would. This test is about construction reaching the
+ # header stage at all.
+ def _stub(self):
+ self.org_id, self.project_id = "org", "proj"
+
+ with patch.object(MemoryClient, "_validate_api_key", _stub):
+ client = MemoryClient(api_key="m0-test")
+
+ assert client.client.headers["X-Mem0-Client"].startswith("mem0-python/")
+
+
+# AsyncMemoryClient is deliberately not constructed here: its validation path
+# makes a real request to /v1/ping/, and a unit test that needs the network is
+# worse than none. It shares _client_headers with the sync client, which is the
+# code the construction test above actually guards.
+def test_headers_carry_this_sdk():
+ headers = _client_headers("m0-test", "u1")
+ assert headers["X-Mem0-Client"].startswith("mem0-python/")
+
+
+def test_our_entry_survives_a_caller_that_already_filled_the_stack():
+ # Appending first and trimming to four dropped exactly the entry the
+ # function exists to add.
+ stack = _bounded_stack(["a/1", "b/2", "c/3", "d/4"], "mem0-python/9.9.9")
+
+ assert "mem0-python/9.9.9" in stack
+ assert len(stack.split(",")) <= 4
+
+
+def test_the_character_cap_drops_whole_entries_not_characters():
+ long_entries = [f"{'n' * 90}/1.0", f"{'m' * 90}/1.0", "c/3"]
+ stack = _bounded_stack(long_entries, "mem0-python/9.9.9")
+
+ assert len(stack) <= 200
+ assert stack.endswith("mem0-python/9.9.9")
+ for entry in stack.split(","):
+ assert entry.strip().count("/") == 1, f"severed entry: {entry!r}"
+
+
+def test_an_outer_stack_is_appended_to_not_replaced():
+ with patch.dict(os.environ, {"MEM0_CLIENT_STACK": "openclaw/2.1.0"}):
+ stack = _client_stack()
+
+ assert stack.startswith("openclaw/2.1.0")
+ assert "mem0-python/" in stack
From a8d36343128c0410a3e71626b8edfd31f875bd17 Mon Sep 17 00:00:00 2001
From: Saket Aryan
Date: Fri, 18 Sep 2026 14:13:22 +0530
Subject: [PATCH 12/54] fix(plugins): stop the TypeScript telemetry losing
events and misattributing accounts (#7358)
---
.github/workflows/opencode-plugin-checks.yml | 3 +
.../typescript/src/telemetry.ts | 99 ++++++-
.../typescript/tests/telemetry.test.ts | 247 ++++++++++++++++++
integrations/openclaw/cli/config-file.ts | 20 ++
integrations/openclaw/config.ts | 1 +
integrations/openclaw/openclaw.plugin.json | 4 +
integrations/openclaw/telemetry.ts | 64 ++++-
.../openclaw/tests/config-file.test.ts | 40 +++
integrations/openclaw/tests/config.test.ts | 15 ++
integrations/openclaw/tests/telemetry.test.ts | 80 +++++-
integrations/opencode-plugin/package.json | 1 +
.../opencode-plugin/telemetry.test.ts | 51 +++-
integrations/opencode-plugin/telemetry.ts | 27 +-
13 files changed, 623 insertions(+), 29 deletions(-)
diff --git a/.github/workflows/opencode-plugin-checks.yml b/.github/workflows/opencode-plugin-checks.yml
index 4fb95fc6c..a93d741eb 100644
--- a/.github/workflows/opencode-plugin-checks.yml
+++ b/.github/workflows/opencode-plugin-checks.yml
@@ -32,6 +32,9 @@ jobs:
- name: Type check
run: bun run type-check
+ - name: Test
+ run: bun test
+
- name: Build
run: bun run build
diff --git a/integrations/agent-plugin-core/typescript/src/telemetry.ts b/integrations/agent-plugin-core/typescript/src/telemetry.ts
index c6a7544ce..2b6c5286e 100644
--- a/integrations/agent-plugin-core/typescript/src/telemetry.ts
+++ b/integrations/agent-plugin-core/typescript/src/telemetry.ts
@@ -1,3 +1,5 @@
+import { randomUUID } from "node:crypto";
+
import { redactSecrets } from "./lifecycle.ts";
const POSTHOG_API_KEY = "phc_hgJkUVJFYtmaJqrvf6CYN67TIQ8yhXAkWzUn9AMU4yX";
@@ -74,34 +76,108 @@ export function errorKind(error: unknown): string {
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[]) => {
- await fetch(POSTHOG_BATCH_URL, {
+ 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(): Promise {
+ 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 {
- // Telemetry must never affect plugin behavior.
+ // 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 {
- void flush();
+ // 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 {
@@ -112,6 +188,15 @@ export function createTelemetry(config: TelemetryConfig) {
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 ?? {}),
@@ -134,8 +219,10 @@ export function createTelemetry(config: TelemetryConfig) {
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 (queue.length > maxQueueSize) queue = queue.slice(-maxQueueSize);
if (!timer) {
timer = setInterval(() => void flush(), config.flushIntervalMs ?? 5_000);
timer.unref?.();
@@ -149,6 +236,8 @@ export function createTelemetry(config: TelemetryConfig) {
function resetForTesting(): void {
queue = [];
+ consecutiveFailures = 0;
+ retryNotBefore = 0;
if (timer) clearInterval(timer);
timer = undefined;
process.off("beforeExit", beforeExit);
diff --git a/integrations/agent-plugin-core/typescript/tests/telemetry.test.ts b/integrations/agent-plugin-core/typescript/tests/telemetry.test.ts
index e04794614..cf9671682 100644
--- a/integrations/agent-plugin-core/typescript/tests/telemetry.test.ts
+++ b/integrations/agent-plugin-core/typescript/tests/telemetry.test.ts
@@ -122,3 +122,250 @@ test("error classification does not expose messages", () => {
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/openclaw/cli/config-file.ts b/integrations/openclaw/cli/config-file.ts
index 99453cb1b..a34d6c08b 100644
--- a/integrations/openclaw/cli/config-file.ts
+++ b/integrations/openclaw/cli/config-file.ts
@@ -35,6 +35,8 @@ export interface PluginAuthConfig {
autoCapture?: boolean;
topK?: number;
anonymousTelemetryId?: string;
+ /** SHA-256 prefix of the API key userEmail was resolved for. */
+ keyFingerprint?: string;
}
// ============================================================================
@@ -135,6 +137,9 @@ export function readPluginAuth(): PluginAuthConfig {
autoCapture: cfg.autoCapture as boolean | undefined,
topK: cfg.topK as number | undefined,
anonymousTelemetryId: cfg.anonymousTelemetryId as string | undefined,
+ // Without this the reader silently drops it, every fingerprint comparison
+ // fails against undefined, and the resolved email is never used again.
+ keyFingerprint: cfg.keyFingerprint as string | undefined,
};
}
@@ -236,6 +241,21 @@ export function getBaseUrl(): string {
return auth.baseUrl || DEFAULT_BASE_URL;
}
+/** Forget the resolved account, so the next capture re-resolves for the current key. */
+export function clearResolvedAccount(): void {
+ const full = readFullConfig() as any;
+ const cfg = full?.plugins?.entries?.[PLUGIN_ID]?.config;
+ if (!cfg) return;
+ let changed = false;
+ for (const key of ["userEmail", "keyFingerprint"]) {
+ if (key in cfg) {
+ delete cfg[key];
+ changed = true;
+ }
+ }
+ if (changed) writeFullConfig(full);
+}
+
/** Remove anonymousTelemetryId from config (after PostHog aliasing) */
export function clearAnonymousTelemetryId(): void {
const full = readFullConfig() as any;
diff --git a/integrations/openclaw/config.ts b/integrations/openclaw/config.ts
index 4e43c8c44..09dcbc837 100644
--- a/integrations/openclaw/config.ts
+++ b/integrations/openclaw/config.ts
@@ -148,6 +148,7 @@ const ALLOWED_KEYS = [
"mode",
"apiKey",
"anonymousTelemetryId",
+ "keyFingerprint",
"baseUrl",
"userId",
"userEmail",
diff --git a/integrations/openclaw/openclaw.plugin.json b/integrations/openclaw/openclaw.plugin.json
index 2d9f46518..02d05be4b 100644
--- a/integrations/openclaw/openclaw.plugin.json
+++ b/integrations/openclaw/openclaw.plugin.json
@@ -209,6 +209,10 @@
"type": "string",
"description": "Persistent anonymous telemetry identifier"
},
+ "keyFingerprint": {
+ "type": "string",
+ "description": "Digest of the API key userEmail was resolved for. Set automatically; a mismatch re-resolves the account."
+ },
"oss": {
"type": "object",
"properties": {
diff --git a/integrations/openclaw/telemetry.ts b/integrations/openclaw/telemetry.ts
index fc1c6b99d..bd77e1656 100644
--- a/integrations/openclaw/telemetry.ts
+++ b/integrations/openclaw/telemetry.ts
@@ -1,14 +1,20 @@
import { createHash, randomUUID } from "node:crypto";
import { createTelemetry } from "../agent-plugin-core/typescript/src/telemetry.ts";
-import { clearAnonymousTelemetryId, getBaseUrl, readPluginAuth, writePluginAuth } from "./cli/config-file.ts";
+import {
+ clearAnonymousTelemetryId,
+ clearResolvedAccount,
+ getBaseUrl,
+ readPluginAuth,
+ writePluginAuth,
+} from "./cli/config-file.ts";
declare const __OPENCLAW_PLUGIN_VERSION__: string;
export const PLUGIN_VERSION: string = __OPENCLAW_PLUGIN_VERSION__;
let cachedAnonymousId: string | undefined;
let aliasCheckDone = false;
-let emailResolutionAttempted = false;
+let resolutionAttemptedFor = "";
let currentDistinctId = "";
function enabled(): boolean {
@@ -33,10 +39,35 @@ function anonymousId(): string {
return (cachedAnonymousId = created);
}
+/** SHA-256 prefix of the key an account was resolved for. */
+function keyFingerprint(apiKey?: string): string {
+ return apiKey ? createHash("sha256").update(apiKey).digest("hex").slice(0, 16) : "";
+}
+
function distinctId(apiKey?: string): string {
try {
- const email = readPluginAuth().userEmail;
- if (email) return createHash("sha256").update(email).digest("hex");
+ const auth = readPluginAuth();
+ if (auth.userEmail) {
+ // Only when it belongs to the key in hand. Without this check a cached
+ // email was used forever: switch to a different account and every event
+ // kept reporting under the previous one, with nothing to notice it by.
+ if (auth.keyFingerprint === keyFingerprint(apiKey)) {
+ return createHash("sha256").update(auth.userEmail).digest("hex");
+ }
+ // Only a REAL key that disagrees means the account changed. Without the
+ // apiKey guard the comparison is `undefined === ""` for any call that
+ // simply omits the key, so a capture with no context wiped a perfectly
+ // good account out of openclaw.json.
+ //
+ // A row with an email and NO fingerprint is the legacy shape, from an
+ // install predating this field. Clearing it here deleted a real account
+ // before anything had replaced it, and if the re-resolve then failed
+ // because the user was offline the email was gone from disk for good. The
+ // Python core refuses the same trade: verify, and keep what you have until
+ // the verification succeeds. resolveEmail below overwrites both fields
+ // when it does, so there is nothing to clear first.
+ if (apiKey && auth.keyFingerprint) clearResolvedAccount();
+ }
} catch {
// Fall through to the API key or anonymous identity.
}
@@ -66,8 +97,16 @@ function identifyAnonymous(id: string): void {
}
function resolveEmail(apiKey: string): void {
- if (emailResolutionAttempted) return;
- emailResolutionAttempted = true;
+ // Latched per key, not once per process. A single boolean meant a key changed
+ // mid-session was never looked up, so the fallback identity stuck until restart.
+ const fingerprint = keyFingerprint(apiKey);
+ if (resolutionAttemptedFor === fingerprint) return;
+ resolutionAttemptedFor = fingerprint;
+ const releaseLatch = () => {
+ // A failed lookup must not pin the fallback identity for the rest of the
+ // process. Released so the next capture tries again.
+ if (resolutionAttemptedFor === fingerprint) resolutionAttemptedFor = "";
+ };
fetch(`${getBaseUrl().replace(/\/+$/, "")}/v1/ping/`, {
method: "GET",
headers: { Authorization: `Token ${apiKey}`, "Content-Type": "application/json" },
@@ -76,7 +115,7 @@ function resolveEmail(apiKey: string): void {
.then((response) => response.json())
.then((data: any) => {
if (!data?.user_email) return;
- writePluginAuth({ userEmail: data.user_email });
+ writePluginAuth({ userEmail: data.user_email, keyFingerprint: fingerprint });
const oldId = createHash("sha256").update(apiKey).digest("hex");
const newId = createHash("sha256").update(data.user_email).digest("hex");
for (const event of telemetry.queueForTesting()) {
@@ -84,7 +123,8 @@ function resolveEmail(apiKey: string): void {
}
})
.catch(() => {
- // The API-key hash remains a stable fallback.
+ // The API-key hash remains a stable fallback, and the next capture retries.
+ releaseLatch();
});
}
@@ -96,13 +136,15 @@ export function captureEvent(
if (!enabled()) return;
try {
currentDistinctId = distinctId(context?.apiKey);
- let hasEmail = false;
+ let resolvedForThisKey = false;
try {
- hasEmail = Boolean(readPluginAuth().userEmail);
+ const auth = readPluginAuth();
+ resolvedForThisKey =
+ Boolean(auth.userEmail) && auth.keyFingerprint === keyFingerprint(context?.apiKey);
} catch {
// Resolve it below when possible.
}
- if (context?.apiKey && !hasEmail) resolveEmail(context.apiKey);
+ if (context?.apiKey && !resolvedForThisKey) resolveEmail(context.apiKey);
identifyAnonymous(currentDistinctId);
telemetry.capture(eventName, {
mode: context?.mode,
diff --git a/integrations/openclaw/tests/config-file.test.ts b/integrations/openclaw/tests/config-file.test.ts
index e059ddff3..ba63180cb 100644
--- a/integrations/openclaw/tests/config-file.test.ts
+++ b/integrations/openclaw/tests/config-file.test.ts
@@ -237,3 +237,43 @@ describe("getBaseUrl", () => {
expect(getBaseUrl()).toBe(DEFAULT_BASE_URL);
});
});
+
+// ---------------------------------------------------------------------------
+// keyFingerprint round trip
+// ---------------------------------------------------------------------------
+
+describe("keyFingerprint survives a write and read", () => {
+ it("readPluginAuth returns a persisted keyFingerprint", () => {
+ // It did not. readPluginAuth builds its result field by field, and this one
+ // was missing, so every fingerprint comparison ran against undefined, the
+ // resolved email was never used again, and telemetry silently fell back to
+ // the API key hash. The telemetry tests could not see it because they mock
+ // this module and their mock returned the field the real reader dropped.
+ setConfigFile({
+ plugins: {
+ entries: {
+ "openclaw-mem0": {
+ config: {
+ apiKey: "m0-test",
+ userEmail: "person@example.com",
+ keyFingerprint: "0123456789abcdef",
+ },
+ },
+ },
+ },
+ });
+
+ expect(readPluginAuth().keyFingerprint).toBe("0123456789abcdef");
+ });
+
+ it("writePluginAuth persists it where readPluginAuth looks", () => {
+ setConfigFile({ plugins: { entries: { "openclaw-mem0": { config: {} } } } });
+
+ writePluginAuth({ userEmail: "person@example.com", keyFingerprint: "abc123" });
+
+ const written = JSON.parse(mockWriteText.mock.calls.at(-1)![1] as string);
+ const cfg = written.plugins.entries["openclaw-mem0"].config;
+ expect(cfg.keyFingerprint).toBe("abc123");
+ expect(cfg.userEmail).toBe("person@example.com");
+ });
+});
diff --git a/integrations/openclaw/tests/config.test.ts b/integrations/openclaw/tests/config.test.ts
index 2c6dbac2e..334c064fb 100644
--- a/integrations/openclaw/tests/config.test.ts
+++ b/integrations/openclaw/tests/config.test.ts
@@ -485,3 +485,18 @@ describe("mem0ConfigSchema.parse() — apiKey edge cases", () => {
expect(cfg.needsSetup).toBe(false);
});
});
+
+describe("telemetry fingerprint round trip", () => {
+ it("a config carrying keyFingerprint is accepted by the real schema", () => {
+ // What writePluginAuth persists after a successful lookup. It was not in
+ // ALLOWED_KEYS, and assertAllowedKeys throws, so the first successful
+ // resolve wrote a config that broke every subsequent load of the plugin.
+ const persisted = {
+ apiKey: "m0-test",
+ userEmail: "person@example.com",
+ keyFingerprint: "0123456789abcdef",
+ };
+
+ expect(() => mem0ConfigSchema.parse(persisted)).not.toThrow();
+ });
+});
diff --git a/integrations/openclaw/tests/telemetry.test.ts b/integrations/openclaw/tests/telemetry.test.ts
index 9a7bee716..ad7a9bbe0 100644
--- a/integrations/openclaw/tests/telemetry.test.ts
+++ b/integrations/openclaw/tests/telemetry.test.ts
@@ -3,15 +3,30 @@ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
// Mock config-file before importing telemetry
vi.mock("../cli/config-file.ts", () => ({
readPluginAuth: vi.fn().mockReturnValue({}),
+ writePluginAuth: vi.fn(),
+ clearAnonymousTelemetryId: vi.fn(),
+ clearResolvedAccount: vi.fn(),
+ getBaseUrl: vi.fn().mockReturnValue("https://api.mem0.ai"),
}));
import { captureEvent } from "../telemetry.ts";
-import { readPluginAuth } from "../cli/config-file.ts";
+import { clearResolvedAccount, readPluginAuth } from "../cli/config-file.ts";
+
+/** sha256(key).slice(0, 16), the shape telemetry.ts stores. */
+async function fingerprintOf(apiKey: string): Promise {
+ const { createHash } = await import("node:crypto");
+ return createHash("sha256").update(apiKey).digest("hex").slice(0, 16);
+}
describe("telemetry", () => {
let fetchSpy: ReturnType;
beforeEach(() => {
+ // Call history has to be cleared per test, not just restored: the mocks are
+ // module-level vi.fn()s, so without this one test's calls are visible to the
+ // next and assertions on "was not called" pass or fail by ordering.
+ vi.clearAllMocks();
+ (readPluginAuth as ReturnType).mockReturnValue({});
// Reset telemetry enabled state
(globalThis as any).__mem0_telemetry_override = undefined;
fetchSpy = vi.fn().mockResolvedValue({ ok: true });
@@ -40,11 +55,31 @@ describe("telemetry", () => {
expect(() => captureEvent("test_event")).not.toThrow();
});
- it("uses userEmail as distinct ID when available", () => {
- (readPluginAuth as ReturnType).mockReturnValueOnce({
+ it("uses userEmail as distinct ID when it belongs to the current key", async () => {
+ // Previously asserted only not.toThrow(), which passed whatever the identity
+ // turned out to be, and under the fingerprint gate the no-context path does
+ // not use the email at all. Pin the real condition instead.
+ (readPluginAuth as ReturnType).mockReturnValue({
userEmail: "test@example.com",
+ keyFingerprint: await fingerprintOf("key-a"),
});
- expect(() => captureEvent("test_event")).not.toThrow();
+
+ captureEvent("test_event", {}, { apiKey: "key-a" });
+
+ expect(clearResolvedAccount).not.toHaveBeenCalled();
+ });
+
+ it("a capture with no apiKey leaves a resolved account alone", async () => {
+ // `undefined === ""` made every keyless capture look like a key change, so
+ // one context-free call wiped a good account out of openclaw.json.
+ (readPluginAuth as ReturnType).mockReturnValue({
+ userEmail: "test@example.com",
+ keyFingerprint: await fingerprintOf("key-a"),
+ });
+
+ captureEvent("test_event");
+
+ expect(clearResolvedAccount).not.toHaveBeenCalled();
});
it("falls back to a generated anonymous id when no apiKey", () => {
@@ -52,6 +87,43 @@ describe("telemetry", () => {
expect(() => captureEvent("test_event", {}, {})).not.toThrow();
});
+ it("keeps using a cached email only while it belongs to the current key", async () => {
+ (readPluginAuth as ReturnType).mockReturnValue({
+ userEmail: "person@example.com",
+ keyFingerprint: await fingerprintOf("key-a"),
+ });
+
+ captureEvent("test_event", {}, { apiKey: "key-a" });
+
+ expect(clearResolvedAccount).not.toHaveBeenCalled();
+ });
+
+ it("forgets the account when the API key changes", async () => {
+ // The defect: the cached email was used forever, so events after an account
+ // switch kept reporting under the previous account.
+ (readPluginAuth as ReturnType).mockReturnValue({
+ userEmail: "person@example.com",
+ keyFingerprint: await fingerprintOf("key-a"),
+ });
+
+ captureEvent("test_event", {}, { apiKey: "key-b" });
+
+ expect(clearResolvedAccount).toHaveBeenCalled();
+ });
+
+ it("re-resolves for a key it has not looked up before", async () => {
+ (readPluginAuth as ReturnType).mockReturnValue({
+ userEmail: "person@example.com",
+ keyFingerprint: await fingerprintOf("key-a"),
+ });
+
+ captureEvent("test_event", {}, { apiKey: "key-c" });
+
+ // The resolution latch is per key, not once per process, so a key changed
+ // mid-session is actually looked up instead of sticking to the fallback.
+ expect(fetchSpy).toHaveBeenCalled();
+ });
+
it("handles readPluginAuth errors gracefully", () => {
(readPluginAuth as ReturnType).mockImplementationOnce(() => {
throw new Error("config read failed");
diff --git a/integrations/opencode-plugin/package.json b/integrations/opencode-plugin/package.json
index 79f68c4a8..acdbaf469 100644
--- a/integrations/opencode-plugin/package.json
+++ b/integrations/opencode-plugin/package.json
@@ -38,6 +38,7 @@
"build": "bun build opencode-mem0.ts --outdir dist --target bun --format esm --entry-naming index.[ext]",
"dev": "bun build opencode-mem0.ts --outdir dist --target bun --format esm --entry-naming index.[ext] --watch",
"type-check": "tsc --noEmit",
+ "test": "bun test",
"prepack": "bun run build",
"postpack": ""
},
diff --git a/integrations/opencode-plugin/telemetry.test.ts b/integrations/opencode-plugin/telemetry.test.ts
index 393150977..79dc3ffdb 100644
--- a/integrations/opencode-plugin/telemetry.test.ts
+++ b/integrations/opencode-plugin/telemetry.test.ts
@@ -1,3 +1,5 @@
+import { createHash } from "node:crypto";
+
import { afterEach, describe, expect, test } from "bun:test";
import { buildEvent, captureEvent, isTelemetryEnabled } from "./telemetry";
@@ -13,7 +15,10 @@ describe("opencode telemetry", () => {
expect(payload).not.toBeNull();
const props = payload!.properties as Record;
expect(payload!.event).toBe("plugin.session_start");
- expect(props.source).toBe("plugin");
+ // Was "plugin", which named no particular plugin and matched no vocabulary.
+ // Now shaped like every other surface. Any saved PostHog insight filtering
+ // source = "plugin" needs repointing; historical data is untouched.
+ expect(props.source).toBe("OPENCODE_PLUGIN");
expect(props.platform).toBe("opencode");
expect(props.memory_count).toBe(5);
expect(props.$process_person_profile).toBe(false);
@@ -30,7 +35,7 @@ describe("opencode telemetry", () => {
const props = buildEvent("x", { platform: "HACK", source: "HACK" }, KEY)!
.properties as Record;
expect(props.platform).toBe("opencode");
- expect(props.source).toBe("plugin");
+ expect(props.source).toBe("OPENCODE_PLUGIN");
});
test("returns null without an API key (no anonymous events)", () => {
@@ -56,9 +61,12 @@ describe("opencode telemetry", () => {
expect(typeof props.os_version).toBe("string");
});
- test("project_hash is sha256(projectId) when a project id is supplied", async () => {
+ test("project_hash is a salted digest of the project id", async () => {
+ // Previously asserted the bare sha256(projectId), which is the defect: that
+ // digest is reversible by anyone who can guess a project id. Salted with the
+ // API key, which is already in play here and is high entropy.
const { createHash } = await import("node:crypto");
- const expected = createHash("sha256").update("acme-repo").digest("hex");
+ const expected = createHash("sha256").update(`${KEY}:acme-repo`).digest("hex");
const props = buildEvent("session_start", {}, KEY, "acme-repo")!
.properties as Record;
expect(props.project_hash).toBe(expected);
@@ -76,3 +84,38 @@ describe("opencode telemetry", () => {
}
});
});
+
+describe("project_hash salting", () => {
+ const PROJECT = "my-project";
+
+ test("is not a bare digest of the project id", () => {
+ // The defect: an unsalted SHA-256 over a guessable identifier is reversible
+ // by anyone who can enumerate project ids.
+ const unsalted = createHash("sha256").update(PROJECT).digest("hex");
+ const payload = buildEvent("session_start", {}, KEY, PROJECT) as Record;
+
+ expect(payload.properties.project_hash).toBeDefined();
+ expect(payload.properties.project_hash).not.toBe(unsalted);
+ });
+
+ test("differs per account for the same project", () => {
+ const a = buildEvent("session_start", {}, "m0-account-a", PROJECT) as Record;
+ const b = buildEvent("session_start", {}, "m0-account-b", PROJECT) as Record;
+
+ expect(a.properties.project_hash).not.toBe(b.properties.project_hash);
+ });
+
+ test("is stable for one account, so joins still work", () => {
+ const first = buildEvent("session_start", {}, KEY, PROJECT) as Record;
+ const second = buildEvent("session_end", {}, KEY, PROJECT) as Record;
+
+ expect(first.properties.project_hash).toBe(second.properties.project_hash);
+ });
+
+ test("is omitted rather than unsalted when there is no key", () => {
+ const payload = buildEvent("session_start", {}, undefined, PROJECT);
+
+ // No key means no event at all, so there is no unsalted hash to leak.
+ expect(payload).toBeNull();
+ });
+});
diff --git a/integrations/opencode-plugin/telemetry.ts b/integrations/opencode-plugin/telemetry.ts
index 8d0861d97..e2316dd88 100644
--- a/integrations/opencode-plugin/telemetry.ts
+++ b/integrations/opencode-plugin/telemetry.ts
@@ -25,7 +25,9 @@ const PLUGIN_VERSION = (() => {
let currentDistinctId = "";
const telemetry = createTelemetry({
host: "opencode",
- source: "plugin",
+ // Shaped like the platform's EventSource values, as every other surface is.
+ // "plugin" said nothing about which plugin and matched no vocabulary.
+ source: "OPENCODE_PLUGIN",
version: PLUGIN_VERSION,
distinctId: () => currentDistinctId,
eventName: (event) => `plugin.${event}`,
@@ -40,8 +42,23 @@ function distinctId(apiKey: string): string {
return createHash("sha256").update(apiKey).digest("hex").slice(0, 32);
}
-function projectHash(projectId?: string): Record {
- return projectId ? { project_hash: createHash("sha256").update(projectId).digest("hex") } : {};
+/**
+ * Salted so the hash is not enumerable.
+ *
+ * An unsalted SHA-256 of a project id is reversible by anyone who can guess the
+ * id, which for a project identifier is a small space. The API key is the salt:
+ * it is already in play here (distinctId is a digest of it), it is high entropy,
+ * and using it needs no per-install file and so no write race to get wrong. The
+ * hash is therefore per account rather than per machine, which also keeps joins
+ * working for one user across machines. It resets when the key rotates, which is
+ * consistent, because distinctId resets with it.
+ *
+ * Both are omitted without a key. An event cannot be built without a distinctId
+ * anyway, so this costs nothing.
+ */
+function projectHash(projectId?: string, apiKey?: string): Record {
+ if (!projectId || !apiKey) return {};
+ return { project_hash: createHash("sha256").update(`${apiKey}:${projectId}`).digest("hex") };
}
export function buildEvent(
@@ -51,7 +68,7 @@ export function buildEvent(
projectId?: string,
): Record | null {
currentDistinctId = apiKey ? distinctId(apiKey) : "";
- const event = telemetry.build(eventType, { ...properties, ...projectHash(projectId) });
+ const event = telemetry.build(eventType, { ...properties, ...projectHash(projectId, apiKey) });
return event ? { api_key: POSTHOG_API_KEY, ...event } : null;
}
@@ -62,5 +79,5 @@ export function captureEvent(
projectId?: string,
): void {
currentDistinctId = apiKey ? distinctId(apiKey) : "";
- telemetry.capture(eventType, { ...properties, ...projectHash(projectId) });
+ telemetry.capture(eventType, { ...properties, ...projectHash(projectId, apiKey) });
}
From 19f713408273fb1d657daa38d7b82ccf496d36d5 Mon Sep 17 00:00:00 2001
From: Saket Aryan
Date: Fri, 18 Sep 2026 16:28:55 +0530
Subject: [PATCH 13/54] chore(release): bump every package the telemetry
attribution work changed (#7373)
Co-authored-by: kartik-mem0
---
.claude-plugin/marketplace.json | 2 +-
.cursor-plugin/marketplace.json | 2 +-
.kimi-plugin/marketplace.json | 2 +-
cli/node/package.json | 2 +-
cli/python/pyproject.toml | 2 +-
cli/python/src/mem0_cli/__init__.py | 2 +-
docs/changelog/sdk.mdx | 131 +++++++++++++-----
.../agent-plugin-core/python/memory_core.py | 2 +-
.../antigravity-plugin/core/memory_core.py | 2 +-
.../antigravity-plugin/plugin-build.json | 2 +-
.../.claude-plugin/plugin.json | 2 +-
.../claude-code-plugin/core/memory_core.py | 2 +-
.../claude-code-plugin/plugin-build.json | 2 +-
.../tests/test_memory_core.py | 8 +-
.../codex-plugin/.codex-plugin/plugin.json | 2 +-
integrations/codex-plugin/core/memory_core.py | 2 +-
integrations/codex-plugin/plugin-build.json | 2 +-
.../cursor-plugin/.cursor-plugin/plugin.json | 2 +-
.../cursor-plugin/core/memory_core.py | 2 +-
integrations/cursor-plugin/plugin-build.json | 2 +-
integrations/deepseek-plugin/package.json | 2 +-
integrations/kimi-plugin/core/memory_core.py | 2 +-
integrations/kimi-plugin/kimi.plugin.json | 2 +-
integrations/kimi-plugin/plugin-build.json | 2 +-
.../mem0-agent-plugin/core/memory_core.py | 2 +-
integrations/mem0-agent-plugin/plugin.json | 2 +-
integrations/openclaw/openclaw.plugin.json | 2 +-
integrations/openclaw/package.json | 2 +-
integrations/opencode-plugin/package.json | 2 +-
integrations/pi-agent-plugin/package.json | 2 +-
integrations/vercel-ai-sdk/package.json | 2 +-
marketplace.json | 2 +-
mem0-ts/package.json | 2 +-
pyproject.toml | 2 +-
34 files changed, 135 insertions(+), 68 deletions(-)
diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json
index d46a19e49..ccaa4dcea 100644
--- a/.claude-plugin/marketplace.json
+++ b/.claude-plugin/marketplace.json
@@ -12,7 +12,7 @@
"name": "mem0",
"source": "./integrations/claude-code-plugin",
"description": "Cross-session memory and token savings for coding agents.",
- "version": "0.3.1"
+ "version": "0.3.2"
}
]
}
diff --git a/.cursor-plugin/marketplace.json b/.cursor-plugin/marketplace.json
index 409b7d8fc..84f31855b 100644
--- a/.cursor-plugin/marketplace.json
+++ b/.cursor-plugin/marketplace.json
@@ -12,7 +12,7 @@
"name": "mem0",
"source": "./integrations/cursor-plugin",
"description": "Cross-session memory and token savings for coding agents.",
- "version": "0.3.1"
+ "version": "0.3.2"
}
]
}
diff --git a/.kimi-plugin/marketplace.json b/.kimi-plugin/marketplace.json
index 8ff2134b4..0b8cbcac0 100644
--- a/.kimi-plugin/marketplace.json
+++ b/.kimi-plugin/marketplace.json
@@ -5,7 +5,7 @@
{
"id": "mem0",
"displayName": "Mem0",
- "version": "0.3.1",
+ "version": "0.3.2",
"description": "Cross-session memory and token savings for coding agents.",
"homepage": "https://mem0.ai",
"keywords": ["memory", "personalization", "mcp", "semantic-search"],
diff --git a/cli/node/package.json b/cli/node/package.json
index d078066e2..b2f57b09f 100644
--- a/cli/node/package.json
+++ b/cli/node/package.json
@@ -1,6 +1,6 @@
{
"name": "@mem0/cli",
- "version": "0.2.13",
+ "version": "0.2.14",
"description": "The official CLI for mem0 — the memory layer for AI agents",
"type": "module",
"bin": {
diff --git a/cli/python/pyproject.toml b/cli/python/pyproject.toml
index be7e72709..961d2b78d 100644
--- a/cli/python/pyproject.toml
+++ b/cli/python/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
[project]
name = "mem0-cli"
-version = "0.2.12"
+version = "0.2.13"
description = "The official CLI for mem0 — the memory layer for AI agents"
readme = "README.md"
license = "Apache-2.0"
diff --git a/cli/python/src/mem0_cli/__init__.py b/cli/python/src/mem0_cli/__init__.py
index 6d686291e..0aeb58270 100644
--- a/cli/python/src/mem0_cli/__init__.py
+++ b/cli/python/src/mem0_cli/__init__.py
@@ -1,3 +1,3 @@
"""mem0 CLI — the command-line interface for the mem0 memory layer."""
-__version__ = "0.2.12"
+__version__ = "0.2.13"
diff --git a/docs/changelog/sdk.mdx b/docs/changelog/sdk.mdx
index 71fb7e1d8..50922493e 100644
--- a/docs/changelog/sdk.mdx
+++ b/docs/changelog/sdk.mdx
@@ -7,6 +7,14 @@ mode: "wide"
+
+
+**Improvements:**
+- **Client:** Requests now carry three surface-identity headers so the platform can tell which product made a call. `X-Mem0-Source` names the surface and `X-Application` the host app it runs inside, both set-once so a wrapper that already declared its identity keeps it. `X-Mem0-Client` is append-only and carries `name/version` per layer, outermost first, so a plugin calling this SDK reports the whole chain rather than only the last speaker. `MEM0_SOURCE`, `MEM0_APPLICATION` and `MEM0_CLIENT_STACK` set them from the environment for wrappers that cannot pass options ([#7326](https://github.com/mem0ai/mem0/pull/7326))
+- **Client:** The client stack is bounded by dropping whole entries rather than slicing characters, and this SDK's own entry is the reserved one. Truncating the joined string could sever an identifier mid-name and the platform parsed the fragment as a real client ([#7326](https://github.com/mem0ai/mem0/pull/7326))
+
+
+
**Improvements:**
@@ -1227,6 +1235,14 @@ See the [OSS v2 to v3 migration guide](https://docs.mem0.ai/migration/oss-v2-to-
+
+
+**Improvements:**
+- **Client:** Requests now carry `X-Mem0-Source`, `X-Application` and `X-Mem0-Client`, matching the Python SDK. The first two are set-once so an outer wrapper keeps its identity; the third is append-only and reports the whole layer chain. Read from `MEM0_SOURCE`, `MEM0_APPLICATION` and `MEM0_CLIENT_STACK` when set ([#7326](https://github.com/mem0ai/mem0/pull/7326))
+- **Client:** The SDK version in `X-Mem0-Client` is injected at build time rather than hardcoded, so it cannot go stale at the next release ([#7326](https://github.com/mem0ai/mem0/pull/7326))
+
+
+
**Improvements:**
@@ -1864,6 +1880,13 @@ See the [OSS v2 to v3 migration guide](https://docs.mem0.ai/migration/oss-v2-to-
+
+
+**Improvements:**
+- **Client:** Requests now carry the three surface-identity headers (`X-Mem0-Source`, `X-Application`, `X-Mem0-Client`) introduced in the Python and TypeScript SDKs, so the platform can attribute calls made through the CLI to the correct surface and version ([#7326](https://github.com/mem0ai/mem0/pull/7326))
+
+
+
**New Features:**
@@ -2076,7 +2099,7 @@ A full-featured command-line interface for Mem0, available in both Python and No
- New Git repository writes use a hash of the remote identity in `agent_id`. Search and explicit shared-memory deletion include both current and legacy repository IDs within the repository's `app_id`. Existing memories are not rewritten. Legacy IDs retain their original ambiguity for matching owner/repository names on different Git hosts.
**Packaging:**
-- Claude Code, Cursor, Codex, Kimi, Antigravity, and the portable Python bundle are versioned at `0.3.1`. OpenCode, Pi Agent, and DeepSeek Harness are `0.3.0`; OpenClaw is `1.1.0`. Each host's changes and upgrade considerations are listed in its tab.
+- Claude Code, Cursor, Codex, Kimi, Antigravity, and the portable Python bundle are versioned at `0.3.1`. OpenCode and DeepSeek Harness are `0.3.0`; Pi Agent is `0.3.0`; OpenClaw is `1.1.0`. Each host's changes and upgrade considerations are listed in its tab.
- Python and TypeScript CI run their respective runtime suites. Package checks build the installable artifacts, check generated-file consistency, and reject TypeScript output that still imports monorepo source.
[#7203](https://github.com/mem0ai/mem0/pull/7203)
@@ -2371,9 +2394,14 @@ Initial release of the Mem0 plugin for Claude Code and Cursor, followed by Codex
-
+
-Sidekick is now available only in Claude Code, with Sonnet, worktree isolation, and parent memories.
+**Improvements:**
+- **Telemetry:** `PLUGIN_VERSION` bumped to `0.3.2`. The `mem0-plugin/` wire header and `plugin_version` telemetry field now reflect the fixes from #7322 through #7358 ([#7373](https://github.com/mem0ai/mem0/pull/7373))
+- **Telemetry:** Events are no longer delivered twice, no longer lose parked events on flush, and now attribute each event to the plugin that produced it ([#7323](https://github.com/mem0ai/mem0/pull/7323), [#7324](https://github.com/mem0ai/mem0/pull/7324), [#7358](https://github.com/mem0ai/mem0/pull/7358))
+
+**Changes:**
+- **Sidekick:** Sidekick is now available only in Claude Code, with Sonnet, worktree isolation, and parent memories.
@@ -2396,9 +2424,14 @@ Sidekick is now available only in Claude Code, with Sonnet, worktree isolation,
-
+
-Removes Sidekick and its start/stop hooks. Memory capture, search, and six skills remain available.
+**Improvements:**
+- **Telemetry:** `PLUGIN_VERSION` bumped to `0.3.2`. The `mem0-plugin/` wire header and `plugin_version` telemetry field now reflect the fixes from #7322 through #7358 ([#7373](https://github.com/mem0ai/mem0/pull/7373))
+- **Telemetry:** Events are no longer delivered twice, no longer lose parked events on flush, and now attribute each event to the plugin that produced it ([#7323](https://github.com/mem0ai/mem0/pull/7323), [#7324](https://github.com/mem0ai/mem0/pull/7324), [#7358](https://github.com/mem0ai/mem0/pull/7358))
+
+**Changes:**
+- **Sidekick:** Removes Sidekick and its start/stop hooks. Memory capture, search, and six skills remain available.
@@ -2421,9 +2454,14 @@ Removes Sidekick and its start/stop hooks. Memory capture, search, and six skill
-
+
-Renames shared tracking to use subagent terminology. Native subagent memory support remains available.
+**Improvements:**
+- **Telemetry:** `PLUGIN_VERSION` bumped to `0.3.2`. The `mem0-plugin/` wire header and `plugin_version` telemetry field now reflect the fixes from #7322 through #7358 ([#7373](https://github.com/mem0ai/mem0/pull/7373))
+- **Telemetry:** Events are no longer delivered twice, no longer lose parked events on flush, and now attribute each event to the plugin that produced it ([#7323](https://github.com/mem0ai/mem0/pull/7323), [#7324](https://github.com/mem0ai/mem0/pull/7324), [#7358](https://github.com/mem0ai/mem0/pull/7358))
+
+**Changes:**
+- **Sidekick:** Renames shared tracking to use subagent terminology. Native subagent memory support remains available.
@@ -2443,32 +2481,16 @@ Renames shared tracking to use subagent terminology. Native subagent memory supp
-
-
-
-
-Sidekick is available only in Claude Code, not in the portable package.
-
-
-
-
-
-**Added:**
-- One portable package at `integrations/mem0-agent-plugin/`, using the Agent Plugins 1.0.0 root `plugin.json`, `mcp.json`, and fixed `skills/` locations.
-- Ships a local, read-only `search_memories` server and the six shared memory skills. Uses `PLUGIN_ROOT` for bundled files and `PLUGIN_DATA` for persistent plugin state; all package files remain inside the installable directory.
-
-**Packaging:**
-- Generated from the shared Python runtime and skill templates. Builds validate the manifest, MCP configuration, skills, and generated-file consistency.
-- Host lifecycle hooks and native Sidekick declarations remain in the native plugin packages; the portable package does not provide automatic lifecycle capture or host-specific subagent isolation. Its bundled remember skill cannot persist a new memory on its own because the portable package has no capture hooks or write tool.
-
-[#7203](https://github.com/mem0ai/mem0/pull/7203)
-
-
-
-
-
+
+
+**Changes:**
+- **Telemetry:** The PostHog `source` tag changed from the literal `"plugin"` to `OPENCODE_PLUGIN`, and `project_hash` is now salted. Saved PostHog insights filtering on `source = "plugin"` will stop matching new events; historical data is unaffected ([#7322](https://github.com/mem0ai/mem0/pull/7322))
+- **Config:** A new `keyFingerprint` key appears in the install-count deduplication logic; installs are now counted once per key rather than on every activation ([#7325](https://github.com/mem0ai/mem0/pull/7325))
+
+
+
**Changed:**
@@ -2567,9 +2589,14 @@ Sidekick is available only in Claude Code, not in the portable package.
-
+
-Removes Sidekick. Memory capture, search, and six skills remain available.
+**Improvements:**
+- **Telemetry:** `PLUGIN_VERSION` bumped to `0.3.2`. The `mem0-plugin/` wire header and `plugin_version` telemetry field now reflect the fixes from #7322 through #7358 ([#7373](https://github.com/mem0ai/mem0/pull/7373))
+- **Telemetry:** Events are no longer delivered twice, no longer lose parked events on flush, and now attribute each event to the plugin that produced it ([#7323](https://github.com/mem0ai/mem0/pull/7323), [#7324](https://github.com/mem0ai/mem0/pull/7324), [#7358](https://github.com/mem0ai/mem0/pull/7358))
+
+**Changes:**
+- **Sidekick:** Removes Sidekick. Memory capture, search, and six skills remain available.
@@ -2665,9 +2692,14 @@ Existing memories written by the previous versions are not rewritten. If your me
-
+
-Removes Sidekick and its start/stop hooks. Memory capture, recall, and six skills remain available.
+**Improvements:**
+- **Telemetry:** `PLUGIN_VERSION` bumped to `0.3.2`. The `mem0-plugin/` wire header and `plugin_version` telemetry field now reflect the fixes from #7322 through #7358 ([#7373](https://github.com/mem0ai/mem0/pull/7373))
+- **Telemetry:** Events are no longer delivered twice, no longer lose parked events on flush, and now attribute each event to the plugin that produced it ([#7323](https://github.com/mem0ai/mem0/pull/7323), [#7324](https://github.com/mem0ai/mem0/pull/7324), [#7358](https://github.com/mem0ai/mem0/pull/7358))
+
+**Changes:**
+- **Sidekick:** Removes Sidekick and its start/stop hooks. Memory capture, recall, and six skills remain available.
@@ -2705,6 +2737,14 @@ Removes Sidekick and its start/stop hooks. Memory capture, recall, and six skill
+
+
+**Changes:**
+- **Config:** Added `keyFingerprint` to the config schema for install-count deduplication; installs are now counted once per key rather than on every activation ([#7325](https://github.com/mem0ai/mem0/pull/7325))
+- **Telemetry:** Events are no longer delivered twice, and the `plugin_version` field now reflects the plugin that produced the event ([#7323](https://github.com/mem0ai/mem0/pull/7323), [#7324](https://github.com/mem0ai/mem0/pull/7324), [#7358](https://github.com/mem0ai/mem0/pull/7358))
+
+
+
**Changed:**
@@ -2993,6 +3033,13 @@ Removes Sidekick and its start/stop hooks. Memory capture, recall, and six skill
+
+
+**Improvements:**
+- **Telemetry:** Events are no longer delivered twice, no longer lose parked events, and now attribute each event to the plugin that produced it. The `plugin_version` wire field reflects the fixed release ([#7323](https://github.com/mem0ai/mem0/pull/7323), [#7324](https://github.com/mem0ai/mem0/pull/7324), [#7358](https://github.com/mem0ai/mem0/pull/7358))
+
+
+
**Changed:**
@@ -3106,6 +3153,13 @@ Removes Sidekick and its start/stop hooks. Memory capture, recall, and six skill
+
+
+**Improvements:**
+- **Telemetry:** Rebuild with the fixed shared telemetry core from `agent-plugin-core`. Events are no longer delivered twice, no longer lose parked events on flush, and now attribute each event to the plugin that produced it ([#7323](https://github.com/mem0ai/mem0/pull/7323), [#7324](https://github.com/mem0ai/mem0/pull/7324), [#7358](https://github.com/mem0ai/mem0/pull/7358))
+
+
+
**Added:**
@@ -3150,6 +3204,13 @@ Removes Sidekick and its start/stop hooks. Memory capture, recall, and six skill
+
+
+**Improvements:**
+- **Client:** Inherits the three surface-identity headers (`X-Mem0-Source`, `X-Application`, `X-Mem0-Client`) from the TypeScript SDK bump, so platform calls made through the Vercel AI SDK provider are now correctly attributed ([#7326](https://github.com/mem0ai/mem0/pull/7326))
+
+
+
**Security:**
diff --git a/integrations/agent-plugin-core/python/memory_core.py b/integrations/agent-plugin-core/python/memory_core.py
index d350e76d2..ea2670dac 100644
--- a/integrations/agent-plugin-core/python/memory_core.py
+++ b/integrations/agent-plugin-core/python/memory_core.py
@@ -29,7 +29,7 @@ from typing import Any, Iterable
import telemetry
DEFAULT_API_URL = "https://api.mem0.ai"
-PLUGIN_VERSION = "0.3.1"
+PLUGIN_VERSION = "0.3.2"
_harness_name: str = "generic"
_harness_env_prefix: str = "MEM0_PLUGIN"
diff --git a/integrations/antigravity-plugin/core/memory_core.py b/integrations/antigravity-plugin/core/memory_core.py
index d350e76d2..ea2670dac 100644
--- a/integrations/antigravity-plugin/core/memory_core.py
+++ b/integrations/antigravity-plugin/core/memory_core.py
@@ -29,7 +29,7 @@ from typing import Any, Iterable
import telemetry
DEFAULT_API_URL = "https://api.mem0.ai"
-PLUGIN_VERSION = "0.3.1"
+PLUGIN_VERSION = "0.3.2"
_harness_name: str = "generic"
_harness_env_prefix: str = "MEM0_PLUGIN"
diff --git a/integrations/antigravity-plugin/plugin-build.json b/integrations/antigravity-plugin/plugin-build.json
index ac65c4bea..43b90d8cb 100644
--- a/integrations/antigravity-plugin/plugin-build.json
+++ b/integrations/antigravity-plugin/plugin-build.json
@@ -1,6 +1,6 @@
{
"id": "mem0",
- "version": "0.3.1",
+ "version": "0.3.2",
"homepage": "https://docs.mem0.ai/integrations/antigravity",
"native": {
"pluginRoot": "${ANTIGRAVITY_PLUGIN_ROOT}",
diff --git a/integrations/claude-code-plugin/.claude-plugin/plugin.json b/integrations/claude-code-plugin/.claude-plugin/plugin.json
index 6f214cc14..0dd8298e9 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.1",
+ "version": "0.3.2",
"description": "Cross-session memory and token savings for coding agents.",
"author": {
"name": "Mem0"
diff --git a/integrations/claude-code-plugin/core/memory_core.py b/integrations/claude-code-plugin/core/memory_core.py
index d350e76d2..ea2670dac 100644
--- a/integrations/claude-code-plugin/core/memory_core.py
+++ b/integrations/claude-code-plugin/core/memory_core.py
@@ -29,7 +29,7 @@ from typing import Any, Iterable
import telemetry
DEFAULT_API_URL = "https://api.mem0.ai"
-PLUGIN_VERSION = "0.3.1"
+PLUGIN_VERSION = "0.3.2"
_harness_name: str = "generic"
_harness_env_prefix: str = "MEM0_PLUGIN"
diff --git a/integrations/claude-code-plugin/plugin-build.json b/integrations/claude-code-plugin/plugin-build.json
index 68d306fd6..4b98c2919 100644
--- a/integrations/claude-code-plugin/plugin-build.json
+++ b/integrations/claude-code-plugin/plugin-build.json
@@ -1,6 +1,6 @@
{
"id": "mem0",
- "version": "0.3.1",
+ "version": "0.3.2",
"homepage": "https://docs.mem0.ai/integrations/claude-code",
"native": {
"pluginRoot": "${CLAUDE_PLUGIN_ROOT}",
diff --git a/integrations/claude-code-plugin/tests/test_memory_core.py b/integrations/claude-code-plugin/tests/test_memory_core.py
index 8c7017913..9aea939cf 100644
--- a/integrations/claude-code-plugin/tests/test_memory_core.py
+++ b/integrations/claude-code-plugin/tests/test_memory_core.py
@@ -1,6 +1,7 @@
from __future__ import annotations
import json
+import re
import os
import sqlite3
import subprocess
@@ -3460,7 +3461,12 @@ 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.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")
diff --git a/integrations/codex-plugin/.codex-plugin/plugin.json b/integrations/codex-plugin/.codex-plugin/plugin.json
index 916b72e66..0a80bf9e3 100644
--- a/integrations/codex-plugin/.codex-plugin/plugin.json
+++ b/integrations/codex-plugin/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "mem0",
- "version": "0.3.1",
+ "version": "0.3.2",
"description": "Cross-session memory and token savings for coding agents.",
"author": { "name": "Mem0", "email": "support@mem0.ai" },
"homepage": "https://docs.mem0.ai/integrations/codex",
diff --git a/integrations/codex-plugin/core/memory_core.py b/integrations/codex-plugin/core/memory_core.py
index d350e76d2..ea2670dac 100644
--- a/integrations/codex-plugin/core/memory_core.py
+++ b/integrations/codex-plugin/core/memory_core.py
@@ -29,7 +29,7 @@ from typing import Any, Iterable
import telemetry
DEFAULT_API_URL = "https://api.mem0.ai"
-PLUGIN_VERSION = "0.3.1"
+PLUGIN_VERSION = "0.3.2"
_harness_name: str = "generic"
_harness_env_prefix: str = "MEM0_PLUGIN"
diff --git a/integrations/codex-plugin/plugin-build.json b/integrations/codex-plugin/plugin-build.json
index 8d4c51c07..7f5fc94f6 100644
--- a/integrations/codex-plugin/plugin-build.json
+++ b/integrations/codex-plugin/plugin-build.json
@@ -1,6 +1,6 @@
{
"id": "mem0",
- "version": "0.3.1",
+ "version": "0.3.2",
"homepage": "https://docs.mem0.ai/integrations/codex",
"native": {
"pluginRoot": "${PLUGIN_ROOT}",
diff --git a/integrations/cursor-plugin/.cursor-plugin/plugin.json b/integrations/cursor-plugin/.cursor-plugin/plugin.json
index e33de76a2..a30f9ad9a 100644
--- a/integrations/cursor-plugin/.cursor-plugin/plugin.json
+++ b/integrations/cursor-plugin/.cursor-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "mem0",
- "version": "0.3.1",
+ "version": "0.3.2",
"description": "Cross-session memory and token savings for coding agents.",
"author": { "name": "Mem0", "email": "support@mem0.ai" },
"homepage": "https://docs.mem0.ai/integrations/cursor",
diff --git a/integrations/cursor-plugin/core/memory_core.py b/integrations/cursor-plugin/core/memory_core.py
index d350e76d2..ea2670dac 100644
--- a/integrations/cursor-plugin/core/memory_core.py
+++ b/integrations/cursor-plugin/core/memory_core.py
@@ -29,7 +29,7 @@ from typing import Any, Iterable
import telemetry
DEFAULT_API_URL = "https://api.mem0.ai"
-PLUGIN_VERSION = "0.3.1"
+PLUGIN_VERSION = "0.3.2"
_harness_name: str = "generic"
_harness_env_prefix: str = "MEM0_PLUGIN"
diff --git a/integrations/cursor-plugin/plugin-build.json b/integrations/cursor-plugin/plugin-build.json
index 279b3178c..30024586e 100644
--- a/integrations/cursor-plugin/plugin-build.json
+++ b/integrations/cursor-plugin/plugin-build.json
@@ -1,6 +1,6 @@
{
"id": "mem0",
- "version": "0.3.1",
+ "version": "0.3.2",
"homepage": "https://docs.mem0.ai/integrations/cursor",
"native": {
"pluginRoot": "${CURSOR_PLUGIN_ROOT}",
diff --git a/integrations/deepseek-plugin/package.json b/integrations/deepseek-plugin/package.json
index ea00bb9c5..2df84283c 100644
--- a/integrations/deepseek-plugin/package.json
+++ b/integrations/deepseek-plugin/package.json
@@ -1,6 +1,6 @@
{
"name": "@mem0/deepseek-plugin",
- "version": "0.3.0",
+ "version": "0.3.1",
"description": "Mem0 long-term memory as a native DeepSeek Harness (Cordis) plugin.",
"type": "module",
"license": "Apache-2.0",
diff --git a/integrations/kimi-plugin/core/memory_core.py b/integrations/kimi-plugin/core/memory_core.py
index d350e76d2..ea2670dac 100644
--- a/integrations/kimi-plugin/core/memory_core.py
+++ b/integrations/kimi-plugin/core/memory_core.py
@@ -29,7 +29,7 @@ from typing import Any, Iterable
import telemetry
DEFAULT_API_URL = "https://api.mem0.ai"
-PLUGIN_VERSION = "0.3.1"
+PLUGIN_VERSION = "0.3.2"
_harness_name: str = "generic"
_harness_env_prefix: str = "MEM0_PLUGIN"
diff --git a/integrations/kimi-plugin/kimi.plugin.json b/integrations/kimi-plugin/kimi.plugin.json
index 0d63501fe..e58bec328 100644
--- a/integrations/kimi-plugin/kimi.plugin.json
+++ b/integrations/kimi-plugin/kimi.plugin.json
@@ -1,6 +1,6 @@
{
"name": "mem0",
- "version": "0.3.1",
+ "version": "0.3.2",
"description": "Cross-session memory and token savings for coding agents.",
"keywords": ["memory", "coding-agents", "continual-learning", "token-efficiency"],
"author": { "name": "Mem0", "email": "support@mem0.ai" },
diff --git a/integrations/kimi-plugin/plugin-build.json b/integrations/kimi-plugin/plugin-build.json
index 3926a57df..e73643eab 100644
--- a/integrations/kimi-plugin/plugin-build.json
+++ b/integrations/kimi-plugin/plugin-build.json
@@ -1,6 +1,6 @@
{
"id": "mem0",
- "version": "0.3.1",
+ "version": "0.3.2",
"homepage": "https://docs.mem0.ai/integrations/kimi",
"native": {
"pluginRoot": "${KIMI_PLUGIN_ROOT}",
diff --git a/integrations/mem0-agent-plugin/core/memory_core.py b/integrations/mem0-agent-plugin/core/memory_core.py
index d350e76d2..ea2670dac 100644
--- a/integrations/mem0-agent-plugin/core/memory_core.py
+++ b/integrations/mem0-agent-plugin/core/memory_core.py
@@ -29,7 +29,7 @@ from typing import Any, Iterable
import telemetry
DEFAULT_API_URL = "https://api.mem0.ai"
-PLUGIN_VERSION = "0.3.1"
+PLUGIN_VERSION = "0.3.2"
_harness_name: str = "generic"
_harness_env_prefix: str = "MEM0_PLUGIN"
diff --git a/integrations/mem0-agent-plugin/plugin.json b/integrations/mem0-agent-plugin/plugin.json
index 2cbaa99de..7a2baba80 100644
--- a/integrations/mem0-agent-plugin/plugin.json
+++ b/integrations/mem0-agent-plugin/plugin.json
@@ -1,7 +1,7 @@
{
"$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json",
"name": "mem0",
- "version": "0.3.1",
+ "version": "0.3.2",
"description": "Cross-session memory and token savings for coding agents.",
"author": {
"name": "Mem0",
diff --git a/integrations/openclaw/openclaw.plugin.json b/integrations/openclaw/openclaw.plugin.json
index 02d05be4b..9d4cacaf8 100644
--- a/integrations/openclaw/openclaw.plugin.json
+++ b/integrations/openclaw/openclaw.plugin.json
@@ -2,7 +2,7 @@
"id": "openclaw-mem0",
"name": "Memory (Mem0)",
"description": "Mem0 memory backend for OpenClaw — platform (mem0.ai cloud) or self-hosted open-source. Auto-recall and auto-capture are opt-in (disabled by default). Supports OpenAI, Anthropic, Ollama (fully local), Qdrant, and PGVector providers.",
- "version": "1.1.0",
+ "version": "1.2.0",
"kind": "memory",
"skills": ["skills"],
"commandAliases": [
diff --git a/integrations/openclaw/package.json b/integrations/openclaw/package.json
index 03938e4da..49f49dbf4 100644
--- a/integrations/openclaw/package.json
+++ b/integrations/openclaw/package.json
@@ -1,6 +1,6 @@
{
"name": "@mem0/openclaw-mem0",
- "version": "1.1.0",
+ "version": "1.2.0",
"type": "module",
"description": "Mem0 memory backend for OpenClaw — platform or self-hosted open-source",
"license": "Apache-2.0",
diff --git a/integrations/opencode-plugin/package.json b/integrations/opencode-plugin/package.json
index acdbaf469..efcb60a28 100644
--- a/integrations/opencode-plugin/package.json
+++ b/integrations/opencode-plugin/package.json
@@ -1,6 +1,6 @@
{
"name": "@mem0/opencode-plugin",
- "version": "0.3.0",
+ "version": "0.4.0",
"type": "module",
"description": "Mem0 persistent memory plugin for OpenCode — add, search, and manage memories across sessions",
"main": "dist/index.js",
diff --git a/integrations/pi-agent-plugin/package.json b/integrations/pi-agent-plugin/package.json
index d05673406..7ef9f822e 100644
--- a/integrations/pi-agent-plugin/package.json
+++ b/integrations/pi-agent-plugin/package.json
@@ -1,6 +1,6 @@
{
"name": "@mem0/pi-agent-plugin",
- "version": "0.3.0",
+ "version": "0.3.1",
"type": "module",
"description": "Mem0 memory extension for Pi Agent persistent, scoped, semantic memory across sessions and projects",
"license": "Apache-2.0",
diff --git a/integrations/vercel-ai-sdk/package.json b/integrations/vercel-ai-sdk/package.json
index 7b417e460..1165c3f92 100644
--- a/integrations/vercel-ai-sdk/package.json
+++ b/integrations/vercel-ai-sdk/package.json
@@ -1,6 +1,6 @@
{
"name": "@mem0/vercel-ai-provider",
- "version": "3.0.2",
+ "version": "3.0.3",
"description": "Vercel AI Provider for providing memory to LLMs",
"main": "./dist/index.js",
"module": "./dist/index.mjs",
diff --git a/marketplace.json b/marketplace.json
index eea48e2af..b1608c958 100644
--- a/marketplace.json
+++ b/marketplace.json
@@ -13,7 +13,7 @@
},
"category": "Productivity",
"description": "Cross-session memory and token savings for coding agents.",
- "version": "0.3.1"
+ "version": "0.3.2"
}
]
}
diff --git a/mem0-ts/package.json b/mem0-ts/package.json
index 7697b2384..b0490dd2e 100644
--- a/mem0-ts/package.json
+++ b/mem0-ts/package.json
@@ -1,6 +1,6 @@
{
"name": "mem0ai",
- "version": "3.1.8",
+ "version": "3.2.0",
"description": "The Memory Layer For Your AI Apps",
"main": "./dist/index.js",
"module": "./dist/index.mjs",
diff --git a/pyproject.toml b/pyproject.toml
index 587dac221..73c5cdf71 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
[project]
name = "mem0ai"
-version = "2.0.20"
+version = "2.1.0"
description = "Long-term memory for AI Agents"
authors = [
{ name = "Mem0", email = "support@mem0.ai" }
From a39a802bbc93e85b820078cd3c4dbaf53af25dbe Mon Sep 17 00:00:00 2001
From: Himanshu <104683257+Himanshu-Sangshetti@users.noreply.github.com>
Date: Fri, 18 Sep 2026 23:19:15 +0530
Subject: [PATCH 14/54] docs(cookbooks): Company Brain with Mem0 Platform +
Supabase (#7309)
---
docs/cookbooks/integrations/supabase.mdx | 388 +++++++++++++++++++++++
docs/docs.json | 3 +-
docs/llms.txt | 1 +
3 files changed, 391 insertions(+), 1 deletion(-)
create mode 100644 docs/cookbooks/integrations/supabase.mdx
diff --git a/docs/cookbooks/integrations/supabase.mdx b/docs/cookbooks/integrations/supabase.mdx
new file mode 100644
index 000000000..cf9b8c038
--- /dev/null
+++ b/docs/cookbooks/integrations/supabase.mdx
@@ -0,0 +1,388 @@
+---
+title: Build a Company Brain with Mem0 Platform and Supabase
+description: "A step-by-step guide to a shared organizational memory: Mem0 Platform is the managed brain, Supabase is your system of record, and every agent taps it through the Mem0 MCP server."
+---
+
+
+**Uses:** Mem0 **Platform** (`MemoryClient`) · **System of record:** Supabase (Postgres + Auth) · **Access layer:** the hosted Mem0 MCP server. **You'll build:** a company brain your whole org (and every agent) writes to and queries, ending with a new-hire onboarding demo.
+
+
+Companies lose knowledge constantly: why you picked Postgres over Mongo, who owns billing, the deploy rule only one engineer remembers. A **company brain** captures this and answers questions about it, for every employee and every agent, and keeps it after people leave.
+
+We'll build one on **Mem0 Platform** (the managed memory layer, so there's no vector DB to run) with **Supabase as the system of record** (where your employees, teams, and source documents actually live) and the **Mem0 MCP server** as the wire that lets Claude Code, Cursor, or a Slack bot all reach the same brain.
+
+
+**How Platform and Supabase divide the work.** Mem0 Platform manages storage and extraction server-side, you do **not** point it at your own database. Supabase is your app's source of truth and identity provider; we *ingest* knowledge from Supabase into the brain and use Supabase Auth to decide who's asking. (If you want to self-host the vector store instead, that's the OSS path, see the [Supabase vector store reference](/components/vectordbs/dbs/supabase).)
+
+
+## Architecture
+
+```mermaid
+flowchart LR
+ subgraph SB["Supabase: system of record"]
+ K[(knowledge / employees / teams)]
+ AU[Auth · who is asking]
+ end
+ subgraph M0["Mem0 Platform: the brain"]
+ B[(managed memory)]
+ end
+ K -->|ingest| B
+ AU -->|maps to scope| B
+ CC[Claude Code] --> MCP[Mem0 MCP server]
+ CU[Cursor] --> MCP
+ SL[Slack bot] --> MCP
+ MCP --> B
+```
+
+Memory splits by entity. An individual is a **`user_id`** (their Supabase Auth id). Shared knowledge lives on an **`agent_id`**: the company-wide brain is `org:acme`, and each team is its own agent, e.g. `team:payments`. A person's own facts route to their `user_id`; company and team facts route to the agent. This split is what lets one search return "my" context alongside the shared org knowledge.
+
+## Prerequisites
+
+- **Python 3.9+**
+- A **Mem0 Platform API key**, [app.mem0.ai/dashboard/api-keys](https://app.mem0.ai/dashboard/api-keys?utm_source=oss&utm_medium=cookbook-company-brain). (Platform runs extraction and embeddings for you, so there's no OpenAI key to manage.)
+- A **Supabase** project, [supabase.com](https://supabase.com)
+
+About 20 minutes.
+
+---
+
+## Step 1: Get your Mem0 Platform API key
+
+Sign in at [app.mem0.ai](https://app.mem0.ai) and copy a key from **Dashboard → API Keys**. The key is scoped to your org and project; Mem0 resolves both server-side, so you never pass IDs by hand.
+
+## Step 2: Create the Supabase system of record
+
+In the Supabase **SQL editor**, create the tables your company already thinks in: people, teams, and a `knowledge` table the brain will ingest from. Identity reuses Supabase Auth's built-in `auth.users`.
+
+```sql
+-- Employees extend Supabase Auth's users; identity is auth.users.id (uuid)
+create table public.employees (
+ id uuid primary key references auth.users (id) on delete cascade,
+ name text not null,
+ team text not null
+);
+
+-- The company knowledge the brain ingests. `scope` decides who can recall it.
+create table public.knowledge (
+ id bigint generated always as identity primary key,
+ scope text not null, -- the shared agent this belongs to: 'org:acme' | 'team:payments'
+ content text not null,
+ author uuid references auth.users (id), -- who recorded it (their user_id); null for org seed data
+ created_at timestamptz default now(),
+ mem0_synced_at timestamptz -- null until ingested into the brain
+);
+create index on public.knowledge (mem0_synced_at, created_at);
+
+-- Seed a little company knowledge to ingest.
+insert into public.knowledge (scope, content) values
+ ('org:acme', 'We chose Postgres over MongoDB for the core product for strong transactional guarantees and relational joins.'),
+ ('org:acme', 'All production deploys go out Tuesday and Thursday; never on Fridays.'),
+ ('org:acme', 'Customer data must stay in the EU region for GDPR compliance.'),
+ ('org:acme', 'Billing is owned by the Payments team, and Alice is the Payments tech lead.'),
+ ('team:payments', 'Stripe is our processor; webhooks are verified with PAYMENTS_WEBHOOK_SECRET.');
+```
+
+Grab your project URL and **service-role** key from **Settings → API** (the ingestion job runs server-side and needs to read every scope).
+
+## Step 3: Project setup
+
+```bash
+mkdir company-brain && cd company-brain
+pip install "mem0ai>=2.0.17" supabase requests # 2.0.17+ for agent_custom_instructions
+```
+
+```bash
+export MEM0_API_KEY="m0-..."
+export SUPABASE_URL="https://.supabase.co"
+export SUPABASE_SERVICE_KEY=""
+```
+
+## Step 4: Configure the brain
+
+Create **`brain.py`**. This constructs the Platform client and teaches it what to remember. The key is the **two** instruction sets: `custom_instructions` governs a person's own (`user_id`) memories, and `agent_custom_instructions` governs shared (`agent_id`) memories, phrased in the third person so company facts read "The company…", not "The user's organization…". `custom_categories` files each memory under a useful label.
+
+```python
+# brain.py
+import os
+from mem0 import MemoryClient
+
+client = MemoryClient(api_key=os.environ["MEM0_API_KEY"])
+
+# Steer extraction (project-wide). Runs server-side; no LLM key needed here.
+client.project.update(
+ # Governs a person's OWN memories (user_id).
+ custom_instructions=(
+ "Extract the individual's own durable preferences, context, and how they work. "
+ "Ignore greetings and one-off chatter."
+ ),
+ # Governs SHARED memories (agent_id); write them in the third person.
+ agent_custom_instructions=(
+ "Extract durable company/team knowledge in the third person "
+ "(\"The company...\", \"The team...\"): decisions and their rationale, ownership "
+ "(who owns what), processes, policies, tooling choices, and gotchas. "
+ "Ignore greetings, scheduling, and one-off chatter."
+ ),
+ custom_categories=[
+ {"decision": "Architectural or product decisions and why they were made"},
+ {"ownership": "Who owns a system, service, or process"},
+ {"policy": "Compliance, security, and process rules"},
+ {"tooling": "Tools, services, and how they're configured"},
+ ],
+)
+
+# Scopes. A person is a user_id; shared brains are agent_ids.
+COMPANY = "org:acme" # agent_id: company-wide shared brain
+def team(name): return f"team:{name}" # agent_id: a team's shared brain
+def person(uid): return uid # user_id: an individual (Supabase auth id)
+```
+
+Run it once to apply the project settings:
+
+```bash
+python -c "import brain; print('brain configured')"
+```
+
+
+## Step 5: Ingest company knowledge from Supabase
+
+This is where Supabase and the brain connect. Create **`ingest.py`**: read un-synced rows from `knowledge`, add each to the Platform brain under its scope, then mark it synced. Platform `add()` is **asynchronous**, it returns an `event_id` you can poll, so we include a small `wait_for` helper.
+
+```python
+# ingest.py
+import os, time, requests
+from supabase import create_client
+from brain import client, person
+
+sb = create_client(os.environ["SUPABASE_URL"], os.environ["SUPABASE_SERVICE_KEY"])
+MEM0_HEADERS = {"Authorization": f"Token {os.environ['MEM0_API_KEY']}"}
+
+def wait_for(event_id, timeout=30):
+ """Platform extraction is async; poll the event until it settles."""
+ for _ in range(timeout):
+ r = requests.get(f"https://api.mem0.ai/v1/event/{event_id}/", headers=MEM0_HEADERS).json()
+ if r.get("status") in ("SUCCEEDED", "FAILED"):
+ return r["status"]
+ time.sleep(1)
+ return "TIMEOUT"
+
+# 1. Read knowledge that hasn't been ingested yet
+rows = sb.table("knowledge").select("*").is_("mem0_synced_at", "null").execute().data
+
+for row in rows:
+ # 2. Add it. agent_id = the shared scope (org/team); user_id = who recorded it.
+ # Mem0 routes shared facts to the agent and personal facts to the individual,
+ # so pass both when there's an author.
+ add_kwargs = {
+ "agent_id": row["scope"],
+ "metadata": {"source": "supabase", "knowledge_id": row["id"]},
+ }
+ if row["author"]:
+ add_kwargs["user_id"] = person(row["author"])
+ res = client.add([{"role": "user", "content": row["content"]}], **add_kwargs)
+ # 3. Platform returns an event_id; wait for extraction to finish
+ event_id = res.get("event_id") if isinstance(res, dict) else None
+ if event_id:
+ wait_for(event_id)
+ # 4. Mark the row synced so we never double-ingest
+ sb.table("knowledge").update({"mem0_synced_at": "now()"}).eq("id", row["id"]).execute()
+
+print(f"Ingested {len(rows)} knowledge items into the company brain.")
+```
+
+```bash
+python ingest.py
+```
+
+```text
+Ingested 5 knowledge items into the company brain.
+```
+
+Re-running is safe, `mem0_synced_at` gates it, so a nightly cron can keep the brain in step with Supabase.
+
+## Step 6: Ask the brain
+
+Create **`ask.py`**. It searches everything relevant to the asker: their own (`user_id`) memories **plus** the shared company and team (`agent_id`) memories. This has to be an **`OR`**, each memory row belongs to exactly one entity, so a flat filter or an `AND` of a `user_id` and an `agent_id` matches nothing.
+
+```python
+# ask.py
+import sys
+from brain import client, COMPANY, team, person
+
+def ask(question: str, uid: str | None = None, user_team: str | None = None) -> str:
+ scopes = [{"agent_id": COMPANY}] # company-wide brain
+ if user_team:
+ scopes.append({"agent_id": team(user_team)}) # the asker's team
+ if uid:
+ scopes.append({"user_id": person(uid)}) # the asker's own memories
+ hits = client.search(
+ query=question,
+ filters={"OR": scopes}, # OR, never AND (one FK per memory row)
+ top_k=5,
+ rerank=True,
+ )
+ return "\n".join(f"- {h['memory']}" for h in hits.get("results", hits))
+
+if __name__ == "__main__":
+ print(ask(" ".join(sys.argv[1:]) or "When can we deploy?"))
+```
+
+```bash
+python ask.py "Why did we pick Postgres, and can I deploy on Friday?"
+```
+
+```text
+- The company chose Postgres over MongoDB for strong transactional guarantees and relational joins
+- The company's production deploys go out Tuesday and Thursday, never on Fridays
+```
+
+Search returns every relevant memory, so a question resolves across separate facts, here it pulls both the owning team and the person:
+
+```bash
+python ask.py "Who should I talk to about billing?"
+```
+
+```text
+- Billing is owned by the Payments team
+- Alice is the Payments tech lead
+```
+
+## Step 7: Sharper retrieval
+
+Platform search is hybrid (semantic + keyword) and filterable. Combine a keyword pass with a category filter to answer precise questions:
+
+```python
+client.search(
+ query="webhook signing secret",
+ filters={"agent_id": "team:payments", "categories": {"in": ["tooling"]}},
+ keyword_search=True, # hybrid keyword + semantic
+ rerank=True,
+ threshold=0.3,
+)
+```
+
+Filters use keyword operators (`in`, `gte`, `contains`, …) and AND/OR/NOT, so you can scope by date, category, or metadata, for example the company's policies added this quarter:
+
+```python
+client.search(
+ query="compliance rules",
+ filters={"AND": [
+ {"agent_id": "org:acme"},
+ {"categories": {"in": ["policy"]}},
+ {"created_at": {"gte": "2026-01-01"}},
+ ]},
+)
+```
+
+## Step 8: Expose the brain to every agent (MCP)
+
+A brain only your script can reach isn't a company brain. Mem0's **hosted MCP server** lets any agent (Claude Code, Cursor, a Slack bot) query and contribute to the *same* brain. The endpoint is `https://mcp.mem0.ai/mcp`, and the supported way to connect is the `mcp-add` helper, which registers the server and runs Mem0's OAuth login so no key ever lands in a config file.
+
+
+
+```bash
+npx mcp-add --url "https://mcp.mem0.ai/mcp" --clients "claude code,cursor"
+```
+Complete the browser login on first connect. Now the agent has the brain's memory tools (`add_memory`, `search_memories`, and more) available in-editor.
+
+
+```json
+{
+ "mcpServers": {
+ "mem0": { "url": "https://mcp.mem0.ai/mcp" }
+ }
+}
+```
+Auth happens via Mem0's OAuth flow on first use, don't paste a static token into the file (the hosted gateway may reject a raw `Token` header).
+
+
+```python
+# A Slack bot is just another MCP client. Point its MCP layer at the same URL,
+# authenticate via Mem0's OAuth flow, and pass the company scope on each call.
+await mcp.call_tool("search_memories", {
+ "query": user_message,
+ "agent_id": "org:acme",
+})
+```
+
+
+
+With this, an engineer asks the brain from their editor and a teammate asks it from Slack, one shared memory behind both.
+
+## Step 9: Onboard a new hire (the payoff)
+
+This is what a company brain is *for*. Dana joins, and her identity comes from **Supabase Auth**, which maps straight to her Mem0 `user_id`. She asks the questions every new hire asks and gets real answers on day one, drawn from the shared company (and her team's) brain, plus anything she's told it herself.
+
+```python
+# onboarding.py
+from brain import client, person
+from ask import ask
+
+# In a real app these come from sb.auth.get_user(jwt) and the employees table.
+dana_uid, dana_team = "8f3c...-dana", "payments"
+
+# Dana also tells the brain how *she* works. This is personal, so it goes to her
+# user_id, not the shared agent, and stays scoped to her.
+client.add(
+ [{"role": "user", "content": "I prefer early returns over nested ifs, and I review PRs in the morning."}],
+ user_id=person(dana_uid),
+)
+
+for q in [
+ "Who owns billing and who do I talk to?", # company (agent) knowledge
+ "When are deploys, and are there hard rules?",
+ "How do I like to write code?", # Dana's own (user) knowledge
+]:
+ print(f"Q: {q}\nA: {ask(q, uid=dana_uid, user_team=dana_team)}\n")
+```
+
+```text
+Q: Who owns billing and who do I talk to?
+A: - Billing is owned by the Payments team; Alice is the Payments tech lead
+
+Q: When are deploys, and are there hard rules?
+A: - The company's production deploys go out Tuesday and Thursday, never on Fridays
+
+Q: How do I like to write code?
+A: - User prefers early returns over nested ifs
+```
+
+The same `ask()` blends the shared company facts with Dana's own preference, because the `OR` filter spans both her `user_id` and the org and team `agent_id`s.
+
+Dana onboarded herself by asking, drawing on the shared brain the rest of the team had been filling.
+
+## Production notes
+
+
+**`user_id` vs `agent_id`.** An individual is a `user_id`; shared brains (company, team) are `agent_id`s. Keeping them separate is what gives you the third-person "The company…" framing and lets a person's own context sit alongside org knowledge. Put a secret like a webhook key on a **team** agent, never the company agent, or everyone can recall it, and mirror the boundary in Supabase with a Row Level Security policy on `knowledge`.
+
+
+
+**Search must `OR` the scopes.** A memory row belongs to exactly one entity, so `filters={"OR": [{"user_id": ...}, {"agent_id": "org:acme"}, {"agent_id": "team:..."}]}`. A flat filter, or an `AND` of a `user_id` and an `agent_id`, returns nothing.
+
+
+
+**`add()` is asynchronous.** It returns `{event_id, status: "PENDING"}` and extraction finishes a moment later, poll `GET /v1/event/{event_id}/` (as in Step 5) when you need to know a write has landed before searching for it.
+
+
+
+**Where the entity ID goes differs by call.** `search()` and `get_all()` take the scope inside `filters={...}` (a top-level `user_id=`/`agent_id=` is rejected). `add()` and `delete_all()` are the opposite, they take it as a top-level keyword: `client.delete_all(agent_id="team:payments")`. Deletes are asynchronous too, so a `get_all` right after a `delete_all` can still show rows for a few seconds.
+
+
+## Where to take it next
+
+- **Auto-feed the brain** from PR descriptions, RFCs, and incident write-ups so it grows without anyone thinking about it, just insert into Supabase `knowledge` and let the cron ingest.
+- **Scope by real identity** end to end: verify the Supabase JWT, read `sb.auth.get_user(jwt).user.id` for the `user_id`, look up the person's team, and `OR` their `user_id` with the company and team `agent_id`s on every recall.
+- **Give teams a private view** with Supabase RLS so `team:` knowledge is only readable by that team.
+
+---
+
+
+
+ Connect any agent or editor to the brain over MCP.
+
+
+ Steer exactly what the brain extracts and how it's filed.
+
+
+
+
diff --git a/docs/docs.json b/docs/docs.json
index 4ca51fa24..7aecc007c 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -444,7 +444,8 @@
"cookbooks/integrations/mastra-agent",
"cookbooks/integrations/healthcare-google-adk",
"cookbooks/integrations/aws-bedrock",
- "cookbooks/integrations/tavily-search"
+ "cookbooks/integrations/tavily-search",
+ "cookbooks/integrations/supabase"
]
},
{
diff --git a/docs/llms.txt b/docs/llms.txt
index 686835a0e..ce60e29f5 100644
--- a/docs/llms.txt
+++ b/docs/llms.txt
@@ -326,6 +326,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.
From 17852dc648ed332aa62360de2eba4ff84ebf6ad9 Mon Sep 17 00:00:00 2001
From: "mintlify[bot]" <109931778+mintlify[bot]@users.noreply.github.com>
Date: Tue, 22 Sep 2026 18:50:39 +0530
Subject: [PATCH 15/54] SEO & metadata audit: shorten supabase cookbook
description (#7380)
Co-authored-by: mintlify[bot] <109931778+mintlify[bot]@users.noreply.github.com>
---
docs/cookbooks/integrations/supabase.mdx | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/docs/cookbooks/integrations/supabase.mdx b/docs/cookbooks/integrations/supabase.mdx
index cf9b8c038..60b102324 100644
--- a/docs/cookbooks/integrations/supabase.mdx
+++ b/docs/cookbooks/integrations/supabase.mdx
@@ -1,6 +1,6 @@
---
title: Build a Company Brain with Mem0 Platform and Supabase
-description: "A step-by-step guide to a shared organizational memory: Mem0 Platform is the managed brain, Supabase is your system of record, and every agent taps it through the Mem0 MCP server."
+description: "Build a shared company brain using Mem0 Platform as the managed memory layer, Supabase as your system of record, and the Mem0 MCP server."
---
From 8b38da9ab8f1e0347870abad662c8c26c07007f2 Mon Sep 17 00:00:00 2001
From: "mintlify[bot]" <109931778+mintlify[bot]@users.noreply.github.com>
Date: Tue, 22 Sep 2026 18:51:03 +0530
Subject: [PATCH 16/54] Fix grammar & typos: SDK changelog v2.0.8 entry (#6716)
Co-authored-by: mintlify[bot] <109931778+mintlify[bot]@users.noreply.github.com>
---
docs/changelog/sdk.mdx | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/docs/changelog/sdk.mdx b/docs/changelog/sdk.mdx
index 50922493e..5562fbe1d 100644
--- a/docs/changelog/sdk.mdx
+++ b/docs/changelog/sdk.mdx
@@ -182,7 +182,7 @@ mode: "wide"
**New Features:**
-- **Embeddings:** Add native `embed_batch` to five embedders: LM Studio, Together, HuggingFace, Vertex AI, and Google GenAI: for batched embedding requests ([#5609](https://github.com/mem0ai/mem0/pull/5609))
+- **Embeddings:** Add native `embed_batch` to five embedders for batched embedding requests: LM Studio, Together, HuggingFace, Vertex AI, and Google GenAI ([#5609](https://github.com/mem0ai/mem0/pull/5609))
**Bug Fixes:**
- **Core:** Guard against malformed `image_url` entries in `parse_vision_messages` to prevent crashes ([#5631](https://github.com/mem0ai/mem0/pull/5631))
From a214ec37bcc6309b0332ac3e8a58b7fc717dfa19 Mon Sep 17 00:00:00 2001
From: Shahil kadia
Date: Tue, 22 Sep 2026 19:01:33 +0530
Subject: [PATCH 17/54] fix(examples): migrate OSS Memory search/get_all calls
to v3 filters API (#7300)
Co-authored-by: Shahil Kadia
---
examples/misc/movie_recommendation_grok3.py | 6 +++---
examples/misc/strands_agent_aws_elasticache_neptune.py | 6 +++---
examples/misc/vllm_example.py | 10 +++++-----
3 files changed, 11 insertions(+), 11 deletions(-)
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!")
From fd8fd087ea551648897717ce7bca86acfee5b268 Mon Sep 17 00:00:00 2001
From: 88lin <431761794@qq.com>
Date: Tue, 22 Sep 2026 21:55:51 +0800
Subject: [PATCH 18/54] docs(vectordbs/pinecone): document extra_params on the
Python config table (#7222)
---
docs/components/vectordbs/dbs/pinecone.mdx | 1 +
1 file changed, 1 insertion(+)
diff --git a/docs/components/vectordbs/dbs/pinecone.mdx b/docs/components/vectordbs/dbs/pinecone.mdx
index 31662ed29..1cd06b592 100644
--- a/docs/components/vectordbs/dbs/pinecone.mdx
+++ b/docs/components/vectordbs/dbs/pinecone.mdx
@@ -94,6 +94,7 @@ Here are the parameters available for configuring Pinecone:
| `hybrid_search` | Whether to enable hybrid search | `False` |
| `metric` | Distance metric for vector similarity | `"cosine"` |
| `batch_size` | Batch size for operations | `100` |
+| `extra_params` | Additional keyword arguments passed to the `Pinecone` client constructor. Ignored when `client` is supplied. | `None` |
| `namespace` | Namespace for the collection, useful for multi-tenancy. | `None` |
From 5d38e3703ab58df2922fe900b772412e9ae1bcab Mon Sep 17 00:00:00 2001
From: Deshraj Yadav
Date: Tue, 22 Sep 2026 07:22:54 -0700
Subject: [PATCH 19/54] chore: remove CLI_SPECIFICATION.md (#4578)
Co-authored-by: Claude Opus 4.6 (1M context)
Co-authored-by: kartik-mem0
---
cli/CLI_SPECIFICATION.md | 1613 --------------------------------------
1 file changed, 1613 deletions(-)
delete mode 100644 cli/CLI_SPECIFICATION.md
diff --git a/cli/CLI_SPECIFICATION.md b/cli/CLI_SPECIFICATION.md
deleted file mode 100644
index a243e833c..000000000
--- a/cli/CLI_SPECIFICATION.md
+++ /dev/null
@@ -1,1613 +0,0 @@
-# mem0 CLI SDK Specification
-
-Complete reference for the mem0 CLI. This document is the authoritative guide for any developer or AI agent working on this SDK.
-
----
-
-## Table of Contents
-
-1. [Project Overview](#1-project-overview)
-2. [Architecture](#2-architecture)
-3. [Complete Command Reference](#3-complete-command-reference)
-4. [API Endpoints](#4-api-endpoints)
-5. [Configuration](#5-configuration)
-6. [Key Behavioral Patterns](#6-key-behavioral-patterns)
-7. [Output Modes](#7-output-modes)
-8. [Agent-Friendly Design Decisions](#8-agent-friendly-design-decisions)
-9. [Adding a New Command](#9-adding-a-new-command)
-10. [Adding a New Language Implementation](#10-adding-a-new-language-implementation)
-
----
-
-## 1. Project Overview
-
-### What is mem0 CLI?
-
-mem0 CLI is the official command-line interface for [mem0](https://mem0.ai) -- the memory layer for AI agents. It lets developers and AI agents add, search, list, update, and delete memories via the mem0 Platform API from the terminal.
-
-### Who is it for?
-
-- Developers integrating mem0 into their workflows
-- AI agents that need persistent memory (the CLI is designed with `--json`/`--agent` global flags and `help --json` specifically for machine consumption)
-- DevOps/CI pipelines that need to manage memories programmatically
-
-### Project Structure
-
-The `cli/` directory provides the mem0 CLI in two languages with a shared specification for behavioral consistency.
-
-| Language | Directory | Package Name | Install Command |
-|------------|------------|---------------|----------------------------|
-| TypeScript | `node/` | `@mem0/cli` | `npm install -g @mem0/cli` |
-| Python | `python/` | `mem0-cli` | `pip install mem0-cli` |
-
-Both implementations produce a binary named `mem0` and provide **identical CLI behavior** -- same commands, same options, same output formats, same error messages.
-
-### Version
-
-Current version: `0.1.0` (defined in `cli-spec.json`, `node/package.json`, and `python/pyproject.toml`).
-
-### License
-
-Apache-2.0
-
----
-
-## 2. Architecture
-
-### Directory Layout
-
-```
-.
-├── cli-spec.json # Shared CLI specification (source of truth)
-├── README.md # CLI README
-├── SDK_SPECIFICATION.md # This file
-├── python/
-│ ├── pyproject.toml # Python package config (hatchling build)
-│ ├── README.md
-│ └── src/mem0_cli/
-│ ├── __init__.py # __version__
-│ ├── app.py # Main Typer app, command registration, helpers
-│ ├── config.py # Config loading/saving, env var overrides
-│ ├── branding.py # Colors, icons, banner, timed_status, print helpers
-│ ├── output.py # Output formatting (text, json, table, quiet)
-│ ├── backend/
-│ │ ├── __init__.py # Re-exports get_backend
-│ │ ├── base.py # Abstract Backend ABC, get_backend factory
-│ │ └── platform.py # PlatformBackend (httpx), error classes
-│ └── commands/
-│ ├── memory.py # cmd_add, cmd_search, cmd_get, cmd_list, cmd_update, cmd_delete, cmd_delete_all
-│ ├── init_cmd.py # run_init (interactive wizard)
-│ ├── config_cmd.py # cmd_config_show, cmd_config_get, cmd_config_set
-│ ├── entities.py # cmd_entities_list, cmd_entities_delete
-│ ├── events_cmd.py # cmd_event_list, cmd_event_status
-│ └── utils.py # cmd_status, cmd_version, cmd_import
-└── node/
- ├── package.json # Node package config (tsup build)
- ├── README.md
- └── src/
- ├── index.ts # Main Commander.js app, command registration, helpers
- ├── config.ts # Config loading/saving, env var overrides
- ├── branding.ts # Colors, icons, banner, timedStatus, print helpers
- ├── output.ts # Output formatting (text, json, table, quiet)
- ├── state.ts # Agent mode flag (setAgentMode, isAgentMode)
- ├── help.ts # Rich-style help formatter (panels, command ordering)
- ├── backend/
- │ ├── index.ts # Re-exports
- │ ├── base.ts # Backend interface, error classes, getBackend factory
- │ └── platform.ts # PlatformBackend (native fetch), _buildFilters
- └── commands/
- ├── memory.ts # cmdAdd, cmdSearch, cmdGet, cmdList, cmdUpdate, cmdDelete, cmdDeleteAll
- ├── init.ts # runInit (interactive wizard)
- ├── config.ts # cmdConfigShow, cmdConfigGet, cmdConfigSet
- ├── entities.ts # cmdEntitiesList, cmdEntitiesDelete
- ├── events.ts # cmdEventList, cmdEventStatus
- └── utils.ts # cmdStatus, cmdVersion, cmdImport
-```
-
-### How Both CLIs Mirror Each Other
-
-Every command, option, argument, and behavioral pattern is implemented identically in both CLIs. The shared `cli-spec.json` is the source of truth for:
-
-- All command names, descriptions, and usage strings
-- All arguments and options (names, types, defaults, help text, panel grouping)
-- API endpoint paths and methods
-- Branding constants (colors, icons, logo)
-- Config schema (sections, fields, env var mappings)
-- Error messages and templates
-- Option grouping (Scope, Search, Pagination, Filters, Output, Connection)
-
-### Tech Stacks
-
-| Concern | Python | Node |
-|------------------|-------------------------------------|-----------------------------------------|
-| CLI framework | Typer >= 0.9.0 | Commander.js ^12.0.0 |
-| Rich output | Rich >= 13.0.0 | chalk ^5.3.0 + cli-table3 ^0.6.4 |
-| Spinners | Rich Status | ora ^8.0.0 |
-| Boxed panels | Rich Panel | boxen ^7.1.0 |
-| HTTP client | httpx >= 0.24.0 | Native fetch (Node >= 18) |
-| Build system | Hatchling | tsup ^8.0.0 |
-| Test framework | pytest >= 7.0 | vitest ^1.5.0 |
-| Linter | ruff >= 0.1.0 | Biome ^1.7.0 |
-| Type checking | (ruff type checks) | TypeScript ^5.4.0 |
-| Min runtime | Python >= 3.10 | Node >= 18.0.0 |
-| Module format | Standard Python package | ESM (`"type": "module"`) |
-| Entrypoint | `mem0 = "mem0_cli.app:main"` | `"bin": { "mem0": "./dist/index.js" }` |
-
----
-
-## 3. Complete Command Reference
-
-### 3.1 `init`
-
-Interactive setup wizard for mem0 CLI.
-
-| Property | Value |
-|------------------|-------|
-| Usage | `mem0 init [OPTIONS]` |
-| needsBackend | No |
-| needsConfig | No |
-| resolveIds | No |
-| resolveGraph | No |
-| confirmDangerous | No |
-
-**Options:**
-
-| Flag | Type | Required | Default | Help |
-|-----------------|--------|----------|---------|------|
-| `--api-key` | string | No | - | API key (skip prompt). |
-| `-u, --user-id` | string | No | - | Default user ID (skip prompt). |
-| `--email` | string | No | - | Login via email verification code. |
-| `--code` | string | No | - | Verification code (use with --email for non-interactive login). |
-| `--force` | bool | No | false | Overwrite existing config without confirmation. |
-
-**Behavior:**
-
-*Existing config protection:*
-- If `~/.mem0/config.json` exists with an API key, the CLI warns and asks for confirmation before overwriting.
-- In non-TTY mode, this is a hard error unless `--force` is passed.
-- `--force` skips the confirmation in both TTY and non-TTY modes.
-
-*Email login flow (when `--email` is provided):*
-- Sends a 6-digit verification code to the email via `POST /api/v1/auth/email_code/`.
-- If `--code` is also provided, verifies immediately (fully non-interactive).
-- If `--code` is not provided, prompts for the code interactively.
-- On success: receives API key, org_id, project_id. Saves to config. Creates account if email is new.
-- Cannot be combined with `--api-key`.
-
-*API key flow (existing behavior):*
-- If both `--api-key` and `--user-id` are provided, runs non-interactively (no prompts).
-- If running in a non-TTY without both flags, prints an error with usage hint and exits.
-- Interactive mode: prints banner, prompts for API key (masked with `*`), prompts for default user ID (default: `mem0-cli`), validates connection, saves config.
-- API key input uses raw terminal mode to echo `*` for each character typed. Supports backspace and Ctrl+U (clear line).
-
-**Examples:**
-```bash
-mem0 init
-mem0 init --api-key m0-xxx --user-id alice
-mem0 init --api-key m0-xxx --user-id alice --force
-mem0 init --email alice@company.com
-mem0 init --email alice@company.com --code 482901
-```
-
----
-
-### 3.2 `add`
-
-Add a memory from text, messages, file, or stdin.
-
-| Property | Value |
-|------------------|-------|
-| Usage | `mem0 add [OPTIONS]` |
-| needsBackend | Yes |
-| needsConfig | Yes |
-| resolveIds | Yes |
-| resolveGraph | Yes |
-| confirmDangerous | No |
-| Output formats | text, json, quiet |
-| Default output | text |
-| API endpoint | `POST /v1/memories/` |
-
-**Arguments:**
-
-| Name | Type | Required | Help |
-|--------|--------|----------|------|
-| `text` | string | No | Text content to add as a memory. |
-
-**Options:**
-
-| Flag | Type | Default | Panel | Help |
-|------------------|---------|---------|------------|------|
-| `-u, --user-id` | string | - | Scope | Scope to user. |
-| `--agent-id` | string | - | Scope | Scope to agent. |
-| `--app-id` | string | - | Scope | Scope to app. |
-| `--run-id` | string | - | Scope | Scope to run. |
-| `--messages` | string | - | - | Conversation messages as JSON. |
-| `-f, --file` | path | - | - | Read messages from JSON file. |
-| `-m, --metadata` | string | - | - | Custom metadata as JSON. |
-| `--immutable` | boolean | false | - | Prevent future updates. |
-| `--no-infer` | boolean | false | - | Skip inference, store raw. |
-| `--expires` | string | - | - | Expiration date (YYYY-MM-DD). |
-| `--categories` | string | - | - | Categories (JSON array or comma-separated). |
-| `--graph` | boolean | false | Scope | Enable graph memory extraction. |
-| `--no-graph` | boolean | false | Scope | Disable graph memory extraction. |
-| `-o, --output` | string | "text" | Output | Output format: text, json, quiet. |
-| `--api-key` | string | - | Connection | Override API key. |
-| `--base-url` | string | - | Connection | Override API base URL. |
-
-**Input priority:** `--file` > `--messages` > text argument > stdin (if piped and no text).
-
-**Content wrapping:** Text content is wrapped as `[{"role": "user", "content": ""}]` before sending to the API. Messages from `--messages` or `--file` are sent as-is.
-
-**Examples:**
-```bash
-mem0 add "I prefer dark mode" --user-id alice
-echo "text" | mem0 add -u alice
-mem0 add --file msgs.json -u alice -o json
-```
-
----
-
-### 3.3 `search`
-
-Search memories by semantic query.
-
-| Property | Value |
-|------------------|-------|
-| Usage | `mem0 search [OPTIONS]` |
-| needsBackend | Yes |
-| needsConfig | Yes |
-| resolveIds | Yes |
-| resolveGraph | Yes |
-| confirmDangerous | No |
-| Output formats | text, json, table |
-| Default output | text |
-| API endpoint | `POST /v2/memories/search/` |
-
-**Arguments:**
-
-| Name | Type | Required | Help |
-|---------|--------|----------|------|
-| `query` | string | Yes | Search query. |
-
-**Options:**
-
-| Flag | Type | Default | Panel | Help |
-|-------------------------|---------|---------|------------|------|
-| `-u, --user-id` | string | - | Scope | Filter by user. |
-| `--agent-id` | string | - | Scope | Filter by agent. |
-| `--app-id` | string | - | Scope | Filter by app. |
-| `--run-id` | string | - | Scope | Filter by run. |
-| `-k, --top-k, --limit` | integer | 10 | Search | Number of results. |
-| `--threshold` | float | 0.3 | Search | Minimum similarity score. |
-| `--rerank` | boolean | false | Search | Enable reranking (Platform only). |
-| `--keyword` | boolean | false | Search | Use keyword search. |
-| `--filter` | string | - | Search | Advanced filter expression (JSON). |
-| `--fields` | string | - | Search | Specific fields to return (comma-separated). |
-| `--graph` | boolean | false | Search | Enable graph in search. |
-| `--no-graph` | boolean | false | Search | Disable graph in search. |
-| `-o, --output` | string | "text" | Output | Output: text, json, table. |
-| `--api-key` | string | - | Connection | Override API key. |
-| `--base-url` | string | - | Connection | Override API base URL. |
-
-**Stdin fallback:** If no query argument is provided and stdin is piped, reads query from stdin.
-
-**Examples:**
-```bash
-mem0 search "preferences" --user-id alice
-mem0 search "tools" -u alice -o json -k 5
-echo "preferences" | mem0 search -u alice
-```
-
----
-
-### 3.4 `get`
-
-Get a specific memory by ID.
-
-| Property | Value |
-|------------------|-------|
-| Usage | `mem0 get [OPTIONS]` |
-| needsBackend | Yes |
-| needsConfig | No |
-| resolveIds | No |
-| resolveGraph | No |
-| confirmDangerous | No |
-| Output formats | text, json |
-| Default output | text |
-| API endpoint | `GET /v1/memories/{memory_id}/` |
-
-**Arguments:**
-
-| Name | Type | Required | Help |
-|-------------|--------|----------|------|
-| `memory_id` | string | Yes | Memory ID to retrieve. |
-
-**Options:**
-
-| Flag | Type | Default | Panel | Help |
-|----------------|--------|---------|------------|------|
-| `-o, --output` | string | "text" | Output | Output: text, json. |
-| `--api-key` | string | - | Connection | Override API key. |
-| `--base-url` | string | - | Connection | Override API base URL. |
-
-**Examples:**
-```bash
-mem0 get abc-123-def-456
-mem0 get abc-123-def-456 -o json
-```
-
----
-
-### 3.5 `list`
-
-List memories with optional filters.
-
-| Property | Value |
-|------------------|-------|
-| Usage | `mem0 list [OPTIONS]` |
-| needsBackend | Yes |
-| needsConfig | Yes |
-| resolveIds | Yes |
-| resolveGraph | Yes |
-| confirmDangerous | No |
-| Output formats | text, json, table |
-| Default output | table |
-| API endpoint | `POST /v2/memories/` |
-
-**Arguments:** None.
-
-**Options:**
-
-| Flag | Type | Default | Panel | Help |
-|------------------|---------|---------|------------|------|
-| `-u, --user-id` | string | - | Scope | Filter by user. |
-| `--agent-id` | string | - | Scope | Filter by agent. |
-| `--app-id` | string | - | Scope | Filter by app. |
-| `--run-id` | string | - | Scope | Filter by run. |
-| `--page` | integer | 1 | Pagination | Page number. |
-| `--page-size` | integer | 100 | Pagination | Results per page. |
-| `--category` | string | - | Filters | Filter by category. |
-| `--after` | string | - | Filters | Created after (YYYY-MM-DD). |
-| `--before` | string | - | Filters | Created before (YYYY-MM-DD). |
-| `--graph` | boolean | false | Filters | Enable graph in listing. |
-| `--no-graph` | boolean | false | Filters | Disable graph in listing. |
-| `-o, --output` | string | "table" | Output | Output: text, json, table. |
-| `--api-key` | string | - | Connection | Override API key. |
-| `--base-url` | string | - | Connection | Override API base URL. |
-
-**Examples:**
-```bash
-mem0 list -u alice
-mem0 list --category prefs --after 2024-01-01 -o json
-```
-
----
-
-### 3.6 `update`
-
-Update a memory's text or metadata.
-
-| Property | Value |
-|------------------|-------|
-| Usage | `mem0 update [text] [OPTIONS]` |
-| needsBackend | Yes |
-| needsConfig | No |
-| resolveIds | No |
-| resolveGraph | No |
-| confirmDangerous | No |
-| Output formats | text, json, quiet |
-| Default output | text |
-| API endpoint | `PUT /v1/memories/{memory_id}/` |
-
-**Arguments:**
-
-| Name | Type | Required | Help |
-|-------------|--------|----------|------|
-| `memory_id` | string | Yes | Memory ID to update. |
-| `text` | string | No | New memory text. |
-
-**Options:**
-
-| Flag | Type | Default | Panel | Help |
-|------------------|--------|---------|------------|------|
-| `-m, --metadata` | string | - | - | Update metadata (JSON). |
-| `-o, --output` | string | "text" | Output | Output: text, json, quiet. |
-| `--api-key` | string | - | Connection | Override API key. |
-| `--base-url` | string | - | Connection | Override API base URL. |
-
-**Stdin fallback:** If no text argument is provided and no `--metadata` flag is set and stdin is piped, reads text from stdin.
-
-**Examples:**
-```bash
-mem0 update abc-123 "new text"
-mem0 update abc-123 --metadata '{"key":"val"}'
-echo "new text" | mem0 update abc-123
-```
-
----
-
-### 3.7 `delete`
-
-Delete a memory, all memories matching a scope, or an entity. This is a consolidated command with three mutually exclusive modes.
-
-| Property | Value |
-|------------------|-------|
-| Usage | `mem0 delete [memory_id] [OPTIONS]` |
-| needsBackend | Yes |
-| needsConfig | Yes |
-| resolveIds | Yes |
-| resolveGraph | No |
-| confirmDangerous | Yes |
-| Output formats | text, json, quiet |
-| Default output | text |
-| API endpoint | `DELETE /v1/memories/{memory_id}/` (single), `DELETE /v1/memories/` (--all), `DELETE /v1/entities/` (--entity) |
-
-**Arguments:**
-
-| Name | Type | Required | Help |
-|-------------|--------|----------|------|
-| `memory_id` | string | No | Memory ID to delete (omit when using --all or --entity). |
-
-**Options:**
-
-| Flag | Type | Default | Panel | Help |
-|-----------------|---------|---------|------------|------|
-| `--all` | boolean | false | - | Delete all memories matching scope filters. |
-| `--entity` | boolean | false | - | Delete the entity itself and all its memories (cascade). |
-| `--project` | boolean | false | - | With --all: delete ALL memories project-wide. |
-| `--dry-run` | boolean | false | - | Show what would be deleted without deleting. |
-| `--force` | boolean | false | - | Skip confirmation. |
-| `-u, --user-id` | string | - | Scope | Scope to user. |
-| `--agent-id` | string | - | Scope | Scope to agent. |
-| `--app-id` | string | - | Scope | Scope to app. |
-| `--run-id` | string | - | Scope | Scope to run. |
-| `-o, --output` | string | "text" | Output | Output: text, json, quiet. |
-| `--api-key` | string | - | Connection | Override API key. |
-| `--base-url` | string | - | Connection | Override API base URL. |
-
-**Three modes (mutually exclusive):**
-
-1. **Single memory:** `mem0 delete ` -- deletes one memory by ID. Cannot combine with `--all` or `--entity`.
-2. **Bulk delete:** `mem0 delete --all [scope]` -- deletes all memories matching scope filters. Use `--project` with `--all` to wipe all memories project-wide (sends wildcard `*` entity IDs). Cannot combine with `` or `--entity`.
-3. **Entity cascade:** `mem0 delete --entity [scope]` -- deletes the entity itself and all its memories. Cannot combine with `` or `--all`.
-
-If none of ``, `--all`, or `--entity` is provided, the command prints a usage hint and exits with an error.
-
-**Dry-run behavior:**
-- Single: fetches the memory via `GET`, displays it, then prints "No changes made."
-- `--all`: lists matching memories and displays the count, then prints "No changes made."
-- `--entity`: shows the scope that would be affected without deleting.
-
-**Confirmation:** Without `--force`, prompts the user with "[y/N]" confirmation. With `--all --project`, the prompt warns about entire project wipe.
-
-**`--all --project` wildcard behavior:** Sends `DELETE /v1/memories/` with query params `user_id=*&agent_id=*&app_id=*&run_id=*`. The API typically returns an async response with a `message` field (deletion happens in background). The CLI detects this and prints "Deletion started. Memories will be removed in the background."
-
-**Examples:**
-```bash
-mem0 delete abc-123-def-456 # single memory
-mem0 delete --all -u alice --force # all memories for user
-mem0 delete --all --project --force # project-wide wipe
-mem0 delete --entity -u alice --force # entity + all its memories
-mem0 delete abc-123 --dry-run # preview single delete
-```
-
----
-
-### 3.8 `import`
-
-Import memories from a JSON file.
-
-| Property | Value |
-|------------------|-------|
-| Usage | `mem0 import [OPTIONS]` |
-| needsBackend | Yes |
-| needsConfig | Yes |
-| resolveIds | Yes |
-| resolveGraph | No |
-| confirmDangerous | No |
-| Output formats | text, json |
-| Default output | text |
-| API endpoint | `POST /v1/memories/` (per item) |
-
-**Arguments:**
-
-| Name | Type | Required | Help |
-|-------------|--------|----------|------|
-| `file_path` | string | Yes | JSON file to import. |
-
-**Options:**
-
-| Flag | Type | Default | Panel | Help |
-|-----------------|--------|---------|------------|------|
-| `-u, --user-id` | string | - | Scope | Override user ID. |
-| `--agent-id` | string | - | Scope | Override agent ID. |
-| `-o, --output` | string | "text" | Output | Output: text, json. |
-| `--api-key` | string | - | Connection | Override API key. |
-| `--base-url` | string | - | Connection | Override API base URL. |
-
-**File format:** JSON array (or single object) where each item has `memory`, `text`, or `content` field for the text, plus optional `user_id`, `agent_id`, and `metadata` fields.
-
-**Behavior:** Iterates through items, calling `backend.add()` for each. CLI-provided `--user-id` and `--agent-id` override per-item values. Displays progress indicator (every 10 items in Node, Rich progress bar in Python). Reports `added` and `failed` counts.
-
-**JSON output envelope:**
-```json
-{
- "status": "success",
- "command": "import",
- "data": { "added": 42, "failed": 0, "duration_s": 3.14 },
- "duration_ms": 3140
-}
-```
-
-**Examples:**
-```bash
-mem0 import data.json --user-id alice
-mem0 import data.json -u alice -o json
-```
-
----
-
-### 3.9 `config show`
-
-Display current configuration (secrets redacted).
-
-| Property | Value |
-|------------------|-------|
-| Usage | `mem0 config show [OPTIONS]` |
-| needsBackend | No |
-| needsConfig | No |
-
-**Options:**
-
-| Flag | Type | Default | Help |
-|----------------|--------|---------|------|
-| `-o, --output` | string | "text" | Output: text, json. |
-
-**Behavior:** Loads config (file + env vars), displays as table (text) or JSON envelope. API keys are always redacted using `redact_key()`.
-
-**Examples:**
-```bash
-mem0 config show
-mem0 config show -o json
-```
-
----
-
-### 3.10 `config get`
-
-Get a configuration value.
-
-| Property | Value |
-|------------------|-------|
-| Usage | `mem0 config get ` |
-| needsBackend | No |
-| needsConfig | No |
-
-**Arguments:**
-
-| Name | Type | Required | Help |
-|-------|--------|----------|------|
-| `key` | string | Yes | Config key (e.g. `platform.api_key`). |
-
-**Valid keys:** `platform.api_key`, `platform.base_url`, `defaults.user_id`, `defaults.agent_id`, `defaults.app_id`, `defaults.run_id`, `defaults.enable_graph`.
-
-**Behavior:** Prints the value to stdout. API keys are redacted. Unknown keys print an error.
-
-**Examples:**
-```bash
-mem0 config get platform.api_key
-mem0 config get defaults.user_id
-```
-
----
-
-### 3.11 `config set`
-
-Set a configuration value.
-
-| Property | Value |
-|------------------|-------|
-| Usage | `mem0 config set ` |
-| needsBackend | No |
-| needsConfig | No |
-
-**Arguments:**
-
-| Name | Type | Required | Help |
-|---------|--------|----------|------|
-| `key` | string | Yes | Config key (e.g. `platform.api_key`). |
-| `value` | string | Yes | Value to set. |
-
-**Type coercion:** Boolean fields accept `true/1/yes` (case-insensitive) as true, anything else as false. Integer fields are parsed via `parseInt`. String fields are stored as-is.
-
-**Examples:**
-```bash
-mem0 config set defaults.user_id alice
-mem0 config set platform.base_url https://api.mem0.ai
-```
-
----
-
-### 3.12 `entity list`
-
-List all entities of a given type.
-
-| Property | Value |
-|------------------|-------|
-| Usage | `mem0 entity list ` |
-| needsBackend | Yes |
-| needsConfig | No |
-| resolveIds | No |
-| resolveGraph | No |
-| confirmDangerous | No |
-| Output formats | table, json |
-| Default output | table |
-| API endpoint | `GET /v1/entities/` |
-
-**Arguments:**
-
-| Name | Type | Required | Choices | Help |
-|---------------|--------|----------|--------------------------------|------|
-| `entity_type` | string | Yes | `users`, `agents`, `apps`, `runs` | Entity type to list. |
-
-**Behavior:** Calls `GET /v1/entities/` which returns ALL entity types, then filters client-side using the type map: `users` -> `user`, `agents` -> `agent`, `apps` -> `app`, `runs` -> `run`. Displays a table with "Name / ID" and "Created" columns.
-
-**Options:**
-
-| Flag | Type | Default | Panel | Help |
-|----------------|--------|---------|------------|------|
-| `-o, --output` | string | "table" | Output | Output: table, json. |
-| `--api-key` | string | - | Connection | Override API key. |
-| `--base-url` | string | - | Connection | Override API base URL. |
-
-**Examples:**
-```bash
-mem0 entity list users
-mem0 entity list agents -o json
-```
-
----
-
-### 3.13 `entity delete`
-
-Delete an entity and ALL its memories (cascade). Also accessible via `mem0 delete --entity`.
-
-| Property | Value |
-|------------------|-------|
-| Usage | `mem0 entity delete [OPTIONS]` |
-| needsBackend | Yes |
-| needsConfig | No |
-| resolveIds | No |
-| resolveGraph | No |
-| confirmDangerous | Yes |
-| Output formats | text, json, quiet |
-| Default output | text |
-| API endpoint | `DELETE /v1/entities/` |
-
-**Arguments:** None.
-
-**Options:**
-
-| Flag | Type | Default | Panel | Help |
-|-----------------|---------|---------|------------|------|
-| `-u, --user-id` | string | - | Scope | User ID. |
-| `--agent-id` | string | - | Scope | Agent ID. |
-| `--app-id` | string | - | Scope | App ID. |
-| `--run-id` | string | - | Scope | Run ID. |
-| `--dry-run` | boolean | false | - | Show what would be deleted without deleting. |
-| `--force` | boolean | false | - | Skip confirmation. |
-| `-o, --output` | string | "text" | Output | Output: text, json, quiet. |
-| `--api-key` | string | - | Connection | Override API key. |
-| `--base-url` | string | - | Connection | Override API base URL. |
-
-**Validation:** At least one entity ID is required. Errors if none provided.
-
-**Examples:**
-```bash
-mem0 entity delete --user-id alice --force
-mem0 entity delete --user-id alice --dry-run
-```
-
----
-
-### 3.14 `event list`
-
-List recent background processing events.
-
-| Property | Value |
-|------------------|-------|
-| Usage | `mem0 event list [OPTIONS]` |
-| needsBackend | Yes |
-| needsConfig | Yes |
-| resolveIds | No |
-| resolveGraph | No |
-| confirmDangerous | No |
-| Output formats | text (table), json |
-| Default output | table |
-| API endpoint | `GET /v1/events/` |
-
-**Options:**
-
-| Flag | Type | Default | Panel | Help |
-|----------------|--------|---------|------------|------|
-| `-o, --output` | string | "table" | Output | Output: text, json. |
-| `--api-key` | string | - | Connection | Override API key. |
-| `--base-url` | string | - | Connection | Override API base URL. |
-
-**Behavior:** Fetches all background events for the project. Displays as a table with columns: Event ID (first 8 chars), Type, Status (color-coded), Latency, Created. Status values: `PENDING` (accent), `SUCCEEDED` (green), `FAILED` (red), `PROCESSING` (yellow).
-
-**JSON output envelope:**
-```json
-{
- "status": "success",
- "command": "event list",
- "count": 3,
- "duration_ms": 87,
- "data": [
- { "id": "evt-abc", "event_type": "ADD", "status": "SUCCEEDED", "latency": 412.0, "created_at": "2026-01-01T10:00:00Z" }
- ]
-}
-```
-
-**Examples:**
-```bash
-mem0 event list
-mem0 event list --output json
-```
-
----
-
-### 3.15 `event status`
-
-Get the status and results of a specific background event.
-
-| Property | Value |
-|------------------|-------|
-| Usage | `mem0 event status [OPTIONS]` |
-| needsBackend | Yes |
-| needsConfig | Yes |
-| resolveIds | No |
-| resolveGraph | No |
-| confirmDangerous | No |
-| Output formats | text, json |
-| Default output | text |
-| API endpoint | `GET /v1/events/{event_id}/` |
-
-**Arguments:**
-
-| Name | Type | Required | Help |
-|------------|--------|----------|------|
-| `event_id` | string | Yes | Event ID to inspect. |
-
-**Options:**
-
-| Flag | Type | Default | Panel | Help |
-|----------------|--------|---------|------------|------|
-| `-o, --output` | string | "text" | Output | Output: text, json. |
-| `--api-key` | string | - | Connection | Override API key. |
-| `--base-url` | string | - | Connection | Override API base URL. |
-
-**Behavior:** Fetches the event by ID and displays: Event ID, Type, Status (color-coded), Latency, Created, Updated, and a numbered list of result memories (event type, memory text, user_id, truncated memory ID). Displayed in a boxed panel (text) or JSON envelope.
-
-**JSON output envelope:**
-```json
-{
- "status": "success",
- "command": "event status",
- "duration_ms": 65,
- "data": {
- "id": "evt-abc",
- "event_type": "ADD",
- "status": "SUCCEEDED",
- "latency": 412.0,
- "created_at": "2026-01-01T10:00:00Z",
- "updated_at": "2026-01-01T10:00:01Z",
- "results": [
- { "id": "mem-xyz", "event": "ADD", "user_id": "alice", "memory": "User prefers dark mode" }
- ]
- }
-}
-```
-
-**Examples:**
-```bash
-mem0 event status evt-abc-123
-mem0 event status evt-abc-123 --output json
-```
-
----
-
-### 3.16 `status`
-
-Check connectivity and authentication.
-
-| Property | Value |
-|------------------|-------|
-| Usage | `mem0 status [OPTIONS]` |
-| needsBackend | Yes |
-| needsConfig | Yes |
-| resolveIds | No |
-| resolveGraph | No |
-| confirmDangerous | No |
-
-**Options:**
-
-| Flag | Type | Default | Panel | Help |
-|----------------|--------|---------|------------|------|
-| `-o, --output` | string | "text" | Output | Output: text, json. |
-| `--api-key` | string | - | Connection | Override API key. |
-| `--base-url` | string | - | Connection | Override API base URL. |
-
-**Behavior:** Validates connectivity by calling `GET /v1/ping/`. Displays connection status in a boxed panel (text) or JSON envelope. The ping endpoint is lightweight and does not require any entity scope.
-
-**JSON output:**
-```json
-{
- "status": "success",
- "command": "status",
- "duration_ms": 112,
- "data": {
- "connected": true,
- "backend": "platform",
- "base_url": "https://api.mem0.ai"
- }
-}
-```
-
-**Examples:**
-```bash
-mem0 status
-mem0 status -o json
-```
-
----
-
-### 3.17 `help`
-
-Show help. Use `--json` for machine-readable output (for LLM agents).
-
-| Property | Value |
-|------------------|-------|
-| Usage | `mem0 help [OPTIONS]` |
-| needsBackend | No |
-| needsConfig | No |
-
-**Options:**
-
-| Flag | Type | Default | Help |
-|----------|---------|---------|------|
-| `--json` | boolean | false | Output machine-readable JSON for LLM agents. |
-
-**Behavior:**
-- Without `--json`: prints a human-readable summary of all commands.
-- With `--json`: Node outputs the entire `cli-spec.json` file. Python outputs a hand-built JSON object describing all commands, arguments, options, and global options.
-
-**Examples:**
-```bash
-mem0 help
-mem0 help --json
-```
-
----
-
-## 4. API Endpoints
-
-### Base URL
-
-Default: `https://api.mem0.ai` (configurable via `--base-url`, `MEM0_BASE_URL`, or `platform.base_url` in config).
-
-### Authentication
-
-All requests include the header:
-```
-Authorization: Token
-```
-
-The auth header name is `Authorization` and the scheme is `Token` (not Bearer).
-
-### Timeout
-
-30 seconds for all requests (Python: `httpx.Client(timeout=30.0)`, Node: `AbortSignal.timeout(30_000)`).
-
-### Endpoint Reference
-
-| Operation | Method | Path | Request Body | Query Params |
-|-----------------|----------|-------------------------------|------------------|-------------------------|
-| Add memory | `POST` | `/v1/memories/` | JSON payload | - |
-| Search | `POST` | `/v2/memories/search/` | JSON payload | - |
-| Get memory | `GET` | `/v1/memories/{memory_id}/` | - | - |
-| List memories | `POST` | `/v2/memories/` | JSON payload | `page`, `page_size` |
-| Update memory | `PUT` | `/v1/memories/{memory_id}/` | JSON payload | - |
-| Delete memory | `DELETE` | `/v1/memories/{memory_id}/` | - | - |
-| Delete all | `DELETE` | `/v1/memories/` | - | entity ID params |
-| List entities | `GET` | `/v1/entities/` | - | - |
-| Delete entities | `DELETE` | `/v1/entities/` | - | entity ID params |
-| List events | `GET` | `/v1/events/` | - | - |
-| Get event | `GET` | `/v1/events/{event_id}/` | - | - |
-| Ping (status) | `GET` | `/v1/ping/` | - | - |
-
-### How Filters Are Built (`_buildFilters` / `_build_filters`)
-
-Both CLIs use an identical filter-building algorithm:
-
-1. If the caller passed a pre-built filter structure containing `AND` or `OR` keys (e.g. from `--filter`), use it directly.
-2. Otherwise, build an array of AND conditions:
- - Each entity ID becomes `{"user_id": "..."}`, `{"agent_id": "..."}`, etc.
- - Extra filters (category, date ranges) are appended as additional conditions.
-3. If exactly 1 condition: return it directly (no wrapping).
-4. If 2+ conditions: return `{"AND": [condition1, condition2, ...]}`.
-5. If 0 conditions: return `undefined`/`None`.
-
-**Category filter format:** `{"categories": {"contains": ""}}`
-
-**Date filter format:** `{"created_at": {"gte": "YYYY-MM-DD"}}` and/or `{"created_at": {"lte": "YYYY-MM-DD"}}`. If both `after` and `before` are set, they merge into one `created_at` object: `{"created_at": {"gte": "...", "lte": "..."}}`.
-
-### How Pagination Works
-
-For the `list` command (and `search` internally):
-- `page` and `page_size` are sent as **query parameters** (not in the POST body).
-- Filters and `enable_graph` are sent in the **POST body**.
-- Default: `page=1`, `page_size=100`.
-
-### Response Normalization
-
-Both CLIs handle inconsistent API response formats:
-```
-# For search and list, the API may return:
-result = [...] # Direct array
-result = {"results": [...]} # Wrapped in results key
-result = {"memories": [...]} # Wrapped in memories key
-
-# Normalization logic (identical in both CLIs):
-if isinstance(result, list):
- return result
-else:
- return result.get("results", result.get("memories", []))
-```
-
-### Error Handling
-
-HTTP errors are mapped to typed exceptions:
-
-| HTTP Status | Error Class | Message Template |
-|-------------|----------------|-----------------|
-| 401 | `AuthError` | "Authentication failed. Your API key may be invalid or expired." |
-| 404 | `NotFoundError`| "Resource not found: {path}" |
-| 400 | `APIError` | "Bad request to {path}: {detail}" (detail extracted from response JSON `.detail` field) |
-| 204 | (success) | Returns `{}` (empty object) |
-| Other | Generic Error | "HTTP {status}: {statusText}" |
-
----
-
-## 5. Configuration
-
-### Config File Location
-
-- Directory: `~/.mem0/` (created with permissions `0700`)
-- File: `~/.mem0/config.json` (written with permissions `0600`)
-
-### Config Precedence (highest to lowest)
-
-1. **CLI flags** (`--api-key`, `--base-url`, `--user-id`, etc.)
-2. **Environment variables** (`MEM0_API_KEY`, etc.)
-3. **Config file** (`~/.mem0/config.json`)
-4. **Defaults** (hardcoded)
-
-### Environment Variables
-
-| Variable | Config Path | Type | Default |
-|--------------------|--------------------------|---------|-----------------------|
-| `MEM0_API_KEY` | `platform.api_key` | string | `""` |
-| `MEM0_BASE_URL` | `platform.base_url` | string | `"https://api.mem0.ai"` |
-| `MEM0_USER_ID` | `defaults.user_id` | string | `""` |
-| `MEM0_AGENT_ID` | `defaults.agent_id` | string | `""` |
-| `MEM0_APP_ID` | `defaults.app_id` | string | `""` |
-| `MEM0_RUN_ID` | `defaults.run_id` | string | `""` |
-| `MEM0_ENABLE_GRAPH`| `defaults.enable_graph` | boolean | `false` |
-
-**Boolean parsing for `MEM0_ENABLE_GRAPH`:** Accepted truthy values are `"true"`, `"1"`, `"yes"` (case-insensitive). Everything else is `false`.
-
-### Config File JSON Schema
-
-```json
-{
- "version": 1,
- "defaults": {
- "user_id": "",
- "agent_id": "",
- "app_id": "",
- "run_id": "",
- "enable_graph": false
- },
- "platform": {
- "api_key": "",
- "base_url": "https://api.mem0.ai"
- }
-}
-```
-
-| Field | Type | Default | Description |
-|--------------------------|---------|--------------------------|-------------|
-| `version` | integer | `1` | Config schema version. |
-| `defaults.user_id` | string | `""` | Default user ID for scoping. |
-| `defaults.agent_id` | string | `""` | Default agent ID for scoping. |
-| `defaults.app_id` | string | `""` | Default app ID for scoping. |
-| `defaults.run_id` | string | `""` | Default run ID for scoping. |
-| `defaults.enable_graph` | boolean | `false` | Default graph memory extraction. |
-| `platform.api_key` | string | `""` | API key for mem0 Platform. |
-| `platform.base_url` | string | `"https://api.mem0.ai"` | Base URL for API requests. |
-
-### Config Key Map (for `config get`/`config set`)
-
-The dotted key paths map to internal config objects as follows:
-
-| Dotted Key | Section | Field |
-|-------------------------|------------|--------------|
-| `platform.api_key` | platform | apiKey / api_key |
-| `platform.base_url` | platform | baseUrl / base_url |
-| `defaults.user_id` | defaults | userId / user_id |
-| `defaults.agent_id` | defaults | agentId / agent_id |
-| `defaults.app_id` | defaults | appId / app_id |
-| `defaults.run_id` | defaults | runId / run_id |
-| `defaults.enable_graph` | defaults | enableGraph / enable_graph |
-
-### API Key Redaction
-
-The `redact_key`/`redactKey` function:
-- Empty string: returns `"(not set)"`
-- Length <= 8: returns first 2 chars + `"***"`
-- Length > 8: returns first 4 chars + `"..."` + last 4 chars
-
----
-
-## 6. Key Behavioral Patterns
-
-These patterns are the **contract** both CLIs must follow. Any new implementation must replicate them exactly.
-
-### 6.1 Entity ID Resolution
-
-**Function:** `_resolve_ids` (Python) / `resolveIds` (Node)
-
-**Rule:** If **any** explicit entity ID is provided via CLI flags, only use the explicitly provided IDs. Do NOT mix in defaults for other entity types (which would over-filter). If **no** explicit IDs are provided, fall back to **all** configured defaults.
-
-```
-if any(user_id, agent_id, app_id, run_id):
- # Only use what was explicitly passed; others become None
- return {user_id or None, agent_id or None, app_id or None, run_id or None}
-else:
- # Fall back to all configured defaults
- return {config.user_id or None, config.agent_id or None, ...}
-```
-
-**Rationale:** If a user passes `--user-id alice` and the config also has `agent_id=bot1`, they probably want only Alice's memories, not the intersection of Alice AND bot1.
-
-### 6.2 Graph Tri-State Resolution
-
-**Rule:** `--no-graph` > `--graph` > config default.
-
-```
-if opts.no_graph: return false
-if opts.graph: return true
-return config.defaults.enable_graph
-```
-
-This is resolved in the main app file (not in the command handlers) before calling the command function.
-
-### 6.3 Category Parsing
-
-**Rule:** Try JSON parse first, fallback to comma-split.
-
-```
-if categories:
- try:
- cats = JSON.parse(categories) # e.g. '["a","b"]'
- except:
- cats = categories.split(",").map(s => s.trim()) # e.g. "a, b"
-```
-
-### 6.4 Stdin Detection
-
-**Rule:** Read from stdin if no text argument is provided AND stdin is piped (not a TTY).
-
-- `add`: If no `text`, no `--messages`, no `--file`, and stdin is piped -> read content from stdin.
-- `search`: If no `query` argument and stdin is piped -> read query from stdin.
-- `update`: If no `text` argument and no `--metadata` and stdin is piped -> read text from stdin.
-
-Detection method:
-- Python: `not sys.stdin.isatty()`
-- Node: `!process.stdin.isTTY`
-
-Reading method:
-- Python: `sys.stdin.read().strip()`
-- Node: `fs.readFileSync(0, "utf-8").trim()`
-
-### 6.5 Filter Building (`_buildFilters`)
-
-Detailed algorithm (see Section 4 for full description):
-
-1. If `extraFilters` has `AND` or `OR` key -> return it as-is (pre-built filter).
-2. Collect AND conditions from entity IDs.
-3. Append extra filters (category, date ranges).
-4. 0 conditions -> `undefined`/`None`.
-5. 1 condition -> return that single object.
-6. 2+ conditions -> `{"AND": [...]}`.
-
-### 6.6 API Response Normalization
-
-All `search` and `listMemories`/`list_memories` calls normalize the response:
-
-```
-if Array.isArray(result): return result
-return result.results ?? result.memories ?? []
-```
-
-This handles both direct array responses and wrapped `{results: [...]}` or `{memories: [...]}` formats.
-
-### 6.7 Config File Permissions
-
-- Config directory (`~/.mem0/`): created with mode `0o700` (owner read+write+execute only).
-- Config file (`~/.mem0/config.json`): written with mode `0o600` (owner read+write only).
-- Python uses `os.chmod()` with `stat.S_IRWXU` (dir) and `stat.S_IRUSR | stat.S_IWUSR` (file).
-- Node uses `fs.mkdirSync(..., { mode: 0o700 })` and `fs.chmodSync(file, 0o600)`.
-
-### 6.8 Timed Status Pattern
-
-Every API call is wrapped in a spinner + timing pattern:
-
-**Python:**
-```python
-with timed_status(err_console, "Adding memory...") as ts:
- result = backend.add(...)
-```
-Uses Rich `Status` context manager on stderr. On success, prints `ts.success_msg` with elapsed time. On error, prints `ts.error_msg` with elapsed time.
-
-**Node:**
-```typescript
-result = await timedStatus("Adding memory...", async (ctx) => {
- return backend.add(...);
-});
-```
-Uses `ora` spinner on stderr. On success, prints `ctx.successMsg` with elapsed time. On error, prints `ctx.errorMsg` with elapsed time.
-
-Both use `performance.now()` / `time.perf_counter()` for timing. Elapsed time is formatted as `{seconds:.2f}s`.
-
-**Key:** Spinners and timing messages always go to **stderr** so they never contaminate machine-readable stdout.
-
-### 6.9 Error Hierarchy
-
-```
-AuthError (HTTP 401) -> "Authentication failed. Your API key may be invalid or expired."
-NotFoundError (HTTP 404) -> "Resource not found: {path}"
-APIError (HTTP 400) -> "Bad request to {path}: {detail}"
-```
-
-For HTTP 400, the CLI attempts to extract a `detail` field from the JSON response body. If parsing fails, falls back to `resp.statusText`/`resp.text`.
-
-HTTP 204 is treated as success with empty body (`{}`).
-
-Any other non-OK response throws a generic error with `"HTTP {status}: {statusText}"`.
-
-### 6.10 `delete --all --project` Wildcard Behavior
-
-When `delete --all --project` is used, the CLI sends wildcard entity IDs (`user_id=*`, `agent_id=*`, `app_id=*`, `run_id=*`) to `DELETE /v1/memories/`. The API typically returns an **asynchronous response** with a `message` field (the deletion happens in the background). The CLI detects the `message` key in the response and prints "Deletion started. Memories will be removed in the background." instead of a success count.
-
-### 6.11 Non-Interactive Init
-
-When both `--api-key` and `--user-id` are provided to `mem0 init`:
-1. Sets config values directly (no prompts).
-2. Validates the platform connection.
-3. Saves config to disk.
-4. Prints success message.
-
-When running in a non-TTY (piped input) without both flags, prints an error with usage hint:
-```
-"Non-interactive terminal detected and missing required flags."
-"Usage: mem0 init --api-key --user-id "
-```
-
-### 6.12 Add Result Event Display
-
-The `format_add_result` function handles the API response from `POST /v1/memories/`:
-
-The response is either a direct array or `{results: [...]}`. Each result item has an `event` field:
-
-| Event | Icon | Label |
-|----------|------|------------|
-| `ADD` | `+` | Added |
-| `UPDATE` | `~` | Updated |
-| `DELETE` | `-` | Deleted |
-| `NOOP` | `.` | No change |
-| `PENDING`| hourglass | Queued (async) |
-
-For `PENDING` events, displays "Processing in background" with the event ID.
-
----
-
-## 7. Output Modes
-
-### 7.1 Supported Modes Per Command
-
-All commands also support `agent` mode via the global `--json`/`--agent` flag, which wraps output in a structured JSON envelope with sanitized fields.
-
-| Command | text | json | table | quiet |
-|----------------|------|------|-------|-------|
-| add | Y | Y | - | Y |
-| search | Y | Y | Y | - |
-| get | Y | Y | - | - |
-| list | Y | Y | Y (default) | - |
-| update | Y | Y | - | Y |
-| delete | Y | Y | - | Y |
-| import | Y | Y | - | - |
-| config show | Y | Y | - | - |
-| config get | (raw value) | - | - | - |
-| config set | (success msg) | - | - | - |
-| entity list | - | Y | Y (default) | - |
-| entity delete | Y | Y | - | Y |
-| event list | Y (table) | Y | - | - |
-| event status | Y | Y | - | - |
-| status | Y | Y | - | - |
-| help | Y | Y (--json) | - | - |
-
-### 7.2 JSON Envelope Format
-
-There are two related envelope formats:
-
-**`formatJsonEnvelope`** — used by `config show`, `status`, and `import` for `--output json`:
-
-```json
-{
- "status": "success",
- "command": "",
- "duration_ms": 245,
- "scope": {"user_id": "alice", "agent_id": null},
- "count": 10,
- "error": null,
- "data": { ... }
-}
-```
-
-**`formatAgentEnvelope`** — used by all commands in agent mode (`--json`/`--agent`). Same structure, but `data` is passed through `sanitizeAgentData(command, data)` to project only the most relevant fields:
-
-| Command | Fields in `data` |
-|---------------|-----------------|
-| add | `[{id, memory, event}]` or `[{status, event_id}]` for PENDING |
-| search | `[{id, memory, score, created_at, categories}]` |
-| list | `[{id, memory, created_at, categories}]` |
-| get | `{id, memory, created_at, updated_at, categories, metadata}` |
-| update | `{id, memory}` |
-| delete | (raw API response) |
-| entity list | `[{name, type, count}]` |
-| event list | `[{id, event_type, status, latency, created_at}]` |
-| event status | `{id, event_type, status, latency, created_at, updated_at, results: [{id, event, user_id, memory}]}` |
-| status/config/import | (pass-through) |
-
-Error envelopes (on non-zero exit):
-```json
-{
- "status": "error",
- "command": "",
- "error": "Authentication failed. Your API key may be invalid or expired.",
- "data": null
-}
-```
-
-Fields:
-- `status`: `"success"` or `"error"`.
-- `command`: The command name.
-- `duration_ms`: Optional, elapsed time in milliseconds.
-- `scope`: Optional, active entity scope (omitted if empty).
-- `count`: Optional, result count.
-- `error`: Only present when `status` is `"error"`.
-- `data`: The primary payload (sanitized in agent mode).
-
-### 7.3 Text Output
-
-- `formatMemoriesText`: Numbered list with memory text, score, ID (first 8 chars), created date, and category, separated by ` . ` in dim color.
-- `formatSingleMemory`: Boxed panel (boxen/Rich Panel) showing memory text, ID, created date, updated date, metadata, and categories.
-- `formatAddResult`: Event-based output with icons (+, ~, -, .) and labels.
-
-### 7.4 Table Output
-
-Uses `cli-table3` (Node) or `rich.table.Table` (Python) with columns:
-- ID (first 8 chars, dim)
-- Memory (truncated to 60 chars with "...")
-- Category (first category from array)
-- Created (YYYY-MM-DD)
-
-### 7.5 Quiet Mode
-
-Commands that support `--output quiet` (`add`, `update`, `delete`, `entity delete`) produce **no stdout output** in quiet mode. The operation still executes. Exit code indicates success/failure.
-
-### 7.6 Error Output
-
-- **Errors always go to stderr.** Both CLIs use a separate stderr console:
- - Python: `Console(stderr=True)` for `print_error` calls.
- - Node: `console.error()` in `printError`, spinner on `process.stderr` stream.
-- **Data always goes to stdout.** JSON output, table output, and text output all go to stdout.
-
-### 7.7 Unicode Symbol Degradation
-
-The `_sym`/`sym` function selects symbols based on terminal capability:
-
-| Condition | Fancy Symbol | Plain Fallback |
-|----------------------------------------|-------------|----------------|
-| `!stdout.isTTY` or `NO_COLOR` env set | - | Used |
-| Interactive TTY with color | Used | - |
-
-| Symbol | Fancy | Plain |
-|----------|-------|-----------|
-| Success | `checkmark` | `[ok]` |
-| Error | `X` | `[error]` |
-| Warning | `warning triangle` | `[warn]` |
-| Info | `diamond` | `*` |
-
-### 7.8 Result Summary Footer
-
-After list/search results, a summary line is printed in dim:
-```
- 10 results . page 1 . user id=alice . 0.45s
-```
-
-Format: `{count} result(s) . page {n} . {scope} . {elapsed}s`
-
-### 7.9 Date Formatting
-
-All dates are normalized to `YYYY-MM-DD` format for display. The formatting handles ISO 8601 strings with `Z` timezone suffix by replacing it with `+00:00` before parsing.
-
----
-
-## 8. Agent-Friendly Design Decisions
-
-### Why `--dry-run` exists on destructive commands
-
-The `delete` command (all modes) and `entity delete` support `--dry-run`. This lets AI agents preview the effect of a destructive operation before committing. For `delete `, it fetches the memory and displays it. For `delete --all`, it lists matching memories and shows the count. For `delete --entity` / `entity delete`, it shows the scope that would be affected.
-
-### Why `--force` exists
-
-Destructive commands (`delete --all`, `delete --entity`, `entity delete`) require interactive confirmation by default. The `--force` flag skips this confirmation, which is essential for:
-- AI agents (non-interactive)
-- CI/CD pipelines
-- Scripting
-
-### Why `--json`/`--agent` global flags exist
-
-The `--json` and `--agent` flags (aliases of each other) activate agent mode globally. When set:
-1. All output becomes a structured JSON envelope (`{status, command, duration_ms, scope, count, data}`).
-2. The `data` field is sanitized via `sanitizeAgentData` — only the most relevant fields are included per command, reducing noise for agents parsing the output.
-3. All human-readable output (spinners, colors, banners, timing lines) is suppressed.
-4. Errors are emitted as JSON to stdout with a non-zero exit code, not to stderr as text.
-
-This is distinct from `--output json`, which returns the raw API response without sanitization.
-
-### Why `--output json` is on every command
-
-Every data-returning command supports `--output json` (or `--json` for `help`). This enables machine consumption by AI agents and scripts. JSON output goes to stdout while human-readable spinners/timing go to stderr, so piping `mem0 list -o json | jq .` works cleanly.
-
-### Why stdin is supported
-
-Commands `add`, `search`, and `update` can read from stdin when piped. This enables composability:
-```bash
-echo "I prefer dark mode" | mem0 add -u alice
-cat query.txt | mem0 search -u alice
-echo "updated text" | mem0 update abc-123
-```
-
-### Why `help --json` exists
-
-The `help --json` command outputs the complete CLI specification in machine-readable JSON. AI agents can call this once to discover all available commands, their arguments, options, and valid values -- enabling self-documenting tool use.
-
-### Why errors go to stderr
-
-All error messages, warnings, spinners, and timing information go to stderr. This means `--output json` produces **only** valid JSON on stdout, with no interleaved human-readable messages. An AI agent can safely parse stdout as JSON.
-
----
-
-## 9. Adding a New Command
-
-Step-by-step guide for adding a new command to both CLIs.
-
-### Step 1: Add to `cli-spec.json`
-
-Add a new entry to the `commands` array with all required fields:
-
-```json
-{
- "name": "my-command",
- "description": "What this command does.",
- "usage": "mem0 my-command [OPTIONS]",
- "needsBackend": true,
- "needsConfig": true,
- "resolveIds": true,
- "resolveGraph": false,
- "confirmDangerous": false,
- "outputFormats": ["text", "json"],
- "defaultOutput": "text",
- "arguments": [
- {
- "name": "arg",
- "type": "string",
- "required": true,
- "help": "Argument description."
- }
- ],
- "options": [
- {
- "name": "user_id",
- "flags": ["--user-id", "-u"],
- "type": "string",
- "help": "Scope to user.",
- "panel": "Scope"
- },
- {
- "name": "output",
- "flags": ["--output", "-o"],
- "type": "string",
- "default": "text",
- "help": "Output format.",
- "panel": "Output"
- }
- ],
- "apiEndpoint": "myEndpoint"
-}
-```
-
-If the command calls a new API endpoint, also add it to `api.endpoints`.
-
-### Step 2: Add Backend Method (if new API endpoint)
-
-**Python** (`python/src/mem0_cli/backend/base.py` and `platform.py`):
-1. Add abstract method to `Backend` ABC in `base.py`.
-2. Implement in `PlatformBackend` in `platform.py`.
-
-**Node** (`node/src/backend/base.ts` and `platform.ts`):
-1. Add method signature to `Backend` interface in `base.ts`.
-2. Implement in `PlatformBackend` class in `platform.ts`.
-
-### Step 3: Add Command Handler
-
-**Python** (`python/src/mem0_cli/commands/`):
-Create a function `cmd_my_command(backend, ...)` in the appropriate commands file. Follow the patterns:
-- Use `timed_status(err_console, "...")` for API calls.
-- Use `print_error(err_console, ...)` for errors.
-- Use `format_json(console, ...)` for JSON output.
-- Raise `typer.Exit(1)` on errors.
-
-**Node** (`node/src/commands/`):
-Create an async function `cmdMyCommand(backend, ...)`. Follow the patterns:
-- Use `await timedStatus("...", async () => { ... })` for API calls.
-- Use `printError(...)` for errors.
-- Use `formatJson(...)` for JSON output.
-- Call `process.exit(1)` on errors.
-
-### Step 4: Register in App Entrypoint
-
-**Python** (`python/src/mem0_cli/app.py`):
-```python
-@app.command(name="my-command")
-def my_command(
- arg: str = typer.Argument(..., help="..."),
- output: str = typer.Option("text", "--output", "-o", help="...", rich_help_panel="Output"),
- api_key: str | None = typer.Option(None, "--api-key", help="...", rich_help_panel="Connection"),
- base_url: str | None = typer.Option(None, "--base-url", help="...", rich_help_panel="Connection"),
-) -> None:
- """Command description."""
- from mem0_cli.commands.my_module import cmd_my_command
- backend, config = _get_backend_and_config(api_key, base_url)
- ids = _resolve_ids(config, ...)
- cmd_my_command(backend, arg, **ids, output=output)
-```
-
-**Node** (`node/src/index.ts`):
-```typescript
-program
- .command("my-command ")
- .description("Command description.")
- .option("-o, --output ", "Output format.", "text")
- .option("--api-key ", "Override API key.")
- .option("--base-url ", "Override API base URL.")
- .action(async (arg, opts) => {
- const { cmdMyCommand } = await import("./commands/my-module.js");
- const { backend, config } = getBackendAndConfig(opts.apiKey, opts.baseUrl);
- const ids = resolveIds(config, opts);
- await cmdMyCommand(backend, arg, { ...ids, output: opts.output });
- });
-```
-
-### Step 5: Add Help Examples
-
-Both CLIs include examples in the help text:
-- Python: In the docstring of the Typer command function.
-- Node: Via `.addHelpText("after", "\nExamples:\n $ mem0 ...")`.
-
-### Step 6: Add to Help Display and Command Order
-
-**Node** (`node/src/help.ts`):
-1. Add `"my-command"` to `COMMAND_ORDER` array (determines display order in `--help`).
-2. Add option-to-panel mappings in `OPTION_PANELS["my-command"]`.
-
-**Python**: Options are assigned to panels via `rich_help_panel="..."` on each `typer.Option()`. The `help` command's `_build_help_json()` function needs a new entry.
-
-### Step 7: Add to `help` Command Output
-
-**Python** (`python/src/mem0_cli/app.py`):
-1. Add entry in `_build_help_json()` dict.
-2. Add line in the `help` command's human-readable output.
-
-**Node** (`node/src/index.ts`):
-Add line in the `help` command's human-readable output listing.
-
-### Step 8: Add Tests
-
-- Python: Add tests in `python/tests/`.
-- Node: Add tests in `node/src/__tests__/` or similar.
-
-### Step 9: Update This Specification
-
-Add the command to the Complete Command Reference (Section 3) with all arguments, options, behavior notes, and examples.
-
----
-
-## 10. Adding a New Language Implementation
-
-To add a new language implementation (e.g., Go, Rust, Ruby), you need to replicate the exact behavioral contract defined in `cli-spec.json` and this document. Here is what is required:
-
-### 10.1 Core Modules to Implement
-
-| Module | Purpose |
-|---------------|---------|
-| **config** | Load `~/.mem0/config.json`, apply env var overrides, enforce precedence. Implement `load_config`, `save_config`, `ensure_config_dir`, `redact_key`, `get_nested_value`, `set_nested_value`. |
-| **backend/base** | Define the `Backend` interface/trait with all 8 methods: `add`, `search`, `get`, `list_memories`, `update`, `delete`, `delete_entities`, `status`, `entities`. Define error types: `AuthError`, `NotFoundError`, `APIError`. |
-| **backend/platform** | Implement `PlatformBackend` with HTTP client. Must implement `_build_filters` logic exactly. Must handle response normalization. Must set `Authorization: Token ` header. 30s timeout. |
-| **branding** | Implement print helpers (`print_success`, `print_error`, `print_warning`, `print_info`, `print_scope`), `print_banner`, `timed_status` pattern, `sym` function for Unicode degradation. Colors must match the hex values in `cli-spec.json`. |
-| **output** | Implement `format_memories_text`, `format_memories_table`, `format_single_memory`, `format_add_result`, `format_json`, `format_json_envelope`, `print_result_summary`. Date formatting to YYYY-MM-DD. ID truncation to 8 chars. Memory text truncation to 60 chars in tables. |
-| **commands/** | Implement all command handlers matching the exact behavior described in Section 3. |
-| **app/main** | CLI entrypoint with all commands registered. Implement `resolve_ids`, `resolve_graph`, stdin detection, and the `getBackendAndConfig` helper. |
-| **help** | Implement help formatter with grouped option panels (Scope, Search, Pagination, Filters, Output, Connection). Implement `help --json` output. |
-
-### 10.2 Behavioral Checklist
-
-Every new implementation MUST:
-
-- [ ] Read and respect `cli-spec.json` for all command names, descriptions, argument names, option flags, and defaults
-- [ ] Implement config precedence: CLI flags > env vars > config file > defaults
-- [ ] Implement entity ID resolution (explicit IDs only vs. all defaults)
-- [ ] Implement graph tri-state (`--no-graph` > `--graph` > config default)
-- [ ] Implement category parsing (JSON first, comma-split fallback)
-- [ ] Implement stdin detection and reading for `add`, `search`, `update`
-- [ ] Implement `_build_filters` with AND/OR structure
-- [ ] Implement response normalization (array vs `{results}` vs `{memories}`)
-- [ ] Set config directory permissions to 0700 and file to 0600
-- [ ] Implement timed status with spinner on stderr + elapsed time
-- [ ] Implement error hierarchy (AuthError 401, NotFoundError 404, APIError 400)
-- [ ] Implement `delete --all --project` with wildcard `*` entity IDs and async response handling
-- [ ] Implement non-interactive `init` when both `--api-key` and `--user-id` provided
-- [ ] Implement `--dry-run` on delete (all modes) and entity delete
-- [ ] Implement `--force` on delete --all, delete --entity, and entity delete
-- [ ] Send errors to stderr, data to stdout
-- [ ] Implement Unicode symbol degradation for non-TTY/NO_COLOR
-- [ ] Implement JSON envelope format for status, config show, import
-- [ ] Support `--output` on all data-returning commands
-- [ ] Implement `help --json` for machine-readable command discovery
-- [ ] Implement masked API key input during `init` (echo `*` per character)
-- [ ] Implement confirmation prompts for dangerous commands (unless `--force`)
-- [ ] Binary must be named `mem0`
-
-### 10.3 Package Metadata
-
-Follow the naming conventions:
-- Package description: "The official CLI for mem0 -- the memory layer for AI agents"
-- Author: `mem0.ai `
-- License: Apache-2.0
-- Keywords: `mem0`, `memory`, `ai`, `agents`, `cli`
-
-### 10.4 Testing
-
-Conformance tests should verify:
-- All commands from `cli-spec.json` are registered
-- All options from `cli-spec.json` are accepted
-- Config precedence is correct
-- Entity ID resolution matches the spec
-- Filter building produces correct structures
-- Output modes produce expected formats
-- Error codes are mapped correctly
-- Stdin reading works for supported commands
From f8082a7345dadd9e042ebbc40b57b1498c8f6d63 Mon Sep 17 00:00:00 2001
From: "mintlify[bot]" <109931778+mintlify[bot]@users.noreply.github.com>
Date: Tue, 22 Sep 2026 20:06:21 +0530
Subject: [PATCH 20/54] Fix grammar & typos: API casing in template heading
(#7410)
Co-authored-by: mintlify[bot] <109931778+mintlify[bot]@users.noreply.github.com>
---
docs/templates/api_reference_template.mdx | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
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.
From 8c02c425a53ea31bd0d493bbcf0ab22c1be3609d Mon Sep 17 00:00:00 2001
From: Kartik
Date: Wed, 23 Sep 2026 19:35:25 +0530
Subject: [PATCH 21/54] fix(agent-plugins): match memo prompts and tool
descriptions, release 0.3.3 (#7420)
Co-authored-by: Claude
---
.claude-plugin/marketplace.json | 2 +-
.cursor-plugin/marketplace.json | 2 +-
.kimi-plugin/marketplace.json | 2 +-
docs/changelog/sdk.mdx | 84 +++++++++++++++++++
integrations/agent-plugin-core/README.md | 4 +-
.../agent-plugin-core/python/mcp_server.py | 13 +--
.../agent-plugin-core/python/memory_core.py | 10 +--
.../skills/search/SKILL.md.tmpl | 8 +-
.../typescript/src/lifecycle.ts | 7 +-
.../typescript/src/prompts.ts | 10 +++
.../typescript/tests/prompts.test.ts | 31 +++++++
.../antigravity-plugin/core/mcp_server.py | 13 +--
.../antigravity-plugin/core/memory_core.py | 10 +--
.../antigravity-plugin/plugin-build.json | 2 +-
.../antigravity-plugin/skills/search/SKILL.md | 8 +-
.../.claude-plugin/plugin.json | 2 +-
.../claude-code-plugin/agents/sidekick.md | 7 +-
.../claude-code-plugin/core/mcp_server.py | 13 +--
.../claude-code-plugin/core/memory_core.py | 10 +--
.../claude-code-plugin/plugin-build.json | 2 +-
.../claude-code-plugin/skills/search/SKILL.md | 8 +-
.../tests/test_memory_core.py | 8 +-
.../codex-plugin/.codex-plugin/plugin.json | 2 +-
integrations/codex-plugin/core/mcp_server.py | 13 +--
integrations/codex-plugin/core/memory_core.py | 10 +--
integrations/codex-plugin/plugin-build.json | 2 +-
.../codex-plugin/skills/search/SKILL.md | 8 +-
.../cursor-plugin/.cursor-plugin/plugin.json | 2 +-
integrations/cursor-plugin/core/mcp_server.py | 13 +--
.../cursor-plugin/core/memory_core.py | 10 +--
integrations/cursor-plugin/plugin-build.json | 2 +-
.../cursor-plugin/skills/search/SKILL.md | 8 +-
integrations/deepseek-plugin/package.json | 2 +-
integrations/deepseek-plugin/src/index.ts | 12 ++-
integrations/kimi-plugin/core/mcp_server.py | 13 +--
integrations/kimi-plugin/core/memory_core.py | 10 +--
integrations/kimi-plugin/kimi.plugin.json | 2 +-
integrations/kimi-plugin/plugin-build.json | 2 +-
.../kimi-plugin/skills/search/SKILL.md | 8 +-
.../mem0-agent-plugin/core/mcp_server.py | 13 +--
.../mem0-agent-plugin/core/memory_core.py | 10 +--
integrations/mem0-agent-plugin/plugin.json | 2 +-
.../mem0-agent-plugin/skills/search/SKILL.md | 8 +-
integrations/openclaw/openclaw.plugin.json | 2 +-
integrations/openclaw/package.json | 2 +-
integrations/openclaw/tools/memory-search.ts | 5 +-
integrations/opencode-plugin/opencode-mem0.ts | 11 +--
.../mem0-context-loader/SKILL.md | 24 +-----
.../opencode-skills/mem0-search/SKILL.md | 7 +-
integrations/opencode-plugin/package.json | 2 +-
integrations/pi-agent-plugin/README.md | 2 +-
integrations/pi-agent-plugin/package.json | 2 +-
.../skills/context-loader/SKILL.md | 23 +----
.../pi-agent-plugin/src/memory/tools.ts | 10 +--
integrations/pi-agent-plugin/src/prompt.ts | 11 ++-
marketplace.json | 2 +-
56 files changed, 262 insertions(+), 249 deletions(-)
create mode 100644 integrations/agent-plugin-core/typescript/src/prompts.ts
create mode 100644 integrations/agent-plugin-core/typescript/tests/prompts.test.ts
diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json
index ccaa4dcea..752311cbc 100644
--- a/.claude-plugin/marketplace.json
+++ b/.claude-plugin/marketplace.json
@@ -12,7 +12,7 @@
"name": "mem0",
"source": "./integrations/claude-code-plugin",
"description": "Cross-session memory and token savings for coding agents.",
- "version": "0.3.2"
+ "version": "0.3.3"
}
]
}
diff --git a/.cursor-plugin/marketplace.json b/.cursor-plugin/marketplace.json
index 84f31855b..4d083a06b 100644
--- a/.cursor-plugin/marketplace.json
+++ b/.cursor-plugin/marketplace.json
@@ -12,7 +12,7 @@
"name": "mem0",
"source": "./integrations/cursor-plugin",
"description": "Cross-session memory and token savings for coding agents.",
- "version": "0.3.2"
+ "version": "0.3.3"
}
]
}
diff --git a/.kimi-plugin/marketplace.json b/.kimi-plugin/marketplace.json
index 0b8cbcac0..47c986c6c 100644
--- a/.kimi-plugin/marketplace.json
+++ b/.kimi-plugin/marketplace.json
@@ -5,7 +5,7 @@
{
"id": "mem0",
"displayName": "Mem0",
- "version": "0.3.2",
+ "version": "0.3.3",
"description": "Cross-session memory and token savings for coding agents.",
"homepage": "https://mem0.ai",
"keywords": ["memory", "personalization", "mcp", "semantic-search"],
diff --git a/docs/changelog/sdk.mdx b/docs/changelog/sdk.mdx
index 5562fbe1d..008e58b9f 100644
--- a/docs/changelog/sdk.mdx
+++ b/docs/changelog/sdk.mdx
@@ -2394,6 +2394,17 @@ Initial release of the Mem0 plugin for Claude Code and Cursor, followed by Codex
+
+
+**Improvements:**
+- **Search:** The `search_memories` tool description no longer tells the agent to call it before answering anything that could depend on prior context. It now asks for a search before repeating investigation or when earlier decisions, fixes, commands, or results may help, which reduces unnecessary searches ([#7420](https://github.com/mem0ai/mem0/pull/7420))
+- **Sidekick:** Sidekick searches memories when earlier sessions could help, instead of before every answer ([#7420](https://github.com/mem0ai/mem0/pull/7420))
+- **Extraction:** Repository memory instructions are shorter. They no longer ask for a dedicated memory for each command that failed and was then fixed, and no longer carry separate rules against saving personal preferences or memories that only name the repository, branch, or directory ([#7420](https://github.com/mem0ai/mem0/pull/7420))
+- **Search skill:** `/search` no longer describes categories as best-effort labels or asks for a retry without the category ([#7420](https://github.com/mem0ai/mem0/pull/7420))
+- **Packaging:** `PLUGIN_VERSION` bumped to `0.3.3`, so the `mem0-plugin/` wire header and `plugin_version` telemetry field identify builds with these prompts ([#7420](https://github.com/mem0ai/mem0/pull/7420))
+
+
+
**Improvements:**
@@ -2424,6 +2435,16 @@ Initial release of the Mem0 plugin for Claude Code and Cursor, followed by Codex
+
+
+**Improvements:**
+- **Search:** The `search_memories` tool description no longer tells the agent to call it before answering anything that could depend on prior context. It now asks for a search before repeating investigation or when earlier decisions, fixes, commands, or results may help, which reduces unnecessary searches ([#7420](https://github.com/mem0ai/mem0/pull/7420))
+- **Extraction:** Repository memory instructions are shorter. They no longer ask for a dedicated memory for each command that failed and was then fixed, and no longer carry separate rules against saving personal preferences or memories that only name the repository, branch, or directory ([#7420](https://github.com/mem0ai/mem0/pull/7420))
+- **Search skill:** `/search` no longer describes categories as best-effort labels or asks for a retry without the category ([#7420](https://github.com/mem0ai/mem0/pull/7420))
+- **Packaging:** `PLUGIN_VERSION` bumped to `0.3.3`, so the `mem0-plugin/` wire header and `plugin_version` telemetry field identify builds with these prompts ([#7420](https://github.com/mem0ai/mem0/pull/7420))
+
+
+
**Improvements:**
@@ -2454,6 +2475,16 @@ Initial release of the Mem0 plugin for Claude Code and Cursor, followed by Codex
+
+
+**Improvements:**
+- **Search:** The `search_memories` tool description no longer tells the agent to call it before answering anything that could depend on prior context. It now asks for a search before repeating investigation or when earlier decisions, fixes, commands, or results may help, which reduces unnecessary searches ([#7420](https://github.com/mem0ai/mem0/pull/7420))
+- **Extraction:** Repository memory instructions are shorter. They no longer ask for a dedicated memory for each command that failed and was then fixed, and no longer carry separate rules against saving personal preferences or memories that only name the repository, branch, or directory ([#7420](https://github.com/mem0ai/mem0/pull/7420))
+- **Search skill:** `/search` no longer describes categories as best-effort labels or asks for a retry without the category ([#7420](https://github.com/mem0ai/mem0/pull/7420))
+- **Packaging:** `PLUGIN_VERSION` bumped to `0.3.3`, so the `mem0-plugin/` wire header and `plugin_version` telemetry field identify builds with these prompts ([#7420](https://github.com/mem0ai/mem0/pull/7420))
+
+
+
**Improvements:**
@@ -2483,6 +2514,15 @@ Initial release of the Mem0 plugin for Claude Code and Cursor, followed by Codex
+
+
+**Improvements:**
+- **Search:** The `search_memories` tool description no longer asks the agent to search proactively or to run several searches for multi-part questions. It now asks for a search before repeating investigation or when earlier decisions, fixes, commands, or results may help, the same wording as the other coding-agent plugins ([#7420](https://github.com/mem0ai/mem0/pull/7420))
+- **Session context:** Removed two system-context lines that told the agent to run 2 parallel searches before responding and 2-4 parallel searches for non-trivial tasks ([#7420](https://github.com/mem0ai/mem0/pull/7420))
+- **Skills:** `/mem0-search` and `/mem0-context-loader` make one `search_memories` call instead of 2 and 2-4 parallel calls. `/mem0-context-loader` now uses the search skill description from the other coding-agent plugins instead of asking to load at every new task or context switch ([#7420](https://github.com/mem0ai/mem0/pull/7420))
+
+
+
**Changes:**
@@ -2589,6 +2629,16 @@ Initial release of the Mem0 plugin for Claude Code and Cursor, followed by Codex
+
+
+**Improvements:**
+- **Search:** The `search_memories` tool description no longer tells the agent to call it before answering anything that could depend on prior context. It now asks for a search before repeating investigation or when earlier decisions, fixes, commands, or results may help, which reduces unnecessary searches ([#7420](https://github.com/mem0ai/mem0/pull/7420))
+- **Extraction:** Repository memory instructions are shorter. They no longer ask for a dedicated memory for each command that failed and was then fixed, and no longer carry separate rules against saving personal preferences or memories that only name the repository, branch, or directory ([#7420](https://github.com/mem0ai/mem0/pull/7420))
+- **Search skill:** `/search` no longer describes categories as best-effort labels or asks for a retry without the category ([#7420](https://github.com/mem0ai/mem0/pull/7420))
+- **Packaging:** `PLUGIN_VERSION` bumped to `0.3.3`, so the `mem0-plugin/` wire header and `plugin_version` telemetry field identify builds with these prompts ([#7420](https://github.com/mem0ai/mem0/pull/7420))
+
+
+
**Improvements:**
@@ -2692,6 +2742,16 @@ Existing memories written by the previous versions are not rewritten. If your me
+
+
+**Improvements:**
+- **Search:** The `search_memories` tool description no longer tells the agent to call it before answering anything that could depend on prior context. It now asks for a search before repeating investigation or when earlier decisions, fixes, commands, or results may help, which reduces unnecessary searches ([#7420](https://github.com/mem0ai/mem0/pull/7420))
+- **Extraction:** Repository memory instructions are shorter. They no longer ask for a dedicated memory for each command that failed and was then fixed, and no longer carry separate rules against saving personal preferences or memories that only name the repository, branch, or directory ([#7420](https://github.com/mem0ai/mem0/pull/7420))
+- **Search skill:** `/search` no longer describes categories as best-effort labels or asks for a retry without the category ([#7420](https://github.com/mem0ai/mem0/pull/7420))
+- **Packaging:** `PLUGIN_VERSION` bumped to `0.3.3`, so the `mem0-plugin/` wire header and `plugin_version` telemetry field identify builds with these prompts ([#7420](https://github.com/mem0ai/mem0/pull/7420))
+
+
+
**Improvements:**
@@ -2737,6 +2797,13 @@ Existing memories written by the previous versions are not rewritten. If your me
+
+
+**Improvements:**
+- **Search:** The `memory_search` tool description no longer asks the agent to search proactively or to run several searches for multi-part questions. It now asks for a search before repeating investigation or when earlier decisions, fixes, commands, or results may help. Recall strategies (`smart`, `always`, `manual`) are unchanged ([#7420](https://github.com/mem0ai/mem0/pull/7420))
+
+
+
**Changes:**
@@ -3033,6 +3100,15 @@ Existing memories written by the previous versions are not rewritten. If your me
+
+
+**Improvements:**
+- **Search:** The memory policy, `mem0_memory` tool description, and prompt guidelines no longer ask the agent to search before answering anything that may depend on earlier context or to run several searches per question. They now ask for a search before repeating investigation or when earlier decisions, fixes, commands, or results may help ([#7420](https://github.com/mem0ai/mem0/pull/7420))
+- **Skills:** `context-loader` makes one search instead of 2-4 parallel searches, and uses the search skill description from the other coding-agent plugins ([#7420](https://github.com/mem0ai/mem0/pull/7420))
+- **Automatic recall:** Injected memories are introduced as "Mem0 found these relevant memories from earlier work in this repository:", the same heading as the Python plugins. The old heading called them a shallow first pass and told the agent to search again ([#7420](https://github.com/mem0ai/mem0/pull/7420))
+
+
+
**Improvements:**
@@ -3153,6 +3229,14 @@ Existing memories written by the previous versions are not rewritten. If your me
+
+
+**Improvements:**
+- **Search:** The `search_memory` tool description no longer asks the agent to search proactively before answering anything that may depend on earlier context. It now asks for a search before repeating investigation or when earlier decisions, fixes, commands, or results may help ([#7420](https://github.com/mem0ai/mem0/pull/7420))
+- **Automatic recall:** Injected memories are introduced as "Mem0 found these relevant memories from earlier work:". The old heading called them a shallow first pass and told the agent to search again with `mem0_memory`, a tool DeepSeek does not have ([#7420](https://github.com/mem0ai/mem0/pull/7420))
+
+
+
**Improvements:**
diff --git a/integrations/agent-plugin-core/README.md b/integrations/agent-plugin-core/README.md
index f11026319..dab9a88b7 100644
--- a/integrations/agent-plugin-core/README.md
+++ b/integrations/agent-plugin-core/README.md
@@ -8,7 +8,7 @@ This directory is the single source of shared memory behavior for Mem0 coding-ag
integrations/
├── agent-plugin-core/ # Shared source; never installed as a plugin
│ ├── python/ # Claude-derived capture, recall, MCP, scoping, and telemetry
-│ ├── typescript/ # Shared lifecycle, formatting, identity, 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
@@ -45,7 +45,7 @@ New Git repository writes use a hashed remote identity for shared `agent_id`. Se
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 and lifecycle utilities but 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.
+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).
diff --git a/integrations/agent-plugin-core/python/mcp_server.py b/integrations/agent-plugin-core/python/mcp_server.py
index 036fbbdc9..a0b73cb79 100644
--- a/integrations/agent-plugin-core/python/mcp_server.py
+++ b/integrations/agent-plugin-core/python/mcp_server.py
@@ -21,16 +21,9 @@ from memory_core import (
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."
+ "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",
diff --git a/integrations/agent-plugin-core/python/memory_core.py b/integrations/agent-plugin-core/python/memory_core.py
index ea2670dac..9b420a063 100644
--- a/integrations/agent-plugin-core/python/memory_core.py
+++ b/integrations/agent-plugin-core/python/memory_core.py
@@ -29,7 +29,7 @@ from typing import Any, Iterable
import telemetry
DEFAULT_API_URL = "https://api.mem0.ai"
-PLUGIN_VERSION = "0.3.2"
+PLUGIN_VERSION = "0.3.3"
_harness_name: str = "generic"
_harness_env_prefix: str = "MEM0_PLUGIN"
@@ -71,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 the current 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 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."""
diff --git a/integrations/agent-plugin-core/skills/search/SKILL.md.tmpl b/integrations/agent-plugin-core/skills/search/SKILL.md.tmpl
index 3a255b1ad..6c4fdd03c 100644
--- a/integrations/agent-plugin-core/skills/search/SKILL.md.tmpl
+++ b/integrations/agent-plugin-core/skills/search/SKILL.md.tmpl
@@ -12,11 +12,9 @@ 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
diff --git a/integrations/agent-plugin-core/typescript/src/lifecycle.ts b/integrations/agent-plugin-core/typescript/src/lifecycle.ts
index 42c522b54..738ccc1c7 100644
--- a/integrations/agent-plugin-core/typescript/src/lifecycle.ts
+++ b/integrations/agent-plugin-core/typescript/src/lifecycle.ts
@@ -1,5 +1,6 @@
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;
@@ -70,12 +71,14 @@ export function extractConversation(
}
interface RecallOptions {
+ heading?: string;
maxChars?: number;
seenIds?: Set;
timeoutMs?: number;
}
interface MemoryLifecycleOptions {
+ recallHeading?: string;
maxContextChars?: number;
recallTimeoutMs?: number;
}
@@ -109,6 +112,7 @@ class MemoryLifecycle {
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,
@@ -148,8 +152,7 @@ export async function buildRecallContext(
const unseen = memories.filter((memory) => !options.seenIds?.has(memory.id));
if (!unseen.length) return "";
- const prefix =
- "\nRetrieved automatically for the current request. This is a shallow first pass — search mem0_memory for more if you need it.\n";
+ const prefix = `\n${options.heading ?? RECALL_HEADING}\n`;
const suffix = "\n";
const maxChars = options.maxChars ?? DEFAULT_MAX_CONTEXT_CHARS;
const lines: string[] = [];
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/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/antigravity-plugin/core/mcp_server.py b/integrations/antigravity-plugin/core/mcp_server.py
index 036fbbdc9..a0b73cb79 100644
--- a/integrations/antigravity-plugin/core/mcp_server.py
+++ b/integrations/antigravity-plugin/core/mcp_server.py
@@ -21,16 +21,9 @@ from memory_core import (
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."
+ "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",
diff --git a/integrations/antigravity-plugin/core/memory_core.py b/integrations/antigravity-plugin/core/memory_core.py
index ea2670dac..9b420a063 100644
--- a/integrations/antigravity-plugin/core/memory_core.py
+++ b/integrations/antigravity-plugin/core/memory_core.py
@@ -29,7 +29,7 @@ from typing import Any, Iterable
import telemetry
DEFAULT_API_URL = "https://api.mem0.ai"
-PLUGIN_VERSION = "0.3.2"
+PLUGIN_VERSION = "0.3.3"
_harness_name: str = "generic"
_harness_env_prefix: str = "MEM0_PLUGIN"
@@ -71,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 the current 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 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."""
diff --git a/integrations/antigravity-plugin/plugin-build.json b/integrations/antigravity-plugin/plugin-build.json
index 43b90d8cb..5a9112025 100644
--- a/integrations/antigravity-plugin/plugin-build.json
+++ b/integrations/antigravity-plugin/plugin-build.json
@@ -1,6 +1,6 @@
{
"id": "mem0",
- "version": "0.3.2",
+ "version": "0.3.3",
"homepage": "https://docs.mem0.ai/integrations/antigravity",
"native": {
"pluginRoot": "${ANTIGRAVITY_PLUGIN_ROOT}",
diff --git a/integrations/antigravity-plugin/skills/search/SKILL.md b/integrations/antigravity-plugin/skills/search/SKILL.md
index 7a6af05fa..530a70a86 100644
--- a/integrations/antigravity-plugin/skills/search/SKILL.md
+++ b/integrations/antigravity-plugin/skills/search/SKILL.md
@@ -12,11 +12,9 @@ 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
diff --git a/integrations/claude-code-plugin/.claude-plugin/plugin.json b/integrations/claude-code-plugin/.claude-plugin/plugin.json
index 0dd8298e9..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.2",
+ "version": "0.3.3",
"description": "Cross-session memory and token savings for coding agents.",
"author": {
"name": "Mem0"
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/mcp_server.py b/integrations/claude-code-plugin/core/mcp_server.py
index 036fbbdc9..a0b73cb79 100644
--- a/integrations/claude-code-plugin/core/mcp_server.py
+++ b/integrations/claude-code-plugin/core/mcp_server.py
@@ -21,16 +21,9 @@ from memory_core import (
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."
+ "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",
diff --git a/integrations/claude-code-plugin/core/memory_core.py b/integrations/claude-code-plugin/core/memory_core.py
index ea2670dac..9b420a063 100644
--- a/integrations/claude-code-plugin/core/memory_core.py
+++ b/integrations/claude-code-plugin/core/memory_core.py
@@ -29,7 +29,7 @@ from typing import Any, Iterable
import telemetry
DEFAULT_API_URL = "https://api.mem0.ai"
-PLUGIN_VERSION = "0.3.2"
+PLUGIN_VERSION = "0.3.3"
_harness_name: str = "generic"
_harness_env_prefix: str = "MEM0_PLUGIN"
@@ -71,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 the current 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 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."""
diff --git a/integrations/claude-code-plugin/plugin-build.json b/integrations/claude-code-plugin/plugin-build.json
index 4b98c2919..d62d653c3 100644
--- a/integrations/claude-code-plugin/plugin-build.json
+++ b/integrations/claude-code-plugin/plugin-build.json
@@ -1,6 +1,6 @@
{
"id": "mem0",
- "version": "0.3.2",
+ "version": "0.3.3",
"homepage": "https://docs.mem0.ai/integrations/claude-code",
"native": {
"pluginRoot": "${CLAUDE_PLUGIN_ROOT}",
diff --git a/integrations/claude-code-plugin/skills/search/SKILL.md b/integrations/claude-code-plugin/skills/search/SKILL.md
index 198a1f023..f7289b91d 100644
--- a/integrations/claude-code-plugin/skills/search/SKILL.md
+++ b/integrations/claude-code-plugin/skills/search/SKILL.md
@@ -12,11 +12,9 @@ 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
diff --git a/integrations/claude-code-plugin/tests/test_memory_core.py b/integrations/claude-code-plugin/tests/test_memory_core.py
index 9aea939cf..b6b1c28f9 100644
--- a/integrations/claude-code-plugin/tests/test_memory_core.py
+++ b/integrations/claude-code-plugin/tests/test_memory_core.py
@@ -1,8 +1,8 @@
from __future__ import annotations
import json
-import re
import os
+import re
import sqlite3
import subprocess
import sys
@@ -2307,8 +2307,8 @@ def test_sidekick_instructions_reject_unrequested_related_changes():
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
@@ -4333,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()
diff --git a/integrations/codex-plugin/.codex-plugin/plugin.json b/integrations/codex-plugin/.codex-plugin/plugin.json
index 0a80bf9e3..e91eca25a 100644
--- a/integrations/codex-plugin/.codex-plugin/plugin.json
+++ b/integrations/codex-plugin/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "mem0",
- "version": "0.3.2",
+ "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",
diff --git a/integrations/codex-plugin/core/mcp_server.py b/integrations/codex-plugin/core/mcp_server.py
index 036fbbdc9..a0b73cb79 100644
--- a/integrations/codex-plugin/core/mcp_server.py
+++ b/integrations/codex-plugin/core/mcp_server.py
@@ -21,16 +21,9 @@ from memory_core import (
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."
+ "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",
diff --git a/integrations/codex-plugin/core/memory_core.py b/integrations/codex-plugin/core/memory_core.py
index ea2670dac..9b420a063 100644
--- a/integrations/codex-plugin/core/memory_core.py
+++ b/integrations/codex-plugin/core/memory_core.py
@@ -29,7 +29,7 @@ from typing import Any, Iterable
import telemetry
DEFAULT_API_URL = "https://api.mem0.ai"
-PLUGIN_VERSION = "0.3.2"
+PLUGIN_VERSION = "0.3.3"
_harness_name: str = "generic"
_harness_env_prefix: str = "MEM0_PLUGIN"
@@ -71,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 the current 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 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."""
diff --git a/integrations/codex-plugin/plugin-build.json b/integrations/codex-plugin/plugin-build.json
index 7f5fc94f6..a354c31f5 100644
--- a/integrations/codex-plugin/plugin-build.json
+++ b/integrations/codex-plugin/plugin-build.json
@@ -1,6 +1,6 @@
{
"id": "mem0",
- "version": "0.3.2",
+ "version": "0.3.3",
"homepage": "https://docs.mem0.ai/integrations/codex",
"native": {
"pluginRoot": "${PLUGIN_ROOT}",
diff --git a/integrations/codex-plugin/skills/search/SKILL.md b/integrations/codex-plugin/skills/search/SKILL.md
index f6c27b19c..90f435008 100644
--- a/integrations/codex-plugin/skills/search/SKILL.md
+++ b/integrations/codex-plugin/skills/search/SKILL.md
@@ -12,11 +12,9 @@ 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
diff --git a/integrations/cursor-plugin/.cursor-plugin/plugin.json b/integrations/cursor-plugin/.cursor-plugin/plugin.json
index a30f9ad9a..7c2304f29 100644
--- a/integrations/cursor-plugin/.cursor-plugin/plugin.json
+++ b/integrations/cursor-plugin/.cursor-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "mem0",
- "version": "0.3.2",
+ "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",
diff --git a/integrations/cursor-plugin/core/mcp_server.py b/integrations/cursor-plugin/core/mcp_server.py
index 036fbbdc9..a0b73cb79 100644
--- a/integrations/cursor-plugin/core/mcp_server.py
+++ b/integrations/cursor-plugin/core/mcp_server.py
@@ -21,16 +21,9 @@ from memory_core import (
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."
+ "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",
diff --git a/integrations/cursor-plugin/core/memory_core.py b/integrations/cursor-plugin/core/memory_core.py
index ea2670dac..9b420a063 100644
--- a/integrations/cursor-plugin/core/memory_core.py
+++ b/integrations/cursor-plugin/core/memory_core.py
@@ -29,7 +29,7 @@ from typing import Any, Iterable
import telemetry
DEFAULT_API_URL = "https://api.mem0.ai"
-PLUGIN_VERSION = "0.3.2"
+PLUGIN_VERSION = "0.3.3"
_harness_name: str = "generic"
_harness_env_prefix: str = "MEM0_PLUGIN"
@@ -71,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 the current 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 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."""
diff --git a/integrations/cursor-plugin/plugin-build.json b/integrations/cursor-plugin/plugin-build.json
index 30024586e..5320fb7f9 100644
--- a/integrations/cursor-plugin/plugin-build.json
+++ b/integrations/cursor-plugin/plugin-build.json
@@ -1,6 +1,6 @@
{
"id": "mem0",
- "version": "0.3.2",
+ "version": "0.3.3",
"homepage": "https://docs.mem0.ai/integrations/cursor",
"native": {
"pluginRoot": "${CURSOR_PLUGIN_ROOT}",
diff --git a/integrations/cursor-plugin/skills/search/SKILL.md b/integrations/cursor-plugin/skills/search/SKILL.md
index 7a7ddfa90..2e3bde6a7 100644
--- a/integrations/cursor-plugin/skills/search/SKILL.md
+++ b/integrations/cursor-plugin/skills/search/SKILL.md
@@ -12,11 +12,9 @@ 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
diff --git a/integrations/deepseek-plugin/package.json b/integrations/deepseek-plugin/package.json
index 2df84283c..41a8fe7a5 100644
--- a/integrations/deepseek-plugin/package.json
+++ b/integrations/deepseek-plugin/package.json
@@ -1,6 +1,6 @@
{
"name": "@mem0/deepseek-plugin",
- "version": "0.3.1",
+ "version": "0.3.2",
"description": "Mem0 long-term memory as a native DeepSeek Harness (Cordis) plugin.",
"type": "module",
"license": "Apache-2.0",
diff --git a/integrations/deepseek-plugin/src/index.ts b/integrations/deepseek-plugin/src/index.ts
index 3ac86f4b0..c5eb64390 100644
--- a/integrations/deepseek-plugin/src/index.ts
+++ b/integrations/deepseek-plugin/src/index.ts
@@ -21,6 +21,11 @@ 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", "systemPrompt"];
@@ -107,7 +112,7 @@ export function apply(ctx: Context, config: Config): void {
const stateFor = (session: object): SessionState => {
let state = sessionStates.get(session);
if (!state) {
- const lifecycle = createMemoryLifecycle();
+ const lifecycle = createMemoryLifecycle({ recallHeading: USER_RECALL_HEADING });
lifecycle.beginSession();
state = { lifecycle, messages: [] };
sessionStates.set(session, state);
@@ -197,10 +202,9 @@ export function apply(ctx: Context, config: Config): void {
ctx.tools.register(
defineTool({
name: "search_memory",
- description:
- "Search the user's long-term Mem0 memory for facts relevant to a query. Use proactively before answering anything that may depend on what the user told you earlier.",
+ description: USER_SEARCH_TOOL_DESCRIPTION,
parameters: {
- query: { type: "string", description: "What to recall.", required: true },
+ query: { type: "string", description: USER_SEARCH_QUERY_DESCRIPTION, required: true },
limit: {
type: "integer",
description: `Max results to return (default ${DEFAULT_SEARCH_LIMIT}).`,
diff --git a/integrations/kimi-plugin/core/mcp_server.py b/integrations/kimi-plugin/core/mcp_server.py
index 036fbbdc9..a0b73cb79 100644
--- a/integrations/kimi-plugin/core/mcp_server.py
+++ b/integrations/kimi-plugin/core/mcp_server.py
@@ -21,16 +21,9 @@ from memory_core import (
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."
+ "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",
diff --git a/integrations/kimi-plugin/core/memory_core.py b/integrations/kimi-plugin/core/memory_core.py
index ea2670dac..9b420a063 100644
--- a/integrations/kimi-plugin/core/memory_core.py
+++ b/integrations/kimi-plugin/core/memory_core.py
@@ -29,7 +29,7 @@ from typing import Any, Iterable
import telemetry
DEFAULT_API_URL = "https://api.mem0.ai"
-PLUGIN_VERSION = "0.3.2"
+PLUGIN_VERSION = "0.3.3"
_harness_name: str = "generic"
_harness_env_prefix: str = "MEM0_PLUGIN"
@@ -71,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 the current 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 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."""
diff --git a/integrations/kimi-plugin/kimi.plugin.json b/integrations/kimi-plugin/kimi.plugin.json
index e58bec328..6b28575d3 100644
--- a/integrations/kimi-plugin/kimi.plugin.json
+++ b/integrations/kimi-plugin/kimi.plugin.json
@@ -1,6 +1,6 @@
{
"name": "mem0",
- "version": "0.3.2",
+ "version": "0.3.3",
"description": "Cross-session memory and token savings for coding agents.",
"keywords": ["memory", "coding-agents", "continual-learning", "token-efficiency"],
"author": { "name": "Mem0", "email": "support@mem0.ai" },
diff --git a/integrations/kimi-plugin/plugin-build.json b/integrations/kimi-plugin/plugin-build.json
index e73643eab..35e38ecf5 100644
--- a/integrations/kimi-plugin/plugin-build.json
+++ b/integrations/kimi-plugin/plugin-build.json
@@ -1,6 +1,6 @@
{
"id": "mem0",
- "version": "0.3.2",
+ "version": "0.3.3",
"homepage": "https://docs.mem0.ai/integrations/kimi",
"native": {
"pluginRoot": "${KIMI_PLUGIN_ROOT}",
diff --git a/integrations/kimi-plugin/skills/search/SKILL.md b/integrations/kimi-plugin/skills/search/SKILL.md
index eb92a6ca8..316b78e53 100644
--- a/integrations/kimi-plugin/skills/search/SKILL.md
+++ b/integrations/kimi-plugin/skills/search/SKILL.md
@@ -12,11 +12,9 @@ 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
diff --git a/integrations/mem0-agent-plugin/core/mcp_server.py b/integrations/mem0-agent-plugin/core/mcp_server.py
index 036fbbdc9..a0b73cb79 100644
--- a/integrations/mem0-agent-plugin/core/mcp_server.py
+++ b/integrations/mem0-agent-plugin/core/mcp_server.py
@@ -21,16 +21,9 @@ from memory_core import (
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."
+ "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",
diff --git a/integrations/mem0-agent-plugin/core/memory_core.py b/integrations/mem0-agent-plugin/core/memory_core.py
index ea2670dac..9b420a063 100644
--- a/integrations/mem0-agent-plugin/core/memory_core.py
+++ b/integrations/mem0-agent-plugin/core/memory_core.py
@@ -29,7 +29,7 @@ from typing import Any, Iterable
import telemetry
DEFAULT_API_URL = "https://api.mem0.ai"
-PLUGIN_VERSION = "0.3.2"
+PLUGIN_VERSION = "0.3.3"
_harness_name: str = "generic"
_harness_env_prefix: str = "MEM0_PLUGIN"
@@ -71,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 the current 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 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."""
diff --git a/integrations/mem0-agent-plugin/plugin.json b/integrations/mem0-agent-plugin/plugin.json
index 7a2baba80..95ff54651 100644
--- a/integrations/mem0-agent-plugin/plugin.json
+++ b/integrations/mem0-agent-plugin/plugin.json
@@ -1,7 +1,7 @@
{
"$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json",
"name": "mem0",
- "version": "0.3.2",
+ "version": "0.3.3",
"description": "Cross-session memory and token savings for coding agents.",
"author": {
"name": "Mem0",
diff --git a/integrations/mem0-agent-plugin/skills/search/SKILL.md b/integrations/mem0-agent-plugin/skills/search/SKILL.md
index d52c4ff34..bbd4eb535 100644
--- a/integrations/mem0-agent-plugin/skills/search/SKILL.md
+++ b/integrations/mem0-agent-plugin/skills/search/SKILL.md
@@ -10,11 +10,9 @@ 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
diff --git a/integrations/openclaw/openclaw.plugin.json b/integrations/openclaw/openclaw.plugin.json
index 9d4cacaf8..e3b299112 100644
--- a/integrations/openclaw/openclaw.plugin.json
+++ b/integrations/openclaw/openclaw.plugin.json
@@ -2,7 +2,7 @@
"id": "openclaw-mem0",
"name": "Memory (Mem0)",
"description": "Mem0 memory backend for OpenClaw — platform (mem0.ai cloud) or self-hosted open-source. Auto-recall and auto-capture are opt-in (disabled by default). Supports OpenAI, Anthropic, Ollama (fully local), Qdrant, and PGVector providers.",
- "version": "1.2.0",
+ "version": "1.2.1",
"kind": "memory",
"skills": ["skills"],
"commandAliases": [
diff --git a/integrations/openclaw/package.json b/integrations/openclaw/package.json
index 49f49dbf4..39aaeb70e 100644
--- a/integrations/openclaw/package.json
+++ b/integrations/openclaw/package.json
@@ -1,6 +1,6 @@
{
"name": "@mem0/openclaw-mem0",
- "version": "1.2.0",
+ "version": "1.2.1",
"type": "module",
"description": "Mem0 memory backend for OpenClaw — platform or self-hosted open-source",
"license": "Apache-2.0",
diff --git a/integrations/openclaw/tools/memory-search.ts b/integrations/openclaw/tools/memory-search.ts
index 58ce8183a..51d2ebcfd 100644
--- a/integrations/openclaw/tools/memory-search.ts
+++ b/integrations/openclaw/tools/memory-search.ts
@@ -1,4 +1,5 @@
import { Type } from "@sinclair/typebox";
+import { USER_SEARCH_QUERY_DESCRIPTION, USER_SEARCH_TOOL_DESCRIPTION } from "../../agent-plugin-core/typescript/src/prompts.ts";
import type { MemoryItem, SearchOptions } from "../types.ts";
import type { ToolDeps } from "./index.ts";
@@ -8,9 +9,9 @@ export function createMemorySearchTool(deps: ToolDeps) {
return {
name: "memory_search",
label: "Memory Search",
- description: "Search long-term memories stored in Mem0 by semantic meaning. Use this proactively before answering when the request may depend on the user's past work, preferences, or decisions -- relevant memories are not always already in context. For multi-part or comparative questions, run several searches with different phrasings and combine the results rather than stopping after one (multi-hop).",
+ description: USER_SEARCH_TOOL_DESCRIPTION,
parameters: Type.Object({
- query: Type.String({ description: "Search query" }),
+ query: Type.String({ description: USER_SEARCH_QUERY_DESCRIPTION }),
limit: Type.Optional(Type.Number({ description: `Max results (default: ${cfg.topK})` })),
userId: Type.Optional(Type.String({ description: "User ID to scope search" })),
agentId: Type.Optional(Type.String({ description: "Agent ID to search a specific agent's memories" })),
diff --git a/integrations/opencode-plugin/opencode-mem0.ts b/integrations/opencode-plugin/opencode-mem0.ts
index 8dcf6d535..a86eab3af 100644
--- a/integrations/opencode-plugin/opencode-mem0.ts
+++ b/integrations/opencode-plugin/opencode-mem0.ts
@@ -18,6 +18,7 @@ import {asScope, scopeSearchFilters, scopeWriteParams, resolveDefaultScope, SCOP
import {parseProjectFromRemote} from "./project";
import {resolveApiKey} from "./api-key";
import {createMemoryLifecycle} from "../agent-plugin-core/typescript/src/lifecycle.ts";
+import {SEARCH_QUERY_DESCRIPTION, SEARCH_TOOL_DESCRIPTION} from "../agent-plugin-core/typescript/src/prompts.ts";
async function getUserId(): Promise {
if (process.env.MEM0_USER_ID) return process.env.MEM0_USER_ID;
@@ -424,9 +425,9 @@ Identity context (resolved at plugin startup):
}),
search_memories: tool({
- description: "Search stored memories by semantic meaning. Use this proactively before answering when the request may depend on the user's past work, preferences, decisions, or environment -- relevant memories are not always auto-injected. For multi-part or comparative questions, run several searches with different phrasings and combine the results rather than stopping after one (multi-hop).",
+ description: SEARCH_TOOL_DESCRIPTION,
args: {
- query: tool.schema.string().describe("Search query"),
+ query: tool.schema.string().describe(SEARCH_QUERY_DESCRIPTION),
user_id: tool.schema.string().optional().describe("User ID"),
app_id: tool.schema.string().optional().describe("App/Project ID"),
agent_id: tool.schema.string().optional().describe("Agent ID"),
@@ -636,9 +637,6 @@ Identity context (resolved at plugin startup):
}
if (memoryCount > 0) {
- systemContext.push(
- "Search mem0 for recent decisions and task learnings before responding. Run 2 parallel searches: one for decision type, one for task_learning type.",
- );
try {
const res = await mem0.search(
"recent session state decisions and learnings",
@@ -659,9 +657,6 @@ Identity context (resolved at plugin startup):
}
}
- systemContext.push(
- "Mem0 searches apply when user references past work, decision questions, errors, or non-trivial tasks. Queries use noun-phrases, 2-4 parallel calls with different metadata.type filters, and include user_id + app_id.",
- );
systemContext.push(SCOPE_GUIDANCE);
const activeScope = loadDefaultScope();
if (activeScope !== "project") {
diff --git a/integrations/opencode-plugin/opencode-skills/mem0-context-loader/SKILL.md b/integrations/opencode-plugin/opencode-skills/mem0-context-loader/SKILL.md
index 803689076..b22f647dc 100644
--- a/integrations/opencode-plugin/opencode-skills/mem0-context-loader/SKILL.md
+++ b/integrations/opencode-plugin/opencode-skills/mem0-context-loader/SKILL.md
@@ -1,35 +1,19 @@
---
name: mem0-context-loader
-description: Searches and injects relevant memories into context before starting work on a task. Use when beginning a new task, switching context, or when project history, past decisions, or coding conventions need to be loaded.
+description: Search memories from earlier OpenCode 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.
---
# Context Loader
Pre-fetches relevant memories to prime context before working on a task.
-## When to use
-
-- Session start (invoke manually or auto-triggered by skill description matching)
-- User starts work on a specific feature or file set
-- Complex multi-step task begins
-- User says "what do we know about X" or "context for X"
-
## Steps
1. **Extract topics** from current message/task. Identify: file paths, module names, feature areas, error patterns.
-2. **Run 2-4 parallel `search_memories` calls** with different angles:
+2. **Call `search_memories` once** with a focused question about the task: `filters={"AND": [{"user_id": ""}, {"app_id": ""}]}`, `top_k=10`.
- | Query angle | Filter | Purpose |
- |---|---|---|
- | Feature/module name | `{"AND": [{"user_id": ""}, {"app_id": ""}, {"metadata": {"type": "decision"}}]}` | Architecture decisions |
- | File paths mentioned | `{"AND": [{"user_id": ""}, {"app_id": ""}, {"metadata": {"type": "convention"}}]}` | Coding patterns |
- | Error keywords (if any) | `{"AND": [{"user_id": ""}, {"app_id": ""}, {"metadata": {"type": "anti_pattern"}}]}` | Known pitfalls |
- | Broad project context | `{"AND": [{"user_id": ""}, {"app_id": ""}]}` | Catch-all |
-
-3. **Deduplicate** results by memory ID across all search responses.
-
-4. **Output compact context block** (max 10 memories):
+3. **Output compact context block** (max 10 memories):
```
context-loader: loaded memories for ""
@@ -38,7 +22,7 @@ context-loader: loaded memories for ""
- [anti_pattern] [mem0:]
```
-5. If **zero results**: output nothing. Don't announce empty context.
+4. If **zero results**: output nothing. Don't announce empty context.
## Constraints
diff --git a/integrations/opencode-plugin/opencode-skills/mem0-search/SKILL.md b/integrations/opencode-plugin/opencode-skills/mem0-search/SKILL.md
index ed3533991..e6b570d12 100644
--- a/integrations/opencode-plugin/opencode-skills/mem0-search/SKILL.md
+++ b/integrations/opencode-plugin/opencode-skills/mem0-search/SKILL.md
@@ -27,14 +27,11 @@ When an ID is detected:
### Step 2: Search
-Run 2 parallel `search_memories` calls:
-
-1. Broad: `query=`, `filters={"AND": [{"user_id": ""}, {"app_id": ""}]}`, `top_k=10`, `rerank=true`
-2. Targeted: `query=`, `filters={"AND": [{"user_id": ""}, {"app_id": ""}, {"metadata": {"type": "decision"}}]}`, `top_k=5`, `rerank=true`
+Call `search_memories` once with the user's question: `query=`, `filters={"AND": [{"user_id": ""}, {"app_id": ""}]}`, `top_k=10`.
### Step 3: Display
-Deduplicate by ID, then show compact results:
+Show compact results:
```
## mem0 search: "" ( results)
diff --git a/integrations/opencode-plugin/package.json b/integrations/opencode-plugin/package.json
index efcb60a28..36c3dce6b 100644
--- a/integrations/opencode-plugin/package.json
+++ b/integrations/opencode-plugin/package.json
@@ -1,6 +1,6 @@
{
"name": "@mem0/opencode-plugin",
- "version": "0.4.0",
+ "version": "0.4.1",
"type": "module",
"description": "Mem0 persistent memory plugin for OpenCode — add, search, and manage memories across sessions",
"main": "dist/index.js",
diff --git a/integrations/pi-agent-plugin/README.md b/integrations/pi-agent-plugin/README.md
index cb28d2314..3dc5b351b 100644
--- a/integrations/pi-agent-plugin/README.md
+++ b/integrations/pi-agent-plugin/README.md
@@ -71,7 +71,7 @@ The plugin includes 6 skills that guide the agent on how to use each capability:
| Skill | Purpose |
|-------|---------|
-| `context-loader` | Pre-fetch relevant memories at session start |
+| `context-loader` | Search memories when earlier work may already explain the task |
| `remember` | Store facts with category classification |
| `search` | Quick semantic search with compact results |
| `forget` | Delete memories with confirmation |
diff --git a/integrations/pi-agent-plugin/package.json b/integrations/pi-agent-plugin/package.json
index 7ef9f822e..fbec4db1b 100644
--- a/integrations/pi-agent-plugin/package.json
+++ b/integrations/pi-agent-plugin/package.json
@@ -1,6 +1,6 @@
{
"name": "@mem0/pi-agent-plugin",
- "version": "0.3.1",
+ "version": "0.3.2",
"type": "module",
"description": "Mem0 memory extension for Pi Agent persistent, scoped, semantic memory across sessions and projects",
"license": "Apache-2.0",
diff --git a/integrations/pi-agent-plugin/skills/context-loader/SKILL.md b/integrations/pi-agent-plugin/skills/context-loader/SKILL.md
index 22c10b2c8..616de9d02 100644
--- a/integrations/pi-agent-plugin/skills/context-loader/SKILL.md
+++ b/integrations/pi-agent-plugin/skills/context-loader/SKILL.md
@@ -1,34 +1,19 @@
---
name: context-loader
-description: Searches and injects relevant memories into context before starting work on a task or topic. Use when beginning a new task, switching context, or when past decisions, preferences, or knowledge need to be loaded.
+description: Search memories from earlier Pi 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.
---
# Context Loader
Pre-fetches relevant memories to prime context before working on a task or topic.
-## When to use
-
-- Session start (auto-triggered by the extension's `before_agent_start` event)
-- User starts work on a specific topic or area
-- User says "what do we know about X" or "context for X"
-
## Steps
1. **Extract topics** from current message/task. Identify: subject areas, people mentioned, project names, goal references.
-2. **Run 2-4 parallel searches** using `mem0_memory` tool with `action="search"` and different query angles:
+2. **Call `mem0_memory` once** with `action="search"` and a focused question about the task.
- | Query angle | Purpose |
- |---|---|
- | Topic/subject name | Relevant decisions and preferences |
- | People mentioned | Relationship context |
- | Project/goal references | Progress and background |
- | Broad context | Catch-all for anything relevant |
-
-3. **Deduplicate** results by memory ID across all search responses.
-
-4. **Output compact context block** (max 10 memories):
+3. **Output compact context block** (max 10 memories):
```
context-loader: loaded memories for ""
@@ -37,7 +22,7 @@ context-loader: loaded memories for ""
- [lessons] [mem0:]
```
-5. If **zero results**: output nothing. Don't announce empty context.
+4. If **zero results**: output nothing. Don't announce empty context.
## Constraints
diff --git a/integrations/pi-agent-plugin/src/memory/tools.ts b/integrations/pi-agent-plugin/src/memory/tools.ts
index 96d8e9b3e..f6110a73f 100644
--- a/integrations/pi-agent-plugin/src/memory/tools.ts
+++ b/integrations/pi-agent-plugin/src/memory/tools.ts
@@ -1,4 +1,5 @@
import { resolveToolScope } from "../../../agent-plugin-core/typescript/src/scoping.ts";
+import { SEARCH_QUERY_DESCRIPTION, SEARCH_WHEN } from "../../../agent-plugin-core/typescript/src/prompts.ts";
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
import { Type } from "typebox";
import { StringEnum } from "@earendil-works/pi-ai";
@@ -144,11 +145,10 @@ export function registerMemoryTool(
name: "mem0_memory",
label: "Mem0 Memory",
description:
- "Search, add, update, and manage persistent semantic memories powered by Mem0. Memories persist across sessions and devices. Use action \"search\" proactively -- before answering anything that may depend on what the user told you earlier -- and run multiple searches with different phrasings for multi-part questions. Output is truncated to 200 lines / 50KB.",
+ `Search, add, update, and manage persistent semantic memories powered by Mem0. Memories persist across sessions and devices. Use action "search" ${SEARCH_WHEN}. Output is truncated to 200 lines / 50KB.`,
promptSnippet: "Semantic memory search and storage via Mem0",
promptGuidelines: [
- 'Use mem0_memory with action "search" proactively whenever the request may depend on the user\'s past work, preferences, decisions, or environment -- not only when they explicitly mention the past',
- 'For multi-part or comparative questions, run several searches with different phrasings and combine the results before answering -- one search is rarely enough',
+ `Use mem0_memory with action "search" ${SEARCH_WHEN}`,
'Use mem0_memory with action "add" to save important facts, preferences, goals, decisions, or lessons the user shares',
'Use mem0_memory with action "update" to modify an existing memory — requires memory_id and content. Preserves the memory ID',
"Always use the default project scope unless the user EXPLICITLY asks to search across all projects — only after the user selects /mem0-scope global use scope \"global\"",
@@ -166,13 +166,13 @@ export function registerMemoryTool(
] as const,
{
description:
- "Memory operation to run: \"search\" (semantic recall -- use proactively before answering; run several with different phrasings for multi-part questions), \"add\" (save a new fact/preference/decision), \"get_all\" (list everything in scope, no query needed), \"update\" (replace an existing memory's text by id), \"delete\" (remove one memory by id), \"delete_all\" (wipe every memory in the scope -- destructive, only on explicit request).",
+ "Memory operation to run: \"search\" (semantic recall of earlier work in this repository), \"add\" (save a new fact/preference/decision), \"get_all\" (list everything in scope, no query needed), \"update\" (replace an existing memory's text by id), \"delete\" (remove one memory by id), \"delete_all\" (wipe every memory in the scope -- destructive, only on explicit request).",
},
),
query: Type.Optional(
Type.String({
description:
- "Search text -- required for action \"search\". Use a focused noun-phrase; for multi-part questions run several searches with different phrasings.",
+ `Search text -- required for action "search". ${SEARCH_QUERY_DESCRIPTION}`,
}),
),
content: Type.Optional(
diff --git a/integrations/pi-agent-plugin/src/prompt.ts b/integrations/pi-agent-plugin/src/prompt.ts
index 83365239b..dd1137d35 100644
--- a/integrations/pi-agent-plugin/src/prompt.ts
+++ b/integrations/pi-agent-plugin/src/prompt.ts
@@ -1,10 +1,9 @@
-export const MEMORY_POLICY = `
-You have persistent semantic memory via the mem0_memory tool, powered by Mem0. Relevant memories may be auto-injected under , but that retrieval is shallow — treat it as a starting point, not the full picture.
+import { SEARCH_WHEN } from "../../agent-plugin-core/typescript/src/prompts.ts";
-Be proactive about retrieval:
-- Search memory BEFORE answering whenever the request could depend on the user's past work, preferences, decisions, environment, or anything they told you earlier — don't wait to be asked.
-- Check memory before asking the user something they may have already told you.
-- For multi-part, comparative, or "how did we…" questions, run SEVERAL searches with different phrasings and combine the results. One search is rarely enough — keep going until you have what you need (multi-hop).
+export const MEMORY_POLICY = `
+You have persistent semantic memory via the mem0_memory tool, powered by Mem0. Relevant memories may be auto-injected under .
+
+Use mem0_memory with action "search" ${SEARCH_WHEN}.
Be proactive about saving:
- Save important facts, preferences, goals, decisions, lessons learned, identity, relationships, and routines the user shares.
diff --git a/marketplace.json b/marketplace.json
index b1608c958..ded2d2ece 100644
--- a/marketplace.json
+++ b/marketplace.json
@@ -13,7 +13,7 @@
},
"category": "Productivity",
"description": "Cross-session memory and token savings for coding agents.",
- "version": "0.3.2"
+ "version": "0.3.3"
}
]
}
From 83b07b1537d688b9687bb116f8e0c6a9cabf2d95 Mon Sep 17 00:00:00 2001
From: "mintlify[bot]" <109931778+mintlify[bot]@users.noreply.github.com>
Date: Wed, 23 Sep 2026 19:53:11 +0530
Subject: [PATCH 22/54] Fix grammar & typos: minor fixes across docs (#7423)
Co-authored-by: mintlify[bot] <109931778+mintlify[bot]@users.noreply.github.com>
---
docs/components/embedders/models/together.mdx | 2 +-
docs/components/vectordbs/dbs/azure.mdx | 2 +-
docs/cookbooks/integrations/healthcare-google-adk.mdx | 2 +-
docs/integrations/llama-index.mdx | 2 +-
4 files changed, 4 insertions(+), 4 deletions(-)
diff --git a/docs/components/embedders/models/together.mdx b/docs/components/embedders/models/together.mdx
index 75f44227e..a71c1764a 100644
--- a/docs/components/embedders/models/together.mdx
+++ b/docs/components/embedders/models/together.mdx
@@ -11,7 +11,7 @@ To use Together embedding models, set the `TOGETHER_API_KEY` environment variabl
The `embedding_model_dims` parameter for `vector_store` should be set to `1024` for Together embedder.
-**Breaking default change.** The default Together embedding model is now `intfloat/multilingual-e5-large-instruct` (**1024-dim**), replacing the previous default `togethercomputer/m2-bert-80M-8k-retrieval` (**768-dim**). If you created a self-hosted vector store with the old default, its collection is 768-dim and will reject the new 1024-dim vectors **recreate/reindex the collection at 1024 dimensions** after upgrading. To defer the change, pin the previous values explicitly (`model="togethercomputer/m2-bert-80M-8k-retrieval"`, `embedding_dims=768`) note Together no longer lists this model among its recommended embeddings, so reindexing at 1024 is the durable path.
+**Breaking default change.** The default Together embedding model is now `intfloat/multilingual-e5-large-instruct` (**1024-dim**), replacing the previous default `togethercomputer/m2-bert-80M-8k-retrieval` (**768-dim**). If you created a self-hosted vector store with the old default, its collection is 768-dim and will reject the new 1024-dim vectors — **recreate/reindex the collection at 1024 dimensions** after upgrading. To defer the change, pin the previous values explicitly (`model="togethercomputer/m2-bert-80M-8k-retrieval"`, `embedding_dims=768`) — note Together no longer lists this model among its recommended embeddings, so reindexing at 1024 is the durable path.
diff --git a/docs/components/vectordbs/dbs/azure.mdx b/docs/components/vectordbs/dbs/azure.mdx
index 93a0bf4ad..8577b50cc 100644
--- a/docs/components/vectordbs/dbs/azure.mdx
+++ b/docs/components/vectordbs/dbs/azure.mdx
@@ -95,7 +95,7 @@ Uses the identity from Azure PowerShell (`Connect-AzAccount`).
7. **Azure Developer CLI Credential:**
Uses the session from Azure Developer CLI (`azd auth login`).
- If an API is provided, it will be used for authentication over an Azure Identity
+ If an API key is provided, it will be used for authentication over an Azure Identity
To enable Role-Based Access Control (RBAC) for Azure AI Search, follow these steps:
1. In the Azure Portal, navigate to your **Azure AI Search** service.
diff --git a/docs/cookbooks/integrations/healthcare-google-adk.mdx b/docs/cookbooks/integrations/healthcare-google-adk.mdx
index 0696f45e5..9c9571a66 100644
--- a/docs/cookbooks/integrations/healthcare-google-adk.mdx
+++ b/docs/cookbooks/integrations/healthcare-google-adk.mdx
@@ -30,7 +30,7 @@ pip install google-adk mem0ai python-dotenv
## Code Breakdown
-Let's get started and understand the different components required in building a healthcare assistant powered by memory
+Let's get started and understand the different components required in building a healthcare assistant powered by memory.
```python
# Import dependencies
diff --git a/docs/integrations/llama-index.mdx b/docs/integrations/llama-index.mdx
index f2bc02491..d529937f6 100644
--- a/docs/integrations/llama-index.mdx
+++ b/docs/integrations/llama-index.mdx
@@ -45,7 +45,7 @@ memory_from_client = Mem0Memory.from_client(
)
```
-Context is used to identify the user, agent or the conversation in the Mem0. It is required to be passed in the at least one of the fields in the `Mem0Memory` constructor. It can be any of the following:
+Context is used to identify the user, agent or the conversation in the Mem0. It is required to be passed in at least one of the fields in the `Mem0Memory` constructor. It can be any of the following:
```python
context = {
From 0cddc36d524ac6f54228e6355048adb936b436c3 Mon Sep 17 00:00:00 2001
From: Brennan <31714723+BCathcart@users.noreply.github.com>
Date: Wed, 23 Sep 2026 10:02:04 -0700
Subject: [PATCH 23/54] Protect against None timestamps in Valkey layer (#6993)
Signed-off-by: Brennan Cathcart
---
mem0/vector_stores/valkey.py | 20 +++++---------------
tests/vector_stores/test_valkey.py | 26 ++++++++++++++++++++++++++
2 files changed, 31 insertions(+), 15 deletions(-)
diff --git a/mem0/vector_stores/valkey.py b/mem0/vector_stores/valkey.py
index 0688a1288..189285539 100644
--- a/mem0/vector_stores/valkey.py
+++ b/mem0/vector_stores/valkey.py
@@ -299,13 +299,8 @@ class ValkeyDB(VectorStoreBase):
# Create the key for the hash
key = f"{self.prefix}:{id}"
- # Check for required fields and provide defaults if missing
- if "data" not in payload:
- # Silently use default value for missing 'data' field
- pass
-
- # Ensure created_at is present
- if "created_at" not in payload:
+ # Default created_at when missing or None to current time
+ if not payload.get("created_at"):
payload["created_at"] = datetime.now(pytz.timezone(self.timezone)).isoformat()
# Prepare the hash data
@@ -499,13 +494,8 @@ class ValkeyDB(VectorStoreBase):
try:
key = f"{self.prefix}:{vector_id}"
- # Check for required fields and provide defaults if missing
- if "data" not in payload:
- # Silently use default value for missing 'data' field
- pass
-
- # Ensure created_at is present
- if "created_at" not in payload:
+ # Default created_at when missing or None to current time
+ if not payload.get("created_at"):
payload["created_at"] = datetime.now(pytz.timezone(self.timezone)).isoformat()
# Prepare the hash data
@@ -521,7 +511,7 @@ class ValkeyDB(VectorStoreBase):
hash_data["embedding"] = np.array(vector, dtype=np.float32).tobytes()
# Add updated_at if available
- if "updated_at" in payload:
+ if payload.get("updated_at"):
hash_data["updated_at"] = int(datetime.fromisoformat(payload["updated_at"]).timestamp())
# Add optional fields
diff --git a/tests/vector_stores/test_valkey.py b/tests/vector_stores/test_valkey.py
index 769f511d4..b42a54848 100644
--- a/tests/vector_stores/test_valkey.py
+++ b/tests/vector_stores/test_valkey.py
@@ -158,6 +158,32 @@ def test_insert_handles_missing_created_at(valkey_db, mock_valkey_client):
assert "created_at" in kwargs["mapping"] # Should be added automatically
+def test_insert_and_update_with_none_timestamps(valkey_db, mock_valkey_client):
+ """Regression: a None timestamp must not crash insert() or update().
+
+ A None created_at falls back to now and a None updated_at is skipped, so
+ neither reaches fromisoformat() which only accepts a str.
+ """
+ vector = np.random.rand(1536).tolist()
+
+ valkey_db.insert(
+ vectors=[vector],
+ payloads=[{"hash": "h", "data": "d", "created_at": None, "updated_at": None}],
+ ids=["id1"],
+ )
+ _, insert_kwargs = mock_valkey_client.hset.call_args
+ assert isinstance(insert_kwargs["mapping"]["created_at"], int)
+
+ valkey_db.update(
+ vector_id="id1",
+ vector=vector,
+ payload={"hash": "h", "data": "d", "created_at": None, "updated_at": None},
+ )
+ _, update_kwargs = mock_valkey_client.hset.call_args
+ assert isinstance(update_kwargs["mapping"]["created_at"], int)
+ assert "updated_at" not in update_kwargs["mapping"]
+
+
def test_delete(valkey_db, mock_valkey_client):
"""Test deleting a vector."""
# Call delete
From ea9bbcabed98418a1800c104aade8975e6460a04 Mon Sep 17 00:00:00 2001
From: Karthik
Date: Thu, 24 Sep 2026 00:11:22 +0530
Subject: [PATCH 24/54] =?UTF-8?q?feat(profiles):=20User=20Profiles=20v1=20?=
=?UTF-8?q?=E2=80=94=20SDK=20methods=20+=20docs=20(#7340)?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Co-authored-by: Pratik <10096516+pratikgajjar@users.noreply.github.com>
Co-authored-by: Claude Opus 4.8 (1M context)
---
.../profiles/generate-profiles.mdx | 5 +
.../profiles/get-profile-job.mdx | 5 +
.../profiles/get-profile-settings.mdx | 5 +
docs/api-reference/profiles/get-profile.mdx | 5 +
.../profiles/update-profile-settings.mdx | 5 +
docs/changelog/sdk.mdx | 14 +
docs/docs.json | 12 +
docs/llms.txt | 6 +
docs/openapi.json | 476 ++++++++++-
docs/platform/features/user-profiles.mdx | 359 ++++++++
examples/notebooks/user-profiles.ipynb | 764 ++++++++++++++++++
mem0-ts/package.json | 2 +-
mem0-ts/src/client/index.ts | 8 +
mem0-ts/src/client/mem0.ts | 206 ++++-
mem0-ts/src/client/mem0.types.ts | 95 +++
.../tests/memoryClient.profiles.test.ts | 341 ++++++++
mem0-ts/src/client/utils.ts | 3 +
mem0/client/main.py | 384 ++++++++-
pyproject.toml | 2 +-
tests/test_client_profiles.py | 272 +++++++
20 files changed, 2961 insertions(+), 8 deletions(-)
create mode 100644 docs/api-reference/profiles/generate-profiles.mdx
create mode 100644 docs/api-reference/profiles/get-profile-job.mdx
create mode 100644 docs/api-reference/profiles/get-profile-settings.mdx
create mode 100644 docs/api-reference/profiles/get-profile.mdx
create mode 100644 docs/api-reference/profiles/update-profile-settings.mdx
create mode 100644 docs/platform/features/user-profiles.mdx
create mode 100644 examples/notebooks/user-profiles.ipynb
create mode 100644 mem0-ts/src/client/tests/memoryClient.profiles.test.ts
create mode 100644 tests/test_client_profiles.py
diff --git a/docs/api-reference/profiles/generate-profiles.mdx b/docs/api-reference/profiles/generate-profiles.mdx
new file mode 100644
index 000000000..e5de5a12d
--- /dev/null
+++ b/docs/api-reference/profiles/generate-profiles.mdx
@@ -0,0 +1,5 @@
+---
+title: 'Generate Profiles'
+description: "Start one generation: sample a few entities, or build one for a single entity."
+openapi: post /v2/profiles/jobs/
+---
diff --git a/docs/api-reference/profiles/get-profile-job.mdx b/docs/api-reference/profiles/get-profile-job.mdx
new file mode 100644
index 000000000..c24e86794
--- /dev/null
+++ b/docs/api-reference/profiles/get-profile-job.mdx
@@ -0,0 +1,5 @@
+---
+title: 'Get Generation Job'
+description: "Read the progress of a generation, and whether it finished."
+openapi: get /v2/profiles/jobs/{job_id}/
+---
diff --git a/docs/api-reference/profiles/get-profile-settings.mdx b/docs/api-reference/profiles/get-profile-settings.mdx
new file mode 100644
index 000000000..82eb1b37b
--- /dev/null
+++ b/docs/api-reference/profiles/get-profile-settings.mdx
@@ -0,0 +1,5 @@
+---
+title: 'Get Profile Settings'
+description: "Retrieve the profile schema, custom instructions, and enabled flag for the current project."
+openapi: get /v2/profiles/settings/
+---
diff --git a/docs/api-reference/profiles/get-profile.mdx b/docs/api-reference/profiles/get-profile.mdx
new file mode 100644
index 000000000..604535a3c
--- /dev/null
+++ b/docs/api-reference/profiles/get-profile.mdx
@@ -0,0 +1,5 @@
+---
+title: 'Get Profile'
+description: "Retrieve the structured profile for a user, with a status describing whether generation has completed."
+openapi: get /v2/entities/{entity_type}/{entity_id}/profile/
+---
diff --git a/docs/api-reference/profiles/update-profile-settings.mdx b/docs/api-reference/profiles/update-profile-settings.mdx
new file mode 100644
index 000000000..e33dc9198
--- /dev/null
+++ b/docs/api-reference/profiles/update-profile-settings.mdx
@@ -0,0 +1,5 @@
+---
+title: 'Update Profile Settings'
+description: "Set the JSON Schema, custom instructions, or enabled flag that control profile generation for the project."
+openapi: post /v2/profiles/settings/
+---
diff --git a/docs/changelog/sdk.mdx b/docs/changelog/sdk.mdx
index 008e58b9f..bf53c5d31 100644
--- a/docs/changelog/sdk.mdx
+++ b/docs/changelog/sdk.mdx
@@ -7,6 +7,13 @@ mode: "wide"
+
+
+**New Features:**
+- **Client:** Add User Profiles to `MemoryClient` and `AsyncMemoryClient`: `get_profile()`, `generate_profile()`, `get_profile_settings()`, `update_profile_settings()`, `sample_profiles()`, and `get_profile_job()`. A profile is a structured, always-current JSON summary of one user, shaped by a JSON Schema you configure per project and filled by an LLM from that user's memories. Generation is asynchronous. Every job POST carries an `Idempotency-Key`; to retry a lost request without starting a second job, pass the same `idempotency_key` on each attempt ([#7340](https://github.com/mem0ai/mem0/pull/7340))
+
+
+
**Improvements:**
@@ -1235,6 +1242,13 @@ See the [OSS v2 to v3 migration guide](https://docs.mem0.ai/migration/oss-v2-to-
+
+
+**New Features:**
+- **Client:** Add User Profiles to `MemoryClient`: `getProfile()`, `generateProfile()`, `getProfileSettings()`, `updateProfileSettings()`, `sampleProfiles()`, and `getProfileJob()`. A profile is a structured, always-current JSON summary of one user, shaped by a JSON Schema you configure per project and filled by an LLM from that user's memories. Generation is asynchronous. Every job POST carries an `Idempotency-Key`; to retry a lost request without starting a second job, pass the same `idempotencyKey` on each attempt ([#7340](https://github.com/mem0ai/mem0/pull/7340))
+
+
+
**Improvements:**
diff --git a/docs/docs.json b/docs/docs.json
index 7aecc007c..969ebad35 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -72,6 +72,7 @@
"pages": [
"platform/features/v2-memory-filters",
"platform/features/entity-scoped-memory",
+ "platform/features/user-profiles",
"platform/features/graph-memory",
"platform/features/async-client",
"platform/features/multimodal-support",
@@ -513,6 +514,17 @@
"api-reference/entities/delete-user"
]
},
+ {
+ "group": "Profiles",
+ "icon": "id-card",
+ "pages": [
+ "api-reference/profiles/get-profile",
+ "api-reference/profiles/get-profile-settings",
+ "api-reference/profiles/update-profile-settings",
+ "api-reference/profiles/generate-profiles",
+ "api-reference/profiles/get-profile-job"
+ ]
+ },
{
"group": "Organizations",
"icon": "building",
diff --git a/docs/llms.txt b/docs/llms.txt
index ce60e29f5..2a939cbe3 100644
--- a/docs/llms.txt
+++ b/docs/llms.txt
@@ -198,6 +198,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.
@@ -364,6 +365,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.
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/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/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/mem0-ts/package.json b/mem0-ts/package.json
index b0490dd2e..3bb996079 100644
--- a/mem0-ts/package.json
+++ b/mem0-ts/package.json
@@ -1,6 +1,6 @@
{
"name": "mem0ai",
- "version": "3.2.0",
+ "version": "3.3.0",
"description": "The Memory Layer For Your AI Apps",
"main": "./dist/index.js",
"module": "./dist/index.mjs",
diff --git a/mem0-ts/src/client/index.ts b/mem0-ts/src/client/index.ts
index 24ec5b8f4..138b29dc7 100644
--- a/mem0-ts/src/client/index.ts
+++ b/mem0-ts/src/client/index.ts
@@ -23,6 +23,14 @@ export type {
FeedbackPayload,
CreateMemoryExportPayload,
GetMemoryExportPayload,
+ ProfileEntityType,
+ ProfileStatus,
+ ProfileResponse,
+ ProfileJobResponse,
+ ProfileJobStatus,
+ ProfileSettings,
+ ProfileSettingsResponse,
+ EntityProfileSettings,
} from "./mem0.types";
// Re-export enums as values (not type-only)
diff --git a/mem0-ts/src/client/mem0.ts b/mem0-ts/src/client/mem0.ts
index 33e03f0c2..0f8725164 100644
--- a/mem0-ts/src/client/mem0.ts
+++ b/mem0-ts/src/client/mem0.ts
@@ -1,4 +1,5 @@
import axios from "axios";
+import { v7 as uuidv7 } from "uuid";
import {
AllUsers,
PaginatedMemories,
@@ -20,6 +21,12 @@ import {
FeedbackPayload,
CreateMemoryExportPayload,
GetMemoryExportPayload,
+ ProfileEntityType,
+ ProfileResponse,
+ ProfileJobResponse,
+ ProfileJobStatus,
+ ProfileSettings,
+ ProfileSettingsResponse,
} from "./mem0.types";
import {
captureClientEvent,
@@ -92,6 +99,9 @@ interface ClientIdentity {
}
// Shares one ping per (host, api key) across clients; FIFO-capped.
+// One collection for every generation; the operation is a body field.
+const PROFILE_JOBS_PATH = "/v2/profiles/jobs/";
+
const IDENTITY_CACHE_MAX_DEFAULT = 50;
const identityByCredentials = new Map>();
@@ -305,7 +315,8 @@ export default class MemoryClient {
});
}
- async _fetchWithErrorHandling(url: string, options: any): Promise {
+ /** Fetch with no key conversion, for payloads carrying user-controlled property names. */
+ async _fetchRawJson(url: string, options: any): Promise {
const response = await fetch(url, {
...options,
headers: {
@@ -318,8 +329,11 @@ export default class MemoryClient {
const errorData = await response.text();
throw createExceptionFromResponse(response.status, errorData);
}
- const jsonResponse = await response.json();
- return snakeToCamelKeys(jsonResponse);
+ return response.json();
+ }
+
+ async _fetchWithErrorHandling(url: string, options: any): Promise {
+ return snakeToCamelKeys(await this._fetchRawJson(url, options));
}
_preparePayload(
@@ -816,6 +830,192 @@ export default class MemoryClient {
return response;
}
+ /**
+ * Get the memory profile for a single user.
+ *
+ * Branch on `status`, not on an empty `profile`: generation is asynchronous,
+ * so a known user without a profile yet is a normal response.
+ */
+ async getProfile(data: { entityId: string }): Promise {
+ this._captureEvent("get_profile", []);
+ await this._awaitIdentity();
+
+ const response = await this._fetchWithErrorHandling(
+ `${this.host}/v2/entities/user/${encodeURIComponent(data.entityId)}/profile/`,
+ {
+ headers: this.headers,
+ },
+ );
+ return response;
+ }
+
+ /**
+ * Generate or refresh the profile for one user, now.
+ *
+ * Profiles are otherwise built once a user crosses an internal message
+ * threshold, so a new user has none for its first few memories. Returns as
+ * soon as the work is queued: poll {@link getProfile} and branch on `status`.
+ *
+ * Pass `idempotencyKey` and reuse it to retry a lost request without starting
+ * (and being billed for) a second job.
+ */
+ async generateProfile(data: {
+ entityId: string;
+ idempotencyKey?: string;
+ }): Promise {
+ this._captureEvent("generate_profile", []);
+ await this._awaitIdentity();
+
+ const response = await this._fetchWithErrorHandling(
+ `${this.host}${PROFILE_JOBS_PATH}`,
+ {
+ method: "POST",
+ headers: {
+ ...this.headers,
+ "Idempotency-Key": data.idempotencyKey ?? uuidv7(),
+ },
+ body: JSON.stringify({
+ operation: "trigger",
+ entity_type: "user",
+ entity_id: data.entityId,
+ }),
+ },
+ );
+ return response;
+ }
+
+ /** Get the profile settings for the current project. */
+ async getProfileSettings(): Promise {
+ this._captureEvent("get_profile_settings", []);
+ await this._awaitIdentity();
+
+ const raw = await this._fetchRawJson(`${this.host}/v2/profiles/settings/`, {
+ headers: this.headers,
+ });
+ return this._settingsWithVerbatimSchema(raw);
+ }
+
+ /**
+ * The envelope keys are ours; the schema's property names are the customer's.
+ *
+ * Each entity type carries its own schema, so every one has to be restored
+ * from the raw body — otherwise camel-casing rewrites the customer's field
+ * names and a profile comes back under keys they never chose.
+ */
+ private _settingsWithVerbatimSchema(raw: any): ProfileSettingsResponse {
+ const settings = snakeToCamelKeys(raw) as ProfileSettingsResponse;
+ if (!raw || typeof raw !== "object") {
+ return settings;
+ }
+
+ const rawEntities = raw.entities;
+ if (rawEntities && typeof rawEntities === "object") {
+ for (const [entityType, entitySettings] of Object.entries(rawEntities)) {
+ if (
+ entitySettings &&
+ typeof entitySettings === "object" &&
+ "schema" in entitySettings &&
+ settings.entities?.[entityType as ProfileEntityType]
+ ) {
+ settings.entities[entityType as ProfileEntityType]!.schema = (
+ entitySettings as Record
+ ).schema;
+ }
+ }
+ }
+
+ return settings;
+ }
+
+ /**
+ * Update profile settings. Only the fields you pass are written.
+ *
+ * `schema` and `customInstructions` are per user and are nested under
+ * `entities` for the API; only `enabled` is project-wide. Sending them flat
+ * is rejected with `Unsupported settings`.
+ */
+ async updateProfileSettings(
+ settings: ProfileSettings,
+ ): Promise {
+ const payloadKeys = Object.keys(settings || {});
+ this._captureEvent("update_profile_settings", [payloadKeys]);
+ await this._awaitIdentity();
+
+ const { schema, customInstructions, enabled } = settings || {};
+
+ const body: Record = {};
+ if (enabled !== undefined) {
+ body.enabled = enabled;
+ }
+
+ const entitySettings: Record = {};
+ // The schema's property names are the customer's and must reach the API verbatim.
+ if (schema !== undefined) {
+ entitySettings.schema = schema;
+ }
+ if (customInstructions !== undefined) {
+ entitySettings.custom_instructions = customInstructions;
+ }
+ if (Object.keys(entitySettings).length > 0) {
+ body.entities = { user: entitySettings };
+ }
+
+ const raw = await this._fetchRawJson(`${this.host}/v2/profiles/settings/`, {
+ method: "POST",
+ headers: this.headers,
+ body: JSON.stringify(body),
+ });
+ return this._settingsWithVerbatimSchema(raw);
+ }
+
+ /**
+ * Generate profiles for a few real users, to check a schema.
+ *
+ * Real generations against real memories, and the results are kept: the
+ * profiles are written to those users and count toward usage.
+ */
+ async sampleProfiles(data?: {
+ limit?: number;
+ idempotencyKey?: string;
+ }): Promise {
+ this._captureEvent("sample_profiles", []);
+ await this._awaitIdentity();
+
+ const response = await this._fetchWithErrorHandling(
+ `${this.host}${PROFILE_JOBS_PATH}`,
+ {
+ method: "POST",
+ headers: {
+ ...this.headers,
+ "Idempotency-Key": data?.idempotencyKey ?? uuidv7(),
+ },
+ body: JSON.stringify({
+ operation: "sample",
+ // Required: the API refuses a job that does not name an entity kind.
+ entity_type: "user",
+ ...this._prepareParams({ limit: data?.limit }),
+ }),
+ },
+ );
+ return response;
+ }
+
+ /**
+ * Read one generation job. Accepts the `statusUrl` from a create call, or a
+ * bare job id. Prefer `statusUrl` so a route change needs no client update.
+ */
+ async getProfileJob(jobIdOrStatusUrl: string): Promise {
+ await this._awaitIdentity();
+
+ const path = jobIdOrStatusUrl.startsWith("/")
+ ? jobIdOrStatusUrl
+ : `${PROFILE_JOBS_PATH}${jobIdOrStatusUrl}/`;
+ return this._fetchWithErrorHandling(`${this.host}${path}`, {
+ method: "GET",
+ headers: this.headers,
+ });
+ }
+
async createMemoryExport(
data: CreateMemoryExportPayload,
): Promise<{ message: string; id: string }> {
diff --git a/mem0-ts/src/client/mem0.types.ts b/mem0-ts/src/client/mem0.types.ts
index cbe541321..606cf0daf 100644
--- a/mem0-ts/src/client/mem0.types.ts
+++ b/mem0-ts/src/client/mem0.types.ts
@@ -239,3 +239,98 @@ export interface GetMemoryExportPayload {
filters?: Record;
memoryExportId?: string;
}
+
+// ─── Profile Types ──────────────────────────────────────────
+
+/** The entity kind that carries a profile. */
+export type ProfileEntityType = "user";
+
+/**
+ * `succeeded` is the only state in which `profile` is guaranteed to hold content.
+ *
+ * These are values, not keys, so the client does not camel-case them: the wire
+ * spelling is what a comparison has to match.
+ */
+export type ProfileStatus =
+ | "succeeded"
+ | "pending"
+ | "failed"
+ | "not_enabled"
+ | "insufficient_data";
+
+export interface ProfileResponse {
+ /** Shaped by the project's schema; keys are not camel-cased. */
+ profile: Record;
+ status: ProfileStatus;
+ entityType: ProfileEntityType;
+ entityId: string;
+ updatedAt: string | null;
+ generationCount: number;
+ /** The last generation's failure reason, when `status` is `failed`. */
+ error?: string | null;
+}
+
+/** Every accepted generation. `statusUrl` is the server's own poll path. */
+export interface ProfileJobResponse {
+ jobId: string;
+ status: string;
+ statusUrl: string;
+ operation: string;
+ entityType: ProfileEntityType;
+ /** Entities reserved against usage for this job. */
+ entityCountReserved?: number;
+ /** Null when the job has no associated event. */
+ eventId?: string | null;
+ replayed?: boolean;
+ /** Sample runs only: how many entities were picked. */
+ sampled?: number;
+ /** Sample runs only: the entity ids picked. Read each one with `getProfile`. */
+ entityIds?: string[];
+}
+
+/** The settings to write. `schema` and `customInstructions` apply to user profiles. */
+export interface ProfileSettings {
+ /** Turn profile generation on or off. Project-wide. */
+ enabled?: boolean;
+ /** JSON Schema for the profile. Every property needs a `description`. */
+ schema?: Record | null;
+ customInstructions?: string | null;
+}
+
+/** One entity type's stored configuration. */
+export interface EntityProfileSettings {
+ /** The customer's JSON Schema, with its property names verbatim. */
+ schema?: Record | null;
+ customInstructions?: string | null;
+ [key: string]: any;
+}
+
+/**
+ * The settings as stored. `schema` and `customInstructions` are per entity
+ * type and nest under `entities`; only `enabled` is project-wide.
+ */
+export interface ProfileSettingsResponse {
+ enabled?: boolean;
+ entities?: Partial>;
+ capabilities?: Record;
+ [key: string]: any;
+}
+
+/** `GET /v2/profiles/jobs/{id}/`. The job nests under `job`. */
+export interface ProfileJobStatus {
+ job: {
+ id: string;
+ operation: string;
+ entityType: ProfileEntityType;
+ status: string;
+ /** Null until `enumerationComplete`. */
+ total: number | null;
+ enumerationComplete: boolean;
+ /** succeeded + failed + skipped. */
+ completed: number;
+ succeeded: number;
+ failed: number;
+ skipped: number;
+ [key: string]: any;
+ };
+}
diff --git a/mem0-ts/src/client/tests/memoryClient.profiles.test.ts b/mem0-ts/src/client/tests/memoryClient.profiles.test.ts
new file mode 100644
index 000000000..27069a570
--- /dev/null
+++ b/mem0-ts/src/client/tests/memoryClient.profiles.test.ts
@@ -0,0 +1,341 @@
+/**
+ * MemoryClient unit tests — profiles.
+ * Verifies request construction and the verbatim round-trip of user-controlled
+ * profile/schema keys, not mock response echo.
+ */
+import { MemoryClient } from "../mem0";
+import type { ProfileStatus } from "../mem0.types";
+import { TEST_API_KEY } from "./helpers";
+import {
+ setupMockFetch,
+ findFetchCall,
+ getFetchBody,
+ installConsoleSuppression,
+} from "./setup";
+
+installConsoleSuppression();
+
+describe("MemoryClient - getProfile()", () => {
+ test("reads the v2 entity route and keeps profile keys verbatim", async () => {
+ const extra = new Map();
+ extra.set("/v2/entities/user/alice/profile/", {
+ status: 200,
+ body: {
+ // Customer schema keys: camel-casing these would break the schema they wrote.
+ profile: {
+ favorite_topics: ["hiking"],
+ work_style: { preferred_hours: "mornings" },
+ },
+ status: "succeeded",
+ entity_type: "user",
+ entity_id: "alice",
+ updated_at: "2026-02-08T00:00:00Z",
+ generation_count: 3,
+ },
+ });
+ const mock = setupMockFetch(extra);
+
+ const client = new MemoryClient({ apiKey: TEST_API_KEY });
+ const result = await client.getProfile({ entityId: "alice" });
+
+ const call = findFetchCall(mock, "/v2/entities/user/alice/profile/");
+ expect(call).toBeDefined();
+
+ expect(result.profile).toEqual({
+ favorite_topics: ["hiking"],
+ work_style: { preferred_hours: "mornings" },
+ });
+ expect(result.entityType).toBe("user");
+ expect(result.entityId).toBe("alice");
+ expect(result.generationCount).toBe(3);
+ expect(result.status).toBe("succeeded");
+ });
+
+ test("status keeps its wire spelling", async () => {
+ // A status is a VALUE, not a key, so the client does not camel-case it.
+ // Declaring the union as `insufficientData` made tsc reject the comparison
+ // that works and accept one that can never be true.
+ const extra = new Map();
+ extra.set("/v2/entities/user/bob/profile/", {
+ status: 200,
+ body: {
+ profile: {},
+ status: "insufficient_data",
+ entity_type: "user",
+ entity_id: "bob",
+ },
+ });
+ setupMockFetch(extra);
+
+ const client = new MemoryClient({ apiKey: TEST_API_KEY });
+ const result = await client.getProfile({ entityId: "bob" });
+
+ expect(result.status).toBe("insufficient_data");
+ // Assignable without a cast: the declared union must contain the wire value.
+ const status: ProfileStatus = result.status;
+ expect(status).not.toBe("insufficientData");
+ });
+
+ test("scopes to user and encodes the entity id", async () => {
+ const extra = new Map();
+ extra.set("/v2/entities/user/", {
+ status: 200,
+ body: { profile: {}, status: "pending", entity_type: "user" },
+ });
+ const mock = setupMockFetch(extra);
+
+ const client = new MemoryClient({ apiKey: TEST_API_KEY });
+ await client.getProfile({ entityId: "a/b" });
+
+ const call = findFetchCall(mock, "/v2/entities/user/a%2Fb/profile/");
+ expect(call).toBeDefined();
+ });
+});
+
+describe("MemoryClient - generateProfile()", () => {
+ test("sends operation trigger with the entity to the jobs collection", async () => {
+ const extra = new Map();
+ extra.set("/v2/profiles/jobs/", {
+ status: 202,
+ body: {
+ job_id: "00000000-0000-7000-8000-000000000001",
+ status: "QUEUED",
+ status_url: "/v2/profiles/jobs/00000000-0000-7000-8000-000000000001/",
+ operation: "trigger",
+ entity_type: "user",
+ entity_count_reserved: 1,
+ event_id: "00000000-0000-7000-8000-000000000002",
+ replayed: false,
+ },
+ });
+ const mock = setupMockFetch(extra);
+
+ const client = new MemoryClient({ apiKey: TEST_API_KEY });
+ const result = await client.generateProfile({ entityId: "alice" });
+
+ const call = findFetchCall(mock, "/v2/profiles/jobs/", "POST");
+ expect(call).toBeDefined();
+ const body = getFetchBody(call!);
+ expect(body.operation).toBe("trigger");
+ expect(body.entity_type).toBe("user");
+ expect(body.entity_id).toBe("alice");
+ // A generated Idempotency-Key is always sent so the create can be retried safely.
+ const headers = call![1].headers as Record