docs: update AGENTS.md hierarchy with latest structure and line counts

- Root: Add Prometheus/Metis/Momus agents, MCP architecture, 82 test files
- agents/: Document 7-section delegation and wisdom notepad
- auth/: Multi-account load balancing (10 accounts), endpoint fallback
- features/: Update background-agent 825 lines, builtin-skills 1230 lines
- hooks/: 22+ hooks with event timing details
- tools/: sisyphus-task 583 lines, LSP client 632 lines
- cli/: config-manager 725 lines, 17+ doctor checks
- shared/: Cross-cutting utilities with usage patterns
This commit is contained in:
YeonGyu-Kim 2026-01-13 21:00:00 +09:00
parent cf53b2b51a
commit d9ab6ab99b
8 changed files with 211 additions and 303 deletions

View File

@ -1,7 +1,7 @@
# PROJECT KNOWLEDGE BASE # PROJECT KNOWLEDGE BASE
**Generated:** 2026-01-09T15:38:00+09:00 **Generated:** 2026-01-13T14:45:00+09:00
**Commit:** 0581793 **Commit:** e47b5514
**Branch:** dev **Branch:** dev
## OVERVIEW ## OVERVIEW
@ -13,16 +13,16 @@ OpenCode plugin implementing Claude Code/AmpCode features. Multi-model agent orc
``` ```
oh-my-opencode/ oh-my-opencode/
├── src/ ├── src/
│ ├── agents/ # AI agents (7): Sisyphus, oracle, librarian, explore, frontend, document-writer, multimodal-looker │ ├── agents/ # AI agents (7+): Sisyphus, oracle, librarian, explore, frontend, document-writer, multimodal-looker, prometheus, metis, momus
│ ├── hooks/ # 22 lifecycle hooks - see src/hooks/AGENTS.md │ ├── hooks/ # 22+ lifecycle hooks - see src/hooks/AGENTS.md
│ ├── tools/ # LSP, AST-Grep, Grep, Glob, session mgmt - see src/tools/AGENTS.md │ ├── tools/ # LSP, AST-Grep, Grep, Glob, session mgmt - see src/tools/AGENTS.md
│ ├── features/ # Claude Code compat layer - see src/features/AGENTS.md │ ├── features/ # Claude Code compat layer - see src/features/AGENTS.md
│ ├── auth/ # Google Antigravity OAuth - see src/auth/AGENTS.md │ ├── auth/ # Google Antigravity OAuth - see src/auth/AGENTS.md
│ ├── shared/ # Cross-cutting utilities - see src/shared/AGENTS.md │ ├── shared/ # Cross-cutting utilities - see src/shared/AGENTS.md
│ ├── cli/ # CLI installer, doctor - see src/cli/AGENTS.md │ ├── cli/ # CLI installer, doctor - see src/cli/AGENTS.md
│ ├── mcp/ # MCP configs: context7, grep_app │ ├── mcp/ # MCP configs: context7, grep_app, websearch
│ ├── config/ # Zod schema, TypeScript types │ ├── config/ # Zod schema (12k lines), TypeScript types
│ └── index.ts # Main plugin entry (548 lines) │ └── index.ts # Main plugin entry (563 lines)
├── script/ # build-schema.ts, publish.ts, generate-changelog.ts ├── script/ # build-schema.ts, publish.ts, generate-changelog.ts
├── assets/ # JSON schema ├── assets/ # JSON schema
└── dist/ # Build output (ESM + .d.ts) └── dist/ # Build output (ESM + .d.ts)
@ -50,7 +50,7 @@ oh-my-opencode/
| Shared utilities | `src/shared/` | Cross-cutting utilities | | Shared utilities | `src/shared/` | Cross-cutting utilities |
| Slash commands | `src/hooks/auto-slash-command/` | Auto-detect and execute `/command` patterns | | Slash commands | `src/hooks/auto-slash-command/` | Auto-detect and execute `/command` patterns |
| Ralph Loop | `src/hooks/ralph-loop/` | Self-referential dev loop until completion | | Ralph Loop | `src/hooks/ralph-loop/` | Self-referential dev loop until completion |
| Orchestrator | `src/hooks/sisyphus-orchestrator/` | Main orchestration hook (660 lines) | | Orchestrator | `src/hooks/sisyphus-orchestrator/` | Main orchestration hook (677 lines) |
## TDD (Test-Driven Development) ## TDD (Test-Driven Development)
@ -83,7 +83,7 @@ oh-my-opencode/
- **Build**: `bun build` (ESM) + `tsc --emitDeclarationOnly` - **Build**: `bun build` (ESM) + `tsc --emitDeclarationOnly`
- **Exports**: Barrel pattern in index.ts; explicit named exports for tools/hooks - **Exports**: Barrel pattern in index.ts; explicit named exports for tools/hooks
- **Naming**: kebab-case directories, createXXXHook/createXXXTool factories - **Naming**: kebab-case directories, createXXXHook/createXXXTool factories
- **Testing**: BDD comments `#given/#when/#then`, TDD workflow (RED-GREEN-REFACTOR) - **Testing**: BDD comments `#given/#when/#then`, TDD workflow (RED-GREEN-REFACTOR), 82 test files
- **Temperature**: 0.1 for code agents, max 0.3 - **Temperature**: 0.1 for code agents, max 0.3
## ANTI-PATTERNS (THIS PROJECT) ## ANTI-PATTERNS (THIS PROJECT)
@ -122,13 +122,16 @@ oh-my-opencode/
| Agent | Default Model | Purpose | | Agent | Default Model | Purpose |
|-------|---------------|---------| |-------|---------------|---------|
| Sisyphus | anthropic/claude-opus-4-5 | Primary orchestrator | | Sisyphus | anthropic/claude-opus-4-5 | Primary orchestrator with extended thinking |
| oracle | openai/gpt-5.2 | Read-only consultation. High-IQ debugging, architecture | | oracle | openai/gpt-5.2 | Read-only consultation. High-IQ debugging, architecture |
| librarian | opencode/glm-4.7-free | Multi-repo analysis, docs | | librarian | opencode/glm-4.7-free | Multi-repo analysis, docs |
| explore | opencode/grok-code | Fast codebase exploration | | explore | opencode/grok-code | Fast codebase exploration |
| frontend-ui-ux-engineer | google/gemini-3-pro-preview | UI generation | | frontend-ui-ux-engineer | google/gemini-3-pro-preview | UI generation |
| document-writer | google/gemini-3-pro-preview | Technical docs | | document-writer | google/gemini-3-pro-preview | Technical docs |
| multimodal-looker | google/gemini-3-flash | PDF/image analysis | | multimodal-looker | google/gemini-3-flash | PDF/image analysis |
| Prometheus (Planner) | anthropic/claude-opus-4-5 | Strategic planning, interview-driven |
| Metis (Plan Consultant) | anthropic/claude-sonnet-4-5 | Pre-planning analysis |
| Momus (Plan Reviewer) | anthropic/claude-sonnet-4-5 | Plan validation |
## COMMANDS ## COMMANDS
@ -137,7 +140,7 @@ bun run typecheck # Type check
bun run build # ESM + declarations + schema bun run build # ESM + declarations + schema
bun run rebuild # Clean + Build bun run rebuild # Clean + Build
bun run build:schema # Schema only bun run build:schema # Schema only
bun test # Run tests (76 test files, 2559+ BDD assertions) bun test # Run tests (82 test files, 2559+ BDD assertions)
``` ```
## DEPLOYMENT ## DEPLOYMENT
@ -160,23 +163,38 @@ bun test # Run tests (76 test files, 2559+ BDD assertions)
| File | Lines | Description | | File | Lines | Description |
|------|-------|-------------| |------|-------|-------------|
| `src/agents/orchestrator-sisyphus.ts` | 1484 | Orchestrator agent, complex delegation | | `src/agents/orchestrator-sisyphus.ts` | 1486 | Orchestrator agent, 7-section delegation, accumulated wisdom |
| `src/features/builtin-skills/skills.ts` | 1230 | Skill definitions (frontend-ui-ux, playwright) | | `src/features/builtin-skills/skills.ts` | 1230 | Skill definitions (frontend-ui-ux, playwright) |
| `src/agents/prometheus-prompt.ts` | 982 | Planning agent system prompt | | `src/agents/prometheus-prompt.ts` | 988 | Planning agent, interview mode, multi-agent validation |
| `src/auth/antigravity/fetch.ts` | 798 | Token refresh, URL rewriting | | `src/auth/antigravity/fetch.ts` | 798 | Token refresh, multi-account rotation, endpoint fallback |
| `src/auth/antigravity/thinking.ts` | 755 | Thinking block extraction | | `src/auth/antigravity/thinking.ts` | 755 | Thinking block extraction, signature management |
| `src/cli/config-manager.ts` | 725 | JSONC parsing, env detection | | `src/cli/config-manager.ts` | 725 | JSONC parsing, multi-level config, env detection |
| `src/hooks/sisyphus-orchestrator/index.ts` | 660 | Orchestrator hook impl | | `src/hooks/sisyphus-orchestrator/index.ts` | 677 | Orchestrator hook impl |
| `src/agents/sisyphus.ts` | 641 | Main Sisyphus prompt | | `src/agents/sisyphus.ts` | 643 | Main Sisyphus prompt |
| `src/tools/lsp/client.ts` | 612 | LSP protocol, JSON-RPC | | `src/tools/lsp/client.ts` | 632 | LSP protocol, JSON-RPC |
| `src/features/background-agent/manager.ts` | 608 | Task lifecycle | | `src/features/background-agent/manager.ts` | 825 | Task lifecycle, concurrency |
| `src/auth/antigravity/response.ts` | 599 | Response transformation, streaming | | `src/auth/antigravity/response.ts` | 598 | Response transformation, streaming |
| `src/hooks/anthropic-context-window-limit-recovery/executor.ts` | 556 | Multi-stage recovery | | `src/tools/sisyphus-task/tools.ts` | 583 | Category-based task delegation |
| `src/index.ts` | 548 | Main plugin, all hook/tool init | | `src/index.ts` | 563 | Main plugin, all hook/tool init |
| `src/hooks/anthropic-context-window-limit-recovery/executor.ts` | 555 | Multi-stage recovery |
## MCP ARCHITECTURE
Three-tier MCP system:
1. **Built-in**: `websearch` (Exa), `context7` (docs), `grep_app` (GitHub search)
2. **Claude Code compatible**: `.mcp.json` files with `${VAR}` expansion
3. **Skill-embedded**: YAML frontmatter in skills (e.g., playwright)
## CONFIG SYSTEM
- **Zod validation**: `src/config/schema.ts` (12k lines)
- **JSONC support**: Comments and trailing commas
- **Multi-level**: User (`~/.config/opencode/`) → Project (`.opencode/`)
- **CLI doctor**: Validates config and reports errors
## NOTES ## NOTES
- **Testing**: Bun native test (`bun test`), BDD-style `#given/#when/#then`, 76 test files - **Testing**: Bun native test (`bun test`), BDD-style `#given/#when/#then`, 82 test files
- **OpenCode**: Requires >= 1.0.150 - **OpenCode**: Requires >= 1.0.150
- **Multi-lang docs**: README.md (EN), README.ko.md (KO), README.ja.md (JA), README.zh-cn.md (ZH-CN) - **Multi-lang docs**: README.md (EN), README.ko.md (KO), README.ja.md (JA), README.zh-cn.md (ZH-CN)
- **Config**: `~/.config/opencode/oh-my-opencode.json` (user) or `.opencode/oh-my-opencode.json` (project) - **Config**: `~/.config/opencode/oh-my-opencode.json` (user) or `.opencode/oh-my-opencode.json` (project)

