{
  "_meta": {
    "version": "2.1.0",
    "description": "SOP编排系统集中化配置 — 引擎级运营参数单一真相源",
    "scope": "仅包含引擎级运营参数（超时/重试/文件验证/健康度/目录结构/上下文管理/会话恢复/降级验证/模板Pre-Write门禁/上下文健康检查/LOOP_BACK快照/JSON缓存Phase-B瘦身桥接/自适应Stall检测/Token优化/防幻觉指令体系）",
    "nonScope": "业务规则（字段覆盖率/步骤卡格式/章节结构/活动类型/成本结构对齐/枚举值对齐等）定义在各SKILL.md中，不在此文件",
    "usage": "由 MG-01 SOP编排专家在 Phase 0 启动时加载",
    "changelog": {
      "2.1.0": "V14.0 四维优化: ① stallDetection(自适应Stall检测,per-step stallTimeoutMs覆盖全局30min); ② tokenOptimization(指令文件动态加载,instructionFile替代内联instruction,Token节省60-80%); ③ antiHallucination(强制文件引用+结构化校验点+上下文隔离策略)",
      "2.0.0": "Phase-B JSON缓存全量推广: ⑤ 18个步骤迁移hybrid模式(Phase1全部生成/验证+Phase2/3评估代理); ⑥ 跨SubSkill桥接瘦身(仅内联变量,step-cache按需读取); ⑦ ctx-checkpoint瘦身(slim模式,inlineCtx+stepCache元数据)",
      "1.4.0": "V1.4.0新增：verificationStrategy.levels.L1_5_preWrite（Gate-COST成本结构阻断门禁+Gate-ENUM枚举值阻断门禁），基于LTC-SOP完整版排查结果新增模板写入前强制校验层",
      "1.3.0": "P1优化：断点Schema扩展(+currentPhase/loopRound/contextSnapshot)；压缩阈值前移(50K→40K,30次→20次)+自适应压缩；降级验证策略(degradedVerification)；超时保护协议",
      "1.2.0": "P0超时修复：q1Step02cFramework 900000→1800000(30min)对齐avatar.json；拆分02c为两个子步骤(framework-types+conditional)；精简framework规则至最小集；分级验证策略；上下文优化",
      "1.1.0": "新增 contextManagement（上下文保护+溢出恢复+预生成缓存）+ sessionRecovery（断点续传）；调优 q1Step02a超时(35min)+chunk(300行)；预生成管线V2.0双批次架构",
      "1.0.0": "初始版本：超时/重试/文件验证/健康度/目录结构/修复路径/质量门禁/蓝图规则"
    },
    "authoritativeSources": {
      "sop-generation-rules": "字段覆盖率/步骤卡格式/DC规则/Phase A~E/C-01~C-08 等业务规则",
      "blueprint-planner": "蓝图规划算法/G1-G5门禁/B1-B4锁定规则 等业务规则",
      "avatar.json": "各步骤timeoutMs/postStepFileVerification/目录结构/上下文保护指令 等引擎参数"
    }
  },
  "timeoutConfig": {
    "_doc": "超时配置 — 动态公式系数 + 固定超时值（权威来源：avatar.json各步骤timeoutMs）",
    "dynamicFormulas": {
      "q2Verification": {
        "formula": "base + (N × sopWeight + M × tmpWeight + evalRound × roundWeight)",
        "base": 15,
        "sopWeight": 1,
        "tmpWeight": 0.3,
        "roundWeight": 5,
        "unit": "minutes"
      },
      "phase3RequirementAnalysis": {
        "formula": "base + (N × sopWeight + M × tmpWeight)",
        "base": 25,
        "sopWeight": 1.5,
        "tmpWeight": 0.4,
        "unit": "minutes",
        "platformHardLimit": 80
      }
    },
    "fixedTimeouts_ms": {
      "_doc": "各步骤固定超时值（毫秒），与avatar.json中timeoutMs字段一一对应",
      "phase0": {
        "selfCheck": 300000,
        "conflictDetection": 300000,
        "fourTierCollect": 300000,
        "threeTierConfirmSubStep": 180000,
        "c1c6Gate": 300000,
        "createDirectories": 180000,
        "generateStartupSummary": 300000
      },
      "phase1": {
        "q1Step01Instruction": 900000,
        "q1Step02aSop000": 2100000,
        "q1Step02aSop000_note": "V1.1.0 调优：1800000→2100000（35min），含预生成管线V2.0双批次+SOP-000分步写入+LLM波动余量",
        "q1Step02bOperational": 4500000,
        "q1Step02bOperational_note": "V13.1.0 调优：2700000→4500000（75min），V2.0蓝图25+操作性SOP逐个生成+分步写入（旧版9个→45min，新版25个→75min）",
        "q1Step02c1FrameworkTypes": 1500000,
        "q1Step02c1FrameworkTypes_note": "V13.1.0 调优：900000→1500000（25min），V2.0蓝图3个框架型SOP×7min+校验2min=23min→25min",
        "q1Step02c2Conditional": 2100000,
        "q1Step02c2Conditional_note": "V13.1.0 调优：900000→2100000（35min），V2.0蓝图3个条件分支型SOP×10min+校验2min+写入3min=35min",
        "q1Step02cFramework_LEGACY": 1800000,
        "q1Step02cFramework_LEGACY_note": "V1.2.0废弃：原02c合并步骤(30min)已拆分为02c-1+02c-2两个子步骤",
        "q1Step02dTemplates": 2400000,
        "q1Step02dTemplates_note": "V13.1.0 调优：2100000→2400000（40min），V2.0蓝图32模板×1min/个+登记表+9项自检=38min→40min",
        "q1Step03aStructureCheck": 1800000,
        "q1Step03aStructureCheck_note": "V13.1.0 调优：480000→1800000（30min），V2.0蓝图66文件×11项检查I/O（旧版15文件→8min超时，新版66文件→30min）",
        "q1Step03bContentScoring": 2400000,
        "q1Step03bContentScoring_note": "V13.1.0 调优：600000→2400000（40min），V2.0蓝图33SOP精读§1/§7/§9/§10+32模板抽检（旧版15文件→10min，新版66文件→40min）",
        "q1Step03cGateDecision": 900000,
        "q1Step03cGateDecision_note": "V13.1.0 调优：180000→900000（15min），V2.0蓝图评分报告规模增大",
        "q1Step04Failure": 1200000,
        "q1Step04Failure_note": "V13.1.0 调优：900000→1200000（20min），重试步骤需生成完整SOP文件",
        "q1Step05VerifyOutput": 2700000,
        "q1Step05VerifyOutput_note": "V13.1.0 调优：1200000→2700000（45min），V2.0蓝图66文件×15项校验+差异化修复+承诺清单逐项核对",
        "q2Step01Instruction": 600000,
        "q2Step02Execution": 4200000,
        "q2Step02Execution_note": "V13.1.0 调优：2700000→4200000（70min），V2.0蓝图66文件×12维度×136检查点逐项验证",
        "q2Step03Judgment": 900000,
        "q2Step03Judgment_note": "V13.1.0 调优：600000→900000（15min），V2.0蓝图综合判定规模增大",
        "q3Step01Analysis": 1200000,
        "q3Step01Analysis_note": "V13.1.0 调优：900000→1200000（20min），V2.0蓝图六维度分析规模增大",
        "q3Step06ReturnFix": 1200000,
        "q3Step06ReturnFix_note": "V13.1.0 调优：600000→1200000（20min），V2.0蓝图回退修复规模增大"
      },
      "phase2": {
        "evaluationAgent": 3600000
      },
      "phase3": {
        "parseInput": 180000,
        "dispatchViaRoster": 180000,
        "selfCheckGate": 300000,
        "buildInstruction": 300000,
        "evaluationAgent17steps": 4800000,
        "requirementStructureDecision": 300000
      }
    },
    "timeSliceAllocation": {
      "_doc": "时间片分配权重（权威来源：avatar.json q1-step-02a~02d instruction）",
      "weights": {
        "sop000": 3,
        "operationalSop": 1.5,
        "approvalSop": 1,
        "template": 0.8
      },
      "shares": {
        "sop000": 0.25,
        "sop000MaxMinutes": 8,
        "operational": 0.4,
        "regulatory": 0.1,
        "template": 0.25
      }
    },
    "contextCompression": {
      "_doc": "上下文压缩阈值",
      "g1MaxChars": 2000,
      "g2MaxChars": 1000
    },
    "incrementalRepairBudgetRatio": 0.3,
    "complexityTimeRatio": {
      "light": 0.1,
      "medium": 0.25,
      "heavy": 0.65
    }
  },
  "fileVerification": {
    "_doc": "postStepFileVerification 引擎级文件验证参数（权威来源：avatar.json各步骤postStepFileVerification）",
    "q1Phase": {
      "minFileCount": {
        "default": 10,
        "note": "从蓝图清单动态推导时作为回退默认值"
      },
      "minFileSizeBytes": 100,
      "maxRetries": 3,
      "loopBackMaxRetries": 2,
      "extractionFallbackMinCount": 25,
      "criticalFilePatterns": [
        "*SOP-000*"
      ],
      "requiredContentPatterns": [
        "^#\\s+",
        "^##\\s+",
        "CV-1",
        "CV-2",
        "CV-3"
      ]
    },
    "phase2Evaluation": {
      "minFileCount": 1,
      "minFileSizeBytes": 5000,
      "maxRetries": 1,
      "loopBackMaxRetries": 2
    },
    "phase3Evaluation": {
      "minFileCount": 1,
      "minFileSizeBytes": 10000,
      "maxRetries": 1,
      "loopBackMaxRetries": 2
    },
    "decisionOutput": {
      "minFileCount": 1,
      "minFileSizeBytes": 500,
      "maxRetries": 1,
      "loopBackMaxRetries": 2
    }
  },
  "retryPolicy": {
    "_doc": "重试与间隔策略（权威来源：avatar.json + sop-generation-rules）",
    "selfCheck": {
      "maxRetries": 3,
      "escalationOnExhaustion": "升级提示用户确认所有必填信息"
    },
    "failureRetry": {
      "attempts": [
        {
          "attempt": 1,
          "waitSeconds": 30
        },
        {
          "attempt": 2,
          "waitSeconds": 60
        },
        {
          "attempt": 3,
          "action": "降级处理"
        }
      ]
    },
    "innerLoop": {
      "maxRounds": 5
    },
    "dc6Retry": {
      "maxRetries": 3,
      "thirdRetryAction": "强制使用 expectMin 作为下限，自动补充缺失SOP框架结构"
    },
    "commitmentItemRetry": {
      "maxRetries": 2
    },
    "blueprintValidation": {
      "maxRetries": 3
    },
    "evaluationLoop": {
      "autoContinue": 3,
      "checkTrend": [
        4,
        6
      ],
      "mustAskUser": 7
    },
    "trendHistoryFifoLimit": 5
  },
  "healthMetrics": {
    "_doc": "生成健康度监控指标（权威来源：avatar.json + sop-generation-rules）",
    "generationRateRedLine": 0.3,
    "qualityScoreRedLine": 0.6,
    "timeoutWarningMultiplier": 1.5,
    "consecutiveTimeoutSlimMode": 2,
    "consecutiveTimeoutPauseReport": 3,
    "estimatedTimeWarningRatio": 1.2
  },
  "contextManagement": {
    "_doc": "上下文窗口管理策略（V1.1.0 新增 — 防止 Phase 1 大体量生成导致上下文溢出）",
    "preQ1CompactThresholdTokens": 40000,
    "preQ1CompactAction": "进入 Q1 Step 2（SOP文档包生成）前，若累计工具调用 ≥ 20 次或上下文估算 > 40K tokens，强制执行上下文压缩：将历史工具调用结果摘要化（仅保留文件路径+行数+关键结论），释放上下文空间",
    "adaptiveCompression": {
      "enabled": true,
      "checkInterval": 5,
      "note": "每5次工具调用检查一次上下文大小，超过40K tokens即触发压缩"
    },
    "perFileWriteMaxLines": 300,
    "perFileWriteStrategy": "单次 write_file 调用写入不超过 300 行；超过 300 行的文档（如 SOP-000 总纲 1154 行）必须拆分为多次追加写入（write_file + append 模式），每次写入后输出确认日志",
    "checkpointIntervalToolCalls": 3,
    "checkpointStrategy": "每完成 3 次工具调用（或每完成 1 个 SOP 文件写入），立即更新 {sopOutputPath}/知识库/循环轮次/断点状态.json，记录：当前步骤ID、已完成文件列表、下一步骤ID、时间戳、currentPhase、loopRound、contextSnapshot（含processName/sopOutputPath/knowledgeBasePath/qualityScore/fieldCoverage）。同时写入引擎层 ctx-checkpoint（.twork/sessions/）供跨SubSkill桥接使用",
    "sessionRecoveryHint": "新会话启动 Phase 1 时，优先读取 断点状态.json 恢复进度，跳过已完成的文件生成步骤",
    "largeDocSplitRules": {
      "_doc": "大体量文档拆分规则（V1.1.0 调优：sop000从250→300，减少1次LLM往返）",
      "sop000MaxLinesPerChunk": 300,
      "operationalSopMaxLinesPerChunk": 300,
      "templateMaxLinesPerChunk": 250,
      "appendModeRequired": true,
      "interChunkLog": "每次追加写入后输出：[chunk N/M] {文件名} 已写入 {累计行数} 行"
    },
    "contextOverflowRecovery": {
      "_doc": "上下文溢出（prompt is too long）应急恢复协议（V1.1.0 新增）",
      "detectionSignals": [
        "LLM 返回 'prompt is too long' 错误",
        "引擎 auto-compact 连续失败 2 次",
        "累计工具调用 ≥ 60 次且未压缩"
      ],
      "immediateActions": [
        "1. 立即将当前进度写入 断点状态.json（currentStep/completedFiles/partialFile/timestamp）",
        "2. 输出用户提示：⚠️ 上下文窗口已满，已保存断点，请新建会话继续执行",
        "3. 停止所有后续文件写入操作（防止引擎超时清理级联）"
      ],
      "prohibitedActions": [
        "禁止在溢出后继续尝试 write_file（会触发引擎 stall_timeout → 全量清理）",
        "禁止忽略溢出信号继续生成（上下文截断会导致产物不完整）"
      ],
      "recoveryFlow": "新会话 → q1-step-01 Step -1 断点恢复检查 → 验证 completedFiles 磁盘存在性 → 从 nextStep 继续",
      "engineLayerBackup": "即使 Agent 未能主动保存断点，engine.ts 在 stall_timeout/user_abort 时也会自动写入 .twork/sessions/{id}-interrupted.json"
    },
    "preGenerationCache": {
      "_doc": "预生成管线V2.0缓存配置（Round 2+跳过机制）",
      "cacheFile": "{knowledgeBasePath}/循环轮次/预检缓存.json",
      "skipCondition": "currentRound >= 2 AND cacheFile存在 AND blueprintLocked=true",
      "invalidationTriggers": [
        "蓝图重新规划",
        "用户手动删除缓存",
        "承诺清单与蓝图不一致"
      ],
      "estimatedTimeSaved": "10-12 min（跳过Batch-A + Batch-B全部LLM调用）"
    },
    "performanceTuning": {
      "_doc": "V2.1 性能调优参数",
      "batchWriteSize": 5,
      "batchWriteNote": "模板生成每批5个统一写入（原3-5个），减少工具调用次数",
      "skipRedundantReads": true,
      "skipRedundantReadsNote": "已在前序步骤读取的文件，后续步骤直接使用上下文缓存",
      "contextReusePolicy": "structured-summary",
      "contextReuseNote": "步骤间传递结构化摘要（文件清单+关键决策），非全文",
      "crossStepSkillCache": true,
      "crossStepSkillCacheNote": "V1.2.0：相邻步骤共享同一linkedSkill时（如02c-1和02c-2都用sop-generation-rules-framework），第二个步骤复用引擎已加载的skill内容，避免重复注入",
      "splitStepContextOptimization": {
        "description": "V1.2.0 拆分子步骤上下文优化策略",
        "excludePreviousSubStepOutput": true,
        "excludePreviousSubStepOutputNote": "02c-2排除02c-1的完整输出（framework_types_sops），仅保留文件路径+行数摘要",
        "summaryOnlyKeys": ["framework_types_sops", "conditional_sops", "operational_sops"],
        "summaryFormat": "文件清单（编号+名称+行数+路径）+ 关键决策摘要（≤200字）",
        "estimatedTokenSaving": "每个排除的outputKey节省约2000-4000 tokens"
      }
    }
  },
  "directoryStructure": {
    "_doc": "标准化目录结构名（权威来源：avatar.json howItWorks）",
    "phase0Output": "启动与信息收集",
    "phase1Output": "内循环",
    "phase1SubDirs": [
      "Q1",
      "Q2",
      "Q3"
    ],
    "templateSubDir": "模板文件",
    "phase2Output": "SOP产品化分析评估",
    "phase3Output": "产品化需求分析评估",
    "knowledgeBase": "知识库",
    "cycleWorkDir": "循环轮次"
  },
  "sessionRecovery": {
    "_doc": "会话中断恢复协议（V1.1.0 新增 — 解决上下文溢出/超时中断后产物丢失问题）",
    "checkpointFile": {
      "path": "{sopOutputPath}/知识库/循环轮次/断点状态.json",
      "schema": {
        "currentStep": "string — 中断时正在执行的步骤ID",
        "currentPhase": "string — 当前所在Phase（phase0|phase1|phase2|phase3）",
        "loopRound": "number — 当前内循环轮次",
        "completedFiles": "string[] — 已成功写入磁盘的文件名列表",
        "nextStep": "string — 恢复时应执行的下一步骤ID",
        "timestamp": "string — ISO8601 时间戳",
        "partialFile": "string|null — 写入一半的文件（需重新生成）",
        "contextSnapshot": {
          "processName": "string — 流程名称",
          "sopOutputPath": "string — SOP输出路径",
          "knowledgeBasePath": "string — 知识库路径",
          "qualityScore": "number|null — 最近一次质量评分",
          "fieldCoverage": "string|undefined — 字段覆盖率（F-02 Schema扩展）"
        },
        "ctxVersion": "number — 检查点版本号（P-01 变量版本化，每次写入递增）"
      },
      "writeFrequency": "每完成1个文件写入后立即更新",
      "atomicWrite": true
    },
    "engineCheckpoint": {
      "_doc": "引擎层断点（engine.ts 中断时自动保存）",
      "path": "{workingDirectory}/.twork/sessions/{conversationId}-interrupted.json",
      "schema": {
        "conversationId": "string",
        "workingDirectory": "string",
        "interruptedAt": "string — ISO8601",
        "reason": "string — stall_timeout | user_abort | context_overflow",
        "status": "interrupted"
      },
      "triggerConditions": [
        "stall_timeout",
        "user_abort",
        "context_overflow"
      ],
      "globalCheckpoint": {
        "_doc": "M-01 全局检查点（stall_timeout 清理前复制到全局目录，确保 clearSessionWorkingDirectory 后仍可恢复）",
        "path": "{workingDirectory}/.twork/global-checkpoints/latest-ctx-checkpoint.json",
        "triggerConditions": ["stall_timeout"],
        "source": "从 {workingDirectory}/.twork/sessions/{conversationId}-ctx-checkpoint.json 复制"
      }
    },
    "recoveryProtocol": {
      "step1": "新会话启动 Phase 1 时，q1-step-01-instruction Step -1 自动检查断点状态.json",
      "step2": "验证 completedFiles 中的文件是否实际存在于磁盘（list_directory 检查）",
      "step3": "存在且完整 → 跳过已完成文件，从 nextStep 继续",
      "step4": "文件不存在 → 从 completedFiles 移除，回退到对应步骤重新生成",
      "step5": "断点文件不存在 → 正常执行（首次运行或全新轮次）"
    },
    "artifactPanelExemption": {
      "_doc": "产物面板豁免规则（OutputDirProvider.ts V1.1.0）",
      "exemptedDirMarkers": [
        "启动与信息收集",
        "内循环",
        "SOP产品化分析评估",
        "产品化需求分析评估",
        "知识库",
        "循环轮次",
        "模板文件"
      ],
      "behavior": "匹配标志目录的文件豁免会话时间戳过滤，确保跨阶段/跨会话可见"
    }
  },
  "repairPaths": {
    "_doc": "修复路径定义（权威来源：sop-generation-rules Phase A~E）",
    "pathA": {
      "name": "定点修正",
      "trigger": "P0高严重度",
      "timeoutPerItem": "0.5h"
    },
    "pathB": {
      "name": "增量补充",
      "trigger": "P1/P2中严重度",
      "timeoutPerItem": "1h"
    },
    "pathC": {
      "name": "结构性重构",
      "trigger": "P3低严重度/建议",
      "timeoutPerItem": "2h"
    }
  },
  "qualityThresholdsReference": {
    "_doc": "质量门禁阈值索引 — 权威定义在各SKILL.md中，此处仅作跨文件一致性参考",
    "fieldCoverage": {
      "_authoritativeSource": "sop-generation-rules SKILL.md §sop-field-coverage 四级阈值判定",
      "levels": "<40%阻断 | 40-60%阻断提问 | 60-80%警告 | ≥80%正常",
      "pendingFieldWeight": 0.5
    },
    "dynamicContentGates": {
      "_authoritativeSource": "avatar.json q1-step-03b instruction 动态门禁",
      "gates": "≤5个SOP: ≥80分 | 6-12个SOP: ≥85分 | >12个SOP: ≥88分"
    },
    "c08QualityGate": {
      "_authoritativeSource": "sop-generation-rules SKILL.md §C-08 质量自评门禁",
      "totalScore": "正常≥85 | 警告70-84 | 重生成<70",
      "completenessDimension": "26/30",
      "consistencyDimension": "20/25"
    }
  },
  "blueprintRulesReference": {
    "_doc": "蓝图规划参数索引 — 权威定义在blueprint-planner SKILL.md中",
    "_authoritativeSource": "blueprint-planner SKILL.md Step 0/Step 3",
    "g1ToleranceFactor": 0.9,
    "templateMultipliers": {
      "standardRefValid_T6": 1.1,
      "standardRefValid_G4_P0": 1.15,
      "standardRefInvalid_T7": 1.2,
      "standardRefInvalid_G4_P1": 1.2
    },
    "subProcessIndependenceThreshold": 2,
    "dc6Threshold": 0.9,
    "dc6DegradedThreshold": 0.7
  },
  "verificationStrategy": {
    "_doc": "V1.2.0 分级验证策略 — 将验证负担从生成步骤内移至步骤后/阶段末，减少每步骤执行时间",
    "levels": {
      "L1_inline": {
        "description": "生成时内嵌轻量自检，每个SOP写入后立即执行",
        "scope": "章节存在性 + 编号一致性 + 角色/术语字典查询",
        "estimatedOverhead": "0-1 min/SOP",
        "appliesTo": ["q1-step-02a", "q1-step-02b", "q1-step-02c-1", "q1-step-02c-2"]
      },
      "L1_5_preWrite": {
        "description": "V1.3.0新增：模板写入前阻断门禁，每个TMP文件写入前执行",
        "scope": "Gate-COST(成本结构对齐) + Gate-ENUM(枚举值对齐) + 字段类型标准校验",
        "estimatedOverhead": "0.5-1 min/TMP",
        "appliesTo": ["q1-step-02d（每个模板写入前）"],
        "blockingGates": {
          "Gate-COST": {
            "trigger": "模板含成本/报价/核算类字段",
            "checkRule": "A~L字段名称+公式 vs anchor.costStructureTree 逐项比对",
            "failureAction": "阻断写入，修正后重新生成",
            "referenceSkill": "sop-skeleton-templates TMP-COST-01"
          },
          "Gate-ENUM": {
            "trigger": "每个模板写入前",
            "checkRule": "枚举字段取值 vs anchor.businessLines + SOP-000 §12约束",
            "failureAction": "阻断写入，修正枚举值后重新生成",
            "referenceSkill": "sop-skeleton-templates TMP-ENUM-01"
          }
        }
      },
      "L2_batch": {
        "description": "每批次SOP完成后批量校验（在步骤末尾执行一次，非每文件）",
        "scope": "RACI交叉校验 + 跨SOP引用格式 + 编号连续性 + 术语一致性",
        "estimatedOverhead": "2-3 min/batch",
        "appliesTo": ["q1-step-02b（全部操作性SOP完成后）", "q1-step-02c-2（全部条件分支型完成后）"]
      },
      "L3_full": {
        "description": "Q1全量校验，由 q1-step-05-verify-output 统一执行",
        "scope": "B1-B5场景覆盖 + 12项目录校验 + 承诺清单逐项核对 + 接口/规则完整性 + 跨文件一致性 + FAC验收",
        "estimatedOverhead": "15-20 min（已有20min超时）",
        "appliesTo": ["q1-step-05-verify-output"]
      }
    },
    "prohibitedInGenerationSteps": [
      "禁止在02a/02b/02c生成步骤内执行跨SOP交叉校验（属L2/L3范围）",
      "禁止在生成步骤内执行B1-B5场景覆盖检查（属L3范围）",
      "禁止在生成步骤内执行RACI矩阵全量交叉校验（属L2范围）"
    ],
    "degradedVerification": {
      "_doc": "V1.3.0 降级验证策略 — 当全量验证超时/失败时，缩减验证维度但收紧通过阈值",
      "dimensions": ["A", "B", "C", "D", "E", "G"],
      "excludedDimensions": ["F(跨SOP一致性)", "H(字段覆盖率)", "I(业务场景)", "J(模板合规)", "K(收敛趋势)", "L(承诺清单)"],
      "adjustedThresholds": {
        "P6_pass": "无阻断 + 高=0 + 中≤2（降级后维度减少，阈值收紧）",
        "P7_conditional": "高≤1 + 中≤3",
        "note": "降级验证通过后标注'降级通过-待全量复验'，Phase 2 前必须全量复验"
      },
      "triggerConditions": [
        "Q2全量验证超时（超过动态公式计算时间）",
        "Q2执行失败（连续2次重试后仍失败）",
        "用户主动选择降级验证"
      ],
      "mandatoryFullRevalidation": true,
      "fullRevalidationTiming": "Phase 2 评估前必须完成全量复验，否则阻断流转"
    }
  },
  "contextHealthCheck": {
    "_doc": "P-03 上下文健康检查配置 — 定期校验关键上下文变量完整性，防止静默丢失",
    "checkIntervalSteps": 5,
    "requiredVariables": {
      "phase0": ["processName", "sopOutputPath", "knowledgeBasePath"],
      "phase1": ["processName", "sopOutputPath", "knowledgeBasePath", "positionManualPath", "serviceCatalogPath"],
      "phase2": ["processName", "sopOutputPath", "knowledgeBasePath"],
      "phase3": ["processName", "sopOutputPath", "knowledgeBasePath"]
    },
    "recoverySource": "{knowledgeBasePath}/参数.json",
    "onMissing": "warn_and_recover",
    "logPrefix": "[P-03-ContextHealth]"
  },
  "loopBackSnapshot": {
    "_doc": "P-02 LOOP_BACK上下文快照 — 回退前保存完整 ctx 快照，便于调试和回滚",
    "enabled": true,
    "snapshotDir": "{workingDirectory}/.twork/sessions",
    "snapshotFilePattern": "{conversationId}-loopback-snapshot-{round}.json",
    "maxSnapshots": 5,
    "includeFields": ["ctx", "currentStep", "targetStep", "loopRound", "timestamp"]
  },
  "stallDetection": {
    "_doc": "V14.0 自适应 Stall 检测配置 — per-step stallTimeoutMs 覆盖全局默认值，防止简单步骤误等30min",
    "globalDefaults": {
      "seqStallTimeoutMs": 1800000,
      "seqStallTimeoutMs_note": "顺序步骤全局默认 stall 超时（30min），当步骤未配置 stallTimeoutMs 时使用",
      "parallelStallTimeoutMs": 1800000,
      "parallelStallTimeoutMs_note": "并行组全局默认 stall 超时（30min）",
      "logPrefix": "[AdaptiveStall]"
    },
    "perStepPresets": {
      "_doc": "按步骤类型推荐的 stallTimeoutMs 预设值（avatar.json 各步骤可直接引用）",
      "simple": {
        "description": "简单步骤：路由/判定/决策/门禁",
        "stallTimeoutMs": 300000,
        "appliesTo": ["q1-step-01", "q1-step-03c", "q2-step-03", "q3-step-01", "phase0-c1c6-gate"]
      },
      "medium": {
        "description": "中等步骤：单文件生成/单SOP生成",
        "stallTimeoutMs": 600000,
        "appliesTo": ["q1-step-02a（单SOP-000）", "q1-step-04", "phase0-create-directories"]
      },
      "complex": {
        "description": "复杂步骤：批量SOP生成/模板生成/全量验证",
        "stallTimeoutMs": 1800000,
        "appliesTo": ["q1-step-02b", "q1-step-02c-1", "q1-step-02c-2", "q1-step-02d", "q1-step-03a", "q1-step-03b", "q1-step-05", "q2-step-02"]
      }
    },
    "detectionBehavior": {
      "resetOnAnyActivity": true,
      "resetOnAnyActivity_note": "任何 textDelta/toolCall/toolResult 均重置 stall 计时器",
      "abortAction": "触发 stepCtrl.abort()，由 continueOnError 决定后续行为",
      "logOnTrigger": true
    }
  },
  "tokenOptimization": {
    "_doc": "V14.0 Token 消耗优化配置 — 指令文件动态加载 + 上下文压缩策略",
    "dynamicInstructionLoading": {
      "enabled": true,
      "priority": "instructionFile > instruction（文件存在时优先文件，不存在时 fallback 到内联）",
      "templateVariableSupport": true,
      "templateVariableSupport_note": "instructionFile 内容支持 {{variable}} 模板变量替换（通过 renderTemplate 实现）",
      "logPrefix": "[DynamicInstruction]",
      "fallbackBehavior": "文件不存在或读取失败时，自动 fallback 到 step.instruction 内联字段",
      "estimatedTokenSaving": {
        "before": "~80K tokens/step（44个步骤 instruction 全量注入）",
        "after": "~5-15K tokens/step（仅加载当前步骤 instruction）",
        "savingPercent": "60-80%"
      }
    },
    "contextIsolation": {
      "_doc": "跨步骤上下文隔离策略 — 前序大体积输出通过 step-cache 按需读取，不全量注入",
      "excludeLargeOutputs": true,
      "excludeLargeOutputs_note": "超过 contextBudget 的前序步骤输出自动转为 step-cache 引用（文件路径+行数摘要）",
      "summaryOnlyKeys": [
        "operational_sops",
        "conditional_sops",
        "framework_types_sops",
        "all_templates",
        "verification_report"
      ],
      "summaryFormat": "文件清单（编号+名称+行数+路径）+ 关键决策摘要（≤200字）",
      "perKeyMaxChars": 2000,
      "totalContextBudgetChars": 40000
    },
    "instructionFileRecommendations": {
      "_doc": "avatar.json 各步骤 instructionFile 配置推荐（迁移指南）",
      "highPriority": [
        { "stepId": "q1-step-02b", "recommendFile": "instructions/q1-step-02b-instruction.md", "reason": "最长 instruction（~15K chars），批量生成25+操作性SOP" },
        { "stepId": "q1-step-02d", "recommendFile": "instructions/q1-step-02d-instruction.md", "reason": "模板生成 instruction（~12K chars）" },
        { "stepId": "q1-step-05", "recommendFile": "instructions/q1-step-05-instruction.md", "reason": "产出校验 instruction（~10K chars）" },
        { "stepId": "q2-step-02", "recommendFile": "instructions/q2-step-02-instruction.md", "reason": "Q2验证执行 instruction（~12K chars）" }
      ],
      "mediumPriority": [
        { "stepId": "q1-step-02a", "recommendFile": "instructions/q1-step-02a-instruction.md", "reason": "SOP-000 总纲生成（~8K chars）" },
        { "stepId": "q1-step-03b", "recommendFile": "instructions/q1-step-03b-instruction.md", "reason": "内容评分（~6K chars）" }
      ]
    }
  },
  "antiHallucination": {
    "_doc": "V14.0 防幻觉指令体系 — 强制文件引用 + 结构化校验点 + 上下文隔离",
    "forcedFileReference": {
      "_doc": "LLM 引用文件内容前必须先通过工具读取，禁止凭记忆引用",
      "enabled": true,
      "rules": [
        "禁止引用未通过 read_file/list_directory/glob 工具确认存在的文件路径",
        "禁止引用超过 5000 字符前读取的文件内容（上下文窗口外内容视为不可靠）",
        "引用文件行号时必须标注来源文件路径，格式：[来源: {filePath}:L{lineNumber}]",
        "跨 SOP 引用术语/角色时，必须先 grep 确认该术语在目标 SOP 中存在"
      ],
      "violationDetection": {
        "logPrefix": "[AntiHallucination]",
        "signals": [
          "LLM 引用的文件路径在 list_directory 结果中不存在",
          "LLM 引用的行号超出文件实际行数",
          "LLM 声称读取文件但工具调用记录中无对应 read_file 调用"
        ],
        "onViolation": "在输出中标记 ⚠️ [AntiHallucination] 疑似虚构引用，触发 postStepFileVerification 重新校验"
      }
    },
    "structuredValidationCheckpoints": {
      "_doc": "每步输出前强制自检 — 文件存在性/编号连续性/角色一致性",
      "checkpoints": [
        {
          "id": "SVC-01",
          "name": "文件存在性自检",
          "trigger": "每步完成前（output 生成前）",
          "check": "声明的所有已生成文件必须通过 list_directory 确认存在",
          "onFail": "LOOP_BACK 到文件生成步骤"
        },
        {
          "id": "SVC-02",
          "name": "编号连续性自检",
          "trigger": "SOP/模板批量生成步骤完成前",
          "check": "SOP-000 到 SOP-NNN 编号无跳跃，TMP-001 到 TMP-MMM 编号无跳跃",
          "onFail": "补充缺失编号的文件"
        },
        {
          "id": "SVC-03",
          "name": "角色一致性自检",
          "trigger": "每个 SOP 生成完成后",
          "check": "SOP 中出现的角色必须存在于 SOP-000 §7 角色清单中",
          "onFail": "修正角色名称或补充角色定义到 SOP-000"
        },
        {
          "id": "SVC-04",
          "name": "跨文件引用自检",
          "trigger": "Q2 验证步骤中",
          "check": "所有 [REF: SOP-XXX §Y] 格式的引用必须指向真实存在的章节",
          "onFail": "修正引用目标或补充缺失章节"
        }
      ]
    },
    "contextIsolationStrategy": {
      "_doc": "上下文隔离 — 前序步骤大体积输出通过 step-cache 按需读取，防止注意力分散导致幻觉",
      "maxInlineChars": 4000,
      "maxInlineChars_note": "单个 outputKey 内联到 prompt 的最大字符数，超过此值自动转为 step-cache 引用",
      "stepCacheRefFormat": "[step-cache: {outputKey}] → 文件已写入 {filePath}（{lineCount} 行），需要时通过 read_file 读取",
      "excludeFromContextAggregation": [
        "operational_sops",
        "conditional_sops",
        "framework_types_sops",
        "all_templates",
        "verification_report_full"
      ]
    }
  }
}