// tools/triage-request.ts — SPEC-726: Triagier role MCP tool handler
import { z } from 'zod';
import { classifyIntent } from '../engine/triagier/classifier.js';
import { appendArtifact } from '../engine/handoff-artifacts/io.js';
import { interactiveResult } from './response-helpers.js';
// ---------------------------------------------------------------------------
// Input schema
// ---------------------------------------------------------------------------
export const TriageRequestInputSchema = z.object({
    description: z
        .string()
        .min(1)
        .max(5000)
        .describe('Natural language description of what the user wants to build, fix, or explore'),
    sessionId: z
        .string()
        .optional()
        .describe('Optional session identifier for continuity across calls'),
    hint: z
        .object({
        kind: z
            .enum(['idea', 'quick-fix', 'bug-spec', 'feature-spec', 'epic'])
            .optional()
            .describe('Pre-classified kind to skip LLM classification'),
    })
        .optional()
        .describe('Optional classification hint'),
    projectId: z
        .string()
        .optional()
        .describe('Project identifier for artifact storage. Required to write intake.json'),
    specId: z
        .string()
        .optional()
        .describe('Spec identifier for artifact storage. Auto-generated if absent when projectId is given'),
});
// ---------------------------------------------------------------------------
// Low-confidence disambiguation questions
// ---------------------------------------------------------------------------
const CONFIDENCE_THRESHOLD = 0.6;
function buildDisambiguationQuestions(description) {
    return [
        {
            question: `What kind of work is "${description.slice(0, 60)}${description.length > 60 ? '…' : ''}"?`,
            header: 'Triage Kind',
            options: [
                {
                    label: 'idea',
                    description: 'An exploratory idea or "what if" — goes to the backlog, no spec created',
                },
                {
                    label: 'quick-fix',
                    description: 'A small, self-contained change (typo, rename) — implement directly without elicitation',
                },
                {
                    label: 'bug-spec',
                    description: 'A defect that needs a formal bug report and investigation',
                },
                {
                    label: 'feature-spec (Recommended)',
                    description: 'A new feature or enhancement that requires requirements elicitation',
                },
                {
                    label: 'epic',
                    description: 'A large-scale initiative spanning multiple features or systems',
                },
            ],
            multiSelect: false,
        },
    ];
}
// ---------------------------------------------------------------------------
// Handler
// ---------------------------------------------------------------------------
export async function handleTriageRequest(input) {
    const { description, sessionId, hint, projectId } = input;
    // Classify the intent
    const result = await classifyIntent({ description, sessionId, hint });
    // Low confidence — ask the user before committing
    if (result.confidence < CONFIDENCE_THRESHOLD) {
        const questions = buildDisambiguationQuestions(description);
        return interactiveResult(questions, `Triage confidence (${Math.round(result.confidence * 100)}%) is below threshold — please select the kind to proceed.`, 'claude-code');
    }
    // Write intake.json if projectId is available
    let artifactPath = null;
    let artifactError = null;
    if (projectId) {
        const specId = input.specId ?? `intake-${Date.now()}`;
        try {
            const written = await appendArtifact({
                projectId,
                specId,
                kind: 'intake',
                payload: {
                    schema_version: '1.0.0',
                    kind: result.kind,
                    description,
                    confidence: result.confidence,
                    rationale: result.rationale,
                    createdAt: new Date().toISOString(),
                },
            });
            artifactPath = written.path;
        }
        catch (err) {
            artifactError = err instanceof Error ? err.message : String(err);
        }
    }
    const responseData = {
        kind: result.kind,
        confidence: result.confidence,
        rationale: result.rationale,
        nextStep: result.nextStep,
        ...(artifactPath ? { artifactPath } : {}),
        ...(artifactError ? { artifactWarning: `intake.json not written: ${artifactError}` } : {}),
        ...(projectId === undefined
            ? { note: 'Provide projectId to persist the intake.json handoff artifact' }
            : {}),
    };
    const text = [
        `## Triage Result`,
        '',
        `**Kind**: ${result.kind}`,
        `**Confidence**: ${Math.round(result.confidence * 100)}%`,
        `**Rationale**: ${result.rationale}`,
        '',
        `**Next step**: Call \`${result.nextStep.tool}\`${result.nextStep.mode ? ` (mode: ${result.nextStep.mode})` : ''}${result.nextStep.estimatedMinutes !== undefined ? ` — ~${String(result.nextStep.estimatedMinutes)} min` : ''}`,
        ...(artifactPath ? ['', `✅ Intake artifact written: \`${artifactPath}\``] : []),
        ...(artifactError ? ['', `⚠️ Intake artifact not written: ${artifactError}`] : []),
    ].join('\n');
    return {
        content: [{ type: 'text', text }],
        structuredContent: responseData,
    };
}
//# sourceMappingURL=triage-request.js.map