codecraft:基于 OpenCode 的上下文工程插件项目

用opencode为opencode写了一个插件codecraft:文件规划法,像 Manus 一样工作

Branch1Tags0
FilesLast commitLast update
9 months ago
9 months ago
9 months ago
9 months ago
10 months ago
10 months ago
9 months ago
10 months ago
9 months ago
9 months ago
9 months ago
9 months ago
10 months ago
9 months ago
9 months ago
10 months ago

CodeCraft 🛠️

Context Engineering for OpenCode - Enhance your programming skills through intelligent code analysis and persistent context management.

"Markdown is my 'working memory' on disk. Since I process information iteratively and my active context has limits, Markdown files serve as scratch pads for notes, checkpoints for progress, building blocks for final deliverables." — Manus AI

🧠 Context Engineering Principles

CodeCraft implements the revolutionary context engineering approach that helped Manus AI achieve $100M+ revenue in just 8 months.

Core Principle

Context Window = RAM (volatile, limited)
Filesystem = Disk (persistent, unlimited)

→ Anything important gets written to disk.

The 3-File Pattern

For every complex task, CodeCraft automatically maintains THREE files:

  1. task_plan.md → Track phases and progress
  2. findings.md → Store research and discoveries
  3. progress.md → Session logs and test results

🚀 Key Features

🔍 Code Quality Analysis

  • Real-time code quality assessment
  • Issue detection with severity levels
  • Code metrics calculation (complexity, maintainability, lines of code)
  • Support for multiple programming languages

💡 Best Practice Suggestions

  • Language-specific recommendations
  • Modern coding patterns
  • Security best practices
  • Code style improvements

⚡ Performance Optimization

  • Performance bottleneck identification
  • Optimization suggestions
  • Resource usage recommendations
  • Algorithm efficiency tips

🎯 Context Engineering

  • Persistent Context: Survives context resets and restarts
  • Goal Tracking: Prevents goal drift after 50+ tool calls
  • Error Logging: Tracks failures to avoid repetition
  • Smart Reminders: Plan checks every 10 tool calls
  • 2-Action Rule: Save findings after every 2 research operations

📋 Smart Monitoring

  • Automatic analysis on file edits
  • Integration with code-related commands
  • Structured logging for debugging
  • Completion verification before stopping

Installation

Local Installation

  1. Clone this repository:
git clone https://gitcode.com/skywalk163/codecraft.git
cd codecraft
  1. Install dependencies:
bun install
  1. Copy the plugin to your OpenCode plugin directory:
# For project-level plugins
cp -r src/index.ts .opencode/plugin/codecraft.ts

# Or for global plugins
cp -r src/index.ts ~/.config/opencode/plugin/codecraft.ts

NPM Installation

Add to your opencode.json:

{
  "$schema": "https://opencode.ai/config.json",
  "plugin": ["codecraft"]
}

🚀 Quick Start

5-Minute Setup

  1. Install the plugin:
git clone https://gitcode.com/skywalk163/codecraft.git
cd codecraft
bun install
cp src/index.ts .opencode/plugin/codecraft.ts
cp -r templates .opencode/
  1. Start OpenCode and create your first plan:
opencode
/codecraft plan --taskName "my-project" --objective "Build a web application"
  1. Start working - CodeCraft will automatically:
    • Remind you to check your plan every 10 tool calls
    • Suggest saving findings after every 2 research operations
    • Log all errors for future reference
    • Update progress automatically

🛠️ Available Tools

Context Management Tools

plan

Create or update task plan with 3-file pattern.

/codecraft plan --taskName "user-auth" --objective "Implement JWT authentication"

context

Review current context and state.

/codecraft context --includeFindings true --includeProgress true

Code Analysis Tools

analyze

Analyze code quality and metrics for a file or entire project.

/codecraft analyze --filePath "src/app.js" --includeMetrics true
/codecraft analyze --includeMetrics true  # Entire project

suggest

Get best practice suggestions for code improvement.

/codecraft suggest --code "function example() { console.log('test'); }" --language "javascript"

optimize

Provide performance optimization suggestions.

/codecraft optimize --code "for (let i = 0; i < arr.length; i++) { console.log(arr[i]); }" --language "javascript"

🤖 Automatic Features

Smart Reminders

  • Plan Check: Every 10 tool calls, reminds you to review task_plan.md
  • 2-Action Rule: Every 2 research operations, suggests saving to findings.md
  • Progress Update: After file edits, reminds to update progress.md

Error Tracking

  • ALL errors logged automatically to prevent repetition
  • Attempt tracking to avoid failed approaches
  • Resolution documentation for future reference

Context Persistence

  • Automatic file creation on first use
  • Cross-session context preservation
  • Completion verification before stopping

File Monitoring

  • Real-time analysis when files are edited
  • Automatic progress updates
  • Integration with code-related commands

