Agent Skills › Taoidle/plan-cascade

Taoidle/plan-cascade

GitHub

提供Go语言编码最佳实践,涵盖代码风格、错误处理、并发模式、项目结构及测试规范。适用于编写或审查Go代码时参考,确保代码符合惯用模式并避免常见反模式。

7 skills 120

Install All Skills

npx skills add Taoidle/plan-cascade --all -g -y
More Options

List skills in collection

npx skills add Taoidle/plan-cascade --list

Skills in Collection (7)

提供Go语言编码最佳实践,涵盖代码风格、错误处理、并发模式、项目结构及测试规范。适用于编写或审查Go代码时参考,确保代码符合惯用模式并避免常见反模式。
编写Go代码 审查Go代码 解决Go并发问题 设计Go项目结构
builtin-skills/go/SKILL.md
npx skills add Taoidle/plan-cascade --skill go-best-practices -g -y
SKILL.md
Frontmatter
{
    "name": "go-best-practices",
    "license": "MIT",
    "metadata": {
        "author": "plan-cascade",
        "version": "1.0.0"
    },
    "description": "Go coding best practices. Use when writing or reviewing Go code. Covers error handling, concurrency, and idiomatic patterns."
}

Go Best Practices

Code Style

Rule Guideline
Formatter gofmt or goimports
Linter golangci-lint
Naming Short, clear; avoid stuttering
Comments Godoc for exported items

Error Handling

Rule Guideline
Always check Never ignore errors
Wrap context fmt.Errorf("ctx: %w", err)
Sentinel errors var ErrNotFound = errors.New(...)
func Load(path string) (*Config, error) {
    data, err := os.ReadFile(path)
    if err != nil {
        return nil, fmt.Errorf("load config %s: %w", path, err)
    }
    // ...
}

Project Structure

cmd/appname/main.go
internal/config/
internal/service/
go.mod

Concurrency

Pattern Usage
context.Context Cancellation, timeouts
sync.WaitGroup Wait for goroutines
errgroup.Group Goroutines with errors
func Process(ctx context.Context, items []Item) error {
    for _, item := range items {
        select {
        case <-ctx.Done():
            return ctx.Err()
        default:
            if err := process(item); err != nil { return err }
        }
    }
    return nil
}

Anti-Patterns

Avoid Use Instead
Naked returns Explicit returns
panic for errors Return errors
Large interfaces Small, focused
init() Explicit init

Testing (Table-Driven)

func TestParse(t *testing.T) {
    tests := []struct{ name, input string; want int; wantErr bool }{
        {"valid", "42", 42, false},
        {"invalid", "abc", 0, true},
    }
    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            got, err := Parse(tt.input)
            if (err != nil) != tt.wantErr { t.Errorf("err=%v, want=%v", err, tt.wantErr) }
            if got != tt.want { t.Errorf("got=%v, want=%v", got, tt.want) }
        })
    }
}
提供Java 17+编码最佳实践,涵盖代码风格、现代特性(Records/Sealed)、错误处理、项目结构及测试规范。用于指导Java代码的编写与审查,提升代码质量与现代性。
编写Java代码 审查Java代码 Java 17及以上版本开发
builtin-skills/java/SKILL.md
npx skills add Taoidle/plan-cascade --skill java-best-practices -g -y
SKILL.md
Frontmatter
{
    "name": "java-best-practices",
    "license": "MIT",
    "metadata": {
        "author": "plan-cascade",
        "version": "1.0.0"
    },
    "description": "Java coding best practices. Use when writing or reviewing Java code (17+). Covers modern features, error handling, and patterns."
}

Java Best Practices (17+)

Code Style

Rule Guideline
Formatter google-java-format
Analysis SpotBugs, Error Prone
Naming Clear, no abbreviations

Modern Features

Feature Usage
Records Immutable data carriers
Sealed classes Restricted hierarchies
Pattern matching instanceof with binding
var Local type inference
public record User(String id, String name) {}

if (obj instanceof String s && !s.isEmpty()) { process(s); }

public sealed interface Result<T> permits Success, Failure {}
record Success<T>(T value) implements Result<T> {}
record Failure<T>(Exception error) implements Result<T> {}

Error Handling

Rule Guideline
Specific exceptions Not bare Exception
Try-with-resources For AutoCloseable
try (var reader = new BufferedReader(new FileReader(path))) {
    return reader.lines().toList();
} catch (IOException e) {
    throw new ConfigException("Failed: " + path, e);
}

Project Structure

src/main/java/com/example/{domain,service}/
src/test/java/
pom.xml or build.gradle

Common Patterns

Pattern Usage
Optional Null-safe returns
Stream API Functional collections
Builder Complex construction
public Optional<User> findById(String id) {
    return Optional.ofNullable(users.get(id));
}

Anti-Patterns

Avoid Use Instead
Returning null Optional<T>
Mutable data Records
instanceof chains Pattern matching

Testing (JUnit 5 + AssertJ)

@Test void shouldProcess() {
    var service = new Service(mockRepo);
    var result = service.process(input);
    assertThat(result.status()).isEqualTo(SUCCESS);
}
提供Python编码最佳实践指南,涵盖代码风格、类型提示、异常处理、项目结构及常用模式。适用于编写或审查Python代码时参考,确保代码规范与质量。
编写Python代码 审查Python代码 配置Python项目结构
builtin-skills/python/SKILL.md
npx skills add Taoidle/plan-cascade --skill python-best-practices -g -y
SKILL.md
Frontmatter
{
    "name": "python-best-practices",
    "license": "MIT",
    "metadata": {
        "author": "plan-cascade",
        "version": "1.0.0"
    },
    "description": "Python coding best practices. Use when writing or reviewing Python code. Covers type hints, error handling, and common patterns."
}

Python Best Practices

Code Style

Rule Guideline
Formatter ruff format or black
Linter ruff check with strict rules
Type hints Always for public APIs
Docstrings Google or NumPy style

Type Hints

def process(items: list[str], max_count: int = 10) -> dict[str, int]: ...
def find_user(user_id: int) -> User | None: ...

Error Handling

