No more wasting the first 20% of your session context asking the agent to explore your repo, and no more repeating yourself every session. The agent will know your codebase structure. This doesn't take many tokens away from your context as the structure is already summarized in markdown.
The Context Manager scans your repository and creates/updates modular context files in .opencode/context/. It always creates repo-structure.md with core project info, and optionally creates additional files for components, hooks, API endpoints, etc. based on what it discovers.
Once installed, context files are automatically included in every prompt, giving the AI persistent knowledge about your project.
Version 2.0 introduces a two-phase architecture: static analysis (zero AI tokens) followed by selective AI reading (minimal tokens).
Phase 1: Static Analysis (0 AI tokens)
├── TypeScript Compiler API → imports, exports, signatures, JSDoc
├── Dependency graph → file relationships, importance scores
├── Auto-summarizer → summaries for well-documented files
└── Capability detector → database, auth, integrations, etc.
Phase 2: AI Agent (minimal tokens)
├── Reads pre-analysis summary (map of the codebase)
├── Reads only important/undocumented files
├── Detects cross-file patterns from samples
└── Generates context from summaries + readings
| Scenario | Cost | vs Reading Everything |
|---|---|---|
| First run | ~150-200K tokens | 40-55% savings |
| Full scan (cached) | ~15-20K tokens | 94% savings |
| Incremental (5 files) | ~8-12K tokens | 97% savings |
| Incremental (1 file) | ~3-5K tokens | 99% savings |
| No changes | ~0 tokens | 100% savings |
First Run (one-time investment):
- Static analysis builds dependency graph and auto-generates summaries (0 AI tokens)
- AI reads only important files (those without JSDoc, heavily imported, etc.)
- AI generates comprehensive context from summaries + file readings
- Everything cached in
.opencode/analysis/(committed to git for team sharing)
Subsequent Updates (cheap and fast):
- Git diff identifies changed files
- Dependency graph finds affected files (imports/exports tracking)
- AI re-reads only affected files and updates their context sections
- Unchanged content preserved
The static analysis pre-processes your codebase and detects:
- Dependencies & imports: Symbol-level tracking (which functions imported from where)
- Project capabilities: Database/ORM, auth provider, state management, styling framework, API style, integrations (Stripe, SendGrid, etc.), deployment platform, CI/CD, queues, realtime, i18n, testing, logging, monorepo setup, and more
- File importance: Scores each file by import count, JSDoc presence, file size, and complexity
- Auto-summaries: Generates descriptions for well-documented and simple files without AI
TypeScript (primary, symbol-level):
- Uses TypeScript Compiler API
- Tracks which specific symbols are imported from each module
- Extracts JSDoc comments, interface members, function signatures
- Detects
anytypes and generic names as needing AI reading
JavaScript (fallback, file-level):
- Uses madge for file-level dependency tracking
- Detects circular dependencies
Other languages: Falls back to pattern-based categorization
# Auto-decide (recommended)
/context-update
# Force full scan
/context-update --full
# Rebuild dependency graph
/context-update --rebuild-graphThe tool outputs a human-readable action plan before scanning:
═══════════════════════════════════════════════════════════
CONTEXT UPDATE ACTION PLAN
═══════════════════════════════════════════════════════════
MODE: INCREMENTAL UPDATE
REASON: Changes are localized and safe for incremental update
CHANGED FILES: 3
~ src/components/Button.tsx
~ src/utils/helpers.ts
+ src/hooks/useDebounce.ts
AFFECTED FILES: 4
• src/components/Button.tsx
Directly modified
• src/utils/helpers.ts
Directly modified (exports unchanged, importers safe)
• src/hooks/useDebounce.ts
New file added
• src/pages/Home.tsx
Imports Button.tsx (exports changed)
ACTIONS:
1. Read ONLY the affected files listed above
2. Update their summaries in the analysis cache
3. Update ONLY the affected sections in context files
4. Preserve all unchanged content
5. Save context with new git metadata
───────────────────────────────────────────────────────────
ESTIMATED TOKEN USAGE: ~10K tokens
SAVINGS vs full read: ~97%
═══════════════════════════════════════════════════════════
Analysis artifacts are committed to git so the whole team benefits:
.opencode/
├── analysis/ # Committed to git
│ └── codebase-analysis.json # Dependency graph + summaries + capabilities
├── context/ # Committed to git
│ ├── repo-structure.md
│ └── (optional category files)
├── skill/
└── command/
Run the test script to verify the system:
./test-incremental.sh- Cumulative Knowledge: Each time you update context, it enriches the knowledge base for future work
- Faster Onboarding: New AI agents (or human developers) can quickly understand the codebase structure
- Consistency: Architectural patterns and conventions get documented automatically
- Long-term Memory: Important patterns don't get lost between coding sessions
- Always Available: Context is automatically included in every prompt
Run this command in your project root:
npx opencode-context-manager initThis will:
- Install the
/context-updatecommand and skill - Configure
opencode.jsonto include context files in every prompt (via glob pattern)
# Overwrite existing files without asking
npx opencode-context-manager init --force
# Install globally to ~/.config/opencode/
npx opencode-context-manager init --globalAfter installation, generate your context files:
# Run inside OpenCode
/context-updateThe skill will:
- Scan the repository from your current directory downward
- Discover components, hooks, services, types, and patterns
- Create/update context files in
.opencode/context/ - Report what changed
Created context files in .opencode/context/
repo-structure.md
- Tech stack: React 19.2.0 with TypeScript
- Directory structure mapped
- 5 environment variables documented
frontend/components.md
- 12 reusable components documented
frontend/hooks.md
- 5 custom hooks documented
Summary: Created 3 context files.
Updated context files in .opencode/context/
repo-structure.md
~ Updated Tech Stack: added @types/node v24.10.1
frontend/components.md
+ Added: WeatherSummary, LoadingSpinner (2 new)
- Removed: OldButton (no longer exists)
frontend/hooks.md
+ Added: useSummary
Summary: Updated 3 files.
The skill intelligently scans for:
- Framework, language, and versions (from package.json, etc.)
- Build tools
- Key dependencies
- Components: React, Vue, Svelte components with descriptions
- Hooks: Custom React hooks / Vue composables
- API Services: Backend integration code
- Utilities: Helper functions and modules
- Types: TypeScript definitions and interfaces
- Export styles (named vs default)
- Naming conventions
- File organization patterns
- Error handling approaches
- Required environment variables (from .env.example)
- Build commands and scripts
- Testing setup (if present)
The skill uses smart discovery:
- Doesn't hardcode paths - adapts to your project structure
- Deep scans up to 5 directory levels
- Follows import patterns to find what's actually used
- Works with any framework: React, Vue, Node, Go, Python, etc.
The context file is scoped to where you run the command:
# From repo root - scans everything
/project$ /context-update
-> Creates .opencode/context/repo-structure.md (entire repo)
# From subdirectory - scans only that subtree
/project/packages/frontend$ /context-update
-> Creates packages/frontend/.opencode/context/repo-structure.md (frontend only)For monorepos, you can have context files for each package. Add glob patterns to your opencode.json:
{
"instructions": [
".opencode/context/**/*.md",
"packages/frontend/.opencode/context/**/*.md",
"packages/backend/.opencode/context/**/*.md"
]
}Then run /context-update from each package directory to generate its context.
Run /context-update when:
- After completing a major feature - Capture structural changes
- After refactoring - Document new patterns and organization
- When joining a project - Create initial context for AI agents
- Periodically - Keep context fresh (it's idempotent, safe to run anytime)
- Forgot to run it for a while? - No problem! It scans current state, not history
The skill creates modular context files based on what it discovers:
.opencode/context/
├── repo-structure.md # Always created - core project info
├── frontend/ # Created if frontend-heavy
│ ├── components.md # If 3+ reusable components
│ └── hooks.md # If 3+ custom hooks
├── backend/ # Created if backend-heavy
│ ├── api.md # If significant API surface
│ └── services.md # If 3+ service modules
└── shared/ # Created if significant shared code
├── types.md # Key TypeScript types
└── utilities.md # Utility functions
Simple projects may only need repo-structure.md. Larger projects get additional files automatically when there's enough content to warrant separation.
Contains: Tech stack, directory structure, conventions, environment variables, build scripts.
| File | Created when... |
|---|---|
frontend/components.md |
3+ reusable UI components |
frontend/hooks.md |
3+ custom hooks/composables |
backend/api.md |
Significant API endpoints |
backend/services.md |
3+ service modules |
shared/types.md |
Key TypeScript types |
shared/utilities.md |
3+ utility modules |
The skill and command files are installed locally in your .opencode/ folder. Feel free to customize them:
- Change output location: Edit
.opencode/skill/context-update/SKILL.mdand update the output path - Add/remove sections: Modify the skill instructions to scan for different things
- Change scanning depth: Adjust the depth limit in the skill
To update to a newer version of the skill:
npx opencode-context-manager init --forceAfter installation, your project will have:
your-project/
├── .opencode/
│ ├── command/
│ │ └── context-update.md # The /context-update command
│ ├── skill/
│ │ └── context-update/
│ │ └── SKILL.md # Skill instructions
│ └── context/ # Generated context (after first run)
│ ├── repo-structure.md # Always created
│ ├── frontend/ # Optional, if relevant
│ │ ├── components.md
│ │ └── hooks.md
│ └── backend/ # Optional, if relevant
│ └── api.md
└── opencode.json # Config with glob pattern
You can run context updates non-interactively using the OpenCode CLI. This is useful for:
- Git hooks (post-commit, pre-push)
- CI pipelines (on PR merge to main)
- Scripts
opencode run --model <provider/model> "/context-update"Note: The --model flag is required in non-interactive mode.
# .github/workflows/context-update.yml
name: Update Context
on:
pull_request:
types: [closed]
branches: [main]
jobs:
update-context:
if: github.event.pull_request.merged == true
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install OpenCode
run: curl -fsSL https://opencode.ai/install | bash
- name: Update context
run: opencode run --model <provider/model> "/context-update"
env:
# Add your provider's API key as a secret
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
- name: Commit changes
run: |
git config user.name "github-actions[bot]"
git config user.email "github-actions[bot]@users.noreply.github.com"
git add .opencode/context/
git diff --staged --quiet || git commit -m "chore: update repo context"
git pushon:
push:
branches: [main]This usually means TypeScript compilation errors or missing dependencies.
Fix:
# Check for TypeScript errors
npx tsc --noEmit
# Install dependencies
npm install
# Try updating with full scan
/context-update --fullThe tool will automatically fall back to file-level analysis (madge) if TypeScript analysis fails.
This is normal and happens when:
- Switching branches
- First run after git clone
- Cache older than 7 days
- Config files changed
The tool will regenerate the cache (~30K tokens) then use it for future updates.
Force a full scan to ensure everything is current:
/context-update --fullIf you suspect the incremental logic missed something:
-
Check the analysis cache:
cat .opencode/analysis/codebase-analysis.json | head -20 -
Rebuild the dependency graph:
/context-update --rebuild-graph
-
Or force full scan:
/context-update --full
The tool requires a git repository for incremental updates. Initialize one:
git init
git add .
git commit -m "Initial commit"If you want to always use full scans, set an environment variable:
export OPENCODE_CONTEXT_INCREMENTAL=false
/context-updateThe skill only reads .env.example or template files - it never reads actual .env files that might contain secrets.
Found a pattern the skill should detect? Want to improve the scanning logic? Contributions welcome!
MIT