import { createToolRegistrar } from "../middleware.js";
import { ScaffoldSchema, AcceptSchema, DeliverSchema } from "../schemas.js";
import { lazyScaffolder, lazyDelivery, lazyGitDeps, lazyObservability, lazyEnforcementGuard, lazyWorkspaceLease, lazyDeliveryReadiness, lazyLocalAcceptance, lazyOodSolid, lazyBackendImplementation, lazyCodeObservability, } from "../lazy_loaders.js";
import { checkCodingReadinessGate, checkLocalAcceptanceGate } from "../gate_checks.js";
import { assessCepBeforeDelivery } from "../cep_assessment.js";
import { TOOL_DIAGNOSTIC_CODES } from "../../../engine/audit/diagnostic_registry.js";
export async function registerScaffoldAcceptTools(ctx) {
    const { registerSafeTool } = createToolRegistrar(ctx);
    const { config, taskContext, projectPath } = ctx;
    // ── sf_scaffold: 根据项目模板生成标准化代码骨架 ──
    registerSafeTool("sf_scaffold", "根据项目模板生成标准化代码骨架（Controller/Service/DTO/测试等）。仅在 task_type=scaffold 时使用", ScaffoldSchema, async (args) => {
        const ctx = await taskContext.load(args.task_id);
        if (!ctx?.classification) {
            return {
                result: { error: "任务不存在或尚未分类" },
            };
        }
        if (ctx.classification.task_type !== "scaffold") {
            return {
                result: {
                    error: "sf_scaffold 仅适用于 scaffold 类型任务",
                    current_type: ctx.classification.task_type,
                },
            };
        }
        const result = await (await lazyScaffolder()).generateScaffold({
            intent: ctx.intent,
            classification: ctx.classification,
            config,
            projectPath,
        });
        result.task_id = args.task_id;
        return {
            result: result,
        };
    });
    // ── sf_accept: 记录任务验收证据（本地验收 + 产物确认） ──
    registerSafeTool("sf_accept", "记录任务验收证据，解除 sf_deliver 的本地验收门和产物确认门", AcceptSchema, async (args) => {
        const ctx = await taskContext.load(args.task_id);
        if (!ctx) {
            return { result: { error: "任务不存在" } };
        }
        const runMode = args.run_mode;
        const notes = String(args.acceptance_notes ?? "").trim();
        const confirmedBy = String(args.confirmed_by ?? "").trim();
        const confirmationRef = String(args.confirmation_ref ?? "").trim();
        if (args.confirm !== true || !confirmedBy || !confirmationRef || !notes) {
            return {
                result: {
                    error: "验收必须包含显式确认、确认者、可审计确认引用和验收说明",
                    diagnostic_code: "SF-ACCEPT-CONFIRMATION-REQUIRED",
                    recovery_next_tools: ["sf_accept", "sf_status"],
                    recovery_forbidden_tools: ["sf_verify", "sf_scaffold", "sf_classify", "sf_expand"],
                },
            };
        }
        const currentVerification = ctx.verification_result;
        if (currentVerification?.status !== "passed") {
            return {
                result: {
                    error: "验收前必须已有真实执行并通过的 verification_result",
                    diagnostic_code: "SF-ACCEPT-VERIFICATION-REQUIRED",
                    recovery_next_tools: ["sf_verify", "sf_record_verification_execution", "sf_status"],
                    recovery_forbidden_tools: ["sf_verify", "sf_scaffold", "sf_classify", "sf_expand"],
                },
            };
        }
        const evidenceRef = `acceptance:user_confirmation:${confirmationRef}`;
        if (runMode === "manual_review") {
            const acceptanceModule = await lazyLocalAcceptance();
            if (!args.final_access) {
                return {
                    result: {
                        error: "manual_review 验收缺少 final_access 真实访问证据",
                        diagnostic_code: "SF-ACCEPT-FINAL-ACCESS-REQUIRED",
                        recovery_next_tools: ["sf_accept", "sf_status"],
                        recovery_forbidden_tools: ["sf_verify", "sf_scaffold", "sf_classify", "sf_expand"],
                    },
                };
            }
            const finalAccessResult = acceptanceModule.validateFinalAccess(args.final_access, "local_dev_server");
            if (!finalAccessResult.passed) {
                return {
                    result: {
                        error: `manual_review 验收证据不完整: ${finalAccessResult.blocking_reasons.join("; ")}`,
                        diagnostic_code: "SF-ACCEPT-FINAL-ACCESS-INVALID",
                        recovery_next_tools: ["sf_accept", "sf_status"],
                        recovery_forbidden_tools: ["sf_verify", "sf_scaffold", "sf_classify", "sf_expand"],
                    },
                };
            }
        }
        // 设置本地验收证据
        ctx.local_acceptance_evidence = {
            status: runMode === "manual_review" ? "passed" : "not_applicable",
            run_mode: runMode,
            confirmed_by: confirmedBy,
            confirmation_ref: confirmationRef,
            final_access: args.final_access ?? {
                frontend_urls: [],
                backend_urls: [],
                docs_or_swagger_urls: [],
                start_commands: [],
                stop_commands: [],
                running_status: "not_started",
                manual_review_steps_zh: [notes],
                known_limits_zh: [],
            },
            evidence_refs: [evidenceRef],
        };
        await taskContext.save(ctx);
        let updatedCtx = ctx;
        // 产物确认必须经过统一生命周期校验，不直接改写 status。
        if (ctx.artifact_output && ctx.artifact_output.status === "verified") {
            updatedCtx = await taskContext.updateArtifactStatus(args.task_id, {
                status: "accepted",
                evidenceRef,
                hasAcceptance: true,
            }) ?? ctx;
        }
        return {
            result: {
                task_id: args.task_id,
                acceptance_status: "passed",
                run_mode: runMode,
                evidence_ref: evidenceRef,
                artifact_transition: updatedCtx.artifact_output
                    ? `${updatedCtx.artifact_output.status}`
                    : "no_artifact",
            },
        };
    });
}
export async function registerDeliverTools(ctx) {
    const { registerSafeTool } = createToolRegistrar(ctx);
    const { config, knowledgeIndex, taskContext, ioController, projectPath } = ctx;
    // ── sf_deliver: 自动提交、推送、创建 PR ──
    registerSafeTool("sf_deliver", "验收后自动提交代码、推送、创建 PR 和生成变更日志", DeliverSchema, async (args) => {
        const ctx = await taskContext.load(args.task_id);
        if (!ctx) {
            return {
                result: { error: "任务不存在" },
            };
        }
        // H4: 交付前工作区完整性检查 — advisory 模式，仅警告不阻断
        const deliverIntegrity = await ioController.verify();
        const h4DeliverWarning = !deliverIntegrity.clean
            ? { warning: `H4 advisory: ${deliverIntegrity.message}`, dirty_files: deliverIntegrity.dirty_files }
            : undefined;
        // 模板契约修复指令优先于通用产物状态提示，确保客户端获得可执行的修复重验路径。
        if (ctx.repair_reverify_directive) {
            return {
                result: {
                    error: "存在未清零的模板契约修复指令，需完成修复重验后才能交付",
                    diagnostic_code: TOOL_DIAGNOSTIC_CODES.contractDraft,
                    repair_directive: ctx.repair_reverify_directive,
                    recovery: "修复文档缺口后重新执行 sf_verify，验证通过后 repair_reverify_directive 自动清零",
                    recovery_next_tools: ["sf_learn", "sf_deliver", "sf_status"],
                    recovery_forbidden_tools: ["sf_verify", "sf_scaffold", "sf_classify", "sf_expand"],
                },
            };
        }
        // 问题六十六/六十七: 审查或验证阶段产生的工程硬失败不得进入交付。
        const oodModule = await lazyOodSolid();
        if (oodModule.hasBlockingSolidFindings(ctx.ood_solid_findings ?? [])) {
            return {
                result: {
                    error: "OOD/SOLID 契约仍存在硬失败，不得交付",
                    diagnostic_code: TOOL_DIAGNOSTIC_CODES.oodDeliveryBlock,
                    findings: ctx.ood_solid_findings,
                    recovery: "按 finding 修复职责或依赖边界，并重新执行 sf_review 与 sf_verify",
                },
            };
        }
        const backendModule = await lazyBackendImplementation();
        if (backendModule.hasBlockingBackendFindings(ctx.backend_implementation_findings ?? [])) {
            return {
                result: {
                    error: "后端实现工程契约仍存在硬失败，不得交付",
                    diagnostic_code: TOOL_DIAGNOSTIC_CODES.backendDeliveryBlock,
                    findings: ctx.backend_implementation_findings,
                    recovery: "按 finding 修复后端边界、安全或一致性问题，并重新执行 sf_review 与 sf_verify",
                },
            };
        }
        // 问题六十八: 代码可维护性与可观测性 P0 阻断交付。
        const obsModule = await lazyCodeObservability();
        const obsDeliveryBlock = obsModule.evaluateDeliveryBlock(ctx.code_observability_findings ?? []);
        if (obsDeliveryBlock.blocked) {
            return {
                result: {
                    error: `代码可维护性/可观测性存在阻断: ${obsDeliveryBlock.reason_zh}`,
                    diagnostic_code: TOOL_DIAGNOSTIC_CODES.codeObservabilityFinding,
                    findings: obsDeliveryBlock.blocking_findings,
                    recovery: "按 finding 修复敏感信息泄漏、缺失日志或吞异常问题，并重新执行 sf_review 与 sf_verify",
                },
            };
        }
        // 产物状态门控: deliver 需要产物状态为 accepted 且有证据
        if (ctx.artifact_output) {
            const status = ctx.artifact_output.status;
            if (status === "draft") {
                return {
                    result: {
                        error: `产物状态为 ${status}，需先通过验证 (verified) 并确认 (accepted) 才能交付`,
                        artifact_id: ctx.artifact_output.artifact_id,
                        current_status: status,
                    },
                };
            }
            if (status === "verified") {
                return {
                    result: {
                        error: `产物状态为 ${status}，需人工确认或后续 workflow 采用后变为 accepted 才能交付`,
                        artifact_id: ctx.artifact_output.artifact_id,
                        current_status: status,
                    },
                };
            }
            // accepted 必须有确认证据
            if (status === "accepted") {
                const hasAcceptanceEvidence = ctx.artifact_output.evidence_refs.some((r) => r.includes("acceptance") || r.includes("workflow_adoption"));
                if (!hasAcceptanceEvidence) {
                    return {
                        result: {
                            error: `产物状态为 accepted 但缺少确认证据 (acceptance/workflow_adoption evidence_ref)`,
                            artifact_id: ctx.artifact_output.artifact_id,
                            current_status: status,
                        },
                    };
                }
            }
        }
        // 问题六十二: 依赖设计产物的任务只有 implementation_ready 后才可交付。
        if (ctx.design_artifact_pack && ctx.design_artifact_pack.status !== "implementation_ready") {
            return {
                result: {
                    error: `设计产物包状态为 ${ctx.design_artifact_pack.status}，未达到 implementation_ready，不得交付`,
                    diagnostic_code: "SF-DESIGN-PACK-NOT-READY",
                    findings: ctx.design_artifact_pack.findings,
                    recovery: "请完成设计产物真实复验并修复所有阻断项后重新交付",
                },
            };
        }
        if (ctx.traceability_binding && ctx.traceability_binding.status !== "bound") {
            return {
                result: {
                    error: "追踪绑定未闭合，不得交付编码结果",
                    diagnostic_code: TOOL_DIAGNOSTIC_CODES.traceabilityDeliveryBlocked,
                    traceability_binding: ctx.traceability_binding,
                    recovery: "补齐需求/原型/设计/切片/验收追踪矩阵并重新 sf_expand → sf_verify，通过后再 sf_deliver",
                },
            };
        }
        // 交付 lease 互斥检查
        const leaseModule = await lazyWorkspaceLease();
        const deliverLease = leaseModule.acquireLease(args.task_id, "delivery", [projectPath]);
        if (deliverLease.lease?.status === "conflicted" || deliverLease.conflicts.length > 0) {
            return {
                result: {
                    error: `交付 lease 冲突: ${deliverLease.conflicts.map((c) => `${c.conflict_type}: ${c.conflict_path}`).join(", ")}`,
                    conflicts: deliverLease.conflicts,
                },
            };
        }
        // 交付就绪评估 — delivery_allowed=false 必须阻断交付
        const drModule = await lazyDeliveryReadiness();
        const guardModule = await lazyEnforcementGuard();
        const currentVResult = ctx.verification_result;
        const currentVPlan = ctx.verification_plan;
        const guardFindings = guardModule.evaluateDeliveryReadinessGuard(currentVResult, currentVPlan);
        // 问题五十一: 编码就绪门 — 交付前检查 coding readiness
        const codingGate = await checkCodingReadinessGate({ ctx });
        if (!codingGate.allowed) {
            if (deliverLease.lease) {
                leaseModule.releaseLease(deliverLease.lease.lease_id);
            }
            return {
                result: {
                    error: `编码就绪检查未通过: ${codingGate.reason_zh}`,
                    missing_preconditions: codingGate.missing_preconditions,
                    status: "blocked",
                    recovery: "请先满足编码就绪条件（测试计划、验收标准、主链路入口）",
                },
            };
        }
        const metricsData = await (await lazyObservability()).collectDeliveryMetricSamples(taskContext.getStateDir());
        // acceptanceConfig: 从项目配置推断 project_run_mode
        const projectHasFrontend = config.tech_stack.frontend.lang && config.tech_stack.frontend.lang !== "none";
        const projectHasBackend = config.tech_stack.backend.lang && config.tech_stack.backend.lang !== "none";
        const readinessReport = drModule.evaluateDeliveryReadiness(args.task_id, currentVResult, guardFindings, true, // scope_check — 已在 sf_verify 写入护栏中检查
        deliverLease.conflicts.length === 0, // lease_check — 无冲突即通过
        true, // privacy_check — 已在任务创建时脱敏
        true, // artifact_acceptance — 上面已检查产物状态
        metricsData, projectHasFrontend ? { final_access: { frontend_urls: [], backend_urls: [], docs_or_swagger_urls: [], start_commands: [], stop_commands: [], running_status: "not_started", manual_review_steps_zh: [], known_limits_zh: [] }, project_run_mode: "local_dev_server" } : undefined);
        // 保存就绪报告到任务上下文
        const ctxForReadiness = await taskContext.load(args.task_id);
        if (ctxForReadiness) {
            ctxForReadiness.delivery_readiness = readinessReport;
            await taskContext.save(ctxForReadiness);
        }
        if (!readinessReport.delivery_allowed) {
            // 释放 lease 并阻断交付
            if (deliverLease.lease) {
                leaseModule.releaseLease(deliverLease.lease.lease_id);
            }
            return {
                result: {
                    error: `交付就绪检查未通过: ${readinessReport.blocking_findings.map((f) => f.message_zh).join("; ")}`,
                    delivery_readiness: readinessReport,
                },
            };
        }
        // 问题五十二: 本地验收门 — 前端/全栈交付前必须有本地访问证据（仅在有施工指令契约时强制）
        const hasInstructionContract = !!ctx?.instruction_contract;
        if (hasInstructionContract) {
            const localAcceptanceGate = await checkLocalAcceptanceGate({
                ctx,
                hasFrontend: !!projectHasFrontend,
                hasBackend: !!projectHasBackend,
                hasDockerCompose: false,
                hasDockerfile: false,
            });
            if (!localAcceptanceGate.allowed) {
                if (deliverLease.lease) {
                    leaseModule.releaseLease(deliverLease.lease.lease_id);
                }
                return {
                    result: {
                        error: `本地验收检查未通过: ${localAcceptanceGate.reason_zh}`,
                        required_but_missing: localAcceptanceGate.required_but_missing,
                        status: "blocked",
                        recovery: "请提供本地运行证据或说明 not_applicable 原因（如纯后端 API 项目）",
                    },
                };
            }
        }
        // 问题六十：交付结论必须经过 UnsupportedClaimGate
        {
            const { createEvidenceGroundingSystem, assessTaskRisk } = await import("../../../engine/contracts/evidence_grounding_contract.js");
            const _dRoute = ctx.route_decision?.route ?? ctx.classification?.route_decision?.route;
            const _dRisk = assessTaskRisk(ctx.classification?.task_type, _dRoute, ctx.intent);
            if (_dRisk !== "low") {
                const _deg = createEvidenceGroundingSystem();
                // 注册验证结果和交付上下文
                if (currentVResult) {
                    _deg.registry.register({
                        source_type: "validation_result",
                        authority: "authoritative",
                        freshness: "current",
                        permission: "allowed",
                        scope: "verification",
                        description: `验证状态: ${currentVResult.status}`,
                        source_ref: `verification:${args.task_id}`,
                    });
                }
                _deg.registry.register({
                    source_type: "task_context",
                    authority: "authoritative",
                    freshness: "current",
                    permission: "allowed",
                    scope: "delivery",
                    description: "交付上下文",
                    source_ref: `task:${args.task_id}`,
                });
                const _dClaims = [
                    {
                        id: "claim-deliver-1",
                        category: "release_status",
                        claim_text: "交付基于真实验证结果",
                        evidence_ids: _deg.registry.query({ source_type: "validation_result" }).map((e) => e.id),
                        is_uncertain: false,
                        risk_level: _dRisk,
                    },
                ];
                const _dMatrix = _deg.builder.buildContext(_dClaims, { target_claims: ["交付验证"], source_types: ["validation_result", "task_context"], keywords: ["验证", "交付"], max_results: 10 });
                _dMatrix.task_id = args.task_id;
                const _dGateResult = _deg.gate.evaluate(_dMatrix, _dRisk);
                // 写回 TaskContext（blocked 也保存）
                await taskContext.setEvidenceGroundingResult(args.task_id, {
                    evidence_matrix: _dMatrix,
                    evidence_gate_result: _dGateResult,
                    unsupported_claims: _dGateResult.unsupported_claims,
                    conflict_resolutions: _dMatrix.conflicts,
                });
                if (!_dGateResult.allowed) {
                    if (deliverLease.lease) {
                        leaseModule.releaseLease(deliverLease.lease.lease_id);
                    }
                    return {
                        result: {
                            error: `证据驱动门禁未通过: ${_dGateResult.reason_zh}`,
                            diagnostic_code: _dGateResult.diagnostic_code,
                            unsupported_claims: _dGateResult.unsupported_claims,
                        },
                    };
                }
            }
        }
        // 交付前检查 false completion（通过提取的主链路函数）
        const cepNfcResult = await assessCepBeforeDelivery({
            task_id: args.task_id,
            verification_passed: currentVResult?.status === "passed",
            build_passed: (currentVResult?.passed_commands ?? 0) > 0,
            browser_acceptance_passed: ctx.artifact_output?.status === "accepted" || ctx.artifact_output === undefined,
            guard_passed: guardFindings.length === 0 || guardFindings.every((f) => f.severity !== "hard_fail"),
            evidence_sufficient: (currentVResult?.evidence_ids?.length ?? 0) > 0,
            current_status: ctx.status === "done" ? "完成" : ctx.status,
        });
        if (cepNfcResult.decision === "blocked" || cepNfcResult.decision === "回退") {
            if (deliverLease.lease) {
                leaseModule.releaseLease(deliverLease.lease.lease_id);
            }
            const ctxForCep = await taskContext.load(args.task_id);
            if (ctxForCep) {
                ctxForCep.core_experience_evaluation = {
                    task_id: args.task_id,
                    workflow_id: "sf_deliver",
                    evaluated_principles: ["auto_repair_no_fake_completion"],
                    violations: [{
                            principle: "auto_repair_no_fake_completion",
                            severity: "blocking",
                            reason_zh: cepNfcResult.reason_zh,
                            evidence_refs: [],
                            required_action: cepNfcResult.decision === "blocked" ? "block_delivery" : "回退",
                        }],
                    user_facing_summary_zh: `CEP 检查未通过: ${cepNfcResult.reason_zh}`,
                    internal_trace_refs: [],
                    passed: false,
                };
                await taskContext.save(ctxForCep);
            }
            return {
                result: {
                    error: `CEP false completion 检查未通过: ${cepNfcResult.reason_zh}`,
                    cep_decision: cepNfcResult.decision,
                },
            };
        }
        const result = await (await lazyDelivery()).deliver({
            taskContext: ctx,
            config,
            knowledgeIndex,
            projectPath,
            gitOps: (await lazyGitDeps()).realGitOps,
            skipPush: args.skip_push,
            skipPr: args.skip_pr,
        });
        await taskContext.setDelivery(args.task_id, result);
        // 交付完成后释放 lease
        if (deliverLease.lease) {
            leaseModule.releaseLease(deliverLease.lease.lease_id);
        }
        return {
            result: h4DeliverWarning ? { ...result, h4_advisory: h4DeliverWarning } : result,
        };
    });
}
//# sourceMappingURL=scaffold_accept_deliver.js.map