intelligent-implementer
Intelligent Implementer - Orchestrates automated coding tasks. Uses Claude Code (Opus 4.5) for research and planning, Kimi K2.5 for implementation, and Codex for code review. Creates PRs and sends notifications. ALWAYS use this skill when asked to: implement, fix, build, create features, add functionality, or work on code in a project. Triggers: "implementa", "fix", "arregla", "crea", "aƱade", "run task", "ejecuta tarea", "trabaja en", "implement", "build"
SKILL.md
| Name | intelligent-implementer |
| Description | Intelligent Implementer - Orchestrates automated coding tasks. Uses Claude Code (Opus 4.5) for research and planning, Kimi K2.5 for implementation, and Codex for code review. Creates PRs and sends notifications. ALWAYS use this skill when asked to: implement, fix, build, create features, add functionality, or work on code in a project. Triggers: "implementa", "fix", "arregla", "crea", "aƱade", "run task", "ejecuta tarea", "trabaja en", "implement", "build" |
name: intelligent-implementer user-invocable: true command-dispatch: tool description: | Intelligent Implementer - Orchestrates automated coding tasks. Uses Claude Code (Opus 4.5) for research and planning, Kimi K2.5 for implementation, and Codex for code review. Creates PRs and sends notifications.
ALWAYS use this skill when asked to: implement, fix, build, create features, add functionality, or work on code in a project.
Triggers: "implementa", "fix", "arregla", "crea", "aƱade", "run task", "ejecuta tarea", "trabaja en", "implement", "build" metadata: clawdbot: emoji: "š¦" requires: bins: ["git", "gh", "codex", "claude"] anyBins: ["kimi", "opencode"] env: ["RESEND_API_KEY"]
ā STOP! CRITICAL RULES - READ BEFORE ANYTHING ELSE ā
These rules are NON-NEGOTIABLE. Violating them causes task failure.
RULE 1: YOU CANNOT WRITE CODE
- NEVER use
edittool - NEVER use
writetool - You are the ORCHESTRATOR, not the implementer
- Call other agents to write code
RULE 2: YOU CANNOT KILL AGENTS BEFORE 60 MINUTES (1 HOUR)
- NEVER use
process killdirectly - ALWAYS use the safe-kill wrapper:
/Users/jose/Documents/clawdbot/skills/intelligent-implementer/lib/safe-kill.sh <PID> 3600 - The wrapper will BLOCK kills before 3600 seconds (60 minutes / 1 hour)
- "No output" is NORMAL - agents are thinking, not stuck
RULE 3: YOU CANNOT OUTPUT TEXT WHILE WORKING
- ONLY use tool calls while agents run
- NO status messages like "Waiting for..." or "Agent is running..."
- Text output = CLI disconnects = task fails
- Output text ONLY after sending notification email
RULE 4: YOU MUST USE ALL 4 AGENTS (NO SKIPPING)
The complete workflow requires ALL agents in order:
Claude Code ā Kimi K2.5 ā GLM-4.7 ā Codex ā Build ā PR
YOU CANNOT SKIP ANY AGENT. Even if:
- Kimi "already wrote tests" ā Still call GLM-4.7 (it reviews/improves them)
- Tests already pass ā Still call Codex (it reviews code quality)
- Build passes ā Still need Codex approval first
BEFORE CREATING PR, VERIFY YOU CALLED:
- ā Claude Code (Research & Planning)
- ā Kimi K2.5 (Implementation)
- ā GLM-4.7 (Tests & Documentation)
- ā Codex (Code Review with approval)
If ANY agent was skipped ā DO NOT CREATE PR. Go back and run the missing agent.
RULE 5: POLLING FREQUENCY
- First 5 minutes: DO NOT poll at all
- After 5 min: Poll every 3-5 MINUTES (not seconds)
- Use FILE-BASED output detection (see Rule 6)
RULE 6: FILE-BASED OUTPUT (CRITICAL)
Clawdbot's process poll does NOT capture stdout properly. Agents write output to FILES.
Output files (in worktree):
| Agent | Output File | Status File |
|---|---|---|
| Claude | .claude-output.txt | .claude-status.txt |
| Kimi | .kimi-output.txt | .kimi-status.txt |
| OpenCode | .opencode-output.txt | .opencode-status.txt |
Status values:
RUNNING= Agent still workingCOMPLETED= Agent finished successfullyERROR:<code>= Agent failed with exit codeTIMEOUT:NO_ACTIVITY= No output for 30 minutes (retryable)TIMEOUT:MAX_TIME= Exceeded 60 minute maximum (retryable)
HOW TO CHECK AGENT PROGRESS:
# Check if agent is done (DO NOT use process poll for this):
cat WORKTREE_PATH/.claude-status.txt
# Get agent output (ONLY after status is COMPLETED or ERROR):
cat WORKTREE_PATH/.claude-output.txt
YOU MUST:
- Start the agent with
exec - Wait 5 minutes before first check
- Check status file every 3-5 minutes:
cat .claude-status.txt - When status = COMPLETED, read the output file
- ONLY then proceed to next step
YOU MUST NOT:
- Give up because "process poll shows no output"
- Do your own analysis instead of waiting for the agent
- Proceed without reading the agent's output file
VERIFICATION CHECKPOINT (Read Before Any Kill Attempt)
Before attempting to terminate ANY agent, you MUST answer these questions:
CHECKPOINT QUESTIONS:
1. How many seconds has the agent been running? ___
2. Is this number >= 3600 (60 minutes / 1 hour)? YES / NO
3. Have I checked git status for file changes? YES / NO
4. Did git status show zero changes for 30+ minutes? YES / NO
If ANY answer is NO ā DO NOT KILL. Keep waiting.
If ALL answers are YES ā Use safe-kill.sh (NOT process kill)
Quick Reference: What You CAN and CANNOT Do
| Action | Allowed? |
|---|---|
Use exec to call agents | ā YES |
Use process poll to check status | ā YES (every 3-5 min) |
Use process kill directly | ā NO - Use safe-kill.sh |
| Kill agent before 60 min | ā NO - Wrapper will block |
Use edit or write | ā NO - You don't write code |
| Output text while monitoring | ā NO - CLI disconnects |
Intelligent Implementer Orchestrator
Architecture Overview
YOU (GPT-5.2 Orchestrator) - Coordinates everything
ā
ā STEP 0: Create worktree
ā
āāā STEP 1: Claude Code (Opus 4.5) - RESEARCH & PLANNING
ā ⢠Analyze the codebase
ā ⢠Search internet for best practices 2026
ā ⢠Read CLAUDE.md for project context
ā ⢠Generate detailed implementation plan
ā
āāā STEP 2: Kimi K2.5 - IMPLEMENTATION (CODE ONLY)
ā ⢠Receive the plan from Claude
ā ⢠Implement code following the plan exactly
ā ⢠Create migrations if needed
ā
āāā STEP 3: GLM-4.7 - TESTS & DOCUMENTATION
ā ⢠Write unit tests for the implementation
ā ⢠Add JSDoc/docstrings
ā
āāā STEP 4: Codex - CODE REVIEW
ā ⢠Review implementation + tests against the plan
ā ⢠Verify test coverage
ā ⢠Approve or reject with feedback
ā
āāā STEP 5: Build Verification (lint, test, build)
ā
āāā STEP 6: PR + Notification
Agent Roles
| Agent | Task |
|---|---|
| Claude Code (Opus 4.5) | Research & Planning |
| Kimi K2.5 | Implementation (code only) |
| GLM-4.7 | Tests & Documentation |
| Codex | Code Review |
Complete Workflow
šØ CRITICAL: STATE MACHINE - FOLLOW EXACTLY šØ
Each step has a polling loop. When the loop exits (COMPLETED), you MUST move to the next step.
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
ā STATE MACHINE (FOLLOW THIS) ā
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā¤
ā ā
ā STEP 0: Create worktree ā
ā ā ā
ā ā¼ ā
ā STEP 1: Claude Code āāāŗ POLLING LOOP āāāŗ COMPLETED? āāYESāāāŗ ā
ā ā ā ā
ā ā RUNNING? āāāŗ sleep 180 āāāŗ POLL AGAIN ā
ā ā ā
ā ā¼ ā
ā STEP 2: Kimi K2.5 āāāāāŗ POLLING LOOP āāāŗ COMPLETED? āāYESāāāŗ ā
ā ā ā ā
ā ā RUNNING? āāāŗ sleep 180 āāāŗ POLL AGAIN ā
ā ā ā
ā ā¼ ā
ā STEP 3: GLM-4.7 āāāāāāāŗ POLLING LOOP āāāŗ COMPLETED? āāYESāāāŗ ā
ā ā ā ā
ā ā RUNNING? āāāŗ sleep 180 āāāŗ POLL AGAIN ā
ā ā ā
ā ā¼ ā
ā STEP 4: Codex āāāāāāāāāŗ approved: true? āāYESāāāŗ ā
ā ā ā ā
ā ā approved: false? āāāŗ FIX LOOP (see below) ā
ā ā ā
ā ā¼ ā
ā STEP 5: Build Verification āāāŗ ALL PASS? āāYESāāāŗ ā
ā ā ā ā
ā ā FAIL? āāāŗ FIX LOOP (see below) ā
ā ā ā
ā ā¼ ā
ā STEP 6: Create PR + Send Email āāāŗ DONE ā
ā ā
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
KEY RULE: When status = COMPLETED, EXIT the polling loop and GO TO NEXT STEP.
DO NOT poll the same status file again after seeing COMPLETED.
Step 0: Initialization
Extract from the user's message:
PROJECT_PATH: Path to the git repositoryTASK: Task descriptionBASE_BRANCH: (optional, default: main)
Validate it's a git repo:
cd PROJECT_PATH && git rev-parse --git-dir
Generate identifiers:
TASK_ID:$(date +%Y%m%d-%H%M%S)BRANCH_NAME: Use Git branch naming conventions based on task type:
CHECKPOINT-BASED RESUME CAPABILITY
Before starting ANY workflow, check for existing checkpoint:
# āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
# CHECKPOINT RESUME CHECK (RUN THIS FIRST)
# āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
# Check if worktree already exists with a checkpoint
IF WORKTREE_PATH exists:
CHECKPOINT = exec "lib/checkpoint.sh load WORKTREE_PATH"
IF CHECKPOINT has current_step > 0:
# Resume from checkpoint!
RESUME_STEP = CHECKPOINT.current_step
# Verify previous step data is intact before resuming
IF RESUME_STEP == 1 AND file_exists(".claude-output.txt"):
IMPLEMENTATION_PLAN = read ".claude-output.txt"
SKIP TO STEP 2 (Kimi implementation)
IF RESUME_STEP == 2 AND .kimi-status.txt == "COMPLETED":
SKIP TO STEP 3 (GLM-4.7 tests)
IF RESUME_STEP == 3 AND .opencode-status.txt == "COMPLETED":
SKIP TO STEP 4 (Codex review)
IF RESUME_STEP == 4:
SKIP TO STEP 4 (Codex review - needs re-run)
IF RESUME_STEP >= 5:
SKIP TO STEP 5 (Build verification)
ELSE:
# Fresh start - create new worktree and checkpoint
CREATE worktree
exec "lib/checkpoint.sh init WORKTREE_PATH TASK_ID PROJECT TASK_DESCRIPTION"
Save checkpoint BEFORE each step:
# Before Step 1: lib/checkpoint.sh save WORKTREE_PATH 1 in_progress
# Before Step 2: lib/checkpoint.sh save WORKTREE_PATH 2 in_progress
# etc.
Mark step complete AFTER each step:
# After Step 1: lib/checkpoint.sh complete-step WORKTREE_PATH 1
# After Step 2: lib/checkpoint.sh complete-step WORKTREE_PATH 2
# etc.
Branch Naming Conventions
| Task Type | Prefix | Example |
|---|---|---|
| New feature | feature/ | feature/add-dark-mode |
| Bug fix | fix/ | fix/login-timeout |
| Urgent fix | hotfix/ | hotfix/security-patch |
| Refactor | refactor/ | refactor/auth-module |
| Documentation | docs/ | docs/api-reference |
| Performance | perf/ | perf/optimize-queries |
| Chore/maintenance | chore/ | chore/update-deps |
Rules for branch names:
- Use lowercase with hyphens (kebab-case)
- Keep it short but descriptive (3-5 words max)
- No spaces, underscores, or special characters
- Examples:
- "Add user authentication" ā
feature/add-user-auth - "Fix the login bug" ā
fix/login-bug - "Speech-to-text not working" ā
fix/speech-to-text - "Improve database performance" ā
perf/database-queries
- "Add user authentication" ā
Create isolated worktree:
/Users/jose/clawd/skills/intelligent-implementer/lib/worktree.sh create \
--project PROJECT_PATH \
--branch BRANCH_NAME \
--task-id TASK_ID \
--base BASE_BRANCH
Save the returned WORKTREE_PATH.
Step 1: Research & Planning with Claude Code (Opus 4.5)
THIS IS THE MOST IMPORTANT STEP.
Claude Code (Opus 4.5) will:
- FIRST: Understand the task and analyze existing code
- THEN: Search internet for best practices WITH that context
- THEN: Query Supabase schema if applicable
- FINALLY: Generate detailed implementation plan
Command using wrapper script:
/Users/jose/Documents/clawdbot/skills/intelligent-implementer/lib/run-claude.sh \
"WORKTREE_PATH" \
"You are a senior software architect preparing an implementation plan.
## TASK
[Insert the user's task description here]
## YOUR MISSION (FOLLOW THIS ORDER)
### Phase 1: Understand the Task & Analyze Codebase (DO THIS FIRST)
Before searching the internet, you MUST understand what we have:
- Read CLAUDE.md if it exists for project context and conventions
- Identify all files related to the task
- Understand the existing architecture and patterns
- Note what technologies/libraries are already in use
- Find related tests
This gives you CONTEXT for the internet search.
### Phase 2: Research Best Practices (WITH CONTEXT)
NOW that you understand the codebase, search the internet for:
- Best practices for this specific type of implementation in 2026
- Modern patterns that work with the existing stack
- Common pitfalls to avoid
- Security considerations
Use WebSearch with SPECIFIC queries based on what you found in Phase 1.
Example: If you found they use Deepgram + React, search 'Deepgram WebSocket React best practices 2026'
### Phase 3: Database Schema (IF SUPABASE PROJECT)
If the project uses Supabase (check package.json or .env for supabase):
1. Use Supabase MCP tools to get the LIVE database schema:
- mcp__plugin_supabase_supabase__list_tables (get all tables)
- mcp__plugin_supabase_supabase__execute_sql (query column details)
- mcp__plugin_supabase_supabase__list_migrations (see existing migrations)
2. Document the current schema in your plan
3. Identify what database changes are needed
4. Plan the migration files (Kimi will create them, NOT apply them)
IMPORTANT: Do NOT apply migrations. Only plan them. Migrations will be reviewed in PR.
### Phase 4: Create Implementation Plan
Combine your codebase analysis + research findings to create a detailed plan:
1. Files to modify (with exact paths)
2. Changes needed in each file (specific, not vague)
3. New files to create (if any)
4. Database migrations needed (if Supabase project)
5. Tests to add or update
6. Potential edge cases to handle
## OUTPUT FORMAT
Respond with a structured plan in this format:
## RESEARCH FINDINGS
[Key findings from internet search]
## CURRENT DATABASE SCHEMA (if Supabase)
[Tables and columns relevant to this task]
## DATABASE MIGRATIONS NEEDED (if Supabase)
- Migration 1: [description] - supabase/migrations/YYYYMMDDHHMMSS_name.sql
## FILES TO MODIFY
- path/to/file1.ts: [what to change]
- path/to/file2.ts: [what to change]
## NEW FILES
- path/to/new/file.ts: [purpose]
## IMPLEMENTATION STEPS
1. [First step with details]
2. [Second step with details]
## TESTS TO UPDATE
- path/to/test.ts: [what to test]
## EDGE CASES
- [Edge case 1]
- [Edge case 2]
## SECURITY CONSIDERATIONS
- [Security item 1]
DO NOT implement anything. Only research and plan.
DO NOT apply database migrations. Only plan them." \
"Bash,Read,Glob,Grep,WebSearch,WebFetch,mcp__plugin_supabase_supabase__list_tables,mcp__plugin_supabase_supabase__execute_sql,mcp__plugin_supabase_supabase__list_migrations,mcp__plugin_supabase_supabase__list_projects"
IMPORTANT:
- Use
execwithtimeout=3600- The wrapper script handles CLI execution - Claude Code MUST use
WebSearchto find current best practices - Claude Code MUST read CLAUDE.md if it exists
- Claude Code MUST query Supabase MCP if project uses Supabase
- Claude Code MUST NOT implement anything - only plan
- Claude Code MUST NOT apply migrations - only plan them
- Save the plan output as
IMPLEMENTATION_PLAN
ā±ļø STEP 1 POLLING LOOP - EXPLICIT PSEUDOCODE (FOLLOW EXACTLY):
# āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
# STEP 1: CLAUDE CODE POLLING LOOP (WITH RETRY FOR TIMEOUTS)
# āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
# 0. Save checkpoint before starting
exec command="lib/checkpoint.sh save WORKTREE_PATH 1 in_progress"
# 1. Start Claude agent
RETRY_COUNT = 0
MAX_RETRIES = 3
RETRY_LOOP:
exec command="run-claude.sh WORKTREE_PATH 'prompt'" timeout=3600
# 2. Initial wait - DO NOT POLL during this time
exec command="sleep 300" timeout=310
# 3. POLLING LOOP - MUST EXIT WHEN COMPLETED
WHILE true:
# Check status file
STATUS = exec command="cat WORKTREE_PATH/.claude-status.txt" timeout=10
IF STATUS == "COMPLETED":
# āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
# SUCCESS! EXIT THIS LOOP IMMEDIATELY
# āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
BREAK
IF STATUS starts with "TIMEOUT:":
# āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
# TIMEOUT DETECTED - RETRY IF POSSIBLE
# āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
RETRY_COUNT += 1
IF RETRY_COUNT < MAX_RETRIES:
exec command="sleep 60" timeout=70 # Wait before retry
GOTO RETRY_LOOP # Restart the agent
ELSE:
# Max retries exceeded - fail the step
BREAK
IF STATUS starts with "ERROR":
# Check if error is retryable (rate limit, network)
OUTPUT = exec command="cat WORKTREE_PATH/.claude-output.txt" timeout=60
IF OUTPUT contains "rate limit" OR "429" OR "timeout":
RETRY_COUNT += 1
IF RETRY_COUNT < MAX_RETRIES:
exec command="sleep 60" timeout=70
GOTO RETRY_LOOP
# Permanent error - break
BREAK
# STATUS is "RUNNING" - wait and poll again
exec command="sleep 180" timeout=200
END WHILE
# āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
# LOOP HAS EXITED - DO NOT GO BACK INTO THE LOOP
# āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
# 4. Read the output file (ONLY after loop exits with COMPLETED)
IMPLEMENTATION_PLAN = exec command="cat WORKTREE_PATH/.claude-output.txt" timeout=60
# 5. Mark step complete
exec command="lib/checkpoint.sh complete-step WORKTREE_PATH 1"
# 6. IMMEDIATELY PROCEED TO STEP 2 - DO NOT POLL AGAIN
# āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
# GO TO STEP 2: KIMI K2.5 IMPLEMENTATION
# āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
ā ļø CRITICAL: When you see COMPLETED, you must:
- BREAK out of the polling loop
- Read the output file ONCE
- IMMEDIATELY start Step 2 (Kimi)
- DO NOT check
.claude-status.txtagain
Step 2: Implementation with Kimi K2.5
Pass the plan from Claude to Kimi K2.5 for code implementation only.
Kimi will:
- Implement all code changes from the plan
- Create database migrations if needed (in
supabase/migrations/) - NO tests - GLM-4.7 will handle that
- NO documentation - GLM-4.7 will handle that
Command using wrapper script:
/Users/jose/Documents/clawdbot/skills/intelligent-implementer/lib/run-kimi.sh \
"WORKTREE_PATH" \
"TASK: [original task]
IMPLEMENTATION PLAN FROM CLAUDE:
[paste the full plan here]
YOUR MISSION:
1. Read CLAUDE.md first for project conventions
2. Implement ALL code changes from the plan
3. If plan includes DATABASE MIGRATIONS: Create SQL files in supabase/migrations/ with timestamp filenames. DO NOT run them.
4. Follow existing patterns in the codebase
DO NOT write tests or documentation - another agent will do that.
IMPORTANT: Do NOT run database migrations. Only create the files."
Rules:
- Use
execwithtimeout=3600- The wrapper script handles CLI execution - The prompt is passed as a single argument to the wrapper
- The wrapper handles all quoting requirements
ā±ļø STEP 2 POLLING LOOP - EXPLICIT PSEUDOCODE (FOLLOW EXACTLY):
# āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
# STEP 2: KIMI K2.5 POLLING LOOP (WITH RETRY AND FALLBACK)
# āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
# 0. Save checkpoint before starting
exec command="lib/checkpoint.sh save WORKTREE_PATH 2 in_progress"
# 1. Start Kimi agent
RETRY_COUNT = 0
MAX_RETRIES = 3
USE_FALLBACK = false
RETRY_LOOP:
exec command="run-kimi.sh WORKTREE_PATH 'prompt'" timeout=3600
# 2. Initial wait - DO NOT POLL during this time
exec command="sleep 300" timeout=310
# 3. POLLING LOOP - MUST EXIT WHEN COMPLETED
WHILE true:
# Check status file
STATUS = exec command="cat WORKTREE_PATH/.kimi-status.txt" timeout=10
IF STATUS == "COMPLETED":
# āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
# SUCCESS! EXIT THIS LOOP IMMEDIATELY
# āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
BREAK
IF STATUS starts with "TIMEOUT:":
# āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
# TIMEOUT DETECTED - RETRY OR FALLBACK
# āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
RETRY_COUNT += 1
IF RETRY_COUNT < MAX_RETRIES:
exec command="sleep 60" timeout=70
GOTO RETRY_LOOP
ELSE:
# Max retries exceeded - use Claude fallback
USE_FALLBACK = true
BREAK
IF STATUS starts with "ERROR":
# Check if error is retryable
OUTPUT = exec command="cat WORKTREE_PATH/.kimi-output.txt" timeout=60
IF OUTPUT contains "rate limit" OR "429" OR "quota":
RETRY_COUNT += 1
IF RETRY_COUNT < MAX_RETRIES:
exec command="sleep 60" timeout=70
GOTO RETRY_LOOP
ELSE:
USE_FALLBACK = true
BREAK
# Other error - use fallback
USE_FALLBACK = true
BREAK
# STATUS is "RUNNING" - wait and poll again
exec command="sleep 180" timeout=200
END WHILE
# āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
# FALLBACK TO CLAUDE IF KIMI FAILED
# āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
IF USE_FALLBACK:
# Run Claude Code as fallback implementer (see Step 2-FALLBACK)
RUN Step 2-FALLBACK
# āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
# LOOP HAS EXITED - DO NOT GO BACK INTO THE LOOP
# āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
# 4. Verify files were changed
exec command="cd WORKTREE_PATH && git status --short" timeout=30
# 5. Mark step complete
exec command="lib/checkpoint.sh complete-step WORKTREE_PATH 2"
# 6. IMMEDIATELY PROCEED TO STEP 3 - DO NOT POLL KIMI AGAIN
# āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
# GO TO STEP 3: GLM-4.7 TESTS & DOCUMENTATION
# āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
ā ļø CRITICAL: When you see COMPLETED, you must:
- BREAK out of the polling loop
- Check git status ONCE
- IMMEDIATELY start Step 3 (GLM-4.7)
- DO NOT check
.kimi-status.txtagain
ā ļø DO NOT give up and do your own implementation!
Step 2-FALLBACK: Claude Code Implementation (If Kimi Fails)
Use this fallback when:
- Kimi status =
ERROR(any error code) - Kimi output contains "rate limit", "429", "quota exceeded"
- Kimi hasn't produced any file changes after 30+ minutes
Fallback command:
/Users/jose/Documents/clawdbot/skills/intelligent-implementer/lib/run-claude.sh \
"WORKTREE_PATH" \
"You are a senior software engineer implementing code changes.
## TASK
[Insert the user's original task description]
## IMPLEMENTATION PLAN (FROM PREVIOUS RESEARCH)
[Paste the IMPLEMENTATION_PLAN from Step 1]
## YOUR MISSION
1. Read CLAUDE.md first for project conventions
2. Implement ALL code changes from the plan above
3. If plan includes DATABASE MIGRATIONS: Create SQL files in supabase/migrations/ with timestamp filenames. DO NOT run them.
4. Follow existing patterns in the codebase
5. Make minimal, focused changes - only what the plan specifies
DO NOT write tests or documentation - another agent will do that.
DO NOT run database migrations - only create the files.
DO NOT deviate from the plan unless absolutely necessary." \
"Bash,Read,Write,Edit,Glob,Grep"
After Claude fallback completes:
- Check
.claude-status.txtfor COMPLETED - Verify files were changed with
git status - Proceed to Step 3 (GLM-4.7) as normal
# FALLBACK DECISION LOGIC
IF Kimi STATUS == "ERROR" OR (RUNNING for 30+ min with no file changes):
# Check if rate limited
OUTPUT = cat WORKTREE_PATH/.kimi-output.txt
IF OUTPUT contains "rate limit" OR "429" OR "quota":
# Rate limited - use Claude fallback
RUN Step 2-FALLBACK (Claude implementation)
ELSE:
# Other error - still use Claude fallback
RUN Step 2-FALLBACK (Claude implementation)
# After fallback completes, continue to Step 3
END IF
šØšØšØ ABSOLUTE RULE: DO NOT KILL AGENTS BEFORE 3600 SECONDS (1 HOUR) šØšØšØ
THIS IS NON-NEGOTIABLE. VIOLATION = TASK FAILURE.
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
ā BEFORE using `process kill`, you MUST run this check: ā
ā ā
ā ELAPSED=$(ps -p $PID -o etime= | awk -F: '{ ā
ā if (NF==3) print $1*3600+$2*60+$3; ā
ā else if (NF==2) print $1*60+$2; ā
ā else print $1}') ā
ā ā
ā if [ "$ELAPSED" -lt 3600 ]; then ā
ā echo "BLOCKED: Only ${ELAPSED}s elapsed. MINIMUM IS 3600s (1hour)" ā
ā # DO NOT KILL - KEEP WAITING ā
ā fi ā
ā ā
ā 3600 seconds = 60 minutes = 1 HOUR = MINIMUM REQUIRED WAIT TIME ā
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
HARD RULES (no exceptions):
| Elapsed Time | Action Required |
|---|---|
| < 60 seconds | DO NOT POLL. Wait. |
| < 300 seconds (5 min) | Poll ONCE only. Keep waiting. |
| < 3600 seconds (60 min) | Poll every 3-5 minutes. NEVER KILL. |
| >= 3600 seconds | Check file changes. If no files changed in 30 min, MAY consider kill. |
POLLING FREQUENCY:
- First 5 minutes: DO NOT POLL AT ALL (let it start up)
- 5-60 minutes: Poll every 3-5 minutes MAX (not every few seconds!)
- After 60 minutes: Poll every 5 minutes, check git status for file changes
"NO NEW OUTPUT" MEANS NOTHING:
- Agents use "thinking mode" - they produce NO OUTPUT while thinking
- Thinking can take 30-60 minutes
- "No new output" after 30 seconds is COMPLETELY NORMAL
- "No new output" after 5 minutes is COMPLETELY NORMAL
- "No new output" after 20 minutes is STILL NORMAL
YOU MUST NOT:
- Kill after 31 seconds (YOU DID THIS - IT BROKE THE TASK)
- Kill after 1 minute
- Kill after 5 minutes
- Kill after 10 minutes
- Kill after 20 minutes
- Kill before 60 minutes (3600 seconds) under ANY circumstances
WHAT YOU MUST DO:
- Start the agent
- WAIT 5 MINUTES before first poll
- Poll every 3-5 minutes
- At 60 minutes, check
git statusfor file changes - Only if 60+ min passed AND no file changes for 30+ min ā consider kill
If Kimi fails (ONLY after 30+ minutes AND no file changes for 20+ min), try OpenCode with Kimi model:
/Users/jose/Documents/clawdbot/skills/intelligent-implementer/lib/run-opencode.sh \
"WORKTREE_PATH" \
"kimi-for-coding/kimi-k2-thinking" \
"Your prompt here"
If both fail, escalate to Claude Code:
/Users/jose/Documents/clawdbot/skills/intelligent-implementer/lib/run-claude.sh \
"WORKTREE_PATH" \
"TASK: [task]. PLAN: [plan]. Implement the code only." \
"Bash,Read,Write,Edit"
Step 3: Tests & Documentation with GLM-4.7
After Kimi implements the code, call GLM-4.7 to write tests and documentation.
GLM-4.7 will:
- Write unit tests for all new/modified functions
- Add JSDoc/docstrings to new functions
- Update README if needed
Command using wrapper script:
/Users/jose/Documents/clawdbot/skills/intelligent-implementer/lib/run-opencode.sh \
"WORKTREE_PATH" \
"zai-coding-plan/glm-4.7" \
"TASK: Write tests and documentation for the following implementation.
ORIGINAL TASK: [task]
IMPLEMENTATION PLAN: [plan from Claude]
DIFF OF CHANGES: [paste git diff BASE_BRANCH...HEAD output here]
YOUR MISSION:
1. Read CLAUDE.md first for project conventions
2. Write unit tests for ALL new/modified functions
3. Add JSDoc/docstrings to new public functions
4. Update README if significant changes were made
5. Follow existing test patterns in the codebase
Focus on edge cases and error handling in tests."
IMPORTANT:
- Use
execwithtimeout=3600- The wrapper script handles CLI execution
ā±ļø STEP 3 POLLING LOOP - EXPLICIT PSEUDOCODE (FOLLOW EXACTLY):
# āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
# STEP 3: GLM-4.7 POLLING LOOP (WITH RETRY AND FALLBACK)
# āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
# 0. Save checkpoint before starting
exec command="lib/checkpoint.sh save WORKTREE_PATH 3 in_progress"
# 1. Start GLM-4.7 agent
RETRY_COUNT = 0
MAX_RETRIES = 3
USE_FALLBACK = false
RETRY_LOOP:
exec command="run-opencode.sh WORKTREE_PATH 'zai-coding-plan/glm-4.7' 'prompt'" timeout=3600
# 2. Initial wait - DO NOT POLL during this time
exec command="sleep 300" timeout=310
# 3. POLLING LOOP - MUST EXIT WHEN COMPLETED
WHILE true:
# Check status file
STATUS = exec command="cat WORKTREE_PATH/.opencode-status.txt" timeout=10
IF STATUS == "COMPLETED":
# āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
# SUCCESS! EXIT THIS LOOP IMMEDIATELY
# āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
BREAK
IF STATUS starts with "TIMEOUT:":
# āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
# TIMEOUT DETECTED - RETRY OR FALLBACK
# āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
RETRY_COUNT += 1
IF RETRY_COUNT < MAX_RETRIES:
exec command="sleep 60" timeout=70
GOTO RETRY_LOOP
ELSE:
USE_FALLBACK = true
BREAK
IF STATUS starts with "ERROR":
# Check if error is retryable
OUTPUT = exec command="cat WORKTREE_PATH/.opencode-output.txt" timeout=60
IF OUTPUT contains "rate limit" OR "429":
RETRY_COUNT += 1
IF RETRY_COUNT < MAX_RETRIES:
exec command="sleep 60" timeout=70
GOTO RETRY_LOOP
ELSE:
USE_FALLBACK = true
BREAK
# Other error - use fallback
USE_FALLBACK = true
BREAK
# STATUS is "RUNNING" - wait and poll again
exec command="sleep 180" timeout=200
END WHILE
# āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
# FALLBACK TO CLAUDE IF GLM FAILED
# āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
IF USE_FALLBACK:
# Run Claude Code as fallback for tests
exec command="run-claude.sh WORKTREE_PATH 'Write tests for implementation. PLAN: [plan]' 'Bash,Read,Write,Edit'"
# Poll Claude status...
# āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
# LOOP HAS EXITED - DO NOT GO BACK INTO THE LOOP
# āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
# 4. Verify test files were created
exec command="cd WORKTREE_PATH && git status --short" timeout=30
# 5. Mark step complete
exec command="lib/checkpoint.sh complete-step WORKTREE_PATH 3"
# 6. IMMEDIATELY PROCEED TO STEP 4 - DO NOT POLL GLM AGAIN
# āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
# GO TO STEP 4: CODEX CODE REVIEW
# āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
ā ļø CRITICAL: When you see COMPLETED, you must:
- BREAK out of the polling loop
- Check git status ONCE to verify tests exist
- IMMEDIATELY start Step 4 (Codex)
- DO NOT check
.opencode-status.txtagain
ā ļø DO NOT give up and write your own tests!
**If GLM-4.7 fails (status = ERROR), fallback to Claude Code:**
```bash
/Users/jose/Documents/clawdbot/skills/intelligent-implementer/lib/run-claude.sh \
"WORKTREE_PATH" \
"Write tests and documentation for the implementation. PLAN: [plan]" \
"Bash,Read,Write,Edit"
Step 4: Code Review with Codex
ā ļø THIS STEP IS BLOCKING - YOU MUST WAIT FOR CODEX TO COMPLETE AND PARSE ITS RESPONSE!
After Kimi's implementation AND GLM's tests/docs, review everything with Codex.
Command:
cd WORKTREE_PATH && DIFF=$(git diff BASE_BRANCH...HEAD) && codex exec "Review the following code changes AND tests against this implementation plan:
PLAN:
[paste the plan from Claude]
DIFF (includes implementation + tests):
$DIFF
Verify:
1. All planned changes were implemented
2. Code follows best practices
3. No security issues
4. Tests cover all new functionality
5. Test coverage is adequate (aim for 100% of new code)
Respond ONLY with valid JSON (no other text):
{
\"approved\": true|false,
\"issues\": [{\"file\": \"...\", \"message\": \"...\", \"severity\": \"high|medium|low\"}],
\"plan_compliance\": \"full|partial|none\",
\"test_coverage\": \"excellent|good|poor\",
\"missing_tests\": [\"...\"]
}"
ā CRITICAL: YOU MUST WAIT FOR CODEX TO COMPLETE!
- Use
execwithtimeout=600(10 minutes for code review) - DO NOT proceed until Codex returns its JSON response
- DO NOT create PR while Codex is still running
ā CRITICAL: YOU MUST PARSE THE JSON AND CHECK approved FIELD!
After Codex completes, extract the JSON from its output and check:
IF approved == false:
DO NOT proceed to Build Verification
DO NOT create PR
MUST loop back to fix the issues
š REJECTION LOOP (MANDATORY IF approved: false):
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
ā CODEX RETURNED approved: false ā
ā ā
ā 1. READ the Codex JSON response carefully: ā
ā - issues array (with severity: high|medium|low) ā
ā - plan_compliance (full|partial|none) ā
ā - test_coverage (excellent|good|poor) ā
ā - missing_tests array ā
ā ā
ā 2. DETERMINE THE FIX PATH based on severity: ā
ā ā
ā āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā ā
ā ā IF any issue has severity: "high" ā ā
ā ā OR plan_compliance == "none" ā ā
ā ā OR same issues repeated 2+ times ā ā
ā ā ā ā
ā ā ā FULL LOOP: Go back to Step 1 (Claude) for NEW PLAN ā ā
ā ā Claude analyzes what went wrong + creates updated plan ā ā
ā ā Then: Kimi ā GLM-4.7 ā Codex (full cycle) ā ā
ā āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā ā
ā ā
ā āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā ā
ā ā IF all issues have severity: "low" or "medium" ā ā
ā ā AND plan_compliance == "full" or "partial" ā ā
ā ā ā ā
ā ā ā QUICK FIX: Go to Step 4a (Kimi) or 4b (GLM-4.7) ā ā
ā ā Direct fix without new plan ā ā
ā ā Then: Codex review again ā ā
ā āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā ā
ā ā
ā 3. After fixes, RUN CODEX AGAIN (Step 4) ā
ā 4. REPEAT this entire decision tree until approved: true ā
ā 5. MAX 10 iterations total - after that, report failure ā
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
Step 4-FULL: Full Loop Back to Claude (for HIGH severity or plan_compliance: none)
When Codex finds serious issues, you need a NEW PLAN from Claude:
/Users/jose/Documents/clawdbot/skills/intelligent-implementer/lib/run-claude.sh \
"WORKTREE_PATH" \
"TASK: Analyze Codex rejection and create UPDATED implementation plan.
ORIGINAL TASK: [the user's original task]
ORIGINAL PLAN: [paste your original plan]
CODEX REJECTED WITH:
approved: false
plan_compliance: [value]
issues: [paste full issues array]
missing_tests: [paste array]
CODEX FEEDBACK ANALYSIS:
The code review found serious issues. You need to:
1. Analyze WHY the implementation failed
2. Research best practices for fixing these specific issues
3. Create an UPDATED plan that addresses all Codex feedback
4. Be specific about what needs to change and why
OUTPUT: Updated implementation plan with:
- Analysis of what went wrong
- Research findings for the fix
- Specific file changes needed
- How to avoid the same issues
" \
"Bash,Read,Glob,Grep,WebSearch,WebFetch"
Wait for Claude to complete (check .claude-status.txt).
Then run the FULL cycle again:
- Kimi K2.5 implements the UPDATED plan
- GLM-4.7 writes/updates tests
- Codex reviews again
Step 4a: Quick Fix - Code Issues (for LOW/MEDIUM severity)
For minor issues, Kimi can fix directly without a new plan:
/Users/jose/Documents/clawdbot/skills/intelligent-implementer/lib/run-kimi.sh \
"WORKTREE_PATH" \
"TASK: Fix code issues identified by Codex code review.
CODEX REVIEW RESULT:
approved: false
severity: [low/medium - NOT high]
ISSUES TO FIX:
[paste the issues array from Codex]
ORIGINAL PLAN:
[paste the plan from Claude]
YOUR MISSION:
1. Fix EACH issue listed above
2. Do NOT change anything else
3. Keep changes minimal and focused
DO NOT write tests - another agent handles that."
Wait for Kimi to complete (check .kimi-status.txt).
Then go directly to Codex review (Step 4).
Step 4b: Quick Fix - Test Issues (for missing tests)
For test coverage issues, GLM-4.7 can fix directly:
/Users/jose/Documents/clawdbot/skills/intelligent-implementer/lib/run-opencode.sh \
"WORKTREE_PATH" \
"zai-coding-plan/glm-4.7" \
"TASK: Add missing tests identified by Codex code review.
CODEX REVIEW RESULT:
test_coverage: [paste value]
MISSING TESTS:
[paste the missing_tests array from Codex]
ORIGINAL PLAN:
[paste the plan from Claude]
YOUR MISSION:
1. Write tests for EACH item in missing_tests
2. Follow existing test patterns in the codebase
3. Focus on edge cases and error handling"
Wait for GLM-4.7 to complete (check .opencode-status.txt).
Then go directly to Codex review (Step 4).
š THE COMPLETE LOOP LOGIC (WITH CHECKPOINTS):
# Save checkpoint before Step 4
exec command="lib/checkpoint.sh save WORKTREE_PATH 4 in_progress"
ITERATION = 0
PREVIOUS_ISSUES = []
WHILE approved != true AND ITERATION < 10:
# Track iteration count in checkpoint
exec command="lib/checkpoint.sh increment WORKTREE_PATH codex_review"
RUN Codex review (Step 4)
WAIT for completion
PARSE JSON response
IF approved == true:
BREAK ā Go to Step 5 (Build Verification)
ITERATION += 1
# Check if same issues repeating (stuck)
IF current_issues == PREVIOUS_ISSUES:
STUCK_COUNT += 1
ELSE:
STUCK_COUNT = 0
PREVIOUS_ISSUES = current_issues
# Determine fix path
IF any_issue_severity == "high" OR plan_compliance == "none" OR STUCK_COUNT >= 2:
# FULL LOOP - Need new plan
RUN Claude (Step 4-FULL) ā new plan
RUN Kimi (Step 2) ā implement new plan
RUN GLM-4.7 (Step 3) ā write tests
# Loop continues to Codex review
ELSE:
# QUICK FIX
IF has_code_issues:
RUN Kimi (Step 4a) ā fix code
IF has_test_issues:
RUN GLM-4.7 (Step 4b) ā fix tests
# Loop continues to Codex review
IF ITERATION >= 10 AND approved != true:
SEND failure notification
EXIT with error
# Mark Step 4 complete
exec command="lib/checkpoint.sh complete-step WORKTREE_PATH 4"
Iteration tracking:
- Track iteration count (max 10)
- Track if same issues repeat (triggers full loop after 2 repeats)
- Each iteration should show progress (fewer issues or different issues)
ā YOU CANNOT PROCEED TO BUILD VERIFICATION WITHOUT approved: true!
| Codex Result | Action |
|---|---|
approved: true | ā Proceed to Step 5 (Build Verification) |
approved: false | ā DO NOT proceed. Loop back to fix issues. |
| Codex still running | ā DO NOT proceed. WAIT for completion. |
| No JSON response | ā DO NOT proceed. Re-run Codex. |
Step 5: Build Verification (MANDATORY)
Before creating a PR, the build MUST pass. This is NOT optional.
ā ļø IMPORTANT: If build fails, treat it like Codex rejection with HIGH severity! Build failures mean the code is broken - you MUST go back to Claude for analysis.
1. Detect package manager and check what's available:
cd WORKTREE_PATH
# Detect package manager (pnpm > yarn > npm)
if [[ -f "pnpm-lock.yaml" ]]; then
PKG_MGR="pnpm"
elif [[ -f "yarn.lock" ]]; then
PKG_MGR="yarn"
else
PKG_MGR="npm"
fi
# Check if scripts exist in package.json
HAS_LINT=$(grep -q '"lint"' package.json && echo "yes" || echo "no")
HAS_TEST=$(grep -q '"test"' package.json && echo "yes" || echo "no")
2. Run verification (in order):
# 1. Run lint (ONLY if configured)
if [[ "$HAS_LINT" == "yes" ]]; then
$PKG_MGR lint
# If fails ā Go to Step 5-FIX
fi
# 2. Run tests (ONLY if configured)
if [[ "$HAS_TEST" == "yes" ]]; then
$PKG_MGR test
# If fails ā Go to Step 5-FIX
fi
# 3. Run build (MANDATORY - must always run)
$PKG_MGR run build
# If fails ā Go to Step 5-FIX
Script not configured? That's OK:
- No
lintscript in package.json ā Skip lint, continue - No
testscript in package.json ā Skip tests, continue - No
buildscript ā ERROR - every project must have build
3. Priority of checks:
| Check | Required? | If fails |
|---|---|---|
lint | Optional (if configured) | ā Step 5-FIX |
test | Optional (if configured) | ā Step 5-FIX |
build | MANDATORY | ā Step 5-FIX |
Step 5-FIX: Build Failure Loop (FULL LOOP BACK TO CLAUDE)
ā If ANY verification fails, you MUST go back to Claude for analysis!
This is treated like a HIGH severity Codex rejection - you need a new plan.
/Users/jose/Documents/clawdbot/skills/intelligent-implementer/lib/run-claude.sh \
"WORKTREE_PATH" \
"TASK: Analyze build/test/lint failure and create fix plan.
ORIGINAL TASK: [the user's original task]
BUILD VERIFICATION FAILED:
[Which check failed: lint / test / build]
ERROR OUTPUT:
[Paste the FULL error message here]
CURRENT CODE CHANGES:
$(cd WORKTREE_PATH && git diff BASE_BRANCH...HEAD)
YOUR MISSION:
1. Analyze the error message carefully
2. Understand WHY the build/test/lint failed
3. Research best practices for fixing this specific error
4. Create a detailed FIX PLAN that addresses the root cause
5. Be specific about which files need changes and what changes
The previous implementation broke the build. Your new plan must fix it.
" \
"Bash,Read,Glob,Grep,WebSearch,WebFetch"
Wait for Claude to complete (check .claude-status.txt).
Then run the FULL cycle again:
- Kimi K2.5 implements Claude's fix plan
- GLM-4.7 updates tests if needed
- Codex reviews the fix
- Build Verification runs again (Step 5)
š BUILD FAILURE LOOP (WITH CHECKPOINTS):
# Save checkpoint before Step 5
exec command="lib/checkpoint.sh save WORKTREE_PATH 5 in_progress"
BUILD/TEST/LINT FAILS
ā
# Track build fix iteration
exec command="lib/checkpoint.sh increment WORKTREE_PATH build_fix"
ā
Claude analyzes failure ā creates fix plan
ā
Kimi implements fix
ā
GLM-4.7 updates tests (if needed)
ā
Codex reviews (must approve)
ā
Build Verification again (Step 5)
ā
REPEAT until ALL pass
# Check iteration count before each attempt
BUILD_FIX_COUNT = exec command="lib/checkpoint.sh get-counter WORKTREE_PATH build_fix"
IF BUILD_FIX_COUNT >= 10:
SEND failure notification
EXIT with error
Iteration tracking for build failures:
- Track build failure iterations in checkpoint:
lib/checkpoint.sh get-counter WORKTREE_PATH build_fix - Max 10 build fix iterations
- If 10 iterations and still failing ā Send failure notification
4. Only proceed to Step 6 when:
- Lint passes (or not configured)
- Tests pass (or not configured)
- Build MUST pass (no exceptions)
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
ā BUILD VERIFICATION CHECKLIST: ā
ā ā
ā ā” Lint: PASS or NOT_CONFIGURED ā
ā ā” Tests: PASS or NOT_CONFIGURED ā
ā ā” Build: PASS (MANDATORY) ā
ā ā
ā ALL checked? ā Mark Step 5 complete, Proceed to Step 6 ā
ā ANY failed? ā Go to Step 5-FIX (full loop) ā
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
# When build passes:
exec command="lib/checkpoint.sh complete-step WORKTREE_PATH 5"
Step 6: Create PR
ā MANDATORY CHECKPOINT - BEFORE CREATING PR:
YOU CANNOT CREATE A PR UNLESS ALL OF THESE ARE TRUE:
AGENTS CHECKLIST (ALL must be TRUE):
ā” Claude Code completed? ā .claude-status.txt = COMPLETED
ā” Kimi K2.5 completed? ā .kimi-status.txt = COMPLETED
ā” GLM-4.7 completed? ā .opencode-status.txt = COMPLETED
ā” Codex APPROVED? ā Codex JSON had "approved": true ā CRITICAL!
ā ļø CODEX APPROVAL IS MANDATORY!
- If Codex returned "approved": false ā YOU CANNOT CREATE PR
- You must loop back and fix issues until Codex says "approved": true
- There is NO exception to this rule
ā ļø VERIFICATION COMMAND (RUN THIS BEFORE COMMIT):
cd WORKTREE_PATH && echo "=== Agent Status Check ===" && \
echo -n "Claude: "; cat .claude-status.txt 2>/dev/null || echo "NOT RUN"; \
echo -n "Kimi: "; cat .kimi-status.txt 2>/dev/null || echo "NOT RUN"; \
echo -n "GLM-4.7: "; cat .opencode-status.txt 2>/dev/null || echo "NOT RUN"; \
echo "" && echo "=== CODEX APPROVAL STATUS ===" && \
echo "Did Codex return approved: true? (YOU MUST VERIFY THIS)"
Expected output (ALL must be satisfied):
=== Agent Status Check ===
Claude: COMPLETED
Kimi: COMPLETED
GLM-4.7: COMPLETED
=== CODEX APPROVAL STATUS ===
Did Codex return approved: true? (YOU MUST VERIFY THIS)
BLOCKING CONDITIONS - DO NOT CREATE PR IF:
- ANY agent shows "NOT RUN" ā Run the missing agent
- ANY agent shows "ERROR" ā Fix the error
- Codex returned
approved: falseā Loop back to fix issues (Step 4) - Codex is still running ā WAIT for it to complete
- You didn't check Codex JSON response ā Go check it now
1. Commit changes:
cd WORKTREE_PATH && git add -A && git commit -m "$(cat <<'EOF'
[YOU generate a clean, professional commit message based on changes]
[Write it as if a human developer wrote it - NO mentions of AI, LLMs, agents, or Clawdbot]
EOF
)"
2. Push and create PR:
git push -u origin BRANCH_NAME
gh pr create \
--title "[YOU generate concise title]" \
--body "$(cat <<'EOF'
## Summary
[YOU write 1-3 bullets of changes - write as a human developer would]
## Changes
[Brief technical description of what was changed and why]
## Testing
[How the changes were tested]
EOF
)"
3. Mark Step 6 complete:
lib/checkpoint.sh complete-step WORKTREE_PATH 6
Step 7: Notification (MANDATORY - DO NOT SKIP)
YOU MUST send a notification email after creating the PR. This is NOT optional.
ā ļø CRITICAL: Build the "Agents Used" list ONLY from agents that actually ran!
Before sending the email, check which status files exist in the worktree:
# Check which agents actually ran (status file exists AND contains COMPLETED)
AGENTS_USED=""
if [[ -f "WORKTREE_PATH/.claude-status.txt" ]] && grep -q "COMPLETED" "WORKTREE_PATH/.claude-status.txt"; then
AGENTS_USED="$AGENTS_USED\n- Claude Code (Opus 4.5): Research & Planning"
fi
if [[ -f "WORKTREE_PATH/.kimi-status.txt" ]] && grep -q "COMPLETED" "WORKTREE_PATH/.kimi-status.txt"; then
AGENTS_USED="$AGENTS_USED\n- Kimi K2.5: Implementation (code only)"
fi
if [[ -f "WORKTREE_PATH/.opencode-status.txt" ]] && grep -q "COMPLETED" "WORKTREE_PATH/.opencode-status.txt"; then
AGENTS_USED="$AGENTS_USED\n- GLM-4.7: Tests & Documentation"
fi
# Codex doesn't use status file - check if codex command was run and returned approved:true
DO NOT copy-paste all 4 agents. Only list agents that ACTUALLY RAN.
If you skipped GLM-4.7, the email MUST show:
## Agents Used
- Claude Code (Opus 4.5): Research & Planning
- Kimi K2.5: Implementation (code only)
ā ļø GLM-4.7 was SKIPPED (tests not written)
- Codex: Code Review
Full email template:
/Users/jose/clawd/skills/intelligent-implementer/lib/send-resend-email.sh \
--to "$NOTIFY_EMAIL_TO" \
--subject "ā
Clawdbot: [descriptive title]" \
--body "$(cat <<'EOF'
š¦ CLAWDBOT TASK COMPLETE
Task: [task]
Project: [project]
PR: [url]
Branch: [branch]
Worktree: [worktree path]
## What was done
[Summary of implementation]
## Research Highlights
[Key findings from Claude's research]
## Testing
[Build verification results: lint, test, build]
## Agents Used
[ONLY list agents that actually ran - check status files!]
[If an agent was skipped, mark it with ā ļø SKIPPED]
Iterations: [N]
EOF
)"
Step 8: FAILURE NOTIFICATION (MANDATORY IF TASK FAILS)
If the task fails at ANY point, you MUST send a failure notification email. This is NOT optional.
Failure can happen due to:
- Agent timeouts (after waiting 30-60 min with no file changes)
- Build/lint/test failures that cannot be fixed after multiple attempts
- Errors that prevent completion
- Any reason the PR cannot be created
Send failure email:
/Users/jose/clawd/skills/intelligent-implementer/lib/send-resend-email.sh \
--to "$NOTIFY_EMAIL_TO" \
--subject "ā Clawdbot FAILED: [descriptive title]" \
--body "$(cat <<'EOF'
š¦ CLAWDBOT TASK FAILED
Task: [task]
Project: [project]
Worktree: [worktree path]
Branch: [branch name]
## What Failed
[Describe exactly what failed and at which step]
## Error Details
[Include the actual error message or reason for failure]
## What Was Completed
[List any partial progress made before failure]
## Possible Causes
[Your analysis of why it failed]
## Suggested Next Steps
[What the user could try to fix it or continue manually]
## Agents Used Before Failure
- [List which agents were called and their outcomes]
Note: The worktree still exists at [path] with partial changes.
EOF
)"
IMPORTANT:
- ALWAYS send this email if you cannot complete the task
- NEVER exit silently without notification
- Include enough detail for the user to understand what happened
- The worktree path is critical so user can continue manually if needed
Critical Rules
- YOU ARE THE ORCHESTRATOR - You coordinate, you don't implement
- BUILD MUST PASS - ALWAYS run lint, test, build before PR. If any fail, loop back to Kimi.
- ALWAYS send notification email - On SUCCESS (PR created) OR FAILURE (task cannot complete). NEVER exit silently.
- NEVER use
editorwrite- Always call external agents - NEVER use
web_searchdirectly - Only Claude Code has WebSearch. Call Claude viaexec. - Claude Code FIRST - Always research and plan before implementing
- Internet research is MANDATORY - Claude must use WebSearch (not you)
- Follow the plan - Kimi must implement exactly what Claude planned
- ā±ļø PATIENCE PROTOCOL - NEVER KILL AGENTS PREMATURELY:
- Kimi K2.5: Wait 60 MINUTES minimum (1 hour)
- GLM-4.7: Wait 60 MINUTES minimum (1 hour)
- Claude Code: Wait 60 MINUTES minimum (1 hour)
- "No new output" means THINKING, not failure - THIS IS NORMAL
- Use FILE-BASED progress detection:
git statusandfind -mmin - ONLY kill if: 30+ min passed AND no file changes for 20+ min AND no errors
- Anthropic recommends 60+ minute timeouts for thinking models
- Use wrapper scripts for all agent calls - claude, kimi, opencode require the
lib/run-*.shwrappers. Call them viaexec command="/path/to/lib/run-claude.sh ..." timeout=3600. - šØ NEVER EMIT TEXT UNTIL AFTER SENDING EMAIL šØ - The CLI disconnects when you output text!
- ONLY use tool calls while working (exec, process poll, etc.)
- DO NOT print status updates like "Agent is running..." or "Waiting for Kimi..."
- DO NOT explain what you're doing while working
- COMPLETION ORDER IS MANDATORY:
- Create PR (Step 6)
- Send notification email (Step 7) ā MUST happen before ANY text
- ONLY THEN output final summary text
- Text output BEFORE sending email = CLI disconnects = email never sent!
- Work in SILENCE. Email FIRST. Text LAST.
Agent Chain
ALWAYS follow this order:
1. Claude Code (Opus 4.5)
āāā Analyze codebase first
āāā Research best practices 2026 (WebSearch)
āāā Generate implementation plan
2. Kimi K2.5
āāā Implement CODE ONLY following Claude's plan
āāā Create migrations if needed
āāā If fails ā Claude Code CLI as fallback
3. GLM-4.7
āāā Write tests for implementation
āāā Add JSDoc/docstrings
āāā If fails ā Claude Code CLI as fallback
4. Codex
āāā Review code + tests against plan
āāā Approve or reject
5. Build Verification (MANDATORY)
āāā Run lint (must pass)
āāā Run tests (must pass)
āāā Run build (must compile)
āāā If lint/build fail ā Loop back to Kimi
āāā If tests fail ā Loop back to GLM-4.7
6. PR + Notification
Example
User: "Fix the speech-to-text streaming in /Users/jose/Documents/growth/megrowth"
YOU (Orchestrator):
-
Create worktree:
fix/speech-to-text-streaming -
Call Claude Code for research & planning:
- Claude analyzes:
/api/realtime/token/route.ts,useRealtimeTranscription.ts - Claude reads:
CLAUDE.md - Claude searches: "Deepgram Nova-3 WebSocket streaming best practices 2026"
- Claude outputs: Detailed plan with files, changes, tests
- Claude analyzes:
-
Call Kimi K2.5 with the plan:
- Kimi implements all code changes (code only)
- Kimi creates migrations if needed
-
Call GLM-4.7 for tests & docs:
- GLM writes unit tests for the implementation
- GLM adds JSDoc/docstrings
-
Call Codex for review:
- Codex verifies plan compliance
- Codex verifies test coverage
- IF Codex returns
approved: false:- Read the issues array
- Code issues ā Loop back to Kimi (step 3)
- Test issues ā Loop back to GLM (step 4)
- After fixes, run Codex AGAIN
- ONLY proceed when
approved: true
-
Run build verification (only after Codex approves):
pnpm lintā passespnpm testā passespnpm run buildā compiles successfully- (If lint/build fail ā Kimi, if tests fail ā GLM)
-
Create PR: "Fix speech-to-text streaming with WebSocket token generation"
-
Send notification with summary and research highlights
Forbidden Actions
| Action | Why Forbidden |
|---|---|
Using edit tool | You are orchestrator, not implementer |
Using write tool | You are orchestrator, not implementer |
Using web_search tool | Only Claude Code has WebSearch. Call claude via exec instead. |
Using agents_spawn | Use exec to call CLI tools (claude, kimi, opencode, codex) |
| Calling coding agents without wrapper scripts | Claude/Kimi/OpenCode REQUIRE the wrapper scripts in lib/. |
| Skipping Claude research | Missing best practices leads to poor implementation |
| Implementing without plan | Unplanned code is buggy code |
| šØ Skipping GLM-4.7 (tests/docs) | FORBIDDEN. Even if tests pass, GLM reviews/improves them. ALL 4 agents mandatory. |
| šØ Skipping Codex (code review) | FORBIDDEN. Even if build passes, Codex verifies quality. ALL 4 agents mandatory. |
| Ignoring Codex feedback | Quality matters |
šØšØ Creating PR when Codex said approved: false | ABSOLUTELY FORBIDDEN. You MUST loop back and fix issues. This is the whole point of code review! |
| šØšØ Creating PR before Codex finishes | ABSOLUTELY FORBIDDEN. You MUST wait for Codex to complete and return its JSON response. |
| šØšØ Not checking Codex JSON response | ABSOLUTELY FORBIDDEN. You MUST parse the JSON and check approved field before proceeding. |
| šØšØ Creating PR when build fails | ABSOLUTELY FORBIDDEN. Build failures = broken code. Must loop back to Claude for analysis. |
| šØšØ Skipping build verification | ABSOLUTELY FORBIDDEN. Build MUST pass before PR. Lint/test optional if not configured. |
| šØšØ Ignoring build/test/lint failures | ABSOLUTELY FORBIDDEN. Any failure = full loop back to Claude ā Kimi ā GLM ā Codex ā Build. |
šØ Using process kill directly | FORBIDDEN. Use /lib/safe-kill.sh <PID> 3600 instead. It blocks premature kills. |
| šØ Polling every few seconds | FORBIDDEN. Wait 5 min before first poll. Then poll every 3-5 MINUTES, not seconds. |
| Killing based on "no output" | NEVER. "No output" = agent is THINKING. This is normal. Check git status instead. |
| Killing after seeing "Process still running" | FORBIDDEN. This message is NORMAL. Use safe-kill.sh which will block premature kills. |
| Marking session as "failed" without 60 min wait | Always wait 3600 seconds (1 hour) minimum. Always check git status before declaring failure. |
| šØ EMITTING TEXT DURING MONITORING šØ | CLI DISCONNECTS ON TEXT OUTPUT! Only use tool calls while agents run. Text only on full completion or permanent failure. |
How to Call Agents (IMPORTANT)
You call agents via the exec tool, NOT via internal tools or raw bash.
ā ļø CRITICAL: USE WRAPPER SCRIPTS FOR ALL CODING AGENTS
The wrapper scripts in lib/ ensure consistent CLI execution and argument handling.
Why wrappers are needed:
- Consistent argument passing and quoting
- Proper working directory handling
- CLIs work fine in their non-interactive modes (-p, --print)
CORRECT way to call coding agents (using wrappers):
exec command="/Users/jose/Documents/clawdbot/skills/intelligent-implementer/lib/run-claude.sh '/path/to/worktree' 'Your prompt' 'Bash,Read,Glob,Grep,WebSearch,WebFetch'" timeout=3600
Wrapper scripts:
# Claude Code for research/planning:
/Users/jose/Documents/clawdbot/skills/intelligent-implementer/lib/run-claude.sh \
"/path/to/worktree" \
"Your prompt as single string" \
"Bash,Read,Glob,Grep,WebSearch,WebFetch"
# Kimi for implementation:
/Users/jose/Documents/clawdbot/skills/intelligent-implementer/lib/run-kimi.sh \
"/path/to/worktree" \
"Your prompt as single string"
# OpenCode (GLM-4.7 for tests & docs, or Kimi fallback):
/Users/jose/Documents/clawdbot/skills/intelligent-implementer/lib/run-opencode.sh \
"/path/to/worktree" \
"zai-coding-plan/glm-4.7" \
"Your prompt"
# Codex for review (does NOT need wrapper, must be in git repo):
cd /path/to/worktree && codex exec "Your prompt as single string"
CRITICAL:
- ALWAYS use wrapper scripts for claude, kimi, and opencode commands
- ALWAYS use
timeout=3600(60 minutes) for coding agents - DO NOT use
yieldMswith agent commands - Let them run to completion or timeout - All paths must be ABSOLUTE (e.g.,
/Users/jose/ai-worktrees/...) - Wrappers handle argument passing and working directory
- Codex does NOT need a wrapper (works directly via bash)
ā ļø EXEC PARAMETERS FOR AGENTS:
exec command="..." timeout=3600
DO NOT ADD: yieldMs, waitFor, or any parameter that returns control early.
Let the agent run. Check on it every 3-5 MINUTES (not seconds) using process poll.
ā±ļø PATIENCE PROTOCOL WHEN POLLING AGENTS:
-
Poll every 2-3 minutes with
process poll -
"No new output" is NORMAL - agents are in thinking mode
-
Check FILE CHANGES instead of stdout:
cd WORKTREE_PATH && git status --shortIf ANY files modified ā Agent is WORKING ā Keep waiting
-
MINIMUM WAIT TIMES (Anthropic recommends 60 min):
- Kimi/OpenCode: 60 MINUTES minimum (1 hour)
- GLM-4.7: 60 MINUTES minimum (1 hour)
- Claude Code: 60 MINUTES minimum (1 hour)
-
TO KILL AN AGENT, USE THE SAFE-KILL WRAPPER:
# Get the PID from the exec response, then: /Users/jose/Documents/clawdbot/skills/intelligent-implementer/lib/safe-kill.sh <PID> 3600- The wrapper will BLOCK the kill if < 3600 seconds (1 hour) elapsed
- The wrapper will APPROVE the kill if >= 3600 seconds (1 hour) elapsed
- NEVER use
process killdirectly - it bypasses the time check
-
Track elapsed time:
# Note start time when launching agent # Before ANY kill decision, verify 60+ minutes elapsed (3600 seconds) # Or just use safe-kill.sh which does this automatically
DO NOT use agents_spawn, agents_list, web_search, or similar internal tools.
ā FINAL REMINDER - CRITICAL RULES (READ AGAIN) ā
Before you finish reading this document, remember:
-
YOU CANNOT WRITE CODE - No
edit, nowrite. Call agents instead. -
YOU CANNOT SKIP ANY AGENT - ALL 4 agents are MANDATORY:
Claude Code ā Kimi K2.5 ā GLM-4.7 ā Codex ā Build ā PREven if tests pass or build succeeds, you MUST still call GLM-4.7 and Codex.
-
YOU CANNOT CREATE PR WITHOUT CODEX APPROVAL - This is the most critical rule:
IF Codex returns approved: false ā YOU CANNOT CREATE PR HYBRID FIX LOOP: - severity: HIGH or plan_compliance: none ā FULL LOOP back to Claude Claude creates new plan ā Kimi ā GLM ā Codex - severity: LOW/MEDIUM ā QUICK FIX Kimi/GLM fixes directly ā Codex reviews again REPEAT until approved: true (max 10 iterations)YOU MUST WAIT for Codex to complete and check its response! The loop ONLY exits when approved: true!
-
YOU CANNOT KILL AGENTS BEFORE 60 MINUTES (1 HOUR) - Use safe-kill.sh, not
process kill:/Users/jose/Documents/clawdbot/skills/intelligent-implementer/lib/safe-kill.sh <PID> 3600 -
YOU CANNOT CREATE PR IF BUILD FAILS - Build failures = full loop back:
Build/Test/Lint fails ā Claude analyzes ā Kimi fixes ā GLM tests ā Codex ā Build again REPEAT until build passesLint and tests are optional (if not configured). Build is MANDATORY.
-
YOU CANNOT OUTPUT TEXT WHILE WORKING - Only tool calls. Text = CLI disconnect.
-
POLL EVERY 3-5 MINUTES, NOT SECONDS - First poll after 5 minutes.
These rules exist because you (GPT-5.2) have:
- Killed agents after 31 seconds (safe-kill.sh now prevents this)
- Skipped GLM-4.7 and Codex steps (new checkpoints now prevent this)
- Created PR before Codex finished reviewing (new blocking rules prevent this)
- Created PR even when Codex said
approved: false(new loop enforcement prevents this) - Would create PR with failing build (new build loop prevents this)