View File

@ -1,25 +1,23 @@
# AGENTS KNOWLEDGE BASE # AGENTS KNOWLEDGE BASE
## OVERVIEW ## OVERVIEW
AI agent definitions for multi-model orchestration, delegating tasks to specialized experts.
AI agent definitions for multi-model orchestration. 7 specialized agents: Sisyphus (orchestrator), oracle (read-only consultation), librarian (research), explore (grep), frontend-ui-ux-engineer, document-writer, multimodal-looker.
## STRUCTURE ## STRUCTURE
``` ```
agents/ agents/
├── orchestrator-sisyphus.ts # Orchestrator agent (1484 lines) - complex delegation ├── orchestrator-sisyphus.ts # Orchestrator agent (1486 lines) - 7-section delegation, wisdom
├── sisyphus.ts # Main Sisyphus prompt (641 lines) ├── sisyphus.ts # Main Sisyphus prompt (643 lines)
├── sisyphus-junior.ts # Junior variant for delegated tasks ├── sisyphus-junior.ts # Junior variant for delegated tasks
├── oracle.ts # Strategic advisor (GPT-5.2) ├── oracle.ts # Strategic advisor (GPT-5.2)
├── librarian.ts # Multi-repo research (Claude Sonnet 4.5) ├── librarian.ts # Multi-repo research (GLM-4.7-free)
├── explore.ts # Fast codebase grep (Grok Code) ├── explore.ts # Fast codebase grep (Grok Code)
├── frontend-ui-ux-engineer.ts # UI generation (Gemini 3 Pro) ├── frontend-ui-ux-engineer.ts # UI generation (Gemini 3 Pro)
├── document-writer.ts # Technical docs (Gemini 3 Pro) ├── document-writer.ts # Technical docs (Gemini 3 Pro)
├── multimodal-looker.ts # PDF/image analysis (Gemini 3 Flash) ├── multimodal-looker.ts # PDF/image analysis (Gemini 3 Flash)
├── prometheus-prompt.ts # Planning agent prompt (982 lines) ├── prometheus-prompt.ts # Planning agent prompt (988 lines) - interview mode
├── metis.ts # Plan Consultant agent (404 lines) ├── metis.ts # Plan Consultant agent - pre-planning analysis
├── momus.ts # Plan Reviewer agent (404 lines) ├── momus.ts # Plan Reviewer agent - plan validation
├── build-prompt.ts # Shared build agent prompt ├── build-prompt.ts # Shared build agent prompt
├── plan-prompt.ts # Shared plan agent prompt ├── plan-prompt.ts # Shared plan agent prompt
├── types.ts # AgentModelConfig interface ├── types.ts # AgentModelConfig interface
@ -28,69 +26,35 @@ agents/
``` ```
## AGENT MODELS ## AGENT MODELS
| Agent | Default Model | Purpose |
| Agent | Default Model | Fallback | Purpose | |-------|---------------|---------|
|-------|---------------|----------|---------| | Sisyphus | claude-opus-4-5 | Primary orchestrator. 32k extended thinking budget. |
| Sisyphus | anthropic/claude-opus-4-5 | - | Primary orchestrator with extended thinking | | oracle | openai/gpt-5.2 | High-IQ debugging, architecture, strategic consultation. |
| oracle | openai/gpt-5.2 | - | Read-only consultation. High-IQ debugging, architecture | | librarian | glm-4.7-free | Multi-repo analysis, docs research, GitHub examples. |
| librarian | opencode/glm-4.7-free | - | Docs, OSS research, GitHub examples | | explore | grok-code | Fast contextual grep. Fallbacks: Gemini-3-Flash, Haiku-4-5. |
| explore | opencode/grok-code | google/gemini-3-flash, anthropic/claude-haiku-4-5 | Fast contextual grep | | frontend-ui-ux | gemini-3-pro | Production-grade UI/UX generation and styling. |
| frontend-ui-ux-engineer | google/gemini-3-pro-preview | - | UI/UX code generation | | document-writer | gemini-3-pro | Technical writing, guides, API documentation. |
| document-writer | google/gemini-3-pro-preview | - | Technical writing | | Prometheus | claude-opus-4-5 | Strategic planner. Interview mode, orchestrates Metis/Momus. |
| multimodal-looker | google/gemini-3-flash | - | PDF/image analysis | | Metis | claude-sonnet-4-5 | Plan Consultant. Pre-planning risk/requirement analysis. |
| Momus | claude-sonnet-4-5 | Plan Reviewer. Validation and quality enforcement. |
## HOW TO ADD AN AGENT ## HOW TO ADD AN AGENT
1. Create `src/agents/my-agent.ts` exporting `AgentConfig`.
1. Create `src/agents/my-agent.ts`: 2. Add to `builtinAgents` in `src/agents/index.ts`.
```typescript 3. Update `types.ts` if adding new config interfaces.
import type { AgentConfig } from "@opencode-ai/sdk"
export const myAgent: AgentConfig = {
model: "provider/model-name",
temperature: 0.1,
system: "Agent system prompt...",
tools: { include: ["tool1", "tool2"] }, // or exclude: [...]
}
```
2. Add to `builtinAgents` in `src/agents/index.ts`
3. Update `types.ts` if adding new config options
## AGENT CONFIG OPTIONS
| Option | Type | Description |
|--------|------|-------------|
| model | string | Model identifier (provider/model-name) |
| temperature | number | 0.0-1.0, most use 0.1 for consistency |
| system | string | System prompt (can be multiline template literal) |
| tools | object | `{ include: [...] }` or `{ exclude: [...] }` |
| top_p | number | Optional nucleus sampling |
| maxTokens | number | Optional max output tokens |
## MODEL FALLBACK LOGIC ## MODEL FALLBACK LOGIC
`createBuiltinAgents()` handles resolution:
1. User config override (`agents.{name}.model`).
2. Environment-specific settings (max20, antigravity).
3. Hardcoded defaults in `index.ts`.
`createBuiltinAgents()` in utils.ts handles model fallback: ## ANTI-PATTERNS
- **Trusting reports**: NEVER trust subagent self-reports; always verify outputs.
1. Check user config override (`agents.{name}.model`) - **High temp**: Don't use >0.3 for code agents (Sisyphus/Prometheus use 0.1).
2. Check installer settings (claude max20, gemini antigravity) - **Sequential calls**: Prefer `sisyphus_task` with `run_in_background` for parallelism.
3. Use default model
**Fallback order for explore**:
- If gemini antigravity enabled → `google/gemini-3-flash`
- If claude max20 enabled → `anthropic/claude-haiku-4-5`
- Default → `opencode/grok-code` (free)
## ANTI-PATTERNS (AGENTS)
- **High temperature**: Don't use >0.3 for code-related agents
- **Broad tool access**: Prefer explicit `include` over unrestricted access
- **Monolithic prompts**: Keep prompts focused; delegate to specialized agents
- **Missing fallbacks**: Consider free/cheap fallbacks for rate-limited models
## SHARED PROMPTS ## SHARED PROMPTS
- **build-prompt.ts**: Unified base for Sisyphus and Builder variants.
- **build-prompt.ts**: Base prompt for build agents (OpenCode default + Sisyphus variants) - **plan-prompt.ts**: Core planning logic shared across planning agents.
- **plan-prompt.ts**: Base prompt for plan agents (legacy) - **orchestrator-sisyphus.ts**: Uses a 7-section prompt structure and "wisdom notepad" to preserve learnings across turns.
- **prometheus-prompt.ts**: System prompt for Prometheus (Planner) agent
- **metis.ts**: Metis (Plan Consultant) agent for pre-planning analysis
Used by `src/index.ts` when creating Builder-Sisyphus and Prometheus (Planner) variants.

