opencode-codegraph
v0.1.37
Published
OpenCode plugin for CodeGraph CPG-powered code analysis
Maintainers
Readme
opencode-codegraph
OpenCode plugin for CodeGraph CPG-powered code analysis.
Automatically enriches AI conversations with Code Property Graph data -- security findings, call graphs, complexity metrics, and taint analysis -- without manual tool invocation.
The plugin now also exposes an explicit CodeGraph/OpenViking context session for agent-native memory operations: open session, inspect metadata, fetch context, read/browse specific viking:// resources, persist used-context, share a session read-only, hand off ownership, explicitly close or archive a session, and trigger background commit.
These low-level tools remain available as the stable contract while higher-level scenario wrappers are introduced in later phases.
Install
// opencode.json
{
"plugin": ["opencode-codegraph"]
}Prerequisites
- CodeGraph installed with CPG database built
- CodeGraph API running (
uvicorn src.api.main:app --port 8000) - CodeGraph MCP server configured in
opencode.json
Features
Auto-Enrichment
When you mention a file in chat, the plugin adds CPG context automatically:
You: "Refactor src/api/routers/webhook.py"
Plugin injects:
### CPG context: src/api/routers/webhook.py
**12 methods** in file:
- `receive_github_webhook` CC=5 fan_in=0 fan_out=3 [entry]
- `_handle_push` CC=2 fan_in=4 fan_out=2
**2 security findings:**
- CWE-89 L42: SQL injection in query parameterIf the message also suggests an edit intent (refactor, fix, modify, update, etc.), the plugin appends a pre-edit warning block with complexity, fan-out, dead-code, and security hints for the referenced file.
If the message suggests workflow guidance intent (what next, am I done, can I push, etc.), the plugin appends the current dogfooding status summary so the session can answer with the right next command immediately.
System Prompt
Every conversation includes:
- a project summary with file count, top complexity hotspots, and open security findings;
- a lightweight dogfooding status block when available, including freshness, current
HEAD, git branch/worktree cleanliness, review-trace state, and recommended next action. - the same status block now also includes branch and worktree cleanliness, which lets guided commands distinguish
changes_pending_reviewfromready_to_push. - a recommended command (
/status,/update, or/review) when the workflow can point to a deterministic next step. - a normalized workflow state so the session can distinguish
refresh_needed,trace_pending,review_required, andready_to_continue. - a
ready_to_pushstate when the session is fresh, the review trace is green, and the worktree is clean. - database availability is reported as read-only session status; manual maintenance and unlock controls are intentionally not exposed through the plugin.
Post-Commit Updates
After git commit, the plugin triggers incremental CPG re-parsing via GoCPG and syncs the default OpenViking context plane. When the legacy Chroma profile is enabled, the same post-commit flow also keeps that fallback store current. If durable review-trace artifacts exist for the new HEAD, the plugin also appends a structured post-commit block plus the current workflow guidance with:
- what changed in the review trace
- why it matters
- top recommendations
- one clear next action
- one suggested command to run next
- one normalized workflow state
If the durable review trace is not available yet, the plugin still appends a pending summary telling the developer to check /status instead of leaving the post-commit state ambiguous.
This means the post-commit UX now has two explicit states:
- trace ready -> structured summary with findings, recommendations, and next action
- trace pending/missing -> structured pending summary with deterministic follow-up
Explicit Agent Context
For OpenViking-backed agent memory flows, the plugin exposes explicit tools instead of relying only on prompt injection. The normal pattern is:
codegraph_context_open_sessioncodegraph_context_fetchcodegraph_context_readorcodegraph_context_browsecodegraph_context_record_used_contextcodegraph_context_commitcodegraph_context_status
codegraph_context_commit starts a background commit on the CodeGraph side. The corresponding commit status can be checked later without blocking the main coding workflow.
Recommended OpenViking Flows
For onboarding, investigation, review, and commit packaging, the preferred patterns are:
- Onboarding:
codegraph_context_sync_statuscodegraph_context_open_sessioncodegraph_skill_listwithcategory="onboarding"codegraph_context_fetchcodegraph_context_browseorcodegraph_context_read
- Investigation:
- use
codegraph_fused_searchwhen the task references files, symbols, callers/callees, impact, or refactoring scope - use
codegraph_context_fetchfor broader semantic recall - use
codegraph_context_browsefor namespace exploration - use
codegraph_context_readonly for the selectedviking://artifacts
- use
- Review and follow-up:
codegraph_context_open_sessioncodegraph_skill_listwithcategory="review"codegraph_fused_searchfor the risky changed files or symbolscodegraph_review- keep follow-up questions on the same session instead of opening a fresh evidence chain
- Post-task commit:
- persist the actual used resources with
codegraph_context_record_used_context - trigger
codegraph_context_commit - check
codegraph_context_statuslater without blocking the main coding loop
- persist the actual used resources with
The plugin now reuses the remembered explicit session across follow-up investigation, review, git, and test actions when possible, and it suppresses duplicate background commit requests when the used-context set has not changed.
Phase 3 also persists a lightweight local runtime snapshot under .opencode/state/ so the plugin can recover one explicit session after compaction or restart. /continue now prefers reconnecting that remembered session first, and if the local resume state is missing, the plugin emits explicit manual recovery instructions instead of failing silently.
Phase 2 of the collaboration layer adds explicit multi-user semantics on top of the same session contract:
read-only sharekeeps one evidence chain available to another developer, reviewer, or tester without silently changing ownership.ownership transfermakes handoff explicit and auditable. The nominated target accepts or rejects the handoff instead of relying on opaque session-ID reuse./continueand/statusnow surface lifecycle state, owner, and current access mode when that metadata is available.
Runtime write rules are now explicit:
read_onlyparticipants can inspect and reopen the same evidence chain, but they cannot append messages, mutate used-context, or trigger commit.- active mutation remains with the owner or a future contributor-class access mode.
- once a session is
closedorarchived, it is no longer valid for active context operations.
Recovery limitations: the local snapshot preserves session linkage, workflow state, pending review commit, and recently used context items, but it does not replace the underlying OpenViking session history or reconstruct arbitrary prior chat text on its own.
If OpenViking context is not ready, the plugin can still fall back to bounded graph-first discovery flows.
Context Modes
The plugin now distinguishes three user-visible context states:
full context mode-> OpenViking context is synced and session-aware retrieval is the preferred path.sync-pending mode-> OpenViking is configured but not ready yet, so onboarding and investigation stay bounded until sync completes.graph-only fallback-> OpenViking is unavailable or degraded, so the plugin keeps the workflow on CodeGraph graph/review/status guidance without pretending semantic context is ready.
This mode is surfaced in scenario wrappers such as /onboard, /review, /continue, and /next, so the user sees whether the plugin is in OpenViking-native mode or bounded fallback mode.
The primary readiness signal is now a CodeGraph-owned versioned contract returned by codegraph_context_sync_status / /api/v1/agent/context-sync-status, not an implicit mix of backend fields. The plugin reads contract_version and readiness_mode first and only falls back to legacy heuristics for compatibility.
OpenViking-backed knowledge is also lifecycle-governed. Default skill guidance and retrieval stay in current_only mode, needs_review content appears only through explicit opt-in, and deprecated content is excluded from default guidance. When non-current content is intentionally included, the plugin and agent-facing payloads surface warning text instead of silently treating it as trusted context.
Phase 5 extends the same scenario model to /explain, /status, and /update:
/explainis now expected to reuse one explicit investigation session before widening scope./statusshould report workflow plus explicit context follow-up state when a session is already linked./updateshould preserve that session continuity so post-refresh review or investigation does not restart from zero.
CodeGraph Skill Hint
Scenario wrappers now emit one bounded skill hint when it materially helps:
- onboarding -> onboarding skill
- review and resume -> review skill
- investigation/debug/file editing -> analysis skill
The hint is advisory and bounded to one curated skill. Low-level tools remain available even when no skill hint is shown.
Custom Tools
| Tool | Description |
|------|-------------|
| codegraph_context_open_session | Open or reconnect explicit CodeGraph/OpenViking context session |
| codegraph_context_list_sessions | List authoritative explicit context sessions visible to the current user |
| codegraph_context_session_metadata | Read authoritative lifecycle metadata for one explicit context session |
| codegraph_context_share_session | Share a session read-only or nominate a handoff target explicitly |
| codegraph_context_accept_handoff | Accept explicit ownership transfer for a shared evidence chain |
| codegraph_context_reject_handoff | Reject a pending ownership transfer |
| codegraph_context_revoke_share | Revoke explicit participant access from a session |
| codegraph_context_fetch | Fetch semantic context candidates for the active OpenCode session |
| codegraph_context_read | Read a specific OpenViking viking:// URI |
| codegraph_context_browse | Browse an OpenViking viking:// URI tree |
| codegraph_context_record_used_context | Persist used-context trace before background commit |
| codegraph_context_close_session | Explicitly close an active context session so it cannot be resumed accidentally |
| codegraph_context_archive_session | Archive a context session for history without keeping it active |
| codegraph_context_commit | Trigger background commit for the explicit context session |
| codegraph_context_status | Check background commit status |
| codegraph_skill_list | List curated agent-visible CodeGraph skills for the current project scope |
| codegraph_review | Security + impact analysis on current diff |
| codegraph_explain_function | Deep function analysis with call graph |
Permissions
All codegraph_* MCP tools are auto-allowed -- no confirmation prompts.
Custom Commands
Place in .opencode/commands/:
| Command | Description |
|---------|-------------|
| /review | CPG-powered code review |
| /audit | Full codebase audit (12 dimensions) |
| /explain | Function analysis with call graph |
| /onboard | Codebase understanding |
| /update | Freshness check and incremental CPG update |
| /status | Unified freshness + latest review-trace status |
| /next | Single best next command for the current workflow state |
| /continue | Reconnect the remembered explicit session first and surface shared or handed-off lifecycle state before resuming work |
Custom Agent
.opencode/agents/codegraph.md -- CPG-focused analysis agent. Switch with /agent codegraph.
Configuration
| Variable | Default | Description |
|----------|---------|-------------|
| CODEGRAPH_API_URL | http://localhost:8000 | CodeGraph API base URL |
| CODEGRAPH_PROJECT | (empty) | Default project ID |
Operator note: the backend can disable multi-user share and handoff flows with openviking.multi_user_sessions_enabled=false while keeping the original single-user explicit session workflow available.
Hooks
| Hook | Purpose |
|------|---------|
| experimental.chat.system.transform | Inject project summary into system prompt |
| chat.message | Add CPG context for mentioned files |
| chat.message (edit intent) | Add pre-edit warnings for files likely to be modified |
| chat.message (workflow intent) | Add dogfooding status when the user asks what to do next |
| tool.execute.after on test commands | Add after-test workflow guidance and detect failed test runs before suggesting the next command |
| tool.execute.after on git status / git diff | Add the same normalized workflow guidance block used by other status-oriented surfaces |
| tool.execute.after | Trigger CPG update after git commit and append structured post-commit review summary |
| generic tool.execute.after | Surface workflow-state transitions after other bash commands when the underlying state changes |
| codegraph_context_* tools | Explicit OpenViking-backed agent context operations with background commit |
| codegraph_review tool | Returns review results together with current workflow guidance and suggested follow-up command |
| codegraph_explain_function tool | Returns function analysis together with current workflow guidance |
| experimental.session.compacting | Preserve current dogfooding status when OpenCode compacts long sessions |
| experimental.session.compacting (Phase 3) | Persist and restore explicit session continuity summary for resume-after-compaction |
| command.execute.before | Inject current dogfooding status into /review, /audit, /update, /status, /next, /continue, and scenario-aware /explain |
| command.execute.before on /continue | Prefer reconnect/resume semantics and emit manual fallback instructions when no local state is available |
| command.execute.before on /status and /update | Surface explicit context follow-up state when the session runtime already knows the active evidence chain |
| command.execute.before on /explain | Bootstrap one bounded investigation session before explanation-specific tools are used |
| permission.ask | Auto-allow codegraph_* tools |
Across status-oriented surfaces, the plugin is converging on one shared summary contract:
- workflow state
- policy version / priority reason
- primary issue
- recovery sequence
- blockers
- warnings
- what improved
- still blocked
- recommended command
- database access blockers when DuckDB reads are temporarily unavailable
License
MIT
