"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.MissionCheckpointStore = exports.MissionStateStore = void 0;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const AtomicWriter_1 = require("./util/AtomicWriter");
class MissionStateStore {
    baseDir;
    constructor() {
        this.baseDir = path.join(process.cwd(), '.artifacts', 'missions');
        if (!fs.existsSync(this.baseDir))
            fs.mkdirSync(this.baseDir, { recursive: true });
    }
    persist(state) {
        const filePath = path.join(this.baseDir, `${state.taskId}.json`);
        (0, AtomicWriter_1.writeJsonAtomic)(filePath, state);
        if (state.consequenceThoughtTrace) {
            const thoughtTracePath = path.join(this.baseDir, `${state.taskId}.thought-trace.json`);
            (0, AtomicWriter_1.writeJsonAtomic)(thoughtTracePath, state.consequenceThoughtTrace);
        }
        return filePath;
    }
}
exports.MissionStateStore = MissionStateStore;
/**
 * Checkpoint persistence backed by atomic writes. Each missionId has at most
 * one active checkpoint file; saveCheckpoint replaces the previous one.
 *
 * Storage: `<stateDir>/checkpoints/<sanitizedMissionId>.json` where
 * `<stateDir>` = `OPENLIFE_STATE_DIR` env var if set, else `.openlife/`
 * relative to the constructor root (or process.cwd()).
 *
 * Why a separate store and not extending MissionStateStore? Checkpoints are
 * autonomy-layer artifacts (lives in `.openlife/`, survives across project
 * workspaces) while MissionStateStore is workspace-scoped under
 * `.artifacts/missions/`. The split matches the v1.2 layering: `.openlife/`
 * is the autonomous runtime layer, `.artifacts/` is the execution-results
 * layer.
 */
class MissionCheckpointStore {
    baseDir;
    constructor(root = process.cwd()) {
        const stateDir = process.env.OPENLIFE_STATE_DIR || path.join(root, '.openlife');
        this.baseDir = path.join(stateDir, 'checkpoints');
    }
    /**
     * Save (or overwrite) the latest checkpoint for `missionId`. The write is
     * atomic — if the process crashes mid-save the previous checkpoint stays
     * intact.
     */
    saveCheckpoint(missionId, step, state) {
        const ckpt = {
            missionId,
            step,
            state,
            savedAt: new Date().toISOString(),
        };
        (0, AtomicWriter_1.writeJsonAtomic)(this.checkpointPath(missionId), ckpt);
    }
    /**
     * Read the latest checkpoint for `missionId`. Returns null if no checkpoint
     * exists or the file is corrupted (in which case the caller should treat
     * the mission as un-resumable and start fresh).
     */
    getLatestCheckpoint(missionId) {
        const filePath = this.checkpointPath(missionId);
        if (!fs.existsSync(filePath))
            return null;
        try {
            const raw = JSON.parse(fs.readFileSync(filePath, 'utf-8'));
            if (raw && typeof raw === 'object' && typeof raw.step === 'string') {
                return raw;
            }
            return null;
        }
        catch {
            return null;
        }
    }
    /**
     * Read the latest checkpoint and signal intent to resume. Currently
     * identical to getLatestCheckpoint; the separate method exists so that
     * future audit/event hooks (e.g. emit `mission.resume.started` to the
     * security event log) can be attached here without changing call sites.
     */
    resumeFromCheckpoint(missionId) {
        return this.getLatestCheckpoint(missionId);
    }
    /**
     * List all missionIds that currently have a saved checkpoint. Useful for
     * recovery sweeps on daemon boot (find pending resumes after a crash).
     */
    list() {
        if (!fs.existsSync(this.baseDir))
            return [];
        return fs.readdirSync(this.baseDir)
            .filter((f) => f.endsWith('.json'))
            .map((f) => f.replace(/\.json$/, ''));
    }
    /**
     * Remove the checkpoint for `missionId`. Call after a successful resume
     * has consumed the checkpoint, or after the mission has reached a
     * terminal state.
     */
    clear(missionId) {
        const filePath = this.checkpointPath(missionId);
        if (fs.existsSync(filePath)) {
            fs.unlinkSync(filePath);
        }
    }
    /** Exposed for tests so they can assert the resolved storage location. */
    _baseDir() {
        return this.baseDir;
    }
    checkpointPath(missionId) {
        return path.join(this.baseDir, `${this.sanitize(missionId)}.json`);
    }
    sanitize(missionId) {
        return missionId.replace(/[^a-zA-Z0-9._-]/g, '_');
    }
}
exports.MissionCheckpointStore = MissionCheckpointStore;
