Skip to content
Draft
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions .cursor-plugin/marketplace.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"name": "agentmemory",
"owner": {
"name": "Rohit Ghumare",
"github": "rohitg00"
},
"metadata": {
"description": "Persistent memory for AI coding agents",
"version": "0.9.28"
},
"plugins": [
{
"name": "agentmemory",
"source": "./plugin",
"description": "Cursor lifecycle hooks + MCP + skills for agentmemory",
"version": "0.9.28"
}
]
}
69 changes: 69 additions & 0 deletions integrations/cursor/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
# agentmemory for Cursor

Cursor-native plugin: **lifecycle hooks** (workspace resolver), **MCP**, and shared **skills**.

Upstream today ships Claude/Codex hooks only. This integration adds `plugin/.cursor-plugin/` + `plugin/hooks/hooks.cursor.json` — the PR-ready layout.

## Quick local install

Prereq: `~/.agentmemory/.env` with `AGENTMEMORY_URL` and `AGENTMEMORY_SECRET`.

```bash
node integrations/cursor/install-local.mjs
node integrations/cursor/verify-flow.mjs
```

Then in Cursor:

1. **Settings → Plugins → Add marketplace** → select the **repo root**
`<path-to-your-agentmemory-clone>`
(must contain `.cursor-plugin/marketplace.json`)
2. Enable plugin **agentmemory**
3. **Disable** the old `rohitg00/agentmemory` marketplace entry if both are on
4. **Developer: Reload Window**
5. Confirm hooks log shows `${CURSOR_PLUGIN_ROOT}/scripts/cursor/agentmemory-*`

Only after plugin hooks are confirmed:

```bash
node integrations/cursor/install-local.mjs --clear-user-hooks
```

## Layout (PR target)

```text
agentmemory/ ← marketplace root (git repo)
.cursor-plugin/marketplace.json
plugin/
.cursor-plugin/plugin.json
hooks/hooks.cursor.json ← Cursor camelCase format
scripts/cursor/agentmemory-*.mjs ← workspace resolver + detached workers
skills/ ← shared with Claude/Codex
.mcp.json
integrations/cursor/
install-local.mjs ← dev installer
verify-flow.mjs ← smoke test
```

## Hooks

| Hook | Role |
|------|------|
| `sessionStart` | Register session + optional context inject |
| `beforeSubmitPrompt` | Capture user intent |
| `preToolUse` / `postToolUse` | Tool I/O capture |
| `stop` | Episodic summarize (reliable) |
| `sessionEnd` | `session/end` + consolidation |

## sessionEnd (Cursor 3.13.x)

- `window_close`: often broken (`MainThreadShellExec not initialized`)
- Tab close may work — test manually
- `stop` is reliable for summarize, not for `completed` status

## PR checklist

- [ ] `plugin/.cursor-plugin/plugin.json` + `hooks.cursor.json`
- [ ] README: Cursor = MCP + native hooks (not MCP-only)
- [ ] `agentmemory connect cursor` docs update
- [ ] Disable duplicate user `~/.cursor/hooks.json` in docs only (not auto-cleared)
171 changes: 171 additions & 0 deletions integrations/cursor/install-local.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
#!/usr/bin/env node
import { chmodSync, copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { homedir } from 'node:os';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { execSync } from 'node:child_process';

const INTEGRATION_ROOT = resolve(dirname(fileURLToPath(import.meta.url)));
const REPO_ROOT = resolve(INTEGRATION_ROOT, '../..');
const CURSOR_DIR = join(homedir(), '.cursor');
const ENV_PATH = join(homedir(), '.agentmemory', '.env');
const MCP_PATH = join(CURSOR_DIR, 'mcp.json');
const HOOKS_PATH = join(CURSOR_DIR, 'hooks.json');
const MARKETPLACE_NAME = 'local-agentmemory';
const MARKETPLACE_DIR = join(CURSOR_DIR, 'plugins', 'marketplaces', MARKETPLACE_NAME);
const LEGACY_MARKETPLACE_DIR = join(CURSOR_DIR, 'plugins', 'marketplaces', 'local-agentmemory-cursor');

function loadEnv(path) {
const out = {};
if (!existsSync(path)) return out;
for (const line of readFileSync(path, 'utf-8').split('\n')) {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith('#')) continue;
const idx = trimmed.indexOf('=');
if (idx === -1) continue;
out[trimmed.slice(0, idx).trim()] = trimmed.slice(idx + 1).trim();
}
return out;
}