View File

@ -1,11 +1,9 @@
# AUTH KNOWLEDGE BASE # AUTH KNOWLEDGE BASE
## OVERVIEW ## OVERVIEW
Google Antigravity OAuth for Gemini models. Token management, fetch interception, thinking block extraction. Google Antigravity OAuth for Gemini models. Token management, fetch interception, thinking block extraction.
## STRUCTURE ## STRUCTURE
``` ```
auth/ auth/
└── antigravity/ └── antigravity/
@ -13,11 +11,11 @@ auth/
├── oauth.ts # OAuth flow, token acquisition ├── oauth.ts # OAuth flow, token acquisition
├── token.ts # Token storage, refresh logic ├── token.ts # Token storage, refresh logic
├── fetch.ts # Fetch interceptor (798 lines) ├── fetch.ts # Fetch interceptor (798 lines)
├── response.ts # Response transformation (599 lines) ├── response.ts # Response transformation (598 lines)
├── thinking.ts # Thinking block extraction (755 lines) ├── thinking.ts # Thinking block extraction (755 lines)
├── thought-signature-store.ts # Signature caching ├── thought-signature-store.ts # Signature caching
├── message-converter.ts # Format conversion ├── message-converter.ts # Format conversion
├── accounts.ts # Multi-account management ├── accounts.ts # Multi-account management (up to 10 accounts)
├── browser.ts # Browser automation for OAuth ├── browser.ts # Browser automation for OAuth
├── cli.ts # CLI interaction ├── cli.ts # CLI interaction
├── request.ts # Request building ├── request.ts # Request building
@ -29,33 +27,29 @@ auth/
``` ```
## KEY COMPONENTS ## KEY COMPONENTS
| File | Purpose | | File | Purpose |
|------|---------| |------|---------|
| fetch.ts | URL rewriting, token injection, retries | | fetch.ts | URL rewriting, multi-account rotation, endpoint fallback |
| thinking.ts | Extract `<antThinking>` blocks | | thinking.ts | Thinking block extraction, signature management, budget mapping |
| response.ts | Streaming SSE parsing | | response.ts | Streaming SSE parsing and response transformation |
| oauth.ts | Browser-based OAuth flow | | accounts.ts | Load balancing across up to 10 Google accounts |
| token.ts | Token persistence, expiry | | thought-signature-store.ts | Caching signatures for multi-turn thinking conversations |
## HOW IT WORKS ## HOW IT WORKS
1. **Intercept**: `fetch.ts` intercepts Anthropic/Google requests.
1. **Intercept**: fetch.ts intercepts Anthropic/Google requests 2. **Route**: Rotates accounts and selects best endpoint (daily → autopush → prod).
2. **Rewrite**: URLs → Antigravity proxy endpoints 3. **Auth**: Injects Bearer tokens from `token.ts` persistence.
3. **Auth**: Bearer token from stored OAuth credentials 4. **Process**: `response.ts` parses SSE; `thinking.ts` manages thought blocks.
4. **Response**: Streaming parsed, thinking blocks extracted 5. **Recovery**: Detects GCP permission errors and triggers recovery/rotation.
5. **Transform**: Normalized for OpenCode
## FEATURES ## FEATURES
- Multi-account load balancing (up to 10 accounts)
- Multi-account (up to 10 Google accounts) - Strategic endpoint fallback: daily → autopush → prod
- Auto-fallback on rate limit - Persistent thought signatures for continuity in thinking models
- Thinking blocks preserved - Automated GCP permission error recovery
- Antigravity proxy for AI Studio access
## ANTI-PATTERNS ## ANTI-PATTERNS
- Hardcoding endpoints: Use `constants.ts` or let `fetch.ts` route.
- Direct API calls (use fetch interceptor) - Manual token handling: Use `token.ts` and `storage.ts` abstraction.
- Tokens in code (use token.ts storage) - Sync OAuth calls: All auth flows must be non-blocking/async.
- Ignoring refresh (check expiry first) - Ignoring account rotation: Let `fetch.ts` handle load balancing.
- Blocking on OAuth (always async)

