// ── 工具组: 管理/基础设施工具 ──
// sf_resume_workspace, sf_audit_sample, sf_escape_report,
// sf_capability_update, sf_governance_report, sf_audit_integration, sf_navigation
// 从 tools.ts 第 4567-4912 行提取。
import { z } from "zod";
import { internalWarn } from "../../../engine/core/logger.js";
import { createToolRegistrar } from "../middleware.js";
import { lazyWorkspaceResumer, lazyJob, lazyAuditPool, lazyEscape, lazyAuditSampler, lazyCapState, lazyCapability, lazyCapAdvisor, lazyDualLayer, lazyGovernance, lazyConfigPrecedence, lazyMainPath, } from "../lazy_loaders.js";
import { errorMessage } from "../../../engine/core/helpers.js";
export async function registerAdminTools(ctx) {
    const { registerSafeTool, loadRelevantAnchors } = createToolRegistrar(ctx);
    const { config, taskContext, projectPath } = ctx;
    // ── sf_resume_workspace: 扫描恢复中断工单 ──
    registerSafeTool("sf_resume_workspace", "扫描 .soloforge/state/ 目录，恢复中断工单并播报当前进度。新会话启动时必须优先调用", {}, async () => {
        const result = await (await lazyWorkspaceResumer()).scanAndResume(taskContext);
        // 认知锚点：按恢复任务的 changed_files 相关性加载，禁止全量
        if (result.task) {
            const ctx = await taskContext.load(result.task.task_id);
            const changedFiles = ctx?.execution?.changed_files;
            if (changedFiles && changedFiles.length > 0) {
                const anchors = await loadRelevantAnchors({ file_paths: changedFiles });
                if (anchors && anchors.length > 0) {
                    result.cognitive_anchors = anchors;
                }
            }
        }
        // JobManager advisory: 查询活跃 jobs
        try {
            const jm = new (await lazyJob()).JobManager(taskContext.getStateDir());
            const activeJobs = await jm.listActiveJobs();
            if (activeJobs.length > 0) {
                result.active_jobs = activeJobs.map((j) => ({
                    job_id: j.job_id,
                    task_id: j.task_id,
                    phase: j.current_phase,
                    is_alive: j.is_alive,
                    latest_anchor_summary: j.latest_anchor?.summary,
                    checkpoint_count: j.checkpoint_count,
                }));
            }
        }
        catch {
            // JobManager advisory — 忽略错误
        }
        return {
            result: result,
        };
    });
    // ── sf_audit_sample: 从审计池按风险加权抽样生成抽检清单 ──
    const AuditSampleSchema = {
        seed: z.number().optional().describe("抽样种子（默认 0，同种子可复现）"),
    };
    registerSafeTool("sf_audit_sample", "从审计池按风险加权抽样，生成抽检清单（SamplingDecision 列表）。只读，不落盘，不生成逃逸报告，不改能力状态", AuditSampleSchema, async (args) => {
        const stateDir = taskContext.getStateDir();
        const pool = new (await lazyAuditPool()).AuditPool(stateDir);
        const items = pool.list();
        const seed = args.seed ?? 0;
        const result = (await lazyAuditSampler()).sampleAuditItems(items, seed);
        return {
            result: result,
        };
    });
    // ── sf_escape_report: 记录逃逸/误伤/工具故障报告 ──
    const EscapeReportSchema = {
        escape_id: z.string().describe("逃逸报告唯一 ID"),
        task_id: z.string().describe("关联任务 ID"),
        policy_id: z.string().describe("关联能力 policy ID"),
        failure_type: z.enum(["rule_gap", "weak_test", "bad_evidence", "ai_escape", "human_miss", "tool_bug", "false_positive"]).describe("失败类型"),
        expected_guard: z.string().describe("期望的守卫行为"),
        actual_escape: z.string().describe("实际的逃逸行为"),
        evidence: z.string().describe("证据"),
        root_cause: z.string().describe("根因分析"),
        fix_required: z.string().describe("修复要求"),
        owner: z.string().describe("负责人"),
        due_date: z.string().describe("修复截止日期"),
        capability_action: z.enum(["keep", "downgrade", "disable", "promote_blocked"]).describe("建议的能力动作"),
        created_at: z.string().optional().describe("报告时间（ISO，默认当前时间）"),
    };
    registerSafeTool("sf_escape_report", "记录逃逸、误伤或工具故障报告。只落盘记录，不自动降级，不改能力状态", EscapeReportSchema, async (args) => {
        const stateDir = taskContext.getStateDir();
        const store = new (await lazyEscape()).EscapeReportStore(stateDir);
        const report = {
            escape_id: args.escape_id,
            task_id: args.task_id,
            policy_id: args.policy_id,
            failure_type: args.failure_type,
            expected_guard: args.expected_guard,
            actual_escape: args.actual_escape,
            evidence: args.evidence,
            root_cause: args.root_cause,
            fix_required: args.fix_required,
            owner: args.owner,
            due_date: args.due_date,
            capability_action: args.capability_action,
            created_at: args.created_at ?? new Date().toISOString(),
        };
        store.append(report);
        return {
            result: { recorded: true, escape_id: report.escape_id },
        };
    });
    // ── sf_capability_update: 根据复盘结果更新 Capability Registry ──
    const CapabilityUpdateSchema = {
        policy_id: z.string().describe("要更新的 policy ID（如 CAP-003）"),
        target_state: z.enum(["enforced", "advisory", "experimental", "removed"]).describe("目标状态"),
        reason: z.string().describe("变更原因"),
        evidence_ids: z.array(z.string()).describe("支撑此变更的 escape report ID 列表"),
        confirmed_by: z.string().describe("人工确认者标识（如操作者名字）"),
        dry_run: z.boolean().optional().describe("dry_run 模式：只校验不持久化（默认 false）"),
        confirm: z.boolean().describe("人工确认标志，必须为 true 才能执行变更"),
    };
    registerSafeTool("sf_capability_update", "根据复盘结果更新 Capability Registry 状态。支持 dry_run 校验、证据校验、人工确认。不会自动触发，必须显式调用", CapabilityUpdateSchema, async (args) => {
        const stateDir = taskContext.getStateDir();
        const escapeStore = new (await lazyEscape()).EscapeReportStore(stateDir);
        const stateStore = new (await lazyCapState()).CapabilityStateStore(stateDir);
        const escapeReports = escapeStore.list();
        const capabilities = (await lazyCapability()).getAllCapabilities();
        const cap = capabilities.find((c) => c.policy_id === args.policy_id);
        const currentState = stateStore.getEffectiveState(args.policy_id, cap?.state ?? "experimental");
        const result = stateStore.apply({
            policy_id: args.policy_id,
            target_state: args.target_state,
            reason: args.reason,
            evidence_ids: args.evidence_ids,
            confirmed_by: args.confirmed_by,
            dry_run: args.dry_run ?? false,
            confirm: args.confirm,
        }, currentState, cap?.id ?? null, escapeReports);
        return {
            result: result,
        };
    });
    // ── sf_governance_report: 治理健康报告 ──
    const GovernanceReportSchema = {
        seed: z.number().optional().describe("抽样种子（用于计算 sampled_count，默认 0）"),
    };
    registerSafeTool("sf_governance_report", "生成治理健康报告：汇总审计池、逃逸报告、能力动作决策。只读，不改状态", GovernanceReportSchema, async (args) => {
        const stateDir = taskContext.getStateDir();
        const seed = args.seed ?? 0;
        const pool = new (await lazyAuditPool()).AuditPool(stateDir);
        const escapeStore = new (await lazyEscape()).EscapeReportStore(stateDir);
        const auditItems = pool.list();
        const auditStats = pool.stats();
        const escapeReports = escapeStore.list();
        const escapeStats = escapeStore.stats();
        // 为所有能力生成动作决策（使用有效状态）
        const capabilities = (await lazyCapability()).getAllCapabilities();
        const stateStore = new (await lazyCapState()).CapabilityStateStore(stateDir);
        const decisions = await Promise.all(capabilities.map(async (cap) => {
            const effectiveState = stateStore.getEffectiveState(cap.policy_id, cap.state);
            return (await lazyCapAdvisor()).decideAction(escapeReports, effectiveState, cap.policy_id);
        }));
        // 为 sampled_count 生成抽样决策
        const sampleResult = (await lazyAuditSampler()).sampleAuditItems(auditItems, seed);
        // 双层机制发现
        const dlFindings = (await lazyDualLayer()).validateMechanismLayerMaps();
        const dlMechanismCount = (await lazyDualLayer()).listMechanismLayerMaps().length;
        // 收集近期任务的产物记录
        const recentTasks = await taskContext.listRecent(20);
        const artifacts = [];
        for (const t of recentTasks) {
            const tCtx = await taskContext.load(t.task_id);
            if (tCtx?.artifact_output)
                artifacts.push(tCtx.artifact_output);
        }
        // 收集配置解析报告 — 使用共享函数获取真实数据
        let configReports = [];
        let configEntries = [];
        try {
            const resolved = await (await lazyConfigPrecedence()).resolveCurrentProjectConfigReports(projectPath);
            configReports = resolved.reports;
            configEntries = resolved.entries;
        }
        catch (e) {
            internalWarn("配置报告", "解析失败:", errorMessage(e));
        }
        // 同时包含近期任务上下文中的报告
        for (const t of recentTasks) {
            const tCtx = await taskContext.load(t.task_id);
            if (tCtx?.expansion?.config_resolution_reports) {
                configReports.push(...tCtx.expansion.config_resolution_reports);
            }
        }
        const report = (await lazyGovernance()).generateReport(auditStats, auditItems, escapeReports, escapeStats, decisions, new Date(), sampleResult.decisions, dlFindings, dlMechanismCount, artifacts.length > 0 ? artifacts : undefined, configReports.length > 0 ? configReports : undefined, configEntries.length > 0 ? configEntries : undefined);
        return {
            result: report,
        };
    });
    // ── sf_audit_integration: 主链路集成审计 ──
    const AuditIntegrationSchema = {
        changed_files: z.array(z.string()).optional().describe("只审计指定的变更文件列表"),
        json_output: z.boolean().optional().describe("以 JSON 格式输出（默认为人类可读文本）"),
    };
    registerSafeTool("sf_audit_integration", "审计生产代码的主链路集成状态，检测孤岛模块（只被测试导入、无生产代码调用的模块）", AuditIntegrationSchema, async (args) => {
        const projectPath = config._projectPath || process.cwd();
        // 使用作用域感知的生产文件收集（支持多仓库、多语言）
        const { collectAllProductionFiles } = await import("../../../engine/audit/main_path_integration_contract.js");
        const allProdFiles = collectAllProductionFiles(projectPath, config);
        if (allProdFiles.length === 0) {
            return {
                result: { error: "未找到生产源文件" },
            };
        }
        const targetFiles = args.changed_files
            ? allProdFiles.filter((rel) => (args.changed_files ?? []).some((cf) => rel === cf || rel.startsWith(cf.replace(/\.(ts|tsx|js|jsx|java|kt|go|py)$/, ""))))
            : allProdFiles;
        const contracts = (await lazyMainPath()).buildMainPathIntegrationContracts(projectPath, targetFiles, config);
        const report = (await lazyMainPath()).auditIntegration(contracts);
        if (args.json_output) {
            return {
                result: report,
            };
        }
        const lines = [];
        lines.push("主链路集成审计报告");
        lines.push(`受检模块: ${targetFiles.length} | 孤岛: ${report.orphan_modules.length} | 仅测试: ${report.test_only_modules.length} | 仅注册: ${report.registry_only_modules.length}`);
        lines.push("");
        for (const finding of report.findings) {
            const icon = finding.severity === "hard_fail" ? "X" : finding.severity === "warning" ? "~" : "i";
            lines.push(`${icon} ${finding.module_path}: ${finding.reason}`);
            if (finding.recommended_action) {
                lines.push(`  -> ${finding.recommended_action}`);
            }
        }
        if (report.findings.length === 0) {
            lines.push("所有受检模块已通过集成检查。");
        }
        return {
            result: { text: lines.join("\n") },
        };
    });
    // ── sf_navigation: 工作流导航 — 问题六十五 ──
    const NavigationSchema = {
        project_path: z.string().optional().describe("项目路径（可选，默认当前目录）"),
    };
    registerSafeTool("sf_navigation", "查询工作流导航: 当前项目阶段、任务阶段、下一步操作和禁止操作。用于\"下一步\"\"继续\"\"现在能写代码吗\"等模糊推进意图。不得靠模型经验回答，必须调用此工具获取真实导航状态", NavigationSchema, async (args) => {
        const projectPath = args.project_path || config._projectPath || process.cwd();
        const { planNextAction } = await import("../../../engine/workflow/next_action_planner.js");
        const plan = await planNextAction(projectPath);
        return {
            result: {
                project_stage: plan.project_stage,
                task_stage: plan.task_stage,
                current_task_id: plan.current_task_id,
                confidence: plan.confidence,
                stage_evidence: plan.stage_evidence,
                blocking_reasons: plan.blocking_reasons,
                stale_task: plan.stale_task,
                confirmation_decisions: plan.confirmation_decisions,
                work_package: plan.work_package ? {
                    id: plan.work_package.id,
                    goal_zh: plan.work_package.goal_zh,
                    description_zh: plan.work_package.description_zh,
                    action: plan.work_package.action,
                    tool_name: plan.work_package.tool_name,
                    must_read: plan.work_package.must_read,
                    forbidden_changes: plan.work_package.forbidden_changes,
                    expected_outputs: plan.work_package.expected_outputs,
                    acceptance_commands: plan.work_package.acceptance_commands,
                } : null,
                disallowed_actions: plan.disallowed_actions,
                recommended_commands: plan.recommended_commands,
                recommended_prompt_zh: plan.recommended_prompt_zh,
            },
        };
    });
}
//# sourceMappingURL=admin.js.map