// tools/challenge-spec.ts — Devil's advocate resilience testing
// Analyzes a spec from adversarial perspectives: failure scenarios,
// concurrency issues, scale limits, security holes, and data consistency.
import { specStore, knowledgeStore } from '../storage/index.js';
import { t, ti } from '../i18n/index.js';
import { generateFailureScenarios, generateSecurityScenarios, generateScaleScenarios, generateDataConsistencyScenarios, generateGameChallenges, generateDesktopAutoUpdateChallenges, } from './challenge-spec-scenarios.js';
import { generateConcurrencyAnalysis, buildScalabilityAssessment, calculateOverallRisk, readSpecContent, } from './challenge-spec-helpers.js';
import { generateAgentChallengeScenarios, isAgentSpec, } from './challenge-spec/agent-challenge-scenarios.js';
import { getPlatformChallenges } from './challenge-spec/platform-challenge-scenarios.js';
import { generateSecurityChallengeScenarios } from './challenge-spec/security-challenge-scenarios.js';
import { generatePrivacyChallengeScenarios } from './challenge-spec/privacy-challenge-scenarios.js';
import { generateEventChallengeScenarios } from './challenge-spec/event-challenge-scenarios.js';
import { generateDddChallenges, generateXpPairClarityChallenge, } from './challenge-spec/architecture-challenge-scenarios.js';
import { generateResilienceChallengeScenarios } from './challenge-spec/resilience-challenge-scenarios.js';
const ALL_FOCUS_AREAS = [
    'failures',
    'concurrency',
    'scale',
    'security',
    'data-consistency',
];
export async function handleChallengeSpec(args) {
    const { specId, projectId, focus } = args;
    // 1. Load spec
    const spec = await specStore.getSpec(projectId, specId);
    if (!spec) {
        return {
            content: [{ type: 'text', text: ti('spec.notFound', { id: specId }) }],
            isError: true,
        };
    }
    // 2. Load project knowledge
    const knowledge = await knowledgeStore.getKnowledge(projectId);
    if (!knowledge) {
        return {
            content: [{ type: 'text', text: t('project.notFound') }],
            isError: true,
        };
    }
    // 2b. Load Constitution for compliance context
    const constitution = await knowledgeStore.getConstitution(projectId);
    // 3. Read spec content
    const specContent = await readSpecContent(spec);
    // 4. Determine focus areas
    const focusAreas = focus && focus.length > 0 ? focus : ALL_FOCUS_AREAS;
    // 5. Generate failure scenarios
    const failureScenarios = [];
    if (focusAreas.includes('failures')) {
        failureScenarios.push(...generateFailureScenarios(spec, specContent, knowledge));
    }
    if (focusAreas.includes('security')) {
        failureScenarios.push(...generateSecurityScenarios(spec, specContent, knowledge));
    }
    if (focusAreas.includes('scale')) {
        failureScenarios.push(...generateScaleScenarios(spec, specContent, knowledge));
    }
    if (focusAreas.includes('data-consistency')) {
        failureScenarios.push(...generateDataConsistencyScenarios(spec, specContent, knowledge));
    }
    // 5e. Game-specific challenges (performance, balance, cheating, physics)
    if (knowledge.projectCategory === 'game' ||
        (knowledge.framework !== null &&
            ['unity', 'godot', 'unreal', 'bevy', 'phaser', 'pygame'].includes(knowledge.framework))) {
        failureScenarios.push(...generateGameChallenges(spec, specContent, knowledge));
    }
    // 5f. SPEC-014b: Desktop auto-update edge cases
    failureScenarios.push(...generateDesktopAutoUpdateChallenges(spec, specContent, knowledge));
    // 5g. SPEC-016a: AI agent-specific failure modes
    if (isAgentSpec(spec, specContent)) {
        failureScenarios.push(...generateAgentChallengeScenarios(spec, specContent, knowledge));
    }
    // 5h. SPEC-015a: Smart contract, bot, and IoT challenges
    failureScenarios.push(...getPlatformChallenges(spec, specContent, knowledge));
    // 5i. SPEC-029: Security authorization and STRIDE challenges
    if (focusAreas.includes('security')) {
        failureScenarios.push(...generateSecurityChallengeScenarios(spec, specContent, knowledge));
    }
    // 5j. SPEC-030: Privacy challenges (mandatory when spec has PII)
    failureScenarios.push(...generatePrivacyChallengeScenarios(spec, specContent, knowledge));
    // 5k. SPEC-031: Event-driven challenges (contract, idempotence, DLQ)
    failureScenarios.push(...generateEventChallengeScenarios(spec, specContent, knowledge));
    // 5l. SPEC-033: DDD aggregate integrity challenges
    const hasDdd = knowledge.architecture.primary === 'ddd' || knowledge.architecture.secondary.includes('ddd');
    if (hasDdd) {
        failureScenarios.push(...generateDddChallenges(spec, specContent));
    }
    // 5n. SPEC-034: Resilience, validation, concurrency, and saga challenges
    failureScenarios.push(...generateResilienceChallengeScenarios(spec, specContent, knowledge));
    // 5m. SPEC-033: XP pair programming clarity challenge — check agileConfig via safe cast
    const knowledgeAny = knowledge;
    const agileConfig = knowledgeAny.agileConfig;
    if (agileConfig?.process === 'xp') {
        failureScenarios.push(...generateXpPairClarityChallenge(spec, specContent));
    }
    // 6. Generate concurrency analysis
    const concurrencyAnalysis = focusAreas.includes('concurrency')
        ? generateConcurrencyAnalysis(spec, specContent, knowledge)
        : { hotPaths: [], raceConditions: [], sharedState: [], recommendations: [] };
    // 7. Build scalability assessment
    const scalabilityAssessment = buildScalabilityAssessment(spec, knowledge, failureScenarios);
    // 8. Calculate overall risk
    const overallRisk = calculateOverallRisk(failureScenarios, concurrencyAnalysis);
    const analysis = {
        failureScenarios,
        concurrencyAnalysis,
        scalabilityAssessment,
        overallRisk,
    };
    return {
        content: [
            {
                type: 'text',
                text: ti('tools.challenge_spec.success', {
                    scenarioCount: String(failureScenarios.length),
                }),
            },
            {
                type: 'text',
                text: JSON.stringify({
                    ...analysis,
                    summary: {
                        totalScenarios: failureScenarios.length,
                        criticalImpact: failureScenarios.filter((s) => s.impact === 'critical').length,
                        highImpact: failureScenarios.filter((s) => s.impact === 'high').length,
                        raceConditions: concurrencyAnalysis.raceConditions.length,
                        overallRisk,
                        focusAreas: focusAreas,
                        warnings: overallRisk === 'critical' || overallRisk === 'high'
                            ? [
                                `⚠️ HIGH RISK spec: overall risk is "${overallRisk}". Review all critical/high scenarios before implementation.`,
                                overallRisk === 'critical'
                                    ? 'BLOCK: Resolve critical scenarios before merging to main branch.'
                                    : 'CAUTION: Add extra code review and integration tests for high-risk paths.',
                            ]
                            : [],
                    },
                    constitutionCompliance: constitution
                        ? {
                            principlesCount: constitution.principles.length,
                            strictCount: constitution.principles.filter((p) => p.enforceLevel === 'strict')
                                .length,
                            checkedAt: new Date().toISOString(),
                        }
                        : null,
                }, null, 2),
            },
        ],
    };
}
//# sourceMappingURL=challenge-spec.js.map