<purpose>
Sequential CLI-delegate coordinator. Each chain step executes via `maestro delegate "prompt" --to <tool> --mode write`
with a template-driven prompt. After each step, gemini analysis evaluates output quality and generates
optimization hints for subsequent steps. All execution is background-async with hook callbacks.
Intent → Resolve Chain → Step 1 → Analysis → Step 2 → Analysis → … → Report
(chainMap) delegate gemini delegate gemini
callback callback callback callback
</purpose>
<required_reading>
@~/.maestro/workflows/maestro-coordinate.codex.md — authoritative detectTaskType, detectNextAction, chainMap (35+ intent patterns, 40+ chain types). Read before executing any step.
</required_reading>
<deferred_reading>
<context>
$ARGUMENTS — user intent text, or special flags.
Flags:
-y, --yes — Auto mode: skip all prompts, inject auto-confirm into delegates
-c, --continue — Resume previous session from last incomplete step
--dry-run — Show planned chain without executing
--chain <name> — Force specific chain (skips intent classification)
Session state: .workflow/.maestro-coordinate/{session-id}/state.json
</context>
<invariants>
1. **STOP after each delegate call**: Background execution via `run_in_background: true`, wait for hook callback.
2. **State machine**: Advance via `current_step`, no sync loops for async operations.
3. **Template-driven**: All steps use `coordinate-step.txt`, no per-command prompt assembly.
4. **Context propagation**: Parse PHASE / spec session ID / scratch_dir / issue_id from each step output, feed to next step.
5. **Gemini analysis after each step**: Evaluate output quality, generate hints for next step, chain via `--resume`.
6. **Auto-confirm injection**: `{{AUTO_DIRECTIVE}}` in template prevents blocking during background execution.
7. **Resumable**: `-c` reads `state.json`, jumps to first pending step.
8. **Delegate tool**: `maestro delegate --to codex` for all execution steps; `--to gemini` only for post-step analysis.</invariants>
<execution>
Step 1: Parse Arguments
javascript
1const args = $ARGUMENTS.trim();
2const AUTO_YES = /\b(-y|--yes)\b/.test(args);
3const RESUME = /\b(-c|--continue)\b/.test(args);
4const DRY_RUN = /\b--dry-run\b/.test(args);
5const forcedChain = args.match(/--chain\s+(\S+)/)?.[1] || null;
6const intent = args
7 .replace(/\b(-y|--yes|-c|--continue|--dry-run)\b/g, '')
8 .replace(/--chain\s+\S+/g, '')
9 .trim();
If RESUME: Find latest state.json in .workflow/.maestro-coordinate/, load → jump to Step 6.
Step 2–4: Classify Intent → Confirm
- Read
.workflow/state.json + .workflow/roadmap.md + current phase
- If
--chain given → use directly; else classify via detectTaskType + chainMap
- If clarity < 2 and not AUTO_YES → clarify via AskUserQuestion (max 2 rounds)
--dry-run: Display chain and exit
- User confirmation (skip if AUTO_YES): Execute / Execute from step N / Cancel
Step 5: Setup Session
javascript
1const sessionId = `coord-${new Date().toISOString().replace(/[-:T]/g, '').slice(0, 15)}`;
2const sessionDir = `.workflow/.maestro-coordinate/${sessionId}`;
3
4const state = {
5 session_id: sessionId, status: 'running',
6 created_at: new Date().toISOString(),
7 intent, task_type: taskType, chain_name: chainName,
8 auto_mode: AUTO_YES, phase: resolvedPhase,
9 current_step: 0, gemini_session_id: null, step_analyses: [],
10 steps: chain.map((s, i) => ({
11 index: i, cmd: s.cmd, args: s.args || '',
12 status: 'pending', exec_id: null, analysis: null
13 }))
14};
15Write(`${sessionDir}/state.json`, JSON.stringify(state, null, 2));
Step 6: Execute Step via maestro delegate
6a: Assemble args
javascript
1const AUTO_FLAG_MAP = {
2 'maestro-analyze': '-y', 'maestro-brainstorm': '-y', 'maestro-ui-design': '-y',
3 'maestro-plan': '--auto', 'maestro-spec-generate': '-y', 'quality-test': '--auto-fix',
4 'quality-retrospective': '--auto-yes',
5};
6
7function assembleArgs(step) {
8 let a = (step.args || '')
9 .replace(/\{phase\}/g, context.current_phase || '')
10 .replace(/\{description\}/g, context.user_intent || '')
11 .replace(/\{issue_id\}/g, context.issue_id || '')
12 .replace(/\{spec_session_id\}/g, context.spec_session_id || '')
13 .replace(/\{scratch_dir\}/g, context.scratch_dir || '');
14 if (state.auto_mode) {
15 const flag = AUTO_FLAG_MAP[step.cmd];
16 if (flag && !a.includes(flag)) a = a ? `${a} ${flag}` : flag;
17 }
18 return a.trim();
19}
6b: Build prompt from template + launch
Read ~/.maestro/templates/cli/prompts/coordinate-step.txt, fill placeholders.
If previous step has analysis hints, inject as {{ANALYSIS_HINTS}}.
javascript
1const prompt = template
2 .replace('{{COMMAND}}', `/${step.cmd}`)
3 .replace('{{ARGS}}', assembledArgs)
4 .replace('{{STEP_N}}', `${state.current_step + 1}/${state.steps.length}`)
5 .replace('{{AUTO_DIRECTIVE}}', state.auto_mode ? 'Auto-confirm all prompts. No interactive questions.' : '')
6 .replace('{{CHAIN_NAME}}', state.chain_name)
7 .replace('{{ANALYSIS_HINTS}}', analysisHints);
8
9Bash({
10 command: `maestro delegate ${escapeForShell(prompt)} --to codex --mode write`,
11 run_in_background: true, timeout: 600000
12});
13// ■ STOP — wait for hook callback
Step 7: Post-Step Callback
javascript
1// Context propagation from output
2const phaseMatch = output.match(/PHASE:\s*(\d+)/m);
3if (phaseMatch) context.current_phase = phaseMatch[1];
4const specMatch = output.match(/SPEC-[\w-]+/);
5if (specMatch) context.spec_session_id = specMatch[0];
6const scratchMatch = output.match(/scratch_dir:\s*(.+)/m);
7if (scratchMatch) context.scratch_dir = scratchMatch[1].trim();
8
9// Success/failure
10const failed = /^STATUS:\s*FAILURE/m.test(output);
11if (!failed) { step.status = 'completed'; }
12else if (state.auto_mode && !step.retried) { step.retried = true; /* re-execute Step 6 */ return; }
13else { step.status = 'skipped'; /* or AskUserQuestion: Retry / Skip / Abort */ }
14
15Write(`${sessionDir}/step-${stepIdx + 1}-output.txt`, output);
16// → Step 7b (gemini analysis) if completed + multi-step chain
17// → else advance current_step, loop to Step 6 or Step 8
Step 7b: Analyze Step Output (via gemini)
javascript
1let delegateCmd = `maestro delegate ${escapeForShell(analysisPrompt)} --to gemini --mode analysis --rule analysis-review-code-quality`;
2if (state.gemini_session_id) delegateCmd += ` --resume ${state.gemini_session_id}`;
3Bash({ command: delegateCmd, run_in_background: true, timeout: 300000 });
4// ■ STOP — wait for hook callback
Post-analyze: store quality_score + issues + next_step_hints in state.step_analyses[], chain gemini sessions via --resume.
Step 8: Completion Report
============================================================
MAESTRO-COORDINATE COMPLETE
============================================================
Session: {session_id}
Chain: {chain_name} ({done}/{total})
Steps:
[✓] 1. maestro-plan — completed (quality: 85/100)
[✓] 2. maestro-execute — completed (quality: 78/100)
Avg Quality: {avg_score}/100
Next: $maestro-coordinate --continue
============================================================
</execution>
<error_codes>
| Code | Severity | Description | Recovery |
|---|
| E001 | error | No intent and project not initialized | Suggest $maestro-init |
| E002 | error | Clarity too low after 2 rounds | Ask to rephrase |
| E003 | error | Step failed + abort | Suggest resume with -c |
| E004 | error | Resume session not found | Show available sessions |
| </error_codes> | | | |
<success_criteria>