Skip to content

mythicalhacker/Auto-Code-V2

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

85 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

autocode

A multi-agent AI coding pipeline orchestrator written in Go. It reads structured markdown task files and coordinates AI agents (Claude Code, OpenAI Codex) to plan, implement, verify, review, and merge code changes — all in parallel with dependency awareness, sprint gating, and retry logic.

How It Works

autocode automates the full cycle from task specification to merged code (simplified view — the full 14-state machine is documented in Task State Machine):

┌─────────┐   ┌──────────┐   ┌────────────┐   ┌──────────┐
│ PENDING │──▶│ PLANNING │──▶│ CRITIQUING │──▶│ APPROVED │
└─────────┘   └──────────┘   └────────────┘   └──────────┘
                   ▲                                │
                   │                                ▼
              ┌────────┐                     ┌──────────────┐
              │ FAILED │                     │   RUNNING    │
              └────────┘                     └──────────────┘
               ▲     ▲                              │
               │     │      ┌───────────┐           │
               │     └──────│ VERIFYING │◀──────────┘
               │            └───────────┘
               │                  │
               │                  ▼
               │            ┌───────────┐      ┌────────┐
               └────────────│ REVIEWING │─────▶│ MERGED │
                            └───────────┘      └────────┘

End-to-End Flow

  1. Load config — defaults ← JSON config file ← CLI flag overrides
  2. Parse task file — sprints, task prompts, verification commands, dependencies
  3. Initialize or resume state — persisted in .pipeline/state.json
  4. Plan each task using AI agents, then critique and refine until the score threshold passes
  5. Dispatch approved tasks — create an isolated git worktree and run the AI coding agent
  6. Verify — run Run: verification commands extracted from the task prompt
  7. Review — optionally run an AI code review
  8. Merge — merge the task branch back to main and mark the task done in the task file
  9. Repeat until all tasks reach a terminal state

The event loop runs a periodic reconciliation tick (default 30s) that advances every task through this pipeline, respecting dependencies and sprint boundaries.

Installation

Prerequisites

  • Go 1.26+
  • git in PATH
  • Claude Code CLI (claude) — install instructions
  • OpenAI Codex CLI (optional) — requires node + codex.js

Build

make build    # produces autocode.exe (Windows) or autocode (Unix)

Or directly:

go build -ldflags "-X main.version=$(git describe --tags --always --dirty 2>/dev/null || echo dev)" \
  -o autocode.exe ./cmd/autocode/

Test

make test     # runs all tests with race detection (5-minute timeout)
make vet      # runs go vet

Quick Start

  1. Create a task file (see Task File Format below).
  2. Run:
autocode --task-file tasks.md --project-root /path/to/project

Windows PowerShell:

.\autocode.exe --task-file .\tasks.md --project-root .

Useful modes:

Flag Description
--dry-run Parse and validate the task file, print active tasks, then exit
--resume Load previous .pipeline/state.json and recover zombie tasks
--clean Delete state file and worktrees, then exit
--verbose Enable debug-level logging

Task File Format

Tasks are defined in a structured markdown file with sprint headers, task headers, and fenced prompt blocks.

# Project Tasks

## Dependencies
1.1:
1.2: 1.1
2.1: 1.1, 1.2

## Sprint 1

### CC-1: Task 1.1 -- Setup project scaffold

```text
Create the project scaffold with module init, directory structure, and CI config.

Run: go test ./...
Run: go vet ./...
```

### Codex-2: Task 1.2 -- Implement feature X

```text
Implement feature X with full test coverage.

Run: go test ./... -run TestFeatureX
```

## Sprint 2

### CC-3: Task 2.1 -- Integration polish

```text
Wire up feature X end to end and add integration tests.

Run: go test ./...
```

Parsing Rules

Element Syntax Example
Sprint header ## Sprint <N> ## Sprint 1
Task header ### <Type>-<Slot>: Task <ID> -- <Title> ### CC-0: Task 1.1 -- Setup
Done task Prefix with checkmark ### ✅ CC-0: Task 1.1 -- Setup
Task prompt First fenced code block after the task header ```text ... ```
Verification Lines starting with Run: inside the prompt Run: go test ./...
Dependencies ## Dependencies section 1.2: 1.1
Worker types CC (Claude Code) or Codex (OpenAI Codex) ### CC-1: ... / ### Codex-2: ...

CLI Flags

Required

Flag Description
--task-file Path to the markdown task file
--project-root Root directory of the target project

Run Mode

Flag Default Description
--config Path to a JSON config file
--resume false Resume from previous pipeline state
--clean false Delete state file and worktrees, then exit
--dry-run false Parse and validate without executing
--verbose false Debug-level logging
--version Print version and exit

Worker Pool

Flag Default Description
--cc-planners 2 Claude Code planner workers
--codex-planners 2 Codex planner workers
--cc-executors 2 Claude Code executor workers
--codex-executors 2 Codex executor workers

Models

Flag Default Description
--cc-model sonnet Model for Claude Code workers
--codex-model o3 Model for Codex workers

Pipeline Behavior

Flag Default Description
--sprint-gating true Only process tasks in the lowest active sprint
--code-review true Enable AI code review after execution
--plan-threshold 4.0 Minimum score (1–5) to approve a plan
--consensus-mode delphi Planning consensus mode (delphi or single)
--max-plan-rounds 3 Maximum planning refinement rounds per task
--max-exec-retries 3 Maximum execution retries per task
--max-stuck-retries 2 Maximum stuck-task retries
--plan-timeout 5m Timeout for the planning phase
--exec-timeout 15m Timeout for the execution phase

