Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b8f7e1dc6e | ||
|
|
2ef6291307 |
@@ -10,9 +10,9 @@
|
||||
"plugins": [
|
||||
{
|
||||
"name": "mem0",
|
||||
"source": "./integrations/claude-code-plugin",
|
||||
"description": "Cross-session memory and token savings for coding agents.",
|
||||
"version": "0.3.0"
|
||||
"source": "./integrations/mem0-plugin",
|
||||
"description": "Mem0 memory layer for AI applications. Add persistent memory, personalization, and semantic search to Claude workflows.",
|
||||
"version": "0.2.14"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
"name": "mem0",
|
||||
"source": "./integrations/mem0-plugin",
|
||||
"description": "Mem0 memory layer for AI applications. Add persistent memory, personalization, and semantic search.",
|
||||
"version": "0.2.15"
|
||||
"version": "0.2.14"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
+6
-60
@@ -18,21 +18,15 @@ Package workflows keep their own push-to-main and manual triggers. Their `pull_r
|
||||
| Python CLI | `cli-python-ci.yml` | Push to main (`cli/python/`), manual | Ruff + pytest + hatch build on Python 3.10, 3.11, 3.12 |
|
||||
| Node CLI | `cli-node-ci.yml` | Push to main (`cli/node/`), manual | Biome + tsc + vitest + tsup on Node 20, 22 |
|
||||
| OpenClaw | `openclaw-checks.yml` | Push to main (`integrations/openclaw/`), manual | tsc + vitest (Codecov) + tsup on Node 20, 22 |
|
||||
| Mem0 Plugin (legacy) | `mem0-plugin-checks.yml` | Push to main (`integrations/mem0-plugin/`, excluding `.opencode-plugin/`), manual | pytest + hook exec bits + JSON manifest validation on Python 3.10, 3.11, 3.12 |
|
||||
| Claude Code Plugin | `claude-code-plugin-checks.yml` | Push to main (`integrations/claude-code-plugin/`), manual | pytest + ruff + JSON manifest validation on Python 3.10, 3.11, 3.12 |
|
||||
| Mem0 Plugin | `mem0-plugin-checks.yml` | Push to main (`integrations/mem0-plugin/`, excluding `.opencode-plugin/`), manual | pytest + hook exec bits + JSON manifest validation on Python 3.10, 3.11, 3.12 |
|
||||
| OpenCode Plugin | `opencode-plugin-checks.yml` | Push to main (`.opencode-plugin/`), manual | Bun: tsc + build + dist artifact check |
|
||||
| Pi Agent Plugin | `pi-agent-plugin-checks.yml` | Push to main (`integrations/pi-agent-plugin/`), manual | tsc + vitest + tsup on Node 20, 22 |
|
||||
| DeepSeek Harness Plugin | `deepseek-plugin-checks.yml` | Push to main (`integrations/deepseek-plugin/`), manual | tsc + vitest + tsup on Node 20, 22 |
|
||||
| n8n Node | `n8n-nodes-mem0-checks.yml` | Push to main (`integrations/n8n-nodes-mem0/`), manual | ESLint + tsc build on Node 20 |
|
||||
| Zapier App | `zapier-mem0-checks.yml` | Push to main (`integrations/zapier-mem0/`), manual | tsc + `zapier validate` + offline unit tests on Node 22 |
|
||||
| mem0-strands | `mem0-strands-checks.yml` | Push to main (`integrations/mem0-strands/`), manual | Ruff + mypy + pytest + hatch build on Python 3.10, 3.11, 3.12 |
|
||||
| docs llms.txt | `docs-llms-txt-check.yml` | Manual | `docs/llms.txt` coverage |
|
||||
| GitHub Scripts | inline in `ci-gate.yml` | none | `node` over every `.github/scripts/*.test.js` |
|
||||
|
||||
Adding a package CI workflow: give it `workflow_call` plus `push` / `workflow_dispatch` as needed but **no `pull_request` trigger**, then register it in `ci-gate.yml` with a path filter under the `changes` job, a call job, and an entry in the gate job's `needs` list.
|
||||
|
||||
`GitHub Scripts` is the one row that is a plain job inside `ci-gate.yml` rather than a called workflow, because a reusable workflow wrapping two `node` invocations would be more file than test. It runs on the `github_scripts` filter, which covers `.github/scripts/**` plus every file those tests read: `pr-gate.yml`, `vouch-check-pr.yml`, `issue-labeler.yml`, and `VOUCHED.td`. Add a new `.github/scripts/*.test.js` and it is picked up with no wiring; make a test read a new file and that file belongs in the filter.
|
||||
|
||||
## Branch protection on `main`
|
||||
|
||||
A repository ruleset named `Main Branch Rule`, id `11813754`. It enforces squash-only merges, linear history, no deletion, no force-push, and one approving review. Two status checks belong in its `required_status_checks` rule:
|
||||
@@ -61,9 +55,7 @@ Requiring `CI Gate` also means fork PRs from first-time contributors cannot merg
|
||||
| OpenClaw | `openclaw-cd.yml` | `openclaw-v*` | npm (`@mem0/openclaw-mem0`) |
|
||||
| OpenCode Plugin | `opencode-plugin-cd.yml` | `opencode-v*` | npm (`@mem0/opencode-plugin`) |
|
||||
| Pi Agent Plugin | `pi-agent-plugin-cd.yml` | `pi-agent-v*` | npm (`@mem0/pi-agent-plugin`) |
|
||||
| DeepSeek Harness Plugin | `deepseek-plugin-cd.yml` | `deepseek-plugin-v*` | npm (`@mem0/deepseek-plugin`) |
|
||||
| n8n Node | `n8n-nodes-mem0-cd.yml` | `n8n-nodes-mem0-v*` | npm (`@mem0/n8n-nodes-mem0`) |
|
||||
| mem0-strands | `mem0-strands-cd.yml` | `mem0-strands-v*` | PyPI (`mem0-strands`) |
|
||||
|
||||
- Package CD workflows are `workflow_dispatch`-only, with `tag` and `prerelease` inputs. They check out and build the given tag.
|
||||
- All publishing uses **OIDC trusted publishing**. No tokens, no secrets.
|
||||
@@ -77,9 +69,9 @@ Requiring `CI Gate` also means fork PRs from first-time contributors cannot merg
|
||||
|
||||
| Workflow | File | Purpose |
|
||||
|----------|------|---------|
|
||||
| PR Gate | `pr-gate.yml` | Closes PRs that do not link an issue labeled `accepted`, and reopens them when that label arrives. Exempts members, bots, drafts, and docs-only changes. Never checks out PR code. |
|
||||
| Vouch (check PR) | `vouch-check-pr.yml` | Closes PRs from authors denounced in `VOUCHED.td`. Comments once on PRs from authors merely absent from it, and blocks nothing in that case. |
|
||||
| Vouch (manage list) | `vouch-manage-by-issue.yml` | Maintainers edit the trust list by commenting `!vouch @user`, `!denounce @user`, or `!unvouch @user` on any issue. Opens a PR against `VOUCHED.td` through a GitHub App token, for a maintainer to merge. |
|
||||
| PR Gate | `pr-gate.yml` | Closes PRs that do not link an issue labeled `accepted`, with a reopen path. Exempts members, bots, drafts, and docs-only changes. Never checks out PR code. |
|
||||
| Vouch (check PR) | `vouch-check-pr.yml` | Comments on PRs from authors absent from `VOUCHED.td`. Comment-only mode (`auto-close: false`). |
|
||||
| Vouch (manage list) | `vouch-manage-by-issue.yml` | Maintainers edit the trust list by commenting `!vouch @user`, `!denounce @user`, or `!unvouch @user` on any issue. Commits back to `VOUCHED.td` through a GitHub App token. |
|
||||
| Issue Labeler | `issue-labeler.yml` | Labels issues from the `component` field in the issue forms |
|
||||
| PR Labeler | `pr-labeler.yml` | Path-based labels, plus propagating labels from linked issues |
|
||||
| Stale Bot | `stale.yml` | Marks stale issues and PRs |
|
||||
@@ -87,53 +79,7 @@ Requiring `CI Gate` also means fork PRs from first-time contributors cannot merg
|
||||
|
||||
`pr-gate.yml` and `vouch-check-pr.yml` use `pull_request_target`, which is required to label and close fork PRs. Neither checks out PR code and neither has a `run:` step, so there is no pwn-request or script-injection surface. Keep it that way: any future `run:` step in these files must never interpolate `github.event.*` text.
|
||||
|
||||
Both workflows exempt maintainers twice, and the second guard is the one that holds. `author_association` is rendered for the viewer, and a webhook payload has no privileged viewer: `MEMBER` needs the author's org membership to be **public**, `COLLABORATOR` needs a **direct** repository invite. An org member with private membership whose `maintain` comes through a team matches neither and arrives as `CONTRIBUTOR`, which is how PR #6948 was closed by its own author's gate. So the guard also skips any PR whose head branch lives in this repository (`head.repo.full_name == github.repository`). Pushing a branch here already requires write access and outside contributors always arrive from a fork, so that test means the same thing without depending on who is looking. Keep both: the `author_association` arm still covers members who work from their own fork.
|
||||
|
||||
`pr-gate.yml` carries two jobs whose `if:` conditions are deliberately disjoint. `gate` closes, and only ever runs on `opened`, `reopened`, and `ready_for_review`. `reopen` reopens, and only ever runs on `edited` or on `issues: labeled` with the `accepted` label. Nothing can both close and reopen on the same event, which is the property to preserve when editing either guard.
|
||||
|
||||
That split exists because the two halves of a gated PR's recovery arrive in either order. A maintainer usually labels the issue `accepted` at triage, before the author has linked it; sometimes the link lands first and the label follows. So `reopen` handles both directions. From `issues: labeled` it walks `closedByPullRequestsReferences` back to the pull requests that link the issue. From `edited` it takes the edited pull request directly. Both paths then apply the same four tests: the author is not denounced in `VOUCHED.td`, the PR is `CLOSED`, it links an issue labeled `accepted`, and it carries the `<!-- pr-gate -->` marker comment. Without the label path, a maintainer's label is inert. Without the `edited` path, an author who links the issue after it was labeled is stuck, since no other event fires.
|
||||
|
||||
The denounce test is what keeps the two gates from cancelling each other out. A denounced author whose PR also lacked an accepted issue was closed by both workflows, so it carries the `<!-- pr-gate -->` marker, and labeling the linked issue would otherwise reopen it. Vouch cannot undo that: reopening runs through `GITHUB_TOKEN`, which raises no events, so `vouch-check-pr.yml` never fires a second time. Reading the list here is the only place the check can live. It fails open like vouch does, warning and treating nobody as denounced if the file cannot be read, and it is the one piece of vouch semantics duplicated outside `vouch-check-pr.yml`, because `pr-gate.yml` never checks out the repository and so cannot import a shared parser. `.github/scripts/vouch-decision.test.js` covers the parsing and asserts `pr-gate.yml` still filters the list the same way.
|
||||
|
||||
`edited` must never reach the `gate` job. It fires on any title or description change, so when `gate` listened for it the gate re-judged pull requests that had been open for days and closed them the moment their author touched the description, which is what closed #6948. Rescuing on `edited` is safe for the same reason closing on it was not: the job can only move a PR from closed to open.
|
||||
|
||||
Reopening runs through `GITHUB_TOKEN`, which by design raises no further workflow events, so `gate` cannot bounce a freshly reopened PR straight back out.
|
||||
|
||||
The concurrency group is keyed on `github.event.action` as well as `github.event_name` and the number, and both keys carry weight. Without the event name, a maintainer applying `bug` right after `accepted` cancels the reopen mid-flight, since `cancel-in-progress` is on for `pull_request_target` and both label events would land in the same group. Without the action, `opened` and `edited` share a group on the same pull request, and an author who ticks a template checkbox in the seconds after opening cancels the run that was about to gate them: `gate` skips `edited` and `reopen` skips an open pull request, so the cancelled run is never replaced and the pull request stays ungated forever, since `opened` fires exactly once. Rapid successive edits still cancel each other, which is the dedup that was wanted.
|
||||
|
||||
The `edited` arm of `reopen` requires `github.event.pull_request.state == 'closed'`, so ordinary description edits on open pull requests do not start a runner.
|
||||
|
||||
Two known gaps, both mild. A PR that the gate closed, that someone reopened, and that a maintainer then closed deliberately still carries the marker, so labeling its issue reopens it again; a maintainer closes it once more. And an author who strips `Closes #<number>` out after passing keeps an open PR, which a reviewer sees anyway.
|
||||
|
||||
`GATE_EFFECTIVE_FROM` in `pr-gate.yml` is a `created_at` cutoff. `reopened` and `ready_for_review` still fire on PRs opened long before the gate existed, so without the cutoff part of the open backlog would be closed by a rule that did not exist when those PRs were filed. Set it to the actual merge date in UTC.
|
||||
|
||||
The gate's docs-only exemption covers `docs/` plus a named allowlist of four root files: `README.md`, `CONTRIBUTING.md`, `CODE_OF_CONDUCT.md`, and `SECURITY.md`. It is an allowlist rather than a rule about top-level markdown because the repository root also holds `AGENTS.md`, `CLAUDE.md`, and `LLM.md`, which are the instructions coding agents read before touching this codebase. Those are functional files that happen to be written in prose, and rewriting them is a change to behaviour, so they stay gated. Markdown nested anywhere else stays gated for the same reason: `skills/**/*.md` and everything under `.github/` are functional too. Adding a genuinely prose root file means adding it to `rootDocs` in `pr-gate.yml`.
|
||||
|
||||
`.github/scripts/pr-gate-docs-exemption.test.js` covers that predicate. It pulls the `rootDocs` and `isDocs` lines out of `pr-gate.yml` and evaluates them, so it exercises the shipped rule rather than a copy that could drift from it, and it pins `AGENTS.md`, `CLAUDE.md`, and `LLM.md` on the gated side along with `skills/**/*.md`, nested `.github/` files, and the empty file list. It only accepts those two declarations in a literal one-line form, so keep `rootDocs` a `Set` of quoted names and `isDocs` a single arrow expression.
|
||||
|
||||
The two contribution gates answer different questions and neither covers for the other. `pr-gate.yml` judges the change, and the `accepted` label is how a maintainer says yes to it. `vouch-check-pr.yml` judges the author, and `VOUCHED.td` is how a maintainer says no to one. A vouched author with no accepted issue is still closed by the gate; a denounced author with an accepted issue is still closed by vouch. Read either one as a backstop for the other and both get weakened.
|
||||
|
||||
Vouch enforces on the denounce axis only, through `require-vouch: false` with `auto-close: true`. That pair is not the obvious reading of either input, so the decision table from v1.5.0 (`vouch/github.nu` at pinned SHA `d66fa29`) is worth stating outright:
|
||||
|
||||
| Author | `status` | Effect |
|
||||
|---|---|---|
|
||||
| ends in `[bot]` | `skipped` | nothing |
|
||||
| collaborator with write or admin | `vouched` | nothing |
|
||||
| listed in `VOUCHED.td` | `vouched` | nothing |
|
||||
| listed as `-handle` | `closed` | action comments and closes |
|
||||
| absent from the file | `allowed` | workflow comments, nothing closed |
|
||||
|
||||
`require-vouch: true` would close every first-time contributor, which is the opposite of what a trust list is for: the funnel has to stay open or nobody ever earns a vouch. `auto-close: false` is the setting that looked safe and did nothing at all, since in v1.5.0 both the unvouched and the denounced branch return before posting anything, leaving only a line in the run log. That is why `!denounce` was decorative until this pair landed.
|
||||
|
||||
Only the `allowed` arm is ours: a `github-script` step posts the soft comment, keyed on a `<!-- vouch-check -->` marker so a reopen does not comment twice. The `closed` arm belongs to the action, message and all. Keeping the two arms disjoint is what stops a denounced author getting two comments, so if that step is ever re-keyed off `allowed`, check the overlap first.
|
||||
|
||||
`.github/scripts/vouch-decision.test.js` holds that table as a `decide()` function and asserts the workflow's `require-vouch`, `auto-close`, and comment-step gating still produce it, comment counts included. Be clear about what that does and does not prove. `decide()` is a **hand transcription** of `gh-check-pr`, read from `vouch/github.nu` at the pinned SHA; the test cannot run the action, so it cannot notice the action changing underneath it. Left alone it would agree with itself forever, which makes bumping the pinned SHA the one edit it would otherwise sail through. So it also asserts `vouch-check-pr.yml` still pins `PINNED_VOUCH_SHA`, and a bump fails it on purpose: re-read `gh-check-pr` at the new revision, correct `decide()` and the table above, then move the constant. CI runs it through the `GitHub Scripts` job on any change to the scripts or the files they read.
|
||||
|
||||
Failure is open by design. If the action cannot read `VOUCHED.td` it falls back to an empty list, every author reads as absent, and nobody is closed by an API hiccup.
|
||||
|
||||
`vouch-manage-by-issue.yml` runs with `merge-immediately: "false"`. The `Main Branch Rule` ruleset requires one approving review and has no bypass actors, so the action's immediate `PUT /pulls/{n}/merge` would return 405 and leave `VOUCHED.td` unchanged on `main`. The bot opens the PR, a maintainer merges it. Setting `pull-request: "false"` is not an alternative: the same ruleset blocks direct pushes.
|
||||
|
||||
That workflow also needs `VOUCH_APP_ID` and `VOUCH_APP_PRIVATE_KEY` repository secrets. Without them it fails at the token step before doing anything. `vouch-check-pr.yml` needs neither.
|
||||
`GATE_EFFECTIVE_FROM` in `pr-gate.yml` is a `created_at` cutoff. `edited`, `reopened`, and `ready_for_review` fire on PRs opened long before the gate existed, so without the cutoff the whole open backlog would be closed by a rule that did not exist when those PRs were filed. Set it to the actual merge date in UTC.
|
||||
|
||||
## Issue forms and templates
|
||||
|
||||
@@ -153,4 +99,4 @@ Current field ids:
|
||||
|
||||
`VOUCHED.td` is one GitHub username per line, `#` for comments. Seeded from every author with at least one merged PR in this repository, then filtered: accounts at or below a 16% merge rate across five or more attempts were dropped, since landing one change out of many is the signature of automated submission rather than contribution.
|
||||
|
||||
Vouch's only built-in exemptions are accounts ending in `[bot]` and repo collaborators with `write` or `admin`. **Organization membership alone is not one of them.** So `vouch-check-pr.yml` carries a job-level `if:` that skips the check for `OWNER`, `MEMBER`, and `COLLABORATOR` authors, the same exemption `pr-gate.yml` already applies. Org members are still listed in the file as a fallback, but the workflow guard is what actually holds.
|
||||
Vouch's only built-in exemptions are accounts ending in `[bot]` and repo collaborators with `write` or `admin`. **Organization membership alone is not one of them.** So `vouch-check-pr.yml` carries a job-level `if:` that skips the check for `OWNER`, `MEMBER`, and `COLLABORATOR` authors, the same exemption `pr-gate.yml` already applies. `author_association` is `MEMBER` for every org member regardless of repository permission, so no member can be flagged even if their `VOUCHED.td` entry is missing, misspelled, or miscased. Org members are still listed in the file as a fallback, but the workflow guard is what actually holds.
|
||||
|
||||
+6
-20
@@ -1,29 +1,15 @@
|
||||
# The list of vouched (or denounced) users for this repository.
|
||||
#
|
||||
# A denounced user (prefixed with a minus) is blocked outright: their pull
|
||||
# requests are closed on sight, whatever they link. Being absent from this file
|
||||
# blocks nothing. An unvouched author gets one comment saying so and their pull
|
||||
# request is reviewed like anyone else's, because a first contribution has to
|
||||
# start somewhere. Vouching is how that comment stops.
|
||||
#
|
||||
# This list is about who, and it is the only thing that judges who. Whether a
|
||||
# change is wanted is a separate question, answered by the accepted label and
|
||||
# enforced by pr-gate.yml. Neither gate substitutes for the other: a vouched
|
||||
# author still needs an accepted issue, and a denounced author is turned away
|
||||
# even holding one.
|
||||
# Only vouched users can open pull requests here. A denounced user (prefixed
|
||||
# with a minus) is blocked outright.
|
||||
#
|
||||
# Vouch automatically allows two kinds of account without consulting this file:
|
||||
# accounts ending in [bot], and repo collaborators with write or admin
|
||||
# permission. Org membership on its own is NOT one of them, so
|
||||
# vouch-check-pr.yml skips the check for OWNER, MEMBER, and COLLABORATOR
|
||||
# authors, and for any branch pushed to this repository.
|
||||
#
|
||||
# Keep every mem0ai member listed below anyway. The author_association arm of
|
||||
# that guard is weaker than it looks: MEMBER needs the member's org membership
|
||||
# to be public and COLLABORATOR needs a direct repo invite, so a member with
|
||||
# private membership and a team-derived role reads as CONTRIBUTOR. Working from
|
||||
# a branch here covers them, working from their own fork leaves this file as
|
||||
# the only thing that does. A missing or miscased entry is a real gap.
|
||||
# vouch-check-pr.yml skips the check entirely for OWNER, MEMBER, and
|
||||
# COLLABORATOR authors. mem0ai org members are listed below as well, but that
|
||||
# workflow guard is what actually protects them: a missing, misspelled, or
|
||||
# miscased entry here can never cause a member to be flagged.
|
||||
#
|
||||
# Syntax:
|
||||
# - One handle per line (without @), sorted alphabetically.
|
||||
|
||||
@@ -1,60 +0,0 @@
|
||||
const assert = require('assert');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const gate = fs.readFileSync(path.join(__dirname, '..', 'workflows', 'pr-gate.yml'), 'utf8');
|
||||
|
||||
const rootDocsLine = gate.match(/^\s*(const rootDocs = new Set\(\['[\w.-]+'(?:, '[\w.-]+')*\]\);)\s*$/m);
|
||||
const isDocsLine = gate.match(/^\s*(const isDocs = \(\w+\) => [\w.'"()[\]\/, |&!=><+-]+;)\s*$/m);
|
||||
|
||||
assert.ok(
|
||||
rootDocsLine,
|
||||
'pr-gate.yml no longer declares rootDocs as a single-line Set of quoted filenames. ' +
|
||||
'This test evaluates that line to exercise the shipped predicate rather than a copy of it, ' +
|
||||
'and only accepts a literal shape, so widen the pattern deliberately or keep the declaration literal.',
|
||||
);
|
||||
assert.ok(
|
||||
isDocsLine,
|
||||
'pr-gate.yml no longer declares isDocs as a single-line arrow expression. ' +
|
||||
'This test evaluates that line to exercise the shipped predicate rather than a copy of it, ' +
|
||||
'and refuses anything with a statement body, so keep it an expression.',
|
||||
);
|
||||
|
||||
const isDocs = new Function(`${rootDocsLine[1]}\n${isDocsLine[1]}\nreturn isDocs;`)();
|
||||
|
||||
const exempt = (files) => files.length > 0 && files.every(isDocs);
|
||||
|
||||
const cases = [
|
||||
[['docs/a.mdx'], true],
|
||||
[['docs/platform/quickstart.mdx'], true],
|
||||
[['README.md'], true],
|
||||
[['CONTRIBUTING.md'], true],
|
||||
[['CODE_OF_CONDUCT.md'], true],
|
||||
[['SECURITY.md'], true],
|
||||
[['README.md', 'CONTRIBUTING.md', 'docs/x.mdx'], true],
|
||||
[['AGENTS.md'], false],
|
||||
[['CLAUDE.md'], false],
|
||||
[['LLM.md'], false],
|
||||
[['README.md', 'AGENTS.md'], false],
|
||||
[['README.md', 'mem0/memory/main.py'], false],
|
||||
[['skills/mem0/SKILL.md'], false],
|
||||
[['.github/AGENTS.md'], false],
|
||||
[['.github/workflows/ci.yml'], false],
|
||||
[['docs-site/index.md'], false],
|
||||
[[], false],
|
||||
];
|
||||
|
||||
let failures = 0;
|
||||
for (const [files, expected] of cases) {
|
||||
const actual = exempt(files);
|
||||
const label = files.length ? files.join(', ') : '(no files)';
|
||||
if (actual === expected) {
|
||||
console.log(`ok ${label} -> ${actual ? 'exempt' : 'gated'}`);
|
||||
} else {
|
||||
failures += 1;
|
||||
console.log(`FAIL ${label} -> ${actual ? 'exempt' : 'gated'}, expected ${expected ? 'exempt' : 'gated'}`);
|
||||
}
|
||||
}
|
||||
|
||||
console.log(failures === 0 ? '\nPASS' : `\nFAIL (${failures} cases)`);
|
||||
process.exit(failures === 0 ? 0 : 1);
|
||||
@@ -1,122 +0,0 @@
|
||||
const assert = require('assert');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const workflowPath = path.join(__dirname, '..', 'workflows', 'vouch-check-pr.yml');
|
||||
const workflow = fs.readFileSync(workflowPath, 'utf8');
|
||||
|
||||
const PINNED_VOUCH_SHA = 'd66fa29a64600490892131ad87597c30c91fcac4';
|
||||
|
||||
assert.ok(
|
||||
workflow.includes(`mitchellh/vouch/action/check-pr@${PINNED_VOUCH_SHA}`),
|
||||
`decide() below is a hand transcription of gh-check-pr from vouch/github.nu at ${PINNED_VOUCH_SHA} (v1.5.0). ` +
|
||||
'It reads the action, it does not run it, so on its own it agrees with itself whatever the action does. ' +
|
||||
'vouch-check-pr.yml now pins a different revision: re-read gh-check-pr there, update decide() and the ' +
|
||||
'decision table in .github/AGENTS.md to match it, then set PINNED_VOUCH_SHA to the new SHA.',
|
||||
);
|
||||
|
||||
const actionDefaults = { 'require-vouch': true, 'auto-close': false };
|
||||
|
||||
const booleanInput = (name) => {
|
||||
const match = workflow.match(new RegExp(`^\\s+${name}:\\s*"?(true|false)"?\\s*$`, 'm'));
|
||||
return match ? match[1] === 'true' : actionDefaults[name];
|
||||
};
|
||||
|
||||
const requireVouch = booleanInput('require-vouch');
|
||||
const autoClose = booleanInput('auto-close');
|
||||
|
||||
const commentedStatus = (() => {
|
||||
const match = workflow.match(/steps\.vouch\.outputs\.status == '(\w+)'/);
|
||||
assert.ok(match, 'the follow-up comment step is not keyed on a vouch status');
|
||||
return match[1];
|
||||
})();
|
||||
|
||||
const decide = (author) => {
|
||||
if (author === 'bot') return { status: 'skipped', closed: false, actionComments: false };
|
||||
if (author === 'collaborator' || author === 'vouched') {
|
||||
return { status: 'vouched', closed: false, actionComments: false };
|
||||
}
|
||||
if (author === 'denounced') {
|
||||
if (!autoClose) return { status: 'closed', closed: false, actionComments: false };
|
||||
return { status: 'closed', closed: true, actionComments: true };
|
||||
}
|
||||
if (!requireVouch) return { status: 'allowed', closed: false, actionComments: false };
|
||||
if (!autoClose) return { status: 'closed', closed: false, actionComments: false };
|
||||
return { status: 'closed', closed: true, actionComments: true };
|
||||
};
|
||||
|
||||
const outcome = (author) => {
|
||||
const result = decide(author);
|
||||
return { ...result, workflowComments: result.status === commentedStatus };
|
||||
};
|
||||
|
||||
const cases = [
|
||||
{ author: 'bot', closed: false, comments: 0 },
|
||||
{ author: 'collaborator', closed: false, comments: 0 },
|
||||
{ author: 'vouched', closed: false, comments: 0 },
|
||||
{ author: 'unvouched', closed: false, comments: 1 },
|
||||
{ author: 'denounced', closed: true, comments: 1 },
|
||||
];
|
||||
|
||||
let failures = 0;
|
||||
for (const expected of cases) {
|
||||
const actual = outcome(expected.author);
|
||||
const comments = Number(actual.actionComments) + Number(actual.workflowComments);
|
||||
try {
|
||||
assert.strictEqual(actual.closed, expected.closed, `${expected.author}: closed`);
|
||||
assert.strictEqual(comments, expected.comments, `${expected.author}: comment count`);
|
||||
console.log(`ok ${expected.author} -> ${actual.status}, closed=${actual.closed}, comments=${comments}`);
|
||||
} catch (error) {
|
||||
failures += 1;
|
||||
console.log(`FAIL ${expected.author} -> ${actual.status}, closed=${actual.closed}, comments=${comments}`);
|
||||
console.log(` ${error.message}: expected ${JSON.stringify(expected)}`);
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`\nvouch@${PINNED_VOUCH_SHA.slice(0, 7)} require-vouch=${requireVouch} auto-close=${autoClose} comment-on=${commentedStatus}`);
|
||||
|
||||
const parseDenounced = (contents) => new Set(contents
|
||||
.split('\n')
|
||||
.map((line) => line.trim())
|
||||
.filter((line) => line.startsWith('-'))
|
||||
.map((line) => line.slice(1).split(/\s+/)[0].split(':').pop().toLowerCase())
|
||||
.filter(Boolean));
|
||||
|
||||
const gate = fs.readFileSync(path.join(__dirname, '..', 'workflows', 'pr-gate.yml'), 'utf8');
|
||||
assert.ok(
|
||||
gate.includes(".filter((line) => line.startsWith('-'))"),
|
||||
'pr-gate.yml no longer parses the denounce list the way this test does',
|
||||
);
|
||||
|
||||
const vouched = fs.readFileSync(path.join(__dirname, '..', 'VOUCHED.td'), 'utf8');
|
||||
const denouncedNow = parseDenounced(vouched);
|
||||
const sample = parseDenounced([
|
||||
'# -notacomment is a comment line',
|
||||
'-SpamBot seeded 2026-08-12',
|
||||
'-github:OtherSpammer',
|
||||
'realcontributor',
|
||||
'',
|
||||
].join('\n'));
|
||||
|
||||
let parseFailures = 0;
|
||||
for (const [label, actual, expected] of [
|
||||
['denounce entry, with note', sample.has('spambot'), true],
|
||||
['denounce entry, platform prefixed', sample.has('otherspammer'), true],
|
||||
['comment line is not an entry', sample.has('notacomment'), false],
|
||||
['vouched entry is not denounced', sample.has('realcontributor'), false],
|
||||
['live file parses without throwing', denouncedNow instanceof Set, true],
|
||||
]) {
|
||||
try {
|
||||
assert.strictEqual(actual, expected, label);
|
||||
console.log(`ok ${label}`);
|
||||
} catch (error) {
|
||||
parseFailures += 1;
|
||||
console.log(`FAIL ${label}: ${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`denounced in VOUCHED.td: ${denouncedNow.size}`);
|
||||
|
||||
const total = failures + parseFailures;
|
||||
console.log(total === 0 ? 'PASS' : `FAIL (${total} assertions)`);
|
||||
process.exit(total === 0 ? 0 : 1);
|
||||
@@ -39,15 +39,11 @@ jobs:
|
||||
cli_node: ${{ steps.filter.outputs.cli_node }}
|
||||
openclaw: ${{ steps.filter.outputs.openclaw }}
|
||||
mem0_plugin: ${{ steps.filter.outputs.mem0_plugin }}
|
||||
claude_code_plugin: ${{ steps.filter.outputs.claude_code_plugin }}
|
||||
opencode_plugin: ${{ steps.filter.outputs.opencode_plugin }}
|
||||
pi_agent_plugin: ${{ steps.filter.outputs.pi_agent_plugin }}
|
||||
deepseek_plugin: ${{ steps.filter.outputs.deepseek_plugin }}
|
||||
n8n_nodes_mem0: ${{ steps.filter.outputs.n8n_nodes_mem0 }}
|
||||
zapier_mem0: ${{ steps.filter.outputs.zapier_mem0 }}
|
||||
mem0_strands: ${{ steps.filter.outputs.mem0_strands }}
|
||||
docs_llms_txt: ${{ steps.filter.outputs.docs_llms_txt }}
|
||||
github_scripts: ${{ steps.filter.outputs.github_scripts }}
|
||||
steps:
|
||||
- uses: dorny/paths-filter@v3
|
||||
id: filter
|
||||
@@ -83,10 +79,6 @@ jobs:
|
||||
- '!integrations/mem0-plugin/.opencode-plugin/**'
|
||||
- '.github/workflows/mem0-plugin-checks.yml'
|
||||
- '.github/workflows/ci-gate.yml'
|
||||
claude_code_plugin:
|
||||
- 'integrations/claude-code-plugin/**'
|
||||
- '.github/workflows/claude-code-plugin-checks.yml'
|
||||
- '.github/workflows/ci-gate.yml'
|
||||
opencode_plugin:
|
||||
- 'integrations/mem0-plugin/.opencode-plugin/**'
|
||||
- '.github/workflows/opencode-plugin-checks.yml'
|
||||
@@ -95,10 +87,6 @@ jobs:
|
||||
- 'integrations/pi-agent-plugin/**'
|
||||
- '.github/workflows/pi-agent-plugin-checks.yml'
|
||||
- '.github/workflows/ci-gate.yml'
|
||||
deepseek_plugin:
|
||||
- 'integrations/deepseek-plugin/**'
|
||||
- '.github/workflows/deepseek-plugin-checks.yml'
|
||||
- '.github/workflows/ci-gate.yml'
|
||||
n8n_nodes_mem0:
|
||||
- 'integrations/n8n-nodes-mem0/**'
|
||||
- '.github/workflows/n8n-nodes-mem0-checks.yml'
|
||||
@@ -106,10 +94,6 @@ jobs:
|
||||
- 'integrations/zapier-mem0/**'
|
||||
- '.github/workflows/zapier-mem0-checks.yml'
|
||||
- '.github/workflows/ci-gate.yml'
|
||||
mem0_strands:
|
||||
- 'integrations/mem0-strands/**'
|
||||
- '.github/workflows/mem0-strands-checks.yml'
|
||||
- '.github/workflows/ci-gate.yml'
|
||||
docs_llms_txt:
|
||||
- 'docs/**/*.mdx'
|
||||
- 'docs/llms.txt'
|
||||
@@ -117,13 +101,6 @@ jobs:
|
||||
- 'scripts/llms-txt-ignore.txt'
|
||||
- '.github/workflows/docs-llms-txt-check.yml'
|
||||
- '.github/workflows/ci-gate.yml'
|
||||
github_scripts:
|
||||
- '.github/scripts/**'
|
||||
- '.github/VOUCHED.td'
|
||||
- '.github/workflows/pr-gate.yml'
|
||||
- '.github/workflows/vouch-check-pr.yml'
|
||||
- '.github/workflows/issue-labeler.yml'
|
||||
- '.github/workflows/ci-gate.yml'
|
||||
|
||||
python-sdk:
|
||||
name: Python SDK
|
||||
@@ -167,13 +144,6 @@ jobs:
|
||||
uses: ./.github/workflows/mem0-plugin-checks.yml
|
||||
secrets: inherit
|
||||
|
||||
claude-code-plugin:
|
||||
name: Claude Code Plugin
|
||||
needs: changes
|
||||
if: needs.changes.outputs.claude_code_plugin == 'true'
|
||||
uses: ./.github/workflows/claude-code-plugin-checks.yml
|
||||
secrets: inherit
|
||||
|
||||
opencode-plugin:
|
||||
name: OpenCode Plugin
|
||||
needs: changes
|
||||
@@ -188,13 +158,6 @@ jobs:
|
||||
uses: ./.github/workflows/pi-agent-plugin-checks.yml
|
||||
secrets: inherit
|
||||
|
||||
deepseek-plugin:
|
||||
name: DeepSeek Harness Plugin
|
||||
needs: changes
|
||||
if: needs.changes.outputs.deepseek_plugin == 'true'
|
||||
uses: ./.github/workflows/deepseek-plugin-checks.yml
|
||||
secrets: inherit
|
||||
|
||||
n8n-nodes-mem0:
|
||||
name: n8n Node
|
||||
needs: changes
|
||||
@@ -207,13 +170,6 @@ jobs:
|
||||
uses: ./.github/workflows/zapier-mem0-checks.yml
|
||||
secrets: inherit
|
||||
|
||||
mem0-strands:
|
||||
name: mem0-strands
|
||||
needs: changes
|
||||
if: needs.changes.outputs.mem0_strands == 'true'
|
||||
uses: ./.github/workflows/mem0-strands-checks.yml
|
||||
secrets: inherit
|
||||
|
||||
docs-llms-txt:
|
||||
name: docs llms.txt
|
||||
needs: changes
|
||||
@@ -221,24 +177,6 @@ jobs:
|
||||
uses: ./.github/workflows/docs-llms-txt-check.yml
|
||||
secrets: inherit
|
||||
|
||||
github-scripts:
|
||||
name: GitHub Scripts
|
||||
needs: changes
|
||||
if: needs.changes.outputs.github_scripts == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 20
|
||||
- name: Run .github/scripts tests
|
||||
run: |
|
||||
for test in .github/scripts/*.test.js; do
|
||||
echo "::group::$test"
|
||||
node "$test"
|
||||
echo "::endgroup::"
|
||||
done
|
||||
|
||||
gate:
|
||||
name: CI Gate
|
||||
needs:
|
||||
@@ -249,15 +187,11 @@ jobs:
|
||||
- cli-node
|
||||
- openclaw
|
||||
- mem0-plugin
|
||||
- claude-code-plugin
|
||||
- opencode-plugin
|
||||
- pi-agent-plugin
|
||||
- deepseek-plugin
|
||||
- n8n-nodes-mem0
|
||||
- zapier-mem0
|
||||
- mem0-strands
|
||||
- docs-llms-txt
|
||||
- github-scripts
|
||||
if: always()
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
|
||||
@@ -1,46 +0,0 @@
|
||||
name: Claude Code Plugin Checks
|
||||
|
||||
# On PRs this is invoked by ci-gate.yml (the single required check);
|
||||
# push-to-main and manual runs remain standalone.
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches: [main]
|
||||
paths:
|
||||
- 'integrations/claude-code-plugin/**'
|
||||
- '.github/workflows/claude-code-plugin-checks.yml'
|
||||
workflow_call:
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
python-version: ["3.10", "3.11", "3.12"]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Python ${{ matrix.python-version }}
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: ${{ matrix.python-version }}
|
||||
|
||||
- name: Install test tooling
|
||||
run: pip install pytest ruff
|
||||
# The plugin itself has zero runtime dependencies — nothing else to install.
|
||||
|
||||
- name: Check manifests are valid JSON
|
||||
working-directory: integrations/claude-code-plugin
|
||||
run: |
|
||||
for f in .claude-plugin/plugin.json .mcp.json hooks/hooks.json; do
|
||||
jq empty "$f" || (echo "Invalid JSON: $f" && exit 1)
|
||||
done
|
||||
|
||||
- name: Lint
|
||||
working-directory: integrations/claude-code-plugin
|
||||
run: python3 -m ruff check .
|
||||
|
||||
- name: Run tests
|
||||
working-directory: integrations/claude-code-plugin
|
||||
run: python3 -m pytest tests -q
|
||||
@@ -1,60 +0,0 @@
|
||||
name: Publish @mem0/deepseek-plugin 📦 to npm
|
||||
|
||||
# Dispatched by release.yml (Release Router) when a release tagged
|
||||
# deepseek-plugin-v* is published. Can also be dispatched manually to re-publish
|
||||
# a tag.
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag:
|
||||
description: 'Release tag to build and publish (e.g. deepseek-plugin-v0.1.1)'
|
||||
required: true
|
||||
type: string
|
||||
prerelease:
|
||||
description: 'Publish under the version preid dist-tag instead of latest'
|
||||
required: false
|
||||
type: boolean
|
||||
default: false
|
||||
|
||||
jobs:
|
||||
build-n-publish:
|
||||
name: Build and publish @mem0/deepseek-plugin 📦 to npm
|
||||
if: startsWith(inputs.tag, 'deepseek-plugin-v')
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
id-token: write
|
||||
defaults:
|
||||
run:
|
||||
working-directory: integrations/deepseek-plugin
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ inputs.tag }}
|
||||
|
||||
- name: Install pnpm
|
||||
uses: pnpm/action-setup@v4
|
||||
with:
|
||||
version: 9
|
||||
|
||||
- name: Set up Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '22'
|
||||
registry-url: 'https://registry.npmjs.org'
|
||||
cache: 'pnpm'
|
||||
cache-dependency-path: integrations/deepseek-plugin/pnpm-lock.yaml
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: Build
|
||||
run: pnpm build
|
||||
|
||||
- name: Publish to npm
|
||||
run: |
|
||||
if [ "${{ inputs.prerelease }}" = "true" ]; then
|
||||
PREID=$(node -p "require('./package.json').version.split('-')[1].split('.')[0]")
|
||||
npx npm@latest publish --provenance --access public --tag "$PREID"
|
||||
else
|
||||
npx npm@latest publish --provenance --access public
|
||||
fi
|
||||
@@ -1,90 +0,0 @@
|
||||
name: deepseek-plugin checks
|
||||
|
||||
# On PRs this is invoked by ci-gate.yml (the single required check);
|
||||
# push-to-main and manual runs remain standalone.
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches: [main]
|
||||
paths:
|
||||
- 'integrations/deepseek-plugin/**'
|
||||
- '.github/workflows/deepseek-plugin-checks.yml'
|
||||
workflow_call:
|
||||
|
||||
jobs:
|
||||
lint:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Install pnpm
|
||||
uses: pnpm/action-setup@v4
|
||||
with:
|
||||
version: 9
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 20
|
||||
cache: 'pnpm'
|
||||
cache-dependency-path: integrations/deepseek-plugin/pnpm-lock.yaml
|
||||
|
||||
- name: Install dependencies
|
||||
run: cd integrations/deepseek-plugin && pnpm install --frozen-lockfile
|
||||
|
||||
- name: Type check
|
||||
run: cd integrations/deepseek-plugin && pnpm exec tsc --noEmit
|
||||
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
node-version: [20, 22]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Install pnpm
|
||||
uses: pnpm/action-setup@v4
|
||||
with:
|
||||
version: 9
|
||||
|
||||
- name: Setup Node.js ${{ matrix.node-version }}
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: ${{ matrix.node-version }}
|
||||
cache: 'pnpm'
|
||||
cache-dependency-path: integrations/deepseek-plugin/pnpm-lock.yaml
|
||||
|
||||
- name: Install dependencies
|
||||
run: cd integrations/deepseek-plugin && pnpm install --frozen-lockfile
|
||||
|
||||
- name: Run tests
|
||||
run: cd integrations/deepseek-plugin && pnpm exec vitest run
|
||||
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Install pnpm
|
||||
uses: pnpm/action-setup@v4
|
||||
with:
|
||||
version: 9
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 20
|
||||
cache: 'pnpm'
|
||||
cache-dependency-path: integrations/deepseek-plugin/pnpm-lock.yaml
|
||||
|
||||
- name: Install dependencies
|
||||
run: cd integrations/deepseek-plugin && pnpm install --frozen-lockfile
|
||||
|
||||
- name: Build
|
||||
run: cd integrations/deepseek-plugin && pnpm build
|
||||
|
||||
- name: Verify dist output exists
|
||||
run: |
|
||||
test -f integrations/deepseek-plugin/dist/index.js || (echo "Build output missing: dist/index.js" && exit 1)
|
||||
test -f integrations/deepseek-plugin/dist/index.d.ts || (echo "Build output missing: dist/index.d.ts" && exit 1)
|
||||
@@ -1,50 +0,0 @@
|
||||
name: Publish mem0-strands 🐍 distribution 📦 to PyPI
|
||||
|
||||
# Dispatched by release.yml (Release Router) when a release tagged
|
||||
# mem0-strands-v* is published. Can also be dispatched manually to re-publish
|
||||
# a tag. Publishing uses PyPI Trusted Publishing (OIDC), so no API token is
|
||||
# stored; the `mem0-strands` PyPI project must have a trusted publisher
|
||||
# configured for mem0ai/mem0 + this workflow.
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag:
|
||||
description: 'Release tag to build and publish (e.g. mem0-strands-v0.1.0)'
|
||||
required: true
|
||||
type: string
|
||||
prerelease:
|
||||
description: 'Unused for PyPI (pre-releases are expressed in the version itself); accepted for router uniformity'
|
||||
required: false
|
||||
type: boolean
|
||||
default: false
|
||||
|
||||
jobs:
|
||||
build-n-publish:
|
||||
name: Build and publish mem0-strands 📦 to PyPI
|
||||
if: startsWith(inputs.tag, 'mem0-strands-v')
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
id-token: write
|
||||
defaults:
|
||||
run:
|
||||
working-directory: integrations/mem0-strands/python
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ inputs.tag }}
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: '3.11'
|
||||
|
||||
- name: Install Hatch
|
||||
run: pip install hatch
|
||||
|
||||
- name: Build a binary wheel and a source tarball
|
||||
run: hatch build --clean
|
||||
|
||||
- name: Publish distribution 📦 to PyPI
|
||||
uses: pypa/gh-action-pypi-publish@release/v1
|
||||
with:
|
||||
packages-dir: integrations/mem0-strands/python/dist/
|
||||
@@ -1,82 +0,0 @@
|
||||
name: mem0-strands CI
|
||||
|
||||
# On PRs this is invoked by ci-gate.yml (the single required check);
|
||||
# push-to-main and manual runs remain standalone.
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches: [main]
|
||||
paths:
|
||||
- 'integrations/mem0-strands/**'
|
||||
- '.github/workflows/mem0-strands-checks.yml'
|
||||
workflow_call:
|
||||
|
||||
jobs:
|
||||
lint:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: '3.12'
|
||||
|
||||
- name: Install dev dependencies
|
||||
working-directory: integrations/mem0-strands/python
|
||||
run: pip install -e ".[dev]"
|
||||
|
||||
- name: Lint with ruff
|
||||
working-directory: integrations/mem0-strands/python
|
||||
run: ruff check .
|
||||
|
||||
- name: Check formatting
|
||||
working-directory: integrations/mem0-strands/python
|
||||
run: ruff format --check .
|
||||
|
||||
- name: Type-check with mypy
|
||||
working-directory: integrations/mem0-strands/python
|
||||
run: mypy src
|
||||
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
python-version: ["3.10", "3.11", "3.12"]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Python ${{ matrix.python-version }}
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: ${{ matrix.python-version }}
|
||||
|
||||
- name: Install dev dependencies
|
||||
working-directory: integrations/mem0-strands/python
|
||||
run: pip install -e ".[dev]"
|
||||
|
||||
- name: Run tests
|
||||
working-directory: integrations/mem0-strands/python
|
||||
run: pytest
|
||||
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: '3.12'
|
||||
|
||||
- name: Install Hatch
|
||||
run: pip install hatch
|
||||
|
||||
- name: Build
|
||||
working-directory: integrations/mem0-strands/python
|
||||
run: hatch build --clean
|
||||
|
||||
- name: Verify dist output
|
||||
run: |
|
||||
ls integrations/mem0-strands/python/dist/*.whl || (echo "Wheel file missing" && exit 1)
|
||||
ls integrations/mem0-strands/python/dist/*.tar.gz || (echo "Source dist missing" && exit 1)
|
||||
@@ -2,13 +2,11 @@ name: PR Gate
|
||||
|
||||
on:
|
||||
pull_request_target:
|
||||
types: [opened, reopened, ready_for_review, edited]
|
||||
issues:
|
||||
types: [labeled]
|
||||
types: [opened, reopened, edited, ready_for_review]
|
||||
|
||||
concurrency:
|
||||
group: pr-gate-${{ github.event_name }}-${{ github.event.action }}-${{ github.event.pull_request.number || github.event.issue.number }}
|
||||
cancel-in-progress: ${{ github.event_name == 'pull_request_target' }}
|
||||
group: pr-gate-${{ github.event.pull_request.number }}
|
||||
cancel-in-progress: true
|
||||
|
||||
env:
|
||||
GATE_EFFECTIVE_FROM: '2026-08-12T00:00:00Z'
|
||||
@@ -21,11 +19,8 @@ permissions:
|
||||
jobs:
|
||||
gate:
|
||||
if: >-
|
||||
github.event_name == 'pull_request_target' &&
|
||||
github.event.action != 'edited' &&
|
||||
github.event.pull_request.draft == false &&
|
||||
github.event.pull_request.user.type != 'Bot' &&
|
||||
github.event.pull_request.head.repo.full_name != github.repository &&
|
||||
!contains(fromJSON('["OWNER","MEMBER","COLLABORATOR"]'), github.event.pull_request.author_association)
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
@@ -52,9 +47,7 @@ jobs:
|
||||
const files = await github.paginate(github.rest.pulls.listFiles, {
|
||||
owner, repo, pull_number: pr.number, per_page: 100,
|
||||
});
|
||||
const rootDocs = new Set(['README.md', 'CONTRIBUTING.md', 'CODE_OF_CONDUCT.md', 'SECURITY.md']);
|
||||
const isDocs = (filename) => filename.startsWith('docs/') || rootDocs.has(filename);
|
||||
if (files.length > 0 && files.every((file) => isDocs(file.filename))) {
|
||||
if (files.length > 0 && files.every((file) => file.filename.startsWith('docs/'))) {
|
||||
core.info('Docs-only PR, gate skipped');
|
||||
return;
|
||||
}
|
||||
@@ -82,7 +75,6 @@ jobs:
|
||||
}
|
||||
|
||||
const body = [
|
||||
'<!-- pr-gate -->',
|
||||
'Thanks for taking the time to open this.',
|
||||
'',
|
||||
'We only review pull requests that fix an issue we have already agreed to take on, so this one is closed for now.',
|
||||
@@ -92,9 +84,10 @@ jobs:
|
||||
'',
|
||||
'1. Make sure an issue describes the problem, with the version you are on, a runnable reproduction, and the real output or traceback you saw.',
|
||||
'2. Link it from this pull request description with `Closes #<number>`.',
|
||||
'3. Ask a maintainer to label that issue `accepted`. This pull request reopens by itself when they do.',
|
||||
'3. Ask a maintainer to label that issue `accepted`.',
|
||||
'4. Reopen this pull request. The check runs again and it stays open.',
|
||||
'',
|
||||
'Issue already labeled `accepted`? Just add `Closes #<number>` to the description. That reopens this too.',
|
||||
'Already linked an accepted issue? Edit the description to include `Closes #<number>` and reopen. The check reruns automatically.',
|
||||
'',
|
||||
'Documentation-only changes skip this gate entirely.',
|
||||
'',
|
||||
@@ -108,107 +101,3 @@ jobs:
|
||||
owner, repo, pull_number: pr.number, state: 'closed',
|
||||
});
|
||||
core.info(`Closed #${pr.number}: no accepted issue linked`);
|
||||
|
||||
reopen:
|
||||
if: >-
|
||||
(github.event_name == 'issues' && github.event.label.name == 'accepted') ||
|
||||
(github.event.action == 'edited' && github.event.pull_request.state == 'closed')
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/github-script@v7
|
||||
with:
|
||||
script: |
|
||||
const { owner, repo } = context.repo;
|
||||
const marker = '<!-- pr-gate -->';
|
||||
|
||||
const denounced = await (async () => {
|
||||
try {
|
||||
const { data } = await github.rest.repos.getContent({
|
||||
owner, repo, path: '.github/VOUCHED.td',
|
||||
ref: context.payload.repository.default_branch,
|
||||
});
|
||||
return new Set(Buffer.from(data.content, 'base64').toString('utf8')
|
||||
.split('\n')
|
||||
.map((line) => line.trim())
|
||||
.filter((line) => line.startsWith('-'))
|
||||
.map((line) => line.slice(1).split(/\s+/)[0].split(':').pop().toLowerCase())
|
||||
.filter(Boolean));
|
||||
} catch (error) {
|
||||
core.warning(`Could not read VOUCHED.td, treating nobody as denounced: ${error.message}`);
|
||||
return new Set();
|
||||
}
|
||||
})();
|
||||
|
||||
const isReopenable = async (number) => {
|
||||
const { repository } = await github.graphql(
|
||||
`query ($owner: String!, $repo: String!, $number: Int!) {
|
||||
repository(owner: $owner, name: $repo) {
|
||||
pullRequest(number: $number) {
|
||||
state
|
||||
author { login }
|
||||
closingIssuesReferences(first: 20) {
|
||||
nodes { labels(first: 50) { nodes { name } } }
|
||||
}
|
||||
}
|
||||
}
|
||||
}`,
|
||||
{ owner, repo, number },
|
||||
);
|
||||
const pullRequest = repository.pullRequest;
|
||||
if (denounced.has(pullRequest.author?.login?.toLowerCase())) {
|
||||
core.info(`#${number} is from a denounced author. Vouch outranks this gate.`);
|
||||
return false;
|
||||
}
|
||||
return pullRequest.state === 'CLOSED' &&
|
||||
pullRequest.closingIssuesReferences.nodes.some((issue) =>
|
||||
issue.labels.nodes.some((label) => label.name === 'accepted'));
|
||||
};
|
||||
|
||||
let candidates;
|
||||
if (context.eventName === 'issues') {
|
||||
const { repository } = await github.graphql(
|
||||
`query ($owner: String!, $repo: String!, $number: Int!) {
|
||||
repository(owner: $owner, name: $repo) {
|
||||
issue(number: $number) {
|
||||
closedByPullRequestsReferences(first: 20, includeClosedPrs: true) {
|
||||
nodes { number }
|
||||
}
|
||||
}
|
||||
}
|
||||
}`,
|
||||
{ owner, repo, number: context.payload.issue.number },
|
||||
);
|
||||
candidates = repository.issue.closedByPullRequestsReferences.nodes.map((pr) => pr.number);
|
||||
} else {
|
||||
candidates = [context.payload.pull_request.number];
|
||||
}
|
||||
|
||||
for (const number of candidates) {
|
||||
if (!(await isReopenable(number))) {
|
||||
core.info(`#${number} is not a closed pull request linking an accepted issue. Skipped.`);
|
||||
continue;
|
||||
}
|
||||
|
||||
const comments = await github.paginate(github.rest.issues.listComments, {
|
||||
owner, repo, issue_number: number, per_page: 100,
|
||||
});
|
||||
if (!comments.some((comment) => comment.body?.startsWith(marker))) {
|
||||
core.info(`#${number} was not closed by this gate. Left alone.`);
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
await github.rest.pulls.update({
|
||||
owner, repo, pull_number: number, state: 'open',
|
||||
});
|
||||
} catch (error) {
|
||||
core.warning(`Could not reopen #${number}: ${error.message}`);
|
||||
continue;
|
||||
}
|
||||
|
||||
await github.rest.issues.createComment({
|
||||
owner, repo, issue_number: number,
|
||||
body: 'An `accepted` issue is linked now, so this is open again and ready for review.',
|
||||
});
|
||||
core.info(`Reopened #${number}`);
|
||||
}
|
||||
|
||||
@@ -45,9 +45,7 @@ jobs:
|
||||
openclaw-v*) workflow="openclaw-cd.yml" ;;
|
||||
opencode-v*) workflow="opencode-plugin-cd.yml" ;;
|
||||
pi-agent-v*) workflow="pi-agent-plugin-cd.yml" ;;
|
||||
deepseek-plugin-v*) workflow="deepseek-plugin-cd.yml" ;;
|
||||
n8n-nodes-mem0-v*) workflow="n8n-nodes-mem0-cd.yml" ;;
|
||||
mem0-strands-v*) workflow="mem0-strands-cd.yml" ;;
|
||||
v*) workflow="cd.yml" ;;
|
||||
*)
|
||||
echo "::error::Release tag '$TAG' does not match any known package prefix — nothing will be published. See the tag prefix table in AGENTS.md."
|
||||
|
||||
@@ -16,44 +16,12 @@ jobs:
|
||||
check:
|
||||
if: >-
|
||||
github.event.pull_request.user.type != 'Bot' &&
|
||||
github.event.pull_request.head.repo.full_name != github.repository &&
|
||||
!contains(fromJSON('["OWNER","MEMBER","COLLABORATOR"]'), github.event.pull_request.author_association)
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: mitchellh/vouch/action/check-pr@d66fa29a64600490892131ad87597c30c91fcac4 # v1.5.0
|
||||
id: vouch
|
||||
with:
|
||||
pr-number: ${{ github.event.pull_request.number }}
|
||||
require-vouch: false
|
||||
auto-close: true
|
||||
auto-close: false
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- if: steps.vouch.outputs.status == 'allowed'
|
||||
uses: actions/github-script@v7
|
||||
with:
|
||||
script: |
|
||||
const { owner, repo } = context.repo;
|
||||
const pr = context.payload.pull_request;
|
||||
const marker = '<!-- vouch-check -->';
|
||||
|
||||
const comments = await github.paginate(github.rest.issues.listComments, {
|
||||
owner, repo, issue_number: pr.number, per_page: 100,
|
||||
});
|
||||
if (comments.some((comment) => comment.body?.startsWith(marker))) {
|
||||
core.info('Vouch comment already posted, skipped.');
|
||||
return;
|
||||
}
|
||||
|
||||
const body = [
|
||||
marker,
|
||||
`Hi @${context.payload.pull_request.user.login}, thanks for opening this pull request.`,
|
||||
'',
|
||||
"This is just a soft check: you are not yet in this repo's vouched contributor list (`.github/VOUCHED.td`). Nothing is blocked and there is nothing you need to do.",
|
||||
'',
|
||||
`A maintainer can vouch for you by commenting \`!vouch @${context.payload.pull_request.user.login}\` on any issue.`,
|
||||
].join('\n');
|
||||
|
||||
await github.rest.issues.createComment({
|
||||
owner, repo, issue_number: pr.number, body,
|
||||
});
|
||||
|
||||
@@ -37,6 +37,6 @@ jobs:
|
||||
denounce-keyword: "!denounce"
|
||||
unvouch-keyword: "!unvouch"
|
||||
pull-request: "true"
|
||||
merge-immediately: "false"
|
||||
merge-immediately: "true"
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ steps.app-token.outputs.token }}
|
||||
|
||||
@@ -191,7 +191,3 @@ qdrant_storage/
|
||||
testing.ipynb
|
||||
.weave/
|
||||
|
||||
|
||||
# TypeScript incremental build info and local, uncommitted e2e scripts (used by the integrations, e.g. integrations/deepseek-plugin)
|
||||
*.tsbuildinfo
|
||||
*.local.mjs
|
||||
|
||||
@@ -10,7 +10,6 @@ This is a polyglot monorepo and **every package sets its own rules**. Read the `
|
||||
## Do NOT
|
||||
|
||||
- Open a pull request without a signed CLA. It will not be reviewed. See [The CLA is not optional](#the-cla-is-not-optional).
|
||||
- Open a pull request that does not link an issue carrying the `accepted` label. A bot closes it within a minute. See [Two gates decide whether your pull request stays open](#two-gates-decide-whether-your-pull-request-stays-open).
|
||||
- Modify anything in `.github/workflows/` without explicit maintainer approval. Publishing credentials are pinned to workflow filenames.
|
||||
- Commit `.env` files, API keys, or credentials.
|
||||
- Skip pre-commit hooks.
|
||||
@@ -122,24 +121,6 @@ Full guide: [`CONTRIBUTING.md`](CONTRIBUTING.md). Conduct: [`CODE_OF_CONDUCT.md`
|
||||
6. Open the PR against `main` and fill in [the template](.github/PULL_REQUEST_TEMPLATE.md). Do not paraphrase it; GitHub prefills it.
|
||||
7. **Sign the CLA.**
|
||||
|
||||
### Two gates decide whether your pull request stays open
|
||||
|
||||
Two workflows run on every pull request from a fork. They judge different things and neither covers for the other, so a pull request has to get past both.
|
||||
|
||||
**The [PR Gate](.github/workflows/pr-gate.yml) judges the change.** It closes any pull request that does not link an issue carrying the `accepted` label. Closed is a queue decision, not a verdict: when a maintainer applies the label the pull request reopens by itself. Drafts, documentation-only changes, and branches pushed to this repository rather than a fork are all exempt.
|
||||
|
||||
**The [vouch check](.github/workflows/vouch-check-pr.yml) judges the account.** It reads [`.github/VOUCHED.td`](.github/VOUCHED.td), which has three possible answers about any given person:
|
||||
|
||||
| The list says | Meaning | Effect on the pull request |
|
||||
|---|---|---|
|
||||
| `-handle` | a maintainer ran `!denounce` after the code of conduct process | closed, even with an accepted issue |
|
||||
| nothing at all | everybody who has not contributed here before | **none.** One comment saying nothing is blocked. |
|
||||
| `handle` | a maintainer ran `!vouch` | none, and the comment stops appearing |
|
||||
|
||||
Being vouched grants nothing. It is a "we have seen this person before" flag that mutes the newcomer comment, not permission to skip the accepted-issue rule. Being absent from the list costs nothing.
|
||||
|
||||
If you are an agent opening a pull request on someone's behalf, the practical consequence is one rule: **get the linked issue labelled `accepted` before you open the pull request, or expect the pull request to be closed and to reopen later.** Do not work around either gate, do not reopen a gated pull request by hand, and do not re-file the same change under a new pull request when one is closed.
|
||||
|
||||
### The CLA is not optional
|
||||
|
||||
**A pull request from a contributor who has not signed the Contributor License Agreement is not accepted, not reviewed, and not merged.** This is not a formality applied at merge time. An unsigned pull request does not enter the review queue at all: maintainers do not read the diff, do not leave feedback, and do not discuss the approach. It sits until the CLA is signed, and it is closed if it goes stale.
|
||||
@@ -170,6 +151,5 @@ Beyond the CLA and the accepted-issue gate, the [Contribution Conduct](CODE_OF_C
|
||||
| Documentation contributions | `docs/contributing/documentation.mdx` |
|
||||
| PR template | `.github/PULL_REQUEST_TEMPLATE.md` |
|
||||
| Issue forms | `.github/ISSUE_TEMPLATE/` |
|
||||
| Contribution gates | [Two gates decide whether your pull request stays open](#two-gates-decide-whether-your-pull-request-stays-open) |
|
||||
| Trust list (vouch) | [`.github/VOUCHED.td`](.github/VOUCHED.td) |
|
||||
| Trust list (vouch) | `.github/VOUCHED.td` |
|
||||
| CI/CD, gates, rulesets | [`.github/AGENTS.md`](.github/AGENTS.md) |
|
||||
|
||||
+3
-31
@@ -40,24 +40,9 @@ agree the change is one we want.
|
||||
|
||||
Pull requests that don't link an accepted issue are closed automatically by the
|
||||
[PR Gate](./.github/workflows/pr-gate.yml). **Closed does not mean rejected.** It
|
||||
means the change isn't in the queue yet. Once a maintainer labels the issue the
|
||||
pull request reopens itself, and you don't have to do anything. Documentation-only
|
||||
changes skip the gate entirely.
|
||||
|
||||
A second check looks at who opened the pull request rather than what it changes.
|
||||
If you are not yet in this repo's contributor list
|
||||
([`.github/VOUCHED.td`](./.github/VOUCHED.td)) you get one comment saying so.
|
||||
**Nothing is blocked and there is nothing you need to do.** A maintainer can add
|
||||
you by commenting `!vouch @you` on any issue, which only stops that comment from
|
||||
appearing again. Being on the list is not permission to skip the accepted-issue
|
||||
rule, and being absent from it costs you nothing.
|
||||
|
||||
The list has a negative side too. A maintainer can `!denounce` an account that
|
||||
has been through the
|
||||
[code of conduct](./CODE_OF_CONDUCT.md#contribution-conduct) enforcement process,
|
||||
and pull requests from that account are closed whether or not they link an
|
||||
accepted issue. This is rare, it is never where anyone starts, and it is
|
||||
reversible.
|
||||
means the change isn't in the queue yet. Once a maintainer labels the issue,
|
||||
reopen the pull request and it stays open. Documentation-only changes skip the
|
||||
gate entirely.
|
||||
|
||||
Security fixes are the one exception, and they don't go through public pull
|
||||
requests at all. Follow the [Security Policy](./SECURITY.md) instead, which uses
|
||||
@@ -100,19 +85,6 @@ sign. Signing takes less than a minute and only needs to be done once. Pull
|
||||
requests from contributors who have not signed the CLA will be blocked from
|
||||
merging.
|
||||
|
||||
## First Contribution Fast Path
|
||||
|
||||
Fixing a typo or a small docs issue? You don't need the full workflow below.
|
||||
|
||||
1. **Pick something small.** Look for issues labeled `documentation` or `good first issue`, or a typo/broken link you noticed while reading the docs.
|
||||
2. **Branch from `main`** with a name that says what you're fixing, e.g. `docs/fix-quickstart-typo` or `fix/broken-crewai-link`.
|
||||
3. **Make the change, then run only what applies:**
|
||||
- Docs-only change (`docs/**`): preview with `make docs`. If you added or removed an `.mdx` page, run `python scripts/check-llms-txt-coverage.py --write` so `docs/llms.txt` stays in sync.
|
||||
- Code change: run the linter and tests for the package you touched, see [Development Workflow](#development-workflow) below.
|
||||
4. **Open a PR** against `main` with `Closes #<issue-number>` and a one-line description of what you fixed.
|
||||
|
||||
For anything larger than a docs fix or a small bug, follow the full workflow below.
|
||||
|
||||
## Repository Layout
|
||||
|
||||
The two most common contribution targets are the SDKs:
|
||||
|
||||
@@ -11,7 +11,7 @@ install:
|
||||
hatch env create
|
||||
|
||||
install_all:
|
||||
pip install ruff==0.16.0 groq together boto3 'litellm>=1.83.7,<1.98.0' ollama chromadb weaviate weaviate-client sentence_transformers vertexai \
|
||||
pip install ruff==0.16.0 groq together boto3 litellm ollama chromadb weaviate weaviate-client sentence_transformers vertexai \
|
||||
google-generativeai elasticsearch opensearch-py vecs "pinecone<7.0.0" pinecone-text faiss-cpu langchain-community \
|
||||
upstash-vector azure-search-documents langchain-memgraph langchain-neo4j langchain-aws rank-bm25 pymochow pymongo psycopg kuzu databricks-sdk valkey
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@mem0/cli",
|
||||
"version": "0.2.13",
|
||||
"version": "0.2.12",
|
||||
"description": "The official CLI for mem0 — the memory layer for AI agents",
|
||||
"type": "module",
|
||||
"bin": {
|
||||
|
||||
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
|
||||
|
||||
[project]
|
||||
name = "mem0-cli"
|
||||
version = "0.2.12"
|
||||
version = "0.2.11"
|
||||
description = "The official CLI for mem0 — the memory layer for AI agents"
|
||||
readme = "README.md"
|
||||
license = "Apache-2.0"
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
"""mem0 CLI — the command-line interface for the mem0 memory layer."""
|
||||
|
||||
__version__ = "0.2.12"
|
||||
__version__ = "0.2.11"
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
title: "Preview Dream Scope"
|
||||
description: "A no-write preview of the scope Dream synthesis would analyze for a project."
|
||||
openapi: "post /api/v1/orgs/organizations/{org_id}/projects/{project_id}/dream/preview/"
|
||||
---
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
title: "Get Dream Activity"
|
||||
description: "Supersede/merge activity feed for a project, newest first (keyset-paginated)."
|
||||
openapi: "get /api/v1/orgs/organizations/{org_id}/projects/{project_id}/dream/activity/"
|
||||
---
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
title: "Get Dream Configuration"
|
||||
description: "Retrieve a project's Dream (memory synthesis) configuration and plan entitlements."
|
||||
openapi: "get /api/v1/orgs/organizations/{org_id}/projects/{project_id}/dream/config/"
|
||||
---
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
title: "Get a Synthesized Memory's Sources"
|
||||
description: "The source memories a synthesized (pattern) memory was distilled from."
|
||||
openapi: "get /api/v1/orgs/organizations/{org_id}/projects/{project_id}/dream/memory/{memory_id}/sources/"
|
||||
---
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
title: "Get Memories in a Dream Run"
|
||||
description: "Keyset page of the synthesized memories within a single synthesis run."
|
||||
openapi: "get /api/v1/orgs/organizations/{org_id}/projects/{project_id}/dream/runs/{run_id}/memories/"
|
||||
---
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
title: "Get Dream Synthesis Runs"
|
||||
description: "Synthesis activity grouped per run, newest first (keyset-paginated)."
|
||||
openapi: "get /api/v1/orgs/organizations/{org_id}/projects/{project_id}/dream/runs/"
|
||||
---
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
title: "Get Dream Stats"
|
||||
description: "Lifecycle and synthesis counts for a project, plus reflection freshness."
|
||||
openapi: "get /api/v1/orgs/organizations/{org_id}/projects/{project_id}/dream/stats/"
|
||||
---
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
title: "Update Dream Configuration"
|
||||
description: "Enable or disable Synthesis (reflection) for a project, or change the reflection mode."
|
||||
openapi: "patch /api/v1/orgs/organizations/{org_id}/projects/{project_id}/dream/config/"
|
||||
---
|
||||
@@ -4,55 +4,6 @@ description: "Major product launches, headline features, and milestones for Mem0
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
<Update label="2026-08-24" description="DeepSeek Harness plugin">
|
||||
|
||||
**DeepSeek Harness: Mem0 as a Native Cordis Plugin**
|
||||
|
||||
The DeepSeek Harness agent forgets everything between sessions. [`@mem0/deepseek-plugin`](https://www.npmjs.com/package/@mem0/deepseek-plugin) gives it two Mem0-backed tools, so recall and writes persist across runs against the same memory bank you already use from Claude Code, Codex, and every other connected agent.
|
||||
|
||||
- **Two agent-callable tools:** `search_memory` recalls facts relevant to a query, `add_memory` stores a fact for future sessions. Both accept per-call `userId` / `agentId` / `runId` scope overrides.
|
||||
- **Native Cordis lifecycle:** The plugin declares `inject = ['tools']` so it waits for the harness tool registry, then registers through `ctx.tools.register()`. Unmounting the plugin removes the tools automatically.
|
||||
- **Managed backend, not a memory file:** Server-side extraction, semantic dedup, and conflict resolution, rather than a Markdown file the agent has to maintain itself.
|
||||
- **Config:** `userId` is required, `apiKey` defaults to `$MEM0_API_KEY`, and `host` optionally targets a dedicated Mem0 Platform base URL.
|
||||
|
||||
See [DeepSeek Harness](/integrations/deepseek-plugin) for setup and [SDK & Tools](/changelog/sdk) for PR links.
|
||||
|
||||
<Note>
|
||||
Developer preview. Auto-capture and auto-recall, where memory reaches the context with no explicit tool call, are planned but not yet built.
|
||||
</Note>
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="2026-08-24" description="Strands Agents integration">
|
||||
|
||||
**Strands Agents: Mem0 as a Native MemoryStore**
|
||||
|
||||
[`mem0-strands`](https://pypi.org/project/mem0-strands/) plugs Mem0 into AWS's [Strands Agents](https://strandsagents.com/) SDK as a native `MemoryStore`, so recall and writes happen inside the agent loop rather than as tool calls the model has to remember to make.
|
||||
|
||||
- **Automatic recall:** The `MemoryManager` drives the store on every turn, searching Mem0 and injecting the results into the prompt with no tool call required.
|
||||
- **Server-side extraction:** Because the store implements `add_messages`, enabling extraction routes raw conversation turns straight to Mem0's extraction pipeline, skipping the extra client-side model call needed to distill facts first.
|
||||
- **Hosted or self-hosted:** An API key targets the hosted Mem0 Platform; a config dict targets self-hosted Mem0 OSS.
|
||||
- **Entity scoping:** Accepts `user_id`, `agent_id`, `run_id`, and `app_id`, with at least one required and invalid combinations rejected at construction rather than on the first write.
|
||||
|
||||
See [Strands Agents](/integrations/strands) for setup and [SDK & Tools](/changelog/sdk) for PR links.
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="2026-08-13" description="Kimi Code plugin">
|
||||
|
||||
**Kimi Code: Mem0 Joins the Editor Plugin Family**
|
||||
|
||||
The shared Mem0 editor plugin now covers Kimi Code alongside Claude Code, Cursor, Codex, and Antigravity, running on the same scripts, skills, and memory bank, so context written in one editor is available in the others.
|
||||
|
||||
- **Hosted MCP server:** Registers `https://mcp.mem0.ai/mcp/`, authenticated with `MEM0_API_KEY` as a bearer token.
|
||||
- **Automatic capture and recall:** SessionStart loads context through the `context-loader` skill, and hooks on prompt submit, file reads, Bash output, stop, and pre-compact capture and inject memory without an explicit tool call.
|
||||
- **Guardrails:** Direct `Write` / `Edit` / `MultiEdit` to memory files is blocked, and metadata defaults are enforced on every Mem0 MCP tool call.
|
||||
- **Kimi hook adapter:** A shim normalizes Kimi Code's hook contract to the shape the shared scripts already expect, resolving the real project directory and translating the differing prompt, tool-output, and MCP tool-name fields.
|
||||
|
||||
See [SDK & Tools](/changelog/sdk) for version details and PR links.
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="2026-07-30" description="n8n and Zapier integrations">
|
||||
|
||||
**Workflow Automation: Mem0 Memory in n8n and Zapier**
|
||||
|
||||
@@ -7,27 +7,6 @@ mode: "wide"
|
||||
<Tabs>
|
||||
<Tab title="Python">
|
||||
|
||||
<Update label="2026-09-02" description="v2.0.20">
|
||||
|
||||
**Improvements:**
|
||||
- **OSS notices:** Notice configuration now comes from a static, cacheable repository file with a bundled disabled fallback and deterministic rollout assignment, instead of calling PostHog's feature-flag evaluation API. This keeps notices fail-safe when the remote config is unavailable and removes the PostHog feature-flag request from notice evaluation ([#7185](https://github.com/mem0ai/mem0/pull/7185))
|
||||
- **Vector Stores:** `RedisDBConfig` now uses Pydantic's native `extra="forbid"` handling for unknown fields instead of a custom model validator, preserving strict validation while returning standard Pydantic errors ([#7089](https://github.com/mem0ai/mem0/pull/7089))
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="2026-08-24" description="v2.0.19">
|
||||
|
||||
**Bug Fixes:**
|
||||
- **Embeddings:** `HuggingFaceEmbedding` now falls back to the `HUGGINGFACE_API_KEY` env var, then a placeholder key, when `huggingface_base_url` is set and no `api_key` is configured. The OpenAI-compatible client used to talk to TEI endpoints raises at construction when no key resolves at all, so a TEI deployment that doesn't require a real key previously failed to initialize ([#6947](https://github.com/mem0ai/mem0/pull/6947))
|
||||
- **Core:** `remove_code_blocks()` now accepts list-shaped content (a sequence of `{"text": ...}` blocks, as some agent frameworks pass) by joining each block's text before stripping code fences, instead of raising `AttributeError` from calling `.strip()` on a list ([#6947](https://github.com/mem0ai/mem0/pull/6947))
|
||||
- **Core:** `create_procedural_memory()` (`Memory` and `AsyncMemory`) now raises a clear `ValueError` when the LLM returns no content for the summary, instead of continuing with empty content that surfaced as a confusing error further down the call ([#6947](https://github.com/mem0ai/mem0/pull/6947))
|
||||
- **Proxy:** `mem0.proxy` no longer auto-installs `litellm` via a `pip install` subprocess when the import fails; it now raises `ImportError` with instructions to install it yourself. The auto-install could hang or fail silently in restricted environments and ran an unreviewed install on the caller's behalf ([#6947](https://github.com/mem0ai/mem0/pull/6947))
|
||||
- **Client:** `get_all()` (sync and async) now sends `page` and `page_size` as independent query params instead of requiring both to be set before either was sent. Passing only `page_size` without `page` previously had it silently dropped, so results came back at the server's default page size ([#6900](https://github.com/mem0ai/mem0/pull/6900))
|
||||
- **LLMs:** Add `provider_override` to `AWSBedrockConfig`, an explicit provider name (for example `"anthropic"`) for when `model` is an application inference profile ARN whose opaque ID has no provider substring for `extract_provider()` to detect. Without it, those ARNs raised `ValueError: Unable to determine provider` ([#6899](https://github.com/mem0ai/mem0/pull/6899))
|
||||
- **LLMs:** `VllmConfig` now falls back to the `VLLM_BASE_URL` env var when `vllm_base_url` isn't passed explicitly. The default was filled in before the env var was ever checked, so `VLLM_BASE_URL` was silently ignored ([#6897](https://github.com/mem0ai/mem0/pull/6897))
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="2026-08-11" description="v2.0.18">
|
||||
|
||||
**Bug Fixes:**
|
||||
@@ -1227,26 +1206,6 @@ See the [OSS v2 to v3 migration guide](https://docs.mem0.ai/migration/oss-v2-to-
|
||||
|
||||
<Tab title="TypeScript">
|
||||
|
||||
<Update label="2026-09-02" description="v3.1.8">
|
||||
|
||||
**Improvements:**
|
||||
- **OSS notices:** Notice configuration now comes from a static, cacheable repository file with a bundled disabled fallback and deterministic rollout assignment, instead of calling PostHog's feature-flag evaluation API. This keeps notices fail-safe when the remote config is unavailable and removes the PostHog feature-flag request from notice evaluation ([#7185](https://github.com/mem0ai/mem0/pull/7185))
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="2026-08-24" description="v3.1.7">
|
||||
|
||||
**Bug Fixes:**
|
||||
- **Vector Stores:** Redis and Valkey `search()` / `get()` / `list()` now preserve `agent_id`, `run_id`, and `user_id` as snake_case in the returned payload. The shared payload formatter camelCased every key including those three identity fields, so entity ids came back as `agentId` / `runId` / `userId`, inconsistent with every other vector store ([#6902](https://github.com/mem0ai/mem0/pull/6902))
|
||||
- **Memory (OSS):** Embedding-cache lookups now use `Object.prototype.hasOwnProperty.call()` instead of the `in` operator or a falsy `||` check. Memory text matching an inherited `Object.prototype` property name (`constructor`, `toString`, and similar) previously short-circuited the lookup and resolved to that inherited value instead of computing a real embedding, silently corrupting the stored vector ([#6903](https://github.com/mem0ai/mem0/pull/6903))
|
||||
- **Client:** `getAll()` now sends `page` and `pageSize` as independent query params instead of requiring both to be set before either was sent. Passing only `pageSize` without `page` previously had it silently dropped, so results came back at the server's default page size ([#6900](https://github.com/mem0ai/mem0/pull/6900))
|
||||
- **LLMs:** Add `providerOverride` to the Bedrock `LLMConfig`, an explicit provider name for when `model` is an application inference profile ARN whose opaque ID has no provider substring for `extractProvider()` to detect. Without it, those ARNs threw before the provider-specific settings could be initialized ([#6899](https://github.com/mem0ai/mem0/pull/6899))
|
||||
|
||||
**Security:**
|
||||
- **Dependencies:** Resolved 17 additional high and critical severity dependency vulnerabilities across 5 pnpm workspaces (`mem0-ts`, `vercel-ai-sdk`, `n8n-nodes-mem0`, `zapier-mem0`, `server/dashboard`) via `pnpm.overrides` and a `tar` patch ([#7032](https://github.com/mem0ai/mem0/pull/7032))
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="2026-08-11" description="v3.1.6">
|
||||
|
||||
**New Features:**
|
||||
@@ -1864,17 +1823,6 @@ See the [TypeScript SDK migration guide](https://docs.mem0.ai/migration/ts-v2-to
|
||||
|
||||
<Tab title="CLI">
|
||||
|
||||
<Update label="2026-08-24" description="Python v0.2.12 / Node v0.2.13">
|
||||
|
||||
**New Features:**
|
||||
- **`version`:** New `mem0 version` subcommand, alongside the existing `--version` flag, so scripts and agent harnesses can read the CLI version as a regular subcommand instead of a root-level flag (Python and Node [#6907](https://github.com/mem0ai/mem0/pull/6907))
|
||||
- **`add`:** New `--agent-custom-instructions` flag, threaded through to `agent_custom_instructions` on the `/v3/memories/add/` payload: a second extraction instruction set that applies only to agent-scoped memories, matching the SDKs' `agentCustomInstructions` / `agent_custom_instructions` support (Python and Node [#6910](https://github.com/mem0ai/mem0/pull/6910))
|
||||
|
||||
**Documentation:**
|
||||
- **`search --filter`:** The `--filter` help text and `docs/platform/cli.mdx` now spell out the JSON shape (`{"AND": [...]}` / `{"OR": [...]}`) with a concrete example instead of just calling it "an advanced filter expression," and a matching example command was added to both the CLI help text and the docs page (Python and Node [#6907](https://github.com/mem0ai/mem0/pull/6907))
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="2026-08-04" description="Python v0.2.11 / Node v0.2.12">
|
||||
|
||||
**New Features:**
|
||||
@@ -2060,22 +2008,6 @@ A full-featured command-line interface for Mem0, available in both Python and No
|
||||
<Tabs>
|
||||
<Tab title="Mem0 Plugin">
|
||||
|
||||
<Update label="2026-08-24" description="mem0-plugin v0.2.15">
|
||||
|
||||
**Fixes:**
|
||||
- **Search:** A failed search request now prints `[mem0] search request failed: <error>` to stderr before returning no results. `search_memories()` swallowed every exception and returned `[]`, so an expired API key, a network failure, or a 500 from the backend was indistinguishable from a genuine "nothing stored yet" and the agent carried on with no context and no warning. Shared by Claude Code, Cursor, Codex, Antigravity, and Kimi ([#6898](https://github.com/mem0ai/mem0/pull/6898))
|
||||
- **Cursor:** `mcpServers` in `.cursor-plugin/plugin.json` now points at `./.cursor-mcp.json` instead of `.cursor-mcp.json`. The un-prefixed path resolved inconsistently depending on Cursor's working directory when it loaded the plugin ([#6948](https://github.com/mem0ai/mem0/pull/6948))
|
||||
- **Codex:** `install_codex_hooks.py` now prints all six registered events (`PreToolUse, SessionStart, UserPromptSubmit, PostToolUse, Stop, PreCompact`) after installing, instead of a stale four-event list left over from an earlier version of the installer. The README's hook table is corrected to match, documenting the three `PreToolUse` handlers and two `PostToolUse` handlers that were previously undocumented ([#6948](https://github.com/mem0ai/mem0/pull/6948))
|
||||
|
||||
**Documentation:**
|
||||
- New [Claude.ai](/integrations/claude-ai) integration page ([#6948](https://github.com/mem0ai/mem0/pull/6948))
|
||||
|
||||
<Note>
|
||||
The Claude Code, Cursor, and Codex per-editor manifests (`.claude-plugin/plugin.json`, `.cursor-plugin/plugin.json`, `.codex-plugin/plugin.json`) had drifted to `0.2.13` while the `.claude-plugin/marketplace.json` and `.cursor-plugin/marketplace.json` listings had already moved to `0.2.14`, so installs were pinned one release behind what the marketplace advertised. This release realigns every manifest and marketplace listing to `0.2.15`.
|
||||
</Note>
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="2026-08-04" description="mem0-plugin v0.2.14">
|
||||
|
||||
**Fixes:**
|
||||
@@ -2428,13 +2360,6 @@ Initial release of the Mem0 plugin for Claude Code and Cursor, followed by Codex
|
||||
|
||||
<Tab title="Antigravity">
|
||||
|
||||
<Update label="2026-08-24" description="Antigravity plugin v0.1.7">
|
||||
|
||||
**Fixes:**
|
||||
- **Hooks:** The `mem0-ensure-deps` and `mem0-session-start` hook commands in `hooks.json` no longer redirect stderr to `/dev/null`. Both commands still end in `|| true` so a failure can't block startup, but a broken dependency install or session bootstrap now shows up in the Antigravity hook log instead of failing invisibly ([#6948](https://github.com/mem0ai/mem0/pull/6948))
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="2026-08-04" description="Antigravity plugin v0.1.6">
|
||||
|
||||
**Fixes:**
|
||||
@@ -2502,31 +2427,8 @@ Existing memories written by the previous versions are not rewritten. If your me
|
||||
|
||||
</Tab>
|
||||
|
||||
<Tab title="Kimi">
|
||||
|
||||
<Update label="2026-08-24" description="kimi-plugin v0.1.0">
|
||||
|
||||
**Initial release** of the Mem0 plugin for Kimi Code, sharing its scripts, skills, and marketplace listing with the Claude Code / Cursor / Codex / Antigravity plugin family ([#6919](https://github.com/mem0ai/mem0/pull/6919))
|
||||
|
||||
**New Features:**
|
||||
- **MCP server:** Registers the hosted Mem0 MCP server at `https://mcp.mem0.ai/mcp/`, authenticated via the `MEM0_API_KEY` env var as a bearer token.
|
||||
- **Lifecycle hooks:** Wires SessionStart (loads context through the `context-loader` skill), UserPromptSubmit, three PreToolUse hooks (blocks direct `Write`/`Edit`/`MultiEdit` to memory files, enforces metadata defaults on Mem0 MCP tool calls, and injects context on file reads), two PostToolUse hooks (post-tool tracking and Bash-output scanning), Stop, and PreCompact.
|
||||
- **Hook adapter:** `kimi_hook_shim.sh` normalizes Kimi Code's hook contract to what the shared hook scripts expect: it resolves the real project directory from the payload's `cwd` (Kimi forces the plugin root as the working directory), converts the array-shaped `prompt` field and the `tool_output` / `tool_input.path` field names to the Claude-style shapes the scripts already handle, and translates the plugin-scoped MCP tool name prefix.
|
||||
- **Shared policy skill:** Bundles the `/mem0:policy` skill for managing the `## Instructions` and `## Agent Instructions` sections of `mem0.md`.
|
||||
|
||||
</Update>
|
||||
|
||||
</Tab>
|
||||
|
||||
<Tab title="OpenClaw">
|
||||
|
||||
<Update label="2026-08-24" description="openclaw-mem0 v1.0.16">
|
||||
|
||||
**Security:**
|
||||
- **Dependencies:** Tightened the `undici` pnpm override from `<6.27.0 → >=6.27.0 <8.0.0` to `<7.29.0 → >=7.29.0 <8.0.0`, closing a newer CVE range the previous floor didn't cover, as part of a wider dependency patch sweep across the pnpm workspaces ([#6847](https://github.com/mem0ai/mem0/pull/6847))
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="2026-08-01" description="openclaw-mem0 v1.0.15">
|
||||
|
||||
**Improvements:**
|
||||
@@ -2790,13 +2692,6 @@ Existing memories written by the previous versions are not rewritten. If your me
|
||||
|
||||
<Tab title="Pi Agent">
|
||||
|
||||
<Update label="2026-08-24" description="Pi Agent plugin v0.1.5">
|
||||
|
||||
**Security:**
|
||||
- **Dependencies:** Tightened the `undici` pnpm override from `<6.27.0 → >=6.27.0 <8.0.0` / `>=8.0.0 <8.5.0 → >=8.5.0` to `<7.29.0 → >=7.29.0 <8.0.0` / `>=8.0.0 <8.9.0 → >=8.9.0 <9.0.0`, closing a newer CVE range the previous floors didn't cover, as part of a wider dependency patch sweep across the pnpm workspaces ([#6847](https://github.com/mem0ai/mem0/pull/6847))
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="2026-08-01" description="Pi Agent plugin v0.1.4">
|
||||
|
||||
**Security:**
|
||||
@@ -2854,71 +2749,8 @@ Existing memories written by the previous versions are not rewritten. If your me
|
||||
|
||||
</Tab>
|
||||
|
||||
<Tab title="Strands">
|
||||
|
||||
<Update label="2026-08-25" description="mem0-strands v0.1.1">
|
||||
|
||||
**New Features:**
|
||||
- **Usage telemetry:** Anonymous usage events (`strands.store.init`, `strands.store.search`, `strands.store.add`, `strands.store.add_messages`) ride the Mem0 SDK's existing PostHog client, unsampled, with no new dependency. Events carry only counts, durations, booleans, and coarse failure kinds: never queries, memory text, message content, entity ids, metadata, or API keys. Opt out with `MEM0_TELEMETRY=false` ([#7110](https://github.com/mem0ai/mem0/pull/7110))
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="2026-08-24" description="mem0-strands v0.1.0">
|
||||
|
||||
**Initial release** of [`mem0-strands`](https://pypi.org/project/mem0-strands/), a native `MemoryStore` that plugs Mem0 into the [Strands Agents](https://strandsagents.com/) `MemoryManager` ([#7021](https://github.com/mem0ai/mem0/pull/7021))
|
||||
|
||||
**New Features:**
|
||||
- **Automatic recall and injection:** `Mem0MemoryStore.search()` runs every turn through the `MemoryManager`, so relevant memories are searched and prepended to the prompt with no explicit tool call required.
|
||||
- **Server-side extraction:** `add_messages()` renders raw conversation turns to text and hands them to Mem0's own extraction pipeline (`infer=True`), so enabling extraction skips an extra client-side model call to distill facts first.
|
||||
- **Verbatim writes:** `add()` stores a single fact exactly as given (`infer=False`), the sink used by the `add_memory` tool or a client-side extractor.
|
||||
- **Entity scoping:** Accepts `user_id`, `agent_id`, `run_id`, and `app_id`; at least one is required, and mixing the platform-only `app_id` with a self-hosted `config` raises at construction instead of failing on the first write.
|
||||
- **Hosted or self-hosted:** Defaults to the hosted Mem0 Platform via `api_key` (or `$MEM0_API_KEY`), or pass a `config` dict for a self-hosted Mem0 OSS backend.
|
||||
- **Non-blocking construction:** The underlying Mem0 client is built lazily on first use inside `asyncio.to_thread`, so API-key validation and OSS embedder/vector-store setup never block the event loop.
|
||||
|
||||
<Note>
|
||||
`Mem0MemoryStore` is the automatic-recall store for the `MemoryManager`. For a model-called tool instead, use the [`mem0_memory`](https://github.com/strands-agents/tools) tool from `strands-agents-tools`; both share the same Mem0 backend and namespace. See [Strands Agents](/integrations/strands) for setup.
|
||||
</Note>
|
||||
|
||||
</Update>
|
||||
|
||||
</Tab>
|
||||
|
||||
<Tab title="DeepSeek Harness">
|
||||
|
||||
<Update label="2026-08-25" description="deepseek-plugin v0.1.1">
|
||||
|
||||
**New Features:**
|
||||
- **Usage telemetry:** Anonymous usage events (`deepseek.plugin.mounted`, `deepseek.tool.search_memory`, `deepseek.tool.add_memory`) are batched to PostHog over native fetch and flushed in the background. Events carry only tool names, durations, counts, and coarse failure kinds: never queries, memory text, filters, or API keys. Opt out with `MEM0_TELEMETRY=false` ([#7110](https://github.com/mem0ai/mem0/pull/7110))
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="2026-08-24" description="deepseek-plugin v0.1.0">
|
||||
|
||||
**Initial release** of [`deepseek-plugin`](https://www.npmjs.com/package/@mem0/deepseek-plugin), a native DeepSeek Harness (Cordis) plugin that registers Mem0 as two agent-callable tools ([#7027](https://github.com/mem0ai/mem0/pull/7027))
|
||||
|
||||
**New Features:**
|
||||
- **`search_memory`:** Recalls facts relevant to a query, with an optional `limit` (default 10) and per-call `userId` / `agentId` / `runId` scope overrides.
|
||||
- **`add_memory`:** Stores a fact for future sessions, tagged `source: "DEEPSEEK_HARNESS"` for backend attribution; extraction runs asynchronously server-side, so a stored fact may take a moment to become searchable.
|
||||
- **Cordis lifecycle:** `apply(ctx, config)` declares `inject = ['tools']`, so the plugin waits for the harness tool registry to exist, and both tools are registered via `ctx.tools.register()` so they auto-unregister when the plugin unmounts.
|
||||
- **Config:** `userId` is required; `apiKey` defaults to `$MEM0_API_KEY`; `host` optionally points at a dedicated Mem0 Platform base URL (not a switch to self-hosted Mem0 OSS).
|
||||
|
||||
<Note>
|
||||
Developer preview: auto-capture and auto-recall (memory injected into context automatically, without an explicit tool call) are planned but not yet built. The backend's `KNOWN_EVENT_SOURCES` allowlist also needs `"DEEPSEEK_HARNESS"` added before usage surfaces by name in telemetry rather than bucketing into "OTHERS". See [DeepSeek Harness](/integrations/deepseek-plugin) for setup.
|
||||
</Note>
|
||||
|
||||
</Update>
|
||||
|
||||
</Tab>
|
||||
|
||||
<Tab title="Vercel AI SDK">
|
||||
|
||||
<Update label="2026-08-24" description="Vercel AI SDK v3.0.2">
|
||||
|
||||
**Security:**
|
||||
- **Dependencies:** Tightened the `js-yaml` pnpm overrides from `<3.15.0 → >=3.15.0 <4.0.0` / `>=4.0.0 <4.3.0 → >=4.3.0 <5.0.0` to `<3.15.1 → >=3.15.1 <4.0.0` / `>=4.0.0 <4.3.1 → >=4.3.1 <5.0.0`, closing a newer CVE range the previous floors didn't cover, as part of a wider dependency patch sweep across the pnpm workspaces ([#7032](https://github.com/mem0ai/mem0/pull/7032))
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="2026-08-01" description="Vercel AI SDK v3.0.1">
|
||||
|
||||
**Security:**
|
||||
@@ -3011,13 +2843,6 @@ Existing memories written by the previous versions are not rewritten. If your me
|
||||
|
||||
<Tab title="n8n">
|
||||
|
||||
<Update label="2026-08-24" description="n8n-nodes-mem0 v0.1.4">
|
||||
|
||||
**Security:**
|
||||
- **Dependencies:** Add `js-yaml` pnpm overrides (`<3.15.1 → >=3.15.1 <4.0.0`, `>=4.0.0 <4.3.1 → >=4.3.1 <5.0.0`) to close a HIGH/CRITICAL severity advisory, as part of a wider dependency patch sweep across the pnpm workspaces ([#7032](https://github.com/mem0ai/mem0/pull/7032))
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="2026-08-05" description="n8n-nodes-mem0 v0.1.3">
|
||||
|
||||
**Changes:**
|
||||
@@ -3062,21 +2887,6 @@ Existing memories written by the previous versions are not rewritten. If your me
|
||||
|
||||
<Tab title="Zapier">
|
||||
|
||||
<Update label="2026-08-24" description="Zapier app v0.1.2">
|
||||
|
||||
**Changes:**
|
||||
- **Connection label:** The saved connection now shows the account's email (`{{user_email}}`, read from the `/v1/ping/` test response) in the Zap editor instead of a static "Mem0" label, so a user with more than one Mem0 connection can tell them apart ([#6985](https://github.com/mem0ai/mem0/pull/6985))
|
||||
- **Action and search copy:** Reworded labels and descriptions to address Zapier's publishing review: **Get Memories** is now **Find Memories by User**, **Search Memories** is now **Find Memories**, and every description now reads as a third-person statement of what the step does ([#6985](https://github.com/mem0ai/mem0/pull/6985))
|
||||
- **Attribution:** Add Memory now tags writes with `source: "ZAPIER"` in the request body, so usage is attributed to this integration server-side ([#6985](https://github.com/mem0ai/mem0/pull/6985))
|
||||
|
||||
**Removed:**
|
||||
- **Client-side telemetry:** Deleted the embedded PostHog telemetry client (`telemetry.ts`) and its call sites in Add Memory, Get Memories, and Search Memories. Usage attribution now happens server-side via the `source: "ZAPIER"` tag above instead of a separate fire-and-forget analytics call from inside the published app ([#6985](https://github.com/mem0ai/mem0/pull/6985))
|
||||
|
||||
**Security:**
|
||||
- **Dependencies:** Tightened the `undici` pnpm override to `<7.29.0 → >=7.29.0 <8.0.0` / `>=8.0.0 <8.9.0 → >=8.9.0 <9.0.0` and added a `brace-expansion` override ([#6847](https://github.com/mem0ai/mem0/pull/6847)), then added a `js-yaml` override (`<3.15.1 → >=3.15.1 <4.0.0`, `>=4.0.0 <4.3.1 → >=4.3.1 <5.0.0`) closing a further HIGH/CRITICAL severity advisory ([#7032](https://github.com/mem0ai/mem0/pull/7032))
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="2026-08-04" description="Zapier app v0.1.1">
|
||||
|
||||
**Bug Fixes:**
|
||||
|
||||
@@ -99,7 +99,6 @@ Here are the parameters available for configuring the Hugging Face embedder:
|
||||
| `embedding_dims` | Dimensions of the embedding model | `selected_model_dimensions` |
|
||||
| `model_kwargs` | Additional arguments for the model | `None` |
|
||||
| `huggingface_base_url` | URL to connect to Text Embeddings Inference (TEI) API | `None` |
|
||||
| `api_key` | API key for the endpoint; falls back to the `HUGGINGFACE_API_KEY` env var. Only used on the `huggingface_base_url` path | `"hf"` |
|
||||
</Tab>
|
||||
<Tab title="TypeScript">
|
||||
| Parameter | Description | Default Value |
|
||||
|
||||
@@ -14,7 +14,7 @@ description: "Use Oracle Database AI Vector Search as a vector store in Mem0 for
|
||||
|
||||
<CodeGroup>
|
||||
```bash Python
|
||||
pip install mem0ai
|
||||
pip install oracledb
|
||||
```
|
||||
|
||||
```bash TypeScript
|
||||
@@ -141,13 +141,11 @@ const config = {
|
||||
|
||||
Here are the parameters available for configuring Oracle AI Vector Search:
|
||||
|
||||
Provide either `connection_params`/`connectionParams` or an existing connection or pool as `client`.
|
||||
|
||||
| Python | TypeScript | Description | Default Value |
|
||||
| --- | --- | --- | --- |
|
||||
| `connection_params` | `connectionParams` | Connection settings passed to the Oracle driver, such as `user`, `password` and `dsn` (`connectString` in TypeScript). Required unless `client` is provided. See the [Python](https://python-oracledb.readthedocs.io/en/latest/user_guide/connection_handling.html) or [Node.js](https://node-oracledb.readthedocs.io/en/latest/user_guide/connection_handling.html) connection handling guide. | `None` |
|
||||
| `connection_params` | `connectionParams` | Connection settings passed to the Oracle driver, such as `user`, `password` and `dsn` (`connectString` in TypeScript). See the [Python](https://python-oracledb.readthedocs.io/en/latest/user_guide/connection_handling.html) or [Node.js](https://node-oracledb.readthedocs.io/en/latest/user_guide/connection_handling.html) connection handling guide. | `None` |
|
||||
| `use_connection_pool` | `useConnectionPool` | Create a connection pool from the connection parameters instead of a single connection | `True` |
|
||||
| `client` | `client` | An existing Oracle connection or pool to use instead of building one from the connection parameters. Required unless connection parameters are provided. | `None` |
|
||||
| `client` | `client` | An existing Oracle connection or pool to use instead of building one from the connection parameters | `None` |
|
||||
| `collection_name` | `collectionName` | Name of the Oracle table that stores vectors and payloads | `mem0` |
|
||||
| `embedding_model_dims` | `embeddingModelDims` | Dimension of your embedding vectors, must be greater than 0 | `1536` |
|
||||
| `distance_metric` | `distanceMetric` | Distance function used for indexing and search: `COSINE`, `EUCLIDEAN`, `EUCLIDEAN_SQUARED`, `DOT`, `HAMMING` or `MANHATTAN` | `COSINE` |
|
||||
@@ -224,21 +222,15 @@ Multiple fields at the top level are combined with `AND`:
|
||||
```python Python
|
||||
m.search(
|
||||
"movie recommendations",
|
||||
filters={
|
||||
"user_id": "alice",
|
||||
"category": {"in": ["movies", "books"]},
|
||||
"rating": {"gte": 4},
|
||||
},
|
||||
user_id="alice",
|
||||
filters={"category": {"in": ["movies", "books"]}, "rating": {"gte": 4}},
|
||||
)
|
||||
```
|
||||
|
||||
```typescript TypeScript
|
||||
await memory.search("movie recommendations", {
|
||||
filters: {
|
||||
user_id: "alice",
|
||||
category: { in: ["movies", "books"] },
|
||||
rating: { gte: 4 },
|
||||
},
|
||||
userId: "alice",
|
||||
filters: { category: { in: ["movies", "books"] }, rating: { gte: 4 } },
|
||||
});
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
@@ -79,33 +79,6 @@ For detailed guidance on pull requests, refer to [GitHub's documentation](https:
|
||||
|
||||
---
|
||||
|
||||
## Installing from Source
|
||||
|
||||
If you just want to run the latest, unreleased SDK code instead of the published `mem0ai` package, for example to try out a fix before it ships, or to depend on a fork, install directly from a local clone rather than setting up the full contributor environment below.
|
||||
|
||||
### Python SDK
|
||||
|
||||
```bash
|
||||
git clone https://github.com/mem0ai/mem0.git
|
||||
cd mem0
|
||||
pip install -e .
|
||||
```
|
||||
|
||||
This installs `mem0ai` in editable mode, so edits under `mem0/` take effect immediately without reinstalling. Add an extra if you need one, e.g. `pip install -e ".[vector-stores]"` (see `pyproject.toml` for the full list). If you are contributing to the SDK itself and need every optional dependency for the test suite, use `hatch` instead, see [Dependency Management](#dependency-management).
|
||||
|
||||
### TypeScript SDK
|
||||
|
||||
```bash
|
||||
git clone https://github.com/mem0ai/mem0.git
|
||||
cd mem0/mem0-ts
|
||||
pnpm install
|
||||
pnpm run build
|
||||
```
|
||||
|
||||
This builds `mem0-ts/dist` (CJS + ESM). To use it from another local project, add it as a `file:` dependency pointing at `mem0-ts`, or run `pnpm link --global` inside `mem0-ts` and `pnpm link --global mem0ai` in the consuming project.
|
||||
|
||||
---
|
||||
|
||||
## Python SDK (`mem0/`)
|
||||
|
||||
### Dependency Management
|
||||
|
||||
@@ -0,0 +1,519 @@
|
||||
---
|
||||
title: Control Memory Ingestion
|
||||
description: "Filter speculation, enforce formats, and gate low-confidence data before it persists."
|
||||
---
|
||||
|
||||
<Info icon="cloud">
|
||||
**Works with:** Mem0 Platform (`MemoryClient`)
|
||||
</Info>
|
||||
|
||||
AI assistants plugged with memory systems face a problem - they often store everything. Not every conversation needs to be remembered, and not every detail should go to the memory store. Without proper controls, memory systems accumulate unreliable data.
|
||||
|
||||
Mem0 lets you control your memory ingestion pipeline. In this cookbook, we'll demonstrate these controls using a medical assistant example - showing how to filter unwanted data, enforce data formats, and implement confidence-based storage.
|
||||
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
Without controls, everything gets stored - speculation, low-confidence data, and information that shouldn't persist. This uncontrolled ingestion leads to cluttered memory and retrieval failures.
|
||||
|
||||
Mem0 provides **three tools to control** what gets stored:
|
||||
|
||||
1. **Custom instructions** define what to remember and what to ignore.
|
||||
2. **Confidence thresholds** ensure only verified facts persist.
|
||||
3. **Memory updates** let you change information without creating duplicates.
|
||||
|
||||
In this tutorial, we will:
|
||||
|
||||
- Filter speculative statements with custom instructions
|
||||
- Configure confidence thresholds for fact verification
|
||||
- Update stored information without duplication
|
||||
- Build a complete ingestion pipeline
|
||||
|
||||
---
|
||||
|
||||
## Setup
|
||||
|
||||
```python
|
||||
from mem0 import MemoryClient
|
||||
|
||||
client = MemoryClient(api_key="your-api-key")
|
||||
```
|
||||
|
||||
<Note>
|
||||
Replace `your-api-key` with your actual Mem0 API key from the <a href="https://app.mem0.ai?utm_source=oss&utm_medium=cookbook-memory-ingestion" rel="nofollow">dashboard</a>. Without proper API authentication, memory operations will fail.
|
||||
</Note>
|
||||
|
||||
---
|
||||
|
||||
## The Problem
|
||||
|
||||
Uncontrolled ingestion stores everything, including speculation:
|
||||
|
||||
```python
|
||||
# Patient mentions speculation
|
||||
messages = [{"role": "user", "content": "I think I might be allergic to penicillin"}]
|
||||
client.add(messages, user_id="patient_123")
|
||||
|
||||
# Check what got stored
|
||||
results = client.search("patient allergies", filters={"user_id": "patient_123"})
|
||||
print(results['results'][0]['memory'])
|
||||
|
||||
```
|
||||
|
||||
**Output:**
|
||||
|
||||
```
|
||||
Patient is allergic to penicillin
|
||||
```
|
||||
|
||||
<Warning>
|
||||
Without custom instructions, AI assistants treat speculation as confirmed facts. "I think I might be allergic" becomes "Patient is allergic": a dangerous transformation in sensitive domains like healthcare, legal, or financial services.
|
||||
</Warning>
|
||||
|
||||
The speculation became a confirmed fact. Let's add controls.
|
||||
|
||||
---
|
||||
|
||||
## Custom Instructions
|
||||
|
||||
Custom instructions tell Mem0 what to store and what to ignore.
|
||||
|
||||
```python
|
||||
instructions = """
|
||||
Only store CONFIRMED medical facts.
|
||||
|
||||
Store:
|
||||
- Confirmed diagnoses from doctors
|
||||
- Known allergies with documented reactions
|
||||
- Current medications being taken
|
||||
|
||||
Ignore:
|
||||
- Speculation (words like "might", "maybe", "I think")
|
||||
- Unverified symptoms
|
||||
- Casual mentions without confirmation
|
||||
"""
|
||||
|
||||
client.project.update(custom_instructions=instructions)
|
||||
|
||||
# Same speculative statement
|
||||
messages = [{"role": "user", "content": "I think I might be allergic to penicillin"}]
|
||||
client.add(messages, user_id="patient_123")
|
||||
|
||||
# Check what got stored
|
||||
results = client.get_all(filters={"user_id": "patient_123"})
|
||||
print(f"Memories stored: {len(results['results'])}")
|
||||
|
||||
```
|
||||
|
||||
**Output:**
|
||||
|
||||
```
|
||||
Memories stored: 0
|
||||
```
|
||||
|
||||
<Info>
|
||||
**Expected output:** Zero memories stored. The speculative statement "I think I might be allergic" was filtered out before reaching storage. Custom instructions are actively blocking unreliable data.
|
||||
</Info>
|
||||
|
||||
The speculation was filtered out.
|
||||
|
||||
---
|
||||
|
||||
## Designing Custom Instructions
|
||||
|
||||
When designing instructions, consider the trade-off between precision and recall:
|
||||
|
||||
**Too restrictive:** You'll miss important information (false negatives)
|
||||
|
||||
```python
|
||||
# Too strict - filters out useful context
|
||||
"""
|
||||
Only store information if explicitly stated by a doctor with full name,
|
||||
date, time, and medical license number.
|
||||
"""
|
||||
|
||||
```
|
||||
|
||||
**Too permissive:** You'll store unreliable data (false positives)
|
||||
|
||||
```python
|
||||
# Too loose - stores speculation as fact
|
||||
"""
|
||||
Store any health-related information mentioned.
|
||||
"""
|
||||
|
||||
```
|
||||
|
||||
**Balanced approach:**
|
||||
|
||||
```python
|
||||
# Clear categories with examples
|
||||
"""
|
||||
Store CONFIRMED facts:
|
||||
- Diagnoses: "Dr. Smith diagnosed hypertension on March 15th"
|
||||
- Allergies: "Patient had hives reaction to penicillin"
|
||||
- Medications: "Taking Lisinopril 10mg daily"
|
||||
|
||||
Ignore SPECULATION:
|
||||
- "I think I might have..."
|
||||
- "Maybe it's..."
|
||||
- "Could be related to..."
|
||||
"""
|
||||
|
||||
```
|
||||
|
||||
<Tip>
|
||||
Start with strict instructions (only store confirmed facts), then relax them based on your use case. It's easier to allow more data than to clean up polluted memory. Test with sample conversations before deploying to production.
|
||||
</Tip>
|
||||
|
||||
Start with clear categories and iterate based on retrieval quality.
|
||||
|
||||
---
|
||||
|
||||
## Confidence Thresholds
|
||||
|
||||
Mem0 assigns confidence scores to extracted memories. Use these to filter low-quality data.
|
||||
|
||||
### Setting Thresholds
|
||||
|
||||
Setting the right confidence threshold depends on your application:
|
||||
|
||||
- **High-stakes domains** (medical, legal): Require 0.8+ confidence
|
||||
- **General assistants**: 0.6+ confidence is often sufficient
|
||||
- **Exploratory systems**: Lower thresholds (0.4+) capture more data
|
||||
|
||||
Test your pipeline with multiple input examples and threshold combinations to find what works for your use case.
|
||||
|
||||
```python
|
||||
# Configure stricter instructions
|
||||
client.project.update(
|
||||
custom_instructions="""
|
||||
Only extract memories with HIGH confidence.
|
||||
Require specific details (dates, dosages, doctor names) for medical facts.
|
||||
Skip vague or uncertain statements.
|
||||
"""
|
||||
)
|
||||
|
||||
# Test with uncertain statement
|
||||
messages = [{"role": "user", "content": "The doctor mentioned something about my blood pressure"}]
|
||||
result1 = client.add(messages, user_id="patient_123")
|
||||
|
||||
# Test with confirmed fact
|
||||
messages = [{"role": "user", "content": "Dr. Smith diagnosed me with hypertension on March 15th"}]
|
||||
result2 = client.add(messages, user_id="patient_123")
|
||||
|
||||
print("Vague statement stored:", len(result1['results']) > 0)
|
||||
print("Confirmed fact stored:", len(result2['results']) > 0)
|
||||
|
||||
```
|
||||
|
||||
**Output:**
|
||||
|
||||
```
|
||||
Vague statement stored: False
|
||||
Confirmed fact stored: True
|
||||
```
|
||||
|
||||
<Info icon="check">
|
||||
**Expected behavior:** Low-confidence extractions are now filtered out automatically. Only verified facts with specific details (names, dates, dosages) persist in memory. The confidence threshold is working.
|
||||
</Info>
|
||||
|
||||
The vague statement was filtered for low confidence. The confirmed fact with specific details was stored.
|
||||
|
||||
---
|
||||
|
||||
## Filtering Sensitive Information
|
||||
|
||||
Custom instructions can prevent storing personal identifiers:
|
||||
|
||||
```python
|
||||
client.project.update(
|
||||
custom_instructions="""
|
||||
Medical memory rules:
|
||||
|
||||
STORE:
|
||||
- Confirmed diagnoses
|
||||
- Verified allergies
|
||||
- Current medications
|
||||
|
||||
NEVER STORE:
|
||||
- Social Security Numbers
|
||||
- Insurance policy numbers
|
||||
- Credit card information
|
||||
- Full addresses
|
||||
- Phone numbers
|
||||
|
||||
Replace identifiers with generic references if mentioned.
|
||||
"""
|
||||
)
|
||||
|
||||
# Test with PII
|
||||
messages = [
|
||||
{"role": "user", "content": "My SSN is 123-45-6789 and I'm allergic to penicillin"}
|
||||
]
|
||||
client.add(messages, user_id="patient_123")
|
||||
|
||||
# Check what was stored
|
||||
results = client.get_all(filters={"user_id": "patient_123"})
|
||||
for result in results['results']:
|
||||
print(result['memory'])
|
||||
|
||||
```
|
||||
|
||||
**Output:**
|
||||
|
||||
```
|
||||
Patient is allergic to penicillin
|
||||
```
|
||||
|
||||
The SSN was filtered out, but the allergy was stored.
|
||||
|
||||
---
|
||||
|
||||
## Updating Memories
|
||||
|
||||
When information changes, update existing memories instead of creating duplicates.
|
||||
|
||||
```python
|
||||
# Initial allergy stored
|
||||
result = client.add(
|
||||
[{"role": "user", "content": "Patient confirmed allergy to penicillin with documented hives reaction"}],
|
||||
user_id="patient_123"
|
||||
)
|
||||
|
||||
memory_id = result['results'][0]['id']
|
||||
print(f"Stored memory: {memory_id}")
|
||||
|
||||
# Later, patient gets retested - allergy was false positive
|
||||
client.update(
|
||||
memory_id=memory_id,
|
||||
text="Patient tested negative for penicillin allergy on April 2nd, 2025. Previous allergy was false positive.",
|
||||
metadata={"verified": True, "updated_date": "2025-04-02"}
|
||||
)
|
||||
|
||||
# Retrieve the updated memory
|
||||
updated = client.get(memory_id)
|
||||
print(f"\\nUpdated memory: {updated['memory']}")
|
||||
print(f"Metadata: {updated['metadata']}")
|
||||
|
||||
```
|
||||
|
||||
**Output:**
|
||||
|
||||
```
|
||||
Stored memory: mem_abc123
|
||||
|
||||
Updated memory: Patient tested negative for penicillin allergy on April 2nd, 2025. Previous allergy was false positive.
|
||||
Metadata: {'verified': True, 'updated_date': '2025-04-02'}
|
||||
|
||||
```
|
||||
|
||||
### Benefits of Updating
|
||||
|
||||
**Preserves history:**
|
||||
|
||||
- `created_at` shows when the memory was first stored
|
||||
- `updated_at` shows when it was modified
|
||||
- Audit trail for compliance
|
||||
|
||||
**Avoids conflicts:**
|
||||
|
||||
- No duplicate or contradicting memories
|
||||
- Single source of truth for each fact
|
||||
|
||||
<Warning>
|
||||
That “no duplicates” promise comes from the inference pipeline. Keep `infer=True` when you rely on automatic updates. Raw imports (`infer=False`) skip conflict checks, so mixing the two modes for the same fact will create duplicates.
|
||||
</Warning>
|
||||
|
||||
### Pick the right inference mode
|
||||
|
||||
| Mode | What it does | Best for | Watch out for |
|
||||
| --- | --- | --- | --- |
|
||||
| `infer=True` *(default)* | Runs the LLM pipeline so Mem0 extracts structured facts and resolves conflicts automatically. | Daily conversations, preference tracking, anything you want deduped. | Slightly slower because inference runs on every write. |
|
||||
| `infer=False` | Stores your payload exactly as-is: no inference, no dedupe. | Bulk imports, compliance snapshots, curated facts you already trust. | Later `infer=True` calls for the same fact will create duplicates you must clean manually. |
|
||||
|
||||
<Tip>
|
||||
Stay consistent per data source. If you need both behaviors, keep them in separate scopes (e.g., different `app_id` or `run_id`) so you always know which memories are inferred vs direct imports.
|
||||
</Tip>
|
||||
|
||||
---
|
||||
|
||||
## Update vs Delete
|
||||
|
||||
When should you update vs delete?
|
||||
|
||||
### Update when:
|
||||
|
||||
- Information changes but remains relevant
|
||||
- You need audit history
|
||||
- The memory has relationships to other data
|
||||
|
||||
```python
|
||||
# Medication dosage changed
|
||||
client.update(
|
||||
memory_id=med_id,
|
||||
text="Taking Lisinopril 20mg daily (increased from 10mg on March 1st)"
|
||||
)
|
||||
|
||||
```
|
||||
|
||||
### Delete when:
|
||||
|
||||
- Information was completely wrong
|
||||
- Memory is no longer relevant
|
||||
- Duplicate entry
|
||||
|
||||
```python
|
||||
# Duplicate entry
|
||||
client.delete(memory_id)
|
||||
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Putting It Together
|
||||
|
||||
Here's a complete ingestion pipeline with all controls:
|
||||
|
||||
```python
|
||||
from mem0 import MemoryClient
|
||||
import os
|
||||
|
||||
# Initialize client
|
||||
client = MemoryClient(api_key=os.getenv("MEM0_API_KEY"))
|
||||
|
||||
# Configure custom instructions
|
||||
client.project.update(
|
||||
custom_instructions="""
|
||||
Medical memory assistant rules:
|
||||
|
||||
STORE:
|
||||
- Confirmed diagnoses (with doctor name and date)
|
||||
- Verified allergies (with reaction details)
|
||||
- Current medications (with dosage)
|
||||
|
||||
IGNORE:
|
||||
- Speculation (might, maybe, possibly)
|
||||
- Unverified symptoms
|
||||
- Personal identifiers (SSN, insurance numbers)
|
||||
|
||||
CONFIDENCE:
|
||||
Require high confidence. Reject vague or uncertain statements.
|
||||
Require specific details: names, dates, dosages.
|
||||
"""
|
||||
)
|
||||
|
||||
# Helper function for safe ingestion
|
||||
def add_medical_memory(content, user_id, metadata=None):
|
||||
"""Add memory with automatic filtering."""
|
||||
result = client.add(
|
||||
[{"role": "user", "content": content}],
|
||||
user_id=user_id,
|
||||
metadata=metadata or {}
|
||||
)
|
||||
|
||||
if result['results']:
|
||||
print(f"✓ Stored: {result['results'][0]['memory']}")
|
||||
else:
|
||||
print(f"✗ Filtered: {content}")
|
||||
|
||||
return result
|
||||
|
||||
# Test cases
|
||||
print("Testing ingestion pipeline:\\n")
|
||||
|
||||
test_cases = [
|
||||
"I think I might be allergic to penicillin",
|
||||
"Dr. Johnson confirmed penicillin allergy on Jan 15th with hives reaction",
|
||||
"Patient SSN is 123-45-6789",
|
||||
"Currently taking Lisinopril 10mg daily for hypertension",
|
||||
"Feeling tired lately",
|
||||
"Dr. Martinez diagnosed Type 2 diabetes on February 3rd, 2025"
|
||||
]
|
||||
|
||||
for content in test_cases:
|
||||
add_medical_memory(content, user_id="patient_123")
|
||||
print()
|
||||
|
||||
```
|
||||
|
||||
**Output:**
|
||||
|
||||
```
|
||||
Testing ingestion pipeline:
|
||||
|
||||
✗ Filtered: I think I might be allergic to penicillin
|
||||
|
||||
✓ Stored: Patient has confirmed penicillin allergy diagnosed by Dr. Johnson on January 15th with hives reaction
|
||||
|
||||
✗ Filtered: Patient SSN is 123-45-6789
|
||||
|
||||
✓ Stored: Patient is currently taking Lisinopril 10mg daily for hypertension
|
||||
|
||||
✗ Filtered: Feeling tired lately
|
||||
|
||||
✓ Stored: Patient diagnosed with Type 2 diabetes by Dr. Martinez on February 3rd, 2025
|
||||
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Per-Call Instructions
|
||||
|
||||
You can override project-level instructions for specific conversations:
|
||||
|
||||
First define custom instructions
|
||||
|
||||
```python
|
||||
custom_instructions="""Emergency intake mode:Store ALL symptoms and observations immediately.
|
||||
Flag for later review and verification."""
|
||||
|
||||
```
|
||||
|
||||
```python
|
||||
# Emergency intake - store everything temporarily
|
||||
emergency_messages = [
|
||||
{"role": "user", "content": "Patient arrived with chest pain and shortness of breath"}
|
||||
]
|
||||
|
||||
client.add(
|
||||
emergency_messages,
|
||||
user_id="patient_456",
|
||||
custom_instructions=custom_instructions,
|
||||
metadata={"type": "emergency", "review_required": True}
|
||||
)
|
||||
|
||||
```
|
||||
|
||||
This is useful for:
|
||||
|
||||
- Different conversation types (emergency vs routine)
|
||||
- Channel-specific rules (phone vs in-person)
|
||||
- Temporary data collection that needs review
|
||||
|
||||
---
|
||||
|
||||
## What You Built
|
||||
|
||||
You now have a medical assistant with production-grade memory controls:
|
||||
|
||||
- **Custom instructions** - Filter speculation and enforce confirmed facts only
|
||||
- **Confidence thresholds** - Gate extractions below 0.7 confidence score
|
||||
- **Memory updates** - Modify stored information without creating duplicates
|
||||
- **Per-call instructions** - Apply temporary rules for specific conversations
|
||||
- **PII filtering** - Block sensitive data (SSNs, insurance numbers) automatically
|
||||
|
||||
These controls prevent retrieval failures and ensure your AI assistant works with reliable, verified information.
|
||||
|
||||
---
|
||||
|
||||
## Summary
|
||||
|
||||
Start with conservative filters (only store confirmed facts) and iterate based on your application's needs. Combine custom instructions with confidence thresholds for the most reliable memory ingestion pipeline.
|
||||
|
||||
<Card title="Build a Mem0 Companion" icon="users" href="/cookbooks/essentials/building-ai-companion">
|
||||
Learn core memory patterns including temporary vs permanent data handling.
|
||||
</Card>
|
||||
|
||||
<Snippet file="star-on-github.mdx" />
|
||||
@@ -332,10 +332,10 @@ You learned how to:
|
||||
href="/platform/features/v2-memory-filters"
|
||||
/>
|
||||
<Card
|
||||
title="Custom Instructions"
|
||||
description="Pair scoped storage with instructions that steer what Mem0 extracts and stores."
|
||||
title="Control Memory Ingestion"
|
||||
description="Pair scoped storage with rules that block low-quality facts."
|
||||
icon="shield-check"
|
||||
href="/platform/features/custom-instructions"
|
||||
href="/cookbooks/essentials/controlling-memory-ingestion"
|
||||
/>
|
||||
</CardGroup>
|
||||
|
||||
|
||||
@@ -287,8 +287,8 @@ Use **`get_all()`** for bulk retrieval, **`search()`** for specific questions, a
|
||||
<Card title="Build a Mem0 Companion" icon="users" href="/cookbooks/essentials/building-ai-companion">
|
||||
Learn core memory patterns including temporary vs permanent data handling.
|
||||
</Card>
|
||||
<Card title="Custom Instructions" icon="filter" href="/platform/features/custom-instructions">
|
||||
Steer what Mem0 extracts so only verified insights make it into your export pipeline.
|
||||
<Card title="Control Memory Ingestion" icon="filter" href="/cookbooks/essentials/controlling-memory-ingestion">
|
||||
Ensure only verified insights make it into your export pipeline.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
|
||||
@@ -249,8 +249,8 @@ Categories make retrieval faster and compliance easier. Define 3-5 clear categor
|
||||
Instead of searching through everything, agents jump directly to the information type they need: billing issues, account details, or support tickets.
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Custom Instructions" icon="filter" href="/platform/features/custom-instructions">
|
||||
Keep categories meaningful by steering what Mem0 extracts before it lands in storage.
|
||||
<Card title="Control Memory Ingestion" icon="filter" href="/cookbooks/essentials/controlling-memory-ingestion">
|
||||
Keep categories meaningful by filtering noise before it lands in storage.
|
||||
</Card>
|
||||
<Card title="Export Tagged Memories" icon="download" href="/cookbooks/essentials/exporting-memories">
|
||||
Use categories to drive audits, migrations, and compliance reports.
|
||||
|
||||
@@ -293,8 +293,8 @@ run().catch(console.error);
|
||||
<Card title="Agents SDK Tool with Mem0" icon="robot" href="/cookbooks/integrations/agents-sdk-tool">
|
||||
Extend the OpenAI Agents SDK with Mem0 integration capabilities.
|
||||
</Card>
|
||||
<Card title="Custom Instructions" icon="filter" href="/platform/features/custom-instructions">
|
||||
Steer what memories get stored during tool calls.
|
||||
<Card title="Control Memory Ingestion" icon="filter" href="/cookbooks/essentials/controlling-memory-ingestion">
|
||||
Fine-tune what memories get stored during tool calls.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
|
||||
@@ -360,8 +360,8 @@ Mem0 enables a seamless, intelligent content-writing workflow, perfect for conte
|
||||
---
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Custom Instructions" icon="filter" href="/platform/features/custom-instructions">
|
||||
Steer what Mem0 extracts and stores to maintain a consistent writing style.
|
||||
<Card title="Control Memory Ingestion" icon="filter" href="/cookbooks/essentials/controlling-memory-ingestion">
|
||||
Filter and curate content examples to maintain consistent writing style.
|
||||
</Card>
|
||||
<Card title="Email Automation with Mem0" icon="envelope" href="/cookbooks/operations/email-automation">
|
||||
Automate email drafting with memory-powered context and tone matching.
|
||||
|
||||
@@ -35,7 +35,7 @@ Every cookbook opens with a **Works with** badge naming the SDK surface it uses.
|
||||
| [Memory-Powered Support Agent](/cookbooks/operations/support-inbox) | Operations | OSS only |
|
||||
</Tab>
|
||||
<Tab title="Hosted Platform">
|
||||
Twenty cookbooks run on the hosted Platform, using `MemoryClient` or the Mem0 MCP server with a `MEM0_API_KEY`.
|
||||
Twenty-one cookbooks run on the hosted Platform, using `MemoryClient` or the Mem0 MCP server with a `MEM0_API_KEY`.
|
||||
|
||||
| Cookbook | Category | Works with |
|
||||
| --- | --- | --- |
|
||||
@@ -43,6 +43,7 @@ Every cookbook opens with a **Works with** badge naming the SDK surface it uses.
|
||||
| [Research Assistant for YouTube](/cookbooks/companions/youtube-research) | Companions | Platform only |
|
||||
| [Voice-First AI Companion](/cookbooks/companions/voice-companion-openai) | Companions | Platform only |
|
||||
| [Build a Companion with Mem0](/cookbooks/essentials/building-ai-companion) | Essentials | OSS and Platform |
|
||||
| [Control Memory Ingestion](/cookbooks/essentials/controlling-memory-ingestion) | Essentials | Platform only |
|
||||
| [Export Stored Memories](/cookbooks/essentials/exporting-memories) | Essentials | Platform only |
|
||||
| [Partition Memories by Entity](/cookbooks/essentials/entity-partitioning-playbook) | Essentials | Platform only |
|
||||
| [Tag and Organize Memories](/cookbooks/essentials/tagging-and-organizing-memories) | Essentials | Platform only |
|
||||
@@ -96,18 +97,11 @@ The most popular cookbooks to get going fast:
|
||||
Balance personalization with consistent behavior across users, agents, and apps.
|
||||
</Card>
|
||||
<Card
|
||||
title="Tag and Organize Memories"
|
||||
icon="tags"
|
||||
href="/cookbooks/essentials/tagging-and-organizing-memories"
|
||||
title="Control Memory Ingestion"
|
||||
icon="filter"
|
||||
href="/cookbooks/essentials/controlling-memory-ingestion"
|
||||
>
|
||||
Use categories to keep retrieval fast and audits simple.
|
||||
</Card>
|
||||
<Card
|
||||
title="Export Memories"
|
||||
icon="download"
|
||||
href="/cookbooks/essentials/exporting-memories"
|
||||
>
|
||||
Back up, migrate, and audit stored memory data.
|
||||
Filter speculation and low-confidence data.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
|
||||
@@ -1,69 +1,68 @@
|
||||
---
|
||||
title: Memory Types
|
||||
description: "What memory_type actually does in Mem0: procedural memory is implemented, semantic and episodic are not."
|
||||
description: "See how Mem0 layers conversation, session, and user memories to keep agents contextual."
|
||||
icon: "tag"
|
||||
iconType: "solid"
|
||||
---
|
||||
|
||||
# Memory Types
|
||||
# How Mem0 Organizes Memory
|
||||
|
||||
Mem0's Python SDK exposes a `memory_type` parameter on `add()`. The underlying `MemoryType` enum defines three values, but only one of them is wired up. This page states plainly which is which so you don't build against a type that doesn't exist yet.
|
||||
Mem0 separates memory into layers so agents remember the right detail at the right time. Think of it like a notebook: a sticky note for the current task, a daily journal for the session, and an archive for everything a user has shared.
|
||||
|
||||
## Status
|
||||
## Key terms
|
||||
|
||||
| Type | Enum value | Status | Notes |
|
||||
| --- | --- | --- | --- |
|
||||
| Procedural memory | `procedural_memory` | **Implemented** | Python OSS only (`Memory`/`AsyncMemory`). Pass `memory_type="procedural_memory"` and `agent_id` to `add()`. Not available on the Platform `MemoryClient`, and not available in the TypeScript SDK (OSS or Platform). |
|
||||
| Semantic memory | `semantic_memory` | **Not implemented** | Defined in the `MemoryType` enum but never read anywhere else in the codebase. Passing it to `add()` raises a validation error. There is no evidence in this repo of a roadmap date for this. |
|
||||
| Episodic memory | `episodic_memory` | **Not implemented** | Same as above: defined, never wired into the extraction pipeline, rejected by validation, no documented roadmap. |
|
||||
- **Conversation memory**: In-flight messages inside a single turn (what was just said).
|
||||
- **Session memory**: Short-lived facts that apply for the current task or channel.
|
||||
- **User memory**: Long-lived knowledge tied to a person, account, or workspace.
|
||||
- **Organizational memory**: Shared context available to multiple agents or teams.
|
||||
|
||||
<Warning>
|
||||
Only `procedural_memory` is a real, working value. Calling `memory.add(messages, memory_type="semantic_memory")` (or `episodic_memory`) is rejected and tells you to pass `procedural_memory` instead. Sync `Memory.add()` raises `Mem0ValidationError`; `AsyncMemory.add()` raises a plain `ValueError`.
|
||||
</Warning>
|
||||
|
||||
## Procedural memory
|
||||
|
||||
Procedural memory stores step-by-step task knowledge (how an agent performs a workflow) rather than facts about a user. It requires `agent_id`:
|
||||
|
||||
```python
|
||||
from mem0 import Memory
|
||||
|
||||
memory = Memory()
|
||||
|
||||
memory.add(
|
||||
[
|
||||
{"role": "user", "content": "Book a flight from SFO to NYC"},
|
||||
{"role": "assistant", "content": "1. Search flights. 2. Filter by price. 3. Confirm booking."},
|
||||
],
|
||||
agent_id="travel-agent",
|
||||
memory_type="procedural_memory",
|
||||
)
|
||||
```mermaid
|
||||
graph LR
|
||||
A[Conversation turn] --> B[Session memory]
|
||||
B --> C[User memory]
|
||||
C --> D[Org memory]
|
||||
C --> E[Mem0 retrieval layer]
|
||||
```
|
||||
|
||||
Omit `memory_type` entirely and Mem0 stores the messages as an ordinary memory: there is no semantic/episodic pathway for it to fall into. Any other explicit value is rejected by validation rather than quietly falling back to an ordinary memory.
|
||||
## Short-term vs long-term memory
|
||||
|
||||
## How every other memory is scoped
|
||||
Short-term memory keeps the current conversation coherent. It includes:
|
||||
|
||||
Outside of the `procedural_memory` special case, Mem0 does not sort memories into named types. Every memory is scoped by the identifiers you pass in, and the same identifiers are used to retrieve it later:
|
||||
- **Conversation history**: recent turns in order so the agent remembers what was just said.
|
||||
- **Working memory**: temporary state such as tool outputs or intermediate calculations.
|
||||
- **Attention context**: the immediate focus of the assistant, similar to what a person holds in mind mid-sentence.
|
||||
|
||||
- **`user_id`**: ties a memory to a specific person or account.
|
||||
- **`agent_id`**: ties a memory to a specific agent or assistant persona.
|
||||
- **`run_id`**: ties a memory to a specific session, task, or conversation thread.
|
||||
- **`app_id`** (Platform only): ties a memory to a specific application or tenant, in addition to the three above. See <Link href="/platform/features/entity-scoped-memory">Entity-Scoped Memory</Link>.
|
||||
Long-term memory preserves knowledge across sessions. It captures:
|
||||
|
||||
At least one identifier is required on `add()`. Passing more than one narrows the scope further (for example, `user_id` + `run_id` together).
|
||||
- **Factual memory**: user preferences, account details, and domain facts.
|
||||
- **Episodic memory**: summaries of past interactions or completed tasks.
|
||||
- **Semantic memory**: relationships between concepts so agents can reason about them later.
|
||||
|
||||
Mem0 maps these classic categories onto its layered storage so you can decide what should fade quickly versus what should last for months.
|
||||
|
||||
## How does it work?
|
||||
|
||||
Mem0 stores each layer separately and merges them when you query:
|
||||
|
||||
1. **Capture**: Messages enter the conversation layer while the turn is active.
|
||||
2. **Promote**: Relevant details persist to session or user memory based on your `user_id`, `run_id`, and metadata.
|
||||
3. **Retrieve**: The search pipeline pulls from all layers, ranking user memories first, then session notes, then raw history.
|
||||
|
||||
```python
|
||||
import os
|
||||
|
||||
from mem0 import Memory
|
||||
|
||||
memory = Memory()
|
||||
|
||||
# Sticky note: conversation memory
|
||||
memory.add(
|
||||
"I'm Alex and I prefer boutique hotels.",
|
||||
["I'm Alex and I prefer boutique hotels."],
|
||||
user_id="alex",
|
||||
run_id="trip-planning-2025",
|
||||
)
|
||||
|
||||
# Later in the session, pull long-term + session context
|
||||
results = memory.search(
|
||||
"Any hotel preferences?",
|
||||
filters={"user_id": "alex", "run_id": "trip-planning-2025"},
|
||||
@@ -71,48 +70,52 @@ results = memory.search(
|
||||
```
|
||||
|
||||
<Tip>
|
||||
Use `run_id` when you want a set of memories to stay tied to one session or task; use `user_id` alone for anything that should persist across every session for that person.
|
||||
Use `run_id` when you want short-term context to expire automatically; rely on `user_id` for lasting personalization.
|
||||
</Tip>
|
||||
|
||||
## How memories are extracted and updated
|
||||
## When should you use each layer?
|
||||
|
||||
When `infer=True` (the default) on `add()`, Mem0 runs a single pipeline rather than routing through separate type-specific paths:
|
||||
- **Conversation memory**: Tool calls or chain-of-thought that only matter within the current turn.
|
||||
- **Session memory**: Multi-step tasks (onboarding flows, debugging sessions) that should reset once complete.
|
||||
- **User memory**: Personal preferences, account state, or compliance details that must persist across interactions.
|
||||
- **Organizational memory**: Shared FAQs, product catalogs, or policies that every agent should recall.
|
||||
|
||||
1. **Context gathering**: pulls the most recent messages already stored for the same `user_id`/`agent_id`/`run_id` scope.
|
||||
2. **Existing memory retrieval**: embeds the new messages and runs a vector search against memories already in that same scope, to find candidates that might need to change.
|
||||
3. **Extraction**: a single LLM call compares the new messages against the retrieved candidates and decides, per fact, whether to `ADD`, `UPDATE`, `DELETE`, or leave a memory alone.
|
||||
## How it compares
|
||||
|
||||
Alongside this, both OSS and Platform extract named entities (people, places, organizations) from memory text and use shared entities between memories to boost related results at search time. On Platform, that entity graph is also queryable directly; see <Link href="/platform/features/graph-memory">Graph Memory</Link>. In OSS, entities only affect ranking, there is no separate graph to query.
|
||||
| Layer | Lifetime | Short or long term | Best for | Trade-offs |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| Conversation | Single response | Short-term | Tool execution detail | Lost after the turn finishes |
|
||||
| Session | Minutes to hours | Short-term | Multi-step flows | Clear it manually when done |
|
||||
| User | Weeks to forever | Long-term | Personalization | Requires consent/governance |
|
||||
| Org | Configured globally | Long-term | Shared knowledge | Needs owner to keep current |
|
||||
|
||||
<Warning>
|
||||
Avoid storing secrets or unredacted PII in memories: they are retrievable by design. Encrypt or hash sensitive values before calling `add()`.
|
||||
Avoid storing secrets or unredacted PII in user or org memories: Mem0 is retrievable by design. Encrypt or hash sensitive values first.
|
||||
</Warning>
|
||||
|
||||
## Put it into practice
|
||||
|
||||
- Use the <Link href="/core-concepts/memory-operations/add">Add Memory</Link> guide to persist user preferences.
|
||||
- Follow <Link href="/platform/advanced-memory-operations">Advanced Memory Operations</Link> to tune metadata and retrieval.
|
||||
|
||||
## See it live
|
||||
|
||||
- <Link href="/cookbooks/companions/ai-tutor">AI Tutor with Mem0</Link> shows session vs user memories in action.
|
||||
- <Link href="/cookbooks/operations/support-inbox">Support Inbox with Mem0</Link> demonstrates shared org memory.
|
||||
|
||||
{/* DEBUG: verify CTA targets */}
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card
|
||||
title="Explore Memory Operations"
|
||||
description="Dive into the add/search/update/delete operations next."
|
||||
description="Dive into the add/search/update/delete concepts next."
|
||||
icon="circle-check"
|
||||
href="/core-concepts/memory-operations/add"
|
||||
/>
|
||||
<Card
|
||||
title="Advanced Memory Operations"
|
||||
description="Tune metadata, filters, and retrieval on Platform."
|
||||
icon="sliders"
|
||||
href="/platform/advanced-memory-operations"
|
||||
/>
|
||||
<Card
|
||||
title="AI Tutor Cookbook"
|
||||
description="See user_id-scoped memory used in a real tutoring agent."
|
||||
title="See a Cookbook"
|
||||
description="Apply layered memories inside a customer support agent."
|
||||
icon="rocket"
|
||||
href="/cookbooks/companions/ai-tutor"
|
||||
/>
|
||||
<Card
|
||||
title="Support Inbox Cookbook"
|
||||
description="See user_id-scoped memory used in a support workflow."
|
||||
icon="inbox"
|
||||
href="/cookbooks/operations/support-inbox"
|
||||
/>
|
||||
</CardGroup>
|
||||
|
||||
+24
-285
@@ -325,9 +325,7 @@
|
||||
"integrations/google-ai-adk",
|
||||
"integrations/mastra",
|
||||
"integrations/vercel-ai-sdk",
|
||||
"integrations/vercel",
|
||||
"integrations/chatdev",
|
||||
"integrations/strands"
|
||||
"integrations/chatdev"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -370,7 +368,6 @@
|
||||
"icon": "terminal",
|
||||
"pages": [
|
||||
"integrations/claude-code",
|
||||
"integrations/claude-ai",
|
||||
"integrations/cursor",
|
||||
"integrations/codex",
|
||||
"integrations/opencode",
|
||||
@@ -383,8 +380,7 @@
|
||||
"pages": [
|
||||
"integrations/openclaw",
|
||||
"integrations/hermes",
|
||||
"integrations/pi-agent",
|
||||
"integrations/deepseek-plugin"
|
||||
"integrations/pi-agent"
|
||||
]
|
||||
}
|
||||
]
|
||||
@@ -405,6 +401,7 @@
|
||||
"pages": [
|
||||
"cookbooks/essentials/building-ai-companion",
|
||||
"cookbooks/essentials/entity-partitioning-playbook",
|
||||
"cookbooks/essentials/controlling-memory-ingestion",
|
||||
"cookbooks/essentials/tagging-and-organizing-memories",
|
||||
"cookbooks/essentials/exporting-memories"
|
||||
]
|
||||
@@ -539,20 +536,6 @@
|
||||
"api-reference/project/delete-project"
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "Dream",
|
||||
"icon": "sparkles",
|
||||
"pages": [
|
||||
"api-reference/dream/get-dream-config",
|
||||
"api-reference/dream/update-dream-config",
|
||||
"api-reference/dream/get-dream-stats",
|
||||
"api-reference/dream/get-dream-activity",
|
||||
"api-reference/dream/get-dream-runs",
|
||||
"api-reference/dream/get-dream-run-memories",
|
||||
"api-reference/dream/get-dream-memory-sources",
|
||||
"api-reference/dream/dream-preview"
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "Webhooks",
|
||||
"icon": "webhook",
|
||||
@@ -969,20 +952,24 @@
|
||||
"destination": "/platform/features/memory-export"
|
||||
},
|
||||
{
|
||||
"source": "/v0x/components/:slug*",
|
||||
"destination": "/components/:slug*"
|
||||
"source": "/v0x/components/:a/:b/:c",
|
||||
"destination": "/components/:a/:b/:c"
|
||||
},
|
||||
{
|
||||
"source": "/v0x/core-concepts/:slug*",
|
||||
"destination": "/core-concepts/:slug*"
|
||||
"source": "/v0x/components/:a/:b",
|
||||
"destination": "/components/:a/:b"
|
||||
},
|
||||
{
|
||||
"source": "/v0x/integrations/:slug*",
|
||||
"destination": "/integrations/:slug*"
|
||||
"source": "/v0x/core-concepts/:a/:b",
|
||||
"destination": "/core-concepts/:a/:b"
|
||||
},
|
||||
{
|
||||
"source": "/v0x/open-source/:slug*",
|
||||
"destination": "/open-source/:slug*"
|
||||
"source": "/v0x/integrations/:slug",
|
||||
"destination": "/integrations/:slug"
|
||||
},
|
||||
{
|
||||
"source": "/v0x/open-source/:slug",
|
||||
"destination": "/open-source/:slug"
|
||||
},
|
||||
{
|
||||
"source": "/v0x/introduction",
|
||||
@@ -1057,8 +1044,8 @@
|
||||
"destination": "/platform/features/graph-memory"
|
||||
},
|
||||
{
|
||||
"source": "/features/:slug*",
|
||||
"destination": "/platform/features/:slug*"
|
||||
"source": "/features/:slug",
|
||||
"destination": "/platform/features/:slug"
|
||||
},
|
||||
{
|
||||
"source": "/platform/features/online-memory",
|
||||
@@ -1185,7 +1172,7 @@
|
||||
"destination": "/open-source/overview"
|
||||
},
|
||||
{
|
||||
"source": "/self-hosting/:slug*",
|
||||
"source": "/self-hosting/:slug",
|
||||
"destination": "/open-source/overview"
|
||||
},
|
||||
{
|
||||
@@ -1193,7 +1180,7 @@
|
||||
"destination": "/open-source/overview"
|
||||
},
|
||||
{
|
||||
"source": "/self-hosted/:slug*",
|
||||
"source": "/self-hosted/:slug",
|
||||
"destination": "/open-source/overview"
|
||||
},
|
||||
{
|
||||
@@ -1201,7 +1188,7 @@
|
||||
"destination": "/platform/quickstart"
|
||||
},
|
||||
{
|
||||
"source": "/getting-started/:slug*",
|
||||
"source": "/getting-started/:slug",
|
||||
"destination": "/platform/quickstart"
|
||||
},
|
||||
{
|
||||
@@ -1209,7 +1196,7 @@
|
||||
"destination": "/open-source/setup"
|
||||
},
|
||||
{
|
||||
"source": "/deployment/:slug*",
|
||||
"source": "/deployment/:slug",
|
||||
"destination": "/open-source/setup"
|
||||
},
|
||||
{
|
||||
@@ -1221,12 +1208,12 @@
|
||||
"destination": "/open-source/overview"
|
||||
},
|
||||
{
|
||||
"source": "/oss/:slug*",
|
||||
"source": "/oss/:slug",
|
||||
"destination": "/open-source/overview"
|
||||
},
|
||||
{
|
||||
"source": "/concepts/:slug*",
|
||||
"destination": "/core-concepts/:slug*"
|
||||
"source": "/concepts/:slug",
|
||||
"destination": "/core-concepts/:slug"
|
||||
},
|
||||
{
|
||||
"source": "/pricing",
|
||||
@@ -1263,254 +1250,6 @@
|
||||
{
|
||||
"source": "/integrations/keywords",
|
||||
"destination": "/integrations/respan"
|
||||
},
|
||||
{
|
||||
"source": "/cookbooks/essentials/controlling-memory-ingestion",
|
||||
"destination": "/platform/features/custom-instructions"
|
||||
},
|
||||
{
|
||||
"source": "/open-source/quickstart",
|
||||
"destination": "/open-source/overview"
|
||||
},
|
||||
{
|
||||
"source": "/open-source/graph-memory/overview",
|
||||
"destination": "/open-source/overview"
|
||||
},
|
||||
{
|
||||
"source": "/what-is-mem0",
|
||||
"destination": "https://mem0.ai/"
|
||||
},
|
||||
{
|
||||
"source": "/platform-vs-oss",
|
||||
"destination": "/platform/platform-vs-oss"
|
||||
},
|
||||
{
|
||||
"source": "/components/overview",
|
||||
"destination": "/components/llms/overview"
|
||||
},
|
||||
{
|
||||
"source": "/v0x/core-concepts/memory-operations/add",
|
||||
"destination": "/core-concepts/memory-operations/add"
|
||||
},
|
||||
{
|
||||
"source": "/v0x/integrations/llama-index",
|
||||
"destination": "/integrations/llama-index"
|
||||
},
|
||||
{
|
||||
"source": "/api-reference/event/get-event",
|
||||
"destination": "/api-reference/events/get-event"
|
||||
},
|
||||
{
|
||||
"source": "/api-reference/webhook/get-webhooks",
|
||||
"destination": "/api-reference/webhook/get-webhook"
|
||||
},
|
||||
{
|
||||
"source": "/api-reference/organization/update-organization-members",
|
||||
"destination": "/api-reference/organization/update-org-member"
|
||||
},
|
||||
{
|
||||
"source": "/api-reference/organization/delete-project",
|
||||
"destination": "/api-reference/project/delete-project"
|
||||
},
|
||||
{
|
||||
"source": "/api-reference/entities/get-entities",
|
||||
"destination": "/api-reference/entities/get-users"
|
||||
},
|
||||
{
|
||||
"source": "/api-reference/event/get-events",
|
||||
"destination": "/api-reference/events/get-events"
|
||||
},
|
||||
{
|
||||
"source": "/api-reference/entities/delete-users",
|
||||
"destination": "/api-reference/entities/delete-user"
|
||||
},
|
||||
{
|
||||
"source": "/api-reference/organization/update-organization-member",
|
||||
"destination": "/api-reference/organization/update-org-member"
|
||||
},
|
||||
{
|
||||
"source": "/api-reference/organization/get-organizations",
|
||||
"destination": "/api-reference/organization/get-orgs"
|
||||
},
|
||||
{
|
||||
"source": "/api-reference/entities/get-user",
|
||||
"destination": "/api-reference/entities/get-users"
|
||||
},
|
||||
{
|
||||
"source": "/api-reference/export/create-memory-export",
|
||||
"destination": "/api-reference/memory/create-memory-export"
|
||||
},
|
||||
{
|
||||
"source": "/integrations/mcp",
|
||||
"destination": "/platform/mem0-mcp"
|
||||
},
|
||||
{
|
||||
"source": "/platform/api-reference",
|
||||
"destination": "/api-reference"
|
||||
},
|
||||
{
|
||||
"source": "/api-reference/memory/add-memory",
|
||||
"destination": "/api-reference/memory/add-memories"
|
||||
},
|
||||
{
|
||||
"source": "/api-reference/overview",
|
||||
"destination": "/api-reference"
|
||||
},
|
||||
{
|
||||
"source": "/platform/reference/python-sdk",
|
||||
"destination": "/open-source/python-quickstart"
|
||||
},
|
||||
{
|
||||
"source": "/platform/python",
|
||||
"destination": "/open-source/python-quickstart"
|
||||
},
|
||||
{
|
||||
"source": "/platform/features/memory",
|
||||
"destination": "/platform/features/memory-decay"
|
||||
},
|
||||
{
|
||||
"source": "/platform/api-reference/python",
|
||||
"destination": "/open-source/python-quickstart"
|
||||
},
|
||||
{
|
||||
"source": "/api-reference/webhooks",
|
||||
"destination": "/api-reference/webhook/create-webhook"
|
||||
},
|
||||
{
|
||||
"source": "/platform/python-quickstart",
|
||||
"destination": "/open-source/python-quickstart"
|
||||
},
|
||||
{
|
||||
"source": "/api-reference/organization/delete-org-project",
|
||||
"destination": "/api-reference/organization/delete-org"
|
||||
},
|
||||
{
|
||||
"source": "/platform/features/scoping",
|
||||
"destination": "/platform/features/entity-scoped-memory"
|
||||
},
|
||||
{
|
||||
"source": "/platform/quickstart/python",
|
||||
"destination": "/open-source/python-quickstart"
|
||||
},
|
||||
{
|
||||
"source": "/api-reference/memory/history",
|
||||
"destination": "/api-reference/memory/history-memory"
|
||||
},
|
||||
{
|
||||
"source": "/api-reference/entities/get-user-memories",
|
||||
"destination": "/api-reference/entities/get-users"
|
||||
},
|
||||
{
|
||||
"source": "/platform/api-reference/webhooks/create",
|
||||
"destination": "/api-reference/webhook/create-webhook"
|
||||
},
|
||||
{
|
||||
"source": "/platform/python/quickstart",
|
||||
"destination": "/open-source/python-quickstart"
|
||||
},
|
||||
{
|
||||
"source": "/api-reference/memory/batch-update-memory",
|
||||
"destination": "/api-reference/memory/batch-update"
|
||||
},
|
||||
{
|
||||
"source": "/api-reference/memories/add",
|
||||
"destination": "/api-reference/memory/add-memories"
|
||||
},
|
||||
{
|
||||
"source": "/python-quickstart",
|
||||
"destination": "/open-source/python-quickstart"
|
||||
},
|
||||
{
|
||||
"source": "/api-reference/webhook/list-webhooks",
|
||||
"destination": "/api-reference/webhook/get-webhook"
|
||||
},
|
||||
{
|
||||
"source": "/platform/reference/memory/delete-memory",
|
||||
"destination": "/api-reference/memory/delete-memory"
|
||||
},
|
||||
{
|
||||
"source": "/platform/webhooks",
|
||||
"destination": "/platform/features/webhooks"
|
||||
},
|
||||
{
|
||||
"source": "/platform/api-reference/memories/add",
|
||||
"destination": "/api-reference/memory/add-memories"
|
||||
},
|
||||
{
|
||||
"source": "/api-reference/organization/organizations",
|
||||
"destination": "/api-reference/organization/create-org"
|
||||
},
|
||||
{
|
||||
"source": "/sdk/python/quickstart",
|
||||
"destination": "/open-source/python-quickstart"
|
||||
},
|
||||
{
|
||||
"source": "/platform/export",
|
||||
"destination": "/platform/features/memory-export"
|
||||
},
|
||||
{
|
||||
"source": "/open-source/python-memory",
|
||||
"destination": "/open-source/python-quickstart"
|
||||
},
|
||||
{
|
||||
"source": "/platform/reference",
|
||||
"destination": "/api-reference"
|
||||
},
|
||||
{
|
||||
"source": "/api-reference/memory/get-all-memories",
|
||||
"destination": "/api-reference/memory/get-memories"
|
||||
},
|
||||
{
|
||||
"source": "/api-reference/user/delete-users",
|
||||
"destination": "/api-reference/entities/delete-user"
|
||||
},
|
||||
{
|
||||
"source": "/api-reference/memories/search-memories",
|
||||
"destination": "/api-reference/memory/search-memories"
|
||||
},
|
||||
{
|
||||
"source": "/api-reference/organization/update-members",
|
||||
"destination": "/api-reference/project/update-project-member"
|
||||
},
|
||||
{
|
||||
"source": "/platform/api-reference/memory/batch-update",
|
||||
"destination": "/api-reference/memory/batch-update"
|
||||
},
|
||||
{
|
||||
"source": "/api-reference/memory/search",
|
||||
"destination": "/api-reference/memory/search-memories"
|
||||
},
|
||||
{
|
||||
"source": "/api-reference/batch/update-memories",
|
||||
"destination": "/api-reference/memory/batch-update"
|
||||
},
|
||||
{
|
||||
"source": "/api-reference/organization/update-organization-member-role",
|
||||
"destination": "/api-reference/project/update-project-member"
|
||||
},
|
||||
{
|
||||
"source": "/api-reference/webhooks/delete",
|
||||
"destination": "/api-reference/webhook/delete-webhook"
|
||||
},
|
||||
{
|
||||
"source": "/api-reference/memory/delete-all-memories",
|
||||
"destination": "/api-reference/memory/delete-memories"
|
||||
},
|
||||
{
|
||||
"source": "/platform/reference/overview",
|
||||
"destination": "/api-reference"
|
||||
},
|
||||
{
|
||||
"source": "/api-reference/mem0/add-memories",
|
||||
"destination": "/api-reference/memory/add-memories"
|
||||
},
|
||||
{
|
||||
"source": "/platform/mcp/overview",
|
||||
"destination": "/platform/mem0-mcp"
|
||||
},
|
||||
{
|
||||
"source": "/openmemory/mcp/introduction",
|
||||
"destination": "https://mem0.ai/blog/introducing-openmemory-mcp"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -1,88 +0,0 @@
|
||||
<svg viewBox="0 0 600 420" role="img" aria-labelledby="venn-title venn-desc" xmlns="http://www.w3.org/2000/svg">
|
||||
<title id="venn-title">Mem0 Memory Scoping</title>
|
||||
<desc id="venn-desc">Venn diagram showing how a single add call produces shared project memory and personal memory, with search returning the union of both.</desc>
|
||||
|
||||
<rect width="600" height="420" fill="#f5f5f5"/>
|
||||
|
||||
<text x="300" y="36" fill="#2d3142" font-size="20" font-weight="400"
|
||||
font-family="Georgia, serif" text-anchor="middle">Memory Scoping</text>
|
||||
<text x="300" y="56" fill="#7a8399" font-size="9"
|
||||
font-family="monospace" text-anchor="middle" letter-spacing="0.08em">ONE ADD CALL · TWO MEMORY BUCKETS</text>
|
||||
|
||||
<circle cx="228" cy="212" r="132" fill="rgba(45,49,66,0.05)" stroke="#4f5d75" stroke-width="1"/>
|
||||
<circle cx="372" cy="212" r="132" fill="rgba(79,93,117,0.05)" stroke="#7a8399" stroke-width="1"/>
|
||||
|
||||
<defs>
|
||||
<clipPath id="clip-left">
|
||||
<circle cx="228" cy="212" r="132"/>
|
||||
</clipPath>
|
||||
</defs>
|
||||
<circle cx="372" cy="212" r="132" fill="rgba(235,108,54,0.10)" clip-path="url(#clip-left)"/>
|
||||
|
||||
<text x="124" y="84" fill="#2d3142" font-size="13" font-weight="600"
|
||||
font-family="sans-serif" text-anchor="middle">Shared Project</text>
|
||||
<text x="124" y="100" fill="#4f5d75" font-size="9"
|
||||
font-family="monospace" text-anchor="middle">agent_id = repo slug</text>
|
||||
|
||||
<text x="476" y="84" fill="#2d3142" font-size="13" font-weight="600"
|
||||
font-family="sans-serif" text-anchor="middle">Personal</text>
|
||||
<text x="476" y="100" fill="#4f5d75" font-size="9"
|
||||
font-family="monospace" text-anchor="middle">user_id = you</text>
|
||||
|
||||
<text x="168" y="176" fill="#2d3142" font-size="11" font-weight="500"
|
||||
font-family="sans-serif" text-anchor="middle">Conventions</text>
|
||||
<text x="168" y="196" fill="#2d3142" font-size="11" font-weight="500"
|
||||
font-family="sans-serif" text-anchor="middle">Commands</text>
|
||||
<text x="168" y="216" fill="#2d3142" font-size="11" font-weight="500"
|
||||
font-family="sans-serif" text-anchor="middle">Decisions</text>
|
||||
<text x="168" y="236" fill="#2d3142" font-size="11" font-weight="500"
|
||||
font-family="sans-serif" text-anchor="middle">Fixes</text>
|
||||
|
||||
<text x="168" y="264" fill="#7a8399" font-size="9"
|
||||
font-family="monospace" text-anchor="middle">no user_id</text>
|
||||
<text x="168" y="276" fill="#7a8399" font-size="9"
|
||||
font-family="monospace" text-anchor="middle">visible to team</text>
|
||||
|
||||
<text x="432" y="192" fill="#2d3142" font-size="11" font-weight="500"
|
||||
font-family="sans-serif" text-anchor="middle">Preferences</text>
|
||||
<text x="432" y="212" fill="#2d3142" font-size="11" font-weight="500"
|
||||
font-family="sans-serif" text-anchor="middle">Habits</text>
|
||||
<text x="432" y="232" fill="#2d3142" font-size="11" font-weight="500"
|
||||
font-family="sans-serif" text-anchor="middle">Style</text>
|
||||
|
||||
<text x="432" y="260" fill="#7a8399" font-size="9"
|
||||
font-family="monospace" text-anchor="middle">no agent_id</text>
|
||||
<text x="432" y="272" fill="#7a8399" font-size="9"
|
||||
font-family="monospace" text-anchor="middle">private to you</text>
|
||||
|
||||
<text x="300" y="196" fill="#eb6c36" font-size="12" font-weight="600"
|
||||
font-family="sans-serif" text-anchor="middle">Search</text>
|
||||
<text x="300" y="212" fill="#eb6c36" font-size="12" font-weight="600"
|
||||
font-family="sans-serif" text-anchor="middle">Result</text>
|
||||
<text x="300" y="232" fill="#7a8399" font-size="9"
|
||||
font-family="monospace" text-anchor="middle">OR [agent_id+app_id,</text>
|
||||
<text x="300" y="244" fill="#7a8399" font-size="9"
|
||||
font-family="monospace" text-anchor="middle">user_id+app_id]</text>
|
||||
|
||||
<line x1="40" y1="360" x2="560" y2="360" stroke="rgba(45,49,66,0.12)" stroke-width="0.8"/>
|
||||
|
||||
<text x="80" y="380" fill="#4f5d75" font-size="9" font-weight="600"
|
||||
font-family="monospace" text-anchor="middle" letter-spacing="0.06em">agent_id</text>
|
||||
<text x="80" y="396" fill="#7a8399" font-size="8"
|
||||
font-family="monospace" text-anchor="middle">repo slug</text>
|
||||
|
||||
<text x="220" y="380" fill="#4f5d75" font-size="9" font-weight="600"
|
||||
font-family="monospace" text-anchor="middle" letter-spacing="0.06em">app_id</text>
|
||||
<text x="220" y="396" fill="#7a8399" font-size="8"
|
||||
font-family="monospace" text-anchor="middle">repo</text>
|
||||
|
||||
<text x="380" y="380" fill="#4f5d75" font-size="9" font-weight="600"
|
||||
font-family="monospace" text-anchor="middle" letter-spacing="0.06em">user_id</text>
|
||||
<text x="380" y="396" fill="#7a8399" font-size="8"
|
||||
font-family="monospace" text-anchor="middle">you</text>
|
||||
|
||||
<text x="520" y="380" fill="#4f5d75" font-size="9" font-weight="600"
|
||||
font-family="monospace" text-anchor="middle" letter-spacing="0.06em">run_id</text>
|
||||
<text x="520" y="396" fill="#7a8399" font-size="8"
|
||||
font-family="monospace" text-anchor="middle">session</text>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 4.8 KiB |
@@ -1,133 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 860 784" width="860" role="img" aria-labelledby="seq-title seq-desc">
|
||||
<title id="seq-title">Mem0 Plugin Architecture</title>
|
||||
<desc id="seq-desc">Sequence diagram showing the full Claude Code plugin: lifecycle hooks, first-prompt memory recall, capture events, background extraction via detached worker, and on-demand skills and search tool.</desc>
|
||||
|
||||
<defs>
|
||||
<marker id="arrow" markerWidth="8" markerHeight="6" refX="7" refY="3" orient="auto">
|
||||
<polygon points="0 0, 8 3, 0 6" fill="#4f5d75"/>
|
||||
</marker>
|
||||
<marker id="arrow-accent" markerWidth="8" markerHeight="6" refX="7" refY="3" orient="auto">
|
||||
<polygon points="0 0, 8 3, 0 6" fill="#eb6c36"/>
|
||||
</marker>
|
||||
<marker id="arrow-link" markerWidth="8" markerHeight="6" refX="7" refY="3" orient="auto">
|
||||
<polygon points="0 0, 8 3, 0 6" fill="#2e5aa8"/>
|
||||
</marker>
|
||||
<marker id="arrow-open" markerWidth="8" markerHeight="6" refX="7" refY="3" orient="auto">
|
||||
<polyline points="0 0, 8 3, 0 6" fill="none" stroke="#4f5d75" stroke-width="1.2"/>
|
||||
</marker>
|
||||
<style>
|
||||
text { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; }
|
||||
</style>
|
||||
</defs>
|
||||
|
||||
<rect width="100%" height="100%" fill="#f5f5f5"/>
|
||||
|
||||
<!-- LIFELINES -->
|
||||
<line x1="108" y1="76" x2="108" y2="720" stroke="rgba(45,49,66,0.12)" stroke-width="1" stroke-dasharray="3,3"/>
|
||||
<line x1="320" y1="76" x2="320" y2="720" stroke="rgba(45,49,66,0.12)" stroke-width="1" stroke-dasharray="3,3"/>
|
||||
<line x1="540" y1="76" x2="540" y2="720" stroke="rgba(45,49,66,0.12)" stroke-width="1" stroke-dasharray="3,3"/>
|
||||
<line x1="740" y1="76" x2="740" y2="720" stroke="rgba(45,49,66,0.12)" stroke-width="1" stroke-dasharray="3,3"/>
|
||||
|
||||
<!-- PHASE 1: SESSION INIT -->
|
||||
<text x="32" y="100" fill="#7a8399" font-size="9" font-style="italic">Session init</text>
|
||||
|
||||
<rect x="164" y="104" width="84" height="12" rx="2" fill="#f5f5f5"/>
|
||||
<text x="206" y="114" fill="#7a8399" font-size="8" font-family="monospace" text-anchor="middle" letter-spacing="0.06em">SESSION-START</text>
|
||||
<line x1="112" y1="128" x2="316" y2="128" stroke="#4f5d75" stroke-width="1" marker-end="url(#arrow)"/>
|
||||
|
||||
<!-- PHASE 2: CAPTURE & RECALL -->
|
||||
<text x="32" y="160" fill="#7a8399" font-size="9" font-style="italic">Capture and recall</text>
|
||||
|
||||
<rect x="162" y="168" width="88" height="12" rx="2" fill="#f5f5f5"/>
|
||||
<text x="206" y="178" fill="#7a8399" font-size="8" font-family="monospace" text-anchor="middle" letter-spacing="0.06em">USER-PROMPT</text>
|
||||
<line x1="112" y1="192" x2="316" y2="192" stroke="#4f5d75" stroke-width="1" marker-end="url(#arrow)"/>
|
||||
|
||||
<!-- OPT fragment -->
|
||||
<rect x="260" y="212" width="520" height="148" rx="4" fill="rgba(235,108,54,0.08)" stroke="#eb6c36" stroke-width="1" stroke-opacity="0.4"/>
|
||||
<rect x="260" y="212" width="36" height="16" rx="2" fill="#f5f5f5" stroke="#eb6c36" stroke-width="1" stroke-opacity="0.4"/>
|
||||
<text x="278" y="224" fill="#eb6c36" font-size="8" font-family="monospace" text-anchor="middle" letter-spacing="0.12em">OPT</text>
|
||||
<text x="308" y="236" fill="#7a8399" font-size="8" font-family="monospace" letter-spacing="0.04em">[first prompt]</text>
|
||||
|
||||
<rect x="472" y="248" width="108" height="12" rx="2" fill="#f5f5f5"/>
|
||||
<text x="526" y="258" fill="#2e5aa8" font-size="8" font-family="monospace" text-anchor="middle" letter-spacing="0.06em">SEARCH MEMORIES</text>
|
||||
<line x1="324" y1="272" x2="736" y2="272" stroke="#2e5aa8" stroke-width="1" marker-end="url(#arrow-link)"/>
|
||||
|
||||
<rect x="480" y="280" width="80" height="12" rx="2" fill="#f5f5f5"/>
|
||||
<text x="520" y="290" fill="#7a8399" font-size="8" font-family="monospace" text-anchor="middle" letter-spacing="0.06em">≤5 MEMORIES</text>
|
||||
<line x1="736" y1="304" x2="324" y2="304" stroke="#4f5d75" stroke-width="1" stroke-dasharray="5,4" marker-end="url(#arrow)"/>
|
||||
|
||||
<rect x="148" y="316" width="120" height="12" rx="2" fill="#f5f5f5"/>
|
||||
<text x="208" y="326" fill="#eb6c36" font-size="8" font-family="monospace" text-anchor="middle" letter-spacing="0.06em">CONTEXT INJECTED</text>
|
||||
<line x1="316" y1="348" x2="112" y2="348" stroke="#eb6c36" stroke-width="1" stroke-dasharray="5,4" marker-end="url(#arrow-accent)"/>
|
||||
|
||||
<rect x="176" y="380" width="60" height="12" rx="2" fill="#f5f5f5"/>
|
||||
<text x="206" y="390" fill="#7a8399" font-size="8" font-family="monospace" text-anchor="middle" letter-spacing="0.06em">POST-TOOL</text>
|
||||
<line x1="112" y1="404" x2="316" y2="404" stroke="#4f5d75" stroke-width="1" marker-end="url(#arrow)"/>
|
||||
|
||||
<rect x="156" y="416" width="100" height="12" rx="2" fill="#f5f5f5"/>
|
||||
<text x="206" y="426" fill="#7a8399" font-size="8" font-family="monospace" text-anchor="middle" letter-spacing="0.06em">SIDEKICK-START</text>
|
||||
<line x1="112" y1="440" x2="316" y2="440" stroke="#4f5d75" stroke-width="1" marker-end="url(#arrow)"/>
|
||||
|
||||
<rect x="184" y="452" width="48" height="12" rx="2" fill="#f5f5f5"/>
|
||||
<text x="208" y="462" fill="#7a8399" font-size="8" font-family="monospace" text-anchor="middle" letter-spacing="0.06em">STOP</text>
|
||||
<line x1="112" y1="476" x2="316" y2="476" stroke="#4f5d75" stroke-width="1" marker-end="url(#arrow)"/>
|
||||
|
||||
<text x="332" y="466" fill="#7a8399" font-size="8" font-style="italic">repeats each exchange</text>
|
||||
|
||||
<!-- PHASE 3: BACKGROUND EXTRACTION -->
|
||||
<text x="32" y="508" fill="#7a8399" font-size="9" font-style="italic">Background extraction</text>
|
||||
|
||||
<rect x="380" y="516" width="96" height="12" rx="2" fill="#f5f5f5"/>
|
||||
<text x="428" y="526" fill="#7a8399" font-size="8" font-family="monospace" text-anchor="middle" letter-spacing="0.06em">HAND_OFF_FLUSH</text>
|
||||
<line x1="324" y1="540" x2="536" y2="540" stroke="#4f5d75" stroke-width="1" stroke-dasharray="5,4" marker-end="url(#arrow-open)"/>
|
||||
<text x="332" y="556" fill="#7a8399" font-size="8" font-style="italic">periodic, idle (5 min), or session-end</text>
|
||||
|
||||
<rect x="620" y="568" width="28" height="12" rx="2" fill="#f5f5f5"/>
|
||||
<text x="634" y="578" fill="#2e5aa8" font-size="8" font-family="monospace" text-anchor="middle" letter-spacing="0.06em">ADD</text>
|
||||
<line x1="544" y1="592" x2="736" y2="592" stroke="#2e5aa8" stroke-width="1" marker-end="url(#arrow-link)"/>
|
||||
<rect x="564" y="596" width="160" height="12" rx="2" fill="#f5f5f5"/>
|
||||
<text x="644" y="606" fill="#7a8399" font-size="8" font-family="monospace" text-anchor="middle">agent_id + user_id + app_id + run_id</text>
|
||||
|
||||
<rect x="616" y="616" width="48" height="12" rx="2" fill="#f5f5f5"/>
|
||||
<text x="640" y="626" fill="#7a8399" font-size="8" font-family="monospace" text-anchor="middle" letter-spacing="0.06em">STORED</text>
|
||||
<line x1="736" y1="640" x2="544" y2="640" stroke="#4f5d75" stroke-width="1" stroke-dasharray="5,4" marker-end="url(#arrow)"/>
|
||||
|
||||
<!-- PHASE 4: ON-DEMAND -->
|
||||
<text x="32" y="672" fill="#7a8399" font-size="9" font-style="italic">On-demand (skills + tool)</text>
|
||||
|
||||
<rect x="136" y="680" width="144" height="12" rx="2" fill="#f5f5f5"/>
|
||||
<text x="208" y="690" fill="#7a8399" font-size="8" font-family="monospace" text-anchor="middle" letter-spacing="0.04em">/MEM0:SEARCH, FORGET</text>
|
||||
<line x1="112" y1="704" x2="316" y2="704" stroke="#4f5d75" stroke-width="1" marker-end="url(#arrow)"/>
|
||||
<rect x="468" y="680" width="108" height="12" rx="2" fill="#f5f5f5"/>
|
||||
<text x="522" y="690" fill="#2e5aa8" font-size="8" font-family="monospace" text-anchor="middle" letter-spacing="0.04em">SEARCH / DELETE</text>
|
||||
<line x1="324" y1="704" x2="736" y2="704" stroke="#2e5aa8" stroke-width="1" marker-end="url(#arrow-link)"/>
|
||||
|
||||
<!-- ACTIVATION BARS -->
|
||||
<rect x="316" y="124" width="8" height="232" fill="rgba(45,49,66,0.06)" stroke="#4f5d75" stroke-width="0.8"/>
|
||||
<rect x="316" y="400" width="8" height="84" fill="rgba(45,49,66,0.06)" stroke="#4f5d75" stroke-width="0.8"/>
|
||||
<rect x="316" y="536" width="8" height="12" fill="rgba(45,49,66,0.06)" stroke="#4f5d75" stroke-width="0.8"/>
|
||||
<rect x="316" y="700" width="8" height="12" fill="rgba(45,49,66,0.06)" stroke="#4f5d75" stroke-width="0.8"/>
|
||||
<rect x="736" y="268" width="8" height="40" fill="rgba(45,49,66,0.06)" stroke="#4f5d75" stroke-width="0.8"/>
|
||||
<rect x="536" y="536" width="8" height="108" fill="rgba(45,49,66,0.06)" stroke="#4f5d75" stroke-width="0.8"/>
|
||||
<rect x="736" y="588" width="8" height="56" fill="rgba(45,49,66,0.06)" stroke="#4f5d75" stroke-width="0.8"/>
|
||||
<rect x="736" y="700" width="8" height="12" fill="rgba(45,49,66,0.06)" stroke="#4f5d75" stroke-width="0.8"/>
|
||||
|
||||
<!-- ACTOR BOXES -->
|
||||
<rect x="48" y="36" width="120" height="40" rx="6" fill="#ececec" stroke="#2d3142" stroke-width="1"/>
|
||||
<text x="108" y="60" fill="#2d3142" font-size="12" font-weight="600" text-anchor="middle">Claude Code</text>
|
||||
|
||||
<rect x="268" y="36" width="104" height="40" rx="6" fill="rgba(235,108,54,0.08)" stroke="#eb6c36" stroke-width="1"/>
|
||||
<rect x="276" y="42" width="44" height="12" rx="2" fill="transparent" stroke="#eb6c36" stroke-width="0.8" stroke-opacity="0.5"/>
|
||||
<text x="298" y="51" fill="#eb6c36" font-size="7" font-family="monospace" text-anchor="middle" letter-spacing="0.08em">PLUGIN</text>
|
||||
<text x="320" y="64" fill="#2d3142" font-size="12" font-weight="600" text-anchor="middle">Mem0</text>
|
||||
|
||||
<rect x="476" y="36" width="128" height="40" rx="6" fill="rgba(45,49,66,0.05)" stroke="#4f5d75" stroke-width="1"/>
|
||||
<rect x="484" y="42" width="52" height="12" rx="2" fill="transparent" stroke="#4f5d75" stroke-width="0.8" stroke-opacity="0.5"/>
|
||||
<text x="510" y="51" fill="#7a8399" font-size="7" font-family="monospace" text-anchor="middle" letter-spacing="0.08em">DETACHED</text>
|
||||
<text x="540" y="64" fill="#2d3142" font-size="12" font-weight="600" text-anchor="middle">flush_worker</text>
|
||||
|
||||
<rect x="680" y="36" width="120" height="40" rx="6" fill="rgba(45,49,66,0.03)" stroke="rgba(45,49,66,0.3)" stroke-width="1"/>
|
||||
<rect x="688" y="42" width="28" height="12" rx="2" fill="transparent" stroke="rgba(45,49,66,0.3)" stroke-width="0.8"/>
|
||||
<text x="702" y="51" fill="#7a8399" font-size="7" font-family="monospace" text-anchor="middle" letter-spacing="0.08em">API</text>
|
||||
<text x="740" y="64" fill="#2d3142" font-size="12" font-weight="600" text-anchor="middle">Mem0 Platform</text>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 10 KiB |
@@ -1,85 +0,0 @@
|
||||
---
|
||||
title: Claude.ai
|
||||
description: "Add persistent memory to Claude.ai with the Mem0 remote MCP server: custom connector setup and native-memory troubleshooting."
|
||||
---
|
||||
|
||||
Add persistent memory to [**Claude.ai**](https://claude.ai) (the hosted web app, not Claude Code) using Mem0's remote MCP server. Claude.ai connects to MCP servers over the internet as **custom connectors**; there is no local plugin or hook system here, since chats run in Anthropic's cloud, not on your machine.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
1. A Mem0 Platform account: <a href="https://app.mem0.ai?utm_source=oss&utm_medium=integration-claude-ai" rel="nofollow">sign up at app.mem0.ai</a>
|
||||
2. A Claude.ai account on any plan (free, Pro, Max, Team, or Enterprise)
|
||||
|
||||
You don't need an API key up front: the connector uses browser-based sign-in the first time Claude calls a Mem0 tool (see [Signing in](#signing-in)).
|
||||
|
||||
## Installation
|
||||
|
||||
### Individual accounts (Pro, Max, or free)
|
||||
|
||||
1. Go to **Customize > Connectors**
|
||||
2. Click **+**, then **Add custom connector**
|
||||
3. Enter the server URL: `https://mcp.mem0.ai/mcp/`
|
||||
4. Click **Add**
|
||||
|
||||
<Note>
|
||||
Free-tier accounts are limited to one custom connector. Pro, Max, Team, and Enterprise accounts can add multiple.
|
||||
</Note>
|
||||
|
||||
### Team and Enterprise organizations
|
||||
|
||||
An organization owner registers the connector once for everyone:
|
||||
|
||||
1. Go to **Organization Settings > Connectors**
|
||||
2. Click **Add**, hover **Custom**, then select **Web**
|
||||
3. Enter the server URL: `https://mcp.mem0.ai/mcp/`
|
||||
4. Click **Add**
|
||||
|
||||
Members then connect individually: **Customize > Connectors**, find **mem0**, and click **Connect**.
|
||||
|
||||
### Enabling in a chat
|
||||
|
||||
Connectors are opt-in per conversation. Click the **+** button next to the chat prompt, open **Connectors**, and toggle **mem0** on before you start.
|
||||
|
||||
## Signing in
|
||||
|
||||
The first time Claude calls a Mem0 tool, your browser opens a sign-in prompt to authorize the connector against your Mem0 account. Approve it once; Claude.ai stores and refreshes the resulting token for you. There's no API key to paste into the connector UI itself.
|
||||
|
||||
## What's Included
|
||||
|
||||
| Component | Included |
|
||||
|-----------|:--------:|
|
||||
| MCP Server (9 memory tools) | Yes |
|
||||
| Lifecycle Hooks | No (Claude.ai has no local hook system) |
|
||||
| Mem0 SDK Skill | No (Claude.ai has no local skills directory) |
|
||||
|
||||
## Available MCP Tools
|
||||
|
||||
| Tool | Description |
|
||||
|------|-------------|
|
||||
| `add_memory` | Save text or conversation history for a user/agent |
|
||||
| `search_memories` | Semantic search across memories with filters |
|
||||
| `get_memories` | List memories with filters and pagination |
|
||||
| `get_memory` | Retrieve a specific memory by ID |
|
||||
| `update_memory` | Overwrite a memory's text by ID |
|
||||
| `delete_memory` | Delete a single memory by ID |
|
||||
| `delete_all_memories` | Bulk delete all memories in scope |
|
||||
| `delete_entities` | Delete a user/agent/app/run entity and its memories |
|
||||
| `list_entities` | List users/agents/apps/runs stored in Mem0 |
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
- **Claude never calls the mem0 tools, even though the connector shows as connected**: Claude.ai ships its own native memory (Settings > Capabilities > Memory, on by default), which synthesizes a running summary from your chat history automatically. When both are active, Claude's system prompt tends to favor its built-in memory and rarely reaches for a third-party memory tool on its own. Ask explicitly ("search my mem0 memories for...", "save this to mem0") to force the tool call, or pause Claude's native memory (Settings > Capabilities > Memory > Pause) if you want Mem0 to be the primary memory store for that account.
|
||||
- **"Connection failed" or the connector won't add**: Confirm the URL is exactly `https://mcp.mem0.ai/mcp/`. Custom connectors reach your MCP server from Anthropic's cloud, not your device, so a localhost URL will never work here.
|
||||
- **No tools appearing after adding the connector**: Make sure you toggled **mem0** on for the current conversation under the **+ > Connectors** menu; adding a connector doesn't enable it in every chat automatically.
|
||||
- **Can't add a second connector**: Free-tier accounts are capped at one custom connector; upgrade to Pro/Max/Team/Enterprise for more.
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Mem0 MCP Setup" icon="puzzle-piece" href="/platform/mem0-mcp">
|
||||
Detailed MCP configuration for all clients
|
||||
</Card>
|
||||
<Card title="Claude Code Integration" icon="/images/provider-icons/anthropic.svg" href="/integrations/claude-code">
|
||||
Add Mem0 memory to Claude Code workflows
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
<Snippet file="star-on-github.mdx" />
|
||||
+147
-124
@@ -1,166 +1,189 @@
|
||||
---
|
||||
title: Claude Code
|
||||
description: "Persistent cross-session memory for Claude Code. Install once, memories are captured automatically and recalled in every future session."
|
||||
description: "Add persistent memory to Claude Code and Claude Cowork with the Mem0 plugin: MCP server, lifecycle hooks, and SDK skill."
|
||||
---
|
||||
|
||||
Claude Code forgets everything between sessions. This plugin fixes that. Install it, work normally, and Claude remembers what happened across sessions.
|
||||
Add persistent memory to [**Claude Code**](https://docs.anthropic.com/en/docs/claude-code) (CLI) and **Claude Cowork** (desktop app) with the Mem0 plugin. Your agent forgets everything between sessions. 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 before every response.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
1. A Mem0 Platform account and API key (starts with `m0-`):
|
||||
- [Sign up at app.mem0.ai](https://app.mem0.ai?utm_source=oss&utm_medium=integration-claude-code)
|
||||
- [Get your API key](https://app.mem0.ai/dashboard/api-keys?utm_source=oss&utm_medium=integration-claude-code)
|
||||
Before setting up Mem0 with Claude Code, ensure you have:
|
||||
|
||||
2. A Claude Code version that supports plugin agents, worktree isolation for agents, and the `SubagentStart`, `SubagentStop`, and `PostToolUseFailure` hook events.
|
||||
1. A Mem0 Platform account and API key:
|
||||
- <a href="https://app.mem0.ai?utm_source=oss&utm_medium=integration-claude-code" rel="nofollow">Sign up at app.mem0.ai</a>
|
||||
- <a href="https://app.mem0.ai/dashboard/api-keys?utm_source=oss&utm_medium=integration-claude-code" rel="nofollow">Get your API key</a> (starts with `m0-`)
|
||||
|
||||
3. Python 3.10+ and Git on your machine.
|
||||
2. Claude Code CLI or Claude Cowork desktop app installed
|
||||
|
||||
## Quick start
|
||||
3. Your API key added to your shell profile (persists across sessions):
|
||||
|
||||
```bash
|
||||
export MEM0_API_KEY='your-mem0-api-key'
|
||||
claude plugin marketplace add mem0ai/mem0
|
||||
claude plugin install mem0@mem0-plugins --scope user --config api_key="$MEM0_API_KEY"
|
||||
unset MEM0_API_KEY
|
||||
<CodeGroup>
|
||||
```bash zsh
|
||||
echo 'export MEM0_API_KEY="m0-your-api-key"' >> ~/.zshrc
|
||||
source ~/.zshrc
|
||||
```
|
||||
|
||||
Restart Claude Code (or run `/reload-plugins`), open a Git repository, and work normally. That's it.
|
||||
```bash bash
|
||||
echo 'export MEM0_API_KEY="m0-your-api-key"' >> ~/.bashrc
|
||||
source ~/.bashrc
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
### Managing the plugin
|
||||
Confirm it's set:
|
||||
|
||||
```bash
|
||||
echo $MEM0_API_KEY
|
||||
# Should print: m0-your-api-key
|
||||
```
|
||||
|
||||
## Installation
|
||||
|
||||
### Option A: Plugin Marketplace (Recommended)
|
||||
|
||||
Install the full plugin including MCP server, lifecycle hooks, and SDK skill.
|
||||
|
||||
1. Add the Mem0 marketplace:
|
||||
|
||||
```bash
|
||||
claude plugin marketplace add mem0ai/mem0
|
||||
```
|
||||
|
||||
2. Install the plugin:
|
||||
|
||||
```bash
|
||||
claude plugin install mem0@mem0-plugins
|
||||
```
|
||||
|
||||
**Claude Cowork desktop app:** Open the Cowork tab, click **Customize** in the sidebar, click **Browse plugins**, and install Mem0.
|
||||
|
||||
### Option B: MCP Only
|
||||
|
||||
Add the Mem0 MCP server directly with a single command:
|
||||
|
||||
```bash
|
||||
npx mcp-add \
|
||||
--name mem0-mcp \
|
||||
--type http \
|
||||
--url "https://mcp.mem0.ai/mcp/" \
|
||||
--clients "claude code"
|
||||
```
|
||||
|
||||
This gives you the MCP tools but not the lifecycle hooks or SDK skill.
|
||||
|
||||
### Option C: Manual MCP Configuration
|
||||
|
||||
Add to your Claude Code MCP config (`.mcp.json`):
|
||||
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"mem0": {
|
||||
"type": "http",
|
||||
"url": "https://mcp.mem0.ai/mcp/",
|
||||
"headers": {
|
||||
"Authorization": "Token ${MEM0_API_KEY}"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Managing the Plugin
|
||||
|
||||
```bash
|
||||
claude plugin update mem0@mem0-plugins # update the plugin to the latest version (restart to apply)
|
||||
claude plugin marketplace update mem0-plugins # refresh the marketplace catalog
|
||||
claude plugin update mem0@mem0-plugins --scope user # update the plugin (restart to apply)
|
||||
claude plugin uninstall mem0@mem0-plugins # uninstall the plugin (keeps the marketplace)
|
||||
claude plugin marketplace remove mem0-plugins # unregister the marketplace entirely
|
||||
```
|
||||
|
||||
## What you can do
|
||||
<Info icon="check">
|
||||
Start a new session and ask: *"List my mem0 entities"* or *"Search my memories for hello"*. If the `mem0` tools appear and respond, you're all set.
|
||||
</Info>
|
||||
|
||||
### Automatic memory
|
||||
## Post-Installation: Run `/mem0:onboard`
|
||||
|
||||
Once installed, memory works without any action from you:
|
||||
After installing the plugin, start a new Claude Code session and run:
|
||||
|
||||
- **Capture** happens in the background as you work. Hooks save user messages, Claude's answers, changed files, and test/build results locally. Nothing calls a model or slows your session.
|
||||
- **Recall** happens automatically before Claude's first response in a new session. The plugin searches your memories with your prompt and injects up to five relevant ones.
|
||||
```
|
||||
/mem0:onboard
|
||||
```
|
||||
|
||||
### Commands
|
||||
This runs the setup wizard which:
|
||||
1. Verifies your API key and MCP connection
|
||||
2. Detects and imports project files (`CLAUDE.md`, `AGENTS.md`, `.cursorrules`)
|
||||
3. Installs coding-optimized memory categories
|
||||
4. Shows your identity (user ID, project scope, branch)
|
||||
|
||||
| Command | What it does |
|
||||
| --- | --- |
|
||||
| `/mem0:search` | Search memories from earlier sessions. Supports `--top-k <n>`, `--category <name>`, and `--scope <repo\|dir\|mine>`. |
|
||||
| `/mem0:status` | Check if memory is working: config, capture state, pending flushes, API key validity. |
|
||||
| `/mem0:forget` | Delete your memories for this repo (shared project memory stays unless you pass `--include-project-memory`). |
|
||||
| `/mem0:pause` | Pause memory capture. |
|
||||
| `/mem0:resume` | Resume capture after a pause. |
|
||||
| `/mem0:remember` | Tell Claude to capture something specific in its reply. |
|
||||
The onboarding is idempotent and safe to re-run anytime. It auto-triggers on first session in a new project, but you can always invoke it manually.
|
||||
|
||||
Categories for `--category`: `project_knowledge`, `decisions_and_constraints`, `workflows`, `problems_and_fixes`, `results`. Without it, all categories are searched.
|
||||
## What's Included
|
||||
|
||||
### Search tool
|
||||
| Component | Plugin Install | MCP Only |
|
||||
|-----------|:--------------:|:--------:|
|
||||
| MCP Server (9 memory tools) | Yes | Yes |
|
||||
| Lifecycle Hooks | Yes | No |
|
||||
| Mem0 SDK Skill | Yes | No |
|
||||
|
||||
After the automatic first-prompt search, Claude can also call `search_memories` with a specific question, and you can run `/mem0:search` yourself. Explicit searches return up to 3 results by default (configurable to 20). All results are capped at 4,000 characters.
|
||||
## Available MCP Tools
|
||||
|
||||
### Sidekick agent
|
||||
Once installed, the following tools are available in every Claude Code session:
|
||||
|
||||
`mem0:sidekick` is a Sonnet coding agent that runs in a separate Git worktree. Use it to offload investigation, implementation, testing, or review without burning main-session context.
|
||||
| Tool | Description |
|
||||
|------|-------------|
|
||||
| `add_memory` | Save text or conversation history for a user/agent |
|
||||
| `search_memories` | Semantic search across memories with filters |
|
||||
| `get_memories` | List memories with filters and pagination |
|
||||
| `get_memory` | Retrieve a specific memory by ID |
|
||||
| `update_memory` | Overwrite a memory's text by ID |
|
||||
| `delete_memory` | Delete a single memory by ID |
|
||||
| `delete_all_memories` | Bulk delete all memories in scope |
|
||||
| `delete_entities` | Delete a user/agent/app/run entity and its memories |
|
||||
| `list_entities` | List users/agents/apps/runs stored in Mem0 |
|
||||
|
||||
## Lifecycle Hooks
|
||||
|
||||
When installed via the plugin marketplace, Mem0 hooks into Claude Code's lifecycle to automatically manage memory:
|
||||
|
||||
| Hook | Event | What it does |
|
||||
|------|-------|-------------|
|
||||
| **Setup** | `Setup` | Installs the mem0 SDK and dependencies (runs on init and maintenance) |
|
||||
| **Session start** | `SessionStart` | Loads prior memories and displays status banner |
|
||||
| **User prompt** | `UserPromptSubmit` | Searches relevant memories before each message; skips short prompts |
|
||||
| **Pre-tool (3 handlers)** | `PreToolUse` | Blocks MEMORY.md writes; enforces `user_id`/`app_id` on mem0 tool calls; scans files being read for relevant memory context |
|
||||
| **Post-tool** | `PostToolUse` | Tracks stats, scans bash errors for related memories |
|
||||
| **Stop** | `Stop` | Stores a session summary at the end of every assistant turn (not just at session end) |
|
||||
| **Pre-compact** | `PreCompact` | Stores a summary before the context is compacted |
|
||||
|
||||
What you type is stored as yours. What Claude produces (session summaries and compaction summaries) is stored as the assistant's, so its suggestions never become your stated preferences.
|
||||
|
||||
## Example Workflow
|
||||
|
||||
```text
|
||||
Ask Mem0's sidekick to investigate and implement this in its separate worktree.
|
||||
Review its result and send any corrections back to the same sidekick.
|
||||
```
|
||||
# Session 1: Working on a feature
|
||||
You: Let's refactor the auth module to use JWT tokens instead of sessions.
|
||||
|
||||
Changes stay in the sidekick's worktree until the main agent reviews and copies them over. By default the worktree branches from the repo's default branch. Set `worktree.baseRef` to `"head"` in your Claude settings to branch from the current commit instead. Uncommitted changes are not copied into the sidekick's worktree.
|
||||
# Claude searches memories, finds nothing relevant, proceeds with the work.
|
||||
# Mem0 stores what you said as yours:
|
||||
# - Your preference: "Prefers TypeScript, uses ESLint"
|
||||
# ...and what Claude did as the assistant's, in the session summary:
|
||||
# - Decision: "Migrated auth from sessions to JWT tokens"
|
||||
# - Files modified: auth/middleware.ts, auth/token.ts
|
||||
|
||||
## How it works
|
||||
# Session 2 (days later): Related work
|
||||
You: Add refresh token rotation to the auth system.
|
||||
|
||||
The plugin follows a simple cycle: capture during a session, extract memories in the background, recall in the next session.
|
||||
|
||||
<Frame>
|
||||
<img src="/images/plugin-sequence.svg" alt="Sequence diagram: session start triggers first-prompt search, hooks capture activity during the session, a background worker extracts memories after every five exchanges or on idle/exit, and the next session recalls them." />
|
||||
</Frame>
|
||||
|
||||
**Step by step:**
|
||||
|
||||
1. **Capture.** Hooks save the main agent's activity locally: user messages, Claude's answers, changed files, and short test/build results. Subagent (sidekick) output is excluded. No model calls, no blocking.
|
||||
|
||||
2. **Flush.** After every five completed exchanges, a detached background worker sends that batch to Mem0. Large exchanges flush sooner. Ending or compacting the session flushes anything remaining. If the session sits idle, an auto-flush runs after five minutes (configurable with `MEM0_CODE_IDLE_FLUSH_SECONDS`). The timer resets on each new exchange. The worker survives Claude Code exiting.
|
||||
|
||||
3. **Extract.** Each flush sends a single `add` call with `agent_id` (the project identity), `user_id` (you), `app_id` (the repository), and `run_id` (the session). Mem0 classifies each extracted memory as shared project knowledge or a personal preference.
|
||||
|
||||
4. **Recall.** On the next session's first prompt, the plugin searches automatically and supplies up to five relevant memories. No model is called to write the query.
|
||||
|
||||
## Memory scoping
|
||||
|
||||
Each `add` call carries separate extraction instructions for project facts and personal facts. Mem0 sorts each memory into one of two buckets:
|
||||
|
||||
- **Shared project memory** (keyed by `agent_id`, scoped by `app_id`): one namespace per repository. Stores conventions, decisions, constraints, commands that work, and commands that failed with what fixed them. Everyone on the repo reads and writes the same pool. Project memory never carries a `user_id`, so teammates' searches never mix in your preferences. Directory information is stored in metadata for directory-scoped searches.
|
||||
|
||||
- **Personal memory** (keyed by `user_id`, scoped by `app_id`): your preferred tools, style, habits, and anything you asked to be remembered. Scoped to the repository by `app_id`, private to you.
|
||||
|
||||
Credentials are redacted before anything leaves your machine.
|
||||
|
||||
<Frame>
|
||||
<img src="/images/memory-scoping-venn.svg" alt="Venn diagram showing one add call producing shared project memory (agent_id, visible to team) and personal memory (user_id, private to you). Search returns the union of both." />
|
||||
</Frame>
|
||||
|
||||
## Search scope
|
||||
|
||||
Every memory carries identifiers showing where it came from:
|
||||
|
||||
| Identifier | What it is | Example |
|
||||
| --- | --- | --- |
|
||||
| `user_id` | You (personal memory only) | Your Mem0 user ID |
|
||||
| `agent_id` | The project identity (shared memory only) | `acme-payments-api` |
|
||||
| `app_id` | The repository (scopes both lanes) | `acme-payments-api` |
|
||||
| `run_id` | The Claude Code session | The session ID |
|
||||
|
||||
A search returns the union of shared project memory and your personal preferences. The scope narrows the project part:
|
||||
|
||||
| Scope | What you get |
|
||||
| --- | --- |
|
||||
| `repo` (default) | All project memory across every subdirectory, plus your preferences |
|
||||
| `dir` | Project memory from the directory you're in (and its children), plus your preferences |
|
||||
| `mine` | Your personal preferences only |
|
||||
|
||||
The `dir` scope is hierarchical: a parent directory sees everything in its children, but a child never sees the parent's memories.
|
||||
|
||||
Pass `--run-id <session-id>` to see only what one specific session recorded. Set the default scope with the `search_scope` setting or `MEM0_CODE_SEARCH_SCOPE` env var.
|
||||
|
||||
## Settings
|
||||
|
||||
| Setting | Default | What it controls |
|
||||
| --- | --- | --- |
|
||||
| `api_key` | required | Mem0 Platform API key. |
|
||||
| `user_id` | local account name | User ID for memory storage. Resolved from: setting, `MEM0_CODE_USER_ID`, `MEM0_USER_ID`, `MEM0_RESOLVED_USER_ID`, `$USER`, `%USERNAME%`, then `default`. Set explicitly to share memories across machines. |
|
||||
| `top_k` | `3` | Max memories per explicit search (1 to 20). |
|
||||
| `max_context_chars` | `4000` | Max characters returned per search (1,000 to 10,000). |
|
||||
| `search_scope` | `repo` | Default scope: `repo`, `dir`, or `mine`. Also read from `MEM0_CODE_SEARCH_SCOPE`. |
|
||||
|
||||
## Upgrading from 0.2.x
|
||||
|
||||
Breaking update. Your memories carry over, most local config does not.
|
||||
|
||||
- **Memories carry over.** Same user and repository scoping, including `~/.mem0/project_map.json`.
|
||||
- **Env vars still work.** `MEM0_API_KEY`, `MEM0_USER_ID`, `MEM0_PROJECT_ID`.
|
||||
- **Commands replaced.** Old commands replaced by `/mem0:search`, `/mem0:status`, `/mem0:forget`, `/mem0:pause`, `/mem0:resume`, `/mem0:remember`.
|
||||
- **MCP server replaced.** Nine read/write tools replaced by the single read-only `search_memories` tool.
|
||||
- **Local config ignored.** `~/.mem0/settings.json` and per-project `mem0.md` files are no longer read.
|
||||
- **Old memories searchable, not by category.** Normal search finds pre-upgrade memories, but category filters do not.
|
||||
|
||||
```bash
|
||||
claude plugin marketplace update mem0-plugins
|
||||
claude plugin update mem0@mem0-plugins --scope user
|
||||
# Claude searches memories, retrieves the JWT migration context.
|
||||
# Knows the file structure, decisions made, and your stated preferences.
|
||||
# Continues seamlessly without re-explaining the codebase.
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
| Problem | Fix |
|
||||
| --- | --- |
|
||||
| Missing key | Reinstall with `--config api_key="$MEM0_API_KEY"` while the var is set. |
|
||||
| `401 Unauthorized` | API key is invalid or expired. Run `/mem0:status` to confirm. |
|
||||
| No memory after ending a session | Extraction runs in the background. Wait a moment, then search again. |
|
||||
| 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` |
|
||||
- **"Connection failed"**: Verify `MEM0_API_KEY` is set in your shell: `echo $MEM0_API_KEY`. If empty, add it to your shell profile (see Prerequisites)
|
||||
- **No tools appearing**: Restart your Claude Code session after installation
|
||||
- **Memories not being captured**: Ensure you installed via the plugin marketplace (Option A) for lifecycle hooks. MCP-only installs require manual memory operations
|
||||
- **"Mem0 Inactive" banner every session**: Your API key isn't persisting. Add `export MEM0_API_KEY="m0-..."` to your `~/.zshrc` (or `~/.bashrc`) and run `source ~/.zshrc`
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Mem0 MCP Setup" icon="puzzle-piece" href="/platform/mem0-mcp">
|
||||
|
||||
@@ -91,23 +91,12 @@ To update, run `codex plugin marketplace upgrade` to pull the latest from the Me
|
||||
After either option, start a new Codex task and ask: *"List my mem0 entities"* or *"Search my memories for hello"*. If the `mem0` tools appear and respond, you're all set.
|
||||
</Info>
|
||||
|
||||
## Codex Cloud
|
||||
|
||||
[Codex Cloud](https://developers.openai.com/codex/cloud/environments) tasks run setup scripts and the agent in separate phases with different variable scoping:
|
||||
|
||||
- **Environment Variables** persist for the full duration of the task, through both the setup script and the agent phase.
|
||||
- **Secrets** are only available to the setup script; they are wiped before the agent phase starts, so the agent itself cannot read them.
|
||||
|
||||
Because the `mem0` MCP server authenticates on every tool call the agent makes (not just during setup), set `MEM0_API_KEY` as an **Environment Variable** in your Codex Cloud environment configuration, not as a Secret. A Secret will let a setup script authenticate but the agent will lose access to `MEM0_API_KEY` once the task phase begins, breaking Mem0 MCP calls.
|
||||
|
||||
Lifecycle hooks that shell out to local scripts (Option A) are not applicable in Codex Cloud's ephemeral containers; use Option B (Direct MCP) with `MEM0_API_KEY` set as above.
|
||||
|
||||
## What's Included
|
||||
|
||||
| Component | Plugin Install | MCP Only |
|
||||
|-----------|:--------------:|:--------:|
|
||||
| MCP Server (9 memory tools) | Yes | Yes |
|
||||
| Lifecycle Hooks | Opt-in (see below) | No |
|
||||
| Lifecycle Hooks | Yes | No |
|
||||
| Mem0 SDK Skill | Yes | No |
|
||||
|
||||
## Available MCP Tools
|
||||
@@ -128,22 +117,7 @@ Once installed, the following tools are available in every Codex session:
|
||||
|
||||
## Lifecycle Hooks
|
||||
|
||||
Unlike Claude Code, Codex has no plugin-host mechanism for auto-wiring hooks from an installed plugin: it only reads hooks from `~/.codex/hooks.json` (or `<repo>/.codex/hooks.json`). Installing the plugin (Option A) does **not** turn hooks on by itself. To enable them, run the bundled installer once against your local clone:
|
||||
|
||||
```bash
|
||||
python3 <path-to-your-clone>/integrations/mem0-plugin/scripts/install_codex_hooks.py
|
||||
```
|
||||
|
||||
This merges Mem0's entries into `~/.codex/hooks.json` and is idempotent (safe to re-run after upgrading). It also requires the `codex_hooks` feature flag in `~/.codex/config.toml`:
|
||||
|
||||
```toml
|
||||
[features]
|
||||
codex_hooks = true
|
||||
```
|
||||
|
||||
The installer prints a reminder if the flag isn't set. Restart Codex after installing hooks or editing the config. To remove: `python3 .../install_codex_hooks.py --uninstall`.
|
||||
|
||||
Once enabled, Mem0 hooks into Codex's lifecycle to automatically manage memory:
|
||||
When installed via the plugin marketplace, Mem0 hooks into Codex's lifecycle to automatically manage memory:
|
||||
|
||||
| Hook | Event | What it does |
|
||||
|------|-------|-------------|
|
||||
@@ -181,7 +155,7 @@ You: Add WebSocket support for real-time notification delivery.
|
||||
- **"Connection failed"**: Verify `MEM0_API_KEY` is set: `echo $MEM0_API_KEY`
|
||||
- **No tools appearing**: Restart your Codex session after installation
|
||||
- **Duplicate `mem0` MCP / "tool collision" errors**: You combined Option A with Option B. Remove the `[mcp_servers.mem0]` block from `~/.codex/config.toml`; the plugin registers it automatically
|
||||
- **Hooks not firing**: Hooks are opt-in and are not installed by the marketplace install itself. Run `scripts/install_codex_hooks.py` (see [Lifecycle Hooks](#lifecycle-hooks)), confirm `codex_hooks = true` is set under `[features]` in `~/.codex/config.toml`, and restart Codex. MCP-only installs (Option B) never include hooks
|
||||
- **Hooks not firing**: Ensure the plugin is installed via the marketplace (Option A). MCP-only installs do not include hooks
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Mem0 MCP Setup" icon="puzzle-piece" href="/platform/mem0-mcp">
|
||||
|
||||
@@ -39,10 +39,6 @@ os.environ["SERPER_API_KEY"] = "your-serper-api-key"
|
||||
client = MemoryClient()
|
||||
```
|
||||
|
||||
<Note>
|
||||
Newer versions of CrewAI removed the `memory_config={"provider": "mem0"}` shortcut on `Crew(...)` that older guides referenced. CrewAI still offers a native Mem0 path through its `ExternalMemory` API, so that option remains open; check [CrewAI's memory documentation](https://docs.crewai.com/en/concepts/memory) for the shape your version expects. This guide wires Mem0 in explicitly through `MemoryClient` instead, which keeps retrieval under your control and stays valid as CrewAI's memory API changes.
|
||||
</Note>
|
||||
|
||||
## Store User Preferences
|
||||
|
||||
Set up initial conversation and preferences storage:
|
||||
@@ -73,21 +69,9 @@ messages = [
|
||||
store_user_preferences("crew_user_1", messages)
|
||||
```
|
||||
|
||||
## Retrieve Relevant Memories
|
||||
|
||||
Look up what Mem0 already knows about the user before planning a trip, so the crew's output reflects their actual preferences:
|
||||
|
||||
```python
|
||||
def get_user_context(user_id: str, query: str) -> str:
|
||||
"""Fetch relevant memories and format them for a task description"""
|
||||
relevant_memories = client.search(query, filters={"user_id": user_id})
|
||||
memories = [m["memory"] for m in relevant_memories.get("results", [])]
|
||||
return "\n".join(f"- {memory}" for memory in memories)
|
||||
```
|
||||
|
||||
## Create CrewAI Agent
|
||||
|
||||
Define an agent with search capabilities:
|
||||
Define an agent with memory capabilities:
|
||||
|
||||
```python
|
||||
def create_travel_agent():
|
||||
@@ -99,60 +83,61 @@ def create_travel_agent():
|
||||
goal="Plan personalized travel itineraries",
|
||||
backstory="""You are a seasoned travel planner, known for your meticulous attention to detail.""",
|
||||
allow_delegation=False,
|
||||
memory=True,
|
||||
tools=[search_tool],
|
||||
)
|
||||
```
|
||||
|
||||
## Define Tasks
|
||||
|
||||
Create a task that folds the retrieved memories into its description, so the agent plans around the user's known preferences:
|
||||
Create tasks for your agent:
|
||||
|
||||
```python
|
||||
def create_planning_task(agent, destination: str, user_context: str):
|
||||
"""Create a travel planning task personalized with the user's stored preferences"""
|
||||
def create_planning_task(agent, destination: str):
|
||||
"""Create a travel planning task"""
|
||||
return Task(
|
||||
description=f"""Find places to live, eat, and visit in {destination}.
|
||||
|
||||
Known preferences for this user:
|
||||
{user_context or "No stored preferences yet."}
|
||||
""",
|
||||
expected_output=f"A detailed list of places to live, eat, and visit in {destination}, tailored to the user's preferences.",
|
||||
description=f"""Find places to live, eat, and visit in {destination}.""",
|
||||
expected_output=f"A detailed list of places to live, eat, and visit in {destination}.",
|
||||
agent=agent,
|
||||
)
|
||||
```
|
||||
|
||||
## Set Up Crew
|
||||
|
||||
Configure the crew. Mem0 handles persistence outside of CrewAI, so the crew itself does not need `memory=True` or a `memory_config`:
|
||||
Configure the crew with memory integration:
|
||||
|
||||
```python
|
||||
def setup_crew(agents: list, tasks: list):
|
||||
"""Set up a crew; memory is managed through Mem0, not CrewAI's memory_config"""
|
||||
"""Set up a crew with Mem0 memory integration"""
|
||||
return Crew(
|
||||
agents=agents,
|
||||
tasks=tasks,
|
||||
process=Process.sequential,
|
||||
memory=True,
|
||||
memory_config={
|
||||
"provider": "mem0",
|
||||
"config": {"user_id": "crew_user_1"},
|
||||
}
|
||||
)
|
||||
```
|
||||
|
||||
## Main Execution Function
|
||||
|
||||
Implement the main function to run the travel planning system: retrieve context from Mem0, run the crew, then store the new conversation back:
|
||||
Implement the main function to run the travel planning system:
|
||||
|
||||
```python
|
||||
def plan_trip(destination: str, user_id: str):
|
||||
# Create agent
|
||||
travel_agent = create_travel_agent()
|
||||
user_context = get_user_context(user_id, f"travel preferences for {destination}")
|
||||
planning_task = create_planning_task(travel_agent, destination, user_context)
|
||||
|
||||
# Create task
|
||||
planning_task = create_planning_task(travel_agent, destination)
|
||||
|
||||
# Setup crew
|
||||
crew = setup_crew([travel_agent], [planning_task])
|
||||
result = crew.kickoff()
|
||||
|
||||
client.add(
|
||||
[{"role": "user", "content": f"Planned a trip to {destination}."}],
|
||||
user_id=user_id,
|
||||
)
|
||||
|
||||
return result
|
||||
# Execute and return results
|
||||
return crew.kickoff()
|
||||
|
||||
# Example usage
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -1,89 +0,0 @@
|
||||
---
|
||||
title: DeepSeek Harness
|
||||
description: "Add persistent Mem0 memory to the DeepSeek Harness (Cordis) agent with two native tools: search and add."
|
||||
---
|
||||
|
||||
Add persistent memory to the [**DeepSeek Harness**](https://github.com/deepseek-ai/deepseek-harness) with `@mem0/deepseek-plugin`. The Harness agent forgets everything between sessions. This plugin gives it two Mem0-backed tools so recall and writes persist across runs, sharing the same memory bank you already use from Claude Code, Codex, and other agents.
|
||||
|
||||
## Overview
|
||||
|
||||
The plugin registers two agent-callable tools:
|
||||
|
||||
| Tool | Does |
|
||||
|---|---|
|
||||
| `search_memory` | Recall facts from Mem0 relevant to a query |
|
||||
| `add_memory` | Store a fact in Mem0 for future sessions |
|
||||
|
||||
Unlike file-based memory plugins, Mem0 is a managed backend: server-side extraction, semantic dedup, and conflict resolution, with the same memory reusable across every agent you connect.
|
||||
|
||||
## How it works
|
||||
|
||||
A Cordis plugin is a module exporting `apply(ctx, config)`. This one declares `inject = ['tools']` so it waits for the harness tool registry, then registers the two tools via `ctx.tools.register(...)`. When the plugin unmounts, the tools are removed automatically (Cordis revertible effects).
|
||||
|
||||
## Prerequisites
|
||||
|
||||
1. A Mem0 Platform account and API key:
|
||||
- <a href="https://app.mem0.ai?utm_source=oss&utm_medium=integration-deepseek-plugin" rel="nofollow">Sign up at app.mem0.ai</a>
|
||||
- <a href="https://app.mem0.ai/dashboard/api-keys?utm_source=oss&utm_medium=integration-deepseek-plugin" rel="nofollow">Get your API key</a> (starts with `m0-`)
|
||||
|
||||
2. The DeepSeek Harness installed.
|
||||
|
||||
3. Your API key exported in your shell:
|
||||
|
||||
<CodeGroup>
|
||||
```bash zsh
|
||||
echo 'export MEM0_API_KEY="m0-your-api-key"' >> ~/.zshrc
|
||||
source ~/.zshrc
|
||||
```
|
||||
|
||||
```bash bash
|
||||
echo 'export MEM0_API_KEY="m0-your-api-key"' >> ~/.bashrc
|
||||
source ~/.bashrc
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
## Try it locally
|
||||
|
||||
1. Build the plugin:
|
||||
```sh
|
||||
cd integrations/deepseek-plugin
|
||||
pnpm install
|
||||
pnpm build
|
||||
```
|
||||
|
||||
2. Point the Harness at it. Copy `cordis.example.yml`, set the absolute path to `dist/index.js` and your `userId`, then load it:
|
||||
```sh
|
||||
pnpm dsh web --patch ./integrations/deepseek-plugin/cordis.example.yml
|
||||
```
|
||||
|
||||
3. Open the web UI and ask the agent to remember something, then recall it in a later turn.
|
||||
|
||||
The `cordis.yml` entry looks like this:
|
||||
|
||||
```yaml
|
||||
- name: "@deepseek-ai/dsh-system-prompt"
|
||||
- name: "@deepseek-ai/dsh-tools"
|
||||
- insert:
|
||||
- id: mem0
|
||||
name: "/absolute/path/to/integrations/deepseek-plugin/dist/index.js"
|
||||
config:
|
||||
# apiKey is read from MEM0_API_KEY when omitted here.
|
||||
userId: "your-user-id"
|
||||
# host: "https://your-onprem.mem0.ai" # optional: Platform on-prem / dedicated base URL
|
||||
```
|
||||
|
||||
For a Mem0 Platform on-prem or dedicated deployment, point `config.host` at that base URL (defaults to `api.mem0.ai`). `host` is a Platform base-URL override, not a switch to self-hosted Mem0 OSS.
|
||||
|
||||
## Configuration
|
||||
|
||||
| Field | Required | Default | Notes |
|
||||
|---|---|---|---|
|
||||
| `apiKey` | no | `$MEM0_API_KEY` | Mem0 platform API key |
|
||||
| `userId` | yes | | Default entity that owns the memories |
|
||||
| `host` | no | `api.mem0.ai` | Platform base URL (on-prem / dedicated) |
|
||||
|
||||
Both tools also accept optional per-call `userId`, `agentId`, and `runId` params so a single install can partition memory by entity, agent, or session; when omitted they fall back to the configured `userId`.
|
||||
|
||||
## Telemetry
|
||||
|
||||
Writes are tagged `source="DEEPSEEK_HARNESS"` so Mem0's backend can attribute usage to this integration.
|
||||
@@ -1,69 +0,0 @@
|
||||
---
|
||||
title: Strands Agents
|
||||
description: "Add persistent long-term memory to AWS Strands agents with Mem0, as a native MemoryStore that plugs into the agent loop."
|
||||
---
|
||||
|
||||
Integrate [**Mem0**](https://github.com/mem0ai/mem0) with [Strands Agents](https://github.com/strands-agents/sdk-python), AWS's open-source SDK for building AI agents. The [`mem0-strands`](https://github.com/mem0ai/mem0/tree/main/integrations/mem0-strands) package ships a native `MemoryStore`, so recall and writes happen automatically inside the agent loop, not as tool calls the model has to remember.
|
||||
|
||||
## Overview
|
||||
|
||||
1. A `MemoryStore` the `MemoryManager` drives on every turn: it searches Mem0 and injects the results into the prompt, and writes memory back when extraction is enabled.
|
||||
2. Server-side extraction: because the store implements `add_messages`, enabling `extraction` routes raw conversation turns to Mem0's own extraction pipeline, with no extra client-side model call.
|
||||
3. Works with the hosted Mem0 Platform (an API key) or self-hosted Mem0 OSS (a config dict).
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Before setting up Mem0 with Strands, ensure you have:
|
||||
|
||||
1. Installed the required packages:
|
||||
```bash
|
||||
pip install mem0-strands
|
||||
```
|
||||
|
||||
2. A valid API key:
|
||||
- <a href="https://app.mem0.ai/dashboard/api-keys?utm_source=oss&utm_medium=integration-strands" rel="nofollow">Mem0 API Key</a> (set as `MEM0_API_KEY`)
|
||||
|
||||
## Basic Integration Example
|
||||
|
||||
Hand a `Mem0MemoryStore` to a `MemoryManager`, and the agent gets automatic recall and memory writes:
|
||||
|
||||
```python
|
||||
import os
|
||||
from strands import Agent
|
||||
from strands.memory import MemoryManager
|
||||
from mem0_strands import Mem0MemoryStore
|
||||
|
||||
os.environ["MEM0_API_KEY"] = "your-mem0-api-key"
|
||||
|
||||
# extraction=True routes conversation turns to Mem0's server-side extraction.
|
||||
store = Mem0MemoryStore(user_id="alex", extraction=True)
|
||||
agent = Agent(memory_manager=MemoryManager(stores=[store]))
|
||||
|
||||
agent("Remember I use Neovim and deploy on Fridays.") # writes memory
|
||||
print(agent("What editor do I use?")) # recalls it, injected automatically
|
||||
```
|
||||
|
||||
Scope memories with any of `user_id`, `agent_id`, `run_id`, or `app_id` (`app_id` is platform-only). Pass `max_search_results` to bound how many memories are injected per turn.
|
||||
|
||||
## Self-hosted Mem0 (OSS)
|
||||
|
||||
To run against self-hosted Mem0 instead of the platform, pass a `config` dict:
|
||||
|
||||
```python
|
||||
store = Mem0MemoryStore(
|
||||
user_id="alex",
|
||||
extraction=True,
|
||||
config={
|
||||
"vector_store": {"provider": "qdrant", "config": {"host": "localhost", "port": 6333}},
|
||||
},
|
||||
)
|
||||
```
|
||||
|
||||
## Explicit memory tool
|
||||
|
||||
If you want the model to call memory explicitly instead of (or alongside) the automatic store, use the `mem0_memory` tool from `strands-agents-tools`. A store and the tool can share the same Mem0 backend and namespace.
|
||||
|
||||
## Learn more
|
||||
|
||||
- [mem0-strands on GitHub](https://github.com/mem0ai/mem0/tree/main/integrations/mem0-strands)
|
||||
- [Strands Agents documentation](https://strandsagents.com)
|
||||
@@ -1,130 +0,0 @@
|
||||
---
|
||||
title: Vercel
|
||||
description: "Add persistent memory to your Vercel apps with the Mem0 Vercel Marketplace integration. Install from the Marketplace, get an API key, and start building."
|
||||
---
|
||||
|
||||
The **Mem0 Vercel integration** provisions managed Mem0 access directly from the [Vercel Marketplace](https://vercel.com/marketplace). Installing it creates a Mem0 account for you and injects a `MEM0_API_KEY` into your Vercel project, so you can add long-term memory to your AI apps and agents in minutes, with no separate signup and billing handled through Vercel.
|
||||
|
||||
<Note type="info">
|
||||
This is the managed Marketplace integration. If you instead want to use Mem0 with the Vercel AI SDK in code, see [Vercel AI SDK](/integrations/vercel-ai-sdk).
|
||||
</Note>
|
||||
|
||||
## Overview
|
||||
|
||||
When you install Mem0 from the Vercel Marketplace:
|
||||
|
||||
- A Mem0 account and project are created for you (Vercel Native).
|
||||
- Mem0 environment variables (`MEM0_API_KEY`, `MEM0_ORG_ID`, `MEM0_PROJECT_ID`, `MEM0_BASE_URL`) are added to your connected Vercel project.
|
||||
- Billing is handled through your Vercel account, with no separate Mem0 subscription.
|
||||
|
||||
You call Mem0 from your app with the injected key. There is nothing else to wire up.
|
||||
|
||||
## Install
|
||||
|
||||
<Steps>
|
||||
<Step title="Add the integration">
|
||||
From the [Vercel Marketplace](https://vercel.com/marketplace), find **Mem0** and click **Install**. Choose **Create New Mem0 Account** (Vercel Native).
|
||||
</Step>
|
||||
<Step title="Pick a plan">
|
||||
Select **Hobby** (free) or **Starter** ($20/month). You can change this anytime from the installation settings in your Vercel dashboard.
|
||||
</Step>
|
||||
<Step title="Connect a project">
|
||||
Connect the Mem0 resource to a Vercel project. Mem0 injects its environment variables into that project.
|
||||
</Step>
|
||||
<Step title="Redeploy">
|
||||
Redeploy so the variables are available at runtime, or run `vercel env pull` to use them locally.
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Environment variables
|
||||
|
||||
The integration sets the following on your connected project:
|
||||
|
||||
| Variable | Description |
|
||||
| --- | --- |
|
||||
| `MEM0_API_KEY` | Your Mem0 API key, scoped to the org and project created for this installation. This is what you authenticate with. |
|
||||
| `MEM0_ORG_ID` | The Mem0 organization id for this installation. |
|
||||
| `MEM0_PROJECT_ID` | The Mem0 project id for this installation. |
|
||||
| `MEM0_BASE_URL` | The Mem0 API base URL (`https://api.mem0.ai`). |
|
||||
|
||||
The API key is scoped to your org and project, so the SDK needs only `MEM0_API_KEY` to get started.
|
||||
|
||||
## Quickstart
|
||||
|
||||
Install the SDK:
|
||||
|
||||
<CodeGroup>
|
||||
```bash npm
|
||||
npm install mem0ai
|
||||
```
|
||||
|
||||
```bash pip
|
||||
pip install mem0ai
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
Add and search memories using the injected key:
|
||||
|
||||
<CodeGroup>
|
||||
```typescript JavaScript
|
||||
import MemoryClient from "mem0ai";
|
||||
|
||||
const memory = new MemoryClient({ apiKey: process.env.MEM0_API_KEY });
|
||||
|
||||
// Store a memory
|
||||
await memory.add(
|
||||
[{ role: "user", content: "I'm a vegetarian and allergic to nuts." }],
|
||||
{ userId: "user123" },
|
||||
);
|
||||
|
||||
// Retrieve relevant memories
|
||||
const results = await memory.search("What are my dietary restrictions?", {
|
||||
filters: { user_id: "user123" },
|
||||
});
|
||||
console.log(results);
|
||||
```
|
||||
|
||||
```python Python
|
||||
import os
|
||||
from mem0 import MemoryClient
|
||||
|
||||
memory = MemoryClient(api_key=os.environ["MEM0_API_KEY"])
|
||||
|
||||
# Store a memory
|
||||
memory.add(
|
||||
[{"role": "user", "content": "I'm a vegetarian and allergic to nuts."}],
|
||||
user_id="user123",
|
||||
)
|
||||
|
||||
# Retrieve relevant memories
|
||||
results = memory.search("What are my dietary restrictions?", filters={"user_id": "user123"})
|
||||
print(results)
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
See the [platform quickstart](/platform/quickstart) for the full API.
|
||||
|
||||
## Plans and billing
|
||||
|
||||
| Plan | Price | Memories | Retrieval calls | Projects | Support |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| Hobby | Free | 10,000 | 1,000 / month | 1 | Community |
|
||||
| Starter | $20 / month | 50,000 | 5,000 / month | 1 | Community |
|
||||
|
||||
Billing runs through your Vercel account; Mem0 never charges your card directly. You can upgrade or downgrade anytime from the installation's settings in the Vercel dashboard.
|
||||
|
||||
## Managing the integration
|
||||
|
||||
- **Change plan:** open the installation in your Vercel dashboard and update the billing plan.
|
||||
- **Open in Mem0:** use the **Open in Mem0** link to sign in to the Mem0 dashboard for this installation.
|
||||
- **Uninstall:** removing the integration deactivates the API key and tears down the resource. Any usage for the current period is invoiced before removal.
|
||||
|
||||
## Notes
|
||||
|
||||
- The integration creates a **new** Mem0 account for the installation. Linking an existing Mem0 account is not supported yet.
|
||||
- The injected `MEM0_API_KEY` is scoped to the org and project created for this installation, so you do not manage keys by hand.
|
||||
|
||||
## Related
|
||||
|
||||
- [Platform quickstart](/platform/quickstart)
|
||||
- [Vercel AI SDK integration](/integrations/vercel-ai-sdk)
|
||||
+3
-22
@@ -185,7 +185,7 @@ If the user is on a pre-current major (Python < 2, TS < 3, or a Platform call st
|
||||
## Core Concepts
|
||||
|
||||
- [How Mem0 Works](https://docs.mem0.ai/core-concepts/how-it-works) [Both]: Use when explaining the end-to-end pipeline: extraction (ADD-only distillation), storage across vector/entity/history stores, and multi-signal retrieval.
|
||||
- [Memory Types](https://docs.mem0.ai/core-concepts/memory-types) [Both]: Use when checking which `memory_type` values actually work: `procedural_memory` is implemented, `semantic_memory` and `episodic_memory` are defined in the enum but rejected by validation.
|
||||
- [Memory Types](https://docs.mem0.ai/core-concepts/memory-types) [Both]: Use when explaining working, factual, episodic, and semantic memory distinctions.
|
||||
- [Memory Operations - Add](https://docs.mem0.ai/core-concepts/memory-operations/add) [Both]: Use when explaining how `add()` extracts facts, resolves conflicts, and writes to both stores.
|
||||
- [Memory Operations - Search](https://docs.mem0.ai/core-concepts/memory-operations/search) [Both]: Use when explaining how queries are processed and ranked.
|
||||
- [Memory Operations - Update](https://docs.mem0.ai/core-concepts/memory-operations/update) [Both]: Use when memories need to be edited in place or reconciled against new info.
|
||||
@@ -257,18 +257,14 @@ If the user is on a pre-current major (Python < 2, TS < 3, or a Platform call st
|
||||
- [ChatDev](https://docs.mem0.ai/integrations/chatdev) [Platform]: Use when the user is on ChatDev.
|
||||
- [Hermes](https://docs.mem0.ai/integrations/hermes) [Both]: Use when the user is on Hermes.
|
||||
- [Pi Agent](https://docs.mem0.ai/integrations/pi-agent) [Platform]: Use when adding persistent memory to Pi Agent with the Mem0 plugin.
|
||||
- [DeepSeek Harness](https://docs.mem0.ai/integrations/deepseek-plugin) [Platform]: Use when adding persistent memory to the DeepSeek Harness (Cordis) agent via the Mem0 plugin.
|
||||
- [OpenAI Agents SDK](https://docs.mem0.ai/integrations/openai-agents-sdk) [Platform]: Use when the user is on the OpenAI Agents SDK.
|
||||
- [Google AI ADK](https://docs.mem0.ai/integrations/google-ai-adk) [Platform]: Use when the user is on Google's Agent Development Kit.
|
||||
- [Mastra](https://docs.mem0.ai/integrations/mastra) [Platform]: Use when the user is on Mastra (TypeScript).
|
||||
- [OpenClaw](https://docs.mem0.ai/integrations/openclaw) [Both]: Use when wiring Mem0 into Claude Code or editors via OpenClaw.
|
||||
- [Vercel AI SDK](https://docs.mem0.ai/integrations/vercel-ai-sdk) [Both]: Use when the user is on the Vercel AI SDK.
|
||||
- [Vercel](https://docs.mem0.ai/integrations/vercel) [Platform]: Use when deploying on Vercel and installing Mem0 from the Vercel Marketplace.
|
||||
- [Strands Agents](https://docs.mem0.ai/integrations/strands) [Both]: Use when the user is on AWS Strands and wants a native MemoryStore.
|
||||
|
||||
### AI Coding Tools
|
||||
- [Claude Code](https://docs.mem0.ai/integrations/claude-code) [Both]: Use when wiring memory into Claude Code.
|
||||
- [Claude.ai](https://docs.mem0.ai/integrations/claude-ai) [Platform]: Use when connecting Mem0 to Claude.ai (the hosted web app) via a custom remote MCP connector, or when Claude's native memory seems to be crowding out mem0 tool calls.
|
||||
- [Cursor](https://docs.mem0.ai/integrations/cursor) [Platform]: Use when wiring memory into Cursor.
|
||||
- [Codex](https://docs.mem0.ai/integrations/codex) [Platform]: Use when wiring memory into Codex / other editor assistants.
|
||||
- [OpenCode](https://docs.mem0.ai/integrations/opencode) [Platform]: Use when wiring memory into OpenCode.
|
||||
@@ -298,6 +294,7 @@ If the user is on a pre-current major (Python < 2, TS < 3, or a Platform call st
|
||||
### Essentials
|
||||
- [Building an AI Companion](https://docs.mem0.ai/cookbooks/essentials/building-ai-companion) [Both]: Use when starting a companion app from scratch.
|
||||
- [Partition Memories by Entity](https://docs.mem0.ai/cookbooks/essentials/entity-partitioning-playbook) [Both]: Use when isolating multi-tenant memories.
|
||||
- [Controlling Memory Ingestion](https://docs.mem0.ai/cookbooks/essentials/controlling-memory-ingestion) [Both]: Use when deciding what to store and what to skip.
|
||||
- [Tagging and Organizing Memories](https://docs.mem0.ai/cookbooks/essentials/tagging-and-organizing-memories) [Both]: Use when memory taxonomy matters.
|
||||
- [Exporting Memories](https://docs.mem0.ai/cookbooks/essentials/exporting-memories) [Both]: Use when backing up or migrating memory data.
|
||||
|
||||
@@ -383,16 +380,6 @@ All API Reference docs describe Mem0 Platform REST endpoints (requires API key).
|
||||
- [Remove Project Member](https://docs.mem0.ai/api-reference/project/remove-project-member) [Platform]: Use when removing a member from a project.
|
||||
- [Delete Project](https://docs.mem0.ai/api-reference/project/delete-project) [Platform]: Use when removing a project.
|
||||
|
||||
### Dream
|
||||
- [Get Dream Configuration](https://docs.mem0.ai/api-reference/dream/get-dream-config) [Platform]: Use when reading a project's Dream (memory synthesis) config and plan entitlements.
|
||||
- [Update Dream Configuration](https://docs.mem0.ai/api-reference/dream/update-dream-config) [Platform]: Use when enabling/disabling Synthesis or changing its mode for a project.
|
||||
- [Get Dream Stats](https://docs.mem0.ai/api-reference/dream/get-dream-stats) [Platform]: Use when fetching lifecycle and synthesis counts for the Dream dashboard.
|
||||
- [Get Dream Activity](https://docs.mem0.ai/api-reference/dream/get-dream-activity) [Platform]: Use when listing recent supersede/merge activity for a project.
|
||||
- [Get Dream Synthesis Runs](https://docs.mem0.ai/api-reference/dream/get-dream-runs) [Platform]: Use when listing synthesis runs and the memories they generated.
|
||||
- [Get Memories in a Dream Run](https://docs.mem0.ai/api-reference/dream/get-dream-run-memories) [Platform]: Use when paging the synthesized memories within a single run.
|
||||
- [Get a Synthesized Memory's Sources](https://docs.mem0.ai/api-reference/dream/get-dream-memory-sources) [Platform]: Use when tracing the source memories a synthesized memory was distilled from.
|
||||
- [Preview Dream Scope](https://docs.mem0.ai/api-reference/dream/dream-preview) [Platform]: Use when previewing what Synthesis would analyze for a project (no writes).
|
||||
|
||||
### Webhooks
|
||||
- [Create Webhook](https://docs.mem0.ai/api-reference/webhook/create-webhook) [Platform]: Use when registering a webhook endpoint.
|
||||
- [Get Webhook](https://docs.mem0.ai/api-reference/webhook/get-webhook) [Platform]: Use when fetching webhook config.
|
||||
@@ -413,17 +400,11 @@ Source: https://github.com/mem0ai/mem0/tree/main/skills
|
||||
|
||||
Each subdirectory is a Claude Code Skill (`SKILL.md` + supporting assets). Load only the one that matches the user's stack.
|
||||
|
||||
### Claude Code Plugin
|
||||
|
||||
Source: https://github.com/mem0ai/mem0/tree/main/integrations/claude-code-plugin
|
||||
|
||||
The `integrations/claude-code-plugin/` directory is the Claude Code plugin (v0.3.0, installs as `mem0@mem0-plugins`). It captures evidence locally through lifecycle hooks, extracts memories in a detached background worker, and exposes a single local MCP tool, `search_memories`, plus six `/mem0:*` skills and the `mem0:sidekick` agent. Pure-stdlib Python, nothing to install.
|
||||
|
||||
### Editor Plugin (shared glue)
|
||||
|
||||
Source: https://github.com/mem0ai/mem0/tree/main/integrations/mem0-plugin
|
||||
|
||||
The `integrations/mem0-plugin/` directory provides MCP server connection, lifecycle hooks, and skill bundling for Cursor, Codex, Kimi, Antigravity, and OpenCode. It exposes 9 MCP tools: `add_memory`, `search_memories`, `get_memories`, `get_memory`, `update_memory`, `delete_memory`, `delete_all_memories`, `delete_entities`, `list_entities`. Claude Code moved to `integrations/claude-code-plugin/` in v0.3.0; do not run both at the same time.
|
||||
The `integrations/mem0-plugin/` directory provides MCP server connection, lifecycle hooks, and skill bundling for Claude Code, Cursor, Codex, OpenCode, and Antigravity. It exposes 9 MCP tools: `add_memory`, `search_memories`, `get_memories`, `get_memory`, `update_memory`, `delete_memory`, `delete_all_memories`, `delete_entities`, `list_entities`.
|
||||
|
||||
Editor-specific setup docs (already listed above under `## Integrations > AI Coding Tools`):
|
||||
|
||||
|
||||
@@ -6,10 +6,6 @@ icon: "filter"
|
||||
|
||||
Enhanced metadata filtering in Mem0 lets you run complex queries across memory metadata. Combine comparisons, logical operators, and wildcard matches to zero in on the exact memories your agent needs.
|
||||
|
||||
<Info>
|
||||
This page covers the self-hosted `Memory` / `AsyncMemory` grammar. Sibling top-level keys are implicitly ANDed on both self-hosted and the hosted Platform API, so a flat filter like `{"user_id": "alice", "category": "work"}` works without wrapping it in `AND` on either. Two real differences remain: the `nin` operator documented below is not part of the Platform contract, and Platform validates every top-level key against a fixed allow-list, rejecting anything else with a 400. See [Memory Filters (Platform)](/platform/features/v2-memory-filters) for the hosted grammar.
|
||||
</Info>
|
||||
|
||||
---
|
||||
|
||||
## Feature anatomy
|
||||
@@ -23,7 +19,7 @@ This page covers the self-hosted `Memory` / `AsyncMemory` grammar. Sibling top-l
|
||||
| `lt` / `lte` | Less than / less than or equal | Cap numeric values (e.g., ratings, timestamps). |
|
||||
| `in` / `nin` | In list / not in list | Pre-approve or block sets of values without chaining multiple filters. |
|
||||
| `contains` / `icontains` | Case-sensitive / case-insensitive substring match | Scan text fields for keywords. |
|
||||
| `*` | Wildcard | Match regardless of value. Exact semantics (field-must-exist vs. no-op) vary by vector store, see [Wildcard matching](#wildcard-matching). |
|
||||
| `*` | Wildcard | Require that a field exists, regardless of value. |
|
||||
| `AND` / `OR` / `NOT` | Combine filters | Build logic trees so multiple conditions work together. |
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
@@ -115,7 +111,7 @@ results = m.search(
|
||||
|
||||
### Wildcard matching
|
||||
|
||||
Match any value for a field, handy when the mere presence of a field matters.
|
||||
Allow any value for a field while still requiring the field to exist: handy when the mere presence of a field matters.
|
||||
|
||||
```python
|
||||
# Match any value for a field
|
||||
@@ -128,18 +124,10 @@ results = m.search(
|
||||
)
|
||||
```
|
||||
|
||||
<Warning>
|
||||
Wildcard semantics differ by vector store. pgvector requires the key to exist in the payload (a real "field exists" check). Qdrant and Chroma have no native "field exists" filter, so `*` is a no-op there: the field condition is dropped and every record passes, including ones where the field is missing entirely. Do not rely on `*` to exclude records with a missing field unless you have confirmed your store's behavior in `mem0/vector_stores/<provider>.py`.
|
||||
</Warning>
|
||||
|
||||
### Logical combinations
|
||||
|
||||
Combine filters with `AND`, `OR`, and `NOT` to express complex decision trees. Nest logical operators to encode multi-branch workflows.
|
||||
|
||||
<Warning>
|
||||
The examples on this page use `search()`. `get_all()` accepts the same entity and comparison-operator filters, but the `AND` / `OR` / `NOT` wrapper is only translated at the `search()` layer before it reaches the vector store. Whether it also works on `get_all()` depends on your vector store: Qdrant recognizes raw `AND` / `OR` / `NOT` keys natively, but pgvector does not, so a logical wrapper passed to `get_all()` on pgvector silently matches nothing. Stick to `search()` for logical trees, or use plain sibling keys (implicitly ANDed) with `get_all()`.
|
||||
</Warning>
|
||||
|
||||
```python
|
||||
# Logical AND
|
||||
results = m.search(
|
||||
@@ -257,18 +245,25 @@ avoid_filters = {
|
||||
When you reorder filters so indexed fields come first (`good_filters` example), queries typically return faster than the `avoid_filters` pattern where expensive text searches run before simple checks.
|
||||
</Info>
|
||||
|
||||
Vector store support varies widely. This table reflects what each provider's filter-translation code (`mem0/vector_stores/<provider>.py`) actually implements, confirm before shipping if you use a store not listed:
|
||||
Vector store support varies. Confirm operator coverage before shipping:
|
||||
|
||||
| Store | `eq`/`ne`/`gt`/`gte`/`lt`/`lte`/`in`/`nin` | `contains`/`icontains` | `AND`/`OR`/`NOT` | `*` wildcard |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| Qdrant | Full support (`in`/`nin` must be a list, or the Qdrant client raises a validation error) | Yes | Yes, nested | No-op: matches every record regardless of whether the field is present |
|
||||
| pgvector | Full support (`in`/`nin` must be a list, or the call raises `ValueError`) | Yes, via SQL `LIKE`/`ILIKE` | Yes, nested | Requires the key to exist in the payload |
|
||||
| Chroma | Full support | No: silently falls back to equality | Yes, one level of nesting | No-op: the filter is dropped |
|
||||
| Pinecone | Full support | Not implemented | Not implemented: filters are only ANDed field-by-field | Not implemented: `"*"` is matched as the literal string `"*"`, not a wildcard |
|
||||
| Weaviate | Not implemented: only `user_id`, `agent_id` and `run_id` are filtered on, as exact equality. Every other key, including all metadata, is silently dropped | Not implemented | Not implemented: only an implicit AND across the three supported keys | Not implemented |
|
||||
<AccordionGroup>
|
||||
<Accordion title="Qdrant">
|
||||
Full comparison, list, and logical support. Handles deeply nested boolean logic efficiently.
|
||||
</Accordion>
|
||||
<Accordion title="Chroma">
|
||||
Equality and basic comparisons only. Limited nesting: break large trees into smaller calls.
|
||||
</Accordion>
|
||||
<Accordion title="Pinecone">
|
||||
Comparisons plus `in`/`nin`. Text operators are constrained; rely on tags where possible.
|
||||
</Accordion>
|
||||
<Accordion title="Weaviate">
|
||||
Full operator coverage with advanced text filters. Best option when you need hybrid text + metadata queries.
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
<Warning>
|
||||
If an operator is unsupported, most stores silently ignore it or fall back to equality rather than raising an error. Test filters against your actual store instead of assuming operator parity with Qdrant.
|
||||
If an operator is unsupported, most stores silently ignore that branch. Add validation before execution so you can fall back to simpler queries instead of returning empty results.
|
||||
</Warning>
|
||||
|
||||
### Migrate from earlier filters
|
||||
@@ -432,7 +427,4 @@ except ValueError as e:
|
||||
<Card title="Tag and Organize Memories" icon="tag" href="/cookbooks/essentials/tagging-and-organizing-memories">
|
||||
Practice building workflows that label and retrieve memories with clear metadata filters.
|
||||
</Card>
|
||||
<Card title="Memory Filters (Platform)" icon="cloud" href="/platform/features/v2-memory-filters">
|
||||
Using the hosted API instead? See the allow-listed top-level fields, the missing `nin` operator, and Platform-only fields like `created_at` and `memory_ids`.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
@@ -7207,869 +7207,6 @@
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"/api/v1/orgs/organizations/{org_id}/projects/{project_id}/dream/config/": {
|
||||
"get": {
|
||||
"tags": [
|
||||
"dream"
|
||||
],
|
||||
"summary": "Get Dream configuration",
|
||||
"description": "Retrieve the project's Dream (memory synthesis) configuration together with the plan entitlement snapshot. Dream automatically supersedes/merges memories on the add path; **Synthesis** (reflection) is the opt-in part controlled by `reflection_enabled`.",
|
||||
"operationId": "get_dream_config",
|
||||
"parameters": [
|
||||
{
|
||||
"name": "org_id",
|
||||
"in": "path",
|
||||
"required": true,
|
||||
"description": "Unique identifier of the organization.",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "project_id",
|
||||
"in": "path",
|
||||
"required": true,
|
||||
"description": "Unique identifier of the project.",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Successful response.",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"config": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"reflection_enabled": {
|
||||
"type": "boolean",
|
||||
"description": "Whether background synthesis (reflection) is enabled for the project."
|
||||
},
|
||||
"reflection_enabled_at": {
|
||||
"type": "string",
|
||||
"description": "When synthesis was last enabled. Synthesis only considers memories created on or after this time (forward-only).",
|
||||
"format": "date-time",
|
||||
"nullable": true
|
||||
},
|
||||
"reflection_mode": {
|
||||
"type": "string",
|
||||
"description": "Synthesis execution mode.",
|
||||
"enum": [
|
||||
"batch",
|
||||
"direct"
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"entitlements": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"plan": {
|
||||
"type": "string",
|
||||
"description": "Resolved billing tier for the project (e.g. `free`, `pro`, `custom`)."
|
||||
},
|
||||
"reflection_interval_days": {
|
||||
"type": "integer",
|
||||
"description": "How often synthesis runs for this plan, in days (Pro weekly, Enterprise daily)."
|
||||
},
|
||||
"features": {
|
||||
"type": "object",
|
||||
"properties": {},
|
||||
"description": "Per-feature entitlement snapshot, keyed by Dream feature (e.g. `dream_reflection`, `dream_tab`, `dream_preview`).",
|
||||
"additionalProperties": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"entitled": {
|
||||
"type": "boolean",
|
||||
"description": "Whether the plan is entitled to the feature."
|
||||
},
|
||||
"killed": {
|
||||
"type": "boolean",
|
||||
"description": "Whether the feature is globally disabled by a kill switch."
|
||||
},
|
||||
"enabled": {
|
||||
"type": "boolean",
|
||||
"description": "Effective state: entitled AND not killed AND turned on."
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"patch": {
|
||||
"tags": [
|
||||
"dream"
|
||||
],
|
||||
"summary": "Update Dream configuration",
|
||||
"description": "Enable or disable Synthesis (reflection) for the project, or change the reflection mode. Requires a Pro or Enterprise (CUSTOM) plan and organization-owner permission. Synthesis is forward-only: after enabling, it only synthesizes memories added from that point on.",
|
||||
"operationId": "update_dream_config",
|
||||
"parameters": [
|
||||
{
|
||||
"name": "org_id",
|
||||
"in": "path",
|
||||
"required": true,
|
||||
"description": "Unique identifier of the organization.",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "project_id",
|
||||
"in": "path",
|
||||
"required": true,
|
||||
"description": "Unique identifier of the project.",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
],
|
||||
"requestBody": {
|
||||
"required": true,
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"reflection_enabled": {
|
||||
"type": "boolean",
|
||||
"description": "Turn background synthesis on or off."
|
||||
},
|
||||
"reflection_mode": {
|
||||
"type": "string",
|
||||
"description": "Synthesis execution mode.",
|
||||
"enum": [
|
||||
"batch",
|
||||
"direct"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Updated configuration.",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"config": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"reflection_enabled": {
|
||||
"type": "boolean",
|
||||
"description": "Whether background synthesis (reflection) is enabled for the project."
|
||||
},
|
||||
"reflection_enabled_at": {
|
||||
"type": "string",
|
||||
"description": "When synthesis was last enabled. Synthesis only considers memories created on or after this time (forward-only).",
|
||||
"format": "date-time",
|
||||
"nullable": true
|
||||
},
|
||||
"reflection_mode": {
|
||||
"type": "string",
|
||||
"description": "Synthesis execution mode.",
|
||||
"enum": [
|
||||
"batch",
|
||||
"direct"
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"entitlements": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"plan": {
|
||||
"type": "string",
|
||||
"description": "Resolved billing tier for the project (e.g. `free`, `pro`, `custom`)."
|
||||
},
|
||||
"reflection_interval_days": {
|
||||
"type": "integer",
|
||||
"description": "How often synthesis runs for this plan, in days (Pro weekly, Enterprise daily)."
|
||||
},
|
||||
"features": {
|
||||
"type": "object",
|
||||
"properties": {},
|
||||
"description": "Per-feature entitlement snapshot, keyed by Dream feature (e.g. `dream_reflection`, `dream_tab`, `dream_preview`).",
|
||||
"additionalProperties": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"entitled": {
|
||||
"type": "boolean",
|
||||
"description": "Whether the plan is entitled to the feature."
|
||||
},
|
||||
"killed": {
|
||||
"type": "boolean",
|
||||
"description": "Whether the feature is globally disabled by a kill switch."
|
||||
},
|
||||
"enabled": {
|
||||
"type": "boolean",
|
||||
"description": "Effective state: entitled AND not killed AND turned on."
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "Validation error (e.g. a field the plan is not entitled to change)."
|
||||
},
|
||||
"403": {
|
||||
"description": "Not entitled on the current plan (`upgrade_required: true`), or the caller is not an organization owner."
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/orgs/organizations/{org_id}/projects/{project_id}/dream/stats/": {
|
||||
"get": {
|
||||
"tags": [
|
||||
"dream"
|
||||
],
|
||||
"summary": "Get Dream stats",
|
||||
"description": "Lifecycle + synthesis counts for the project's Dream dashboard, plus reflection freshness. Requires a Pro or Enterprise (CUSTOM) plan.",
|
||||
"operationId": "get_dream_stats",
|
||||
"parameters": [
|
||||
{
|
||||
"name": "org_id",
|
||||
"in": "path",
|
||||
"required": true,
|
||||
"description": "Unique identifier of the organization.",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "project_id",
|
||||
"in": "path",
|
||||
"required": true,
|
||||
"description": "Unique identifier of the project.",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Successful response.",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"active": {
|
||||
"type": "integer",
|
||||
"description": "Active (current) memory count."
|
||||
},
|
||||
"merged": {
|
||||
"type": "integer",
|
||||
"description": "Count of memories merged into a canonical one."
|
||||
},
|
||||
"superseded": {
|
||||
"type": "integer",
|
||||
"description": "Count of memories superseded by a newer one."
|
||||
},
|
||||
"synthesized": {
|
||||
"type": "integer",
|
||||
"description": "Count of higher-order pattern memories created by synthesis."
|
||||
},
|
||||
"last_run_at": {
|
||||
"type": "string",
|
||||
"description": "When synthesis last completed.",
|
||||
"format": "date-time",
|
||||
"nullable": true
|
||||
},
|
||||
"processed_through": {
|
||||
"type": "string",
|
||||
"description": "Timestamp of the newest source memory synthesis has processed.",
|
||||
"format": "date-time",
|
||||
"nullable": true
|
||||
},
|
||||
"running": {
|
||||
"type": "boolean",
|
||||
"description": "Whether a synthesis run is currently in flight."
|
||||
},
|
||||
"next_run_at": {
|
||||
"type": "string",
|
||||
"description": "Projected next synthesis run.",
|
||||
"format": "date-time",
|
||||
"nullable": true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"403": {
|
||||
"description": "Not entitled on the current plan (`upgrade_required: true`)."
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/orgs/organizations/{org_id}/projects/{project_id}/dream/activity/": {
|
||||
"get": {
|
||||
"tags": [
|
||||
"dream"
|
||||
],
|
||||
"summary": "Get Dream activity",
|
||||
"description": "Supersede/merge activity feed (newest first), keyset-paginated. Synthesis output is not included here — see the runs endpoint.",
|
||||
"operationId": "get_dream_activity",
|
||||
"parameters": [
|
||||
{
|
||||
"name": "org_id",
|
||||
"in": "path",
|
||||
"required": true,
|
||||
"description": "Unique identifier of the organization.",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "project_id",
|
||||
"in": "path",
|
||||
"required": true,
|
||||
"description": "Unique identifier of the project.",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "limit",
|
||||
"in": "query",
|
||||
"required": false,
|
||||
"description": "Page size (default 50, max 200).",
|
||||
"schema": {
|
||||
"type": "integer",
|
||||
"default": 50
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "cursor",
|
||||
"in": "query",
|
||||
"required": false,
|
||||
"description": "Opaque keyset cursor from a previous page's `next_cursor`.",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Successful response.",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"results": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"memory_id": {
|
||||
"type": "string",
|
||||
"description": "The superseded/merged memory's ID."
|
||||
},
|
||||
"text": {
|
||||
"type": "string",
|
||||
"description": "The memory's text (truncated)."
|
||||
},
|
||||
"transition": {
|
||||
"type": "string",
|
||||
"description": "Lifecycle transition.",
|
||||
"enum": [
|
||||
"merged",
|
||||
"superseded"
|
||||
]
|
||||
},
|
||||
"at": {
|
||||
"type": "string",
|
||||
"description": "When the transition happened.",
|
||||
"format": "date-time"
|
||||
},
|
||||
"replaced_by": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"id": {
|
||||
"type": "string",
|
||||
"description": "ID of the newer memory."
|
||||
},
|
||||
"text": {
|
||||
"type": "string",
|
||||
"description": "Text of the newer memory (truncated).",
|
||||
"nullable": true
|
||||
}
|
||||
},
|
||||
"nullable": true,
|
||||
"description": "The newer memory that replaced this one (null for a merge with no single replacement)."
|
||||
},
|
||||
"sources": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"id": {
|
||||
"type": "string",
|
||||
"description": "Source memory ID."
|
||||
},
|
||||
"text": {
|
||||
"type": "string",
|
||||
"description": "Source memory text (truncated)."
|
||||
}
|
||||
}
|
||||
},
|
||||
"nullable": true,
|
||||
"description": "Always null on this feed; synthesis provenance is shown on the runs feed."
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"next_cursor": {
|
||||
"type": "string",
|
||||
"description": "Cursor for the next page, or null when there are no more.",
|
||||
"nullable": true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/orgs/organizations/{org_id}/projects/{project_id}/dream/runs/": {
|
||||
"get": {
|
||||
"tags": [
|
||||
"dream"
|
||||
],
|
||||
"summary": "Get Dream synthesis runs",
|
||||
"description": "Synthesis activity grouped per run (newest first), keyset-paginated. Each run inlines its first page of synthesized memories with their sources; larger runs page the rest via the run-memories endpoint.",
|
||||
"operationId": "get_dream_runs",
|
||||
"parameters": [
|
||||
{
|
||||
"name": "org_id",
|
||||
"in": "path",
|
||||
"required": true,
|
||||
"description": "Unique identifier of the organization.",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "project_id",
|
||||
"in": "path",
|
||||
"required": true,
|
||||
"description": "Unique identifier of the project.",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "limit",
|
||||
"in": "query",
|
||||
"required": false,
|
||||
"description": "Number of runs per page (default 20, max 100).",
|
||||
"schema": {
|
||||
"type": "integer",
|
||||
"default": 20
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "cursor",
|
||||
"in": "query",
|
||||
"required": false,
|
||||
"description": "Opaque keyset cursor from a previous page's `next_cursor`.",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Successful response.",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"results": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"run_id": {
|
||||
"type": "string",
|
||||
"description": "Identifier of the synthesis run."
|
||||
},
|
||||
"at": {
|
||||
"type": "string",
|
||||
"description": "When the run produced memories.",
|
||||
"format": "date-time"
|
||||
},
|
||||
"count": {
|
||||
"type": "integer",
|
||||
"description": "Total synthesized memories in this run."
|
||||
},
|
||||
"synthesized": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"id": {
|
||||
"type": "string",
|
||||
"description": "Synthesized memory ID."
|
||||
},
|
||||
"text": {
|
||||
"type": "string",
|
||||
"description": "Synthesized (pattern) memory text."
|
||||
},
|
||||
"sources": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"id": {
|
||||
"type": "string",
|
||||
"description": "Source memory ID."
|
||||
},
|
||||
"text": {
|
||||
"type": "string",
|
||||
"description": "Source memory text (truncated)."
|
||||
}
|
||||
}
|
||||
},
|
||||
"description": "Source memories this pattern was distilled from."
|
||||
}
|
||||
}
|
||||
},
|
||||
"description": "First page of synthesized memories (each with its sources)."
|
||||
},
|
||||
"has_more": {
|
||||
"type": "boolean",
|
||||
"description": "Whether the run has more memories than are inlined here."
|
||||
},
|
||||
"mem_cursor": {
|
||||
"type": "string",
|
||||
"description": "Cursor to page this run's remaining memories via the run-memories endpoint.",
|
||||
"nullable": true
|
||||
},
|
||||
"sources": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"id": {
|
||||
"type": "string",
|
||||
"description": "Source memory ID."
|
||||
},
|
||||
"text": {
|
||||
"type": "string",
|
||||
"description": "Source memory text (truncated)."
|
||||
}
|
||||
}
|
||||
},
|
||||
"description": "De-duplicated source memories across the inlined page."
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"next_cursor": {
|
||||
"type": "string",
|
||||
"description": "Cursor for the next page, or null when there are no more.",
|
||||
"nullable": true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/orgs/organizations/{org_id}/projects/{project_id}/dream/runs/{run_id}/memories/": {
|
||||
"get": {
|
||||
"tags": [
|
||||
"dream"
|
||||
],
|
||||
"summary": "Get memories in a Dream run",
|
||||
"description": "Keyset page of the synthesized memories within a single run (for runs whose `has_more` is true).",
|
||||
"operationId": "get_dream_run_memories",
|
||||
"parameters": [
|
||||
{
|
||||
"name": "org_id",
|
||||
"in": "path",
|
||||
"required": true,
|
||||
"description": "Unique identifier of the organization.",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "project_id",
|
||||
"in": "path",
|
||||
"required": true,
|
||||
"description": "Unique identifier of the project.",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "run_id",
|
||||
"in": "path",
|
||||
"required": true,
|
||||
"description": "Identifier of the synthesis run.",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "limit",
|
||||
"in": "query",
|
||||
"required": false,
|
||||
"description": "Page size (default 50, max 200).",
|
||||
"schema": {
|
||||
"type": "integer",
|
||||
"default": 50
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "cursor",
|
||||
"in": "query",
|
||||
"required": false,
|
||||
"description": "Opaque keyset cursor (use the run's `mem_cursor` or a previous `next_cursor`).",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Successful response.",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"results": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"id": {
|
||||
"type": "string",
|
||||
"description": "Synthesized memory ID."
|
||||
},
|
||||
"text": {
|
||||
"type": "string",
|
||||
"description": "Synthesized (pattern) memory text."
|
||||
},
|
||||
"sources": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"id": {
|
||||
"type": "string",
|
||||
"description": "Source memory ID."
|
||||
},
|
||||
"text": {
|
||||
"type": "string",
|
||||
"description": "Source memory text (truncated)."
|
||||
}
|
||||
}
|
||||
},
|
||||
"description": "Source memories this pattern was distilled from."
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"next_cursor": {
|
||||
"type": "string",
|
||||
"description": "Cursor for the next page, or null when there are no more.",
|
||||
"nullable": true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/orgs/organizations/{org_id}/projects/{project_id}/dream/memory/{memory_id}/sources/": {
|
||||
"get": {
|
||||
"tags": [
|
||||
"dream"
|
||||
],
|
||||
"summary": "Get a synthesized memory's sources",
|
||||
"description": "The source memories a synthesized (pattern) memory was distilled from, for the memory drawer's provenance panel.",
|
||||
"operationId": "get_dream_memory_sources",
|
||||
"parameters": [
|
||||
{
|
||||
"name": "org_id",
|
||||
"in": "path",
|
||||
"required": true,
|
||||
"description": "Unique identifier of the organization.",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "project_id",
|
||||
"in": "path",
|
||||
"required": true,
|
||||
"description": "Unique identifier of the project.",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "memory_id",
|
||||
"in": "path",
|
||||
"required": true,
|
||||
"description": "ID of the (synthesized) memory.",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Successful response.",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"memory_id": {
|
||||
"type": "string",
|
||||
"description": "The memory's ID."
|
||||
},
|
||||
"synthesized": {
|
||||
"type": "boolean",
|
||||
"description": "Whether this memory was produced by synthesis."
|
||||
},
|
||||
"sources": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"id": {
|
||||
"type": "string",
|
||||
"description": "Source memory ID."
|
||||
},
|
||||
"text": {
|
||||
"type": "string",
|
||||
"description": "Source memory text."
|
||||
},
|
||||
"lifecycle_state": {
|
||||
"type": "string",
|
||||
"description": "Source memory lifecycle state.",
|
||||
"enum": [
|
||||
"active",
|
||||
"merged",
|
||||
"superseded"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"404": {
|
||||
"description": "Memory not found in this project."
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/orgs/organizations/{org_id}/projects/{project_id}/dream/preview/": {
|
||||
"post": {
|
||||
"tags": [
|
||||
"dream"
|
||||
],
|
||||
"summary": "Preview Dream scope",
|
||||
"description": "A no-write preview of the scope Dream synthesis would analyze for the project (a capped sample plus the count of users with enough memories to benefit). Never runs the LLM and never mutates anything.",
|
||||
"operationId": "dream_preview",
|
||||
"parameters": [
|
||||
{
|
||||
"name": "org_id",
|
||||
"in": "path",
|
||||
"required": true,
|
||||
"description": "Unique identifier of the organization.",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "project_id",
|
||||
"in": "path",
|
||||
"required": true,
|
||||
"description": "Unique identifier of the project.",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Successful response.",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"active_total": {
|
||||
"type": "integer",
|
||||
"description": "Total active memories in the project."
|
||||
},
|
||||
"scanned": {
|
||||
"type": "integer",
|
||||
"description": "How many recent memories the preview aggregated over (capped)."
|
||||
},
|
||||
"cap": {
|
||||
"type": "integer",
|
||||
"description": "The scan cap applied."
|
||||
},
|
||||
"eligible_users": {
|
||||
"type": "integer",
|
||||
"description": "Users with enough memories to benefit from synthesis."
|
||||
},
|
||||
"note": {
|
||||
"type": "string",
|
||||
"description": "Human-readable note about the preview scope."
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"403": {
|
||||
"description": "Preview not available on the current plan (`upgrade_required: true`)."
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"components": {
|
||||
|
||||
@@ -76,8 +76,18 @@ await client.add(messages, { userId: "alice" })
|
||||
|
||||
```json Output
|
||||
{
|
||||
"event_id": "evt-uuid",
|
||||
"status": "PENDING"
|
||||
"results": [
|
||||
{
|
||||
"memory": "Name is Alice",
|
||||
"event": "ADD",
|
||||
"id": "7ae113a3-3cb5-46e9-b6f7-486c36391847"
|
||||
},
|
||||
{
|
||||
"memory": "Likes large pizza with toppings including cherry tomatoes, black olives, green spinach, yellow bell peppers, diced ham, and sliced mushrooms",
|
||||
"event": "ADD",
|
||||
"id": "56545065-7dee-4acf-8bf2-a5b2535aabb3"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
@@ -82,11 +82,11 @@ client.add(messages, { userId: "user1", timestamp: unixTimestamp })
|
||||
```
|
||||
|
||||
```bash cURL
|
||||
curl -X POST "https://api.mem0.ai/v3/memories/add/" \
|
||||
curl -X POST "https://api.mem0.ai/v1/memories/" \
|
||||
-H "Authorization: Token your-api-key" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"messages": [{"role": "user", "content": "Travelling to SF"}],
|
||||
"messages": [{"role": "user", "content": "I'm travelling to SF"}],
|
||||
"user_id": "user1",
|
||||
"timestamp": 1721577600
|
||||
}'
|
||||
@@ -94,8 +94,13 @@ curl -X POST "https://api.mem0.ai/v3/memories/add/" \
|
||||
|
||||
```json Output
|
||||
{
|
||||
"event_id": "evt-uuid",
|
||||
"status": "PENDING"
|
||||
"results": [
|
||||
{
|
||||
"id": "a1b2c3d4-e5f6-4g7h-8i9j-k0l1m2n3o4p5",
|
||||
"data": {"memory": "Travelling to SF"},
|
||||
"event": "ADD"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
@@ -29,46 +29,6 @@ Filters use a nested JSON structure with logical operators at the root:
|
||||
}
|
||||
```
|
||||
|
||||
A single bare condition needs no wrapper:
|
||||
|
||||
```python
|
||||
# Works: one condition, no wrapper needed
|
||||
filters = {"user_id": "user_123"}
|
||||
```
|
||||
|
||||
Sibling top-level keys in a flat object are accepted too: the API implicitly ANDs them, so the flat form and the explicit `AND` form are equivalent:
|
||||
|
||||
```python
|
||||
# Works: sibling keys are implicitly ANDed
|
||||
filters = {
|
||||
"user_id": "user_123",
|
||||
"categories": {"in": ["finance"]}
|
||||
}
|
||||
|
||||
# Equivalent, explicit form
|
||||
filters = {
|
||||
"AND": [
|
||||
{"user_id": "user_123"},
|
||||
{"categories": {"in": ["finance"]}}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
Reach for an explicit `AND`, `OR`, or `NOT` wrapper when you need `OR` or `NOT` semantics, or when you need to nest conditions. What the API does reject is an unrecognized top-level key:
|
||||
|
||||
```python
|
||||
# Rejected: unknown top-level key
|
||||
filters = {"user_id": "user_123", "bogus_key": "z"}
|
||||
# 400: Top-level key must be a logical operator or an allowed field:
|
||||
# ['AND', 'OR', 'NOT', 'user_id', 'agent_id', 'app_id', 'run_id',
|
||||
# 'created_at', 'updated_at', 'timestamp', 'expiration_date', 'text',
|
||||
# 'categories', 'metadata', 'keywords_search', 'memory_ids', 'keywords']
|
||||
```
|
||||
|
||||
<Callout type="info" icon="cloud" color="#00A8FF">
|
||||
Both the hosted Platform API and the self-hosted OSS SDK implicitly AND sibling top-level keys, so the flat and explicit `AND` forms behave the same way on either. The real differences: Platform validates each top-level key against a fixed allow-list and returns a 400 for anything else, and Platform has no `nin` operator. See [Enhanced Metadata Filtering](/open-source/features/metadata-filtering) for the OSS grammar.
|
||||
</Callout>
|
||||
|
||||
## Available fields and operators
|
||||
|
||||
### Entity fields
|
||||
@@ -82,15 +42,14 @@ Both the hosted Platform API and the self-hosted OSS SDK implicitly AND sibling
|
||||
### Time fields
|
||||
| Field | Operators | Example |
|
||||
|-------|-----------|---------|
|
||||
| `created_at` | `gt`, `gte`, `lt`, `lte`, `ne`, `in`. Explicit `eq` is rejected, pass a bare value instead | `{"created_at": {"gte": "2024-01-01"}}` |
|
||||
| `updated_at` | `gt`, `gte`, `lt`, `lte`, `ne`, `in`. Explicit `eq` is rejected, pass a bare value instead | `{"updated_at": {"lt": "2024-12-31"}}` |
|
||||
| `timestamp` | `gt`, `gte`, `lt`, `lte`, `ne`, `in`. Explicit `eq` is rejected, pass a bare value instead | `{"timestamp": {"gt": "2024-01-01"}}` |
|
||||
| `expiration_date` | `gt`, `gte`, `lt`, `lte`, `ne`, `in`. Explicit `eq` is rejected, pass a bare value instead | `{"expiration_date": {"lte": "2026-12-31"}}` |
|
||||
| `created_at` | `gt`, `gte`, `lt`, `lte`, `eq`, `ne` | `{"created_at": {"gte": "2024-01-01"}}` |
|
||||
| `updated_at` | `gt`, `gte`, `lt`, `lte`, `eq`, `ne` | `{"updated_at": {"lt": "2024-12-31"}}` |
|
||||
| `timestamp` | `gt`, `gte`, `lt`, `lte`, `eq`, `ne` | `{"timestamp": {"gt": "2024-01-01"}}` |
|
||||
|
||||
### Content fields
|
||||
| Field | Operators | Example |
|
||||
|-------|-----------|---------|
|
||||
| `categories` | `in` (takes a list, matches any category in it), `contains` (case-insensitive). `eq` and `ne` are rejected | `{"categories": {"in": ["finance"]}}` |
|
||||
| `categories` | `eq`, `ne`, `in` (matches any category in the list), `contains` (case-insensitive) | `{"categories": {"in": ["finance"]}}` |
|
||||
| `metadata` | `eq`, `ne`, `contains` | `{"metadata": {"key": "value"}}` |
|
||||
| `keywords` | `contains` (case-sensitive), `icontains` (case-insensitive) | `{"keywords": {"icontains": "invoice"}}` |
|
||||
|
||||
@@ -107,14 +66,6 @@ The `*` wildcard matches any non-null value. Records with null values for that f
|
||||
Use operator keywords exactly as shown (`eq`, `ne`, `gte`, etc.). SQL-style symbols such as `>=` or `!=` are rejected by the Platform API.
|
||||
</Callout>
|
||||
|
||||
<Callout type="warning" icon="exclamation-triangle" color="#E74C3C">
|
||||
There is no `nin` ("not in") operator on Platform. It is an OSS-only operator; see [Enhanced Metadata Filtering](/open-source/features/metadata-filtering). To exclude a set of values on Platform, wrap an `in` clause in `NOT`:
|
||||
|
||||
```python
|
||||
{"NOT": {"categories": {"in": ["spam", "test"]}}}
|
||||
```
|
||||
</Callout>
|
||||
|
||||
## Common filter patterns
|
||||
|
||||
Use these ready-made filters to target typical retrieval scenarios without rebuilding logic from scratch.
|
||||
@@ -377,7 +328,7 @@ Level up foundational patterns with compound filters that coordinate entity scop
|
||||
## Best practices
|
||||
|
||||
<Callout type="tip" icon="lightbulb" color="#26A17B">
|
||||
The root does not have to be `AND`, `OR`, or `NOT`. A bare filter like `{"user_id": "alice"}` works on its own, and several top-level keys in one flat filter are implicitly ANDed. Wrap conditions in a logical operator when you need OR/NOT semantics or nested grouping.
|
||||
The root does not have to be `AND`, `OR`, or `NOT`. A bare filter like `{"user_id": "alice"}` works on its own; wrap conditions in a logical operator only when you need to combine more than one.
|
||||
</Callout>
|
||||
|
||||
<Callout type="tip" icon="lightbulb" color="#26A17B">
|
||||
@@ -441,7 +392,7 @@ A filter object with both an `AND` key and a sibling `OR` key at the same level
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="Do I need AND/OR/NOT?">
|
||||
No. A bare filter like `{"user_id": "u1"}` works on its own, and several top-level keys in one flat filter like `{"user_id": "u1", "agent_id": "a1"}` are implicitly ANDed. Reach for `AND`, `OR`, or `NOT` when you need OR/NOT semantics or nested grouping, not merely to combine conditions.
|
||||
No. A bare filter like `{"user_id": "u1"}` works on its own. Add `AND`, `OR`, or `NOT` only when you need to combine more than one condition.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="What does * match?">
|
||||
@@ -470,8 +421,8 @@ A filter object with both an `AND` key and a sibling `OR` key at the same level
|
||||
"AND": [
|
||||
{"user_id": "user_123"},
|
||||
{"OR": [
|
||||
{"categories": {"in": ["finance"]}},
|
||||
{"categories": {"in": ["health"]}}
|
||||
{"categories": "finance"},
|
||||
{"categories": "health"}
|
||||
]}
|
||||
]
|
||||
}
|
||||
|
||||
+19
-12
@@ -28,15 +28,11 @@ npx mcp-add \
|
||||
--name mem0-mcp \
|
||||
--type http \
|
||||
--url "https://mcp.mem0.ai/mcp" \
|
||||
--clients "claude code,cursor,windsurf,vscode,opencode"
|
||||
--clients "claude,claude code,cursor,windsurf,vscode,opencode"
|
||||
```
|
||||
|
||||
`mcp-add` is a helper that writes the Mem0 server into each client's own MCP config file, so you do not have to edit them by hand. Name only the clients you actually use. If you would rather see the change yourself, every client's manual config is under [Client-specific setup](#client-specific-setup).
|
||||
|
||||
<Note>
|
||||
Claude Desktop is not in the list above: it rejects the `mcp-add` command. Add it through Settings instead, see [Claude Desktop](#client-specific-setup) below.
|
||||
</Note>
|
||||
|
||||
Restart each client afterwards so it picks up the new server.
|
||||
|
||||
## Signing in
|
||||
@@ -85,14 +81,25 @@ You can also configure individual clients:
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="Claude Desktop">
|
||||
Claude Desktop does not support the `mcp-add` command, it rejects the server as "not a valid MCP server." Add the Mem0 server through the Settings UI instead:
|
||||
```bash
|
||||
npx mcp-add \
|
||||
--name mem0-mcp \
|
||||
--type http \
|
||||
--url "https://mcp.mem0.ai/mcp" \
|
||||
--clients "claude"
|
||||
```
|
||||
|
||||
1. Open Claude Desktop and go to **Settings > Connectors**.
|
||||
2. Click **Add custom connector**.
|
||||
3. Enter a name (for example `mem0-mcp`) and the URL `https://mcp.mem0.ai/mcp`.
|
||||
4. Save, then restart Claude Desktop.
|
||||
|
||||
The first time you use a Mem0 tool, Claude Desktop opens a browser window to sign in, see [Signing in](#signing-in).
|
||||
Or manually add to your Claude Desktop configuration (`claude_desktop_config.json`):
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"mem0-mcp": {
|
||||
"type": "http",
|
||||
"url": "https://mcp.mem0.ai/mcp"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Claude Code">
|
||||
|
||||
@@ -6,7 +6,7 @@ icon: "code-compare"
|
||||
|
||||
## Which Mem0 is right for you?
|
||||
|
||||
Mem0 offers two ways to add memory to your AI applications. Both run the same core extraction and retrieval logic; the Platform adds hosting, a small set of v3-only capabilities, and management surfaces that OSS does not have.
|
||||
Mem0 offers two powerful ways to add memory to your AI applications. Choose based on your priorities:
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card
|
||||
@@ -16,7 +16,7 @@ Mem0 offers two ways to add memory to your AI applications. Both run the same co
|
||||
>
|
||||
**Managed, hassle-free**
|
||||
|
||||
Get started in 5 minutes with our hosted solution. No vector store, LLM, or embedder to configure.
|
||||
Get started in 5 minutes with our hosted solution. Perfect for fast iteration and production apps.
|
||||
</Card>
|
||||
|
||||
<Card
|
||||
@@ -32,85 +32,89 @@ Mem0 offers two ways to add memory to your AI applications. Both run the same co
|
||||
|
||||
---
|
||||
|
||||
## What's the same
|
||||
|
||||
The core memory loop is identical on both: `add`, `search`, `get`, `get_all`, `update`, `delete`, `delete_all`, and per-memory `history` all exist on the self-hosted `Memory`/`AsyncMemory` classes and on the hosted `MemoryClient`/`AsyncMemoryClient`. Both support:
|
||||
|
||||
- **Entity scoping** by `user_id`, `agent_id`, and `run_id`
|
||||
- **Filter grouping**: both accept `AND`/`OR`/`NOT` wrappers, both implicitly AND a flat multi-key filter like `{"user_id": "alice", "agent_id": "a1"}`, and both accept `*` as a wildcard value. Which fields you may filter on, and which operators each field accepts, differ (see below)
|
||||
- **Entity-aware ranking**: both extract entities from memory text and use shared entities to boost related results at search time
|
||||
- **Multimodal input**, **memory expiration** (`expiration_date`), **reranking**, **procedural memory** (Python), and **custom extraction instructions** (`custom_instructions`)
|
||||
- Python and JavaScript SDKs, plus a REST API (self-hosted via `server/`, or hosted)
|
||||
|
||||
## What's actually different
|
||||
## Feature Comparison
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="Hosting & infrastructure" icon="server">
|
||||
<Accordion title="Setup & Getting Started" icon="rocket">
|
||||
| Feature | Platform | Open Source |
|
||||
|---------|----------|-------------|
|
||||
| **Vector store, LLM, embedder** | Run and tuned by Mem0 | You provision, configure, and pay for each |
|
||||
| **Scaling & availability** | Managed | Your responsibility |
|
||||
| **Web dashboard** | `app.mem0.ai` | Not included |
|
||||
| **Time to first memory** | Minutes (API key only) | Depends on your vector DB / LLM setup |
|
||||
| **Time to first memory** | 5 minutes | 15-30 minutes |
|
||||
| **Infrastructure needed** | None | Vector DB + Python/Node env |
|
||||
| **API key setup** | One environment variable | Configure LLM + embedder + vector DB |
|
||||
| **Maintenance** | Fully managed by Mem0 | Self-managed |
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Entity scoping & workspace structure" icon="layer-group">
|
||||
<Accordion title="Core Memory Features" icon="brain">
|
||||
| Feature | Platform | Open Source |
|
||||
|---------|----------|-------------|
|
||||
| **Scoping identifiers** | `user_id`, `agent_id`, `run_id`, plus `app_id` for app/tenant separation | `user_id`, `agent_id`, `run_id` only, no `app_id` |
|
||||
| **Organizations & projects** | Multi-org, multi-project, with member roles ([API reference](/api-reference/organization/get-org)) | No org/project concept; a single local config |
|
||||
| **Project-wide event feed** | `GET /v1/events/` lists recent add/search/delete events per org and project, usable for dashboards, alerting, or audit trails | Only per-memory `history(memory_id)`, no project-wide event log |
|
||||
|
||||
See [Entity-Scoped Memory](/platform/features/entity-scoped-memory) for the full `app_id` model.
|
||||
| **User & agent memories** | ✅ | ✅ |
|
||||
| **Smart deduplication** | ✅ | ✅ |
|
||||
| **Semantic search** | ✅ | ✅ |
|
||||
| **Memory updates** | ✅ | ✅ |
|
||||
| **Multi-language SDKs** | Python, JavaScript | Python, JavaScript |
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Search-time ranking (v3-only)" icon="sparkles">
|
||||
<Accordion title="Advanced Capabilities" icon="sparkles">
|
||||
| Feature | Platform | Open Source |
|
||||
|---------|----------|-------------|
|
||||
| **Graph Memory** | Native, always-on graph over extracted entities; connections feed directly into the ranking `score` ([details](/platform/features/graph-memory)) | Removed. OSS previously connected external graph stores (Neo4j, Memgraph, Kuzu, Apache AGE); that integration was dropped when the v3 pipeline landed. OSS still extracts entities and uses them to boost ranking, but there is no queryable graph and no `relations` field |
|
||||
| **Memory Decay** | Opt-in per project; reinforces recently-used memories and gently dampens stale ones at search time ([details](/platform/features/memory-decay)) | Not supported. Passing `decay` raises `"The decay parameter is not supported by the OSS Memory SDK."` |
|
||||
| **Temporal Reasoning** | Boosts memories whose event dates match the time expressed in a query (`timestamp` / `reference_date`) ([details](/platform/features/temporal-reasoning)) | Not supported. Both parameters raise a "not supported by the OSS Memory SDK" error |
|
||||
| **Dream (background consolidation)** | Continuously synthesizes patterns, supersedes outdated facts, and merges duplicates per user ([details](/platform/features/dream)) | Not available |
|
||||
| **Multimodal support** | ✅ | ✅ |
|
||||
| **Custom categories** | ✅ | Limited |
|
||||
| **Advanced retrieval** | ✅ | ✅ |
|
||||
| **Temporal reasoning** | ✅ (v3) | ❌ |
|
||||
| **Memory decay** | ✅ (v3) | ❌ |
|
||||
| **Graph memory** | ✅ Built-in | ✅ External graph store |
|
||||
| **Memory filters v2** | ✅ | ⚠️ (via metadata) |
|
||||
| **Webhooks** | ✅ | ❌ |
|
||||
| **Memory export** | ✅ | ❌ |
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Configuration & data operations" icon="sliders">
|
||||
<Accordion title="Infrastructure & Scaling" icon="server">
|
||||
| Feature | Platform | Open Source |
|
||||
|---------|----------|-------------|
|
||||
| **Custom categories** | Set per project or per `add` call ([details](/platform/features/custom-categories)) | Not supported. `Memory.add()` has no `custom_categories` parameter, and OSS project updates are rejected outright |
|
||||
| **Webhooks** | Project-scoped HTTP callbacks on memory and ingest events ([details](/platform/features/webhooks)) | Not available |
|
||||
| **Memory Export** | Schema-driven structured export jobs over filtered memories ([details](/platform/features/memory-export)) | Not available |
|
||||
| **Batch operations** | `batch_update` and `batch_delete` apply up to 1000 memories per call | Not available. Loop over the single-memory `update`/`delete` calls |
|
||||
| **Feedback** | `feedback(memory_id, ...)` records `POSITIVE`, `NEGATIVE`, or `VERY_NEGATIVE` signals against a retrieved memory ([details](/platform/features/feedback-mechanism)) | Not available |
|
||||
| **Summaries** | `get_summary(filters)` returns a generated summary over the matching memories | Not available |
|
||||
| **Filterable fields** | Top-level filter keys come from a fixed allowlist: `user_id`, `agent_id`, `app_id`, `run_id`, `created_at`, `updated_at`, `timestamp`, `expiration_date`, `categories`, `metadata`, `keywords`, `memory_ids`, plus the `AND`/`OR`/`NOT` operators and a few endpoint-specific extras. Any other key is rejected with a `400` ([details](/platform/features/v2-memory-filters)) | Any metadata key is filterable directly, with no allowlist |
|
||||
| **Comparison operators** | Depends on the field: `metadata` accepts `eq`, `ne`, `contains`; `categories` accepts `contains`, `in`; the date fields accept the range operators | The filter layer accepts the full set on any key: `eq`, `ne`, `gt`, `gte`, `lt`, `lte`, `in`, `nin`, `contains`, `icontains`. What actually runs depends on the vector store you configured, so confirm operator coverage for yours ([details](/open-source/features/metadata-filtering)) |
|
||||
| **Hosting** | Managed by Mem0 | Self-hosted |
|
||||
| **Auto-scaling** | ✅ | Manual |
|
||||
| **High availability** | ✅ Built-in | DIY setup |
|
||||
| **Vector DB choice** | Managed | 20+ stores: Qdrant, Pinecone, Chroma, Weaviate, Milvus, pgvector |
|
||||
| **LLM choice** | Managed (optimized) | 15+ providers: OpenAI, Anthropic, Gemini, Groq, Ollama, Together |
|
||||
| **Data residency** | US (expandable) | Your choice |
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Support" icon="life-ring">
|
||||
| Channel | Platform | Open Source |
|
||||
|---------|----------|-------------|
|
||||
| **Community & maintainers** | Discord, GitHub Discussions, direct calls with the founders | Same: Discord, GitHub Discussions, direct calls with the founders |
|
||||
<Accordion title="Pricing & Cost" icon="dollar-sign">
|
||||
| Aspect | Platform | Open Source |
|
||||
|--------|----------|-------------|
|
||||
| **License** | Usage-based pricing | Apache 2.0 (free) |
|
||||
| **Infrastructure costs** | Included in pricing | You pay for VectorDB + LLM + hosting |
|
||||
| **Support** | Included | Community + GitHub |
|
||||
| **Best for** | Fast iteration, production apps | Cost-sensitive, custom requirements |
|
||||
</Accordion>
|
||||
|
||||
Support channels are currently the same for both. If you need something contractual (a support SLA, for example), ask before assuming it exists: it is not documented as a Platform benefit today.
|
||||
<Accordion title="Development & Integration" icon="code">
|
||||
| Feature | Platform | Open Source |
|
||||
|---------|----------|-------------|
|
||||
| **REST API** | ✅ | ✅ (self-hosted server) |
|
||||
| **Python SDK** | ✅ | ✅ |
|
||||
| **JavaScript SDK** | ✅ | ✅ |
|
||||
| **Framework integrations** | LangChain, CrewAI, LlamaIndex, and 20+ more | Same |
|
||||
| **Dashboard** | ✅ Web-based | ❌ |
|
||||
| **Analytics** | ✅ Built-in | DIY |
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
User Profiles are not listed above. The feature is still being finalized internally, so this page does not present it as an available Platform benefit.
|
||||
|
||||
---
|
||||
|
||||
## Decision Guide
|
||||
|
||||
**Choose Platform if you want:**
|
||||
- Zero infrastructure: no vector store, LLM, or embedder to provision or tune.
|
||||
- The v3-only ranking features: Graph Memory, Memory Decay, Temporal Reasoning, and Dream.
|
||||
- App-level and org/project-level scoping, plus webhooks, memory export, and custom categories.
|
||||
- Fast time to market: get your AI app with memory live in hours, not weeks.
|
||||
- Production-ready hosting: auto-scaling, high availability, and managed infrastructure.
|
||||
- Built-in analytics: track memory usage, query patterns, and user engagement through the dashboard.
|
||||
- Advanced features: webhooks, memory export, custom categories, and priority support.
|
||||
|
||||
**Choose Open Source if you need:**
|
||||
- Full data control: host everything on your own infrastructure.
|
||||
- Custom configuration: your own vector DB, LLM provider, and embedder ([25 vector stores](/components/vectordbs/overview), [18 LLM providers](/components/llms/overview), [11 embedders](/components/embedders/overview) at the time of writing).
|
||||
- Extensibility: modify the codebase, add custom providers, and contribute back.
|
||||
- Cost optimization: local LLMs (Ollama), self-hosted vector DBs, no usage-based billing.
|
||||
- Full data control: host everything on your infrastructure with complete data residency.
|
||||
- Custom configuration: choose your own vector DB, LLM provider, embedder, and deployment strategy.
|
||||
- Extensibility: modify the codebase, add custom features, and contribute back to the community.
|
||||
- Cost optimization: use local LLMs (Ollama), self-hosted vector DBs, and optimize for your use case.
|
||||
|
||||
---
|
||||
|
||||
|
||||
Vendored
+3
-2
@@ -25,7 +25,7 @@ Cookbooks are narrative tutorials. They start with a real problem, show the brok
|
||||
## ✅ COPY THIS: Content Skeleton
|
||||
Paste the block below into a new cookbook, then replace all placeholders. Remove any section you don't need **only after** the happy path works.
|
||||
|
||||
````mdx
|
||||
```mdx
|
||||
---
|
||||
title: [Cookbook title: action oriented]
|
||||
description: [1 sentence outcome]
|
||||
@@ -175,7 +175,7 @@ Call out the most common mistake or edge case for this layer.
|
||||
href="#next-link"
|
||||
/>
|
||||
</CardGroup>
|
||||
````
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
@@ -189,6 +189,7 @@ Call out the most common mistake or edge case for this layer.
|
||||
- [ ] Linked related docs (cookbooks, guides, reference) in Next Steps.
|
||||
|
||||
Stick to the skeleton above. If you need to deviate, document the rationale in the PR so we can update the template for everyone else.
|
||||
```
|
||||
|
||||
## Browse Other Templates
|
||||
|
||||
|
||||
@@ -6,16 +6,13 @@ Agent and editor integrations. Each subdirectory is self-contained: its own `pac
|
||||
|-----------|---------|-------|------|------|
|
||||
| `vercel-ai-sdk/` | `@mem0/vercel-ai-provider` | tsup (CJS+ESM) | ESLint + Prettier | jest + vitest (edge/node) |
|
||||
| `openclaw/` | `@mem0/openclaw-mem0` | tsup (ESM) | none | vitest |
|
||||
| `claude-code-plugin/` | Claude Code plugin, installs as `mem0@mem0-plugins` (v0.3.0) | none | ruff | pytest |
|
||||
| `mem0-plugin/` | Cursor / Codex / Kimi / Antigravity / OpenCode plugin (legacy — Claude Code moved to `claude-code-plugin/`) | none | none | pytest |
|
||||
| `mem0-plugin/` | Claude Code / Cursor / Codex plugin | none | none | pytest |
|
||||
| `mem0-plugin/.opencode-plugin/` | `@mem0/opencode-plugin` | Bun | none | tsc type-check |
|
||||
| `pi-agent-plugin/` | `@mem0/pi-agent-plugin` | tsup | none | vitest |
|
||||
| `deepseek-plugin/` | `@mem0/deepseek-plugin` | tsup (ESM) | none | vitest |
|
||||
| `n8n-nodes-mem0/` | `@mem0/n8n-nodes-mem0` | tsc | ESLint (n8n-nodes-base) | none |
|
||||
| `zapier-mem0/` | `@mem0/zapier` | tsc | none | offline unit tests + `zapier validate` |
|
||||
| `mem0-strands/` | `mem0-strands` (PyPI) | hatch | Ruff + mypy | pytest |
|
||||
|
||||
pnpm everywhere except `.opencode-plugin/` (Bun) and `mem0-strands/` (Python: pip / hatch). Never npm, never yarn.
|
||||
pnpm everywhere except `.opencode-plugin/`, which uses Bun. Never npm, never yarn.
|
||||
|
||||
## Commands
|
||||
|
||||
@@ -41,12 +38,10 @@ Run the type check after every TypeScript change: `pnpm run typecheck` or `tsc -
|
||||
## What each one is
|
||||
|
||||
- **`vercel-ai-sdk/`** wraps the Vercel AI SDK through a `createMem0` provider. Integrations for AI-SDK repos go through this wrapper, not raw `MemoryClient`.
|
||||
- **`claude-code-plugin/`** is the Claude Code plugin (v0.3.0, installs as `mem0@mem0-plugins`): local evidence capture via lifecycle hooks, background memory extraction to the Mem0 Platform, a local `search_memories` MCP tool, six `/mem0:*` skills, and the `mem0:sidekick` agent. Pure-stdlib Python — no dependencies to install. Its `core/` + `adapters/claude/` split marks engine vs. harness glue; future per-harness plugins start by copying `core/` and keeping the contract tests verbatim (see its `docs/CONTRACT.md`).
|
||||
- **`mem0-plugin/`** connects Cursor, Codex, Kimi, Antigravity, and OpenCode to the MCP server at `mcp.mem0.ai` and installs lifecycle hooks for automatic memory capture. Exposes 9 MCP tools: `add_memory`, `search_memories`, `get_memories`, `get_memory`, `update_memory`, `delete_memory`, `delete_all_memories`, `delete_entities`, `list_entities`. The Claude Code plugin moved to [`claude-code-plugin/`](claude-code-plugin/) in v0.3.0 (installs as `mem0@mem0-plugins`); do not run both at the same time.
|
||||
- **`openclaw/`**, **`pi-agent-plugin/`**, **`deepseek-plugin/`** are editor and agent plugins with the same shape. `deepseek-plugin/` registers Mem0 search/add tools as a native DeepSeek Harness (Cordis) plugin.
|
||||
- **`mem0-plugin/`** connects Claude Code, Cursor, and Codex to the MCP server at `mcp.mem0.ai` and installs lifecycle hooks for automatic memory capture. Exposes 9 MCP tools: `add_memory`, `search_memories`, `get_memories`, `get_memory`, `update_memory`, `delete_memory`, `delete_all_memories`, `delete_entities`, `list_entities`.
|
||||
- **`openclaw/`**, **`pi-agent-plugin/`** are editor and agent plugins with the same shape.
|
||||
- **`n8n-nodes-mem0/`** is an n8n community node: add, search, get, update, delete.
|
||||
- **`zapier-mem0/`** is a Zapier Platform CLI app: add, search, get, delete. It deploys to Zapier, not npm, so it is **not** in the release router. Deploy it with `gh workflow run zapier-mem0-cd.yml --ref main` (needs the `ZAPIER_DEPLOY_KEY` secret).
|
||||
- **`mem0-strands/`** is a native Strands `MemoryStore` (Python, published to PyPI as `mem0-strands`). It plugs into the Strands `MemoryManager` for automatic recall and server-side extraction, over the hosted Mem0 platform or self-hosted Mem0 OSS. The package lives under `mem0-strands/python/`.
|
||||
|
||||
## Adding an integration
|
||||
|
||||
|
||||
@@ -1,52 +0,0 @@
|
||||
{
|
||||
"name": "mem0",
|
||||
"version": "0.3.0",
|
||||
"description": "Cross-session memory and token savings for coding agents.",
|
||||
"author": {
|
||||
"name": "Mem0"
|
||||
},
|
||||
"homepage": "https://docs.mem0.ai/integrations/claude-code",
|
||||
"repository": "https://github.com/mem0ai/mem0",
|
||||
"license": "Apache-2.0",
|
||||
"keywords": ["memory", "coding-agents", "continual-learning", "token-efficiency"],
|
||||
"userConfig": {
|
||||
"api_key": {
|
||||
"type": "string",
|
||||
"title": "Mem0 API Key",
|
||||
"description": "Mem0 Platform API key used to create and search memories.",
|
||||
"sensitive": true,
|
||||
"required": true
|
||||
},
|
||||
"user_id": {
|
||||
"type": "string",
|
||||
"title": "Memory user ID",
|
||||
"description": "Optional stable ID shared across machines. When omitted, Mem0 uses your local account name, matching the earlier Mem0 Claude Code plugin.",
|
||||
"required": false
|
||||
},
|
||||
"top_k": {
|
||||
"type": "number",
|
||||
"title": "Manual search results",
|
||||
"description": "Maximum number of memories returned when Claude runs another search after the automatic first search.",
|
||||
"default": 3,
|
||||
"min": 1,
|
||||
"max": 20,
|
||||
"required": false
|
||||
},
|
||||
"max_context_chars": {
|
||||
"type": "number",
|
||||
"title": "Maximum retrieved context",
|
||||
"description": "Maximum number of memory characters returned for one search.",
|
||||
"default": 4000,
|
||||
"min": 1000,
|
||||
"max": 10000,
|
||||
"required": false
|
||||
},
|
||||
"search_scope": {
|
||||
"type": "string",
|
||||
"title": "Default search scope",
|
||||
"description": "How wide every search runs by default. 'repo' is the whole repository's shared memory plus your own preferences, 'dir' narrows the shared memory to the directory you are working in, and 'mine' is your preferences alone.",
|
||||
"default": "repo",
|
||||
"required": false
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
.pytest_cache/
|
||||
.ruff_cache/
|
||||
.venv/
|
||||
*.sqlite3
|
||||
*.sqlite3-shm
|
||||
*.sqlite3-wal
|
||||
flush-worker.log
|
||||
plugin-errors.log
|
||||
pending/
|
||||
@@ -1,11 +0,0 @@
|
||||
{
|
||||
"mcpServers": {
|
||||
"mem0": {
|
||||
"command": "python3",
|
||||
"args": ["${CLAUDE_PLUGIN_ROOT}/core/mcp_server.py"],
|
||||
"env": {
|
||||
"MEM0_CODE_DATA_DIR": "${CLAUDE_PLUGIN_DATA}"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,190 +0,0 @@
|
||||
# Mem0 for Claude Code
|
||||
|
||||
Persistent cross-session memory for Claude Code, plus a Sonnet sidekick agent for delegated work.
|
||||
|
||||
Claude Code forgets everything between sessions. This plugin fixes that: hooks capture session details locally, a background worker turns them into Mem0 memories, and Claude automatically gets the relevant ones back at the start of later sessions.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Python 3.10+ and Git.
|
||||
- A Claude Code version that supports plugin agents, worktree isolation for agents, and the `SubagentStart`, `SubagentStop`, and `PostToolUseFailure` hook events.
|
||||
- A [Mem0 Platform API key](https://app.mem0.ai/dashboard/api-keys) (starts with `m0-`).
|
||||
|
||||
## Install
|
||||
|
||||
```bash
|
||||
export MEM0_API_KEY='your-mem0-api-key'
|
||||
claude plugin marketplace add mem0ai/mem0
|
||||
claude plugin install mem0@mem0-plugins --scope user --config api_key="$MEM0_API_KEY"
|
||||
unset MEM0_API_KEY
|
||||
```
|
||||
|
||||
Restart Claude Code (or run `/reload-plugins`), then open a Git repository and work normally.
|
||||
|
||||
To update:
|
||||
|
||||
```bash
|
||||
claude plugin marketplace update mem0-plugins
|
||||
claude plugin update mem0@mem0-plugins --scope user
|
||||
```
|
||||
|
||||
To remove:
|
||||
|
||||
```bash
|
||||
claude plugin uninstall mem0@mem0-plugins
|
||||
```
|
||||
|
||||
For local development, load the current checkout directly:
|
||||
|
||||
```bash
|
||||
claude --plugin-dir .
|
||||
```
|
||||
|
||||
## How it works
|
||||
|
||||
### Memory
|
||||
|
||||
1. **Capture.** Hooks save the main agent's activity locally: user messages, Claude's answers, changed file paths, and short test/build results. No model calls, no blocking. Sidekick output is excluded.
|
||||
|
||||
2. **Flush.** After every five completed exchanges, a detached background worker sends that batch to Mem0. Large exchanges flush sooner. Ending or compacting the session flushes anything remaining. If idle, an auto-flush runs after five minutes (configurable with `MEM0_CODE_IDLE_FLUSH_SECONDS`). The worker survives Claude Code exiting.
|
||||
|
||||
3. **Extract.** Each flush sends a single `add` call with `agent_id` (the project identity), `user_id` (you), `app_id` (the repository), and `run_id` (the session). Mem0 classifies each extracted memory as either:
|
||||
- **Shared project memory** (`agent_id`): one namespace per repo, scoped by `app_id`. Stores conventions, decisions, constraints, working commands, and failed commands with their fixes. Everyone on the repo reads and writes the same pool. Never carries a `user_id`. Directory information is stored in metadata for directory-scoped searches.
|
||||
- **Personal memory** (`user_id`): your preferred tools, style, habits, and anything you asked to be remembered. Scoped to the repo by `app_id`. Private to you.
|
||||
|
||||
4. **Recall.** On the next session's first prompt, the plugin searches automatically and supplies up to five relevant memories. No model is called to write the query.
|
||||
|
||||
After that first search, Claude can call `search_memories` with a specific question, and you can run `/mem0:search` yourself. Explicit searches return up to 3 results by default (configurable to 20), capped at 4,000 characters.
|
||||
|
||||
### Sonnet sidekick agent
|
||||
|
||||
`mem0:sidekick` is a Sonnet coding agent that runs in a separate Git worktree. It can investigate, implement, test, debug, or review something instead of the main (Opus/Fable) session doing the same work, reducing cost when the main agent doesn't need to repeat it.
|
||||
|
||||
The main agent reviews the result. Corrections go back to the same sidekick so it keeps what it learned. Changes stay in the sidekick's worktree until the main agent reviews and copies them over.
|
||||
|
||||
Mem0 never blocks normal Claude Code work when a hook fails. It does not proxy Claude traffic, rewrite tool output, edit `CLAUDE.md`, force Claude to use the sidekick, or change how Claude implements the user's request.
|
||||
|
||||
## Use
|
||||
|
||||
Work in Claude Code normally. Memory is captured and recalled automatically.
|
||||
|
||||
```text
|
||||
/mem0:search Why does the ODS serializer keep dates timezone-naive?
|
||||
/mem0:search What parser failures were fixed? --top-k 5 --category problems_and_fixes
|
||||
/mem0:search Do I prefer pnpm or npm? --scope mine
|
||||
```
|
||||
|
||||
To use the sidekick:
|
||||
|
||||
```text
|
||||
Ask Mem0's sidekick to investigate and implement this in its separate worktree.
|
||||
Review its result and send any corrections back to the same sidekick.
|
||||
```
|
||||
|
||||
By default the worktree branches from the repo's default branch. Set `worktree.baseRef` to `"head"` in your Claude settings to branch from the current commit instead. Uncommitted changes are not copied into the sidekick's worktree.
|
||||
|
||||
## Commands
|
||||
|
||||
| Command | What it does |
|
||||
| --- | --- |
|
||||
| `/mem0:search` | Search memories from earlier sessions. Accepts `--top-k <n>`, `--category <name>`, and `--scope <repo\|dir\|mine>`. |
|
||||
| `/mem0:status` | Check config, capture state, pending flushes, and API key validity. |
|
||||
| `/mem0:forget` | Delete your memories for this repo (shared project memory stays unless you pass `--include-project-memory`). |
|
||||
| `/mem0:pause` | Pause memory capture. |
|
||||
| `/mem0:resume` | Resume capture after a pause. |
|
||||
| `/mem0:remember` | Tell Claude to capture something specific in its reply. |
|
||||
|
||||
Categories for `--category`: `project_knowledge`, `decisions_and_constraints`, `workflows`, `problems_and_fixes`, `results`.
|
||||
|
||||
## Search scope
|
||||
|
||||
| Scope | What you get |
|
||||
| --- | --- |
|
||||
| `repo` (default) | All project memory across every subdirectory, plus your preferences |
|
||||
| `dir` | Project memory from the current directory (and children), plus your preferences |
|
||||
| `mine` | Your personal preferences only |
|
||||
|
||||
Set the default with the `search_scope` setting or `MEM0_CODE_SEARCH_SCOPE`. Pass `--run-id <session-id>` to see only what one specific session recorded.
|
||||
|
||||
## Settings
|
||||
|
||||
| Setting | Default | What it controls |
|
||||
| --- | --- | --- |
|
||||
| `api_key` | required | Mem0 Platform API key |
|
||||
| `user_id` | local account name | User ID for memory storage. Resolved from: setting, `MEM0_CODE_USER_ID`, `MEM0_USER_ID`, `MEM0_RESOLVED_USER_ID`, `$USER`, `%USERNAME%`, then `default`. Set explicitly to share across machines. |
|
||||
| `top_k` | `3` | Max memories per explicit search (1 to 20) |
|
||||
| `max_context_chars` | `4000` | Max characters returned per search (1,000 to 10,000) |
|
||||
| `search_scope` | `repo` | Default scope: `repo`, `dir`, or `mine` |
|
||||
|
||||
## What is stored and sent
|
||||
|
||||
Local data lives in `${CLAUDE_PLUGIN_DATA}`:
|
||||
|
||||
- `api-key`: the configured Mem0 key (readable only by the local user)
|
||||
- `evidence.sqlite3`: session details and records of memory creation/search
|
||||
- `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
|
||||
|
||||
Mem0 receives each block of user messages, Claude's answers, the sidekick's answer, and changed file paths. Complete files and general tool output stay on your machine. Values that look like credentials are redacted before anything is sent.
|
||||
|
||||
## 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.
|
||||
|
||||
Turn it off:
|
||||
|
||||
```bash
|
||||
export MEM0_TELEMETRY=false
|
||||
```
|
||||
|
||||
## Five-minute memory test
|
||||
|
||||
Run this in a Git repository after installing:
|
||||
|
||||
1. Tell Claude:
|
||||
```text
|
||||
Remember for future work that this repository's acceptance marker is cobalt-orchid-731.
|
||||
```
|
||||
|
||||
2. End the session. Start a new one in the same repo and run:
|
||||
```text
|
||||
/mem0:search What is the acceptance marker?
|
||||
```
|
||||
|
||||
3. Check that the result contains `cobalt-orchid-731`.
|
||||
|
||||
Memory creation runs in the background. If the first search is empty, wait a moment and try again.
|
||||
|
||||
## Upgrading from 0.2.x
|
||||
|
||||
Breaking update. Memories carry over, most local config does not.
|
||||
|
||||
- **Memories carry over.** Same user and repo scoping, including `~/.mem0/project_map.json`.
|
||||
- **Old memories searchable, not by category.** Category filters only work on new memories.
|
||||
- **Commands replaced.** Old commands replaced by `/mem0:search`, `/mem0:status`, `/mem0:forget`, `/mem0:pause`, `/mem0:resume`, `/mem0:remember`.
|
||||
- **MCP server replaced.** Nine read/write tools replaced by the single read-only `search_memories` tool.
|
||||
- **`~/.mem0/settings.json` ignored.** All keys stop applying: `auto_save`, `auto_search`, `search_limit`, `confidence_threshold`, `retention_session_days`, `global_search`, `debug`.
|
||||
- **Per-project `mem0.md` files ignored.**
|
||||
- **Most `MEM0_*` env vars ignored.** Only `MEM0_API_KEY`, `MEM0_USER_ID`, `MEM0_RESOLVED_USER_ID`, and `MEM0_PROJECT_ID` are still read. Run `/mem0:status` to see what is active.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
| Problem | Fix |
|
||||
| --- | --- |
|
||||
| Missing key | Reinstall with `--config api_key="$MEM0_API_KEY"` while the var is set. |
|
||||
| `401 Unauthorized` | API key is invalid or expired. Run `/mem0:status`. |
|
||||
| No memory after ending a session | Extraction runs in the background. Wait a moment, then search again. |
|
||||
| Sidekick won't start | Must be in a Git repo with a Claude Code version supporting plugin agents and worktrees. |
|
||||
| Remove the plugin | `claude plugin uninstall mem0@mem0-plugins` |
|
||||
|
||||
## Development checks
|
||||
|
||||
Run from `integrations/claude-code-plugin/`:
|
||||
|
||||
```bash
|
||||
python3 -m pytest tests -q
|
||||
python3 -m ruff check .
|
||||
claude plugin validate --strict .
|
||||
```
|
||||
@@ -1,369 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Claude Code hooks for Mem0."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "core"))
|
||||
|
||||
import telemetry
|
||||
from memory_core import (
|
||||
EvidenceStore,
|
||||
api_key,
|
||||
cache_plugin_api_key,
|
||||
checkpoint_session,
|
||||
clear_stale_api_key_cache,
|
||||
data_dir,
|
||||
detached_process_kwargs,
|
||||
format_context,
|
||||
record_session_start,
|
||||
record_sidekick_start,
|
||||
record_sidekick_stop,
|
||||
record_stop,
|
||||
record_tool,
|
||||
record_user_prompt,
|
||||
search_memories,
|
||||
)
|
||||
|
||||
|
||||
STALE_RUNNING_SECONDS = 300
|
||||
PENDING_EXPIRY_SECONDS = 7 * 24 * 60 * 60
|
||||
PENDING_LAUNCH_LIMIT = 5
|
||||
|
||||
|
||||
def read_hook_input() -> dict:
|
||||
try:
|
||||
value = json.load(sys.stdin)
|
||||
return value if isinstance(value, dict) else {}
|
||||
except (json.JSONDecodeError, OSError):
|
||||
return {}
|
||||
|
||||
|
||||
def first_prompt_memory_output(store: EvidenceStore, hook_input: dict) -> dict:
|
||||
"""Search once before Claude handles the first prompt in a session."""
|
||||
repo, session_id, prompt, is_first_prompt = record_user_prompt(store, hook_input)
|
||||
if not is_first_prompt:
|
||||
return {}
|
||||
try:
|
||||
minimum_query_chars = int(os.environ.get("MEM0_CODE_MIN_QUERY_CHARS", "20"))
|
||||
except ValueError:
|
||||
minimum_query_chars = 20
|
||||
if len(prompt.strip()) < max(minimum_query_chars, 1):
|
||||
return {}
|
||||
result = search_memories(
|
||||
store,
|
||||
repo,
|
||||
session_id,
|
||||
prompt,
|
||||
top_k=5,
|
||||
operation="first-prompt-search",
|
||||
timeout=2,
|
||||
)
|
||||
if not result.memories:
|
||||
return {}
|
||||
context = format_context(
|
||||
result.memories,
|
||||
"Mem0 found these relevant memories from earlier work in this repository:",
|
||||
)
|
||||
telemetry.record(
|
||||
"context_injected",
|
||||
repo=repo,
|
||||
session_id=session_id,
|
||||
trigger="first-prompt",
|
||||
memory_count=len(result.memories),
|
||||
context_chars=len(context),
|
||||
prompt_chars=len(prompt),
|
||||
)
|
||||
return {
|
||||
"hookSpecificOutput": {
|
||||
"hookEventName": "UserPromptSubmit",
|
||||
"additionalContext": context,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _launch_handoff(handoff_path: Path) -> bool:
|
||||
running_path = handoff_path.with_suffix(".running")
|
||||
try:
|
||||
handoff_path.replace(running_path)
|
||||
except OSError:
|
||||
return False
|
||||
worker = Path(__file__).resolve().parents[2] / "core" / "flush_worker.py"
|
||||
log_path = data_dir() / "flush-worker.log"
|
||||
log_handle = open(log_path, "a", encoding="utf-8")
|
||||
try:
|
||||
subprocess.Popen(
|
||||
[sys.executable, str(worker), str(running_path)],
|
||||
stdin=subprocess.DEVNULL,
|
||||
stdout=log_handle,
|
||||
stderr=log_handle,
|
||||
close_fds=True,
|
||||
**detached_process_kwargs(),
|
||||
)
|
||||
finally:
|
||||
log_handle.close()
|
||||
return True
|
||||
|
||||
|
||||
def recover_pending_handoffs() -> int:
|
||||
pending_dir = data_dir() / "pending"
|
||||
pending_dir.mkdir(parents=True, exist_ok=True)
|
||||
now = time.time()
|
||||
for running in pending_dir.glob("*.running"):
|
||||
try:
|
||||
if now - running.stat().st_mtime > STALE_RUNNING_SECONDS:
|
||||
running.replace(running.with_suffix(".json"))
|
||||
except OSError:
|
||||
continue
|
||||
recoverable = []
|
||||
for handoff in pending_dir.glob("*.json"):
|
||||
try:
|
||||
age = now - handoff.stat().st_mtime
|
||||
except OSError:
|
||||
continue
|
||||
if age > PENDING_EXPIRY_SECONDS:
|
||||
handoff.unlink(missing_ok=True)
|
||||
continue
|
||||
recoverable.append((age, handoff))
|
||||
recoverable.sort(key=lambda item: item[0], reverse=True)
|
||||
launched = 0
|
||||
for _, handoff in recoverable[:PENDING_LAUNCH_LIMIT]:
|
||||
launched += int(_launch_handoff(handoff))
|
||||
return launched
|
||||
|
||||
|
||||
def refresh_pending_handoffs() -> None:
|
||||
"""Hold unsent packets while paused instead of letting them expire."""
|
||||
pending_dir = data_dir() / "pending"
|
||||
if not pending_dir.is_dir():
|
||||
return
|
||||
for pattern in ("*.json", "*.running"):
|
||||
for handoff in pending_dir.glob(pattern):
|
||||
try:
|
||||
os.utime(handoff)
|
||||
except OSError:
|
||||
continue
|
||||
|
||||
|
||||
def hand_off_flush(
|
||||
hook_input: dict, reason: str, *, wait_for_inflight: bool = False
|
||||
) -> None:
|
||||
"""Persist hook input and detach delivery from Claude's shutdown lifecycle."""
|
||||
pending_dir = data_dir() / "pending"
|
||||
pending_dir.mkdir(parents=True, exist_ok=True)
|
||||
material = (
|
||||
f"{hook_input.get('cwd', '')}\0{hook_input.get('session_id', '')}\0{reason}"
|
||||
)
|
||||
digest = hashlib.sha256(material.encode()).hexdigest()[:24]
|
||||
handoff_path = pending_dir / f"{digest}-{uuid.uuid4().hex[:8]}.json"
|
||||
temporary_path = handoff_path.with_suffix(".tmp")
|
||||
temporary_path.write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"hook_input": hook_input,
|
||||
"reason": reason,
|
||||
"wait_for_inflight": wait_for_inflight,
|
||||
}
|
||||
),
|
||||
encoding="utf-8",
|
||||
)
|
||||
temporary_path.replace(handoff_path)
|
||||
_launch_handoff(handoff_path)
|
||||
|
||||
|
||||
def automatic_flush_enabled() -> bool:
|
||||
return os.environ.get("MEM0_CODE_AUTO_FLUSH", "true").lower() in {
|
||||
"1",
|
||||
"true",
|
||||
"yes",
|
||||
"on",
|
||||
}
|
||||
|
||||
|
||||
def schedule_periodic_checkpoint(
|
||||
store: EvidenceStore,
|
||||
hook_input: dict,
|
||||
repo,
|
||||
session_id: str,
|
||||
) -> bool:
|
||||
"""Start one background extraction when a complete block is ready."""
|
||||
if (
|
||||
not automatic_flush_enabled()
|
||||
or not api_key()
|
||||
or not store.checkpoint_due(repo.identity, session_id)
|
||||
):
|
||||
return False
|
||||
if store.prepare_flush(repo, session_id, "periodic") is None:
|
||||
return False
|
||||
hand_off_flush(hook_input, "periodic")
|
||||
return True
|
||||
|
||||
|
||||
DEFAULT_IDLE_FLUSH_SECONDS = 300
|
||||
|
||||
|
||||
def _idle_flush_seconds() -> int:
|
||||
try:
|
||||
return max(
|
||||
int(os.environ.get("MEM0_CODE_IDLE_FLUSH_SECONDS", str(DEFAULT_IDLE_FLUSH_SECONDS))),
|
||||
0,
|
||||
)
|
||||
except ValueError:
|
||||
return DEFAULT_IDLE_FLUSH_SECONDS
|
||||
|
||||
|
||||
def schedule_idle_flush(
|
||||
store: EvidenceStore,
|
||||
hook_input: dict,
|
||||
repo,
|
||||
session_id: str,
|
||||
) -> bool:
|
||||
"""Launch a delayed background flush for sessions that may never end."""
|
||||
delay = _idle_flush_seconds()
|
||||
if delay <= 0 or not automatic_flush_enabled() or not api_key():
|
||||
return False
|
||||
if store.has_inflight_flush(repo.identity, session_id):
|
||||
return False
|
||||
if not store.has_unflushed_events(repo.identity, session_id):
|
||||
return False
|
||||
pending_dir = data_dir() / "pending"
|
||||
pending_dir.mkdir(parents=True, exist_ok=True)
|
||||
material = f"idle\0{hook_input.get('cwd', '')}\0{hook_input.get('session_id', '')}"
|
||||
digest = hashlib.sha256(material.encode()).hexdigest()[:24]
|
||||
for old in pending_dir.glob(f"idle-{digest}*"):
|
||||
old.unlink(missing_ok=True)
|
||||
handoff_path = pending_dir / f"idle-{digest}-{uuid.uuid4().hex[:8]}.json"
|
||||
temporary_path = handoff_path.with_suffix(".tmp")
|
||||
temporary_path.write_text(
|
||||
json.dumps({
|
||||
"hook_input": hook_input,
|
||||
"reason": "idle",
|
||||
"delay_seconds": delay,
|
||||
}),
|
||||
encoding="utf-8",
|
||||
)
|
||||
temporary_path.replace(handoff_path)
|
||||
_launch_handoff(handoff_path)
|
||||
return True
|
||||
|
||||
|
||||
def log_failure(exc: Exception) -> None:
|
||||
try:
|
||||
log_path = data_dir() / "plugin-errors.log"
|
||||
with log_path.open("a", encoding="utf-8") as handle:
|
||||
handle.write(f"{time.time():.3f} {type(exc).__name__}: {exc}\n")
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument(
|
||||
"action",
|
||||
choices=[
|
||||
"session-start",
|
||||
"user-prompt",
|
||||
"post-tool",
|
||||
"post-tool-failure",
|
||||
"sidekick-start",
|
||||
"sidekick-stop",
|
||||
"stop",
|
||||
"flush",
|
||||
],
|
||||
)
|
||||
parser.add_argument("--reason", default="manual")
|
||||
parser.add_argument("--plugin-data-dir", default="")
|
||||
args = parser.parse_args()
|
||||
if args.plugin_data_dir:
|
||||
os.environ["MEM0_CODE_DATA_DIR"] = args.plugin_data_dir
|
||||
cache_plugin_api_key()
|
||||
if args.action == "session-start":
|
||||
clear_stale_api_key_cache()
|
||||
hook_input = read_hook_input()
|
||||
store = EvidenceStore()
|
||||
try:
|
||||
if store.is_paused():
|
||||
if args.action == "session-start":
|
||||
refresh_pending_handoffs()
|
||||
telemetry.record("session_start", paused=True)
|
||||
telemetry.spawn_flush()
|
||||
return 0
|
||||
if args.action == "session-start":
|
||||
if telemetry.is_first_run():
|
||||
telemetry.record("install")
|
||||
recovered = recover_pending_handoffs()
|
||||
record_session_start(store, hook_input)
|
||||
if recovered:
|
||||
telemetry.record("handoff_recovered", count=recovered)
|
||||
telemetry.spawn_flush()
|
||||
elif args.action == "user-prompt":
|
||||
output = first_prompt_memory_output(store, hook_input)
|
||||
if output:
|
||||
print(json.dumps(output))
|
||||
elif args.action == "post-tool":
|
||||
record_tool(store, hook_input)
|
||||
elif args.action == "post-tool-failure":
|
||||
record_tool(store, hook_input, failed=True)
|
||||
elif args.action == "sidekick-start":
|
||||
context = record_sidekick_start(store, hook_input)
|
||||
if context:
|
||||
print(
|
||||
json.dumps(
|
||||
{
|
||||
"hookSpecificOutput": {
|
||||
"hookEventName": "SubagentStart",
|
||||
"additionalContext": context,
|
||||
}
|
||||
}
|
||||
)
|
||||
)
|
||||
elif args.action == "sidekick-stop":
|
||||
record_sidekick_stop(store, hook_input)
|
||||
elif args.action == "stop":
|
||||
repo, session_id = record_stop(store, hook_input)
|
||||
if not schedule_periodic_checkpoint(store, hook_input, repo, session_id):
|
||||
schedule_idle_flush(store, hook_input, repo, session_id)
|
||||
elif args.action == "flush":
|
||||
automatic = args.reason in {"session-end", "pre-compact"}
|
||||
if automatic and not automatic_flush_enabled():
|
||||
return 0
|
||||
if args.reason == "session-end":
|
||||
# In print mode, SessionEnd can arrive before the Stop hook has
|
||||
# recorded Claude's final response. Read any remaining visible
|
||||
# transcript messages before preparing the final extraction.
|
||||
record_stop(store, hook_input)
|
||||
if os.environ.get("MEM0_CODE_SYNC_FLUSH") == "1":
|
||||
print(json.dumps(checkpoint_session(store, hook_input, args.reason)))
|
||||
else:
|
||||
session_id = str(hook_input.get("session_id") or "unknown-session")
|
||||
repo = store.repo_for_session(session_id, hook_input.get("cwd"))
|
||||
already_running = store.has_inflight_flush(repo.identity, session_id)
|
||||
if already_running and args.reason == "session-end":
|
||||
hand_off_flush(
|
||||
hook_input, args.reason, wait_for_inflight=True
|
||||
)
|
||||
elif not already_running and store.prepare_flush(
|
||||
repo, session_id, args.reason
|
||||
) is not None:
|
||||
hand_off_flush(hook_input, args.reason)
|
||||
finally:
|
||||
store.close()
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
raise SystemExit(main())
|
||||
except Exception as exc:
|
||||
# Memory must never prevent the coding agent from continuing.
|
||||
log_failure(exc)
|
||||
raise SystemExit(0)
|
||||
@@ -1,70 +0,0 @@
|
||||
---
|
||||
name: sidekick
|
||||
description: A Sonnet coding agent that works in a separate Git worktree and keeps its own conversation. Use it when it can investigate, implement, test, debug, or review something instead of the main agent doing the same work. This can lower the cost of an Opus or Fable session. Keep quick changes and product or architecture decisions with the main agent. Tell the sidekick exactly what work to do, any constraints, and what you need back. Review its result and send corrections to the same sidekick.
|
||||
model: sonnet
|
||||
effort: medium
|
||||
tools: Read, Grep, Glob, Bash, Edit, Write, WebFetch, WebSearch, Monitor, SendMessage, Skill, mcp__plugin_mem0_mem0__search_memories
|
||||
isolation: worktree
|
||||
color: cyan
|
||||
---
|
||||
|
||||
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.
|
||||
|
||||
Inspect the relevant code and repository rules. Reproduce the problem when that
|
||||
helps. Decide the implementation details, edit files when asked, and test the
|
||||
result. The main agent may give you a whole task or one part of its work. Do the
|
||||
work instead of returning only advice or a plan when you can complete it.
|
||||
|
||||
Complete only the work the main agent assigned. Do not make related improvements just
|
||||
because they seem useful or low-risk; report them separately. Before returning,
|
||||
compare your changes with the request and remove changes that were not requested.
|
||||
|
||||
Keep the work proportional to the requested result. Start with the smallest
|
||||
useful reproduction and the tests closest to the changed code. Add or update
|
||||
tests and documentation when they are needed for the requested behavior, but do
|
||||
not fix unrelated baseline failures or clean up unrelated files. Do not install
|
||||
optional development tools or run repository-wide formatting or linting merely
|
||||
to make the existing checkout clean. If broader validation is standard,
|
||||
available, and relevant, run it once after the focused checks pass. Stop when the
|
||||
requested result is implemented and the decisive validation passes.
|
||||
|
||||
The main agent should tell you what result it needs and any constraints, not
|
||||
dictate exact code. If a
|
||||
material product decision, contradictory requirement, missing repository state,
|
||||
or unsafe ambiguity prevents responsible implementation, use `SendMessage` to
|
||||
ask the main agent one concise question. Otherwise proceed independently. Treat
|
||||
later messages from the main agent as continuations of the same work and retain
|
||||
what you already learned instead of repeating repository exploration.
|
||||
|
||||
Your current working directory is the worktree Claude Code assigned to you. Use
|
||||
it directly. Never `cd` to a parent-checkout path from the request and
|
||||
never edit the parent checkout. If relevant committed or uncommitted parent
|
||||
state is missing, tell the main agent instead of guessing. Before interpreting a test
|
||||
result, confirm that the command resolves source from this worktree rather than
|
||||
an editable install pointing at the parent checkout.
|
||||
|
||||
When you change files, create a small local commit after testing and report its
|
||||
SHA. The main agent will use this commit to review and copy your changes:
|
||||
never push, open a pull request, or modify unrelated work. If the main agent sends
|
||||
corrections, amend the commit or add another small commit and rerun the relevant
|
||||
validation.
|
||||
|
||||
Every final response must state:
|
||||
|
||||
- Outcome: what you found and completed.
|
||||
- Files changed: the repository-relative paths and concise purpose.
|
||||
- Validation: exact commands and outcomes.
|
||||
- Remaining risk: unresolved uncertainty, or `none identified`.
|
||||
- Commit: the local SHA when files changed, otherwise `none`.
|
||||
- Worktree: the path and current branch.
|
||||
|
||||
Keep the report concise enough for the main agent to review one diff without repeating
|
||||
your investigation.
|
||||
@@ -1,88 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Detached remote checkpoint worker.
|
||||
|
||||
Claude Code may cancel SessionEnd hooks as a print-mode process exits. The hook
|
||||
therefore persists its input first and launches this process in a new session.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import telemetry
|
||||
from memory_core import (
|
||||
EvidenceStore,
|
||||
checkpoint_session,
|
||||
record_stop,
|
||||
touch_handoff_heartbeat,
|
||||
)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
if len(sys.argv) != 2:
|
||||
return 2
|
||||
handoff_path = Path(sys.argv[1])
|
||||
os.environ["MEM0_CODE_HANDOFF_PATH"] = str(handoff_path)
|
||||
completed = False
|
||||
try:
|
||||
payload = json.loads(handoff_path.read_text(encoding="utf-8"))
|
||||
delay = float(payload.get("delay_seconds") or 0)
|
||||
if delay > 0:
|
||||
payload.pop("delay_seconds", None)
|
||||
handoff_path.write_text(
|
||||
json.dumps(payload), encoding="utf-8"
|
||||
)
|
||||
time.sleep(delay)
|
||||
if not handoff_path.exists():
|
||||
return 0
|
||||
hook_input = payload.get("hook_input") or {}
|
||||
reason = str(payload.get("reason") or "checkpoint")
|
||||
wait_for_inflight = bool(payload.get("wait_for_inflight"))
|
||||
store = EvidenceStore()
|
||||
try:
|
||||
if wait_for_inflight:
|
||||
session_id = str(
|
||||
hook_input.get("session_id") or "unknown-session"
|
||||
)
|
||||
repo = store.repo_for_session(session_id, hook_input.get("cwd"))
|
||||
deadline = time.monotonic() + float(
|
||||
os.environ.get("MEM0_CODE_EXTRACTION_WAIT_SECONDS", "120")
|
||||
)
|
||||
while (
|
||||
store.has_inflight_flush(repo.identity, session_id)
|
||||
and time.monotonic() < deadline
|
||||
):
|
||||
touch_handoff_heartbeat()
|
||||
time.sleep(0.25)
|
||||
if reason == "session-end":
|
||||
record_stop(store, hook_input)
|
||||
result = checkpoint_session(store, hook_input, reason)
|
||||
print(json.dumps(result, sort_keys=True), flush=True)
|
||||
completed = result.get("status") in {
|
||||
"semantic-succeeded",
|
||||
"explicitly-stored",
|
||||
"nothing-to-flush",
|
||||
}
|
||||
finally:
|
||||
store.close()
|
||||
return 0
|
||||
finally:
|
||||
telemetry.flush()
|
||||
if completed:
|
||||
try:
|
||||
handoff_path.unlink()
|
||||
except OSError:
|
||||
pass
|
||||
elif handoff_path.suffix == ".running":
|
||||
try:
|
||||
handoff_path.replace(handoff_path.with_suffix(".json"))
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -1,230 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Expose Mem0's memory search as one local Claude Code tool."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
from typing import Any
|
||||
|
||||
import telemetry
|
||||
from memory_core import (
|
||||
CODING_MEMORY_CATEGORY_NAMES,
|
||||
format_search_result,
|
||||
resolve_repo,
|
||||
SEARCH_SCOPES,
|
||||
search_memories,
|
||||
)
|
||||
|
||||
|
||||
PROTOCOL_VERSION = "2024-11-05"
|
||||
TOOL_NAME = "search_memories"
|
||||
TOOL_DESCRIPTION = (
|
||||
"Search memories from earlier work in this repository. ALWAYS call this "
|
||||
"tool before answering anything that could depend on prior context: the "
|
||||
"user's preferences, facts about this codebase, history, people, projects, "
|
||||
"or earlier decisions. Do not rely on the chat window alone. The "
|
||||
"repository's memory is shared by everyone who works in it and includes "
|
||||
"what it took to run, test, or build here, so search before assuming an "
|
||||
"invocation works. The scope argument changes what is searched: 'repo' "
|
||||
"(default) is the whole repository's shared memory plus your own "
|
||||
"preferences, 'dir' narrows the shared part to the directory you are "
|
||||
"working in, and 'mine' is your preferences alone. Pass run_id to look "
|
||||
"at one earlier Claude Code session only."
|
||||
)
|
||||
TOOL_SCHEMA = {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"query": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 2000,
|
||||
"description": "A direct question about earlier work in this repository.",
|
||||
},
|
||||
"top_k": {
|
||||
"type": "integer",
|
||||
"minimum": 1,
|
||||
"maximum": 20,
|
||||
"description": "Maximum memories to return. Uses Mem0's configured default when omitted.",
|
||||
},
|
||||
"category": {
|
||||
"type": "string",
|
||||
"enum": list(CODING_MEMORY_CATEGORY_NAMES),
|
||||
"description": "Optional memory category. Omit to search every category.",
|
||||
},
|
||||
"scope": {
|
||||
"type": "string",
|
||||
"enum": list(SEARCH_SCOPES),
|
||||
"description": (
|
||||
"Which memories to search. 'repo' (default) is the whole repository's "
|
||||
"shared memory plus your own preferences, 'dir' narrows the shared "
|
||||
"part to the current directory, 'mine' is your preferences alone."
|
||||
),
|
||||
},
|
||||
"run_id": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 200,
|
||||
"description": "Optional Claude Code session ID. Restricts the search to memories written from that session.",
|
||||
},
|
||||
},
|
||||
"required": ["query"],
|
||||
"additionalProperties": False,
|
||||
}
|
||||
|
||||
|
||||
class ToolInputError(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
def _validate_arguments(
|
||||
arguments: Any,
|
||||
) -> tuple[str, int | None, str | None, str | None, str | None]:
|
||||
if not isinstance(arguments, dict):
|
||||
raise ToolInputError("Search arguments must be an object.")
|
||||
|
||||
unknown = set(arguments) - {"query", "top_k", "category", "scope", "run_id"}
|
||||
if unknown:
|
||||
raise ToolInputError(f"Unknown search argument: {sorted(unknown)[0]}")
|
||||
|
||||
query = arguments.get("query")
|
||||
if not isinstance(query, str) or not query.strip():
|
||||
raise ToolInputError("query must be a non-empty string.")
|
||||
query = query.strip()
|
||||
if len(query) > 2000:
|
||||
raise ToolInputError("query must be at most 2,000 characters.")
|
||||
|
||||
top_k = arguments.get("top_k")
|
||||
if top_k is not None and (
|
||||
isinstance(top_k, bool) or not isinstance(top_k, int) or not 1 <= top_k <= 20
|
||||
):
|
||||
raise ToolInputError("top_k must be an integer from 1 to 20.")
|
||||
|
||||
category = arguments.get("category")
|
||||
if category is not None and category not in CODING_MEMORY_CATEGORY_NAMES:
|
||||
raise ToolInputError("category must be one of Mem0's supported categories.")
|
||||
|
||||
scope = arguments.get("scope")
|
||||
if scope is not None and scope not in SEARCH_SCOPES:
|
||||
raise ToolInputError(f"scope must be one of {list(SEARCH_SCOPES)}.")
|
||||
|
||||
run_id = arguments.get("run_id")
|
||||
if run_id is not None and (
|
||||
not isinstance(run_id, str) or not run_id.strip() or len(run_id) > 200
|
||||
):
|
||||
raise ToolInputError("run_id must be a non-empty string of at most 200 characters.")
|
||||
return query, top_k, category, scope, run_id
|
||||
|
||||
|
||||
def call_search_memories(arguments: Any) -> str:
|
||||
query, top_k, category, scope, run_id = _validate_arguments(arguments)
|
||||
repo = resolve_repo(os.environ.get("CLAUDE_PROJECT_DIR") or os.getcwd())
|
||||
result = search_memories(
|
||||
None,
|
||||
repo,
|
||||
None,
|
||||
query,
|
||||
top_k=top_k,
|
||||
category=category,
|
||||
scope=scope,
|
||||
run_id=run_id,
|
||||
operation="mcp-search",
|
||||
)
|
||||
return format_search_result(result)
|
||||
|
||||
|
||||
def _tool_response(text: str, *, is_error: bool = False) -> dict[str, Any]:
|
||||
return {
|
||||
"content": [{"type": "text", "text": text}],
|
||||
"isError": is_error,
|
||||
}
|
||||
|
||||
|
||||
def handle_request(message: Any) -> dict[str, Any] | None:
|
||||
if not isinstance(message, dict):
|
||||
return None
|
||||
request_id = message.get("id")
|
||||
method = message.get("method")
|
||||
|
||||
if method == "notifications/initialized":
|
||||
return None
|
||||
if method == "initialize":
|
||||
requested = (message.get("params") or {}).get("protocolVersion")
|
||||
return {
|
||||
"jsonrpc": "2.0",
|
||||
"id": request_id,
|
||||
"result": {
|
||||
"protocolVersion": requested or PROTOCOL_VERSION,
|
||||
"capabilities": {"tools": {"listChanged": False}},
|
||||
"serverInfo": {"name": "mem0", "version": "0.3.0"},
|
||||
},
|
||||
}
|
||||
if method == "ping":
|
||||
return {"jsonrpc": "2.0", "id": request_id, "result": {}}
|
||||
if method == "tools/list":
|
||||
return {
|
||||
"jsonrpc": "2.0",
|
||||
"id": request_id,
|
||||
"result": {
|
||||
"tools": [
|
||||
{
|
||||
"name": TOOL_NAME,
|
||||
"description": TOOL_DESCRIPTION,
|
||||
"inputSchema": TOOL_SCHEMA,
|
||||
"annotations": {
|
||||
"readOnlyHint": True,
|
||||
"idempotentHint": True,
|
||||
"openWorldHint": True,
|
||||
},
|
||||
}
|
||||
]
|
||||
},
|
||||
}
|
||||
if method == "tools/call":
|
||||
params = message.get("params") or {}
|
||||
if params.get("name") != TOOL_NAME:
|
||||
result = _tool_response("Unknown Mem0 tool.", is_error=True)
|
||||
else:
|
||||
try:
|
||||
result = _tool_response(call_search_memories(params.get("arguments")))
|
||||
except ToolInputError as exc:
|
||||
result = _tool_response(str(exc), is_error=True)
|
||||
except Exception:
|
||||
result = _tool_response("Memory search failed.", is_error=True)
|
||||
return {"jsonrpc": "2.0", "id": request_id, "result": result}
|
||||
if request_id is None:
|
||||
return None
|
||||
return {
|
||||
"jsonrpc": "2.0",
|
||||
"id": request_id,
|
||||
"error": {"code": -32601, "message": "Method not found"},
|
||||
}
|
||||
|
||||
|
||||
def main() -> int:
|
||||
for raw_line in sys.stdin:
|
||||
try:
|
||||
message = json.loads(raw_line)
|
||||
response = handle_request(message)
|
||||
except json.JSONDecodeError:
|
||||
response = {
|
||||
"jsonrpc": "2.0",
|
||||
"id": None,
|
||||
"error": {"code": -32700, "message": "Parse error"},
|
||||
}
|
||||
except Exception:
|
||||
response = {
|
||||
"jsonrpc": "2.0",
|
||||
"id": None,
|
||||
"error": {"code": -32603, "message": "Internal error"},
|
||||
}
|
||||
if response is not None:
|
||||
sys.stdout.write(json.dumps(response, separators=(",", ":")) + "\n")
|
||||
sys.stdout.flush()
|
||||
telemetry.spawn_flush()
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -1,148 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Mem0 diagnostics and user controls."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
|
||||
import telemetry
|
||||
from memory_core import (
|
||||
EvidenceStore,
|
||||
api_key,
|
||||
data_dir,
|
||||
doctor,
|
||||
forget_remote_repo,
|
||||
resolve_repo,
|
||||
user_id,
|
||||
)
|
||||
|
||||
|
||||
def _print_status(value: dict) -> None:
|
||||
last = value.get("last_operation") or {}
|
||||
print(f"Mem0: {'paused' if value['paused'] else 'active'}")
|
||||
print(f"Repository: {value['repo_id']}")
|
||||
print(f"Local data: {value['data_dir']}")
|
||||
print(f"API key: {'configured' if value['api_key_configured'] else 'missing'}")
|
||||
print(
|
||||
"Saved on this computer: "
|
||||
f"{value['events']} session details, {value['flushes']} memory updates"
|
||||
)
|
||||
print(
|
||||
f"Used in this repository: {value['retrievals']} memories returned, "
|
||||
f"{value['sidekick_runs']} sidekick runs"
|
||||
)
|
||||
if last:
|
||||
item_label = ""
|
||||
if last["operation"] in {"flush", "flush-retry"}:
|
||||
item_label = f", {last['item_count']} memories"
|
||||
operation = (
|
||||
"memory update"
|
||||
if last["operation"] in {"flush", "flush-retry"}
|
||||
else last["operation"].replace("-", " ")
|
||||
)
|
||||
print(
|
||||
f"Last {operation}: "
|
||||
f"{'succeeded' if last['success'] else 'failed'} "
|
||||
f"({last['duration_ms']:.1f} ms{item_label})"
|
||||
)
|
||||
sidekick = value.get("last_sidekick") or {}
|
||||
if sidekick:
|
||||
state = "finished" if sidekick.get("stopped_at") else "started"
|
||||
print(
|
||||
"Last sidekick: "
|
||||
f"{state}, received {sidekick['context_chars']} characters of memory, "
|
||||
f"agent {sidekick['agent_id']}"
|
||||
)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--plugin-data-dir", default="")
|
||||
subparsers = parser.add_subparsers(dest="command", required=True)
|
||||
|
||||
status = subparsers.add_parser("status")
|
||||
status.add_argument("--json", action="store_true")
|
||||
|
||||
doctor_parser = subparsers.add_parser("doctor")
|
||||
doctor_parser.add_argument("--json", action="store_true")
|
||||
|
||||
subparsers.add_parser("pause")
|
||||
subparsers.add_parser("resume")
|
||||
|
||||
forget = subparsers.add_parser("forget")
|
||||
forget.add_argument("--remote", action="store_true")
|
||||
forget.add_argument("--yes", action="store_true")
|
||||
forget.add_argument("--include-project-memory", action="store_true")
|
||||
|
||||
args = parser.parse_args()
|
||||
if args.plugin_data_dir:
|
||||
os.environ["MEM0_CODE_DATA_DIR"] = args.plugin_data_dir
|
||||
store = EvidenceStore()
|
||||
try:
|
||||
repo = resolve_repo(os.getcwd())
|
||||
telemetry.record("control", repo=repo, action=args.command)
|
||||
if args.command == "status":
|
||||
result = {
|
||||
**store.status(repo.identity),
|
||||
"repo_id": repo.identity,
|
||||
"app_id": repo.app_id,
|
||||
"project_id": repo.project_id,
|
||||
"directory": repo.directory,
|
||||
"user_id": user_id(),
|
||||
"data_dir": str(data_dir()),
|
||||
"api_key_configured": bool(api_key()),
|
||||
}
|
||||
if args.json:
|
||||
print(json.dumps(result, indent=2, default=str))
|
||||
else:
|
||||
_print_status(result)
|
||||
elif args.command == "doctor":
|
||||
result = doctor(os.getcwd())
|
||||
if args.json:
|
||||
print(json.dumps(result, indent=2, default=str))
|
||||
else:
|
||||
for name, check in result["checks"].items():
|
||||
print(
|
||||
f"{'PASS' if check['ok'] else 'FAIL'} {name}: {check['detail']}"
|
||||
)
|
||||
return 0 if result["ok"] else 1
|
||||
elif args.command == "pause":
|
||||
store.set_setting("paused", "true")
|
||||
print("Mem0 stopped saving and searching memories.")
|
||||
elif args.command == "resume":
|
||||
store.set_setting("paused", "false")
|
||||
print("Mem0 resumed saving and searching memories.")
|
||||
elif args.command == "forget":
|
||||
if not args.yes:
|
||||
print(
|
||||
"Refusing to delete data without --yes. Add --remote to also "
|
||||
"delete this user/repository scope from Mem0."
|
||||
)
|
||||
return 2
|
||||
remote_result = (
|
||||
forget_remote_repo(
|
||||
repo, include_project_memory=args.include_project_memory
|
||||
)
|
||||
if args.remote
|
||||
else None
|
||||
)
|
||||
local_result = store.forget_local_repo(repo.identity)
|
||||
print(
|
||||
json.dumps(
|
||||
{"local": local_result, "remote": remote_result},
|
||||
indent=2,
|
||||
default=str,
|
||||
)
|
||||
)
|
||||
if remote_result and remote_result.get("status") == "error":
|
||||
return 1
|
||||
finally:
|
||||
store.close()
|
||||
telemetry.spawn_flush()
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,347 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Anonymous usage telemetry for the Mem0 Claude Code plugin.
|
||||
|
||||
Hooks run on a 3-6 second budget and fire on every tool call, so recording never
|
||||
touches the network: `record` appends one JSON line to a local spool and returns.
|
||||
A detached `python3 telemetry.py` drains the spool in one batched PostHog request,
|
||||
started once per session and again from the flush worker that is already detached.
|
||||
|
||||
Pure stdlib, matching the rest of the plugin. Opt out with MEM0_TELEMETRY=false.
|
||||
|
||||
Never sends prompts, memory text, queries, file paths, repository names, or API
|
||||
keys: only event names, durations, counts, coarse outcomes, and salted hashes.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import platform
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import memory_core
|
||||
|
||||
POSTHOG_API_KEY = "phc_hgJkUVJFYtmaJqrvf6CYN67TIQ8yhXAkWzUn9AMU4yX"
|
||||
POSTHOG_CAPTURE_URL = "https://us.i.posthog.com/i/v0/e/"
|
||||
POSTHOG_BATCH_URL = "https://us.i.posthog.com/batch/"
|
||||
EVENT_PREFIX = "code"
|
||||
SPOOL_LIMIT_BYTES = 256 * 1024
|
||||
BATCH_SIZE = 100
|
||||
SEND_TIMEOUT = 5
|
||||
CLAIM_STALE_SECONDS = 120
|
||||
CLAIM_EXPIRY_SECONDS = 7 * 24 * 60 * 60
|
||||
|
||||
|
||||
def is_enabled() -> bool:
|
||||
"""Whether telemetry is switched on for this process."""
|
||||
return os.environ.get("MEM0_TELEMETRY", "true").strip().lower() not in {
|
||||
"false",
|
||||
"0",
|
||||
"no",
|
||||
"off",
|
||||
}
|
||||
|
||||
|
||||
def _digest(value: str, length: int = 16) -> str:
|
||||
return hashlib.sha256(value.encode("utf-8")).hexdigest()[:length]
|
||||
|
||||
|
||||
def _spool_path() -> Path:
|
||||
return memory_core.data_dir() / "telemetry.jsonl"
|
||||
|
||||
|
||||
def _identity_path() -> Path:
|
||||
return memory_core.data_dir() / "telemetry-identity.json"
|
||||
|
||||
|
||||
def _read_identity() -> dict[str, str]:
|
||||
try:
|
||||
value = json.loads(_identity_path().read_text(encoding="utf-8"))
|
||||
except (OSError, json.JSONDecodeError):
|
||||
return {}
|
||||
return value if isinstance(value, dict) else {}
|
||||
|
||||
|
||||
def _write_identity(identity: dict[str, str]) -> None:
|
||||
path = _identity_path()
|
||||
temporary = path.with_suffix(f".{os.getpid()}.tmp")
|
||||
try:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
temporary.write_text(json.dumps(identity), encoding="utf-8")
|
||||
temporary.replace(path)
|
||||
except OSError:
|
||||
try:
|
||||
temporary.unlink()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def anonymous_id(identity: dict[str, str] | None = None) -> str:
|
||||
"""Per-machine anonymous identifier, created and persisted on first use."""
|
||||
identity = _read_identity() if identity is None else identity
|
||||
existing = identity.get("anonymous_id")
|
||||
if existing:
|
||||
return existing
|
||||
created = f"code-anon-{uuid.uuid4().hex}"
|
||||
identity["anonymous_id"] = created
|
||||
_write_identity(identity)
|
||||
return created
|
||||
|
||||
|
||||
def is_first_run() -> bool:
|
||||
"""Whether this machine has never recorded a plugin event before."""
|
||||
return not _identity_path().exists()
|
||||
|
||||
|
||||
def record(
|
||||
event: str,
|
||||
*,
|
||||
repo: Any = None,
|
||||
session_id: str | None = None,
|
||||
**properties: Any,
|
||||
) -> None:
|
||||
"""Append one event to the local spool. Never blocks and never raises."""
|
||||
if not is_enabled():
|
||||
return
|
||||
try:
|
||||
spool = _spool_path()
|
||||
try:
|
||||
if spool.stat().st_size > SPOOL_LIMIT_BYTES:
|
||||
return
|
||||
except OSError:
|
||||
pass
|
||||
properties.update(
|
||||
harness="claude-code",
|
||||
plugin_version=memory_core.PLUGIN_VERSION,
|
||||
os=sys.platform,
|
||||
python_version=platform.python_version(),
|
||||
)
|
||||
if repo is not None:
|
||||
properties["repo_hash"] = _digest(getattr(repo, "identity", ""))
|
||||
if session_id:
|
||||
properties["session_hash"] = _digest(session_id)
|
||||
line = json.dumps(
|
||||
{
|
||||
"event": f"{EVENT_PREFIX}.{event}",
|
||||
"timestamp": memory_core.utc_now(),
|
||||
"properties": {
|
||||
key: value for key, value in properties.items() if value is not None
|
||||
},
|
||||
},
|
||||
separators=(",", ":"),
|
||||
default=str,
|
||||
)
|
||||
spool.parent.mkdir(parents=True, exist_ok=True)
|
||||
with spool.open("a", encoding="utf-8") as handle:
|
||||
handle.write(line + "\n")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def error_kind(exc: BaseException | str) -> str:
|
||||
"""Coarse, content-free label for a failure, safe to send."""
|
||||
text = exc if isinstance(exc, str) else f"{type(exc).__name__}: {exc}"
|
||||
lowered = text.lower()
|
||||
if "timed out" in lowered or "timeout" in lowered:
|
||||
return "timeout"
|
||||
if "401" in lowered or "403" in lowered or "unauthor" in lowered or "forbidden" in lowered:
|
||||
return "auth"
|
||||
if "429" in lowered or "rate limit" in lowered:
|
||||
return "rate-limited"
|
||||
if any(code in lowered for code in ("500", "502", "503", "504")):
|
||||
return "server-error"
|
||||
if "400" in lowered or "422" in lowered:
|
||||
return "bad-request"
|
||||
if isinstance(exc, str):
|
||||
return "other"
|
||||
if isinstance(exc, urllib.error.URLError):
|
||||
return "network"
|
||||
return type(exc).__name__
|
||||
|
||||
|
||||
def spawn_flush() -> bool:
|
||||
"""Start the detached sender that drains the spool."""
|
||||
if not is_enabled():
|
||||
return False
|
||||
try:
|
||||
if not _spool_path().exists() and not any(
|
||||
memory_core.data_dir().glob("telemetry-*.sending")
|
||||
):
|
||||
return False
|
||||
subprocess.Popen(
|
||||
[sys.executable, str(Path(__file__).resolve())],
|
||||
stdin=subprocess.DEVNULL,
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
close_fds=True,
|
||||
**memory_core.detached_process_kwargs(),
|
||||
)
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _claim_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"
|
||||
spool = _spool_path()
|
||||
try:
|
||||
spool.replace(claim)
|
||||
return claim
|
||||
except OSError:
|
||||
pass
|
||||
now = time.time()
|
||||
for orphan in sorted(directory.glob("telemetry-*.sending")):
|
||||
try:
|
||||
age = now - orphan.stat().st_mtime
|
||||
except OSError:
|
||||
continue
|
||||
if age > CLAIM_EXPIRY_SECONDS:
|
||||
try:
|
||||
orphan.unlink()
|
||||
except OSError:
|
||||
pass
|
||||
continue
|
||||
if age < CLAIM_STALE_SECONDS:
|
||||
continue
|
||||
try:
|
||||
orphan.replace(claim)
|
||||
return claim
|
||||
except OSError:
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def _resolve_email(key: str) -> str:
|
||||
"""Trade the API key for the account email so events join other Mem0 surfaces."""
|
||||
url = os.environ.get("MEM0_API_URL", memory_core.DEFAULT_API_URL).rstrip("/") + "/v1/ping/"
|
||||
request = urllib.request.Request(
|
||||
url, headers={"Authorization": f"Token {key}", "Content-Type": "application/json"}
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=SEND_TIMEOUT) as response:
|
||||
payload = json.loads(response.read().decode("utf-8"))
|
||||
except Exception:
|
||||
return ""
|
||||
email = payload.get("user_email") if isinstance(payload, dict) else ""
|
||||
return email if isinstance(email, str) else ""
|
||||
|
||||
|
||||
def _post(payload: dict[str, Any], url: str) -> bool:
|
||||
request = urllib.request.Request(
|
||||
url,
|
||||
data=json.dumps(payload, default=str).encode("utf-8"),
|
||||
headers={"Content-Type": "application/json"},
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=SEND_TIMEOUT):
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def resolve_distinct_id() -> tuple[str, str]:
|
||||
"""Return the PostHog distinct id and the anonymous id it replaced, if any."""
|
||||
identity = _read_identity()
|
||||
email = identity.get("email", "")
|
||||
if email:
|
||||
return email, ""
|
||||
key = memory_core.api_key()
|
||||
if not key:
|
||||
return anonymous_id(identity), ""
|
||||
email = _resolve_email(key)
|
||||
if not email:
|
||||
return anonymous_id(identity), ""
|
||||
previous = identity.get("anonymous_id", "")
|
||||
identity["email"] = email
|
||||
_write_identity(identity)
|
||||
return email, previous
|
||||
|
||||
|
||||
def flush() -> int:
|
||||
"""Drain claimed spools to PostHog and return the number of events sent."""
|
||||
if not is_enabled():
|
||||
return 0
|
||||
claim = _claim_spool()
|
||||
if claim is None:
|
||||
return 0
|
||||
try:
|
||||
lines = claim.read_text(encoding="utf-8").splitlines()
|
||||
except OSError:
|
||||
return 0
|
||||
events = []
|
||||
for line in lines:
|
||||
try:
|
||||
value = json.loads(line)
|
||||
except json.JSONDecodeError:
|
||||
continue
|
||||
if isinstance(value, dict) and value.get("event"):
|
||||
events.append(value)
|
||||
if not events:
|
||||
try:
|
||||
claim.unlink()
|
||||
except OSError:
|
||||
pass
|
||||
return 0
|
||||
|
||||
distinct_id, aliased_anonymous_id = resolve_distinct_id()
|
||||
if aliased_anonymous_id:
|
||||
_post(
|
||||
{
|
||||
"api_key": POSTHOG_API_KEY,
|
||||
"event": "$identify",
|
||||
"distinct_id": distinct_id,
|
||||
"properties": {
|
||||
"$anon_distinct_id": aliased_anonymous_id,
|
||||
"$lib": "posthog-python",
|
||||
},
|
||||
},
|
||||
POSTHOG_CAPTURE_URL,
|
||||
)
|
||||
|
||||
sent = 0
|
||||
for start in range(0, len(events), BATCH_SIZE):
|
||||
batch = [
|
||||
{
|
||||
"event": event["event"],
|
||||
"distinct_id": distinct_id,
|
||||
"timestamp": event.get("timestamp"),
|
||||
"properties": {
|
||||
"source": "CLAUDE_CODE_PLUGIN",
|
||||
"language": "python",
|
||||
"$process_person_profile": False,
|
||||
"$lib": "posthog-python",
|
||||
**(event.get("properties") or {}),
|
||||
},
|
||||
}
|
||||
for event in events[start : start + BATCH_SIZE]
|
||||
]
|
||||
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
|
||||
|
||||
|
||||
def main() -> int:
|
||||
flush()
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
raise SystemExit(main())
|
||||
except Exception:
|
||||
raise SystemExit(0)
|
||||
@@ -1,110 +0,0 @@
|
||||
{
|
||||
"description": "Create memories from Claude Code sessions, search them during later work, and provide a Sonnet coding agent in a separate Git worktree.",
|
||||
"hooks": {
|
||||
"SessionStart": [
|
||||
{
|
||||
"matcher": "startup|resume|clear|compact",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "python3 \"${CLAUDE_PLUGIN_ROOT}/adapters/claude/hook.py\" session-start --plugin-data-dir \"${CLAUDE_PLUGIN_DATA}\"",
|
||||
"timeout": 5
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"UserPromptSubmit": [
|
||||
{
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "python3 \"${CLAUDE_PLUGIN_ROOT}/adapters/claude/hook.py\" user-prompt --plugin-data-dir \"${CLAUDE_PLUGIN_DATA}\"",
|
||||
"timeout": 6
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"PostToolUse": [
|
||||
{
|
||||
"matcher": ".*",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "python3 \"${CLAUDE_PLUGIN_ROOT}/adapters/claude/hook.py\" post-tool --plugin-data-dir \"${CLAUDE_PLUGIN_DATA}\"",
|
||||
"timeout": 3
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"PostToolUseFailure": [
|
||||
{
|
||||
"matcher": ".*",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "python3 \"${CLAUDE_PLUGIN_ROOT}/adapters/claude/hook.py\" post-tool-failure --plugin-data-dir \"${CLAUDE_PLUGIN_DATA}\"",
|
||||
"timeout": 3
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"SubagentStart": [
|
||||
{
|
||||
"matcher": "^mem0:sidekick$",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "python3 \"${CLAUDE_PLUGIN_ROOT}/adapters/claude/hook.py\" sidekick-start --plugin-data-dir \"${CLAUDE_PLUGIN_DATA}\"",
|
||||
"timeout": 5
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"SubagentStop": [
|
||||
{
|
||||
"matcher": "^mem0:sidekick$",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "python3 \"${CLAUDE_PLUGIN_ROOT}/adapters/claude/hook.py\" sidekick-stop --plugin-data-dir \"${CLAUDE_PLUGIN_DATA}\"",
|
||||
"timeout": 5
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"Stop": [
|
||||
{
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "python3 \"${CLAUDE_PLUGIN_ROOT}/adapters/claude/hook.py\" stop --plugin-data-dir \"${CLAUDE_PLUGIN_DATA}\"",
|
||||
"timeout": 3
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"PreCompact": [
|
||||
{
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "python3 \"${CLAUDE_PLUGIN_ROOT}/adapters/claude/hook.py\" flush --reason pre-compact --plugin-data-dir \"${CLAUDE_PLUGIN_DATA}\"",
|
||||
"statusMessage": "Saving memories from this session...",
|
||||
"timeout": 5
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"SessionEnd": [
|
||||
{
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "python3 \"${CLAUDE_PLUGIN_ROOT}/adapters/claude/hook.py\" flush --reason session-end --plugin-data-dir \"${CLAUDE_PLUGIN_DATA}\"",
|
||||
"timeout": 5
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
---
|
||||
name: forget
|
||||
description: Delete the Mem0 memories stored for this repository and this user. Use when the user asks to forget, clear, wipe, or delete memories.
|
||||
disable-model-invocation: true
|
||||
---
|
||||
|
||||
# Forget this repository's memories
|
||||
|
||||
This permanently deletes remote memories. Before running anything, tell the
|
||||
user exactly what will be deleted: their own memories for this repository
|
||||
only. The repository's project memory is shared by everyone who works in it,
|
||||
so it stays unless the user explicitly asks to delete that too.
|
||||
|
||||
After the user confirms, run:
|
||||
|
||||
```bash
|
||||
python3 "${CLAUDE_PLUGIN_ROOT}/core/memory_cli.py" forget --remote --yes
|
||||
```
|
||||
|
||||
If the user also asked to delete the repository's shared project memory, add
|
||||
`--include-project-memory` and say that this removes it for every teammate.
|
||||
|
||||
Report what the command output says was deleted. If the user only wants local
|
||||
data cleared (evidence log, pending queue), run the same command without
|
||||
`--remote`. Never pass `--yes` before the user has confirmed in this
|
||||
conversation.
|
||||
@@ -1,20 +0,0 @@
|
||||
---
|
||||
name: pause
|
||||
description: Pause Mem0 memory capture on this machine. Use when the user wants to stop memories being recorded, for example for private work or experiments.
|
||||
disable-model-invocation: true
|
||||
---
|
||||
|
||||
# Pause memory capture
|
||||
|
||||
To pause (hooks stop capturing and sending session content; a minimal
|
||||
anonymous telemetry ping still fires at session start unless
|
||||
`MEM0_TELEMETRY=false`):
|
||||
|
||||
```bash
|
||||
python3 "${CLAUDE_PLUGIN_ROOT}/core/memory_cli.py" pause
|
||||
```
|
||||
|
||||
Confirm the new state back to the user, and remind them that already-created
|
||||
memories still exist and remain searchable. Pending unsent packets are held
|
||||
while paused, not expired, and are delivered after resuming. To turn capture
|
||||
back on, use `/mem0:resume`.
|
||||
@@ -1,21 +0,0 @@
|
||||
---
|
||||
name: remember
|
||||
description: Acknowledge a "remember this" request and make sure it is captured well. Use when the user explicitly asks to remember, note, or save something for future sessions.
|
||||
disable-model-invocation: true
|
||||
---
|
||||
|
||||
# Remember something for future sessions
|
||||
|
||||
Mem0 creates memories from the session automatically — there is no separate
|
||||
write command. When the user asks to remember something:
|
||||
|
||||
1. Restate the fact clearly and completely in your reply, in one or two
|
||||
sentences, including any names, values, or paths it depends on. Your visible
|
||||
reply is what memory extraction reads, so a precise restatement is what gets
|
||||
remembered.
|
||||
2. Tell the user it will be saved with this session's memories when the session
|
||||
ends or compacts, and that it will surface in future sessions in this
|
||||
repository (they can check later with /mem0:search).
|
||||
|
||||
Do not invent a storage confirmation or a memory ID — creation happens in the
|
||||
background after the session.
|
||||
@@ -1,19 +0,0 @@
|
||||
---
|
||||
name: resume
|
||||
description: Resume Mem0 memory capture after it was paused with /mem0:pause.
|
||||
disable-model-invocation: true
|
||||
---
|
||||
|
||||
# Resume memory capture
|
||||
|
||||
Resume memory capture for this machine.
|
||||
|
||||
Run:
|
||||
|
||||
```bash
|
||||
python3 "${CLAUDE_PLUGIN_ROOT}/core/memory_cli.py" resume
|
||||
```
|
||||
|
||||
Confirm to the user that capture is active again. New sessions record evidence and
|
||||
create memories as normal; nothing that happened while paused is retroactively
|
||||
captured.
|
||||
@@ -1,26 +0,0 @@
|
||||
---
|
||||
name: search
|
||||
description: Search memories from earlier Claude Code sessions in this repository. Use it when earlier work may already explain the code, error, decision, or command you need, so you can avoid repeating file reads, searches, or experiments.
|
||||
argument-hint: "[question] [--top-k number] [--category category-name] [--scope repo|dir|mine] [--run-id session-id]"
|
||||
disable-model-invocation: true
|
||||
---
|
||||
|
||||
# Search memories
|
||||
|
||||
Call `search_memories` with the user's question. Treat `--top-k`, `--category`,
|
||||
`--scope`, and `--run-id` as tool arguments instead of including them in the
|
||||
query.
|
||||
|
||||
Omit `top_k` to use Mem0's configured default. Omit `category` to search every
|
||||
category; 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.
|
||||
|
||||
Pass `scope` when the question needs something else: `dir` to narrow the
|
||||
shared memory to the directory you are working in (a package inside a
|
||||
monorepo), `mine` for your own preferences alone. Pass `run_id` with a Claude
|
||||
Code session ID to look at what one earlier session recorded, for example to
|
||||
pick up where a compacted or closed session left off. Return the tool's result
|
||||
directly.
|
||||
@@ -1,23 +0,0 @@
|
||||
---
|
||||
name: status
|
||||
description: Show whether Mem0 memory is working in this repository, covering configuration, capture state, pending flushes, and whether the Mem0 API key is valid. Use when the user asks whether memory is on, why a memory is missing, or anything looks broken.
|
||||
disable-model-invocation: false
|
||||
---
|
||||
|
||||
# Memory status
|
||||
|
||||
Run both commands and report the combined result in plain language:
|
||||
|
||||
```bash
|
||||
python3 "${CLAUDE_PLUGIN_ROOT}/core/memory_cli.py" status --json
|
||||
python3 "${CLAUDE_PLUGIN_ROOT}/core/memory_cli.py" doctor
|
||||
```
|
||||
|
||||
Summarize, using only fields the JSON actually reports: whether capture is
|
||||
active or paused, the user ID and repository scope (`repo_id`), whether an
|
||||
API key is configured, the event/flush/retrieval counts (`flushes` is the
|
||||
number of completed flushes, not a pending count), and the doctor check
|
||||
results. If doctor reports an authentication failure (401 / invalid key), say
|
||||
clearly that the Mem0 API key is invalid or expired and that memories are NOT
|
||||
being created. Never report an auth failure as "no memories found". Suggest
|
||||
reinstalling with `--config api_key=...` in that case.
|
||||
@@ -1,7 +0,0 @@
|
||||
"""Keep the test suite from sending usage telemetry to the live PostHog project."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
|
||||
os.environ["MEM0_TELEMETRY"] = "false"
|
||||
@@ -1,242 +0,0 @@
|
||||
"""Live scoping tests against the Mem0 Platform: run with MEM0_API_KEY set, skipped otherwise."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
PLUGIN_ROOT = Path(__file__).resolve().parents[2]
|
||||
sys.path.insert(0, str(PLUGIN_ROOT / "core"))
|
||||
sys.path.insert(0, str(PLUGIN_ROOT / "adapters" / "claude"))
|
||||
|
||||
import hook # noqa: E402
|
||||
import memory_core # noqa: E402
|
||||
|
||||
pytestmark = pytest.mark.skipif(
|
||||
not os.environ.get("MEM0_API_KEY"), reason="MEM0_API_KEY is required for live scoping tests"
|
||||
)
|
||||
|
||||
GIT_ENV = {
|
||||
**os.environ,
|
||||
"GIT_AUTHOR_NAME": "t",
|
||||
"GIT_AUTHOR_EMAIL": "t@t",
|
||||
"GIT_COMMITTER_NAME": "t",
|
||||
"GIT_COMMITTER_EMAIL": "t@t",
|
||||
}
|
||||
|
||||
|
||||
def _git_repo(path: Path, remote: str) -> None:
|
||||
path.mkdir(parents=True)
|
||||
for args in (
|
||||
["init", "-q"],
|
||||
["remote", "add", "origin", remote],
|
||||
["commit", "-q", "--allow-empty", "-m", "init"],
|
||||
):
|
||||
subprocess.run(["git", "-C", str(path), *args], check=True, capture_output=True, env=GIT_ENV)
|
||||
|
||||
|
||||
def _bash(command: str, failed: bool, preview: str) -> dict:
|
||||
return {
|
||||
"tool": "Bash",
|
||||
"command": command,
|
||||
"command_kind": "test",
|
||||
"failed": failed,
|
||||
"result_preview": preview,
|
||||
}
|
||||
|
||||
|
||||
class Namespace:
|
||||
"""One fresh, isolated set of users and repositories for a test run."""
|
||||
|
||||
def __init__(self, tmp: Path):
|
||||
self.tag = uuid.uuid4().hex[:8]
|
||||
self.users = {name: f"live-{self.tag}-{name}" for name in ("alice", "bob", "carol", "dave", "erin")}
|
||||
self.root = tmp / "monorepo"
|
||||
_git_repo(self.root, f"https://github.com/live-{self.tag}/monorepo.git")
|
||||
(self.root / "services" / "billing").mkdir(parents=True)
|
||||
(self.root / "apps" / "web").mkdir(parents=True)
|
||||
self.notes_a = tmp / "carol" / "notes"
|
||||
self.notes_b = tmp / "dave" / "notes"
|
||||
self.notes_a.mkdir(parents=True)
|
||||
self.notes_b.mkdir(parents=True)
|
||||
os.environ["MEM0_CODE_DATA_DIR"] = str(tmp / "data")
|
||||
os.environ["MEM0_CODE_TELEMETRY"] = "false"
|
||||
os.environ["MEM0_CODE_EXTRACTION_WAIT_SECONDS"] = "180"
|
||||
self.store = memory_core.EvidenceStore()
|
||||
self.reads = 0
|
||||
|
||||
def as_user(self, name: str) -> str:
|
||||
os.environ["MEM0_CODE_USER_ID"] = self.users[name]
|
||||
return self.users[name]
|
||||
|
||||
def session(self, user: str, cwd: Path, sid: str, prompt: str, tools: list[dict], answer: str, reason="session-end"):
|
||||
self.as_user(user)
|
||||
sid = f"{self.tag}-{sid}"
|
||||
ctx = self.store.repo_for_session(sid, str(cwd))
|
||||
self.store.record_event(ctx, sid, "user_prompt", {"text": prompt})
|
||||
for tool in tools:
|
||||
self.store.record_event(ctx, sid, "tool_result", tool)
|
||||
self.store.record_event(ctx, sid, "assistant_stop", {"text": answer})
|
||||
result = memory_core.flush_session(self.store, {"session_id": sid, "cwd": str(cwd)}, reason)
|
||||
assert result.get("status") == "semantic-succeeded", result
|
||||
return sid
|
||||
|
||||
def search(self, user: str, cwd: Path, query: str, *, tries: int = 6, top_k: int = 20, **kwargs) -> list[dict]:
|
||||
self.as_user(user)
|
||||
ctx = memory_core.resolve_repo(str(cwd))
|
||||
memories: list[dict] = []
|
||||
for attempt in range(tries):
|
||||
self.reads += 1
|
||||
memories = memory_core.search_memories(
|
||||
self.store, ctx, f"{self.tag}-read-{self.reads}", query, top_k=top_k, operation="live-test", timeout=30, **kwargs
|
||||
).memories
|
||||
if memories or attempt == tries - 1:
|
||||
return memories
|
||||
time.sleep(5)
|
||||
return memories
|
||||
|
||||
def cleanup(self):
|
||||
for user, cwd in (("alice", self.root), ("bob", self.root), ("erin", self.root), ("carol", self.notes_a), ("dave", self.notes_b)):
|
||||
self.as_user(user)
|
||||
memory_core.forget_remote_repo(memory_core.resolve_repo(str(cwd)), include_project_memory=True)
|
||||
self.store.close()
|
||||
|
||||
|
||||
def _text(memories: list[dict]) -> str:
|
||||
return " ".join(str(m.get("memory", "")) for m in memories).lower()
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def ns(tmp_path_factory):
|
||||
namespace = Namespace(tmp_path_factory.mktemp("live"))
|
||||
root, billing, web = namespace.root, namespace.root / "services" / "billing", namespace.root / "apps" / "web"
|
||||
namespace.session(
|
||||
"alice", root, "root-alice",
|
||||
"Remember that I personally prefer uv over pip. Also document that invoices are rounded half-up in api/invoices.py.",
|
||||
[{"tool": "Edit", "path": "README.md"}, _bash("pytest", False, "12 passed")],
|
||||
"README now documents that invoices round half-up in api/invoices.py. Noted that you prefer uv over pip.",
|
||||
)
|
||||
namespace.session(
|
||||
"bob", billing, "billing-bob",
|
||||
"The billing worker must retry Stripe webhooks five times with exponential backoff. Run the billing tests.",
|
||||
[_bash("npm test", True, "npm ERR! missing script: test"), _bash("make billing-test", False, "34 passed")],
|
||||
"Documented: the billing worker retries Stripe webhooks five times with exponential backoff. `npm test` does not exist here; `make billing-test` runs the billing suite.",
|
||||
)
|
||||
namespace.session(
|
||||
"bob", web, "web-bob",
|
||||
"The web app is built with Vite. Start it with pnpm --filter web dev.",
|
||||
[_bash("pnpm --filter web dev", False, "VITE ready in 300ms")],
|
||||
"Confirmed: the web app uses Vite and starts with `pnpm --filter web dev`.",
|
||||
)
|
||||
namespace.session(
|
||||
"carol", namespace.notes_a, "notes-carol",
|
||||
"Private notes folder. My journal password hint lives in hints.txt. I like vim keybindings.",
|
||||
[{"tool": "Edit", "path": "hints.txt"}],
|
||||
"Added the journal password hint to hints.txt. Noted that you like vim keybindings.",
|
||||
)
|
||||
namespace.session(
|
||||
"dave", namespace.notes_b, "notes-dave",
|
||||
"This notes folder holds my grocery list in groceries.md.",
|
||||
[{"tool": "Edit", "path": "groceries.md"}],
|
||||
"Saved the grocery list to groceries.md.",
|
||||
)
|
||||
namespace.handoff_session = namespace.session(
|
||||
"alice", root, "handoff-old",
|
||||
"We decided to migrate the ledger table to bigint ids. Migration 0042 is written but test_ledger_precision still fails.",
|
||||
[_bash("pytest tests/test_ledger.py", True, "FAILED test_ledger_precision: Decimal rounding mismatch")],
|
||||
"Migration 0042 moves ledger ids to bigint. test_ledger_precision still fails with a Decimal rounding mismatch; that is the next thing to fix.",
|
||||
reason="pre-compact",
|
||||
)
|
||||
yield namespace
|
||||
namespace.cleanup()
|
||||
|
||||
|
||||
def test_personal_preferences_stay_with_their_owner(ns):
|
||||
mine = ns.search("alice", ns.root, "which package manager do I prefer", scope="mine")
|
||||
assert "uv" in _text(mine)
|
||||
assert {m.get("user_id") for m in mine} == {ns.users["alice"]}
|
||||
|
||||
teammate = ns.search("bob", ns.root, "which package manager do I prefer, uv or pip", tries=1)
|
||||
assert not any(m.get("user_id") == ns.users["alice"] for m in teammate)
|
||||
assert "uv" not in _text(teammate)
|
||||
|
||||
|
||||
def test_shared_project_memory_reaches_a_teammate_who_never_wrote(ns):
|
||||
found = ns.search("erin", ns.root, "how are invoices rounded")
|
||||
assert "half" in _text(found)
|
||||
assert all(m.get("user_id") is None and m.get("agent_id") for m in found)
|
||||
|
||||
|
||||
def test_repo_scope_spans_every_subdirectory(ns):
|
||||
found = ns.search("erin", ns.root, "how many times are Stripe webhooks retried", scope="repo")
|
||||
assert "stripe" in _text(found)
|
||||
app_ids = {m.get("app_id") for m in found}
|
||||
assert any(app.endswith("/services/billing") for app in app_ids)
|
||||
|
||||
|
||||
def test_dir_scope_narrows_shared_memory_to_the_directory(ns):
|
||||
billing = ns.root / "services" / "billing"
|
||||
found = ns.search("erin", billing, "how do I run the tests here", scope="dir")
|
||||
assert "billing-test" in _text(found)
|
||||
assert {m.get("app_id") for m in found if m.get("agent_id")} == {memory_core.directory_app_id(memory_core.resolve_repo(str(billing)))}
|
||||
|
||||
web = ns.root / "apps" / "web"
|
||||
elsewhere = ns.search("erin", web, "Stripe webhook retries exponential backoff", scope="dir", tries=1)
|
||||
assert "stripe" not in _text(elsewhere)
|
||||
|
||||
|
||||
def test_project_memory_never_carries_a_user_id(ns):
|
||||
found = ns.search("erin", ns.root, "invoices rounding billing webhooks vite dev server")
|
||||
assert found
|
||||
for memory in found:
|
||||
assert memory.get("user_id") is None
|
||||
assert memory.get("agent_id") == memory_core.resolve_repo(str(ns.root)).project_id
|
||||
|
||||
|
||||
def test_same_named_plain_folders_at_different_paths_do_not_share(ns):
|
||||
carol = ns.search("carol", ns.notes_a, "where is my journal password hint")
|
||||
assert "hint" in _text(carol)
|
||||
|
||||
dave = ns.search("dave", ns.notes_b, "where is the journal password hint", tries=1)
|
||||
assert "hint" not in _text(dave)
|
||||
assert not any((m.get("metadata") or {}).get("author") == ns.users["carol"] for m in dave)
|
||||
|
||||
|
||||
def test_run_id_recovers_one_session_after_compaction(ns):
|
||||
found = ns.search("alice", ns.root, "what was I working on and what still fails", run_id=ns.handoff_session)
|
||||
assert "ledger" in _text(found) or "0042" in _text(found)
|
||||
assert {m.get("run_id") for m in found} == {ns.handoff_session}
|
||||
|
||||
other = ns.search("alice", ns.root, "invoices rounding half-up", run_id=ns.handoff_session, tries=1)
|
||||
assert all(m.get("run_id") == ns.handoff_session for m in other)
|
||||
|
||||
|
||||
def test_a_pending_packet_is_recovered_and_delivered_by_the_worker(ns):
|
||||
ns.as_user("alice")
|
||||
sid = f"{ns.tag}-recovered"
|
||||
ctx = ns.store.repo_for_session(sid, str(ns.root))
|
||||
ns.store.record_event(ctx, sid, "user_prompt", {"text": "Note that nightly builds are published from the release-bot machine at 02:00 UTC."})
|
||||
ns.store.record_event(ctx, sid, "tool_result", {"tool": "Edit", "path": "docs/releases.md"})
|
||||
ns.store.record_event(ctx, sid, "assistant_stop", {"text": "Documented that nightly builds are published from the release-bot machine at 02:00 UTC."})
|
||||
|
||||
pending = memory_core.data_dir() / "pending"
|
||||
pending.mkdir(parents=True, exist_ok=True)
|
||||
stale = pending / "stale-run.running"
|
||||
stale.write_text(json.dumps({"hook_input": {"session_id": sid, "cwd": str(ns.root)}, "reason": "session-end"}))
|
||||
os.utime(stale, (time.time() - 3600, time.time() - 3600))
|
||||
|
||||
assert hook.recover_pending_handoffs() == 1
|
||||
deadline = time.time() + 240
|
||||
while time.time() < deadline and list(pending.iterdir()):
|
||||
time.sleep(3)
|
||||
assert not list(pending.iterdir()), "worker left its packet behind"
|
||||
|
||||
found = ns.search("erin", ns.root, "when and where are nightly builds published", run_id=sid)
|
||||
assert "nightly" in _text(found) or "02:00" in _text(found)
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,236 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
PLUGIN_ROOT = Path(__file__).resolve().parents[1]
|
||||
CORE = PLUGIN_ROOT / "core"
|
||||
sys.path.insert(0, str(CORE))
|
||||
|
||||
import memory_core # noqa: E402
|
||||
import telemetry # noqa: E402
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def isolated_env(tmp_path, monkeypatch):
|
||||
monkeypatch.setenv("MEM0_CODE_DATA_DIR", str(tmp_path / "data"))
|
||||
monkeypatch.setenv("MEM0_TELEMETRY", "true")
|
||||
monkeypatch.delenv("MEM0_API_KEY", raising=False)
|
||||
monkeypatch.delenv("CLAUDE_PLUGIN_OPTION_API_KEY", raising=False)
|
||||
monkeypatch.delenv("CLAUDE_PLUGIN_OPTION_MEM0_API_KEY", raising=False)
|
||||
monkeypatch.delenv("MEM0_API_URL", raising=False)
|
||||
return tmp_path
|
||||
|
||||
|
||||
def repo() -> memory_core.RepoContext:
|
||||
return memory_core.RepoContext(
|
||||
cwd="/tmp/repo",
|
||||
root="/tmp/repo",
|
||||
identity="https://github.com/example/secret-repo",
|
||||
app_id="code-example",
|
||||
branch="main",
|
||||
head_sha="abc123",
|
||||
)
|
||||
|
||||
|
||||
def spool_lines() -> list[dict]:
|
||||
path = memory_core.data_dir() / "telemetry.jsonl"
|
||||
if not path.exists():
|
||||
return []
|
||||
return [json.loads(line) for line in path.read_text().splitlines()]
|
||||
|
||||
|
||||
def test_opt_out_writes_nothing(isolated_env, monkeypatch):
|
||||
for value in ("false", "0", "no", "OFF"):
|
||||
monkeypatch.setenv("MEM0_TELEMETRY", value)
|
||||
telemetry.record("search", repo=repo(), session_id="s-1")
|
||||
assert not telemetry.is_enabled()
|
||||
assert spool_lines() == []
|
||||
|
||||
|
||||
def test_record_hashes_identifiers_and_keeps_no_content(isolated_env):
|
||||
telemetry.record(
|
||||
"search",
|
||||
repo=repo(),
|
||||
session_id="session-abcdef",
|
||||
trigger="first-prompt-search",
|
||||
matched_count=3,
|
||||
dropped=None,
|
||||
)
|
||||
(event,) = spool_lines()
|
||||
assert event["event"] == "code.search"
|
||||
assert event["timestamp"]
|
||||
properties = event["properties"]
|
||||
assert properties["harness"] == "claude-code"
|
||||
assert properties["plugin_version"] == memory_core.PLUGIN_VERSION
|
||||
assert properties["matched_count"] == 3
|
||||
assert "dropped" not in properties
|
||||
assert len(properties["repo_hash"]) == 16
|
||||
assert len(properties["session_hash"]) == 16
|
||||
serialized = json.dumps(event)
|
||||
assert "secret-repo" not in serialized
|
||||
assert "session-abcdef" not in serialized
|
||||
|
||||
|
||||
def test_record_stops_appending_past_the_spool_cap(isolated_env):
|
||||
spool = memory_core.data_dir() / "telemetry.jsonl"
|
||||
spool.parent.mkdir(parents=True, exist_ok=True)
|
||||
spool.write_text("x" * (telemetry.SPOOL_LIMIT_BYTES + 1))
|
||||
telemetry.record("search")
|
||||
assert spool.read_text() == "x" * (telemetry.SPOOL_LIMIT_BYTES + 1)
|
||||
|
||||
|
||||
def test_record_never_raises_on_a_broken_spool(isolated_env, monkeypatch):
|
||||
monkeypatch.setattr(telemetry, "_spool_path", lambda: Path("/does/not/exist/x"))
|
||||
telemetry.record("search")
|
||||
|
||||
|
||||
def test_error_kind_stays_coarse_and_content_free():
|
||||
assert telemetry.error_kind("HTTP 429 too many requests") == "rate-limited"
|
||||
assert telemetry.error_kind("HTTP 401 for /v1/memories/") == "auth"
|
||||
assert telemetry.error_kind("HTTP 503 upstream") == "server-error"
|
||||
assert telemetry.error_kind(TimeoutError("timed out")) == "timeout"
|
||||
assert telemetry.error_kind(ValueError("token sk-abcdef leaked")) == "ValueError"
|
||||
|
||||
|
||||
def test_flush_posts_one_batch_and_clears_the_spool(isolated_env):
|
||||
telemetry.record("session_start")
|
||||
telemetry.record("search", matched_count=1)
|
||||
posted = []
|
||||
|
||||
with patch.object(telemetry, "_post", lambda payload, url: posted.append((payload, url)) or True):
|
||||
assert telemetry.flush() == 2
|
||||
|
||||
(payload, url) = posted[0]
|
||||
assert url == telemetry.POSTHOG_BATCH_URL
|
||||
assert payload["api_key"] == telemetry.POSTHOG_API_KEY
|
||||
assert [event["event"] for event in payload["batch"]] == [
|
||||
"code.session_start",
|
||||
"code.search",
|
||||
]
|
||||
first = payload["batch"][0]
|
||||
assert first["distinct_id"].startswith("code-anon-")
|
||||
assert first["properties"]["source"] == "CLAUDE_CODE_PLUGIN"
|
||||
assert first["properties"]["$process_person_profile"] is False
|
||||
assert not (memory_core.data_dir() / "telemetry.jsonl").exists()
|
||||
assert not list(memory_core.data_dir().glob("telemetry-*.sending"))
|
||||
|
||||
|
||||
def test_flush_chunks_batches(isolated_env):
|
||||
for index in range(telemetry.BATCH_SIZE + 5):
|
||||
telemetry.record("search", index=index)
|
||||
sizes = []
|
||||
|
||||
with patch.object(
|
||||
telemetry, "_post", lambda payload, url: sizes.append(len(payload["batch"])) or True
|
||||
):
|
||||
assert telemetry.flush() == telemetry.BATCH_SIZE + 5
|
||||
|
||||
assert sizes == [telemetry.BATCH_SIZE, 5]
|
||||
|
||||
|
||||
def test_a_failed_post_keeps_the_events_for_the_next_run(isolated_env):
|
||||
telemetry.record("search")
|
||||
|
||||
with patch.object(telemetry, "_post", lambda payload, url: False):
|
||||
assert telemetry.flush() == 0
|
||||
|
||||
claims = list(memory_core.data_dir().glob("telemetry-*.sending"))
|
||||
assert len(claims) == 1
|
||||
assert json.loads(claims[0].read_text().splitlines()[0])["event"] == "code.search"
|
||||
|
||||
|
||||
def test_a_claimed_spool_is_not_sent_twice(isolated_env):
|
||||
telemetry.record("search")
|
||||
first = telemetry._claim_spool()
|
||||
assert first is not None
|
||||
assert telemetry._claim_spool() is None
|
||||
|
||||
with patch.object(telemetry, "_post", lambda payload, url: True):
|
||||
assert telemetry.flush() == 0
|
||||
|
||||
|
||||
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
|
||||
)
|
||||
|
||||
with patch.object(telemetry, "_post", lambda payload, url: True):
|
||||
assert telemetry.flush() == 1
|
||||
|
||||
|
||||
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
|
||||
)
|
||||
assert telemetry._claim_spool() is None
|
||||
assert not list(memory_core.data_dir().glob("telemetry-*.sending"))
|
||||
|
||||
|
||||
def test_the_email_replaces_the_anonymous_id_once_and_is_aliased(isolated_env, monkeypatch):
|
||||
monkeypatch.setenv("MEM0_API_KEY", "test-key")
|
||||
anonymous = telemetry.anonymous_id()
|
||||
telemetry.record("search")
|
||||
posted = []
|
||||
|
||||
with (
|
||||
patch.object(telemetry, "_resolve_email", lambda key: "dev@example.com"),
|
||||
patch.object(telemetry, "_post", lambda payload, url: posted.append(payload) or True),
|
||||
):
|
||||
assert telemetry.flush() == 1
|
||||
|
||||
identify, batch = posted
|
||||
assert identify["event"] == "$identify"
|
||||
assert identify["distinct_id"] == "dev@example.com"
|
||||
assert identify["properties"]["$anon_distinct_id"] == anonymous
|
||||
assert batch["batch"][0]["distinct_id"] == "dev@example.com"
|
||||
|
||||
telemetry.record("search")
|
||||
posted.clear()
|
||||
with (
|
||||
patch.object(telemetry, "_resolve_email", lambda key: pytest.fail("re-resolved")),
|
||||
patch.object(telemetry, "_post", lambda payload, url: posted.append(payload) or True),
|
||||
):
|
||||
assert telemetry.flush() == 1
|
||||
assert [payload.get("event") for payload in posted] == [None]
|
||||
|
||||
|
||||
def test_an_unresolvable_key_falls_back_to_the_anonymous_id(isolated_env, monkeypatch):
|
||||
monkeypatch.setenv("MEM0_API_KEY", "test-key")
|
||||
telemetry.record("search")
|
||||
|
||||
with (
|
||||
patch.object(telemetry, "_resolve_email", lambda key: ""),
|
||||
patch.object(telemetry, "_post", lambda payload, url: True),
|
||||
):
|
||||
assert telemetry.flush() == 1
|
||||
|
||||
assert telemetry.resolve_distinct_id()[0].startswith("code-anon-")
|
||||
|
||||
|
||||
def test_is_first_run_flips_after_the_first_identity_write(isolated_env):
|
||||
assert telemetry.is_first_run()
|
||||
telemetry.anonymous_id()
|
||||
assert not telemetry.is_first_run()
|
||||
|
||||
|
||||
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
|
||||
popen.assert_not_called()
|
||||
|
||||
telemetry.record("search")
|
||||
with patch.object(telemetry.subprocess, "Popen") as popen:
|
||||
assert telemetry.spawn_flush() is True
|
||||
popen.assert_called_once()
|
||||
@@ -1,7 +0,0 @@
|
||||
# The DeepSeek Harness SDK (@deepseek-ai/dsh-tools) declares the rest of the
|
||||
# harness runtime (dsh-llm, dsh-agent, dsh-scope, ...) as peer dependencies.
|
||||
# The host harness provides those at runtime; this adapter only needs cordis +
|
||||
# dsh-tools to build and type-check. Auto-installing the full peer graph pulls
|
||||
# unpublished internal packages (e.g. dsh-type-meta), so keep it off.
|
||||
auto-install-peers=false
|
||||
package-manager-strict-version=false
|
||||
@@ -1,201 +0,0 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [2023] [Taranjeet Singh]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -1,62 +0,0 @@
|
||||
# deepseek-plugin
|
||||
|
||||
[Mem0](https://mem0.ai) long-term memory as a native [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness) (Cordis) plugin.
|
||||
|
||||
It gives a Harness agent two memory tools backed by the Mem0 SDK, so recall and writes persist across sessions:
|
||||
|
||||
| Tool | Does |
|
||||
|---|---|
|
||||
| `search_memory` | Recall facts from Mem0 relevant to a query |
|
||||
| `add_memory` | Store a fact in Mem0 for future sessions |
|
||||
|
||||
Unlike the local/file-based memory plugins in the ecosystem, Mem0 is a managed backend: server-side extraction, semantic dedup and conflict resolution, and the same memory bank reusable across Harness, Claude Code, Codex, and other agents.
|
||||
|
||||
## How it works
|
||||
|
||||
A Cordis plugin is a module exporting `apply(ctx, config)`. This one declares `inject = ['tools']` so it waits for the harness tool registry, then registers the two tools via `ctx.tools.register(defineTool(...))`. When the plugin unmounts, the tools are removed automatically (Cordis revertible effects).
|
||||
|
||||
```
|
||||
[ mem0ai SDK ] <-- managed memory, owned by Mem0
|
||||
|
|
||||
[ deepseek-plugin: apply(ctx) -> ctx.tools.register(...) ] <-- this package
|
||||
|
|
||||
[ DeepSeek Harness ] <-- the agent, loaded via cordis.yml
|
||||
```
|
||||
|
||||
## Try it locally
|
||||
|
||||
1. Build the plugin:
|
||||
```sh
|
||||
cd integrations/deepseek-plugin
|
||||
pnpm install
|
||||
pnpm build
|
||||
```
|
||||
2. Set your Mem0 key:
|
||||
```sh
|
||||
export MEM0_API_KEY=...
|
||||
```
|
||||
3. Point Harness at it. Copy `cordis.example.yml`, set the absolute path to `dist/index.js` and your `userId`, then:
|
||||
```sh
|
||||
pnpm dsh web --patch ./integrations/deepseek-plugin/cordis.example.yml
|
||||
```
|
||||
4. Open http://127.0.0.1:3080 and ask the agent to remember something, then recall it in a later turn.
|
||||
|
||||
For a Mem0 Platform on-prem or dedicated deployment, point `config.host` at that base URL (defaults to `api.mem0.ai`). `host` is a Platform base-URL override — it is not a switch to self-hosted Mem0 OSS, whose server exposes a different API surface.
|
||||
|
||||
## Configuration
|
||||
|
||||
| Field | Required | Default | Notes |
|
||||
|---|---|---|---|
|
||||
| `apiKey` | no | `$MEM0_API_KEY` | Mem0 platform API key |
|
||||
| `userId` | yes | | Entity that owns the memories |
|
||||
| `host` | no | `api.mem0.ai` | Platform base URL (on-prem / dedicated) |
|
||||
|
||||
## 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.
|
||||
|
||||
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`.
|
||||
|
||||
## Status
|
||||
|
||||
Developer preview. Tracks the DeepSeek Harness v0.1 plugin API (`@deepseek-ai/cordis`, `@deepseek-ai/dsh-tools`), which is young and moving; pin versions once it stabilizes. Auto-capture (store turns without an explicit tool call) and auto-recall (inject memory into the prompt at assembly) are planned once the harness session/assembly event API is confirmed.
|
||||
@@ -1,19 +0,0 @@
|
||||
# Example DeepSeek Harness config that loads deepseek-plugin alongside the built-in
|
||||
# tools plugin. Load with:
|
||||
#
|
||||
# pnpm dsh web --patch ./integrations/deepseek-plugin/cordis.example.yml
|
||||
#
|
||||
# The tools plugin (and its system-prompt dependency) must be present, because
|
||||
# the memory tools contribute schemas the system prompt renders.
|
||||
|
||||
- name: "@deepseek-ai/dsh-system-prompt"
|
||||
- name: "@deepseek-ai/dsh-tools"
|
||||
- insert:
|
||||
- id: mem0
|
||||
# Absolute path to the built plugin (run `pnpm build` first), or point
|
||||
# at src/index.ts when running through tsx during development.
|
||||
name: "/absolute/path/to/mem0/integrations/deepseek-plugin/dist/index.js"
|
||||
config:
|
||||
# apiKey is read from the MEM0_API_KEY env var when omitted here.
|
||||
userId: "your-user-id"
|
||||
# host: "https://your-onprem.mem0.ai" # optional: Platform on-prem / dedicated base URL
|
||||
@@ -1,59 +0,0 @@
|
||||
{
|
||||
"name": "@mem0/deepseek-plugin",
|
||||
"version": "0.1.1",
|
||||
"description": "Mem0 long-term memory as a native DeepSeek Harness (Cordis) plugin.",
|
||||
"type": "module",
|
||||
"license": "Apache-2.0",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/mem0ai/mem0",
|
||||
"directory": "integrations/deepseek-plugin"
|
||||
},
|
||||
"keywords": [
|
||||
"deepseek-harness",
|
||||
"dsh",
|
||||
"dsh-plugin",
|
||||
"cordis",
|
||||
"mem0",
|
||||
"memory",
|
||||
"agent"
|
||||
],
|
||||
"main": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"import": "./dist/index.js"
|
||||
}
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"files": [
|
||||
"dist",
|
||||
"src",
|
||||
"README.md",
|
||||
"LICENSE"
|
||||
],
|
||||
"scripts": {
|
||||
"build": "tsup",
|
||||
"test": "vitest run",
|
||||
"test:watch": "vitest",
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"mem0ai": "^3.0.7"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@deepseek-ai/cordis": "*",
|
||||
"@deepseek-ai/dsh-tools": "*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@deepseek-ai/cordis": "4.0.1",
|
||||
"@deepseek-ai/dsh-tools": "0.0.1-rc.1",
|
||||
"@types/node": "^22.15.0",
|
||||
"tsup": "^8.5.0",
|
||||
"typescript": "^5.6.0",
|
||||
"vitest": "^4.1.7"
|
||||
}
|
||||
}
|
||||
-2094
File diff suppressed because it is too large
Load Diff
@@ -1,69 +0,0 @@
|
||||
/**
|
||||
* Compact, token-cheap rendering of Mem0 results for the model context.
|
||||
*
|
||||
* Mirrors the format used by the sibling Mem0 plugins
|
||||
* (integrations/pi-agent-plugin/src/memory/formatting.ts) so a memory reads the
|
||||
* same way across every harness: `[category] text (age) [mem0:id]`. Dumping the
|
||||
* raw search envelope instead would spend most of the tokens on JSON scaffolding.
|
||||
*/
|
||||
|
||||
export interface MemoryLike {
|
||||
id: string;
|
||||
memory?: string;
|
||||
categories?: string[];
|
||||
createdAt?: Date | string;
|
||||
}
|
||||
|
||||
export function formatAge(date: Date | string): string {
|
||||
const d = typeof date === "string" ? new Date(date) : date;
|
||||
const ms = Date.now() - d.getTime();
|
||||
const minutes = Math.floor(ms / 60_000);
|
||||
if (minutes < 60) return `${minutes}m ago`;
|
||||
const hours = Math.floor(minutes / 60);
|
||||
if (hours < 24) return `${hours}h ago`;
|
||||
const days = Math.floor(hours / 24);
|
||||
return `${days}d ago`;
|
||||
}
|
||||
|
||||
export function formatMemoryCompact(mem: MemoryLike): string {
|
||||
const cat = mem.categories?.[0] ?? "uncategorized";
|
||||
const age = mem.createdAt ? ` (${formatAge(mem.createdAt)})` : "";
|
||||
return `[${cat}] ${mem.memory ?? "(empty)"}${age} [mem0:${mem.id}]`;
|
||||
}
|
||||
|
||||
export function formatMemoryList(memories: MemoryLike[]): string {
|
||||
if (memories.length === 0) return "No memories found.";
|
||||
return memories
|
||||
.map((m, i) => `${i + 1}. ${formatMemoryCompact(m)}`)
|
||||
.join("\n");
|
||||
}
|
||||
|
||||
/**
|
||||
* One-line confirmation for a write.
|
||||
*
|
||||
* `client.add` hits the async `/v3/memories/add/` endpoint, which returns
|
||||
* `{ event_id, status: "PENDING" }` — extraction runs server-side *after* the
|
||||
* call returns, so the extracted memories are not in this response. Report the
|
||||
* write as queued in that case; only render a list when the backend actually
|
||||
* returns memories (older / OSS shapes).
|
||||
*/
|
||||
export function formatAddResult(result: unknown): string {
|
||||
const items: MemoryLike[] = Array.isArray(result)
|
||||
? (result as MemoryLike[])
|
||||
: ((result as { results?: MemoryLike[] } | null)?.results ??
|
||||
(result ? [result as MemoryLike] : []));
|
||||
|
||||
const pending = items.find(
|
||||
(r) => (r as { status?: string }).status === "PENDING",
|
||||
) as { eventId?: string; event_id?: string } | undefined;
|
||||
if (pending) {
|
||||
// The SDK camel-cases response keys (event_id -> eventId); accept either.
|
||||
const id = pending.eventId ?? pending.event_id;
|
||||
const evt = id ? ` (event ${id})` : "";
|
||||
return `Memory queued for background extraction${evt}; it will be searchable shortly.`;
|
||||
}
|
||||
|
||||
if (items.length === 0) return "Memory stored.";
|
||||
const noun = items.length === 1 ? "memory" : "memories";
|
||||
return `Stored ${items.length} ${noun}:\n${formatMemoryList(items)}`;
|
||||
}
|
||||
@@ -1,190 +0,0 @@
|
||||
/**
|
||||
* deepseek-plugin: Mem0 long-term memory as a native DeepSeek Harness (Cordis) plugin.
|
||||
*
|
||||
* Registers two agent-callable tools backed by the Mem0 SDK:
|
||||
* - `search_memory` recalls facts relevant to a query
|
||||
* - `add_memory` stores a fact for future sessions
|
||||
*
|
||||
* A plugin is a Cordis module that exports `apply(ctx, config)`. Declaring
|
||||
* `inject = ['tools']` holds the plugin until the harness tool registry exists;
|
||||
* tools registered via `ctx.tools.register(...)` are auto-unregistered when the
|
||||
* plugin unmounts (Cordis revertible effects).
|
||||
*/
|
||||
import type { Context } from "@deepseek-ai/cordis";
|
||||
import { defineTool } from "@deepseek-ai/dsh-tools";
|
||||
import { MemoryClient } from "mem0ai";
|
||||
import { formatMemoryList, formatAddResult } from "./formatting.ts";
|
||||
import { truncateOutput } from "./output.ts";
|
||||
import { resolveSearchFilters, resolveAddParams } from "./scoping.ts";
|
||||
import { captureEvent, errorKind } from "./telemetry.ts";
|
||||
|
||||
export const name = "mem0";
|
||||
export const inject = ["tools"];
|
||||
|
||||
// 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).
|
||||
const SOURCE = "DEEPSEEK_HARNESS";
|
||||
|
||||
const DEFAULT_SEARCH_LIMIT = 10;
|
||||
|
||||
export interface Config {
|
||||
/** Mem0 API key. Defaults to the MEM0_API_KEY env var. */
|
||||
apiKey?: string;
|
||||
/** Default entity that owns the memories (Mem0 user scope). */
|
||||
userId: string;
|
||||
/** Optional Mem0 Platform base-URL override (on-prem / dedicated); defaults to api.mem0.ai. Not a switch to self-hosted OSS. */
|
||||
host?: string;
|
||||
}
|
||||
|
||||
// Both tools return a single text string; the render is identical, so lift it
|
||||
// into one shared declaration instead of repeating the block per tool.
|
||||
const textOutput = {
|
||||
schema: { type: "string" } as const,
|
||||
render: (_args: unknown, value: string) => [
|
||||
{ type: "text" as const, text: value },
|
||||
],
|
||||
};
|
||||
|
||||
// Optional per-call scoping params, shared by both tools. A single harness
|
||||
// install can serve more than one entity, so the model may override the
|
||||
// mount-time default per call (see scoping.ts).
|
||||
const scopeParams = {
|
||||
userId: {
|
||||
type: "string",
|
||||
description:
|
||||
"Entity that owns the memory. Defaults to the plugin's configured userId; set this only to read or write another user's memories.",
|
||||
},
|
||||
agentId: {
|
||||
type: "string",
|
||||
description: "Optional agent scope, to partition memories by agent.",
|
||||
},
|
||||
runId: {
|
||||
type: "string",
|
||||
description: "Optional run/session scope, to partition memories by session.",
|
||||
},
|
||||
} as const;
|
||||
|
||||
export function apply(ctx: Context, config: Config): void {
|
||||
const apiKey = config.apiKey ?? process.env.MEM0_API_KEY;
|
||||
if (!apiKey) {
|
||||
throw new Error("deepseek-plugin: set config.apiKey or the MEM0_API_KEY env var");
|
||||
}
|
||||
const userId = config.userId;
|
||||
if (!userId) {
|
||||
throw new Error("deepseek-plugin: config.userId is required");
|
||||
}
|
||||
|
||||
const client = new MemoryClient({
|
||||
apiKey,
|
||||
...(config.host ? { host: config.host } : {}),
|
||||
});
|
||||
|
||||
captureEvent("deepseek.plugin.mounted", { has_host: Boolean(config.host) }, client);
|
||||
|
||||
// Recall. The platform rejects top-level entity params on search, so scope
|
||||
// goes inside `filters` (unlike add below, which takes them top-level).
|
||||
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.",
|
||||
parameters: {
|
||||
query: { type: "string", description: "What to recall.", required: true },
|
||||
limit: {
|
||||
type: "integer",
|
||||
description: `Max results to return (default ${DEFAULT_SEARCH_LIMIT}).`,
|
||||
},
|
||||
...scopeParams,
|
||||
},
|
||||
output: textOutput,
|
||||
async execute({ query, limit, userId: u, agentId, runId }) {
|
||||
const filters = resolveSearchFilters({ userId: u, agentId, runId }, userId);
|
||||
const topK = limit && limit > 0 ? limit : DEFAULT_SEARCH_LIMIT;
|
||||
const started = Date.now();
|
||||
try {
|
||||
const { results } = await client.search(query, { filters, topK });
|
||||
captureEvent(
|
||||
"deepseek.tool.search_memory",
|
||||
{
|
||||
success: true,
|
||||
duration_ms: Date.now() - started,
|
||||
top_k: topK,
|
||||
result_count: results?.length ?? 0,
|
||||
query_chars: query.length,
|
||||
scope_overridden: Boolean(u && u !== userId),
|
||||
has_agent_id: Boolean(agentId),
|
||||
has_run_id: Boolean(runId),
|
||||
},
|
||||
client,
|
||||
);
|
||||
return truncateOutput(formatMemoryList(results ?? []));
|
||||
} catch (err) {
|
||||
captureEvent(
|
||||
"deepseek.tool.search_memory",
|
||||
{
|
||||
success: false,
|
||||
duration_ms: Date.now() - started,
|
||||
top_k: topK,
|
||||
error_kind: errorKind(err),
|
||||
},
|
||||
client,
|
||||
);
|
||||
return `search_memory failed: ${err instanceof Error ? err.message : String(err)}`;
|
||||
}
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
// Write. `source` tags the memory for telemetry attribution.
|
||||
ctx.tools.register(
|
||||
defineTool({
|
||||
name: "add_memory",
|
||||
description:
|
||||
"Store a fact in the user's long-term Mem0 memory for later sessions. Extraction runs asynchronously server-side, so a stored fact may take a moment to become searchable; do not immediately search to confirm the write.",
|
||||
parameters: {
|
||||
text: { type: "string", description: "The fact to remember.", required: true },
|
||||
...scopeParams,
|
||||
},
|
||||
output: textOutput,
|
||||
async execute({ text, userId: u, agentId, runId }) {
|
||||
const addParams = resolveAddParams({ userId: u, agentId, runId }, userId);
|
||||
const started = Date.now();
|
||||
try {
|
||||
const result = await client.add([{ role: "user", content: text }], {
|
||||
...addParams,
|
||||
source: SOURCE,
|
||||
});
|
||||
captureEvent(
|
||||
"deepseek.tool.add_memory",
|
||||
{
|
||||
success: true,
|
||||
duration_ms: Date.now() - started,
|
||||
text_chars: text.length,
|
||||
memory_count: Array.isArray(result) ? result.length : 0,
|
||||
scope_overridden: Boolean(u && u !== userId),
|
||||
has_agent_id: Boolean(agentId),
|
||||
has_run_id: Boolean(runId),
|
||||
},
|
||||
client,
|
||||
);
|
||||
return truncateOutput(formatAddResult(result));
|
||||
} catch (err) {
|
||||
captureEvent(
|
||||
"deepseek.tool.add_memory",
|
||||
{
|
||||
success: false,
|
||||
duration_ms: Date.now() - started,
|
||||
text_chars: text.length,
|
||||
error_kind: errorKind(err),
|
||||
},
|
||||
client,
|
||||
);
|
||||
return `add_memory failed: ${err instanceof Error ? err.message : String(err)}`;
|
||||
}
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
/**
|
||||
* Hard cap on tool output before it reaches the model context.
|
||||
*
|
||||
* Same guard the sibling plugins apply (200 lines / 50KB, see
|
||||
* integrations/pi-agent-plugin/src/memory/tools.ts): a large recall or a wide
|
||||
* result set can otherwise flood the context window in a single tool call.
|
||||
*/
|
||||
|
||||
export const MAX_OUTPUT_LINES = 200;
|
||||
export const MAX_OUTPUT_BYTES = 50_000;
|
||||
|
||||
export function truncateOutput(text: string): string {
|
||||
const lines = text.split("\n");
|
||||
if (lines.length <= MAX_OUTPUT_LINES && text.length <= MAX_OUTPUT_BYTES) {
|
||||
return text;
|
||||
}
|
||||
|
||||
const kept = lines.slice(0, MAX_OUTPUT_LINES);
|
||||
let result = kept.join("\n");
|
||||
const byteCapped = result.length > MAX_OUTPUT_BYTES;
|
||||
if (byteCapped) {
|
||||
result = result.slice(0, MAX_OUTPUT_BYTES);
|
||||
}
|
||||
|
||||
const dropped = lines.length - kept.length;
|
||||
const reasons: string[] = [];
|
||||
if (dropped > 0) reasons.push(`showing ${kept.length} of ${lines.length} lines`);
|
||||
if (byteCapped) reasons.push(`cut at ${Math.floor(MAX_OUTPUT_BYTES / 1000)}KB`);
|
||||
if (reasons.length > 0) {
|
||||
result += `\n\n[Output truncated: ${reasons.join(", ")}]`;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
/**
|
||||
* Per-call memory scoping.
|
||||
*
|
||||
* The plugin is mounted with one default `userId`, but a single harness install
|
||||
* can serve more than one entity, so both tools accept optional `userId` /
|
||||
* `agentId` / `runId` params that override the mount-time default per call.
|
||||
* A missing or blank param falls back to the configured user.
|
||||
*
|
||||
* The two call sites need different key casing, and it is deliberate rather than
|
||||
* incidental: search passes scope inside `filters`, sent to the platform raw, so
|
||||
* it must be snake_case; add takes the entity params top-level, through the
|
||||
* SDK's camel->snake converter, so it must be camelCase. Keeping the split
|
||||
* explicit (like integrations/pi-agent-plugin/src/memory/scoping.ts) means the
|
||||
* asymmetry is visible in the code, not load-bearing on a converter no-op.
|
||||
*/
|
||||
|
||||
export interface EntityParams {
|
||||
userId?: string;
|
||||
agentId?: string;
|
||||
runId?: string;
|
||||
}
|
||||
|
||||
const clean = (v: string | undefined) => v?.trim() || undefined;
|
||||
|
||||
/** Search: snake_case, spread into `filters` and passed to the platform raw. */
|
||||
export function resolveSearchFilters(
|
||||
params: EntityParams,
|
||||
defaultUserId: string,
|
||||
): Record<string, string> {
|
||||
const filters: Record<string, string> = {
|
||||
user_id: clean(params.userId) ?? defaultUserId,
|
||||
};
|
||||
const agentId = clean(params.agentId);
|
||||
if (agentId) filters.agent_id = agentId;
|
||||
const runId = clean(params.runId);
|
||||
if (runId) filters.run_id = runId;
|
||||
return filters;
|
||||
}
|
||||
|
||||
/** Add: camelCase, top-level params run through the SDK's camel->snake converter. */
|
||||
export function resolveAddParams(
|
||||
params: EntityParams,
|
||||
defaultUserId: string,
|
||||
): Record<string, string> {
|
||||
const out: Record<string, string> = {
|
||||
userId: clean(params.userId) ?? defaultUserId,
|
||||
};
|
||||
const agentId = clean(params.agentId);
|
||||
if (agentId) out.agentId = agentId;
|
||||
const runId = clean(params.runId);
|
||||
if (runId) out.runId = runId;
|
||||
return out;
|
||||
}
|
||||
@@ -1,173 +0,0 @@
|
||||
/**
|
||||
* Anonymous usage telemetry for the DeepSeek Harness plugin.
|
||||
*
|
||||
* Fire-and-forget PostHog events over native fetch, batched and flushed every
|
||||
* 5 seconds, at 10 queued events, or on process exit. Never throws, never logs.
|
||||
*
|
||||
* Events carry only tool names, durations, counts, and coarse failure kinds:
|
||||
* never queries, memory text, filters, or API keys.
|
||||
*
|
||||
* Disable with MEM0_TELEMETRY=false.
|
||||
*/
|
||||
import { randomUUID } from "node:crypto";
|
||||
import * as fs from "node:fs";
|
||||
import * as os from "node:os";
|
||||
import * as path from "node:path";
|
||||
|
||||
const POSTHOG_API_KEY = "phc_hgJkUVJFYtmaJqrvf6CYN67TIQ8yhXAkWzUn9AMU4yX";
|
||||
const POSTHOG_BATCH_URL = "https://us.i.posthog.com/batch/";
|
||||
const FLUSH_INTERVAL_MS = 5_000;
|
||||
const FLUSH_THRESHOLD = 10;
|
||||
const SEND_TIMEOUT_MS = 3_000;
|
||||
|
||||
const PLUGIN_VERSION = ((): string => {
|
||||
try {
|
||||
return JSON.parse(
|
||||
fs.readFileSync(new URL("../package.json", import.meta.url), "utf-8"),
|
||||
).version;
|
||||
} catch {
|
||||
return "unknown";
|
||||
}
|
||||
})();
|
||||
|
||||
/** The Mem0 SDK resolves this to the account email once ping() lands, so events join other Mem0 surfaces. */
|
||||
export interface TelemetryIdentity {
|
||||
telemetryId?: string;
|
||||
}
|
||||
|
||||
let queue: Record<string, unknown>[] = [];
|
||||
let flushTimer: ReturnType<typeof setInterval> | undefined;
|
||||
let exitHandlerInstalled = false;
|
||||
let cachedAnonymousId: string | undefined;
|
||||
let identified = false;
|
||||
|
||||
function identityPath(): string {
|
||||
return path.join(os.homedir(), ".mem0", "deepseek-plugin-telemetry.json");
|
||||
}
|
||||
|
||||
export function isTelemetryEnabled(): boolean {
|
||||
const value = process.env.MEM0_TELEMETRY?.toLowerCase();
|
||||
return value !== "false" && value !== "0" && value !== "no" && value !== "off";
|
||||
}
|
||||
|
||||
function anonymousId(): string {
|
||||
if (cachedAnonymousId) return cachedAnonymousId;
|
||||
try {
|
||||
const stored = JSON.parse(fs.readFileSync(identityPath(), "utf-8"));
|
||||
if (typeof stored.anonymousId === "string" && stored.anonymousId) {
|
||||
cachedAnonymousId = stored.anonymousId;
|
||||
return cachedAnonymousId!;
|
||||
}
|
||||
} catch {
|
||||
/* first run, or an unreadable identity file */
|
||||
}
|
||||
const created = `deepseek-anon-${randomUUID().replace(/-/g, "")}`;
|
||||
try {
|
||||
const target = identityPath();
|
||||
fs.mkdirSync(path.dirname(target), { recursive: true });
|
||||
fs.writeFileSync(target, JSON.stringify({ anonymousId: created }), "utf-8");
|
||||
} catch {
|
||||
/* an unwritable home directory must not break the plugin */
|
||||
}
|
||||
cachedAnonymousId = created;
|
||||
return created;
|
||||
}
|
||||
|
||||
/** Merge the pre-ping anonymous history into the account once the email resolves. */
|
||||
function identifyEvent(distinctId: string): Record<string, unknown> | undefined {
|
||||
if (identified || distinctId.startsWith("deepseek-anon-")) return undefined;
|
||||
identified = true;
|
||||
let storedAnonymousId: string | undefined;
|
||||
try {
|
||||
storedAnonymousId = JSON.parse(fs.readFileSync(identityPath(), "utf-8")).anonymousId;
|
||||
fs.unlinkSync(identityPath());
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
cachedAnonymousId = undefined;
|
||||
if (!storedAnonymousId) return undefined;
|
||||
return {
|
||||
event: "$identify",
|
||||
distinct_id: distinctId,
|
||||
properties: { $anon_distinct_id: storedAnonymousId, $lib: "posthog-node" },
|
||||
};
|
||||
}
|
||||
|
||||
export function flushEvents(): void {
|
||||
if (queue.length === 0) return;
|
||||
const batch = queue;
|
||||
queue = [];
|
||||
fetch(POSTHOG_BATCH_URL, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ api_key: POSTHOG_API_KEY, batch }),
|
||||
signal: AbortSignal.timeout(SEND_TIMEOUT_MS),
|
||||
}).catch(() => {
|
||||
/* telemetry never surfaces its own failures */
|
||||
});
|
||||
}
|
||||
|
||||
function scheduleFlush(): void {
|
||||
if (!flushTimer) {
|
||||
flushTimer = setInterval(flushEvents, FLUSH_INTERVAL_MS);
|
||||
flushTimer.unref?.();
|
||||
}
|
||||
if (!exitHandlerInstalled) {
|
||||
exitHandlerInstalled = true;
|
||||
process.on("beforeExit", flushEvents);
|
||||
}
|
||||
}
|
||||
|
||||
export function errorKind(error: unknown): string {
|
||||
const text = (error instanceof Error ? error.message : String(error)).toLowerCase();
|
||||
if (text.includes("timeout") || text.includes("aborted")) return "timeout";
|
||||
if (text.includes("401") || text.includes("403") || text.includes("unauthor")) return "auth";
|
||||
if (text.includes("429") || text.includes("rate limit")) return "rate-limited";
|
||||
if (/50[0234]/.test(text)) return "server-error";
|
||||
if (text.includes("400") || text.includes("422")) return "bad-request";
|
||||
if (text.includes("fetch failed") || text.includes("enotfound")) return "network";
|
||||
return error instanceof Error ? error.constructor.name : "other";
|
||||
}
|
||||
|
||||
export function captureEvent(
|
||||
event: string,
|
||||
properties: Record<string, unknown>,
|
||||
client: TelemetryIdentity,
|
||||
): void {
|
||||
if (!isTelemetryEnabled()) return;
|
||||
try {
|
||||
const distinctId = client.telemetryId || anonymousId();
|
||||
const identify = identifyEvent(distinctId);
|
||||
if (identify) queue.push(identify);
|
||||
queue.push({
|
||||
event,
|
||||
distinct_id: distinctId,
|
||||
properties: {
|
||||
source: "DEEPSEEK_HARNESS",
|
||||
language: "node",
|
||||
plugin_version: PLUGIN_VERSION,
|
||||
node_version: process.version,
|
||||
os: process.platform,
|
||||
$process_person_profile: false,
|
||||
$lib: "posthog-node",
|
||||
...properties,
|
||||
},
|
||||
});
|
||||
scheduleFlush();
|
||||
if (queue.length >= FLUSH_THRESHOLD) flushEvents();
|
||||
} catch {
|
||||
/* telemetry never breaks a tool call */
|
||||
}
|
||||
}
|
||||
|
||||
export function _queueForTesting(): Record<string, unknown>[] {
|
||||
return queue;
|
||||
}
|
||||
|
||||
export function _resetForTesting(): void {
|
||||
queue = [];
|
||||
clearInterval(flushTimer);
|
||||
flushTimer = undefined;
|
||||
cachedAnonymousId = undefined;
|
||||
identified = false;
|
||||
}
|
||||
@@ -1,148 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
||||
|
||||
// Offline mock of the Mem0 SDK so these tests never touch the network.
|
||||
const mockSearch = vi.fn();
|
||||
const mockAdd = vi.fn();
|
||||
vi.mock("mem0ai", () => ({
|
||||
MemoryClient: class {
|
||||
search = mockSearch;
|
||||
add = mockAdd;
|
||||
},
|
||||
}));
|
||||
|
||||
// The real `@deepseek-ai/dsh-tools` runtime transitively imports harness peer
|
||||
// packages the host provides at runtime but which aren't installed here. For
|
||||
// these unit tests we only need `defineTool` to hand back the definition it was
|
||||
// given, so the registered tool's `execute`/`name` can be exercised directly.
|
||||
vi.mock("@deepseek-ai/dsh-tools", () => ({
|
||||
defineTool: (options: unknown) => options,
|
||||
}));
|
||||
|
||||
import { apply, type Config } from "../src/index.ts";
|
||||
|
||||
interface RegisteredTool {
|
||||
name: string;
|
||||
execute(args: unknown, exec: unknown): Promise<unknown>;
|
||||
}
|
||||
|
||||
function applyAndCollect(config: Config): Map<string, RegisteredTool> {
|
||||
const tools = new Map<string, RegisteredTool>();
|
||||
const ctx = {
|
||||
tools: { register: (t: RegisteredTool) => tools.set(t.name, t) },
|
||||
};
|
||||
apply(ctx as never, config);
|
||||
return tools;
|
||||
}
|
||||
|
||||
let savedKey: string | undefined;
|
||||
let savedTelemetry: string | undefined;
|
||||
|
||||
beforeEach(() => {
|
||||
savedKey = process.env.MEM0_API_KEY;
|
||||
savedTelemetry = process.env.MEM0_TELEMETRY;
|
||||
process.env.MEM0_TELEMETRY = "false";
|
||||
mockSearch.mockReset();
|
||||
mockAdd.mockReset();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
if (savedKey === undefined) delete process.env.MEM0_API_KEY;
|
||||
else process.env.MEM0_API_KEY = savedKey;
|
||||
if (savedTelemetry === undefined) delete process.env.MEM0_TELEMETRY;
|
||||
else process.env.MEM0_TELEMETRY = savedTelemetry;
|
||||
});
|
||||
|
||||
describe("apply() config validation", () => {
|
||||
it("throws when no apiKey is set and MEM0_API_KEY is absent", () => {
|
||||
delete process.env.MEM0_API_KEY;
|
||||
expect(() => applyAndCollect({ userId: "u" } as Config)).toThrow(/apiKey|MEM0_API_KEY/);
|
||||
});
|
||||
|
||||
it("throws when userId is missing", () => {
|
||||
expect(() => applyAndCollect({ apiKey: "k", userId: "" } as Config)).toThrow(/userId/);
|
||||
});
|
||||
|
||||
it("registers both memory tools", () => {
|
||||
const tools = applyAndCollect({ apiKey: "k", userId: "u" });
|
||||
expect([...tools.keys()].sort()).toEqual(["add_memory", "search_memory"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("search_memory tool", () => {
|
||||
it("returns a formatted list scoped to the configured user", async () => {
|
||||
mockSearch.mockResolvedValue({
|
||||
results: [{ id: "m1", memory: "Likes tea", categories: ["preference"] }],
|
||||
});
|
||||
const tools = applyAndCollect({ apiKey: "k", userId: "u" });
|
||||
|
||||
const out = await tools.get("search_memory")!.execute({ query: "drink" }, {});
|
||||
|
||||
expect(out).toContain("Likes tea");
|
||||
expect(out).toContain("[mem0:m1]");
|
||||
expect(mockSearch).toHaveBeenCalledWith("drink", {
|
||||
filters: { user_id: "u" },
|
||||
topK: 10,
|
||||
});
|
||||
});
|
||||
|
||||
it("honors a per-call userId override and limit", async () => {
|
||||
mockSearch.mockResolvedValue({ results: [] });
|
||||
const tools = applyAndCollect({ apiKey: "k", userId: "u" });
|
||||
|
||||
await tools.get("search_memory")!.execute({ query: "x", userId: "alice", limit: 3 }, {});
|
||||
|
||||
expect(mockSearch).toHaveBeenCalledWith("x", {
|
||||
filters: { user_id: "alice" },
|
||||
topK: 3,
|
||||
});
|
||||
});
|
||||
|
||||
it("returns a graceful failure line instead of rejecting on error", async () => {
|
||||
mockSearch.mockRejectedValue(new Error("network down"));
|
||||
const tools = applyAndCollect({ apiKey: "k", userId: "u" });
|
||||
|
||||
const out = await tools.get("search_memory")!.execute({ query: "x" }, {});
|
||||
|
||||
expect(out).toContain("search_memory failed");
|
||||
expect(out).toContain("network down");
|
||||
});
|
||||
});
|
||||
|
||||
describe("add_memory tool", () => {
|
||||
it("reports the write as queued on the async PENDING response, with camelCase scope + source", async () => {
|
||||
// The real /v3/memories/add/ response — not an array of memories. The SDK
|
||||
// camel-cases response keys, so it surfaces as `eventId`, not `event_id`.
|
||||
mockAdd.mockResolvedValue({ eventId: "evt-123", status: "PENDING" });
|
||||
const tools = applyAndCollect({ apiKey: "k", userId: "u" });
|
||||
|
||||
const out = await tools.get("add_memory")!.execute({ text: "remember this" }, {});
|
||||
|
||||
expect(out).toContain("queued");
|
||||
expect(out).toContain("evt-123");
|
||||
expect(out).not.toContain("No new distinct memory");
|
||||
expect(mockAdd).toHaveBeenCalledWith(
|
||||
[{ role: "user", content: "remember this" }],
|
||||
{ userId: "u", source: "DEEPSEEK_HARNESS" },
|
||||
);
|
||||
});
|
||||
|
||||
it("renders a list when the backend returns memories", async () => {
|
||||
mockAdd.mockResolvedValue([{ id: "m1", memory: "Fact" }]);
|
||||
const tools = applyAndCollect({ apiKey: "k", userId: "u" });
|
||||
|
||||
const out = await tools.get("add_memory")!.execute({ text: "x" }, {});
|
||||
|
||||
expect(out).toContain("Stored 1 memory");
|
||||
expect(out).toContain("[mem0:m1]");
|
||||
});
|
||||
|
||||
it("returns a graceful failure line on error", async () => {
|
||||
mockAdd.mockRejectedValue(new Error("boom"));
|
||||
const tools = applyAndCollect({ apiKey: "k", userId: "u" });
|
||||
|
||||
const out = await tools.get("add_memory")!.execute({ text: "x" }, {});
|
||||
|
||||
expect(out).toContain("add_memory failed");
|
||||
expect(out).toContain("boom");
|
||||
});
|
||||
});
|
||||
@@ -1,71 +0,0 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import {
|
||||
formatAge,
|
||||
formatMemoryCompact,
|
||||
formatMemoryList,
|
||||
formatAddResult,
|
||||
} from "../src/formatting.ts";
|
||||
|
||||
describe("formatAge", () => {
|
||||
it("formats minutes, hours, and days", () => {
|
||||
expect(formatAge(new Date(Date.now() - 30 * 60_000))).toBe("30m ago");
|
||||
expect(formatAge(new Date(Date.now() - 3 * 3_600_000))).toBe("3h ago");
|
||||
expect(formatAge(new Date(Date.now() - 5 * 86_400_000))).toBe("5d ago");
|
||||
});
|
||||
});
|
||||
|
||||
describe("formatMemoryCompact", () => {
|
||||
it("renders one line with category, text, and id", () => {
|
||||
const line = formatMemoryCompact({
|
||||
id: "abc-123",
|
||||
memory: "User prefers dark mode",
|
||||
categories: ["preference"],
|
||||
createdAt: new Date(),
|
||||
});
|
||||
expect(line).toContain("[preference]");
|
||||
expect(line).toContain("User prefers dark mode");
|
||||
expect(line).toContain("[mem0:abc-123]");
|
||||
});
|
||||
|
||||
it("falls back to uncategorized and (empty)", () => {
|
||||
expect(formatMemoryCompact({ id: "x" })).toContain("[uncategorized]");
|
||||
expect(formatMemoryCompact({ id: "x" })).toContain("(empty)");
|
||||
});
|
||||
});
|
||||
|
||||
describe("formatMemoryList", () => {
|
||||
it("numbers multiple memories", () => {
|
||||
const output = formatMemoryList([
|
||||
{ id: "id-1", memory: "Fact one", categories: ["insight"] },
|
||||
{ id: "id-2", memory: "Fact two", categories: ["convention"] },
|
||||
]);
|
||||
expect(output).toContain("1.");
|
||||
expect(output).toContain("2.");
|
||||
});
|
||||
|
||||
it("returns a plain message when there are no memories", () => {
|
||||
expect(formatMemoryList([])).toBe("No memories found.");
|
||||
});
|
||||
});
|
||||
|
||||
describe("formatAddResult", () => {
|
||||
it("reports queued for the async PENDING response, with the event id", () => {
|
||||
// SDK camel-cases response keys, so the real shape is `eventId`.
|
||||
const out = formatAddResult({ eventId: "evt-9", status: "PENDING" });
|
||||
expect(out).toContain("queued");
|
||||
expect(out).toContain("evt-9");
|
||||
});
|
||||
|
||||
it("reports the stored count when the backend returns memories", () => {
|
||||
expect(formatAddResult([{ id: "1", memory: "A" }])).toContain("Stored 1 memory");
|
||||
expect(formatAddResult([{ id: "1" }, { id: "2" }])).toContain("Stored 2 memories");
|
||||
});
|
||||
|
||||
it("unwraps a { results: [...] } envelope", () => {
|
||||
expect(formatAddResult({ results: [{ id: "1", memory: "A" }] })).toContain("Stored 1 memory");
|
||||
});
|
||||
|
||||
it("handles an empty result", () => {
|
||||
expect(formatAddResult([])).toBe("Memory stored.");
|
||||
});
|
||||
});
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user