"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.writeRunState = writeRunState;
exports.readRunState = readRunState;
exports.getRunStateMtime = getRunStateMtime;
exports.runStateRelativePath = runStateRelativePath;
exports.initialRunState = initialRunState;
exports.patchRunState = patchRunState;
/**
 * Run state sidecar: `<projectFolder>/.ccweb/tracks/<basename>.run-state.json`
 *
 * v-j 起作为 LLM 节点完成判定的唯一信号源，并兼任运行进度的对外可视表达：
 *   - runtime 在节点 active/completed/failed 时同步写入文件
 *   - LLM 节点的 prompt 系统指令要求 LLM 完成时把 nodes[<id>].done=true，
 *     或不能完成时 nodes[<id>].failed=true + reason='...'；
 *   - llm-dispatcher polling 本文件 mtime，读 nodes[currentNodeId] 决定 success/failed
 *
 * 文件保留覆盖写（不在 run 结束时删，方便用户回看上一次结果）。
 */
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
function runStatePath(projectFolder, basename) {
    return path.join(projectFolder, '.ccweb', 'tracks', `${basename}.run-state.json`);
}
function atomicWriteJson(target, value) {
    try {
        fs.mkdirSync(path.dirname(target), { recursive: true });
        const tmp = `${target}.tmp.${process.pid}.${Date.now()}`;
        fs.writeFileSync(tmp, JSON.stringify(value, null, 2), 'utf8');
        fs.renameSync(tmp, target);
        return true;
    }
    catch {
        return false;
    }
}
function writeRunState(projectFolder, basename, state) {
    return atomicWriteJson(runStatePath(projectFolder, basename), state);
}
/** 读取 run-state.json。文件不存在 / parse 失败返 null。 */
function readRunState(projectFolder, basename) {
    const p = runStatePath(projectFolder, basename);
    try {
        if (!fs.existsSync(p))
            return null;
        const raw = fs.readFileSync(p, 'utf8');
        const parsed = JSON.parse(raw);
        if (parsed.version !== 1)
            return null;
        return parsed;
    }
    catch {
        return null;
    }
}
/** statSync mtime — dispatcher polling 用。 */
function getRunStateMtime(projectFolder, basename) {
    try {
        return fs.statSync(runStatePath(projectFolder, basename)).mtimeMs;
    }
    catch {
        return 0;
    }
}
/** 返回 sidecar 文件**相对项目根**的路径，用于 prompt 系统指令告知 LLM。 */
function runStateRelativePath(basename) {
    return `.ccweb/tracks/${basename}.run-state.json`;
}
function initialRunState(runId, basename, nodes) {
    const nodeMap = {};
    for (const n of nodes) {
        nodeMap[n.id] = {
            label: n.label,
            type: n.type,
            status: 'idle',
            iter: 0,
        };
    }
    return {
        version: 1,
        runId,
        basename,
        startedAt: Date.now(),
        finishedAt: null,
        status: 'pending',
        currentNodeId: null,
        nodes: nodeMap,
        error: null,
    };
}
/** Mutate-and-write helper：runtime 在每个状态切换点调一次，承担 read-modify-write 与
 *  原子写。文件可能并发被 LLM 改写（done flag），所以必须 read 最新值再 merge。 */
function patchRunState(projectFolder, basename, patcher) {
    const cur = readRunState(projectFolder, basename);
    if (!cur)
        return null;
    const next = patcher(cur);
    writeRunState(projectFolder, basename, next);
    return next;
}
//# sourceMappingURL=run-state-file.js.map