Rule Guideline
Specific exceptions Never bare except:
Context managers Use with for resources
Early return Validate inputs, fail fast
# Good
try:
    result = process(data)
except ValidationError as e:
    logger.warning(f"Validation failed: {e}")
    return default

Project Structure

src/package_name/
├── __init__.py
├── core/
└── py.typed
tests/
├── conftest.py
└── test_*.py
pyproject.toml

Common Patterns

Pattern Usage
@dataclass Data containers
@property Computed attributes
Generators Memory-efficient iteration
functools.cache Memoization

Anti-Patterns

Avoid Use Instead
Mutable default args None default, create inside
import * Explicit imports
Global state Dependency injection
# Bad: def add(item, items=[]): ...
# Good:
def add(item, items=None):
    items = items or []
    items.append(item)
    return items

Tools

Tool Purpose
pytest Testing
ruff Linting + formatting
mypy Type checking
uv Dependencies
提供 TypeScript/Node.js 最佳实践指南,涵盖代码规范、类型安全、错误处理、项目结构、异步模式及反模式避免。适用于编写或审查 TypeScript 代码时参考。
编写 TypeScript 代码 审查 TypeScript 代码 解决类型安全问题 优化异步逻辑
builtin-skills/typescript/SKILL.md
npx skills add Taoidle/plan-cascade --skill typescript-best-practices -g -y
SKILL.md
Frontmatter
{
    "name": "typescript-best-practices",
    "license": "MIT",
    "metadata": {
        "author": "plan-cascade",
        "version": "1.0.0"
    },
    "description": "TypeScript\/Node.js best practices. Use when writing or reviewing TypeScript code. Covers type safety, async patterns, and error handling."
}

TypeScript Best Practices

Code Style

Rule Guideline
Formatter Prettier
Linter ESLint + @typescript-eslint
Strict mode strict: true in tsconfig

Type Safety

Rule Guideline
Avoid any Use unknown + narrowing
Type guards Custom predicates
Discriminated unions For variants
type Result<T> = { success: true; data: T } | { success: false; error: Error };

function isUser(v: unknown): v is User {
  return typeof v === 'object' && v !== null && 'id' in v;
}

Error Handling

class ApiError extends Error {
  constructor(message: string, public status: number) {
    super(message);
    this.name = 'ApiError';
  }
}

async function fetchUser(id: string): Promise<User> {
  const res = await fetch(`/api/users/${id}`);
  if (!res.ok) throw new ApiError('Failed', res.status);
  return res.json();
}

Project Structure

src/{index.ts, types/, services/, utils/}
tests/
package.json, tsconfig.json

Async Patterns

Pattern Usage
Promise.all Parallel operations
AbortController Cancellation
const [user, settings] = await Promise.all([fetchUser(id), fetchSettings(id)]);

Anti-Patterns

Avoid Use Instead
as assertions Type guards
! non-null ?. and ??
any unknown + narrowing
// Bad: data as User, user!.name
// Good:
if (isUser(data)) { /* data is User */ }
const name = user?.name ?? 'Unknown';

Testing (Vitest)

describe('Service', () => {
  it('should create', async () => {
    const mock = { save: vi.fn().mockResolvedValue({ id: '1' }) };
    const result = await new Service(mock).create({ name: 'Test' });
    expect(result.id).toBe('1');
  });
});
结合Ralph PRD格式与Planning-with-Files的混合架构,支持从任务描述自动生成PRD、管理并行故事执行及依赖解析,并通过上下文恢复协议确保多轮对话中的状态连续性。
需要生成结构化产品需求文档 启动多用户故事的并行开发任务 在会话中断后恢复执行上下文
skills/hybrid-ralph/SKILL.md
npx skills add Taoidle/plan-cascade --skill hybrid-ralph -g -y
SKILL.md
Frontmatter
{
    "name": "hybrid-ralph",
    "hooks": {
        "Stop": [
            {
                "hooks": [
                    {
                        "type": "command",
                        "command": "if [ -f \".current-story\" ]; then\n  STORY_ID=$(cat .current-story 2>\/dev\/null || echo \"\")\n  if [ -n \"$STORY_ID\" ]; then\n    echo \"\"\n    echo \"=== Story Completion Check ===\"\n    echo \"Current story: $STORY_ID\"\n    echo \"Mark complete in progress.txt with: [COMPLETE] $STORY_ID\"\n    echo \"\"\n  fi\nfi"
                    }
                ]
            }
        ],
        "PreToolUse": [
            {
                "hooks": [
                    {
                        "type": "command",
                        "command": "# Show hybrid execution context if we're in a hybrid task\nif [ -f \"prd.json\" ] || [ -f \".planning-config.json\" ] || [ -f \".hybrid-execution-context.md\" ]; then\n  if command -v uv &> \/dev\/null; then\n    # Update and display context reminder\n    uv run python \"${CLAUDE_PLUGIN_ROOT}\/skills\/hybrid-ralph\/scripts\/hybrid-context-reminder.py\" both 2>\/dev\/null || true\n  fi\nfi\n# Show current story context if we're executing a story\nif [ -f \".current-story\" ]; then\n  STORY_ID=$(cat .current-story 2>\/dev\/null || echo \"\")\n  if [ -n \"$STORY_ID\" ]; then\n    echo \"\"\n    echo \"=== Current Story: $STORY_ID ===\"\n    # Show story details from prd.json if available\n    if command -v uv &> \/dev\/null; then\n      (cd \"${CLAUDE_PLUGIN_ROOT}\" && uv run python -m plan_cascade.state.context_filter get-story \"$STORY_ID\" 2>\/dev\/null | head -20) || true\n    fi\n    echo \"\"\n  fi\nfi"
                    }
                ],
                "matcher": "Write|Edit|Bash|Task"
            }
        ],
        "PostToolUse": [
            {
                "hooks": [
                    {
                        "type": "command",
                        "command": "# Update execution context file\n# Best-effort: script exits silently if no hybrid context is detected.\nif command -v uv &> \/dev\/null; then\n  uv run python \"${CLAUDE_PLUGIN_ROOT}\/skills\/hybrid-ralph\/scripts\/hybrid-context-reminder.py\" update 2>\/dev\/null || true\nelif command -v python &> \/dev\/null; then\n  python \"${CLAUDE_PLUGIN_ROOT}\/skills\/hybrid-ralph\/scripts\/hybrid-context-reminder.py\" update 2>\/dev\/null || true\nfi\n# Remind about findings\nif [ -f \".current-story\" ]; then\n  STORY_ID=$(cat .current-story 2>\/dev\/null || echo \"\")\n  if [ -n \"$STORY_ID\" ]; then\n    echo \"[hybrid-ralph] Consider updating findings.md with this discovery (tag with <!-- @tags: $STORY_ID -->)\"\n  fi\nfi"
                    }
                ],
                "matcher": "Write|Edit|Bash|Task"
            }
        ]
    },
    "version": "3.2.0",
    "description": "Hybrid architecture combining Ralph's PRD format with Planning-with-Files' structured approach. Auto-generates PRDs from task descriptions, manages parallel story execution with dependency resolution, and provides context-filtered agents for efficient multi-story development.",
    "allowed-tools": [
        "Read",
        "Write",
        "Edit",
        "Bash",
        "Task",
        "Glob",
        "Grep",
        "AskUserQuestion"
    ],
    "user-invocable": true
}