View File

@ -1,24 +1,22 @@
# CLI KNOWLEDGE BASE # CLI KNOWLEDGE BASE
## OVERVIEW ## OVERVIEW
CLI for oh-my-opencode: interactive installer, health diagnostics (doctor), runtime launcher. Entry: `bunx oh-my-opencode`. CLI for oh-my-opencode: interactive installer, health diagnostics (doctor), runtime launcher. Entry: `bunx oh-my-opencode`.
## STRUCTURE ## STRUCTURE
``` ```
cli/ cli/
├── index.ts # Commander.js entry, subcommand routing ├── index.ts # Commander.js entry, subcommand routing (184 lines)
├── install.ts # Interactive TUI installer (436 lines) ├── install.ts # Interactive TUI installer (436 lines)
├── config-manager.ts # JSONC parsing, env detection (725 lines) ├── config-manager.ts # JSONC parsing, env detection (725 lines)
├── types.ts # CLI-specific types ├── types.ts # CLI-specific types
├── commands/ # CLI subcommands ├── commands/ # CLI subcommands (auth.ts)
├── doctor/ # Health check system ├── doctor/ # Health check system
│ ├── index.ts # Doctor command entry │ ├── index.ts # Doctor command entry
│ ├── runner.ts # Health check orchestration │ ├── runner.ts # Health check orchestration
│ ├── constants.ts # Check categories │ ├── constants.ts # Check categories
│ ├── types.ts # Check result interfaces │ ├── types.ts # Check result interfaces
│ └── checks/ # 17+ individual checks (auth, config, dependencies, gh, lsp, mcp, opencode, plugin, version) │ └── checks/ # 10+ check modules (17+ individual checks)
├── get-local-version/ # Version detection ├── get-local-version/ # Version detection
└── run/ # OpenCode session launcher └── run/ # OpenCode session launcher
├── completion.ts # Completion logic ├── completion.ts # Completion logic
@ -26,47 +24,34 @@ cli/
``` ```
## CLI COMMANDS ## CLI COMMANDS
| Command | Purpose | | Command | Purpose |
|---------|---------| |---------|---------|
| `install` | Interactive setup wizard | | `install` | Interactive setup wizard with subscription detection |
| `doctor` | Environment health checks | | `doctor` | Environment health checks (LSP, Auth, Config, Deps) |
| `run` | Launch OpenCode session | | `run` | Launch OpenCode session with event handling |
| `auth` | Manage authentication providers |
## DOCTOR CHECKS ## DOCTOR CHECKS
17+ checks in `doctor/checks/`: 17+ checks in `doctor/checks/`:
- version.ts (OpenCode >= 1.0.150) - `version.ts`: OpenCode >= 1.0.150
- config.ts (plugin registered) - `config.ts`: Plugin registration & JSONC validity
- bun.ts, node.ts, git.ts - `dependencies.ts`: bun, node, git, gh-cli
- anthropic-auth.ts, openai-auth.ts, google-auth.ts - `auth.ts`: Anthropic, OpenAI, Google (Antigravity)
- lsp-*.ts, mcp-*.ts - `lsp.ts`, `mcp.ts`: Tool connectivity checks
## CONFIG-MANAGER (669 lines) ## CONFIG-MANAGER
- **JSONC**: Supports comments and trailing commas via `parseJsonc`
- JSONC support (comments, trailing commas) - **Multi-source**: Merges User (`~/.config/opencode/`) + Project (`.opencode/`)
- Multi-source: User (~/.config/opencode/) + Project (.opencode/) - **Validation**: Strict Zod schema with error aggregation for `doctor`
- Zod validation - **Env**: Detects `OPENCODE_CONFIG_DIR` for profile isolation
- Legacy format migration
- Error aggregation for doctor
## HOW TO ADD CHECK ## HOW TO ADD CHECK
1. Create `src/cli/doctor/checks/my-check.ts` returning `DoctorCheck`
1. Create `src/cli/doctor/checks/my-check.ts`: 2. Export from `checks/index.ts` and add to `getAllCheckDefinitions()`
```typescript 3. Use `CheckContext` for shared utilities (LSP, Auth)
export const myCheck: DoctorCheck = {
name: "my-check",
category: "environment",
check: async () => {
return { status: "pass" | "warn" | "fail", message: "..." }
}
}
```
2. Add to `src/cli/doctor/checks/index.ts`
## ANTI-PATTERNS ## ANTI-PATTERNS
- Blocking prompts in non-TTY (check `process.stdout.isTTY`) - Blocking prompts in non-TTY (check `process.stdout.isTTY`)
- Hardcoded paths (use shared utilities) - Direct `JSON.parse` (breaks JSONC compatibility)
- JSON.parse for user files (use parseJsonc) - Silent failures (always return `warn` or `fail` in `doctor`)
- Silent failures in doctor checks - Environment-specific hardcoding (use `ConfigManager`)

