feat(ci): gate pull requests on an accepted issue (#6894)

This commit is contained in:
Kartik
2026-08-14 17:05:27 +05:30
committed by GitHub
parent ef6f51d977
commit 290de24bb8
35 changed files with 2029 additions and 967 deletions
+102
View File
@@ -0,0 +1,102 @@
# CI/CD and repository automation (`.github/`)
> **Do not modify any workflow without explicit approval from a maintainer.** Publishing
> credentials are bound to workflow filenames, and the gate workflows decide whether
> contributions are accepted. Read this file before proposing any change here.
## CI: one gate, many pipelines
`ci-gate.yml` (**CI Gate**) is the single entry point. It runs on every PR, detects which packages changed, and calls only the relevant package workflows as reusable workflows (`workflow_call`). Its final `CI Gate` job aggregates the results: skipped pipelines pass, failed or cancelled ones fail. It is the **only CI status check that needs to be required** in branch protection.
Package workflows keep their own push-to-main and manual triggers. Their `pull_request` triggers live in the gate's path filters instead.
| Workflow | File | Standalone triggers | Runs |
|----------|------|---------------------|------|
| CI Gate | `ci-gate.yml` | All PRs | Routes to and aggregates everything below |
| Python SDK | `ci.yml` | Push to main | Ruff + pytest on Python 3.10, 3.11, 3.12 |
| TypeScript SDK | `ts-sdk-ci.yml` | Push to main (`mem0-ts/`) | Prettier + build + jest on Node 20, 22 |
| 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 | `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 |
| 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 |
| docs llms.txt | `docs-llms-txt-check.yml` | Manual | `docs/llms.txt` coverage |
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.
## 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:
| Context | Posted by | Why |
|---------|-----------|-----|
| `CI Gate` | `ci-gate.yml` | Aggregates every package pipeline |
| `license/cla` | CLA Assistant | Proves the CLA is signed, not merely requested |
Editing the ruleset requires repo **admin**. `maintain` is not enough, and the API returns 404 rather than 403 in that case. Until `license/cla` is required, the claim in `CONTRIBUTING.md` that unsigned PRs are blocked from merging holds by convention only.
Requiring `CI Gate` also means fork PRs from first-time contributors cannot merge until a maintainer approves the workflow run. Those sit at `action_required`, which is intended behavior.
## CD: one router, many publishers
`release.yml` (**Release Router**) is the only workflow listening to `release: published`. It matches the tag prefix and dispatches the matching package workflow through `workflow_dispatch`, so one release produces exactly one routed run.
| Workflow | File | Tag prefix | Target |
|----------|------|------------|--------|
| Release Router | `release.yml` | all releases | dispatches the rows below |
| Python SDK | `cd.yml` | `v*` | PyPI (`mem0ai`) |
| TypeScript SDK | `ts-sdk-cd.yml` | `ts-v*` | npm (`mem0ai`) |
| Python CLI | `cli-python-cd.yml` | `cli-v*` | PyPI (`mem0-cli`) |
| Node CLI | `cli-node-cd.yml` | `cli-node-v*` | npm (`@mem0/cli`) |
| Vercel AI SDK | `vercel-ai-cd.yml` | `vercel-ai-v*` | npm (`@mem0/vercel-ai-provider`) |
| 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`) |
| n8n Node | `n8n-nodes-mem0-cd.yml` | `n8n-nodes-mem0-v*` | npm (`@mem0/n8n-nodes-mem0`) |
- 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.
- Registry trusted-publisher settings are pinned to each package's own workflow **filename**. Renaming a CD workflow breaks publishing for that package.
- First publish of a new npm package must be done manually. OIDC works from the second version onward.
- To re-publish a release, do **not** delete and recreate the GitHub release. Dispatch the workflow directly: `gh workflow run <package>-cd.yml --ref refs/tags/<tag> -f tag=<tag>`.
- The Zapier app deploys to Zapier's platform, not npm, so it is not in the router. Deploy with `gh workflow run zapier-mem0-cd.yml --ref main`.
- Adding a package: add its CD workflow, then register its tag prefix in the `case` block in `release.yml`, keeping the bare `v*` arm last.
## Contribution gates
| Workflow | File | Purpose |
|----------|------|---------|
| 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 |
| llms.txt Check | `docs-llms-txt-check.yml` | Blocks PRs touching `docs/**/*.mdx` when `docs/llms.txt` is out of sync |
`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.
`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
`ISSUE_TEMPLATE/*.yml` are GitHub issue **forms**, not markdown templates. Only forms support `required: true` and machine-parseable field ids. Blank issues are disabled in `config.yml`.
`issue-labeler.yml` reads only the `component` field id through `stefanbuck/github-issue-parser` and `redhat-plumbers-in-action/advanced-issue-labeler`, so adding new field ids is safe. Renaming `component` is not.
Current field ids:
| Form | Ids |
|------|-----|
| `bug_report.yml` | `component`, `description`, `verification`, `ai_assistance` |
| `feature_request.yml` | `component`, `description`, `ai_assistance` |
| `documentation_issue.yml` | `description`, `ai_assistance` |
## Trust list
`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. `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.
+1
View File
@@ -0,0 +1 @@
AGENTS.md
+40
View File
@@ -51,3 +51,43 @@ body:
- OS:
validations:
required: true
- type: textarea
id: verification
attributes:
label: How You Verified This
description: We only take on bugs someone has actually reproduced. Show your work.
value: |
### What I Ran
The exact command or script, and where it ran.
### What I Saw
The real output, log line, or traceback. Paste it, do not describe it.
### Why This Is a Bug
What should have happened instead, and what says so: a docs link, a
docstring, a test, or the code itself.
### What I Ruled Out
Anything you checked that turned out not to be the cause.
validations:
required: true
- type: dropdown
id: ai_assistance
attributes:
label: AI Assistance
description: >-
This asks how the bug was found and confirmed, not how the text was
written. Drafting the write-up with AI is fine. We ask because it tells
us how much to trust the reproduction, not because it counts against you.
options:
- No AI involved
- AI helped me find it, and I reproduced it myself afterwards
- AI found and wrote this, and I have not reproduced it myself
validations:
required: true
+6 -3
View File
@@ -1,8 +1,11 @@
blank_issues_enabled: true
blank_issues_enabled: false
contact_links:
- name: Discord Community
- name: Question or general help
url: https://discord.gg/6PzXDgEjG5
about: Ask questions and discuss with the community
about: Ask on Discord. The issue tracker is for bugs and accepted work only.
- name: Documentation
url: https://docs.mem0.ai
about: Read the official mem0 documentation
- name: Report a security vulnerability
url: https://github.com/mem0ai/mem0/security/advisories/new
about: Report privately through a security advisory. Never open a public issue.
@@ -21,3 +21,17 @@ body:
How should the docs be improved?
validations:
required: true
- type: dropdown
id: ai_assistance
attributes:
label: AI Assistance
description: >-
This asks how the problem was found, not how the text was written.
Drafting the write-up with AI is fine.
options:
- No AI involved, I hit this reading the docs
- AI-assisted, but I checked the page myself
- AI found this, and I have not opened the page
validations:
required: true
@@ -36,3 +36,18 @@ body:
Any workarounds you've tried or other approaches considered.
validations:
required: true
- type: dropdown
id: ai_assistance
attributes:
label: AI Assistance
description: >-
This asks where the idea came from, not how the text was written.
Drafting the write-up with AI is fine. A request you hit yourself while
building something carries more weight than one a model suggested.
options:
- No AI involved, this is a need I hit myself
- AI-assisted, but the need is mine
- AI suggested this feature
validations:
required: true
+12
View File
@@ -14,6 +14,18 @@ Closes #<!-- issue number -->
- [ ] Refactor (no functional changes)
- [ ] Documentation update
## AI Assistance
<!-- This is about the code, not this description. Writing the description with AI is fine. -->
- [ ] No AI assistance
- [ ] AI-assisted (autocomplete, or I asked a model questions while writing this)
- [ ] AI-generated (an agent wrote most or all of this diff)
<!-- If you ticked either AI box, name the tool and what you checked yourself. -->
- [ ] **I can explain every line of this diff and how it interacts with the rest of the codebase, without asking an AI tool.**
## Breaking Changes
<!-- If this is a breaking change, describe what breaks and the migration path. Delete this section if not applicable. -->
+413
View File
@@ -0,0 +1,413 @@
# The list of vouched (or denounced) users for this repository.
#
# 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 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.
# - Optionally specify platform: `platform:username` (e.g. `github:mitchellh`).
# - To denounce a user, prefix with minus: `-username`.
# - Optionally add a note after a space following the handle.
#
# Maintainers vouch by commenting "!vouch @username" on any issue, and denounce
# with "!denounce @username". The bot commits the change back to this file.
#
# Seeded on 2026-08-12 from every author with at least one merged pull request,
# then filtered: accounts with a merge rate at or below 16% across six or more
# attempts were dropped, since landing one change out of many is the signature
# of automated submission rather than contribution. Removal is not a ban. Any
# maintainer can !vouch these accounts back in.
1MikeMakuch
aaishikdutta
Aarkin7
abdullahirfann
AbdurNawaz
abhay-codes07
Abhineshhh
ac12644
acarbonetto
adh-wonolo
Aditya-Tripuraneni
aesher9o1
agumpandey
ahnedeee
ajmalmohad
AkisAya
akshat1423
akshseh
alessandropanzieri
alohays
aloktripathi1
amahuli03
amanagarwal042
Ameysr
amjadraza
anantoj
anchit-nishant
andrewghlee
andy-k-improving
anifort
anishesg
AnkushMalaker
AnnaSuSu
anujshandillya
ArchishmanSengupta
Arsh-mem0
ArthurHoward1
aryankhanna475
Ashu463
atahanyild
AtharvaJaiswal005
atkinsh
avp1598
axelray-dev
ayaangazali
aymenkrifa
barry166
being-abhi
berwinjoule
BillionClaw
bioshazard
bisla
bkidd1
blino
bmsvinci1729
boss-mao
Br1an67
brucewkz
cachho
caifeizhi
candidosales
cclauss
chaithanyak42
chinnuabey
ChiragArora31
ChrisFloofyKitsune
chrisqu777
clementantonyk
codexvn
Colsrch
CrepuscularIRIS
ctxlong
danielsiwiec
darkhaniop
davidatorres
deshraj
Dev-Khant
Devan019
deven298
devYRPauli
DhanushNehru
DhilipBinny
Dhravya
dimigerontaki
Diveyam-Mishra
divyansh-1009
Divyanshu9822
dog-last
DrJsPBs
dtee1
DumoeDss
e-biswas
Echo3ToEcho7
eldar702
eltociear
EnzoFanAccount
Esparon1
Fahmid-Arman
Failfail2603
FarukhS52
farzad528
felipeavilis
femto
fengjikui
fenilfaldu
fileames
Flyfoxs
fmercurio
FoliageOwO
fran3cc
frank-zsy
frederikb96
Freshield
freya0926
G26karthik
gabe-l-hart
gabrielstein-mem0
gajazlikovac
gasolin
gaurav0107
gauravagerwala
Genarojrsanchez
ghdcksgml1
GingerMoon
gmdorf
golemus
GongRzhe
GopalGB
Gyubin
haarishmk26
hackice20
halanm
hardik1408
Harin329
harshgupta-mem0
harshpandit007
hayescode
hcsum
he-yufeng
heng-ah
Hexecu
Himanshu-Sangshetti
hjlarry
HowieG
HrushiYadav
HScarb
huveewomg
Hybirdss
ianupamsingh
IgnazioDS
immuhammadfurqan
into-the-night
invincible04
Itz-Antaripa
ixchio
Jaco-Ren
Jai0401
JainamShah-22
Jainish-S
jarediaz
jeanibarz
Jerry-Terrasse
jessai2026
jesse-c
jfeng18
jferrettiboke
jjjojoj
joaomdmoura
JoeSL
johnwlockwood
jonasiwnl
josephchancey
juananpe
juaneloDev
junmo1215
Jupiter363
KapilM26
karthik-indla
KarthikeyaKollu
kartik-mem0
katarinasupe
ketangangal
kimnamu
kindertheo
kirex0
kirklin
kk2211
kmitul
koi646
kratos0718
krescent
Krishnachaitanyakc
kriszlazar
KushagraB424
l1anch1
lamost423
lan17
LeonieFreisinger
lh0x00
limboinf
liviaellen
longway-code
lsvishaal
LuciAkirami
lucifertrj
lvpx
ly-wang19
maamalama
maccuryj
mae5357
mahone3297
Malhis
maljazaery
manganeseheptoxide
manthanguptaa
mark-watson
Mark-Zeng
markmbain
matanco1
mauricioalarcon
maxvonhippel
me-tusharchandra
mezotv
MgeeeeK
mggger
mgoulart
microbluey
mikejgray
Mingxiangyu
Mini256
misrasaurabh1
mjzcng
mogith-pn
morgoth9808
moyueheng
mrbusche
Mrinank-Bhowmick
muhammed-mamun
MUZAMMILPERVAIZ
mvanhorn
naman09
NavyaAlapati13
neilbhutada
NightClover-code
nikhilsharma26500
NILAY1556
niv-hertz
NoahStapp
norrishuang
OfficialAbhinavSingh
officialasishkumar
OjusWiZard
okaditya84
omahs
OsamaNabih
oskarrough
p-tirth
Padarn
paipeline
ParseDark
parshvadaftari
Parteeksachdeva
parthshr370
parzival418
Paulie-Aditya
paurushmittal
pc9
Pecunia201
peterj
pragnyanramtha
PranavPuranik
PrashantDixit0
prateekchhikara
prathameshagrawal
pratikgajjar
PratikRai0101
Prikshit7766
Prithvi1994
QunBB
rafid001
raghavtyagii
rahulsharmavishwakarma
rajib76
rakheesingh
ranjithkumar8352
Rayhanpatel
reachAnushaKondam
Real5K
Rhythm-08
richawo
Rishiraj2594
RitwijParmar
RobinALG87
rocke2020
rodboev
rohitgr7
ron-42
roshan-shaik-ml
rst0070
rudra717
rudrajmehta-mem0
rupamoraczen
rupeshbansal
ryanrozich
SaharshPatel24
sahilyadav902
sahithreddy05
SakshiSrivastava2024
SamuelDevdas
sarkarsaurabh27
sdht0
seetharam-rajagopal
sergio-toro
SerSamgy
shafdev
shashank42
ShauryaaSharma
Sheharyar570
shenxiangzhuang
ShivamMenda
shlokkhemani
shraderdm
shrivastavanolo
shubhampal123
shuoli84
sidmohanty11
siroa
slobodaapl
soapun
soumil-rathi
spike-spiegel-21
srishti-git1110
SSDWGG
sssserrano
subhadip001
subhajit20
SudoAnirudh
sukkritsharmaofficial
sw8fbar
swarnaprakash
sxu75374
SZemse
taranjeet
techcontributor
tgabi333
theagenticguy
thomasgtaylor
tomasonjo
TommyZihao
TruptiAgrawal
turtletongue
Tushar-kalsi
Ukong0324
umran666
utkarsh240799
UzairNaeem3
V-Silpin
vatsalrathod16
vedant381
veeceey
vgvoleg
VictorECDSA
VikramIyer125
Vir-8
vsatyamuralikrishna
vuonghuuhung
WayneCao
whysosaket
wobushixiaoj
xiangpingjiang
XiaojuCH
xu-xiang
xyb
yashikabadaya
yashs33244
ygorth
youneshima
ytkimirti
YuriyTW
YusukeJustinNakajima
zaiddkhan
zegerhoogeboom
zinyando
Zlo7
Zncl2222
zzaym
+1 -1
View File
@@ -28,7 +28,7 @@ jobs:
}
base_version=$(git show "$BASE_SHA:pyproject.toml" 2>/dev/null | extract_version || echo "")
head_version=$(extract_version < pyproject.toml)
head_version=$(git show "$HEAD_SHA:pyproject.toml" | extract_version)
echo "Base version: ${base_version:-<unknown>}"
echo "Head version: $head_version"
+103
View File
@@ -0,0 +1,103 @@
name: PR Gate
on:
pull_request_target:
types: [opened, reopened, edited, ready_for_review]
concurrency:
group: pr-gate-${{ github.event.pull_request.number }}
cancel-in-progress: true
env:
GATE_EFFECTIVE_FROM: '2026-08-12T00:00:00Z'
permissions:
contents: read
pull-requests: write
issues: read
jobs:
gate:
if: >-
github.event.pull_request.draft == false &&
github.event.pull_request.user.type != 'Bot' &&
!contains(fromJSON('["OWNER","MEMBER","COLLABORATOR"]'), github.event.pull_request.author_association)
runs-on: ubuntu-latest
steps:
- uses: actions/github-script@v7
with:
script: |
const pr = context.payload.pull_request;
const { owner, repo } = context.repo;
const effectiveFrom = process.env.GATE_EFFECTIVE_FROM;
if (effectiveFrom && Date.parse(pr.created_at) < Date.parse(effectiveFrom)) {
core.info(`Opened ${pr.created_at}, before the gate took effect ${effectiveFrom}. Skipped.`);
return;
}
const { data: current } = await github.rest.pulls.get({
owner, repo, pull_number: pr.number,
});
if (current.state !== 'open') {
core.info(`#${pr.number} is already ${current.state}. Skipped.`);
return;
}
const files = await github.paginate(github.rest.pulls.listFiles, {
owner, repo, pull_number: pr.number, per_page: 100,
});
if (files.length > 0 && files.every((file) => file.filename.startsWith('docs/'))) {
core.info('Docs-only PR, gate skipped');
return;
}
const { repository } = await github.graphql(
`query ($owner: String!, $repo: String!, $number: Int!) {
repository(owner: $owner, name: $repo) {
pullRequest(number: $number) {
closingIssuesReferences(first: 20) {
nodes { number labels(first: 50) { nodes { name } } }
}
}
}
}`,
{ owner, repo, number: pr.number },
);
const accepted = repository.pullRequest.closingIssuesReferences.nodes
.filter((issue) => issue.labels.nodes.some((label) => label.name === 'accepted'))
.map((issue) => issue.number);
if (accepted.length > 0) {
core.info(`Accepted issue linked: #${accepted.join(', #')}`);
return;
}
const body = [
'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.',
'**Closed does not mean rejected.** It means it is not in the queue yet, and reopening takes about a minute.',
'',
'To get it reviewed:',
'',
'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`.',
'4. Reopen this pull request. The check runs again and it stays open.',
'',
'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.',
'',
'See [CONTRIBUTING.md](https://github.com/mem0ai/mem0/blob/main/CONTRIBUTING.md) for the full policy.',
].join('\n');
await github.rest.issues.createComment({
owner, repo, issue_number: pr.number, body,
});
await github.rest.pulls.update({
owner, repo, pull_number: pr.number, state: 'closed',
});
core.info(`Closed #${pr.number}: no accepted issue linked`);
+1 -1
View File
@@ -41,7 +41,7 @@ jobs:
set -euo pipefail
base_version=$(git show "$BASE_SHA:mem0-ts/package.json" 2>/dev/null | jq -r .version || echo "")
head_version=$(jq -r .version mem0-ts/package.json)
head_version=$(git show "$HEAD_SHA:mem0-ts/package.json" | jq -r .version)
echo "Base version: ${base_version:-<unknown>}"
echo "Head version: $head_version"
+27
View File
@@ -0,0 +1,27 @@
name: Vouch - Check PR
on:
pull_request_target:
types: [opened, reopened]
concurrency:
group: vouch-check-pr-${{ github.event.pull_request.number }}
cancel-in-progress: true
permissions:
contents: read
pull-requests: write
jobs:
check:
if: >-
github.event.pull_request.user.type != 'Bot' &&
!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
with:
pr-number: ${{ github.event.pull_request.number }}
auto-close: false
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
@@ -0,0 +1,42 @@
name: Vouch - Manage by Issue
on:
issue_comment:
types: [created]
concurrency:
group: vouch-manage
cancel-in-progress: false
permissions:
contents: write
issues: write
pull-requests: write
jobs:
manage:
if: contains(github.event.comment.body, '!vouch') || contains(github.event.comment.body, '!denounce') || contains(github.event.comment.body, '!unvouch')
runs-on: ubuntu-latest
steps:
- uses: actions/create-github-app-token@v3
id: app-token
with:
app-id: ${{ secrets.VOUCH_APP_ID }}
private-key: ${{ secrets.VOUCH_APP_PRIVATE_KEY }}
- uses: actions/checkout@v4
with:
token: ${{ steps.app-token.outputs.token }}
- uses: mitchellh/vouch/action/manage-by-issue@d66fa29a64600490892131ad87597c30c91fcac4 # v1.5.0
with:
repo: ${{ github.repository }}
issue-id: ${{ github.event.issue.number }}
comment-id: ${{ github.event.comment.id }}
vouch-keyword: "!vouch"
denounce-keyword: "!denounce"
unvouch-keyword: "!unvouch"
pull-request: "true"
merge-immediately: "true"
env:
GITHUB_TOKEN: ${{ steps.app-token.outputs.token }}
+105 -543
View File
@@ -1,593 +1,155 @@
# AGENTS.md
This file provides context for AI coding assistants (Claude Code, Cursor, GitHub Copilot, Codex, etc.) working with the Mem0 repository.
Context for AI coding assistants (Claude Code, Cursor, Copilot, Codex) working in the Mem0 repository.
## Project Overview
**Mem0** ("mem-zero") is a memory layer for AI agents: persistent, personalized memory through a hosted platform API and self-hosted open-source SDKs. Apache-2.0.
[Repository](https://github.com/mem0ai/mem0) · [Documentation](https://docs.mem0.ai)
**Mem0** ("mem-zero") is an intelligent memory layer for AI agents and assistants. It provides persistent, personalized memory via both a hosted platform API and self-hosted open-source SDKs.
This is a polyglot monorepo and **every package sets its own rules**. Read the `AGENTS.md` nearest the files you are editing before running any command. The linters, formatters, test runners, and line lengths genuinely differ per package, and using the wrong one fails CI or produces a diff full of noise.
- **Repository**: https://github.com/mem0ai/mem0
- **Documentation**: https://docs.mem0.ai
- **License**: Apache-2.0
## Do NOT
## Repository Structure
- Open a pull request without a signed CLA. It will not be reviewed. See [The CLA is not optional](#the-cla-is-not-optional).
- 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.
- Use npm or yarn in TypeScript packages. This repo is pnpm-only (Bun in `.opencode-plugin/`).
- Use `require()` in TypeScript. ES module `import` syntax only.
- Mix up linter configs. Root Python is ruff at line length **120**, `cli/python/` is ruff at **100**, `cli/node/` is Biome, `mem0-ts/` is Prettier, `integrations/vercel-ai-sdk/` is ESLint.
- Add Python dependencies to the core `dependencies` list in `pyproject.toml`. Use an optional group.
- Change a public API without updating `docs/` in the same pull request.
- Introduce a new framework or abstraction without discussion. Follow the patterns already in the file you are editing.
This is a **polyglot monorepo** containing Python and TypeScript packages, CLIs, servers, plugins, and documentation.
## Where to look
### Key Directories
| Editing | Read | Toolchain |
|---------|------|-----------|
| `mem0/` | [`mem0/AGENTS.md`](mem0/AGENTS.md) | hatch, ruff 120, pytest |
| `tests/` | [`tests/AGENTS.md`](tests/AGENTS.md) | pytest |
| `mem0-ts/` | [`mem0-ts/AGENTS.md`](mem0-ts/AGENTS.md) | pnpm, tsup, Prettier, jest |
| `cli/python/` | [`cli/python/AGENTS.md`](cli/python/AGENTS.md) | ruff **100**, pytest |
| `cli/node/` | [`cli/node/AGENTS.md`](cli/node/AGENTS.md) | pnpm, tsup, Biome, vitest |
| `integrations/` | [`integrations/AGENTS.md`](integrations/AGENTS.md) | varies per integration |
| `server/` | [`server/AGENTS.md`](server/AGENTS.md) | Docker Compose, FastAPI |
| `docs/` | [`docs/AGENTS.md`](docs/AGENTS.md) | Mintlify |
| `skills/` | [`skills/AGENTS.md`](skills/AGENTS.md) | markdown, size-budgeted |
| `.github/` | [`.github/AGENTS.md`](.github/AGENTS.md) | GitHub Actions |
| Directory | Description |
|-----------|-------------|
| `mem0/` | Core Python SDK (`mem0ai` on PyPI) — memory, LLMs, embeddings, vector stores, graphs, rerankers |
| `mem0-ts/` | TypeScript SDK (`mem0ai` on npm) — client + OSS memory |
| `cli/python/` | Python CLI (`mem0-cli` on PyPI) — Typer-based, entry point `mem0` |
| `cli/node/` | Node CLI (`@mem0/cli` on npm) — Commander-based, entry point `mem0` |
| `integrations/` | **Agent & editor integrations**, one directory per integration (see "Adding a New Integration") |
| `integrations/mem0-plugin/` | AI editor plugins (Claude Code, Cursor, Codex) — MCP server connection, lifecycle hooks, skills. Contains nested `.opencode-plugin/` (`@mem0/opencode-plugin`) |
| `integrations/openclaw/` | `@mem0/openclaw-mem0` — OpenClaw plugin for Claude Code / AI editors |
| `integrations/pi-agent-plugin/` | `@mem0/pi-agent-plugin` — Pi Agent plugin |
| `integrations/vercel-ai-sdk/` | `@mem0/vercel-ai-provider` — Vercel AI SDK memory provider |
| `integrations/n8n-nodes-mem0/` | `@mem0/n8n-nodes-mem0` — n8n community node; add / search / get / update / delete memories |
| `integrations/zapier-mem0/` | `@mem0/zapier` — Zapier Platform CLI app (deploys to Zapier, not npm); add / search / get / delete memories |
| `server/` | FastAPI REST server for self-hosted Mem0 (Docker: FastAPI + PostgreSQL/pgvector + Neo4j) |
| `skills/` | Claude Code skill definitions. Reference skills (SDK knowledge, always-on): `mem0/`, `mem0-cli/`, `mem0-vercel-ai-sdk/`. Pipeline skills (run on demand): `mem0-integrate/`, `mem0-test-integration/`, `mem0-oss-to-platform/` |
## Repository map
| Directory | What it is |
|-----------|------------|
| `mem0/` | Core Python SDK (`mem0ai` on PyPI): memory, LLMs, embeddings, vector stores, graphs, rerankers |
| `mem0-ts/` | TypeScript SDK (`mem0ai` on npm): hosted client + OSS memory |
| `cli/python/` | Python CLI (`mem0-cli` on PyPI), Typer-based, entry point `mem0` |
| `cli/node/` | Node CLI (`@mem0/cli` on npm), Commander-based, entry point `mem0` |
| `integrations/` | Agent and editor integrations, one self-contained directory each |
| `server/` | FastAPI REST server for self-hosted Mem0 (Docker: FastAPI + pgvector + Neo4j) |
| `skills/` | Claude Code skill definitions, published by raw URL |
| `docs/` | Documentation site (Mintlify) |
| `tests/` | Python SDK tests (pytest) |
| `evaluation/` | Submodule → [`mem0ai/memory-benchmarks`](https://github.com/mem0ai/memory-benchmarks) — benchmarking (LOCOMO, LongMemEval, BEAM) lives in that repo |
| `examples/` | Sample projects & runnable demos — apps, Chrome extension, multi-agent patterns, and Jupyter notebooks (`notebooks/`) |
| `examples/` | Sample apps, Chrome extension, multi-agent patterns, notebooks |
| `scripts/` | Repo-wide utilities, e.g. `check-llms-txt-coverage.py` |
| `evaluation/` | Submodule pinned to [`mem0ai/memory-benchmarks`](https://github.com/mem0ai/memory-benchmarks) |
| `pr-reviews/` | Pull request review materials |
| `scripts/` | Repo-wide utility scripts (e.g., `check-llms-txt-coverage.py` for docs/llms.txt sync) |
### Core Package Dependencies
```
mem0 (Python SDK) mem0-ts (TypeScript SDK)
├── mem0/memory/ ├── src/client/ (MemoryClient — hosted)
├── mem0/llms/ └── src/oss/ (Memory — self-hosted)
├── mem0/memory/ ├── src/client/ MemoryClient (hosted)
├── mem0/llms/ └── src/oss/ Memory (self-hosted)
├── mem0/embeddings/ ├── src/llms/
├── mem0/vector_stores/ ├── src/embeddings/
├── mem0/graphs/ ├── src/vector_stores/
└── mem0/reranker/ └── src/graphs/
cli/python/ ──▶ mem0ai (optional, for OSS mode)
cli/node/ ──▶ mem0ai (npm, for API calls)
integrations/vercel-ai-sdk/ ──▶ ai, @ai-sdk/* providers
cli/python/ ──▶ mem0ai (optional, OSS mode)
cli/node/ ──▶ mem0ai (npm)
integrations/vercel-ai-sdk/ ──▶ ai, @ai-sdk/*
integrations/openclaw/ ──▶ mem0ai (npm)
```
## Development Setup
### Requirements
- **Python**: 3.9+ (3.10+ for CLI)
- **Node.js**: v18+ (v20 or v22 recommended)
- **pnpm**: v10+ (`npm install -g pnpm@10`) — used for all TypeScript packages
- **Hatch**: Python build/environment tool (`pip install hatch`)
- **Docker**: Required for `server/` development
### Initial Setup
## Setup
```bash
# Python SDK
hatch shell dev_py_3_11 # creates environment with all deps
pre-commit install # install git hooks
hatch shell dev_py_3_11 # Python: creates the env with all deps
pre-commit install # ruff + isort on commit
# TypeScript packages
cd mem0-ts && pnpm install # TS SDK
cd cli/node && pnpm install # Node CLI
cd integrations/vercel-ai-sdk && pnpm install # Vercel AI provider
cd integrations/openclaw && pnpm install # OpenClaw plugin
cd <ts-package> && pnpm install
```
## Build, Lint, and Test Commands
Requirements: Python 3.9+ (3.10+ for the CLI), Node 18+ (20 or 22 preferred), pnpm 10+, hatch, Docker for `server/`.
### Python SDK (`mem0/`)
## Conventions everywhere
- **Naming:** `snake_case.py`, `test_<module>.py`, `snake_case.ts`, `<module>.test.ts`, `kebab-case` for config and manifest files.
- **Python:** Pydantic v2 for models and config. Providers inherit a `base.py` abstract class; config lives in `configs.py`.
- **TypeScript:** strict mode, tsup builds, ES module imports.
- **Commits:** [Conventional Commits](https://www.conventionalcommits.org/) (`feat:`, `fix:`, `docs:`, `refactor:`, `test:`).
- **Versions:** bump in `pyproject.toml` or `package.json`. Releases are cut by tag prefix; see [`.github/AGENTS.md`](.github/AGENTS.md).
## Benchmarking
Benchmarks (LOCOMO, LongMemEval, BEAM) live in [`mem0ai/memory-benchmarks`](https://github.com/mem0ai/memory-benchmarks). The in-repo `evaluation/` path is a submodule pinned to that repo's `main`:
```bash
# Environment setup (uses Hatch)
hatch shell dev_py_3_11 # or dev_py_3_9, dev_py_3_10, dev_py_3_12
# Linting and formatting
make lint # ruff check
make format # ruff format
make sort # isort mem0/
# Tests
make test # pytest tests/
make test-py-3.9 # test specific Python version (3.9–3.12)
# Build and publish
make build # hatch build
make publish # hatch publish
git submodule update --init evaluation
```
- **Python:** 3.9, 3.10, 3.11, 3.12
- **Linter/formatter:** Ruff (line length **120**)
- **Import sorting:** isort (`profile = "black"`)
- **Test framework:** pytest (with pytest-mock, pytest-asyncio)
- **Pre-commit hooks:** ruff + isort — run `pre-commit install` before committing
## What to ship with a change
### TypeScript SDK (`mem0-ts/`)
Guidelines, not rules. Trivial fixes need less; anything user-facing needs more.
```bash
cd mem0-ts
pnpm install
pnpm run build # tsup
pnpm run test # jest (all tests)
pnpm run test:unit # jest --coverage (unit tests only)
pnpm run test:integration # jest (integration tests, needs MEM0_API_KEY)
pnpm run test:ci # jest --coverage --ci (CI mode)
pnpm run test:watch # jest watch mode
```
| Change | Expect |
|--------|--------|
| **Bug fix** | A regression test that fails without the fix, written first. The fix. The relevant suite passing. The package's linter run. |
| **New feature** | Implementation following existing patterns, test coverage, `docs/` updates for public APIs, an example if the behavior is user-facing, and an `llms.txt` entry for any new `.mdx` page. |
| **New provider** | See [Adding a provider](mem0/AGENTS.md#adding-a-provider). |
| **New integration** | See [Adding an integration](integrations/AGENTS.md#adding-an-integration). |
| **Refactor** | Tests for changed behavior, existing tests still green. No docs needed for internal-only changes. |
- **Node:** 20, 22 (CI-tested)
- **Build:** tsup (CJS + ESM)
- **Test:** jest
- **Formatter:** prettier
Fix bugs at the root, not at the symptom. If a guard belongs in a shared function, put it there rather than in each caller.
### Python CLI (`cli/python/`)
## Contributing
```bash
cd cli/python
pip install -e ".[dev]" # dev install with ruff + pytest
ruff check . # lint
ruff format . # format
pytest # test
hatch build # build
```
Full guide: [`CONTRIBUTING.md`](CONTRIBUTING.md). Conduct: [`CODE_OF_CONDUCT.md`](CODE_OF_CONDUCT.md).
- **Python:** 3.10+ (not 3.9)
- **Linter/formatter:** Ruff (line length **100** — different from root SDK)
- **Ruff rules:** E, F, I, W, UP, B, SIM, RUF (ignores E501, B008 for Typer patterns, SIM108)
- **Framework:** Typer + Rich + httpx
- **Entry point:** `mem0 = "mem0_cli.app:main"`
- **Source layout:** `src/mem0_cli/`
- **Optional dependency:** `mem0ai` (for OSS mode, via `[oss]` extra)
1. Open an issue **first** and wait for a maintainer to apply the `accepted` label. Every PR must link it with `Closes #<number>`. PRs without an accepted linked issue are closed automatically by the [PR Gate](.github/workflows/pr-gate.yml), with a reopen path. Documentation-only changes are exempt.
2. Fork, then branch from `main` (`feature/...`, `fix/...`).
3. Make the change: code, tests, docs, examples.
4. Run lint and tests for **every** package you touched.
5. Commit with Conventional Commits.
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.**
### Node CLI (`cli/node/`)
### The CLA is not optional
```bash
cd cli/node
pnpm install
pnpm run build # tsup
pnpm run lint # biome check src/
pnpm run lint:fix # biome check --write src/
pnpm run typecheck # tsc --noEmit
pnpm run test # vitest run
pnpm run test:watch # vitest (watch mode)
pnpm run dev # tsx src/index.ts (development)
```
**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.
- **Node:** 18+ required
- **Build:** tsup (ESM)
- **Linter:** Biome (not ESLint, not Ruff)
- **Test:** vitest (not jest)
- **Framework:** Commander + Chalk + ora + cli-table3
The `CLAassistant` bot comments on your first pull request with a link. Signing takes under a minute, is done once per GitHub account, and covers every contribution you make afterwards. Until it is signed the `license/cla` check stays red.
### Vercel AI SDK Provider (`integrations/vercel-ai-sdk/`)
If you are an agent opening a pull request on someone's behalf, tell them they must sign it themselves. Nobody else can sign for them, and the pull request goes nowhere until they do.
```bash
cd integrations/vercel-ai-sdk
pnpm install
pnpm run build # tsup
pnpm run lint # eslint
pnpm run type-check # tsc --noEmit
pnpm run prettier-check # prettier --check
pnpm run test # jest
pnpm run test:edge # vitest (edge runtime)
pnpm run test:node # vitest (node runtime)
```
### What gets a pull request closed
- **Build:** tsup (CJS + ESM)
- **Lint:** ESLint + Prettier
- **Test:** jest + vitest (edge/node configs)
Beyond the CLA and the accepted-issue gate, the [Contribution Conduct](CODE_OF_CONDUCT.md#contribution-conduct) section of the code of conduct is the enforceable form of this repo's anti-slop policy:
### OpenClaw Plugin (`integrations/openclaw/`)
- **Disclose AI use.** The PR template asks how the *code* was written; drafting the description with a model is fine. The disclosure is never held against you, it tells a reviewer where to look. Silence followed by a review comment you cannot answer is what costs everyone the afternoon.
- **Do not submit work you have not run.** A bug report means you reproduced it. A PR means you ran the tests.
- **Do not fabricate evidence.** Invented tracebacks, unmeasured benchmarks, tests that assert the implementation back at itself, descriptions that describe a different change than the diff makes.
- **Match your volume to your engagement.** Open changes at the rate you can discuss them.
- **Do not press for merges.** One polite follow-up after a reasonable wait is fine.
- **You must be able to explain every line of your diff** and how it interacts with the rest of the codebase, without asking an AI tool. This is the one rule that does not bend.
```bash
cd integrations/openclaw
pnpm install
pnpm run build # tsup
pnpm run test # vitest run
```
### Reference
- **Build:** tsup (ESM)
- **Test:** vitest (with Codecov in CI)
- **Plugin manifest:** `openclaw.plugin.json`
### Server (`server/`)
```bash
# Docker production build
cd server
make build # docker build -t mem0-api-server .
make run_local # docker run -p 8000:8000 with .env
# Docker Compose development (FastAPI + PostgreSQL/pgvector + Neo4j)
cd server
docker-compose up # starts all 3 services
# mem0 API: localhost:8888
# PostgreSQL: localhost:8432
# Neo4j HTTP: localhost:8474, Bolt: localhost:8687
```
- **Framework:** FastAPI with uvicorn (auto-reload in dev)
- **Services:** PostgreSQL with pgvector, Neo4j 5.x with APOC plugin
- **Hot reload:** Dev Dockerfile mounts `server/` and `mem0/` for live changes
### Documentation (`docs/`)
```bash
make docs # or: cd docs && mintlify dev
```
- **Framework:** Mintlify
- **API spec:** `docs/openapi.json`
- **Structure:** `api-reference/`, `open-source/`, `platform/`, `integrations/`, `cookbooks/`, `core-concepts/`
### Evaluation / Benchmarking
Benchmarking lives in the external [`mem0ai/memory-benchmarks`](https://github.com/mem0ai/memory-benchmarks) repo (LOCOMO + LongMemEval + BEAM). The in-repo `evaluation/` path is a **git submodule** pinned to that repo's `main` — populate it with `git submodule update --init evaluation` (or clone mem0 with `--recurse-submodules`), or clone the benchmarks repo standalone:
```bash
git clone https://github.com/mem0ai/memory-benchmarks.git
cd memory-benchmarks
pip install -r requirements.txt
# Run a benchmark (Mem0 Cloud; use docker compose for OSS)
python -m benchmarks.locomo.run --project-name my-test --backend cloud --mem0-api-key $MEM0_API_KEY
python -m benchmarks.longmemeval.run --project-name my-test --backend cloud --mem0-api-key $MEM0_API_KEY --all-questions
python -m benchmarks.beam.run --project-name my-test --backend cloud --mem0-api-key $MEM0_API_KEY --chat-sizes 100K --conversations 0-9
```
## Core APIs
### Python
| Function / Class | Purpose | Import |
|-----------------|---------|--------|
| `Memory` | Self-hosted memory (sync) | `from mem0 import Memory` |
| `AsyncMemory` | Self-hosted memory (async) | `from mem0 import AsyncMemory` |
| `MemoryClient` | Hosted platform client (sync) | `from mem0 import MemoryClient` |
| `AsyncMemoryClient` | Hosted platform client (async) | `from mem0 import AsyncMemoryClient` |
**Key `Memory` / `MemoryClient` methods:**
| Method | Purpose |
|--------|---------|
| `add(messages, *, user_id, agent_id, run_id, metadata)` | Store a new memory |
| `search(query, *, user_id, agent_id, run_id, limit, filters)` | Search memories |
| `get(memory_id)` | Retrieve a single memory by ID |
| `get_all(*, user_id, agent_id, run_id, limit)` | List all memories |
| `update(memory_id, data)` | Update a memory |
| `delete(memory_id)` | Delete a memory |
| `delete_all(*, user_id, agent_id, run_id)` | Delete all memories |
| `history(memory_id)` | Get change history for a memory |
### TypeScript
| Export | Purpose | Import |
|--------|---------|--------|
| `MemoryClient` | Hosted platform client | `import { MemoryClient } from 'mem0ai'` |
| `Memory` | Self-hosted OSS memory | `import { Memory } from 'mem0ai/oss'` |
## Import Patterns
### Python
| What | Import |
|------|--------|
| Core memory classes | `from mem0 import Memory, AsyncMemory` |
| Platform client | `from mem0 import MemoryClient, AsyncMemoryClient` |
| Configuration | `from mem0.configs.base import MemoryConfig` |
| LLM providers | `from mem0.llms.<provider> import <ProviderLLM>` |
| Embedding providers | `from mem0.embeddings.<provider> import <ProviderEmbedding>` |
| Vector store providers | `from mem0.vector_stores.<provider> import <ProviderVectorStore>` |
### TypeScript
| What | Import |
|------|--------|
| Hosted client | `import { MemoryClient } from 'mem0ai'` |
| OSS memory | `import { Memory } from 'mem0ai/oss'` |
| Specific providers (OSS) | `import { OpenAIEmbedding } from 'mem0ai/oss'` |
## Coding Standards
### File Naming Conventions
- **Python source files:** `snake_case.py` (e.g., `azure_openai.py`, `cohere_reranker.py`)
- **Python test files:** `test_<module>.py` (e.g., `test_memory.py`, `test_main.py`)
- **TypeScript source files:** `snake_case.ts` (e.g., `azure_ai_search.ts`)
- **TypeScript test files:** `<module>.test.ts` (e.g., `memory.test.ts`)
- **Config/manifest files:** `kebab-case` (e.g., `openclaw.plugin.json`, `jest.config.js`)
### Python Conventions
- **Provider pattern:** All providers (LLMs, embeddings, vector stores, graphs, rerankers) inherit from a `base.py` abstract class in their directory. Config classes live in `configs.py`.
- **Pydantic v2** for all data models and configuration.
- **Ruff** is the single linting and formatting tool — no black, no flake8.
- Root SDK: line length **120**
- Python CLI: line length **100** with extended rule set (UP, B, SIM, RUF)
- **isort** with `profile = "black"` for import sorting.
### TypeScript Conventions
- **Build:** tsup across all packages.
- **Package manager:** pnpm everywhere (no npm, no yarn).
- **TypeScript strict mode** across all packages.
- **Linting varies by package:**
| Package | Linter | Formatter | Test Framework |
|---------|--------|-----------|---------------|
| `mem0-ts/` | — | Prettier | jest |
| `cli/node/` | Biome | Biome | vitest |
| `integrations/vercel-ai-sdk/` | ESLint | Prettier | jest + vitest |
| `integrations/openclaw/` | — | — | vitest |
### Type Checking
Always run type checking after modifying TypeScript code:
```bash
cd <package> && pnpm run typecheck # or: tsc --noEmit
```
## Architecture
### Provider Pattern
The SDK uses a consistent plugin architecture across 5 categories. Each category has a `base.py` abstract class and concrete provider implementations:
| Category | Count | Examples |
|----------|-------|---------|
| **LLMs** | 24 | OpenAI, Anthropic, AWS Bedrock, Azure OpenAI, Gemini, Groq, Ollama, Together, DeepSeek, vLLM, LiteLLM, LM Studio, xAI |
| **Vector Stores** | 30 | Qdrant, Pinecone, Chroma, Weaviate, Milvus, MongoDB, Redis, Elasticsearch, pgvector, Supabase, Faiss, S3 Vectors |
| **Embeddings** | 15 | OpenAI, Azure OpenAI, Gemini, HuggingFace, FastEmbed, Together, AWS Bedrock, Ollama, Vertex AI |
| **Graph Stores** | 4 | Neo4j, Memgraph, Kuzu, Apache AGE |
| **Rerankers** | 5 | Cohere, HuggingFace, LLM-based, Sentence Transformer, Zero Entropy |
### Two Usage Modes
Self-hosted `Memory` / `AsyncMemory` classes and hosted-platform `MemoryClient` — both in Python and TypeScript.
### Graph Memory
Optional layer on top of vector memory for relationship-aware retrieval. Configured via the `graph` section of `MemoryConfig`.
### MCP Integration
Model Context Protocol support in multiple places:
- **Remote:** MCP server at `mcp.mem0.ai`
- **Plugin:** MCP tools in `integrations/mem0-plugin/` — 9 tools: `add_memory`, `search_memories`, `get_memories`, `get_memory`, `update_memory`, `delete_memory`, `delete_all_memories`, `delete_entities`, `list_entities`
### Plugin & Skills System
- `integrations/mem0-plugin/` provides integrations for Claude Code, Cursor, and Codex via MCP server connections and lifecycle hooks for automatic memory capture.
- `skills/` contains structured skill definitions for AI agents, split into two categories:
- **Reference skills** (always-on SDK knowledge): `mem0` (Python + TS SDKs, framework integrations), `mem0-cli` (terminal workflows), `mem0-vercel-ai-sdk` (Vercel AI provider).
- **Pipeline skills** (run on demand): `mem0-integrate` wires Mem0 into an existing repo via a TDD pipeline; `mem0-test-integration` verifies what the integrator produced on the same branch (the two are loosely coupled via `.mem0-integration/` artifacts); `mem0-oss-to-platform` migrates an existing project from Mem0 OSS to the hosted Platform SDK (plan, then execute on approval).
### Adding a New Provider
To add a new LLM, embedding, vector store, or reranker provider:
1. Create `mem0/<category>/<provider_name>.py`
2. Inherit from the abstract base class in `mem0/<category>/base.py`
3. Add configuration to `mem0/<category>/configs.py` (if the category uses one)
4. Register the provider in `mem0/<category>/__init__.py`
5. Add tests in `tests/<category>/<provider_name>/`
6. Add any new dependencies to the appropriate optional group in `pyproject.toml` (never to core `dependencies`)
7. Follow the exact pattern of existing providers in the same category — match method signatures, error handling, and config structure
### Adding a New Integration
Agent/editor integrations live under `integrations/`. Each is a self-contained directory (its own `package.json`/lockfile, build, and tests). To add one:
1. Create `integrations/<name>/` and build the integration there.
2. If it publishes to a registry, set `repository.directory: "integrations/<name>"` in its `package.json` so npm provenance links to the correct subdirectory.
3. Add CI/CD under `.github/workflows/` (`<name>-checks.yml`, `<name>-cd.yml`). Use `integrations/<name>` in `paths:` triggers, `working-directory`, and `cache-dependency-path`. Register the release tag prefix in the `case` block in `release.yml` (keep the bare `v*` arm last). Keep workflow **filenames** stable — npm OIDC trusted publishing is pinned to repo + workflow filename.
4. If it is a Claude Code / editor marketplace plugin, register its path in the five `marketplace.json` files (root + `.claude-plugin/`, `.cursor-plugin/`, `.codex-plugin/`, `.agents/plugins/`).
5. Document it under `docs/integrations/` and add the page to `docs/docs.json` and `docs/llms.txt`.
6. Add rows to the "Key Directories" table and the CI/CD tables in this file.
## CI/CD
### CI Workflows (automated testing)
PR testing is orchestrated by a single entry point: **`ci-gate.yml` (CI Gate)** runs on every PR, detects which packages changed, and invokes only the relevant package workflows below as reusable workflows (`workflow_call`). Its final **`CI Gate`** job aggregates the results (skipped pipelines pass; failed or cancelled ones fail) and is the **only status check that needs to be required** in branch protection. Package workflows keep their own push-to-main and manual triggers; their `pull_request` triggers moved into the gate's path filters.
| Workflow | File | Standalone Triggers | Tests |
|----------|------|---------------------|-------|
| CI Gate | `ci-gate.yml` | All PRs | Routes to and aggregates the workflows below |
| Python SDK | `ci.yml` | Push to main | Ruff lint + pytest on Python 3.10, 3.11, 3.12 |
| TypeScript SDK | `ts-sdk-ci.yml` | Push to main (on `mem0-ts/`) | Prettier + build + jest on Node 20, 22 |
| Python CLI | `cli-python-ci.yml` | Push to main (on `cli/python/`), manual | Ruff lint + pytest + hatch build on Python 3.10, 3.11, 3.12 |
| Node CLI | `cli-node-ci.yml` | Push to main (on `cli/node/`), manual | Biome lint + tsc + vitest + tsup build on Node 20, 22 |
| OpenClaw | `openclaw-checks.yml` | Push to main (on `integrations/openclaw/`), manual | tsc + vitest (with Codecov) + tsup build on Node 20, 22 |
| Mem0 Plugin | `mem0-plugin-checks.yml` | Push to main (on `integrations/mem0-plugin/`, excluding `.opencode-plugin/`), manual | pytest + hook entry-point exec bits + JSON manifest validation on Python 3.10, 3.11, 3.12 |
| OpenCode Plugin | `opencode-plugin-checks.yml` | Push to main (on `integrations/mem0-plugin/.opencode-plugin/`), manual | Bun: tsc type-check + build + dist artifact check |
| Pi Agent Plugin | `pi-agent-plugin-checks.yml` | Push to main (on `integrations/pi-agent-plugin/`), manual | tsc + vitest + tsup build (dist artifact check) on Node 20, 22 |
| n8n Node | `n8n-nodes-mem0-checks.yml` | Push to main (on `integrations/n8n-nodes-mem0/`), manual | ESLint (n8n-nodes-base) + tsc build (dist artifact check) on Node 20 |
| Zapier App | `zapier-mem0-checks.yml` | Push to main (on `integrations/zapier-mem0/`), manual | build (tsc) + `zapier validate` + offline unit tests on Node 22 |
| docs llms.txt | `docs-llms-txt-check.yml` | Manual | `docs/llms.txt` coverage check |
When adding a new 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` — a path filter under the `changes` job, a call job, and an entry in the gate job's `needs` list.
### CD Workflows (automated publishing)
Publishing is routed through a single entry point: **`release.yml` (Release Router)** is the only workflow that listens to `release: published` events. It matches the release tag prefix and dispatches the corresponding package workflow via `workflow_dispatch`, so each release produces exactly one routed run (no skipped runs from the other pipelines).
| Workflow | File | Tag Prefix | Target |
|----------|------|------------|--------|
| Release Router | `release.yml` | (all releases) | dispatches the matching workflow below |
| Python SDK | `cd.yml` | `v*` | PyPI (`mem0ai`) |
| TypeScript SDK | `ts-sdk-cd.yml` | `ts-v*` | npm (`mem0ai`) |
| Python CLI | `cli-python-cd.yml` | `cli-v*` | PyPI (`mem0-cli`) |
| Node CLI | `cli-node-cd.yml` | `cli-node-v*` | npm (`@mem0/cli`) |
| Vercel AI SDK | `vercel-ai-cd.yml` | `vercel-ai-v*` | npm (`@mem0/vercel-ai-provider`) |
| 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`) |
| n8n Node | `n8n-nodes-mem0-cd.yml` | `n8n-nodes-mem0-v*` | npm (`@mem0/n8n-nodes-mem0`) |
- Package CD workflows are `workflow_dispatch`-only (inputs: `tag`, `prerelease`); they check out and build the given tag. Registry trusted-publisher settings stay pinned to each package's own workflow filename.
- All publishing uses **OIDC trusted publishing** — no tokens or secrets required.
- First publish of a new npm package must be done manually; OIDC works for subsequent versions.
- To re-publish a release (e.g. after a registry settings fix), do **not** delete/recreate the GitHub release — manually dispatch the package workflow instead: `gh workflow run <package>-cd.yml --ref refs/tags/<tag> -f tag=<tag>`.
- The **Zapier app** (`integrations/zapier-mem0`) deploys to Zapier's own platform, not npm, so it is **not** in the release router. Deploy it manually: `gh workflow run zapier-mem0-cd.yml --ref main` (requires the `ZAPIER_DEPLOY_KEY` secret).
- When adding a new package: add its CD workflow (`workflow_dispatch` with `tag`/`prerelease` inputs), then register its tag prefix in the `case` block in `release.yml`. Keep the bare `v*` arm last.
### Utility Workflows
| Workflow | File | Purpose |
|----------|------|---------|
| Issue Labeler | `issue-labeler.yml` | Automatic issue labeling |
| PR Labeler | `pr-labeler.yml` | Path-based PR labeling plus propagating labels from linked issues |
| Stale Bot | `stale.yml` | Marks stale issues and PRs |
| llms.txt Check | `docs-llms-txt-check.yml` | Blocks PRs touching `docs/**/*.mdx` when `docs/llms.txt` is out of sync. Fix locally with `python scripts/check-llms-txt-coverage.py --write`. |
## Task Completion Guidelines
These guidelines outline typical artifacts for different task types. Use judgment to adapt based on scope and context.
### Bug Fixes
1. **Unit tests**: Add tests that would fail without the fix (regression tests)
2. **Implementation**: Fix the bug
3. **Manual verification**: Run the relevant test suite to confirm the fix
4. **Lint**: Run the appropriate linter for the package you modified
### New Features
1. **Implementation**: Build the feature following existing patterns
2. **Unit tests**: Comprehensive test coverage for new functionality
3. **Documentation**: Update relevant docs in `docs/` for public APIs
4. **Examples**: Add usage examples if the feature introduces new user-facing behavior
5. **llms.txt**: Any new `.mdx` page under `docs/` must be linked in `docs/llms.txt` with a scope tag (`[Platform]` / `[OSS]` / `[Both]`) and a `Use when ...` description. The `docs-llms-txt-check.yml` workflow runs on every PR that touches docs and **fails the check** if the index is out of sync. To fix: run `python scripts/check-llms-txt-coverage.py --write` locally to scaffold placeholders under `## Unclassified - needs triage`, then replace the `[TODO: ...]` tags, rewrite descriptions as `Use when ...`, move entries into the right section, and delete the triage heading when empty.
### New Provider (LLM / Embedding / Vector Store / Reranker)
1. **Implementation**: Follow the "Adding a New Provider" steps above
2. **Tests**: Add unit tests matching the pattern of existing providers
3. **Configuration**: Add to the appropriate `configs.py` and `__init__.py`
4. **Dependencies**: Add to the correct optional group in `pyproject.toml`
5. **Documentation**: Add an integration guide in `docs/integrations/`
### Refactoring / Internal Changes
- Unit tests for any changed behavior
- No documentation needed for internal-only changes
- Ensure all existing tests still pass
### When to Deviate
These are guidelines, not rigid rules. Adjust based on:
- **Scope**: Trivial fixes (typos, comments) may not need tests
- **Visibility**: Internal changes may not need documentation
- **Context**: Some changes span multiple categories — use judgment
When uncertain about expected artifacts, ask for clarification.
## Contributing Guidelines
### Workflow
1. Fork and clone the repository.
2. Create a feature branch from `main` (e.g., `feature/my-new-feature`).
3. Make your changes — add tests, docs, and examples as appropriate.
4. Run linting and tests for every package you modified (see commands above).
5. Run `pre-commit install` on first setup — hooks run ruff + isort automatically.
6. Commit with a clear message following [Conventional Commits](https://www.conventionalcommits.org/) (e.g., `feat:`, `fix:`, `docs:`, `refactor:`).
7. Push and open a Pull Request against `main`.
### Pull Request Requirements
Every PR must follow the repo's PR template (`.github/PULL_REQUEST_TEMPLATE.md`):
1. **Linked Issue** — Reference the issue with `Closes #<number>`. If no issue exists, create one first or explain why in the description.
2. **Description** — Explain what the PR does and why it's needed.
3. **Type of Change** — Check the appropriate box:
- Bug fix / New feature / Breaking change / Refactor / Documentation update
4. **Breaking Changes** — If applicable, describe what breaks and the migration path.
5. **Test Coverage** — Check what applies:
- Added/updated unit tests
- Added/updated integration tests
- Tested manually (describe how)
- No tests needed (explain why)
6. **Checklist** — All must be checked before merge:
- [ ] Code follows the project's style guidelines
- [ ] Self-review performed
- [ ] Tests added that prove the fix/feature works
- [ ] New and existing tests pass locally
- [ ] Documentation updated if needed
### PR Description Template
```markdown
## Linked Issue
Closes #<!-- issue number -->
## Description
<!-- What does this PR do? Why is it needed? -->
## Type of Change
- [ ] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing functionality to change)
- [ ] Refactor (no functional changes)
- [ ] Documentation update
## Breaking Changes
N/A
## Test Coverage
- [ ] I added/updated unit tests
- [ ] I added/updated integration tests
- [ ] I tested manually (describe below)
- [ ] No tests needed (explain why)
## Checklist
- [ ] My code follows the project's style guidelines
- [ ] I have performed a self-review of my code
- [ ] I have added tests that prove my fix/feature works
- [ ] New and existing tests pass locally
- [ ] I have updated documentation if needed
```
### General Rules
- Follow existing code patterns — don't introduce new frameworks or abstractions without discussion.
- Version bumps go in `pyproject.toml` (Python) or `package.json` (TypeScript).
- For `server/` work, use Docker Compose for local development.
- Do NOT use `pip` or `conda` for dependency management — use `hatch` (see `docs/contributing/development.mdx`).
### Contributing Guides
| Task | Guide |
|------|-------|
| Code contributions | `docs/contributing/development.mdx` |
| Topic | File |
|-------|------|
| Contributor guide | [`CONTRIBUTING.md`](CONTRIBUTING.md) |
| Code of conduct | [`CODE_OF_CONDUCT.md`](CODE_OF_CONDUCT.md) |
| Security reports | [`SECURITY.md`](SECURITY.md) |
| Development setup | `docs/contributing/development.mdx` |
| Documentation contributions | `docs/contributing/documentation.mdx` |
| PR template | `.github/PULL_REQUEST_TEMPLATE.md` |
| Bug reports | `.github/ISSUE_TEMPLATE/bug_report.yml` |
| Feature requests | `.github/ISSUE_TEMPLATE/feature_request.yml` |
| Documentation issues | `.github/ISSUE_TEMPLATE/documentation_issue.yml` |
## Do NOT
- Modify CI/CD workflows without explicit approval.
- Add new Python dependencies to the core `dependencies` list in `pyproject.toml` without discussion — use optional dependency groups instead.
- Commit `.env` files, API keys, or credentials.
- Skip pre-commit hooks.
- Use npm or yarn in TypeScript packages — this repo uses pnpm exclusively.
- Use `require()` for imports in TypeScript — use ES module `import` syntax.
- Mix up linter configs: root Python SDK uses line-length 120, Python CLI uses 100, Node CLI uses Biome (not ESLint/Ruff).
- Change public APIs without updating documentation in `docs/`.
| Issue forms | `.github/ISSUE_TEMPLATE/` |
| Trust list (vouch) | `.github/VOUCHED.td` |
| CI/CD, gates, rulesets | [`.github/AGENTS.md`](.github/AGENTS.md) |
+181
View File
@@ -0,0 +1,181 @@
# Contributor Covenant Code of Conduct
## Our Pledge
We as members, contributors, and leaders pledge to make participation in our
community a harassment-free experience for everyone, regardless of age, body
size, visible or invisible disability, ethnicity, sex characteristics, gender
identity and expression, level of experience, education, socio-economic status,
nationality, personal appearance, race, caste, color, religion, or sexual
identity and orientation.
We pledge to act and interact in ways that contribute to an open, welcoming,
diverse, inclusive, and healthy community.
## Our Standards
Examples of behavior that contributes to a positive environment for our
community include:
- Demonstrating empathy and kindness toward other people
- Being respectful of differing opinions, viewpoints, and experiences
- Giving and gracefully accepting constructive feedback
- Accepting responsibility and apologizing to those affected by our mistakes,
and learning from the experience
- Focusing on what is best not just for us as individuals, but for the overall
community
Examples of unacceptable behavior include:
- The use of sexualized language or imagery, and sexual attention or advances of
any kind
- Trolling, insulting or derogatory comments, and personal or political attacks
- Public or private harassment
- Publishing others' private information, such as a physical or email address,
without their explicit permission
- Other conduct which could reasonably be considered inappropriate in a
professional setting
## Contribution Conduct
Mem0 receives more contributions than any maintainer can read line by line. The
rules below exist so that the time we do have goes to people who are actually
trying to improve the project. They apply to issues, pull requests, discussions,
and reviews.
**Be honest about how the work was produced.** Using an AI tool to find a bug,
write a patch, or draft a description is fine and welcome. Not saying so is not.
Every issue form and the pull request template ask about AI, and the answer is
never held against you. It tells a reviewer where to look. An unanswered review
comment on code the author cannot explain is what costs us the afternoon.
**Do not submit work you have not verified.** A reported bug means you ran it and
saw it. A pull request means you ran the tests. Pasting a model's output, a
scanner result, or a plausible-looking patch and letting maintainers find out
whether it is real moves your work onto someone else's desk. Reports and patches
that turn out to be unverified are closed without a detailed response.
**Do not fabricate evidence.** Invented tracebacks, benchmark numbers you did not
measure, reproductions that were never run, tests that assert the implementation
back at itself, and descriptions that describe a different change than the diff
makes are all treated the same way, regardless of whether a person or a tool
produced them.
**Match your volume to your engagement.** Open changes at the rate you can
discuss them. A queue of open pull requests from one author, none of them
answered when questioned, is treated as automated submission and handled under
enforcement below, whatever the individual diffs look like.
**Do not press for merges.** Bumping a thread, tagging maintainers repeatedly,
asking in Discord or by direct message for a review, and reopening a closed pull
request without addressing why it was closed all take attention away from the
queue rather than moving your change through it. One polite follow-up after a
reasonable wait is fine.
**Do not contribute for a badge.** Changes made to raise a contribution count,
qualify for an event, or pad a profile, whitespace edits, README churn, and
mechanical reformatting bundled with nothing else, are closed on sight.
**Disagreement is fine, and closing is not a verdict.** Our pull request gate
closes changes that do not yet link an accepted issue. That is a queue decision,
not a judgment of you or your code, and reopening takes about a minute. Argue for
your change on its merits; that is a normal and welcome part of contributing.
## Enforcement Responsibilities
Community leaders are responsible for clarifying and enforcing our standards of
acceptable behavior and will take appropriate and fair corrective action in
response to any behavior that they deem inappropriate, threatening, offensive,
or harmful.
Community leaders have the right and responsibility to remove, edit, or reject
comments, commits, code, wiki edits, issues, and other contributions that are
not aligned to this Code of Conduct, and will communicate reasons for moderation
decisions when appropriate.
## Scope
This Code of Conduct applies within all community spaces, including this
repository, our Discord, and our documentation, and also applies when an
individual is officially representing the community in public spaces. Examples of
representing our community include using an official email address, posting via
an official social media account, or acting as an appointed representative at an
online or offline event.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported to the maintainers at **support@mem0.ai**. All complaints will be
reviewed and investigated promptly and fairly.
All community leaders are obligated to respect the privacy and security of the
reporter of any incident.
## Enforcement Guidelines
Community leaders will follow these Community Impact Guidelines in determining
the consequences for any action they deem in violation of this Code of Conduct:
### 1. Correction
**Community Impact**: Use of inappropriate language or other behavior deemed
unprofessional or unwelcome in the community, or a first contribution that
breaches the Contribution Conduct rules above.
**Consequence**: A private, written warning from community leaders, providing
clarity around the nature of the violation and an explanation of why the
behavior was inappropriate. A public apology may be requested.
### 2. Warning
**Community Impact**: A violation through a single incident or series of
actions, including a repeated pattern of unverified or automated submissions
after a first warning.
**Consequence**: A warning with consequences for continued behavior. No
interaction with the people involved, including unsolicited interaction with
those enforcing the Code of Conduct, for a specified period of time. This
includes avoiding interactions in community spaces as well as external channels
like social media. Violating these terms may lead to a temporary or permanent
ban. At this stage the account may be denounced in `.github/VOUCHED.td`, which
means new pull requests are flagged automatically.
### 3. Temporary Ban
**Community Impact**: A serious violation of community standards, including
sustained inappropriate behavior.
**Consequence**: A temporary ban from any sort of interaction or public
communication with the community for a specified period of time. No public or
private interaction with the people involved, including unsolicited interaction
with those enforcing the Code of Conduct, is allowed during this period.
Violating these terms may lead to a permanent ban.
### 4. Permanent Ban
**Community Impact**: Demonstrating a pattern of violation of community
standards, including sustained inappropriate behavior, harassment of an
individual, or aggression toward or disparagement of classes of individuals.
**Consequence**: A permanent ban from any sort of public interaction within the
community.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
version 2.1, available at
[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
The Contribution Conduct section is specific to this repository.
Community Impact Guidelines were inspired by
[Mozilla's code of conduct enforcement ladder][mozilla].
For answers to common questions about this code of conduct, see the FAQ at
[https://www.contributor-covenant.org/faq][faq]. Translations are available at
[https://www.contributor-covenant.org/translations][translations].
[homepage]: https://www.contributor-covenant.org
[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
[mozilla]: https://github.com/mozilla/inclusion
[faq]: https://www.contributor-covenant.org/faq
[translations]: https://www.contributor-covenant.org/translations
+52 -2
View File
@@ -7,6 +7,12 @@ new features, documentation, examples, and integrations.
Mem0 is a polyglot monorepo, and this guide covers contributing to both the
**Python SDK** and the **TypeScript SDK** (and the rest of the repository).
By participating you agree to our [Code of Conduct](./CODE_OF_CONDUCT.md). Its
**Contribution Conduct** section is the enforceable form of the rules on this
page: disclose AI use, don't submit work you haven't run, don't fabricate
reproductions or benchmarks, keep your volume matched to your engagement, and
don't press for merges.
## Before You Start
### 1. Open an Issue First
@@ -23,9 +29,53 @@ in code.
- For anything beyond a trivial fix, wait for a maintainer to confirm the approach
before starting significant work.
Every pull request must link to an issue using `Closes #<issue-number>`.
A bug report needs a reproduction we can run, the version you are on, and the
real output or traceback you saw. Reports without those cannot be acted on and
get closed. A feature request needs the problem you hit and the workaround you
are living with, not just the API you would like.
### 2. Sign the Contributor License Agreement (CLA)
Every pull request must link to an issue using `Closes #<issue-number>`, and that
issue must carry the `accepted` label. A maintainer applies `accepted` once we
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,
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
a private advisory and a private fork so the vulnerability isn't disclosed before
the fix ships.
### 2. Understand Your Code
**You must be able to explain what your changes do and how they interact with
the rest of the codebase without the help of an AI tool.** This is the one rule
we will not bend on.
Using AI to write code is fine. Most of us do. You can build real understanding
by interrogating an agent about this codebase until you grasp the edge cases and
the blast radius of your change. What is not fine is opening a pull request for
a diff you cannot defend in review.
Disclose it in the pull request template and say what you checked yourself.
We ask about the code, not the write-up: using AI to draft the pull request
description is fine. We ask because it tells reviewers where to look, not
because it counts against you. An honest "an agent wrote this, here is what I
verified" is welcome. Silence, followed by a review comment you cannot answer,
is what wastes everyone's time.
Signs your pull request will be closed:
- Invented APIs, config keys, or providers that don't exist in this repo.
- Tests that assert the implementation back at itself rather than the behaviour.
- A description that describes a different change than the diff makes.
- Sweeping unrelated reformatting bundled with a small fix.
- You cannot answer a direct question about your own diff.
### 3. Sign the Contributor License Agreement (CLA)
**We cannot accept or merge any pull request until you have signed our Contributor
License Agreement (CLA).**
+6
View File
@@ -26,6 +26,12 @@ following as you can:
- Clear, step-by-step reproduction instructions
- The security impact and a proof of concept, if available
- Any suggested fix or mitigation
- Whether an AI tool was involved in finding or writing up the report
Reports generated by an AI tool are welcome, but only once you have run the
reproduction yourself and confirmed the impact is real. A scan result or model
output pasted in without that step is not a vulnerability report, and we close
those without a detailed response so we can spend the time on real ones.
## Response Process
+49
View File
@@ -0,0 +1,49 @@
# Documentation (`docs/`)
Mintlify site published at https://docs.mem0.ai.
## Commands
```bash
make docs # from repo root
cd docs && mintlify dev
```
## Structure
| Path | Contents |
|------|----------|
| `api-reference/` | Platform REST endpoints |
| `open-source/` | Self-hosted SDK guides |
| `platform/` | Hosted platform guides |
| `integrations/` | One page per integration |
| `core-concepts/` | Memory model, graph memory, scoping |
| `cookbooks/` | End-to-end recipes |
| `contributing/` | Contributor guides |
| `docs.json` | Navigation tree |
| `openapi.json` | Platform API spec |
| `llms.txt` | Scope-tagged index for agents |
## Adding a page
Every new `.mdx` page needs three things, or CI fails:
1. The page itself under the right section.
2. A navigation entry in `docs.json`.
3. A line in `llms.txt` with a scope tag (`[Platform]`, `[OSS]`, or `[Both]`) and a description that starts with `Use when ...`.
`docs-llms-txt-check.yml` runs on every PR touching `docs/**/*.mdx` and **blocks the merge** when `llms.txt` is out of sync. To fix:
```bash
python scripts/check-llms-txt-coverage.py --write
```
That scaffolds placeholders under `## Unclassified - needs triage`. Then replace each `[TODO: ...]` tag, rewrite the descriptions as `Use when ...`, move entries into the correct section, and delete the triage heading once it is empty.
## Conventions
- Frontmatter needs `title`, `description`, and usually `icon`.
- Mintlify components (`<Note>`, `<Card>`, `<Tabs>`, `<CodeGroup>`) are available; prefer them over raw HTML.
- Code samples must be runnable. If a sample calls a public SDK method, it has to match the real signature.
- Documentation-only PRs are exempt from the `accepted`-issue requirement in the PR gate, but not from the CLA.
- Any change to a public SDK signature has to update the matching page here in the same PR.
+1
View File
@@ -0,0 +1 @@
AGENTS.md
+24 -2
View File
@@ -14,7 +14,8 @@ Follow the steps below for a smooth contribution process.
<Note>
For the complete contributor checklist, see
[CONTRIBUTING.md](https://github.com/mem0ai/mem0/blob/main/CONTRIBUTING.md) in
the repository root.
the repository root. By participating you agree to our
[Code of Conduct](https://github.com/mem0ai/mem0/blob/main/CODE_OF_CONDUCT.md).
</Note>
## Before You Start
@@ -30,7 +31,28 @@ change, avoid duplicate work, and agree on the approach before you write code.
or [feature request](https://github.com/mem0ai/mem0/issues/new?template=feature_request.yml).
- For anything beyond a trivial fix, wait for a maintainer to confirm the approach.
Every pull request must link to an issue using `Closes #<issue-number>`.
Every pull request must link to an issue using `Closes #<issue-number>`, and that
issue must carry the `accepted` label. A maintainer applies `accepted` once we
agree the change is worth making. Pull requests that do not link an accepted
issue are closed automatically, with instructions to reopen once the label is
applied. Documentation-only changes are exempt.
<Note>
Closed does not mean rejected. Getting the label and reopening takes about a
minute, and the check reruns on reopen.
</Note>
### Show Your Work
Both issue forms ask how you verified the problem: what you ran, the real output
you saw, and why it is a bug rather than expected behavior. Reports without that
are hard to act on and usually sit unanswered.
They also ask whether AI was involved. That question is about how the problem was
found and confirmed, not about how the text was written: drafting the write-up
with a model is fine. The same applies to pull requests, where the AI disclosure
covers the code in the diff. We ask because it tells reviewers where to look, not
because it counts against you.
### 2. Sign the Contributor License Agreement (CLA)
+55
View File
@@ -0,0 +1,55 @@
# Integrations (`integrations/`)
Agent and editor integrations. Each subdirectory is self-contained: its own `package.json`, lockfile, build, and tests. **There is no shared toolchain.** Check the table before running anything.
| Directory | Package | Build | Lint | Test |
|-----------|---------|-------|------|------|
| `vercel-ai-sdk/` | `@mem0/vercel-ai-provider` | tsup (CJS+ESM) | ESLint + Prettier | jest + vitest (edge/node) |
| `openclaw/` | `@mem0/openclaw-mem0` | tsup (ESM) | none | vitest |
| `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 |
| `n8n-nodes-mem0/` | `@mem0/n8n-nodes-mem0` | tsc | ESLint (n8n-nodes-base) | none |
| `zapier-mem0/` | `@mem0/zapier` | tsc | none | offline unit tests + `zapier validate` |
pnpm everywhere except `.opencode-plugin/`, which uses Bun. Never npm, never yarn.
## Commands
```bash
cd integrations/vercel-ai-sdk
pnpm install
pnpm run build # tsup
pnpm run lint # eslint
pnpm run type-check # tsc --noEmit
pnpm run prettier-check
pnpm run test # jest
pnpm run test:edge # vitest, edge runtime
pnpm run test:node # vitest, node runtime
cd integrations/openclaw
pnpm install
pnpm run build # tsup
pnpm run test # vitest
```
Run the type check after every TypeScript change: `pnpm run typecheck` or `tsc --noEmit`, whichever the package defines.
## 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`.
- **`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).
## Adding an integration
1. Create `integrations/<name>/` and build it there, self-contained.
2. If it publishes to a registry, set `repository.directory: "integrations/<name>"` in `package.json` so npm provenance links to the right subdirectory.
3. Add `.github/workflows/<name>-checks.yml` and `<name>-cd.yml`. Use `integrations/<name>` in the `paths:` trigger, `working-directory`, and `cache-dependency-path`. Register the release tag prefix in the `case` block in `release.yml`, keeping the bare `v*` arm last.
**Workflow filenames are load-bearing:** npm OIDC trusted publishing is pinned to repository plus workflow filename. Renaming one breaks publishing.
4. Register the CI workflow in `ci-gate.yml`: a path filter under the `changes` job, a call job, and an entry in the gate job's `needs` list.
5. If it is a Claude Code or editor marketplace plugin, register its path in all five `marketplace.json` files: root, `.claude-plugin/`, `.cursor-plugin/`, `.codex-plugin/`, and `.agents/plugins/`.
6. Document it under `docs/integrations/` and add the page to `docs/docs.json` and `docs/llms.txt`.
7. Add rows to the table above and to the CI/CD tables in [`../.github/AGENTS.md`](../.github/AGENTS.md).
+1
View File
@@ -0,0 +1 @@
AGENTS.md
+56
View File
@@ -0,0 +1,56 @@
# TypeScript SDK (`mem0-ts/`)
The `mem0ai` package on npm. Hosted client plus self-hosted OSS memory.
## Commands
```bash
pnpm install
pnpm run build # tsup (CJS + ESM)
pnpm run test # jest, all tests
pnpm run test:unit # jest --coverage
pnpm run test:integration # jest, needs MEM0_API_KEY
pnpm run test:ci # jest --coverage --ci
pnpm run test:watch
pnpm run typecheck # tsc --noEmit
```
pnpm only. Never npm, never yarn.
## Conventions
- **Node 20 and 22** are the CI-tested versions.
- **Build:** tsup, dual CJS + ESM output.
- **Formatter:** Prettier. No linter is configured here; `cli/node/` uses Biome and `integrations/vercel-ai-sdk/` uses ESLint, so do not assume a shared setup.
- **Tests:** jest. `cli/node/` and `integrations/openclaw/` use vitest instead.
- **TypeScript strict mode.**
- ES module `import` syntax only. Never `require()`.
- Source files are `snake_case.ts`, tests are `<module>.test.ts`.
Run `pnpm run typecheck` after every change.
## Layout
```
mem0-ts/src/
├── client/ MemoryClient (hosted platform)
└── oss/ Memory (self-hosted)
├── llms/
├── embeddings/
├── vector_stores/
└── graphs/
```
## Public API
| Export | Purpose | Import |
| -------------- | ---------------------- | ---------------------------------------------- |
| `MemoryClient` | Hosted platform client | `import { MemoryClient } from 'mem0ai'` |
| `Memory` | Self-hosted OSS memory | `import { Memory } from 'mem0ai/oss'` |
| Providers | OSS building blocks | `import { OpenAIEmbedding } from 'mem0ai/oss'` |
The method surface mirrors the Python SDK: `add`, `search`, `get`, `getAll`, `update`, `delete`, `deleteAll`, `history`. Changing any public signature means updating `docs/` in the same PR.
## Releasing
Tag prefix `ts-v*` triggers `ts-sdk-cd.yml`, which publishes to npm over OIDC. Bump the version in `package.json` first.
+1
View File
@@ -0,0 +1 @@
AGENTS.md
+105
View File
@@ -0,0 +1,105 @@
# Python SDK (`mem0/`)
The `mem0ai` package on PyPI. Memory core plus five pluggable provider categories.
## Commands
```bash
hatch shell dev_py_3_11 # or dev_py_3_9 / dev_py_3_10 / dev_py_3_12
pre-commit install # first time only; runs ruff + isort on commit
make lint # ruff check
make format # ruff format
make sort # isort mem0/
make test # pytest tests/
make test-py-3.9 # pin a Python version (3.9 through 3.12)
make install_all # optional deps; run before the full test suite
make build # hatch build
```
Use `hatch` for environments and dependencies. Do not use `pip` or `conda`.
## Conventions
- **Python 3.9 through 3.12.** Code must run on 3.9.
- **Ruff**, line length **120**. `cli/python/` uses 100; do not carry that config across.
- **isort**, `profile = "black"`, first-party `mem0` and `mem0_cli`.
- **Pydantic v2** for every data model and config class.
- **pytest** with pytest-mock and pytest-asyncio. Tests live in `../tests/`.
- Source files are `snake_case.py`.
## Layout
```
mem0/
├── memory/ Memory, AsyncMemory
├── client/ MemoryClient, AsyncMemoryClient
├── configs/ MemoryConfig and per-category config models
├── llms/ 24 providers
├── embeddings/ 15 providers
├── vector_stores/ 30 providers
├── graphs/ 4 providers
└── reranker/ 5 providers
```
## Provider pattern
Every category follows the same shape: a `base.py` with the abstract class, one module per provider, config models in `configs.py`, registration in `__init__.py`.
| Category | Count | Examples |
|----------|-------|---------|
| LLMs | 24 | OpenAI, Anthropic, AWS Bedrock, Azure OpenAI, Gemini, Groq, Ollama, Together, DeepSeek, vLLM, LiteLLM, LM Studio, xAI |
| Vector stores | 30 | Qdrant, Pinecone, Chroma, Weaviate, Milvus, MongoDB, Redis, Elasticsearch, pgvector, Supabase, Faiss, S3 Vectors |
| Embeddings | 15 | OpenAI, Azure OpenAI, Gemini, HuggingFace, FastEmbed, Together, AWS Bedrock, Ollama, Vertex AI |
| Graph stores | 4 | Neo4j, Memgraph, Kuzu, Apache AGE |
| Rerankers | 5 | Cohere, HuggingFace, LLM-based, Sentence Transformer, Zero Entropy |
### Adding a provider
1. Create `mem0/<category>/<provider_name>.py`.
2. Inherit the abstract base class from `mem0/<category>/base.py`.
3. Add its config to `mem0/<category>/configs.py` if the category uses one.
4. Register it in `mem0/<category>/__init__.py`.
5. Add tests under `tests/<category>/<provider_name>/`.
6. Put new dependencies in an **optional** group in `pyproject.toml`, never in core `dependencies`.
7. Match an existing provider in the same category exactly: method signatures, error handling, config structure.
8. Add an integration guide under `docs/integrations/`.
## Public API
| Class | Purpose | Import |
|-------|---------|--------|
| `Memory` | Self-hosted, sync | `from mem0 import Memory` |
| `AsyncMemory` | Self-hosted, async | `from mem0 import AsyncMemory` |
| `MemoryClient` | Hosted platform, sync | `from mem0 import MemoryClient` |
| `AsyncMemoryClient` | Hosted platform, async | `from mem0 import AsyncMemoryClient` |
Both `Memory` and `MemoryClient` expose the same surface:
| Method | Purpose |
|--------|---------|
| `add(messages, *, user_id, agent_id, run_id, metadata)` | Store a memory |
| `search(query, *, user_id, agent_id, run_id, limit, filters)` | Search memories |
| `get(memory_id)` | Fetch one memory |
| `get_all(*, user_id, agent_id, run_id, limit)` | List memories |
| `update(memory_id, data)` | Update a memory |
| `delete(memory_id)` | Delete a memory |
| `delete_all(*, user_id, agent_id, run_id)` | Delete a scope |
| `history(memory_id)` | Change history for a memory |
Changing any of these signatures means updating `docs/` in the same PR.
### Import paths
| What | Import |
|------|--------|
| Memory classes | `from mem0 import Memory, AsyncMemory` |
| Platform client | `from mem0 import MemoryClient, AsyncMemoryClient` |
| Configuration | `from mem0.configs.base import MemoryConfig` |
| LLM provider | `from mem0.llms.<provider> import <ProviderLLM>` |
| Embedding provider | `from mem0.embeddings.<provider> import <ProviderEmbedding>` |
| Vector store provider | `from mem0.vector_stores.<provider> import <ProviderVectorStore>` |
## Graph memory
An optional layer on top of vector memory for relationship-aware retrieval, configured through the `graph` section of `MemoryConfig`. It supplements vector search rather than replacing it.
+1
View File
@@ -0,0 +1 @@
AGENTS.md
+31
View File
@@ -0,0 +1,31 @@
# Self-hosted server (`server/`)
FastAPI REST server wrapping the Python SDK. Docker only; there is no local non-Docker path.
## Commands
```bash
# Production image
make build # docker build -t mem0-api-server .
make run_local # docker run -p 8000:8000 with .env
# Development stack (FastAPI + PostgreSQL/pgvector + Neo4j)
docker-compose up
```
| Service | Port |
|---------|------|
| mem0 API | 8888 |
| PostgreSQL (pgvector) | 8432 |
| Neo4j HTTP | 8474 |
| Neo4j Bolt | 8687 |
## Conventions
- **Framework:** FastAPI on uvicorn, auto-reload in dev.
- **Stores:** PostgreSQL with the pgvector extension, Neo4j 5.x with the APOC plugin.
- **Hot reload:** the dev Dockerfile mounts both `server/` and `mem0/`, so SDK edits take effect without a rebuild.
- Use Docker Compose for local work. Do not add a "run it with uvicorn directly" path.
- The server imports the Python SDK from the repo, so its conventions apply to any SDK code you touch: see [`../mem0/AGENTS.md`](../mem0/AGENTS.md).
Never commit `.env`. Credentials for the compose services belong in `.env.example` as placeholders only.
+1
View File
@@ -0,0 +1 @@
AGENTS.md
+100
View File
@@ -0,0 +1,100 @@
# Skills (`skills/`)
Claude Code skill definitions published from this repo. Agents fetch them by raw URL, so treat every file here as a public API.
## The two kinds
**Reference skills** carry SDK knowledge and are always available:
| Skill | Covers |
|-------|--------|
| `mem0/` | Python + TypeScript SDKs, Platform and OSS, framework integrations |
| `mem0-cli/` | Terminal workflows for `mem0-cli` and `@mem0/cli` |
| `mem0-vercel-ai-sdk/` | The `@mem0/vercel-ai-provider` package |
**Pipeline skills** run on demand and have side effects:
| Skill | Does |
|-------|------|
| `mem0-integrate/` | Wires Mem0 into an existing repo through a TDD pipeline. Writes a feature branch plus `.mem0-integration/` artifacts. |
| `mem0-test-integration/` | Verifies what the integrator produced, on the same branch. Read-only against the repo. |
| `mem0-oss-to-platform/` | Migrates a project from OSS to the hosted Platform SDK. Plans first, executes on approval. |
`mem0-integrate` and `mem0-test-integration` are **loosely coupled**: they share state only through `.mem0-integration/` files, never through conversation context.
## File layout
```
skills/<name>/
├── SKILL.md entry point, always loaded when the skill triggers
├── README.md human-facing, GitHub renders this
├── LICENSE Apache-2.0
├── references/ loaded on demand, one file per topic
├── client/ optional, per-runtime call patterns
└── scripts/ optional executables
```
## Size budget
`SKILL.md` is loaded in full every time the skill fires, so it is the expensive file. Keep it **under 500 lines**. Everything past the decision-making core belongs in `references/`, which the agent loads only when it needs that topic.
Rule of thumb for what stays in `SKILL.md`:
- Frontmatter, including the trigger and do-not-trigger conditions.
- Anything the agent must honor on **every** run: non-negotiable principles, preconditions, gates.
- A one-line-per-step overview of the pipeline.
- Invocation, modes, exit codes.
Everything else, meaning full step mechanics, document templates, and verbatim subagent prompts, goes in `references/` with a link from the overview.
Current sizes, longest first:
```
mem0/references/use-cases.md 720 reference, on demand
mem0-cli/references/command-reference.md 694 reference, on demand
mem0/client/python.md 487 reference, on demand
mem0-integrate/references/pipeline.md 375 reference, on demand
mem0-test-integration/SKILL.md 368 entry point, under budget
mem0-integrate/SKILL.md 220 entry point
mem0/SKILL.md 193 entry point
mem0-vercel-ai-sdk/SKILL.md 192 entry point
mem0-cli/SKILL.md 169 entry point
mem0-oss-to-platform/SKILL.md 120 entry point
```
`mem0-integrate` is the one skill that needed splitting: it was 620 lines, now
220, with the ten-step mechanics in `references/pipeline.md` and the two
verbatim subagent system prompts in `references/subagent-prompts.md`. The
`SKILL.md` keeps only what every run must honor: canonical sources, the seven
integration principles, the delegation table, preconditions, a one-line-per-step
pipeline overview, artifacts, modes, invocation, and exit codes.
Reference files may run long. They are only read when the agent asks for that topic, so a 700-line `use-cases.md` costs nothing on a run that never opens it.
## Frontmatter
```yaml
---
name: <matches the directory name>
description: >
What it does, then TRIGGER when: ... then DO NOT TRIGGER when: ...
The trigger conditions are what routing depends on. Be specific and
name the sibling skill to use instead.
license: Apache-2.0
metadata:
author: mem0ai
version: "0.1.0"
category: ai-memory
tags: "comma, separated"
mem0_tested_versions: "mem0ai (PyPI) >=2.0.0,<3.0.0; mem0ai (npm) >=3.0.0,<4.0.0"
---
```
Bump `mem0_tested_versions` whenever the SDK majors move. Skills that pin call shapes against a version that no longer exists produce code that fails at runtime, which is worse than a skill that declines to fire.
## Conventions
- Cite canonical sources by URL (`https://docs.mem0.ai/llms.txt`, `openapi.json`, raw skill URLs). Skills must not rely on ambient model knowledge of the Mem0 API.
- When one skill's territory is covered by another, delegate to it by raw URL rather than paraphrasing its patterns.
- Pipeline skills declare **exit codes** in a table and mean them.
- Cross-references between files use relative paths so the skill works when vendored into another repo.
+1
View File
@@ -0,0 +1 @@
AGENTS.md
+14 -414
View File
@@ -141,422 +141,22 @@ Exit with a written rationale if any precondition fails. Do not try to
## Pipeline
### 1. Language detection
Ten steps. Full mechanics, document templates, and gate rules are in
[`references/pipeline.md`](references/pipeline.md). Read that file when you
start executing a step; the summary below is only for routing.
| Signal | Track |
|---|---|
| `package.json` + TypeScript config | Node / TypeScript |
| `package.json` (no TS config) | Node / JavaScript |
| `pyproject.toml` or `requirements.txt` | Python |
Monorepo with both → ask which subdirectory to operate in, then recurse.
### 2. Repo comprehension — what does this repo do, and where is the backend?
Before any decision (product, goal, plan), understand the repo enough
to locate *where in the backend* the integration belongs. This is not
fit-surveying — the user already decided Mem0 fits. This is mechanics:
you cannot write a plan without knowing what files matter.
Read, in order, with a token budget — do not scan the whole tree:
1. `README.md` (root) + first-page of any `README_*.md` variants.
2. `CONTRIBUTING.md` / `AGENTS.md` / `CLAUDE.md` at root if present —
these often spell out architecture and entry points.
3. `package.json` / `pyproject.toml` scripts + entry points.
4. The layout of the top two directory levels (not recursive).
5. Key config files: `docker-compose.yml`, `Dockerfile`, `Makefile`,
`langgraph.json`, `next.config.*`, `nuxt.config.*`.
Produce `.mem0-integration/repo-summary.md`:
# Repo comprehension
**What this repo does:** <one paragraph in plain English. Who is
the end user? What does the app do for them? What LLM / agent
behavior is central? Do not list dependencies — describe behavior.>
**Architecture at a glance:**
- Backend: <path(s), framework, primary entry point>
- Frontend: <path(s) if any, framework — for context only; no
integration here>
- Agent loop / orchestration: <LangGraph? custom? none?>
- Existing memory/session/state systems: <name them — these are
what step 6 Coexistence must preserve>
**Candidate backend integration surfaces** (ranked, best first):
1. `<backend-file>:<line_range>` — <function> — <one-sentence
reason this is where write/read could slot in without
replacing anything existing>
2. ...
3. ...
**Not a fit here:** <list anything the skill considered but ruled
out — e.g., "frontend chat component: client-side, excluded by
backend-only rule"; "existing memory subsystem X: would require
replacement, excluded by additive principle">
**Sources read:** <list the files actually opened, with line counts,
so reviewers can verify coverage.>
Show the user the rendered summary and ask: *"Is this understanding
correct? Which of the candidate surfaces (1, 2, 3 ...) should step 3
forward target?"*
Gate rules:
- If no backend surface is found → exit code 1. The preconditions
should already have caught frontend-only repos; reaching this point
means a more subtle miss (e.g., the "backend" is actually just a
static build). Do not force a fit.
- If every candidate surface would require replacing an existing
memory/session system → exit code 1 with the "additive principle"
rationale. The user can manually point at a non-conflicting location
and re-run.
- User corrections update `repo-summary.md` and re-confirm. Max 3
rounds; beyond that, exit code 1.
The user's chosen surface index is baked into `product.json` as
`preferred_site` and referenced by steps 5 and 6.
### 3. Product selection — Platform vs OSS (ask with a recommendation)
Read the `## Identify the User's Setup` block in
`https://docs.mem0.ai/llms.txt` for the Platform-first routing rules, then
apply the heuristics below. Ask, but never blank:
- Other managed-service SDKs present (`@clerk/*`, `stripe`, `@supabase/*`,
`openai`, `@upstash/*`, `posthog-*`) — 3+ → recommend **Platform**.
- Local-infra signals (`docker-compose.yml` with postgres / redis / qdrant /
neo4j, ollama configs, self-hosted auth) — 2+ → recommend **OSS**.
- No strong signal → default recommendation: **Platform** (lower integration
cost; migration later is supported).
Example:
> I see `stripe`, `@clerk/nextjs`, and `@supabase/supabase-js` — managed
> services throughout. I recommend **Mem0 Platform** (4-line integration).
> Override and use open source?
Bake the choice into the goal doc in step 5. Do not re-decide later.
### 4. API key check (env-first, then ask)
| Track | Key | Where to find |
| # | Step | Gate |
|---|---|---|
| Platform | `MEM0_API_KEY` | https://app.mem0.ai |
| OSS (default LLM) | `OPENAI_API_KEY` | https://platform.openai.com/api-keys |
If present in env → continue.
If `MEM0_API_KEY` is missing AND the track is **Platform** → **default to Agent Mode**: run `mem0 init --agent --agent-caller <your-name> --json` (after `pip install mem0-cli` or `npm install -g @mem0/cli`), substituting your agent identity (e.g. `claude-code`, `cursor`, `codex`). If you forgot to pass `--agent-caller`, run `mem0 identify <your-name>` after init. Cache the key to `.env` (with user consent) and continue. Tell the user to claim later with `mem0 init --email <their-email>` — same key, no agent disruption.
If missing AND **CI mode** (`MEM0_INTEGRATE_CI=1`) → exit with code 2 and the name of the missing key.
Never echo key values into `trace.jsonl`. Persist to `.env` only with
explicit user consent, and append `.env` to `.gitignore` if not already there.
If the user is on OSS and wants a non-OpenAI LLM, route them to the
`components/llms/*` docs and re-run this step with the chosen provider's key.
### 5. Goal doc — the hard gate
Write `.mem0-integration/goal.md` and **require user approval before step 6**.
Template:
# Mem0 Integration Goal
**What gets stored:** <one sentence — user utterances? extracted
preferences? a specific domain fact like "dietary restrictions"?>
**When it gets retrieved:** <one sentence — on each user turn? before a
specific tool call? at session start?>
**Why:** <one sentence — the user-visible behavior change. "Assistant
remembers previous orders across sessions," not "we added memory.">
**Product:** Platform | OSS (locked from step 3, do not change)
**Delegated skill:** <raw URL of the published skill being used
from "Skill delegation rules" above, or "none — custom integration
against `skills/mem0`">.
**Out of scope:** <anything explicitly excluded: "no graph memory,"
"no multimodal," "no migration from existing store">
Rules:
- User must approve explicitly. If they edit the doc, reload and re-confirm.
- `goal.md` is the contract the test suite is written against. Never
rewrite it after step 6 starts.
- Max 3 rejection rounds. On the 4th, exit with code 3 and the rejection
notes — the integration is not well-specified enough to proceed.
### 6. Integration plan — how and where (hard gate)
Given `goal.md` is "what and why," this step produces "where and how" and
gets explicit user sign-off before any code is written.
The skill does a **scoped** read of the repo (no wide survey):
- Grep for the LLM call sites that match the goal (e.g., `openai.chat.`,
`anthropic.messages.`, `model.generateContent`, `ChatOpenAI`, `createLLM`).
- Grep for the user-identity source (`req.user`, `session.user`, `auth()`,
`ctx.userId`, cookies).
- Check `package.json` / `pyproject.toml` / `requirements.txt` for
conflicts (e.g., existing `mem0ai` at a different version).
Then write `.mem0-integration/plan.md`:
# Mem0 Integration Plan
**Write pattern:** <one sentence — e.g., "After each assistant reply,
call client.add([user_msg, assistant_msg], user_id=<source>).">
**Read pattern:** <one sentence — e.g., "Before building the LLM prompt,
call client.search(query=latest_user_msg, user_id=<source>, limit=5)
and inject results as a system message.">
**User identifier source:** <code path — e.g., `req.auth.userId`,
`session.user.email`, `ctx.params.user_id`. If none, ask the user.>
**Session scoping:**
- user_id: <source>
- agent_id: <static slug | null>
- run_id: <source | null>
**Write call site:** `<file:line_range>` — inside `<function>`
**Read call site:** `<file:line_range>` — inside `<function>`
**Dependencies to add:**
- `<package>@<version pinned in frontmatter>`
**Preserved behavior:** <list the existing repo behaviors that must
keep working after this edit — e.g., "existing OpenAI streaming still
works," "existing Redis session store still used," "existing tests
still pass unchanged.">
**Coexistence:** <one bullet per existing system the integration sits
alongside. Name the files/classes. Example: "The existing
`agents/memory/storage.py` MemoryStorage class remains untouched and
keeps its LangGraph SummarizationEvent flow. Mem0 is added as a
parallel long-term-facts store, in a new file, invoked only when
MEM0_ENABLED=1 is set.">
**Feature flag:** <the exact mechanism and the default. Required.
Example: `env MEM0_ENABLED=1`, default unset / off; `config.mem0.enabled`,
default false. With the flag in its default state, the repo must
behave exactly like `main`.>
**Sources consulted:** <minimum 2 URLs from "Canonical sources" above
that informed this plan. At least one `docs.mem0.ai` URL and one
delegated-skill URL. Cite the specific section or heading.>
**E2E recipe:** <how the verification skill should drive the app
end-to-end. Omit only if the repo is a pure library with no runnable
entry point — in which case the E2E step will skip with a warning.>
start: <shell command to launch the app locally,
using $PORT for any network port>
ready_probe: <one of: url=<URL> status=<code> /
log="<substring to wait for>" /
sleep=<seconds, last resort>>
compose_services: <optional: whitespace-separated service
names in docker-compose.yml to start first;
use label mem0-e2e: "true" to mark them>
write_call: <command that triggers the Mem0 write path
exactly once; ≤ 60s runtime>
write_async_wait_ms: <milliseconds to wait after write_call for
async memory flush; default 0>
read_call: <command that triggers the Mem0 read path,
typically a fresh session / new request>
read_assert: <substring, regex, or jsonpath=<expr>=<value>
that MUST appear in read_call's output for
the E2E to pass. Derived from goal.md's
"What gets stored.">
**Rejected alternatives:** <briefly, 1–2 bullets — patterns the skill
considered but did not pick, and why. Helps the user decide.>
Rules:
- Show the user the proposed call sites with 10 lines of context around
each before asking for approval.
- If the skill can't find a plausible call site for either write or read,
it exits with code 5 and asks the user to name the file(s) manually
(this is the "no fit here" signal — don't guess).
- Max 3 rejection rounds on the plan. On the 4th, exit code 5 with the
last plan and the user's notes.
- If the user edits `plan.md` by hand, reload and re-confirm.
`plan.md` (not `goal.md`) is the contract the subagent implements against
in step 8.
### 7. Tests first (TDD)
Main agent writes failing tests against `goal.md` in the repo's native
test framework:
| Track | Default framework |
|---|---|
| Python | `pytest` |
| TypeScript | `vitest` if detected, else `jest` |
| JavaScript | same |
Test assertion shapes must match the **canonical signatures**:
- Platform method signatures: `https://docs.mem0.ai/openapi.json`
(request body schemas for `/v1/memories/` and `/v1/memories/search/`).
- OSS method signatures: the delegated skill named in `plan.md`
(fetched from its raw URL) or `skills/mem0/SKILL.md` as the default.
- Do not hand-roll request shapes. If the delegated skill has an
example block, lift it verbatim.
Minimum two test files (paths taken from `plan.md` call sites):
- `test_mem0_write.<ext>` — asserts `add()` is called at the Write call
site with the right payload shape (Platform messages-array vs OSS string)
and the right `user_id` source.
- `test_mem0_read.<ext>` — asserts `search()` runs before the Read call
site and the result is wired into the LLM prompt / response path.
Tests MUST be importable with `MEM0_API_KEY` unset. This is the design
pressure that forces step 8's lazy `MemoryClient()` / `Memory()`
construction — eager module-level init hits the API on import and
breaks pre-existing test collection when the key is missing.
Run the tests. They **must fail**. If they pass before any implementation,
the tests are wrong — rewrite them.
### 8. Implementation (subagent, fresh context)
Spawn a subagent with:
- **Inputs**: the repo, `goal.md`, `plan.md`, the two test files, and
direct URLs to: the delegated skill (from `plan.md`), the SDK source
(pinned per `mem0_tested_versions`), `https://docs.mem0.ai/llms.txt`,
and `https://docs.mem0.ai/openapi.json`.
- **No access** to main agent's reasoning trace or scratchpad.
- **System prompt** (verbatim):
You are implementing a Mem0 integration for an existing repo.
Read these first:
- plan.md (the mechanical contract)
- goal.md (the intent — do not change it)
- the test files (do not change them either)
- <delegated skill raw URL from plan.md>
- https://docs.mem0.ai/llms.txt
- https://docs.mem0.ai/openapi.json (Platform only)
Constraints — all required, all enforced at review:
1. Touch only the files named in plan.md's call sites, or add
strictly new files.
2. Do not remove or rename any existing symbol. Do not change
any public signature.
3. Do not modify any existing test.
4. Gate every line of new Mem0 code behind the feature flag from
plan.md. With the flag in its default state, the repo must
behave exactly like `main` — byte-for-byte, including stdout
and return values.
5. Use only the <Platform | OSS> SDK surface. No new dependencies
beyond those listed under plan.md's "Dependencies to add."
6. Preserve everything listed under plan.md's "Preserved behavior"
and "Coexistence."
7. Lazy client construction. `MemoryClient()` validates the API
key in `__init__` (it makes a network call). Never instantiate
it at module-import time — construct on first use inside the
request / handler path. The same rule applies to OSS `Memory()`,
which can eagerly initialize embedding and LLM providers. Use
a function-local singleton (`functools.lru_cache`, a module-level
`_client = None` + getter, or DI scope) — never a top-level
global. Eager init breaks the pre-existing test suite at
collection time whenever the key is missing or invalid, which
is a non-invasiveness violation.
Implement the plan to make the new tests pass while all
pre-existing tests continue to pass unchanged.
Subagent returns a diff. Main agent reviews against `plan.md` (the
mechanical contract) and `goal.md` (the intent):
- Approved → apply the diff, commit.
- Rejected → return with specific, actionable feedback (not "try again").
- Max 3 review loops. Beyond that → exit code 4 with the last diff and
reviewer feedback.
### 9. Commit + handoff
Create branch `mem0-integrate/<short-goal-slug>` and commit in
**separate commits** so reviewers can cherry-pick:
1. `mem0: add gated dependency` — just the `pyproject.toml` / `package.json`
change.
2. `mem0: add integration module` — the new file(s).
3. `mem0: wire into <call site>` — the call-site edit(s), still gated.
4. `mem0: add tests` — the new test files.
If `--no-heal` is set → print `Run /mem0-test-integration to verify.`
and exit. Otherwise proceed to step 10.
### 10. Self-healing loop (default ON; disable with `--no-heal`)
Run `/mem0-test-integration --ci` in a subprocess. If `scorecard.json`
reports `overall: pass` → done, exit 0.
Otherwise loop:
1. **Categorize the failing check** from `scorecard.json`. Route per
category:
- `install` / `static_checks` → dependency or import fix.
- `unit_tests` → wiring or assertion fix.
- `smoke_test` → API key or SDK call-shape fix.
- `e2e_test` → recipe, flag-wiring, or integration-point fix.
- **Pre-existing test failure (test skill exit code 7,
`non_invasive: false` in scorecard) → STOP.** This is a
non-invasiveness violation. Do NOT attempt to "fix" it (that
breaks principle 3). Exit code 6 with rationale.
2. **Spawn a remediation subagent**, fresh context. Inputs:
`plan.md`, `goal.md`, `scorecard.md`, `scorecard.json`, the last
committed diff, and the relevant log file for the failing category
(`test-stdout.log` / `smoke-stdout.log` / `e2e-app.log` /
`e2e-calls.log`).
System prompt (verbatim):
You are fixing a failing Mem0 integration test.
Non-negotiable constraints:
- Do not modify test files.
- Do not remove or rename any existing symbol or signature.
- Do not change pre-existing behavior. The feature flag from
plan.md must still default to OFF, and with the flag in its
default state the repo must behave exactly like main.
- Touch only the files named in plan.md's call sites, or add
strictly new files.
- Return the smallest possible diff that fixes the single
failing check listed in scorecard.md. No drive-by cleanup.
3. **Apply the diff**; commit on the same branch with message
`mem0-heal: <category> attempt <N>`. Do NOT amend earlier commits
(reviewers need the heal trail).
4. **Re-run `/mem0-test-integration --ci`**. Outcomes:
- `overall: pass` → done, exit 0.
- Same check still failing → increment attempt counter; loop.
- A *different* check now failing → regression. Revert the heal
commit (`git revert HEAD --no-edit`), record the regression in
`.mem0-integration/heal-trace.md`, exit code 6.
5. **Bounded iterations.** Default 3 attempts per failing category.
Override with `--heal-max N` (hard cap 10). On exhaustion, exit 6
with the full attempt trace: each diff, each scorecard, final log
tail.
6. **Post-loop summary** written to `.mem0-integration/heal-trace.md`:
which category failed, how many attempts, each diff's intent, final
status, and — on success — the delta from initial scorecard to final.
| 1 | **Language detection.** `package.json` / `pyproject.toml` / `requirements.txt`. Monorepo, ask which subdirectory. | |
| 2 | **Repo comprehension.** Budgeted read of README, contributor docs, entry points, top two directory levels. Produces `repo-summary.md` with ranked backend surfaces. | User confirms the summary and picks a surface. No backend surface, exit 1. |
| 3 | **Product selection.** Platform vs OSS, recommended from dependency signals, never asked blank. | Locked into `goal.md`, never re-decided. |
| 4 | **API key check.** `MEM0_API_KEY` (Platform) or `OPENAI_API_KEY` (OSS). Missing on Platform, default to Agent Mode via `mem0 init --agent`. | CI mode with a missing key, exit 2. |
| 5 | **Goal doc.** `goal.md`: what gets stored, when it is retrieved, why, product, delegated skill, out of scope. | **Hard gate.** Explicit approval required. 3 rejections, exit 3. |
| 6 | **Integration plan.** Scoped grep for call sites and identity source. `plan.md`: write/read patterns, scoping, call sites, dependencies, preserved behavior, coexistence, feature flag, sources, E2E recipe. | **Hard gate.** No plausible additive call site or 3 rejections, exit 5. |
| 7 | **Tests first.** Failing write and read tests in the repo's native framework, assertion shapes lifted from the canonical signatures. Must be importable with `MEM0_API_KEY` unset. | Tests must fail. If they pass, they are wrong. |
| 8 | **Implementation.** Fresh-context subagent, prompt in [`references/subagent-prompts.md`](references/subagent-prompts.md), returns a diff reviewed against `plan.md` and `goal.md`. | 3 review loops, then exit 4. |
| 9 | **Commit and handoff.** Branch `mem0-integrate/<slug>`, four separable commits: dependency, module, wiring, tests. | `--no-heal` stops here. |
| 10 | **Self-healing loop.** Runs `/mem0-test-integration --ci`, categorizes the failure, spawns a bounded remediation subagent, reverts on regression. | Pre-existing test failure, **stop**, exit 6. Never "fix" it. |
## Artifacts (all under `.mem0-integration/`)
@@ -0,0 +1,375 @@
# Pipeline mechanics
Full step-by-step for `mem0-integrate`. Read this when you are executing a
step. The one-line-per-step overview and every non-negotiable rule live in
`../SKILL.md`, which is loaded on every run; this file is loaded on demand.
Verbatim subagent system prompts for steps 8 and 10 are in
[`subagent-prompts.md`](subagent-prompts.md).
## 1. Language detection
| Signal | Track |
|---|---|
| `package.json` + TypeScript config | Node / TypeScript |
| `package.json` (no TS config) | Node / JavaScript |
| `pyproject.toml` or `requirements.txt` | Python |
Monorepo with both, ask which subdirectory to operate in, then recurse.
## 2. Repo comprehension: what does this repo do, and where is the backend?
Before any decision (product, goal, plan), understand the repo enough to
locate *where in the backend* the integration belongs. This is not
fit-surveying, the user already decided Mem0 fits. This is mechanics: you
cannot write a plan without knowing what files matter.
Read, in order, with a token budget. Do not scan the whole tree.
1. `README.md` (root) plus the first page of any `README_*.md` variants.
2. `CONTRIBUTING.md` / `AGENTS.md` / `CLAUDE.md` at root if present. These
often spell out architecture and entry points.
3. `package.json` / `pyproject.toml` scripts and entry points.
4. The layout of the top two directory levels, not recursive.
5. Key config files: `docker-compose.yml`, `Dockerfile`, `Makefile`,
`langgraph.json`, `next.config.*`, `nuxt.config.*`.
Produce `.mem0-integration/repo-summary.md`:
# Repo comprehension
**What this repo does:** <one paragraph in plain English. Who is
the end user? What does the app do for them? What LLM / agent
behavior is central? Do not list dependencies, describe behavior.>
**Architecture at a glance:**
- Backend: <path(s), framework, primary entry point>
- Frontend: <path(s) if any, framework, for context only; no
integration here>
- Agent loop / orchestration: <LangGraph? custom? none?>
- Existing memory/session/state systems: <name them, these are
what step 6 Coexistence must preserve>
**Candidate backend integration surfaces** (ranked, best first):
1. `<backend-file>:<line_range>` <function> <one-sentence
reason this is where write/read could slot in without
replacing anything existing>
2. ...
3. ...
**Not a fit here:** <list anything the skill considered but ruled
out, e.g. "frontend chat component: client-side, excluded by
backend-only rule"; "existing memory subsystem X: would require
replacement, excluded by additive principle">
**Sources read:** <list the files actually opened, with line counts,
so reviewers can verify coverage.>
Show the user the rendered summary and ask: *"Is this understanding correct?
Which of the candidate surfaces (1, 2, 3 ...) should step 3 forward target?"*
Gate rules:
- No backend surface found, exit code 1. Preconditions should already have
caught frontend-only repos; reaching this point means a subtler miss (for
example the "backend" is actually just a static build). Do not force a fit.
- Every candidate surface would require replacing an existing memory or
session system, exit code 1 with the additive-principle rationale. The user
can point at a non-conflicting location manually and re-run.
- User corrections update `repo-summary.md` and re-confirm. Max 3 rounds,
beyond that exit code 1.
The user's chosen surface index is baked into `product.json` as
`preferred_site` and referenced by steps 5 and 6.
## 3. Product selection: Platform vs OSS
Read the `## Identify the User's Setup` block in
`https://docs.mem0.ai/llms.txt` for the Platform-first routing rules, then
apply the heuristics below. Ask, but never blank.
- Other managed-service SDKs present (`@clerk/*`, `stripe`, `@supabase/*`,
`openai`, `@upstash/*`, `posthog-*`), 3 or more, recommend **Platform**.
- Local-infra signals (`docker-compose.yml` with postgres / redis / qdrant /
neo4j, ollama configs, self-hosted auth), 2 or more, recommend **OSS**.
- No strong signal, default recommendation **Platform**: lower integration
cost, and migration later is supported.
Example:
> I see `stripe`, `@clerk/nextjs`, and `@supabase/supabase-js`, managed
> services throughout. I recommend **Mem0 Platform** (4-line integration).
> Override and use open source?
Bake the choice into the goal doc in step 5. Do not re-decide later.
## 4. API key check (env first, then ask)
| Track | Key | Where to find |
|---|---|---|
| Platform | `MEM0_API_KEY` | https://app.mem0.ai |
| OSS (default LLM) | `OPENAI_API_KEY` | https://platform.openai.com/api-keys |
Present in env, continue.
`MEM0_API_KEY` missing and the track is **Platform**, **default to Agent
Mode**: run `mem0 init --agent --agent-caller <your-name> --json` (after
`pip install mem0-cli` or `npm install -g @mem0/cli`), substituting your agent
identity such as `claude-code`, `cursor`, `codex`. If you forgot
`--agent-caller`, run `mem0 identify <your-name>` after init. Cache the key to
`.env` with user consent and continue. Tell the user to claim it later with
`mem0 init --email <their-email>`: same key, no agent disruption.
Missing and **CI mode** (`MEM0_INTEGRATE_CI=1`), exit code 2 with the name of
the missing key.
Never echo key values into `trace.jsonl`. Persist to `.env` only with explicit
user consent, and append `.env` to `.gitignore` if it is not there already.
If the user is on OSS and wants a non-OpenAI LLM, route them to the
`components/llms/*` docs and re-run this step with the chosen provider's key.
## 5. Goal doc, the hard gate
Write `.mem0-integration/goal.md` and **require user approval before step 6**.
# Mem0 Integration Goal
**What gets stored:** <one sentence. User utterances? Extracted
preferences? A specific domain fact like "dietary restrictions"?>
**When it gets retrieved:** <one sentence. On each user turn? Before a
specific tool call? At session start?>
**Why:** <one sentence, the user-visible behavior change. "Assistant
remembers previous orders across sessions," not "we added memory.">
**Product:** Platform | OSS (locked from step 3, do not change)
**Delegated skill:** <raw URL of the published skill being used
from the delegation table in SKILL.md, or "none, custom integration
against `skills/mem0`">.
**Out of scope:** <anything explicitly excluded: "no graph memory,"
"no multimodal," "no migration from existing store">
Rules:
- The user must approve explicitly. If they edit the doc, reload and
re-confirm.
- `goal.md` is the contract the test suite is written against. Never rewrite
it after step 6 starts.
- Max 3 rejection rounds. On the 4th, exit code 3 with the rejection notes:
the integration is not well-specified enough to proceed.
## 6. Integration plan, where and how (hard gate)
`goal.md` is what and why. This step produces where and how, and gets explicit
sign-off before any code is written.
Do a **scoped** read of the repo, no wide survey:
- Grep for the LLM call sites that match the goal (`openai.chat.`,
`anthropic.messages.`, `model.generateContent`, `ChatOpenAI`, `createLLM`).
- Grep for the user-identity source (`req.user`, `session.user`, `auth()`,
`ctx.userId`, cookies).
- Check `package.json` / `pyproject.toml` / `requirements.txt` for conflicts,
for example an existing `mem0ai` at a different version.
Then write `.mem0-integration/plan.md`:
# Mem0 Integration Plan
**Write pattern:** <one sentence, e.g. "After each assistant reply,
call client.add([user_msg, assistant_msg], user_id=<source>).">
**Read pattern:** <one sentence, e.g. "Before building the LLM prompt,
call client.search(query=latest_user_msg, user_id=<source>, limit=5)
and inject results as a system message.">
**User identifier source:** <code path, e.g. `req.auth.userId`,
`session.user.email`, `ctx.params.user_id`. If none, ask the user.>
**Session scoping:**
- user_id: <source>
- agent_id: <static slug | null>
- run_id: <source | null>
**Write call site:** `<file:line_range>` inside `<function>`
**Read call site:** `<file:line_range>` inside `<function>`
**Dependencies to add:**
- `<package>@<version pinned in frontmatter>`
**Preserved behavior:** <list the existing repo behaviors that must
keep working after this edit, e.g. "existing OpenAI streaming still
works," "existing Redis session store still used," "existing tests
still pass unchanged.">
**Coexistence:** <one bullet per existing system the integration sits
alongside. Name the files/classes. Example: "The existing
`agents/memory/storage.py` MemoryStorage class remains untouched and
keeps its LangGraph SummarizationEvent flow. Mem0 is added as a
parallel long-term-facts store, in a new file, invoked only when
MEM0_ENABLED=1 is set.">
**Feature flag:** <the exact mechanism and the default. Required.
Example: `env MEM0_ENABLED=1`, default unset / off; `config.mem0.enabled`,
default false. With the flag in its default state, the repo must
behave exactly like `main`.>
**Sources consulted:** <minimum 2 URLs from "Canonical sources" in
SKILL.md that informed this plan. At least one `docs.mem0.ai` URL and
one delegated-skill URL. Cite the specific section or heading.>
**E2E recipe:** <how the verification skill should drive the app
end-to-end. Omit only if the repo is a pure library with no runnable
entry point, in which case the E2E step skips with a warning.>
start: <shell command to launch the app locally,
using $PORT for any network port>
ready_probe: <one of: url=<URL> status=<code> /
log="<substring to wait for>" /
sleep=<seconds, last resort>>
compose_services: <optional: whitespace-separated service
names in docker-compose.yml to start first;
use label mem0-e2e: "true" to mark them>
write_call: <command that triggers the Mem0 write path
exactly once; 60s runtime or less>
write_async_wait_ms: <milliseconds to wait after write_call for
async memory flush; default 0>
read_call: <command that triggers the Mem0 read path,
typically a fresh session / new request>
read_assert: <substring, regex, or jsonpath=<expr>=<value>
that MUST appear in read_call's output for
the E2E to pass. Derived from goal.md's
"What gets stored.">
**Rejected alternatives:** <briefly, 1 or 2 bullets. Patterns the skill
considered but did not pick, and why. Helps the user decide.>
Rules:
- Show the user the proposed call sites with 10 lines of context around each
before asking for approval.
- If no plausible call site exists for either write or read, exit code 5 and
ask the user to name the files manually. That is the "no fit here" signal,
do not guess.
- Max 3 rejection rounds on the plan. On the 4th, exit code 5 with the last
plan and the user's notes.
- If the user edits `plan.md` by hand, reload and re-confirm.
`plan.md`, not `goal.md`, is the contract the subagent implements against in
step 8.
## 7. Tests first (TDD)
The main agent writes failing tests against `goal.md` in the repo's native
test framework:
| Track | Default framework |
|---|---|
| Python | `pytest` |
| TypeScript | `vitest` if detected, else `jest` |
| JavaScript | same |
Test assertion shapes must match the **canonical signatures**:
- Platform method signatures: `https://docs.mem0.ai/openapi.json`, the request
body schemas for `/v1/memories/` and `/v1/memories/search/`.
- OSS method signatures: the delegated skill named in `plan.md` (fetched from
its raw URL), or `skills/mem0/SKILL.md` as the default.
- Do not hand-roll request shapes. If the delegated skill has an example
block, lift it verbatim.
Minimum two test files, paths taken from `plan.md` call sites:
- `test_mem0_write.<ext>` asserts `add()` is called at the write call site
with the right payload shape (Platform messages-array vs OSS string) and the
right `user_id` source.
- `test_mem0_read.<ext>` asserts `search()` runs before the read call site and
the result is wired into the LLM prompt or response path.
Tests MUST be importable with `MEM0_API_KEY` unset. This is the design
pressure that forces step 8's lazy `MemoryClient()` / `Memory()` construction:
eager module-level init hits the API on import and breaks pre-existing test
collection when the key is missing.
Run the tests. They **must fail**. If they pass before any implementation, the
tests are wrong. Rewrite them.
## 8. Implementation (subagent, fresh context)
Spawn a subagent with:
- **Inputs**: the repo, `goal.md`, `plan.md`, the two test files, and direct
URLs to the delegated skill (from `plan.md`), the SDK source (pinned per
`mem0_tested_versions`), `https://docs.mem0.ai/llms.txt`, and
`https://docs.mem0.ai/openapi.json`.
- **No access** to the main agent's reasoning trace or scratchpad.
- **System prompt**: use the implementation prompt in
[`subagent-prompts.md`](subagent-prompts.md) verbatim.
The subagent returns a diff. The main agent reviews it against `plan.md` (the
mechanical contract) and `goal.md` (the intent):
- Approved, apply the diff and commit.
- Rejected, return with specific actionable feedback, not "try again."
- Max 3 review loops. Beyond that, exit code 4 with the last diff and the
reviewer feedback.
## 9. Commit and handoff
Create branch `mem0-integrate/<short-goal-slug>` and commit in **separate
commits** so reviewers can cherry-pick:
1. `mem0: add gated dependency`, just the `pyproject.toml` / `package.json`
change.
2. `mem0: add integration module`, the new files.
3. `mem0: wire into <call site>`, the call-site edits, still gated.
4. `mem0: add tests`, the new test files.
With `--no-heal`, print `Run /mem0-test-integration to verify.` and exit.
Otherwise proceed to step 10.
## 10. Self-healing loop (default ON, disable with `--no-heal`)
Run `/mem0-test-integration --ci` in a subprocess. If `scorecard.json` reports
`overall: pass`, done, exit 0.
Otherwise loop:
1. **Categorize the failing check** from `scorecard.json` and route:
- `install` / `static_checks`, dependency or import fix.
- `unit_tests`, wiring or assertion fix.
- `smoke_test`, API key or SDK call-shape fix.
- `e2e_test`, recipe, flag-wiring, or integration-point fix.
- **Pre-existing test failure** (test skill exit code 7,
`non_invasive: false` in the scorecard), **STOP**. This is a
non-invasiveness violation. Do NOT attempt to fix it, that breaks
principle 3. Exit code 6 with a rationale.
2. **Spawn a remediation subagent** with fresh context. Inputs: `plan.md`,
`goal.md`, `scorecard.md`, `scorecard.json`, the last committed diff, and
the relevant log for the failing category (`test-stdout.log` /
`smoke-stdout.log` / `e2e-app.log` / `e2e-calls.log`). Use the remediation
prompt in [`subagent-prompts.md`](subagent-prompts.md) verbatim.
3. **Apply the diff** and commit on the same branch as
`mem0-heal: <category> attempt <N>`. Do NOT amend earlier commits,
reviewers need the heal trail.
4. **Re-run `/mem0-test-integration --ci`**:
- `overall: pass`, done, exit 0.
- Same check still failing, increment the attempt counter and loop.
- A *different* check now failing, that is a regression. Revert the heal
commit (`git revert HEAD --no-edit`), record it in
`.mem0-integration/heal-trace.md`, exit code 6.
5. **Bounded iterations.** Default 3 attempts per failing category, override
with `--heal-max N` (hard cap 10). On exhaustion, exit code 6 with the full
attempt trace: each diff, each scorecard, final log tail.
6. **Post-loop summary** written to `.mem0-integration/heal-trace.md`: which
category failed, how many attempts, each diff's intent, final status, and
on success the delta from the initial scorecard to the final one.
@@ -0,0 +1,67 @@
# Subagent system prompts
Pass these verbatim. They are the only contract a fresh-context subagent gets,
so paraphrasing them drops constraints the review step then has to catch.
## Step 8: implementation
You are implementing a Mem0 integration for an existing repo.
Read these first:
- plan.md (the mechanical contract)
- goal.md (the intent, do not change it)
- the test files (do not change them either)
- <delegated skill raw URL from plan.md>
- https://docs.mem0.ai/llms.txt
- https://docs.mem0.ai/openapi.json (Platform only)
Constraints, all required, all enforced at review:
1. Touch only the files named in plan.md's call sites, or add
strictly new files.
2. Do not remove or rename any existing symbol. Do not change
any public signature.
3. Do not modify any existing test.
4. Gate every line of new Mem0 code behind the feature flag from
plan.md. With the flag in its default state, the repo must
behave exactly like `main`, byte-for-byte, including stdout
and return values.
5. Use only the <Platform | OSS> SDK surface. No new dependencies
beyond those listed under plan.md's "Dependencies to add."
6. Preserve everything listed under plan.md's "Preserved behavior"
and "Coexistence."
7. Lazy client construction. `MemoryClient()` validates the API
key in `__init__` (it makes a network call). Never instantiate
it at module-import time, construct on first use inside the
request / handler path. The same rule applies to OSS `Memory()`,
which can eagerly initialize embedding and LLM providers. Use
a function-local singleton (`functools.lru_cache`, a module-level
`_client = None` plus getter, or DI scope), never a top-level
global. Eager init breaks the pre-existing test suite at
collection time whenever the key is missing or invalid, which
is a non-invasiveness violation.
Implement the plan to make the new tests pass while all
pre-existing tests continue to pass unchanged.
Substitute `<delegated skill raw URL from plan.md>` and `<Platform | OSS>`
before sending. Leave everything else as written.
## Step 10: remediation
You are fixing a failing Mem0 integration test.
Non-negotiable constraints:
- Do not modify test files.
- Do not remove or rename any existing symbol or signature.
- Do not change pre-existing behavior. The feature flag from
plan.md must still default to OFF, and with the flag in its
default state the repo must behave exactly like main.
- Touch only the files named in plan.md's call sites, or add
strictly new files.
- Return the smallest possible diff that fixes the single
failing check listed in scorecard.md. No drive-by cleanup.
Never send this prompt for a pre-existing test failure. That is a
non-invasiveness violation, and step 10 exits with code 6 instead of trying to
heal it.
+24
View File
@@ -0,0 +1,24 @@
# Python SDK tests (`tests/`)
pytest suite for the `mem0/` package.
## Commands
```bash
make install_all # optional deps; several tests need them
make test # pytest tests/
make test-py-3.9 # pin a Python version (3.9 through 3.12)
pytest tests/llms/test_openai.py::test_generate_response # single test
```
## Conventions
- Files are named `test_<module>.py`.
- Provider tests mirror the source tree: `tests/<category>/<provider_name>/`.
- pytest-mock for mocks, pytest-asyncio for the async surface.
- Ruff line length **120**, matching `mem0/`. See [`../mem0/AGENTS.md`](../mem0/AGENTS.md).
- Mock the provider SDK, never the code under test. A test that asserts the implementation back at itself is worse than no test.
- Bug fixes need a regression test that fails without the fix. Write it first and watch it fail.
Tests for other packages live with those packages: `mem0-ts/` (jest), `cli/python/tests/` (pytest), `cli/node/` (vitest), and each directory under `integrations/`.
+1
View File
@@ -0,0 +1 @@
AGENTS.md