// Planu — .claude/rules/ auditor for SPEC-092
import { readFile, readdir } from 'node:fs/promises';
import { homedir } from 'node:os';
import { join } from 'node:path';
const DOCS_REF = 'https://code.claude.com/docs/en/memory#rules';
async function auditRulesDir(rulesPath, label) {
    const findings = [];
    let files;
    try {
        const entries = await readdir(rulesPath);
        files = entries.filter((f) => f.endsWith('.md'));
    }
    catch {
        findings.push({
            area: 'rules',
            severity: 'info',
            message: `${label} directory does not exist`,
            suggestion: 'Create .claude/rules/ with scoped rule files to keep CLAUDE.md lean',
            docsRef: DOCS_REF,
        });
        return findings;
    }
    if (files.length === 0) {
        findings.push({
            area: 'rules',
            severity: 'info',
            message: `${label} directory exists but has no .md files`,
            suggestion: 'Add rule files with paths: frontmatter for context-aware loading',
            docsRef: DOCS_REF,
        });
        return findings;
    }
    for (const file of files) {
        try {
            const content = await readFile(join(rulesPath, file), 'utf-8');
            const firstLines = content.split('\n').slice(0, 5).join('\n');
            const hasPaths = /^paths:/m.test(firstLines) || /^---[\s\S]*?paths:/m.test(firstLines);
            if (!hasPaths) {
                // Check if file has TypeScript/test-specific content that should be scoped
                const lowerContent = content.toLowerCase();
                const isScoped = lowerContent.includes('typescript') ||
                    lowerContent.includes('.test.') ||
                    lowerContent.includes('vitest') ||
                    lowerContent.includes('jest') ||
                    lowerContent.includes('.tsx') ||
                    lowerContent.includes('.jsx');
                if (isScoped) {
                    findings.push({
                        area: 'rules',
                        severity: 'warn',
                        message: `Rule "${file}" has language/test-specific content but no paths: frontmatter`,
                        suggestion: `Add "paths: src/**/*.ts" or similar frontmatter so it only loads for matching files`,
                        docsRef: DOCS_REF,
                    });
                }
            }
        }
        catch {
            // Skip unreadable files
        }
    }
    return findings;
}
export async function auditRules(projectPath, includeGlobal) {
    const findings = [];
    findings.push(...(await auditRulesDir(join(projectPath, '.claude', 'rules'), 'Project .claude/rules/')));
    if (includeGlobal) {
        findings.push(...(await auditRulesDir(join(homedir(), '.claude', 'rules'), 'Global ~/.claude/rules/')));
    }
    return findings;
}
//# sourceMappingURL=rules-auditor.js.map