// engine/onboarding-engine.ts — SPEC-360: Interactive Onboarding & Guided Tours
import * as fs from 'node:fs/promises';
import * as path from 'node:path';
// ---------------------------------------------------------------------------
// Recommendations
// ---------------------------------------------------------------------------
export function buildRecommendations(role, projectType, teamSize) {
    const recs = [];
    // Role-based
    if (role === 'solo-dev') {
        recs.push({
            category: 'Workflow',
            text: 'As a solo developer, use `quick_start` with the `solo-dev` template to get started fast.',
            toolSuggestion: 'quick_start',
        });
    }
    else if (role === 'team-lead') {
        recs.push({
            category: 'Collaboration',
            text: 'Set up team roles with `configure_roles` and use `plan_team_distribution` to assign specs.',
            toolSuggestion: 'configure_roles',
        });
        recs.push({
            category: 'Visibility',
            text: 'Use `workspace_overview` to monitor all team projects from a single view.',
            toolSuggestion: 'workspace_overview',
        });
    }
    else if (role === 'pm') {
        recs.push({
            category: 'Planning',
            text: 'Use `create_spec` to capture requirements and `check_readiness` before starting implementation.',
            toolSuggestion: 'create_spec',
        });
        recs.push({
            category: 'Reporting',
            text: 'Use `workspace_report` to generate progress summaries for stakeholders.',
            toolSuggestion: 'workspace_report',
        });
    }
    else {
        // architect
        recs.push({
            category: 'Architecture',
            text: 'Use `generate_diagram` to document architecture and `analyze_spec_dependencies` for dependency graphs.',
            toolSuggestion: 'generate_diagram',
        });
    }
    // Project type based
    if (projectType === 'saas') {
        recs.push({
            category: 'SaaS Specifics',
            text: 'Explore the Spec Cookbook for SaaS patterns: billing, onboarding, team management.',
            toolSuggestion: 'cookbook_list',
        });
    }
    else if (projectType === 'api') {
        recs.push({
            category: 'API Quality',
            text: 'Use `validate_api_contract` to keep your OpenAPI spec aligned with implementation.',
            toolSuggestion: 'validate_api_contract',
        });
    }
    else if (projectType === 'mobile') {
        recs.push({
            category: 'Mobile CI',
            text: 'Use `generate_automation_guide` with the mobile template to set up iOS/Android CI pipelines.',
            toolSuggestion: 'generate_automation_guide',
        });
    }
    // Team size based
    if (teamSize === '1') {
        recs.push({
            category: 'Efficiency',
            text: 'Enable compact mode with `set_work_mode` to minimize token usage while working solo.',
            toolSuggestion: 'set_work_mode',
        });
    }
    else if (teamSize === '6-20' || teamSize === '20+') {
        recs.push({
            category: 'Scale',
            text: 'Configure approval policies with `configure_approval_policy` to enforce review workflows.',
            toolSuggestion: 'configure_approval_policy',
        });
        recs.push({
            category: 'Integrations',
            text: 'Connect your issue tracker (Jira/Linear) to keep specs and tickets in sync.',
            toolSuggestion: 'configure_jira',
        });
    }
    return recs;
}
export function formatRecommendationsMarkdown(config, recommendations) {
    const lines = [
        `# Welcome to Planu!`,
        ``,
        `**Role:** ${config.role} | **Project type:** ${config.projectType} | **Team size:** ${config.teamSize}`,
        ``,
        `## Personalized Recommendations`,
        ``,
    ];
    const byCategory = new Map();
    for (const rec of recommendations) {
        const existing = byCategory.get(rec.category) ?? [];
        existing.push(rec);
        byCategory.set(rec.category, existing);
    }
    for (const [category, recs] of byCategory) {
        lines.push(`### ${category}`);
        for (const rec of recs) {
            lines.push(`- ${rec.text}`);
        }
        lines.push('');
    }
    lines.push(`## Next Steps`, ``);
    lines.push(`1. Run \`onboarding_checklist\` to see what's already set up`);
    lines.push(`2. Run \`guided_tour\` with area \`spec-lifecycle\` to learn the basics`);
    lines.push(`3. Run \`quick_start\` to scaffold your first spec`);
    return lines.join('\n');
}
// ---------------------------------------------------------------------------
// Guided Tours
// ---------------------------------------------------------------------------
const TOURS = {
    'spec-lifecycle': {
        area: 'spec-lifecycle',
        title: 'Spec Lifecycle: From Idea to Done',
        steps: [
            {
                stepNumber: 1,
                title: 'Create a Spec',
                description: 'Every feature starts with a spec. Use `create_spec` to define the feature title, description, and acceptance criteria.',
                toolHint: 'create_spec',
                example: 'create_spec with title="User login" and projectPath="/path/to/project"',
            },
            {
                stepNumber: 2,
                title: 'Challenge & Refine',
                description: 'Use `challenge_spec` to stress-test your spec and find gaps before implementation starts.',
                toolHint: 'challenge_spec',
                example: 'challenge_spec with specId="SPEC-001" and projectPath="..."',
            },
            {
                stepNumber: 3,
                title: 'Check Readiness',
                description: '`check_readiness` verifies the spec has enough detail for implementation. Fix any issues it flags.',
                toolHint: 'check_readiness',
            },
            {
                stepNumber: 4,
                title: 'Approve & Implement',
                description: 'Move the spec to `approved` status. Implement the feature, then move to `done`.',
                toolHint: 'update_status',
            },
            {
                stepNumber: 5,
                title: 'Validate',
                description: 'Run `validate` to confirm the implementation matches the spec criteria.',
                toolHint: 'validate',
            },
        ],
    },
    'team-collaboration': {
        area: 'team-collaboration',
        title: 'Team Collaboration Workflows',
        steps: [
            {
                stepNumber: 1,
                title: 'Configure Roles',
                description: 'Set up roles (owner, reviewer, developer) with `configure_roles`.',
                toolHint: 'configure_roles',
            },
            {
                stepNumber: 2,
                title: 'Assign Specs',
                description: 'Use `assign_role` to assign specs to team members.',
                toolHint: 'assign_role',
            },
            {
                stepNumber: 3,
                title: 'Comments & Reviews',
                description: 'Use `add_comment` and `request_changes` to collaborate on spec details.',
                toolHint: 'add_comment',
            },
            {
                stepNumber: 4,
                title: 'Approval Policy',
                description: 'Configure who can approve specs with `configure_approval_policy`.',
                toolHint: 'configure_approval_policy',
            },
        ],
    },
    integrations: {
        area: 'integrations',
        title: 'Connecting Your Tools',
        steps: [
            {
                stepNumber: 1,
                title: 'Issue Trackers',
                description: 'Sync specs with Jira, Linear, or Asana using the respective configure tools.',
                toolHint: 'configure_jira',
            },
            {
                stepNumber: 2,
                title: 'CI/CD',
                description: 'Generate CI workflows with `generate_planu_ci` for GitHub Actions.',
                toolHint: 'generate_planu_ci',
            },
            {
                stepNumber: 3,
                title: 'Notifications',
                description: 'Configure Slack notifications for spec status changes with `configure_slack`.',
                toolHint: 'configure_slack',
            },
            {
                stepNumber: 4,
                title: 'Webhooks',
                description: 'Set up outbound webhooks to trigger custom workflows on spec events.',
                toolHint: 'configure_webhook',
            },
        ],
    },
    'ai-tools': {
        area: 'ai-tools',
        title: 'AI-Powered Features',
        steps: [
            {
                stepNumber: 1,
                title: 'Suggest Criteria',
                description: 'Use `suggest_criteria` to auto-generate acceptance criteria from a description.',
                toolHint: 'suggest_criteria',
            },
            {
                stepNumber: 2,
                title: 'Clarify Requirements',
                description: '`clarify_requirements` runs an interview-style session to uncover hidden requirements.',
                toolHint: 'clarify_requirements',
            },
            {
                stepNumber: 3,
                title: 'Red Team',
                description: 'Use `red_team` to adversarially challenge your spec for edge cases.',
                toolHint: 'red_team',
            },
            {
                stepNumber: 4,
                title: 'Generate Tests',
                description: 'Generate test scaffolds from spec criteria with `tdd_scaffold`.',
                toolHint: 'tdd_scaffold',
            },
        ],
    },
    security: {
        area: 'security',
        title: 'Security & Compliance',
        steps: [
            {
                stepNumber: 1,
                title: 'Security Scan',
                description: 'Run `security_scan` to check specs for security anti-patterns.',
                toolHint: 'security_scan',
            },
            {
                stepNumber: 2,
                title: 'Compliance',
                description: 'Configure compliance checks (GDPR, SOC2) with `configure_compliance`.',
                toolHint: 'configure_compliance',
            },
            {
                stepNumber: 3,
                title: 'Audit Trail',
                description: 'View spec change history with `audit_trail` for compliance reporting.',
                toolHint: 'audit_trail',
            },
        ],
    },
    reporting: {
        area: 'reporting',
        title: 'Reporting & Metrics',
        steps: [
            {
                stepNumber: 1,
                title: 'Velocity Report',
                description: 'See team velocity trends with `velocity_report`.',
                toolHint: 'velocity_report',
            },
            {
                stepNumber: 2,
                title: 'Usage Stats',
                description: 'View tool usage and spec activity with `usage_stats`.',
                toolHint: 'usage_stats',
            },
            {
                stepNumber: 3,
                title: 'Workspace Report',
                description: 'Generate a workspace-level HTML report with `workspace_report`.',
                toolHint: 'workspace_report',
            },
            {
                stepNumber: 4,
                title: 'Export',
                description: 'Export specs as CSV, Markdown, or PDF for external stakeholders.',
                toolHint: 'export_specs_csv',
            },
        ],
    },
};
export function getGuidedTour(area) {
    return TOURS[area];
}
export function formatTourMarkdown(tour) {
    const lines = [
        `# Guided Tour: ${tour.title}`,
        ``,
        `This tour covers ${String(tour.steps.length)} steps.`,
        ``,
    ];
    for (const step of tour.steps) {
        lines.push(`## Step ${String(step.stepNumber)}: ${step.title}`, ``);
        lines.push(step.description, ``);
        if (step.example !== undefined) {
            lines.push(`**Example:** \`${step.example}\``, ``);
        }
        if (step.toolHint !== undefined) {
            lines.push(`**Tool:** \`${step.toolHint}\``, ``);
        }
    }
    return lines.join('\n');
}
// ---------------------------------------------------------------------------
// Checklist
// ---------------------------------------------------------------------------
export async function buildOnboardingChecklist(projectPath) {
    const items = [];
    // Check planu.json
    const planuJson = await fileExists(path.join(projectPath, 'planu.json'));
    items.push({
        id: 'planu-init',
        label: 'Project initialized (planu.json exists)',
        completed: planuJson,
        hint: 'Run `init_project` to initialize your project',
    });
    // Check CLAUDE.md or constitution
    const constitutionExists = (await fileExists(path.join(projectPath, 'CLAUDE.md'))) ||
        (await fileExists(path.join(projectPath, '.claude', 'CLAUDE.md')));
    items.push({
        id: 'constitution',
        label: 'Project constitution (CLAUDE.md) exists',
        completed: constitutionExists,
        hint: 'Run `init_constitution` to create your project constitution',
    });
    // Check planu/ directory has specs
    const planuDir = path.join(projectPath, 'planu', 'specs');
    const specsExist = await dirHasContents(planuDir);
    items.push({
        id: 'first-spec',
        label: 'At least one spec created',
        completed: specsExist,
        hint: 'Run `create_spec` to create your first spec',
    });
    // Check .claude/rules/ exists
    const rulesDir = await dirHasContents(path.join(projectPath, '.claude', 'rules'));
    items.push({
        id: 'rules',
        label: 'Project rules configured (.claude/rules/ exists)',
        completed: rulesDir,
        hint: 'Run `reconcile_rules` to set up project rules',
    });
    // Check .claude/skills/ exists
    const skillsDir = await dirHasContents(path.join(projectPath, '.claude', 'skills'));
    items.push({
        id: 'skills',
        label: 'Project skills configured (.claude/skills/ exists)',
        completed: skillsDir,
        hint: 'Run `reconcile_skills` to set up project skills',
    });
    const completedCount = items.filter((i) => i.completed).length;
    const totalCount = items.length;
    return {
        projectPath,
        items,
        completedCount,
        totalCount,
        percentComplete: Math.round((completedCount / totalCount) * 100),
    };
}
export function formatChecklistMarkdown(checklist) {
    const lines = [
        `# Onboarding Checklist`,
        ``,
        `**Progress:** ${String(checklist.completedCount)}/${String(checklist.totalCount)} steps complete (${String(checklist.percentComplete)}%)`,
        ``,
    ];
    for (const item of checklist.items) {
        const icon = item.completed ? '✅' : '⬜';
        lines.push(`${icon} **${item.label}**`);
        if (!item.completed && item.hint !== undefined) {
            lines.push(`   > ${item.hint}`);
        }
    }
    return lines.join('\n');
}
// ---------------------------------------------------------------------------
// Quick Start Templates
// ---------------------------------------------------------------------------
const QUICK_START_CONTENT = {
    'solo-dev': `# Solo Developer Quick Start

## 1. Initialize your project
\`\`\`
init_project projectPath="/path/to/your/project"
\`\`\`

## 2. Create your first spec
\`\`\`
create_spec title="My First Feature" projectPath="/path/to/your/project"
\`\`\`

## 3. Check readiness and implement
\`\`\`
check_readiness specId="SPEC-001" projectPath="..."
\`\`\`

## 4. Validate when done
\`\`\`
validate specId="SPEC-001" projectPath="..."
update_status specId="SPEC-001" newStatus="done" projectPath="..."
\`\`\`
`,
    'team-project': `# Team Project Quick Start

## 1. Initialize and configure roles
\`\`\`
init_project projectPath="/path/to/your/project"
configure_roles projectPath="..."
\`\`\`

## 2. Set up approval policy
\`\`\`
configure_approval_policy projectPath="..." requiredApprovals=1
\`\`\`

## 3. Create specs and assign reviewers
\`\`\`
create_spec title="Feature Name" projectPath="..."
assign_role specId="SPEC-001" role="reviewer" userId="..."
\`\`\`

## 4. Connect integrations
\`\`\`
configure_slack webhookUrl="https://..."
configure_jira host="..." apiToken="..."
\`\`\`
`,
    'api-first': `# API-First Development Quick Start

## 1. Initialize and set up API spec validation
\`\`\`
init_project projectPath="/path/to/your/project"
\`\`\`

## 2. Create API specs from cookbook
\`\`\`
cookbook_get id="api-rate-limiting"
cookbook_apply id="api-auth" projectName="My API"
\`\`\`

## 3. Validate API contract
\`\`\`
validate_api_contract projectPath="..." specFile="openapi.yaml"
\`\`\`

## 4. Generate tests
\`\`\`
tdd_scaffold specId="SPEC-001" projectPath="..."
\`\`\`
`,
    'mobile-app': `# Mobile App Quick Start

## 1. Initialize project
\`\`\`
init_project projectPath="/path/to/your/project"
\`\`\`

## 2. Browse mobile cookbook patterns
\`\`\`
cookbook_list domain="mobile"
\`\`\`

## 3. Generate CI/CD pipeline
\`\`\`
generate_automation_guide projectPath="..." platform="mobile"
\`\`\`

## 4. Set up push notification spec
\`\`\`
cookbook_apply id="mobile-push-notifications" projectName="MyApp"
\`\`\`
`,
    'open-source': `# Open Source Project Quick Start

## 1. Initialize project
\`\`\`
init_project projectPath="/path/to/your/project"
\`\`\`

## 2. Create contribution guidelines via spec
\`\`\`
create_spec title="Contribution Workflow" projectPath="..."
\`\`\`

## 3. Set up CI validation
\`\`\`
generate_planu_ci projectPath="..." provider="github-actions"
\`\`\`

## 4. Generate documentation site
\`\`\`
generate_docs_site projectPath="..."
\`\`\`
`,
};
export function getQuickStart(template) {
    return QUICK_START_CONTENT[template];
}
// ---------------------------------------------------------------------------
// Progress Summary
// ---------------------------------------------------------------------------
export async function buildProgressSummary(projectPath, config) {
    const checklist = await buildOnboardingChecklist(projectPath);
    const nextSteps = [];
    for (const item of checklist.items) {
        if (!item.completed && item.hint !== undefined) {
            nextSteps.push(item.hint);
        }
        if (nextSteps.length >= 3) {
            break;
        }
    }
    if (nextSteps.length === 0) {
        nextSteps.push('All setup steps complete! Explore `guided_tour` for advanced topics.');
    }
    return {
        projectPath,
        config,
        checklist,
        percentComplete: checklist.percentComplete,
        nextSteps,
    };
}
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
async function fileExists(filePath) {
    try {
        await fs.access(filePath);
        return true;
    }
    catch {
        return false;
    }
}
async function dirHasContents(dirPath) {
    try {
        const entries = await fs.readdir(dirPath);
        return entries.length > 0;
    }
    catch {
        return false;
    }
}
export function formatTourStep(step) {
    return `**Step ${String(step.stepNumber)}:** ${step.title} — ${step.description}`;
}
//# sourceMappingURL=onboarding-engine.js.map