Alvin Unreal пре 2 месеци
родитељ
комит
20ead2229f
7 измењених фајлова са 1706 додато и 115 уклоњено
  1. 31 36
      .slim/cartography.json
  2. 185 7
      codemap.md
  3. 255 14
      src/agents/codemap.md
  4. 298 11
      src/background/codemap.md
  5. 335 14
      src/cli/codemap.md
  6. 260 16
      src/config/codemap.md
  7. 342 17
      src/tools/codemap.md

+ 31 - 36
.slim/cartography.json

@@ -1,7 +1,7 @@
 {
 {
   "metadata": {
   "metadata": {
     "version": "1.0.0",
     "version": "1.0.0",
-    "last_run": "2026-01-25T21:23:31.047804Z",
+    "last_run": "2026-01-28T20:25:58.984513Z",
     "root": "/Users/xp/repos/oh-my-opencode-slim",
     "root": "/Users/xp/repos/oh-my-opencode-slim",
     "include_patterns": [
     "include_patterns": [
       "src/**/*.ts",
       "src/**/*.ts",
@@ -23,32 +23,32 @@
     "exceptions": []
     "exceptions": []
   },
   },
   "file_hashes": {
   "file_hashes": {
-    "package.json": "61caa0502a04ebbbcec2e594b54bea39",
+    "package.json": "7715619acbfd880221f72135dabb55cd",
     "src/agents/designer.ts": "ea6af83207f143260a775d79ab229407",
     "src/agents/designer.ts": "ea6af83207f143260a775d79ab229407",
     "src/agents/explorer.ts": "4678dc549476feeb9088149e72bcffdb",
     "src/agents/explorer.ts": "4678dc549476feeb9088149e72bcffdb",
     "src/agents/fixer.ts": "02aa0b9da795e0aa38c9651fe0c5a8c9",
     "src/agents/fixer.ts": "02aa0b9da795e0aa38c9651fe0c5a8c9",
-    "src/agents/index.ts": "a830fce51b5e44de72845581b08dd707",
+    "src/agents/index.ts": "9a715acd64b4d0a7cd65c651207fd234",
     "src/agents/librarian.ts": "8a85df35044c719b6615d6afdbe26f04",
     "src/agents/librarian.ts": "8a85df35044c719b6615d6afdbe26f04",
     "src/agents/oracle.ts": "d6a40e69fad62a4f95568f3e9314a06a",
     "src/agents/oracle.ts": "d6a40e69fad62a4f95568f3e9314a06a",
     "src/agents/orchestrator.ts": "74b53f65eed498b9664f11eb4f91761f",
     "src/agents/orchestrator.ts": "74b53f65eed498b9664f11eb4f91761f",
-    "src/background/background-manager.ts": "3c7dac0af2d0223d67ea78c76d543a90",
+    "src/background/background-manager.ts": "7f91035b3a8662f2f2eac3e0d082ffba",
     "src/background/index.ts": "c20308c54093f4578e3f5145307e1a42",
     "src/background/index.ts": "c20308c54093f4578e3f5145307e1a42",
-    "src/background/tmux-session-manager.ts": "5a67f78e83aa4f84f491be2633b7af83",
-    "src/cli/config-io.ts": "b4f50950ae59730f9dd899c14a3f17d5",
+    "src/background/tmux-session-manager.ts": "5dad9a8ff9ed6ac6a0c9a3587d47540f",
+    "src/cli/config-io.ts": "7f812a28b4d140f51b5f9129085482bb",
     "src/cli/config-manager.ts": "7f2960f55aaebab21d822c586c2b12eb",
     "src/cli/config-manager.ts": "7f2960f55aaebab21d822c586c2b12eb",
-    "src/cli/custom-skills.ts": "3af1341d323e8693610ee5070f388029",
-    "src/cli/index.ts": "afbd341f1c5cdc3566aa0a55ab47439e",
-    "src/cli/install.ts": "e03e50013793299055bd0f3aa24f5457",
+    "src/cli/custom-skills.ts": "f03bea6c621673bdadb84f3cf7c1ea46",
+    "src/cli/index.ts": "bf1190c5940db5db5e43acab4653a713",
+    "src/cli/install.ts": "cb30607fdb8c92b03199c00c102bf962",
     "src/cli/paths.ts": "7b5c9ce35d55d5e2fdf9f48b759aa323",
     "src/cli/paths.ts": "7b5c9ce35d55d5e2fdf9f48b759aa323",
-    "src/cli/providers.ts": "e4e819fff7f1854e01461ae42eef4687",
+    "src/cli/providers.ts": "36a0a27c80163969c61c8ba387789ebf",
     "src/cli/skills.ts": "75cb8bcf04dae88cd56772f9c7d01782",
     "src/cli/skills.ts": "75cb8bcf04dae88cd56772f9c7d01782",
     "src/cli/system.ts": "15663904f06d63352c49066371c66c0d",
     "src/cli/system.ts": "15663904f06d63352c49066371c66c0d",
-    "src/cli/types.ts": "8518735f1de623098df620059f9cfe5e",
+    "src/cli/types.ts": "e8184c9181b3cec5c129d4cc298b437d",
     "src/config/agent-mcps.ts": "f65c01e9a29fd9c2ff5658ce30c89f98",
     "src/config/agent-mcps.ts": "f65c01e9a29fd9c2ff5658ce30c89f98",
-    "src/config/constants.ts": "4970144850560dae8449e5c0cc5d7cf8",
+    "src/config/constants.ts": "d3fd2518f1d17ac182d933eae7f5c80f",
     "src/config/index.ts": "7ec846841f7fe8fcc6d4bc5d5120412d",
     "src/config/index.ts": "7ec846841f7fe8fcc6d4bc5d5120412d",
     "src/config/loader.ts": "9e60d552a223515b4fc4dd34b2ad0cc2",
     "src/config/loader.ts": "9e60d552a223515b4fc4dd34b2ad0cc2",
-    "src/config/schema.ts": "fbf24c0421bc311120fd76f68af556af",
+    "src/config/schema.ts": "49fdb0b2d31244ff985e2327b3e80c34",
     "src/config/utils.ts": "bc3af4a86874329f638a374ac7c00701",
     "src/config/utils.ts": "bc3af4a86874329f638a374ac7c00701",
     "src/hooks/auto-update-checker/cache.ts": "2d49b0e0ea0f1a36b2ae79f43d163b45",
     "src/hooks/auto-update-checker/cache.ts": "2d49b0e0ea0f1a36b2ae79f43d163b45",
     "src/hooks/auto-update-checker/checker.ts": "0cd527f77d797a663476224d77ac44f4",
     "src/hooks/auto-update-checker/checker.ts": "0cd527f77d797a663476224d77ac44f4",
@@ -58,7 +58,7 @@
     "src/hooks/index.ts": "85f2c28ccaf0968698a0b8343e3977c3",
     "src/hooks/index.ts": "85f2c28ccaf0968698a0b8343e3977c3",
     "src/hooks/phase-reminder/index.ts": "d8c9c5d0f7147e5f44e000303daa6cc2",
     "src/hooks/phase-reminder/index.ts": "d8c9c5d0f7147e5f44e000303daa6cc2",
     "src/hooks/post-read-nudge/index.ts": "7463a25eac61ebd8833a44bee60f2d81",
     "src/hooks/post-read-nudge/index.ts": "7463a25eac61ebd8833a44bee60f2d81",
-    "src/index.ts": "b494ac1fce3b86b3c60a8e8e8f613ffd",
+    "src/index.ts": "dcc8a0bcad2c0fd9b57b8031c70a4539",
     "src/mcp/context7.ts": "4e02e8ef204b6eb7e99a3209078428b5",
     "src/mcp/context7.ts": "4e02e8ef204b6eb7e99a3209078428b5",
     "src/mcp/grep-app.ts": "f76cb0ffb3484b16d55f27729e80e864",
     "src/mcp/grep-app.ts": "f76cb0ffb3484b16d55f27729e80e864",
     "src/mcp/index.ts": "d19746215624f8dfdcb21b6a1ad552c0",
     "src/mcp/index.ts": "d19746215624f8dfdcb21b6a1ad552c0",
@@ -71,15 +71,15 @@
     "src/tools/ast-grep/tools.ts": "3f7c2c65cffd5273b0cd6c849800176d",
     "src/tools/ast-grep/tools.ts": "3f7c2c65cffd5273b0cd6c849800176d",
     "src/tools/ast-grep/types.ts": "34ad28b5b1e9617b584f082dba9a427c",
     "src/tools/ast-grep/types.ts": "34ad28b5b1e9617b584f082dba9a427c",
     "src/tools/ast-grep/utils.ts": "1dd3b2133c4b8c847a26eea0423bc0b2",
     "src/tools/ast-grep/utils.ts": "1dd3b2133c4b8c847a26eea0423bc0b2",
-    "src/tools/background.ts": "11c0aac39c0346220a55a98d61d89899",
-    "src/tools/grep/cli.ts": "7105badf3f343bce8f0ad547705cbc36",
+    "src/tools/background.ts": "f35973287ce4f4bb75f007da8bbd96e2",
+    "src/tools/grep/cli.ts": "e53cf03c5d2672fc6aca651da9dfb322",
     "src/tools/grep/constants.ts": "52f05a89470828582aee209b0c72b01f",
     "src/tools/grep/constants.ts": "52f05a89470828582aee209b0c72b01f",
     "src/tools/grep/downloader.ts": "876022c453c4072f313ddaf7ea595409",
     "src/tools/grep/downloader.ts": "876022c453c4072f313ddaf7ea595409",
     "src/tools/grep/index.ts": "20eef5dabac9f703a9c97ffe89ce2f4e",
     "src/tools/grep/index.ts": "20eef5dabac9f703a9c97ffe89ce2f4e",
     "src/tools/grep/tools.ts": "55d0a611e0e4e1a7612a4dde40b3be51",
     "src/tools/grep/tools.ts": "55d0a611e0e4e1a7612a4dde40b3be51",
     "src/tools/grep/types.ts": "4b7e3313306e58f2fae265cf0d1c3ed3",
     "src/tools/grep/types.ts": "4b7e3313306e58f2fae265cf0d1c3ed3",
     "src/tools/grep/utils.ts": "af0426f46b8e5080621adc99b2e496c2",
     "src/tools/grep/utils.ts": "af0426f46b8e5080621adc99b2e496c2",
-    "src/tools/index.ts": "24538b32510bc2f8438d6037dc023540",
+    "src/tools/index.ts": "d9ad8f58b2403662294d5260b3d005bb",
     "src/tools/lsp/client.ts": "445c0c95dce6f6235e85021761fc4bc8",
     "src/tools/lsp/client.ts": "445c0c95dce6f6235e85021761fc4bc8",
     "src/tools/lsp/config.ts": "ebe9cb109e877e5af5cd8580aa0def50",
     "src/tools/lsp/config.ts": "ebe9cb109e877e5af5cd8580aa0def50",
     "src/tools/lsp/constants.ts": "37f03eb9604b67b0cfa1b992709c01d6",
     "src/tools/lsp/constants.ts": "37f03eb9604b67b0cfa1b992709c01d6",
@@ -87,10 +87,6 @@
     "src/tools/lsp/tools.ts": "023d712c7a06ab9e43851826114309a0",
     "src/tools/lsp/tools.ts": "023d712c7a06ab9e43851826114309a0",
     "src/tools/lsp/types.ts": "8921e8b2874630760f2344f53376aefc",
     "src/tools/lsp/types.ts": "8921e8b2874630760f2344f53376aefc",
     "src/tools/lsp/utils.ts": "1ccffd60530384af9ec1c68bb37490b8",
     "src/tools/lsp/utils.ts": "1ccffd60530384af9ec1c68bb37490b8",
-    "src/tools/quota/api.ts": "1f43c2446e6c1c63d4d585a2ca911c33",
-    "src/tools/quota/command.ts": "3e9e45ea608ea1572f9b5d7412b5ed82",
-    "src/tools/quota/index.ts": "97d09317e92c8cdb8178f4d1b5125b03",
-    "src/tools/quota/types.ts": "1d404edf536be538cd4fdaf15d9100f2",
     "src/utils/agent-variant.ts": "1ab47427e7e8381ae13f09fd499d8755",
     "src/utils/agent-variant.ts": "1ab47427e7e8381ae13f09fd499d8755",
     "src/utils/index.ts": "4f84dbeb33eb59ededba98288c436e21",
     "src/utils/index.ts": "4f84dbeb33eb59ededba98288c436e21",
     "src/utils/logger.ts": "779c3886f558ddb6a3b268c249ecfc4e",
     "src/utils/logger.ts": "779c3886f558ddb6a3b268c249ecfc4e",
@@ -100,22 +96,21 @@
     "tsconfig.json": "1d2bb6e93a43366843785a156c8e538a"
     "tsconfig.json": "1d2bb6e93a43366843785a156c8e538a"
   },
   },
   "folder_hashes": {
   "folder_hashes": {
-    "src/hooks/phase-reminder": "0a66b20683c09b9d4af7a81f4036d60b",
-    "src/mcp": "f9241cd556adebddc643d71ee55ee2a8",
-    "src": "c704f69c9f9a2a12b8897287539d70c0",
-    "src/cli": "dbab999877b28320e006f338ab12957b",
-    "src/background": "6bf11cd6942be5be684bbe61e41b283c",
+    ".": "eb229c8bd2c68ec5d9060c8aba078a9a",
+    "src": "ef897ff6240850f382fbb88da0c183e6",
+    "src/background": "310f509fa3b777173ca3943148129cfb",
+    "src/config": "6b119dc0d74f3764942a7d09c808858f",
+    "src/tools/grep": "6b4f06b396c51ba1317e986930422c8c",
     "src/utils": "e9668ece9a7fac2ae976455c058e60fa",
     "src/utils": "e9668ece9a7fac2ae976455c058e60fa",
-    "src/hooks/post-read-nudge": "d781f673f38b4d485db0731bdf6b1cac",
-    "src/config": "735cd8e695b5c89f627e094050a9aa4d",
-    "src/tools/grep": "6f8a4b3e3a98e00c1807d717f9f24bdb",
-    "src/tools/quota": "8644ac867c3bca1fd6c4530ec8f04dec",
-    "src/hooks/auto-update-checker": "34086e02a2cc2f000e2826091fcfb94d",
-    "src/tools/lsp": "3bec4280e142d54c8b0cddafc257e9d8",
-    ".": "71c8ece7421eeab137098d051cb22269",
     "src/tools/ast-grep": "2cb1b48926d4317af9837859cba0c3f6",
     "src/tools/ast-grep": "2cb1b48926d4317af9837859cba0c3f6",
+    "src/tools/lsp": "3bec4280e142d54c8b0cddafc257e9d8",
     "src/hooks": "dab7d541aa73558a8984eb9d9b3c1685",
     "src/hooks": "dab7d541aa73558a8984eb9d9b3c1685",
-    "src/agents": "4f804a51b82dda11e1578d37b223459d",
-    "src/tools": "566ef2faddc0903ac9a7162cc6c34da5"
+    "src/cli": "b993b56eaae369e25beb5b5df7a8b785",
+    "src/agents": "fcfa72336080b78681f283023ffe939c",
+    "src/mcp": "f9241cd556adebddc643d71ee55ee2a8",
+    "src/tools": "8e3d29e65aa7435e69eeabe6df16e95c",
+    "src/hooks/auto-update-checker": "34086e02a2cc2f000e2826091fcfb94d",
+    "src/hooks/post-read-nudge": "d781f673f38b4d485db0731bdf6b1cac",
+    "src/hooks/phase-reminder": "0a66b20683c09b9d4af7a81f4036d60b"
   }
   }
-}
+}

+ 185 - 7
codemap.md

@@ -1,17 +1,46 @@
 # Repository Atlas: oh-my-opencode-slim
 # Repository Atlas: oh-my-opencode-slim
 
 
 ## Project Responsibility
 ## Project Responsibility
-Provides an OpenCode plugin that orchestrates specialist agents, background task execution, tooling (grep/AST/LSP/quota), MCP connectors, and lifecycle hooks, plus a CLI installer that bootstraps user configuration and skill setup.
+
+**oh-my-opencode-slim** is a lightweight agent orchestration plugin for OpenCode - a slimmed-down fork of oh-my-opencode. It provides a multi-agent system that enables specialized AI agents to work together under an orchestrator to optimize coding tasks for quality, speed, cost, and reliability.
+
+The plugin integrates with OpenCode to provide:
+- **Multi-agent orchestration** with specialized roles (Orchestrator, Explorer, Librarian, Oracle, Designer, Fixer)
+- **Background task management** for long-running async operations
+- **MCP (Model Context Protocol) integration** for external tools and services
+- **LSP (Language Server Protocol) tools** for code intelligence
+- **Code search capabilities** via grep and AST-grep
+- **Tmux integration** for visual task tracking
+- **Configuration system** with agent overrides and skill management
+- **CLI installer** for interactive setup and configuration
 
 
 ## System Entry Points
 ## System Entry Points
-- `src/index.ts`: Plugin entrypoint that registers agents, tools, MCPs, hooks, and configuration hooks with OpenCode.
-- `src/cli/index.ts`: CLI entry that dispatches to the installer workflow.
-- `package.json`: Dependency manifest and build/runtime scripts.
-- `tsconfig.json`: TypeScript compiler configuration.
+
+| File | Purpose | Key Exports |
+|------|---------|-------------|
+| `package.json` | Project manifest, dependencies, and build scripts | `oh-my-opencode-slim` CLI, `dist/index.js` main entry |
+| `src/index.ts` | Main plugin entry point | `OhMyOpenCodeLite` plugin, agent configs, tools, MCPs |
+| `src/cli/index.ts` | CLI installer entry point | `install` command, configuration management |
+| `tsconfig.json` | TypeScript compiler configuration | Build settings, type checking, declaration generation |
+
+### Build Artifacts
+
+- `dist/index.js` - Main plugin bundle (ESM)
+- `dist/index.d.ts` - TypeScript declarations
+- `dist/cli/index.js` - CLI bundle
+- `dist/cli/index.d.ts` - CLI TypeScript declarations
+
+### Published Files
+
+- `dist/` - Built JavaScript and declarations
+- `src/skills/` - Skill definitions (included in npm package)
+- `README.md` - Documentation
+- `LICENSE` - MIT license
 
 
 ## Repository Directory Map
 ## Repository Directory Map
+
 | Directory | Responsibility Summary | Detailed Map |
 | Directory | Responsibility Summary | Detailed Map |
-| --- | --- | --- |
+|-----------|------------------------|--------------|
 | `src/` | Main plugin entrypoint plus all feature modules that compose agents, tools, hooks, background managers, and utils. | [View Map](src/codemap.md) |
 | `src/` | Main plugin entrypoint plus all feature modules that compose agents, tools, hooks, background managers, and utils. | [View Map](src/codemap.md) |
 | `src/agents/` | Defines specialist agents and the orchestrator, with factories and override/permission helpers. | [View Map](src/agents/codemap.md) |
 | `src/agents/` | Defines specialist agents and the orchestrator, with factories and override/permission helpers. | [View Map](src/agents/codemap.md) |
 | `src/background/` | Background task/session managers and tmux pane orchestration for off-thread agent runs. | [View Map](src/background/codemap.md) |
 | `src/background/` | Background task/session managers and tmux pane orchestration for off-thread agent runs. | [View Map](src/background/codemap.md) |
@@ -26,5 +55,154 @@ Provides an OpenCode plugin that orchestrates specialist agents, background task
 | `src/tools/ast-grep/` | AST-grep CLI discovery, execution, and tool definitions. | [View Map](src/tools/ast-grep/codemap.md) |
 | `src/tools/ast-grep/` | AST-grep CLI discovery, execution, and tool definitions. | [View Map](src/tools/ast-grep/codemap.md) |
 | `src/tools/grep/` | Ripgrep/grep runner, downloader, and tool definition. | [View Map](src/tools/grep/codemap.md) |
 | `src/tools/grep/` | Ripgrep/grep runner, downloader, and tool definition. | [View Map](src/tools/grep/codemap.md) |
 | `src/tools/lsp/` | LSP client stack and tool surface for definitions, diagnostics, and rename. | [View Map](src/tools/lsp/codemap.md) |
 | `src/tools/lsp/` | LSP client stack and tool surface for definitions, diagnostics, and rename. | [View Map](src/tools/lsp/codemap.md) |
-| `src/tools/quota/` | Antigravity quota fetcher and CLI tool output formatter. | [View Map](src/tools/quota/codemap.md) |
+
 | `src/utils/` | Shared helpers for variants, tmux, polling, logging, and zip extraction. | [View Map](src/utils/codemap.md) |
 | `src/utils/` | Shared helpers for variants, tmux, polling, logging, and zip extraction. | [View Map](src/utils/codemap.md) |
+
+## Architecture Overview
+
+### Plugin Initialization Flow
+
+```
+OpenCode loads plugin
+    ↓
+src/index.ts: OhMyOpenCodeLite(ctx)
+    ↓
+Load plugin config (src/config)
+    ↓
+Initialize agent configs (src/agents)
+    ↓
+Initialize background manager (src/background)
+    ↓
+Initialize MCPs (src/mcp)
+    ↓
+Initialize hooks (src/hooks)
+    ↓
+Register tools (src/tools)
+    ↓
+Return plugin object with:
+    - agent: Agent configurations
+    - tool: Tool implementations
+    - mcp: MCP configurations
+    - config: Config merger
+    - event: Event handlers
+    - hooks: Message transforms
+```
+
+### Key Integrations
+
+1. **Agent System** (`src/agents/`)
+   - Orchestrator delegates to specialized subagents
+   - Each agent has specific tools, permissions, and temperature settings
+   - MCP tools configured per agent based on role
+
+2. **Background Tasks** (`src/background/`)
+   - Fire-and-forget task execution
+   - Session lifecycle management
+   - Optional tmux pane integration for visual tracking
+
+3. **Configuration** (`src/config/`)
+   - User, project, and preset config layers
+   - Agent overrides and custom prompts
+   - MCP availability and permissions
+
+4. **Tools** (`src/tools/`)
+   - Code search (grep, AST-grep)
+   - LSP integration (diagnostics, references, rename)
+   - Background task orchestration
+
+5. **MCP Integration** (`src/mcp/`)
+   - Built-in remote MCPs (websearch, context7, grep.app)
+   - Type-safe configuration
+   - Disabled MCP filtering
+
+6. **Hooks** (`src/hooks/`)
+   - Auto-update checking
+   - Phase reminders for workflow compliance
+   - Post-read nudges for delegation
+
+## Development Workflow
+
+```bash
+# Build the project
+bun run build
+
+# Type checking
+bun run typecheck
+
+# Run tests
+bun test
+
+# Linting
+bun run lint
+
+# Format code
+bun run format
+
+# Run all checks (lint + format + organize imports)
+bun run check
+
+# CI mode checks (no auto-fix)
+bun run check:ci
+
+# Build and run with OpenCode
+bun run dev
+```
+
+## Key Dependencies
+
+| Dependency | Purpose |
+|------------|---------|
+| `@opencode-ai/plugin` | OpenCode plugin SDK |
+| `@opencode-ai/sdk` | OpenCode AI SDK |
+| `@modelcontextprotocol/sdk` | MCP protocol implementation |
+| `@ast-grep/cli` | AST-aware code search |
+| `vscode-jsonrpc` | JSON-RPC protocol |
+| `vscode-languageserver-protocol` | LSP protocol |
+| `zod` | Runtime validation |
+
+## Extension Points
+
+### Adding New Agents
+
+1. Create agent definition in `src/agents/`
+2. Add to agent factory registry
+3. Configure default model in `src/config/constants.ts`
+4. Add MCP configuration in `src/config/agent-mcps.ts`
+5. Add skill permissions in `src/cli/skills/`
+
+### Adding New Tools
+
+1. Implement tool in `src/tools/`
+2. Export from `src/tools/index.ts`
+3. Register in main plugin (`src/index.ts`)
+4. Configure agent permissions
+
+### Adding New MCPs
+
+1. Define MCP config in `src/mcp/`
+2. Add to `createBuiltinMcps` registry
+3. Configure agent access in `src/config/agent-mcps.ts`
+
+### Adding New Hooks
+
+1. Implement hook in `src/hooks/`
+2. Export factory function from `src/hooks/index.ts`
+3. Register in main plugin (`src/index.ts`)
+
+## Configuration Structure
+
+```typescript
+interface PluginConfig {
+  agents?: {
+    [agentName: string]: AgentOverrideConfig;
+  };
+  tmux?: TmuxConfig;
+  disabled_mcps?: McpName[];
+  background?: BackgroundTaskConfig;
+  presets?: Record<string, Partial<PluginConfig>>;
+}
+```
+
+## License
+
+MIT License - See [LICENSE](LICENSE) for details.

+ 255 - 14
src/agents/codemap.md

@@ -1,26 +1,267 @@
-# src/agents/
+# Agents Directory Codemap
 
 
 ## Responsibility
 ## Responsibility
 
 
-Hosts every OpenCode specialist agent plus the orchestrator definition that coordinates them. `index.ts` is responsible for instantiating each agent definition (model, temperature, prompt) using the folder-level factories, applying per-agent overrides from `config`, wiring in default permissions, and exposing helpers (`createAgents`, `getAgentConfigs`) consumed by the plugin runtime.
+The `src/agents/` directory defines and configures the multi-agent orchestration system for OpenCode. It creates specialized AI agents with distinct roles, capabilities, and behaviors that work together under an orchestrator to optimize coding tasks for quality, speed, cost, and reliability.
 
 
 ## Design
 ## Design
 
 
-- Each specialist (`explorer`, `librarian`, `oracle`, `designer`, `fixer`) is defined in its own file. They share the `AgentDefinition` shape from `orchestrator.ts`, configure temperature/model, and build a default prompt that can be replaced or appended with custom content.
-- `orchestrator.ts` also hosts the central prompt template that defines the delegation workflow, the role descriptions, and the policy for when to spin up specialists. That template plus the shared `createOrchestratorAgent` helper keep the orchestrator bundle self-contained.
-- The module follows a factory + post-processing pattern: `SUBAGENT_FACTORIES` maps names to creators, `createAgents` builds proto-agents, then decorates them with overrides, permissions, and the orchestrator definition before returning the full roster.
-- Permission helpers (`applyOverrides`, `applyDefaultPermissions`) enforce consistent runtime metadata (model, temperature, skill permissions) while keeping authorization logic separate from factory instantiation.
+### Core Architecture
+
+**Agent Definition Interface**
+```typescript
+interface AgentDefinition {
+  name: string;
+  description?: string;
+  config: AgentConfig;
+}
+```
+
+All agents follow a consistent factory pattern:
+- `createXAgent(model, customPrompt?, customAppendPrompt?)` → `AgentDefinition`
+- Custom prompts can fully replace or append to default prompts
+- Temperature varies by agent role (0.1-0.7) to balance precision vs creativity
+
+### Agent Classification
+
+**Primary Agent**
+- **Orchestrator**: Central coordinator that delegates tasks to specialists
+
+**Subagents** (5 specialized agents)
+1. **Explorer** - Codebase navigation and search (temperature: 0.1)
+2. **Librarian** - Documentation and library research (temperature: 0.1)
+3. **Oracle** - Strategic technical advisor (temperature: 0.1)
+4. **Designer** - UI/UX specialist (temperature: 0.7)
+5. **Fixer** - Fast implementation specialist (temperature: 0.2)
+
+### Configuration System
+
+**Override Application**
+- Model and temperature can be overridden per agent via user config
+- Fallback mechanism: Fixer inherits Librarian's model if not configured
+- Default models defined in `../config/DEFAULT_MODELS`
+
+**Permission System**
+- All agents get `question: 'allow'` by default
+- Skill permissions applied via `getSkillPermissionsForAgent()`
+- Nested permission structure: `{ question, skill: { ... } }`
+
+**Custom Prompts**
+- Loaded via `loadAgentPrompt(name)` from config
+- Supports full replacement or append mode
+- Applied after default prompt construction
+
+### Agent Specialization Matrix
+
+| Agent | Primary Focus | Tools | Constraints | Temperature |
+|-------|--------------|-------|-------------|-------------|
+| Explorer | Codebase search | grep, glob, ast_grep_search | Read-only, parallel | 0.1 |
+| Librarian | External docs | context7, grep_app, websearch | Evidence-based | 0.1 |
+| Oracle | Architecture | Analysis tools | Read-only, advisory | 0.1 |
+| Designer | UI/UX | Tailwind, CSS | Visual excellence | 0.7 |
+| Fixer | Implementation | Edit/write tools | No research/delegation | 0.2 |
 
 
 ## Flow
 ## Flow
 
 
-1. `createAgents(config?)` is the entry point. It determines the fallback models (fixer inherits librarian’s model when undefined), loads any custom prompts, then instantiates each subagent via `SUBAGENT_FACTORIES`.
-2. Each proto agent passes through `applyOverrides` (model/temperature) and `applyDefaultPermissions`, which merges configured skill permissions from `getSkillPermissionsForAgent` and always allows the `question` permission.
-3. The orchestrator is built last with `createOrchestratorAgent`, honoring its own prompt overrides before default permissions/override logic runs again.
-4. `getAgentConfigs(config?)` turns the roster into a record keyed by agent name, attaches descriptions, includes MCPs via `getAgentMcpList`, and flags `mode` (subagent vs primary) based on `isSubagent`.
+### Agent Creation Flow
+
+```
+createAgents(config?)
+  │
+  ├─→ For each subagent:
+  │   ├─→ Get model (with fallback for fixer)
+  │   ├─→ Load custom prompts
+  │   ├─→ Call factory function
+  │   ├─→ Apply overrides (model, temperature)
+  │   └─→ Apply default permissions
+  │
+  ├─→ Create orchestrator:
+  │   ├─→ Get model
+  │   ├─→ Load custom prompts
+  │   ├─→ Call factory function
+  │   ├─→ Apply overrides
+  │   └─→ Apply default permissions
+  │
+  └─→ Return [orchestrator, ...subagents]
+```
+
+### SDK Configuration Flow
+
+```
+getAgentConfigs(config?)
+  │
+  ├─→ createAgents(config)
+  │
+  ├─→ For each agent:
+  │   ├─→ Extract config
+  │   ├─→ Add description
+  │   ├─→ Add MCP list via getAgentMcpList()
+  │   ├─→ Set mode:
+  │   │   ├─→ 'primary' for orchestrator
+  │   │   └─→ 'subagent' for others
+  │   └─→ Map to Record<string, SDKAgentConfig>
+  │
+  └─→ Return config object
+```
+
+### Orchestrator Delegation Flow
+
+```
+User Request
+    │
+    ↓
+Understand (parse requirements)
+    │
+    ↓
+Path Analysis (quality, speed, cost, reliability)
+    │
+    ↓
+Delegation Check
+    │
+    ├─→ Need to discover unknowns? → @explorer
+    ├─→ Complex/evolving APIs? → @librarian
+    ├─→ High-stakes decisions? → @oracle
+    ├─→ User-facing polish? → @designer
+    ├─→ Clear spec, parallel tasks? → @fixer
+    └─→ Simple/quick? → Do yourself
+    │
+    ↓
+Parallelize (if applicable)
+    │
+    ├─→ Multiple @explorer searches?
+    ├─→ @explorer + @librarian research?
+    └─→ Multiple @fixer instances?
+    │
+    ↓
+Execute & Integrate
+    │
+    ↓
+Verify (lsp_diagnostics, tests)
+```
+
+### Agent Interaction Patterns
+
+**Research → Implementation Chain**
+```
+Orchestrator
+    ↓ delegates to
+Explorer (find files) + Librarian (get docs)
+    ↓ provide context to
+Fixer (implement changes)
+```
+
+**Advisory Pattern**
+```
+Orchestrator
+    ↓ delegates to
+Oracle (architecture decision)
+    ↓ provides guidance to
+Orchestrator (implements or delegates to Fixer)
+```
+
+**Design Pattern**
+```
+Orchestrator
+    ↓ delegates to
+Designer (UI/UX implementation)
+    ↓ (Designer may use Fixer for parallel tasks)
+```
 
 
 ## Integration
 ## Integration
 
 
-- Depends on the shared config layer (`../config` and `../config/agent-mcps`) for default models, override data, custom prompts, and MCP routing decisions.
-- Hooks into `../cli/skills` to fetch skill-specific permissions for each agent so the orchestrator can enforce runtime guardrails without hardcoding skill lists here.
-- Consumers (plugin entrypoints/runtime) import `createAgents`/`getAgentConfigs` to register agents with the OpenCode SDK; the orchestrator prompt mentions the specialists and guides delegation.
-- Specialist agents themselves are mostly self-contained (hardcoded prompts + simple factory) but are composed and configured through this folder’s public API before being surfaced to the rest of the system.
+### Dependencies
+
+**External Dependencies**
+- `@opencode-ai/sdk` - Core agent configuration types (`AgentConfig`)
+- `@modelcontextprotocol/sdk` - MCP protocol (via config)
+
+**Internal Dependencies**
+- `../config` - Agent overrides, default models, MCP lists, custom prompts
+- `../cli/skills` - Skill permission system (`getSkillPermissionsForAgent`)
+
+### Consumers
+
+**Direct Consumers**
+- `src/index.ts` - Main plugin entry point exports `getAgentConfigs()`
+- `src/cli/index.ts` - CLI entry point uses agent configurations
+
+**Indirect Consumers**
+- OpenCode SDK - Consumes agent configurations via `getAgentConfigs()`
+- MCP servers - Agents configured with specific MCP tool lists
+
+### Configuration Integration
+
+**Agent Override Config**
+```typescript
+interface AgentOverrideConfig {
+  model?: string;
+  temperature?: number;
+  skills?: string[];
+}
+```
+
+**Plugin Config**
+```typescript
+interface PluginConfig {
+  agents?: {
+    [agentName: string]: AgentOverrideConfig;
+  };
+  // ... other config
+}
+```
+
+### Skill System Integration
+
+Each agent gets skill-specific permissions:
+- Permissions loaded from `../cli/skills`
+- Applied via nested `skill` key in permissions object
+- Respects user-configured skill lists if provided
+
+### MCP Integration
+
+Agents are configured with specific MCP tool lists:
+- `getAgentMcpList(agentName, config)` returns tool list
+- MCP tools enable agent capabilities (e.g., grep_app for Librarian)
+- Configured per agent based on role and needs
+
+## Key Design Decisions
+
+1. **Factory Pattern**: Consistent agent creation with customization hooks
+2. **Temperature Gradient**: 0.1 (precision) → 0.7 (creativity) based on role
+3. **Read-Only Specialists**: Explorer, Librarian, Oracle don't modify code
+4. **Execution Specialist**: Fixer is the only agent that makes code changes
+5. **Fallback Model**: Fixer inherits Librarian's model for backward compatibility
+6. **Permission Defaults**: All agents get `question: 'allow'` for smooth UX
+7. **Custom Prompt Flexibility**: Full replacement or append mode for customization
+8. **Parallel-First**: Orchestrator encouraged to parallelize independent tasks
+9. **Evidence-Based Research**: Librarian must provide sources and citations
+10. **Visual Excellence Priority**: Designer prioritizes aesthetics over code perfection
+
+## File Structure
+
+```
+src/agents/
+├── index.ts          # Main entry point, agent factory registry, config application
+├── orchestrator.ts   # Orchestrator agent definition and delegation workflow
+├── explorer.ts       # Codebase navigation specialist
+├── librarian.ts      # Documentation and library research specialist
+├── oracle.ts         # Strategic technical advisor
+├── fixer.ts          # Fast implementation specialist
+└── designer.ts       # UI/UX design specialist
+```
+
+## Extension Points
+
+**Adding New Agents**
+1. Create `src/agents/newagent.ts` with `createNewAgent()` factory
+2. Add to `SUBAGENT_FACTORIES` in `index.ts`
+3. Add to `SUBAGENT_NAMES` in `../config`
+4. Configure default model in `../config/DEFAULT_MODELS`
+5. Add MCP configuration in `../config/agent-mcps`
+6. Add skill permissions in `../cli/skills`
+
+**Customizing Existing Agents**
+- Override model/temperature via plugin config
+- Replace or append to prompts via `loadAgentPrompt()`
+- Configure MCP tools via agent-mcps config
+- Adjust skill permissions via skills config

+ 298 - 11
src/background/codemap.md

@@ -1,23 +1,310 @@
-# src/background/
+# Background Module Codemap
 
 
 ## Responsibility
 ## Responsibility
 
 
-- Hosts the services that run OpenCode agents outside the main conversation, keeping work progressing while users continue interacting in the foreground. `BackgroundTaskManager` orchestrates task lifecycle (session creation, prompt delivery, polling, result capture), and `TmuxSessionManager` surfaces child sessions inside tmux panes when enabled so operators see streaming updates.
+The `src/background/` module manages long-running AI agent tasks that execute asynchronously in isolated sessions. It enables fire-and-forget task execution, allowing users to continue working while background tasks complete independently. The module handles task lifecycle management, session creation, completion detection, and optional tmux pane integration for visual task tracking.
 
 
 ## Design
 ## Design
 
 
-- `BackgroundTaskManager` stores tasks in a `Map`, creates isolated sessions via the plugin client, applies agent variants/extensions, and polls session status/messages at configured intervals (`POLL_INTERVAL_BACKGROUND_MS`/`POLL_INTERVAL_SLOW_MS`) until completion or failure (see `background-manager.ts:66-165` and `background-manager.ts:218-313`).
-- `TmuxSessionManager` listens for `session.created` hooks, spawns/closes panes with `spawnTmuxPane`/`closeTmuxPane`, and maintains per-session metadata plus polling/timeout logic to tear down stale panes (`tmux-session-manager.ts:30-205`).
-- Both managers rely on shared config helpers (`applyAgentVariant`, `resolveAgentVariant`, `tmux` utils) and the plugin client/ directory context passed from the host plugin bootstrap (see `background-manager.ts:15-83`, `tmux-session-manager.ts:1-55`, and `index.ts`).
+### Core Abstractions
+
+#### BackgroundTask Interface
+Represents a background task with complete lifecycle tracking:
+- **id**: Unique task identifier (`bg_<random>`)
+- **sessionId**: OpenCode session ID (set when starting)
+- **description**: Human-readable task description
+- **agent**: Agent name handling the task
+- **status**: Task state (`pending` | `starting` | `running` | `completed` | `failed` | `cancelled`)
+- **result**: Final output from agent (when completed)
+- **error**: Error message (when failed)
+- **config**: Task configuration
+- **parentSessionId**: Parent session for notifications
+- **startedAt**: Creation timestamp
+- **completedAt**: Completion/failure timestamp
+- **prompt**: Initial prompt sent to agent
+
+#### LaunchOptions Interface
+Configuration for launching new background tasks:
+- **agent**: Agent to handle the task
+- **prompt**: Initial prompt to send to the agent
+- **description**: Human-readable task description
+- **parentSessionId**: Parent session ID for task hierarchy
+
+### Key Patterns
+
+#### 1. Fire-and-Forget Launch Pattern
+Two-phase task launch:
+- **Phase A (sync)**: Creates task record and returns immediately with `pending` status
+- **Phase B (async)**: Session creation and prompt sending happen in background
+
+#### 2. Start Queue with Concurrency Control
+- Tasks are queued for background start
+- Configurable `maxConcurrentStarts` limit (default: 10)
+- Queue processing ensures controlled resource usage
+- Prevents overwhelming the system with simultaneous session starts
+
+#### 3. Event-Driven Completion Detection
+- Listens to `session.status` events instead of polling
+- Detects idle status to mark tasks as completed
+- Extracts final output from session messages
+- Falls back to polling for reliability
+
+#### 4. Dual-Index Task Tracking
+- `tasks` Map: Task ID → BackgroundTask
+- `tasksBySessionId` Map: Session ID → Task ID
+- Enables bidirectional lookups for event handling
+
+#### 5. Promise-Based Waiting
+- `completionResolvers` Map stores pending wait promises
+- `waitForCompletion()` returns promise that resolves on task completion
+- Supports optional timeout parameter
+
+#### 6. Race-Condition Safe Cancellation
+- Marks status as `cancelled` before removing from queue
+- Checks cancellation status in `startTask()` after incrementing `activeStarts`
+- Uses type assertion to bypass TypeScript strictness during race handling
+
+### Classes
+
+#### BackgroundTaskManager
+Main orchestrator for background task lifecycle:
+
+**State:**
+- `tasks`: Map of all tracked tasks
+- `tasksBySessionId`: Session ID to task ID mapping
+- `client`: OpenCode client API
+- `directory`: Working directory for tasks
+- `tmuxEnabled`: Whether tmux integration is active
+- `config`: Plugin configuration
+- `backgroundConfig`: Background task configuration
+- `startQueue`: Queue of tasks waiting to start
+- `activeStarts`: Count of currently starting tasks
+- `maxConcurrentStarts`: Concurrency limit
+- `completionResolvers`: Map of waiting promises
+
+**Key Methods:**
+- `launch(opts)`: Create and queue a new background task (sync)
+- `handleSessionStatus(event)`: Process session.status events
+- `getResult(taskId)`: Retrieve current task state
+- `waitForCompletion(taskId, timeout)`: Wait for task completion
+- `cancel(taskId?)`: Cancel one or all tasks
+- `cleanup()`: Clean up all tasks
+
+#### TmuxSessionManager
+Manages tmux pane lifecycle for background sessions:
+
+**State:**
+- `client`: OpenCode client API
+- `tmuxConfig`: Tmux configuration
+- `serverUrl`: OpenCode server URL
+- `sessions`: Map of tracked sessions
+- `pollInterval`: Polling timer
+- `enabled`: Whether tmux integration is active
+
+**Key Methods:**
+- `onSessionCreated(event)`: Spawn tmux pane for child sessions
+- `onSessionStatus(event)`: Close pane when session becomes idle
+- `pollSessions()`: Fallback polling for status updates
+- `closeSession(sessionId)`: Close pane and remove tracking
+- `cleanup()`: Close all panes and stop polling
+
+### Interfaces
+
+#### TrackedSession (TmuxSessionManager)
+- `sessionId`: OpenCode session ID
+- `paneId`: Tmux pane identifier
+- `parentId`: Parent session ID
+- `title`: Session title
+- `createdAt`: Creation timestamp
+- `lastSeenAt`: Last seen timestamp
+- `missingSince`: When session went missing (optional)
+
+#### SessionEvent
+- `type`: Event type (`session.created`, `session.status`)
+- `properties`: Event properties containing session info
 
 
 ## Flow
 ## Flow
 
 
-- Launch: `launch()` creates a session under the parent ID, registers the task, optionally waits for tmux pane, resolves agent variant, then sends the prompt to the new session (`background-manager.ts:95-148`).
-- Polling: a shared interval iterates running tasks, queries session status, fetches assistant messages only after the session becomes idle, and stores the aggregated result or error plus timestamps (`background-manager.ts:217-315`).
-- Cancellation/Cleanup: `cancel()` marks tasks as failed with user-supplied reason; `TmuxSessionManager` closes panes when sessions time out or disappear, and exposes `cleanup()` for plugin shutdown (`background-manager.ts:187-215`, `tmux-session-manager.ts:89-205`).
+### Task Launch Flow
+
+```
+User calls launch()
+  ↓
+Create BackgroundTask with status='pending'
+  ↓
+Store in tasks Map
+  ↓
+Enqueue in startQueue
+  ↓
+processQueue() checks concurrency limit
+  ↓
+startTask() executes (async)
+  ↓
+  ├─ Set status='starting'
+  ├─ Increment activeStarts
+  ├─ Check for cancellation (race condition)
+  ├─ Create OpenCode session
+  ├─ Store sessionId in tasksBySessionId
+  ├─ Set status='running'
+  ├─ Wait 500ms (if tmux enabled)
+  ├─ Send prompt to session
+  └─ Decrement activeStarts and processQueue()
+```
+
+### Completion Detection Flow
+
+```
+session.status event received
+  ↓
+handleSessionStatus() checks event type
+  ↓
+Lookup taskId from tasksBySessionId
+  ↓
+Verify task is running
+  ↓
+Check if status.type === 'idle'
+  ↓
+extractAndCompleteTask()
+  ↓
+  ├─ Fetch session messages
+  ├─ Filter assistant messages
+  ├─ Extract text/reasoning parts
+  ├─ Join extracted content
+  └─ completeTask()
+      ↓
+      ├─ Set status='completed'
+      ├─ Set result or error
+      ├─ Delete from tasksBySessionId
+      ├─ Send notification to parent session
+      ├─ Resolve completionResolvers
+      └─ Log completion
+```
+
+### Cancellation Flow
+
+```
+User calls cancel(taskId?)
+  ↓
+Find task(s) with pending/starting/running status
+  ↓
+For each task:
+  ↓
+  ├─ Delete from completionResolvers
+  ├─ Check if in startQueue (before marking cancelled)
+  ├─ Set status='cancelled' (prevents race with startTask)
+  ├─ Remove from startQueue if pending
+  └─ completeTask() with 'cancelled' status
+```
+
+### Tmux Integration Flow
+
+```
+session.created event received
+  ↓
+onSessionCreated() checks enabled and parentID
+  ↓
+Skip if already tracking
+  ↓
+spawnTmuxPane() with session info
+  ↓
+  ├─ Create pane with title
+  ├─ Connect to OpenCode server
+  └─ Return paneId
+  ↓
+Store in sessions Map
+  ↓
+Start polling (if not already running)
+```
+
+```
+session.status event received (idle)
+  ↓
+onSessionStatus() checks enabled
+  ↓
+closeSession()
+  ↓
+  ├─ closeTmuxPane()
+  ├─ Delete from sessions Map
+  └─ Stop polling if no sessions left
+```
+
+### Polling Fallback Flow (TmuxSessionManager)
+
+```
+pollSessions() runs on interval
+  ↓
+Fetch all session statuses
+  ↓
+For each tracked session:
+  ↓
+  ├─ Check if idle → close
+  ├─ Update lastSeenAt if found
+  ├─ Set missingSince if not found
+  ├─ Check missingTooLong → close
+  └─ Check timeout → close
+```
 
 
 ## Integration
 ## Integration
 
 
-- Communicates with OpenCode’s plugin API client (`PluginInput`) for session creation, prompting, status, and messages; relies on the plugin config (`PluginConfig`, `TmuxConfig`) for model/variant overrides and tmux settings (`background-manager.ts` and `tmux-session-manager.ts`).
-- When tmux is enabled, `TmuxSessionManager` is wired to the plugin’s event hook so it can spawn panes as soon as `session.created` events arrive (`tmux-session-manager.ts:57-115`).
-- `index.ts` re-exports the managers so host code can import them together for plugin setup (`index.ts:1-6`).
+### Dependencies
+
+#### Internal Dependencies
+- `@opencode-ai/plugin`: PluginInput type, client API
+- `../config`: BackgroundTaskConfig, PluginConfig, TmuxConfig, POLL_INTERVAL_BACKGROUND_MS
+- `../utils`: applyAgentVariant, resolveAgentVariant, log, tmux utilities
+
+#### External Dependencies
+- None (uses only OpenCode SDK and standard Node.js APIs)
+
+### Consumers
+
+#### Direct Consumers
+- Main plugin entry point (`src/index.ts`)
+- Background task skill (`src/skills/background-task.ts`)
+
+#### Integration Points
+
+1. **Plugin Initialization**
+   - BackgroundTaskManager instantiated with PluginInput, TmuxConfig, and PluginConfig
+   - TmuxSessionManager instantiated with PluginInput and TmuxConfig
+
+2. **Event Handling**
+   - Both managers register as event handlers for session events
+   - BackgroundTaskManager handles `session.status` for completion detection
+   - TmuxSessionManager handles `session.created` and `session.status`
+
+3. **Skill Integration**
+   - Background task skill calls `launch()` to create tasks
+   - Skill calls `getResult()` and `waitForCompletion()` to retrieve results
+   - Skill calls `cancel()` to cancel tasks
+
+4. **Cleanup**
+   - Both managers provide `cleanup()` methods
+   - Called during plugin shutdown to release resources
+
+### Configuration
+
+#### BackgroundTaskConfig
+- `maxConcurrentStarts`: Maximum concurrent task starts (default: 10)
+
+#### TmuxConfig
+- `enabled`: Whether tmux integration is active
+- Additional tmux-specific settings (see `../config/schema`)
+
+### Error Handling
+
+- Session creation failures mark tasks as `failed`
+- Message extraction failures mark tasks as `failed`
+- Tmux pane spawn failures are logged but don't fail the task
+- Polling errors are logged but don't stop the manager
+- Notification failures are logged but don't affect task completion
+
+### Logging
+
+All operations are logged with context:
+- Task launch, start, completion, failure, cancellation
+- Session creation and pane spawning
+- Polling lifecycle
+- Error conditions
+
+Logs use the format `[component-name] message` with structured metadata.

+ 335 - 14
src/cli/codemap.md

@@ -1,21 +1,342 @@
-# src/cli/
+# CLI Module Codemap
 
 
 ## Responsibility
 ## Responsibility
-- Serve as the installer CLI for oh-my-opencode-slim: `src/cli/index.ts` parses bun-CLI flags and routes to the install workflow, while `src/cli/install.ts` orchestrates interactive prompts, validation, skill installation, next-step messaging, and exit handling.
-- Provide lightweight utilities (`types.ts`, `system.ts`, `paths.ts`, `config-manager.ts`, `config-io.ts`, `providers.ts`, `skills.ts`, `custom-skills.ts`) that encapsulate the configuration, provider, and skill-install responsibilities so `install.ts` remains focused on sequencing.
 
 
-## Design Patterns
-- Procedural command flow with helper primitives: `install.ts` keeps UI helpers (colored symbols, step printers) and step runners close together while delegating persistence and system checks to the re-exported `config-manager` modules.
-- Configuration abstraction: `config-io.ts` (JSON/JSONC parsing, atomic writes, comment stripping) and `paths.ts` centralize file system paths so callers only express intent (`addProviderConfig`, `writeLiteConfig`, `disableDefaultAgents`).
-- Provider/skill registries as data-driven definitions: `providers.ts` exports `CLIPROXY_PROVIDER_CONFIG`, `MODEL_MAPPINGS`, and `generateLiteConfig` that build presets from `RECOMMENDED_SKILLS`, while `custom-skills.ts` and `skills.ts` expose lists plus install helpers (`installSkill`, `installCustomSkill`).
+The `src/cli/` directory provides the command-line interface for installing and configuring **oh-my-opencode-slim**, an OpenCode plugin. It handles:
+
+- **Installation orchestration**: Interactive and non-interactive installation flows
+- **Configuration management**: Reading, parsing, and writing OpenCode configuration files
+- **Skill management**: Installing recommended skills (via npx) and custom skills (bundled)
+- **Provider configuration**: Setting up model mappings for different AI providers (Kimi, OpenAI, Zen)
+- **System integration**: Detecting OpenCode installation, validating environment
+
+## Design
+
+### Architecture Pattern
+
+The CLI module follows a **layered architecture** with clear separation of concerns:
+
+```
+┌─────────────────────────────────────────┐
+│         index.ts (Entry Point)          │
+│    - Argument parsing                    │
+│    - Command routing                     │
+└─────────────────┬───────────────────────┘
+                  │
+┌─────────────────▼───────────────────────┐
+│         install.ts (Orchestrator)       │
+│    - Interactive TUI                     │
+│    - Installation workflow               │
+│    - Step-by-step execution              │
+└─────────────────┬───────────────────────┘
+                  │
+    ┌─────────────┼─────────────┐
+    │             │             │
+┌───▼────┐  ┌────▼────┐  ┌────▼──────┐
+│ config │  │ skills  │  │  system   │
+│  -io   │  │         │  │           │
+│ paths  │  │custom   │  │           │
+│providers│ │         │  │           │
+└────────┘  └─────────┘  └────────────┘
+```
+
+### Key Abstractions
+
+#### 1. **Configuration Abstraction**
+
+**OpenCodeConfig** (`types.ts`):
+```typescript
+interface OpenCodeConfig {
+  plugin?: string[];
+  provider?: Record<string, unknown>;
+  agent?: Record<string, unknown>;
+  [key: string];
+}
+```
+
+Represents the main OpenCode configuration file (`opencode.json`/`opencode.jsonc`).
+
+**InstallConfig** (`types.ts`):
+```typescript
+interface InstallConfig {
+  hasKimi: boolean;
+  hasOpenAI: boolean;
+  hasOpencodeZen: boolean;
+  hasTmux: boolean;
+  installSkills: boolean;
+  installCustomSkills: boolean;
+}
+```
+
+User preferences collected during installation.
+
+#### 2. **Skill Abstractions**
+
+**RecommendedSkill** (`skills.ts`):
+```typescript
+interface RecommendedSkill {
+  name: string;
+  repo: string;
+  skillName: string;
+  allowedAgents: string[];
+  description: string;
+  postInstallCommands?: string[];
+}
+```
+
+Skills installed via `npx skills add` from external repositories.
+
+**CustomSkill** (`custom-skills.ts`):
+```typescript
+interface CustomSkill {
+  name: string;
+  description: string;
+  allowedAgents: string[];
+  sourcePath: string;
+}
+```
+
+Skills bundled in the repository, copied directly to `~/.config/opencode/skills/`.
+
+#### 3. **Result Abstraction**
+
+**ConfigMergeResult** (`types.ts`):
+```typescript
+interface ConfigMergeResult {
+  success: boolean;
+  configPath: string;
+  error?: string;
+}
+```
+
+Standardized result type for configuration operations.
+
+### Design Patterns
+
+1. **Atomic Write Pattern** (`config-io.ts`):
+   - Write to temporary file (`.tmp`)
+   - Rename to target path (atomic operation)
+   - Backup existing file (`.bak`) before writes
+
+2. **JSONC Support** (`config-io.ts`):
+   - Strip comments (single-line `//` and multi-line `/* */`)
+   - Remove trailing commas
+   - Parse as standard JSON
+
+3. **Provider Priority** (`providers.ts`):
+   - Kimi > OpenAI > Zen-free (fallback)
+   - Hybrid mode: Kimi for orchestrator/designer, OpenAI for oracle
+
+4. **Skill Permission Model** (`skills.ts`):
+   - Orchestrator gets `*` (all skills)
+   - Other agents get role-specific skills
+   - Wildcard support (`*`, `!skill`)
 
 
 ## Flow
 ## Flow
-- CLI entry: `index.ts` slices `process.argv`, handles `--help` or `install`, and feeds `InstallArgs` into `install(args)`.
-- `install.ts` branches between non-TUI (expects yes/no flags) and interactive modes: both call `runInstall`, which detects existing config, prints numbered steps, ensures OpenCode is installed, and updates configs/plugins.
-- `runInstall` sequentially adds the plugin, disables default agents, adds cliproxy provider if requested, writes the lite config, installs recommended/custom skills, and then prints the summary/next steps; helper functions like `handleStepResult`, `formatConfigSummary`, and `printAgentModels` keep each responsibility isolated.
-- Configuration helpers (`config-io.ts`) parse existing configs (JSON/JSONC, stripping comments), enforce atomic writes (temp + rename + backup), and expose detection helpers used in `runInstall` and interactive prompts.
+
+### Installation Flow
+
+```
+User runs: bunx oh-my-opencode-slim install
+         │
+         ▼
+┌─────────────────────────────────────────┐
+│ index.ts: parseArgs()                   │
+│ - Parse CLI arguments                   │
+│ - Validate --no-tui mode requirements   │
+└─────────────────┬───────────────────────┘
+                  │
+                  ▼
+┌─────────────────────────────────────────┐
+│ install.ts: install()                   │
+│                                         │
+│ ┌─────────────────────────────────────┐ │
+│ │ Interactive Mode (--tui, default)   │ │
+│ │ 1. Check OpenCode installed         │ │
+│ │ 2. Ask user questions (TUI)         │ │
+│ │    - Kimi access?                   │ │
+│ │    - OpenAI access?                 │ │
+│ │    - Install recommended skills?    │ │
+│ │    - Install custom skills?         │ │
+│ └─────────────────────────────────────┘ │
+│                                         │
+│ ┌─────────────────────────────────────┐ │
+│ │ Non-Interactive Mode (--no-tui)     │ │
+│ │ - Validate all required flags       │ │
+│ │ - Convert args to InstallConfig     │ │
+│ └─────────────────────────────────────┘ │
+└─────────────────┬───────────────────────┘
+                  │
+                  ▼
+┌─────────────────────────────────────────┐
+│ install.ts: runInstall()                │
+│                                         │
+│ Step 1: Check OpenCode installation     │
+│   └─> system.ts: isOpenCodeInstalled() │
+│                                         │
+│ Step 2: Add plugin to config            │
+│   └─> config-io.ts:                     │
+│      addPluginToOpenCodeConfig()        │
+│      - Parse existing config            │
+│      - Add 'oh-my-opencode-slim'        │
+│      - Remove old versions              │
+│      - Atomic write                     │
+│                                         │
+│ Step 3: Disable default agents          │
+│   └─> config-io.ts:                     │
+│      disableDefaultAgents()             │
+│      - Set agent.explore.disable=true   │
+│      - Set agent.general.disable=true   │
+│                                         │
+│ Step 4: Write lite config               │
+│   └─> config-io.ts: writeLiteConfig()   │
+│      └─> providers.ts:                  │
+│         generateLiteConfig()            │
+│         - Determine active preset       │
+│         - Build agent configurations    │
+│         - Map models to agents          │
+│         - Assign skills per agent       │
+│         - Add MCPs per agent            │
+│                                         │
+│ Step 5: Install recommended skills      │
+│   └─> skills.ts: installSkill()        │
+│      - npx skills add <repo>            │
+│      - Run post-install commands        │
+│                                         │
+│ Step 6: Install custom skills           │
+│   └─> custom-skills.ts:                 │
+│      installCustomSkill()               │
+│      - Copy from src/skills/            │
+│      - To ~/.config/opencode/skills/    │
+│                                         │
+│ Step 7: Print summary & next steps      │
+└─────────────────────────────────────────┘
+```
+
+### Configuration Detection Flow
+
+```
+detectCurrentConfig() [config-io.ts]
+         │
+         ▼
+┌─────────────────────────────────────────┐
+│ Parse opencode.json/jsonc               │
+│ - Check for plugin entry                │
+│ - Check for kimi provider               │
+└─────────────────┬───────────────────────┘
+                  │
+                  ▼
+┌─────────────────────────────────────────┐
+│ Parse oh-my-opencode-slim.json          │
+│ - Extract preset name                   │
+│ - Check agent models for OpenAI/Zen     │
+│ - Check tmux.enabled flag               │
+└─────────────────────────────────────────┘
+```
+
+### Model Mapping Flow
+
+```
+generateLiteConfig() [providers.ts]
+         │
+         ▼
+┌─────────────────────────────────────────┐
+│ Determine active preset                 │
+│ - hasKimi → 'kimi'                      │
+│ - hasOpenAI → 'openai'                  │
+│ - else → 'zen-free'                     │
+└─────────────────┬───────────────────────┘
+                  │
+                  ▼
+┌─────────────────────────────────────────┐
+│ For each agent (orchestrator, oracle,   │
+│ librarian, explorer, designer, fixer):  │
+│                                         │
+│ 1. Get model from MODEL_MAPPINGS        │
+│ 2. Apply hybrid logic (if needed)       │
+│ 3. Assign skills:                       │
+│    - Orchestrator: '*'                  │
+│    - Others: role-specific skills       │
+│ 4. Add MCPs from DEFAULT_AGENT_MCPS     │
+└─────────────────────────────────────────┘
+```
 
 
 ## Integration
 ## Integration
-- Tightly coupled with OpenCode installation: calls `system.ts` to detect `opencode` (and eventually `tmux`) binaries before proceeding, and manipulates `~/.config/opencode/opencode.json{c}` via `paths.ts`/`config-io.ts`.
-- Talks to provider/skill bundles: uses `providers.ts` to inject cliproxy configuration and build lite configs from `MODEL_MAPPINGS` plus external `DEFAULT_AGENT_MCPS`, installs `RECOMMENDED_SKILLS` via `npx skills add` (with optional `postInstallCommands`), and copies bundled `CUSTOM_SKILLS` into the user config directory.
-- Exposes a single façade via `config-manager.ts`, which re-exports the config I/O, path helpers, provider setup, and system checks so `install.ts` can treat configuration updates atomically without duplicating path logic.
+
+### External Dependencies
+
+| Module | Dependency | Purpose |
+|--------|-----------|---------|
+| `system.ts` | `opencode` CLI | Check installation, get version |
+| `skills.ts` | `npx skills` | Install recommended skills |
+| `skills.ts` | `npm` | Install agent-browser globally |
+| `skills.ts` | `agent-browser` CLI | Install browser automation |
+| `system.ts` | `tmux` CLI | Check tmux installation |
+
+### Internal Dependencies
+
+```
+index.ts
+  └─> install.ts
+       ├─> config-io.ts
+       │    ├─> paths.ts
+       │    └─> providers.ts
+       ├─> custom-skills.ts
+       ├─> skills.ts
+       └─> system.ts
+
+config-manager.ts (barrel)
+  ├─> config-io.ts
+  ├─> paths.ts
+  ├─> providers.ts
+  └─> system.ts
+```
+
+### Configuration Files
+
+| File | Location | Purpose |
+|------|----------|---------|
+| `opencode.json` | `~/.config/opencode/` | Main OpenCode config |
+| `opencode.jsonc` | `~/.config/opencode/` | Main config with comments |
+| `oh-my-opencode-slim.json` | `~/.config/opencode/` | Plugin-specific config |
+
+### Consumers
+
+1. **End Users**: Via `bunx oh-my-opencode-slim install`
+2. **OpenCode**: Reads generated configs to load plugin and agents
+3. **CI/CD**: Via `--no-tui` flag for automated installations
+
+### Data Flow Summary
+
+```
+User Input (CLI args or TUI)
+         │
+         ▼
+InstallConfig (preferences)
+         │
+         ├─> OpenCodeConfig (main config)
+         │    - Plugin registration
+         │    - Agent disabling
+         │
+         └─> LiteConfig (plugin config)
+              - Preset selection
+              - Model mappings
+              - Skill assignments
+              - MCP configurations
+              - Tmux settings
+```
+
+## Key Files Reference
+
+| File | Lines | Purpose |
+|------|-------|---------|
+| `index.ts` | 68 | CLI entry point, argument parsing |
+| `install.ts` | 402 | Installation orchestration, TUI |
+| `config-io.ts` | 251 | Config file I/O, JSONC parsing |
+| `providers.ts` | 110 | Model mappings, config generation |
+| `skills.ts` | 132 | Recommended skills management |
+| `custom-skills.ts` | 99 | Bundled skills management |
+| `paths.ts` | 48 | Path resolution utilities |
+| `system.ts` | 53 | System checks (OpenCode, tmux) |
+| `types.ts` | 40 | TypeScript type definitions |
+| `config-manager.ts` | 5 | Barrel exports |

+ 260 - 16
src/config/codemap.md

@@ -1,28 +1,272 @@
-# src/config/
-
-Manages the OpenCode Slim plugin configuration surface (constants, schema, loader helpers, and agent/MCP defaults) and exposes a cohesive API for the rest of the app.
+# Config Module Codemap
 
 
 ## Responsibility
 ## Responsibility
 
 
-- `constants.ts` defines agent name enums, default models, and polling/time settings that serve as the canonical runtime defaults for every subprocess.
-- `schema.ts` captures the zod-based structure of user/project configs (agents, presets, MCP toggles, tmux options), enabling rigorous validation for every entry point.
-- `loader.ts`, `agent-mcps.ts`, and `utils.ts` orchestrate reading, merging, and overriding those configs, plus discovering custom agent prompts and MCP availability.
+The `src/config/` module is responsible for:
+
+1. **Configuration Management**: Loading, validating, and merging plugin configuration from multiple sources (user config, project config, environment variables)
+2. **Schema Validation**: Providing type-safe configuration using Zod schemas
+3. **Agent Configuration**: Managing agent-specific overrides, models, skills, and MCP (Model Context Protocol) assignments
+4. **Prompt Customization**: Loading custom agent prompts from user directories
+5. **Constants Management**: Centralizing agent names, default models, polling intervals, and timeouts
 
 
 ## Design
 ## Design
 
 
-- Schemas: re-exported zod helpers keep shape/typing centralized (`AgentOverrideConfigSchema`, `PluginConfigSchema`, `McpNameSchema`, etc.), so validation and inference travel with exports.
-- Override helpers: `getAgentOverride` handles legacy aliases and layered agent configs; `DEFAULT_AGENT_MCPS` + `parseList` provide wildcard/exclusion semantics for MCP selection.
-- Loader patterns: `deepMerge` recursively merges nested maps (agents/tmux) while letting arrays/primitives be replaced, and the loader chains user, project, and preset configs with environment overrides to preserve precedence.
+### Key Patterns
+
+**Multi-Source Configuration Merging**
+- User config: `~/.config/opencode/oh-my-opencode-slim.json` (or `$XDG_CONFIG_HOME`)
+- Project config: `<directory>/.opencode/oh-my-opencode-slim.json`
+- Environment override: `OH_MY_OPENCODE_SLIM_PRESET`
+- Project config takes precedence over user config
+- Nested objects (agents, tmux) are deep-merged; arrays are replaced
+
+**Preset System**
+- Named presets contain agent configurations
+- Presets are merged with root-level agent config (root overrides)
+- Supports preset selection via config file or environment variable
+
+**Wildcard/Exclusion Syntax**
+- Skills and MCPs support `"*"` (all) and `"!item"` (exclude) syntax
+- Used in `parseList()` function for flexible filtering
+
+**Backward Compatibility**
+- Agent aliases map legacy names to current names (e.g., `explore` → `explorer`)
+- `getAgentOverride()` checks both current name and aliases
+
+### Core Abstractions
+
+**Configuration Schema Hierarchy**
+```
+PluginConfig
+├── preset?: string
+├── presets?: Record<string, Preset>
+├── agents?: Record<string, AgentOverrideConfig>
+├── disabled_mcps?: string[]
+├── tmux?: TmuxConfig
+└── background?: BackgroundTaskConfig
+
+AgentOverrideConfig
+├── model?: string
+├── temperature?: number
+├── variant?: string
+├── skills?: string[]
+└── mcps?: string[]
+
+TmuxConfig
+├── enabled: boolean
+├── layout: TmuxLayout
+└── main_pane_size: number
+```
+
+**Agent Names**
+- `ORCHESTRATOR_NAME`: `'orchestrator'`
+- `SUBAGENT_NAMES`: `['explorer', 'librarian', 'oracle', 'designer', 'fixer']`
+- `ALL_AGENT_NAMES`: All agents combined
+- `AGENT_ALIASES`: Legacy name mappings
+
+### Interfaces
+
+**TypeScript Types**
+- `PluginConfig`: Main configuration object
+- `AgentOverrideConfig`: Per-agent configuration overrides
+- `TmuxConfig`: Tmux integration settings
+- `TmuxLayout`: Layout enum (`main-horizontal`, `main-vertical`, `tiled`, `even-horizontal`, `even-vertical`)
+- `Preset`: Named agent configuration presets
+- `AgentName`: Union type of all agent names
+- `McpName`: Union type of available MCPs (`'websearch'`, `'context7'`, `'grep_app'`)
+- `BackgroundTaskConfig`: Background task concurrency settings
+
+**Exported Functions**
+- `loadPluginConfig(directory: string): PluginConfig` - Load and merge all configs
+- `loadAgentPrompt(agentName: string): { prompt?, appendPrompt? }` - Load custom prompts
+- `getAgentOverride(config, name): AgentOverrideConfig | undefined` - Get agent config with alias support
+- `parseList(items, allAvailable): string[]` - Parse wildcard/exclusion lists
+- `getAvailableMcpNames(config?): string[]` - Get enabled MCPs
+- `getAgentMcpList(agentName, config?): string[]` - Get MCPs for specific agent
 
 
 ## Flow
 ## Flow
 
 
-- `loadPluginConfig` is the entry point: it reads `~/.config/opencode/oh-my-opencode-slim.json`, then `<project>/.opencode/oh-my-opencode-slim.json`, deep-merges agents/tmux objects, and replaces top-level arrays with project-specific values.
-- Environment overrides (`OH_MY_OPENCODE_SLIM_PRESET`) are applied after the merge, and any preset name resolves via `config.presets` with a warning if missing.
-- `loadAgentPrompt` layers user-supplied `{agent}.md` and `_append` files from the prompts directory, so custom prompts can replace or extend defaults without touching code.
-- `getAgentMcpList` pulls agent-level overrides (via `getAgentOverride`) before falling back to `DEFAULT_AGENT_MCPS`, and `getAvailableMcpNames` filters the MCP schema by `disabled_mcps`.
+### Configuration Loading Flow
+
+```
+loadPluginConfig(directory)
+│
+├─→ Load user config from ~/.config/opencode/oh-my-opencode-slim.json
+│   └─→ Validate with PluginConfigSchema
+│       └─→ Return null if invalid/missing
+│
+├─→ Load project config from <directory>/.opencode/oh-my-opencode-slim.json
+│   └─→ Validate with PluginConfigSchema
+│       └─→ Return null if invalid/missing
+│
+├─→ Deep merge configs (project overrides user)
+│   ├─→ Top-level: project replaces user
+│   └─→ Nested (agents, tmux): deep merge
+│
+├─→ Apply environment preset override (OH_MY_OPENCODE_SLIM_PRESET)
+│
+└─→ Resolve and merge preset
+    ├─→ Find preset in config.presets[preset]
+    ├─→ Deep merge preset agents with root agents
+    └─→ Warn if preset not found
+```
+
+### Prompt Loading Flow
+
+```
+loadAgentPrompt(agentName)
+│
+├─→ Check ~/.config/opencode/oh-my-opencode-slim/{agentName}.md
+│   └─→ If exists → read as replacement prompt
+│
+└─→ Check ~/.config/opencode/oh-my-opencode-slim/{agentName}_append.md
+    └─→ If exists → read as append prompt
+```
+
+### MCP Resolution Flow
+
+```
+getAgentMcpList(agentName, config)
+│
+├─→ Get agent override config (with alias support)
+│
+├─→ If agent has explicit mcps config
+│   └─→ Return parseList(agent.mcps, availableMcps)
+│
+└─→ Otherwise return DEFAULT_AGENT_MCPS[agentName]
+```
+
+### Deep Merge Algorithm
+
+```
+deepMerge(base, override)
+│
+├─→ If base is undefined → return override
+├─→ If override is undefined → return base
+│
+└─→ For each key in override
+    ├─→ If both values are non-array objects
+    │   └─→ Recursively deepMerge
+    └─→ Otherwise → override replaces base
+```
 
 
 ## Integration
 ## Integration
 
 
-- `src/index.ts` invokes `loadPluginConfig` early in startup to feed runtime contexts (including tmux config) and imports `TmuxConfig` via re-export from `src/config/index.ts`.
-- `src/config/index.ts` re-exports constants, schema types, loaders, and `getAgentOverride`, so any other workspace module needing config metadata or validators consumes this folder as a single surface.
-- Defaults from `constants.ts` (poll intervals, `DEFAULT_MODELS`, agent aliases) propagate to orchestrator/subagent bootstrap and keep behavior consistent even when user configs are absent.
+### Dependencies
+
+**External Dependencies**
+- `zod`: Runtime schema validation
+- `node:fs`, `node:os`, `node:path`: File system operations
+
+**Internal Dependencies**
+- None (this is a leaf module)
+
+### Consumers
+
+**Direct Consumers**
+- `src/index.ts` - Main plugin entry point
+- `src/skills/` - Agent skill implementations
+- `src/agent/` - Agent configuration and initialization
+
+**Configuration Usage Patterns**
+
+1. **Plugin Initialization**
+   ```typescript
+   const config = loadPluginConfig(projectDir);
+   ```
+
+2. **Agent Configuration**
+   ```typescript
+   const agentOverride = getAgentOverride(config, agentName);
+   const model = agentOverride?.model ?? DEFAULT_MODELS[agentName];
+   ```
+
+3. **MCP Assignment**
+   ```typescript
+   const mcps = getAgentMcpList(agentName, config);
+   ```
+
+4. **Prompt Customization**
+   ```typescript
+   const { prompt, appendPrompt } = loadAgentPrompt(agentName);
+   ```
+
+### Constants Usage
+
+**Polling Configuration**
+- `POLL_INTERVAL_MS` (500ms): Standard polling interval
+- `POLL_INTERVAL_SLOW_MS` (1000ms): Slower polling for background tasks
+- `POLL_INTERVAL_BACKGROUND_MS` (2000ms): Background task polling
+
+**Timeouts**
+- `DEFAULT_TIMEOUT_MS` (2 minutes): Default operation timeout
+- `MAX_POLL_TIME_MS` (5 minutes): Maximum polling duration
+
+**Stability**
+- `STABLE_POLLS_THRESHOLD` (3): Number of stable polls before considering state settled
+
+### Default MCP Assignments
+
+| Agent      | Default MCPs                          |
+|------------|---------------------------------------|
+| orchestrator | `['websearch']`                       |
+| designer    | `[]`                                  |
+| oracle      | `[]`                                  |
+| librarian   | `['websearch', 'context7', 'grep_app']` |
+| explorer    | `[]`                                  |
+| fixer       | `[]`                                  |
+
+### Default Models
+
+| Agent      | Model                          |
+|------------|--------------------------------|
+| orchestrator | `kimi-for-coding/k2p5`        |
+| oracle      | `openai/gpt-5.2-codex`        |
+| librarian   | `openai/gpt-5.1-codex-mini`   |
+| explorer    | `openai/gpt-5.1-codex-mini`   |
+| designer    | `kimi-for-coding/k2p5`        |
+| fixer       | `openai/gpt-5.1-codex-mini`   |
+
+## File Organization
+
+```
+src/config/
+├── index.ts          # Public API exports
+├── loader.ts         # Config loading and merging logic
+├── schema.ts         # Zod schemas and TypeScript types
+├── constants.ts      # Agent names, defaults, timeouts
+├── utils.ts          # Helper functions (agent overrides)
+└── agent-mcps.ts     # MCP configuration and resolution
+```
+
+## Error Handling
+
+**Configuration Loading**
+- Missing config files: Returns empty config (expected behavior)
+- Invalid JSON: Logs warning, returns null
+- Schema validation failure: Logs detailed error, returns null
+- File read errors (non-ENOENT): Logs warning, returns null
+
+**Prompt Loading**
+- Missing prompt files: Returns empty object (expected behavior)
+- File read errors: Logs warning, continues
+
+**Preset Resolution**
+- Invalid preset name: Logs warning with available presets, continues without preset
+
+## Extension Points
+
+**Adding New Agents**
+1. Add to `SUBAGENT_NAMES` in `constants.ts`
+2. Add default model to `DEFAULT_MODELS`
+3. Add default MCPs to `DEFAULT_AGENT_MCPS` in `agent-mcps.ts`
+
+**Adding New MCPs**
+1. Add to `McpNameSchema` enum in `schema.ts`
+2. Update `DEFAULT_AGENT_MCPS` as needed
+
+**Adding New Configuration Options**
+1. Add to `PluginConfigSchema` in `schema.ts`
+2. Update deep merge logic in `loader.ts` if nested
+3. Document in user-facing config documentation

+ 342 - 17
src/tools/codemap.md

@@ -1,29 +1,354 @@
-# src/tools/
-
-The `src/tools/` directory exposes the command-and-control helpers agents rely on when they need to search the repository (grep/AST), interrogate the language server, or orchestrate long-running background work.
+# src/tools/ Codemap
 
 
 ## Responsibility
 ## Responsibility
 
 
-- `index.ts` re-exports the AST-grep helpers, RG-backed `grep`, LSP helpers, and the quota tool so that callers can import a single entry point for tooling.
-- `background.ts` wires up the `background_task`, `background_output`, and `background_cancel` tools that plugin agents use to launch, monitor, and cancel background jobs (sync or async) while automatically managing sessions and metadata.
+The `src/tools/` directory provides the core tool implementations for the oh-my-opencode-slim plugin. It exposes three main categories of tools:
+
+1. **Grep** - Fast regex-based content search using ripgrep (with fallback to system grep)
+2. **LSP** - Language Server Protocol integration for code intelligence (definition, references, diagnostics, rename)
+3. **AST-grep** - AST-aware structural code search and replacement across 25 languages
+4. **Background Tasks** - Fire-and-forget agent task management with automatic notification
+
+These tools are consumed by the OpenCode plugin system and exposed to AI agents for code navigation, analysis, and modification tasks.
+
+---
 
 
 ## Design
 ## Design
 
 
-- Tools are built via `@opencode-ai/plugin`'s `tool` schema; each tool declares arguments/descriptions plus an `execute` body that is sandboxed by the plugin framework.
-- `background_task` supports both async launches (delegating to `BackgroundTaskManager.launch`) and a sync path that pipelines through helper functions (`resolveSessionId`, `sendPrompt`, `pollSession`, `extractResponseText`).
-- Session helpers encapsulate concerns like reusing parent directories, applying agent variants (via `applyAgentVariant`), disabling recursive tools in prompts, and formatting responses with `<task_metadata>` for consumers.
-- Polling uses configuration constants (`MAX_POLL_TIME_MS`, `POLL_INTERVAL_MS`, `STABLE_POLLS_THRESHOLD`) to decide when a session has stabilized, while cancel/output helpers rely on the `BackgroundTaskManager` API.
+### Architecture Overview
+
+```
+src/tools/
+├── index.ts              # Central export point
+├── background.ts         # Background task tools
+├── grep/                 # Regex search (ripgrep-based)
+│   ├── cli.ts           # CLI execution layer
+│   ├── tools.ts         # Tool definition
+│   ├── types.ts         # TypeScript interfaces
+│   ├── utils.ts         # Output formatting
+│   ├── constants.ts     # Safety limits & CLI resolution
+│   └── downloader.ts    # Binary auto-download
+├── lsp/                  # Language Server Protocol
+│   ├── client.ts        # LSP client & connection pooling
+│   ├── tools.ts         # 4 tool definitions
+│   ├── types.ts         # LSP type re-exports
+│   ├── utils.ts         # Formatters & workspace edit application
+│   ├── config.ts        # Server discovery & language mapping
+│   └── constants.ts     # Built-in server configs
+└── ast-grep/            # AST-aware search
+    ├── cli.ts           # CLI execution layer
+    ├── tools.ts         # 2 tool definitions
+    ├── types.ts         # TypeScript interfaces
+    ├── utils.ts         # Output formatting & hints
+    ├── constants.ts     # CLI resolution & environment checks
+    └── downloader.ts    # Binary auto-download
+```
+
+### Key Patterns
+
+#### 1. Tool Definition Pattern
+All tools follow the OpenCode plugin tool schema:
+```typescript
+export const toolName: ToolDefinition = tool({
+  description: string,
+  args: { /* Zod schema */ },
+  execute: async (args, context) => { /* implementation */ }
+});
+```
+
+#### 2. CLI Abstraction Layer
+Both `grep/` and `ast-grep/` use a similar CLI execution pattern:
+- **cli.ts**: Low-level subprocess spawning with timeout handling
+- **tools.ts**: High-level tool definitions that call CLI functions
+- **constants.ts**: CLI path resolution with fallback chain
+- **downloader.ts**: Binary auto-download for missing dependencies
+
+#### 3. Connection Pooling (LSP)
+The LSP module implements a singleton `LSPServerManager` with:
+- **Connection pooling**: Reuse LSP clients per workspace root
+- **Reference counting**: Track active usage
+- **Idle cleanup**: Auto-shutdown after 5 minutes of inactivity
+- **Initialization tracking**: Prevent concurrent initialization
+
+#### 4. Safety Limits
+All tools enforce strict safety limits:
+- **Timeout**: 60s (grep), 300s (ast-grep, LSP)
+- **Output size**: 10MB (grep), 1MB (ast-grep)
+- **Match limits**: 500 matches (grep), 200 diagnostics/references (LSP)
+- **Depth limits**: 20 directories (grep)
+
+#### 5. Error Handling
+- Graceful degradation (ripgrep → grep fallback)
+- Clear error messages with installation hints
+- Timeout handling with process cleanup
+- Truncation detection and reporting
+
+---
 
 
 ## Flow
 ## Flow
 
 
-- `background_task` validates `toolContext`, then either launches a background job through `manager.launch` (async) or calls `executeSync` (sync).
-- `executeSync`: resolve/create a session, send the agent prompt (with recursive tools disabled), poll the session status/messages until idle/stable, fetch messages, extract assistant parts, and wrap the final text with metadata before returning.
-- `background_output` fetches stored task state via `manager.getResult`, summarizes metadata/duration, and appends raw result or error depending on the task status.
-- `background_cancel` pauses ongoing tasks either globally (`all=true`) or for a specific `task_id` by delegating to `manager.cancel`.
+### Grep Tool Flow
+
+```
+User Request
+    ↓
+grep tool (tools.ts)
+    ↓
+runRg() (cli.ts)
+    ↓
+resolveGrepCli() (constants.ts)
+    ├─→ OpenCode bundled rg
+    ├─→ System PATH rg
+    ├─→ Cached download
+    └─→ System grep (fallback)
+    ↓
+buildArgs() → Safety flags + user options
+    ↓
+spawn([cli, ...args]) with timeout
+    ↓
+parseOutput() → GrepMatch[]
+    ↓
+formatGrepResult() (utils.ts)
+    ↓
+Group by file → Return formatted output
+```
+
+### LSP Tool Flow
+
+```
+User Request (e.g., lsp_goto_definition)
+    ↓
+Tool definition (tools.ts)
+    ↓
+withLspClient() (utils.ts)
+    ├─→ findServerForExtension() (config.ts)
+    │   ├─→ Match extension to BUILTIN_SERVERS
+    │   └─→ isServerInstalled() → PATH check
+    ├─→ findWorkspaceRoot() → .git, package.json, etc.
+    └─→ lspManager.getClient() (client.ts)
+        ├─→ Check cache (root::serverId)
+        ├─→ If cached: increment refCount, return
+        └─→ If new:
+            ├─→ new LSPClient(root, server)
+            ├─→ client.start() → spawn server
+            ├─→ client.initialize() → LSP handshake
+            └─→ Store in pool with refCount=1
+    ↓
+client.definition() / references() / diagnostics() / rename()
+    ├─→ openFile() → textDocument/didOpen
+    └─→ Send LSP request
+    ↓
+Format result (formatLocation, formatDiagnostic, etc.)
+    ↓
+lspManager.releaseClient() → decrement refCount
+    ↓
+Return formatted output
+```
+
+**LSP Client Lifecycle:**
+```
+start()
+  ├─→ spawn(command)
+  ├─→ Create JSON-RPC connection (vscode-jsonrpc)
+  ├─→ Register handlers (diagnostics, configuration)
+  └─→ Wait for process to stabilize
+    ↓
+initialize()
+  ├─→ sendRequest('initialize', capabilities)
+  └─→ sendNotification('initialized')
+    ↓
+[Operational phase]
+  ├─→ openFile() → textDocument/didOpen
+  ├─→ definition() / references() / diagnostics() / rename()
+  └─→ Receive notifications (diagnostics)
+    ↓
+stop()
+  ├─→ sendRequest('shutdown')
+  ├─→ sendNotification('exit')
+  └─→ kill process
+```
+
+### AST-grep Tool Flow
+
+```
+User Request (ast_grep_search or ast_grep_replace)
+    ↓
+Tool definition (tools.ts)
+    ↓
+runSg() (cli.ts)
+    ├─→ getAstGrepPath()
+    │   ├─→ Check cached path
+    │   ├─→ findSgCliPathSync()
+    │   │   ├─→ Cached binary
+    │   │   ├─→ @ast-grep/cli package
+    │   │   ├─→ Platform-specific package
+    │   │   └─→ Homebrew (macOS)
+    │   └─→ ensureAstGrepBinary() → download if missing
+    └─→ Build args: pattern, lang, rewrite, globs, paths
+    ↓
+spawn([sg, 'run', '-p', pattern, '--lang', lang, ...])
+    ↓
+Parse JSON output → CliMatch[]
+    ↓
+Handle truncation (max_output_bytes, max_matches)
+    ↓
+formatSearchResult() / formatReplaceResult() (utils.ts)
+    ├─→ Group by file
+    ├─→ Truncate long text
+    └─→ Add summary
+    ↓
+Add empty result hints (getEmptyResultHint)
+    ↓
+Return formatted output
+```
+
+### Background Task Flow
+
+```
+User Request (background_task)
+    ↓
+Tool definition (background.ts)
+    ↓
+manager.launch()
+    ├─→ Create task with unique ID
+    ├─→ Store in BackgroundTaskManager
+    └─→ Return task_id immediately (~1ms)
+    ↓
+[Background execution]
+    ├─→ Agent runs independently
+    ├─→ Completes with result/error
+    └─→ Auto-notify parent session
+    ↓
+User Request (background_output)
+    ↓
+manager.getResult(task_id)
+    ├─→ If timeout > 0: waitForCompletion()
+    └─→ Return status/result/error
+    ↓
+User Request (background_cancel)
+    ↓
+manager.cancel(task_id) or manager.cancel(all)
+    └─→ Cancel running tasks only
+```
+
+---
 
 
 ## Integration
 ## Integration
 
 
-- Relies on the plugin `ctx` (session client) to create/get sessions, send prompts, read statuses/messages, and logs via `../utils/logger`.
-- Uses shared configuration across the repo (`../config`, schema definitions, `SUBAGENT_NAMES`, timeouts) plus helper utilities like `applyAgentVariant`/`resolveAgentVariant` to honor agent overrides.
-- Accepts optional `tmuxConfig` and `PluginConfig` so the session creation/prompt logic respects tmux-managed panes and agent variant settings.
-- `index.ts` also exports `antigravity_quota` and the LSP helpers, so higher-level modules can wire grepping, AST-grep, and diagnostics together with background tooling through this directory.
+### Dependencies
+
+#### External Dependencies
+- **@opencode-ai/plugin**: Tool definition schema (`tool`, `ToolDefinition`)
+- **vscode-jsonrpc**: LSP JSON-RPC protocol implementation
+- **vscode-languageserver-protocol**: LSP type definitions
+- **bun**: Subprocess spawning (`spawn`), file operations (`Bun.write`)
+
+#### Internal Dependencies
+- **src/background**: `BackgroundTaskManager` for background task tools
+- **src/config**: `SUBAGENT_NAMES`, `PluginConfig`, `TmuxConfig`
+- **src/utils**: `extractZip` for binary extraction
+
+### Consumers
+
+#### Direct Consumers
+- **src/index.ts**: Main plugin entry point imports all tools
+- **src/cli/index.ts**: CLI entry point may use tools directly
+
+#### Tool Registry
+All tools are exported from `src/tools/index.ts`:
+```typescript
+export { grep } from './grep';
+export { ast_grep_search, ast_grep_replace } from './ast-grep';
+export {
+  lsp_diagnostics,
+  lsp_find_references,
+  lsp_goto_definition,
+  lsp_rename,
+  lspManager,
+} from './lsp';
+export { createBackgroundTools } from './background';
+```
+
+### Configuration
+
+#### LSP Server Configuration
+- **BUILTIN_SERVERS** (lsp/constants.ts): Pre-configured servers for 12 languages
+- **EXT_TO_LANG** (lsp/constants.ts): Extension to language ID mapping
+- **LSP_INSTALL_HINTS** (lsp/constants.ts): Installation instructions per server
+
+#### Grep Configuration
+- **Safety limits** (grep/constants.ts): Max depth, filesize, count, columns, timeout
+- **RG_SAFETY_FLAGS**: `--no-follow`, `--color=never`, `--no-heading`, `--line-number`, `--with-filename`
+- **GREP_SAFETY_FLAGS**: `-n`, `-H`, `--color=never`
+
+#### AST-grep Configuration
+- **CLI_LANGUAGES** (ast-grep/types.ts): 25 supported languages
+- **LANG_EXTENSIONS** (ast-grep/constants.ts): Language to file extension mapping
+- **Safety limits**: Timeout (300s), max output (1MB), max matches (500)
+
+### Binary Management
+
+#### Ripgrep (grep/downloader.ts)
+- **Version**: 14.1.1
+- **Platforms**: darwin-arm64, darwin-x64, linux-arm64, linux-x64, win32-x64
+- **Install location**: `~/.cache/oh-my-opencode-slim/bin/rg` (Linux/macOS), `%LOCALAPPDATA%\oh-my-opencode-slim\bin\rg.exe` (Windows)
+- **Fallback**: System grep if ripgrep unavailable
+
+#### AST-grep (ast-grep/downloader.ts)
+- **Version**: 0.40.0 (synced with @ast-grep/cli package)
+- **Platforms**: darwin-arm64, darwin-x64, linux-arm64, linux-x64, win32-x64, win32-arm64, win32-ia32
+- **Install location**: `~/.cache/oh-my-opencode-slim/bin/sg` (Linux/macOS), `%LOCALAPPDATA%\oh-my-opencode-slim\bin\sg.exe` (Windows)
+- **Fallback**: Manual installation instructions
+
+### Error Handling Integration
+
+All tools follow a consistent error handling pattern:
+1. Try-catch around execution
+2. Return formatted error messages
+3. Include installation hints for missing binaries
+4. Graceful degradation (fallback tools)
+5. Timeout handling with process cleanup
+
+### Performance Considerations
+
+- **Connection pooling**: LSP clients reused across tool calls
+- **Idle cleanup**: LSP clients shutdown after 5 minutes inactivity
+- **Output truncation**: Prevent memory issues with large outputs
+- **Timeout enforcement**: All subprocess operations have timeouts
+- **Caching**: CLI paths cached to avoid repeated filesystem checks
+- **Background tasks**: Fire-and-forget pattern for long-running operations
+
+---
+
+## File-by-File Summary
+
+### Root Level
+- **index.ts**: Central export point for all tools
+- **background.ts**: Background task management (3 tools: launch, output, cancel)
+
+### grep/
+- **index.ts**: Re-exports grep module
+- **cli.ts**: `runRg()`, `runRgCount()` - subprocess execution with timeout
+- **tools.ts**: `grep` tool definition
+- **types.ts**: `GrepMatch`, `GrepResult`, `CountResult`, `GrepOptions`
+- **utils.ts**: `formatGrepResult()` - output formatting
+- **constants.ts**: Safety limits, `resolveGrepCli()`, `resolveGrepCliWithAutoInstall()`
+- **downloader.ts**: `downloadAndInstallRipgrep()`, `getInstalledRipgrepPath()`
+
+### lsp/
+- **index.ts**: Re-exports LSP module and types
+- **client.ts**: `LSPServerManager` (singleton), `LSPClient` class
+- **tools.ts**: 4 tools: `lsp_goto_definition`, `lsp_find_references`, `lsp_diagnostics`, `lsp_rename`
+- **types.ts**: LSP type re-exports from vscode-languageserver-protocol
+- **utils.ts**: `withLspClient()`, formatters, `applyWorkspaceEdit()`
+- **config.ts**: `findServerForExtension()`, `getLanguageId()`, `isServerInstalled()`
+- **constants.ts**: `BUILTIN_SERVERS`, `EXT_TO_LANG`, `LSP_INSTALL_HINTS`, safety limits
+
+### ast-grep/
+- **index.ts**: Re-exports ast-grep module
+- **cli.ts**: `runSg()`, `getAstGrepPath()`, `startBackgroundInit()`
+- **tools.ts**: 2 tools: `ast_grep_search`, `ast_grep_replace`
+- **types.ts**: `CliLanguage`, `CliMatch`, `SgResult`, `CLI_LANGUAGES`
+- **utils.ts**: `formatSearchResult()`, `formatReplaceResult()`, `getEmptyResultHint()`
+- **constants.ts**: `findSgCliPathSync()`, `checkEnvironment()`, safety limits
+- **downloader.ts**: `downloadAstGrep()`, `ensureAstGrepBinary()`, cache management