"use strict";
/**
 * CapabilityPackState — lifecycle store for Capability Packs.
 *
 * Story 1.4 — OpenLife v1.3 Agent OS Integration.
 *
 * Owns the `draft → tested → active → deprecated` state machine and the
 * append-only audit ledger at `.openlife/capability-lifecycle.jsonl`.
 *
 * Promotion rules:
 *   draft → tested     : requires `validatedBy` (test/checklist name)
 *   tested → active    : requires explicit `actor` (canonization)
 *   active → deprecated: anytime
 *   anyState → deprecated: anytime (for emergency disabling)
 *
 * Never auto-promotes — every transition is an explicit call with an actor.
 *
 * Uses AtomicWriter for both the per-pack status file and the JSONL ledger,
 * surviving kill -9 (same contract as MissionCheckpointStore, Story 6.2).
 */
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.CapabilityPackStateStore = void 0;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const AtomicWriter_1 = require("../util/AtomicWriter");
/** Valid transition map. Source → set of allowed destinations. */
const ALLOWED_TRANSITIONS = {
    draft: new Set(['tested', 'deprecated']),
    tested: new Set(['active', 'draft', 'deprecated']),
    active: new Set(['deprecated']),
    deprecated: new Set([]),
};
class CapabilityPackStateStore {
    stateDir;
    ledgerFile;
    constructor(opts = {}) {
        this.stateDir = opts.stateDir
            || process.env.OPENLIFE_STATE_DIR
            || path.join(process.cwd(), '.openlife');
        this.ledgerFile = path.join(this.stateDir, 'capability-lifecycle.jsonl');
    }
    statusFile(packId) {
        const safe = packId.replace(/[^a-zA-Z0-9._-]/g, '_');
        return path.join(this.stateDir, 'capabilities', `${safe}.json`);
    }
    read(packId) {
        const f = this.statusFile(packId);
        if (!fs.existsSync(f))
            return null;
        try {
            return JSON.parse(fs.readFileSync(f, 'utf-8'));
        }
        catch {
            return null;
        }
    }
    /**
     * Initialize a pack at status `draft`. Idempotent — if a status file
     * already exists, returns it unchanged.
     */
    init(packId, actor) {
        const existing = this.read(packId);
        if (existing)
            return existing;
        const now = new Date().toISOString();
        const initial = {
            packId,
            status: 'draft',
            updatedAt: now,
            updatedBy: actor,
            history: [],
        };
        (0, AtomicWriter_1.writeJsonAtomic)(this.statusFile(packId), initial);
        (0, AtomicWriter_1.appendJsonlAtomic)(this.ledgerFile, {
            packId, from: '<none>', to: 'draft', actor, at: now, event: 'init',
        });
        return initial;
    }
    promote(opts) {
        const { packId, to, actor, reason, validatedBy } = opts;
        const current = this.read(packId);
        if (!current)
            return { ok: false, error: 'pack_not_initialized' };
        const from = current.status;
        if (!ALLOWED_TRANSITIONS[from].has(to)) {
            return { ok: false, error: `transition_not_allowed:${from}->${to}` };
        }
        // Promotion to `tested` requires evidence — refuse silent promotion.
        if (to === 'tested' && !validatedBy) {
            return { ok: false, error: 'tested_promotion_requires_validated_by' };
        }
        // Promotion to `active` requires an actor distinct from auto-systems.
        if (to === 'active' && (!actor || actor === 'system' || actor === 'auto')) {
            return { ok: false, error: 'active_promotion_requires_human_actor' };
        }
        const now = new Date().toISOString();
        const transition = {
            packId, from, to, actor, reason, validatedBy, at: now,
        };
        const next = {
            packId,
            status: to,
            updatedAt: now,
            updatedBy: actor,
            history: [...current.history, transition],
        };
        (0, AtomicWriter_1.writeJsonAtomic)(this.statusFile(packId), next);
        (0, AtomicWriter_1.appendJsonlAtomic)(this.ledgerFile, { ...transition, event: 'transition' });
        return { ok: true, status: next };
    }
    /** List all known packs and their current lifecycle status. */
    list() {
        const dir = path.join(this.stateDir, 'capabilities');
        if (!fs.existsSync(dir))
            return [];
        const out = [];
        for (const f of fs.readdirSync(dir)) {
            if (!f.endsWith('.json'))
                continue;
            try {
                out.push(JSON.parse(fs.readFileSync(path.join(dir, f), 'utf-8')));
            }
            catch {
                // skip corrupted entries
            }
        }
        return out;
    }
}
exports.CapabilityPackStateStore = CapabilityPackStateStore;
