From 74fd33fea282880ab69830b50cf3e1252863612c Mon Sep 17 00:00:00 2001 From: Andrew Date: Sun, 26 Jul 2026 18:06:39 +0800 Subject: [PATCH 01/18] feat(cursor): add native hooks plugin with workspace resolver Add Cursor marketplace manifest, hooks.cursor.json, and Cursor-specific hook scripts under plugin/ so lifecycle capture works via plugin install (not only user-level ~/.cursor/hooks.json). Includes local dev installer and verify-flow smoke test. --- .cursor-plugin/marketplace.json | 19 ++ integrations/cursor/README.md | 69 +++++ integrations/cursor/install-local.mjs | 114 ++++++++ integrations/cursor/verify-flow.mjs | 116 ++++++++ plugin/.cursor-plugin/plugin.json | 29 ++ plugin/hooks/hooks.cursor.json | 56 ++++ plugin/scripts/cursor/agentmemory-lib.mjs | 269 ++++++++++++++++++ .../cursor/agentmemory-post-tool-failure.mjs | 66 +++++ .../cursor/agentmemory-post-tool-use.mjs | 109 +++++++ .../cursor/agentmemory-pre-compact.mjs | 76 +++++ .../cursor/agentmemory-pre-tool-use.mjs | 89 ++++++ .../cursor/agentmemory-prompt-submit.mjs | 61 ++++ .../cursor/agentmemory-session-end.mjs | 143 ++++++++++ .../cursor/agentmemory-session-start.mjs | 83 ++++++ plugin/scripts/cursor/agentmemory-stop.mjs | 113 ++++++++ .../cursor/agentmemory-subagent-start.mjs | 63 ++++ .../cursor/agentmemory-subagent-stop.mjs | 66 +++++ .../cursor/close-stale-am-sessions.mjs | 136 +++++++++ .../cursor/fix-cursor-session-projects.mjs | 130 +++++++++ 19 files changed, 1807 insertions(+) create mode 100644 .cursor-plugin/marketplace.json create mode 100644 integrations/cursor/README.md create mode 100644 integrations/cursor/install-local.mjs create mode 100644 integrations/cursor/verify-flow.mjs create mode 100644 plugin/.cursor-plugin/plugin.json create mode 100644 plugin/hooks/hooks.cursor.json create mode 100644 plugin/scripts/cursor/agentmemory-lib.mjs create mode 100644 plugin/scripts/cursor/agentmemory-post-tool-failure.mjs create mode 100644 plugin/scripts/cursor/agentmemory-post-tool-use.mjs create mode 100644 plugin/scripts/cursor/agentmemory-pre-compact.mjs create mode 100644 plugin/scripts/cursor/agentmemory-pre-tool-use.mjs create mode 100644 plugin/scripts/cursor/agentmemory-prompt-submit.mjs create mode 100644 plugin/scripts/cursor/agentmemory-session-end.mjs create mode 100644 plugin/scripts/cursor/agentmemory-session-start.mjs create mode 100644 plugin/scripts/cursor/agentmemory-stop.mjs create mode 100644 plugin/scripts/cursor/agentmemory-subagent-start.mjs create mode 100644 plugin/scripts/cursor/agentmemory-subagent-stop.mjs create mode 100644 plugin/scripts/cursor/close-stale-am-sessions.mjs create mode 100644 plugin/scripts/cursor/fix-cursor-session-projects.mjs diff --git a/.cursor-plugin/marketplace.json b/.cursor-plugin/marketplace.json new file mode 100644 index 0000000000..6c412994d7 --- /dev/null +++ b/.cursor-plugin/marketplace.json @@ -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" + } + ] +} diff --git a/integrations/cursor/README.md b/integrations/cursor/README.md new file mode 100644 index 0000000000..86cce94276 --- /dev/null +++ b/integrations/cursor/README.md @@ -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** + `D:\Andrew\Code\Github\agentmemory` + (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) + +``` +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) diff --git a/integrations/cursor/install-local.mjs b/integrations/cursor/install-local.mjs new file mode 100644 index 0000000000..19d4232c7d --- /dev/null +++ b/integrations/cursor/install-local.mjs @@ -0,0 +1,114 @@ +#!/usr/bin/env node +import { 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 {}; + return JSON.parse(readFileSync(path, 'utf-8')); +} + +function writeJson(path, data) { + mkdirSync(dirname(path), { recursive: true }); + writeFileSync(path, `${JSON.stringify(data, null, 2)}\n`, 'utf-8'); +} + +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) { + const mcp = readJson(MCP_PATH); + 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); + writeJson(MCP_PATH, mcp); + return backup; +} + +function disableUserHooks() { + if (!process.argv.includes('--clear-user-hooks')) return null; + if (!existsSync(HOOKS_PATH)) return null; + const hooks = readJson(HOOKS_PATH); + 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: '); +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'); diff --git a/integrations/cursor/verify-flow.mjs b/integrations/cursor/verify-flow.mjs new file mode 100644 index 0000000000..645efaf65f --- /dev/null +++ b/integrations/cursor/verify-flow.mjs @@ -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); +} + +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); diff --git a/plugin/.cursor-plugin/plugin.json b/plugin/.cursor-plugin/plugin.json new file mode 100644 index 0000000000..3b314b6c53 --- /dev/null +++ b/plugin/.cursor-plugin/plugin.json @@ -0,0 +1,29 @@ +{ + "name": "agentmemory", + "displayName": "agentmemory", + "version": "0.9.28", + "description": "Persistent memory for AI coding agents — Cursor-native lifecycle hooks, 53 MCP tools, 15 skills, real-time viewer.", + "author": { + "name": "Rohit Ghumare", + "url": "https://github.com/rohitg00" + }, + "license": "Apache-2.0", + "homepage": "https://github.com/rohitg00/agentmemory", + "repository": "https://github.com/rohitg00/agentmemory", + "keywords": [ + "agentmemory", + "memory", + "hooks", + "mcp", + "cursor" + ], + "category": "developer-tools", + "tags": [ + "memory", + "hooks", + "mcp" + ], + "skills": "./skills/", + "mcpServers": "./.mcp.json", + "hooks": "./hooks/hooks.cursor.json" +} diff --git a/plugin/hooks/hooks.cursor.json b/plugin/hooks/hooks.cursor.json new file mode 100644 index 0000000000..35b464d657 --- /dev/null +++ b/plugin/hooks/hooks.cursor.json @@ -0,0 +1,56 @@ +{ + "version": 1, + "hooks": { + "sessionStart": [ + { + "command": "node \"${CURSOR_PLUGIN_ROOT}/scripts/cursor/agentmemory-session-start.mjs\"" + } + ], + "beforeSubmitPrompt": [ + { + "command": "node \"${CURSOR_PLUGIN_ROOT}/scripts/cursor/agentmemory-prompt-submit.mjs\"" + } + ], + "preToolUse": [ + { + "matcher": "Edit|Write|Read|Glob|Grep|Shell", + "command": "node \"${CURSOR_PLUGIN_ROOT}/scripts/cursor/agentmemory-pre-tool-use.mjs\"" + } + ], + "postToolUse": [ + { + "command": "node \"${CURSOR_PLUGIN_ROOT}/scripts/cursor/agentmemory-post-tool-use.mjs\"" + } + ], + "postToolUseFailure": [ + { + "command": "node \"${CURSOR_PLUGIN_ROOT}/scripts/cursor/agentmemory-post-tool-failure.mjs\"" + } + ], + "preCompact": [ + { + "command": "node \"${CURSOR_PLUGIN_ROOT}/scripts/cursor/agentmemory-pre-compact.mjs\"" + } + ], + "subagentStart": [ + { + "command": "node \"${CURSOR_PLUGIN_ROOT}/scripts/cursor/agentmemory-subagent-start.mjs\"" + } + ], + "subagentStop": [ + { + "command": "node \"${CURSOR_PLUGIN_ROOT}/scripts/cursor/agentmemory-subagent-stop.mjs\"" + } + ], + "stop": [ + { + "command": "node \"${CURSOR_PLUGIN_ROOT}/scripts/cursor/agentmemory-stop.mjs\"" + } + ], + "sessionEnd": [ + { + "command": "node \"${CURSOR_PLUGIN_ROOT}/scripts/cursor/agentmemory-session-end.mjs\"" + } + ] + } +} diff --git a/plugin/scripts/cursor/agentmemory-lib.mjs b/plugin/scripts/cursor/agentmemory-lib.mjs new file mode 100644 index 0000000000..ccf7b9c284 --- /dev/null +++ b/plugin/scripts/cursor/agentmemory-lib.mjs @@ -0,0 +1,269 @@ +#!/usr/bin/env node +import { readFileSync, writeFileSync, existsSync, readdirSync } from 'node:fs'; +import { join, dirname, basename } from 'node:path'; +import { homedir } from 'node:os'; +import { execSync } from 'node:child_process'; + +const HOME = homedir(); +const CURSOR_PROJECTS_DIR = join(HOME, '.cursor', 'projects'); +const SESSION_CACHE_PATH = join(HOME, '.cursor', 'hooks', '.agentmemory-session-cache.json'); + +function isBadPath(value) { + if (!value || typeof value !== 'string') return true; + const trimmed = value.trim(); + if (!trimmed || trimmed === '/' || trimmed === '.') return true; + if (trimmed === '.cursor' || trimmed.endsWith('/.cursor')) return true; + return false; +} + +function loadSessionCache() { + try { + return JSON.parse(readFileSync(SESSION_CACHE_PATH, 'utf-8')); + } catch { + return {}; + } +} + +function rememberSession(sessionId, project, cwd) { + if (!sessionId || !project || project === '.cursor') return; + try { + const cache = loadSessionCache(); + cache[sessionId] = { project, cwd, updatedAt: new Date().toISOString() }; + writeFileSync(SESSION_CACHE_PATH, JSON.stringify(cache, null, 2)); + } catch {} +} + +function recallSession(sessionId) { + if (!sessionId) return null; + const cache = loadSessionCache(); + return cache[sessionId] || null; +} + +function collectPathStrings(value, out = []) { + if (typeof value === 'string') { + if (value.startsWith(HOME) && !value.includes('/.cursor/')) out.push(value); + return out; + } + if (Array.isArray(value)) { + for (const item of value) collectPathStrings(item, out); + return out; + } + if (value && typeof value === 'object') { + for (const v of Object.values(value)) collectPathStrings(v, out); + } + return out; +} + +function existingAncestor(pathValue) { + let current = pathValue; + while (current && current !== HOME && current !== '/') { + if (existsSync(current)) return current; + current = dirname(current); + } + return null; +} + +function gitRootFromPath(targetPath) { + return execSync('git rev-parse --show-toplevel', { + cwd: targetPath, + encoding: 'utf-8', + stdio: ['ignore', 'pipe', 'ignore'] + }).trim(); +} + +function cleanRepoName(dirPath) { + const normalized = String(dirPath || '').replace(/\\/g, '/').replace(/\/+$/, ''); + if (!normalized) return 'unknown-project'; + + // Claude/Cursor worktrees: ...//.claude/worktrees/agent-xxx -> + const claudeWt = normalized.match(/^(.*?)\/\.claude\/worktrees\/[^/]+$/i); + if (claudeWt?.[1]) return cleanRepoName(claudeWt[1]); + + // Generic git worktree folder named agent- + const baseName = basename(normalized); + if (/^agent-[a-f0-9]{6,}$/i.test(baseName)) { + const parent = dirname(normalized); + if (parent && parent !== normalized && parent !== '.' && parent !== '/') { + return cleanRepoName(parent); + } + } + + let name = baseName.replace(/(-worktree-\d+|-worktree|-[a-f0-9]{7,40})$/i, ''); + // Known local variant folders that should share one memory bucket + if (/^pxread-/i.test(name)) return 'pxread'; + return name || 'unknown-project'; +} + +function projectFromPath(targetPath) { + try { + return cleanRepoName(gitRootFromPath(targetPath)); + } catch { + return cleanRepoName(targetPath); + } +} + +function decodeSlugCandidates(slug) { + if (!slug || slug === 'empty-window') return []; + const parts = slug.split('-'); + if (parts[0] !== 'Users' || parts.length < 2) return []; + + const results = new Set(); + + function walk(index, currentPath) { + if (index >= parts.length) { + if (existsSync(currentPath)) results.add(currentPath); + return; + } + walk(index + 1, `${currentPath}/${parts[index]}`); + const remainder = parts.slice(index).join('-'); + const alt = `${currentPath}/${remainder}`; + if (existsSync(alt)) results.add(alt); + } + + walk(2, `/${parts[0]}/${parts[1]}`); + return [...results]; +} + +function pickBestCandidate(candidates, preferredLabel) { + if (!candidates.length) return null; + if (preferredLabel) { + const labelMatch = candidates.find((p) => basename(p) === preferredLabel); + if (labelMatch) return labelMatch; + } + + const gitRoots = []; + for (const candidate of candidates) { + try { + gitRoots.push(gitRootFromPath(candidate)); + } catch {} + } + const uniqueGitRoots = [...new Set(gitRoots)]; + if (uniqueGitRoots.length === 1) return uniqueGitRoots[0]; + + return candidates.sort((a, b) => b.length - a.length)[0]; +} + +function findSessionTranscript(sessionId) { + if (!sessionId || !existsSync(CURSOR_PROJECTS_DIR)) return null; + + for (const slug of readdirSync(CURSOR_PROJECTS_DIR)) { + const transcriptsRoot = join(CURSOR_PROJECTS_DIR, slug, 'agent-transcripts'); + if (!existsSync(transcriptsRoot)) continue; + + for (const entry of readdirSync(transcriptsRoot)) { + if (entry === sessionId || entry.startsWith(`${sessionId}-`)) { + const transcriptFile = join(transcriptsRoot, entry, `${entry}.jsonl`); + return { + slug, + transcriptFile: existsSync(transcriptFile) ? transcriptFile : null + }; + } + } + } + return null; +} + +function workspaceFromTranscriptFile(transcriptFile) { + if (!transcriptFile || !existsSync(transcriptFile)) return null; + + const chunk = readFileSync(transcriptFile, 'utf-8').slice(0, 250000); + const escapedHome = HOME.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + const re = new RegExp(`${escapedHome}/[^\\s"'\\\\]+`, 'g'); + const counts = new Map(); + + for (const match of chunk.match(re) || []) { + if (match.includes('/.cursor/')) continue; + const existing = existingAncestor(match); + if (!existing || existing === HOME) continue; + counts.set(existing, (counts.get(existing) || 0) + 1); + } + + let best = null; + let bestCount = 0; + for (const [pathValue, count] of counts) { + if (count > bestCount) { + best = pathValue; + bestCount = count; + } + } + + return best; +} + +function workspaceFromSessionId(sessionId) { + const hit = findSessionTranscript(sessionId); + if (!hit) return null; + + const fromTranscript = workspaceFromTranscriptFile(hit.transcriptFile); + if (fromTranscript) return fromTranscript; + + const preferredLabel = process.env.CURSOR_WORKSPACE_LABEL || ''; + const candidates = decodeSlugCandidates(hit.slug); + return pickBestCandidate(candidates, preferredLabel); +} + +export function resolveWorkspace(data) { + const sessionId = data?.session_id; + const cached = recallSession(sessionId); + if (cached?.cwd && !isBadPath(cached.cwd)) { + return { project: cached.project, cwd: cached.cwd }; + } + + const payloadCandidates = [ + ...(Array.isArray(data?.workspace_roots) ? data.workspace_roots : []), + ...(Array.isArray(data?.workspace_folders) ? data.workspace_folders : []), + data?.workspace_folder, + data?.workspaceFolder, + data?.workspace, + data?.cwd, + data?.root_path, + data?.project_path, + process.env.CURSOR_WORKSPACE_ROOT, + process.env.CURSOR_WORKSPACE_FOLDER, + process.env.PWD, + process.env.VSCODE_CWD + ]; + + for (const candidate of payloadCandidates) { + if (isBadPath(candidate)) continue; + const existing = existingAncestor(candidate); + if (!existing) continue; + const project = projectFromPath(existing); + if (project !== '.cursor') { + rememberSession(sessionId, project, existing); + return { project, cwd: existing }; + } + } + + const toolPaths = collectPathStrings(data?.tool_input) + .map(existingAncestor) + .filter(Boolean); + for (const existing of toolPaths) { + const project = projectFromPath(existing); + if (project !== '.cursor') { + rememberSession(sessionId, project, existing); + return { project, cwd: existing }; + } + } + + if (sessionId) { + const fromSession = workspaceFromSessionId(sessionId); + if (fromSession) { + const project = projectFromPath(fromSession); + rememberSession(sessionId, project, fromSession); + return { project, cwd: fromSession }; + } + } + + if (process.env.CURSOR_WORKSPACE_LABEL) { + const label = process.env.CURSOR_WORKSPACE_LABEL; + rememberSession(sessionId, label, label); + return { project: label, cwd: label }; + } + + return { project: 'unknown-project', cwd: 'unknown-project' }; +} + +export function resolveProject(data) { + return resolveWorkspace(data).project; +} diff --git a/plugin/scripts/cursor/agentmemory-post-tool-failure.mjs b/plugin/scripts/cursor/agentmemory-post-tool-failure.mjs new file mode 100644 index 0000000000..3ca6e56114 --- /dev/null +++ b/plugin/scripts/cursor/agentmemory-post-tool-failure.mjs @@ -0,0 +1,66 @@ +#!/usr/bin/env node +import { readFileSync, existsSync } from 'node:fs'; +import { join } from 'node:path'; +import { homedir } from 'node:os'; +import { resolveWorkspace } from './agentmemory-lib.mjs'; + +const config = {}; +const envPath = join(homedir(), '.agentmemory', '.env'); +if (existsSync(envPath)) { + const content = readFileSync(envPath, 'utf-8'); + for (const line of content.split('\n')) { + const trimmed = line.trim(); + if (trimmed && !trimmed.startsWith('#')) { + const idx = trimmed.indexOf('='); + if (idx !== -1) { + const key = trimmed.slice(0, idx).trim(); + const val = trimmed.slice(idx + 1).trim(); + config[key] = val; + } + } + } +} + +const REST_URL = process.env.AGENTMEMORY_URL || config.AGENTMEMORY_URL || 'http://localhost:3111'; +const SECRET = process.env.AGENTMEMORY_SECRET || config.AGENTMEMORY_SECRET || ''; + +function authHeaders() { + const h = { 'Content-Type': 'application/json' }; + if (SECRET) h['Authorization'] = `Bearer ${SECRET}`; + return h; +} + + +async function main() { + let input = ''; + for await (const chunk of process.stdin) input += chunk; + let data; + try { + data = JSON.parse(input); + } catch { + return; + } + if (data.is_interrupt) return; + const sessionId = data.session_id || 'unknown'; + const { project, cwd } = resolveWorkspace(data); + try { + await fetch(`${REST_URL}/agentmemory/observe`, { + method: 'POST', + headers: authHeaders(), + body: JSON.stringify({ + hookType: 'post_tool_failure', + sessionId, + project, + cwd, + timestamp: new Date().toISOString(), + data: { + tool_name: data.tool_name, + tool_input: typeof data.tool_input === 'string' ? data.tool_input.slice(0, 4000) : JSON.stringify(data.tool_input ?? '').slice(0, 4000), + error: typeof data.error === 'string' ? data.error.slice(0, 4000) : JSON.stringify(data.error ?? '').slice(0, 4000) + } + }), + signal: AbortSignal.timeout(3000) + }); + } catch {} +} +main(); diff --git a/plugin/scripts/cursor/agentmemory-post-tool-use.mjs b/plugin/scripts/cursor/agentmemory-post-tool-use.mjs new file mode 100644 index 0000000000..f0f09c320a --- /dev/null +++ b/plugin/scripts/cursor/agentmemory-post-tool-use.mjs @@ -0,0 +1,109 @@ +#!/usr/bin/env node +import { readFileSync, existsSync } from 'node:fs'; +import { join } from 'node:path'; +import { homedir } from 'node:os'; +import { resolveWorkspace } from './agentmemory-lib.mjs'; + +const config = {}; +const envPath = join(homedir(), '.agentmemory', '.env'); +if (existsSync(envPath)) { + const content = readFileSync(envPath, 'utf-8'); + for (const line of content.split('\n')) { + const trimmed = line.trim(); + if (trimmed && !trimmed.startsWith('#')) { + const idx = trimmed.indexOf('='); + if (idx !== -1) { + const key = trimmed.slice(0, idx).trim(); + const val = trimmed.slice(idx + 1).trim(); + config[key] = val; + } + } + } +} + +const REST_URL = process.env.AGENTMEMORY_URL || config.AGENTMEMORY_URL || 'http://localhost:3111'; +const SECRET = process.env.AGENTMEMORY_SECRET || config.AGENTMEMORY_SECRET || ''; + +function authHeaders() { + const h = { 'Content-Type': 'application/json' }; + if (SECRET) h['Authorization'] = `Bearer ${SECRET}`; + return h; +} + + +async function main() { + let input = ''; + for await (const chunk of process.stdin) input += chunk; + let data; + try { + data = JSON.parse(input); + } catch { + return; + } + const sessionId = data.session_id || 'unknown'; + const { project, cwd } = resolveWorkspace(data); + const { imageData, cleanOutput } = extractImageData(data.tool_response ?? data.tool_output); + try { + await fetch(`${REST_URL}/agentmemory/observe`, { + method: 'POST', + headers: authHeaders(), + body: JSON.stringify({ + hookType: 'post_tool_use', + sessionId, + project, + cwd, + timestamp: new Date().toISOString(), + data: { + tool_name: data.tool_name, + tool_input: data.tool_input, + tool_output: truncate(cleanOutput, 8000), + ...imageData ? { image_data: imageData } : {} + } + }), + signal: AbortSignal.timeout(3000) + }); + } catch {} +} + +function isBase64Image(val) { + return typeof val === 'string' && (val.startsWith('data:image/') || val.startsWith('iVBORw0KGgo') || val.startsWith('/9j/')); +} + +function extractImageData(output) { + if (isBase64Image(output)) return { + imageData: output, + cleanOutput: '[image data extracted]' + }; + if (typeof output === 'object' && output !== null && !Array.isArray(output)) { + const obj = output; + let imageData; + const clean = {}; + for (const [key, val] of Object.entries(obj)) { + if (!imageData && isBase64Image(val)) { + imageData = val; + clean[key] = '[image data extracted]'; + } else { + clean[key] = val; + } + } + return { + imageData, + cleanOutput: clean + }; + } + return { + imageData: undefined, + cleanOutput: output + }; +} + +function truncate(value, max) { + if (typeof value === 'string' && value.length > max) return value.slice(0, max) + '\n[...truncated]'; + if (typeof value === 'object' && value !== null) { + const str = JSON.stringify(value); + if (str.length > max) return str.slice(0, max) + '...[truncated]'; + return value; + } + return value; +} +main(); diff --git a/plugin/scripts/cursor/agentmemory-pre-compact.mjs b/plugin/scripts/cursor/agentmemory-pre-compact.mjs new file mode 100644 index 0000000000..120eb22268 --- /dev/null +++ b/plugin/scripts/cursor/agentmemory-pre-compact.mjs @@ -0,0 +1,76 @@ +#!/usr/bin/env node +import { readFileSync, existsSync } from 'node:fs'; +import { join } from 'node:path'; +import { homedir } from 'node:os'; +import { resolveWorkspace } from './agentmemory-lib.mjs'; + +const config = {}; +const envPath = join(homedir(), '.agentmemory', '.env'); +if (existsSync(envPath)) { + const content = readFileSync(envPath, 'utf-8'); + for (const line of content.split('\n')) { + const trimmed = line.trim(); + if (trimmed && !trimmed.startsWith('#')) { + const idx = trimmed.indexOf('='); + if (idx !== -1) { + const key = trimmed.slice(0, idx).trim(); + const val = trimmed.slice(idx + 1).trim(); + config[key] = val; + } + } + } +} + +const REST_URL = process.env.AGENTMEMORY_URL || config.AGENTMEMORY_URL || 'http://localhost:3111'; +const SECRET = process.env.AGENTMEMORY_SECRET || config.AGENTMEMORY_SECRET || ''; + +function authHeaders() { + const h = { 'Content-Type': 'application/json' }; + if (SECRET) h['Authorization'] = `Bearer ${SECRET}`; + return h; +} + + +async function main() { + let input = ''; + for await (const chunk of process.stdin) input += chunk; + let data; + try { + data = JSON.parse(input); + } catch { + return; + } + const sessionId = data.session_id || 'unknown'; + const { project, cwd } = resolveWorkspace(data); + if (process.env.CLAUDE_MEMORY_BRIDGE === 'true' || config.CLAUDE_MEMORY_BRIDGE === 'true') { + try { + await fetch(`${REST_URL}/agentmemory/claude-bridge/sync`, { + method: 'POST', + headers: authHeaders(), + body: JSON.stringify({}), + signal: AbortSignal.timeout(5000) + }); + } catch {} + } + try { + const res = await fetch(`${REST_URL}/agentmemory/context`, { + method: 'POST', + headers: authHeaders(), + body: JSON.stringify({ + sessionId, + project, + budget: 1500 + }), + signal: AbortSignal.timeout(5000) + }); + if (res.ok) { + const result = await res.json(); + if (result.context) { + process.stdout.write(JSON.stringify({ + additional_context: result.context + })); + } + } + } catch {} +} +main(); diff --git a/plugin/scripts/cursor/agentmemory-pre-tool-use.mjs b/plugin/scripts/cursor/agentmemory-pre-tool-use.mjs new file mode 100644 index 0000000000..6952596f4f --- /dev/null +++ b/plugin/scripts/cursor/agentmemory-pre-tool-use.mjs @@ -0,0 +1,89 @@ +#!/usr/bin/env node +import { readFileSync, existsSync } from 'node:fs'; +import { join } from 'node:path'; +import { homedir } from 'node:os'; +import { resolveWorkspace } from './agentmemory-lib.mjs'; + +const config = {}; +const envPath = join(homedir(), '.agentmemory', '.env'); +if (existsSync(envPath)) { + const content = readFileSync(envPath, 'utf-8'); + for (const line of content.split('\n')) { + const trimmed = line.trim(); + if (trimmed && !trimmed.startsWith('#')) { + const idx = trimmed.indexOf('='); + if (idx !== -1) { + const key = trimmed.slice(0, idx).trim(); + const val = trimmed.slice(idx + 1).trim(); + config[key] = val; + } + } + } +} + +const INJECT_CONTEXT = process.env.AGENTMEMORY_INJECT_CONTEXT === 'true' || config.AGENTMEMORY_INJECT_CONTEXT === 'true'; +const REST_URL = process.env.AGENTMEMORY_URL || config.AGENTMEMORY_URL || 'http://localhost:3111'; +const SECRET = process.env.AGENTMEMORY_SECRET || config.AGENTMEMORY_SECRET || ''; + +function authHeaders() { + const h = { 'Content-Type': 'application/json' }; + if (SECRET) h['Authorization'] = `Bearer ${SECRET}`; + return h; +} + + +async function main() { + if (!INJECT_CONTEXT) return; + let input = ''; + for await (const chunk of process.stdin) input += chunk; + let data; + try { + data = JSON.parse(input); + } catch { + return; + } + const toolName = data.tool_name; + if (!toolName) return; + if (!['Edit', 'Write', 'Read', 'Glob', 'Grep', 'Shell'].includes(toolName)) return; + + const toolInput = data.tool_input || {}; + const files = []; + const fileKeys = toolName === 'Grep' ? ['path', 'file'] : ['file_path', 'path', 'file', 'pattern']; + + for (const key of fileKeys) { + const val = toolInput[key]; + if (typeof val === 'string' && val.length > 0) files.push(val); + } + if (files.length === 0) return; + + const terms = []; + if (toolName === 'Grep' || toolName === 'Glob') { + const pattern = toolInput['pattern']; + if (typeof pattern === 'string' && pattern.length > 0) terms.push(pattern); + } + const sessionId = data.session_id || 'unknown'; + const { project, cwd } = resolveWorkspace(data); + try { + const res = await fetch(`${REST_URL}/agentmemory/enrich`, { + method: 'POST', + headers: authHeaders(), + body: JSON.stringify({ + sessionId, + project, + files, + terms, + toolName + }), + signal: AbortSignal.timeout(2000) + }); + if (res.ok) { + const result = await res.json(); + if (result.context) { + process.stdout.write(JSON.stringify({ + additional_context: result.context + })); + } + } + } catch {} +} +main(); diff --git a/plugin/scripts/cursor/agentmemory-prompt-submit.mjs b/plugin/scripts/cursor/agentmemory-prompt-submit.mjs new file mode 100644 index 0000000000..f5fe2ceb61 --- /dev/null +++ b/plugin/scripts/cursor/agentmemory-prompt-submit.mjs @@ -0,0 +1,61 @@ +#!/usr/bin/env node +import { readFileSync, existsSync } from 'node:fs'; +import { join } from 'node:path'; +import { homedir } from 'node:os'; +import { resolveWorkspace } from './agentmemory-lib.mjs'; + +const config = {}; +const envPath = join(homedir(), '.agentmemory', '.env'); +if (existsSync(envPath)) { + const content = readFileSync(envPath, 'utf-8'); + for (const line of content.split('\n')) { + const trimmed = line.trim(); + if (trimmed && !trimmed.startsWith('#')) { + const idx = trimmed.indexOf('='); + if (idx !== -1) { + const key = trimmed.slice(0, idx).trim(); + const val = trimmed.slice(idx + 1).trim(); + config[key] = val; + } + } + } +} + +const REST_URL = process.env.AGENTMEMORY_URL || config.AGENTMEMORY_URL || 'http://localhost:3111'; +const SECRET = process.env.AGENTMEMORY_SECRET || config.AGENTMEMORY_SECRET || ''; + +function authHeaders() { + const h = { 'Content-Type': 'application/json' }; + if (SECRET) h['Authorization'] = `Bearer ${SECRET}`; + return h; +} + + +async function main() { + let input = ''; + for await (const chunk of process.stdin) input += chunk; + let data; + try { + data = JSON.parse(input); + } catch { + return; + } + const sessionId = data.session_id || 'unknown'; + const { project, cwd } = resolveWorkspace(data); + try { + await fetch(`${REST_URL}/agentmemory/observe`, { + method: 'POST', + headers: authHeaders(), + body: JSON.stringify({ + hookType: 'prompt_submit', + sessionId, + project, + cwd, + timestamp: new Date().toISOString(), + data: { prompt: data.prompt || data.user_prompt } + }), + signal: AbortSignal.timeout(3000) + }); + } catch {} +} +main(); diff --git a/plugin/scripts/cursor/agentmemory-session-end.mjs b/plugin/scripts/cursor/agentmemory-session-end.mjs new file mode 100644 index 0000000000..2d8a70b61c --- /dev/null +++ b/plugin/scripts/cursor/agentmemory-session-end.mjs @@ -0,0 +1,143 @@ +#!/usr/bin/env node +import { readFileSync, existsSync } from 'node:fs'; +import { join } from 'node:path'; +import { homedir } from 'node:os'; +import { spawn } from 'node:child_process'; +import { fileURLToPath } from 'node:url'; +import { resolveWorkspace } from './agentmemory-lib.mjs'; + +// Runs in two modes: +// parent -> reads stdin, spawns a DETACHED background worker, exits immediately +// so Cursor never waits on this hook when closing / switching workspace. +// worker -> performs the (possibly slow, remote) memory calls, then force-exits. +// A hard watchdog guarantees the process always terminates -> no leftover node. +const IS_WORKER = process.env.AM_HOOK_WORKER === '1'; + +const config = {}; +const envPath = join(homedir(), '.agentmemory', '.env'); +if (existsSync(envPath)) { + const content = readFileSync(envPath, 'utf-8'); + for (const line of content.split('\n')) { + const trimmed = line.trim(); + if (trimmed && !trimmed.startsWith('#')) { + const idx = trimmed.indexOf('='); + if (idx !== -1) { + const key = trimmed.slice(0, idx).trim(); + const val = trimmed.slice(idx + 1).trim(); + config[key] = val; + } + } + } +} + +const REST_URL = process.env.AGENTMEMORY_URL || config.AGENTMEMORY_URL || 'http://localhost:3111'; +const SECRET = process.env.AGENTMEMORY_SECRET || config.AGENTMEMORY_SECRET || ''; + +function authHeaders() { + const h = { 'Content-Type': 'application/json' }; + if (SECRET) h['Authorization'] = `Bearer ${SECRET}`; + return h; +} + +// ---- worker mode: do the actual (slow) work, then guarantee self-termination ---- +async function runWorker() { + // Absolute backstop: even if a request wedges past its own AbortSignal, the + // worker is force-killed. Slightly above the sum of per-request timeouts below. + const HARD_LIMIT_MS = 250000; + const watchdog = setTimeout(() => process.exit(0), HARD_LIMIT_MS); + + try { + let data; + try { + data = JSON.parse(process.env.AM_HOOK_INPUT || '{}'); + } catch { + data = {}; + } + const sessionId = data.session_id || 'unknown'; + const { project } = resolveWorkspace(data); + + try { + await fetch(`${REST_URL}/agentmemory/session/end`, { + method: 'POST', + headers: authHeaders(), + body: JSON.stringify({ sessionId, project }), + signal: AbortSignal.timeout(30000) + }); + } catch {} + + if (process.env.CONSOLIDATION_ENABLED === 'true' || config.CONSOLIDATION_ENABLED === 'true') { + try { + await fetch(`${REST_URL}/agentmemory/crystals/auto`, { + method: 'POST', + headers: authHeaders(), + body: JSON.stringify({ olderThanDays: 0, project }), + signal: AbortSignal.timeout(60000) + }); + } catch {} + try { + await fetch(`${REST_URL}/agentmemory/consolidate-pipeline`, { + method: 'POST', + headers: authHeaders(), + body: JSON.stringify({ tier: 'all', force: true, project }), + signal: AbortSignal.timeout(120000) + }); + } catch {} + } + + if (process.env.CLAUDE_MEMORY_BRIDGE === 'true' || config.CLAUDE_MEMORY_BRIDGE === 'true') { + try { + await fetch(`${REST_URL}/agentmemory/claude-bridge/sync`, { + method: 'POST', + headers: authHeaders(), + signal: AbortSignal.timeout(30000) + }); + } catch {} + } + } finally { + clearTimeout(watchdog); + // Force exit so undici's keep-alive socket pool cannot keep the process alive. + process.exit(0); + } +} + +// ---- parent mode: capture stdin, hand off to detached worker, exit fast ---- +function readStdin(timeoutMs) { + return new Promise((resolve) => { + let input = ''; + let done = false; + const finish = () => { + if (done) return; + done = true; + try { process.stdin.destroy(); } catch {} + resolve(input); + }; + const t = setTimeout(finish, timeoutMs); + if (t.unref) t.unref(); + process.stdin.on('data', (c) => { input += c; }); + process.stdin.on('end', () => { clearTimeout(t); finish(); }); + process.stdin.on('error', () => { clearTimeout(t); finish(); }); + }); +} + +async function runParent() { + const input = await readStdin(1500); + + const child = spawn(process.execPath, [fileURLToPath(import.meta.url)], { + detached: true, + stdio: 'ignore', + windowsHide: true, + env: { ...process.env, AM_HOOK_WORKER: '1', AM_HOOK_INPUT: input } + }); + child.unref(); + + const bail = setTimeout(() => process.exit(0), 2000); + if (bail.unref) bail.unref(); + child.on('spawn', () => process.exit(0)); + child.on('error', () => process.exit(0)); +} + +if (IS_WORKER) { + runWorker(); +} else { + runParent(); +} diff --git a/plugin/scripts/cursor/agentmemory-session-start.mjs b/plugin/scripts/cursor/agentmemory-session-start.mjs new file mode 100644 index 0000000000..5c629d9846 --- /dev/null +++ b/plugin/scripts/cursor/agentmemory-session-start.mjs @@ -0,0 +1,83 @@ +#!/usr/bin/env node +import { readFileSync, existsSync } from 'node:fs'; +import { join } from 'node:path'; +import { homedir } from 'node:os'; +import { resolveWorkspace } from './agentmemory-lib.mjs'; + +// Load config from ~/.agentmemory/.env +const config = {}; +const envPath = join(homedir(), '.agentmemory', '.env'); +if (existsSync(envPath)) { + const content = readFileSync(envPath, 'utf-8'); + for (const line of content.split('\n')) { + const trimmed = line.trim(); + if (trimmed && !trimmed.startsWith('#')) { + const idx = trimmed.indexOf('='); + if (idx !== -1) { + const key = trimmed.slice(0, idx).trim(); + const val = trimmed.slice(idx + 1).trim(); + config[key] = val; + } + } + } +} + +const INJECT_CONTEXT = process.env.AGENTMEMORY_INJECT_CONTEXT === 'true' || config.AGENTMEMORY_INJECT_CONTEXT === 'true'; +const REST_URL = process.env.AGENTMEMORY_URL || config.AGENTMEMORY_URL || 'http://localhost:3111'; +const SECRET = process.env.AGENTMEMORY_SECRET || config.AGENTMEMORY_SECRET || ''; +const INJECT_TIMEOUT_MS = 2500; +const REGISTER_TIMEOUT_MS = 1500; + +function authHeaders() { + const h = { 'Content-Type': 'application/json' }; + if (SECRET) h['Authorization'] = `Bearer ${SECRET}`; + return h; +} + + +async function main() { + let input = ''; + for await (const chunk of process.stdin) input += chunk; + let data; + try { + data = JSON.parse(input); + } catch { + return; + } + const sessionId = data.session_id || `ses_${Date.now().toString(36)}`; + const { project, cwd } = resolveWorkspace(data); + const url = `${REST_URL}/agentmemory/session/start`; + const init = { + method: 'POST', + headers: authHeaders(), + body: JSON.stringify({ + sessionId, + project, + cwd + }) + }; + if (!INJECT_CONTEXT) { + try { + await fetch(url, { + ...init, + signal: AbortSignal.timeout(REGISTER_TIMEOUT_MS) + }); + } catch {} + return; + } + try { + const res = await fetch(url, { + ...init, + signal: AbortSignal.timeout(INJECT_TIMEOUT_MS) + }); + if (res.ok) { + const result = await res.json(); + if (result.context) { + process.stdout.write(JSON.stringify({ + additional_context: result.context + })); + } + } + } catch {} +} +main(); diff --git a/plugin/scripts/cursor/agentmemory-stop.mjs b/plugin/scripts/cursor/agentmemory-stop.mjs new file mode 100644 index 0000000000..7f4601274d --- /dev/null +++ b/plugin/scripts/cursor/agentmemory-stop.mjs @@ -0,0 +1,113 @@ +#!/usr/bin/env node +import { readFileSync, existsSync } from 'node:fs'; +import { join } from 'node:path'; +import { homedir } from 'node:os'; +import { spawn } from 'node:child_process'; +import { fileURLToPath } from 'node:url'; +import { resolveWorkspace } from './agentmemory-lib.mjs'; + +// Runs in two modes: +// parent -> reads stdin, spawns a DETACHED background worker, exits immediately +// so Cursor never waits on this hook at the end of a response. +// worker -> performs the (possibly slow, remote) summarize call, then force-exits. +// A hard watchdog guarantees the process always terminates -> no leftover node. +const IS_WORKER = process.env.AM_HOOK_WORKER === '1'; + +const config = {}; +const envPath = join(homedir(), '.agentmemory', '.env'); +if (existsSync(envPath)) { + const content = readFileSync(envPath, 'utf-8'); + for (const line of content.split('\n')) { + const trimmed = line.trim(); + if (trimmed && !trimmed.startsWith('#')) { + const idx = trimmed.indexOf('='); + if (idx !== -1) { + const key = trimmed.slice(0, idx).trim(); + const val = trimmed.slice(idx + 1).trim(); + config[key] = val; + } + } + } +} + +const REST_URL = process.env.AGENTMEMORY_URL || config.AGENTMEMORY_URL || 'http://localhost:3111'; +const SECRET = process.env.AGENTMEMORY_SECRET || config.AGENTMEMORY_SECRET || ''; + +function authHeaders() { + const h = { 'Content-Type': 'application/json' }; + if (SECRET) h['Authorization'] = `Bearer ${SECRET}`; + return h; +} + +// ---- worker mode: do the actual (slow) work, then guarantee self-termination ---- +async function runWorker() { + // Absolute backstop: even if the request wedges past its AbortSignal, force-kill. + const HARD_LIMIT_MS = 130000; + const watchdog = setTimeout(() => process.exit(0), HARD_LIMIT_MS); + + try { + let data; + try { + data = JSON.parse(process.env.AM_HOOK_INPUT || '{}'); + } catch { + data = {}; + } + const sessionId = data.session_id || 'unknown'; + const { project } = resolveWorkspace(data); + + try { + await fetch(`${REST_URL}/agentmemory/summarize`, { + method: 'POST', + headers: authHeaders(), + body: JSON.stringify({ sessionId, project }), + signal: AbortSignal.timeout(120000) + }); + } catch {} + } finally { + clearTimeout(watchdog); + // Force exit so undici's keep-alive socket pool cannot keep the process alive. + process.exit(0); + } +} + +// ---- parent mode: capture stdin, hand off to detached worker, exit fast ---- +function readStdin(timeoutMs) { + return new Promise((resolve) => { + let input = ''; + let done = false; + const finish = () => { + if (done) return; + done = true; + try { process.stdin.destroy(); } catch {} + resolve(input); + }; + const t = setTimeout(finish, timeoutMs); + if (t.unref) t.unref(); + process.stdin.on('data', (c) => { input += c; }); + process.stdin.on('end', () => { clearTimeout(t); finish(); }); + process.stdin.on('error', () => { clearTimeout(t); finish(); }); + }); +} + +async function runParent() { + const input = await readStdin(1500); + + const child = spawn(process.execPath, [fileURLToPath(import.meta.url)], { + detached: true, + stdio: 'ignore', + windowsHide: true, + env: { ...process.env, AM_HOOK_WORKER: '1', AM_HOOK_INPUT: input } + }); + child.unref(); + + const bail = setTimeout(() => process.exit(0), 2000); + if (bail.unref) bail.unref(); + child.on('spawn', () => process.exit(0)); + child.on('error', () => process.exit(0)); +} + +if (IS_WORKER) { + runWorker(); +} else { + runParent(); +} diff --git a/plugin/scripts/cursor/agentmemory-subagent-start.mjs b/plugin/scripts/cursor/agentmemory-subagent-start.mjs new file mode 100644 index 0000000000..2cbacb262d --- /dev/null +++ b/plugin/scripts/cursor/agentmemory-subagent-start.mjs @@ -0,0 +1,63 @@ +#!/usr/bin/env node +import { readFileSync, existsSync } from 'node:fs'; +import { join } from 'node:path'; +import { homedir } from 'node:os'; +import { resolveWorkspace } from './agentmemory-lib.mjs'; + +const config = {}; +const envPath = join(homedir(), '.agentmemory', '.env'); +if (existsSync(envPath)) { + const content = readFileSync(envPath, 'utf-8'); + for (const line of content.split('\n')) { + const trimmed = line.trim(); + if (trimmed && !trimmed.startsWith('#')) { + const idx = trimmed.indexOf('='); + if (idx !== -1) { + const key = trimmed.slice(0, idx).trim(); + const val = trimmed.slice(idx + 1).trim(); + config[key] = val; + } + } + } +} + +const REST_URL = process.env.AGENTMEMORY_URL || config.AGENTMEMORY_URL || 'http://localhost:3111'; +const SECRET = process.env.AGENTMEMORY_SECRET || config.AGENTMEMORY_SECRET || ''; +const TIMEOUT_MS = 800; + +function authHeaders() { + const h = { 'Content-Type': 'application/json' }; + if (SECRET) h['Authorization'] = `Bearer ${SECRET}`; + return h; +} + + +async function main() { + let input = ''; + for await (const chunk of process.stdin) input += chunk; + let data; + try { + data = JSON.parse(input); + } catch { + return; + } + const sessionId = data.session_id || 'unknown'; + const { project, cwd } = resolveWorkspace(data); + fetch(`${REST_URL}/agentmemory/observe`, { + method: 'POST', + headers: authHeaders(), + body: JSON.stringify({ + hookType: 'subagent_start', + sessionId, + project, + cwd, + timestamp: new Date().toISOString(), + data: { + agent_id: data.agent_id, + agent_type: data.agent_type + } + }), + signal: AbortSignal.timeout(TIMEOUT_MS) + }).catch(() => {}); +} +main(); diff --git a/plugin/scripts/cursor/agentmemory-subagent-stop.mjs b/plugin/scripts/cursor/agentmemory-subagent-stop.mjs new file mode 100644 index 0000000000..c3ebb7661f --- /dev/null +++ b/plugin/scripts/cursor/agentmemory-subagent-stop.mjs @@ -0,0 +1,66 @@ +#!/usr/bin/env node +import { readFileSync, existsSync } from 'node:fs'; +import { join } from 'node:path'; +import { homedir } from 'node:os'; +import { resolveWorkspace } from './agentmemory-lib.mjs'; + +const config = {}; +const envPath = join(homedir(), '.agentmemory', '.env'); +if (existsSync(envPath)) { + const content = readFileSync(envPath, 'utf-8'); + for (const line of content.split('\n')) { + const trimmed = line.trim(); + if (trimmed && !trimmed.startsWith('#')) { + const idx = trimmed.indexOf('='); + if (idx !== -1) { + const key = trimmed.slice(0, idx).trim(); + const val = trimmed.slice(idx + 1).trim(); + config[key] = val; + } + } + } +} + +const REST_URL = process.env.AGENTMEMORY_URL || config.AGENTMEMORY_URL || 'http://localhost:3111'; +const SECRET = process.env.AGENTMEMORY_SECRET || config.AGENTMEMORY_SECRET || ''; + +function authHeaders() { + const h = { 'Content-Type': 'application/json' }; + if (SECRET) h['Authorization'] = `Bearer ${SECRET}`; + return h; +} + + +async function main() { + let input = ''; + for await (const chunk of process.stdin) input += chunk; + let data; + try { + data = JSON.parse(input); + } catch { + return; + } + const sessionId = data.session_id || 'unknown'; + const { project, cwd } = resolveWorkspace(data); + const lastMsg = typeof data.last_assistant_message === 'string' ? data.last_assistant_message.slice(0, 4000) : ''; + try { + await fetch(`${REST_URL}/agentmemory/observe`, { + method: 'POST', + headers: authHeaders(), + body: JSON.stringify({ + hookType: 'subagent_stop', + sessionId, + project, + cwd, + timestamp: new Date().toISOString(), + data: { + agent_id: data.agent_id, + agent_type: data.agent_type, + last_message: lastMsg + } + }), + signal: AbortSignal.timeout(2000) + }); + } catch {} +} +main(); diff --git a/plugin/scripts/cursor/close-stale-am-sessions.mjs b/plugin/scripts/cursor/close-stale-am-sessions.mjs new file mode 100644 index 0000000000..d1f6ddd86b --- /dev/null +++ b/plugin/scripts/cursor/close-stale-am-sessions.mjs @@ -0,0 +1,136 @@ +#!/usr/bin/env node +/** + * Close agentmemory sessions stuck in status "active" (sessionEnd hook never ran). + * + * Usage: + * node close-stale-am-sessions.mjs --dry-run + * node close-stale-am-sessions.mjs --min-age-hours 24 + * node close-stale-am-sessions.mjs --min-age-hours 6 --project 智能报表-wrenai + * node close-stale-am-sessions.mjs --exclude ses_abc123,def456 + */ +import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { homedir } from 'node:os'; + +function loadEnv() { + const envPath = join(homedir(), '.agentmemory', '.env'); + const env = {}; + for (const line of readFileSync(envPath, 'utf-8').split('\n')) { + const trimmed = line.trim(); + if (!trimmed || trimmed.startsWith('#')) continue; + const eq = trimmed.indexOf('='); + if (eq === -1) continue; + env[trimmed.slice(0, eq).trim()] = trimmed.slice(eq + 1).trim(); + } + return env; +} + +function parseArgs() { + const args = process.argv.slice(2); + const opts = { + dryRun: args.includes('--dry-run'), + minAgeHours: 24, + project: null, + exclude: new Set() + }; + for (let i = 0; i < args.length; i++) { + if (args[i] === '--min-age-hours' && args[i + 1]) { + opts.minAgeHours = Number(args[++i]); + } else if (args[i] === '--project' && args[i + 1]) { + opts.project = args[++i]; + } else if (args[i] === '--exclude' && args[i + 1]) { + for (const id of args[++i].split(',')) { + const t = id.trim(); + if (t) opts.exclude.add(t); + } + } + } + return opts; +} + +async function main() { + const opts = parseArgs(); + const { AGENTMEMORY_URL, AGENTMEMORY_SECRET } = loadEnv(); + if (!AGENTMEMORY_URL || !AGENTMEMORY_SECRET) { + console.error('Missing AGENTMEMORY_URL or AGENTMEMORY_SECRET in ~/.agentmemory/.env'); + process.exit(1); + } + + const headers = { + Authorization: `Bearer ${AGENTMEMORY_SECRET}`, + 'Content-Type': 'application/json' + }; + + const listRes = await fetch(`${AGENTMEMORY_URL}/agentmemory/sessions`, { headers }); + if (!listRes.ok) { + console.error('Failed to list sessions:', listRes.status, await listRes.text()); + process.exit(1); + } + + const { sessions } = await listRes.json(); + const cutoff = Date.now() - opts.minAgeHours * 3600000; + const candidates = sessions.filter((s) => { + if (s.status !== 'active') return false; + if (opts.exclude.has(s.id)) return false; + if (opts.project && s.project !== opts.project) return false; + const started = Date.parse(s.startedAt); + if (!Number.isFinite(started) || started > cutoff) return false; + return true; + }); + + candidates.sort((a, b) => Date.parse(a.startedAt) - Date.parse(b.startedAt)); + + console.log( + `Found ${candidates.length} active session(s) older than ${opts.minAgeHours}h` + + (opts.project ? ` (project=${opts.project})` : '') + ); + + for (const s of candidates) { + const ageH = ((Date.now() - Date.parse(s.startedAt)) / 3600000).toFixed(1); + console.log( + ` ${s.id.slice(0, 12)}… ${s.project} obs=${s.observationCount ?? 0} age=${ageH}h` + ); + } + + if (!candidates.length) { + console.log('Nothing to close.'); + return; + } + + if (opts.dryRun) { + console.log(`Dry run: would close ${candidates.length} session(s) via POST /agentmemory/session/end`); + return; + } + + let closed = 0; + let failed = 0; + + for (const s of candidates) { + const res = await fetch(`${AGENTMEMORY_URL}/agentmemory/session/end`, { + method: 'POST', + headers, + body: JSON.stringify({ sessionId: s.id }) + }); + if (res.ok) { + closed++; + } else { + failed++; + console.error(` failed ${s.id}: ${res.status} ${await res.text()}`); + } + } + + console.log(`Closed ${closed} session(s), ${failed} failed.`); + + const verify = await fetch(`${AGENTMEMORY_URL}/agentmemory/sessions`, { headers }).then((r) => + r.json() + ); + const stillActive = verify.sessions.filter( + (s) => s.status === 'active' && Date.parse(s.startedAt) <= cutoff + ).length; + console.log(`Remaining stale active (>${opts.minAgeHours}h): ${stillActive}`); +} + +main().catch((err) => { + console.error(err); + process.exit(1); +}); diff --git a/plugin/scripts/cursor/fix-cursor-session-projects.mjs b/plugin/scripts/cursor/fix-cursor-session-projects.mjs new file mode 100644 index 0000000000..35857a0b66 --- /dev/null +++ b/plugin/scripts/cursor/fix-cursor-session-projects.mjs @@ -0,0 +1,130 @@ +#!/usr/bin/env node +/** + * One-off migration: fix sessions stored with project/cwd ".cursor" + * by re-resolving the real workspace from Cursor transcript paths. + * + * Usage: + * node fix-cursor-session-projects.mjs # apply + * node fix-cursor-session-projects.mjs --dry-run # preview only + */ +import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { homedir } from 'node:os'; +import { resolveWorkspace } from './agentmemory-lib.mjs'; + +const dryRun = process.argv.includes('--dry-run'); + +function loadEnv() { + const envPath = join(homedir(), '.agentmemory', '.env'); + const env = {}; + for (const line of readFileSync(envPath, 'utf-8').split('\n')) { + const trimmed = line.trim(); + if (!trimmed || trimmed.startsWith('#')) continue; + const eq = trimmed.indexOf('='); + if (eq === -1) continue; + env[trimmed.slice(0, eq).trim()] = trimmed.slice(eq + 1).trim(); + } + return env; +} + +function isBadSession(session) { + const { project, cwd } = session; + if (project === '.cursor' || cwd === '.cursor') return true; + if (project?.endsWith('/.cursor') || cwd?.endsWith('/.cursor')) return true; + if (project?.includes('/.cursor') || cwd?.includes('/.cursor')) return true; + return false; +} + +async function main() { + const { AGENTMEMORY_URL, AGENTMEMORY_SECRET } = loadEnv(); + if (!AGENTMEMORY_URL || !AGENTMEMORY_SECRET) { + console.error('Missing AGENTMEMORY_URL or AGENTMEMORY_SECRET in ~/.agentmemory/.env'); + process.exit(1); + } + + const headers = { + Authorization: `Bearer ${AGENTMEMORY_SECRET}`, + 'Content-Type': 'application/json' + }; + + const listRes = await fetch(`${AGENTMEMORY_URL}/agentmemory/sessions`, { headers }); + if (!listRes.ok) { + console.error('Failed to list sessions:', listRes.status, await listRes.text()); + process.exit(1); + } + + const { sessions } = await listRes.json(); + const bad = sessions.filter(isBadSession); + console.log(`Found ${bad.length} session(s) with .cursor project/cwd (of ${sessions.length} total)`); + + const fixes = []; + const skipped = []; + + for (const session of bad) { + const resolved = resolveWorkspace({ session_id: session.id }); + if ( + !resolved?.project || + resolved.project === '.cursor' || + resolved.project === 'unknown-project' + ) { + skipped.push({ id: session.id, reason: 'could not resolve workspace', resolved }); + continue; + } + if (resolved.project === session.project && resolved.cwd === session.cwd) { + skipped.push({ id: session.id, reason: 'already correct', resolved }); + continue; + } + fixes.push({ + id: session.id, + from: { project: session.project, cwd: session.cwd }, + to: resolved, + session: { ...session, project: resolved.project, cwd: resolved.cwd } + }); + } + + for (const fix of fixes) { + console.log(` ${fix.id}: ${fix.from.project} → ${fix.to.project}`); + } + for (const s of skipped) { + console.log(` skip ${s.id}: ${s.reason}`); + } + + if (!fixes.length) { + console.log('Nothing to update.'); + return; + } + + if (dryRun) { + console.log(`Dry run: would update ${fixes.length} session(s).`); + return; + } + + const importRes = await fetch(`${AGENTMEMORY_URL}/agentmemory/import`, { + method: 'POST', + headers, + body: JSON.stringify({ + strategy: 'merge', + exportData: { + version: '0.9.21', + sessions: fixes.map((f) => f.session), + memories: [], + summaries: [], + observations: {} + } + }) + }); + + const result = await importRes.json(); + if (!importRes.ok || result.success === false) { + console.error('Import failed:', importRes.status, result); + process.exit(1); + } + + console.log('Import result:', result); + console.log(`Updated ${fixes.length} session(s).`); +} + +main().catch((err) => { + console.error(err); + process.exit(1); +}); From caec665595996c97889780e67a1a1386190e5c3e Mon Sep 17 00:00:00 2001 From: Andrew Date: Sun, 26 Jul 2026 18:26:01 +0800 Subject: [PATCH 02/18] fix(cursor): address CodeRabbit review for hooks and utilities Consolidate shared env/config helpers, harden session cache writes and detached worker payload handoff, validate stale-session CLI args, and remove hardcoded local paths from docs. --- integrations/cursor/README.md | 4 +- integrations/cursor/install-local.mjs | 24 +- plugin/scripts/cursor/agentmemory-lib.mjs | 242 ++++++++++++++++-- .../cursor/agentmemory-post-tool-failure.mjs | 44 +--- .../cursor/agentmemory-post-tool-use.mjs | 62 ++--- .../cursor/agentmemory-pre-compact.mjs | 44 +--- .../cursor/agentmemory-pre-tool-use.mjs | 45 +--- .../cursor/agentmemory-prompt-submit.mjs | 35 +-- .../cursor/agentmemory-session-end.mjs | 124 +++------ .../cursor/agentmemory-session-start.mjs | 43 +--- plugin/scripts/cursor/agentmemory-stop.mjs | 100 ++------ .../cursor/agentmemory-subagent-start.mjs | 34 +-- .../cursor/agentmemory-subagent-stop.mjs | 35 +-- .../cursor/close-stale-am-sessions.mjs | 38 ++- .../cursor/fix-cursor-session-projects.mjs | 39 +-- 15 files changed, 379 insertions(+), 534 deletions(-) diff --git a/integrations/cursor/README.md b/integrations/cursor/README.md index 86cce94276..2ed747bb99 100644 --- a/integrations/cursor/README.md +++ b/integrations/cursor/README.md @@ -16,7 +16,7 @@ node integrations/cursor/verify-flow.mjs Then in Cursor: 1. **Settings → Plugins → Add marketplace** → select the **repo root** - `D:\Andrew\Code\Github\agentmemory` + `` (must contain `.cursor-plugin/marketplace.json`) 2. Enable plugin **agentmemory** 3. **Disable** the old `rohitg00/agentmemory` marketplace entry if both are on @@ -31,7 +31,7 @@ node integrations/cursor/install-local.mjs --clear-user-hooks ## Layout (PR target) -``` +```text agentmemory/ ← marketplace root (git repo) .cursor-plugin/marketplace.json plugin/ diff --git a/integrations/cursor/install-local.mjs b/integrations/cursor/install-local.mjs index 19d4232c7d..a2ff1530f9 100644 --- a/integrations/cursor/install-local.mjs +++ b/integrations/cursor/install-local.mjs @@ -1,5 +1,5 @@ #!/usr/bin/env node -import { copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; +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'; @@ -30,12 +30,21 @@ function loadEnv(path) { function readJson(path) { if (!existsSync(path)) return {}; - return JSON.parse(readFileSync(path, 'utf-8')); + try { + return JSON.parse(readFileSync(path, 'utf-8')); + } catch { + return {}; + } } -function writeJson(path, data) { +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 linkMarketplace() { @@ -62,8 +71,13 @@ function mergeMcp(env) { }, }; const backup = `${MCP_PATH}.bak-${Date.now()}`; - if (existsSync(MCP_PATH)) copyFileSync(MCP_PATH, backup); - writeJson(MCP_PATH, mcp); + if (existsSync(MCP_PATH)) { + copyFileSync(MCP_PATH, backup); + try { + chmodSync(backup, 0o600); + } catch {} + } + writeJson(MCP_PATH, mcp, true); return backup; } diff --git a/plugin/scripts/cursor/agentmemory-lib.mjs b/plugin/scripts/cursor/agentmemory-lib.mjs index ccf7b9c284..2a7f663b12 100644 --- a/plugin/scripts/cursor/agentmemory-lib.mjs +++ b/plugin/scripts/cursor/agentmemory-lib.mjs @@ -1,21 +1,131 @@ #!/usr/bin/env node -import { readFileSync, writeFileSync, existsSync, readdirSync } from 'node:fs'; -import { join, dirname, basename } from 'node:path'; -import { homedir } from 'node:os'; -import { execSync } from 'node:child_process'; +import { + closeSync, + existsSync, + mkdirSync, + openSync, + readFileSync, + renameSync, + readdirSync, + unlinkSync, + writeFileSync +} from 'node:fs'; +import { spawn, execSync } from 'node:child_process'; +import { dirname, join, basename } from 'node:path'; +import { homedir, tmpdir } from 'node:os'; +import { fileURLToPath } from 'node:url'; const HOME = homedir(); const CURSOR_PROJECTS_DIR = join(HOME, '.cursor', 'projects'); const SESSION_CACHE_PATH = join(HOME, '.cursor', 'hooks', '.agentmemory-session-cache.json'); +const ENV_FILE_PATH = join(HOME, '.agentmemory', '.env'); + +let cachedEnvFile = null; + +export function loadAgentmemoryEnv(envPath = ENV_FILE_PATH) { + const out = {}; + if (!existsSync(envPath)) return out; + try { + for (const line of readFileSync(envPath, '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(); + } + } catch {} + return out; +} + +function getEnvFile() { + if (!cachedEnvFile) cachedEnvFile = loadAgentmemoryEnv(); + return cachedEnvFile; +} + +export function getConfigValue(key) { + if (process.env[key] !== undefined && process.env[key] !== '') return process.env[key]; + return getEnvFile()[key]; +} + +export function isConfigEnabled(key) { + return getConfigValue(key) === 'true'; +} + +export function getRestUrl() { + return getConfigValue('AGENTMEMORY_URL') || 'http://localhost:3111'; +} + +export function getSecret() { + return getConfigValue('AGENTMEMORY_SECRET') || ''; +} + +export function authHeaders() { + const h = { 'Content-Type': 'application/json' }; + const secret = getSecret(); + if (secret) h.Authorization = `Bearer ${secret}`; + return h; +} + +export function truncateValue(value, max) { + if (typeof value === 'string') { + if (value.length > max) return `${value.slice(0, max)}\n[...truncated]`; + return value; + } + if (typeof value === 'object' && value !== null) { + const str = JSON.stringify(value); + if (str.length > max) return `${str.slice(0, max)}...[truncated]`; + return str; + } + return value; +} + +export function normalizePathSlashes(value) { + return String(value).replace(/\\/g, '/'); +} + +export function isCursorMetadataPath(value) { + if (!value || typeof value !== 'string') return false; + const trimmed = normalizePathSlashes(value.trim()); + if (trimmed === '.cursor') return true; + return /(^|\/)\.cursor(\/|$)/.test(trimmed); +} function isBadPath(value) { if (!value || typeof value !== 'string') return true; - const trimmed = value.trim(); + const trimmed = normalizePathSlashes(value.trim()); if (!trimmed || trimmed === '/' || trimmed === '.') return true; - if (trimmed === '.cursor' || trimmed.endsWith('/.cursor')) return true; + if (isCursorMetadataPath(trimmed)) return true; return false; } +function sleepMs(ms) { + const end = Date.now() + ms; + while (Date.now() < end) {} +} + +function withSessionCacheLock(fn) { + const lockPath = `${SESSION_CACHE_PATH}.lock`; + mkdirSync(dirname(SESSION_CACHE_PATH), { recursive: true }); + let fd; + for (let i = 0; i < 50; i++) { + try { + fd = openSync(lockPath, 'wx'); + break; + } catch { + sleepMs(10); + } + } + if (!fd) return; + try { + return fn(); + } finally { + closeSync(fd); + try { + unlinkSync(lockPath); + } catch {} + } +} + function loadSessionCache() { try { return JSON.parse(readFileSync(SESSION_CACHE_PATH, 'utf-8')); @@ -26,11 +136,15 @@ function loadSessionCache() { function rememberSession(sessionId, project, cwd) { if (!sessionId || !project || project === '.cursor') return; - try { - const cache = loadSessionCache(); - cache[sessionId] = { project, cwd, updatedAt: new Date().toISOString() }; - writeFileSync(SESSION_CACHE_PATH, JSON.stringify(cache, null, 2)); - } catch {} + withSessionCacheLock(() => { + try { + const cache = loadSessionCache(); + cache[sessionId] = { project, cwd, updatedAt: new Date().toISOString() }; + const tmp = `${SESSION_CACHE_PATH}.${process.pid}.${Date.now()}.tmp`; + writeFileSync(tmp, JSON.stringify(cache, null, 2)); + renameSync(tmp, SESSION_CACHE_PATH); + } catch {} + }); } function recallSession(sessionId) { @@ -39,9 +153,16 @@ function recallSession(sessionId) { return cache[sessionId] || null; } +function pathUnderHome(value) { + if (typeof value !== 'string') return false; + const homeNorm = normalizePathSlashes(HOME); + const valueNorm = normalizePathSlashes(value); + return value.startsWith(HOME) || valueNorm.startsWith(homeNorm); +} + function collectPathStrings(value, out = []) { if (typeof value === 'string') { - if (value.startsWith(HOME) && !value.includes('/.cursor/')) out.push(value); + if (pathUnderHome(value) && !isCursorMetadataPath(value)) out.push(value); return out; } if (Array.isArray(value)) { @@ -72,14 +193,12 @@ function gitRootFromPath(targetPath) { } function cleanRepoName(dirPath) { - const normalized = String(dirPath || '').replace(/\\/g, '/').replace(/\/+$/, ''); + const normalized = normalizePathSlashes(dirPath).replace(/\/+$/, ''); if (!normalized) return 'unknown-project'; - // Claude/Cursor worktrees: ...//.claude/worktrees/agent-xxx -> const claudeWt = normalized.match(/^(.*?)\/\.claude\/worktrees\/[^/]+$/i); if (claudeWt?.[1]) return cleanRepoName(claudeWt[1]); - // Generic git worktree folder named agent- const baseName = basename(normalized); if (/^agent-[a-f0-9]{6,}$/i.test(baseName)) { const parent = dirname(normalized); @@ -89,7 +208,6 @@ function cleanRepoName(dirPath) { } let name = baseName.replace(/(-worktree-\d+|-worktree|-[a-f0-9]{7,40})$/i, ''); - // Known local variant folders that should share one memory bucket if (/^pxread-/i.test(name)) return 'pxread'; return name || 'unknown-project'; } @@ -166,13 +284,13 @@ function findSessionTranscript(sessionId) { function workspaceFromTranscriptFile(transcriptFile) { if (!transcriptFile || !existsSync(transcriptFile)) return null; - const chunk = readFileSync(transcriptFile, 'utf-8').slice(0, 250000); - const escapedHome = HOME.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); - const re = new RegExp(`${escapedHome}/[^\\s"'\\\\]+`, 'g'); + const chunk = normalizePathSlashes(readFileSync(transcriptFile, 'utf-8').slice(0, 250000)); + const escapedHome = normalizePathSlashes(HOME).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + const re = new RegExp(`${escapedHome}[^\\s"'\\\\]+`, 'g'); const counts = new Map(); for (const match of chunk.match(re) || []) { - if (match.includes('/.cursor/')) continue; + if (isCursorMetadataPath(match)) continue; const existing = existingAncestor(match); if (!existing || existing === HOME) continue; counts.set(existing, (counts.get(existing) || 0) + 1); @@ -202,6 +320,90 @@ function workspaceFromSessionId(sessionId) { return pickBestCandidate(candidates, preferredLabel); } +export function readHookStdinComplete(maxWaitMs = 30000) { + return new Promise((resolve) => { + let input = ''; + let done = false; + const finish = () => { + if (done) return; + done = true; + try { + process.stdin.destroy(); + } catch {} + resolve(input); + }; + const t = setTimeout(finish, maxWaitMs); + if (t.unref) t.unref(); + process.stdin.on('data', (c) => { + input += c; + }); + process.stdin.on('end', () => { + clearTimeout(t); + finish(); + }); + process.stdin.on('error', () => { + clearTimeout(t); + finish(); + }); + }); +} + +export function writeHookPayloadTemp(input) { + const path = join(tmpdir(), `am-hook-${process.pid}-${Date.now()}.json`); + writeFileSync(path, input, 'utf-8'); + return path; +} + +export function readWorkerHookPayload() { + const file = process.env.AM_HOOK_INPUT_FILE; + if (!file) { + console.error('[agentmemory] missing AM_HOOK_INPUT_FILE in worker'); + return null; + } + try { + const raw = readFileSync(file, 'utf-8'); + return JSON.parse(raw); + } catch (err) { + console.error('[agentmemory] failed to parse hook payload:', err.message); + return null; + } finally { + try { + unlinkSync(file); + } catch {} + } +} + +export function spawnDetachedHookWorker(scriptUrl, input) { + const payloadFile = writeHookPayloadTemp(input); + const child = spawn(process.execPath, [fileURLToPath(scriptUrl)], { + detached: true, + stdio: 'ignore', + windowsHide: true, + env: { + ...process.env, + AM_HOOK_WORKER: '1', + AM_HOOK_INPUT_FILE: payloadFile + } + }); + child.unref(); + + const bail = setTimeout(() => process.exit(0), 2000); + if (bail.unref) bail.unref(); + child.on('spawn', () => process.exit(0)); + child.on('error', (err) => { + console.error('[agentmemory] failed to spawn hook worker:', err.message); + try { + unlinkSync(payloadFile); + } catch {} + process.exit(0); + }); +} + +export async function runDetachedHookParent(scriptUrl) { + const input = await readHookStdinComplete(); + spawnDetachedHookWorker(scriptUrl, input); +} + export function resolveWorkspace(data) { const sessionId = data?.session_id; const cached = recallSession(sessionId); diff --git a/plugin/scripts/cursor/agentmemory-post-tool-failure.mjs b/plugin/scripts/cursor/agentmemory-post-tool-failure.mjs index 3ca6e56114..43dd5b8260 100644 --- a/plugin/scripts/cursor/agentmemory-post-tool-failure.mjs +++ b/plugin/scripts/cursor/agentmemory-post-tool-failure.mjs @@ -1,35 +1,10 @@ #!/usr/bin/env node -import { readFileSync, existsSync } from 'node:fs'; -import { join } from 'node:path'; -import { homedir } from 'node:os'; -import { resolveWorkspace } from './agentmemory-lib.mjs'; - -const config = {}; -const envPath = join(homedir(), '.agentmemory', '.env'); -if (existsSync(envPath)) { - const content = readFileSync(envPath, 'utf-8'); - for (const line of content.split('\n')) { - const trimmed = line.trim(); - if (trimmed && !trimmed.startsWith('#')) { - const idx = trimmed.indexOf('='); - if (idx !== -1) { - const key = trimmed.slice(0, idx).trim(); - const val = trimmed.slice(idx + 1).trim(); - config[key] = val; - } - } - } -} - -const REST_URL = process.env.AGENTMEMORY_URL || config.AGENTMEMORY_URL || 'http://localhost:3111'; -const SECRET = process.env.AGENTMEMORY_SECRET || config.AGENTMEMORY_SECRET || ''; - -function authHeaders() { - const h = { 'Content-Type': 'application/json' }; - if (SECRET) h['Authorization'] = `Bearer ${SECRET}`; - return h; -} - +import { + authHeaders, + getRestUrl, + resolveWorkspace, + truncateValue +} from './agentmemory-lib.mjs'; async function main() { let input = ''; @@ -44,7 +19,7 @@ async function main() { const sessionId = data.session_id || 'unknown'; const { project, cwd } = resolveWorkspace(data); try { - await fetch(`${REST_URL}/agentmemory/observe`, { + await fetch(`${getRestUrl()}/agentmemory/observe`, { method: 'POST', headers: authHeaders(), body: JSON.stringify({ @@ -55,12 +30,13 @@ async function main() { timestamp: new Date().toISOString(), data: { tool_name: data.tool_name, - tool_input: typeof data.tool_input === 'string' ? data.tool_input.slice(0, 4000) : JSON.stringify(data.tool_input ?? '').slice(0, 4000), - error: typeof data.error === 'string' ? data.error.slice(0, 4000) : JSON.stringify(data.error ?? '').slice(0, 4000) + tool_input: truncateValue(data.tool_input, 4000), + error: truncateValue(data.error, 4000) } }), signal: AbortSignal.timeout(3000) }); } catch {} } + main(); diff --git a/plugin/scripts/cursor/agentmemory-post-tool-use.mjs b/plugin/scripts/cursor/agentmemory-post-tool-use.mjs index f0f09c320a..1fe8fe7348 100644 --- a/plugin/scripts/cursor/agentmemory-post-tool-use.mjs +++ b/plugin/scripts/cursor/agentmemory-post-tool-use.mjs @@ -1,35 +1,10 @@ #!/usr/bin/env node -import { readFileSync, existsSync } from 'node:fs'; -import { join } from 'node:path'; -import { homedir } from 'node:os'; -import { resolveWorkspace } from './agentmemory-lib.mjs'; - -const config = {}; -const envPath = join(homedir(), '.agentmemory', '.env'); -if (existsSync(envPath)) { - const content = readFileSync(envPath, 'utf-8'); - for (const line of content.split('\n')) { - const trimmed = line.trim(); - if (trimmed && !trimmed.startsWith('#')) { - const idx = trimmed.indexOf('='); - if (idx !== -1) { - const key = trimmed.slice(0, idx).trim(); - const val = trimmed.slice(idx + 1).trim(); - config[key] = val; - } - } - } -} - -const REST_URL = process.env.AGENTMEMORY_URL || config.AGENTMEMORY_URL || 'http://localhost:3111'; -const SECRET = process.env.AGENTMEMORY_SECRET || config.AGENTMEMORY_SECRET || ''; - -function authHeaders() { - const h = { 'Content-Type': 'application/json' }; - if (SECRET) h['Authorization'] = `Bearer ${SECRET}`; - return h; -} - +import { + authHeaders, + getRestUrl, + resolveWorkspace, + truncateValue +} from './agentmemory-lib.mjs'; async function main() { let input = ''; @@ -44,7 +19,7 @@ async function main() { const { project, cwd } = resolveWorkspace(data); const { imageData, cleanOutput } = extractImageData(data.tool_response ?? data.tool_output); try { - await fetch(`${REST_URL}/agentmemory/observe`, { + await fetch(`${getRestUrl()}/agentmemory/observe`, { method: 'POST', headers: authHeaders(), body: JSON.stringify({ @@ -55,8 +30,8 @@ async function main() { timestamp: new Date().toISOString(), data: { tool_name: data.tool_name, - tool_input: data.tool_input, - tool_output: truncate(cleanOutput, 8000), + tool_input: truncateValue(data.tool_input, 4000), + tool_output: truncateValue(cleanOutput, 8000), ...imageData ? { image_data: imageData } : {} } }), @@ -70,10 +45,12 @@ function isBase64Image(val) { } function extractImageData(output) { - if (isBase64Image(output)) return { - imageData: output, - cleanOutput: '[image data extracted]' - }; + if (isBase64Image(output)) { + return { + imageData: output, + cleanOutput: '[image data extracted]' + }; + } if (typeof output === 'object' && output !== null && !Array.isArray(output)) { const obj = output; let imageData; @@ -97,13 +74,4 @@ function extractImageData(output) { }; } -function truncate(value, max) { - if (typeof value === 'string' && value.length > max) return value.slice(0, max) + '\n[...truncated]'; - if (typeof value === 'object' && value !== null) { - const str = JSON.stringify(value); - if (str.length > max) return str.slice(0, max) + '...[truncated]'; - return value; - } - return value; -} main(); diff --git a/plugin/scripts/cursor/agentmemory-pre-compact.mjs b/plugin/scripts/cursor/agentmemory-pre-compact.mjs index 120eb22268..a599d674da 100644 --- a/plugin/scripts/cursor/agentmemory-pre-compact.mjs +++ b/plugin/scripts/cursor/agentmemory-pre-compact.mjs @@ -1,35 +1,10 @@ #!/usr/bin/env node -import { readFileSync, existsSync } from 'node:fs'; -import { join } from 'node:path'; -import { homedir } from 'node:os'; -import { resolveWorkspace } from './agentmemory-lib.mjs'; - -const config = {}; -const envPath = join(homedir(), '.agentmemory', '.env'); -if (existsSync(envPath)) { - const content = readFileSync(envPath, 'utf-8'); - for (const line of content.split('\n')) { - const trimmed = line.trim(); - if (trimmed && !trimmed.startsWith('#')) { - const idx = trimmed.indexOf('='); - if (idx !== -1) { - const key = trimmed.slice(0, idx).trim(); - const val = trimmed.slice(idx + 1).trim(); - config[key] = val; - } - } - } -} - -const REST_URL = process.env.AGENTMEMORY_URL || config.AGENTMEMORY_URL || 'http://localhost:3111'; -const SECRET = process.env.AGENTMEMORY_SECRET || config.AGENTMEMORY_SECRET || ''; - -function authHeaders() { - const h = { 'Content-Type': 'application/json' }; - if (SECRET) h['Authorization'] = `Bearer ${SECRET}`; - return h; -} - +import { + authHeaders, + getRestUrl, + isConfigEnabled, + resolveWorkspace +} from './agentmemory-lib.mjs'; async function main() { let input = ''; @@ -42,9 +17,9 @@ async function main() { } const sessionId = data.session_id || 'unknown'; const { project, cwd } = resolveWorkspace(data); - if (process.env.CLAUDE_MEMORY_BRIDGE === 'true' || config.CLAUDE_MEMORY_BRIDGE === 'true') { + if (isConfigEnabled('CLAUDE_MEMORY_BRIDGE')) { try { - await fetch(`${REST_URL}/agentmemory/claude-bridge/sync`, { + await fetch(`${getRestUrl()}/agentmemory/claude-bridge/sync`, { method: 'POST', headers: authHeaders(), body: JSON.stringify({}), @@ -53,7 +28,7 @@ async function main() { } catch {} } try { - const res = await fetch(`${REST_URL}/agentmemory/context`, { + const res = await fetch(`${getRestUrl()}/agentmemory/context`, { method: 'POST', headers: authHeaders(), body: JSON.stringify({ @@ -73,4 +48,5 @@ async function main() { } } catch {} } + main(); diff --git a/plugin/scripts/cursor/agentmemory-pre-tool-use.mjs b/plugin/scripts/cursor/agentmemory-pre-tool-use.mjs index 6952596f4f..4b33e64839 100644 --- a/plugin/scripts/cursor/agentmemory-pre-tool-use.mjs +++ b/plugin/scripts/cursor/agentmemory-pre-tool-use.mjs @@ -1,39 +1,13 @@ #!/usr/bin/env node -import { readFileSync, existsSync } from 'node:fs'; -import { join } from 'node:path'; -import { homedir } from 'node:os'; -import { resolveWorkspace } from './agentmemory-lib.mjs'; - -const config = {}; -const envPath = join(homedir(), '.agentmemory', '.env'); -if (existsSync(envPath)) { - const content = readFileSync(envPath, 'utf-8'); - for (const line of content.split('\n')) { - const trimmed = line.trim(); - if (trimmed && !trimmed.startsWith('#')) { - const idx = trimmed.indexOf('='); - if (idx !== -1) { - const key = trimmed.slice(0, idx).trim(); - const val = trimmed.slice(idx + 1).trim(); - config[key] = val; - } - } - } -} - -const INJECT_CONTEXT = process.env.AGENTMEMORY_INJECT_CONTEXT === 'true' || config.AGENTMEMORY_INJECT_CONTEXT === 'true'; -const REST_URL = process.env.AGENTMEMORY_URL || config.AGENTMEMORY_URL || 'http://localhost:3111'; -const SECRET = process.env.AGENTMEMORY_SECRET || config.AGENTMEMORY_SECRET || ''; - -function authHeaders() { - const h = { 'Content-Type': 'application/json' }; - if (SECRET) h['Authorization'] = `Bearer ${SECRET}`; - return h; -} - +import { + authHeaders, + getRestUrl, + isConfigEnabled, + resolveWorkspace +} from './agentmemory-lib.mjs'; async function main() { - if (!INJECT_CONTEXT) return; + if (!isConfigEnabled('AGENTMEMORY_INJECT_CONTEXT')) return; let input = ''; for await (const chunk of process.stdin) input += chunk; let data; @@ -58,13 +32,13 @@ async function main() { const terms = []; if (toolName === 'Grep' || toolName === 'Glob') { - const pattern = toolInput['pattern']; + const pattern = toolInput.pattern; if (typeof pattern === 'string' && pattern.length > 0) terms.push(pattern); } const sessionId = data.session_id || 'unknown'; const { project, cwd } = resolveWorkspace(data); try { - const res = await fetch(`${REST_URL}/agentmemory/enrich`, { + const res = await fetch(`${getRestUrl()}/agentmemory/enrich`, { method: 'POST', headers: authHeaders(), body: JSON.stringify({ @@ -86,4 +60,5 @@ async function main() { } } catch {} } + main(); diff --git a/plugin/scripts/cursor/agentmemory-prompt-submit.mjs b/plugin/scripts/cursor/agentmemory-prompt-submit.mjs index f5fe2ceb61..a27b5dfaa6 100644 --- a/plugin/scripts/cursor/agentmemory-prompt-submit.mjs +++ b/plugin/scripts/cursor/agentmemory-prompt-submit.mjs @@ -1,35 +1,5 @@ #!/usr/bin/env node -import { readFileSync, existsSync } from 'node:fs'; -import { join } from 'node:path'; -import { homedir } from 'node:os'; -import { resolveWorkspace } from './agentmemory-lib.mjs'; - -const config = {}; -const envPath = join(homedir(), '.agentmemory', '.env'); -if (existsSync(envPath)) { - const content = readFileSync(envPath, 'utf-8'); - for (const line of content.split('\n')) { - const trimmed = line.trim(); - if (trimmed && !trimmed.startsWith('#')) { - const idx = trimmed.indexOf('='); - if (idx !== -1) { - const key = trimmed.slice(0, idx).trim(); - const val = trimmed.slice(idx + 1).trim(); - config[key] = val; - } - } - } -} - -const REST_URL = process.env.AGENTMEMORY_URL || config.AGENTMEMORY_URL || 'http://localhost:3111'; -const SECRET = process.env.AGENTMEMORY_SECRET || config.AGENTMEMORY_SECRET || ''; - -function authHeaders() { - const h = { 'Content-Type': 'application/json' }; - if (SECRET) h['Authorization'] = `Bearer ${SECRET}`; - return h; -} - +import { authHeaders, getRestUrl, resolveWorkspace } from './agentmemory-lib.mjs'; async function main() { let input = ''; @@ -43,7 +13,7 @@ async function main() { const sessionId = data.session_id || 'unknown'; const { project, cwd } = resolveWorkspace(data); try { - await fetch(`${REST_URL}/agentmemory/observe`, { + await fetch(`${getRestUrl()}/agentmemory/observe`, { method: 'POST', headers: authHeaders(), body: JSON.stringify({ @@ -58,4 +28,5 @@ async function main() { }); } catch {} } + main(); diff --git a/plugin/scripts/cursor/agentmemory-session-end.mjs b/plugin/scripts/cursor/agentmemory-session-end.mjs index 2d8a70b61c..b7a20d2eb3 100644 --- a/plugin/scripts/cursor/agentmemory-session-end.mjs +++ b/plugin/scripts/cursor/agentmemory-session-end.mjs @@ -1,143 +1,79 @@ #!/usr/bin/env node -import { readFileSync, existsSync } from 'node:fs'; -import { join } from 'node:path'; -import { homedir } from 'node:os'; -import { spawn } from 'node:child_process'; -import { fileURLToPath } from 'node:url'; -import { resolveWorkspace } from './agentmemory-lib.mjs'; +import { + authHeaders, + getRestUrl, + isConfigEnabled, + readWorkerHookPayload, + resolveWorkspace, + runDetachedHookParent +} from './agentmemory-lib.mjs'; -// Runs in two modes: -// parent -> reads stdin, spawns a DETACHED background worker, exits immediately -// so Cursor never waits on this hook when closing / switching workspace. -// worker -> performs the (possibly slow, remote) memory calls, then force-exits. -// A hard watchdog guarantees the process always terminates -> no leftover node. const IS_WORKER = process.env.AM_HOOK_WORKER === '1'; -const config = {}; -const envPath = join(homedir(), '.agentmemory', '.env'); -if (existsSync(envPath)) { - const content = readFileSync(envPath, 'utf-8'); - for (const line of content.split('\n')) { - const trimmed = line.trim(); - if (trimmed && !trimmed.startsWith('#')) { - const idx = trimmed.indexOf('='); - if (idx !== -1) { - const key = trimmed.slice(0, idx).trim(); - const val = trimmed.slice(idx + 1).trim(); - config[key] = val; - } - } - } -} - -const REST_URL = process.env.AGENTMEMORY_URL || config.AGENTMEMORY_URL || 'http://localhost:3111'; -const SECRET = process.env.AGENTMEMORY_SECRET || config.AGENTMEMORY_SECRET || ''; - -function authHeaders() { - const h = { 'Content-Type': 'application/json' }; - if (SECRET) h['Authorization'] = `Bearer ${SECRET}`; - return h; -} - -// ---- worker mode: do the actual (slow) work, then guarantee self-termination ---- async function runWorker() { - // Absolute backstop: even if a request wedges past its own AbortSignal, the - // worker is force-killed. Slightly above the sum of per-request timeouts below. const HARD_LIMIT_MS = 250000; const watchdog = setTimeout(() => process.exit(0), HARD_LIMIT_MS); try { - let data; - try { - data = JSON.parse(process.env.AM_HOOK_INPUT || '{}'); - } catch { - data = {}; - } + const data = readWorkerHookPayload(); + if (!data) return; + const sessionId = data.session_id || 'unknown'; const { project } = resolveWorkspace(data); try { - await fetch(`${REST_URL}/agentmemory/session/end`, { + await fetch(`${getRestUrl()}/agentmemory/session/end`, { method: 'POST', headers: authHeaders(), body: JSON.stringify({ sessionId, project }), signal: AbortSignal.timeout(30000) }); - } catch {} + } catch (err) { + console.error('[agentmemory] session/end failed:', err.message); + } - if (process.env.CONSOLIDATION_ENABLED === 'true' || config.CONSOLIDATION_ENABLED === 'true') { + if (isConfigEnabled('CONSOLIDATION_ENABLED')) { try { - await fetch(`${REST_URL}/agentmemory/crystals/auto`, { + await fetch(`${getRestUrl()}/agentmemory/crystals/auto`, { method: 'POST', headers: authHeaders(), body: JSON.stringify({ olderThanDays: 0, project }), signal: AbortSignal.timeout(60000) }); - } catch {} + } catch (err) { + console.error('[agentmemory] crystals/auto failed:', err.message); + } try { - await fetch(`${REST_URL}/agentmemory/consolidate-pipeline`, { + await fetch(`${getRestUrl()}/agentmemory/consolidate-pipeline`, { method: 'POST', headers: authHeaders(), body: JSON.stringify({ tier: 'all', force: true, project }), signal: AbortSignal.timeout(120000) }); - } catch {} + } catch (err) { + console.error('[agentmemory] consolidate-pipeline failed:', err.message); + } } - if (process.env.CLAUDE_MEMORY_BRIDGE === 'true' || config.CLAUDE_MEMORY_BRIDGE === 'true') { + if (isConfigEnabled('CLAUDE_MEMORY_BRIDGE')) { try { - await fetch(`${REST_URL}/agentmemory/claude-bridge/sync`, { + await fetch(`${getRestUrl()}/agentmemory/claude-bridge/sync`, { method: 'POST', headers: authHeaders(), signal: AbortSignal.timeout(30000) }); - } catch {} + } catch (err) { + console.error('[agentmemory] claude-bridge/sync failed:', err.message); + } } } finally { clearTimeout(watchdog); - // Force exit so undici's keep-alive socket pool cannot keep the process alive. process.exit(0); } } -// ---- parent mode: capture stdin, hand off to detached worker, exit fast ---- -function readStdin(timeoutMs) { - return new Promise((resolve) => { - let input = ''; - let done = false; - const finish = () => { - if (done) return; - done = true; - try { process.stdin.destroy(); } catch {} - resolve(input); - }; - const t = setTimeout(finish, timeoutMs); - if (t.unref) t.unref(); - process.stdin.on('data', (c) => { input += c; }); - process.stdin.on('end', () => { clearTimeout(t); finish(); }); - process.stdin.on('error', () => { clearTimeout(t); finish(); }); - }); -} - -async function runParent() { - const input = await readStdin(1500); - - const child = spawn(process.execPath, [fileURLToPath(import.meta.url)], { - detached: true, - stdio: 'ignore', - windowsHide: true, - env: { ...process.env, AM_HOOK_WORKER: '1', AM_HOOK_INPUT: input } - }); - child.unref(); - - const bail = setTimeout(() => process.exit(0), 2000); - if (bail.unref) bail.unref(); - child.on('spawn', () => process.exit(0)); - child.on('error', () => process.exit(0)); -} - if (IS_WORKER) { runWorker(); } else { - runParent(); + runDetachedHookParent(import.meta.url); } diff --git a/plugin/scripts/cursor/agentmemory-session-start.mjs b/plugin/scripts/cursor/agentmemory-session-start.mjs index 5c629d9846..9acf4892a5 100644 --- a/plugin/scripts/cursor/agentmemory-session-start.mjs +++ b/plugin/scripts/cursor/agentmemory-session-start.mjs @@ -1,40 +1,14 @@ #!/usr/bin/env node -import { readFileSync, existsSync } from 'node:fs'; -import { join } from 'node:path'; -import { homedir } from 'node:os'; -import { resolveWorkspace } from './agentmemory-lib.mjs'; +import { + authHeaders, + getRestUrl, + isConfigEnabled, + resolveWorkspace +} from './agentmemory-lib.mjs'; -// Load config from ~/.agentmemory/.env -const config = {}; -const envPath = join(homedir(), '.agentmemory', '.env'); -if (existsSync(envPath)) { - const content = readFileSync(envPath, 'utf-8'); - for (const line of content.split('\n')) { - const trimmed = line.trim(); - if (trimmed && !trimmed.startsWith('#')) { - const idx = trimmed.indexOf('='); - if (idx !== -1) { - const key = trimmed.slice(0, idx).trim(); - const val = trimmed.slice(idx + 1).trim(); - config[key] = val; - } - } - } -} - -const INJECT_CONTEXT = process.env.AGENTMEMORY_INJECT_CONTEXT === 'true' || config.AGENTMEMORY_INJECT_CONTEXT === 'true'; -const REST_URL = process.env.AGENTMEMORY_URL || config.AGENTMEMORY_URL || 'http://localhost:3111'; -const SECRET = process.env.AGENTMEMORY_SECRET || config.AGENTMEMORY_SECRET || ''; const INJECT_TIMEOUT_MS = 2500; const REGISTER_TIMEOUT_MS = 1500; -function authHeaders() { - const h = { 'Content-Type': 'application/json' }; - if (SECRET) h['Authorization'] = `Bearer ${SECRET}`; - return h; -} - - async function main() { let input = ''; for await (const chunk of process.stdin) input += chunk; @@ -46,7 +20,7 @@ async function main() { } const sessionId = data.session_id || `ses_${Date.now().toString(36)}`; const { project, cwd } = resolveWorkspace(data); - const url = `${REST_URL}/agentmemory/session/start`; + const url = `${getRestUrl()}/agentmemory/session/start`; const init = { method: 'POST', headers: authHeaders(), @@ -56,7 +30,7 @@ async function main() { cwd }) }; - if (!INJECT_CONTEXT) { + if (!isConfigEnabled('AGENTMEMORY_INJECT_CONTEXT')) { try { await fetch(url, { ...init, @@ -80,4 +54,5 @@ async function main() { } } catch {} } + main(); diff --git a/plugin/scripts/cursor/agentmemory-stop.mjs b/plugin/scripts/cursor/agentmemory-stop.mjs index 7f4601274d..dd6422c7d0 100644 --- a/plugin/scripts/cursor/agentmemory-stop.mjs +++ b/plugin/scripts/cursor/agentmemory-stop.mjs @@ -1,113 +1,43 @@ #!/usr/bin/env node -import { readFileSync, existsSync } from 'node:fs'; -import { join } from 'node:path'; -import { homedir } from 'node:os'; -import { spawn } from 'node:child_process'; -import { fileURLToPath } from 'node:url'; -import { resolveWorkspace } from './agentmemory-lib.mjs'; +import { + authHeaders, + getRestUrl, + readWorkerHookPayload, + resolveWorkspace, + runDetachedHookParent +} from './agentmemory-lib.mjs'; -// Runs in two modes: -// parent -> reads stdin, spawns a DETACHED background worker, exits immediately -// so Cursor never waits on this hook at the end of a response. -// worker -> performs the (possibly slow, remote) summarize call, then force-exits. -// A hard watchdog guarantees the process always terminates -> no leftover node. const IS_WORKER = process.env.AM_HOOK_WORKER === '1'; -const config = {}; -const envPath = join(homedir(), '.agentmemory', '.env'); -if (existsSync(envPath)) { - const content = readFileSync(envPath, 'utf-8'); - for (const line of content.split('\n')) { - const trimmed = line.trim(); - if (trimmed && !trimmed.startsWith('#')) { - const idx = trimmed.indexOf('='); - if (idx !== -1) { - const key = trimmed.slice(0, idx).trim(); - const val = trimmed.slice(idx + 1).trim(); - config[key] = val; - } - } - } -} - -const REST_URL = process.env.AGENTMEMORY_URL || config.AGENTMEMORY_URL || 'http://localhost:3111'; -const SECRET = process.env.AGENTMEMORY_SECRET || config.AGENTMEMORY_SECRET || ''; - -function authHeaders() { - const h = { 'Content-Type': 'application/json' }; - if (SECRET) h['Authorization'] = `Bearer ${SECRET}`; - return h; -} - -// ---- worker mode: do the actual (slow) work, then guarantee self-termination ---- async function runWorker() { - // Absolute backstop: even if the request wedges past its AbortSignal, force-kill. const HARD_LIMIT_MS = 130000; const watchdog = setTimeout(() => process.exit(0), HARD_LIMIT_MS); try { - let data; - try { - data = JSON.parse(process.env.AM_HOOK_INPUT || '{}'); - } catch { - data = {}; - } + const data = readWorkerHookPayload(); + if (!data) return; + const sessionId = data.session_id || 'unknown'; const { project } = resolveWorkspace(data); try { - await fetch(`${REST_URL}/agentmemory/summarize`, { + await fetch(`${getRestUrl()}/agentmemory/summarize`, { method: 'POST', headers: authHeaders(), body: JSON.stringify({ sessionId, project }), signal: AbortSignal.timeout(120000) }); - } catch {} + } catch (err) { + console.error('[agentmemory] summarize failed:', err.message); + } } finally { clearTimeout(watchdog); - // Force exit so undici's keep-alive socket pool cannot keep the process alive. process.exit(0); } } -// ---- parent mode: capture stdin, hand off to detached worker, exit fast ---- -function readStdin(timeoutMs) { - return new Promise((resolve) => { - let input = ''; - let done = false; - const finish = () => { - if (done) return; - done = true; - try { process.stdin.destroy(); } catch {} - resolve(input); - }; - const t = setTimeout(finish, timeoutMs); - if (t.unref) t.unref(); - process.stdin.on('data', (c) => { input += c; }); - process.stdin.on('end', () => { clearTimeout(t); finish(); }); - process.stdin.on('error', () => { clearTimeout(t); finish(); }); - }); -} - -async function runParent() { - const input = await readStdin(1500); - - const child = spawn(process.execPath, [fileURLToPath(import.meta.url)], { - detached: true, - stdio: 'ignore', - windowsHide: true, - env: { ...process.env, AM_HOOK_WORKER: '1', AM_HOOK_INPUT: input } - }); - child.unref(); - - const bail = setTimeout(() => process.exit(0), 2000); - if (bail.unref) bail.unref(); - child.on('spawn', () => process.exit(0)); - child.on('error', () => process.exit(0)); -} - if (IS_WORKER) { runWorker(); } else { - runParent(); + runDetachedHookParent(import.meta.url); } diff --git a/plugin/scripts/cursor/agentmemory-subagent-start.mjs b/plugin/scripts/cursor/agentmemory-subagent-start.mjs index 2cbacb262d..7c3e1f9fec 100644 --- a/plugin/scripts/cursor/agentmemory-subagent-start.mjs +++ b/plugin/scripts/cursor/agentmemory-subagent-start.mjs @@ -1,37 +1,8 @@ #!/usr/bin/env node -import { readFileSync, existsSync } from 'node:fs'; -import { join } from 'node:path'; -import { homedir } from 'node:os'; -import { resolveWorkspace } from './agentmemory-lib.mjs'; +import { authHeaders, getRestUrl, resolveWorkspace } from './agentmemory-lib.mjs'; -const config = {}; -const envPath = join(homedir(), '.agentmemory', '.env'); -if (existsSync(envPath)) { - const content = readFileSync(envPath, 'utf-8'); - for (const line of content.split('\n')) { - const trimmed = line.trim(); - if (trimmed && !trimmed.startsWith('#')) { - const idx = trimmed.indexOf('='); - if (idx !== -1) { - const key = trimmed.slice(0, idx).trim(); - const val = trimmed.slice(idx + 1).trim(); - config[key] = val; - } - } - } -} - -const REST_URL = process.env.AGENTMEMORY_URL || config.AGENTMEMORY_URL || 'http://localhost:3111'; -const SECRET = process.env.AGENTMEMORY_SECRET || config.AGENTMEMORY_SECRET || ''; const TIMEOUT_MS = 800; -function authHeaders() { - const h = { 'Content-Type': 'application/json' }; - if (SECRET) h['Authorization'] = `Bearer ${SECRET}`; - return h; -} - - async function main() { let input = ''; for await (const chunk of process.stdin) input += chunk; @@ -43,7 +14,7 @@ async function main() { } const sessionId = data.session_id || 'unknown'; const { project, cwd } = resolveWorkspace(data); - fetch(`${REST_URL}/agentmemory/observe`, { + fetch(`${getRestUrl()}/agentmemory/observe`, { method: 'POST', headers: authHeaders(), body: JSON.stringify({ @@ -60,4 +31,5 @@ async function main() { signal: AbortSignal.timeout(TIMEOUT_MS) }).catch(() => {}); } + main(); diff --git a/plugin/scripts/cursor/agentmemory-subagent-stop.mjs b/plugin/scripts/cursor/agentmemory-subagent-stop.mjs index c3ebb7661f..0807a562ae 100644 --- a/plugin/scripts/cursor/agentmemory-subagent-stop.mjs +++ b/plugin/scripts/cursor/agentmemory-subagent-stop.mjs @@ -1,35 +1,5 @@ #!/usr/bin/env node -import { readFileSync, existsSync } from 'node:fs'; -import { join } from 'node:path'; -import { homedir } from 'node:os'; -import { resolveWorkspace } from './agentmemory-lib.mjs'; - -const config = {}; -const envPath = join(homedir(), '.agentmemory', '.env'); -if (existsSync(envPath)) { - const content = readFileSync(envPath, 'utf-8'); - for (const line of content.split('\n')) { - const trimmed = line.trim(); - if (trimmed && !trimmed.startsWith('#')) { - const idx = trimmed.indexOf('='); - if (idx !== -1) { - const key = trimmed.slice(0, idx).trim(); - const val = trimmed.slice(idx + 1).trim(); - config[key] = val; - } - } - } -} - -const REST_URL = process.env.AGENTMEMORY_URL || config.AGENTMEMORY_URL || 'http://localhost:3111'; -const SECRET = process.env.AGENTMEMORY_SECRET || config.AGENTMEMORY_SECRET || ''; - -function authHeaders() { - const h = { 'Content-Type': 'application/json' }; - if (SECRET) h['Authorization'] = `Bearer ${SECRET}`; - return h; -} - +import { authHeaders, getRestUrl, resolveWorkspace } from './agentmemory-lib.mjs'; async function main() { let input = ''; @@ -44,7 +14,7 @@ async function main() { const { project, cwd } = resolveWorkspace(data); const lastMsg = typeof data.last_assistant_message === 'string' ? data.last_assistant_message.slice(0, 4000) : ''; try { - await fetch(`${REST_URL}/agentmemory/observe`, { + await fetch(`${getRestUrl()}/agentmemory/observe`, { method: 'POST', headers: authHeaders(), body: JSON.stringify({ @@ -63,4 +33,5 @@ async function main() { }); } catch {} } + main(); diff --git a/plugin/scripts/cursor/close-stale-am-sessions.mjs b/plugin/scripts/cursor/close-stale-am-sessions.mjs index d1f6ddd86b..ee9ffb176b 100644 --- a/plugin/scripts/cursor/close-stale-am-sessions.mjs +++ b/plugin/scripts/cursor/close-stale-am-sessions.mjs @@ -8,22 +8,7 @@ * node close-stale-am-sessions.mjs --min-age-hours 6 --project 智能报表-wrenai * node close-stale-am-sessions.mjs --exclude ses_abc123,def456 */ -import { readFileSync } from 'node:fs'; -import { join } from 'node:path'; -import { homedir } from 'node:os'; - -function loadEnv() { - const envPath = join(homedir(), '.agentmemory', '.env'); - const env = {}; - for (const line of readFileSync(envPath, 'utf-8').split('\n')) { - const trimmed = line.trim(); - if (!trimmed || trimmed.startsWith('#')) continue; - const eq = trimmed.indexOf('='); - if (eq === -1) continue; - env[trimmed.slice(0, eq).trim()] = trimmed.slice(eq + 1).trim(); - } - return env; -} +import { getRestUrl, getSecret } from './agentmemory-lib.mjs'; function parseArgs() { const args = process.argv.slice(2); @@ -35,7 +20,13 @@ function parseArgs() { }; for (let i = 0; i < args.length; i++) { if (args[i] === '--min-age-hours' && args[i + 1]) { - opts.minAgeHours = Number(args[++i]); + const raw = args[++i]; + const parsed = Number(raw); + if (!Number.isFinite(parsed) || parsed < 0) { + console.error(`Invalid --min-age-hours value: ${raw}`); + process.exit(1); + } + opts.minAgeHours = parsed; } else if (args[i] === '--project' && args[i + 1]) { opts.project = args[++i]; } else if (args[i] === '--exclude' && args[i + 1]) { @@ -50,18 +41,19 @@ function parseArgs() { async function main() { const opts = parseArgs(); - const { AGENTMEMORY_URL, AGENTMEMORY_SECRET } = loadEnv(); - if (!AGENTMEMORY_URL || !AGENTMEMORY_SECRET) { + const restUrl = getRestUrl(); + const secret = getSecret(); + if (!restUrl || !secret) { console.error('Missing AGENTMEMORY_URL or AGENTMEMORY_SECRET in ~/.agentmemory/.env'); process.exit(1); } const headers = { - Authorization: `Bearer ${AGENTMEMORY_SECRET}`, + Authorization: `Bearer ${secret}`, 'Content-Type': 'application/json' }; - const listRes = await fetch(`${AGENTMEMORY_URL}/agentmemory/sessions`, { headers }); + const listRes = await fetch(`${restUrl}/agentmemory/sessions`, { headers }); if (!listRes.ok) { console.error('Failed to list sessions:', listRes.status, await listRes.text()); process.exit(1); @@ -106,7 +98,7 @@ async function main() { let failed = 0; for (const s of candidates) { - const res = await fetch(`${AGENTMEMORY_URL}/agentmemory/session/end`, { + const res = await fetch(`${restUrl}/agentmemory/session/end`, { method: 'POST', headers, body: JSON.stringify({ sessionId: s.id }) @@ -121,7 +113,7 @@ async function main() { console.log(`Closed ${closed} session(s), ${failed} failed.`); - const verify = await fetch(`${AGENTMEMORY_URL}/agentmemory/sessions`, { headers }).then((r) => + const verify = await fetch(`${restUrl}/agentmemory/sessions`, { headers }).then((r) => r.json() ); const stillActive = verify.sessions.filter( diff --git a/plugin/scripts/cursor/fix-cursor-session-projects.mjs b/plugin/scripts/cursor/fix-cursor-session-projects.mjs index 35857a0b66..0298346a81 100644 --- a/plugin/scripts/cursor/fix-cursor-session-projects.mjs +++ b/plugin/scripts/cursor/fix-cursor-session-projects.mjs @@ -7,47 +7,34 @@ * node fix-cursor-session-projects.mjs # apply * node fix-cursor-session-projects.mjs --dry-run # preview only */ -import { readFileSync } from 'node:fs'; -import { join } from 'node:path'; -import { homedir } from 'node:os'; -import { resolveWorkspace } from './agentmemory-lib.mjs'; +import { + getRestUrl, + getSecret, + isCursorMetadataPath, + resolveWorkspace +} from './agentmemory-lib.mjs'; const dryRun = process.argv.includes('--dry-run'); -function loadEnv() { - const envPath = join(homedir(), '.agentmemory', '.env'); - const env = {}; - for (const line of readFileSync(envPath, 'utf-8').split('\n')) { - const trimmed = line.trim(); - if (!trimmed || trimmed.startsWith('#')) continue; - const eq = trimmed.indexOf('='); - if (eq === -1) continue; - env[trimmed.slice(0, eq).trim()] = trimmed.slice(eq + 1).trim(); - } - return env; -} - function isBadSession(session) { const { project, cwd } = session; - if (project === '.cursor' || cwd === '.cursor') return true; - if (project?.endsWith('/.cursor') || cwd?.endsWith('/.cursor')) return true; - if (project?.includes('/.cursor') || cwd?.includes('/.cursor')) return true; - return false; + return isCursorMetadataPath(project) || isCursorMetadataPath(cwd); } async function main() { - const { AGENTMEMORY_URL, AGENTMEMORY_SECRET } = loadEnv(); - if (!AGENTMEMORY_URL || !AGENTMEMORY_SECRET) { + const restUrl = getRestUrl(); + const secret = getSecret(); + if (!restUrl || !secret) { console.error('Missing AGENTMEMORY_URL or AGENTMEMORY_SECRET in ~/.agentmemory/.env'); process.exit(1); } const headers = { - Authorization: `Bearer ${AGENTMEMORY_SECRET}`, + Authorization: `Bearer ${secret}`, 'Content-Type': 'application/json' }; - const listRes = await fetch(`${AGENTMEMORY_URL}/agentmemory/sessions`, { headers }); + const listRes = await fetch(`${restUrl}/agentmemory/sessions`, { headers }); if (!listRes.ok) { console.error('Failed to list sessions:', listRes.status, await listRes.text()); process.exit(1); @@ -99,7 +86,7 @@ async function main() { return; } - const importRes = await fetch(`${AGENTMEMORY_URL}/agentmemory/import`, { + const importRes = await fetch(`${restUrl}/agentmemory/import`, { method: 'POST', headers, body: JSON.stringify({ From 9a1b921c6c22e2ce9f3ba691cc5541069a03cb3a Mon Sep 17 00:00:00 2001 From: Andrew Date: Sun, 26 Jul 2026 18:38:49 +0800 Subject: [PATCH 03/18] fix(cursor): harden install-local, path checks, and hook payloads Abort on corrupt mcp.json, use private 0600 hook payload files, bound home path matching, and cap oversized screenshot data. --- integrations/cursor/install-local.mjs | 22 +++++++++++++++---- plugin/scripts/cursor/agentmemory-lib.mjs | 15 +++++++++---- .../cursor/agentmemory-post-tool-use.mjs | 12 ++++++++-- 3 files changed, 39 insertions(+), 10 deletions(-) diff --git a/integrations/cursor/install-local.mjs b/integrations/cursor/install-local.mjs index a2ff1530f9..f23522640c 100644 --- a/integrations/cursor/install-local.mjs +++ b/integrations/cursor/install-local.mjs @@ -32,8 +32,8 @@ function readJson(path) { if (!existsSync(path)) return {}; try { return JSON.parse(readFileSync(path, 'utf-8')); - } catch { - return {}; + } catch (err) { + throw new Error(`Cannot parse ${path}: ${err.message}`); } } @@ -59,7 +59,14 @@ function linkMarketplace() { } function mergeMcp(env) { - const mcp = readJson(MCP_PATH); + let mcp; + try { + mcp = 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); + } if (!mcp.mcpServers) mcp.mcpServers = {}; mcp.mcpServers.agentmemory = { command: 'npx', @@ -84,7 +91,14 @@ function mergeMcp(env) { function disableUserHooks() { if (!process.argv.includes('--clear-user-hooks')) return null; if (!existsSync(HOOKS_PATH)) return null; - const hooks = readJson(HOOKS_PATH); + 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); + } const hasAgentmemory = JSON.stringify(hooks).includes('agentmemory-'); if (!hasAgentmemory) return null; const backup = `${HOOKS_PATH}.pre-plugin-${Date.now()}.bak`; diff --git a/plugin/scripts/cursor/agentmemory-lib.mjs b/plugin/scripts/cursor/agentmemory-lib.mjs index 2a7f663b12..700905c3fc 100644 --- a/plugin/scripts/cursor/agentmemory-lib.mjs +++ b/plugin/scripts/cursor/agentmemory-lib.mjs @@ -1,5 +1,6 @@ #!/usr/bin/env node import { + chmodSync, closeSync, existsSync, mkdirSync, @@ -12,7 +13,7 @@ import { } from 'node:fs'; import { spawn, execSync } from 'node:child_process'; import { dirname, join, basename } from 'node:path'; -import { homedir, tmpdir } from 'node:os'; +import { homedir } from 'node:os'; import { fileURLToPath } from 'node:url'; const HOME = homedir(); @@ -157,7 +158,7 @@ function pathUnderHome(value) { if (typeof value !== 'string') return false; const homeNorm = normalizePathSlashes(HOME); const valueNorm = normalizePathSlashes(value); - return value.startsWith(HOME) || valueNorm.startsWith(homeNorm); + return valueNorm === homeNorm || valueNorm.startsWith(`${homeNorm}/`); } function collectPathStrings(value, out = []) { @@ -348,9 +349,15 @@ export function readHookStdinComplete(maxWaitMs = 30000) { }); } +const HOOK_PAYLOAD_DIR = join(HOME, '.cursor', 'hooks', '.am-hook-payloads'); + export function writeHookPayloadTemp(input) { - const path = join(tmpdir(), `am-hook-${process.pid}-${Date.now()}.json`); - writeFileSync(path, input, 'utf-8'); + mkdirSync(HOOK_PAYLOAD_DIR, { recursive: true }); + try { + chmodSync(HOOK_PAYLOAD_DIR, 0o700); + } catch {} + const path = join(HOOK_PAYLOAD_DIR, `am-hook-${process.pid}-${Date.now()}.json`); + writeFileSync(path, input, { encoding: 'utf-8', mode: 0o600 }); return path; } diff --git a/plugin/scripts/cursor/agentmemory-post-tool-use.mjs b/plugin/scripts/cursor/agentmemory-post-tool-use.mjs index 1fe8fe7348..bebc02e84e 100644 --- a/plugin/scripts/cursor/agentmemory-post-tool-use.mjs +++ b/plugin/scripts/cursor/agentmemory-post-tool-use.mjs @@ -44,10 +44,18 @@ function isBase64Image(val) { return typeof val === 'string' && (val.startsWith('data:image/') || val.startsWith('iVBORw0KGgo') || val.startsWith('/9j/')); } +const MAX_IMAGE_DATA_CHARS = 8000; + +function boundImageData(imageData) { + if (!imageData || typeof imageData !== 'string') return undefined; + if (imageData.length <= MAX_IMAGE_DATA_CHARS) return imageData; + return undefined; +} + function extractImageData(output) { if (isBase64Image(output)) { return { - imageData: output, + imageData: boundImageData(output), cleanOutput: '[image data extracted]' }; } @@ -57,7 +65,7 @@ function extractImageData(output) { const clean = {}; for (const [key, val] of Object.entries(obj)) { if (!imageData && isBase64Image(val)) { - imageData = val; + imageData = boundImageData(val); clean[key] = '[image data extracted]'; } else { clean[key] = val; From 5ded7375defb910f31aee48b5b1503f18d96a71c Mon Sep 17 00:00:00 2001 From: Andrew Date: Sun, 26 Jul 2026 18:45:50 +0800 Subject: [PATCH 04/18] fix(cursor): validate mcp.json and hooks.json object shape before merge --- integrations/cursor/install-local.mjs | 31 ++++++++++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/integrations/cursor/install-local.mjs b/integrations/cursor/install-local.mjs index f23522640c..ca831efae8 100644 --- a/integrations/cursor/install-local.mjs +++ b/integrations/cursor/install-local.mjs @@ -47,6 +47,31 @@ function writeJson(path, data, restrictPermissions = false) { } } +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)) { @@ -61,12 +86,14 @@ function linkMarketplace() { function mergeMcp(env) { let mcp; try { - mcp = readJson(MCP_PATH); + 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', @@ -99,6 +126,8 @@ function disableUserHooks() { 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`; From 1b0398b2f3f1e791fa40b3bd3dd735efbb469b89 Mon Sep 17 00:00:00 2001 From: Andrew Date: Sun, 26 Jul 2026 19:56:46 +0800 Subject: [PATCH 05/18] refactor(cursor): replace duplicated hooks with thin shims delegating to official scripts Keep hooks.cursor.json and resolveWorkspace() as the Cursor adapter; run-hook.mjs and run-detached.mjs forward to plugin/scripts/*.mjs. Add workspace resolver tests, relocate dev utilities to integrations/cursor/, and harden verify-flow timing. --- integrations/cursor/README.md | 56 +++-- .../cursor/close-stale-am-sessions.mjs | 29 ++- integrations/cursor/install-local.mjs | 2 +- .../cursor/migrate-bad-projects.mjs | 31 ++- integrations/cursor/verify-flow.mjs | 62 ++++-- plugin/hooks/hooks.cursor.json | 20 +- .../cursor/agentmemory-post-tool-failure.mjs | 42 ---- .../cursor/agentmemory-post-tool-use.mjs | 85 -------- .../cursor/agentmemory-pre-compact.mjs | 52 ----- .../cursor/agentmemory-pre-tool-use.mjs | 64 ------ .../cursor/agentmemory-prompt-submit.mjs | 32 --- .../cursor/agentmemory-session-end.mjs | 79 ------- .../cursor/agentmemory-session-start.mjs | 58 ----- plugin/scripts/cursor/agentmemory-stop.mjs | 43 ---- .../cursor/agentmemory-subagent-start.mjs | 35 --- .../cursor/agentmemory-subagent-stop.mjs | 37 ---- plugin/scripts/cursor/run-detached.mjs | 59 ++++++ plugin/scripts/cursor/run-hook.mjs | 74 +++++++ .../{agentmemory-lib.mjs => workspace.mjs} | 200 +++++++----------- test/cursor-workspace.test.ts | 45 ++++ 20 files changed, 385 insertions(+), 720 deletions(-) rename {plugin/scripts => integrations}/cursor/close-stale-am-sessions.mjs (77%) rename plugin/scripts/cursor/fix-cursor-session-projects.mjs => integrations/cursor/migrate-bad-projects.mjs (76%) delete mode 100644 plugin/scripts/cursor/agentmemory-post-tool-failure.mjs delete mode 100644 plugin/scripts/cursor/agentmemory-post-tool-use.mjs delete mode 100644 plugin/scripts/cursor/agentmemory-pre-compact.mjs delete mode 100644 plugin/scripts/cursor/agentmemory-pre-tool-use.mjs delete mode 100644 plugin/scripts/cursor/agentmemory-prompt-submit.mjs delete mode 100644 plugin/scripts/cursor/agentmemory-session-end.mjs delete mode 100644 plugin/scripts/cursor/agentmemory-session-start.mjs delete mode 100644 plugin/scripts/cursor/agentmemory-stop.mjs delete mode 100644 plugin/scripts/cursor/agentmemory-subagent-start.mjs delete mode 100644 plugin/scripts/cursor/agentmemory-subagent-stop.mjs create mode 100644 plugin/scripts/cursor/run-detached.mjs create mode 100644 plugin/scripts/cursor/run-hook.mjs rename plugin/scripts/cursor/{agentmemory-lib.mjs => workspace.mjs} (76%) create mode 100644 test/cursor-workspace.test.ts diff --git a/integrations/cursor/README.md b/integrations/cursor/README.md index 2ed747bb99..031976d2f9 100644 --- a/integrations/cursor/README.md +++ b/integrations/cursor/README.md @@ -1,8 +1,8 @@ # agentmemory for Cursor -Cursor-native plugin: **lifecycle hooks** (workspace resolver), **MCP**, and shared **skills**. +Cursor-native plugin: **lifecycle hooks** (thin shim + 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. +Hooks delegate to the canonical compiled scripts in `plugin/scripts/*.mjs` (from `src/hooks/*.ts`). The only Cursor-specific code lives in `plugin/scripts/cursor/`. ## Quick local install @@ -21,7 +21,7 @@ Then in Cursor: 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-*` +5. Confirm hooks log shows `scripts/cursor/run-hook.mjs` or `run-detached.mjs` Only after plugin hooks are confirmed: @@ -29,7 +29,7 @@ Only after plugin hooks are confirmed: node integrations/cursor/install-local.mjs --clear-user-hooks ``` -## Layout (PR target) +## Layout ```text agentmemory/ ← marketplace root (git repo) @@ -37,33 +37,51 @@ agentmemory/ ← marketplace root (git repo) 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 + scripts/cursor/ + workspace.mjs ← resolveWorkspace() + run-hook.mjs ← shim → plugin/scripts/*.mjs + run-detached.mjs ← non-blocking stop / sessionEnd + scripts/*.mjs ← canonical hooks (shared with Claude/Codex) + skills/ .mcp.json integrations/cursor/ - install-local.mjs ← dev installer - verify-flow.mjs ← smoke test + install-local.mjs + verify-flow.mjs + close-stale-am-sessions.mjs ← dev utility + migrate-bad-projects.mjs ← one-off migration for bad .cursor projects ``` ## 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 | +| Hook | Shim | Delegates to | +|------|------|--------------| +| `sessionStart` | `run-hook.mjs` | `session-start.mjs` | +| `beforeSubmitPrompt` | `run-hook.mjs` | `prompt-submit.mjs` | +| `preToolUse` / `postToolUse` | `run-hook.mjs` | `pre-tool-use.mjs` / `post-tool-use.mjs` | +| `stop` | `run-detached.mjs` | `stop.mjs` | +| `sessionEnd` | `run-detached.mjs` | `session-end.mjs` | + +The shim calls `resolveWorkspace()`, sets `AGENTMEMORY_PROJECT_NAME`, enriches `cwd` on the payload, then spawns the official hook script. ## 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 +- `stop` is reliable for summarize; treat `sessionEnd` as best-effort until Cursor fixes lifecycle on their side + +## Dev utilities + +```bash +node integrations/cursor/close-stale-am-sessions.mjs --dry-run +node integrations/cursor/migrate-bad-projects.mjs --dry-run +``` + +`migrate-bad-projects.mjs` is for legacy sessions stored with `project=.cursor` only. The resolver should prevent new bad data. ## PR checklist -- [ ] `plugin/.cursor-plugin/plugin.json` + `hooks.cursor.json` -- [ ] README: Cursor = MCP + native hooks (not MCP-only) +- [x] `plugin/.cursor-plugin/plugin.json` + `hooks.cursor.json` +- [x] Shim delegates to `plugin/scripts/*.mjs` (no duplicated hook logic) +- [ ] README: Cursor = MCP + native hooks (not MCP-only) — upstream root README - [ ] `agentmemory connect cursor` docs update -- [ ] Disable duplicate user `~/.cursor/hooks.json` in docs only (not auto-cleared) +- [x] Disable duplicate user `~/.cursor/hooks.json` in docs only (not auto-cleared) diff --git a/plugin/scripts/cursor/close-stale-am-sessions.mjs b/integrations/cursor/close-stale-am-sessions.mjs similarity index 77% rename from plugin/scripts/cursor/close-stale-am-sessions.mjs rename to integrations/cursor/close-stale-am-sessions.mjs index ee9ffb176b..d2cf08f489 100644 --- a/plugin/scripts/cursor/close-stale-am-sessions.mjs +++ b/integrations/cursor/close-stale-am-sessions.mjs @@ -3,12 +3,28 @@ * Close agentmemory sessions stuck in status "active" (sessionEnd hook never ran). * * Usage: - * node close-stale-am-sessions.mjs --dry-run - * node close-stale-am-sessions.mjs --min-age-hours 24 - * node close-stale-am-sessions.mjs --min-age-hours 6 --project 智能报表-wrenai - * node close-stale-am-sessions.mjs --exclude ses_abc123,def456 + * node integrations/cursor/close-stale-am-sessions.mjs --dry-run + * node integrations/cursor/close-stale-am-sessions.mjs --min-age-hours 24 + * node integrations/cursor/close-stale-am-sessions.mjs --min-age-hours 6 --project my-project + * node integrations/cursor/close-stale-am-sessions.mjs --exclude ses_abc123,def456 */ -import { getRestUrl, getSecret } from './agentmemory-lib.mjs'; +import { existsSync, readFileSync } from 'node:fs'; +import { homedir } from 'node:os'; +import { join } from 'node:path'; + +function loadEnv() { + const envPath = join(homedir(), '.agentmemory', '.env'); + const env = {}; + if (!existsSync(envPath)) return env; + for (const line of readFileSync(envPath, 'utf-8').split('\n')) { + const trimmed = line.trim(); + if (!trimmed || trimmed.startsWith('#')) continue; + const eq = trimmed.indexOf('='); + if (eq === -1) continue; + env[trimmed.slice(0, eq).trim()] = trimmed.slice(eq + 1).trim(); + } + return env; +} function parseArgs() { const args = process.argv.slice(2); @@ -41,8 +57,7 @@ function parseArgs() { async function main() { const opts = parseArgs(); - const restUrl = getRestUrl(); - const secret = getSecret(); + const { AGENTMEMORY_URL: restUrl, AGENTMEMORY_SECRET: secret } = loadEnv(); if (!restUrl || !secret) { console.error('Missing AGENTMEMORY_URL or AGENTMEMORY_SECRET in ~/.agentmemory/.env'); process.exit(1); diff --git a/integrations/cursor/install-local.mjs b/integrations/cursor/install-local.mjs index ca831efae8..faac0446b9 100644 --- a/integrations/cursor/install-local.mjs +++ b/integrations/cursor/install-local.mjs @@ -166,6 +166,6 @@ 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('6. In hooks log, confirm commands use ${CURSOR_PLUGIN_ROOT}/scripts/cursor/run-hook.mjs'); console.log('\nOnly after plugin hooks are confirmed:'); console.log(' node integrations/cursor/install-local.mjs --clear-user-hooks'); diff --git a/plugin/scripts/cursor/fix-cursor-session-projects.mjs b/integrations/cursor/migrate-bad-projects.mjs similarity index 76% rename from plugin/scripts/cursor/fix-cursor-session-projects.mjs rename to integrations/cursor/migrate-bad-projects.mjs index 0298346a81..1c6b2a1626 100644 --- a/plugin/scripts/cursor/fix-cursor-session-projects.mjs +++ b/integrations/cursor/migrate-bad-projects.mjs @@ -4,26 +4,37 @@ * by re-resolving the real workspace from Cursor transcript paths. * * Usage: - * node fix-cursor-session-projects.mjs # apply - * node fix-cursor-session-projects.mjs --dry-run # preview only + * node integrations/cursor/migrate-bad-projects.mjs # apply + * node integrations/cursor/migrate-bad-projects.mjs --dry-run */ -import { - getRestUrl, - getSecret, - isCursorMetadataPath, - resolveWorkspace -} from './agentmemory-lib.mjs'; +import { existsSync, readFileSync } from 'node:fs'; +import { homedir } from 'node:os'; +import { join } from 'node:path'; +import { isCursorMetadataPath, resolveWorkspace } from '../../plugin/scripts/cursor/workspace.mjs'; const dryRun = process.argv.includes('--dry-run'); +function loadEnv() { + const envPath = join(homedir(), '.agentmemory', '.env'); + const env = {}; + if (!existsSync(envPath)) return env; + for (const line of readFileSync(envPath, 'utf-8').split('\n')) { + const trimmed = line.trim(); + if (!trimmed || trimmed.startsWith('#')) continue; + const eq = trimmed.indexOf('='); + if (eq === -1) continue; + env[trimmed.slice(0, eq).trim()] = trimmed.slice(eq + 1).trim(); + } + return env; +} + function isBadSession(session) { const { project, cwd } = session; return isCursorMetadataPath(project) || isCursorMetadataPath(cwd); } async function main() { - const restUrl = getRestUrl(); - const secret = getSecret(); + const { AGENTMEMORY_URL: restUrl, AGENTMEMORY_SECRET: secret } = loadEnv(); if (!restUrl || !secret) { console.error('Missing AGENTMEMORY_URL or AGENTMEMORY_SECRET in ~/.agentmemory/.env'); process.exit(1); diff --git a/integrations/cursor/verify-flow.mjs b/integrations/cursor/verify-flow.mjs index 645efaf65f..b913b28917 100644 --- a/integrations/cursor/verify-flow.mjs +++ b/integrations/cursor/verify-flow.mjs @@ -7,7 +7,7 @@ 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 CURSOR_SCRIPTS = join(REPO_ROOT, 'plugin', 'scripts', 'cursor'); const ENV_PATH = join(homedir(), '.agentmemory', '.env'); function loadEnv(path) { @@ -23,11 +23,17 @@ function loadEnv(path) { return out; } -function runHook(script, payload) { - const r = spawnSync(process.execPath, [join(SCRIPTS, script)], { +function runHook(script, args, payload) { + const hookEnv = { + ...process.env, + ...(env.AGENTMEMORY_URL ? { AGENTMEMORY_URL: env.AGENTMEMORY_URL } : {}), + ...(env.AGENTMEMORY_SECRET ? { AGENTMEMORY_SECRET: env.AGENTMEMORY_SECRET } : {}) + }; + const r = spawnSync(process.execPath, [join(CURSOR_SCRIPTS, script), ...args], { input: JSON.stringify(payload), encoding: 'utf-8', - timeout: 30000, + timeout: 60000, + env: hookEnv }); return { script, status: r.status, stderr: r.stderr?.slice(0, 200) }; } @@ -35,7 +41,7 @@ function runHook(script, payload) { async function fetchSession(url, secret, id) { const r = await fetch(`${url}/agentmemory/sessions`, { headers: { Authorization: `Bearer ${secret}` }, - signal: AbortSignal.timeout(30000), + signal: AbortSignal.timeout(30000) }); if (!r.ok) throw new Error(`sessions list ${r.status}`); const data = await r.json(); @@ -50,25 +56,26 @@ if (!url || !secret) { process.exit(1); } -if (!existsSync(join(SCRIPTS, 'agentmemory-session-start.mjs'))) { - console.error(`Missing plugin scripts at ${SCRIPTS}`); +if (!existsSync(join(CURSOR_SCRIPTS, 'run-hook.mjs'))) { + console.error(`Missing Cursor shim at ${CURSOR_SCRIPTS}`); process.exit(1); } -const sessionId = `cursor-plugin-verify-${new Date().toISOString().slice(0, 10).replace(/-/g, '')}`; +const repoRootNorm = join(REPO_ROOT).replace(/\\/g, '/'); +const sessionId = `cursor-plugin-verify-${Date.now()}`; const basePayload = { session_id: sessionId, - workspace_roots: [join(REPO_ROOT).replace(/\\/g, '/')], - cwd: '.cursor', + workspace_roots: [repoRootNorm], + cwd: repoRootNorm }; console.log('=== agentmemory Cursor plugin verify ===\n'); -console.log(`Scripts: ${SCRIPTS}\n`); +console.log(`Shim scripts: ${CURSOR_SCRIPTS}\n`); try { const livez = await fetch(`${url}/agentmemory/livez`, { headers: { Authorization: `Bearer ${secret}` }, - signal: AbortSignal.timeout(15000), + signal: AbortSignal.timeout(15000) }); console.log(`livez: ${livez.ok ? 'ok' : livez.status}`); } catch (e) { @@ -76,15 +83,28 @@ try { process.exit(1); } -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 hookSteps = [ + ['run-hook.mjs', ['sessionStart'], basePayload], + [ + 'run-hook.mjs', + ['postToolUse'], + { + ...basePayload, + tool_name: 'Read', + tool_input: { path: join(REPO_ROOT, 'package.json') }, + tool_output: 'verify-flow smoke test' + } + ], + ['run-detached.mjs', ['stop'], basePayload], + ['run-detached.mjs', ['sessionEnd'], { ...basePayload, reason: 'window_close' }] +]; + +for (const step of hookSteps) { + const result = runHook(step[0], step[1], step[2]); + const label = `${step[0]} ${step[1].join(' ')}`; + console.log(`${label}: exit ${result.status}${result.stderr ? ` (${result.stderr})` : ''}`); + const waitMs = step[1][0] === 'postToolUse' ? 5000 : 2500; + await new Promise((r) => setTimeout(r, waitMs)); } const session = await fetchSession(url, secret, sessionId); diff --git a/plugin/hooks/hooks.cursor.json b/plugin/hooks/hooks.cursor.json index 35b464d657..2efe3a1b5f 100644 --- a/plugin/hooks/hooks.cursor.json +++ b/plugin/hooks/hooks.cursor.json @@ -3,53 +3,53 @@ "hooks": { "sessionStart": [ { - "command": "node \"${CURSOR_PLUGIN_ROOT}/scripts/cursor/agentmemory-session-start.mjs\"" + "command": "node \"${CURSOR_PLUGIN_ROOT}/scripts/cursor/run-hook.mjs\" sessionStart" } ], "beforeSubmitPrompt": [ { - "command": "node \"${CURSOR_PLUGIN_ROOT}/scripts/cursor/agentmemory-prompt-submit.mjs\"" + "command": "node \"${CURSOR_PLUGIN_ROOT}/scripts/cursor/run-hook.mjs\" beforeSubmitPrompt" } ], "preToolUse": [ { "matcher": "Edit|Write|Read|Glob|Grep|Shell", - "command": "node \"${CURSOR_PLUGIN_ROOT}/scripts/cursor/agentmemory-pre-tool-use.mjs\"" + "command": "node \"${CURSOR_PLUGIN_ROOT}/scripts/cursor/run-hook.mjs\" preToolUse" } ], "postToolUse": [ { - "command": "node \"${CURSOR_PLUGIN_ROOT}/scripts/cursor/agentmemory-post-tool-use.mjs\"" + "command": "node \"${CURSOR_PLUGIN_ROOT}/scripts/cursor/run-hook.mjs\" postToolUse" } ], "postToolUseFailure": [ { - "command": "node \"${CURSOR_PLUGIN_ROOT}/scripts/cursor/agentmemory-post-tool-failure.mjs\"" + "command": "node \"${CURSOR_PLUGIN_ROOT}/scripts/cursor/run-hook.mjs\" postToolUseFailure" } ], "preCompact": [ { - "command": "node \"${CURSOR_PLUGIN_ROOT}/scripts/cursor/agentmemory-pre-compact.mjs\"" + "command": "node \"${CURSOR_PLUGIN_ROOT}/scripts/cursor/run-hook.mjs\" preCompact" } ], "subagentStart": [ { - "command": "node \"${CURSOR_PLUGIN_ROOT}/scripts/cursor/agentmemory-subagent-start.mjs\"" + "command": "node \"${CURSOR_PLUGIN_ROOT}/scripts/cursor/run-hook.mjs\" subagentStart" } ], "subagentStop": [ { - "command": "node \"${CURSOR_PLUGIN_ROOT}/scripts/cursor/agentmemory-subagent-stop.mjs\"" + "command": "node \"${CURSOR_PLUGIN_ROOT}/scripts/cursor/run-hook.mjs\" subagentStop" } ], "stop": [ { - "command": "node \"${CURSOR_PLUGIN_ROOT}/scripts/cursor/agentmemory-stop.mjs\"" + "command": "node \"${CURSOR_PLUGIN_ROOT}/scripts/cursor/run-detached.mjs\" stop" } ], "sessionEnd": [ { - "command": "node \"${CURSOR_PLUGIN_ROOT}/scripts/cursor/agentmemory-session-end.mjs\"" + "command": "node \"${CURSOR_PLUGIN_ROOT}/scripts/cursor/run-detached.mjs\" sessionEnd" } ] } diff --git a/plugin/scripts/cursor/agentmemory-post-tool-failure.mjs b/plugin/scripts/cursor/agentmemory-post-tool-failure.mjs deleted file mode 100644 index 43dd5b8260..0000000000 --- a/plugin/scripts/cursor/agentmemory-post-tool-failure.mjs +++ /dev/null @@ -1,42 +0,0 @@ -#!/usr/bin/env node -import { - authHeaders, - getRestUrl, - resolveWorkspace, - truncateValue -} from './agentmemory-lib.mjs'; - -async function main() { - let input = ''; - for await (const chunk of process.stdin) input += chunk; - let data; - try { - data = JSON.parse(input); - } catch { - return; - } - if (data.is_interrupt) return; - const sessionId = data.session_id || 'unknown'; - const { project, cwd } = resolveWorkspace(data); - try { - await fetch(`${getRestUrl()}/agentmemory/observe`, { - method: 'POST', - headers: authHeaders(), - body: JSON.stringify({ - hookType: 'post_tool_failure', - sessionId, - project, - cwd, - timestamp: new Date().toISOString(), - data: { - tool_name: data.tool_name, - tool_input: truncateValue(data.tool_input, 4000), - error: truncateValue(data.error, 4000) - } - }), - signal: AbortSignal.timeout(3000) - }); - } catch {} -} - -main(); diff --git a/plugin/scripts/cursor/agentmemory-post-tool-use.mjs b/plugin/scripts/cursor/agentmemory-post-tool-use.mjs deleted file mode 100644 index bebc02e84e..0000000000 --- a/plugin/scripts/cursor/agentmemory-post-tool-use.mjs +++ /dev/null @@ -1,85 +0,0 @@ -#!/usr/bin/env node -import { - authHeaders, - getRestUrl, - resolveWorkspace, - truncateValue -} from './agentmemory-lib.mjs'; - -async function main() { - let input = ''; - for await (const chunk of process.stdin) input += chunk; - let data; - try { - data = JSON.parse(input); - } catch { - return; - } - const sessionId = data.session_id || 'unknown'; - const { project, cwd } = resolveWorkspace(data); - const { imageData, cleanOutput } = extractImageData(data.tool_response ?? data.tool_output); - try { - await fetch(`${getRestUrl()}/agentmemory/observe`, { - method: 'POST', - headers: authHeaders(), - body: JSON.stringify({ - hookType: 'post_tool_use', - sessionId, - project, - cwd, - timestamp: new Date().toISOString(), - data: { - tool_name: data.tool_name, - tool_input: truncateValue(data.tool_input, 4000), - tool_output: truncateValue(cleanOutput, 8000), - ...imageData ? { image_data: imageData } : {} - } - }), - signal: AbortSignal.timeout(3000) - }); - } catch {} -} - -function isBase64Image(val) { - return typeof val === 'string' && (val.startsWith('data:image/') || val.startsWith('iVBORw0KGgo') || val.startsWith('/9j/')); -} - -const MAX_IMAGE_DATA_CHARS = 8000; - -function boundImageData(imageData) { - if (!imageData || typeof imageData !== 'string') return undefined; - if (imageData.length <= MAX_IMAGE_DATA_CHARS) return imageData; - return undefined; -} - -function extractImageData(output) { - if (isBase64Image(output)) { - return { - imageData: boundImageData(output), - cleanOutput: '[image data extracted]' - }; - } - if (typeof output === 'object' && output !== null && !Array.isArray(output)) { - const obj = output; - let imageData; - const clean = {}; - for (const [key, val] of Object.entries(obj)) { - if (!imageData && isBase64Image(val)) { - imageData = boundImageData(val); - clean[key] = '[image data extracted]'; - } else { - clean[key] = val; - } - } - return { - imageData, - cleanOutput: clean - }; - } - return { - imageData: undefined, - cleanOutput: output - }; -} - -main(); diff --git a/plugin/scripts/cursor/agentmemory-pre-compact.mjs b/plugin/scripts/cursor/agentmemory-pre-compact.mjs deleted file mode 100644 index a599d674da..0000000000 --- a/plugin/scripts/cursor/agentmemory-pre-compact.mjs +++ /dev/null @@ -1,52 +0,0 @@ -#!/usr/bin/env node -import { - authHeaders, - getRestUrl, - isConfigEnabled, - resolveWorkspace -} from './agentmemory-lib.mjs'; - -async function main() { - let input = ''; - for await (const chunk of process.stdin) input += chunk; - let data; - try { - data = JSON.parse(input); - } catch { - return; - } - const sessionId = data.session_id || 'unknown'; - const { project, cwd } = resolveWorkspace(data); - if (isConfigEnabled('CLAUDE_MEMORY_BRIDGE')) { - try { - await fetch(`${getRestUrl()}/agentmemory/claude-bridge/sync`, { - method: 'POST', - headers: authHeaders(), - body: JSON.stringify({}), - signal: AbortSignal.timeout(5000) - }); - } catch {} - } - try { - const res = await fetch(`${getRestUrl()}/agentmemory/context`, { - method: 'POST', - headers: authHeaders(), - body: JSON.stringify({ - sessionId, - project, - budget: 1500 - }), - signal: AbortSignal.timeout(5000) - }); - if (res.ok) { - const result = await res.json(); - if (result.context) { - process.stdout.write(JSON.stringify({ - additional_context: result.context - })); - } - } - } catch {} -} - -main(); diff --git a/plugin/scripts/cursor/agentmemory-pre-tool-use.mjs b/plugin/scripts/cursor/agentmemory-pre-tool-use.mjs deleted file mode 100644 index 4b33e64839..0000000000 --- a/plugin/scripts/cursor/agentmemory-pre-tool-use.mjs +++ /dev/null @@ -1,64 +0,0 @@ -#!/usr/bin/env node -import { - authHeaders, - getRestUrl, - isConfigEnabled, - resolveWorkspace -} from './agentmemory-lib.mjs'; - -async function main() { - if (!isConfigEnabled('AGENTMEMORY_INJECT_CONTEXT')) return; - let input = ''; - for await (const chunk of process.stdin) input += chunk; - let data; - try { - data = JSON.parse(input); - } catch { - return; - } - const toolName = data.tool_name; - if (!toolName) return; - if (!['Edit', 'Write', 'Read', 'Glob', 'Grep', 'Shell'].includes(toolName)) return; - - const toolInput = data.tool_input || {}; - const files = []; - const fileKeys = toolName === 'Grep' ? ['path', 'file'] : ['file_path', 'path', 'file', 'pattern']; - - for (const key of fileKeys) { - const val = toolInput[key]; - if (typeof val === 'string' && val.length > 0) files.push(val); - } - if (files.length === 0) return; - - const terms = []; - if (toolName === 'Grep' || toolName === 'Glob') { - const pattern = toolInput.pattern; - if (typeof pattern === 'string' && pattern.length > 0) terms.push(pattern); - } - const sessionId = data.session_id || 'unknown'; - const { project, cwd } = resolveWorkspace(data); - try { - const res = await fetch(`${getRestUrl()}/agentmemory/enrich`, { - method: 'POST', - headers: authHeaders(), - body: JSON.stringify({ - sessionId, - project, - files, - terms, - toolName - }), - signal: AbortSignal.timeout(2000) - }); - if (res.ok) { - const result = await res.json(); - if (result.context) { - process.stdout.write(JSON.stringify({ - additional_context: result.context - })); - } - } - } catch {} -} - -main(); diff --git a/plugin/scripts/cursor/agentmemory-prompt-submit.mjs b/plugin/scripts/cursor/agentmemory-prompt-submit.mjs deleted file mode 100644 index a27b5dfaa6..0000000000 --- a/plugin/scripts/cursor/agentmemory-prompt-submit.mjs +++ /dev/null @@ -1,32 +0,0 @@ -#!/usr/bin/env node -import { authHeaders, getRestUrl, resolveWorkspace } from './agentmemory-lib.mjs'; - -async function main() { - let input = ''; - for await (const chunk of process.stdin) input += chunk; - let data; - try { - data = JSON.parse(input); - } catch { - return; - } - const sessionId = data.session_id || 'unknown'; - const { project, cwd } = resolveWorkspace(data); - try { - await fetch(`${getRestUrl()}/agentmemory/observe`, { - method: 'POST', - headers: authHeaders(), - body: JSON.stringify({ - hookType: 'prompt_submit', - sessionId, - project, - cwd, - timestamp: new Date().toISOString(), - data: { prompt: data.prompt || data.user_prompt } - }), - signal: AbortSignal.timeout(3000) - }); - } catch {} -} - -main(); diff --git a/plugin/scripts/cursor/agentmemory-session-end.mjs b/plugin/scripts/cursor/agentmemory-session-end.mjs deleted file mode 100644 index b7a20d2eb3..0000000000 --- a/plugin/scripts/cursor/agentmemory-session-end.mjs +++ /dev/null @@ -1,79 +0,0 @@ -#!/usr/bin/env node -import { - authHeaders, - getRestUrl, - isConfigEnabled, - readWorkerHookPayload, - resolveWorkspace, - runDetachedHookParent -} from './agentmemory-lib.mjs'; - -const IS_WORKER = process.env.AM_HOOK_WORKER === '1'; - -async function runWorker() { - const HARD_LIMIT_MS = 250000; - const watchdog = setTimeout(() => process.exit(0), HARD_LIMIT_MS); - - try { - const data = readWorkerHookPayload(); - if (!data) return; - - const sessionId = data.session_id || 'unknown'; - const { project } = resolveWorkspace(data); - - try { - await fetch(`${getRestUrl()}/agentmemory/session/end`, { - method: 'POST', - headers: authHeaders(), - body: JSON.stringify({ sessionId, project }), - signal: AbortSignal.timeout(30000) - }); - } catch (err) { - console.error('[agentmemory] session/end failed:', err.message); - } - - if (isConfigEnabled('CONSOLIDATION_ENABLED')) { - try { - await fetch(`${getRestUrl()}/agentmemory/crystals/auto`, { - method: 'POST', - headers: authHeaders(), - body: JSON.stringify({ olderThanDays: 0, project }), - signal: AbortSignal.timeout(60000) - }); - } catch (err) { - console.error('[agentmemory] crystals/auto failed:', err.message); - } - try { - await fetch(`${getRestUrl()}/agentmemory/consolidate-pipeline`, { - method: 'POST', - headers: authHeaders(), - body: JSON.stringify({ tier: 'all', force: true, project }), - signal: AbortSignal.timeout(120000) - }); - } catch (err) { - console.error('[agentmemory] consolidate-pipeline failed:', err.message); - } - } - - if (isConfigEnabled('CLAUDE_MEMORY_BRIDGE')) { - try { - await fetch(`${getRestUrl()}/agentmemory/claude-bridge/sync`, { - method: 'POST', - headers: authHeaders(), - signal: AbortSignal.timeout(30000) - }); - } catch (err) { - console.error('[agentmemory] claude-bridge/sync failed:', err.message); - } - } - } finally { - clearTimeout(watchdog); - process.exit(0); - } -} - -if (IS_WORKER) { - runWorker(); -} else { - runDetachedHookParent(import.meta.url); -} diff --git a/plugin/scripts/cursor/agentmemory-session-start.mjs b/plugin/scripts/cursor/agentmemory-session-start.mjs deleted file mode 100644 index 9acf4892a5..0000000000 --- a/plugin/scripts/cursor/agentmemory-session-start.mjs +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/env node -import { - authHeaders, - getRestUrl, - isConfigEnabled, - resolveWorkspace -} from './agentmemory-lib.mjs'; - -const INJECT_TIMEOUT_MS = 2500; -const REGISTER_TIMEOUT_MS = 1500; - -async function main() { - let input = ''; - for await (const chunk of process.stdin) input += chunk; - let data; - try { - data = JSON.parse(input); - } catch { - return; - } - const sessionId = data.session_id || `ses_${Date.now().toString(36)}`; - const { project, cwd } = resolveWorkspace(data); - const url = `${getRestUrl()}/agentmemory/session/start`; - const init = { - method: 'POST', - headers: authHeaders(), - body: JSON.stringify({ - sessionId, - project, - cwd - }) - }; - if (!isConfigEnabled('AGENTMEMORY_INJECT_CONTEXT')) { - try { - await fetch(url, { - ...init, - signal: AbortSignal.timeout(REGISTER_TIMEOUT_MS) - }); - } catch {} - return; - } - try { - const res = await fetch(url, { - ...init, - signal: AbortSignal.timeout(INJECT_TIMEOUT_MS) - }); - if (res.ok) { - const result = await res.json(); - if (result.context) { - process.stdout.write(JSON.stringify({ - additional_context: result.context - })); - } - } - } catch {} -} - -main(); diff --git a/plugin/scripts/cursor/agentmemory-stop.mjs b/plugin/scripts/cursor/agentmemory-stop.mjs deleted file mode 100644 index dd6422c7d0..0000000000 --- a/plugin/scripts/cursor/agentmemory-stop.mjs +++ /dev/null @@ -1,43 +0,0 @@ -#!/usr/bin/env node -import { - authHeaders, - getRestUrl, - readWorkerHookPayload, - resolveWorkspace, - runDetachedHookParent -} from './agentmemory-lib.mjs'; - -const IS_WORKER = process.env.AM_HOOK_WORKER === '1'; - -async function runWorker() { - const HARD_LIMIT_MS = 130000; - const watchdog = setTimeout(() => process.exit(0), HARD_LIMIT_MS); - - try { - const data = readWorkerHookPayload(); - if (!data) return; - - const sessionId = data.session_id || 'unknown'; - const { project } = resolveWorkspace(data); - - try { - await fetch(`${getRestUrl()}/agentmemory/summarize`, { - method: 'POST', - headers: authHeaders(), - body: JSON.stringify({ sessionId, project }), - signal: AbortSignal.timeout(120000) - }); - } catch (err) { - console.error('[agentmemory] summarize failed:', err.message); - } - } finally { - clearTimeout(watchdog); - process.exit(0); - } -} - -if (IS_WORKER) { - runWorker(); -} else { - runDetachedHookParent(import.meta.url); -} diff --git a/plugin/scripts/cursor/agentmemory-subagent-start.mjs b/plugin/scripts/cursor/agentmemory-subagent-start.mjs deleted file mode 100644 index 7c3e1f9fec..0000000000 --- a/plugin/scripts/cursor/agentmemory-subagent-start.mjs +++ /dev/null @@ -1,35 +0,0 @@ -#!/usr/bin/env node -import { authHeaders, getRestUrl, resolveWorkspace } from './agentmemory-lib.mjs'; - -const TIMEOUT_MS = 800; - -async function main() { - let input = ''; - for await (const chunk of process.stdin) input += chunk; - let data; - try { - data = JSON.parse(input); - } catch { - return; - } - const sessionId = data.session_id || 'unknown'; - const { project, cwd } = resolveWorkspace(data); - fetch(`${getRestUrl()}/agentmemory/observe`, { - method: 'POST', - headers: authHeaders(), - body: JSON.stringify({ - hookType: 'subagent_start', - sessionId, - project, - cwd, - timestamp: new Date().toISOString(), - data: { - agent_id: data.agent_id, - agent_type: data.agent_type - } - }), - signal: AbortSignal.timeout(TIMEOUT_MS) - }).catch(() => {}); -} - -main(); diff --git a/plugin/scripts/cursor/agentmemory-subagent-stop.mjs b/plugin/scripts/cursor/agentmemory-subagent-stop.mjs deleted file mode 100644 index 0807a562ae..0000000000 --- a/plugin/scripts/cursor/agentmemory-subagent-stop.mjs +++ /dev/null @@ -1,37 +0,0 @@ -#!/usr/bin/env node -import { authHeaders, getRestUrl, resolveWorkspace } from './agentmemory-lib.mjs'; - -async function main() { - let input = ''; - for await (const chunk of process.stdin) input += chunk; - let data; - try { - data = JSON.parse(input); - } catch { - return; - } - const sessionId = data.session_id || 'unknown'; - const { project, cwd } = resolveWorkspace(data); - const lastMsg = typeof data.last_assistant_message === 'string' ? data.last_assistant_message.slice(0, 4000) : ''; - try { - await fetch(`${getRestUrl()}/agentmemory/observe`, { - method: 'POST', - headers: authHeaders(), - body: JSON.stringify({ - hookType: 'subagent_stop', - sessionId, - project, - cwd, - timestamp: new Date().toISOString(), - data: { - agent_id: data.agent_id, - agent_type: data.agent_type, - last_message: lastMsg - } - }), - signal: AbortSignal.timeout(2000) - }); - } catch {} -} - -main(); diff --git a/plugin/scripts/cursor/run-detached.mjs b/plugin/scripts/cursor/run-detached.mjs new file mode 100644 index 0000000000..e33075ee58 --- /dev/null +++ b/plugin/scripts/cursor/run-detached.mjs @@ -0,0 +1,59 @@ +#!/usr/bin/env node +import { spawn } from 'node:child_process'; +import { unlinkSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import { readHookStdinComplete, readWorkerHookPayload, writeHookPayloadTemp } from './workspace.mjs'; +import { delegateHook } from './run-hook.mjs'; + +const IS_WORKER = process.env.AM_HOOK_WORKER === '1'; +const hookKey = process.argv[2]; + +async function runWorker() { + const hardLimitMs = hookKey === 'sessionEnd' ? 250000 : 130000; + const watchdog = setTimeout(() => process.exit(0), hardLimitMs); + + try { + const data = readWorkerHookPayload(); + if (!data || !hookKey) return; + delegateHook(hookKey, data); + } finally { + clearTimeout(watchdog); + process.exit(0); + } +} + +async function runParent() { + if (!hookKey) process.exit(0); + + const input = await readHookStdinComplete(); + const payloadFile = writeHookPayloadTemp(input); + + const child = spawn(process.execPath, [fileURLToPath(import.meta.url), hookKey], { + detached: true, + stdio: 'ignore', + windowsHide: true, + env: { + ...process.env, + AM_HOOK_WORKER: '1', + AM_HOOK_INPUT_FILE: payloadFile + } + }); + child.unref(); + + const bail = setTimeout(() => process.exit(0), 2000); + if (bail.unref) bail.unref(); + child.on('spawn', () => process.exit(0)); + child.on('error', (err) => { + console.error('[agentmemory] failed to spawn detached hook worker:', err.message); + try { + unlinkSync(payloadFile); + } catch {} + process.exit(0); + }); +} + +if (IS_WORKER) { + runWorker(); +} else { + runParent(); +} diff --git a/plugin/scripts/cursor/run-hook.mjs b/plugin/scripts/cursor/run-hook.mjs new file mode 100644 index 0000000000..411dfc5b68 --- /dev/null +++ b/plugin/scripts/cursor/run-hook.mjs @@ -0,0 +1,74 @@ +#!/usr/bin/env node +import { spawnSync } from 'node:child_process'; +import { dirname, join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { resolveWorkspace } from './workspace.mjs'; + +export const HOOK_MAP = { + sessionStart: 'session-start.mjs', + beforeSubmitPrompt: 'prompt-submit.mjs', + preToolUse: 'pre-tool-use.mjs', + postToolUse: 'post-tool-use.mjs', + postToolUseFailure: 'post-tool-failure.mjs', + preCompact: 'pre-compact.mjs', + subagentStart: 'subagent-start.mjs', + subagentStop: 'subagent-stop.mjs', + stop: 'stop.mjs', + sessionEnd: 'session-end.mjs' +}; + +const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url)); +const OFFICIAL_DIR = join(SCRIPT_DIR, '..'); + +const SLOW_HOOKS = new Set(['stop', 'sessionEnd']); + +export function enrichPayload(data) { + const { project, cwd } = resolveWorkspace(data); + return { + project, + payload: { + ...data, + session_id: data.session_id ?? data.sessionId, + cwd + } + }; +} + +export function delegateHook(hookKey, data) { + const script = HOOK_MAP[hookKey]; + if (!script) return 0; + + const { project, payload } = enrichPayload(data); + const scriptPath = join(OFFICIAL_DIR, script); + const child = spawnSync(process.execPath, [scriptPath], { + input: JSON.stringify(payload), + env: { ...process.env, AGENTMEMORY_PROJECT_NAME: project }, + encoding: 'utf-8', + maxBuffer: 10 * 1024 * 1024, + timeout: SLOW_HOOKS.has(hookKey) ? 180000 : 30000 + }); + + if (child.stdout) process.stdout.write(child.stdout); + if (child.stderr) process.stderr.write(child.stderr); + return child.status ?? 0; +} + +async function main() { + const hookKey = process.argv[2]; + if (!hookKey || !HOOK_MAP[hookKey]) process.exit(0); + + let input = ''; + for await (const chunk of process.stdin) input += chunk; + if (!input.trim()) process.exit(0); + + let data; + try { + data = JSON.parse(input); + } catch { + process.exit(0); + } + + process.exit(delegateHook(hookKey, data)); +} + +main(); diff --git a/plugin/scripts/cursor/agentmemory-lib.mjs b/plugin/scripts/cursor/workspace.mjs similarity index 76% rename from plugin/scripts/cursor/agentmemory-lib.mjs rename to plugin/scripts/cursor/workspace.mjs index 700905c3fc..f616574a66 100644 --- a/plugin/scripts/cursor/agentmemory-lib.mjs +++ b/plugin/scripts/cursor/workspace.mjs @@ -1,4 +1,3 @@ -#!/usr/bin/env node import { chmodSync, closeSync, @@ -8,77 +7,18 @@ import { readFileSync, renameSync, readdirSync, + statSync, unlinkSync, writeFileSync } from 'node:fs'; -import { spawn, execSync } from 'node:child_process'; +import { execSync } from 'node:child_process'; import { dirname, join, basename } from 'node:path'; import { homedir } from 'node:os'; -import { fileURLToPath } from 'node:url'; const HOME = homedir(); const CURSOR_PROJECTS_DIR = join(HOME, '.cursor', 'projects'); const SESSION_CACHE_PATH = join(HOME, '.cursor', 'hooks', '.agentmemory-session-cache.json'); -const ENV_FILE_PATH = join(HOME, '.agentmemory', '.env'); - -let cachedEnvFile = null; - -export function loadAgentmemoryEnv(envPath = ENV_FILE_PATH) { - const out = {}; - if (!existsSync(envPath)) return out; - try { - for (const line of readFileSync(envPath, '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(); - } - } catch {} - return out; -} - -function getEnvFile() { - if (!cachedEnvFile) cachedEnvFile = loadAgentmemoryEnv(); - return cachedEnvFile; -} - -export function getConfigValue(key) { - if (process.env[key] !== undefined && process.env[key] !== '') return process.env[key]; - return getEnvFile()[key]; -} - -export function isConfigEnabled(key) { - return getConfigValue(key) === 'true'; -} - -export function getRestUrl() { - return getConfigValue('AGENTMEMORY_URL') || 'http://localhost:3111'; -} - -export function getSecret() { - return getConfigValue('AGENTMEMORY_SECRET') || ''; -} - -export function authHeaders() { - const h = { 'Content-Type': 'application/json' }; - const secret = getSecret(); - if (secret) h.Authorization = `Bearer ${secret}`; - return h; -} - -export function truncateValue(value, max) { - if (typeof value === 'string') { - if (value.length > max) return `${value.slice(0, max)}\n[...truncated]`; - return value; - } - if (typeof value === 'object' && value !== null) { - const str = JSON.stringify(value); - if (str.length > max) return `${str.slice(0, max)}...[truncated]`; - return str; - } - return value; -} +const HOOK_PAYLOAD_DIR = join(HOME, '.cursor', 'hooks', '.am-hook-payloads'); export function normalizePathSlashes(value) { return String(value).replace(/\\/g, '/'); @@ -91,11 +31,29 @@ export function isCursorMetadataPath(value) { return /(^|\/)\.cursor(\/|$)/.test(trimmed); } +export function pathUnderHome(value) { + if (typeof value !== 'string') return false; + const homeNorm = normalizePathSlashes(HOME); + const valueNorm = normalizePathSlashes(value); + return valueNorm === homeNorm || valueNorm.startsWith(`${homeNorm}/`); +} + +function isIdeInstallPath(value) { + if (!value || typeof value !== 'string') return false; + const norm = normalizePathSlashes(value).toLowerCase(); + return ( + /(^|[\\/])(programs|program files|program files \(x86\))[\\/]cursor([\\/]|$)/i.test(norm) || + /cursor\.app[\\/]contents/i.test(norm) || + /(^|[\\/])microsoft vs code[\\/]resources[\\/]app([\\/]|$)/i.test(norm) + ); +} + function isBadPath(value) { if (!value || typeof value !== 'string') return true; const trimmed = normalizePathSlashes(value.trim()); if (!trimmed || trimmed === '/' || trimmed === '.') return true; if (isCursorMetadataPath(trimmed)) return true; + if (isIdeInstallPath(trimmed)) return true; return false; } @@ -154,16 +112,18 @@ function recallSession(sessionId) { return cache[sessionId] || null; } -function pathUnderHome(value) { - if (typeof value !== 'string') return false; - const homeNorm = normalizePathSlashes(HOME); - const valueNorm = normalizePathSlashes(value); - return valueNorm === homeNorm || valueNorm.startsWith(`${homeNorm}/`); +function isCollectablePath(value) { + if (typeof value !== 'string' || isCursorMetadataPath(value)) return false; + if (pathUnderHome(value)) return true; + if (process.platform === 'win32' && /^[a-zA-Z]:[\\/]/.test(value) && pathExists(value)) { + return true; + } + return false; } function collectPathStrings(value, out = []) { if (typeof value === 'string') { - if (pathUnderHome(value) && !isCursorMetadataPath(value)) out.push(value); + if (isCollectablePath(value)) out.push(value); return out; } if (Array.isArray(value)) { @@ -176,10 +136,27 @@ function collectPathStrings(value, out = []) { return out; } +function pathExists(pathValue) { + if (existsSync(pathValue)) return true; + if (process.platform === 'win32') { + const native = pathValue.replace(/\//g, '\\'); + if (native !== pathValue && existsSync(native)) return true; + } + return false; +} + function existingAncestor(pathValue) { let current = pathValue; while (current && current !== HOME && current !== '/') { - if (existsSync(current)) return current; + if (pathExists(current)) { + const resolved = process.platform === 'win32' ? current.replace(/\//g, '\\') : current; + try { + if (statSync(resolved).isFile()) { + return dirname(resolved); + } + } catch {} + return resolved; + } current = dirname(current); } return null; @@ -349,8 +326,6 @@ export function readHookStdinComplete(maxWaitMs = 30000) { }); } -const HOOK_PAYLOAD_DIR = join(HOME, '.cursor', 'hooks', '.am-hook-payloads'); - export function writeHookPayloadTemp(input) { mkdirSync(HOOK_PAYLOAD_DIR, { recursive: true }); try { @@ -380,39 +355,22 @@ export function readWorkerHookPayload() { } } -export function spawnDetachedHookWorker(scriptUrl, input) { - const payloadFile = writeHookPayloadTemp(input); - const child = spawn(process.execPath, [fileURLToPath(scriptUrl)], { - detached: true, - stdio: 'ignore', - windowsHide: true, - env: { - ...process.env, - AM_HOOK_WORKER: '1', - AM_HOOK_INPUT_FILE: payloadFile +function resolveFromPathCandidates(candidates, sessionId) { + for (const candidate of candidates) { + if (isBadPath(candidate)) continue; + const existing = existingAncestor(candidate); + if (!existing || isIdeInstallPath(existing)) continue; + const project = projectFromPath(existing); + if (project !== '.cursor') { + rememberSession(sessionId, project, existing); + return { project, cwd: existing }; } - }); - child.unref(); - - const bail = setTimeout(() => process.exit(0), 2000); - if (bail.unref) bail.unref(); - child.on('spawn', () => process.exit(0)); - child.on('error', (err) => { - console.error('[agentmemory] failed to spawn hook worker:', err.message); - try { - unlinkSync(payloadFile); - } catch {} - process.exit(0); - }); -} - -export async function runDetachedHookParent(scriptUrl) { - const input = await readHookStdinComplete(); - spawnDetachedHookWorker(scriptUrl, input); + } + return null; } export function resolveWorkspace(data) { - const sessionId = data?.session_id; + const sessionId = data?.session_id ?? data?.sessionId; const cached = recallSession(sessionId); if (cached?.cwd && !isBadPath(cached.cwd)) { return { project: cached.project, cwd: cached.cwd }; @@ -426,44 +384,36 @@ export function resolveWorkspace(data) { data?.workspace, data?.cwd, data?.root_path, - data?.project_path, - process.env.CURSOR_WORKSPACE_ROOT, - process.env.CURSOR_WORKSPACE_FOLDER, - process.env.PWD, - process.env.VSCODE_CWD + data?.project_path ]; - for (const candidate of payloadCandidates) { - if (isBadPath(candidate)) continue; - const existing = existingAncestor(candidate); - if (!existing) continue; - const project = projectFromPath(existing); - if (project !== '.cursor') { - rememberSession(sessionId, project, existing); - return { project, cwd: existing }; - } - } + const fromPayload = resolveFromPathCandidates(payloadCandidates, sessionId); + if (fromPayload) return fromPayload; const toolPaths = collectPathStrings(data?.tool_input) .map(existingAncestor) - .filter(Boolean); - for (const existing of toolPaths) { - const project = projectFromPath(existing); - if (project !== '.cursor') { - rememberSession(sessionId, project, existing); - return { project, cwd: existing }; - } - } + .filter((p) => p && !isIdeInstallPath(p)); + const fromTools = resolveFromPathCandidates(toolPaths, sessionId); + if (fromTools) return fromTools; if (sessionId) { const fromSession = workspaceFromSessionId(sessionId); - if (fromSession) { + if (fromSession && !isIdeInstallPath(fromSession)) { const project = projectFromPath(fromSession); rememberSession(sessionId, project, fromSession); return { project, cwd: fromSession }; } } + const envCandidates = [ + process.env.CURSOR_WORKSPACE_ROOT, + process.env.CURSOR_WORKSPACE_FOLDER, + process.env.PWD, + process.env.VSCODE_CWD + ]; + const fromEnv = resolveFromPathCandidates(envCandidates, sessionId); + if (fromEnv) return fromEnv; + if (process.env.CURSOR_WORKSPACE_LABEL) { const label = process.env.CURSOR_WORKSPACE_LABEL; rememberSession(sessionId, label, label); diff --git a/test/cursor-workspace.test.ts b/test/cursor-workspace.test.ts new file mode 100644 index 0000000000..3c473946f3 --- /dev/null +++ b/test/cursor-workspace.test.ts @@ -0,0 +1,45 @@ +import { describe, it, expect } from 'vitest'; +import { join } from 'node:path'; +import { + isCursorMetadataPath, + normalizePathSlashes, + pathUnderHome, + resolveWorkspace +} from '../plugin/scripts/cursor/workspace.mjs'; + +describe('cursor workspace resolver', () => { + it('isCursorMetadataPath rejects substring false positives', () => { + expect(isCursorMetadataPath('.cursor')).toBe(true); + expect(isCursorMetadataPath('/foo/.cursor/bar')).toBe(true); + expect(isCursorMetadataPath('C:\\Users\\me\\.cursor-backup')).toBe(false); + expect(isCursorMetadataPath('/home/user/.cursor-workspace-clone')).toBe(false); + }); + + it('pathUnderHome requires a path-component boundary after HOME', () => { + const home = normalizePathSlashes(process.env.HOME || process.env.USERPROFILE || '/home/alice'); + expect(pathUnderHome(home)).toBe(true); + expect(pathUnderHome(`${home}/projects/agentmemory`)).toBe(true); + expect(pathUnderHome(`${home}-backup`)).toBe(false); + }); + + it('resolveWorkspace uses workspace_roots when cwd is .cursor metadata', () => { + const repoRoot = join(process.cwd()).replace(/\\/g, '/'); + const resolved = resolveWorkspace({ + session_id: 'test-session', + workspace_roots: [repoRoot], + cwd: '.cursor' + }); + expect(resolved.project).toBe('agentmemory'); + expect(normalizePathSlashes(resolved.cwd)).toBe(repoRoot); + }); + + it('resolveWorkspace uses tool_input paths under home', () => { + const repoRoot = join(process.cwd()).replace(/\\/g, '/'); + const resolved = resolveWorkspace({ + session_id: `tool-${Date.now()}`, + tool_input: { path: `${repoRoot}/package.json` } + }); + expect(resolved.project).toBe('agentmemory'); + expect(normalizePathSlashes(resolved.cwd)).toBe(repoRoot); + }); +}); From 7457dc692c184be3686b701346feb75ec8089bce Mon Sep 17 00:00:00 2001 From: Andrew Date: Mon, 27 Jul 2026 00:10:12 +0800 Subject: [PATCH 06/18] refactor(cursor): compile the Cursor adapter from src/hooks/cursor The Cursor shims were hand-written .mjs sitting inside plugin/scripts/, a directory that is otherwise generated from src/hooks/*.ts. Move them into the same tsdown pipeline so they are typechecked, rebuilt by `npm run build`, and tested from source instead of from the build artifact. Splitting the dispatcher (delegate.ts) out of the CLI entrypoints also removes the stdin race flagged in review: run-detached.mjs used to import run-hook.mjs, whose module body called main(), leaving two readers on the same stdin in one process. Each entry now bundles standalone, so there is no shared module left to trigger. Port only -- no behavior change. The 13 canonical hook artifacts rebuild byte-identical. --- .gitignore | 4 +- plugin/scripts/cursor/run-detached.mjs | 503 ++++++++++++++++++++++--- plugin/scripts/cursor/run-hook.mjs | 434 +++++++++++++++++---- plugin/scripts/cursor/workspace.mjs | 428 --------------------- src/hooks/cursor/delegate.ts | 83 ++++ src/hooks/cursor/run-detached.ts | 67 ++++ src/hooks/cursor/run-hook.ts | 25 ++ src/hooks/cursor/workspace.ts | 467 +++++++++++++++++++++++ test/cursor-workspace.test.ts | 2 +- tsdown.config.ts | 15 + 10 files changed, 1477 insertions(+), 551 deletions(-) delete mode 100644 plugin/scripts/cursor/workspace.mjs create mode 100644 src/hooks/cursor/delegate.ts create mode 100644 src/hooks/cursor/run-detached.ts create mode 100644 src/hooks/cursor/run-hook.ts create mode 100644 src/hooks/cursor/workspace.ts diff --git a/.gitignore b/.gitignore index ba6af995b7..24fd0ff9d7 100644 --- a/.gitignore +++ b/.gitignore @@ -10,8 +10,8 @@ dist/ .DS_Store .claude/ -plugin/scripts/*.map -plugin/scripts/*.d.mts +plugin/scripts/**/*.map +plugin/scripts/**/*.d.mts data/ !eval/data/ !eval/data/** diff --git a/plugin/scripts/cursor/run-detached.mjs b/plugin/scripts/cursor/run-detached.mjs index e33075ee58..3c59f0fe2c 100644 --- a/plugin/scripts/cursor/run-detached.mjs +++ b/plugin/scripts/cursor/run-detached.mjs @@ -1,59 +1,456 @@ #!/usr/bin/env node -import { spawn } from 'node:child_process'; -import { unlinkSync } from 'node:fs'; -import { fileURLToPath } from 'node:url'; -import { readHookStdinComplete, readWorkerHookPayload, writeHookPayloadTemp } from './workspace.mjs'; -import { delegateHook } from './run-hook.mjs'; - -const IS_WORKER = process.env.AM_HOOK_WORKER === '1'; +import { execSync, spawn, spawnSync } from "node:child_process"; +import { chmodSync, closeSync, existsSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs"; +import { fileURLToPath } from "node:url"; +import { basename, dirname, join } from "node:path"; +import { homedir } from "node:os"; +//#region src/hooks/cursor/workspace.ts +const HOME = homedir(); +const CURSOR_PROJECTS_DIR = join(HOME, ".cursor", "projects"); +const SESSION_CACHE_PATH = join(HOME, ".cursor", "hooks", ".agentmemory-session-cache.json"); +const HOOK_PAYLOAD_DIR = join(HOME, ".cursor", "hooks", ".am-hook-payloads"); +function normalizePathSlashes(value) { + return String(value).replace(/\\/g, "/"); +} +function isCursorMetadataPath(value) { + if (!value || typeof value !== "string") return false; + const trimmed = normalizePathSlashes(value.trim()); + if (trimmed === ".cursor") return true; + return /(^|\/)\.cursor(\/|$)/.test(trimmed); +} +function pathUnderHome(value) { + if (typeof value !== "string") return false; + const homeNorm = normalizePathSlashes(HOME); + const valueNorm = normalizePathSlashes(value); + return valueNorm === homeNorm || valueNorm.startsWith(`${homeNorm}/`); +} +function isIdeInstallPath(value) { + if (!value || typeof value !== "string") return false; + const norm = normalizePathSlashes(value).toLowerCase(); + return /(^|[\\/])(programs|program files|program files \(x86\))[\\/]cursor([\\/]|$)/i.test(norm) || /cursor\.app[\\/]contents/i.test(norm) || /(^|[\\/])microsoft vs code[\\/]resources[\\/]app([\\/]|$)/i.test(norm); +} +function isBadPath(value) { + if (!value || typeof value !== "string") return true; + const trimmed = normalizePathSlashes(value.trim()); + if (!trimmed || trimmed === "/" || trimmed === ".") return true; + if (isCursorMetadataPath(trimmed)) return true; + if (isIdeInstallPath(trimmed)) return true; + return false; +} +function sleepMs(ms) { + const end = Date.now() + ms; + while (Date.now() < end); +} +function withSessionCacheLock(fn) { + const lockPath = `${SESSION_CACHE_PATH}.lock`; + mkdirSync(dirname(SESSION_CACHE_PATH), { recursive: true }); + let fd; + for (let i = 0; i < 50; i++) try { + fd = openSync(lockPath, "wx"); + break; + } catch { + sleepMs(10); + } + if (fd === void 0) return void 0; + try { + return fn(); + } finally { + closeSync(fd); + try { + unlinkSync(lockPath); + } catch {} + } +} +function loadSessionCache() { + try { + return JSON.parse(readFileSync(SESSION_CACHE_PATH, "utf-8")); + } catch { + return {}; + } +} +function rememberSession(sessionId, project, cwd) { + if (!sessionId || !project || project === ".cursor") return; + withSessionCacheLock(() => { + try { + const cache = loadSessionCache(); + cache[sessionId] = { + project, + cwd, + updatedAt: (/* @__PURE__ */ new Date()).toISOString() + }; + const tmp = `${SESSION_CACHE_PATH}.${process.pid}.${Date.now()}.tmp`; + writeFileSync(tmp, JSON.stringify(cache, null, 2)); + renameSync(tmp, SESSION_CACHE_PATH); + } catch {} + }); +} +function recallSession(sessionId) { + if (!sessionId) return null; + return loadSessionCache()[sessionId] ?? null; +} +function isCollectablePath(value) { + if (typeof value !== "string" || isCursorMetadataPath(value)) return false; + if (pathUnderHome(value)) return true; + if (process.platform === "win32" && /^[a-zA-Z]:[\\/]/.test(value) && pathExists(value)) return true; + return false; +} +function collectPathStrings(value, out = []) { + if (typeof value === "string") { + if (isCollectablePath(value)) out.push(value); + return out; + } + if (Array.isArray(value)) { + for (const item of value) collectPathStrings(item, out); + return out; + } + if (value && typeof value === "object") for (const v of Object.values(value)) collectPathStrings(v, out); + return out; +} +function pathExists(pathValue) { + if (existsSync(pathValue)) return true; + if (process.platform === "win32") { + const native = pathValue.replace(/\//g, "\\"); + if (native !== pathValue && existsSync(native)) return true; + } + return false; +} +function existingAncestor(pathValue) { + let current = pathValue; + while (current && current !== HOME && current !== "/") { + if (pathExists(current)) { + const resolved = process.platform === "win32" ? current.replace(/\//g, "\\") : current; + try { + if (statSync(resolved).isFile()) return dirname(resolved); + } catch {} + return resolved; + } + current = dirname(current); + } + return null; +} +function gitRootFromPath(targetPath) { + return execSync("git rev-parse --show-toplevel", { + cwd: targetPath, + encoding: "utf-8", + stdio: [ + "ignore", + "pipe", + "ignore" + ] + }).trim(); +} +function cleanRepoName(dirPath) { + const normalized = normalizePathSlashes(dirPath).replace(/\/+$/, ""); + if (!normalized) return "unknown-project"; + const claudeWt = normalized.match(/^(.*?)\/\.claude\/worktrees\/[^/]+$/i); + if (claudeWt?.[1]) return cleanRepoName(claudeWt[1]); + const baseName = basename(normalized); + if (/^agent-[a-f0-9]{6,}$/i.test(baseName)) { + const parent = dirname(normalized); + if (parent && parent !== normalized && parent !== "." && parent !== "/") return cleanRepoName(parent); + } + const name = baseName.replace(/(-worktree-\d+|-worktree|-[a-f0-9]{7,40})$/i, ""); + if (/^pxread-/i.test(name)) return "pxread"; + return name || "unknown-project"; +} +function projectFromPath(targetPath) { + try { + return cleanRepoName(gitRootFromPath(targetPath)); + } catch { + return cleanRepoName(targetPath); + } +} +function decodeSlugCandidates(slug) { + if (!slug || slug === "empty-window") return []; + const parts = slug.split("-"); + if (parts[0] !== "Users" || parts.length < 2) return []; + const results = /* @__PURE__ */ new Set(); + function walk(index, currentPath) { + if (index >= parts.length) { + if (existsSync(currentPath)) results.add(currentPath); + return; + } + walk(index + 1, `${currentPath}/${parts[index]}`); + const alt = `${currentPath}/${parts.slice(index).join("-")}`; + if (existsSync(alt)) results.add(alt); + } + walk(2, `/${parts[0]}/${parts[1]}`); + return [...results]; +} +function pickBestCandidate(candidates, preferredLabel) { + if (!candidates.length) return null; + if (preferredLabel) { + const labelMatch = candidates.find((p) => basename(p) === preferredLabel); + if (labelMatch) return labelMatch; + } + const gitRoots = []; + for (const candidate of candidates) try { + gitRoots.push(gitRootFromPath(candidate)); + } catch {} + const uniqueGitRoots = [...new Set(gitRoots)]; + if (uniqueGitRoots.length === 1) return uniqueGitRoots[0] ?? null; + return candidates.sort((a, b) => b.length - a.length)[0] ?? null; +} +function findSessionTranscript(sessionId) { + if (!sessionId || !existsSync(CURSOR_PROJECTS_DIR)) return null; + for (const slug of readdirSync(CURSOR_PROJECTS_DIR)) { + const transcriptsRoot = join(CURSOR_PROJECTS_DIR, slug, "agent-transcripts"); + if (!existsSync(transcriptsRoot)) continue; + for (const entry of readdirSync(transcriptsRoot)) if (entry === sessionId || entry.startsWith(`${sessionId}-`)) { + const transcriptFile = join(transcriptsRoot, entry, `${entry}.jsonl`); + return { + slug, + transcriptFile: existsSync(transcriptFile) ? transcriptFile : null + }; + } + } + return null; +} +function workspaceFromTranscriptFile(transcriptFile) { + if (!transcriptFile || !existsSync(transcriptFile)) return null; + const chunk = normalizePathSlashes(readFileSync(transcriptFile, "utf-8").slice(0, 25e4)); + const escapedHome = normalizePathSlashes(HOME).replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + const re = new RegExp(`${escapedHome}[^\\s"'\\\\]+`, "g"); + const counts = /* @__PURE__ */ new Map(); + for (const match of chunk.match(re) || []) { + if (isCursorMetadataPath(match)) continue; + const existing = existingAncestor(match); + if (!existing || existing === HOME) continue; + counts.set(existing, (counts.get(existing) || 0) + 1); + } + let best = null; + let bestCount = 0; + for (const [pathValue, count] of counts) if (count > bestCount) { + best = pathValue; + bestCount = count; + } + return best; +} +function workspaceFromSessionId(sessionId) { + const hit = findSessionTranscript(sessionId); + if (!hit) return null; + const fromTranscript = workspaceFromTranscriptFile(hit.transcriptFile); + if (fromTranscript) return fromTranscript; + const preferredLabel = process.env["CURSOR_WORKSPACE_LABEL"] || ""; + return pickBestCandidate(decodeSlugCandidates(hit.slug), preferredLabel); +} +function readHookStdinComplete(maxWaitMs = 3e4) { + return new Promise((resolve) => { + let input = ""; + let done = false; + const finish = () => { + if (done) return; + done = true; + try { + process.stdin.destroy(); + } catch {} + resolve(input); + }; + const t = setTimeout(finish, maxWaitMs); + if (t.unref) t.unref(); + process.stdin.on("data", (c) => { + input += c; + }); + process.stdin.on("end", () => { + clearTimeout(t); + finish(); + }); + process.stdin.on("error", () => { + clearTimeout(t); + finish(); + }); + }); +} +function writeHookPayloadTemp(input) { + mkdirSync(HOOK_PAYLOAD_DIR, { recursive: true }); + try { + chmodSync(HOOK_PAYLOAD_DIR, 448); + } catch {} + const path = join(HOOK_PAYLOAD_DIR, `am-hook-${process.pid}-${Date.now()}.json`); + writeFileSync(path, input, { + encoding: "utf-8", + mode: 384 + }); + return path; +} +function readWorkerHookPayload() { + const file = process.env["AM_HOOK_INPUT_FILE"]; + if (!file) { + console.error("[agentmemory] missing AM_HOOK_INPUT_FILE in worker"); + return null; + } + try { + const raw = readFileSync(file, "utf-8"); + return JSON.parse(raw); + } catch (err) { + console.error("[agentmemory] failed to parse hook payload:", err.message); + return null; + } finally { + try { + unlinkSync(file); + } catch {} + } +} +function resolveFromPathCandidates(candidates, sessionId) { + for (const candidate of candidates) { + if (typeof candidate !== "string" || isBadPath(candidate)) continue; + const existing = existingAncestor(candidate); + if (!existing || isIdeInstallPath(existing)) continue; + const project = projectFromPath(existing); + if (project !== ".cursor") { + rememberSession(sessionId, project, existing); + return { + project, + cwd: existing + }; + } + } + return null; +} +function resolveWorkspace(data) { + const sessionId = data?.["session_id"] ?? data?.["sessionId"]; + const cached = recallSession(sessionId); + if (cached?.cwd && !isBadPath(cached.cwd)) return { + project: cached.project, + cwd: cached.cwd + }; + const fromPayload = resolveFromPathCandidates([ + ...Array.isArray(data?.["workspace_roots"]) ? data["workspace_roots"] : [], + ...Array.isArray(data?.["workspace_folders"]) ? data["workspace_folders"] : [], + data?.["workspace_folder"], + data?.["workspaceFolder"], + data?.["workspace"], + data?.["cwd"], + data?.["root_path"], + data?.["project_path"] + ], sessionId); + if (fromPayload) return fromPayload; + const fromTools = resolveFromPathCandidates(collectPathStrings(data?.["tool_input"]).map(existingAncestor).filter((p) => Boolean(p) && !isIdeInstallPath(p)), sessionId); + if (fromTools) return fromTools; + if (sessionId) { + const fromSession = workspaceFromSessionId(sessionId); + if (fromSession && !isIdeInstallPath(fromSession)) { + const project = projectFromPath(fromSession); + rememberSession(sessionId, project, fromSession); + return { + project, + cwd: fromSession + }; + } + } + const fromEnv = resolveFromPathCandidates([ + process.env["CURSOR_WORKSPACE_ROOT"], + process.env["CURSOR_WORKSPACE_FOLDER"], + process.env["PWD"], + process.env["VSCODE_CWD"] + ], sessionId); + if (fromEnv) return fromEnv; + const label = process.env["CURSOR_WORKSPACE_LABEL"]; + if (label) { + rememberSession(sessionId, label, label); + return { + project: label, + cwd: label + }; + } + return { + project: "unknown-project", + cwd: "unknown-project" + }; +} +//#endregion +//#region src/hooks/cursor/delegate.ts +const HOOK_MAP = { + sessionStart: "session-start.mjs", + beforeSubmitPrompt: "prompt-submit.mjs", + preToolUse: "pre-tool-use.mjs", + postToolUse: "post-tool-use.mjs", + postToolUseFailure: "post-tool-failure.mjs", + preCompact: "pre-compact.mjs", + subagentStart: "subagent-start.mjs", + subagentStop: "subagent-stop.mjs", + stop: "stop.mjs", + sessionEnd: "session-end.mjs" +}; +function isCursorHookKey(value) { + return typeof value === "string" && value in HOOK_MAP; +} +const SLOW_HOOKS = new Set(["stop", "sessionEnd"]); +function defaultOfficialDir() { + return join(dirname(fileURLToPath(import.meta.url)), ".."); +} +function enrichPayload(data) { + const { project, cwd } = resolveWorkspace(data); + return { + project, + payload: { + ...data, + session_id: data["session_id"] ?? data["sessionId"], + cwd + } + }; +} +function delegateHook(hookKey, data, options = {}) { + const script = HOOK_MAP[hookKey]; + const { project, payload } = enrichPayload(data); + const scriptPath = join(options.officialDir ?? defaultOfficialDir(), script); + const child = spawnSync(process.execPath, [scriptPath], { + input: JSON.stringify(payload), + env: { + ...process.env, + AGENTMEMORY_PROJECT_NAME: project + }, + encoding: "utf-8", + maxBuffer: 10 * 1024 * 1024, + timeout: SLOW_HOOKS.has(hookKey) ? 18e4 : 3e4 + }); + if (child.stdout) process.stdout.write(child.stdout); + if (child.stderr) process.stderr.write(child.stderr); + return child.status ?? 0; +} +//#endregion +//#region src/hooks/cursor/run-detached.ts +const IS_WORKER = process.env["AM_HOOK_WORKER"] === "1"; const hookKey = process.argv[2]; - -async function runWorker() { - const hardLimitMs = hookKey === 'sessionEnd' ? 250000 : 130000; - const watchdog = setTimeout(() => process.exit(0), hardLimitMs); - - try { - const data = readWorkerHookPayload(); - if (!data || !hookKey) return; - delegateHook(hookKey, data); - } finally { - clearTimeout(watchdog); - process.exit(0); - } +function runWorker() { + const watchdog = setTimeout(() => process.exit(0), hookKey === "sessionEnd" ? 25e4 : 13e4); + try { + const data = readWorkerHookPayload(); + if (!data || !isCursorHookKey(hookKey)) return; + delegateHook(hookKey, data); + } finally { + clearTimeout(watchdog); + process.exit(0); + } } - async function runParent() { - if (!hookKey) process.exit(0); - - const input = await readHookStdinComplete(); - const payloadFile = writeHookPayloadTemp(input); - - const child = spawn(process.execPath, [fileURLToPath(import.meta.url), hookKey], { - detached: true, - stdio: 'ignore', - windowsHide: true, - env: { - ...process.env, - AM_HOOK_WORKER: '1', - AM_HOOK_INPUT_FILE: payloadFile - } - }); - child.unref(); - - const bail = setTimeout(() => process.exit(0), 2000); - if (bail.unref) bail.unref(); - child.on('spawn', () => process.exit(0)); - child.on('error', (err) => { - console.error('[agentmemory] failed to spawn detached hook worker:', err.message); - try { - unlinkSync(payloadFile); - } catch {} - process.exit(0); - }); + if (!hookKey) process.exit(0); + const payloadFile = writeHookPayloadTemp(await readHookStdinComplete()); + const child = spawn(process.execPath, [fileURLToPath(import.meta.url), hookKey], { + detached: true, + stdio: "ignore", + windowsHide: true, + env: { + ...process.env, + AM_HOOK_WORKER: "1", + AM_HOOK_INPUT_FILE: payloadFile + } + }); + child.unref(); + const bail = setTimeout(() => process.exit(0), 2e3); + if (bail.unref) bail.unref(); + child.on("spawn", () => process.exit(0)); + child.on("error", (err) => { + console.error("[agentmemory] failed to spawn detached hook worker:", err.message); + try { + unlinkSync(payloadFile); + } catch {} + process.exit(0); + }); } +if (IS_WORKER) runWorker(); +else runParent(); +//#endregion +export {}; -if (IS_WORKER) { - runWorker(); -} else { - runParent(); -} +//# sourceMappingURL=run-detached.mjs.map \ No newline at end of file diff --git a/plugin/scripts/cursor/run-hook.mjs b/plugin/scripts/cursor/run-hook.mjs index 411dfc5b68..0bfdae450b 100644 --- a/plugin/scripts/cursor/run-hook.mjs +++ b/plugin/scripts/cursor/run-hook.mjs @@ -1,74 +1,374 @@ #!/usr/bin/env node -import { spawnSync } from 'node:child_process'; -import { dirname, join } from 'node:path'; -import { fileURLToPath } from 'node:url'; -import { resolveWorkspace } from './workspace.mjs'; - -export const HOOK_MAP = { - sessionStart: 'session-start.mjs', - beforeSubmitPrompt: 'prompt-submit.mjs', - preToolUse: 'pre-tool-use.mjs', - postToolUse: 'post-tool-use.mjs', - postToolUseFailure: 'post-tool-failure.mjs', - preCompact: 'pre-compact.mjs', - subagentStart: 'subagent-start.mjs', - subagentStop: 'subagent-stop.mjs', - stop: 'stop.mjs', - sessionEnd: 'session-end.mjs' +import { execSync, spawnSync } from "node:child_process"; +import { basename, dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { closeSync, existsSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs"; +import { homedir } from "node:os"; +//#region src/hooks/cursor/workspace.ts +const HOME = homedir(); +const CURSOR_PROJECTS_DIR = join(HOME, ".cursor", "projects"); +const SESSION_CACHE_PATH = join(HOME, ".cursor", "hooks", ".agentmemory-session-cache.json"); +join(HOME, ".cursor", "hooks", ".am-hook-payloads"); +function normalizePathSlashes(value) { + return String(value).replace(/\\/g, "/"); +} +function isCursorMetadataPath(value) { + if (!value || typeof value !== "string") return false; + const trimmed = normalizePathSlashes(value.trim()); + if (trimmed === ".cursor") return true; + return /(^|\/)\.cursor(\/|$)/.test(trimmed); +} +function pathUnderHome(value) { + if (typeof value !== "string") return false; + const homeNorm = normalizePathSlashes(HOME); + const valueNorm = normalizePathSlashes(value); + return valueNorm === homeNorm || valueNorm.startsWith(`${homeNorm}/`); +} +function isIdeInstallPath(value) { + if (!value || typeof value !== "string") return false; + const norm = normalizePathSlashes(value).toLowerCase(); + return /(^|[\\/])(programs|program files|program files \(x86\))[\\/]cursor([\\/]|$)/i.test(norm) || /cursor\.app[\\/]contents/i.test(norm) || /(^|[\\/])microsoft vs code[\\/]resources[\\/]app([\\/]|$)/i.test(norm); +} +function isBadPath(value) { + if (!value || typeof value !== "string") return true; + const trimmed = normalizePathSlashes(value.trim()); + if (!trimmed || trimmed === "/" || trimmed === ".") return true; + if (isCursorMetadataPath(trimmed)) return true; + if (isIdeInstallPath(trimmed)) return true; + return false; +} +function sleepMs(ms) { + const end = Date.now() + ms; + while (Date.now() < end); +} +function withSessionCacheLock(fn) { + const lockPath = `${SESSION_CACHE_PATH}.lock`; + mkdirSync(dirname(SESSION_CACHE_PATH), { recursive: true }); + let fd; + for (let i = 0; i < 50; i++) try { + fd = openSync(lockPath, "wx"); + break; + } catch { + sleepMs(10); + } + if (fd === void 0) return void 0; + try { + return fn(); + } finally { + closeSync(fd); + try { + unlinkSync(lockPath); + } catch {} + } +} +function loadSessionCache() { + try { + return JSON.parse(readFileSync(SESSION_CACHE_PATH, "utf-8")); + } catch { + return {}; + } +} +function rememberSession(sessionId, project, cwd) { + if (!sessionId || !project || project === ".cursor") return; + withSessionCacheLock(() => { + try { + const cache = loadSessionCache(); + cache[sessionId] = { + project, + cwd, + updatedAt: (/* @__PURE__ */ new Date()).toISOString() + }; + const tmp = `${SESSION_CACHE_PATH}.${process.pid}.${Date.now()}.tmp`; + writeFileSync(tmp, JSON.stringify(cache, null, 2)); + renameSync(tmp, SESSION_CACHE_PATH); + } catch {} + }); +} +function recallSession(sessionId) { + if (!sessionId) return null; + return loadSessionCache()[sessionId] ?? null; +} +function isCollectablePath(value) { + if (typeof value !== "string" || isCursorMetadataPath(value)) return false; + if (pathUnderHome(value)) return true; + if (process.platform === "win32" && /^[a-zA-Z]:[\\/]/.test(value) && pathExists(value)) return true; + return false; +} +function collectPathStrings(value, out = []) { + if (typeof value === "string") { + if (isCollectablePath(value)) out.push(value); + return out; + } + if (Array.isArray(value)) { + for (const item of value) collectPathStrings(item, out); + return out; + } + if (value && typeof value === "object") for (const v of Object.values(value)) collectPathStrings(v, out); + return out; +} +function pathExists(pathValue) { + if (existsSync(pathValue)) return true; + if (process.platform === "win32") { + const native = pathValue.replace(/\//g, "\\"); + if (native !== pathValue && existsSync(native)) return true; + } + return false; +} +function existingAncestor(pathValue) { + let current = pathValue; + while (current && current !== HOME && current !== "/") { + if (pathExists(current)) { + const resolved = process.platform === "win32" ? current.replace(/\//g, "\\") : current; + try { + if (statSync(resolved).isFile()) return dirname(resolved); + } catch {} + return resolved; + } + current = dirname(current); + } + return null; +} +function gitRootFromPath(targetPath) { + return execSync("git rev-parse --show-toplevel", { + cwd: targetPath, + encoding: "utf-8", + stdio: [ + "ignore", + "pipe", + "ignore" + ] + }).trim(); +} +function cleanRepoName(dirPath) { + const normalized = normalizePathSlashes(dirPath).replace(/\/+$/, ""); + if (!normalized) return "unknown-project"; + const claudeWt = normalized.match(/^(.*?)\/\.claude\/worktrees\/[^/]+$/i); + if (claudeWt?.[1]) return cleanRepoName(claudeWt[1]); + const baseName = basename(normalized); + if (/^agent-[a-f0-9]{6,}$/i.test(baseName)) { + const parent = dirname(normalized); + if (parent && parent !== normalized && parent !== "." && parent !== "/") return cleanRepoName(parent); + } + const name = baseName.replace(/(-worktree-\d+|-worktree|-[a-f0-9]{7,40})$/i, ""); + if (/^pxread-/i.test(name)) return "pxread"; + return name || "unknown-project"; +} +function projectFromPath(targetPath) { + try { + return cleanRepoName(gitRootFromPath(targetPath)); + } catch { + return cleanRepoName(targetPath); + } +} +function decodeSlugCandidates(slug) { + if (!slug || slug === "empty-window") return []; + const parts = slug.split("-"); + if (parts[0] !== "Users" || parts.length < 2) return []; + const results = /* @__PURE__ */ new Set(); + function walk(index, currentPath) { + if (index >= parts.length) { + if (existsSync(currentPath)) results.add(currentPath); + return; + } + walk(index + 1, `${currentPath}/${parts[index]}`); + const alt = `${currentPath}/${parts.slice(index).join("-")}`; + if (existsSync(alt)) results.add(alt); + } + walk(2, `/${parts[0]}/${parts[1]}`); + return [...results]; +} +function pickBestCandidate(candidates, preferredLabel) { + if (!candidates.length) return null; + if (preferredLabel) { + const labelMatch = candidates.find((p) => basename(p) === preferredLabel); + if (labelMatch) return labelMatch; + } + const gitRoots = []; + for (const candidate of candidates) try { + gitRoots.push(gitRootFromPath(candidate)); + } catch {} + const uniqueGitRoots = [...new Set(gitRoots)]; + if (uniqueGitRoots.length === 1) return uniqueGitRoots[0] ?? null; + return candidates.sort((a, b) => b.length - a.length)[0] ?? null; +} +function findSessionTranscript(sessionId) { + if (!sessionId || !existsSync(CURSOR_PROJECTS_DIR)) return null; + for (const slug of readdirSync(CURSOR_PROJECTS_DIR)) { + const transcriptsRoot = join(CURSOR_PROJECTS_DIR, slug, "agent-transcripts"); + if (!existsSync(transcriptsRoot)) continue; + for (const entry of readdirSync(transcriptsRoot)) if (entry === sessionId || entry.startsWith(`${sessionId}-`)) { + const transcriptFile = join(transcriptsRoot, entry, `${entry}.jsonl`); + return { + slug, + transcriptFile: existsSync(transcriptFile) ? transcriptFile : null + }; + } + } + return null; +} +function workspaceFromTranscriptFile(transcriptFile) { + if (!transcriptFile || !existsSync(transcriptFile)) return null; + const chunk = normalizePathSlashes(readFileSync(transcriptFile, "utf-8").slice(0, 25e4)); + const escapedHome = normalizePathSlashes(HOME).replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + const re = new RegExp(`${escapedHome}[^\\s"'\\\\]+`, "g"); + const counts = /* @__PURE__ */ new Map(); + for (const match of chunk.match(re) || []) { + if (isCursorMetadataPath(match)) continue; + const existing = existingAncestor(match); + if (!existing || existing === HOME) continue; + counts.set(existing, (counts.get(existing) || 0) + 1); + } + let best = null; + let bestCount = 0; + for (const [pathValue, count] of counts) if (count > bestCount) { + best = pathValue; + bestCount = count; + } + return best; +} +function workspaceFromSessionId(sessionId) { + const hit = findSessionTranscript(sessionId); + if (!hit) return null; + const fromTranscript = workspaceFromTranscriptFile(hit.transcriptFile); + if (fromTranscript) return fromTranscript; + const preferredLabel = process.env["CURSOR_WORKSPACE_LABEL"] || ""; + return pickBestCandidate(decodeSlugCandidates(hit.slug), preferredLabel); +} +function resolveFromPathCandidates(candidates, sessionId) { + for (const candidate of candidates) { + if (typeof candidate !== "string" || isBadPath(candidate)) continue; + const existing = existingAncestor(candidate); + if (!existing || isIdeInstallPath(existing)) continue; + const project = projectFromPath(existing); + if (project !== ".cursor") { + rememberSession(sessionId, project, existing); + return { + project, + cwd: existing + }; + } + } + return null; +} +function resolveWorkspace(data) { + const sessionId = data?.["session_id"] ?? data?.["sessionId"]; + const cached = recallSession(sessionId); + if (cached?.cwd && !isBadPath(cached.cwd)) return { + project: cached.project, + cwd: cached.cwd + }; + const fromPayload = resolveFromPathCandidates([ + ...Array.isArray(data?.["workspace_roots"]) ? data["workspace_roots"] : [], + ...Array.isArray(data?.["workspace_folders"]) ? data["workspace_folders"] : [], + data?.["workspace_folder"], + data?.["workspaceFolder"], + data?.["workspace"], + data?.["cwd"], + data?.["root_path"], + data?.["project_path"] + ], sessionId); + if (fromPayload) return fromPayload; + const fromTools = resolveFromPathCandidates(collectPathStrings(data?.["tool_input"]).map(existingAncestor).filter((p) => Boolean(p) && !isIdeInstallPath(p)), sessionId); + if (fromTools) return fromTools; + if (sessionId) { + const fromSession = workspaceFromSessionId(sessionId); + if (fromSession && !isIdeInstallPath(fromSession)) { + const project = projectFromPath(fromSession); + rememberSession(sessionId, project, fromSession); + return { + project, + cwd: fromSession + }; + } + } + const fromEnv = resolveFromPathCandidates([ + process.env["CURSOR_WORKSPACE_ROOT"], + process.env["CURSOR_WORKSPACE_FOLDER"], + process.env["PWD"], + process.env["VSCODE_CWD"] + ], sessionId); + if (fromEnv) return fromEnv; + const label = process.env["CURSOR_WORKSPACE_LABEL"]; + if (label) { + rememberSession(sessionId, label, label); + return { + project: label, + cwd: label + }; + } + return { + project: "unknown-project", + cwd: "unknown-project" + }; +} +//#endregion +//#region src/hooks/cursor/delegate.ts +const HOOK_MAP = { + sessionStart: "session-start.mjs", + beforeSubmitPrompt: "prompt-submit.mjs", + preToolUse: "pre-tool-use.mjs", + postToolUse: "post-tool-use.mjs", + postToolUseFailure: "post-tool-failure.mjs", + preCompact: "pre-compact.mjs", + subagentStart: "subagent-start.mjs", + subagentStop: "subagent-stop.mjs", + stop: "stop.mjs", + sessionEnd: "session-end.mjs" }; - -const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url)); -const OFFICIAL_DIR = join(SCRIPT_DIR, '..'); - -const SLOW_HOOKS = new Set(['stop', 'sessionEnd']); - -export function enrichPayload(data) { - const { project, cwd } = resolveWorkspace(data); - return { - project, - payload: { - ...data, - session_id: data.session_id ?? data.sessionId, - cwd - } - }; +function isCursorHookKey(value) { + return typeof value === "string" && value in HOOK_MAP; } - -export function delegateHook(hookKey, data) { - const script = HOOK_MAP[hookKey]; - if (!script) return 0; - - const { project, payload } = enrichPayload(data); - const scriptPath = join(OFFICIAL_DIR, script); - const child = spawnSync(process.execPath, [scriptPath], { - input: JSON.stringify(payload), - env: { ...process.env, AGENTMEMORY_PROJECT_NAME: project }, - encoding: 'utf-8', - maxBuffer: 10 * 1024 * 1024, - timeout: SLOW_HOOKS.has(hookKey) ? 180000 : 30000 - }); - - if (child.stdout) process.stdout.write(child.stdout); - if (child.stderr) process.stderr.write(child.stderr); - return child.status ?? 0; +const SLOW_HOOKS = new Set(["stop", "sessionEnd"]); +function defaultOfficialDir() { + return join(dirname(fileURLToPath(import.meta.url)), ".."); } - +function enrichPayload(data) { + const { project, cwd } = resolveWorkspace(data); + return { + project, + payload: { + ...data, + session_id: data["session_id"] ?? data["sessionId"], + cwd + } + }; +} +function delegateHook(hookKey, data, options = {}) { + const script = HOOK_MAP[hookKey]; + const { project, payload } = enrichPayload(data); + const scriptPath = join(options.officialDir ?? defaultOfficialDir(), script); + const child = spawnSync(process.execPath, [scriptPath], { + input: JSON.stringify(payload), + env: { + ...process.env, + AGENTMEMORY_PROJECT_NAME: project + }, + encoding: "utf-8", + maxBuffer: 10 * 1024 * 1024, + timeout: SLOW_HOOKS.has(hookKey) ? 18e4 : 3e4 + }); + if (child.stdout) process.stdout.write(child.stdout); + if (child.stderr) process.stderr.write(child.stderr); + return child.status ?? 0; +} +//#endregion +//#region src/hooks/cursor/run-hook.ts async function main() { - const hookKey = process.argv[2]; - if (!hookKey || !HOOK_MAP[hookKey]) process.exit(0); - - let input = ''; - for await (const chunk of process.stdin) input += chunk; - if (!input.trim()) process.exit(0); - - let data; - try { - data = JSON.parse(input); - } catch { - process.exit(0); - } - - process.exit(delegateHook(hookKey, data)); + const hookKey = process.argv[2]; + if (!isCursorHookKey(hookKey)) process.exit(0); + let input = ""; + for await (const chunk of process.stdin) input += chunk; + if (!input.trim()) process.exit(0); + let data; + try { + data = JSON.parse(input); + } catch { + process.exit(0); + } + process.exit(delegateHook(hookKey, data)); } - main(); +//#endregion +export {}; + +//# sourceMappingURL=run-hook.mjs.map \ No newline at end of file diff --git a/plugin/scripts/cursor/workspace.mjs b/plugin/scripts/cursor/workspace.mjs deleted file mode 100644 index f616574a66..0000000000 --- a/plugin/scripts/cursor/workspace.mjs +++ /dev/null @@ -1,428 +0,0 @@ -import { - chmodSync, - closeSync, - existsSync, - mkdirSync, - openSync, - readFileSync, - renameSync, - readdirSync, - statSync, - unlinkSync, - writeFileSync -} from 'node:fs'; -import { execSync } from 'node:child_process'; -import { dirname, join, basename } from 'node:path'; -import { homedir } from 'node:os'; - -const HOME = homedir(); -const CURSOR_PROJECTS_DIR = join(HOME, '.cursor', 'projects'); -const SESSION_CACHE_PATH = join(HOME, '.cursor', 'hooks', '.agentmemory-session-cache.json'); -const HOOK_PAYLOAD_DIR = join(HOME, '.cursor', 'hooks', '.am-hook-payloads'); - -export function normalizePathSlashes(value) { - return String(value).replace(/\\/g, '/'); -} - -export function isCursorMetadataPath(value) { - if (!value || typeof value !== 'string') return false; - const trimmed = normalizePathSlashes(value.trim()); - if (trimmed === '.cursor') return true; - return /(^|\/)\.cursor(\/|$)/.test(trimmed); -} - -export function pathUnderHome(value) { - if (typeof value !== 'string') return false; - const homeNorm = normalizePathSlashes(HOME); - const valueNorm = normalizePathSlashes(value); - return valueNorm === homeNorm || valueNorm.startsWith(`${homeNorm}/`); -} - -function isIdeInstallPath(value) { - if (!value || typeof value !== 'string') return false; - const norm = normalizePathSlashes(value).toLowerCase(); - return ( - /(^|[\\/])(programs|program files|program files \(x86\))[\\/]cursor([\\/]|$)/i.test(norm) || - /cursor\.app[\\/]contents/i.test(norm) || - /(^|[\\/])microsoft vs code[\\/]resources[\\/]app([\\/]|$)/i.test(norm) - ); -} - -function isBadPath(value) { - if (!value || typeof value !== 'string') return true; - const trimmed = normalizePathSlashes(value.trim()); - if (!trimmed || trimmed === '/' || trimmed === '.') return true; - if (isCursorMetadataPath(trimmed)) return true; - if (isIdeInstallPath(trimmed)) return true; - return false; -} - -function sleepMs(ms) { - const end = Date.now() + ms; - while (Date.now() < end) {} -} - -function withSessionCacheLock(fn) { - const lockPath = `${SESSION_CACHE_PATH}.lock`; - mkdirSync(dirname(SESSION_CACHE_PATH), { recursive: true }); - let fd; - for (let i = 0; i < 50; i++) { - try { - fd = openSync(lockPath, 'wx'); - break; - } catch { - sleepMs(10); - } - } - if (!fd) return; - try { - return fn(); - } finally { - closeSync(fd); - try { - unlinkSync(lockPath); - } catch {} - } -} - -function loadSessionCache() { - try { - return JSON.parse(readFileSync(SESSION_CACHE_PATH, 'utf-8')); - } catch { - return {}; - } -} - -function rememberSession(sessionId, project, cwd) { - if (!sessionId || !project || project === '.cursor') return; - withSessionCacheLock(() => { - try { - const cache = loadSessionCache(); - cache[sessionId] = { project, cwd, updatedAt: new Date().toISOString() }; - const tmp = `${SESSION_CACHE_PATH}.${process.pid}.${Date.now()}.tmp`; - writeFileSync(tmp, JSON.stringify(cache, null, 2)); - renameSync(tmp, SESSION_CACHE_PATH); - } catch {} - }); -} - -function recallSession(sessionId) { - if (!sessionId) return null; - const cache = loadSessionCache(); - return cache[sessionId] || null; -} - -function isCollectablePath(value) { - if (typeof value !== 'string' || isCursorMetadataPath(value)) return false; - if (pathUnderHome(value)) return true; - if (process.platform === 'win32' && /^[a-zA-Z]:[\\/]/.test(value) && pathExists(value)) { - return true; - } - return false; -} - -function collectPathStrings(value, out = []) { - if (typeof value === 'string') { - if (isCollectablePath(value)) out.push(value); - return out; - } - if (Array.isArray(value)) { - for (const item of value) collectPathStrings(item, out); - return out; - } - if (value && typeof value === 'object') { - for (const v of Object.values(value)) collectPathStrings(v, out); - } - return out; -} - -function pathExists(pathValue) { - if (existsSync(pathValue)) return true; - if (process.platform === 'win32') { - const native = pathValue.replace(/\//g, '\\'); - if (native !== pathValue && existsSync(native)) return true; - } - return false; -} - -function existingAncestor(pathValue) { - let current = pathValue; - while (current && current !== HOME && current !== '/') { - if (pathExists(current)) { - const resolved = process.platform === 'win32' ? current.replace(/\//g, '\\') : current; - try { - if (statSync(resolved).isFile()) { - return dirname(resolved); - } - } catch {} - return resolved; - } - current = dirname(current); - } - return null; -} - -function gitRootFromPath(targetPath) { - return execSync('git rev-parse --show-toplevel', { - cwd: targetPath, - encoding: 'utf-8', - stdio: ['ignore', 'pipe', 'ignore'] - }).trim(); -} - -function cleanRepoName(dirPath) { - const normalized = normalizePathSlashes(dirPath).replace(/\/+$/, ''); - if (!normalized) return 'unknown-project'; - - const claudeWt = normalized.match(/^(.*?)\/\.claude\/worktrees\/[^/]+$/i); - if (claudeWt?.[1]) return cleanRepoName(claudeWt[1]); - - const baseName = basename(normalized); - if (/^agent-[a-f0-9]{6,}$/i.test(baseName)) { - const parent = dirname(normalized); - if (parent && parent !== normalized && parent !== '.' && parent !== '/') { - return cleanRepoName(parent); - } - } - - let name = baseName.replace(/(-worktree-\d+|-worktree|-[a-f0-9]{7,40})$/i, ''); - if (/^pxread-/i.test(name)) return 'pxread'; - return name || 'unknown-project'; -} - -function projectFromPath(targetPath) { - try { - return cleanRepoName(gitRootFromPath(targetPath)); - } catch { - return cleanRepoName(targetPath); - } -} - -function decodeSlugCandidates(slug) { - if (!slug || slug === 'empty-window') return []; - const parts = slug.split('-'); - if (parts[0] !== 'Users' || parts.length < 2) return []; - - const results = new Set(); - - function walk(index, currentPath) { - if (index >= parts.length) { - if (existsSync(currentPath)) results.add(currentPath); - return; - } - walk(index + 1, `${currentPath}/${parts[index]}`); - const remainder = parts.slice(index).join('-'); - const alt = `${currentPath}/${remainder}`; - if (existsSync(alt)) results.add(alt); - } - - walk(2, `/${parts[0]}/${parts[1]}`); - return [...results]; -} - -function pickBestCandidate(candidates, preferredLabel) { - if (!candidates.length) return null; - if (preferredLabel) { - const labelMatch = candidates.find((p) => basename(p) === preferredLabel); - if (labelMatch) return labelMatch; - } - - const gitRoots = []; - for (const candidate of candidates) { - try { - gitRoots.push(gitRootFromPath(candidate)); - } catch {} - } - const uniqueGitRoots = [...new Set(gitRoots)]; - if (uniqueGitRoots.length === 1) return uniqueGitRoots[0]; - - return candidates.sort((a, b) => b.length - a.length)[0]; -} - -function findSessionTranscript(sessionId) { - if (!sessionId || !existsSync(CURSOR_PROJECTS_DIR)) return null; - - for (const slug of readdirSync(CURSOR_PROJECTS_DIR)) { - const transcriptsRoot = join(CURSOR_PROJECTS_DIR, slug, 'agent-transcripts'); - if (!existsSync(transcriptsRoot)) continue; - - for (const entry of readdirSync(transcriptsRoot)) { - if (entry === sessionId || entry.startsWith(`${sessionId}-`)) { - const transcriptFile = join(transcriptsRoot, entry, `${entry}.jsonl`); - return { - slug, - transcriptFile: existsSync(transcriptFile) ? transcriptFile : null - }; - } - } - } - return null; -} - -function workspaceFromTranscriptFile(transcriptFile) { - if (!transcriptFile || !existsSync(transcriptFile)) return null; - - const chunk = normalizePathSlashes(readFileSync(transcriptFile, 'utf-8').slice(0, 250000)); - const escapedHome = normalizePathSlashes(HOME).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); - const re = new RegExp(`${escapedHome}[^\\s"'\\\\]+`, 'g'); - const counts = new Map(); - - for (const match of chunk.match(re) || []) { - if (isCursorMetadataPath(match)) continue; - const existing = existingAncestor(match); - if (!existing || existing === HOME) continue; - counts.set(existing, (counts.get(existing) || 0) + 1); - } - - let best = null; - let bestCount = 0; - for (const [pathValue, count] of counts) { - if (count > bestCount) { - best = pathValue; - bestCount = count; - } - } - - return best; -} - -function workspaceFromSessionId(sessionId) { - const hit = findSessionTranscript(sessionId); - if (!hit) return null; - - const fromTranscript = workspaceFromTranscriptFile(hit.transcriptFile); - if (fromTranscript) return fromTranscript; - - const preferredLabel = process.env.CURSOR_WORKSPACE_LABEL || ''; - const candidates = decodeSlugCandidates(hit.slug); - return pickBestCandidate(candidates, preferredLabel); -} - -export function readHookStdinComplete(maxWaitMs = 30000) { - return new Promise((resolve) => { - let input = ''; - let done = false; - const finish = () => { - if (done) return; - done = true; - try { - process.stdin.destroy(); - } catch {} - resolve(input); - }; - const t = setTimeout(finish, maxWaitMs); - if (t.unref) t.unref(); - process.stdin.on('data', (c) => { - input += c; - }); - process.stdin.on('end', () => { - clearTimeout(t); - finish(); - }); - process.stdin.on('error', () => { - clearTimeout(t); - finish(); - }); - }); -} - -export function writeHookPayloadTemp(input) { - mkdirSync(HOOK_PAYLOAD_DIR, { recursive: true }); - try { - chmodSync(HOOK_PAYLOAD_DIR, 0o700); - } catch {} - const path = join(HOOK_PAYLOAD_DIR, `am-hook-${process.pid}-${Date.now()}.json`); - writeFileSync(path, input, { encoding: 'utf-8', mode: 0o600 }); - return path; -} - -export function readWorkerHookPayload() { - const file = process.env.AM_HOOK_INPUT_FILE; - if (!file) { - console.error('[agentmemory] missing AM_HOOK_INPUT_FILE in worker'); - return null; - } - try { - const raw = readFileSync(file, 'utf-8'); - return JSON.parse(raw); - } catch (err) { - console.error('[agentmemory] failed to parse hook payload:', err.message); - return null; - } finally { - try { - unlinkSync(file); - } catch {} - } -} - -function resolveFromPathCandidates(candidates, sessionId) { - for (const candidate of candidates) { - if (isBadPath(candidate)) continue; - const existing = existingAncestor(candidate); - if (!existing || isIdeInstallPath(existing)) continue; - const project = projectFromPath(existing); - if (project !== '.cursor') { - rememberSession(sessionId, project, existing); - return { project, cwd: existing }; - } - } - return null; -} - -export function resolveWorkspace(data) { - const sessionId = data?.session_id ?? data?.sessionId; - const cached = recallSession(sessionId); - if (cached?.cwd && !isBadPath(cached.cwd)) { - return { project: cached.project, cwd: cached.cwd }; - } - - const payloadCandidates = [ - ...(Array.isArray(data?.workspace_roots) ? data.workspace_roots : []), - ...(Array.isArray(data?.workspace_folders) ? data.workspace_folders : []), - data?.workspace_folder, - data?.workspaceFolder, - data?.workspace, - data?.cwd, - data?.root_path, - data?.project_path - ]; - - const fromPayload = resolveFromPathCandidates(payloadCandidates, sessionId); - if (fromPayload) return fromPayload; - - const toolPaths = collectPathStrings(data?.tool_input) - .map(existingAncestor) - .filter((p) => p && !isIdeInstallPath(p)); - const fromTools = resolveFromPathCandidates(toolPaths, sessionId); - if (fromTools) return fromTools; - - if (sessionId) { - const fromSession = workspaceFromSessionId(sessionId); - if (fromSession && !isIdeInstallPath(fromSession)) { - const project = projectFromPath(fromSession); - rememberSession(sessionId, project, fromSession); - return { project, cwd: fromSession }; - } - } - - const envCandidates = [ - process.env.CURSOR_WORKSPACE_ROOT, - process.env.CURSOR_WORKSPACE_FOLDER, - process.env.PWD, - process.env.VSCODE_CWD - ]; - const fromEnv = resolveFromPathCandidates(envCandidates, sessionId); - if (fromEnv) return fromEnv; - - if (process.env.CURSOR_WORKSPACE_LABEL) { - const label = process.env.CURSOR_WORKSPACE_LABEL; - rememberSession(sessionId, label, label); - return { project: label, cwd: label }; - } - - return { project: 'unknown-project', cwd: 'unknown-project' }; -} - -export function resolveProject(data) { - return resolveWorkspace(data).project; -} diff --git a/src/hooks/cursor/delegate.ts b/src/hooks/cursor/delegate.ts new file mode 100644 index 0000000000..8130f3ce16 --- /dev/null +++ b/src/hooks/cursor/delegate.ts @@ -0,0 +1,83 @@ +import { spawnSync } from "node:child_process"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { resolveWorkspace } from "./workspace.js"; + +// Cursor fires camelCase lifecycle events; each one maps to the canonical +// hook compiled from src/hooks/*.ts. Keep this table the only place that +// knows Cursor's naming — everything downstream is the shared hook. +export const HOOK_MAP = { + sessionStart: "session-start.mjs", + beforeSubmitPrompt: "prompt-submit.mjs", + preToolUse: "pre-tool-use.mjs", + postToolUse: "post-tool-use.mjs", + postToolUseFailure: "post-tool-failure.mjs", + preCompact: "pre-compact.mjs", + subagentStart: "subagent-start.mjs", + subagentStop: "subagent-stop.mjs", + stop: "stop.mjs", + sessionEnd: "session-end.mjs", +} as const; + +export type CursorHookKey = keyof typeof HOOK_MAP; + +export function isCursorHookKey(value: unknown): value is CursorHookKey { + return typeof value === "string" && value in HOOK_MAP; +} + +// stop/sessionEnd fan out to summarize + consolidate on the daemon side, so +// they get a longer leash than the interactive hooks. +const SLOW_HOOKS = new Set(["stop", "sessionEnd"]); + +export type HookPayload = Record; + +export interface DelegateOptions { + // Tests run against src/, where the canonical .mjs files do not sit one + // level up. Bundled output resolves it correctly on its own. + officialDir?: string; +} + +// Bundled to plugin/scripts/cursor/.mjs, so the canonical hooks are +// exactly one directory up. +function defaultOfficialDir(): string { + return join(dirname(fileURLToPath(import.meta.url)), ".."); +} + +export function enrichPayload(data: HookPayload): { + project: string; + payload: HookPayload; +} { + const { project, cwd } = resolveWorkspace(data); + return { + project, + payload: { + ...data, + session_id: data["session_id"] ?? data["sessionId"], + cwd, + }, + }; +} + +export function delegateHook( + hookKey: CursorHookKey, + data: HookPayload, + options: DelegateOptions = {}, +): number { + const script = HOOK_MAP[hookKey]; + const { project, payload } = enrichPayload(data); + const scriptPath = join(options.officialDir ?? defaultOfficialDir(), script); + + const child = spawnSync(process.execPath, [scriptPath], { + input: JSON.stringify(payload), + // resolveProject() in the canonical hooks reads this before falling back + // to git/cwd, which is how the Cursor-specific resolution wins. + env: { ...process.env, AGENTMEMORY_PROJECT_NAME: project }, + encoding: "utf-8", + maxBuffer: 10 * 1024 * 1024, + timeout: SLOW_HOOKS.has(hookKey) ? 180000 : 30000, + }); + + if (child.stdout) process.stdout.write(child.stdout); + if (child.stderr) process.stderr.write(child.stderr); + return child.status ?? 0; +} diff --git a/src/hooks/cursor/run-detached.ts b/src/hooks/cursor/run-detached.ts new file mode 100644 index 0000000000..914cf16df3 --- /dev/null +++ b/src/hooks/cursor/run-detached.ts @@ -0,0 +1,67 @@ +#!/usr/bin/env node +import { spawn } from "node:child_process"; +import { unlinkSync } from "node:fs"; +import { fileURLToPath } from "node:url"; +import { delegateHook, isCursorHookKey } from "./delegate.js"; +import { + readHookStdinComplete, + readWorkerHookPayload, + writeHookPayloadTemp, +} from "./workspace.js"; + +// stop/sessionEnd trigger summarize + consolidate on the daemon. Cursor +// kills its hook process tree when the window closes, so the real work runs +// in a detached worker that outlives the window; the parent only hands off +// the payload and returns control immediately. +const IS_WORKER = process.env["AM_HOOK_WORKER"] === "1"; +const hookKey = process.argv[2]; + +function runWorker(): void { + const hardLimitMs = hookKey === "sessionEnd" ? 250000 : 130000; + const watchdog = setTimeout(() => process.exit(0), hardLimitMs); + + try { + const data = readWorkerHookPayload(); + if (!data || !isCursorHookKey(hookKey)) return; + delegateHook(hookKey, data); + } finally { + clearTimeout(watchdog); + process.exit(0); + } +} + +async function runParent(): Promise { + if (!hookKey) process.exit(0); + + const input = await readHookStdinComplete(); + const payloadFile = writeHookPayloadTemp(input); + + const child = spawn(process.execPath, [fileURLToPath(import.meta.url), hookKey], { + detached: true, + stdio: "ignore", + windowsHide: true, + env: { + ...process.env, + AM_HOOK_WORKER: "1", + AM_HOOK_INPUT_FILE: payloadFile, + }, + }); + child.unref(); + + const bail = setTimeout(() => process.exit(0), 2000); + if (bail.unref) bail.unref(); + child.on("spawn", () => process.exit(0)); + child.on("error", (err: Error) => { + console.error("[agentmemory] failed to spawn detached hook worker:", err.message); + try { + unlinkSync(payloadFile); + } catch {} + process.exit(0); + }); +} + +if (IS_WORKER) { + runWorker(); +} else { + void runParent(); +} diff --git a/src/hooks/cursor/run-hook.ts b/src/hooks/cursor/run-hook.ts new file mode 100644 index 0000000000..9a81a9d299 --- /dev/null +++ b/src/hooks/cursor/run-hook.ts @@ -0,0 +1,25 @@ +#!/usr/bin/env node +import { delegateHook, isCursorHookKey, type HookPayload } from "./delegate.js"; + +// CLI entrypoint for Cursor's synchronous hooks. Kept separate from +// delegate.ts so importing the dispatcher never starts a second stdin +// reader in the same process (run-detached.ts depends on that). +async function main(): Promise { + const hookKey = process.argv[2]; + if (!isCursorHookKey(hookKey)) process.exit(0); + + let input = ""; + for await (const chunk of process.stdin) input += chunk; + if (!input.trim()) process.exit(0); + + let data: HookPayload; + try { + data = JSON.parse(input) as HookPayload; + } catch { + process.exit(0); + } + + process.exit(delegateHook(hookKey, data)); +} + +main(); diff --git a/src/hooks/cursor/workspace.ts b/src/hooks/cursor/workspace.ts new file mode 100644 index 0000000000..0afb5d4d6d --- /dev/null +++ b/src/hooks/cursor/workspace.ts @@ -0,0 +1,467 @@ +import { + chmodSync, + closeSync, + existsSync, + mkdirSync, + openSync, + readFileSync, + renameSync, + readdirSync, + statSync, + unlinkSync, + writeFileSync, +} from "node:fs"; +import { execSync } from "node:child_process"; +import { dirname, join, basename } from "node:path"; +import { homedir } from "node:os"; + +// Cursor does not hand hooks a trustworthy working directory: `cwd` can be +// `.cursor`, the IDE install path (via VSCODE_CWD), or absent entirely. This +// module is the Cursor-specific piece of the adapter — everything it exists +// to do is turn whatever Cursor sends into a real project directory, so the +// canonical hooks in src/hooks/*.ts can stay unchanged. +const HOME = homedir(); +const CURSOR_PROJECTS_DIR = join(HOME, ".cursor", "projects"); +const SESSION_CACHE_PATH = join(HOME, ".cursor", "hooks", ".agentmemory-session-cache.json"); +const HOOK_PAYLOAD_DIR = join(HOME, ".cursor", "hooks", ".am-hook-payloads"); + +export interface Workspace { + project: string; + cwd: string; +} + +export type HookData = Record | null | undefined; + +interface SessionCacheEntry { + project: string; + cwd: string; + updatedAt: string; +} + +type SessionCache = Record; + +export function normalizePathSlashes(value: unknown): string { + return String(value).replace(/\\/g, "/"); +} + +export function isCursorMetadataPath(value: unknown): boolean { + if (!value || typeof value !== "string") return false; + const trimmed = normalizePathSlashes(value.trim()); + if (trimmed === ".cursor") return true; + return /(^|\/)\.cursor(\/|$)/.test(trimmed); +} + +export function pathUnderHome(value: unknown): boolean { + if (typeof value !== "string") return false; + const homeNorm = normalizePathSlashes(HOME); + const valueNorm = normalizePathSlashes(value); + return valueNorm === homeNorm || valueNorm.startsWith(`${homeNorm}/`); +} + +// VSCODE_CWD points at the Cursor install directory, which resolves to a +// project literally named "cursor" if it is allowed through. +function isIdeInstallPath(value: unknown): boolean { + if (!value || typeof value !== "string") return false; + const norm = normalizePathSlashes(value).toLowerCase(); + return ( + /(^|[\\/])(programs|program files|program files \(x86\))[\\/]cursor([\\/]|$)/i.test(norm) || + /cursor\.app[\\/]contents/i.test(norm) || + /(^|[\\/])microsoft vs code[\\/]resources[\\/]app([\\/]|$)/i.test(norm) + ); +} + +function isBadPath(value: unknown): boolean { + if (!value || typeof value !== "string") return true; + const trimmed = normalizePathSlashes(value.trim()); + if (!trimmed || trimmed === "/" || trimmed === ".") return true; + if (isCursorMetadataPath(trimmed)) return true; + if (isIdeInstallPath(trimmed)) return true; + return false; +} + +function sleepMs(ms: number): void { + const end = Date.now() + ms; + while (Date.now() < end) { + // Busy wait: this runs inside a lock retry loop in a short-lived hook + // process, where blocking is cheaper than an async scheduler hop. + } +} + +function withSessionCacheLock(fn: () => T): T | undefined { + const lockPath = `${SESSION_CACHE_PATH}.lock`; + mkdirSync(dirname(SESSION_CACHE_PATH), { recursive: true }); + let fd: number | undefined; + for (let i = 0; i < 50; i++) { + try { + fd = openSync(lockPath, "wx"); + break; + } catch { + sleepMs(10); + } + } + if (fd === undefined) return undefined; + try { + return fn(); + } finally { + closeSync(fd); + try { + unlinkSync(lockPath); + } catch {} + } +} + +function loadSessionCache(): SessionCache { + try { + return JSON.parse(readFileSync(SESSION_CACHE_PATH, "utf-8")) as SessionCache; + } catch { + return {}; + } +} + +function rememberSession(sessionId: string | undefined, project: string, cwd: string): void { + if (!sessionId || !project || project === ".cursor") return; + withSessionCacheLock(() => { + try { + const cache = loadSessionCache(); + cache[sessionId] = { project, cwd, updatedAt: new Date().toISOString() }; + const tmp = `${SESSION_CACHE_PATH}.${process.pid}.${Date.now()}.tmp`; + writeFileSync(tmp, JSON.stringify(cache, null, 2)); + renameSync(tmp, SESSION_CACHE_PATH); + } catch {} + }); +} + +function recallSession(sessionId: string | undefined): SessionCacheEntry | null { + if (!sessionId) return null; + const cache = loadSessionCache(); + return cache[sessionId] ?? null; +} + +function isCollectablePath(value: unknown): value is string { + if (typeof value !== "string" || isCursorMetadataPath(value)) return false; + if (pathUnderHome(value)) return true; + if (process.platform === "win32" && /^[a-zA-Z]:[\\/]/.test(value) && pathExists(value)) { + return true; + } + return false; +} + +function collectPathStrings(value: unknown, out: string[] = []): string[] { + if (typeof value === "string") { + if (isCollectablePath(value)) out.push(value); + return out; + } + if (Array.isArray(value)) { + for (const item of value) collectPathStrings(item, out); + return out; + } + if (value && typeof value === "object") { + for (const v of Object.values(value)) collectPathStrings(v, out); + } + return out; +} + +function pathExists(pathValue: string): boolean { + if (existsSync(pathValue)) return true; + if (process.platform === "win32") { + const native = pathValue.replace(/\//g, "\\"); + if (native !== pathValue && existsSync(native)) return true; + } + return false; +} + +// Payloads often carry a file path (tool_input.path) rather than a +// directory, and sometimes a path that no longer exists. Walk up until +// something real is found, then normalise a file down to its directory. +function existingAncestor(pathValue: string): string | null { + let current = pathValue; + while (current && current !== HOME && current !== "/") { + if (pathExists(current)) { + const resolved = process.platform === "win32" ? current.replace(/\//g, "\\") : current; + try { + if (statSync(resolved).isFile()) { + return dirname(resolved); + } + } catch {} + return resolved; + } + current = dirname(current); + } + return null; +} + +function gitRootFromPath(targetPath: string): string { + return execSync("git rev-parse --show-toplevel", { + cwd: targetPath, + encoding: "utf-8", + stdio: ["ignore", "pipe", "ignore"], + }).trim(); +} + +function cleanRepoName(dirPath: string): string { + const normalized = normalizePathSlashes(dirPath).replace(/\/+$/, ""); + if (!normalized) return "unknown-project"; + + const claudeWt = normalized.match(/^(.*?)\/\.claude\/worktrees\/[^/]+$/i); + if (claudeWt?.[1]) return cleanRepoName(claudeWt[1]); + + const baseName = basename(normalized); + if (/^agent-[a-f0-9]{6,}$/i.test(baseName)) { + const parent = dirname(normalized); + if (parent && parent !== normalized && parent !== "." && parent !== "/") { + return cleanRepoName(parent); + } + } + + const name = baseName.replace(/(-worktree-\d+|-worktree|-[a-f0-9]{7,40})$/i, ""); + if (/^pxread-/i.test(name)) return "pxread"; + return name || "unknown-project"; +} + +function projectFromPath(targetPath: string): string { + try { + return cleanRepoName(gitRootFromPath(targetPath)); + } catch { + return cleanRepoName(targetPath); + } +} + +// Cursor names transcript directories after the workspace path with every +// separator flattened to "-", so "Users-me-src-my-app" is ambiguous between +// .../src/my/app and .../src/my-app. Try both splits at each position and +// keep whatever exists on disk. +function decodeSlugCandidates(slug: string): string[] { + if (!slug || slug === "empty-window") return []; + const parts = slug.split("-"); + if (parts[0] !== "Users" || parts.length < 2) return []; + + const results = new Set(); + + function walk(index: number, currentPath: string): void { + if (index >= parts.length) { + if (existsSync(currentPath)) results.add(currentPath); + return; + } + walk(index + 1, `${currentPath}/${parts[index]}`); + const remainder = parts.slice(index).join("-"); + const alt = `${currentPath}/${remainder}`; + if (existsSync(alt)) results.add(alt); + } + + walk(2, `/${parts[0]}/${parts[1]}`); + return [...results]; +} + +function pickBestCandidate(candidates: string[], preferredLabel: string): string | null { + if (!candidates.length) return null; + if (preferredLabel) { + const labelMatch = candidates.find((p) => basename(p) === preferredLabel); + if (labelMatch) return labelMatch; + } + + const gitRoots: string[] = []; + for (const candidate of candidates) { + try { + gitRoots.push(gitRootFromPath(candidate)); + } catch {} + } + const uniqueGitRoots = [...new Set(gitRoots)]; + if (uniqueGitRoots.length === 1) return uniqueGitRoots[0] ?? null; + + return candidates.sort((a, b) => b.length - a.length)[0] ?? null; +} + +function findSessionTranscript( + sessionId: string, +): { slug: string; transcriptFile: string | null } | null { + if (!sessionId || !existsSync(CURSOR_PROJECTS_DIR)) return null; + + for (const slug of readdirSync(CURSOR_PROJECTS_DIR)) { + const transcriptsRoot = join(CURSOR_PROJECTS_DIR, slug, "agent-transcripts"); + if (!existsSync(transcriptsRoot)) continue; + + for (const entry of readdirSync(transcriptsRoot)) { + if (entry === sessionId || entry.startsWith(`${sessionId}-`)) { + const transcriptFile = join(transcriptsRoot, entry, `${entry}.jsonl`); + return { + slug, + transcriptFile: existsSync(transcriptFile) ? transcriptFile : null, + }; + } + } + } + return null; +} + +function workspaceFromTranscriptFile(transcriptFile: string | null): string | null { + if (!transcriptFile || !existsSync(transcriptFile)) return null; + + const chunk = normalizePathSlashes(readFileSync(transcriptFile, "utf-8").slice(0, 250000)); + const escapedHome = normalizePathSlashes(HOME).replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + const re = new RegExp(`${escapedHome}[^\\s"'\\\\]+`, "g"); + const counts = new Map(); + + for (const match of chunk.match(re) || []) { + if (isCursorMetadataPath(match)) continue; + const existing = existingAncestor(match); + if (!existing || existing === HOME) continue; + counts.set(existing, (counts.get(existing) || 0) + 1); + } + + let best: string | null = null; + let bestCount = 0; + for (const [pathValue, count] of counts) { + if (count > bestCount) { + best = pathValue; + bestCount = count; + } + } + + return best; +} + +function workspaceFromSessionId(sessionId: string): string | null { + const hit = findSessionTranscript(sessionId); + if (!hit) return null; + + const fromTranscript = workspaceFromTranscriptFile(hit.transcriptFile); + if (fromTranscript) return fromTranscript; + + const preferredLabel = process.env["CURSOR_WORKSPACE_LABEL"] || ""; + const candidates = decodeSlugCandidates(hit.slug); + return pickBestCandidate(candidates, preferredLabel); +} + +export function readHookStdinComplete(maxWaitMs = 30000): Promise { + return new Promise((resolve) => { + let input = ""; + let done = false; + const finish = (): void => { + if (done) return; + done = true; + try { + process.stdin.destroy(); + } catch {} + resolve(input); + }; + const t = setTimeout(finish, maxWaitMs); + if (t.unref) t.unref(); + process.stdin.on("data", (c) => { + input += c; + }); + process.stdin.on("end", () => { + clearTimeout(t); + finish(); + }); + process.stdin.on("error", () => { + clearTimeout(t); + finish(); + }); + }); +} + +export function writeHookPayloadTemp(input: string): string { + mkdirSync(HOOK_PAYLOAD_DIR, { recursive: true }); + try { + chmodSync(HOOK_PAYLOAD_DIR, 0o700); + } catch {} + const path = join(HOOK_PAYLOAD_DIR, `am-hook-${process.pid}-${Date.now()}.json`); + writeFileSync(path, input, { encoding: "utf-8", mode: 0o600 }); + return path; +} + +export function readWorkerHookPayload(): Record | null { + const file = process.env["AM_HOOK_INPUT_FILE"]; + if (!file) { + console.error("[agentmemory] missing AM_HOOK_INPUT_FILE in worker"); + return null; + } + try { + const raw = readFileSync(file, "utf-8"); + return JSON.parse(raw) as Record; + } catch (err) { + console.error("[agentmemory] failed to parse hook payload:", (err as Error).message); + return null; + } finally { + try { + unlinkSync(file); + } catch {} + } +} + +function resolveFromPathCandidates( + candidates: unknown[], + sessionId: string | undefined, +): Workspace | null { + for (const candidate of candidates) { + if (typeof candidate !== "string" || isBadPath(candidate)) continue; + const existing = existingAncestor(candidate); + if (!existing || isIdeInstallPath(existing)) continue; + const project = projectFromPath(existing); + if (project !== ".cursor") { + rememberSession(sessionId, project, existing); + return { project, cwd: existing }; + } + } + return null; +} + +export function resolveWorkspace(data: HookData): Workspace { + const sessionId = (data?.["session_id"] ?? data?.["sessionId"]) as string | undefined; + const cached = recallSession(sessionId); + if (cached?.cwd && !isBadPath(cached.cwd)) { + return { project: cached.project, cwd: cached.cwd }; + } + + const payloadCandidates: unknown[] = [ + ...(Array.isArray(data?.["workspace_roots"]) ? (data["workspace_roots"] as unknown[]) : []), + ...(Array.isArray(data?.["workspace_folders"]) ? (data["workspace_folders"] as unknown[]) : []), + data?.["workspace_folder"], + data?.["workspaceFolder"], + data?.["workspace"], + data?.["cwd"], + data?.["root_path"], + data?.["project_path"], + ]; + + const fromPayload = resolveFromPathCandidates(payloadCandidates, sessionId); + if (fromPayload) return fromPayload; + + const toolPaths = collectPathStrings(data?.["tool_input"]) + .map(existingAncestor) + .filter((p): p is string => Boolean(p) && !isIdeInstallPath(p)); + const fromTools = resolveFromPathCandidates(toolPaths, sessionId); + if (fromTools) return fromTools; + + if (sessionId) { + const fromSession = workspaceFromSessionId(sessionId); + if (fromSession && !isIdeInstallPath(fromSession)) { + const project = projectFromPath(fromSession); + rememberSession(sessionId, project, fromSession); + return { project, cwd: fromSession }; + } + } + + // Env comes last: VSCODE_CWD in particular is frequently the IDE install + // directory rather than the workspace. + const envCandidates: unknown[] = [ + process.env["CURSOR_WORKSPACE_ROOT"], + process.env["CURSOR_WORKSPACE_FOLDER"], + process.env["PWD"], + process.env["VSCODE_CWD"], + ]; + const fromEnv = resolveFromPathCandidates(envCandidates, sessionId); + if (fromEnv) return fromEnv; + + const label = process.env["CURSOR_WORKSPACE_LABEL"]; + if (label) { + rememberSession(sessionId, label, label); + return { project: label, cwd: label }; + } + + return { project: "unknown-project", cwd: "unknown-project" }; +} + +export function resolveProject(data: HookData): string { + return resolveWorkspace(data).project; +} diff --git a/test/cursor-workspace.test.ts b/test/cursor-workspace.test.ts index 3c473946f3..81c3b6f488 100644 --- a/test/cursor-workspace.test.ts +++ b/test/cursor-workspace.test.ts @@ -5,7 +5,7 @@ import { normalizePathSlashes, pathUnderHome, resolveWorkspace -} from '../plugin/scripts/cursor/workspace.mjs'; +} from '../src/hooks/cursor/workspace.js'; describe('cursor workspace resolver', () => { it('isCursorMetadataPath rejects substring false positives', () => { diff --git a/tsdown.config.ts b/tsdown.config.ts index 0c6426c1b0..e13501b6cf 100644 --- a/tsdown.config.ts +++ b/tsdown.config.ts @@ -17,6 +17,14 @@ const hookEntries = [ "src/hooks/antigravity-bridge.ts", ]; +// Cursor gets a thin adapter rather than its own hook copies: two CLI +// entrypoints that resolve the workspace Cursor fails to report, then +// delegate to the canonical hooks above. workspace.ts/delegate.ts are not +// entries — they inline into each CLI, so the emitted files stay +// self-contained like every other hook, and the canonical .mjs they spawn +// sit exactly one directory up from plugin/scripts/cursor/. +const cursorEntries = ["src/hooks/cursor/run-hook.ts", "src/hooks/cursor/run-detached.ts"]; + const shared = { format: ["esm"] as const, target: "node20" as const, @@ -83,4 +91,11 @@ export default defineConfig([ clean: false, sourcemap: false, })), + ...cursorEntries.map((entry) => ({ + entry: [entry], + outDir: "plugin/scripts/cursor", + ...shared, + clean: false, + sourcemap: false, + })), ]); From 3f04558b696ddf3406fb38b565f3737a86c0fe18 Mon Sep 17 00:00:00 2001 From: Andrew Date: Mon, 27 Jul 2026 00:47:55 +0800 Subject: [PATCH 07/18] fix(cursor): address review findings in the adapter and dev scripts - delegate: spawnSync reports a launch failure as status === null, so `status ?? 0` announced success and lost the observation silently. Report error/signal on stderr and stay fail-open; a real non-zero exit from the canonical hook is still passed through. - workspace: accept absolute paths outside $HOME. Containers check repos out at /workspaces/..., which the HOME-only rule silently rejected, disabling tool_input resolution there. OS-owned trees stay excluded so a stray /usr/lib/... cannot become a project named "lib". - workspace: drop a hardcoded `pxread-*` project alias that had no business in a shared resolver. - integrations: add _env.mjs so the scripts read the runtime environment first and ~/.agentmemory/.env second. They end and rewrite sessions on whatever host they are given, and ignoring an explicit AGENTMEMORY_URL aimed a destructive operation at the wrong server. Also removes the third copy of the same .env parser. - verify-flow: poll for daemon state instead of sleeping. run-detached returns once its worker is spawned and the canonical hooks exit on a timer, so a fixed sleep proved nothing in either direction. Fail on a non-ok /livez. sessionEnd is now opt-in: it fans out to crystals/auto plus consolidate-pipeline, which loads the daemon enough that back-to-back runs lose observations. The observe check retries with a varied tool_input for the same reason -- the dedup key is (sessionId, tool_name, tool_input), so an identical retry could never land. - test: use a unique session id; resolveWorkspace caches per session, so the fixed id was served from cache and stopped exercising the branch. - Drop migrate-bad-projects.mjs. It repaired sessions the resolver no longer produces, the reviewer asked for it to go, and there is no installed base beyond the machine it was written on. --- integrations/cursor/_env.mjs | 54 +++++ .../cursor/close-stale-am-sessions.mjs | 24 +- integrations/cursor/install-local.mjs | 21 +- integrations/cursor/migrate-bad-projects.mjs | 128 ---------- integrations/cursor/verify-flow.mjs | 220 +++++++++++------- plugin/scripts/cursor/run-detached.mjs | 36 ++- plugin/scripts/cursor/run-hook.mjs | 36 ++- src/hooks/cursor/delegate.ts | 20 ++ src/hooks/cursor/workspace.ts | 40 +++- test/cursor-workspace.test.ts | 5 +- 10 files changed, 320 insertions(+), 264 deletions(-) create mode 100644 integrations/cursor/_env.mjs delete mode 100644 integrations/cursor/migrate-bad-projects.mjs diff --git a/integrations/cursor/_env.mjs b/integrations/cursor/_env.mjs new file mode 100644 index 0000000000..846b0d0766 --- /dev/null +++ b/integrations/cursor/_env.mjs @@ -0,0 +1,54 @@ +/** + * Shared configuration loading for the Cursor integration scripts. + * + * The documented contract for agentmemory is that `AGENTMEMORY_URL` and + * `AGENTMEMORY_SECRET` come from the runtime environment, with + * `~/.agentmemory/.env` as the persistent default. These scripts end and + * rewrite sessions on whatever host they are pointed at, so reading the file + * only -- and ignoring an explicit `AGENTMEMORY_URL=... node ...` -- would + * quietly aim a destructive operation at the wrong server. + */ +import { existsSync, readFileSync } from 'node:fs'; +import { homedir } from 'node:os'; +import { join } from 'node:path'; + +export const ENV_PATH = join(homedir(), '.agentmemory', '.env'); + +export function parseEnvFile(path = ENV_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; +} + +/** Runtime environment first, `~/.agentmemory/.env` second, '' if neither. */ +export function loadConfig(keys, path = ENV_PATH) { + const file = parseEnvFile(path); + const out = {}; + for (const key of keys) { + const fromEnv = process.env[key]?.trim(); + out[key] = fromEnv || file[key] || ''; + } + return out; +} + +/** loadConfig for the two keys every script needs, with a uniform error. */ +export function requireConnection(path = ENV_PATH) { + const { AGENTMEMORY_URL: url, AGENTMEMORY_SECRET: secret } = loadConfig( + ['AGENTMEMORY_URL', 'AGENTMEMORY_SECRET'], + path + ); + if (!url || !secret) { + console.error( + `Missing AGENTMEMORY_URL / AGENTMEMORY_SECRET. Set them in the environment or in ${path}.` + ); + process.exit(1); + } + return { url, secret }; +} diff --git a/integrations/cursor/close-stale-am-sessions.mjs b/integrations/cursor/close-stale-am-sessions.mjs index d2cf08f489..bf8fee2fb3 100644 --- a/integrations/cursor/close-stale-am-sessions.mjs +++ b/integrations/cursor/close-stale-am-sessions.mjs @@ -8,23 +8,7 @@ * node integrations/cursor/close-stale-am-sessions.mjs --min-age-hours 6 --project my-project * node integrations/cursor/close-stale-am-sessions.mjs --exclude ses_abc123,def456 */ -import { existsSync, readFileSync } from 'node:fs'; -import { homedir } from 'node:os'; -import { join } from 'node:path'; - -function loadEnv() { - const envPath = join(homedir(), '.agentmemory', '.env'); - const env = {}; - if (!existsSync(envPath)) return env; - for (const line of readFileSync(envPath, 'utf-8').split('\n')) { - const trimmed = line.trim(); - if (!trimmed || trimmed.startsWith('#')) continue; - const eq = trimmed.indexOf('='); - if (eq === -1) continue; - env[trimmed.slice(0, eq).trim()] = trimmed.slice(eq + 1).trim(); - } - return env; -} +import { requireConnection } from './_env.mjs'; function parseArgs() { const args = process.argv.slice(2); @@ -57,11 +41,7 @@ function parseArgs() { async function main() { const opts = parseArgs(); - const { AGENTMEMORY_URL: restUrl, AGENTMEMORY_SECRET: secret } = loadEnv(); - if (!restUrl || !secret) { - console.error('Missing AGENTMEMORY_URL or AGENTMEMORY_SECRET in ~/.agentmemory/.env'); - process.exit(1); - } + const { url: restUrl, secret } = requireConnection(); const headers = { Authorization: `Bearer ${secret}`, diff --git a/integrations/cursor/install-local.mjs b/integrations/cursor/install-local.mjs index faac0446b9..6aae0abf02 100644 --- a/integrations/cursor/install-local.mjs +++ b/integrations/cursor/install-local.mjs @@ -4,30 +4,17 @@ import { homedir } from 'node:os'; import { dirname, join, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; import { execSync } from 'node:child_process'; +import { ENV_PATH, loadConfig } from './_env.mjs'; 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 { @@ -136,9 +123,11 @@ function disableUserHooks() { return backup; } -const env = loadEnv(ENV_PATH); +const env = loadConfig(['AGENTMEMORY_URL', 'AGENTMEMORY_SECRET', 'AGENTMEMORY_TOOLS']); if (!env.AGENTMEMORY_URL || !env.AGENTMEMORY_SECRET) { - console.error('Missing ~/.agentmemory/.env with AGENTMEMORY_URL and AGENTMEMORY_SECRET'); + console.error( + `Missing AGENTMEMORY_URL / AGENTMEMORY_SECRET. Set them in the environment or in ${ENV_PATH}.` + ); process.exit(1); } diff --git a/integrations/cursor/migrate-bad-projects.mjs b/integrations/cursor/migrate-bad-projects.mjs deleted file mode 100644 index 1c6b2a1626..0000000000 --- a/integrations/cursor/migrate-bad-projects.mjs +++ /dev/null @@ -1,128 +0,0 @@ -#!/usr/bin/env node -/** - * One-off migration: fix sessions stored with project/cwd ".cursor" - * by re-resolving the real workspace from Cursor transcript paths. - * - * Usage: - * node integrations/cursor/migrate-bad-projects.mjs # apply - * node integrations/cursor/migrate-bad-projects.mjs --dry-run - */ -import { existsSync, readFileSync } from 'node:fs'; -import { homedir } from 'node:os'; -import { join } from 'node:path'; -import { isCursorMetadataPath, resolveWorkspace } from '../../plugin/scripts/cursor/workspace.mjs'; - -const dryRun = process.argv.includes('--dry-run'); - -function loadEnv() { - const envPath = join(homedir(), '.agentmemory', '.env'); - const env = {}; - if (!existsSync(envPath)) return env; - for (const line of readFileSync(envPath, 'utf-8').split('\n')) { - const trimmed = line.trim(); - if (!trimmed || trimmed.startsWith('#')) continue; - const eq = trimmed.indexOf('='); - if (eq === -1) continue; - env[trimmed.slice(0, eq).trim()] = trimmed.slice(eq + 1).trim(); - } - return env; -} - -function isBadSession(session) { - const { project, cwd } = session; - return isCursorMetadataPath(project) || isCursorMetadataPath(cwd); -} - -async function main() { - const { AGENTMEMORY_URL: restUrl, AGENTMEMORY_SECRET: secret } = loadEnv(); - if (!restUrl || !secret) { - console.error('Missing AGENTMEMORY_URL or AGENTMEMORY_SECRET in ~/.agentmemory/.env'); - process.exit(1); - } - - const headers = { - Authorization: `Bearer ${secret}`, - 'Content-Type': 'application/json' - }; - - const listRes = await fetch(`${restUrl}/agentmemory/sessions`, { headers }); - if (!listRes.ok) { - console.error('Failed to list sessions:', listRes.status, await listRes.text()); - process.exit(1); - } - - const { sessions } = await listRes.json(); - const bad = sessions.filter(isBadSession); - console.log(`Found ${bad.length} session(s) with .cursor project/cwd (of ${sessions.length} total)`); - - const fixes = []; - const skipped = []; - - for (const session of bad) { - const resolved = resolveWorkspace({ session_id: session.id }); - if ( - !resolved?.project || - resolved.project === '.cursor' || - resolved.project === 'unknown-project' - ) { - skipped.push({ id: session.id, reason: 'could not resolve workspace', resolved }); - continue; - } - if (resolved.project === session.project && resolved.cwd === session.cwd) { - skipped.push({ id: session.id, reason: 'already correct', resolved }); - continue; - } - fixes.push({ - id: session.id, - from: { project: session.project, cwd: session.cwd }, - to: resolved, - session: { ...session, project: resolved.project, cwd: resolved.cwd } - }); - } - - for (const fix of fixes) { - console.log(` ${fix.id}: ${fix.from.project} → ${fix.to.project}`); - } - for (const s of skipped) { - console.log(` skip ${s.id}: ${s.reason}`); - } - - if (!fixes.length) { - console.log('Nothing to update.'); - return; - } - - if (dryRun) { - console.log(`Dry run: would update ${fixes.length} session(s).`); - return; - } - - const importRes = await fetch(`${restUrl}/agentmemory/import`, { - method: 'POST', - headers, - body: JSON.stringify({ - strategy: 'merge', - exportData: { - version: '0.9.21', - sessions: fixes.map((f) => f.session), - memories: [], - summaries: [], - observations: {} - } - }) - }); - - const result = await importRes.json(); - if (!importRes.ok || result.success === false) { - console.error('Import failed:', importRes.status, result); - process.exit(1); - } - - console.log('Import result:', result); - console.log(`Updated ${fixes.length} session(s).`); -} - -main().catch((err) => { - console.error(err); - process.exit(1); -}); diff --git a/integrations/cursor/verify-flow.mjs b/integrations/cursor/verify-flow.mjs index b913b28917..9399c22945 100644 --- a/integrations/cursor/verify-flow.mjs +++ b/integrations/cursor/verify-flow.mjs @@ -1,67 +1,72 @@ #!/usr/bin/env node -import { existsSync, readFileSync } from 'node:fs'; -import { homedir } from 'node:os'; +/** + * End-to-end smoke test for the Cursor plugin hook pipeline against a live + * agentmemory daemon. + * + * Every assertion polls the daemon rather than sleeping for a fixed time. + * The hook processes are deliberately not synchronous with the work they + * cause: the canonical hooks fire-and-forget their HTTP calls and exit on a + * short timer, and run-detached.mjs returns as soon as its background worker + * is spawned. A fixed sleep therefore proves nothing -- too short and a + * healthy pipeline reports FAIL, too long and a broken one still has time to + * look healthy. Polling for the state change is the only honest check. + */ +import { existsSync } from 'node:fs'; import { dirname, join, resolve } from 'node:path'; import { spawnSync } from 'node:child_process'; import { fileURLToPath } from 'node:url'; +import { requireConnection } from './_env.mjs'; const INTEGRATION_ROOT = resolve(dirname(fileURLToPath(import.meta.url))); const REPO_ROOT = resolve(INTEGRATION_ROOT, '../..'); const CURSOR_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; -} + +const POLL_INTERVAL_MS = 1000; +const POLL_TIMEOUT_MS = 90000; + +const { url, secret } = requireConnection(); +const authHeaders = { Authorization: `Bearer ${secret}` }; function runHook(script, args, payload) { - const hookEnv = { - ...process.env, - ...(env.AGENTMEMORY_URL ? { AGENTMEMORY_URL: env.AGENTMEMORY_URL } : {}), - ...(env.AGENTMEMORY_SECRET ? { AGENTMEMORY_SECRET: env.AGENTMEMORY_SECRET } : {}) - }; const r = spawnSync(process.execPath, [join(CURSOR_SCRIPTS, script), ...args], { input: JSON.stringify(payload), encoding: 'utf-8', timeout: 60000, - env: hookEnv + env: { ...process.env, AGENTMEMORY_URL: url, AGENTMEMORY_SECRET: secret } }); - return { script, status: r.status, stderr: r.stderr?.slice(0, 200) }; + return { status: r.status, stderr: r.stderr?.trim().slice(0, 300) ?? '' }; } -async function fetchSession(url, secret, id) { +async function fetchSession(id) { const r = await fetch(`${url}/agentmemory/sessions`, { - headers: { Authorization: `Bearer ${secret}` }, + headers: authHeaders, signal: AbortSignal.timeout(30000) }); - if (!r.ok) throw new Error(`sessions list ${r.status}`); + if (!r.ok) throw new Error(`GET /agentmemory/sessions -> ${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); +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); + +/** Poll until `predicate(session)` holds. Returns the last session seen. */ +async function waitFor(id, predicate, timeoutMs = POLL_TIMEOUT_MS) { + const deadline = Date.now() + timeoutMs; + let last = null; + for (;;) { + last = await fetchSession(id); + if (last && predicate(last)) return { session: last, ok: true, waitedMs: 0 }; + if (Date.now() >= deadline) return { session: last, ok: false }; + await sleep(POLL_INTERVAL_MS); + } } if (!existsSync(join(CURSOR_SCRIPTS, 'run-hook.mjs'))) { - console.error(`Missing Cursor shim at ${CURSOR_SCRIPTS}`); + console.error(`Missing Cursor shim at ${CURSOR_SCRIPTS}. Run \`npm run build\` first.`); process.exit(1); } -const repoRootNorm = join(REPO_ROOT).replace(/\\/g, '/'); +const repoRootNorm = REPO_ROOT.replace(/\\/g, '/'); const sessionId = `cursor-plugin-verify-${Date.now()}`; const basePayload = { session_id: sessionId, @@ -70,67 +75,112 @@ const basePayload = { }; console.log('=== agentmemory Cursor plugin verify ===\n'); -console.log(`Shim scripts: ${CURSOR_SCRIPTS}\n`); +console.log(`Shim scripts: ${CURSOR_SCRIPTS}`); +console.log(`Session id: ${sessionId}\n`); +// A non-2xx /livez means the daemon is up but rejecting us (usually a bad +// secret). Continuing past it turns one clear error into four confusing ones. +let livez; try { - const livez = await fetch(`${url}/agentmemory/livez`, { - headers: { Authorization: `Bearer ${secret}` }, + livez = await fetch(`${url}/agentmemory/livez`, { + headers: authHeaders, signal: AbortSignal.timeout(15000) }); - console.log(`livez: ${livez.ok ? 'ok' : livez.status}`); } catch (e) { - console.error('livez failed:', e.message); + console.error(`livez: unreachable (${e.message})`); process.exit(1); } +if (!livez.ok) { + console.error(`livez: HTTP ${livez.status} -- check AGENTMEMORY_URL / AGENTMEMORY_SECRET`); + process.exit(1); +} +console.log('livez: ok'); -const hookSteps = [ - ['run-hook.mjs', ['sessionStart'], basePayload], - [ - 'run-hook.mjs', - ['postToolUse'], - { - ...basePayload, - tool_name: 'Read', - tool_input: { path: join(REPO_ROOT, 'package.json') }, - tool_output: 'verify-flow smoke test' - } - ], - ['run-detached.mjs', ['stop'], basePayload], - ['run-detached.mjs', ['sessionEnd'], { ...basePayload, reason: 'window_close' }] -]; - -for (const step of hookSteps) { - const result = runHook(step[0], step[1], step[2]); - const label = `${step[0]} ${step[1].join(' ')}`; - console.log(`${label}: exit ${result.status}${result.stderr ? ` (${result.stderr})` : ''}`); - const waitMs = step[1][0] === 'postToolUse' ? 5000 : 2500; - await new Promise((r) => setTimeout(r, waitMs)); +const results = []; +function record(name, ok, detail) { + results.push({ name, ok, detail }); + console.log(` ${ok ? 'PASS' : 'FAIL'} ${name}${detail ? ` -- ${detail}` : ''}`); } -const session = await fetchSession(url, secret, sessionId); -if (!session) { - console.error('\nFAIL: session not found on NAS after hook pipeline'); - process.exit(1); +// 1. sessionStart: the session must show up on the daemon at all. +console.log('\n[1/4] sessionStart'); +let r = runHook('run-hook.mjs', ['sessionStart'], basePayload); +console.log(` shim exit ${r.status}${r.stderr ? ` (${r.stderr})` : ''}`); +let w = await waitFor(sessionId, (s) => Boolean(s)); +record('session registered', w.ok, w.session ? `project=${w.session.project}` : 'never appeared'); +record( + 'resolver picked the repo, not .cursor', + w.session?.project === 'agentmemory', + `got ${w.session?.project ?? '(none)'}` +); + +// 2. postToolUse: an observation must land against that session. +// +// Retried, because the daemon drops observations when it is busy -- a +// `stop` from an earlier run leaves /summarize working in the background, +// and observations posted into that window can vanish. The adapter's job +// ends at "emitted a correct POST" (test/cursor-adapter.test.ts asserts +// that deterministically against a local server); this step additionally +// checks the daemon actually recorded it, so it has to tolerate the +// daemon's own load. Each attempt varies tool_input: the dedup key is +// (sessionId, tool_name, tool_input), so a byte-identical retry would be +// discarded as a duplicate and could never succeed. +console.log('\n[2/4] postToolUse'); +const OBSERVE_ATTEMPTS = 3; +for (let attempt = 1; attempt <= OBSERVE_ATTEMPTS; attempt++) { + r = runHook('run-hook.mjs', ['postToolUse'], { + ...basePayload, + tool_name: 'Read', + tool_input: { path: join(REPO_ROOT, 'package.json'), attempt }, + tool_output: `verify-flow smoke test (attempt ${attempt})` + }); + console.log(` attempt ${attempt}: shim exit ${r.status}${r.stderr ? ` (${r.stderr})` : ''}`); + if (r.status !== 0) break; + w = await waitFor(sessionId, (s) => (s.observationCount ?? 0) >= 1, 20000); + if (w.ok) break; + if (attempt < OBSERVE_ATTEMPTS) console.log(' not recorded yet -- daemon may be busy, retrying'); +} +record( + 'observation captured', + Boolean(w.ok), + w.ok ? `obs=${w.session?.observationCount ?? 0}` : `daemon never recorded it in ${OBSERVE_ATTEMPTS} attempts` +); + +// 3. stop: run-detached returns immediately, so the only meaningful signal is +// the session reaching a terminal state on the daemon afterwards. +console.log('\n[3/4] stop (detached)'); +r = runHook('run-detached.mjs', ['stop'], basePayload); +console.log(` parent exit ${r.status}${r.stderr ? ` (${r.stderr})` : ''} (worker continues in background)`); +w = await waitFor(sessionId, (s) => s.status === 'completed' || Boolean(s.endedAt)); +record( + 'detached worker closed the session', + w.ok, + `status=${w.session?.status ?? '?'} endedAt=${w.session?.endedAt ?? '(none)'}` +); + +// 4. sessionEnd is opt-in and diagnostic only, for two reasons. Cursor 3.13.x +// frequently fails to fire it on window close ("MainThreadShellExec not +// initialized"), so `stop` is the hook the pipeline actually relies on -- +// gating on it would report a Cursor bug as an adapter bug. And it fans out +// to /crystals/auto plus /consolidate-pipeline on the daemon, which is +// heavy enough that back-to-back smoke runs start losing observations to +// the resulting load. Running it by default makes this script flaky +// against itself. +if (process.argv.includes('--with-session-end')) { + console.log('\n[4/4] sessionEnd (diagnostic only)'); + r = runHook('run-detached.mjs', ['sessionEnd'], { ...basePayload, reason: 'window_close' }); + console.log(` parent exit ${r.status}${r.stderr ? ` (${r.stderr})` : ''}`); + const final = await fetchSession(sessionId); + console.log(` session: status=${final?.status ?? '?'} obs=${final?.observationCount ?? 0}`); + console.log(' (not a pass condition -- Cursor may never fire this on window close)'); +} else { + console.log('\n[4/4] sessionEnd skipped (pass --with-session-end to exercise it)'); } -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); +const failed = results.filter((x) => !x.ok); +console.log(`\n${results.length - failed.length}/${results.length} checks passed.`); +if (failed.length) { + console.error(`FAILED: ${failed.map((f) => f.name).join(', ')}`); + process.exit(1); } -process.exit(1); +console.log('Cursor hook pipeline OK.'); diff --git a/plugin/scripts/cursor/run-detached.mjs b/plugin/scripts/cursor/run-detached.mjs index 3c59f0fe2c..5e98b69ae1 100644 --- a/plugin/scripts/cursor/run-detached.mjs +++ b/plugin/scripts/cursor/run-detached.mjs @@ -88,10 +88,32 @@ function recallSession(sessionId) { if (!sessionId) return null; return loadSessionCache()[sessionId] ?? null; } +const SYSTEM_PATH_PREFIXES = [ + "/usr/", + "/etc/", + "/bin/", + "/sbin/", + "/lib/", + "/lib64/", + "/opt/", + "/var/", + "/proc/", + "/sys/", + "/dev/", + "/run/", + "/boot/", + "/snap/", + "/nix/" +]; +function isSystemPath(value) { + const norm = normalizePathSlashes(value); + return SYSTEM_PATH_PREFIXES.some((prefix) => norm.startsWith(prefix)); +} function isCollectablePath(value) { if (typeof value !== "string" || isCursorMetadataPath(value)) return false; if (pathUnderHome(value)) return true; - if (process.platform === "win32" && /^[a-zA-Z]:[\\/]/.test(value) && pathExists(value)) return true; + if (/^[a-zA-Z]:[\\/]/.test(value)) return pathExists(value); + if (value.startsWith("/")) return !isSystemPath(value) && pathExists(value); return false; } function collectPathStrings(value, out = []) { @@ -149,9 +171,7 @@ function cleanRepoName(dirPath) { const parent = dirname(normalized); if (parent && parent !== normalized && parent !== "." && parent !== "/") return cleanRepoName(parent); } - const name = baseName.replace(/(-worktree-\d+|-worktree|-[a-f0-9]{7,40})$/i, ""); - if (/^pxread-/i.test(name)) return "pxread"; - return name || "unknown-project"; + return baseName.replace(/(-worktree-\d+|-worktree|-[a-f0-9]{7,40})$/i, "") || "unknown-project"; } function projectFromPath(targetPath) { try { @@ -406,6 +426,14 @@ function delegateHook(hookKey, data, options = {}) { }); if (child.stdout) process.stdout.write(child.stdout); if (child.stderr) process.stderr.write(child.stderr); + if (child.error) { + console.error(`[agentmemory] cursor hook "${hookKey}" could not run ${script}: ${child.error.message}`); + return 0; + } + if (child.signal) { + console.error(`[agentmemory] cursor hook "${hookKey}" (${script}) was killed by ${child.signal} -- treating as no-op`); + return 0; + } return child.status ?? 0; } //#endregion diff --git a/plugin/scripts/cursor/run-hook.mjs b/plugin/scripts/cursor/run-hook.mjs index 0bfdae450b..661a20d309 100644 --- a/plugin/scripts/cursor/run-hook.mjs +++ b/plugin/scripts/cursor/run-hook.mjs @@ -88,10 +88,32 @@ function recallSession(sessionId) { if (!sessionId) return null; return loadSessionCache()[sessionId] ?? null; } +const SYSTEM_PATH_PREFIXES = [ + "/usr/", + "/etc/", + "/bin/", + "/sbin/", + "/lib/", + "/lib64/", + "/opt/", + "/var/", + "/proc/", + "/sys/", + "/dev/", + "/run/", + "/boot/", + "/snap/", + "/nix/" +]; +function isSystemPath(value) { + const norm = normalizePathSlashes(value); + return SYSTEM_PATH_PREFIXES.some((prefix) => norm.startsWith(prefix)); +} function isCollectablePath(value) { if (typeof value !== "string" || isCursorMetadataPath(value)) return false; if (pathUnderHome(value)) return true; - if (process.platform === "win32" && /^[a-zA-Z]:[\\/]/.test(value) && pathExists(value)) return true; + if (/^[a-zA-Z]:[\\/]/.test(value)) return pathExists(value); + if (value.startsWith("/")) return !isSystemPath(value) && pathExists(value); return false; } function collectPathStrings(value, out = []) { @@ -149,9 +171,7 @@ function cleanRepoName(dirPath) { const parent = dirname(normalized); if (parent && parent !== normalized && parent !== "." && parent !== "/") return cleanRepoName(parent); } - const name = baseName.replace(/(-worktree-\d+|-worktree|-[a-f0-9]{7,40})$/i, ""); - if (/^pxread-/i.test(name)) return "pxread"; - return name || "unknown-project"; + return baseName.replace(/(-worktree-\d+|-worktree|-[a-f0-9]{7,40})$/i, "") || "unknown-project"; } function projectFromPath(targetPath) { try { @@ -349,6 +369,14 @@ function delegateHook(hookKey, data, options = {}) { }); if (child.stdout) process.stdout.write(child.stdout); if (child.stderr) process.stderr.write(child.stderr); + if (child.error) { + console.error(`[agentmemory] cursor hook "${hookKey}" could not run ${script}: ${child.error.message}`); + return 0; + } + if (child.signal) { + console.error(`[agentmemory] cursor hook "${hookKey}" (${script}) was killed by ${child.signal} -- treating as no-op`); + return 0; + } return child.status ?? 0; } //#endregion diff --git a/src/hooks/cursor/delegate.ts b/src/hooks/cursor/delegate.ts index 8130f3ce16..a33f587c84 100644 --- a/src/hooks/cursor/delegate.ts +++ b/src/hooks/cursor/delegate.ts @@ -79,5 +79,25 @@ export function delegateHook( if (child.stdout) process.stdout.write(child.stdout); if (child.stderr) process.stderr.write(child.stderr); + + // spawnSync reports a failure to launch (missing script, timeout kill) as + // status === null, so `status ?? 0` would announce success and lose the + // observation silently -- the exact failure mode that makes a memory hook + // untrustworthy. Say so on stderr, but still exit 0: agentmemory is a + // passive recorder and must never block the editor. A genuine non-zero + // exit from the canonical hook is a real decision and is passed through. + if (child.error) { + console.error( + `[agentmemory] cursor hook "${hookKey}" could not run ${script}: ${child.error.message}`, + ); + return 0; + } + if (child.signal) { + console.error( + `[agentmemory] cursor hook "${hookKey}" (${script}) was killed by ${child.signal}` + + ` -- treating as no-op`, + ); + return 0; + } return child.status ?? 0; } diff --git a/src/hooks/cursor/workspace.ts b/src/hooks/cursor/workspace.ts index 0afb5d4d6d..e1ec2a4ed7 100644 --- a/src/hooks/cursor/workspace.ts +++ b/src/hooks/cursor/workspace.ts @@ -137,12 +137,45 @@ function recallSession(sessionId: string | undefined): SessionCacheEntry | null return cache[sessionId] ?? null; } +// Absolute paths that belong to the OS rather than to any user project. A +// stray /usr/lib/... or /etc/... reference inside tool_input must not be +// allowed to resolve to a project named "lib" or "etc". +const SYSTEM_PATH_PREFIXES = [ + "/usr/", + "/etc/", + "/bin/", + "/sbin/", + "/lib/", + "/lib64/", + "/opt/", + "/var/", + "/proc/", + "/sys/", + "/dev/", + "/run/", + "/boot/", + "/snap/", + "/nix/", +]; + +function isSystemPath(value: string): boolean { + const norm = normalizePathSlashes(value); + return SYSTEM_PATH_PREFIXES.some((prefix) => norm.startsWith(prefix)); +} + +// tool_input carries whatever shape the tool used, so paths are harvested by +// walking the object. The filter has to be permissive enough to find the +// project and strict enough not to invent one. function isCollectablePath(value: unknown): value is string { if (typeof value !== "string" || isCursorMetadataPath(value)) return false; if (pathUnderHome(value)) return true; - if (process.platform === "win32" && /^[a-zA-Z]:[\\/]/.test(value) && pathExists(value)) { - return true; - } + // Windows drive-absolute: HOME is regularly on C: while the checkout sits + // on D:, so a HOME-only rule loses every cross-drive project. + if (/^[a-zA-Z]:[\\/]/.test(value)) return pathExists(value); + // POSIX-absolute outside $HOME: containers (Codespaces, devcontainers) + // check repos out at /workspaces/..., which a HOME-only rule silently + // rejects. existingAncestor() and the git lookup downstream validate it. + if (value.startsWith("/")) return !isSystemPath(value) && pathExists(value); return false; } @@ -214,7 +247,6 @@ function cleanRepoName(dirPath: string): string { } const name = baseName.replace(/(-worktree-\d+|-worktree|-[a-f0-9]{7,40})$/i, ""); - if (/^pxread-/i.test(name)) return "pxread"; return name || "unknown-project"; } diff --git a/test/cursor-workspace.test.ts b/test/cursor-workspace.test.ts index 81c3b6f488..9dcf560b8b 100644 --- a/test/cursor-workspace.test.ts +++ b/test/cursor-workspace.test.ts @@ -24,8 +24,11 @@ describe('cursor workspace resolver', () => { it('resolveWorkspace uses workspace_roots when cwd is .cursor metadata', () => { const repoRoot = join(process.cwd()).replace(/\\/g, '/'); + // resolveWorkspace persists what it resolves under this session id, so a + // fixed id would be served from the cache on the second run and stop + // exercising the workspace_roots branch this test exists to cover. const resolved = resolveWorkspace({ - session_id: 'test-session', + session_id: `metadata-cwd-${Date.now()}-${Math.random().toString(36).slice(2)}`, workspace_roots: [repoRoot], cwd: '.cursor' }); From a6a4b5caa8ec5c8d4dced0f137b742ecf810cd9b Mon Sep 17 00:00:00 2001 From: Andrew Date: Mon, 27 Jul 2026 01:32:56 +0800 Subject: [PATCH 08/18] feat(cursor): resolve the workspace from Cursor's own records The resolver only ever inferred where a session was running. On Windows the two layers meant to handle "the payload told us nothing" were both dead: decodeSlugCandidates() returned early unless the transcript directory name started with "Users-", and the transcript scan anchored its regex on $HOME, which never matches a checkout on another drive. Measured over 300 real sessions on a Windows machine, they resolved 0. Cursor knows the answer exactly and stores it, so ask it first, then fall back to better inference: - cursor-db.ts: look the session up in Cursor's SQLite storage. A hook's session_id is the composerId, so composer.composerHeaders in globalStorage maps it straight to a workspace path. Cursor 3.0 centralised that index and migrates workspaces lazily, so pre-3.0 per-workspace allComposers arrays are handled too, ordered by recency and capped. The driver is node:sqlite when present (Node >=22.5) and better-sqlite3 when installed, following src/functions/migrate.ts; with neither, every path returns null and the inference layers below take over. Never a requirement, only accuracy. - decodeSlugCandidates: add the drive-letter branch, and replace the "only the trailing segment may contain hyphens" walk with a complete search pruned by what exists on disk. It now finds Code/Andrew-tech/mcp, not just Code/cc-router. - transcript scan: match any absolute path shape rather than $HOME-prefixed ones, and only let existing directories vote, for their git root, with a minimum vote count. Without the git-root rule the winner is whatever generic directory the conversation mentioned most -- "/bin", "C:/Users". It also now runs after the slug decode rather than before it: the slug is verified against the filesystem, the scan is a guess. Correctness fixes found while validating the above: - existingAncestor could not terminate. dirname() is a fixed point at every root ("//", "C:", "D:/"), and the generalised scan feeds it "//host/path" out of every URL in a transcript. Hung the hook for minutes. - A stale path from an authoritative source silently climbed to a surviving ancestor, turning a moved D:/Andrew/Code/cc-router into the project "Code". Authoritative sources now require the directory to exist exactly. - Any project name starting with "." is rejected, not just ".cursor"; sessions were landing under ".codex". - ~/.cursor/worktrees/ is no longer treated as metadata. Those are real checkouts for Cursor's background agents, and are folded onto the repo name. AM_CURSOR_DEBUG=1 makes the resolver report which layer answered. Every layer returns the same shape, so a wrong project is otherwise undiagnosable. Same 300 sessions, session_id only, no payload: 10 resolved by the database, 8 by the slug, 12 honestly unknown (deleted projects, workspace-less windows). No wrong attributions. --- plugin/scripts/cursor/run-detached.mjs | 314 ++++++++++++++++++++++--- plugin/scripts/cursor/run-hook.mjs | 314 ++++++++++++++++++++++--- src/hooks/cursor/cursor-db.ts | 261 ++++++++++++++++++++ src/hooks/cursor/workspace.ts | 259 ++++++++++++++++---- 4 files changed, 1032 insertions(+), 116 deletions(-) create mode 100644 src/hooks/cursor/cursor-db.ts diff --git a/plugin/scripts/cursor/run-detached.mjs b/plugin/scripts/cursor/run-detached.mjs index 5e98b69ae1..0b882a6c4f 100644 --- a/plugin/scripts/cursor/run-detached.mjs +++ b/plugin/scripts/cursor/run-detached.mjs @@ -1,9 +1,195 @@ #!/usr/bin/env node +import { createRequire } from "node:module"; import { execSync, spawn, spawnSync } from "node:child_process"; import { chmodSync, closeSync, existsSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs"; import { fileURLToPath } from "node:url"; import { basename, dirname, join } from "node:path"; import { homedir } from "node:os"; +//#region src/hooks/cursor/cursor-db.ts +/** +* Exact session -> workspace lookup from Cursor's own SQLite storage. +* +* Everything else in the resolver infers the workspace: from payload fields +* Cursor may or may not send, from paths that happen to appear in tool +* arguments, from a transcript directory name whose path separators have been +* flattened into hyphens. Those work, but they are inference, and inference +* that lands on the wrong project writes a user's memories into the wrong +* place without ever reporting an error. +* +* Cursor knows the answer exactly, and stores it. The layout (reverse +* engineered; see integrations/cursor/README.md for the full picture): +* +* /globalStorage/state.vscdb +* ItemTable["composer.composerHeaders"] +* -> { allComposers: [ { composerId, workspaceIdentifier: { +* id, uri: { fsPath, ... } } } ] } +* +* A Cursor hook's `session_id` is the `composerId`, so one indexed lookup +* gives the workspace path with no guessing. +* +* Two things stop this from being the only strategy: +* +* - Cursor 3.0 (April 2026) moved this index from per-workspace databases +* into the global one, and the migration is lazy: a workspace migrates +* when it is next opened. Machines still on <=2.6, or with workspaces not +* opened since the upgrade, keep the old per-workspace `allComposers` +* array instead. Both shapes are handled below. +* - Reading SQLite needs a driver. `node:sqlite` only exists from Node 22.5, +* and this package supports Node >=20. better-sqlite3 is an optional +* dependency of the daemon, not something a hook can count on. +* +* So every failure path here returns null and the caller falls back to +* inference. This module is an accuracy upgrade, never a requirement. +*/ +const require = createRequire(import.meta.url); +let driverCache; +function requireQuietly(id) { + const previous = process.listeners("warning"); + process.removeAllListeners("warning"); + process.on("warning", (warning) => { + if (warning.name !== "ExperimentalWarning") process.emitWarning(warning); + }); + try { + return require(id); + } catch { + return null; + } finally { + process.removeAllListeners("warning"); + for (const listener of previous) process.on("warning", listener); + } +} +function loadDriver() { + if (driverCache !== void 0) return driverCache; + const nodeSqlite = requireQuietly("node:sqlite"); + if (nodeSqlite?.DatabaseSync) { + driverCache = { open: (path) => new nodeSqlite.DatabaseSync(path, { readOnly: true }) }; + return driverCache; + } + const better = requireQuietly("better-sqlite3"); + if (better) { + driverCache = { open: (path) => new better(path, { + readonly: true, + fileMustExist: true + }) }; + return driverCache; + } + driverCache = null; + return driverCache; +} +/** Read one ItemTable value. Returns null for any failure, including a locked DB. */ +function readItemTableValue(dbPath, key) { + if (!existsSync(dbPath)) return null; + const driver = loadDriver(); + if (!driver) return null; + let db = null; + try { + db = driver.open(dbPath); + const value = db.prepare("SELECT value FROM ItemTable WHERE key = ?").get(key)?.value; + if (typeof value === "string") return value; + if (value instanceof Uint8Array) return Buffer.from(value).toString("utf-8"); + return null; + } catch { + return null; + } finally { + try { + db?.close(); + } catch {} + } +} +function cursorStorageRoots() { + const home = homedir(); + const bases = []; + if (process.platform === "win32") { + const appData = process.env["APPDATA"]; + if (appData) bases.push(join(appData, "Cursor", "User")); + bases.push(join(home, "AppData", "Roaming", "Cursor", "User")); + } else if (process.platform === "darwin") bases.push(join(home, "Library", "Application Support", "Cursor", "User")); + else { + const configHome = process.env["XDG_CONFIG_HOME"]; + if (configHome) bases.push(join(configHome, "Cursor", "User")); + bases.push(join(home, ".config", "Cursor", "User")); + } + for (const base of bases) { + const globalStorage = join(base, "globalStorage"); + if (existsSync(globalStorage)) return { + globalStorage, + workspaceStorage: join(base, "workspaceStorage") + }; + } + return null; +} +function fsPathFromHeader(header) { + const uri = header?.workspaceIdentifier?.uri; + const value = uri?.fsPath ?? uri?.path; + return typeof value === "string" && value.trim() ? value : null; +} +/** Cursor 3.0+: one central index in the global database. */ +function fromGlobalIndex(sessionId, roots) { + const raw = readItemTableValue(join(roots.globalStorage, "state.vscdb"), "composer.composerHeaders"); + if (!raw) return null; + try { + const hit = JSON.parse(raw).allComposers?.find((c) => c?.composerId === sessionId); + return fsPathFromHeader(hit); + } catch { + return null; + } +} +/** `{"folder":"file:///d%3A/repo"}`, or a vscode-remote:// URI we cannot map. */ +function folderFromWorkspaceJson(workspaceDir) { + const file = join(workspaceDir, "workspace.json"); + if (!existsSync(file)) return null; + try { + const folder = JSON.parse(readFileSync(file, "utf-8")).folder; + if (typeof folder !== "string" || !folder.startsWith("file://")) return null; + return fileURLToPath(folder); + } catch { + return null; + } +} +const LEGACY_SCAN_LIMIT = 40; +function fromLegacyWorkspaceDbs(sessionId, roots) { + if (!existsSync(roots.workspaceStorage)) return null; + let dirs; + try { + dirs = readdirSync(roots.workspaceStorage).map((dir) => { + try { + return { + dir, + mtime: statSync(join(roots.workspaceStorage, dir, "state.vscdb")).mtimeMs + }; + } catch { + return null; + } + }).filter((x) => x !== null).sort((a, b) => b.mtime - a.mtime).slice(0, LEGACY_SCAN_LIMIT); + } catch { + return null; + } + for (const { dir } of dirs) { + const raw = readItemTableValue(join(roots.workspaceStorage, dir, "state.vscdb"), "composer.composerData"); + if (!raw) continue; + try { + const parsed = JSON.parse(raw); + if (!Array.isArray(parsed.allComposers)) continue; + if (!parsed.allComposers.some((c) => c?.composerId === sessionId)) continue; + return folderFromWorkspaceJson(join(roots.workspaceStorage, dir)); + } catch { + continue; + } + } + return null; +} +/** +* The workspace directory Cursor recorded for this session, or null when it +* cannot be determined (no driver, no storage, workspace-less window, or a +* remote URI that does not map to a local path). +*/ +function workspaceFromCursorDb(sessionId) { + if (!sessionId) return null; + const roots = cursorStorageRoots(); + if (!roots) return null; + return fromGlobalIndex(sessionId, roots) ?? fromLegacyWorkspaceDbs(sessionId, roots); +} +//#endregion //#region src/hooks/cursor/workspace.ts const HOME = homedir(); const CURSOR_PROJECTS_DIR = join(HOME, ".cursor", "projects"); @@ -16,6 +202,7 @@ function isCursorMetadataPath(value) { if (!value || typeof value !== "string") return false; const trimmed = normalizePathSlashes(value.trim()); if (trimmed === ".cursor") return true; + if (/(^|\/)\.cursor\/worktrees\/[^/]/.test(trimmed)) return false; return /(^|\/)\.cursor(\/|$)/.test(trimmed); } function pathUnderHome(value) { @@ -33,6 +220,7 @@ function isBadPath(value) { if (!value || typeof value !== "string") return true; const trimmed = normalizePathSlashes(value.trim()); if (!trimmed || trimmed === "/" || trimmed === ".") return true; + if (/^[a-zA-Z]:\/?$/.test(trimmed)) return true; if (isCursorMetadataPath(trimmed)) return true; if (isIdeInstallPath(trimmed)) return true; return false; @@ -136,9 +324,11 @@ function pathExists(pathValue) { } return false; } +const MAX_ANCESTOR_STEPS = 64; function existingAncestor(pathValue) { let current = pathValue; - while (current && current !== HOME && current !== "/") { + for (let step = 0; step < MAX_ANCESTOR_STEPS; step++) { + if (!current || current === HOME || current === "/") return null; if (pathExists(current)) { const resolved = process.platform === "win32" ? current.replace(/\//g, "\\") : current; try { @@ -146,7 +336,9 @@ function existingAncestor(pathValue) { } catch {} return resolved; } - current = dirname(current); + const parent = dirname(current); + if (parent === current) return null; + current = parent; } return null; } @@ -161,11 +353,24 @@ function gitRootFromPath(targetPath) { ] }).trim(); } +function gitRootNearby(startPath) { + let current = startPath; + for (let step = 0; step < MAX_ANCESTOR_STEPS; step++) { + if (!current || current === "/") return null; + if (pathExists(join(current, ".git"))) return current; + const parent = dirname(current); + if (parent === current) return null; + current = parent; + } + return null; +} function cleanRepoName(dirPath) { const normalized = normalizePathSlashes(dirPath).replace(/\/+$/, ""); if (!normalized) return "unknown-project"; const claudeWt = normalized.match(/^(.*?)\/\.claude\/worktrees\/[^/]+$/i); if (claudeWt?.[1]) return cleanRepoName(claudeWt[1]); + const cursorWt = normalized.match(/\/\.cursor\/worktrees\/([^/]+)$/i); + if (cursorWt?.[1]) return cursorWt[1].replace(/-[a-z0-9]{4,8}$/i, "") || cursorWt[1]; const baseName = basename(normalized); if (/^agent-[a-f0-9]{6,}$/i.test(baseName)) { const parent = dirname(normalized); @@ -182,19 +387,24 @@ function projectFromPath(targetPath) { } function decodeSlugCandidates(slug) { if (!slug || slug === "empty-window") return []; + if (/^\d{10,}$/.test(slug)) return []; const parts = slug.split("-"); - if (parts[0] !== "Users" || parts.length < 2) return []; + if (!parts.length) return []; const results = /* @__PURE__ */ new Set(); function walk(index, currentPath) { if (index >= parts.length) { - if (existsSync(currentPath)) results.add(currentPath); + results.add(currentPath); return; } - walk(index + 1, `${currentPath}/${parts[index]}`); - const alt = `${currentPath}/${parts.slice(index).join("-")}`; - if (existsSync(alt)) results.add(alt); + for (let take = 1; index + take <= parts.length; take++) { + const next = `${currentPath}/${parts.slice(index, index + take).join("-")}`; + if (!pathExists(next)) continue; + walk(index + take, next); + } } - walk(2, `/${parts[0]}/${parts[1]}`); + const first = parts[0]; + if (first && /^[a-zA-Z]$/.test(first)) walk(1, `${first.toUpperCase()}:`); + walk(0, ""); return [...results]; } function pickBestCandidate(candidates, preferredLabel) { @@ -226,17 +436,34 @@ function findSessionTranscript(sessionId) { } return null; } +const TRANSCRIPT_SCAN_BYTES = 25e4; +const TRANSCRIPT_CANDIDATE_LIMIT = 120; +const TRANSCRIPT_MATCH_LIMIT = 4e3; +const TRANSCRIPT_MIN_VOTES = 3; +const TRANSCRIPT_PATH_PATTERNS = [/[a-zA-Z]:[A-Za-z0-9._@+\-/]{3,240}/g, /\/[A-Za-z0-9._@+\-/]{3,240}/g]; function workspaceFromTranscriptFile(transcriptFile) { if (!transcriptFile || !existsSync(transcriptFile)) return null; - const chunk = normalizePathSlashes(readFileSync(transcriptFile, "utf-8").slice(0, 25e4)); - const escapedHome = normalizePathSlashes(HOME).replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); - const re = new RegExp(`${escapedHome}[^\\s"'\\\\]+`, "g"); + const chunk = normalizePathSlashes(readFileSync(transcriptFile, "utf-8").slice(0, TRANSCRIPT_SCAN_BYTES)); const counts = /* @__PURE__ */ new Map(); - for (const match of chunk.match(re) || []) { - if (isCursorMetadataPath(match)) continue; - const existing = existingAncestor(match); - if (!existing || existing === HOME) continue; - counts.set(existing, (counts.get(existing) || 0) + 1); + const seen = /* @__PURE__ */ new Set(); + for (const pattern of TRANSCRIPT_PATH_PATTERNS) { + pattern.lastIndex = 0; + let match; + let scanned = 0; + while ((match = pattern.exec(chunk)) !== null) { + if (++scanned > TRANSCRIPT_MATCH_LIMIT) break; + if (seen.size >= TRANSCRIPT_CANDIDATE_LIMIT) break; + const value = match[0]; + if (seen.has(value)) continue; + seen.add(value); + if (value.startsWith("//")) continue; + if (isCursorMetadataPath(value) || isIdeInstallPath(value) || isSystemPath(value)) continue; + const existing = existingDirectory(value); + if (!existing || existing === HOME || isBadPath(existing)) continue; + const root = gitRootNearby(existing); + if (!root || root === HOME || isBadPath(root)) continue; + counts.set(root, (counts.get(root) || 0) + 1); + } } let best = null; let bestCount = 0; @@ -244,15 +471,15 @@ function workspaceFromTranscriptFile(transcriptFile) { best = pathValue; bestCount = count; } - return best; + return bestCount >= TRANSCRIPT_MIN_VOTES ? best : null; } function workspaceFromSessionId(sessionId) { const hit = findSessionTranscript(sessionId); if (!hit) return null; - const fromTranscript = workspaceFromTranscriptFile(hit.transcriptFile); - if (fromTranscript) return fromTranscript; const preferredLabel = process.env["CURSOR_WORKSPACE_LABEL"] || ""; - return pickBestCandidate(decodeSlugCandidates(hit.slug), preferredLabel); + const fromSlug = pickBestCandidate(decodeSlugCandidates(hit.slug), preferredLabel); + if (fromSlug) return fromSlug; + return workspaceFromTranscriptFile(hit.transcriptFile); } function readHookStdinComplete(maxWaitMs = 3e4) { return new Promise((resolve) => { @@ -311,13 +538,25 @@ function readWorkerHookPayload() { } catch {} } } -function resolveFromPathCandidates(candidates, sessionId) { +function isMetadataProjectName(project) { + return project.startsWith("."); +} +function existingDirectory(pathValue) { + if (!pathExists(pathValue)) return null; + const resolved = process.platform === "win32" ? pathValue.replace(/\//g, "\\") : pathValue; + try { + return statSync(resolved).isFile() ? dirname(resolved) : resolved; + } catch { + return null; + } +} +function resolveFromPathCandidates(candidates, sessionId, options = {}) { for (const candidate of candidates) { if (typeof candidate !== "string" || isBadPath(candidate)) continue; - const existing = existingAncestor(candidate); - if (!existing || isIdeInstallPath(existing)) continue; + const existing = options.exact ? existingDirectory(candidate) : existingAncestor(candidate); + if (!existing || isBadPath(existing)) continue; const project = projectFromPath(existing); - if (project !== ".cursor") { + if (!isMetadataProjectName(project)) { rememberSession(sessionId, project, existing); return { project, @@ -327,6 +566,10 @@ function resolveFromPathCandidates(candidates, sessionId) { } return null; } +function debugLayer(layer, result) { + if (result && process.env["AM_CURSOR_DEBUG"] === "1") console.error(`[agentmemory] workspace resolved by ${layer}: ${result.project} (${result.cwd})`); + return result; +} function resolveWorkspace(data) { const sessionId = data?.["session_id"] ?? data?.["sessionId"]; const cached = recallSession(sessionId); @@ -334,7 +577,7 @@ function resolveWorkspace(data) { project: cached.project, cwd: cached.cwd }; - const fromPayload = resolveFromPathCandidates([ + const fromPayload = debugLayer("payload", resolveFromPathCandidates([ ...Array.isArray(data?.["workspace_roots"]) ? data["workspace_roots"] : [], ...Array.isArray(data?.["workspace_folders"]) ? data["workspace_folders"] : [], data?.["workspace_folder"], @@ -343,27 +586,22 @@ function resolveWorkspace(data) { data?.["cwd"], data?.["root_path"], data?.["project_path"] - ], sessionId); + ], sessionId)); if (fromPayload) return fromPayload; - const fromTools = resolveFromPathCandidates(collectPathStrings(data?.["tool_input"]).map(existingAncestor).filter((p) => Boolean(p) && !isIdeInstallPath(p)), sessionId); + const fromTools = debugLayer("tool_input", resolveFromPathCandidates(collectPathStrings(data?.["tool_input"]).map(existingAncestor).filter((p) => Boolean(p) && !isIdeInstallPath(p)), sessionId)); if (fromTools) return fromTools; if (sessionId) { - const fromSession = workspaceFromSessionId(sessionId); - if (fromSession && !isIdeInstallPath(fromSession)) { - const project = projectFromPath(fromSession); - rememberSession(sessionId, project, fromSession); - return { - project, - cwd: fromSession - }; - } + const fromDb = debugLayer("cursor-db", resolveFromPathCandidates([workspaceFromCursorDb(sessionId)], sessionId, { exact: true })); + if (fromDb) return fromDb; + const fromSession = debugLayer("transcript-dir", resolveFromPathCandidates([workspaceFromSessionId(sessionId)], sessionId, { exact: true })); + if (fromSession) return fromSession; } - const fromEnv = resolveFromPathCandidates([ + const fromEnv = debugLayer("env", resolveFromPathCandidates([ process.env["CURSOR_WORKSPACE_ROOT"], process.env["CURSOR_WORKSPACE_FOLDER"], process.env["PWD"], process.env["VSCODE_CWD"] - ], sessionId); + ], sessionId)); if (fromEnv) return fromEnv; const label = process.env["CURSOR_WORKSPACE_LABEL"]; if (label) { diff --git a/plugin/scripts/cursor/run-hook.mjs b/plugin/scripts/cursor/run-hook.mjs index 661a20d309..ed04310168 100644 --- a/plugin/scripts/cursor/run-hook.mjs +++ b/plugin/scripts/cursor/run-hook.mjs @@ -1,9 +1,195 @@ #!/usr/bin/env node +import { createRequire } from "node:module"; import { execSync, spawnSync } from "node:child_process"; import { basename, dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; import { closeSync, existsSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs"; import { homedir } from "node:os"; +//#region src/hooks/cursor/cursor-db.ts +/** +* Exact session -> workspace lookup from Cursor's own SQLite storage. +* +* Everything else in the resolver infers the workspace: from payload fields +* Cursor may or may not send, from paths that happen to appear in tool +* arguments, from a transcript directory name whose path separators have been +* flattened into hyphens. Those work, but they are inference, and inference +* that lands on the wrong project writes a user's memories into the wrong +* place without ever reporting an error. +* +* Cursor knows the answer exactly, and stores it. The layout (reverse +* engineered; see integrations/cursor/README.md for the full picture): +* +* /globalStorage/state.vscdb +* ItemTable["composer.composerHeaders"] +* -> { allComposers: [ { composerId, workspaceIdentifier: { +* id, uri: { fsPath, ... } } } ] } +* +* A Cursor hook's `session_id` is the `composerId`, so one indexed lookup +* gives the workspace path with no guessing. +* +* Two things stop this from being the only strategy: +* +* - Cursor 3.0 (April 2026) moved this index from per-workspace databases +* into the global one, and the migration is lazy: a workspace migrates +* when it is next opened. Machines still on <=2.6, or with workspaces not +* opened since the upgrade, keep the old per-workspace `allComposers` +* array instead. Both shapes are handled below. +* - Reading SQLite needs a driver. `node:sqlite` only exists from Node 22.5, +* and this package supports Node >=20. better-sqlite3 is an optional +* dependency of the daemon, not something a hook can count on. +* +* So every failure path here returns null and the caller falls back to +* inference. This module is an accuracy upgrade, never a requirement. +*/ +const require = createRequire(import.meta.url); +let driverCache; +function requireQuietly(id) { + const previous = process.listeners("warning"); + process.removeAllListeners("warning"); + process.on("warning", (warning) => { + if (warning.name !== "ExperimentalWarning") process.emitWarning(warning); + }); + try { + return require(id); + } catch { + return null; + } finally { + process.removeAllListeners("warning"); + for (const listener of previous) process.on("warning", listener); + } +} +function loadDriver() { + if (driverCache !== void 0) return driverCache; + const nodeSqlite = requireQuietly("node:sqlite"); + if (nodeSqlite?.DatabaseSync) { + driverCache = { open: (path) => new nodeSqlite.DatabaseSync(path, { readOnly: true }) }; + return driverCache; + } + const better = requireQuietly("better-sqlite3"); + if (better) { + driverCache = { open: (path) => new better(path, { + readonly: true, + fileMustExist: true + }) }; + return driverCache; + } + driverCache = null; + return driverCache; +} +/** Read one ItemTable value. Returns null for any failure, including a locked DB. */ +function readItemTableValue(dbPath, key) { + if (!existsSync(dbPath)) return null; + const driver = loadDriver(); + if (!driver) return null; + let db = null; + try { + db = driver.open(dbPath); + const value = db.prepare("SELECT value FROM ItemTable WHERE key = ?").get(key)?.value; + if (typeof value === "string") return value; + if (value instanceof Uint8Array) return Buffer.from(value).toString("utf-8"); + return null; + } catch { + return null; + } finally { + try { + db?.close(); + } catch {} + } +} +function cursorStorageRoots() { + const home = homedir(); + const bases = []; + if (process.platform === "win32") { + const appData = process.env["APPDATA"]; + if (appData) bases.push(join(appData, "Cursor", "User")); + bases.push(join(home, "AppData", "Roaming", "Cursor", "User")); + } else if (process.platform === "darwin") bases.push(join(home, "Library", "Application Support", "Cursor", "User")); + else { + const configHome = process.env["XDG_CONFIG_HOME"]; + if (configHome) bases.push(join(configHome, "Cursor", "User")); + bases.push(join(home, ".config", "Cursor", "User")); + } + for (const base of bases) { + const globalStorage = join(base, "globalStorage"); + if (existsSync(globalStorage)) return { + globalStorage, + workspaceStorage: join(base, "workspaceStorage") + }; + } + return null; +} +function fsPathFromHeader(header) { + const uri = header?.workspaceIdentifier?.uri; + const value = uri?.fsPath ?? uri?.path; + return typeof value === "string" && value.trim() ? value : null; +} +/** Cursor 3.0+: one central index in the global database. */ +function fromGlobalIndex(sessionId, roots) { + const raw = readItemTableValue(join(roots.globalStorage, "state.vscdb"), "composer.composerHeaders"); + if (!raw) return null; + try { + const hit = JSON.parse(raw).allComposers?.find((c) => c?.composerId === sessionId); + return fsPathFromHeader(hit); + } catch { + return null; + } +} +/** `{"folder":"file:///d%3A/repo"}`, or a vscode-remote:// URI we cannot map. */ +function folderFromWorkspaceJson(workspaceDir) { + const file = join(workspaceDir, "workspace.json"); + if (!existsSync(file)) return null; + try { + const folder = JSON.parse(readFileSync(file, "utf-8")).folder; + if (typeof folder !== "string" || !folder.startsWith("file://")) return null; + return fileURLToPath(folder); + } catch { + return null; + } +} +const LEGACY_SCAN_LIMIT = 40; +function fromLegacyWorkspaceDbs(sessionId, roots) { + if (!existsSync(roots.workspaceStorage)) return null; + let dirs; + try { + dirs = readdirSync(roots.workspaceStorage).map((dir) => { + try { + return { + dir, + mtime: statSync(join(roots.workspaceStorage, dir, "state.vscdb")).mtimeMs + }; + } catch { + return null; + } + }).filter((x) => x !== null).sort((a, b) => b.mtime - a.mtime).slice(0, LEGACY_SCAN_LIMIT); + } catch { + return null; + } + for (const { dir } of dirs) { + const raw = readItemTableValue(join(roots.workspaceStorage, dir, "state.vscdb"), "composer.composerData"); + if (!raw) continue; + try { + const parsed = JSON.parse(raw); + if (!Array.isArray(parsed.allComposers)) continue; + if (!parsed.allComposers.some((c) => c?.composerId === sessionId)) continue; + return folderFromWorkspaceJson(join(roots.workspaceStorage, dir)); + } catch { + continue; + } + } + return null; +} +/** +* The workspace directory Cursor recorded for this session, or null when it +* cannot be determined (no driver, no storage, workspace-less window, or a +* remote URI that does not map to a local path). +*/ +function workspaceFromCursorDb(sessionId) { + if (!sessionId) return null; + const roots = cursorStorageRoots(); + if (!roots) return null; + return fromGlobalIndex(sessionId, roots) ?? fromLegacyWorkspaceDbs(sessionId, roots); +} +//#endregion //#region src/hooks/cursor/workspace.ts const HOME = homedir(); const CURSOR_PROJECTS_DIR = join(HOME, ".cursor", "projects"); @@ -16,6 +202,7 @@ function isCursorMetadataPath(value) { if (!value || typeof value !== "string") return false; const trimmed = normalizePathSlashes(value.trim()); if (trimmed === ".cursor") return true; + if (/(^|\/)\.cursor\/worktrees\/[^/]/.test(trimmed)) return false; return /(^|\/)\.cursor(\/|$)/.test(trimmed); } function pathUnderHome(value) { @@ -33,6 +220,7 @@ function isBadPath(value) { if (!value || typeof value !== "string") return true; const trimmed = normalizePathSlashes(value.trim()); if (!trimmed || trimmed === "/" || trimmed === ".") return true; + if (/^[a-zA-Z]:\/?$/.test(trimmed)) return true; if (isCursorMetadataPath(trimmed)) return true; if (isIdeInstallPath(trimmed)) return true; return false; @@ -136,9 +324,11 @@ function pathExists(pathValue) { } return false; } +const MAX_ANCESTOR_STEPS = 64; function existingAncestor(pathValue) { let current = pathValue; - while (current && current !== HOME && current !== "/") { + for (let step = 0; step < MAX_ANCESTOR_STEPS; step++) { + if (!current || current === HOME || current === "/") return null; if (pathExists(current)) { const resolved = process.platform === "win32" ? current.replace(/\//g, "\\") : current; try { @@ -146,7 +336,9 @@ function existingAncestor(pathValue) { } catch {} return resolved; } - current = dirname(current); + const parent = dirname(current); + if (parent === current) return null; + current = parent; } return null; } @@ -161,11 +353,24 @@ function gitRootFromPath(targetPath) { ] }).trim(); } +function gitRootNearby(startPath) { + let current = startPath; + for (let step = 0; step < MAX_ANCESTOR_STEPS; step++) { + if (!current || current === "/") return null; + if (pathExists(join(current, ".git"))) return current; + const parent = dirname(current); + if (parent === current) return null; + current = parent; + } + return null; +} function cleanRepoName(dirPath) { const normalized = normalizePathSlashes(dirPath).replace(/\/+$/, ""); if (!normalized) return "unknown-project"; const claudeWt = normalized.match(/^(.*?)\/\.claude\/worktrees\/[^/]+$/i); if (claudeWt?.[1]) return cleanRepoName(claudeWt[1]); + const cursorWt = normalized.match(/\/\.cursor\/worktrees\/([^/]+)$/i); + if (cursorWt?.[1]) return cursorWt[1].replace(/-[a-z0-9]{4,8}$/i, "") || cursorWt[1]; const baseName = basename(normalized); if (/^agent-[a-f0-9]{6,}$/i.test(baseName)) { const parent = dirname(normalized); @@ -182,19 +387,24 @@ function projectFromPath(targetPath) { } function decodeSlugCandidates(slug) { if (!slug || slug === "empty-window") return []; + if (/^\d{10,}$/.test(slug)) return []; const parts = slug.split("-"); - if (parts[0] !== "Users" || parts.length < 2) return []; + if (!parts.length) return []; const results = /* @__PURE__ */ new Set(); function walk(index, currentPath) { if (index >= parts.length) { - if (existsSync(currentPath)) results.add(currentPath); + results.add(currentPath); return; } - walk(index + 1, `${currentPath}/${parts[index]}`); - const alt = `${currentPath}/${parts.slice(index).join("-")}`; - if (existsSync(alt)) results.add(alt); + for (let take = 1; index + take <= parts.length; take++) { + const next = `${currentPath}/${parts.slice(index, index + take).join("-")}`; + if (!pathExists(next)) continue; + walk(index + take, next); + } } - walk(2, `/${parts[0]}/${parts[1]}`); + const first = parts[0]; + if (first && /^[a-zA-Z]$/.test(first)) walk(1, `${first.toUpperCase()}:`); + walk(0, ""); return [...results]; } function pickBestCandidate(candidates, preferredLabel) { @@ -226,17 +436,34 @@ function findSessionTranscript(sessionId) { } return null; } +const TRANSCRIPT_SCAN_BYTES = 25e4; +const TRANSCRIPT_CANDIDATE_LIMIT = 120; +const TRANSCRIPT_MATCH_LIMIT = 4e3; +const TRANSCRIPT_MIN_VOTES = 3; +const TRANSCRIPT_PATH_PATTERNS = [/[a-zA-Z]:[A-Za-z0-9._@+\-/]{3,240}/g, /\/[A-Za-z0-9._@+\-/]{3,240}/g]; function workspaceFromTranscriptFile(transcriptFile) { if (!transcriptFile || !existsSync(transcriptFile)) return null; - const chunk = normalizePathSlashes(readFileSync(transcriptFile, "utf-8").slice(0, 25e4)); - const escapedHome = normalizePathSlashes(HOME).replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); - const re = new RegExp(`${escapedHome}[^\\s"'\\\\]+`, "g"); + const chunk = normalizePathSlashes(readFileSync(transcriptFile, "utf-8").slice(0, TRANSCRIPT_SCAN_BYTES)); const counts = /* @__PURE__ */ new Map(); - for (const match of chunk.match(re) || []) { - if (isCursorMetadataPath(match)) continue; - const existing = existingAncestor(match); - if (!existing || existing === HOME) continue; - counts.set(existing, (counts.get(existing) || 0) + 1); + const seen = /* @__PURE__ */ new Set(); + for (const pattern of TRANSCRIPT_PATH_PATTERNS) { + pattern.lastIndex = 0; + let match; + let scanned = 0; + while ((match = pattern.exec(chunk)) !== null) { + if (++scanned > TRANSCRIPT_MATCH_LIMIT) break; + if (seen.size >= TRANSCRIPT_CANDIDATE_LIMIT) break; + const value = match[0]; + if (seen.has(value)) continue; + seen.add(value); + if (value.startsWith("//")) continue; + if (isCursorMetadataPath(value) || isIdeInstallPath(value) || isSystemPath(value)) continue; + const existing = existingDirectory(value); + if (!existing || existing === HOME || isBadPath(existing)) continue; + const root = gitRootNearby(existing); + if (!root || root === HOME || isBadPath(root)) continue; + counts.set(root, (counts.get(root) || 0) + 1); + } } let best = null; let bestCount = 0; @@ -244,23 +471,35 @@ function workspaceFromTranscriptFile(transcriptFile) { best = pathValue; bestCount = count; } - return best; + return bestCount >= TRANSCRIPT_MIN_VOTES ? best : null; } function workspaceFromSessionId(sessionId) { const hit = findSessionTranscript(sessionId); if (!hit) return null; - const fromTranscript = workspaceFromTranscriptFile(hit.transcriptFile); - if (fromTranscript) return fromTranscript; const preferredLabel = process.env["CURSOR_WORKSPACE_LABEL"] || ""; - return pickBestCandidate(decodeSlugCandidates(hit.slug), preferredLabel); + const fromSlug = pickBestCandidate(decodeSlugCandidates(hit.slug), preferredLabel); + if (fromSlug) return fromSlug; + return workspaceFromTranscriptFile(hit.transcriptFile); +} +function isMetadataProjectName(project) { + return project.startsWith("."); +} +function existingDirectory(pathValue) { + if (!pathExists(pathValue)) return null; + const resolved = process.platform === "win32" ? pathValue.replace(/\//g, "\\") : pathValue; + try { + return statSync(resolved).isFile() ? dirname(resolved) : resolved; + } catch { + return null; + } } -function resolveFromPathCandidates(candidates, sessionId) { +function resolveFromPathCandidates(candidates, sessionId, options = {}) { for (const candidate of candidates) { if (typeof candidate !== "string" || isBadPath(candidate)) continue; - const existing = existingAncestor(candidate); - if (!existing || isIdeInstallPath(existing)) continue; + const existing = options.exact ? existingDirectory(candidate) : existingAncestor(candidate); + if (!existing || isBadPath(existing)) continue; const project = projectFromPath(existing); - if (project !== ".cursor") { + if (!isMetadataProjectName(project)) { rememberSession(sessionId, project, existing); return { project, @@ -270,6 +509,10 @@ function resolveFromPathCandidates(candidates, sessionId) { } return null; } +function debugLayer(layer, result) { + if (result && process.env["AM_CURSOR_DEBUG"] === "1") console.error(`[agentmemory] workspace resolved by ${layer}: ${result.project} (${result.cwd})`); + return result; +} function resolveWorkspace(data) { const sessionId = data?.["session_id"] ?? data?.["sessionId"]; const cached = recallSession(sessionId); @@ -277,7 +520,7 @@ function resolveWorkspace(data) { project: cached.project, cwd: cached.cwd }; - const fromPayload = resolveFromPathCandidates([ + const fromPayload = debugLayer("payload", resolveFromPathCandidates([ ...Array.isArray(data?.["workspace_roots"]) ? data["workspace_roots"] : [], ...Array.isArray(data?.["workspace_folders"]) ? data["workspace_folders"] : [], data?.["workspace_folder"], @@ -286,27 +529,22 @@ function resolveWorkspace(data) { data?.["cwd"], data?.["root_path"], data?.["project_path"] - ], sessionId); + ], sessionId)); if (fromPayload) return fromPayload; - const fromTools = resolveFromPathCandidates(collectPathStrings(data?.["tool_input"]).map(existingAncestor).filter((p) => Boolean(p) && !isIdeInstallPath(p)), sessionId); + const fromTools = debugLayer("tool_input", resolveFromPathCandidates(collectPathStrings(data?.["tool_input"]).map(existingAncestor).filter((p) => Boolean(p) && !isIdeInstallPath(p)), sessionId)); if (fromTools) return fromTools; if (sessionId) { - const fromSession = workspaceFromSessionId(sessionId); - if (fromSession && !isIdeInstallPath(fromSession)) { - const project = projectFromPath(fromSession); - rememberSession(sessionId, project, fromSession); - return { - project, - cwd: fromSession - }; - } + const fromDb = debugLayer("cursor-db", resolveFromPathCandidates([workspaceFromCursorDb(sessionId)], sessionId, { exact: true })); + if (fromDb) return fromDb; + const fromSession = debugLayer("transcript-dir", resolveFromPathCandidates([workspaceFromSessionId(sessionId)], sessionId, { exact: true })); + if (fromSession) return fromSession; } - const fromEnv = resolveFromPathCandidates([ + const fromEnv = debugLayer("env", resolveFromPathCandidates([ process.env["CURSOR_WORKSPACE_ROOT"], process.env["CURSOR_WORKSPACE_FOLDER"], process.env["PWD"], process.env["VSCODE_CWD"] - ], sessionId); + ], sessionId)); if (fromEnv) return fromEnv; const label = process.env["CURSOR_WORKSPACE_LABEL"]; if (label) { diff --git a/src/hooks/cursor/cursor-db.ts b/src/hooks/cursor/cursor-db.ts new file mode 100644 index 0000000000..1847e79d0d --- /dev/null +++ b/src/hooks/cursor/cursor-db.ts @@ -0,0 +1,261 @@ +/** + * Exact session -> workspace lookup from Cursor's own SQLite storage. + * + * Everything else in the resolver infers the workspace: from payload fields + * Cursor may or may not send, from paths that happen to appear in tool + * arguments, from a transcript directory name whose path separators have been + * flattened into hyphens. Those work, but they are inference, and inference + * that lands on the wrong project writes a user's memories into the wrong + * place without ever reporting an error. + * + * Cursor knows the answer exactly, and stores it. The layout (reverse + * engineered; see integrations/cursor/README.md for the full picture): + * + * /globalStorage/state.vscdb + * ItemTable["composer.composerHeaders"] + * -> { allComposers: [ { composerId, workspaceIdentifier: { + * id, uri: { fsPath, ... } } } ] } + * + * A Cursor hook's `session_id` is the `composerId`, so one indexed lookup + * gives the workspace path with no guessing. + * + * Two things stop this from being the only strategy: + * + * - Cursor 3.0 (April 2026) moved this index from per-workspace databases + * into the global one, and the migration is lazy: a workspace migrates + * when it is next opened. Machines still on <=2.6, or with workspaces not + * opened since the upgrade, keep the old per-workspace `allComposers` + * array instead. Both shapes are handled below. + * - Reading SQLite needs a driver. `node:sqlite` only exists from Node 22.5, + * and this package supports Node >=20. better-sqlite3 is an optional + * dependency of the daemon, not something a hook can count on. + * + * So every failure path here returns null and the caller falls back to + * inference. This module is an accuracy upgrade, never a requirement. + */ +import { createRequire } from "node:module"; +import { existsSync, readFileSync, readdirSync, statSync } from "node:fs"; +import { homedir } from "node:os"; +import { join } from "node:path"; +import { fileURLToPath } from "node:url"; + +const require = createRequire(import.meta.url); + +interface Statement { + get(...params: unknown[]): unknown; +} +interface DbHandle { + prepare(sql: string): Statement; + close(): void; +} +interface Driver { + open(path: string): DbHandle; +} + +// `undefined` = not probed yet, `null` = probed and unavailable. +let driverCache: Driver | null | undefined; + +// node:sqlite is still flagged experimental and emits a process warning the +// first time it is required. Hook stderr is surfaced in Cursor's hook log, so +// a warning on every session would be noise about an implementation detail +// the user did not ask for. Silence that one warning across the require, then +// restore whatever listeners were there. +function requireQuietly(id: string): T | null { + const previous = process.listeners("warning"); + process.removeAllListeners("warning"); + process.on("warning", (warning: Error) => { + if (warning.name !== "ExperimentalWarning") process.emitWarning(warning); + }); + try { + return require(id) as T; + } catch { + return null; + } finally { + process.removeAllListeners("warning"); + for (const listener of previous) process.on("warning", listener); + } +} + +function loadDriver(): Driver | null { + if (driverCache !== undefined) return driverCache; + + const nodeSqlite = requireQuietly<{ DatabaseSync: new (p: string, o?: object) => DbHandle }>( + "node:sqlite", + ); + if (nodeSqlite?.DatabaseSync) { + driverCache = { + open: (path) => new nodeSqlite.DatabaseSync(path, { readOnly: true }), + }; + return driverCache; + } + + // Same lazy-optional pattern the daemon uses for better-sqlite3 in + // src/functions/migrate.ts -- used when installed, never required. + const better = requireQuietly DbHandle>("better-sqlite3"); + if (better) { + driverCache = { + open: (path) => new better(path, { readonly: true, fileMustExist: true }), + }; + return driverCache; + } + + driverCache = null; + return driverCache; +} + +/** Read one ItemTable value. Returns null for any failure, including a locked DB. */ +function readItemTableValue(dbPath: string, key: string): string | null { + if (!existsSync(dbPath)) return null; + const driver = loadDriver(); + if (!driver) return null; + + let db: DbHandle | null = null; + try { + db = driver.open(dbPath); + const row = db.prepare("SELECT value FROM ItemTable WHERE key = ?").get(key) as + | { value?: unknown } + | undefined; + const value = row?.value; + if (typeof value === "string") return value; + if (value instanceof Uint8Array) return Buffer.from(value).toString("utf-8"); + return null; + } catch { + // Cursor holds the database open while running. Readers normally coexist + // fine, but a locked or half-migrated file must not break the hook. + return null; + } finally { + try { + db?.close(); + } catch {} + } +} + +export interface CursorStorageRoots { + globalStorage: string; + workspaceStorage: string; +} + +export function cursorStorageRoots(): CursorStorageRoots | null { + const home = homedir(); + const bases: string[] = []; + if (process.platform === "win32") { + const appData = process.env["APPDATA"]; + if (appData) bases.push(join(appData, "Cursor", "User")); + bases.push(join(home, "AppData", "Roaming", "Cursor", "User")); + } else if (process.platform === "darwin") { + bases.push(join(home, "Library", "Application Support", "Cursor", "User")); + } else { + const configHome = process.env["XDG_CONFIG_HOME"]; + if (configHome) bases.push(join(configHome, "Cursor", "User")); + bases.push(join(home, ".config", "Cursor", "User")); + } + + for (const base of bases) { + const globalStorage = join(base, "globalStorage"); + if (existsSync(globalStorage)) { + return { globalStorage, workspaceStorage: join(base, "workspaceStorage") }; + } + } + return null; +} + +interface ComposerHeader { + composerId?: unknown; + workspaceIdentifier?: { uri?: { fsPath?: unknown; path?: unknown } }; +} + +function fsPathFromHeader(header: ComposerHeader | undefined): string | null { + const uri = header?.workspaceIdentifier?.uri; + const value = uri?.fsPath ?? uri?.path; + return typeof value === "string" && value.trim() ? value : null; +} + +/** Cursor 3.0+: one central index in the global database. */ +function fromGlobalIndex(sessionId: string, roots: CursorStorageRoots): string | null { + const raw = readItemTableValue( + join(roots.globalStorage, "state.vscdb"), + "composer.composerHeaders", + ); + if (!raw) return null; + try { + const parsed = JSON.parse(raw) as { allComposers?: ComposerHeader[] }; + const hit = parsed.allComposers?.find((c) => c?.composerId === sessionId); + // A hit with no uri is a workspace-less "empty window" chat -- Cursor + // genuinely has no path for it, so neither do we. + return fsPathFromHeader(hit); + } catch { + return null; + } +} + +/** `{"folder":"file:///d%3A/repo"}`, or a vscode-remote:// URI we cannot map. */ +function folderFromWorkspaceJson(workspaceDir: string): string | null { + const file = join(workspaceDir, "workspace.json"); + if (!existsSync(file)) return null; + try { + const parsed = JSON.parse(readFileSync(file, "utf-8")) as { folder?: unknown }; + const folder = parsed.folder; + if (typeof folder !== "string" || !folder.startsWith("file://")) return null; + return fileURLToPath(folder); + } catch { + return null; + } +} + +// Pre-3.0 lookup means opening one database per workspace, so it is ordered +// by recency and capped: the workspace a live session belongs to was touched +// moments ago and sits at the top. A full scan of ~120 workspaces measures +// around 200ms; this ordering turns the common case into one or two opens. +const LEGACY_SCAN_LIMIT = 40; + +function fromLegacyWorkspaceDbs(sessionId: string, roots: CursorStorageRoots): string | null { + if (!existsSync(roots.workspaceStorage)) return null; + + let dirs: Array<{ dir: string; mtime: number }>; + try { + dirs = readdirSync(roots.workspaceStorage) + .map((dir) => { + try { + return { dir, mtime: statSync(join(roots.workspaceStorage, dir, "state.vscdb")).mtimeMs }; + } catch { + return null; + } + }) + .filter((x): x is { dir: string; mtime: number } => x !== null) + .sort((a, b) => b.mtime - a.mtime) + .slice(0, LEGACY_SCAN_LIMIT); + } catch { + return null; + } + + for (const { dir } of dirs) { + const raw = readItemTableValue( + join(roots.workspaceStorage, dir, "state.vscdb"), + "composer.composerData", + ); + if (!raw) continue; + try { + const parsed = JSON.parse(raw) as { allComposers?: Array<{ composerId?: unknown }> }; + // Migrated workspaces no longer carry allComposers; their sessions are + // in the global index handled above. + if (!Array.isArray(parsed.allComposers)) continue; + if (!parsed.allComposers.some((c) => c?.composerId === sessionId)) continue; + return folderFromWorkspaceJson(join(roots.workspaceStorage, dir)); + } catch { + continue; + } + } + return null; +} + +/** + * The workspace directory Cursor recorded for this session, or null when it + * cannot be determined (no driver, no storage, workspace-less window, or a + * remote URI that does not map to a local path). + */ +export function workspaceFromCursorDb(sessionId: string): string | null { + if (!sessionId) return null; + const roots = cursorStorageRoots(); + if (!roots) return null; + return fromGlobalIndex(sessionId, roots) ?? fromLegacyWorkspaceDbs(sessionId, roots); +} diff --git a/src/hooks/cursor/workspace.ts b/src/hooks/cursor/workspace.ts index e1ec2a4ed7..8b7a6fbd0a 100644 --- a/src/hooks/cursor/workspace.ts +++ b/src/hooks/cursor/workspace.ts @@ -14,6 +14,7 @@ import { import { execSync } from "node:child_process"; import { dirname, join, basename } from "node:path"; import { homedir } from "node:os"; +import { workspaceFromCursorDb } from "./cursor-db.js"; // Cursor does not hand hooks a trustworthy working directory: `cwd` can be // `.cursor`, the IDE install path (via VSCODE_CWD), or absent entirely. This @@ -48,6 +49,11 @@ export function isCursorMetadataPath(value: unknown): boolean { if (!value || typeof value !== "string") return false; const trimmed = normalizePathSlashes(value.trim()); if (trimmed === ".cursor") return true; + // ~/.cursor/worktrees/ is the exception: Cursor puts real git + // checkouts there for its background agents. Treating those as metadata + // sends the session to whatever the transcript scan guesses instead of to + // the repository the agent is actually editing. + if (/(^|\/)\.cursor\/worktrees\/[^/]/.test(trimmed)) return false; return /(^|\/)\.cursor(\/|$)/.test(trimmed); } @@ -74,6 +80,9 @@ function isBadPath(value: unknown): boolean { if (!value || typeof value !== "string") return true; const trimmed = normalizePathSlashes(value.trim()); if (!trimmed || trimmed === "/" || trimmed === ".") return true; + // A bare drive root is never a project. Cursor emits a single-letter + // transcript slug for some legacy windows ("c"), which decodes to "C:". + if (/^[a-zA-Z]:\/?$/.test(trimmed)) return true; if (isCursorMetadataPath(trimmed)) return true; if (isIdeInstallPath(trimmed)) return true; return false; @@ -203,12 +212,15 @@ function pathExists(pathValue: string): boolean { return false; } +const MAX_ANCESTOR_STEPS = 64; + // Payloads often carry a file path (tool_input.path) rather than a // directory, and sometimes a path that no longer exists. Walk up until // something real is found, then normalise a file down to its directory. function existingAncestor(pathValue: string): string | null { let current = pathValue; - while (current && current !== HOME && current !== "/") { + for (let step = 0; step < MAX_ANCESTOR_STEPS; step++) { + if (!current || current === HOME || current === "/") return null; if (pathExists(current)) { const resolved = process.platform === "win32" ? current.replace(/\//g, "\\") : current; try { @@ -218,7 +230,15 @@ function existingAncestor(pathValue: string): string | null { } catch {} return resolved; } - current = dirname(current); + // dirname() is a fixed point at every filesystem root -- dirname("//") is + // "//", dirname("C:") is "C:", dirname("D:/") is "D:/" -- so climbing + // without a progress check spins forever. Nothing produced such an input + // while this only ever saw $HOME-prefixed paths; a general path scan + // produces them constantly, because every "https://host/x" in a + // transcript contains a "//host/x". + const parent = dirname(current); + if (parent === current) return null; + current = parent; } return null; } @@ -231,6 +251,22 @@ function gitRootFromPath(targetPath: string): string { }).trim(); } +// Filesystem-only equivalent of `git rev-parse --show-toplevel`, for hot +// paths that would otherwise spawn a process per candidate. `.git` is a +// directory in a normal clone and a file in a linked worktree, so a plain +// existence check covers both. +function gitRootNearby(startPath: string): string | null { + let current = startPath; + for (let step = 0; step < MAX_ANCESTOR_STEPS; step++) { + if (!current || current === "/") return null; + if (pathExists(join(current, ".git"))) return current; + const parent = dirname(current); + if (parent === current) return null; + current = parent; + } + return null; +} + function cleanRepoName(dirPath: string): string { const normalized = normalizePathSlashes(dirPath).replace(/\/+$/, ""); if (!normalized) return "unknown-project"; @@ -238,6 +274,15 @@ function cleanRepoName(dirPath: string): string { const claudeWt = normalized.match(/^(.*?)\/\.claude\/worktrees\/[^/]+$/i); if (claudeWt?.[1]) return cleanRepoName(claudeWt[1]); + // Cursor names agent worktrees "-<4-8 char token>" under + // ~/.cursor/worktrees. Fold them back onto the repository so a background + // agent's memories land with the rest of that project's. + const cursorWt = normalized.match(/\/\.cursor\/worktrees\/([^/]+)$/i); + if (cursorWt?.[1]) { + const stripped = cursorWt[1].replace(/-[a-z0-9]{4,8}$/i, ""); + return stripped || cursorWt[1]; + } + const baseName = basename(normalized); if (/^agent-[a-f0-9]{6,}$/i.test(baseName)) { const parent = dirname(normalized); @@ -258,29 +303,49 @@ function projectFromPath(targetPath: string): string { } } -// Cursor names transcript directories after the workspace path with every -// separator flattened to "-", so "Users-me-src-my-app" is ambiguous between -// .../src/my/app and .../src/my-app. Try both splits at each position and -// keep whatever exists on disk. +// Cursor names each directory under ~/.cursor/projects after the workspace +// path with every separator flattened to "-", so the transcript directory for +// a session already encodes where that session was running. Decoding it is +// lossy in one direction only: a directory name may itself contain hyphens, +// which makes "d-Andrew-Code-cc-router" mean D:/Andrew/Code/cc-router and, +// just as validly on paper, D:/Andrew/Code/cc/router. +// +// The disambiguator is the filesystem. Try every way of grouping consecutive +// segments into one directory name, but only descend into groupings that +// actually exist -- pruning collapses what looks like a 2^segments search +// into the handful of real directories on the machine. function decodeSlugCandidates(slug: string): string[] { if (!slug || slug === "empty-window") return []; + // Cursor 3.x names workspace-less windows (started from the welcome screen) + // after a timestamp. Those never correspond to a path. + if (/^\d{10,}$/.test(slug)) return []; + const parts = slug.split("-"); - if (parts[0] !== "Users" || parts.length < 2) return []; + if (!parts.length) return []; const results = new Set(); function walk(index: number, currentPath: string): void { if (index >= parts.length) { - if (existsSync(currentPath)) results.add(currentPath); + results.add(currentPath); return; } - walk(index + 1, `${currentPath}/${parts[index]}`); - const remainder = parts.slice(index).join("-"); - const alt = `${currentPath}/${remainder}`; - if (existsSync(alt)) results.add(alt); + for (let take = 1; index + take <= parts.length; take++) { + const next = `${currentPath}/${parts.slice(index, index + take).join("-")}`; + if (!pathExists(next)) continue; + walk(index + take, next); + } } - walk(2, `/${parts[0]}/${parts[1]}`); + // A single leading letter is a Windows drive: "d-Andrew-Code" -> D:/Andrew/Code. + // Without this branch the whole function returns nothing on Windows, which + // is where HOME and the checkout most often sit on different drives. + const first = parts[0]; + if (first && /^[a-zA-Z]$/.test(first)) walk(1, `${first.toUpperCase()}:`); + // Otherwise the slug starts at the filesystem root: "Users-alice-src", + // "home-andrew-src", "workspaces-repo". + walk(0, ""); + return [...results]; } @@ -325,19 +390,74 @@ function findSessionTranscript( return null; } +const TRANSCRIPT_SCAN_BYTES = 250000; +const TRANSCRIPT_CANDIDATE_LIMIT = 120; +const TRANSCRIPT_MATCH_LIMIT = 4000; +const TRANSCRIPT_MIN_VOTES = 3; + +// Paths are normalised to forward slashes before matching, so a Windows path +// looks like "D:/repo/src/a.ts" by the time these run. +// +// Both patterns are a single character class with one bounded quantifier, on +// purpose. The obvious formulation -- /\/(?:[\w.-]+\/)+[\w.-]*/ -- nests a +// quantifier inside a quantifier, and on a 250KB transcript full of +// slash-bearing strings that backtracks badly enough to hang the hook for +// minutes. There is no clever matching to do here anyway: grab anything +// path-shaped and let the existence check below decide. +const TRANSCRIPT_PATH_PATTERNS = [ + /[a-zA-Z]:[A-Za-z0-9._@+\-/]{3,240}/g, // Windows drive-absolute + /\/[A-Za-z0-9._@+\-/]{3,240}/g, // POSIX absolute +]; + +// Last resort before environment variables: mine the session transcript for +// paths and take the directory that shows up across the most of them. +// +// This used to anchor its regex on $HOME, which quietly made the whole layer +// dead on the two most common non-trivial setups -- Windows with HOME on C: +// and the checkout on D:, and containers that check out under /workspaces. +// Match any absolute path shape instead and let existence plus the git lookup +// downstream throw out the noise (URLs, log fragments, OS paths). function workspaceFromTranscriptFile(transcriptFile: string | null): string | null { if (!transcriptFile || !existsSync(transcriptFile)) return null; - const chunk = normalizePathSlashes(readFileSync(transcriptFile, "utf-8").slice(0, 250000)); - const escapedHome = normalizePathSlashes(HOME).replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); - const re = new RegExp(`${escapedHome}[^\\s"'\\\\]+`, "g"); + const chunk = normalizePathSlashes( + readFileSync(transcriptFile, "utf-8").slice(0, TRANSCRIPT_SCAN_BYTES), + ); const counts = new Map(); - - for (const match of chunk.match(re) || []) { - if (isCursorMetadataPath(match)) continue; - const existing = existingAncestor(match); - if (!existing || existing === HOME) continue; - counts.set(existing, (counts.get(existing) || 0) + 1); + const seen = new Set(); + + // Bounded on both axes: every candidate costs filesystem walks, and a busy + // transcript can contain thousands of path-shaped strings. + for (const pattern of TRANSCRIPT_PATH_PATTERNS) { + pattern.lastIndex = 0; + let match: RegExpExecArray | null; + let scanned = 0; + while ((match = pattern.exec(chunk)) !== null) { + if (++scanned > TRANSCRIPT_MATCH_LIMIT) break; + if (seen.size >= TRANSCRIPT_CANDIDATE_LIMIT) break; + const value = match[0]; + if (seen.has(value)) continue; + seen.add(value); + // "//host/path" is the tail of a URL, not a filesystem path. + if (value.startsWith("//")) continue; + if (isCursorMetadataPath(value) || isIdeInstallPath(value) || isSystemPath(value)) continue; + // Only paths that still exist vote, and they vote for their git root. + // + // Both halves matter. Letting a path climb to whatever ancestor still + // exists (existingAncestor) means a deleted D:/repo/pkg/src/a.ts votes + // for D:/repo, and a transcript is full of such paths, so the + // shallowest common directory always wins -- a session in + // D:/Andrew/Code/pkg resolves to the project "Code". Counting existing + // directories as themselves instead just moves the problem: the winner + // becomes whatever generic directory the conversation mentioned most, + // which in practice is "/bin" or "C:/Users". Requiring a repository + // root is what makes a vote mean "this is a project". + const existing = existingDirectory(value); + if (!existing || existing === HOME || isBadPath(existing)) continue; + const root = gitRootNearby(existing); + if (!root || root === HOME || isBadPath(root)) continue; + counts.set(root, (counts.get(root) || 0) + 1); + } } let best: string | null = null; @@ -349,19 +469,32 @@ function workspaceFromTranscriptFile(transcriptFile: string | null): string | nu } } - return best; + // One passing mention of a repository is not evidence that the session was + // running in it. This layer is a guess of last resort, and a wrong guess + // files a user's memories under someone else's project -- worse than + // admitting the workspace is unknown. + return bestCount >= TRANSCRIPT_MIN_VOTES ? best : null; } function workspaceFromSessionId(sessionId: string): string | null { const hit = findSessionTranscript(sessionId); if (!hit) return null; - const fromTranscript = workspaceFromTranscriptFile(hit.transcriptFile); - if (fromTranscript) return fromTranscript; - + // Slug first. It is a lossy encoding of the workspace path, but every + // candidate it produces is verified against the filesystem, so a result is + // a directory that really exists and really matches the name Cursor gave + // this session's transcript directory. const preferredLabel = process.env["CURSOR_WORKSPACE_LABEL"] || ""; - const candidates = decodeSlugCandidates(hit.slug); - return pickBestCandidate(candidates, preferredLabel); + const fromSlug = pickBestCandidate(decodeSlugCandidates(hit.slug), preferredLabel); + if (fromSlug) return fromSlug; + + // Transcript scan last: it answers "which directory is mentioned most in + // this conversation", which is a guess, not a fact. Asked first it will + // happily answer "agentmemory" for a session about agentmemory that was + // actually running somewhere else entirely. It stays because it is the only + // thing that can place a workspace-less window that was still working on + // real files. + return workspaceFromTranscriptFile(hit.transcriptFile); } export function readHookStdinComplete(maxWaitMs = 30000): Promise { @@ -421,16 +554,39 @@ export function readWorkerHookPayload(): Record | null { } } +// A project name starting with "." is always a tool's metadata directory +// (.cursor, .codex, .claude, .vscode), never the thing the user is working on. +function isMetadataProjectName(project: string): boolean { + return project.startsWith("."); +} + +// The path exactly, or its parent when it points at a file. Unlike +// existingAncestor() this does not climb: for a workspace path that some +// source claims is authoritative, "the directory is gone" means the record is +// stale, not "use whatever ancestor still exists". Climbing there silently +// turns D:/Andrew/Code/cc-router (moved away) into the project "Code" and +// files the session's memories under it. +function existingDirectory(pathValue: string): string | null { + if (!pathExists(pathValue)) return null; + const resolved = process.platform === "win32" ? pathValue.replace(/\//g, "\\") : pathValue; + try { + return statSync(resolved).isFile() ? dirname(resolved) : resolved; + } catch { + return null; + } +} + function resolveFromPathCandidates( candidates: unknown[], sessionId: string | undefined, + options: { exact?: boolean } = {}, ): Workspace | null { for (const candidate of candidates) { if (typeof candidate !== "string" || isBadPath(candidate)) continue; - const existing = existingAncestor(candidate); - if (!existing || isIdeInstallPath(existing)) continue; + const existing = options.exact ? existingDirectory(candidate) : existingAncestor(candidate); + if (!existing || isBadPath(existing)) continue; const project = projectFromPath(existing); - if (project !== ".cursor") { + if (!isMetadataProjectName(project)) { rememberSession(sessionId, project, existing); return { project, cwd: existing }; } @@ -438,6 +594,17 @@ function resolveFromPathCandidates( return null; } +// Which layer answered is the single most useful thing to know when a session +// lands under the wrong project, and it is invisible from the outside: every +// layer returns the same shape. Set AM_CURSOR_DEBUG=1 to have the resolver say +// so on stderr, which Cursor surfaces in its hook log. +function debugLayer(layer: string, result: Workspace | null): Workspace | null { + if (result && process.env["AM_CURSOR_DEBUG"] === "1") { + console.error(`[agentmemory] workspace resolved by ${layer}: ${result.project} (${result.cwd})`); + } + return result; +} + export function resolveWorkspace(data: HookData): Workspace { const sessionId = (data?.["session_id"] ?? data?.["sessionId"]) as string | undefined; const cached = recallSession(sessionId); @@ -456,22 +623,34 @@ export function resolveWorkspace(data: HookData): Workspace { data?.["project_path"], ]; - const fromPayload = resolveFromPathCandidates(payloadCandidates, sessionId); + const fromPayload = debugLayer("payload", resolveFromPathCandidates(payloadCandidates, sessionId)); if (fromPayload) return fromPayload; const toolPaths = collectPathStrings(data?.["tool_input"]) .map(existingAncestor) .filter((p): p is string => Boolean(p) && !isIdeInstallPath(p)); - const fromTools = resolveFromPathCandidates(toolPaths, sessionId); + const fromTools = debugLayer("tool_input", resolveFromPathCandidates(toolPaths, sessionId)); if (fromTools) return fromTools; if (sessionId) { - const fromSession = workspaceFromSessionId(sessionId); - if (fromSession && !isIdeInstallPath(fromSession)) { - const project = projectFromPath(fromSession); - rememberSession(sessionId, project, fromSession); - return { project, cwd: fromSession }; - } + // Cursor's own record of where this session was running. Exact, so it is + // tried before the inference layers below -- it costs one indexed SQLite + // read (~5ms) and, because the result is cached per session, happens at + // most once per session rather than once per hook. + const fromDb = debugLayer( + "cursor-db", + resolveFromPathCandidates([workspaceFromCursorDb(sessionId)], sessionId, { exact: true }), + ); + if (fromDb) return fromDb; + + // Same validation as every other layer: both sources here already + // verified the directory exists, so `exact` keeps a stale one from + // silently climbing to a parent. + const fromSession = debugLayer( + "transcript-dir", + resolveFromPathCandidates([workspaceFromSessionId(sessionId)], sessionId, { exact: true }), + ); + if (fromSession) return fromSession; } // Env comes last: VSCODE_CWD in particular is frequently the IDE install @@ -482,7 +661,7 @@ export function resolveWorkspace(data: HookData): Workspace { process.env["PWD"], process.env["VSCODE_CWD"], ]; - const fromEnv = resolveFromPathCandidates(envCandidates, sessionId); + const fromEnv = debugLayer("env", resolveFromPathCandidates(envCandidates, sessionId)); if (fromEnv) return fromEnv; const label = process.env["CURSOR_WORKSPACE_LABEL"]; From f58b1aa3337d42a19b88f01ceeed688da3069b63 Mon Sep 17 00:00:00 2001 From: Andrew Date: Mon, 27 Jul 2026 01:38:23 +0800 Subject: [PATCH 09/18] test(cursor): cover the adapter without a daemon The adapter had four resolver unit tests and nothing else. Everything that makes it work -- picking the right canonical hook, telling it which project this is, reporting what happened, and the detached path that has to outlive a closing window -- was only ever verified by running it against a live NAS by hand, which is not something a reviewer can do. test/cursor-adapter.test.ts asserts the delegation contract against a local HTTP server and temporary stand-in hooks: every HOOK_MAP entry resolves to a canonical script that exists, every event in hooks.cursor.json is a key the dispatcher knows, AGENTMEMORY_PROJECT_NAME and the enriched cwd arrive as the hook expects, a non-zero exit is passed through, and a missing canonical hook is reported rather than swallowed. It uses async spawn throughout: spawnSync blocks the caller's event loop, so an in-process server cannot accept the connection the child is opening, and the requests appear only after the child exits -- which reads exactly like "the hook sent nothing". test/cursor-workspace.test.ts adds the branches that were found breaking real sessions: OS directories and tool metadata directories must never become a project, a bare drive root must not either, ~/.cursor/worktrees is a real checkout rather than metadata, an IDE install path stays rejected, tool_input resolves outside $HOME (the container layout), and the ancestor walk terminates on paths whose parent is themselves. Also fixes what the missing-hook test exposed: a canonical hook that is not there let node start and exit 1 with a module-not-found stack, which the adapter forwarded as if the hook had decided to fail. It now checks first and says what to do about it. And the node:sqlite experimental warning was not actually being suppressed -- process.emitWarning defers to the next tick, so restoring listeners in a finally block happened before the warning existed. --- plugin/scripts/cursor/run-detached.mjs | 20 +- plugin/scripts/cursor/run-hook.mjs | 22 ++- src/hooks/cursor/cursor-db.ts | 32 ++- src/hooks/cursor/delegate.ts | 19 +- test/cursor-adapter.test.ts | 260 +++++++++++++++++++++++++ test/cursor-workspace.test.ts | 145 +++++++++++--- 6 files changed, 451 insertions(+), 47 deletions(-) create mode 100644 test/cursor-adapter.test.ts diff --git a/plugin/scripts/cursor/run-detached.mjs b/plugin/scripts/cursor/run-detached.mjs index 0b882a6c4f..996199a065 100644 --- a/plugin/scripts/cursor/run-detached.mjs +++ b/plugin/scripts/cursor/run-detached.mjs @@ -43,19 +43,23 @@ import { homedir } from "node:os"; */ const require = createRequire(import.meta.url); let driverCache; -function requireQuietly(id) { +let warningFilterInstalled = false; +function suppressSqliteExperimentalWarning() { + if (warningFilterInstalled) return; + warningFilterInstalled = true; const previous = process.listeners("warning"); process.removeAllListeners("warning"); process.on("warning", (warning) => { - if (warning.name !== "ExperimentalWarning") process.emitWarning(warning); + if (warning.name === "ExperimentalWarning" && /sqlite/i.test(warning.message)) return; + for (const listener of previous) listener(warning); }); +} +function requireQuietly(id) { + suppressSqliteExperimentalWarning(); try { return require(id); } catch { return null; - } finally { - process.removeAllListeners("warning"); - for (const listener of previous) process.on("warning", listener); } } function loadDriver() { @@ -650,8 +654,12 @@ function enrichPayload(data) { } function delegateHook(hookKey, data, options = {}) { const script = HOOK_MAP[hookKey]; - const { project, payload } = enrichPayload(data); const scriptPath = join(options.officialDir ?? defaultOfficialDir(), script); + if (!existsSync(scriptPath)) { + console.error(`[agentmemory] cursor hook "${hookKey}": canonical hook not found at ${scriptPath}. Run \`npm run build\` in the agentmemory checkout.`); + return 0; + } + const { project, payload } = enrichPayload(data); const child = spawnSync(process.execPath, [scriptPath], { input: JSON.stringify(payload), env: { diff --git a/plugin/scripts/cursor/run-hook.mjs b/plugin/scripts/cursor/run-hook.mjs index ed04310168..0f77534c3e 100644 --- a/plugin/scripts/cursor/run-hook.mjs +++ b/plugin/scripts/cursor/run-hook.mjs @@ -1,9 +1,9 @@ #!/usr/bin/env node import { createRequire } from "node:module"; import { execSync, spawnSync } from "node:child_process"; +import { closeSync, existsSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs"; import { basename, dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; -import { closeSync, existsSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs"; import { homedir } from "node:os"; //#region src/hooks/cursor/cursor-db.ts /** @@ -43,19 +43,23 @@ import { homedir } from "node:os"; */ const require = createRequire(import.meta.url); let driverCache; -function requireQuietly(id) { +let warningFilterInstalled = false; +function suppressSqliteExperimentalWarning() { + if (warningFilterInstalled) return; + warningFilterInstalled = true; const previous = process.listeners("warning"); process.removeAllListeners("warning"); process.on("warning", (warning) => { - if (warning.name !== "ExperimentalWarning") process.emitWarning(warning); + if (warning.name === "ExperimentalWarning" && /sqlite/i.test(warning.message)) return; + for (const listener of previous) listener(warning); }); +} +function requireQuietly(id) { + suppressSqliteExperimentalWarning(); try { return require(id); } catch { return null; - } finally { - process.removeAllListeners("warning"); - for (const listener of previous) process.on("warning", listener); } } function loadDriver() { @@ -593,8 +597,12 @@ function enrichPayload(data) { } function delegateHook(hookKey, data, options = {}) { const script = HOOK_MAP[hookKey]; - const { project, payload } = enrichPayload(data); const scriptPath = join(options.officialDir ?? defaultOfficialDir(), script); + if (!existsSync(scriptPath)) { + console.error(`[agentmemory] cursor hook "${hookKey}": canonical hook not found at ${scriptPath}. Run \`npm run build\` in the agentmemory checkout.`); + return 0; + } + const { project, payload } = enrichPayload(data); const child = spawnSync(process.execPath, [scriptPath], { input: JSON.stringify(payload), env: { diff --git a/src/hooks/cursor/cursor-db.ts b/src/hooks/cursor/cursor-db.ts index 1847e79d0d..538886e4ea 100644 --- a/src/hooks/cursor/cursor-db.ts +++ b/src/hooks/cursor/cursor-db.ts @@ -55,24 +55,36 @@ interface Driver { // `undefined` = not probed yet, `null` = probed and unavailable. let driverCache: Driver | null | undefined; -// node:sqlite is still flagged experimental and emits a process warning the -// first time it is required. Hook stderr is surfaced in Cursor's hook log, so -// a warning on every session would be noise about an implementation detail -// the user did not ask for. Silence that one warning across the require, then -// restore whatever listeners were there. -function requireQuietly(id: string): T | null { +// node:sqlite is still flagged experimental and emits a process warning on +// load. Hook stderr is surfaced in Cursor's hook log, so that would put a +// paragraph about an implementation detail in front of the user on every +// session that reaches this module. +// +// The filter is installed once and left in place, rather than wrapped around +// the require, because process.emitWarning defers the actual emission to the +// next tick: restoring the original listeners in a `finally` happens before +// the warning is ever emitted, so the wrapping approach silences nothing. It +// is scoped as tightly as it can be -- only this one warning is dropped, and +// everything else is re-emitted untouched. +let warningFilterInstalled = false; + +function suppressSqliteExperimentalWarning(): void { + if (warningFilterInstalled) return; + warningFilterInstalled = true; const previous = process.listeners("warning"); process.removeAllListeners("warning"); process.on("warning", (warning: Error) => { - if (warning.name !== "ExperimentalWarning") process.emitWarning(warning); + if (warning.name === "ExperimentalWarning" && /sqlite/i.test(warning.message)) return; + for (const listener of previous) listener(warning); }); +} + +function requireQuietly(id: string): T | null { + suppressSqliteExperimentalWarning(); try { return require(id) as T; } catch { return null; - } finally { - process.removeAllListeners("warning"); - for (const listener of previous) process.on("warning", listener); } } diff --git a/src/hooks/cursor/delegate.ts b/src/hooks/cursor/delegate.ts index a33f587c84..b123d3332a 100644 --- a/src/hooks/cursor/delegate.ts +++ b/src/hooks/cursor/delegate.ts @@ -1,4 +1,5 @@ import { spawnSync } from "node:child_process"; +import { existsSync } from "node:fs"; import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; import { resolveWorkspace } from "./workspace.js"; @@ -64,9 +65,25 @@ export function delegateHook( options: DelegateOptions = {}, ): number { const script = HOOK_MAP[hookKey]; - const { project, payload } = enrichPayload(data); const scriptPath = join(options.officialDir ?? defaultOfficialDir(), script); + // Checked explicitly rather than left to the spawn: node starts fine and + // then exits 1 with a module-not-found stack, which the block below would + // forward as a deliberate non-zero decision from the hook, and which lands + // a Node stack trace in Cursor's hook log. This is a real installation + // state -- the plugin ships built .mjs, so a source checkout that has not + // run `npm run build` hits it -- and it deserves an answer the user can act + // on rather than a stack trace. + if (!existsSync(scriptPath)) { + console.error( + `[agentmemory] cursor hook "${hookKey}": canonical hook not found at ${scriptPath}.` + + ` Run \`npm run build\` in the agentmemory checkout.`, + ); + return 0; + } + + const { project, payload } = enrichPayload(data); + const child = spawnSync(process.execPath, [scriptPath], { input: JSON.stringify(payload), // resolveProject() in the canonical hooks reads this before falling back diff --git a/test/cursor-adapter.test.ts b/test/cursor-adapter.test.ts new file mode 100644 index 0000000000..556ee464bf --- /dev/null +++ b/test/cursor-adapter.test.ts @@ -0,0 +1,260 @@ +import { describe, it, expect, beforeAll, afterAll } from "vitest"; +import { createServer, type Server } from "node:http"; +import { spawn } from "node:child_process"; +import { mkdtempSync, mkdirSync, writeFileSync, existsSync, rmSync, readFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { basename, join } from "node:path"; +import { HOOK_MAP, delegateHook, isCursorHookKey } from "../src/hooks/cursor/delegate.js"; + +// What the Cursor adapter is responsible for is narrow and testable without a +// daemon: pick the right canonical hook, tell it which project this is, hand +// it the payload, and report what happened. These tests cover exactly that. +// +// They deliberately do not use spawnSync. spawnSync blocks the calling +// process's event loop, so an in-process HTTP server cannot accept the very +// connection the child is making -- the requests arrive only after the child +// has exited, which reads as "the hook sent nothing" and sends you hunting a +// bug that is not there. + +const REPO_ROOT = join(import.meta.dirname, ".."); +const CURSOR_SCRIPTS = join(REPO_ROOT, "plugin", "scripts", "cursor"); +const OFFICIAL_SCRIPTS = join(REPO_ROOT, "plugin", "scripts"); + +const uniqueId = (prefix: string): string => + `${prefix}-${Date.now()}-${Math.random().toString(36).slice(2)}`; + +interface Capture { + url: string; + body: unknown; +} + +function startCaptureServer(): Promise<{ url: string; captures: Capture[]; close: () => void }> { + const captures: Capture[] = []; + const server: Server = createServer((req, res) => { + let raw = ""; + req.on("data", (c) => (raw += c)); + req.on("end", () => { + let body: unknown = raw; + try { + body = JSON.parse(raw); + } catch {} + captures.push({ url: req.url ?? "", body }); + res.writeHead(200, { "Content-Type": "application/json" }); + res.end(JSON.stringify({ ok: true, sessions: [] })); + }); + }); + return new Promise((resolve) => { + server.listen(0, "127.0.0.1", () => { + const address = server.address(); + const port = typeof address === "object" && address ? address.port : 0; + resolve({ + url: `http://127.0.0.1:${port}`, + captures, + close: () => server.close(), + }); + }); + }); +} + +function runShim( + script: string, + args: string[], + payload: unknown, + env: Record, +): Promise<{ code: number | null; stderr: string }> { + return new Promise((resolve) => { + const child = spawn(process.execPath, [join(CURSOR_SCRIPTS, script), ...args], { + env: { ...process.env, ...env }, + stdio: ["pipe", "pipe", "pipe"], + }); + let stderr = ""; + child.stderr.on("data", (c) => (stderr += c)); + child.stdout.resume(); + child.stdin.end(JSON.stringify(payload)); + child.on("close", (code) => resolve({ code, stderr })); + }); +} + +const sleep = (ms: number): Promise => new Promise((r) => setTimeout(r, ms)); + +async function waitForCapture( + captures: Capture[], + predicate: (c: Capture) => boolean, + timeoutMs = 15000, +): Promise { + const deadline = Date.now() + timeoutMs; + while (Date.now() < deadline) { + const hit = captures.find(predicate); + if (hit) return hit; + await sleep(50); + } + return null; +} + +describe("cursor hook map", () => { + // The map is the only thing standing between a Cursor lifecycle event and + // the hook that handles it, and its values are bare strings. A typo here + // does not throw: the hook silently stops recording and nothing reports it. + it("every Cursor event maps to a canonical hook that exists", () => { + const missing = Object.entries(HOOK_MAP).filter( + ([, script]) => !existsSync(join(OFFICIAL_SCRIPTS, script)), + ); + expect(missing).toEqual([]); + }); + + it("covers the events hooks.cursor.json declares", () => { + const config = JSON.parse( + readFileSync(join(REPO_ROOT, "plugin", "hooks", "hooks.cursor.json"), "utf-8"), + ) as { hooks: Record }; + for (const event of Object.keys(config.hooks)) { + expect(isCursorHookKey(event), `hooks.cursor.json declares "${event}"`).toBe(true); + } + }); +}); + +describe("delegateHook", () => { + let dir: string; + + beforeAll(() => { + dir = mkdtempSync(join(tmpdir(), "am-cursor-delegate-")); + // A stand-in for a canonical hook: records the environment and payload it + // was handed so the adapter's contract with it can be asserted. + writeFileSync( + join(dir, "session-start.mjs"), + [ + "let input = '';", + "for await (const chunk of process.stdin) input += chunk;", + "process.stdout.write(JSON.stringify({", + " project: process.env.AGENTMEMORY_PROJECT_NAME,", + " payload: JSON.parse(input || '{}'),", + "}));", + ].join("\n"), + ); + writeFileSync(join(dir, "stop.mjs"), "process.exit(3);"); + }); + + afterAll(() => rmSync(dir, { recursive: true, force: true })); + + it("passes the resolved project through the environment and cwd through the payload", () => { + const workspace = join(dir, "my-test-project"); + mkdirSync(workspace, { recursive: true }); + + const chunks: string[] = []; + const write = process.stdout.write.bind(process.stdout); + process.stdout.write = ((c: string) => { + chunks.push(String(c)); + return true; + }) as typeof process.stdout.write; + try { + delegateHook( + "sessionStart", + { session_id: uniqueId("delegate"), workspace_roots: [workspace] }, + { officialDir: dir }, + ); + } finally { + process.stdout.write = write; + } + + const seen = JSON.parse(chunks.join("")) as { + project: string; + payload: { cwd: string; session_id: string }; + }; + // resolveProject() in the canonical hooks reads AGENTMEMORY_PROJECT_NAME + // before anything else; that is the whole delegation mechanism. + expect(seen.project).toBe("my-test-project"); + expect(basename(seen.payload.cwd)).toBe("my-test-project"); + expect(seen.payload.session_id).toBeTruthy(); + }); + + it("propagates a non-zero exit from the canonical hook", () => { + expect(delegateHook("stop", { session_id: uniqueId("exit") }, { officialDir: dir })).toBe(3); + }); + + it("reports a hook that cannot be launched instead of returning success", () => { + const errors: string[] = []; + const original = console.error; + console.error = (...args: unknown[]) => errors.push(args.join(" ")); + let status: number; + try { + status = delegateHook( + "preToolUse", // pre-tool-use.mjs does not exist in the temp dir + { session_id: uniqueId("missing") }, + { officialDir: join(dir, "does-not-exist") }, + ); + } finally { + console.error = original; + } + // Fail open -- a memory hook must never block the editor -- but say so, + // rather than reporting the silent loss as success. The message has to be + // actionable: this is what a source checkout that never ran the build + // hits, and a Node module-not-found stack would not explain it. + expect(status).toBe(0); + expect(errors.join("\n")).toMatch(/canonical hook not found/); + expect(errors.join("\n")).toMatch(/npm run build/); + }); +}); + +describe("built shims against a local server", () => { + let server: Awaited>; + + beforeAll(async () => { + server = await startCaptureServer(); + }); + afterAll(() => server.close()); + + const hookEnv = (): Record => ({ + AGENTMEMORY_URL: server.url, + AGENTMEMORY_SECRET: "test-secret", + }); + + it("run-hook delivers sessionStart with the resolved project", async () => { + const workspace = mkdtempSync(join(tmpdir(), "am-cursor-ws-")); + const sessionId = uniqueId("shim-start"); + + const { code } = await runShim( + "run-hook.mjs", + ["sessionStart"], + { session_id: sessionId, workspace_roots: [workspace.replace(/\\/g, "/")] }, + hookEnv(), + ); + expect(code).toBe(0); + + const hit = await waitForCapture(server.captures, (c) => + c.url.includes("/agentmemory/session/start"), + ); + expect(hit, "no session/start request reached the server").not.toBeNull(); + const body = hit!.body as { sessionId: string; project: string; cwd: string }; + expect(body.sessionId).toBe(sessionId); + expect(body.project).toBe(basename(workspace)); + rmSync(workspace, { recursive: true, force: true }); + }, 30000); + + it("run-detached completes the work in its background worker", async () => { + const workspace = mkdtempSync(join(tmpdir(), "am-cursor-ws-")); + const sessionId = uniqueId("shim-stop"); + const before = server.captures.length; + + // The parent's exit says only that the worker was spawned. What matters + // is that the detached worker -- which outlives a closing Cursor window -- + // actually reaches the daemon. + const { code } = await runShim( + "run-detached.mjs", + ["stop"], + { session_id: sessionId, workspace_roots: [workspace.replace(/\\/g, "/")] }, + hookEnv(), + ); + expect(code).toBe(0); + + const hit = await waitForCapture( + server.captures, + (c, ) => + server.captures.indexOf(c) >= before && + typeof c.body === "object" && + c.body !== null && + (c.body as { sessionId?: string }).sessionId === sessionId, + 30000, + ); + expect(hit, "detached worker never reached the server").not.toBeNull(); + rmSync(workspace, { recursive: true, force: true }); + }, 45000); +}); diff --git a/test/cursor-workspace.test.ts b/test/cursor-workspace.test.ts index 9dcf560b8b..7942f9da79 100644 --- a/test/cursor-workspace.test.ts +++ b/test/cursor-workspace.test.ts @@ -1,5 +1,7 @@ import { describe, it, expect } from 'vitest'; -import { join } from 'node:path'; +import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { basename, join } from 'node:path'; import { isCursorMetadataPath, normalizePathSlashes, @@ -7,6 +9,32 @@ import { resolveWorkspace } from '../src/hooks/cursor/workspace.js'; +// resolveWorkspace caches per session id, so every test needs a fresh one or +// it is served the previous run's answer instead of exercising its branch. +const sessionId = (label: string): string => + `${label}-${Date.now()}-${Math.random().toString(36).slice(2)}`; + +// The last resort before "unknown" reads the environment. Tests that assert a +// payload was rejected have to blank it, or the developer's own shell (PWD) +// answers instead and the assertion passes for the wrong reason. +const ENV_KEYS = [ + 'CURSOR_WORKSPACE_ROOT', + 'CURSOR_WORKSPACE_FOLDER', + 'CURSOR_WORKSPACE_LABEL', + 'PWD', + 'VSCODE_CWD' +]; + +function withoutWorkspaceEnv(fn: () => T): T { + const saved = ENV_KEYS.map((k) => [k, process.env[k]] as const); + for (const k of ENV_KEYS) delete process.env[k]; + try { + return fn(); + } finally { + for (const [k, v] of saved) if (v !== undefined) process.env[k] = v; + } +} + describe('cursor workspace resolver', () => { it('isCursorMetadataPath rejects substring false positives', () => { expect(isCursorMetadataPath('.cursor')).toBe(true); @@ -15,6 +43,13 @@ describe('cursor workspace resolver', () => { expect(isCursorMetadataPath('/home/user/.cursor-workspace-clone')).toBe(false); }); + it('treats ~/.cursor/worktrees as real checkouts, not metadata', () => { + // Cursor puts background-agent worktrees there. Classifying them as + // metadata sends those sessions to whatever the transcript scan guesses. + expect(isCursorMetadataPath('/home/me/.cursor/worktrees/myrepo-a1b2')).toBe(false); + expect(isCursorMetadataPath('/home/me/.cursor/extensions')).toBe(true); + }); + it('pathUnderHome requires a path-component boundary after HOME', () => { const home = normalizePathSlashes(process.env.HOME || process.env.USERPROFILE || '/home/alice'); expect(pathUnderHome(home)).toBe(true); @@ -22,27 +57,91 @@ describe('cursor workspace resolver', () => { expect(pathUnderHome(`${home}-backup`)).toBe(false); }); - it('resolveWorkspace uses workspace_roots when cwd is .cursor metadata', () => { - const repoRoot = join(process.cwd()).replace(/\\/g, '/'); - // resolveWorkspace persists what it resolves under this session id, so a - // fixed id would be served from the cache on the second run and stop - // exercising the workspace_roots branch this test exists to cover. - const resolved = resolveWorkspace({ - session_id: `metadata-cwd-${Date.now()}-${Math.random().toString(36).slice(2)}`, - workspace_roots: [repoRoot], - cwd: '.cursor' - }); - expect(resolved.project).toBe('agentmemory'); - expect(normalizePathSlashes(resolved.cwd)).toBe(repoRoot); - }); - - it('resolveWorkspace uses tool_input paths under home', () => { - const repoRoot = join(process.cwd()).replace(/\\/g, '/'); - const resolved = resolveWorkspace({ - session_id: `tool-${Date.now()}`, - tool_input: { path: `${repoRoot}/package.json` } - }); - expect(resolved.project).toBe('agentmemory'); - expect(normalizePathSlashes(resolved.cwd)).toBe(repoRoot); + it('uses workspace_roots when cwd is .cursor metadata', () => { + const dir = mkdtempSync(join(tmpdir(), 'am-ws-')); + try { + const resolved = resolveWorkspace({ + session_id: sessionId('metadata-cwd'), + workspace_roots: [normalizePathSlashes(dir)], + cwd: '.cursor' + }); + expect(resolved.project).toBe(basename(dir)); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); + + it('resolves a tool_input file path to its directory, outside $HOME', () => { + // Doubles as the container case: on CI the temp dir is /tmp/... (POSIX + // absolute, not under $HOME), which a HOME-only rule silently rejected -- + // the same way it rejects a Codespaces checkout under /workspaces. + const dir = mkdtempSync(join(tmpdir(), 'am-ws-')); + writeFileSync(join(dir, 'package.json'), '{}'); + try { + const resolved = resolveWorkspace({ + session_id: sessionId('tool-input'), + tool_input: { path: normalizePathSlashes(join(dir, 'package.json')) } + }); + expect(resolved.project).toBe(basename(dir)); + expect(normalizePathSlashes(resolved.cwd)).toBe(normalizePathSlashes(dir)); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); + + it('never reports an OS directory as the project', () => { + // A stray /usr/lib/... in tool_input must not produce a project "lib". + const resolved = withoutWorkspaceEnv(() => + resolveWorkspace({ + session_id: sessionId('system-path'), + tool_input: { path: '/usr/lib/node_modules/whatever.js' } + }) + ); + expect(resolved.project).toBe('unknown-project'); + }); + + it('never reports a tool metadata directory as the project', () => { + // Sessions were landing under ".codex"; only ".cursor" used to be blocked. + const home = process.env.HOME || process.env.USERPROFILE || tmpdir(); + const dotDir = join(home, `.am-test-dot-${Date.now()}`); + mkdirSync(dotDir, { recursive: true }); + try { + const resolved = withoutWorkspaceEnv(() => + resolveWorkspace({ session_id: sessionId('dot-dir'), cwd: normalizePathSlashes(dotDir) }) + ); + expect(resolved.project).toBe('unknown-project'); + } finally { + rmSync(dotDir, { recursive: true, force: true }); + } + }); + + it('never reports a bare drive root as the project', () => { + const resolved = withoutWorkspaceEnv(() => + resolveWorkspace({ session_id: sessionId('drive-root'), cwd: 'C:/' }) + ); + expect(resolved.project).toBe('unknown-project'); + }); + + it('terminates on paths whose parent is itself', () => { + // Regression: the ancestor walk used dirname() with only a `!== "/"` + // guard, but dirname is a fixed point at every root -- dirname("//") is + // "//", dirname("C:") is "C:". Any URL-shaped path ("//host/x", which the + // transcript scan produces constantly) spun forever and hung the hook. + const started = Date.now(); + for (const cwd of ['//', '//host/share/project', 'C:', 'D:/', '/']) { + withoutWorkspaceEnv(() => resolveWorkspace({ session_id: sessionId('root-ish'), cwd })); + } + expect(Date.now() - started).toBeLessThan(10000); + }); + + it('ignores an IDE install directory', () => { + const resolved = withoutWorkspaceEnv(() => + resolveWorkspace({ + session_id: sessionId('ide-install'), + // VSCODE_CWD leaks this shape and used to yield the project "cursor". + cwd: 'C:/Users/me/AppData/Local/Programs/cursor' + }) + ); + expect(resolved.project).not.toBe('cursor'); }); }); From fb3e4f16b83f53f8ff7aa73dcfd82fb5782d34a0 Mon Sep 17 00:00:00 2001 From: Andrew Date: Mon, 27 Jul 2026 01:41:15 +0800 Subject: [PATCH 10/18] docs(cursor): explain why the adapter is shaped the way it is The code now carries a lot of decisions that look arbitrary in isolation: an eight-layer resolver, a SQLite read from another application's storage, an exhaustive-but-pruned search over a hyphen-flattened directory name, two processes for one hook. Each of those exists because of something specific Cursor does, and none of it is discoverable from the code alone. Documents the delegation flow, what differs from the Claude Code hooks and what it costs, why stop/sessionEnd are detached, Cursor's on-disk storage as reverse engineered (including the 3.0 index migration and the fact that a hook's session_id is the composerId), the resolution chain layer by layer, and the measured behaviour over 300 real sessions. --- integrations/cursor/README.md | 311 +++++++++++++++++++++++++++++----- 1 file changed, 269 insertions(+), 42 deletions(-) diff --git a/integrations/cursor/README.md b/integrations/cursor/README.md index 031976d2f9..7af7e3c54e 100644 --- a/integrations/cursor/README.md +++ b/integrations/cursor/README.md @@ -1,27 +1,34 @@ # agentmemory for Cursor -Cursor-native plugin: **lifecycle hooks** (thin shim + workspace resolver), **MCP**, and shared **skills**. +Cursor-native plugin: **lifecycle hooks**, **MCP**, and shared **skills**. -Hooks delegate to the canonical compiled scripts in `plugin/scripts/*.mjs` (from `src/hooks/*.ts`). The only Cursor-specific code lives in `plugin/scripts/cursor/`. +The hooks are the canonical ones. `plugin/scripts/*.mjs` — compiled from +`src/hooks/*.ts` and shared with Claude Code, Codex and Copilot — do all the +work. Cursor gets a thin adapter in front of them, compiled from +`src/hooks/cursor/*.ts` through the same tsdown pipeline, and nothing else. + +--- ## Quick local install -Prereq: `~/.agentmemory/.env` with `AGENTMEMORY_URL` and `AGENTMEMORY_SECRET`. +Prereq: `AGENTMEMORY_URL` and `AGENTMEMORY_SECRET`, in the environment or in +`~/.agentmemory/.env`. ```bash +npm run build node integrations/cursor/install-local.mjs node integrations/cursor/verify-flow.mjs ``` Then in Cursor: -1. **Settings → Plugins → Add marketplace** → select the **repo root** - `` +1. **Settings → Plugins → Add marketplace** → select the **repo root** + `` (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 `scripts/cursor/run-hook.mjs` or `run-detached.mjs` +5. Confirm the hooks log shows `scripts/cursor/run-hook.mjs` or `run-detached.mjs` Only after plugin hooks are confirmed: @@ -29,59 +36,279 @@ Only after plugin hooks are confirmed: node integrations/cursor/install-local.mjs --clear-user-hooks ``` +--- + ## Layout ```text -agentmemory/ ← marketplace root (git repo) +agentmemory/ ← marketplace root (git repo) .cursor-plugin/marketplace.json plugin/ .cursor-plugin/plugin.json - hooks/hooks.cursor.json ← Cursor camelCase format - scripts/cursor/ - workspace.mjs ← resolveWorkspace() - run-hook.mjs ← shim → plugin/scripts/*.mjs - run-detached.mjs ← non-blocking stop / sessionEnd - scripts/*.mjs ← canonical hooks (shared with Claude/Codex) + hooks/hooks.cursor.json ← Cursor's camelCase lifecycle names + scripts/cursor/ ← built from src/hooks/cursor/ + run-hook.mjs ← the 8 synchronous hooks + run-detached.mjs ← stop / sessionEnd + scripts/*.mjs ← canonical hooks, shared with every agent skills/ - .mcp.json + src/hooks/cursor/ ← the only Cursor-specific source + run-hook.ts, run-detached.ts ← CLI entrypoints + delegate.ts ← event -> canonical hook dispatch + workspace.ts ← resolveWorkspace() + cursor-db.ts ← reads Cursor's own SQLite storage integrations/cursor/ - install-local.mjs - verify-flow.mjs - close-stale-am-sessions.mjs ← dev utility - migrate-bad-projects.mjs ← one-off migration for bad .cursor projects + install-local.mjs ← local marketplace + MCP wiring + verify-flow.mjs ← live smoke test against a daemon + close-stale-am-sessions.mjs ← dev utility + _env.mjs ← shared config loading ``` -## Hooks +`workspace.ts` and `delegate.ts` are not build entrypoints; they are inlined +into each CLI, so the emitted files are self-contained exactly like every +other hook artifact. -| Hook | Shim | Delegates to | -|------|------|--------------| -| `sessionStart` | `run-hook.mjs` | `session-start.mjs` | -| `beforeSubmitPrompt` | `run-hook.mjs` | `prompt-submit.mjs` | -| `preToolUse` / `postToolUse` | `run-hook.mjs` | `pre-tool-use.mjs` / `post-tool-use.mjs` | -| `stop` | `run-detached.mjs` | `stop.mjs` | -| `sessionEnd` | `run-detached.mjs` | `session-end.mjs` | +--- -The shim calls `resolveWorkspace()`, sets `AGENTMEMORY_PROJECT_NAME`, enriches `cwd` on the payload, then spawns the official hook script. +## What a hook call actually does -## sessionEnd (Cursor 3.13.x) +```text +Cursor + │ reads plugin/hooks/hooks.cursor.json, spawns a process, writes JSON to stdin + ▼ +run-hook.mjs run-detached.mjs stop|sessionEnd + │ │ writes the payload to a temp file, + │ │ spawns a detached worker, returns + │ ▼ + │ (background worker) + ▼ +resolveWorkspace(payload) ──► { project, cwd } + │ + │ AGENTMEMORY_PROJECT_NAME= in the environment + │ cwd= merged into the payload + ▼ +node plugin/scripts/.mjs ← unmodified + │ + ▼ +POST $AGENTMEMORY_URL/agentmemory/... +``` -- `window_close`: often broken (`MainThreadShellExec not initialized`) -- Tab close may work — test manually -- `stop` is reliable for summarize; treat `sessionEnd` as best-effort until Cursor fixes lifecycle on their side +`resolveProject()` in the canonical hooks reads `AGENTMEMORY_PROJECT_NAME` +before falling back to git or cwd. That one environment variable is the whole +delegation mechanism — it is how Cursor-specific knowledge reaches a hook that +knows nothing about Cursor. -## Dev utilities +### Differences from the Claude Code hooks -```bash -node integrations/cursor/close-stale-am-sessions.mjs --dry-run -node integrations/cursor/migrate-bad-projects.mjs --dry-run +| | Claude Code | Cursor | +|---|---|---| +| Event names | `PostToolUse` | `postToolUse` | +| Config shape | `[{hooks:[{type,command}]}]` | `[{command}]` | +| Plugin root var | `${CLAUDE_PLUGIN_ROOT}` | `${CURSOR_PLUGIN_ROOT}` | +| `preToolUse` matcher | `Edit\|Write\|Read\|Glob\|Grep` | …`\|Shell` (Cursor has a Shell tool) | +| Session id field | `session_id` | `session_id` or `sessionId` | +| Working directory | reliable | **not reliable — see below** | + +The extra process hop costs about 100ms per synchronous hook (one additional +Node startup plus resolution). The canonical hooks already spend ~500ms of +their own deliberately, waiting for their fire-and-forget POST to leave, so +this is roughly a 20% overhead on something the user does not wait for. It +buys zero duplicated hook logic, which was the explicit trade. + +### Why `stop` and `sessionEnd` are detached + +`sessionEnd` fans out to four daemon endpoints — session end, crystals, +consolidate pipeline, bridge sync. Cursor kills its hook process tree when the +window closes, so run inline that work is cut off halfway and the session's +memories are lost. + +`run-detached.mjs` runs the same file twice in two roles. The parent reads +stdin, writes the payload to a `0600` temp file, spawns itself with +`detached: true`, `stdio: 'ignore'` and `AM_HOOK_WORKER=1`, then exits as soon +as the spawn is confirmed. The worker reads the file back, deletes it, and +delegates normally under a watchdog. + +* Temp file, not a pipe, because `stdio: 'ignore'` is what keeps the parent + from being held open by the child. +* `detached` puts the worker in its own process group, out of reach of + Cursor's teardown. +* `unref()` stops the parent's event loop waiting on it. + +Measured: the parent returns in **99ms** where an inline `stop` would hold +Cursor for about **1500ms**. + +The eight synchronous hooks stay inline: they are fast, and some need to write +to stdout for Cursor to read (`sessionStart` can inject project context). + +--- + +## Why there is a workspace resolver at all + +Every hook has to answer one question: **which project is this?** For Claude +Code that is 20 lines — read `cwd`, run `git rev-parse --show-toplevel`, take +the basename. + +Cursor does not give hooks a trustworthy working directory. In practice the +payload contains one of: + +* `.cursor` — Cursor's own metadata directory, not the project; +* the **Cursor install directory**, leaked through `VSCODE_CWD`, which resolves + to a project literally named `cursor`; +* nothing at all, just a `tool_input` holding a *file* path; +* a session id, with the workspace recorded somewhere else entirely. + +Getting this wrong is not a crash. It silently files a user's memories under +the wrong project, or under `.cursor`, and nobody notices until the data is +already there. That is why the resolver is the largest piece of this +integration, and why every layer either verifies its answer against the +filesystem or refuses to answer. + +### The chain + +Layers are tried in order. `resolveWorkspace` caches the result under the +session id, so the whole chain runs at most **once per session** — every +later hook in that session is a single JSON read. + +| # | Layer | Basis | Notes | +|---|---|---|---| +| 1 | Session cache | previous answer | `~/.cursor/hooks/.agentmemory-session-cache.json`, written under a lock | +| 2 | Payload paths | `workspace_roots`, `workspace_folder`, `cwd`, … | eight aliases because Cursor is inconsistent; `cwd` is deliberately ranked low | +| 3 | `tool_input` paths | any path-shaped string in the tool arguments | file paths resolve to their directory | +| 4 | **Cursor's database** | `composer.composerHeaders` | exact, no inference — see below | +| 5 | Transcript directory name | `~/.cursor/projects//` | slug is the workspace path with separators flattened | +| 6 | Transcript contents | most-mentioned git root | a guess; needs ≥3 votes | +| 7 | Environment | `CURSOR_WORKSPACE_ROOT`, `PWD`, `VSCODE_CWD` | last, because `VSCODE_CWD` lies | +| 8 | `unknown-project` | — | the honest answer when nothing else is | + +Every candidate then passes the same gate: not `.cursor`, not an IDE install +path, not an OS directory, not a bare drive root, and the resulting project +name must not start with `.` (which caught sessions landing under `.codex`). + +Layers 4–6 additionally require the directory to **exist exactly**. Climbing to +whatever ancestor survives is right for a file path out of `tool_input`, but +wrong for a workspace path a source claims is authoritative: a project that +moved away from `D:/Andrew/Code/cc-router` otherwise resolves to the project +`Code`, and every session from that machine piles up under it. + +Set **`AM_CURSOR_DEBUG=1`** to have the resolver print which layer answered. +Every layer returns the same shape, so a wrong project is otherwise +undiagnosable from the outside. + +--- + +## How Cursor stores this (reverse engineered) + +Layers 4–6 rely on Cursor's on-disk state. The layout, as of Cursor 3.x: + +```text +/ %APPDATA%/Cursor/User (Windows) + │ ~/Library/Application Support/Cursor/User (macOS) + │ ~/.config/Cursor/User (Linux) + ├── globalStorage/state.vscdb SQLite; all chat content + the 3.0 index + └── workspaceStorage// + ├── workspace.json {"folder":"file:///d%3A/repo"} + └── state.vscdb SQLite; pre-3.0 per-workspace chat list + +~/.cursor/projects//agent-transcripts//.jsonl ``` -`migrate-bad-projects.mjs` is for legacy sessions stored with `project=.cursor` only. The resolver should prevent new bad data. +**A Cursor hook's `session_id` is the `composerId`.** That is what makes layer +4 possible: `composer.composerHeaders` in the global database maps a +`composerId` straight to `workspaceIdentifier.uri.fsPath`. One indexed read, +measured at 4–7ms even against a 3.6GB database, and cached for the rest of +the session. + +Two caveats, both handled: + +* **Cursor 3.0 (April 2026) centralised that index**, moving it out of the + per-workspace databases, and migrates each workspace lazily — when it is next + opened. Machines still on ≤2.6, or with workspaces untouched since the + upgrade, keep the old per-workspace `allComposers` array. On one real machine + 55 of 124 workspaces were still in the old format. Both shapes are read; the + legacy scan is ordered by recency and capped, because the workspace a live + session belongs to was touched moments ago. +* **Reading SQLite needs a driver.** `node:sqlite` exists from Node 22.5 and + this package supports Node ≥20; `better-sqlite3` is optional. With neither, + every path in `cursor-db.ts` returns null and layers 5–6 take over. This + layer is an accuracy upgrade, never a requirement. + +### The slug encoding (layer 5) + +`~/.cursor/projects/` names one directory per workspace after the workspace +path with every separator flattened to `-`: + +```text +D:\Andrew\Code\Github\agentmemory → d-Andrew-Code-Github-agentmemory +``` + +The encoding is lossy in one direction: a directory name may itself contain +hyphens, so `d-Andrew-Code-cc-router` is `D:/Andrew/Code/cc-router` and, just +as validly on paper, `D:/Andrew/Code/cc/router`. The disambiguator is the +filesystem — try every grouping of consecutive segments, descend only into +groupings that exist. Pruning turns what looks like a 2ⁿ search into the +handful of real directories on the machine: 39 slugs decode in 29ms, with zero +ambiguous results. + +### What layer 6 is for, and why it is last + +The transcript scan answers "which git root is mentioned most in this +conversation". That is a guess, and it was originally asked *before* the slug — +so a session about agentmemory that was actually running elsewhere resolved to +agentmemory. It now runs last, only existing directories vote, they vote for +their git root, and a winner needs at least three votes. Without the git-root +rule the winner is whatever generic directory came up most: `/bin`, `C:/Users`. + +It stays because it is the only layer that can place a **workspace-less +window** — a chat started from Cursor's welcome screen — that was nonetheless +editing real files. + +### Measured behaviour + +Over 300 real sessions on a Windows machine, resolving from **`session_id` +alone** (no payload at all — the worst case, which real hooks rarely hit +because layer 2 usually answers): + +| Resolved by | Sessions | +|---|---| +| Cursor's database (layer 4) | 10 | +| Slug decode (layer 5) | 8 | +| `unknown-project` | 12 | + +The twelve unknowns are deleted or moved projects and workspace-less windows — +cases where no correct answer exists. There were no wrong attributions. Before +this work both layers returned **zero** on Windows: the slug decoder bailed +unless the name started with `Users-`, and the transcript scan anchored its +regex on `$HOME`, which never matches a checkout on another drive. + +--- + +## Known Cursor limitations + +* `sessionEnd` on window close is unreliable in Cursor 3.13.x + (`MainThreadShellExec not initialized`). `stop` is what the pipeline relies + on; `verify-flow.mjs` treats `sessionEnd` as diagnostic only and needs + `--with-session-end` to exercise it at all. +* The daemon drops observations while it is busy — a `stop` leaves + `/summarize` running in the background, and observations posted into that + window can vanish. `verify-flow.mjs` retries with a varied `tool_input`, + because the dedup key is `(sessionId, tool_name, tool_input)` and a + byte-identical retry would be discarded as a duplicate. + +--- + +## Testing + +```bash +npx vitest run test/cursor-adapter.test.ts test/cursor-workspace.test.ts # no daemon +node integrations/cursor/verify-flow.mjs # live daemon +node integrations/cursor/close-stale-am-sessions.mjs --dry-run # dev utility +``` -## PR checklist +The unit tests are the authoritative check: they assert the delegation +contract against a local HTTP server and stand-in hooks, and cover the +resolver branches that were found misfiring on real sessions. -- [x] `plugin/.cursor-plugin/plugin.json` + `hooks.cursor.json` -- [x] Shim delegates to `plugin/scripts/*.mjs` (no duplicated hook logic) -- [ ] README: Cursor = MCP + native hooks (not MCP-only) — upstream root README -- [ ] `agentmemory connect cursor` docs update -- [x] Disable duplicate user `~/.cursor/hooks.json` in docs only (not auto-cleared) +One trap worth knowing if you extend them: **do not use `spawnSync`**. +`spawnSync` blocks the caller's event loop, so an in-process HTTP server +cannot accept the connection the child is opening. The requests only arrive +after the child has exited, which looks exactly like "the hook sent nothing" +and costs an afternoon. From ba16a38265e065b5c0027fb13a9c76f32b2b0b82 Mon Sep 17 00:00:00 2001 From: Andrew Date: Mon, 27 Jul 2026 01:56:02 +0800 Subject: [PATCH 11/18] fix(cursor): only reject dot-named directories that are not repositories The rule was "a project name starting with '.' is always a tool's metadata directory", which is false. ~/.dotfiles, ~/.emacs.d, ~/.config kept under chezmoi and GitHub's convention of a repository named ".github" are all real projects people open in an editor, and all of them were being thrown away. What actually separates them from ~/.codex or ~/.vscode is not the leading dot, it is that a human deliberately version controls them. projectFromPath now reports whether the name came from a git toplevel, and only a dot-named directory that is not a repository is treated as another agent's state. That needs no list of tool names to keep current as new agents ship. --- integrations/cursor/README.md | 12 +++++++-- plugin/scripts/cursor/run-detached.mjs | 20 +++++++++------ plugin/scripts/cursor/run-hook.mjs | 20 +++++++++------ src/hooks/cursor/workspace.ts | 34 ++++++++++++++++++-------- test/cursor-workspace.test.ts | 23 +++++++++++++++++ 5 files changed, 83 insertions(+), 26 deletions(-) diff --git a/integrations/cursor/README.md b/integrations/cursor/README.md index 7af7e3c54e..ebf834d538 100644 --- a/integrations/cursor/README.md +++ b/integrations/cursor/README.md @@ -180,8 +180,16 @@ later hook in that session is a single JSON read. | 8 | `unknown-project` | — | the honest answer when nothing else is | Every candidate then passes the same gate: not `.cursor`, not an IDE install -path, not an OS directory, not a bare drive root, and the resulting project -name must not start with `.` (which caught sessions landing under `.codex`). +path, not an OS directory, not a bare drive root, and not another agent's +state directory. + +That last one is narrower than it sounds. Sessions were landing under +`.codex`, but rejecting every dot-named directory would be wrong — plenty of +real projects are dot-named, from `~/.dotfiles` and `~/.emacs.d` to GitHub's +convention of a repository literally called `.github`. What separates those +from `~/.codex` or `~/.vscode` is not the name but that a human deliberately +version controls them, so the rule is **a dot-named directory that is not a +git repository**. No list of tool names to keep current as new agents ship. Layers 4–6 additionally require the directory to **exist exactly**. Climbing to whatever ancestor survives is right for a file path out of `tool_input`, but diff --git a/plugin/scripts/cursor/run-detached.mjs b/plugin/scripts/cursor/run-detached.mjs index 996199a065..d99e4e888c 100644 --- a/plugin/scripts/cursor/run-detached.mjs +++ b/plugin/scripts/cursor/run-detached.mjs @@ -384,9 +384,15 @@ function cleanRepoName(dirPath) { } function projectFromPath(targetPath) { try { - return cleanRepoName(gitRootFromPath(targetPath)); + return { + name: cleanRepoName(gitRootFromPath(targetPath)), + fromGitRoot: true + }; } catch { - return cleanRepoName(targetPath); + return { + name: cleanRepoName(targetPath), + fromGitRoot: false + }; } } function decodeSlugCandidates(slug) { @@ -542,8 +548,8 @@ function readWorkerHookPayload() { } catch {} } } -function isMetadataProjectName(project) { - return project.startsWith("."); +function isMetadataProject(project) { + return project.name.startsWith(".") && !project.fromGitRoot; } function existingDirectory(pathValue) { if (!pathExists(pathValue)) return null; @@ -560,10 +566,10 @@ function resolveFromPathCandidates(candidates, sessionId, options = {}) { const existing = options.exact ? existingDirectory(candidate) : existingAncestor(candidate); if (!existing || isBadPath(existing)) continue; const project = projectFromPath(existing); - if (!isMetadataProjectName(project)) { - rememberSession(sessionId, project, existing); + if (!isMetadataProject(project)) { + rememberSession(sessionId, project.name, existing); return { - project, + project: project.name, cwd: existing }; } diff --git a/plugin/scripts/cursor/run-hook.mjs b/plugin/scripts/cursor/run-hook.mjs index 0f77534c3e..7ea1830a24 100644 --- a/plugin/scripts/cursor/run-hook.mjs +++ b/plugin/scripts/cursor/run-hook.mjs @@ -384,9 +384,15 @@ function cleanRepoName(dirPath) { } function projectFromPath(targetPath) { try { - return cleanRepoName(gitRootFromPath(targetPath)); + return { + name: cleanRepoName(gitRootFromPath(targetPath)), + fromGitRoot: true + }; } catch { - return cleanRepoName(targetPath); + return { + name: cleanRepoName(targetPath), + fromGitRoot: false + }; } } function decodeSlugCandidates(slug) { @@ -485,8 +491,8 @@ function workspaceFromSessionId(sessionId) { if (fromSlug) return fromSlug; return workspaceFromTranscriptFile(hit.transcriptFile); } -function isMetadataProjectName(project) { - return project.startsWith("."); +function isMetadataProject(project) { + return project.name.startsWith(".") && !project.fromGitRoot; } function existingDirectory(pathValue) { if (!pathExists(pathValue)) return null; @@ -503,10 +509,10 @@ function resolveFromPathCandidates(candidates, sessionId, options = {}) { const existing = options.exact ? existingDirectory(candidate) : existingAncestor(candidate); if (!existing || isBadPath(existing)) continue; const project = projectFromPath(existing); - if (!isMetadataProjectName(project)) { - rememberSession(sessionId, project, existing); + if (!isMetadataProject(project)) { + rememberSession(sessionId, project.name, existing); return { - project, + project: project.name, cwd: existing }; } diff --git a/src/hooks/cursor/workspace.ts b/src/hooks/cursor/workspace.ts index 8b7a6fbd0a..7ed581003b 100644 --- a/src/hooks/cursor/workspace.ts +++ b/src/hooks/cursor/workspace.ts @@ -295,11 +295,17 @@ function cleanRepoName(dirPath: string): string { return name || "unknown-project"; } -function projectFromPath(targetPath: string): string { +interface ResolvedProject { + name: string; + /** Whether the name came from a git toplevel rather than a bare directory. */ + fromGitRoot: boolean; +} + +function projectFromPath(targetPath: string): ResolvedProject { try { - return cleanRepoName(gitRootFromPath(targetPath)); + return { name: cleanRepoName(gitRootFromPath(targetPath)), fromGitRoot: true }; } catch { - return cleanRepoName(targetPath); + return { name: cleanRepoName(targetPath), fromGitRoot: false }; } } @@ -554,10 +560,18 @@ export function readWorkerHookPayload(): Record | null { } } -// A project name starting with "." is always a tool's metadata directory -// (.cursor, .codex, .claude, .vscode), never the thing the user is working on. -function isMetadataProjectName(project: string): boolean { - return project.startsWith("."); +// Sessions were landing under ".codex": a path pointing into an agent's state +// directory walked up to ~/.codex and that became the project name. +// +// Rejecting every dot-named directory would be wrong, though. Plenty of real +// projects are dot-named -- ~/.dotfiles, ~/.emacs.d, ~/.config kept under +// chezmoi, and GitHub's own convention of a repository literally named +// ".github". What separates those from ~/.codex or ~/.vscode is not the name, +// it is that a human deliberately version controls them. So the rule is "a +// dot-named directory that is not a repository", which needs no list of tool +// names to keep up to date as new agents ship. +function isMetadataProject(project: ResolvedProject): boolean { + return project.name.startsWith(".") && !project.fromGitRoot; } // The path exactly, or its parent when it points at a file. Unlike @@ -586,9 +600,9 @@ function resolveFromPathCandidates( const existing = options.exact ? existingDirectory(candidate) : existingAncestor(candidate); if (!existing || isBadPath(existing)) continue; const project = projectFromPath(existing); - if (!isMetadataProjectName(project)) { - rememberSession(sessionId, project, existing); - return { project, cwd: existing }; + if (!isMetadataProject(project)) { + rememberSession(sessionId, project.name, existing); + return { project: project.name, cwd: existing }; } } return null; diff --git a/test/cursor-workspace.test.ts b/test/cursor-workspace.test.ts index 7942f9da79..64863664f4 100644 --- a/test/cursor-workspace.test.ts +++ b/test/cursor-workspace.test.ts @@ -1,4 +1,5 @@ import { describe, it, expect } from 'vitest'; +import { execFileSync } from 'node:child_process'; import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { basename, join } from 'node:path'; @@ -115,6 +116,28 @@ describe('cursor workspace resolver', () => { } }); + it('keeps a dot-named directory that is version controlled', () => { + // ~/.dotfiles, ~/.emacs.d, ~/.config under chezmoi, and GitHub's own + // convention of a repository named ".github" are all real projects people + // open in an editor. What separates them from ~/.codex is not the leading + // dot, it is that a human deliberately version controls them. + const parent = mkdtempSync(join(tmpdir(), 'am-ws-')); + const repo = join(parent, '.dotfiles'); + mkdirSync(repo, { recursive: true }); + execFileSync('git', ['init', '-q'], { cwd: repo, stdio: 'ignore' }); + try { + const resolved = withoutWorkspaceEnv(() => + resolveWorkspace({ + session_id: sessionId('dot-repo'), + workspace_roots: [normalizePathSlashes(repo)] + }) + ); + expect(resolved.project).toBe('.dotfiles'); + } finally { + rmSync(parent, { recursive: true, force: true }); + } + }); + it('never reports a bare drive root as the project', () => { const resolved = withoutWorkspaceEnv(() => resolveWorkspace({ session_id: sessionId('drive-root'), cwd: 'C:/' }) From 6b1219b54a09c8b8b74383f65d0c66db829e303e Mon Sep 17 00:00:00 2001 From: Andrew Date: Mon, 27 Jul 2026 02:17:43 +0800 Subject: [PATCH 12/18] fix(cursor): space out the smoke test's observation retries Measured against a Tailscale-reachable daemon, roughly 15% of observations are dropped, and they drop in bursts -- three in a row, then thirty in a row land. Immediate retries all fall inside the same burst, so the smoke test reported a failure that a second run would not reproduce. The same rate applies when the canonical hook is invoked directly, without this adapter (13/15 vs 12/15 interleaved), so this is the fire-and-forget hook contract meeting a busy remote daemon, not something the Cursor path introduces. Raising the exit timer from 500ms to 3000ms changed nothing (15/15 either way), which rules out the request being cut off mid-flight. Four attempts with a widening gap; five consecutive runs pass. --- integrations/cursor/verify-flow.mjs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/integrations/cursor/verify-flow.mjs b/integrations/cursor/verify-flow.mjs index 9399c22945..ea9ff00f9e 100644 --- a/integrations/cursor/verify-flow.mjs +++ b/integrations/cursor/verify-flow.mjs @@ -126,8 +126,15 @@ record( // (sessionId, tool_name, tool_input), so a byte-identical retry would be // discarded as a duplicate and could never succeed. console.log('\n[2/4] postToolUse'); -const OBSERVE_ATTEMPTS = 3; +// Measured against a Tailscale-reachable daemon: roughly 15% of observations +// are dropped, in bursts rather than independently -- three in a row is +// normal, then thirty in a row land. The same rate applies when the canonical +// hook is invoked directly, without this adapter, so it is a property of the +// fire-and-forget hook contract plus a busy daemon, not of the Cursor path. +// Retries therefore have to be spaced, not just repeated. +const OBSERVE_ATTEMPTS = 4; for (let attempt = 1; attempt <= OBSERVE_ATTEMPTS; attempt++) { + if (attempt > 1) await sleep(attempt * 2000); r = runHook('run-hook.mjs', ['postToolUse'], { ...basePayload, tool_name: 'Read', From d59584b2e941400f95100a6ba1a223b36d6d3602 Mon Sep 17 00:00:00 2001 From: Andrew Date: Mon, 27 Jul 2026 02:23:25 +0800 Subject: [PATCH 13/18] fix(cursor): stop telling users MCP is all Cursor can do `agentmemory connect cursor` printed "Using MCP (the only protocol Cursor speaks)" and grouped Cursor with the MCP-only hosts. That was true before this branch and is the exact claim it exists to disprove, so a user following the CLI would never learn the hooks are there. Cursor now groups with the native hosts, and the note points at the plugin. Deliberately no --with-hooks flag: Codex and Claude Code have one because those hosts fail to dispatch plugin-scope hooks, so the plugin's entries have to be mirrored into a user-scope file. Cursor dispatches them correctly, and writing ~/.cursor/hooks.json as well would make both copies fire and record every observation twice -- which is why install-local.mjs offers to clear that file rather than write to it. Also gives Cursor a section in the root README, where the agent table said "merge into mcpServers" and nothing else. --- README.md | 15 ++++++++++++++- src/cli/connect/cursor.ts | 12 ++++++++++-- 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 7fee00649a..3d3d6ebae8 100644 --- a/README.md +++ b/README.md @@ -602,6 +602,19 @@ copilot plugin install rohitg00/agentmemory:plugin `agentmemory connect copilot-cli` merges `mcpServers.agentmemory` into `~/.copilot/mcp-config.json` (or `$COPILOT_HOME/mcp-config.json` when `COPILOT_HOME` is set) and preserves existing servers. This adapter is Windows-safe even though other `connect` adapters still require manual Windows setup. Copilot picks up the MCP server on next launch or after `/mcp`. Install the plugin as well when you want the full hook/skill experience. +### Cursor + +```bash +# MCP wiring +agentmemory connect cursor +``` + +Then add the native hooks: **Settings → Plugins → Add marketplace** → select an agentmemory checkout (the directory containing `.cursor-plugin/marketplace.json`), enable the **agentmemory** plugin, and reload the window. + +Cursor runs the same lifecycle hooks as every other host — they are the canonical `plugin/scripts/*.mjs`, not a separate implementation. A thin adapter in front of them resolves which project a session belongs to, which Cursor does not reliably report: its payload `cwd` can be `.cursor`, the Cursor install directory, or missing entirely. Do not also wire hooks into `~/.cursor/hooks.json` — the plugin already dispatches them, and both copies firing records every observation twice. + +Full guide: [`integrations/cursor/`](integrations/cursor/) +
OpenClaw (paste this prompt) @@ -689,7 +702,7 @@ The agentmemory entry is the **same MCP server block** across every host that us | Agent | Config file | Notes | |---|---|---| | **Cursor (MCP only)** | `~/.cursor/mcp.json` | Merge into `mcpServers`, or `agentmemory connect cursor`. One-click deeplink also available on the website. | -| **Cursor (full plugin)** | `.cursor-plugin/` | Cursor Marketplace listing (submission in review) or Cursor Settings → Plugins → local checkout. Registers 7 auto-capture hooks (sessionStart, beforeSubmitPrompt, preToolUse, postToolUse, postToolUseFailure, stop, sessionEnd) + 17 skills + the MCP server, with `AGENTMEMORY_URL` / `AGENTMEMORY_SECRET` managed in Cursor's plugin dashboard. Works in the Cursor IDE and `cursor-agent` CLI; CLI print-mode prompts are backfilled from the session transcript at session end. | +| **Cursor (full plugin)** | `.cursor-plugin/` | Cursor Marketplace listing or Settings → Plugins → local checkout. Registers lifecycle hooks via a thin adapter that delegates to the canonical `plugin/scripts/*.mjs`, plus skills and MCP. The adapter resolves the workspace Cursor does not reliably report. See [Cursor](#cursor). Works in the Cursor IDE and `cursor-agent` CLI. | | **Claude Desktop** | `claude_desktop_config.json` (Application Support) | Merge into `mcpServers`. Restart Claude Desktop after editing. | | **Cline / Roo Code / Kilo Code** | Cline MCP settings (Settings UI → MCP Servers → Edit) | Same `mcpServers` block. | | **Devin CLI (MCP + hooks)** | `~/.config/devin/config.json` | `agentmemory connect devin` merges the MCP entry; `--with-hooks` adds six native auto-capture hooks (SessionStart, UserPromptSubmit, PreToolUse, PostToolUse, Stop, SessionEnd) with Devin'"'"'s lowercase tool matchers. Verify with `devin mcp list` and `/hooks` inside devin. | diff --git a/src/cli/connect/cursor.ts b/src/cli/connect/cursor.ts index fb4c5afb3c..642add4efb 100644 --- a/src/cli/connect/cursor.ts +++ b/src/cli/connect/cursor.ts @@ -5,9 +5,17 @@ import { createJsonMcpAdapter } from "./json-mcp-adapter.js"; export const adapter = createJsonMcpAdapter({ name: "cursor", displayName: "Cursor", + // Cursor speaks lifecycle hooks as well as MCP, so it groups with the + // native hosts rather than the MCP-only ones. + category: "native", detectDir: join(homedir(), ".cursor"), configPath: join(homedir(), ".cursor", "mcp.json"), - docs: "https://github.com/rohitg00/agentmemory#other-agents", + docs: "https://github.com/rohitg00/agentmemory#cursor", + // Deliberately no --with-hooks here, unlike Codex and Claude Code. Theirs + // mirror the plugin's hooks into a user-scope file to work around hosts + // that fail to dispatch plugin-scope hooks; Cursor dispatches them fine. + // Writing ~/.cursor/hooks.json as well would just make both copies fire and + // record every observation twice. protocolNote: - "→ Using MCP (the only protocol Cursor speaks). Memory bridge runs at :3111 underneath.", + "→ Using MCP. Lifecycle hooks ship in the Cursor plugin: Settings → Plugins → Add marketplace → this repo, then enable agentmemory.", }); From ba0e4cdb7d02b8625cf71c5e5b00bf7f1ea2ffb3 Mon Sep 17 00:00:00 2001 From: Andrew Date: Mon, 27 Jul 2026 02:40:59 +0800 Subject: [PATCH 14/18] fix(cursor): do not file sessions under the home directory An agent launched with no workspace reports $HOME, and the resolver accepted it: 18 real sessions in a single day landed under a project named "Andrew" with cwd C:\Users\Andrew, all with zero observations. That is the account name, not a project. The transcript scan already refused $HOME; the payload, tool_input and environment layers did not. Same carve-out as the dot-directory rule -- if $HOME is itself a git repository, that is the dotfiles-in-$HOME layout and it stays. --- plugin/scripts/cursor/run-detached.mjs | 4 ++++ plugin/scripts/cursor/run-hook.mjs | 4 ++++ src/hooks/cursor/workspace.ts | 11 +++++++++++ test/cursor-workspace.test.ts | 13 +++++++++++++ 4 files changed, 32 insertions(+) diff --git a/plugin/scripts/cursor/run-detached.mjs b/plugin/scripts/cursor/run-detached.mjs index d99e4e888c..f15951d47f 100644 --- a/plugin/scripts/cursor/run-detached.mjs +++ b/plugin/scripts/cursor/run-detached.mjs @@ -551,6 +551,9 @@ function readWorkerHookPayload() { function isMetadataProject(project) { return project.name.startsWith(".") && !project.fromGitRoot; } +function isHomeDirectory(pathValue) { + return normalizePathSlashes(pathValue) === normalizePathSlashes(HOME); +} function existingDirectory(pathValue) { if (!pathExists(pathValue)) return null; const resolved = process.platform === "win32" ? pathValue.replace(/\//g, "\\") : pathValue; @@ -566,6 +569,7 @@ function resolveFromPathCandidates(candidates, sessionId, options = {}) { const existing = options.exact ? existingDirectory(candidate) : existingAncestor(candidate); if (!existing || isBadPath(existing)) continue; const project = projectFromPath(existing); + if (isHomeDirectory(existing) && !project.fromGitRoot) continue; if (!isMetadataProject(project)) { rememberSession(sessionId, project.name, existing); return { diff --git a/plugin/scripts/cursor/run-hook.mjs b/plugin/scripts/cursor/run-hook.mjs index 7ea1830a24..d28abe0177 100644 --- a/plugin/scripts/cursor/run-hook.mjs +++ b/plugin/scripts/cursor/run-hook.mjs @@ -494,6 +494,9 @@ function workspaceFromSessionId(sessionId) { function isMetadataProject(project) { return project.name.startsWith(".") && !project.fromGitRoot; } +function isHomeDirectory(pathValue) { + return normalizePathSlashes(pathValue) === normalizePathSlashes(HOME); +} function existingDirectory(pathValue) { if (!pathExists(pathValue)) return null; const resolved = process.platform === "win32" ? pathValue.replace(/\//g, "\\") : pathValue; @@ -509,6 +512,7 @@ function resolveFromPathCandidates(candidates, sessionId, options = {}) { const existing = options.exact ? existingDirectory(candidate) : existingAncestor(candidate); if (!existing || isBadPath(existing)) continue; const project = projectFromPath(existing); + if (isHomeDirectory(existing) && !project.fromGitRoot) continue; if (!isMetadataProject(project)) { rememberSession(sessionId, project.name, existing); return { diff --git a/src/hooks/cursor/workspace.ts b/src/hooks/cursor/workspace.ts index 7ed581003b..a80ea5eb88 100644 --- a/src/hooks/cursor/workspace.ts +++ b/src/hooks/cursor/workspace.ts @@ -574,6 +574,10 @@ function isMetadataProject(project: ResolvedProject): boolean { return project.name.startsWith(".") && !project.fromGitRoot; } +function isHomeDirectory(pathValue: string): boolean { + return normalizePathSlashes(pathValue) === normalizePathSlashes(HOME); +} + // The path exactly, or its parent when it points at a file. Unlike // existingAncestor() this does not climb: for a workspace path that some // source claims is authoritative, "the directory is gone" means the record is @@ -600,6 +604,13 @@ function resolveFromPathCandidates( const existing = options.exact ? existingDirectory(candidate) : existingAncestor(candidate); if (!existing || isBadPath(existing)) continue; const project = projectFromPath(existing); + // $HOME is what a hook sees when the agent was launched with no workspace + // at all. Accepting it invents a project named after the account -- real + // sessions were being filed under "Andrew" with cwd C:\Users\Andrew -- + // when the honest answer is that there is no workspace. Same carve-out as + // the dot-directory rule: allowed when HOME is itself a repository, which + // is the dotfiles-checked-out-in-$HOME layout. + if (isHomeDirectory(existing) && !project.fromGitRoot) continue; if (!isMetadataProject(project)) { rememberSession(sessionId, project.name, existing); return { project: project.name, cwd: existing }; diff --git a/test/cursor-workspace.test.ts b/test/cursor-workspace.test.ts index 64863664f4..0216af2b70 100644 --- a/test/cursor-workspace.test.ts +++ b/test/cursor-workspace.test.ts @@ -138,6 +138,19 @@ describe('cursor workspace resolver', () => { } }); + it('never reports the home directory as the project', () => { + // An agent launched with no workspace reports $HOME, which used to become + // a project named after the account -- 18 real sessions in one day filed + // under "Andrew", cwd C:\Users\Andrew. Unless $HOME is itself a + // repository, "no workspace" is the honest answer. + const home = process.env.HOME || process.env.USERPROFILE; + if (!home) return; + const resolved = withoutWorkspaceEnv(() => + resolveWorkspace({ session_id: sessionId('home-cwd'), cwd: normalizePathSlashes(home) }) + ); + expect(resolved.project).toBe('unknown-project'); + }); + it('never reports a bare drive root as the project', () => { const resolved = withoutWorkspaceEnv(() => resolveWorkspace({ session_id: sessionId('drive-root'), cwd: 'C:/' }) From 3e15c459a88dac50956f88da7a702ae898c670db Mon Sep 17 00:00:00 2001 From: Andrew Date: Sun, 16 Aug 2026 09:49:22 -0400 Subject: [PATCH 15/18] fix(cursor): replace #1213 direct hooks with the workspace adapter Keep the marketplace layout from main (.cursor-plugin/plugin.json + plugin/cursor/) and point every Cursor event at run-hook.mjs / run-detached.mjs. Drop the second plugin root so both copies cannot fire. --- .cursor-plugin/marketplace.json | 19 --------- CHANGELOG.md | 6 +++ README.md | 2 +- integrations/cursor/README.md | 18 ++++----- integrations/cursor/install-local.mjs | 6 +-- plugin/.cursor-plugin/plugin.json | 29 -------------- plugin/cursor/hooks.json | 31 +++++++++++---- plugin/hooks/hooks.cursor.json | 56 --------------------------- test/cursor-adapter.test.ts | 6 +-- test/cursor-plugin.test.ts | 14 +++++++ 10 files changed, 59 insertions(+), 128 deletions(-) delete mode 100644 .cursor-plugin/marketplace.json delete mode 100644 plugin/.cursor-plugin/plugin.json delete mode 100644 plugin/hooks/hooks.cursor.json diff --git a/.cursor-plugin/marketplace.json b/.cursor-plugin/marketplace.json deleted file mode 100644 index 6c412994d7..0000000000 --- a/.cursor-plugin/marketplace.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "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" - } - ] -} diff --git a/CHANGELOG.md b/CHANGELOG.md index 0904921e9b..e1a4485b33 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,12 @@ All notable changes to agentmemory will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [Unreleased] + +### Changed + +- **Cursor hooks go through a workspace adapter.** `#1213` wired Cursor camelCase events straight at `plugin/scripts/*.mjs`. That is still the work those scripts do, but `plugin/cursor/hooks.json` now calls `plugin/scripts/cursor/run-hook.mjs` / `run-detached.mjs` first. The adapter resolves the project Cursor does not reliably report (payload `cwd` can be `.cursor`, the IDE install path, `$HOME`, or missing), sets `AGENTMEMORY_PROJECT_NAME`, and detaches `stop` / `sessionEnd` so window-close does not kill summarize. Canonical hooks are unchanged. Source: `src/hooks/cursor/`. + ## [0.9.29] — 2026-08-15 Release wave in two parts. Recall quality: hybrid ranking reaches the primary recall path, lessons get a real index, every record learns where it came from, the knowledge graph populates keyless, and agent scoping threads through all save paths — plus connector parity for pi and Codex, a new DeepSeek Harness connector, current provider model defaults, and a viewer clarity pass. Foundation: the `.env` file now applies everywhere, imports become searchable, consolidation runs on session stop, twelve MCP-only agents get activated on connect, and every capture surface agrees on what "project" means. No breaking changes; read the upgrade notes for behavior changes you will notice. diff --git a/README.md b/README.md index 3d3d6ebae8..8150421c05 100644 --- a/README.md +++ b/README.md @@ -609,7 +609,7 @@ copilot plugin install rohitg00/agentmemory:plugin agentmemory connect cursor ``` -Then add the native hooks: **Settings → Plugins → Add marketplace** → select an agentmemory checkout (the directory containing `.cursor-plugin/marketplace.json`), enable the **agentmemory** plugin, and reload the window. +Then add the native hooks: **Settings → Plugins → Add marketplace** → select an agentmemory checkout (the directory containing `.cursor-plugin/plugin.json`), enable the **agentmemory** plugin, and reload the window. Cursor runs the same lifecycle hooks as every other host — they are the canonical `plugin/scripts/*.mjs`, not a separate implementation. A thin adapter in front of them resolves which project a session belongs to, which Cursor does not reliably report: its payload `cwd` can be `.cursor`, the Cursor install directory, or missing entirely. Do not also wire hooks into `~/.cursor/hooks.json` — the plugin already dispatches them, and both copies firing records every observation twice. diff --git a/integrations/cursor/README.md b/integrations/cursor/README.md index ebf834d538..4349e3873c 100644 --- a/integrations/cursor/README.md +++ b/integrations/cursor/README.md @@ -24,11 +24,11 @@ Then in Cursor: 1. **Settings → Plugins → Add marketplace** → select the **repo root** `` - (must contain `.cursor-plugin/marketplace.json`) + (must contain `.cursor-plugin/plugin.json`) 2. Enable plugin **agentmemory** -3. **Disable** the old `rohitg00/agentmemory` marketplace entry if both are on +3. **Disable** any second agentmemory marketplace entry if both are on 4. **Developer: Reload Window** -5. Confirm the hooks log shows `scripts/cursor/run-hook.mjs` or `run-detached.mjs` +5. Confirm the hooks log shows `plugin/scripts/cursor/run-hook.mjs` or `run-detached.mjs` Only after plugin hooks are confirmed: @@ -41,13 +41,13 @@ node integrations/cursor/install-local.mjs --clear-user-hooks ## Layout ```text -agentmemory/ ← marketplace root (git repo) - .cursor-plugin/marketplace.json +agentmemory/ ← Cursor plugin root (git repo) + .cursor-plugin/plugin.json ← marketplace manifest (hooks + MCP + skills) plugin/ - .cursor-plugin/plugin.json - hooks/hooks.cursor.json ← Cursor's camelCase lifecycle names + cursor/hooks.json ← Cursor camelCase events → adapter + cursor/mcp.json scripts/cursor/ ← built from src/hooks/cursor/ - run-hook.mjs ← the 8 synchronous hooks + run-hook.mjs ← the synchronous hooks run-detached.mjs ← stop / sessionEnd scripts/*.mjs ← canonical hooks, shared with every agent skills/ @@ -73,7 +73,7 @@ other hook artifact. ```text Cursor - │ reads plugin/hooks/hooks.cursor.json, spawns a process, writes JSON to stdin + │ reads plugin/cursor/hooks.json, spawns a process, writes JSON to stdin ▼ run-hook.mjs run-detached.mjs stop|sessionEnd │ │ writes the payload to a temp file, diff --git a/integrations/cursor/install-local.mjs b/integrations/cursor/install-local.mjs index 6aae0abf02..98b70848ec 100644 --- a/integrations/cursor/install-local.mjs +++ b/integrations/cursor/install-local.mjs @@ -150,11 +150,11 @@ console.log('AGENTMEMORY_SECRET: '); 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(' (repo root — must contain .cursor-plugin/plugin.json)'); console.log('2. Enable plugin: agentmemory'); -console.log('3. Disable the old rohitg00/agentmemory marketplace plugin if both are enabled.'); +console.log('3. Disable any second agentmemory marketplace entry 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/run-hook.mjs'); +console.log('6. In hooks log, confirm commands use plugin/scripts/cursor/run-hook.mjs'); console.log('\nOnly after plugin hooks are confirmed:'); console.log(' node integrations/cursor/install-local.mjs --clear-user-hooks'); diff --git a/plugin/.cursor-plugin/plugin.json b/plugin/.cursor-plugin/plugin.json deleted file mode 100644 index 3b314b6c53..0000000000 --- a/plugin/.cursor-plugin/plugin.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "name": "agentmemory", - "displayName": "agentmemory", - "version": "0.9.28", - "description": "Persistent memory for AI coding agents — Cursor-native lifecycle hooks, 53 MCP tools, 15 skills, real-time viewer.", - "author": { - "name": "Rohit Ghumare", - "url": "https://github.com/rohitg00" - }, - "license": "Apache-2.0", - "homepage": "https://github.com/rohitg00/agentmemory", - "repository": "https://github.com/rohitg00/agentmemory", - "keywords": [ - "agentmemory", - "memory", - "hooks", - "mcp", - "cursor" - ], - "category": "developer-tools", - "tags": [ - "memory", - "hooks", - "mcp" - ], - "skills": "./skills/", - "mcpServers": "./.mcp.json", - "hooks": "./hooks/hooks.cursor.json" -} diff --git a/plugin/cursor/hooks.json b/plugin/cursor/hooks.json index 8f6e393b7d..b652a9c648 100644 --- a/plugin/cursor/hooks.json +++ b/plugin/cursor/hooks.json @@ -3,38 +3,53 @@ "hooks": { "sessionStart": [ { - "command": "node ${CURSOR_PLUGIN_ROOT}/plugin/scripts/session-start.mjs" + "command": "node \"${CURSOR_PLUGIN_ROOT}/plugin/scripts/cursor/run-hook.mjs\" sessionStart" } ], "beforeSubmitPrompt": [ { - "command": "node ${CURSOR_PLUGIN_ROOT}/plugin/scripts/prompt-submit.mjs" + "command": "node \"${CURSOR_PLUGIN_ROOT}/plugin/scripts/cursor/run-hook.mjs\" beforeSubmitPrompt" } ], "preToolUse": [ { - "command": "node ${CURSOR_PLUGIN_ROOT}/plugin/scripts/pre-tool-use.mjs", - "matcher": "Shell|Read|Write|Grep" + "matcher": "Edit|Write|Read|Glob|Grep|Shell", + "command": "node \"${CURSOR_PLUGIN_ROOT}/plugin/scripts/cursor/run-hook.mjs\" preToolUse" } ], "postToolUse": [ { - "command": "node ${CURSOR_PLUGIN_ROOT}/plugin/scripts/post-tool-use.mjs" + "command": "node \"${CURSOR_PLUGIN_ROOT}/plugin/scripts/cursor/run-hook.mjs\" postToolUse" } ], "postToolUseFailure": [ { - "command": "node ${CURSOR_PLUGIN_ROOT}/plugin/scripts/post-tool-failure.mjs" + "command": "node \"${CURSOR_PLUGIN_ROOT}/plugin/scripts/cursor/run-hook.mjs\" postToolUseFailure" + } + ], + "preCompact": [ + { + "command": "node \"${CURSOR_PLUGIN_ROOT}/plugin/scripts/cursor/run-hook.mjs\" preCompact" + } + ], + "subagentStart": [ + { + "command": "node \"${CURSOR_PLUGIN_ROOT}/plugin/scripts/cursor/run-hook.mjs\" subagentStart" + } + ], + "subagentStop": [ + { + "command": "node \"${CURSOR_PLUGIN_ROOT}/plugin/scripts/cursor/run-hook.mjs\" subagentStop" } ], "stop": [ { - "command": "node ${CURSOR_PLUGIN_ROOT}/plugin/scripts/stop.mjs" + "command": "node \"${CURSOR_PLUGIN_ROOT}/plugin/scripts/cursor/run-detached.mjs\" stop" } ], "sessionEnd": [ { - "command": "node ${CURSOR_PLUGIN_ROOT}/plugin/scripts/session-end.mjs" + "command": "node \"${CURSOR_PLUGIN_ROOT}/plugin/scripts/cursor/run-detached.mjs\" sessionEnd" } ] } diff --git a/plugin/hooks/hooks.cursor.json b/plugin/hooks/hooks.cursor.json deleted file mode 100644 index 2efe3a1b5f..0000000000 --- a/plugin/hooks/hooks.cursor.json +++ /dev/null @@ -1,56 +0,0 @@ -{ - "version": 1, - "hooks": { - "sessionStart": [ - { - "command": "node \"${CURSOR_PLUGIN_ROOT}/scripts/cursor/run-hook.mjs\" sessionStart" - } - ], - "beforeSubmitPrompt": [ - { - "command": "node \"${CURSOR_PLUGIN_ROOT}/scripts/cursor/run-hook.mjs\" beforeSubmitPrompt" - } - ], - "preToolUse": [ - { - "matcher": "Edit|Write|Read|Glob|Grep|Shell", - "command": "node \"${CURSOR_PLUGIN_ROOT}/scripts/cursor/run-hook.mjs\" preToolUse" - } - ], - "postToolUse": [ - { - "command": "node \"${CURSOR_PLUGIN_ROOT}/scripts/cursor/run-hook.mjs\" postToolUse" - } - ], - "postToolUseFailure": [ - { - "command": "node \"${CURSOR_PLUGIN_ROOT}/scripts/cursor/run-hook.mjs\" postToolUseFailure" - } - ], - "preCompact": [ - { - "command": "node \"${CURSOR_PLUGIN_ROOT}/scripts/cursor/run-hook.mjs\" preCompact" - } - ], - "subagentStart": [ - { - "command": "node \"${CURSOR_PLUGIN_ROOT}/scripts/cursor/run-hook.mjs\" subagentStart" - } - ], - "subagentStop": [ - { - "command": "node \"${CURSOR_PLUGIN_ROOT}/scripts/cursor/run-hook.mjs\" subagentStop" - } - ], - "stop": [ - { - "command": "node \"${CURSOR_PLUGIN_ROOT}/scripts/cursor/run-detached.mjs\" stop" - } - ], - "sessionEnd": [ - { - "command": "node \"${CURSOR_PLUGIN_ROOT}/scripts/cursor/run-detached.mjs\" sessionEnd" - } - ] - } -} diff --git a/test/cursor-adapter.test.ts b/test/cursor-adapter.test.ts index 556ee464bf..69e7f64501 100644 --- a/test/cursor-adapter.test.ts +++ b/test/cursor-adapter.test.ts @@ -102,12 +102,12 @@ describe("cursor hook map", () => { expect(missing).toEqual([]); }); - it("covers the events hooks.cursor.json declares", () => { + it("covers the events plugin/cursor/hooks.json declares", () => { const config = JSON.parse( - readFileSync(join(REPO_ROOT, "plugin", "hooks", "hooks.cursor.json"), "utf-8"), + readFileSync(join(REPO_ROOT, "plugin", "cursor", "hooks.json"), "utf-8"), ) as { hooks: Record }; for (const event of Object.keys(config.hooks)) { - expect(isCursorHookKey(event), `hooks.cursor.json declares "${event}"`).toBe(true); + expect(isCursorHookKey(event), `plugin/cursor/hooks.json declares "${event}"`).toBe(true); } }); }); diff --git a/test/cursor-plugin.test.ts b/test/cursor-plugin.test.ts index afba14073f..a6c164c5af 100644 --- a/test/cursor-plugin.test.ts +++ b/test/cursor-plugin.test.ts @@ -79,6 +79,20 @@ describe("Cursor plugin hooks config", () => { } } }); + + it("routes every event through the Cursor adapter instead of the canonical hook", () => { + for (const [event, entries] of Object.entries(hooks.hooks) as Array< + [string, Array<{ command: string }>] + >) { + for (const entry of entries) { + if (event === "stop" || event === "sessionEnd") { + expect(entry.command).toContain("plugin/scripts/cursor/run-detached.mjs"); + } else { + expect(entry.command).toContain("plugin/scripts/cursor/run-hook.mjs"); + } + } + } + }); }); describe("Cursor plugin MCP config", () => { From a5517188f5faee4b1b6f9dd1e1457e7d86f350d6 Mon Sep 17 00:00:00 2001 From: Rohit Ghumare Date: Sun, 18 Oct 2026 05:32:14 +0000 Subject: [PATCH 16/18] fix(cursor): address Devin Review findings on workspace adapter and installer - delegate: pass resolved project in payload so pre-tool enrich stays scoped - workspace: prune session cache (7d / 200 entries), drop cached paths that no longer exist, never cache PWD/VSCODE_CWD guesses, honor CURSOR_PROJECT_DIR - install-local: --clear-user-hooks removes only agentmemory entries, keeps other hooks and top-level fields, backs up before writing - install-local/_env: allow keyless daemons (secret optional), parse quoted values, export prefix and inline comments in .env - docs:sync / skills:gen regenerated outputs --- AGENTS.md | 2 +- README.md | 6 +-- READMEs/README.ar-SA.md | 6 +-- READMEs/README.bn-BD.md | 6 +-- READMEs/README.cs-CZ.md | 6 +-- READMEs/README.da-DK.md | 6 +-- READMEs/README.de-DE.md | 6 +-- READMEs/README.el-GR.md | 6 +-- READMEs/README.es-ES.md | 6 +-- READMEs/README.fi-FI.md | 6 +-- READMEs/README.fr-FR.md | 6 +-- READMEs/README.he-IL.md | 6 +-- READMEs/README.hi-IN.md | 6 +-- READMEs/README.hu-HU.md | 6 +-- READMEs/README.id-ID.md | 6 +-- READMEs/README.it-IT.md | 6 +-- READMEs/README.ja-JP.md | 6 +-- READMEs/README.ko-KR.md | 6 +-- READMEs/README.nb-NO.md | 6 +-- READMEs/README.nl-NL.md | 6 +-- READMEs/README.pl-PL.md | 6 +-- READMEs/README.pt-BR.md | 6 +-- READMEs/README.pt-PT.md | 6 +-- READMEs/README.ro-RO.md | 6 +-- READMEs/README.ru-RU.md | 6 +-- READMEs/README.sv-SE.md | 6 +-- READMEs/README.th-TH.md | 6 +-- READMEs/README.tl-PH.md | 6 +-- READMEs/README.tr-TR.md | 6 +-- READMEs/README.uk-UA.md | 6 +-- READMEs/README.ur-PK.md | 6 +-- READMEs/README.vi-VN.md | 6 +-- READMEs/README.zh-CN.md | 6 +-- READMEs/README.zh-TW.md | 6 +-- assets/tags/light/stat-tests.svg | 4 +- assets/tags/stat-tests.svg | 4 +- integrations/cursor/README.md | 12 +++-- integrations/cursor/_env.mjs | 28 +++++++--- .../cursor/close-stale-am-sessions.mjs | 4 +- integrations/cursor/install-local.mjs | 31 ++++++++--- integrations/cursor/verify-flow.mjs | 4 +- plugin/scripts/cursor/run-detached.mjs | 40 ++++++++------ plugin/scripts/cursor/run-hook.mjs | 40 ++++++++------ plugin/skills/agentmemory-agents/REFERENCE.md | 2 +- scripts/docs-sync.state.json | 6 +-- src/hooks/cursor/delegate.ts | 1 + src/hooks/cursor/workspace.ts | 53 +++++++++++++------ test/cursor-adapter.test.ts | 4 +- test/cursor-env.test.ts | 37 +++++++++++++ test/cursor-workspace.test.ts | 53 +++++++++++++++++++ 50 files changed, 346 insertions(+), 177 deletions(-) mode change 100644 => 100755 plugin/scripts/cursor/run-detached.mjs mode change 100644 => 100755 plugin/scripts/cursor/run-hook.mjs create mode 100644 test/cursor-env.test.ts diff --git a/AGENTS.md b/AGENTS.md index 8c1bfc2eff..df4575ab11 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -101,7 +101,7 @@ Hook scripts in `src/hooks/` are standalone Node.js scripts (no iii-sdk import). ## Testing -- Before every commit run, in order: `npm run build`, `npm run skills:gen`, `npm run docs:sync`, `npm run skills:check`, `npm test` (3,600+ tests). Commit anything the generators changed. CI runs the same build, skills check and tests. +- Before every commit run, in order: `npm run build`, `npm run skills:gen`, `npm run docs:sync`, `npm run skills:check`, `npm test` (3,700+ tests). Commit anything the generators changed. CI runs the same build, skills check and tests. - Before any npm publish: `npm run release:gate` must pass. It installs the packed tarballs into a clean home and runs capture, recovery, restart, export/import, MCP and status checks against the installed CLI (see CONTRIBUTING.md, Release process) - Mock pattern: `vi.mock("iii-sdk")` with mock `sdk.trigger`, `kv.get/set/list` - Test files go in `test/` with `.test.ts` extension diff --git a/README.md b/README.md index ccb624347d..a4d587375b 100644 --- a/README.md +++ b/README.md @@ -72,7 +72,7 @@ 54 MCP tools 12 auto hooks 0 external DBs - 3,600+ tests passing + 3,700+ tests passing

@@ -1448,7 +1448,7 @@ fi | Prometheus / Grafana | iii OTEL + health monitor | | Custom plugin systems | `iii worker add ` | -**242 source files · ~55,000 LOC · 3,400+ tests · 324 functions · 67 KV scopes**, all on three primitives. No `agentmemory plugin install`. The plugin system is iii itself. +**247 source files · ~55,000 LOC · 3,400+ tests · 324 functions · 67 KV scopes**, all on three primitives. No `agentmemory plugin install`. The plugin system is iii itself. --- @@ -1880,7 +1880,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Content-Type: a ```bash npm run dev # Hot reload npm run build # Production build -npm test # 3,600+ tests +npm test # 3,700+ tests npm run test:integration # API tests (requires running services) ``` diff --git a/READMEs/README.ar-SA.md b/READMEs/README.ar-SA.md index bd28c4684e..06bc3da077 100644 --- a/READMEs/README.ar-SA.md +++ b/READMEs/README.ar-SA.md @@ -73,7 +73,7 @@ 54 MCP tools 12 auto hooks 0 external DBs - 3,600+ tests passing + 3,700+ tests passing

@@ -1439,7 +1439,7 @@ fi | Prometheus / Grafana | OTEL في iii + مراقب الحالة الصحية | | أنظمة إضافات مخصصة | `iii worker add ` | -**242 ملف مصدري · ~55,000 سطر برمجي · 3,600+ اختبار · 324 دالة · 67 نطاق KV**، كل ذلك على ثلاث بنى أساسية. لا يوجد أمر `agentmemory plugin install`. نظام الإضافات هو iii نفسه. +**247 ملف مصدري · ~55,000 سطر برمجي · 3,700+ اختبار · 324 دالة · 67 نطاق KV**، كل ذلك على ثلاث بنى أساسية. لا يوجد أمر `agentmemory plugin install`. نظام الإضافات هو iii نفسه. --- @@ -1863,7 +1863,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Content-Type: a ```bash npm run dev # Hot reload npm run build # Production build -npm test # 3,600+ tests +npm test # 3,700+ tests npm run test:integration # API tests (requires running services) ``` diff --git a/READMEs/README.bn-BD.md b/READMEs/README.bn-BD.md index 4886b94c8d..8ff7a07e81 100644 --- a/READMEs/README.bn-BD.md +++ b/READMEs/README.bn-BD.md @@ -71,7 +71,7 @@ 54 MCP টুল 12 অটো হুক 0 এক্সটার্নাল ডিবি - 3,600+ টেস্ট পাস + 3,700+ টেস্ট পাস

@@ -1437,7 +1437,7 @@ fi | Prometheus / Grafana | iii OTEL + হেলথ মনিটর | | কাস্টম প্লাগইন সিস্টেম | `iii worker add ` | -**242 সোর্স ফাইল · ~55,000 LOC · 3,400+ টেস্ট · 324 ফাংশন · 67 KV স্কোপ**, সবকিছু তিনটি প্রিমিটিভের উপর। কোনো `agentmemory plugin install` নেই। প্লাগইন সিস্টেমটাই iii নিজে। +**247 সোর্স ফাইল · ~55,000 LOC · 3,400+ টেস্ট · 324 ফাংশন · 67 KV স্কোপ**, সবকিছু তিনটি প্রিমিটিভের উপর। কোনো `agentmemory plugin install` নেই। প্লাগইন সিস্টেমটাই iii নিজে। --- @@ -1861,7 +1861,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Content-Type: a ```bash npm run dev # Hot reload npm run build # Production build -npm test # 3,600+ tests +npm test # 3,700+ tests npm run test:integration # API tests (requires running services) ``` diff --git a/READMEs/README.cs-CZ.md b/READMEs/README.cs-CZ.md index dc94f6a4f5..08107040c6 100644 --- a/READMEs/README.cs-CZ.md +++ b/READMEs/README.cs-CZ.md @@ -71,7 +71,7 @@ 54 MCP nástrojů 12 automatických hooks 0 externích databází - 3,600+ testů úspěšně proběhlo + 3,700+ testů úspěšně proběhlo

@@ -1446,7 +1446,7 @@ fi | Prometheus / Grafana | iii OTEL + health monitor | | Vlastní systémy pluginů | `iii worker add ` | -**242 zdrojových souborů · ~55,000 řádků kódu · 3,400+ testů · 324 funkcí · 67 KV scopes**, vše na třech primitivech. Žádné `agentmemory plugin install`. Systém pluginů je samo iii. +**247 zdrojových souborů · ~55,000 řádků kódu · 3,400+ testů · 324 funkcí · 67 KV scopes**, vše na třech primitivech. Žádné `agentmemory plugin install`. Systém pluginů je samo iii. --- @@ -1870,7 +1870,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Content-Type: a ```bash npm run dev # Hot reload npm run build # Production build -npm test # 3,600+ tests +npm test # 3,700+ tests npm run test:integration # API tests (requires running services) ``` diff --git a/READMEs/README.da-DK.md b/READMEs/README.da-DK.md index 0c53d6beba..f643ebbf32 100644 --- a/READMEs/README.da-DK.md +++ b/READMEs/README.da-DK.md @@ -71,7 +71,7 @@ 54 MCP-værktøjer 12 automatiske hooks 0 eksterne databaser - 3,600+ beståede tests + 3,700+ beståede tests

@@ -1436,7 +1436,7 @@ fi | Prometheus / Grafana | iii OTEL + health monitor | | Custom plugin-systemer | `iii worker add ` | -**242 kildefiler · ~55,000 LOC · 3,400+ tests · 324 funktioner · 67 KV-scopes**, alt på tre primitiver. Intet `agentmemory plugin install`. Plugin-systemet er iii selv. +**247 kildefiler · ~55,000 LOC · 3,400+ tests · 324 funktioner · 67 KV-scopes**, alt på tre primitiver. Intet `agentmemory plugin install`. Plugin-systemet er iii selv. --- @@ -1860,7 +1860,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Content-Type: a ```bash npm run dev # Hot reload npm run build # Production build -npm test # 3,600+ tests +npm test # 3,700+ tests npm run test:integration # API tests (requires running services) ``` diff --git a/READMEs/README.de-DE.md b/READMEs/README.de-DE.md index 95d5cb58d2..8998868ed9 100644 --- a/READMEs/README.de-DE.md +++ b/READMEs/README.de-DE.md @@ -71,7 +71,7 @@ 54 MCP-Tools 12 Auto-Hooks 0 externe DBs - 3,600+ bestandene Tests + 3,700+ bestandene Tests

@@ -1446,7 +1446,7 @@ fi | Prometheus / Grafana | iii OTEL + Health-Monitor | | Eigene Plugin-Systeme | `iii worker add ` | -**242 Quelldateien · ~55,000 LOC · 3,400+ Tests · 324 Funktionen · 67 KV-Scopes**, alles auf drei Primitiven. Kein `agentmemory plugin install`. Das Plugin-System ist iii selbst. +**247 Quelldateien · ~55,000 LOC · 3,400+ Tests · 324 Funktionen · 67 KV-Scopes**, alles auf drei Primitiven. Kein `agentmemory plugin install`. Das Plugin-System ist iii selbst. --- @@ -1870,7 +1870,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Content-Type: a ```bash npm run dev # Hot reload npm run build # Production build -npm test # 3,600+ tests +npm test # 3,700+ tests npm run test:integration # API tests (requires running services) ``` diff --git a/READMEs/README.el-GR.md b/READMEs/README.el-GR.md index 2169d41852..5f18084d36 100644 --- a/READMEs/README.el-GR.md +++ b/READMEs/README.el-GR.md @@ -71,7 +71,7 @@ 54 εργαλεία MCP 12 αυτόματα hooks 0 εξωτερικές βάσεις δεδομένων - 3,600+ επιτυχημένες δοκιμές + 3,700+ επιτυχημένες δοκιμές

@@ -1438,7 +1438,7 @@ fi | Prometheus / Grafana | iii OTEL + monitor υγείας | | Προσαρμοσμένα συστήματα plugin | `iii worker add ` | -**242 αρχεία πηγαίου κώδικα · ~55,000 LOC · 3,400+ δοκιμές · 324 functions · 67 KV scopes**, όλα πάνω σε τρία primitives. Δεν υπάρχει `agentmemory plugin install`. Το σύστημα plugin είναι το ίδιο το iii. +**247 αρχεία πηγαίου κώδικα · ~55,000 LOC · 3,400+ δοκιμές · 324 functions · 67 KV scopes**, όλα πάνω σε τρία primitives. Δεν υπάρχει `agentmemory plugin install`. Το σύστημα plugin είναι το ίδιο το iii. --- @@ -1862,7 +1862,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Content-Type: a ```bash npm run dev # Hot reload npm run build # Production build -npm test # 3,600+ tests +npm test # 3,700+ tests npm run test:integration # API tests (requires running services) ``` diff --git a/READMEs/README.es-ES.md b/READMEs/README.es-ES.md index dce73f859f..1da053e66d 100644 --- a/READMEs/README.es-ES.md +++ b/READMEs/README.es-ES.md @@ -71,7 +71,7 @@ 54 tools MCP 12 hooks automáticos 0 bases de datos externas - 3,600+ tests superados + 3,700+ tests superados

@@ -1446,7 +1446,7 @@ fi | Prometheus / Grafana | iii OTEL + monitor de salud | | Sistemas de plugins propios | `iii worker add ` | -**242 ficheros de código · ~55,000 LOC · 3,400+ tests · 324 funciones · 67 scopes KV**, todo sobre tres primitivos. No hay `agentmemory plugin install`. El sistema de plugins es iii mismo. +**247 ficheros de código · ~55,000 LOC · 3,400+ tests · 324 funciones · 67 scopes KV**, todo sobre tres primitivos. No hay `agentmemory plugin install`. El sistema de plugins es iii mismo. --- @@ -1870,7 +1870,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Content-Type: a ```bash npm run dev # Hot reload npm run build # Production build -npm test # 3,600+ tests +npm test # 3,700+ tests npm run test:integration # API tests (requires running services) ``` diff --git a/READMEs/README.fi-FI.md b/READMEs/README.fi-FI.md index 42e9a5e0ab..6333cc556b 100644 --- a/READMEs/README.fi-FI.md +++ b/READMEs/README.fi-FI.md @@ -71,7 +71,7 @@ 54 MCP-työkalua 12 automaattista hookia 0 ulkoista tietokantaa - 3,600+ testiä läpäisty + 3,700+ testiä läpäisty

@@ -1446,7 +1446,7 @@ fi | Prometheus / Grafana | iii OTEL + terveysmonitori | | Mukautetut plugin-järjestelmät | `iii worker add ` | -**242 lähdetiedostoa · ~55,000 LOC · 3,400+ testiä · 324 funktiota · 67 KV-scopea**, kaikki kolmen primitiivin päällä. Ei `agentmemory plugin install` -komentoa. Plugin-järjestelmä on iii itse. +**247 lähdetiedostoa · ~55,000 LOC · 3,400+ testiä · 324 funktiota · 67 KV-scopea**, kaikki kolmen primitiivin päällä. Ei `agentmemory plugin install` -komentoa. Plugin-järjestelmä on iii itse. --- @@ -1870,7 +1870,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Content-Type: a ```bash npm run dev # Hot reload npm run build # Production build -npm test # 3,600+ tests +npm test # 3,700+ tests npm run test:integration # API tests (requires running services) ``` diff --git a/READMEs/README.fr-FR.md b/READMEs/README.fr-FR.md index d2dde35a20..e26b62854d 100644 --- a/READMEs/README.fr-FR.md +++ b/READMEs/README.fr-FR.md @@ -71,7 +71,7 @@ 54 MCP tools 12 auto hooks 0 external DBs - 3,600+ tests passing + 3,700+ tests passing

@@ -1448,7 +1448,7 @@ fi | Prometheus / Grafana | iii OTEL + moniteur de santé | | Systèmes de plugins custom | `iii worker add ` | -**242 fichiers sources · ~55,000 LOC · 3,600+ tests · 324 fonctions · 67 scopes KV**, tout sur trois primitives. Pas de `agentmemory plugin install`. Le système de plugins, c'est iii lui-même. +**247 fichiers sources · ~55,000 LOC · 3,700+ tests · 324 fonctions · 67 scopes KV**, tout sur trois primitives. Pas de `agentmemory plugin install`. Le système de plugins, c'est iii lui-même. --- @@ -1872,7 +1872,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Content-Type: a ```bash npm run dev # Hot reload npm run build # Production build -npm test # 3,600+ tests +npm test # 3,700+ tests npm run test:integration # API tests (requires running services) ``` diff --git a/READMEs/README.he-IL.md b/READMEs/README.he-IL.md index 91f065d3a3..ce2579054f 100644 --- a/READMEs/README.he-IL.md +++ b/READMEs/README.he-IL.md @@ -73,7 +73,7 @@ 54 כלי MCP 12 hooks אוטומטיים 0 מסדי נתונים חיצוניים - 3,600+ בדיקות עוברות + 3,700+ בדיקות עוברות

@@ -1439,7 +1439,7 @@ fi | Prometheus / Grafana | iii OTEL + מוניטור health | | מערכות plugin מותאמות אישית | `iii worker add ` | -**242 קבצי מקור · ~55,000 LOC · 3,400+ בדיקות · 324 פונקציות · 67 תחומי KV**, הכול על שלושה primitives. אין `agentmemory plugin install`. מערכת ה-plugin היא iii עצמו. +**247 קבצי מקור · ~55,000 LOC · 3,400+ בדיקות · 324 פונקציות · 67 תחומי KV**, הכול על שלושה primitives. אין `agentmemory plugin install`. מערכת ה-plugin היא iii עצמו. --- @@ -1863,7 +1863,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Content-Type: a ```bash npm run dev # Hot reload npm run build # Production build -npm test # 3,600+ tests +npm test # 3,700+ tests npm run test:integration # API tests (requires running services) ``` diff --git a/READMEs/README.hi-IN.md b/READMEs/README.hi-IN.md index 927d6d554f..b65667e7db 100644 --- a/READMEs/README.hi-IN.md +++ b/READMEs/README.hi-IN.md @@ -71,7 +71,7 @@ 54 MCP tools 12 auto hooks 0 external DBs - 3,600+ tests passing + 3,700+ tests passing

@@ -1449,7 +1449,7 @@ fi | Prometheus / Grafana | iii OTEL + health monitor | | Custom plugin systems | `iii worker add ` | -**242 source files · ~55,000 LOC · 3,400+ tests · 324 functions · 67 KV scopes**, सब कुछ तीन primitives पर। कोई `agentmemory plugin install` नहीं। Plugin system iii स्वयं है। +**247 source files · ~55,000 LOC · 3,400+ tests · 324 functions · 67 KV scopes**, सब कुछ तीन primitives पर। कोई `agentmemory plugin install` नहीं। Plugin system iii स्वयं है। --- @@ -1873,7 +1873,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Content-Type: a ```bash npm run dev # Hot reload npm run build # Production build -npm test # 3,600+ tests +npm test # 3,700+ tests npm run test:integration # API tests (requires running services) ``` diff --git a/READMEs/README.hu-HU.md b/READMEs/README.hu-HU.md index 046e91fb45..4db97d34f0 100644 --- a/READMEs/README.hu-HU.md +++ b/READMEs/README.hu-HU.md @@ -71,7 +71,7 @@ 54 MCP eszköz 12 automatikus hook 0 külső adatbázis - 3,600+ sikeres teszt + 3,700+ sikeres teszt

@@ -1446,7 +1446,7 @@ A `/agentmemory/export` emellett elfogadja a `?maxSessions=`-t és a `?offset=`- | Prometheus / Grafana | iii OTEL + egészségfigyelő | | Egyéni plugin-rendszerek | `iii worker add ` | -**242 forrásfájl · ~55,000 LOC · 3,400+ teszt · 324 funkció · 67 KV-hatókör**, mindez három primitíven. Nincs `agentmemory plugin install`. A plugin-rendszer maga az iii. +**247 forrásfájl · ~55,000 LOC · 3,400+ teszt · 324 funkció · 67 KV-hatókör**, mindez három primitíven. Nincs `agentmemory plugin install`. A plugin-rendszer maga az iii. --- @@ -1870,7 +1870,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Content-Type: a ```bash npm run dev # Hot reload npm run build # Production build -npm test # 3,600+ tests +npm test # 3,700+ tests npm run test:integration # API tests (requires running services) ``` diff --git a/READMEs/README.id-ID.md b/READMEs/README.id-ID.md index 5503f72e2a..867f9e0e06 100644 --- a/READMEs/README.id-ID.md +++ b/READMEs/README.id-ID.md @@ -71,7 +71,7 @@ 54 tool MCP 12 hook otomatis 0 DB eksternal - 3,600+ pengujian lolos + 3,700+ pengujian lolos

@@ -1447,7 +1447,7 @@ fi | Prometheus / Grafana | iii OTEL + health monitor | | Sistem plugin custom | `iii worker add ` | -**242 file sumber · ~55,000 LOC · 3,600+ pengujian · 324 fungsi · 67 scope KV**, semua di atas tiga primitif. Tidak ada `agentmemory plugin install`. Sistem plugin-nya adalah iii itu sendiri. +**247 file sumber · ~55,000 LOC · 3,700+ pengujian · 324 fungsi · 67 scope KV**, semua di atas tiga primitif. Tidak ada `agentmemory plugin install`. Sistem plugin-nya adalah iii itu sendiri. --- @@ -1871,7 +1871,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Content-Type: a ```bash npm run dev # Hot reload npm run build # Production build -npm test # 3,600+ tests +npm test # 3,700+ tests npm run test:integration # API tests (requires running services) ``` diff --git a/READMEs/README.it-IT.md b/READMEs/README.it-IT.md index 3f881f3729..8b8787a1e8 100644 --- a/READMEs/README.it-IT.md +++ b/READMEs/README.it-IT.md @@ -71,7 +71,7 @@ 54 MCP tools 12 auto hooks 0 external DBs - 3,600+ tests passing + 3,700+ tests passing

@@ -1446,7 +1446,7 @@ fi | Prometheus / Grafana | iii OTEL + monitor di salute | | Sistemi di plugin personalizzati | `iii worker add ` | -**242 file sorgente · ~55,000 righe di codice · 3,400+ test · 324 funzioni · 67 scope KV**, tutto su tre primitive. Nessun `agentmemory plugin install`. Il sistema di plugin è iii stesso. +**247 file sorgente · ~55,000 righe di codice · 3,400+ test · 324 funzioni · 67 scope KV**, tutto su tre primitive. Nessun `agentmemory plugin install`. Il sistema di plugin è iii stesso. --- @@ -1870,7 +1870,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Content-Type: a ```bash npm run dev # Hot reload npm run build # Production build -npm test # 3,600+ tests +npm test # 3,700+ tests npm run test:integration # API tests (requires running services) ``` diff --git a/READMEs/README.ja-JP.md b/READMEs/README.ja-JP.md index e6160b754c..8c2b8870c5 100644 --- a/READMEs/README.ja-JP.md +++ b/READMEs/README.ja-JP.md @@ -71,7 +71,7 @@ 54 MCP ツール 12 自動 hooks 外部 DB 0 個 - 3,600+ 件のテストが成功 + 3,700+ 件のテストが成功

@@ -1445,7 +1445,7 @@ fi | Prometheus / Grafana | iii OTEL + ヘルスモニタ | | カスタムプラグインシステム | `iii worker add ` | -**242 ソースファイル · ~55,000 LOC · 3,400+ テスト · 324 functions · 67 KV スコープ** — すべて 3 つのプリミティブの上に。`agentmemory plugin install` はありません。プラグインシステムは iii そのものです。 +**247 ソースファイル · ~55,000 LOC · 3,400+ テスト · 324 functions · 67 KV スコープ** — すべて 3 つのプリミティブの上に。`agentmemory plugin install` はありません。プラグインシステムは iii そのものです。 --- @@ -1869,7 +1869,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Content-Type: a ```bash npm run dev # Hot reload npm run build # Production build -npm test # 3,600+ tests +npm test # 3,700+ tests npm run test:integration # API tests (requires running services) ``` diff --git a/READMEs/README.ko-KR.md b/READMEs/README.ko-KR.md index 2b806c19a2..b36e6b0721 100644 --- a/READMEs/README.ko-KR.md +++ b/READMEs/README.ko-KR.md @@ -71,7 +71,7 @@ 54 MCP tools 12 auto hooks 0 external DBs - 3,600+ tests passing + 3,700+ tests passing

@@ -1446,7 +1446,7 @@ fi | Prometheus / Grafana | iii OTEL + health 모니터 | | 커스텀 플러그인 시스템 | `iii worker add ` | -**소스 파일 242개 · LOC ~55,000줄 · 테스트 3,400+개 · 함수 324개 · KV 스코프 67개**, 모두 세 가지 프리미티브 위에서 동작합니다. `agentmemory plugin install` 같은 것은 없습니다. 플러그인 시스템은 곧 iii 자체입니다. +**소스 파일 247개 · LOC ~55,000줄 · 테스트 3,400+개 · 함수 324개 · KV 스코프 67개**, 모두 세 가지 프리미티브 위에서 동작합니다. `agentmemory plugin install` 같은 것은 없습니다. 플러그인 시스템은 곧 iii 자체입니다. --- @@ -1870,7 +1870,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Content-Type: a ```bash npm run dev # Hot reload npm run build # Production build -npm test # 3,600+ tests +npm test # 3,700+ tests npm run test:integration # API tests (requires running services) ``` diff --git a/READMEs/README.nb-NO.md b/READMEs/README.nb-NO.md index 31e07c3e6a..3b8db43ca9 100644 --- a/READMEs/README.nb-NO.md +++ b/READMEs/README.nb-NO.md @@ -71,7 +71,7 @@ 54 MCP tools 12 auto hooks 0 external DBs - 3,600+ tests passing + 3,700+ tests passing

@@ -1447,7 +1447,7 @@ fi | Prometheus / Grafana | iii OTEL + helseovervåker | | Egendefinerte plugin-systemer | `iii worker add ` | -**242 kildefiler · ~55,000 LOC · 3,400+ tester · 324 funksjoner · 67 KV-scopes**, alt på tre primitiver. Ingen `agentmemory plugin install`. Plugin-systemet er iii selv. +**247 kildefiler · ~55,000 LOC · 3,400+ tester · 324 funksjoner · 67 KV-scopes**, alt på tre primitiver. Ingen `agentmemory plugin install`. Plugin-systemet er iii selv. --- @@ -1871,7 +1871,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Content-Type: a ```bash npm run dev # Hot reload npm run build # Production build -npm test # 3,600+ tests +npm test # 3,700+ tests npm run test:integration # API tests (requires running services) ``` diff --git a/READMEs/README.nl-NL.md b/READMEs/README.nl-NL.md index 0977826656..5693c6771f 100644 --- a/READMEs/README.nl-NL.md +++ b/READMEs/README.nl-NL.md @@ -71,7 +71,7 @@ 54 MCP tools 12 auto hooks 0 external DBs - 3,600+ tests passing + 3,700+ tests passing

@@ -1446,7 +1446,7 @@ fi | Prometheus / Grafana | iii OTEL + health monitor | | Custom plugin-systemen | `iii worker add ` | -**242 bronbestanden · ~55,000 LOC · 3,400+ tests · 324 functies · 67 KV-scopes**, allemaal op drie primitieven. Geen `agentmemory plugin install`. Het pluginsysteem is iii zelf. +**247 bronbestanden · ~55,000 LOC · 3,400+ tests · 324 functies · 67 KV-scopes**, allemaal op drie primitieven. Geen `agentmemory plugin install`. Het pluginsysteem is iii zelf. --- @@ -1870,7 +1870,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Content-Type: a ```bash npm run dev # Hot reload npm run build # Production build -npm test # 3,600+ tests +npm test # 3,700+ tests npm run test:integration # API tests (requires running services) ``` diff --git a/READMEs/README.pl-PL.md b/READMEs/README.pl-PL.md index 2e3255c9eb..1a556af20e 100644 --- a/READMEs/README.pl-PL.md +++ b/READMEs/README.pl-PL.md @@ -71,7 +71,7 @@ 54 narzędzia MCP 12 automatycznych hooków 0 zewnętrznych baz danych - 3,600+ zaliczonych testów + 3,700+ zaliczonych testów

@@ -1446,7 +1446,7 @@ fi | Prometheus / Grafana | iii OTEL + monitor stanu | | Niestandardowe systemy pluginów | `iii worker add ` | -**242 pliki źródłowe · ~55,000 LOC · 3,600+ testów · 324 funkcje · 67 zakresów KV**, wszystko na trzech prymitywach. Nie ma `agentmemory plugin install`. Systemem pluginów jest sam iii. +**247 pliki źródłowe · ~55,000 LOC · 3,700+ testów · 324 funkcje · 67 zakresów KV**, wszystko na trzech prymitywach. Nie ma `agentmemory plugin install`. Systemem pluginów jest sam iii. --- @@ -1870,7 +1870,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Content-Type: a ```bash npm run dev # Hot reload npm run build # Production build -npm test # 3,600+ tests +npm test # 3,700+ tests npm run test:integration # API tests (requires running services) ``` diff --git a/READMEs/README.pt-BR.md b/READMEs/README.pt-BR.md index 7fa780c894..b11ee19955 100644 --- a/READMEs/README.pt-BR.md +++ b/READMEs/README.pt-BR.md @@ -71,7 +71,7 @@ 54 MCP tools 12 auto hooks 0 external DBs - 3,600+ tests passing + 3,700+ tests passing

@@ -1447,7 +1447,7 @@ fi | Prometheus / Grafana | iii OTEL + monitor de saúde | | Sistemas de plugin customizados | `iii worker add ` | -**242 arquivos de código · ~55,000 LOC · 3,400+ testes · 324 funções · 67 escopos KV**, tudo em cima de três primitivos. Sem `agentmemory plugin install`. O sistema de plugins é o próprio iii. +**247 arquivos de código · ~55,000 LOC · 3,400+ testes · 324 funções · 67 escopos KV**, tudo em cima de três primitivos. Sem `agentmemory plugin install`. O sistema de plugins é o próprio iii. --- @@ -1871,7 +1871,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Content-Type: a ```bash npm run dev # Hot reload npm run build # Production build -npm test # 3,600+ tests +npm test # 3,700+ tests npm run test:integration # API tests (requires running services) ``` diff --git a/READMEs/README.pt-PT.md b/READMEs/README.pt-PT.md index bd099331e2..5f09959a69 100644 --- a/READMEs/README.pt-PT.md +++ b/READMEs/README.pt-PT.md @@ -71,7 +71,7 @@ 54 ferramentas MCP 12 hooks automáticos 0 bases de dados externas - 3,600+ testes aprovados + 3,700+ testes aprovados

@@ -1446,7 +1446,7 @@ O `/agentmemory/export` também aceita `?maxSessions=` e `?offset=` para dividir | Prometheus / Grafana | iii OTEL + monitor de saúde | | Sistemas de plugins personalizados | `iii worker add ` | -**242 ficheiros de código-fonte · ~55,000 LOC · 3,400+ testes · 324 funções · 67 âmbitos de KV**, tudo sobre três primitivos. Sem `agentmemory plugin install`. O sistema de plugins é o próprio iii. +**247 ficheiros de código-fonte · ~55,000 LOC · 3,400+ testes · 324 funções · 67 âmbitos de KV**, tudo sobre três primitivos. Sem `agentmemory plugin install`. O sistema de plugins é o próprio iii. --- @@ -1870,7 +1870,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Content-Type: a ```bash npm run dev # Hot reload npm run build # Production build -npm test # 3,600+ tests +npm test # 3,700+ tests npm run test:integration # API tests (requires running services) ``` diff --git a/READMEs/README.ro-RO.md b/READMEs/README.ro-RO.md index c41760f0c4..e0fa91815b 100644 --- a/READMEs/README.ro-RO.md +++ b/READMEs/README.ro-RO.md @@ -71,7 +71,7 @@ 54 de instrumente MCP 12 hook-uri automate 0 baze de date externe - 3,600+ teste trecute + 3,700+ teste trecute

@@ -1430,7 +1430,7 @@ fi | Prometheus / Grafana | iii OTEL + monitor de sănătate | | Sisteme de plugin-uri personalizate | `iii worker add ` | -**242 de fișiere sursă · ~55,000 LOC · 3,600+ de teste · 324 de funcții · 67 de domenii KV**, toate pe trei primitive. Niciun `agentmemory plugin install`. Sistemul de plugin-uri este chiar iii. +**247 de fișiere sursă · ~55,000 LOC · 3,700+ de teste · 324 de funcții · 67 de domenii KV**, toate pe trei primitive. Niciun `agentmemory plugin install`. Sistemul de plugin-uri este chiar iii. --- @@ -1854,7 +1854,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Content-Type: a ```bash npm run dev # Hot reload npm run build # Production build -npm test # 3,600+ tests +npm test # 3,700+ tests npm run test:integration # API tests (requires running services) ``` diff --git a/READMEs/README.ru-RU.md b/READMEs/README.ru-RU.md index 0e9423ebbb..e5ed9480b4 100644 --- a/READMEs/README.ru-RU.md +++ b/READMEs/README.ru-RU.md @@ -71,7 +71,7 @@ 54 MCP tools 12 auto hooks 0 external DBs - 3,600+ tests passing + 3,700+ tests passing

@@ -1446,7 +1446,7 @@ fi | Prometheus / Grafana | iii OTEL + монитор состояния | | Самописные плагинные системы | `iii worker add ` | -**242 исходных файлов · ~55,000 LOC · 3,400+ тестов · 324 функций · 67 KV-scope**, всё на трёх примитивах. Никакого `agentmemory plugin install`. Плагинная система — это сам iii. +**247 исходных файлов · ~55,000 LOC · 3,400+ тестов · 324 функций · 67 KV-scope**, всё на трёх примитивах. Никакого `agentmemory plugin install`. Плагинная система — это сам iii. --- @@ -1870,7 +1870,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Content-Type: a ```bash npm run dev # Hot reload npm run build # Production build -npm test # 3,600+ tests +npm test # 3,700+ tests npm run test:integration # API tests (requires running services) ``` diff --git a/READMEs/README.sv-SE.md b/READMEs/README.sv-SE.md index fc1104b68d..315c06a659 100644 --- a/READMEs/README.sv-SE.md +++ b/READMEs/README.sv-SE.md @@ -71,7 +71,7 @@ 54 MCP-verktyg 12 automatiska hooks 0 externa databaser - 3,600+ godkända tester + 3,700+ godkända tester

@@ -1437,7 +1437,7 @@ fi | Prometheus / Grafana | iii OTEL + hälsoövervakare | | Anpassade pluginsystem | `iii worker add ` | -**242 källkodsfiler · ~55,000 LOC · 3,400+ tester · 324 funktioner · 67 KV-scopes**, allt på tre primitiv. Inget `agentmemory plugin install`. Pluginsystemet är iii självt. +**247 källkodsfiler · ~55,000 LOC · 3,400+ tester · 324 funktioner · 67 KV-scopes**, allt på tre primitiv. Inget `agentmemory plugin install`. Pluginsystemet är iii självt. --- @@ -1861,7 +1861,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Content-Type: a ```bash npm run dev # Hot reload npm run build # Production build -npm test # 3,600+ tests +npm test # 3,700+ tests npm run test:integration # API tests (requires running services) ``` diff --git a/READMEs/README.th-TH.md b/READMEs/README.th-TH.md index d17b0cd203..ce64755886 100644 --- a/READMEs/README.th-TH.md +++ b/READMEs/README.th-TH.md @@ -71,7 +71,7 @@ 54 เครื่องมือ MCP 12 hook อัตโนมัติ ไม่ต้องพึ่ง external DB เลย - ผ่านการทดสอบ 3,600+ รายการ + ผ่านการทดสอบ 3,700+ รายการ

@@ -1444,7 +1444,7 @@ fi | Prometheus / Grafana | iii OTEL + health monitor | | Custom plugin systems | `iii worker add ` | -**242 source file · ~55,000 LOC · 3,400+ การทดสอบ · 324 function · 67 KV scope** ทั้งหมดอยู่บน primitive สามตัว ไม่มี `agentmemory plugin install` ระบบ plugin ก็คือ iii เองนั่นแหละ +**247 source file · ~55,000 LOC · 3,400+ การทดสอบ · 324 function · 67 KV scope** ทั้งหมดอยู่บน primitive สามตัว ไม่มี `agentmemory plugin install` ระบบ plugin ก็คือ iii เองนั่นแหละ --- @@ -1868,7 +1868,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Content-Type: a ```bash npm run dev # Hot reload npm run build # Production build -npm test # 3,600+ tests +npm test # 3,700+ tests npm run test:integration # API tests (requires running services) ``` diff --git a/READMEs/README.tl-PH.md b/READMEs/README.tl-PH.md index 1ac0b7d081..11906e8268 100644 --- a/READMEs/README.tl-PH.md +++ b/READMEs/README.tl-PH.md @@ -71,7 +71,7 @@ 54 MCP tool 12 awtomatikong hook 0 panlabas na DB - 3,600+ pumapasang test + 3,700+ pumapasang test

@@ -1446,7 +1446,7 @@ Tinatanggap din ng `/agentmemory/export` ang `?maxSessions=` at `?offset=` para | Prometheus / Grafana | iii OTEL + health monitor | | Custom na plugin system | `iii worker add ` | -**242 na source file · ~55,000 LOC · 3,400+ na test · 324 na function · 67 na KV scope**, lahat sa tatlong primitive. Walang `agentmemory plugin install`. Ang plugin system mismo ay ang iii. +**247 na source file · ~55,000 LOC · 3,400+ na test · 324 na function · 67 na KV scope**, lahat sa tatlong primitive. Walang `agentmemory plugin install`. Ang plugin system mismo ay ang iii. --- @@ -1870,7 +1870,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Content-Type: a ```bash npm run dev # Hot reload npm run build # Production build -npm test # 3,600+ tests +npm test # 3,700+ tests npm run test:integration # API tests (requires running services) ``` diff --git a/READMEs/README.tr-TR.md b/READMEs/README.tr-TR.md index 7fb8e85a9e..2f13a48deb 100644 --- a/READMEs/README.tr-TR.md +++ b/READMEs/README.tr-TR.md @@ -71,7 +71,7 @@ 54 MCP tools 12 auto hooks 0 external DBs - 3,600+ tests passing + 3,700+ tests passing

@@ -1437,7 +1437,7 @@ fi | Prometheus / Grafana | iii OTEL + health monitor | | Custom eklenti sistemleri | `iii worker add ` | -**242 kaynak dosya · ~55,000 LOC · 3,400+ test · 324 fonksiyon · 67 KV scope**, hepsi üç primitif üzerinde. `agentmemory plugin install` yok. Eklenti sistemi, iii'nin kendisidir. +**247 kaynak dosya · ~55,000 LOC · 3,400+ test · 324 fonksiyon · 67 KV scope**, hepsi üç primitif üzerinde. `agentmemory plugin install` yok. Eklenti sistemi, iii'nin kendisidir. --- @@ -1861,7 +1861,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Content-Type: a ```bash npm run dev # Hot reload npm run build # Production build -npm test # 3,600+ tests +npm test # 3,700+ tests npm run test:integration # API tests (requires running services) ``` diff --git a/READMEs/README.uk-UA.md b/READMEs/README.uk-UA.md index 8bc2c90b6d..eff7749d0d 100644 --- a/READMEs/README.uk-UA.md +++ b/READMEs/README.uk-UA.md @@ -71,7 +71,7 @@ 54 інструменти MCP 12 автоматичних хуків 0 зовнішніх БД - 3,600+ тестів пройдено + 3,700+ тестів пройдено

@@ -1447,7 +1447,7 @@ fi | Prometheus / Grafana | iii OTEL + монітор стану здоров'я | | Власні системи плагінів | `iii worker add ` | -**242 вихідних файлів · ~55,000 LOC · 3,400+ тестів · 324 функцій · 67 KV-скоупів**, усе на трьох примітивах. Жодного `agentmemory plugin install`. Система плагінів — це сам iii. +**247 вихідних файлів · ~55,000 LOC · 3,400+ тестів · 324 функцій · 67 KV-скоупів**, усе на трьох примітивах. Жодного `agentmemory plugin install`. Система плагінів — це сам iii. --- @@ -1871,7 +1871,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Content-Type: a ```bash npm run dev # Hot reload npm run build # Production build -npm test # 3,600+ tests +npm test # 3,700+ tests npm run test:integration # API tests (requires running services) ``` diff --git a/READMEs/README.ur-PK.md b/READMEs/README.ur-PK.md index aa90388812..fd7bc2c11b 100644 --- a/READMEs/README.ur-PK.md +++ b/READMEs/README.ur-PK.md @@ -73,7 +73,7 @@ 54 MCP ٹولز 12 خودکار ہکس 0 خارجی ڈیٹابیسز - 3,600+ ٹیسٹس پاس ہو رہے ہیں + 3,700+ ٹیسٹس پاس ہو رہے ہیں

@@ -1432,7 +1432,7 @@ fi | Prometheus / Grafana | iii OTEL + health monitor | | کسٹم plugin سسٹمز | `iii worker add ` | -**242 سورس فائلز · ~55,000 لائنز کوڈ · 3,600+ ٹیسٹس · 324 فنکشنز · 67 KV اسکوپس**، سب تین primitives پر۔ کوئی `agentmemory plugin install` نہیں۔ plugin سسٹم خود iii ہی ہے۔ +**247 سورس فائلز · ~55,000 لائنز کوڈ · 3,700+ ٹیسٹس · 324 فنکشنز · 67 KV اسکوپس**، سب تین primitives پر۔ کوئی `agentmemory plugin install` نہیں۔ plugin سسٹم خود iii ہی ہے۔ --- @@ -1854,7 +1854,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Content-Type: a ```bash npm run dev # Hot reload npm run build # Production build -npm test # 3,600+ tests +npm test # 3,700+ tests npm run test:integration # API tests (requires running services) ``` diff --git a/READMEs/README.vi-VN.md b/READMEs/README.vi-VN.md index ef7bb14eda..a0f9030a3f 100644 --- a/READMEs/README.vi-VN.md +++ b/READMEs/README.vi-VN.md @@ -71,7 +71,7 @@ 54 MCP tools 12 auto hooks 0 external DBs - 3,600+ tests passing + 3,700+ tests passing

@@ -1437,7 +1437,7 @@ fi | Prometheus / Grafana | iii OTEL + health monitor | | Hệ thống plugin tùy chỉnh | `iii worker add ` | -**242 file source · ~55,000 LOC · 3,400+ test · 324 function · 67 KV scope**, tất cả trên ba primitive. Không có `agentmemory plugin install`. Hệ thống plugin chính là iii. +**247 file source · ~55,000 LOC · 3,400+ test · 324 function · 67 KV scope**, tất cả trên ba primitive. Không có `agentmemory plugin install`. Hệ thống plugin chính là iii. --- @@ -1861,7 +1861,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Content-Type: a ```bash npm run dev # Hot reload npm run build # Production build -npm test # 3,600+ tests +npm test # 3,700+ tests npm run test:integration # API tests (requires running services) ``` diff --git a/READMEs/README.zh-CN.md b/READMEs/README.zh-CN.md index 8a98022c87..c23632edcb 100644 --- a/READMEs/README.zh-CN.md +++ b/READMEs/README.zh-CN.md @@ -71,7 +71,7 @@ 54 个 MCP 工具 12 个自动 hooks 0 个外部数据库 - 3,600+ 项测试通过 + 3,700+ 项测试通过

@@ -1444,7 +1444,7 @@ fi | Prometheus / Grafana | iii OTEL + 健康监控 | | Custom plugin systems | `iii worker add ` | -**242 个源文件 · ~55,000 行代码 · 3,400+ 个测试 · 324 个函数 · 67 个 KV 作用域**,全部基于三种原语。没有 `agentmemory plugin install`。插件系统就是 iii 本身。 +**247 个源文件 · ~55,000 行代码 · 3,400+ 个测试 · 324 个函数 · 67 个 KV 作用域**,全部基于三种原语。没有 `agentmemory plugin install`。插件系统就是 iii 本身。 --- @@ -1868,7 +1868,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Content-Type: a ```bash npm run dev # Hot reload npm run build # Production build -npm test # 3,600+ tests +npm test # 3,700+ tests npm run test:integration # API tests (requires running services) ``` diff --git a/READMEs/README.zh-TW.md b/READMEs/README.zh-TW.md index 4fb78bc4fa..41d14b6653 100644 --- a/READMEs/README.zh-TW.md +++ b/READMEs/README.zh-TW.md @@ -71,7 +71,7 @@ 54 個 MCP 工具 12 個自動 hooks 0 個外部資料庫 - 3,600+ 測試通過 + 3,700+ 測試通過

@@ -1430,7 +1430,7 @@ fi | Prometheus / Grafana | iii OTEL + 健康監控 | | 自訂外掛系統 | `iii worker add ` | -**242 個原始檔 · ~55,000 行程式碼 · 3,400+ 測試 · 324 個函式 · 67 個 KV 範圍**,全部基於三種原語。沒有 `agentmemory plugin install`。外掛系統就是 iii 本身。 +**247 個原始檔 · ~55,000 行程式碼 · 3,400+ 測試 · 324 個函式 · 67 個 KV 範圍**,全部基於三種原語。沒有 `agentmemory plugin install`。外掛系統就是 iii 本身。 --- @@ -1854,7 +1854,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Content-Type: a ```bash npm run dev # Hot reload npm run build # Production build -npm test # 3,600+ tests +npm test # 3,700+ tests npm run test:integration # API tests (requires running services) ``` diff --git a/assets/tags/light/stat-tests.svg b/assets/tags/light/stat-tests.svg index 1a99e20ad3..ff8bd8633b 100644 --- a/assets/tags/light/stat-tests.svg +++ b/assets/tags/light/stat-tests.svg @@ -1,5 +1,5 @@ - + - 3600+ + 3700+ TESTS PASSING diff --git a/assets/tags/stat-tests.svg b/assets/tags/stat-tests.svg index 7ca382fa07..cec9823188 100644 --- a/assets/tags/stat-tests.svg +++ b/assets/tags/stat-tests.svg @@ -1,5 +1,5 @@ - + - 3600+ + 3700+ TESTS PASSING diff --git a/integrations/cursor/README.md b/integrations/cursor/README.md index 4349e3873c..4d82766cbf 100644 --- a/integrations/cursor/README.md +++ b/integrations/cursor/README.md @@ -11,8 +11,8 @@ work. Cursor gets a thin adapter in front of them, compiled from ## Quick local install -Prereq: `AGENTMEMORY_URL` and `AGENTMEMORY_SECRET`, in the environment or in -`~/.agentmemory/.env`. +Prereq: `AGENTMEMORY_URL` (and `AGENTMEMORY_SECRET` when the daemon sets one), +in the environment or in `~/.agentmemory/.env`. ```bash npm run build @@ -30,7 +30,8 @@ Then in Cursor: 4. **Developer: Reload Window** 5. Confirm the hooks log shows `plugin/scripts/cursor/run-hook.mjs` or `run-detached.mjs` -Only after plugin hooks are confirmed: +Only after plugin hooks are confirmed, remove the old agentmemory entries from +`~/.cursor/hooks.json` (other hooks are kept, and a backup is written): ```bash node integrations/cursor/install-local.mjs --clear-user-hooks @@ -170,13 +171,14 @@ later hook in that session is a single JSON read. | # | Layer | Basis | Notes | |---|---|---|---| -| 1 | Session cache | previous answer | `~/.cursor/hooks/.agentmemory-session-cache.json`, written under a lock | +| 1 | Session cache | previous answer | `~/.cursor/hooks/.agentmemory-session-cache.json`, written under a lock; entries expire after 7 days (max 200) and are ignored once their directory is gone | | 2 | Payload paths | `workspace_roots`, `workspace_folder`, `cwd`, … | eight aliases because Cursor is inconsistent; `cwd` is deliberately ranked low | | 3 | `tool_input` paths | any path-shaped string in the tool arguments | file paths resolve to their directory | | 4 | **Cursor's database** | `composer.composerHeaders` | exact, no inference — see below | | 5 | Transcript directory name | `~/.cursor/projects//` | slug is the workspace path with separators flattened | | 6 | Transcript contents | most-mentioned git root | a guess; needs ≥3 votes | -| 7 | Environment | `CURSOR_WORKSPACE_ROOT`, `PWD`, `VSCODE_CWD` | last, because `VSCODE_CWD` lies | +| 7 | Environment | `CURSOR_PROJECT_DIR`, `CURSOR_WORKSPACE_ROOT`, `CURSOR_WORKSPACE_FOLDER` | Cursor's documented hook env var, then explicit overrides | +| 7b | Launch directory | `PWD`, `VSCODE_CWD` | used for this hook only, never cached, because `VSCODE_CWD` lies | | 8 | `unknown-project` | — | the honest answer when nothing else is | Every candidate then passes the same gate: not `.cursor`, not an IDE install diff --git a/integrations/cursor/_env.mjs b/integrations/cursor/_env.mjs index 846b0d0766..b40c1ca327 100644 --- a/integrations/cursor/_env.mjs +++ b/integrations/cursor/_env.mjs @@ -22,7 +22,17 @@ export function parseEnvFile(path = ENV_PATH) { if (!trimmed || trimmed.startsWith('#')) continue; const idx = trimmed.indexOf('='); if (idx === -1) continue; - out[trimmed.slice(0, idx).trim()] = trimmed.slice(idx + 1).trim(); + const key = trimmed.slice(0, idx).trim().replace(/^export\s+/, ''); + let value = trimmed.slice(idx + 1).trim(); + const quote = value[0] === '"' || value[0] === "'" ? value[0] : ''; + if (quote) { + const close = value.indexOf(quote, 1); + if (close !== -1) value = value.slice(1, close); + } else { + const hash = value.indexOf(' #'); + if (hash !== -1) value = value.slice(0, hash).trim(); + } + out[key] = value; } return out; } @@ -38,17 +48,23 @@ export function loadConfig(keys, path = ENV_PATH) { return out; } -/** loadConfig for the two keys every script needs, with a uniform error. */ +/** + * loadConfig for the two keys every script needs. The URL is required; the + * secret may be empty because a local daemon can run keyless. + */ export function requireConnection(path = ENV_PATH) { const { AGENTMEMORY_URL: url, AGENTMEMORY_SECRET: secret } = loadConfig( ['AGENTMEMORY_URL', 'AGENTMEMORY_SECRET'], path ); - if (!url || !secret) { - console.error( - `Missing AGENTMEMORY_URL / AGENTMEMORY_SECRET. Set them in the environment or in ${path}.` - ); + if (!url) { + console.error(`Missing AGENTMEMORY_URL. Set it in the environment or in ${path}.`); process.exit(1); } return { url, secret }; } + +/** Bearer header only when a secret is configured. */ +export function authHeader(secret) { + return secret ? { Authorization: `Bearer ${secret}` } : {}; +} diff --git a/integrations/cursor/close-stale-am-sessions.mjs b/integrations/cursor/close-stale-am-sessions.mjs index bf8fee2fb3..938c3a6b81 100644 --- a/integrations/cursor/close-stale-am-sessions.mjs +++ b/integrations/cursor/close-stale-am-sessions.mjs @@ -8,7 +8,7 @@ * node integrations/cursor/close-stale-am-sessions.mjs --min-age-hours 6 --project my-project * node integrations/cursor/close-stale-am-sessions.mjs --exclude ses_abc123,def456 */ -import { requireConnection } from './_env.mjs'; +import { authHeader, requireConnection } from './_env.mjs'; function parseArgs() { const args = process.argv.slice(2); @@ -44,7 +44,7 @@ async function main() { const { url: restUrl, secret } = requireConnection(); const headers = { - Authorization: `Bearer ${secret}`, + ...authHeader(secret), 'Content-Type': 'application/json' }; diff --git a/integrations/cursor/install-local.mjs b/integrations/cursor/install-local.mjs index 98b70848ec..1e93b7cf79 100644 --- a/integrations/cursor/install-local.mjs +++ b/integrations/cursor/install-local.mjs @@ -102,6 +102,10 @@ function mergeMcp(env) { return backup; } +function isAgentmemoryHook(entry) { + return JSON.stringify(entry ?? '').includes('agentmemory'); +} + function disableUserHooks() { if (!process.argv.includes('--clear-user-hooks')) return null; if (!existsSync(HOOKS_PATH)) return null; @@ -115,19 +119,30 @@ function disableUserHooks() { } requireObjectConfig(HOOKS_PATH, hooks, 'hooks.json root'); requireObjectField(HOOKS_PATH, 'hooks', hooks.hooks); - const hasAgentmemory = JSON.stringify(hooks).includes('agentmemory-'); - if (!hasAgentmemory) return null; + if (!hooks.hooks) return null; + + let removed = 0; + const filtered = {}; + for (const [event, entries] of Object.entries(hooks.hooks)) { + if (!Array.isArray(entries)) { + filtered[event] = entries; + continue; + } + const kept = entries.filter((entry) => !isAgentmemoryHook(entry)); + removed += entries.length - kept.length; + if (kept.length > 0) filtered[event] = kept; + } + if (removed === 0) return null; + const backup = `${HOOKS_PATH}.pre-plugin-${Date.now()}.bak`; copyFileSync(HOOKS_PATH, backup); - writeJson(HOOKS_PATH, { version: 1, hooks: {} }); + writeJson(HOOKS_PATH, { ...hooks, hooks: filtered }); return backup; } const env = loadConfig(['AGENTMEMORY_URL', 'AGENTMEMORY_SECRET', 'AGENTMEMORY_TOOLS']); -if (!env.AGENTMEMORY_URL || !env.AGENTMEMORY_SECRET) { - console.error( - `Missing AGENTMEMORY_URL / AGENTMEMORY_SECRET. Set them in the environment or in ${ENV_PATH}.` - ); +if (!env.AGENTMEMORY_URL) { + console.error(`Missing AGENTMEMORY_URL. Set it in the environment or in ${ENV_PATH}.`); process.exit(1); } @@ -146,7 +161,7 @@ if (existsSync(LEGACY_MARKETPLACE_DIR)) { 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: '); +console.log(`AGENTMEMORY_SECRET: ${env.AGENTMEMORY_SECRET ? '' : ''}`); console.log('\nNext steps:'); console.log('1. Cursor → Settings → Plugins → Add marketplace from folder:'); console.log(` ${REPO_ROOT}`); diff --git a/integrations/cursor/verify-flow.mjs b/integrations/cursor/verify-flow.mjs index ea9ff00f9e..c4c72a18f5 100644 --- a/integrations/cursor/verify-flow.mjs +++ b/integrations/cursor/verify-flow.mjs @@ -15,7 +15,7 @@ import { existsSync } from 'node:fs'; import { dirname, join, resolve } from 'node:path'; import { spawnSync } from 'node:child_process'; import { fileURLToPath } from 'node:url'; -import { requireConnection } from './_env.mjs'; +import { authHeader, requireConnection } from './_env.mjs'; const INTEGRATION_ROOT = resolve(dirname(fileURLToPath(import.meta.url))); const REPO_ROOT = resolve(INTEGRATION_ROOT, '../..'); @@ -25,7 +25,7 @@ const POLL_INTERVAL_MS = 1000; const POLL_TIMEOUT_MS = 90000; const { url, secret } = requireConnection(); -const authHeaders = { Authorization: `Bearer ${secret}` }; +const authHeaders = authHeader(secret); function runHook(script, args, payload) { const r = spawnSync(process.execPath, [join(CURSOR_SCRIPTS, script), ...args], { diff --git a/plugin/scripts/cursor/run-detached.mjs b/plugin/scripts/cursor/run-detached.mjs old mode 100644 new mode 100755 index f15951d47f..b0861e26b3 --- a/plugin/scripts/cursor/run-detached.mjs +++ b/plugin/scripts/cursor/run-detached.mjs @@ -199,6 +199,8 @@ const HOME = homedir(); const CURSOR_PROJECTS_DIR = join(HOME, ".cursor", "projects"); const SESSION_CACHE_PATH = join(HOME, ".cursor", "hooks", ".agentmemory-session-cache.json"); const HOOK_PAYLOAD_DIR = join(HOME, ".cursor", "hooks", ".am-hook-payloads"); +const SESSION_CACHE_MAX_AGE_MS = 10080 * 60 * 1e3; +const SESSION_CACHE_MAX_ENTRIES = 200; function normalizePathSlashes(value) { return String(value).replace(/\\/g, "/"); } @@ -260,15 +262,24 @@ function loadSessionCache() { return {}; } } +function pruneSessionCache(cache, now) { + const fresh = Object.entries(cache).filter(([, entry]) => { + const updated = Date.parse(entry?.updatedAt ?? ""); + return Number.isFinite(updated) && now - updated < SESSION_CACHE_MAX_AGE_MS; + }); + fresh.sort((a, b) => Date.parse(b[1].updatedAt) - Date.parse(a[1].updatedAt)); + return Object.fromEntries(fresh.slice(0, SESSION_CACHE_MAX_ENTRIES)); +} function rememberSession(sessionId, project, cwd) { if (!sessionId || !project || project === ".cursor") return; withSessionCacheLock(() => { try { - const cache = loadSessionCache(); + const now = Date.now(); + const cache = pruneSessionCache(loadSessionCache(), now); cache[sessionId] = { project, cwd, - updatedAt: (/* @__PURE__ */ new Date()).toISOString() + updatedAt: new Date(now).toISOString() }; const tmp = `${SESSION_CACHE_PATH}.${process.pid}.${Date.now()}.tmp`; writeFileSync(tmp, JSON.stringify(cache, null, 2)); @@ -571,7 +582,7 @@ function resolveFromPathCandidates(candidates, sessionId, options = {}) { const project = projectFromPath(existing); if (isHomeDirectory(existing) && !project.fromGitRoot) continue; if (!isMetadataProject(project)) { - rememberSession(sessionId, project.name, existing); + if (options.remember !== false) rememberSession(sessionId, project.name, existing); return { project: project.name, cwd: existing @@ -587,7 +598,7 @@ function debugLayer(layer, result) { function resolveWorkspace(data) { const sessionId = data?.["session_id"] ?? data?.["sessionId"]; const cached = recallSession(sessionId); - if (cached?.cwd && !isBadPath(cached.cwd)) return { + if (cached?.cwd && !isBadPath(cached.cwd) && existingDirectory(cached.cwd)) return { project: cached.project, cwd: cached.cwd }; @@ -611,20 +622,18 @@ function resolveWorkspace(data) { if (fromSession) return fromSession; } const fromEnv = debugLayer("env", resolveFromPathCandidates([ + process.env["CURSOR_PROJECT_DIR"], process.env["CURSOR_WORKSPACE_ROOT"], - process.env["CURSOR_WORKSPACE_FOLDER"], - process.env["PWD"], - process.env["VSCODE_CWD"] + process.env["CURSOR_WORKSPACE_FOLDER"] ], sessionId)); if (fromEnv) return fromEnv; + const fromLaunch = debugLayer("launch-env", resolveFromPathCandidates([process.env["PWD"], process.env["VSCODE_CWD"]], sessionId, { remember: false })); + if (fromLaunch) return fromLaunch; const label = process.env["CURSOR_WORKSPACE_LABEL"]; - if (label) { - rememberSession(sessionId, label, label); - return { - project: label, - cwd: label - }; - } + if (label) return { + project: label, + cwd: label + }; return { project: "unknown-project", cwd: "unknown-project" @@ -658,7 +667,8 @@ function enrichPayload(data) { payload: { ...data, session_id: data["session_id"] ?? data["sessionId"], - cwd + cwd, + project } }; } diff --git a/plugin/scripts/cursor/run-hook.mjs b/plugin/scripts/cursor/run-hook.mjs old mode 100644 new mode 100755 index d28abe0177..955522e397 --- a/plugin/scripts/cursor/run-hook.mjs +++ b/plugin/scripts/cursor/run-hook.mjs @@ -199,6 +199,8 @@ const HOME = homedir(); const CURSOR_PROJECTS_DIR = join(HOME, ".cursor", "projects"); const SESSION_CACHE_PATH = join(HOME, ".cursor", "hooks", ".agentmemory-session-cache.json"); join(HOME, ".cursor", "hooks", ".am-hook-payloads"); +const SESSION_CACHE_MAX_AGE_MS = 10080 * 60 * 1e3; +const SESSION_CACHE_MAX_ENTRIES = 200; function normalizePathSlashes(value) { return String(value).replace(/\\/g, "/"); } @@ -260,15 +262,24 @@ function loadSessionCache() { return {}; } } +function pruneSessionCache(cache, now) { + const fresh = Object.entries(cache).filter(([, entry]) => { + const updated = Date.parse(entry?.updatedAt ?? ""); + return Number.isFinite(updated) && now - updated < SESSION_CACHE_MAX_AGE_MS; + }); + fresh.sort((a, b) => Date.parse(b[1].updatedAt) - Date.parse(a[1].updatedAt)); + return Object.fromEntries(fresh.slice(0, SESSION_CACHE_MAX_ENTRIES)); +} function rememberSession(sessionId, project, cwd) { if (!sessionId || !project || project === ".cursor") return; withSessionCacheLock(() => { try { - const cache = loadSessionCache(); + const now = Date.now(); + const cache = pruneSessionCache(loadSessionCache(), now); cache[sessionId] = { project, cwd, - updatedAt: (/* @__PURE__ */ new Date()).toISOString() + updatedAt: new Date(now).toISOString() }; const tmp = `${SESSION_CACHE_PATH}.${process.pid}.${Date.now()}.tmp`; writeFileSync(tmp, JSON.stringify(cache, null, 2)); @@ -514,7 +525,7 @@ function resolveFromPathCandidates(candidates, sessionId, options = {}) { const project = projectFromPath(existing); if (isHomeDirectory(existing) && !project.fromGitRoot) continue; if (!isMetadataProject(project)) { - rememberSession(sessionId, project.name, existing); + if (options.remember !== false) rememberSession(sessionId, project.name, existing); return { project: project.name, cwd: existing @@ -530,7 +541,7 @@ function debugLayer(layer, result) { function resolveWorkspace(data) { const sessionId = data?.["session_id"] ?? data?.["sessionId"]; const cached = recallSession(sessionId); - if (cached?.cwd && !isBadPath(cached.cwd)) return { + if (cached?.cwd && !isBadPath(cached.cwd) && existingDirectory(cached.cwd)) return { project: cached.project, cwd: cached.cwd }; @@ -554,20 +565,18 @@ function resolveWorkspace(data) { if (fromSession) return fromSession; } const fromEnv = debugLayer("env", resolveFromPathCandidates([ + process.env["CURSOR_PROJECT_DIR"], process.env["CURSOR_WORKSPACE_ROOT"], - process.env["CURSOR_WORKSPACE_FOLDER"], - process.env["PWD"], - process.env["VSCODE_CWD"] + process.env["CURSOR_WORKSPACE_FOLDER"] ], sessionId)); if (fromEnv) return fromEnv; + const fromLaunch = debugLayer("launch-env", resolveFromPathCandidates([process.env["PWD"], process.env["VSCODE_CWD"]], sessionId, { remember: false })); + if (fromLaunch) return fromLaunch; const label = process.env["CURSOR_WORKSPACE_LABEL"]; - if (label) { - rememberSession(sessionId, label, label); - return { - project: label, - cwd: label - }; - } + if (label) return { + project: label, + cwd: label + }; return { project: "unknown-project", cwd: "unknown-project" @@ -601,7 +610,8 @@ function enrichPayload(data) { payload: { ...data, session_id: data["session_id"] ?? data["sessionId"], - cwd + cwd, + project } }; } diff --git a/plugin/skills/agentmemory-agents/REFERENCE.md b/plugin/skills/agentmemory-agents/REFERENCE.md index e184c45b44..67801e4b67 100644 --- a/plugin/skills/agentmemory-agents/REFERENCE.md +++ b/plugin/skills/agentmemory-agents/REFERENCE.md @@ -14,7 +14,7 @@ Generated from `src/cli/connect/index.ts`. Do not edit the block below by hand; | Codex CLI | `codex` | Using MCP. Hooks ship via the Codex plugin; on Codex Desktop, also pass --with-hooks to install the global hooks.json workaround. | | Continue | `continue` | Using MCP via ~/.continue/config.yaml (preferred) or config.json (legacy, only when no yaml). | | GitHub Copilot CLI | `copilot-cli` | Using MCP. Install the plugin too for full hooks/skills coverage. | -| Cursor | `cursor` | Using MCP (the only protocol Cursor speaks). Memory bridge runs at :3111 underneath. | +| Cursor | `cursor` | Using MCP. Lifecycle hooks ship in the Cursor plugin: Settings → Plugins → Add marketplace → this repo, then enable agentmemory. | | Devin CLI | `devin` | Using MCP via the user config. Devin CLI migrates mcpServers into mcp_config.json on newer builds. Pass --with-hooks for native auto-capture. | | Droid (Factory.ai) | `droid` | Using MCP via ~/.factory/mcp.json. The `/mcp` slash command inside droid lists configured servers. Pass --with-hooks to also install the native ~/.factory/hooks.json auto-capture hooks. | | DeepSeek Harness | `dsh` | Using MCP via $DSH_HOME/cordis.patch.yml (the home-level patch layer every profile loads). Tools appear as mcp__agentmemory__*. Pass --with-hooks to also wire auto-capture through Harness's Claude Code hook bridge. | diff --git a/scripts/docs-sync.state.json b/scripts/docs-sync.state.json index 5b38ec02af..49a2b75f0f 100644 --- a/scripts/docs-sync.state.json +++ b/scripts/docs-sync.state.json @@ -20,16 +20,16 @@ "12" ], "tests": [ - "3600+" + "3700+" ], "functions": [ "324" ], "sourceFiles": [ - "242" + "247" ], "loc": [ - "56000" + "58000" ], "kvScopes": [ "67" diff --git a/src/hooks/cursor/delegate.ts b/src/hooks/cursor/delegate.ts index b123d3332a..8fc6c581f6 100644 --- a/src/hooks/cursor/delegate.ts +++ b/src/hooks/cursor/delegate.ts @@ -55,6 +55,7 @@ export function enrichPayload(data: HookPayload): { ...data, session_id: data["session_id"] ?? data["sessionId"], cwd, + project, }, }; } diff --git a/src/hooks/cursor/workspace.ts b/src/hooks/cursor/workspace.ts index a80ea5eb88..da98d2c11a 100644 --- a/src/hooks/cursor/workspace.ts +++ b/src/hooks/cursor/workspace.ts @@ -41,6 +41,9 @@ interface SessionCacheEntry { type SessionCache = Record; +const SESSION_CACHE_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000; +const SESSION_CACHE_MAX_ENTRIES = 200; + export function normalizePathSlashes(value: unknown): string { return String(value).replace(/\\/g, "/"); } @@ -127,12 +130,24 @@ function loadSessionCache(): SessionCache { } } +// Every hook is a fresh process that parses this file, so it is kept small: +// stale sessions are dropped and only the most recent entries survive. +function pruneSessionCache(cache: SessionCache, now: number): SessionCache { + const fresh = Object.entries(cache).filter(([, entry]) => { + const updated = Date.parse(entry?.updatedAt ?? ""); + return Number.isFinite(updated) && now - updated < SESSION_CACHE_MAX_AGE_MS; + }); + fresh.sort((a, b) => Date.parse(b[1].updatedAt) - Date.parse(a[1].updatedAt)); + return Object.fromEntries(fresh.slice(0, SESSION_CACHE_MAX_ENTRIES)); +} + function rememberSession(sessionId: string | undefined, project: string, cwd: string): void { if (!sessionId || !project || project === ".cursor") return; withSessionCacheLock(() => { try { - const cache = loadSessionCache(); - cache[sessionId] = { project, cwd, updatedAt: new Date().toISOString() }; + const now = Date.now(); + const cache = pruneSessionCache(loadSessionCache(), now); + cache[sessionId] = { project, cwd, updatedAt: new Date(now).toISOString() }; const tmp = `${SESSION_CACHE_PATH}.${process.pid}.${Date.now()}.tmp`; writeFileSync(tmp, JSON.stringify(cache, null, 2)); renameSync(tmp, SESSION_CACHE_PATH); @@ -597,7 +612,7 @@ function existingDirectory(pathValue: string): string | null { function resolveFromPathCandidates( candidates: unknown[], sessionId: string | undefined, - options: { exact?: boolean } = {}, + options: { exact?: boolean; remember?: boolean } = {}, ): Workspace | null { for (const candidate of candidates) { if (typeof candidate !== "string" || isBadPath(candidate)) continue; @@ -612,7 +627,7 @@ function resolveFromPathCandidates( // is the dotfiles-checked-out-in-$HOME layout. if (isHomeDirectory(existing) && !project.fromGitRoot) continue; if (!isMetadataProject(project)) { - rememberSession(sessionId, project.name, existing); + if (options.remember !== false) rememberSession(sessionId, project.name, existing); return { project: project.name, cwd: existing }; } } @@ -632,8 +647,10 @@ function debugLayer(layer: string, result: Workspace | null): Workspace | null { export function resolveWorkspace(data: HookData): Workspace { const sessionId = (data?.["session_id"] ?? data?.["sessionId"]) as string | undefined; + // A cached workspace that has since moved or been deleted is stale; fall + // through so the current payload can replace it. const cached = recallSession(sessionId); - if (cached?.cwd && !isBadPath(cached.cwd)) { + if (cached?.cwd && !isBadPath(cached.cwd) && existingDirectory(cached.cwd)) { return { project: cached.project, cwd: cached.cwd }; } @@ -678,22 +695,28 @@ export function resolveWorkspace(data: HookData): Workspace { if (fromSession) return fromSession; } - // Env comes last: VSCODE_CWD in particular is frequently the IDE install - // directory rather than the workspace. - const envCandidates: unknown[] = [ + // Env comes last. CURSOR_PROJECT_DIR is Cursor's documented workspace root + // for hooks; the other two are explicit user overrides. Those are cached. + const authoritativeEnv: unknown[] = [ + process.env["CURSOR_PROJECT_DIR"], process.env["CURSOR_WORKSPACE_ROOT"], process.env["CURSOR_WORKSPACE_FOLDER"], - process.env["PWD"], - process.env["VSCODE_CWD"], ]; - const fromEnv = debugLayer("env", resolveFromPathCandidates(envCandidates, sessionId)); + const fromEnv = debugLayer("env", resolveFromPathCandidates(authoritativeEnv, sessionId)); if (fromEnv) return fromEnv; + // PWD and VSCODE_CWD only describe where the hook process was launched + // (VSCODE_CWD is often the IDE install directory), so they are used for + // this hook but never cached: later hooks with real evidence must win. + const launchEnv: unknown[] = [process.env["PWD"], process.env["VSCODE_CWD"]]; + const fromLaunch = debugLayer( + "launch-env", + resolveFromPathCandidates(launchEnv, sessionId, { remember: false }), + ); + if (fromLaunch) return fromLaunch; + const label = process.env["CURSOR_WORKSPACE_LABEL"]; - if (label) { - rememberSession(sessionId, label, label); - return { project: label, cwd: label }; - } + if (label) return { project: label, cwd: label }; return { project: "unknown-project", cwd: "unknown-project" }; } diff --git a/test/cursor-adapter.test.ts b/test/cursor-adapter.test.ts index 69e7f64501..1d7145ecb6 100644 --- a/test/cursor-adapter.test.ts +++ b/test/cursor-adapter.test.ts @@ -157,12 +157,14 @@ describe("delegateHook", () => { const seen = JSON.parse(chunks.join("")) as { project: string; - payload: { cwd: string; session_id: string }; + payload: { cwd: string; session_id: string; project: string }; }; // resolveProject() in the canonical hooks reads AGENTMEMORY_PROJECT_NAME // before anything else; that is the whole delegation mechanism. expect(seen.project).toBe("my-test-project"); expect(basename(seen.payload.cwd)).toBe("my-test-project"); + // pre-tool-use reads data.project directly to scope /enrich. + expect(seen.payload.project).toBe("my-test-project"); expect(seen.payload.session_id).toBeTruthy(); }); diff --git a/test/cursor-env.test.ts b/test/cursor-env.test.ts new file mode 100644 index 0000000000..94f56c639e --- /dev/null +++ b/test/cursor-env.test.ts @@ -0,0 +1,37 @@ +import { describe, it, expect } from "vitest"; +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +// @ts-expect-error -- plain .mjs integration script without type declarations +import { authHeader, parseEnvFile } from "../integrations/cursor/_env.mjs"; + +describe("cursor integration env file", () => { + it("strips quotes and inline comments like the daemon", () => { + const dir = mkdtempSync(join(tmpdir(), "am-cursor-env-")); + const file = join(dir, ".env"); + writeFileSync( + file, + [ + 'AGENTMEMORY_URL="http://localhost:3111"', + "AGENTMEMORY_SECRET='abc'", + "AGENTMEMORY_TOOLS=all # every tool", + "export EXTRA=1", + ].join("\n"), + ); + try { + expect(parseEnvFile(file)).toEqual({ + AGENTMEMORY_URL: "http://localhost:3111", + AGENTMEMORY_SECRET: "abc", + AGENTMEMORY_TOOLS: "all", + EXTRA: "1", + }); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); + + it("omits the bearer header for a keyless daemon", () => { + expect(authHeader("")).toEqual({}); + expect(authHeader("abc")).toEqual({ Authorization: "Bearer abc" }); + }); +}); diff --git a/test/cursor-workspace.test.ts b/test/cursor-workspace.test.ts index 0216af2b70..cabeea1be6 100644 --- a/test/cursor-workspace.test.ts +++ b/test/cursor-workspace.test.ts @@ -19,6 +19,7 @@ const sessionId = (label: string): string => // payload was rejected have to blank it, or the developer's own shell (PWD) // answers instead and the assertion passes for the wrong reason. const ENV_KEYS = [ + 'CURSOR_PROJECT_DIR', 'CURSOR_WORKSPACE_ROOT', 'CURSOR_WORKSPACE_FOLDER', 'CURSOR_WORKSPACE_LABEL', @@ -180,4 +181,56 @@ describe('cursor workspace resolver', () => { ); expect(resolved.project).not.toBe('cursor'); }); + + it('drops a cached workspace that no longer exists', () => { + const parent = mkdtempSync(join(tmpdir(), 'am-ws-')); + const oldDir = join(parent, 'old-app'); + const newDir = join(parent, 'new-app'); + mkdirSync(oldDir); + mkdirSync(newDir); + const id = sessionId('moved'); + try { + withoutWorkspaceEnv(() => { + expect(resolveWorkspace({ session_id: id, workspace_roots: [oldDir] }).project).toBe('old-app'); + rmSync(oldDir, { recursive: true, force: true }); + expect(resolveWorkspace({ session_id: id, workspace_roots: [newDir] }).project).toBe('new-app'); + }); + } finally { + rmSync(parent, { recursive: true, force: true }); + } + }); + + it('does not cache a workspace inferred from the launch directory', () => { + const parent = mkdtempSync(join(tmpdir(), 'am-ws-')); + const launchDir = join(parent, 'launch-dir'); + const realDir = join(parent, 'real-app'); + mkdirSync(launchDir); + mkdirSync(realDir); + const id = sessionId('pwd'); + try { + withoutWorkspaceEnv(() => { + process.env.PWD = launchDir; + expect(resolveWorkspace({ session_id: id }).project).toBe('launch-dir'); + delete process.env.PWD; + expect(resolveWorkspace({ session_id: id, workspace_roots: [realDir] }).project).toBe( + 'real-app' + ); + }); + } finally { + rmSync(parent, { recursive: true, force: true }); + } + }); + + it("uses Cursor's documented CURSOR_PROJECT_DIR", () => { + const dir = mkdtempSync(join(tmpdir(), 'am-ws-')); + try { + const resolved = withoutWorkspaceEnv(() => { + process.env.CURSOR_PROJECT_DIR = dir; + return resolveWorkspace({ session_id: sessionId('project-dir') }); + }); + expect(resolved.project).toBe(basename(dir)); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); }); From f5f926e29f783a4807698734f9eb44473eb212a8 Mon Sep 17 00:00:00 2001 From: Andrew Wang Date: Sat, 24 Oct 2026 21:15:46 -0400 Subject: [PATCH 17/18] docs(cursor): note read-only state.vscdb access for Marketplace review --- integrations/cursor/README.md | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/integrations/cursor/README.md b/integrations/cursor/README.md index 4d82766cbf..418fe07f67 100644 --- a/integrations/cursor/README.md +++ b/integrations/cursor/README.md @@ -241,6 +241,17 @@ Two caveats, both handled: every path in `cursor-db.ts` returns null and layers 5–6 take over. This layer is an accuracy upgrade, never a requirement. +### Data handling: what layer 4 reads from Cursor's database + +For Cursor Marketplace review: layer 4 opens Cursor's `state.vscdb` +**read-only** — `node:sqlite` with `readOnly: true`, or `better-sqlite3` +with `readonly: true, fileMustExist: true` — and runs a single-key lookup, +`SELECT value FROM ItemTable WHERE key = 'composer.composerHeaders'`, to map +a hook's `session_id` (the composerId) to its workspace path. It never writes +to the database, never reads chat content, and never touches any other key. +The connection is closed after the read, and a locked or half-migrated file +just makes the layer return null so layers 5–6 take over. + ### The slug encoding (layer 5) `~/.cursor/projects/` names one directory per workspace after the workspace From ea5b15045f8646a72b2c46ce7cc48950a61592c1 Mon Sep 17 00:00:00 2001 From: Rohit Ghumare Date: Sun, 25 Oct 2026 14:42:30 +0530 Subject: [PATCH 18/18] fix(cursor): ignore missing tool paths during workspace resolution --- integrations/cursor/README.md | 2 +- plugin/scripts/cursor/run-detached.mjs | 2 +- plugin/scripts/cursor/run-hook.mjs | 2 +- src/hooks/cursor/workspace.ts | 4 +-- test/cursor-workspace.test.ts | 13 ++++++++ test/rest-proxy-credentials.test.ts | 43 ++++++++++++++++++++++++++ 6 files changed, 61 insertions(+), 5 deletions(-) diff --git a/integrations/cursor/README.md b/integrations/cursor/README.md index 762cc8298d..96ad35a7c1 100644 --- a/integrations/cursor/README.md +++ b/integrations/cursor/README.md @@ -176,7 +176,7 @@ other agents. |---|---|---|---| | 1 | Session cache | previous answer | `~/.cursor/hooks/.agentmemory-session-cache.json`, written under a lock; entries expire after 7 days (max 200) and are ignored once their directory is gone | | 2 | Payload paths | `workspace_roots`, `workspace_folder`, `cwd`, … | eight aliases because Cursor is inconsistent; `cwd` is deliberately ranked low | -| 3 | `tool_input` or `toolArgs` paths | any path-shaped string in the tool arguments | file paths resolve to their directory | +| 3 | `tool_input` or `toolArgs` paths | existing paths in the tool arguments | file paths resolve to their directory; missing paths fall through | | 4 | **Cursor's database** | `composer.composerHeaders` | exact, no inference — see below | | 5 | Transcript directory name | `~/.cursor/projects//` | slug is the workspace path with separators flattened | | 6 | Transcript contents | most-mentioned git root | a guess; needs ≥3 votes | diff --git a/plugin/scripts/cursor/run-detached.mjs b/plugin/scripts/cursor/run-detached.mjs index 3e0d672b62..25515f55e7 100755 --- a/plugin/scripts/cursor/run-detached.mjs +++ b/plugin/scripts/cursor/run-detached.mjs @@ -648,7 +648,7 @@ function resolveWorkspace(data) { data?.["project_path"] ], sessionId)); if (fromPayload) return fromPayload; - const fromTools = debugLayer("tool_input", resolveFromPathCandidates(collectPathStrings(data?.["tool_input"] ?? data?.["toolArgs"]).map(existingAncestor).filter((p) => Boolean(p) && !isIdeInstallPath(p)), sessionId)); + const fromTools = debugLayer("tool_input", resolveFromPathCandidates(collectPathStrings(data?.["tool_input"] ?? data?.["toolArgs"]).map(existingDirectory).filter((p) => Boolean(p) && !isIdeInstallPath(p)), sessionId)); if (fromTools) return fromTools; if (sessionId) { const fromDb = debugLayer("cursor-db", resolveFromPathCandidates([workspaceFromCursorDb(sessionId)], sessionId, { exact: true })); diff --git a/plugin/scripts/cursor/run-hook.mjs b/plugin/scripts/cursor/run-hook.mjs index 009f12f222..cad1c0492b 100755 --- a/plugin/scripts/cursor/run-hook.mjs +++ b/plugin/scripts/cursor/run-hook.mjs @@ -590,7 +590,7 @@ function resolveWorkspace(data) { data?.["project_path"] ], sessionId)); if (fromPayload) return fromPayload; - const fromTools = debugLayer("tool_input", resolveFromPathCandidates(collectPathStrings(data?.["tool_input"] ?? data?.["toolArgs"]).map(existingAncestor).filter((p) => Boolean(p) && !isIdeInstallPath(p)), sessionId)); + const fromTools = debugLayer("tool_input", resolveFromPathCandidates(collectPathStrings(data?.["tool_input"] ?? data?.["toolArgs"]).map(existingDirectory).filter((p) => Boolean(p) && !isIdeInstallPath(p)), sessionId)); if (fromTools) return fromTools; if (sessionId) { const fromDb = debugLayer("cursor-db", resolveFromPathCandidates([workspaceFromCursorDb(sessionId)], sessionId, { exact: true })); diff --git a/src/hooks/cursor/workspace.ts b/src/hooks/cursor/workspace.ts index 36bf72b7c9..29a2c38dcc 100644 --- a/src/hooks/cursor/workspace.ts +++ b/src/hooks/cursor/workspace.ts @@ -204,7 +204,7 @@ function isCollectablePath(value: unknown): value is string { if (/^[a-zA-Z]:[\\/]/.test(value)) return true; // POSIX-absolute outside $HOME: containers (Codespaces, devcontainers) // check repos out at /workspaces/..., which a HOME-only rule silently - // rejects. existingAncestor() and the git lookup downstream validate it. + // rejects. existingDirectory() and the git lookup downstream validate it. if (value.startsWith("/")) return !isSystemPath(value); return false; } @@ -654,7 +654,7 @@ export function resolveWorkspace(data: HookData): Workspace { if (fromPayload) return fromPayload; const toolPaths = collectPathStrings(data?.["tool_input"] ?? data?.["toolArgs"]) - .map(existingAncestor) + .map(existingDirectory) .filter((p): p is string => Boolean(p) && !isIdeInstallPath(p)); const fromTools = debugLayer("tool_input", resolveFromPathCandidates(toolPaths, sessionId)); if (fromTools) return fromTools; diff --git a/test/cursor-workspace.test.ts b/test/cursor-workspace.test.ts index b2df1461a6..87b4384c95 100644 --- a/test/cursor-workspace.test.ts +++ b/test/cursor-workspace.test.ts @@ -275,6 +275,19 @@ describe('cursor workspace cache and aliases', () => { expect(resolveWorkspace({ conversation_id: 'conversation', toolArgs: { path: join(workspace, 'file.ts') } }).project).toBe('project'); expect(resolveWorkspace({ conversation_id: 'conversation' }).cwd).toBe(workspace); }); + it.each(['temporary', 'home'])('does not cache a generic ancestor of a missing %s tool path', async location => { + const root = location === 'temporary' ? tmpdir() : home; + const missing = join(root, `am-missing-${Date.now()}`, 'result.json'); + const workspace = join(home, 'actual-project'); + mkdirSync(workspace); + const { resolveWorkspace } = await import('../src/hooks/cursor/workspace.js'); + + expect(resolveWorkspace({ session_id: 'missing-tool', tool_input: { path: missing } }).project).toBe('unknown-project'); + expect(resolveWorkspace({ session_id: 'missing-tool', workspace_roots: [workspace] }).project).toBe('actual-project'); + + vi.stubEnv('CURSOR_PROJECT_DIR', workspace); + expect(resolveWorkspace({ session_id: 'tool-with-env', toolArgs: { path: missing } }).project).toBe('actual-project'); + }); it('keeps shared project naming and explicit overrides across linked worktrees', async () => { const repo = join(home, 'main-repo'); const worktree = join(home, 'other-checkout'); mkdirSync(repo); execFileSync('git', ['init', '-q'], { cwd: repo }); diff --git a/test/rest-proxy-credentials.test.ts b/test/rest-proxy-credentials.test.ts index b382a71190..7761e12d75 100644 --- a/test/rest-proxy-credentials.test.ts +++ b/test/rest-proxy-credentials.test.ts @@ -2,6 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; +import { createServer, type Server } from "node:http"; import { resetHandleForTests, resolveHandle, setLivezProbe } from "../src/mcp/rest-proxy.js"; describe("MCP proxy credential origins", () => { @@ -115,6 +116,48 @@ describe("MCP proxy credential origins", () => { expect(redirects).toEqual(["error", "error"]); }); + it.each(["probe", "write"])("does not send local credentials or data to a redirected %s destination", async (phase) => { + const redirected: string[] = []; + const authorization: Array = []; + const destination = createServer((req, res) => { + redirected.push(req.url ?? ""); + res.end("{}"); + }); + const listen = async (server: Server) => { + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const address = server.address(); + if (!address || typeof address === "string") throw new Error("missing server address"); + return `http://127.0.0.1:${address.port}`; + }; + const destinationUrl = await listen(destination); + const origin = createServer((req, res) => { + authorization.push(req.headers.authorization); + if (phase === "write" && req.url === "/agentmemory/livez") res.end("{}"); + else { + res.writeHead(307, { location: `${destinationUrl}/redirected` }); + res.end(); + } + }); + try { + vi.stubEnv("AGENTMEMORY_URL", await listen(origin)); + vi.stubEnv("AGENTMEMORY_SECRET", "synthetic-local-secret"); + const handle = await resolveHandle(); + if (phase === "probe") expect(handle.mode).toBe("local"); + else { + if (handle.mode !== "proxy") throw new Error("expected proxy mode"); + await expect(handle.call("/agentmemory/remember", { + method: "POST", body: '{"content":"synthetic"}', redirect: "follow", + })).rejects.toThrow(); + } + expect(authorization).toEqual(Array(phase === "probe" ? 1 : 2).fill("Bearer synthetic-local-secret")); + expect(redirected).toEqual([]); + } finally { + origin.closeAllConnections(); + destination.closeAllConnections(); + await Promise.all([origin, destination].map(server => new Promise(resolve => server.close(() => resolve())))); + } + }); + it.each([ "file:///synthetic-url-secret", "https://user:synthetic-url-secret@example.invalid", "https://example.invalid/?token=synthetic-url-secret", "https://example.invalid/#synthetic-url-secret",