"use strict";
/**
 * GovernanceScopeLedger — Story 14.2 (v1.5)
 *
 * Tamper-evident append-only ledger of every GovernanceDecision.
 *
 * v1.3 wrote a single consent record at decision time. v1.5 promotes this
 * to a SHA-chained JSONL ledger so any post-hoc tampering with an existing
 * entry breaks the chain and is detectable by `verify()`.
 *
 * File: `.openlife/governance-ledger.jsonl` (override via OPENLIFE_STATE_DIR).
 *
 * Chain rules:
 *   • First entry has prevHash = 'GENESIS'.
 *   • Each entry's entryHash = SHA-256( prevHash || JSON.stringify(payload) ).
 *   • verify() walks the file and reports the first index where the chain
 *     breaks. An empty file is considered valid (no entries to verify).
 *
 * The hook into GovernanceLayer.evaluate() is best-effort: a write failure
 * never blocks the decision returned to the caller.
 */
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.GovernanceScopeLedger = void 0;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const crypto = __importStar(require("crypto"));
class GovernanceScopeLedger {
    file;
    constructor(stateDir) {
        const root = stateDir
            || process.env.OPENLIFE_STATE_DIR
            || path.join(process.cwd(), '.openlife');
        fs.mkdirSync(root, { recursive: true });
        this.file = path.join(root, 'governance-ledger.jsonl');
    }
    path() {
        return this.file;
    }
    append(goal, project, decision) {
        const prevHash = this.tailHash();
        const index = this.size();
        const goalHash = sha256(goal);
        const payload = { index, ts: new Date().toISOString(), project, goalHash, decision };
        const entryHash = sha256(prevHash + JSON.stringify(payload));
        const entry = { ...payload, prevHash, entryHash };
        fs.appendFileSync(this.file, JSON.stringify(entry) + '\n', 'utf-8');
        return entry;
    }
    read() {
        if (!fs.existsSync(this.file))
            return [];
        return fs.readFileSync(this.file, 'utf-8')
            .split('\n')
            .filter((l) => l.trim().length > 0)
            .map((l) => {
            try {
                return JSON.parse(l);
            }
            catch {
                return null;
            }
        })
            .filter((e) => e !== null);
    }
    /** Walk the chain. Returns the first broken index when tampering is detected. */
    verify() {
        const entries = this.read();
        if (entries.length === 0)
            return { ok: true, entries: 0 };
        let prev = 'GENESIS';
        for (let i = 0; i < entries.length; i++) {
            const e = entries[i];
            if (e.prevHash !== prev) {
                return { ok: false, entries: entries.length, brokenAt: i, reason: 'prevHash_mismatch' };
            }
            const { index, ts, project, goalHash, decision } = e;
            const expectedHash = sha256(prev + JSON.stringify({ index, ts, project, goalHash, decision }));
            if (e.entryHash !== expectedHash) {
                return { ok: false, entries: entries.length, brokenAt: i, reason: 'entryHash_mismatch' };
            }
            if (e.index !== i) {
                return { ok: false, entries: entries.length, brokenAt: i, reason: 'index_mismatch' };
            }
            prev = e.entryHash;
        }
        return { ok: true, entries: entries.length };
    }
    tailHash() {
        const entries = this.read();
        return entries.length === 0 ? 'GENESIS' : entries[entries.length - 1].entryHash;
    }
    size() {
        if (!fs.existsSync(this.file))
            return 0;
        return this.read().length;
    }
}
exports.GovernanceScopeLedger = GovernanceScopeLedger;
function sha256(input) {
    return crypto.createHash('sha256').update(input).digest('hex');
}
