// engine/reconcile/verify-write.ts — SPEC-1011 Bug D: Post-write integrity verification
// After reconcile_spec writes changes, re-reads the file to assert each newValue is present.
import { readFile } from 'node:fs/promises';
import { RECONCILE_METADATA_SECTIONS, } from '../../types/index.js';
/**
 * Re-reads the file at `filePath` and checks that each approved change's `newValue`
 * is present somewhere in the file content.
 *
 * If any check fails, `verified` is false and `missingChanges` lists what was not found.
 */
export async function verifyWriteSucceeded(filePath, changes) {
    const approvedChanges = changes.filter((c) => c.approved);
    if (approvedChanges.length === 0) {
        return { verified: true, missingChanges: [] };
    }
    let content;
    try {
        content = await readFile(filePath, 'utf-8');
    }
    catch (err) {
        const reason = err instanceof Error ? err.message : String(err);
        return {
            verified: false,
            missingChanges: approvedChanges.map((c) => ({
                section: c.section,
                newValue: c.newValue,
                reason: `Could not re-read file after write: ${reason}`,
            })),
        };
    }
    const missingChanges = [];
    for (const change of approvedChanges) {
        // Skip metadata-only sections that do not produce text in spec.md
        if (RECONCILE_METADATA_SECTIONS.has(change.section)) {
            continue;
        }
        if (!content.includes(change.newValue)) {
            missingChanges.push({
                section: change.section,
                newValue: change.newValue,
                reason: `newValue not found in file after write`,
            });
        }
    }
    return {
        verified: missingChanges.length === 0,
        missingChanges,
    };
}
//# sourceMappingURL=verify-write.js.map