Hybrid Ralph + Planning-with-Files

A hybrid architecture combining the best of three approaches:

Auto-Recovery Protocol (CRITICAL)

At the START of any interaction, perform this check to recover context after compression/truncation:

  1. Check if .hybrid-execution-context.md exists in the current directory

  2. If YES:

    • Read the file content using Read tool
    • Display: "Detected ongoing hybrid task execution"
    • Show current batch and pending stories from the file
    • Resume story execution based on the state
    • If unsure of state, suggest: /hybrid:resume --auto
  3. If NO but prd.json exists:

    • Run: uv run python "${CLAUDE_PLUGIN_ROOT}/skills/hybrid-ralph/scripts/hybrid-context-reminder.py" both
    • This will generate the context file and display current state

This ensures context recovery even after:

  • Context compression (AI summarizes old messages)

  • Context truncation (old messages deleted)

  • New conversation session

  • Claude Code restart

  • Ralph: Structured PRD format (prd.json), progress tracking patterns, small task philosophy

  • Planning-with-Files: 3-file planning pattern (task_plan.md, findings.md, progress.txt), Git Worktree support

  • Claude Code Native: Task tool with subagents for parallel story execution

Quick Start

Automatic PRD Generation

Generate a PRD from your task description:

/hybrid:auto Implement a user authentication system with login, registration, and password reset

This will:

  1. Launch a Planning Agent to analyze your task
  2. Generate a PRD with user stories
  3. Show the PRD for review
  4. Wait for your approval

Manual PRD Loading

Load an existing PRD file:

/hybrid:manual path/to/prd.json

Approval and Execution

After reviewing the PRD:

/approve

This begins parallel execution of stories according to the dependency graph.

Architecture

File Structure

project-root/
├── prd.json                 # Product Requirements Document
├── findings.md              # Research findings (tagged by story)
├── progress.txt             # Progress tracking
├── .current-story           # Currently executing story
├── .locks/                  # File locks for concurrent access
└── .agent-outputs/          # Individual agent logs

The PRD Format

The prd.json file contains:

  • metadata: Creation date, version, description
  • goal: One-sentence project goal
  • objectives: List of specific objectives
  • stories: Array of user stories with:
    • id: Unique story identifier (story-001, story-002, etc.)
    • title: Short story title
    • description: Detailed story description
    • priority: high, medium, or low
    • dependencies: Array of story IDs this story depends on
    • status: pending, in_progress, or complete
    • acceptance_criteria: List of completion criteria
    • context_estimate: small, medium, large, or xlarge
    • tags: Array of tags for categorization

Parallel Execution Model

Stories are organized into execution batches:

  1. Batch 1: Stories with no dependencies (run in parallel)
  2. Batch 2+: Stories whose dependencies are complete (run in parallel)
Batch 1 (Parallel):
  - story-001: Design database schema
  - story-002: Design API endpoints

Batch 2 (After story-001 complete):
  - story-003: Implement database schema

Batch 3 (After story-002, story-003 complete):
  - story-004: Implement API endpoints

Context Filtering

Each agent receives only relevant context:

  • Their story description and acceptance criteria
  • Summaries of completed dependencies
  • Findings tagged with their story ID

This keeps context windows focused and efficient.

Core Python Modules

context_filter (migrated to src/plan_cascade/state/)

Context filtering functionality is now provided by the main package.

# Get story details
uv run python -m plan_cascade.state.context_filter get-story story-001

# Get context for a story
uv run python -m plan_cascade.state.context_filter get-context story-001

# Get execution batch
uv run python -m plan_cascade.state.context_filter get-batch 1

# Show full execution plan
uv run python -m plan_cascade.state.context_filter plan-batches

state_manager.py

Thread-safe file operations with platform-specific locking.

# Read PRD
uv run python state_manager.py read-prd

# Mark story complete
uv run python state_manager.py mark-complete story-001

# Get all story statuses
uv run python state_manager.py get-statuses

prd_generator.py

Generates PRD from task descriptions and manages story dependencies.

# Validate PRD
uv run python prd_generator.py validate

# Show execution batches
uv run python prd_generator.py batches

# Create sample PRD
uv run python prd_generator.py sample

orchestrator.py

Manages parallel execution of stories.

# Show execution plan
uv run python orchestrator.py plan

# Show execution status
uv run python orchestrator.py status

# Execute a batch
uv run python orchestrator.py execute-batch 1

Commands Reference

/hybrid:auto

Generate PRD from task description and enter review mode. Auto-generates user stories with priorities, dependencies, and acceptance criteria for parallel execution.

/hybrid:auto [options] <task description> [design-doc-path]

Parameters:

