Fix opencode session project path tracking in agentmemory capture plugin#999
Fix opencode session project path tracking in agentmemory capture plugin#999LyricsYo wants to merge 2 commits into
Conversation
|
Someone is attempting to deploy a commit to the rohitg00's projects Team on Vercel. A member of the Team first needs to authorize it. |
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthroughAdds per-session project and cwd tracking in the OpenCode plugin. Session events, shell environment updates, observe requests, and context injection now use session-specific values instead of a single global project path. ChangesPer-session project tracking
Estimated code review effort: 2 (Simple) | ~15 minutes Possibly related issues
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 3
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
plugin/opencode/agentmemory-capture.ts (2)
638-644: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
/contextcalls still use the stale globalprojectPath, bypassing per-session tracking.
chat.system.transformandexperimental.session.compactingboth callpostJson("/context", { sessionId: sid, project: projectPath }), not the per-session value fromsessionProjects. Sinceobserve()and/session/startwere updated to usesessionProjects.get(sid) || projectPath(Line 50), these two remaining call sites can still fetch context for the wrong project when multiple sessions from different projects are active in the same plugin instance — the exact class of bug this PR targets.🐛 Proposed fix
- const result = await postJson("/context", { - sessionId: sid, - project: projectPath, - }); + const result = await postJson("/context", { + sessionId: sid, + project: sessionProjects.get(sid) || projectPath, + });Apply the same change at Line 680.
Also applies to: 678-681
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@plugin/opencode/agentmemory-capture.ts` around lines 638 - 644, The remaining /context calls in chat.system.transform and experimental.session.compacting still pass the global projectPath instead of the per-session project. Update those postJson("/context", { sessionId: sid, project: ... }) calls to use the same session-scoped lookup already used in observe() and /session/start, namely sessionProjects.get(sid) || projectPath, so each sid resolves context against the correct project.
94-104: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
sessionProjectsneeds cleanup onsession.deleted
pruneSessionMaps()is defined but never called in this file, and the deletion handler only clears the other session maps. AddsessionProjects.delete(sid)there, or callpruneSessionMaps(sid)and remove the duplicated deletes, so dead sessions don't keep accumulating state.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@plugin/opencode/agentmemory-capture.ts` around lines 94 - 104, The session cleanup path is leaving stale entries behind in sessionProjects. Update the session.deleted handling to either call pruneSessionMaps(sid) or explicitly add sessionProjects.delete(sid) alongside the other map clears, and remove any duplicated deletions if you switch to the helper. Use the existing pruneSessionMaps and updateSessionProject symbols in agentmemory-capture.ts to keep dead sessions from retaining state.
🧹 Nitpick comments (1)
plugin/opencode/agentmemory-capture.ts (1)
193-259: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winDuplicated AGENTMEMORY_PROJECT/session-project update logic across three call sites.
The
AGENTMEMORY_PROJECT || <derived value>pattern is repeated at session.created, session.updated, and assistant message.updated instead of routing through a shared helper. Consider extendingupdateSessionProject()(once it also honorsAGENTMEMORY_PROJECT, per the prior comment) and calling it from all these sites to keep the precedence rule in one place.Also applies to: 320-323
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@plugin/opencode/agentmemory-capture.ts` around lines 193 - 259, The session project selection logic is duplicated across session.created, session.updated, and assistant message.updated. Move the AGENTMEMORY_PROJECT-or-derived-path precedence into the shared updateSessionProject() helper and call that helper from each of these event handlers so the rule lives in one place and stays consistent.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@plugin/opencode/agentmemory-capture.ts`:
- Around line 208-212: The session title fallback in the agent memory capture
flow is using a raw filesystem path, which can expose local details in the
dashboard. Update the title assignment in agentmemory-capture’s session payload
so it does not default to sessionProject; instead, keep a human-readable
placeholder or null when info?.title is absent, while leaving the rest of the
captured fields unchanged.
- Around line 101-105: updateSessionProject() is bypassing the
AGENTMEMORY_PROJECT override and can overwrite the chosen project with
shell.cwd. Update updateSessionProject() in agentmemory-capture.ts to resolve
the project path the same way session.created, session.updated, and
message.updated do: prefer process.env.AGENTMEMORY_PROJECT when present,
otherwise fall back to cwd. Keep the existing guards and sessionProjects.set
logic, and make sure the shell.env handler path uses this consistent precedence.
- Around line 180-181: The fallback chain in agentmemory-capture.ts is broken
because currentDirectory always resolves to a truthy value, making
ctx.project?.id and ctx.worktree unreachable in the projectPath assignment.
Update the precedence logic in the agentmemory capture flow so the order is
truly directory → project id → worktree → cwd, and avoid pre-falling back
currentDirectory to process.cwd() before the full chain is evaluated.
---
Outside diff comments:
In `@plugin/opencode/agentmemory-capture.ts`:
- Around line 638-644: The remaining /context calls in chat.system.transform and
experimental.session.compacting still pass the global projectPath instead of the
per-session project. Update those postJson("/context", { sessionId: sid,
project: ... }) calls to use the same session-scoped lookup already used in
observe() and /session/start, namely sessionProjects.get(sid) || projectPath, so
each sid resolves context against the correct project.
- Around line 94-104: The session cleanup path is leaving stale entries behind
in sessionProjects. Update the session.deleted handling to either call
pruneSessionMaps(sid) or explicitly add sessionProjects.delete(sid) alongside
the other map clears, and remove any duplicated deletions if you switch to the
helper. Use the existing pruneSessionMaps and updateSessionProject symbols in
agentmemory-capture.ts to keep dead sessions from retaining state.
---
Nitpick comments:
In `@plugin/opencode/agentmemory-capture.ts`:
- Around line 193-259: The session project selection logic is duplicated across
session.created, session.updated, and assistant message.updated. Move the
AGENTMEMORY_PROJECT-or-derived-path precedence into the shared
updateSessionProject() helper and call that helper from each of these event
handlers so the rule lives in one place and stays consistent.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: e31d0610-7a26-41a0-b452-c6a6b2af3bd5
📒 Files selected for processing (1)
plugin/opencode/agentmemory-capture.ts
| async function updateSessionProject(sessionId: string, cwd: unknown): Promise<void> { | ||
| if (typeof cwd !== "string" || cwd.length === 0) return; | ||
| if (sessionProjects.get(sessionId) === cwd) return; | ||
| sessionProjects.set(sessionId, cwd); | ||
| } |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
updateSessionProject() ignores AGENTMEMORY_PROJECT, unlike every other update site.
session.created (193-197), session.updated (257-259), and assistant message.updated (320-323) all prefer process.env.AGENTMEMORY_PROJECT before the discovered path. updateSessionProject() — the only function invoked by the new shell.env handler (Lines 604-608) — writes cwd unconditionally, so a shell command's directory can silently clobber a user's explicit AGENTMEMORY_PROJECT override. This reintroduces the "wrong project directory picked up" failure mode this PR is fixing.
🐛 Proposed fix
async function updateSessionProject(sessionId: string, cwd: unknown): Promise<void> {
if (typeof cwd !== "string" || cwd.length === 0) return;
- if (sessionProjects.get(sessionId) === cwd) return;
- sessionProjects.set(sessionId, cwd);
+ const resolved = process.env.AGENTMEMORY_PROJECT || cwd;
+ if (sessionProjects.get(sessionId) === resolved) return;
+ sessionProjects.set(sessionId, resolved);
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| async function updateSessionProject(sessionId: string, cwd: unknown): Promise<void> { | |
| if (typeof cwd !== "string" || cwd.length === 0) return; | |
| if (sessionProjects.get(sessionId) === cwd) return; | |
| sessionProjects.set(sessionId, cwd); | |
| } | |
| async function updateSessionProject(sessionId: string, cwd: unknown): Promise<void> { | |
| if (typeof cwd !== "string" || cwd.length === 0) return; | |
| const resolved = process.env.AGENTMEMORY_PROJECT || cwd; | |
| if (sessionProjects.get(sessionId) === resolved) return; | |
| sessionProjects.set(sessionId, resolved); | |
| } |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@plugin/opencode/agentmemory-capture.ts` around lines 101 - 105,
updateSessionProject() is bypassing the AGENTMEMORY_PROJECT override and can
overwrite the chosen project with shell.cwd. Update updateSessionProject() in
agentmemory-capture.ts to resolve the project path the same way session.created,
session.updated, and message.updated do: prefer process.env.AGENTMEMORY_PROJECT
when present, otherwise fall back to cwd. Keep the existing guards and
sessionProjects.set logic, and make sure the shell.env handler path uses this
consistent precedence.
| const currentDirectory = (ctx as any).directory || process.cwd(); | ||
| projectPath = process.env.AGENTMEMORY_PROJECT || currentDirectory || ctx.project?.id || ctx.worktree || process.cwd(); |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Broken fallback precedence — ctx.project?.id/ctx.worktree become unreachable dead code.
currentDirectory already falls back to process.cwd() when ctx.directory is absent, so it's always truthy. That means in line 181, ctx.project?.id || ctx.worktree can never be evaluated — the intended precedence order (directory → project id → worktree → cwd) is silently broken.
🐛 Proposed fix
- const currentDirectory = (ctx as any).directory || process.cwd();
- projectPath = process.env.AGENTMEMORY_PROJECT || currentDirectory || ctx.project?.id || ctx.worktree || process.cwd();
+ projectPath = process.env.AGENTMEMORY_PROJECT || (ctx as any).directory || ctx.project?.id || ctx.worktree || process.cwd();📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| const currentDirectory = (ctx as any).directory || process.cwd(); | |
| projectPath = process.env.AGENTMEMORY_PROJECT || currentDirectory || ctx.project?.id || ctx.worktree || process.cwd(); | |
| projectPath = process.env.AGENTMEMORY_PROJECT || (ctx as any).directory || ctx.project?.id || ctx.worktree || process.cwd(); |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@plugin/opencode/agentmemory-capture.ts` around lines 180 - 181, The fallback
chain in agentmemory-capture.ts is broken because currentDirectory always
resolves to a truthy value, making ctx.project?.id and ctx.worktree unreachable
in the projectPath assignment. Update the precedence logic in the agentmemory
capture flow so the order is truly directory → project id → worktree → cwd, and
avoid pre-falling back currentDirectory to process.cwd() before the full chain
is evaluated.
| title: info?.title ?? sessionProject, | ||
| parentID: info?.parentID ?? null, | ||
| version: info?.version ?? null, | ||
| project: projectPath, | ||
| cwd: projectPath, | ||
| project: sessionProject, | ||
| cwd: sessionProject, |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Session title now defaults to a raw filesystem path.
title: info?.title ?? sessionProject means, absent a real title, the dashboard will display an absolute local path (potentially containing a username, e.g. /Users/jdoe/...) as the session title instead of a human-readable placeholder or null.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@plugin/opencode/agentmemory-capture.ts` around lines 208 - 212, The session
title fallback in the agent memory capture flow is using a raw filesystem path,
which can expose local details in the dashboard. Update the title assignment in
agentmemory-capture’s session payload so it does not default to sessionProject;
instead, keep a human-readable placeholder or null when info?.title is absent,
while leaving the rest of the captured fields unchanged.
Problem agentmemory-capture.ts currently uses the plugin-level path:
as the project/cwd for all sessions.
In opencode desktop/server setups, that value can point to the server/worktree path instead of the actual active session directory. After switching projects, new sessions can be incorrectly assigned to the previous project scope, causing the dashboard to show the wrong session path.
Key Fix Track project paths per session:
Update observe() to prefer the current session’s project path instead of the global plugin path:
On session.created, read the real session directory from opencode session metadata:
Use that value when starting the agentmemory session:
Also keep the session project path in sync from session.updated, assistant message path.cwd, and shell.env to avoid path drift during the session.
Summary by CodeRabbit
New Features
/observe, session start details, and system context injection.Bug Fixes