# opencode-ultra

> **Disclaimer**: This project is not built by or affiliated with the [OpenCode](https://github.com/anomalyco/opencode) team.
> It is a community-built plugin forked from [oh-my-opencode](https://github.com/code-yeongyu/oh-my-opencode).

A lightweight OpenCode 1.2.x plugin that provides multi-agent orchestration, keyword-driven mode switching, rules injection, session continuity, AST search, and self-improvement (evolve) in a single plugin.

## Install

```bash
# In your OpenCode plugin directory
bun add opencode-ultra
```

Register in `opencode.jsonc`:

```jsonc
{
  "plugins": ["opencode-ultra"]
}
```

## Features

### Tools (12)

| Tool | Description |
|------|-------------|
| `spawn_agent` | Parallel agent execution (ConcurrencyPool + spawn limit + timeout + sanitizer) |
| `ralph_loop` | Autonomous loop execution (completion detection via `<promise>DONE</promise>`, per-iteration timeout) |
| `cancel_ralph` | Cancel a running Ralph Loop |
| `batch_read` | Parallel multi-file reading (max 20) |
| `ledger_save` | Save Continuity Ledger (.opencode/ledgers/) |
| `ledger_load` | Load Continuity Ledger (by name or latest) |
| `ast_search` | AST-aware code search (uses ast-grep/sg binary, auto-skips if not installed) |
| `evolve_apply` | Trust score evaluation + auto-apply plugin recommendations to OpenCode config (dry-run/backup) |
| `evolve_scan` | Validate, merge, score improvement proposals from JSONL + generate numbered report |
| `evolve_score` | Score and rank proposals (Priority x Effort weighted) |
| `evolve_exe` | Autonomous execution pipeline (git branch -> implement -> test -> build -> review -> merge/rollback) |
| `evolve_publish` | Version bump + test + build + npm publish (with deploy instructions) |

### Hooks (9)

| Hook | Hook Point | Description |
|------|-----------|-------------|
| `keyword-detector` | chat.message | Detects ultrawork/search/analyze/think/evolve keywords |
| `rules-injector` | system.transform | Injects .opencode/rules.md into system prompt |
| `context-injector` | system.transform | Auto-injects ARCHITECTURE.md / CODE_STYLE.md |
| `fragment-injector` | system.transform | Per-agent custom prompt fragment injection |
| `prompt-renderer` | system.transform | Model-specific system prompt format optimization (markdown/xml/json) |
| `comment-checker` | tool.execute.after | Detects AI slop comments after Write/Edit |
| `token-truncation` | tool.execute.after | Compresses tool output >30000 chars to first 40% + last 40% |
| `todo-enforcer` | event (session.idle) | Detects unfinished TODOs and forces continuation |
| `session-compaction` | experimental.session.compacting | Generates structured summary during session compaction |

### Safety

| Feature | Description |
|---------|-------------|
| **Prompt Injection Sanitizer** | Detects and neutralizes injection patterns in agent output (17 patterns, 6 categories) |
| **Spawn Limit** | Max concurrent sessions (default: 15) |
| **Agent Timeout** | Per-agent timeout (default: 180s) |
| **Trust Score** | npm package trust score (0-100) — quality gate for evolve recommendations |
| **Concurrency Pool** | Semaphore-based global/provider/model three-tier concurrency control |

### Evolve (Self-Improvement)

Triggered by `evolve` / `self-improve` keywords. A 5-phase self-improvement cycle:

| Phase | Description |
|-------|-------------|
| 1. RESEARCH | Scan npm/GitHub for plugin ecosystem |
| 2. COMPARE | Feature matrix diff against opencode-ultra |
| 3. PROPOSE | Structured implementation proposals (target files/functions, issues, changes, effects) + JSONL output |
| 4. SCORE | Score all proposals via `evolve_score` (Priority x Effort weighted) |
| 5. SAVE | Persist results via `ledger_save` |

Proposals are output to `.opencode/evolve-proposals.jsonl`:

```json
{"title":"Feature","priority":"P0","effort":"Medium","inspiration":"reference-plugin","current_state":"Current state","why":"Benefit","how":"target-file:function — change description"}
```

Score calculation: `priority_weight x effort_weight`

| Priority | Weight | Effort | Weight |
|----------|--------|--------|--------|
| P0 | 10 | Low | 3 |
| P1 | 5 | Medium | 2 |
| P2 | 1 | High | 1 |

P0+Low=30 (highest priority) / P2+High=1 (lowest)

### Evolve Execution (Autonomous)

Fully automate proposal implementation with `evolve_exe`. Each proposal is isolated in a git branch with automatic rollback on failure.

```
evolve_exe({ proposals: "1,3" })              — Execute proposals #1 and #3
evolve_exe({ proposals: "all" })               — Execute all accepted proposals
evolve_exe({ proposals: "1", dryRun: true })   — Show execution plan only
evolve_exe({ proposals: "1,2", publish: true }) — Auto-publish after execution
```

| Phase | Description |
|-------|-------------|
| 1. GIT BRANCH | Create `evolve/{slug}` branch |
| 2. IMPLEMENT | implementAgent (default: hephaestus) autonomously implements |
| 3. TEST | Run `bun test` (failure -> rollback) |
| 4. BUILD | Run `bun run build` (failure -> rollback) |
| 5. REVIEW | reviewAgent (default: momus) code review (BLOCK is logged) |
| 6. MERGE | `--no-ff` merge to original branch, delete feature branch |

Post-implementation publish:

```
evolve_publish({ bump: "patch" })                      — test -> build -> version bump -> npm publish
evolve_publish({ bump: "minor", deploy: "my-server" }) — publish + SSH deploy instructions
```

## Agent Configuration

Sisyphus (orchestrator) handles reading, analysis, and planning, then delegates implementation to sub-agents.

| Agent | Role | Tier |
|-------|------|------|
| **sisyphus** | Orchestrator — read + analyze + plan + delegate | High |
| **momus** | Code review and quality check | High |
| **oracle** | Design, debugging, architecture decisions | Mid |
| **hephaestus** | Autonomous implementation worker | Mid |
| **metis** | Task decomposition and parallel execution planning | Mid |
| **multimodal-looker** | Image and screenshot analysis | Mid |
| **explore** | Fast codebase reconnaissance | Fast |
| **librarian** | Documentation and best practices research | Fast |
| **scout** | Plugin ecosystem research | Fast |
| **atlas** | Task management and progress tracking | Low |

All agent models are configured via `opencode-ultra.json`. Only providers/models defined in your `opencode.jsonc` `provider` section can be specified.

### Default Models

| Agent | Default Model |
|-------|--------------|
| sisyphus | anthropic/claude-opus-4-5 |
| oracle | openai/gpt-5.2 |
| hephaestus | openai/gpt-5.2 |
| momus | anthropic/claude-sonnet-4-5 |
| metis | anthropic/claude-sonnet-4-5 |
| explore | anthropic/claude-haiku-4-5 |
| librarian | anthropic/claude-sonnet-4-5 |
| multimodal-looker | anthropic/claude-sonnet-4-5 |
| atlas | anthropic/claude-sonnet-4-5 |

You can override these with any model from your configured providers (OpenAI, Anthropic, Google, OpenRouter, etc.).

## Keyword Detection

| Keyword | Mode | Effect |
|---------|------|--------|
| `ultrawork` / `ulw` | ultrawork | variant "max", full agent utilization |
| `search` / `find` / `探して` etc. | search | Comprehensive search |
| `analyze` / `調査` / `debug` etc. | analyze | Context collection |
| `think hard` / `じっくり` / `熟考` etc. | think | Extended thinking enabled |
| `evolve` / `self-improve` / `自己改善` etc. | evolve | Self-improvement cycle |

Supports Japanese and Chinese keywords.

## Configuration

Two-level merge via `opencode-ultra.json` (or `.jsonc`):

1. **User config**: `~/.config/opencode/opencode-ultra.json[c]`
2. **Project config**: `<project>/.opencode/opencode-ultra.json[c]`

Project config overrides user config.

### Profiles

Define multiple configurations and switch between them via `activeProfile` or the `OPENCODE_ULTRA_PROFILE` environment variable:

```jsonc
{
  "activeProfile": "cloud",
  "profiles": {
    "cloud": {
      "agents": {
        "sisyphus": { "model": "anthropic/claude-opus-4" },
        "hephaestus": { "model": "openai/gpt-4o" },
        "explore": { "model": "anthropic/claude-haiku-4" }
      },
      "background_task": { "defaultConcurrency": 4 }
    },
    "local": {
      "agents": {
        "sisyphus": { "model": "ollama/llama3:70b" },
        "hephaestus": { "model": "ollama/qwen3:32b" },
        "explore": { "model": "ollama/mistral:7b" }
      },
      "background_task": { "defaultConcurrency": 2 }
    }
  }
}
```

Switch profiles at runtime:

```bash
# Via environment variable (takes priority over activeProfile)
OPENCODE_ULTRA_PROFILE=local opencode exec --agent sisyphus "implement feature X"

# Or set activeProfile in config for the default
```

Profile settings are deep-merged on top of base config values defined outside `profiles`. You can override just the fields you need per profile — everything else inherits from the base config.

### Configuration Schema

```jsonc
{
  // Agent model settings (specify models defined in opencode.jsonc provider section)
  "agents": {
    "sisyphus": { "model": "anthropic/claude-opus-4-5" },
    "oracle":   { "model": "openai/gpt-5.2" },
    "hephaestus": { "model": "openai/gpt-5.2" },
    "explore":  { "model": "anthropic/claude-haiku-4-5" },
    "momus":    { "model": "anthropic/claude-sonnet-4-5" }
  },

  // Categories (bulk model switching via spawn_agent category parameter)
  // Note: category takes priority over individual agent models
  "categories": {
    "quick": { "model": "anthropic/claude-haiku-4-5" },
    "deep":  { "model": "anthropic/claude-opus-4-5" }
  },

  // Fragment Injection (per-agent prompt fragments)
  "fragments": {
    "hephaestus": [".opencode/fragments/strict.md"]
  },

  // Per-model Prompt Renderer
  "prompt_renderer": {
    "default": "markdown",
    "model_overrides": {
      "provider/model": "xml"
    }
  },

  // Disable features
  "disabled_agents": [],
  "disabled_hooks": [],   // keyword-detector, rules-injector, context-injector,
                          // fragment-injector, prompt-renderer, comment-checker,
                          // token-truncation, todo-enforcer, session-compaction
  "disabled_tools": [],   // spawn_agent, ralph_loop, cancel_ralph, batch_read,
                          // ledger_save, ledger_load, ast_search, evolve_apply,
                          // evolve_scan, evolve_score, evolve_exe, evolve_publish
  "disabled_mcps": [],    // context7

  // Built-in Agent Demotion (default: true)
  "demote_builtin": true,

  // Concurrency control
  "background_task": {
    "defaultConcurrency": 3,
    "providerConcurrency": { "openai": 8 },
    "modelConcurrency": { "openai/gpt-5.2": 2 }
  },

  // Safety
  "safety": {
    "maxTotalSpawned": 15,
    "agentTimeoutMs": 180000
  },

  // Evolve Execution
  "evolve_exe": {
    "maxIterations": 10,
    "iterationTimeoutMs": 300000,
    "totalTimeoutMs": 900000,
    "skipReview": false,
    "skipTests": false,
    "implementAgent": "hephaestus",
    "reviewAgent": "momus"
  },

  // Token Truncation
  "token_truncation": { "maxChars": 30000 },

  // Comment Checker
  "comment_checker": { "maxRatio": 0.3, "slopThreshold": 3 },

  // Todo Enforcer
  "todo_enforcer": { "maxEnforcements": 5 },

  // MCP API Keys
  "mcp_api_keys": { "context7": "ctx7sk-..." }
}
```

## Continuity Ledger

Markdown documents for session-to-session context continuity. Saved to `.opencode/ledgers/`.

```typescript
// Save
ledger_save({ name: "auth-refactor", content: "## Context\n..." })

// Load (by name)
ledger_load({ name: "auth-refactor" })

// Load (latest)
ledger_load({})
```

## Build & Test

```bash
bun install
bun run build
bun test
```

## Attribution

This project is a fork of [oh-my-opencode](https://github.com/code-yeongyu/oh-my-opencode) by [code-yeongyu](https://github.com/code-yeongyu), built on top of [OpenCode](https://github.com/anomalyco/opencode) by the OpenCode team.

We respect and follow the upstream licenses:
- oh-my-opencode: [Sustainable Use License v1.0](./LICENSE.md)
- OpenCode: [MIT License](https://github.com/anomalyco/opencode/blob/main/LICENSE)

## License

[Sustainable Use License v1.0](./LICENSE.md) — Free for personal and non-commercial use.
See [LICENSE.md](./LICENSE.md) for full terms.
