Sakura Execution Pipeline & Orchestrator
Overview
The Sakura orchestrator is a multi-agent execution engine that coordinates autonomous AI agents to complete complex software engineering tasks. It implements a deterministic plan/apply pattern with safety gates, iterative self-correction, and GitHub-native delivery.
Sources: src/orchestrator/index.ts
Architecture Overview
1. Headless Tool Loop
The headless tool loop is the core autonomous execution engine. Unlike the interactive REPL, it runs without user input — the agent reads its own work and iterates until a completion signal is emitted.
Sources: src/orchestrator/headless-loop.ts
Key Behaviors
- Max iterations: Bounded loop prevents infinite agent drift
- History accumulation: Tool results are appended to conversation history so the LLM sees what it has already done
- Completion signal: The agent emits
<promise>TASK_COMPLETE</promise>when all acceptance criteria are met and build/tests pass - Context compaction: When history exceeds
MAX_HISTORY_CHARS(32,000), the loop auto-compacts via LLM summarization
Sources: src/repl/tool-loop.ts
// Auto-compact when history grows too large
async function autoCompactIfNeeded(
history: ChatMessage[],
provider: LlmProvider,
): Promise<ChatMessage[]> {
const totalChars = history.reduce((sum, m) => sum + m.content.length, 0);
if (totalChars < MAX_HISTORY_CHARS || history.length < 4) return history;
// ... summarize via LLM
}
2. The Ralph Loop (Iterative Self-Correction)
The "Ralph loop" (ralphLoop) is named for the pattern where an agent reads its own previous work before each iteration. The prompt stays constant; the agent's context grows with each tool call result.
Sources: src/orchestrator/ralph.ts
Engineer Prompt Structure
The engineer prompt is constructed with full context at each invocation:
Sources: src/orchestrator/pipeline.ts
function buildEngineerPrompt(
task: Task,
scope: string,
arch: string,
qaFeedback?: string,
memory?: string
): string {
return `You are a ${task.assignee} engineer. Complete the following task.
${memory ? `\n${memory}\n` : ""}
## Task: ${task.title}
${task.description}
## Acceptance Criteria
${task.acceptance_criteria.map((c) => `- ${c}`).join("\n")}
## Architecture (follow exactly)
${arch}
## Project Scope (for context)
${scope}
${qaFeedback ? `\n## QA Feedback (fix these issues)\n${qaFeedback}` : ""}
Rules:
- Read existing files before modifying them
- Run the build and tests after making changes
- If build/tests fail, fix the issues
- Follow the architecture document exactly
- Output <promise>TASK_COMPLETE</promise> when ALL acceptance criteria are met`;
}
Anti-Drift Mechanisms
The tool loop injects state anchors every STATE_INJECT_INTERVAL (5) iterations to prevent the agent from losing track of its goal:
Sources: src/repl/tool-loop.ts
// State injection every N iterations (anti-drift anchor)
if (iteration > 1 && iteration % STATE_INJECT_INTERVAL === 0) {
const stateBlock = buildStateAnchor(input, toolLog);
currentPrompt = `${stateBlock}\n\n${currentPrompt}`;
}
// Force low temperature for late iterations (anti-drift)
const effectiveTemp = iteration > 10 ? 0.2 : ctx.temperature;
3. Git Strategy
Sakura uses a structured branching model to isolate task work and enable clean integration.
Sources: src/orchestrator/github.ts
Branch Lifecycle
Key Functions
| Function | Description | Source |
|---|---|---|
setupIntegrationBranch | Creates integration/[slug] from base branch | github.ts |
createTaskBranch | Creates task/[slug] from integration branch | ralph.ts |
commitAndReturn | Stages all, commits with message, checks out integration | ralph.ts |
mergeTaskBranch | Merges task branch into integration, deletes task branch | ralph.ts |
pushBranch | Pushes integration branch to remote | github.ts |
createPullRequest | Creates PR via gh CLI | github.ts |
integrationBranch | Derives branch name from task list slug | github.ts |
4. GitHub Integration
GitHub integration is handled via the gh CLI, which must be installed and authenticated.
Sources: src/orchestrator/github.ts
Prerequisites Check
export async function checkGhCli(): Promise<boolean> {
// Verifies `gh` is installed and authenticated
}
Pull Request Creation
PRs are created with structured bodies that include:
- Task summary
- Acceptance criteria
- Architecture compliance notes
- QA sign-off status
5. Pre-flight Checks
Before any pipeline execution, Sakura runs a comprehensive pre-flight check to catch configuration issues early.
Sources: src/orchestrator/preflight.ts
Preflight Items
| Check | What It Validates |
|---|---|
| Git repo | git rev-parse --git-dir succeeds |
gh CLI | Installed and authenticated |
| API keys | OPENAI_API_KEY or ANTHROPIC_API_KEY set, or sakura login active |
| Dependencies | node_modules present, build tools available |
| File permissions | Working directory is writable |
| Branch state | No uncommitted changes that would conflict |
Sources: src/orchestrator/preflight.ts
6. QA Review Cycle
Each task goes through an engineer → QA outer loop. The QA agent reviews the code against acceptance criteria and architecture compliance.
Sources: src/orchestrator/pipeline.ts
QA Prompt Structure
function buildQaPrompt(task: Task, arch: string): string {
return `You are a QA reviewer. Review the code changes for this task.
## Task: ${task.title}
${task.description}
## Acceptance Criteria
${task.acceptance_criteria.map((c) => `- ${c}`).join("\n")}
## Architecture (check compliance)
${arch}
Review the current code for:
1. All acceptance criteria met
2. Architecture compliance
3. Error handling
4. Edge cases`;
}
Sources: src/orchestrator/pipeline.ts
7. MemPalace Memory Integration
Sakura includes a memory system (MemPalace) that persists agent knowledge across sessions and tasks.
Sources: src/memory/
Memory in the Engineer Prompt
When memory is available, it is injected at the top of the engineer prompt:
function buildEngineerPrompt(
task: Task,
scope: string,
arch: string,
qaFeedback?: string,
memory?: string // ← MemPalace content
): string {
return `You are a ${task.assignee} engineer. Complete the following task.
${memory ? `\n${memory}\n` : ""}
...`;
}
Sources: src/orchestrator/pipeline.ts, mempalace.yaml
8. Safety Guardrails
Sakura implements multiple layers of safety to prevent unintended mutations.
8.1 AWS Risk Classification
Every AWS command is classified before execution:
Sources: src/aws/guard.ts