// tools/capture-learning.ts — Capture learned patterns into spec criteria (SPEC-012)
// Accepts a natural language description, performs semantic dedup against existing
// spec criteria, and routes new patterns to the most relevant spec.
import { globalStore } from '../storage/index.js';
import { extractKeywords, isDuplicate, findBestSpec, formatCriterion, } from '../engine/learning-router.js';
export async function handleCaptureLearning(args) {
    const { description, subcommand, lessonType, tags = [] } = args;
    // --- Subcommand: lesson ---
    if (subcommand === 'lesson') {
        return handleLessonCapture(description, lessonType ?? 'bug-pattern', tags);
    }
    // --- Main flow: capture pattern into spec criteria ---
    const patternKeywords = extractKeywords(description);
    // Build minimal spec descriptors from known specs (static registry)
    const specDescriptors = buildSpecDescriptors();
    // 1. Check for semantic duplicates
    const dupResult = isDuplicate(patternKeywords, specDescriptors);
    if (dupResult.isDuplicate) {
        return {
            content: [
                {
                    type: 'text',
                    text: [
                        `Pattern already covered (${String(dupResult.similarity)}% similarity).`,
                        `Existing spec: ${dupResult.existingSpecId ?? 'unknown'}`,
                        `Existing criterion: "${dupResult.existingCriterion ?? ''}"`,
                        'No duplicate criterion inserted.',
                    ].join('\n'),
                },
                {
                    type: 'text',
                    text: JSON.stringify({
                        action: 'duplicate_detected',
                        similarity: dupResult.similarity,
                        existingSpecId: dupResult.existingSpecId,
                        existingCriterion: dupResult.existingCriterion,
                    }, null, 2),
                },
            ],
        };
    }
    // 2. Route to best matching spec
    const targetSpecId = args.specId ?? findBestSpec(patternKeywords, specDescriptors);
    const formattedCriterion = formatCriterion(description);
    // 3. Store the pending criterion (persisted as a lesson with 'test-complexity' type
    //    so it's queryable; future iterations would insert into HU.md)
    const lessonId = `LEARN-${Date.now().toString(36).toUpperCase()}`;
    const lesson = {
        id: lessonId,
        specId: targetSpecId ?? 'unrouted',
        type: 'arch-mismatch',
        description: formattedCriterion,
        tags: [...patternKeywords.slice(0, 5), 'pending-criterion'],
        recordedAt: new Date().toISOString(),
    };
    await globalStore.saveLessonLearned(lesson);
    const output = {
        action: 'criterion_captured',
        lessonId,
        targetSpecId: targetSpecId ?? null,
        formattedCriterion,
        status: 'pending',
        message: targetSpecId
            ? `New criterion added to ${targetSpecId} (status: pending, requires manual review).`
            : 'No matching spec found. Criterion stored as unrouted pending entry.',
    };
    return {
        content: [
            {
                type: 'text',
                text: output.message,
            },
            {
                type: 'text',
                text: JSON.stringify(output, null, 2),
            },
        ],
    };
}
// ---------------------------------------------------------------------------
// handleLessonCapture — learn_pattern lesson subcommand
// ---------------------------------------------------------------------------
async function handleLessonCapture(description, lessonType, tags) {
    const keywords = extractKeywords(description);
    const lessonId = `LESSON-${Date.now().toString(36).toUpperCase()}`;
    const lesson = {
        id: lessonId,
        specId: 'global',
        type: lessonType,
        description: description.trim(),
        tags: [...new Set([...tags, ...keywords.slice(0, 3)])],
        recordedAt: new Date().toISOString(),
    };
    await globalStore.saveLessonLearned(lesson);
    const output = {
        action: 'lesson_captured',
        lessonId,
        type: lessonType,
        description: lesson.description,
        tags: lesson.tags,
    };
    return {
        content: [
            {
                type: 'text',
                text: `Lesson captured (${lessonType}): "${lesson.description.slice(0, 80)}..."`,
            },
            {
                type: 'text',
                text: JSON.stringify(output, null, 2),
            },
        ],
    };
}
// ---------------------------------------------------------------------------
// buildSpecDescriptors — static registry of known specs for routing
// ---------------------------------------------------------------------------
function buildSpecDescriptors() {
    return [
        {
            specId: 'SPEC-002',
            title: 'Create Spec Enhancement',
            criteria: [],
            keywords: ['spec', 'create', 'template', 'diagram', 'split', 'hu', 'ficha'],
        },
        {
            specId: 'SPEC-003',
            title: 'Web Fetcher',
            criteria: [],
            keywords: ['web', 'fetch', 'http', 'npm', 'pypi', 'crates', 'registry'],
        },
        {
            specId: 'SPEC-004',
            title: 'Init Project',
            criteria: [],
            keywords: ['init', 'project', 'language', 'framework', 'architecture', 'detection'],
        },
        {
            specId: 'SPEC-005',
            title: 'DoR DoD Plan',
            criteria: [],
            keywords: ['dor', 'dod', 'plan', 'status', 'implementing', 'done', 'red', 'green'],
        },
        {
            specId: 'SPEC-006',
            title: 'Spec Versioning',
            criteria: [],
            keywords: ['version', 'diff', 'cascade', 'drift', 'dependency'],
        },
        {
            specId: 'SPEC-007',
            title: 'Constitution',
            criteria: [],
            keywords: ['constitution', 'principle', 'enforce', 'validation', 'rule'],
        },
        {
            specId: 'SPEC-008',
            title: 'NLI Engine',
            criteria: [],
            keywords: ['nli', 'natural', 'language', 'context', 'intent', 'resolution'],
        },
        {
            specId: 'SPEC-009',
            title: 'NLI Chains',
            criteria: [],
            keywords: ['chain', 'orchestrate', 'phase', 'event', 'experience', 'beginner', 'expert'],
        },
        {
            specId: 'SPEC-010',
            title: 'Quality Audit',
            criteria: [],
            keywords: ['audit', 'quality', 'score', 'solid', 'claude', 'rule'],
        },
        {
            specId: 'SPEC-011',
            title: 'Auto Learning',
            criteria: [],
            keywords: ['learn', 'calibrate', 'registry', 'feedback', 'verified', 'pattern'],
        },
        {
            specId: 'SPEC-012',
            title: 'Auto Improvement Tokens',
            criteria: [],
            keywords: ['token', 'budget', 'improvement', 'override', 'dashboard', 'model'],
        },
    ];
}
//# sourceMappingURL=capture-learning.js.map