/**
 * 诊断码注册表 — 问题三十六 (Diagnostic Code Contract)。
 *
 * 核心规则:
 * - 诊断码格式 SF-{AREA}-{NNNN}，一旦发布不得复用
 * - blocking/critical 事件没有诊断码不得输出
 * - 每个 active code 必须有 title_zh、user_message_zh、recovery_hint_zh
 * - deprecated/removed code 不得复用
 */
export const TOOL_DIAGNOSTIC_CODES = {
    planGate: "SF-PLAN-5001",
    instructionContract: "SF-INSTR-5801",
    oodMissingSummary: "SF-OOD-6601",
    oodDeliveryBlock: "SF-OOD-6602",
    backendMissingSummary: "SF-BACKEND-6701",
    backendDeliveryBlock: "SF-BACKEND-6702",
    codeObservabilityWorkPackage: "SF-OBS-6801",
    codeObservabilityFinding: "SF-OBS-6802",
    projectKnowledgeBlocked: "SF-PK-6901",
    contractDraft: "SF-CONTRACT-0003",
    verifyPlanMismatch: "SF-VERIFY-5002",
    traceabilityMissing: "SF-TRACE-7301",
    traceabilityBindingMissing: "SF-TRACE-7302",
    traceabilityVerifyFailed: "SF-TRACE-7303",
    traceabilityDeliveryBlocked: "SF-TRACE-7304",
};
const BUILTIN_DIAGNOSTICS = [
    // STATE 领域
    { code: "SF-STATE-0001", area: "STATE", severity: "blocking", status: "active",
        title_zh: "非法状态转移: failed → completed",
        user_message_zh: "任务已失败，不能直接标记完成。需要人工确认恢复后重新验证。",
        recovery_hint_zh: "检查失败原因，修复后重新执行验证流程。",
        owner_component: "engine/task_context", evidence_refs: ["task_context状态机"] },
    { code: "SF-STATE-0002", area: "STATE", severity: "blocking", status: "active",
        title_zh: "非法状态转移: blocked → completed",
        user_message_zh: "任务被阻断，不能直接标记完成。需要解除阻断条件。",
        recovery_hint_zh: "检查阻断原因，解决阻断条件后重试。",
        owner_component: "engine/task_context", evidence_refs: ["task_context状态机"] },
    { code: "SF-STATE-0003", area: "STATE", severity: "blocking", status: "active",
        title_zh: "非法状态转移: requires_human → completed",
        user_message_zh: "任务需要人工确认，不能自动标记完成。",
        recovery_hint_zh: "等待人工确认后继续。",
        owner_component: "engine/task_context", evidence_refs: ["task_context状态机"] },
    // GUARD 领域
    { code: "SF-GUARD-0001", area: "GUARD", severity: "blocking", status: "active",
        title_zh: "只读工作流写入业务源码",
        user_message_zh: "当前工作流不允许写入业务源码，操作已阻断。",
        recovery_hint_zh: "检查路由是否正确，或切换到允许写入的工作流。",
        owner_component: "engine/enforcement_guard", evidence_refs: ["enforcement_guard写入护栏"] },
    { code: "SF-GUARD-0002", area: "GUARD", severity: "blocking", status: "active",
        title_zh: "超出 output artifact 范围写入",
        user_message_zh: "source_extraction 工作流只能写入指定的 output artifact 路径。",
        recovery_hint_zh: "确认输出路径是否在允许范围内。",
        owner_component: "engine/enforcement_guard", evidence_refs: ["enforcement_guard范围护栏"] },
    { code: "SF-GUARD-0003", area: "GUARD", severity: "blocking", status: "active",
        title_zh: "破坏性命令未经人工确认",
        user_message_zh: "检测到破坏性命令（如删除、覆盖）但缺少人工确认。操作已阻止。",
        recovery_hint_zh: "请通过 sf_status confirm 确认执行，或调整命令为非破坏性操作。",
        owner_component: "engine/enforcement_guard", evidence_refs: ["enforcement_guard执行护栏"] },
    { code: "SF-GUARD-0004", area: "GUARD", severity: "blocking", status: "active",
        title_zh: "不可注入知识条目被注入到 prompt",
        user_message_zh: "知识条目的 status 或 scope 不允许注入，但被尝试注入。操作已阻止。",
        recovery_hint_zh: "检查知识条目的 lifecycle status 和 injection 权限。",
        owner_component: "engine/enforcement_guard", evidence_refs: ["enforcement_guard知识护栏"] },
    { code: "SF-GUARD-0005", area: "GUARD", severity: "blocking", status: "active",
        title_zh: "prompt 超出工作流契约权限",
        user_message_zh: "当前工作流不允许此 prompt 内容或权限级别。操作已阻止。",
        recovery_hint_zh: "检查工作流契约的 prompt 权限配置。",
        owner_component: "engine/enforcement_guard", evidence_refs: ["enforcement_guard prompt护栏"] },
    { code: "SF-GUARD-0006", area: "GUARD", severity: "blocking", status: "active",
        title_zh: "外部副作用无 evidence 记录",
        user_message_zh: "检测到外部副作用操作（push/PR/deploy）但缺少 evidence 记录。",
        recovery_hint_zh: "确保所有外部副作用操作有完整的 evidence chain。",
        owner_component: "engine/enforcement_guard", evidence_refs: ["enforcement_guard副作用护栏"] },
    // VERIFY 领域
    { code: "SF-VERIFY-0001", area: "VERIFY", severity: "critical", status: "active",
        title_zh: "验证计划被当作验证证据",
        user_message_zh: "检测到只有验证计划没有验证结果。计划不得替代真实执行。",
        recovery_hint_zh: "执行验证命令获取真实结果。",
        owner_component: "engine/verification_contract", evidence_refs: ["verification_contract分离"] },
    { code: "SF-VERIFY-0002", area: "VERIFY", severity: "blocking", status: "active",
        title_zh: "未验证但尝试交付",
        user_message_zh: "任务未通过验证，不允许交付。",
        recovery_hint_zh: "先完成验证流程，确保所有检查通过。",
        owner_component: "engine/delivery_readiness", evidence_refs: ["delivery_readiness门控"] },
    // FAILURE 领域
    { code: "SF-FAILURE-0001", area: "FAILURE", severity: "critical", status: "active",
        title_zh: "重试预算耗尽",
        user_message_zh: "失败重试次数已达上限，需要人工介入。",
        recovery_hint_zh: "检查错误根因，手动修复后重新执行。",
        owner_component: "engine/recovery_policy", evidence_refs: ["recovery_policy预算"] },
    { code: "SF-FAILURE-0002", area: "FAILURE", severity: "warning", status: "active",
        title_zh: "外部副作用部分执行",
        user_message_zh: "检测到外部副作用部分执行，已记录已发生动作。",
        recovery_hint_zh: "检查已执行副作用，确认是否需要回滚。",
        owner_component: "engine/recovery_policy", evidence_refs: ["recovery_policy副作用"] },
    // DEGRADE 领域
    { code: "SF-DEGRADE-0001", area: "DEGRADE", severity: "warning", status: "active",
        title_zh: "验证器不可用，降级运行",
        user_message_zh: "验证器不可用，当前为降级模式。结果未经验证。",
        recovery_hint_zh: "等待验证器恢复后重新验证，或人工确认。",
        owner_component: "engine/degradation", evidence_refs: ["degradation降级"] },
    // WORKSPACE 领域
    { code: "SF-WORKSPACE-0001", area: "WORKSPACE", severity: "blocking", status: "active",
        title_zh: "并发写入冲突",
        user_message_zh: "检测到其他任务正在写入相同文件范围，操作已阻断。",
        recovery_hint_zh: "等待其他任务完成或人工协调写入顺序。",
        owner_component: "engine/workspace_lease", evidence_refs: ["workspace_lease冲突"] },
    // OBSERVE 领域
    { code: "SF-OBSERVE-0001", area: "OBSERVE", severity: "warning", status: "active",
        title_zh: "TaskContext 尝试存储敏感原文",
        user_message_zh: "检测到尝试将敏感信息存入 TaskContext，已自动脱敏。",
        recovery_hint_zh: "确认脱敏后的内容是否满足需求。",
        owner_component: "engine/task_context", evidence_refs: ["task_context边界"] },
    // CONTRACT 领域
    { code: "SF-CONTRACT-0001", area: "CONTRACT", severity: "blocking", status: "active",
        title_zh: "引用已废弃/已移除的契约",
        user_message_zh: "工作流引用了已废弃或已移除的契约，操作已阻断。",
        recovery_hint_zh: "迁移到替代契约或更新工作流配置。",
        owner_component: "engine/contract_registry", evidence_refs: ["contract_registry门控"] },
    // PRIVACY 领域
    { code: "SF-PRIVACY-0001", area: "PRIVACY", severity: "blocking", status: "active",
        title_zh: "命令输出包含敏感信息",
        user_message_zh: "命令执行输出检测到敏感信息，已自动脱敏存储。",
        recovery_hint_zh: "检查脱敏后内容，确认是否需要重新执行。",
        owner_component: "engine/privacy_secret_contract", evidence_refs: ["privacy脱敏"] },
    { code: TOOL_DIAGNOSTIC_CODES.planGate, area: "GUARD", severity: "blocking", status: "active",
        title_zh: "写工具缺少计划前置门",
        user_message_zh: "写入类工具执行前缺少已确认的计划。",
        recovery_hint_zh: "先完成 sf_classify → sf_expand，并确认执行计划。",
        owner_component: "server/tools", evidence_refs: ["PlanProposalFirstGate"] },
    { code: TOOL_DIAGNOSTIC_CODES.instructionContract, area: "CONTRACT", severity: "blocking", status: "active",
        title_zh: "施工指令契约未就绪",
        user_message_zh: "施工指令缺少目标、范围、验收或禁止绕过项。",
        recovery_hint_zh: "补齐施工指令后再执行写入。",
        owner_component: "engine/instruction_contract", evidence_refs: ["InstructionContract"] },
    { code: TOOL_DIAGNOSTIC_CODES.oodMissingSummary, area: "CONTRACT", severity: "blocking", status: "active",
        title_zh: "OOD/SOLID 摘要缺失",
        user_message_zh: "复杂实现任务缺少面向对象与 SOLID 设计摘要。",
        recovery_hint_zh: "先补齐职责、依赖方向、扩展点和边界说明。",
        owner_component: "engine/ood_solid_contract", evidence_refs: ["OOD/SOLID契约"] },
    { code: TOOL_DIAGNOSTIC_CODES.oodDeliveryBlock, area: "DELIVER", severity: "blocking", status: "active",
        title_zh: "OOD/SOLID 问题未闭合",
        user_message_zh: "实现仍存在职责、依赖或扩展性硬失败，不能交付。",
        recovery_hint_zh: "修复 OOD/SOLID finding 后重新验证。",
        owner_component: "engine/ood_solid_contract", evidence_refs: ["OOD/SOLID交付门"] },
    { code: TOOL_DIAGNOSTIC_CODES.backendMissingSummary, area: "CONTRACT", severity: "blocking", status: "active",
        title_zh: "后端工程契约摘要缺失",
        user_message_zh: "后端实现缺少参数、事务、权限、幂等或审计等工程契约。",
        recovery_hint_zh: "补齐后端实现工作包后再编码。",
        owner_component: "engine/backend_implementation_contract", evidence_refs: ["后端工程契约"] },
    { code: TOOL_DIAGNOSTIC_CODES.backendDeliveryBlock, area: "DELIVER", severity: "blocking", status: "active",
        title_zh: "后端工程契约未闭合",
        user_message_zh: "后端实现仍存在参数校验、事务、安全或审计硬失败，不能交付。",
        recovery_hint_zh: "修复后端工程 finding 后重新验证。",
        owner_component: "engine/backend_implementation_contract", evidence_refs: ["后端工程交付门"] },
    { code: TOOL_DIAGNOSTIC_CODES.codeObservabilityWorkPackage, area: "OBSERVE", severity: "blocking", status: "active",
        title_zh: "代码可维护性与可观测性工作包缺失",
        user_message_zh: "业务编码前缺少必要注释、日志和脱敏约束。",
        recovery_hint_zh: "先生成并确认代码可维护性与可观测性工作包。",
        owner_component: "engine/code_maintainability_observability_contract", evidence_refs: ["问题六十八"] },
    { code: TOOL_DIAGNOSTIC_CODES.codeObservabilityFinding, area: "OBSERVE", severity: "blocking", status: "active",
        title_zh: "代码可维护性与可观测性 finding 未闭合",
        user_message_zh: "代码存在敏感日志、不可定位日志、吞异常或关键操作缺日志，不能交付。",
        recovery_hint_zh: "修复注释/日志 finding 后重新验证。",
        owner_component: "engine/code_maintainability_observability_contract", evidence_refs: ["问题六十八"] },
    { code: TOOL_DIAGNOSTIC_CODES.projectKnowledgeBlocked, area: "CONTRACT", severity: "blocking", status: "active",
        title_zh: "用户项目知识规则不可消费",
        user_message_zh: "项目 .soloforge/knowledge 中存在 hard rule 路由、触发条件或身份冲突，不能进入执行、审查、验证或交付。",
        recovery_hint_zh: "运行 soloforge audit-project-knowledge，修复规则 frontmatter、routes、primary_triggers 或冲突后重试。",
        owner_component: "engine/project_knowledge_contract", evidence_refs: ["用户项目知识消费体系"] },
    { code: TOOL_DIAGNOSTIC_CODES.contractDraft, area: "CONTRACT", severity: "blocking", status: "active",
        title_zh: "设计产物仍为草稿",
        user_message_zh: "设计产物未通过契约验证或仍是草稿，不能交付。",
        recovery_hint_zh: "修复设计产物并重新执行 sf_verify。",
        owner_component: "engine/standard_asset_contract", evidence_refs: ["标准资产契约"] },
    { code: TOOL_DIAGNOSTIC_CODES.verifyPlanMismatch, area: "VERIFY", severity: "blocking", status: "active",
        title_zh: "验证计划不匹配",
        user_message_zh: "请求的验证计划与当前任务计划不一致。",
        recovery_hint_zh: "使用当前任务的 plan_id 重新执行验证。",
        owner_component: "server/tools", evidence_refs: ["VerificationPlan"] },
    { code: TOOL_DIAGNOSTIC_CODES.traceabilityMissing, area: "CONTRACT", severity: "blocking", status: "active",
        title_zh: "设计实现追踪链路缺失",
        user_message_zh: "编码前缺少需求、原型、设计、切片和验收追踪矩阵，不能脱离已确认设计开始实现。",
        recovery_hint_zh: "补齐追踪矩阵，并让架构、详细设计、切片计划绑定 REQ/PROTO/ARCH/DD/PHASE/SLICE/AC ID。",
        owner_component: "engine/traceability", evidence_refs: ["问题七十三"] },
    { code: TOOL_DIAGNOSTIC_CODES.traceabilityBindingMissing, area: "CONTRACT", severity: "blocking", status: "active",
        title_zh: "编码任务缺少追踪 ID 绑定",
        user_message_zh: "本次编码任务没有绑定切片、详细设计和验收 ID，不能确认实现范围。",
        recovery_hint_zh: "在任务上下文或指令中明确 PHASE-*、SLICE-*、DD-*、AC-* 后重新执行。",
        owner_component: "server/tools", evidence_refs: ["问题七十三"] },
    { code: TOOL_DIAGNOSTIC_CODES.traceabilityVerifyFailed, area: "CONTRACT", severity: "blocking", status: "active",
        title_zh: "代码变更未绑定设计追踪",
        user_message_zh: "变更文件缺少有效的切片、详细设计或验收绑定，不能作为已按设计实现的结果。",
        recovery_hint_zh: "补充追踪绑定或修正任务范围后重新执行 sf_verify。",
        owner_component: "server/tools", evidence_refs: ["问题七十三"] },
    { code: TOOL_DIAGNOSTIC_CODES.traceabilityDeliveryBlocked, area: "CONTRACT", severity: "blocking", status: "active",
        title_zh: "交付前追踪绑定未闭合",
        user_message_zh: "任务仍存在未闭合的设计实现追踪绑定，不能交付。",
        recovery_hint_zh: "完成追踪矩阵和任务绑定复验后重新交付。",
        owner_component: "server/tools", evidence_refs: ["问题七十三"] },
];
let runtimeDiagnostics = null;
function getRegistry() {
    if (!runtimeDiagnostics) {
        runtimeDiagnostics = new Map();
        for (const entry of BUILTIN_DIAGNOSTICS) {
            runtimeDiagnostics.set(entry.code, { ...entry });
        }
    }
    return runtimeDiagnostics;
}
/** 按 code 获取诊断码 */
export function getDiagnosticByCode(code) {
    return getRegistry().get(code);
}
/** 列出所有诊断码 */
export function listAllDiagnostics() {
    return [...getRegistry().values()];
}
/** 按领域列出诊断码 */
export function listDiagnosticsByArea(area) {
    return [...getRegistry().values()].filter((d) => d.area === area);
}
/** 按 severity 列出诊断码 */
export function listDiagnosticsBySeverity(severity) {
    return [...getRegistry().values()].filter((d) => d.severity === severity);
}
/** 注册新诊断码（运行时） */
export function registerDiagnostic(entry) {
    const registry = getRegistry();
    if (registry.has(entry.code)) {
        return { success: false, error: `诊断码 ${entry.code} 已存在` };
    }
    if (!/^SF-[A-Z]+-\d{4}$/.test(entry.code)) {
        return { success: false, error: `诊断码格式错误: ${entry.code}，必须为 SF-{AREA}-{NNNN}` };
    }
    if (!entry.title_zh || !entry.user_message_zh || !entry.recovery_hint_zh) {
        return { success: false, error: "诊断码必须有 title_zh、user_message_zh、recovery_hint_zh" };
    }
    registry.set(entry.code, { ...entry });
    return { success: true };
}
/** 创建诊断事件 */
export function createDiagnosticEvent(code, context, contractId, taskId) {
    const entry = getRegistry().get(code);
    if (!entry)
        return null;
    if (entry.status === "deprecated" || entry.status === "removed")
        return null;
    return {
        code,
        occurred_at: new Date().toISOString(),
        context: context ?? {},
        user_visible_message: entry.user_message_zh,
        contract_id: contractId,
        task_id: taskId,
    };
}
/** 验证所有 blocking/critical 事件必须有诊断码 */
export function validateDiagnosticCoverage(eventSeverities) {
    const errors = [];
    for (const event of eventSeverities) {
        if ((event.severity === "blocking" || event.severity === "critical") && !event.has_code) {
            errors.push({
                severity: event.severity,
                error: `${event.severity} 事件缺少诊断码`,
            });
        }
    }
    return errors;
}
/** 重置注册表（测试用） */
export function resetDiagnosticRegistry() {
    runtimeDiagnostics = null;
}
/** 获取诊断码统计 */
export function getDiagnosticStats() {
    const entries = [...getRegistry().values()];
    const by_area = {};
    const by_severity = {};
    for (const e of entries) {
        by_area[e.area] = (by_area[e.area] ?? 0) + 1;
        by_severity[e.severity] = (by_severity[e.severity] ?? 0) + 1;
    }
    return { total: entries.length, by_area, by_severity };
}
//# sourceMappingURL=diagnostic_registry.js.map