📊 Context Engineering Rules

✅ Always Do

  • Create Plan First - Never start without task_plan.md
  • The 2-Action Rule - Save findings after every 2 view/browser operations
  • Log ALL Errors - They help avoid repetition
  • Check Plan Regularly - Every 10 tool calls

❌ Never Do

  • Start Without a Plan - Leads to goal drift
  • Stuff Context - Use filesystem instead
  • Ignore Errors - Track and learn from failures
  • Repeat Failed Approaches - Mutate your strategy

📈 Code Quality Metrics

The plugin calculates and tracks several key metrics:

  • Complexity: Cyclomatic complexity score
  • Lines of Code: Non-empty, non-comment lines
  • Maintainability Index: Overall code maintainability score (0-100)
  • Duplicate Lines: Detected code duplication

🌍 Supported Languages

  • JavaScript / TypeScript
  • Python
  • Java
  • C/C++
  • Go
  • Rust
  • And more...

⚙️ Configuration

The plugin works out-of-the-box but can be customized through OpenCode's configuration system.

Basic Configuration

{
  "plugin": ["codecraft"],
  "codecraft": {
    "autoInitialize": true,
    "contextCheckInterval": 10,
    "findingsReminder": true,
    "errorTracking": true
  }
}

Advanced Configuration

{
  "codecraft": {
    "autoInitialize": true,
    "contextCheckInterval": 10,
    "findingsReminder": true,
    "errorTracking": true,
    "rules": {
      "maxLineLength": 120,
      "complexityThreshold": 10,
      "maintainabilityThreshold": 70
    },
    "languages": ["javascript", "typescript", "python", "java"],
    "excludedPaths": ["node_modules", ".git", "dist"]
  }
}

📁 File Structure

After installation, CodeCraft creates this structure in your .opencode/ directory:

.opencode/
├── task_plan.md      # Your project roadmap and phases
├── findings.md       # Research, discoveries, and decisions
├── progress.md       # Session logs and test results
├── plugin/
│   └── codecraft.ts  # The plugin itself
└── templates/        # Customizable templates
    ├── task_plan.md
    ├── findings.md
    └── progress.md

🔄 Workflow Example

Starting a New Task

# 1. Create plan (ALWAYS first)
/codecraft plan --taskName "user-auth" --objective "Implement JWT authentication"

# 2. Plan is created with phases:
# Phase 1: Research JWT libraries
# Phase 2: Implement auth middleware
# Phase 3: Add login/logout endpoints
# Phase 4: Test and document

During Development

# Research phase
/websearch "JWT best practices Node.js"
/webfetch "https://jwt.io/libraries/"

# CodeCraft reminds: "2-Action Rule: Consider saving findings to findings.md"
/codecraft suggest --code "JWT research" --language "javascript"

# Implementation phase
/write auth-middleware.js
# CodeCraft automatically updates progress.md

# After 10 tool calls, CodeCraft reminds: "📋 Plan Check: Reviewing task_plan.md"

Error Handling

# If an error occurs:
# Error is automatically logged to findings.md
# CodeCraft tracks attempts and resolutions
# "Never Repeat Failures" principle enforced

🛠️ Development

Building

bun run build

Linting

bun run lint

Formatting

bun run format

Testing

bun run test

🗺️ Roadmap

Context Engineering Features

Code Analysis Features

💡 Examples

Context Engineering in Action

Before CodeCraft:

# Session 1: Research authentication
# (Context gets reset, all research lost)

# Session 2: Start implementation
# (Forgot research decisions, repeat work)

# Session 3: Hit same error
# (Repeat failed approach, waste time)

After CodeCraft:

# Session 1: Research and save to findings.md
# Session 2: Review findings.md, continue implementation
# Session 3: Check error log, use different approach

Code Analysis Examples

JavaScript Analysis

// Input code
function calculateTotal(items) {
  var total = 0;
  for (var i = 0; i < items.length; i++) {
    total = total + items[i].price;
  }
  return total;
}

CodeCraft Suggestions:

  • Use const instead of var for better scoping
  • Use reduce() for more concise array operations
  • Use strict equality (===) when possible

Performance Optimization

// Before
for (let i = 0; i < elements.length; i++) {
  document.getElementById(elements[i]).style.color = 'red';
}

CodeCraft Optimization:

  • Cache DOM elements to avoid repeated queries
  • Use forEach or map for better readability
  • Consider batch DOM updates for better performance

📚 Documentation

Getting Started

Workflow & Usage

🤝 Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests if applicable
  5. Submit a pull request

📄 License

MIT License - see LICENSE file for details.

🆘 Support


Built with ❤️ by the OpenCode community
Inspired by Manus AI's context engineering principles

Introduction

用opencode为opencode写了一个插件codecraft:文件规划法,像 Manus 一样工作

Customize your domain