Parameter Description
--flow <quick|standard|full> Execution flow depth controlling quality gate strictness
--tdd <off|on|auto> Test-Driven Development mode
--confirm Require batch confirmation during execution
--no-confirm Disable batch confirmation
--spec <off|auto|on> Spec interview before PRD generation
--first-principles Enable first-principles questioning in spec interview
--max-questions N Max questions in spec interview
--agent <name> Agent to use for PRD generation
design-doc-path Optional path to existing design document

Parameters are saved to prd.json and propagated to /approve.

/hybrid:manual

Load an existing PRD file and enter review mode.

/hybrid:manual [path/to/prd.json]

/hybrid:worktree

Start a new task in an isolated Git worktree with Hybrid Ralph PRD mode. Creates worktree, branch, loads existing PRD or auto-generates from description.

/hybrid:worktree [options] <task-name> <target-branch> <prd-path-or-description> [design-doc-path]

Arguments:

  • task-name: Name for the worktree (e.g., "feature-auth", "fix-api-bug")
  • target-branch: Branch to merge into (default: auto-detect main/master)
  • prd-path-or-description: Either a task description to generate PRD, or path to existing PRD file

Parameters:

Parameter Description
--flow <quick|standard|full> Execution flow depth controlling quality gate strictness
--tdd <off|on|auto> Test-Driven Development mode
--confirm Require batch confirmation during execution
--no-confirm Disable batch confirmation
--spec <off|auto|on> Spec interview before PRD generation
--first-principles Enable first-principles questioning in spec interview
--max-questions N Max questions in spec interview
--agent <name> Agent to use for PRD generation
design-doc-path Optional path to existing design document

Parameters are saved to the worktree's prd.json, ensuring isolation from other tasks.

/approve

Approve PRD and begin parallel story execution. Analyzes dependencies, creates execution batches, launches background Task agents, and monitors progress.

/approve [options]

Parameters:

Parameter Description
--flow <quick|standard|full> Override execution flow depth (quality gate strictness)
--tdd <off|on|auto> Control TDD mode for story execution
--confirm Require confirmation before each batch
--no-confirm Disable batch confirmation (even in full flow)
--agent <name> Global agent override for all stories
--impl-agent <name> Agent for implementation phase
--retry-agent <name> Agent for retry phase (after failures)
--no-verify Skip AI verification gate
--verify-agent <name> Agent for verification phase
--no-review Skip code review gate
--no-fallback Disable agent fallback chain
--auto-run Use Python-based full-auto execution with retry

Flow Levels:

Flow Gate Mode AI Verification Code Review Test Enforcement
quick soft (warnings) disabled no no
standard soft (warnings) enabled no no
full hard (blocking) enabled required required

Execution Modes:

Mode Description
Auto Automatically progresses through batches, pauses on errors
Manual Requires user approval before each batch
Full Auto Python-based execution with auto-retry (up to 3 attempts)

/hybrid:complete

Complete a worktree task. Verifies all stories are complete, commits code changes (excluding planning files), merges to target branch, and removes worktree.

/hybrid:complete [target-branch]

/edit

Edit the PRD in your default editor. Opens prd.json, validates after saving, and re-displays review.

/edit

/status

Show execution status of all stories. Displays batch progress, individual story states, completion percentage, and recent activity.

/status

/show-dependencies

Display the dependency graph for all stories in the PRD. Shows visual ASCII graph, critical path analysis, and detects issues like circular dependencies.

/show-dependencies

Workflows

Complete Workflow

1. /hybrid:auto "Implement feature X"
   ↓
2. Review generated PRD
   ↓
3. /edit (if needed) or /approve
   ↓
4. Agents execute stories in parallel batches
   ↓
5. Monitor with /status
   ↓
6. All stories complete

Manual PRD Workflow

1. Create prd.json (or use template)
   ↓
2. /hybrid:manual prd.json
   ↓
3. Review and edit as needed
   ↓
4. /approve
   ↓
5. Execution begins

Findings Tagging

When updating findings.md, tag sections with relevant story IDs:

<!-- @tags: story-001,story-002 -->

## Database Schema Discovery

The existing schema uses UUIDs for primary keys...

This allows agents to receive only relevant findings.

Progress Tracking

Track progress in progress.txt:

[2024-01-15 10:00:00] story-001: [IN_PROGRESS] story-001
[2024-01-15 10:15:00] story-001: [COMPLETE] story-001
[2024-01-15 10:15:00] story-002: [IN_PROGRESS] story-002

File Locking

The state manager uses platform-specific locking:

  • Linux/Mac: fcntl for advisory file locking
  • Windows: msvcrt for file locking
  • Fallback: PID-based lock files

Lock files are stored in .locks/ directory.

Error Handling

Validation Errors

If PRD validation fails:

  1. Check for duplicate story IDs
  2. Verify all dependencies exist
  3. Ensure required fields are present
  4. Use /edit to fix issues

Execution Failures

If a story fails:

  1. Check .agent-outputs/<story-id>.log
  2. Review progress.txt for error messages
  3. Fix issues manually or with agent help
  4. Re-run the story

Dependency Cycles

If dependency cycles are detected:

  1. Review /show-dependencies output
  2. Use /edit to break cycles
  3. Re-validate with /hybrid:manual

Best Practices

  1. Write Clear Descriptions: Agents work better with specific, detailed descriptions
  2. Use Acceptance Criteria: Define what "done" means for each story
  3. Tag Findings: Always tag findings with relevant story IDs
  4. Update Progress: Mark stories complete promptly
  5. Review Before Approval: Always review the PRD before approving

Integration with Planning-with-Files

This skill integrates seamlessly with planning-with-files:

  • Standard Mode: Use alongside existing task_plan.md, findings.md, progress.md
  • Worktree Mode: Each worktree can have its own PRD and story execution
  • Session Recovery: Resume work after /clear with /hybrid:manual

Templates

Use the provided templates as starting points:

  • templates/prd.json.example - Example PRD structure
  • templates/prd_review.md - PRD review display template
  • templates/findings.md - Structured findings template

Troubleshooting

PRD Not Found

Error: No PRD found in current directory

Solution: Use /hybrid:auto to generate or /hybrid:manual to load.

Lock Timeout

