// Planu — CLAUDE.md auditor for SPEC-092
import { readFile } from 'node:fs/promises';
import { homedir } from 'node:os';
import { join } from 'node:path';
const DOCS_REF = 'https://code.claude.com/docs/en/memory';
const MAX_LINES = 200;
const CRITICAL_LINES = 400;
const SECTION_THRESHOLD = 20;
async function readFileLines(filePath) {
    try {
        const content = await readFile(filePath, 'utf-8');
        return content.split('\n');
    }
    catch {
        return null;
    }
}
function auditSingleClaudeMd(lines, label) {
    const findings = [];
    const lineCount = lines.length;
    if (lineCount > CRITICAL_LINES) {
        findings.push({
            area: 'CLAUDE.md',
            severity: 'critical',
            message: `${label} has ${String(lineCount)} lines (limit: ${String(CRITICAL_LINES)})`,
            suggestion: 'Split into .claude/rules/ files with paths: frontmatter for scoped loading',
            docsRef: DOCS_REF,
        });
    }
    else if (lineCount > MAX_LINES) {
        findings.push({
            area: 'CLAUDE.md',
            severity: 'warn',
            message: `${label} has ${String(lineCount)} lines (recommended: <${String(MAX_LINES)})`,
            suggestion: 'Move detailed sections to .claude/rules/ files to reduce context overhead',
            docsRef: DOCS_REF,
        });
    }
    // Detect large sections that could be extracted to rules
    let currentSectionStart = -1;
    let currentSectionLines = 0;
    for (let i = 0; i < lines.length; i++) {
        const line = lines[i];
        if (line?.startsWith('## ')) {
            if (currentSectionLines > SECTION_THRESHOLD && currentSectionStart >= 0) {
                const sectionName = lines[currentSectionStart]?.replace('## ', '') ?? 'unknown';
                findings.push({
                    area: 'CLAUDE.md',
                    severity: 'info',
                    message: `Section "${sectionName}" is ${String(currentSectionLines)} lines — could be a rule file`,
                    suggestion: `Move to .claude/rules/${sectionName.toLowerCase().replace(/\s+/g, '-')}.md`,
                    docsRef: DOCS_REF,
                });
            }
            currentSectionStart = i;
            currentSectionLines = 0;
        }
        else {
            currentSectionLines++;
        }
    }
    // Check last section
    if (currentSectionLines > SECTION_THRESHOLD && currentSectionStart >= 0) {
        const sectionName = lines[currentSectionStart]?.replace('## ', '') ?? 'unknown';
        findings.push({
            area: 'CLAUDE.md',
            severity: 'info',
            message: `Section "${sectionName}" is ${String(currentSectionLines)} lines — could be a rule file`,
            suggestion: `Move to .claude/rules/${sectionName.toLowerCase().replace(/\s+/g, '-')}.md`,
            docsRef: DOCS_REF,
        });
    }
    return findings;
}
export async function auditClaudeMd(projectPath, includeGlobal) {
    const findings = [];
    // Check project-level CLAUDE.md locations
    const projectPaths = [join(projectPath, 'CLAUDE.md'), join(projectPath, '.claude', 'CLAUDE.md')];
    let foundProject = false;
    for (const p of projectPaths) {
        const lines = await readFileLines(p);
        if (lines) {
            foundProject = true;
            findings.push(...auditSingleClaudeMd(lines, `Project CLAUDE.md (${p})`));
        }
    }
    if (!foundProject) {
        findings.push({
            area: 'CLAUDE.md',
            severity: 'warn',
            message: 'No CLAUDE.md found in project root or .claude/ directory',
            suggestion: 'Create a CLAUDE.md with project conventions, commands, and architecture overview',
            docsRef: DOCS_REF,
        });
    }
    // Check for CLAUDE.local.md
    const localMdLines = await readFileLines(join(projectPath, 'CLAUDE.local.md'));
    if (!localMdLines) {
        findings.push({
            area: 'CLAUDE.md',
            severity: 'info',
            message: 'No CLAUDE.local.md found — personal preferences go here (gitignored)',
            suggestion: 'Create CLAUDE.local.md for personal project-specific preferences not tracked in git',
            docsRef: DOCS_REF,
        });
    }
    // Check for @import syntax
    for (const p of projectPaths) {
        const lines = await readFileLines(p);
        if (lines) {
            const hasImports = lines.some((l) => l.startsWith('@'));
            if (!hasImports) {
                findings.push({
                    area: 'CLAUDE.md',
                    severity: 'info',
                    message: 'CLAUDE.md does not use @path imports (e.g. @README.md, @package.json)',
                    suggestion: 'Use @path syntax to import key files so Claude always has fresh context',
                    docsRef: DOCS_REF,
                });
            }
        }
    }
    // Global CLAUDE.md
    if (includeGlobal) {
        const globalPath = join(homedir(), '.claude', 'CLAUDE.md');
        const globalLines = await readFileLines(globalPath);
        if (globalLines) {
            findings.push(...auditSingleClaudeMd(globalLines, 'Global ~/.claude/CLAUDE.md'));
        }
    }
    return findings;
}
//# sourceMappingURL=claudemd-auditor.js.map