npm package: @heyuchuan/opencode-heuristic-solve
Description: An OpenCode plugin for heuristic problem-solving that orchestrates multiple agents to recursively decompose and tackle complex challenges.
Author: heyuchuan
Latest version: 0.1.0

# heuristic-solve

An OpenCode plugin that implements a heuristic problem-solving framework. It orchestrates multiple agents to recursively decompose and tackle complex challenges using the OpenCode plugin system.

> Built on the [opencode-plugin-template](https://github.com/zenobi-us/opencode-plugin-template)

## Features

- 🧠 **Recursive Problem Decomposition** - Breaks complex problems into manageable sub-problems
- 🔄 **Parallel Execution** - Solves sub-problems concurrently with configurable limits
- 🎯 **Specialized Tools** - Analyst and creative expert tools for different thinking modes
- 🧹 **Automatic Cleanup** - Manages OpenCode sessions and resources efficiently
- ✅ **Comprehensive Testing** - 40 tests with 81 assertions ensuring reliability
- 📦 **TypeScript** - Fully typed with Zod schema validation

## Installation

### Local Development

1. **Build the plugin:**
   ```bash
   bun build ./src/index.ts --outdir dist --target bun
   ```

2. **Symlink to OpenCode plugin directory:**
   ```bash
   mkdir -p ~/.config/opencode/plugin
   ln -sf "$(pwd)" ~/.config/opencode/plugin/heuristic-solve
   ```

3. **Configure OpenCode** in `~/.config/opencode/config.json`:
   ```json
   {
     "plugins": ["heuristic-solve"]
   }
   ```

4. **Verify installation:**
   ```bash
   bun run ./test-plugin.js
   ```

### From npm (when published)

```bash
npm install -g heuristic-solve
```

Then add to your OpenCode config:
```json
{
  "plugins": ["heuristic-solve"]
}
```

## Available Tools

The plugin provides four tools that can be called by the LLM during conversations:

### 1. `heuristic_solve`

Recursively decomposes complex problems into manageable sub-problems, solves them in parallel, and synthesizes results.

**Parameters:**
- `problem` (string, required): The complex problem to solve
- `maxDepth` (number, optional): Maximum recursion depth (default: 5)
- `maxParallel` (number, optional): Maximum parallel tasks per batch (default: 3)

**How it works:**
1. Analyzes whether the problem should be decomposed
2. If complex, breaks it into 3-5 sub-problems
3. Solves sub-problems in parallel batches
4. Synthesizes results into a comprehensive solution
5. Recurses until reaching atomic tasks or max depth

### 2. `analyst`

Provides rigorous analytical assessment with logic analysis, feasibility evaluation, and risk assessment.

**Parameters:**
- `problem` (string, required): The problem or question to analyze
- `context` (string, optional): Additional context for the analysis

**Use cases:**
- Feasibility studies
- Risk assessment
- Decision analysis
- Technical evaluation

### 3. `creative`

Generates creative solutions using divergent thinking and unconventional approaches.

**Parameters:**
- `problem` (string, required): The problem or challenge to explore creatively
- `constraints` (string, optional): Any constraints or requirements to consider

**Use cases:**
- Brainstorming sessions
- Innovation challenges
- Alternative approaches
- "What if" scenarios

### 4. `analyze_task_tree`

Analyzes the task decomposition tree from a heuristic solve operation.

**Parameters:**
- `problem` (string, required): The problem that was solved

**Note:** Currently returns a placeholder. Full implementation requires persistent task tree storage.

## How It Works

### Architecture

```
┌─────────────────────────────────────────┐
│         HeuristicCoordinator            │
│  (Orchestrates recursive solving)       │
└─────────────────┬───────────────────────┘
                  │
        ┌─────────┴─────────┐
        │                   │
   ┌────▼────┐         ┌────▼────┐
   │ Analyst │         │Creative │
   │  Tool   │         │  Tool   │
   └─────────┘         └─────────┘
        │                   │
        └─────────┬─────────┘
                  │
         ┌────────▼────────┐
         │ OpenCode Client │
         │  (Session Mgmt) │
         └─────────────────┘
```

### Execution Flow

```
Problem Input
     │
     ▼
Decomposition Analysis
     │
     ├─── Atomic? ──► Solve Directly
     │
     └─── Complex? ──► Decompose
                         │
                         ▼
                   Create Sub-Tasks
                         │
                         ▼
                   Parallel Execution
                    (Batch by batch)
                         │
                         ▼
                   Synthesize Results
                         │
                         ▼
                   Final Solution
```

### Session Management

- Each task gets its own isolated OpenCode session
- Sessions are created with descriptive titles for debugging
- Automatic cleanup in `finally` blocks prevents resource leaks
- Configurable recursion depth prevents infinite loops

## Development

### Prerequisites

- [Bun](https://bun.sh/) runtime
- [OpenCode](https://opencode.ai/) CLI
- Node.js 18+ (for some tooling)

### Setup

```bash
# Install dependencies
bun install

# Run tests
bun test

# Run tests in watch mode
bun test --watch

# Build
bun build ./src/index.ts --outdir dist --target bun

# Lint
bun run --bun eslint src --ext .ts

# Fix linting issues
bun run --bun eslint src --ext .ts --fix

# Format code
bun run --bun prettier --write src

# Type check
bun run --bun tsc --noEmit --skipLibCheck
```

### Project Structure

```
src/
├── types.ts           # Type definitions and Zod schemas
├── coordinator.ts     # Main orchestration logic
├── tools.ts          # Specialist tools (analyst, creative)
├── index.ts          # Plugin entry point
├── command/          # Optional slash commands (empty by default)
├── *.test.ts         # Test files
└── ...

dist/                 # Built output
test-plugin.js        # Integration test script
```

## Testing

The plugin includes comprehensive tests:

- **40 tests** covering all major functionality
- **81 assertions** ensuring correctness
- Unit tests for types, coordinator, and tools
- Integration tests for end-to-end workflows
- Mock OpenCode client for isolated testing

Run tests:
```bash
bun test
```

Run integration test:
```bash
bun run ./test-plugin.js
```

## Configuration

Default configuration:
```typescript
{
  maxDepth: 5,        // Maximum recursion depth
  maxParallel: 3,     // Maximum parallel tasks per batch
  model: {
    providerID: 'anthropic',
    modelID: 'claude-3-5-sonnet-20241022'
  }
}
```

Override when calling `heuristic_solve`:
```typescript
{
  problem: "Your complex problem",
  maxDepth: 3,      // Limit recursion
  maxParallel: 5    // More parallelism
}
```

## Examples

### Example 1: System Architecture Design

**Problem:** "Design a scalable microservices architecture for an e-commerce platform"

**Process:**
1. Decomposes into: authentication, payment, inventory, shipping, notifications
2. Each service designed independently
3. Results synthesized into complete architecture
4. Includes integration patterns and data flow

### Example 2: Technical Decision

**Problem:** "Should we migrate from monolith to microservices?"

**Using analyst tool:**
- Feasibility assessment
- Cost-benefit analysis
- Risk evaluation
- Migration strategy
- Recommended approach with rationale

### Example 3: Innovation Challenge

**Problem:** "How to reduce customer churn in our SaaS product?"

**Using creative tool:**
- Unconventional retention strategies
- Gamification approaches
- Community building ideas
- Predictive intervention methods

## Troubleshooting

### Plugin fails to load with ENOENT error

**Error:** `ENOENT: no such file or directory, open '.../dist/command'`

**Solution:** This has been fixed in the current version. The plugin now gracefully handles missing command directories. Rebuild:
```bash
bun build ./src/index.ts --outdir dist --target bun
```

### Sessions not cleaning up

The plugin automatically cleans up all sessions in `finally` blocks. If you notice orphaned sessions:
1. Check OpenCode logs for errors during cleanup
2. Verify the OpenCode client is functioning correctly
3. Run the integration test to verify cleanup: `bun run ./test-plugin.js`

### Type errors during development

Run type checking with:
```bash
bun run --bun tsc --noEmit --skipLibCheck
```

The `--skipLibCheck` flag is needed due to OpenCode SDK type complexities.

### Tests failing

Ensure you have the latest dependencies:
```bash
bun install
bun test
```

If specific tests fail, run with verbose output:
```bash
bun test --reporter=verbose
```

## Contributing

Contributions are welcome! Please:

1. Fork the repository
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Make your changes
4. Add tests for new functionality
5. Ensure all tests pass: `bun test`
6. Ensure linting passes: `bun run --bun eslint src --ext .ts`
7. Commit your changes (`git commit -m 'Add amazing feature'`)
8. Push to the branch (`git push origin feature/amazing-feature`)
9. Open a Pull Request

## Changelog

### v0.1.0 (Current)

- ✅ Initial implementation of heuristic problem-solving framework
- ✅ Recursive decomposition with configurable depth
- ✅ Parallel execution with batch processing
- ✅ Analyst and creative specialist tools
- ✅ Automatic session cleanup
- ✅ Comprehensive test suite (40 tests, 81 assertions)
- ✅ Fixed command directory loading issue

## Author

yc.he <he.yc@foxmail.com>

## Repository

https://github.com/heyuch/opencode-plugin-heuristic-solve.git

## License

MIT License. See the [LICENSE](LICENSE) file for details.

## Acknowledgments

- Built on the [opencode-plugin-template](https://github.com/zenobi-us/opencode-plugin-template)
- Follows OpenCode plugin architecture patterns
- Inspired by heuristic problem-solving methodologies