/**
 * Constitution loader — reads AGENTS.md or CLAUDE.md from a project root.
 *
 * Every agent should read the project constitution before acting.
 * Search order: AGENTS.md > agents.md > CLAUDE.md > claude.md
 * Returns structured content with parsed markdown sections.
 */
import { readFile } from 'node:fs/promises';
import { join } from 'node:path';
// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------
/** Search order — AGENTS.md preferred, CLAUDE.md fallback */
const SEARCH_FILES = ['AGENTS.md', 'agents.md', 'CLAUDE.md', 'claude.md'];
// ---------------------------------------------------------------------------
// Section parser
// ---------------------------------------------------------------------------
/**
 * Parse markdown content into heading-delimited sections.
 * Splits on lines matching ^#{1,3}\s pattern.
 */
function parseSections(content) {
    const lines = content.split('\n');
    const sections = [];
    const headingRegex = /^(#{1,3})\s+(.+)$/;
    let currentHeading = null;
    let currentLevel = 0;
    let currentLines = [];
    for (const line of lines) {
        const match = headingRegex.exec(line);
        if (match) {
            // Flush previous section
            if (currentHeading !== null) {
                sections.push({
                    heading: currentHeading,
                    level: currentLevel,
                    content: currentLines.join('\n').trim(),
                });
            }
            currentHeading = match[2].trim();
            currentLevel = match[1].length;
            currentLines = [];
        }
        else {
            currentLines.push(line);
        }
    }
    // Flush last section
    if (currentHeading !== null) {
        sections.push({
            heading: currentHeading,
            level: currentLevel,
            content: currentLines.join('\n').trim(),
        });
    }
    return sections;
}
// ---------------------------------------------------------------------------
// Main loader
// ---------------------------------------------------------------------------
/**
 * Load the project constitution from the given directory.
 *
 * Searches for AGENTS.md, agents.md, CLAUDE.md, claude.md (in that order).
 * Returns null if no constitution file is found.
 */
export async function loadConstitution(projectDir) {
    for (const filename of SEARCH_FILES) {
        const filePath = join(projectDir, filename);
        try {
            const content = await readFile(filePath, 'utf-8');
            const sections = parseSections(content);
            return { content, source: filename, sections };
        }
        catch { }
    }
    return null;
}
//# sourceMappingURL=constitution.js.map