/**
 * 任务上下文 — 状态转换验证逻辑
 *
 * 从 TaskContextManager.updateStatus 中提取的验证和转换逻辑。
 */
import { evaluateStateGuard } from "../../contracts/enforcement_guard.js";
import { executeStageGate } from "../stage_gate_engine.js";
import { VALID_TRANSITIONS } from "./constants.js";
import { SoloForgeError } from "../../core/errors.js";
/**
 * 验证状态转换的合法性，执行事实前置条件校验和阶段门禁。
 * 返回验证后的上下文（状态已修改但未持久化），或抛出错误。
 */
export function validateAndUpdateStatus(ctx, targetStatus, templatesDir, systemType) {
    if (!VALID_TRANSITIONS[ctx.status].includes(targetStatus)) {
        throw new SoloForgeError(`无效状态转换: ${ctx.status} → ${targetStatus}`, "INVALID_STATUS_TRANSITION", "error", "检查 VALID_TRANSITIONS 常量和任务当前状态");
    }
    // 状态护栏 — 阻断 failed → done
    if (ctx.status === "failed" && targetStatus === "done") {
        const guardFindings = evaluateStateGuard(ctx.status, "completed", "task_context_contract");
        if (guardFindings.length > 0 && guardFindings[0].blocked) {
            throw new Error(`状态护栏阻断: ${guardFindings[0].reason_zh}`);
        }
    }
    // 事实前置条件校验：防止无数据伪推进
    if (ctx.status === "classifying" && targetStatus === "expanding") {
        if (!ctx.classification) {
            throw new Error(`事实缺失: classifying → expanding 需要 classification`);
        }
    }
    if (ctx.status === "expanding" && targetStatus === "executing") {
        if (!ctx.expansion) {
            throw new Error(`事实缺失: expanding → executing 需要 expansion`);
        }
    }
    if (ctx.status === "executing" && targetStatus === "verifying") {
        const hasChangedFiles = ctx.execution && ctx.execution.changed_files.length > 0;
        const hasFailureHistory = ctx.execution && ctx.execution.failure_history.length > 0;
        const hasNoChangeArtifact = ctx.execution?.no_change_artifact === true;
        if (!hasChangedFiles && !hasFailureHistory && !hasNoChangeArtifact) {
            throw new Error(`事实缺失: executing → verifying 需要 execution evidence (changed_files / failure_history / no_change_artifact)`);
        }
    }
    if (ctx.status === "verifying" && (targetStatus === "learning" || targetStatus === "done")) {
        if (!ctx.verification && !ctx.skip_verification_reason) {
            throw new Error(`事实缺失: verifying → ${targetStatus} 需要 verification（或显式 skip_verification_reason）`);
        }
    }
    if (ctx.status === "failed" && targetStatus === "expanding") {
        if (!ctx.classification) {
            throw new Error(`事实缺失: failed → expanding 需要 classification`);
        }
    }
    if (ctx.status === "failed" && targetStatus === "classifying") {
        // 允许无 classification 回到 classifying 重新分类
    }
    if (ctx.status === "retrying" && targetStatus === "executing") {
        if (!ctx.expansion) {
            throw new Error(`事实缺失: retrying → executing 需要 expansion`);
        }
    }
    if (ctx.status === "reworking" && targetStatus === "executing") {
        if (!ctx.expansion) {
            throw new Error(`事实缺失: reworking → executing 需要 expansion`);
        }
    }
    // 阶段门禁强制执行
    if (targetStatus === "executing" && templatesDir) {
        const artifacts = {
            classification: ctx.classification,
            expansion: ctx.expansion,
        };
        const gateResult = executeStageGate("编码与单元测试", artifacts, templatesDir, systemType);
        if (gateResult && !gateResult.passed) {
            throw new Error(`阶段门禁未通过: ${gateResult.blocking_reason_zh ?? gateResult.gate_id}`);
        }
    }
    ctx.status = targetStatus;
    return ctx;
}
//# sourceMappingURL=status_transitions.js.map