Configuration

Config is loaded in layers: Defaults ← JSON file ← CLI flags.

Durations accept either Go duration strings ("5m", "30s") or integer milliseconds (300000).

Example config.json

{
  "taskFile": "tasks.md",
  "projectRoot": ".",
  "ccPlanners": 2,
  "codexPlanners": 2,
  "ccExecutors": 2,
  "codexExecutors": 2,
  "ccModel": "sonnet",
  "codexModel": "o3",
  "planThreshold": 4.0,
  "consensusMode": "delphi",
  "safetyGateMinimum": 3.0,
  "maxPlanRounds": 3,
  "maxExecRetries": 3,
  "maxStuckRetries": 2,
  "planTimeout": "5m",
  "critiqueTimeout": "3m",
  "execTimeout": "15m",
  "reconcileInterval": "30s",
  "sprintGating": true,
  "codeReview": true
}

Context Documents

Additional markdown context is loaded automatically into planning prompts from:

  • Global: ~/.autocode/context/*.md (applies to all projects)
  • Per-project: <projectRoot>/.autocode/context/*.md (overrides global on name collision)

Architecture

cmd/autocode/          CLI entry point, event loop, signal handling
internal/
  agent/               AI agent invocation (Claude Code, Codex) with retry and fallback
  config/              Layered configuration (defaults ← JSON ← CLI flags)
  execution/           Process management, verification, code review, fix prompts
  git/                 Git worktree creation, merging, and cleanup
  logging/             Structured logging with real-time file output
  planning/            Plan generation, critique, refinement, Delphi consensus
  platform/            Cross-platform process management (Windows/Unix)
  prompt/              Template loading and codebase context generation
  state/               State machine (14 states), task manager, worker pool
  steps/               Pipeline orchestration (planning, dispatch, retry, checkpoint)
  taskfile/            Markdown task file parser with dependency resolution
  testutil/            Test helpers
templates/             Embedded prompt templates for all AI interactions

Planning Pipeline

Plans go through a critique-refine loop scored on 6 dimensions:

Dimension Description
Completeness Does the plan cover all requirements?
Specificity Are the steps concrete and actionable?
Safety Does the plan avoid breaking existing functionality?
Verification Are test/verification steps adequate?
Feasibility Can the plan be executed by an AI agent?
Exec Prompt Quality Is the execution prompt clear and complete?

Scores are combined via geometric mean. A plan is approved when its score meets the threshold (default 4.0/5.0). A safety gate immediately rejects plans with a safety score below 3.0 regardless of overall score.

Consensus modes:

  • single — one critic evaluates the plan
  • delphi — multiple critics evaluate independently, then reconcile disagreements through a deliberation phase

Task State Machine

Full state transition diagram:

Success path:
  PENDING → PLANNING → CRITIQUING → APPROVED → QUEUED → DISPATCHED → RUNNING → VERIFYING → [REVIEWING] → MERGED

Failure/retry path:
  RUNNING/VERIFYING/REVIEWING → FAILED → REPLANNING → PLANNING
  FAILED → STUCK → PENDING  (if stuck retries remain)

Terminal states:
  MERGED, SKIPPED, STUCK (when retries exhausted)

Failure Recovery

  • Failed executions generate a fix prompt incorporating error output, review feedback, and file diffs, then re-enter the planning phase
  • Stuck tasks retry with the opposite worker type (Claude Code ↔ Codex) as a fallback
  • Retry budgets prevent infinite loops (--max-exec-retries, --max-stuck-retries)

Concurrency

  • Each task executes in its own git worktree for full isolation
  • File overlap detection defers dispatch when concurrent tasks would modify the same files
  • Worker pools enforce concurrency limits for planner and executor workers
  • All state mutations are mutex-protected with atomic file persistence

Prompt Templates

Embedded templates in templates/ drive all AI interactions:

Template Purpose
planner.md.tmpl Initial plan generation
refinement.md.tmpl Plan refinement after critique
critic-batch1.md.tmpl Scoring completeness, specificity, safety
critic-batch2.md.tmpl Scoring verification, feasibility, exec prompt quality
critic-followup.md.tmpl Feedback for failed plans
deliberation.md.tmpl Delphi consensus deliberation
review.md.tmpl Code review
fix-prompt.md.tmpl Retry fix prompt after execution failure

Runtime Artifacts

With default pipelineDir at the project root:

.pipeline/state.json                    Pipeline state (JSON, atomic writes)
.pipeline/worktrees/wt-<task-id>/       Per-task git worktrees
logs/task-<task-id>/execution-live.log  Real-time execution output
logs/task-<task-id>/execution.log       Final execution log
logs/review-prompt.md                   Last review prompt sent
logs/review-output.md                   Last review output received

Worktree branch names follow the pattern task-<id> (dots replaced with dashes). Merge target is the main branch.

Dependencies

Package Purpose
koanf Layered configuration loading
renameio Atomic file writes

Operational Notes

  • --config does not error if the file path does not exist; defaults and CLI values are still used
  • Dependency IDs are not validated at startup; invalid references can leave tasks permanently blocked
  • Verification commands are split and executed directly (not through a shell), so complex pipes/redirection may not work as expected
  • --resume resets transient/zombie task states and clears stale worker assignments

About

Multi-agent AI coding pipeline orchestrator in Go — plans, critiques, implements, verifies, reviews, and merges code via coordinated Claude Code and Codex workers

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors