Browse Source

Update cartography prompt (#88)

Alvin 2 months ago
parent
commit
0778c7c890

+ 0 - 3
.gitignore

@@ -46,9 +46,6 @@ local
 opencode
 oh-my-opencode
 
-# Cartography
-.slim/
-
 # Python
 __pycache__/
 *.py[cod]

+ 121 - 0
.slim/cartography.json

@@ -0,0 +1,121 @@
+{
+  "metadata": {
+    "version": "1.0.0",
+    "last_run": "2026-01-25T21:23:31.047804Z",
+    "root": "/Users/xp/repos/oh-my-opencode-slim",
+    "include_patterns": [
+      "src/**/*.ts",
+      "src/**/*.tsx",
+      "package.json",
+      "tsconfig.json"
+    ],
+    "exclude_patterns": [
+      "**/*.test.ts",
+      "**/*.spec.ts",
+      "tests/**",
+      "__tests__/**",
+      "docs/**",
+      "dist/**",
+      "node_modules/**",
+      "*.md",
+      "LICENSE"
+    ],
+    "exceptions": []
+  },
+  "file_hashes": {
+    "package.json": "61caa0502a04ebbbcec2e594b54bea39",
+    "src/agents/designer.ts": "ea6af83207f143260a775d79ab229407",
+    "src/agents/explorer.ts": "4678dc549476feeb9088149e72bcffdb",
+    "src/agents/fixer.ts": "02aa0b9da795e0aa38c9651fe0c5a8c9",
+    "src/agents/index.ts": "a830fce51b5e44de72845581b08dd707",
+    "src/agents/librarian.ts": "8a85df35044c719b6615d6afdbe26f04",
+    "src/agents/oracle.ts": "d6a40e69fad62a4f95568f3e9314a06a",
+    "src/agents/orchestrator.ts": "74b53f65eed498b9664f11eb4f91761f",
+    "src/background/background-manager.ts": "3c7dac0af2d0223d67ea78c76d543a90",
+    "src/background/index.ts": "c20308c54093f4578e3f5145307e1a42",
+    "src/background/tmux-session-manager.ts": "5a67f78e83aa4f84f491be2633b7af83",
+    "src/cli/config-io.ts": "b4f50950ae59730f9dd899c14a3f17d5",
+    "src/cli/config-manager.ts": "7f2960f55aaebab21d822c586c2b12eb",
+    "src/cli/custom-skills.ts": "3af1341d323e8693610ee5070f388029",
+    "src/cli/index.ts": "afbd341f1c5cdc3566aa0a55ab47439e",
+    "src/cli/install.ts": "e03e50013793299055bd0f3aa24f5457",
+    "src/cli/paths.ts": "7b5c9ce35d55d5e2fdf9f48b759aa323",
+    "src/cli/providers.ts": "e4e819fff7f1854e01461ae42eef4687",
+    "src/cli/skills.ts": "75cb8bcf04dae88cd56772f9c7d01782",
+    "src/cli/system.ts": "15663904f06d63352c49066371c66c0d",
+    "src/cli/types.ts": "8518735f1de623098df620059f9cfe5e",
+    "src/config/agent-mcps.ts": "f65c01e9a29fd9c2ff5658ce30c89f98",
+    "src/config/constants.ts": "4970144850560dae8449e5c0cc5d7cf8",
+    "src/config/index.ts": "7ec846841f7fe8fcc6d4bc5d5120412d",
+    "src/config/loader.ts": "9e60d552a223515b4fc4dd34b2ad0cc2",
+    "src/config/schema.ts": "fbf24c0421bc311120fd76f68af556af",
+    "src/config/utils.ts": "bc3af4a86874329f638a374ac7c00701",
+    "src/hooks/auto-update-checker/cache.ts": "2d49b0e0ea0f1a36b2ae79f43d163b45",
+    "src/hooks/auto-update-checker/checker.ts": "0cd527f77d797a663476224d77ac44f4",
+    "src/hooks/auto-update-checker/constants.ts": "c46dcf24c3184965314f008ede59b7c7",
+    "src/hooks/auto-update-checker/index.ts": "22ff46cdeb63b0ce4fa3a2fa060ca56c",
+    "src/hooks/auto-update-checker/types.ts": "2c4bec82d99722a7e6789029fc6688c5",
+    "src/hooks/index.ts": "85f2c28ccaf0968698a0b8343e3977c3",
+    "src/hooks/phase-reminder/index.ts": "d8c9c5d0f7147e5f44e000303daa6cc2",
+    "src/hooks/post-read-nudge/index.ts": "7463a25eac61ebd8833a44bee60f2d81",
+    "src/index.ts": "b494ac1fce3b86b3c60a8e8e8f613ffd",
+    "src/mcp/context7.ts": "4e02e8ef204b6eb7e99a3209078428b5",
+    "src/mcp/grep-app.ts": "f76cb0ffb3484b16d55f27729e80e864",
+    "src/mcp/index.ts": "d19746215624f8dfdcb21b6a1ad552c0",
+    "src/mcp/types.ts": "a67078f79aa8b99c41fb5be5d9fa9319",
+    "src/mcp/websearch.ts": "a01f59b67867b173919f7a52b7e43052",
+    "src/tools/ast-grep/cli.ts": "77cc479a5dde21188bc90df195a3134b",
+    "src/tools/ast-grep/constants.ts": "ef016f4d4c5a6861fed9c28e968cad07",
+    "src/tools/ast-grep/downloader.ts": "c5b3d9b861acd9d971e5df1f5112b928",
+    "src/tools/ast-grep/index.ts": "842b8f43bd1ebc7e2e33a9f7fa0d3fec",
+    "src/tools/ast-grep/tools.ts": "3f7c2c65cffd5273b0cd6c849800176d",
+    "src/tools/ast-grep/types.ts": "34ad28b5b1e9617b584f082dba9a427c",
+    "src/tools/ast-grep/utils.ts": "1dd3b2133c4b8c847a26eea0423bc0b2",
+    "src/tools/background.ts": "11c0aac39c0346220a55a98d61d89899",
+    "src/tools/grep/cli.ts": "7105badf3f343bce8f0ad547705cbc36",
+    "src/tools/grep/constants.ts": "52f05a89470828582aee209b0c72b01f",
+    "src/tools/grep/downloader.ts": "876022c453c4072f313ddaf7ea595409",
+    "src/tools/grep/index.ts": "20eef5dabac9f703a9c97ffe89ce2f4e",
+    "src/tools/grep/tools.ts": "55d0a611e0e4e1a7612a4dde40b3be51",
+    "src/tools/grep/types.ts": "4b7e3313306e58f2fae265cf0d1c3ed3",
+    "src/tools/grep/utils.ts": "af0426f46b8e5080621adc99b2e496c2",
+    "src/tools/index.ts": "24538b32510bc2f8438d6037dc023540",
+    "src/tools/lsp/client.ts": "445c0c95dce6f6235e85021761fc4bc8",
+    "src/tools/lsp/config.ts": "ebe9cb109e877e5af5cd8580aa0def50",
+    "src/tools/lsp/constants.ts": "37f03eb9604b67b0cfa1b992709c01d6",
+    "src/tools/lsp/index.ts": "65c41604a48c4e4c193c8250812f5080",
+    "src/tools/lsp/tools.ts": "023d712c7a06ab9e43851826114309a0",
+    "src/tools/lsp/types.ts": "8921e8b2874630760f2344f53376aefc",
+    "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/index.ts": "4f84dbeb33eb59ededba98288c436e21",
+    "src/utils/logger.ts": "779c3886f558ddb6a3b268c249ecfc4e",
+    "src/utils/polling.ts": "b1d9c52df1fae7391234d0f5476d53b5",
+    "src/utils/tmux.ts": "f6d6e51b16e19bdebbc60c09f24bdca1",
+    "src/utils/zip-extractor.ts": "9af9d8584db77a5257d333314b48557c",
+    "tsconfig.json": "1d2bb6e93a43366843785a156c8e538a"
+  },
+  "folder_hashes": {
+    "src/hooks/phase-reminder": "0a66b20683c09b9d4af7a81f4036d60b",
+    "src/mcp": "f9241cd556adebddc643d71ee55ee2a8",
+    "src": "c704f69c9f9a2a12b8897287539d70c0",
+    "src/cli": "dbab999877b28320e006f338ab12957b",
+    "src/background": "6bf11cd6942be5be684bbe61e41b283c",
+    "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/hooks": "dab7d541aa73558a8984eb9d9b3c1685",
+    "src/agents": "4f804a51b82dda11e1578d37b223459d",
+    "src/tools": "566ef2faddc0903ac9a7162cc6c34da5"
+  }
+}

+ 30 - 0
codemap.md

@@ -0,0 +1,30 @@
+# Repository Atlas: oh-my-opencode-slim
+
+## 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.
+
+## 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.
+
+## Repository Directory 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/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/cli/` | Installer CLI flow, config edits, provider setup, and skill installation helpers. | [View Map](src/cli/codemap.md) |
+| `src/config/` | Plugin configuration schemas, defaults, loaders, and MCP/agent override helpers. | [View Map](src/config/codemap.md) |
+| `src/hooks/` | Re-exported hook factories and option types for lifecycle hooks. | [View Map](src/hooks/codemap.md) |
+| `src/hooks/auto-update-checker/` | Startup update check hook with cache invalidation and optional auto-install. | [View Map](src/hooks/auto-update-checker/codemap.md) |
+| `src/hooks/phase-reminder/` | Orchestrator message transform hook that injects phase reminders. | [View Map](src/hooks/phase-reminder/codemap.md) |
+| `src/hooks/post-read-nudge/` | Read tool after-hook that appends delegation nudges. | [View Map](src/hooks/post-read-nudge/codemap.md) |
+| `src/mcp/` | Built-in MCP registry and config types for remote connectors. | [View Map](src/mcp/codemap.md) |
+| `src/tools/` | Tool registry plus background task tool implementations. | [View Map](src/tools/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/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) |

+ 26 - 0
src/agents/codemap.md

@@ -0,0 +1,26 @@
+# src/agents/
+
+## 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.
+
+## 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.
+
+## 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`.
+
+## 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.

+ 23 - 0
src/background/codemap.md

@@ -0,0 +1,23 @@
+# src/background/
+
+## 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.
+
+## 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`).
+
+## 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`).
+
+## 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`).

+ 21 - 0
src/cli/codemap.md

@@ -0,0 +1,21 @@
+# src/cli/
+
+## 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`).
+
+## 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.
+
+## 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.

+ 24 - 0
src/codemap.md

@@ -0,0 +1,24 @@
+# src/
+
+## Responsibility
+- `src/index.ts` delivers the oh-my-opencode-slim plugin by merging configuration, instantiating orchestrator/subagent definitions, wiring background managers, tmux helpers, built-in tools, MCPs, and lifecycle hooks so OpenCode sees a single cohesive module.
+- `config/`, `agents/`, `tools/`, `background/`, `hooks/`, and `utils/` contain the reusable building blocks (loader/schema/constants, agent factories/permission helpers, tool factories, background polling/session managers, hook implementations, and tmux/variant/log helpers) that power that entry point.
+- `cli/` exposes the install/update script (argument parsing + interactive prompts) that edits OpenCode config, installs recommended/custom skills, and updates provider credentials to bootstrap this plugin on a host machine.
+
+## Design
+- Agent creation follows explicit factories (`agents/index.ts`, per-agent creators under `agents/`) with override/permission helpers (`config/utils.ts`, `cli/skills.ts`) so defaults live in `config/constants.ts`, prompts can be swapped via `config/loader.ts`, and variant labels propagate through `utils/agent-variant.ts`.
+- Background tooling composes `BackgroundTaskManager`, `TmuxSessionManager`, and `createBackgroundTools` (which uses `tool` with Zod schemas) to provide async/sync task launches plus cancel/output helpers; polling/prompt flow lives in `tools/background.ts` while TMUX lifecycle uses `utils/tmux.ts` to spawn/close panes and reapply layouts.
+- Hooks are isolated (`hooks/auto-update-checker`, `phase-reminder`, `post-read-nudge`) and exported via `hooks/index.ts`, so the plugin simply registers them via the `event`, `experimental.chat.messages.transform`, and `tool.execute.after` hooks defined in `index.ts`.
+- Supplemental tools (`tools/grep`, `tools/lsp`, `tools/quota`) bundle ripgrep, LSP helpers, and Antigravity quota calls behind the OpenCode `tool` interface and are mounted in `index.ts` alongside background/task tools.
+
+## Flow
+- Startup: `index.ts` calls `loadPluginConfig` (user + project JSON + presets) to build a `PluginConfig`, passes it to `getAgentConfigs` (which uses `createAgents`, agent factories, `loadAgentPrompt`, and `getAgentMcpList`) and to `BackgroundTaskManager`/`TmuxSessionManager`/`createBackgroundTools` so the in-memory state matches user overrides.
+- Plugin registration: `index.ts` registers agents, the tool map (background/task, `grep`, `ast_grep_*`, `lsp_*`, `antigravity_quota`), MCP definitions (`createBuiltinMcps`), and hooks (`createAutoUpdateCheckerHook`, `createPhaseReminderHook`, `createPostReadNudgeHook`); configuration hook merges those values back into the OpenCode config (default agent, permission rules parsed from `config/agent-mcps`, and MCP access policies).
+- Runtime: `BackgroundTaskManager.launch` spins up sessions and prompts agents via the OpenCode client, `pollTask`/`pollSession` watch for idle status before resolving results, while `TmuxSessionManager` observes `session.created` events to spawn panes via `utils/tmux` and close them when sessions idle or time out; tool hooks prevent recursion by toggling `background_task/task` permission when sending prompts.
+- CLI flow: `cli/install.ts` parses flags, optionally asks interactive prompts, checks OpenCode installation, adds plugin entries via `cli/config-manager.ts`, disables default agents, writes the lite config (`cli/config-io.ts`), and installs skills (`cli/skills.ts`, `cli/custom-skills.ts`).
+
+## Integration
+- Connects directly to the OpenCode plugin API (`@opencode-ai/plugin`): registers agents/tools/mcps, responds to `session.created` and `tool.execute.after` events, injects `experimental.chat.messages.transform`, and makes RPC calls via `ctx.client`/`ctx.client.session` throughout `tools/background` and `background/*`.
+- Integrates with the host environment: `utils/tmux.ts` checks for tmux and server availability, `startTmuxCheck` pre-seeds the binary path, and `TmuxSessionManager`/`BackgroundTaskManager` coordinate via shared configuration and `tools/background` to keep CLI panes synchronized.
+- Hooks and helpers tie into external behavior: `hooks/auto-update-checker` reads `package.json` metadata, runs safe `bun install`, and posts toasts; `hooks/phase-reminder/post-read-nudge` enforce workflow reminders; `utils/logger.ts` centralizes structured logging used across modules.
+- CLI utilities modify OpenCode CLI/user config files (`cli/config-manager.ts`) and install additional skills/ providers, ensuring the plugin lands with the expected agents, provider auth helpers, and custom skill definitions.

+ 28 - 0
src/config/codemap.md

@@ -0,0 +1,28 @@
+# 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.
+
+## 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.
+
+## 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.
+
+## 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`.
+
+## 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.

+ 28 - 0
src/hooks/auto-update-checker/codemap.md

@@ -0,0 +1,28 @@
+# src/hooks/auto-update-checker/
+
+## Responsibility
+
+- Provides an OpenCode hook that reacts to `session.created`, ensures the hook only runs once per startup, and surfaces update information to the user via TUI toasts and logs.
+- Detects local development builds, cached installs, and running plugins pinned to specific versions so the hook can decide whether to notify, auto-update, or skip work.
+
+## Design
+
+- `index.ts` orchestrates the hook lifecycle: it filters session events, defers the heavy work via `setTimeout`, and delegates version discovery and updates to helper functions while respecting the user’s `autoUpdate` and `showStartupToast` preferences.
+- `checker.ts` encapsulates environment-aware utilities (config path discovery, local dev detection, NPM registry fetching, and pinned-version mutation) plus memoized cache lookups so the hook can derive current, cached, and latest versions without duplicating logic.
+- `cache.ts` is responsible for invalidating cached installs (`node_modules`, `package.json`, `bun.lock`) before a fresh `bun install`, keeping the cached package state consistent with the server-provided latest version.
+- Shared `constants.ts` standardizes paths (cache directory, config locations, package name, registry URL) and fetch timeouts so the rest of the hook is configuration-free.
+
+## Flow
+
+- On the first `session.created` event without a parent session, `createAutoUpdateCheckerHook` schedules `runBackgroundUpdateCheck` while immediately showing an initial toast (unless disabled) and short-circuiting for local dev builds.
+- `runBackgroundUpdateCheck` resolves the current plugin entry and cached version, determines the update channel via `extractChannel`, retrieves the latest dist-tag from `getLatestVersion`, and compares versions.
+- When an update is available, the hook either notifies the user or, if `autoUpdate` is on, updates the pinned entry in the OpenCode config (`updatePinnedVersion`), invalidates the cached package, and runs `bun install` safely (`runBunInstallSafe`) with a 60-second timeout before showing success/error toasts.
+- `checker.ts` supports the above flow with helpers (`getLocalDevVersion`, `findPluginEntry`, `getCachedVersion`, `extractChannel`, etc.) that read configs (`.opencode/*.jsonc`, global config paths) via `stripJsonComments` and `fs` operations.
+- `cache.ts` runs before reinstall to remove lingering plugin directories, dependency entries, and JSON-formatted `bun.lock` references, ensuring `runBunInstallSafe` operates on a clean slate.
+
+## Integration
+
+- Hooks into the OpenCode plugin lifecycle via `ctx.client.tui.showToast` and the `session.created` event, leveraging `PluginInput` to know the working directory and show UI feedback.
+- Reads OpenCode configuration files exposed by `../../cli/config-manager` to locate plugin entries, pinned versions, and local `file://` installs, so it stays aligned with the same config sources that enable plugin loading.
+- Uses shared `../../utils/logger` for tracing background operations and errors while talking to platform APIs (`fetch`, `Bun.spawn`, `fs`) to inspect, mutate, and reinstall the `oh-my-opencode-slim` package stored under `CACHE_DIR`.
+- Exposes `AutoUpdateCheckerOptions` for consumers (via `index.ts`) to opt out of toasts or automatic installs while still reusing the same checker/cache helpers.

+ 21 - 0
src/hooks/codemap.md

@@ -0,0 +1,21 @@
+# src/hooks/
+
+This directory exposes the public hook entry points that feature code imports to tap into behavior such as update checks, phase reminders, and post-read nudges.
+
+## Responsibility
+
+It acts as a single entry point that re-exports the factory functions and option types for every hook implementation underneath `src/hooks/`, so other modules can `import { createAutoUpdateCheckerHook, AutoUpdateCheckerOptions } from 'src/hooks'` without needing to know the subpaths.
+
+## Design
+
+- Aggregator/re-export pattern: `index.ts` consolidates factories (`createAutoUpdateCheckerHook`, `createPhaseReminderHook`, `createPostReadNudgeHook`) and the shared `AutoUpdateCheckerOptions` type so the rest of the app depends only on this flat namespace.
+- Each hook implementation underneath follows a factory-based design; callers receive a configured hook instance by passing structured options through the exported creator functions.
+
+## Flow
+
+Callers import a factory from `src/hooks`, supply any typed options (e.g., `AutoUpdateCheckerOptions`), and the factory wires together the hook’s internal checks/side-effects before returning the hook interface that the feature layer consumes.
+
+## Integration
+
+- Feature modules across the app import everything through `src/hooks/index.ts`; there are no direct relations to deeper hook files, keeping consumers ignorant of the implementation details.
+- Option types such as `AutoUpdateCheckerOptions` are shared from this file so both the hook creator and its consumers agree on the configuration contract.

File diff suppressed because it is too large
+ 19 - 0
src/hooks/phase-reminder/codemap.md


+ 19 - 0
src/hooks/post-read-nudge/codemap.md

@@ -0,0 +1,19 @@
+# src/hooks/post-read-nudge/
+
+<!-- Explorer: Fill in this section with architectural understanding -->
+
+## Responsibility
+
+Provide a lightweight safety net that reminds agents to stay in the delegation workflow whenever they read project files. When the Read tool emits output, this hook appends a standardized nudge so that follow-up work is routed to the right specialists instead of being solved immediately.
+
+## Design
+
+Exports a single factory (`createPostReadNudgeHook`) that returns a handler map for the `tool.execute.after` event. The hook keeps a shared `NUDGE` constant and enforces a policy guard (`input.tool === 'Read' || input.tool === 'read'`) before mutating the `output`. This keeps the implementation focused and pluggable inside the broader hook registry.
+
+## Flow
+
+The hook is instantiated once and registered with the hook system, which invokes `tool.execute.after` after every tool call. When the Read tool completes, the hook sees the input metadata, verifies the tool name, and appends the reminder text to `output.output`, thereby altering the user-facing response before it bubbles back to the agent.
+
+## Integration
+
+Plugged into the global hook registry, this module intercepts every tool response via the `tool.execute.after` lifecycle event. It directly touches only the Read tool’s output object so there are no downstream dependencies, but the appended reminder influences all downstream consumers who display read results.

+ 25 - 0
src/mcp/codemap.md

@@ -0,0 +1,25 @@
+# src/mcp/
+
+<!-- Explorer: Fill in this section with architectural understanding -->
+
+## Responsibility
+
+- Define and expose the built-in MCP endpoints (websearch, context7, grep.app) alongside the shared type aliases so the application can treat remote and local MCPs uniformly (`src/mcp/index.ts`, `src/mcp/types.ts`).
+- Provide a single entry point (`createBuiltinMcps`) for instantiating the default connectors while honoring feature flags/disabled lists.
+
+## Design
+
+- `types.ts` defines the discriminated union `McpConfig` with `RemoteMcpConfig` and `LocalMcpConfig`, keeping the shape of every connector explicit and easy to validate at compile time.
+- Each service file exports a `RemoteMcpConfig` literal that points at the remote URL and optionally supplies headers derived from the corresponding environment variable to avoid leaking secrets (`websearch.ts`, `context7.ts`, `grep-app.ts`).
+- `index.ts` aggregates the built-in configs in a `Record<McpName, McpConfig>` and exposes helpers/types for external consumers, keeping the set of hard-coded MCPs centralized.
+
+## Flow
+
+- On startup `createBuiltinMcps` iterates over the in-module registry and filters out any MCP listed in `disabled_mcps`, returning the remaining configs as a string-keyed record for the higher-level stack (`src/index.ts`).
+- Each remote config is evaluated eagerly, so the only per-request variability is the `disabled_mcps` list and the presence of environment-provided API keys for headers.
+
+## Integration
+
+- `src/index.ts` imports `createBuiltinMcps` to construct the MCP map used by the runtime, passing the user/cli-configured `disabled_mcps` array.
+- Types exported from `src/mcp/types.ts` are re-exported by `src/mcp/index.ts`, letting other modules reference `McpConfig`, `LocalMcpConfig`, and `RemoteMcpConfig` without reaching into individual files.
+- Remote configs are pure data objects consumed by the runtime's MCP execution layer (via the `McpConfig` contract) and depend only on environment-provided credentials and the URLs defined here.

+ 38 - 8
src/skills/cartography/SKILL.md

@@ -37,7 +37,7 @@ If it **doesn't exist**: Continue to Step 2 (Initialize).
 
 ```bash
 python3 ~/.config/opencode/skills/cartography/scripts/cartographer.py init \
-  --root /path/to/repo \
+  --root ./ \
   --include "src/**/*.ts" \
   --exclude "**/*.test.ts" --exclude "dist/**" --exclude "node_modules/**"
 ```
@@ -54,7 +54,7 @@ This creates:
 
 ```bash
 python3 ~/.config/opencode/skills/cartography/scripts/cartographer.py changes \
-  --root /path/to/repo
+  --root ./
 ```
 
 2. **Review the output** - It shows:
@@ -68,17 +68,26 @@ python3 ~/.config/opencode/skills/cartography/scripts/cartographer.py changes \
 
 ```bash
 python3 ~/.config/opencode/skills/cartography/scripts/cartographer.py update \
-  --root /path/to/repo
+  --root ./
 ```
 
+### Step 4: Finalize Repository Atlas (Root Codemap)
+
+Once all specific directories are mapped, the Orchestrator must create or update the root `codemap.md`. This file serves as the **Master Entry Point** for any agent or human entering the repository.
+
+1.  **Map Root Assets**: Document the root-level files (e.g., `package.json`, `index.ts`, `plugin.json`) and the project's overall purpose.
+2.  **Aggregate Sub-Maps**: Create a "Repository Directory Map" section. For every folder that has a `codemap.md`, extract its **Responsibility** summary and include it in a table or list in the root map.
+3.  **Cross-Reference**: Ensure that the root map contains the absolute or relative paths to the sub-maps so agents can jump directly to the relevant details.
+
+
 ## Codemap Content
 
-Explorers should write **timeless architectural understanding**, not exact details that get stale:
+Explorers are granted write permissions for `codemap.md` files during this workflow. Use precise technical terminology to document the implementation:
 
-- **Responsibility** - What is this folder's job in the system?
-- **Design** - Key patterns, abstractions, architectural decisions
-- **Flow** - How does data/control flow through this module?
-- **Integration** - How does it connect to other parts of the system?
+- **Responsibility** - Define the specific role of this directory using standard software engineering terms (e.g., "Service Layer", "Data Access Object", "Middleware").
+- **Design Patterns** - Identify and name specific patterns used (e.g., "Observer", "Singleton", "Factory", "Strategy"). Detail the abstractions and interfaces.
+- **Data & Control Flow** - Explicitly trace how data enters and leaves the module. Mention specific function call sequences and state transitions.
+- **Integration Points** - List dependencies and consumer modules. Use technical names for hooks, events, or API endpoints.
 
 Example codemap:
 
@@ -105,3 +114,24 @@ Each agent is a prompt + permission set. Config system uses:
 - Consumed by: Main plugin (src/index.ts)
 - Depends on: Config loader, skills registry
 ```
+
+Example **Root Codemap (Atlas)**:
+
+```markdown
+# Repository Atlas: oh-my-opencode-slim
+
+## Project Responsibility
+A high-performance, low-latency agent orchestration plugin for OpenCode, focusing on specialized sub-agent delegation and background task management.
+
+## System Entry Points
+- `src/index.ts`: Plugin initialization and OpenCode integration.
+- `package.json`: Dependency manifest and build scripts.
+- `oh-my-opencode-slim.json`: User configuration schema.
+
+## Directory Map (Aggregated)
+| Directory | Responsibility Summary | Detailed Map |
+|-----------|------------------------|--------------|
+| `src/agents/` | Defines agent personalities (Orchestrator, Explorer) and manages model routing. | [View Map](src/agents/codemap.md) |
+| `src/features/` | Core logic for tmux integration, background task spawning, and session state. | [View Map](src/features/codemap.md) |
+| `src/config/` | Implements the configuration loading pipeline and environment variable injection. | [View Map](src/config/codemap.md) |
+```

+ 28 - 0
src/tools/ast-grep/codemap.md

@@ -0,0 +1,28 @@
+# src/tools/ast-grep/
+
+## Responsibility
+
+- Wrap the external `ast-grep` CLI so the broader system can invoke AST-aware search and replace without caring about binary discovery or argument details (`cli.ts`, `tools.ts`).
+- Provide well-typed tooling primitives (`types.ts`) plus formatted user output hints/summary helpers (`utils.ts`) that can be re-used by CLI commands or plugin UI layers.
+- Manage the brittle parts of CLI usage: locating a binary from caches, npm packages, or homebrew, downloading platform-specific releases when needed, and surfacing environment status/limits (`constants.ts`, `downloader.ts`).
+
+## Design Patterns and Decisions
+
+- **Singleton initialization with retries:** `getAstGrepPath` caches an init promise so concurrent requests share discovery/download work and fallback from local binaries to downloads (`cli.ts`).
+- **Tool definition as declarative metadata:** `tools.ts` exports `ast_grep_search` and `ast_grep_replace` via the OpenCode tool registry, which keeps descriptions, schemas, and execution logic centralized.
+- **Separation of concerns:** `cli.ts` focuses on process spawning and JSON parsing, `constants.ts` owns binary path resolution plus environment checks/formatting, `utils.ts` formats results while `downloader.ts` handles platform maps, cache directories, and fetch/extraction.
+- **Fail fast with hints:** Empty-match hints tailored per language (e.g., help removing trailing colons in Python) make search UX better while keeping AST requirements explicit.
+
+## Data & Control Flow
+
+- Tools (`ast_grep_search`, `ast_grep_replace`) call `runSg`, populating CLI arguments (pattern, rewrite, globs, context) and routing output through `formatSearchResult`/`formatReplaceResult` before reporting via `showOutputToUser` (`tools.ts`).
+- `runSg` constructs the command, ensures the CLI binary exists (resetting via `getAstGrepPath` which may call `findSgCliPathSync` or trigger a download), spawns the process with timeout handling, and parses compact JSON while guarding against truncated output and CLI errors (`cli.ts`).
+- Binary resolution uses `constants.ts` helpers to detect cached binaries, installed packages, platform-specific packages, or Homebrew paths, and exposes environment checks/formatting to upstream callers (`constants.ts`).
+- `downloader.ts` is the fallback path: it infers the platform key, downloads the matching GitHub release, extracts `sg`, sets executable bits, and caches it under `~/.cache/oh-my-opencode-slim/bin` (or Windows AppData) so subsequent commands reuse the binary.
+
+## Integration Points
+
+- `index.ts` re-exports `ast_grep_search`, `ast_grep_replace`, runtime helpers (`ensureCliAvailable`, `checkEnvironment`, etc.), and downloader utilities so other modules can plug into the tooling layer while sharing diagnostics (`index.ts`).
+- The OpenCode plugin layer imports `builtinTools` from `src/tools/ast-grep/index.ts` to surface search/replace capabilities through the CLI tool registry.
+- `constants.ts` and `downloader.ts` are used by `cli.ts` to decide where to execute `sg`, while environment helpers inform onboarding UIs or setup scripts about missing binaries.
+- `types.ts` defines the shared `CliLanguage`, `CliMatch`, and `SgResult` shapes that drive type safety across CLI invocation, formatting utilities, and tooling schemas.

+ 29 - 0
src/tools/codemap.md

@@ -0,0 +1,29 @@
+# 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.
+
+## 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.
+
+## 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.
+
+## 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`.
+
+## 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.

File diff suppressed because it is too large
+ 19 - 0
src/tools/grep/codemap.md


+ 29 - 0
src/tools/lsp/codemap.md

@@ -0,0 +1,29 @@
+# src/tools/lsp/
+
+## Responsibility
+
+- Encapsulate a minimal LSP client stack so the CLI can ask language servers for definitions, references, diagnostics, and renames without managing subprocesses itself.
+- Provide thin, documented tools (`lsp_goto_definition`, `lsp_find_references`, `lsp_diagnostics`, `lsp_rename`) that compose `withLspClient` helpers with exported plugin schema definitions (see `src/tools/lsp/tools.ts`).
+
+## Design
+
+- `LSPServerManager` in `src/tools/lsp/client.ts` is a singleton connection pool that keys clients by `<workspace-root>::<server-id>`, tracks reference counts, and evicts idle or dead processes.
+- `LSPClient` wears responsibility for spawning the underlying language server (`bun.spawn`), wiring vscode-jsonrpc streams, maintaining opened documents, collecting diagnostics notifications, and gracefully shutting down/ restarting when needed.
+- Utility helpers in `src/tools/lsp/utils.ts` keep formatting, severity mapping, diagnostic filtering, workspace root discovery, URI translation, and workspace-edit application consolidated; they also host `withLspClient`, which orchestrates server lookup, client acquisition/release, and retry messaging when initialization is still in progress.
+- Constants/configuration (`src/tools/lsp/constants.ts`, `src/tools/lsp/config.ts`) define the supported servers, extension-to-language mappings, install hints, and runtime checks for whether the configured binaries exist, so the tools never start a missing server.
+- Shared types from `src/tools/lsp/types.ts` mirror the vscode-languageserver-protocol definitions that both the client and tools consume.
+
+## Flow
+
+1. Tool execution (e.g., `lsp_find_references`) calls `withLspClient` with a file path; `withLspClient` resolves the extension using `findServerForExtension` and either throws an install/configuration error or proceeds.
+2. `withLspClient` asks `lspManager` for a client tied to the workspace root; the manager either reuses an existing `LSPClient` or starts/initializes a new one, waiting on the init promise before handing it back, and increments the reference count.
+3. `LSPClient` ensures the file is open via `textDocument/didOpen` (loading the text, waiting for the server) before sending requests such as `textDocument/definition`, `references`, `diagnostic`, or `rename`; diagnostics request also waits for pending `publishDiagnostics` notifications when the server cannot answer directly.
+4. Responses flow back through `vscode-jsonrpc` and are formatted/filtered by `utils` (`formatLocation`, `filterDiagnosticsBySeverity`, `formatDiagnostic`, etc.), and in the rename path the returned `WorkspaceEdit` is applied locally, with results reported via `formatApplyResult`.
+5. After the tool receives its answer, `withLspClient` releases the client reference; the manager later tears down idle clients or when the process exits.
+
+## Integration
+
+- `src/tools/lsp/index.ts` re-exports the manager and the defined tools/types so other pieces of the CLI can import the LSP surface without touching implementation details.
+- Tools are wired into the plugin layer via `@opencode-ai/plugin/tool`; the exported `ToolDefinition` instances declare arguments, descriptions, and error formatting using helpers from `src/tools/lsp/utils.ts`.
+- `client.ts` depends on `config.ts` and `constants.ts` for language IDs, server configuration, and install hints; `utils.ts` depends on the same modules for severity maps, `findServerForExtension`, and `lspManager`.
+- External callers (e.g., command handlers) simply feed absolute paths and cursor positions into the exported tools; the module reports installation errors, server initialization delays, or successful results back through formatted strings so higher layers can relay them to the user.

+ 29 - 0
src/tools/quota/codemap.md

@@ -0,0 +1,29 @@
+# src/tools/quota/
+
+Responsibility: expose the `antigravity_quota` tool that reads locally configured Antigravity/Gemini accounts, refreshes Google OAuth tokens, polls the Cloud Code quota endpoints, and formats a compact progress-bar view of each model’s remaining quota so OpenCode can present it on demand. The folder also prepares the desktop command file (`command.ts`) that surfaces the tool name, description, and invocation example for users.
+
+## Responsibility
+
+- Coordinates quota-checking for every account listed in the user’s Antigravity config, shielding the rest of the app from the OAuth/token refresh, quota fetching, and model filtering logic.
+
+## Design
+
+- `src/tools/quota/api.ts` contains the low-level orchestration: loading config paths defined relative to platform-specific config/data directories, refreshing tokens via `https://oauth2.googleapis.com/token`, optionally discovering a project via `loadCodeAssist`, and calling Cloud Code’s `fetchAvailableModels`. Results are normalized into `ModelQuota` objects (see `types.ts`) with percent completed, reset timers, and sorted names.
+- `src/tools/quota/index.ts` wraps the API in the OpenCode plugin tool (`tool({ ... execute() { ... } })`), handles errors, provides deterministic defaults (e.g., fake `account-1` email), groups models into the Claude/Flash/Pro families, renders ASCII progress bars, and emits the quoted output block that must be displayed verbatim.
+- `command.ts` ensures the contextual command file describing `antigravity_quota()` exists under the OpenCode command cache so the CLI can present the tool description and usage to users.
+- Reusable types (`Account`, `AccountsConfig`, `ModelQuota`, etc.) live in `types.ts` and keep the API and tool layers aligned on data shapes.
+
+## Flow
+
+1. At runtime the tool loads `antigravity-accounts.json` from one of the configured paths; if missing, the tool immediately reports the paths it checked.
+2. Each account’s refresh token is exchanged for an access token (`refreshToken`). If no `projectId` is provided, `loadCodeAssist` can supply one via the Cloud AI companion project metadata.
+3. `fetchAvailableModels` returns quota data; entries matching the `EXCLUDED_PATTERNS` blacklist are dropped, the remaining ones are clamped to 0–100%, and their reset times are turned into human-friendly durations (`formatDuration`).
+4. The tool groups models by quota family, computes padded names/pct values, renders `[filled/empty]` bars, and builds a `blocks` array that is ultimately joined into the final output string, prefixed with an error section if any accounts failed.
+5. `command.ts` complements this flow by ensuring the CLI knows about `antigravity_quota` via the generated Markdown file so users can discover it.
+
+## Integration
+
+- Plugin registration: `index.ts` exports `antigravity_quota` via `tool` from `@opencode-ai/plugin`, making the quota view callable through OpenCode’s CLI/API surface.
+- Config/read access: `api.ts` relies on `CONFIG_PATHS` derived from `os.platform()` and XDG conventions, reading `antigravity-accounts.json` and expecting `Account` objects with refresh tokens and optional project IDs.
+- HTTP dependencies: every account invocation hits Google’s OAuth token endpoint and the CloudCode quota endpoints, so the tool depends on network connectivity and the `fetch` global (Node 18+ or polyfilled environment).
+- Command discovery: `command.ts` writes to the user’s `~/.config/opencode/command/antigravity-quota.md` (or `%APPDATA%` on Windows) so the CLI automatically lists the tool and instructs on using `antigravity_quota()` without needing to inspect the code.

File diff suppressed because it is too large
+ 19 - 0
src/utils/codemap.md