function readJson(path) {
if (!existsSync(path)) return {};
try {
return JSON.parse(readFileSync(path, 'utf-8'));
} catch (err) {
throw new Error(`Cannot parse ${path}: ${err.message}`);
}
}

function writeJson(path, data, restrictPermissions = false) {
mkdirSync(dirname(path), { recursive: true });
writeFileSync(path, `${JSON.stringify(data, null, 2)}\n`, 'utf-8');
if (restrictPermissions) {
try {
chmodSync(path, 0o600);
} catch {}
}
}

function isPlainObject(value) {
return value !== null && typeof value === 'object' && !Array.isArray(value);
}

function describeJsonType(value) {
if (value === null) return 'null';
if (Array.isArray(value)) return 'array';
return typeof value;
}

function requireObjectConfig(path, value, label) {
if (!isPlainObject(value)) {
console.error(`${path}: expected ${label} to be a JSON object, got ${describeJsonType(value)}`);
process.exit(1);
}
}

function requireObjectField(path, fieldName, value) {
if (value === undefined) return;
if (!isPlainObject(value)) {
console.error(`${path}: expected "${fieldName}" to be a JSON object, got ${describeJsonType(value)}`);
process.exit(1);
}
}

function linkMarketplace() {
mkdirSync(dirname(MARKETPLACE_DIR), { recursive: true });
if (!existsSync(MARKETPLACE_DIR)) {
if (process.platform === 'win32') {
execSync(`cmd /c mklink /J "${MARKETPLACE_DIR}" "${REPO_ROOT}"`, { stdio: 'inherit' });
} else {
execSync(`ln -s "${REPO_ROOT}" "${MARKETPLACE_DIR}"`, { stdio: 'inherit' });
}
}
}

