Skip to content

fix(plugin): per-session project detection from session.created directory#749

Open
Acharnite wants to merge 2 commits into
rohitg00:mainfrom
Acharnite:fix/per-session-project-detection
Open

fix(plugin): per-session project detection from session.created directory#749
Acharnite wants to merge 2 commits into
rohitg00:mainfrom
Acharnite:fix/per-session-project-detection

Conversation

@Acharnite
Copy link
Copy Markdown

@Acharnite Acharnite commented May 31, 2026

Problem

When OpenCode runs as a web service from a workspace root directory (e.g., /home/user/projects/) serving multiple sub-projects, the agentmemory-capture plugin's projectPath is initialized once at plugin load time. Every session receives the same project string — the workspace root — regardless of which sub-project the user is actually working in.

This causes memory cross-contamination: sessions in project-a and project-b both get tagged with project: "/home/user/projects/", making project-scoped queries (mem::search with project filter) useless and mixing memories across unrelated projects.

Solution

Two changes to plugin/opencode/agentmemory-capture.ts:

1. Better plugin-init project detection (line 171)

The OpenCode plugin context already has ctx.project?.worktree (full filesystem path) and ctx.directory — use them before falling back to process.cwd():

-  projectPath = ctx.worktree || ctx.project?.id || process.cwd();
+  projectPath = ctx.worktree || ctx.project?.worktree || ctx.directory || process.cwd();

ctx.project?.id returns a short name (e.g., my-app) while ctx.project?.worktree returns the full path (e.g., /home/user/projects/my-app). Full paths are unique, short names are not.

2. Per-session project from session.created event (line 191, 197-198)

The OpenCode bus publishes session.created events that include a directory field with the specific project path. Extract it per-session instead of using the global init-time value:

+        const sessionProject = (info?.directory as string) || projectPath;
         const startResult = await postJson("/session/start", {
           sessionId,
           title: info?.title ?? null,
           parentID: info?.parentID ?? null,
           version: info?.version ?? null,
-          project: projectPath,
-          cwd: projectPath,
+          project: sessionProject,
+          cwd: sessionProject,

This is a 3-line change (1 new, 2 modified) with a clean fallback: if info?.directory is not available (e.g., CLI mode), it uses the init-time projectPath.

Testing

Verified on OpenCode 1.15.12 running as a systemd web service with WorkingDirectory=/home/kiffer/projects/ and multiple sub-projects. Before the fix, agentmemory-error.log showed all sessions with project: "/home/kiffer/projects". After the fix, sessions are correctly tagged with their specific project directory (e.g., project: "/home/kiffer/projects/kodehold").

Related issues

Summary by CodeRabbit

  • Bug Fixes
    • Improved project path resolution and session initialization. Sessions now derive project and working-directory context from the workspace directory with enhanced fallbacks, ensuring accurate project tracking and correct working-directory context during agent operations and memory capture.

…tory

Two changes:

1. Use ctx.project?.worktree (full path) instead of ctx.project?.id (short name)
   as the plugin-init project detection fallback.

2. Resolve project per-session from session.created event's info?.directory
   field, falling back to the init-time projectPath. This ensures that when
   OpenCode runs from a workspace root (e.g. /home/user/projects/) serving
   multiple sub-projects, each session is correctly tagged with its own
   project directory (e.g. /home/user/projects/my-app) instead of the
   shared workspace root.
@vercel
Copy link
Copy Markdown

vercel Bot commented May 31, 2026

@Acharnite is attempting to deploy a commit to the rohitg00's projects Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 31, 2026

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 7957e47a-0dd1-4245-9e20-da9827d5794c

📥 Commits

Reviewing files that changed from the base of the PR and between ca4dbdb and 58d1abe.

📒 Files selected for processing (1)
  • plugin/opencode/agentmemory-capture.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • plugin/opencode/agentmemory-capture.ts

📝 Walkthrough

Walkthrough

The plugin changes projectPath sourcing to use the project's worktree at init, and session.created now computes a per-session project path from the session directory (falling back to the init-time projectPath) used for both project and cwd in the /session/start request.

Changes

Project path sourcing and session initialization

Layer / File(s) Summary
Project path derivation from worktree
plugin/opencode/agentmemory-capture.ts
projectPath assignment switches from ctx.project?.id to ctx.project?.worktree as the primary source, with fallbacks to ctx.worktree, ctx.directory, and process.cwd().
Session startup with per-session project paths
plugin/opencode/agentmemory-capture.ts
The session.created handler computes a per-session sessionProject from info.directory or the global projectPath, and uses it for both project and cwd fields in the /session/start POST payload instead of always using projectPath.
JSON POST helper doc comment
plugin/opencode/agentmemory-capture.ts
Adds a header doc comment describing the JSON POST helper's POST/parse behavior and null-on-failure semantics.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

Poem

A rabbit hops through paths anew,
From ID to worktree's truer view,
Sessions start on local ground,
Project and cwd now tightly bound,
Tiny notes and changes too. 🐇

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main fix: implementing per-session project detection from the session.created directory event, which is the core change addressing cross-project memory contamination.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 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`:
- Line 191: The assignment to sessionProject uses a type assertion
(info?.directory as string) without runtime checks, so if info?.directory is
non-string or empty the backend will reject /session/start; replace this with
explicit validation: check if info?.directory is a non-empty string before using
it and otherwise fall back to projectPath or throw/return a clear error; update
the logic around sessionProject (where sessionProject is set) to validate typeof
info?.directory === "string" && info.directory.trim().length > 0 and only then
use it, otherwise use projectPath or raise a descriptive error to fail fast.
🪄 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: 0de8058a-1c91-445e-8c7d-71d710b3eae2

📥 Commits

Reviewing files that changed from the base of the PR and between fd9e3bd and ca4dbdb.

📒 Files selected for processing (1)
  • plugin/opencode/agentmemory-capture.ts

Comment thread plugin/opencode/agentmemory-capture.ts Outdated
CodeRabbitAI review feedback:
- Replace (info?.directory as string) type assertion with proper
  runtime typeof + length validation to avoid 400 errors from backend
- Add JSDoc comments to AgentmemoryCapturePlugin and postJson
- Add inline comment explaining validation logic

Refs: PR rohitg00#749 CodeRabbitAI review
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant