diff --git a/AGENTS.md b/AGENTS.md index 50ac5f758..f31141989 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,29 +1,29 @@ # PROJECT KNOWLEDGE BASE -**Generated:** 2026-01-17T19:00:25+09:00 -**Commit:** 987ae468 +**Generated:** 2026-01-17T21:55:00+09:00 +**Commit:** 255f535a **Branch:** dev ## OVERVIEW -OpenCode plugin implementing Claude Code/AmpCode features. Multi-model agent orchestration (GPT-5.2, Claude, Gemini, Grok), LSP tools (11), AST-Grep search, MCP integrations (context7, websearch_exa, grep_app). "oh-my-zsh" for OpenCode. +OpenCode plugin implementing multi-model agent orchestration (Claude Opus 4.5, GPT-5.2, Gemini 3, Grok, GLM-4.7). 31 lifecycle hooks, 20+ tools (LSP, AST-Grep, delegation), 10 specialized agents, Claude Code compatibility layer. "oh-my-zsh" for OpenCode. ## STRUCTURE ``` oh-my-opencode/ ├── src/ -│ ├── agents/ # AI agents (10+): 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 -│ ├── shared/ # Cross-cutting utilities - see src/shared/AGENTS.md -│ ├── cli/ # CLI installer, doctor - see src/cli/AGENTS.md -│ ├── mcp/ # MCP configs: context7, grep_app, websearch +│ ├── agents/ # 10 AI agents (Sisyphus, oracle, librarian, explore, frontend, etc.) - see src/agents/AGENTS.md +│ ├── hooks/ # 31 lifecycle hooks (PreToolUse, PostToolUse, Stop, etc.) - see src/hooks/AGENTS.md +│ ├── tools/ # 20+ tools (LSP, AST-Grep, delegation, session) - see src/tools/AGENTS.md +│ ├── features/ # Background agents, Claude Code compat layer - see src/features/AGENTS.md +│ ├── shared/ # 43 cross-cutting utilities - see src/shared/AGENTS.md +│ ├── cli/ # CLI installer, doctor, run - see src/cli/AGENTS.md +│ ├── mcp/ # Built-in MCPs: websearch, context7, grep_app │ ├── config/ # Zod schema, TypeScript types │ └── index.ts # Main plugin entry (568 lines) -├── script/ # build-schema.ts, publish.ts, generate-changelog.ts -├── assets/ # JSON schema +├── script/ # build-schema.ts, publish.ts, build-binaries.ts +├── packages/ # 7 platform-specific binaries └── dist/ # Build output (ESM + .d.ts) ``` @@ -31,46 +31,34 @@ oh-my-opencode/ | Task | Location | Notes | |------|----------|-------| -| Add agent | `src/agents/` | Create .ts, add to builtinAgents in index.ts, update types.ts | -| Add hook | `src/hooks/` | Create dir with createXXXHook(), export from index.ts | -| Add tool | `src/tools/` | Dir with index/types/constants/tools.ts, add to builtinTools | -| Add MCP | `src/mcp/` | Create config, add to index.ts and types.ts | -| Add skill | `src/features/builtin-skills/` | Create skill dir with SKILL.md | +| Add agent | `src/agents/` | Create .ts with factory, add to `builtinAgents` in index.ts | +| Add hook | `src/hooks/` | Create dir with `createXXXHook()`, register in index.ts | +| Add tool | `src/tools/` | Dir with index/types/constants/tools.ts, add to `builtinTools` | +| Add MCP | `src/mcp/` | Create config, add to index.ts | +| Add skill | `src/features/builtin-skills/` | Create dir with SKILL.md | | LSP behavior | `src/tools/lsp/` | client.ts (connection), tools.ts (handlers) | | AST-Grep | `src/tools/ast-grep/` | napi.ts for @ast-grep/napi binding | | Config schema | `src/config/schema.ts` | Zod schema, run `bun run build:schema` after changes | | Claude Code compat | `src/features/claude-code-*-loader/` | Command, skill, agent, mcp loaders | -| Background agents | `src/features/background-agent/` | manager.ts for task management | +| Background agents | `src/features/background-agent/` | manager.ts (1165 lines) for task lifecycle | | Skill MCP | `src/features/skill-mcp-manager/` | MCP servers embedded in skills | -| Interactive terminal | `src/tools/interactive-bash/` | tmux session management | -| CLI installer | `src/cli/install.ts` | Interactive TUI installation | -| Doctor checks | `src/cli/doctor/checks/` | Health checks for environment | -| 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 | +| CLI installer | `src/cli/install.ts` | Interactive TUI (462 lines) | +| Doctor checks | `src/cli/doctor/checks/` | 14 health checks across 6 categories | | Orchestrator | `src/hooks/sisyphus-orchestrator/` | Main orchestration hook (771 lines) | ## TDD (Test-Driven Development) **MANDATORY for new features and bug fixes.** Follow RED-GREEN-REFACTOR: -``` -1. RED - Write failing test first (test MUST fail) -2. GREEN - Write MINIMAL code to pass (nothing more) -3. REFACTOR - Clean up while tests stay GREEN -4. REPEAT - Next test case -``` - | Phase | Action | Verification | |-------|--------|--------------| -| **RED** | Write test describing expected behavior | `bun test` -> FAIL (expected) | -| **GREEN** | Implement minimum code to pass | `bun test` -> PASS | -| **REFACTOR** | Improve code quality, remove duplication | `bun test` -> PASS (must stay green) | +| **RED** | Write test describing expected behavior | `bun test` → FAIL (expected) | +| **GREEN** | Implement minimum code to pass | `bun test` → PASS | +| **REFACTOR** | Improve code quality, remove duplication | `bun test` → PASS (must stay green) | **Rules:** - NEVER write implementation before test - NEVER delete failing tests to "pass" - fix the code -- One test at a time - don't batch - Test file naming: `*.test.ts` alongside source - BDD comments: `#given`, `#when`, `#then` (same as AAA) @@ -79,40 +67,37 @@ oh-my-opencode/ - **Package manager**: Bun only (`bun run`, `bun build`, `bunx`) - **Types**: bun-types (not @types/node) - **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), 80+ test files +- **Exports**: Barrel pattern in index.ts; explicit named exports +- **Naming**: kebab-case directories, `createXXXHook`/`createXXXTool` factories +- **Testing**: BDD comments `#given/#when/#then`, 84 test files - **Temperature**: 0.1 for code agents, max 0.3 ## ANTI-PATTERNS (THIS PROJECT) -- **npm/yarn**: Use bun exclusively -- **@types/node**: Use bun-types -- **Bash file ops**: Never mkdir/touch/rm/cp/mv for file creation in code -- **Direct bun publish**: GitHub Actions workflow_dispatch only (OIDC provenance) -- **Local version bump**: Version managed by CI workflow -- **Year 2024**: NEVER use 2024 in code/prompts (use current year) -- **Rush completion**: Never mark tasks complete without verification -- **Over-exploration**: Stop searching when sufficient context found -- **High temperature**: Don't use >0.3 for code-related agents -- **Broad tool access**: Prefer explicit `include` over unrestricted access -- **Sequential agent calls**: Use `delegate_task` for parallel execution -- **Heavy PreToolUse logic**: Slows every tool call -- **Self-planning for complex tasks**: Spawn planning agent (Prometheus) instead -- **Trust agent self-reports**: ALWAYS verify results independently -- **Skip TODO creation**: Multi-step tasks MUST have todos first -- **Batch completions**: Mark TODOs complete immediately, don't group -- **Giant commits**: 3+ files = 2+ commits minimum -- **Separate test from impl**: Same commit always +| Category | Forbidden | +|----------|-----------| +| **Package Manager** | npm, yarn - use Bun exclusively | +| **Types** | @types/node - use bun-types | +| **File Ops** | mkdir/touch/rm/cp/mv in code - agents use bash tool | +| **Publishing** | Direct `bun publish` - use GitHub Actions workflow_dispatch | +| **Versioning** | Local version bump - managed by CI | +| **Date References** | Year 2024 - use current year | +| **Type Safety** | `as any`, `@ts-ignore`, `@ts-expect-error` | +| **Error Handling** | Empty catch blocks `catch(e) {}` | +| **Testing** | Deleting failing tests to "pass" | +| **Agent Calls** | Sequential agent calls - use `delegate_task` for parallel | +| **Tool Access** | Broad tool access - prefer explicit `include` | +| **Hook Logic** | Heavy PreToolUse computation - slows every tool call | +| **Commits** | Giant commits (3+ files = 2+ commits), separate test from impl | +| **Temperature** | >0.3 for code agents | +| **Trust** | Trust agent self-reports - ALWAYS verify independently | ## UNIQUE STYLES - **Platform**: Union type `"darwin" | "linux" | "win32" | "unsupported"` - **Optional props**: Extensive `?` for optional interface properties - **Flexible objects**: `Record` for dynamic configs -- **Error handling**: Consistent try/catch with async/await - **Agent tools**: `tools: { include: [...] }` or `tools: { exclude: [...] }` -- **Temperature**: Most agents use `0.1` for consistency - **Hook naming**: `createXXXHook` function convention - **Factory pattern**: Components created via `createXXX()` functions @@ -121,13 +106,13 @@ oh-my-opencode/ | Agent | Default Model | 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 | 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 | +| oracle | openai/gpt-5.2 | Read-only consultation, high-IQ debugging | +| librarian | opencode/glm-4.7-free | Multi-repo analysis, docs, GitHub search | +| explore | opencode/grok-code | Fast codebase exploration (contextual grep) | +| frontend-ui-ux-engineer | google/gemini-3-pro-preview | UI generation, visual design | +| document-writer | google/gemini-3-flash | Technical documentation | | multimodal-looker | google/gemini-3-flash | PDF/image analysis | -| Prometheus (Planner) | anthropic/claude-opus-4-5 | Strategic planning, interview-driven | +| Prometheus (Planner) | anthropic/claude-opus-4-5 | Strategic planning, interview mode | | Metis (Plan Consultant) | anthropic/claude-sonnet-4-5 | Pre-planning analysis | | Momus (Plan Reviewer) | anthropic/claude-sonnet-4-5 | Plan validation | @@ -138,7 +123,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 (80+ test files, 2500+ BDD assertions) +bun test # Run tests (84 test files) ``` ## DEPLOYMENT @@ -153,24 +138,23 @@ bun test # Run tests (80+ test files, 2500+ BDD assertions) ## CI PIPELINE -- **ci.yml**: Parallel test/typecheck, build verification, auto-commit schema on master, rolling `next` draft release -- **publish.yml**: Manual workflow_dispatch, version bump, changelog, OIDC npm publish +- **ci.yml**: Parallel test/typecheck → build → auto-commit schema on master → rolling `next` draft release +- **publish.yml**: Manual workflow_dispatch → version bump → changelog → 8-package OIDC npm publish → force-push master ## COMPLEXITY HOTSPOTS | File | Lines | Description | |------|-------|-------------| -| `src/agents/orchestrator-sisyphus.ts` | 1531 | Orchestrator agent, 7-section delegation, accumulated wisdom | -| `src/features/builtin-skills/skills.ts` | 1203 | Skill definitions (frontend-ui-ux, playwright) | -| `src/agents/prometheus-prompt.ts` | 1196 | Planning agent, interview mode, multi-agent validation | -| `src/features/background-agent/manager.ts` | 1165 | Task lifecycle, concurrency | -| `src/hooks/sisyphus-orchestrator/index.ts` | 771 | Orchestrator hook impl | -| `src/tools/delegate-task/tools.ts` | 770 | Category-based task delegation | -| `src/cli/config-manager.ts` | 730 | JSONC parsing, multi-level config, env detection | +| `src/agents/orchestrator-sisyphus.ts` | 1531 | Orchestrator agent, 7-section delegation, wisdom accumulation | +| `src/features/builtin-skills/skills.ts` | 1203 | Skill definitions (playwright, git-master, frontend-ui-ux) | +| `src/agents/prometheus-prompt.ts` | 1196 | Planning agent, interview mode, Momus loop | +| `src/features/background-agent/manager.ts` | 1165 | Task lifecycle, concurrency, notification batching | +| `src/hooks/sisyphus-orchestrator/index.ts` | 771 | Orchestrator hook implementation | +| `src/tools/delegate-task/tools.ts` | 761 | Category-based task delegation | +| `src/cli/config-manager.ts` | 730 | JSONC parsing, multi-level config | | `src/agents/sisyphus.ts` | 640 | Main Sisyphus prompt | | `src/features/builtin-commands/templates/refactor.ts` | 619 | Refactoring command template | | `src/tools/lsp/client.ts` | 596 | LSP protocol, JSON-RPC | -| `src/index.ts` | 568 | Main plugin, all hook/tool init | ## MCP ARCHITECTURE @@ -183,16 +167,15 @@ Three-tier MCP system: - **Zod validation**: `src/config/schema.ts` - **JSONC support**: Comments and trailing commas -- **Multi-level**: User (`~/.config/opencode/`) → Project (`.opencode/`) +- **Multi-level**: Project (`.opencode/`) → User (`~/.config/opencode/`) - **CLI doctor**: Validates config and reports errors ## NOTES -- **Testing**: Bun native test (`bun test`), BDD-style `#given/#when/#then`, 80+ test files +- **Testing**: Bun native test (`bun test`), BDD-style, 84 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) - **Trusted deps**: @ast-grep/cli, @ast-grep/napi, @code-yeongyu/comment-checker -- **JSONC support**: Config files support comments (`// comment`, `/* block */`) and trailing commas - **Claude Code Compat**: Full compatibility layer for settings.json hooks, commands, skills, agents, MCPs -- **Skill MCP**: Skills can embed MCP server configs in YAML frontmatter +- **Flaky tests**: 2 known flaky tests (ralph-loop CI timeout, session-state parallel pollution) diff --git a/src/agents/AGENTS.md b/src/agents/AGENTS.md index f7b56cf3c..93b7c0bc7 100644 --- a/src/agents/AGENTS.md +++ b/src/agents/AGENTS.md @@ -1,50 +1,71 @@ # AGENTS KNOWLEDGE BASE ## OVERVIEW -AI agent definitions for multi-model orchestration, delegating tasks to specialized experts. + +10 AI agents for multi-model orchestration. Sisyphus (primary), oracle, librarian, explore, frontend, document-writer, multimodal-looker, Prometheus, Metis, Momus. ## STRUCTURE + ``` agents/ -├── orchestrator-sisyphus.ts # Orchestrator agent (1531 lines) - 7-section delegation, wisdom -├── sisyphus.ts # Main Sisyphus prompt (640 lines) -├── sisyphus-junior.ts # Junior variant for delegated tasks -├── oracle.ts # Strategic advisor (GPT-5.2) -├── 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 Preview) -├── document-writer.ts # Technical docs (Gemini 3 Pro Preview) -├── multimodal-looker.ts # PDF/image analysis (Gemini 3 Flash) -├── prometheus-prompt.ts # Planning agent prompt (1196 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 -├── sisyphus-prompt-builder.ts # Factory for orchestrator prompts -├── types.ts # AgentModelConfig interface -├── utils.ts # createBuiltinAgents(), getAgentName() -└── index.ts # builtinAgents export +├── orchestrator-sisyphus.ts # Orchestrator (1531 lines) - 7-phase delegation +├── sisyphus.ts # Main prompt (640 lines) +├── sisyphus-junior.ts # Delegated task executor +├── sisyphus-prompt-builder.ts # Dynamic prompt generation +├── oracle.ts # Strategic advisor (GPT-5.2) +├── librarian.ts # Multi-repo research (GLM-4.7-free) +├── explore.ts # Fast grep (Grok Code) +├── frontend-ui-ux-engineer.ts # UI specialist (Gemini 3 Pro) +├── document-writer.ts # Technical writer (Gemini 3 Flash) +├── multimodal-looker.ts # Media analyzer (Gemini 3 Flash) +├── prometheus-prompt.ts # Planning (1196 lines) - interview mode +├── metis.ts # Plan consultant - pre-planning analysis +├── momus.ts # Plan reviewer - validation +├── types.ts # AgentModelConfig interface +├── utils.ts # createBuiltinAgents(), getAgentName() +└── index.ts # builtinAgents export ``` -## HOW TO ADD AN AGENT -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. +## AGENT MODELS -## 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`. +| Agent | Model | Temperature | Purpose | +|-------|-------|-------------|---------| +| Sisyphus | anthropic/claude-opus-4-5 | 0.1 | Primary orchestrator, todo-driven | +| oracle | openai/gpt-5.2 | 0.1 | Read-only consultation, debugging | +| librarian | opencode/glm-4.7-free | 0.1 | Docs, GitHub search, OSS examples | +| explore | opencode/grok-code | 0.1 | Fast contextual grep | +| frontend-ui-ux-engineer | google/gemini-3-pro-preview | 0.7 | UI generation, visual design | +| document-writer | google/gemini-3-flash | 0.3 | Technical documentation | +| multimodal-looker | google/gemini-3-flash | 0.1 | PDF/image analysis | +| Prometheus | anthropic/claude-opus-4-5 | 0.1 | Strategic planning, interview mode | +| Metis | anthropic/claude-sonnet-4-5 | 0.1 | Pre-planning gap analysis | +| Momus | anthropic/claude-sonnet-4-5 | 0.1 | Plan validation | -## SHARED PROMPTS -- **7-Section Delegation**: `orchestrator-sisyphus.ts` uses strict phases (0-6) for classification, research, planning, validation. -- **Wisdom Notepad**: Persistent scratchpad preserving project-specific learnings across turns. -- **Interview Mode**: `Prometheus` defaults to conversational consultant mode for requirement extraction. -- **build-prompt.ts**: Unified base for Sisyphus and Builder variants. -- **plan-prompt.ts**: Core planning logic shared across planning agents. +## HOW TO ADD + +1. Create `src/agents/my-agent.ts` exporting `AgentConfig` +2. Add to `builtinAgents` in `src/agents/index.ts` +3. Update `AgentNameSchema` in `src/config/schema.ts` +4. Register in `src/index.ts` initialization + +## TOOL RESTRICTIONS + +| Agent | Denied Tools | +|-------|-------------| +| oracle | write, edit, task, delegate_task | +| librarian | write, edit, task, delegate_task, call_omo_agent | +| explore | write, edit, task, delegate_task, call_omo_agent | +| multimodal-looker | Allowlist: read, glob, grep | + +## KEY PATTERNS + +- **Factory**: `createXXXAgent(model?: string): AgentConfig` +- **Metadata**: `XXX_PROMPT_METADATA: AgentPromptMetadata` +- **Tool restrictions**: `permission: { edit: "deny", bash: "ask" }` +- **Thinking**: 32k budget tokens for Sisyphus, Oracle, Prometheus ## 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 `delegate_task` with `run_in_background` for parallelism. + +- **Trust reports**: NEVER trust subagent "I'm done" - verify outputs +- **High temp**: Don't use >0.3 for code agents +- **Sequential calls**: Use `delegate_task` with `run_in_background` diff --git a/src/cli/AGENTS.md b/src/cli/AGENTS.md index 88ae9b7a6..cd1096a3c 100644 --- a/src/cli/AGENTS.md +++ b/src/cli/AGENTS.md @@ -1,57 +1,91 @@ # CLI KNOWLEDGE BASE ## OVERVIEW -CLI for oh-my-opencode: interactive installer, health diagnostics (doctor), runtime launcher. Entry: `bunx oh-my-opencode`. + +CLI entry point: `bunx oh-my-opencode`. Interactive installer, doctor diagnostics, session runner. Uses Commander.js + @clack/prompts TUI. ## STRUCTURE + ``` cli/ -├── index.ts # Commander.js entry, subcommand routing +├── index.ts # Commander.js entry, 5 subcommands ├── install.ts # Interactive TUI installer (462 lines) -├── config-manager.ts # JSONC parsing, env detection (730 lines) -├── types.ts # CLI-specific types -├── doctor/ # Health check system +├── config-manager.ts # JSONC parsing, multi-level merge (730 lines) +├── types.ts # InstallArgs, InstallConfig, DetectedConfig +├── doctor/ │ ├── index.ts # Doctor command entry -│ ├── runner.ts # Health check orchestration -│ ├── constants.ts # Check categories -│ ├── types.ts # Check result interfaces -│ └── checks/ # 10 check modules (14 individual checks) -├── get-local-version/ # Version detection -└── run/ # OpenCode session launcher - ├── completion.ts # Completion logic - └── events.ts # Event handling +│ ├── runner.ts # Check orchestration +│ ├── formatter.ts # Colored output, symbols +│ ├── constants.ts # Check IDs, categories, symbols +│ ├── types.ts # CheckResult, CheckDefinition +│ └── checks/ # 14 checks across 6 categories +│ ├── version.ts # OpenCode + plugin version +│ ├── config.ts # JSONC validity, Zod validation +│ ├── auth.ts # Anthropic, OpenAI, Google +│ ├── dependencies.ts # AST-Grep, Comment Checker +│ ├── lsp.ts # LSP server connectivity +│ ├── mcp.ts # MCP server validation +│ └── gh.ts # GitHub CLI availability +├── run/ +│ ├── index.ts # Run command entry +│ └── runner.ts # Session launcher +└── get-local-version/ + ├── index.ts # Version detection + └── formatter.ts # Version output ``` ## CLI COMMANDS + | Command | Purpose | |---------|---------| -| `install` | Interactive setup wizard with subscription detection | -| `doctor` | Environment health checks (LSP, Auth, Config, Deps) | -| `run` | Launch OpenCode session with todo/background completion enforcement | -| `get-local-version` | Detect and return local plugin version & update status | +| `install` | Interactive setup, subscription detection | +| `doctor` | 14 health checks, `--verbose`, `--json`, `--category` | +| `run` | Launch OpenCode session with completion enforcement | +| `get-local-version` | Version detection, update checking | -## DOCTOR CHECKS -14 checks in `doctor/checks/`: -- `version.ts`: OpenCode >= 1.0.150 & plugin update status -- `config.ts`: Plugin registration & JSONC validity -- `dependencies.ts`: AST-Grep (CLI/NAPI), Comment Checker -- `auth.ts`: Anthropic, OpenAI, Google (Antigravity) -- `lsp.ts`, `mcp.ts`: Tool connectivity checks -- `gh.ts`: GitHub CLI availability +## DOCTOR CHECK CATEGORIES -## 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 +| Category | Checks | +|----------|--------| +| installation | opencode, plugin registration | +| configuration | config validity, Zod validation | +| authentication | anthropic, openai, google | +| dependencies | ast-grep CLI/NAPI, comment-checker | +| tools | LSP, MCP connectivity | +| updates | version comparison | ## HOW TO ADD CHECK -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) + +1. Create `src/cli/doctor/checks/my-check.ts`: + ```typescript + export function getMyCheckDefinition(): CheckDefinition { + return { + id: "my-check", + name: "My Check", + category: "configuration", + check: async () => ({ status: "pass", message: "OK" }) + } + } + ``` +2. Export from `checks/index.ts` +3. Add to `getAllCheckDefinitions()` + +## TUI FRAMEWORK + +- **@clack/prompts**: `select()`, `spinner()`, `intro()`, `outro()`, `note()` +- **picocolors**: Colored terminal output +- **Symbols**: ✓ (pass), ✗ (fail), ⚠ (warn), ○ (skip) + +## CONFIG-MANAGER + +- **JSONC**: Comments (`// ...`), block comments, trailing commas +- **Multi-source**: User (`~/.config/opencode/`) + Project (`.opencode/`) +- **Env override**: `OPENCODE_CONFIG_DIR` for profile isolation +- **Validation**: Zod schema with error aggregation ## ANTI-PATTERNS -- Blocking prompts in non-TTY (check `process.stdout.isTTY`) -- Direct `JSON.parse` (breaks JSONC compatibility) -- Silent failures (always return `warn` or `fail` in `doctor`) -- Environment-specific hardcoding (use `ConfigManager`) + +- **Blocking in non-TTY**: Check `process.stdout.isTTY` +- **Direct JSON.parse**: Use `parseJsonc()` for config +- **Silent failures**: Always return warn/fail in doctor +- **Hardcoded paths**: Use `ConfigManager` diff --git a/src/features/AGENTS.md b/src/features/AGENTS.md index ab1069376..2d7abe141 100644 --- a/src/features/AGENTS.md +++ b/src/features/AGENTS.md @@ -1,39 +1,62 @@ # FEATURES KNOWLEDGE BASE ## OVERVIEW -Claude Code compatibility layer + core feature modules. Commands, skills, agents, MCPs, hooks from Claude Code work seamlessly. + +Core feature modules + Claude Code compatibility layer. Background agents, skill MCP, builtin skills/commands, and 5 loaders for Claude Code compat. ## STRUCTURE + ``` features/ -├── background-agent/ # Task lifecycle, notifications (1165 lines manager.ts) -├── boulder-state/ # Boulder/Todo state persistence -├── builtin-commands/ # Built-in slash commands (ralph-loop, refactor, init-deep) -├── builtin-skills/ # Built-in skills (1203 lines skills.ts) -│ ├── git-master/ # Atomic commits, history search -│ ├── playwright/ # Browser automation -│ └── frontend-ui-ux/ # Designer-developer skill +├── background-agent/ # Task lifecycle (1165 lines manager.ts) +│ ├── manager.ts # Launch → poll → complete orchestration +│ ├── concurrency.ts # Per-provider/model limits +│ └── types.ts # BackgroundTask, LaunchInput +├── skill-mcp-manager/ # MCP client lifecycle +│ ├── manager.ts # Lazy loading, idle cleanup +│ └── types.ts # SkillMcpConfig, transports +├── builtin-skills/ # Playwright, git-master, frontend-ui-ux +│ └── skills.ts # 1203 lines of skill definitions +├── builtin-commands/ # ralph-loop, refactor, init-deep +│ └── templates/ # Command implementations ├── claude-code-agent-loader/ # ~/.claude/agents/*.md ├── claude-code-command-loader/ # ~/.claude/commands/*.md -├── claude-code-mcp-loader/ # .mcp.json files with ${VAR} expansion +├── claude-code-mcp-loader/ # .mcp.json with ${VAR} expansion ├── claude-code-plugin-loader/ # installed_plugins.json ├── claude-code-session-state/ # Session state persistence -├── context-injector/ # AGENTS.md/README.md/Rules injection -├── opencode-skill-loader/ # Skills from OpenCode + Claude paths -├── skill-mcp-manager/ # MCP servers in skill YAML (stdio/http transports) -├── task-toast-manager/ # Task status toast notifications -└── hook-message-injector/ # Message injection into conversation streams +├── opencode-skill-loader/ # Skills from 6 directories +├── context-injector/ # AGENTS.md/README.md injection +├── boulder-state/ # Todo state persistence +├── task-toast-manager/ # Toast notifications +└── hook-message-injector/ # Message injection ``` ## LOADER PRIORITY -| Loader | Priority (highest first) | -|--------|--------------------------| + +| Type | Priority (highest first) | +|------|--------------------------| | Commands | `.opencode/command/` > `~/.config/opencode/command/` > `.claude/commands/` > `~/.claude/commands/` | | Skills | `.opencode/skill/` > `~/.config/opencode/skill/` > `.claude/skills/` > `~/.claude/skills/` | | Agents | `.claude/agents/` > `~/.claude/agents/` | | MCPs | `.claude/.mcp.json` > `.mcp.json` > `~/.claude/.mcp.json` | +## BACKGROUND AGENT + +- **Lifecycle**: `launch` → `poll` (2s interval) → `complete` +- **Stability**: 3 consecutive polls with same message count = idle +- **Concurrency**: Per-provider/model limits (e.g., max 3 Opus, max 10 Gemini) +- **Notification**: Batched system reminders to parent session +- **Cleanup**: 30m TTL, 3m stale timeout, signal handlers + +## SKILL MCP + +- **Lazy**: Clients created on first tool call +- **Transports**: stdio (local process), http (SSE/Streamable) +- **Environment**: `${VAR}` expansion in config +- **Lifecycle**: 5m idle cleanup, session-scoped + ## CONFIG TOGGLES + ```jsonc { "claude_code": { @@ -46,20 +69,9 @@ features/ } ``` -## BACKGROUND AGENT -- **Lifecycle**: `launch` → `poll` (idle/stability detection) → `complete`. -- **Concurrency**: Per-provider/model limits in `concurrency.ts`. -- **Notification**: Auto-injects system reminders into parent session on task completion. -- **Cleanup**: Shutdown handler cancels pending waiters; idle tasks pruning (30m TTL). - -## SKILL MCP -- **Lazy Loading**: Clients connect on first tool call via `SkillMcpManager`. -- **Transports**: `stdio` (local process) or `http` (SSE/Streamable HTTP). -- **Environment**: `${VAR}` expansion in config via `env-expander.ts`. -- **Lifecycle**: Session-scoped clients; auto-cleanup after 5m idle. - ## ANTI-PATTERNS -- **Sequential Delegation**: Calling agents one-by-one; use `delegate_task` for parallel runs. -- **Self-Report Trust**: Trusting agent's "I'm done" without verifying against session state. -- **Main Thread Blocks**: Heavy I/O or long-running logic during loader initialization. -- **Manual Versioning**: Updating `package.json` version field; managed exclusively by CI. + +- **Sequential delegation**: Use `delegate_task` for parallel +- **Trust self-reports**: ALWAYS verify agent outputs +- **Main thread blocks**: No heavy I/O in loader init +- **Manual versioning**: CI manages package.json version diff --git a/src/hooks/AGENTS.md b/src/hooks/AGENTS.md index dd879882e..f350e7ad6 100644 --- a/src/hooks/AGENTS.md +++ b/src/hooks/AGENTS.md @@ -1,53 +1,73 @@ # HOOKS KNOWLEDGE BASE ## OVERVIEW -22+ lifecycle hooks intercepting/modifying agent behavior via PreToolUse, PostToolUse, UserPromptSubmit, and more. + +31 lifecycle hooks intercepting/modifying agent behavior. Events: PreToolUse, PostToolUse, UserPromptSubmit, Stop, onSummarize. ## STRUCTURE + ``` hooks/ -├── sisyphus-orchestrator/ # Main orchestration & agent delegation (771 lines) -├── anthropic-context-window-limit-recovery/ # Auto-summarize at token limit (14 files) -├── todo-continuation-enforcer.ts # Force completion of [ ] items -├── ralph-loop/ # Self-referential dev loop (7 files) -├── claude-code-hooks/ # settings.json hook compatibility layer (13 files) -├── comment-checker/ # Prevents AI slop/excessive comments (13 files) -├── auto-slash-command/ # Detects and executes /command patterns +├── sisyphus-orchestrator/ # Main orchestration & delegation (771 lines) +├── anthropic-context-window-limit-recovery/ # Auto-summarize at token limit +├── todo-continuation-enforcer.ts # Force TODO completion +├── ralph-loop/ # Self-referential dev loop until done +├── claude-code-hooks/ # settings.json hook compat layer (13 files) +├── comment-checker/ # Prevents AI slop/excessive comments +├── auto-slash-command/ # Detects /command patterns ├── rules-injector/ # Conditional rules from .claude/rules/ -├── 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 +├── directory-agents-injector/ # Auto-injects AGENTS.md files +├── directory-readme-injector/ # Auto-injects README.md files +├── preemptive-compaction/ # Triggers summary at 85% context +├── edit-error-recovery/ # Recovers from tool failures ├── thinking-block-validator/ # Ensures valid format ├── context-window-monitor.ts # Reminds agents of remaining headroom -├── session-recovery/ # Auto-recovers from session crashes -├── think-mode/ # Dynamic thinking budget adjustment +├── session-recovery/ # Auto-recovers from crashes +├── think-mode/ # Dynamic thinking budget +├── keyword-detector/ # ultrawork/search/analyze modes ├── background-notification/ # OS notification on task completion -└── tool-output-truncator.ts # Prevents context bloat from verbose tools +└── tool-output-truncator.ts # Prevents context bloat ``` ## HOOK EVENTS -| 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) | + +| Event | Timing | Can Block | Use Case | +|-------|--------|-----------|----------| +| PreToolUse | Before tool | Yes | Validate/modify inputs, inject context | +| PostToolUse | After tool | No | Append warnings, truncate output | +| UserPromptSubmit | On prompt | Yes | Keyword detection, mode switching | +| Stop | Session idle | No | Auto-continue (todo-continuation, ralph-loop) | +| onSummarize | Compaction | No | Preserve critical state | + +## EXECUTION ORDER + +**chat.message**: keywordDetector → claudeCodeHooks → autoSlashCommand → startWork → ralphLoop + +**tool.execute.before**: claudeCodeHooks → nonInteractiveEnv → commentChecker → directoryAgentsInjector → directoryReadmeInjector → rulesInjector + +**tool.execute.after**: editErrorRecovery → delegateTaskRetry → commentChecker → toolOutputTruncator → emptyTaskResponseDetector → claudeCodeHooks ## HOW TO ADD -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`. + +1. Create `src/hooks/name/` with `index.ts` exporting `createMyHook(ctx)` +2. Implement event handlers: `"tool.execute.before"`, `"tool.execute.after"`, etc. +3. Add hook name to `HookNameSchema` in `src/config/schema.ts` +4. Register in `src/index.ts`: + ```typescript + const myHook = isHookEnabled("my-hook") ? createMyHook(ctx) : null + // Add to event handlers + ``` ## PATTERNS -- **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. + +- **Session-scoped state**: `Map>` for tracking per-session +- **Conditional execution**: Check `input.tool` before processing +- **Output modification**: `output.output += "\n${REMINDER}"` to append context +- **Async state**: Use promises for CLI path resolution, cache results ## ANTI-PATTERNS -- **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. + +- **Blocking non-critical**: Use PostToolUse warnings instead of PreToolUse blocks +- **Heavy computation**: Keep PreToolUse light - slows every tool call +- **Redundant injection**: Track injected files to prevent duplicates +- **Verbose output**: Keep hook messages technical, brief diff --git a/src/shared/AGENTS.md b/src/shared/AGENTS.md index b1614d8ad..7add35f56 100644 --- a/src/shared/AGENTS.md +++ b/src/shared/AGENTS.md @@ -1,52 +1,63 @@ # SHARED UTILITIES KNOWLEDGE BASE ## OVERVIEW -Core cross-cutting utilities for path resolution, token-safe text processing, and Claude Code compatibility. + +43 cross-cutting utilities: path resolution, token truncation, config parsing, Claude Code compatibility. ## STRUCTURE + ``` shared/ -├── logger.ts # Persistent file-based logging (tmpdir/oh-my-opencode.log) +├── logger.ts # File-based logging (tmpdir/oh-my-opencode.log) ├── permission-compat.ts # Agent tool restrictions (ask/allow/deny) -├── dynamic-truncator.ts # Token-aware truncation with context headroom -├── frontmatter.ts # YAML frontmatter parsing with JSON_SCHEMA safety -├── jsonc-parser.ts # JSON with Comments support for config files -├── data-path.ts # XDG-compliant storage paths (~/.local/share) -├── opencode-config-dir.ts # Resolve ~/.config/opencode for CLI/Desktop -├── claude-config-dir.ts # Resolve ~/.claude for compatibility -├── migration.ts # Legacy name mapping (omo -> Sisyphus) -└── opencode-version.ts # Version comparison logic (e.g., >= 1.0.150) +├── dynamic-truncator.ts # Token-aware truncation (50% headroom) +├── frontmatter.ts # YAML frontmatter parsing +├── jsonc-parser.ts # JSON with Comments support +├── data-path.ts # XDG-compliant storage (~/.local/share) +├── opencode-config-dir.ts # ~/.config/opencode resolution +├── claude-config-dir.ts # ~/.claude resolution +├── migration.ts # Legacy config migration (omo → Sisyphus) +├── opencode-version.ts # Version comparison (>= 1.0.150) +├── external-plugin-detector.ts # OAuth spoofing detection +├── env-expander.ts # ${VAR} expansion in configs +├── system-directive.ts # System directive types +├── hook-utils.ts # Hook helper functions +└── *.test.ts # Test files (colocated) ``` ## WHEN TO USE + | Task | Utility | |------|---------| -| Debugging/Auditing | `log(message, data)` in `logger.ts` | -| Limit agent context | `dynamicTruncate(ctx, sessionId, output)` | -| Parse rule meta | `parseFrontmatter(content)` | -| Load user configs | `parseJsonc(text)` or `readJsoncFile(path)` | -| Restrict tools | `createAgentToolAllowlist(tools)` | -| Resolve app paths | `getOpenCodeConfigDir()` or `getClaudeConfigDir()` | -| Update legacy config | `migrateConfigFile(path, rawConfig)` | +| Debug logging | `log(message, data)` in `logger.ts` | +| Limit context | `dynamicTruncate(ctx, sessionId, output)` | +| Parse frontmatter | `parseFrontmatter(content)` | +| Load JSONC config | `parseJsonc(text)` or `readJsoncFile(path)` | +| Restrict agent tools | `createAgentToolAllowlist(tools)` | +| Resolve paths | `getOpenCodeConfigDir()`, `getClaudeConfigDir()` | +| Migrate config | `migrateConfigFile(path, rawConfig)` | +| Compare versions | `isOpenCodeVersionAtLeast("1.1.0")` | + +## KEY PATTERNS -## CRITICAL PATTERNS ```typescript -// Truncate large output based on 50% remaining context window -const { result } = await dynamicTruncate(ctx, sessionID, largeBuffer); +// Token-aware truncation +const { result } = await dynamicTruncate(ctx, sessionID, largeBuffer) -// Safe config loading with comment/trailing comma support -const settings = readJsoncFile(configPath); +// JSONC config loading +const settings = readJsoncFile(configPath) -// Version-gated logic for OpenCode 1.1.0+ -if (isOpenCodeVersionAtLeast("1.1.0")) { /* ... */ } +// Version-gated features +if (isOpenCodeVersionAtLeast("1.1.0")) { /* new feature */ } -// Permission normalization for agent tools -const permissions = migrateToolsToPermission(legacyTools); +// Tool permission normalization +const permissions = migrateToolsToPermission(legacyTools) ``` ## ANTI-PATTERNS -- Raw `JSON.parse` for configs (use `jsonc-parser.ts`) -- Hardcoded `~/.claude` (use `claude-config-dir.ts`) -- `console.log` for background agents (use `logger.ts`) -- Unbounded tool output (always use `dynamic-truncator.ts`) -- Manual version parsing (use `opencode-version.ts`) + +- **Raw JSON.parse**: Use `jsonc-parser.ts` for config files +- **Hardcoded paths**: Use `*-config-dir.ts` utilities +- **console.log**: Use `logger.ts` for background agents +- **Unbounded output**: Always use `dynamic-truncator.ts` +- **Manual version parse**: Use `opencode-version.ts` diff --git a/src/tools/AGENTS.md b/src/tools/AGENTS.md index f9534eb88..03c602e46 100644 --- a/src/tools/AGENTS.md +++ b/src/tools/AGENTS.md @@ -1,50 +1,74 @@ # TOOLS KNOWLEDGE BASE ## OVERVIEW -Core toolset implementing LSP, structural search, and system orchestration. Extends OpenCode with high-performance C++ bindings and multi-agent delegation. + +20+ tools: LSP (11), AST-Grep (2), Search (2), Session (4), Agent delegation (3), System (2). High-performance C++ bindings via @ast-grep/napi. ## STRUCTURE + ``` tools/ ├── [tool-name]/ -│ ├── index.ts # Tool factory entry -│ ├── tools.ts # Business logic & implementation -│ ├── types.ts # Zod schemas & TS types -│ └── constants.ts # Tool-specific fixed values -├── lsp/ # 11 tools via JSON-RPC client (596 lines client.ts) -├── ast-grep/ # Structural search (NAPI bindings) -├── delegate-task/ # Category-based agent routing (770 lines tools.ts) -├── session-manager/ # OpenCode session history (9 files) -└── interactive-bash/ # Tmux session management (5 files) +│ ├── index.ts # Barrel export +│ ├── tools.ts # Business logic, ToolDefinition +│ ├── types.ts # Zod schemas +│ └── constants.ts # Fixed values, descriptions +├── lsp/ # 11 tools: goto_definition, references, symbols, diagnostics, rename +├── ast-grep/ # 2 tools: search, replace (25 languages via NAPI) +├── delegate-task/ # Category-based agent routing (761 lines) +├── session-manager/ # 4 tools: list, read, search, info +├── grep/ # Custom grep with timeout/truncation +├── glob/ # Custom glob with 60s timeout, 100 file limit +├── interactive-bash/ # Tmux session management +├── look-at/ # Multimodal PDF/image analysis +├── skill/ # Skill execution +├── skill-mcp/ # Skill MCP operations +├── slashcommand/ # Slash command dispatch +├── call-omo-agent/ # Direct agent invocation +└── background-task/ # background_output, background_cancel ``` ## TOOL CATEGORIES -| Category | Purpose | Key Implementations | -|----------|---------|---------------------| -| **LSP** | Semantic code intelligence | `lsp_goto_definition`, `lsp_find_references`, `lsp_rename` | -| **Search** | Fast discovery & matching | `glob`, `grep`, `ast_grep_search`, `ast_grep_replace` | -| **System** | CLI & Environment | `bash`, `interactive_bash` (tmux), `look_at` (vision) | -| **Session** | History & Context | `session_read`, `session_search`, `session_select` | -| **Agent** | Task Orchestration | `delegate_task`, `call_omo_agent` | + +| Category | Tools | Purpose | +|----------|-------|---------| +| **LSP** | lsp_goto_definition, lsp_find_references, lsp_symbols, lsp_diagnostics, lsp_prepare_rename, lsp_rename | Semantic code intelligence | +| **Search** | ast_grep_search, ast_grep_replace, grep, glob | Pattern discovery | +| **Session** | session_list, session_read, session_search, session_info | History navigation | +| **Agent** | delegate_task, call_omo_agent, background_output, background_cancel | Task orchestration | +| **System** | interactive_bash, look_at | CLI, multimodal | +| **Skill** | skill, skill_mcp, slashcommand | Skill execution | ## HOW TO ADD -1. **Directory**: Create `src/tools/[name]/` with standard files. -2. **Factory**: Use `tool()` from `@opencode-ai/plugin/tool`. -3. **Parameters**: Define strict Zod schemas in `types.ts`. -4. **Registration**: Export from `src/tools/index.ts` and add to `builtinTools`. + +1. Create `src/tools/[name]/` with standard files +2. Use `tool()` from `@opencode-ai/plugin/tool`: + ```typescript + export const myTool: ToolDefinition = tool({ + description: "...", + args: { param: tool.schema.string() }, + execute: async (args) => { /* ... */ } + }) + ``` +3. Export from `src/tools/index.ts` +4. Add to `builtinTools` object ## LSP SPECIFICS -- **Client**: `lsp/client.ts` manages stdio lifecycle and JSON-RPC. -- **Capabilities**: Supports definition, references, symbols, diagnostics, and workspace-wide rename. -- **Protocol**: Maps standard LSP methods to tool-compatible responses. + +- **Client**: `client.ts` manages stdio lifecycle, JSON-RPC +- **Singleton**: `LSPServerManager` with ref counting +- **Protocol**: Standard LSP methods mapped to tool responses +- **Capabilities**: definition, references, symbols, diagnostics, rename ## AST-GREP SPECIFICS -- **Engine**: Uses `@ast-grep/napi` for 25+ language support. -- **Patterns**: Supports meta-variables (`$VAR`) and multi-node matching (`$$$`). -- **Performance**: Structural matching executed in Rust/C++ layer. + +- **Engine**: `@ast-grep/napi` for 25+ languages +- **Patterns**: Meta-variables `$VAR` (single), `$$$` (multiple) +- **Performance**: Rust/C++ layer for structural matching ## ANTI-PATTERNS -- **Sequential Calls**: Don't call `bash` in loops; use `&&` or delegation. -- **Raw File Ops**: Never use `mkdir/touch` inside tool logic. -- **Heavy Sync**: Keep `PreToolUse` light; heavy computation belongs in `tools.ts`. -- **Sleep**: Never use `sleep N`; use polling loops or tool-specific wait flags. + +- **Sequential bash**: Use `&&` or delegation, not loops +- **Raw file ops**: Never mkdir/touch in tool logic +- **Sleep**: Use polling loops, tool-specific wait flags +- **Heavy sync**: Keep PreToolUse light, computation in tools.ts