// engine/claude-md-injector/file-patcher.ts — Patches CLAUDE.md with Planu proactive-behavior rules
import { readFile, writeFile } from 'node:fs/promises';
const START_MARKER_REGEX = /<!-- planu:rules:start[^>]* -->/;
const BLOCK_REGEX = /<!-- planu:rules:start[\s\S]*?<!-- planu:rules:end -->/;
/**
 * Patches a CLAUDE.md file by injecting or replacing the Planu proactive-behavior rules section.
 *
 * Algorithm:
 * 1. If the file doesn't exist: create it with the section as its entire content.
 * 2. If the file exists:
 *    a. Read content and write a backup to `{claudeMdPath}.planu-backup`.
 *    b. If a `<!-- planu:rules:start` marker exists: replace the entire block.
 *    c. Otherwise: append the section at the end of the file.
 *    d. If write fails: restore the backup (best-effort).
 */
export async function patchClaudeMd(claudeMdPath, section) {
    let existing;
    try {
        existing = await readFile(claudeMdPath, 'utf8');
    }
    catch {
        // File does not exist — create it with just the section
        await writeFile(claudeMdPath, section, 'utf8');
        return;
    }
    // Write backup before modifying
    const backupPath = `${claudeMdPath}.planu-backup`;
    await writeFile(backupPath, existing, 'utf8');
    const hasBlock = START_MARKER_REGEX.test(existing);
    const updated = hasBlock ? existing.replace(BLOCK_REGEX, section) : `${existing}\n\n${section}`;
    try {
        await writeFile(claudeMdPath, updated, 'utf8');
    }
    catch (writeError) {
        // Restore backup on failure — best-effort, ignore secondary errors
        /* c8 ignore next 3 */
        await writeFile(claudeMdPath, existing, 'utf8').catch(() => undefined);
        throw writeError;
    }
}
//# sourceMappingURL=file-patcher.js.map