/**
 * Decomposition protocol validation.
 * @task T4537
 * @epic T4454
 */
import { existsSync, readFileSync } from 'node:fs';
import { ExitCode } from '@cleocode/contracts';
import { CleoError } from '../../errors.js';
import { getManifestPath } from '../../paths.js';
function findManifestEntry(taskId, manifestPath) {
    if (!existsSync(manifestPath))
        return null;
    const lines = readFileSync(manifestPath, 'utf-8').trim().split('\n');
    for (let i = lines.length - 1; i >= 0; i--) {
        if (lines[i].includes(`"${taskId}"`))
            return lines[i];
    }
    return null;
}
/** Validate decomposition protocol for a task. */
export async function validateDecompositionTask(taskId, opts) {
    const manifestPath = getManifestPath();
    const entry = findManifestEntry(taskId, manifestPath);
    if (!entry) {
        throw new CleoError(ExitCode.NOT_FOUND, `No manifest entry found for task ${taskId}`);
    }
    const manifest = JSON.parse(entry);
    const violations = [];
    // DCMP-007: agent_type check
    if (manifest.agent_type !== 'specification') {
        violations.push({
            code: 'DCMP-007',
            severity: 'high',
            message: `Expected agent_type "specification", got "${manifest.agent_type}"`,
        });
    }
    const score = violations.length === 0 ? 100 : Math.max(0, 100 - violations.length * 25);
    const result = {
        valid: violations.length === 0,
        violations,
        score,
        protocol: 'decomposition',
        taskId,
    };
    if (opts.strict && violations.length > 0) {
        throw new CleoError(63, `Decomposition protocol violations for ${taskId}`);
    }
    return result;
}
/** Validate decomposition protocol from manifest file. */
export async function checkDecompositionManifest(manifestFile, opts) {
    if (!existsSync(manifestFile)) {
        throw new CleoError(ExitCode.NOT_FOUND, `Manifest file not found: ${manifestFile}`);
    }
    const manifest = JSON.parse(readFileSync(manifestFile, 'utf-8'));
    const taskId = manifest.linked_tasks?.[0] ?? 'UNKNOWN';
    return validateDecompositionTask(taskId, opts);
}
//# sourceMappingURL=decomposition.js.map