import { appendEvent } from "../observability/index.js";
import { createId, nowIso, readJsonFile, sanitizeText, withFileLock, writeJsonFile } from "../../shared/index.js";
import { ensureWorkspaceState, workspaceDiffsPath } from "./store.js";
import { normalizeWorkspacePolicyPath } from "./enforcement.js";
export async function listWorkspaceDiffRefs(store, runId) {
    await ensureWorkspaceState(store, runId);
    return ((await readJsonFile(workspaceDiffsPath(store, runId))) ?? []).map(normalizeDiffRef);
}
export async function recordWorkspaceDiffRef(store, runId, input) {
    await ensureWorkspaceState(store, runId);
    const file = workspaceDiffsPath(store, runId);
    const diff = await withFileLock(file, async () => {
        const diffs = ((await readJsonFile(file)) ?? []).map(normalizeDiffRef);
        const diffId = createId("workspace_diff");
        const next = {
            diff_id: diffId,
            diff_ref: `workspace/diffs.json#${diffId}`,
            run_id: runId,
            status: "recorded",
            owner: sanitizeText(input.owner),
            subplan_id: optionalText(input.subplan_id),
            paths: unique(input.paths.map(normalizeWorkspacePolicyPath).filter(Boolean)),
            lease_ids: unique(input.lease_ids ?? []),
            summary: sanitizeText(input.summary),
            evidence_refs: unique(input.evidence_refs ?? []),
            created_at: nowIso(),
        };
        diffs.push(next);
        await writeJsonFile(file, diffs);
        return next;
    });
    await appendEvent(store, runId, {
        type: "workspace_diff_recorded",
        actor: diff.owner,
        summary: diff.subplan_id ? `${diff.subplan_id}: ${diff.summary}` : diff.summary,
        metadata: { diff },
    });
    return diff;
}
function normalizeDiffRef(diff) {
    return {
        ...diff,
        diff_ref: diff.diff_ref ?? `workspace/diffs.json#${diff.diff_id}`,
        status: diff.status ?? "recorded",
        paths: unique((diff.paths ?? []).map(normalizeWorkspacePolicyPath).filter(Boolean)),
        lease_ids: unique(diff.lease_ids ?? []),
        evidence_refs: unique(diff.evidence_refs ?? []),
    };
}
function optionalText(value) {
    const sanitized = value === undefined ? undefined : sanitizeText(value).trim();
    return sanitized || undefined;
}
function unique(values) {
    return [...new Set(values.filter(Boolean))];
}
//# sourceMappingURL=diff.js.map