import { appendFile, mkdir, writeFile } from "fs/promises";
import { join } from "path";
export async function persistLoopArtifacts(state, decision, options) {
    const runId = options.runId ?? state.runId;
    const runDir = join(options.root, ".omk", "runs", runId);
    await mkdir(runDir, { recursive: true });
    const statePath = join(runDir, "loop-state.json");
    const decisionsPath = join(runDir, "loop-decisions.jsonl");
    const nextInputPath = options.nextInputEnvelope
        ? join(runDir, "next-input-envelope.json")
        : undefined;
    await Promise.all([
        writeFile(statePath, `${JSON.stringify(state, null, 2)}\n`, "utf-8"),
        appendFile(decisionsPath, `${JSON.stringify(decision)}\n`, "utf-8"),
        nextInputPath && options.nextInputEnvelope
            ? writeFile(nextInputPath, `${JSON.stringify(options.nextInputEnvelope, null, 2)}\n`, "utf-8")
            : Promise.resolve(),
    ]);
    return { runDir, statePath, decisionsPath, nextInputPath };
}
