// tools/suggest-tooling/orchestration-generator.ts — SPEC-022 TD: 3-layer orchestration script generator
// Generates a parallel automation bash script: validate → worktrees → parallel claude -p → wait → report → cleanup
const DEFAULT_MAIN_BRANCH = 'main';
const DEFAULT_BASE_BRANCH = 'develop';
const WORKTREE_BASE = '.claude/worktrees';
/**
 * Generates a parallel orchestration bash script that:
 * 1. Validates working tree is clean
 * 2. Creates one git worktree per spec
 * 3. Launches `env -u CLAUDECODE claude -p` per spec in parallel (macOS bash 3.2 compatible)
 * 4. Waits for all processes to complete
 * 5. Reports pass/fail per spec
 * 6. Provides cleanup instructions for successful worktrees
 */
export function generateOrchestrationScript(input) {
    const { specIds, projectPath, mainBranch, baseBranch } = input;
    const main = mainBranch ?? DEFAULT_MAIN_BRANCH;
    const base = baseBranch ?? DEFAULT_BASE_BRANCH;
    const worktreeSetupLines = buildWorktreeSetup(specIds, base);
    const launchLines = buildParallelLaunch(specIds, projectPath);
    const waitLines = buildWaitAndReport(specIds);
    const cleanupLines = buildCleanupInstructions(specIds);
    return [
        '#!/usr/bin/env bash',
        '# 3-Layer Parallel Automation Script',
        '# Generated by Planu — SPEC-022 orchestration-generator',
        `# Main branch: ${main} | Base branch: ${base}`,
        '# Layer 1: Skills (per-agent Claude Code workflows)',
        '# Layer 2: Sub-agents (scoped delegated tasks)',
        '# Layer 3: Orchestration (this script — parallel worktrees + claude -p)',
        '',
        'set -euo pipefail',
        '',
        `PROJECT_PATH="${projectPath}"`,
        `WORKTREE_BASE="${WORKTREE_BASE}"`,
        `BASE_BRANCH="${base}"`,
        '',
        '# ── Step 1: Validate working tree is clean ──────────────────────────────',
        'echo "[orchestrate] Checking working tree..."',
        'if ! git -C "$PROJECT_PATH" diff --quiet || ! git -C "$PROJECT_PATH" diff --cached --quiet; then',
        '  echo "[ERROR] Working tree has uncommitted changes. Commit or stash before running." >&2',
        '  exit 1',
        'fi',
        'echo "[orchestrate] Working tree is clean."',
        '',
        '# ── Step 2: Create worktrees ─────────────────────────────────────────────',
        ...worktreeSetupLines,
        '',
        '# ── Step 3: Launch parallel claude -p instances ──────────────────────────',
        'declare -A PIDS',
        ...launchLines,
        '',
        '# ── Step 4: Wait and report ──────────────────────────────────────────────',
        ...waitLines,
        '',
        '# ── Step 5: Cleanup instructions ─────────────────────────────────────────',
        ...cleanupLines,
    ].join('\n');
}
function buildWorktreeSetup(specIds, baseBranch) {
    const lines = [];
    for (const specId of specIds) {
        const slug = specId.toLowerCase().replace(/[^a-z0-9-]/g, '-');
        const worktreePath = `$WORKTREE_BASE/${slug}`;
        const branchName = `feat/${specId}`;
        lines.push(`echo "[orchestrate] Creating worktree for ${specId}..."`, `git -C "$PROJECT_PATH" worktree add "${worktreePath}" -b "${branchName}" "${baseBranch}" 2>/dev/null || \\`, `  git -C "$PROJECT_PATH" worktree add "${worktreePath}" "${branchName}"`);
    }
    return lines;
}
function buildParallelLaunch(specIds, projectPath) {
    const lines = [];
    for (const specId of specIds) {
        const slug = specId.toLowerCase().replace(/[^a-z0-9-]/g, '-');
        const worktreePath = `${projectPath}/${WORKTREE_BASE}/${slug}`;
        const logFile = `/tmp/planu-${slug}.log`;
        const prompt = `Implement ${specId} following its spec.md (check planu/specs/ or docs/sdd/specs/ for the spec location). Follow all acceptance criteria. Run pnpm typecheck && pnpm lint && pnpm test after implementing.`;
        lines.push(`echo "[orchestrate] Launching agent for ${specId}..."`, `env -u CLAUDECODE claude -p "${prompt}" \\`, `  --cwd "${worktreePath}" \\`, `  > "${logFile}" 2>&1 &`, `PIDS[${specId}]=$!`);
    }
    return lines;
}
function buildWaitAndReport(specIds) {
    const lines = ['FAILED=0', ''];
    for (const specId of specIds) {
        const slug = specId.toLowerCase().replace(/[^a-z0-9-]/g, '-');
        const logFile = `/tmp/planu-${slug}.log`;
        lines.push(`echo "[orchestrate] Waiting for ${specId} (PID \${PIDS[${specId}]})..."`, `if wait "\${PIDS[${specId}]}"; then`, `  echo "[PASS] ${specId} completed successfully"`, `else`, `  echo "[FAIL] ${specId} failed — see ${logFile}" >&2`, `  FAILED=$((FAILED + 1))`, `fi`);
    }
    lines.push('', 'echo ""', 'echo "[orchestrate] Results: ' + String(specIds.length) + ' specs, $FAILED failed"', 'if [ "$FAILED" -gt 0 ]; then', '  echo "[ERROR] Some agents failed. Review logs in /tmp/planu-*.log" >&2', '  exit 1', 'fi');
    return lines;
}
function buildCleanupInstructions(specIds) {
    const lines = [
        'echo ""',
        'echo "[orchestrate] All agents completed successfully."',
        'echo "[orchestrate] Review each branch and merge when ready:"',
        'echo ""',
    ];
    for (const specId of specIds) {
        const slug = specId.toLowerCase().replace(/[^a-z0-9-]/g, '-');
        const worktreePath = `$WORKTREE_BASE/${slug}`;
        lines.push(`echo "  ${specId}: git -C \\"$PROJECT_PATH\\" worktree remove \\"${worktreePath}\\""`);
    }
    lines.push('echo ""', 'echo "[orchestrate] To remove all worktrees after merging:"', `echo "  git -C \\"$PROJECT_PATH\\" worktree prune"`);
    return lines;
}
//# sourceMappingURL=orchestration-generator.js.map