TimeoutError: Could not acquire lock within 30s

Solution: Run uv run python state_manager.py cleanup-locks to remove stale locks.

Dependency Not Found

Validation Error: Unknown dependency 'story-005'

Solution: Edit PRD to fix dependency reference or add missing story.

See Also

项目级多任务编排系统,基于hybrid-ralph管理并行特性开发。支持依赖解析、协调PRD生成及统一合并工作流。具备上下文自动恢复机制,通过/mega命令实现计划创建、审批、监控与完成,确保多分支协作高效有序。
需要规划包含多个功能的大型项目时 需要并行处理具有依赖关系的多特性开发时 在会话中断或压缩后需要恢复项目执行上下文时
skills/mega-plan/SKILL.md
npx skills add Taoidle/plan-cascade --skill mega-plan -g -y
SKILL.md
Frontmatter
{
    "name": "mega-plan",
    "hooks": {
        "PreToolUse": [
            {
                "hooks": [
                    {
                        "type": "command",
                        "command": "# Show mega-plan context if we're in a mega-plan project\nif [ -f \"mega-plan.json\" ] || [ -f \".mega-execution-context.md\" ]; then\n  if command -v uv &> \/dev\/null; then\n    # Update and display context reminder\n    uv run python \"${CLAUDE_PLUGIN_ROOT}\/skills\/mega-plan\/scripts\/mega-context-reminder.py\" both 2>\/dev\/null || true\n  fi\nfi\n# Detect potential wrong-branch execution\nif [ -f \"mega-plan.json\" ] && [ -d \".worktree\" ]; then\n  CURRENT_BRANCH=$(git branch --show-current 2>\/dev\/null)\n  if [ \"$CURRENT_BRANCH\" = \"main\" ] || [ \"$CURRENT_BRANCH\" = \"master\" ]; then\n    echo \"\"\n    echo \"!!! WARNING: You are on $CURRENT_BRANCH but worktrees exist !!!\"\n    echo \"!!! Feature work should happen in .worktree\/<feature>\/ directories !!!\"\n    echo \"\"\n  fi\nfi"
                    }
                ],
                "matcher": "Write|Edit|Bash|Task"
            }
        ],
        "PostToolUse": [
            {
                "hooks": [
                    {
                        "type": "command",
                        "command": "# Best-effort: scripts exit silently if no mega-plan context is detected.\nif command -v uv &> \/dev\/null; then\n  uv run python \"${CLAUDE_PLUGIN_ROOT}\/skills\/mega-plan\/scripts\/mega-sync.py\" 2>\/dev\/null || true\n  uv run python \"${CLAUDE_PLUGIN_ROOT}\/skills\/mega-plan\/scripts\/mega-context-reminder.py\" update 2>\/dev\/null || true\nelif command -v python &> \/dev\/null; then\n  python \"${CLAUDE_PLUGIN_ROOT}\/skills\/mega-plan\/scripts\/mega-sync.py\" 2>\/dev\/null || true\n  python \"${CLAUDE_PLUGIN_ROOT}\/skills\/mega-plan\/scripts\/mega-context-reminder.py\" update 2>\/dev\/null || true\nfi"
                    }
                ],
                "matcher": "Write|Edit|Bash|Task"
            }
        ]
    },
    "version": "3.2.0",
    "description": "Project-level multi-task orchestration system. Manages multiple hybrid:worktree features in parallel with dependency resolution, coordinated PRD generation, and unified merge workflow.",
    "allowed-tools": [
        "Read",
        "Write",
        "Edit",
        "Bash",
        "Task",
        "Glob",
        "Grep",
        "AskUserQuestion"
    ],
    "user-invocable": true
}

Mega Plan

A project-level orchestration system that sits above hybrid-ralph to manage multiple parallel features as a unified project plan.

Auto-Recovery Protocol (CRITICAL)

At the START of any interaction, perform this check to recover context after compression/truncation:

  1. Check if .mega-execution-context.md exists in the project root

  2. If YES:

    • Read the file content using Read tool
    • Display: "Detected ongoing mega-plan execution"
    • Show current batch and active worktrees from the file
    • CRITICAL: All feature work MUST happen in worktrees, NOT main branch
    • If unsure of state, suggest: /mega:resume --auto-prd
  3. If NO but mega-plan.json exists:

    • Run: uv run python "${CLAUDE_PLUGIN_ROOT}/skills/mega-plan/scripts/mega-context-reminder.py" both
    • This will generate the context file and display current state

This ensures context recovery even after:

  • Context compression (AI summarizes old messages)
  • Context truncation (old messages deleted)
  • New conversation session
  • Claude Code restart

Architecture

Level 1: Mega Plan (Project Level)
    └── Level 2: Features (Feature Level) = hybrid:worktree
              └── Level 3: Stories (Story Level) = hybrid internal parallelism

Quick Start

Create a Mega Plan

Generate a mega-plan from your project description:

/mega:plan Build an e-commerce platform with user authentication, product catalog, shopping cart, and order processing

This will:

  1. Analyze your project description
  2. Break it into features with dependencies
  3. Create mega-plan.json, mega-findings.md, .mega-status.json
  4. Display the plan for review

Approve and Execute

After reviewing the mega-plan:

/mega:approve

Or with automatic PRD approval for all features:

/mega:approve --auto-prd

This will:

  1. Calculate feature batches based on dependencies
  2. Create worktrees for Batch 1 features
  3. Generate PRDs in each worktree
  4. Wait for PRD approvals (or auto-approve with --auto-prd)
  5. Execute story batches within each feature
  6. Progress to next feature batch when complete

Monitor Progress

/mega:status

Shows:

  • Overall project progress percentage
  • Feature status by batch
  • Story progress within each feature
  • Current batch details

Complete and Merge

When all features are complete:

/mega:complete

This will:

  1. Verify all features are complete
  2. Merge features in dependency order
  3. Clean up worktrees and branches
  4. Remove mega-plan files

File Structure

