// tools/generate-automation-guide.ts — Generate Claude Code automation guide (SPEC-257)
import { mkdir, writeFile } from 'fs/promises';
import { dirname } from 'path';
import { z } from 'zod';
import { buildClaudeCommand, generateStreamJsonPipeline, getJobPermissionMode, } from '../engine/ci-generator/output-formats.js';
export const GenerateAutomationGuideInputSchema = z.object({
    projectPath: z.string().describe('Absolute path to the project root'),
    saveToDisk: z.boolean().optional().describe('Save guide to docs/automation-guide.md'),
    includeExamples: z
        .boolean()
        .optional()
        .describe('Include code examples for each section (default: true)'),
});
function buildGuide(includeExamples) {
    const sections = [];
    sections.push('# Claude Code Automation Guide');
    sections.push('');
    sections.push('> This guide covers how to automate Claude Code in CI pipelines, scheduled tasks, and non-interactive workflows.');
    sections.push('');
    // Section 1: Non-interactive mode
    sections.push('## 1. Non-Interactive Mode (`claude -p`)');
    sections.push('');
    sections.push('The `-p` flag runs Claude non-interactively — a single prompt, then Claude exits. Ideal for one-off queries and CI pipelines.');
    sections.push('');
    if (includeExamples) {
        sections.push('```bash');
        sections.push(buildClaudeCommand({ prompt: 'Summarize all failing tests', nonInteractive: true }));
        sections.push(buildClaudeCommand({
            prompt: 'Check for security issues',
            nonInteractive: true,
            permissionMode: 'plan',
        }));
        sections.push('```');
        sections.push('');
    }
    // Section 2: Output formats
    sections.push('## 2. Output Formats');
    sections.push('');
    sections.push('Three output formats are available. Choose based on your integration needs:');
    sections.push('');
    sections.push('| Format | Description | Best for |');
    sections.push('|--------|-------------|----------|');
    sections.push('| `text` | Plain text response (default) | Human-readable output, logs |');
    sections.push('| `json` | Full conversation as JSON | Structured parsing, audit trails |');
    sections.push('| `stream-json` | Real-time JSON events streamed | Live dashboards, piping to `jq` |');
    sections.push('');
    if (includeExamples) {
        sections.push('```bash');
        sections.push('# text (default)');
        sections.push(buildClaudeCommand({ prompt: 'List all TODOs', nonInteractive: true }));
        sections.push('');
        sections.push('# json — full conversation object');
        sections.push(buildClaudeCommand({
            prompt: 'Audit dependencies',
            nonInteractive: true,
            outputFormat: 'json',
        }));
        sections.push('');
        sections.push('# stream-json — pipe to jq for filtering');
        sections.push(generateStreamJsonPipeline('Run linter and report issues', '.content'));
        sections.push('```');
        sections.push('');
    }
    // Section 3: Permission modes
    sections.push('## 3. Permission Modes');
    sections.push('');
    sections.push('Permission modes control what actions Claude can take without asking for confirmation:');
    sections.push('');
    sections.push('| Mode | Description | When to use |');
    sections.push('|------|-------------|-------------|');
    sections.push('| `plan` | Read-only analysis — no file writes | Safe exploration, spec validation |');
    sections.push('| `acceptEdits` | Can edit files, asks before running commands | Iterating on code while reviewing |');
    sections.push('| `auto` | Long tasks, reduces prompt fatigue | Requires Team plan + Sonnet/Opus 4.6 |');
    sections.push('| `dontAsk` | Pre-approved tools only, no confirmations | Locked CI environments |');
    sections.push('| `bypassPermissions` | No safety checks — full autonomy | Containers/VMs only |');
    sections.push('');
    sections.push('**Recommended modes per CI job type:**');
    sections.push('');
    sections.push(`- validate → \`${getJobPermissionMode('validate')}\` — safe, read-only spec checks`);
    sections.push(`- lint → \`${getJobPermissionMode('lint')}\` — pre-approved linting tools only`);
    sections.push(`- migrate → \`${getJobPermissionMode('migrate')}\` — automated migrations with Team plan`);
    sections.push(`- container → \`${getJobPermissionMode('container')}\` — full autonomy inside isolated VMs`);
    sections.push(`- review → \`${getJobPermissionMode('review')}\` — edits files while you review commands`);
    sections.push('');
    if (includeExamples) {
        sections.push('```bash');
        sections.push(buildClaudeCommand({
            prompt: 'validate all specs',
            nonInteractive: true,
            permissionMode: 'plan',
        }));
        sections.push('```');
        sections.push('');
    }
    // Section 4: Scheduled tasks
    sections.push('## 4. Scheduled Tasks');
    sections.push('');
    sections.push('Multiple scheduling options exist — choose based on your access requirements:');
    sections.push('');
    sections.push('| Method | Runs when offline | Access to | Best for |');
    sections.push('|--------|-------------------|-----------|----------|');
    sections.push('| **Cloud** (`claude.ai/code`) | Yes | Remote repos only | Background jobs independent of your machine |');
    sections.push('| **Desktop** | No (requires local machine) | Local files, uncommitted changes | Dev-time checks on local work |');
    sections.push('| **GitHub Actions** | Yes | Repo at event time | Repo-event-driven automation |');
    sections.push('| **`/loop`** | No (session only) | Current context | Quick session-scoped repetition |');
    sections.push('');
    sections.push('> **Note**: `/loop` is cancelled when the session exits — not suitable for production automation.');
    sections.push('');
    // Section 5: Fan-out pattern
    sections.push('## 5. Fan-Out Pattern');
    sections.push('');
    sections.push('Process multiple files in parallel by looping with `claude -p` and `--allowedTools`:');
    sections.push('');
    if (includeExamples) {
        sections.push('```bash');
        sections.push('# Fan-out: lint every changed file independently');
        sections.push('for file in $(git diff --name-only HEAD~1); do');
        sections.push(`  ${buildClaudeCommand({
            prompt: 'Review this file for issues: $file',
            nonInteractive: true,
            permissionMode: 'plan',
            allowedTools: ['Read', 'Grep'],
        })} &`);
        sections.push('done');
        sections.push('wait  # wait for all parallel jobs');
        sections.push('```');
        sections.push('');
    }
    // Section 6: Session resume
    sections.push('## 6. Session Resume');
    sections.push('');
    sections.push('Resume previous Claude sessions to maintain context across invocations:');
    sections.push('');
    sections.push('| Flag | Behavior |');
    sections.push('|------|----------|');
    sections.push('| `--continue` | Resume the most recent session |');
    sections.push('| `--resume <name>` | Resume a named session by identifier |');
    sections.push('| `--from-pr <N>` | Start a session pre-loaded with PR #N context |');
    sections.push('');
    if (includeExamples) {
        sections.push('```bash');
        sections.push('# Continue the last session and run non-interactively');
        sections.push('claude --continue -p "Summarize what was accomplished in the last session"');
        sections.push('');
        sections.push('# Resume a named session');
        sections.push('claude --resume my-migration-session -p "Continue the migration"');
        sections.push('');
        sections.push('# Start from a PR context');
        sections.push('claude --from-pr 42 -p "Review the changes in this PR"');
        sections.push('```');
        sections.push('');
    }
    // Section 7: dontAsk for CI
    sections.push('## 7. `dontAsk` for CI Environments');
    sections.push('');
    sections.push('Use `dontAsk` permission mode in locked CI environments where only pre-approved tools should run. Combined with `--allowedTools`, this gives deterministic, safe automation:');
    sections.push('');
    if (includeExamples) {
        sections.push('```yaml');
        sections.push('# .github/workflows/planu-validate.yml');
        sections.push('name: Planu Spec Validation');
        sections.push('');
        sections.push('on:');
        sections.push('  pull_request:');
        sections.push('    branches: [main, develop]');
        sections.push('');
        sections.push('jobs:');
        sections.push('  validate:');
        sections.push('    name: Validate Specs');
        sections.push('    runs-on: ubuntu-latest');
        sections.push('    steps:');
        sections.push('      - uses: actions/checkout@v4');
        sections.push('');
        sections.push('      - name: Install Claude Code');
        sections.push('        run: npm install -g @anthropic-ai/claude-code');
        sections.push('');
        sections.push('      - name: Validate all specs');
        sections.push(`        run: ${buildClaudeCommand({
            prompt: 'validate all specs and report any issues',
            nonInteractive: true,
            permissionMode: 'dontAsk',
            allowedTools: ['Read', 'Glob', 'Grep'],
        })}`);
        sections.push('        env:');
        sections.push('          ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}');
        sections.push('```');
        sections.push('');
    }
    // Section 8: Agent Teams Orchestration
    sections.push('## 8. Agent Teams Orchestration');
    sections.push('');
    sections.push('When implementing 3+ independent specs in parallel, use Agent Teams to maximize throughput:');
    sections.push('');
    sections.push('**When to use teams:**');
    sections.push('- 3+ specs are approved and ready to implement simultaneously');
    sections.push('- Estimated total effort > 8h');
    sections.push('- Specs touch different modules (clear file ownership boundaries)');
    sections.push('- Monorepo or multi-layer architecture');
    sections.push('');
    if (includeExamples) {
        sections.push('```bash');
        sections.push('# Step 1: Plan team distribution — assigns exclusive file ownership');
        sections.push(buildClaudeCommand({
            prompt: 'plan_team_distribution with specIds ["SPEC-010", "SPEC-011", "SPEC-012"]',
            nonInteractive: true,
            permissionMode: 'plan',
        }));
        sections.push('');
        sections.push('# Step 2: Generate isolated prompt for each teammate');
        sections.push(buildClaudeCommand({
            prompt: 'generate_teammate_prompt for teammate assignment from plan_team_distribution',
            nonInteractive: true,
            permissionMode: 'plan',
        }));
        sections.push('');
        sections.push('# Step 3: Spawn N agents in parallel (one per teammate)');
        sections.push('claude -p "<teammate-1-prompt>" &');
        sections.push('claude -p "<teammate-2-prompt>" &');
        sections.push('claude -p "<teammate-3-prompt>" &');
        sections.push('wait  # wait for all agents to complete');
        sections.push('');
        sections.push('# Step 4: Validate merged results');
        sections.push(buildClaudeCommand({
            prompt: 'validate_team_results for projectPath /path/to/project',
            nonInteractive: true,
            permissionMode: 'plan',
        }));
        sections.push('```');
        sections.push('');
    }
    sections.push('> See `.claude/rules/agent-teams.md` for full rules on file ownership and team patterns.');
    sections.push('');
    return sections.join('\n');
}
export async function handleGenerateAutomationGuide(args) {
    const includeExamples = args.includeExamples ?? true;
    const guide = buildGuide(includeExamples);
    if (args.saveToDisk === true) {
        const outputPath = `${args.projectPath}/docs/automation-guide.md`;
        await mkdir(dirname(outputPath), { recursive: true });
        await writeFile(outputPath, guide, 'utf-8');
        return {
            content: [
                {
                    type: 'text',
                    text: [
                        '## Automation Guide Generated',
                        '',
                        `Saved to: \`${outputPath}\``,
                        '',
                        guide,
                    ].join('\n'),
                },
            ],
        };
    }
    return {
        content: [
            {
                type: 'text',
                text: guide,
            },
        ],
    };
}
//# sourceMappingURL=generate-automation-guide.js.map