-
Notifications
You must be signed in to change notification settings - Fork 2.3k
feat(cursor): add native hooks plugin with workspace resolver #1112
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
andrew05060414
wants to merge
14
commits into
rohitg00:main
Choose a base branch
from
andrew05060414:feat/cursor-native-plugin
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from 4 commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
2e81a27
feat(cursor): add native hooks plugin with workspace resolver
andrew05060414 f908083
fix(cursor): address CodeRabbit review for hooks and utilities
andrew05060414 409d548
fix(cursor): harden install-local, path checks, and hook payloads
andrew05060414 9a708c1
fix(cursor): validate mcp.json and hooks.json object shape before merge
andrew05060414 33b699b
refactor(cursor): replace duplicated hooks with thin shims delegating…
andrew05060414 394b773
refactor(cursor): compile the Cursor adapter from src/hooks/cursor
andrew05060414 a36eab2
fix(cursor): address review findings in the adapter and dev scripts
andrew05060414 bcde3ea
feat(cursor): resolve the workspace from Cursor's own records
andrew05060414 f3d6d52
test(cursor): cover the adapter without a daemon
andrew05060414 6d1f807
docs(cursor): explain why the adapter is shaped the way it is
andrew05060414 819734a
fix(cursor): only reject dot-named directories that are not repositories
andrew05060414 1a04b56
fix(cursor): space out the smoke test's observation retries
andrew05060414 9e32cb1
fix(cursor): stop telling users MCP is all Cursor can do
andrew05060414 f750e12
fix(cursor): do not file sessions under the home directory
andrew05060414 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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" | ||
| } | ||
| ] | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); | ||
| } | ||
| 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'); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 🤖 Prompt for AI Agents |
||
|
|
||
| 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); | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.