project-root/
├── mega-plan.json              # Project-level plan
├── mega-findings.md            # Shared findings (read-only in worktrees)
├── .mega-status.json           # Execution status
├── .worktree/
│   ├── feature-auth/
│   │   ├── prd.json           # Feature PRD
│   │   ├── findings.md        # Feature-specific findings
│   │   ├── progress.txt       # Story progress
│   │   ├── mega-findings.md   # Read-only link to shared findings
│   │   └── .planning-config.json
│   └── feature-products/
│       └── ...

Commands Reference

/mega:plan

Generate a mega-plan for project-level multi-feature orchestration. Breaks a complex project into parallel features with dependencies.

/mega:plan [options] <project description> [design-doc-path]

Parameters:

Parameter Description
--flow <quick|standard|full> Execution flow depth controlling quality gate strictness
--tdd <off|on|auto> Test-Driven Development mode for feature execution
--confirm Require confirmation before each batch
--no-confirm Disable batch confirmation
--spec <off|auto|on> Spec interview before plan generation
--first-principles Enable first-principles questioning in spec interview
--max-questions N Max questions in spec interview
design-doc-path Optional path to existing design document

Parameters are saved to mega-plan.json and propagated to /mega:approve and feature-level /approve commands.

Example:

/mega:plan --flow full --tdd auto Create a blog platform with user accounts, article management, comments, and RSS feeds

/mega:edit

Edit the mega-plan interactively. Add, remove, or modify features.

/mega:edit

/mega:approve

Approve the mega-plan and start feature execution. Creates worktrees and generates PRDs for each feature in batch-by-batch order.

/mega:approve [options]

Parameters:

Parameter Description
--flow <quick|standard|full> Execution flow depth for feature execution
--tdd <off|on|auto> TDD mode propagated to feature execution
--confirm Require confirmation before each batch
--no-confirm Disable batch confirmation
--spec <off|auto|on> Spec interview for feature PRD generation
--first-principles First-principles questioning for spec interviews
--max-questions N Max questions in spec interviews
--auto-prd Auto-approve all generated PRDs (skip manual review)
--agent <name> Global agent override
--prd-agent <name> Agent for PRD generation phase
--impl-agent <name> Agent for story implementation phase

Approval Modes:

Mode Trigger Use Case
Manual PRD Review /mega:approve Review each feature's PRD before execution
Auto PRD Approval /mega:approve --auto-prd Trust PRD generation, fully automated execution

/mega:status

Show detailed status of mega-plan execution including feature progress, story completion, and batch summary.

/mega:status

/mega:complete

Complete the mega-plan by cleaning up planning files. All features should already be merged via /mega:approve.

/mega:complete

mega-plan.json Format

{
  "metadata": {
    "created_at": "2026-01-28T10:00:00Z",
    "version": "1.0.0"
  },
  "goal": "Project goal",
  "description": "Original user description",
  "execution_mode": "auto",
  "target_branch": "main",
  "features": [
    {
      "id": "feature-001",
      "name": "feature-auth",
      "title": "User Authentication",
      "description": "Detailed description for PRD generation",
      "priority": "high",
      "dependencies": [],
      "status": "pending"
    }
  ]
}

Feature Status Flow

pending → prd_generated → approved → in_progress → complete
                                           ↓
                                        failed
Status Description
pending Feature not yet started
prd_generated Worktree created, PRD generated
approved PRD approved, ready for execution
in_progress Stories are being executed
complete All stories complete
failed Feature execution failed

Execution Modes

Auto Mode

Features and their story batches execute automatically:

Batch 1 (Features) → PRDs generated → approved → stories execute → complete
         ↓
Batch 2 (Features) → PRDs generated → approved → stories execute → complete
         ↓
All complete → /mega:complete

Manual Mode

Each batch waits for explicit confirmation:

Batch 1 → PRDs generated → [you review] → /approve in each worktree
         ↓
Batch 2 → PRDs generated → [you review] → /approve in each worktree
         ↓
All complete → /mega:complete

Workflows

Complete Workflow

1. /mega:plan "Build e-commerce platform"
   ↓
2. Review generated mega-plan.json
   ↓
3. /mega:edit (if needed) or /mega:approve
   ↓
4. Feature worktrees created (Batch 1)
   ↓
5. PRDs generated in each worktree
   ↓
6. Review and /approve in each worktree (or use --auto-prd)
   ↓
7. Stories execute in parallel
   ↓
8. Monitor with /mega:status
   ↓
9. Batch 2 features start when Batch 1 complete
   ↓
10. All complete → /mega:complete

Multi-Terminal Workflow

# Terminal 1: Main orchestration
/mega:plan "Project description"
/mega:approve
/mega:status  # Monitor progress

# Terminal 2: Feature 1 work
cd .worktree/feature-auth
/approve  # Approve PRD
# ... stories execute ...

# Terminal 3: Feature 2 work (parallel!)
cd .worktree/feature-products
/approve  # Approve PRD
# ... stories execute ...

# Terminal 1: After all complete
/mega:complete

Relationship with Hybrid Ralph

Mega Plan orchestrates multiple hybrid-ralph workflows:

Component Mega Plan Hybrid Ralph
Scope Project-level Feature-level
Unit Features Stories
Files mega-plan.json prd.json
Findings mega-findings.md (shared) findings.md (per-feature)
Worktrees Creates for features Works within worktree
Merge All features → target N/A (handled by mega)

Core Python Modules

mega_generator.py

Generates mega-plan from project descriptions.

# Validate mega-plan
uv run python mega_generator.py validate

# Show execution batches
uv run python mega_generator.py batches

# Show progress
uv run python mega_generator.py progress

mega_state.py

Thread-safe state management.

# Read mega-plan
uv run python mega_state.py read-plan

# Read status
uv run python mega_state.py read-status

# Sync from worktrees
uv run python mega_state.py sync-worktrees

feature_orchestrator.py

Orchestrates feature execution.

# Show execution plan
uv run python feature_orchestrator.py plan

# Show status
uv run python feature_orchestrator.py status

merge_coordinator.py

Coordinates final merge.

# Verify all complete
uv run python merge_coordinator.py verify

# Show merge plan
uv run python merge_coordinator.py plan

