/**
 * 任务上下文 — 高级 setter 方法（产物/修复/返工/证据等）
 *
 * 通过 applySetterMethods 将这些方法混入 TaskContextManager 实例。
 * 这样可以将大型类拆分为多个文件，同时保持单一公共 API。
 */
import { validateTransition } from "../../contracts/artifact_contract_registry.js";
import { MAX_REWORK } from "./constants.js";
import { computePhaseDirective } from "./phase_directive.js";
export function createSetterMethods(load, save) {
    return {
        async setPlanning(taskId, result) {
            const ctx = await load(taskId);
            if (!ctx)
                return null;
            ctx.planning = result;
            await save(ctx);
            return ctx;
        },
        async setCodeReview(taskId, result) {
            const ctx = await load(taskId);
            if (!ctx)
                return null;
            ctx.code_review = result;
            ctx.phase_directive = computePhaseDirective(ctx);
            await save(ctx);
            return ctx;
        },
        async setDelivery(taskId, result) {
            const ctx = await load(taskId);
            if (!ctx)
                return null;
            ctx.delivery = result;
            await save(ctx);
            return ctx;
        },
        async setToolTrace(taskId, trace, violations) {
            const ctx = await load(taskId);
            if (!ctx)
                return null;
            ctx.last_tool_trace = trace;
            if (violations && violations.length > 0) {
                ctx.invocation_violations = violations;
            }
            await save(ctx);
            return ctx;
        },
        async setPlanProposalGate(taskId, gate, existingCtx) {
            const ctx = existingCtx ?? await load(taskId);
            if (!ctx)
                return null;
            ctx.plan_proposal_gate = gate;
            await save(ctx);
            return ctx;
        },
        async setPlanProposalEvidence(taskId, evidence) {
            const ctx = await load(taskId);
            if (!ctx)
                return null;
            ctx.plan_proposal_evidence = evidence;
            await save(ctx);
            return ctx;
        },
        checkPlanGateBeforeWrite(ctx) {
            const gate = ctx.plan_proposal_gate;
            if (!gate) {
                return { allowed: false, reason_zh: "执行前缺少 Plan Proposal Gate 评估结果" };
            }
            if (!gate.passed) {
                return { allowed: false, reason_zh: `Plan Gate 未通过: ${gate.reason_zh}` };
            }
            if (gate.blocked_actions.length > 0) {
                return { allowed: false, reason_zh: `以下动作被 Plan Gate 阻断: ${gate.blocked_actions.join(", ")}` };
            }
            return { allowed: true, reason_zh: "Plan Gate 通过" };
        },
        async setArtifact(taskId, artifact, existingCtx) {
            const ctx = existingCtx ?? await load(taskId);
            if (!ctx)
                return null;
            ctx.artifact_output = artifact;
            await save(ctx);
            return ctx;
        },
        async updateArtifactStatus(taskId, params) {
            const p = typeof params === "string"
                ? { status: params }
                : params;
            const ctx = await load(taskId);
            if (!ctx || !ctx.artifact_output)
                return null;
            const artifact = ctx.artifact_output;
            const findings = validateTransition(artifact, p.status, p.hasVerification ?? false, p.hasAcceptance ?? false);
            const hardFails = findings.filter(f => f.severity === "hard_fail");
            if (hardFails.length > 0) {
                const err = new Error(`updateArtifactStatus blocked: ${hardFails.map(f => f.message).join("; ")}`);
                err.findings = findings;
                throw err;
            }
            artifact.status = p.status;
            if (p.evidenceRef) {
                artifact.evidence_refs = [...(artifact.evidence_refs ?? []), p.evidenceRef];
            }
            await save(ctx);
            return ctx;
        },
        async updateRepairLoop(taskId, failurePhase, autoRepairable, escalationReason) {
            const ctx = await load(taskId);
            if (!ctx || !ctx.execution)
                return null;
            if (!ctx.execution.repair_loop) {
                ctx.execution.repair_loop = {
                    attempt: 0,
                    max_attempts: 3,
                    phase_origin: failurePhase,
                    auto_repairable: true,
                    recurrence_count: 0,
                };
            }
            ctx.execution.repair_loop.attempt++;
            ctx.execution.repair_loop.phase_origin = failurePhase;
            ctx.execution.repair_loop.auto_repairable = autoRepairable;
            ctx.execution.repair_loop.escalation_reason = escalationReason;
            const samePhaseFailures = ctx.execution.failure_history.filter((f) => f.phase === failurePhase);
            ctx.execution.repair_loop.recurrence_count = samePhaseFailures.length;
            await save(ctx);
            return ctx;
        },
        async setEvidenceGroundingResult(taskId, payload) {
            const ctx = await load(taskId);
            if (!ctx)
                return null;
            if (payload.evidence_matrix)
                ctx.evidence_matrix = payload.evidence_matrix;
            if (payload.evidence_gate_result)
                ctx.evidence_gate_result = payload.evidence_gate_result;
            if (payload.unsupported_claims)
                ctx.unsupported_claims = payload.unsupported_claims;
            if (payload.conflict_resolutions)
                ctx.conflict_resolutions = payload.conflict_resolutions;
            await save(ctx);
            return ctx;
        },
        async recordRework(taskId, fromPhase, toPhase, reason) {
            const ctx = await load(taskId);
            if (!ctx)
                return null;
            if (!ctx.rework_history)
                ctx.rework_history = [];
            const reworkCount = ctx.rework_history.length;
            if (reworkCount >= MAX_REWORK) {
                ctx.phase_directive = "停止升级";
                await save(ctx);
                return ctx;
            }
            ctx.rework_history.push({
                from_phase: fromPhase,
                to_phase: toPhase,
                reason,
                timestamp: new Date().toISOString(),
            });
            await save(ctx);
            return ctx;
        },
    };
}
//# sourceMappingURL=manager_setters.js.map