"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.JobLifecycleStore = void 0;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const AtomicWriter_1 = require("./util/AtomicWriter");
class JobLifecycleStore {
    baseDir;
    jobsDir;
    eventsDir;
    constructor(workspaceId = 'default') {
        this.baseDir = path.join(process.cwd(), '.artifacts', 'workspaces', workspaceId, 'jobs');
        this.jobsDir = path.join(this.baseDir, 'records');
        this.eventsDir = path.join(this.baseDir, 'events');
        fs.mkdirSync(this.jobsDir, { recursive: true });
        fs.mkdirSync(this.eventsDir, { recursive: true });
    }
    enqueue(goal, workspaceId = 'default', serviceId, taskId) {
        const now = new Date().toISOString();
        const jobId = `job_${Date.now()}`;
        const rec = { jobId, workspaceId, serviceId, taskId, goal, status: 'enqueued', createdAt: now, updatedAt: now };
        this.save(rec);
        this.append({ jobId, workspaceId, type: 'enqueued', summary: 'Job enqueued', at: now });
        return rec;
    }
    transition(jobId, workspaceId, status, summary, ownerAgentId, blocker) {
        const rec = this.get(jobId);
        if (!rec)
            return null;
        const next = { ...rec, workspaceId, status, ownerAgentId: ownerAgentId ?? rec.ownerAgentId, blocker: blocker ?? rec.blocker, updatedAt: new Date().toISOString() };
        this.save(next);
        this.append({ jobId, workspaceId, type: status, summary, at: next.updatedAt });
        return next;
    }
    get(jobId) {
        const p = path.join(this.jobsDir, `${jobId}.json`);
        if (!fs.existsSync(p))
            return null;
        return JSON.parse(fs.readFileSync(p, 'utf-8'));
    }
    list(limit = 100) {
        const files = fs.readdirSync(this.jobsDir).filter((f) => f.endsWith('.json')).slice(-limit);
        return files.map((f) => JSON.parse(fs.readFileSync(path.join(this.jobsDir, f), 'utf-8')));
    }
    events(jobId) {
        const p = path.join(this.eventsDir, `${jobId}.jsonl`);
        if (!fs.existsSync(p))
            return [];
        return fs.readFileSync(p, 'utf-8').split('\n').filter(Boolean).map((l) => JSON.parse(l));
    }
    save(rec) {
        (0, AtomicWriter_1.writeJsonAtomic)(path.join(this.jobsDir, `${rec.jobId}.json`), rec);
    }
    append(ev) {
        (0, AtomicWriter_1.appendJsonlAtomic)(path.join(this.eventsDir, `${ev.jobId}.jsonl`), ev);
    }
}
exports.JobLifecycleStore = JobLifecycleStore;