# Complete (merge & cleanup)
uv run python merge_coordinator.py complete

Findings Management

Shared Findings (mega-findings.md)

  • Located at project root
  • Contains findings relevant to all features
  • Read-only copy placed in each worktree
  • Updated only from project root

Feature Findings (findings.md)

  • Located in each feature worktree
  • Contains feature-specific discoveries
  • Tagged with story IDs
  • Independent per feature

Best Practices

  1. Clear Feature Boundaries: Each feature should be independent enough to develop in isolation
  2. Minimize Dependencies: Fewer dependencies mean more parallelism
  3. Meaningful Names: Use descriptive feature names (they become directory names)
  4. Review PRDs: Take time to review generated PRDs before approving
  5. Monitor Progress: Use /mega:status regularly to track execution
  6. Handle Failures: If a feature fails, fix it in its worktree before completing

Troubleshooting

Worktree Conflict

Error: Worktree already exists

Solution: Remove stale worktree or use different feature name.

Merge Conflict

Error: Merge conflict in feature-001

Solution:

  1. Resolve conflict in target branch
  2. Re-run /mega:complete

Incomplete Features

Error: Incomplete features: feature-002, feature-003

Solution:

  1. Check /mega:status for details
  2. Complete stories in incomplete features
  3. Re-run /mega:complete

See Also

实现类Manus的文件式规划,通过持久化Markdown文件管理复杂任务。支持会话恢复与可选的Git worktree并行开发模式,适用于多步骤任务及需多次工具调用的场景。
开始复杂的多步骤任务 启动研究项目 需要超过5次工具调用的操作
skills/planning-with-files/SKILL.md
npx skills add Taoidle/plan-cascade --skill planning-with-files -g -y
SKILL.md
Frontmatter
{
    "name": "planning-with-files",
    "hooks": {
        "Stop": [
            {
                "hooks": [
                    {
                        "type": "command",
                        "command": "SCRIPT_DIR=\"${CLAUDE_PLUGIN_ROOT:-$HOME\/.claude\/plugins\/planning-with-files}\/scripts\"\nif command -v pwsh &> \/dev\/null && [[ \"$OSTYPE\" == \"msys\" || \"$OSTYPE\" == \"win32\" || \"$OS\" == \"Windows_NT\" ]]; then\n  pwsh -ExecutionPolicy Bypass -File \"$SCRIPT_DIR\/check-complete.ps1\" 2>\/dev\/null || powershell -ExecutionPolicy Bypass -File \"$SCRIPT_DIR\/check-complete.ps1\" 2>\/dev\/null || bash \"$SCRIPT_DIR\/check-complete.sh\"\nelse\n  bash \"$SCRIPT_DIR\/check-complete.sh\"\nfi"
                    }
                ]
            }
        ],
        "PreToolUse": [
            {
                "hooks": [
                    {
                        "type": "command",
                        "command": "SCRIPT_DIR=\"${CLAUDE_PLUGIN_ROOT:-$HOME\/.claude\/plugins\/planning-with-files}\/scripts\"\n# Check for worktree config and verify location\nif [ -f \".planning-config.json\" ]; then\n  # Determine which verification script to use\n  if command -v pwsh &> \/dev\/null && [[ \"$OSTYPE\" == \"msys\" || \"$OSTYPE\" == \"win32\" || \"$OS\" == \"Windows_NT\" ]]; then\n    pwsh -ExecutionPolicy Bypass -File \"$SCRIPT_DIR\/verify-location.ps1\" 2>\/dev\/null || powershell -ExecutionPolicy Bypass -File \"$SCRIPT_DIR\/verify-location.ps1\" 2>\/dev\/null || bash \"$SCRIPT_DIR\/verify-location.sh\"\n  else\n    bash \"$SCRIPT_DIR\/verify-location.sh\"\n  fi\n  # Exit code 1 means wrong location - block the operation\n  if [ $? -eq 1 ]; then\n    exit 1\n  fi\nfi\n"
                    }
                ],
                "matcher": "Write|Edit"
            },
            {
                "hooks": [
                    {
                        "type": "command",
                        "command": "# In worktree mode, silence read\/grep\/glob operations\nif [ -f \".planning-config.json\" ]; then\n  MODE=$(jq -r '.mode' .planning-config.json 2>\/dev\/null || echo \"\")\n  if [ \"$MODE\" = \"worktree\" ]; then\n    # Silent for read\/grep\/glob in worktree mode\n    case \"$CLAUDE_TOOL_NAME\" in\n      Read|Glob|Grep) exit 0 ;;\n    esac\n  fi\nfi\n# Show task_plan for write\/edit\/bash or standard mode\ncat task_plan.md 2>\/dev\/null | head -30 || true"
                    }
                ],
                "matcher": "Write|Edit|Bash|Read|Glob|Grep"
            }
        ],
        "PostToolUse": [
            {
                "hooks": [
                    {
                        "type": "command",
                        "command": "echo '[planning-with-files] File updated. If this completes a phase, update task_plan.md status.'"
                    }
                ],
                "matcher": "Write|Edit"
            }
        ]
    },
    "version": "3.2.0",
    "description": "Implements Manus-style file-based planning for complex tasks. Creates task_plan.md, findings.md, and progress.md. Use when starting complex multi-step tasks, research projects, or any task requiring >5 tool calls. Now with automatic session recovery after \/clear and optional Git worktree mode.",
    "allowed-tools": [
        "Read",
        "Write",
        "Edit",
        "Bash",
        "Glob",
        "Grep",
        "WebFetch",
        "WebSearch"
    ],
    "user-invocable": true
}

Planning with Files

Work like Manus: Use persistent markdown files as your "working memory on disk."

FIRST: Check for Previous Session (v2.2.0)

Before starting work, check for unsynced context from a previous session:

# Linux/macOS
uv run python ${CLAUDE_PLUGIN_ROOT}/scripts/session-catchup.py "$(pwd)"
# Windows PowerShell
& (Get-Command python -ErrorAction SilentlyContinue).Source "$env:USERPROFILE\.claude\skills\planning-with-files\scripts\session-catchup.py" (Get-Location)