function mergeMcp(env) {
let mcp;
try {
mcp = existsSync(MCP_PATH) ? readJson(MCP_PATH) : {};
} catch (err) {
console.error(err.message);
console.error('Refusing to overwrite mcp.json. Fix the file or restore from backup.');
process.exit(1);
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
requireObjectConfig(MCP_PATH, mcp, 'mcp.json root');
requireObjectField(MCP_PATH, 'mcpServers', mcp.mcpServers);
if (!mcp.mcpServers) mcp.mcpServers = {};
mcp.mcpServers.agentmemory = {
command: 'npx',
args: ['-y', '@agentmemory/mcp'],
env: {
AGENTMEMORY_URL: env.AGENTMEMORY_URL || 'http://localhost:3111',
AGENTMEMORY_SECRET: env.AGENTMEMORY_SECRET || '',
AGENTMEMORY_TOOLS: env.AGENTMEMORY_TOOLS || 'all',
},
};
const backup = `${MCP_PATH}.bak-${Date.now()}`;
if (existsSync(MCP_PATH)) {
copyFileSync(MCP_PATH, backup);
try {
chmodSync(backup, 0o600);
} catch {}
}
writeJson(MCP_PATH, mcp, true);
return backup;
}

function disableUserHooks() {
if (!process.argv.includes('--clear-user-hooks')) return null;
if (!existsSync(HOOKS_PATH)) return null;
let hooks;
try {
hooks = readJson(HOOKS_PATH);
} catch (err) {
console.error(err.message);
console.error('Refusing to clear hooks.json until the file is valid JSON.');
process.exit(1);
}
requireObjectConfig(HOOKS_PATH, hooks, 'hooks.json root');
requireObjectField(HOOKS_PATH, 'hooks', hooks.hooks);
const hasAgentmemory = JSON.stringify(hooks).includes('agentmemory-');
if (!hasAgentmemory) return null;
const backup = `${HOOKS_PATH}.pre-plugin-${Date.now()}.bak`;
copyFileSync(HOOKS_PATH, backup);
writeJson(HOOKS_PATH, { version: 1, hooks: {} });
return backup;
}

const env = loadEnv(ENV_PATH);
if (!env.AGENTMEMORY_URL || !env.AGENTMEMORY_SECRET) {
console.error('Missing ~/.agentmemory/.env with AGENTMEMORY_URL and AGENTMEMORY_SECRET');
process.exit(1);
}

linkMarketplace();
const mcpBackup = mergeMcp(env);
const hooksBackup = disableUserHooks();

console.log('\nagentmemory Cursor plugin (local dev) wired.\n');
console.log(`Repo root: ${REPO_ROOT}`);
console.log(`Plugin package: ${join(REPO_ROOT, 'plugin')}`);
console.log(`Marketplace junction: ${MARKETPLACE_DIR}`);
if (existsSync(LEGACY_MARKETPLACE_DIR)) {
console.log(`Legacy junction still present: ${LEGACY_MARKETPLACE_DIR}`);
console.log(' Remove it in Cursor Settings → Plugins if you added marketplace from integrations/cursor before.');
}
if (mcpBackup) console.log(`mcp.json backup: ${mcpBackup}`);
if (hooksBackup) console.log(`hooks.json backup: ${hooksBackup}`);
console.log(`AGENTMEMORY_URL: ${env.AGENTMEMORY_URL}`);
console.log('AGENTMEMORY_SECRET: <set, not printed>');
console.log('\nNext steps:');
console.log('1. Cursor → Settings → Plugins → Add marketplace from folder:');
console.log(` ${REPO_ROOT}`);
console.log(' (repo root — must contain .cursor-plugin/marketplace.json)');
console.log('2. Enable plugin: agentmemory');
console.log('3. Disable the old rohitg00/agentmemory marketplace plugin if both are enabled.');
console.log('4. Developer: Reload Window');
console.log('5. Run: node integrations/cursor/verify-flow.mjs');
console.log('6. In hooks log, confirm commands use ${CURSOR_PLUGIN_ROOT}/scripts/cursor/');
console.log('\nOnly after plugin hooks are confirmed:');
console.log(' node integrations/cursor/install-local.mjs --clear-user-hooks');
116 changes: 116 additions & 0 deletions integrations/cursor/verify-flow.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
#!/usr/bin/env node
import { existsSync, readFileSync } from 'node:fs';
import { homedir } from 'node:os';
import { dirname, join, resolve } from 'node:path';
import { spawnSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';

const INTEGRATION_ROOT = resolve(dirname(fileURLToPath(import.meta.url)));
const REPO_ROOT = resolve(INTEGRATION_ROOT, '../..');
const SCRIPTS = join(REPO_ROOT, 'plugin', 'scripts', 'cursor');
const ENV_PATH = join(homedir(), '.agentmemory', '.env');

function loadEnv(path) {
const out = {};
if (!existsSync(path)) return out;
for (const line of readFileSync(path, 'utf-8').split('\n')) {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith('#')) continue;
const idx = trimmed.indexOf('=');
if (idx === -1) continue;
out[trimmed.slice(0, idx).trim()] = trimmed.slice(idx + 1).trim();
}
return out;
}

function runHook(script, payload) {
const r = spawnSync(process.execPath, [join(SCRIPTS, script)], {
input: JSON.stringify(payload),
encoding: 'utf-8',
timeout: 30000,
});
return { script, status: r.status, stderr: r.stderr?.slice(0, 200) };
}

async function fetchSession(url, secret, id) {
const r = await fetch(`${url}/agentmemory/sessions`, {
headers: { Authorization: `Bearer ${secret}` },
signal: AbortSignal.timeout(30000),
});
if (!r.ok) throw new Error(`sessions list ${r.status}`);
const data = await r.json();
return data.sessions?.find((s) => s.id === id) ?? null;
}

const env = loadEnv(ENV_PATH);
const url = env.AGENTMEMORY_URL;
const secret = env.AGENTMEMORY_SECRET;
if (!url || !secret) {
console.error('Need AGENTMEMORY_URL and AGENTMEMORY_SECRET in ~/.agentmemory/.env');
process.exit(1);
}

if (!existsSync(join(SCRIPTS, 'agentmemory-session-start.mjs'))) {
console.error(`Missing plugin scripts at ${SCRIPTS}`);
process.exit(1);
}

const sessionId = `cursor-plugin-verify-${new Date().toISOString().slice(0, 10).replace(/-/g, '')}`;
const basePayload = {
session_id: sessionId,
workspace_roots: [join(REPO_ROOT).replace(/\\/g, '/')],
cwd: '.cursor',
};

console.log('=== agentmemory Cursor plugin verify ===\n');
console.log(`Scripts: ${SCRIPTS}\n`);

try {
const livez = await fetch(`${url}/agentmemory/livez`, {
headers: { Authorization: `Bearer ${secret}` },
signal: AbortSignal.timeout(15000),
});
console.log(`livez: ${livez.ok ? 'ok' : livez.status}`);
} catch (e) {
console.error('livez failed:', e.message);
process.exit(1);
}
Comment on lines +84 to +92

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Fail on unhealthy HTTP responses.

This only exits for fetch exceptions; a 401, 500, or other non-OK /livez response is logged and the smoke test continues. Throw when !livez.ok.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@integrations/cursor/verify-flow.mjs` around lines 75 - 84, Update the livez
check after the fetch in the surrounding verification flow to throw when
livez.ok is false, before logging success. Preserve the existing catch behavior
so non-OK HTTP responses log the failure and exit through the same path as fetch
exceptions.


for (const step of [
['agentmemory-session-start.mjs', basePayload],
['agentmemory-post-tool-use.mjs', { ...basePayload, tool_name: 'Read', tool_input: { path: join(REPO_ROOT, 'package.json') } }],
['agentmemory-stop.mjs', basePayload],
['agentmemory-session-end.mjs', { ...basePayload, reason: 'window_close' }],
]) {
const result = runHook(step[0], step[1]);
console.log(`${step[0]}: exit ${result.status}${result.stderr ? ` (${result.stderr})` : ''}`);
await new Promise((r) => setTimeout(r, 2500));
}

const session = await fetchSession(url, secret, sessionId);
if (!session) {
console.error('\nFAIL: session not found on NAS after hook pipeline');
process.exit(1);
}

console.log('\nNAS session:');
console.log(` id: ${session.id}`);
console.log(` project: ${session.project}`);
console.log(` status: ${session.status}`);
console.log(` obs: ${session.observationCount}`);
console.log(` endedAt: ${session.endedAt ?? '(none)'}`);

const okProject = session.project === 'agentmemory';
const okObs = session.observationCount >= 1;
const okEnd = session.status === 'completed' && session.endedAt;

console.log('\nResult:');
console.log(` resolver: ${okProject ? 'PASS' : 'FAIL'} (expected agentmemory)`);
console.log(` capture: ${okObs ? 'PASS' : 'FAIL'} (expected obs>=1)`);
console.log(` session/end: ${okEnd ? 'PASS' : 'PARTIAL'} (script works; Cursor may not fire sessionEnd on close)`);

if (okProject && okObs) {
console.log('\nPlugin hook pipeline OK for PR smoke test.');
process.exit(0);
}
process.exit(1);
Loading