// engine/universal-rules/user-edit-detector.ts — SPEC-779
// Detect whether a user has manually edited a rule file since install.
import { readFile } from 'node:fs/promises';
import { createHash } from 'node:crypto';
/**
 * Compute SHA-256 hex hash of a string.
 */
export function hashContent(content) {
    return createHash('sha256').update(content, 'utf-8').digest('hex');
}
/**
 * Read and parse the .planu-rules-manifest.json file.
 * Returns null if the file doesn't exist or can't be parsed.
 */
export async function readManifest(manifestPath) {
    try {
        const raw = await readFile(manifestPath, 'utf-8');
        const parsed = JSON.parse(raw);
        if (parsed !== null &&
            typeof parsed === 'object' &&
            'rules' in parsed &&
            Array.isArray(parsed.rules)) {
            return parsed;
        }
        return null;
    }
    catch {
        return null;
    }
}
/**
 * Check if the content of a file on disk matches the hash stored at install time.
 * Returns true if the user has modified the file (disk hash ≠ install hash).
 * Returns false if file matches or the manifest entry is missing.
 */
export async function isUserModified(ruleId, manifestPath) {
    const manifest = await readManifest(manifestPath);
    if (manifest === null) {
        return false;
    }
    const entry = manifest.rules.find((r) => r.id === ruleId);
    if (entry === undefined) {
        return false;
    }
    try {
        const diskContent = await readFile(entry.path, 'utf-8');
        const diskHash = hashContent(diskContent);
        return diskHash !== entry.hashAtInstall;
    }
    catch {
        return false;
    }
}
/**
 * Build an updated manifest by adding or replacing an entry for the given rule.
 */
export function upsertManifestEntry(manifest, newEntry) {
    const existing = manifest.rules.filter((r) => r.id !== newEntry.id);
    return { rules: [...existing, newEntry] };
}
//# sourceMappingURL=user-edit-detector.js.map