If catchup report shows unsynced context:

  1. Run git diff --stat to see actual code changes
  2. Read current planning files
  3. Update planning files based on catchup + git diff
  4. Then proceed with task

Important: Where Files Go

  • Templates are in ${CLAUDE_PLUGIN_ROOT}/templates/
  • Your planning files go in your project directory
Location What Goes There
Skill directory (${CLAUDE_PLUGIN_ROOT}/) Templates, scripts, reference docs
Your project directory task_plan.md, findings.md, progress.md

Quick Start

Standard Mode

Before ANY complex task:

  1. Create task_plan.md — Use templates/task_plan.md as reference
  2. Create findings.md — Use templates/findings.md as reference
  3. Create progress.md — Use templates/progress.md as reference
  4. Re-read plan before decisions — Refreshes goals in attention window
  5. Update after each phase — Mark complete, log errors

Worktree Mode (Multi-Task Parallel Development)

For parallel multi-task development with isolated Git worktrees:

  1. Start worktree mode — Use /planning-with-files:worktree [task-name] [target-branch]

    • Example: /planning-with-files:worktree feature-auth main
    • Creates a new Git worktree directory (.worktree/feature-auth/)
    • Creates a task branch with planning files inside the worktree
    • Main directory stays on original branch (no switching!)
    • Multiple worktrees can exist simultaneously for parallel tasks
  2. Navigate to worktreecd .worktree/feature-auth

    • Work on your task in this isolated environment
    • Follow standard planning workflow
  3. Complete and merge — Use /planning-with-files:complete [target-branch] from inside the worktree

    • Deletes planning files from worktree
    • Navigates to root directory
    • Merges task branch to target
    • Removes the worktree directory
    • Deletes the task branch

Multi-Task Example:

# Start task 1
/planning-with-files:worktree fix-auth-bug
cd .worktree/fix-auth-bug

# In another terminal, start task 2 (parallel!)
/planning-with-files:worktree refactor-api
cd .worktree/refactor-api

# Each task has its own directory and branch
# No conflicts, no branch switching needed

Benefits:

  • Work on multiple tasks simultaneously without conflicts
  • Each task has its own isolated environment
  • No need to switch branches in the main directory
  • Easy cleanup when tasks are complete

Note: Planning files go in your project root, not the skill installation folder.

The Core Pattern

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

→ Anything important gets written to disk.

File Purposes

File Purpose When to Update
task_plan.md Phases, progress, decisions After each phase
findings.md Research, discoveries After ANY discovery
progress.md Session log, test results Throughout session

Critical Rules

1. Create Plan First

Never start a complex task without task_plan.md. Non-negotiable.

2. The 2-Action Rule

"After every 2 view/browser/search operations, IMMEDIATELY save key findings to text files."

This prevents visual/multimodal information from being lost.

3. Read Before Decide

Before major decisions, read the plan file. This keeps goals in your attention window.

4. Update After Act

After completing any phase:

  • Mark phase status: in_progresscomplete
  • Log any errors encountered
  • Note files created/modified

5. Log ALL Errors

Every error goes in the plan file. This builds knowledge and prevents repetition.

## Errors Encountered
| Error | Attempt | Resolution |
|-------|---------|------------|
| FileNotFoundError | 1 | Created default config |
| API timeout | 2 | Added retry logic |

6. Never Repeat Failures

if action_failed:
    next_action != same_action

Track what you tried. Mutate the approach.

The 3-Strike Error Protocol

ATTEMPT 1: Diagnose & Fix
  → Read error carefully
  → Identify root cause
  → Apply targeted fix

ATTEMPT 2: Alternative Approach
  → Same error? Try different method
  → Different tool? Different library?
  → NEVER repeat exact same failing action

ATTEMPT 3: Broader Rethink
  → Question assumptions
  → Search for solutions
  → Consider updating the plan

AFTER 3 FAILURES: Escalate to User
  → Explain what you tried
  → Share the specific error
  → Ask for guidance

Read vs Write Decision Matrix

Situation Action Reason
Just wrote a file DON'T read Content still in context
Viewed image/PDF Write findings NOW Multimodal → text before lost
Browser returned data Write to file Screenshots don't persist
Starting new phase Read plan/findings Re-orient if context stale
Error occurred Read relevant file Need current state to fix
Resuming after gap Read all planning files Recover state

The 5-Question Reboot Test

If you can answer these, your context management is solid:

Question Answer Source
Where am I? Current phase in task_plan.md
Where am I going? Remaining phases
What's the goal? Goal statement in plan
What have I learned? findings.md
What have I done? progress.md

When to Use This Pattern

Use for:

  • Multi-step tasks (3+ steps)
  • Research tasks
  • Building/creating projects
  • Tasks spanning many tool calls
  • Anything requiring organization

Skip for:

  • Simple questions
  • Single-file edits
  • Quick lookups

Templates

Copy these templates to start:

Scripts

Helper scripts for automation:

Standard Mode Scripts

  • scripts/init-session.sh — Initialize all planning files
  • scripts/check-complete.sh — Verify all phases complete
  • scripts/session-catchup.py — Recover context from previous session (v2.2.0)

Worktree Mode Scripts (v2.7.2)

  • scripts/worktree-init.sh — Start a new worktree session (bash)
  • scripts/worktree-init.ps1 — Start a new worktree session (PowerShell)
  • scripts/worktree-complete.sh — Complete and merge worktree (bash)
  • scripts/worktree-complete.ps1 — Complete and merge worktree (PowerShell)

Advanced Topics

Anti-Patterns

Don't Do Instead
Use TodoWrite for persistence Create task_plan.md file
State goals once and forget Re-read plan before decisions
Hide errors and retry silently Log errors to plan file
Stuff everything in context Store large content in files
Start executing immediately Create plan file FIRST
Repeat failed actions Track attempts, mutate approach
Create files in skill directory Create files in your project

Home - Wiki
Copyright © 2011-2026 iteam. Current version is 2.155.2. UTC+08:00, 2026-07-21 03:40
浙ICP备14020137号-1 $Map of visitor$