"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.EnterpriseDoctor = exports.LearningLoopStore = exports.MissionEvaluationStore = exports.PilotStore = exports.PluginManifestStore = exports.InstitutionalContextStore = void 0;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const AtomicWriter_1 = require("./util/AtomicWriter");
const ensureDir = (p) => fs.mkdirSync(p, { recursive: true });
const stateRoot = (root) => process.env.OPENLIFE_STATE_DIR || path.join(root, '.openlife');
const now = () => new Date().toISOString();
const readJson = (p, fallback) => {
    if (!fs.existsSync(p))
        return fallback;
    try {
        return JSON.parse(fs.readFileSync(p, 'utf-8'));
    }
    catch {
        return fallback;
    }
};
const writeJson = (p, data) => { (0, AtomicWriter_1.writeJsonAtomic)(p, data); };
const validId = (id) => /^[a-z0-9][a-z0-9._-]{1,80}$/i.test(id);
const validRisk = (risk) => ['low', 'medium', 'high'].includes(String(risk).toLowerCase());
const err = (error, detail) => ({ ok: false, error, ...(detail ? { detail } : {}) });
class InstitutionalContextStore {
    root;
    constructor(root = process.cwd()) {
        this.root = root;
    }
    stateDir() { return stateRoot(this.root); }
    dir() { return path.join(this.stateDir(), 'institutional-context'); }
    requiredFiles() {
        return [
            'brand.md', 'governance.md', 'operating-model.md', 'quality-bar.md',
            'company-vocabulary.md', 'decision-principles.md', 'approved-patterns.md', 'forbidden-patterns.md'
        ];
    }
    init(name = 'OpenLife Institutional Context') {
        ensureDir(this.dir());
        const templates = {
            'brand.md': `# Brand\n\nName: ${name}\n\nVoice, positioning, visual identity, and examples live here.\n`,
            'governance.md': '# Governance\n\n- Read-only before write.\n- Human approval for destructive/public actions.\n- Audit every mission.\n',
            'operating-model.md': '# Operating Model\n\nServices are continuous operational truth; missions/tasks are execution units.\n',
            'quality-bar.md': '# Quality Bar\n\nOutputs must be actionable, grounded, auditable, and ready for review.\n',
            'company-vocabulary.md': '# Company Vocabulary\n\nCanonical terms, acronyms, and forbidden wording.\n',
            'decision-principles.md': '# Decision Principles\n\nPrefer measurable pilots, reversible steps, and explicit tradeoffs.\n',
            'approved-patterns.md': '# Approved Patterns\n\nReusable patterns that passed review.\n',
            'forbidden-patterns.md': '# Forbidden Patterns\n\nNo deceptive mocks. No runtime source-of-truth from Obsidian. No destructive action without approval.\n'
        };
        const files = this.requiredFiles().map(f => {
            const p = path.join(this.dir(), f);
            if (!fs.existsSync(p))
                (0, AtomicWriter_1.writeStringAtomic)(p, templates[f] || `# ${f}\n`);
            return p;
        });
        writeJson(path.join(this.dir(), 'manifest.json'), { name, version: 1, updatedAt: now(), files: this.requiredFiles() });
        return { ok: true, type: 'institutional-context.init', stateDir: this.stateDir(), dir: this.dir(), files };
    }
    doctor() {
        const required = this.requiredFiles();
        const present = required.filter(f => fs.existsSync(path.join(this.dir(), f)));
        return { ok: present.length === required.length, type: 'institutional-context.doctor', stateDir: this.stateDir(), dir: this.dir(), summary: { requiredPresent: present.length, requiredTotal: required.length, missing: required.filter(f => !present.includes(f)) } };
    }
    summary() {
        const manifest = readJson(path.join(this.dir(), 'manifest.json'), { name: null, version: 0, files: [] });
        return { ok: true, type: 'institutional-context.summary', stateDir: this.stateDir(), context: { ...manifest, requiredFiles: this.requiredFiles(), doctor: this.doctor().summary } };
    }
}
exports.InstitutionalContextStore = InstitutionalContextStore;
class PluginManifestStore {
    root;
    constructor(root = process.cwd()) {
        this.root = root;
    }
    stateDir() { return stateRoot(this.root); }
    dir() { return path.join(this.stateDir(), 'plugins'); }
    pathFor(id) { return path.join(this.dir(), `${id}.json`); }
    riskTemplate(risk) {
        const r = (risk || 'low').toLowerCase();
        if (r === 'high')
            return { riskLevel: 'high', permissionScope: ['read'], deniedCapabilities: ['delete', 'rename', 'network:write', 'public:write'] };
        if (r === 'medium')
            return { riskLevel: 'medium', permissionScope: ['read', 'write', 'network:read'], deniedCapabilities: ['delete', 'network:write', 'public:write'] };
        return { riskLevel: 'low', permissionScope: ['read', 'write', 'network:read'], deniedCapabilities: ['delete'] };
    }
    install(id, capabilities, risk = 'low') {
        if (!validId(id))
            return err('invalid_plugin_id', { expected: '^[a-z0-9][a-z0-9._-]{1,80}$' });
        if (!validRisk(risk))
            return err('invalid_risk_level', { allowed: ['low', 'medium', 'high'] });
        ensureDir(this.dir());
        const existing = readJson(this.pathFor(id), null);
        const createdAt = existing?.createdAt || now();
        const plugin = { id, name: id.replace(/[-_]/g, ' '), capabilities: capabilities.length ? Array.from(new Set(capabilities)) : ['general.execution'], governance: this.riskTemplate(risk), source: 'openlife-cli', status: 'installed', version: (existing?.version || 0) + 1, createdAt, updatedAt: now() };
        writeJson(this.pathFor(id), plugin);
        return { ok: true, type: 'plugin.install', stateDir: this.stateDir(), plugin };
    }
    list() {
        ensureDir(this.dir());
        const plugins = fs.readdirSync(this.dir()).filter(f => f.endsWith('.json')).map(f => readJson(path.join(this.dir(), f), null)).filter(Boolean);
        return { ok: true, type: 'plugin.list', stateDir: this.stateDir(), plugins };
    }
    inspect(id) {
        if (!validId(id))
            return err('invalid_plugin_id', { id });
        const plugin = readJson(this.pathFor(id), null);
        return plugin ? { ok: true, type: 'plugin.inspect', plugin } : err('plugin_not_found', { id });
    }
    setStatus(id, status) {
        if (!validId(id))
            return err('invalid_plugin_id', { id });
        const plugin = readJson(this.pathFor(id), null);
        if (!plugin)
            return err('plugin_not_found', { id });
        plugin.status = status;
        plugin.updatedAt = now();
        plugin.version += 1;
        writeJson(this.pathFor(id), plugin);
        return { ok: true, type: `plugin.${status === 'disabled' ? 'disable' : 'enable'}`, plugin };
    }
}
exports.PluginManifestStore = PluginManifestStore;
class PilotStore {
    root;
    constructor(root = process.cwd()) {
        this.root = root;
    }
    stateDir() { return stateRoot(this.root); }
    dir() { return path.join(this.stateDir(), 'pilots'); }
    pathFor(id) { return path.join(this.dir(), `${id}.json`); }
    create(id, metric, service = 'unassigned') {
        if (!validId(id))
            return err('invalid_pilot_id');
        const existing = readJson(this.pathFor(id), null);
        const pilot = { id, status: 'active', service, hypothesis: `Pilot ${id} should produce measurable operational value.`, metrics: metric ? [metric] : [], successCriteria: metric ? [metric] : ['define measurable success metric'], workflows: existing?.workflows || [], outcome: existing?.outcome || null, createdAt: existing?.createdAt || now(), updatedAt: now() };
        writeJson(this.pathFor(id), pilot);
        return { ok: true, type: 'pilot.create', stateDir: this.stateDir(), pilot };
    }
    list() {
        ensureDir(this.dir());
        const pilots = fs.readdirSync(this.dir()).filter(f => f.endsWith('.json')).map(f => readJson(path.join(this.dir(), f), null)).filter((p) => !!p);
        return { ok: true, type: 'pilot.list', stateDir: this.stateDir(), pilots };
    }
    report(id) {
        if (!validId(id))
            return err('invalid_pilot_id', { id });
        const pilot = readJson(this.pathFor(id), null);
        if (!pilot)
            return err('pilot_not_found', { id });
        const report = { id, status: pilot.status, service: pilot.service, successCriteria: pilot.successCriteria || pilot.metrics || [], recommendation: pilot.status === 'completed' ? 'promote-learning-or-scale' : 'continue-with-governed-experiment', generatedAt: now() };
        return { ok: true, type: 'pilot.report', pilot, report };
    }
    complete(id, outcome = 'completed') {
        if (!validId(id))
            return err('invalid_pilot_id', { id });
        const pilot = readJson(this.pathFor(id), null);
        if (!pilot)
            return err('pilot_not_found', { id });
        pilot.status = 'completed';
        pilot.outcome = outcome;
        pilot.updatedAt = now();
        writeJson(this.pathFor(id), pilot);
        return { ok: true, type: 'pilot.complete', pilot };
    }
}
exports.PilotStore = PilotStore;
class MissionEvaluationStore {
    root;
    constructor(root = process.cwd()) {
        this.root = root;
    }
    stateDir() { return stateRoot(this.root); }
    dir() { return path.join(this.stateDir(), 'evaluations'); }
    pathFor(mission) { return path.join(this.dir(), `${mission}.json`); }
    judge(mission, criteriaCsv) {
        if (!validId(mission))
            return err('invalid_mission_id');
        const criteria = criteriaCsv.split(',').map(s => s.trim()).filter(Boolean);
        const score = Math.max(0, Math.min(100, 70 + Math.min(criteria.length, 5) * 4));
        const evaluation = { mission, criteria, score, verdict: score >= 75 ? 'ready_for_review' : 'needs_iteration', risks: ['verify evidence before external delivery'], createdAt: now(), path: this.pathFor(mission) };
        writeJson(this.pathFor(mission), evaluation);
        return { ok: true, type: 'eval.judge', stateDir: this.stateDir(), evaluation };
    }
    report(mission) {
        if (!validId(mission))
            return err('invalid_mission_id', { mission });
        const evaluation = readJson(this.pathFor(mission), null);
        return evaluation ? { ok: true, type: 'eval.report', evaluation } : err('evaluation_not_found', { mission });
    }
    list() {
        ensureDir(this.dir());
        return fs.readdirSync(this.dir())
            .filter(f => f.endsWith('.json'))
            .map(f => readJson(path.join(this.dir(), f), null))
            .filter((e) => !!e);
    }
}
exports.MissionEvaluationStore = MissionEvaluationStore;
class LearningLoopStore {
    root;
    constructor(root = process.cwd()) {
        this.root = root;
    }
    stateDir() { return stateRoot(this.root); }
    dir() { return path.join(this.stateDir(), 'learning'); }
    pathFor(mission) { return path.join(this.dir(), `${mission}.json`); }
    fromLastRun(mission, feedback) {
        if (!validId(mission))
            return err('invalid_mission_id');
        const suggestions = [
            { type: 'skill', action: 'create_or_patch', title: `Reusable workflow from ${mission}`, rationale: feedback || 'Promote repeated operational pattern.' },
            { type: 'context', action: 'update', title: 'Institutional context update', rationale: 'Capture human correction and decision principles.' },
            { type: 'evaluation', action: 'add_criteria', title: 'Quality criterion', rationale: 'Convert review into future scoring.' }
        ];
        const record = { mission, feedback, suggestions, createdAt: now() };
        writeJson(this.pathFor(mission), record);
        return { ok: true, type: 'learn.from-last-run', stateDir: this.stateDir(), recordPath: this.pathFor(mission), suggestions };
    }
    list() {
        ensureDir(this.dir());
        const records = fs.readdirSync(this.dir())
            .filter(f => f.endsWith('.json'))
            .map(f => readJson(path.join(this.dir(), f), null))
            .filter((r) => !!r);
        return { ok: true, type: 'learn.list', stateDir: this.stateDir(), records };
    }
}
exports.LearningLoopStore = LearningLoopStore;
class EnterpriseDoctor {
    root;
    constructor(root = process.cwd()) {
        this.root = root;
    }
    run() {
        const context = new InstitutionalContextStore(this.root).doctor();
        const plugins = new PluginManifestStore(this.root).list().plugins;
        const pilots = new PilotStore(this.root).list().pilots;
        const evals = new MissionEvaluationStore(this.root).list();
        const learning = new LearningLoopStore(this.root).list().records;
        const checks = { context, plugins: { ok: true, count: plugins.length }, pilots: { ok: true, count: pilots.length }, evaluations: { ok: true, count: evals.length }, learning: { ok: true, count: learning.length } };
        return { ok: context.ok && plugins.length >= 0 && pilots.length >= 0, type: 'enterprise.doctor', stateDir: stateRoot(this.root), checks };
    }
}
exports.EnterpriseDoctor = EnterpriseDoctor;
