import { appendJsonl, readJson, writeJsonAtomic } from '../fsx.js';
import { loopRunLogPath, loopStatePath } from './loop-artifacts.js';
export async function readLoopState(root, missionId, loopId) {
    return readJson(loopStatePath(root, missionId, loopId), null);
}
export async function writeLoopState(root, state) {
    await writeJsonAtomic(loopStatePath(root, state.mission_id, state.loop_id), state);
    return state;
}
export async function appendLoopRunLog(root, missionId, loopId, event) {
    await appendJsonl(loopRunLogPath(root, missionId, loopId), { ts: event.ts || new Date().toISOString(), ...event });
}
export async function updateLoopState(root, missionId, loopId, patch) {
    const current = await readLoopState(root, missionId, loopId);
    if (!current)
        throw new Error(`loop_state_missing:${loopId}`);
    const next = {
        ...current,
        ...patch,
        acting_on: { ...current.acting_on, ...(patch.acting_on || {}) },
        handoff: { ...current.handoff, ...(patch.handoff || {}) },
        budget_used: { ...current.budget_used, ...(patch.budget_used || {}) },
        updated_at: new Date().toISOString()
    };
    await writeLoopState(root, next);
    return next;
}
export function initialLoopState(input) {
    return {
        schema: 'sks.loop-state.v1',
        mission_id: input.missionId,
        loop_id: input.loopId,
        status: 'planned',
        iteration: 0,
        acting_on: {
            files: input.files,
            worktree_id: input.worktreeId || null,
            branch: input.branch || null
        },
        current_phase: 'triage',
        last_action: null,
        last_gate_result: null,
        last_checker_result: null,
        blockers: [],
        handoff: {
            required: false,
            reason: null,
            artifact: null
        },
        budget_used: {
            wall_ms: 0,
            model_calls: 0,
            subagents: 0,
            iterations: 0,
            changed_files: 0,
            patch_bytes: 0
        },
        updated_at: new Date().toISOString()
    };
}
//# sourceMappingURL=loop-state.js.map