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
**Generated:** 2026-01-09T15:38:00+09:00
**Commit:** 0581793
**Generated:** 2026-01-13T14:45:00+09:00
**Commit:** e47b5514
**Branch:** dev
## OVERVIEW
@ -13,16 +13,16 @@ OpenCode plugin implementing Claude Code/AmpCode features. Multi-model agent orc
```
oh-my-opencode/
├── src/
│ ├── agents/ # AI agents (7): Sisyphus, oracle, librarian, explore, frontend, document-writer, multimodal-looker
│ ├── hooks/ # 22 lifecycle hooks - see src/hooks/AGENTS.md
│ ├── 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
│ ├── tools/ # LSP, AST-Grep, Grep, Glob, session mgmt - see src/tools/AGENTS.md
│ ├── features/ # Claude Code compat layer - see src/features/AGENTS.md
│ ├── auth/ # Google Antigravity OAuth - see src/auth/AGENTS.md
│ ├── shared/ # Cross-cutting utilities - see src/shared/AGENTS.md
│ ├── cli/ # CLI installer, doctor - see src/cli/AGENTS.md
│ ├── mcp/ # MCP configs: context7, grep_app
│ ├── config/ # Zod schema, TypeScript types
│ └── index.ts # Main plugin entry (548 lines)
│ ├── mcp/ # MCP configs: context7, grep_app, websearch
│ ├── config/ # Zod schema (12k lines), TypeScript types
│ └── index.ts # Main plugin entry (563 lines)
├── script/ # build-schema.ts, publish.ts, generate-changelog.ts
├── assets/ # JSON schema
└── dist/ # Build output (ESM + .d.ts)
@ -50,7 +50,7 @@ oh-my-opencode/
| Shared utilities | `src/shared/` | Cross-cutting utilities |
| 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 |
| Orchestrator | `src/hooks/sisyphus-orchestrator/` | Main orchestration hook (660 lines) |
| Orchestrator | `src/hooks/sisyphus-orchestrator/` | Main orchestration hook (677 lines) |
## TDD (Test-Driven Development)
@ -83,7 +83,7 @@ oh-my-opencode/
- **Build**: `bun build` (ESM) + `tsc --emitDeclarationOnly`
- **Exports**: Barrel pattern in index.ts; explicit named exports for tools/hooks
- **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
## ANTI-PATTERNS (THIS PROJECT)
@ -122,13 +122,16 @@ oh-my-opencode/
| 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 |
| librarian | opencode/glm-4.7-free | Multi-repo analysis, docs |
| explore | opencode/grok-code | Fast codebase exploration |
| frontend-ui-ux-engineer | google/gemini-3-pro-preview | UI generation |
| document-writer | google/gemini-3-pro-preview | Technical docs |
| 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
@ -137,7 +140,7 @@ bun run typecheck # Type check
bun run build # ESM + declarations + schema
bun run rebuild # Clean + Build
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
@ -160,23 +163,38 @@ bun test # Run tests (76 test files, 2559+ BDD assertions)
| 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/agents/prometheus-prompt.ts` | 982 | Planning agent system prompt |
| `src/auth/antigravity/fetch.ts` | 798 | Token refresh, URL rewriting |
| `src/auth/antigravity/thinking.ts` | 755 | Thinking block extraction |
| `src/cli/config-manager.ts` | 725 | JSONC parsing, env detection |
| `src/hooks/sisyphus-orchestrator/index.ts` | 660 | Orchestrator hook impl |
| `src/agents/sisyphus.ts` | 641 | Main Sisyphus prompt |
| `src/tools/lsp/client.ts` | 612 | LSP protocol, JSON-RPC |
| `src/features/background-agent/manager.ts` | 608 | Task lifecycle |
| `src/auth/antigravity/response.ts` | 599 | Response transformation, streaming |
| `src/hooks/anthropic-context-window-limit-recovery/executor.ts` | 556 | Multi-stage recovery |
| `src/index.ts` | 548 | Main plugin, all hook/tool init |
| `src/agents/prometheus-prompt.ts` | 988 | Planning agent, interview mode, multi-agent validation |
| `src/auth/antigravity/fetch.ts` | 798 | Token refresh, multi-account rotation, endpoint fallback |
| `src/auth/antigravity/thinking.ts` | 755 | Thinking block extraction, signature management |
| `src/cli/config-manager.ts` | 725 | JSONC parsing, multi-level config, env detection |
| `src/hooks/sisyphus-orchestrator/index.ts` | 677 | Orchestrator hook impl |
| `src/agents/sisyphus.ts` | 643 | Main Sisyphus prompt |
| `src/tools/lsp/client.ts` | 632 | LSP protocol, JSON-RPC |
| `src/features/background-agent/manager.ts` | 825 | Task lifecycle, concurrency |
| `src/auth/antigravity/response.ts` | 598 | Response transformation, streaming |
| `src/tools/sisyphus-task/tools.ts` | 583 | Category-based task delegation |
| `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
- **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
- **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)

View File

@ -1,25 +1,23 @@
# AGENTS KNOWLEDGE BASE
## OVERVIEW
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.
AI agent definitions for multi-model orchestration, delegating tasks to specialized experts.
## STRUCTURE
```
agents/
├── orchestrator-sisyphus.ts # Orchestrator agent (1484 lines) - complex delegation
├── sisyphus.ts # Main Sisyphus prompt (641 lines)
├── orchestrator-sisyphus.ts # Orchestrator agent (1486 lines) - 7-section delegation, wisdom
├── sisyphus.ts # Main Sisyphus prompt (643 lines)
├── sisyphus-junior.ts # Junior variant for delegated tasks
├── 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)
├── frontend-ui-ux-engineer.ts # UI generation (Gemini 3 Pro)
├── document-writer.ts # Technical docs (Gemini 3 Pro)
├── multimodal-looker.ts # PDF/image analysis (Gemini 3 Flash)
├── prometheus-prompt.ts # Planning agent prompt (982 lines)
├── metis.ts # Plan Consultant agent (404 lines)
├── momus.ts # Plan Reviewer agent (404 lines)
├── prometheus-prompt.ts # Planning agent prompt (988 lines) - interview mode
├── metis.ts # Plan Consultant agent - pre-planning analysis
├── momus.ts # Plan Reviewer agent - plan validation
├── build-prompt.ts # Shared build agent prompt
├── plan-prompt.ts # Shared plan agent prompt
├── types.ts # AgentModelConfig interface
@ -28,69 +26,35 @@ agents/
```
## AGENT MODELS
| Agent | Default Model | Fallback | Purpose |
|-------|---------------|----------|---------|
| Sisyphus | anthropic/claude-opus-4-5 | - | Primary orchestrator with extended thinking |
| oracle | openai/gpt-5.2 | - | Read-only consultation. High-IQ debugging, architecture |
| librarian | opencode/glm-4.7-free | - | Docs, OSS research, GitHub examples |
| explore | opencode/grok-code | google/gemini-3-flash, anthropic/claude-haiku-4-5 | Fast contextual grep |
| frontend-ui-ux-engineer | google/gemini-3-pro-preview | - | UI/UX code generation |
| document-writer | google/gemini-3-pro-preview | - | Technical writing |
| multimodal-looker | google/gemini-3-flash | - | PDF/image analysis |
| Agent | Default Model | Purpose |
|-------|---------------|---------|
| Sisyphus | claude-opus-4-5 | Primary orchestrator. 32k extended thinking budget. |
| oracle | openai/gpt-5.2 | High-IQ debugging, architecture, strategic consultation. |
| librarian | glm-4.7-free | Multi-repo analysis, docs research, GitHub examples. |
| explore | grok-code | Fast contextual grep. Fallbacks: Gemini-3-Flash, Haiku-4-5. |
| frontend-ui-ux | gemini-3-pro | Production-grade UI/UX generation and styling. |
| document-writer | gemini-3-pro | Technical writing, guides, API documentation. |
| Prometheus | claude-opus-4-5 | Strategic planner. Interview mode, orchestrates Metis/Momus. |
| 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
1. Create `src/agents/my-agent.ts`:
```typescript
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 |
1. Create `src/agents/my-agent.ts` exporting `AgentConfig`.
2. Add to `builtinAgents` in `src/agents/index.ts`.
3. Update `types.ts` if adding new config interfaces.
## 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:
1. Check user config override (`agents.{name}.model`)
2. Check installer settings (claude max20, gemini antigravity)
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
## ANTI-PATTERNS
- **Trusting reports**: NEVER trust subagent self-reports; always verify outputs.
- **High temp**: Don't use >0.3 for code agents (Sisyphus/Prometheus use 0.1).
- **Sequential calls**: Prefer `sisyphus_task` with `run_in_background` for parallelism.
## SHARED PROMPTS
- **build-prompt.ts**: Base prompt for build agents (OpenCode default + Sisyphus variants)
- **plan-prompt.ts**: Base prompt for plan agents (legacy)
- **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.
- **build-prompt.ts**: Unified base for Sisyphus and Builder variants.
- **plan-prompt.ts**: Core planning logic shared across planning agents.
- **orchestrator-sisyphus.ts**: Uses a 7-section prompt structure and "wisdom notepad" to preserve learnings across turns.

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,85 +1,60 @@
# TOOLS KNOWLEDGE BASE
## OVERVIEW
Custom tools extending agent capabilities: LSP integration (11 tools), AST-aware code search/replace, file operations with timeouts, background task management.
Custom tools extending agent capabilities: LSP (11 tools), AST-aware search/replace, background tasks, and multimodal analysis.
## STRUCTURE
```
tools/
├── ast-grep/ # AST-aware code search/replace (25 languages)
│ ├── cli.ts # @ast-grep/cli subprocess
│ ├── napi.ts # @ast-grep/napi native binding (preferred)
│ ├── constants.ts, types.ts, tools.ts, utils.ts
├── ast-grep/ # AST-aware search/replace (25 languages)
│ ├── cli.ts # @ast-grep/cli fallback
│ └── napi.ts # @ast-grep/napi native binding (preferred)
├── background-task/ # Async agent task management
├── call-omo-agent/ # Spawn explore/librarian agents
├── glob/ # File pattern matching (timeout-safe)
├── grep/ # Content search (timeout-safe)
├── interactive-bash/ # Tmux session management
├── look-at/ # Multimodal analysis (PDF, images)
├── lsp/ # 11 LSP tools
│ ├── client.ts # LSP connection lifecycle (612 lines)
│ ├── utils.ts # LSP utilities (461 lines)
│ ├── config.ts # Server configurations
│ ├── tools.ts # Tool implementations (405 lines)
│ └── types.ts
├── session-manager/ # OpenCode session file management
│ ├── 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
├── lsp/ # IDE-like code intelligence
│ ├── client.ts # LSP connection lifecycle (632 lines)
│ ├── tools.ts # Tool implementations
│ └── config.ts, types.ts, utils.ts
├── session-manager/ # OpenCode session history management
├── sisyphus-task/ # Category-based delegation (583 lines)
├── skill/ # Skill loading/execution
├── skill-mcp/ # Skill-embedded MCP invocation
├── slashcommand/ # Slash command execution
└── index.ts # builtinTools export
└── index.ts # builtinTools export (82 lines)
```
## TOOL CATEGORIES
| 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 |
| AST | ast_grep_search, ast_grep_replace | Pattern-based code search/replace |
| File Search | grep, glob | Content and file pattern matching |
| Session | session_list, session_read, session_search, session_info | OpenCode session file management |
| Background | sisyphus_task, background_output, background_cancel | Async agent orchestration |
| Multimodal | look_at | PDF/image analysis via Gemini |
| Terminal | interactive_bash | Tmux session control |
| Commands | slashcommand | Execute slash commands |
| Skills | skill, skill_mcp | Load skills, invoke skill-embedded MCPs |
| Agents | call_omo_agent | Spawn explore/librarian |
| 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 | Structural pattern matching/rewriting |
| Search | grep, glob | Timeout-safe file and content search |
| Session | session_list, session_read, session_search, session_info | History navigation and retrieval |
| Background | sisyphus_task, background_output, background_cancel | Parallel agent orchestration |
| UI/Terminal | look_at, interactive_bash | Visual analysis and tmux control |
| Execution | slashcommand, skill, skill_mcp | Command and skill-based extensibility |
## HOW TO ADD A TOOL
1. Create directory: `src/tools/my-tool/`
2. Create files:
- `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`
1. Create directory `src/tools/my-tool/`.
2. Implement `tools.ts` (factory), `types.ts`, and `constants.ts`.
3. Export via `index.ts` and register in `src/tools/index.ts`.
## LSP SPECIFICS
- **Client lifecycle**: Lazy init on first use, auto-shutdown on idle
- **Config priority**: opencode.json > oh-my-opencode.json > defaults
- **Supported servers**: typescript-language-server, pylsp, gopls, rust-analyzer, etc.
- **Custom servers**: Add via `lsp` config in oh-my-opencode.json
- **Lifecycle**: Lazy initialization on first call; auto-shutdown on idle.
- **Config**: Merges `opencode.json` and `oh-my-opencode.json`.
- **Capability**: Supports full LSP spec including `codeAction/resolve` and `prepareRename`.
## 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)
- **Languages**: 25 supported (typescript, tsx, python, rust, go, etc.)
- **Binding**: Prefers @ast-grep/napi (native), falls back to @ast-grep/cli
- **Pattern must be valid AST**: `export async function $NAME($$$) { $$$ }` not fragments
## 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
## ANTI-PATTERNS
- **Sync Ops**: Never use synchronous file I/O; blocking the main thread kills responsiveness.
- **No Timeouts**: Always wrap external CLI/LSP calls in timeouts (default 60s).
- **Direct Subprocess**: Avoid raw `spawn` for ast-grep; use NAPI binding.
- **Manual Pathing**: Use `shared/utils` for path normalization across platforms.