View File

@ -1,35 +1,34 @@
# FEATURES KNOWLEDGE BASE # FEATURES KNOWLEDGE BASE
## OVERVIEW ## OVERVIEW
Claude Code compatibility layer + core feature modules. Commands, skills, agents, MCPs, hooks from Claude Code work seamlessly. Claude Code compatibility layer + core feature modules. Commands, skills, agents, MCPs, hooks from Claude Code work seamlessly.
## STRUCTURE ## STRUCTURE
``` ```
features/ features/
├── background-agent/ # Task lifecycle, notifications (608 lines) ├── background-agent/ # Task lifecycle, notifications (825 lines manager.ts)
├── boulder-state/ # Boulder state persistence ├── boulder-state/ # Boulder state persistence
├── builtin-commands/ # Built-in slash commands ├── builtin-commands/ # Built-in slash commands
│ └── templates/ # start-work, refactor, init-deep, ralph-loop │ └── templates/ # start-work, refactor, init-deep, ralph-loop
├── builtin-skills/ # Built-in skills ├── builtin-skills/ # Built-in skills (1230 lines skills.ts)
│ ├── git-master/ # Atomic commits, rebase, history search │ ├── git-master/ # Atomic commits, rebase, history search
│ ├── playwright/ # Browser automation skill
│ └── frontend-ui-ux/ # Designer-turned-developer skill │ └── frontend-ui-ux/ # Designer-turned-developer skill
├── claude-code-agent-loader/ # ~/.claude/agents/*.md ├── claude-code-agent-loader/ # ~/.claude/agents/*.md
├── claude-code-command-loader/ # ~/.claude/commands/*.md ├── claude-code-command-loader/ # ~/.claude/commands/*.md
├── claude-code-mcp-loader/ # .mcp.json files ├── claude-code-mcp-loader/ # .mcp.json files
│ └── env-expander.ts # ${VAR} expansion │ └── env-expander.ts # ${VAR} expansion
├── claude-code-plugin-loader/ # installed_plugins.json (486 lines) ├── claude-code-plugin-loader/ # installed_plugins.json
├── claude-code-session-state/ # Session state persistence ├── claude-code-session-state/ # Session state persistence
├── context-injector/ # Context collection and injection ├── context-injector/ # Context collection and injection
├── opencode-skill-loader/ # Skills from OpenCode + Claude paths ├── opencode-skill-loader/ # Skills from OpenCode + Claude paths
├── skill-mcp-manager/ # MCP servers in skill YAML ├── skill-mcp-manager/ # MCP servers in skill YAML
├── task-toast-manager/ # Task toast notifications ├── task-toast-manager/ # Task toast notifications
└── hook-message-injector/ # Inject messages into conversation ├── hook-message-injector/ # Inject messages into conversation
└── context-injector/ # Context collection and injection
``` ```
## LOADER PRIORITY ## LOADER PRIORITY
| Loader | Priority (highest first) | | Loader | Priority (highest first) |
|--------|--------------------------| |--------|--------------------------|
| Commands | `.opencode/command/` > `~/.config/opencode/command/` > `.claude/commands/` > `~/.claude/commands/` | | Commands | `.opencode/command/` > `~/.config/opencode/command/` > `.claude/commands/` > `~/.claude/commands/` |
@ -38,7 +37,6 @@ features/
| MCPs | `.claude/.mcp.json` > `.mcp.json` > `~/.claude/.mcp.json` | | MCPs | `.claude/.mcp.json` > `.mcp.json` > `~/.claude/.mcp.json` |
## CONFIG TOGGLES ## CONFIG TOGGLES
```json ```json
{ {
"claude_code": { "claude_code": {
@ -52,21 +50,19 @@ features/
``` ```
## BACKGROUND AGENT ## BACKGROUND AGENT
- Lifecycle: pending → running → completed/failed - Lifecycle: pending → running → completed/failed
- OS notification on complete - Concurrency limits per provider/model (manager.ts)
- `background_output` to retrieve results - `background_output` to retrieve results, `background_cancel` for cleanup
- `background_cancel` with task_id or all=true - Automatic task expiration and cleanup logic
## SKILL MCP ## SKILL MCP
- MCP servers embedded in skill YAML frontmatter - MCP servers embedded in skill YAML frontmatter
- Lazy client loading, session-scoped cleanup - Lazy client loading via `skill-mcp-manager`
- `skill_mcp` tool exposes capabilities - `skill_mcp` tool for cross-skill tool discovery
- Session-scoped MCP server lifecycle management
## ANTI-PATTERNS ## ANTI-PATTERNS
- Sequential execution for independent tasks (use `sisyphus_task`)
- Blocking on load (loaders run at startup) - Trusting agent self-reports without verification
- No error handling (always try/catch) - Blocking main thread during loader initialization
- Ignoring priority order - Manual version bumping in `package.json`
- Writing to ~/.claude/ (read-only)

View File

@ -1,73 +1,54 @@
# HOOKS KNOWLEDGE BASE # HOOKS KNOWLEDGE BASE
## OVERVIEW ## OVERVIEW
22+ lifecycle hooks intercepting/modifying agent behavior via PreToolUse, PostToolUse, UserPromptSubmit, and more.
22+ lifecycle hooks intercepting/modifying agent behavior. Context injection, error recovery, output control, notifications.
## STRUCTURE ## STRUCTURE
``` ```
hooks/ hooks/
├── anthropic-context-window-limit-recovery/ # Auto-compact at token limit (556 lines) ├── anthropic-context-window-limit-recovery/ # Auto-summarize at token limit (555 lines)
├── auto-slash-command/ # Detect and execute /command patterns ├── sisyphus-orchestrator/ # Main orchestration & agent delegation (677 lines)
├── auto-update-checker/ # Version notifications, startup toast ├── ralph-loop/ # Self-referential dev loop (364 lines)
├── background-notification/ # OS notify on task complete ├── claude-code-hooks/ # settings.json hook compatibility layer
├── claude-code-hooks/ # settings.json PreToolUse/PostToolUse/etc (408 lines) ├── comment-checker/ # Prevents AI slop/excessive comments
├── comment-checker/ # Prevent excessive AI comments ├── auto-slash-command/ # Detects and executes /command patterns
│ ├── filters/ # docstring, directive, bdd, shebang
│ └── output/ # XML builder, formatter
├── compaction-context-injector/ # Preserve context during compaction
├── directory-agents-injector/ # Auto-inject AGENTS.md
├── directory-readme-injector/ # Auto-inject README.md
├── edit-error-recovery/ # Recover from edit failures
├── empty-message-sanitizer/ # Sanitize empty messages
├── interactive-bash-session/ # Tmux session management
├── keyword-detector/ # ultrawork/search keyword activation
├── non-interactive-env/ # CI/headless handling
├── preemptive-compaction/ # Pre-emptive at 85% usage
├── prometheus-md-only/ # Restrict prometheus to read-only
├── ralph-loop/ # Self-referential dev loop
├── rules-injector/ # Conditional rules from .claude/rules/ ├── rules-injector/ # Conditional rules from .claude/rules/
├── session-recovery/ # Recover from errors (432 lines) ├── directory-agents-injector/ # Auto-injects local AGENTS.md files
├── sisyphus-orchestrator/ # Main orchestration hook (660 lines) ├── directory-readme-injector/ # Auto-injects local README.md files
├── start-work/ # Initialize Sisyphus work session ├── preemptive-compaction/ # Triggers summary at 85% usage
├── task-resume-info/ # Track task resume state ├── edit-error-recovery/ # Recovers from tool execution failures
├── think-mode/ # Auto-detect thinking triggers ├── thinking-block-validator/ # Ensures valid <thinking> format
├── thinking-block-validator/ # Validate thinking block format ├── context-window-monitor.ts # Reminds agents of remaining headroom
├── agent-usage-reminder/ # Remind to use specialists ├── session-recovery/ # Auto-recovers from session crashes
├── context-window-monitor.ts # Monitor usage (standalone) ├── start-work/ # Initializes work sessions (ulw/ulw)
├── session-notification.ts # OS notify on idle ├── think-mode/ # Dynamic thinking budget adjustment
├── todo-continuation-enforcer.ts # Force TODO completion (413 lines) ├── background-notification/ # OS notification on task completion
└── tool-output-truncator.ts # Truncate verbose outputs ├── todo-continuation-enforcer.ts # Force completion of [ ] items
└── tool-output-truncator.ts # Prevents context bloat from verbose tools
``` ```
## HOOK EVENTS ## HOOK EVENTS
| Event | Timing | Can Block | Description |
| Event | Timing | Can Block | Use Case | |-------|--------|-----------|-------------|
|-------|--------|-----------|----------| | PreToolUse | Before tool | Yes | Validate/modify inputs (e.g., directory-agents-injector) |
| PreToolUse | Before tool | Yes | Validate, modify input | | PostToolUse | After tool | No | Append context/warnings (e.g., edit-error-recovery) |
| PostToolUse | After tool | No | Add context, warnings | | UserPromptSubmit | On prompt | Yes | Filter/modify user input (e.g., keyword-detector) |
| UserPromptSubmit | On prompt | Yes | Inject messages, block | | Stop | Session idle | No | Auto-continue tasks (e.g., todo-continuation-enforcer) |
| Stop | Session idle | No | Inject follow-ups | | onSummarize | Compaction | No | State preservation (e.g., compaction-context-injector) |
| onSummarize | Compaction | No | Preserve context |
## HOW TO ADD ## HOW TO ADD
1. Create `src/hooks/name/` with `index.ts` factory (e.g., `createMyHook`).
1. Create `src/hooks/my-hook/` 2. Implement `PreToolUse`, `PostToolUse`, `UserPromptSubmit`, `Stop`, or `onSummarize`.
2. Files: `index.ts` (createMyHook), `constants.ts`, `types.ts` (optional) 3. Register in `src/hooks/index.ts`.
3. Return: `{ PreToolUse?, PostToolUse?, UserPromptSubmit?, Stop?, onSummarize? }`
4. Export from `src/hooks/index.ts`
## PATTERNS ## PATTERNS
- **Context Injection**: Use `PreToolUse` to prepend instructions to tool inputs.
- **Storage**: JSON file for persistent state across sessions - **Resilience**: Implement `edit-error-recovery` style logic to retry failed tools.
- **Once-per-session**: Track injected paths in Set - **Telegraphic UI**: Use `PostToolUse` to add brief warnings without bloating transcript.
- **Message injection**: Return `{ messages: [...] }` - **Statelessness**: Prefer local file storage for state that must persist across sessions.
- **Blocking**: Return `{ blocked: true, message: "..." }` from PreToolUse
## ANTI-PATTERNS ## ANTI-PATTERNS
- **Blocking**: Avoid blocking tools unless critical (use warnings in `PostToolUse` instead).
- Heavy computation in PreToolUse (slows every tool call) - **Latency**: No heavy computation in `PreToolUse`; it slows every interaction.
- Blocking without actionable message - **Redundancy**: Don't inject the same file multiple times; track state in session storage.
- Duplicate injection (track what's injected) - **Prose**: Never use verbose prose in hook outputs; keep it technical and brief.
- Missing try/catch (don't crash session)

View File

@ -1,11 +1,9 @@
# SHARED UTILITIES KNOWLEDGE BASE # SHARED UTILITIES KNOWLEDGE BASE
## OVERVIEW ## OVERVIEW
Cross-cutting utilities for path resolution, config management, text processing, and Claude Code compatibility.
Cross-cutting utilities: path resolution, config management, text processing, Claude Code compatibility helpers.
## STRUCTURE ## STRUCTURE
``` ```
shared/ shared/
├── index.ts # Barrel export ├── index.ts # Barrel export
@ -30,7 +28,6 @@ shared/
``` ```
## WHEN TO USE ## WHEN TO USE
| Task | Utility | | Task | Utility |
|------|---------| |------|---------|
| Find ~/.claude | `getClaudeConfigDir()` | | Find ~/.claude | `getClaudeConfigDir()` |
@ -43,21 +40,19 @@ shared/
| Legacy names | `migrateLegacyAgentNames()` | | Legacy names | `migrateLegacyAgentNames()` |
## CRITICAL PATTERNS ## CRITICAL PATTERNS
```typescript ```typescript
// Dynamic truncation // Dynamic truncation with context budget
const output = dynamicTruncate(result, remainingTokens, 0.5) const output = dynamicTruncate(result, remainingTokens, 0.5)
// Deep merge priority // Config resolution priority
const final = deepMerge(deepMerge(defaults, userConfig), projectConfig) const final = deepMerge(deepMerge(defaults, userConfig), projectConfig)
// Safe JSONC // Safe JSONC parsing for user-edited files
const { config, error } = parseJsoncSafe(content) const { config, error } = parseJsoncSafe(content)
``` ```
## ANTI-PATTERNS ## ANTI-PATTERNS
- Hardcoding paths (use `getClaudeConfigDir`, `getUserConfigPath`)
- Hardcoding paths (use getClaudeConfigDir, getUserConfigPath) - Using `JSON.parse` for user configs (always use `parseJsonc`)
- JSON.parse for user files (use parseJsonc) - Ignoring output size (large tool outputs MUST use `dynamicTruncate`)
- Ignoring truncation (large outputs MUST use dynamicTruncate) - Manual case conversion (use `toSnakeCase`, `normalizeToolName`)
- Direct string concat for configs (use deepMerge)

View File

@ -1,85 +1,60 @@
# TOOLS KNOWLEDGE BASE # TOOLS KNOWLEDGE BASE
## OVERVIEW ## OVERVIEW
Custom tools extending agent capabilities: LSP (11 tools), AST-aware search/replace, background tasks, and multimodal analysis.
Custom tools extending agent capabilities: LSP integration (11 tools), AST-aware code search/replace, file operations with timeouts, background task management.
## STRUCTURE ## STRUCTURE
``` ```
tools/ tools/
├── ast-grep/ # AST-aware code search/replace (25 languages) ├── ast-grep/ # AST-aware search/replace (25 languages)
│ ├── cli.ts # @ast-grep/cli subprocess │ ├── cli.ts # @ast-grep/cli fallback
│ ├── napi.ts # @ast-grep/napi native binding (preferred) │ └── napi.ts # @ast-grep/napi native binding (preferred)
│ ├── constants.ts, types.ts, tools.ts, utils.ts
├── background-task/ # Async agent task management ├── background-task/ # Async agent task management
├── call-omo-agent/ # Spawn explore/librarian agents ├── call-omo-agent/ # Spawn explore/librarian agents
├── glob/ # File pattern matching (timeout-safe) ├── glob/ # File pattern matching (timeout-safe)
├── grep/ # Content search (timeout-safe) ├── grep/ # Content search (timeout-safe)
├── interactive-bash/ # Tmux session management ├── interactive-bash/ # Tmux session management
├── look-at/ # Multimodal analysis (PDF, images) ├── look-at/ # Multimodal analysis (PDF, images)
├── lsp/ # 11 LSP tools ├── lsp/ # IDE-like code intelligence
│ ├── client.ts # LSP connection lifecycle (612 lines) │ ├── client.ts # LSP connection lifecycle (632 lines)
│ ├── utils.ts # LSP utilities (461 lines) │ ├── tools.ts # Tool implementations
│ ├── config.ts # Server configurations │ └── config.ts, types.ts, utils.ts
│ ├── tools.ts # Tool implementations (405 lines) ├── session-manager/ # OpenCode session history management
│ └── types.ts ├── sisyphus-task/ # Category-based delegation (583 lines)
├── session-manager/ # OpenCode session file management ├── skill/ # Skill loading/execution
│ ├── constants.ts # Storage paths, descriptions
│ ├── types.ts # Session data interfaces
│ ├── storage.ts # File I/O operations
│ ├── utils.ts # Formatting, filtering
│ └── tools.ts # Tool implementations
├── sisyphus-task/ # Category-based task delegation (493 lines)
├── skill/ # Skill loading and execution
├── skill-mcp/ # Skill-embedded MCP invocation ├── skill-mcp/ # Skill-embedded MCP invocation
├── slashcommand/ # Slash command execution ├── slashcommand/ # Slash command execution
└── index.ts # builtinTools export └── index.ts # builtinTools export (82 lines)
``` ```
## TOOL CATEGORIES ## TOOL CATEGORIES
| Category | Tools | Purpose | | Category | Tools | Purpose |
|----------|-------|---------| |----------|-------|---------|
| LSP | lsp_hover, lsp_goto_definition, lsp_find_references, lsp_document_symbols, lsp_workspace_symbols, lsp_diagnostics, lsp_servers, lsp_prepare_rename, lsp_rename, lsp_code_actions, lsp_code_action_resolve | IDE-like code intelligence | | LSP | lsp_hover, lsp_goto_definition, lsp_find_references, lsp_diagnostics, lsp_rename, etc. | IDE-grade code intelligence (11 tools) |
| AST | ast_grep_search, ast_grep_replace | Pattern-based code search/replace | | AST | ast_grep_search, ast_grep_replace | Structural pattern matching/rewriting |
| File Search | grep, glob | Content and file pattern matching | | Search | grep, glob | Timeout-safe file and content search |
| Session | session_list, session_read, session_search, session_info | OpenCode session file management | | Session | session_list, session_read, session_search, session_info | History navigation and retrieval |
| Background | sisyphus_task, background_output, background_cancel | Async agent orchestration | | Background | sisyphus_task, background_output, background_cancel | Parallel agent orchestration |
| Multimodal | look_at | PDF/image analysis via Gemini | | UI/Terminal | look_at, interactive_bash | Visual analysis and tmux control |
| Terminal | interactive_bash | Tmux session control | | Execution | slashcommand, skill, skill_mcp | Command and skill-based extensibility |
| Commands | slashcommand | Execute slash commands |
| Skills | skill, skill_mcp | Load skills, invoke skill-embedded MCPs |
| Agents | call_omo_agent | Spawn explore/librarian |
## HOW TO ADD A TOOL ## HOW TO ADD A TOOL
1. Create directory `src/tools/my-tool/`.
1. Create directory: `src/tools/my-tool/` 2. Implement `tools.ts` (factory), `types.ts`, and `constants.ts`.
2. Create files: 3. Export via `index.ts` and register in `src/tools/index.ts`.
- `constants.ts`: `TOOL_NAME`, `TOOL_DESCRIPTION`
- `types.ts`: Parameter/result interfaces
- `tools.ts`: Tool implementation (returns OpenCode tool object)
- `index.ts`: Barrel export
- `utils.ts`: Helpers (optional)
3. Add to `builtinTools` in `src/tools/index.ts`
## LSP SPECIFICS ## LSP SPECIFICS
- **Lifecycle**: Lazy initialization on first call; auto-shutdown on idle.
- **Client lifecycle**: Lazy init on first use, auto-shutdown on idle - **Config**: Merges `opencode.json` and `oh-my-opencode.json`.
- **Config priority**: opencode.json > oh-my-opencode.json > defaults - **Capability**: Supports full LSP spec including `codeAction/resolve` and `prepareRename`.
- **Supported servers**: typescript-language-server, pylsp, gopls, rust-analyzer, etc.
- **Custom servers**: Add via `lsp` config in oh-my-opencode.json
## AST-GREP SPECIFICS ## AST-GREP SPECIFICS
- **Precision**: Uses tree-sitter for structural matching (avoids regex pitfalls).
- **Binding**: Uses `@ast-grep/napi` for performance; ensure patterns are valid AST nodes.
- **Variables**: Supports `$VAR` and `$$$` meta-variables for capture.
- **Meta-variables**: `$VAR` (single node), `$$$` (multiple nodes) ## ANTI-PATTERNS
- **Languages**: 25 supported (typescript, tsx, python, rust, go, etc.) - **Sync Ops**: Never use synchronous file I/O; blocking the main thread kills responsiveness.
- **Binding**: Prefers @ast-grep/napi (native), falls back to @ast-grep/cli - **No Timeouts**: Always wrap external CLI/LSP calls in timeouts (default 60s).
- **Pattern must be valid AST**: `export async function $NAME($$$) { $$$ }` not fragments - **Direct Subprocess**: Avoid raw `spawn` for ast-grep; use NAPI binding.
- **Manual Pathing**: Use `shared/utils` for path normalization across platforms.
## ANTI-PATTERNS (TOOLS)
- **No timeout**: Always use timeout for file operations (default 60s)
- **Blocking main thread**: Use async/await, never sync file ops
- **Ignoring LSP errors**: Gracefully handle server not found/crashed
- **Raw subprocess for ast-grep**: Prefer napi binding for performance