"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.ServiceStateStore = void 0;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const AtomicWriter_1 = require("./util/AtomicWriter");
class ServiceStateStore {
    workspaceId;
    baseDir;
    eventsDir;
    missionsDir;
    constructor(workspaceId = 'default') {
        this.workspaceId = workspaceId;
        this.baseDir = path.join(process.cwd(), '.artifacts', 'workspaces', workspaceId, 'services');
        this.eventsDir = path.join(this.baseDir, 'events');
        this.missionsDir = path.join(process.cwd(), '.artifacts', 'missions');
        fs.mkdirSync(this.baseDir, { recursive: true });
        fs.mkdirSync(this.eventsDir, { recursive: true });
    }
    list(limit = 100) {
        return fs.readdirSync(this.baseDir)
            .filter((f) => f.endsWith('.json'))
            .slice(-limit)
            .map((f) => JSON.parse(fs.readFileSync(path.join(this.baseDir, f), 'utf-8')));
    }
    upsertFromMission(state) {
        const trace = state.consequenceThoughtTrace;
        if (!trace)
            return null;
        const serviceId = trace.serviceContext.serviceId;
        const now = new Date().toISOString();
        const filePath = path.join(this.baseDir, `${serviceId}.json`);
        const existing = this.load(filePath);
        const missionIds = Array.from(new Set([...(existing?.missionIds || []), state.taskId]));
        const total = missionIds.length;
        const completed = this.estimateCompletedCount(missionIds);
        const blocked = this.estimateBlockedCount(missionIds);
        const completionRate = total > 0 ? Number((completed / total).toFixed(4)) : undefined;
        const governanceBlockRate = total > 0 ? Number((blocked / total).toFixed(4)) : undefined;
        const fallbackUsed = state.attempts.some((a) => a.role === 'executor' && a.status === 'partial');
        const budget = existing?.budget || { hardStop: false };
        const hardStopTriggered = Boolean(budget.hardStop && budget.monthlyLimitCents && budget.spentCents && budget.spentCents >= budget.monthlyLimitCents);
        const next = {
            workspaceId: this.workspaceId,
            serviceId,
            objective: trace.serviceContext.serviceObjective,
            status: hardStopTriggered ? 'paused' : (state.status === 'failed' ? 'degraded' : 'active'),
            riskProfile: trace.governanceRisk,
            slo: existing?.slo || {},
            kpis: { ...(existing?.kpis || {}), completionRate, governanceBlockRate, fallbackRate: fallbackUsed ? 1 : (existing?.kpis?.fallbackRate ?? 0) },
            budget,
            missionIds,
            latestThoughtTracePath: path.join(process.cwd(), '.artifacts', 'missions', `${state.taskId}.thought-trace.json`),
            createdAt: existing?.createdAt || now,
            updatedAt: now
        };
        (0, AtomicWriter_1.writeJsonAtomic)(filePath, next);
        this.appendEvent(this.buildEvent(existing, next, state));
        if (hardStopTriggered)
            this.appendEvent({ type: 'budget_hard_stop', workspaceId: this.workspaceId, serviceId, taskId: state.taskId, summary: `Budget hard-stop acionado para ${serviceId}.`, at: now });
        return filePath;
    }
    buildEvent(previous, next, state) {
        const base = { workspaceId: this.workspaceId, serviceId: next.serviceId, taskId: state.taskId, at: new Date().toISOString() };
        if (!previous)
            return { type: 'mission_attached', ...base, summary: `Serviço criado e missão anexada (${state.taskId}).` };
        const blocked = state.governanceEvents.some((event) => event.type === 'destructive_action_blocked' || event.type === 'prompt_injection_detected');
        if (blocked)
            return { type: 'governance_blocked', ...base, summary: `Missão ${state.taskId} bloqueada por governança.` };
        if (previous.status !== 'degraded' && next.status === 'degraded')
            return { type: 'service_degraded', ...base, summary: `Serviço degradado após missão ${state.taskId}.` };
        if (previous.status === 'degraded' && next.status === 'active')
            return { type: 'service_recovered', ...base, summary: `Serviço recuperado com missão ${state.taskId}.` };
        return { type: 'mission_attached', ...base, summary: `Missão anexada ao serviço (${state.taskId}).` };
    }
    getById(serviceId) { return this.load(path.join(this.baseDir, `${serviceId}.json`)); }
    setStatus(serviceId, status, reason, taskId = `manual_${Date.now()}`) {
        const current = this.getById(serviceId);
        if (!current)
            return null;
        const next = { ...current, status, updatedAt: new Date().toISOString() };
        (0, AtomicWriter_1.writeJsonAtomic)(path.join(this.baseDir, `${serviceId}.json`), next);
        this.appendEvent({ type: status === 'paused' ? 'service_paused' : status === 'active' ? 'service_resumed' : 'mission_attached', workspaceId: this.workspaceId, serviceId, taskId, summary: reason, at: new Date().toISOString() });
        return next;
    }
    listEvents(serviceId, limit = 50) {
        const eventPath = path.join(this.eventsDir, `${serviceId}.jsonl`);
        if (!fs.existsSync(eventPath))
            return [];
        return fs.readFileSync(eventPath, 'utf-8').trim().split('\n').filter(Boolean).slice(-limit).map((line) => JSON.parse(line));
    }
    /**
     * Promote a task into a service.
     *
     * v1.3 (Story 2.4) — explicit-only contract:
     *   - `actor` is REQUIRED and must not be 'system', 'auto', or ''.
     *     Refuses silent promotion by background processes.
     *   - `consentScope` is REQUIRED and must equal 'task_promotion'.
     *     This pairs with GovernanceConsentStore so promotions can be
     *     gated by a per-user consent record in the future (the consent
     *     itself is the caller's responsibility — this method only
     *     refuses obvious bypasses).
     *   - Emits `task_promoted` event with actor + consentScope context.
     *
     * Returns the new ServiceState on success; throws on policy violation.
     */
    promoteTaskToService(state, serviceId, objective, opts = {}) {
        const actor = (opts.actor || '').trim();
        if (!actor || actor === 'system' || actor === 'auto') {
            const err = new Error(`promoteTaskToService refused: actor must be a human/operator id (got '${actor || '<empty>'}'); silent promotion is forbidden by v1.3 contract`);
            err.code = 'task_promotion_requires_human_actor';
            throw err;
        }
        if (opts.consentScope !== 'task_promotion') {
            const err = new Error(`promoteTaskToService refused: consentScope must equal 'task_promotion' (got '${opts.consentScope ?? '<missing>'}')`);
            err.code = 'task_promotion_requires_consent_scope';
            throw err;
        }
        const now = new Date().toISOString();
        const existing = this.getById(serviceId);
        const next = { workspaceId: this.workspaceId, serviceId, objective: objective ?? state.goal, status: existing?.status ?? 'active', riskProfile: existing?.riskProfile ?? 'medium', slo: existing?.slo ?? {}, kpis: existing?.kpis ?? {}, budget: existing?.budget ?? { hardStop: false }, missionIds: Array.from(new Set([...(existing?.missionIds ?? []), state.taskId])), latestThoughtTracePath: state.consequenceThoughtTrace ? path.join(process.cwd(), '.artifacts', 'missions', `${state.taskId}.thought-trace.json`) : existing?.latestThoughtTracePath, createdAt: existing?.createdAt ?? now, updatedAt: now };
        (0, AtomicWriter_1.writeJsonAtomic)(path.join(this.baseDir, `${serviceId}.json`), next);
        this.appendEvent({
            type: 'task_promoted',
            workspaceId: this.workspaceId,
            serviceId,
            taskId: state.taskId,
            summary: `Task ${state.taskId} promoted to service by ${actor}${opts.reason ? ': ' + opts.reason : ''}.`,
            at: now,
        });
        return next;
    }
    appendEvent(event) { (0, AtomicWriter_1.appendJsonlAtomic)(path.join(this.eventsDir, `${event.serviceId}.jsonl`), event); }
    load(filePath) { if (!fs.existsSync(filePath))
        return null; try {
        return JSON.parse(fs.readFileSync(filePath, 'utf-8'));
    }
    catch {
        return null;
    } }
    estimateCompletedCount(missionIds) { let c = 0; for (const id of missionIds) {
        const p = path.join(this.missionsDir, `${id}.json`);
        if (!fs.existsSync(p))
            continue;
        try {
            if (JSON.parse(fs.readFileSync(p, 'utf-8'))?.status === 'completed')
                c += 1;
        }
        catch { }
    } return c; }
    estimateBlockedCount(missionIds) { let c = 0; for (const id of missionIds) {
        const p = path.join(this.missionsDir, `${id}.json`);
        if (!fs.existsSync(p))
            continue;
        try {
            if (JSON.parse(fs.readFileSync(p, 'utf-8'))?.status === 'failed')
                c += 1;
        }
        catch { }
    } return c; }
}
exports.ServiceStateStore = ServiceStateStore;
