--- name: plan-and-build description: > Dual-mode workflow: PLAN mode (deep code analysis → structured plan → approval gate → ZERO code changes) then BUILD mode (step-by-step execution with auto-debug, auto-test, and Plan Fidelity Score). Use when: (1) user asks to plan, design, architect, blueprint, or "think before building", (2) user says "plan mode", "/plan", "plan:", "спланируй", "план", "архитектура", (3) task involves 3+ files, new feature, refactor, API design, or DB schema, (4) user describes a complex task without saying "just do it". NOT for: quick one-liners, trivial edits, simple file reads, or when user explicitly says "no plan, just do it". ⚠️ TOKEN USAGE: ~5k context overhead + 30-400k per session depending on complexity. Free models (qwen/qwen3:free) = free. Paid models: ~$0.15-$5/session. 🐛 Bug reports & feature requests: Telegram @gym_rat1488 metadata: openclaw: emoji: "🧠" --- # Plan & Build > ⚠️ **Token Cost Notice:** This skill uses ~5k context tokens per message + 30-400k per full session depending on task. > **Free models** (qwen/qwen3:free): $0 — use freely. **Paid models** (Claude, GPT-4): ~$0.15-$5 per session. > Only use this skill for non-trivial tasks (3+ files, new features, refactors). For simple edits, use direct commands. Think first. Build on approval. Debug automatically. Test everything. Report fidelity. --- ## STATE MACHINE ``` [No Plan] ─────▶ [PLANNING] ─────▶ [WAITING_APPROVAL] │ │ │ ┌─────┴──────┐ │ "reject" "approve" │ │ │ │ ▼ ▼ │ [No Plan] [PRE-BUILD GATE] │ │ │ ┌──────┴──────┐ │ denied/abort granted │ │ │ │ ▼ ▼ │ [No Plan] [BUILDING] │ │ │ ┌──────┴──────┐ │ completed error (≤3 retries) │ │ │ │ ▼ ▼ │ [COMPLETED] ← self-heal │ │ │ all retries fail │ │ │ ▼ │ [WAITING_APPROVAL] (re-plan) └────────────────────── (loop if user requests changes) ``` --- ## PLAN Mode **GOLDEN RULE: During PLAN mode — ZERO write/edit/destructive exec on the codebase.** Allowed: `read`, `grep`, `glob`, `list`, `exec` (read-only: `ls`, `cat`, `grep`, `git log --no-pager`, `git diff --no-pager`, `find`, `tree`, `wc`, `head`, `tail`), `web_fetch`, `web_search`, `memory_search`. FORBIDDEN: `write`, `edit`, `patch`, `exec rm/del/install/pip/npm/composer` (anything that mutates), `bash` with side effects. ### Step 1: Recon 1. Read SOUL.md, USER.md, MEMORY.md for project context. 2. Scan project structure — `tree -L 2` or `ls` of root. 3. Read key files: entry points, configs (`package.json`, `requirements.txt`, `pyproject.toml`, `.env.example`, etc.), main modules. 4. Read files directly related to the request. Be surgical — don't read the whole tree. ### Step 2: Analysis Build mental model of: - Current architecture and data flow - Exact files to create/modify/delete (with line refs if modifying) - Dependencies, imports, and potential breakage points - Open questions requiring user decision ### Step 3: Produce Plan Output in this EXACT format: ```markdown # 🧠 Plan: ## Context 1-2 sentences: what we're building and why. ## 📁 Impact Table | File | Change | Risk | Why | |------|--------|------|-----| | src/auth.py | Modify (line ~42) | 🔴 High — core auth logic | Add JWT generation | | src/models/user.py | Create | 🟢 Low | New User model | | tests/test_auth.py | Create | 🟢 Low | 5 test cases | ## 📐 Architecture Approach + patterns (MVC, repository, etc.). ASCII diagram if non-trivial. ## 🔧 Execution Steps 1. **[Create]** `src/models/user.py` — User: id, email, hashed_password, timestamps 2. **[Modify]** `src/auth.py` — JWT generation + update /login route 3. **[Create]** `tests/test_auth.py` — register, login, invalid creds, expired, refresh 4. **[Validate]** Run pytest — expect 5/5 green 5. **[Update]** `README.md` — auth API docs ## ⚠️ Risks & Decisions Needed - 🔴 **Risk:** Modifying `auth.py` may break OAuth sessions → backup first - ❓ **Decision:** bcrypt vs argon2? (Recommend: bcrypt) - ❓ **Decision:** Token expiry — 24h or configurable? ## ✅ Acceptance Criteria - [ ] POST /api/register → 201 + user created - [ ] POST /api/login → valid JWT - [ ] Passwords never plaintext - [ ] Tests: 5/5 passing - [ ] No OAuth regressions --- 💬 Reply with: - **"approve"** — Pre-Build Gate → BUILD - **"approve with: "** — revise → Pre-Build Gate → BUILD - **"reject"** — discuss alternatives ``` **STOP after outputting the plan. Do NOT write/edit/create ANY file in the project. Wait for approval.** Only exception: if user says "save the plan" → ensure `.openclaw/plans/` exists (`mkdir -p .openclaw/plans` or equivalent), then write to `.openclaw/plans/YYYY-MM-DD-.md` with frontmatter: ```yaml --- status: draft task: "" created: YYYY-MM-DD --- ``` --- ## PRE-BUILD GATE — NEVER SKIP THIS **Before any BUILD mode begins, you MUST present this gate and wait for explicit permission.** ```markdown ## 🔒 Pre-Build Check | Check | Status | Detail | |-------|--------|--------| | Plan approved | ✅ | | | Backup created | ✅/⏳ | `git commit` / manual snapshot / N/A | | Auto-debug max retries | ⚙️ 3 (default) | | Auto-test after build | ⚙️ ON | | Build steps | 🔢 5 | | Estimated time | ⏱️ ~5 min | ### Permissions Requested **1. Auto-Debugging** — If any step fails (syntax error, missing import, runtime crash, test failure), I will automatically: - Read the error message and traceback - Identify the root cause (missing file, wrong path, typo, wrong dependency) - Fix the code in place - Re-run the validation - Retry up to **3 iterations** per step - If all retries fail → STOP and report to you **2. Auto-Testing** — After all BUILD steps complete, I will: - Run available tests (pytest, npm test, etc.) - Verify structural integrity (files exist, no syntax errors) - Check each Acceptance Criterion from the plan - Calculate a **Plan Fidelity Score** (% match to the original plan) - Report results in a structured format **3. Rollback Permission** — If Build fails catastrophically, I will: - Use `git reset --hard` (if git project) to revert all changes - Or manually delete created files and undo modifications - Report exactly what was rolled back --- ⚡ Reply: - **"build / давай / го / ✅"** → start BUILD - **"no debug"** → BUILD without auto-debugging (manual only) - **"no tests"** → BUILD without auto-testing - **"abort"** → cancel, back to planning ``` **DO NOT BUILD until the user grants permission.** Respect their choice on debug/test toggles. ### What Each Toggle Means | Toggle | If ON | If OFF | |--------|-------|--------| | Auto-Debug | Fix errors automatically (≤3 retries per step) | Stop on first error, wait for user | | Auto-Test | Run tests + Fidelity Score after BUILD | Skip testing, just report files changed | | Rollback | Auto-revert on catastrophic failure | Inform user, wait for manual instruction | --- ## BUILD Mode — AFTER Gate Cleared ### Build Execution Loop (per step) ``` For each step in the approved plan: 1. Announce: "🔨 Step X/N: " 2. EXECUTE the change (write/edit/create/modify) 3. VALIDATE immediately: - Syntax: python -m py_compile / node -c / equivalent - Import check: quick import or require test - Read-back: verify the file contains expected content - If step was [Validate]: run the actual test/lint command 4. If validation FAILS and auto-debug is ON → SELF-HEAL CYCLE (below) 5. If validation FAILS and auto-debug is OFF → STOP, report error 6. If validation PASSES → report: "✅ Step X/N done" 7. Commit: `git add -A && git commit -m "plan-and-build: step X/N - "` After all steps → POST-BUILD VERIFICATION ``` ### Self-Heal Cycle (auto-debugging) When a step fails and auto-debug is ON: ``` DEBUG ITERATION (i/3 of 3) for Step X/N: 1. [Diagnose] Read error output. Classify error type: - SYNTAX → missing bracket, wrong indentation, typo - IMPORT → wrong module path, missing dependency, circular import - RUNTIME → null reference, wrong args, unhandled exception - TEST → logic error, wrong assertion, missing fixture - ENV → missing package, wrong Python/Node version, permission denied 2. [Read] Open the failing file and 10 lines around the error 3. [Fix] Apply the minimal fix using edit tool 4. [Verify] Re-run the SAME validation that failed 5. If it passes → log "🩹 Fixed in debug attempt i/3", continue to next step 6. If it fails → log "❌ Debug attempt i/3 failed: ", retry or escalate 7. After 3 failed attempts → STOP, report: - What failed - What was tried - Error messages - Options: (a) user provides guidance, (b) re-plan, (c) rollback ``` **Debug rules:** - Max 3 iterations per failure. No infinite loops. - Never try random fixes — always read the error first. - If the error is ENV-related (missing dependency), ask user before installing. - If the same error appears after 2 fixes, stop and escalate. ### Parallel BUILD (for independent steps) If steps are INDEPENDENT (no file dependencies between them), parallelize: ``` Spawn subagent for each independent step: sessions_spawn(task: "Plan-and-Build Step 2/N: . Follow the plan exactly. Validate after each change.") Monitor with subagents(action=list). ``` If steps are DEPENDENT (step N needs step N-1 output), run sequentially. ### BUILD Rules - **No deviation.** Follow the approved plan exactly. If you discover a better approach mid-build, report it and ask before deviating. - **Atomic commits.** One git commit per step. Never bundle multiple steps. - **Never push/deploy** without explicit approval after BUILD completes. - **User mid-build changes.** If user says "actually, also do X" → add to plan, acknowledge, continue. Don't restart the full plan. - **Respect toggles.** If user said "no debug" → DO NOT auto-fix. If "no tests" → DO NOT test. --- ## POST-BUILD VERIFICATION (if auto-test is ON) After all BUILD steps complete successfully: ### 1. Structural Verification ```markdown ## 📋 Structural Check - [ ] All created files exist - [ ] All modified files are readable - [ ] No syntax errors in any changed file - [ ] No broken imports ``` ### 2. Functional Testing Run available test suites, smoke tests, or manual verification: - `pytest`, `npm test`, `cargo test`, `go test`, or equivalent - For web projects: `curl` or `web_fetch` on endpoints - For CLI tools: run the command with sample input - For static sites: check that the build produces output (if applicable) ### 3. Acceptance Criteria Verification Go through each acceptance criterion from the plan. Test it. ### 4. Plan Fidelity Score ```markdown ## 📊 Plan Fidelity Score ### Step Completion | Step | Description | Status | Notes | |------|-------------|--------|-------| | 1 | Create user model | ✅ Done | 42 lines, all fields correct | | 2 | Modify auth.py | ✅ Done | JWT added, route updated | | 3 | Create test file | ✅ Done | 5/5 tests passing | | 4 | Run validation | ✅ Done | pytest green | | 5 | Update README | ✅ Done | Auth section added | ### Metrics - **Steps completed:** 5/5 → 100% - **Acceptance criteria met:** 5/5 → 100% - **Tests passing:** 5/5 → 100% - **Auto-debug cycles used:** 1/3 (Step 2 — import path fixed) - **Files created:** 2 | **Modified:** 2 | **Deleted:** 0 ### 🏆 Plan Fidelity: 100% Interpretation: 100% — Perfect. Plan executed exactly as designed. 90-99% — Excellent. Minor deviations, no functional impact. 75-89% — Good. Acceptable with minor tradeoffs noted. 60-74% — Partial. Some criteria unmet — review needed. Below 60% — Incomplete. Significant re-plan or rework recommended. ``` ### 5. Edge Cases & Recommendations ```markdown ## 🔍 Edge Cases Discovered - - ## 💡 Recommendations for Next Iteration - Add rate limiting to /login - Add input validation for email format - Consider adding refresh token rotation ``` --- ## ROLLBACK PROCEDURE Triggered when: user says "rollback", build fails catastrophically, or user says "undo everything". ``` ROLLBACK: 1. If git project: `git diff --name-only` → list changed files 2. For uncommitted changes: `git checkout -- ` or delete newly created files 3. For committed changes: `git reset --hard HEAD~N` (N = commits made during build) 4. Verify rollback: `git status` should be clean or back to pre-build state 5. Report: "🔄 Rollback complete. Restored to state before Build." 6. Move plan status to "rejected" or "archived" ``` --- ## Smart Sizing (Heuristics) Auto-adjust plan depth + BUILD rigor: | Signals | Plan Depth | BUILD Rigor | |---------|-----------|-------------| | 1-2 files, trivial, low risk | 3-bullet inline | Quick validate, no deep tests | | 3-10 files, moderate | Full plan template | Full self-heal + tests | | 10+ files, architectural | Full plan + subagent analysis | Full + subagent parallel BUILD | | Destructive (DB migration, prod) | Full + backup plan as Step 0 | Max debug (3), manual gate before rollback | --- ## Proactive Planning If the user describes a task with **any** of these signals → default to PLAN mode: - Mentions: "API", "database", "auth", "migration", "refactor", "redesign", "build", "create", "new feature", "restructure" - 3+ files affected, or new feature from scratch - Words: "big", "complex", "rethink", "from zero", "с нуля", "полностью" Ask: *"Хочу сначала спланировать — покажу список файлов, архитектуру и риски до того как начну писать. Ок?"* If user says "no plan, just do it" / "просто сделай" / "без плана, делай" → skip PLAN, BUILD immediately. --- ## Quick Triggers | User says | Action | |-----------|--------| | "plan: ", "/plan", "/plan ", "спланируй" | Enter PLAN mode | | "approve", "✅", "давай", "го", "build", "+", "ок" | Pre-Build Gate → (if approved) → BUILD | | "approve with: " | PLAN → revise → Pre-Build Gate → BUILD | | "reject", "nope", "нет" | Discard plan | | "no debug" | BUILD without auto-debugging | | "no tests" | BUILD without auto-testing | | "rollback" | Execute rollback | | "status" | Show current plan state | | "last plan" | Show most recent plan | --- ## Plan File Format (Audit Trail) If user says "save the plan" or project has `.openclaw/plans/` directory. If the directory does not exist, create it first (`mkdir -p .openclaw/plans` or equivalent). ``` .openclaw/plans/ ├── 2026-04-02-auth-system.md (status: completed) ├── 2026-04-05-dashboard-redesign.md (status: draft) └── 2026-04-10-api-v2-migration.md (status: rejected) ``` Each file has YAML frontmatter with `status`, `task`, `created`, and optionally `approved`, `completed`, `fidelity_score`. --- ## What This Beats (vs OpenCode's Plan Mode) | Feature | OpenCode Plan Mode | Plan & Build | |---------|-------------------|--------------| | Tool lockdown | System-level | Behavioral (GOLDEN RULE) | | Plan structure | Freeform | Structured: Impact Table, Architecture, Steps, Risks, Criteria | | Pre-Build Gate | None | Permission request with debug/test/rollback toggles | | Auto-Debugging | None | Self-heal cycle with error classification, ≤3 retries | | Auto-Testing | None | Structural + functional + acceptance criteria verification | | Plan Fidelity Score | None | % completion across steps, criteria, and tests | | Audit trail | Manual | Auto-save to `.openclaw/plans/` with status tracking | | Mode switching | UI keybind | Natural language (EN + RU) | | Plan → Build | Manual | Seamless pipeline with explicit gate | | Smart sizing | None | Auto-adjusts by task complexity | | Rollback | Manual | Guided with git + manual cleanup | | Error classification | None | Syntax/Import/Runtime/Test/ENV categorization | | Edge case reporting | None | Post-build edge case discovery + recommendations | | Parallel BUILD | No | Subagent spawning for independent steps | | Build rigor | None | Per-step validate → commit → next step | --- ## Community & Feedback 🐛 **Bug reports, feature requests, suggestions:** Telegram **@gym_rat1488** Found a bug? A mode not triggering correctly? Want a feature? Message directly — the author reads every report. > 💬 *"This skill was born from one person's need to ship code without breaking things. If you make it better, I want to know."* --- ## Anti-Patterns (What NOT to Do) - ❌ Start writing code during PLAN mode - ❌ Skip Pre-Build Gate or present it as a formality — user MUST consciously approve - ❌ Auto-debug more than 3 times per failure - ❌ Auto-install dependencies without asking - ❌ Deploy or push without explicit post-build approval - ❌ Silently deviate from the plan — if you discover a better way, REPORT it - ❌ Continue building after catastrophic failure — STOP and re-plan - ❌ Skip structural verification even if auto-test is off (minimum: check files exist and have no syntax errors)